content
stringlengths
0
14.9M
filename
stringlengths
44
136
test_NoY <- function() { dTrainZ <- data.frame(x=c('a','a','a','a','b','b','b'), z=c(1,2,3,4,5,NA,7)) dTestZ <- data.frame(x=c('a','b','c',NA), z=c(10,20,30,NA)) treatmentsZ = designTreatmentsZ(dTrainZ,colnames(dTrainZ), rareCount=0, verbose=FALSE) dTrainZTreated <- prepare(treatmentsZ,dTrainZ,pruneSig=NULL, check_for_duplicate_frames=FALSE) dTestZTreated <- prepare(treatmentsZ,dTestZ,pruneSig=NULL, check_for_duplicate_frames=FALSE) expect_true(!is.null(dTestZTreated)) invisible(NULL) } test_NoY()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_NoY.R
test_PC <- function() { set.seed(2352) d <- data.frame(x=c(1,1,1,1,2,2,2,2), y=c(0,0,1,0,0,1,1,1), stringsAsFactors = FALSE) splitter <- makekWayCrossValidationGroupedByColumn('x') cfe <- mkCrossFrameNExperiment(d,'x','y', splitFunction = splitter, ncross = 2, verbose = FALSE) expect_true(length(cfe$evalSets)==2) xValCount <- vapply(cfe$evalSets,function(ci) { length(unique(d$x[ci$train]))}, numeric(1)) expect_true(all(xValCount==1)) expect_true('clean' %in% cfe$treatments$scoreFrame$code) invisible(NULL) } test_PC()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_PC.R
test_Parallel <- function() { # # # left-over from when we were using testthat # # seems to kill testthat on stop, possibly https://github.com/hadley/testthat/issues/129 # Sys.setenv("R_TESTS" = "") dir <- system.file("tinytest", package = "vtreat", mustWork = TRUE) load(paste(dir, 'uci.car.data.Rdata', sep = "/")) cl <- NULL if(requireNamespace("parallel", quietly=TRUE)) { cl <- parallel::makeCluster(2) } dYName <- "rating" dYTarget <- 'vgood' pvars <- setdiff(colnames(uci.car.data),dYName) seedVal=946463L set.seed(seedVal) treatmentsCP <- designTreatmentsC(uci.car.data, pvars,dYName,dYTarget,verbose=FALSE, parallelCluster=cl) dTrainCTreatedP <- prepare(treatmentsCP,uci.car.data,pruneSig=c(), parallelCluster=cl, check_for_duplicate_frames=FALSE) if(!is.null(cl)) { parallel::stopCluster(cl) cl <- NULL } set.seed(seedVal) treatmentsC <- designTreatmentsC(uci.car.data, pvars,dYName,dYTarget,verbose=FALSE) dTrainCTreated <- prepare(treatmentsC,uci.car.data,pruneSig=c(), check_for_duplicate_frames=FALSE) expect_true(nrow(dTrainCTreated)==nrow(dTrainCTreatedP)) expect_true(length(colnames(dTrainCTreated))==length(colnames(dTrainCTreatedP))) expect_true(all(colnames(dTrainCTreated)==colnames(dTrainCTreatedP))) for(v in setdiff(colnames(dTrainCTreated),dYName)) { ev <- max(abs(dTrainCTreated[[v]]-dTrainCTreatedP[[v]])) expect_true(ev<1.0e-3) } invisible(NULL) } test_Parallel()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_Parallel.R
test_Scale <- function() { library('vtreat') dTrainC <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6), y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE, catScaling=TRUE, verbose=FALSE) dTrainCTreatedUnscaled <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=FALSE, check_for_duplicate_frames=FALSE) dTrainCTreatedScaled <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) slopeFrame <- data.frame(varName=treatmentsC$scoreFrame$varName, stringsAsFactors = FALSE) slopeFrame$mean <- vapply(dTrainCTreatedScaled[,slopeFrame$varName,drop=FALSE],mean, numeric(1)) slopeFrame$slope <- vapply(slopeFrame$varName, function(c) { glm(paste('y',c,sep='~'),family=binomial, data=dTrainCTreatedScaled)$coefficients[[2]] }, numeric(1)) slopeFrame$sig <- vapply(slopeFrame$varName, function(c) { treatmentsC$scoreFrame[treatmentsC$scoreFrame$varName==c,'sig'] }, numeric(1)) slopeFrame$badSlope <- ifelse(is.na(slopeFrame$slope),TRUE,abs(slopeFrame$slope-1)>1.e-8) expect_true(!any(is.na(dTrainCTreatedUnscaled))) expect_true(!any(is.na(dTrainCTreatedScaled))) expect_true(!any(is.na(slopeFrame$mean))) expect_true(!any(is.infinite(slopeFrame$mean))) expect_true(max(abs(slopeFrame$mean))<=1.0e-8) expect_true(!any(slopeFrame$badSlope & (slopeFrame$sig<1))) invisible(NULL) } test_Scale()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_Scale.R
test_Sig <- function() { d <- data.frame(x=c(1,3,2,1), y=c(1,2,2,0), yC=c(TRUE,TRUE,FALSE,FALSE)) # summary(lm(y~x,data=d)) # sL <- vtreat:::linScore('x',d$x,d$y,NULL) # expect_true(abs(sL$sig-0.1818)<=1.0e-3) tL <- designTreatmentsN(d,'x','y',verbose=FALSE) expect_true(abs(tL$scoreFrame[1,'sig']-0.1818)<=1.0e-3) # model <- glm(yC~x,data=d,family=binomial) # delta_deviance <- model$null.deviance - model$deviance # delta_df <- model$df.null - model$df.residual # pRsq <- 1.0 - model$deviance/model$null.deviance # sig <- stats::pchisq(delta_deviance, delta_df,lower.tail=FALSE) # sC <- vtreat:::catScore('x',d$x,d$yC,TRUE,NULL) # expect_true(abs(sC$sig-0.5412708)<=1.0e-3) tC <- designTreatmentsC(d,'x','yC',TRUE,verbose=FALSE) expect_true(abs(tC$scoreFrame[1,'sig']-0.5412708)<=1.0e-3) invisible(NULL) } test_Sig()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_Sig.R
test_Stability <- function() { set.seed(235235) expandTab <- function(tab) { # expand out into data d <- c() for(vLevelI in seq_len(nrow(tab))) { for(yLevelI in seq_len(ncol(tab))) { count <- tab[vLevelI,yLevelI] if(count>0) { di <- data.frame(x=character(count), y=logical(count)) di$x <- rownames(tab)[vLevelI] di$y <- as.logical(colnames(tab)[yLevelI]) d <- rbind(d,di) } } } d } tab <- matrix( data = c( 202,89,913,419,498,214,8,0,3,0, 1260,651,70,31,24,4,225,107,1900, 921,1810,853,10,1,778,282,104,58 ), byrow = TRUE,ncol = 2 ) rownames(tab) <- c( 'Beige', 'Blau', 'Braun', 'Gelb', 'Gold', 'Grau', 'Grun', 'Orange', 'Rot', 'Schwarz', 'Silber', 'Violett', 'Weiss', 'unknown' ) colnames(tab) <- c(FALSE,TRUE) d <- expandTab(tab) d$x[d$x!='Weiss'] <- 'unknown' nRun <- 5 set.seed(235235) # vtreat run: max arount 0.5 min ~ 5e-5 csig <- numeric(nRun) for(i in seq_len(nRun)) { tP <- vtreat::designTreatmentsC(d,'x','y',TRUE,rareSig=1,verbose=FALSE) # looking at instability in csig of Weiss level csig[[i]] <- tP$scoreFrame$sig[tP$scoreFrame$varName=='x_lev_x_Weiss'] } expect_true((max(csig)-min(csig))<1.0e-5) invisible(NULL) } test_Stability()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_Stability.R
test_UniqValue <- function() { dTrainN <- data.frame(x=c('a','a','a','a','a','a','b'), z=c(0,0,0,0,0,0,1), y=c(1,0,0,0,0,0,0)) dTestN <- data.frame(x=c('a','b','c',NA), z=c(10,20,30,NA)) treatmentsN = designTreatmentsN(dTrainN,colnames(dTrainN),'y', rareCount=0,rareSig=1, verbose=FALSE) dTrainNTreated <- prepare(treatmentsN,dTrainN,pruneSig=1, check_for_duplicate_frames=FALSE) dTestNTreated <- prepare(treatmentsN,dTestN,pruneSig=1, check_for_duplicate_frames=FALSE) dTrainC <- data.frame(x=c('a','a','a','a','a','a','b'), z=c(0,0,0,0,0,0,1), y=c(TRUE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE)) dTestC <- data.frame(x=c('a','b','c',NA), z=c(10,20,30,NA)) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE, rareCount=0,rareSig=1, verbose=FALSE) dTrainCTreated <- prepare(treatmentsC,dTrainC, pruneSig=1,doCollar=FALSE, check_for_duplicate_frames=FALSE) dTestCTreated <- prepare(treatmentsC,dTestC, pruneSig=1,doCollar=FALSE, check_for_duplicate_frames=FALSE) dTrainZ <- data.frame(x=c('a','a','a','a','a','a','b'), z=c(0,0,0,0,0,0,1)) dTestZ <- data.frame(x=c('a','b','c',NA), z=c(10,20,30,NA)) treatmentsZ = designTreatmentsZ(dTrainN,colnames(dTrainN), rareCount=0, verbose=FALSE) dTrainZTreated <- prepare(treatmentsN,dTrainN,pruneSig=1, check_for_duplicate_frames=FALSE) dTestZTreated <- prepare(treatmentsN,dTestN,pruneSig=1, check_for_duplicate_frames=FALSE) expect_true(!is.null(dTestZTreated)) invisible(NULL) } test_UniqValue()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_UniqValue.R
test_W1 <- function() { # build data set.seed(235) zip <- paste('z',1:100) N = 1000 d <- data.frame(zip=sample(zip,N,replace=TRUE), # no signal zip2=sample(zip,N,replace=TRUE), # has signal y=runif(N)) del <- runif(length(zip)) names(del) <- zip d$y <- d$y + del[d$zip2] d$yc <- d$y>=mean(d$y) # show good variable control on numeric/regression tN <- designTreatmentsN(d,c('zip','zip2'),'y', rareCount=2,rareSig=0.5, verbose=FALSE) dTN <- prepare(tN,d,pruneSig=0.01, check_for_duplicate_frames=FALSE) expect_true(!('zip_catN' %in% colnames(dTN))) expect_true('zip2_catN' %in% colnames(dTN)) # show good variable control on categorization tC <- designTreatmentsC(d,c('zip','zip2'),'yc',TRUE, rareCount=2,rareSig=0.5, verbose=FALSE) dTC <- prepare(tC,d,pruneSig=0.01, check_for_duplicate_frames=FALSE) expect_true(!('zip_catB' %in% colnames(dTC))) expect_true('zip2_catB' %in% colnames(dTC)) tC# show naive method has high correlations dTN <- prepare(tN,d,pruneSig=c(), check_for_duplicate_frames=FALSE) expect_true(cor(dTN$zip_catN,dTN$y)>0.1) dTC <- prepare(tC,d,pruneSig=c(), check_for_duplicate_frames=FALSE) expect_true(cor(as.numeric(dTC$yc),dTC$zip_catB)>0.1) # show cross table helps lower this cC <- mkCrossFrameCExperiment(d,c('zip','zip2'),'yc',TRUE, rareCount=2,rareSig=0.5, verbose = FALSE) expect_true(cor(as.numeric(cC$crossFrame$yc),cC$crossFrame$zip_catB)<0.1) expect_true(cor(as.numeric(cC$crossFrame$yc),cC$crossFrame$zip2_catB)>0.1) # show cross table helps lower this cN <- mkCrossFrameNExperiment(d,c('zip','zip2'),'y', rareCount=2,rareSig=0.5, verbose = FALSE) expect_true(cor(cN$crossFrame$y,cN$crossFrame$zip_catN)<0.1) expect_true(cor(cN$crossFrame$y,cN$crossFrame$zip2_catN)>0.1) invisible(NULL) } test_W1()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_W1.R
test_WeirdTypes <- function() { suppressWarnings({ d <- data.frame(xInteger=1:4, xNumeric=0, xCharacter='a', xFactor=as.factor('b'), xPOSIXct=Sys.time(), xRaw=raw(4), xLogical=TRUE, xArrayNull=as.array(list(NULL,NULL,NULL,NULL)), stringsAsFactors=FALSE) d$xPOSIXlt <- as.POSIXlt(c(Sys.time(),Sys.time()+100,Sys.time()+200,Sys.time()+300)) d$xArray <- as.array(c(17,18,19,20)) d$xMatrix1 <- matrix(data=c(88,89,90,91),nrow=4,ncol=1) d$xMatrix2 <- matrix(data=c(1,2,3,4,5,6,7,8),nrow=4,ncol=2) d$xMatrixC1 <- matrix(data=c('88','89','90','91'),nrow=4,ncol=1) d$xMatrixC2 <- matrix(data=c('1','2','3','4','5','6','7','8'),nrow=4,ncol=2) d$xListH <- list(10,20,'thirty','forty') d$xListR <- list(list(),list('a'),list('a','b'),list('a','b','c')) d$xData.Frame <- data.frame(xData.FrameA=6:9,xData.FrameB=11:14) d$xListR2 <- I(list(NULL,'a',c('a','b'),1)) d$xFunctions=I(c(function(){},function(){},function(){},function(){})) d$y <- c(1,1,0,0) yVar <- 'y' yTarget <- 1 xVars <- setdiff(colnames(d),yVar) treatmentsC <- designTreatmentsC(d,xVars,yVar,yTarget,verbose=FALSE) treatmentsN <- designTreatmentsN(d,xVars,yVar,verbose=FALSE) expect_true(!is.null(treatmentsC)) expect_true(!is.null(treatmentsN)) }) invisible(NULL) } test_WeirdTypes()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_WeirdTypes.R
test_ZW <- function() { # categorical example set.seed(235256) dTrainC <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)) dTrainC <- rbind(dTrainC,dTrainC) trainCWeights <- numeric(nrow(dTrainC)) trainCWeights[1:(length(trainCWeights)/2)] <- 1 dTestC <- data.frame(x=c('a','b','c',NA),z=c(10,20,30,NA)) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE, catScaling = TRUE, weights=trainCWeights,verbose=FALSE) dTrainCTreated <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) varsC <- setdiff(colnames(dTrainCTreated),'y') # all input variables should be mean 0 sapply(dTrainCTreated[,varsC,drop=FALSE],mean) # all slopes should be 1 sapply(varsC,function(c) { glm(paste('y',c,sep='~'),family='binomial', data=dTrainCTreated)$coefficients[[2]]}) dTestCTreated <- prepare(treatmentsC,dTestC,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) # categorical example indicator mode set.seed(235256) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE, catScaling = FALSE, weights=trainCWeights,verbose=FALSE) dTrainCTreated <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) varsC <- setdiff(colnames(dTrainCTreated),'y') # all input variables should be mean 0 sapply(dTrainCTreated[,varsC,drop=FALSE],mean) # all slopes should be 1 sapply(varsC,function(c) { lm(paste('y',c,sep='~'), data=dTrainCTreated)$coefficients[[2]]}) dTestCTreated <- prepare(treatmentsC,dTestC,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) # numeric example set.seed(235256) dTrainN <- data.frame(x=c('a','a','a','a','b','b',NA), z=c(1,2,3,4,5,NA,7),y=c(0,0,0,1,0,1,1)) dTrainN <- rbind(dTrainN,dTrainN) trainNWeights <- numeric(nrow(dTrainN)) trainNWeights[1:(length(trainNWeights)/2)] <- 1 dTestN <- data.frame(x=c('a','b','c',NA),z=c(10,20,30,NA)) treatmentsN = designTreatmentsN(dTrainN,colnames(dTrainN),'y', weights=trainNWeights, verbose=FALSE) dTrainNTreated <- prepare(treatmentsN,dTrainN,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) varsN <- setdiff(colnames(dTrainNTreated),'y') # all input variables should be mean 0 sapply(dTrainNTreated[,varsN,drop=FALSE],mean) # all slopes should be 1 sapply(varsN,function(c) { lm(paste('y',c,sep='~'), data=dTrainNTreated)$coefficients[[2]]}) dTestNTreated <- prepare(treatmentsN,dTestN,pruneSig=c(),scale=TRUE, check_for_duplicate_frames=FALSE) expect_true(!is.null(dTestNTreated)) invisible(NULL) } test_ZW()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_ZW.R
test_bind_frames <- function() { d <- data.frame(x = 1, y = 's', stringsAsFactors = FALSE) frame_list = list(d, d) # fn way r <- vtreat:::.rbindListOfFrames(frame_list) expect_true(is.data.frame(r)) expect <- data.frame(x = c(1, 1), y = c('s', 's'), stringsAsFactors = FALSE) expect_true(isTRUE(all.equal(r, expect))) expect_true(is.character(r$y)) expect_true(!is.factor(r$y)) # base R way r <- do.call(base::rbind, c(frame_list, list('stringsAsFactors' = FALSE))) expect_true(is.data.frame(r)) expect <- data.frame(x = c(1, 1), y = c('s', 's'), stringsAsFactors = FALSE) expect_true(isTRUE(all.equal(r, expect))) expect_true(is.character(r$y)) expect_true(!is.factor(r$y)) # data.table way if(requireNamespace("data.table", quietly = TRUE)) { r <- as.data.frame(data.table::rbindlist(frame_list), stringsAsFactor=FALSE) expect_true(is.data.frame(r)) expect <- data.frame(x = c(1, 1), y = c('s', 's'), stringsAsFactors = FALSE) expect_true(isTRUE(all.equal(r, expect))) expect_true(is.character(r$y)) expect_true(!is.factor(r$y)) } invisible(NULL) } test_bind_frames()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_bind_frames.R
test_col_dups <- function() { d <- data.frame(x = c(1:8, NA, NA), y = c(1,1,1,1,1,0,0,0,0,0)) cross_frame_experiment <- vtreat::mkCrossFrameCExperiment( d, varlist = "x", outcomename = "y", outcometarget = 1, verbose = FALSE, scale = TRUE) dTrainAll_treated <- cross_frame_experiment$crossFrame expect_true(length(colnames(dTrainAll_treated))==length(unique(colnames(dTrainAll_treated)))) expect_true(!isTRUE(any(is.na(dTrainAll_treated$x)))) treatment_plan <- cross_frame_experiment$treatments dTest_treated <- prepare(treatment_plan, d, scale = TRUE, check_for_duplicate_frames=FALSE) dTest_treated expect_true(length(colnames(dTest_treated))==length(unique(colnames(dTest_treated)))) expect_true(!isTRUE(any(is.na(dTest_treated$x)))) invisible(NULL) } test_col_dups()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_col_dups.R
test_consts_rejected <- function() { cb <- vtreat:::.mkCatBayes(origVarName = "x", vcolin = c(1,1,1,1), rescol= c(1,1,0,0), resTarget = 1, smFactor = 0, levRestriction = NULL, weights = c(1,1,1,1), catScaling = FALSE) expect_true(is.null(cb)) cn <- vtreat:::.mkCatNum(origVarName = "x", vcolin = c(1,1,1,1), rescol= c(1,1,0,0), smFactor = 0, levRestriction = NULL, weights = c(1,1,1,1)) expect_true(is.null(cn)) invisible(NULL) } test_consts_rejected()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_consts_rejected.R
test_custom_coder <- function() { set.seed(23525) x_codes <- rnorm(5) names(x_codes) <- letters[1:length(x_codes)] n_rows <- 1000 d <- data.frame(x1 = sample(names(x_codes), n_rows, replace = TRUE), x2 = rnorm(n_rows), stringsAsFactors = FALSE) d$yN <- x_codes[d$x1] + d$x2 - rnorm(nrow(d)) d$yC <- ifelse(d$yN>0, "Y", "N") lmCoder <- function(v, vcol, y, weights) { d <- data.frame(x = vcol, y = y, stringsAsFactors = FALSE) m = stats::lm(y ~ x, data=d, weights=weights) predict(m, newdata=d) } glmCoder <- function(v, vcol, y, weights) { d <- data.frame(x = vcol, y = y, stringsAsFactors = FALSE) m = stats::glm(y ~ x, data=d, weights=weights, family=binomial) predict(m, newdata=d, type='link') } customCoders = list('c.logit.center' = glmCoder, 'c.lm.center' = lmCoder, 'n.lm.center' = lmCoder, 'n.lm.num.center' = lmCoder) treatplanC = designTreatmentsC(d, varlist = c("x1", "x2"), outcomename = 'yC', outcometarget= 'Y', customCoders = customCoders, verbose=FALSE) expect_true("x1_logit" %in% treatplanC$scoreFrame$varName) expect_true("x1_lm" %in% treatplanC$scoreFrame$varName) treatplanN = designTreatmentsN(d, varlist = c("x1", "x2"), outcomename = 'yN', customCoders = customCoders, verbose=FALSE) expect_true("x1_lm" %in% treatplanN$scoreFrame$varName) expect_true("x2_lm" %in% treatplanN$scoreFrame$varName) invisible(NULL) } test_custom_coder()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_custom_coder.R
test_ft_classification <- function() { # From: https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification_FT.md make_data <- function(nrows) { d <- data.frame(x = 5*rnorm(nrows)) d['y'] = sin(d['x']) + 0.1*rnorm(n = nrows) d[4:10, 'x'] = NA # introduce NAs d['xc'] = paste0('level_', 5*round(d$y/5, 1)) d['x2'] = rnorm(n = nrows) d[d['xc']=='level_-1', 'xc'] = NA # introduce a NA level d['yc'] = d[['y']]>0.5 d['qq'] = d[['y']] return(d) } d = make_data(50) transform_design = vtreat::BinomialOutcomeTreatment( var_list = setdiff(colnames(d), c('y', 'yc', 'qq')), # columns to transform outcome_name = 'yc', # outcome variable cols_to_copy = c('y', 'yc'), # make sure this gets copied outcome_target = TRUE # outcome of interest ) # learn transform from data d_prepared <- transform_design$fit_transform(d) expect_true('yc' %in% colnames(d_prepared)) expect_true('y' %in% colnames(d_prepared)) expect_true(!('qq' %in% colnames(d_prepared))) # get statistics on the variables score_frame <- transform_design$score_frame() expect_true(!('yc' %in% score_frame$origName)) expect_true(!('y' %in% score_frame$origName)) expect_true(!('qq' %in% score_frame$origName)) # check simple xform saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(d), warning = function(...) { saw_warning <<- TRUE }) expect_true(saw_warning) dZ <- d dZ['zz'] <- 0 saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(dZ), warning = function(...) { saw_warning <<- TRUE }) expect_true(!saw_warning) expect_true('yc' %in% colnames(d2)) expect_true('y' %in% colnames(d2)) d2b <- dZ %.>% transform_design expect_true(isTRUE(all.equal(d2, d2b))) invisible(NULL) } test_ft_classification() test_ft_regression <- function() { # From: https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification_FT.md make_data <- function(nrows) { d <- data.frame(x = 5*rnorm(nrows)) d['y'] = sin(d['x']) + 0.1*rnorm(n = nrows) d[4:10, 'x'] = NA # introduce NAs d['xc'] = paste0('level_', 5*round(d$y/5, 1)) d['x2'] = rnorm(n = nrows) d[d['xc']=='level_-1', 'xc'] = NA # introduce a NA level d['yc'] = d[['y']]>0.5 d['qq'] = d[['y']] return(d) } d = make_data(50) transform_design = vtreat::NumericOutcomeTreatment( var_list = setdiff(colnames(d), c('y', 'yc', 'qq')), # columns to transform outcome_name = 'y', # outcome variable cols_to_copy = c('y', 'yc') # make sure this gets copied ) # learn transform from data d_prepared <- transform_design$fit_transform(d) expect_true('yc' %in% colnames(d_prepared)) expect_true('y' %in% colnames(d_prepared)) expect_true(!('qq' %in% colnames(d_prepared))) # get statistics on the variables score_frame <- transform_design$score_frame() expect_true(!('yc' %in% score_frame$origName)) expect_true(!('y' %in% score_frame$origName)) expect_true(!('qq' %in% score_frame$origName)) # check simple xform saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(d), warning = function(...) { saw_warning <<- TRUE }) expect_true(saw_warning) dZ <- d dZ['zz'] <- 0 saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(dZ), warning = function(...) { saw_warning <<- TRUE }) expect_true(!saw_warning) expect_true('yc' %in% colnames(d2)) expect_true('y' %in% colnames(d2)) d2b <- dZ %.>% transform_design expect_true(isTRUE(all.equal(d2, d2b))) invisible(NULL) } test_ft_regression() test_ft_unsupervised <- function() { # From: https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification_FT.md make_data <- function(nrows) { d <- data.frame(x = 5*rnorm(nrows)) d['y'] = sin(d['x']) + 0.1*rnorm(n = nrows) d[4:10, 'x'] = NA # introduce NAs d['xc'] = paste0('level_', 5*round(d$y/5, 1)) d['x2'] = rnorm(n = nrows) d[d['xc']=='level_-1', 'xc'] = NA # introduce a NA level d['yc'] = d[['y']]>0.5 d['qq'] = d[['y']] return(d) } d = make_data(50) transform_design = vtreat::UnsupervisedTreatment( var_list = setdiff(colnames(d), c('y', 'yc', 'qq')), # columns to transform cols_to_copy = c('y', 'yc') # make sure this gets copied ) # learn transform from data d_prepared <- transform_design$fit_transform(d) expect_true('yc' %in% colnames(d_prepared)) expect_true('y' %in% colnames(d_prepared)) expect_true(!('qq' %in% colnames(d_prepared))) # get statistics on the variables score_frame <- transform_design$score_frame() expect_true(!('yc' %in% score_frame$origName)) expect_true(!('y' %in% score_frame$origName)) expect_true(!('qq' %in% score_frame$origName)) # check simple xform saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(d), warning = function(...) { saw_warning <<- TRUE }) expect_true(!saw_warning) expect_true('yc' %in% colnames(d2)) expect_true('y' %in% colnames(d2)) d2b <- d %.>% transform_design expect_true(isTRUE(all.equal(d2, d2b))) invisible(NULL) } test_ft_unsupervised() test_ft_multinomial <- function() { # From: https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification_FT.md make_data <- function(nrows) { d <- data.frame(x = 5*rnorm(nrows)) d['y'] = sin(d['x']) + 0.1*rnorm(n = nrows) d[4:10, 'x'] = NA # introduce NAs d['xc'] = paste0('level_', 5*round(d$y/5, 1)) d['x2'] = rnorm(n = nrows) d[d['xc']=='level_-1', 'xc'] = NA # introduce a NA level d['yc'] = d[['y']]>0.5 d['qq'] = d[['y']] return(d) } d = make_data(50) transform_design = vtreat::MultinomialOutcomeTreatment( var_list = setdiff(colnames(d), c('y', 'yc', 'qq')), # columns to transform outcome_name = 'yc', # outcome variable cols_to_copy = c('y', 'yc') # make sure this gets copied ) # learn transform from data d_prepared <- transform_design$fit_transform(d) expect_true('yc' %in% colnames(d_prepared)) expect_true('y' %in% colnames(d_prepared)) expect_true(!('qq' %in% colnames(d_prepared))) # get statistics on the variables score_frame <- transform_design$score_frame() expect_true(!('yc' %in% score_frame$origName)) expect_true(!('y' %in% score_frame$origName)) expect_true(!('qq' %in% score_frame$origName)) # check simple xform saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(d), warning = function(...) { saw_warning <<- TRUE }) expect_true(saw_warning) dZ <- d dZ['zz'] <- 0 saw_warning <- FALSE tryCatch( d2 <- transform_design$transform(dZ), warning = function(...) { saw_warning <<- TRUE }) expect_true(!saw_warning) expect_true('yc' %in% colnames(d2)) expect_true('y' %in% colnames(d2)) d2b <- dZ %.>% transform_design expect_true(isTRUE(all.equal(d2, d2b))) invisible(NULL) } test_ft_multinomial() test_Rapi_classification <- function() { # From: https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification_FT.md make_data <- function(nrows) { d <- data.frame(x = 5*rnorm(nrows)) d['y'] = sin(d['x']) + 0.1*rnorm(n = nrows) d[4:10, 'x'] = NA # introduce NAs d['xc'] = paste0('level_', 5*round(d$y/5, 1)) d['x2'] = rnorm(n = nrows) d[d['xc']=='level_-1', 'xc'] = NA # introduce a NA level d['yc'] = d[['y']]>0.5 d['qq'] = d[['y']] return(d) } d = make_data(50) transform_design = vtreat::mkCrossFrameCExperiment( dframe = d, # data to learn transform from varlist = setdiff(colnames(d), c('y', 'yc', 'qq')), # columns to transform outcomename = 'yc', # outcome variable outcometarget = TRUE, # outcome of interest verbose = FALSE ) # learn transform from data d_prepared <- transform_design$crossFrame expect_true('yc' %in% colnames(d_prepared)) expect_true(!('y' %in% colnames(d_prepared))) expect_true(!('qq' %in% colnames(d_prepared))) # get statistics on the variables score_frame <- transform_design$treatments$scoreFrame expect_true(!('yc' %in% score_frame$origName)) expect_true(!('y' %in% score_frame$origName)) expect_true(!('qq' %in% score_frame$origName)) # check simple xform saw_warning <- FALSE tryCatch( d2 <- prepare(transform_design$treatments, d), warning = function(...) { saw_warning <<- TRUE }) expect_true(saw_warning) dZ <- d dZ['zz'] <- 0 saw_warning <- FALSE tryCatch( d2 <- prepare(transform_design$treatments, dZ), warning = function(...) { saw_warning <<- TRUE }) expect_true(!saw_warning) expect_true('yc' %in% colnames(d2)) expect_true(!('y' %in% colnames(d2))) d2b <- dZ %.>% transform_design$treatments expect_true(isTRUE(all.equal(d2, d2b))) invisible(NULL) } test_Rapi_classification()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_ft.R
test_imputation_control <- function() { d = data.frame( "x" = c(0, 1, 1000, NA), "w" = c(3, 6, NA, 100), "y" = c(0, 0, 1, 1) ) # NULL for global_val or map means "use default" check_unsupervised = function(d, global_val, map) { newparams = unsupervised_parameters(list(missingness_imputation=global_val)) transform = UnsupervisedTreatment( var_list = c('x','w'), cols_to_copy = 'y', params = newparams, imputation_map = map ) # use the fit().prepare() path d_treated = fit(transform, d) %.>% prepare(., d) d_treated } check_classification = function(d, global_val, map, useFT=TRUE) { newparams = classification_parameters( list( missingness_imputation=global_val, check_for_duplicate_frames = FALSE # shut the warning up ) ) transform = BinomialOutcomeTreatment( var_list = c('x','w'), outcome_name = 'y', outcome_target = 1, params = newparams, imputation_map = map ) if(useFT) { unpack[treatments = treatments] <- fit_prepare(transform, d) d_treated = prepare(treatments,d) } else { # use the fit().prepare() path d_treated = fit(transform, d) %.>% prepare(., d) } d_treated } check_regression = function(d, global_val, map, useFT=TRUE) { newparams = regression_parameters( list( missingness_imputation=global_val, check_for_duplicate_frames = FALSE # shut the warning up ) ) transform = NumericOutcomeTreatment( var_list = c('x','w'), outcome_name = 'y', params = newparams, imputation_map = map ) if(useFT) { unpack[treatments = treatments] <- fit_prepare(transform, d) d_treated = prepare(treatments,d) } else { # use the fit().prepare() path d_treated = fit(transform, d) %.>% prepare(., d) } d_treated } equal_df = function(a, b, tolerance = 0.1) { isTRUE(all.equal(a, b, tolerance = tolerance)) } check_all = function(d, global_val, map, gold_standard=NULL) { # unsupervised is the gold standard c0 = check_unsupervised(d, global_val, map) if(!is.null(gold_standard)) { expect_true(equal_df(c0, gold_standard)) } else { gold_standard = c0 } # classification c1 = check_classification(d, global_val, map) expect_true(equal_df(c1, gold_standard)) c2 = check_classification(d, global_val, map, useFT=FALSE) expect_true(equal_df(c2, gold_standard)) # regression r1 = check_regression(d, global_val, map) expect_true(equal_df(r1, gold_standard)) r2 = check_regression(d, global_val, map, useFT=FALSE) expect_true(equal_df(r2, gold_standard)) invisible(gold_standard) } global_imp = NULL imp_map = NULL gs <- wrapr::build_frame( "x" , "x_isBAD", "w" , "w_isBAD", "y" | 0 , 0 , 3 , 0 , 0 | 1 , 0 , 6 , 0 , 0 | 1000 , 0 , 36.33, 1 , 1 | 333.7, 1 , 100 , 0 , 1 ) check_all(d, global_imp, imp_map, gold_standard = gs) median2 <- function(x, wts) { median(x) } global_imp = median2 imp_map = NULL check_all(d, global_imp, imp_map) global_imp = -1 imp_map = NULL check_all(d, global_imp, imp_map) max2 <- function(x, wts) { max(x) } global_imp = NULL imp_map = list( x = max2, w = 0 ) # cat(draw_frame(gs)) gs <- wrapr::build_frame( "x" , "x_isBAD", "w", "w_isBAD", "y" | 0 , 0 , 3 , 0 , 0 | 1 , 0 , 6 , 0 , 0 | 1000, 0 , 0 , 1 , 1 | 1000, 1 , 100, 0 , 1 ) gs = check_all(d, global_imp, imp_map, gold_standard = gs) global_imp = -1 imp_map = list( x = max2 ) check_all(d, global_imp, imp_map) global_imp = NULL imp_map = list( x = max2 ) check_all(d, global_imp, imp_map) invisible(NULL) } test_imputation_control()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_imputation_control.R
test_level_clash <- function() { # confirm levels are being encoded correctly (even after name collision) d <- data.frame( time = c(rep(">= 37 weeks", 3), rep("< 37 weeks", 5)), y = c(rep(1,5), rep(0, 3)), stringsAsFactors = FALSE ) tp <- designTreatmentsN(d, "time", "y", verbose = FALSE) d_treated <- prepare(tp, d, check_for_duplicate_frames = FALSE) d_treated$time <- d$time # print(d_treated) # unclass(tp$treatments[[1]]) expect_true("time_lev_x_lt_37_weeks" %in% colnames(d_treated)) expect_true("time_lev_x_gt_eq_37_weeks" %in% colnames(d_treated)) expect_true(isTRUE(all.equal(d_treated$time_lev_x_lt_37_weeks, 1 - d_treated$time_lev_x_gt_eq_37_weeks))) expect_true(isTRUE(all.equal(d_treated$time_lev_x_lt_37_weeks == 1, d_treated$time == "< 37 weeks"))) # force a collision by using fact . and _ map together # (and are problems at the start of a name). d <- data.frame( time = c(rep(".37 weeks", 3), rep("_37 weeks", 5)), y = c(rep(1,5), rep(0, 3)), stringsAsFactors = FALSE ) tp <- designTreatmentsN(d, "time", "y", verbose = FALSE) d_treated <- prepare(tp, d, check_for_duplicate_frames = FALSE) d_treated$time <- d$time # print(d_treated) # unclass(tp$treatments[[1]]) expect_true("time_lev_x_37_weeks" %in% colnames(d_treated)) expect_true("time_lev_x_37_weeks_1" %in% colnames(d_treated)) expect_true(isTRUE(all.equal(d_treated$time_lev_x_37_weeks, 1 - d_treated$time_lev_x_37_weeks_1))) is_diag_2 <- function(t) { isTRUE(all.equal(dim(t), c(2, 2))) && ((t[1,1]==0) && (t[2,2]==0)) || ((t[1,2]==0) && (t[2,1]==0)) } expect_true(is_diag_2(table(d_treated$time_lev_x_37_weeks, d$time))) expect_true(is_diag_2(table(d_treated$time_lev_x_37_weeks_1, d$time))) invisible(NULL) } test_level_clash()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_level_clash.R
test_multiclass <- function() { # create example data set.seed(326346) sym_bonuses <- rnorm(3) names(sym_bonuses) <- c("a", "b", "c") sym_bonuses3 <- rnorm(3) names(sym_bonuses3) <- as.character(seq_len(length(sym_bonuses3))) n_row <- 1000 d <- data.frame(x1 = rnorm(n_row), x2 = sample(names(sym_bonuses), n_row, replace = TRUE), x3 = sample(names(sym_bonuses3), n_row, replace = TRUE), y = "NoInfo", stringsAsFactors = FALSE) d$y[sym_bonuses[d$x2] > pmax(d$x1, sym_bonuses3[d$x3], runif(n_row))] <- "Large1" d$y[sym_bonuses3[d$x3] > pmax(sym_bonuses[d$x2], d$x1, runif(n_row))] <- "Large2" # define problem vars <- c("x1", "x2", "x3") y_name <- "y" y_levels <- sort(unique(d[[y_name]])) # build the multi-class cross frame and treatments cfe_m <- mkCrossFrameMExperiment(d, vars, y_name) sf <- cfe_m$score_frame cf <- cfe_m$cross_frame prepped <- prepare(cfe_m$treat_m, d, check_for_duplicate_frames=FALSE) expect_equal(sort(colnames(prepped)), sort(colnames(cf))) expect_equal(character(0), setdiff(sf$varName, colnames(cf))) expect_equal("y", setdiff(colnames(cf), sf$varName)) invisible(NULL) } test_multiclass()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_multiclass.R
test_name_munging <- function() { # Issue 23 https://github.com/WinVector/vtreat/issues/23 d <- wrapr::build_frame( "mis be hav (%)", "Sepal.Width", "Petal.Length", "Petal.Width", "Species" | 5.1 , 3.5 , 1.4 , 0.2 , "setosa" | 4.9 , 3 , NA , 0.2 , "setosa" | 4.7 , 3.2 , 1.3 , 0.2 , "setosa" ) t <- designTreatmentsZ(d, names(d), verbose = FALSE) d2 <- prepare(t, d, check_for_duplicate_frames=FALSE) expect_true(isTRUE(all.equal(make.names(colnames(d2)), colnames(d2)))) ts <- design_missingness_treatment(d) ds <- prepare(ts, d) expect_true(isTRUE(all.equal(make.names(colnames(ds)), colnames(ds)))) invisible(NULL) } test_name_munging()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_name_munging.R
test_rquery <- function() { # see what tests we can run eval_examples <- requireNamespace("rquery", quietly = TRUE) eval_rqdt <- eval_examples && requireNamespace("rqdatatable", quietly = TRUE) eval_db <- eval_examples && requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE) # regular in-memory runs dTrainC <- data.frame(x= c('a', 'a', 'a', 'b' ,NA , 'b'), z= c(1, 2, NA, 4, 5, 6), y= c(FALSE, FALSE, TRUE, FALSE, TRUE, TRUE), stringsAsFactors = FALSE) dTrainC$id <- seq_len(nrow(dTrainC)) treatmentsC <- designTreatmentsC(dTrainC, c("x", "z"), 'y', TRUE, verbose = FALSE) treated_c_1 <- prepare(treatmentsC, dTrainC, check_for_duplicate_frames=FALSE) dTrainR <- data.frame(x= c('a', 'a', 'a', 'b' ,NA , 'b'), z= c(1, 2, NA, 4, 5, 6), y= as.numeric(c(FALSE, FALSE, TRUE, FALSE, TRUE, TRUE)), stringsAsFactors = FALSE) dTrainR$id <- seq_len(nrow(dTrainR)) treatmentsN <- designTreatmentsN(dTrainR, c("x", "z"), 'y', verbose = FALSE) treated_n_1 <- prepare(treatmentsN, dTrainR, check_for_duplicate_frames=FALSE) dTrainZ <- data.frame(x= c('a', 'a', 'a', 'b' ,NA , 'b'), z= c(1, 2, NA, 4, 5, 6), stringsAsFactors = FALSE) dTrainZ$id <- seq_len(nrow(dTrainZ)) treatmentsZ <- designTreatmentsZ(dTrainZ, c("x", "z"), verbose = FALSE) treated_z_1 <- prepare(treatmentsZ, dTrainZ, check_for_duplicate_frames=FALSE) if(eval_examples) { rqplan_c <- as_rquery_plan(list(treatmentsC)) rqplan_n <- as_rquery_plan(list(treatmentsN)) rqplan_z <- as_rquery_plan(list(treatmentsZ)) if(eval_rqdt) { treated_dt_c1 <- vtreat::rqdatatable_prepare(rqplan_c, dTrainC, extracols = "id") treated_dt_c2 <- vtreat::rqdatatable_prepare(rqplan_c, dTrainC, extracols = "id", non_join_mapping = TRUE) treated_dt_r <- vtreat::rqdatatable_prepare(rqplan_n, dTrainR, extracols = "id") treated_dt_z <- vtreat::rqdatatable_prepare(rqplan_z, dTrainZ, extracols = "id") } if(eval_db) { db <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") source_data_c <- rquery::rq_copy_to(db, "dTrainC", dTrainC, overwrite = TRUE, temporary = TRUE) source_data_r <- rquery::rq_copy_to(db, "dTrainR", dTrainR, overwrite = TRUE, temporary = TRUE) source_data_z <- rquery::rq_copy_to(db, "dTrainZ", dTrainZ, overwrite = TRUE, temporary = TRUE) rest_c <- rquery_prepare(db, rqplan_c, source_data_c, "dTreatedC", extracols = "id") resd_c <- DBI::dbReadTable(db, rest_c$table_name) rest_n <- rquery_prepare(db, rqplan_n, source_data_r, "dTreatedN", extracols = "id") resd_n <- DBI::dbReadTable(db, rest_n$table_name) rest_z <- rquery_prepare(db, rqplan_z, source_data_z, "dTreatedZ", extracols = "id") resd_z <- DBI::dbReadTable(db, rest_z$table_name) rquery::rq_remove_table(db, source_data_c$table_name) rquery::rq_remove_table(db, rest_c$table_name) rquery::rq_remove_table(db, source_data_r$table_name) rquery::rq_remove_table(db, rest_n$table_name) rquery::rq_remove_table(db, source_data_z$table_name) rquery::rq_remove_table(db, rest_z$table_name) DBI::dbDisconnect(db) } # TODO: compare frames } invisible(NULL) } test_rquery()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_rquery.R
test_simple_col_replace <- function() { d <- wrapr::build_frame( "x1" , "x2" , "x3", "y" | 1 , "a" , 6 , 10 | NA_real_, "b" , 7 , 20 | 3 , NA_character_, 8 , 30 ) plan1 <- vtreat::design_missingness_treatment(d) r <- vtreat::prepare(plan1, d) expect <- c("x1", "x1_isBAD", "x2", "x3", "y") expect_equal(expect, sort(colnames(r))) invisible(NULL) } test_simple_col_replace()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_simple_col_replace.R
test_simple_missingness <- function() { d <- wrapr::build_frame( "x1", "x2", "x3" | 1 , 4 , "A" | NA , 5 , "B" | 3 , 6 , NA ) plan <- design_missingness_treatment(d) prepare(plan, d) prepare(plan, data.frame(x1=NA, x2=NA, x3="E")) invisible(NULL) } test_simple_missingness()
/scratch/gouwar.j/cran-all/cranData/vtreat/inst/tinytest/test_simple_missingness.R
--- title: "Multi Class vtreat" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Multi Class vtreat} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- [`vtreat`](https://github.com/WinVector/vtreat) can now effectively prepare data for multi-class classification or multinomial modeling. The two functions needed ([`mkCrossFrameMExperiment()`](https://winvector.github.io/vtreat/reference/mkCrossFrameMExperiment.html) and the `S3` method [`prepare.multinomial_plan()`](https://winvector.github.io/vtreat/reference/prepare.multinomial_plan.html)) are now part of `vtreat`. Let's work a specific example: trying to model multi-class `y` as a function of `x1` and `x2`. ```{r libs} library("vtreat") ``` ```{r mkex} # create example data set.seed(326346) sym_bonuses <- rnorm(3) names(sym_bonuses) <- c("a", "b", "c") sym_bonuses3 <- rnorm(3) names(sym_bonuses3) <- as.character(seq_len(length(sym_bonuses3))) n_row <- 1000 d <- data.frame( x1 = rnorm(n_row), x2 = sample(names(sym_bonuses), n_row, replace = TRUE), x3 = sample(names(sym_bonuses3), n_row, replace = TRUE), y = "NoInfo", stringsAsFactors = FALSE) d$y[sym_bonuses[d$x2] > pmax(d$x1, sym_bonuses3[d$x3], runif(n_row))] <- "Large1" d$y[sym_bonuses3[d$x3] > pmax(sym_bonuses[d$x2], d$x1, runif(n_row))] <- "Large2" knitr::kable(head(d)) ``` We define the problem controls and use `mkCrossFrameMExperiment()` to build both a cross-frame and a treatment plan. ```{r tdef} # define problem vars <- c("x1", "x2", "x3") y_name <- "y" # build the multi-class cross frame and treatments cfe_m <- mkCrossFrameMExperiment(d, vars, y_name) ``` The cross-frame is the entity safest for training on (unless you have made separate data split for the treatment design step). It uses cross-validation to reduce nested model bias. Some notes on this issue are available [here](https://winvector.github.io/vtreat/articles/vtreatCrossFrames.html), and [here](https://github.com/WinVector/vtreat/blob/master/extras/vtreat.pdf). ```{r crossframe} # look at the data we would train models on str(cfe_m$cross_frame) ``` `prepare()` can apply the designed treatments to new data. Here we are simulating new data by re-using our design data. ```{r treatment_plan} # pretend original data is new data to be treated # NA out top row to show processing for(vi in vars) { d[[vi]][[1]] <- NA } str(prepare(cfe_m$treat_m, d)) ``` Obvious issues include: computing variable importance, and blow up and co-dependency of produced columns. These we leave for the next modeling step to deal with (this is our philosophy with most issues that involve joint distributions of variables). We also have per-outcome variable importance. ```{r varimp} knitr::kable( cfe_m$score_frame[, c("varName", "rsq", "sig", "outcome_level"), drop = FALSE]) ``` One can relate these per-target and per-treatment performances back to original columns by aggregating. ```{r varagg} tapply(cfe_m$score_frame$rsq, cfe_m$score_frame$origName, max) tapply(cfe_m$score_frame$sig, cfe_m$score_frame$origName, min) ```
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/MultiClassVtreat.Rmd
--- title: "Saving Treatment Plans" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Saving Treatment Plans} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- You can save and load treatment plans. Note: treatments plans are intended to be used with the version of `vtreat` they were constructed with (though we try to make plans forward-compatible). So it is good idea to have procedures to re-build treatment plans. The easiest way to save `vtreat` treatment plans is to use `R`'s built in `saveRDS` function. To save in a file: ```{r savefile} library("vtreat") dTrainC <- data.frame(x=c('a','a','a','b','b',NA,NA), z=c(1,2,3,4,NA,6,NA), y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,TRUE)) treatmentsC <- designTreatmentsC(dTrainC, colnames(dTrainC), 'y', TRUE, verbose= FALSE) fileName = paste0(tempfile(c('vtreatPlan')), '.RDS') saveRDS(treatmentsC,fileName) rm(list=c('treatmentsC')) ``` And then to restore and use. ```{r loadfile} library("vtreat") treatmentsC <- readRDS(fileName) dTestC <- data.frame(x=c('a','b','c',NA),z=c(10,20,30,NA)) dTestCTreated <- prepare(treatmentsC, dTestC, pruneSig= c()) # clean up unlink(fileName) ``` Treatment plans can also be stored as binary blobs in databases. Using ideas from [here](https://jfaganuk.github.io/2015/01/12/storing-r-objects-in-sqlite-tables/) gives us the following through the `DBI` interface. ```{r dbsave} con <- NULL if (requireNamespace('RSQLite', quietly = TRUE) && requireNamespace('DBI', quietly = TRUE)) { library("RSQLite") con <- dbConnect(drv=SQLite(), dbname=":memory:") # create table dbExecute(con, 'create table if not exists treatments (key varchar(200) primary key, treatment blob)') # wrap data df <- data.frame( key='treatmentsC', treatment = I(list(serialize(treatmentsC, NULL)))) # Clear any previous version dbExecute(con, "delete from treatments where key='treatmentsC'") # insert treatmentplan # depreciated # dbGetPreparedQuery(con, # 'insert into treatments (key, treatment) values (:key, :treatment)', # bind.data=df) dbExecute(con, 'insert into treatments (key, treatment) values (:key, :treatment)', params=df) constr <- paste(capture.output(print(con)),collapse='\n') paste('saved to db: ', constr) } rm(list= c('treatmentsC', 'dTestCTreated')) ``` And we can read the treatment back in as follows. ```{r dbload} if(!is.null(con)) { treatmentsList <- lapply( dbGetQuery(con, "select * from treatments where key='treatmentsC'")$treatment, unserialize) treatmentsC <- treatmentsList[[1]] dbDisconnect(con) dTestCTreated <- prepare(treatmentsC, dTestC, pruneSig= c()) print(dTestCTreated) } ```
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/SavingTreamentPlans.Rmd
--- title: "vtreat Variable Importance" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat Variable Importance} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- [`vtreat`](https://github.com/WinVector/vtreat)'s purpose is to produce pure numeric [`R`](https://www.r-project.org) `data.frame`s that are ready for [supervised predictive modeling](https://en.wikipedia.org/wiki/Supervised_learning) (predicting a value from other values). By ready we mean: a purely numeric data frame with no missing values and a reasonable number of columns (missing-values re-encoded with indicators, and high-degree categorical re-encode by effects codes or impact codes). Part of the `vtreat` philosophy is to assume after the `vtreat` variable processing the next step is a sophisticated [supervised machine learning](https://en.wikipedia.org/wiki/Supervised_learning) method. Under this assumption we assume the machine learning methodology (be it regression, tree methods, random forests, boosting, or neural nets) will handle issues of redundant variables, joint distributions of variables, overall regularization, and joint dimension reduction. However, an important exception is: variable screening. In practice we have seen wide data-warehouses with hundreds of columns overwhelm and defeat state of the art machine learning algorithms due to over-fitting. We have some synthetic examples of this ([here](https://win-vector.com/2014/02/01/bad-bayes-an-example-of-why-you-need-hold-out-testing/) and [here](https://win-vector.com/talks-and-presentations/)). The upshot is: even in 2018 you can not treat every column you find in a data warehouse as a variable. You must at least perform some basic screening. To help with this `vtreat` incorporates a per-variable linear significance report. This report shows how useful each variable is taken alone in a linear or generalized linear model (some details can be found [here](https://arxiv.org/abs/1611.09477)). However, this sort of calculation was optimized for speed, not discovery power. `vtreat` now includes a direct variable valuation system that works very well with complex numeric relationships. It is a function called [`vtreat::value_variables_N()`](https://winvector.github.io/vtreat/reference/value_variables_N.html) for numeric or regression problems and [`vtreat::value_variables_C()`](https://winvector.github.io/vtreat/reference/value_variables_C.html) for binomial classification problems. It works by fitting two transformed copies of each numeric variable to the outcome. One transform is a low frequency transform realized as an optimal `k`-segment linear model for a moderate choice of `k`. The other fit is a high-frequency trasnform realized as a `k`-nearest neighbor average for moderate choice of `k`. Some of the methodology is shown [here](https://github.com/WinVector/vtreat/blob/master/extras/SegFitter.md). We recommend using `vtreat::value_variables_*()` as an initial variable screen. Let's demonstrate this using the data from the segment fitter example. In our case the value to be predicted ("`y`") is a noisy copy of `sin(x)`. Let's set up our example data: ```{r} set.seed(1999) d <- data.frame(x = seq(0, 15, by = 0.25)) d$y_ideal <- sin(d$x) d$x_noise <- d$x[sample.int(nrow(d), nrow(d), replace = FALSE)] d$y <- d$y_ideal + 0.5*rnorm(nrow(d)) dim(d) ``` Now a simple linear valuation of the the variables can be produced as follows. ```{r} cfe <- vtreat::mkCrossFrameNExperiment( d, varlist = c("x", "x_noise"), outcomename = "y") sf <- cfe$treatments$scoreFrame knitr::kable(sf[, c("varName", "rsq", "sig")]) ``` Notice the signal carrying variable did not score better (having a larger `r`-squared and a smaller (better) significance value) than the noise variable (that is unrelated to the outcome). This is because the relation between `x` and `y` is not linear. Now let's try `vtreat::value_variables_N()`. ```{r} vf = vtreat::value_variables_N( d, varlist = c("x", "x_noise"), outcomename = "y") knitr::kable(vf[, c("var", "rsq", "sig")]) ``` Now the difference is night and day. The important variable `x` is singled out (scores very well), and the unimportant variable `x_noise` doesn't often score well. Though, as with all significance tests, useless variables can get lucky from time to time- (an issue that can be addressed by using a [Cohen's-`d` style calculation](https://win-vector.com/2017/09/08/remember-p-values-are-not-effect-sizes/)). Our modeling advice is: * Use `vtreat::value_variables_*()` * Pick all variables with `sig <= 1/number_of_variables_being_considered`. The idea is: each "pure noise" (or purely useless) variable has a significance that is distributed uniformly between zero and one. So the expected number of useless variables that make it through the above screening is `number_of_useless_varaibles * P[useless_sig <= 1/number_of_variables_being_considered]`. This equals `number_of_useless_varaibles * 1/number_of_variables_being_considered`. As `number_of_useless_varaibles <= number_of_variables_being_considered` we get this quantity is no more than one. So we expect a constant number of useless variables to sneak through this filter. The hope is: this should not be enough useless variables to overwhelm the next stage supervised machine learning step. Obviously there are situations where variable importance can not be discovered without considering joint distributions. The most famous one being "xor" where the concept to be learned is if an odd or even number of indicator variables are zero or one (each such variable is individual completely uninformative about the outcome until you have all of the variables simultaneously). However, for practical problems you often have that most variables have a higher marginal predictive power taken alone than they have in the final joint model (as other, better, variables consume some of common variables' predictive power in the joint model). With this in mind single variable screening often at least gives an indication where to look. In conclusion the `vtreat` package and `vtreat::value_variables_*()` can be a valuable addition to your supervised learning practice.
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/VariableImportance.Rmd
--- title: "vtreat package" author: "John Mount, Nina Zumel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat package} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- `vtreat` is a `data.frame` processor/conditioner (available [for `R`](https://github.com/WinVector/vtreat), and [for `Python`](https://github.com/WinVector/pyvtreat)) that prepares real-world data for supervised machine learning or predictive modeling in a statistically sound manner. A nice video lecture on what sorts of problems `vtreat` solves can be found [here](https://youtu.be/sniHkkrAsOc?t=42). `vtreat` takes an input `data.frame` that has a specified column called "the outcome variable" (or "y") that is the quantity to be predicted (and must not have missing values). Other input columns are possible explanatory variables (typically numeric or categorical/string-valued, these columns may have missing values) that the user later wants to use to predict "y". In practice such an input `data.frame` may not be immediately suitable for machine learning procedures that often expect only numeric explanatory variables, and may not tolerate missing values. To solve this, `vtreat` builds a transformed `data.frame` where all explanatory variable columns have been transformed into a number of numeric explanatory variable columns, without missing values. The `vtreat` implementation produces derived numeric columns that capture most of the information relating the explanatory columns to the specified "y" or dependent/outcome column through a number of numeric transforms (indicator variables, impact codes, prevalence codes, and more). This transformed `data.frame` is suitable for a wide range of supervised learning methods from linear regression, through gradient boosted machines. The idea is: you can take a `data.frame` of messy real world data and easily, faithfully, reliably, and repeatably prepare it for machine learning using documented methods using `vtreat`. Incorporating `vtreat` into your machine learning workflow lets you quickly work with very diverse structured data. In all cases (classification, regression, unsupervised, and multinomial classification) the intent is that `vtreat` transforms are essentially one liners. The preparation commands are organized as follows: * **Regression**: [`R` regression example, fit/prepare interface](https://github.com/WinVector/vtreat/blob/master/Examples/Regression/Regression_FP.md), [`R` regression example, design/prepare/experiment interface](https://github.com/WinVector/vtreat/blob/master/Examples/Regression/Regression.md), [`Python` regression example](https://github.com/WinVector/pyvtreat/blob/master/Examples/Regression/Regression.md). * **Classification**: [`R` classification example, fit/prepare interface](https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification_FP.md), [`R` classification example, design/prepare/experiment interface](https://github.com/WinVector/vtreat/blob/master/Examples/Classification/Classification.md), [`Python` classification example](https://github.com/WinVector/pyvtreat/blob/master/Examples/Classification/Classification.md). * **Unsupervised tasks**: [`R` unsupervised example, fit/prepare interface](https://github.com/WinVector/vtreat/blob/master/Examples/Unsupervised/Unsupervised_FP.md), [`R` unsupervised example, design/prepare/experiment interface](https://github.com/WinVector/vtreat/blob/master/Examples/Unsupervised/Unsupervised.md), [`Python` unsupervised example](https://github.com/WinVector/pyvtreat/blob/master/Examples/Unsupervised/Unsupervised.md). * **Multinomial classification**: [`R` multinomial classification example, fit/prepare interface](https://github.com/WinVector/vtreat/blob/master/Examples/Multinomial/MultinomialExample_FP.md), [`R` multinomial classification example, design/prepare/experiment interface](https://github.com/WinVector/vtreat/blob/master/Examples/Multinomial/MultinomialExample.md), [`Python` multinomial classification example](https://github.com/WinVector/pyvtreat/blob/master/Examples/Multinomial/MultinomialExample.md). In all cases: variable preparation is intended to be a "one liner." These current revisions of the examples are designed to be small, yet complete. So as a set they have some overlap, but the user can rely mostly on a single example for a single task type. For more detail please see here: [arXiv:1611.09477 stat.AP](https://arxiv.org/abs/1611.09477) (the documentation describes the `R` version, however all of the examples can be found worked in `Python` [here](https://github.com/WinVector/pyvtreat/tree/master/Examples/vtreat_paper1)). `vtreat` is available as an [`R` package](https://github.com/WinVector/vtreat), and also as a [`Python`/`Pandas` package](https://github.com/WinVector/vtreat). Even with modern machine learning techniques (random forests, support vector machines, neural nets, gradient boosted trees, and so on) or standard statistical methods (regression, generalized regression, generalized additive models) there are *common* data issues that can cause modeling to fail. vtreat deals with a number of these in a principled and automated fashion. In particular vtreat emphasizes a concept called "y-aware pre-processing" and implements: - Treatment of missing values through safe replacement plus indicator column (a simple but very powerful method when combined with downstream machine learning algorithms). - Treatment of novel levels (new values of categorical variable seen during test or application, but not seen during training) through sub-models (or impact/effects coding of pooled rare events). - Explicit coding of categorical variable levels as new indicator variables (with optional suppression of non-significant indicators). - Treatment of categorical variables with very large numbers of levels through sub-models (again [impact/effects coding](https://win-vector.com/2012/07/23/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/)). - (optional) User specified significance pruning on levels coded into effects/impact sub-models. - Correct treatment of nested models or sub-models through data split (see [here](https://winvector.github.io/vtreat/articles/vtreatOverfit.html)) or through the generation of "cross validated" data frames (see [here](https://winvector.github.io/vtreat/articles/vtreatCrossFrames.html)); these are issues similar to what is required to build statistically efficient stacked models or super-learners). - Safe processing of "wide data" (data with very many variables, often driving common machine learning algorithms to over-fit) through [out of sample per-variable significance estimates and user controllable pruning](https://winvector.github.io/vtreat/articles/vtreatSignificance.html) (something we have lectured on previously [here](https://github.com/WinVector/WinVector.github.io/tree/master/DS) and [here](https://win-vector.com/2014/02/01/bad-bayes-an-example-of-why-you-need-hold-out-testing/)). - Collaring/Winsorizing of unexpected out of range numeric inputs. - (optional) Conversion of all variables into effects (or "y-scale") units (through the optional `scale` argument to `vtreat::prepare()`, using some of the ideas discussed [here](https://win-vector.com/2014/06/02/skimming-statistics-papers-for-the-ideas-instead-of-the-complete-procedures/)). This allows correct/sensible application of principal component analysis pre-processing in a machine learning context. - Joining in additional training distribution data (which can be useful in analysis, called "catP" and "catD"). The idea is: even with a sophisticated machine learning algorithm there are *many* ways messy real world data can defeat the modeling process, and vtreat helps with at least ten of them. We emphasize: these problems are already in your data, you simply build better and more reliable models if you attempt to mitigate them. Automated processing is no substitute for actually looking at the data, but vtreat supplies efficient, reliable, documented, and tested implementations of many of the commonly needed transforms. To help explain the methods we have prepared some documentation: - The [vtreat package overall](https://winvector.github.io/vtreat/index.html). - [Preparing data for analysis using R white-paper](https://winvector.github.io/DataPrep/EN-CNTNT-Whitepaper-Data-Prep-Using-R.pdf) - The [types of new variables](https://winvector.github.io/vtreat/articles/vtreatVariableTypes.html) introduced by vtreat processing (including how to limit down to domain appropriate variable types). - Statistically sound treatment of the nested modeling issue introduced by any sort of pre-processing (such as vtreat itself): [nested over-fit issues](https://winvector.github.io/vtreat/articles/vtreatOverfit.html) and a general [cross-frame solution](https://winvector.github.io/vtreat/articles/vtreatCrossFrames.html). - [Principled ways to pick significance based pruning levels](https://winvector.github.io/vtreat/articles/vtreatSignificance.html). Data treatments are "y-aware" (use distribution relations between independent variables and the dependent variable). For binary classification use `designTreatmentsC()` and for numeric regression use `designTreatmentsN()`. After the design step, `prepare()` should be used as you would use model.matrix. `prepare()` treated variables are all numeric and never take the value NA or +-Inf (so are very safe to use in modeling). In application we suggest splitting your data into three sets: one for building vtreat encodings, one for training models using these encodings, and one for test and model evaluation. The purpose of `vtreat` library is to reliably prepare data for supervised machine learning. We try to leave as much as possible to the machine learning algorithms themselves, but cover most of the truly necessary typically ignored precautions. The library is designed to produce a `data.frame` that is entirely numeric and takes common precautions to guard against the following real world data issues: - Categorical variables with very many levels. We re-encode such variables as a family of indicator or dummy variables for common levels plus an additional [impact code](https://win-vector.com/2012/07/23/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/) (also called "effects coded"). This allows principled use (including smoothing) of huge categorical variables (like zip-codes) when building models. This is critical for some libraries (such as `randomForest`, which has hard limits on the number of allowed levels). - Rare categorical levels. Levels that do not occur often during training tend not to have reliable effect estimates and contribute to over-fit. vtreat helps with 2 precautions in this case. First the `rareLevel` argument suppresses levels with this count our below from modeling, except possibly through a grouped contribution. Also with enough data vtreat attempts to estimate out of sample performance of derived variables. Finally we suggest users reserve a portion of data for vtreat design, separate from any data used in additional training, calibration, or testing. - Novel categorical levels. A common problem in deploying a classifier to production is: new levels (levels not seen during training) encountered during model application. We deal with this by encoding categorical variables in a possibly redundant manner: reserving a dummy variable for all levels (not the more common all but a reference level scheme). This is in fact the correct representation for regularized modeling techniques and lets us code novel levels as all dummies simultaneously zero (which is a reasonable thing to try). This encoding while limited is cheaper than the fully Bayesian solution of computing a weighted sum over previously seen levels during model application. - Missing/invalid values NA, NaN, +-Inf. Variables with these issues are re-coded as two columns. The first column is clean copy of the variable (with missing/invalid values replaced with either zero or the grand mean, depending on the user chose of the `scale` parameter). The second column is a dummy or indicator that marks if the replacement has been performed. This is simpler than imputation of missing values, and allows the downstream model to attempt to use missingness as a useful signal (which it often is in industrial data). - Extreme values. Variables can be restricted to stay in ranges seen during training. This can defend against some run-away classifier issues during model application. - Constant and near-constant variables. Variables that "don't vary" or "nearly don't vary" are suppressed. - Need for estimated single-variable model effect sizes and significances. It is a dirty secret that even popular machine learning techniques need some variable pruning (when exposed to very wide data frames, see [here](https://win-vector.com/2014/02/01/bad-bayes-an-example-of-why-you-need-hold-out-testing/) and [here](https://www.youtube.com/watch?v=X_Rn3EOEjGE)). We make the necessary effect size estimates and significances easily available and supply initial variable pruning. The above are all awful things that often lurk in real world data. Automating these steps ensures they are easy enough that you actually perform them and leaves the analyst time to look for additional data issues. For example this allowed us to essentially automate a number of the steps taught in chapters 4 and 6 of [*Practical Data Science with R* (Zumel, Mount; Manning 2014)](https://win-vector.com/practical-data-science-with-r/) into a [very short worksheet](https://winvector.github.io/KDD2009/KDD2009RF.html) (though we think for understanding it is *essential* to work all the steps by hand as we did in the book). The 2nd edition of *Practical Data Science with R* covers using `vtreat` in `R` in chapter 8 "Advanced Data Preparation." The idea is: `data.frame`s prepared with the `vtreat` library are somewhat safe to train on as some precaution has been taken against all of the above issues. Also of interest are the `vtreat` variable significances (help in initial variable pruning, a necessity when there are a large number of columns) and `vtreat::prepare(scale=TRUE)` which re-encodes all variables into effect units making them suitable for y-aware dimension reduction (variable clustering, or principal component analysis) and for geometry sensitive machine learning techniques (k-means, knn, linear SVM, and more). You may want to do more than the `vtreat` library does (such as Bayesian imputation, variable clustering, and more) but you certainly do not want to do less. There have been a number of recent substantial improvements to the library, including: - Out of sample scoring. - Ability to use `parallel`. - More general calculation of effect sizes and significances. Some of our related articles (which should make clear some of our motivations, and design decisions): - [Modeling trick: impact coding of categorical variables with many levels](https://win-vector.com/2012/07/23/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/) - [A bit more on impact coding](https://win-vector.com/2012/08/02/a-bit-more-on-impact-coding/) - [vtreat: designing a package for variable treatment](https://win-vector.com/2014/08/07/vtreat-designing-a-package-for-variable-treatment/) - [A comment on preparing data for classifiers](https://win-vector.com/2014/12/04/a-comment-on-preparing-data-for-classifiers/) - [Nina Zumel presenting on vtreat](https://www.slideshare.net/ChesterChen/vtreat) - [What is new in the vtreat library?](https://win-vector.com/2015/05/07/what-is-new-in-the-vtreat-library/) - [How do you know if your data has signal?](https://win-vector.com/2015/08/10/how-do-you-know-if-your-data-has-signal/) Examples of current best practice using `vtreat` (variable coding, train, test split) can be found [here](https://winvector.github.io/vtreat/articles/vtreatOverfit.html) and [here](https://winvector.github.io/KDD2009/KDD2009RF.html). Some small examples: We attach our packages. ```{r} library("vtreat") packageVersion("vtreat") citation('vtreat') ``` A small categorical example. ```{r} # categorical example set.seed(23525) # we set up our raw training and application data dTrainC <- data.frame( x = c('a', 'a', 'a', 'b', 'b', NA, NA), z = c(1, 2, 3, 4, NA, 6, NA), y = c(FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE)) dTestC <- data.frame( x = c('a', 'b', 'c', NA), z = c(10, 20, 30, NA)) # we perform a vtreat cross frame experiment # and unpack the results into treatmentsC # and dTrainCTreated unpack[ treatmentsC = treatments, dTrainCTreated = crossFrame ] <- mkCrossFrameCExperiment( dframe = dTrainC, varlist = setdiff(colnames(dTrainC), 'y'), outcomename = 'y', outcometarget = TRUE, verbose = FALSE) # the treatments include a score frame relating new # derived variables to original columns treatmentsC$scoreFrame[, c('origName', 'varName', 'code', 'rsq', 'sig', 'extraModelDegrees', 'recommended')] %.>% knitr::kable(.) # the treated frame is a "cross frame" which # is a transform of the training data built # as if the treatment were learned on a different # disjoint training set to avoid nested model # bias and over-fit. dTrainCTreated %.>% head(.) %.>% knitr::kable(.) # Any future application data is prepared with # the prepare method. dTestCTreated <- prepare(treatmentsC, dTestC, pruneSig=NULL) dTestCTreated %.>% head(.) %.>% knitr::kable(.) ``` A small numeric example. ```{r} # numeric example set.seed(23525) # we set up our raw training and application data dTrainN <- data.frame( x = c('a', 'a', 'a', 'a', 'b', 'b', NA, NA), z = c(1, 2, 3, 4, 5, NA, 7, NA), y = c(0, 0, 0, 1, 0, 1, 1, 1)) dTestN <- data.frame( x = c('a', 'b', 'c', NA), z = c(10, 20, 30, NA)) # we perform a vtreat cross frame experiment # and unpack the results into treatmentsN # and dTrainNTreated unpack[ treatmentsN = treatments, dTrainNTreated = crossFrame ] <- mkCrossFrameNExperiment( dframe = dTrainN, varlist = setdiff(colnames(dTrainN), 'y'), outcomename = 'y', verbose = FALSE) # the treatments include a score frame relating new # derived variables to original columns treatmentsN$scoreFrame[, c('origName', 'varName', 'code', 'rsq', 'sig', 'extraModelDegrees')] %.>% knitr::kable(.) # the treated frame is a "cross frame" which # is a transform of the training data built # as if the treatment were learned on a different # disjoint training set to avoid nested model # bias and over-fit. dTrainNTreated %.>% head(.) %.>% knitr::kable(.) # Any future application data is prepared with # the prepare method. dTestNTreated <- prepare(treatmentsN, dTestN, pruneSig=NULL) dTestNTreated %.>% head(.) %.>% knitr::kable(.) ``` Related work: * Cohen J, Cohen P (1983). Applied Multiple Regression/Correlation Analysis For The Behavioral Sciences. 2 edition. Lawrence Erlbaum Associates, Inc. ISBN 0-89859-268-2. * ["A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems"](https://dl.acm.org/doi/10.1145/507533.507538) Daniele Micci-Barreca; ACM SIGKDD Explorations, Volume 3 Issue 1, July 2001 Pages 27-32. * ["Modeling Trick: Impact Coding of Categorical Variables with Many Levels"](https://win-vector.com/2012/07/23/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/) Nina Zumel; Win-Vector blog, 2012. * "Big Learning Made Easy – with Counts!", Misha Bilenko, Cortana Intelligence and Machine Learning Blog, 2015. ## Note Notes on controlling `vtreat`'s cross-validation plans can be found [here](https://github.com/WinVector/vtreat/blob/master/Examples/CustomizedCrossPlan/CustomizedCrossPlan.md). Note: `vtreat` is meant only for "tame names", that is: variables and column names that are also valid *simple* (without quotes) `R` variables names.
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreat.Rmd
--- title: "vtreat cross frames" author: "John Mount, Nina Zumel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat cross frames} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- Example demonstrating "cross validated training frames" (or "cross frames") in vtreat. Consider the following data frame. The outcome only depends on the "good" variables, not on the (high degree of freedom) "bad" variables. Modeling such a data set runs a high risk of over-fit. ```{r} set.seed(22626) mkData <- function(n) { d <- data.frame(xBad1=sample(paste('level',1:1000,sep=''),n,replace=TRUE), xBad2=sample(paste('level',1:1000,sep=''),n,replace=TRUE), xBad3=sample(paste('level',1:1000,sep=''),n,replace=TRUE), xGood1=rnorm(n), xGood2=rnorm(n)) # outcome only depends on "good" variables d$y <- rnorm(nrow(d))+0.2*d$xGood1 + 0.3*d$xGood2>0.5 # the random group used for splitting the data set, not a variable. d$rgroup <- sample(c("cal","train","test"),nrow(d),replace=TRUE) d } d <- mkData(2000) # devtools::install_github("WinVector/WVPlots") # library('WVPlots') plotRes <- function(d,predName,yName,title) { print(title) tab <- table(truth=d[[yName]],pred=d[[predName]]>0.5) print(tab) diag <- sum(vapply(seq_len(min(dim(tab))), function(i) tab[i,i],numeric(1))) acc <- diag/sum(tab) # if(requireNamespace("WVPlots",quietly=TRUE)) { # print(WVPlots::ROCPlot(d,predName,yName,title)) # } print(paste('accuracy',acc)) } ``` ## The Wrong Way Bad practice: use the same set of data to prepare variable encoding and train a model. ```{r badmixcalandtrain} dTrain <- d[d$rgroup!='test',,drop=FALSE] dTest <- d[d$rgroup=='test',,drop=FALSE] treatments <- vtreat::designTreatmentsC(dTrain,c('xBad1','xBad2','xBad3','xGood1','xGood2'), 'y',TRUE, rareCount=0 # Note: usually want rareCount>0, setting to zero to illustrate problem ) dTrainTreated <- vtreat::prepare(treatments,dTrain, pruneSig=c() # Note: usually want pruneSig to be a small fraction, setting to null to illustrate problems ) f <- wrapr::mk_formula("y", treatments$scoreFrame$varName) print(f) m1 <- glm(f, data=dTrainTreated,family=binomial(link='logit')) print(summary(m1)) # notice low residual deviance dTrain$predM1 <- predict(m1,newdata=dTrainTreated,type='response') plotRes(dTrain,'predM1','y','model1 on train') dTestTreated <- vtreat::prepare(treatments,dTest,pruneSig=c()) dTest$predM1 <- predict(m1,newdata=dTestTreated,type='response') plotRes(dTest,'predM1','y','model1 on test') ``` Notice above that we see a training accuracy of 98% and a test accuracy of 60%. Also notice the downstream model (the `glm`) erroneously thinks the `xBad?_cat` variables are significant (due to the large number of degrees of freedom hidden from the downstream model by the [impact/effect coding](https://win-vector.com/2012/07/23/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/)). ## The Right Way: A Calibration Set Now try a proper calibration/train/test split: ```{r separatecalandtrain} dCal <- d[d$rgroup=='cal',,drop=FALSE] dTrain <- d[d$rgroup=='train',,drop=FALSE] dTest <- d[d$rgroup=='test',,drop=FALSE] # a nice heuristic, # expect only a constant number of noise variables to sneak past pruneSig <- 1/ncol(dTrain) treatments <- vtreat::designTreatmentsC(dCal, c('xBad1','xBad2','xBad3','xGood1','xGood2'), 'y',TRUE, rareCount=0 # Note: usually want rareCount>0, setting to zero to illustrate problem ) dTrainTreated <- vtreat::prepare(treatments,dTrain, pruneSig=pruneSig) newvars <- setdiff(colnames(dTrainTreated),'y') m1 <- glm(paste('y',paste(newvars,collapse=' + '),sep=' ~ '), data=dTrainTreated,family=binomial(link='logit')) print(summary(m1)) dTrain$predM1 <- predict(m1,newdata=dTrainTreated,type='response') plotRes(dTrain,'predM1','y','model1 on train') dTestTreated <- vtreat::prepare(treatments,dTest, pruneSig=pruneSig) dTest$predM1 <- predict(m1,newdata=dTestTreated,type='response') plotRes(dTest,'predM1','y','model1 on test') ``` Notice above that we now see training and test accuracies of 70%. We have defeated over-fit in two ways: training performance is closer to test performance, and test performance is better. Also we see that the model now properly considers the "bad" variables to be insignificant. ## Another Right Way: Cross-Validation Below is a more statistically efficient practice: building a cross training frame. ### The intuition Consider any trained statistical model (in this case our treatment plan and variable selection plan) as a two-argument function _f(A,B)_. The first argument is the training data and the second argument is the application data. In our case _f(A,B)_ is: `designTreatmentsC(A) %>% prepare(B)`, and it produces a treated data frame. When we use the same data in both places to build our training frame, as in > _TrainTreated = f(TrainData,TrainData)_, we are not doing a good job simulating the future application of _f(,)_, which will be _f(TrainData,FutureData)_. To improve the quality of our simulation we can call > _TrainTreated = f(CalibrationData,TrainData)_ where _CalibrationData_ and _TrainData_ are disjoint datasets (as we did in the earlier example) and expect this to be a good imitation of future _f(CalibrationData,FutureData)_. ### Cross-Validation and vtreat: The cross-frame. Another approach is to build a "cross validated" version of _f_. We split _TrainData_ into a list of 3 disjoint row intervals: _Train1_,_Train2_,_Train3_. Instead of computing _f(TrainData,TrainData)_ compute: > _TrainTreated = f(Train2+Train3,Train1) + f(Train1+Train3,Train2) + f(Train1+Train2,Train3)_ (where + denotes `rbind()`). The idea is this looks a lot like _f(TrainData,TrainData)_ except it has the important property that no row in the right-hand side is ever worked on by a model built using that row (a key characteristic that future data will have) so we have a good imitation of _f(TrainData,FutureData)_. In other words: we use cross validation to simulate future data. The main thing we are doing differently is remembering that we can apply cross validation to *any* two argument function _f(A,B)_ and not only to functions of the form _f(A,B)_ = `buildModel(A) %>% scoreData(B)`. We can use this formulation in stacking or super-learning with _f(A,B)_ of the form `buildSubModels(A) %>% combineModels(B)` (to produce a stacked or ensemble model); the idea applies to improving ensemble methods in general. See: - "General oracle inequalities for model selection" Charles Mitchell and Sara van de Geer - "On Cross-Validation and Stacking: Building seemingly predictive models on random data" Claudia Perlich and Grzegorz Swirszcz - "Super Learner" Mark J. van der Laan, Eric C. Polley, and Alan E. Hubbard In fact you can think of vtreat as a super-learner. In super learning cross validation techniques are used to simulate having built sub-model predictions on novel data. The simulated out of sample-applications of these sub models (and not the sub models themselves) are then used as input data for the next stage learner. In future application the actual sub-models are applied and their immediate outputs is used by the super model. <img src="superX.png" width="600"> In vtreat the sub-models are single variable treatments and the outer model construction is left to the practitioner (using the cross-frames for simulation and not the treatmentplan). In application the treatment plan is used. <img src="vtreatX.png" width="600"> ### Example Below is the example cross-run. The function `mkCrossFrameCExperiment` returns a treatment plan for use in preparing future data, and a cross-frame for use in fitting a model. ```{r crossframes} dTrain <- d[d$rgroup!='test',,drop=FALSE] dTest <- d[d$rgroup=='test',,drop=FALSE] prep <- vtreat::mkCrossFrameCExperiment(dTrain, c('xBad1','xBad2','xBad3','xGood1','xGood2'), 'y',TRUE, rareCount=0 # Note: usually want rareCount>0, setting to zero to illustrate problems ) treatments <- prep$treatments knitr::kable(treatments$scoreFrame[,c('varName','sig')]) colnames(prep$crossFrame) # vtreat::mkCrossFrameCExperiment doesn't take a pruneSig argument, but we can # prune on our own. print(pruneSig) newvars <- treatments$scoreFrame$varName[treatments$scoreFrame$sig<=pruneSig] # force in bad variables, to show we "belt and suspenders" deal with them # in that things go well in the cross-frame even if they sneak past pruning newvars <- sort(union(newvars,c("xBad1_catB","xBad2_catB","xBad3_catB"))) print(newvars) dTrainTreated <- prep$crossFrame ``` We ensured the undesirable `xBad*_catB` variables back in to demonstrate that even if they sneak past a lose `pruneSig`, the crossframe lets the downstream model deal with them correctly. To ensure more consistent filtering of the complicated variables one can increase the `ncross` argument in `vtreat::mkCrossFrameCExperiment`/`vtreat::mkCrossFrameNExperiment`. Now we fit the model to *the cross-frame* rather than to `prepare(treatments, dTrain)` (the treated training data). ```{r xframemodel} m1 <- glm(paste('y',paste(newvars,collapse=' + '),sep=' ~ '), data=dTrainTreated,family=binomial(link='logit')) print(summary(m1)) dTrain$predM1 <- predict(m1,newdata=dTrainTreated,type='response') plotRes(dTrain,'predM1','y','model1 on train') dTestTreated <- vtreat::prepare(treatments,dTest, pruneSig=c(),varRestriction=newvars) knitr::kable(head(dTestTreated)) dTest$predM1 <- predict(m1,newdata=dTestTreated,type='response') plotRes(dTest,'predM1','y','model1 on test') ``` We again get the better 70% test accuracy. And this is a more statistically efficient technique as we didn't have to restrict some data to calibration. The model fit to the cross-frame behaves similarly to the model produced via the process _f(CalibrationData, TrainData)_. Notice that the `xBad*_catB` variables fail to achieve significance in the downstream `glm` model, allowing that model to give them small coefficients and even (if need be) prune them out. This is the point of using a cross frame as we see in the first example the `xBad*_catB` are hard to remove if they make it to standard (non-cross) frames as they are hiding a lot of degrees of freedom from downstream modeling procedures.
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatCrossFrames.Rmd
--- title: "vtreat grouping example" author: "Nina Zumel, Nate Sutton" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat grouping example} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r setup, include=FALSE} knitr::opts_chunk$set(fig.width = 7) ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} library(vtreat) set.seed(23255) have_rqdatatable = requireNamespace("rqdatatable", quietly=TRUE) if(have_rqdatatable) { library(rqdatatable) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} # # takes the frame (d) and the outcome column (d$conc) # from the global environment # showGroupingBehavior = function(groupcol, title) { print(title) # display means of each group print("Group means:") means = tapply(d$conc, d[[groupcol]], mean) print(means) print(paste("Standard deviation of group means:", sd(means))) } ``` This vignette shows an example use of _y_-stratified sampling with a grouping restriction in `vtreat`. For this example, we will use the `Theosph` dataset: data from an experiment on the pharmacokinetics of theophylline. We will demonstrate the desired effects of _y_-stratification while also respecting a grouping constraint. ## The Data First, let's look at the data. ```{r data} # panel data for concentration in multiple subjects d <- datasets::Theoph head(d) summary(d) ``` We have twelve subjects, who each received a dose of the anti-asthma drug theophylline. The theophylline concentration in the patients' blood was then measured at eleven points during the next 25 hours. Most of the patients got about the same dose, although the dose information reported in the dataset is normalized by weight. ## Partitioning the Data for Modeling Suppose we wanted to fit a model to analyze how a patient's weight affects how theophylline is metabolized, and validate that model with three-fold cross-validation. It would be important that all readings from a given patient stay in the same fold. We might also want the population in each fold to have similar distributions of theophylline concentrations curves. Recall that the goal of _y_-stratification is to insure that all samples from the data have as close to identical _y_ distributions as possible. This becomes more difficult when we also have to obey a grouping constraint. Let's look at three ways of splitting the data into folds. First, we will split the data arbitrarily into three groups, using the modulo of the Subject id to do the splitting. ```{r} # a somewhat arbitrary split of patients subnum = as.numeric(as.character(d$Subject)) d$modSplit = as.factor(subnum %% 3) ``` We can verify that this split preserves groups, by looking at the table of subject observations in each fold. Each subject should only appear in a single fold. ```{r} print(table(Subject=d$Subject, groupid=d$modSplit)) ``` Now let's try the standard _y_ stratification in `vtreat`. ```{r} # stratify by outcome only # forces concentration to be equivalent pStrat <- kWayStratifiedY(nrow(d),3,d,d$conc) attr(pStrat, "splitmethod") d$stratSplit <- vtreat::getSplitPlanAppLabels(nrow(d),pStrat) print(table(Subject=d$Subject, groupid=d$stratSplit)) ``` We can see this partition didn't preserve the `Subject` grouping. Finally, we can try `vtreat`'s group-preserving split, which also tries to _y_-stratify as much as possible (by stratifying on the mean *y* observation from each group). ```{r} # stratify by patient and outcome # allows concentration to vary amoung individual patients splitter <- makekWayCrossValidationGroupedByColumn('Subject') split <- splitter(nrow(d),3,d,d$conc) attr(split, "splitmethod") d$subjectSplit <- vtreat::getSplitPlanAppLabels(nrow(d),split) print(table(Subject=d$Subject, groupid=d$subjectSplit)) ``` This is again a subject-preserving partition. We can compare the mean theophylline concentration and the average pharmacokinetic profile for each fold, for both of the subject-preserving partitions. We see that the stratification reduces some of the variation between folds. ### Arbitrary Partition ```{r echo=FALSE} showGroupingBehavior("modSplit", "Arbitrary grouping") ``` ### Group-preserving, _y_-stratified Partition ```{r echo=FALSE} showGroupingBehavior("subjectSplit", "Group by patient, stratify on y") ```
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatGrouping.Rmd
--- title: "vtreat overfit" author: "John Mount, Nina Zumel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat overfit} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- Example showing safe "best practice" use of the ['vtreat'](https://cran.r-project.org/package=vtreat) variable preparation library. For more on `vtreat` see [here](https://github.com/WinVector/vtreat). Below we generate an example data frame with no relation between x and y. We are using a synthetic data set so we know what the "right answer is" (no signal). False fitting on no-signal variables is bad for several reasons: * It creates undesirable biases in variable quality estimates and in subsequent models. * It "hides degrees of freedom" from subsequent models. * It creates the false impression you have a good result (which you may fail to falsify). * Complex bad variables can starve out simple weak good variables. This example shows things we don't want to happen, and then the additional precautions that help prevent them. ```{r} set.seed(22626) d <- data.frame(x=sample(paste('level',1:1000,sep=''),2000,replace=TRUE)) # independent variable. d$y <- runif(nrow(d))>0.5 # the quantity to be predicted, notice: independent of variables. d$rgroup <- round(100*runif(nrow(d))) # the random group used for splitting the data set, not a variable. ``` ## Bad Practice: Using the same data to treat and to train Using the same set of data to prepare the variable encoding and train the model can lead to the false belief (derived from the training set) that the model fit well. This is largely due to the treated variable appearing to consume only one degree of freedom, when it in fact consumes many more. In many cases a reasonable setting of `pruneSig` (say 0.01) will help against a noise variable being considered desirable, but selected variables may still be mis-used by downstream modeling. ```{r} dTrain <- d[d$rgroup<=80,,drop=FALSE] dTest <- d[d$rgroup>80,,drop=FALSE] library('vtreat') treatments <- vtreat::designTreatmentsC(dTrain,'x','y',TRUE, rareCount=0 # Note: usually want rareCount>0, setting to zero to illustrate problem ) dTrainTreated <- vtreat::prepare(treatments,dTrain, pruneSig=c() # Note: usually want pruneSig to be a small fraction, setting to null to illustrate problem ) m1 <- glm(y~x_catB,data=dTrainTreated,family=binomial(link='logit')) print(summary(m1)) # notice low residual deviance dTrain$predM1 <- predict(m1,newdata=dTrainTreated,type='response') # devtools::install_github("WinVector/WVPlots") # library('WVPlots') plotRes <- function(d,predName,yName,title) { print(title) tab <- table(truth=d[[yName]],pred=d[[predName]]>0.5) print(tab) diag <- sum(vapply(seq_len(min(dim(tab))), function(i) tab[i,i],numeric(1))) acc <- diag/sum(tab) # if(requireNamespace("WVPlots",quietly=TRUE)) { # print(WVPlots::ROCPlot(d,predName,yName,title)) # } print(paste('accuracy',acc)) } # evaluate model on training plotRes(dTrain,'predM1','y','model1 on train') # evaluate model on test dTestTreated <- vtreat::prepare(treatments,dTest,pruneSig=c()) dTest$predM1 <- predict(m1,newdata=dTestTreated,type='response') plotRes(dTest,'predM1','y','model1 on test') ``` The above is bad: we saw a "significant" model fit on training data (even though there is no relation to be found). This means the treated training data can be confusing to machine learning techniques and to the analyst. The issue is that the training data is no longer exchangeable with the test data because the training data was used to build the variable encodings. One way to avoid this is to not use the training data for variable encoding construction, but instead use a third set for this task. ### What went wrong? Notice that vtreat did not think there was any usable signal, and did not want us to use the variables: the values in `treatments$scoreFrame$sig` are all much larger than a nominally acceptable significance level like 0.05. The variables stayed in our model because we did not prune them (_ie_ we set `pruneSig=c()`). Also notice we set `rareCount=0`, which allows the use of very rare levels (which help drive the problem). ```{r} print(treatments$scoreFrame) ``` Subsequently, the down-stream machine learning (in this case a standard logistic regression) used the variable incorrectly. The modeling algorithm gave the variable a non-negligible coefficient (around 3) that it thought was reliably bounded away from zero; it also believed that the resulting model almost halved deviance (when in fact it explained nothing). So any variables that do get through may have distributional issues (and misleadingly low apparent degrees of freedom). **Rare levels of a categorical variable** The biggest contributors to this distributional issue tend to be rare levels of categorical variables. Since the individual levels are rare we have unreliable estimates for their effects, and if there are very many of them we may see quite a large effect in aggregate. To help combat this we have a control called `rareLevels`. Any level that is observed no more than `rareLevels` times during training is re-mapped to a new special level called _rare_ and not allowed to directly contribute (i.e. can not generate unique indicator columns, and doesn't have a direct effect on `catB` or `catN` encodings). If all the rare levels have a distinct behavior after grouping, the _rare_ level can capture that. **Impact-coding of categorical variables with many levels** Another undesirable effect is over-estimating significance of derived variable fit for `catB` and `catN` impact-coded variables. To fight this vtreat attempts to estimate out of sample or cross-validated effect significances (when it has enough data). With enough data, setting the `pruneSig` parameter during `prepare()` will help remove noise variables. One can set `pruneSig` to something like _1/number-of-columns_ to ensure that with high probability only an constant number of truly useless variables make it to later modeling. However, the significance of a given effect size for variables that actually have some signal (i.e. non-noise variables) can still be sensitive to in/out sample scoring and the hiding of degrees of freedom that occurs when a large categorical variable (that represents a large number of degrees of freedom) is re-coded as an impact or effect (which appears to have only a single degree of freedom). We next show how to avoid these undesirable illusory effects: better practice in partitioning and using training data. We are doing more with our data (essentially chaining models), so we have to take a bit more care with our data. ## Correct Practice 1/2: Use different data to treat and train Below is part of our suggested work pattern: coding/train/test split. ```{r} dCode <- d[d$rgroup<=20,,drop=FALSE] dTrain <- d[(d$rgroup>20) & (d$rgroup<=80),,drop=FALSE] treatments <- vtreat::designTreatmentsC(dCode,'x','y',TRUE, rareCount=0, # Note set this to something larger, like 5 rareSig=c() # Note set this to something like 0.3 ) dTrainTreated <- vtreat::prepare(treatments,dTrain, pruneSig=c() # Note: set this to filter, like 0.05 or 1/nvars ) m2 <- glm(y~x_catB,data=dTrainTreated,family=binomial(link='logit')) print(summary(m2)) # notice high residual deviance dTrain$predM2 <- predict(m2,newdata=dTrainTreated,type='response') plotRes(dTrain,'predM2','y','model2 on train') # We do not advise creating dCodeTreated for any purpose other than # diagnostic plotting. You should not use the treated coding data # for anything (as that would undo the benefit of having a separate # coding data subset). dCodeTreated <- vtreat::prepare(treatments,dCode,pruneSig=c()) dCode$predM2 <- predict(m2,newdata=dCodeTreated,type='response') plotRes(dCode,'predM2','y','model2 on coding set') dTestTreated <- vtreat::prepare(treatments,dTest,pruneSig=c()) dTest$predM2 <- predict(m2,newdata=dTestTreated,type='response') plotRes(dTest,'predM2','y','model2 on test set') ``` In the above example we saw training and test performance are similar -- and equally poor, as they should be since there is no signal. Though it didn't happen in this case, note the coding set can (falsely) show high performance. This is the bad behavior we wanted to isolate out of the training set. Remember, the goal isn't good performance on training- it is good performance on future data (simulated by test). So doing well on training and bad on test is worse than doing bad on both test and training. There are, of course, other methods to avoid the bias introduced in using the same data to both treat/encode the variables and to train the model. vtreat incorporates a number of these methods, including smoothing (controlled through `smFactor`) and pruning of rare levels (controlled through `rareSig`). ## Correct Practice 2/2: Use simulated out of sample methods (cross methods) Another effective technique: cross-constructed training frames can also be accessed by using `mkCrossFrameCExperiment` or `mkCrossFrameNExperiment`, which we demonstrate here. ```{r} dTrain <- d[d$rgroup<=80,,drop=FALSE] xdat <- vtreat::mkCrossFrameCExperiment(dTrain,'x','y',TRUE, rareCount=0, # Note set this to something larger, like 5 rareSig=c()) treatments <- xdat$treatments print(treatments$scoreFrame) dTrainTreated <- xdat$crossFrame m3 <- glm(y~x_catB,data=dTrainTreated,family=binomial(link='logit')) print(summary(m3)) # notice high residual deviance dTrainTreated$predM3 <- predict(m3,newdata=dTrainTreated,type='response') plotRes(dTrainTreated,'predM3','y','model3 on train') dTestTreated <- vtreat::prepare(treatments,dTest,pruneSig=c()) dTest$predM3 <- predict(m3,newdata=dTestTreated,type='response') plotRes(dTest,'predM3','y','model3 on test set') ``` Notice the glm significance is off, but the model quality is similar on train and test, and the scoreFrame significance is a correct indication.
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatOverfit.Rmd
--- title: "vtreat Rare Levels" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat Rare Levels} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- For some categorical variables rarity can reflect structural features. For instance with United States Zip codes rare zip codes often represent low population density regions. When this is the case it can make sense to pool the rare levels into a new re-coded level called ``rare.'' If this new level is statistically significant it can be a usable modeling feature. This sort of pooling is only potentially useful if below a given training count behave similarly. This capability was more of an experimental demonstration of possible extensions of `vtreat` to have more inference capabilities about rare level than a commonly useful feature. Most of this power has since been captured in the more useful `catP` feature (also demonstrated here). Even more power is found in using an interaction of `catN` or `catB` with `catP`. An example of the rare level feature using `vtreat` is given below. First we set up some data by defining a set of population centers (`populationFrame`) and code to observe individuals (with replacement) uniformly from the combined population with a rare condition (`inClass`) that has elevated occurrence in observations coming from the small population centers (`rareCodes`). ```{r} library('vtreat') set.seed(2325) populationFrame <- data.frame( popsize = round(rlnorm(100,meanlog=log(4000),sdlog=1)), stringsAsFactors = FALSE) populationFrame$code <- paste0('z',formatC(sample.int(100000, size=nrow(populationFrame), replace=FALSE),width=5,flag='0')) rareCodes <- populationFrame$code[populationFrame$popsize<1000] # Draw individuals from code-regions proportional to size of code region # (or uniformly over all individuals labeled by code region). # Also add the outcome which has altered conditional probability for rareCodes. drawIndividualsAndReturnCodes <- function(n) { ords <- sort(sample.int(sum(populationFrame$popsize),size=n,replace=TRUE)) cs <- cumsum(populationFrame$popsize) indexes <- findInterval(ords,cs)+1 indexes <- indexes[sample.int(n,size=n,replace=FALSE)] samp <- data.frame(code=populationFrame$code[indexes], stringsAsFactors = FALSE) samp$inClass <- runif(n) < ifelse(samp$code %in% rareCodes,0.3,0.01) samp } ``` We then draw a sample we want to make some observations on. ```{r} testSet <- drawIndividualsAndReturnCodes(2000) table(generatedAsRare=testSet$code %in% rareCodes,inClass=testSet$inClass) ``` Notice that in the sample we can observe the elevated rate of `inClass==TRUE` conditioned on coming from a `code` that is one of the `rareCodes`. We could try to learn this relation using `vtreat`. To do this we set up another sample (`designSet`) to work on, so we are not inferring from `testSet` (where we will evaluate results). ```{r} designSet <- drawIndividualsAndReturnCodes(2000) treatments <- vtreat::designTreatmentsC(designSet,'code','inClass',TRUE, rareCount=5,rareSig=NULL, verbose=FALSE) treatments$scoreFrame[,c('varName','sig'),drop=FALSE] ``` We see in `treatments$scoreFrame` we have a level called `code_lev_rare`, which is where a number of rare levels are re-coding. We can also confirm levels that occur `rareCount` or fewer times are eligible to code to to `code_lev_rare`. ```{r} designSetTreated <- vtreat::prepare(treatments,designSet,pruneSig=0.5) designSetTreated$code <- designSet$code summary(as.numeric(table(designSetTreated$code[designSetTreated$code_lev_rare==1]))) summary(as.numeric(table(designSetTreated$code[designSetTreated$code_lev_rare!=1]))) ``` We can now apply this treatment to `testSet` to see how this inferred rare level performs. Notice also the `code_catP` which directly encodes prevalence or frequency of the level during training also gives usable estimate of size (likely a more useful one then the rare-level code itself). As we can see below the `code_lev_rare` correlates with the condition, and usefully re-codes novel levels (levels in `testSet` that were not seen in `designSet`) to rare. ```{r, fig.width=6} testSetTreated <- vtreat::prepare(treatments,testSet,pruneSig=0.5) testSetTreated$code <- testSet$code testSetTreated$newCode <- !(testSetTreated$code %in% unique(designSet$code)) testSetTreated$generatedAsRareCode <- testSetTreated$code %in% rareCodes # Show code_lev_rare==1 corresponds to a subset of rows with elevated inClass==TRUE rate. table(code_lev_rare=testSetTreated$code_lev_rare, inClass=testSetTreated$inClass) # Show newCodes get coded with code_level_rare==1. table(newCode=testSetTreated$newCode,code_lev_rare=testSetTreated$code_lev_rare) # Show newCodes tend to come from defined rareCodes. table(newCode=testSetTreated$newCode, generatedAsRare=testSetTreated$generatedAsRareCode) ``` ```{r, fig.width=6} # Show code_catP's behavior on rare and novel levels. summary(testSetTreated$code_catP) summary(testSetTreated$code_catP[testSetTreated$code_lev_rare==1]) summary(testSetTreated$code_catP[testSetTreated$newCode]) summary(testSetTreated$code_catP[testSetTreated$generatedAsRareCode]) ```
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatRareLevels.Rmd
--- title: "vtreat scale mode" author: "Win-Vector LLC" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat scale mode} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- <code>vtreat::prepare(scale=TRUE)</code> is a variation of <code>vtreat::prepare()</code> intended to prepare data frames so all the derived input or independent (`x`) variables are fully in outcome or dependent variable (`y`) units. This is in the sense of a linear regression for numeric `y`'s (`vtreat::designTreatmentsN` and `vtreat::mkCrossFrameNExperiment`). For classification problems (or categorical `y`'s) as of version `0.5.26` and newer (available [here](https://github.com/WinVector/vtreat)) scaling is established through a a logistic regression ["in link units"](https://github.com/WinVector/Examples/blob/master/PCR/YAwarePCAclassification.md) or as 0/1 indicators depending on the setting of the `catScaling` argument in `vtreat::designTreatmentsC` or `vtreat::mkCrossFrameNExperiment`. Prior to this version classification the scaling calculation (and only the scaling calculation) was always handled as a linear regression against a 0/1 `y`-indicator. `catScaling=FALSE` can be a bit faster as the underlying regression can be a bit quicker than a logistic regression. This is the appropriate preparation before a geometry/metric sensitive modeling step such as principal components analysis or clustering (such as k-means clustering). Normally (with <code>vtreat::prepare(scale=FALSE)</code>) vtreat passes through a number of variables with minimal alteration (cleaned numeric), builds 0/1 indicator variables for various conditions (categorical levels, presence of NAs, and so on), and builds some "in y-units" variables (catN, catB) that are in fact sub-models. With <code>vtreat::prepare(scale=TRUE)</code> all of these numeric variables are then re-processed to have mean zero, and slope 1 (when possible) when appropriately regressed against the y-variable. This is easiest to illustrate with a concrete example. ```{r exampledata} library('vtreat') dTrainC <- data.frame(x=c('a','a','a','b','b',NA), y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE, catScaling=FALSE, verbose=FALSE) dTrainCTreatedUnscaled <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=FALSE) dTrainCTreatedScaled <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=TRUE) ``` Note we have set `catScaling=FALSE` to ask that we treat `y` as a 0/1 indicator and scale using linear regression. The standard vtreat treated frame converts the original data from this: ```{r printorig} print(dTrainC) ``` into this: ```{r printunscaled} print(dTrainCTreatedUnscaled) ``` This is the "standard way" to run vtreat -- with the exception that for this example we set <code>pruneSig</code> to <code>NULL</code> to suppress variable pruning, instead of setting it to a value in the interval <code>(0,1)</code>. The principle is: vtreat inflicts the minimal possible alterations on the data, leaving as much as possible to the downstream machine learning code. This does turn out to already be a lot of alteration. Mostly vtreat is taking only steps that are unsafe to leave for later: re-encoding of large categoricals, re-coding of aberrant values, and bulk pruning of variables. However some procedures, in particular principal components analysis or geometric clustering, assume all of the columns have been fully transformed. The usual assumption ("more honored in the breach than the observance") is that the columns are centered (mean zero) and scaled. The non y-aware meaning of "scaled" is unit variance. However, vtreat is designed to emphasize y-aware processing and we feel the y-aware sense of scaling should be: unit slope when regressed against y. If you want standard scaling you can use the standard frame produced by vtreat and scale it yourself. If you want vtreat style y-aware scaling you (which we strongly think is the right thing to do) you can use <code>vtreat::prepare(scale=TRUE)</code> which produces a frame that looks like the following: ```{r printscaled} print(dTrainCTreatedScaled) ``` First we can check the claims. Are the variables mean-zero and slope 1 when regressed against y? ```{r check} slopeFrame <- data.frame(varName = treatmentsC$scoreFrame$varName, stringsAsFactors = FALSE) slopeFrame$mean <- vapply(dTrainCTreatedScaled[, slopeFrame$varName, drop = FALSE], mean, numeric(1)) slopeFrame$slope <- vapply(slopeFrame$varName, function(c) { lm(paste('y', c, sep = '~'), data = dTrainCTreatedScaled)$coefficients[[2]] }, numeric(1)) slopeFrame$sig <- vapply(slopeFrame$varName, function(c) { treatmentsC$scoreFrame[treatmentsC$scoreFrame$varName == c, 'sig'] }, numeric(1)) slopeFrame$badSlope <- ifelse(is.na(slopeFrame$slope), TRUE, abs(slopeFrame$slope - 1) > 1.e-8) print(slopeFrame) ``` The above claims are true with the exception of the derived variable <code>x_lev_x.b</code>. This is because the outcome variable <code>y</code> has identical distribution when the original variable <code>x=='b'</code> and when <code>x!='b'</code> (on half the time in both cases). This means <code>y</code> is perfectly independent of <code>x=='b'</code> and the regression slope must be zero (thus, cannot be 1). vtreat now treats this as needing to scale by a multiplicative factor of zero. Note also that the significance level associated with <code>x_lev_x.b</code> is large, making this variable easy to prune. The <code>varMoves</code> and significance facts in <code>treatmentsC\$scoreFrame</code> are about the un-scaled frame (where <code>x_lev_x.b</code> does in fact move). For a good discussion of the application of *y*-aware scaling to Principal Components Analysis please see [here](https://win-vector.com/2016/05/23/pcr_part2_yaware/). Previous versions of vtreat (0.5.22 and earlier) would copy variables that could not be sensibly scaled into the treated frame unaltered. This was considered the "most faithful" thing to do. However we now feel that this practice was not safe for many downstream procedures, such as principal components analysis and geometric clustering. ### Categorical outcome mode "catScaling=TRUE" As of version `0.5.26` `vtreat` also supports a "scaling mode for categorical outcomes." In this mode scaling is performed using the coefficient of a logistic regression fit on a categorical instead of the coefficient of a linear fit (with the outcome encoded as a zero/one indicator). The idea is with this mode on we are scaling as a logistic regression would- so we are in logistic regression "link space" (where logistic regression assume effects are additive). The mode may be well suited for principal components analysis or principal components regression where the target variable is a categorical (i.e. classification tasks). To ensure this effect we set the argument `catScaling=TRUE` in `vtreat::designTreatmentsC` or `vtreat::mkCrossFrameCExperiment`. WE demonstrate this below. ```{r catscale} treatmentsC2 <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE, catScaling=TRUE, verbose=FALSE) dTrainCTreatedScaled2 <- prepare(treatmentsC2,dTrainC,pruneSig=c(),scale=TRUE) print(dTrainCTreatedScaled2) ``` Notice the new scaled frame is in a different scale than the original scaled frame. It likely is a function of the problem domain which scaling is more appropriate or useful. The new scaled columns are again mean-0 (so they are not exactly the logistic link values, which may not have been so shifted). The new scaled columns do not necessarily have linear model slope 1 as the original scaled columns did as we see below: ```{r checks} colMeans(dTrainCTreatedScaled2) lm(y~x_lev_NA,data=dTrainCTreatedScaled) lm(y~x_lev_NA,data=dTrainCTreatedScaled2) ``` The new scaled columns, however are in good logistic link units. ```{r} vapply(slopeFrame$varName, function(c) { glm(paste('y', c, sep = '~'),family=binomial, data = dTrainCTreatedScaled2)$coefficients[[2]] }, numeric(1)) ``` ### PCA/PCR The intended applications of scale mode include preparing data for metric sensitive applications such as KNN classification/regression and Principal Components Analysis/Regression. Please see [here](https://github.com/WinVector/Examples/tree/master/PCR) for an article series describing such applications. Overall the advice is to first use the following pattern: * Significance prune incoming variables. * Use *y*-aware scaling. * Significance prune resulting latent variables. However, practitioners experienced in principal components analysis may uncomfortable with the range of eigenvalues or singular values returned by *y*-aware analysis. If a more familiar scale is desired we suggest performing the *y*-aware scaling against an additional scaled and centered *y* to try to get ranges closer the traditional unit ranges. This can be achieved as shown below. ```{r} set.seed(235235) dTrainN <- data.frame(x1=rnorm(100), x2=rnorm(100), x3=rnorm(100), stringsAsFactors=FALSE) dTrainN$y <- 1000*(dTrainN$x1 + dTrainN$x2) cEraw <- vtreat::mkCrossFrameNExperiment(dTrainN, c('x1','x2','x3'),'y', scale=TRUE) newvars <- cEraw$treatments$scoreFrame$varName print(newvars) dM1 <- as.matrix(cEraw$crossFrame[, newvars]) pCraw <- stats::prcomp(dM1, scale.=FALSE,center=TRUE) print(pCraw) dTrainN$yScaled <- scale(dTrainN$y,center=TRUE,scale=TRUE) cEscaled <- vtreat::mkCrossFrameNExperiment(dTrainN, c('x1','x2','x3'),'yScaled', scale=TRUE) newvars_s <- cEscaled$treatments$scoreFrame$varName print(newvars_s) dM2 <- as.matrix(cEscaled$crossFrame[, newvars_s]) pCscaled <- stats::prcomp(dM2, scale.=FALSE,center=TRUE) print(pCscaled) ``` Notice the second application of `stats::prcomp` has more standard scaling of the reported standard deviations (though we still do not advise choosing latent variables based on mere comparisons to unit magnitude).
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatScaleMode.Rmd
--- title: "vtreat significance" author: "John Mount, Nina Zumel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat significance} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- `vtreat::prepare` includes a required argument `pruneSig` that (if not NULL) is used to prune variables. Obviously significance depends on training set size (so is not an intrinsic property of just the variables) and there are issues of bias in the estimate (which vtreat attempts to eliminate by estimating significance of complex sub-model variables on cross-validated or out of sample data). As always there is a question of what to set a significance control to. Our advice is the following pragmatic: Use variable filtering on wide datasets (datasets with many columns or variables). Most machine learning algorithms can not defend themselves against large numbers of noise variables (including those algorithms that have cross-validation procedures built in). Examples are given [here](https://win-vector.com/2014/02/01/bad-bayes-an-example-of-why-you-need-hold-out-testing/). As an upper bound think of setting `pruneSig` below _1/numberOfColumns_. Setting `pruneSig` to _1/numberOfColumns_ means that (in expectation) only a constant number of pure noise variables (variables with no actual relation to the outcome we are trying to predict) should create columns. This means (under some assumptions, and in expectation) we expect only a bounded number of noisy columns to be exposed to downstream statistical and machine learning algorithms (which they can presumably handle). As a lower bound think of what sort of good variables get thrown out at a given setting of `pruneSig`. For example suppose our problem is categorization in a data set with _n/2_ positive examples and _n/2_ negative examples. Consider the observed significance of a rare indicator variable that is on _k_ times in training and is only on for positive instances. A random variable that is on _k_ times would achieve this purity with probability $2^{-k}$, so we expect it to have a _-log(significance)_ in the ballpark of _k_. So a `pruneSig` of $2^{-k}$ will filter all such variables out (be they good or bad). Thus if you want levels or indicators that are on only a _z_ fraction of the time on a training set of size _n_ you want `pruneSig` >> $2^{-z*n}$. Example: ```{r} signk <- function(n,k) { sigTab <- data.frame(y=c(rep(TRUE,n/2),rep(FALSE,n/2)),v=FALSE) sigTab[seq_len(k),'v'] <- TRUE vtreat::designTreatmentsC(sigTab,'v','y',TRUE,verbose=FALSE)$scoreFrame[1,'sig'] } sigTab <- data.frame(k=c(1,2,3,4,5,10,20,50,100)) # If you want to see a rare but perfect indicator of positive class # that's only on k times out of 1000, this is the lower bound on pruneSig sigTab$sigEst = vapply(sigTab$k,function(k) signk(1000,k),numeric(1)) sigTab$minusLogSig = -log(sigTab$sigEst) # we expect this to be approximately k print(sigTab) ``` For a data set with 100 variables (and 1000 rows), you might want to set `pruneSig` <= 0.01 to limit the number of pure noise variables that enter the model. Note that this value is smaller than the lower bounds given above for $k < 5$. This means that in a data set of this width and length, you may not be able to detect rare but perfect indicators that occur fewer than 5 times. You would have a chance of using such rare indicators in a _catN_ or _catB_ effects coded variable. Below we design a data frame with a perfect categorical variable (completely determines the outcome y) where each level occurs exactly 2 times. The individual levels are insignificant, but we can still extract a significant _catB_ effect coded variable. ```{r} set.seed(3346) n <- 1000 k <- 4 d <- data.frame(y=rbinom(n,size=1,prob=0.5)>0) d$catVarNoise <- rep(paste0('lev',sprintf("%03d",1:floor(n/k))),(k+1))[1:n] d$catVarPerfect <- paste0(d$catVar,substr(as.character(d$y),1,1)) d <- d[order(d$catVarPerfect),] head(d) treatmentsC <- vtreat::designTreatmentsC(d,c('catVarNoise','catVarPerfect'),'y',TRUE) # Estimate effect significance (not coefficient significance). estSigGLM <- function(xVar,yVar,numberOfHiddenDegrees=0) { d <- data.frame(x=xVar,y=yVar,stringsAsFactors = FALSE) model <- stats::glm(stats::as.formula('y~x'), data=d, family=stats::binomial(link='logit')) delta_deviance <- model$null.deviance - model$deviance delta_df <- model$df.null - model$df.residual + numberOfHiddenDegrees pRsq <- 1.0 - model$deviance/model$null.deviance sig <- stats::pchisq(delta_deviance, delta_df, lower.tail=FALSE) sig } prepD <- vtreat::prepare(treatmentsC,d,pruneSig=c()) ``` vtreat produces good variable significances using out of sample simulation (cross frames). ```{r scoreframe} print(treatmentsC$scoreFrame[,c('varName','rsq','sig','extraModelDegrees')]) ``` For categorical targets we have in the `scoreFrame` the `sig` column is the significance of the single variable logistic regression using the named variable (plus a constant term), and the `rsq` column is the "pseudo-r-squared" or portion of deviance explained (please see [here](https://win-vector.com/2011/09/14/the-simpler-derivation-of-logistic-regression/) for some notes). For numeric targets the `sig` column is the significance of the single variable linear regression using the named variable (plus a constant term), and the `rsq` column is the "r-squared" or portion of variance explained (please see [here](https://win-vector.com/2011/11/21/correlation-and-r-squared/)) for some notes). Signal carrying complex variables can score as significant, even those composed of rare levels. ```{r scoresignal} summary(glm(y~d$catVarPerfect=='lev001T',data=d,family=binomial)) estSigGLM(prepD$catVarPerfect_catB,prepD$y,0) # wrong est estSigGLM(prepD$catVarPerfect_catB,prepD$y, numberOfHiddenDegrees=length(unique(d$catVarPerfect))-1) ``` Noise variables (those without a relation to outcome) are also scored correctly as long was we account for the degrees of freedom. ```{r scorenoise} summary(glm(y~d$catVarNoise=='lev001',data=d,family=binomial)) estSigGLM(prepD$catVarNoise_catB,prepD$y,0) # wrong est estSigGLM(prepD$catVarNoise_catB,prepD$y, numberOfHiddenDegrees=length(unique(d$catVarNoise))-1) ```
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatSignificance.Rmd
--- title: "vtreat data splitting" author: "John Mount, Nina Zumel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vtreat data splitting} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(fig.width = 7) ``` ## vtreat data set splitting ### Motivation [`vtreat`](https://github.com/WinVector/vtreat) supplies a number of data set splitting or cross-validation planning facilities. Some services are implicit such as the simulated out of sample scoring of high degree of freedom derived variables (such as `catB`, `catN`,`catD`, and `catP`; see [here](https://winvector.github.io/vtreathtml/vtreatVariableTypes.html) for a list of variable types). Some services are explicit such as `vtreat::mkCrossFrameCExperiment` and `vtreat::mkCrossFrameNExperiment` (please see [here](https://winvector.github.io/vtreathtml/vtreatCrossFrames.html)). And there is even a user-facing cross-validation planner in `vtreat::buildEvalSets` (try `help(buildEvalSets)` for details). We (Nina Zumel and John Mount) have written a lot on structured cross-validation; the most relevant article being [Random Test/Train Split is not Always Enough](https://win-vector.com/2015/01/05/random-testtrain-split-is-not-always-enough/). The point is that in retrospective studies random test/train split is *at best* a simulation of how a model will be applied in the future. It is not an actual experimental design as in a [randomized control trial](https://en.wikipedia.org/wiki/Randomized_controlled_trial). To be an effective simulation you must work to preserve structure that will be true in future application. The overall idea is: a better splitting plan helps build a model that actually performs better in practice. And porting such a splitting plan back to your evaluation procedures gives you a better estimate of this future model performance. A random test/train split attempts to preserve the following: * Future application data is exchangeable with training data (prior to model construction). * Future application data remains exchangeable with test data (even after model construction, as test data is not used in model construction). Note if there is a concept change (also called issues of non-stationarity) then future data is already not statistically exchangeable with training data (so can't preserve a property you never had). However even if your future data starts exchangeable with training data there is at least one (often) un-modeled difference between training data and future application data: * Future application data tends to be formed after (or in the future of) training data. This is usually an unstated structure of your problem solving plan: use annotated data from the past to build a supervised model for future un-annotated data. ### Examples With the above discussion under our belt we get back to the problem at hand. When creating an appropriate test/train split, we may have to consider one or more of the following: * **Stratification:** Stratification preserves the distribution or prevalence of the outcome variable (or any other variable, but vtreat only stratifies on _y_). For example, for a classification problem with a target class prevalence of 15%, stratifying on _y_ insures that both the training and test sets have target class prevalence of precisely 15% (or as close to that as is possible), not just "around" 15%, as would happen with a simple randomized test/train split. This is especially important for modeling rare events. * **Grouping:** By "grouping" we mean not splitting closely related events into test and train: if a set of rows constitutes a "group," then we want all those rows to go either into test or into train -- as a group. Typical examples are multiple events from a single customer (as you really want your model to predict behavior of new customers) or records close together in time (as latter application records will not be close in time to original training records). * **Structured back testing:** Structured back testing preserves the order of time ordered events. In finance it is considered ridiculous to use data from a Monday and a Wednesday to build a model for prices on the intervening Tuesday -- but this is the kind of thing that can happen if the training and evaluation data are partitioned using a simple random split. Our goal is for `vtreat` to be a domain agnostic, `y`-aware data conditioner. So `vtreat` should _y_-stratify its data splits throughout. Prior to version `0.5.26` `vtreat` used simple random splits. Now with version `0.5.26` (currently available from [Github](https://github.com/WinVector/vtreat)) `vtreat` defaults to stratified sampling throughout. Respecting things like locality of record grouping or ordering of time are domain issues and should be handled by the analyst. Any splitting or stratification plan requires domain knowledge and should represent domain sensitive trade-off between the competing goals of: * Having a random split. * Stability of distribution of outcome variable across splits. * Not cutting into "atomic" groups of records. * Not using data from the future to predict the past. * Having a lot of data in each split. * Having disjoint training and testing data. As of version `0.5.26` `vtreat` supports this by allowing a user specified data splitting function where the analyst can encode their desired domain invariants. The user-implemented splitting function should have the signature `function(nRows,nSplits,dframe,y)` where * `nRows` is the number of rows you are trying to split * `nSplits` is the number of split groups you want * `dframe` is the original data frame (which may contain grouping or order columns that you want), * `y` is the outcome variable converted to numeric The function should return a list of lists. The *i*th element should have slots `train` and `app`, where `[[i]]$train` designates the training data used to fit the model that evaluates the data designated by `[[i]]$app`. This is easiest to show through an example: ```{r} vtreat::kWayStratifiedY(3,2,NULL,NULL) ``` As we can see `vtreat::oneWayHoldout` builds three split sets where in each set the "application data rows" is a single row index and the corresponding training rows are the complementary row indexes. This is a leave-one-out [cross validation plan](https://en.wikipedia.org/wiki/Cross-validation_(statistics)). `vtreat` supplies a number of cross validation split/plan implementations: * `kWayStratifiedY`: k-way y-stratified cross-validation. This is the `vtreat` default splitting plan. * `makekWayCrossValidationGroupedByColumn`: k-way y-stratified cross-validation that preserves grouping (for example, all rows corresponding to a single customer or patient, etc). This is a complex splitting plan, and only recommended when absolutely needed. * `kWayCrossValidation`: k-way un-stratified cross-validation * `oneWayHoldout`: jackknife, or leave-one-out cross-validation. Note one way hold out can leak target expectations, so is not preferred for nested model situations. The function `buildEvalSets` takes one of the above splitting functions as input and returns a cross-validation plan that instantiates the desired splitting, while also guarding against corner cases. You can also explicitly specify the splitting plan when designing a vtreat variable treatment plan using `designTreatments[N\C]` or `mkCrossFrame[N\C]Experiment`. For issues beyond stratification the user may want to supply their own splitting plan. Such a function can then be passed into any `vtreat` operation that takes a `splitFunction` argument (such as `mkCrossFrameNExperiment`, `designTreatmentsN`, and many more). For example we can pass a user defined `splitFn` into `vtreat::buildEvalSets` as follows: For example to use a user supplied splitting function we would write the following function definition. ```{r} # This method is not a great idea as the data could have structure that strides # in the same pattern as this split. # Such technically is possible for any split, but we typically use # pseudo-random structure (that is not the same across many potential # split calls) to try and make it unlikely such structures # match often. modularSplit <- function(nRows,nSplits,dframe,y) { group <- seq_len(nRows) %% nSplits lapply(unique(group), function(gi) { list(train=which(group!=gi), app=which(group==gi)) }) } ``` This function can then be passed into any `vtreat` operation that takes a `splitFunction` argument (such as `mkCrossFrameNExperiment`, `designTreatmentsN`, and many more). For example we can pass the user defined `splitFn` into `vtreat::buildEvalSets` as follows: ```{r} vtreat::buildEvalSets(nRows=25,nSplits=3,splitFunction=modularSplit) ``` As stated above, the vtreat library code will try to use the user function for splitting, but will fall back to an appropriate vtreat function in corner cases that the user function may not handle (for example, too few rows, too few groups, and so on). Thus the user code can assume it is in a reasonable situation (and even safely return NULL if it can’t deal with the situation it is given). For example the following bad user split is detected and corrected: ```{r} badSplit <- function(nRows,nSplits,dframe,y) { list(list(train=seq_len(nRows),app=seq_len(nRows))) } vtreat::buildEvalSets(nRows=5,nSplits=3,splitFunction=badSplit) ``` Notice above the returned split does not meet all of the original desiderata, but is guaranteed to be a useful data partition. ### Implementations The file [outOfSample.R](https://github.com/WinVector/vtreat/blob/master/R/outOfSample.R) contains worked examples. In particular we would suggest running the code displayed when you type any of: * `help(kWayCrossValidation)` * `help(kWayStratifiedY)` * `help(makekWayCrossValidationGroupedByColumn)` * `help(oneWayHoldout)` For example from `help(kWayStratifiedY)` we can see that the distribution of `y` is much more similar in each fold when we stratify than when we don't: ```{r warning=FALSE} library('vtreat') ``` ```{r} set.seed(23255) d <- data.frame(y=sin(1:100)) # stratified 5-fold cross validation pStrat <- kWayStratifiedY(nrow(d),5,d,d$y) # check if the split is a good partition check = vtreat::problemAppPlan(nrow(d),5,pStrat,TRUE) if(is.null(check)) { print("Plan is good") } else { print(paste0("Problem with plan: ", check)) } d$stratGroup <- vtreat::getSplitPlanAppLabels(nrow(d),pStrat) # unstratified 5-fold cross validation pSimple <- kWayCrossValidation(nrow(d),5,d,d$y) # check if the split is a good partition; return null if so check = vtreat::problemAppPlan(nrow(d),5,pSimple,TRUE) if(is.null(check)) { print("Plan is good") } else { print(paste0("Problem with plan: ", check)) } d$simpleGroup <- vtreat::getSplitPlanAppLabels(nrow(d),pSimple) # mean(y) for each fold, unstratified tapply(d$y,d$simpleGroup,mean) # standard error of mean(y) sd(tapply(d$y,d$simpleGroup,mean)) # mean(y) for each fold, unstratified tapply(d$y,d$stratGroup,mean) # standard error of mean(y) sd(tapply(d$y,d$stratGroup,mean)) ``` Notice the increased similarity if distributions. ## Conclusion Controlling the way data is split in cross-validation -- preserving y-distribution, groups, and even ordering -- can improve the real world performance of models trained on such data. Obviously this adds some complexity and "places to go wrong", but it is a topic worth learning about.
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatSplitting.Rmd
--- title: "Variable Types" author: "Win-Vector LLC" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Variable Types} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- 'vtreat' is a package that prepares arbitrary data frames into clean data frames that are ready for analysis (usually supervised learning). A clean data frame: - Only has numeric columns (other than the outcome). - Has no Infinite/NA/NaN values in the effective variable columns. To effect this encoding 'vtreat' replaces original variables or columns with new derived variables. In this note we will use variables and columns as interchangeable concepts. This note describes the current family of 'vtreat' derived variable types. 'vtreat' usage splits into three main cases: * When the target to predict is categorical. * When the target to predict is numeric. * When there is no supplied target to predict. In all cases vtreat variable names are built by appending a notation onto the original user supplied column name. In all cases the easiest way to examine the derived variables is to look at the `scoreFrame` component of the returned treatment plan. We will outline each of these situations below: ## When the target to predict is categorical An example categorical variable treatment is demonstrated below: ```{r categoricalexample, tidy=FALSE} library(vtreat) dTrainC <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE), stringsAsFactors = FALSE) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE) scoreColsToPrint <- c('origName','varName','code','rsq','sig','extraModelDegrees') print(treatmentsC$scoreFrame[,scoreColsToPrint]) ``` For each user supplied variable or column (in this case `x` and `z`) 'vtreat' proposes derived or treated variables. The mapping from original variable name to derived variable name is given by comparing the columns `origName` and `varName`. One can map facts about the new variables back to the original variables as follows: ```{r map} # Build a map from vtreat names back to reasonable display names vmap <- as.list(treatmentsC$scoreFrame$origName) names(vmap) <- treatmentsC$scoreFrame$varName print(vmap['x_catB']) # Map significances back to original variables aggregate(sig~origName,data=treatmentsC$scoreFrame,FUN=min) ``` In the `scoreFrame` the `sig` column is the significance of the single variable logistic regression using the named variable (plus a constant term), and the `rsq` column is the "pseudo-r-squared" or portion of deviance explained (please see [here](https://win-vector.com/2011/09/14/the-simpler-derivation-of-logistic-regression/) for some notes). Essentially a derived variable name is built by concatenating an original variable name and a treatment type (also recorded in the `code` column for convenience). The codes give the different 'vtreat' variable types (or really meanings, as all derived variables are numeric). For categorical targets the possible variable types are as follows: * **clean** : a numeric variable passed through with all NA/NaN/infinite values replaced with either zero or mean value of the non-NA/NaN/infinite examples of the variable. * **is\_Bad** : a companion to the 'clean' treatment. 'is\_Bad' is an indicator that indicates a value replacement has occurred. For many noisy datasets this column can be more informative than the clean column! * **lev** : a 0/1 indicator indicating a particular value of a categorical variable was present. For example `x_lev_x.a` is 1 when the original `x` variable had a value of "a". These indicators are essentially variables representing explicit encoding of levels as dummy variables. In some cases a special level code is used to represent pooled rare values. * **cat\_B** : a single variable Bayesian model of the change in logit-odds in outcome from mean distribution conditioned on the observed value of the original variable. In our example: `x_catB = logit(P[y==target|x]) - logit(P[y==target])`. This encoding is especially useful for categorical variables that have a large number of levels, but be aware it can obscure degrees of freedom if not used properly. * **cat\_P** : a "prevalence fact" about a categorical level. Tells us if the original level was rare or common. Probably not good for direct use in a model, but possibly useful for meta-analysis on the variable. ## When the target to predict is numeric An example numeric variable treatment is demonstrated below: ```{r numericexample, tidy=FALSE} library(vtreat) dTrainN <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=as.numeric(c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)), stringsAsFactors = FALSE) treatmentsN <- designTreatmentsN(dTrainN,colnames(dTrainN),'y') print(treatmentsN$scoreFrame[,scoreColsToPrint]) ``` The treatment of numeric targets is similar to that of categorical targets. In the numeric case the possible derived variable types are: * **clean** : a numeric variable passed through with all NA/NaN/infinite values replaced with either zero or mean value of the non-NA/NaN/infinite examples of the variable. * **is\_Bad** : a companion to the 'clean' treatment. 'is\_Bad' is an indicator that indicates a value replacement has occurred. For many noisy datasets this column can be more informative than the clean column! * **lev** : a 0/1 indicator indicating a particular value of a categorical variable was present. For example `x_lev_x.a` is 1 when the original `x` variable had a value of "a". These indicators are essentially variables representing explicit encoding of levels as dummy variables. In some cases a special level code is used to represent pooled rare values. * **cat\_N** : a single variable regression model of the difference in outcome expectation conditioned on the observed value of the original variable. In our example: `x_catN = E[y|x] - E[y]`. This encoding is especially useful for categorical variables that have a large number of levels, but be aware it can obscure degrees of freedom if not used properly. * **cat\_P** : a "prevalence fact" about a categorical level. Tells us if the original level was rare or common. Tells us if the original level was rare or common. Probably not good for direct use in a model, but possibly useful for met-analysis on the variable. * **cat\_D** : a "deviation fact" about a categorical level tells us if 'y' is concentrated or diffuse when conditioned on the observed level of the original categorical variable. Probably not good for direct use in a model, but possibly useful for meta-analysis on the variable. Note: for categorical targets we don't need `cat\_D` variables as this information is already encoded in `cat\_B` variables. In the `scoreFrame` the `sig` column is the significance of the single variable linear regression using the named variable (plus a constant term), and the `rsq` column is the "r-squared" or portion of variance explained (please see [here](https://win-vector.com/2011/11/21/correlation-and-r-squared/)) for some notes). ## When there is no supplied target to predict An example "no target" variable treatment is demonstrated below: ```{r notargetexample, tidy=FALSE} library(vtreat) dTrainZ <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6), stringsAsFactors = FALSE) treatmentsZ <- designTreatmentsZ(dTrainZ,colnames(dTrainZ)) print(treatmentsZ$scoreFrame[, c('origName','varName','code','extraModelDegrees')]) ``` Note: because there is no user supplied target the `scoreFrame` significance columns are not meaningful, and are populated only for regularity of code interface. Also indicator variables are only formed by `designTreatmentsZ` for `vtreat` 0.5.28 or newer. Beyond that the no-target treatments are similar to the earlier treatments. Possible derived variable types in this case are: * **clean** : a numeric variable passed through with all NA/NaN/infinite values replaced with either zero or mean value of the non-NA/NaN/infinite examples of the variable. * **is\_Bad** : a companion to the 'clean' treatment. 'is\_Bad' is an indicator that indicates a value replacement has occurred. For many noisy datasets this column can be more informative than the clean column! * **lev** : a 0/1 indicator indicating a particular value of a categorical variable was present. For example `x_lev_x.a` is 1 when the original `x` variable had a value of "a". These indicators are essentially variables representing explicit encoding of levels as dummy variables. In some cases a special level code is used to represent pooled rare values. * **cat\_P** : a "prevalence fact" about a categorical level. Tells us if the original level was rare or common. Probably not good for direct use in a model, but possibly useful for meta-analysis on the variable. ## Restricting to Specific Variable Types Both `designTreatmentsX` and `prepare` functions take an argument called `codeRestriction` that restricts the type of variable that is created. For example, you may not want to create `catP` and `catD` variables for a regression problem. ```{r restrict1} dTrainN <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=as.numeric(c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)), stringsAsFactors = FALSE) treatmentsN <- designTreatmentsN(dTrainN,colnames(dTrainN),'y', codeRestriction = c('lev', 'catN', 'clean', 'isBAD'), verbose=FALSE) # no catP or catD variables print(treatmentsN$scoreFrame[,scoreColsToPrint]) ``` Conversely, even if you have created a treatment plan for a particular type of variable, you may subsequently decide not to use it. For example, perhaps you only want to use indicator variables and not the `catN` variable for modeling. You can use `codeRestriction` in `prepare()`. ```{r restrict2} dTreated = prepare(treatmentsN, dTrainN, codeRestriction = c('lev','clean', 'isBAD')) # no catN variables head(dTreated) ``` `varRestriction` works similarly, only you must list the explicit variables to use. See the example below. ## Overall Variables that "do not move" (don't take on at least two values during treatment design) or don't achieve at least a minimal significance are suppressed. The `catB`/`catN` variables are essentially single variable models and are very useful for re-encoding categorical variables that take on a very large number of values (such as zip-codes). The intended use of 'vtreat' is as follows: * Data is split into three non-overlapping portions * One portion is used to "design treatments" (we sometime informally call this calibration). * Another portion is used to train a model. * The remaining portion is used to evaluate the model. 'vtreat' attempts to compute "out of sample" significances for each variable effect ( the `sig` column in `scoreFrame`) through cross-validation techniques. 'vtreat' is primarily intended to be "y-aware" processing. Of particular interest is using `vtreat::prepare()` with `scale=TRUE` which tries to put most columns in 'y-effect' units. This can be an important pre-processing step before attempting dimension reduction (such as principal components methods). The vtreat user should pick which sorts of variables they are want and also filter on estimated significance. Doing this looks like the following: ```{r selectvars} dTrainN <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=as.numeric(c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)), stringsAsFactors = FALSE) treatmentsN <- designTreatmentsN(dTrainN,colnames(dTrainN),'y', codeRestriction = c('lev', 'catN', 'clean', 'isBAD'), verbose=FALSE) print(treatmentsN$scoreFrame[,scoreColsToPrint]) pruneSig <- 1.0 # don't filter on significance for this tiny example vScoreFrame <- treatmentsN$scoreFrame varsToUse <- vScoreFrame$varName[(vScoreFrame$sig<=pruneSig)] print(varsToUse) origVarNames <- sort(unique(vScoreFrame$origName[vScoreFrame$varName %in% varsToUse])) print(origVarNames) # prepare a treated data frame using only the "significant" variables dTreated = prepare(treatmentsN, dTrainN, varRestriction = varsToUse) head(dTreated) ``` We strongly suggest using the standard variables coded as 'lev', 'clean', and 'isBad'; and the "y aware" variables coded as 'catN' and 'catB'. The non sub-model variables ('catP' and 'catD') can be useful (possibly as interactions or guards on the corresponding 'catN' and 'catB' variables) but also encode distributional facts about the data that may or may not be appropriate depending on your problem domain. When displaying variables to end users we suggest using the original names and the min significance seen on any derived variable: ```{r displayvars} origVarNames <- sort(unique(vScoreFrame$origName[vScoreFrame$varName %in% varsToUse])) print(origVarNames) origVarSigs <- vScoreFrame[vScoreFrame$varName %in% varsToUse,] aggregate(sig~origName,data=origVarSigs,FUN=min) ``` ## Links * ['vtreat' on Github'](https://github.com/WinVector/vtreat) * ['vtreat' on CRAN](https://cran.r-project.org/package=vtreat)
/scratch/gouwar.j/cran-all/cranData/vtreat/vignettes/vtreatVariableTypes.Rmd
#' @title Format an indicator-based pattern table #' #' @author Nick Barrowman #' #' @description #' Given a pattern table produced by \code{vtree} for indicator (i.e 0/1) variables, #' \code{VennTable} returns an augmented table. #' The augmented table includes an extra row with the total for each indicator variable #' and an extra row with the corresponding percentage #' (which will not in general add to 100\%). #' Also, optionally, does some additional formatting for pandoc markdown. #' #' @param x Required: Pattern table produced by \code{vtree} for indicator (i.e 0/1) variables #' @param markdown Format nicely for markdown (see Details). #' @param NAcode Code to use to represent NAs in markdown formatting #' @param checked Vector of character strings that represent checked values; #' by default: \code{c("1","TRUE","Yes","yes","N/A")} #' @param unchecked Vector of character strings that represent unchecked values; #' by default: \code{c("0","FALSE","No","no","not N/A")} #' @param sort Sort variables by frequency? #' #' @details #' The column totals ignore missing values. #' #' When \code{markdown=TRUE}, the row and column headings for percentages are #' labeled "\%", indicator values equal to 1 are replaced by checkmark codes, #' indicator values equal to 0 are replaced by spaces, and missing indicator #' values are replaced by dashes. Empty headings are replaced by spaces. #' Finally the table is transposed. #' #' @examples #' # Generate a pattern table for the indicator variables Ind1 and Ind2 #' ptab <- vtree(FakeData,"Ind1 Ind2",ptable=TRUE) #' # Augment the table #' ptab2 <- VennTable(ptab) #' # Print the result without quotation marks (which are distracting) #' print(ptab2,quote=FALSE) #' # Generate a table with pandoc markdown formatting #' ptab3 <- VennTable(ptab,markdown=TRUE) #' #' @return #' Returns a character matrix with extra rows containing indicator sums. #' #' @export #' VennTable <- function(x,markdown=FALSE,NAcode="-", unchecked=c("0","FALSE","No","no","not N/A"),checked=c("1","TRUE","Yes","yes","N/A"), sort=TRUE) { TotalSampleSize <- sum(x$n) # {m}ark{d}own {t}able function mdt <- function(x) { cn <- colnames(x) cn[cn==""] <- "&nbsp;" rn <- rownames(x) rn[rn==""] <- "&nbsp;" x <- cbind(rn,x) header <- paste0(cn,collapse="|") dashes <- paste0(rep("-",length(cn)+1),collapse="|") x[x==""] <- "&nbsp;" body <- paste0(apply(x,1,paste0,collapse="|"),collapse="\n") paste0("&nbsp;|",header,"\n",dashes,"\n",body,collapse="\n") } mat <- as.matrix(x[,-c(1,2),drop=FALSE]) # Convert logical values to 0's and 1's mat[mat %in% unchecked] <- "0" mat[mat %in% checked] <- "1" mode(mat) <- "numeric" mat <- mat*x$n # Note that this relies on column recycling countByVar <- apply(mat,2,sum,na.rm=TRUE) if (sort) { o <- rev(order(countByVar)) mat <- mat[,o,drop=FALSE] countByVar <- countByVar[o] } varsorted_mat <- as.matrix(cbind(x[,c(1,2),drop=FALSE],mat)) mode(mat) <- "character" if (markdown) { varsorted_mat[,-(1:2)][is.na(varsorted_mat[,-(1:2)])] <- NAcode varsorted_mat[,-(1:2)][varsorted_mat[,-(1:2)]=="0"] <- "" varsorted_mat[,-(1:2)][ varsorted_mat[,-(1:2)]!="" & varsorted_mat[,-(1:2)]!=NAcode] <- "&#10004;" } #browser() xmat <- rbind(varsorted_mat,c(TotalSampleSize,100,rep("",ncol(mat)))) xmat <- rbind(xmat,c("","",countByVar)) xmat <- rbind(xmat,c("","",round(100*countByVar/sum(x[,1])))) rownames(xmat) <- c(rep("",nrow(x)),"Total","N","pct") if (markdown) { colnames(xmat)[colnames(xmat)=="pct"] <- "%" rownames(xmat)[rownames(xmat)=="pct"] <- "%" rownames(xmat)[rownames(xmat)==""] <- "&nbsp;" xmat <- t(xmat) mdt(xmat) } else { xmat } }
/scratch/gouwar.j/cran-all/cranData/vtree/R/VennTable.R
around <- function (x, digits = 2, thousands = "",tooLong = 12) { if (is.character(x)) { x } else if (is.integer(x) || is.factor(x)) { as.character(x) } else if (is.data.frame(x)) { for (i in seq_len(ncol(x))) { x[[i]] <- around(x[[i]], digits = digits) } x } else if (!is.numeric(x)) { if (all(is.na(x))) { rep("NA",length(x)) } else { x } } else { if (digits == 0) { result <- formatC(x, digits = digits, drop0trailing = TRUE, big.mark = thousands, format = "f", flag = "#") result[nchar(result) > tooLong] <- formatC(x[nchar(result) > tooLong], digits = digits, drop0trailing = TRUE, big.mark = thousands, format = "g", flag = "#") } else { result <- formatC(x, digits = digits, drop0trailing = FALSE, big.mark = thousands, format = "f", flag = "#") result[nchar(result) > tooLong] <- formatC(x[nchar(result) > tooLong], digits = digits, drop0trailing = FALSE, big.mark = thousands, format = "g", flag = "#") } #browser() result[result == "-0"] <- "0" result[result == "-0.0"] <- "0.0" result[result == "-0.00"] <- "0.00" result[result == "-0.000"] <- "0.000" result } }
/scratch/gouwar.j/cran-all/cranData/vtree/R/around.R
#' #' @title Build a data frame to display with vtree #' #' @description #' Build a data frame by specifying variable names and patterns of values together with frequencies. #' #' @author Nick Barrowman <[email protected]> #' #' @param varnames A vector of variable names. #' @param ... Lists of patterns and the frequency of each pattern. #' When a pattern is shorter than the list of variable names #' (for example, 3 variable names but only 2 values in the pattern), #' \code{NA}'s are substituted for the missing variable names. #' #' @details #' Suppose \code{varnames=c("animal","size","hair")}, #' then one pattern would be \code{list("dog","small","short",4)}, #' which specifies 4 dogs that are small and short-haired. #' Another pattern could be \code{list("cat","large","long",101)}, #' specifying 101 large cats. #' #' @return A data frame. #' #' @examples #' # Number of countries in Africa, whether population is over 30 million or not, #' # and whether landlocked or not. #' # https://www.worldometers.info/geography/how-many-countries-in-africa/ #' # #' df <- build.data.frame( #' c("continent","population","landlocked"), #' list("Africa","Over 30 million","landlocked",2), #' list("Africa","Over 30 million","not landlocked",12), #' list("Africa","Under 30 million","landlocked",14), #' list("Africa","Under 30 million","not landlocked",26)) #' #' @export #' build.data.frame <- function(varnames,...) { input <- list(...) nvar <- length(varnames) count <- NULL for (i in seq_len(length(input))) { m <- length(input[[i]]) if ((m-1)!=nvar) stop(paste0( "There are ",nvar," variable names, so each list should have ", nvar+1," elements (",nvar," values followed by a count).")) count <- c(count,input[[i]][[m]]) } listit <- vector("list",length=length(input[[1]])-1) names(listit) <- varnames for (i in seq_len(length(input))) { for (j in 1:(length(input[[i]])-1)) { listit[[j]] <- c(listit[[j]],rep(input[[i]][[j]],count[i])) } if ( (length(input[[i]])-1) < nvar) { for (j in (length(input[[i]]):nvar)) { listit[[j]] <- c(listit[[j]],rep(NA,count[i])) } } } as.data.frame(listit) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/build.data.frame.R
buildCanopy <- function(z,root=TRUE,novars=FALSE,title="",parent=1,last=1,labels=NULL,tlabelnode=NULL,HTMLtext=FALSE, var, check.is.na=FALSE, labelvar=NULL, varminwidth=NULL,varminheight=NULL,varlabelloc=NULL, showvarinnode=FALSE,shownodelabels=TRUE,sameline=FALSE, prune=NULL, tprune=NULL, prunelone=NULL,prunesmaller=NULL,prunebigger=NULL, keep=NULL,tkeep=NULL, text=NULL,ttext=NULL,TopText="",showempty=FALSE,digits=0,cdigits=2, showpct=TRUE, showrootcount=FALSE, showcount=TRUE, prefixcount="", showvarnames=FALSE, pruneNA=FALSE, splitwidth=Inf,topcolor="black",color="blue",topfillcolor="olivedrab3", fillcolor="olivedrab2",vp=TRUE,rounded=FALSE,just="c",justtext=NULL,thousands="", showroot=TRUE,verbose=FALSE,sortfill=FALSE) { # # Write DOT code for a single-level {flow}chart of {cat}egories using the # DiagrammeR framework. # # https://en.wikipedia.org/wiki/DOT_(graph_description_language) # if (HTMLtext) { sepN <- "<BR/>" } else { sepN <- "\n" } if (is.na(shownodelabels)) shownodelabels <- TRUE if (is.logical(z)) { z <- factor(z, c("FALSE", "TRUE")) } categoryCounts <- table(z,exclude=NULL) names(categoryCounts)[is.na(names(categoryCounts))] <- "NA" sampleSize <- sum(categoryCounts[names(categoryCounts)!="NA"]) #browser() if (is.null(prunesmaller)) { numsmallernodes <- 0 sumsmallernodes <- 0 } else { if (vp) { selectcount <- categoryCounts>=prunesmaller | names(categoryCounts)=="NA" } else { selectcount <- categoryCounts>=prunesmaller } #browser() numsmallernodes <- sum(!selectcount & categoryCounts>0) sumsmallernodes <- sum(categoryCounts[!selectcount]) categoryCounts <- categoryCounts[selectcount] } if (is.null(prunebigger)) { numbiggernodes <- 0 sumbiggernodes <- 0 } else { if (vp) { selectcount <- categoryCounts<=prunebigger | names(categoryCounts)=="NA" } else { selectcount <- categoryCounts<=prunebigger } numbiggernodes <- sum(!selectcount & categoryCounts>0) sumbiggernodes <- sum(categoryCounts[!selectcount]) categoryCounts <- categoryCounts[selectcount] } if (length(categoryCounts)==0) { return(list( root=root, value="", n=NULL, pct=NULL, npctString=NULL, extraText="", levels="", nodenum=parent, edges="", labelassign="", lastnode=parent, numsmallernodes=numsmallernodes, sumsmallernodes=sumsmallernodes, numbiggernodes=numbiggernodes, sumbiggernodes=sumbiggernodes)) } # Pre-pend the parent node categoryCounts <- c(length(z),categoryCounts) names(categoryCounts)[1] <- title if (novars) { showcount <- TRUE } if (vp & any(names(categoryCounts)=="NA")) { cc <- categoryCounts[-1] if (length(cc)>0) { npctString <- rep("",length(cc)) nString <- cc if (showcount) { for (i in 1:length(cc)) { npctString[i] <- format(cc[i],big.mark=thousands) } npctString <- paste0(prefixcount,npctString) #if (showpct) npctString <- paste0(npctString," ") } pctString <- ifelse(names(cc)=="NA","",around(100*cc/sampleSize,digits)) if (showpct) { npctString <- ifelse(names(cc)=="NA",npctString,paste0(npctString," (",pctString,"%)")) } } else { npctString <- NULL nString <- NULL pctString <- NULL } } else { npctString <- rep("",length(categoryCounts[-1])) nString <- categoryCounts[-1] if (showcount) { numbers <- categoryCounts[-1] for (i in 1:length(numbers)) { npctString[i] <- format(numbers[i],big.mark=thousands) } npctString <- paste0(prefixcount,npctString) } pctString <- around(100*categoryCounts[-1]/length(z),digits) if (showpct) { npctString <- paste0(npctString," (",pctString,"%)") } } npctString <- c(format(length(z),big.mark=thousands),npctString) nString <- c(length(z),nString) pctString <- c("",pctString) if (!showempty) { s <- categoryCounts>0 categoryCounts <- categoryCounts[s] npctString <- npctString[s] } if (length(tprune)>0) { for (j in seq_len(length(tprune))) { if (length(tprune[[j]])==1 && any(names(tprune[[j]])==var)) { tpruneLevel <- names(categoryCounts[-1]) %in% unlist(tprune[[j]][names(tprune[[j]])==var]) categoryCounts <- c(categoryCounts[1],categoryCounts[-1][!tpruneLevel]) npctString <- c(npctString[1],npctString[-1][!tpruneLevel]) pctString <- c(pctString[1],pctString[-1][!tpruneLevel]) nString <- c(nString[1],nString[-1][!tpruneLevel]) } } } if (length(tkeep)>0) { for (j in seq_len(length(tkeep))) { if (length(tkeep[[j]])==1 && any(names(tkeep[[j]])==var)) { matching <- match(unlist(tkeep[[j]][names(tkeep[[j]])==var]),names(categoryCounts)[-1]) matching <- matching[!is.na(matching)] removed <- categoryCounts[-1][-matching] npctremoved <- npctString[-1][-matching] if (!vp) { if (any(names(removed)=="NA")) { NAremoved <- names(removed)=="NA" nr <- npctremoved[NAremoved] #if (nr>1) description <- "NAs" else description <- "NA" #warning(paste0(var,": keep removed ",npctremoved[NAremoved]," ",description),call.=FALSE) } } else { newkeep <- c(names(categoryCounts[-1])[matching],"NA") matching <- match(newkeep,names(categoryCounts)[-1]) matching <- matching[!is.na(matching)] } #browser() categoryCounts <- c(categoryCounts[1],categoryCounts[-1][matching]) npctString <- c(npctString[1],npctString[-1][matching]) pctString <- c(pctString[1],pctString[-1][matching]) nString <- c(nString[1],nString[-1][matching]) } } } if (!is.null(prune)) { matching <- names(categoryCounts)[-1] %in% prune removed <- categoryCounts[-1][matching] npctremoved <- npctString[-1][matching] if (any(names(removed)=="NA")) { NAremoved <- names(removed)=="NA" nr <- npctremoved[NAremoved] if (nr>1) description <- "NAs" else description <- "NA" warning(paste0(var,": prune removed ",npctremoved[NAremoved]," ",description),call.=FALSE) } categoryCounts <- c(categoryCounts[1],categoryCounts[-1][!matching]) npctString <- c(npctString[1],npctString[-1][!matching]) pctString <- c(pctString[1],pctString[-1][!matching]) nString <- c(nString[1],nString[-1][!matching]) } if (!is.null(keep)) { matching <- match(keep,names(categoryCounts)[-1]) matching <- matching[!is.na(matching)] removed <- categoryCounts[-1][-matching] npctremoved <- npctString[-1][-matching] if (!vp) { if (any(names(removed)=="NA")) { NAremoved <- names(removed)=="NA" nr <- npctremoved[NAremoved] #if (nr>1) description <- "NAs" else description <- "NA" #warning(paste0(var,": keep removed ",npctremoved[NAremoved]," ",description),call.=FALSE) } } else { newkeep <- c(keep,"NA") matching <- match(newkeep,names(categoryCounts)[-1]) matching <- matching[!is.na(matching)] } #browser() categoryCounts <- c(categoryCounts[1],categoryCounts[-1][matching]) npctString <- c(npctString[1],npctString[-1][matching]) pctString <- c(pctString[1],pctString[-1][matching]) nString <- c(nString[1],nString[-1][matching]) } if (pruneNA) { m <- names(categoryCounts)[-1]!="NA" categoryCounts <- c(categoryCounts[1],categoryCounts[-1][m]) npctString <- c(npctString[1],npctString[-1][m]) } if (!is.null(prunelone)) { if (length(categoryCounts[-1])==1) { if (names(categoryCounts)[-1] %in% prunelone) { categoryCounts <- categoryCounts[1] } } } # Number of new nodes to add to the tree n <- length(categoryCounts)-1 # exclude the parent node if (n>0) { # Number the parent node and the additional nodes to be added nodenum <- c(parent,last+(1:n)) } else { nodenum <- parent } nodenames <- paste0("Node_",nodenum) CAT <- names(categoryCounts) FILLCOLOR <- fillcolor[match(CAT[-1],names(fillcolor))] if (sortfill) { o <- order(categoryCounts[-1][CAT[-1]!="NA"]) toChange <- (1:length(CAT[-1]))[CAT[-1]!="NA"] names(FILLCOLOR)[toChange] <- names(FILLCOLOR)[toChange][o] FILLCOLOR <- FILLCOLOR[CAT[-1]] } extraText <- rep("",length(CAT)) # Match extra text to nodes if (TopText!="") extraText[1] <- TopText # paste0(sepN,TopText) for (label in names(text)) { if (label %in% names(categoryCounts)) { m <- match(label,names(categoryCounts)) if (text[names(text)==label]!="") { extraText[m] <- paste0("",text[names(text)==label]) } } } if (length(ttext)>0) { for (j in seq_len(length(ttext))) { if (length(ttext[[j]])==2 && any(names(ttext[[j]])==var)) { TTEXTposition <- CAT[-1] == ttext[[j]][names(ttext[[j]])==var] extraText[-1][TTEXTposition] <- ttext[[j]]["text"] } } } if (length(tlabelnode)>0) { for (j in seq_len(length(tlabelnode))) { if (length(tlabelnode[[j]])==2 && any(names(tlabelnode[[j]])==var)) { tlabelnode_position <- CAT[-1] == tlabelnode[[j]][names(tlabelnode[[j]])==var] CAT[-1][tlabelnode_position] <- tlabelnode[[j]]["label"] } } } displayCAT <- CAT if (HTMLtext) { displayCAT <- splitlines(displayCAT,width=splitwidth,sp="<BR/>",at=" ") } else { displayCAT <- splitlines(displayCAT,width=splitwidth,sp="\n",at = c(" ", ".", "-", "+", "_", "=", "/")) } if (check.is.na) { for (i in 2:length(displayCAT)) { varname <- gsub("^MISSING_(.+)", "\\1", var) } } # Relabel the nodes if labels have been specified for (label in labels) { if (label %in% names(categoryCounts)) { m <- match(label,names(categoryCounts)) displayCAT[m] <- names(labels)[labels==label] } } # Write DOT code for the edges if (showroot & !novars) { edgeVector <- paste0(nodenames[1],"->",nodenames[-1]) edges <- paste(edgeVector,collapse=" ") } else { edges <- "" } if (rounded) { styleString <- ' style="rounded,filled"' } else { styleString <- ' style=filled' } # Glue a space or a line break onto the non-empty elements of CAT if (sameline) { for (i in seq_len(length(displayCAT))) { if (showcount || showpct || extraText[i]!="") { if (displayCAT[i]!="") displayCAT[i] <- paste0(displayCAT[i],", ") } } } else { for (i in seq_len(length(displayCAT))) { if (displayCAT[i]!="") displayCAT[i] <- paste0(displayCAT[i],sepN) } } if (!shownodelabels) { for (i in 2:length(displayCAT)) displayCAT[i] <- "" } # Relabel the nodes if showvarinnode is TRUE if (showvarinnode) { if (is.null(labelvar)) { displayCAT[-1] <- paste0(var,": ",displayCAT[-1]) } else { displayCAT[-1] <- paste0(labelvar,sepN,displayCAT[-1]) } } extra_text <- extraText if (!HTMLtext) { # Move any linebreaks at the start of extraText to # the end of npctString, so that justification works right for (i in seq_len(length(extraText))) { if (length(grep("^\n",extraText[i]))>0) { npctString[i] <- paste0(npctString[i],"\n") extraText[i] <- sub("^(\n)","",extraText[i]) } } displayCAT <- convertToHTML(displayCAT,just=just) npctString <- convertToHTML(npctString,just=just) extraText <- convertToHTML(extraText,just=justtext) } # Write DOT code for assigning labels (using the DiagrammeR framework) VARLABELLOC <- "" if (!is.null(varlabelloc) && !is.na(varlabelloc)) VARLABELLOC <- paste0("labelloc=",varlabelloc) VARMINWIDTH <- "" if (!is.null(varminwidth) && !is.na(varminwidth)) VARMINWIDTH <- paste0("width=",varminwidth) VARMINHEIGHT <- "" if (!is.null(varminheight) && !is.na(varminheight)) VARMINHEIGHT <- paste0("height=",varminheight) labelassign <- c() if (root) { if (showroot) { if (!showrootcount) { npctString[1] <- "" } rgb <- grDevices::col2rgb(topfillcolor) red <- rgb["red",]; green <- rgb["green",]; blue <- rgb["blue",] FONTCOLOR <- ifelse((red*0.299 + green*0.587 + blue*0.114) > 186,"#000000","#ffffff") labelassign <- paste(paste0( nodenames[1],'[label=<',displayCAT[1],npctString[1],extraText[1],'> fontcolor=<',FONTCOLOR,'> color=',topcolor,styleString, ' fillcolor=<',topfillcolor,'>]'),collapse='\n') } if (!novars) { rgb <- grDevices::col2rgb(FILLCOLOR) red <- rgb["red",]; green <- rgb["green",]; blue <- rgb["blue",] FONTCOLOR <- ifelse((red*0.299 + green*0.587 + blue*0.114) > 186,"#000000","#ffffff") labelassign <- paste0(labelassign,'\n',paste(paste0( nodenames[-1],'[label=<',displayCAT[-1],npctString[-1],extraText[-1],'> fontcolor=<',FONTCOLOR,'> color=',color,styleString, ' fillcolor=<',FILLCOLOR,'>',VARLABELLOC,' ',VARMINWIDTH,' ',VARMINHEIGHT,']')),collapse='\n') #browser() } } else { rgb <- grDevices::col2rgb(FILLCOLOR) red <- rgb["red",]; green <- rgb["green",]; blue <- rgb["blue",] FONTCOLOR <- ifelse((red*0.299 + green*0.587 + blue*0.114) > 186,"#000000","#ffffff") labelassign <- paste(paste0( nodenames[-1],'[label=<',displayCAT[-1],npctString[-1],extraText[-1],'> fontcolor=<',FONTCOLOR,'> color=',color,styleString, ' fillcolor=<',FILLCOLOR,'>',VARLABELLOC,' ',VARMINWIDTH,' ',VARMINHEIGHT,']'),collapse='\n') } #browser() return(list( root=root, value=CAT[-1], n=as.numeric(nString[-1]), pct=as.numeric(pctString[-1]), npctString=npctString[-1], extraText=extra_text[-1], levels=names(categoryCounts)[-1], nodenum=nodenum[-1], edges=edges, labelassign=labelassign, lastnode=nodenum[length(nodenum)], numsmallernodes=numsmallernodes, sumsmallernodes=sumsmallernodes, numbiggernodes=numbiggernodes, sumbiggernodes=sumbiggernodes)) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/buildCanopy.R
combineVars <- function(prefix,text_part,matching_vars,checked,unchecked,z) { if (prefix=="any:" || prefix=="anyx:" || prefix=="rany:" || prefix=="ranyx:" || prefix=="anyr:" || prefix=="anyrx:") { output <- rep(FALSE,nrow(z)) for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% checked,TRUE, ifelse(z[[matching_vars[j]]] %in% unchecked,FALSE,NA)) if (prefix=="anyx:" || prefix=="ranyx:" || prefix=="anyrx:") { convertedToLogical[is.na(convertedToLogical)] <- FALSE } output <- output | convertedToLogical } NewVarName <- paste0("Any: ",text_part) } if (prefix=="none:" || prefix=="nonex:") { output <- rep(TRUE,nrow(z)) for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% unchecked,TRUE, ifelse(z[[matching_vars[j]]] %in% checked,FALSE,NA)) if (prefix=="nonex:") { convertedToLogical[is.na(convertedToLogical)] <- TRUE } output <- output & convertedToLogical } NewVarName <- paste0("None: ",text_part) } if (prefix=="all:" || prefix=="allx:") { output <- rep(TRUE,nrow(z)) for (j in seq_len(length(matching_vars))) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% checked,TRUE, ifelse(z[[matching_vars[j]]] %in% unchecked,FALSE,NA)) if (prefix=="allx:") { convertedToLogical[is.na(convertedToLogical)] <- TRUE } output <- output & convertedToLogical } NewVarName <- paste0("All: ",text_part) } if (prefix=="notall:" || prefix=="notallx:") { output <- rep(FALSE,nrow(z)) for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% unchecked,TRUE, ifelse(z[[matching_vars[j]]] %in% checked,FALSE,NA)) if (prefix=="notallx:") { convertedToLogical[is.na(convertedToLogical)] <- FALSE } output <- output | convertedToLogical } NewVarName <- paste0("Not all: ",text_part) } return(list(output=output,NewVarName=NewVarName)) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/combineVars.R
#' @importFrom utf8 as_utf8 convertToHTML <- function(x,just="c") { # Convert various text elements to their HTML entities. # Note that order matters here! x <- utf8::as_utf8(x) x <- gsub("&","&amp;",x) x <- gsub("'","&rsquo;",x) # x <- gsub("<=","&le;",x) x <- gsub("<=","&lt;=",x) x <- gsub(">=","&gt;=",x) # x <- gsub(">=","&ge;",x) x <- gsub("<","&lt;",x) x <- gsub(">","&gt;",x) # Also convert character sequences for line breaks. x <- gsub("\n\\*l","<BR ALIGN='LEFT'/>",x) if (just %in% c("c","C","center","Center","centre","Centre")) { x <- gsub("\\\\n","<BR/>",x) x <- gsub("\n","<BR/>",x) } else if (just %in% c("l","L","left","Left")) { x <- gsub("\\\\n","<BR ALIGN='LEFT'/>",x) x <- gsub("\n","<BR ALIGN='LEFT'/>",x) } else if (just %in% c("r","R","right","Right")) { x <- gsub("\\\\n","<BR ALIGN='RIGHT'/>",x) x <- gsub("\n","<BR ALIGN='RIGHT'/>",x) } else stop("Unknown argument of just") # Markdown-style formatting x <- gsub("\\*\\*(.+?)\\*\\*","<B>\\1</B>",x) x <- gsub("\\*(.+?)\\*","<I>\\1</I>",x) # In markdown, _underscores_ can be used to format in italics. # But I have disabled this because it caused problems with # variable_names_likeThis # x <- gsub("_(.+?)_","<I>\\1</I>",x) # Special character sequence for color! x <- gsub("%%([^ ]+?) (.+?)%%","<FONT COLOR=\"\\1\">\\2</FONT>",x) # Markdown-style formatting for superscript and subscript x <- gsub("\\^(.+?)\\^","<FONT POINT-SIZE='10'><SUP>\\1</SUP></FONT>",x) x <- gsub("~(.+?)~","<FONT POINT-SIZE='10'><SUB>\\1</SUB></FONT>",x) x }
/scratch/gouwar.j/cran-all/cranData/vtree/R/convertToHTML.R
#' @title Convert a crosstabulation into a data frame of cases. #' #' @author Nick Barrowman, based on the \code{countsToCases} function at \url{http://www.cookbook-r.com/Manipulating_data/Converting_between_data_frames_and_contingency_tables/#countstocases-function} #' #' @description #' Convert a table of crosstabulated counts into a data frame of cases. #' #' @param x a matrix or table of frequencies representing a crosstabulation. #' @return #' Returns a data frame of cases. #' #' @examples #' # The Titanic data set is in the datasets package. #' # Convert it from a 4 x 2 x 2 x 2 crosstabulation #' # to a 4-column data frame of 2201 individuals #' titanic <- crosstabToCases(Titanic) #' #' @export #' crosstabToCases <- function(x) { if (!is.table(x)) { if (is.matrix(x)) { x <- as.table(x) } else { stop("not a matrix") } } u <- data.frame(x) # Get the row indices to pull from x idx <- rep.int(seq_len(nrow(u)), u$Freq) # Drop count column u$Freq <- NULL # Get the rows from x rows <- u[idx, ] rownames(rows) <- NULL rows }
/scratch/gouwar.j/cran-all/cranData/vtree/R/crosstabToCases.R
#' Fake clinical dataset #' #' A dataset consisting of made-up clinical data. #' Note that some observations are missing (i.e. NAs). #' #' @format A small data frame in which the rows represent (imaginary) patients and #' the columns represent variables of possible clinical relevance. #' #' \describe{ #' \item{id}{Integer: Patient ID number} #' \item{Group}{Factor: Treatment Group, A or B} #' \item{Severity}{Factor representing severity of condition: Mild, Moderate, or Severe} #' \item{Sex}{Factor: M or F} #' \item{Male}{Integer: Sex coded as 1=M, 0=F} #' \item{Age}{Integer: Age in years, continuous} #' \item{Score}{Integer: Score on a test} #' \item{Category}{Factor: single, double, or triple} #' \item{Pre}{Numeric: initial measurement} #' \item{Post}{Numeric: measurement taken after something happened} #' \item{Post2}{Numeric: measurement taken at the very end of the study} #' \item{Time}{Numeric: time to event, or time of censoring} #' \item{Event}{Integer: Did the event occur? 1=yes, 0=no (i.e. censoring)} #' \item{Ind1}{Integer: Indicator variable for a certain characteristic, 1=present, 0=absent} #' \item{Ind2}{Integer: Indicator variable for a certain characteristic, 1=present, 0=absent} #' \item{Ind3}{Integer: Indicator variable for a certain characteristic, 1=present, 0=absent} #' \item{Ind4}{Integer: Indicator variable for a certain characteristic, 1=present, 0=absent} #' \item{Viral}{Logical: Does this patient have a viral illness?} #' #' } "FakeData" #' Fake Randomized Controlled Trial (RCT) data #' #' A dataset consisting of made-up RCT data. #' #' @format A small data frame in which the rows represent (imaginary) patients and #' the columns represent variables of possible clinical relevance. #' #' \describe{ #' \item{id}{String: Patient ID number} #' \item{eligible}{Factor: Eligible or Ineligible} #' \item{randomized}{Factor: Randomized or Not randomized} #' \item{group}{Factor: A or B} #' \item{followup}{Factor: Followed up or Not followed up} #' \item{analyzed}{Factor: Analyzed or Not analyzed} #' #' } "FakeRCT" #' The Matrix trilogy characters #' #' This data set was abstracted from the three movies. #' #' @format A tibble with 35 rows and 14 variables: #' #' \describe{ #' \item{name}{Name of character} #' \item{height}{Height (m)} #' \item{sex}{male, female; by appearance} #' \item{nature}{This is the nature of the character, whether plugged into the matrix and took a red pill (coppertop), born free in Zion (born free), or a computer application running in the matrix (app)} #' \item{sunglasses}{yes, no} #' \item{apparel}{Description of clothing worn} #' \item{bodycount1, bodycount2, bodycount3}{A count of the number of onscreen kills, in or out of the matrix, for each of the movies} #' \item{ship}{List of ships} #' \item{the.matrix, the.matrix.reloaded., the.matrix.revolutions}{Indicates if the character was in the movie} #' } #' #' @author Franco Momoli #' @examples #' #' # ship within sunglasses within nature #' vtree(the.matrix,"nature sunglasses ship") #' "the.matrix"
/scratch/gouwar.j/cran-all/cranData/vtree/R/data.R
#' @title Export an htmlwidget object into an image file #' #' @author Nick Barrowman #' #' @description #' Export an \code{htmlwidget} object (produced by \code{DiagrammerR::grViz}) into a PNG file #' #' @param g an object produced by the \code{grViz} function from the DiagrammmeR package #' @param width the width in pixels of the bitmap #' @param height the height in pixels of the bitmap #' @param format Graphics file format. Currently "png" and "pdf" are supported. #' @param folder path to folder where the PNG file should stored #' @param filename an optional filename stem. #' If not provided, the filename stem will be derived from the name #' of the argument of \code{g}. #' #' @details #' First the \code{grViz} object is exported to an SVG file (using \code{DiagrammeRsvg::export_svg}). #' Then the SVG file is converted to a bitmap (using \code{rsvg::rsvg}). #' Then the bitmap is exported as a PNG file (using \code{png::writePNG}). #' Note that the SVG file and the PNG file will be named using the name of the \code{g} parameter #' #' @note #' In addition to the DiagrammmeR package, the following packages are used: \code{DiagrammeRsvg}, \code{rsvg} #' #' @return #' Returns the full path of the imagefile. #' #' @importFrom utils capture.output #' #' @export #' grVizToImageFile <- function (g, width=NULL, height=NULL, format="png", folder = ".",filename) { filenamestem <- sub(pattern = "(.*)\\..*$", replacement = "\\1", filename) if (!("htmlwidget" %in% class(g))) stop("Argument must be of class htmlwidget.") if (is.null(folder)) { stop("folder parameter is NULL") } if (missing(filenamestem)) { filenamestem <- paste0(sapply(as.list(substitute({g})[-1]), deparse)) } # If the filename doesn't have an extension, add one if (filename==filenamestem) { filename <- ifelse( format=="png", paste0(filenamestem,".png"), ifelse( format=="pdf", paste0(filenamestem,".pdf"), stop("Unsupported format"))) } if (is.null(g)) { g <- format(DiagrammeR::grViz("digraph empty{ Node1[label='Empty'] }")) } # Convert any double backslashes to forward slashes. folder <- gsub("\\\\","/",folder) fullpath <- file.path(folder,filename) message <- utils::capture.output(svg <- format(DiagrammeRsvg::export_svg(g))) if (format=="png") { result <- rsvg::rsvg_png(charToRaw(svg),fullpath, width = width, height=height) } else if (format=="pdf") { result <- rsvg::rsvg_pdf(charToRaw(svg),fullpath, width = width, height=height) } invisible(fullpath) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/grVizToImageFile.R
#' @title Export an htmlwidget object into a PNG file #' #' @author Nick Barrowman #' #' @description #' Export an \code{htmlwidget} object (produced by \code{DiagrammerR::grViz}) into a PNG file #' #' @param g an object produced by the \code{grViz} function from the DiagrammmeR package #' @param width the width in pixels of the bitmap #' @param height the height in pixels of the bitmap #' @param folder path to folder where the PNG file should stored #' @param filename an optional filename. #' If not provided, the filename will be derived from the name #' of the argument of \code{g}. #' #' @details #' First the \code{grViz} object is exported to an SVG file (using \code{DiagrammeRsvg::export_svg}). #' Then the SVG file is converted to a bitmap (using \code{rsvg::rsvg}). #' Then the bitmap is exported as a PNG file (using \code{png::writePNG}). #' Note that the SVG file and the PNG file will be named using the name of the \code{g} parameter #' #' @note #' In addition to the DiagrammmeR package, the following packages are used: \code{DiagrammeRsvg}, \code{rsvg} #' #' @return #' Returns the full path of the PNG file. #' #' @export #' grVizToPNG <- function (g, width=NULL, height=NULL, folder = ".",filename) { if (missing(filename)) { filename <- paste0(sapply(as.list(substitute({g})[-1]), deparse),".png") } grVizToImageFile(g=g,width=width,height=height,format="png",folder=folder,filename=filename) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/grVizToPNG.R
joinflow <- function(...) { # # {join} information (from the flowcat function) about two or more {flow}charts # numsmallernodes <- 0 sumsmallernodes <- 0 numbiggernodes <- 0 sumbiggernodes <- 0 edges <- labelassign <- labelshow <- nodenum <- c() flows <- list(...) for (i in seq_len(length(flows))) { if (!is.null(flows[[i]])) { numsmallernodes <- numsmallernodes + flows[[i]]$numsmallernodes sumsmallernodes <- sumsmallernodes + flows[[i]]$sumsmallernodes numbiggernodes <- numbiggernodes + flows[[i]]$numbiggernodes sumbiggernodes <- sumbiggernodes + flows[[i]]$sumbiggernodes nodenum <- c(nodenum,flows[[i]]$nodenum) if (length(edges)==0) { edges <- flows[[i]]$edges } else { edges <- paste0(edges,"\n",flows[[i]]$edges) } if (length(labelassign)==0) { labelassign <- flows[[i]]$labelassign } else { labelassign <- paste0(labelassign,"\n",flows[[i]]$labelassign) } } } return( list( nodenum=nodenum,edges=edges,labelassign=labelassign,labelshow=labelshow, numsmallernodes=numsmallernodes,sumsmallernodes=sumsmallernodes, numbiggernodes=numbiggernodes,sumbiggernodes=sumbiggernodes)) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/joinflow.R
labelsAndLegends <- function(z,OLDVARS,vars,labelvar,HTMLtext,vsplitwidth,just,colorvarlabels, varnamebold,varlabelcolors,varnamepointsize,showroot,rounded,numvars,Venn,labelnode, fillcolor,showlegendsum,thousands,splitwidth,nodefunc,nodeargs,showvarnames,check.is.na, vp,showlpct,digits,legendpointsize,horiz,color,showlegend,pattern,sepN) { if (showvarnames) { # Special case for check.is.na if (check.is.na) { VARS <- OLDVARS } else { VARS <- vars } if (!is.null(labelvar)) { for (i in 1:numvars) { if (!is.na(labelvar[vars[i]])) { VARS[i] <- labelvar[vars[i]] } } } if (!HTMLtext) { VARS <- splitlines(VARS,width=vsplitwidth,sp='\n',at = c(" ", ".", "-", "+", "_", "=", "/")) VARS <- convertToHTML(VARS,just=just) } if (colorvarlabels) { if (varnamebold) { colored_VARS <- paste0('<FONT COLOR="',varlabelcolors,'">',"<B>",VARS,' </B>','</FONT>') } else { colored_VARS <- paste0('<FONT COLOR="',varlabelcolors,'">',VARS,'</FONT>') } } else { colored_VARS <- VARS } colored_VARS <- paste0('<FONT POINT-SIZE="',varnamepointsize,'">',colored_VARS,'</FONT>') marginalText <- rep("",numvars) # *********************************************************************** # Begin: Legend stuff ---- # *********************************************************************** if (showroot) { NL <- "Node_L0_0 [style=invisible]\n" } else { NL <- "" } if (rounded) { styleString <- ' style="rounded,filled"' } else { styleString <- ' style=filled' } for (i in seq_len(numvars)) { thisvarname <- vars[i] thisvar <- z[[thisvarname]] if (is.logical(thisvar)) { thisvar <- factor(thisvar, c("FALSE", "TRUE")) } categoryCounts <- table(thisvar,exclude=NULL) if (Venn) { names(categoryCounts)[which(names(categoryCounts)=="1" | names(categoryCounts)=="TRUE")] <- "Yes" names(categoryCounts)[which(names(categoryCounts)=="0" | names(categoryCounts)=="FALSE")] <- "No" } names(categoryCounts)[is.na(names(categoryCounts))] <- "NA" if (vp & any(is.na(thisvar))) { cc <- categoryCounts cc <- cc[names(cc)!="NA"] if (length(cc)>0) { if (showlpct) { npctString <- paste0( lapply(cc,function(x) format(x,big.mark=thousands)), " (", around(100*cc/sum(cc),digits),"%)") } else { npctString <- lapply(cc,function(x) format(x,big.mark=thousands)) } } else { npctString <- NULL } npctString <- c(npctString,categoryCounts["NA"]) } else { if (showlpct) { #browser() npctString <- paste0( lapply(categoryCounts,function(x) format(x,big.mark=thousands)), " (", around(100*categoryCounts/length(thisvar),digits),"%)") } else { npctString <- lapply(categoryCounts,function(x) format(x,big.mark=thousands)) } } CAT <- names(categoryCounts) # Relabel the nodes if labels have been specified labels <- labelnode[[thisvarname]] for (label in labels) { if (label %in% CAT) { m <- match(label,CAT) CAT[m] <- names(labels)[labels==label] } } labels <- paste0( 'label=<', colored_VARS[i], '>') nlheading <- paste0("Node_L",i,"_0", '[', labels, ' shape=none margin=0]',collapse = '\n') FILLCOLOR <- fillcolor[[thisvarname]][seq_len(length(categoryCounts))] if (HTMLtext) { displayCAT <- splitlines(CAT,width=splitwidth,sp="<BR/>",at=" ") } else { displayCAT <- splitlines(CAT,width=splitwidth,sp="\n",at = c(" ", ".", "-", "+", "_", "=", "/")) } if (HTMLtext) { displayCAT <- displayCAT } else { displayCAT <- convertToHTML(displayCAT,just=just) } legendlabel <- paste0(displayCAT,", ",npctString) ThisLayerText <- rep("",length(legendlabel)) if (showlegendsum) { if (!is.null(nodefunc)) { if (numvars == 1) nodeargs$leaf <- TRUE ThisLayerText <- c() current_var <- as.character(thisvar) current_var[is.na(current_var)] <- "NA" summarytext <- vector("list",length=length(CAT)) names(summarytext) <- CAT for (value in displayCAT) { df_subset <- z[current_var == value,,drop=FALSE] summarytext[[value]] <- nodefunc(df_subset, vars[i], value, args = nodeargs) nodetext <- paste0(summarytext[[value]],collapse="") nodetext <- splitlines(nodetext, width = splitwidth, sp = sepN, at=" ") ThisLayerText <- c(ThisLayerText, paste0(nodetext,sepN)) } } } extendedlegendlabel <- paste0(legendlabel,convertToHTML(ThisLayerText,just=just)) labels <- paste0( 'label=<<FONT POINT-SIZE="',legendpointsize,'">', extendedlegendlabel, '</FONT>>') if (!horiz) { labels <- rev(labels) FILLCOLOR <- rev(FILLCOLOR) } rgb <- grDevices::col2rgb(FILLCOLOR) red <- rgb["red",]; green <- rgb["green",]; blue <- rgb["blue",] FONTCOLOR <- ifelse((red*0.299 + green*0.587 + blue*0.114) > 186,"#000000","#ffffff") nl <- paste0("Node_L",i,"_",seq_len(length(categoryCounts)), '[', labels, ' fontcolor=<',FONTCOLOR,'>', ' color=',color[i+1],' ', styleString, ' fillcolor=<',FILLCOLOR,'> height=0]', collapse = '\n') nl_allnodes <- paste0("Node_L",i,"_",seq(0,length(categoryCounts)),collapse=" ") if (showlegend) { nl <- paste0( "subgraph cluster_",i," {\n", "style=rounded\n", "color=<#bdbdbd>\n", "{rank=same"," ",nl_allnodes,"}\n", nlheading, "\n", nl, "\n}\n", paste0("Node_L",i-1,"_0 -> Node_L",i,"_0 [style=invisible arrowhead=none]\n")) if ((pattern | check.is.na) && i==1) { nl <- "Node_L1_0[style=invisible arrowhead=none]\n" } } else { link <- paste0("Node_L",i-1,"_0 -> Node_L",i,"_0 [style=invisible arrowhead=none]\n") if (i==1 & !showroot) link <- "" nl <- paste0( nlheading, "\n", link) } NL <- paste0(NL,"\n",nl) #-^------------------------------^--------------------------------------^- # End: Legend stuff ---- #------------------------------------------------------------------------- } } else { NL <- '' } NL }
/scratch/gouwar.j/cran-all/cranData/vtree/R/labelsAndLegends.R
nodeMeanSD <- function(u,varname,value,args) { if (is.null(args$digits)) args$digits <- 1 # default value paste0("\n",args$var,": mean (SD)\n", around(mean(u[[args$var]],na.rm=TRUE),args$digits), " (",around(sd(u[[args$var]],na.rm=TRUE),args$digits),")", " mv=",sum(is.na(u[[args$var]]))) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/nodeMeanSD.R
.onAttach <- function(...) { if (interactive()) { packageStartupMessage("vtree version ",utils::packageVersion("vtree")," -- For more information, type: vignette(\"vtree\")") } }
/scratch/gouwar.j/cran-all/cranData/vtree/R/onAttach.R
parseSummary <- function(z,vars,summary,verbose,choicechecklist,checked,unchecked) { # regexVarName and regexComplex could in fact be passed in regexVarName <- "([a-zA-Z0-9~@#()_|,.]+)" regexComplex <- "^((i|r|any|anyx|all|allx|notall|notallx|none|nonex)+:)*([^([:space:]|:)@\\*#]*)([@\\*#]?)(.*)$" regex <- "^(\\S+)\\s(.+)$" codevar <- gsub(regex, "\\1", summary) summaryvar <- heading <- codevar summaryformat <- gsub(regex, "\\2", summary) summaryformat[grep(regex,summary,invert=TRUE)] <- "" extra_variables <- NULL # Process >= tag in variable names in summary argument regex <- paste0("^",regexVarName,"(>=)",regexVarName) findgte <- grep(regex,codevar) if (length(findgte)>0) { for (i in seq_len(length(codevar))) { if (i %in% findgte) { gtevar <- sub(regex,"\\1",codevar[i]) if (is.null(z[[gtevar]])) stop(paste("Unknown variable in summary:",gtevar)) gteval <- sub(regex,"\\3",codevar[i]) newvarname <- paste0(gtevar,"_gte_",gteval) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[gtevar]]))))>0)) { gteval <- gsub("_"," ",gteval) } m <- z[[gtevar]]>=as.numeric(gteval) z[[newvarname]] <- m summaryvar <- newvarname # codevar[i] <- gtvar } } } # Process != tag in variable names in summary argument # (Note that this comes before the = tag so that it doesn't match first.) regex <- paste0("^",regexVarName,"(\\!=)",regexVarName) findnotequal <- grep(regex,codevar) if (length(findnotequal)>0) { for (i in seq_len(length(codevar))) { if (i %in% findnotequal) { thevar <- sub(regex,"\\1",codevar[i]) if (is.null(z[[thevar]])) stop(paste("Unknown variable in summary:",thevar)) theval <- sub(regex,"\\3",codevar[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[thevar]]))))>0)) { theval <- gsub("_"," ",equalval) } m <- z[[thevar]]!=theval z[[thevar]] <- m summaryvar <- thevar # codevar[i] <- thevar } } } # Process = tag in variable names in summary argument regex <- paste0("^",regexVarName,"(=)",regexVarName) findequal <- grep(regex,codevar) if (length(findequal)>0) { for (i in seq_len(length(codevar))) { if ((i %in% findequal) && !(i %in% findnotequal)) { equalvar <- sub(regex,"\\1",codevar[i]) if (is.null(z[[equalvar]])) stop(paste("Unknown variable in summary:",equalvar)) equalval <- sub(regex,"\\3",codevar[i]) newvarname <- paste0(equalvar,equalval) # Check to see if any of the values of the specified variable contain spaces. # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[equalvar]]))))>0)) { equalval <- gsub("_"," ",equalval) } m <- z[[equalvar]]==equalval z[[newvarname]] <- m summaryvar <- newvarname # codevar[i] <- equalvar } } } # Process > tag in variable names in summary argument regex <- paste0("^",regexVarName,"(>)",regexVarName) findgt <- grep(regex,codevar) if (length(findgt)>0) { for (i in seq_len(length(codevar))) { if (i %in% findgt) { gtvar <- sub(regex,"\\1",codevar[i]) if (is.null(z[[gtvar]])) stop(paste("Unknown variable in summary:",gtvar)) gtval <- sub(regex,"\\3",codevar[i]) newvarname <- paste0(gtvar,"_gt_",gtval) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[gtvar]]))))>0)) { gtval <- gsub("_"," ",gtval) } m <- z[[gtvar]]>as.numeric(gtval) z[[newvarname]] <- m summaryvar <- newvarname # codevar[i] <- gtvar } } } # Process < tag in variable names in summary argument regex <- paste0("^",regexVarName,"(<)",regexVarName) findlt <- grep(regex,codevar) if (length(findlt)>0) { for (i in seq_len(length(codevar))) { if (i %in% findlt) { ltvar <- sub(regex,"\\1",codevar[i]) if (is.null(z[[ltvar]])) stop(paste("Unknown variable in summary:",ltvar)) ltval <- sub(regex,"\\3",codevar[i]) newvarname <- paste0(ltvar,"_lt_",ltval) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[ltvar]]))))>0)) { ltval <- gsub("_"," ",ltval) } m <- z[[ltvar]]<as.numeric(ltval) z[[newvarname]] <- m summaryvar <- newvarname # codevar[i] <- ltvar } } } # Process is.na: tag in variable names to handle individual missing value checks regex <- paste0("^is\\.na:",regexVarName,"$") findna <- grep(regex,codevar) if (length(findna)>0) { for (i in seq_len(length(vars))) { if (i %in% findna) { navar <- sub(regex,"\\1",codevar[i]) if (is.null(z[[navar]])) stop(paste("Unknown variable:",navar)) NewVar <- paste0("is.na:",navar) m <- is.na(z[[navar]]) z[[NewVar]] <- factor(m, levels = c(FALSE, TRUE),c("not N/A","N/A")) summaryvar <- NewVar } } } # Process stem: tag in variable names in summary argument regex <- paste0("^stem:",regexVarName,"$") findstem <- grep(regex,codevar) if (length(findstem)>0) { for (i in seq_len(length(codevar))) { if (i %in% findstem) { thevar <- sub(regex,"\\1",codevar[i]) expanded_stem <- names(z)[grep(paste0("^",thevar,"___[0-9]+$"),names(z))] if (verbose) message(paste0(codevar[i]," expands to: ",paste(expanded_stem,collapse=", "))) if (length(expanded_stem)==0) { stop(paste0("summary: Could not find variables with names matching the specified stem: ",thevar)) } rexp0 <- "\\(choice=.+\\)" rexp1 <- "(.+) \\(choice=(.+)\\)" rexp2 <- "(.+): (.+)" expandedvars <- c() if (choicechecklist) { for (j in 1:length(expanded_stem)) { lab <- attributes(z[[expanded_stem[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) } else { stop("Could not find value of checklist item") } if (verbose) message(paste0(expanded_stem[j]," is ",choice)) z[[choice]] <- z[[expanded_stem[j]]] expandedvars <- c(expandedvars,choice) } } else { expandedvars <- c(expandedvars,expanded_stem) } summaryvar <- expandedvars heading <- expandedvars extra_variables <- c(extra_variables,expanded_stem) summaryformat <- rep(summaryformat,length(expanded_stem)) } } } # Process stemc: tag in variable names in summary argument regex <- paste0("^stemc:",regexVarName,"$") findstem <- grep(regex,codevar) if (length(findstem)>0) { for (i in seq_len(length(codevar))) { if (i %in% findstem) { y <- rep("",nrow(z)) none <- rep(TRUE,nrow(z)) thevar <- sub(regex,"\\1",codevar[i]) expanded_stem <- names(z)[grep(paste0("^",thevar,"___[0-9]+$"),names(z))] if (verbose) message(paste0(codevar[i]," expands to: ",paste(expanded_stem,collapse=", "))) if (length(expanded_stem)==0) { stop(paste0("summary: Could not find variables with names matching the specified stem: ",thevar)) } rexp0 <- "\\(choice=.+\\)" rexp1 <- "(.+) \\(choice=(.+)\\)" rexp2 <- "(.+): (.+)" expandedvars <- c() if (choicechecklist) { for (j in 1:length(expanded_stem)) { lab <- attributes(z[[expanded_stem[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) } else { stop("Could not find value of checklist item") } y <- ifelse(z[[expanded_stem[j]]]==1, ifelse(y=="",choice,paste0(y,"+",choice)),y) if (verbose) message(paste0(expanded_stem[j]," is ",choice)) z[[choice]] <- z[[expanded_stem[j]]] expandedvars <- c(expandedvars,choice) } } else { expandedvars <- c(expandedvars,expanded_stem) } y[y %in% ""] <- "*None" newvar <- paste0("stem:",thevar) z[[newvar]] <- y summaryvar <- newvar heading <- "" extra_variables <- c(extra_variables,newvar) summaryformat <- rep(summaryformat,length(expanded_stem)) } } } # # >> Process complex summary specification ---- # including REDCap variables, intersections, and wildcards # # Uses the same regular expression as for variable specifications, # namely the string regexComplex match_regex <- grep(regexComplex,codevar) if (length(match_regex)>0) { expandedvars <- c() for (i in seq_len(length(codevar))) { if (i %in% match_regex) { y <- rep("",nrow(z)) none <- rep(TRUE,nrow(z)) prefix <- sub(regexComplex,"\\1",codevar[i]) text_part <- sub(regexComplex,"\\3",codevar[i]) wildcard <- sub(regexComplex,"\\4",codevar[i]) tail <- sub(regexComplex,"\\5",codevar[i]) if (prefix=="" && wildcard=="") { expandedvars <- c(expandedvars,vars[i]) } else if (prefix=="any:" || prefix=="anyx:" || prefix=="none:" || prefix=="nonex:" || prefix=="all:" || prefix=="allx:" || prefix=="notall:" || prefix=="notallx:" ) { if (wildcard=="*") { matching_vars <- names(z)[grep(paste0("^",text_part,".*",tail,"$"),names(z))] } else if (wildcard=="#") { matching_vars <- names(z)[grep(paste0("^",text_part,"[0-9]+",tail,"$"),names(z))] } else { stop("Invalid wildcard in summary specification") } expandedvars <- c() if (length(matching_vars)==0) { stop("Could not find variables matching summary specification") } if (verbose) message(paste0(vars[i]," expands to: ",paste(matching_vars,collapse=", "))) out <- combineVars(prefix,text_part,matching_vars,checked,unchecked,z) output <- out$output NewVarName <- out$NewVarName z[[NewVarName]] <- output expandedvars <- c(expandedvars,NewVarName) newvarheading <- NewVarName summaryvar <- NewVarName heading <- NewVarName extra_variables <- c(extra_variables,NewVarName) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="r:" || prefix=="ir:" || prefix=="ri:" || prefix=="anyr:" || prefix=="rany:" || prefix=="allr:" || prefix=="rall:" || prefix=="noner:" || prefix=="rnone:" || prefix=="notallr:" || prefix=="rnotall:") { if (wildcard=="@") { matching_vars <- names(z)[grep(paste0("^",text_part,"___[0-9]+$"),names(z))] } else { stop("Invalid wildcard in summary specification") } if (length(matching_vars)==0) { stop("Could not find variables names matching summary specification") } if (verbose) message(paste0(codevar[i]," expands to: ",paste(matching_vars,collapse=", "))) #message(paste0("prefix-->",prefix,"<-- matching_vars=",paste(matching_vars,collapse=", "))) rexp0 <- "\\(choice=.+\\)" rexp1 <- "(.+) \\(choice=(.+)\\)" rexp2 <- "(.+): (.+)" expandedvars <- c() if (prefix=="r:") { if (choicechecklist) { for (j in seq_len(length(matching_vars))) { lab <- attributes(z[[matching_vars[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) } else { stop("Could not find value of checklist item") } if (verbose) message(paste0(matching_vars[j]," is ",choice)) z[[choice]] <- z[[matching_vars[j]]] expandedvars <- c(expandedvars,choice) } } else { expandedvars <- c(expandedvars,matching_vars) } summaryvar <- expandedvars heading <- expandedvars extra_variables <- c(extra_variables,matching_vars) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="anyr:" || prefix=="rany:") { lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { out <- combineVars(prefix,REDCap_var_label,matching_vars,checked,unchecked,z) } output <- out$output REDCap_var_label_any <- out$NewVarName z[[REDCap_var_label_any]] <- output expandedvars <- c(expandedvars,REDCap_var_label_any) summaryvar <- expandedvars heading <- expandedvars extra_variables <- c(extra_variables,matching_vars) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="noner:" || prefix=="rnone:") { lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(!(z[[matching_vars[j]]] %in% checked),TRUE, ifelse(!(z[[matching_vars[j]]] %in% unchecked),FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output & convertedToLogical } } } REDCap_var_label_none <- paste0("None: ",REDCap_var_label) z[[REDCap_var_label_none]] <- output expandedvars <- c(expandedvars,REDCap_var_label_none) summaryvar <- expandedvars heading <- expandedvars extra_variables <- c(extra_variables,matching_vars) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="allr:" || prefix=="rall:") { lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% checked,TRUE, ifelse(z[[matching_vars[j]]] %in% unchecked,FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output & convertedToLogical } } } REDCap_var_label_all <- paste0("All: ",REDCap_var_label) z[[REDCap_var_label_all]] <- output expandedvars <- c(expandedvars,REDCap_var_label_all) summaryvar <- expandedvars heading <- expandedvars extra_variables <- c(extra_variables,matching_vars) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="notallr:" || prefix=="rnotall:") { lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(!(z[[matching_vars[j]]] %in% checked),TRUE, ifelse(!(z[[matching_vars[j]]] %in% unchecked),FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output | convertedToLogical } } } REDCap_var_label_notall <- paste0("Not all: ",REDCap_var_label) z[[REDCap_var_label_notall]] <- output expandedvars <- c(expandedvars,REDCap_var_label_notall) summaryvar <- expandedvars heading <- expandedvars extra_variables <- c(extra_variables,matching_vars) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="ri:" | prefix=="ir:") { if (choicechecklist) { for (j in seq_len(length(matching_vars))) { lab <- attributes(z[[matching_vars[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) } else { stop("Could not find value of checklist item") } y <- ifelse(z[[matching_vars[j]]]==1, ifelse(y=="",choice,paste0(y,"+",choice)),y) if (verbose) message(paste0(matching_vars[j]," is ",choice)) z[[choice]] <- z[[matching_vars[j]]] expandedvars <- c(matching_vars,choice) } } else { expandedvars <- c(expandedvars,matching_vars) } y[y %in% ""] <- "*None" newvar <- paste0("stem:",text_part) z[[newvar]] <- y summaryvar <- newvar heading <- "" extra_variables <- c(extra_variables,newvar) summaryformat <- rep(summaryformat,length(matching_vars)) } } else { if (wildcard=="*") { matching_vars <- names(z)[grep(paste0("^",text_part,".*",tail,"$"),names(z))] } else if (wildcard=="#") { matching_vars <- names(z)[grep(paste0("^",text_part,"[0-9]+",tail,"$"),names(z))] } else { stop("Invalid wildcard in summary specification") } if (length(matching_vars)==0) { stop("summary: Could not find variables with matching names") } if (verbose) message(paste0(codevar[i]," expands to: ",paste(matching_vars,collapse=", "))) #message(paste0("prefix-->",prefix,"<-- matching_vars=",paste(matching_vars,collapse=", "))) if (prefix=="i:") { expandedvars <- c() if (choicechecklist) { for (j in seq_len(length(matching_vars))) { y <- ifelse(z[[matching_vars[j]]]==1, ifelse(y=="",matching_vars[j],paste0(y,"+",matching_vars[j])),y) } } y[y %in% ""] <- "*None" newvar <- paste0("combinations_of_",paste(matching_vars,collapse="_")) newvarheading <- paste0("combinations of ",paste(matching_vars,collapse=", ")) z[[newvar]] <- y summaryvar <- newvar heading <- newvarheading extra_variables <- c(extra_variables,newvar) summaryformat <- rep(summaryformat,length(matching_vars)) } else if (prefix=="") { summaryvar <- matching_vars heading <- matching_vars summaryformat <- rep(summaryformat,length(matching_vars)) } else { stop("Unknown prefix") } } } } } # If an element of codevar is not the name of a variable in z, # perhaps it's an expression that can be evaluated in z if (length(summaryvar)==1) { if (length(grep("^([oair]+[oair]*:)*(\\S*)([\\*#@])$",summaryvar))==0) { if (length(grep("^stem:",summaryvar))==0) { # except for stems if (length(grep("^stemc:",summaryvar))==0) { # except for stems if (length(grep("\\*$",summaryvar))==0) { # except for ending in * if (length(grep("#$",summaryvar))==0) { # except for ending in # if (!(summaryvar %in% names(z))) { derivedvar <- with(z,eval(parse(text=summaryvar,keep.source=FALSE))) z[[summaryvar]] <- derivedvar } } } } } } } #browser() list(z=z,summaryvar=summaryvar,format=summaryformat,heading=heading,codevar=codevar) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/parseSummary.R
#' Setup for inline CSS #' #' Initial CSS setup for the SVG. #' #' @param minheight minimum height in \code{"px"}. Default is "200px". #' @param cursor_all The cursor symbol for the whole SVG. Default is "all-scroll". #' @param overflow Overflow value for the whole SVG. Default is "inherit". #' @param position CSS position of the SVG. Default is "sticky". #' @param fill Fill color for the SVG background. Default is "transparent". #' @param cursor_text The cursor symbol for text nodes. Default is "pointer". #' #' @importFrom shiny HTML #' @seealso \code{\link{use_svgzoom}} #' @keywords internal #' @family Shiny Functions inlineCssSetup <- function(minheight, cursor_all, overflow, position, fill, cursor_text) { svg <- sprintf(".grViz svg { min-height: %s; cursor: %s; overflow: %s; position: %s; }", minheight, cursor_all, overflow, position) poly <- sprintf(".grViz #graph0 > polygon { fill: %s; }", fill) text <- sprintf(".grViz text { cursor: %s; }", cursor_text) shiny::HTML(paste(svg, poly, text)) } #' Setup for interactive Vtree #' #' This function must be called in the UI, in order to make the \code{\link{vtree}} interactive. #' #' @inheritParams inlineCssSetup #' @inheritParams init_js #' #' @importFrom shiny addResourcePath singleton tags #' @seealso \code{\link{vtreeOutput}}, \code{\link{vtree}} #' @family Shiny Functions #' @examples \dontrun{ #' library(shiny) #' library(vtree) #' #' ui <- fluidPage( #' use_svgzoom(), #' helpText(div(style="font-weight: 800; font-size: large; color: black;", #' HTML("Zooming and Panning is possible with mouse-drag ", #' "and mouse-wheel <br>, or with shortcuts;", #' " +,- and arrow-keys and CTRL+Backspace to", #' " resize+fit+center the svg.."))), #' vtreeOutput("vtree", width = "100%", height = "500px") #' ) #' #' server <- function(input, output, session) { #' output$vtree <- renderVtree({ #' vtree(FakeData,"Severity Sex", #' labelnode=list(Sex=(c("Male"="M","Female"="F"))), #' pngknit=FALSE) #' }) #' } #' #' shinyApp(ui, server) #' } #' @export use_svgzoom <- function(minheight = "200px", cursor_all = "all-scroll", overflow = "inherit !important", position = "sticky", fill = "transparent", cursor_text = "pointer", init_event = c("mouseenter","click","dblclick"), onwindow_resize = TRUE, shortcuts = TRUE ) { init_event <- match.arg(init_event) shiny::addResourcePath("vtree", system.file(package = "vtree")) shiny::singleton( shiny::tags$head( shiny::tags$script(src = "vtree/www/svg_pan_zoom.js"), shiny::tags$style(inlineCssSetup(minheight, cursor_all, overflow, position, fill, cursor_text)), shiny::tags$script(init_js(init_event, onwindow_resize, shortcuts)) ) ) } #' Initializing JS-Part #' @param init_event The mouse event to activate zooming and panning. #' Default is \code{mouseenter}. #' @param onwindow_resize Should the SVG be resized when the window size changes? #' Default is \code{TRUE}. #' @param shortcuts Should Keyboard shortcuts be used to control the SVG? #' Default is \code{TRUE}. #' @family Shiny Functions #' @keywords internal init_js <- function(init_event, onwindow_resize, shortcuts) { ## Text snippets ######################## wrap_conn <- '$(document).on("shiny:connected", function(event) { %s %s });' initjs <- paste0('$(document).on("%s", ".grViz svg", function(){ if ($(".grViz svg").length > 0) { svgPanZoom(".grViz svg"); } });') initjs <- sprintf(initjs, init_event) resize <- '$(window).on("resize", function(){ if ($(".grViz svg:visible").length > 0) { var inst = svgPanZoom(".grViz svg"); inst.resize(); // update SVG cached size and controls positions inst.fit(); inst.center(); } });' ## Output ################## if (onwindow_resize) { initjs <- shiny::HTML(sprintf(wrap_conn, initjs, resize)) } else { initjs <- shiny::HTML(sprintf(wrap_conn, initjs, "")) } if (shortcuts) { ## text snippet ########################### shcts <- "// Shortcuts Functions $(document).on('keydown', function(e) { //e.preventDefault(); //e.stopPropagation(); if ($('.grViz') && $('.grViz').is(':hover')) { var ekey = e.keyCode; var panZoomTiger = svgPanZoom('.grViz svg'); switch(ekey){ // Zoom IN (+) case 171: { panZoomTiger.zoomBy(1.1); break; } // Zoom Out (-) case 173: { panZoomTiger.zoomBy(0.9); break; } // Center and Fit (CTRL + Backspace) case 8: { if (e.ctrlKey && e.ctrlKey === true) { panZoomTiger.resize(); // update SVG cached size and controls positions panZoomTiger.fit(); panZoomTiger.center(); } break; } // Pan Left (left arrow) case 37: { panZoomTiger.panBy({x: -50, y: 0}); break; } // Pan Right (right arrow) case 39: { panZoomTiger.panBy({x: 50, y: 0}); break; } // Pan Up (up arrow) case 38: { panZoomTiger.panBy({x: 0, y: -50}); break; } // Pan Down (down arrow) case 40: { panZoomTiger.panBy({x: 0, y: 50}); break; } } } });" ####################### shiny::HTML(paste(initjs, shcts)) } else { initjs } } #' vtree widget #' #' Shiny bindings for vtree. It is actually a wrapper around \code{\link[DiagrammeR]{grViz}}. #' @param outputId output variable to read from #' @param width,height must be a valid CSS unit in pixels #' or a number, which will be coerced to a string and have \code{"px"} appended. #' @seealso \code{\link{renderVtree}} #' @family Shiny Functions #' @examples \dontrun{ #' library(shiny) #' library(vtree) #' #' ui <- fluidPage( #' vtreeOutput("vtree", width = "100%", height = "800px") #' ) #' #' server <- function(input, output, session) { #' output$vtree <- renderVtree({ #' vtree(FakeData,"Severity Sex", #' labelnode=list(Sex=(c("Male"="M","Female"="F"))), #' pngknit=FALSE) #' }) #' } #' #' shinyApp(ui, server) #' } #' @export vtreeOutput <- function(outputId, width = "100%", height = "100%"){ htmlwidgets::shinyWidgetOutput(outputId, 'grViz', width, height, package = 'DiagrammeR') } #' vtree widget #' #' Shiny bindings for vtree #' #' @param expr an expression that generates a variable tree #' @param env the environment in which to evaluate \code{expr}. #' @param quoted is \code{expr} a quoted expression (with \code{quote()})? This #' is useful if you want to save an expression in a variable. #' @seealso \code{\link{vtreeOutput}}, \code{\link{vtree}} #' @importFrom htmlwidgets shinyRenderWidget shinyWidgetOutput #' @family Shiny Functions #' @examples \dontrun{ #' library(shiny) #' library(vtree) #' #' ui <- fluidPage( #' vtreeOutput("vtree", width = "100%", height = "800px") #' ) #' #' server <- function(input, output, session) { #' output$vtree <- renderVtree({ #' vtree(FakeData,"Severity Sex", #' labelnode=list(Sex=(c("Male"="M","Female"="F"))), #' pngknit=FALSE) #' }) #' } #' #' shinyApp(ui, server) #' } #' @export renderVtree <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted htmlwidgets::shinyRenderWidget(expr, vtreeOutput, env, quoted = TRUE) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/shiny.R
showflow <- function(flow,getscript=FALSE,font,nodesep=0.5,ranksep=0.5,margin=0.2, nodelevels="",horiz=FALSE,width=NULL,height=NULL, graphattr="",nodeattr="",edgeattr="") { # # {show} a {flow}chart produced by flowcat or by hier. # # showscript Only show the script generated rather than displaying the flowchart? Useful for debugging. # nodesep The nodesep graph attribute. # ranksep The ranksep graph attribute. # nodePart <- paste0('node [fontname = "',font,'", fontcolor = black,shape = rectangle, color = black, tooltip=" "') nodePart <- paste0(nodePart,",margin=",margin) nodePart <- paste0(nodePart,ifelse(nodeattr=="","",","),nodeattr) nodePart <- paste0(nodePart,"]\n") graphPart <- paste0('graph [nodesep=',nodesep, ', ranksep=',ranksep,', tooltip=" "') graphPart <- paste0(graphPart,ifelse(graphattr=="","",","),graphattr) graphPart <- paste0(graphPart,']\n') script <- paste0( 'digraph vtree {\n', graphPart, nodePart) if (horiz) { script <- paste0(script,'rankdir=LR;\n') } script <- paste0(script,nodelevels) edgePart <- '\nedge[style=solid' edgePart <- paste0(edgePart,ifelse(edgeattr=="","",","),edgeattr) edgePart <- paste0(edgePart,']\n') script <- paste0(script,edgePart, flow$edges,"\n\n",flow$labelassign,sep="\n") script <- paste0(script,"\n}\n") if (getscript) { return(script) } flowchart <- DiagrammeR::grViz(script,width=width,height=height) flowchart }
/scratch/gouwar.j/cran-all/cranData/vtree/R/showflow.R
splitlines <- function (x, width = 10, sp = "\n", at = c(" ", "-", "+", "_", "=", "/"), same = FALSE) { # NOTE: I removed forward slash from the default at argument, # because it caused a problem with HTML where / is important. # e.g. <BR/> if (any(is.na(x))) stop("Missing value in vector of strings.") n <- nchar(x) nsp <- nchar(sp) result <- rep("", length(x)) splits <- rep(0, length(x)) if (is.null(x) || (length(x)==0)) return(NULL) for (i in seq_len(length(x))) { count <- 0 start <- 1 for (j in 1:(n[i])) { count <- count + 1 char <- substring(x[i], j, j) if (char %in% sp) { count <- 0 } else { if (char %in% at) { if (count > width) { if (char == " ") { end <- j - 1 } else { end <- j } result[i] <- paste0(result[i], substring(x[i], start, end), sp) start <- j + 1 count <- 0 splits[i] <- splits[i] + 1 } } } } if (start <= n[i]) result[i] <- paste0(result[i], substring(x[i], start, n[i])) } if (same) { maxsplits <- max(splits) for (i in seq_len(length(x))) { while (splits[i] < maxsplits) { result[i] <- paste0(result[i], sp) splits[i] <- splits[i] + 1 } } } result }
/scratch/gouwar.j/cran-all/cranData/vtree/R/splitlines.R
#' @importFrom stats median quantile sd summaryNodeFunction <- function (u, varname, value, args) { # Conditional substitution: whereas gsub evaluates the replacement expression # even if x doesn't match pattern, this function only evaluates the # replacement expression if x matches pattern. condsub <- function(pattern,replacement,x) { if (length(grep(pattern,x))>0) { gsub(pattern,replacement,x) } else { x } } fullsummary <- function(w,digits,thousands,varname) { nMissing <- sum(is.na(w)) if (length(w)<=3) { return(paste0(varname,"\n",paste(around(w,digits=digits,thousands=thousands),collapse=", "))) } if (nMissing==length(w)) { return(paste0(varname,"\n","missing ",nMissing)) } med <- around(as.numeric(stats::median(w,na.rm=TRUE)), digits=digits,thousands=thousands) lo <- around(as.numeric(min(w,na.rm=TRUE)), digits=digits,thousands=thousands) hi <- around(as.numeric(max(w,na.rm=TRUE)), digits=digits,thousands=thousands) q25 <- around(quantile(w,0.25,na.rm=TRUE), digits=digits,thousands=thousands) q75 <- around(quantile(w,0.75,na.rm=TRUE), digits=digits,thousands=thousands) mn <- around(mean(w,na.rm=TRUE), digits=digits,thousands=thousands) s <- around(stats::sd(w,na.rm=TRUE), digits=digits,thousands=thousands) paste0( varname,"\n", "missing ",nMissing,"\n", "mean ",mn," SD ",s,"\n", "med ",med," IQR ",q25,", ",q75,"\n", "range ",lo,", ",hi) } medianfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%median% : expected a numeric variable.") } nMissing <- sum(is.na(w)) m <- around(stats::median(w,na.rm=TRUE), digits=digits,thousands=thousands) if (nMissing>0) { paste0(m," mv=",nMissing) } else { m } } minfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%min% : expected a numeric variable.") } nMissing <- sum(is.na(w)) m <- around(min(w,na.rm=TRUE), digits=digits,thousands=thousands) if (nMissing>0) { paste0(m," mv=",nMissing) } else { m } } maxfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%max% : expected a numeric variable.") } nMissing <- sum(is.na(w)) m <- around(max(w,na.rm=TRUE), digits=digits,thousands=thousands) if (nMissing>0) { paste0(m," mv=",nMissing) } else { m } } IQRfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%IQR% : expected a numeric variable.") } nMissing <- sum(is.na(w)) i <- paste0( around(qntl(w,0.25,na.rm=TRUE), digits=digits,thousands=thousands),", ", around(qntl(w,0.75,na.rm=TRUE), digits=digits,thousands=thousands)) if (nMissing>0) { paste0(i," mv=",nMissing) } else { i } } rangefunc <- function(w,digits,thousands,na.rm=FALSE) { if (!(is.numeric(w) | is.logical(w))) { stop("%range% : expected a numeric variable.") } #print(w) if (na.rm) w <- w[!is.na(w)] nMissing <- sum(is.na(w)) if (length(w[!is.na(w)])==0) { if (nMissing==0) { "No values" } else { paste0("mv=",nMissing) } } else { r <- paste0( around(min(w,na.rm=TRUE), digits=digits,thousands=thousands),", ", around(max(w,na.rm=TRUE), digits=digits,thousands=thousands)) if (nMissing>0) { paste0(r," mv=",nMissing) } else { r } } } SDfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%SD% : expected a numeric variable.") } nMissing <- sum(is.na(w)) s <- around(stats::sd(w,na.rm=TRUE), digits=digits,thousands=thousands) if (nMissing>0) { paste0(s," mv=",nMissing) } else { s } } sumfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%sum% : expected a numeric variable.") } nMissing <- sum(is.na(w)) s <- around(sum(w,na.rm=TRUE), digits=digits,thousands=thousands) if (nMissing>0) { paste0(s," mv=",nMissing) } else { s } } meanfunc <- function(w,digits,thousands) { if (!(is.numeric(w) | is.logical(w))) { stop("%mean% : expected a numeric variable.") } nMissing <- sum(is.na(w)) m <- around(mean(w,na.rm=TRUE), digits=digits,thousands=thousands) if (nMissing>0) { paste0(m," mv=",nMissing) } else { m } } justpct <- function(w,digits=2,vp=TRUE,empty="") { if (!(is.numeric(w) | is.logical(w))) { stop("%pct% : expected a logical or 0-1 variable.") } if (vp) { num <- sum(w==1,na.rm=TRUE) den <- length(w) - sum(is.na(w)) } else { num <- sum(w==1,na.rm=TRUE) den <- length(w) } pctString <- paste0(around(100*num/den,digits),"%") if (den==0) { pctString <- empty } if (any(is.na(w))) pctString <- paste0(pctString," mv=",sum(is.na(w))) pctString } nAndpct <- function(w,digits=2,thousands,vp=TRUE,empty="",varname="") { if (!(is.numeric(w) | is.logical(w))) { stop("%npct% : expected a logical or 0-1 variable.") } if (vp) { num <- sum(w==1,na.rm=TRUE) den <- length(w) - sum(is.na(w)) } else { num <- sum(w==1,na.rm=TRUE) den <- length(w) } npctString <- paste0(format(num,big.mark=thousands)," (", around(100*num/den,digits),"%)") if (den==0) { npctString <- empty } if (any(is.na(w))) npctString <- paste0(npctString," mv=",sum(is.na(w))) if (!is.na(varname) & varname!="") npctString <- paste0(varname,": ",npctString) npctString } freqfunc <- function(w,digits=2,cdigits=2,thousands,vp=TRUE,empty="", pcs = "%", showN = FALSE, shown = TRUE, showp = TRUE, nmiss = FALSE, nmiss0 = FALSE, includemiss = TRUE, showzero = FALSE, percentfirst = FALSE, sep = ", ",sort=FALSE,varname="",na.rm = FALSE) { x <- w if (na.rm) { x <- x[!is.na(x)] } x <- around(x,digits=cdigits) nmissString <- "" missingNum <- sum(is.na(x)) if (nmiss) { nmissString <- paste0("mv=", missingNum) if (!vp) nmissString <- paste0("[", nmissString, "]") nmissString <- paste0(" ^", nmissString, "^") if (!nmiss0 & missingNum == 0) nmissString <- "" } if (vp) { x <- x[!is.na(x)] } if (is.logical(x)) { x <- factor(x, c("FALSE", "TRUE")) } if (length(x) == 0 & (!is.factor(x))) return(empty) tab <- table(x, exclude = NULL) if (sort) { tab <- rev(sort(tab)) } if (any(is.na(names(tab)))) names(tab)[is.na(names(tab))] <- "NA" result <- "" if (shown) { pr <- paste(result) if (!showzero) pr[pr == "0"] <- "" result <- paste0(pr, tab) if (showN) result <- paste0(result, "/", length(x)) } if (showp) { pct <- paste0(around(100 * as.numeric(tab)/sum(tab), digits=digits,thousands=thousands),pcs) if (shown) { pct <- paste0(" (",pct,")") } pct[pct==" (NaN%)"] <- "" result <- paste0(result,pct) } if (percentfirst & shown & showp) { result <- paste(around(100 * as.numeric(tab)/sum(tab), digits=digits,thousands=thousands), pcs, sep = "") result <- paste0(result, " (", tab) if (showN) result <- paste0(result, "/", length(x)) result <- paste0(result, ")") } if (!showzero) result[!is.na(tab) & tab == 0] <- "" result <- paste0(result, nmissString) names(result) <- names(tab) result <- result[names(result) != "NA"] if (includemiss) { if (missingNum>0) { # | showzero) { result["NA"] <- missingNum } } RESULT <- paste0(paste0(names(result),": ",result),collapse=sep) if (varname!="") RESULT <- paste0(varname,"\n",RESULT) RESULT } qntl <- function(w,...) { if (!(is.numeric(w) | is.logical(w))) { stop("%q% : expected a numeric variable.") } if (any(is.na(x))) { NA } else { stats::quantile(x,...) } } #--- Body of code starts here ----------------------------------------------- thousands <- args$thousands sepN <- args$sepN if (is.null(args$digits)) args$digits <- 1 if (is.null(args$cdigits)) args$cdigits <- 2 if (is.null(args$na.rm)) args$na.rm <- TRUE if (is.null(args$root)) { args$root <- FALSE } if (is.null(args$leaf)) { args$leaf <- FALSE } nargs <- length(args$var) RESULT <- rep("",nargs) for (i in 1:nargs) { var <- args$var[i] original_var <- args$original_var[i] ShowSimpleSummary <- TRUE Formatstring <- FALSE SortIt <- TRUE if (args$format[i]=="") { SortIt <- TRUE FormatString <- FALSE ShowSimpleSummary <- TRUE } # else { # SortIt <- FALSE # FormatString <- TRUE # ShowSimpleSummary <- FALSE # } if (length(grep("%v%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%list%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%listlines%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%list_%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqpct%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqpctx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freq%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqpctlines%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqpct_%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqpctx_%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqlines%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freq_%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%freqx_%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%mv%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%nonmv%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%npct%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%pct%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%mean%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%meanx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%sum%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%sumx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%median%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%medianx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%SD%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%SDx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%min%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%minx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%max%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%maxx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%range%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%rangex%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%IQR%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%IQRx%" ,args$format[i])>0)) ShowSimpleSummary <- FALSE if (length(grep("%combo%",args$format[i]))>0) { ShowCombinations <- TRUE } else { ShowCombinations <- FALSE } if (length(grep("%sort%",args$format[i]))>0) { SortIt <- TRUE } else if (length(grep("%nosort%",args$format[i]))>0) { SortIt <- FALSE } # check if it's a stem StemSpecified <- StarSpecified <- HashmarkSpecified <- FALSE if (length(grep("\\*$",var))>0) { StarSpecified <- TRUE ShowSimpleSummary <- FALSE thevar <- sub("(\\S+)\\*$","\\1",var) expanded_stem <- names(u)[grep(paste0("^",thevar,".*$"),names(u))] none <- rep(TRUE,nrow(u)) if (ShowCombinations) { y <- rep("",nrow(u)) for (j in 1:length(expanded_stem)) { y <- ifelse(is.na(u[[expanded_stem[j]]]), paste0("NA(",expanded_stem[j],")"), ifelse(u[[expanded_stem[j]]]==1, ifelse(y=="",expanded_stem[j],paste0(y,"+",expanded_stem[j])),y)) } } else { y <- NULL for (j in 1:length(expanded_stem)) { none <- none & u[[expanded_stem[j]]]==0 y <- c(y,rep(expanded_stem[j],sum(u[[expanded_stem[j]]],na.rm=TRUE))) y <- c(y,rep(paste0("NA(",expanded_stem[j],")"),sum(is.na(u[[expanded_stem[j]]])))) } } if (ShowCombinations) { y[y %in% ""] <- "*None" } } else { y <- u[[var]] } show <- TRUE if (!is.null(args$sf)) { show <- args$sf[[i]](u) } if (show) { format <- args$format[i] digits <- args$digits cdigits <- args$cdigits na.rm <- args$na.rm missingNum <- sum(is.na(y)) nonmissingNum <- sum(!is.na(y)) if (na.rm) { x <- y[!is.na(y)] if (is.null(x)) x <- NA } else { x <- y } result <- format ShowNodeText <- TRUE # check the %var=V% and %node=N% codes if (length(grep("%var=([^%]+)%",result))>0) { varspec <- sub("(.*)%var=([^%]+)%(.*)","\\2",result) if (varspec==varname) { if (length(grep("%node=([^%]+)%",result))>0) { nodespec <- sub("(.*)%node=([^%]+)%(.*)","\\2",result) if (!is.na(value) & (nodespec==value)) { ShowNodeText <- TRUE } else { ShowNodeText <- FALSE } } else { ShowNodeText <- TRUE } } else { ShowNodeText <- FALSE } } else { if (length(grep("%node=([^%]+)%",result))>0) { nodespec <- sub("(.*)%node=([^%]+)%(.*)","\\2",result) if (!is.na(value) & (nodespec==value)) { ShowNodeText <- TRUE } else { ShowNodeText <- FALSE } } } y_event <- NULL if (length(grep("%pct=([^%]+)%",result))>0) { pct_arg <- sub( "(.*)%pct=([^%]+)%(.*)","\\2",result) y_event <- y==pct_arg } if (length(grep("%npct=([^%]+)%",result))>0) { npct_arg <- sub( "(.*)%npct=([^%]+)%(.*)","\\2",result) y_event <- y==npct_arg } if (!args$leaf) { if (length(grep("%leafonly%",result))>0) { ShowNodeText <- FALSE } } if (args$root) { if (length(grep("%noroot%",result))>0) { ShowNodeText <- FALSE } } TruncNodeText <- FALSE if (length(grep("%trunc=([^%]+)%",result))>0) { truncval <- as.numeric(sub("(.*)%trunc=([^%]+)%(.*)","\\2",result)) TruncNodeText <- TRUE } # Format %list% output tabval <- tableWithoutSort(around(sort(y,na.last=TRUE),digits=cdigits,thousands=thousands),exclude=NULL) countval <- paste0(" (n=",tabval,")") countval[tabval==1] <- "" listOutput <- paste0(paste0(names(tabval),countval),collapse=", ") listLinesOutput <- paste0(paste0(names(tabval),countval),collapse=sepN) if (ShowNodeText) { if (length(x)==0 || !is.numeric(x)) { minx <- maxx <- NA } else { minx <- min(x) maxx <- max(x) } if (ShowSimpleSummary) { if (is.numeric(y) && length(unique(y))>3) { result <- paste0("\n",fullsummary(y,digits=cdigits,thousands=thousands,varname=var)) } else if (is.logical(y) || (is.numeric(y) && (all(unique(y) %in% c(NA,0,1))))) { result <- paste0("\n",nAndpct(y,digits=digits,thousands=thousands,varname=original_var)) } else { result <- paste0("\n",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sep="\n",sort=SortIt,varname=original_var,showzero=TRUE)) } } else if (StemSpecified && !FormatString) { result <- paste0("\n",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sort=SortIt,sep="\n",showp=FALSE)) } else { result <- gsub("%var=[^%]+%","",result) result <- gsub("%node=[^%]+%","",result) result <- gsub("%trunc=(.+)%","",result) result <- gsub("%noroot%","",result) result <- gsub("%combo%","",result) result <- gsub("%sort%","",result) result <- gsub("%nosort%","",result) result <- gsub("%leafonly%","",result) result <- gsub("%v%",args$var[i],result) result <- gsub("%list%",listOutput,result) result <- gsub("%listlines%",listLinesOutput,result) result <- gsub("%list_%",listLinesOutput,result) result <- gsub("%freqpct%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sort=SortIt),result) result <- gsub("%freqpctx%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sort=SortIt,na.rm=TRUE),result) result <- gsub("%freq%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,showp=FALSE,sort=SortIt),result) result <- gsub("%freqx%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,showp=FALSE,sort=SortIt,na.rm=TRUE),result) result <- gsub("%freqpctlines%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sep="\n",sort=SortIt),result) result <- gsub("%freqpct_%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sep="\n",sort=SortIt),result) result <- gsub("%freqpctx_%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,sep="\n",sort=SortIt,na.rm=TRUE),result) result <- gsub("%freqlines%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,showp=FALSE,sep="\n",sort=SortIt),result) result <- gsub("%freq_%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,showp=FALSE,sep="\n",sort=SortIt),result) result <- gsub("%freqx_%",freqfunc(y,digits=digits,cdigits=cdigits,thousands=thousands,showp=FALSE,sep="\n",sort=SortIt,na.rm=TRUE),result) result <- gsub("%mv%",paste0(missingNum),result) result <- gsub("%nonmv%",paste0(nonmissingNum),result) result <- condsub("%npct%",nAndpct(y,digits=digits,thousands=thousands),result) result <- condsub("%pct%",justpct(y,digits=digits),result) result <- condsub("%mean%", meanfunc(y,digits=cdigits,thousands=thousands),result) result <- condsub("%meanx%", around(mean(x), digits = cdigits,thousands=thousands),result) result <- condsub("%sum%", sumfunc(y,digits=cdigits,thousands=thousands),result) result <- condsub("%sumx%", around(sum(x), digits = cdigits,thousands=thousands),result) result <- condsub("%median%", medianfunc(y,digits=cdigits,thousands=thousands),result) result <- condsub("%medianx%", around(stats::median(x), digits = cdigits,thousands=thousands), result) result <- condsub("%SD%", SDfunc(y,digits=cdigits,thousands=thousands), result) result <- condsub("%SDx%", around(stats::sd(x), digits = cdigits,thousands=thousands), result) result <- condsub("%min%", minfunc(y, digits = cdigits,thousands=thousands), result) result <- condsub("%minx%", around(min(x), digits = cdigits,thousands=thousands), result) result <- condsub("%max%", maxfunc(y, digits = cdigits,thousands=thousands), result) result <- condsub("%maxx%", around(max(x), digits = cdigits,thousands=thousands), result) result <- condsub("%range%", rangefunc(y,digits=cdigits,thousands=thousands), result) result <- condsub("%rangex%", rangefunc(y,digits=cdigits,thousands=thousands,na.rm=TRUE), result) result <- condsub("%IQR%", IQRfunc(y,digits=cdigits,thousands=thousands), result) result <- condsub("%IQRx%", paste0( around(qntl(x,0.25), digits = cdigits,thousands=thousands),", ", around(qntl(x,0.75), digits = cdigits,thousands=thousands)), result) repeat { if (length(grep("%(p)([0-9]+)%", result)) == 0) break quant <- sub("(.*)%(p)([0-9]+)%(.*)", "\\3", result) if (quant != "") { qq <- around(qntl(x, as.numeric(quant)/100), digits=digits,thousands=thousands) result <- sub(paste0("%p", quant,"%"), qq, result) } } } } else { result <- "" } if (TruncNodeText) { if (nchar(result)>truncval) { RESULT[i] <- paste0(substr(result,1,truncval),"...") } else { RESULT[i] <- result } } else { RESULT[i] <- result } } } RESULT }
/scratch/gouwar.j/cran-all/cranData/vtree/R/summaryNodeFunction.R
#' @title Create a Shiny vtree, with svg-pan-zoom functionality. #' #' @param ... parameters to be passed to `vtree` #' #' @description #' `svtree` uses Shiny and the svg-pan-zoom JavaScript library to #' create a variable tree with panning and zooming functionality. #' The mousewheel allows you to zoom in or out. #' The variable tree can also be dragged to a different position. #' #' @details The svg-pan-zoom library webpage is #' https://github.com/ariutta/svg-pan-zoom #' #' @export #' svtree <- function(...) { shiny::shinyApp( shiny::fluidPage( use_svgzoom(), shiny::tags$head(shiny::tags$style(shiny::HTML("body {background-color: #9c9ca096;}"))), vtreeOutput("vtree", width = "100%", height = "500px")), function(input, output, session) { output$vtree <- renderVtree(vtree(...,pngknit=FALSE)) }) }
/scratch/gouwar.j/cran-all/cranData/vtree/R/svtree.R
tableWithoutSort <- function(x,exclude = NA) { tab <- table(x,exclude=exclude) u <- unique(x) if (any(is.na(u))) { u <- u[!is.na(u)] ustr <- as.character(u) count <- tab[ustr] count <- c(count,tab[is.na(names(tab))]) } else { ustr <- as.character(u) #count <- tab[ustr] count <- tab[match(ustr,names(tab))] } names(dimnames(count)) <- NULL count }
/scratch/gouwar.j/cran-all/cranData/vtree/R/tableWithoutSort.R
#' vtree: a tool for calculating and drawing variable trees. #' #' @description #' vtree is a flexible tool for generating variable trees — #' diagrams that display information about nested subsets of a data frame. #' Given simple specifications, #' the \code{vtree} function produces these diagrams and automatically #' labels them with counts, percentages, and other summaries. #' #' With vtree, you can: #' \itemize{ #' \item explore a data set interactively, and #' \item produce customized figures for reports and publications. #' } #' #' For a comprehensive introduction see the \href{../doc/vtree.html}{vignette}. #' #' @author Nick Barrowman <[email protected]> #' #' @seealso #' \itemize{ #' \item \url{https://nbarrowman.github.io/vtree} #' \item \url{https://github.com/nbarrowman/vtree} #' \item Report bugs at \url{https://github.com/nbarrowman/vtree/issues} #' } #' #' @docType package #' @name vtree-package NULL #' #' Draw a variable tree #' #' @description #' Variable trees display information about nested subsets of a data frame, #' in which the subsetting is defined by the values of categorical variables. #' #' @author Nick Barrowman <[email protected]> #' #' @param data Required: Data frame, or a single vector. #' @param vars Required (unless \code{data} is a single vector): #' Variables to use for the tree. Can be #' (1) a character string of whitespace-separated variable names, #' (2) a vector of variable names, #' (3) a formula without a left-hand side, #' e.g. \code{~ Age + Sex}, #' but note that extended variable specifications cannot be used in this case. #' #' @param showuniform Show a variable even when it only has one value? #' @param hideconstant Hide a variable if its only value is one of the specified strings. #' #' @param words A list of named vectors of values. #' Used to build a variable tree #' representing all permutations of these values. #' No counts will be shown. #' #' @param prune,keep,prunebelow,follow #' List of named vectors that specify pruning. #' (see \strong{Pruning} below) #' @param tprune,tkeep,tprunebelow,tfollow #' List of lists of named vectors that specify "targeted" pruning. #' (see \strong{Pruning} below) #' #' @param prunesmaller Prune any nodes with count less than specified number. #' @param prunebigger Prune any nodes with count greater than specified number. #' @param splitspaces When \code{vars} is a character string, #' split it by spaces to get variable names? #' It is only rarely necessary to use this parameter. #' This should only be \code{FALSE} when a single variable name #' that contains spaces is specified. #' @param horiz Should the tree be drawn horizontally? #' (i.e. root node on the left, with the tree growing to the right) #' @param labelnode List of vectors used to change how values of variables are displayed. #' The name of each element of the #' list is one of the variable names in \code{vars}. #' Each element of the list is a vector of character strings, #' representing the values of the variable. #' The names of the vector represent the labels to be used in place of the values. #' @param tlabelnode A list of vectors, each of which specifies a particular node, #' as well as a label for that node (a "targeted" label). #' The names of each vector specify variable names, #' except for an element named \code{label}, which specifies the label to use. #' @param labelvar A named vector of labels for variables. #' #' @param varlabelloc A named vector of vertical label locations #' ("t", "c", or "b" for top, center, or bottom, respectively) #' for nodes of each variable. #' (Sets the Graphviz \code{labelloc} attribute.) #' @param title Label for the root node of the tree. #' @param font Font. #' @param varnamepointsize Font size (in points) to use when displaying variable names. #' @param varnamebold Show the variable name in bold? #' @param legendpointsize Font size (in points) to use when displaying legend. #' @param sameline Display node label on the same line as the count and percentage? #' A single value (with no names) specifies the setting for all variables. #' A logical vector of \code{TRUE} for named variables is interpreted as #` \code{TRUE} for those variables and \code{FALSE} for all others. #' A logical vector of \code{FALSE} for named variables is interpreted as #' \code{FALSE} for those variables and \code{TRUE} for all others. #' @param check.is.na Replace each variable named in \code{vars} with a logical vector indicating #' whether or not each of its values is missing? #' @param summary A character string used to specify summary statistics to display in the nodes. #' See \strong{Displaying summary information} below for details. #' @param tsummary A list of character-string vectors. #' The initial elements of each character string vector point to a specific node. #' The final element of each character string vector is a summary string, #' with the same structure as \code{summary}. #' @param text A list of vectors containing extra text to add to #' nodes corresponding to specified values of a specified variable. #' The name of each element of the list #' must be one of the variable names in \code{vars}. #' Each element is a vector of character strings. #' The names of the vector identify the nodes to which the text should be added. #' @param ttext A list of vectors, each of which specifies a particular node, #' as well as text to add to that node ("targeted" text). #' The names of each vector specify variable names, #' except for an element named \code{text}, which specifies the text to add. #' @param HTMLtext Is the text formatted in HTML? #' @param splitwidth,vsplitwidth #' The minimum number of characters before an automatic #' linebreak is inserted. #' \code{splitwidth} is for node labels, \code{vsplitwidth} is for variable names. #' @param vp Use \emph{valid percentages}? #' Valid percentages are computed by first excluding any missing values, #' i.e. restricting attention to the set of "valid" observations. #' The denominator is thus the number of non-missing observations. #' When \code{vp=TRUE}, nodes for missing values show the number of missing values #' but do not show a percentage; #' all the other nodes show valid percentages. #' When \code{vp=FALSE}, all nodes (including nodes for missing values) #' show percentages of the total number of observations. #' @param getscript Instead of displaying the variable tree, #' return the DOT script as a character string? #' #' @param digits,cdigits #' Number of decimal digits to show in percentages (\code{digits}) #' and in continuous values displayed via the summary parameter (\code{cdigits}). #' #' @param fillnodes [Color] Fill the nodes with color? #' @param gradient [Color] Use gradients of fill color across the values of each variable? #' A single value (with no names) specifies the setting for all variables. #' A logical vector of \code{TRUE} values for named variables is interpreted as #' \code{TRUE} for those variables and \code{FALSE} for all others. #' A logical vector of \code{FALSE} values for named variables is interpreted as #' \code{FALSE} for those variables and \code{TRUE} for all others. #' @param revgradient [Color] Should the gradient be reversed (i.e. dark to light instead of light to dark)? #' A single value (with no names) specifies the setting for all variables. #' A logical vector of \code{TRUE} values for named variables is interpreted as #` \code{TRUE} for those variables and \code{FALSE} for all others. #' A logical vector of \code{FALSE} values for named variables is interpreted as #' \code{FALSE} for those variables and \code{TRUE} for all others. #' @param sortfill [Color] Sort colors in order of node count? #' When a \code{gradient} fill is used, this results in #' the nodes with the smallest counts having the lightest shades #' and the nodes with the largest counts having the darkest shades. #' @param colorvarlabels [Color] Color the variable labels? #' @param fillcolor [Color] A named vector of colors for filling the nodes of each variable. #' If an unnamed, scalar color is specified, #' all nodes will have this color. #' @param specfill [Color] A list with specified color values for specified variables. #' @param NAfillcolor [Color] Fill-color for missing-value nodes. #' If \code{NULL}, fill colors of missing value nodes will be consistent #' with the fill colors in the rest of the tree. #' @param rootfillcolor [Color] Fill-color for the root node. #' @param palette [Color] A vector of palette numbers (which can range between 1 and 14). #' The names of the vector indicate the corresponding variable. #' See \strong{Palettes} below for more information. #' @param singlecolor [Color] When a variable has a single value, #' this parameter is used to specify whether nodes should have a #' (1) light shade, (2) a medium shade, or (3) a dark shade. #' specify \code{singlecolor=1} to assign a light shade. #' @param color [Color] A vector of color names for the \emph{outline} of the nodes in each layer. #' @param colornodes [Color] Color the node outlines? #' @param plain [Color] Use "plain" settings? #' These settings are as follows: for each variable all nodes are the same color, #' namely a shade of blue (with each successive variable using a darker shade); #' all variable labels are black; and the \code{squeeze} parameter is set to 0.6. #' #' @param width,height #' Width and height (in pixels) to be passed to \code{DiagrammeR::grViz}. #' #' #' @param showpct,showlpct #' Show percentage? \code{showpct} is for nodes, \code{showlpct} is for legends. #' A single value (with no names) specifies the setting for all variables. #' A logical vector of \code{TRUE} for named variables is interpreted as #` \code{TRUE} for those variables and \code{FALSE} for all others. #' A logical vector of \code{FALSE} for named variables is interpreted as #' \code{FALSE} for those variables and TRUE for all others. #' @param showvarinnode Show the variable name in each node? #' @param shownodelabels Show node labels? #' A single value (with no names) specifies the setting for all variables. #' Otherwise, a named logical vector indicates which variables should have their #' node labels shown. #' If the vector consists of only \code{TRUE} values, #' it is interpreted as \code{TRUE} for those variables and \code{FALSE} for all others. #' Similarly, if the vector consists of only \code{FALSE} values, #' it is interpreted as \code{FALSE} for those variables and \code{TRUE} for all others. #' #' @param showvarnames Show the name of the variable next to each layer of the tree? #' @param showcount Show count in each node? #' A single value (with no names) specifies the setting for all variables. #' A logical vector of \code{TRUE} for named variables is interpreted as #` \code{TRUE} for those variables and \code{FALSE} for all others. #' A logical vector of \code{FALSE} for named variables is interpreted as #' \code{FALSE} for those variables and \code{TRUE} for all others. #' @param prefixcount Text that will precede each count. #' @param showrootcount Should count in root node? #' @param showlegend Show legend (including marginal frequencies) for each variable? #' @param showlegendsum Show summary information in the legend? #' (Provided \code{summary} has been specified). #' @param showempty Show nodes that do not contain any observations? #' #' @param seq Display the variable tree using \emph{sequences}? #' Each unique sequence (i.e. pattern) of values will be shown separately. #' The sequences are sorted from least frequent to most frequent. #' @param pattern Display the variable tree using \emph{patterns}? #' These are the same as \code{seq}, but lines without arrows are drawn, #' and instead of a sequence variable, a pattern variable is shown. #' @param ptable Generate a pattern table instead of a variable tree? #' Only applies when \code{pattern=TRUE}. #' @param showroot Show the root node? #' When \code{seq=TRUE}, it may be useful to set \code{showroot=FALSE}. #' @param Venn Display multi-way set membership information? #' This provides an alternative to a Venn diagram. #' This sets \code{showpct=FALSE} and \code{shownodelabels=FALSE}. #' Assumption: all of the specified variables are logicals or 0/1 numeric variables. #' #' @param choicechecklist When REDCap checklists are specified using the \code{stem:} syntax, #' automatically extract the names of choices and use them as variable names? #' #' @param mincount,maxcount #' Minimum or maximum count to include in a pattern tree or pattern table. #' (\code{maxcount} overrides \code{mincount}.) #' #' @param pxwidth,pxheight #' Width and height of the PNG bitmap to be rendered #' when \code{vtree} is called from R Markdown. #' If neither \code{pxwidth} nor \code{pxheight} is specified, #' \code{pxwidth} is automatically set to 2000 pixels. #' #' @param trim (LaTeX Sweave only.) Crop the image using a feature #' of \code{\\includegraphics}. #' Vector of bp (big points) to trim in the order #' left, lower, right, upper. #' #' @param imagewidth,imageheight #' Character strings representing width and height of the PNG image #' to be rendered when \code{vtree} is called from R Markdown, #' e.g. \code{"4in"} #' If neither \code{imageheight} nor \code{imagewidth} is specified, #' \code{imageheight} is set to 3 inches. #' #' @param maxNodes An error occurs if the number of nodes exceeds \code{maxNodes}. #' #' @param unchecked,checked #' Vector of character strings interpreted as "unchecked" and "checked" respectively. #' #' @param just Text justification ("l"=left, "c"=center, "r"=right). #' @param justtext Like \code{just}, but only for extra text, like summaries. #' @param thousands Thousands separator for big numbers. #' @param folder,format,imageFileOnly,pngknit #' Control image file generation. #' \code{folder}: a path to a folder where image file will be stored. #' \code{format}: "png" or "pdf" format. #' \code{imageFileOnly}: should an image file should be produced but not displayed? #' \code{pngknit}: generate a PNG file when called during knit? #' (See \strong{Knitr, R Markdown, Sweave} below for more information.) #' #' @param auto Automatically choose variables? (\code{vars} should not be specified) #' #' @param rounded [Graphviz] Use rounded boxes for nodes? #' #' @param varminwidth,varminheight #' [Graphviz] Named vector of minimum initial widths or heights for nodes of each variable. #' #' \code{varminwidth} sets the Graphviz \code{width} attribute. #' \code{varminheight} sets the Graphviz \code{height} attribute. #' #' @param squeeze [GraphViz] The degree (between 0 and 1) to which the tree will be "squeezed". #' This controls two Graphviz parameters: \code{margin} and \code{nodesep}. #' @param arrowhead [Graphviz] arrowhead style. Defaults to \code{"normal"}. #' Other choices include \code{"none"}, \code{"vee"}. #' @param nodesep,ranksep,margin #' [Graphviz] attributes for node separation amount, #' rank separation amount, and node margin. #' #' @param graphattr,nodeattr,edgeattr #' [Graphviz] Character string: Graphviz attributes for the graph, node, and edge respectively. #' #' @param nodefunc,nodeargs #' Node function and node arguments (see \strong{Node functions} below). #' @param verbose Report additional details? #' @param runsummary A list of functions, with the same length as \code{summary}. #' Each function must take a data frame as its sole argument, #' and return a logical value. #' Each string in \code{summary} will only be interpreted if #' the corresponding logical value is \code{TRUE}. #' the corresponding string in \code{summary} will be evaluated. #' @param retain Vector of names of additional variables in the data frame that need to be #' available to execute the functions in \code{runsummary}. #' #' @param parent,last [Internal use only.] Node number of parent and last node. #' #' @param root [Internal use only.] Is this the root node of the tree? #' @param subset [Internal use only.] A vector representing the subset of observations. #' @param numsmallernodes [Internal use only.] Counting nodes that were suppressed by prunesmaller. #' @param sumsmallernodes [Internal use only.] Summing nodes that were suppress by prunesmaller. #' @param numbiggernodes [Internal use only.] Counting nodes that were suppressed by prunebigger. #' @param sumbiggernodes [Internal use only.] Summing nodes that were suppress by prunebigger. #' @param as.if.knit (Deprecated) Behave as if called while knitting? #' @param prunelone (Deprecated) A vector of values specifying "lone nodes" (of \emph{any} variable) to prune. #' A lone node is a node that has no siblings (an "only child"). #' @param pruneNA (Deprecated) Prune all missing values? #' This is problematic because "valid" percentages #' are hard to interpret when NAs are pruned. #' @param lsplitwidth (Deprecated) In legends, the minimum number of characters before an automatic #' linebreak is inserted. #' @param showlevels (Deprecated) Same as showvarnames. #' @param z (Deprecated) This was replaced by the \code{data} parameter #' #' @return #' The value returned by \code{vtree} varies #' depending on both the parameter values specified #' and the context in which \code{vtree} is called. #' #' First, there are two special cases where \code{vtree} does not show a variable tree: #' #' \itemize{ #' \item If \code{ptable=TRUE}, the return value is a data frame representing a pattern table. #' \item Otherwise, if \code{getscript=TRUE}, the return value is a character string, #' consisting of a DOT script that describes the variable tree. #' } #' #' If neither of the above cases applies, the return value is as follows. #' If knitting is \emph{not} taking place #' (such as when \code{vtree} is used \strong{interactively}): #' \itemize{ #' \item the return value is an object of class \code{htmlwidget} (see \link[DiagrammeR]{DiagrammeR}). #' It will intelligently print itself into HTML in a variety of contexts #' including the R console, within R Markdown documents, #' and within Shiny output bindings. #' #' The \code{info} attribute of the return object is a list whose top #' level represents the root node of the tree. #' Within this list is a list named after the first variable in the tree. #' In turn, within this list are lists named after the observed #' values of that variable. #' In turn, each of these lists is an element named after #' the next variable in the tree. #' And so on. #' The root element as well as each list element named after a value of a variable also #' contains elements \code{.n} (representing the number of observations), #' \code{.pct} (representing the percentage), and #' \code{.txt} (representing additional text such as summaries). #' #' } #' #' If knitting \emph{is} taking place: #' \itemize{ #' \item If \code{pngknit=TRUE} (the default), #' the return value is a character string of #' pandoc markdown code to embed a PNG file with fully-specified path. #' The character string will have class \code{knit_asis} so that #' knitr will treat it as is #' (the effect is the same as the chunk option results = 'asis') #' when it is written to the output. (See \code{?knitr::asis_output}) #' \item If \code{pngknit=FALSE}, the return value is the same as when knitting is not #' taking place, i.e. an object of class \code{htmlwidget}. #' } #' #' @section Knitr, R Markdown, Sweave: #' If \code{folder} is not specified and knitting to LaTeX, #' the folder will be set to the value of \code{knitr::opts_chunk$get("fig.path")}. #' (If this folder does not exist, it will be created.) #' If \code{folder} is not specified and knitting to markdown, #' a temporary folder will be used. #' #' If \code{format} is not specified and knitting is taking place, #' then a PNG file is generated, unless a LaTeX document is #' being generated (e.g. via Sweave), in which case a PDF file is generated. #' PNG image files will end in \code{.png}. #' PDF image files will end in \code{.pdf}. #' #' As noted in the \strong{Value} section above, #' \code{vtree} has special support for R Markdown. #' #' By default, when knitting an R Markdown file, #' \code{vtree} generates PNG files and embeds them automatically in the output document. #' This feature is needed when knitting to a \code{.docx} file. #' When knitting to HTML, it is not necessary to generate PNG files #' because HTML browsers can directly display htmlwidgets. #' #' To generate htmlwidgets instead of PNG files, specify \code{pngknit=FALSE}. #' (Note, however, that there are some advantages to embedding PNG files in an HTML file. #' For example, #' some browsers perform poorly when numerous htmlwidgets are included in an HTML file.) #' #' When PNG files are generated, they are stored by default in a temporary folder. #' The folder can also be specified using the \code{folder} parameter. #' (Using the base R function \code{options}, #' a custom option \code{vtree_folder} is used to automatically keep track of this.) #' Successive PNG files generated by an R Markdown file #' are named \code{vtree001.png}, \code{vtree002.png}, etc. #' (A custom option \code{vtree_count} is used to automatically keep track of the number of PNG files.) #' #' @section Pruning: #' Each of the parameters \code{prune}, \code{keep}, \code{prunebelow}, \code{follow} #' takes a named list of vectors as its argument. #' Each vector specifies nodes of a variable. #' \itemize{ #' \item \code{prune}: which nodes should be pruned. #' \item \code{keep}: which nodes should \emph{not} be pruned. #' \item \code{prunebelow}: which nodes should have their descendants pruned. #' \item \code{follow}: which nodes should \emph{not} have their descendants pruned. #' } #' The \code{tprune} parameter specifies "targeted" pruning. #' Standard pruning removes all nodes with the specified value of the specified variable. #' The \code{tprune} parameter specifies one or more particular paths from the root of the tree #' down to a node to be pruned. #' #' @section Displaying summary information: #' The \code{summary} parameter allows you to specify information to display #' in each node. The parameter can be specified as a vector of character strings, #' where each element represents a different variable to summarize. #' When an element of \code{summary} is specified as a single variable name, #' the following default set of summary statistics is shown: #' the variable name, number of missing values, mean and standard deviation, #' median and interquartile range and range. #' A customized summary is shown when an element of \code{summary} #' is specified as a character string with the following structure: #' \itemize{ #' \item{First, the name of the variable for which a summary is desired.} #' \item{Next a space.} #' \item{The remainder of the string specifies what to display, with text as well as special codes (such as \code{\%mean\%}) to indicate the type of summary desired and to control which nodes display the summary, etc. See the vignette for more details.} #' } #' #' @section Palettes: #' The following palettes #' (obtained from \code{RColorBrewer}) are used in the order indicated: #' #' \tabular{rlcrlcrlcrlcclcr}{ #' 1 \tab Reds \tab \tab 4 \tab Oranges \tab \tab 7 \tab PuBu \tab \tab 10 \tab PuBuGn \tab \tab 13 \tab RdYlGn \cr #' 2 \tab Blues \tab \tab 5 \tab Purples \tab \tab 8 \tab PuRd \tab \tab 11 \tab BuPu \tab \tab 14 \tab Set1 \cr #' 3 \tab Greens \tab \tab 6 \tab YlGn \tab \tab 9 \tab YlOrBr \tab \tab 12 \tab YlOrRd \tab \tab \tab \cr #' } #' #' @seealso #' \href{../doc/vtree.html}{\code{vignette("vtree")}} #' #' @examples #' #' # Call vtree and give the root node a title #' vtree(FakeData,"Sex Severity",title="People") #' #' # R Markdown inline call to vtree #' # `r vtree(FakeData,"Sex Severity")` #' #' # Rename some nodes #' vtree(FakeData,"Severity Sex",labelnode=list(Sex=(c("Male"="M","Female"="F")))) #' #' # Rename a variable #' vtree(FakeData,"Severity Sex",labelvar=c(Severity="How bad?")) #' #' # Show legend. Put labels on the same line as counts and percentages #' vtree(FakeData,"Severity Sex Viral",sameline=TRUE,showlegend=TRUE) #' #' # Use the summary parameter to list ID numbers (truncated to 40 characters) in specified nodes #' vtree(FakeData,"Severity Sex",summary="id \nid = %list% %var=Severity% %trunc=40%") #' #' # Add text to specified nodes of a tree ("targeted text") #' vtree(FakeData,"Severity Sex",ttext=list( #' c(Severity="Severe",Sex="M",text="\nMales with Severe disease"), #' c(Severity="NA",text="\nUnknown severity"))) #' #' @importFrom utils capture.output #' #' @export vtree <- function ( data=NULL, vars, showuniform = TRUE, hideconstant = NULL, words = NULL, horiz = TRUE, title = "", sameline=FALSE, vp = TRUE, prune=list(), tprune=list(), keep=list(), tkeep=list(), prunebelow = list(), tprunebelow = list(), follow=list(), tfollow=list(), prunesmaller=NULL, prunebigger=NULL, summary =NULL, tsummary=NULL, shownodelabels=TRUE, showvarnames = TRUE, showpct=TRUE, showlpct=TRUE, showcount=TRUE, prefixcount="", showrootcount=TRUE, showlegend=FALSE, showroot=TRUE, showvarinnode=FALSE, showlegendsum=FALSE, labelvar = NULL, labelnode = list(), tlabelnode=NULL, digits = 0, cdigits=1, fillcolor = NULL, specfill = NULL, fillnodes = TRUE, NAfillcolor="white", rootfillcolor="#EFF3FF", palette=NULL, gradient=TRUE, revgradient=FALSE, sortfill=FALSE, singlecolor=2, colorvarlabels=TRUE, color = c("blue", "forestgreen", "red", "orange", "pink"), colornodes = FALSE, plain = FALSE, Venn = FALSE, check.is.na = FALSE, seq=FALSE, pattern=FALSE, ptable=FALSE, text = list(), ttext=list(), varlabelloc=NULL, font = "Arial", varnamepointsize = 24, varnamebold=FALSE, legendpointsize = 14, HTMLtext = FALSE, splitwidth = 20, vsplitwidth=8, splitspaces=TRUE, getscript = FALSE, mincount=1, maxcount, showempty = FALSE, choicechecklist = TRUE, just="c", justtext=NULL, thousands="", folder=NULL, format="", imageFileOnly=FALSE, pngknit=TRUE, pxwidth=NULL, pxheight=NULL, imagewidth="", imageheight="", width=NULL, height=NULL, maxNodes=1000, unchecked=c("0","FALSE","No","no"), checked=c("1","TRUE","Yes","yes"), trim=NULL, rounded = TRUE, varminwidth=NULL, varminheight=NULL, squeeze = 1, arrowhead="normal", nodesep = 0.5, ranksep = 0.5, margin = 0.2, graphattr="", nodeattr="", edgeattr="", nodefunc = NULL, nodeargs = NULL, verbose=FALSE, runsummary = NULL, retain=NULL, auto=FALSE, parent = 1, last = 1, root = TRUE, subset = 1:nrow(z), numsmallernodes = 0, sumsmallernodes = 0, numbiggernodes = 0, sumbiggernodes = 0, as.if.knit=FALSE, prunelone=NULL, pruneNA=FALSE, lsplitwidth=15, showlevels = TRUE, z=NULL) { makeHTML <- function(x) { if (is.list(x)) { lapply(x, convertToHTML,just=just) } else { convertToHTML(x,just=just) } } makeHTMLnames <- function(x) { if (is.list(x)) { x <- lapply(x, function(u) { names(u) <- convertToHTML(names(u),just=just) u }) } else { names(x) <- convertToHTML(names(x),just=just) } x } if (HTMLtext) { sepN <- "<BR/>" } else { sepN <- "\n" } novars <- FALSE if (missing(z)) z <- data # ************************************************************************* # Begin code for root only ---- # ************************************************************************* if (root) { if (!missing(words)) { showcount <- FALSE showpct <- FALSE showrootcount <- FALSE data <- expand.grid(words) z <- data vars <- names(words) } # ************************************************************************* ## Begin: Check arguments ---- # ************************************************************************* #if (!is.data.frame(z)) { # stop("The argument of data must be a data frame.") #} if (!missing(words) && !is.list(words)) { stop("The argument of words must be a list.") } if (!is.logical(splitspaces)) { stop("The argument of splitspaces must be TRUE or FALSE") } if (!missing(labelnode) && !is.list(labelnode)) { stop("The argument of labelnode must be a list.") } if (!missing(tlabelnode) && !is.list(tlabelnode)) { stop("The argument of tlabelnode must be a list.") } if (length(prune)>0 && (!is.list(prune) || is.null(names(prune)))) { stop("The argument of prune should be a named list.") } if (!missing(tprune) && !is.list(tprune)) { stop("The argument of tprune should be a list of lists.") } if (!missing(tkeep) && !is.list(tkeep)) { stop("The argument of tkeep should be a list of lists.") } if (!missing(tfollow) && !is.list(tfollow)) { stop("The argument of tfollow should be a list of lists.") } if (!missing(tprunebelow) && !is.list(tprunebelow)) { stop("The argument of tprunebelow should be a list of lists.") } if (!missing(tsummary) && (!is.list(tsummary))) { stop("The argument of tsummary should be a list") } if (length(prunebelow)>0 && (!is.list(prunebelow) || is.null(names(prunebelow)))) { stop("The argument of prunebelow should be a named list.") } if (length(follow)>0 && (!is.list(follow) || is.null(names(follow)))) { stop("The argument of follow should be a named list.") } if (length(keep)>0 && (!is.list(keep) || is.null(names(keep)))) { stop("The argument of keep should be a named list.") } # ************************************************************************* # End: Check arguments ---- # ************************************************************************* unknowncolor <- "pink" argname <- sapply(as.list(substitute({data})[-1]), deparse) # # Start of section: Show messages about deprecated parameters # if (!missing(prunelone)) { message("prunelone is deprecated and will be removed in an upcoming release.") } if (!missing(pruneNA)) { message("pruneNA is deprecated and will be removed in an upcoming release.") } if (!missing(showlevels)) { message("showlevels is deprecated and will be removed in an upcoming release. Use showvarnames instead.") } if (!missing(lsplitwidth) & missing(vsplitwidth)) { message("lsplitwidth is deprecated and will be removed in an upcoming release. Use vsplitwidth instead") vsplitwidth=lsplitwidth } # # End of section about deprecated parameters # if (is.null(justtext)) justtext <- just if (ptable & !(pattern | seq | check.is.na)) { pattern <- TRUE } if (!auto) { if (missing(vars)) { # Special case where z is provided as a vector instead of a data frame if (!is.data.frame(z)) { z <- data.frame(z) colnames(z)[1] <- argname vars <- argname } else { novars <- TRUE vars <- "" } } else if (inherits(vars,"formula")) { # There is no is.formula function in R vars <- all.vars(vars) } else if (length(vars)==1) { if (!is.na(vars) & vars=="") { novars <- TRUE } else if (splitspaces) { vars <- strsplit(vars,"\\s+")[[1]] # In case the first element is empty # (due to whitespace at the beginning of the string) if (vars[1]=="") vars <- vars[-1] } } } if (auto) { if (missing(showvarinnode) & !check.is.na) showvarinnode <- TRUE vars <- c() non_discrete_vars <- c() for (candidate in names(z)) { if (length(unique(z[[candidate]]))<5) { vars <- c(vars,candidate) } else { non_discrete_vars <- c(non_discrete_vars,candidate) } } # Calculate a quick approximation to the cumulative number of nodes nodes <- 1 layer <- 1 excluded_discrete_vars <- c() while (layer<=length(vars)) { nodes <- nodes*length(unique(z[[vars[layer]]])) if (nodes>maxNodes) { ev <- vars[-seq_len(layer)] vars <- vars[seq_len(layer)] excluded_discrete_vars <- c(ev,excluded_discrete_vars) break } layer <- layer+1 } if (verbose) message("--Discrete variables included: ",paste(vars,collapse=" ")) if (verbose && length(excluded_discrete_vars)>0) message("--Discrete variables excluded: ",paste(excluded_discrete_vars,collapse=" ")) if (verbose && length(non_discrete_vars)>0) message("Additional variables excluded: ",paste(non_discrete_vars,collapse=" ")) } # ************************************************************************* # Begin: Variable specifications ---- # ************************************************************************* # # The following complex regular expression is used for both # variable specifications and summary arguments. # regexVarName <- "([a-zA-Z0-9~@#()_|,.]+)" regexComplex <- "^((i|r|any|anyx|all|allx|notall|notallx|none|nonex)+:)*([^([:space:]|:)@\\*#]*)([@\\*#]?)(.*)$" if (!(all(vars==""))) { # Process != tag in variable names regex <- paste0("^",regexVarName,"(\\!=)",regexVarName) findnotequal <- grep(regex,vars) if (length(findnotequal)>0) { for (i in seq_len(length(vars))) { if (i %in% findnotequal) { equalvar <- sub(regex,"\\1",vars[i]) if (is.null(z[[equalvar]])) stop(paste("Unknown variable:",equalvar)) equalval <- sub("(\\S+)(=)(\\S+)","\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[equalvar]]))))>0)) { equalval <- gsub("_"," ",equalval) } m <- z[[equalvar]]==equalval z[[equalvar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0("Not ",equalval),paste0(equalval))) vars[i] <- equalvar } } } # Process = tag in variable names regex <- paste0("^",regexVarName,"(=)",regexVarName) findequal <- grep(regex,vars) if (length(findequal)>0) { for (i in seq_len(length(vars))) { if ((i %in% findequal) && !(i %in% findnotequal)) { equalvar <- sub(regex,"\\1",vars[i]) if (is.null(z[[equalvar]])) stop(paste("Unknown variable:",equalvar)) equalval <- sub("(\\S+)(=)(\\S+)","\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[equalvar]]))))>0)) { equalval <- gsub("_"," ",equalval) } m <- z[[equalvar]]==equalval z[[equalvar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0("Not ",equalval),paste0(equalval))) vars[i] <- equalvar } } } # Process > tag in variable names regex <- paste0("^",regexVarName,"(>)",regexVarName) findgt <- grep(regex,vars) if (length(findgt)>0) { for (i in seq_len(length(vars))) { if (i %in% findgt) { gtvar <- sub(regex,"\\1",vars[i]) if (is.null(z[[gtvar]])) stop(paste("Unknown variable:",gtvar)) gtval <- sub(regex,"\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[gtvar]]))))>0)) { gtval <- gsub("_"," ",gtval) } m <- z[[gtvar]]>as.numeric(gtval) z[[gtvar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0("<=",gtval),paste0(">",gtval))) vars[i] <- gtvar } } } # Process < tag in variable names regex <- paste0("^",regexVarName,"(<)",regexVarName) findlt <- grep(regex,vars) if (length(findlt)>0) { for (i in seq_len(length(vars))) { if (i %in% findlt) { ltvar <- sub(regex,"\\1",vars[i]) if (is.null(z[[ltvar]])) stop(paste("Unknown variable:",ltvar)) ltval <- sub(regex,"\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[ltvar]]))))>0)) { ltval <- gsub("_"," ",ltval) } m <- z[[ltvar]]<as.numeric(ltval) z[[ltvar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0(">=",ltval),paste0("<",ltval))) vars[i] <- ltvar } } } # Process > tag in variable names regex <- paste0("^",regexVarName,"(>)",regexVarName) findgt <- grep(regex,vars) if (length(findgt)>0) { for (i in seq_len(length(vars))) { if (i %in% findgt) { gtvar <- sub(regex,"\\1",vars[i]) if (is.null(z[[gtvar]])) stop(paste("Unknown variable:",gtvar)) gtval <- sub(regex,"\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[gtvar]]))))>0)) { gtval <- gsub("_"," ",gtval) } m <- z[[gtvar]]>as.numeric(gtval) z[[gtvar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0("<=",gtval),paste0(">",gtval))) vars[i] <- gtvar } } } # Process >= tag in variable names regex <- paste0("^",regexVarName,"(>=)",regexVarName) findgte <- grep(regex,vars) if (length(findgte)>0) { for (i in seq_len(length(vars))) { if (i %in% findgte) { gtevar <- sub(regex,"\\1",vars[i]) if (is.null(z[[gtevar]])) stop(paste("Unknown variable:",gtevar)) gteval <- sub(regex,"\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[gtevar]]))))>0)) { gteval <- gsub("_"," ",gteval) } m <- z[[gtevar]]>=as.numeric(gteval) z[[gtevar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0("<",gteval),paste0(">=",gteval))) vars[i] <- gtevar } } } # Process <= tag in variable names regex <- paste0("^",regexVarName,"(<=)",regexVarName) findlte <- grep(regex,vars) if (length(findlte)>0) { for (i in seq_len(length(vars))) { if (i %in% findlte) { ltevar <- sub(regex,"\\1",vars[i]) if (is.null(z[[ltevar]])) stop(paste("Unknown variable:",ltevar)) lteval <- sub(regex,"\\3",vars[i]) # Check to see if any of the values of the specified variable contain spaces # If they do, replace underscores in the specified value with spaces. if (any(length(grep(" ",names(table(z[[ltevar]]))))>0)) { lteval <- gsub("_"," ",lteval) } m <- z[[ltevar]]<=as.numeric(lteval) z[[ltevar]] <- factor(m, levels = c(FALSE, TRUE), c(paste0(">",lteval),paste0("<=",lteval))) vars[i] <- ltevar } } } # Process is.na: tag in variable names to handle individual missing value checks regex <- paste0("^is\\.na:",regexVarName,"$") findna <- grep(regex,vars) if (length(findna)>0) { for (i in seq_len(length(vars))) { if (i %in% findna) { navar <- sub(regex,"\\1",vars[i]) if (is.null(z[[navar]])) stop(paste("Unknown variable:",navar)) NewVar <- paste0("is.na:",navar) m <- is.na(z[[navar]]) z[[NewVar]] <- factor(m, levels = c(FALSE, TRUE),c("not N/A","N/A")) # Note that available comes before N/A in alphabetical sorting. # Similarly FALSE comes before TRUE. # And 0 (representing FALSE) comes before 1 (representing TRUE) numerically. # This is convenient, especially when when using the seq parameter. vars[i] <- NewVar } } } # Process stem: tag in variable names to handle REDCap checklists automatically regex <- paste0("^stem:",regexVarName,"$") findstem <- grep(regex,vars) if (length(findstem)>0) { expandedvars <- c() for (i in seq_len(length(vars))) { if (i %in% findstem) { stem <- sub(regex,"\\1",vars[i]) expanded_stem <- names(z)[grep(paste0("^",stem,"___[0-9]+.*$"),names(z))] # remove any variable name that contains ".factor" expanded_stem <- expanded_stem[grep("\\.factor",expanded_stem,invert=TRUE)] if (length(expanded_stem)==0) { stop(paste0("Could not find variables with names matching the specified stem: ",stem)) } if (verbose) message(paste0(vars[i]," expands to: ",paste(expanded_stem,collapse=", "))) rexp0 <- "\\(choice=.+\\)" rexp1 <- "(.+) \\(choice=(.+)\\)" rexp2 <- "(.+): (.+)" if (choicechecklist) { for (j in 1:length(expanded_stem)) { lab <- attributes(z[[expanded_stem[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) } else { stop("Could not find value of checklist item") } z[[choice]] <- z[[expanded_stem[j]]] expandedvars <- c(expandedvars,choice) } } else { expandedvars <- c(expandedvars,expanded_stem) } } else { expandedvars <- c(expandedvars,vars[i]) } } vars <- expandedvars } # # Process complex variable name specification # including REDCap variables, intersections, and wildcards # # Uses the same regular expression as for variable specifications, # namely the string regex match_regex <- grep(regexComplex,vars) if (length(match_regex)>0) { expandedvars <- c() # # Regular expressions for extracting REDCap checklist choices # (to be used a bit later) # rexp0 <- "\\(choice=.+\\)" rexp1 <- "(.+) \\(choice=(.+)\\)" rexp2 <- "(.+): (.+)" # for (i in seq_len(length(vars))) { if (i %in% match_regex) { y <- rep("",nrow(z)) prefix <- sub(regexComplex,"\\1",vars[i]) text_part <- sub(regexComplex,"\\3",vars[i]) wildcard <- sub(regexComplex,"\\4",vars[i]) tail <- sub(regexComplex,"\\5",vars[i]) if (prefix=="" && wildcard=="") { expandedvars <- c(expandedvars,vars[i]) } else if (prefix=="") { if (wildcard=="*") { matching_vars <- names(z)[grep(paste0("^",text_part,".*",tail,"$"),names(z))] } else if (wildcard=="#") { matching_vars <- names(z)[grep(paste0("^",text_part,"[0-9]+",tail,"$"),names(z))] } else { stop("Invalid wildcard in variable specification") } if (length(matching_vars)==0) { stop("Could not find variables with names matching variable specification") } expandedvars <- c(expandedvars,matching_vars) } else if (prefix=="r:" && (wildcard=="*" || wildcard=="#")) { if (wildcard=="*") { matching_vars <- names(z)[grep(paste0("^",text_part,".*$"),names(z))] } else if (wildcard=="#") { matching_vars <- names(z)[grep(paste0("^",text_part,"[0-9]+$"),names(z))] } else { stop("Invalid wildcard in variable specification") } if (length(matching_vars)==0) { stop("Could not find variables with names matching variable specification") } if (choicechecklist) { for (j in 1:length(matching_vars)) { lab <- attributes(z[[matching_vars[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) if (choice %in% names(z)) { choice <- paste0(choice,".") } z[[choice]] <- z[[matching_vars[j]]] } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) if (choice %in% names(z)) { choice <- paste0(choice,".") } z[[choice]] <- z[[matching_vars[j]]] } else { #stop("Could not find value of REDCap checklist item in variable specification") choice <- matching_vars[j] } expandedvars <- c(expandedvars,choice) } } } else if (prefix=="any:" || prefix=="anyx:" || prefix=="none:" || prefix=="nonex:" || prefix=="all:" || prefix=="allx:" || prefix=="notall:" || prefix=="notallx:" ) { if (wildcard=="*") { matching_vars <- names(z)[grep(paste0("^",text_part,".*$"),names(z))] } else if (wildcard=="#") { matching_vars <- names(z)[grep(paste0("^",text_part,"[0-9]+$"),names(z))] } else { stop("Invalid wildcard in variable specification") } if (length(matching_vars)==0) { stop("Could not find variables with names matching variable specification") } if (verbose) message(paste0(vars[i]," expands to: ",paste(matching_vars,collapse=", "))) out <- combineVars(prefix,text_part,matching_vars,checked,unchecked,z) output <- out$output NewVarName <- out$NewVarName z[[NewVarName]] <- output expandedvars <- c(expandedvars,NewVarName) } else if (prefix=="i:") { if (wildcard=="*") { matching_vars <- names(z)[grep(paste0("^",text_part,".*$"),names(z))] } else if (wildcard=="#") { matching_vars <- names(z)[grep(paste0("^",text_part,"[0-9]+$"),names(z))] } else { stop("Invalid wildcard in variable specification") } if (length(matching_vars)==0) { stop("Could not find variables with names matching variable specification") } if (verbose) message(paste0(vars[i]," expands to: ",paste(matching_vars,collapse=", "))) expandedvars <- c() if (choicechecklist) { for (j in seq_len(length(matching_vars))) { y <- ifelse(z[[matching_vars[j]]]==1, ifelse(y=="",matching_vars[j],paste0(y,"+",matching_vars[j])),y) } } y[y %in% ""] <- "*None" newvar <- paste0("combinations_of_",paste(matching_vars,collapse="_")) newvarheading <- paste0("combinations of ",paste(matching_vars,collapse=", ")) z[[newvar]] <- y expandedvars <- c(expandedvars,newvar) } else if (wildcard=="@") { matching_vars <- names(z)[grep(paste0("^",text_part,"___[0-9]+.*$"),names(z))] # remove any variable name that contains ".factor" matching_vars <- matching_vars[grep("\\.factor",matching_vars,invert=TRUE)] if (length(matching_vars)==0) { stop(paste0("Could not find variables with names matching variable specification")) } if (verbose) message(paste0(vars[i]," expands to: ",paste(matching_vars,collapse=", "))) if (prefix=="rall:" || prefix=="allr:") { # with wildcard @ lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% checked,TRUE, ifelse(z[[matching_vars[j]]] %in% unchecked,FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output & convertedToLogical } } } REDCap_var_label_any <- paste0("All: ",REDCap_var_label) z[[REDCap_var_label_any]] <- output expandedvars <- c(expandedvars,REDCap_var_label_any) } else if (prefix=="rnotall:" || prefix=="notallr:") { # with wildcard @ lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% checked,TRUE, ifelse(z[[matching_vars[j]]] %in% unchecked,FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output & convertedToLogical } } } REDCap_var_label_any <- paste0("Not all: ",REDCap_var_label) z[[REDCap_var_label_any]] <- !output expandedvars <- c(expandedvars,REDCap_var_label_any) } else if (prefix=="rany:" || prefix=="anyr:") { # with wildcard @ lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(z[[matching_vars[j]]] %in% checked,TRUE, ifelse(z[[matching_vars[j]]] %in% unchecked,FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output | convertedToLogical } } } REDCap_var_label_any <- paste0("Any: ",REDCap_var_label) z[[REDCap_var_label_any]] <- output expandedvars <- c(expandedvars,REDCap_var_label_any) } else if (prefix=="rnone:" || prefix=="noner:") { # with wildcard @ lab1 <- attributes(z[[matching_vars[1]]])$label if (length(grep(rexp0,lab1))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab1) } else { REDCap_var_label <- sub(rexp2,"\\1",lab1) } if (choicechecklist) { for (j in 1:length(matching_vars)) { convertedToLogical <- ifelse(!(z[[matching_vars[j]]] %in% checked),TRUE, ifelse(!(z[[matching_vars[j]]] %in% unchecked),FALSE,NA)) if (j==1) { output <- convertedToLogical } else { output <- output & convertedToLogical } } } REDCap_var_label_none <- paste0("None: ",REDCap_var_label) z[[REDCap_var_label_none]] <- output expandedvars <- c(expandedvars,REDCap_var_label_none) } else if (prefix=="r:") { # with wildcard @ if (choicechecklist) { for (j in 1:length(matching_vars)) { lab <- attributes(z[[matching_vars[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) if (choice %in% names(z)) { choice <- paste0(choice,".") } z[[choice]] <- z[[matching_vars[j]]] } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) if (choice %in% names(z)) { choice <- paste0(choice,".") } z[[choice]] <- z[[matching_vars[j]]] } else { choice <- matching_vars[j] } expandedvars <- c(expandedvars,choice) } } } else if (prefix=="ri:" || prefix=="ir:") { # with wildcard @ if (choicechecklist) { for (j in seq_len(length(matching_vars))) { lab <- attributes(z[[matching_vars[j]]])$label if (length(grep(rexp0,lab))>0) { REDCap_var_label <- sub(rexp1,"\\1",lab) choice <- sub(rexp1,"\\2",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\2",lab) } else { stop("Could not find value of REDCap checklist item in variable specification") } y <- ifelse(z[[matching_vars[j]]]==1, ifelse(y=="",choice,paste0(y,"+",choice)),y) if (verbose) message(paste0(matching_vars[j]," is ",choice)) z[[choice]] <- z[[matching_vars[j]]] } } y[y %in% ""] <- "*None" NewVarName <- paste0("stem:",text_part) z[[NewVarName]] <- y expandedvars <- c(expandedvars,NewVarName) } } else if (wildcard=="") { if (!(text_part %in% names(z))) { stop("Could not find variable named ",text_part) } if (choicechecklist) { rexp1 <- ".+\\(choice=(.+)\\)" rexp2 <- ".+: (.+)" lab <- attributes(z[[text_part]])$label if (length(grep(rexp1,lab))>0) { choice <- sub(rexp1,"\\1",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\1",lab) } else { stop("Could not find value of REDCap checklist item in variable specification") } z[[choice]] <- z[[text_part]] expandedvars <- c(expandedvars,choice) } else { expandedvars <- c(expandedvars,text_part) } } } else { expandedvars <- c(expandedvars,vars[i]) } } vars <- expandedvars } # Process rc: tag in variable names to handle single REDCap checklist items automatically regex <- "^rc:(\\S+)$" findtag <- grep(regex,vars) if (length(findtag)>0) { expandedvars <- c() for (i in seq_len(length(vars))) { if (i %in% findtag) { rcvar <- sub(regex,"\\1",vars[i]) if (choicechecklist) { rexp1 <- ".+\\(choice=(.+)\\)" rexp2 <- ".+: (.+)" lab <- attributes(z[[rcvar]])$label if (length(grep(rexp1,lab))>0) { choice <- sub(rexp1,"\\1",lab) } else if (length(grep(rexp2,lab))>0) { choice <- sub(rexp2,"\\1",lab) } else { stop("Could not find value of checklist item") } z[[choice]] <- z[[rcvar]] expandedvars <- c(expandedvars,choice) } else { expandedvars <- c(expandedvars,rcvar) } } else { expandedvars <- c(expandedvars,vars[i]) } } vars <- expandedvars } } # ************************************************************************* # End: Variable specifications ---- # ************************************************************************* if (!missing(showlevels)) showvarnames <- showlevels allvars <- vars # ************************************************************************* # Begin: Summaries ---- # ************************************************************************* summaryvarlist <- summaryvaluelist <- headinglist <- summaryformatlist <- list() if (!is.null(tsummary)) { for (TSUMMARY in tsummary) { lastTSUMMARY <- TSUMMARY[length(TSUMMARY)] result <- parseSummary(z,vars=vars, summary=lastTSUMMARY,verbose=verbose,choicechecklist=choicechecklist, checked=checked,unchecked=unchecked) z <- result$z summaryvarlist <- c(summaryvarlist,result$summaryvar) summaryvaluelist <- c(summaryvaluelist,TSUMMARY[length(TSUMMARY)-1]) headingslist <- c(headinglist,result$heading) summaryformatlist <- c(summaryformatlist,result$format) } summaryvars <- unlist(summaryvarlist) summaryvalues <- unlist(summaryvaluelist) headings <- unlist(headingslist) allvars <- c(allvars,summaryvars) if (!is.null(runsummary)) { if (length(runsummary) != length(summary)) { stop("runsummary argument is not the same length as summary argument.") } } nodefunc <- summaryNodeFunction nodeargs <- list( var = summaryvars, value = summaryvalues, format = unlist(summaryformatlist), original_var=headings, sf = runsummary, digits = digits, cdigits = cdigits, sepN=sepN, thousands = thousands) } else if (!is.null(summary)) { for (SUMMARY in summary) { result <- parseSummary(z,vars=vars, summary=SUMMARY,verbose=verbose,choicechecklist=choicechecklist, checked=checked,unchecked=unchecked) z <- result$z summaryvarlist <- c(summaryvarlist,result$summaryvar) headingslist <- c(headinglist,result$heading) summaryformatlist <- c(summaryformatlist,result$format) } summaryvars <- unlist(summaryvarlist) headings <- unlist(headingslist) allvars <- c(allvars,summaryvars) if (!is.null(runsummary)) { if (length(runsummary) != length(summary)) { stop("runsummary argument is not the same length as summary argument.") } } nodefunc <- summaryNodeFunction nodeargs <- list( var = summaryvars, format = unlist(summaryformatlist), original_var=headings, sf = runsummary, digits = digits, cdigits = cdigits, sepN=sepN, thousands = thousands) } # ************************************************************************* # End: Summaries ---- # ************************************************************************* # Add any extra variables needed allvars <- c(allvars,retain) numvars <- length(vars) # ************************************************************************* # Begin: Color palettes ---- # ************************************************************************* # Each element of the following list # is a matrix where the rows are the different hues (one for each variable). # The 1st matrix is for a single-valued variable, # The 2nd matrix is for a two-valued variable, # and so on. col <- list( rbind( c("#DE2D26"), c("#3182BD"), c("#31A354"), c("#E6550D"), c("#756BB1"), c("#31A354"), c("#2B8CBE"), c("#DD1C77"), c("#D95F0E"), c("#1C9099"), c("#8856A7"), c("#F03B20"), c("#43A2CA"), c("#2C7FB8"), c("#C51B8A"), c("#2CA25F"), c("#E34A33"), c("#636363") ), rbind( c("#FEE0D2","#DE2D26"), c("#DEEBF7","#3182BD"), c("#E5F5E0","#31A354"), c("#FEE6CE","#E6550D"), c("#EFEDF5","#756BB1"), c("#F7FCB9","#31A354"), c("#ECE7F2","#2B8CBE"), c("#E7E1EF","#DD1C77"), c("#FFF7BC","#D95F0E"), c("#ECE2F0","#1C9099"), c("#E0ECF4","#8856A7"), c("#FFEDA0","#F03B20"), c("#E0F3DB","#43A2CA"), c("#EDF8B1","#2C7FB8"), c("#FDE0DD","#C51B8A"), c("#E5F5F9","#2CA25F"), c("#FEE8C8","#E34A33"), c("#F0F0F0","#636363") ), rbind( c("#FEE0D2","#FC9272","#DE2D26"), c("#DEEBF7","#9ECAE1","#3182BD"), c("#E5F5E0","#A1D99B","#31A354"), c("#FEE6CE","#FDAE6B","#E6550D"), c("#EFEDF5","#BCBDDC","#756BB1"), c("#F7FCB9","#ADDD8E","#31A354"), c("#ECE7F2","#A6BDDB","#2B8CBE"), c("#E7E1EF","#C994C7","#DD1C77"), c("#FFF7BC","#FEC44F","#D95F0E"), c("#ECE2F0","#A6BDDB","#1C9099"), c("#E0ECF4","#9EBCDA","#8856A7"), c("#FFEDA0","#FEB24C","#F03B20"), c("#E0F3DB","#A8DDB5","#43A2CA"), c("#EDF8B1","#7FCDBB","#2C7FB8"), c("#FDE0DD","#FA9FB5","#C51B8A"), c("#E5F5F9","#99D8C9","#2CA25F"), c("#FEE8C8","#FDBB84","#E34A33"), c("#F0F0F0","#BDBDBD","#636363") ), rbind( c("#FEE5D9","#FCAE91","#FB6A4A","#CB181D"), c("#EFF3FF","#BDD7E7","#6BAED6","#2171B5"), c("#EDF8E9","#BAE4B3","#74C476","#238B45"), c("#FEEDDE","#FDBE85","#FD8D3C","#D94701"), c("#F2F0F7","#CBC9E2","#9E9AC8","#6A51A3"), c("#FFFFCC","#C2E699","#78C679","#238443"), c("#F1EEF6","#BDC9E1","#74A9CF","#0570B0"), c("#F1EEF6","#D7B5D8","#DF65B0","#CE1256"), c("#FFFFD4","#FED98E","#FE9929","#CC4C02"), c("#F6EFF7","#BDC9E1","#67A9CF","#02818A"), c("#EDF8FB","#B3CDE3","#8C96C6","#88419D"), c("#FFFFB2","#FECC5C","#FD8D3C","#E31A1C"), c("#F0F9E8","#BAE4BC","#7BCCC4","#2B8CBE"), c("#FFFFCC","#A1DAB4","#41B6C4","#225EA8"), c("#FEEBE2","#FBB4B9","#F768A1","#AE017E"), c("#EDF8FB","#B2E2E2","#66C2A4","#238B45"), c("#FEF0D9","#FDCC8A","#FC8D59","#D7301F"), c("#F7F7F7","#CCCCCC","#969696","#525252") ), rbind( c("#FEE5D9","#FCAE91","#FB6A4A","#DE2D26","#A50F15"), c("#EFF3FF","#BDD7E7","#6BAED6","#3182BD","#08519C"), c("#EDF8E9","#BAE4B3","#74C476","#31A354","#006D2C"), c("#FEEDDE","#FDBE85","#FD8D3C","#E6550D","#A63603"), c("#F2F0F7","#CBC9E2","#9E9AC8","#756BB1","#54278F"), c("#FFFFCC","#C2E699","#78C679","#31A354","#006837"), c("#F1EEF6","#BDC9E1","#74A9CF","#2B8CBE","#045A8D"), c("#F1EEF6","#D7B5D8","#DF65B0","#DD1C77","#980043"), c("#FFFFD4","#FED98E","#FE9929","#D95F0E","#993404"), c("#F6EFF7","#BDC9E1","#67A9CF","#1C9099","#016C59"), c("#EDF8FB","#B3CDE3","#8C96C6","#8856A7","#810F7C"), c("#FFFFB2","#FECC5C","#FD8D3C","#F03B20","#BD0026"), c("#F0F9E8","#BAE4BC","#7BCCC4","#43A2CA","#0868AC"), c("#FFFFCC","#A1DAB4","#41B6C4","#2C7FB8","#253494"), c("#FEEBE2","#FBB4B9","#F768A1","#C51B8A","#7A0177"), c("#EDF8FB","#B2E2E2","#66C2A4","#2CA25F","#006D2C"), c("#FEF0D9","#FDCC8A","#FC8D59","#E34A33","#B30000"), c("#F7F7F7","#CCCCCC","#969696","#636363","#252525") ), rbind( c("#FEE5D9","#FCBBA1","#FC9272","#FB6A4A","#DE2D26","#A50F15"), c("#EFF3FF","#C6DBEF","#9ECAE1","#6BAED6","#3182BD","#08519C"), c("#EDF8E9","#C7E9C0","#A1D99B","#74C476","#31A354","#006D2C"), c("#FEEDDE","#FDD0A2","#FDAE6B","#FD8D3C","#E6550D","#A63603"), c("#F2F0F7","#DADAEB","#BCBDDC","#9E9AC8","#756BB1","#54278F"), c("#FFFFCC","#D9F0A3","#ADDD8E","#78C679","#31A354","#006837"), c("#F1EEF6","#D0D1E6","#A6BDDB","#74A9CF","#2B8CBE","#045A8D"), c("#F1EEF6","#D4B9DA","#C994C7","#DF65B0","#DD1C77","#980043"), c("#FFFFD4","#FEE391","#FEC44F","#FE9929","#D95F0E","#993404"), c("#F6EFF7","#D0D1E6","#A6BDDB","#67A9CF","#1C9099","#016C59"), c("#EDF8FB","#BFD3E6","#9EBCDA","#8C96C6","#8856A7","#810F7C"), c("#FFFFB2","#FED976","#FEB24C","#FD8D3C","#F03B20","#BD0026"), c("#F0F9E8","#CCEBC5","#A8DDB5","#7BCCC4","#43A2CA","#0868AC"), c("#FFFFCC","#C7E9B4","#7FCDBB","#41B6C4","#2C7FB8","#253494"), c("#FEEBE2","#FCC5C0","#FA9FB5","#F768A1","#C51B8A","#7A0177"), c("#EDF8FB","#CCECE6","#99D8C9","#66C2A4","#2CA25F","#006D2C"), c("#FEF0D9","#FDD49E","#FDBB84","#FC8D59","#E34A33","#B30000"), c("#F7F7F7","#D9D9D9","#BDBDBD","#969696","#636363","#252525") ), rbind( c("#FEE5D9","#FCBBA1","#FC9272","#FB6A4A","#EF3B2C","#CB181D","#99000D"), c("#EFF3FF","#C6DBEF","#9ECAE1","#6BAED6","#4292C6","#2171B5","#084594"), c("#EDF8E9","#C7E9C0","#A1D99B","#74C476","#41AB5D","#238B45","#005A32"), c("#FEEDDE","#FDD0A2","#FDAE6B","#FD8D3C","#F16913","#D94801","#8C2D04"), c("#F2F0F7","#DADAEB","#BCBDDC","#9E9AC8","#807DBA","#6A51A3","#4A1486"), c("#FFFFCC","#D9F0A3","#ADDD8E","#78C679","#41AB5D","#238443","#005A32"), c("#F1EEF6","#D0D1E6","#A6BDDB","#74A9CF","#3690C0","#0570B0","#034E7B"), c("#F1EEF6","#D4B9DA","#C994C7","#DF65B0","#E7298A","#CE1256","#91003F"), c("#FFFFD4","#FEE391","#FEC44F","#FE9929","#EC7014","#CC4C02","#8C2D04"), c("#F6EFF7","#D0D1E6","#A6BDDB","#67A9CF","#3690C0","#02818A","#016450"), c("#EDF8FB","#BFD3E6","#9EBCDA","#8C96C6","#8C6BB1","#88419D","#6E016B"), c("#FFFFB2","#FED976","#FEB24C","#FD8D3C","#FC4E2A","#E31A1C","#B10026"), c("#F0F9E8","#CCEBC5","#A8DDB5","#7BCCC4","#4EB3D3","#2B8CBE","#08589E"), c("#FFFFCC","#C7E9B4","#7FCDBB","#41B6C4","#1D91C0","#225EA8","#0C2C84"), c("#FEEBE2","#FCC5C0","#FA9FB5","#F768A1","#DD3497","#AE017E","#7A0177"), c("#EDF8FB","#CCECE6","#99D8C9","#66C2A4","#41AE76","#238B45","#005824"), c("#FEF0D9","#FDD49E","#FDBB84","#FC8D59","#EF6548","#D7301F","#990000"), c("#F7F7F7","#D9D9D9","#BDBDBD","#969696","#737373","#525252","#252525") ), rbind( c("#FFF5F0","#FEE0D2","#FCBBA1","#FC9272","#FB6A4A","#EF3B2C","#CB181D","#99000D"), c("#F7FBFF","#DEEBF7","#C6DBEF","#9ECAE1","#6BAED6","#4292C6","#2171B5","#084594"), c("#F7FCF5","#E5F5E0","#C7E9C0","#A1D99B","#74C476","#41AB5D","#238B45","#005A32"), c("#FFF5EB","#FEE6CE","#FDD0A2","#FDAE6B","#FD8D3C","#F16913","#D94801","#8C2D04"), c("#FCFBFD","#EFEDF5","#DADAEB","#BCBDDC","#9E9AC8","#807DBA","#6A51A3","#4A1486"), c("#FFFFE5","#F7FCB9","#D9F0A3","#ADDD8E","#78C679","#41AB5D","#238443","#005A32"), c("#FFF7FB","#ECE7F2","#D0D1E6","#A6BDDB","#74A9CF","#3690C0","#0570B0","#034E7B"), c("#F7F4F9","#E7E1EF","#D4B9DA","#C994C7","#DF65B0","#E7298A","#CE1256","#91003F"), c("#FFFFE5","#FFF7BC","#FEE391","#FEC44F","#FE9929","#EC7014","#CC4C02","#8C2D04"), c("#FFF7FB","#ECE2F0","#D0D1E6","#A6BDDB","#67A9CF","#3690C0","#02818A","#016450"), c("#F7FCFD","#E0ECF4","#BFD3E6","#9EBCDA","#8C96C6","#8C6BB1","#88419D","#6E016B"), c("#FFFFCC","#FFEDA0","#FED976","#FEB24C","#FD8D3C","#FC4E2A","#E31A1C","#B10026"), c("#F7FCF0","#E0F3DB","#CCEBC5","#A8DDB5","#7BCCC4","#4EB3D3","#2B8CBE","#08589E"), c("#FFFFD9","#EDF8B1","#C7E9B4","#7FCDBB","#41B6C4","#1D91C0","#225EA8","#0C2C84"), c("#FFF7F3","#FDE0DD","#FCC5C0","#FA9FB5","#F768A1","#DD3497","#AE017E","#7A0177"), c("#F7FCFD","#E5F5F9","#CCECE6","#99D8C9","#66C2A4","#41AE76","#238B45","#005824"), c("#FFF7EC","#FEE8C8","#FDD49E","#FDBB84","#FC8D59","#EF6548","#D7301F","#990000"), c("#FFFFFF","#F0F0F0","#D9D9D9","#BDBDBD","#969696","#737373","#525252","#252525") ), rbind( c("#FFF5F0","#FEE0D2","#FCBBA1","#FC9272","#FB6A4A","#EF3B2C","#CB181D","#A50F15","#67000D"), c("#F7FBFF","#DEEBF7","#C6DBEF","#9ECAE1","#6BAED6","#4292C6","#2171B5","#08519C","#08306B"), c("#F7FCF5","#E5F5E0","#C7E9C0","#A1D99B","#74C476","#41AB5D","#238B45","#006D2C","#00441B"), c("#FFF5EB","#FEE6CE","#FDD0A2","#FDAE6B","#FD8D3C","#F16913","#D94801","#A63603","#7F2704"), c("#FCFBFD","#EFEDF5","#DADAEB","#BCBDDC","#9E9AC8","#807DBA","#6A51A3","#54278F","#3F007D"), c("#FFFFE5","#F7FCB9","#D9F0A3","#ADDD8E","#78C679","#41AB5D","#238443","#006837","#004529"), c("#FFF7FB","#ECE7F2","#D0D1E6","#A6BDDB","#74A9CF","#3690C0","#0570B0","#045A8D","#023858"), c("#F7F4F9","#E7E1EF","#D4B9DA","#C994C7","#DF65B0","#E7298A","#CE1256","#980043","#67001F"), c("#FFFFE5","#FFF7BC","#FEE391","#FEC44F","#FE9929","#EC7014","#CC4C02","#993404","#662506"), c("#FFF7FB","#ECE2F0","#D0D1E6","#A6BDDB","#67A9CF","#3690C0","#02818A","#016C59","#014636"), c("#F7FCFD","#E0ECF4","#BFD3E6","#9EBCDA","#8C96C6","#8C6BB1","#88419D","#810F7C","#4D004B"), c("#FFFFCC","#FFEDA0","#FED976","#FEB24C","#FD8D3C","#FC4E2A","#E31A1C","#BD0026","#800026"), c("#F7FCF0","#E0F3DB","#CCEBC5","#A8DDB5","#7BCCC4","#4EB3D3","#2B8CBE","#0868AC","#084081"), c("#FFFFD9","#EDF8B1","#C7E9B4","#7FCDBB","#41B6C4","#1D91C0","#225EA8","#253494","#081D58"), c("#FFF7F3","#FDE0DD","#FCC5C0","#FA9FB5","#F768A1","#DD3497","#AE017E","#7A0177","#49006A"), c("#F7FCFD","#E5F5F9","#CCECE6","#99D8C9","#66C2A4","#41AE76","#238B45","#006D2C","#00441B"), c("#FFF7EC","#FEE8C8","#FDD49E","#FDBB84","#FC8D59","#EF6548","#D7301F","#B30000","#7F0000"), c("#FFFFFF","#F0F0F0","#D9D9D9","#BDBDBD","#969696","#737373","#525252","#252525","#000000") )) # ************************************************************************* # End: Color palettes ---- # ************************************************************************* # Duplicate the color gradients 3 times to allow for huge trees. for (i in seq_len(length(col))) { col[[i]] <- rbind(col[[i]],col[[i]],col[[i]]) } # When a variable has a single value, # should nodes be colored light (1) medium (2) or dark (3)? if (singlecolor==1) { col[[1]] <- col[[3]][,1,drop=FALSE] } if (singlecolor==2) { col[[1]] <- col[[3]][,2,drop=FALSE] } if (singlecolor==3) { col[[1]] <- col[[3]][,3,drop=FALSE] } # Identify any "tri:" variables tri.variable <- rep(FALSE,length(allvars)) findtri <- grep("tri:",allvars) ALLVARS <- allvars if (length(findtri)>0) { tri.variable[findtri] <- TRUE for (i in seq_len(length(allvars))) { if (i %in% findtri) { trivar <- sub("^tri:(\\S+)$","\\1",allvars[i]) ALLVARS[i] <- trivar } } } # Check that all of the named variables are in the data frame if (novars) ALLVARS <- ALLVARS[ALLVARS!=""] findallvars <- ALLVARS %in% names(z) if (any(!findallvars)) { stop("The following variables were not found in the data frame: ", paste(ALLVARS[!findallvars], collapse = ", ")) } # Use a data frame that *only* contains the variables of interest. # This greatly speeds things up! z <- z[ALLVARS] if (Venn) { if (missing(shownodelabels)) shownodelabels <- FALSE if (missing(showpct)) showpct <- FALSE if (missing(showlegend)) showlegend <- FALSE if (missing(showlpct)) showlpct <- FALSE } if (check.is.na) { if (missing(pattern)) pattern <- TRUE if (missing(shownodelabels)) shownodelabels <- FALSE } if (length(labelvar) > 0) { namesvarheaders <- names(labelvar) labelvar <- splitlines(labelvar, splitwidth, sp = sepN, at = c(" ", ".", "-", "+", "_", "=", "/")) names(labelvar) <- namesvarheaders } if (length(labelnode) > 0) { for (i in seq_len(length(labelnode))) { names(labelnode[[i]]) <- splitlines(names(labelnode[[i]]),splitwidth,sp =sepN, at=" ") } } if (check.is.na) { OLDVARS <- vars NEWVARS <- c() for (v in vars) { newvar <- paste0("MISSING_", v) m <- is.na(z[[v]]) z[[newvar]] <- factor(m, levels = c(FALSE, TRUE),c("not N/A","N/A")) # Note that available comes before N/A in alphabetical sorting. # Similarly FALSE comes before TRUE. # And 0 (representing FALSE) comes before 1 (representing TRUE) numerically. # This is convenient, especially when when using the seq parameter. NEWVARS <- c(NEWVARS, newvar) } vars <- NEWVARS } # ************************************************************************* # Begin: Process patterns ---- # ************************************************************************* if (pattern | seq) { if (missing(showroot)) showroot <- FALSE if (pattern) { edgeattr <- paste(edgeattr,"arrowhead=none") } for (i in 1:length(vars)) { if (i==1) { PATTERN <- paste(z[[vars[i]]]) } else { PATTERN <- paste(PATTERN,z[[vars[i]]]) } } TAB <- table(PATTERN) if (!missing(maxcount)) { TAB <- TAB[TAB<=maxcount] } else { TAB <- TAB[TAB>=mincount] } if (showroot) { PATTERN_levels <- names(sort(TAB)) } else { o <- order(as.numeric(TAB),tolower(names(TAB)),decreasing=TRUE) PATTERN_levels <- names(TAB)[o] } select <- PATTERN %in% PATTERN_levels PATTERN <- PATTERN[select] z <- z[select,,drop=FALSE] #PATTERN[!(PATTERN) %in% PATTERN_levels] <- "Other" #PATTERN_levels <- c(PATTERN_levels,"Other") PATTERN_values <- data.frame(matrix("",nrow=length(PATTERN_levels),ncol=length(vars)), stringsAsFactors=FALSE) names(PATTERN_values) <- vars for (i in seq_len(length(PATTERN_levels))) { patternRow <- z[PATTERN==PATTERN_levels[i],,drop=FALSE] for (j in 1:length(vars)) { PATTERN_values[[vars[j]]][i] <- as.character(patternRow[[vars[j]]][1]) } } PATTERN <- factor(PATTERN,levels=PATTERN_levels) if (!is.null(prunesmaller)) { tabpattern <- table(PATTERN) # Uniform variables are defined in terms of the patterns that will be shown if (!is.null(hideconstant) || !showuniform) { #browser() sel <- PATTERN %in% names(tabpattern[tabpattern>=prunesmaller]) patterns_pruned <- sum(tabpattern[tabpattern>=prunesmaller]) cases_pruned <- sum(!sel) cases_pruned_pct <- round(100*cases_pruned/nrow(z)) z <- z[sel,] PATTERN <- PATTERN[sel] if (patterns_pruned==1) { description1 <- " pattern was pruned, for a total of " } else { description1 <- " patterns were pruned, for a total of " } if (cases_pruned==1) { description2 <- paste0( " case (",cases_pruned_pct,"% of total).") } else { description2 <- paste0( " cases (",cases_pruned_pct,"% of total).") } message("Since prunesmaller=",prunesmaller,", ", patterns_pruned,description1,cases_pruned,description2) } } if (!is.null(prunebigger)) { tabpattern <- table(PATTERN) # Uniform variables are defined in terms of the patterns that will be shown if (!is.null(hideconstant) || !showuniform) { #browser() sel <- PATTERN %in% names(tabpattern[tabpattern<=prunebigger]) patterns_pruned <- sum(tabpattern[tabpattern<=prunebigger]) cases_pruned <- sum(!sel) cases_pruned_pct <- round(100*cases_pruned/nrow(z)) z <- z[sel,] PATTERN <- PATTERN[sel] if (patterns_pruned==1) { description1 <- " pattern was pruned, for a total of " } else { description1 <- " patterns were pruned, for a total of " } if (cases_pruned==1) { description2 <- paste0( " case (",cases_pruned_pct,"% of total).") } else { description2 <- paste0( " cases (",cases_pruned_pct,"% of total).") } message("Since prunebigger=",prunebigger,", ", patterns_pruned,description1,cases_pruned,description2) } } if (!is.null(hideconstant)) { for (var in vars) { if (length(unique(z[[var]]))==1) { if ((unique(z[[var]]) %in% hideconstant)) { message(paste0("Not showing ",var,", since its only value is ",z[[var]][1])) vars <- vars[vars!=var] } } } } else if (!showuniform) { for (var in vars) { #message(var) #print(table(z[[var]])) if (length(unique(z[[var]]))==1) { message(paste0("Not showing ",var,", since the only value is ",z[[var]][1])) vars <- vars[vars!=var] } } } if (pattern) { z$pattern <- PATTERN vars <- c("pattern",vars) } else { z$sequence <- PATTERN vars <- c("sequence",vars) } tri.variable <- c(tri.variable,FALSE) if (check.is.na) { OLDVARS <- c("pattern",OLDVARS) } numvars <- length(vars) if (pattern) { if (missing(showcount)) showcount <- c(pattern=TRUE) if (missing(showpct)) showpct <- c(pattern=TRUE) if (missing(shownodelabels)) shownodelabels <- c(pattern=FALSE) } else { if (missing(showcount)) showcount <- c(sequence=TRUE) if (missing(showpct)) showpct <- c(sequence=TRUE) if (missing(shownodelabels)) shownodelabels <- c(sequence=FALSE) } } else { if (arrowhead!="normal") { edgeattr <- paste(edgeattr,paste0("arrowhead=",arrowhead)) } if (!is.null(hideconstant)) { for (var in vars) { if (length(unique(z[[var]]))==1) { if ((unique(z[[var]]) %in% hideconstant)) { message(paste0("Not showing ",var,", since the only value is ",z[[var]][1])) vars <- vars[vars!=var] } } } } else if (!showuniform) { for (var in vars) { #message(var) #print(table(z[[var]])) if (length(unique(z[[var]]))==1) { message(paste0("Not showing ",var,", since the only value is ",z[[var]][1])) vars <- vars[vars!=var] } } if (length(vars)==0) { novars <- TRUE vars <- "" } } } # ************************************************************************* # End: Process patterns ---- # ************************************************************************* if (is.null(names(gradient))) { gradient <- rep(gradient[1],numvars) names(gradient) <- vars } else { if (all(gradient)) { gg <- rep(FALSE,numvars) } else if (all(!gradient)) { gg <- rep(TRUE,numvars) } else if (length(gradient)!=numvars) { stop("gradient: ambiguous specification.") } else { gg <- rep(NA,numvars) } if (any(names(gradient) %in% vars)) { m <- match(names(gradient),vars) gg[m[!is.na(m)]] <- gradient[!is.na(m)] } names(gg) <- vars gradient <- gg } findvars <- names(shownodelabels) %in% vars if (is.null(names(shownodelabels))) { shownodelabels <- rep(shownodelabels[1],numvars) names(shownodelabels) <- vars } else { if (any(!findvars)) { stop("The following variables named in shownodelabels were not in vars: ", paste(names(shownodelabels)[!findvars], collapse = ", ")) } if (all(shownodelabels)) { sn <- rep(FALSE,numvars) names(sn) <- vars } else if (all(!shownodelabels)) { sn <- rep(TRUE,numvars) names(sn) <- vars } else if (length(shownodelabels)!=numvars) { stop("shownodelabels: ambiguous specification.") } else { sn <- rep(NA,numvars) } if (any(names(shownodelabels) %in% vars)) { m <- match(names(shownodelabels),vars) sn[m[!is.na(m)]] <- shownodelabels[!is.na(m)] } names(sn) <- vars shownodelabels <- sn } if (is.null(names(showcount))) { showcount <- rep(showcount[1],numvars) names(showcount) <- vars } else { if (all(showcount)) { sc <- rep(FALSE,numvars) } else if (all(!showcount)) { sc <- rep(TRUE,numvars) } else if (length(showcount)!=numvars) { stop("showcount: ambiguous specification.") } else { sc <- rep(NA,length(vars)) } if (any(names(showcount) %in% vars)) { m <- match(names(showcount),vars) sc[m[!is.na(m)]] <- showcount[!is.na(m)] } names(sc) <- vars showcount <- sc } if (is.null(names(showpct))) { showpct <- rep(showpct[1],numvars) names(showpct) <- vars } else { if (all(showpct)) { sp <- rep(FALSE,numvars) } else if (all(!showpct)) { sp <- rep(TRUE,numvars) } else if (length(showpct)!=numvars) { stop("showpct: ambiguous specification.") } else { sp <- rep(NA,numvars) } if (any(names(showpct) %in% vars)) { m <- match(names(showpct),vars) sp[m[!is.na(m)]] <- showpct[!is.na(m)] } names(sp) <- vars showpct <- sp } if (is.null(names(sameline))) { sameline <- rep(sameline[1],numvars) names(sameline) <- vars } else { if (all(sameline)) { sl <- rep(FALSE,numvars) } else if (all(!sameline)) { sl <- rep(TRUE,numvars) } else if (length(sameline)!=numvars) { stop("sameline: ambiguous specification.") } else { sl <- rep(NA,numvars) } if (any(names(sameline) %in% vars)) { m <- match(names(sameline),vars) sl[m[!is.na(m)]] <- sameline[!is.na(m)] } names(sl) <- vars sameline <- sl } if (is.null(names(revgradient))) { revgradient <- rep(revgradient[1],numvars) names(revgradient) <- vars } else { if (all(revgradient)) { rg <- rep(FALSE,numvars) } else if (all(!revgradient)) { rg <- rep(TRUE,numvars) } else if (length(revgradient)!=numvars) { stop("revgradient: ambiguous specification.") } else { rg <- rep(NA,numvars) } if (any(names(revgradient) %in% vars)) { m <- match(names(revgradient),vars) rg[m[!is.na(m)]] <- revgradient[!is.na(m)] } names(rg) <- vars revgradient <- rg } # If varlabelloc is a single unnamed value, then apply it to all variables. if (!missing(varlabelloc) && (length(varlabelloc)==1) && (is.null(names(varlabelloc))) ) { varlabelloc <- rep(varlabelloc,numvars) names(varlabelloc) <- vars } # If varminwidth is a single unnamed value, then apply it to all variables. if (!missing(varminwidth) && (length(varminwidth)==1) && (is.null(names(varminwidth))) ) { varminwidth <- rep(varminwidth,numvars) names(varminwidth) <- vars } # If varminheight is a single unnamed value, then apply it to all variables. if (!missing(varminheight) && (length(varminheight)==1) && (is.null(names(varminheight))) ) { varminheight <- rep(varminheight,numvars) names(varminheight) <- vars } if (plain) { fillcolor <- rep(c("#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5","#084594"), 8)[1:numvars] autocolorvar <- FALSE if (missing(colorvarlabels)) colorvarlabels <- FALSE if (missing(showlegend)) showlegend <- FALSE if (missing(squeeze)) squeeze <- 0.6 } if (squeeze<0 || squeeze>1) stop("The squeeze parameter must be between 0 and 1.") if (missing(nodesep)) nodesep <- 0.1+(1-squeeze)*(1-0.1) if (missing(margin)) margin <- 0.1+(1-squeeze)*(0.3-0.1) singleColor <- FALSE # Single color specified if (!is.null(fillcolor) && (length(fillcolor)==1) && (is.null(names(fillcolor)))) { singleColor <- TRUE fillcolor <- rep(fillcolor,numvars) names(fillcolor) <- vars if (is.null(rootfillcolor)) rootfillcolor <- fillcolor } holdvarlabelcolors <- FALSE if (is.null(fillcolor)) { varlabelcolors <- rep(unknowncolor,numvars) } else { varlabelcolors <- fillcolor varlabelcolors[fillcolor=="white"] <- "black" # So that varlabels are visible on a white background if (singleColor || plain) varlabelcolors[TRUE] <- "black" holdvarlabelcolors <- TRUE } if (!is.null(palette)) { if (length(palette)==1) { if (is.null(names(palette))) { # Use the specified palette for all variables. palette <- rep(palette,numvars) names(palette) <- vars if (is.null(rootfillcolor)) rootfillcolor <- col[[1]][palette,1] } } else { if (length(vars)<=length(palette)) { names(palette) <- c(vars,rep("NoVariable",length(palette)-length(vars))) } else { names(palette) <- vars[seq_len(length(palette))] } } } # ************************************************************************* # Begin: Assign colors ---- # ************************************************************************* if (!plain) { FILLCOLOR <- vector("list",numvars) names(FILLCOLOR) <- vars numPalettes <- nrow(col[[1]]) for (i in seq_len(numvars)) { if (tri.variable[i]) { thisvar <- factor(c("low","mid","high","NA"),levels=c("high","mid","low","NA")) } else { thisvar <- z[[vars[i]]] } if (i>numPalettes) { row <- i %% numPalettes } else { row <- i } if (!is.null(palette)) { if (check.is.na) { if (any(names(palette)==OLDVARS[i])) { row <- palette[names(palette)==OLDVARS[i]] } } else { if (any(names(palette)==vars[i])) { row <- palette[names(palette)==vars[i]] } } } revgrad <- revgradient[vars[i]] if (is.na(revgrad)) revgrad <- FALSE if (is.logical(thisvar)) { thisvar <- factor(thisvar, c("FALSE", "TRUE")) } values <- names(table(thisvar,exclude=NULL)) values[is.na(values)] <- "NA" Nallvalues <- length(values) Nnonmissing <- length(values[values!="NA"]) if (is.null(NAfillcolor)) { valuecolors <- rep(unknowncolor,length(values)) } else { valuecolors <- rep(NAfillcolor,length(values)) } if (Nnonmissing>0) { if (is.null(fillcolor) & (Nnonmissing>length(col) || (seq & (vars[i]=="sequence")) || (pattern & (vars[i]=="pattern")) || (row==0))) { # Too many values to permit distinct colors valuecolors[values!="NA"] <- col[[1]][row] # "grey90" names(valuecolors) <- values varlabelcolors[i] <- col[[1]][row] # "grey90" } else { if (!is.null(fillcolor) && (vars[i] %in% names(fillcolor))) { if (is.null(NAfillcolor)) { valuecolors[TRUE] <- fillcolor[names(fillcolor)==vars[i]] } else { valuecolors[values!="NA"] <- fillcolor[names(fillcolor)==vars[i]] } if (!holdvarlabelcolors) { varlabelcolors[i] <- fillcolor[names(fillcolor)==vars[i]] } } else if (!is.null(specfill)) { if (is.null(NAfillcolor)) { valuecolors[TRUE] <- specfill[[vars[[i]]]] } else { valuecolors[values!="NA"] <- specfill[[vars[[i]]]] } varlabelcolors[i] <- "black" } else if (gradient[vars[i]]) { if (revgrad) { if (is.null(NAfillcolor)) { valuecolors[TRUE] <- rev(col[[Nallvalues]][row,]) } else { valuecolors[values!="NA"] <- rev(col[[Nnonmissing]][row,]) } varlabelcolors[i] <- col[[2]][row,2] } else { if (is.null(NAfillcolor)) { valuecolors[TRUE] <- col[[Nallvalues]][row,] } else { valuecolors[values!="NA"] <- col[[Nnonmissing]][row,] } varlabelcolors[i] <- col[[2]][row,2] } names(valuecolors) <- values } else { if (is.null(NAfillcolor)) { valuecolors[TRUE] <- rep(col[[1]][row],Nallvalues) } else { valuecolors[values!="NA"] <- rep(col[[1]][row],Nnonmissing) } varlabelcolors[i] <- col[[1]][row] } } } names(valuecolors) <- values FILLCOLOR[[vars[i]]] <- valuecolors } fillcolor <- FILLCOLOR colorIndex <- rep(1:numPalettes,length.out=numvars) names(varlabelcolors) <- vars if (check.is.na) { names(varlabelcolors) <- OLDVARS } } # ************************************************************************* # End: Assign colors ---- # ************************************************************************* # If fillcolor isn't a list, create a list if (!is.list(fillcolor)) { FILLCOLOR <- vector("list",numvars) names(FILLCOLOR) <- vars for (i in seq_len(length(vars))) { values <- names(table(z[[vars[i]]],exclude=NULL)) values[is.na(values)] <- "NA" valuecolors <- rep(fillcolor[i],length(values)) names(valuecolors) <- values FILLCOLOR[[vars[i]]] <- valuecolors } fillcolor <- FILLCOLOR } z_names <- names(z) # Special case with a single variable being relabled and variable name not specified if (!missing(labelvar) && is.null(names(labelvar))) { if ((numvars==1) && (length(labelvar)==1)) { names(labelvar) <- z_names } } findvars <- names(labelvar) %in% z_names if (verbose && any(!findvars)) { message("The following variables named in labelvar were not found in vars: ", paste(names(labelvar)[!findvars], collapse = ", ")) } findvars <- names(prunebelow) %in% z_names if (verbose && any(!findvars)) { message("The following variables named in prunebelow were not found in vars: ", paste(names(prunebelow)[!findvars], collapse = ", ")) } findvars <- names(prune) %in% z_names if (verbose && any(!findvars)) { message("The following variables named in prune were not found in vars: ", paste(names(prune)[!findvars], collapse = ", ")) } findvars <- names(follow) %in% z_names if (verbose && any(!findvars)) { message("The following variables named in follow were not found in vars: ", paste(names(follow)[!findvars], collapse = ", ")) } findvars <- names(keep) %in% z_names if (verbose && any(!findvars)) { message("The following variables named in keep were not found in vars: ", paste(names(keep)[!findvars], collapse = ", ")) } } # ************************************************************************* # End code for root only ---- # ************************************************************************* numvars <- length(vars) # Node outline colors if (!colornodes) color <- rep("black", 100) if (is.null(z) || is.null(vars)) { #cat("Return NULL because z is NULL or vars is NULL\n") return(NULL) } if (nrow(z) == 0 || numvars == 0) { #cat("Return NULL because z is empty or vars has zero length\n") return(NULL) } # Process tri: tag in variable names actualvarname <- vars[1] findtri <- grep("tri:",vars[1]) if (length(findtri)>0) { trivar <- sub("^tri:(\\S+)$","\\1",vars[1]) med <- median(z[[trivar]],na.rm=TRUE) iqrange <- quantile(z[[trivar]],0.75,na.rm=TRUE)- quantile(z[[trivar]],0.25,na.rm=TRUE) upper <- med+1.5*iqrange lower <- med-1.5*iqrange m <- ifelse(z[[trivar]]<lower,"low", ifelse(z[[trivar]]>=lower & z[[trivar]]<upper,"mid", ifelse(z[[trivar]]>=upper,"high","impossible"))) z[[vars[1]]] <- factor(m,levels=c("high","mid","low")) } TopText <- "" tsummaryLen <- sapply(tsummary,length) qqq <- z[[vars[1]]] qqq <- as.character(qqq) qqq[is.na(qqq)] <- "NA" categoryCounts <- table(qqq, exclude = NULL) CAT <- names(categoryCounts) ThisLayerText <- rep("",length(CAT)) # Process summaries to include in nodes ---- if (any(tsummaryLen==2)) { # # Prepare targeted summaries # for (i in seq_len(length(tsummary))) { if (tsummaryLen[i]==2) { if (numvars == 1) nodeargs$leaf <- TRUE summarytext <- vector("list",length=length(CAT)) names(summarytext) <- CAT for (k in seq_len(length(CAT))) { value <- CAT[k] zselect <- z[qqq == value,,drop=FALSE] for (j in seq_len(ncol(zselect))) { attr(zselect[,j],"label") <- attr(z[,j],"label") } if (tsummary[[i]][1]==value) { choose <- nodeargs$value==value if (any(choose)) { args <- nodeargs args$var <- args$var[choose] args$format <- args$format[choose] args$value <- args$value[choose] # not really necessary summarytext[[value]] <- nodefunc(zselect, vars[1], value, args = args) nodetext <- paste0(summarytext[[value]],collapse="") nodetext <- splitlines(nodetext, width = splitwidth, sp = sepN, at=" ") ThisLayerText[k] <- paste0(ThisLayerText[k], paste0(nodetext,sepN)) } } } names(ThisLayerText) <- CAT } } } else if (is.null(tsummary) & !is.null(nodefunc)) { # # Prepare non-targeted summaries # if (numvars == 1) nodeargs$leaf <- TRUE summarytext <- vector("list",length=length(CAT)) names(summarytext) <- CAT for (k in seq_len(length(CAT))) { value <- CAT[k] zselect <- z[qqq == value,,drop=FALSE] for (i in seq_len(ncol(zselect))) { attr(zselect[,i],"label") <- attr(z[,i],"label") } summarytext[[value]] <- nodefunc(zselect, vars[1], value, args = nodeargs) nodetext <- paste0(summarytext[[value]],collapse="") nodetext <- splitlines(nodetext, width = splitwidth, sp = sepN, at=" ") ThisLayerText[k] <- paste0(ThisLayerText[k], paste0(nodetext,sepN)) } if (root) { topnodeargs <- nodeargs topnodeargs$root <- TRUE topnodeargs$leaf <- FALSE overallsummary <- nodefunc(z, "", value = NA, args = topnodeargs) nodetext <- paste0(overallsummary,collapse="") nodetext <- splitlines(nodetext, width = splitwidth,sp = sepN, at=" ") TopText <- paste0(nodetext,sepN) } names(ThisLayerText) <- CAT } else { ThisLayerText <- text[[vars[1]]] summarytext <- NULL } if (pattern & vars[1]!="pattern") ThisLayerText <- "" if (seq & vars[1]!="sequence") ThisLayerText <- "" if (novars) { zvalue <- rep(0,nrow(z)) showCOUNT <- showcount showPCT <- showpct sameLINE <- sameline } else { zvalue <- z[[vars[1]]] showCOUNT <- showcount[[vars[1]]] showPCT <- showpct[vars[1]] sameLINE <- sameline[vars[1]] } # ************************************************************************* # Build a canopy ---- # ************************************************************************* tree <- buildCanopy(zvalue, root = root, novars=novars, title = title, parent = parent, var=vars[[1]], last = last, labels = labelnode[[vars[1]]], tlabelnode=tlabelnode, labelvar = labelvar[vars[1]], varminwidth=varminwidth[vars[1]],varminheight=varminheight[vars[1]],varlabelloc=varlabelloc[vars[1]], check.is.na=check.is.na, sameline=sameLINE, showvarinnode=showvarinnode,shownodelabels=shownodelabels[vars[1]], showpct=showPCT, showrootcount=showrootcount, showcount=showCOUNT, prefixcount=prefixcount, prune=prune[[vars[1]]], tprune=tprune, prunelone=prunelone, prunesmaller=prunesmaller, prunebigger=prunebigger, HTMLtext = HTMLtext, showvarnames = showvarnames, keep=keep[[vars[1]]], tkeep=tkeep, pruneNA=pruneNA, text = ThisLayerText, ttext=ttext,TopText = TopText, digits = digits, cdigits = cdigits, splitwidth = splitwidth, showempty = showempty, topcolor = color[1], color = color[2], topfillcolor = rootfillcolor, fillcolor = fillcolor[[vars[1]]], vp = vp, rounded = rounded, just=just, justtext=justtext, thousands=thousands, showroot=showroot, verbose=verbose,sortfill=sortfill) numsmallernodes <- tree$numsmallernodes sumsmallernodes <- tree$sumsmallernodes numbiggernodes <- tree$numbiggernodes sumbiggernodes <- tree$sumbiggernodes if (root) { treedata <- list(.n=nrow(z),.pct=100) } if (vars[[1]]!="") { if (root) { treedata <- list(.n=nrow(z),.pct=100) } else { treedata <- list() } children <- list() for (i in seq_len(length(tree$value))) { if (tree$extraText[i]!="") { children[[tree$value[i]]] <- list(.n=tree$n[i],.pct=tree$pct[i],.text=tree$extraText[i]) } else { children[[tree$value[i]]] <- list(.n=tree$n[i],.pct=tree$pct[i]) } } treedata[[vars[1]]] <- children } if (length(tree$nodenum)>0 && tree$nodenum[length(tree$nodenum)]>maxNodes) { stop( "Too many nodes. ", "Specify different variables ", "or change maxNodes parameter (currently set to ",maxNodes,").") } if (root & ptable) { if (length(labelvar)>0) { for (CNP in colnames(PATTERN_values)) { if (CNP %in% names(labelvar)) { for (i in 1:length(labelvar)) { colnames(PATTERN_values)[colnames(PATTERN_values)==names(labelvar)[i]] <- labelvar[i] } } } } if (vars[1]=="pattern" | vars[1]=="sequence") { patternTable <- data.frame(n=tree$n,pct=tree$pct, PATTERN_values[seq_len(length(tree$n)),],check.names=FALSE) if (length(summarytext)>0) { numsum <- max(sapply(summarytext,length)) for (j in 1:numsum) { patternTable[[paste0("summary_",j)]] <- "" } for (i in 1:length(summarytext)) { sm <- gsub("\n"," ",summarytext[[PATTERN_levels[i]]]) sm <- gsub("<BR/>"," ",sm) for (j in 1:length(sm)) { patternTable[[paste0("summary_",j)]][i] <- sm[j] } } } } } CurrentVar <- vars[1] if (CurrentVar %in% names(follow)) { followlevels <- follow[[CurrentVar]] } else { followlevels <- NULL } if (CurrentVar %in% names(prunebelow)) { prunebelowlevels <- prunebelow[[CurrentVar]] } else { prunebelowlevels <- NULL } tfollow_this_var <- FALSE if (length(tfollow)>0) { for (j in seq_len(length(tfollow))) { if (length(tfollow[[j]])==1 && any(names(tfollow[[j]])==CurrentVar)) { tfollow_this_var <- TRUE } } } tprunebelow_this_var <- FALSE if (length(tprunebelow)>0) { for (j in seq_len(length(tprunebelow))) { if (length(tprunebelow[[j]])==1 && any(names(tprunebelow[[j]])==CurrentVar)) { tprunebelow_this_var <- TRUE } } } tfollowlevels <- NULL tprunebelowlevels <- NULL # ************************************************************************* # Begin: Loop over variable levels ---- # ************************************************************************* varlevelindex <- 0 for (varlevel in tree$levels) { varlevelindex <- varlevelindex + 1 if (tfollow_this_var) { for (j in seq_len(length(tfollow))) { tfollowlevels <- c(tfollowlevels,unlist(tfollow[[j]][names(tfollow[[j]])==CurrentVar])) } } if (tprunebelow_this_var) { for (j in seq_len(length(tprunebelow))) { tprunebelowlevels <- c(tprunebelowlevels,unlist(tprunebelow[[j]][names(tprunebelow[[j]])==CurrentVar])) } } # ************************************************************************* ## Begin: Tracking of targeted nodes ---- # ************************************************************************* TTEXT <- ttext j <- 1 while (j <= length(TTEXT)) { if (!any(names(TTEXT[[j]])==CurrentVar)) { TTEXT[[j]] <- "" } else { if (TTEXT[[j]][CurrentVar]==varlevel) { TTEXT[[j]] <- TTEXT[[j]][names(TTEXT[[j]])!=CurrentVar] } else { if (TTEXT[[j]][CurrentVar]!=varlevel) { TTEXT[[j]] <- "" } } } j <-j + 1 } TSUMMARY <- tsummary j <- 1 while (j <= length(TSUMMARY)) { if (!any(names(TSUMMARY[[j]])==CurrentVar)) { TSUMMARY[[j]] <- "" } else { if (TSUMMARY[[j]][CurrentVar]==varlevel) { TSUMMARY[[j]] <- TSUMMARY[[j]][names(TSUMMARY[[j]])!=CurrentVar] } else { if (TSUMMARY[[j]][CurrentVar]!=varlevel) { TSUMMARY[[j]] <- "" } } } j <-j + 1 } TLABELNODE <- tlabelnode j <- 1 while (j <= length(TLABELNODE)) { if (!any(names(TLABELNODE[[j]])==CurrentVar)) { TLABELNODE[[j]] <- "" } else { if (TLABELNODE[[j]][CurrentVar]==varlevel) { TLABELNODE[[j]] <- TLABELNODE[[j]][names(TLABELNODE[[j]])!=CurrentVar] } else { if (TLABELNODE[[j]][CurrentVar]!=varlevel) { TLABELNODE[[j]] <- "" } } } j <-j + 1 } TPRUNE <- tprune j <- 1 while (j <= length(TPRUNE)) { if (!any(names(TPRUNE[[j]])==CurrentVar)) { TPRUNE[[j]] <- "" } else { if (TPRUNE[[j]][CurrentVar]==varlevel) { TPRUNE[[j]] <- TPRUNE[[j]][names(TPRUNE[[j]])!=CurrentVar] } else { if (TPRUNE[[j]][CurrentVar]!=varlevel) { TPRUNE[[j]] <- "" } } } j <-j + 1 } TKEEP <- tkeep j <- 1 while (j <= length(TKEEP)) { if (!any(names(TKEEP[[j]])==CurrentVar)) { TKEEP[[j]] <- "" } else { if (TKEEP[[j]][CurrentVar]==varlevel) { TKEEP[[j]] <- TKEEP[[j]][names(TKEEP[[j]])!=CurrentVar] } else { if (TKEEP[[j]][CurrentVar]!=varlevel) { TKEEP[[j]] <- "" } } } j <-j + 1 } TFOLLOW <- tfollow j <- 1 while (j <= length(TFOLLOW)) { if (!any(names(TFOLLOW[[j]])==CurrentVar)) { TFOLLOW[[j]] <- "" } else { if (TFOLLOW[[j]][CurrentVar]==varlevel) { TFOLLOW[[j]] <- TFOLLOW[[j]][names(TFOLLOW[[j]])!=CurrentVar] } else { if (TFOLLOW[[j]][CurrentVar]!=varlevel) { TFOLLOW[[j]] <- "" } } } j <-j + 1 } TPRUNEBELOW <- tprunebelow j <- 1 while (j <= length(TPRUNEBELOW)) { if (!any(names(TPRUNEBELOW[[j]])==CurrentVar)) { TPRUNEBELOW[[j]] <- "" } else { if (TPRUNEBELOW[[j]][CurrentVar]==varlevel) { TPRUNEBELOW[[j]] <- TPRUNEBELOW[[j]][names(TPRUNEBELOW[[j]])!=CurrentVar] } else { if (TPRUNEBELOW[[j]][CurrentVar]!=varlevel) { TPRUNEBELOW[[j]] <- "" } } } j <-j + 1 } if (tfollow_this_var) { followlevels <- tfollowlevels } if (tprunebelow_this_var) { prunebelowlevels <- tprunebelowlevels } # ************************************************************************* # End: Tracking of targeted nodes ---- # ************************************************************************* condition_to_follow <- !(varlevel %in% prunebelowlevels) & (is.null(followlevels) | (varlevel %in% followlevels)) & !(varlevel=="NA" & length(keep)>0 & (!is.null(keep[[CurrentVar]]) & !("NA" %in% keep[[CurrentVar]]))) if (condition_to_follow) { if (varlevel == "NA") { select <- is.na(z[[CurrentVar]]) | (!is.na(z[[CurrentVar]]) & z[[CurrentVar]]=="NA") } else { select <- which(z[[CurrentVar]] == varlevel) } if (length(select)>0 & numvars>=1) { zselect <- z[select, , drop = FALSE] for (index in seq_len(ncol(zselect))) { attr(zselect[[index]],"label") <- attr(z[[index]],"label") } # ************************************************************************* # Call vtree recursively ---- # ************************************************************************* fcChild <- vtree(data=zselect, vars=vars[-1], auto=FALSE,parent = tree$nodenum[varlevelindex], last = max(tree$nodenum), labelnode = labelnode, tlabelnode = TLABELNODE, colorvarlabels=colorvarlabels, check.is.na=check.is.na, tsummary=TSUMMARY, showvarinnode=showvarinnode,shownodelabels=shownodelabels, showpct=showpct, showcount=showcount, prefixcount=prefixcount, sameline=sameline, showempty = showempty, root = FALSE, prune=prune, prunebelow = prunebelow, tprunebelow=TPRUNEBELOW, prunesmaller=prunesmaller,prunebigger=prunebigger, tprune=TPRUNE, tkeep=TKEEP, labelvar = labelvar, varminwidth = varminwidth, varminheight = varminheight, varlabelloc=varlabelloc, prunelone=prunelone, nodefunc = nodefunc, nodeargs = nodeargs, digits = digits, showvarnames = showvarnames, keep=keep, follow=follow, tfollow=TFOLLOW, pruneNA=pruneNA, pattern=pattern,seq=seq, numsmallernodes=numsmallernodes,sumsmallernodes=sumsmallernodes, numbiggernodes=numbiggernodes,sumbiggernodes=sumbiggernodes, text = text, ttext=TTEXT,gradient=gradient,sortfill=sortfill, maxNodes=maxNodes, colornodes = colornodes, color = color[-1], fillnodes = fillnodes, fillcolor = fillcolor, splitwidth = splitwidth, HTMLtext=HTMLtext, vp = vp, rounded = rounded, just=just, justtext=justtext,thousands=thousands, verbose=verbose) if (!is.null(fcChild$treedata)){ treedata[[vars[1]]][[varlevel]] <- c(treedata[[vars[1]]][[varlevel]],fcChild$treedata) } tree <- joinflow(tree,fcChild) #browser() } } } tree$treedata <- treedata # ************************************************************************* # End: Loop over variable levels ---- # ************************************************************************* if (length(tree$nodenum)==0) { tree <- NULL } # ************************************************************************* # Begin code for root call only ---- # ************************************************************************* if (root) { if ((!is.null(prunesmaller) | !is.null(prunebigger)) && is.null(hideconstant)) { if (tree$numsmallernodes==0) { if (!is.null(prunesmaller)) { if (pattern) { message("No patterns had fewer than ",prunesmaller," cases") } else { message("No nodes were smaller than ",prunesmaller) } } } if (tree$numbiggernodes==0) { if (!is.null(prunebigger)) { if (pattern) { message("No patterns had more than than ",prunebigger," cases") } else { message("No nodes were larger than ",prunebigger) } } } else { if (!is.null(prunesmaller)) { if (pattern) { if (tree$numsmallernodes==1) { description <- " pattern was pruned, " } else { description <- " patterns were pruned, " } description <- paste0(description, "for a total of ",tree$sumsmallernodes," cases", " (",round(100*tree$sumsmallernodes/nrow(z)),"% of total)") } else { if (tree$numsmallernodes==1) { description <- " node was pruned." } else { description <- " nodes were pruned." } } message("Since prunesmaller=",prunesmaller,", ", tree$numsmallernodes,description) } if (!is.null(prunebigger)) { if (pattern) { if (tree$numbiggernodes==1) { description <- " pattern was pruned, " } else { description <- " patterns were pruned, " } description <- paste0(description, "for a total of ",tree$sumbiggernodes," cases", " (",round(100*tree$sumbiggernodes/nrow(z)),"% of total)") } else { if (tree$numbiggernodes==1) { description <- " node was pruned." } else { description <- " nodes were pruned." } } message("Since prunebigger=",prunebigger,", ", tree$numbiggernodes,description) } } } NL <- labelsAndLegends(z=z,OLDVARS=OLDVARS,vars=vars,labelvar=labelvar, HTMLtext=HTMLtext,vsplitwidth=vsplitwidth,just=just, colorvarlabels=colorvarlabels,varnamebold=varnamebold, varlabelcolors=varlabelcolors,varnamepointsize=varnamepointsize, showroot=showroot,rounded=rounded,numvars=numvars,Venn=Venn, labelnode=labelnode,fillcolor=fillcolor,showlegendsum=showlegendsum, thousands=thousands, splitwidth=splitwidth,nodefunc=nodefunc,nodeargs=nodeargs, showvarnames=showvarnames,check.is.na=check.is.na,vp=vp,showlpct=showlpct, digits=digits,legendpointsize=legendpointsize,horiz=horiz,color=color, showlegend=showlegend,pattern=pattern,sepN=sepN) # ************************************************************************* ## Outputs ---- # ************************************************************************* if (ptable) { pt <- patternTable[nrow(patternTable):1,] rownames(pt) <- NULL pt } else { if (novars) NL <- "" flowchart <- showflow(tree, getscript = getscript, font = font, nodesep = nodesep, ranksep=ranksep, margin=margin, nodelevels = NL, horiz = horiz, width=width,height=height, graphattr=graphattr,nodeattr=nodeattr,edgeattr=edgeattr) attributes(flowchart)$info <- treedata if (!imageFileOnly && (getscript || !pngknit || (!isTRUE(getOption('knitr.in.progress')) && !as.if.knit))) { return(flowchart) } if (imageFileOnly) { if (is.null(folder)) { folder <- "." } options(vtree_folder=folder) } if (is.null(getOption("vtree_count"))) { options("vtree_count"=0) if (is.null(folder)) { if (isTRUE(getOption('knitr.in.progress'))) { if (is.null(options()$vtree_folder)) { if (knitr::opts_knit$get("out.format") %in% c("latex","sweave","markdown")) { knitr.fig.path <- knitr::opts_chunk$get("fig.path") options(vtree_folder=knitr.fig.path) if (!dir.exists(knitr.fig.path)){ tf <- tempfile() cat("```{r}\nplot(0)\n```\n",file=tf) OUTPUT <- utils::capture.output(suppressMessages(knitr::knit_child(tf, options=list(fig.show='hide',warning=FALSE,message=FALSE)))) } } else { options(vtree_folder=tempdir()) } } } } else { options(vtree_folder=folder) } } options("vtree_count"=getOption("vtree_count")+1) padCount <- sprintf("%03d",getOption("vtree_count")) filenamestem <- paste0("vtree",padCount) outfmt <- knitr::opts_knit$get("out.format") if (format=="") { if (is.null(outfmt)) { format <- "png" } else { if (outfmt %in% c("latex","sweave")) { format <- "pdf" } else if (outfmt %in% c("markdown")) { format <- "png" } } } if (is.null(pxheight)) { if (is.null(pxwidth)) { fullpath <- grVizToImageFile(flowchart,width=2000, format=format,filename=filenamestem,folder=getOption("vtree_folder")) } else { fullpath <- grVizToImageFile(flowchart,width=pxwidth, format=format,filename=filenamestem,folder=getOption("vtree_folder")) } } else { if (is.null(pxwidth)) { fullpath <- grVizToImageFile(flowchart,height=pxheight, format=format,filename=filenamestem,folder=getOption("vtree_folder")) } else { fullpath <- grVizToImageFile(flowchart,width=pxwidth,height=pxheight, format=format,filename=filenamestem,folder=getOption("vtree_folder")) } } if (verbose) message("Image file saved to ",fullpath) if (imagewidth=="" && imageheight=="") { if (imageFileOnly && (!isTRUE(getOption('knitr.in.progress')) && !as.if.knit)) { return(invisible(NULL)) } else { output <- knitr::include_graphics(fullpath) attributes(output)$info <- treedata return(output) } } fmt <- knitr::opts_knit$get("out.format") if (!is.null(fmt) && fmt %in% c("latex","sweave")) { stuff <- "\n\\includegraphics[" if (!is.null(trim)) { stuff <- paste0(stuff,"trim=",paste(trim,collapse=" "),", clip,") } if (imageheight=="") { if (imagewidth=="") { result <- paste0(stuff," width=5.5in") } else { result <- paste0(stuff," width=",imagewidth) } } else { if (imagewidth=="") { result <- paste0(stuff," height=",imageheight) } else { result <- paste0(stuff," width=", imagewidth,", height=",imageheight) } } #if (absolutePath) { # np <- normalizePath(fullpath,"/") #} else { np <- fullpath #} result <- paste0(result,",keepaspectratio]{", np,"}\n") } else { embedded <- paste0("![](",fullpath,")") if (imageheight=="") { if (imagewidth=="") { result <- paste0(embedded,"{ height=3in }") } else { result <- paste0(embedded,"{width=",imagewidth,"}") } } else { if (imagewidth=="") { result <- paste0(embedded,"{height=",imageheight,"}") } else { result <- paste0(embedded,"{width=",imagewidth," height=",imageheight,"}") } } } if (imageFileOnly && (!isTRUE(getOption('knitr.in.progress')) && !as.if.knit)) { return(invisible(NULL)) } else { output <- knitr::asis_output(result) attributes(output)$info <- treedata output } } } else { tree } # The End ---- }
/scratch/gouwar.j/cran-all/cranData/vtree/R/vtree.R
## ---- echo=FALSE------------------------------------------------------------------------ suppressMessages(library(ggplot2)) library(vtree) #source("../source.R") options(width=90) options(rmarkdown.html_vignette.check_title = FALSE) ## ---- echo=FALSE------------------------------------------------------------------------ spaces <- function (n) { paste(rep("&nbsp;", n), collapse = "") } ## ---- echo=FALSE------------------------------------------------------------------------ df <- build.data.frame( c("continent","population","landlocked"), list("Africa","Over 30 million","landlocked",2), list("Africa","Over 30 million","not landlocked",12), list("Africa","Under 30 million","landlocked",14), list("Africa","Under 30 million","not landlocked",26)) ## --------------------------------------------------------------------------------------- plot(0) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(df,"v1 v2") ## ---- eval=FALSE------------------------------------------------------------------------ # simple_tree <- vtree(df,"v1 v2") ## ---- eval=FALSE------------------------------------------------------------------------ # simple_tree ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(df) ## ----eval=FALSE, results="asis"--------------------------------------------------------- # vtree(FakeData,"Severity") ## ----eval=FALSE------------------------------------------------------------------------- # library(dplyr) # FakeData %>% rename("HowBad"=Severity) %>% vtree("HowBad") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex",showlegend=TRUE,shownodelabels=FALSE) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex",prune=list(Severity=c("Mild","Moderate"))) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate")) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"),vp=FALSE) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex",prunebelow=list(Severity=c("Mild","Moderate"))) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Sex Severity",tkeep=list(list(Sex="M",Severity="Moderate"))) ## ---- eval=FALSE------------------------------------------------------------------------ # tkeep=list(list(Sex="M",Severity=c("Moderate","Severe")),list(Sex=F",Severity="Mild")) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Severity Sex Age Category",sameline=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,prunesmaller=3) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Sex",horiz=FALSE,labelvar=c(Severity="Initial severity")) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Group Sex",horiz=FALSE,labelnode=list(Sex=c(Male="M",Female="F"))) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Group Sex",horiz=FALSE, # labelnode=list(Group=c(Child="A",Adult="B")), # tlabelnode=list( # c(Group="A",Sex="F",label="girl"), # c(Group="A",Sex="M",label="boy"), # c(Group="B",Sex="F",label="woman"), # c(Group="B",Sex="M",label="man"))) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, # text=list(Severity=c(Mild="\n*Excluding\nnew diagnoses*"))) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, # ttext=list( # c(Group="B",Severity="Mild",text="\n*Excluding\nnew diagnoses*"), # c(Group="A",text="\nSweden"), # c(Group="B",text="\nNorway"))) ## ----eval=FALSE------------------------------------------------------------------------- # library(dplyr) # FakeData %>% mutate(missingScore=is.na(Score)) %>% vtree("missingScore") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"is.na:Score") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,summary="Score") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity",summary="Score",horiz=FALSE) ## ----attributes------------------------------------------------------------------------- vSeverity <- vtree(FakeData,"Severity",summary="Score",horiz=FALSE) info <- attributes(vSeverity)$info cat(info$Severity$Mild$.text) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,summary="Category") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,summary="Event") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity",summary="Category=single",horiz=FALSE) ## ----summary-pattern,eval=FALSE--------------------------------------------------------- # vtree(FakeData,"Severity",summary="Ind*",sameline=TRUE,horiz=FALSE,just="l") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Severity Category",summary="Score<10 %var=Category%%node=single%", # sameline=TRUE, showlegend=TRUE, showlegendsum=TRUE) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity",summary="Score \nmean score\n%mean%",sameline=TRUE,horiz=FALSE) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Category", # summary="(Post-Pre)/Pre \nmean = %mean%",sameline=TRUE,horiz=FALSE,cdigits=1) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity",horiz=FALSE,showvarnames=FALSE,splitwidth=Inf,sameline=TRUE, # summary=c("Score \nScore: mean (SD) %meanx% (%SD%)","Pre \nPre: range %range%")) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Age Sex",tsummary=list(list(Age="5",Sex="M","id \n%list%")),horiz=FALSE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Severity Sex") # vtree(FakeData,"Severity Sex",pattern=TRUE) ## --------------------------------------------------------------------------------------- vtree(FakeData,"Severity Sex",ptable=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Ind1 Ind2 Ind3 Ind4",Venn=TRUE,pattern=TRUE) ## --------------------------------------------------------------------------------------- vtree(FakeData,"Ind1 Ind2",ptable=TRUE) ## --------------------------------------------------------------------------------------- VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE)) ## --------------------------------------------------------------------------------------- print(VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE)),quote=FALSE) ## ---- eval=FALSE------------------------------------------------------------------------ # `r VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE),markdown=TRUE)` ## --------------------------------------------------------------------------------------- vtree(FakeData,"Severity Sex",summary=c("Score %mean%","Pre %mean%"),ptable=TRUE) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # `r VennTable(vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,ptable=TRUE), # markdown=TRUE)` ## --------------------------------------------------------------------------------------- vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,summary="id %list%%trunc=15%", ptable=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Sex Severity",palette=c(3,4)) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeData,"Sex Group Severity",revgradient=c(Sex=TRUE,Severity=TRUE)) ## --------------------------------------------------------------------------------------- dessert <- build.data.frame( c( "group","IceCream___1","IceCream___2","IceCream___3"), list("A", 1, 0, 0, 7), list("A", 1, 0, 1, 2), list("A", 0, 0, 0, 1), list("A", 1, 1, 1, 1), list("B", 1, 0, 1, 1), list("B", 1, 0, 0, 2), list("B", 0, 1, 1, 1), list("B", 0, 0, 0, 1)) attr(dessert$IceCream___1,"label") <- "Ice cream (choice=Chocolate)" attr(dessert$IceCream___2,"label") <- "Ice cream (choice=Vanilla)" attr(dessert$IceCream___3,"label") <- "Ice cream (choice=Strawberry)" ## ----eval=FALSE------------------------------------------------------------------------- # vtree(dessert,"r:IceCream___1") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(dessert,"r:IceCream@") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(dessert,"rnone:IceCream@") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(dessert,"ri:IceCream@") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(dessert,"IceCream___1 IceCream___2 IceCream___3",pattern=TRUE) ## ----eval=FALSE------------------------------------------------------------------------- # vtree(dessert,"stem:IceCream",pattern=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(dessert,summary="stem:IceCream",splitwidth=Inf,just="l") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(dessert,"rc:IceCream___1 rc:IceCream___3",pattern=TRUE) ## ---- comment=""------------------------------------------------------------------------ dotscript <- vtree(FakeData,"Severity",getscript=TRUE) cat(dotscript) ## ----echo=TRUE,message=FALSE,eval=FALSE------------------------------------------------- # v <- vtree(FakeData,"Group Viral",horiz=FALSE) # v ## ----echo=FALSE,message=FALSE----------------------------------------------------------- v <- vtree(FakeData,"Group Viral",pxwidth=800,imageheight="2in",horiz=FALSE) v ## ----echo=TRUE,message=FALSE------------------------------------------------------------ attributes(v)$info ## ---- eval=FALSE,echo=TRUE-------------------------------------------------------------- # <unknown>:1919791: Invalid asm.js: Function definition doesn't match use ## ---- eval=FALSE------------------------------------------------------------------------ # `r vtree(FakeData,"Sex Severity")` ## --------------------------------------------------------------------------------------- build.data.frame( c("pet","breed","size"), list("dog","golden retriever","large",5), list("cat","tabby","small",2)) ## ---- eval=FALSE------------------------------------------------------------------------ # build.data.frame( # c("pet","breed","size"), # list("dog","golden retriever","large",5), # list("cat","tabby","small",2), # list("dog","Dalmation","various",101), # list("cat","Abyssinian","small",5), # list("cat","Abyssinian","large",22), # list("cat","tabby","large",86)) ## --------------------------------------------------------------------------------------- FakeRCT ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, # keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), # horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility") ## ----eval=FALSE------------------------------------------------------------------------- # vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, # follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), # horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, # follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), # horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", # summary="id \nid: %list% %noroot%") ## ---- eval=FALSE------------------------------------------------------------------------ # # Relabel agegp 75+ to 75plus because vtree tries to parse the + # ESOPH <- esoph # levels(ESOPH$agegp)[levels(ESOPH$agegp)=="75+"] <- "75plus" # # vtree(ESOPH,"agegp=75plus",sameline=TRUE,cdigits=0, # summary=c("ncases \ncases=%sum%%leafonly%","ncontrols controls=%sum%%leafonly%")) ## ---- eval=FALSE------------------------------------------------------------------------ # hec <- crosstabToCases(HairEyeColor) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(hec,"Hair Eye=Green Sex",sameline=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # titanic <- crosstabToCases(Titanic) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(titanic,"Class Sex Age",summary="Survived=Yes \n%pct% survived",sameline=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # mt <- mtcars # mt$name <- rownames(mt) # rownames(mt) <- NULL ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(mt,"cyl gear carb",summary="hp \nmean (SD) HP %mean% (%SD%)") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(mt,"cyl gear carb",summary="hp mean (SD) HP %mean% (%SD%)", # cdigits=0,labelvar=c(cyl="# cylinders",gear="# gears",carb="# carburetors"), # ptable=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(mt,"gear carb",summary="name \n%list%%noroot%",splitwidth=50,sameline=TRUE, # labelvar=c(gear="# gears",carb="# carburetors")) ## ---- eval=FALSE------------------------------------------------------------------------ # ucb <- crosstabToCases(UCBAdmissions) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(ucb,"Dept Gender",summary="Admit=Admitted \n%pct% admitted",sameline=TRUE) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(ChickWeight,"Diet Time", # keep=list(Time=c("0","4")),summary="weight \nmean weight %mean%g") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(ChickWeight,"Diet Time",keep=list(Time=c("0","4")), # labelnode=list( # Diet=c("Diet 1"="1","Diet 2"="2","Diet 3"="3","Diet 4"="4"), # Time=c("0 days"="0","4 days"="4")), # labelvar=c(Time="Days since birth"),summary="weight \nmean weight %mean%g") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(InsectSprays,"spray",splitwidth=80,sameline=TRUE, # summary="count \ncounts: %list%%noroot%",cdigits=0) ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(ToothGrowth,"supp dose",summary="len>20 \n%pct% length > 20") ## ---- eval=FALSE------------------------------------------------------------------------ # vtree(ToothGrowth,"supp dose",summary="len>20 \n%pct% length > 20", # labelvar=c("supp"="Supplement type","dose"="Dose (mg/day)"), # labelnode=list(supp=c("Vitamin C"="VC","Orange Juice"="OJ")))
/scratch/gouwar.j/cran-all/cranData/vtree/inst/doc/vtree.R
--- title: "Introduction to vtree" subtitle: "*Exploring subsets of data using variable trees*" author: '`r paste0("Nick Barrowman, ",strftime(Sys.time(),format="%d-%b-%Y"),", Version ",packageVersion("vtree"))`' output: rmarkdown::html_vignette: css: vtreeVignette.css toc: true toc_depth: '2' vignette: > %\VignetteIndexEntry{Introduction to vtree} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo=FALSE} suppressMessages(library(ggplot2)) library(vtree) #source("../source.R") options(width=90) options(rmarkdown.html_vignette.check_title = FALSE) ``` ```{r, echo=FALSE} spaces <- function (n) { paste(rep("&nbsp;", n), collapse = "") } ``` # Introduction vtree is a flexible tool for calculating and displaying *variable trees* &mdash; diagrams that show information about nested subsets of a data frame. vtree can be used to: 1. explore a data set interactively 2. produce customized figures for reports and publications. Note, however, that vtree is *not* designed to build or display decision trees. Given a data frame and simple specifications, vtree will produce a variable tree and automatically label it with counts, percentages, and other summaries. The sections below introduce variable trees and provide an overview of the features of vtree. Or you can [skip ahead and start using the `vtree` function](#vtreeFunction). ## Two examples *Subsets* play an important role in almost any data analysis. Imagine a data set of countries that includes variables named `population`, `continent`, and `landlocked`. Suppose we wish to examine subsets of the data set based on the `continent` variable. Within each of these subsets, we could examine *nested* subsets based on the `population` variable, for example, countries with populations under 30 million and over 30 million. We might continue to a third nesting based on the `landlocked` variable. Nested subsets are at the heart of questions like the following: *Among African countries with a population over 30 million, what percentage are landlocked?* The variable tree below provides the answer: ```{r, echo=FALSE} df <- build.data.frame( c("continent","population","landlocked"), list("Africa","Over 30 million","landlocked",2), list("Africa","Over 30 million","not landlocked",12), list("Africa","Under 30 million","landlocked",14), list("Africa","Under 30 million","not landlocked",26)) ``` `r spaces(30)` `r vtree(df,"continent population landlocked",showroot=FALSE,pxwidth=800, imageheight="3in")` By default, vtree uses the colorful display above (to help distinguish variables and values), but if you prefer a more sedate version, you can specify a single fill color (or simply white): `r spaces(30)` `r vtree(df,"continent population landlocked",showroot=FALSE,fillcolor="aliceblue", pxwidth=800,imageheight="3in")` Even in simple situations like this, it can be a chore to keep track of nested subsets and calculate the corresponding percentages. The denominator used to calculate percentages may also depend on whether the variables have any missing values, as discussed later. Finally, as the number of variables increases, the magnitude of the task balloons, because the number of nested subsets grows exponentially. vtree provides a general solution to the problem of calculating nested subsets and displaying information about them. Nested subsets arise in all kinds of situations. Consider, for example, flow diagrams for clinical studies, such as the following [CONSORT](http://www.consort-statement.org)-style diagram, produced by vtree. `r spaces(50)` `r vtree(FakeRCT,"eligible randomized group followup",plain=TRUE, keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", pxwidth=500,imageheight="4.5in") ` Both the structure of this variable tree and the numbers shown were automatically determined. When manual calculation and transcription are instead used to populate diagrams like this, mistakes are likely. And although the errors that make it into published articles are often minor, they can sometimes be disastrous. One motivation for developing vtree was to make flow diagrams [reproducible](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3383002/). The ability to reproducibly generate variable trees also means that when a data set is updated, a revised tree can be automatically produced. At the end of this vignette, there is a collection of [examples of variable trees using R datasets](#RdatasetExamples) that you can try. ## Basic features of a variable tree The examples that follow use a data set called `FakeData` which represents `r nrow(FakeData)` fictitious patients. We'll start by using just two variables, although variable trees are especially useful with three or more variables. The variable tree below depicts subsets defined by `Sex` (M or F) nested within subsets defined by disease `Severity` (Mild, Moderate, Severe, or NA). `r vtree(FakeData,"Severity Sex",showlegend=FALSE,horiz=FALSE, pxwidth=1000,imageheight="2.2in")` A variable tree consists of *nodes* connected by arrows. At the top of the diagram above, the *root* node of the tree contains all 46 patients. The rest of the nodes are arranged in successive layers, where each layer corresponds to a specific variable. Note that this highlights one difference between variable trees and some other kinds of trees: each layer of a variable tree corresponds to just one variable. (In a *decision tree*, by contrast, different branches can have different sequences of variable splits.) Continuing with the variable tree above, the nodes immediately below the root represent values of `Severity` and are referred to as the *children* of the root node. In this case, `Severity` was missing (NA) for 6 patients, and there is a node for these patients. Inside each of the nodes, the number of patients is displayed and---except for in the missing value node---the corresponding percentage is also shown. Note that, by default, `vtree` displays "valid" percentages, i.e. the denominator used to calculate the percentage is the total number of *non-missing* values, `r sum(!is.na(FakeData$Severity))`. The final layer of the tree corresponds to values of `Sex`. These nodes represent males and females *within subsets* defined by each value of `Severity`. In each of these nodes the percentage is calculated in terms of the number of patients in its parent node. Like any node, a missing-value node can have children. For example, of the 6 patients for whom `Severity` is missing, 3 are female and 3 are male. By default, `vtree` displays the full missing-value structure of the specified variables. Also by default, `vtree` automatically assigns a color palette to the nodes of each variable. `Severity` has been assigned red hues (lightest for Mild, darkest for Severe), while `Sex` has been assigned blue hues (light blue for females, dark blue for males). The node representing missing values of `Severity` is colored white to draw attention to it. ## Variable trees compared to contingency tables A tree with two variables is similar to a two-way contingency table. In the example above, `Sex` is shown within levels of `Severity`. This corresponds to the following contingency table, where the percentages within each column add to 100%. These are called *column percentages*. &nbsp;| Mild | Moderate | Severe | NA ------|-----------|----------|----------|--------- **F** | 11 (58%) | 11 (69%) | 2 (40%) | 3 (50%) **M** | 8 (42%) | 5 (31%) | 3 (60%) | 3 (50%) Likewise, a tree with `Severity` shown within levels of `Sex` corresponds to a contingency table with *row percentages*. While the contingency table above is more compact than the corresponding variable tree, some people find the variable tree more intuitive. When three or more variables are of interest, multi-way contingency tables are often used. These are typically displayed using several two-way tables, but as the number of variables increases, these become increasingly difficult to interpret. Variable trees, on the other hand, have the same simple structure regardless of the number of variables. Note that contingency tables are not *always* more compact than variable trees. When most cells of a large contingency table are empty (in which case the table is said to be *sparse*), the corresponding variable tree may be more compact since empty nodes are not shown. ## Features of vtree vtree is designed to be quick and easy to use, so that it is convenient for data exploration, but also flexible enough that it can be used to prepare publication-ready figures. To generate a basic variable tree, it is only necessary to specify a data frame and some variable names. However extra features extend this basic functionality to provide: * control over [labeling](#labeling), [colors](#colors), [legends](#legends), [line wrapping](#wrapping), and [text formatting](#textFormatting); * flexible [pruning](#pruning) to remove parts of the tree that are of lesser interest, which is particularly useful when a tree gets large; * [display of information about other variables in each node](#summary), including a variety of summary statistics; * special displays for [indicator variables](#Venn), [patterns](#patterns) of values, and [missingness](#missingValues); * support for [checkbox variables](#REDCapCheckboxes) from [REDCap](https://www.project-redcap.org) databases; * features for [dichotomizing variables](#dichotomizing) and [checking for outliers](#detectingOutliers); * automatic generation of PNG image files and [embedding in R Markdown](#embeddingInKnitrRmarkdown) documents; and * interactive panning and zooming using the `svtree` function to launch a [Shiny app](#svtree). In many cases, you may wish to generate several different variable trees to investigate a collection of variables in a data frame. For example, it is often useful to change the order of variables, prune parts of the tree, etc. ## Technical overview vtree is built on open-source software: in particular Richard Iannone's [DiagrammeR](http://rich-iannone.github.io/DiagrammeR/) package, which provides an interface to the [Graphviz](https://www.graphviz.org/) software using the [htmlwidgets](https://www.htmlwidgets.org/) framework. Additionally, vtree makes use of the [Shiny](https://www.rstudio.com/products/shiny/) package, and the [svg-pan-zoom](https://github.com/bumbu/svg-pan-zoom) JavaScript library. A formal description of variable trees follows. The root node of the variable tree represents the entire data frame. The root node has a child for each observed value of the first variable that was specified. Each of these child nodes represents a subset of the data frame with a specific value of the variable, and is labeled with the number of observations in the subset and the corresponding percentage of the number of observations in the entire data frame. The *n*^th^ layer below the root of the variable tree corresponds to the *n*^th^ variable specified. Apart from the root node, each node in the variable tree represents the subset of its parent defined by a specific observed value of the variable at that layer of the tree, and is labeled with the number of observations in that subset and the corresponding percentage of the number of observations in its parent node. Note that a node always represents at least one observation. And unlike a contingency table, which can have empty cells, a variable tree has no empty nodes. # The `vtree` function {#vtreeFunction} Consider a data frame named `df`, which includes discrete variables `v1` and `v2`. Suppose we wish to produce a variable tree showing subsets based on values of `v1` as well as subsets of those subsets based on values of `v2`. The variable tree can be displayed using the following command: ```{r, eval=FALSE} vtree(df,"v1 v2") ``` Alternatively, you may wish to assign the output of `vtree` to an object: ```{r, eval=FALSE} simple_tree <- vtree(df,"v1 v2") ``` Then it can be displayed later using: ```{r, eval=FALSE} simple_tree ``` Suppose `vtree` is called without a list of variables: ```{r, eval=FALSE} vtree(df) ``` In this case, only the root node is shown, representing the entire data frame. Although a tree with just one node might not seem very useful, we'll see later that [summary information](#summary) about the whole data frame can be displayed there. The `vtree` function has numerous optional parameters. For example, by default `vtree` produces a horizontal tree (that is, a tree that grows from left to right). To generate a vertical tree, specify `horiz=FALSE`. ## Mini tutorial *This section introduces some basic features of the `vtree` function.* To display a variable tree for a single variable, say `Severity`, use the following command: ```{r,eval=FALSE, results="asis"} vtree(FakeData,"Severity") ``` `r spaces(45)` `r vtree(FakeData,"Severity",width=250,height=250,pxwidth=300,imageheight="2.5in")` By default, next to each layer of the tree, a variable name is shown. In the example above, "Severity" is shown below the corresponding nodes. (For a vertical tree, "Severity" would be shown to the left of the nodes.) If you specify `showvarnames=FALSE`, no variable names will be shown. `vtree` can also be used with dplyr. For example, to rename the `Severity` variable as `HowBad`, we can pipe the data frame into the `rename` function in dplyr, and then pipe the result into `vtree`: ```{r,eval=FALSE} library(dplyr) FakeData %>% rename("HowBad"=Severity) %>% vtree("HowBad") ``` Note that `vtree` also has a [built-in way of renaming variables](#labeling), which is an alternative to using dplyr. Large variable trees can be difficult to display in a readable way. One approach that helps is to display the count and percentage on the same line in each node. For example, in the tree above, the label for the Moderate node is on two lines, like this: `r spaces(65)`**Moderate** \ `r spaces(65)`**16 (40%)** Specifying `sameline=TRUE` results in single-line labels, like this: `r spaces(65)`**Moderate, 16 (40%)** ### Percentages By default, vtree shows "valid percentages", i.e. percentages calculated using the total number of *non-missing* values as denominator. In the case of `Severity`, there are `r sum(is.na(FakeData$Severity))` missing values, so the denominator is `r nrow(FakeData)` - `r sum(is.na(FakeData$Severity))`, or `r nrow(FakeData) - sum(is.na(FakeData$Severity))`. There are `r sum(FakeData$Severity %in% "Mild")` Mild cases, and `r sum(FakeData$Severity %in% "Mild")`/`r nrow(FakeData) - sum(is.na(FakeData$Severity))` = `r sum(FakeData$Severity %in% "Mild")/(nrow(FakeData) - sum(is.na(FakeData$Severity)))` so the percentage shown is 48%. No percentage is shown in the NA node since missing values are not included in the denominator. If you prefer the denominator to represent the complete set of observations (*including* any missing values), specify `vp=FALSE`. A percentage will be shown in each of the nodes, including any NA nodes. If you don't wish to see percentages, specify `showpct=FALSE`, and if you don't wish to see counts, specify `showcount=FALSE`. ### Displaying a legend and hiding node labels {#legends} To display a legend, specify `showlegend=TRUE`. Next to each variable name are "legend nodes" representing the values of that variable and colored accordingly. For each variable, the legend nodes are grouped within a light gray box. Each legend node also contains a count (with a percentage) for the value represented by that node in the whole data frame. This is known as the *marginal* count (and percentage). When the legend is shown, labels in the nodes of the variable tree are redundant, since the colors of the nodes identify the values of the variables (although the labels may aid readability). If you prefer, you can hide the node labels, by specifying `shownodelabels=FALSE`: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",showlegend=TRUE,shownodelabels=FALSE) ``` `r spaces(45)` `r vtree(FakeData,"Severity Sex",showlegend=TRUE,shownodelabels=FALSE, pxwidth=800,imageheight="4in")` Since `Severity` is the first variable in the tree, it is not nested within another variable. Therefore the marginal counts and percentages for `Severity` shown in the legend nodes are identical to those displayed in the nodes of the variable tree. In contrast, for `Sex`, the marginal counts and percentages are different from what is shown in the nodes of the variable tree for `Sex` since they are nested within levels of `Severity`. ### Text wrapping {#wrapping} By default, `vtree` wraps text onto the next line whenever a space occurs after at least 20 characters. This can be adjusted, for example, to 15 characters, by specifying `splitwidth=15`. To disable line splitting, specify `splitwidth=Inf` (`Inf` means infinity, i.e. "do not split".) The `vsplitwidth` parameter is similarly used to control text wrapping in variable names. This is helpful with long variable names, which may be truncated unless wrapping is used. In this case text wrapping occurs not only at spaces, but also at any of the following characters: ```{eval=FALSE} . - + _ = / ( ``` For example if `vsplitwidth=5`, a variable name like `First_Emergency_Visit` would be split into `r spaces(65)``First_`\ `r spaces(65)``Emergency_`\ `r spaces(65)``Visit` *This concludes the mini-tutorial. vtree has many more features, described in the following sections.* ## Pruning {#pruning} *This section shows how to remove branches from a variable tree.* When a variable tree gets too big, or you are only interested in certain parts of the tree, it may be useful to remove some nodes along with their descendants. This is known as *pruning*. For convenience, there are several different ways to prune a tree, described below. ### The `prune` parameter Here's a variable tree we've already seen in various forms: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex") ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex", pxwidth=800,imageheight="4.2in")` Suppose you don't want the tree to show branches for individuals whose disease is Mild or Moderate. Specifying `prune=list(Severity=c("Mild","Moderate"))` removes those nodes, and all of their descendants: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",prune=list(Severity=c("Mild","Moderate"))) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",prune=list(Severity=c("Mild","Moderate")), pxwidth=500,imageheight="2.5in")` In general, the argument of the `prune` parameter is a *list* with an element named for each variable you wish to prune. In the example above, the list has a single element, named `Severity`. In turn, that element is a vector `c("Mild","Moderate")` indicating the values of `Severity` to prune. **Caution**: Once a variable tree has been pruned, it is no longer complete. This can sometimes be confusing since not all observations are represented at certain layers of the tree. For example in the tree above, only 11 observations are shown in the `Severity` nodes and their children. ### The `keep` parameter Sometimes it is more convenient to specify which nodes should be *retained* rather than which ones should be discarded. The `keep` parameter is used for this purpose, and can thus be considered the complement of the `prune` parameter. For example, to retain the Moderate `Severity` node: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate")) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"), pxwidth=500,imageheight="1.7in")` **Note**: In addition to the Moderate node, the missing value node has also been retained. In general, whenever valid percentages are used (which is the default), missing value nodes are retained when `keep` is used. This is because valid percentages are difficult to interpret without knowing the denominator, which requires knowing the number of missing values. On the other hand, here's what happens when `vp=FALSE`: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"),vp=FALSE) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"),vp=FALSE, pxwidth=400,imageheight="1.5in")` ### The `prunebelow` parameter As seen above, a disadvantage of pruning is that in the resulting tree, the counts shown in child nodes may not add up to the counts shown in their parent node. An alternative is to prune *below* the specified nodes (i.e. to prune their descendants), so that the counts always add up. In the present example, this means that the Mild and Moderate nodes will be shown, but not their descendants. The `prunebelow` parameter is used to do this: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",prunebelow=list(Severity=c("Mild","Moderate"))) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",prunebelow=list(Severity=c("Mild","Moderate")), pxwidth=400,imageheight="3in")` ### The `follow` parameter The complement of `prunebelow` is `follow`. Instead of specifying which nodes should be pruned below, this allows you to specify which nodes should be "followed" (that is, *not* pruned below). ### Targeted pruning This section describes a more flexible way to prune variable trees. To explain this, first note that the `prune`, `keep`, `prunebelow`, and `follow` parameters specify pruning across all branches of the tree. For example, if you were pruning `Severity` nested within levels of `Sex`, the pruning would take place in both the M and F branches. Sometimes, however, it is preferable to perform pruning only in specified branches of the tree. This is called *targeted* pruning, and the parameters `tprune`, `tkeep`, `tprunebelow`, and `tfollow` provide this functionality. However, their arguments have a more complex form than those of the corresponding `prune`, `keep`, `prunebelow`, and `follow` parameters because they specify the *full path* from the root of the tree all the way to the nodes to be pruned. For example to remove every `Severity` node except Moderate, but only for males, the following command can be used: ```{r,eval=FALSE} vtree(FakeData,"Sex Severity",tkeep=list(list(Sex="M",Severity="Moderate"))) ``` `r spaces(40)` `r vtree(FakeData,"Sex Severity",tkeep=list(list(Sex="M",Severity="Moderate")), pxwidth=400,imageheight="3in")` Note that the argument of `tkeep` is a list of lists, one for each path through the tree. To keep both Moderate and Severe, specify `tkeep=list(list(Sex="M",Severity=c("Moderate","Severe")))`. Now suppose that, in addition to this, within females,you want to keep just Mild. Use the following specification to do this: ```{r, eval=FALSE} tkeep=list(list(Sex="M",Severity=c("Moderate","Severe")),list(Sex=F",Severity="Mild")) ``` ### The `prunesmaller` parameter As a variable tree grows, it can become difficult to see the forest for the tree. For example, the following tree is hard to read, even when `sameline=TRUE` has been specified: ```{r, eval=FALSE} vtree(FakeData,"Severity Sex Age Category",sameline=TRUE) ``` `r spaces(50)` `r vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,imageheight="5.5in",pxwidth=500)` One solution is to prune nodes that contain small numbers of observations. For example if you want to only see nodes with at least 3 observations, you can specify `prunesmaller=3`, as in this example: ```{r, eval=FALSE} vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,prunesmaller=3) ``` `r spaces(35)` `r vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,prunesmaller=3, imageheight="4in",pxwidth=800)` As with the `keep` parameter, when valid percentages are used (`vp=TRUE`, which is the default), nodes represent missing values will not be pruned. (As noted previously, this is because percentages are confusing when missing values are not shown.) On the other hand, when `vp=FALSE`, missing nodes will be pruned (if they are small enough). ## Labels for variables and nodes {#labeling} *This section shows how to relabel variables and nodes.* By default, `vtree` labels variables and nodes exactly as they appear in the data frame. But it is often useful to change these labels. ### Changing variable labels with the `labelvar` parameter Suppose `Severity` in fact represents initial severity. To label it that way in the variable tree, specify `labelvar=c(Severity="Initial severity")`: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",horiz=FALSE,labelvar=c(Severity="Initial severity")) ``` `r spaces(30)` `r vtree(FakeData,"Severity Sex",horiz=FALSE, labelvar=c(Severity="Initial severity"), pxwidth=1000,imageheight="2in")` ### Changing node labels with the `labelnode` parameter By default, `vtree` labels nodes (except for the root node) using the values of the variable in question. Sometimes it is convenient to instead specify custom labels for nodes. The `labelnode` argument can be used to relabel the values. For example, you might want to use "Male" and "Female" instead of "M" and "F". ```{r,eval=FALSE} vtree(FakeData,"Group Sex",horiz=FALSE,labelnode=list(Sex=c(Male="M",Female="F"))) ``` `r spaces(30)` `r vtree(FakeData,"Group Sex",horiz=FALSE,labelnode=list(Sex=c(Male="M",Female="F")), pxwidth=600,imageheight="1.8in")` The argument of the `labelnode` parameter is specified as a list whose element names are variable names. To substitute a new label for an old label, the syntax is: `"New label"="Old label"`. Thus the full specification, as used above, is: `labelnode=list(Sex=c(Male="M",Female="F"))`. ### Targeted node labels using the `tlabelnode` parameter Suppose in the example above that `Group` A represents children and `Group` B represents adults. In `Group` A, we would like to use the labels "girl" and "boy", while in `Group` B we would like to use "woman" and "man". The `labelnode` parameter cannot handle this situation because the values of `Sex` need to be labeled differently in different branches of the tree. The `tlabelnode` parameter allows "targeted" node labels. ```{r,eval=FALSE} vtree(FakeData,"Group Sex",horiz=FALSE, labelnode=list(Group=c(Child="A",Adult="B")), tlabelnode=list( c(Group="A",Sex="F",label="girl"), c(Group="A",Sex="M",label="boy"), c(Group="B",Sex="F",label="woman"), c(Group="B",Sex="M",label="man"))) ``` `r spaces(40)` `r vtree(FakeData,"Group Sex",horiz=FALSE, labelnode=list(Group=c(Child="A",Adult="B")), tlabelnode=list( c(Group="A",Sex="F",label="girl"), c(Group="A",Sex="M",label="boy"), c(Group="B",Sex="F",label="woman"), c(Group="B",Sex="M",label="man")), pxwidth=600,imageheight="2.2in")` ## Text and text formatting {#textFormatting} *This section shows how to add bold, italics, and other text formatting.* Graphviz, the open source graph visualization software that vtree is built on, supports a variety of text formatting (including bold, colors, etc.). This is used in vtree to control formatting of text such as node labels. ### Markdown-style codes for text formatting By default, the `vtree` package uses markdown-style codes for text formatting. In the tables below, `...` represents arbitrary text. ------------- ----------------------------------------------------------------- `\n` insert a line break `\n*l` make the preceding line left-justified and insert a line break `*...*` display text in italics `**...**` display text in bold `^...^` display text in superscript (using 10 point font) `~...~` display text in subscript (using 10 point font) `%%red ...%%` display text in red (or whichever color is specified) ------------- ----------------------------------------------------------------- ### HTML-like codes for text formatting As an alternative, if you specify `HTMLtext=TRUE` you can use "HTML-like labels" (implemented in Graphviz), including: ---------------------------------- ---------------------------------------------------------- `<BR/>` insert a line break `<BR ALIGN='LEFT'/>` make the preceding line left-justified and insert a line break `<I> ... </I>` display text in italics `<B> ... </B>` display text in bold `<SUP> ... </SUP>` display text in superscript (using 10 point font) `<SUB> ... </SUB>` display text in subscript (using 10 point font) `<FONT POINT-SIZE='10'> ... </FONT>` set font to 10 point `<FONT FACE='Times-Roman'> ... </FONT>` set font to Times-Roman `<FONT COLOR='red'> ... </FONT>` set font to red ---------------------------------- ---------------------------------------------------------- See <https://www.graphviz.org/doc/info/shapes.html#html> for more details. ### Adding text to nodes using the `text` parameter Suppose you wish to add the italicized text "*Excluding new diagnoses*" to any Mild nodes in the tree. The parameter `text` is used to add text to nodes. It is specified as a list with an element named for each variable. In the example below the list has one element, named `Severity`. That element in turn is a vector `c(Mild="\n*Excluding\nnew diagnoses*")` indicating that the Mild node should include additional text using Markdown-style formatting (i.e. `\n` indicates a linebreak and the asterisks around the text indicate that it should be displayed in italics): ```{r,eval=FALSE} vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, text=list(Severity=c(Mild="\n*Excluding\nnew diagnoses*"))) ``` `r spaces(15)` `r vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, text=list(Severity=c(Mild="\n*Excluding\nnew diagnoses*")), pxwidth=1000,imageheight="2.5in")` ### Targeted text using the `ttext` parameter In the example above, suppose that new diagnoses are only excluded from Mild cases in `Group` B. But the `text` parameter adds text to *all* Mild nodes. Thus, in situations like this, the `text` parameter is not sufficient. Instead, you can use the `ttext` parameter to target exactly which nodes should have the specified text. The `ttext` parameter requires that you specify the full path from the root of the tree to the node in question, along with the text in question. The `ttext` parameter is specified as a list so that multiple targeted text strings can be specified at once. For example: ```{r,eval=FALSE} vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, ttext=list( c(Group="B",Severity="Mild",text="\n*Excluding\nnew diagnoses*"), c(Group="A",text="\nSweden"), c(Group="B",text="\nNorway"))) ``` `r spaces(10)` `r vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, ttext=list(c(Group="B",Severity="Mild",text="\n*Excluding\nnew diagnoses*"), c(Group="A",text="\nSweden"),c(Group="B",text="\nNorway")), pxwidth=1000,imageheight="2.5in")` ## Specification of variables {#VariableSpecification} *This section shows how to control how variables appear in a variable tree.* Sometimes it is desirable to modify a variable for use in a variable tree. For example, suppose you wish to determine how many values of `Score` are missing. This is easy to do with dplyr: ```{r,eval=FALSE} library(dplyr) FakeData %>% mutate(missingScore=is.na(Score)) %>% vtree("missingScore") ``` But vtree also offers built-in tools for variable specification. Although limited, they can be very convenient. ### prefix `is.na:` If an individual variable name is preceded by `is.na:`, that variable will be replaced by a missing value indicator in the variable tree. (This differs from the [`check.is.na` parameter](#missingValues), which is used to replace *all* of the specified variables with missing value indicators.) For example: ```{r,eval=FALSE} vtree(FakeData,"is.na:Score") ``` `r spaces(55)` `r vtree(FakeData,"is.na:Score", pxwidth=500,imageheight="1.5in")` ### wildcard `#` Specifying `Ind#` matches all variable names that start with `Ind` and end with one or more numeric digits, namely `Ind1`, `Ind2`, `Ind3`, and `Ind4`. This wildcard can also be used within a variable name. For example, `visit#duration` would match `visit1duration`, `visit2duration`, etc. ### wildcard `*` Specifying `Ind*` matches all variable names that start with `Ind` and end with any other characters (or no other characters). In `FakeData` this matches `Ind1`, `Ind2`, `Ind3`, and `Ind4` (just like `Ind#` does). But if `FakeData` contained variables named `Ind` and `Index`, they would also be matched by `Ind*`. As with the `#` wildcard, the `*` wildcard can be used within a variable name. ### prefix `i:` "Intersections" between multiple variables can be generated using the prefix `i:`. For example, `i:Ind*` generates a variable representing the observed combinations of values of `Ind1`, `Ind2`, `Ind3`, and `Ind4`. (If at least one of the variables is missing, the combination will be missing.) ### prefix `r:` (for REDCap) Vtree includes special support for [REDCap](https://www.project-redcap.org/) data sets. The prefix `r:` is used to indicate REDCap checkbox variables, and can be combined with other prefixes. This is described in the section on [REDCap checkboxes](#REDCapCheckboxes) later in this vignette. ### prefix `any:` Sometimes a group of variables contain responses to a list of checkbox options (often with instructions to "check all that apply"). For example, suppose you have a data frame of shops, including whether they are open on Saturday (`openSaturday`) or Sunday (`openSunday`). Suppose no other variables start with `open`. Then `open*` will match both `openSaturday` and `openSunday`. In general for a group of checkbox variables, it is often useful to know if *any* of the options were selected (i.e. checked). In the case above, we might want to know which shops are open at all on the weekend (either Saturday or Sunday). A specification like `any:open*` is used to generate a variable that is * `TRUE` if *any* of the matching variables has a "checked" value * `FALSE` if none of the matching variables have "checked" values. The parameters `checked` and `unchecked` specify which values are considered checked or unchecked respectively, and have the following defaults: |parameter | default value |:-------------|:----------------------------------------------------------- |`checked` | `c("1","TRUE","Yes","yes")` |`unchecked` | `c("0","FALSE","No","no")` Values not listed in `checked` or `unchecked` are treated as missing values. An alternative prefix, `anyx:`, is used to specify that missing values will be removed when performing the calculation. This matches the behavior of the R function `any` when `na.rm=TRUE` is specified. ### prefix `none:` The logical complement (negation) of the `any:` prefix. An alternative prefix, `nonex:`, is used to specify that missing values will be removed when performing the calculation. ### prefix `all:` A specification like `all:open*` generates a variable which is TRUE if *all* of the matching variables have a "checked" value. An alternative prefix, `allx:`, is used to specify that missing values will be removed when performing the calculation. This matches the behavior of the R function `all` when `na.rm=TRUE` is specified. ### prefix `notall:` The logical complement (negation) of the `all:` prefix. An alternative prefix, `notallx:`, is used to specify that missing values will be removed when performing the calculation. ### prefix `tri:` {#detectingOutliers} The `tri:` prefix is useful for identifying values of a numeric variable that are *extreme* compared to the other values in a node. **Note:** Unlike other variable specifications, which take effect at the level of the entire data frame, the `tri:` prefix takes effect within each node. The effect of this variable specification is to *trichotomize* the values of a numeric variable, i.e. to divide them into three groups: * "mid": values within plus or minus 1.5&times;IQR of the median, * "high": values more than 1.5&times;IQR above the median, * "low": values more than 1.5&times;IQR below the median. ### specification `variable=value` {#dichotomizing} When a variable takes on a large number of different values, the resulting variable tree will very large. One solution is to prune the tree, for example by keeping just the node corresponding to one value of a particular variable. An alternative is to specify the value of the variable that is of primary interest and `vtree` will dichotomize the variable at that value. For example if `Severity=Mild` is specified, the `Severity` variable will be dichotomized between `Mild` and `Not Mild`. ### specifications `variable<value`, `variable>value` These two specifications are used to dichotomize a *numeric* variable, splitting above and below a specified value. This can be useful for identifying subsets with extreme values. ## Displaying summary statistics in nodes {#summary} *This section shows how to display information about other variables in the nodes.* It is often useful to display information about *other* variables (apart from those that define the tree) in the nodes of a variable tree. This is particularly useful for numeric variables, which usually would not be used to build the tree since they have too many distinct values. The `summary` parameter allows you to show information (for example, a mean) about a specified variable within a subset of the data frame. ### Default summaries Suppose you are interested in summary information for the `Score` variable for all of the observations in the data frame (i.e. in the root node). In that case you don't need to specify any variables for the tree itself: ```{r,eval=FALSE} vtree(FakeData,summary="Score") ``` `r spaces(68)` `r vtree(FakeData,summary="Score", pxwidth=500,imageheight="1.2in")` When the name of a numeric variable (in this case `"Score"`) is specified as the argument of the `summary` parameter, a default set of summary statistics (as shown above) appears: the variable name, the number of missing values, the mean and standard deviation, the median and interquartile range (IQR), and the range. (Note, however, that if there are three or fewer observations, instead of showing the above summary statistics, the observations are simply listed.) Suppose we're building a variable tree based on `Severity`. We can display these summaries for `Score` in each node: ```{r,eval=FALSE} vtree(FakeData,"Severity",summary="Score",horiz=FALSE) ``` `r spaces(68)` `r vtree(FakeData,"Severity",summary="Score",horiz=FALSE, pxwidth=1000,imageheight="2.7in")` Sometimes it is helpful to extract summary information as text. For example, we might wish to access the summary information contained in the Mild node. This is explained [later on](#extracting), but here's a brief example: ```{r attributes} vSeverity <- vtree(FakeData,"Severity",summary="Score",horiz=FALSE) info <- attributes(vSeverity)$info cat(info$Severity$Mild$.text) ``` There are also default summaries for factor variables and for indicator variables. For example, `Category` is a factor variable: ```{r,eval=FALSE} vtree(FakeData,summary="Category") ``` `r spaces(68)` `r vtree(FakeData,summary="Category", pxwidth=300,imageheight="1in")` Indicator variables have two levels such as 0 / 1, or `TRUE` / `FALSE`. For example, `Event` is an indicator variable ```{r,eval=FALSE} vtree(FakeData,summary="Event") ``` `r spaces(68)` `r vtree(FakeData,summary="Event", pxwidth=300,imageheight="0.5in")` ### Specification of variables in the summary argument Variables in the `summary` argument can also be specified in a way that is similar to the [specification of variables](#VariableSpecification) for structuring a variable tree. For example, if we wish to know the proportion of patients in each node whose `Category` is single, we specify `Category=single` in the `summary` argument: ```{r,eval=FALSE} vtree(FakeData,"Severity",summary="Category=single",horiz=FALSE) ``` `r vtree(FakeData,"Severity",summary="Category=single",horiz=FALSE, pxwidth=1000,imageheight="1.4in")` Summaries can be obtained for a collection of variables using pattern-matching, for example: ```{r summary-pattern,eval=FALSE} vtree(FakeData,"Severity",summary="Ind*",sameline=TRUE,horiz=FALSE,just="l") ``` `r vtree(FakeData,"Severity",summary="Ind*",sameline=TRUE,horiz=FALSE,just="l", pxwidth=1000,imageheight="2.6in",margin=0.25)` Incidentally, note that `just="l"` specifies that all text should be left-justified, which conveniently lines up all of the rows of the summary. The `summary` argument can also use the prefixes `i:`, `any:`, `none:`, `all:`, `notall:` (as well as `anyx:`, `nonex:`, `allx:`, and `notallx:`) and wildcards `#` and `*` (similar to [variable specifications](#VariableSpecification)). Additionally, specifications for [REDCap checkboxes](#REDCapCheckboxes) can be used. ### Control codes: `%noroot%`, `%leafonly%`, `%var=`*v*`%`, and `%node=`*n*`%` By default, summary information is shown in all nodes. However, it may also be convenient to only show it in specific nodes. To control this, special codes that begin and end with `%` can be specified. The following control codes are available: |code | summary information restricted to: |:----------------|---------------------------------------- |`%noroot%` | all nodes *except* the root |`%leafonly%` | leaf nodes |`%var=`*v*`%` | nodes of variable *v* |`%node=`*n*`%` | nodes named *n* The control codes can be specified by adding them to the end of the summary string, separated with a space. For example, to only show summary information for nodes of the `Category` variable with the value `single`: ```{r, eval=FALSE} vtree(FakeData,"Severity Category",summary="Score<10 %var=Category%%node=single%", sameline=TRUE, showlegend=TRUE, showlegendsum=TRUE) ``` `r spaces(35)` `r vtree(FakeData,"Severity Category",summary="Score<10 %var=Category%%node=single%", sameline=TRUE, showlegend=TRUE, showlegendsum=TRUE, pxwidth=1500,imageheight="4.5in")` Here `showlegend=TRUE` was specified, and additionally `showlegendsum=TRUE`, which indicates that summaries should also be shown in legend nodes. ### Customized summaries The `summary` parameter also allows for customized summaries. For example, we might wish to display only the mean `Score` in each node of the tree. The `%mean%` code is used to represent the mean of the specified variable (preceded here by a line break, `\n`). ```{r,eval=FALSE} vtree(FakeData,"Severity",summary="Score \nmean score\n%mean%",sameline=TRUE,horiz=FALSE) ``` `r spaces(30)` `r vtree(FakeData,"Severity",summary="Score \nmean score\n%mean%", sameline=TRUE,horiz=FALSE, pxwidth=800,imageheight="1.5in")` In addition to the `%mean%` code, numerous other summary codes are supported, as listed in the table below. When such a code is present, the default summary is not shown. Instead, any text that is provided---in this case `\nmean score\n`---is shown, together with the requested summary information. If there are any missing values in a node, the number of missing values is shown using the abbreviation `mv`. To see summaries without any decimals, specify `cdigits=0`. summary code | result :---------------|:------------------------------------------------------------------- `%mean%` | mean\ (variant: `%meanx%` does not report missing values&ast;) `%SD%` | standard deviation\ (variant: `%SDx%` does not report missing values&ast;) `%sum%` | sum\ (variant: `%sumx%` does not report missing values&ast;) `%min%` | minimum\ (variant: `%minx%` does not report missing values&ast;) `%max%` | maximum\ (variant: `%maxx%` does not report missing values&ast;) `%range%` | range\ (variant: `%rangex%` does not report missing values&ast;) `%median%` | median, i.e. p50\ (variant: `%medianx%` does not report missing values&ast;) `%IQR%` | IQR, i.e. p25, p75\ (variant: `%IQRx%` does not report missing values&ast;) `%freqpct%` | frequency and percentage of values of a variable\ (variant: `%freqpct_%` shows each value on a separate line) `%freq%` | frequency of values of a variable\ (variant: `%freq_%` shows each value on a separate line) `%pY%` | *Y*th percentile (e.g. `p50` means the 50th percentile) `%npct%` | frequency and percentage of a logical variable. By default "valid percentages" are used. Any missing values are also reported. `%pct%` | same as `%npct%` but percentage only (with no parentheses). `%list%` | list of individual values, separated by commas\ (variant: `%list_%` shows each value on a separate line) `%mv%` | the number of missing values `%nonmv%` | the number of non-missing values `%v%` | the name of the variable &ast;*Caution is recommended when suppressing missing values.* The `summary` argument can include any number of these codes, mixed with text and formatting codes. ### The `%trunc%` code It is sometimes convenient to see individual values of a variable in each node. A good example is ID numbers. To do this, use the `%list%` code. When a value occurs more than once in the subset, it will be followed by a count of the number of repetitions in parentheses. When there are many individual values, it is often convenient to truncate the output. If you specify `%trunc=`*N*`%`, summary information will be truncated after *N* characters, and followed by "...". ### R expressions in the summary argument Rather than starting the `summary` argument with a variable name, an R expression involving variables in the data frame can be given, as long as it does not contain any spaces. ```{r,eval=FALSE} vtree(FakeData,"Severity Category", summary="(Post-Pre)/Pre \nmean = %mean%",sameline=TRUE,horiz=FALSE,cdigits=1) ``` `r vtree(FakeData,"Severity Category", summary="(Post-Pre)/Pre \nmean = %mean%",sameline=TRUE,horiz=FALSE,cdigits=1, pxwidth=1000,imageheight="2in",margin=0.25)` Expressions involving functions can also be used; for example `sqrt(abs(Post/Pre))`. ### More than one variable Sometimes it is useful to display summary information for more than one variable. To do this, specify `summary` as a *vector* of character strings. For example: ```{r,eval=FALSE} vtree(FakeData,"Severity",horiz=FALSE,showvarnames=FALSE,splitwidth=Inf,sameline=TRUE, summary=c("Score \nScore: mean (SD) %meanx% (%SD%)","Pre \nPre: range %range%")) ``` `r vtree(FakeData,"Severity",horiz=FALSE,showvarnames=FALSE,splitwidth=Inf,sameline=TRUE, summary=c( "Score \nScore: mean (SD) %meanx% (%SD%)", "Pre \nPre: range %range%"), pxwidth=1400,imageheight="1.4in")` ### Targeted summaries Sometimes you only want to show a summary in a particular node. Targeted summaries are specified with the `tsummary` parameter as a list of character-string vectors. The initial elements of each character string vector point to a specific node. The final element of each character string vector is a summary string, with the same structure as \code{summary}. ```{r,eval=FALSE} vtree(FakeData,"Age Sex",tsummary=list(list(Age="5",Sex="M","id \n%list%")),horiz=FALSE) ``` `r vtree(FakeData,"Age Sex",tsummary=list(list(Age="5",Sex="M","id \n%list%")),horiz=FALSE, pxwidth=1400,imageheight="2.3in")` ## Pattern trees and pattern tables {#patterns} *This section shows how to display all the combinations of values in a set of variables.* Each node in a variable tree provides the frequency of a particular combination of values of the variables. The leaf nodes represent the observed combinations of values of *all* of the variables. For example, in a variable tree for `Severity` and `Sex`, the leaf nodes correspond to Mild F, Mild M, Moderate F, Moderate M, etc. These combinations, or "patterns", can be treated as an additional variable. And if this new pattern variable is used as the first variable in a tree, then the branches of the tree will be simplified: each branch will represent a unique pattern, with no sub-branches. A "pattern tree" can be easily produced by specifying `pattern=TRUE`. For example: ```{r, eval=FALSE} vtree(FakeData,"Severity Sex") vtree(FakeData,"Severity Sex",pattern=TRUE) ``` `r spaces(10)` `r vtree(FakeData,"Severity Sex", pxwidth=500,imageheight="4in")` `r spaces(15)` `r vtree(FakeData,"Severity Sex",pattern=TRUE, pxwidth=600,imageheight="4in")` Pattern trees are simpler to read than ordinary variable trees, but they involve a considerable loss of information, since they only represent the *n*th-degree subsets (where *n* is the number of variables). Note that by default, when `pattern=TRUE` is specified, the root node is not shown (in order to simplify the display). A disadvantage of this is that the total sample size is not shown. You can override this behavior by specifying `showroot=TRUE`. A pattern tree has two other special characteristics. First, note that after the first layer (representing `pattern`), counts and percentages are not shown, since they are not informative: by definition, all nodes within a branch have the same count. Second, note that in place of arrows, undirected line segments are shown. This is because, unlike in a regular variable tree, the order of variables is irrelevant in a pattern tree. Sometimes, however, the variables do have a natural ordering, as in the case of longitudinal variables. To show arrows, specify `seq=TRUE` instead of `pattern=TRUE`, and a "sequence" (i.e. an ordered pattern) will be shown. Summaries can be shown in pattern trees (using the `summary` parameter), but they only appear in the pattern node (or the sequence node if `seq=TRUE`). ### Pattern tables A pattern tree has the same structure as a table. Indeed, it may be more convenient to produce a table rather than a pattern tree. A data frame containing the information from the pattern tree can be exported by specifying `ptable=TRUE`: ```{r} vtree(FakeData,"Severity Sex",ptable=TRUE) ``` The pattern table includes a column for the counts from the pattern nodes, and a column for percentages. Compared to a variable tree, this table is much more compact, and may be more suitable for use in a manuscript. ### Indicator variables Pattern trees can be very useful for *indicator variables*, i.e. variables that take values like 0/1, no/yes, FALSE/TRUE, etc. For convenience in this section, we'll refer to 0 (or no, FALSE, etc.) as a *negative* and 1 (or yes, TRUE, etc.) as an *affirmative*. The variables `Ind1` through `Ind4` in `FakeData` are 0/1 indicator variables. If these variables are interpreted as representing set membership (0 = non-member, 1 = member), then a pattern tree is an alternative representation of a Venn diagram. If you specify `Venn=TRUE`, the nodes (except for the pattern nodes) will be blank, with only their shade indicating their value (dark = 1, light = 0, white = missing). ```{r, eval=FALSE} vtree(FakeData,"Ind1 Ind2 Ind3 Ind4",Venn=TRUE,pattern=TRUE) ``` `r spaces(40)` `r vtree(FakeData,"Ind1 Ind2 Ind3 Ind4",Venn=TRUE,pattern=TRUE, pxwidth=500,imageheight="5in")` Big pattern trees can be overwhelming, so it may be useful to prune patterns that occur fewer than, say, 3 times, by specifying `prunesmaller=3`. A pattern tree for indicator variables provides all the information that a Venn diagram represents, but unlike a Venn diagram, missing values are also represented. This can also be shown as a pattern table. For example: ```{r} vtree(FakeData,"Ind1 Ind2",ptable=TRUE) ``` #### The `VennTable` function For indicator variables, there is an extra function, `VennTable`, which converts the pattern table to a matrix of character strings and adds some additional totals. ```{r} VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE)) ``` By default in R, when a matrix of character strings is printed, quotation marks are displayed around each element. Unfortunately the result is unattractive. Instead it's helpful to call the `print` function and specify `quote=FALSE`: ```{r} print(VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE)),quote=FALSE) ``` Without all those quotation marks, it's easier to see what `VennTable` adds: * the total sample size (`r nrow(FakeData)`) and percentage (100), and * the total number (N) of affirmatives for each variable, together with a percentage. The `VennTable` function can also be used in an R Markdown document. Specifying `markdown=TRUE` generates a pandoc markdown pipetable, with several formatting tweaks: * the rows and columns of the table are transposed * affirmatives are represented by checkmarks * negatives are represented by spaces * missing values are represented by dashes (which can be changed with the `NAcode` parameter). To display the table in R Markdown, use this inline call: ```{r, eval=FALSE} `r VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE),markdown=TRUE)` ``` `r VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE),markdown=TRUE)` `VennTable` has some additional parameters. The `checked` parameter is used to specify values that should be interpreted as affirmative. By default, it is set to `c("1","TRUE","Yes","yes","N/A")`. Similarly, the `unchecked` parameter is used to specify values that should be interpreted as negative, with default `c("0","FALSE","No","no","not N/A")`. #### Using the `summary` parameter in pattern tables The `summary` parameter can also be used in pattern tables. If a single summary is requested, it appears in the `summary_1` variable in the data frame. Additional summaries appear as `summary_2`, `summary_3`, etc. ```{r} vtree(FakeData,"Severity Sex",summary=c("Score %mean%","Pre %mean%"),ptable=TRUE) ``` ### Checking for missing values with the `check.is.na` parameter {#missingValues} If `check.is.na=TRUE` is specified, each variable is replaced by an indicator of whether or not it is missing, and `pattern=TRUE` is automatically set. As when `Venn=TRUE` is specified, all nodes except for the pattern node are blank, and only their shade indicates missing (dark) or not (light). Whereas the variables used to build a variable tree are normally categorical, in this situation non-categorical variables can be used, because their missingness is represented instead of their actual values. ```{r,eval=FALSE} vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE) ``` `r spaces(40)` `r vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE, pxwidth=600,imageheight="3in")` Specifying `ptable=TRUE` produces this information in a data frame, and calling `VennTable` shows additional information. To display the table in R Markdown, use this inline call: ```{r, eval=FALSE} `r VennTable(vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,ptable=TRUE), markdown=TRUE)` ``` `r VennTable(vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,ptable=TRUE),markdown=TRUE)` The rows `n` and `pct` represent the frequency and percentage of the total number of cases for each pattern of missingness, and the columns `N` and `pct` on the right-hand side represent the frequency and percentage of missingness for each variable. It may be useful to identify the ID numbers for these patterns. Here the results are truncated to 15 characters: ```{r} vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,summary="id %list%%trunc=15%", ptable=TRUE) ``` ## Colors {#colors} *This section explains how colors and color palettes can be used.* By default, `vtree` assigns colors to nodes of each successive variable using color palettes from [RColorBrewer](https://cran.r-project.org/package=RColorBrewer). The sequence of palettes (identified by short names) is as follows: - ------- ------ -- ------- ------ -- ------- ------- ------ ------ 1 Reds &nbsp; 6 YlGn &nbsp; 11 BuPu &nbsp; 16 RdPu 2 Blues &nbsp; 7 PuBu &nbsp; 12 YlOrRd &nbsp; 17 BuGn 3 Greens &nbsp; 8 PuRd &nbsp; 13 RdYlGn &nbsp; 18 OrRd 4 Oranges &nbsp; 9 YlOrBr &nbsp; 14 GnBu &nbsp; 5 Purples &nbsp; 10 PuBuGn &nbsp; 15 YlGnBu &nbsp; - ------- ------ -- ------- ------ -- ------- ------- ------ ------ If you prefer to change the color assignments, you can use the `palette` parameter. For example, by default a variable tree for `Sex` and `Severity` will assign shades of red to nodes of `Sex` and shades of blue to notes of `Severity`. To switch to shades of, say, green and orange instead, use: ```{r, eval=FALSE} vtree(FakeData,"Sex Severity",palette=c(3,4)) ``` Sometimes it may be useful to reverse the order of a gradient. To reverse the order of all gradients, specify `revgradient=TRUE`. The gradient for selected variables can be reversed as in the example below: ```{r, eval=FALSE} vtree(FakeData,"Sex Group Severity",revgradient=c(Sex=TRUE,Severity=TRUE)) ``` Other color-related parameters include: ---------------- --------------------------------------------------------- `sortfill` Specifying `sortfill=TRUE` fills nodes with gradient colors in sorted order according to the node count. `NAfillcolor` By default, missing value nodes are colored white. For a different color (say gray), specify `NAfillcolor="gray"`. To instead use a color from the current palette, specify `NAfillcolor=NULL`. `rootfillcolor` The color of the root node can be changed (say to yellow) by specifying `rootfillcolor="yellow"`. `fillcolor` To set all nodes of the tree (except for missing value nodes and the root node) to be the same color (say palegreen), specify `fillcolor="palegreen"`. `plain` A simple color scheme is produced by specifying `plain=TRUE`. (Additionally, this increases the spaces between nodes.) ---------------- --------------------------------------------------------- ## REDCap checkboxes {#REDCapCheckboxes} *This section details support for checkbox variables from REDCap.* In datasets exported from [REDCap](https://www.project-redcap.org/), checkboxes (i.e. select-all-that-apply boxes) are represented in a special way. For each item in a checklist, a separate variable is created. Suppose survey respondents were asked to select which flavors of ice cream (Chocolate, Vanilla, Strawberry) they like. Within REDCap, the variable name for this list of checkboxes is `IceCream`, but when the dataset is exported, individual variables `IceCream___1` (representing Chocolate), `IceCream___2` (Vanilla), and `IceCream___3` (Strawberry) are created. When the dataset is read into R, the names of the flavors are embedded in the `attributes` of these variables. For illustrative purposes, let's build a dataframe like this using the `build.data.frame` function (for an explanation of this function see the section of this vignette on [generating a data frame by specifying subset sizes](#GeneratingDataFrames) ```{r} dessert <- build.data.frame( c( "group","IceCream___1","IceCream___2","IceCream___3"), list("A", 1, 0, 0, 7), list("A", 1, 0, 1, 2), list("A", 0, 0, 0, 1), list("A", 1, 1, 1, 1), list("B", 1, 0, 1, 1), list("B", 1, 0, 0, 2), list("B", 0, 1, 1, 1), list("B", 0, 0, 0, 1)) attr(dessert$IceCream___1,"label") <- "Ice cream (choice=Chocolate)" attr(dessert$IceCream___2,"label") <- "Ice cream (choice=Vanilla)" attr(dessert$IceCream___3,"label") <- "Ice cream (choice=Strawberry)" ``` ### prefix `r:` The prefix `r:` identifies a REDCap checklist variable, and extracts a label from the variable attribute. For example, the following call automatically displays "Chocolate": ```{r eval=FALSE} vtree(dessert,"r:IceCream___1") ``` ### suffix `@` The suffix `@` matches REDCap checklist variables based on the naming scheme used by REDCap for checklist variables. For example, the following call automatically displays Chocolate, Vanilla, and Strawberry: ```{r eval=FALSE} vtree(dessert,"r:IceCream@") ``` ### variable prefixes `rany:`, `rnone:`, `rall:`, and `rnotall:` The variable prefixes `any:`, `none:`, `all:`, and `notall:` can be combined with the `r:` prefix to form `rany:`, `rnone:`, `rall:`, and `rnotall:`. For example, to determine whether anyone did not like *any* of the flavors (Chocolate, Vanilla, or Strawberry): ```{r eval=FALSE} vtree(dessert,"rnone:IceCream@") ``` ### variable prefix `ri:` "Intersections" of REDCap variables may be obtained by combining the `r:` prefix with the `i:` prefix: ```{r eval=FALSE} vtree(dessert,"ri:IceCream@") ``` ### Deprecated: variable prefixes `stem:` and `rc:` To examine the pattern of ice-cream flavor choices, the following can be used: ```{r eval=FALSE} vtree(dessert,"IceCream___1 IceCream___2 IceCream___3",pattern=TRUE) ``` One problem is that this doesn't assign the appropriate labels to `IceCream___1` (Chocolate), `IceCream___2` (Vanilla), and `IceCream___3` (Strawberry). Instead, try the following more compact call, which also assigns labels automatically. ```{r eval=FALSE} vtree(dessert,"stem:IceCream",pattern=TRUE) ``` The `summary` parameter also supports a `stem:` prefix: ```{r, eval=FALSE} vtree(dessert,summary="stem:IceCream",splitwidth=Inf,just="l") ``` `r spaces(63)` `r vtree(dessert,summary="stem:IceCream",splitwidth=Inf,just="l", pxwidth=1000,imageheight="1in")` If you wish to only examine specific REDCap checkbox items, the `rc:` prefix can be used. For example to examine results for just Chocolate and Strawberry: ```{r, eval=FALSE} vtree(dessert,"rc:IceCream___1 rc:IceCream___3",pattern=TRUE) ``` ## The DOT script generated by `vtree` *This section shows how to obtain the DOT script that displays a variable tree.* Specifying `getscript=TRUE` lets you capture the DOT script representing a variable tree. (DOT is a graph description language used by Graphviz, which is used by DiagrammeR, which is used by vtree!). Here is an example: ```{r, comment=""} dotscript <- vtree(FakeData,"Severity",getscript=TRUE) cat(dotscript) ``` If you wish to directly edit this code, it can can be pasted into an online Graphviz editor, for example: https://dreampuf.github.io/GraphvizOnline/ http://magjac.com/graphviz-visual-editor/ ## Extracting a list of information about a variable tree {#extracting} *This section explains how to obtain all of the counts and percentages of a variable tree.* Sometimes it is useful to extract counts, percentages, and summary information from a variable tree. The object returned by `vtree` has an attribute `info` containing structured information about the counts and percentages in each node. Here is an example: ```{r,echo=TRUE,message=FALSE,eval=FALSE} v <- vtree(FakeData,"Group Viral",horiz=FALSE) v ``` `r spaces(30)` ```{r,echo=FALSE,message=FALSE} v <- vtree(FakeData,"Group Viral",pxwidth=800,imageheight="2in",horiz=FALSE) v ``` ```{r,echo=TRUE,message=FALSE} attributes(v)$info ``` The list contains the counts (`.n`), percentages (`.pct`), and summary text (`.text`) that appear in the tree. # Ways to call vtree `vtree` behaves differently depending on the context in which it is called. ## Calling vtree interactively * If `vtree` is called interactively in RStudio, it displays the variable tree in the Viewer window. * If `vtree` is called interactively from the RGui console (i.e. from R outside of RStudio), it displays the variable tree in a browser window. ## Calling vtree from knitr and R Markdown {#embeddingInKnitrRmarkdown} When `vtree` is called from knitr, it generates * A PNG file if the output format is Markdown * A PDF file if the output format is LaTeX. Here's how it does that. `vtree` uses the `DiagrammeR` package, which automatically generates an `htmlwidget` object for display in HTML, using the [htmlwidgets](https://www.htmlwidgets.org/) framework. Then `vtree` converts the `htmlwidget` object into an SVG image, and finally into a PNG or PDF file. ### Generating PNG files PNG files are useful because they allow you to display variable trees in Microsoft Word documents, and also because HTML files that use htmlwidgets can get large, and if they contain several widgets they can be slow to load. If `vtree` is called while an R Markdown file is being knitted, it generates a PNG file and automatically embeds it into the knitted document. The resolution of the PNG file in pixels is determined by parameters `pxwidth` and `pxheight`. If neither is specified, `pxwidth` is automatically set to 2000, which provides good resolution for a printed page. The height of the image in the R Markdown output document can be specified using the `imageheight` parameter, for example `imageheight="4in"` for a 4-inch image. There is also an `imagewidth` parameter. If neither is specified, `imageheight` is automatically set to 3 inches. *Note*: You may notice a warning in the R Markdown rendering (in RStudio, the R Markdown pane) like this: ```{r, eval=FALSE,echo=TRUE} <unknown>:1919791: Invalid asm.js: Function definition doesn't match use ``` Although distracting, this message is irrelevant. ### Embedding image files The PNG or PDF file is stored in the folder specified by the `folder` parameter, or if not specified, a temporary folder will be used. Successive PNG files are named `vtree001.png`, `vtree002.png`, and so forth and are stored in the folder. (Similarly PDF files are named `vtree001.pdf`, etc.) During knitting, `vtree` uses the `options` function in base R to store a variable called `vtcount` to count the PNG files, and a variable called `vtfolder` to identify the folder where they will be stored. To call `vtree` in R Markdown, you can use inline code: ```{r, eval=FALSE} `r vtree(FakeData,"Sex Severity")` ``` Or you can use a code chunk: ```` `r ''````{r} vtree(FakeData,"Sex Severity") ``` ```` One advantage of code chunks is that they can also be run interactively (for example within RStudio, by clicking on the green arrow at the top right of a code chunk). ### Generating an image file but not displaying it Specifying `imageFileOnly=TRUE` instructs vtree to generate an image file but not display it. ### Generating an htmlwidget in an HTML document When knitting to an HTML document, htmlwidgets can be used rather than embedding a PNG file. To use htmlwidgets instead of a PNG file simply specify `pngknit=FALSE`. ## `svtree`: Using vtree in Shiny {#svtree} Thanks to Shiny and the svg-pan-zoom JavaScript library, interactive panning and zooming of a variable tree is possible with the `svtree` function. The syntax of `svtree` is the same as that of `vtree`, but instead of generating a static variable tree, it launches a Shiny app. The mousewheel allows you to zoom in or out. The variable tree can also be dragged to a different position. Thanks to the panning and zooming functionality in `svtree`, it is possible to examine larger variable trees than with `vtree`. In large variable trees it is often useful to show the variable name in each node, since the variable labels (which are shown at the bottom or left-hand margin) may not be visible after zooming. To show the variable name in each node, specify `showvarinnode=TRUE`. # Generating a data frame by specifying subset sizes {#GeneratingDataFrames} `vtree` is designed to generate a variable tree based on a data frame. However, sometimes the sizes of subsets are known but no data frame is available. The `build.data.frame` function allows you to build a data frame by specifying the size of subsets. Here's an example involving pets: ```{r} build.data.frame( c("pet","breed","size"), list("dog","golden retriever","large",5), list("cat","tabby","small",2)) ``` In this case there are five large golden retrievers and 2 small tabby cats. Although a data frame like this could easily be created without using `build.data.frame`, it’s a different situation when the counts are large. For example: ```{r, eval=FALSE} build.data.frame( c("pet","breed","size"), list("dog","golden retriever","large",5), list("cat","tabby","small",2), list("dog","Dalmation","various",101), list("cat","Abyssinian","small",5), list("cat","Abyssinian","large",22), list("cat","tabby","large",86)) ``` # Examples ## Rudimentary CONSORT diagrams Consider the following fictitious data about a randomized controlled trial (RCT): ```{r} FakeRCT ``` The CONSORT diagram (http://www.consort-statement.org/) shows the flow of patients through the study, starting with those who meet eligibility criteria, then those who are randomized, etc. It is easy to produce a rudimentary version of a CONSORT diagram in `vtree`. The key step is to prune branches for those who are *not* eligible, *not* randomized, etc. This can be done using the `keep` parameter: ```{r,eval=FALSE} vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility") ``` `r spaces(55)` `r vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", width=230,height=500,pxwidth=300,imageheight="5in")` Note that this does not include all of the additional information for a full CONSORT diagram (exclusion reasons and counts, as well as numbers of patients who received their allocated interventions, who discontinued intervention, and who were excluded from analysis). It does, however, provide the main flow information. Additional information can be obtained by viewing the nodes for patients in the pruned branches (but not their descendants). The `follow` parameter makes that easy: ```{r,eval=FALSE} vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility") ``` `r spaces(30)` `r vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", width=400,height=500,pxwidth=500,imageheight="5in")` Finally, it may be useful to see the ID numbers in each node. This can be done using the `summary` parameter with the `%list%` code. Since IDs are less useful in the root note, the `%noroot%` code is also specified here: ```{r, eval=FALSE} vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", summary="id \nid: %list% %noroot%") ``` `r spaces(30)` `r vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", summary="id \nid: %list% %noroot%", width=500,height=600,pxwidth=600,imageheight="5in")` ## Examples using R datasets {#RdatasetExamples} The `datasets` package is loaded in R by default. In the following section, `vtree` is applied to several of these data sets for illustrative purposes. Note that the variable trees generated by the commands below are not shown. The reader can try these commands to see what the variable trees look like, and experiment with many other possibilities. ### Esophageal cancer The `esoph` data set (data from a case-control study of esophageal cancer in Ille-et-Vilaine, France), has 88 different combinations of age group, alcohol consumption, and tobacco consumption. Let's examine the total number of cases and the total number of controls among patients aged 75 and older compared to the rest of the patients: ```{r, eval=FALSE} # Relabel agegp 75+ to 75plus because vtree tries to parse the + ESOPH <- esoph levels(ESOPH$agegp)[levels(ESOPH$agegp)=="75+"] <- "75plus" vtree(ESOPH,"agegp=75plus",sameline=TRUE,cdigits=0, summary=c("ncases \ncases=%sum%%leafonly%","ncontrols controls=%sum%%leafonly%")) ``` ### Hair and eye color The `HairEyeColor` data set is an array representing a contingency table (also called a crosstab or crosstabulation). Before `vtree` can be applied to this data set, it is necessary to convert the table of crosstabulated frequencies to a data frame of cases. For convenience, the `vtree` package includes a helper function to do this, called `crosstabToCases`. It is adapted from a function listed on the [Cookbook for R website](http://www.cookbook-r.com/Manipulating_data/Converting_between_data_frames_and_contingency_tables/#countstocases-function) ```{r, eval=FALSE} hec <- crosstabToCases(HairEyeColor) ``` There are a lot of combinations but let's say we are especially interested in green eyes (as compared to non-green eyes). We can use the variable specification `Eye=Green` to do this: ```{r, eval=FALSE} vtree(hec,"Hair Eye=Green Sex",sameline=TRUE) ``` ### Titanic The `Titanic` dataset is a 4-dimensional array of counts. First, let's convert it to a dataframe of individuals: ```{r, eval=FALSE} titanic <- crosstabToCases(Titanic) ``` We'll specify `sameline=TRUE` so that the variable tree is a bit more compact: ```{r, eval=FALSE} vtree(titanic,"Class Sex Age",summary="Survived=Yes \n%pct% survived",sameline=TRUE) ``` ### mtcars The `mtcars` data set was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). The rownames of the data set contain the names of the cars. Let's move that information into a column. To do that, we'll make a slightly altered version of the data frame which we'll call `mt`: ```{r, eval=FALSE} mt <- mtcars mt$name <- rownames(mt) rownames(mt) <- NULL ``` Now let's look at the mean and standard deviation of horsepower (HP) by number of carburetors, nested within number of gears, and in turn nested within number of cylinders: ```{r, eval=FALSE} vtree(mt,"cyl gear carb",summary="hp \nmean (SD) HP %mean% (%SD%)") ``` The above shows the mean and SD of horsepower by (1) number of cylinders; (2) number of gears (within number of cylinders); and (3) number of carburetors (within number of gears nested within number of cylinders). That's a lot of information. Suppose instead that we are only interested in number 3 above, i.e. all combinations of number of cylinders, number of gears, and number of carburetors. In that case, we can specify `ptable=TRUE`, To make the table a little easier to read, set the number of digits for the mean and SD to be zero, and relabel the variables. ```{r, eval=FALSE} vtree(mt,"cyl gear carb",summary="hp mean (SD) HP %mean% (%SD%)", cdigits=0,labelvar=c(cyl="# cylinders",gear="# gears",carb="# carburetors"), ptable=TRUE) ``` We might also like to list the names of cars by number of carburetors nested within number of gears: ```{r, eval=FALSE} vtree(mt,"gear carb",summary="name \n%list%%noroot%",splitwidth=50,sameline=TRUE, labelvar=c(gear="# gears",carb="# carburetors")) ``` ### UCBAdmissions The `UCBAdmissions` data is consists of aggregate data on applicants to graduate school at Berkeley for the six largest departments in 1973 classified by admission and sex. According to the data set Details, "This data set is frequently used for illustrating Simpson's paradox, see Bickel et al. (1975). At issue is whether the data show evidence of sex bias in admission practices. There were 2691 male applicants, of whom 1198 (44.5%) were admitted, compared with 1835 female applicants of whom 557 (30.4%) were admitted." Furthermore, "the apparent association between admission and sex stems from differences in the tendency of males and females to apply to the individual departments (females used to apply more to departments with higher rejection rates)." First, we'll convert the crosstab data to a data frame of cases, `ucb`: ```{r, eval=FALSE} ucb <- crosstabToCases(UCBAdmissions) ``` Next, let's look at admission rates by Gender, nested within department: ```{r, eval=FALSE} vtree(ucb,"Dept Gender",summary="Admit=Admitted \n%pct% admitted",sameline=TRUE) ``` ### ChickWeight The `ChickWeight` data set is from an experiment on the effect of diet on early growth of chicks. Let's look at the mean weight of chicks at birth (0 days of age) and 4 days of age, nested within type of diet. A simple variable tree can be produced like this: ```{r, eval=FALSE} vtree(ChickWeight,"Diet Time", keep=list(Time=c("0","4")),summary="weight \nmean weight %mean%g") ``` To make the display a little easier to read, relabel the nodes and the `Time` variable: ```{r, eval=FALSE} vtree(ChickWeight,"Diet Time",keep=list(Time=c("0","4")), labelnode=list( Diet=c("Diet 1"="1","Diet 2"="2","Diet 3"="3","Diet 4"="4"), Time=c("0 days"="0","4 days"="4")), labelvar=c(Time="Days since birth"),summary="weight \nmean weight %mean%g") ``` ### InsectSprays The `InsectSprays` data set contains counts of insects in agricultural experimental units treated with different insecticides. Let's look at those counts by insecticide. ```{r, eval=FALSE} vtree(InsectSprays,"spray",splitwidth=80,sameline=TRUE, summary="count \ncounts: %list%%noroot%",cdigits=0) ``` ### ToothGrowth The `ToothGrowth` data set contains the length of odontoblasts (cells responsible for tooth growth) in 60 guinea pigs. Each animal received one of three dose levels of vitamin C (0.5, 1, and 2 mg/day) by one of two delivery methods, orange juice or ascorbic acid (a form of vitamin C and coded as VC). Let's examine the percentage with length > 20 by dose nested within delivery method: ```{r, eval=FALSE} vtree(ToothGrowth,"supp dose",summary="len>20 \n%pct% length > 20") ``` To make the display a little easier to read, relabel the nodes and the `Time` variable: ```{r, eval=FALSE} vtree(ToothGrowth,"supp dose",summary="len>20 \n%pct% length > 20", labelvar=c("supp"="Supplement type","dose"="Dose (mg/day)"), labelnode=list(supp=c("Vitamin C"="VC","Orange Juice"="OJ"))) ```
/scratch/gouwar.j/cran-all/cranData/vtree/inst/doc/vtree.Rmd
library(shiny) library(vtree) ## ui ################## ui <- fluidPage( use_svgzoom(), tags$head(tags$style(HTML("body {background-color: #9c9ca096;}"))), helpText(div(style="font-weight: 800; font-size: large; color: black;", HTML("Zooming and Panning is possible with mouse-drag ", "and mouse-wheel <br>or with shortcuts; +,- and arrow-keys ", "and CTRL+Backspace to resize+fit+center the svg.."))), vtreeOutput("vtree", width = "100%", height = "500px") ) ## server ################## server <- function(input, output, session) { output$vtree <- renderVtree({ vtree(FakeData,"Severity Sex", horiz = F, labelnode=list(Sex=(c("Male"="M","Female"="F"))), pngknit=FALSE) }) } shinyApp(ui, server)
/scratch/gouwar.j/cran-all/cranData/vtree/inst/examples/shiny_app.R
--- title: "Introduction to vtree" subtitle: "*Exploring subsets of data using variable trees*" author: '`r paste0("Nick Barrowman, ",strftime(Sys.time(),format="%d-%b-%Y"),", Version ",packageVersion("vtree"))`' output: rmarkdown::html_vignette: css: vtreeVignette.css toc: true toc_depth: '2' vignette: > %\VignetteIndexEntry{Introduction to vtree} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo=FALSE} suppressMessages(library(ggplot2)) library(vtree) #source("../source.R") options(width=90) options(rmarkdown.html_vignette.check_title = FALSE) ``` ```{r, echo=FALSE} spaces <- function (n) { paste(rep("&nbsp;", n), collapse = "") } ``` # Introduction vtree is a flexible tool for calculating and displaying *variable trees* &mdash; diagrams that show information about nested subsets of a data frame. vtree can be used to: 1. explore a data set interactively 2. produce customized figures for reports and publications. Note, however, that vtree is *not* designed to build or display decision trees. Given a data frame and simple specifications, vtree will produce a variable tree and automatically label it with counts, percentages, and other summaries. The sections below introduce variable trees and provide an overview of the features of vtree. Or you can [skip ahead and start using the `vtree` function](#vtreeFunction). ## Two examples *Subsets* play an important role in almost any data analysis. Imagine a data set of countries that includes variables named `population`, `continent`, and `landlocked`. Suppose we wish to examine subsets of the data set based on the `continent` variable. Within each of these subsets, we could examine *nested* subsets based on the `population` variable, for example, countries with populations under 30 million and over 30 million. We might continue to a third nesting based on the `landlocked` variable. Nested subsets are at the heart of questions like the following: *Among African countries with a population over 30 million, what percentage are landlocked?* The variable tree below provides the answer: ```{r, echo=FALSE} df <- build.data.frame( c("continent","population","landlocked"), list("Africa","Over 30 million","landlocked",2), list("Africa","Over 30 million","not landlocked",12), list("Africa","Under 30 million","landlocked",14), list("Africa","Under 30 million","not landlocked",26)) ``` `r spaces(30)` `r vtree(df,"continent population landlocked",showroot=FALSE,pxwidth=800, imageheight="3in")` By default, vtree uses the colorful display above (to help distinguish variables and values), but if you prefer a more sedate version, you can specify a single fill color (or simply white): `r spaces(30)` `r vtree(df,"continent population landlocked",showroot=FALSE,fillcolor="aliceblue", pxwidth=800,imageheight="3in")` Even in simple situations like this, it can be a chore to keep track of nested subsets and calculate the corresponding percentages. The denominator used to calculate percentages may also depend on whether the variables have any missing values, as discussed later. Finally, as the number of variables increases, the magnitude of the task balloons, because the number of nested subsets grows exponentially. vtree provides a general solution to the problem of calculating nested subsets and displaying information about them. Nested subsets arise in all kinds of situations. Consider, for example, flow diagrams for clinical studies, such as the following [CONSORT](http://www.consort-statement.org)-style diagram, produced by vtree. `r spaces(50)` `r vtree(FakeRCT,"eligible randomized group followup",plain=TRUE, keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", pxwidth=500,imageheight="4.5in") ` Both the structure of this variable tree and the numbers shown were automatically determined. When manual calculation and transcription are instead used to populate diagrams like this, mistakes are likely. And although the errors that make it into published articles are often minor, they can sometimes be disastrous. One motivation for developing vtree was to make flow diagrams [reproducible](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3383002/). The ability to reproducibly generate variable trees also means that when a data set is updated, a revised tree can be automatically produced. At the end of this vignette, there is a collection of [examples of variable trees using R datasets](#RdatasetExamples) that you can try. ## Basic features of a variable tree The examples that follow use a data set called `FakeData` which represents `r nrow(FakeData)` fictitious patients. We'll start by using just two variables, although variable trees are especially useful with three or more variables. The variable tree below depicts subsets defined by `Sex` (M or F) nested within subsets defined by disease `Severity` (Mild, Moderate, Severe, or NA). `r vtree(FakeData,"Severity Sex",showlegend=FALSE,horiz=FALSE, pxwidth=1000,imageheight="2.2in")` A variable tree consists of *nodes* connected by arrows. At the top of the diagram above, the *root* node of the tree contains all 46 patients. The rest of the nodes are arranged in successive layers, where each layer corresponds to a specific variable. Note that this highlights one difference between variable trees and some other kinds of trees: each layer of a variable tree corresponds to just one variable. (In a *decision tree*, by contrast, different branches can have different sequences of variable splits.) Continuing with the variable tree above, the nodes immediately below the root represent values of `Severity` and are referred to as the *children* of the root node. In this case, `Severity` was missing (NA) for 6 patients, and there is a node for these patients. Inside each of the nodes, the number of patients is displayed and---except for in the missing value node---the corresponding percentage is also shown. Note that, by default, `vtree` displays "valid" percentages, i.e. the denominator used to calculate the percentage is the total number of *non-missing* values, `r sum(!is.na(FakeData$Severity))`. The final layer of the tree corresponds to values of `Sex`. These nodes represent males and females *within subsets* defined by each value of `Severity`. In each of these nodes the percentage is calculated in terms of the number of patients in its parent node. Like any node, a missing-value node can have children. For example, of the 6 patients for whom `Severity` is missing, 3 are female and 3 are male. By default, `vtree` displays the full missing-value structure of the specified variables. Also by default, `vtree` automatically assigns a color palette to the nodes of each variable. `Severity` has been assigned red hues (lightest for Mild, darkest for Severe), while `Sex` has been assigned blue hues (light blue for females, dark blue for males). The node representing missing values of `Severity` is colored white to draw attention to it. ## Variable trees compared to contingency tables A tree with two variables is similar to a two-way contingency table. In the example above, `Sex` is shown within levels of `Severity`. This corresponds to the following contingency table, where the percentages within each column add to 100%. These are called *column percentages*. &nbsp;| Mild | Moderate | Severe | NA ------|-----------|----------|----------|--------- **F** | 11 (58%) | 11 (69%) | 2 (40%) | 3 (50%) **M** | 8 (42%) | 5 (31%) | 3 (60%) | 3 (50%) Likewise, a tree with `Severity` shown within levels of `Sex` corresponds to a contingency table with *row percentages*. While the contingency table above is more compact than the corresponding variable tree, some people find the variable tree more intuitive. When three or more variables are of interest, multi-way contingency tables are often used. These are typically displayed using several two-way tables, but as the number of variables increases, these become increasingly difficult to interpret. Variable trees, on the other hand, have the same simple structure regardless of the number of variables. Note that contingency tables are not *always* more compact than variable trees. When most cells of a large contingency table are empty (in which case the table is said to be *sparse*), the corresponding variable tree may be more compact since empty nodes are not shown. ## Features of vtree vtree is designed to be quick and easy to use, so that it is convenient for data exploration, but also flexible enough that it can be used to prepare publication-ready figures. To generate a basic variable tree, it is only necessary to specify a data frame and some variable names. However extra features extend this basic functionality to provide: * control over [labeling](#labeling), [colors](#colors), [legends](#legends), [line wrapping](#wrapping), and [text formatting](#textFormatting); * flexible [pruning](#pruning) to remove parts of the tree that are of lesser interest, which is particularly useful when a tree gets large; * [display of information about other variables in each node](#summary), including a variety of summary statistics; * special displays for [indicator variables](#Venn), [patterns](#patterns) of values, and [missingness](#missingValues); * support for [checkbox variables](#REDCapCheckboxes) from [REDCap](https://www.project-redcap.org) databases; * features for [dichotomizing variables](#dichotomizing) and [checking for outliers](#detectingOutliers); * automatic generation of PNG image files and [embedding in R Markdown](#embeddingInKnitrRmarkdown) documents; and * interactive panning and zooming using the `svtree` function to launch a [Shiny app](#svtree). In many cases, you may wish to generate several different variable trees to investigate a collection of variables in a data frame. For example, it is often useful to change the order of variables, prune parts of the tree, etc. ## Technical overview vtree is built on open-source software: in particular Richard Iannone's [DiagrammeR](http://rich-iannone.github.io/DiagrammeR/) package, which provides an interface to the [Graphviz](https://www.graphviz.org/) software using the [htmlwidgets](https://www.htmlwidgets.org/) framework. Additionally, vtree makes use of the [Shiny](https://www.rstudio.com/products/shiny/) package, and the [svg-pan-zoom](https://github.com/bumbu/svg-pan-zoom) JavaScript library. A formal description of variable trees follows. The root node of the variable tree represents the entire data frame. The root node has a child for each observed value of the first variable that was specified. Each of these child nodes represents a subset of the data frame with a specific value of the variable, and is labeled with the number of observations in the subset and the corresponding percentage of the number of observations in the entire data frame. The *n*^th^ layer below the root of the variable tree corresponds to the *n*^th^ variable specified. Apart from the root node, each node in the variable tree represents the subset of its parent defined by a specific observed value of the variable at that layer of the tree, and is labeled with the number of observations in that subset and the corresponding percentage of the number of observations in its parent node. Note that a node always represents at least one observation. And unlike a contingency table, which can have empty cells, a variable tree has no empty nodes. # The `vtree` function {#vtreeFunction} Consider a data frame named `df`, which includes discrete variables `v1` and `v2`. Suppose we wish to produce a variable tree showing subsets based on values of `v1` as well as subsets of those subsets based on values of `v2`. The variable tree can be displayed using the following command: ```{r, eval=FALSE} vtree(df,"v1 v2") ``` Alternatively, you may wish to assign the output of `vtree` to an object: ```{r, eval=FALSE} simple_tree <- vtree(df,"v1 v2") ``` Then it can be displayed later using: ```{r, eval=FALSE} simple_tree ``` Suppose `vtree` is called without a list of variables: ```{r, eval=FALSE} vtree(df) ``` In this case, only the root node is shown, representing the entire data frame. Although a tree with just one node might not seem very useful, we'll see later that [summary information](#summary) about the whole data frame can be displayed there. The `vtree` function has numerous optional parameters. For example, by default `vtree` produces a horizontal tree (that is, a tree that grows from left to right). To generate a vertical tree, specify `horiz=FALSE`. ## Mini tutorial *This section introduces some basic features of the `vtree` function.* To display a variable tree for a single variable, say `Severity`, use the following command: ```{r,eval=FALSE, results="asis"} vtree(FakeData,"Severity") ``` `r spaces(45)` `r vtree(FakeData,"Severity",width=250,height=250,pxwidth=300,imageheight="2.5in")` By default, next to each layer of the tree, a variable name is shown. In the example above, "Severity" is shown below the corresponding nodes. (For a vertical tree, "Severity" would be shown to the left of the nodes.) If you specify `showvarnames=FALSE`, no variable names will be shown. `vtree` can also be used with dplyr. For example, to rename the `Severity` variable as `HowBad`, we can pipe the data frame into the `rename` function in dplyr, and then pipe the result into `vtree`: ```{r,eval=FALSE} library(dplyr) FakeData %>% rename("HowBad"=Severity) %>% vtree("HowBad") ``` Note that `vtree` also has a [built-in way of renaming variables](#labeling), which is an alternative to using dplyr. Large variable trees can be difficult to display in a readable way. One approach that helps is to display the count and percentage on the same line in each node. For example, in the tree above, the label for the Moderate node is on two lines, like this: `r spaces(65)`**Moderate** \ `r spaces(65)`**16 (40%)** Specifying `sameline=TRUE` results in single-line labels, like this: `r spaces(65)`**Moderate, 16 (40%)** ### Percentages By default, vtree shows "valid percentages", i.e. percentages calculated using the total number of *non-missing* values as denominator. In the case of `Severity`, there are `r sum(is.na(FakeData$Severity))` missing values, so the denominator is `r nrow(FakeData)` - `r sum(is.na(FakeData$Severity))`, or `r nrow(FakeData) - sum(is.na(FakeData$Severity))`. There are `r sum(FakeData$Severity %in% "Mild")` Mild cases, and `r sum(FakeData$Severity %in% "Mild")`/`r nrow(FakeData) - sum(is.na(FakeData$Severity))` = `r sum(FakeData$Severity %in% "Mild")/(nrow(FakeData) - sum(is.na(FakeData$Severity)))` so the percentage shown is 48%. No percentage is shown in the NA node since missing values are not included in the denominator. If you prefer the denominator to represent the complete set of observations (*including* any missing values), specify `vp=FALSE`. A percentage will be shown in each of the nodes, including any NA nodes. If you don't wish to see percentages, specify `showpct=FALSE`, and if you don't wish to see counts, specify `showcount=FALSE`. ### Displaying a legend and hiding node labels {#legends} To display a legend, specify `showlegend=TRUE`. Next to each variable name are "legend nodes" representing the values of that variable and colored accordingly. For each variable, the legend nodes are grouped within a light gray box. Each legend node also contains a count (with a percentage) for the value represented by that node in the whole data frame. This is known as the *marginal* count (and percentage). When the legend is shown, labels in the nodes of the variable tree are redundant, since the colors of the nodes identify the values of the variables (although the labels may aid readability). If you prefer, you can hide the node labels, by specifying `shownodelabels=FALSE`: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",showlegend=TRUE,shownodelabels=FALSE) ``` `r spaces(45)` `r vtree(FakeData,"Severity Sex",showlegend=TRUE,shownodelabels=FALSE, pxwidth=800,imageheight="4in")` Since `Severity` is the first variable in the tree, it is not nested within another variable. Therefore the marginal counts and percentages for `Severity` shown in the legend nodes are identical to those displayed in the nodes of the variable tree. In contrast, for `Sex`, the marginal counts and percentages are different from what is shown in the nodes of the variable tree for `Sex` since they are nested within levels of `Severity`. ### Text wrapping {#wrapping} By default, `vtree` wraps text onto the next line whenever a space occurs after at least 20 characters. This can be adjusted, for example, to 15 characters, by specifying `splitwidth=15`. To disable line splitting, specify `splitwidth=Inf` (`Inf` means infinity, i.e. "do not split".) The `vsplitwidth` parameter is similarly used to control text wrapping in variable names. This is helpful with long variable names, which may be truncated unless wrapping is used. In this case text wrapping occurs not only at spaces, but also at any of the following characters: ```{eval=FALSE} . - + _ = / ( ``` For example if `vsplitwidth=5`, a variable name like `First_Emergency_Visit` would be split into `r spaces(65)``First_`\ `r spaces(65)``Emergency_`\ `r spaces(65)``Visit` *This concludes the mini-tutorial. vtree has many more features, described in the following sections.* ## Pruning {#pruning} *This section shows how to remove branches from a variable tree.* When a variable tree gets too big, or you are only interested in certain parts of the tree, it may be useful to remove some nodes along with their descendants. This is known as *pruning*. For convenience, there are several different ways to prune a tree, described below. ### The `prune` parameter Here's a variable tree we've already seen in various forms: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex") ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex", pxwidth=800,imageheight="4.2in")` Suppose you don't want the tree to show branches for individuals whose disease is Mild or Moderate. Specifying `prune=list(Severity=c("Mild","Moderate"))` removes those nodes, and all of their descendants: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",prune=list(Severity=c("Mild","Moderate"))) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",prune=list(Severity=c("Mild","Moderate")), pxwidth=500,imageheight="2.5in")` In general, the argument of the `prune` parameter is a *list* with an element named for each variable you wish to prune. In the example above, the list has a single element, named `Severity`. In turn, that element is a vector `c("Mild","Moderate")` indicating the values of `Severity` to prune. **Caution**: Once a variable tree has been pruned, it is no longer complete. This can sometimes be confusing since not all observations are represented at certain layers of the tree. For example in the tree above, only 11 observations are shown in the `Severity` nodes and their children. ### The `keep` parameter Sometimes it is more convenient to specify which nodes should be *retained* rather than which ones should be discarded. The `keep` parameter is used for this purpose, and can thus be considered the complement of the `prune` parameter. For example, to retain the Moderate `Severity` node: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate")) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"), pxwidth=500,imageheight="1.7in")` **Note**: In addition to the Moderate node, the missing value node has also been retained. In general, whenever valid percentages are used (which is the default), missing value nodes are retained when `keep` is used. This is because valid percentages are difficult to interpret without knowing the denominator, which requires knowing the number of missing values. On the other hand, here's what happens when `vp=FALSE`: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"),vp=FALSE) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",keep=list(Severity="Moderate"),vp=FALSE, pxwidth=400,imageheight="1.5in")` ### The `prunebelow` parameter As seen above, a disadvantage of pruning is that in the resulting tree, the counts shown in child nodes may not add up to the counts shown in their parent node. An alternative is to prune *below* the specified nodes (i.e. to prune their descendants), so that the counts always add up. In the present example, this means that the Mild and Moderate nodes will be shown, but not their descendants. The `prunebelow` parameter is used to do this: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",prunebelow=list(Severity=c("Mild","Moderate"))) ``` `r spaces(40)` `r vtree(FakeData,"Severity Sex",prunebelow=list(Severity=c("Mild","Moderate")), pxwidth=400,imageheight="3in")` ### The `follow` parameter The complement of `prunebelow` is `follow`. Instead of specifying which nodes should be pruned below, this allows you to specify which nodes should be "followed" (that is, *not* pruned below). ### Targeted pruning This section describes a more flexible way to prune variable trees. To explain this, first note that the `prune`, `keep`, `prunebelow`, and `follow` parameters specify pruning across all branches of the tree. For example, if you were pruning `Severity` nested within levels of `Sex`, the pruning would take place in both the M and F branches. Sometimes, however, it is preferable to perform pruning only in specified branches of the tree. This is called *targeted* pruning, and the parameters `tprune`, `tkeep`, `tprunebelow`, and `tfollow` provide this functionality. However, their arguments have a more complex form than those of the corresponding `prune`, `keep`, `prunebelow`, and `follow` parameters because they specify the *full path* from the root of the tree all the way to the nodes to be pruned. For example to remove every `Severity` node except Moderate, but only for males, the following command can be used: ```{r,eval=FALSE} vtree(FakeData,"Sex Severity",tkeep=list(list(Sex="M",Severity="Moderate"))) ``` `r spaces(40)` `r vtree(FakeData,"Sex Severity",tkeep=list(list(Sex="M",Severity="Moderate")), pxwidth=400,imageheight="3in")` Note that the argument of `tkeep` is a list of lists, one for each path through the tree. To keep both Moderate and Severe, specify `tkeep=list(list(Sex="M",Severity=c("Moderate","Severe")))`. Now suppose that, in addition to this, within females,you want to keep just Mild. Use the following specification to do this: ```{r, eval=FALSE} tkeep=list(list(Sex="M",Severity=c("Moderate","Severe")),list(Sex=F",Severity="Mild")) ``` ### The `prunesmaller` parameter As a variable tree grows, it can become difficult to see the forest for the tree. For example, the following tree is hard to read, even when `sameline=TRUE` has been specified: ```{r, eval=FALSE} vtree(FakeData,"Severity Sex Age Category",sameline=TRUE) ``` `r spaces(50)` `r vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,imageheight="5.5in",pxwidth=500)` One solution is to prune nodes that contain small numbers of observations. For example if you want to only see nodes with at least 3 observations, you can specify `prunesmaller=3`, as in this example: ```{r, eval=FALSE} vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,prunesmaller=3) ``` `r spaces(35)` `r vtree(FakeData,"Severity Sex Age Category",sameline=TRUE,prunesmaller=3, imageheight="4in",pxwidth=800)` As with the `keep` parameter, when valid percentages are used (`vp=TRUE`, which is the default), nodes represent missing values will not be pruned. (As noted previously, this is because percentages are confusing when missing values are not shown.) On the other hand, when `vp=FALSE`, missing nodes will be pruned (if they are small enough). ## Labels for variables and nodes {#labeling} *This section shows how to relabel variables and nodes.* By default, `vtree` labels variables and nodes exactly as they appear in the data frame. But it is often useful to change these labels. ### Changing variable labels with the `labelvar` parameter Suppose `Severity` in fact represents initial severity. To label it that way in the variable tree, specify `labelvar=c(Severity="Initial severity")`: ```{r,eval=FALSE} vtree(FakeData,"Severity Sex",horiz=FALSE,labelvar=c(Severity="Initial severity")) ``` `r spaces(30)` `r vtree(FakeData,"Severity Sex",horiz=FALSE, labelvar=c(Severity="Initial severity"), pxwidth=1000,imageheight="2in")` ### Changing node labels with the `labelnode` parameter By default, `vtree` labels nodes (except for the root node) using the values of the variable in question. Sometimes it is convenient to instead specify custom labels for nodes. The `labelnode` argument can be used to relabel the values. For example, you might want to use "Male" and "Female" instead of "M" and "F". ```{r,eval=FALSE} vtree(FakeData,"Group Sex",horiz=FALSE,labelnode=list(Sex=c(Male="M",Female="F"))) ``` `r spaces(30)` `r vtree(FakeData,"Group Sex",horiz=FALSE,labelnode=list(Sex=c(Male="M",Female="F")), pxwidth=600,imageheight="1.8in")` The argument of the `labelnode` parameter is specified as a list whose element names are variable names. To substitute a new label for an old label, the syntax is: `"New label"="Old label"`. Thus the full specification, as used above, is: `labelnode=list(Sex=c(Male="M",Female="F"))`. ### Targeted node labels using the `tlabelnode` parameter Suppose in the example above that `Group` A represents children and `Group` B represents adults. In `Group` A, we would like to use the labels "girl" and "boy", while in `Group` B we would like to use "woman" and "man". The `labelnode` parameter cannot handle this situation because the values of `Sex` need to be labeled differently in different branches of the tree. The `tlabelnode` parameter allows "targeted" node labels. ```{r,eval=FALSE} vtree(FakeData,"Group Sex",horiz=FALSE, labelnode=list(Group=c(Child="A",Adult="B")), tlabelnode=list( c(Group="A",Sex="F",label="girl"), c(Group="A",Sex="M",label="boy"), c(Group="B",Sex="F",label="woman"), c(Group="B",Sex="M",label="man"))) ``` `r spaces(40)` `r vtree(FakeData,"Group Sex",horiz=FALSE, labelnode=list(Group=c(Child="A",Adult="B")), tlabelnode=list( c(Group="A",Sex="F",label="girl"), c(Group="A",Sex="M",label="boy"), c(Group="B",Sex="F",label="woman"), c(Group="B",Sex="M",label="man")), pxwidth=600,imageheight="2.2in")` ## Text and text formatting {#textFormatting} *This section shows how to add bold, italics, and other text formatting.* Graphviz, the open source graph visualization software that vtree is built on, supports a variety of text formatting (including bold, colors, etc.). This is used in vtree to control formatting of text such as node labels. ### Markdown-style codes for text formatting By default, the `vtree` package uses markdown-style codes for text formatting. In the tables below, `...` represents arbitrary text. ------------- ----------------------------------------------------------------- `\n` insert a line break `\n*l` make the preceding line left-justified and insert a line break `*...*` display text in italics `**...**` display text in bold `^...^` display text in superscript (using 10 point font) `~...~` display text in subscript (using 10 point font) `%%red ...%%` display text in red (or whichever color is specified) ------------- ----------------------------------------------------------------- ### HTML-like codes for text formatting As an alternative, if you specify `HTMLtext=TRUE` you can use "HTML-like labels" (implemented in Graphviz), including: ---------------------------------- ---------------------------------------------------------- `<BR/>` insert a line break `<BR ALIGN='LEFT'/>` make the preceding line left-justified and insert a line break `<I> ... </I>` display text in italics `<B> ... </B>` display text in bold `<SUP> ... </SUP>` display text in superscript (using 10 point font) `<SUB> ... </SUB>` display text in subscript (using 10 point font) `<FONT POINT-SIZE='10'> ... </FONT>` set font to 10 point `<FONT FACE='Times-Roman'> ... </FONT>` set font to Times-Roman `<FONT COLOR='red'> ... </FONT>` set font to red ---------------------------------- ---------------------------------------------------------- See <https://www.graphviz.org/doc/info/shapes.html#html> for more details. ### Adding text to nodes using the `text` parameter Suppose you wish to add the italicized text "*Excluding new diagnoses*" to any Mild nodes in the tree. The parameter `text` is used to add text to nodes. It is specified as a list with an element named for each variable. In the example below the list has one element, named `Severity`. That element in turn is a vector `c(Mild="\n*Excluding\nnew diagnoses*")` indicating that the Mild node should include additional text using Markdown-style formatting (i.e. `\n` indicates a linebreak and the asterisks around the text indicate that it should be displayed in italics): ```{r,eval=FALSE} vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, text=list(Severity=c(Mild="\n*Excluding\nnew diagnoses*"))) ``` `r spaces(15)` `r vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, text=list(Severity=c(Mild="\n*Excluding\nnew diagnoses*")), pxwidth=1000,imageheight="2.5in")` ### Targeted text using the `ttext` parameter In the example above, suppose that new diagnoses are only excluded from Mild cases in `Group` B. But the `text` parameter adds text to *all* Mild nodes. Thus, in situations like this, the `text` parameter is not sufficient. Instead, you can use the `ttext` parameter to target exactly which nodes should have the specified text. The `ttext` parameter requires that you specify the full path from the root of the tree to the node in question, along with the text in question. The `ttext` parameter is specified as a list so that multiple targeted text strings can be specified at once. For example: ```{r,eval=FALSE} vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, ttext=list( c(Group="B",Severity="Mild",text="\n*Excluding\nnew diagnoses*"), c(Group="A",text="\nSweden"), c(Group="B",text="\nNorway"))) ``` `r spaces(10)` `r vtree(FakeData,"Group Severity",horiz=FALSE,showvarnames=FALSE, ttext=list(c(Group="B",Severity="Mild",text="\n*Excluding\nnew diagnoses*"), c(Group="A",text="\nSweden"),c(Group="B",text="\nNorway")), pxwidth=1000,imageheight="2.5in")` ## Specification of variables {#VariableSpecification} *This section shows how to control how variables appear in a variable tree.* Sometimes it is desirable to modify a variable for use in a variable tree. For example, suppose you wish to determine how many values of `Score` are missing. This is easy to do with dplyr: ```{r,eval=FALSE} library(dplyr) FakeData %>% mutate(missingScore=is.na(Score)) %>% vtree("missingScore") ``` But vtree also offers built-in tools for variable specification. Although limited, they can be very convenient. ### prefix `is.na:` If an individual variable name is preceded by `is.na:`, that variable will be replaced by a missing value indicator in the variable tree. (This differs from the [`check.is.na` parameter](#missingValues), which is used to replace *all* of the specified variables with missing value indicators.) For example: ```{r,eval=FALSE} vtree(FakeData,"is.na:Score") ``` `r spaces(55)` `r vtree(FakeData,"is.na:Score", pxwidth=500,imageheight="1.5in")` ### wildcard `#` Specifying `Ind#` matches all variable names that start with `Ind` and end with one or more numeric digits, namely `Ind1`, `Ind2`, `Ind3`, and `Ind4`. This wildcard can also be used within a variable name. For example, `visit#duration` would match `visit1duration`, `visit2duration`, etc. ### wildcard `*` Specifying `Ind*` matches all variable names that start with `Ind` and end with any other characters (or no other characters). In `FakeData` this matches `Ind1`, `Ind2`, `Ind3`, and `Ind4` (just like `Ind#` does). But if `FakeData` contained variables named `Ind` and `Index`, they would also be matched by `Ind*`. As with the `#` wildcard, the `*` wildcard can be used within a variable name. ### prefix `i:` "Intersections" between multiple variables can be generated using the prefix `i:`. For example, `i:Ind*` generates a variable representing the observed combinations of values of `Ind1`, `Ind2`, `Ind3`, and `Ind4`. (If at least one of the variables is missing, the combination will be missing.) ### prefix `r:` (for REDCap) Vtree includes special support for [REDCap](https://www.project-redcap.org/) data sets. The prefix `r:` is used to indicate REDCap checkbox variables, and can be combined with other prefixes. This is described in the section on [REDCap checkboxes](#REDCapCheckboxes) later in this vignette. ### prefix `any:` Sometimes a group of variables contain responses to a list of checkbox options (often with instructions to "check all that apply"). For example, suppose you have a data frame of shops, including whether they are open on Saturday (`openSaturday`) or Sunday (`openSunday`). Suppose no other variables start with `open`. Then `open*` will match both `openSaturday` and `openSunday`. In general for a group of checkbox variables, it is often useful to know if *any* of the options were selected (i.e. checked). In the case above, we might want to know which shops are open at all on the weekend (either Saturday or Sunday). A specification like `any:open*` is used to generate a variable that is * `TRUE` if *any* of the matching variables has a "checked" value * `FALSE` if none of the matching variables have "checked" values. The parameters `checked` and `unchecked` specify which values are considered checked or unchecked respectively, and have the following defaults: |parameter | default value |:-------------|:----------------------------------------------------------- |`checked` | `c("1","TRUE","Yes","yes")` |`unchecked` | `c("0","FALSE","No","no")` Values not listed in `checked` or `unchecked` are treated as missing values. An alternative prefix, `anyx:`, is used to specify that missing values will be removed when performing the calculation. This matches the behavior of the R function `any` when `na.rm=TRUE` is specified. ### prefix `none:` The logical complement (negation) of the `any:` prefix. An alternative prefix, `nonex:`, is used to specify that missing values will be removed when performing the calculation. ### prefix `all:` A specification like `all:open*` generates a variable which is TRUE if *all* of the matching variables have a "checked" value. An alternative prefix, `allx:`, is used to specify that missing values will be removed when performing the calculation. This matches the behavior of the R function `all` when `na.rm=TRUE` is specified. ### prefix `notall:` The logical complement (negation) of the `all:` prefix. An alternative prefix, `notallx:`, is used to specify that missing values will be removed when performing the calculation. ### prefix `tri:` {#detectingOutliers} The `tri:` prefix is useful for identifying values of a numeric variable that are *extreme* compared to the other values in a node. **Note:** Unlike other variable specifications, which take effect at the level of the entire data frame, the `tri:` prefix takes effect within each node. The effect of this variable specification is to *trichotomize* the values of a numeric variable, i.e. to divide them into three groups: * "mid": values within plus or minus 1.5&times;IQR of the median, * "high": values more than 1.5&times;IQR above the median, * "low": values more than 1.5&times;IQR below the median. ### specification `variable=value` {#dichotomizing} When a variable takes on a large number of different values, the resulting variable tree will very large. One solution is to prune the tree, for example by keeping just the node corresponding to one value of a particular variable. An alternative is to specify the value of the variable that is of primary interest and `vtree` will dichotomize the variable at that value. For example if `Severity=Mild` is specified, the `Severity` variable will be dichotomized between `Mild` and `Not Mild`. ### specifications `variable<value`, `variable>value` These two specifications are used to dichotomize a *numeric* variable, splitting above and below a specified value. This can be useful for identifying subsets with extreme values. ## Displaying summary statistics in nodes {#summary} *This section shows how to display information about other variables in the nodes.* It is often useful to display information about *other* variables (apart from those that define the tree) in the nodes of a variable tree. This is particularly useful for numeric variables, which usually would not be used to build the tree since they have too many distinct values. The `summary` parameter allows you to show information (for example, a mean) about a specified variable within a subset of the data frame. ### Default summaries Suppose you are interested in summary information for the `Score` variable for all of the observations in the data frame (i.e. in the root node). In that case you don't need to specify any variables for the tree itself: ```{r,eval=FALSE} vtree(FakeData,summary="Score") ``` `r spaces(68)` `r vtree(FakeData,summary="Score", pxwidth=500,imageheight="1.2in")` When the name of a numeric variable (in this case `"Score"`) is specified as the argument of the `summary` parameter, a default set of summary statistics (as shown above) appears: the variable name, the number of missing values, the mean and standard deviation, the median and interquartile range (IQR), and the range. (Note, however, that if there are three or fewer observations, instead of showing the above summary statistics, the observations are simply listed.) Suppose we're building a variable tree based on `Severity`. We can display these summaries for `Score` in each node: ```{r,eval=FALSE} vtree(FakeData,"Severity",summary="Score",horiz=FALSE) ``` `r spaces(68)` `r vtree(FakeData,"Severity",summary="Score",horiz=FALSE, pxwidth=1000,imageheight="2.7in")` Sometimes it is helpful to extract summary information as text. For example, we might wish to access the summary information contained in the Mild node. This is explained [later on](#extracting), but here's a brief example: ```{r attributes} vSeverity <- vtree(FakeData,"Severity",summary="Score",horiz=FALSE) info <- attributes(vSeverity)$info cat(info$Severity$Mild$.text) ``` There are also default summaries for factor variables and for indicator variables. For example, `Category` is a factor variable: ```{r,eval=FALSE} vtree(FakeData,summary="Category") ``` `r spaces(68)` `r vtree(FakeData,summary="Category", pxwidth=300,imageheight="1in")` Indicator variables have two levels such as 0 / 1, or `TRUE` / `FALSE`. For example, `Event` is an indicator variable ```{r,eval=FALSE} vtree(FakeData,summary="Event") ``` `r spaces(68)` `r vtree(FakeData,summary="Event", pxwidth=300,imageheight="0.5in")` ### Specification of variables in the summary argument Variables in the `summary` argument can also be specified in a way that is similar to the [specification of variables](#VariableSpecification) for structuring a variable tree. For example, if we wish to know the proportion of patients in each node whose `Category` is single, we specify `Category=single` in the `summary` argument: ```{r,eval=FALSE} vtree(FakeData,"Severity",summary="Category=single",horiz=FALSE) ``` `r vtree(FakeData,"Severity",summary="Category=single",horiz=FALSE, pxwidth=1000,imageheight="1.4in")` Summaries can be obtained for a collection of variables using pattern-matching, for example: ```{r summary-pattern,eval=FALSE} vtree(FakeData,"Severity",summary="Ind*",sameline=TRUE,horiz=FALSE,just="l") ``` `r vtree(FakeData,"Severity",summary="Ind*",sameline=TRUE,horiz=FALSE,just="l", pxwidth=1000,imageheight="2.6in",margin=0.25)` Incidentally, note that `just="l"` specifies that all text should be left-justified, which conveniently lines up all of the rows of the summary. The `summary` argument can also use the prefixes `i:`, `any:`, `none:`, `all:`, `notall:` (as well as `anyx:`, `nonex:`, `allx:`, and `notallx:`) and wildcards `#` and `*` (similar to [variable specifications](#VariableSpecification)). Additionally, specifications for [REDCap checkboxes](#REDCapCheckboxes) can be used. ### Control codes: `%noroot%`, `%leafonly%`, `%var=`*v*`%`, and `%node=`*n*`%` By default, summary information is shown in all nodes. However, it may also be convenient to only show it in specific nodes. To control this, special codes that begin and end with `%` can be specified. The following control codes are available: |code | summary information restricted to: |:----------------|---------------------------------------- |`%noroot%` | all nodes *except* the root |`%leafonly%` | leaf nodes |`%var=`*v*`%` | nodes of variable *v* |`%node=`*n*`%` | nodes named *n* The control codes can be specified by adding them to the end of the summary string, separated with a space. For example, to only show summary information for nodes of the `Category` variable with the value `single`: ```{r, eval=FALSE} vtree(FakeData,"Severity Category",summary="Score<10 %var=Category%%node=single%", sameline=TRUE, showlegend=TRUE, showlegendsum=TRUE) ``` `r spaces(35)` `r vtree(FakeData,"Severity Category",summary="Score<10 %var=Category%%node=single%", sameline=TRUE, showlegend=TRUE, showlegendsum=TRUE, pxwidth=1500,imageheight="4.5in")` Here `showlegend=TRUE` was specified, and additionally `showlegendsum=TRUE`, which indicates that summaries should also be shown in legend nodes. ### Customized summaries The `summary` parameter also allows for customized summaries. For example, we might wish to display only the mean `Score` in each node of the tree. The `%mean%` code is used to represent the mean of the specified variable (preceded here by a line break, `\n`). ```{r,eval=FALSE} vtree(FakeData,"Severity",summary="Score \nmean score\n%mean%",sameline=TRUE,horiz=FALSE) ``` `r spaces(30)` `r vtree(FakeData,"Severity",summary="Score \nmean score\n%mean%", sameline=TRUE,horiz=FALSE, pxwidth=800,imageheight="1.5in")` In addition to the `%mean%` code, numerous other summary codes are supported, as listed in the table below. When such a code is present, the default summary is not shown. Instead, any text that is provided---in this case `\nmean score\n`---is shown, together with the requested summary information. If there are any missing values in a node, the number of missing values is shown using the abbreviation `mv`. To see summaries without any decimals, specify `cdigits=0`. summary code | result :---------------|:------------------------------------------------------------------- `%mean%` | mean\ (variant: `%meanx%` does not report missing values&ast;) `%SD%` | standard deviation\ (variant: `%SDx%` does not report missing values&ast;) `%sum%` | sum\ (variant: `%sumx%` does not report missing values&ast;) `%min%` | minimum\ (variant: `%minx%` does not report missing values&ast;) `%max%` | maximum\ (variant: `%maxx%` does not report missing values&ast;) `%range%` | range\ (variant: `%rangex%` does not report missing values&ast;) `%median%` | median, i.e. p50\ (variant: `%medianx%` does not report missing values&ast;) `%IQR%` | IQR, i.e. p25, p75\ (variant: `%IQRx%` does not report missing values&ast;) `%freqpct%` | frequency and percentage of values of a variable\ (variant: `%freqpct_%` shows each value on a separate line) `%freq%` | frequency of values of a variable\ (variant: `%freq_%` shows each value on a separate line) `%pY%` | *Y*th percentile (e.g. `p50` means the 50th percentile) `%npct%` | frequency and percentage of a logical variable. By default "valid percentages" are used. Any missing values are also reported. `%pct%` | same as `%npct%` but percentage only (with no parentheses). `%list%` | list of individual values, separated by commas\ (variant: `%list_%` shows each value on a separate line) `%mv%` | the number of missing values `%nonmv%` | the number of non-missing values `%v%` | the name of the variable &ast;*Caution is recommended when suppressing missing values.* The `summary` argument can include any number of these codes, mixed with text and formatting codes. ### The `%trunc%` code It is sometimes convenient to see individual values of a variable in each node. A good example is ID numbers. To do this, use the `%list%` code. When a value occurs more than once in the subset, it will be followed by a count of the number of repetitions in parentheses. When there are many individual values, it is often convenient to truncate the output. If you specify `%trunc=`*N*`%`, summary information will be truncated after *N* characters, and followed by "...". ### R expressions in the summary argument Rather than starting the `summary` argument with a variable name, an R expression involving variables in the data frame can be given, as long as it does not contain any spaces. ```{r,eval=FALSE} vtree(FakeData,"Severity Category", summary="(Post-Pre)/Pre \nmean = %mean%",sameline=TRUE,horiz=FALSE,cdigits=1) ``` `r vtree(FakeData,"Severity Category", summary="(Post-Pre)/Pre \nmean = %mean%",sameline=TRUE,horiz=FALSE,cdigits=1, pxwidth=1000,imageheight="2in",margin=0.25)` Expressions involving functions can also be used; for example `sqrt(abs(Post/Pre))`. ### More than one variable Sometimes it is useful to display summary information for more than one variable. To do this, specify `summary` as a *vector* of character strings. For example: ```{r,eval=FALSE} vtree(FakeData,"Severity",horiz=FALSE,showvarnames=FALSE,splitwidth=Inf,sameline=TRUE, summary=c("Score \nScore: mean (SD) %meanx% (%SD%)","Pre \nPre: range %range%")) ``` `r vtree(FakeData,"Severity",horiz=FALSE,showvarnames=FALSE,splitwidth=Inf,sameline=TRUE, summary=c( "Score \nScore: mean (SD) %meanx% (%SD%)", "Pre \nPre: range %range%"), pxwidth=1400,imageheight="1.4in")` ### Targeted summaries Sometimes you only want to show a summary in a particular node. Targeted summaries are specified with the `tsummary` parameter as a list of character-string vectors. The initial elements of each character string vector point to a specific node. The final element of each character string vector is a summary string, with the same structure as \code{summary}. ```{r,eval=FALSE} vtree(FakeData,"Age Sex",tsummary=list(list(Age="5",Sex="M","id \n%list%")),horiz=FALSE) ``` `r vtree(FakeData,"Age Sex",tsummary=list(list(Age="5",Sex="M","id \n%list%")),horiz=FALSE, pxwidth=1400,imageheight="2.3in")` ## Pattern trees and pattern tables {#patterns} *This section shows how to display all the combinations of values in a set of variables.* Each node in a variable tree provides the frequency of a particular combination of values of the variables. The leaf nodes represent the observed combinations of values of *all* of the variables. For example, in a variable tree for `Severity` and `Sex`, the leaf nodes correspond to Mild F, Mild M, Moderate F, Moderate M, etc. These combinations, or "patterns", can be treated as an additional variable. And if this new pattern variable is used as the first variable in a tree, then the branches of the tree will be simplified: each branch will represent a unique pattern, with no sub-branches. A "pattern tree" can be easily produced by specifying `pattern=TRUE`. For example: ```{r, eval=FALSE} vtree(FakeData,"Severity Sex") vtree(FakeData,"Severity Sex",pattern=TRUE) ``` `r spaces(10)` `r vtree(FakeData,"Severity Sex", pxwidth=500,imageheight="4in")` `r spaces(15)` `r vtree(FakeData,"Severity Sex",pattern=TRUE, pxwidth=600,imageheight="4in")` Pattern trees are simpler to read than ordinary variable trees, but they involve a considerable loss of information, since they only represent the *n*th-degree subsets (where *n* is the number of variables). Note that by default, when `pattern=TRUE` is specified, the root node is not shown (in order to simplify the display). A disadvantage of this is that the total sample size is not shown. You can override this behavior by specifying `showroot=TRUE`. A pattern tree has two other special characteristics. First, note that after the first layer (representing `pattern`), counts and percentages are not shown, since they are not informative: by definition, all nodes within a branch have the same count. Second, note that in place of arrows, undirected line segments are shown. This is because, unlike in a regular variable tree, the order of variables is irrelevant in a pattern tree. Sometimes, however, the variables do have a natural ordering, as in the case of longitudinal variables. To show arrows, specify `seq=TRUE` instead of `pattern=TRUE`, and a "sequence" (i.e. an ordered pattern) will be shown. Summaries can be shown in pattern trees (using the `summary` parameter), but they only appear in the pattern node (or the sequence node if `seq=TRUE`). ### Pattern tables A pattern tree has the same structure as a table. Indeed, it may be more convenient to produce a table rather than a pattern tree. A data frame containing the information from the pattern tree can be exported by specifying `ptable=TRUE`: ```{r} vtree(FakeData,"Severity Sex",ptable=TRUE) ``` The pattern table includes a column for the counts from the pattern nodes, and a column for percentages. Compared to a variable tree, this table is much more compact, and may be more suitable for use in a manuscript. ### Indicator variables Pattern trees can be very useful for *indicator variables*, i.e. variables that take values like 0/1, no/yes, FALSE/TRUE, etc. For convenience in this section, we'll refer to 0 (or no, FALSE, etc.) as a *negative* and 1 (or yes, TRUE, etc.) as an *affirmative*. The variables `Ind1` through `Ind4` in `FakeData` are 0/1 indicator variables. If these variables are interpreted as representing set membership (0 = non-member, 1 = member), then a pattern tree is an alternative representation of a Venn diagram. If you specify `Venn=TRUE`, the nodes (except for the pattern nodes) will be blank, with only their shade indicating their value (dark = 1, light = 0, white = missing). ```{r, eval=FALSE} vtree(FakeData,"Ind1 Ind2 Ind3 Ind4",Venn=TRUE,pattern=TRUE) ``` `r spaces(40)` `r vtree(FakeData,"Ind1 Ind2 Ind3 Ind4",Venn=TRUE,pattern=TRUE, pxwidth=500,imageheight="5in")` Big pattern trees can be overwhelming, so it may be useful to prune patterns that occur fewer than, say, 3 times, by specifying `prunesmaller=3`. A pattern tree for indicator variables provides all the information that a Venn diagram represents, but unlike a Venn diagram, missing values are also represented. This can also be shown as a pattern table. For example: ```{r} vtree(FakeData,"Ind1 Ind2",ptable=TRUE) ``` #### The `VennTable` function For indicator variables, there is an extra function, `VennTable`, which converts the pattern table to a matrix of character strings and adds some additional totals. ```{r} VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE)) ``` By default in R, when a matrix of character strings is printed, quotation marks are displayed around each element. Unfortunately the result is unattractive. Instead it's helpful to call the `print` function and specify `quote=FALSE`: ```{r} print(VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE)),quote=FALSE) ``` Without all those quotation marks, it's easier to see what `VennTable` adds: * the total sample size (`r nrow(FakeData)`) and percentage (100), and * the total number (N) of affirmatives for each variable, together with a percentage. The `VennTable` function can also be used in an R Markdown document. Specifying `markdown=TRUE` generates a pandoc markdown pipetable, with several formatting tweaks: * the rows and columns of the table are transposed * affirmatives are represented by checkmarks * negatives are represented by spaces * missing values are represented by dashes (which can be changed with the `NAcode` parameter). To display the table in R Markdown, use this inline call: ```{r, eval=FALSE} `r VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE),markdown=TRUE)` ``` `r VennTable(vtree(FakeData,"Ind1 Ind2",ptable=TRUE),markdown=TRUE)` `VennTable` has some additional parameters. The `checked` parameter is used to specify values that should be interpreted as affirmative. By default, it is set to `c("1","TRUE","Yes","yes","N/A")`. Similarly, the `unchecked` parameter is used to specify values that should be interpreted as negative, with default `c("0","FALSE","No","no","not N/A")`. #### Using the `summary` parameter in pattern tables The `summary` parameter can also be used in pattern tables. If a single summary is requested, it appears in the `summary_1` variable in the data frame. Additional summaries appear as `summary_2`, `summary_3`, etc. ```{r} vtree(FakeData,"Severity Sex",summary=c("Score %mean%","Pre %mean%"),ptable=TRUE) ``` ### Checking for missing values with the `check.is.na` parameter {#missingValues} If `check.is.na=TRUE` is specified, each variable is replaced by an indicator of whether or not it is missing, and `pattern=TRUE` is automatically set. As when `Venn=TRUE` is specified, all nodes except for the pattern node are blank, and only their shade indicates missing (dark) or not (light). Whereas the variables used to build a variable tree are normally categorical, in this situation non-categorical variables can be used, because their missingness is represented instead of their actual values. ```{r,eval=FALSE} vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE) ``` `r spaces(40)` `r vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE, pxwidth=600,imageheight="3in")` Specifying `ptable=TRUE` produces this information in a data frame, and calling `VennTable` shows additional information. To display the table in R Markdown, use this inline call: ```{r, eval=FALSE} `r VennTable(vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,ptable=TRUE), markdown=TRUE)` ``` `r VennTable(vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,ptable=TRUE),markdown=TRUE)` The rows `n` and `pct` represent the frequency and percentage of the total number of cases for each pattern of missingness, and the columns `N` and `pct` on the right-hand side represent the frequency and percentage of missingness for each variable. It may be useful to identify the ID numbers for these patterns. Here the results are truncated to 15 characters: ```{r} vtree(FakeData,"Severity Age Pre Post",check.is.na=TRUE,summary="id %list%%trunc=15%", ptable=TRUE) ``` ## Colors {#colors} *This section explains how colors and color palettes can be used.* By default, `vtree` assigns colors to nodes of each successive variable using color palettes from [RColorBrewer](https://cran.r-project.org/package=RColorBrewer). The sequence of palettes (identified by short names) is as follows: - ------- ------ -- ------- ------ -- ------- ------- ------ ------ 1 Reds &nbsp; 6 YlGn &nbsp; 11 BuPu &nbsp; 16 RdPu 2 Blues &nbsp; 7 PuBu &nbsp; 12 YlOrRd &nbsp; 17 BuGn 3 Greens &nbsp; 8 PuRd &nbsp; 13 RdYlGn &nbsp; 18 OrRd 4 Oranges &nbsp; 9 YlOrBr &nbsp; 14 GnBu &nbsp; 5 Purples &nbsp; 10 PuBuGn &nbsp; 15 YlGnBu &nbsp; - ------- ------ -- ------- ------ -- ------- ------- ------ ------ If you prefer to change the color assignments, you can use the `palette` parameter. For example, by default a variable tree for `Sex` and `Severity` will assign shades of red to nodes of `Sex` and shades of blue to notes of `Severity`. To switch to shades of, say, green and orange instead, use: ```{r, eval=FALSE} vtree(FakeData,"Sex Severity",palette=c(3,4)) ``` Sometimes it may be useful to reverse the order of a gradient. To reverse the order of all gradients, specify `revgradient=TRUE`. The gradient for selected variables can be reversed as in the example below: ```{r, eval=FALSE} vtree(FakeData,"Sex Group Severity",revgradient=c(Sex=TRUE,Severity=TRUE)) ``` Other color-related parameters include: ---------------- --------------------------------------------------------- `sortfill` Specifying `sortfill=TRUE` fills nodes with gradient colors in sorted order according to the node count. `NAfillcolor` By default, missing value nodes are colored white. For a different color (say gray), specify `NAfillcolor="gray"`. To instead use a color from the current palette, specify `NAfillcolor=NULL`. `rootfillcolor` The color of the root node can be changed (say to yellow) by specifying `rootfillcolor="yellow"`. `fillcolor` To set all nodes of the tree (except for missing value nodes and the root node) to be the same color (say palegreen), specify `fillcolor="palegreen"`. `plain` A simple color scheme is produced by specifying `plain=TRUE`. (Additionally, this increases the spaces between nodes.) ---------------- --------------------------------------------------------- ## REDCap checkboxes {#REDCapCheckboxes} *This section details support for checkbox variables from REDCap.* In datasets exported from [REDCap](https://www.project-redcap.org/), checkboxes (i.e. select-all-that-apply boxes) are represented in a special way. For each item in a checklist, a separate variable is created. Suppose survey respondents were asked to select which flavors of ice cream (Chocolate, Vanilla, Strawberry) they like. Within REDCap, the variable name for this list of checkboxes is `IceCream`, but when the dataset is exported, individual variables `IceCream___1` (representing Chocolate), `IceCream___2` (Vanilla), and `IceCream___3` (Strawberry) are created. When the dataset is read into R, the names of the flavors are embedded in the `attributes` of these variables. For illustrative purposes, let's build a dataframe like this using the `build.data.frame` function (for an explanation of this function see the section of this vignette on [generating a data frame by specifying subset sizes](#GeneratingDataFrames) ```{r} dessert <- build.data.frame( c( "group","IceCream___1","IceCream___2","IceCream___3"), list("A", 1, 0, 0, 7), list("A", 1, 0, 1, 2), list("A", 0, 0, 0, 1), list("A", 1, 1, 1, 1), list("B", 1, 0, 1, 1), list("B", 1, 0, 0, 2), list("B", 0, 1, 1, 1), list("B", 0, 0, 0, 1)) attr(dessert$IceCream___1,"label") <- "Ice cream (choice=Chocolate)" attr(dessert$IceCream___2,"label") <- "Ice cream (choice=Vanilla)" attr(dessert$IceCream___3,"label") <- "Ice cream (choice=Strawberry)" ``` ### prefix `r:` The prefix `r:` identifies a REDCap checklist variable, and extracts a label from the variable attribute. For example, the following call automatically displays "Chocolate": ```{r eval=FALSE} vtree(dessert,"r:IceCream___1") ``` ### suffix `@` The suffix `@` matches REDCap checklist variables based on the naming scheme used by REDCap for checklist variables. For example, the following call automatically displays Chocolate, Vanilla, and Strawberry: ```{r eval=FALSE} vtree(dessert,"r:IceCream@") ``` ### variable prefixes `rany:`, `rnone:`, `rall:`, and `rnotall:` The variable prefixes `any:`, `none:`, `all:`, and `notall:` can be combined with the `r:` prefix to form `rany:`, `rnone:`, `rall:`, and `rnotall:`. For example, to determine whether anyone did not like *any* of the flavors (Chocolate, Vanilla, or Strawberry): ```{r eval=FALSE} vtree(dessert,"rnone:IceCream@") ``` ### variable prefix `ri:` "Intersections" of REDCap variables may be obtained by combining the `r:` prefix with the `i:` prefix: ```{r eval=FALSE} vtree(dessert,"ri:IceCream@") ``` ### Deprecated: variable prefixes `stem:` and `rc:` To examine the pattern of ice-cream flavor choices, the following can be used: ```{r eval=FALSE} vtree(dessert,"IceCream___1 IceCream___2 IceCream___3",pattern=TRUE) ``` One problem is that this doesn't assign the appropriate labels to `IceCream___1` (Chocolate), `IceCream___2` (Vanilla), and `IceCream___3` (Strawberry). Instead, try the following more compact call, which also assigns labels automatically. ```{r eval=FALSE} vtree(dessert,"stem:IceCream",pattern=TRUE) ``` The `summary` parameter also supports a `stem:` prefix: ```{r, eval=FALSE} vtree(dessert,summary="stem:IceCream",splitwidth=Inf,just="l") ``` `r spaces(63)` `r vtree(dessert,summary="stem:IceCream",splitwidth=Inf,just="l", pxwidth=1000,imageheight="1in")` If you wish to only examine specific REDCap checkbox items, the `rc:` prefix can be used. For example to examine results for just Chocolate and Strawberry: ```{r, eval=FALSE} vtree(dessert,"rc:IceCream___1 rc:IceCream___3",pattern=TRUE) ``` ## The DOT script generated by `vtree` *This section shows how to obtain the DOT script that displays a variable tree.* Specifying `getscript=TRUE` lets you capture the DOT script representing a variable tree. (DOT is a graph description language used by Graphviz, which is used by DiagrammeR, which is used by vtree!). Here is an example: ```{r, comment=""} dotscript <- vtree(FakeData,"Severity",getscript=TRUE) cat(dotscript) ``` If you wish to directly edit this code, it can can be pasted into an online Graphviz editor, for example: https://dreampuf.github.io/GraphvizOnline/ http://magjac.com/graphviz-visual-editor/ ## Extracting a list of information about a variable tree {#extracting} *This section explains how to obtain all of the counts and percentages of a variable tree.* Sometimes it is useful to extract counts, percentages, and summary information from a variable tree. The object returned by `vtree` has an attribute `info` containing structured information about the counts and percentages in each node. Here is an example: ```{r,echo=TRUE,message=FALSE,eval=FALSE} v <- vtree(FakeData,"Group Viral",horiz=FALSE) v ``` `r spaces(30)` ```{r,echo=FALSE,message=FALSE} v <- vtree(FakeData,"Group Viral",pxwidth=800,imageheight="2in",horiz=FALSE) v ``` ```{r,echo=TRUE,message=FALSE} attributes(v)$info ``` The list contains the counts (`.n`), percentages (`.pct`), and summary text (`.text`) that appear in the tree. # Ways to call vtree `vtree` behaves differently depending on the context in which it is called. ## Calling vtree interactively * If `vtree` is called interactively in RStudio, it displays the variable tree in the Viewer window. * If `vtree` is called interactively from the RGui console (i.e. from R outside of RStudio), it displays the variable tree in a browser window. ## Calling vtree from knitr and R Markdown {#embeddingInKnitrRmarkdown} When `vtree` is called from knitr, it generates * A PNG file if the output format is Markdown * A PDF file if the output format is LaTeX. Here's how it does that. `vtree` uses the `DiagrammeR` package, which automatically generates an `htmlwidget` object for display in HTML, using the [htmlwidgets](https://www.htmlwidgets.org/) framework. Then `vtree` converts the `htmlwidget` object into an SVG image, and finally into a PNG or PDF file. ### Generating PNG files PNG files are useful because they allow you to display variable trees in Microsoft Word documents, and also because HTML files that use htmlwidgets can get large, and if they contain several widgets they can be slow to load. If `vtree` is called while an R Markdown file is being knitted, it generates a PNG file and automatically embeds it into the knitted document. The resolution of the PNG file in pixels is determined by parameters `pxwidth` and `pxheight`. If neither is specified, `pxwidth` is automatically set to 2000, which provides good resolution for a printed page. The height of the image in the R Markdown output document can be specified using the `imageheight` parameter, for example `imageheight="4in"` for a 4-inch image. There is also an `imagewidth` parameter. If neither is specified, `imageheight` is automatically set to 3 inches. *Note*: You may notice a warning in the R Markdown rendering (in RStudio, the R Markdown pane) like this: ```{r, eval=FALSE,echo=TRUE} <unknown>:1919791: Invalid asm.js: Function definition doesn't match use ``` Although distracting, this message is irrelevant. ### Embedding image files The PNG or PDF file is stored in the folder specified by the `folder` parameter, or if not specified, a temporary folder will be used. Successive PNG files are named `vtree001.png`, `vtree002.png`, and so forth and are stored in the folder. (Similarly PDF files are named `vtree001.pdf`, etc.) During knitting, `vtree` uses the `options` function in base R to store a variable called `vtcount` to count the PNG files, and a variable called `vtfolder` to identify the folder where they will be stored. To call `vtree` in R Markdown, you can use inline code: ```{r, eval=FALSE} `r vtree(FakeData,"Sex Severity")` ``` Or you can use a code chunk: ```` `r ''````{r} vtree(FakeData,"Sex Severity") ``` ```` One advantage of code chunks is that they can also be run interactively (for example within RStudio, by clicking on the green arrow at the top right of a code chunk). ### Generating an image file but not displaying it Specifying `imageFileOnly=TRUE` instructs vtree to generate an image file but not display it. ### Generating an htmlwidget in an HTML document When knitting to an HTML document, htmlwidgets can be used rather than embedding a PNG file. To use htmlwidgets instead of a PNG file simply specify `pngknit=FALSE`. ## `svtree`: Using vtree in Shiny {#svtree} Thanks to Shiny and the svg-pan-zoom JavaScript library, interactive panning and zooming of a variable tree is possible with the `svtree` function. The syntax of `svtree` is the same as that of `vtree`, but instead of generating a static variable tree, it launches a Shiny app. The mousewheel allows you to zoom in or out. The variable tree can also be dragged to a different position. Thanks to the panning and zooming functionality in `svtree`, it is possible to examine larger variable trees than with `vtree`. In large variable trees it is often useful to show the variable name in each node, since the variable labels (which are shown at the bottom or left-hand margin) may not be visible after zooming. To show the variable name in each node, specify `showvarinnode=TRUE`. # Generating a data frame by specifying subset sizes {#GeneratingDataFrames} `vtree` is designed to generate a variable tree based on a data frame. However, sometimes the sizes of subsets are known but no data frame is available. The `build.data.frame` function allows you to build a data frame by specifying the size of subsets. Here's an example involving pets: ```{r} build.data.frame( c("pet","breed","size"), list("dog","golden retriever","large",5), list("cat","tabby","small",2)) ``` In this case there are five large golden retrievers and 2 small tabby cats. Although a data frame like this could easily be created without using `build.data.frame`, it’s a different situation when the counts are large. For example: ```{r, eval=FALSE} build.data.frame( c("pet","breed","size"), list("dog","golden retriever","large",5), list("cat","tabby","small",2), list("dog","Dalmation","various",101), list("cat","Abyssinian","small",5), list("cat","Abyssinian","large",22), list("cat","tabby","large",86)) ``` # Examples ## Rudimentary CONSORT diagrams Consider the following fictitious data about a randomized controlled trial (RCT): ```{r} FakeRCT ``` The CONSORT diagram (http://www.consort-statement.org/) shows the flow of patients through the study, starting with those who meet eligibility criteria, then those who are randomized, etc. It is easy to produce a rudimentary version of a CONSORT diagram in `vtree`. The key step is to prune branches for those who are *not* eligible, *not* randomized, etc. This can be done using the `keep` parameter: ```{r,eval=FALSE} vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility") ``` `r spaces(55)` `r vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, keep=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", width=230,height=500,pxwidth=300,imageheight="5in")` Note that this does not include all of the additional information for a full CONSORT diagram (exclusion reasons and counts, as well as numbers of patients who received their allocated interventions, who discontinued intervention, and who were excluded from analysis). It does, however, provide the main flow information. Additional information can be obtained by viewing the nodes for patients in the pruned branches (but not their descendants). The `follow` parameter makes that easy: ```{r,eval=FALSE} vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility") ``` `r spaces(30)` `r vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", width=400,height=500,pxwidth=500,imageheight="5in")` Finally, it may be useful to see the ID numbers in each node. This can be done using the `summary` parameter with the `%list%` code. Since IDs are less useful in the root note, the `%noroot%` code is also specified here: ```{r, eval=FALSE} vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", summary="id \nid: %list% %noroot%") ``` `r spaces(30)` `r vtree(FakeRCT,"eligible randomized group followup analyzed",plain=TRUE, follow=list(eligible="Eligible",randomized="Randomized",followup="Followed up"), horiz=FALSE,showvarnames=FALSE,title="Assessed for eligibility", summary="id \nid: %list% %noroot%", width=500,height=600,pxwidth=600,imageheight="5in")` ## Examples using R datasets {#RdatasetExamples} The `datasets` package is loaded in R by default. In the following section, `vtree` is applied to several of these data sets for illustrative purposes. Note that the variable trees generated by the commands below are not shown. The reader can try these commands to see what the variable trees look like, and experiment with many other possibilities. ### Esophageal cancer The `esoph` data set (data from a case-control study of esophageal cancer in Ille-et-Vilaine, France), has 88 different combinations of age group, alcohol consumption, and tobacco consumption. Let's examine the total number of cases and the total number of controls among patients aged 75 and older compared to the rest of the patients: ```{r, eval=FALSE} # Relabel agegp 75+ to 75plus because vtree tries to parse the + ESOPH <- esoph levels(ESOPH$agegp)[levels(ESOPH$agegp)=="75+"] <- "75plus" vtree(ESOPH,"agegp=75plus",sameline=TRUE,cdigits=0, summary=c("ncases \ncases=%sum%%leafonly%","ncontrols controls=%sum%%leafonly%")) ``` ### Hair and eye color The `HairEyeColor` data set is an array representing a contingency table (also called a crosstab or crosstabulation). Before `vtree` can be applied to this data set, it is necessary to convert the table of crosstabulated frequencies to a data frame of cases. For convenience, the `vtree` package includes a helper function to do this, called `crosstabToCases`. It is adapted from a function listed on the [Cookbook for R website](http://www.cookbook-r.com/Manipulating_data/Converting_between_data_frames_and_contingency_tables/#countstocases-function) ```{r, eval=FALSE} hec <- crosstabToCases(HairEyeColor) ``` There are a lot of combinations but let's say we are especially interested in green eyes (as compared to non-green eyes). We can use the variable specification `Eye=Green` to do this: ```{r, eval=FALSE} vtree(hec,"Hair Eye=Green Sex",sameline=TRUE) ``` ### Titanic The `Titanic` dataset is a 4-dimensional array of counts. First, let's convert it to a dataframe of individuals: ```{r, eval=FALSE} titanic <- crosstabToCases(Titanic) ``` We'll specify `sameline=TRUE` so that the variable tree is a bit more compact: ```{r, eval=FALSE} vtree(titanic,"Class Sex Age",summary="Survived=Yes \n%pct% survived",sameline=TRUE) ``` ### mtcars The `mtcars` data set was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). The rownames of the data set contain the names of the cars. Let's move that information into a column. To do that, we'll make a slightly altered version of the data frame which we'll call `mt`: ```{r, eval=FALSE} mt <- mtcars mt$name <- rownames(mt) rownames(mt) <- NULL ``` Now let's look at the mean and standard deviation of horsepower (HP) by number of carburetors, nested within number of gears, and in turn nested within number of cylinders: ```{r, eval=FALSE} vtree(mt,"cyl gear carb",summary="hp \nmean (SD) HP %mean% (%SD%)") ``` The above shows the mean and SD of horsepower by (1) number of cylinders; (2) number of gears (within number of cylinders); and (3) number of carburetors (within number of gears nested within number of cylinders). That's a lot of information. Suppose instead that we are only interested in number 3 above, i.e. all combinations of number of cylinders, number of gears, and number of carburetors. In that case, we can specify `ptable=TRUE`, To make the table a little easier to read, set the number of digits for the mean and SD to be zero, and relabel the variables. ```{r, eval=FALSE} vtree(mt,"cyl gear carb",summary="hp mean (SD) HP %mean% (%SD%)", cdigits=0,labelvar=c(cyl="# cylinders",gear="# gears",carb="# carburetors"), ptable=TRUE) ``` We might also like to list the names of cars by number of carburetors nested within number of gears: ```{r, eval=FALSE} vtree(mt,"gear carb",summary="name \n%list%%noroot%",splitwidth=50,sameline=TRUE, labelvar=c(gear="# gears",carb="# carburetors")) ``` ### UCBAdmissions The `UCBAdmissions` data is consists of aggregate data on applicants to graduate school at Berkeley for the six largest departments in 1973 classified by admission and sex. According to the data set Details, "This data set is frequently used for illustrating Simpson's paradox, see Bickel et al. (1975). At issue is whether the data show evidence of sex bias in admission practices. There were 2691 male applicants, of whom 1198 (44.5%) were admitted, compared with 1835 female applicants of whom 557 (30.4%) were admitted." Furthermore, "the apparent association between admission and sex stems from differences in the tendency of males and females to apply to the individual departments (females used to apply more to departments with higher rejection rates)." First, we'll convert the crosstab data to a data frame of cases, `ucb`: ```{r, eval=FALSE} ucb <- crosstabToCases(UCBAdmissions) ``` Next, let's look at admission rates by Gender, nested within department: ```{r, eval=FALSE} vtree(ucb,"Dept Gender",summary="Admit=Admitted \n%pct% admitted",sameline=TRUE) ``` ### ChickWeight The `ChickWeight` data set is from an experiment on the effect of diet on early growth of chicks. Let's look at the mean weight of chicks at birth (0 days of age) and 4 days of age, nested within type of diet. A simple variable tree can be produced like this: ```{r, eval=FALSE} vtree(ChickWeight,"Diet Time", keep=list(Time=c("0","4")),summary="weight \nmean weight %mean%g") ``` To make the display a little easier to read, relabel the nodes and the `Time` variable: ```{r, eval=FALSE} vtree(ChickWeight,"Diet Time",keep=list(Time=c("0","4")), labelnode=list( Diet=c("Diet 1"="1","Diet 2"="2","Diet 3"="3","Diet 4"="4"), Time=c("0 days"="0","4 days"="4")), labelvar=c(Time="Days since birth"),summary="weight \nmean weight %mean%g") ``` ### InsectSprays The `InsectSprays` data set contains counts of insects in agricultural experimental units treated with different insecticides. Let's look at those counts by insecticide. ```{r, eval=FALSE} vtree(InsectSprays,"spray",splitwidth=80,sameline=TRUE, summary="count \ncounts: %list%%noroot%",cdigits=0) ``` ### ToothGrowth The `ToothGrowth` data set contains the length of odontoblasts (cells responsible for tooth growth) in 60 guinea pigs. Each animal received one of three dose levels of vitamin C (0.5, 1, and 2 mg/day) by one of two delivery methods, orange juice or ascorbic acid (a form of vitamin C and coded as VC). Let's examine the percentage with length > 20 by dose nested within delivery method: ```{r, eval=FALSE} vtree(ToothGrowth,"supp dose",summary="len>20 \n%pct% length > 20") ``` To make the display a little easier to read, relabel the nodes and the `Time` variable: ```{r, eval=FALSE} vtree(ToothGrowth,"supp dose",summary="len>20 \n%pct% length > 20", labelvar=c("supp"="Supplement type","dose"="Dose (mg/day)"), labelnode=list(supp=c("Vitamin C"="VC","Orange Juice"="OJ"))) ```
/scratch/gouwar.j/cran-all/cranData/vtree/vignettes/vtree.Rmd
date_format_i <- function(x, qvalue=0.75, miss_values=NULL){ miss_str <- tolower(c(miss_values, 'NULL', 'NA', 'N/A', 'NaN', '-Inf', 'Inf', '', ' ', ' ')) monthstr <- "jan|feb|mrz|mar|apr|mai|may|jun|jul|aug|sep|okt|oct|nov|dez|dec" x <- tolower(as.character(x)) x[which(x%in%miss_str)] <- NA nc <- nchar(x[which(!is.na(x))]) x_num <- as.numeric(x) n <- sum(!is.na(x)) n5 <- round(n*0.05) probs <- c((1-qvalue)/2, (1-qvalue)/2+qvalue) pns <- quantile(nc, prob=probs, na.rm=TRUE) tren_1 <- length(grep('[-]', x, ignore.case = TRUE))>(n/2) tren_2 <- length(grep('[/]', x, ignore.case = TRUE))>(n/2) tren_3 <- length(grep('[.]', x, ignore.case = TRUE))>(n/2) tren_4 <- length(grep('[[:blank:]]', x, ignore.case = TRUE))>(n/2) tren_5 <- length(grep('[:]', x, ignore.case = TRUE))>(n/2) months_tx <- (sum(grepl(monthstr, x))>(n/2)) form <- '?' if(all(pns==4) & min(x_num, na.rm=TRUE)>1900 & max(x_num, na.rm=TRUE)<2035){ form<- "%Y" } if(all(pns==5) & tren_5 & !tren_1 & !tren_2 & !tren_3 & !tren_4){ form<- "H:M" } if(all(pns==8) & tren_5 & !tren_1 & !tren_2 & !tren_3 & !tren_4){ form<- "H:M:S" } if(all(pns==8) & !tren_5){ part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%d' if(part_1[1]<1 | part_1[2]>31) pf1 <- '%y' pf2 <- '%m' if(part_2[2]>12) pf2 <- '%d' if(part_2[2]>12 & pf1=='%d') pf1 <- '%m' pf3 <- '%y' if(pf1=='%y' & pf2=='%m') pf3 <- '%d' if(pf1=='%y' & pf2=='%d') pf3 <- '%m' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3) if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3) if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3) if(tren_4) form<- paste0(pf1,' ', pf2, ' ', pf3) } if(all(pns==9) & !months_tx){ part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%m' if(part_1[2]>12 & part_1[2]<=31) pf1 <- '%d' if(part_1[2]>31) pf1 <- '%Y' pf2 <- '%d' if(pf1=='%d') pf2 <- '%m' pf3 <- '%Y' if(pf1=='%Y' & pf2=='%m') pf3 <- '%d' if(pf1=='%Y' & pf2=='%d') pf3 <- '%m' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3) if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3) if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3) if(tren_4) form<- paste0(pf1,' ', pf2, ' ', pf3) } if((pns[1]==8 | pns[1]==9) & (pns[2]==9 | pns[2]==10) &!months_tx & !tren_5){ part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%m' if(part_1[2]>12 & part_1[2]<=31) pf1 <- '%d' if(part_1[2]>31) pf1 <- '%Y' pf2 <- '%d' if(pf1=='%d') pf2 <- '%m' pf3 <- '%Y' if(pf1=='%Y' & pf2=='%m') pf3 <- '%d' if(pf1=='%Y' & pf2=='%d') pf3 <- '%m' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3) if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3) if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3) if(tren_4) form<- paste0(pf1,' ', pf2, ' ', pf3) } if(all(pns==9) & months_tx & (tren_1 | tren_2 | tren_3 | tren_4)){ part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%d' if(part_1[2]>31 | part_1[1]<1) pf1 <- '%y' pf2 <- '%b' pf3 <- '%y' if(pf1=='%y') pf3 <- '%d' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3) if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3) if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3) if(tren_4) form<- paste0(pf1,' ', pf2, ' ', pf3) } if(all(pns==9) & months_tx & !tren_1 & !tren_2 & !tren_3 & !tren_4){ part_1 <- as.numeric(gsub('[a-z].*', '', x)) part_3 <- as.numeric(gsub('^.*[a-z]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%d' if(part_1[2]>31 | part_1[1]<1) pf1 <- '%Y' pf2 <- '%b' pf3 <- '%Y' if(pf1=='%Y') pf3 <- '%d' form<- paste0(pf1,'', pf2, '', pf3) } if(all(pns==10)){ part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%d' if(part_1[2]>31) pf1 <- '%Y' pf2 <- '%m' if(part_2[2]>12) pf2 <- '%d' if(part_2[2]>12 & pf1=='%d') pf1 <- '%m' pf3 <- '%Y' if(pf1=='%Y' & pf2=='%m') pf3 <- '%d' if(pf1=='%Y' & pf2=='%d') pf3 <- '%m' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3) if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3) if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3) if(tren_4) form<- paste0(pf1,' ', pf2, ' ', pf3) } if(all(pns==11) & months_tx){ part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) part_1[which(is.na(part_1))] <- -1 pf1 <- '%d' if(part_1[1]<0 & part_1[2]<0) pf1 <- '%b' if(part_1[2]>31) pf1 <- '%Y' pf2 <- '%b' if(pf1=='%b') pf2 <- '%d' pf3 <- '%Y' if(pf1=='%Y' & pf2=='%b') pf3 <- '%d' if(pf1=='%Y' & pf2=='%d') pf3 <- '%b' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3) if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3) if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3) if(tren_4) form<- paste0(pf1,' ', pf2, ' ', pf3) } if(all(pns==16) & tren_4 & tren_5){ x <- gsub('.{3}[:].*$', '', x) part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%d' if(part_1[2]>31) pf1 <- '%Y' pf2 <- '%m' if(part_2[2]>12) pf2 <- '%d' if(part_2[2]>12 & pf1=='%d') pf1 <- '%m' pf3 <- '%Y' if(pf1=='%Y' & pf2=='%m') pf3 <- '%d' if(pf1=='%Y' & pf2=='%d') pf3 <- '%m' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3, ' %H:%M') if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3, ' %H:%M') if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3, ' %H:%M') if(tren_4 & !tren_1 & !tren_2 & !tren_3) form<- paste0(pf1,' ', pf2, ' ', pf3, ' %H:%M') } if(all(pns==19) & tren_4 & tren_5){ x <- gsub('.{3}[:].*$', '', x) part_1 <- as.numeric(gsub('[-/.[:blank:]].*', '', x)) part_2 <- as.numeric(gsub('[-/.[:blank:]].*$', '', gsub('^.*?[-/.[:blank:]]', '', x))) part_3 <- as.numeric(gsub('^.*[-/.[:blank:]]', '', x)) part_1 <- quantile(part_1, prob=c(0.05, 0.95), na.rm=TRUE) part_2 <- quantile(part_2, prob=c(0.05, 0.95), na.rm=TRUE) part_3 <- quantile(part_3, prob=c(0.05, 0.95), na.rm=TRUE) pf1 <- '%d' if(part_1[2]>31) pf1 <- '%Y' pf2 <- '%m' if(part_2[2]>12) pf2 <- '%d' if(part_2[2]>12 & pf1=='%d') pf1 <- '%m' pf3 <- '%Y' if(pf1=='%Y' & pf2=='%m') pf3 <- '%d' if(pf1=='%Y' & pf2=='%d') pf3 <- '%m' if(tren_1) form<- paste0(pf1,'-', pf2, '-', pf3, ' %H:%M:%S') if(tren_2) form<- paste0(pf1,'/', pf2, '/', pf3, ' %H:%M:%S') if(tren_3) form<- paste0(pf1,'.', pf2, '.', pf3, ' %H:%M:%S') if(tren_4 & !tren_1 & !tren_2 & !tren_3) form<- paste0(pf1,' ', pf2, ' ', pf3, ' %H:%M:%S') } return(form) }
/scratch/gouwar.j/cran-all/cranData/vtype/R/date_format_i.R
postprocessing_data <- function(rf_model, agr_data, data, qvalue=0.75, miss_values=NULL){ miss_str <- tolower(c(miss_values, 'NULL', 'NA', 'N/A', 'NaN', '-Inf', 'Inf', '', ' ', ' ')) #################################### num_format <- function(x, qvalue=0.75){ x <- suppressWarnings(as.numeric(x)) x <- x[which(!is.na(x))] n <- length(x) sum_integer <- function(x){sum(x == round(x), na.rm = TRUE)} form <- 'floating' if((sum_integer(x)/n)>=qvalue) form <- 'integer' return(form) } #################################### #################################### binary_format <- function(x, miss_str=NULL){ x[which(x%in%miss_str)] <- NA x <- x[which(!is.na(x))] values <- substr(sort(names(sort(table(x), T))[1:2]), 1, 9) form <- paste0(values[1], '/', values[2]) return(form) } #################################### #################################### categ_format <- function(x, miss_str=NULL){ x[which(x%in%miss_str)] <- NA x <- x[which(!is.na(x))] nc <- nchar(unique(x)) form <- 'labels' if(all(nc<=2)){ x <- suppressWarnings(as.numeric(x)) form <- paste0(min(x, na.rm=TRUE), '-', max(x, na.rm=TRUE)) } return(form) } #################################### #################################### constant_format <- function(x, miss_str=NULL){ x[which(x%in%miss_str)] <- NA value <- unique(x[which(!is.na(x))])[1] form <- substr(value, 1, 9) if(nchar(value)>9) form <- paste(form, '.') return(form) } #################################### pred <- predict(rf_model, newdata=agr_data, type='prob') alternativ <- ptype <- prob <- formatx <- exampl <- rep(NA, nrow(pred)) vlevels <- colnames(pred) for(i in 1:nrow(pred)){ probas <- pred[i,] idm <- order(probas, decreasing=TRUE) ptype[i]<- vlevels[idm[1]] prob[i] <- probas[idm[1]] if(probas[idm[2]]>0.01) alternativ[i] <- paste0(vlevels[idm[2]], ' (', round(probas[idm[2]]*100, 1), '%)') if(probas[idm[2]]<=0.01) alternativ[i] <- '--' v <- tolower(as.character(data[, agr_data$vars[i]])) v <- gsub(',', '.', v, fixed=TRUE) formatx[i] <- '' if(ptype[i]=='date'){ suppressWarnings(try(formatx[i] <- date_format_i(v, qvalue, miss_str), silent = T)) } if(ptype[i]=='continuous'){ suppressWarnings(try(formatx[i] <- num_format(v, qvalue), silent = T)) } if(ptype[i]=='binary'){ suppressWarnings(try(formatx[i] <- binary_format(v, miss_str), silent = T)) } if(ptype[i]=='categorical'){ suppressWarnings(try(formatx[i] <- categ_format(v, miss_str), silent = T)) } if(ptype[i]=='constant'){ suppressWarnings(try(formatx[i] <- constant_format(v), silent = T)) } exampl[i] <- as.character(v[which(!is.na(v))][1]) } overclass <- '' overclass[which(ptype%in%c('missing', 'constant'))] <- 'uninformative' overclass[which(ptype%in%c('binary', 'categorical'))] <- 'qualitative' overclass[which(ptype%in%c('continuous'))] <- 'quantitative' overclass[which(ptype%in%c('date', 'ID', 'text'))] <- 'supportive' OUT <- data.frame(variable=agr_data$vars, type=ptype, probability=round(prob, 3), format=formatx, class=overclass, alternative=alternativ, n=agr_data$n, missings=agr_data$missings) return(OUT) }
/scratch/gouwar.j/cran-all/cranData/vtype/R/postprocessing_data.R
preprocessing_data <- function(data, qvalue=0.75, miss_values=NULL){ ################################# get_dat_p <- function(x, qvalue, miss_values){ out <- rep(NA, 20) check_integer <- function(x){x == round(x)} probs <- c((1-qvalue)/2, (1-qvalue)/2+qvalue) monthstr <- "jan|feb|mrz|mar|apr|mai|may|jun|jul|aug|sep|okt|oct|nov|dez|dec" miss_str <- tolower(c(miss_values, 'NULL', 'NA', 'N/A', 'N A', 'NaN', '-Inf', 'Inf', '', ' ', ' ')) yearstr <- paste0(192:203, collapse='[0-9]{1}([^0-9]|$)|') x <- tolower(as.character(x)) x <- gsub(',', '.', x, fixed=TRUE) x[which(x%in%miss_str)] <- NA nall <- length(x) n <- sum(!is.na(x)) nmiss <- sum(is.na(x)) nchars<- nchar(x) x_num <- as.numeric(x) x_ppm <- as.numeric(gsub('[^.0-9]*', '', x)) maxid <- (max(x_ppm, na.rm=TRUE)-min(x_ppm, na.rm=TRUE)+1) nnum <- sum(!is.na(x_num)) ints <- sum(check_integer(x_num), na.rm=TRUE) ints2 <- sum(check_integer(x_ppm), na.rm=TRUE) lagnum<- diff(sort(x_ppm)) lagnum[which(lagnum>100)]<- 100 luniq <- length(unique(x[which(!is.na(x))])) yearss_tx <- sum(grepl(yearstr, x)) months_tx <- sum(grepl(monthstr, x)) letter_tx <- length(grep('[a-z]', x, ignore.case = TRUE)) number_tx <- length(grep('[0-9]', x, ignore.case = TRUE)) #points_tx <- unlist(lapply(gregexpr('[.]', x), FUN=function(x){length(x[which(x>0)])})) #trenns_tx <- unlist(lapply(gregexpr('[-:_/ ]', x), FUN=function(x){length(x[which(x>0)])})) out[1] <- n out[2] <- nmiss out[3] <- as.numeric(luniq==2) out[4] <- luniq/n out[5] <- as.numeric(luniq>2 & luniq<=12) out[6] <- as.numeric(luniq==1) out[7] <- nnum/n out[8] <- yearss_tx/n out[9] <- number_tx/n out[10] <- ints2/n out[11] <- as.numeric(n==0) out[12] <- as.numeric(luniq==n) out[13] <- letter_tx/n out[14] <- as.numeric(all(quantile(lagnum, probs, na.rm=TRUE)==1)) out[15] <- ints/n out[16] <- as.numeric(quantile(nchars, probs[1], na.rm=TRUE)==quantile(nchars, probs[2], na.rm=TRUE)) out[17] <- as.numeric(maxid>=nall & maxid<(nall+round(nall*0.05))) out[18] <- as.numeric(min(x_num, na.rm=TRUE)%in%c(0, 1)) out[19] <- mad(nchars, na.rm=TRUE) out[20] <- months_tx/n #out[21] <- as.numeric(all(quantile(points_tx, probs, na.rm=TRUE)==1)) #out[22] <- as.numeric(all(quantile(trenns_tx, probs, na.rm=TRUE)==2)) return(out) } ######################################################################### M <- t(apply(data, MARGIN=2, FUN=get_dat_p, qvalue=qvalue, miss_values=miss_values)) M[which(is.na(M), arr.ind = T)] <- 0 M[which(!is.finite(M), arr.ind = T)] <- 0 colnames(M)<-c('n', 'missings', 'binarity', 'uniqueness', 'categorical', 'constant', 'numeric', 'years', 'numbers', 'subintegers', 'allmiss', 'alluniq', 'letters', 'lag1', 'integer', 'nchar_stabl', 'range', 'start', 'nchar_mad', 'months') vars <-names(data) M2 <-data.frame(vars, M) return(M2) }
/scratch/gouwar.j/cran-all/cranData/vtype/R/preprocessing_data.R
vtype <-function(data, qvalue=0.75, miss_values=NULL){ if(class(data)!='data.frame') stop('data must be a data.frame') if(!is.numeric(qvalue)) stop('qvalue must be a numeric value from [0.1, 1.0]') if(qvalue<0.1) warning('qvalue below 0.1 are not allowed, it was set to 0.1!') if(qvalue>1.0) warning('qvalue above 1.0 are not allowed, it was set to 1.0!') miss_values <- as.character(miss_values) if(!is.vector(miss_values)) stop('miss_values must be a character vector or single string') aggregated <- suppressWarnings(preprocessing_data(data, qvalue=qvalue, miss_values=miss_values)) OUT <- postprocessing_data(fitted_model_rf, agr_data=aggregated, data=data, qvalue=qvalue, miss_values=miss_values) return(OUT) }
/scratch/gouwar.j/cran-all/cranData/vtype/R/vtype.R
## ---- echo=FALSE, warning=FALSE, message=FALSE-------------------------------- library(knitr) library(vtype) ## ---- results='asis'---------------------------------------------------------- knitr::kable(head(sim_nqc_data, 20), caption='Artificial not quality controlled data') ## ---- results='asis'---------------------------------------------------------- tab <- vtype(sim_nqc_data, miss_values='9999') knitr::kable(tab, caption='Application example of vtype') ## ---- results='asis'---------------------------------------------------------- knitr::kable(vtype(sim_nqc_data[1:10,]), caption='Application example with small sample size') ## ---- results='asis'---------------------------------------------------------- knitr::kable(vtype(mtcars), caption='Application example on data without errors')
/scratch/gouwar.j/cran-all/cranData/vtype/inst/doc/vignette.R
--- title: "Application example" author: "Andreas Schulz" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Application example} %\VignetteEngine{knitr::rmarkdown} %\usepackage[utf8]{inputenc} --- ```{r, echo=FALSE, warning=FALSE, message=FALSE} library(knitr) library(vtype) ``` ## Introduction The purpose of the package is automatically detecting type of variables in not quality controlled data. The prediction is based on a pre-trained random forest model, trained on over 5000 medical variables with OOB accuracy of 99%. The accuracy depends heavily on the type and coding style of data. For example, often categorical variables are coded as integers 1 to x, if the number of categories is very large, there is no way to distinguish it from a continuous integer variable. Some types are per definition very sensitive to errors in data, like ID, missing or constant, where a single alternative non-missing value makes it not constant or not missing anymore. The data is assumed to be cross sectional, where ID is unique (no multiple entries per ID). It can be used as a first step by data quality control to help sort the variables in advance and get some information about the possible formats. ## Example data set The data set 'sim_nqc_data' contains 100 observations and 14 artificial variables with some not well formatted or missing values. The data is complete artificial and was not used for training or validation of the random forest model. ```{r, results='asis'} knitr::kable(head(sim_nqc_data, 20), caption='Artificial not quality controlled data') ``` ## Application ### An example on error afflicted data The application is straightforward, it requires data in data.frame format. It is important that all unusual missing values in the data, e.g. the code 9999 for missing values are covered. Values as NA, NaN, Inf, NULL and spaces are automatic considered as invalid (missing) values. The second column `type` is the estimated type of the variable, and the column `probability` indicates how certain the type is. The `format` gives additional information about the possible format of the variable, especially useful for date variables. `Class` is just a translation of type into broader categories. ```{r, results='asis'} tab <- vtype(sim_nqc_data, miss_values='9999') knitr::kable(tab, caption='Application example of vtype') ``` ### An example with very small sample size Very small sample size can reduce the prediction performance significantly. The `id` variable is now detected as integer, `age` as categorical and `decades` as a date variable. ```{r, results='asis'} knitr::kable(vtype(sim_nqc_data[1:10,]), caption='Application example with small sample size') ``` ### An example on data without errors ```{r, results='asis'} knitr::kable(vtype(mtcars), caption='Application example on data without errors') ```
/scratch/gouwar.j/cran-all/cranData/vtype/inst/doc/vignette.Rmd
--- title: "Application example" author: "Andreas Schulz" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Application example} %\VignetteEngine{knitr::rmarkdown} %\usepackage[utf8]{inputenc} --- ```{r, echo=FALSE, warning=FALSE, message=FALSE} library(knitr) library(vtype) ``` ## Introduction The purpose of the package is automatically detecting type of variables in not quality controlled data. The prediction is based on a pre-trained random forest model, trained on over 5000 medical variables with OOB accuracy of 99%. The accuracy depends heavily on the type and coding style of data. For example, often categorical variables are coded as integers 1 to x, if the number of categories is very large, there is no way to distinguish it from a continuous integer variable. Some types are per definition very sensitive to errors in data, like ID, missing or constant, where a single alternative non-missing value makes it not constant or not missing anymore. The data is assumed to be cross sectional, where ID is unique (no multiple entries per ID). It can be used as a first step by data quality control to help sort the variables in advance and get some information about the possible formats. ## Example data set The data set 'sim_nqc_data' contains 100 observations and 14 artificial variables with some not well formatted or missing values. The data is complete artificial and was not used for training or validation of the random forest model. ```{r, results='asis'} knitr::kable(head(sim_nqc_data, 20), caption='Artificial not quality controlled data') ``` ## Application ### An example on error afflicted data The application is straightforward, it requires data in data.frame format. It is important that all unusual missing values in the data, e.g. the code 9999 for missing values are covered. Values as NA, NaN, Inf, NULL and spaces are automatic considered as invalid (missing) values. The second column `type` is the estimated type of the variable, and the column `probability` indicates how certain the type is. The `format` gives additional information about the possible format of the variable, especially useful for date variables. `Class` is just a translation of type into broader categories. ```{r, results='asis'} tab <- vtype(sim_nqc_data, miss_values='9999') knitr::kable(tab, caption='Application example of vtype') ``` ### An example with very small sample size Very small sample size can reduce the prediction performance significantly. The `id` variable is now detected as integer, `age` as categorical and `decades` as a date variable. ```{r, results='asis'} knitr::kable(vtype(sim_nqc_data[1:10,]), caption='Application example with small sample size') ``` ### An example on data without errors ```{r, results='asis'} knitr::kable(vtype(mtcars), caption='Application example on data without errors') ```
/scratch/gouwar.j/cran-all/cranData/vtype/vignettes/vignette.Rmd
calculate.absmax <- function (differences.quantile) { differences.quantile.abs <- abs(differences.quantile) differences.quantile.abs[differences.quantile.abs == Inf] <- 0 absmax <- max(differences.quantile.abs) return(absmax) }
/scratch/gouwar.j/cran-all/cranData/vudc/R/calculate.absmax.R
calculate.quantiles <- function (differences, remove.ratio) { quantiles <- seq(remove.ratio, 1 - remove.ratio, 0.01) differences.sorted <- sort(differences) indices <- floor(quantiles * length(differences.sorted)) + 1 indices[length(indices)] = indices[length(indices) - 1] differences.quantile <- differences.sorted[indices] return(differences.quantile) }
/scratch/gouwar.j/cran-all/cranData/vudc/R/calculate.quantiles.R
calculate.sortsum <- function (vector.unsorted) { vector.sorted <- sort(vector.unsorted, TRUE) vector.sorted.sum <- c() vector.sorted.sum[1] <- 0 for (i in 1:length(vector.sorted)) { vector.sorted.sum[i + 1] <- sum(vector.sorted[1:i]) } return(vector.sorted.sum) }
/scratch/gouwar.j/cran-all/cranData/vudc/R/calculate.sortsum.R
ccdplot <- function (x, remove.absolute = NA, remove.ratio = NA, drawcomposite = TRUE, jump = NA, xlab = "Observations", ylab = "Cumulatives", ...) { check.remove.params(remove.absolute, remove.ratio) if (!is.list(x)) { x.removed <- remove.vector(x, remove.absolute, remove.ratio) x.sortsum <- calculate.sortsum(x.removed) plot(1:length(x.sortsum), x.sortsum, type = "l", xlab = xlab, ylab = ylab, ...) abline(h = 0, lty = "dotted") } else { x.removed <- remove.list(x, remove.absolute, remove.ratio) characteristics.number <- length(x.removed) x.composite <- c() x.sortsum <- list() absoluteMin <- Inf absoluteMax <- -Inf for (i in 1:characteristics.number) { x.sortsum[[i]] <- calculate.sortsum(x.removed[[i]]) x.composite <- c(x.composite, x.removed[[i]]) actualMin <- min(x.sortsum[[i]]) if (!is.na(actualMin) && actualMin < absoluteMin) { absoluteMin <- actualMin } actualMax <- max(x.sortsum[[i]]) if (!is.na(actualMax) && actualMax > absoluteMax) { absoluteMax <- actualMax } } x.composite.sortsum <- calculate.sortsum(x.composite) actualMin <- min(x.composite.sortsum) if (actualMin < absoluteMin) { absoluteMin <- actualMin } actualMax <- max(x.composite.sortsum) if (actualMax > absoluteMax) { absoluteMax <- actualMax } if (is.na(jump)) { jump <- length(x.composite.sortsum)/50 } xmax <- length(x.composite.sortsum) if (!drawcomposite) { xmax <- xmax + (characteristics.number - 1) * jump } plot(c(1, xmax), c(absoluteMin, absoluteMax), xlab = xlab, ylab = ylab, type = "n", ...) abline(h = 0, lty = "dotted") cumulativeLength <- 0 loopend <- characteristics.number if (drawcomposite) { points(1:length(x.composite.sortsum), x.composite.sortsum, type = "l", ...) loopend <- loopend - 1 } for (i in 1:loopend) { x.from <- i * jump + 1 + cumulativeLength x.to <- i * jump + cumulativeLength + length(x.sortsum[[i]]) if (!drawcomposite) { x.from <- x.from - jump x.to <- x.to - jump } points(x.from:x.to, x.sortsum[[i]], type = "l", ...) cumulativeLength <- cumulativeLength + length(x.sortsum[[i]]) } if (drawcomposite) { points((-jump + 1 + cumulativeLength):(-jump + cumulativeLength + length(x.sortsum[[characteristics.number]])), x.sortsum[[characteristics.number]], type = "l", ...) } } }
/scratch/gouwar.j/cran-all/cranData/vudc/R/ccdplot.R
check.remove.params <- function (remove.absolute, remove.ratio) { if (!is.na(remove.absolute) && !is.na(remove.ratio)) { stop("At least one of remove.absolute and remove.ratio should be NA.") } if (!is.na(remove.ratio) && (remove.ratio < 0 || remove.ratio >= 0.5)) { stop("The remove.ratio should take value in range [0, 0.5).") } if (!is.na(remove.absolute) && (remove.absolute <= 0)) { stop("The remove.absolute should take value greater than 0.0.") } }
/scratch/gouwar.j/cran-all/cranData/vudc/R/check.remove.params.R
qddplot <- function (x, y, remove.ratio = 0.1, differences.range = NA, differences.rangemin = 10, differences.drawzero = TRUE, quantiles.drawhalf = TRUE, quantiles.showaxis = TRUE, line.lwd = 5, xlab = "Quantile", ylab = "Difference", main = "Quantile Differences", ...) { if (remove.ratio < 0 || remove.ratio >= 0.5) { stop("Parameter remove.ratio should be fall into range [0, 0.5).") } differences.quantile <- calculate.quantiles(x, remove.ratio) - calculate.quantiles(y, remove.ratio) if (is.na(differences.range)) { differences.range <- calculate.absmax(differences.quantile) } if (!is.na(differences.rangemin)) { if (differences.range < differences.rangemin) { differences.range = differences.rangemin } } plot(c(1, 101 - 2 * 100 * remove.ratio), c(-differences.range, differences.range), type = "n", lty = 0, xaxt = "n", xlab = xlab, ylab = ylab, main = main, ...) points(differences.quantile, type = "l", lwd = line.lwd, ...) if (differences.drawzero) { abline(0, 0, lty = "dotted") } if (quantiles.drawhalf) { abline(v = 51 - 100 * remove.ratio, lty = "dashed") } if (quantiles.showaxis) { if (remove.ratio < 0.2) { axis(side = 1, at = seq(1 - 100 * remove.ratio, 101 - 100 * remove.ratio, 10), labels = seq(0, 1, 0.1)) } else if (remove.ratio < 45) { axis(side = 1, at = seq(1 - 100 * remove.ratio, 101 - 100 * remove.ratio, 5), labels = seq(0, 1, 0.05)) } else { axis(side = 1, at = seq(1 - 100 * remove.ratio, 101 - 100 * remove.ratio, 1), labels = seq(0, 1, 0.01)) } } }
/scratch/gouwar.j/cran-all/cranData/vudc/R/qddplot.R
remove.list <- function (x, remove.absolute, remove.ratio) { x.removed <- x if (!is.na(remove.absolute)) { x.removed <- list() for (i in 1:length(x)) { x.actual <- x[[i]] x.removed[[i]] <- x.actual[abs(x.actual) < remove.absolute] } } else if (!is.na(remove.ratio)) { x.composite <- c() for (i in 1:length(x)) { x.composite <- c(x.composite, x[[i]]) } x.lowerquantile <- quantile(x.composite, remove.ratio)[[1]] x.upperquantile <- quantile(x.composite, 1 - remove.ratio)[[1]] x.removed <- list() for (i in 1:length(x)) { x.column <- x[[i]] x.removed[[i]] <- x.column[(x.lowerquantile < x.column) & (x.column < x.upperquantile)] } } return(x.removed) }
/scratch/gouwar.j/cran-all/cranData/vudc/R/remove.list.R
remove.vector <- function (x, remove.absolute, remove.ratio) { x.removed <- x if (!is.na(remove.absolute)) { x.removed <- x[abs(x) < remove.absolute] } else if (!is.na(remove.ratio)) { x.lowerquantile <- quantile(x, remove.ratio) x.upperquantile <- quantile(x, 1 - remove.ratio) x.removed <- x[(x.lowerquantile[[1]] < x) & (x < x.upperquantile[[1]])] } return(x.removed) }
/scratch/gouwar.j/cran-all/cranData/vudc/R/remove.vector.R
#' Dependencies for Vue #' #' @param offline \code{logical} to use local file dependencies. If \code{FALSE}, #' then the dependencies use cdn as its \code{src}. #' @param minified \code{logical} to use minified (production) version. Use #' \code{minified = FALSE} for debugging or working with Vue devtools. #' #' @return \code{\link[htmltools]{htmlDependency}} #' @importFrom htmltools htmlDependency #' @family dependencies #' @export #' #' @examples #' if(interactive()){ #' #' library(vueR) #' library(htmltools) #' #' attachDependencies( #' tagList( #' tags$div(id="app","{{message}}"), #' tags$script( #' " #' var app = new Vue({ #' el: '#app', #' data: { #' message: 'Hello Vue!' #' } #' }); #' " #' ) #' ), #' html_dependency_vue() #' ) #' } html_dependency_vue <- function(offline=TRUE, minified=TRUE){ hd <- htmltools::htmlDependency( name = "vue", version = vue_version(), src = system.file("www/vue/dist",package="vueR"), script = "vue.min.js" ) if(!minified) { hd$script <- "vue.js" } if(!offline) { hd$src <- list(href=sprintf( "https://unpkg.com/vue@%s/dist/", vue_version() )) } hd } #' Dependencies for 'Vue3' #' #' @param offline \code{logical} to use local file dependencies. If \code{FALSE}, #' then the dependencies use cdn as its \code{src}. #' @param minified \code{logical} to use minified (production) version. Use #' \code{minified = FALSE} for debugging or working with Vue devtools. #' #' @return \code{\link[htmltools]{htmlDependency}} #' @importFrom htmltools htmlDependency #' @family dependencies #' @export #' #' @examples #' if(interactive()){ #' #' library(vueR) #' library(htmltools) #' #' browsable( #' tagList( #' tags$div(id="app","{{message}}"), #' tags$script( #' " #' var app = { #' data: function() { #' return { #' message: 'Hello Vue!' #' } #' } #' }; #' #' Vue.createApp(app).mount('#app'); #' " #' ), #' html_dependency_vue3() #' ) #' ) #' } html_dependency_vue3 <- function(offline=TRUE, minified=TRUE){ hd <- htmltools::htmlDependency( name = "vue", version = vue3_version(), src = system.file("www/vue3/dist",package="vueR"), script = "vue.global.prod.js" ) if(!minified) { hd$script <- "vue.global.js" } if(!offline) { hd$src <- list(href=sprintf( "https://unpkg.com/vue@%s/dist/", vue3_version() )) } hd }
/scratch/gouwar.j/cran-all/cranData/vueR/R/dependencies.R
#'@keywords internal vue_version <- function(){'2.7.14'} #'@keywords internal vue3_version <- function(){'3.3.4'}
/scratch/gouwar.j/cran-all/cranData/vueR/R/meta.R
#' 'Vue.js' 'htmlwidget' #' #' Use 'Vue.js' with the convenience and flexibility of 'htmlwidgets'. #' \code{vue} is a little different from other 'htmlwidgets' though #' since it requires specification of the HTML tags/elements separately. #' #' @param app \code{list} with \code{el} and \code{data} and other pieces #' of a 'Vue.js' app #' @param width,height any valid \code{CSS} size unit, but in reality #' this will not currently have any impact #' @param elementId \code{character} id of the htmlwidget container #' element #' @param minified \code{logical} to indicate minified (\code{minified=TRUE}) or #' non-minified (\code{minified=FALSE}) Vue.js #' #' @import htmlwidgets #' #' @family htmlwidget #' @export #' @example ./inst/examples/vue_widget_examples.R #' @return vue htmlwidget vue <- function( app = list(), width = NULL, height = NULL, elementId = NULL, minified = TRUE ) { # forward options using x x = app # create widget hw <- htmlwidgets::createWidget( name = 'vue', x, width = width, height = height, package = 'vueR', elementId = elementId ) hw$dependencies <- list( html_dependency_vue(offline=TRUE, minified=minified) ) hw } #' 'Vue.js 3' 'htmlwidget' #' #' Use 'Vue.js 3' with the convenience and flexibility of 'htmlwidgets'. #' \code{vue3} is a little different from other 'htmlwidgets' though #' since it requires specification of the HTML tags/elements separately. #' #' @param app \code{list} with \code{el} and \code{data} and other pieces #' of a 'Vue.js 3' app #' @param width,height any valid \code{CSS} size unit, but in reality #' this will not currently have any impact #' @param elementId \code{character} id of the htmlwidget container #' element #' @param minified \code{logical} to indicate minified (\code{minified=TRUE}) or #' non-minified (\code{minified=FALSE}) Vue.js #' #' @import htmlwidgets #' #' @family htmlwidget #' @export #' @example ./inst/examples/vue3_widget_examples.R #' @return vue htmlwidget vue3 <- function( app = list(), width = NULL, height = NULL, elementId = NULL, minified = TRUE ) { # forward options using x x = app # will try to convert data that is not a function in widget JS # create widget hw <- htmlwidgets::createWidget( name = 'vue3', x, width = width, height = height, package = 'vueR', elementId = elementId ) hw$dependencies <- list( html_dependency_vue3(offline=TRUE, minified=minified) ) hw } #' Shiny bindings for vue #' #' Output and render functions for using vue within Shiny #' applications and interactive Rmd documents. #' #' @param outputId output variable to read from #' @param width,height Must be a valid CSS unit (like \code{'100\%'}, #' \code{'400px'}, \code{'auto'}) or a number, which will be coerced to a #' string and have \code{'px'} appended. #' @param expr An expression that generates a vue #' @param env The environment in which to evaluate \code{expr}. #' @param quoted Is \code{expr} a quoted expression (with \code{quote()})? This #' is useful if you want to save an expression in a variable. #' #' @name vue-shiny #' #' @export #' @example ./inst/examples/vue3_shiny_examples.R vueOutput <- function(outputId, width = '100%', height = '400px'){ htmlwidgets::shinyWidgetOutput(outputId, 'vue', width, height, package = 'vueR') } #' @rdname vue-shiny #' @export renderVue <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted htmlwidgets::shinyRenderWidget(expr, vueOutput, env, quoted = TRUE) } #' Shiny bindings for 'vue 3' #' #' Output and render functions for using 'vue 3' within Shiny #' applications and interactive Rmd documents. #' #' @param outputId output variable to read from #' @param width,height Must be a valid CSS unit (like \code{'100\%'}, #' \code{'400px'}, \code{'auto'}) or a number, which will be coerced to a #' string and have \code{'px'} appended. #' @param expr An expression that generates a vue #' @param env The environment in which to evaluate \code{expr}. #' @param quoted Is \code{expr} a quoted expression (with \code{quote()})? This #' is useful if you want to save an expression in a variable. #' #' @name vue-shiny #' #' @export vue3Output <- function(outputId, width = '100%', height = '400px'){ htmlwidgets::shinyWidgetOutput(outputId, 'vue3', width, height, package = 'vueR') } #' @rdname vue-shiny #' @export renderVue3 <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted htmlwidgets::shinyRenderWidget(expr, vueOutput, env, quoted = TRUE) }
/scratch/gouwar.j/cran-all/cranData/vueR/R/vue.R
# use the very nice rgithub; still works but abandoned # remotes::install_github("cscheid/rgithub") get_vue_latest <- function(){ gsub( x=github::get.latest.release("vuejs", "vue")$content$tag_name, pattern="v", replacement="" ) } get_vue3_latest <- function(){ gsub( x=github::get.latest.release("vuejs", "core")$content$tag_name, pattern="v", replacement="" ) } # get newest vue2 download.file( url=sprintf( "https://unpkg.com/vue@%s/dist/vue.min.js", get_vue_latest() ), destfile="./inst/www/vue/dist/vue.min.js" ) download.file( url=sprintf( "https://unpkg.com/vue@%s/dist/vue.js", get_vue_latest() ), destfile="./inst/www/vue/dist/vue.js" ) # get newest vue3 download.file( url=sprintf( "https://unpkg.com/vue@%s/dist/vue.global.prod.js", get_vue3_latest() ), destfile="./inst/www/vue3/dist/vue.global.prod.js" ) download.file( url=sprintf( "https://unpkg.com/vue@%s/dist/vue.global.js", get_vue3_latest() ), destfile="./inst/www/vue3/dist/vue.global.js" ) # write function with newest version # for use when creating dependencies cat( sprintf( "#'@keywords internal\nvue_version <- function(){'%s'}\n#'@keywords internal\nvue3_version <- function(){'%s'}\n", get_vue_latest(), get_vue3_latest() ), file = "./R/meta.R" )
/scratch/gouwar.j/cran-all/cranData/vueR/build/getvue.R
--- title: "Intro to vueR" author: "Kenton Russell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Intro to vueR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- All the awesomeness of [Vue.js](https://vuejs.org) is available in `R` with `vueR`. We will work through some of the examples to give you a feel for both `Vue.js` and how to incorporate this powerful binding framework in your `R` workflows.
/scratch/gouwar.j/cran-all/cranData/vueR/inst/doc/intro_to_vueR.Rmd
if(interactive()) { library(shiny) library(vueR) ui <- tagList( tags$div(id="app-3", tags$p("v-if"="seen", "Now you see me") ), vue3Output('vue1') ) server <- function(input, output, session) { output$vue1 <- renderVue3({ vue3( list( el = '#app-3', data = list(seen = TRUE), mounted = htmlwidgets::JS(" function() { var that = this; setInterval(function(){that.seen=!that.seen},1000); } "), watch = list( seen = htmlwidgets::JS("function() {Shiny.setInputValue('seen',this.seen)}") ) ) ) }) # show that Shiny input value is being updated observeEvent(input$seen, {print(input$seen)}) } shinyApp(ui, server) }
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue3_shiny_examples.R
if(interactive()) { library(vueR) library(htmltools) # recreate Hello Vue! example browsable( tagList( tags$div(id="app", "{{message}}"), vue3( list( el = "#app", # vue 3 is more burdensome but robust requiring data as function # if data is not a function then widget will auto-convert data = list(message = "Hello Vue3!") # data = htmlwidgets::JS(" # function() {return {message: 'Hello Vue3!'}} # ") ) ) ) ) # app2 from Vue.js introduction browsable( tagList( tags$div(id="app-2", tags$span( "v-bind:title" = "message", "Hover your mouse over me for a few seconds to see my dynamically bound title!" ) ), vue3( list( el = "#app-2", # vue 3 is more burdensome but robust requiring data as function # if data is not a function then widget will auto-convert data = htmlwidgets::JS(" function() { return {message: 'You loaded this page on ' + new Date()} } ") ) ) ) ) # app3 from Vue.js introduction # with a setInterval to toggle seen true and false browsable( tagList( tags$div(id="app-3", tags$p("v-if"="seen", "Now you see me") ), vue3( list( el = '#app-3', data = list(seen = TRUE), # data = htmlwidgets::JS("function() {return {seen: true}}"), mounted = htmlwidgets::JS(" function() { var that = this; setInterval(function(){that.seen=!that.seen},1000); } ") ) ) ) ) }
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue3_widget_examples.R
library(htmltools) library(vueR) #### Mint examples ####################################### mint <- htmlDependency( name = "mint-ui", version = "2.0.5", src = c(href="https://unpkg.com/mint-ui/lib"), script = "index.js", stylesheet = "style.css" ) tl <- tagList( tags$script("Vue.use(MINT)"), tags$div( id="app", tag("mt-switch",list("v-model"="value","{{value ? 'on' : 'off'}}")), tag( "mt-checklist", list( title="checkbox list", "v-model"="checkbox_value", ":options"="['Item A', 'Item B', 'Item C']" ) ) ), vue(list(el="#app",data=list(value=TRUE, checkbox_value=list()))) ) browsable( attachDependencies( tl, mint ) ) #### Element examples #################################### element <- htmlDependency( name = "element", version = "2.13.2", src = c(href="https://unpkg.com/[email protected]/lib/"), script = "index.js", stylesheet = "theme-chalk/index.css" ) tl <- tagList( tags$script(" ELEMENT.locale({ el: { colorpicker: { confirm: 'OK', clear: 'Clear' }, datepicker: { now: 'Now', today: 'Today', cancel: 'Cancel', clear: 'Clear', confirm: 'OK', selectDate: 'Select date', selectTime: 'Select time', startDate: 'Start Date', startTime: 'Start Time', endDate: 'End Date', endTime: 'End Time', prevYear: 'Previous Year', nextYear: 'Next Year', prevMonth: 'Previous Month', nextMonth: 'Next Month', year: '', month1: 'January', month2: 'February', month3: 'March', month4: 'April', month5: 'May', month6: 'June', month7: 'July', month8: 'August', month9: 'September', month10: 'October', month11: 'November', month12: 'December', week: 'week', weeks: { sun: 'Sun', mon: 'Mon', tue: 'Tue', wed: 'Wed', thu: 'Thu', fri: 'Fri', sat: 'Sat' }, months: { jan: 'Jan', feb: 'Feb', mar: 'Mar', apr: 'Apr', may: 'May', jun: 'Jun', jul: 'Jul', aug: 'Aug', sep: 'Sep', oct: 'Oct', nov: 'Nov', dec: 'Dec' } }, select: { loading: 'Loading', noMatch: 'No matching data', noData: 'No data', placeholder: 'Select' }, cascader: { noMatch: 'No matching data', loading: 'Loading', placeholder: 'Select', noData: 'No data' }, pagination: { goto: 'Go to', pagesize: '/page', total: 'Total {total}', pageClassifier: '' }, messagebox: { title: 'Message', confirm: 'OK', cancel: 'Cancel', error: 'Illegal input' }, upload: { deleteTip: 'press delete to remove', delete: 'Delete', preview: 'Preview', continue: 'Continue' }, table: { emptyText: 'No Data', confirmFilter: 'Confirm', resetFilter: 'Reset', clearFilter: 'All', sumText: 'Sum' }, tree: { emptyText: 'No Data' }, transfer: { noMatch: 'No matching data', noData: 'No data', titles: ['List 1', 'List 2'], // to be translated filterPlaceholder: 'Enter keyword', // to be translated noCheckedFormat: '{total} items', // to be translated hasCheckedFormat: '{checked}/{total} checked' // to be translated }, image: { error: 'FAILED' }, pageHeader: { title: 'Back' // to be translated }, popconfirm: { confirmButtonText: 'Yes', cancelButtonText: 'No' } } }) "), tags$div( id="app", tags$span("Slider With Breakpoints Displayed"), tag( "el-slider", list( "v-model"="value5", ":step"=10, "show-stops" = NA ) ), tags$span("Time Picker"), tag( "el-time-select", list( "v-model"="value_time", ":picker-options"="{ start: '08:30', step: '00:15', end: '18:30' }", "placeholder"="Select time" ) ), tags$span("Date Picker"), tag( "el-date-picker", list( "v-model"="value_date", type="date", placeholder="Pick a day" ) ) ), vue(list(el="#app",data=list(value5=0, value_time=NULL, value_date=NULL))) ) browsable( attachDependencies( tl, list( element ) ) ) rhd <- treemap::random.hierarchical.data() tl_tree <- tagList( tags$div( id = "app", tag( "el-tree", list( "ref" = "mytree", ":data" = "data.children", ":props" = "defaultProps", "show-checkbox" = NA, "@check-change" = "handleCheckChange" ) ), tags$pre("{{checkedNodes.map(function(d){return d.name})}}") ), vue( list( el="#app", data = list( data = d3r::d3_nest( rhd, value_cols="x" ), defaultProps = list( 'children' = 'children', 'label' = 'name' ), checkedNodes = list() ), methods = list( handleCheckChange = htmlwidgets::JS( " function(data, checked, indeterminate){ //debugger; //data.checked = checked && !indeterminate; console.log(data, checked, indeterminate); this.checkedNodes = this.$refs.mytree.getCheckedNodes(); this.$emit('tree-checked'); } " ) ) ), minified = FALSE ) ) browsable( attachDependencies( tl_tree, list( element ) ) ) # add a d3 tree and make it respond to Vue tree d3t <- networkD3::diagonalNetwork( jsonlite::fromJSON( d3r::d3_nest( rhd, value_cols="x" ), simplifyVector=FALSE, simplifyDataFrame=FALSE ) ) # use onRender to add event handling d3t <- htmlwidgets::onRender( d3t, " function(el, x) { var vue_tree = HTMLWidgets.find('.vue').instance; vue_tree.$on( 'tree-checked', function() { var myvue = this; var checkedNodes = myvue.checkedNodes.map(function(d){return d.name}); var nodes = d3.select(el).selectAll('g.node'); debugger; nodes.each(function(d) { if(checkedNodes.indexOf(d.data.name) > -1){ d3.select(this).select('circle').style('fill', 'gray'); } else { d3.select(this).select('circle').style('fill', 'rgb(255,255,255)'); }; }) } ) } " ) browsable( attachDependencies( tagList( tags$div(tl_tree,style="width:20%; float:left; display:block;"), tags$div(d3t,style="width:70%; float:left; display:block;") ), list( element ) ) )
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_component_examples.R
library(vueR) library(d3r) library(treemap) library(htmltools) hier_dat <- treemap::random.hierarchical.data() hier_json <- d3r::d3_nest( hier_dat, value_cols = "x" ) library(dplyr) hier_json <- hier_dat %>% treemap(index = c("index1", "index2", "index3"), vSize = "x") %>% {.$tm} %>% select(index1:index3,vSize, color) %>% rename(size = vSize) %>% d3_nest(value_cols = c("size", "color")) d2b_dep <- htmltools::htmlDependency( name = "d2b", version = "0.0.24", src = c(href = "https://unpkg.com/[email protected]/build/"), script = "d2b.min.js" ) browsable(tagList( html_dependency_vue(), d3r::d3_dep_v4(), d2b_dep, tags$div( id = "app", style = "height:400px", tag( "sunburst-chart", list(":data" = "sunburstChartData", ":config" = "sunburstChartConfig" ) )), tags$script(HTML( sprintf( " var app = new Vue({ el: '#app', components: { 'sunburst-chart': d2b.vueChartSunburst }, data: { sunburstChartData: %s, sunburstChartConfig: function(chart) { var color = d3.scaleOrdinal(d3.schemeCategory20c); chart.label(function(d){return d.name}); //chart.sunburst().size(function(d){return d.x}); //chart.color(function(d){return color(d.name);}) chart.color(function(d){return typeof(d.color) === 'undefined' ? '#BBB' : d.color; }) } } }) ", hier_json ) )) ))
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_d2b_examples.R
library(shiny) library(treemap) library(d3r) d2b_dep <- htmltools::htmlDependency( name = "d2b", version = "0.0.24", src = c(href = "https://unpkg.com/[email protected]/build/"), script = "d2b.min.js" ) ui <- tagList( # set up a div that will show state tags$div( id = "app", style = "height:400px", tag( "sunburst-chart", list(":data" = "sunburstChartData.data", ":config" = "sunburstChartConfig") ) ), tags$script( sprintf(" // careful here in a real application // set up a global/window store object to hold state // will be a simple object var store = {data: %s}; // add a very simple function that will update our store object // with the x data provided Shiny.addCustomMessageHandler( 'updateStore', function(x) { // mutate store data to equal the x argument store.data = x; console.log('changed to ' + x); } ); // super simple Vue app that watches our store object var app = new Vue({ el: '#app', components: { 'sunburst-chart': d2b.vueChartSunburst }, data: { sunburstChartData: store, sunburstChartConfig: function(chart) { chart.label(function(d){return d.name}); chart.sunburst().size(function(d){return d.x}); } } }); ", d3r::d3_nest( treemap::random.hierarchical.data(), value_cols = "x" ) ) ), # add Vue dependency vueR::html_dependency_vue(offline = FALSE), d3r::d3_dep_v4(offline = FALSE), d2b_dep ) server <- function(input,output,session) { observe({ # every 1 second invalidate our session to trigger update invalidateLater(1000, session) # send a message to update store with a random value session$sendCustomMessage( type = "updateStore", message = d3r::d3_nest( treemap::random.hierarchical.data(), value_cols = "x" ) ) }) } shinyApp(ui, server)
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_d2b_shiny.R
library(treemap) library(vueR) library(d3r) library(htmltools) rhd <- random.hierarchical.data() rhd_json <- d3_nest(rhd, value_cols="x") template <- tag( "template", list( id = "d3treemap", tag( "svg", list( "v-bind:style"="styleObject", tag( "g", list( tag( "rect", list( "v-for" = "(node, index) in nodes", "v-if" = "node.depth === depth", "v-bind:x" = "node.x0", "v-bind:width" = "node.x1 - node.x0", "v-bind:y" = "node.y0", "v-bind:height" = "node.y1 - node.y0", "v-bind:style" = "{fill: node.data.color ? node.data.color : color(node.parent.data.name)}", "v-on:click" = "onNodeClick(node)" ) ) ) ) ) ) ) ) component <- tags$script( " Vue.component('treemap-component', { template: '#d3treemap', props: { tree: Object, sizefield: { type: String, default: 'size' }, treewidth: { type: Number, default: 400 }, treeheight: { type: Number, default: 400 }, tile: { type: Function, default: d3.treemapSquarify }, depth: { type: Number, default: 2 }, color: { type: Function, default: d3.scaleOrdinal(d3.schemeCategory10) } }, computed: { styleObject: function() { return {width: this.treewidth, height: this.treeheight} }, treemap: function() { return this.calculate_tree() }, nodes: function() { var color = this.color; var nodes = []; this.treemap.each(function(d) { nodes.push(d); }); return nodes; } }, methods: { calculate_tree: function() { var sizefield = this.sizefield; var d3t = d3.hierarchy(this.tree) .sum(function(d) { return d[sizefield] }); return d3.treemap() .size([this.treewidth, this.treeheight]) .tile(this.tile) .round(true) .padding(1)(d3t) }, onNodeClick: function(node) { this.$emit('node_click', node, this) } } }); " ) app <- tags$script(HTML( sprintf(" var tree = %s; var app = new Vue({ el: '#app', data: { tree: tree, size: 'x', width: 800, height: 600, tile: d3.treemapSliceDice, depth: 1, color: d3.scaleOrdinal(d3.schemeCategory20c) }, methods: { node_clicked: function(node, component) { console.log(node, component); } } }) ", rhd_json ) )) # one treemap example browsable( tagList( template, component, tags$div( id="app", tag( "treemap-component", list(":tree" = "tree",":sizefield"="'x'","v-on:node_click"="node_clicked") #use defaults ) ), app, html_dependency_vue(offline=FALSE,minified=FALSE), d3_dep_v4(offline=FALSE) ) ) browsable( tagList( template, component, tags$div( id="app", tag( "treemap-component", list(":tree" = "tree",":sizefield"="'x'") #use defaults ), tag( "treemap-component", list(":tree" = "tree",":sizefield"="size",":treeheight"=100,":treewidth"=200) #use explicit height,width ), tag( "treemap-component", list( ":tree" = "tree",":sizefield"="size", ":treeheight"="height",":treewidth"="width", ":depth"="depth", ":color"="color" ) ), tag( "treemap-component", list(":tree" = "tree",":sizefield"="size",":tile"="tile","v-on:node_click"="node_clicked") ) ), tags$script(" setInterval( function(){app.$data.depth = app.$data.depth === 3 ? 1 : app.$data.depth + 1}, 2000 ) "), app, html_dependency_vue(offline=FALSE,minified=FALSE), d3_dep_v4(offline=FALSE) ) ) ### other approach not using directives create_tree: function() { var createElement = this.$createElement; var color = d3.scaleOrdinal(d3.schemeCategory10); var nodes_g = this.nodes.map(function(d) { if(d.depth === 2) { return createElement( 'g', null, [createElement( 'rect', { attrs: { x: d.x0, width: d.x1 - d.x0, y: d.y0, height: d.y1 - d.y0 }, style: { fill: color(d.parent.data.name) }, domProps: { __data__: d } } )] ) } }) return createElement( 'svg', {style: {height: this.treeheight, width: this.treewidth}}, nodes_g ); } , render: function() {return this.create_tree()}, updated: function() {return this.create_tree()}
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_d3_treemap.R
```{r} library(treemap) library(vueR) library(d3r) library(htmltools) rhd <- random.hierarchical.data() rhd_json <- d3_nest(rhd, value_cols="x") ``` <template id="d3treemap"> <svg v-bind:style="styleObject"> <g> <rect v-for="(node, index) in nodes" v-if="node.depth === 2" v-bind:x="node.x0" v-bind:width="node.x1 - node.x0" v-bind:y="node.y0" v-bind:height="node.y1 - node.y0" v-bind:style="{fill: color(node.parent.data.name)}"></rect> </g> </svg> </template> <script> //create greetings component based on the greetings template Vue.component('treemap-component', { template: '#d3treemap', props: { tree: Object, sizefield: { type: String, default: 'size' }, treewidth: { type: Number, default: 400 }, treeheight: { type: Number, default: 400 }, tile: { type: Function, default: d3.treemapSquarify }, color: { type: Function, default: d3.scaleOrdinal(d3.schemeCategory10) } }, computed: { styleObject: function() { return {width: this.treewidth, height: this.treeheight} }, treemap: function() { return this.calculate_tree() }, nodes: function() { var color = this.color; var nodes = []; this.treemap.each(function(d) { nodes.push(d); }); return nodes; } }, methods: { calculate_tree: function() { var sizefield = this.sizefield; var d3t = d3.hierarchy(this.tree) .sum(function(d) { return d[sizefield] }); return d3.treemap() .size([this.treewidth, this.treeheight]) .tile(this.tile) .round(true) .padding(1)(d3t) } } }); </script> ```{r} tagList( tags$div( id="app", tag( "treemap-component", list(":tree" = "tree",":sizefield"="'x'") #use defaults ) ), vue( list( el = "#app", data = list( tree = rhd_json, size = 'x', width = 800, height = 600, tile = htmlwidgets::JS("d3.treemapSliceDice") ) ) ), d3_dep_v4() ) ```
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_d3_treemap.Rmd
library(htmltools) library(leaflet) # I installed leaflet 1.0 with devtools::install_github("timelyportfolio/[email protected]") library(leaflet.extras) library(vueR) topojson <- readr::read_file('https://rawgit.com/TrantorM/leaflet-choropleth/gh-pages/examples/basic_topo/crimes_by_district.topojson') map <- leaflet() %>% setView(-75.14, 40, zoom = 11) %>% addProviderTiles("CartoDB.Positron") %>% addGeoJSONChoropleth( topojson, valueProperty = "{{selected}}", group = "choro" ) ui <- tagList( tags$div( id="app", tags$select("v-model" = "selected", tags$option("disabled value"="","Select one"), tags$option("incidents"), tags$option("dist_num") ), tags$span( "Selected: {{selected}}" ), tags$div(map) ), tags$script( " var app = new Vue({ el: '#app', data: { selected: 'incidents' }, watch: { selected: function() { // uncomment debugger below if you want to step through //debugger; // only expect one // if we expect multiple leaflet then we will need // to be more specific var instance = HTMLWidgets.find('.leaflet'); // get the map // could easily combine with above var map = instance.getMap(); // we set group name to choro above // so that we can easily clear map.layerManager.clearGroup('choro'); // now we will use the prior method to redraw var el = document.querySelector('.leaflet'); // get the original method var addgeo = JSON.parse(document.querySelector(\"script[data-for='\" + el.id + \"']\").innerText).x.calls[1]; addgeo.args[7].valueProperty = this.selected; LeafletWidget.methods.addGeoJSONChoropleth.apply(map,addgeo.args); } } }); " ), html_dependency_vue(offline=FALSE) ) browsable(ui)
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_leaflet.R
library(treemap) library(d3r) library(htmltools) # set up dependency for d2bjs chart library d2b_dep <- htmltools::htmlDependency( name = "d2b", version = "0.0.28", src = c(href = "https://unpkg.com/[email protected]/build/"), script = "d2b.min.js" ) # our simple Vue d3 treemap component template <- tag( "template", list( id = "d3treemap", tag( "svg", list( "v-bind:style"="styleObject", tag( "g", list( tag( "rect", list( "v-for" = "(node, index) in nodes", "v-if" = "node.depth === 2", "v-bind:x" = "node.x0", "v-bind:width" = "node.x1 - node.x0", "v-bind:y" = "node.y0", "v-bind:height" = "node.y1 - node.y0", "v-bind:style" = "{fill: node.data.color ? node.data.color : color(node.parent.data.name)}" ) ) ) ) ) ) ) ) component <- tags$script( " Vue.component('treemap-component', { template: '#d3treemap', props: { tree: Object, sizefield: { type: String, default: 'size' }, treewidth: { type: Number, default: 400 }, treeheight: { type: Number, default: 400 }, tile: { type: Function, default: d3.treemapSquarify }, color: { type: Function, default: d3.scaleOrdinal(d3.schemeCategory10) } }, computed: { styleObject: function() { return {width: this.treewidth, height: this.treeheight} }, treemap: function() { return this.calculate_tree() }, nodes: function() { var color = this.color; var nodes = []; this.treemap.each(function(d) { nodes.push(d); }); return nodes; } }, methods: { calculate_tree: function() { var sizefield = this.sizefield; var d3t = d3.hierarchy(this.tree) .sum(function(d) { return d[sizefield] }); return d3.treemap() .size([this.treewidth, this.treeheight]) .tile(this.tile) .round(true) .padding(1)(d3t) } } }); " ) app <- tags$script(HTML( sprintf( " // try to keep color consistent across charts // so use global color function var color = d3.scaleOrdinal(d3.schemeCategory20); // careful here in a real application // set up a global/window store object to hold state // will be a simple object var tree = %s; var store = { tree: tree, filtered_tree: tree, size: 'x', width: 800, height: 600, tile: d3.treemapBinary, color: color, sunburstChartConfig: function(chart) { chart.label(function(d){return d.name}); chart.color(function(d){return color(d.name);}) chart.sunburst().size(function(d){return d.x}); } }; var app = new Vue({ el: '#app', components: { 'sunburst-chart': d2b.vueChartSunburst }, data: store, methods: { sunburstChartRendered: function (el, chart) { var that = this; d3.select(el).selectAll('.d2b-sunburst-chart') .on('mouseover', function (d) { if(d3.event.target.classList[0] === 'd2b-sunburst-arc'){ that.filtered_tree = d3.select(d3.event.target).datum().data; } }); } } }) ", d3r::d3_nest( treemap::random.hierarchical.data(depth=4), value_cols = "x" ) ) )) ui <- tagList( template, component, tags$div( id = "app", tags$div( style = "height:400px; width:400px; float:left;", tag( "sunburst-chart", list( ":data" = "tree", ":config" = "sunburstChartConfig", "@rendered" = "sunburstChartRendered" ) ) ), tags$div( style = "height:400px; width:400px; float:left;", tag( "treemap-component", list(":tree" = "filtered_tree",":sizefield"="'x'",":color" = "color") #use defaults ) ) ), app, html_dependency_vue(offline=FALSE,minified=FALSE), d3_dep_v4(offline=FALSE), d2b_dep ) browsable(ui)
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_treemap_sunburst.R
if(interactive()) { library(vueR) library(htmltools) # recreate Hello Vue! example browsable( tagList( tags$div(id="app", "{{message}}"), vue3( list( el = "#app", data = list( message = "Hello Vue!" ) ) ) ) ) # app2 from Vue.js introduction browsable( tagList( tags$div(id="app-2", tags$span( "v-bind:title" = "message", "Hover your mouse over me for a few seconds to see my dynamically bound title!" ) ), vue( list( el = "#app-2", data = list( message = htmlwidgets::JS( "'You loaded this page on ' + new Date()" ) ) ) ) ) ) # app3 from Vue.js introduction # with a setInterval to toggle seen true and false browsable( tagList( tags$div(id="app-3", tags$p("v-if"="seen", "Now you see me") ), htmlwidgets::onRender( vue( list( el = '#app-3', data = list( seen = TRUE ) ) ), " function(el,x){ var that = this; setInterval(function(){that.instance.seen=!that.instance.seen},1000); } " ) ) ) }
/scratch/gouwar.j/cran-all/cranData/vueR/inst/examples/vue_widget_examples.R
library(shiny) library(vueR) library(htmltools) library(d3r) library(treemap) element <- htmlDependency( name = "element", version = "2.13.2", src = c(href="https://unpkg.com/[email protected]/lib/"), script = "index.js", stylesheet = "theme-chalk/index.css" ) locale <- {tags$script(HTML( " ELEMENT.locale({ el: { colorpicker: { confirm: 'OK', clear: 'Clear' }, datepicker: { now: 'Now', today: 'Today', cancel: 'Cancel', clear: 'Clear', confirm: 'OK', selectDate: 'Select date', selectTime: 'Select time', startDate: 'Start Date', startTime: 'Start Time', endDate: 'End Date', endTime: 'End Time', prevYear: 'Previous Year', nextYear: 'Next Year', prevMonth: 'Previous Month', nextMonth: 'Next Month', year: '', month1: 'January', month2: 'February', month3: 'March', month4: 'April', month5: 'May', month6: 'June', month7: 'July', month8: 'August', month9: 'September', month10: 'October', month11: 'November', month12: 'December', week: 'week', weeks: { sun: 'Sun', mon: 'Mon', tue: 'Tue', wed: 'Wed', thu: 'Thu', fri: 'Fri', sat: 'Sat' }, months: { jan: 'Jan', feb: 'Feb', mar: 'Mar', apr: 'Apr', may: 'May', jun: 'Jun', jul: 'Jul', aug: 'Aug', sep: 'Sep', oct: 'Oct', nov: 'Nov', dec: 'Dec' } }, select: { loading: 'Loading', noMatch: 'No matching data', noData: 'No data', placeholder: 'Select' }, cascader: { noMatch: 'No matching data', loading: 'Loading', placeholder: 'Select', noData: 'No data' }, pagination: { goto: 'Go to', pagesize: '/page', total: 'Total {total}', pageClassifier: '' }, messagebox: { title: 'Message', confirm: 'OK', cancel: 'Cancel', error: 'Illegal input' }, upload: { deleteTip: 'press delete to remove', delete: 'Delete', preview: 'Preview', continue: 'Continue' }, table: { emptyText: 'No Data', confirmFilter: 'Confirm', resetFilter: 'Reset', clearFilter: 'All', sumText: 'Sum' }, tree: { emptyText: 'No Data' }, transfer: { noMatch: 'No matching data', noData: 'No data', titles: ['List 1', 'List 2'], // to be translated filterPlaceholder: 'Enter keyword', // to be translated noCheckedFormat: '{total} items', // to be translated hasCheckedFormat: '{checked}/{total} checked' // to be translated }, image: { error: 'FAILED' }, pageHeader: { title: 'Back' // to be translated }, popconfirm: { confirmButtonText: 'Yes', cancelButtonText: 'No' } } }) " ))} # some random hierarchical data converted to proper format rhd <- d3r::d3_nest( treemap::random.hierarchical.data(), value_cols="x" ) ui <- tagList( html_dependency_vue(), element, actionButton("btnResetData", "Reset Data"), tags$head(locale), tags$script(HTML( " // add message handler to receive new data from R and update Vue data Shiny.addCustomMessageHandler('updateData', function(message) { var w = HTMLWidgets.find(message.selector); if(typeof(w) !== 'undefined' && w.hasOwnProperty('instance')) { w.instance.data = message.data; w.instance.checkedNodes = []; } }); " )), tags$h3("Tree from element-ui"), tags$div( id = "app", tag( "el-tree", list( "ref" = "mytree", ":data" = "data.children", ":props" = "defaultProps", "show-checkbox" = NA, "@check-change" = "handleCheckChange" ) ), tags$pre("{{checkedNodes.map(function(d){return d.name})}}") ), vue( elementId = "vuewidget", list( el="#app", data = list( data = rhd, defaultProps = list( 'children' = 'children', 'label' = 'name' ), checkedNodes = list() ), methods = list( handleCheckChange = htmlwidgets::JS( " function(data, checked, indeterminate){ //debugger; //data.checked = checked && !indeterminate; console.log(data, checked, indeterminate); this.checkedNodes = this.$refs.mytree.getCheckedNodes(); this.$emit('tree-checked'); } " ) ), watch = list( checkedNodes = htmlwidgets::JS( " function(dat) { debugger Shiny.setInputValue(this.$el.id + '_checked', dat.map(d => d.name)); } " ) ) ), minified = FALSE ) ) server <- function(input, output, session) { observeEvent(input$btnResetData, { session$sendCustomMessage( 'updateData', list( selector = "#vuewidget", data = rhd ) ) }) observeEvent(input$app_checked, { str(input$app_checked) }) } shinyApp(ui, server)
/scratch/gouwar.j/cran-all/cranData/vueR/inst/experiments/experiment_element_shiny.R
library(htmltools) library(vueR) library(shiny) # experiment with standalone vue reactivity in bare page # reference: # https://vuejs.org/v2/guide/reactivity.html # https://dev.to/jinjiang/understanding-reactivity-in-vue-3-0-1jni browsable( tagList( tags$head( tags$script(src = "https://unpkg.com/@vue/[email protected]/dist/reactivity.global.js"), ), tags$p("we should see a number starting at 0 and increasing by one each second"), tags$div(id = "reporter"), tags$script(HTML( " let data = {x: 0}; let data_reactive = VueReactivity.reactive(data) // could also use ref for primitive value console.log(data, data_reactive) VueReactivity.effect(() => { console.log(data_reactive.x) document.getElementById('reporter').innerText = data_reactive.x }) setInterval(function() {data_reactive.x++}, 1000) " )) ) ) # experiment with Shiny inputValues and vue-next # reference: # https://vuejs.org/v2/guide/reactivity.html # https://dev.to/jinjiang/understanding-reactivity-in-vue-3-0-1jni ui <- tagList( tags$head( tags$script(src = "https://unpkg.com/@vue/[email protected]/dist/reactivity.global.js"), ), tags$div( tags$h3("Increment with JavaScript"), tags$span("Shiny: "), textOutput("reporterR", inline = TRUE), tags$span("JavaScript: "), tags$span( id = "reporterJS" ) ), tags$div( tags$h3("Increment with R/Shiny"), tags$span("Shiny (used numeric input for convenience): "), numericInput(inputId = 'x2', label = "", value = 0), tags$span("JavaScript: "), tags$span( id = "reporterJS2" ) ), tags$script(HTML( " $(document).on('shiny:connected', function() { // once Shiny connected replace Shiny inputValues with reactive Shiny inputValues Shiny.shinyapp.$inputValues = VueReactivity.reactive(Shiny.shinyapp.$inputValues) // do our counter using Shiny.setInputValue from JavaScript Shiny.setInputValue('x', 0) // initialize with 0 VueReactivity.effect(() => { console.log('javascript', Shiny.shinyapp.$inputValues.x) document.getElementById('reporterJS').innerText = Shiny.shinyapp.$inputValues.x }) setInterval( function() { Shiny.setInputValue('x', Shiny.shinyapp.$inputValues.x + 1) //increment by 1 }, 1000 ) // react to counter implemented in Shiny VueReactivity.effect(() => { console.log('shiny', Shiny.shinyapp.$inputValues['x2:shiny.number']) document.getElementById('reporterJS2').innerText = Shiny.shinyapp.$inputValues['x2:shiny.number'] }) }) " )) ) server <- function(input, output, session) { x2 <- 0 # use this for state of Shiny counter output$reporterR <- renderText({input$x}) observe({ invalidateLater(1000, session = session) x2 <<- x2 + 1 # <<- or assign required to update parent updateNumericInput(inputId = "x2", value = x2, session = session) }) } shinyApp( ui = ui, server = server, options = list(launch.browser = rstudioapi::viewer) )
/scratch/gouwar.j/cran-all/cranData/vueR/inst/experiments/experiment_vue3_reactive_inputValues.R
library(shiny) library(htmltools) library(ggplot2) library(vueR) ui <- tagList( tags$head( tags$link(href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900", rel="stylesheet"), tags$link(href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css", rel="stylesheet"), tags$link(href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css", rel="stylesheet") ), tags$div( id = "app", HTML( sprintf(" <v-app> <v-main> <v-container class='fill-height' > <v-row justify='center' align='center'> <v-dialog v-model='dialog' width='500' > <template v-slot:activator='{ on, attrs }'> <v-btn color='red lighten-2' dark v-bind='attrs' v-on='on' > Create Plot </v-btn> </template> %s </v-dialog> </v-row> </v-container> </v-main> </v-app> ", plotOutput("plot") ) ) ), html_dependency_vue(), tags$script(src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"), tags$script(HTML(" const app = new Vue({ el: '#app', vuetify: new Vuetify(), data: {dialog: false}, watch: { dialog: { handler: function(val) { if(val === true) { Vue.nextTick(() => { // force bind to bind plot if(!Shiny.shinyapp.$bindings.hasOwnProperty('plot')) { Shiny.bindAll($('.v-dialog')) } // or this seems to work as well without checking // since Shiny ignores already bound // Shiny.bindAll($('.v-dialog')) }) } Shiny.setInputValue('dialog', val) } } } }) $(document).on('shiny:sessioninitialized', function() { Shiny.setInputValue('dialog', app.$data.dialog) }) ")) ) server <- function(input, output, session) { output$plot <- renderPlot({ input$dialog if(input$dialog == TRUE) { # plot with random data ggplot(data = data.frame(x=1:20,y=runif(20)*10), aes(x=x, y=y)) + geom_line() } else { # empty ggplot ggplot() + geom_blank() } }) } shinyApp(ui, server)
/scratch/gouwar.j/cran-all/cranData/vueR/inst/experiments/experiment_vuetify_dialog_with_ggplot_output.R
# quick example of Vuex and Shiny # reference: https://vuex.vuejs.org/guide/ library(htmltools) library(shiny) library(vueR) vuex <- tags$script(src="https://unpkg.com/[email protected]/dist/vuex.js") ui <- tagList( html_dependency_vue(offline = FALSE, minified = FALSE), tags$head(vuex), tags$h1("Shiny with Vue and Vuex"), tags$h3('Vue App'), tags$div( id = "app", tags$button(`@click`="increment", "+"), tags$button(`@click`="decrement", "-"), "{{ count }}" ), tags$h3("Shiny controls"), # add Shiny buttons to demonstrate Shiny to update Vuex state actionButton(inputId = "btnIncrement", label="+"), actionButton(inputId = "btnDecrement", label="-"), tags$script(HTML( " // first example in Vuex documentation Vue.use(Vuex) // make sure to call Vue.use(Vuex) if using a module system const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment: state => state.count++, decrement: state => state.count-- } }) const app = new Vue({ el: '#app', store: store, computed: { count () { return this.$store.state.count } }, methods: { increment () { this.$store.commit('increment') }, decrement () { this.$store.commit('decrement') } } }) $(document).on('shiny:sessioninitialized', function() { // increment from Shiny custom message // chose 'increment' but does not have to match the store mutation name Shiny.addCustomMessageHandler('increment', function(msg) { app.$store.commit('increment') }); Shiny.addCustomMessageHandler('decrement', function(msg) { app.$store.commit('decrement') }); }) " )) ) #browsable(ui) server <- function(input, output, session) { observeEvent(input$btnIncrement, { session$sendCustomMessage("increment", list()) }) observeEvent(input$btnDecrement, { session$sendCustomMessage("decrement", list()) }) } shinyApp( ui = ui, server = server, options = list(launch.browser = rstudioapi::viewer) )
/scratch/gouwar.j/cran-all/cranData/vueR/inst/experiments/experiment_vuex_shiny.R
--- title: "Intro to vueR" author: "Kenton Russell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Intro to vueR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- All the awesomeness of [Vue.js](https://vuejs.org) is available in `R` with `vueR`. We will work through some of the examples to give you a feel for both `Vue.js` and how to incorporate this powerful binding framework in your `R` workflows.
/scratch/gouwar.j/cran-all/cranData/vueR/vignettes/intro_to_vueR.Rmd
#' Check rows #' #' This function prints the number of rows of a data frame. This function is used #' to check that rows are not deleted or doubled unless expected. #' #' @param df The data frame whose rows are to be counted #' @param name The name of the data file (this will be printed) #' @examples #' check_rows(mtcars) #' #' @return A message is printed to the console with the number of rows of the data #' @export check_rows <- function(df, name = NULL) { if (is.null(name)) { name <- deparse(substitute(df)) } print(paste("Number of rows of the ", name, ": ", nrow(df), sep = "")) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/Check_rows.R
#' Count more than 1 #' #' Function to count the number of values greater than 1 in a vector #' This function is used in the function Check_columns_for_double_rows #' to count duplicate values. #' @param x The vector to test #' @return Number of values greater than 1. #' @family vector calculations #' @examples #' count_more_than_1(c(1, 1, 4)) #' #' @export count_more_than_1 <- function(x) { y <- sum(x > 1, na.rm = T) return(y) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/Count_more_than_1.R
#' Drop NA column names #' #' Deletes columns whose name is NA or whose name is empty #' #' @param x dataframe #' #' @return dataframe without columns that are NA #' @export drop_na_column_names <- function(x) { return(x[!is.na(names(x)) & !(names(x) == "")]) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/Drop_NA_column_names.R
#' Assert Date Value in Column #' #' This function asserts that the values in a specified column of a data frame are of Date type. #' It uses the `checkmate::assert_date` function to perform the assertion. #' #' @param column A character vector or string with the column name to be tested. #' @param df The data frame that contains the column. #' @param prefix_column A character string that will be prepended to the column name in the assertion message. Default is NULL. #' @param ... Additional parameters are passed to the `checkmate::assert_date` function. #' @return None #' #' @export assert_date_named <- function(column, df, prefix_column = NULL, ...) { checkmate::assert_date(df[[column]], .var.name = trimws(paste(prefix_column, column)), ... ) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/assert_date_named.R
#' Assert Logical Value in Column #' #' This function asserts that the values in a specified column of a data frame are logical. #' It uses the `checkmate::assert_logical` function to perform the assertion. #' #' @param column A character vector or string with the column name to be tested. #' @param df The data frame that contains the column. #' @param prefix_column A character string that will be prepended to the column name in the assertion message. Default is NULL. #' @param ... Additional parameters are passed to the `checkmate::assert_logical` function. #' @return None #' @examples #' # Create a data frame #' df <- data.frame(a = c(TRUE, FALSE, TRUE, FALSE), b = c(1, 2, 3, 4)) #' # Assert that the values in column "a" are logical #' assert_logical_named("a", df) #' #' @export assert_logical_named <- function(column, df, prefix_column = NULL, ...) { checkmate::assert_logical(df[[column]], .var.name = trimws(paste(prefix_column, column)), ... ) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/assert_logical_named.R