content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Visualize Chi-squared Distribution #' #' Generates a plot of the Chi-squared distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param df degrees of freedom of Chi-squared distribution. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dchisq()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.chisq(stat = 1, df = 3, section = "lower") #' # Evaluates bounded region. #' visualize.chisq(stat = c(1,2), df = 6, section = "bounded") #' # Evaluates upper tail. #' visualize.chisq(stat = 1, df = 3, section = "upper") #' #' visualize.chisq <- function(stat = 1, df = 3, section = "lower") { visualize.it('chisq', stat = stat, list(df = df), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.chisq.R
#' Graphing function for Continuous Distributions. #' #' Handles how continuous distributions are graphed. Users should not use this #' function. Instead, users should use [`visualize.it()`]. #' #' @param dist contains a supported continuos distribution shortname. #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as #' `stat = c(lower_bound, upper_bound)`. Otherwise, a simple #' `stat = desired_point` will suffice. #' @param params A list that must contain the necessary parameters for each #' distribution. For example, `params = list(mu = 1, sd = 1)` #' would be for a normal distribution with mean 1 and standard #' deviation 1. If you are not aware of the parameters for the #' distribution, consider using the `visualize.`*dist_name* #' functions listed under the "See Also" section. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, or`"tails"` #' @author #' James Balamuta #' @seealso #' [visualize.it()], [visualize.beta()], [visualize.chisq()], [visualize.exp()], #' [visualize.gamma()], [visualize.norm()], [visualize.unif()], [visualize.cauchy()], #' [visualize.f()], [visualize.lnorm()], [visualize.t()], [visualize.wilcox()], #' [visualize.logis()]. #' @keywords continuous-distribution #' @export #' @examples #' # Function does not have dist look up, must go through visualize.it #' visualize.it(dist='norm', stat = c(0,1), params = list(mu = 1, sd = 1), section = "bounded") #' visualize.continuous <- function(dist, stat = c(0,1), params, section = "lower"){ #Perform the approriate scales to center the distribution. mean = dist$init(params)[[1]];var = dist$init(params)[[2]] #maybe open these up in the next release? line_width = 3 line_style = 2 #Do we have a mean and variance to work with? if(is.numeric(var)) { lb = -3.5*sqrt(var) + mean; ub = 3.5*sqrt(var) + mean mean = signif(mean, digits=3); var = signif(var, digits=3) } #axis length else { lb = -4*params[[2]] + params[[1]]; ub = 4*params[[2]] + params[[1]] } if(mean=="Undefined"){ cat("Warning: df2 < 2, mean is not able to be generated.\n") } #Special axes if(dist$name != "Normal Distribution" && dist$name != "Student t Distribution" && dist$name != "Cauchy Distribution" && dist$name != "Wilcox Rank Sum Distribution") { if(var>1 && is.numeric(var)) { ub = .75*sqrt(var) + mean } else if(!is.numeric(var) && dist$name=="F Distribution"){ ub=3 cat("Warning: df2 < 4, variance is not able to be generated.\n") } else ub = 13*sqrt(var) + mean lb = -0.008; if(section=="tails"){ cat("Warning: Abnormal request for tails condition supplied on nonsymmetric distribution.\n") } } #Creates the center title by concatenating various bits of information. #This may need to be optimized at a later time. graphmain = paste(dist$name," \n") for(i in seq_along(params)){ graphmain = paste(graphmain, dist$varsymbols[i]," = ",params[[i]], " ") } #Generate the initial PDF and plot it. x = seq(lb,ub,length=500) y = dist$density(x,params) plot(x,y, lwd=2, col="black", type="l", xlab=paste(dist$variable,"- Statistic"), ylab="Probability Density", main=graphmain, axes=TRUE) #Evaluate based on section type. if(section == "lower"){ #handle cases outside of graph window if(lb > stat){ lb = stat } path = seq(lb,stat,.01) polygon(c(lb,path,stat), c(0,dist$density(path,params),0), col="Blue", lty=line_style, lwd=line_width, border="Orange") prob = dist$probability(stat,params) subheader = bquote(P(.(dist$variable) <= .(stat)) == .(signif(prob, digits=3))) } else if(section == "bounded"){ start = stat[[1]]; end = stat[[2]]; path=seq(start,end,.01) polygon(c(start,path,end), c(0,dist$density(path,params),0), col="Blue", lty=line_style, lwd=line_width, border="Orange"); prob = dist$probability(end,params) - dist$probability(start,params) subheader = bquote(P(.(start) <= ~ .(as.name(dist$variable)) <= ~ .(end)) == .(signif(prob, digits=3))) } else if(section == "upper"){ if(ub < stat){ ub = stat } path = seq(stat,ub,.01) polygon(c(stat,path,ub), c(0,dist$density(path,params),0), col="Blue", lty=line_style, lwd=line_width, border="Orange") prob = 1-dist$probability(stat,params) subheader = bquote(P(.(dist$variable) >= .(stat)) == .(signif(prob, digits=3))) } else if(section == "tails"){ lower_stat = stat[[1]];upper_stat=stat[[2]]; #make sure we have the right stats if(lower_stat>upper_stat){ hold = lower_stat lower_stat = upper_stat upper_stat = hold } #handle cases outside of graph window if(ub < upper_stat){ ub = upper_stat } if(lb > lower_stat){ lb = lower_stat } #generate lower area lower_path = seq(lb,lower_stat,.01) polygon(c(lb,lower_path,lower_stat), c(0,dist$density(lower_path,params),0), col="Blue", lty=line_style, lwd=line_width, border="Orange") #generate upper area upper_path = seq(upper_stat,ub,.01) polygon(c(upper_stat,upper_path,ub), c(0,dist$density(upper_path,params),0), col="Blue", lty=line_style, lwd=line_width, border="Orange") prob = 1-dist$probability(upper_stat,params)+dist$probability(lower_stat,params) subheader = bquote(P(.(dist$variable) <= .(lower_stat))+P(.(dist$variable) >= .(upper_stat)) == .(signif(prob, digits=3))) } else{ stop("Section not specified. Please choose either lower, bounded, tails, or upper.") } if(length(stat)==1){ axis(1,at=stat[[1]],labels=bquote(eta[.(stat[[1]])]), line=.69) } else{ axis(1,at=stat[[1]],labels=bquote(eta[.(stat[[1]])]), line=.69) axis(1,at=stat[[2]],labels=bquote(eta[.(stat[[2]])]), line=.69) } mtext(subheader,3) title(sub = bquote(mu ~ "=" ~ .(mean) ~ ", " ~ sigma^2 ~ "=" ~ .(var))) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.continuous.R
#' Graphing function for Discrete Distributions. #' #' Handles how discrete distributions are graphed. Users should not use this #' function. Instead, users should use \code{link{visualize.it}}. #' #' #' @param dist contains the distribution from #' \code{link{visualize.distributions}}. #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param params A list that must contain the necessary parameters for each #' distribution. For example, `params = list(n = 5, prob = .25)` would be #' for a binomial distribution with size 5 and probability .75. If you are not #' aware of the parameters for the distribution, consider using the #' `visualize.`*dist_name* functions listed under the "See Also" #' section. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @param strict Determines whether the probability will be generated as a #' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires #' either values = 0 or =FALSE for equal to OR values =1 or =TRUE for strict. #' For bounded condition use: `strict=c(0,1)` or #' `strict=c(FALSE,TRUE)`. #' @author James Balamuta #' @seealso [visualize.it()], [visualize.binom()], #' [visualize.geom()], [visualize.hyper()], #' [visualize.nbinom()], [visualize.pois()]. #' @export #' @keywords visualize #' @examples #' #' # Function does not have dist look up, must go through visualize.it #' visualize.it(dist='geom', stat = c(2,4), params = list(prob = .75), section = "bounded", #' strict = c(0,1)) #' visualize.discrete <- function(dist, stat = c(0,1), params, section = "lower", strict){ stat = round(stat) #Perform the approriate scales to center the distribution. mean = dist$init(params)[1];var = dist$init(params)[2] lower_bound = max(0,round(-3*sqrt(var) + mean)); upper_bound = round(3*sqrt(var) + mean) #Builds data for graph x = seq(lower_bound,upper_bound,by=1) y = dist$density(x,params) ymax = max(y)+0.05 #Creates Graph Title graphmain = paste(dist$name," \n") for(i in seq_along(params)){ graphmain = paste(graphmain, dist$varsymbols[i]," = ",params[[i]], " ") } #evaluate based on sections, rewrite v5? if(section == "lower"){ if(stat >= lower_bound) region = stat[[1]]-lower_bound+1 else region = 0 #Build lower tail shade if stat is within bounds. i = region-1*(strict[[1]] == 1 & stat >= lower_bound) j = abs(region - upper_bound)+1+1*(strict[[1]] == 1 & stat >= lower_bound) barplot(y, ylim = c(0, ymax), col=c(rep("blue",i),rep("white",j)), axes = FALSE) barplot(y, ylim = c(0, ymax), xlab = "Values", ylab = "Probability", names.arg = x, main=graphmain, col=c(rep("orange",i),rep("white",j)), density=c(rep(3,i),rep(0,j)), add = TRUE) prob = dist$probability(stat-1*(strict[[1]] == 1),params) ineqsym = if(strict[[1]]==0){" <= "}else{" < "} subheader = bquote(P( .(as.name(dist$variable)) ~ .(as.name(ineqsym)) ~ .(as.name(stat)) ) == ~.(signif(prob, digits=3))) } else if(section == "bounded"){ disupper = upper = stat[[2]]; dislower = lower = stat[[1]] #Map the bounds if(upper > upper_bound){ upper = upper_bound if(lower > upper_bound) lower = upper_bound } if(lower < lower_bound){ lower = lower_bound if(upper < lower_bound) upper = lower_bound } #Calculate necessary adjustments. #Figure out whether the stat is outside of the graph display bounds_adjust = -1*((dislower < lower_bound & disupper < lower_bound) || (disupper > upper_bound & dislower > upper_bound)) lower_adjust = 1*(lower_bound == lower & upper_bound != upper); upper_adjust = 1*(upper_bound == upper & lower_bound != lower) #Adjust if inequalities are strict, while checking stat with graph display. strict_adjust = -1*(strict[[1]]==1 & bounds_adjust != -1 & lower_adjust != 1) - 1*(strict[[2]]==1 & bounds_adjust != -1 & upper_adjust != 1) #Build the grid. i = abs(lower-lower_bound) + 1*(strict[[1]]==1 & dislower >= lower_bound) j = abs(upper-lower) + 1 + strict_adjust + bounds_adjust k = abs(upper_bound-upper) + 1*(strict[[2]]==1 & disupper <= upper_bound) #plot the distribution barplot(y, ylim = c(0, ymax), col=c(rep("white",i),rep("blue",j),rep("white",k)), axes = FALSE) barplot(y, ylim = c(0, ymax), xlab = "Values", ylab = "Probability", names.arg = x, main=graphmain, col=c(rep("white",i),rep("orange",j), rep("white",k)), density=c(rep(0,i),rep(3,j),rep(0,k)), add = TRUE) #Generate subtitle prob = dist$probability(disupper-1*(strict[[2]]==1),params) - dist$probability(dislower-1*(strict[[1]]==0),params) if(prob < 0) {prob = 0} low_ineq = if(strict[[1]]==0){" <= "}else{" < "} upper_ineq = if(strict[[2]]==0){" <= "}else{" < "} subheader = bquote(P( .(as.name(dislower)) ~ .(as.name(low_ineq)) ~ .(as.name(dist$variable)) ~ .(as.name(upper_ineq)) ~ .(as.name(disupper)) ) == .(signif(prob, digits=3))) } else if(section == "upper"){ span = upper_bound-lower_bound+1 if(stat <= upper_bound & stat >= lower_bound) region = upper_bound-stat[[1]]+1 else if(stat < lower_bound) region = span else region = 0 i = abs(region - (upper_bound-lower_bound+1))+1*(strict[[1]]==1 & stat >= lower_bound) #region-span of graph j = region-1*(strict[[1]]==1 & stat <= upper_bound & stat >= lower_bound) barplot(y, ylim = c(0, ymax), col=c(rep("white",i),rep("blue",j)), axes = FALSE) barplot(y, ylim = c(0, ymax), xlab = "Values", ylab = "Probability", names.arg = x, main=graphmain, col=c(rep("white",i),rep("orange",j)), density=c(rep(0,i),rep(3,j)), add = TRUE) prob = 1-dist$probability(stat-1*(strict[[1]] == 0),params) ineqsym = if(strict[[1]]==0){">="}else{">"} subheader = bquote(P( .(as.name(dist$variable)) ~ .(as.name(ineqsym)) ~ .(as.name(stat)) ) == .(signif(prob, digits=3))) } else if(section == "tails") #implemented in v4.0 { #set separate stats lower_stat = stat[[1]]; upper_stat = stat[[2]] #set strict values based on 1/0s or true/falses if(strict[[1]]) lower_strict = 1 else lower_strict = 0 if(strict[[2]]) upper_strict = 1 else upper_strict = 0 #determine the span span = upper_bound-lower_bound + 1 #handle the case specific errors if(lower_stat >= lower_bound) lower_region = lower_stat - lower_bound + 1 - 1*(lower_strict==1) else if(lower_stat >= upper_bound) lower_region = span else lower_region = 0 #lower_stat < lower_bound if(upper_stat <= upper_bound & upper_stat >= lower_bound) upper_region = upper_stat-lower_bound+1-1*(upper_strict==1) else upper_region = span #upper_stat < lower_bound #builds counts i = lower_region j = upper_region-i-1+2*(upper_strict==1) k = span-i-j #build graphs barplot(y, ylim = c(0, ymax), col=c(rep("blue",i),rep("white",j),rep("blue",k)), axes = FALSE) barplot(y, ylim = c(0, ymax), xlab = "Values", ylab = "Probability", names.arg = x, main=graphmain, col=c(rep("orange",i),rep("white",j), rep("orange",k)), density=c(rep(3,i),rep(0,j),rep(3,k)), add = TRUE) #handle legend information prob = 1-dist$probability(upper_stat-1*(!upper_strict),params)+dist$probability(lower_stat-1*(lower_strict),params) upper_ineqsym = if(!upper_strict){">="}else{">"} lower_ineqsym = if(!lower_strict){"<="}else{"<"} subheader = bquote(P( .(as.name(dist$variable)) ~ .(as.name(lower_ineqsym)) ~ .(as.name(lower_stat)) ) + P( .(as.name(dist$variable)) ~ .(as.name(upper_ineqsym)) ~ .(as.name(upper_stat)) ) == .(signif(prob, digits=3))) } else{ stop("Section not specified. Please choose either: `lower`, `bounded`, `tails`, or `upper`.") } if(length(stat)==1){ axis(1,at=i+1,labels=bquote(eta[.(stat[[1]])]), line=.69) } else{ axis(1,at=i+1,labels=bquote(eta[.(stat[[1]])]), line=.69) axis(1,at=i+j+2,labels=bquote(eta[.(stat[[2]])]), line=.69) } mtext(subheader,3) title(sub = bquote(mu ~ "=" ~ .(signif(mean, digits=3)) ~ ", " ~ sigma^2 ~ "=" ~ .(signif(var, digits=3))) ) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.discrete.R
#' Visualize Exponential Distribution #' #' Generates a plot of the Exponential distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param theta vector of rates #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dexp()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.exp(stat = .5, theta = 3, section = "lower") #' #' # Evaluates bounded region. #' visualize.exp(stat = c(1,2), theta = 3, section = "bounded") #' #' # Evaluates upper tail. #' visualize.exp(stat = .5, theta = 3, section = "upper") #' visualize.exp <- function(stat = 1, theta = 1, section = "lower") { visualize.it('exp', stat = stat, list(theta = theta), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.exp.R
#' Visualize F distribution #' #' Generates a plot of the F distribution with user specified parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param df1 First Degrees of Freedom #' @param df2 Second Degrees of Freedom #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [df()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.f(stat = 1, df1 = 5, df2 = 4, section = "lower") #' #' # Evaluates bounded region. #' visualize.f(stat = c(3,5), df1 = 6, df2 = 3, section = "bounded") #' #' # Evaluates upper tail. #' visualize.f(stat = 1, df1 = 5, df2 = 4, section = "upper") #' visualize.f <- function(stat = 1, df1 = 5, df2 = 4, section = "lower") { visualize.it('f', stat = stat, list(df1 = df1, df2 = df2), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.f.R
#' Visualize Gamma Distribution #' #' Generates a plot of the Gamma distribution with user specified parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param alpha `alpha` is considered to be *shape* by R's #' implementation of the gamma distribution. `alpha` must be greater than #' 0. #' @param theta `theta` is considered to be *rate* by R's #' implementation of the gamma distribution. `theta` must be greater than #' 0. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dgamma()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluate lower tail. #' visualize.gamma(stat = 1, alpha = 3, theta = 1, section = "lower") #' #' # Evaluate bounded section. #' visualize.gamma(stat = c(0.75,1), alpha = 3, theta = 1, section = "bounded") #' #' # Evaluate upper tail. #' visualize.gamma(stat = 1, alpha = 3, theta = 1, section = "upper") #' #' visualize.gamma <- function(stat = 1, alpha = 1, theta = 1, section = "lower") { visualize.it('gamma', stat = stat, list(alpha = alpha, theta = theta), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.gamma.R
#' Visualize Geometric Distribution #' #' Generates a plot of the Geometric distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param prob probability of picking object. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @param strict Determines whether the probability will be generated as a #' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires #' either values = 0 or =FALSE for equal to OR values =1 or =TRUE for strict. #' For bounded condition use: `strict=c(0,1)` or #' `strict=c(FALSE,TRUE)`. #' @author James Balamuta #' @export #' @seealso [visualize.it()] , [dgeom()]. #' @keywords visualize #' @examples #' #' # Evaluates lower tail. #' visualize.geom(stat = 1, prob = 0.5, section = "lower", strict = FALSE) #' #' # Evaluates bounded region. #' visualize.geom(stat = c(1,3), prob = 0.35, section = "bounded", strict = c(0,1)) #' #' # Evaluates upper tail. #' visualize.geom(stat = 1, prob = 0.5, section = "upper", strict = 1) #' visualize.geom <- function(stat = 1, prob = .3, section = "lower", strict = FALSE) { visualize.it('geom', stat = stat, list(prob = prob), section = section, strict=strict) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.geom.R
#' Visualize Hypergeometric Distribution #' #' Generates a plot of the Hypergeometric distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param m `m` white balls. `m` must be greater than 0. #' @param n `n` black balls. `n` must be greater than 0. #' @param k draw `k` balls without replacement. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @param strict Determines whether the probability will be generated as a #' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires #' either values = 0 or =FALSE for equal to OR values =1 or =TRUE for strict. #' For bounded condition use: `strict=c(0,1)` or #' `strict=c(FALSE,TRUE)`. #' @author James Balamuta #' @export #' @seealso [visualize.it()] , [dhyper()]. #' @keywords visualize #' @examples #' #' # Evaluates lower tail. #' visualize.hyper(stat = 1, m=4, n=5, k=3, section = "lower", strict = 0) #' #' # Evaluates bounded region. #' visualize.hyper(stat = c(2,4), m=14, n=5, k=2, section = "bounded", strict = c(0,1)) #' #' # Evaluates upper tail. #' visualize.hyper(stat = 1, m=4, n=5, k=3, section = "upper", strict = 1) #' visualize.hyper <- function(stat = 1, m = 5, n = 4, k = 2, section = "lower", strict = FALSE) { visualize.it('hyper', stat = stat, list(m = m, n = n, k = k), section = section, strict=strict) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.hyper.R
#' Visualize's Processing Function #' #' Acts as a director of traffic and first line of error handling regarding #' submitted visualization requests. This function should only be used by #' advanced users. #' #' #' @param dist a string that should be contain a supported probability #' distributions name in R. Supported continuous distributions: `"beta"`, #' `"chisq"`, `"exp"`, `"gamma"`, `"norm"`, and #' `"unif"`. Supported discrete distributions: `"binom"`, #' `"geom"`, `"hyper"`, `"nbinom"`, and `"pois"`. #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param params A list that must contain the necessary parameters for each #' distribution. For example, `params = list(mu = 1, sd = 1)` would be for #' a normal distribution with mean 1 and standard deviation 1. If you are not #' aware of the parameters for the distribution, consider using the #' `visualize.dist` functions listed under the "See Also" section. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @param strict Determines whether the probability will be generated as a #' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires #' either values = 0 or =FALSE for strict OR values =1 or =TRUE for equal to. #' For bounded condition use: `strict=c(0,1)` or #' `strict=c(FALSE,TRUE)`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.beta()], [visualize.chisq()], #' [visualize.exp()], [visualize.gamma()], #' [visualize.norm()], [visualize.unif()], #' [visualize.binom()], [visualize.geom()], #' [visualize.hyper()], [visualize.nbinom()], #' [visualize.pois()]. #' @references http://cran.r-project.org/web/views/Distributions.html #' @keywords visualize #' @examples #' #' # Defaults to lower tail evaluation #' visualize.it(dist = 'norm', stat = 1, list(mu = 3 , sd = 2), section = "lower") #' #' # Set to evaluate the upper tail. #' visualize.it(dist = 'norm', stat = 1, list(mu=3,sd=2),section="upper") #' #' # Set to shade inbetween a bounded region. #' visualize.it(dist = 'norm', stat = c(-1,1), list(mu=0,sd=1), section="bounded") #' #' # Gamma distribution evaluated at upper tail. #' visualize.it(dist = 'gamma', stat = 2, params = list(alpha=2,beta=1),section="upper") #' #' # Binomial distribution evaluated at lower tail. #' visualize.it('binom', stat = 2, params = list(n=4,p=.5)) #' #' visualize.it <- function(dist='norm', stat = c(0,1), params = list(mu = 0, sd = 1), section = "lower", strict = c(0,1)) { dist = visualize.distributions[[casefold(dist)]] if(is.null(dist)) stop("Distribution not found.\n") if(length(params) != dist$params) stop("Invalid amount of parameters provided.\n") if(length(stat)>1 & (section != "bounded" & section != "tails")){ stop(paste('Supplied stat length > 1 and section="',section,'" requires one statistic. Please resubmit with stat=your_test_statistic.\n')) } else if(length(stat)<2 & (section == "bounded" | section == "tails")){ stop(paste('Supplied stat length < 2 and section="',section,'" requires two statistics. Please resubmit with stat=c(lower,upper).\n')) } #distribution specific graphing call. if(dist$type == "continuous"){ visualize.continuous(dist, stat, params, section)} else{ #Ensures array is inbounds according to conditions inequality = if(strict[[1]] == 0) {"equal to"} else {"strict"} if(length(strict)<2 & (section == "bounded" | section == "tails")){ strict = c(strict[[1]],strict[[1]]) cat(paste("Supplied strict length < 2, setting inequalities to ", inequality, " inequality.\n")) } visualize.discrete(dist, stat, params, section, strict) } }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.it.R
#' Visualize Log Normal Distribution #' #' Generates a plot of the Log Normal distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param meanlog Mean of the distribution #' @param sdlog Standard deviation of the distribution #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dlnorm()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.lnorm(stat = 1, meanlog = 3, sdlog = 1, section = "lower") #' #' # Evaluates bounded region. #' visualize.lnorm(stat = c(3,5), meanlog = 3, sdlog = 3, section = "bounded") #' #' # Evaluates upper tail. #' visualize.lnorm(stat = 1, meanlog = 3, sdlog = 1, section = "upper") #' visualize.lnorm <- function(stat = 1, meanlog = 3, sdlog = 1, section = "lower") { visualize.it('lnorm', stat = stat, list(meanlog = meanlog, sdlog = sdlog), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.lnorm.R
#' Visualize Logistic distribution #' #' Generates a plot of the Logistic distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param location Location of the distribution. #' @param scale Scale of the distribution. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dlogis()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.logis(stat = 1, location = 4, scale = 2, section = "lower") #' #' # Evaluates bounded region. #' visualize.logis(stat = c(3,5), location = 4, scale = 2, section = "bounded") #' #' # Evaluates upper tail. #' visualize.logis(stat = 1, location = 4, scale = 2, section = "upper") #' visualize.logis <- function(stat = 1, location = 3, scale = 1, section = "lower") { visualize.it('logis', stat = stat, list(location = location, scale = location), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.logis.R
#' Visualize Negative Binomial Distribution #' #' Generates a plot of the Negative Binomial distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param size number of objects. #' @param prob probability of picking object. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @param strict Determines whether the probability will be generated as a #' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires #' either values = 0 or = FALSE for equal to OR values =1 or =TRUE for strict. #' For bounded condition use: `strict=c(0,1)` or #' `strict=c(FALSE,TRUE)`. #' @author James Balamuta #' @export #' @seealso [visualize.it()] , [dnbinom()]. #' @keywords visualize #' @examples #' #' # Evaluates lower tail. #' visualize.nbinom(stat = 1, size = 5, prob = 0.5, section = "lower", strict = 0) #' #' # Evaluates bounded region. #' visualize.nbinom(stat = c(1,3), size = 10, prob = 0.35, section = "bounded", #' strict = c(TRUE, FALSE)) #' #' # Evaluates upper tail. #' visualize.nbinom(stat = 1, size = 5, prob = 0.5, section = "upper", strict = 1) #' visualize.nbinom <- function(stat = 1, size = 6, prob = .5, section = "lower", strict = FALSE) { visualize.it('nbinom', stat = stat, list(size = size, prob = prob), section = section, strict=strict) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.nbinom.R
#' Visualize Normal Distribution #' #' Generates a plot of the Normal distribution with user specified parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param mu mean of the Normal Distribution. #' @param sd standard deviation of the Normal Distribution. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @export #' @seealso [visualize.it()] , [dnorm()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.norm(stat = 1, mu = 4, sd = 5, section = "lower") #' #' # Evaluates bounded region. #' visualize.norm(stat = c(3,6), mu = 5, sd = 3, section = "bounded") #' #' # Evaluates upper tail. #' visualize.norm(stat = 1, mu = 3, sd = 2, section = "upper") #' visualize.norm <- function(stat = 1, mu = 0, sd = 1, section = "lower") { visualize.it('norm', stat = stat, list(mu = mu, sd = sd),section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.norm.R
#' Visualize Poisson Distribution #' #' Generates a plot of the Poisson distribution with user specified parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param lambda lambda value of the Poisson Distribution. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @param strict Determines whether the probability will be generated as a #' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires #' either values = 0 or =FALSE for equal to OR values =1 or =TRUE for strict. #' For bounded condition use: `strict=c(0,1)` or #' `strict=c(FALSE,TRUE)`. #' @author James Balamuta #' @export #' @seealso [visualize.it()] , [dpois()]. #' @keywords visualize #' @examples #' #' # Evaluates lower tail. #' visualize.pois(stat = 1, lambda = 2, section = "lower", strict = FALSE) #' #' # Evaluates bounded region. #' visualize.pois(stat = c(1,3), lambda = 3, section = "bounded", strict = c(0,1)) #' #' # Evaluates upper tail. #' visualize.pois(stat = 1, lambda = 2, section = "upper", strict = 1) #' visualize.pois <- function(stat = 1, lambda = 3.5, section = "lower", strict = FALSE) { visualize.it('pois', stat = stat, list(lambda = lambda), section = section, strict=strict) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.pois.R
#' Visualize Student's t distribution #' #' Generates a plot of the Student's t distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param df Degrees of freedom #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dt()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.t(stat = 1, df = 4, section = "lower") #' #' # Evaluates bounded region. #' visualize.t(stat = c(3,5), df = 6, section = "bounded") #' #' # Evaluates upper tail. #' visualize.t(stat = 1, df = 4, section = "upper") #' visualize.t <- function(stat = 1, df = 3, section = "lower") { visualize.it('t', stat = stat, list(df = df), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.t.R
#' Visualize Uniform Distribution #' #' Generates a plot of the Uniform distribution with user specified parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param a starting point. Note: `a`<`b` #' @param b end point. Note: `b` > `a` #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @author James Balamuta #' @seealso [visualize.it()] , [dunif()]. #' @export #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.unif(stat = 8.75, a = 7, b = 10, section = "lower") #' #' # Evaluates bounded region. #' visualize.unif(stat = c(3,6), a = 1, b = 7, section = "bounded") #' #' # Evaluates upper tail. #' visualize.unif(stat = 2, a = 1, b = 5, section = "upper") #' visualize.unif <- function(stat = 1, a = 0, b = 1, section = "lower") { visualize.it('unif', stat = stat, list(a = a, b = b), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.unif.R
#' Visualize Cauchy Distribution #' #' Generates a plot of the Wilcoxon Rank Sum distribution with user specified #' parameters. #' #' #' @param stat a statistic to obtain the probability from. When using the #' "bounded" condition, you must supply the parameter as `stat = #' c(lower_bound, upper_bound)`. Otherwise, a simple `stat = #' desired_point` will suffice. #' @param m Sample size from group 1. #' @param n Sample size from group 2. #' @param section Select how you want the statistic(s) evaluated via #' `section=` either `"lower"`,`"bounded"`, `"upper"`, #' or`"tails"`. #' @return Returns a plot of the distribution according to the conditions #' supplied. #' @author James Balamuta #' @export #' @seealso [visualize.it()], [dwilcox()]. #' @keywords continuous-distribution #' @examples #' #' # Evaluates lower tail. #' visualize.wilcox(stat = 1, m = 7, n = 3, section = "lower") #' #' # Evaluates bounded region. #' visualize.wilcox(stat = c(2,3), m = 5, n = 4, section = "bounded") #' #' # Evaluates upper tail. #' visualize.wilcox(stat = 1, m = 7, n = 3, section = "upper") #' visualize.wilcox <- function(stat = 1, m = 7, n = 3, section = "lower") { visualize.it('wilcox', stat = stat, list(m = m, n = n), section = section) }
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.wilcox.R
#' Home Mortgage Disclosure Act dataset #' @source Stock, J. H. and Watson, M. W. (2007). Introduction to Econometrics, 2nd ed. Boston: Addison Wesley. #' @docType data #' @usage data(Hmda) #' @keywords datasets "Hmda"
/scratch/gouwar.j/cran-all/cranData/visualpred/R/Hmda.R
#' Breast Cancer Winsconsin dataset #' @docType data #' @usage data(breastwisconsin1) #' @keywords datasets #' @source https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original) "breastwisconsin1"
/scratch/gouwar.j/cran-all/cranData/visualpred/R/breast.R
#' Contour plots and FAMD function for classification modeling #' #' This function presents visual graphics by means of FAMD. #' FAMD function is Factorial Analysis for Mixed Data (interval and categorical) #' Dependent classification variable is set as supplementary variable. #' Machine learning algorithm predictions are presented in a filled contour setting #' @usage famdcontour(dataf=dataf,listconti,listclass,vardep,proba="", #' title="",title2="",depcol="",listacol="",alpha1=0.7,alpha2=0.7,alpha3=0.7, #' classvar=1,intergrid=0,selec=0,modelo="glm",nodos=3,maxit=200,decay=0.01, #' sampsize=400,mtry=2,nodesize=10,ntree=400,ntreegbm=500,shrink=0.01, #' bag.fraction=1,n.minobsinnode=10,C=100,gamma=10,Dime1="Dim.1",Dime2="Dim.2") #' @param dataf data frame. #' @param listconti Interval variables to use, in format c("var1","var2",...). #' @param listclass Class variables to use, in format c("var1","var2",...). #' @param vardep Dependent binary classification variable. #' @param proba vector of probability predictions obtained externally (optional) #' @param Dime1,Dime2 FAMD Dimensions to consider. Dim.1 and Dim.2 by default. #' @param intergrid scale of grid for contour:0 if automatic #' @param selec 1 if stepwise logistic variable selection is required, 0 if not. #' @param title plot main title #' @param title2 plot subtitle #' @param depcol vector of two colors for points #' @param listacol vector of colors for labels #' @param alpha1 alpha transparency for majoritary class #' @param alpha2 alpha transparency for minoritary class #' @param alpha3 alpha transparency for fit probability plots #' @param classvar 1 if dependent variable categories are plotted as supplementary #' @param modelo name of model: "glm","gbm","rf,","nnet","svm". #' @param nodos nnet: nodes #' @param maxit nnet: iterations #' @param decay nnet: decay #' @param sampsize rf: sampsize #' @param mtry rf: mtry #' @param nodesize rf: nodesize #' @param ntree rf: ntree #' @param ntreegbm gbm: ntree #' @param shrink gbm: shrink #' @param bag.fraction gbm: bag.fraction #' @param n.minobsinnode gbm:n.minobsinnode #' @param C svm Radial: C #' @param gamma svm Radial: gamma #' @keywords FAMD, classification, contour_curves #' @export #' @import MASS #' @import ggplot2 #' @importFrom MBA mba.points #' @importFrom magrittr %>% #' @importFrom nnet nnet #' @import gbm #' @import e1071 #' @importFrom stats aggregate quantile #' @importFrom dplyr inner_join #' @importFrom randomForest randomForest #' @importFrom FactoMineR FAMD #' @importFrom pROC roc #' @examples #' data(breastwisconsin1) #' dataf<-breastwisconsin1 #' listconti=c( "clump_thickness","uniformity_of_cell_shape","mitosis") #' listclass=c("") #' vardep="classes" #' result<-famdcontour(dataf=dataf,listconti,listclass,vardep) #' @details #' FAMD algorithm from FactoMineR package is used to compute point coordinates on dimensions #' (Dim.1 and Dim.2 by default). #' Minority class on dependent variable category is represented as red, majority category as green. #' Color scheme can be altered using depcol and listacol, as well as alpha transparency values. #' #'## Predictive modeling #' For predictive modeling, selec=1 selects variables with a simple stepwise logistic regression. #' By default select=0. #' Logistic regression is used by default. Basic parameter setting is supported for algorithms nnet, rf,gbm and svm-RBF. #' A vector of fitted probabilities obtained externally from other #' algorithms can be imported in parameter proba=nameofvector. Contour curves are then #' computed based on this vector. #' #' ## Contour curves #' Contour curves are build by the following process: i) the chosen algorithm model is trained and all #' observations are predicted-fitted. ii) A grid of points on the two chosen FAMD dimensions is built #' iii) package MBA is used to interpol probability estimates over the grid, based on #' previously fitted observations. #' #' ## Variable representation #' In order to represent interval variables, categories of class variables, and points in the same plot, #' a proportional projection of interval variables coordinates over the two dimensions range is applied. #' Since space of input variables is frequently larger than two dimensions, sometimes overlapping of #' points is produced; a frequency variable is used, and alpha values may be adjusted to avoid wrong interpretations #' of the presence of dependent variable category/color. #' #' ## Troubleshooting #' * Check missings. Missing values are not allowed. #' * By default selec=0. Setting selec=1 may sometimes imply that no variables are selected; an error message is shown n this case. #' * Models with only two input variables could lead to plot generation problems. #' * Be sure that variables named in listconti are all numeric. #' * If some numeric variable is constant at one single value, process is stopped since numeric Min-max standarization is performed, #' and NaN values are generated. #' #' @return A list with the following objects:\describe{ #' \item{graph1}{plot of points on FAMD first two dimensions} #' \item{graph2}{plot of points and contour curves} #' \item{graph3}{plot of points and variables} #' \item{graph4}{plot of points variable and contour curves} #' \item{graph5}{plot of points colored by fitted probability} #' \item{graph6}{plot of points colored by abs difference} #' \item{df1}{ data frame used for graph1} #' \item{df2}{ data frame used for contour curves} #' \item{df3}{ data frame used for variable names} #' \item{listconti}{interval variables used-selected } #' \item{listclass}{class variables used-selected } #' } #' @references Pages J. (2004). Analyse factorielle de donnees mixtes. Revue Statistique Appliquee. LII (4). pp. 93-111. ###################################################################### # # famdcontour.R # # copyright (c) 2020-13-10, Javier Portela # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License, # version 3, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but without any warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. See the GNU # General Public License, version 3, for more details. # # A copy of the GNU General Public License, version 3, is available # at http://www.r-project.org/Licenses/GPL-3 # ###################################################################### famdcontour<-function(dataf=dataf,listconti,listclass,vardep,proba="", title="",title2="",depcol="",listacol="",alpha1=0.7,alpha2=0.7,alpha3=0.7, classvar=1,intergrid=0,selec=0,modelo="glm", nodos=3,maxit=200,decay=0.01,sampsize=400,mtry=2,nodesize=10,ntree=400,ntreegbm=500, shrink=0.01,bag.fraction=1,n.minobsinnode=10,C=100, gamma=10,Dime1="Dim.1",Dime2="Dim.2") { if (any(listacol=="")==TRUE) { listacol<-c("#377EB8", "#4DAF4A", "#984EA3", "#FF7F00", "#A65628", "#F781BF", "#999999", "#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E","#E6AB02", "#A6761D", "#666666", "#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072", "#80B1D3", "#FDB462", "#B3DE69", "#FCCDE5", "#D9D9D9","#A6CEE3","#1F78B4","#B2DF8A","#33A02C","#FB9A99","#E31A1C", "#FDBF6F","#FF7F00","#CAB2D6","#6A3D9A","#FFFF99","#B15928") } count.dups <- function(DF){ DT <- data.table::data.table(DF) DT[,.N, by=list(dimf1=DF$dimf1,dimf2=DF$dimf2)] } .N<-numeric() minori<-numeric() dimf1<-numeric() dimf2<-numeric() Frecu<-numeric() Variable<-character() fontface<-numeric() z<-numeric() dife<-numeric() # class minor tabla1<-as.data.frame(table(dataf[,vardep])) tabla1<-tabla1[order(tabla1$Freq),] minoritaria<-as.character(tabla1[1,c("Var1")]) tabla1<-tabla1[order(-tabla1$Freq),] mayoritaria<-as.character(tabla1[1,c("Var1")]) if (minoritaria==mayoritaria) { tabla1<-tabla1[order(tabla1$Freq),] mayoritaria<-as.character(tabla1[2,c("Var1")]) } cosa<-as.data.frame(prop.table(table(dataf[[vardep]]))) fremin<-100*round(min(cosa$Freq),2) totalobs=nrow(dataf) cosa<-as.data.frame(table(dataf[[vardep]])) totalmin<-round(min(cosa$Freq),2) if (any(listclass==c(""))==TRUE) { dataf<-dataf[,c(listconti,vardep)] } if (any(listclass==c(""))==FALSE) { if (any(listconti==c(""))==FALSE) {dataf<-dataf[,c(listconti,listclass,vardep)]} if (any(listconti==c(""))==TRUE) {dataf<-dataf[,c(listclass,vardep)]} } # -INTERVAL: # 1) STANDARD TO 0,1 # 2) BINNING # -CLASS VARIABLES: NOTHING # ALL ARE RECODED TO A FACTOR # # 0-1 if (any(listconti==c(""))==FALSE) { normFunc <- function(x){(x-min(x, na.rm = T))/(max(x, na.rm = T)-min(x, na.rm = T))} dataf[c(listconti)] <- apply(dataf[c(listconti)], 2, normFunc) } # CLASS TO FACTOR if (any(listclass==c(""))==FALSE) { dataf[c(listclass,vardep)]<- lapply(dataf[c(listclass,vardep)],as.factor) } if (any(listclass==c(""))==FALSE) { for (i in listclass) { levels(dataf[,i])<-paste(i,"_",levels(dataf[,i]),sep="") } } # SELECTION IF IT IS REQUIRED if (selec==1) { formu1<-paste("factor(",vardep,")~.") full.model <-stats::glm(stats::formula(formu1), data = dataf, family = binomial(link="logit")) step.model <- full.model %>% stepAIC(trace = FALSE) cosa<-attr(stats::terms(step.model), "term.labels") # Reduce data frame if (any(listclass==c(""))==FALSE) { listclass <- listclass[listclass %in%cosa] if (any(listconti==c(""))==FALSE) { listconti <- listconti[listconti %in%cosa] } } if (any(listclass==c(""))==TRUE) { listconti <- listconti[listconti %in%cosa] } if (any(listclass==c(""))==TRUE) { dataf<-dataf[,c(listconti,vardep)] } if (any(listclass==c(""))==FALSE) { if (any(listconti==c(""))==FALSE) {dataf<-dataf[,c(listconti,listclass,vardep)]} if (any(listconti==c(""))==TRUE) {dataf<-dataf[,c(listclass,vardep)]} } } # LA DEPENDIENTE A char vectordep<-as.data.frame(dataf[,vardep]) dataf[,c(vardep)]<-as.character(dataf[,c(vardep)]) # # QUITO LA VAR. DEPENDIENTE Y AÑADO VARIABLE FANTASMA COSA POR SI ACASO # if (any(listclass==c(""))==FALSE) # { # if (any(listconti==c(""))==FALSE) # { # dataf<-dataf[,c(listconti,listclass)] # } # if (any(listconti==c(""))==TRUE) # { # dataf<-dataf[,c(listclass)] # } # } # # if (any(listclass==c(""))==TRUE||length(listclass)==0) # { # dataf<-dataf[,c(listconti)] # dataf<-as.data.frame(dataf) # } co=0 if (any(listclass==c(""))==TRUE||length(listclass)==0) { co=1 dataf$cosa<-1 dataf$cosa<-as.character(dataf$cosa) dataf<-as.data.frame(dataf) } # FUNCIÓN MCA CON FAMD colu<-which(colnames(dataf)==vardep) mca1= FAMD(dataf,sup.var=colu,graph=FALSE,ncp=5) # mca1_vars_df1 = data.frame(mca1$var$coord,Variable=row.names(mca1$var$coord)) if (co==1) { dataf$cosa<-NULL } mca1_vars_df1=data.frame(mca1$quanti.var$coord,Variable=row.names(mca1$quanti.var$coord)) if (length(listclass)==1 & any(listclass==c(""))==FALSE) { ncats1 = nlevels(as.factor(dataf[,listclass])) cats1 = levels(as.factor(dataf[,listclass])) mca1_vars_df2 = data.frame(mca1$quali.var$coord, Variable = (cats1)) } if (length(listclass)>1) { cats1 = apply(dataf[,listclass], 2, function(x) nlevels(as.factor(x))) mca1_vars_df2 = data.frame(mca1$quali.var$coord, Variable = rep(names(cats1), cats1)) } if (any(listclass==c(""))==TRUE||length(listclass)==0) { mca1_vars_df2 = data.frame(mca1$quali.var$coord, Variable = row.names(mca1$quali.var$coord)) } variss<-data.frame(mca1$quali.sup$coord) variss$Variable<-paste(".",vardep,sep="") mca1$ind$coord= data.frame(mca1$ind$coord) mca1$ind$coord<-cbind(mca1$ind$coord,vardep=vectordep[,1]) mca1$ind$coord$dimf1<-mca1$ind$coord[,c(Dime1)] mca1$ind$coord$dimf2<-mca1$ind$coord[,c(Dime2)] mca1_vars_df2$dimf1<-mca1_vars_df2[,c(Dime1)] mca1_vars_df2$dimf2<-mca1_vars_df2[,c(Dime2)] maxi1<-max(mca1$ind$coord$dimf1) mini1<-max(mca1$ind$coord$dimf1) maxi2<-max(mca1$ind$coord$dimf2) mini2<-max(mca1$ind$coord$dimf2) # Retoco coordenadas var. quanti mca1_vars_df1$dimf1<-mca1_vars_df1[,c(Dime1)] mca1_vars_df1$dimf2<-mca1_vars_df1[,c(Dime2)] mca1_vars_df1$dimf1<-ifelse(mca1_vars_df1$dimf1>=0,mca1_vars_df1$dimf1*maxi1, mca1_vars_df1$dimf1*abs(mini1)) mca1_vars_df1$dimf2<-ifelse(mca1_vars_df1$dimf2>=0,mca1_vars_df1$dimf2*maxi2, mca1_vars_df1$dimf2*abs(mini2)) if (co==0) { mca1_vars_df2$dimf1<-mca1_vars_df2[,c(Dime1)] mca1_vars_df2$dimf2<-mca1_vars_df2[,c(Dime2)] mca1_vars_df1<-rbind(mca1_vars_df1,mca1_vars_df2) } # SUPLEMENTARIA variss$dimf1<-variss[,c(Dime1)] variss$dimf2<-variss[,c(Dime2)] # CONTEO DE FRECUENCIAS EN EL dataf mca1_obs_df au<-as.data.frame(count.dups(mca1$ind$coord)) au$Frecu<-au$N au$N<-NULL mca1$ind$coord<-inner_join(mca1$ind$coord,au, by = c("dimf1","dimf2")) # CONSTRUCCIÓN DE REJILLA Y PREDICCIÓN CONTOUR dataf[,vardep]<-factor(dataf[,vardep],levels=c(mayoritaria,minoritaria)) formu<-paste("factor(",vardep,")~.") formu<-stats::formula(formu) # ********************* # MODELOS # ********************* if (any(proba=="")==TRUE) { if (modelo=="nnet") { model <- nnet( formula(formu),data=dataf, size = nodos, maxit = maxit, trace = FALSE,decay=decay,linout=FALSE) proba<- predict(model,dataf,type="raw") } if (modelo=="glm") { model <- glm(formula(formu), family=binomial(link='logit'),data=dataf) proba<- predict(model,dataf,type="response") } if (modelo=="rf") { if (sampsize>nrow(dataf)) {sampsize=nrow(dataf)} model <- randomForest(formula(formu),data=dataf,sampsize=sampsize, mtry=mtry,nodesize=nodesize,ntree=ntree) proba <- predict(model, dataf,type="prob") proba<-as.vector(proba[,2]) } if (modelo=="gbm") { formu<-paste("clasefin~.") dataf$clasefin<-ifelse(dataf[,c(vardep)]==minoritaria,1,0) dataf$clasefin<-as.character(dataf$clasefin) a3<-dataf a3[,c(vardep)]<-NULL model <- gbm(formula(formu),distribution="bernoulli", data=a3, n.trees=ntreegbm,shrinkage = shrink, bag.fraction = bag.fraction,n.minobsinnode=n.minobsinnode, interaction.depth = 2,verbose=FALSE) proba <- predict(model,a3,type="response",n.trees=model$n.trees) } if (modelo=="svm") { dataf$vardep2<-ifelse(dataf[,c(vardep)]==minoritaria,1,0) vector1<-dataf$vardep dataf$vardep<-NULL formu<-paste("factor(vardep2)~.") model <- svm(formula(formu), data=dataf, kernel = "radial",cost=C,gamma=gamma,probability = TRUE) proba<- predict(model, dataf,probability = TRUE) proba<-as.data.frame(attr(proba, "probabilities","dimnames")) proba<-as.data.frame(proba[,c("1")]) names(proba)<-"V1" dataf$vardep2<-NULL dataf$vardep<-vector1 } } proba<-as.data.frame(proba) names(proba)<-"V1" union<-cbind(proba,mca1$ind$coord) union$V1<-as.numeric(as.character(union$V1)) curvaroc<-suppressMessages(pROC::roc(response=union$vardep,predictor=union$V1)) auc<-round(curvaroc$auc,2) if (any(title2=="")==TRUE) { title2<-paste(vardep," ","minor=", fremin,"% ","totalobs=",totalobs," ","totalmin=",totalmin," ", "algorithm=", modelo, " auc=", auc) } union$x<-union$dimf1 union$y<-union$dimf2 union$z<-union$V1 union$minori<-ifelse(union$vardep==minoritaria,1,0) unia<-union[,c("x","y","z")] unia<-unia[order(unia$x,unia$y,unia$z),] filasorig<-nrow(unia) t <-aggregate(unia, by=list(unia$x,unia$y), FUN=mean, na.rm=TRUE) filasfin<-nrow(t) t<-t[order(t$x,t$y),] # Aquí miro min max minx<-min(t$x) miny<-min(t$y) maxx<-max(t$x) maxy<-max(t$y) maxx<-maxx+intergrid maxy<-maxy+intergrid filas<-nrow(t) rango1<-maxy-miny rango2<-maxx-minx if (intergrid==0) { intergrid=0.5*rango1*rango2/filas intergrid=sqrt(intergrid) } f<-data.frame() for (x in seq(minx,maxx,intergrid)) { for (y in seq(miny,maxy,intergrid)){ b<-cbind(x,y) f<-rbind(f,b) } } filas2<-nrow(f) t<-t[,c("x","y","z")] # AQUÍ SE INTERPOLA EN LOS PUNTOS CREADOS EN EL GRID F ANTERIOR, CON BASE EN EL data t t<-mba.points(t,xy.est=f) t<-as.data.frame(t) t<-t[order(t$xyz.est.x,t$xyz.est.y),] t$x<-t$xyz.est.x t$y<-t$xyz.est.y t$z<-t$xyz.est.z t$z<-ifelse(t$z<0,0.00000001,t$z) t$z<-ifelse(t$z>1,0.9999999,t$z) t<-t[,c("x","y","z")] mca1$ind$coord$x<-mca1$ind$coord$dimf1 mca1$ind$coord$y<-mca1$ind$coord$dimf2 # GRAFICOS # Dimensiones first<-as.numeric(substr(c(Dime1),5,5)) second<-as.numeric(substr(c(Dime2),5,5) ) ejex<-paste(Dime1,"(",trunc(mca1$eig[first,2]*10)/10,"%)",sep="") ejey<-paste(Dime2,"(",trunc(mca1$eig[second,2]*10)/10,"%)",sep="") # COLORS lista1<-c("gray70","red") if (any(depcol=="")==TRUE) { depcol<-c("darkolivegreen3", "red") } la<-c(mayoritaria,minoritaria) colScale <- scale_colour_manual(name = "vardep",values = depcol,labels=la) # k colors from list ta<-as.data.frame(table(as.character(mca1_vars_df1$Variable))) longi<-nrow(ta) ta<-as.character(ta$Var1) listabis<-listacol[c(1:longi)] la2<-c(la,ta) colScale2<- scale_colour_manual(name = "",values =c(depcol,listabis),labels=la2) mxim<-max(as.numeric(names(table(mca1$ind$coord$Frecu)))) mca1$ind$coord$minori<-ifelse(mca1$ind$coord$vardep==minoritaria,1,0) mca1$ind$coord$minori<-as.character(mca1$ind$coord$minori) mxim<-max(as.numeric(names(table(mca1$ind$coord$Frecu)))) k<-nrow(table(mca1$ind$coord$Frecu)) vectorFre<-as.numeric(names(table(mca1$ind$coord$Frecu))) if (k<=4) { bre<-vectorFre rango<-c(1,k) } if (k>=4) { bre<-numeric() for(i in seq(1,mxim,by=mxim/4)) { bre<-append(bre,ceiling(i)) } rango<-c(1,4) } union$minori<-as.numeric(union$minori) union$dife<-(union$minori-union$z) # Add identification variable mca1$ind$coord$Idt<-1:nrow(mca1$ind$coord) union$Idt<-1:nrow(union) breaks=c(0,0.25,0.50,0.75,0.95,1) g2<-ggplot(mca1$ind$coord, aes(x=x, y=y)) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ geom_point(aes(colour=minori,size=Frecu,alpha=minori))+ scale_alpha_manual(values = c(alpha1, alpha2),guide="none")+ scale_size(name="Freq",breaks=bre,range=rango)+ ggtitle(title,subtitle=title2)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) if (classvar==1) { g2<-g2+ geom_text(data = variss,aes(x =dimf1, y =dimf2,label = rownames(variss), fontface=2),size=5,show.legend=F,colour = "orangered4") } g2<-g2+colScale+geom_density2d(colour = "gray80",alpha=1,show.legend=FALSE)+ xlab(ejex)+ylab(ejey)+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1)), size=guide_legend(title="Freq", override.aes = list(alpha = 1)) ) miniz<-min(t$z) maxiz<-max(t$z) for (i in seq(1,5,by=1)) { if (breaks[i]<=miniz & miniz<=breaks[i+1]) {minimo<-i} if (breaks[i]<=maxiz & maxiz<=breaks[i+1]) {maximo<-i} } inicio=0.8-0.12*(minimo-1) fin=0.2+0.12*(5-maximo) g3<-g2+ geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+ scale_fill_grey(start=inicio,end=fin) gradi<-ggplot(union, aes(x=x, y=y)) + theme_bw()+ geom_point(aes(colour=z,size=Frecu),alpha =alpha3)+ scale_size(name="Freq",breaks=bre,range=rango)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) gradi<-gradi+scale_colour_gradient(low= "green1",high = "red",name="Fitted probability")+ xlab(ejex)+ylab(ejey)+ ggtitle(title,subtitle=title2)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(size=guide_legend(title="Freq", override.aes = list(alpha = 1))) gradi2<-ggplot(union, aes(x=x, y=y)) + theme_bw()+ geom_point(aes(fill=dife,size=Frecu),alpha =alpha3,shape=21,color="orange")+ scale_size(name="Freq",breaks=bre,range=rango)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) gradi2<-gradi2+scale_fill_gradient2(midpoint = 0, low = "blue4", mid = "white", high = "red", space = "Lab",name="vardep-p" ) gradi2<-gradi2+ xlab(ejex)+ylab(ejey)+ ggtitle(title,subtitle=title2)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(size=guide_legend(title="Freq", override.aes = list(alpha = 1))) etivar<-ggplot(mca1$ind$coord, aes(x=x, y=y)) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ geom_point(aes(colour=minori,size=Frecu,alpha=minori))+ scale_alpha_manual(values = c(alpha1, alpha2),guide="none")+ scale_size(name="Freq",breaks=bre,range=rango) etivar<-etivar+geom_density2d(colour = "gray80",alpha=1,show.legend=FALSE) if (classvar==1) { etivar<-etivar+ geom_text(data = variss,aes(x =dimf1, y =dimf2,label = rownames(variss), fontface=2),size=5,show.legend=F,colour = "orangered4") } etivar<-etivar+ geom_text(data = mca1_vars_df1 ,aes(x =dimf1,y =dimf2,label = rownames(mca1_vars_df1 ), colour = Variable))+colScale2 etivar<-etivar+geom_hline(yintercept = 0, colour = "gray70") + geom_vline(xintercept = 0, colour = "gray70")+ ggtitle(title,subtitle=title2)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ xlab(ejex)+ylab(ejey) etivar<-etivar+guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1)), size=guide_legend(title="Freq", override.aes = list(alpha = 1)) ) etivar2<-etivar+geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+ scale_fill_grey(start=inicio,end=fin) cosa<-list(g2,g3,etivar,etivar2,gradi,gradi2,mca1$ind$coord,t,mca1_vars_df1,union, listconti,listclass,colScale,colScale2) names(cosa)<-c("graph1","graph2","graph3","graph4","graph5","graph6", "df1","df2","df3","listconti","listclass") return(cosa) }
/scratch/gouwar.j/cran-all/cranData/visualpred/R/famdcontour.R
#' Outliers in Contour plots and FAMD function for classification modeling #' #' This function adds outlier marks to famdcontour using ggrepel package. #' @inheritParams famdcontour #' @param Idt Identification variable, default "", row number #' @param inf,sup Quantiles for x,y outliers #' @param cutprob cut point for outliers based on prob.estimation error #' @param ... options to be passed from famdcontour #' @keywords FAMD, classification, contour_curves, outliers #' @export #' @import MASS #' @import ggplot2 #' @importFrom MBA mba.points #' @importFrom magrittr %>% #' @importFrom nnet nnet #' @import gbm #' @import e1071 #' @importFrom stats aggregate #' @importFrom dplyr inner_join #' @importFrom randomForest randomForest #' @importFrom FactoMineR FAMD #' @importFrom pROC roc #' @importFrom ggrepel geom_label_repel #' @examples #' data(breastwisconsin1) #' dataf<-breastwisconsin1 #' listconti=c( "clump_thickness","uniformity_of_cell_shape","mitosis") #' listclass=c("") #' vardep="classes" #' result<-famdcontourlabel(dataf=dataf,listconti=listconti, #' listclass=listclass,vardep=vardep) #' @details #' An identification variable can be set in Idt parameter. By default, number of row is used. #' There are two source of outliers: i) outliers in the two FAMD dimension space, where the cutpoints are set #' as quantiles given (inf=0.1 and sup=0.9 in both dimensions by default) and ii) outliers with respect #' to the fitted probability. The dependent variable is set to 1 for the mimority class, and 0 for the majority class. #' Points considered outliers are those for which abs(vardep-fittedprob) excede parameter cutprob. #' #' @return A list with the following objects:\describe{ #' \item{graph1_graph6}{plots for dimension outliers} #' \item{graph7_graph12}{plots for fit outliers} #' } ###################################################################### # # famdcontourlabel.R # # copyright (c) 2020-13-10, Javier Portela # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License, # version 3, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but without any warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. See the GNU # General Public License, version 3, for more details. # # A copy of the GNU General Public License, version 3, is available # at http://www.r-project.org/Licenses/GPL-3 # ###################################################################### famdcontourlabel<-function(dataf=dataf,Idt="",inf=0.10,sup=0.9,cutprob=0.5,...) { if (any(Idt=="")==FALSE) { vectorIdt<-dataf[,c(Idt)] salida<-famdcontour(dataf=dataf,...) salida[[7]]$Idt<-vectorIdt salida[[10]]$Idt<-vectorIdt } if (any(Idt=="")==TRUE) { salida<-famdcontour(dataf=dataf,...) } corte1<-quantile(salida[[7]]$x, probs = inf) # decile corte2<-quantile(salida[[7]]$x, probs = sup) # decile corte3<-quantile(salida[[7]]$y, probs = inf) # decile corte4<-quantile(salida[[7]]$y, probs = sup) # decile salida[[7]]$condicion<-ifelse(salida[[7]]$x<corte1|salida[[7]]$x>corte2|salida[[7]]$y<corte3|salida[[7]]$y>corte4,1,0) glabel1<-salida[[1]]+geom_label_repel(aes(label = ifelse(salida[[7]]$condicion==1, as.character(salida[[7]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel2<-salida[[2]]+geom_label_repel(aes(label = ifelse(salida[[7]]$condicion==1, as.character(salida[[7]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel3<-salida[[3]]+geom_label_repel(aes(label = ifelse(salida[[7]]$condicion==1, as.character(salida[[7]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel4<-salida[[4]]+geom_label_repel(aes(label = ifelse(salida[[7]]$condicion==1, as.character(salida[[7]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel5<-salida[[5]]+geom_label_repel(aes(label = ifelse(salida[[7]]$condicion==1, as.character(salida[[7]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel6<-salida[[6]]+geom_label_repel(aes(label = ifelse(salida[[7]]$condicion==1, as.character(salida[[7]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) salida[[10]]$condicion2<-ifelse(abs(salida[[10]]$dife)>cutprob,1,0) glabel7<-salida[[1]]+geom_label_repel(aes(label = ifelse(salida[[10]]$condicion2==1, as.character(salida[[10]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel8<-salida[[2]]+geom_label_repel(aes(label = ifelse(salida[[10]]$condicion2==1, as.character(salida[[10]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel9<-salida[[3]]+geom_label_repel(aes(label = ifelse(salida[[10]]$condicion2==1, as.character(salida[[10]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel10<-salida[[4]]+geom_label_repel(aes(label = ifelse(salida[[10]]$condicion2==1, as.character(salida[[10]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel11<-salida[[5]]+geom_label_repel(aes(label = ifelse(salida[[10]]$condicion2==1, as.character(salida[[10]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) glabel12<-salida[[6]]+geom_label_repel(aes(label = ifelse(salida[[10]]$condicion2==1, as.character(salida[[10]]$Idt),'')),box.padding = 0.35, point.padding = 0.4,segment.color = 'grey50',size=3) outliers1<-salida[[7]][which(salida[[7]]$condicion==1),] outliers1$est.prob<-outliers1$z outliers2<-salida[[10]][which(salida[[10]]$condicion2==1),] outliers2$est.prob<-outliers2$z return(list(glabel1,glabel2,glabel3,glabel4,glabel5,glabel6,glabel7, glabel8,glabel9,glabel10,glabel11,glabel12,outliers1,outliers2)) }
/scratch/gouwar.j/cran-all/cranData/visualpred/R/famdcontourlabel.R
#' Contour plots and MCA function for classification modeling #' #' This function presents visual graphics by means of Multiple correspondence Analysis projection. #' Interval variables are categorized to bins. #' Dependent classification variable is set as supplementary variable. #' Machine learning algorithm predictions are presented in a filled contour setting. #' @usage mcacontour(dataf=dataf,listconti,listclass,vardep,proba="",bins=8, #' Dime1="Dim.1",Dime2="Dim.2",classvar=1,intergrid=0,selec=0, #' title="",title2="",listacol="",depcol="",alpha1=0.8,alpha2=0.8,alpha3=0.7,modelo="glm", #' nodos=3,maxit=200,decay=0.01,sampsize=400,mtry=2,nodesize=5, #' ntree=400,ntreegbm=500,shrink=0.01,bag.fraction=1,n.minobsinnode=10,C=100,gamma=10) #' @param bins Number of bins for categorize interval variables . #' @inheritParams famdcontour #' @keywords MCA, classification, contour_curves #' @export #' @import MASS #' @import ggplot2 #' @importFrom MBA mba.points #' @importFrom magrittr %>% #' @importFrom nnet nnet #' @import gbm #' @import e1071 #' @importFrom stats aggregate formula glm terms predict family binomial #' @importFrom dplyr inner_join #' @importFrom randomForest randomForest #' @importFrom pROC roc #' @examples #' data(breastwisconsin1) #' dataf<-breastwisconsin1 #' listconti=c( "clump_thickness","uniformity_of_cell_shape","mitosis") #' listclass=c("") #' vardep="classes" #' result<-mcacontour(dataf=dataf,listconti,listclass,vardep) #' @details #' This function applies MCA (Multiple Correspondence Analysis) in order to project points and categories of #' class variables in the same plot. In addition, interval variables listed in listconti are categorized to #' the number given in bins parameter (by default 8 bins). Further explanation about machine learning classification #' and contour curves, see the famdcontour function documentation. #' @return A list with the following objects:\describe{ #' \item{graph1}{plot of points on MCA two dimensions} #' \item{graph2}{plot of points and variables} #' \item{graph3}{plot of points and contour curves} #' \item{graph4}{plot of points, contour curves and variables} #' \item{graph5}{plot of points colored by fitted probability} #' \item{graph6}{plot of points colored by abs difference} #' \item{df1}{ dataset used for graph1} #' \item{df2}{ dataset used for graph2} #' \item{df3}{ dataset used for graph3} #' \item{df4}{ dataset used for graph4} #' \item{listconti}{ interval variables used} #' \item{listclass}{ class variables used} #' \item{...}{color schemes and other parameters } #' } ###################################################################### # # mcacontour.R # # copyright (c) 2020-13-10, Javier Portela # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License, # version 3, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but without any warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. See the GNU # General Public License, version 3, for more details. # # A copy of the GNU General Public License, version 3, is available # at http://www.r-project.org/Licenses/GPL-3 # ###################################################################### mcacontour<-function(dataf=dataf,listconti,listclass,vardep,proba="",bins=8, Dime1="Dim.1",Dime2="Dim.2",classvar=1,intergrid=0,selec=0, title="",title2="",listacol="",depcol="",alpha1=0.8,alpha2=0.8,alpha3=0.7, modelo="glm",nodos=3,maxit=200,decay=0.01,sampsize=400,mtry=2,nodesize=5,ntree=400, ntreegbm=500,shrink=0.01,bag.fraction=1,n.minobsinnode=10,C=100,gamma=10) { if (any(listacol=="")==TRUE) { listacol<-c("#377EB8", "#4DAF4A", "#984EA3", "#FF7F00", "#A65628", "#F781BF", "#999999", "#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E","#E6AB02", "#A6761D", "#666666", "#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072", "#80B1D3", "#FDB462", "#B3DE69", "#FCCDE5", "#D9D9D9","#A6CEE3","#1F78B4","#B2DF8A","#33A02C","#FB9A99","#E31A1C", "#FDBF6F","#FF7F00","#CAB2D6","#6A3D9A","#FFFF99","#B15928") } minori<-numeric() dimf1<-numeric() dimf2<-numeric() Frecu<-numeric() Variable=character() fontface=numeric() z<-numeric() dife<-numeric() tabla1<-as.data.frame(table(dataf[,vardep])) tabla1<-tabla1[order(tabla1$Freq),] minoritaria<-as.character(tabla1[1,c("Var1")]) tabla1<-tabla1[order(-tabla1$Freq),] mayoritaria<-as.character(tabla1[1,c("Var1")]) cosa<-as.data.frame(prop.table(table(dataf[[vardep]]))) fremin<-100*round(min(cosa$Freq),2) totalobs=nrow(dataf) minori=1 cosa<-as.data.frame(table(dataf[[vardep]])) totalmin<-round(min(cosa$Freq),2) salida<-mcamodelobis(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, Dime1=Dime1,Dime2=Dime2,bins=bins,selec=selec) daf<-as.data.frame(salida[[1]]) etiquetas<-as.data.frame(salida[[2]]) datafnuevo<-as.data.frame(salida[[3]]) listconti<-salida[4] listclass<-salida[5] if (length(listclass)==0) {listclass<-c("")} ejex<-salida[6] ejey<-salida[7] variss<-salida[[8]] formu<-paste("factor(",vardep,")~.") formu<-stats::formula(formu) # ********************* # MODELOS # ********************* if (any(proba=="")==TRUE) { if (modelo=="nnet") { model <- nnet( formu,data=datafnuevo, size = nodos, maxit = maxit, trace = FALSE,decay=decay,linout=FALSE) proba<- predict(model,dataf,type="raw") } if (modelo=="glm") { model <- glm(formula(formu),family=binomial(link='logit'),data=datafnuevo) proba<- predict(model,dataf,type="response") } if (modelo=="rf") { if (sampsize>nrow(dataf)) {sampsize=nrow(dataf)} model <- randomForest(formu,data=datafnuevo,sampsize=sampsize, mtry=mtry,nodesize=nodesize,ntree=ntree) proba <- predict(model, dataf,type="prob") proba<-as.vector(proba[,2]) } if (modelo=="gbm") { formu<-paste("clasefin~.") datafnuevo$clasefin<-ifelse(datafnuevo[,c(vardep)]==minoritaria,1,0) datafnuevo$clasefin<-as.character(datafnuevo$clasefin) a2<-datafnuevo a2[,c(vardep)]<-NULL dataf$clasefin<-ifelse(dataf[,c(vardep)]==minoritaria,1,0) dataf$clasefin<-as.character(dataf$clasefin) a3<-dataf a3[,c(vardep)]<-NULL model <- gbm(formula(formu),distribution="bernoulli", data=a2, n.trees=ntreegbm,shrinkage = shrink, bag.fraction = bag.fraction,n.minobsinnode =n.minobsinnode , interaction.depth = 2) proba <- predict(model,a3,type="response",n.trees=model$n.trees) } if (modelo=="svm") { a3<-datafnuevo a3$vardep2<-ifelse(a3[,c(vardep)]==minoritaria,1,0) a3[,c(vardep)]<-NULL formu<-paste("factor(vardep2)~.") model <- svm(formu, data=a3, kernel = "radial",cost=C,gamma=gamma,probability = TRUE) proba<- predict(model, dataf,probability = TRUE) proba<-as.data.frame(attr(proba, "probabilities","dimnames")) proba<-as.data.frame(proba[,c("1")]) names(proba)<-"V1" datafnuevo$vardep2<-NULL } } proba<-as.data.frame(proba) names(proba)<-"V1" union<-cbind(proba,daf) curvaroc<-suppressMessages(pROC::roc(response=union$vardep,predictor=union$V1)) auc<-round(curvaroc$auc,2) if (any(title2=="")==TRUE) { title2<-paste(vardep," ","minor=",fremin,"% ","totalobs=",totalobs," ","totalmin=",totalmin) title3<-paste(vardep," ","minor=",fremin,"% ","totalobs=",totalobs," ","totalmin=",totalmin," ", "algorithm=", modelo," auc=",auc) } else if (any(title2=="")==FALSE) { title3=title2 } union$x<-union$dimf1 union$y<-union$dimf2 union$z<-union$V1 unia<-union[,c("x","y","z")] unia<-unia[order(unia$x,unia$y,unia$z),] filasorig<-nrow(unia) aggdata <-aggregate(unia, by=list(unia$x,unia$y), FUN=mean, na.rm=TRUE) filasfin<-nrow(aggdata) ag<-aggdata[order(aggdata$x,aggdata$y),] # Aquí miro min max minx<-min(aggdata$x) miny<-min(aggdata$y) maxx<-max(aggdata$x) maxy<-max(aggdata$y) filas<-nrow(aggdata) rango1<-maxy-miny rango2<-maxx-minx if (intergrid==0) { intergrid=0.5*rango1*rango2/filas intergrid=sqrt(intergrid) } f<-data.frame() for (x in seq(minx,maxx,intergrid)) { for (y in seq(miny,maxy,intergrid)){ b<-cbind(x,y) f<-rbind(f,b) } } ag<-ag[,c("x","y","z")] # AQUÍ SE INTERPOLA EN LOS PUNTOS CREADOS EN EL GRID F ANTERIOR, CON BASE EN EL dataf AG otro<-mba.points(ag,xy.est=f) otro<-as.data.frame(otro) otro<-otro[order(otro$xyz.est.x,otro$xyz.est.y),] t<-otro t$x<-t$xyz.est.x t$y<-t$xyz.est.y t$z<-t$xyz.est.z t$z<-ifelse(t$z<0,0.00000001,t$z) t$z<-ifelse(t$z>1,0.9999999,t$z) t<-t[,c("x","y","z")] daf$x<-daf$dimf1 daf$y<-daf$dimf2 uni<-etiquetas uni$x<-uni$dimf1 uni$y<-uni$dimf2 uni$Variable<-as.character(uni$Variable) # GRAFICOS # COLORES if (any(depcol=="")==TRUE) { depcol<-c("darkolivegreen3", "red") } la<-c(mayoritaria,minoritaria) colScale <- scale_colour_manual(name = vardep,values = depcol,labels=la) # k colors from list # a<-paste(".",vardep,sep="") # uni<-uni[which(uni$Variable!=a),] ta<-as.data.frame(table(uni$Variable)) longi<-nrow(ta) ta<-as.character(ta$Var1) listabis<-listacol[c(1:longi)] la2<-c(la,ta) colScale2<- scale_colour_manual(name = "",values =c(depcol,listabis),labels=la2) mxim<-max(as.numeric(names(table(daf$Frecu)))) k<-nrow(table(daf$Frecu)) vectorFre<-as.numeric(names(table(daf$Frecu))) if (k<=4) { bre<-vectorFre rango<-c(1,k) } if (k>=4) { bre<-numeric() for(i in seq(1,mxim,by=mxim/4)) { bre<-append(bre,ceiling(i)) } rango<-c(1,4) } union$minori<-as.numeric(union$minori) union$dife<-(union$minori-union$z) breaks=c(0,0.25,0.50,0.75,0.95,1) miniz<-min(t$z) maxiz<-max(t$z) for (i in seq(1,5,by=1)) { if (breaks[i]<=miniz & miniz<=breaks[i+1]) {minimo<-i} if (breaks[i]<=maxiz & maxiz<=breaks[i+1]) {maximo<-i} } inicio=0.8-0.12*(minimo-1) fin=0.2+0.12*(5-maximo) g2<-ggplot(daf, aes(x=x, y=y)) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ geom_point(aes(colour=minori,size=Frecu,alpha=minori))+ scale_alpha_manual(values = c(alpha1, alpha2),guide="none")+ scale_size(name="Freq",breaks=bre,range=rango)+ ggtitle(title,subtitle=title2)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) if (classvar==1) { g2<-g2+ geom_text(data = variss,aes(x =dimf1, y =dimf2,label = rownames(variss), fontface=2),size=5,show.legend=F,colour = "orangered4") } g2<-g2+colScale+geom_density2d(colour = "gray80",alpha=1,show.legend=FALSE)+ xlab(ejex)+ylab(ejey)+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1)), size=guide_legend(title="Freq", override.aes = list(alpha = 1)) ) g3<-g2+ geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+ scale_fill_grey(start=inicio,end=fin)+ ggtitle(title, subtitle = title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) g4<-ggplot(daf, aes(x=x, y=y)) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ geom_point(aes(colour=minori,size=Frecu,alpha =minori))+ scale_alpha_manual(values = c(alpha1, alpha2),guide="none")+ scale_size(name="Freq",breaks=bre,range=rango) if (classvar==1) { g4<-g4+ geom_text(data = variss,aes(x =dimf1, y =dimf2,label = rownames(variss), fontface=2),size=5,show.legend=F,colour = "orangered4") } g4<-g4+geom_density2d(colour = "gray80",alpha=1,show.legend=FALSE)+ xlab(ejex)+ylab(ejey)+ geom_text(data = uni,aes(x =x, y =y,label = rownames(uni), colour = Variable,fontface=1),size=sort(uni$tama),show.legend =F)+ colScale2 g4<-g4+ ggtitle(title, subtitle = title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1)), size=guide_legend(title="Freq", override.aes = list(alpha = 1)) ) g3<-g2+ geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+scale_fill_grey(start=inicio,end=fin) g5<-g4+ geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+scale_fill_grey(start=inicio,end=fin)+ ggtitle(title, subtitle = title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1)), size=guide_legend(title="Freq", override.aes = list(alpha = 1)) ) gradi<-ggplot(union, aes(x=x, y=y)) + theme_bw()+ geom_point(aes(colour=z,size=Frecu),alpha =alpha3)+ scale_size(name="Freq",breaks=bre,range=rango)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) gradi<-gradi+scale_colour_gradient(low= "green1",high = "red",name="Fitted probability")+ xlab(ejex)+ylab(ejey)+ ggtitle(title,subtitle=title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(size=guide_legend(title="Freq", override.aes = list(alpha = 1))) gradi2<-ggplot(union, aes(x=x, y=y)) + theme_bw()+ geom_point(aes(fill=dife,size=Frecu),alpha =alpha3,shape=21,color="orange")+ scale_size(name="Freq",breaks=bre,range=rango)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) gradi2<-gradi2+ scale_fill_gradient2(midpoint = 0, low = "blue4", mid = "white", high = "darkred", space = "Lab",name="vardep-p" ) gradi2<-gradi2+ xlab(ejex)+ylab(ejey)+ ggtitle(title,subtitle=title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(size=guide_legend(title="Freq", override.aes = list(alpha = 1))) cosa<-list(g2,g4,g3,g5,gradi,gradi2,daf,uni,t,union,listconti,listclass, colScale,colScale2,ejex,ejey,title2,title3) names(cosa)<-c("graph1","graph2","graph3","graph4","graph5","graph6","df1", "df2","df3","df4","listconti","listclass") return(cosa) }
/scratch/gouwar.j/cran-all/cranData/visualpred/R/mcacontour.R
#' Contour plots and MCA function for classification modeling #' #' This function is similar to mcacontour but points are jittered in every plot #' @usage mcacontourjit(dataf=dataf,jit=0.1,alpha1=0.8,alpha2=0.8,alpha3=0.7,title="",...) #' @inheritParams mcacontour #' @param jit jit distance. Default 0.1. #' @param ... options to be passed from mcacontour #' @keywords MCA, classification, contour_curves #' @export #' @import MASS #' @import ggplot2 #' @importFrom MBA mba.points #' @importFrom magrittr %>% #' @importFrom nnet nnet #' @import gbm #' @import e1071 #' @importFrom stats aggregate formula glm terms predict family binomial #' @importFrom dplyr inner_join #' @importFrom randomForest randomForest #' @examples #' data(breastwisconsin1) #' dataf<-breastwisconsin1 #' listconti=c( "clump_thickness","uniformity_of_cell_shape","mitosis") #' listclass=c("") #' vardep="classes" #' result<-mcacontourjit(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,jit=0.1) #' @return A list with the following objects:\describe{ #' \item{graph1}{plot of points on MCA two dimensions} #' \item{graph2}{plot of points and variables} #' \item{graph3}{plot of points and contour curves} #' \item{graph4}{plot of points, contour curves and variables} #' \item{graph5}{plot of points colored by fitted probability} #' \item{graph6}{plot of points colored by abs difference} #' } # ROXYGEN_STOP mcacontourjit<-function(dataf=dataf,jit=0.1, alpha1=0.8,alpha2=0.8,alpha3=0.7,title="",...) { minori<-numeric() Variable=character() x<-numeric() y<-numeric() z<-numeric() dife<-numeric() salida<-mcacontour(dataf=dataf,...) daf<-salida[[7]] uni<-salida[[8]] t<-salida[[9]] union<-salida[[10]] colScale<-salida[[13]] colScale2<-salida[[14]] ejex<-salida[[15]] ejey<-salida[[16]] title2<-salida[[17]] title3<-salida[[18]] breaks=c(0,0.25,0.50,0.75,0.95,1) miniz<-min(t$z) maxiz<-max(t$z) for (i in seq(1,5,by=1)) { if (breaks[i]<=miniz & miniz<=breaks[i+1]) {minimo<-i} if (breaks[i]<=maxiz & maxiz<=breaks[i+1]) {maximo<-i} } inicio=0.8-0.12*(minimo-1) fin=0.2+0.12*(5-maximo) jitter=position_jitter(width = jit, height = jit) g2<-ggplot(daf, aes(x=x, y=y)) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ geom_point(aes(colour=minori,alpha =minori),position=jitter,size=1)+ scale_alpha_manual(values = c(alpha1, alpha2),guide="none")+ ggtitle(title,subtitle=title2)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) g2<-g2+colScale+geom_density2d(colour = "gray80",alpha=1,show.legend=FALSE)+ xlab(ejex)+ylab(ejey)+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1))) g3<-g2+ geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+ scale_fill_grey(start=inicio,end=fin)+ ggtitle(title, subtitle = title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) g4<-ggplot(daf, aes(x=x, y=y)) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ geom_point(aes(colour=minori,alpha =minori),size=1,position=jitter)+ scale_alpha_manual(values = c(alpha1, alpha2),guide="none") g4<-g4+geom_density2d(colour = "gray80",alpha=1,show.legend=FALSE)+ xlab(ejex)+ylab(ejey)+ geom_text(data = uni,aes(x =x, y =y,label = rownames(uni), colour = Variable,fontface=1),size=sort(uni$tama),show.legend =F)+ colScale2 g4<-g4+ ggtitle(title, subtitle = title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1))) g5<-g4+ geom_contour_filled(data=t, aes(x=x, y=y,z=z),alpha=0.65,breaks=breaks)+ scale_fill_grey(start=inicio,end=fin)+ ggtitle(title, subtitle = title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") )+ guides(colour = guide_legend("", override.aes = list(size = 4,alpha = 1))) gradi<-ggplot(union, aes(x=x, y=y)) + theme_bw()+ geom_point(aes(colour=z),alpha =alpha3,position=jitter,size=1)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) gradi<-gradi+scale_colour_gradient(low= "green1",high = "red",name="Fitted probability")+ xlab(ejex)+ylab(ejey)+ ggtitle(title,subtitle=title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) gradi2<-ggplot(union, aes(x=x, y=y)) + theme_bw()+ geom_point(aes(fill=dife),alpha =alpha3,shape=21,color="orange",position=jitter,size=1)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) gradi2<-gradi2+scale_fill_gradient2(midpoint = 0, low = "blue", mid = "white", high = "red", space = "Lab",name="vardep-p" ) gradi2<-gradi2+ xlab(ejex)+ylab(ejey)+ ggtitle(title,subtitle=title3)+ theme( plot.title = element_text(hjust=0.5,color="blue"), plot.subtitle= element_text(hjust=0.5,color="orangered4") ) cosa<-list(g2,g4,g3,g5,gradi,gradi2) names(cosa)<-c("graph1","graph2","graph3","graph4","graph5","graph6") return(cosa) }
/scratch/gouwar.j/cran-all/cranData/visualpred/R/mcacontourjitter.R
#' Basic MCA function for clasification #' #' This function presents visual graphics by means of Multiple correspondence Analysis projection. #' Interval variables are categorized to bins. #' Dependent classification variable is set as supplementary variable. It is used as base for mcacontour function. #' @usage mcamodelobis(dataf=dataf,listconti,listclass, vardep,bins=8,selec=1, #' Dime1="Dim.1",Dime2="Dim.2") #' @param dataf data frame. #' @param listconti Interval variables to use, in format c("var1","var2",...). #' @param listclass Class variables to use, in format c("var1","var2",...). #' @param vardep Dependent binary classification variable. #' @param bins Number of bins for categorize interval variables . #' @param Dime1,Dime2 MCA Dimensions to consider. Dim.1 and Dim.2 by default. #' @param selec 1 if stepwise logistic variable selection is required, 0 if not. #' @keywords MCA #' @export #' @importFrom magrittr %>% #' @examples #' data(breastwisconsin1) #' dataf<-breastwisconsin1 #' listconti=c( "clump_thickness","uniformity_of_cell_shape","mitosis") #' listclass=c("") #' vardep="classes" #'result<-mcacontour(dataf=dataf,listconti,listclass,vardep,bins=8,title="",selec=1) #' @import MASS #' @importFrom mltools bin_data #' @importFrom FactoMineR MCA #' @importFrom dplyr inner_join #' @importFrom data.table data.table #' @return A list with the following objects:\describe{ #' \item{df1}{ dataset used for graph1} #' \item{df2}{ dataset used for graph2} #' \item{df3}{ dataset used for graph2} #' \item{listconti}{ interval variables used} #' \item{listclass}{ class variables used} #' \item{axisx}{ axis definition in plot} #' \item{axisy}{axis definition in plot} #' } #' mcamodelobis<-function(dataf=dataf,listconti,listclass, vardep,bins=8,selec=1, Dime1="Dim.1",Dime2="Dim.2") { count.dups <- function(DF){ DT <- data.table::data.table(DF) DT[,.N, by=list(dimf1=DF$dimf1,dimf2=DF$dimf2)] } .N<-numeric() minori<-numeric() dimf1<-numeric() dimf2<-numeric() Frecu<-numeric() Variable=character() fontface=numeric() # class minor tabla1<-as.data.frame(table(dataf[,vardep])) tabla1<-tabla1[order(tabla1$Freq),] minoritaria<-as.character(tabla1[1,c("Var1")]) tabla1<-tabla1[order(-tabla1$Freq),] mayoritaria<-as.character(tabla1[1,c("Var1")]) if (any(listclass==c(""))==TRUE) { dataf<-dataf[,c(listconti,vardep)] } if (any(listclass==c(""))==FALSE) { if (any(listconti==c(""))==FALSE) {dataf<-dataf[,c(listconti,listclass,vardep)]} if (any(listconti==c(""))==TRUE) {dataf<-dataf[,c(listclass,vardep)]} } dataf2<-dataf # -INTERVAL: # 1) STANDARD TO 0,1 # 2) BINNING # -CLASS VARIABLES: NOTHING # ALL ARE RECODED TO A FACTOR # # 0-1 if (any(listconti==c(""))==FALSE) { normFunc <- function(x){(x-min(x, na.rm = T))/(max(x, na.rm = T)-min(x, na.rm = T))} dataf[c(listconti)] <- apply(dataf[c(listconti)], 2, normFunc) } # CLASS TO FACTOR if (any(listclass==c(""))==FALSE) { dataf[c(listclass,vardep)]<- lapply(dataf[c(listclass,vardep)],factor) } # SELECTION IF IT IS REQUIRED if (selec==1) { formu1<-paste("factor(",vardep,")~.") full.model <-stats::glm(stats::formula(formu1), data = dataf, family = binomial(link="logit")) step.model <- full.model %>% stepAIC(trace = FALSE) cosa<-attr(stats::terms(step.model), "term.labels") # Reduce data frame if (any(listclass==c(""))==FALSE) { listclass <- listclass[listclass %in%cosa] if (any(listconti==c(""))==FALSE) { listconti <- listconti[listconti %in%cosa] } } if (any(listclass==c(""))==TRUE) { listconti <- listconti[listconti %in%cosa] } if (any(listclass==c(""))==TRUE) { dataf<-dataf[,c(listconti,vardep)] } if (any(listclass==c(""))==FALSE) { if (any(listconti==c(""))==FALSE) {dataf<-dataf[,c(listconti,listclass,vardep)]} if (any(listconti==c(""))==TRUE) {dataf<-dataf[,c(listclass,vardep)]} } } # Binning if (any(listconti==c(""))==FALSE) { for(col in listconti) { dataf[[col]] <- as.integer(bin_data(dataf[[col]],bins=bins,binType="quantile")) - 1L } } # All to factor if (any(listclass==c(""))==FALSE) { if (any(listconti==c(""))==FALSE) { dataf[c(listconti,listclass,vardep)]<- lapply(dataf[c(listconti,listclass,vardep)],factor) } if (any(listconti==c(""))==TRUE) { dataf[c(listclass,vardep)]<- lapply(dataf[c(listclass,vardep)],factor) } } if (any(listclass==c(""))==TRUE) { dataf[c(listconti,vardep)]<- lapply(dataf[c(listconti,vardep)],factor) } # LA DEPENDIENTE A FACTOR dataf[,c(vardep)]<-as.factor(as.character(dataf[,c(vardep)])) # DEPENDENT as SUPLEMENTARy colu<-which( colnames(dataf)==vardep) # MCA FROM FACTOMINER mca1 =MCA(dataf,quali.sup=colu,graph=FALSE) if (ncol(dataf)>2) { cats1 = apply(dataf[,-c(colu)], 2, function(x) nlevels(as.factor(x))) mca1_vars_df1 = data.frame(mca1$var$coord, Variable = rep(names(cats1), cats1)) } # cats2 =nlevels(dataf[,c(colu)]) # names(cats2)<-vardep if (ncol(dataf)==2) { a<- names(dataf) a<- a[a!=vardep] mca1_vars_df1 = data.frame(mca1$var$coord, Variable =a ) } # mca1_vars_df2= data.frame(mca1$quali.sup$coord, Variable = rep(names(cats2), cats2)) # mca1_vars_df2$Variable<-paste(".",mca1_vars_df2$Variable,sep="") mca1_obs_df = data.frame(mca1$ind$coord) mca1_obs_df<-cbind(mca1_obs_df,vardep=dataf[,vardep]) variss<-data.frame(mca1$quali.sup$coord) variss$Variable<-paste(".",vardep,sep="") mca1_vars_df1$tama<-4 # mca1_vars_df2$tama<-5 # uni<-rbind(mca1_vars_df1,mca1_vars_df2) uni<-mca1_vars_df1 uni$fontface<-ifelse(uni$Variable==vardep,2,1) uni$Variable<-as.character(uni$Variable) # SUPLEMENTARIA variss$dimf1<-variss[,c(Dime1)] variss$dimf2<-variss[,c(Dime2)] # AXES first<-as.numeric(substr(c(Dime1),5,5)) second<-as.numeric(substr(c(Dime2),5,5) ) ejex<-paste(Dime1,"(",trunc(mca1$eig[first,2]*10)/10,"%)",sep="") ejey<-paste(Dime2,"(",trunc(mca1$eig[second,2]*10)/10,"%)",sep="") # FREQ mca1_obs_df$minori<-ifelse(mca1_obs_df$vardep==minoritaria,1,0) mca1_obs_df$minori<-as.character(mca1_obs_df$minori) df<-mca1_obs_df df$dimf1<-df[,c(Dime1)] df$dimf2<-df[,c(Dime2)] uni$dimf1<-uni[,c(Dime1)] uni$dimf2<-uni[,c(Dime2)] au<-as.data.frame(count.dups(df)) au$Frecu<-au$N au$N<-NULL df<-inner_join(df,au, by = c("dimf1","dimf2")) cosa<-list(df,uni,dataf2,listconti,listclass,ejex,ejey,variss) names(cosa)<-c("df1","df2","df3","listconti","listclass","axisx","axisy","variss") return(cosa) }
/scratch/gouwar.j/cran-all/cranData/visualpred/R/mcamodelo.R
#' nba dataset #' @docType data #' @usage data(nba) #' @keywords datasets #' @source https://data.world/exercises/logistic-regression-exercise-1 "nba"
/scratch/gouwar.j/cran-all/cranData/visualpred/R/nba.R
#' Pima indian diabetes dataset #' @docType data #' @usage data(pima) #' @keywords datasets #' @source https://sci2s.ugr.es/keel/dataset.php?cod=21 "pima"
/scratch/gouwar.j/cran-all/cranData/visualpred/R/pima.R
#' spiral sample data #' @docType data #' @usage data(spiral) #' @keywords datasets "spiral"
/scratch/gouwar.j/cran-all/cranData/visualpred/R/spiral.R
## ----message=FALSE, echo=FALSE, warning=FALSE--------------------------------- knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7.71, dpi=100, results = "asis" ) ## ----------------------------------------------------------------------------- library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "lvr", "ccs","uria") listclass<-c("pbcr", "dmi", "self") vardep<-c("deny") dataf<-dataf[,c(listconti,listclass,vardep)] set.seed(123) train_ind <- sample(seq_len(nrow(Hmda)), size = 1700) train <- dataf[train_ind, ] test <- dataf[-train_ind, ] formu<-paste("factor(",vardep,")~.") model <- glm(formula(formu),family=binomial(link='logit'),data=train) proba<- predict(model,test,type="response") result<-famdcontour(dataf=test,listconti=listconti,listclass=listclass,vardep=vardep, proba=proba,title="Test Contour under GLM",title2=" ",selec=0,modelo="glm",classvar=0) result[[2]] ## ----------------------------------------------------------------------------- library(randomForest) model <- randomForest(formula(formu),data=train,mtry=4,nodesize=10,ntree=300) proba <- predict(model, test,type="prob") proba<-as.vector(proba[,2]) result<-famdcontour(dataf=test,listconti=listconti,listclass=listclass,vardep=vardep, proba=proba,title="Test Contour under Random Forest",title2=" ",Dime1="Dim.1",Dime2="Dim.2", selec=0,modelo="glm",classvar=0) result[[2]] ## ----------------------------------------------------------------------------- library(ggplot2) library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "lvr", "ccs","uria") listclass<-c("pbcr", "dmi", "self") vardep<-c("deny") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="",title2=" ",selec=0,modelo="glm",classvar=0,depcol=c("gold2","deeppink3")) result[[2]]+ ggtitle("Hmda data",subtitle="2380 obs")+theme( plot.title = element_text(hjust=0.5,color="darkorchid"), plot.subtitle= element_text(hjust=0.5,color="violet") ) ## ----------------------------------------------------------------------------- result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="Dim.1 and Dim.2",title2=" ",Dime1="Dim.1",Dime2="Dim.2", selec=0,modelo="glm",classvar=0) result[[4]] result[[5]] result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="Dim.3 and Dim.4",title2=" ",Dime1="Dim.3",Dime2="Dim.4", selec=0,modelo="glm",classvar=0) result[[4]] result[[5]]
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Advanced.R
--- title: "Advanced settings" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteIndexEntry{Advanced settings} %\usepackage[UTF-8]{inputenc} %\VignetteEngine{knitr::knitr} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7.71, dpi=100, results = "asis" ) ``` # Using external predictions External vector of probabilities can be used as base for contour and prediction plots. For example, one can use other algorithms, packages or other external sources to compute these probabilities and pass them through the 'proba' vector. Besides that, although basic function settings rely on fit and not on out-of-sample prediction, train and test predictions can also be represented. In the next example, data is splitted into train and test. Test predictions are obtained with model built with train data, and then incorporated to famdcontour function through 'proba' vector. Plot for test points is shown. If one wants to apply this procedure, caution is necessary: 1) Reduce dataset to input and vardep variables 2) verify the class predicted is the minority class within the predictive algorithm used 3) use selec=0 in famdcontour function to avoid further selection of variables 4) As algorithm need not to be applied in function famdcontour, use modelo="glm" 5) Using an external vector of probabilities requires that the order of observations in probability vector coincides with the order in the dataset passed to the famdcontour function. In the example, test data (same number of rows as proba) is passed to the famdcontour function. This setting can be altered using cross validation, for example, with caret package, using all data. ```{r} library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "lvr", "ccs","uria") listclass<-c("pbcr", "dmi", "self") vardep<-c("deny") dataf<-dataf[,c(listconti,listclass,vardep)] set.seed(123) train_ind <- sample(seq_len(nrow(Hmda)), size = 1700) train <- dataf[train_ind, ] test <- dataf[-train_ind, ] formu<-paste("factor(",vardep,")~.") model <- glm(formula(formu),family=binomial(link='logit'),data=train) proba<- predict(model,test,type="response") result<-famdcontour(dataf=test,listconti=listconti,listclass=listclass,vardep=vardep, proba=proba,title="Test Contour under GLM",title2=" ",selec=0,modelo="glm",classvar=0) result[[2]] ``` ```{r} library(randomForest) model <- randomForest(formula(formu),data=train,mtry=4,nodesize=10,ntree=300) proba <- predict(model, test,type="prob") proba<-as.vector(proba[,2]) result<-famdcontour(dataf=test,listconti=listconti,listclass=listclass,vardep=vardep, proba=proba,title="Test Contour under Random Forest",title2=" ",Dime1="Dim.1",Dime2="Dim.2", selec=0,modelo="glm",classvar=0) result[[2]] ``` # Colors and titles Dependent variable colors can be set in a vector named depcol where the first color corresponds to the majority class. Color schema for variables and categories can also be set in a vector named listacol. In this example dependent variable colors are changed. Also, title schema can be overwritten with usual ggplot settings. ```{r} library(ggplot2) library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "lvr", "ccs","uria") listclass<-c("pbcr", "dmi", "self") vardep<-c("deny") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="",title2=" ",selec=0,modelo="glm",classvar=0,depcol=c("gold2","deeppink3")) result[[2]]+ ggtitle("Hmda data",subtitle="2380 obs")+theme( plot.title = element_text(hjust=0.5,color="darkorchid"), plot.subtitle= element_text(hjust=0.5,color="violet") ) ``` # Plotting over selected dimensions Plot over other Dimensions built by famd or mca algorithms is allowed, as in the next example. ```{r} result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="Dim.1 and Dim.2",title2=" ",Dime1="Dim.1",Dime2="Dim.2", selec=0,modelo="glm",classvar=0) result[[4]] result[[5]] result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="Dim.3 and Dim.4",title2=" ",Dime1="Dim.3",Dime2="Dim.4", selec=0,modelo="glm",classvar=0) result[[4]] result[[5]] ```
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Advanced.Rmd
## ----message=FALSE, echo=FALSE, warning=FALSE--------------------------------- knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7.71, dpi=100, results = "asis" ) ## ----------------------------------------------------------------------------- library(visualpred) dataf<-breastwisconsin1 listconti=c( "clump_thickness","uniformity_of_cell_shape", "marginal_adhesion","bare_nuclei", "bland_chromatin", "normal_nucleoli", "mitosis") listclass=c("") vardep="classes" result<-famdcontour(dataf=dataf,listconti,listclass,vardep,title="FAMD Plots",selec=1) ## ----echo=F------------------------------------------------------------------- result[[1]] ## ----echo=F------------------------------------------------------------------- result[[2]] ## ----echo=F------------------------------------------------------------------- result[3] ## ----echo=F------------------------------------------------------------------- result[[4]] ## ----echo=F------------------------------------------------------------------- result[5] ## ----echo=F------------------------------------------------------------------- result[6] ## ----------------------------------------------------------------------------- library(visualpred) dataf<-pima listconti<-c("pregnant", "glucose", "pressure", "triceps", "insulin", "bodymass", "pedigree", "age") listclass<-c("") vardep<-"diabetes" resultfamd<-famdcontour(dataf=pima,listconti,listclass,vardep,title="FAMD",selec=1, alpha1=0.7,alpha2=0.7,proba="",modelo="glm") resultmca<-mcacontour(dataf=pima,listconti,listclass,vardep,title="MCA",proba="", modelo="glm",selec=1,alpha1=0.7,alpha2=0.7) ## ----echo=F------------------------------------------------------------------- resultfamd[[4]] ## ----echo=F------------------------------------------------------------------- resultmca[[4]] ## ----------------------------------------------------------------------------- library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "hir", "lvr", "ccs", "mcs", "uria") listclass<-c("pbcr", "dmi", "self", "single", "condominium", "black") vardep<-c("deny") resultfamd<-famdcontour(dataf=Hmda,listconti,listclass,vardep,title="FAMD",selec=1, alpha1=0.7,alpha2=0.7,proba="",modelo="glm") resultmca<-mcacontour(dataf=Hmda,listconti,listclass,vardep,title="MCA",proba="", modelo="glm",selec=1,alpha1=0.7,alpha2=0.7) ## ----echo=F------------------------------------------------------------------- resultfamd[[4]] resultmca[[4]]
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Basic_example.R
--- title: "visualpred package" author: "Javier Portela" date: "`r Sys.Date()`" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteIndexEntry{visualpred package} %\usepackage[UTF-8]{inputenc} %\VignetteEngine{knitr::knitr} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7.71, dpi=100, results = "asis" ) ``` # Basic example with FAMD Factorial Analysis for Mixed Data, applied to the space of input variables, is used to represent points in two dimensions. Points are colored based on dependent classification variable in order to reveal the discriminant power of input variables. 6 plots are generated. Contour plots are built from interpolation on a grid, departing from predicted probabilities for actual data. Some plots project interval input variable and categories of class variables. Other plots show fitted probabilities and absolute difference of fitted probability from real value of dependent variable coded to {0,1}. Logistic regression (glm) is used as default predicting algorithm. In this example a previous stepwise variable selection is performed (selec=1). By default selec=0. Order of plots shown is result[[1]], result[[2]], etc. ```{r} library(visualpred) dataf<-breastwisconsin1 listconti=c( "clump_thickness","uniformity_of_cell_shape", "marginal_adhesion","bare_nuclei", "bland_chromatin", "normal_nucleoli", "mitosis") listclass=c("") vardep="classes" result<-famdcontour(dataf=dataf,listconti,listclass,vardep,title="FAMD Plots",selec=1) ``` ```{r,echo=F} result[[1]] ``` The plot above shows observations projected on first chosen two FAMD dimensions. The plot reveals how input variables can discriminate between categories of the dependent class variable. ```{r,echo=F} result[[2]] ``` This plot above shows contour plot based on glm sample predicted probabilities . ```{r,echo=F} result[3] ``` This plot above is first plot adding interval input variables coordinates. ```{r,echo=F} result[[4]] ``` This plot above is second plot adding interval input variables coordinates. ```{r,echo=F} result[5] ``` This plot above shows fitted probabilities in color scale. ```{r,echo=F} result[6] ``` This plot above shows difference between dependent variable (categorized as 0,1) and predicted probabilities. # Differences between mcacontour and famdcontour In the next example a dataset with only interval input variables is used. Function mcacontour categorizes the input interval variables whereas famdcontour does not. It seems more appropriate to use famd, but interesting predictive clues are obtained in the mca variables plot. ```{r} library(visualpred) dataf<-pima listconti<-c("pregnant", "glucose", "pressure", "triceps", "insulin", "bodymass", "pedigree", "age") listclass<-c("") vardep<-"diabetes" resultfamd<-famdcontour(dataf=pima,listconti,listclass,vardep,title="FAMD",selec=1, alpha1=0.7,alpha2=0.7,proba="",modelo="glm") resultmca<-mcacontour(dataf=pima,listconti,listclass,vardep,title="MCA",proba="", modelo="glm",selec=1,alpha1=0.7,alpha2=0.7) ``` ```{r,echo=F} resultfamd[[4]] ``` Since there are only interval variables famd is able to represent a better point projections, where predictive contour curves are natural and clear . The projection of variable labels show their association with dependent class variable. ```{r,echo=F} resultmca[[4]] ``` Mca plot seems less informative about general contour model fit, but as interval variables are categorized (by default in 8 bins), it shows other interesting associations: pregnant variable=0 could be treated as a dummy category in itself. Also bodymass shows a non linear relationship for classification of the dependent variable. Insulin_0 (lower value of insulin bins) also seems to be a category of interest. None of these clues could be found in previous famd plot. # Dataset with both input class and interval variables ```{r} library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "hir", "lvr", "ccs", "mcs", "uria") listclass<-c("pbcr", "dmi", "self", "single", "condominium", "black") vardep<-c("deny") resultfamd<-famdcontour(dataf=Hmda,listconti,listclass,vardep,title="FAMD",selec=1, alpha1=0.7,alpha2=0.7,proba="",modelo="glm") resultmca<-mcacontour(dataf=Hmda,listconti,listclass,vardep,title="MCA",proba="", modelo="glm",selec=1,alpha1=0.7,alpha2=0.7) ``` ```{r,echo=F} resultfamd[[4]] resultmca[[4]] ```
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Basic_example.Rmd
## ----message=FALSE, echo=FALSE, warning=FALSE--------------------------------- knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 12, fig.width = 9, dpi=100, results = "asis" ) ## ----------------------------------------------------------------------------- require(egg) library(visualpred) dataf<-spiral listconti<-c("x1","x2") listclass<-c("") vardep<-"clase" result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="GLM",title2=" ",selec=0,modelo="glm",classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET",title2=" ",selec=0,modelo="nnet",classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="RF",title2=" ",selec=0,modelo="rf",classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="GBM",title2=" ",selec=0,modelo="gbm",classvar=0) g4<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep,title="SVM", title2=" ",selec=0,modelo="svm",classvar=0) g5<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,g5,ncol =2,nrow=3) ## ----echo=F------------------------------------------------------------------- require(egg) library(visualpred) dataf<-spiral listconti<-c("x1","x2") listclass<-c("") vardep<-"clase" result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 3,maxit=200,decay=0.01",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet", classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 10,maxit=1000,decay=0.001",title2=" ", Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=10,maxit=1000,decay=0.001, classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 15,maxit=2500,decay=0.0001",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=15, maxit=2500,decay=0.0001,classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 20,maxit=2500,decay=0.0001",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=25, maxit=2500,decay=0.0001,classvar=0) g4<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,ncol =2,nrow=2) ## ----echo=F------------------------------------------------------------------- require(egg) library(visualpred) dataf<-na.omit(nba) listconti<-c("GP", "MIN", "PTS", "FGM", "FGA", "FG", "P3Made", "P3A", "P3", "FTM", "FTA", "FT", "OREB", "DREB", "REB", "AST", "STL", "BLK", "TOV") listclass<-c("") vardep<-"TARGET_5Yrs" result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="GLM",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="glm",classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="nnet",classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="RF",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="rf",classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="GBM",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="gbm",classvar=0) g4<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,title="SVM", title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="svm",classvar=0) g5<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="SVM C=0.00001,gamma=0.00001", title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="svm",classvar=0,C=0.00001,gamma=0.00001) g6<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,g5,g6,ncol =2,nrow=3)
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Comparing.R
--- title: "Comparing algorithms" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Comparing algorithms} %\usepackage[UTF-8]{inputenc} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 12, fig.width = 9, dpi=100, results = "asis" ) ``` # Comparing algorithms Package visualpred can help to visualize at a glance the behaviour of different machine learning algorithms. As returned values are often ggplot objects, ggplot options can be used to remove legends. A title is given, and title2 is set to two blank spaces . Next plot shows the behaviour of different algorithms for classification. Although svm seems to be most accurate in this example, all algorithm parameters need some tuning. ```{r} require(egg) library(visualpred) dataf<-spiral listconti<-c("x1","x2") listclass<-c("") vardep<-"clase" result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="GLM",title2=" ",selec=0,modelo="glm",classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET",title2=" ",selec=0,modelo="nnet",classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="RF",title2=" ",selec=0,modelo="rf",classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="GBM",title2=" ",selec=0,modelo="gbm",classvar=0) g4<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep,title="SVM", title2=" ",selec=0,modelo="svm",classvar=0) g5<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,g5,ncol =2,nrow=3) ``` # Tuning representation Next plot illustrates the effects of different tuning settings for a neural network modeling of the spiral dataset. ```{r,echo=F} require(egg) library(visualpred) dataf<-spiral listconti<-c("x1","x2") listclass<-c("") vardep<-"clase" result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 3,maxit=200,decay=0.01",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet", classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 10,maxit=1000,decay=0.001",title2=" ", Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=10,maxit=1000,decay=0.001, classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 15,maxit=2500,decay=0.0001",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=15, maxit=2500,decay=0.0001,classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 20,maxit=2500,decay=0.0001",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=25, maxit=2500,decay=0.0001,classvar=0) g4<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,ncol =2,nrow=2) ``` # Real dataset fitting under different algorithms Next example applies the same schema to a real dataset. With default parameter values, SVM seems to overfit; other values are tried to avoid it but without success for this algorithm. ```{r,echo=F} require(egg) library(visualpred) dataf<-na.omit(nba) listconti<-c("GP", "MIN", "PTS", "FGM", "FGA", "FG", "P3Made", "P3A", "P3", "FTM", "FTA", "FT", "OREB", "DREB", "REB", "AST", "STL", "BLK", "TOV") listclass<-c("") vardep<-"TARGET_5Yrs" result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="GLM",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="glm",classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="nnet",classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="RF",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="rf",classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="GBM",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="gbm",classvar=0) g4<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,title="SVM", title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="svm",classvar=0) g5<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="SVM C=0.00001,gamma=0.00001", title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="svm",classvar=0,C=0.00001,gamma=0.00001) g6<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,g5,g6,ncol =2,nrow=3) ```
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Comparing.Rmd
## ----message=FALSE, echo=FALSE, warning=FALSE--------------------------------- knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 7, fig.width = 9, dpi=100, results = "asis" ) ## ----------------------------------------------------------------------------- library(visualpred) dataf<-na.omit(nba) listconti<-c("GP", "MIN", "PTS", "FGM", "FGA", "FG", "P3Made", "P3A", "P3", "FTM", "FTA", "FT", "OREB", "DREB", "REB", "AST", "STL", "BLK", "TOV") listclass<-c("") vardep<-"TARGET_5Yrs" result<-famdcontourlabel(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,Idt="name", title="Outliers in FAMD plots",title2="",selec=1,inf=0.001,sup=0.999,cutprob=0.9) ## ----echo=T------------------------------------------------------------------- result[[3]] ## ----echo=T------------------------------------------------------------------- result[[10]] result[[11]] result[[12]]
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Outliers.R
--- title: "Plotting outliers" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Plotting outliers} %\usepackage[UTF-8]{inputenc} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 7, fig.width = 9, dpi=100, results = "asis" ) ``` # Outliers with respect to plot dimensions In order to represent outliers, 12 plots are generated.These are the same plots as in the basic famd function, with labels for individuals that accomplish a cutpoint criteria. Idt is the label variable (Idt="" by default for row number). For outliers with respect to the two dimensions, inf and sup cutpoints are used. Next plot shows outliers with respect to Dim.1 and Dim.2 . It can be seen that there are players with special performance in some variables (DREB and REB for Shaquille O'Neal and David Robinson, for example). ```{r} library(visualpred) dataf<-na.omit(nba) listconti<-c("GP", "MIN", "PTS", "FGM", "FGA", "FG", "P3Made", "P3A", "P3", "FTM", "FTA", "FT", "OREB", "DREB", "REB", "AST", "STL", "BLK", "TOV") listclass<-c("") vardep<-"TARGET_5Yrs" result<-famdcontourlabel(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,Idt="name", title="Outliers in FAMD plots",title2="",selec=1,inf=0.001,sup=0.999,cutprob=0.9) ``` ```{r,echo=T} result[[3]] ``` # Outliers with respect to model fit For outliers with respect to model fit, the cutpoint cutprob for the difference between vardep value (in 0,1 scale) and probability estimate is used. Next plots show outliers with respect to model fit. Larry Johnson is fitted with high probability to green class (>5 years),but he really belongs to the red class (<5 years). Package visualpred allways codes as red the minority class; in this dataset this is TARGET_5Yrs=0. ```{r,echo=T} result[[10]] result[[11]] result[[12]] ```
/scratch/gouwar.j/cran-all/cranData/visualpred/inst/doc/Outliers.Rmd
--- title: "Advanced settings" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteIndexEntry{Advanced settings} %\usepackage[UTF-8]{inputenc} %\VignetteEngine{knitr::knitr} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7.71, dpi=100, results = "asis" ) ``` # Using external predictions External vector of probabilities can be used as base for contour and prediction plots. For example, one can use other algorithms, packages or other external sources to compute these probabilities and pass them through the 'proba' vector. Besides that, although basic function settings rely on fit and not on out-of-sample prediction, train and test predictions can also be represented. In the next example, data is splitted into train and test. Test predictions are obtained with model built with train data, and then incorporated to famdcontour function through 'proba' vector. Plot for test points is shown. If one wants to apply this procedure, caution is necessary: 1) Reduce dataset to input and vardep variables 2) verify the class predicted is the minority class within the predictive algorithm used 3) use selec=0 in famdcontour function to avoid further selection of variables 4) As algorithm need not to be applied in function famdcontour, use modelo="glm" 5) Using an external vector of probabilities requires that the order of observations in probability vector coincides with the order in the dataset passed to the famdcontour function. In the example, test data (same number of rows as proba) is passed to the famdcontour function. This setting can be altered using cross validation, for example, with caret package, using all data. ```{r} library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "lvr", "ccs","uria") listclass<-c("pbcr", "dmi", "self") vardep<-c("deny") dataf<-dataf[,c(listconti,listclass,vardep)] set.seed(123) train_ind <- sample(seq_len(nrow(Hmda)), size = 1700) train <- dataf[train_ind, ] test <- dataf[-train_ind, ] formu<-paste("factor(",vardep,")~.") model <- glm(formula(formu),family=binomial(link='logit'),data=train) proba<- predict(model,test,type="response") result<-famdcontour(dataf=test,listconti=listconti,listclass=listclass,vardep=vardep, proba=proba,title="Test Contour under GLM",title2=" ",selec=0,modelo="glm",classvar=0) result[[2]] ``` ```{r} library(randomForest) model <- randomForest(formula(formu),data=train,mtry=4,nodesize=10,ntree=300) proba <- predict(model, test,type="prob") proba<-as.vector(proba[,2]) result<-famdcontour(dataf=test,listconti=listconti,listclass=listclass,vardep=vardep, proba=proba,title="Test Contour under Random Forest",title2=" ",Dime1="Dim.1",Dime2="Dim.2", selec=0,modelo="glm",classvar=0) result[[2]] ``` # Colors and titles Dependent variable colors can be set in a vector named depcol where the first color corresponds to the majority class. Color schema for variables and categories can also be set in a vector named listacol. In this example dependent variable colors are changed. Also, title schema can be overwritten with usual ggplot settings. ```{r} library(ggplot2) library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "lvr", "ccs","uria") listclass<-c("pbcr", "dmi", "self") vardep<-c("deny") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="",title2=" ",selec=0,modelo="glm",classvar=0,depcol=c("gold2","deeppink3")) result[[2]]+ ggtitle("Hmda data",subtitle="2380 obs")+theme( plot.title = element_text(hjust=0.5,color="darkorchid"), plot.subtitle= element_text(hjust=0.5,color="violet") ) ``` # Plotting over selected dimensions Plot over other Dimensions built by famd or mca algorithms is allowed, as in the next example. ```{r} result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="Dim.1 and Dim.2",title2=" ",Dime1="Dim.1",Dime2="Dim.2", selec=0,modelo="glm",classvar=0) result[[4]] result[[5]] result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="Dim.3 and Dim.4",title2=" ",Dime1="Dim.3",Dime2="Dim.4", selec=0,modelo="glm",classvar=0) result[[4]] result[[5]] ```
/scratch/gouwar.j/cran-all/cranData/visualpred/vignettes/Advanced.Rmd
--- title: "visualpred package" author: "Javier Portela" date: "`r Sys.Date()`" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteIndexEntry{visualpred package} %\usepackage[UTF-8]{inputenc} %\VignetteEngine{knitr::knitr} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7.71, dpi=100, results = "asis" ) ``` # Basic example with FAMD Factorial Analysis for Mixed Data, applied to the space of input variables, is used to represent points in two dimensions. Points are colored based on dependent classification variable in order to reveal the discriminant power of input variables. 6 plots are generated. Contour plots are built from interpolation on a grid, departing from predicted probabilities for actual data. Some plots project interval input variable and categories of class variables. Other plots show fitted probabilities and absolute difference of fitted probability from real value of dependent variable coded to {0,1}. Logistic regression (glm) is used as default predicting algorithm. In this example a previous stepwise variable selection is performed (selec=1). By default selec=0. Order of plots shown is result[[1]], result[[2]], etc. ```{r} library(visualpred) dataf<-breastwisconsin1 listconti=c( "clump_thickness","uniformity_of_cell_shape", "marginal_adhesion","bare_nuclei", "bland_chromatin", "normal_nucleoli", "mitosis") listclass=c("") vardep="classes" result<-famdcontour(dataf=dataf,listconti,listclass,vardep,title="FAMD Plots",selec=1) ``` ```{r,echo=F} result[[1]] ``` The plot above shows observations projected on first chosen two FAMD dimensions. The plot reveals how input variables can discriminate between categories of the dependent class variable. ```{r,echo=F} result[[2]] ``` This plot above shows contour plot based on glm sample predicted probabilities . ```{r,echo=F} result[3] ``` This plot above is first plot adding interval input variables coordinates. ```{r,echo=F} result[[4]] ``` This plot above is second plot adding interval input variables coordinates. ```{r,echo=F} result[5] ``` This plot above shows fitted probabilities in color scale. ```{r,echo=F} result[6] ``` This plot above shows difference between dependent variable (categorized as 0,1) and predicted probabilities. # Differences between mcacontour and famdcontour In the next example a dataset with only interval input variables is used. Function mcacontour categorizes the input interval variables whereas famdcontour does not. It seems more appropriate to use famd, but interesting predictive clues are obtained in the mca variables plot. ```{r} library(visualpred) dataf<-pima listconti<-c("pregnant", "glucose", "pressure", "triceps", "insulin", "bodymass", "pedigree", "age") listclass<-c("") vardep<-"diabetes" resultfamd<-famdcontour(dataf=pima,listconti,listclass,vardep,title="FAMD",selec=1, alpha1=0.7,alpha2=0.7,proba="",modelo="glm") resultmca<-mcacontour(dataf=pima,listconti,listclass,vardep,title="MCA",proba="", modelo="glm",selec=1,alpha1=0.7,alpha2=0.7) ``` ```{r,echo=F} resultfamd[[4]] ``` Since there are only interval variables famd is able to represent a better point projections, where predictive contour curves are natural and clear . The projection of variable labels show their association with dependent class variable. ```{r,echo=F} resultmca[[4]] ``` Mca plot seems less informative about general contour model fit, but as interval variables are categorized (by default in 8 bins), it shows other interesting associations: pregnant variable=0 could be treated as a dummy category in itself. Also bodymass shows a non linear relationship for classification of the dependent variable. Insulin_0 (lower value of insulin bins) also seems to be a category of interest. None of these clues could be found in previous famd plot. # Dataset with both input class and interval variables ```{r} library(visualpred) dataf<-na.omit(Hmda) listconti<-c("dir", "hir", "lvr", "ccs", "mcs", "uria") listclass<-c("pbcr", "dmi", "self", "single", "condominium", "black") vardep<-c("deny") resultfamd<-famdcontour(dataf=Hmda,listconti,listclass,vardep,title="FAMD",selec=1, alpha1=0.7,alpha2=0.7,proba="",modelo="glm") resultmca<-mcacontour(dataf=Hmda,listconti,listclass,vardep,title="MCA",proba="", modelo="glm",selec=1,alpha1=0.7,alpha2=0.7) ``` ```{r,echo=F} resultfamd[[4]] resultmca[[4]] ```
/scratch/gouwar.j/cran-all/cranData/visualpred/vignettes/Basic_example.Rmd
--- title: "Comparing algorithms" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Comparing algorithms} %\usepackage[UTF-8]{inputenc} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 12, fig.width = 9, dpi=100, results = "asis" ) ``` # Comparing algorithms Package visualpred can help to visualize at a glance the behaviour of different machine learning algorithms. As returned values are often ggplot objects, ggplot options can be used to remove legends. A title is given, and title2 is set to two blank spaces . Next plot shows the behaviour of different algorithms for classification. Although svm seems to be most accurate in this example, all algorithm parameters need some tuning. ```{r} require(egg) library(visualpred) dataf<-spiral listconti<-c("x1","x2") listclass<-c("") vardep<-"clase" result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="GLM",title2=" ",selec=0,modelo="glm",classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET",title2=" ",selec=0,modelo="nnet",classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="RF",title2=" ",selec=0,modelo="rf",classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="GBM",title2=" ",selec=0,modelo="gbm",classvar=0) g4<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep,title="SVM", title2=" ",selec=0,modelo="svm",classvar=0) g5<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,g5,ncol =2,nrow=3) ``` # Tuning representation Next plot illustrates the effects of different tuning settings for a neural network modeling of the spiral dataset. ```{r,echo=F} require(egg) library(visualpred) dataf<-spiral listconti<-c("x1","x2") listclass<-c("") vardep<-"clase" result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 3,maxit=200,decay=0.01",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet", classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 10,maxit=1000,decay=0.001",title2=" ", Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=10,maxit=1000,decay=0.001, classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 15,maxit=2500,decay=0.0001",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=15, maxit=2500,decay=0.0001,classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=spiral,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET 20,maxit=2500,decay=0.0001",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=0,modelo="nnet",nodos=25, maxit=2500,decay=0.0001,classvar=0) g4<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,ncol =2,nrow=2) ``` # Real dataset fitting under different algorithms Next example applies the same schema to a real dataset. With default parameter values, SVM seems to overfit; other values are tried to avoid it but without success for this algorithm. ```{r,echo=F} require(egg) library(visualpred) dataf<-na.omit(nba) listconti<-c("GP", "MIN", "PTS", "FGM", "FGA", "FG", "P3Made", "P3A", "P3", "FTM", "FTA", "FT", "OREB", "DREB", "REB", "AST", "STL", "BLK", "TOV") listclass<-c("") vardep<-"TARGET_5Yrs" result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="GLM",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="glm",classvar=0) g1<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="NNET",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="nnet",classvar=0) g2<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="RF",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="rf",classvar=0) g3<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="GBM",title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="gbm",classvar=0) g4<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,title="SVM", title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="svm",classvar=0) g5<-result[[2]]+theme(legend.position = "none") result<-famdcontour(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep, title="SVM C=0.00001,gamma=0.00001", title2=" ",Dime1="Dim.1",Dime2="Dim.2",selec=1,modelo="svm",classvar=0,C=0.00001,gamma=0.00001) g6<-result[[2]]+theme(legend.position = "none") ggarrange(g1,g2,g3,g4,g5,g6,ncol =2,nrow=3) ```
/scratch/gouwar.j/cran-all/cranData/visualpred/vignettes/Comparing.Rmd
--- title: "Plotting outliers" output: html_document: df_print: paged prettydoc::html_pretty: theme: cayman highlight: github vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Plotting outliers} %\usepackage[UTF-8]{inputenc} --- ```{r message=FALSE, echo=FALSE, warning=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE, fig.height = 7, fig.width = 9, dpi=100, results = "asis" ) ``` # Outliers with respect to plot dimensions In order to represent outliers, 12 plots are generated.These are the same plots as in the basic famd function, with labels for individuals that accomplish a cutpoint criteria. Idt is the label variable (Idt="" by default for row number). For outliers with respect to the two dimensions, inf and sup cutpoints are used. Next plot shows outliers with respect to Dim.1 and Dim.2 . It can be seen that there are players with special performance in some variables (DREB and REB for Shaquille O'Neal and David Robinson, for example). ```{r} library(visualpred) dataf<-na.omit(nba) listconti<-c("GP", "MIN", "PTS", "FGM", "FGA", "FG", "P3Made", "P3A", "P3", "FTM", "FTA", "FT", "OREB", "DREB", "REB", "AST", "STL", "BLK", "TOV") listclass<-c("") vardep<-"TARGET_5Yrs" result<-famdcontourlabel(dataf=dataf,listconti=listconti,listclass=listclass,vardep=vardep,Idt="name", title="Outliers in FAMD plots",title2="",selec=1,inf=0.001,sup=0.999,cutprob=0.9) ``` ```{r,echo=T} result[[3]] ``` # Outliers with respect to model fit For outliers with respect to model fit, the cutpoint cutprob for the difference between vardep value (in 0,1 scale) and probability estimate is used. Next plots show outliers with respect to model fit. Larry Johnson is fitted with high probability to green class (>5 years),but he really belongs to the red class (<5 years). Package visualpred allways codes as red the minority class; in this dataset this is TARGET_5Yrs=0. ```{r,echo=T} result[[10]] result[[11]] result[[12]] ```
/scratch/gouwar.j/cran-all/cranData/visualpred/vignettes/Outliers.Rmd
#' @name #' visvow #' #' @title #' Visible Vowels #' #' @aliases #' visvow #' #' @description #' Visible Vowels is an app that visualizes vowel variation in f0, F1, F2, F3 and duration. #' #' A vowel is a speech sound produced without audible impediment to the airflow in the mouth and/or throat. #' Each vowel has a particular pitch (except when whispered), quality (timbre) and duration. #' f0 is the fundamental frequency of the periodic waveform and determines the perceived pitch. #' The quality is determined by the formants. #' Formants are resonance frequencies that define the spectral shape of vowels (and vowel-like sounds). #' The formant with the lowest frequency is called F1, the second-lowest F2, and the third F3. #' F1 is correlated with tongue height. #' The closer the tongue approaches the palate, the lower F1. #' F2 correlates with tongue retraction and lip protrusion. #' The more the tongue is positioned towards the front of the mouth, and the wider the lips are spread, the higher F2. #' F3 correlates with the tongue-blade position. #' The closer the blade is to the lips, the higher is F3. #' The acoustic vowel duration primarily corresponds with the perceived duration of a vowel sound. #' See Johnson (2012). #' #' @usage #' visvow() #' #' @format #' NULL #' #' @details #' \code{visvow()} opens Visible Vowels in your default web browser. #' #' @seealso #' The Help tab in the app provides more information about the format of the input file. #' Details about scale conversion and speaker normalization procedures and some specific metrics are found in the vignette. #' #' @references #' \insertRef{johnson:2012}{visvow} #' #' @import #' shiny shinyBS tidyr PBSmapping ggplot2 plot3D MASS ggdendro ggrepel readxl WriteXLS pracma Rtsne grid svglite Cairo tikzDevice shinybusy #' #' @importFrom #' stats sd predict aov manova #' #' @importFrom #' formattable renderFormattable formattable formatter style color_tile formattableOutput #' #' @importFrom #' splitstackshape expandRows #' #' @importFrom #' plyr . #' #' @importFrom #' effectsize eta_squared #' #' @importFrom #' vegan adonis2 #' #' @importFrom #' Rdpack reprompt #' #' @export #' visvow NULL ################################################################################ Scale <- function(h,replyScale,Ref) { if (replyScale==" Hz") { s <- h } if (replyScale==" bark I") { s = 7*log(h/650+sqrt(1+(h/650)^2)) } if (replyScale==" bark II") { s = 13 * atan(0.00076*h) + 3.5 * atan((h/7500)^2) } if (replyScale==" bark III") { s <- (26.81 * (h/(1960+h))) - 0.53 s[which(s< 2 )] <- s[which(s< 2 )] + (0.15 * (2-s[which(s< 2 )] )) s[which(s>20.1)] <- s[which(s>20.1)] + (0.22 * ( s[which(s>20.1)]-20.1)) } if (replyScale==" ERB I") { s <- 16.7 * log10(1 + (h/165.4)) } if (replyScale==" ERB II") { s <- 11.17 * log((h+312) / (h+14675)) + 43 } if (replyScale==" ERB III") { s <- 21.4 * log10((0.00437*h)+1) } if (replyScale==" ln") { s <- log(h) } if (replyScale==" mel I") { s <- (1000/log10(2)) * log10((h/1000) + 1) } if (replyScale==" mel II") { s <- 1127 * log(1 + (h/700)) } if (replyScale==" ST") { s <- 12 * log2(h/Ref) } return(s) } vowelScale <- function(vowelTab, replyScale, Ref) { if (is.null(vowelTab)) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab)) nColumns <- ncol(vowelTab) nPoints <- (nColumns - (indexVowel + 1))/5 vT <- vowelTab for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in ((indexTime+1):(indexTime+4))) { vT[,j] <- Scale(vT[,j],replyScale, Ref) } } return(vT) } ################################################################################ vowelLong1 <- function(vowelScale,replyTimesN) { indexVowel <- grep("^vowel$", colnames(vowelScale)) nColumns <- ncol(vowelScale) nPoints <- (nColumns - (indexVowel + 1))/5 vT <- data.frame() for (i in (1:nPoints)) { if (is.element(as.character(i),replyTimesN)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub <- data.frame(speaker = vowelScale[,1], vowel = vowelScale[,indexVowel], point = i, f0 = vowelScale[,indexTime+1], f1 = vowelScale[,indexTime+2], f2 = vowelScale[,indexTime+3], f3 = vowelScale[,indexTime+4]) vT <- rbind(vT,vTsub) } } return(vT) } vowelLong2 <- function(vowelLong1) { vT <- data.frame() for (j in (1:2)) { vTsub <- data.frame(speaker = vowelLong1$speaker, vowel = vowelLong1$vowel, point = vowelLong1$point, formant = j, f = log(vowelLong1[,j+4])) if (all(is.infinite(vTsub$f))) vTsub$f <- 0 vT <- rbind(vT,vTsub) } return(vT) } vowelLong3 <- function(vowelLong1) { vT <- data.frame() for (j in (1:3)) { vTsub <- data.frame(speaker = as.factor(vowelLong1$speaker), vowel = as.factor(vowelLong1$vowel), point = as.factor(vowelLong1$point), formant = as.factor(j), f = log(vowelLong1[,j+4])) if (all(is.infinite(vTsub$f))) vTsub$f <- 0 vT <- rbind(vT,vTsub) } return(vT) } vowelLong4 <- function(vowelLong1) { vT <- data.frame() for (j in (0:3)) { vTsub <- data.frame(speaker = as.factor(vowelLong1$speaker), vowel = as.factor(vowelLong1$vowel), point = as.factor(vowelLong1$point), formant = as.factor(j), f = log(vowelLong1[,j+4])) if (all(is.infinite(vTsub$f))) vTsub$f <- 0 vT <- rbind(vT,vTsub) } return(vT) } vowelLongD <- function(vowelLong1) { vT <- data.frame() for (j in (1:3)) { vTsub <- data.frame(speaker = vowelLong1$speaker, vowel = vowelLong1$vowel, point = vowelLong1$point, formant = j, f = vowelLong1[,j+4]) vT <- rbind(vT,vTsub) } return(vT) } vowelNormF <- function(vowelScale,vowelLong1,vowelLong2,vowelLong3,vowelLong4,vowelLongD,replyNormal) { if (is.null(vowelScale)) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelScale)) nColumns <- ncol(vowelScale) nPoints <- (nColumns - (indexVowel + 1))/5 SpeaKer <- unique(vowelScale[,1]) nSpeaKer <- length(SpeaKer) VoWel <- unique(vowelScale[,indexVowel]) nVoWel <- length(VoWel) if (replyNormal=="") { vT <- vowelScale } if (replyNormal==" Peterson") { vT <- vowelScale for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vT[,indexTime+1] <- vT[,indexTime+1]/vT[,indexTime+4] vT[,indexTime+2] <- vT[,indexTime+2]/vT[,indexTime+4] vT[,indexTime+3] <- vT[,indexTime+3]/vT[,indexTime+4] } } if (replyNormal==" Sussman") { vT <- vowelScale for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) F123 <- apply(vT[, indexTime+2:4], 1, psych::geometric.mean) vT[,indexTime+2] <- log(vT[,indexTime+2]/F123) vT[,indexTime+3] <- log(vT[,indexTime+3]/F123) vT[,indexTime+4] <- log(vT[,indexTime+4]/F123) } } if (replyNormal==" Syrdal & Gopal") { vT <- vowelScale for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vT[,indexTime+2] <- 1 * (vT[,indexTime+2] - vT[,indexTime+1]) vT[,indexTime+3] <- -1 * (vT[,indexTime+4] - vT[,indexTime+3]) } } if (replyNormal==" Miller") { vT <- data.frame() vTLong1Ag <- stats::aggregate(f0~speaker+vowel+point, data=vowelLong1, FUN=psych::geometric.mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) GMf0 <- psych::geometric.mean(vTLong1AgSub$f0) SR <- 168*((GMf0/168)^(1/3)) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub[,indexTime+4] <- log(vTsub[,indexTime+4] / vTsub[,indexTime+3]) vTsub[,indexTime+3] <- log(vTsub[,indexTime+3] / vTsub[,indexTime+2]) vTsub[,indexTime+2] <- log(vTsub[,indexTime+2] / SR) } vT <- rbind(vT,vTsub) } } if (replyNormal==" Thomas & Kendall") { vT <- vowelScale for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vT[,indexTime+1] <- -1 * (vT[,indexTime+4] - vT[,indexTime+1]) vT[,indexTime+2] <- -1 * (vT[,indexTime+4] - vT[,indexTime+2]) vT[,indexTime+3] <- -1 * (vT[,indexTime+4] - vT[,indexTime+3]) } } if (replyNormal==" Gerstman") { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel , data=vTLong1Ag , FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) minF <- rep(0,4) maxF <- rep(0,4) for (j in 1:4) { minF[j] <- min(vTLong1AgSub[,j+2]) maxF[j] <- max(vTLong1AgSub[,j+2]) } vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (1:4)) { vTsub[,j+indexTime] <- 999 * ((vTsub[,j+indexTime]-minF[j]) / (maxF[j]-minF[j])) } } vT <- rbind(vT,vTsub) } } if ((replyNormal==" Lobanov") & (nVoWel==1)) { vT <- data.frame() vTLong1Ag <- vowelLong1 for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) meanF <- rep(0,4) sdF <- rep(0,4) for (j in 1:4) { meanF[j] <- mean(vTLong1AgSub[,j+3]) sdF[j] <- stats::sd(vTLong1AgSub[,j+3]) } vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (1:4)) { vTsub[,j+indexTime] <- (vTsub[,j+indexTime]-meanF[j])/sdF[j] } } vT <- rbind(vT,vTsub) } } if ((replyNormal==" Lobanov") & (nVoWel> 1)) { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) meanF <- rep(0,4) sdF <- rep(0,4) for (j in 1:4) { meanF[j] <- mean(vTLong1AgSub[,j+3]) sdF[j] <- stats::sd(vTLong1AgSub[,j+3]) } vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (1:4)) { vTsub[,j+indexTime] <- (vTsub[,j+indexTime]-meanF[j])/sdF[j] } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Watt & Fabricius") { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) vowelF1 <- stats::aggregate(f1~vowel, data=vTLong1AgSub, FUN=mean) vowelF2 <- stats::aggregate(f2~vowel, data=vTLong1AgSub, FUN=mean) iF1 <- min(vowelF1$f1) iF2 <- max(vowelF2$f2) uF1 <- min(vowelF1$f1) uF2 <- min(vowelF1$f1) aF1 <- max(vowelF1$f1) aF2 <- vowelF2$f2[which(vowelF1$f1 == aF1)] centroidF1 <- (iF1 + uF1 + aF1)/3 centroidF2 <- (iF2 + uF2 + aF2)/3 vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub[,indexTime+2] <- vTsub[,indexTime+2] / centroidF1 vTsub[,indexTime+3] <- vTsub[,indexTime+3] / centroidF2 } vT <- rbind(vT,vTsub) } } if (replyNormal==" Fabricius et al.") { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) vowelF1 <- stats::aggregate(f1~vowel, data=vTLong1AgSub, FUN=mean) vowelF2 <- stats::aggregate(f2~vowel, data=vTLong1AgSub, FUN=mean) iF1 <- min(vowelF1$f1) iF2 <- max(vowelF2$f2) uF1 <- min(vowelF1$f1) uF2 <- min(vowelF1$f1) aF1 <- max(vowelF1$f1) centroidF1 <- (iF1 + uF1 + aF1)/3 centroidF2 <- (iF2 + uF2 )/2 vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub[,indexTime+2] <- vTsub[,indexTime+2] / centroidF1 vTsub[,indexTime+3] <- vTsub[,indexTime+3] / centroidF2 } vT <- rbind(vT,vTsub) } } if (replyNormal==" Bigham") { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) vowelF1 <- stats::aggregate(f1~vowel, data=vTLong1AgSub, FUN=mean) vowelF2 <- stats::aggregate(f2~vowel, data=vTLong1AgSub, FUN=mean) iF1 <- min(vowelF1$f1) iF2 <- max(vowelF2$f2) uF1 <- min(vowelF1$f1) uF2 <- min(vowelF2$f2) oF1 <- max(vowelF1$f1) oF2 <- min(vowelF2$f2) aF1 <- max(vowelF1$f1) index <- which(vowelF2$vowel == intToUtf8("0x00E6")) if (!length(index)) index <- which(vowelF2$vowel == paste0(intToUtf8("0x00E6"), intToUtf8("0x02D1"))) if (!length(index)) index <- which(vowelF2$vowel == paste0(intToUtf8("0x00E6"), intToUtf8("0x02D0"))) if (!length(index)) index <- which(vowelF2$vowel == intToUtf8("0x0061")) if (!length(index)) index <- which(vowelF2$vowel == paste0(intToUtf8("0x0061"), intToUtf8("0x02D1"))) if (!length(index)) index <- which(vowelF2$vowel == paste0(intToUtf8("0x0061"), intToUtf8("0x02D0"))) if (!length(index)) index <- which(vowelF2$vowel == intToUtf8("0x025B")) if (!length(index)) index <- which(vowelF2$vowel == paste0(intToUtf8("0x025B"), intToUtf8("0x02D1"))) if (!length(index)) index <- which(vowelF2$vowel == paste0(intToUtf8("0x025B"), intToUtf8("0x02D0"))) aF2 <- vowelF2$f2[index] centroidF1 <- (iF1 + uF1 + oF1 + aF1)/4 centroidF2 <- (iF2 + uF2 + oF2 + aF2)/4 vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub[,indexTime+2] <- vTsub[,indexTime+2] / centroidF1 vTsub[,indexTime+3] <- vTsub[,indexTime+3] / centroidF2 } vT <- rbind(vT,vTsub) } } if (replyNormal==" Heeringa & Van de Velde I") { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) vowelF1 <- stats::aggregate(f1~vowel, data=vTLong1AgSub, FUN=mean) vowelF2 <- stats::aggregate(f2~vowel, data=vTLong1AgSub, FUN=mean) k <- grDevices::chull(vowelF1$f1,vowelF2$f2) xx <- vowelF1$f1[k] xx[length(xx)+1] <- xx[1] yy <- vowelF2$f2[k] yy[length(yy)+1] <- yy[1] if ((length(xx)>=3) & (length(yy)>=3)) pc <- pracma::poly_center(xx,yy) else pc <- c(mean(xx),mean(yy)) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub[,indexTime+2] <- vTsub[,indexTime+2]/pc[1] vTsub[,indexTime+3] <- vTsub[,indexTime+3]/pc[2] } vT <- rbind(vT,vTsub) } } if (replyNormal==" Heeringa & Van de Velde II") { vT <- data.frame() vTLong1Ag <- stats::aggregate(cbind(f0,f1,f2,f3)~speaker+vowel+point, data=vowelLong1, FUN=mean) for (q in (1:nSpeaKer)) { vTLong1AgSub <- subset(vTLong1Ag, speaker==SpeaKer[q]) vowelF1 <- stats::aggregate(f1~vowel, data=vTLong1AgSub, FUN=mean) vowelF2 <- stats::aggregate(f2~vowel, data=vTLong1AgSub, FUN=mean) k <- grDevices::chull(vowelF1$f1,vowelF2$f2) xx <- vowelF1$f1[k] xx[length(xx)+1] <- xx[1] yy <- vowelF2$f2[k] yy[length(yy)+1] <- yy[1] if ((length(xx)>=3) & (length(yy)>=3)) pc <- pracma::poly_center(xx,yy) else pc <- c(mean(vowelF1$f1[k]),mean(vowelF2$f2[k])) xxi <- stats::approx(1:length(xx), xx, n = 1000)$y yyi <- stats::approx(1:length(yy), yy, n = 1000)$y xxi <- xxi[1:(length(xxi)-1)] yyi <- yyi[1:(length(yyi)-1)] xxg <- cut(xxi, breaks=10) yyg <- cut(yyi, breaks=10) ag <- stats::aggregate(cbind(xxi,yyi)~xxg+yyg, FUN=mean) mean1 <- mean(ag$xxi) mean2 <- mean(ag$yyi) sd1 <- stats::sd(ag$xxi) sd2 <- stats::sd(ag$yyi) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) vTsub[,indexTime+2] <- (vTsub[,indexTime+2]-pc[1])/sd1 vTsub[,indexTime+3] <- (vTsub[,indexTime+3]-pc[2])/sd2 } vT <- rbind(vT,vTsub) } } if (replyNormal==" Nearey I") { vT <- data.frame() vTLong3Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong4, FUN=mean) for (q in (1:nSpeaKer)) { vTLong3AgSub <- subset(vTLong3Ag, speaker==SpeaKer[q]) speakerMean <- stats::aggregate(f~formant, data=vTLong3AgSub, FUN=mean) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (1:4)) { vTsub[,j+indexTime] <- log(vTsub[,j+indexTime]) - speakerMean$f[j] } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Nearey II") { vT <- data.frame() vTLong3Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong3, FUN=mean) for (q in (1:nSpeaKer)) { vTLong3AgSub <- subset(vTLong3Ag, speaker==SpeaKer[q]) speakerMean <- mean(vTLong3AgSub$f) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:4)) { vTsub[,j+indexTime] <- log(vTsub[,j+indexTime]) - speakerMean } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Barreda & Nearey I") { vTLong3Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong4, FUN=mean) S <- list() for (i in 0:3) { vTLong3AgSub <- subset(vTLong3Ag, vTLong3Ag$formant==i) N <- factor(interaction(vTLong3AgSub$vowel,vTLong3AgSub$point)) M <- stats::lm(f~0+speaker+N, contrasts = list(N=stats::contr.sum), data = vTLong3AgSub) S[[i+1]] <- as.data.frame(stats::dummy.coef(M)$speaker) } vT <- data.frame() for (q in (1:nSpeaKer)) { vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (1:4)) { speakerMeanR <- S[[j]][rownames(S[[j]])==SpeaKer[q],1] vTsub[,j+indexTime] <- log(vTsub[,j+indexTime]) - speakerMeanR } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Barreda & Nearey II") { vTLong3Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong3, FUN=mean) N <- factor(interaction(vTLong3Ag$vowel,vTLong3Ag$point,vTLong3Ag$formant)) M <- stats::lm(f~0+speaker+N, contrasts = list(N=stats::contr.sum), data = vTLong3Ag) S <- as.data.frame(stats::dummy.coef(M)$speaker) vT <- data.frame() for (q in (1:nSpeaKer)) { speakerMeanR <- S[rownames(S)==SpeaKer[q],1] vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:4)) { vTsub[,j+indexTime] <- log(vTsub[,j+indexTime]) - speakerMeanR } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Labov I") { vT <- data.frame() vTLong2Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong2, FUN=mean) grandMean <- mean(vTLong2Ag$f) for (q in (1:nSpeaKer)) { vTLong2AgSub <- subset(vTLong2Ag, speaker==SpeaKer[q]) speakerMean <- psych::geometric.mean(vTLong2AgSub$f) speakerFactor <- exp(grandMean - speakerMean) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:3)) { vTsub[,j+indexTime] <- speakerFactor * vTsub[,j+indexTime] } } vT <- rbind(vT,vTsub) } } if (replyNormal==" LABOV I") { vT <- data.frame() vTLong2Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong2, FUN=psych::geometric.mean) grandMean <- psych::geometric.mean(vTLong2Ag$f) for (q in (1:nSpeaKer)) { vTLong2AgSub <- subset(vTLong2Ag, speaker==SpeaKer[q]) speakerMean <- psych::geometric.mean(vTLong2AgSub$f) speakerFactor <- exp(grandMean - speakerMean) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:3)) { vTsub[,j+indexTime] <- speakerFactor * vTsub[,j+indexTime] } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Labov II") { vT <- data.frame() vTLong3Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong3, FUN=mean) grandMean <- mean(vTLong3Ag$f) for (q in (1:nSpeaKer)) { vTLong3AgSub <- subset(vTLong3Ag, speaker==SpeaKer[q]) speakerMean <- psych::geometric.mean(vTLong3AgSub$f) speakerFactor <- exp(grandMean - speakerMean) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:4)) { vTsub[,j+indexTime] <- speakerFactor * vTsub[,j+indexTime] } } vT <- rbind(vT,vTsub) } } if (replyNormal==" LABOV II") { vT <- data.frame() vTLong3Ag <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLong3, FUN=psych::geometric.mean) grandMean <- psych::geometric.mean(vTLong3Ag$f) for (q in (1:nSpeaKer)) { vTLong3AgSub <- subset(vTLong3Ag, speaker==SpeaKer[q]) speakerMean <- psych::geometric.mean(vTLong3AgSub$f) speakerFactor <- exp(grandMean - speakerMean) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:4)) { vTsub[,j+indexTime] <- speakerFactor * vTsub[,j+indexTime] } } vT <- rbind(vT,vTsub) } } if (replyNormal==" Johnson") { vT <- data.frame() vTLongDAg <- stats::aggregate(f~speaker+vowel+point+formant, data=vowelLongD, FUN=mean) for (q in (1:nSpeaKer)) { vTLongDAgSub <- subset(vTLongDAg, speaker==SpeaKer[q]) deltaF <- mean(vTLongDAgSub$f/(vTLongDAgSub$formant - 0.5)) vTsub <- subset(vowelScale, vowelScale[,1]==SpeaKer[q]) for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) for (j in (2:4)) { vTsub[,j+indexTime] <- vTsub[,j+indexTime]/deltaF } } vT <- rbind(vT,vTsub) } } return(vT) } ################################################################################ optionsScale <- function() { options <- c("Hz" = " Hz", "bark: Schroeder et al. (1979)" = " bark I", "bark: Zwicker & Terhardt (1980)" = " bark II", "bark: Traunmueller (1990)" = " bark III", "ERB: Greenwood (1961)" = " ERB I", "ERB: Moore & Glasberg (1983)" = " ERB II", "ERB: Glasberg & Moore (1990)" = " ERB III", "ln" = " ln", "mel: Fant (1968)" = " mel I", "mel: O'Shaughnessy (1987)" = " mel II", "ST" = " ST") return(options) } optionsNormal <- function(vowelTab, replyScale, noSelF0, noSelF3) { SpeaKer <- unique(vowelTab[,1]) nSpeaKer <- length(SpeaKer) if (nSpeaKer==1) return(c("None" = "")) indexVowel <- grep("^vowel$", colnames(vowelTab)) nonEmptyF0 <- (sum(vowelTab[,indexVowel+3]==0)!=nrow(vowelTab)) nonEmptyF3 <- (sum(vowelTab[,indexVowel+6]==0)!=nrow(vowelTab)) ### options1 <- c() if (nonEmptyF3 & noSelF3) options1 <- c(options1, "Peterson (1951)" = " Peterson") if (nonEmptyF3 & noSelF0 & (replyScale==" Hz")) options1 <- c(options1, "Sussman (1986)" = " Sussman") if (nonEmptyF0 & nonEmptyF3 & noSelF0 & noSelF3) options1 <- c(options1, "Syrdal & Gopal (1986)" = " Syrdal & Gopal") if (nonEmptyF0 & noSelF0 & (replyScale==" Hz")) options1 <- c(options1, "Miller (1989)" = " Miller") if (nonEmptyF3 & noSelF3) options1 <- c(options1, "Thomas & Kendall (2007)" = " Thomas & Kendall") ### options2 <- c() options2 <- c(options2, "Gerstman (1968)" = " Gerstman") ### options3 <- c() options3 <- c(options3, "Lobanov (1971)" = " Lobanov") if (noSelF0 & noSelF3) options3 <- c(options3, "Watt & Fabricius (2002)" = " Watt & Fabricius") if (noSelF0 & noSelF3) options3 <- c(options3, "Fabricius et al. (2009)" = " Fabricius et al.") if (noSelF0 & noSelF3) options3 <- c(options3, "Bigham (2008)" = " Bigham") if (noSelF0 & noSelF3) options3 <- c(options3, "Heeringa & Van de Velde (2021) I" = " Heeringa & Van de Velde I" ) if (noSelF0 & noSelF3) options3 <- c(options3, "Heeringa & Van de Velde (2021) II" = " Heeringa & Van de Velde II") ### options4 <- c() if (replyScale==" Hz") options4 <- c(options4, "Nearey (1978) I" = " Nearey I" ) if (noSelF0 & nonEmptyF3 & (replyScale==" Hz")) options4 <- c(options4, "Nearey (1978) II" = " Nearey II") if (replyScale==" Hz") options4 <- c(options4, "Barreda & Nearey (2018) I" = " Barreda & Nearey I" ) if (noSelF0 & nonEmptyF3 & (replyScale==" Hz")) options4 <- c(options4, "Barreda & Nearey (2018) II" = " Barreda & Nearey II") if (noSelF0 & noSelF3 & (replyScale==" Hz")) options4 <- c(options4, "Labov (2006) log-mean I" = " Labov I" ) if (noSelF0 & noSelF3 & (replyScale==" Hz")) options4 <- c(options4, "Labov (2006) log-geomean I" = " LABOV I" ) if (nonEmptyF3 & noSelF0 & (replyScale==" Hz")) options4 <- c(options4, "Labov (2006) log-mean II" = " Labov II") if (nonEmptyF3 & noSelF0 & (replyScale==" Hz")) options4 <- c(options4, "Labov (2006) log-geomean II" = " LABOV II") if (nonEmptyF3 & noSelF0) options4 <- c(options4, "Johnson (2018)" = " Johnson") ### return(c("None" = "", list(" Formant-ratio normalization"=options1, " Range normalization" =options2, " Centroid normalization" =options3, " Log-mean normalization" =options4))) } ################################################################################ vowelNormD <- function(vowelTab,replyNormal) { if ((is.null(vowelTab)) || (length(replyNormal)==0)) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab)) SpeaKer <- unique(vowelTab[,1]) nSpeaKer <- length(SpeaKer) VoWel <- unique(vowelTab[,indexVowel]) nVoWel <- length(VoWel) if (replyNormal=="") { vT <- vowelTab } if ((replyNormal==" Lobanov") & (nVoWel==1)) { vT <- data.frame() vTAg <- data.frame(vowelTab[,1],vowelTab[,indexVowel+1]) for (q in (1:nSpeaKer)) { vTAgSub <- subset(vTAg, vTAg[,1]==SpeaKer[q]) meanD <- mean(vTAgSub[,2]) sdD <- stats::sd(vTAgSub[,2]) vTsub <- subset(vowelTab, vowelTab[,1]==SpeaKer[q]) vTsub[,indexVowel+1] <- (vTsub[,indexVowel+1]-meanD)/sdD vT <- rbind(vT,vTsub) } } if ((replyNormal==" Lobanov") & (nVoWel> 1)) { vT <- data.frame() vTAg <- stats::aggregate(vowelTab[,indexVowel+1]~vowelTab[,1]+vowelTab[,indexVowel], FUN=mean) for (q in (1:nSpeaKer)) { vTAgSub <- subset(vTAg, vTAg[,1]==SpeaKer[q]) meanD <- mean(vTAgSub[,3]) sdD <- stats::sd(vTAgSub[,3]) vTsub <- subset(vowelTab, vowelTab[,1]==SpeaKer[q]) vTsub[,indexVowel+1] <- (vTsub[,indexVowel+1]-meanD)/sdD vT <- rbind(vT,vTsub) } } return(vT) } ################################################################################ speaker=NULL indexColor=indexShape=indexPlot=NULL X=Y=NULL color=shape=vowel=plot=time=NULL ll=ul=NULL voweltime=NULL xend=yend=NULL V1=V2=NULL ################################################################################ visvow <- function() { options(shiny.sanitize.errors = TRUE) options(shiny.usecairo=FALSE) options(shiny.maxRequestSize=200*1024^2) addResourcePath('www', system.file(package='visvow')) shinyApp( ui <- fluidPage( tags$style(type = 'text/css', '.title { margin-left: 20px; font-weight: bold; }'), tags$style(type = 'text/css', '.navbar-default > .container-fluid { margin-left: -11px; }'), tags$style(type = 'text/css', 'nav.navbar-default { margin-left: 15px; margin-right: 15px; }'), tags$style(type = 'text/css', 'p { margin-top: 0; margin-bottom: 0; }'), tags$style(type = 'text/css', 'h5 { margin-top: 0.3em; margin-bottom: 0.1em; }'), tags$style(type = 'text/css', 'h6 { margin-top: 1.0em; margin-bottom: 0.1em; }'), tags$style(type = 'text/css', 'li { margin-top: 0; margin-bottom: 0.4em; }'), tags$style(type = 'text/css', '.shiny-progress-container { position: absolute; left: 49% !important; width: 200px; margin-left: 100px; top: 40% !important; height: 100px; margin-top: 50px; z-index: 2000; }'), tags$style(type = 'text/css', '.shiny-progress .progress {position: absolute; left: 50% !important; width: 487px; margin-left: -419px; top: 50% !important; height: 16px; margin-top: 8px; }'), tags$style(type = 'text/css', '.shiny-progress .bar { background-color: #2081d4; .opacity = 0.8; }'), tags$style(type = 'text/css', '.shiny-progress .progress-text { position: absolute; right: 30px; height: 30px; width: 490px; background-color: #00AA00; padding-top: 2px; padding-right: 3px; padding-bottom: 2px; padding-left: 3px; opacity: 0.95; border-radius: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; }'), tags$style(type = 'text/css', '.progress-text { top: 15px !important; color: #FFFFFF !important; text-align: center; }'), tags$style(type = 'text/css', '.shiny-progress .progress-text .progress-message { padding-top: 0px; padding-right: 3px; padding-bottom: 3px; padding-left: 10px; font-weight: bold; font-size: 18px; }'), tags$style(type = 'text/css', '.shiny-progress .progress-text .progress-detail { padding-top: 0px; padding-right: 3px; padding-bottom: 3px; padding-left: 3px; font-size: 17px; }'), tags$style(type = 'text/css', '#heartbeat { width: 0; height: 0; visibility: hidden; }'), img(src = 'www/FA1.png', height = 39, align = "right", style = 'margin-top: 19px; margin-right: 15px;'), titlePanel(title = HTML("<div class='title'>Visible Vowels<div>"), windowTitle = "Visible Vowels"), tags$head( tags$link(rel="icon", href="www/FA2.png"), tags$meta(charset="UTF-8"), tags$meta(name ="description", content="Visible Vowels is a web app for the analysis of acoustic vowel measurements: f0, formants and duration. The app is an useful instrument for research in phonetics, sociolinguistics, dialectology, forensic linguistics, and speech-language pathology."), ), navbarPage ( title=NULL, id = "navBar", collapsible = TRUE, tabPanel ( title = "Load file", value = "load_file", fluidPage ( style = "border: 1px solid silver; padding: 6px; min-height: 690px;", fluidPage ( fileInput('vowelFile', 'Upload xlsx file', accept = c(".xlsx"), width="40%") ), fluidPage ( style = "font-size: 90%; white-space: nowrap;", align = "center", DT::dataTableOutput('vowelRound') ) ) ), tabPanel ( title = "Contours", value = "contours", splitLayout ( style = "border: 1px solid silver;", cellWidths = c("32%", "68%"), cellArgs = list(style = "padding: 6px"), column ( width=12, textInput("title0", "Plot title", "", width="100%"), uiOutput('selScale0'), uiOutput('selRef0'), splitLayout ( cellWidths = c("70%", "30%"), radioButtons("selError0", "Size of confidence intervals:", c("0%","90%","95%","99%"), selected = "0%", inline = TRUE), radioButtons("selMeasure0", "Use:", c("SD","SE"), selected = "SE", inline = TRUE) ), splitLayout ( uiOutput('selVar0'), uiOutput('selLine0'), uiOutput('selPlot0') ), splitLayout ( uiOutput('catXaxis0'), uiOutput('catLine0'), uiOutput('catPlot0') ), checkboxGroupInput("selGeon0", "Options:", c("average", "points", "smooth"), selected="points", inline=TRUE) ), column ( width = 12, uiOutput("Graph0"), column ( width = 11, splitLayout ( uiOutput('selFormat0a'), downloadButton('download0a', 'Table'), uiOutput('selSize0b'), uiOutput('selFont0b'), uiOutput('selPoint0b'), uiOutput('selFormat0b'), downloadButton('download0b', 'Graph') ) ) ) ) ), tabPanel ( title = "Formants", value = "formants", splitLayout ( style = "border: 1px solid silver;", cellWidths = c("32%", "68%"), cellArgs = list(style = "padding: 6px"), column ( width=12, textInput("title1", "Plot title", "", width="100%"), uiOutput('selTimes1'), splitLayout ( cellWidths = c("50%", "50%"), uiOutput('selScale1'), uiOutput('selNormal1') ), uiOutput('selTimesN'), splitLayout ( uiOutput('selColor1'), uiOutput('selShape1'), uiOutput('selPlot1') ), splitLayout ( uiOutput('catColor1'), uiOutput('catShape1'), uiOutput('catPlot1') ), uiOutput('selGeon1'), uiOutput('selPars' ), splitLayout ( cellWidths = c("28%", "26%", "46%"), checkboxInput("grayscale1", "grayscale" , FALSE), checkboxInput("average1" , "average" , FALSE), checkboxInput("ltf1" , "long-term formants", FALSE) ) ), column ( width=12, splitLayout ( cellWidths = c("85%", "15%"), uiOutput("Graph1"), column ( width=12, br(),br(), selectInput('axisX', "x-axis", choices=c("F1","F2","F3","--"), selected="F2", selectize=FALSE, width = "100%"), selectInput('axisY', "y-axis", choices=c("F1","F2","F3","--"), selected="F1", selectize=FALSE, width = "100%"), selectInput('axisZ', "z-axis", choices=c("F1","F2","F3","--"), selected="--", selectize=FALSE, width = "100%"), uiOutput('manScale'), uiOutput('selF1min'), uiOutput('selF1max'), uiOutput('selF2min'), uiOutput('selF2max') ) ), column ( width = 11, splitLayout ( uiOutput('selFormat1a'), downloadButton('download1a', 'Table'), uiOutput('selSize1b'), uiOutput('selFont1b'), uiOutput('selPoint1b'), uiOutput('selFormat1b'), downloadButton('download1b', 'Graph') ) ) ) ) ), tabPanel ( title = "Dynamics", value = "dynamics", splitLayout ( style = "border: 1px solid silver;", cellWidths = c("32%", "68%"), cellArgs = list(style = "padding: 6px"), column ( width=12, textInput("title4", "Plot title", "", width="100%"), splitLayout ( cellWidths = c("50%", "49%"), uiOutput('selScale4'), uiOutput('selMethod4') ), uiOutput('selGraph4'), splitLayout ( cellWidths = c("70%", "30%"), radioButtons("selError4", "Size of confidence intervals:", c("0%","90%","95%","99%"), selected = "95%", inline = TRUE), radioButtons("selMeasure4", "Use:", c("SD","SE"), selected = "SE", inline = TRUE) ), splitLayout ( cellWidths = c("21%", "26%", "26%", "26%"), uiOutput('selVar4'), uiOutput('selXaxis4'), uiOutput('selLine4'), uiOutput('selPlot4') ), splitLayout ( cellWidths = c("21%", "26%", "26%", "26%"), uiOutput('selTimes4'), uiOutput('catXaxis4'), uiOutput('catLine4'), uiOutput('catPlot4') ), checkboxGroupInput("selGeon4", "Options:", c("average", "rotate x-axis labels"), inline=TRUE) ), column ( width = 12, uiOutput("Graph4"), column ( width = 11, splitLayout ( uiOutput('selFormat4a'), downloadButton('download4a', 'Table'), uiOutput('selSize4b'), uiOutput('selFont4b'), uiOutput('selPoint4b'), uiOutput('selFormat4b'), downloadButton('download4b', 'Graph') ) ) ) ) ), tabPanel ( title = "Duration", value = "duration", splitLayout ( style = "border: 1px solid silver;", cellWidths = c("32%", "68%"), cellArgs = list(style = "padding: 6px"), column ( width=12, textInput("title2", "Plot title", "", width="100%"), uiOutput('selNormal2'), uiOutput('selGraph2'), splitLayout ( cellWidths = c("70%", "30%"), radioButtons("selError2", "Size of confidence intervals:", c("0%","90%","95%","99%"), selected = "95%", inline = TRUE), radioButtons("selMeasure2", "Use:", c("SD","SE"), selected = "SE", inline = TRUE) ), splitLayout ( uiOutput('selXaxis2'), uiOutput('selLine2'), uiOutput('selPlot2') ), splitLayout ( uiOutput('catXaxis2'), uiOutput('catLine2'), uiOutput('catPlot2') ), checkboxGroupInput("selGeon2", "Options:", c("average", "rotate x-axis labels"), inline=TRUE) ), column ( width = 12, uiOutput("Graph2"), column ( width = 11, splitLayout ( uiOutput('selFormat2a'), downloadButton('download2a', 'Table'), uiOutput('selSize2b'), uiOutput('selFont2b'), uiOutput('selPoint2b'), uiOutput('selFormat2b'), downloadButton('download2b', 'Graph') ) ) ) ) ), tabPanel ( title = "Explore", value = "explore", splitLayout ( style = "border: 1px solid silver;", cellWidths = c("32%", "68%"), cellArgs = list(style = "padding: 6px"), column ( width=12, textInput("title3", "Plot title", "", width="100%"), uiOutput('selTimes3'), splitLayout ( cellWidths = c("50%", "50%"), checkboxGroupInput("selFormant3", "Include formants:", c("F1","F2","F3"), selected=c("F1","F2"), TRUE), radioButtons('selMetric3', 'Metric:', c("Euclidean","Accdist"), selected = "Euclidean", TRUE) ), splitLayout ( cellWidths = c("50%", "50%"), uiOutput('selScale3'), uiOutput('selNormal3') ), uiOutput('selTimesN3'), splitLayout ( uiOutput('selVowel3'), uiOutput('selGrouping3'), uiOutput('catGrouping3') ), radioButtons('selClass3', 'Explorative method:', c("Cluster analysis","Multidimensional scaling"), selected = "Cluster analysis", TRUE), uiOutput('selMethod3'), uiOutput('explVar3'), uiOutput("selGeon3"), splitLayout ( checkboxInput("grayscale3", "grayscale", FALSE), checkboxInput("summarize3" ,"summarize", FALSE) ) ), column ( width = 12, uiOutput("Graph3"), column ( width = 11, splitLayout ( uiOutput('selFormat3a'), downloadButton('download3a', 'Table'), uiOutput('selSize3b'), uiOutput('selFont3b'), uiOutput('selPoint3b'), uiOutput('selFormat3b'), downloadButton('download3b', 'Graph') ) ) ) ) ), tabPanel ( title = "Evaluate", value = "evaluate", splitLayout ( style = "border: 1px solid silver; min-height: 690px;", cellWidths = c("32%", "68%"), cellArgs = list(style = "padding: 6px"), column ( width=12, fluidPage( style = 'border: 1px solid silver; margin-top: 7px; padding-top: 4px; padding-bottom: 4px;', align = "center", actionLink("buttonHelp5", label="", icon=icon("info-circle", lib = "font-awesome"), style='color: #2c84d7; font-size: 180%; margin-left: 4px;') ), br(), uiOutput('selTimes5'), uiOutput('selTimesN5'), splitLayout( uiOutput('selVars51'), uiOutput('selVars52') ), uiOutput("selF035"), br(), uiOutput('goButton') ), column ( width = 12, uiOutput("Graph5"), hr(style='border-top: 1px solid #cccccc;'), splitLayout ( radioButtons(inputId = 'selMeth5', label = 'Choose:', choices = c("Evaluate", "Compare"), selected = "Evaluate", inline = FALSE), uiOutput("getOpts5"), uiOutput("getEval5") ) ) ) ), navbarMenu("More", tabPanel ( title = "Help", value = "help", fluidPage ( style = "border: 1px solid silver;", br(), h5(strong("About")), p("Visible Vowels is a web app for the analysis of acoustic vowel measurements: f0, formants and duration. The app is an useful instrument for research in phonetics, sociolinguistics, dialectology, forensic linguistics, and speech-language pathology. The following people were involved in the development of Visible Vowels: Wilbert Heeringa (implementation), Hans Van de Velde (project manager), Vincent van Heuven (advice). Visible Vowels is still under development. Comments are welcome and can be sent to", img(src = 'www/email.png', height = 20, align = "center"),"."), br(), h5(strong("System requirements")), p("Visible Vowels runs best on a computer with a monitor with a minimum resolution of 1370 x 870 (width x height). The use of Mozilla Firefox as a web browser is to be preferred."), br(), h5(strong("Format")), p("The input file should be a spreadsheet that is created in Excel or LibreOffice. It should be saved as an Excel 2007/2010/2013 XML file, i.e. with extension '.xlsx'. The spreadsheet should include the following variables (shown in red):"), br(), tags$div(tags$ul ( tags$li(tags$span(HTML("<span style='font-variant: small-caps; color:blue'>General</span>"), div(tags$ul( tags$li(tags$span(HTML("<span style='color:crimson'>speaker</span>"), p("Contains the speaker labels. This column is obligatory."))), tags$li(tags$span(HTML("<span style='color:crimson'>vowel</span>"), p("Contains the vowel labels. Multiple pronunciations of the same vowel per speaker are possible. In case you want to use IPA characters, enter them as Unicode characters. In order to find Unicode IPA characters, use the online", tags$a(href="http://westonruter.github.io/ipa-chart/keyboard/", "IPA Chart Keyboard", target="_blank"), "of Weston Ruter. This column is obligatory."))), tags$li(tags$span(HTML("<span style='color:crimson'>timepoint</span>"), p("In this column the time points are labeled by numbers that indicate the order of the time points in the vowel interval. This column is obligatory only when using the long format."))) )))), tags$li(tags$span(HTML("<span style='font-variant: small-caps; color:blue'>Sociolinguistic</span>"),div(tags$ul( tags$li(tags$span(HTML("<span style='color:crimson'>...</span>"), p("An arbitrary number of columns representing categorical variables such as location, language, gender, age group, etc. may follow, but is not obligatory. See to it that each categorical variable has an unique set of different values. Prevent the use of numbers, rather use meaningful codes. For example, rather then using codes '1' and '2' for a variable 'age group' use 'old' and 'young' or 'o' and 'y'."))) )))), tags$li(tags$span(HTML("<span style='font-variant: small-caps; color:blue'>Vowel</span>"), div(tags$ul( tags$li(tags$span(HTML("<span style='color:crimson'>duration</span>"), p("Durations of the vowels. The measurements may be either in seconds or milliseconds. This column is obligatory but may be kept empty."))), tags$li(tags$span(HTML("<span style='color:crimson'>time f0 F1 F2 F3</span>"), p("A set of five columns should follow: 'time', 'f0', 'F1', 'F2' and 'F3'. The variable 'time' gives the time point at which f0, F1, F2 and F3 are measured. This time point within the vowel interval should be measured in seconds or milliseconds. It is assumed that the vowel interval starts at 0 (milli)seconds. It is assumed that f0, F1, F2 and F3 are measured in Hertz and not normalized. A set should always include all five columns, but the columns 'time', 'f0' and 'F3' may be kept empty. ", em("As many"), " sets can be included as time points within the vowel interval are chosen. But a set should occur at least one time. When using the wide format, all the sets are found in the same row, and for each set the same column names should be used. When using the long format, each set is found in a seperate row, and rows that refer to the same realization are distinguished by the codes in the 'timepoint' column."))) )))) )), br(), p("Below both the wide and the long format are schematically shown by means of an example. In this example there are three speakers labeled as 'A', 'B' and 'C'. Each of the speakers pronounced two different vowels: i: and \u0254. Each vowel has been pronounced twice by each speaker, and for each realization f0, F1, F2 and F3 are measured at two time points."), br(), p("Note the importance of the numbers in the fourth column in the long table, where they make it clear which measurements at multiple time points relate to the same vowel realization. In fact, the long format requires that all cases in the table be uniquely defined by the combination of the 'speaker' variable, the 'vowel' variable, the 'timepoint' variable and the categorical variables that follow, i.e. the pink, yellow, grey and white columns to the left of the 'duration' variable."), br(), p(em("Wide format"), style="margin-left: 41px;"), br(), div(img(src = 'www/format1.png', width=580), style="margin-left: 41px;"), br(), br(), p(em("Long format"), style="margin-left: 41px;"), br(), div(img(src = 'www/format2.png', width=450), style="margin-left: 41px;"), br(), br(), h5(strong("Example input file")), p("In order to try Visible Vowels an example spreadsheet can be downloaded ", a("here", href = "www/example.xlsx", target = "_blank"), "and be loaded by this program."), br(), h5(strong("Graphs")), p("Graphs can be saved in six formats: JPG, PNG, SVG, EPS, PDF and TEX. TEX files are created with TikZ. When using this format, it is assumed that XeLaTeX is installed. Generating a TikZ may take a long time. When including a TikZ file in a LaTeX document, you need to use a font that supports the IPA Unicode characters, for example: 'Doulos SIL', 'Charis SIL' or 'Linux Libertine O'. You also need to adjust the left margin and the scaling of the graph. The LaTeX document should be compiled with", code("xelatex"), ". Example of a LaTeX file in which a TikZ file is included:"), br(), code(style="margin-left: 36px;", "\\documentclass{minimal}"), br(), br(), code(style="margin-left: 36px;", "\\usepackage{tikz}"), br(), code(style="margin-left: 36px;", "\\usepackage{fontspec}"), br(), code(style="margin-left: 36px;", "\\setmainfont{Linux Libertine O}"), br(), br(), code(style="margin-left: 36px;", "\\begin{document}"), br(), code(style="margin-left: 36px;", "{\\hspace*{-3cm}\\scalebox{0.8}{\\input{formantPlot.TEX}}}"), br(), code(style="margin-left: 36px;", "\\end{document}"), br(), br(), br(), h5(strong("Implementation")), p("This program is implemented as a Shiny app. Shiny was developed by RStudio. This app uses the following R packages:"), br(), tags$div(tags$ul ( tags$li(tags$span(HTML("<span style='color:blue'>base</span>"),p("R Core Team (2017). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/"))), tags$li(tags$span(HTML("<span style='color:blue'>shiny</span>"),p("Winston Chang, Joe Cheng, J.J. Allaire, Yihui Xie and Jonathan McPherson (2017). shiny: Web Application Framework for R. R package version 1.0.0. https://CRAN.R-project.org/package=shiny"))), tags$li(tags$span(HTML("<span style='color:blue'>shinyBS</span>"),p("Eric Bailey (2015). shinyBS: Twitter Bootstrap Components for Shiny. R package version 0.61. https://CRAN.R-project.org/package=shinyBS"))), tags$li(tags$span(HTML("<span style='color:blue'>stats</span>"),p("R Core Team (2017). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/"))), tags$li(tags$span(HTML("<span style='color:blue'>tydr</span>"),p("Hadley Wickham and Lionel Henry (2019). tidyr: Tidy Messy Data. R package version 1.0.0. https://CRAN.R-project.org/package=tidyr"))), tags$li(tags$span(HTML("<span style='color:blue'>PBSmapping</span>"),p("Jon T. Schnute, Nicholas Boers and Rowan Haigh (2019). PBSmapping: Mapping Fisheries Data and Spatial Analysis Tools. R package version 2.72.1. https://CRAN.R-project.org/package=PBSmapping"))), tags$li(tags$span(HTML("<span style='color:blue'>splitstackshape</span>"),p("Ananda Mahto (2019). splitstackshape: Stack and Reshape Datasets After Splitting Concatenated Values. R package version 1.4.8. https://CRAN.R-project.org/package=splitstackshape"))), tags$li(tags$span(HTML("<span style='color:blue'>plyr</span>"),p("Hadley Wickham (2011). The Split-Apply-Combine Strategy for Data Analysis. Journal of Statistical Software, 40(1), 1-29. URL http://www.jstatsoft.org/v40/i01/"))), tags$li(tags$span(HTML("<span style='color:blue'>dplyr</span>"),p("Hadley Wickham, Romain Fran\u00E7ois, Lionel Henry and Kirill M\u00FCller (2022). dplyr: A Grammar of Data Manipulation. R package version 1.0.10. https://CRAN.R-project.org/package=dplyr"))), tags$li(tags$span(HTML("<span style='color:blue'>formattable</span>"),p("Kun Ren and Kenton Russell (2016). formattable: Create 'Formattable' Data Structures. R package version 0.2.0.1. https://CRAN.R-project.org/package=formattable"))), tags$li(tags$span(HTML("<span style='color:blue'>ggplot2</span>"),p("H. Wickham (2009). ggplot2: Elegant Graphics for Data Analysis. Springer-Verlag New York. http://ggplot2.org"))), tags$li(tags$span(HTML("<span style='color:blue'>plot3D</span>"),p("Karline Soetaert (2017). plot3D: Plotting Multi-Dimensional Data. R package version 1.1.1. https://CRAN.R-project.org/package=plot3D"))), tags$li(tags$span(HTML("<span style='color:blue'>MASS</span>"),p("W.N. Venables & B.D. Ripley (2002). Modern Applied Statistics with S. Fourth Edition. Springer, New York. ISBN 0-387-95457-0"))), tags$li(tags$span(HTML("<span style='color:blue'>ggdendro</span>"),p("Andrie de Vries and Brian D. Ripley (2016). ggdendro: Create Dendrograms and Tree Diagrams Using 'ggplot2'. R package version 0.1-20. https://CRAN.R-project.org/package=ggdendro"))), tags$li(tags$span(HTML("<span style='color:blue'>ggrepel</span>"),p("Kamil Slowikowski (2017). ggrepel: Repulsive Text and Label Geoms for 'ggplot2'. R package version 0.7.0. https://CRAN.R-project.org/package=ggrepel"))), tags$li(tags$span(HTML("<span style='color:blue'>readxl</span>"),p("Hadley Wickham and Jennifer Bryan (2017). readxl: Read Excel Files. R package version 1.0.0. https://CRAN.R-project.org/package=readxl"))), tags$li(tags$span(HTML("<span style='color:blue'>WriteXLS</span>"),p("Marc Schwartz and various authors. (2015). WriteXLS: Cross-Platform Perl Based R Function to Create Excel 2003 (XLS) and Excel 2007 (XLSX) Files. R package version 4.0.0. https://CRAN.R-project.org/package=WriteXLS"))), tags$li(tags$span(HTML("<span style='color:blue'>DT</span>"),p("Yihui Xie (2016). DT: A Wrapper of the JavaScript Library 'DataTables'. R package version 0.2. https://CRAN.R-project.org/package=DT"))), tags$li(tags$span(HTML("<span style='color:blue'>psych</span>"),p("William Revelle (2016). psych: Procedures for Personality and Psychological Research, Northwestern University, Evanston, Illinois, USA, Version = 1.6.12, https://CRAN.R-project.org/package=psych"))), tags$li(tags$span(HTML("<span style='color:blue'>pracma</span>"),p("Hans Werner Borchers (2017). pracma: Practical Numerical Math Functions. R package version 1.9.9. https://CRAN.R-project.org/package=pracma"))), tags$li(tags$span(HTML("<span style='color:blue'>Rtsne</span>"),p("Jesse H. Krijthe (2015). Rtsne: T-Distributed Stochastic Neighbor Embedding using a Barnes-Hut Implementation. https://github.com/jkrijthe/Rtsne"),p("L.J.P. van der Maaten and G.E. Hinton (2008). Visualizing High-Dimensional Data Using t-SNE. Journal of Machine Learning Research 9(Nov):2579-2605"),p("L.J.P. van der Maaten (2014). Accelerating t-SNE using Tree-Based Algorithms. Journal of Machine Learning Research 15(Oct):3221-3245"))), tags$li(tags$span(HTML("<span style='color:blue'>grid</span>"),p("R Core Team (2017). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/"))), tags$li(tags$span(HTML("<span style='color:blue'>svglite</span>"),p("Hadley Wickham, Lionel Henry, T Jake Luciani, Matthieu Decorde and Vaudor Lise (2016). svglite: An 'SVG' Graphics Device. R package version 1.2.0. https://CRAN.R-project.org/package=svglite"))), tags$li(tags$span(HTML("<span style='color:blue'>Cairo</span>"),p("Simon Urbanek and Jeffrey Horner (2015). Cairo: R graphics device using cairo graphics library for creating high-quality bitmap (PNG, JPEG, TIFF), vector (PDF, SVG, PostScript) and display (X11 and Win32) output. R package version 1.5-9. https://CRAN.R-project.org/package=Cairo"))), tags$li(tags$span(HTML("<span style='color:blue'>tikzDevice</span>"),p("Charlie Sharpsteen and Cameron Bracken (2020). tikzDevice: R Graphics Output in LaTeX Format. R package version 0.12.3.1. https://CRAN.R-project.org/package=tikzDevice"))), tags$li(tags$span(HTML("<span style='color:blue'>shinybusy</span>"),p("Fanny Meyer and Victor Perrier (2020). shinybusy: Busy Indicator for 'Shiny' Applications. R package version 0.2.2. https://CRAN.R-project.org/package=shinybusy"))) )), br(), p("Visible Vowels allows to convert and normalize vowel data and calculate some specific metrics. To get all the details on how these values are calculated, type ", span(style="font-family: monospace; font-size: 100%;", 'vignette("visvow")'), " in the R console."), br(), h5(strong("How to cite this app")), p("Heeringa, W. & Van de Velde, H. (2018). \u201CVisible Vowels: a Tool for the Visualization of Vowel Variation.\u201D In ",tags$i("Proceedings CLARIN Annual Conference 2018, 8 - 10 October, Pisa, Italy."),"CLARIN ERIC."), br() ), br() ), tabPanel ( title = "Disclaimer", value = "disclaimer", fluidPage ( style = "border: 1px solid silver; min-height: 690px;", br(), h5(strong("Liability")), p("This app is provided 'as is' without warranty of any kind, either express or implied, including, but not limited to, the implied warranties of fitness for a purpose, or the warranty of non-infringement. Without limiting the foregoing, the Fryske Akademy makes no warranty that: 1) the app will meet your requirements, 2) the app will be uninterrupted, timely, secure or error-free, 3) the results that may be obtained from the use of the app will be effective, accurate or reliable, 4) the quality of the app will meet your expectations, 5) any errors in the app will be corrected."), br(), p("The app and its documentation could include technical or other mistakes, inaccuracies or typographical errors. The Fryske Akademy may make changes to the app or documentation made available on its web site. The app and its documentation may be out of date, and the Fryske Akademy makes no commitment to update such materials."), br(), p("The Fryske Akademy assumes no responsibility for errors or ommissions in the app or documentation available from its web site."), br(), p("In no event shall the Fryske Akademy be liable to you or any third parties for any special, punitive, incidental, indirect or consequential damages of any kind, or any damages whatsoever, including, without limitation, those resulting from loss of use, data or profits, whether or not the Fryske Akademy has been advised of the possibility of such damages, and on any theory of liability, arising out of or in connection with the use of this software."), br(), p("The use of the app is done at your own discretion and risk and with agreement that you will be solely responsible for any damage to your computer system or loss of data that results from such activities. No advice or information, whether oral or written, obtained by you from the Fryske Akademy shall create any warranty for the software."), br(), h5(strong("Other")), p("The disclaimer may be changed from time to time."), br() ) )) ), tags$td(textOutput("heartbeat")) ), ############################################################################ server <- function(input, output, session) { observeEvent(input$navBar, { if (getUrlHash() == paste0("#", input$navBar)) return() updateQueryString(paste0("#", input$navBar), mode = "push") }) observeEvent(getUrlHash(), { Hash <- getUrlHash() if (Hash == paste0("#", input$navBar)) return() Hash <- gsub("#", "", Hash) updateNavbarPage(session, "navBar", selected=Hash) }) output$heartbeat <- renderText( { invalidateLater(5000) Sys.time() }) observe({ message("Press ESC once or more to exit, ignore warnings") options(warn = -1) }) ########################################################################## vowelFile <- reactive( { inFile <- input$vowelFile if (is.null(inFile)) return(NULL) file.rename(inFile$datapath, paste0(inFile$datapath,".xlsx")) vT <- as.data.frame(read_excel(paste0(inFile$datapath,".xlsx"), sheet=1, .name_repair = "minimal")) # wide format if (!("timepoint" %in% colnames(vT))) { return(vT) } # long format if ("timepoint" %in% colnames(vT)) { timepoint <- vT$timepoint vT$timepoint <- NULL indexDuration <- grep("^duration$", tolower(colnames(vT))) ngroups <- (ncol(vT) - indexDuration) / 5 if (ngroups == 1) { freq <- data.frame(table(timepoint)) if (mean(freq$Freq) != round(mean(freq$Freq))) { showNotification("The number of time points is not the same for all cases!", type = "error", duration = 10) return(NULL) } if (!unique((sort(freq$timepoint) == 1:length(freq$timepoint)))) { showNotification("Numbering of time points is not correct!", type = "error", duration = 10) return(NULL) } superIndex <- "" for (i in 1:(indexDuration-1)) { superIndex <- paste0(superIndex, vT[,i]) } ntimepoints <- nrow(freq) if ((nrow(vT)/ntimepoints) > length(unique(superIndex))) { showNotification("Not all cases are uniquely defined!", type = "error", duration = 10) return(NULL) } vT <- vT[order(superIndex, timepoint),] df <- dplyr::filter(vT, ((dplyr::row_number() %% ntimepoints)) == 1) df <- df[, 1:indexDuration] for (g in (1:ntimepoints)) { if (g==ntimepoints) g0 <- 0 else g0 <- g df0 <- dplyr::filter(vT, ((dplyr::row_number() %% ntimepoints)) == g0) df0 <- df0[, (indexDuration+1):(indexDuration+5)] df <- cbind(df, df0) } return(df) } else { showNotification("Cannot have both a variable timepoint and multiple time points in one row!", type = "error", duration = 10) return(NULL) } } }) checkVar <- function(varName, varIndex, checkEmpty) { indexVar <- grep(paste0("^", varName, "$"), tolower(colnames(vowelFile()))) if (!is.element(tolower(varName), tolower(colnames(vowelFile())))) Message <- paste0("Column '", varName, "' not found.") else if ((varIndex!=0) && (tolower(colnames(vowelFile())[varIndex])!=tolower(varName))) Message <- paste0("'", varName, "' found in the wrong column.") else if (checkEmpty && (sum(is.na(vowelFile()[,indexVar]))==nrow(vowelFile()))) Message <- paste0("Column '", varName, "' is empty.") else Message <- "OK" return(Message) } checkVars <- reactive( { if (is.null(vowelFile())) return(NULL) m <- checkVar("speaker" , 1, T) if (m!="OK") return(m) m <- checkVar("vowel" , 2, T) if (m!="OK") return(m) m <- checkVar("duration", 0, F) if (m!="OK") return(m) m <- checkVar("time" , 0, F) if (m!="OK") return(m) m <- checkVar("f0" , 0, F) if (m!="OK") return(m) m <- checkVar("F1" , 0, T) if (m!="OK") return(m) m <- checkVar("F2" , 0, T) if (m!="OK") return(m) m <- checkVar("F3" , 0, F) if (m!="OK") return(m) return("OK") }) Round <- function(x) { return(trunc(x+0.5)) } vowelRound <- reactive( { if (is.null(vowelFile())) return(NULL) # check if (checkVars()!="OK") { showNotification(checkVars(), type = "error", duration = 10) return(NULL) } vT <- vowelFile() nColumns <- ncol(vT) for (i in (1:nColumns)) { if (grepl("^duration",tolower(colnames(vT)[i])) | grepl("^time" ,tolower(colnames(vT)[i])) | grepl("^f0" ,tolower(colnames(vT)[i])) | grepl("^F1" ,toupper(colnames(vT)[i])) | grepl("^F2" ,toupper(colnames(vT)[i])) | grepl("^F3" ,toupper(colnames(vT)[i]))) { if (is.character(vT[,i])) { vT[,i] <- as.numeric(vT[,i]) } if (sum(is.na(vT[,i]))<nrow(vT)) { if (max(vT[,i], na.rm = TRUE)<=1) { vT[,i] <- round(((Round(vT[,i]*1000))/1000),3) } else { vT[,i] <- Round(vT[,i]) } } } } return(vT) }) output$vowelRound <- DT::renderDataTable(expr = vowelRound(), options = list(scrollX = TRUE)) vowelTab <- reactive( { if (is.null(vowelFile()) || (checkVars()!="OK")) return(NULL) vT <- vowelFile() indexDuration <- grep("^duration$", tolower(colnames(vT))) if (indexDuration > 3) { cnames <- colnames(vT) vT <- data.frame(vT[,1], vT[,3:(indexDuration-1)], vT[,2], vT[,indexDuration:ncol(vT)]) cnames <- c(cnames[1],cnames[3:(indexDuration-1)],cnames[2],cnames[indexDuration:ncol(vT)]) colnames(vT) <- cnames } else {} indexVowel <- grep("^vowel$", tolower(trimws(colnames(vT), "r"))) for (k in (1:(indexVowel+1))) { colnames(vT)[k] <- tolower(trimws(colnames(vT)[k], "r")) } k0 <- 0 for (k in ((indexVowel+2):(ncol(vT)))) { k0 <- k0 +1 if (((k0 %% 5)==1) | ((k0 %% 5)==2)) { colnames(vT)[k] <- tolower(colnames(vT)[k]) } else { colnames(vT)[k] <- toupper(colnames(vT)[k]) } } if (length(indexVowel)>0) { for (i in ((indexVowel+1):(ncol(vT)))) { if (is.character(vT[,i])) { vT[,i] <- as.numeric(vT[,i]) } if (sum(is.na(vT[,i]))==nrow(vT)) { vT[,i] <- 0 } } vT <- vT[rowSums(is.na(vT)) == 0,] } return(vT) }) vowelExcl <- reactive( { if (is.null(vowelTab()) || (nrow(vowelTab())==0)) return(NULL) vowels <- unique(vowelTab()$vowel) vowels0 <- unique(vowelTab()$vowel) speakers <- unique(vowelTab()$speaker) for (i in 1:length(speakers)) { vTsub <- subset(vowelTab(), speaker==speakers[i]) vowels <- intersect(vowels,unique(vTsub$vowel)) } return(setdiff(vowels0,vowels)) }) vowelSame <- reactive( { if (is.null(vowelTab()) || (nrow(vowelTab())==0)) return(NULL) if (length(vowelExcl())==0) return(vowelTab()) else return(subset(vowelTab(), !is.element(vowelTab()$vowel,vowelExcl()))) }) showExclVow <- function() { if (length(vowelExcl()) > 0) { vowels <- "Vowels excluded: " for (i in 1:length(vowelExcl())) { vowels <- paste(vowels, vowelExcl()[i]) } showNotification(vowels, type = "error", duration = 30) } } ########################################################################## vowelScale0 <- reactive( { if ((length(input$replyRef0)==0) || is.na(input$replyRef0)) Ref <- 50 else Ref <- input$replyRef0 return(vowelScale(vowelTab(),input$replyScale0,Ref)) }) fuseCols <- function(vT,replyValue) { columns <- "" if (length(replyValue)>0) { for (i in (1:length(replyValue))) { indexValue <- grep(paste0("^",as.character(replyValue)[i],"$"), colnames(vT)) if (i==1) columns <- paste0(columns,vT[,indexValue]) else columns <- paste (columns,vT[,indexValue]) } } return(columns) } getTimeCode <- reactive( { indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 percentages <-FALSE if (sum(is.na(vowelTab()[,indexVowel + 1]))!=nrow(vowelTab())) { meanDuration <- mean(vowelTab()[,indexVowel+1]) if (mean(vowelTab()[,indexVowel+2+((nPoints-1)*5)]) <= meanDuration) { if (meanDuration==0) { meanDuration <- 0.000001 } timeLabel <- c() timeCode <- c() for (i in (1:nPoints)) { indexTime <- indexVowel + 2 + ((i-1)*5) timeLabel[i] <- (mean(vowelTab()[,indexTime])/meanDuration) * 100 timeCode [i] <- i names(timeCode) <- as.character(round(timeLabel)) } percentages <-TRUE } } if (percentages==FALSE) { timeCode <- seq(from=1, to=nPoints, by=1) names(timeCode) <- as.character(timeCode) } return(timeCode) }) vowelSub0 <- reactive( { if (is.null(vowelScale0()) || (nrow(vowelScale0())==0) || (length(input$catXaxis0)==0)) return(NULL) vT <- vowelScale0() vT$indexPlot <- fuseCols(vowelScale0(),input$replyPlot0) vT$indexLine <- fuseCols(vowelScale0(),input$replyLine0) indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 xi <- as.numeric(input$catXaxis0) xn <- names(getTimeCode())[xi] if (input$replyVar0=="f0") varIndex <- 1 else if (input$replyVar0=="F1") varIndex <- 2 else if (input$replyVar0=="F2") varIndex <- 3 else if (input$replyVar0=="F3") varIndex <- 4 else return(NULL) if (input$selError0=="0%") z <- 0 if (input$selError0=="90%") z <- 1.645 if (input$selError0=="95%") z <- 1.96 if (input$selError0=="99%") z <- 2.575 if ((length(input$catPlot0)==0) && ((length(input$catLine0)==0) | (length(input$catLine0)>14))) { x <- c() y <- c() s <- c() v <- c() for (i in (1:nPoints)) { if (is.element(i,xi)) { ii <- which(xi==i) x <- as.numeric(as.character(c(x,rep(xn[ii],nrow(vT))))) indexTime <- indexVowel + 2 + ((i-1)*5) y <- c(y,vT[,indexTime+varIndex]) s <- c(s,as.character(vT$speaker)) v <- c(v,as.character(vT$vowel)) } } vT0 <- data.frame(x,s,v,y) if (is.element("average",input$selGeon0)) { vT0 <- stats::aggregate(y~x+s+v, data=vT0, FUN=mean) vT0 <- stats::aggregate(y~x+ v, data=vT0, FUN=mean) } ag <- stats::aggregate(y~x, data=vT0, FUN=mean) ag$sd <- stats::aggregate(y~x, data=vT0, FUN=sd)[,2] ag$n <- stats::aggregate(y~x, data=vT0, FUN=length)[,2] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure0=="SD") { ag$ll <- ag[,2] - z * ag$sd ag$ul <- ag[,2] + z * ag$sd } if (input$selMeasure0=="SE") { ag$ll <- ag[,2] - z * ag$se ag$ul <- ag[,2] + z * ag$se } colnames(ag)[1] <- "time" colnames(ag)[2] <- input$replyVar0 return(ag) } else if ((length(input$catPlot0)>0) && ((length(input$catLine0)==0) | (length(input$catLine0)>14))) { vT <- subset(vT, is.element(vT$indexPlot,input$catPlot0)) vT$indexPlot <- as.character(vT$indexPlot) if (nrow(vT)==0) return(data.frame()) x <- c() y <- c() p <- c() s <- c() v <- c() for (i in (1:nPoints)) { if (is.element(i,xi)) { ii <- which(xi==i) x <- as.numeric(as.character(c(x,rep(xn[ii],nrow(vT))))) indexTime <- indexVowel + 2 + ((i-1)*5) y <- c(y,vT[,indexTime+varIndex]) p <- c(p,vT$indexPlot) s <- c(s,as.character(vT$speaker)) v <- c(v,as.character(vT$vowel)) } } vT0 <- data.frame(x,p,s,v,y) if (is.element("average",input$selGeon0)) { vT0 <- stats::aggregate(y~x+p+s+v, data=vT0, FUN=mean) vT0 <- stats::aggregate(y~x+p+ v, data=vT0, FUN=mean) } ag <- stats::aggregate(y~x+p, data=vT0, FUN=mean) ag$sd <- stats::aggregate(y~x+p, data=vT0, FUN=sd)[,3] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(y~x+p, data=vT0, FUN=length)[,3] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure0=="SD") { ag$ll <- ag[,3] - z * ag$sd ag$ul <- ag[,3] + z * ag$sd } if (input$selMeasure0=="SE") { ag$ll <- ag[,3] - z * ag$se ag$ul <- ag[,3] + z * ag$se } ag <- ag[order(ag[,2]),] colnames(ag)[1] <- "time" colnames(ag)[2] <- paste(input$replyPlot0, collapse = " ") colnames(ag)[3] <- input$replyVar0 return(ag) } else if ((length(input$catPlot0)==0) && ((length(input$catLine0)>0) & (length(input$catLine0)<=14))) { vT <- subset(vT, is.element(vT$indexLine,input$catLine0)) vT$indexLine <- as.character(vT$indexLine) if (nrow(vT)==0) return(data.frame()) x <- c() y <- c() l <- c() s <- c() v <- c() for (i in (1:nPoints)) { if (is.element(i,xi)) { ii <- which(xi==i) x <- as.numeric(as.character(c(x,rep(xn[ii],nrow(vT))))) indexTime <- indexVowel + 2 + ((i-1)*5) y <- c(y,vT[,indexTime+varIndex]) l <- c(l,vT$indexLine) s <- c(s,as.character(vT$speaker)) v <- c(v,as.character(vT$vowel)) } } vT0 <- data.frame(x,l,s,v,y) if (is.element("average",input$selGeon0)) { vT0 <- stats::aggregate(y~x+l+s+v, data=vT0, FUN=mean) vT0 <- stats::aggregate(y~x+l+ v, data=vT0, FUN=mean) } ag <- stats::aggregate(y~x+l, data=vT0, FUN=mean) ag$sd <- stats::aggregate(y~x+l, data=vT0, FUN=sd)[,3] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(y~x+l, data=vT0, FUN=length)[,3] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure0=="SD") { ag$ll <- ag[,3] - z * ag$sd ag$ul <- ag[,3] + z * ag$sd } if (input$selMeasure0=="SE") { ag$ll <- ag[,3] - z * ag$se ag$ul <- ag[,3] + z * ag$se } ag <- ag[order(ag[,2]),] colnames(ag)[1] <- "time" colnames(ag)[2] <- paste(input$replyLine0, collapse = " ") colnames(ag)[3] <- input$replyVar0 return(ag) } else if ((length(input$catPlot0)>0) && ((length(input$catLine0)>0) & (length(input$catLine0)<=14))) { vT <- subset(vT, is.element(vT$indexPlot,input$catPlot0) & is.element(vT$indexLine,input$catLine0)) vT$indexPlot <- as.character(vT$indexPlot) vT$indexLine <- as.character(vT$indexLine) if (nrow(vT)==0) return(data.frame()) x <- c() y <- c() p <- c() l <- c() s <- c() v <- c() for (i in (1:nPoints)) { if (is.element(i,xi)) { ii <- which(xi==i) x <- as.numeric(as.character(c(x,rep(xn[ii],nrow(vT))))) indexTime <- indexVowel + 2 + ((i-1)*5) y <- c(y,vT[,indexTime+varIndex]) p <- c(p,vT$indexPlot) l <- c(l,vT$indexLine) s <- c(s,as.character(vT$speaker)) v <- c(v,as.character(vT$vowel)) } } vT0 <- data.frame(x,p,l,s,v,y) if (is.element("average",input$selGeon0)) { vT0 <- stats::aggregate(y~x+p+l+s+v, data=vT0, FUN=mean) vT0 <- stats::aggregate(y~x+p+l+ v, data=vT0, FUN=mean) } ag <- stats::aggregate(y~x+p+l, data=vT0, FUN=mean) ag$sd <- stats::aggregate(y~x+p+l, data=vT0, FUN=sd)[,4] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(y~x+p+l, data=vT0, FUN=length)[,4] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure0=="SD") { ag$ll <- ag[,4] - z * ag$sd ag$ul <- ag[,4] + z * ag$sd } if (input$selMeasure0=="SE") { ag$ll <- ag[,4] - z * ag$se ag$ul <- ag[,4] + z * ag$se } ag <- ag[order(ag[,2]),] colnames(ag)[1] <- "time" colnames(ag)[2] <- paste(input$replyPlot0, collapse = " ") colnames(ag)[3] <- paste(input$replyLine0, collapse = " ") colnames(ag)[4] <- input$replyVar0 return(ag) } else return(data.frame()) }) output$selScale0 <- renderUI( { selectInput('replyScale0', 'Scale:', optionsScale(), selected = optionsScale()[1], selectize=FALSE, multiple=FALSE, width="100%") }) output$selRef0 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(input$replyScale0)>0) && (input$replyScale0=="ST")) numericInput('replyRef0', 'Reference frequency:', value=50, min=1, step=1, width = "100%") else return(NULL) }) output$selVar0 <- renderUI( { if (is.null(vowelTab())) return(NULL) options <- c("f0","F1","F2","F3") selectInput('replyVar0', 'Variable:', options, selected = options[1], multiple=FALSE, selectize=FALSE, width="100%", size=4) }) output$catXaxis0 <- renderUI( { if (is.null(vowelTab())) return(NULL) selectInput('catXaxis0', 'Select points:', getTimeCode(), multiple=TRUE, selectize=FALSE, width="100%") }) output$selLine0 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyLine0', 'Color variable:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catLine0 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyLine0)>0) options <- unique(fuseCols(vowelTab(),input$replyLine0)) else options <- NULL selectInput('catLine0', 'Select colors:', options, multiple=TRUE, selectize=FALSE, width="100%") }) output$selPlot0 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyPlot0', 'Panel variable:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catPlot0 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyPlot0)>0) options <- unique(fuseCols(vowelTab(),input$replyPlot0)) else options <- NULL selectInput('catPlot0', 'Select panels:', options, multiple=TRUE, selectize=FALSE, width="100%") }) scaleLab <- function(replyScale) { if (replyScale==" Hz") return("Hz") if (replyScale==" bark I") return("bark") if (replyScale==" bark II") return("bark") if (replyScale==" bark III") return("bark") if (replyScale==" ERB I") return("ERB") if (replyScale==" ERB II") return("ERB") if (replyScale==" ERB III") return("ERB") if (replyScale==" ln") return("ln") if (replyScale==" mel I") return("mel") if (replyScale==" mel II") return("mel") if (replyScale==" ST") return("ST") } scaleLab0 <- function() { return(scaleLab(input$replyScale0)) } plotGraph0 <- function() { if (is.null(vowelSub0()) || (nrow(vowelSub0())==0)) return(NULL) if ((length(input$catPlot0)==0) && ((length(input$catLine0)==0) | (length(input$catLine0)>14))) { vT <- data.frame(x=vowelSub0()$time, y=vowelSub0()[,2], ll=vowelSub0()$ll, ul=vowelSub0()$ul) if (!is.element("smooth", input$selGeon0)) vS <- vT else { vS <- data.frame(stats::spline(vT$x, vT$y, n=nrow(vT)*10)) vS$ll <- stats::spline(vT$x, vT$ll, n=nrow(vT)*10)$y vS$ul <- stats::spline(vT$x, vT$ul, n=nrow(vT)*10)$y } if (is.element("points", input$selGeon0)) Geom_Point <- geom_point(colour="indianred2", size=3) else Geom_Point <- geom_point(colour="indianred2", size=0) graphics::plot(ggplot(data=vT, aes(x, y, group=1)) + geom_line(data=vS, colour="indianred2", linewidth=1) + Geom_Point + geom_ribbon(data=vS, aes(ymin=ll, ymax=ul), alpha=0.2) + ggtitle(input$title0) + scale_x_continuous(breaks = unique(vT$x)) + xlab("relative duration") + ylab(paste0(input$replyVar0," (",scaleLab0(),")")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint0b), family=input$replyFont0b), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67)) } else if ((length(input$catPlot0)>0) && ((length(input$catLine0)==0) | (length(input$catLine0)>14))) { vT <- data.frame(x=vowelSub0()$time, y=vowelSub0()[,3], p=vowelSub0()[,2], ll=vowelSub0()$ll, ul=vowelSub0()$ul) if (!is.element("smooth", input$selGeon0)) vS <- vT else { panels <- unique(vT$p) vS <- data.frame() for (i in 1:length(panels)) { vSsub <- subset(vT, p==panels[i]) vSspl <- data.frame(stats::spline(vSsub$x, vSsub$y, n=nrow(vSsub)*10), p=panels[i]) vSspl$ll <- stats::spline(vSsub$x, vSsub$ll, n=nrow(vSsub)*10)$y vSspl$ul <- stats::spline(vSsub$x, vSsub$ul, n=nrow(vSsub)*10)$y vS <- rbind(vS,vSspl) } vT <- vT[with(vT, order(x, p)), ] vS <- vS[with(vS, order(x, p)), ] } if (is.element("points", input$selGeon0)) Geom_Point <- geom_point(colour="indianred2", size=3) else Geom_Point <- geom_point(colour="indianred2", size=0) graphics::plot(ggplot(data=vT, aes(x, y, group=1)) + geom_line(data=vS, colour="indianred2", linewidth=1) + Geom_Point + geom_ribbon(data=vS, aes(ymin=ll, ymax=ul), alpha=0.2) + ggtitle(input$title0) + scale_x_continuous(breaks = unique(vT$x)) + xlab("relative duration") + ylab(paste0(input$replyVar0," (",scaleLab0(),")")) + facet_wrap(vars(p)) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint0b), family=input$replyFont0b), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67)) } else if ((length(input$catPlot0)==0) && ((length(input$catLine0)>0) & (length(input$catLine0)<=14))) { vT <- data.frame(x=vowelSub0()$time, y=vowelSub0()[,3], l=vowelSub0()[,2], ll=vowelSub0()$ll, ul=vowelSub0()$ul) if (!is.element("smooth", input$selGeon0)) vS <- vT else { lines <- unique(vT$l) vS <- data.frame() for (i in 1:length(lines)) { vSsub <- subset(vT, l==lines[i]) vSspl <- data.frame(stats::spline(vSsub$x, vSsub$y, n=nrow(vSsub)*10), l=lines[i]) vSspl$ll <- stats::spline(vSsub$x, vSsub$ll, n=nrow(vSsub)*10)$y vSspl$ul <- stats::spline(vSsub$x, vSsub$ul, n=nrow(vSsub)*10)$y vS <- rbind(vS,vSspl) } vT <- vT[with(vT, order(x, l)), ] vS <- vS[with(vS, order(x, l)), ] } if (is.element("points", input$selGeon0)) Geom_Point <- geom_point(size=3) else Geom_Point <- geom_point(size=0) graphics::plot(ggplot(data=vT, aes(x, y, group=l, color=l)) + geom_line(data=vS, linewidth=1) + Geom_Point + geom_ribbon(data=vS, aes(x=x, ymin=ll, ymax=ul, fill = l), alpha=0.2, colour=NA) + ggtitle(input$title0) + scale_x_continuous(breaks = unique(vT$x)) + xlab("relative duration") + ylab(paste0(input$replyVar0," (",scaleLab0(),")")) + scale_colour_discrete(name=paste0(paste(input$replyLine0,collapse = " "),"\n")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint0b), family=input$replyFont0b), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'lines'), aspect.ratio =0.67) + guides(fill="none")) } else if ((length(input$catPlot0)>0) && ((length(input$catLine0)>0) & (length(input$catLine0)<=14))) { vT <- data.frame(x=vowelSub0()$time, y=vowelSub0()[,4], p=vowelSub0()[,2], l=vowelSub0()[,3], ll=vowelSub0()$ll, ul=vowelSub0()$ul) if (!is.element("smooth", input$selGeon0)) vS <- vT else { panels <- unique(vT$p) lines <- unique(vT$l) vS <- data.frame() for (i in 1:length(panels)) { for (j in 1:length(lines)) { vSsub <- subset(vT, (p==panels[i]) & (l==lines[j])) if (nrow(vSsub)>0) { vSspl <- data.frame(stats::spline(vSsub$x, vSsub$y, n=nrow(vSsub)*10), p=panels[i], l=lines[j]) vSspl$ll <- stats::spline(vSsub$x, vSsub$ll, n=nrow(vSsub)*10)$y vSspl$ul <- stats::spline(vSsub$x, vSsub$ul, n=nrow(vSsub)*10)$y vS <- rbind(vS,vSspl) } } } vT <- vT[with(vT, order(x, p, l)), ] vS <- vS[with(vS, order(x, p, l)), ] } if (is.element("points", input$selGeon0)) Geom_Point <- geom_point(size=3) else Geom_Point <- geom_point(size=0) graphics::plot(ggplot(data=vT, aes(x, y, group=l, color=l)) + geom_line(data=vS, linewidth=1) + Geom_Point + geom_ribbon(data=vS, aes(x=x, ymin=ll, ymax=ul, fill = l), alpha=0.2, colour=NA) + ggtitle(input$title0) + scale_x_continuous(breaks = unique(vT$x)) + xlab("relative duration") + ylab(paste0(input$replyVar0," (",scaleLab0(),")")) + scale_colour_discrete(name=paste0(paste(input$replyLine0, collapse = " "),"\n")) + facet_wrap(vars(p)) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint0b), family=input$replyFont0b), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'lines'), aspect.ratio =0.67)+ guides(fill="none")) } else {} } res0 <- function() { if (length(input$replySize0b)==0) return( 72) if (input$replySize0b=="tiny" ) return( 54) if (input$replySize0b=="small" ) return( 72) if (input$replySize0b=="normal") return( 90) if (input$replySize0b=="large" ) return(108) if (input$replySize0b=="huge" ) return(144) } observeEvent(input$replySize0b, { output$graph0 <- renderPlot(height = 550, width = 700, res = res0(), { if (length(input$catXaxis0)>0) { plotGraph0() } }) }) output$Graph0 <- renderUI( { plotOutput("graph0", height="627px") }) output$selFormat0a <- renderUI( { options <- c("txt","xlsx") selectInput('replyFormat0a', label=NULL, options, selected = options[2], selectize=FALSE, multiple=FALSE) }) fileName0a <- function() { return(paste0("contoursTable.",input$replyFormat0a)) } output$download0a <- downloadHandler(filename = fileName0a, content = function(file) { if (length(input$catXaxis0)>0) { vT <- vowelSub0() colnames(vT)[which(colnames(vT)=="sd")] <- "standard deviation" colnames(vT)[which(colnames(vT)=="se")] <- "standard error" colnames(vT)[which(colnames(vT)=="n" )] <- "number of observations" colnames(vT)[which(colnames(vT)=="ll")] <- "lower limit" colnames(vT)[which(colnames(vT)=="ul")] <- "upper limit" } else vT <- data.frame() if (input$replyFormat0a=="txt") { utils::write.table(vT, file, sep = "\t", na = "NA", dec = ".", row.names = FALSE, col.names = TRUE) } else if (input$replyFormat0a=="xlsx") { WriteXLS(vT, file, SheetNames = "table", row.names=FALSE, col.names=TRUE, BoldHeaderRow = TRUE, na = "NA", FreezeRow = 1, AdjWidth = TRUE) } else {} }) output$selSize0b <- renderUI( { options <- c("tiny", "small", "normal", "large", "huge") selectInput('replySize0b', label=NULL, options, selected = options[3], selectize=FALSE, multiple=FALSE) }) output$selFont0b <- renderUI( { options <- c("Courier" = "Courier", "Helvetica" = "Helvetica", "Times" = "Times") selectInput('replyFont0b', label=NULL, options, selected = "Helvetica", selectize=FALSE, multiple=FALSE) }) output$selPoint0b <- renderUI( { options <- c(5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,36,40,44,48) selectInput('replyPoint0b', label=NULL, options, selected = 18, selectize=FALSE, multiple=FALSE) }) output$selFormat0b <- renderUI( { options <- c("JPG","PNG","SVG","EPS","PDF","TEX") selectInput('replyFormat0b', label=NULL, options, selected = "PNG", selectize=FALSE, multiple=FALSE) }) fileName0b <- function() { return(paste0("contoursPlot.",input$replyFormat0b)) } output$download0b <- downloadHandler(filename = fileName0b, content = function(file) { grDevices::pdf(NULL) scale <- 72/res0() width <- convertUnit(x=unit(700, "pt"), unitTo="in", valueOnly=TRUE) height <- convertUnit(x=unit(550, "pt"), unitTo="in", valueOnly=TRUE) if ((length(input$catXaxis0)>0) && (nrow(vowelSub0())>0)) plot <- plotGraph0() else plot <- ggplot()+theme_bw() show_modal_spinner() if (input$replyFormat0b=="JPG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="jpeg") else if (input$replyFormat0b=="PNG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="png" ) else if (input$replyFormat0b=="SVG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="svg" ) else if (input$replyFormat0b=="EPS") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_ps ) else if (input$replyFormat0b=="PDF") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_pdf) else if (input$replyFormat0b=="TEX") { tikzDevice::tikz(file=file, width=width, height=height, engine='xetex') print(plot) } else {} grDevices::graphics.off() remove_modal_spinner() }) ########################################################################## replyTimes10 <- reactive(input$replyTimes1) replyTimes1 <- debounce(replyTimes10 , 2000) replyTimesN10 <- reactive(input$replyTimesN1) replyTimesN1 <- debounce(replyTimesN10, 2000) vowelScale1 <- reactive( { return(vowelScale(vowelTab(),input$replyScale1,0)) }) vowelNorm1 <- reactive( { if (length(input$replyNormal1)==0) return(NULL) if (!is.null(replyTimesN1())) replyTimesN <- replyTimesN1() else return(NULL) indexDuration <- grep("^duration$", tolower(colnames(vowelScale1()))) nPoints <- (ncol(vowelScale1()) - indexDuration) / 5 if (max(replyTimesN) > nPoints) replyTimesN <- Round(nPoints/2) else {} vL1 <- vowelLong1(vowelScale1(),replyTimesN) vL2 <- vowelLong2(vL1) vL3 <- vowelLong3(vL1) vL4 <- vowelLong4(vL1) vLD <- vowelLongD(vL1) return(vowelNormF(vowelScale1(), vL1, vL2, vL3, vL4, vLD, input$replyNormal1)) }) vowelSub1 <- reactive( { if ((is.null(vowelNorm1())) || (nrow(vowelNorm1())==0)) return(NULL) vT <- vowelNorm1() vT$indexColor <- fuseCols(vowelNorm1(),input$replyColor1) vT$indexShape <- fuseCols(vowelNorm1(),input$replyShape1) vT$indexPlot <- fuseCols(vowelNorm1(),input$replyPlot1) indexVowel <- grep("^vowel$", colnames(vowelNorm1())) ### check begin nPoints <- (ncol(vowelTab()) - (indexVowel + 1))/5 if (max(as.numeric(replyTimes1()))>nPoints) return(NULL) else if (length(vT$indexColor)==0) return(NULL) else if (length(replyTimes1())>1) {} else if (input$axisZ!="--") {} else if (length(vT$indexShape)==0) return(NULL) else if (length(vT$indexPlot)==0) return(NULL) else {} ### check end if (length(input$catColor1)>0) { vT1 <- data.frame() for (q in (1:length(input$catColor1))) { vT1 <- rbind(vT1, subset(vT, indexColor==input$catColor1[q])) } } else { vT1 <- vT } if (length(input$catShape1)>0) { vT2 <- data.frame() for (q in (1:length(input$catShape1))) { vT2 <- rbind(vT2, subset(vT1, indexShape==input$catShape1[q])) } } else { vT2 <- vT1 } if (length(input$catPlot1)>0) { vT3 <- data.frame() for (q in (1:length(input$catPlot1))) { vT3 <- rbind(vT3, subset(vT2, indexPlot==input$catPlot1[q])) } } else { vT3 <- vT2 } vT <- vT3 ### if (nrow(vT)>0) { vT0 <- data.frame() for (i in (1:length(replyTimes1()))) { Code <- strtoi(replyTimes1()[i]) indexF1 <- indexVowel + 4 + ((Code-1) * 5) indexF2 <- indexVowel + 5 + ((Code-1) * 5) indexF3 <- indexVowel + 6 + ((Code-1) * 5) if (length(input$catColor1)>0) Color <- vT$indexColor else Color <- rep("none",nrow(vT)) if (length(input$catShape1)>0) Shape <- vT$indexShape else Shape <- rep("none",nrow(vT)) if (length(input$catPlot1)>0) Plot <- vT$indexPlot else Plot <- rep("none",nrow(vT)) if (input$axisX=="F1") Xaxis <- vT[,indexF1] if (input$axisX=="F2") Xaxis <- vT[,indexF2] if (input$axisX=="F3") Xaxis <- vT[,indexF3] if (input$axisY=="F1") Yaxis <- vT[,indexF1] if (input$axisY=="F2") Yaxis <- vT[,indexF2] if (input$axisY=="F3") Yaxis <- vT[,indexF3] if (input$axisZ=="--") Zaxis <- 0 if (input$axisZ=="F1") Zaxis <- vT[,indexF1] if (input$axisZ=="F2") Zaxis <- vT[,indexF2] if (input$axisZ=="F3") Zaxis <- vT[,indexF3] if (input$axisX=="--") Xaxis <- 0 if (input$axisY=="--") Yaxis <- 0 if (input$axisZ=="--") Zaxis <- 0 if (any(is.na(Xaxis))) Xaxis <- 0 if (any(is.na(Yaxis))) Yaxis <- 0 if (any(is.na(Zaxis))) Zaxis <- 0 vT0 <- rbind(vT0, data.frame(speaker = vT$speaker , vowel = vT$vowel , color = Color , shape = Shape , plot = Plot , index = rownames(vT), time = i , X = Xaxis, Y = Yaxis, Z = Zaxis)) } if (input$average1 | input$ltf1) vT0 <- stats::aggregate(cbind(X,Y,Z)~speaker+vowel+color+shape+plot+time, data=vT0, FUN=mean) if (input$ltf1) { colnames(vT0)[2] <- "v0wel" colnames(vT0)[1] <- "vowel" vT0$v0wel <- NULL } else vT0$speaker <- NULL vT <- vT0 } else {} ### if ((nrow(vT)>0) & (input$average1 | input$ltf1)) { vT <- stats::aggregate(cbind(X,Y,Z)~vowel+color+shape+plot+time, data=vT, FUN=mean) no <- nrow(stats::aggregate(cbind(X,Y,Z)~vowel+color+shape+plot, data=vT, FUN=mean)) index <- seq(1:no) vT$index <- rep(index,length(replyTimes1())) } ### if (nrow(vT)>0) { vT$vowel <- factor(vT$vowel) vT$color <- factor(vT$color) vT$shape <- factor(vT$shape) vT$plot <- factor(vT$plot) vT$time <- factor(vT$time) vT$index <- factor(vT$index) # utils::write.table(vT, "vT.csv", sep = "\t", row.names = FALSE) return(vT) } else { return(data.frame()) } }) output$selTimes1 <- renderUI( { if (is.null(vowelTab())) return(NULL) timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 checkboxGroupInput('replyTimes1', 'Time points to be shown:', timeCode, selected = Round(nPoints/2), TRUE) }) output$selScale1 <- renderUI( { selectInput('replyScale1', 'Scale:', optionsScale()[1:(length(optionsScale())-1)], selected = optionsScale()[1], selectize=FALSE, multiple=FALSE) }) output$selNormal1 <- renderUI( { if (is.null(vowelTab()) || length(input$replyScale1)==0) return(NULL) onlyF1F2 <- ((input$axisX!="F3") & (input$axisY!="F3") & (input$axisZ!="F3")) selectInput('replyNormal1', 'Normalization:', optionsNormal(vowelTab(), input$replyScale1, TRUE, onlyF1F2), selected = optionsNormal(vowelTab(), input$replyScale1, TRUE, onlyF1F2)[1], selectize=FALSE, multiple=FALSE) }) output$selTimesN <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(input$replyNormal1)>0) && ((input$replyNormal1=="") | (input$replyNormal1==" Peterson") | (input$replyNormal1==" Sussman") | (input$replyNormal1==" Syrdal & Gopal") | (input$replyNormal1==" Thomas & Kendall"))) return(NULL) timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 checkboxGroupInput('replyTimesN1', 'Normalization based on:', timeCode, selected = Round(nPoints/2), TRUE) }) output$manScale <- renderUI( { if (input$axisZ=="--") { checkboxInput("selManual", "min/max", FALSE) } }) output$selF1min <- renderUI( { if ((length(input$selManual)>0) && (input$selManual==TRUE) && (input$axisZ=="--")) { numericInput('replyXmin', 'min. x', value=NULL, step=10, width = "100%") } }) output$selF1max <- renderUI( { if ((length(input$selManual)>0) && (input$selManual==TRUE) && (input$axisZ=="--")) { numericInput('replyXmax', 'max. x', value=NULL, step=10, width = "100%") } }) output$selF2min <- renderUI( { if ((length(input$selManual)>0) && (input$selManual==TRUE) && (input$axisZ=="--")) { numericInput('replyYmin', 'min. y', value=NULL, step=10, width = "100%") } }) output$selF2max <- renderUI( { if ((length(input$selManual)>0) && (input$selManual==TRUE) && (input$axisZ=="--")) { numericInput('replyYmax', 'max. y', value=NULL, step=10, width = "100%") } }) output$selColor1 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[1:(indexVowel-1)])) if (!input$ltf1) options <- c(colnames(vowelTab()[indexVowel]),options) selectInput('replyColor1', 'Color variable:', options, selected=options[1], multiple=TRUE, selectize=FALSE, size=3, width="100%") }) output$catColor1 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyColor1)>0) options <- unique(fuseCols(vowelTab(),input$replyColor1)) else options <- NULL selectInput('catColor1', 'Select colors:', options, multiple=TRUE, selectize = FALSE, size=3, width="100%") }) output$selShape1 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(replyTimes1())==1) && (input$axisZ=="--")) { indexVowel <- grep("^vowel$", colnames(vowelTab())) if (input$geon2 | input$geon3 | input$geon4 | input$geon5) options <- c() else options <- c(colnames(vowelTab()[1:(indexVowel-1)])) if (!input$ltf1) options <- c(colnames(vowelTab()[indexVowel]),options) } else { options <- "none" } selectInput('replyShape1', 'Shape variable:', options, selected = options[1], multiple=TRUE, selectize=FALSE, size=3, width="100%") }) output$catShape1 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(input$replyShape1)>0) && (length(replyTimes1())==1) && (input$axisZ=="--")) { if (input$geon2 | input$geon3 | input$geon4 | input$geon5) options <- NULL else options <- unique(fuseCols(vowelTab(),input$replyShape1)) } else options <- NULL selectInput('catShape1', 'Select shapes:', options, multiple=TRUE, selectize = FALSE, size=3, width="100%") }) output$selPlot1 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (input$axisZ=="--") { indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[1:(indexVowel-1)])) if (!input$ltf1) options <- c(colnames(vowelTab()[indexVowel]),options) } else { options <- "none" } selectInput('replyPlot1', 'Panel variable:', options, selected = options[1], multiple=TRUE, selectize=FALSE, size=3, width="100%") }) output$catPlot1 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(input$replyPlot1)>0) && (input$axisZ=="--")) options <- unique(fuseCols(vowelTab(),input$replyPlot1)) else options <- NULL selectInput('catPlot1', 'Select panels:', options, multiple=TRUE, selectize = FALSE, size=3, width="100%") }) output$selGeon1 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((input$axisZ=="--") && (length(replyTimes1())<=1)) tagList(splitLayout ( cellWidths = c("19%", "17%", "15%", "21%", "19%"), checkboxInput("geon1", "labels" , value = FALSE), checkboxInput("geon2", "cent." , value = FALSE), checkboxInput("geon3", "hull" , value = FALSE), checkboxInput("geon4", "spokes" , value = FALSE), checkboxInput("geon5", "ellipse", value = FALSE) )) else if ((input$axisZ!="--") && (length(replyTimes1())<=1)) tagList(splitLayout ( cellWidths = c("19%", "19%"), checkboxInput("geon1", "labels", value = FALSE), checkboxInput("geon2", "lines" , value = TRUE ) )) else if ((input$axisZ=="--") & (length(replyTimes1())==2)) tagList( checkboxInput("geon1", "labels" , value = FALSE) ) else if ((input$axisZ=="--") & (length(replyTimes1())> 2)) tagList(splitLayout ( cellWidths = c("19%", "46%"), checkboxInput("geon1", "labels" , value = FALSE), checkboxInput("geon6", "smooth trajectories", value = FALSE) )) else if ((input$axisZ!="--") & (length(replyTimes1())>=2)) tagList( checkboxInput("geon6", "smooth trajectories", value = FALSE) ) else {} }) output$selPars <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((input$axisZ=="--") && (length(replyTimes1())==1) && (length(input$geon5)>0) && input$geon5) { tagList(splitLayout ( cellWidths = c("50%", "50%"), numericInput('replyLevel', 'Confidence level:', value=0.95, step=0.01, width = "100%"), selectInput('replyNoise', 'Noise level:', c("\u00B1 0.001 sd", "\u00B1 0.01 sd", "\u00B1 0.1 sd", "\u00B1 0 sd"), selected = "\u00B1 0.001 sd", multiple=FALSE, selectize=FALSE, width="100%") )) } else if (input$axisZ!="--") { tagList(splitLayout ( cellWidths = c("50%", "50%"), numericInput('replyPhi' , 'Angle x-axis:', value=40, step=1, width = "100%"), numericInput('replyTheta', 'Angle z-axis:', value=30, step=1, width = "100%") )) } else return(NULL) }) numColor <- function() { if ((length(input$replyColor1)>0) && (length(input$catColor1)>0)) return(length(input$catColor1)) else return(0) } numShape <- function() { if ((length(input$replyShape1)>0) && (length(input$catShape1)>0)) return(length(input$catShape1)) else return(0) } numAll <- function() { return(numColor()+numShape()) } colPalette <- function(n,grayscale) { if (!grayscale) { labColors <- c("#c87e66","#b58437","#988a00","#709000","#27942e","#00965c","#009482","#008ea3","#0081bd","#386acc","#8d46c8","#b315b1","#bd0088","#b61a51") labPalette <- grDevices::colorRampPalette(labColors, space = "Lab") if (n==1) return(labColors[c(10)]) if (n==2) return(labColors[c(8,14)]) if (n==3) return(labColors[c(5,10,13)]) if (n==4) return(labColors[c(3,7,11,14)]) if (n==5) return(labColors[c(3,5,9,11,14)]) if (n==6) return(labColors[c(2,5,7,10,12,14)]) if (n==7) return(labColors[c(2,4,5,8,10,12,14)]) if (n==8) return(labColors[c(1,3,5,7,9,11,12,14)]) if (n==9) return(labColors[c(1,3,4,6,8,10,11,12,14)]) if (n==10) return(labColors[c(1,3,4,5,7,9,10,11,12,14)]) if (n==11) return(labColors[c(1,2,4,5,6,7,9,10,11,12,14)]) if (n==12) return(labColors[c(1,2,3,4,5,7,8,9,11,12,13,14)]) if (n==13) return(labColors[c(1,2,3,4,5,6,7,8,10,11,12,13,14)]) if (n==14) return(labColors[c(1,2,3,4,5,6,7,8,9,10,11,12,13,14)]) if (n>=15) return(labPalette(n)) } else { return(grDevices::gray(0:(n-1)/n)) } } colPalette1 <- function(n) { return(colPalette(n,input$grayscale1)) } shpPalette <- function() { return(c(19,1,17,2,15,0,18,5,3,4,8)) } scaleLab1 <- function() { return(scaleLab(input$replyScale1)) } plotGraph1 <- function() { if (is.null(vowelSub1()) || (nrow(vowelSub1())==0) | (length(replyTimes1())==0)) return(NULL) if (input$replyNormal1=="") scaleNormalLab <- scaleLab1() else scaleNormalLab <- trimws(input$replyNormal1, "left") if ((length(replyTimes1())==1) && (!(input$geon2 | input$geon3 | input$geon4 | input$geon5)) && (input$axisZ=="--")) { vT <- vowelSub1() if ((numColor()>0) & (numShape()>0) & (numShape()<=11)) { Basis <- ggplot(data=vT, aes(x=X, y=Y, color=color, shape=shape)) + scale_shape_manual(values=shpPalette()) if (input$geon1) Basis <- Basis + geom_point(size=2.5) + geom_text_repel(position="identity", aes(label=vowel), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=5, alpha=1.0, max.overlaps=100) else Basis <- Basis + geom_point(size=2.5) } else if (numColor()>0) { Basis <- ggplot(data=vT, aes(x=X, y=Y, color=color)) if (input$geon1) Basis <- Basis + geom_text(position="identity", aes(label=vowel), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=5, alpha=1.0) else Basis <- Basis + geom_point(size=2.5) } else if ((numShape()>0) & (numShape()<=11)) { Basis <- ggplot(data=vT, aes(x=X, y=Y, shape=shape)) + scale_shape_manual(values=shpPalette()) if (input$geon1) Basis <- Basis + geom_point(size=2.5, colour=colPalette1(1)) + geom_text_repel(position="identity", aes(label=vowel), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=5, alpha=1.0, max.overlaps=100) else Basis <- Basis + geom_point(size=2.5, colour=colPalette1(1)) } else { Basis <- ggplot(data=vT, aes(x=X, y=Y, color=color)) if (input$geon1) Basis <- Basis + geom_text(position="identity", aes(label=vowel), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=5, alpha=1.0) else Basis <- Basis + geom_point(size=2.5) } if (input$geon1 & (!is.null(input$replyColor1) && (length(input$replyColor1)==1) && (input$replyColor1=="vowel"))) Basis <- Basis + guides(colour="none") + labs(shape=paste(input$replyShape1, collapse = " ")) else Basis <- Basis + labs(colour=paste(input$replyColor1, collapse = " "), shape=paste(input$replyShape1, collapse = " ")) if ((length(input$selManual)>0) && (input$selManual==TRUE)) { scaleX <- scale_x_reverse(name=paste0(input$axisX," (",scaleNormalLab,")"), position="top" , limits = c(input$replyXmax, input$replyXmin)) scaleY <- scale_y_reverse(name=paste0(input$axisY," (",scaleNormalLab,")"), position="right", limits = c(input$replyYmax, input$replyYmin)) } else { scaleX <- scale_x_reverse(name=paste0(input$axisX," (",scaleNormalLab,")"), position="top" ) scaleY <- scale_y_reverse(name=paste0(input$axisY," (",scaleNormalLab,")"), position="right") } if (length(input$catPlot1)>0) { Title <- ggtitle(input$title1) Facet <- facet_wrap(~plot) } else { Title <- ggtitle(input$title1) Facet <- facet_null() } if ((numAll()>0) & (numAll()<=18)) Legend <- theme(legend.position="right") else if ((numColor()>0) & (numColor()<=18)) Legend <- guides(shape="none") else if ((numShape()>0) & (numShape()<=11)) Legend <- guides(color="none") else Legend <- theme(legend.position="none") graphics::plot(Basis + scaleX + scaleY + Title + Facet + scale_color_manual(values=colPalette1(length(unique(vT$color)))) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint1b), family=input$replyFont1b), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5,'lines'), aspect.ratio =1) + Legend) } else if ((length(replyTimes1())==1) && (input$geon2 | input$geon3 | input$geon4 | input$geon5) && (input$axisZ=="--")) { vT <- vowelSub1() centers <- stats::aggregate(cbind(X,Y)~color+plot, data=vT, FUN=mean) vT <- vT[order(vT$plot, vT$index, vT$time),] vT$index <- paste0(vT$time,vT$index) if ((input$geon5) & length(input$replyLevel)>0) { if (input$replyNoise == "\u00B1 0.001 sd") replyNoise <- 0.001 if (input$replyNoise == "\u00B1 0.01 sd") replyNoise <- 0.01 if (input$replyNoise == "\u00B1 0.1 sd") replyNoise <- 0.1 if (input$replyNoise == "\u00B1 0 sd") replyNoise <- 0 sdX <- stats::sd(vT$X) * replyNoise sdY <- stats::sd(vT$Y) * replyNoise sdZ <- stats::sd(vT$Z) * replyNoise set.seed(0) noiseX <- stats::runif(nrow(vT), -1*sdX, sdX) noiseY <- stats::runif(nrow(vT), -1*sdY, sdY) noiseZ <- stats::runif(nrow(vT), -1*sdZ, sdZ) vT$X <- vT$X + noiseX vT$Y <- vT$Y + noiseY vT$Z <- vT$Z + noiseZ } Basis <- ggplot(data = vT, aes(x=X, y=Y, fill=color, color=color)) Fill <- geom_blank() if (input$geon1) Points <- geom_text(position="identity", aes(label=vowel), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=5, alpha=0.3) else Points <- geom_blank() if (input$geon2) { if (input$geon4) Centers <- geom_text(data=centers, position="identity", aes(label=color), hjust=0.5, vjust=0.5, family=input$replyFont1b, size= 7, alpha=1.0, color="black") else Centers <- geom_text(data=centers, position="identity", aes(label=color), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=10, alpha=1.0) Legend <- theme(legend.position="none") } else { Centers <- geom_blank() Legend <- theme(legend.position="right") } if (input$geon3) { chulls <- plyr::ddply(vT, plyr::.(color,plot), function(df) df[grDevices::chull(df$X, df$Y), ]) if ((length(unique(vT$color))==1) | (as.character(input$replyColor1)[1]=="vowel")) { Hull <- geom_polygon(data=chulls, aes(x=X, y=Y, group=color, fill=color), alpha=0.1) Fill <- scale_fill_manual(values=colPalette1(length(unique(vT$color)))) } else if (length(unique(vT$color))> 1) { Hull <- geom_polygon(data=chulls, aes(x=X, y=Y, group=color, fill=color), alpha=0 ) Fill <- scale_fill_manual(values=rep("white", length(unique(vT$color)))) } else {} } else { Hull <- geom_blank() } if (input$geon4) { vT0 <- vT for (i in (1:nrow(vT0))) { centersSub <- subset(centers, (centers$color==vT0$color[i]) & (centers$plot==vT0$plot[i])) vT0$X[i] <- centersSub$X vT0$Y[i] <- centersSub$Y } vT0 <- rbind(vT,vT0) vT0 <- vT0[order(vT0$plot, vT0$index, vT0$time),] vT0$index <- paste0(vT0$time,vT0$index) Spokes <- geom_path(data=vT0, aes(group = index), arrow = arrow(ends = "last", length = unit(0, "inches")), size=1.0, alpha=0.3) } else { Spokes <- geom_blank() } if ((input$geon5) & length(input$replyLevel)>0) { if ((input$geon1) | (input$geon3)) Ellipse <- stat_ellipse(position="identity", type="norm", level=input$replyLevel) else { if ((length(unique(vT$color))==1) | (as.character(input$replyColor1)[1]=="vowel")) { Ellipse <- stat_ellipse(position="identity", type="norm", level=input$replyLevel, geom="polygon", alpha=0.3) Fill <- scale_fill_manual(values=colPalette1(length(unique(vT$color)))) } else if (length(unique(vT$color))> 1) { Ellipse <- stat_ellipse(position="identity", type="norm", level=input$replyLevel, geom="polygon", alpha=0 ) Fill <- scale_fill_manual(values=rep("white", length(unique(vT$color)))) } else {} } } else { Ellipse <- geom_blank() } if ((length(input$selManual)>0) && (input$selManual==TRUE)) { scaleX <- scale_x_reverse(name=paste0(input$axisX," (",scaleNormalLab,")"), position="top" , limits = c(input$replyXmax, input$replyXmin)) scaleY <- scale_y_reverse(name=paste0(input$axisY," (",scaleNormalLab,")"), position="right", limits = c(input$replyYmax, input$replyYmin)) } else { scaleX <- scale_x_reverse(name=paste0(input$axisX," (",scaleNormalLab,")"), position="top" ) scaleY <- scale_y_reverse(name=paste0(input$axisY," (",scaleNormalLab,")"), position="right") } if (length(input$catPlot1)>0) { Title <- ggtitle(input$title1) Facet <- facet_wrap(~plot) } else { Title <- ggtitle(input$title1) Facet <- facet_null() } if ((numColor()==0) | (numColor()>18)) { Legend <- theme(legend.position="none") } graphics::plot(Basis + Points + Hull +Spokes + Ellipse + Centers + scaleX + scaleY + Title + Facet + scale_color_manual(values=colPalette1(length(unique(vT$color)))) + Fill + labs(colour=paste(input$replyColor1, collapse = " "), fill=paste(input$replyColor1, collapse = " ")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint1b), family=input$replyFont1b), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5,'lines'), aspect.ratio =1) + Legend) } else if ((length(replyTimes1())>1) && (input$axisZ=="--")) { vT <- vowelSub1()[order(vowelSub1()$index, vowelSub1()$time),] if (input$geon1) vTlab <- subset(vT, time==1) if ((length(input$geon6)>0) && (input$geon6)) { xx <- c() yy <- c() for (i in unique(vT$index)) { vTsub <- subset(vT, index==i) xx <- c(xx, stats::spline(vTsub$time, vTsub$X, n=length(replyTimes1())*10)$y) yy <- c(yy, stats::spline(vTsub$time, vTsub$Y, n=length(replyTimes1())*10)$y) } vT <- splitstackshape::expandRows(vT, 10, count.is.col = F, drop = F) vT$X <- xx vT$Y <- yy } Basis <- ggplot(data=vT, aes(x=X, y=Y, colour=color, label="")) if ((length(input$selManual)>0) && (input$selManual==TRUE)) { scaleX <- scale_x_reverse(name=paste0(input$axisX," (",scaleNormalLab,")"), position="top" , limits = c(input$replyXmax, input$replyXmin)) scaleY <- scale_y_reverse(name=paste0(input$axisY," (",scaleNormalLab,")"), position="right", limits = c(input$replyYmax, input$replyYmin)) } else { scaleX <- scale_x_reverse(name=paste0(input$axisX," (",scaleNormalLab,")"), position="top" ) scaleY <- scale_y_reverse(name=paste0(input$axisY," (",scaleNormalLab,")"), position="right") } if (length(input$catPlot1)>0) { Title <- ggtitle(input$title1) Facet <- facet_wrap(~plot) } else { Title <- ggtitle(input$title1) Facet <- facet_null() } if (input$geon1) Basis <- Basis + geom_text_repel(data=vTlab, position="identity", aes(x=X, y=Y, label=vowel), hjust=0.5, vjust=0.5, family=input$replyFont1b, size=5, alpha=1.0, max.overlaps=100) else geom_blank() if ((numColor()>0) & (numColor()<=18) & !input$geon1) Legend <- theme(legend.position="right") else Legend <- theme(legend.position="none") graphics::plot(Basis + scaleX + scaleY + Title + Facet + geom_path(aes(group = index), arrow = arrow(ends = "last", length = unit(0.1, "inches")), size=0.7) + scale_color_manual(values=colPalette1(length(unique(vT$color)))) + labs(colour=paste(input$replyColor1, collapse = " ")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint1b), family=input$replyFont1b), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5,'lines'), aspect.ratio =1) + Legend ) } else if ((length(replyTimes1())==1) && (input$axisZ!="--")) { vT <- vowelSub1() if (nrow(vT)==1) return(NULL) if ((input$axisX=="F1") | (input$axisX=="F2")) vT$X <- -1 * vT$X if ((input$axisY=="F1") | (input$axisY=="F2")) vT$Y <- -1 * vT$Y if ((input$axisZ=="F1") | (input$axisZ=="F2")) vT$Z <- -1 * vT$Z if (length(unique(vT$Z))==1) { zmin <- mean(vT$Z)-1 zmax <- mean(vT$Z)+1 } else { zmin <- min(vT$Z) zmax <- max(vT$Z) } if (input$geon1) cex <- 0.0 else cex <- 1.0 if (input$geon1) Cex <- 1.0 else Cex <- 0.00001 graphics::par(family = input$replyFont1b) Point <- as.numeric(input$replyPoint1b)/22 if (input$geon2) alpha <- 0.2 else alpha <- 0.0 if ((length(input$replyPhi)==0) || (is.na(input$replyPhi))) Phi <- 40 else Phi <- input$replyPhi if ((length(input$replyPhi)==0) || (is.na(input$replyTheta))) Theta <- 30 else Theta <- input$replyTheta mar <- ((length(unique(vT$color))-1)/length(unique(vT$color)))/2 first <- 1+mar last <- length(unique(vT$color))-mar step <- (last-first)/(length(unique(vT$color))-1) at <- c(first) if (length(unique(vT$color))>2) { for (i in 1:(length(unique(vT$color))-2)) { at <- c(at,first + (i*step)) } } at <- c(at,last) if ((numColor()>1) & (numColor()<=18)) { colvar <- as.integer(as.factor(vT$color)) colkey <- list(at = at, side = 4, addlines = TRUE, length = 0.04*length(unique(vT$color)), width = 0.5, labels = unique(vT$color)) } else { colvar <- F colkey <- FALSE } graphics::par(mar=c(1,2,2.0,4)) scatter3D(x = vT$X, y = vT$Y, z = vT$Z, zlim = c(zmin, zmax), phi = Phi, theta = Theta, bty = "g", type = "h", cex = 0, alpha = alpha, ticktype = "detailed", colvar = colvar, col = colPalette1(length(unique(vT$color))), colkey = FALSE, cex.main = Point * 1.75, cex.lab = Point, cex.axis = Point, main = input$title1, xlab = paste0(input$axisX," (",scaleNormalLab,")"), ylab = paste0(input$axisY," (",scaleNormalLab,")"), zlab = paste0(input$axisZ," (",scaleNormalLab,")"), add = FALSE) scatter3D(x = vT$X, y = vT$Y, z = vT$Z, zlim = c(zmin, zmax), type = "p", pch = 19, cex = cex, alpha = 1, colvar = colvar, col = colPalette1(length(unique(vT$color))), colkey = colkey, add = TRUE) text3D (x = vT$X, y = vT$Y, z = vT$Z, zlim = c(zmin, zmax), cex = Cex, alpha = 1, labels = as.character(vT$vowel), colvar = colvar, col = colPalette1(length(unique(vT$color))), colkey = FALSE, add = TRUE) graphics::par(mar=c(5.1,4.1,4.1,2.1)) } else if ((length(replyTimes1())>1) && (input$axisZ!="--")) { vT <- vowelSub1()[order(vowelSub1()$index, vowelSub1()$time),] if (input$geon6) { xx <- c() yy <- c() zz <- c() for (i in unique(vT$index)) { vTsub <- subset(vT, index==i) xx <- c(xx, stats::spline(vTsub$time, vTsub$X, n=length(replyTimes1())*10)$y) yy <- c(yy, stats::spline(vTsub$time, vTsub$Y, n=length(replyTimes1())*10)$y) zz <- c(zz, stats::spline(vTsub$time, vTsub$Z, n=length(replyTimes1())*10)$y) } vT <- splitstackshape::expandRows(vT, 10, count.is.col = F, drop = F) vT$time <- rep(seq(1, length(replyTimes1())*10), length(unique(vT$index))) vT$X <- xx vT$Y <- yy vT$Z <- zz } if ((input$axisX=="F1") | (input$axisX=="F2")) vT$X <- -1 * vT$X if ((input$axisY=="F1") | (input$axisY=="F2")) vT$Y <- -1 * vT$Y if ((input$axisZ=="F1") | (input$axisZ=="F2")) vT$Z <- -1 * vT$Z if (length(unique(vT$Z))==1) { zmin <- mean(vT$Z)-1 zmax <- mean(vT$Z)+1 } else { zmin <- min(vT$Z) zmax <- max(vT$Z) } graphics::par(family = input$replyFont1b) Point <- as.numeric(input$replyPoint1b)/22 if ((length(input$replyPhi)==0) || (is.na(input$replyPhi))) Phi <- 40 else Phi <- input$replyPhi if ((length(input$replyPhi)==0) || (is.na(input$replyTheta))) Theta <- 30 else Theta <- input$replyTheta mar <- ((length(unique(vT$color))-1)/length(unique(vT$color)))/2 first <- 1+mar last <- length(unique(vT$color))-mar step <- (last-first)/(length(unique(vT$color))-1) at <- c(first) if (length(unique(vT$color))>2) { for (i in 1:(length(unique(vT$color))-2)) { at <- c(at,first + (i*step)) } } at <- c(at,last) if ((numColor()>1) & (numColor()<=18)) { VT <- subset(vT, time==1) colvar <- as.integer(as.factor(vT$color)) ColVar <- as.integer(as.factor(VT$color)) ColKey <- list(at = at, side = 4, addlines = TRUE, length = 0.04*length(unique(VT$color)), width = 0.5, labels = unique(VT$color)) } else { colvar <- F ColVar <- F ColKey <- FALSE } graphics::par(mar=c(1,2,2.0,4)) scatter3D(x = vT$X, y = vT$Y, z = vT$Z, zlim = c(zmin, zmax), phi = Phi, theta = Theta, bty = "g", type = "h", pch = 19, cex = 0, ticktype = "detailed", colvar = colvar, col = colPalette1(length(unique(vT$color))), colkey = FALSE, main = input$title1, cex.main = Point * 1.75, cex.lab = Point, cex.axis = Point, alpha = 0.2, xlab = paste0(input$axisX," (",scaleNormalLab,")"), ylab = paste0(input$axisY," (",scaleNormalLab,")"), zlab = paste0(input$axisZ," (",scaleNormalLab,")"), add = FALSE) nTimes <- length(unique(vT$time)) if (nTimes > 2) { for (i in (2:(nTimes-1))) { vT0 <- subset(vT, time==i-1) vT1 <- subset(vT, time==i) arrows3D(x0 = vT0$X, y0 = vT0$Y, z0 = vT0$Z, x1 = vT1$X, y1 = vT1$Y, z1 = vT1$Z, zlim = c(zmin, zmax), colvar = ColVar, col = colPalette1(length(unique(vT0$color))), colkey = FALSE, code = 0, length = 0.2, type = "triangle", lwd = 2, alpha = 1, add = TRUE) } } vT0 <- subset(vT, time==nTimes-1) vT1 <- subset(vT, time==nTimes ) arrows3D(x0 = vT0$X, y0 = vT0$Y, z0 = vT0$Z, x1 = vT1$X, y1 = vT1$Y, z1 = vT1$Z, zlim = c(zmin, zmax), colvar = ColVar, col = colPalette1(length(unique(vT0$color))), colkey = ColKey, code = 2, length = 0.3, type = "simple", lwd = 2, alpha = 1, add = TRUE) graphics::par(mar=c(5.1,4.1,4.1,2.1)) } else {} } res1 <- function() { if (length(input$replySize1b)==0) return( 72) if (input$replySize1b=="tiny" ) return( 54) if (input$replySize1b=="small" ) return( 72) if (input$replySize1b=="normal") return( 90) if (input$replySize1b=="large" ) return(108) if (input$replySize1b=="huge" ) return(144) } observeEvent(input$replySize1b, { output$graph1 <- renderPlot(height = 550, width = 700, res = res1(), { if (length(replyTimes1())>0) { plotGraph1() } }) }) output$Graph1 <- renderUI( { plotOutput("graph1", height="627px") }) output$selFormat1a <- renderUI( { options <- c("txt","xlsx") selectInput('replyFormat1a', label=NULL, options, selected = options[2], selectize=FALSE, multiple=FALSE) }) fileName1a <- function() { return(paste0("formantsTable.",input$replyFormat1a)) } output$download1a <- downloadHandler(filename = fileName1a, content = function(file) { if (length(replyTimes1())>0) { vT <- vowelSub1() colnames(vT)[which(colnames(vT)=="X")] <- input$axisX colnames(vT)[which(colnames(vT)=="Y")] <- input$axisY colnames(vT)[which(colnames(vT)=="Z")] <- input$axisZ } else vT <- data.frame() if (input$replyFormat1a=="txt") { utils::write.table(vT, file, sep = "\t", na = "NA", dec = ".", row.names = FALSE, col.names = TRUE) } else if (input$replyFormat1a=="xlsx") { WriteXLS(vT, file, SheetNames = "table", row.names=FALSE, col.names=TRUE, BoldHeaderRow = TRUE, na = "NA", FreezeRow = 1, AdjWidth = TRUE) } else {} }) output$selSize1b <- renderUI( { options <- c("tiny", "small", "normal", "large", "huge") selectInput('replySize1b', label=NULL, options, selected = options[3], selectize=FALSE, multiple=FALSE) }) output$selFont1b <- renderUI( { options <- c("Courier" = "Courier", "Helvetica" = "Helvetica", "Times" = "Times") selectInput('replyFont1b', label=NULL, options, selected = "Helvetica", selectize=FALSE, multiple=FALSE) }) output$selPoint1b <- renderUI( { options <- c(5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,36,40,44,48) selectInput('replyPoint1b', label=NULL, options, selected = 18, selectize=FALSE, multiple=FALSE) }) output$selFormat1b <- renderUI( { options <- c("JPG","PNG","SVG","EPS","PDF","TEX") selectInput('replyFormat1b', label=NULL, options, selected = "PNG", selectize=FALSE, multiple=FALSE) }) fileName1b <- function() { return(paste0("formantPlot.",input$replyFormat1b)) } save2D <- function(file) { grDevices::pdf(NULL) scale <- 72/res1() width <- convertUnit(x=unit(700, "pt"), unitTo="in", valueOnly=TRUE) height <- convertUnit(x=unit(550, "pt"), unitTo="in", valueOnly=TRUE) if ((length(replyTimes1())>0) && (nrow(vowelSub1())>0)) plot <- plotGraph1() else plot <- ggplot()+theme_bw() show_modal_spinner() if (input$replyFormat1b=="JPG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="jpeg") else if (input$replyFormat1b=="PNG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="png" ) else if (input$replyFormat1b=="SVG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="svg" ) else if (input$replyFormat1b=="EPS") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_ps ) else if (input$replyFormat1b=="PDF") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_pdf) else if (input$replyFormat1b=="TEX") { tikzDevice::tikz(file=file, width=width, height=height, engine='xetex') print(plot) } else {} grDevices::graphics.off() remove_modal_spinner() } save3D <- function(file) { grDevices::pdf(NULL) scale0 <- 300/res1() width0 <- 700 * scale0 height0 <- 550 * scale0 scale <- 72/res1() width <- convertUnit(x=unit(700, "pt"), unitTo="in", valueOnly=TRUE) * scale height <- convertUnit(x=unit(550, "pt"), unitTo="in", valueOnly=TRUE) * scale show_modal_spinner() if (input$replyFormat1b=="JPG") grDevices::jpeg (file, width = width0, height = height0, pointsize = 12, res = 300) else if (input$replyFormat1b=="PNG") grDevices::png (file, width = width0, height = height0, pointsize = 12, res = 300) else if (input$replyFormat1b=="SVG") grDevices::svg (file, width = width , height = height , pointsize = 12) else if (input$replyFormat1b=="EPS") grDevices ::cairo_ps (file, width = width , height = height , pointsize = 12) else if (input$replyFormat1b=="PDF") grDevices ::cairo_pdf(file, width = width , height = height , pointsize = 12) else if (input$replyFormat1b=="TEX") tikzDevice::tikz (file, width = width , height = height , pointsize = 12, engine='xetex') else {} if ((length(replyTimes1())>0) && (nrow(vowelSub1())>0)) print(plotGraph1()) else graphics::plot.new() grDevices::graphics.off() remove_modal_spinner() } output$download1b <- downloadHandler(filename = fileName1b, content = function(file) { if (input$axisZ=="--") save2D(file) else save3D(file) }) ########################################################################## vowelScale4 <- reactive( { return(vowelScale(vowelTab(),input$replyScale4,0)) }) vowelDyn4 <- reactive( { if (is.null(vowelScale4()) || (nrow(vowelScale4())==0) || (length(input$replyVar4)<1) || (length(input$replyTimes4)<2)) return(NULL) vT <- vowelScale4() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 vT["dynamics"] <- 0 for (i in 1:(length(input$replyTimes4)-1)) { i1 <- as.numeric(input$replyTimes4[i ]) i2 <- as.numeric(input$replyTimes4[i+1]) indexTime1 <- indexVowel + 2 + ((i1-1)*5) indexTime2 <- indexVowel + 2 + ((i2-1)*5) Var <- c("f0","F1","F2","F3") sum <- rep(0,nrow(vT)) for (j in 1:4) { if (is.element(Var[j],input$replyVar4)) { indexVar1 <- indexTime1 + j indexVar2 <- indexTime2 + j sum <- sum + (vT[,indexVar1] - vT[,indexVar2])^2 } } VL <- sqrt(sum) VL_roc <- VL / (vT[,indexTime2] - vT[,indexTime1]) if (input$replyMethod4=="TL") vT$dynamics <- vT$dynamics + VL if (input$replyMethod4=="TL_roc") vT$dynamics <- vT$dynamics + VL_roc } return(vT) }) vowelSub4 <- reactive( { if (is.null(vowelDyn4()) || (nrow(vowelDyn4())==0) || (length(input$catXaxis4)==0)) return(NULL) vT <- vowelDyn4() indexVowel <- grep("^vowel$", colnames(vT)) if (any(is.na(vT[,indexVowel+1]))) vT[,indexVowel+1] <- 0 vT$indexXaxis <- fuseCols(vowelDyn4(),input$replyXaxis4) vT$indexLine <- fuseCols(vowelDyn4(),input$replyLine4) vT$indexPlot <- fuseCols(vowelDyn4(),input$replyPlot4) if (input$selError4=="0%") z <- 0 if (input$selError4=="90%") z <- 1.645 if (input$selError4=="95%") z <- 1.96 if (input$selError4=="99%") z <- 4.575 vT <- subset(vT, is.element(vT$indexXaxis,input$catXaxis4)) if (nrow(vT)==0) return(NULL) if (((length(input$catLine4)==0) | (length(input$catLine4)>14)) && (length(input$catPlot4)==0)) { if (is.element("average",input$selGeon4)) { vT <- data.frame(indexXaxis=vT$indexXaxis, speaker=vT$speaker, vowel=vT$vowel, dynamics=vT$dynamics) vT <- stats::aggregate(dynamics ~ indexXaxis + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(dynamics ~ indexXaxis + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$dynamics ~ vT$indexXaxis, FUN=mean) ag$sd <- stats::aggregate(vT$dynamics ~ vT$indexXaxis, FUN=sd)[,2] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$dynamics ~ vT$indexXaxis, FUN=length)[,2] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure4=="SD") { ag$ll <- ag[,2] - z * ag$sd ag$ul <- ag[,2] + z * ag$sd } if (input$selMeasure4=="SE") { ag$ll <- ag[,2] - z * ag$se ag$ul <- ag[,2] + z * ag$se } ag <- ag[order(ag[,2]),] ag[,1] <- factor(ag[,1], levels=ag[,1]) colnames(ag)[1] <- paste(input$replyXaxis4, collapse = " ") colnames(ag)[2] <- input$replyMethod4 return(ag) } else if (((length(input$catLine4)==0) | (length(input$catLine4)>14)) && (length(input$catPlot4)>0)) { vT <- subset(vT, is.element(vT$indexPlot,input$catPlot4)) if (nrow(vT)==0) return(data.frame()) if (is.element("average",input$selGeon4)) { vT <- data.frame(indexXaxis=vT$indexXaxis, indexPlot=vT$indexPlot, speaker=vT$speaker, vowel=vT$vowel, dynamics=vT$dynamics) vT <- stats::aggregate(dynamics ~ indexXaxis + indexPlot + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(dynamics ~ indexXaxis + indexPlot + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexPlot, FUN=mean) ag$sd <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexPlot, FUN=sd)[,3] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexPlot, FUN=length)[,3] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure4=="SD") { ag$ll <- ag[,3] - z * ag$sd ag$ul <- ag[,3] + z * ag$sd } if (input$selMeasure4=="SE") { ag$ll <- ag[,3] - z * ag$se ag$ul <- ag[,3] + z * ag$se } ag <- ag[order(ag[,3]),] xx <- unique(ag[,1]) ag0 <- data.frame() for (q in (1:length(xx))) { ag0 <- rbind(ag0,ag[ag[,1]==xx[q],]) } ag <- ag0 ag[,1] <- factor(ag[,1], levels=xx) ag[,2] <- as.character(ag[,2]) ag <- ag[order(ag[,2]),] colnames(ag)[1] <- paste(input$replyXaxis4, collapse = " ") colnames(ag)[2] <- paste(input$replyPlot4 , collapse = " ") colnames(ag)[3] <- input$replyMethod4 colnames(ag) <- make.unique(names(ag)) return(ag) } else if (((length(input$catLine4)>0) & (length(input$catLine4)<=14)) && (length(input$catPlot4)==0)) { vT <- subset(vT, is.element(vT$indexLine,input$catLine4)) if (nrow(vT)==0) return(data.frame()) if (is.element("average",input$selGeon4)) { vT <- data.frame(indexXaxis=vT$indexXaxis, indexLine=vT$indexLine, speaker=vT$speaker, vowel=vT$vowel, dynamics=vT$dynamics) vT <- stats::aggregate(dynamics ~ indexXaxis + indexLine + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(dynamics ~ indexXaxis + indexLine + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexLine, FUN=mean) ag$sd <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexLine, FUN=sd)[,3] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexLine, FUN=length)[,3] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure4=="SD") { ag$ll <- ag[,3] - z * ag$sd ag$ul <- ag[,3] + z * ag$sd } if (input$selMeasure4=="SE") { ag$ll <- ag[,3] - z * ag$se ag$ul <- ag[,3] + z * ag$se } ag <- ag[order(ag[,3]),] xx <- unique(ag[,1]) ag0 <- data.frame() for (q in (1:length(xx))) { ag0 <- rbind(ag0,ag[ag[,1]==xx[q],]) } ag <- ag0 ag[,1] <- factor(ag[,1], levels=xx) ag[,2] <- as.character(ag[,2]) colnames(ag)[1] <- paste(input$replyXaxis4, collapse = " ") colnames(ag)[2] <- paste(input$replyLine4 , collapse = " ") colnames(ag)[3] <- input$replyMethod4 colnames(ag) <- make.unique(names(ag)) return(ag) } else if (((length(input$catLine4)>0) & (length(input$catLine4)<=14)) && (length(input$catPlot4)>0)) { vT <- subset(vT, is.element(vT$indexLine,input$catLine4) & is.element(vT$indexPlot,input$catPlot4)) if (nrow(vT)==0) return(data.frame()) if (is.element("average",input$selGeon4)) { vT <- data.frame(indexXaxis=vT$indexXaxis, indexPlot=vT$indexPlot, indexLine=vT$indexLine, speaker=vT$speaker, vowel=vT$vowel, dynamics=vT$dynamics) vT <- stats::aggregate(dynamics ~ indexXaxis + indexPlot + indexLine + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(dynamics ~ indexXaxis + indexPlot + indexLine + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexLine + vT$indexPlot, FUN=mean) ag$sd <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexLine + vT$indexPlot, FUN=sd)[,4] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$dynamics ~ vT$indexXaxis + vT$indexLine + vT$indexPlot, FUN=length)[,4] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure4=="SD") { ag$ll <- ag[,4] - z * ag$sd ag$ul <- ag[,4] + z * ag$sd } if (input$selMeasure4=="SE") { ag$ll <- ag[,4] - z * ag$se ag$ul <- ag[,4] + z * ag$se } ag <- ag[order(ag[,4]),] xx <- unique(ag[,1]) ag0 <- data.frame() for (q in (1:length(xx))) { ag0 <- rbind(ag0,ag[ag[,1]==xx[q],]) } ag <- ag0 ag[,1] <- factor(ag[,1], levels=xx) ag[,2] <- as.character(ag[,2]) ag[,3] <- as.character(ag[,3]) ag <- ag[order(ag[,3]),] colnames(ag)[1] <- paste(input$replyXaxis4, collapse = " ") colnames(ag)[2] <- paste(input$replyLine4 , collapse = " ") colnames(ag)[3] <- paste(input$replyPlot4 , collapse = " ") colnames(ag)[4] <- input$replyMethod4 colnames(ag) <- make.unique(names(ag)) return(ag) } else return(data.frame()) }) output$selScale4 <- renderUI( { selectInput('replyScale4', 'Scale:', optionsScale()[1:(length(optionsScale())-1)], selected = optionsScale()[1], selectize=FALSE, multiple=FALSE) }) output$selMethod4 <- renderUI( { options <- c("Fox & Jacewicz (2009) TL" = "TL", "Fox & Jacewicz (2009) TL_roc" = "TL_roc") selectInput('replyMethod4', 'Method:', options, selected = options[1], selectize=FALSE, multiple=FALSE) }) output$selGraph4 <- renderUI( { if (is.null(vowelTab())) return(NULL) options <- c("Dot plot","Bar chart") selectInput('replyGraph4', 'Select graph type:', options, selected = options[1], selectize=FALSE, multiple=FALSE, width="100%") }) output$selVar4 <- renderUI( { if (is.null(vowelTab())) return(NULL) options <- c("f0","F1","F2","F3") selectInput('replyVar4', 'Variable:', options, selected = character(0), multiple=TRUE, selectize=FALSE, width="100%", size=4) }) output$selTimes4 <- renderUI( { if (is.null(vowelTab())) return(NULL) timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 selectInput('replyTimes4', 'Points:', timeCode, multiple=TRUE, selectize=FALSE, selected = character(0), width="100%") }) output$selXaxis4 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyXaxis4', 'Var. x-axis:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catXaxis4 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyXaxis4)>0) options <- unique(fuseCols(vowelTab(),input$replyXaxis4)) else options <- NULL selectInput('catXaxis4', 'Sel. categ.:', options, multiple=TRUE, selectize = FALSE, width="100%") }) output$selLine4 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) indexVowel <- grep("^vowel$",options) selectInput('replyLine4', 'Color var.:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catLine4 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyLine4)>0) options <- unique(fuseCols(vowelTab(),input$replyLine4)) else options <- NULL selectInput('catLine4', 'Sel. colors:', options, multiple=TRUE, selectize = FALSE, width="100%") }) output$selPlot4 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyPlot4', 'Panel var.:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catPlot4 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyPlot4)>0) options <- unique(fuseCols(vowelTab(),input$replyPlot4)) else options <- NULL selectInput('catPlot4', 'Sel. panels:', options, multiple=TRUE, selectize = FALSE, width="100%") }) scaleLab4 <- function() { return(scaleLab(input$replyScale4)) } plotGraph4 <- function() { if (is.null(vowelSub4()) || (nrow(vowelSub4())==0)) return(NULL) if (input$selError4=="0%") w <- 0 if (input$selError4=="90%") w <- 0.4 if (input$selError4=="95%") w <- 0.4 if (input$selError4=="99%") w <- 0.4 if (is.element("rotate x-axis labels",input$selGeon4)) Angle = 90 else Angle = 0 if (((length(input$catLine4)==0) | (length(input$catLine4)>14)) && (length(input$catPlot4)==0)) { if (input$replyGraph4=="Dot plot") { gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,2], group=1)) + geom_point(colour="indianred2", size=3) + geom_errorbar(colour="indianred2", aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } else if (input$replyGraph4=="Bar chart") { gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,2])) + geom_bar(stat="identity", colour="black", fill="indianred2", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } } else if (((length(input$catLine4)==0) | (length(input$catLine4)>14)) && (length(input$catPlot4)>0)) { if (input$replyGraph4=="Dot plot") { gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,3], group=1)) + geom_point(colour="indianred2", size=3) + geom_errorbar(colour="indianred2", aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + facet_wrap(~vowelSub4()[,2]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } else if (input$replyGraph4=="Bar chart") { gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,3])) + geom_bar(stat="identity", colour="black", fill="indianred2", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + facet_wrap(~vowelSub4()[,2]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } else {} } else if (((length(input$catLine4)>0) & (length(input$catLine4)<=14)) && (length(input$catPlot4)==0)) { if (input$replyGraph4=="Dot plot") { pd <- position_dodge(0.7) gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,3], group=vowelSub4()[,2], color=vowelSub4()[,2])) + geom_point(size=3, position=pd) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + scale_colour_discrete(name=paste0(paste(input$replyLine4, collapse = " "),"\n")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'points'), aspect.ratio =0.67) } else if (input$replyGraph4=="Bar chart") { pd <- position_dodge(0.9) gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,3], fill=vowelSub4()[,2])) + geom_bar(position=position_dodge(), stat="identity", colour="black", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + scale_fill_hue(name=paste0(paste(input$replyLine4, collapse = " "),"\n")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'lines'), aspect.ratio =0.67) } else {} if (input$replyXaxis4==input$replyLine4) gp <- gp + theme(axis.title.x=element_blank(), axis.text.x =element_blank(), axis.ticks.x=element_blank()) else {} } else if (((length(input$catLine4)>0) & (length(input$catLine4)<=14)) && (length(input$catPlot4)>0)) { if (input$replyGraph4=="Dot plot") { pd <- position_dodge(0.5) gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,4], group=vowelSub4()[,2], color=vowelSub4()[,2])) + geom_point(size=3, position=pd) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + scale_colour_discrete(name=paste0(paste(input$replyLine4, collapse = " "),"\n")) + facet_wrap(~vowelSub4()[,3]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'points'), aspect.ratio =0.67) } else if (input$replyGraph4=="Bar chart") { pd <- position_dodge(0.9) gp <- ggplot(data=vowelSub4(), aes(x=vowelSub4()[,1], y=vowelSub4()[,4], fill=vowelSub4()[,2])) + geom_bar(position=position_dodge(), stat="identity", colour="black", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title4) + xlab(paste(input$replyXaxis4, collapse = " ")) + ylab(paste0(input$replyMethod4," ", paste(input$replyVar4,collapse = ' ')," (",scaleLab4(),")")) + scale_fill_hue(name=paste0(paste(input$replyLine4, collapse = " "),"\n")) + facet_wrap(~vowelSub4()[,3]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint4b), family=input$replyFont4b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'lines'), aspect.ratio =0.67) } else {} if (input$replyXaxis4==input$replyLine4) gp <- gp + theme(axis.title.x=element_blank(), axis.text.x =element_blank(), axis.ticks.x=element_blank()) else {} } else {} return(graphics::plot(gp)) } res4 <- function() { if (length(input$replySize4b)==0) return( 72) if (input$replySize4b=="tiny" ) return( 54) if (input$replySize4b=="small" ) return( 72) if (input$replySize4b=="normal") return( 90) if (input$replySize4b=="large" ) return(108) if (input$replySize4b=="huge" ) return(144) } observeEvent(input$replySize4b, { output$graph4 <- renderPlot(height = 550, width = 700, res = res4(), { if ((length(input$replyVar4)>0) & (length(input$replyTimes4)>1) & (length(input$catXaxis4)>0)) { plotGraph4() } }) }) output$Graph4 <- renderUI( { plotOutput("graph4", height="627px") }) output$selFormat4a <- renderUI( { options <- c("txt","xlsx") selectInput('replyFormat4a', label=NULL, options, selected = options[2], selectize=FALSE, multiple=FALSE) }) fileName4a <- function() { return(paste0("dynamicsTable.",input$replyFormat4a)) } output$download4a <- downloadHandler(filename = fileName4a, content = function(file) { if ((length(input$replyVar4)>0) & (length(input$replyTimes4)>1) & (length(input$catXaxis4)>0)) { vT <- vowelSub4() colnames(vT)[which(colnames(vT)=="sd")] <- "standard deviation" colnames(vT)[which(colnames(vT)=="se")] <- "standard error" colnames(vT)[which(colnames(vT)=="n" )] <- "number of observations" colnames(vT)[which(colnames(vT)=="ll")] <- "lower limit" colnames(vT)[which(colnames(vT)=="ul")] <- "upper limit" } else vT <- data.frame() if (input$replyFormat4a=="txt") { utils::write.table(vT, file, sep = "\t", na = "NA", dec = ".", row.names = FALSE, col.names = TRUE) } else if (input$replyFormat4a=="xlsx") { WriteXLS(vT, file, SheetNames = "table", row.names=FALSE, col.names=TRUE, BoldHeaderRow = TRUE, na = "NA", FreezeRow = 1, AdjWidth = TRUE) } else {} }) output$selSize4b <- renderUI( { options <- c("tiny", "small", "normal", "large", "huge") selectInput('replySize4b', label=NULL, options, selected = options[3], selectize=FALSE, multiple=FALSE) }) output$selFont4b <- renderUI( { options <- c("Courier" = "Courier", "Helvetica" = "Helvetica", "Times" = "Times") selectInput('replyFont4b', label=NULL, options, selected = "Helvetica", selectize=FALSE, multiple=FALSE) }) output$selPoint4b <- renderUI( { options <- c(5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,36,40,44,48) selectInput('replyPoint4b', label=NULL, options, selected = 18, selectize=FALSE, multiple=FALSE) }) output$selFormat4b <- renderUI( { options <- c("JPG","PNG","SVG","EPS","PDF","TEX") selectInput('replyFormat4b', label=NULL, options, selected = "PNG", selectize=FALSE, multiple=FALSE) }) fileName4b <- function() { return(paste0("dynamicsPlot.",input$replyFormat4b)) } output$download4b <- downloadHandler(filename = fileName4b, content = function(file) { grDevices::pdf(NULL) scale <- 72/res4() width <- convertUnit(x=unit(700, "pt"), unitTo="in", valueOnly=TRUE) height <- convertUnit(x=unit(550, "pt"), unitTo="in", valueOnly=TRUE) if ((length(input$replyVar4)>0) & (length(input$replyTimes4)>1) & (length(input$catXaxis4)>0) && (nrow(vowelSub4())>0)) plot <- plotGraph4() else plot <- ggplot()+theme_bw() show_modal_spinner() if (input$replyFormat4b=="JPG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="jpeg") else if (input$replyFormat4b=="PNG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="png" ) else if (input$replyFormat4b=="SVG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="svg" ) else if (input$replyFormat4b=="EPS") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_ps ) else if (input$replyFormat4b=="PDF") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_pdf) else if (input$replyFormat4b=="TEX") { tikzDevice::tikz(file=file, width=width, height=height, engine='xetex') print(plot) } else {} grDevices::graphics.off() remove_modal_spinner() }) ########################################################################## vowelNorm2 <- reactive( { return(vowelNormD(vowelTab(),input$replyNormal2)) }) vowelSub2 <- reactive( { if (is.null(vowelNorm2()) || (nrow(vowelNorm2())==0) || (length(input$catXaxis2)==0)) return(NULL) vT <- vowelNorm2() indexVowel <- grep("^vowel$", colnames(vT)) if (any(is.na(vT[,indexVowel+1]))) vT[,indexVowel+1] <- 0 vT$indexXaxis <- fuseCols(vowelNorm2(),input$replyXaxis2) vT$indexLine <- fuseCols(vowelNorm2(),input$replyLine2) vT$indexPlot <- fuseCols(vowelNorm2(),input$replyPlot2) if (input$selError2=="0%") z <- 0 if (input$selError2=="90%") z <- 1.645 if (input$selError2=="95%") z <- 1.96 if (input$selError2=="99%") z <- 2.575 vT <- subset(vT, is.element(vT$indexXaxis,input$catXaxis2)) if (nrow(vT)==0) return(NULL) if (((length(input$catLine2)==0) | (length(input$catLine2)>14)) && (length(input$catPlot2)==0)) { if (is.element("average",input$selGeon2)) { vT <- data.frame(indexXaxis=vT$indexXaxis, speaker=vT$speaker, vowel=vT$vowel, duration=vT$duration) vT <- stats::aggregate(duration ~ indexXaxis + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(duration ~ indexXaxis + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$duration ~ vT$indexXaxis, FUN=mean) ag$sd <- stats::aggregate(vT$duration ~ vT$indexXaxis, FUN=sd)[,2] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$duration ~ vT$indexXaxis, FUN=length)[,2] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure2=="SD") { ag$ll <- ag[,2] - z * ag$sd ag$ul <- ag[,2] + z * ag$sd } if (input$selMeasure2=="SE") { ag$ll <- ag[,2] - z * ag$se ag$ul <- ag[,2] + z * ag$se } ag <- ag[order(ag[,2]),] ag[,1] <- factor(ag[,1], levels=ag[,1]) colnames(ag)[1] <- paste(input$replyXaxis2, collapse = " ") colnames(ag)[2] <- "duration" return(ag) } else if (((length(input$catLine2)==0) | (length(input$catLine2)>14)) && (length(input$catPlot2)>0)) { vT <- subset(vT, is.element(vT$indexPlot,input$catPlot2)) if (nrow(vT)==0) return(data.frame()) if (is.element("average",input$selGeon2)) { vT <- data.frame(indexXaxis=vT$indexXaxis, indexPlot=vT$indexPlot, speaker=vT$speaker, vowel=vT$vowel, duration=vT$duration) vT <- stats::aggregate(duration ~ indexXaxis + indexPlot + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(duration ~ indexXaxis + indexPlot + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexPlot, FUN=mean) ag$sd <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexPlot, FUN=sd)[,3] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexPlot, FUN=length)[,3] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure2=="SD") { ag$ll <- ag[,3] - z * ag$sd ag$ul <- ag[,3] + z * ag$sd } if (input$selMeasure2=="SE") { ag$ll <- ag[,3] - z * ag$se ag$ul <- ag[,3] + z * ag$se } ag <- ag[order(ag[,3]),] xx <- unique(ag[,1]) ag0 <- data.frame() for (q in (1:length(xx))) { ag0 <- rbind(ag0,ag[ag[,1]==xx[q],]) } ag <- ag0 ag[,1] <- factor(ag[,1], levels=xx) ag[,2] <- as.character(ag[,2]) ag <- ag[order(ag[,2]),] colnames(ag)[1] <- paste(input$replyXaxis2, collapse = " ") colnames(ag)[2] <- paste(input$replyPlot2 , collapse = " ") colnames(ag)[3] <- "duration" colnames(ag) <- make.unique(names(ag)) return(ag) } else if (((length(input$catLine2)>0) & (length(input$catLine2)<=14)) && (length(input$catPlot2)==0)) { vT <- subset(vT, is.element(vT$indexLine,input$catLine2)) if (nrow(vT)==0) return(data.frame()) if (is.element("average",input$selGeon2)) { vT <- data.frame(indexXaxis=vT$indexXaxis, indexLine=vT$indexLine, speaker=vT$speaker, vowel=vT$vowel, duration=vT$duration) vT <- stats::aggregate(duration ~ indexXaxis + indexLine + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(duration ~ indexXaxis + indexLine + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexLine, FUN=mean) ag$sd <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexLine, FUN=sd)[,3] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexLine, FUN=length)[,3] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure2=="SD") { ag$ll <- ag[,3] - z * ag$sd ag$ul <- ag[,3] + z * ag$sd } if (input$selMeasure2=="SE") { ag$ll <- ag[,3] - z * ag$se ag$ul <- ag[,3] + z * ag$se } ag <- ag[order(ag[,3]),] xx <- unique(ag[,1]) ag0 <- data.frame() for (q in (1:length(xx))) { ag0 <- rbind(ag0,ag[ag[,1]==xx[q],]) } ag <- ag0 ag[,1] <- factor(ag[,1], levels=xx) ag[,2] <- as.character(ag[,2]) colnames(ag)[1] <- paste(input$replyXaxis2, collapse = " ") colnames(ag)[2] <- paste(input$replyLine2 , collapse = " ") colnames(ag)[3] <- "duration" colnames(ag) <- make.unique(names(ag)) return(ag) } else if (((length(input$catLine2)>0) & (length(input$catLine2)<=14)) && (length(input$catPlot2)>0)) { vT <- subset(vT, is.element(vT$indexLine,input$catLine2) & is.element(vT$indexPlot,input$catPlot2)) if (nrow(vT)==0) return(data.frame()) if (is.element("average",input$selGeon2)) { vT <- data.frame(indexXaxis=vT$indexXaxis, indexPlot=vT$indexPlot, indexLine=vT$indexLine, speaker=vT$speaker, vowel=vT$vowel, duration=vT$duration) vT <- stats::aggregate(duration ~ indexXaxis + indexPlot + indexLine + speaker + vowel, data=vT, FUN=mean) vT <- stats::aggregate(duration ~ indexXaxis + indexPlot + indexLine + vowel, data=vT, FUN=mean) } ag <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexLine + vT$indexPlot, FUN=mean) ag$sd <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexLine + vT$indexPlot, FUN=sd)[,4] ag$sd[is.na(ag$sd)] <- 0 ag$n <- stats::aggregate(vT$duration ~ vT$indexXaxis + vT$indexLine + vT$indexPlot, FUN=length)[,4] ag$se <- ag$sd / sqrt(ag$n) if (input$selMeasure2=="SD") { ag$ll <- ag[,4] - z * ag$sd ag$ul <- ag[,4] + z * ag$sd } if (input$selMeasure2=="SE") { ag$ll <- ag[,4] - z * ag$se ag$ul <- ag[,4] + z * ag$se } ag <- ag[order(ag[,4]),] xx <- unique(ag[,1]) ag0 <- data.frame() for (q in (1:length(xx))) { ag0 <- rbind(ag0,ag[ag[,1]==xx[q],]) } ag <- ag0 ag[,1] <- factor(ag[,1], levels=xx) ag[,2] <- as.character(ag[,2]) ag[,3] <- as.character(ag[,3]) ag <- ag[order(ag[,3]),] colnames(ag)[1] <- paste(input$replyXaxis2, collapse = " ") colnames(ag)[2] <- paste(input$replyLine2 , collapse = " ") colnames(ag)[3] <- paste(input$replyPlot2 , collapse = " ") colnames(ag)[4] <- "duration" colnames(ag) <- make.unique(names(ag)) return(ag) } else return(data.frame()) }) output$selNormal2 <- renderUI( { options <- c("None" = "", "Lobanov (1971)" = " Lobanov") selectInput('replyNormal2', 'Normalization:', options, selected = options[1], selectize=FALSE, multiple=FALSE, width="100%") }) output$selGraph2 <- renderUI( { if (is.null(vowelTab())) return(NULL) options <- c("Dot plot","Bar chart") selectInput('replyGraph2', 'Select graph type:', options, selected = options[1], selectize=FALSE, multiple=FALSE, width="100%") }) output$selXaxis2 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyXaxis2', 'Variable x-axis:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catXaxis2 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyXaxis2)>0) options <- unique(fuseCols(vowelTab(),input$replyXaxis2)) else options <- NULL selectInput('catXaxis2', 'Sel. categories:', options, multiple=TRUE, selectize = FALSE, width="100%") }) output$selLine2 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) indexVowel <- grep("^vowel$",options) selectInput('replyLine2', 'Color variable:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catLine2 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyLine2)>0) options <- unique(fuseCols(vowelTab(),input$replyLine2)) else options <- NULL selectInput('catLine2', 'Select colors:', options, multiple=TRUE, selectize = FALSE, width="100%") }) output$selPlot2 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[indexVowel]),colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyPlot2', 'Panel variable:', options, selected = options[1], multiple=TRUE, selectize=FALSE, width="100%") }) output$catPlot2 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyPlot2)>0) options <- unique(fuseCols(vowelTab(),input$replyPlot2)) else options <- NULL selectInput('catPlot2', 'Select panels:', options, multiple=TRUE, selectize = FALSE, width="100%") }) plotGraph2 <- function() { if (is.null(vowelSub2()) || (nrow(vowelSub2())==0)) return(NULL) if (input$selError2=="0%") w <- 0 if (input$selError2=="90%") w <- 0.4 if (input$selError2=="95%") w <- 0.4 if (input$selError2=="99%") w <- 0.4 if (is.element("rotate x-axis labels",input$selGeon2)) Angle = 90 else Angle = 0 if (((length(input$catLine2)==0) | (length(input$catLine2)>14)) && (length(input$catPlot2)==0)) { if (input$replyGraph2=="Dot plot") { gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,2], group=1)) + geom_point(colour="indianred2", size=3) + geom_errorbar(colour="indianred2", aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } else if (input$replyGraph2=="Bar chart") { gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,2])) + geom_bar(stat="identity", colour="black", fill="indianred2", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } } else if (((length(input$catLine2)==0) | (length(input$catLine2)>14)) && (length(input$catPlot2)>0)) { if (input$replyGraph2=="Dot plot") { gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,3], group=1)) + geom_point(colour="indianred2", size=3) + geom_errorbar(colour="indianred2", aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + facet_wrap(~vowelSub2()[,2]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } else if (input$replyGraph2=="Bar chart") { gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,3])) + geom_bar(stat="identity", colour="black", fill="indianred2", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + facet_wrap(~vowelSub2()[,2]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), aspect.ratio =0.67) } else {} } else if (((length(input$catLine2)>0) & (length(input$catLine2)<=14)) && (length(input$catPlot2)==0)) { if (input$replyGraph2=="Dot plot") { pd <- position_dodge(0.7) gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,3], group=vowelSub2()[,2], color=vowelSub2()[,2])) + geom_point(size=3, position=pd) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + scale_colour_discrete(name=paste0(paste(input$replyLine2, collapse = " "),"\n")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'points'), aspect.ratio =0.67) } else if (input$replyGraph2=="Bar chart") { pd <- position_dodge(0.9) gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,3], fill=vowelSub2()[,2])) + geom_bar(position=position_dodge(), stat="identity", colour="black", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + scale_fill_hue(name=paste0(paste(input$replyLine2, collapse = " "),"\n")) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'lines'), aspect.ratio =0.67) } else {} if (input$replyXaxis2==input$replyLine2) gp <- gp + theme(axis.title.x=element_blank(), axis.text.x =element_blank(), axis.ticks.x=element_blank()) else {} } else if (((length(input$catLine2)>0) & (length(input$catLine2)<=14)) && (length(input$catPlot2)>0)) { if (input$replyGraph2=="Dot plot") { pd <- position_dodge(0.5) gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,4], group=vowelSub2()[,2], color=vowelSub2()[,2])) + geom_point(size=3, position=pd) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + scale_colour_discrete(name=paste0(paste(input$replyLine2, collapse = " "),"\n")) + facet_wrap(~vowelSub2()[,3]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'points'), aspect.ratio =0.67) } else if (input$replyGraph2=="Bar chart") { pd <- position_dodge(0.9) gp <- ggplot(data=vowelSub2(), aes(x=vowelSub2()[,1], y=vowelSub2()[,4], fill=vowelSub2()[,2])) + geom_bar(position=position_dodge(), stat="identity", colour="black", size=.3) + geom_errorbar(aes(ymin=ll, ymax=ul), width=w, position=pd) + ggtitle(input$title2) + xlab(paste(input$replyXaxis2, collapse = " ")) + ylab("duration") + scale_fill_hue(name=paste0(paste(input$replyLine2, collapse = " "),"\n")) + facet_wrap(~vowelSub2()[,3]) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint2b), family=input$replyFont2b), axis.text.x =element_text(angle=Angle), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5, 'lines'), aspect.ratio =0.67) } else {} if (input$replyXaxis2==input$replyLine2) gp <- gp + theme(axis.title.x=element_blank(), axis.text.x =element_blank(), axis.ticks.x=element_blank()) else {} } else {} return(graphics::plot(gp)) } res2 <- function() { if (length(input$replySize2b)==0) return( 72) if (input$replySize2b=="tiny" ) return( 54) if (input$replySize2b=="small" ) return( 72) if (input$replySize2b=="normal") return( 90) if (input$replySize2b=="large" ) return(108) if (input$replySize2b=="huge" ) return(144) } observeEvent(input$replySize2b, { output$graph2 <- renderPlot(height = 550, width = 700, res = res2(), { if (length(input$catXaxis2)>0) { plotGraph2() } }) }) output$Graph2 <- renderUI( { plotOutput("graph2", height="627px") }) output$selFormat2a <- renderUI( { options <- c("txt","xlsx") selectInput('replyFormat2a', label=NULL, options, selected = options[2], selectize=FALSE, multiple=FALSE) }) fileName2a <- function() { return(paste0("durationTable.",input$replyFormat2a)) } output$download2a <- downloadHandler(filename = fileName2a, content = function(file) { if (length(input$catXaxis2)>0) { vT <- vowelSub2() colnames(vT)[which(colnames(vT)=="sd")] <- "standard deviation" colnames(vT)[which(colnames(vT)=="se")] <- "standard error" colnames(vT)[which(colnames(vT)=="n" )] <- "number of observations" colnames(vT)[which(colnames(vT)=="ll")] <- "lower limit" colnames(vT)[which(colnames(vT)=="ul")] <- "upper limit" } else vT <- data.frame() if (input$replyFormat2a=="txt") { utils::write.table(vT, file, sep = "\t", na = "NA", dec = ".", row.names = FALSE, col.names = TRUE) } else if (input$replyFormat2a=="xlsx") { WriteXLS(vT, file, SheetNames = "table", row.names=FALSE, col.names=TRUE, BoldHeaderRow = TRUE, na = "NA", FreezeRow = 1, AdjWidth = TRUE) } else {} }) output$selSize2b <- renderUI( { options <- c("tiny", "small", "normal", "large", "huge") selectInput('replySize2b', label=NULL, options, selected = options[3], selectize=FALSE, multiple=FALSE) }) output$selFont2b <- renderUI( { options <- c("Courier" = "Courier", "Helvetica" = "Helvetica", "Times" = "Times") selectInput('replyFont2b', label=NULL, options, selected = "Helvetica", selectize=FALSE, multiple=FALSE) }) output$selPoint2b <- renderUI( { options <- c(5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,36,40,44,48) selectInput('replyPoint2b', label=NULL, options, selected = 18, selectize=FALSE, multiple=FALSE) }) output$selFormat2b <- renderUI( { options <- c("JPG","PNG","SVG","EPS","PDF","TEX") selectInput('replyFormat2b', label=NULL, options, selected = "PNG", selectize=FALSE, multiple=FALSE) }) fileName2b <- function() { return(paste0("durationPlot.",input$replyFormat2b)) } output$download2b <- downloadHandler(filename = fileName2b, content = function(file) { grDevices::pdf(NULL) scale <- 72/res2() width <- convertUnit(x=unit(700, "pt"), unitTo="in", valueOnly=TRUE) height <- convertUnit(x=unit(550, "pt"), unitTo="in", valueOnly=TRUE) if ((length(input$catXaxis2)>0) && (nrow(vowelSub2())>0)) plot <- plotGraph2() else plot <- ggplot()+theme_bw() show_modal_spinner() if (input$replyFormat2b=="JPG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="jpeg") else if (input$replyFormat2b=="PNG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="png" ) else if (input$replyFormat2b=="SVG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="svg" ) else if (input$replyFormat2b=="EPS") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_ps ) else if (input$replyFormat2b=="PDF") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_pdf) else if (input$replyFormat2b=="TEX") { tikzDevice::tikz(file=file, width=width, height=height, engine='xetex') print(plot) } else {} grDevices::graphics.off() remove_modal_spinner() }) ########################################################################## replyTimes30 <- reactive(input$replyTimes3) replyTimes3 <- debounce(replyTimes30 , 2000) replyTimesN30 <- reactive(input$replyTimesN3) replyTimesN3 <- debounce(replyTimesN30, 2000) selFormant30 <- reactive(input$selFormant3) selFormant3 <- debounce(selFormant30 , 2000) vowelScale3 <- reactive( { return(vowelScale(vowelSame(),input$replyScale3,0)) }) vowelNorm3 <- reactive( { if (length(input$replyNormal3)==0) return(NULL) if (!is.null(replyTimesN3())) replyTimesN <- replyTimesN3() else return(NULL) indexDuration <- grep("^duration$", tolower(colnames(vowelScale3()))) nPoints <- (ncol(vowelScale3()) - indexDuration) / 5 if (max(replyTimesN) > nPoints) replyTimesN <- Round(nPoints/2) else {} vL1 <- vowelLong1(vowelScale1(),replyTimesN) vL2 <- vowelLong2(vL1) vL3 <- vowelLong3(vL1) vL4 <- vowelLong4(vL1) vLD <- vowelLongD(vL1) return(vowelNormF(vowelScale3(), vL1, vL2, vL3, vL4, vLD, input$replyNormal3)) }) vowelSubS3 <- reactive( { if (is.null(vowelTab()) || (nrow(vowelTab())==0)) return(NULL) if (length(vowelSame()$vowel)==0) { showNotification("There are no sounds shared by all speakers!", type = "error", duration = 30) return(NULL) } if ((((input$selMetric3=="Euclidean") & (length(input$replyVowel3)<1)) | ((input$selMetric3=="Accdist") & (length(input$replyVowel3)<3))) || (length(replyTimes3())==0) || (length(selFormant3())==0)) return(NULL) req(vowelNorm3()) vT <- vowelNorm3() vT <- subset(vT, is.element(vT$vowel, input$replyVowel3)) indexVowel <- grep("^vowel$", colnames(vowelTab())) nPoints <- (ncol(vowelTab()) - (indexVowel + 1))/5 if ((nrow(vT)>0) && (max(as.numeric(replyTimes3()))<=nPoints)) { vT0 <- data.frame() for (i in (1:length(replyTimes3()))) { Code <- strtoi(replyTimes3()[i]) indexF1 <- indexVowel + 4 + ((Code-1) * 5) indexF2 <- indexVowel + 5 + ((Code-1) * 5) indexF3 <- indexVowel + 6 + ((Code-1) * 5) vT0 <- rbind(vT0, data.frame(vowel = vT$vowel , speaker = vT$speaker , time = i , F1 = vT[,indexF1], F2 = vT[,indexF2], F3 = vT[,indexF3])) } return(stats::aggregate(cbind(F1,F2,F3)~vowel+speaker+time, data=vT0, FUN=mean)) } else return(data.frame()) }) vowelSubG3 <- reactive( { if (is.null(vowelSubS3()) || (nrow(vowelSubS3())==0) || (length(input$replyGrouping3)==0)) return(NULL) vT0 <- unique(data.frame(speaker=vowelNorm3()$speaker,grouping=fuseCols(vowelNorm3(),input$replyGrouping3))) if (max(as.data.frame(table(vT0$speaker))$Freq)==1) { rownames(vT0) <- vT0$speaker vT0$speaker <- NULL vT <- vT0[as.character(vowelSubS3()$speaker),] } else vT <- rep("none",nrow(vowelSubS3())) return(data.frame(grouping=vT)) }) # Distances among speakers vowelCorS1 <- reactive( { if (is.null(vowelSubS3()) || (nrow(vowelSubS3())==0)) return(NULL) vT <- vowelSubS3() vT$speaker <- as.character(vT$speaker) labs <- unique(vT$speaker) nl <- length(labs) corr <- matrix(0, nrow = nl, ncol = nl) rownames(corr) <- labs colnames(corr) <- labs withProgress(value = 0, style = "old", { for (i in (2:nl)) { incProgress(1/nl, message = paste("Calculating ...", format(round2((i/nl)*100)), "%")) iSub <- subset(vT, speaker==labs[i]) for (j in (1:(i-1))) { jSub <- subset(vT, speaker==labs[j]) if (is.element("F1",selFormant3())) difF1 <- (iSub$F1-jSub$F1)^2 if (is.element("F2",selFormant3())) difF2 <- (iSub$F2-jSub$F2)^2 if (is.element("F3",selFormant3())) difF3 <- (iSub$F3-jSub$F3)^2 sumF <- rep(0, nrow(iSub)) if (is.element("F1",selFormant3())) sumF <- sumF + difF1 if (is.element("F2",selFormant3())) sumF <- sumF + difF2 if (is.element("F3",selFormant3())) sumF <- sumF + difF3 sumF <- sqrt(sumF) corr[i,j] <- mean(sumF) corr[j,i] <- corr[i,j] } } }) for (i in (1:nl)) { corr[i,i] <- 0 } return(corr) }) # Measure distances among vowels per speaker vDist <- function(vTsub) { vTsub$voweltime <- paste(vTsub$vowel,vTsub$time) labs <- unique(vTsub$voweltime) nl <- length(labs) vec <- c() k <- 0 for (i in (2:nl)) { iSub <- subset(vTsub, voweltime==labs[i]) for (j in (1:(i-1))) { jSub <- subset(vTsub, voweltime==labs[j]) k <- k + 1 sqsum <- 0 if (is.element("F1",selFormant3())) sqsum <- sqsum + (iSub$F1-jSub$F1)^2 if (is.element("F2",selFormant3())) sqsum <- sqsum + (iSub$F2-jSub$F2)^2 if (is.element("F3",selFormant3())) sqsum <- sqsum + (iSub$F3-jSub$F3)^2 vec[k] <- sqrt(sqsum) } } return(vec) } # Measure within distances for all speakers wDist <- function(vT) { labs <- unique(vT$speaker) nl <- length(labs) spk <- c() vec <- c() withProgress(value = 0, style = "old", { for (i in (1:nl)) { incProgress(1/nl, message = paste("Calculating part 1/2 ...", format(round2((i/nl)*100)), "%")) iSub <- subset(vT, speaker==labs[i]) iVec <- vDist(iSub) spk <- c(spk,rep(labs[i],length(iVec))) vec <- c(vec,iVec) } }) return(data.frame(speaker=spk,dist=vec)) } # Correlations among speakers vowelCorS2 <- reactive( { if (is.null(vowelSubS3()) || (nrow(vowelSubS3())==0)) return(NULL) vT <- vowelSubS3() vT$speaker <- as.character(vT$speaker) vec <- wDist(vT) labs <- unique(vec$speaker) nl <- length(labs) corr <- matrix(0, nrow = nl, ncol = nl) rownames(corr) <- labs colnames(corr) <- labs withProgress(value = 0, style = "old", { for (i in (2:nl)) { incProgress(1/nl, message = paste("Calculating part 2/2 ...", format(round2((i/nl)*100)), "%")) iVec <- subset(vec, speaker==labs[i])$dist for (j in (1:(i-1))) { jVec <- subset(vec, speaker==labs[j])$dist if ((stats::sd(iVec)>0) && (stats::sd(jVec)>0)) { corr[i,j] <- stats::cor(iVec,jVec) } else corr[i,j] <- 0 corr[j,i] <- corr[i,j] } } }) for (i in (1:nl)) { corr[i,i] <- 1 } return(corr) }) # Compare speakers vowelCorS <- reactive( { if (input$selMetric3=="Euclidean") return(vowelCorS1()) if (input$selMetric3=="Accdist") return(vowelCorS2()) }) # Correlations among speakers of selected groupings vowelCorC <- reactive( { if (is.null(vowelSubG3()) || (nrow(vowelSubG3())==0)) return(NULL) vT <- data.frame(speaker=vowelSubS3()$speaker,grouping=vowelSubG3()) vT <- subset(vT, is.element(vT$grouping,input$catGrouping3)) vT$speaker <- as.character(vT$speaker) labs <- unique(vT$speaker) if (length(labs)<3) return(NULL) return(vowelCorS()[labs,labs]) }) # Correlations among groupings vowelCorG <- reactive( { if (is.null(vowelSubG3()) || (nrow(vowelSubG3())==0)) return(NULL) vT <- data.frame(speaker=vowelSubS3()$speaker,grouping=vowelSubG3()) vT <- subset(vT, is.element(vT$grouping,input$catGrouping3)) vT$speaker <- as.character(vT$speaker) labs <- unique(vT$grouping) nl <- length(labs) if (length(labs)<3) return(NULL) corr <- matrix(0, nrow = nl, ncol = nl) rownames(corr) <- labs colnames(corr) <- labs for (i in (2:nl)) { iSub <- subset(vT, grouping==labs[i]) iLabs <- unique(iSub$speaker) for (j in (1:(i-1))) { jSub <- subset(vT, grouping==labs[j]) jLabs <- unique(jSub$speaker) subVowelCorC <- vowelCorC()[iLabs,jLabs] corr[i,j] <- mean(subVowelCorC) corr[j,i] <- corr[i,j] } } for (i in (1:nl)) corr[i,i] <- 1 return(corr) }) # Measure correlations vowelCor3 <- reactive( { if (is.null(vowelSubS3()) || (nrow(vowelSubS3())==0) || is.null(vowelSubG3()) || (nrow(vowelSubG3())==0)) return(NULL) if (!input$summarize3) vowelCor <- vowelCorC() else vowelCor <- vowelCorG() if (!is.null(vowelCor) && (nrow(vowelCor)>0) && (stats::sd(vowelCor)>0)) return(vowelCor) else return(NULL) }) # Measure distances vowelDiff3 <- reactive( { if (is.null(vowelCor3()) || (nrow(vowelCor3())==0)) return(NULL) if (input$selMetric3=="Euclidean") return( vowelCor3()) if (input$selMetric3=="Accdist" ) return(1-vowelCor3()) }) vowelDist3 <- reactive( { if (is.null(vowelDiff3()) || (nrow(vowelDiff3())==0)) return(NULL) else return(stats::as.dist(vowelDiff3(), diag=FALSE, upper=FALSE)) }) clusObj <- reactive( { if (input$replyMethod31=="S-L") clus <- stats::hclust(vowelDist3(), method="single") if (input$replyMethod31=="C-L") clus <- stats::hclust(vowelDist3(), method="complete") if (input$replyMethod31=="UPGMA") clus <- stats::hclust(vowelDist3(), method="average") if (input$replyMethod31=="WPGMA") clus <- stats::hclust(vowelDist3(), method="mcquitty") if (input$replyMethod31=="Ward") clus <- stats::hclust(vowelDist3(), method="ward.D2") return(clus) }) getPerplexity <- function() { if (nrow(vowelCor3()) < 91) return((nrow(vowelCor3())-1) %/% 3) else return(30) } multObj <- reactive( { if (input$replyMethod32=="Classical") { fit <- stats::cmdscale(vowelDist3(), eig=TRUE, k=2) coords <- as.data.frame(fit$points) } if (input$replyMethod32=="Kruskal's") { fit <- isoMDS(vowelDist3(), k=2) coords <- as.data.frame(fit$points) } if (input$replyMethod32=="Sammon's") { fit <- sammon(vowelDist3(), k=2) coords <- as.data.frame(fit$points) } if (input$replyMethod32=="t-SNE") { fit <- Rtsne(vowelDist3(), check_duplicates=FALSE, pca=TRUE, perplexity=getPerplexity(), theta=0.5, dims=2) coords <- as.data.frame(fit$Y) } return(coords) }) output$selTimes3 <- renderUI( { if (is.null(vowelTab())) return(NULL) showExclVow() timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 checkboxGroupInput('replyTimes3', 'Time points to be included:', timeCode, selected = Round(nPoints/2), TRUE) }) output$selScale3 <- renderUI( { selectInput('replyScale3', 'Scale:', optionsScale()[1:(length(optionsScale())-1)], selected = optionsScale()[1], selectize=FALSE, multiple=FALSE, width="100%") }) output$selNormal3 <- renderUI( { if (is.null(vowelTab()) || length(input$replyScale3)==0) return(NULL) onlyF1F2 <- !is.element("F3", input$selFormant3) selectInput('replyNormal3', 'Normalization:', optionsNormal(vowelTab(), input$replyScale3, TRUE, onlyF1F2), selected = optionsNormal(vowelTab(), input$replyScale3, TRUE, onlyF1F2)[1], selectize=FALSE, multiple=FALSE) }) output$selTimesN3 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(input$replyNormal3)>0) && ((input$replyNormal3=="") | (input$replyNormal3==" Peterson") | (input$replyNormal3==" Sussman") | (input$replyNormal3==" Syrdal & Gopal") | (input$replyNormal3==" Thomas & Kendall"))) return(NULL) timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 checkboxGroupInput('replyTimesN3', 'Normalization based on:', timeCode, selected = Round(nPoints/2), TRUE) }) output$selVowel3 <- renderUI( { if (is.null(vowelSame())) return(NULL) options <- unique(vowelSame()$vowel) selectInput('replyVowel3', 'Sel. vowels:', options, multiple=TRUE, selectize = FALSE, size=4, width="100%") }) output$selGrouping3 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) options <- c(colnames(vowelTab()[1:(indexVowel-1)])) selectInput('replyGrouping3', 'Sel. variable:', options, selected = character(0), multiple=TRUE, selectize=FALSE, size=4, width="100%") }) output$catGrouping3 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$replyGrouping3)>0) options <- unique(fuseCols(vowelTab(),input$replyGrouping3)) else options <- NULL selectInput('catGrouping3', 'Sel. categories:', options, multiple=TRUE, selectize = FALSE, size=4, width="100%") }) output$selMethod3 <- renderUI( { if (is.null(vowelTab())) return(NULL) if (length(input$selClass3)>0) { if (input$selClass3=="Cluster analysis") radioButtons('replyMethod31', NULL, c("S-L","C-L","UPGMA","WPGMA","Ward"), selected="UPGMA" , TRUE) else if (input$selClass3=="Multidimensional scaling") radioButtons('replyMethod32', NULL, c("Classical","Kruskal's","Sammon's","t-SNE"), selected="Classical", TRUE) else {} } else return(NULL) }) output$selGeon3 <- renderUI( { if (is.null(vowelTab())) return(NULL) if ((length(input$selClass3)>0) && (input$selClass3=="Multidimensional scaling")) checkboxGroupInput("mdsGeon3", "Options: ", c("points","labels","X\u21C4Y","inv. X","inv. Y"), selected=c("points","labels"), inline=TRUE) else return(NULL) }) colPalette3 <- function(n) { return(colPalette(n,input$grayscale3)) } plotClus <- function() { dendro <- dendro_data(stats::as.dendrogram(clusObj()), type = "rectangle") gp <- ggplot(dendro$segments) + geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) speakers <- as.character(label(dendro)$label) lookup <- unique(data.frame(speaker=vowelNorm3()$speaker,grouping=fuseCols(vowelNorm3(),input$replyGrouping3))) rownames(lookup) <- lookup$speaker lookup$speaker <- NULL groupings <- lookup[speakers,] if (length(speakers)>90) fs <- 0.7 else if (length(speakers)>75) fs <- 1 else if (length(speakers)>60) fs <- 2 else if (length(speakers)>45) fs <- 3 else if (length(speakers)>30) fs <- 4 else if (length(speakers)>15) fs <- 5 else if (length(speakers)> 1) fs <- 6 else {} fs <- min(fs, convertUnit(unit(as.numeric(input$replyPoint3b), "pt"), "mm", valueOnly=TRUE)) dendro$labels$label <- paste0(" ",dendro$labels$label) if ((input$replyGrouping3=="speaker") || (length(unique(groupings))==1) || (input$summarize3)) gp <- gp + geom_text (data = dendro$labels, aes(x, y, label = label ), hjust = 0, angle = 0, family=input$replyFont3b, size = fs) else gp <- gp + geom_text (data = dendro$labels, aes(x, y, label = label, colour=groupings), hjust = 0, angle = 0, family=input$replyFont3b, size = fs) gp <- gp + scale_y_reverse(expand = c(0.5, 0)) + scale_color_manual(values=colPalette3(length(unique(groupings)))) + labs(colour=paste0(" ",paste(input$replyGrouping3, collapse = " "),"\n")) + coord_flip() + ggtitle(input$title3) + xlab(NULL) + ylab(NULL) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint3b), family=input$replyFont3b), plot.title =element_text(face="bold", hjust = 0.5), axis.text =element_blank(), axis.ticks =element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), legend.key.size =unit(1.5,'lines')) + guides(color = guide_legend(override.aes = list(linetype = 0, shape=3))) print(gp) } plotMult <- function() { coords <- multObj() if (!is.element("X\u21C4Y", input$mdsGeon3)) { Xlab <- "dimension 1" Ylab <- "dimension 2" } else { colnames(coords)[1] <- "V0" colnames(coords)[2] <- "V1" colnames(coords)[1] <- "V2" Xlab <- "dimension 2" Ylab <- "dimension 1" } if (is.element("inv. X", input$mdsGeon3)) coords$V1 <- -1 * coords$V1 if (is.element("inv. Y", input$mdsGeon3)) coords$V2 <- -1 * coords$V2 speakers <- as.character(rownames(as.matrix(vowelDist3()))) lookup <- unique(data.frame(speaker=vowelNorm3()$speaker,grouping=fuseCols(vowelNorm3(),input$replyGrouping3))) rownames(lookup) <- lookup$speaker lookup$speaker <- NULL groupings <- lookup[speakers,] if (length(speakers)>45) fs <- 3 else if (length(speakers)>30) fs <- 4 else if (length(speakers)>10) fs <- 5 else if (length(speakers)> 1) fs <- 6 else {} fs <- min(fs, convertUnit(unit(as.numeric(input$replyPoint3b), "pt"), "mm", valueOnly=TRUE)) if ((input$replyGrouping3=="speaker") || (length(unique(groupings))==1) || (input$summarize3)) gp <- ggplot(coords, aes(V1, V2, label = rownames(as.matrix(vowelDist3())) )) else gp <- ggplot(coords, aes(V1, V2, label = rownames(as.matrix(vowelDist3())), color=groupings)) if (is.element("points", input$mdsGeon3) & is.element("labels", input$mdsGeon3)) gp <- gp + geom_point(size = 2.0) + geom_text_repel(family=input$replyFont3b, size = fs, show.legend=FALSE, max.overlaps=100) else if (is.element("points", input$mdsGeon3)) gp <- gp + geom_point(size = 2.5) else if (is.element("labels", input$mdsGeon3)) gp <- gp + geom_text (family=input$replyFont3b, size = fs, family=input$replyFont3b) else {} gp <- gp + scale_x_continuous(breaks = 0, limits = c(min(coords$V1-0.01,coords$V2-0.01), max(coords$V1+0.01,coords$V2+0.01))) + scale_y_continuous(breaks = 0, limits = c(min(coords$V1-0.01,coords$V2-0.01), max(coords$V1+0.01,coords$V2+0.01))) + scale_color_manual(values=colPalette3(length(unique(groupings)))) + labs(colour=paste0(" ",paste(input$replyGrouping3, collapse = " "),"\n")) + geom_vline(xintercept = 0, color="darkgrey") + geom_hline(yintercept = 0, color="darkgrey") + ggtitle(input$title3) + xlab(Xlab) + ylab(Ylab) + theme_bw() + theme(text =element_text(size=as.numeric(input$replyPoint3b), family=input$replyFont3b), plot.title =element_text(face="bold", hjust = 0.5), legend.key.size=unit(1.5,'lines'), aspect.ratio =1) print(gp) } plotGraph3 <- function() { if (is.null(vowelDist3())) return(NULL) if (length(input$selClass3)>0) { if ((length(input$replyMethod31)>0) && (input$selClass3=="Cluster analysis" )) plotClus() else if ((length(input$replyMethod32)>0) && (input$selClass3=="Multidimensional scaling")) plotMult() else {} } else return(NULL) } res3 <- function() { if (length(input$replySize3b)==0) return( 72) if (input$replySize3b=="tiny" ) return( 54) if (input$replySize3b=="small" ) return( 72) if (input$replySize3b=="normal") return( 90) if (input$replySize3b=="large" ) return(108) if (input$replySize3b=="huge" ) return(144) } observeEvent(input$replySize3b, { output$graph3 <- renderPlot(height = 550, width = 700, res = res3(), { if ((((input$selMetric3=="Euclidean") & (length(input$replyVowel3)>=1)) | ((input$selMetric3=="Accdist") & (length(input$replyVowel3)>=3))) && (length(input$replyGrouping3)>0) && (length(input$catGrouping3)>0) && (length(replyTimes3())>0) && (length(selFormant3())>0) && (!is.null(vowelCor3()))) { plotGraph3() } }) }) output$Graph3 <- renderUI( { plotOutput("graph3", height="627px") }) mdsDist <- function(coords) { nf <- nrow(coords) dist <- matrix(0, nrow = nf, ncol = nf) nd <- ncol(coords) for (i in 2:nf) { for (j in 1:(i-1)) { sum <- 0 for (k in 1:nd) { sum <- sum + (coords[i,k] - coords[j,k])^2 } dist[i,j] <- sqrt(sum) dist[j,i] <- sqrt(sum) } } for (i in 1:nf) dist[i,i] <- 0 return(stats::as.dist(dist, diag=FALSE, upper=FALSE)) } output$explVar3 <- renderUI( { if (is.null(vowelDist3())) return(NULL) if (length(input$selClass3)>0) { if ((length(input$replyMethod31)>0) && (input$selClass3=="Cluster analysis")) { explVar <- formatC(x=stats::cor(vowelDist3(), stats::cophenetic(clusObj()))^2, digits = 4, format = "f") return(tags$div(HTML(paste0("<font color='black'>","Explained variance: ",explVar,"</font><br><br>")))) } else if ((length(input$replyMethod32)>0) && (input$selClass3=="Multidimensional scaling")) { explVar <- formatC(x=stats::cor(vowelDist3(), mdsDist(multObj()))^2, digits = 4, format = "f") return(tags$div(HTML(paste0("<font color='black'>","Explained variance: ",explVar,"</font><br><br>")))) } else {} } else return(NULL) }) output$selFormat3a <- renderUI( { options <- c("txt","xlsx") selectInput('replyFormat3a', label=NULL, options, selected = options[2], selectize=FALSE, multiple=FALSE) }) fileName3a <- function() { return(paste0("exploreTable.",input$replyFormat3a)) } output$download3a <- downloadHandler(filename = fileName3a, content = function(file) { if ((((input$selMetric3=="Euclidean") & (length(input$replyVowel3)>=1)) | ((input$selMetric3=="Accdist") & (length(input$replyVowel3)>=3))) && (length(input$replyGrouping3)>0) && (length(input$catGrouping3)>0) && (length(replyTimes3())>0) && (length(selFormant3())>0) && (!is.null(vowelDiff3()))) { vT <- data.frame(rownames(vowelDiff3()), vowelDiff3()) colnames(vT) <- c("element", colnames(vowelDiff3())) } else vT <- data.frame() if (input$replyFormat3a=="txt") { utils::write.table(vT, file, sep = "\t", na = "NA", dec = ".", row.names = FALSE, col.names = TRUE) } else if (input$replyFormat3a=="xlsx") { WriteXLS(vT, file, SheetNames = "table", row.names=FALSE, col.names=TRUE, na = "NA", FreezeRow = 1, FreezeCol = 1, AdjWidth = TRUE) } else {} }) output$selSize3b <- renderUI( { options <- c("tiny", "small", "normal", "large", "huge") selectInput('replySize3b', label=NULL, options, selected = options[3], selectize=FALSE, multiple=FALSE) }) output$selFont3b <- renderUI( { options <- c("Courier" = "Courier", "Helvetica" = "Helvetica", "Times" = "Times") selectInput('replyFont3b', label=NULL, options, selected = "Helvetica", selectize=FALSE, multiple=FALSE) }) output$selPoint3b <- renderUI( { options <- c(5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,36,40,44,48) selectInput('replyPoint3b', label=NULL, options, selected = 18, selectize=FALSE, multiple=FALSE) }) output$selFormat3b <- renderUI( { options <- c("JPG","PNG","SVG","EPS","PDF","TEX") selectInput('replyFormat3b', label=NULL, options, selected = "PNG", selectize=FALSE, multiple=FALSE) }) fileName3b <- function() { return(paste0("explorePlot.",input$replyFormat3b)) } output$download3b <- downloadHandler(filename = fileName3b, content = function(file) { grDevices::pdf(NULL) scale <- 72/res3() width <- convertUnit(x=unit(700, "pt"), unitTo="in", valueOnly=TRUE) height <- convertUnit(x=unit(550, "pt"), unitTo="in", valueOnly=TRUE) if ((length(input$replyVowel3)>=3) && (length(input$replyGrouping3)>0) && (length(input$catGrouping3)>0) && (length(replyTimes3())>0) && (length(selFormant3())>0) && (!is.null(vowelDiff3()))) plot <- plotGraph3() else plot <- ggplot()+theme_bw() show_modal_spinner() if (input$replyFormat3b=="JPG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="jpeg") else if (input$replyFormat3b=="PNG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="png" ) else if (input$replyFormat3b=="SVG") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device="svg" ) else if (input$replyFormat3b=="EPS") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_ps ) else if (input$replyFormat3b=="PDF") ggsave(filename=file, plot=plot, scale=scale, width=width, height=height, units="in", dpi=300, device=grDevices::cairo_pdf) else if (input$replyFormat3b=="TEX") { tikzDevice::tikz(file=file, width=width, height=height, engine='xetex') print(plot) } else {} grDevices::graphics.off() remove_modal_spinner() }) ########################################################################## global <- reactiveValues(replyScale5=NULL, replyNormal5=NULL) observeEvent(input$buttonHelp5, { showModal(modalDialog(easyClose = TRUE, fade = FALSE, title = HTML(paste0("<span style='font-weight: bold; font-size: 17px;'>Evaluation of scale conversion and speaker normalization methods</span>")), HTML(paste0("<span style='font-size: 15px;'> This tab is meant to be used in order to find the most suitable combination of a scale conversion method and a speaker normalization method for your data set. Choose the settings and press the Go! button. Be prepared that running the evaluation procedures <b>may take some time</b>, depending on the size of your data set. <br><br> In case the speakers have pronounced different sets of vowels, the procedures are run on the basis of the set of vowels that are found across all speakers. The vowels thus excluded are printed. <br><br> <span style='font-weight: bold;'>Evaluate</span><br> The results are presented as a table where the columns represent the scale conversion methods and the rows the normalization procedures. Each score is shown on a background with a color somewhere in between turquoise and yellow. The more yellow the background is, the better the result. Note that for some tests larger scores represent better results, and for other tests smaller scores represent better results. <br><br> <span style='font-weight: bold;'>Compare</span><br> After having selected the option 'Compare' one can choose to compare either scale conversion methods or speaker normalization methods. When comparing the scale conversion methods, the unnormalized formant measurements are used. When comparing the speaker normalization methods, the raw Hz formant measurements are used. <br><br> For more details about the implementation of the methods that are used in this tab type <span style='font-family: monospace; font-size: 90%;'>vignette('visvow')</span> in the R console and read section 6. <br><br> <span style='font-weight: bold;'>References</span><br> Fabricius, A., Watt, D., & Johnson, D. E. (2009). A comparison of three speaker-intrinsic vowel formant frequency normalization algorithms for sociophonetics. <i>Language Variation and Change</i>, 21(3), 413-435. <br> Adank, P., Smits, R., & Van Hout, R. (2004). A comparison of vowel normalization procedures for language variation research. <i>The Journal of the Acoustical Society of America</i>, 116(5), 3099-3107. <br> </span>")), footer = modalButton("OK") )) }) output$selTimes5 <- renderUI( { if (is.null(vowelTab())) return(NULL) showExclVow() timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 checkboxGroupInput('replyTimes5', 'Time points to be included:', timeCode, selected = Round(nPoints/2), TRUE) }) output$selTimesN5 <- renderUI( { if (is.null(vowelTab())) return(NULL) timeCode <- getTimeCode() indexVowel <- grep("^vowel$", colnames(vowelTab())) nColumns <- ncol(vowelTab()) nPoints <- (nColumns - (indexVowel + 1))/5 checkboxGroupInput('replyTimesN5', 'Normalization based on:', timeCode, selected = Round(nPoints/2), TRUE) }) output$selVars51 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) if (indexVowel > 2) options <- c(colnames(vowelTab()[2:(indexVowel-1)])) else options <- NULL selectInput('replyVars51', 'Anatomic var(s):', options, selected=character(0), multiple=TRUE, selectize=FALSE, size=5, width="100%") }) output$selVars52 <- renderUI( { if (is.null(vowelTab())) return(NULL) indexVowel <- grep("^vowel$", colnames(vowelTab())) if (indexVowel > 2) options <- c(colnames(vowelTab()[2:(indexVowel-1)])) else options <- NULL selectInput('replyVars52', 'Socioling. var(s):', options, selected=character(0), multiple=TRUE, selectize=FALSE, size=5, width="100%") }) emptyF0 <- reactive( { req(vowelTab()) indexVowel <- grep("^vowel$", colnames(vowelTab())) return(sum(vowelTab()[,indexVowel+3]==0)==nrow(vowelTab())) }) emptyF3 <- reactive( { req(vowelTab()) indexVowel <- grep("^vowel$", colnames(vowelTab())) return(sum(vowelTab()[,indexVowel+6]==0)==nrow(vowelTab())) }) output$selF035 <- renderUI( { if (!emptyF0() | !emptyF3()) { tL <- tagList(tags$b("Include:")) if (!emptyF0() & !emptyF3()) return(tagList(tL, splitLayout(cellWidths = 38, checkboxInput("replyF05", "f0", value = FALSE, width = NULL), checkboxInput("replyF35", "F3", value = FALSE, width = NULL)))) else if (!emptyF0()) return(tagList(tL, splitLayout(cellWidths = 38, checkboxInput("replyF05", "f0", value = FALSE, width = NULL)))) else if (!emptyF3()) return(tagList(tL, splitLayout(cellWidths = 38, checkboxInput("replyF35", "F3", value = FALSE, width = NULL)))) else return(NULL) } }) output$getOpts5 <- renderUI( { req(input$selMeth5) if (input$selMeth5=="Evaluate") { return(radioButtons(inputId = 'selProc5', label = 'Procedure:', choices = c("Adank et al. (2004) LDA", "Adank et al. (2004) MANOVA"), selected = "Adank et al. (2004) LDA", inline = FALSE)) } if (input$selMeth5=="Compare") { return(radioButtons(inputId = 'selConv5', label = 'Conversion:', choices = c("Scaling", "Normalization"), selected = "Scaling", inline = FALSE)) } }) output$getEval5 <- renderUI( { if (input$selMeth5=="Evaluate") { return(radioButtons(inputId = 'selEval52', label = 'Method:', choices = c("preserve phonemic variation", "minimize anatomic variation", "preserve sociolinguistic variation"), selected = "preserve phonemic variation", inline = FALSE)) } }) output$goButton <- renderUI( { if (length(unique(vowelTab()$speaker)) > 1) { if (length(vowelSame()$vowel) > 0) return(div(style="text-align: center;", actionButton('getEval', 'Go!'))) else { showNotification("There are no sounds shared by all speakers!", type = "error", duration = 30) return(NULL) } } else { showNotification("You need multiple speakers for this function!", type = "error", duration = 30) return(NULL) } }) vowelScale5 <- reactive( { return(vowelScale(vowelSame(), global$replyScale5, 50)) }) vowelNorm5 <- reactive( { if (!is.null(input$replyTimesN5)) replyTimesN <- input$replyTimesN5 else return(NULL) indexDuration <- grep("^duration$", tolower(colnames(vowelScale5()))) nPoints <- (ncol(vowelScale5()) - indexDuration) / 5 if (max(replyTimesN) > nPoints) replyTimesN <- Round(nPoints/2) else {} vL1 <- vowelLong1(vowelScale5(),replyTimesN) vL2 <- vowelLong2(vL1) vL3 <- vowelLong3(vL1) vL4 <- vowelLong4(vL1) vLD <- vowelLongD(vL1) return(vowelNormF(vowelScale5(), vL1, vL2, vL3, vL4, vLD, global$replyNormal5)) }) vowelSubS5 <- reactive( { if (is.null(vowelNorm5()) || (nrow(vowelNorm5())==0) || (length(input$replyTimes5)==0)) return(NULL) vT <- vowelNorm5() indexVowel <- grep("^vowel$", colnames(vowelTab())) nPoints <- (ncol(vowelTab()) - (indexVowel + 1))/5 if ((nrow(vT)>0) && (max(as.numeric(input$replyTimes5))<=nPoints)) { if ((!is.null(input$replyVars51)) && (length(input$replyVars51) > 0)) { indices <- which(colnames(vT) %in% input$replyVars51) vT$vars1 <- unite(data=vT[,1:(indexVowel-1)], col="all", indices, sep = "_", remove = FALSE)$all } else vT$vars1 <- "none" if ((!is.null(input$replyVars52)) && (length(input$replyVars52) > 0)) { indices <- which(colnames(vT) %in% input$replyVars52) vT$vars2 <- unite(data=vT[,1:(indexVowel-1)], col="all", indices, sep = "_", remove = FALSE)$all } else vT$vars2 <- "none" vT0 <- data.frame() for (i in (1:length(input$replyTimes5))) { Code <- strtoi(input$replyTimes5[i]) indexF0 <- indexVowel + 3 + ((Code-1) * 5) indexF1 <- indexVowel + 4 + ((Code-1) * 5) indexF2 <- indexVowel + 5 + ((Code-1) * 5) indexF3 <- indexVowel + 6 + ((Code-1) * 5) if (any(is.na(vT[,indexF0]))) vT[,indexF0] <- 0 if (any(is.na(vT[,indexF1]))) vT[,indexF1] <- 0 if (any(is.na(vT[,indexF2]))) vT[,indexF2] <- 0 if (any(is.na(vT[,indexF3]))) vT[,indexF3] <- 0 vT0 <- rbind(vT0, data.frame(vowel = vT$vowel , speaker = vT$speaker , time = i , vars1 = vT$vars1 , vars2 = vT$vars2 , f0 = vT[,indexF0], F1 = vT[,indexF1], F2 = vT[,indexF2], F3 = vT[,indexF3])) } return(stats::aggregate(cbind(f0,F1,F2,F3)~vowel+speaker+time+vars1+vars2, data=vT0, FUN=mean)) } else return(data.frame()) }) asPolySet <- function(df, PID) { df$PID <- PID df$POS <- 1:nrow(df) return(df) } perc <- function(yp) { eql <- nrow(subset(yp, yp[,1]==yp[,2])) all <- nrow(yp) return((eql/all)*100) } round2 <- function(x, n=0) { scale<-10^n return(trunc(x*scale+sign(x)*0.5)/scale) } formatMatrix <- function(matrix0, Scale, Normal) { matrix0 <- round2(matrix0, n=3) matrix0 <- as.data.frame(matrix0) matrix0[is.na(matrix0)] <- "-" colnames(matrix0) <- Scale[1:(length(Scale)-1)] matrix0 <- cbind(c("None", as.character(Normal[2:length(Normal)])), matrix0) colnames(matrix0)[1] <- " " return(matrix0) } evalResults <- eventReactive(input$getEval, { req(vowelTab()) if ((!emptyF0()) && (input$replyF05)) replyF05 <- T else replyF05 <- F if ((!emptyF3()) && (input$replyF35)) replyF35 <- T else replyF35 <- F Scale <- unlist(optionsScale()) Normal <- unlist(optionsNormal(vowelTab(), " Hz", !replyF05, !replyF35)) allScalesAllowed <- c("", " Peterson", " Syrdal & Gopal", " Thomas & Kendall", " Gerstman", " Lobanov", " Watt & Fabricius", " Fabricius et al.", " Bigham", " Heeringa & Van de Velde I" , " Heeringa & Van de Velde II", " Johnson") matrix1 <- matrix(NA, nrow = length(Normal), ncol = (length(Scale)-1)) matrix2 <- matrix(NA, nrow = length(Normal), ncol = (length(Scale)-1)) matrix3 <- matrix(NA, nrow = length(Normal), ncol = (length(Scale)-1)) matrix4 <- matrix(NA, nrow = length(Normal), ncol = (length(Scale)-1)) matrix5 <- matrix(NA, nrow = length(Normal), ncol = (length(Scale)-1)) matrix6 <- matrix(NA, nrow = length(Normal), ncol = (length(Scale)-1)) loop <- 0 nLoop <- (length(Scale)-1) * length(Normal) withProgress(value = 0, style = "old", { for (i in 1:(length(Scale)-1)) { global$replyScale5 <- Scale[i] for (j in 1:length(Normal)) { loop <- loop + 1 incProgress((1/nLoop), message = paste("Calculating ...", format(round2((loop/nLoop)*100)), "%")) if ((Scale[i]==" Hz") | is.element(Normal[j], allScalesAllowed)) { global$replyNormal5 <- Normal[j] vT <- vowelSubS5(); if (is.null(vT)) next() if (length(unique(vT$vowel)) > 1) { m1 <- 0 m2 <- 0 times <- sort(unique(vT$time)) for (k in 1:length(times)) { vTsub <- subset(vT, time==times[k]) preds <- c() if (!emptyF0() && input$replyF05 && (sd(vTsub$f0) > 0.000001)) preds <- cbind(preds, vTsub$f0) if (sd(vTsub$F1) > 0.000001) preds <- cbind(preds, vTsub$F1) if (sd(vTsub$F2) > 0.000001) preds <- cbind(preds, vTsub$F2) if (!emptyF3() && input$replyF35 && (sd(vTsub$F3) > 0.000001)) preds <- cbind(preds, vTsub$F3) model <- lda(factor(vTsub$vowel)~preds) p <- predict(model) yp <- cbind(as.character(vTsub$vowel), as.character(p$class)) m1 <- m1 + perc(yp) model <- vegan::adonis2(preds~factor(vTsub$vowel), permutations = 99, method="euclidean", na.rm=TRUE) m2 <- m2 + (100 * model$R2[1]) } matrix1[j,i] <- m1/length(times) matrix2[j,i] <- m2/length(times) } if (length(unique(vT$vars1)) > 1) { m3 <- 0 m4 <- 0 voweltimes <- unique(data.frame(vowel=vT$vowel, time=vT$time)) for (k in 1:nrow(voweltimes)) { vTsub <- subset(vT, (vowel==voweltimes$vowel[k]) & (time==voweltimes$time[k])) preds <- c() if (!emptyF0() && input$replyF05 && (sd(vTsub$f0) > 0.000001)) preds <- cbind(preds, vTsub$f0) if (sd(vTsub$F1) > 0.000001) preds <- cbind(preds, vTsub$F1) if (sd(vTsub$F2) > 0.000001) preds <- cbind(preds, vTsub$F2) if (!emptyF3() && input$replyF35 && (sd(vTsub$F3) > 0.000001)) preds <- cbind(preds, vTsub$F3) model <- lda(factor(vTsub$vars1)~preds) p <- predict(model) yp <- cbind(as.character(vTsub$vars1), as.character(p$class)) m3 <- m3 + perc(yp) model <- vegan::adonis2(preds~factor(vTsub$vars1), permutations = 99, method="euclidean", na.rm=TRUE) m4 <- m4 + (100 * model$R2[1]) } matrix3[j,i] <- m3/nrow(voweltimes) matrix4[j,i] <- m4/nrow(voweltimes) } if (length(unique(vT$vars2)) > 1) { m5 <- 0 m6 <- 0 voweltimes <- unique(data.frame(vowel=vT$vowel, time=vT$time)) for (k in 1:nrow(voweltimes)) { vTsub <- subset(vT, (vowel==voweltimes$vowel[k]) & (time==voweltimes$time[k])) preds <- c() if (!emptyF0() && input$replyF05 && (sd(vTsub$f0) > 0.000001)) preds <- cbind(preds, vTsub$f0) if (sd(vTsub$F1) > 0.000001) preds <- cbind(preds, vTsub$F1) if (sd(vTsub$F2) > 0.000001) preds <- cbind(preds, vTsub$F2) if (!emptyF3() && input$replyF35 && (sd(vTsub$F3) > 0.000001)) preds <- cbind(preds, vTsub$F3) model <- lda(factor(vTsub$vars2)~preds) p <- predict(model) yp <- cbind(as.character(vTsub$vars2), as.character(p$class)) m5 <- m5 + perc(yp) model <- vegan::adonis2(preds~factor(vTsub$vars2), permutations = 99, method="euclidean", na.rm=TRUE) m6 <- m6 + (100 * model$R2[1]) } matrix5[j,i] <- m5/nrow(voweltimes) matrix6[j,i] <- m6/nrow(voweltimes) } } } } }) matrix1 <- formatMatrix(matrix1, Scale, Normal) matrix2 <- formatMatrix(matrix2, Scale, Normal) matrix3 <- formatMatrix(matrix3, Scale, Normal) matrix4 <- formatMatrix(matrix4, Scale, Normal) matrix5 <- formatMatrix(matrix5, Scale, Normal) matrix6 <- formatMatrix(matrix6, Scale, Normal) return(list(matrix1, matrix2, matrix3, matrix4, matrix5, matrix6)) }) showResults1 <- eventReactive(input$getEval, { req(vowelTab()) if ((!emptyF0()) && (input$replyF05)) replyF05 <- T else replyF05 <- F if ((!emptyF3()) && (input$replyF35)) replyF35 <- T else replyF35 <- F Scale <- unlist(optionsScale()) Normal <- unlist(optionsNormal(vowelTab(), " Hz", !replyF05, !replyF35)) matrix0 <- matrix(NA, nrow = (length(Scale)-1), ncol = (length(Scale)-1)) rownames(matrix0) <- Scale[1:(length(Scale)-1)] colnames(matrix0) <- Scale[1:(length(Scale)-1)] loop <- 0 nLoop <- ((length(Scale)-1) * ((length(Scale)-1)-1))/2 global$replyNormal5 <- "" withProgress(value = 0, style = "old", { for (i in 2:(length(Scale)-1)) { global$replyScale5 <- Scale[i] vT1 <- vowelSubS5() for (j in 1:(i-1)) { loop <- loop + 1 incProgress((1/nLoop), message = paste("Calculating ...", format(round2((loop/nLoop)*100)), "%")) global$replyScale5 <- Scale[j] vT2 <- vowelSubS5() if (emptyF3() || !input$replyF35) Cor <- 1-((stats::cor(vT1$F1, vT2$F1) + stats::cor(vT1$F2, vT2$F2))/2) else Cor <- 1-((stats::cor(vT1$F1, vT2$F1) + stats::cor(vT1$F2, vT2$F2) + stats::cor(vT1$F3, vT2$F3))/3) matrix0[i,j] <- Cor matrix0[j,i] <- Cor } } }) for (i in 1:(length(Scale)-1)) { matrix0[i,i] <- 0 } return(matrix0) }) showResults2 <- eventReactive(input$getEval, { req(vowelTab()) if ((!emptyF0()) && (input$replyF05)) replyF05 <- T else replyF05 <- F if ((!emptyF3()) && (input$replyF35)) replyF35 <- T else replyF35 <- F Scale <- unlist(optionsScale()) Normal <- unlist(optionsNormal(vowelTab(), " Hz", !replyF05, !replyF35)) matrix0 <- matrix(NA, nrow = length(Normal), ncol = length(Normal)) rownames(matrix0) <- c(" None", Normal[2:length(Normal)]) colnames(matrix0) <- c(" None", Normal[2:length(Normal)]) global$replyScale5 <- " Hz" loop <- 0 nLoop <- (length(Normal) * (length(Normal)-1))/2 withProgress(value = 0, style = "old", { for (i in 2:length(Normal)) { global$replyNormal5 <- Normal[i] vT1 <- vowelSubS5() for (j in 1:(i-1)) { loop <- loop + 1 incProgress((1/nLoop), message = paste("Calculating ...", format(round2((loop/nLoop)*100)), "%")) global$replyNormal5 <- Normal[j] vT2 <- vowelSubS5() if (emptyF3() || !input$replyF35) Cor <- 1-((stats::cor(vT1$F1, vT2$F1) + stats::cor(vT1$F2, vT2$F2))/2) else Cor <- 1-((stats::cor(vT1$F1, vT2$F1) + stats::cor(vT1$F2, vT2$F2) + stats::cor(vT1$F3, vT2$F3))/3) matrix0[i,j] <- Cor matrix0[j,i] <- Cor } } }) for (i in 1:length(Normal)) { matrix0[i,i] <- 0 } return(matrix0) }) output$table5 <- renderFormattable( { if (length(unique(vowelTab()$speaker)) < 2) return(NULL) req(evalResults()) df <- data.frame() if ((input$selProc5=="Adank et al. (2004) LDA") && (input$selEval52 == "preserve phonemic variation")) { df <- evalResults()[[1]] col1 <- "turquoise" col2 <- "yellow" } if ((input$selProc5=="Adank et al. (2004) LDA") && (input$selEval52 == "minimize anatomic variation")) { df <- evalResults()[[3]] col1 <- "yellow" col2 <- "turquoise" } if ((input$selProc5=="Adank et al. (2004) LDA") && (input$selEval52 == "preserve sociolinguistic variation")) { df <- evalResults()[[5]] col1 <- "turquoise" col2 <- "yellow" } if ((input$selProc5=="Adank et al. (2004) MANOVA") && (input$selEval52 == "preserve phonemic variation")) { df <- evalResults()[[2]] col1 <- "turquoise" col2 <- "yellow" } if ((input$selProc5=="Adank et al. (2004) MANOVA") && (input$selEval52 == "minimize anatomic variation")) { df <- evalResults()[[4]] col1 <- "yellow" col2 <- "turquoise" } if ((input$selProc5=="Adank et al. (2004) MANOVA") && (input$selEval52 == "preserve sociolinguistic variation")) { df <- evalResults()[[6]] col1 <- "turquoise" col2 <- "yellow" } formattable(df, align = rep("l", 11), list(formattable::area() ~ color_tile(col1, col2))) }) output$graph5 <- renderPlot( { req(input$selConv5) if (input$selConv5=="Scaling") clus <- stats::hclust(stats::as.dist(showResults1()), method="average") if (input$selConv5=="Normalization") clus <- stats::hclust(stats::as.dist(showResults2()), method="average") dendro <- dendro_data(stats::as.dendrogram(clus), type = "rectangle") dendro$labels$label <- paste0(" ", dendro$labels$label) rownames(dendro$labels) <- 1:nrow(dendro$labels) gp <- ggplot(dendro$segments) + geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) + geom_text (data = dendro$labels, aes(x, y, label = label), hjust = 0, angle = 0, size = 4, family="Helvetica") + scale_y_reverse(expand = c(0.5, 0)) + coord_flip() + ggtitle('') + xlab(NULL) + ylab(NULL) + theme_bw() + theme(text =element_text(size=22, family="Helvetica"), plot.title =element_text(face="bold", hjust = 0.5), axis.text =element_blank(), axis.ticks =element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + guides(color = guide_legend(override.aes = list(linetype = 0, shape=3))) print(gp) }) output$Graph5 <- renderUI( { if (input$selMeth5=="Evaluate") { fluidPage( style = "padding:0; margin:0; font-size: 59%; font-family: Ubuntu; min-height: 500px;", formattableOutput("table5", height=0) ) } else { fluidPage( style = "padding:0; margin:0;", plotOutput("graph5", height="500px") ) } }) } ) } ################################################################################ long2wide <- function(vT, isLong) { if (isLong) { timepoint <- vT$timepoint vT$timepoint <- NULL indexDuration <- grep("^duration$", tolower(colnames(vT))) ngroups <- (ncol(vT) - indexDuration) / 5 if (ngroups == 1) { freq <- data.frame(table(timepoint)) if (mean(freq$Freq) != round(mean(freq$Freq))) { message("The number of time points is not the same for all cases!") return(invisible(NULL)) } if (!unique((sort(freq$timepoint) == 1:length(freq$timepoint)))) { message("Numbering of time points is not correct!") return(invisible(NULL)) } superIndex <- "" for (i in 1:(indexDuration-1)) { superIndex <- paste0(superIndex, vT[,i]) } ntimepoints <- nrow(freq) if ((nrow(vT)/ntimepoints) > length(unique(superIndex))) { message("Not all cases are uniquely defined!") return(invisible(NULL)) } vT <- vT[order(superIndex, timepoint),] df <- dplyr::filter(vT, ((dplyr::row_number() %% ntimepoints)) == 1) df <- df[, 1:indexDuration] for (g in (1:ntimepoints)) { if (g==ntimepoints) g0 <- 0 else g0 <- g df0 <- dplyr::filter(vT, ((dplyr::row_number() %% ntimepoints)) == g0) df0 <- df0[, (indexDuration+1):(indexDuration+5)] df <- cbind(df, df0) } return(df) } else { message("Cannot have both a variable timepoint and multiple time points in one row!") return(invisible(NULL)) } } else return(vT) } wide2long <- function(vT, isLong) { if (isLong) { indexDuration <- grep("^duration$", tolower(colnames(vT))) ngroups <- (ncol(vT) - indexDuration) / 5 vT$index <- 1:nrow(vT) df <- data.frame() for (g in (1:ngroups)) { df1 <- vT[,1:2] df1$timepoint <- g df1$index <- vT$index df2 <- vT[,3:indexDuration] first <- indexDuration + ((g-1) * 5) + 1 last <- first + 4 df3 <- vT[,first:last] df <- rbind(df, cbind(df1,df2,df3)) } df <- df[order(df$index, df$timepoint),] df$index <- NULL return(df) } else return(vT) } #' @name #' normalizeFormants #' #' @title #' Normalize vowel formants. #' #' @aliases #' normalizeFormants #' #' @description #' Scale and/or normalize formants F1, F2 and F3. #' #' @usage #' normalizeFormants(vowelTab, replyScale, replyNormal, replyTimesN) #' #' @param #' vowelTab A data frame containing acoustic vowel measurements; the format is described at https://www.visiblevowels.org/#help . #' @param #' replyScale Choose from: "Hz", "bark I", "bark II", "bark III", "ERB I", "ERB II", "ERB III", "ln", "mel I", "mel II", "ST". #' @param #' replyNormal Choose from: "none", "Peterson", "Sussman", "Syrdal & Gopal", "Miller", "Thomas & Kendall", "Gerstman", "Lobanov", "Watt & Fabricius", "Fabricius et al.", "Bigham", "Heeringa & Van de Velde I", "Heeringa & Van de Velde II", "Nearey I", "Nearey II", "Barreda & Nearey I", "Barreda & Nearey II", "Labov log-mean I", "Labov log-geomean I", "Labov log-mean II", "Labov log-geomean II", "Johnson". #' @param #' replyTimesN If measurements are provided for multiple time points per vowel, provide the indices of the time points that should be included when descriptives such as minimum, maximum, mean and standard deviation are calculated by some normalization methods; when there is just one time point, give index 1; a set of multiple indices are given as a vector, for example, when there are three indices and you want the first and third index be used, give c(1,3). #' #' @export #' normalizeFormants NULL normalizeFormants <- function(vowelTab = data.frame(), replyScale = "Hz", replyNormal = "none", replyTimesN = c()) { if (nrow(vowelTab) == 0) { message("Error: Input table is missing") return(invisible(NULL)) } if (length(replyTimesN) == 0) { message("Error: Vector of indices of descriptive time points are missing") return(invisible(NULL)) } isLong <- ("timepoint" %in% colnames(vowelTab)) vowelTab <- long2wide(vowelTab,isLong) indexDuration <- grep("^duration$", tolower(colnames(vowelTab))) if (indexDuration > 3) { cnames <- colnames(vowelTab) vowelTab <- data.frame(vowelTab[,1], vowelTab[,3:(indexDuration-1)], vowelTab[,2], vowelTab[,indexDuration:ncol(vowelTab)]) cnames <- c(cnames[1],cnames[3:(indexDuration-1)],cnames[2],cnames[indexDuration:ncol(vowelTab)]) colnames(vowelTab) <- cnames } else {} if ((replyScale=="none") | (replyScale=="")) replyScale <- " Hz" else replyScale <- paste0(" ", replyScale) vowelScale <- vowelScale(vowelTab, replyScale, 0) vL1 <- vowelLong1(vowelScale,replyTimesN) vL2 <- vowelLong2(vL1) vL3 <- vowelLong3(vL1) vL4 <- vowelLong4(vL1) vLD <- vowelLongD(vL1) if ((replyNormal=="none") | (replyNormal=="")) replyNormal <- "" else if (replyNormal=="Labov log-mean I") replyNormal <- " Labov 1" else if (replyNormal=="Labov log-geomean I") replyNormal <- " LABOV 1" else if (replyNormal=="Labov log-mean II") replyNormal <- " Labov 2" else if (replyNormal=="Labov log-geomean II") replyNormal <- " LABOV 2" else replyNormal <- paste0(" ", replyNormal) vowelTab <- vowelNormF(vowelScale, vL1, vL2, vL3, vL4, vLD, replyNormal) if (indexDuration > 3) { cnames <- colnames(vowelTab) vowelTab <- data.frame(vowelTab[,1], vowelTab[,indexDuration-1], vowelTab[,2:(indexDuration-2)], vowelTab[,indexDuration:ncol(vowelTab)]) cnames <- c(cnames[1], cnames[indexDuration-1], cnames[2:(indexDuration-2)], cnames[indexDuration:ncol(vowelTab)]) colnames(vowelTab) <- cnames } else {} vowelTab <- wide2long(vowelTab, isLong) return(vowelTab) } #' @name #' normalizeDuration #' #' @title #' Normalize duration #' #' @aliases #' normalizeDuration #' #' @description #' Normalize duration of vowels. #' #' @usage #' normalizeDuration(vowelTab, replyNormal) #' #' @param #' vowelTab A data frame containing acoustic vowel measurements; the format is described at https://www.visiblevowels.org/#help . #' @param #' replyNormal Choose from: "none", "Lobanov". #' #' @export #' normalizeDuration NULL normalizeDuration <- function(vowelTab = data.frame(), replyNormal = "") { if (nrow(vowelTab) == 0) { message("Error: Input table is missing") return(invisible(NULL)) } isLong <- ("timepoint" %in% colnames(vowelTab)) vowelTab <- long2wide(vowelTab,isLong) indexDuration <- grep("^duration$", tolower(colnames(vowelTab))) if (indexDuration > 3) { cnames <- colnames(vowelTab) vowelTab <- data.frame(vowelTab[,1], vowelTab[,3:(indexDuration-1)], vowelTab[,2], vowelTab[,indexDuration:ncol(vowelTab)]) cnames <- c(cnames[1],cnames[3:(indexDuration-1)],cnames[2],cnames[indexDuration:ncol(vowelTab)]) colnames(vowelTab) <- cnames } else {} if ((replyNormal=="none") | (replyNormal=="")) replyNormal <- "" else replyNormal <- paste0(" ", replyNormal) vowelTab <- vowelNormD(vowelTab,replyNormal) if (indexDuration > 3) { cnames <- colnames(vowelTab) vowelTab <- data.frame(vowelTab[,1], vowelTab[,indexDuration-1], vowelTab[,2:(indexDuration-2)], vowelTab[,indexDuration:ncol(vowelTab)]) cnames <- c(cnames[1], cnames[indexDuration-1], cnames[2:(indexDuration-2)], cnames[indexDuration:ncol(vowelTab)]) colnames(vowelTab) <- cnames } else {} vowelTab <- wide2long(vowelTab, isLong) return(vowelTab) } ################################################################################
/scratch/gouwar.j/cran-all/cranData/visvow/R/visvow.R
#' Simulated normal data #' @format A data frame with 200 rows and 10 variables: #' \describe{ #' \item{a}{variable a} #' \item{b}{variable b} #' \item{c}{variable c} #' \item{d}{variable d} #' \item{e}{variable e} #' \item{f}{variable f} #' \item{g}{variable g} #' \item{h}{variable h} #' \item{i}{variable i} #' \item{j}{variable j} #' } #' @source package author "normal_df" #' Simulated normal data with annotations #' @format A data frame with 200 rows and 10 variables: #' \describe{ #' \item{a}{variable a} #' \item{b}{variable b} #' \item{c}{variable c} #' \item{d}{variable d} #' \item{e}{variable e} #' \item{f}{variable f} #' \item{g}{variable g} #' \item{h}{variable h} #' \item{i}{variable i} #' \item{j}{variable j} #' \item{annot}{annotation column} #' } #' @source package author "normal_annotated" #' Simulated normal data with missing values #' @format A data frame with 200 rows and 10 variables: #' \describe{ #' \item{a}{variable a} #' \item{b}{variable b} #' \item{c}{variable c} #' \item{d}{variable d} #' \item{e}{variable e} #' \item{f}{variable f} #' \item{g}{variable g} #' \item{h}{variable h} #' \item{i}{variable i} #' \item{j}{variable with randomly missing values} #' } #' @source package author "normal_missing" #' Simulated logscaled data #' @format A data frame with 200 rows and 10 variables: #' \describe{ #' \item{a}{variable a} #' \item{b}{variable b} #' \item{c}{variable c} #' \item{d}{variable d} #' \item{e}{variable e} #' \item{f}{variable f} #' \item{g}{variable g} #' \item{h}{variable h} #' \item{i}{variable i} #' \item{j}{variable j} #' } #' @source package author "logscaled_df" #' Simulated binary data #' @format A data frame with 200 rows and 10 variables: #' \describe{ #' \item{a}{variable a} #' \item{b}{variable b} #' \item{c}{variable c} #' \item{d}{variable d} #' \item{e}{variable e} #' \item{f}{variable f} #' \item{g}{variable g} #' \item{h}{variable h} #' \item{i}{variable i} #' \item{j}{variable j} #' } #' @source package author "bin_df"
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/data.R
ui_boxplots <- function() { ns <- NS("boxplots") tabPanel( "Boxplots", value = "boxplots", h5("Use the checkbox to hide clusters in the plots. For datasets witih more than 500 rows, a violin plot will be rendered instead of a boxplot"), verticalLayout( checkboxGroupInput( ns("boxplots_selection"), NULL, inline = TRUE ), bs_accordion(ns("cboxplots")) %>% bs_append("Boxplots", plotOutput( ns("boxplots"), width = "100%", height = "auto" ) %>% withSpinner()) %>% bs_append("Summary table", htmlOutput(ns("summary_table"))) %>% bs_append("Annotation distribution across clusters", plotOutput(ns("annotation_summary"), height = "auto") ) ) %>% shinyhelper::helper(type = "markdown", content = "boxplots_help") ) } server_boxplots <- function(id, selected_data, cluster_labels, cluster_colors, boxplot_annotation) { moduleServer(id, function(input, output, session) { ns <- NS(id) # Check if the clusters change to keep the boxplot UI updated observeEvent(cluster_labels(), { clusters <- as.list(table(cluster_labels())) validate(need(length(clusters) > 0, "Not ready")) updateCheckboxGroupInput( session, "boxplots_selection", choiceNames = paste(names(clusters), clusters, sep = ": "), choiceValues = names(clusters), selected = names(clusters) ) }) df_long <- reactive({ validate(need( length(input$boxplots_selection) > 0, "No clusters selected." )) isolate({ c_labels <- cluster_labels() s_data <- selected_data() }) req(all(input$boxplots_selection %in% c_labels)) annotate_clusters(s_data, c_labels, TRUE, input$boxplots_selection) }) boxplots_height <- reactive({ max(225, ncol(selected_data()) %/% 4 * 225) }) # Calculate boxplots for each cluster, faceting by all_data variables output$boxplots <- renderPlot({ isolate({ shape <- if (nrow(selected_data()) < 500) "boxplot" else "violin" }) facet_boxplot( df_long(), "Cluster", "Value", "Measurement", cluster_colors, shape ) }, height = function() boxplots_height()) output$annotation_summary <- renderPlot({ validate(need(ncol(boxplot_annotation()) > 0, "No annotations were selected")) plot_annotation_dist(boxplot_annotation(), cluster_labels(), input$boxplots_selection) }, height = function() max(200, ncol(boxplot_annotation()) * 150 + 200) ) # Create table showing summary for unscaled data across clusters output$summary_table <- renderText({ validate(need( length(input$boxplots_selection) > 0, "No clusters were selected." )) df_wide <- annotate_clusters(selected_data(), cluster_labels(), FALSE, input$boxplots_selection) # Compute IQR and get median, lower and upper iqr_fn <- function(x) { qt <- stats::quantile(x, c(.25, .5, .75)) paste0(round(qt[2], 2), " (", round(qt[1], 2), "-", round(qt[3],2), ")") } # Compute across all variables grouped by clusters agg_data <- stats::aggregate(df_wide %>% dplyr::select(-.data$Cluster), by = list(df_wide$Cluster), iqr_fn) colnames(agg_data)[1] <- "Cluster" t(agg_data) %>% knitr::kable(caption = "Unscaled median, Q1 and Q3 per cluster", align = "r", "html") %>% kableExtra::kable_styling(full_width = T, position = "left", font_size = 12) %>% kableExtra::column_spec(1, bold = TRUE, extra_css = "position: sticky; background: #FFF") %>% kableExtra::scroll_box(width = "900px") }) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_boxplots.R
ui_distancematrix <- function() { ns <- NS("distancematrix") tabPanel("Distance matrix", value = "distm", bs_accordion("distmap") %>% bs_append( "2D Projection", plotOutput(ns("dmat_projection"), width = "400px", height = "400px" ) %>% withSpinner() ) %>% bs_append( "Heatmap", verticalLayout( plotOutput(ns("dmat_heatmap"), width = "15cm", height = "15cm" ) %>% withSpinner() ) ) %>% shinyhelper::helper(type = "markdown", content = "dmat_help") ) } server_distancematrix <- function(id, dmat, cluster_labels, cluster_colors) { moduleServer(id, function(input, output, session) { output$dmat_projection <- renderCachedPlot({ dmat_projection(dmat(), cluster_labels(), cluster_colors) }, cacheKeyExpr = list(dmat(), cluster_labels())) output$dmat_heatmap <- renderCachedPlot({ dmat_heatmap(dmat()) }, cacheKeyExpr = list(dmat())) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_distancematrix.R
ui_evaluation <- function() { ns <- NS("evaluation") tabPanel( "Evaluation", value = "measures", verticalLayout( fluidRow( column(width = 3, selectizeInput( ns("evaluation_selected"), label = "Select measure", choices = c("silhouette", "dunn") )), column(width = 4, selectizeInput( ns("evaluation_highlight"), "Highlight number of clusters (k):", choices = c( "First minimum" = "firstmin", "Global minimum" = "globalmin", "First maximum" = "firstmax", "Global maximum" = "globalmax" ) ))) %>% shinyhelper::helper(type = "markdown", content = "measures_help"), plotOutput(ns("measure_over_k")) ) ) } server_evaluation <- function(id, distance_matrix, clusters) { moduleServer(id, function(input, output, session) { output$measure_over_k <- renderPlot({ req(input$evaluation_selected) metric_results <- compute_metric(distance_matrix(), clusters(), input$evaluation_selected) validate(need(all(!is.na(metric_results)), "Metric not evaluated for current data")) optimal_k <- optimal_score(metric_results$score, method = input$evaluation_highlight) line_plot(metric_results, "k", "score", optimal_k) }) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_evaluation.R
# Gap statistic computation module ui_gapstat <- function() { ns <- NS("gapstat") tabPanel("Gap stat", value = "gapstat", verticalLayout(fluidRow( column( 3, numericInput( ns("gap_B"), "Bootstrap samples:", value = 500, min = 50, step = 50 ) ), column( 2, actionButton( ns("compute_gap"), "Compute", style = "margin-top: 25px") ), column( 4, selectizeInput( ns("gap_method"), "Optimal k method:", choices = c( "firstSEmax", "Tibs2001SEmax", "globalSEmax", "firstmax", "globalmax" ) ) ) ) %>% shinyhelper::helper(type = "markdown", content = "gap_help"), plotOutput(ns("gap_plot")) %>% withSpinner() ) ) } server_gapstat <- function(id, selected_data, clusters) { moduleServer(id, function(input, output, session) { # Wait for user input instead of computing automatically gap_result <- eventReactive(input$compute_gap, { isolate({ df <- selected_data() clustered_data <- clusters() }) validate(need(input$gap_B > 0, "Bootstrap samples must be greater than 0.")) compute_gapstat(df, clustered_data, input$gap_B) }) output$gap_plot <- renderPlot({ req(gap_result()) gap_table <- gap_result() if (isTruthy(input$gap_method)) { optimal_k <- cluster::maxSE(gap_table$gap, gap_table$SE.sim, method = input$gap_method) } else { optimal_k <- NULL } line_plot(gap_table, "k", "gap", xintercept = optimal_k) + labs(y = "Gap statistic") }) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_gapstat.R
ui_heatmap <- function() { ns <- NS("heatmap") tabPanel("Heatmap", value = "heatmap", verticalLayout( plotOutput( ns("heatmap"), width = "25cm", height = "auto" ), checkboxInput(ns("cluster_features"), label = "Cluster features on heatmap?", value = TRUE), checkboxInput(ns("hide_unselected"), label = "Display unselected features?", value = TRUE), checkboxInput(ns("show_col_names"), label = "Display record IDs labels?", value = FALSE) ) ) } server_heatmap <- function(id, heatmap_annotation, clusters, nclusters, cluster_colors, scaled_data, scaled_unselected_data, scale_flag, distance_method) { moduleServer(id, function(input, output, session) { output$heatmap <- renderPlot({ req(scaled_data()) top_matrix <- t(scaled_data()) # Get the data matching the numeric variables that were not selected # If there are no columns it must be set to NULL if (!is.null(scaled_unselected_data()) & input$hide_unselected) { bottom_matrix <- t(scaled_unselected_data()) } else { bottom_matrix <- NULL } heatmap_clusters <- reorder_dendrograms(clusters(), nclusters(), cluster_colors) plot_cluster_heatmaps( top_matrix, bottom_matrix, heatmap_clusters$dendrogram, heatmap_clusters$ids, heatmap_annotation(), scale_flag(), distance_method(), input$cluster_features, input$show_col_names ) }, height = function() { if (ncol(scaled_data()) > 100) 900 else 700 }) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_heatmap.R
ui_overview <- function() { ns <- NS("overview") tabPanel("Data overview", value = "overview", bs_accordion("overview") %>% bs_append( "Correlation heatmap for selected variables", plotOutput( ns("corr_heatmap"), width = "650px", height = "600px") ) %>% bs_append( "Highly correlated variables", DT::DTOutput(ns("dropped_vars_table"))) %>% bs_append( "Raw data histogram", verticalLayout( selectInput( ns("overview_var"), "Choose variable", choices = NULL), checkboxInput( ns("overview_scale"), "Scale?"), plotOutput( ns("overview_hist"), width = "400px", height = "400px") ) ) %>% shinyhelper::helper(type = "markdown", content = "overview_help") ) } server_overview <- function(id, selected_data, selected_numeric, dropped_variables, apply_scaling) { moduleServer(id, function(input, output, session) { # Correlation heatmap of the selected numeric variables output$corr_heatmap <- renderCachedPlot({ df <- selected_data() correlation_heatmap(df) }, cacheKeyExpr = list(selected_data())) # Table with correlation information of dropped variables output$dropped_vars_table <- DT::renderDT({ validate(need(!is.null(dropped_variables()), "No variables were removed due to strong correlation.")) dropped_variables() }) # Update overview variable list observeEvent(selected_numeric(), { updateSelectInput(session, "overview_var", choices = selected_numeric()) }) # Histograms for selected variables output$overview_hist <- renderPlot({ df <- selected_data() validate(need(input$overview_var %in% colnames(df), "Variable does not exist")) df <- df[, input$overview_var] if (input$overview_scale == TRUE) { df <- as.data.frame(scale_data(df, apply_scaling())) } ggplot(df, aes_string(input$overview_var)) + geom_histogram(bins = 15) }) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_overview.R
ui_params <- function() { ns <- NS("params") tabPanel( "Parameters", value = "parameters", verticalLayout( fluidRow( column(2, style = "margin-top: 25px; margin-bottom: 25px", actionButton(ns("configs_save"), "Save parameters")), column(2, style = "margin-top: 25px; margin-bottom: 25px", actionButton(ns("configs_load"), "Load selected")) ) %>% shinyhelper::helper(type = "markdown", content = "params_help"), fluidRow(DT::DTOutput(ns("configs_table"))) ) ) } server_params <- function(id, distance_method, linkage_method, nclusters) { moduleServer(id, function(input, output, session) { saved_configurations <- reactiveVal(list()) ## Render the configuration table output$configs_table <- DT::renderDT({ validate(need(length(saved_configurations()) > 0, "No states saved")) do.call(rbind, saved_configurations()) }, rownames = TRUE, caption = "Click on a row to select parameters to load them again", selection = "single", options = list(ordering = FALSE)) # State saving # Save current key parameters to table. # Currently doesn't save the correlation threshold nor selected variables observeEvent(input$configs_save, { idx <- length(saved_configurations()) + 1 current_config <- list( distance_method = distance_method(), linkage_method = linkage_method(), nclusters = nclusters() ) config_list <- saved_configurations() config_list[[idx]] <- current_config saved_configurations(config_list) }) # State loading # Reload parameters from the selected row on the table selected_config <- eventReactive(input$configs_load, { req(input$configs_table_rows_selected) saved_configurations()[[input$configs_table_rows_selected]] }) selected_config }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_params.R
ui_pca <- function() { ns <- NS("pca") tabPanel("PCA", value = "pca", splitLayout( verticalLayout( fluidRow( column(6,selectizeInput(ns("pca_xaxis"), label = "X axis:", choices = NULL)), column(6,selectizeInput(ns("pca_yaxis"), label = "Y axis:", choices = NULL))), plotOutput(ns("pca_plot"), width = "100%", height = "400px") ), plotOutput(ns("drivers_plot"), width = "100%", height = "auto"), cellWidths = c("40%", "60%") ) %>% shinyhelper::helper(type = "markdown", content = "pca_help") ) } server_pca <- function(id, selected_data, cluster_labels, cluster_colors) { moduleServer(id, function(input, output, session) { pca_data <- reactive({ df <- selected_data() stats::prcomp(df) }) observeEvent(pca_data(), { pca_res <- pca_data() pca_dims <- colnames(pca_res$x) updateSelectizeInput(session, "pca_xaxis", choices = pca_dims, selected = "PC1") updateSelectizeInput(session, "pca_yaxis", choices = pca_dims, selected = "PC2") }) output$pca_plot <- renderPlot({ req(input$pca_xaxis) req(input$pca_yaxis) pca_scatterplot(pca_data(), cluster_labels(), cluster_colors, input$pca_xaxis, input$pca_yaxis) }) output$drivers_plot <- renderPlot({ drivers_df <- pca_drivers_df(selected_data(), pca_data()) pca_driversplot(drivers_df) }, height = function() max(300, ncol(selected_data()) * 25)) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_pca.R
ui_significance <- function() { ns <- NS("signif") tabPanel( "Significance testing", value = "signific", h5("Test significance for variables not used in clustering"), verticalLayout( selectizeInput( ns("signif_var"), "Select variable", choices = NULL, options = list( onInitialize = I('function(){this.setValue("");}') ) ) %>% shinyhelper::helper(type = "markdown", content = "signif_help"), splitLayout( plotOutput(ns("signif_boxplot"), height = 700), htmlOutput(ns("signif_results"), container = pre), cellWidths = c("25%", "75%") ) ) ) } server_significance <- function(id, all_data, cluster_labels, cluster_colors, unselected_vars) { moduleServer(id, function(input, output, session) { observeEvent(unselected_vars(), { updateSelectizeInput(session, "signif_var", choices = unselected_vars()) }) output$signif_boxplot <- renderPlot({ req(input$signif_var) isolate({ all_df <- all_data() }) df <- all_df[, input$signif_var] df$Cluster <- as.factor(cluster_labels()) facet_boxplot(df, "Cluster", input$signif_var, boxplot_colors = cluster_colors, plot_points = FALSE) }, height = 150) # Compute Dunn or t-test # Dunn is only valid when there are more than 3 clusters output$signif_results <- renderPrint({ req(input$signif_var) isolate({ all_df <- all_data() }) clusters <- cluster_labels() num_clusters <- length(unique(clusters)) if (num_clusters > 2) { dunn.test::dunn.test( x = dplyr::pull(all_df, input$signif_var), g = clusters, method = "bh" ) } else { all_df$Cluster <- clusters t_test_formula <- stats::as.formula(paste(input$signif_var, " ~ Cluster")) stats::t.test(t_test_formula, data = all_df) } }) }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_significance.R
ui_table <- function() { ns <- NS("table") tabPanel( "Table view", value = "table", h5("Choose clusters to filter out rows or keep only one cluster. Clusters will be recomputed automatically after clicking on one of the buttons"), fluidRow( column( 4, selectizeInput( ns("clusters_selection"), "Select cluster:", choices = NULL, options = list( onInitialize = I('function(){this.setValue("");}') ) ) ), column( 8, style = "margin-top: 25px", offset = 0, flowLayout( actionButton(ns("remove_rows"), "Remove selected rows"), actionButton(ns("keep_subjects"), "Keep only this cluster")) ) ) %>% shinyhelper::helper(type = "markdown", content = "table_help"), fluidRow(DT::DTOutput(ns("clusters_table"))) ) } server_table <- function(id, all_data, selected_data, cluster_labels, nclusters) { moduleServer(id, function(input, output, session) { observeEvent(c(nclusters(), selected_data()), { req(selected_data()) updateSelectInput(session, inputId = "clusters_selection", choices = 1:nclusters() ) }) # Update cluster table based on selected cluster output$clusters_table <- DT::renderDT({ req(input$clusters_selection) isolate({ all_df <- all_data() }) clusters <- cluster_labels() annotate_clusters(all_df, clusters, long = FALSE, input$clusters_selection) }, caption = "Click on rows to select", selection = "multiple", options = list(scrollX = TRUE, scrollCollapse = TRUE) ) new_data <- reactiveVal(NULL) observeEvent(input$remove_rows, { isolate({ all_df <- all_data() }) updated_data <- remove_selected_rows(all_df, cluster_labels(), input$clusters_selection, input$clusters_table_rows_selected) new_data(updated_data) }) observeEvent(input$keep_subjects, { isolate({ all_df <- all_data() }) updated_data <- keep_selected_rows(all_df, cluster_labels(), input$clusters_selection) new_data(updated_data) }) new_data }) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/mod_table.R
#' Faceted boxplots with points or violin plots #' #' @param df a data frame containing all the variables matching the remaining arguments #' @param x categorical variable #' @param y continuous variable #' @param facet_var optional variable to facet data #' @param boxplot_colors list of colors to use as fill for boxplots #' @param shape either "boxplot" or "violin" #' @param plot_points boolean variable to overlay jittered points or not. Default is `TRUE` #' #' @return a [ggplot2::ggplot] object #' @export #' #' @examples #' facet_boxplot(iris, x = "Species", y = "Sepal.Length", facet_var = "Species") facet_boxplot <- function(df, x, y, facet_var = NULL, boxplot_colors = NULL, shape = c("boxplot", "violin"), plot_points = TRUE) { shape <- match.arg(shape) if (!x %in% colnames(df)) stop("x variable not found in data frame") if (!y %in% colnames(df)) stop("y variable not found in data frame") if (!is.null(facet_var) && (!facet_var %in% colnames(df))) stop("facet_var variable not found in data frame") p <- ggplot(df, aes(x = .data[[x]], fill = .data[[x]])) + theme_bw() + theme(panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(), axis.line = element_line(), axis.ticks = element_line()) if (shape == "boxplot") { p <- p + geom_boxplot(aes(y = .data[[y]]), alpha = 0.6, outlier.shape = NA) # Plot points only works with violin plot if (plot_points) { p <- p + geom_point(aes(y = .data[[y]]), size = 0.2, position = "jitter") } } else { p <- p + geom_violin(aes(y = .data[[y]])) } if (!is.null(facet_var)) { facet_formula <- stats::as.formula(paste("~", facet_var)) p <- p + facet_wrap(facet_formula, ncol = 4, scales = "free") } if (!is.null(boxplot_colors)) { p <- p + scale_fill_manual(values = boxplot_colors) } p } #' Plot boxplots with clusters #' #' This is a convenience wrapper function for `facet_boxplot()`. #' Combined with `annotate_clusters()`, it #' doesn't require specifying axes in `facet_boxplot()`. #' #' @param annotated_data data frame returned by `annotate_clusters()` #' @param ... arguments passed to `facet_boxplot()` #' #' @return boxplots faceted by clusters #' @export #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' clusters <- compute_clusters(dmat, "complete") #' cluster_labels <- cut_clusters(clusters, 2) #' annotated_data <- annotate_clusters(iris[, c("Petal.Length", "Sepal.Length")], cluster_labels) #' cluster_boxplots(annotated_data, boxplot_colors = visxhclust::cluster_colors) cluster_boxplots <- function(annotated_data, ...) { facet_boxplot(annotated_data, "Cluster", "Value", "Measurement", ...) } #' A custom line plot with optional vertical line #' #' @param df data source #' @param x variable for horizontal axis #' @param y variable for vertical axis #' @param xintercept optional value in horizontal axis to highlight #' #' @return a [ggplot2::ggplot] object #' #' @export #' line_plot <- function(df, x, y, xintercept = NULL) { if (!x %in% colnames(df)) stop("x variable not found in data frame") if (!y %in% colnames(df)) stop("y variable not found in data frame") p <- ggplot(df) + geom_line(aes(x = .data[[x]], y = .data[[y]], group = 1)) + theme_bw() if (!is.null(xintercept)) { if (!is.numeric(xintercept)) stop("xintercept must be numeric") p <- p + geom_vline(xintercept = xintercept, linetype = "dashed") } p } #' Plot the first two components from the results of PCA #' #' @param pcres results of prcomp #' @param cluster_labels a list of cluster labels for each point in pcres #' @param cluster_colors a list of colors to match the cluster labels #' #' @noRd pca_scatterplot <- function(pcres, cluster_labels, cluster_colors, xdim = "PC1", ydim ="PC2") { pc_df <- as.data.frame(pcres$x) var_explained <- round(pcres$sdev / sum(pcres$sdev) * 100, 2) pc_labels <- stats::setNames(paste0(colnames(pc_df), " (", as.character(var_explained), "%)"), colnames(pc_df)) pc_df$Cluster <- as.factor(cluster_labels) ggplot(pc_df, aes(.data[[xdim]], .data[[ydim]])) + geom_point(aes(color = .data$Cluster)) + scale_colour_manual(values = cluster_colors) + theme_bw() + labs(title = "PCA") + xlab(pc_labels[xdim]) + ylab(pc_labels[ydim]) + theme(legend.position = "bottom") } #' Plot a drivers plot #' #' @param df a long formatted data frame with columns `PC`, `Variable`, `p` #' or `q`, and `Significant` #' @param adjusted boolean to use either `p` or `q` when plotting #' #' @noRd pca_driversplot <- function(df, adjusted = TRUE) { p_value_var <- if (adjusted) "q" else "p" ylimits <- rev(levels(df$Variable)) ggplot(df, aes( x = .data$PC, y= .data$Variable, fill = .data$Association, color = .data$Significant)) + geom_tile(size = 1L, width = 0.9, height = 0.9) + scale_color_manual(values = c("grey90", "black")) + scale_fill_gradientn(colors = c("white", "pink", "orange", "red", "darkred"), limits = c(0, 1)) + # To consider again: name = bquote(~-log(italic(.(p_value_var))))) + scale_x_discrete(labels = as.character(df$PC), expand = expansion(add = .5)) + scale_y_discrete(limits = ylimits) + theme(panel.grid = element_blank(), plot.margin = margin(1, 0, 0, 0, "cm"),) + labs(title = "Drivers plot", y = NULL, x= NULL) } #' Plot a 2D MDS projection of a distance matrix #' #' @param dmat distance matrix #' @param point_colors optional list of labels to color points (will be coerced to factor) #' @param point_palette optional palette used with [ggplot2::scale_colour_manual()] #' #' @return a ggplot object #' #' @importFrom stats cmdscale #' #' @export #' @examples #' dmat <- dist(iris[, c("Sepal.Width", "Sepal.Length")]) #' dmat_projection(dmat) dmat_projection <- function(dmat, point_colors = NULL, point_palette = NULL) { proj <- as.data.frame(cmdscale(dmat, k = 2)) point_aes <- NULL if (!is.null(point_colors)) { proj$color <- as.factor(point_colors) point_aes <- aes(color = .data$color) } p <- ggplot(proj, aes(.data$V1, .data$V2)) + theme_bw() + labs(x = "D1", y = "D2") + theme(legend.position = "bottom") + geom_point(point_aes) if (!is.null(point_palette)) p <- p + scale_colour_manual(values = point_palette) p } #' Plot distribution of annotation data across clusters #' #' @param annotations_df data frame with variables not used in clustering #' @param cluster_labels output from [visxhclust::cut_clusters()] #' @param selected_clusters optional vector of cluster labels to include in plots #' #' @return a `patchwork` object #' @export #' #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' clusters <- compute_clusters(dmat, "complete") #' cluster_labels <- cut_clusters(clusters, 2) #' plot_annotation_dist(iris["Species"], cluster_labels) plot_annotation_dist <- function(annotations_df, cluster_labels, selected_clusters = NULL) { if (!all(selected_clusters %in% cluster_labels)) { return(NULL) } annot <- annotate_clusters(annotations_df, cluster_labels, FALSE, selected_clusters) # If annotation variable is numeric, plot a histogram and facet by cluster # If annotation variable is categorical, plot bar charts and facet by cluster plots <- lapply(colnames(annotations_df), function(var_name) { if (is.numeric(annot[[var_name]])) { ggplot(stats::na.omit(annot), aes(x = .data[[var_name]])) + geom_histogram(bins = 20) + facet_wrap(~ Cluster, nrow = 1) + theme_bw() + theme(panel.grid.major.x = element_blank(), aspect.ratio = 1, axis.title.x = element_text(face = "bold", size = 12)) } else ggplot(annot, aes(x = .data[[var_name]], fill = .data[[var_name]])) + geom_bar(stat = "count") + facet_wrap(~ Cluster, nrow = 1) + scale_fill_brewer(palette = "Set3") + theme_bw() + theme(panel.grid.major.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), aspect.ratio = 1, axis.title.x = element_text(face = "bold", size = 12)) }) do.call(patchwork::wrap_plots, list(plots, ncol = 1)) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/plot.R
utils::globalVariables(c("where")) #' List of colors used in the Shiny app for clusters #' @export cluster_colors <- c( "#4c78a8", "#f58518", "#e45756", "#72b7b2", "#54a24b", "#eeca3b", "#b07aa1", "#FF9DA7", "#9c755f", "#bab0ab", "#4c78a8", "#f58518", "#e45756", "#4c78a8", "#f58518", "#e45756", "#72b7b2", "#54a24b", "#eeca3b", "#b07aa1", "#FF9DA7", "#9c755f", "#bab0ab", "#4c78a8", "#f58518", "#e45756", "#4c78a8", "#f58518", "#e45756", "#72b7b2", "#54a24b", "#eeca3b", "#b07aa1", "#FF9DA7", "#9c755f", "#bab0ab", "#4c78a8", "#f58518", "#e45756") #' Plot heatmap with cluster results and dendrogram #' #' @param scaled_selected_data scaled matrix or data frame with variables used for clustering #' @param clusters hierarchical cluster results produced by [fastcluster::hclust()] #' @param k targeted number of clusters #' @param cluster_colors list of cluster colors to match with boxplots #' @param scaled_unselected_data (optional) scaled matrix or data frame with variables not used for clustering #' @param annotation (optional) [ComplexHeatmap::columnAnnotation] object #' #' @return a [ComplexHeatmap::Heatmap] #' @export #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' clusters <- compute_clusters(dmat, "complete") #' species_annotation <- create_annotations(iris, "Species") #' cluster_heatmaps(scale(iris[c("Petal.Length", "Sepal.Length")]), #' clusters, #' 3, #' visxhclust::cluster_colors, #' annotation = species_annotation) cluster_heatmaps <- function(scaled_selected_data, clusters, k, cluster_colors, scaled_unselected_data = NULL, annotation = NULL) { top_matrix <- t(scaled_selected_data) if (!is.null(scaled_unselected_data)) { bottom_matrix <- t(scaled_unselected_data) } else { bottom_matrix <- NULL } heatmap_clusters <- reorder_dendrograms(clusters, k, cluster_colors) plot_cluster_heatmaps(top_matrix, bottom_matrix, heatmap_clusters$dendrogram, heatmap_clusters$ids, annotation) } #' Draw two heatmaps #' #' @param top_matrix matrix with selected variables #' @param bottom_matrix matrix with unselected variables #' @param dendrograms to draw above top matrix #' @param clusters_set list of cluster indices #' @param annotation (optional) any kind of annotation object to draw as top_annotation #' @param scaled (optional) boolean to modify colour scale if data has already been scaled #' @param distance_method (optional) if "Binary", use discrete colors for heatmap #' @param cluster_features (optional) If FALSE, row order does not change #' @param show_col_names (optional) If FALSE, does not show column names at base of heatmap #' #' @return two concatenated heatmaps drawn with ComplexHeatmap::draw #' @keywords internal #' #' @importFrom ComplexHeatmap Heatmap %v% draw #' @importFrom RColorBrewer brewer.pal #' plot_cluster_heatmaps <- function(top_matrix, bottom_matrix, dendrograms, clusters_set, annotation = NULL, scaled = FALSE, distance_method = NULL, cluster_features = TRUE, show_col_names = TRUE) { if (scaled) { if (!is.null(bottom_matrix)) { min_both <- min(min(top_matrix), min(bottom_matrix)) max_both <- max(max(top_matrix), max(bottom_matrix)) scale_values <- c(min_both, (max_both + min_both)/2 , max_both) } else { scale_values <- c(min(top_matrix), (max(top_matrix)+min(top_matrix))/2, max(top_matrix)) } col_fun <- grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(11, "RdBu")))(256) } else { if (!is.null(bottom_matrix)) { abs_min_both <- abs(min(min(top_matrix), min(bottom_matrix))) max_both <- max(max(top_matrix), max(bottom_matrix)) scale_end <- max(max_both, abs_min_both) } else { scale_end <- max(abs(min(top_matrix)), max(top_matrix)) } scale_values <- seq(as.integer(-scale_end), as.integer(scale_end), length.out = 11) col_fun <- circlize::colorRamp2( scale_values, rev(RColorBrewer::brewer.pal(length(scale_values), "RdBu")) ) } if (!is.null(distance_method)) if (distance_method == "Binary") { col_fun <- structure(c("#97c354", "#935fd1"), names = 0:1) } col_split <- ifelse(length(clusters_set) == 1, NULL, length(clusters_set)) htmp <- ComplexHeatmap::Heatmap(top_matrix, name="Selected variables", col = col_fun, cluster_columns = dendrograms, cluster_rows = cluster_features, column_split = col_split, column_title = as.character(clusters_set), show_column_names = show_col_names, row_names_gp = grid::gpar(fontsize = 8), column_names_side = "bottom", column_names_gp = grid::gpar(fontsize = 8), cluster_column_slices = FALSE, column_dend_height = grid::unit(3, "cm"), top_annotation = if (is.null(annotation)) NULL else annotation ) if (!is.null(bottom_matrix)) { htmp2 <- ComplexHeatmap::Heatmap(bottom_matrix, name = "Not used in \n clustering", col = col_fun, cluster_columns = dendrograms, column_split = col_split, show_column_names = show_col_names, row_names_gp = grid::gpar(fontsize = 8), column_names_gp = grid::gpar(fontsize = 8), cluster_column_slices = FALSE, show_column_dend = FALSE, cluster_rows = FALSE, show_heatmap_legend = FALSE) ComplexHeatmap::draw(htmp %v% htmp2, annotation_legend_side = "bottom") } else { ComplexHeatmap::draw(htmp, annotation_legend_side = "bottom") } } reorder_dendrograms <- function(clustered_data, k, color_list) { dendro <- stats::as.dendrogram(clustered_data) cut_data <- dendextend::cutree(clustered_data, k = k) cut_data <- cut_data[stats::order.dendrogram(dendro)] cluster_ids <- unique(cut_data) subset_colors <- color_list[1:k] subset_colors <- subset_colors[cluster_ids] list(dendrogram = dendro %>% dendextend::color_branches(k = k, groupLabels = cluster_ids, col = subset_colors), ids = cluster_ids ) } #' Create heatmap annotations from selected variables #' #' This function will create a [ComplexHeatmap::columnAnnotation] object with rows #' for each variable passed as argument. Character columns will be coerced into factors. #' For factors, the ColorBrewer palette `Set3` will be used. For non-negative numeric, the #' `PuBu` palette will be used, and for columns with negative values, the reversed `RdBu` will be used. #' #' @param df a data frame. It can be an original unscaled data, or a scaled one #' @param selected_variables list of columns in the data frame to create annotations for #' #' @return a [ComplexHeatmap::columnAnnotation] object #' #' @export #' @importFrom ComplexHeatmap columnAnnotation #' @importFrom RColorBrewer brewer.pal #' @importFrom circlize colorRamp2 create_annotations <- function(df, selected_variables) { scaled_annotation <- df %>% dplyr::select(dplyr::all_of(selected_variables)) %>% dplyr::mutate(dplyr::across(where(is.numeric), scale)) cat_annot_df <- as.data.frame(scaled_annotation) cat_annot_colors <- lapply(names(cat_annot_df), function(x) { values <- as.vector(cat_annot_df[[x]]) if (!is.numeric(values)) { values <- ifelse(is.na(values), 99, values) max_values <- length(unique(values)) pal_n <- min(max(3, max_values + 1), 12) anno_colors <- brewer.pal(pal_n, "Set3")[1:max_values] names(anno_colors) <- levels(as.factor(values)) } else { if (all(values >= 0)) { breaks <- pretty(values, 4) anno_colors <- colorRamp2(breaks, rev(brewer.pal(length(breaks), "PuBu"))) } else { anno_colors <- colorRamp2(c(-4, -2, -1, 0, 1, 2, 4), rev(brewer.pal(7, "RdBu"))) } } anno_colors }) names(cat_annot_colors) <- names(cat_annot_df) columnAnnotation(df = cat_annot_df, col = cat_annot_colors) } #' Draw a minimal heatmap without labels or dendrograms #' #' @param df a data frame #' #' @return ComplexHeatmap heatmap #' @noRd #' #' dmat_heatmap <- function(df) { ComplexHeatmap::Heatmap(as.matrix(df), name = "Distance matrix", col = RColorBrewer::brewer.pal(9, "RdGy"), show_column_names = FALSE, show_row_names = FALSE, show_row_dend = FALSE, show_column_dend = FALSE ) } #' Plot a correlation heatmap #' #' Computes pairwise Pearson correlation; if there are fewer than 15 columns, prints #' the value of the correlation coefficient inside each tile. #' #' @param df numeric data frame to compute correlations #' #' @return a [ComplexHeatmap::Heatmap] #' #' @export correlation_heatmap <- function(df) { corr_df <- stats::cor(df, method = "pearson") if (length(colnames(corr_df)) < 15) { ComplexHeatmap::Heatmap( corr_df, name = "Pearson's r", col = circlize::colorRamp2(c(-1, -0.5, 0, 0.5, 1), rev(RColorBrewer::brewer.pal(5, "RdBu"))), cell_fun = function(j, i, x, y, width, height, fill) { if (i != j) grid::grid.text(sprintf("%.2f", corr_df[i, j]), x, y, gp = grid::gpar(fontsize = 10)) } ) } else { ComplexHeatmap::Heatmap(corr_df, name = "Pearson's r", col = circlize::colorRamp2(c(-1, -0.5, 0, 0.5, 1), rev(RColorBrewer::brewer.pal(5, "RdBu")))) } }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/plot_heatmaps.R
#' @importFrom dplyr %>% #' @import shiny #' @import ggplot2 #' @importFrom shinycssloaders withSpinner #' @importFrom bsplus bs_append bs_set_opts bs_accordion #' @importFrom shinyhelper helper observe_helpers NULL #' Runs the Shiny app #' #' @return No return value, runs the app by passing it to print #' @export #' @examples #' ## Only run this example in interactive R sessions #' if (interactive()) { #' library(visxhclust) #' run_app() #' } run_app <- function() { addResourcePath("assets", system.file("www", package = "visxhclust") ) shiny::shinyApp(app_ui, app_server,options = list(launch.browser = TRUE)) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/run_app.R
utils::globalVariables(c("where")) #' Server-side #' #' @param input,output,session Internal parameters for {shiny}. #' #' @noRd app_server <- function(input, output, session) { shinyhelper::observe_helpers(help_dir = system.file("helpfiles", package = utils::packageName())) session_values <- reactiveValues(numeric_vars = list(), annotation_vars = list()) dropped_variables <- reactiveVal(NULL) all_data <- reactiveVal(NULL) # File loading ---- loaded_data <- eventReactive(input$file1, { file <- input$file1 load_data(file$datapath) }) # Data and UI initialisation ---- observeEvent(loaded_data(), { new_data <- loaded_data() # Check if there is a column with ID idColExists <- "ID" %in% names(new_data) if (!idColExists) { showNotification("Using rownames as ID column.", type = "warning") new_data$ID <- rownames(new_data) } # Convert any character to factor, except ID new_data <- dplyr::mutate(new_data, dplyr::across(!dplyr::any_of("ID") & where(is.character), as.factor)) # Find columns with missing values (i.e. NA) cols_with_na <- names(which(sapply(new_data, anyNA))) anyColumnsNA <- length(cols_with_na) > 0 if (anyColumnsNA) { showNotification("Columns with missing values were found and marked as annotation-only.", type = "warning", duration = NULL) } numeric_vars <- names(dplyr::select(new_data, where(is.numeric), -cols_with_na)) annotation_vars <- names(dplyr::select(new_data, -.data$ID, -where(is.numeric), cols_with_na)) # Go through removal of strongly correlated variables vars_to_remove <- get_correlated_variables(new_data[, numeric_vars], 0.9) dropped_variables(vars_to_remove) subset_numeric_vars <- !numeric_vars %in% vars_to_remove[["Var2"]] # Update main UI lists (variable selection, overview and comparison tabs) updateCheckboxGroupInput(session, "selected_numeric", choices = numeric_vars, selected = numeric_vars[subset_numeric_vars]) updateCheckboxGroupInput(session, "selected_annotation", choices = annotation_vars) # Keep variables in reactive list session_values$numeric_vars <- numeric_vars session_values$annotation_vars <- annotation_vars # Update reactive all_data with the data that was just loaded all_data(new_data) }) # Update UI ---- selected_numeric <- reactive({ validate(need(!is.null(input$selected_numeric), "No features have been selected")) input$selected_numeric }) unselected_vars <- reactive({ numeric_vars <- session_values$numeric_vars lv <- !(numeric_vars %in% selected_numeric()) numeric_vars[lv] }) observeEvent(input$flip_numeric, { numeric_vars <- session_values$numeric_vars lv <- !(numeric_vars %in% input$selected_numeric) updateCheckboxGroupInput(session, "selected_numeric", selected = numeric_vars[lv]) }) observeEvent(input$select_all, { if (input$select_all %% 2 == 0) { updateCheckboxGroupInput(session, "selected_numeric", choices = session_values$numeric_vars) } else { updateCheckboxGroupInput(session, "selected_numeric", choices = session_values$numeric_vars, selected = session_values$numeric_vars) } }, ignoreNULL = TRUE) # Selecting data and clustering ---- # When user changes numeric or categorical selection, triggers a chain reaction # Any visible output that depends on selected_data() will be updated selected_data <- reactive({ validate(need(!is.null(all_data()), "No data has been loaded")) validCondition <- all(selected_numeric() %in% session_values$numeric_vars) validate(need(validCondition, "Updating")) isolate({ all_df <- all_data() }) all_df[, selected_numeric()] }) scaled_data <- reactive({ if (input$distance_method != "Binary") { scaled_mat <- scale_data(selected_data(), input$scaling) isolate({ rownames(scaled_mat) <- all_data()$ID }) } else scaled_mat <- selected_data() scaled_mat }) unselected_data <- reactive({ dplyr::select(all_data(), where(is.numeric), -input$selected_numeric, -session_values$annotation_vars) }) scaled_unselected_data <- reactive({ if (ncol(unselected_data()) > 0) { scaled_mat <- scale_data(unselected_data(), input$scaling) isolate({ rownames(scaled_mat) <- all_data()$ID }) scaled_mat } else { NULL } }) observeEvent(session_values$numeric_vars, { updateNumericInput(session, "corr_threshold", value = 0.9) }) # If the correlation threshold changes, recompute all variables # Drop any new variables and also update the select input observeEvent(input$corr_threshold, { req(all_data()) numeric_vars <- session_values$numeric_vars clinical_numeric_df <- all_data()[, numeric_vars] vars_to_remove <- get_correlated_variables(clinical_numeric_df, input$corr_threshold) dropped_variables(vars_to_remove) lv_num_vars <- !(numeric_vars %in% vars_to_remove[["Var2"]]) updateSelectInput(session, "selected_numeric", selected = numeric_vars[lv_num_vars]) }) # Reactive computation of distance matrix distance_matrix <- reactive({ req(selected_data()) req(selected_numeric()) compute_dmat(selected_data(), input$distance_method, input$scaling, selected_numeric()) }) # Reactive computation of clusters clusters <- reactive({ compute_clusters(distance_matrix(), linkage_method = input$linkage_method) }) # Reactive extraction of cluster labels cluster_labels <- reactive({ cut_clusters(clusters(), k = input$nclusters) }) all_data_with_clusters <- reactive({ all_df <- all_data() cbind(all_df, cluster_labels()) }) # Download all_data with cluster annotations output$download_clusters <- downloadHandler( filename = function() { paste(input$distance_method,input$linkage_method,input$nclusters,"clusters.csv", sep = "_") }, content = function(file) { utils::write.csv(all_data_with_clusters(), file, row.names = FALSE) } ) # end clustering methods # Overview tab ---- server_overview( "overview", selected_data, selected_numeric, dropped_variables, reactive(input$scaling) ) # Distance matrix tab ---- server_distancematrix( "distancematrix", distance_matrix, cluster_labels, cluster_colors ) # PCA tab ---- server_pca( "pca", selected_data, cluster_labels, cluster_colors ) # Heatmap tab ---- heatmap_annotation <- reactive({ if (isTruthy(input$selected_annotation)) { create_annotations(all_data(), input$selected_annotation) } else { NULL } }) server_heatmap( "heatmap", heatmap_annotation, clusters, reactive(input$nclusters), cluster_colors, scaled_data, scaled_unselected_data, reactive({ input$scaling == "None" }), reactive(input$distance_method) ) # Boxplots tab ---- boxplot_annotation <- reactive({ if (isTruthy(input$selected_annotation)) { all_data()[input$selected_annotation] } else { NULL } }) server_boxplots( "boxplots", selected_data, cluster_labels, cluster_colors, boxplot_annotation ) # Cluster table tab ---- new_data <- server_table( "table", all_data, selected_data, cluster_labels, reactive(input$nclusters) ) # Update dataset when there is interaction in the table observeEvent(new_data(), { all_data(new_data()) }) # Significance testing tab ---- server_significance( "signif", all_data, cluster_labels, cluster_colors, unselected_vars ) # Evaluation tab ---- server_evaluation( "evaluation", distance_matrix, clusters ) # Gap statistic tab ---- server_gapstat( "gapstat", selected_data, clusters ) # Parameter state management tab ---- new_params <- server_params( "params", reactive(input$distance_method), reactive(input$linkage_method), reactive(input$nclusters) ) # Observe when a user loads previous settings observeEvent(new_params(), { conf <- new_params() for (x in names(conf)) { value_conf <- conf[[x]] if (is.numeric(value_conf)) { updateNumericInput(session, x, value = value_conf) } if (is.character(value_conf)) { updateSelectInput(session, x , selected = value_conf) } } }) #end state management }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/server.R
#' UI #' #' @param request internal #' #' @noRd app_ui <- function(request) { fluidPage(theme = "bootstrap.min.css", tags$head(tags$style( HTML( ".shiny-input-container-inline .shiny-options-group div { display: contents; } pre { white-space: break-spaces; } .shiny-notification-error { position: fixed; width: 250px; top: 50% ;left: 50%; } div.shinyhelper-container { right: 25px; } .shiny-output-error-validation { min-height: 50px } .table { white-space: nowrap; } tbody td:first-child { left:0; z-index: 1 } .align-right { margin-right: 5; float: right } .align-right img { vertical-align: middle;} .header-panel { margin-top: 5px; margin-bottom: 5px } " ) ), # Application title tags$title(paste(utils::packageName(), ": visual exploration of hierarchical clustering"))), tags$div( span(paste(utils::packageName(), ": visual exploration of hierarchical clustering"), class = "h2"), span(a(img(src = "assets/github.png", height = "20px", width = "20px"), href = "http://github.com/rhenkin/visxhclust"), class = "align-right"), class = "header-panel" ), # Sidebar ----------------------------------------------------------- sidebarLayout( sidebarPanel( width = 3, ui_sidebar() ), # Main outputs ------------------------------------------------------------ mainPanel( tabsetPanel( id = "menu", ui_overview(), ui_distancematrix(), ui_pca(), ui_heatmap(), ui_boxplots(), ui_table(), ui_significance(), ui_evaluation(), ui_gapstat(), ui_params() ), type = "hidden" ) ) ) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/ui.R
ui_sidebar <- function() { verticalLayout( fileInput( "file1", "Choose file:", multiple = FALSE, accept = c(".rds", ".csv", ".tsv", ".txt") ) %>% shinyhelper::helper(type = "markdown", content = "sidebar_help"), checkboxInput("scaling", "Scale data?", value = TRUE), #radioButtons( # "scaling", # "Scaling:", # choices = c("Z-scores", "Robust", "None") #), div( id = "sidebar", selectInput( "distance_method", p("Distance method:"), choices = c( "Euclidean", "Manhattan", "Mahalanobis", "Cosine", "Maximum", "Canberra", "Minkowski", "Binary" ), selected = "Euclidean" ), selectInput( "linkage_method", p("Linkage method:"), choices = c("single", "complete", "average", "ward.D2"), selected = "ward.D2" ), numericInput( "nclusters", p("No. of clusters:"), value = 2, min = 1, step = 1 ), downloadButton("download_clusters", "Download data with clusters"), tags$br(),tags$br(), bs_accordion(id = "cluster_variable_selection") %>% bs_set_opts(panel_type = "default") %>% bs_append( title = "Numeric features", content = tagList( tags$span( actionButton("flip_numeric", "Flip selection"), actionButton("select_all", "Select all")), checkboxGroupInput( "selected_numeric", NULL, choices = NULL, selected = NULL ) ) ) %>% bs_append( title = "Heatmap features", content = checkboxGroupInput("selected_annotation", NULL, choices = NULL ) ), numericInput( "corr_threshold", p("Correlation threshold for automatic removal:"), value = 0.9, step = 0.01 ) ) ) }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/ui_sidebar.R
#' @noRd cholMaha <- function(df) { dec <- chol(stats::cov(df)) tmp <- forwardsolve(t(dec), t(df) ) stats::dist(t(tmp)) } #' Compute a distance matrix from scaled data #' #' @description This function applies scaling to the columns of a data frame and #' computes and returns a distance matrix from a chosen distance measure. #' #' @param x a numeric data frame or matrix #' @param dist_method a distance measure to apply to the scaled data. Must be those supported by [stats::dist()], plus `"mahalanobis"` and `"cosine"`. Default is `"euclidean"`. #' @param apply_scaling use TRUE to apply [base::scale()]. By default does not scale data. #' @param subset_cols (optional) a list of columns to subset the data #' #' @return an object of class "dist" (see [stats::dist()]) #' #' @export #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' print(class(dmat)) compute_dmat <- function(x, dist_method = "euclidean", apply_scaling = FALSE, subset_cols = NULL) { methods <- c("euclidean", "cosine", "mahalanobis", "manhattan", "maximum", "canberra", "minkowski", "binary") dist_method <- match.arg(tolower(dist_method), methods) if (!is.null(subset_cols)) x <- x[, subset_cols] validate_dataset(x) if (dist_method == "cosine") { # https://stats.stackexchange.com/a/367216 numeric_mat <- as.matrix(x) sim <- numeric_mat / sqrt(rowSums(numeric_mat * numeric_mat)) sim <- sim %*% t(sim) stats::as.dist(1 - sim) } else if (dist_method == "mahalanobis") { cholMaha(x) } else if (dist_method == "binary") { stats::dist(x, method = "binary") } else if (dist_method %in% c("euclidean", "maximum", "manhattan", "canberra", "minkowski")) { stats::dist(scale_data(x, apply_scaling), method = dist_method) } } #' Compute clusters hierarchically from distance matrix #' #' @param dmat a distance matrix #' @param linkage_method a linkage method supported by [fastcluster::hclust()] #' #' @return clusters computed by [fastcluster::hclust()] #' @export #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' res <- compute_clusters(dmat, "complete") compute_clusters <- function(dmat, linkage_method) { fastcluster::hclust(dmat, method = linkage_method) } #' Cut a hierarchical tree targeting k clusters #' #' @param clusters cluster results, produced by e.g. [fastcluster::hclust()] #' @param k target number of clusters #' #' @return cluster labels #' @export #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' clusters <- compute_clusters(dmat, "complete") #' cluster_labels <- cut_clusters(clusters, 2) #' head(cluster_labels) cut_clusters <- function(clusters, k) { dendextend::cutree(clusters, k = k, order_clusters_as_data = TRUE) } # nocov start #' @noRd relabel_clusters <- function(list_of_labels, df, rank_variable) { lapply(list_of_labels, function(x) { df[,"Cluster"] <- x[[2]] medians <- stats::aggregate(. ~ Cluster, df, stats::median) medians <- medians[order(medians[rank_variable]),] factor(x[[2]], levels = medians$Cluster) }) } # nocov end #' Compute an internal evaluation metric for clustered data #' #' @description Metric will be computed from 2 to max_k clusters. Note that the row number in results will be different from k. #' #' @param dmat distance matrix output of [compute_dmat()] or [stats::dist()] #' @param clusters output of [compute_clusters()] or [fastcluster::hclust()] #' @param metric_name "silhouette" or "dunn" #' @param max_k maximum number of clusters to cut using [dendextend::cutree()]. Default is 14. #' #' @return a data frame with columns `k` and `score` #' @export #' #' @examples #' data_to_cluster <- iris[c("Petal.Length", "Sepal.Length")] #' dmat <- compute_dmat(data_to_cluster, "euclidean", TRUE) #' clusters <- compute_clusters(dmat, "complete") #' compute_metric(dmat, clusters, "dunn") compute_metric <- function(dmat, clusters, metric_name, max_k = 14) { if (!metric_name %in% c("silhouette", "dunn")) { stop("Invalid metric name. metric_name should be one of 'silhouette' or 'dunn'") } stopifnot(class(dmat) == "dist", max_k > 2) calc_measure <- as.vector(unlist(lapply(2:max_k, function(k) { if (metric_name == "silhouette") { sil <- cluster::silhouette( x = dendextend::cutree( clusters, k = k, order_clusters_as_data = TRUE ), dist = dmat ) summary_sil <- summary(sil) summary_sil$avg.width } else { clValid::dunn( distance = dmat, clusters = dendextend::cutree( clusters, k = k, order_clusters_as_data = TRUE ) ) } }))) data.frame(k = factor(2:max_k), score = calc_measure) } #' Compute Gap statistic for clustered data #' #' @param df the data used to compute clusters #' @param clusters output of [compute_clusters()] or [fastcluster::hclust()] #' @param gap_B number of bootstrap samples for [cluster::clusGap()] function. Default is 50. #' @param max_k maximum number of clusters to compute the statistic. Default is 14. #' #' @return a data frame with the Tab component of [cluster::clusGap()] results #' @export #' #' @examples #' data_to_cluster <- iris[c("Petal.Length", "Sepal.Length")] #' dmat <- compute_dmat(data_to_cluster, "euclidean", TRUE) #' clusters <- compute_clusters(dmat, "complete") #' gap_results <- compute_gapstat(scale(data_to_cluster), clusters) #' head(gap_results) compute_gapstat <- function(df, clusters, gap_B = 50, max_k = 14) { FUN_gap <- function(clusters, k) { list(cluster = dendextend::cutree(clusters, k = k, order_clusters_as_data = TRUE)) } if (max_k <= 2) stop("max_k must be greater than 2") res <- cluster::clusGap(df, function(x, k, clusters) FUN_gap(clusters, k), B = gap_B, K.max = max_k, clusters = clusters, verbose = FALSE) gap_table <- res$Tab gap_table <- as.data.frame(gap_table) gap_table$k <- as.factor(1:max_k) gap_table } #' Find minimum or maximum score in a vector #' #' @description This function is meant to be used with compute_metric. For Gap statistic, #' use [cluster::maxSE()]. #' #' @param x a numeric vector #' @param method one of "firstmax", "globalmax", "firstmin" or "globalmin" #' #' @return the index (not k) of the identified maximum or minimum score #' @export #' #' @examples #' data_to_cluster <- iris[c("Petal.Length", "Sepal.Length")] #' dmat <- compute_dmat(data_to_cluster, "euclidean", TRUE) #' clusters <- compute_clusters(dmat, "complete") #' res <- compute_metric(dmat, clusters, "dunn") #' optimal_score(res$score, method = "firstmax") optimal_score <- function(x, method = c( "firstmax", "globalmax", "firstmin", "globalmin" ) ) { method <- match.arg(method) stopifnot((K <- length(x)) >= 1) switch(method, "firstmin" = { ## the first local minimum decr <- diff(x) <= 0 # length K-1 if (!all(decr) & any(decr)) which.min(decr) else K # the first TRUE, or K }, "globalmin" = { which.min(x) }, "firstmax" = { ## the first local maximum decr <- diff(x) < 0 # length K-1 if (!all(decr) & any(decr)) which.max(decr) else 1 # the first TRUE, or K }, "globalmax" = { which.max(x) }) } #' Annotate data frame with clusters #' #' @param df a data frame #' @param cluster_labels list of cluster labels, automatically converted to factor. #' @param long if `TRUE`, returned data frame will be in long format. See details for spec. Default is `TRUE`. #' @param selected_clusters optional cluster labels to filter #' #' @details Long data frame will have columns: `Cluster`, `Measurement` and `Value`. #' #' @return a wide or long data frame #' @export #' #' @examples #' dmat <- compute_dmat(iris, "euclidean", TRUE, c("Petal.Length", "Sepal.Length")) #' res <- compute_clusters(dmat, "complete") #' cluster_labels <- cut_clusters(res, 2) #' annotated_data <- annotate_clusters(iris[, c("Petal.Length", "Sepal.Length")], cluster_labels) #' head(annotated_data) annotate_clusters <- function(df, cluster_labels, long = TRUE, selected_clusters = NULL) { stopifnot(is.data.frame(df), "Selected clusters are not valid" = all(selected_clusters %in% cluster_labels)) df$Cluster <- as.factor(cluster_labels) if (!is.null(selected_clusters)) { df <- df[df$Cluster %in% selected_clusters, ] } if (long) { tidyr::pivot_longer(df, c(-"Cluster"), names_to = "Measurement", values_to = "Value") } else { df } }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/utils_clustering.R
#' Loads a file #' #' @param filepath a file path provided by the user or a Shiny app #' #' @return a data frame #' @noRd #' #' load_data <- function(filepath) { ext <- tools::file_ext(filepath) loaded_data <- switch(ext, rds = readRDS(filepath), csv = readr::read_csv(filepath, col_types = readr::cols()), tsv = readr::read_delim(filepath, delim = "\t", col_types = readr::cols()), txt = readr::read_delim(filepath, delim = "\t", col_types = readr::cols()) ) if (!is.data.frame(loaded_data)) { loaded_data <- as.data.frame(loaded_data) } colnames(loaded_data) <- make.names(colnames(loaded_data)) loaded_data } validate_dataset <- function(x) { if (!all(vapply(x, is.numeric, logical(1)))) { stop("All columns in data must be numeric.") } } #' Conditional scaling #' #' @param x a numeric data frame or matrix #' @param flag scale or not? Default is TRUE #' #' @details Robust scaling is done via median absolute deviation #' #' @return a scaled data frame #' #' @noRd #' @examples #' scaled_data <- scale_data(iris[, c("Petal.Length", "Sepal.Length")]) #' head(scaled_data) scale_data <- function(x, flag = TRUE) { validate_dataset(x) if (flag) { scale(x) } else { x } } #' Get list of correlated variables #' #' @param df data frame #' @param threshold correlation threshold #' #' @noRd get_correlated_variables <- function(df, threshold) { corr_df <- as.data.frame(stats::cor(df, method="spearman")) corr_df$Var1 <- rownames(corr_df) corr_df <- tidyr::pivot_longer(corr_df, -.data$Var1, names_to="Var2", values_to="Corr") corr_df <- corr_df[corr_df$Var1 != corr_df$Var2, ] # Rather than having a null hypothesis of rho (correlation) = 0 and an # alternative of two-sided rho != 0, we change our test to be a null # hypothesis H0: rho = 0.9, and an alternative hypothesis of H1: rho < 0.9 # (one-sided). The interpretation will be that we will reject H0 for those # pairs of variables with a correlation significantly lower than a # threshold, let's say the usual 0.05. So we drop variables with correlation # above 0.9, as well as those that are not significantly lower than 0.9; with # this we might catch correlations close enough to 0.9, even if not exactly # 0.9 max_corr <- threshold dof <- nrow(df) - 2 t0 <- sqrt(dof) * max_corr / (sqrt(1 - (max_corr**2))) t1 <- sqrt(dof) * corr_df$Corr / sqrt(1 - (corr_df$Corr ** 2)) #Besides calculating the p-value (and adjusted), the code below also look #for duplicate rows of combinations of variables and remove them corr_df <- corr_df %>% dplyr::mutate(pval = stats::pt(t1, df = dof, ncp = t0), padj = stats::p.adjust(.data$pval, method="fdr")) %>% dplyr::group_by(grp = paste(pmax(.data$Var1, .data$Var2), pmin(.data$Var1, .data$Var2), sep="_")) %>% dplyr::slice(1) %>% dplyr::ungroup() %>% dplyr::select(-.data$grp) #Look for those that are not significantly lower corr_df[corr_df$padj > 0.05, ] } #From: https://github.com/dgrtwo/drlib/blob/master/R/reorder_within.R #' @importFrom stats reorder reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) { new_x <- paste(x, within, sep = sep) stats::reorder(new_x, by, FUN = fun) } scale_x_reordered <- function(..., sep = "___") { reg <- paste0(sep, ".+$") ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...) } scale_y_reordered <- function(..., sep = "___") { reg <- paste0(sep, ".+$") ggplot2::scale_y_discrete(labels = function(x) gsub(reg, "", x), ...) } #' Remove selected rows by cluster #' #' @param df data frame with Cluster column #' @param selected_cluster number of the selected cluster #' @param row_numbers row numbers within the selected cluster subset #' #' @return subset of data frame with the selected rows #' @noRd remove_selected_rows <- function(df, clusters, selected_cluster, row_numbers) { to_remove <- df %>% dplyr::mutate(Cluster = as.factor(clusters)) %>% dplyr::filter(.data$Cluster == selected_cluster) %>% dplyr::filter(dplyr::row_number() %in% row_numbers) df[!(df$ID %in% to_remove$ID) ,] } #' Keep selected rows by cluster #' #' @param df data frame with Cluster column #' @param selected_cluster number of the selected cluster #' @param row_numbers row numbers within the selected cluster subset #' #' @return subset of data frame with the selected rows #' @noRd keep_selected_rows <- function(df, clusters, selected_cluster) { df %>% dplyr::mutate(Cluster = as.factor(clusters)) %>% dplyr::filter(.data$Cluster == selected_cluster) } #' Vectorized computation of p values #' #' @param x a data frame #' @param y an optional second data frame #' @param ... additional arguments to cor.test #' #' @noRd compute_pvalues <- function(x, y = NULL, ...) { FUN <- function(x, y, ...) stats::cor.test(x, y, ...)[["p.value"]] if (missing(y)) { y <- t(x) } z <- outer( colnames(x), colnames(y), Vectorize(function(i, j, ...) { FUN(x[[i]], y[[j]], ...) }, vectorize.args = c("i", "j")), ... ) dimnames(z) <- list(colnames(x), colnames(y)) z } #' Vectorized computation of correlation #' #' @param x a data frame #' @param y an optional second data frame #' @param ... additional arguments to cor.test #' #' @noRd compute_corr <- function(x, y = NULL, ...) { FUN <- function(x, y, ...) stats::cor.test(x, y, ...)[["estimate"]] if (missing(y)) { y <- t(x) } z <- outer( colnames(x), colnames(y), Vectorize(function(i, j, ...) { FUN(x[[i]], y[[j]], ...) }, vectorize.args = c("i", "j")), ... ) dimnames(z) <- list(colnames(x), colnames(y)) z } #' Create data frame for a drivers plot #' #' @param df main data frame #' @param pcres raw PCA results #' @param max_pc maximum number of PCs to keep. Default value is 8 #' @param adjust adjust p-values? Default `TRUE` includes column `q` in results #' #' @noRd #' pca_drivers_df <- function(df, pcres, max_pc = 8, adjust = TRUE) { pc_df <- as.data.frame(pcres$x) var_explained <- round(pcres$sdev / sum(pcres$sdev) * 100, 2) # Fast computation of p values for columns of different dataframes corr <- as.data.frame(compute_corr(df, pc_df)) colnames(corr) <- paste0(colnames(pc_df), " \n(", as.character(var_explained), "%)") pvalues <- as.data.frame(compute_pvalues(df, pc_df)) colnames(pvalues) <- paste0(colnames(pc_df), " \n(", as.character(var_explained), "%)") # Select first max_pc components corr <- corr[, 1:min(max_pc, ncol(pc_df))] corr$Variable <- as.factor(rownames(corr)) pvalues <- pvalues[, 1:min(max_pc, ncol(pc_df))] pvalues$Variable <- as.factor(rownames(pvalues)) corr_long <- tidyr::pivot_longer(corr, -.data$Variable, names_to = "PC", values_to = "Association") pvalues_long <- tidyr::pivot_longer(pvalues, -.data$Variable, names_to = "PC") pvalues_long$Association <- corr_long$Association ^ 2 pvalues_long$Significant <- ifelse(pvalues_long$value <= 0.05, TRUE, FALSE ) pvalues_long$p <- -log10(pvalues_long$value) if (adjust) pvalues_long$q <- -log10(stats::p.adjust(pvalues_long$value, method = "fdr")) pvalues_long }
/scratch/gouwar.j/cran-all/cranData/visxhclust/R/utils_data.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup, message=FALSE, warning=FALSE-------------------------------------- library(visxhclust) library(dplyr) ## ----prep--------------------------------------------------------------------- numeric_data <- iris %>% select(Sepal.Length, Sepal.Width, Petal.Width) dmat <- compute_dmat(numeric_data, "euclidean", TRUE) clusters <- compute_clusters(dmat, "complete") ## ----gapstat------------------------------------------------------------------ gap_results <- compute_gapstat(scale(numeric_data), clusters) optimal_k <- cluster::maxSE(gap_results$gap, gap_results$SE.sim) line_plot(gap_results, "k", "gap", xintercept = optimal_k) ## ----dunn--------------------------------------------------------------------- res <- compute_metric(dmat, clusters, "dunn") optimal_k <- optimal_score(res$score) line_plot(res, "k", "score", optimal_k)
/scratch/gouwar.j/cran-all/cranData/visxhclust/inst/doc/clusterevaluation.R
--- title: "Documenting evaluation" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Documenting evaluation} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The other vignette focuses on reproducing a single clustering workflow that assumes that the number of clusters has been decided. As the app includes a few options for evaluating clusters, some of the functions are also made available in the package. The output of the clustering functions can also be used with other packages. ```{r setup, message=FALSE, warning=FALSE} library(visxhclust) library(dplyr) ``` ### Preprocessing and clustering ```{r prep} numeric_data <- iris %>% select(Sepal.Length, Sepal.Width, Petal.Width) dmat <- compute_dmat(numeric_data, "euclidean", TRUE) clusters <- compute_clusters(dmat, "complete") ``` ### Gap statistic For Gap statistic, the optimal number of clusters depends on the method use to compare cluster solutions. The package cluster includes the function `cluster::maxSE()` to help with that. ```{r gapstat} gap_results <- compute_gapstat(scale(numeric_data), clusters) optimal_k <- cluster::maxSE(gap_results$gap, gap_results$SE.sim) line_plot(gap_results, "k", "gap", xintercept = optimal_k) ``` ### Other measures The Shiny app also includes the option to compute average silhouette widths or Dunn index. The function `compute_metric` works similarly to `compute_gapstat`, whereas `optimal_score` is similar to maxSE. However, `optimal_score` varies only between first and global minimum and maximum. ```{r dunn} res <- compute_metric(dmat, clusters, "dunn") optimal_k <- optimal_score(res$score) line_plot(res, "k", "score", optimal_k) ```
/scratch/gouwar.j/cran-all/cranData/visxhclust/inst/doc/clusterevaluation.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup, message=FALSE, warning=FALSE-------------------------------------- library(visxhclust) library(dplyr) library(ggplot2) ## ----first_step--------------------------------------------------------------- numeric_data <- iris %>% select(where(is.numeric)) annotation_data <- iris %>% select(where(is.factor)) ## ----correlation-------------------------------------------------------------- correlation_heatmap(numeric_data) ## ----subset------------------------------------------------------------------- subset_data <- numeric_data %>% select(Sepal.Length, Sepal.Width, Petal.Width) ## ----params------------------------------------------------------------------- scaling <- TRUE distance_method <- "euclidean" linkage_method <- "ward.D2" # this assumes that, in the app, we identified 3 as the optimal number of clusters k <- 3 ## ----computation-------------------------------------------------------------- dmat <- compute_dmat(subset_data, distance_method, TRUE) clusters <- compute_clusters(dmat, linkage_method) cluster_labels <- cut_clusters(clusters, k) ## ----heatmap------------------------------------------------------------------ species_annotation <- create_annotations(iris, "Species") cluster_heatmaps(scale(subset_data), clusters, k, cluster_colors, annotation = species_annotation) ## ----boxplots----------------------------------------------------------------- annotated_data <- annotate_clusters(subset_data, cluster_labels, TRUE) cluster_boxplots(annotated_data)
/scratch/gouwar.j/cran-all/cranData/visxhclust/inst/doc/clusterworkflow.R
--- title: "Documenting a workflow" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Documenting a workflow} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This document shows how to use some functions included in the package to document and reproduce a clustering workflow from the app. Although these functions do not cover all the steps such as selecting features, they allow users of the Shiny app to show the resulting heatmaps and boxplots. The example dataset used here is the `iris` dataset. ```{r setup, message=FALSE, warning=FALSE} library(visxhclust) library(dplyr) library(ggplot2) ``` ### Preparing First we split the numeric and categorical variables and scale the data. ```{r first_step} numeric_data <- iris %>% select(where(is.numeric)) annotation_data <- iris %>% select(where(is.factor)) ``` Let's check the dataset for highly correlated variables that will likely skew the clusters with redundant information: ```{r correlation} correlation_heatmap(numeric_data) ``` As seen above, petal length and width are highly correlated, so we keep only one of them: ```{r subset} subset_data <- numeric_data %>% select(Sepal.Length, Sepal.Width, Petal.Width) ``` ### Clustering The clustering itself takes three steps: computing a distance matrix, computing the hierarchical clusters and cutting the tree to find the desired number of clusters. In the app, each of these steps has matching parameters: apply scaling and distance/similarity metric, linkage method and the number of clusters. ```{r params} scaling <- TRUE distance_method <- "euclidean" linkage_method <- "ward.D2" # this assumes that, in the app, we identified 3 as the optimal number of clusters k <- 3 ``` These parameters are used in three functions that the app also uses: `compute_dmat`, `compute_clusters` and `cut_clusters`. You can check the documentation for each function in the package website, or interactively through `?compute_dmat`. ```{r computation} dmat <- compute_dmat(subset_data, distance_method, TRUE) clusters <- compute_clusters(dmat, linkage_method) cluster_labels <- cut_clusters(clusters, k) ``` ### Results Now we can check both the heatmap+dendrogram and boxplots. A function that covers most steps to produce the heatmap is included in the package, with the name: `cluster_heatmaps()`. It plots the dendrogram, the annotation layer, the clustered data heatmap and the heatmap with the rest of the data not used for clustering. In the Shiny app this is done automatically, but outside, plotting the annotation and the unselected data are optional steps; the annotations require an extra step with the function `create_annotations()`. The colors used in the app are also exported by the package as the variable `cluster_colors`. ```{r heatmap} species_annotation <- create_annotations(iris, "Species") cluster_heatmaps(scale(subset_data), clusters, k, cluster_colors, annotation = species_annotation) ``` In addition to the heatmap, the boxplots in the app are also available through functions. There are two steps required to show data through box plots: annotating the original data with the cluster and plotting it. ```{r boxplots} annotated_data <- annotate_clusters(subset_data, cluster_labels, TRUE) cluster_boxplots(annotated_data) ```
/scratch/gouwar.j/cran-all/cranData/visxhclust/inst/doc/clusterworkflow.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----run, eval=FALSE---------------------------------------------------------- # library(visxhclust) # run_app()
/scratch/gouwar.j/cran-all/cranData/visxhclust/inst/doc/visxhclust.R
--- title: "visxhclust Shiny app tutorial" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{visxhclust Shiny app tutorial} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This is a simple visual tutorial on the basic loop of the visxhclust Shiny app -- note that almost every tab in the application has a corresponding help icon with more information and tips. To open the Shiny app you need to run: ```{r run, eval=FALSE} library(visxhclust) run_app() ``` ## Steps for simple iteration ### Step 1: Loading data and setting parameters ![Step 1](load_data.gif) ### Step 2: View clustering results ![Step 2](view_results.gif) ### Step 3: Evaluate ![Step 3](evaluate.gif) ### Step 4: Change parameters again ![Step 4](iterate.gif) ### Step 5: Review results ![Step 5](review_results.gif)
/scratch/gouwar.j/cran-all/cranData/visxhclust/inst/doc/visxhclust.Rmd
--- title: "Documenting evaluation" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Documenting evaluation} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The other vignette focuses on reproducing a single clustering workflow that assumes that the number of clusters has been decided. As the app includes a few options for evaluating clusters, some of the functions are also made available in the package. The output of the clustering functions can also be used with other packages. ```{r setup, message=FALSE, warning=FALSE} library(visxhclust) library(dplyr) ``` ### Preprocessing and clustering ```{r prep} numeric_data <- iris %>% select(Sepal.Length, Sepal.Width, Petal.Width) dmat <- compute_dmat(numeric_data, "euclidean", TRUE) clusters <- compute_clusters(dmat, "complete") ``` ### Gap statistic For Gap statistic, the optimal number of clusters depends on the method use to compare cluster solutions. The package cluster includes the function `cluster::maxSE()` to help with that. ```{r gapstat} gap_results <- compute_gapstat(scale(numeric_data), clusters) optimal_k <- cluster::maxSE(gap_results$gap, gap_results$SE.sim) line_plot(gap_results, "k", "gap", xintercept = optimal_k) ``` ### Other measures The Shiny app also includes the option to compute average silhouette widths or Dunn index. The function `compute_metric` works similarly to `compute_gapstat`, whereas `optimal_score` is similar to maxSE. However, `optimal_score` varies only between first and global minimum and maximum. ```{r dunn} res <- compute_metric(dmat, clusters, "dunn") optimal_k <- optimal_score(res$score) line_plot(res, "k", "score", optimal_k) ```
/scratch/gouwar.j/cran-all/cranData/visxhclust/vignettes/clusterevaluation.Rmd
--- title: "Documenting a workflow" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Documenting a workflow} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This document shows how to use some functions included in the package to document and reproduce a clustering workflow from the app. Although these functions do not cover all the steps such as selecting features, they allow users of the Shiny app to show the resulting heatmaps and boxplots. The example dataset used here is the `iris` dataset. ```{r setup, message=FALSE, warning=FALSE} library(visxhclust) library(dplyr) library(ggplot2) ``` ### Preparing First we split the numeric and categorical variables and scale the data. ```{r first_step} numeric_data <- iris %>% select(where(is.numeric)) annotation_data <- iris %>% select(where(is.factor)) ``` Let's check the dataset for highly correlated variables that will likely skew the clusters with redundant information: ```{r correlation} correlation_heatmap(numeric_data) ``` As seen above, petal length and width are highly correlated, so we keep only one of them: ```{r subset} subset_data <- numeric_data %>% select(Sepal.Length, Sepal.Width, Petal.Width) ``` ### Clustering The clustering itself takes three steps: computing a distance matrix, computing the hierarchical clusters and cutting the tree to find the desired number of clusters. In the app, each of these steps has matching parameters: apply scaling and distance/similarity metric, linkage method and the number of clusters. ```{r params} scaling <- TRUE distance_method <- "euclidean" linkage_method <- "ward.D2" # this assumes that, in the app, we identified 3 as the optimal number of clusters k <- 3 ``` These parameters are used in three functions that the app also uses: `compute_dmat`, `compute_clusters` and `cut_clusters`. You can check the documentation for each function in the package website, or interactively through `?compute_dmat`. ```{r computation} dmat <- compute_dmat(subset_data, distance_method, TRUE) clusters <- compute_clusters(dmat, linkage_method) cluster_labels <- cut_clusters(clusters, k) ``` ### Results Now we can check both the heatmap+dendrogram and boxplots. A function that covers most steps to produce the heatmap is included in the package, with the name: `cluster_heatmaps()`. It plots the dendrogram, the annotation layer, the clustered data heatmap and the heatmap with the rest of the data not used for clustering. In the Shiny app this is done automatically, but outside, plotting the annotation and the unselected data are optional steps; the annotations require an extra step with the function `create_annotations()`. The colors used in the app are also exported by the package as the variable `cluster_colors`. ```{r heatmap} species_annotation <- create_annotations(iris, "Species") cluster_heatmaps(scale(subset_data), clusters, k, cluster_colors, annotation = species_annotation) ``` In addition to the heatmap, the boxplots in the app are also available through functions. There are two steps required to show data through box plots: annotating the original data with the cluster and plotting it. ```{r boxplots} annotated_data <- annotate_clusters(subset_data, cluster_labels, TRUE) cluster_boxplots(annotated_data) ```
/scratch/gouwar.j/cran-all/cranData/visxhclust/vignettes/clusterworkflow.Rmd
--- title: "visxhclust Shiny app tutorial" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{visxhclust Shiny app tutorial} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This is a simple visual tutorial on the basic loop of the visxhclust Shiny app -- note that almost every tab in the application has a corresponding help icon with more information and tips. To open the Shiny app you need to run: ```{r run, eval=FALSE} library(visxhclust) run_app() ``` ## Steps for simple iteration ### Step 1: Loading data and setting parameters ![Step 1](load_data.gif) ### Step 2: View clustering results ![Step 2](view_results.gif) ### Step 3: Evaluate ![Step 3](evaluate.gif) ### Step 4: Change parameters again ![Step 4](iterate.gif) ### Step 5: Review results ![Step 5](review_results.gif)
/scratch/gouwar.j/cran-all/cranData/visxhclust/vignettes/visxhclust.Rmd
CVPVI = function(X, ...) UseMethod("CVPVI") CVPVI.default = function(X, y, k = 2, mtry= if (!is.null(y) && !is.factor(y)) max(floor(ncol(X)/3), 1) else floor(sqrt(ncol(X))), ntree = 500, nPerm = 1, parallel = FALSE, ncores = 0, seed = 123, ...){ ################################################################## n = nrow(X) p = ncol(X) if (n == 0) stop("data (x) has 0 rows") x.col.names <- if (is.null(colnames(X))) 1:p else colnames(X) if (!is.null(y)) { if (length(y) != n) stop("length of response must be the same as predictors") } if (any(is.na(X))) stop("NA not permitted in predictors") if (any(is.na(y))) stop("NA not permitted in response") ################################################################## # Windows and parallel ? if(Sys.info()[['sysname']] == "Windows" & parallel ){ cat("\n The parallelized version of the CVPVI implementation are not available on Windows !! \n") parallel = FALSE } ################################################################## # parallel ? if(parallel) { # The number of cores to use, i.e. at most how many child processes will # be run simultaneously. d_ncores = parallel::detectCores() if(ncores>d_ncores) stop("ncores: The number of cores is too large") if(ncores==0){ ncores = max(c(1,floor(d_ncores/2))) } if(k < ncores ) { ncores2 = floor(ncores/k) ncores = k } else { ncores2 = 1 } ## To make this reproducible # Random Number Generation # A "combined multiple-recursive generator" from L'Ecuyer (1999) if("L'Ecuyer-CMRG" != RNGkind()[1]) { cat("\n The random number generator was set to L'Ecuyer-CMRG !! \n") RNGkind("L'Ecuyer-CMRG") } } else { ncores = 1 } # specify seeds set.seed(seed) ################################################################## ## Split indexes k- folds cuts = round(length(y)/k) from = (0:(k-1)*cuts)+1 to = (1:k*cuts) if(to[k]!=length(y)) to[k] = length(y) rs = sample(1:length(y)) l = 1:k ################################################################## # parallel CVPVI implementation if(parallel) { ################################################################## ## Split ntree/ncores2 nt = rep(floor(ntree/ncores2),ncores2) if(sum(nt)<ntree){nt[ncores2] = nt[ncores2] + ntree - sum(nt)} cvl_varim = parallel::mclapply(l, function (l) { lth = rs[from[l]:to[l]] # without the l-th data set Xl = X[-lth,] yl = y[-lth] # the l-th data set X_l = X[lth,] y_l = y[lth] CVVI_ln = parallel::mclapply(nt, function (nt) { rForest_ln = randomForest::randomForest(Xl,yl, mtry = mtry, ntree = nt, keep.forest = T,...) VarImpCVl(X_l,y_l,rForest_ln)[[1]] },mc.cores = ncores2) CVVI_ln=simplify2array(CVVI_ln)[,1,] return((CVVI_ln%*%nt)/ntree) }, mc.cores = ncores) ################################################################## # non parallel CVPVI implementation } else { nt=1 cvl_varim = lapply(l, function (l) { lth = rs[from[l]:to[l]] # without the l-th data set Xl = X[-lth,] yl = y[-lth] # the l-th data set X_l = X[lth,] y_l = y[lth] rForest_l = randomForest::randomForest(Xl,yl, mtry = mtry, ntree = ntree, keep.forest = T,...) # Compute l-th fold-specific variable importance return(VarImpCVl(X_l,y_l,rForest_l,nPerm)) } ) } if (length(nt) == 1 ) { m = as.data.frame.list(cvl_varim) cvl_varimf = m[seq(from = 1, to = 2*k, by = 2)] rownames(cvl_varimf) = x.col.names colnames(cvl_varimf) = paste0(l, rep("-fold_PerVarImp", k)) } else { cvl_varimf = simplify2array(cvl_varim)[,1,] rownames(cvl_varimf) = x.col.names colnames(cvl_varimf) = paste0(l, rep("-fold_PerVarImp", k)) } out = list( # fold-specific permutation variable importance fold_varim = cvl_varimf, # cross-valdated permutation variable importance cv_varim = matrix(rowMeans(cvl_varimf),ncol = 1,dimnames = list(x.col.names ,"CV_PerVarImp")), type = if (is.factor(y)) {"classification"} else{"regression"}, call = match.call()) class(out) = "CVPVI" return(out) } print.CVPVI = function(x, ...){ if (!inherits(x, "CVPVI")) stop(" is not of class CVPVI") cat("Call:\n \n") print(x$call) cat("type: ") print(x$type) cat("\nfold-specific permutation variable importance:\n\n") print(x$fold_varim) cat("\ncross-validated permutation variable importance:\n\n") print(x$cv_varim) }
/scratch/gouwar.j/cran-all/cranData/vita/R/CVPVI.R
NTA = function(PerVarImp) UseMethod("NTA") NTA.default = function (PerVarImp){ # M1 = {VI_j|VI_j<0; j=0,...,p} M1 = PerVarImp[which(PerVarImp<0)] # M2 = {VI_j|VI_j=0; j=0,...,p} M2 = PerVarImp[which(PerVarImp==0)] # M3 = {-VI_j|VI_j<0; j=0,...,p} M3 = -M1 # M = M1 u M2 u M3 if(length(M2)==0){ M = c(M1,M3) } else { M = c(M1,M2,M3) } # The empirical cumulative null distribution function Fn0 of M Fn0 = ecdf(M) out = list ( PerVarImp = PerVarImp, M = M, pvalue = matrix(1-Fn0(PerVarImp),ncol = 1,dimnames = list(dimnames(PerVarImp)[[1]] ,"p-value") ), call = match.call()) class(out) = "NTA" return(out) } print.NTA = function(x, ...){ op = options() options(width = 90, digits = 2) if (!inherits(x, "NTA")) stop(" is not of class NTA") cat("Call:\n \n") print(x$call) cat("------------------------------------------------------------------------------------\n") cat("The non-positive variable importance values with the mirrored values:\n") cat("------------------------------------------------------------------------------------\n") print(format(t(x$M),digits = 2, nsmall = 1,justify = "left"),quote = F) cat("------------------------------------------------------------------------------------\n") cat("p-value :\n") cat("------------------------------------------------------------------------------------\n") print(format(t(x$pvalue),digits = 2, nsmall = 1,justify = "left"),quote = F) options(op) }
/scratch/gouwar.j/cran-all/cranData/vita/R/NTA.R
PIMP = function(X, ...) UseMethod("PIMP") PIMP.default = function(X, y, rForest, S = 100, parallel = FALSE, ncores=0, seed = 123, ...){ ################################################################## # randomForest? if (!inherits(rForest, "randomForest")) stop("rForest is not of class randomForest") mtry=rForest$mtry ntree=rForest$ntree n = nrow(X) p = ncol(X) ################################################################## # Windows and parallel ? if(Sys.info()[['sysname']] == "Windows" & parallel ){ cat("\n The parallelized version of the PIMP-algorithm are not available on Windows !! \n") parallel = FALSE } ################################################################## # parallel ? if(parallel) { # The number of cores to use, i.e. at most how many child processes will # be run simultaneously. d_ncores = parallel::detectCores() if(ncores>d_ncores) stop("ncores: The number of cores is too large") if(ncores==0){ ncores = max(c(1,floor(d_ncores/2))) } ## To make this reproducible # Random Number Generation # A "combined multiple-recursive generator" from L'Ecuyer (1999) if("L'Ecuyer-CMRG" != RNGkind()[1]) { cat("\n The random number generator was set to L'Ecuyer-CMRG !! \n") RNGkind("L'Ecuyer-CMRG") } } else { ncores = 1 } # specify seeds set.seed(seed) ################################################################## # classification ? classRF = is.factor(y) if (classRF) { if(rForest$type == "regression") stop("rForest$type = regression !! y a factor ") ################################################################## # permutes the response vector y.s=replicate(S,sample(as.integer(y))) # Number of permutation i=1:S varip = parallel::mclapply(i, function (i) { randomForest::randomForest(X,as.factor(y.s[,i]),mtry = mtry, importance=TRUE,ntree=ntree,...)[[9]][,3] }, mc.cores =ncores) varip=simplify2array(varip) } else { if(rForest$type == "classification") stop("rForest$type = classification !! y not a factor ") ################################################################## # permutes the response vector y.s=replicate(S,sample(y )) # Number of permutation i=1:S varip = parallel::mclapply(i, function (i) { randomForest::randomForest(X,y.s[,i],mtry = mtry, importance=TRUE,ntree=ntree,...)[[7]][,1] }, mc.cores =ncores) varip=simplify2array(varip) } # dimNames=dimnames(rForest$importance)[[1]] out=list(VarImp = matrix(rForest$importance[,1], ncol=1, dimnames=list(dimNames ,"VarImp")), PerVarImp = varip, type = if (classRF) {"classification"} else{"regression"}, call = match.call()) class(out) = "PIMP" return(out) } print.PIMP = function(x, ...){ if (!inherits(x, "PIMP")) stop(" is not of class PIMP") cat("Call:\n \n") print(x$call) cat("type: ") print(x$type) cat("\noriginal VarImp:\n") print(x$VarImp) cat("\npermutation VarImp:\n") print(x$PerVarImp) }
/scratch/gouwar.j/cran-all/cranData/vita/R/PIMP.R
PimpTest = function(Pimp, ...) UseMethod("PimpTest") PimpTest.default = function(Pimp, para = FALSE, ...){ ################################################################## # randomForest? if (!inherits(Pimp, "PIMP")) stop("Pimp is not of class PIMP") p = nrow(Pimp$PerVarImp) if(para){ # mean and sample variance mean.PerVarImp = apply(Pimp$PerVarImp, 1, mean) sd.PerVarImp = apply(Pimp$PerVarImp, 1, sd) # Kolmogorov-Smirnov Test i=1:p test.norm = sapply(i, function(i){ ks.test(unique(Pimp$PerVarImp[i,]), "pnorm",mean = mean.PerVarImp[i],sd = sd.PerVarImp[i])$p.value }) # the p-value is the probability of observing the original VarImp or one more extreme, p.val = sapply(i, function(i){ pnorm(Pimp$VarImp[i], mean.PerVarImp[i], sd.PerVarImp[i], lower.tail=F) }) } else{ i=1:p # The empirical cumulative null distribution functions Fn0^{*s} of VarImp^{*s} Fn0 = sapply(i, function(i){ ecdf(Pimp$PerVarImp[i,]) }) # the p-value is the probability of observing the original VarImp or one more extreme, p.val = sapply(i, function(i){ 1-Fn0[[i]](Pimp$VarImp[i]) }) } # dimNames=dimnames(Pimp$VarImp)[[1]] out=list(VarImp = Pimp$VarImp, PerVarImp = Pimp$PerVarImp, para = para , meanPerVarImp = if(para){ matrix(mean.PerVarImp, ncol=1, dimnames=list(dimNames, "mean(PerVarImp)")) } else { NULL }, sdPerVarImp =if(para){ matrix(sd.PerVarImp, ncol=1, dimnames=list(dimNames, "sd(PerVarImp)")) } else { NULL }, p.ks.test = if(para){ matrix(test.norm,ncol=1, dimnames=list(dimNames, "ks.test")) } else { NULL}, pvalue = matrix(p.val, ncol=1, dimnames=list(dimNames, "p-value")), type=Pimp$type, call.PIMP=Pimp$call, call = match.call()) class(out) = "PimpTest" return(out) } print.PimpTest = function(x, ...){ if (!inherits(x, "PimpTest")) stop(" is not of class PIMP.Test") cat("Call:\n \n") print(x$call) cat("type: ") print(x$type) cat("\noriginal VarImp:\n") print(x$VarImp) cat("\np-value:\n") print(x$pvalue) }
/scratch/gouwar.j/cran-all/cranData/vita/R/PimpTest.R
# This file was generated by Rcpp::compileAttributes # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 Rcpp_compVarImpReg <- function(x, y, nsample, mdim, nTree, nPerm, lDaughter, rDaughter, nodestatus, split, nodepred, splitVar, inm, ndbigtree, cat, maxcat) { .Call('vita_Rcpp_compVarImpReg', PACKAGE = 'vita', x, y, nsample, mdim, nTree, nPerm, lDaughter, rDaughter, nodestatus, split, nodepred, splitVar, inm, ndbigtree, cat, maxcat) } Rcpp_compVarImpCL <- function(x, y, nsample, mdim, nTree, nclass, lDaughter, rDaughter, nodestatus, xbestsplit, nodeclass, bestvar, inbag, ndbigtree, cat, maxcat) { .Call('vita_Rcpp_compVarImpCL', PACKAGE = 'vita', x, y, nsample, mdim, nTree, nclass, lDaughter, rDaughter, nodestatus, xbestsplit, nodeclass, bestvar, inbag, ndbigtree, cat, maxcat) } Rcpp_VarImpCVLReg <- function(x_l, y_l, nsample, mdim, nTree, nPerm, lDaughter, rDaughter, nodestatus, split, nodepred, splitVar, ndbigtree, cat, maxcat) { .Call('vita_Rcpp_VarImpCVLReg', PACKAGE = 'vita', x_l, y_l, nsample, mdim, nTree, nPerm, lDaughter, rDaughter, nodestatus, split, nodepred, splitVar, ndbigtree, cat, maxcat) } Rcpp_VarImpCVLCL <- function(x_l, y_l, nsample, mdim, nTree, nclass, lDaughter, rDaughter, nodestatus, xbestsplit, nodeclass, bestvar, ndbigtree, cat, maxcat) { .Call('vita_Rcpp_VarImpCVLCL', PACKAGE = 'vita', x_l, y_l, nsample, mdim, nTree, nclass, lDaughter, rDaughter, nodestatus, xbestsplit, nodeclass, bestvar, ndbigtree, cat, maxcat) }
/scratch/gouwar.j/cran-all/cranData/vita/R/RcppExports.R
VarImpCVl = function (X_l, y_l, rForest, nPerm = 1){ if (!inherits(rForest, "randomForest")) stop("rForest is not of class randomForest") if(is.null(rForest$forest)) stop("in randomForest keep.forest must be set to True") n = nrow(X_l) p = ncol(X_l) if(n == 0) stop("data (X_l) has 0 rows") x.col.names <- if (is.null(colnames(X_l))) 1:p else colnames(X_l) if (is.data.frame(X_l)) { xlevels = lapply(X_l, function(x) if (is.factor(x)) levels(x) else 0) ncat = sapply(xlevels, length) ## Treat ordered factors as numerics. ncat = ifelse(sapply(X_l, is.ordered), 1, ncat) maxncat = max(ncat) X_l = data.matrix(X_l) } else{ ncat = rep(1, p) maxncat = 1 } if (!is.null(y_l)) { if (length(y_l) != n) stop("length of response must be the same as predictors") } if (any(is.na(X_l))) stop("NA not permitted in predictors") if (any(is.na(y_l))) stop("NA not permitted in response") classRF = is.factor(y_l) # classification ? if (classRF) { if (!all(levels(y_l) == levels(rForest$y_l))) stop("y_l and rForest$y must have the same levels") if(rForest$type == "regression") stop("rForest$type = regression !! y_l a factor ") nclass = length(levels(y_l)) classOut = .Call('vita_Rcpp_VarImpCVLCL', PACKAGE = 'vita', t(X_l), as.integer(y_l), n, p, rForest$ntree, as.integer(nclass), rForest$forest$treemap[,1,], rForest$forest$treemap[,2,], rForest$forest$nodestatus, rForest$forest$xbestsplit, rForest$forest$nodepred, rForest$forest$bestvar, rForest$forest$ndbigtree, ncat, maxncat) return( list( fold_importance = matrix(classOut$fold_importance, p, 1, dimnames=list(x.col.names, c("MeanDecreaseAccuracy")) ), type = "classification" ) ) } else{ if(rForest$type == "classification") stop("rForest$type = classification !! y_l not a factor ") regOut = .Call('vita_Rcpp_VarImpCVLReg', PACKAGE = 'vita', t(X_l),y_l, n, p, rForest$ntree,nPerm, rForest$forest$leftDaughter, rForest$forest$rightDaughter, rForest$forest$nodestatus, rForest$forest$xbestsplit, rForest$forest$nodepred, rForest$forest$bestvar, rForest$forest$ndbigtree, ncat, maxncat) return( list( fold_importance = matrix(regOut$fold_importance, p, 1, dimnames=list(x.col.names, c("%IncMSE")) ), type = "regression" ) ) } }
/scratch/gouwar.j/cran-all/cranData/vita/R/VarImpCVl.R
compVarImp = function(X, y,rForest,nPerm = 1){ if (!inherits(rForest, "randomForest")) stop("rForest is not of class randomForest") if(is.null(rForest$inbag)) stop("in randomForest keep.inbag must be set to True") if(is.null(rForest$forest)) stop("in randomForest keep.forest must be set to True") n = nrow(X) p = ncol(X) if (n == 0) stop("data (x) has 0 rows") x.col.names <- if (is.null(colnames(X))) 1:p else colnames(X) if (is.data.frame(X)) { X = data.matrix(X) } if (!is.null(y)) { if (length(y) != n) stop("length of response must be the same as predictors") } if (any(is.na(X))) stop("NA not permitted in predictors") if (any(is.na(y))) stop("NA not permitted in response") classRF = is.factor(y) if (classRF) { if (!all(levels(y) == levels(rForest$y))) stop("y and rForest$y must have the same levels") if(rForest$type == "regression") stop("rForest$type = regression !! y a factor ") nclass = length(levels(y)) classOut = .Call('vita_Rcpp_compVarImpCL', PACKAGE = 'vita', t(X), as.integer(y), n, p, rForest$ntree, as.integer(nclass), rForest$forest$treemap[,1,], rForest$forest$treemap[,2,], rForest$forest$nodestatus, rForest$forest$xbestsplit, rForest$forest$nodepred, rForest$forest$bestvar, rForest$inbag, rForest$forest$ndbigtree, rForest$forest$ncat, rForest$forest$maxcat ) dimnames(classOut$importance) = list(x.col.names, c(levels(y), "MeanDecreaseAccuracy")) dimnames(classOut$importanceSD) = list(x.col.names, c(levels(y), "MeanDecreaseAccuracy")) return( list( importance = classOut$importance, importanceSD = classOut$importanceSD, type = "classification" ) ) }else { if(rForest$type == "classification") stop("rForest$type = classification !! y not a factor ") regOut = .Call('vita_Rcpp_compVarImpReg', PACKAGE = 'vita', t(X),y, n,p, rForest$ntree,nPerm,rForest$forest$leftDaughter, rForest$forest$rightDaughter,rForest$forest$nodestatus, rForest$forest$xbestsplit,rForest$forest$nodepred, rForest$forest$bestvar,rForest$inbag,rForest$forest$ndbigtree, rForest$forest$ncat, max(rForest$forest$ncat)) return( list( importance = matrix(regOut$importance, p, 1, dimnames=list(x.col.names, c("%IncMSE")) ), importanceSD = matrix(regOut$importanceSD, p, 1, dimnames=list(x.col.names, c("%IncMSE")) ), type = "regression" ) ) } }
/scratch/gouwar.j/cran-all/cranData/vita/R/compVarImp.R
summary.NTA = function(object, pless=0.05,...){ if (!inherits(object, "NTA")) stop(" is not of class NTA") cmat = cbind( object$PerVarImp, object$pvalue) colnames(cmat) = c( "CV-PerVarImp", "p-value" ) rownames(cmat) = dimnames(object$PerVarImp)[[1]] res = list(call = object$call, cmat = cmat, pless=pless) class(res) = "summary.NTA" return(res) } print.summary.NTA = function(x, ...){ cat("Call:\n") print(x$call) w05=which(x$cmat[, 2] < x$pless) if(length(w05)>0){ if(length(w05)>1){ cat("\n") cat("\n p-values less than ",x$pless,":") cat("\n ---------------------------") cat("\n") printCoefmat(x$cmat[w05,],has.Pvalue = TRUE) } else { cat("\n") cat("\n p-values less than ",x$pless,":") cat("\n ---------------------------") cat("\n") printCoefmat(matrix(x$cmat[w05,],ncol = 2, dimnames = list(rownames(x$cmat[c(w05,w05+1),])[1],c("VarImp","p-value"))), has.Pvalue = TRUE) } } else { cat("\n") cat("\n p-values less than ",x$pless,":") cat("\n ---------------------------") cat("\n") cat("None!!!") } }
/scratch/gouwar.j/cran-all/cranData/vita/R/summaryNTA.R
summary.PimpTest = function(object, pless=0.05,...){ if (!inherits(object, "PimpTest")) stop(" is not of class PimpTest") if(object$para){ cmat = cbind( object$meanPerVarImp, object$sdPerVarImp, object$p.ks.test) colnames(cmat) = c( "mean(PerVarImp)", "sd(PerVarImp)", "ks.p-value" ) rownames(cmat) = dimnames(object$VarImp)[[1]] } else{ cmat = NULL } cmat2 = cbind(object$VarImp , object$pvalue) colnames(cmat2) = c("VarImp","p-value") rownames(cmat2) = dimnames(object$VarImp)[[1]] res = list(para = object$para, type = object$type, call = object$call, call.PIMP=object$call.PIMP, cmat = cmat, cmat2 = cmat2, pless = pless) class(res) <- "summary.PimpTest" return(res) } print.summary.PimpTest = function(x, ...){ ####################################################################### # Output of results cat("Call:\n") print(x$call) cat("\n") print(x$call.PIMP) cat("type: ") print(x$type) cat("\n") if(x$para){ cat("\n Kolmogorov-Smirnov test for the null importances:") cat("\n -------------------------------------------------") cat("\n") printCoefmat(x$cmat,has.Pvalue = T) } w05=which(x$cmat2[, 2] < x$pless) if(length(w05)>0){ if(length(w05)>1){ cat("\n") cat("\n p-values less than ",x$pless,":") cat("\n ----------------------") cat("\n") printCoefmat(x$cmat2[w05,],has.Pvalue = TRUE) } else { cat("\n") cat("\n p-values less than ",x$pless,":") cat("\n ----------------------") cat("\n") printCoefmat(matrix(x$cmat2[w05,],ncol = 2, dimnames = list(rownames(x$cmat2[c(w05,w05+1),])[1],c("VarImp","p-value"))), has.Pvalue = TRUE) } } else { cat("\n") cat("\n p-values less than ",x$pless,":") cat("\n ----------------------") cat("\n") cat("None!!!") } }
/scratch/gouwar.j/cran-all/cranData/vita/R/summaryPimpTest.R
# Output format for entries entry_format_functions <- new.env(parent = emptyenv()) set_entry_formats <- function(entry_format) { entry_format_functions$format <- entry_format } new_entry_formats <- function(brief, detailed) { list(brief = brief, detailed = detailed) }
/scratch/gouwar.j/cran-all/cranData/vitae/R/00_entries.R
#' Awesome CV template #' #' Awesome CV is LaTeX template for a CV or Résumé inspired by #' [Fancy CV](https://www.overleaf.com/latex/templates/friggeri-cv-template/hmnchbfmjgqh): #' https://github.com/posquit0/Awesome-CV #' #' @param \dots Arguments passed to \code{\link[vitae]{cv_document}}. #' @inheritParams rmarkdown::pdf_document #' @param page_total If TRUE, the total number of pages is shown in the footer. #' @param show_footer If TRUE, a footer showing your name, document name, and page number. #' #' @section Preview: #' `r insert_preview("awesomecv")` #' #' @return An R Markdown output format object. #' #' @author Mitchell O'Hara-Wild, theme by Byungjin Park #' ([@posquit0](https://github.com/posquit0)) #' #' @export awesomecv <- function(..., latex_engine = "xelatex", page_total = FALSE, show_footer = TRUE) { template <- system.file("rmarkdown", "templates", "awesomecv", "resources", "awesome-cv.tex", package = "vitae" ) set_entry_formats(awesome_cv_entries) copy_supporting_files("awesomecv") pandoc_vars <- list() if(page_total) pandoc_vars$page_total <- TRUE if(show_footer) pandoc_vars$show_footer <- TRUE cv_document(..., pandoc_vars = pandoc_vars, template = template, latex_engine = latex_engine) } awesome_cv_entries <- new_entry_formats( brief = function(what, when, with){ paste( c( "\\begin{cvhonors}", glue_alt("\t\\cvhonor{}{<<what>>}{<<with>>}{<<when>>}"), "\\end{cvhonors}" ), collapse = "\n" ) }, detailed = function(what, when, with, where, why){ why <- lapply(why, function(x) { if(length(x) == 0) { "{}\\vspace{-4.0mm}" } else { paste(c("{\\begin{cvitems}", paste("\\item", x), "\\end{cvitems}}"), collapse = "\n") } }) paste(c( "\\begin{cventries}", glue_alt("\t\\cventry{<<what>>}{<<with>>}{<<where>>}{<<when>>}<<why>>"), "\\end{cventries}" ), collapse = "\n") } )
/scratch/gouwar.j/cran-all/cranData/vitae/R/awesomecv.R
#' Print bibliography section #' #' Given a bibliography file, this function will generate bibliographic entries #' for one or more types of bib entry. #' #' @param file A path to a bibliography file understood by [`rmarkdown::pandoc_citeproc_convert()`]. #' @param startlabel Defunct. #' @param endlabel Defunct. #' #' @return A dataset representing the bibliographic entries, suitable for #' generating a reference section in a document. #' #' @author Mitchell O'Hara-Wild & Rob J Hyndman #' #' @examplesIf rmarkdown::pandoc_available("2.7") #' # Create a bibliography from a set of packages #' bib <- tempfile(fileext = ".bib") #' knitr::write_bib(c("vitae", "tibble"), bib) #' #' # Import the bibliography entries into a CV #' bibliography_entries(bib) #' #' # The order of these entries can be customised using `dplyr::arrange()` #' bibliography_entries(bib) %>% #' arrange(desc(title)) #' #' # For more complex fields like author, you can also sort by component fields. #' # For example, use `author$family` to sort by family names. #' bibliography_entries(bib) %>% #' arrange(desc(author$family)) #' @export bibliography_entries <- function(file, startlabel = NULL, endlabel = NULL) { if(!is.null(startlabel)){ warning("The `startlabel` argument is defunct and will be removed in the next release.\nPlease use a different approach to including labels.") } if(!is.null(endlabel)){ warning("The `endlabel` argument is defunct and will be removed in the next release.\n. Please use a different approach to including labels.") } # Parse bib file # Set system() output encoding as UTF-8 to fix Windows issue (rmarkdown#2195) bib <- rmarkdown::pandoc_citeproc_convert(file, type = "json") Encoding(bib) <- "UTF-8" bib <- jsonlite::fromJSON(bib, simplifyVector = FALSE) # Produce prototype bib_schema <- unique(vec_c(!!!lapply(bib, names))) ## Add missing fields to schema csl_idx <- match(bib_schema, names(csl_fields)) csl_fields[bib_schema[which(is.na(csl_idx))]] <- character() ## Use schema as prototype bib_ptype <- csl_fields[bib_schema] bib_ptype <- vctrs::vec_init(bib_ptype, 1) # Add missing values to complete rectangular structure bib <- lapply(bib, function(x) { # missing_cols <- setdiff(names(bib_ptype), names(x)) # x[missing_cols] <- as.list(bib_ptype[missing_cols]) array_pos <- lengths(x) > 1 x[array_pos] <- lapply(x[array_pos], list) bib_ptype[names(x)] <- x bib_ptype }) bib <- vctrs::vec_rbind(!!!bib, .ptype = bib_ptype) tibble::new_tibble(bib, preserve = "id", class = c("vitae_bibliography", "vitae_preserve"), nrow = nrow(bib)) } #' @importFrom tibble tbl_sum #' @export tbl_sum.vitae_bibliography <- function(x) { x <- NextMethod() c(x, "vitae type" = "bibliography entries") } #' @importFrom knitr knit_print #' @export knit_print.vitae_bibliography <- function(x, options = knitr::opts_current$get(), ...) { # Reconstruct yaml from tibble yml <- lapply( dplyr::group_split(dplyr::rowwise(x)), function(x) { x <- as.list(x) el_is_list <- vapply(x, is.list, logical(1L)) x[el_is_list] <- lapply(x[el_is_list], `[[`, i=1) Filter(function(x) !is.na(x[1]) && length(x) > 0, x) }) if((options$cache %||% 0) == 0) { file <- tempfile(fileext = ".yaml") } else { file <- paste0(options$cache.path, options$label, ".yaml") } yaml::write_yaml(list(references = yml), file = file) startlabel <- x %@% "startlabel" endlabel <- x %@% "endlabel" out <- glue( ' ::: {#refs-<< rlang::hash_file(file) >>} ::: ', .open = "<<", .close = ">>" ) # Convert file separator to format expected by pandoc-citeproc on Windows file <- gsub("\\", "/", file, fixed = TRUE) knitr::asis_output(out, meta = list(structure(list(file = file, id = x$id), class = "vitae_nocite"))) }
/scratch/gouwar.j/cran-all/cranData/vitae/R/bibliography.R
#' @rdname cv_entries #' @importFrom rlang enexpr expr_text !! #' @export brief_entries <- function(data, what, when, with, .protect = TRUE) { edu_exprs <- list( what = enquo(what) %missing% NA_character_, when = enquo(when) %missing% NA_character_, with = enquo(with) %missing% NA_character_ ) out <- dplyr::as_tibble(map(edu_exprs, eval_tidy, data = data)) structure(out, preserve = names(edu_exprs), protect = .protect, class = c("vitae_brief", "vitae_preserve", class(data)) ) } #' @importFrom tibble tbl_sum #' @export tbl_sum.vitae_brief <- function(x) { x <- NextMethod() c(x, "vitae type" = "brief entries") } #' @importFrom knitr knit_print #' @export knit_print.vitae_brief <- function(x, options, ...) { if(is.null(entry_format_functions$format)) { warn("Brief entry formatter is not defined for this output format.") return(knit_print(tibble::as_tibble(x))) } x[is.na(x)] <- "" if(!(x%@%"protect")){ protect_tex_input <- identity } knitr::asis_output( entry_format_functions$format$brief( protect_tex_input(x$what), protect_tex_input(x$when), protect_tex_input(x$with) ) ) }
/scratch/gouwar.j/cran-all/cranData/vitae/R/brief.R
# nocov start # This file serves as a reference for compatibility functions for # purrr. They are not drop-in replacements but allow a similar style # of programming. This is useful in cases where purrr is too heavy a # package to depend on. map <- function(.x, .f, ...) { lapply(.x, .f, ...) } map_mold <- function(...) { out <- vapply(..., USE.NAMES = FALSE) names(out) <- names(..1) out } map_chr <- function(.x, .f, ...) { map_mold(.x, .f, character(1), ...) } # nocov end
/scratch/gouwar.j/cran-all/cranData/vitae/R/compact-purrr.R
#' A date conforming to the CSL schema #' #' This class provides helper utilities to display, sort, and select attributes #' from a date in the CSL format. #' #' @param x A list of `csl_date()` values. #' @param date_parts A list containing one or two dates in a list. Each date is #' also represented using lists in the format of `list(year, month, day)`. #' Different precision can be achieved by providing an incomplete list: #' `list(year, month)`. A range of dates can be specified by providing two #' dates, where the first date is the start and second date is the end of the #' interval. #' @param season,circa,literal,raw,edtf Additional date variable properties as #' described in the schema. #' #' @seealso #' <https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html#date-fields> #' #' @examples #' # Single date #' csl_date(date_parts = list(list(2020,03,05))) #' # Date interval #' csl_date(date_parts = list(list(2020,03,05), list(2020,08,25))) #' #' @keywords internal #' @export csl_date <- function(date_parts = list(), season = NULL, circa = NULL, literal = NULL, raw = NULL, edtf = NULL) { x <- list(`date-parts` = date_parts, season = season, circa = circa, literal = literal, raw = raw, edtf = edtf) new_csl_date(Filter(Negate(is.null), x), validate = FALSE) } csl_date_fields <- c("date-parts", "season", "circa", "literal", "raw", "edtf") new_csl_date <- function(x, validate = TRUE) { if(!validate || all(names(x) %in% csl_date_fields)) { structure(x, class = "csl_date") } else { abort(sprintf("Unknown CSL date properties: %s.", paste(setdiff(names(x), csl_date_fields), collapse = ", "))) } } #' @export format.csl_date <- function(x, ...) { dates <- vapply(x[["date-parts"]], function(x) paste(vec_c(!!!x), collapse = "-"), character(1)) dates <- paste(dates, collapse = "/") dates } #' @export print.csl_date <- function(x, ...) { cat(format(x, ...)) } #' @export vec_ptype_abbr.csl_dates <- function(x, ..., prefix_named = FALSE, suffix_shape = TRUE) "csl_date" #' @export as.Date.csl_date <- function(x, to, ...) { out <- c(1970, 1, 1) x <- vec_c(!!!x[["date-parts"]][[1]]) out[seq_along(x)] <- x as.Date(paste(out, collapse = "-")) } #' @rdname csl_date #' @export csl_dates <- function(x = list()) { vctrs::new_vctr(lapply(x, new_csl_date), class = "csl_dates") } #' @export vec_cast.csl_dates.list <- function(x, to, ...) { if("date-parts" %in% names(x)) x <- list(x) csl_dates(x) } #' @export format.csl_dates <- function(x, ...) { vapply(x, format, character(1L), ...) } #' @export vec_cast.Date.csl_dates <- function(x, to, ...) { vec_c(!!!lapply(x, as.Date)) } #' @export xtfrm.csl_dates <- function(x, ...) { xtfrm(as.Date(x)) } #' @export vec_proxy_order.csl_dates <- xtfrm.csl_dates
/scratch/gouwar.j/cran-all/cranData/vitae/R/csl_date.R
#' A name variable conforming to the CSL schema #' #' This class provides helper utilities to display, sort, and select attributes #' from a name in the CSL format. #' #' @param x For `csl_name()`, `x` should be a list of `csl_name()`. For #' `list_of_csl_names()`, `x` should be a list of `csl_names()`. #' @param family The family name #' @param given The given name #' @param dropping_particle,non_dropping_particle,suffix,comma_suffix,static_ordering,literal,parse_names Additional #' name variable properties as described in the schema. #' #' @seealso #' <https://citeproc-js.readthedocs.io/en/latest/csl-json/markup.html#name-fields> #' #' @keywords internal #' @export csl_name <- function(family = NULL, given = NULL, dropping_particle = NULL, non_dropping_particle = NULL, suffix = NULL, comma_suffix = NULL, static_ordering = NULL, literal = NULL, parse_names = NULL) { x <- list( family = family, given = given, `dropping-particle` = dropping_particle, `non-dropping-particle` = non_dropping_particle, suffix = suffix, `comma-suffix` = comma_suffix, `static-ordering` = static_ordering, literal = literal, `parse-names` = parse_names ) new_csl_name(Filter(Negate(is.null), x), validate = FALSE) } csl_name_fields <- c("family", "given", "dropping-particle", "non-dropping-particle", "suffix", "comma-suffix", "static-ordering", "literal", "parse-names") new_csl_name <- function(x, validate = TRUE) { if(!validate || all(names(x) %in% csl_name_fields)) { structure(x, class = "csl_name") } else { abort(sprintf("Unknown CSL name properties: %s.", paste(setdiff(names(x), csl_name_fields), collapse = ", "))) } } #' @export format.csl_name <- function(x, ...) { fmt <- x[c("non-dropping-particle", "dropping-particle", "given", "family", "suffix", "literal")] format(paste(Filter(Negate(is.null), fmt), collapse = " "), ...) } #' @export print.csl_name <- function(x, ...) { cat(format(x, ...)) } #' @rdname csl_name #' @export csl_names <- function(x = list()) { vctrs::new_vctr(lapply(x, new_csl_name), class = "csl_names") } #' @export format.csl_names <- function(x, ...) { vapply(x, format, character(1L), ...) } #' @rdname csl_name #' @export list_of_csl_names <- function(x = list()) { new_list_of(x, csl_names(), class = "list_of_csl_names") } #' @export format.list_of_csl_names <- function(x, ...) { vapply(x, function(z) paste(format(z, ...), collapse = ", "), character(1L)) } #' @export obj_print_data.list_of_csl_names <- function(x, ...) { print(format(x), quote = FALSE) } #' @export vec_cast.list_of_csl_names.list <- function(x, to, ...) { if(length(x) == 1 && !is.null(names(x[[1]]))) x <- list(x) list_of_csl_names(lapply(x, csl_names)) } #' @method vec_cast.character list_of_csl_names #' @export vec_cast.character.list_of_csl_names <- function(x, to, ...) { format(x) } #' @export xtfrm.list_of_csl_names <- function(x, ...) { xtfrm(format(x)) } #' @export vec_proxy_order.list_of_csl_names <- xtfrm.list_of_csl_names #' @export names.list_of_csl_names <- function(x) { csl_name_fields } #' @export `$.list_of_csl_names` <- function(x, name) { vapply(x, function(authors) { out <- vapply(authors, function(author) author[[name]], character(1L)) paste(out, collapse = ", ") }, character(1L)) } #' @importFrom pillar pillar_shaft #' @export pillar_shaft.list_of_csl_names <- function(x, ...) { pillar::new_pillar_shaft_simple(format(x), align = "left", min_width = 10) }
/scratch/gouwar.j/cran-all/cranData/vitae/R/csl_name.R
#' Output format for vitae #' #' This output format provides support for including LaTeX dependencies and #' bibliography entries in extension of the `rmarkdown::pdf_document()` format. #' #' @inheritParams rmarkdown::pdf_document #' @inheritParams bookdown::pdf_document2 #' @param ... Arguments passed to rmarkdown::pdf_document(). #' @param pandoc_vars Pandoc variables to be passed to the template. #' #' @keywords internal #' @export cv_document <- function(..., pandoc_args = NULL, pandoc_vars = NULL, base_format = rmarkdown::pdf_document) { for (i in seq_along(pandoc_vars)){ pandoc_args <- c(pandoc_args, rmarkdown::pandoc_variable_arg(names(pandoc_vars)[[i]], pandoc_vars[[i]])) } pandoc_args <- c( c(rbind("--lua-filter", system.file("multiple-bibliographies.lua", package = "vitae", mustWork = TRUE))), pandoc_args ) out <- base_format(..., pandoc_args = pandoc_args) pre <- out$pre_processor out$pre_processor <- function (metadata, input_file, runtime, knit_meta, files_dir, output_dir){ pre(metadata, input_file, runtime, knit_meta, files_dir, output_dir) # Add citations to front matter yaml, there may be a better way to do this. # For example, @* wildcard. Keeping as is to avoid unintended side effects. meta_nocite <- vapply(knit_meta, inherits, logical(1L), "vitae_nocite") bib_files <- lapply(knit_meta[meta_nocite], function(x) x$file) names(bib_files) <- vapply(bib_files, rlang::hash_file, character(1L)) metadata$bibliography <- bib_files bib_ids <- unique(unlist(lapply(knit_meta[meta_nocite], function(x) x$id))) metadata$nocite <- c(metadata$nocite, paste0("@", bib_ids, collapse = ", ")) if(is.null(metadata$csl)) metadata$csl <- system.file("vitae.csl", package = "vitae", mustWork = TRUE) body <- partition_yaml_front_matter(xfun::read_utf8(input_file))$body xfun::write_utf8( c("---", yaml::as.yaml(metadata), "---", body), input_file ) } out } copy_supporting_files <- function(template) { path <- system.file("rmarkdown", "templates", template, "skeleton", package = "vitae") files <- list.files(path) # Copy class and style files for (f in files[files != "skeleton.Rmd"]) { if (!file.exists(f)) { file.copy(file.path(path, f), ".", recursive = TRUE) } } }
/scratch/gouwar.j/cran-all/cranData/vitae/R/cv_document.R
#' CV entries #' #' This function accepts a data object (such as a tibble) and formats the output #' into a suitable format for the template used. The inputs can also involve #' further calculations, which will be done using the provided data. #' #' All non-data inputs are optional, and will result in an empty space if omitted. #' #' @param data A `data.frame` or `tibble`. #' @param what The primary value of the entry (such as workplace title or degree). #' @param when The time of the entry (such as the period spent in the role). #' @param with The company or organisation. #' @param where The location of the entry. #' @param why Any additional information, to be included as dot points. Multiple #' dot points can be provided via a list column. #' Alternatively, if the same `what`, `when`, `with`, and `where` combinations #' are found in multiple rows, the `why` entries of these rows will be combined #' into a list. #' @param .protect When TRUE, inputs to the previous arguments will be protected #' from being parsed as LaTeX code. #' #' @name cv_entries #' @rdname cv_entries #' #' @examples #' packages_used <- tibble::tribble( #' ~ package, ~ date, ~ language, ~ timezone, ~ details, #' "vitae", Sys.Date(), "R", Sys.timezone(), c("Making my CV with vitae.", "Multiple why entries."), #' "rmarkdown", Sys.Date()-10, "R", Sys.timezone(), "Writing reproducible, dynamic reports using R." #' ) #' packages_used %>% #' detailed_entries(what = package, when = date, with = language, where = timezone, why = details) #' #' @importFrom rlang enquo expr_text !! := sym syms #' @export detailed_entries <- function(data, what, when, with, where, why, .protect = TRUE) { edu_exprs <- list( what = enquo(what) %missing% NA_character_, when = enquo(when) %missing% NA_character_, with = enquo(with) %missing% NA_character_, where = enquo(where) %missing% NA_character_, why = enquo(why) %missing% NA_character_ ) edu_vars <- dplyr::as_tibble(map(edu_exprs[-5], eval_tidy, data = data)) data[names(edu_vars)] <- edu_vars data <- dplyr::group_by(data, !!!syms(names(edu_vars))) out <- dplyr::distinct(data, !!!syms(names(edu_exprs)[-5])) data <- dplyr::summarise(data, "why" := compact_list(!!edu_exprs[["why"]])) out <- dplyr::left_join(out, data, by = names(edu_exprs[-5])) structure(out, preserve = names(edu_exprs), protect = .protect, class = c("vitae_detailed", "vitae_preserve", class(data)) ) } #' @importFrom tibble tbl_sum #' @export tbl_sum.vitae_detailed <- function(x) { x <- NextMethod() c(x, "vitae type" = "detailed entries") } #' @importFrom knitr knit_print #' @export knit_print.vitae_detailed <- function(x, options, ...) { if(is.null(entry_format_functions$format)) { warn("Detailed entry formatter is not defined for this output format.") return(knit_print(tibble::as_tibble(x))) } x[is.na(x)] <- "" if(!(x%@%"protect")){ protect_tex_input <- identity } knitr::asis_output( entry_format_functions$format$detailed( protect_tex_input(x$what), protect_tex_input(x$when), protect_tex_input(x$with), protect_tex_input(x$where), lapply(x$why,protect_tex_input) ) ) }
/scratch/gouwar.j/cran-all/cranData/vitae/R/detailed.R
# dplyr methods to preserve attributes #' @importFrom rlang !!! set_names %@% preserve_attributes <- function(fn) { function(.data, ...) { out <- NextMethod() if (any(miss_col <- !(.data %@% "key" %in% colnames(out)))) { miss_nm <- colnames(.data)[miss_col] warn(glue( "This function lost the ", glue_collapse(miss_nm, sep = ", ", last = " and "), " columns! These values will be removed from the report." )) out <- mutate(out, !!!set_names(rep(list(NA), sum(miss_col)), miss_nm)) } out <- structure(out, class = union(class(.data), class(out))) attr <- append(attributes(out), attributes(.data)) `attributes<-`(out, attr[!duplicated(names(attr))]) } } #' @export #' @importFrom dplyr %>% dplyr::`%>%` #' @export #' @importFrom dplyr mutate dplyr::mutate #' @export mutate.vitae_preserve <- preserve_attributes(dplyr::mutate) #' @export #' @importFrom dplyr transmute dplyr::transmute #' @export transmute.vitae_preserve <- preserve_attributes(dplyr::transmute) #' @export #' @importFrom dplyr group_by dplyr::group_by #' @export group_by.vitae_preserve <- preserve_attributes(dplyr::group_by) #' @export #' @importFrom dplyr summarise dplyr::summarise #' @export summarise.vitae_preserve <- preserve_attributes(dplyr::summarise) #' @export #' @importFrom dplyr rename dplyr::rename #' @export rename.vitae_preserve <- preserve_attributes(dplyr::rename) #' @export #' @importFrom dplyr arrange dplyr::arrange #' @export arrange.vitae_preserve <- preserve_attributes(dplyr::arrange) #' @export #' @importFrom dplyr select dplyr::select #' @export select.vitae_preserve <- preserve_attributes(dplyr::select) #' @export #' @importFrom dplyr filter dplyr::filter #' @export filter.vitae_preserve <- preserve_attributes(dplyr::filter) #' @export #' @importFrom dplyr distinct dplyr::distinct #' @export distinct.vitae_preserve <- preserve_attributes(dplyr::distinct) #' @export #' @importFrom dplyr slice dplyr::slice #' @export slice.vitae_preserve <- preserve_attributes(dplyr::slice)
/scratch/gouwar.j/cran-all/cranData/vitae/R/dplyr.R
#' Hyndman CV template #' #' Produces a CV using the style used in Rob Hyndman's CV: #' https://robjhyndman.com/hyndsight/cv/ #' #' @param \dots Arguments passed to \code{\link[vitae]{cv_document}}. #' #' @section Preview: #' `r insert_preview("hyndman")` #' #' @return An R Markdown output format object. #' #' @author Rob J Hyndman & Mitchell O'Hara-Wild #' #' @export hyndman <- function(...) { template <- system.file("rmarkdown", "templates", "hyndman", "resources", "hyndmantemplate.tex", package = "vitae" ) set_entry_formats(hyndman_entries) cv_document(..., template = template) } hyndman_entries <- new_entry_formats( brief = function(what, when, with){ paste( c( "\\begin{longtable}{@{\\extracolsep{\\fill}}ll}", glue_alt( " <<when>> & \\parbox[t]{0.85\\textwidth}{% \\textbf{<<what>>}\\\\[-0.1cm]{\\footnotesize <<with>>}}\\\\[0.4cm]"), "\\end{longtable}" ), collapse = "\n" ) }, detailed = function(what, when, with, where, why){ why <- lapply(why, function(x) { if(length(x) == 0) return("\\empty%") paste(c( "\\vspace{0.1cm}\\begin{minipage}{0.7\\textwidth}%", "\\begin{itemize}%", paste0("\\item ", x, "%"), "\\end{itemize}%", "\\end{minipage}%" ), collapse = "\n") }) where <- ifelse(where == "", "\\empty%", paste0(where, "\\par%")) paste(c( "\\begin{longtable}{@{\\extracolsep{\\fill}}ll}", glue_alt( "<<when>> & \\parbox[t]{0.85\\textwidth}{% \\textbf{<<what>>}\\hfill{\\footnotesize <<with>>}\\newline <<where>> <<why>> \\vspace{\\parsep}}\\\\"), "\\end{longtable}" ), collapse = "\n") } )
/scratch/gouwar.j/cran-all/cranData/vitae/R/hyndman.R
#' latexcv cv and resume templates #' #' A collection of simple and easy to use, yet powerful LaTeX templates for CVs #' and resumes: https://github.com/jankapunkt/latexcv #' #' @param theme The theme used for the template (previews in link above). #' @param \dots Arguments passed to \code{\link[vitae]{cv_document}}. #' #' @section Preview: #' `r insert_preview("latexcv")` #' #' @return An R Markdown output format object. #' #' @author Mitchell O'Hara-Wild, themes by Jan Küster #' ([@jankapunkt](https://github.com/jankapunkt)) #' #' @export latexcv <- function(..., theme = c("classic", "modern", "rows", "sidebar", "two_column")) { theme <- match.arg(theme) if(theme != "classic"){ stop("Only the classic theme is currently supported.") } template <- system.file("rmarkdown", "templates", "latexcv", "resources", theme, "main.tex", package = "vitae" ) set_entry_formats(latexcv_cv_entries) copy_supporting_files("latexcv") cv_document(..., template = template) } latexcv_cv_entries <- new_entry_formats( brief = function(what, when, with){ paste( glue_alt("\\cvevent{<<when>>}{<<what>>}{<<with>>}{\\empty}{\\empty}"), collapse = "\n" ) }, detailed = function(what, when, with, where, why){ why <- lapply(why, function(x) { if(length(x) == 0) return("\\empty") paste(c( "\\begin{minipage}{0.7\\textwidth}%", "\\begin{itemize}%", paste0("\\item ", x, "%"), "\\end{itemize}%", "\\end{minipage}" ), collapse = "\n") }) where <- ifelse(where == "", "\\empty", paste("-", where)) paste( glue_alt("\\cvevent{<<when>>}{<<what>>}{<<with>><<where>>}{<<why>>}"), collapse = "\n" ) } )
/scratch/gouwar.j/cran-all/cranData/vitae/R/latexcv.R
#' Eliseo Papa's markdown-cv template #' #' Produces a CV in the HTML format using various styles of the markdown-cv #' template: https://github.com/elipapa/markdown-cv #' #' @param \dots Arguments passed to \code{\link[vitae]{cv_document}}. #' @param theme The style used in the CV (matches the prefix of CSS files). The #' "kjhealy" theme is inspired by [@kjhealy's vita template](https://github.com/kjhealy/kjh-vita), #' "blmoore" is from [@blmoore's md-cv template](https://github.com/blmoore/md-cv), and #' "davewhipp" is [@davewhipp's theme](https://github.com/davewhipp/markdown-cv) which #' notably has dates right aligned. #' #' @section Preview: #' `r insert_preview("markdowncv")` #' #' @return An R Markdown output format object. #' #' @author Mitchell O'Hara-Wild, theme by Eliseo Papa #' ([@elipapa](https://github.com/elipapa)) #' #' @export markdowncv <- function(..., theme = c("kjhealy", "blmoore", "davewhipp")) { theme <- match.arg(theme) template <- system.file("rmarkdown", "templates", "markdowncv", "resources", "markdowncv.html", package = "vitae") set_entry_formats(markdowncv_entries) copy_supporting_files("markdowncv") cv_document(..., pandoc_vars = list(theme = theme), mathjax = NULL, template = template, base_format = rmarkdown::html_document) } markdowncv_entries <- new_entry_formats( brief = function(what, when, with){ glue_alt( "<p>`<<when>>` <<what>> (<<with>>)</p>", collapse = "\n") }, detailed = function(what, when, with, where, why){ why <- lapply(why, function(x) { if(is_empty(x)) return("") x <- paste("<li>", x, "</li>", collapse = "\n") paste0("<ul>\n", x, "</ul>") }) glue_alt( "<p>`<<when>>` __<<where>>__ <<what>> (<<with>>) <<why>></p>", collapse = "\n") } )
/scratch/gouwar.j/cran-all/cranData/vitae/R/markdowncv.R
#' Moderncv template #' #' Moderncv provides a documentclass for typesetting curricula vitae in various #' styles. Moderncv aims to be both straightforward to use and customizable, #' providing five ready-made styles (classic, casual, banking, oldstyle and #' fancy): https://github.com/xdanaux/moderncv #' #' @param theme The theme used for the template. #' @param \dots Arguments passed to \code{\link[vitae]{cv_document}}. #' @inheritParams rmarkdown::pdf_document #' #' @section Preview: #' `r insert_preview("moderncv")` #' #' @return An R Markdown output format object. #' #' @author Mitchell O'Hara-Wild, theme by Xavier Danaux #' ([@xdanaux](https://github.com/xdanaux)) #' #' @export moderncv <- function(..., theme = c("casual", "classic", "oldstyle", "banking", "fancy"), latex_engine = "pdflatex") { theme <- match.arg(theme) template <- system.file("rmarkdown", "templates", "moderncv", "resources", "moderncv.tex", package = "vitae" ) set_entry_formats(moderncv_cv_entries) copy_supporting_files("moderncv") cv_document(..., pandoc_vars = list(theme = theme), template = template, latex_engine = latex_engine) } moderncv_cv_entries <- new_entry_formats( brief = function(what, when, with){ paste( c( "\\nopagebreak", glue_alt("\t\\cvitem{<<when>>}{<<what>>. <<with>>}") ), collapse = "\n" ) }, detailed = function(what, when, with, where, why){ why <- lapply(why, function(x) { if(length(x) == 0) return("\\empty") paste(c( "\\begin{itemize}%", paste0("\\item ", x, "%"), "\\end{itemize}" ), collapse = "\n") }) paste(c( "\\nopagebreak", glue_alt("\t\\cventry{<<when>>}{<<what>>}{<<with>>}{<<where>>}{}{<<why>>}") ), collapse = "\n") } )
/scratch/gouwar.j/cran-all/cranData/vitae/R/moderncv.R
#' Include a preview of the CV template output for documentation #' #' @param template Name of the template #' #' @keywords internal insert_preview <- function(template) { preview <- paste0("preview-", template, ".png") if(!file.exists(file.path("man", "figures", preview))) { abort(paste0("Missing preview for ", template, ". Add it with render_preview(<template>) from data-raw/preview.R.")) } knitr::asis_output( sprintf( "![](%s 'Template preview')", preview ) ) }
/scratch/gouwar.j/cran-all/cranData/vitae/R/preview.R
/scratch/gouwar.j/cran-all/cranData/vitae/R/reexports.R
#' Twenty Seconds CV template #' #' A curriculum vitae, otherwise known as a CV or résumé, is a document used by #' individuals to communicate their work history, education and skill set. This #' is a style template for your curriculum written in LaTex. The main goal of #' this template is to provide a curriculum that is able to survive to the #' résumés screening of "twenty seconds": #' https://github.com/spagnuolocarmine/TwentySecondsCurriculumVitae-LaTex #' #' @param \dots Arguments passed to \code{\link[vitae]{cv_document}}. #' #' @section Preview: #' `r insert_preview("twentyseconds")` #' #' @return An R Markdown output format object. #' #' @author Mitchell O'Hara-Wild, theme by Carmine Spagnuolo #' ([@spagnuolocarmine](https://github.com/spagnuolocarmine)) #' #' @export twentyseconds <- function(...) { template <- system.file("rmarkdown", "templates", "twentyseconds", "resources", "twentysecondstemplate.tex", package = "vitae" ) set_entry_formats(twentyseconds_cv_entries) copy_supporting_files("twentyseconds") cv_document(..., template = template) } twentyseconds_cv_entries <- new_entry_formats( brief = function(what, when, with){ paste( c( "\\nopagebreak\\begin{twentyshort}", glue_alt("\t\\twentyitemshort{<<when>>}{<<what>>. <<with>>}"), "\\end{twentyshort}" ), collapse = "\n" ) }, detailed = function(what, when, with, where, why){ why <- lapply(why, function(x) { if(length(x) == 0) return("\\empty") paste(c( "\\begin{minipage}{0.7\\textwidth}%", "\\begin{itemize}%", paste0("\\item ", x, "%"), "\\end{itemize}%", "\\end{minipage}" ), collapse = "\n") }) where <- ifelse(where == "", "\\empty", paste0(where, "\\par")) paste(c( "\\nopagebreak\\begin{twenty}", glue_alt("\t\\twentyitem{<<when>>}{<<what>>}{<<with>>}{<<where>><<why>>}"), "\\end{twenty}" ), collapse = "\n") } )
/scratch/gouwar.j/cran-all/cranData/vitae/R/twentyseconds.R
add_class <- function(x, subclass) { `class<-`(x, union(subclass, class(x))) } compact_list <- function(x) { if(is.list(x)) return(x) list(x[!is.na(x)]) } `%||%` <- function(x, y) { if (is.null(x)) y else x } `%empty%` <- function(x, y) { if (length(x) == 0) y else x } `%missing%` <- function(x, y) { if (rlang::quo_is_missing(x)) y else x } protect_tex_input <- function(x, ...) { if (is.character(x) || is.factor(x)) { x <- gsub("'([^ ']*)'", "`\\1'", x, useBytes = TRUE) x <- gsub("\"([^\"]*)\"", "``\\1''", x, useBytes = TRUE) x <- gsub("\\", "\\textbackslash ", x, fixed = TRUE, useBytes = TRUE ) x <- gsub("([{}&$#_^%])", "\\\\\\1", x, useBytes = TRUE) x } else { x } } # From rmarkdown:::partition_yaml_front_matter partition_yaml_front_matter <- function (input_lines) { validate_front_matter <- function(delimiters) { if (length(delimiters) >= 2 && (delimiters[2] - delimiters[1] > 1) && grepl("^---\\s*$", input_lines[delimiters[1]])) { if (delimiters[1] == 1) { TRUE } else all(grepl("^\\s*(<!-- rnb-\\w*-(begin|end) -->)?\\s*$", input_lines[1:delimiters[1] - 1])) } else { FALSE } } delimiters <- grep("^(---|\\.\\.\\.)\\s*$", input_lines) if (validate_front_matter(delimiters)) { front_matter <- input_lines[(delimiters[1]):(delimiters[2])] input_body <- c() if (delimiters[1] > 1) input_body <- c(input_body, input_lines[1:delimiters[1] - 1]) if (delimiters[2] < length(input_lines)) input_body <- c(input_body, input_lines[-(1:delimiters[2])]) list(front_matter = front_matter, body = input_body) } else { list(front_matter = NULL, body = input_lines) } } glue_alt <- function(...) { glue::glue(..., .open = "<<", .close = ">>", .envir = parent.frame()) } require_package <- function(pkg){ if(!requireNamespace(pkg, quietly = TRUE)){ stop( sprintf('The `%s` package must be installed to use this functionality. It can be installed with install.packages("%s")', pkg, pkg), call. = FALSE ) } } with_ext <- function(x, ext) { paste(sub("([^.]+)\\.[[:alnum:]]+$", "\\1", x), ext, sep = ".") }
/scratch/gouwar.j/cran-all/cranData/vitae/R/utils.R
#' @keywords internal "_PACKAGE" #' @import rlang #' @import vctrs NULL
/scratch/gouwar.j/cran-all/cranData/vitae/R/vitae-package.R
#' @import glue NULL
/scratch/gouwar.j/cran-all/cranData/vitae/R/vitae.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
/scratch/gouwar.j/cran-all/cranData/vitae/inst/doc/data.R
--- title: "Data sources for vitae" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using vitae with other packages} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` Using data to dynamically build your Résumé or CV makes many powerful integrations possible. By using data to populate entries in the document, it becomes easy to manipulate and select relevant experiences for a particular application. There are many sources of data which can be used to populate a CV with vitae, some commonly sources are summarised in this vignette. The main purpose of sourcing your CV entries from common data sources is to extend the "do not repeat yourself" programming philosophy to maintaining a CV. If you maintain publications on [ORCID](https://orcid.org/) you shouldn't need to repeat these entries in your CV. If a list of talks you've made can be found on your website, avoid repeating the list in multiple locations to ensure that they both contain the same content. This vignette is far from comprehensive, and there are no doubt many other interesting ways to populate your CV with data. If you're using a data source that you think others should know about, consider making a [pull request](https://github.com/mitchelloharawild/vitae/pulls) that adds your method to this vignette. ## Spreadsheets and data sets The simplest source of entries for vitae are maintained dataset(s) of past experiences and achievements. Just like any dataset, these entries can be loaded into the document as a `data.frame` or `tibble` using functions from base R or the [`readr` package](https://readr.tidyverse.org/). ```r readr::read_csv("employment.csv") %>% detailed_entries(???) ``` It is also possible to load in data from excel using the [`readxl` package](https://readxl.tidyverse.org/) or from Google Sheets using the [`googlesheets` package](https://github.com/jennybc/googlesheets). ```r readxl::read_excel("awards.xlsx") %>% brief_entries(???) ``` ## Google scholar Google Scholar does not require authentication to extract publications. Using the [`scholar` package](https://github.com/jkeirstead/scholar), it is easy to extract a user's publications from their Google Scholar ID. To obtain publications for an individual, you would first find your ID which is accessible from your profile URL. For example, Rob Hyndman's ID would be `"vamErfkAAAAJ"` (https://scholar.google.com/citations?user=vamErfkAAAAJ&hl=en). ```r scholar::get_publications("vamErfkAAAAJ") %>% detailed_entries( what = title, when = year, with = author, where = journal, why = cites ) ``` ## Bibliography files The vitae package directly supports loading `*.bib` files using the `bibliography_entries()` function, which formats the entries in a bibliography style. ```r bibliography_entries("publications.bib") ``` It is also possible to display the contents of your bibliography using template specific entries formats. ```r bibliography_entries("publications.bib") %>% detailed_entries(???) ``` ## R packages A list of R packages that you have helped develop can be obtained using the [`pkgsearch` package](https://github.com/r-hub/pkgsearch). ```r pkgsearch::ps("O'Hara-Wild",size = 100) %>% filter(map_lgl(package_data, ~ grepl("Mitchell O'Hara-Wild", .x$Author, fixed = TRUE))) %>% as_tibble() %>% brief_entries( what = title, when = lubridate::year(date), with = description ) ```
/scratch/gouwar.j/cran-all/cranData/vitae/inst/doc/data.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----add-template, eval = FALSE----------------------------------------------- # usethis::use_rmarkdown_template( # template_name = "Curriculum Vitae (My custom format)", # template_dir = "my_template", # template_description = "The custom vitae template made by me!", # template_create_dir = TRUE) ## ----------------------------------------------------------------------------- #' @rdname cv_formats #' @export my_template <- function(...) { template <- system.file("rmarkdown", "templates", "my_template", "resources", "my_template.tex", package="vitae") set_entry_formats(moderncv_cv_entries) copy_supporting_files("my_template") cv_document(..., template = template) }
/scratch/gouwar.j/cran-all/cranData/vitae/inst/doc/extending.R