content
stringlengths
0
14.9M
filename
stringlengths
44
136
utils::globalVariables(".") #' Print graphical representation of a correlation matrix. #' #'\code{ggcormat} makes the same correlation matrix as \link{cortestR} #' and graphically represents it in a plot #' #' @param cor_mat correlation matrix as produced by cor. #' @param method text specifying type of correlation. #' @param title plot title. #' @param maxpoint maximum for scale_size_manual, may need adjustment depending on plotsize. #' @param textsize for theme text. #' @param axistextsize relative text size for axes. #' @param titlesize as you already guessed, relative text size for title. #' @param breaklabels currently not used, intended for str_wrap. #' @param .low Color for heatmap. #' @param .high Color for heatmap. #' @param lower_only should only lower triangle be plotted? #' @param .legendtitle Optional name for color legend. #' @param p_mat Optional matrix of p-values; if provided, this is used to define #' size of dots rather than absolute correlation. #' #' @return A ggplot object, allowing further styling. #' #' @examples #' coeff_pvalues <- cortestR(mtcars[, c("wt", "mpg", "qsec", "hp")], #' split = TRUE, sign_symbol = FALSE #' ) #' # focus on coefficients: #' ggcormat(cor_mat = coeff_pvalues$corout, maxpoint = 5) #' # size taken from p-value: #' ggcormat( #' cor_mat = coeff_pvalues$corout, #' p_mat = coeff_pvalues$pout, maxpoint = 5) #' #' @export ggcormat <- function(cor_mat, p_mat = NULL, method = "Correlation", title = "", maxpoint = 2.1, textsize = 5, axistextsize = 2, titlesize = 3, breaklabels = NULL, lower_only = TRUE, .low = "blue3", .high = "red2", .legendtitle = NULL) { `.` <- Variable1 <- Variable2 <- value <- size <- x <- y <- NULL rownames(cor_mat) <- colnames(cor_mat) # dd <- as.dist((1-cor_mat)/2) # hc <- hclust(dd) # cor_mat <-cor_mat[hc$order, hc$order] var_order <- rownames(cor_mat) if (lower_only) { cor_mat[upper.tri(cor_mat)] <- NA } melted_cor_mat <- cor_mat |> as_tibble() |> mutate(Variable1 = colnames(cor_mat)) |> pivot_longer(-Variable1,names_to = 'Variable2') |> # gather(key = Variable2, value = value, -Variable1) |> na.omit() |> mutate( Variable1 = factor(Variable1, levels = var_order), Variable2 = factor(Variable2, levels = var_order), value = as.numeric(value), size = abs(value) ) corvar_count <- nrow(cor_mat) if (!is.null(p_mat)) { melted_p_mat <- suppressWarnings( p_mat |> as_tibble() |> mutate(Variable1 = colnames(p_mat)) |> pivot_longer(-Variable1,names_to = 'Variable2', values_to = 'size') |> # gather(key = Variable2, value = size, -Variable1) |> mutate( Variable1 = factor(Variable1, levels = var_order), Variable2 = factor(Variable2, levels = var_order), size = -log10(formatP(as.numeric(size), textout = FALSE )) ) |> na.omit()) melted_p_mat$size[which(melted_p_mat$size > 3)] <- 3 melted_cor_mat <- full_join(melted_cor_mat[1:3], melted_p_mat, by = c("Variable1", "Variable2") ) } if (lower_only) { triangel <- data.frame( x = c(0, rep(corvar_count + 2, 2)), y = c(rep(corvar_count + 2, 2), 0) ) viereck1 <- data.frame( x = c(rep(0, 2), rep(corvar_count + 2.2, 2)), y = c(0, 0.4, 0.4, 0) ) viereck2 <- data.frame( x = c(0, 0.4, 0.4, 0), y = c(rep(0, 2), rep(corvar_count + 2.2, 2)) ) viereck3 <- data.frame( x = c( corvar_count + 0.6, corvar_count + 2.2, corvar_count + 2.2, corvar_count + 0.6 ), y = c(rep(0, 2), rep(corvar_count + 2.2, 2)) ) viereck4 <- data.frame( x = c(rep(0, 2), rep(corvar_count + 2.2, 2)), y = c( corvar_count + 0.6, corvar_count + 2.2, corvar_count + 2.2, corvar_count + 0.6 ) ) } if (is.null(breaklabels)) { breaklabels <- levels(melted_cor_mat$Variable1) } ggheatmap <- ggplot( melted_cor_mat, aes(Variable2, Variable1) ) + # geom_tile(color = "white")+ geom_point(aes(Variable2, Variable1, size = size, color = value )) + geom_vline(xintercept = seq(0.5, corvar_count + 1, by = 1), color = "grey", linewidth = .25) + geom_hline(yintercept = seq(0.5, corvar_count + 1, by = 1), color = "grey", linewidth = .25) + # geom_point(aes(Variable2, Variable1, size=abs(value),color=value))+ scale_color_gradient2( low = .low, high = .high, mid = "lightgrey", midpoint = 0, limit = c(-1, 1), space = "Lab", name = method ) + theme_minimal() + # minimal theme theme( axis.text.x = element_text( angle = 90, vjust = 0, hjust = 1 ), text = element_text(size = textsize), axis.text = element_text(size = rel(axistextsize)), axis.title.x = element_blank(), axis.title.y = element_blank(), panel.grid.major = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.ticks = element_blank(), plot.title = element_text(size = rel(titlesize), face = "bold"), legend.text = element_text(size = rel(1.25)), legend.title = element_text(size = rel(1.65)) # legend.key.size = unit(.5,'lines'), # legend.key.width=unit(5.5,'cm'), ) + coord_fixed() + # theme(legend.position = "right")+ scale_y_discrete( limits = rev(levels(melted_cor_mat$Variable1)), labels = rev(breaklabels) ) + scale_x_discrete( limits = levels(melted_cor_mat$Variable1), labels = breaklabels ) + ggtitle(title) if (is.null(p_mat)) { ggheatmap <- ggheatmap + scale_size_continuous( name = ifelse( is.null(.legendtitle), "abs. correlation scaling", .legendtitle ), limits = c(0, 1), breaks = c(.1, .5, .9), labels = c(.1, .5, .9), range = rel(c(.2, maxpoint)) ) } else { ggheatmap <- ggheatmap + scale_size_continuous( name = ifelse( is.null(.legendtitle), "p-value scaling", .legendtitle ), limits = c(0, 3), breaks = c(-log10(.05), 2, 3), labels = c(.05, .01, .001), range = rel(c(.2, maxpoint)) ) } if (lower_only) { ggheatmap <- ggheatmap + geom_polygon(data = triangel, aes(x = x, y = y), fill = "white") + geom_polygon(data = viereck1, aes(x = x, y = y), fill = "white") + geom_polygon(data = viereck2, aes(x = x, y = y), fill = "white") + geom_polygon(data = viereck3, aes(x = x, y = y), fill = "white") + geom_polygon(data = viereck4, aes(x = x, y = y), fill = "white") + guides( color = guide_colorbar( barwidth = 7, barheight = 1, title.position = "top", title.hjust = 0.5, order = 2 ), size = guide_legend( order = 1, title.position = "top" ) ) + theme( legend.justification = c("right", "top"), legend.direction = "horizontal", legend.position = c(1, .99) ) } return(ggheatmap) } #' Add labels to outliers in boxplot/beeswarm. #' #' @description #' `r lifecycle::badge('experimental')` #' #'\code{label_outliers} adds a text_repel layer to an existing ggplot object. It is intended to be used with boxplots or beeswarm plots. Faceting will result in separate computations for outliers. #' It requires the \code{ggrepel} package. #' #' @param plotbase ggplot object to add labels to. # ' @param xvar x variable for grouping. # ' @param yvar y variable with possible outliers. #' @param labelvar variable to use as label. If NULL, rownames or rownumbers are used. #' @param coef coefficient for boxplot.stats, defaults to 1.5. #' @param nudge_x nudge in x direction, defaults to 0. #' @param nudge_y nudge in y direction, defaults to 0. #' @param color color of labels, defaults to darkred. #' @param size size of labels, defaults to 3. #' @param hjust horizontal justification of labels, defaults to 0. #' @param face font face of labels, defaults to bold. #' #' @return A ggplot object, allowing further styling. #' # ' @examples # todo: group by facet variables #' @export label_outliers <- function(plotbase, labelvar=NULL, #xvar, #yvar, coef=1.5, nudge_x=0, nudge_y=0, color="darkred", size=3, hjust=0, face="bold") { if(!requireNamespace("ggrepel", quietly = TRUE)) { stop("ggrepel package is required") } plotdata <- plotbase$data if(is.null(labelvar)) { labelvar <- "Position" plotdata <- mutate(plotdata, Position = row.names(plotdata)) } plotlist <- ggplot_build(plotbase) xvar <- plotbase$mapping[["x"]] |> as_label() # plotlist[["plot"]][["layers"]][[1]][["computed_mapping"]][1] |> # as.character() |> # str_remove("~") yvar <- plotbase$mapping[["y"]] |> as_label() #plotbase$layers[[1]]$computed_mapping[2] |> # plotlist[["plot"]][["layers"]][[1]][["computed_mapping"]][2] |> # as.character() |> # str_replace_all( # c('^.+\\"(.+)\\".*'="\\1", # "~"="")) # groupvars <- xvar # if(!is.null(plotlist$layout$facet$params$row)){ facet_rows <- names(plotlist$layout$facet$params$row) # groupvars <- c(groupvars,facet_rows) # } # if(!is.null(plotlist$layout$facet$params$col)){ facet_cols <- names(plotlist$layout$facet$params$col) facet_wraps <- names(plotlist$layout$facet$params$facets) groupvars <- c(xvar,facet_rows,facet_cols,facet_wraps) outpositions <- plotbase$data |> group_by(across(all_of(groupvars))) |> reframe(across(all_of(yvar), ~detect_outliers(.x, coef=coef)$outliers)) |> left_join(plotdata) |> unique() plotbase + ggrepel::geom_text_repel(data=outpositions, aes(label=!!sym(labelvar)), nudge_x=nudge_x, nudge_y=nudge_y, color=color, size=size, hjust=hjust, fontface=face) } #' Find outliers based on IQR #' #' @description #' `r lifecycle::badge('experimental')` #' #'\code{detect_outliers} computes IQR and finds outliers. It gives the same results as \code{geom_boxplot} and thus differs slightly from \code{boxplot.stats}. #' #' @param x numeric vector. #' @param coef coefficient for boxplot.stats, defaults to 1.5. #' #' @return A list with elements positions and outliers as numeric vectors. #' #' @examples #' detect_outliers(rnorm(100)) #' @export detect_outliers <- function(x, coef=1.5) { qnt <- quantile(x, probs=c(.25, .75), na.rm = TRUE) iqr <- diff(qnt) upper <- qnt[2] + coef * iqr lower <- qnt[1] - coef * iqr o_pos <- which(x > upper | x < lower) out <- list("positions"=o_pos, "outliers"=x[o_pos]) return(out) }
/scratch/gouwar.j/cran-all/cranData/wrappedtools/R/plots.R
#' Pairwise Fisher's exact tests #' #' \code{pairwise_fisher_test} calculates pairwise comparisons between #' group levels with corrections for multiple testing. #' #' @param dep_var dependent variable, containing the data. #' @param indep_var independent variable, should be factor or coercible. #' @param adjmethod method for adjusting p values (see [p.adjust]). #' @param plevel threshold for significance. #' @param symbols predefined as b,c, d...; provides footnotes to mark group #' differences, e.g. b means different from group 2 #' @param ref is the 1st subgroup the reference (like in Dunnett test)? #' #' @return #' A list with elements "methods" (character), "p.value" (matrix), #' "plevel" (numeric), and "sign_colwise" (vector of length number of levels - 1) #' #' @examples #' # All pairwise comparisons #' pairwise_fisher_test(dep_var = mtcars$cyl, indep_var = mtcars$gear) #' # Only comparison against reference gear=3 #' pairwise_fisher_test(dep_var = mtcars$cyl, indep_var = mtcars$gear, ref = TRUE) #' @export pairwise_fisher_test <- function(dep_var, indep_var, adjmethod = "fdr", plevel = .05, symbols = letters[-1], # c('b','c','d','e','f','g'), ref = FALSE) { if (!is.factor(indep_var)) { indep_var <- factor(indep_var) } if (!is.factor(dep_var)) { dep_var <- factor(dep_var) } if (is.ordered(indep_var)) { indep_var <- factor(indep_var, ordered = F) } ngroups <- length(levels(indep_var)) pft_data <- data.frame(dep_var, indep_var) pft_data <- na.omit(pft_data) # print(pft_data) p_unadj <- matrix( nrow = ngroups - 1, ncol = ngroups - 1, dimnames = list(c(2:ngroups), c(1:(ngroups - 1))) ) for (firstgroup in 1:(ngroups - 1)) { for (secondgroup in (firstgroup + 1):ngroups) { tempdata <- pft_data[which( pft_data$indep_var == levels(pft_data$indep_var)[firstgroup] | pft_data$indep_var == levels(pft_data$indep_var)[secondgroup] ), ] if (min(dim(table(tempdata))) > 1) { p_unadj[secondgroup - 1, firstgroup] <- try( fisher.test(tempdata$dep_var, tempdata$indep_var, simulate.p.value = T,B = 10^5)$p.value, silent = T) } else { p_unadj[secondgroup - 1, firstgroup] <- 1 } } } # print(p_unadj) sign_colwise <- character() if (!ref) { p_adj <- matrix(p.adjust(as.vector(p_unadj), method = adjmethod), byrow = FALSE, nrow = ngroups - 1, ncol = ngroups - 1, dimnames = list(c(2:ngroups), c(1:(ngroups - 1))) ) for (col_i in 1:ncol(p_adj)) { temp <- " " for (row_i in col_i:nrow(p_adj)) { if (!is.na(p_adj[row_i, col_i]) & p_adj[row_i, col_i] < plevel) { temp <- paste0(temp, symbols[row_i]) } } sign_colwise <- c(sign_colwise, temp) } } else { p_adj <- p.adjust(as.vector(p_unadj[, 1]), method = adjmethod) sign_colwise <- markSign(p_adj) # sapply(p_adj,markSign) } return(list( method = adjmethod, p.value = p_adj, plevel = plevel, sign_colwise = sign_colwise )) } #' Pairwise comparison for ordinal categories #' #' \code{pairwise_ordcat_test} calculates pairwise comparisons for ordinal #' categories between all group levels with corrections for multiple testing. #' #' @param dep_var dependent variable, containing the data #' @param indep_var independent variable, should be factor #' @param adjmethod method for adjusting p values (see [p.adjust]) #' @param plevel threshold for significance #' @param symbols predefined as b,c, d...; provides footnotes to mark group #' differences, e.g. b means different from group 2 #' @param ref is the 1st subgroup the reference (like in Dunnett test) #' @param cmh Should Cochran-Mantel-Haenszel test (\link{cmh_test}) be used for #' testing? If false, the linear-by-linear association test (\link{lbl_test}) #' is applied. #' #' @return #' A list with elements "methods" (character), "p.value" (matrix), #' "plevel" (numeric), and "sign_colwise" (vector of length number of levels - 1) #' #' @examples #' # All pairwise comparisons #' mtcars2 <- dplyr::mutate(mtcars, cyl = factor(cyl, ordered = TRUE)) #' pairwise_ordcat_test(dep_var = mtcars2$cyl, indep_var = mtcars2$gear) #' # Only comparison against reference gear=3 #' pairwise_ordcat_test(dep_var = mtcars2$cyl, indep_var = mtcars2$gear, ref = TRUE) #' @export pairwise_ordcat_test <- function(dep_var, indep_var, adjmethod = "fdr", plevel = .05, symbols = letters[-1], ref = FALSE, cmh = TRUE) { dep_var <- factor(dep_var, ordered = TRUE) indep_var <- factor(indep_var) ngroups <- length(levels(indep_var)) pft_data <- data.frame(dep_var, indep_var) pft_data <- na.omit(pft_data) p_unadj <- matrix( nrow = ngroups - 1, ncol = ngroups - 1, dimnames = list(c(2:ngroups), c(1:(ngroups - 1))) ) for (firstgroup in 1:(ngroups - 1)) { for (secondgroup in (firstgroup + 1):ngroups) { tempdata <- pft_data[which( as.numeric(pft_data$indep_var) %in% c(firstgroup, secondgroup) ), ] if (min(dim(table(tempdata))) > 1) { if (cmh) { # print('cmh_test')#(x~group,data=tempdata)) p_unadj[secondgroup - 1, firstgroup] <- coin::pvalue(coin::cmh_test(dep_var ~ indep_var, data = tempdata)) } else { # print('lbl_test')#(x~group,data=tempdata)) p_unadj[secondgroup - 1, firstgroup] <- coin::pvalue(coin::lbl_test(dep_var ~ indep_var, data = tempdata)) } } else { p_unadj[secondgroup - 1, firstgroup] <- 1 } } } sign_colwise <- character() if (!ref) { p_adj <- matrix(p.adjust(as.vector(p_unadj), method = adjmethod), byrow = FALSE, nrow = ngroups - 1, ncol = ngroups - 1, dimnames = list(c(2:ngroups), c(1:(ngroups - 1))) ) for (col_i in 1:ncol(p_adj)) { temp <- " " for (row_i in col_i:nrow(p_adj)) { if (!is.na(p_adj[row_i, col_i]) & p_adj[row_i, col_i] < plevel) { temp <- paste0(temp, symbols[row_i]) } } sign_colwise <- c(sign_colwise, temp) } } else { p_adj <- p.adjust(as.vector(p_unadj[, 1]), method = adjmethod) sign_colwise <- sapply(p_adj, markSign) } return(list( method = adjmethod, p.value = p_adj, plevel = plevel, sign_colwise = sign_colwise, test = ifelse(cmh, "cmh", "lbl") )) } #' Kolmogorov-Smirnov-Test against Normal distribution #' #' \code{ksnormal} is a convenience function around \link{ks.test}, testing against #' Normal distribution. #' If less than 2 values are provided, NA is returned. #' #' @param x Vector of data to test. #' #' @return p.value from \link{ks.test}. #' #' @examples #' # original ks.test: #' ks.test( #' x = mtcars$wt, pnorm, mean = mean(mtcars$wt, na.rm = TRUE), #' sd = sd(mtcars$wt, na.rm = TRUE) #' ) #' # wrapped version: #' ksnormal(x = mtcars$wt) #' @export ksnormal <- function(x) { if(length(na.omit(x))>1){ suppressWarnings( assign("ksout",ks.test(x, "pnorm", mean(x, na.rm = TRUE), sd(x, na.rm = TRUE), exact = FALSE )$p.value)) }else{ ksout <- NA } return(ksout) } #' Confidence interval for generalized linear models #' #' \code{glm_CI} computes and formats CIs for glm. #' #' @usage glmCI(model, min = .01, max = 100, cisep = '\U000022ef', ndigit=2) #' #' @return A list with coefficient, CIs, and pasted coef(\[CIs\]). #' #' @param model Output from \link{glm}. #' @param min,max Lower and upper limits for CIs, useful for extremely wide CIs. #' @param cisep Separator between CI values. #' @param ndigit rounding level. #' #' @examples #' glm_out <- glm(am ~ mpg, family = binomial, data = mtcars) #' glmCI(glm_out) #' @export glmCI <- function(model, min = .01, max = 100, cisep = "\U000022ef", ndigit = 2) { glmReturn <- list( coeff = character(0), ci = character(0), c_ci = NA ) pvTmp <- labels(model$terms) for (pv_i in 1:length(pvTmp)) { rows <- grep(pvTmp[pv_i], names(model$coefficients)) coeffTmp <- as.character(as.vector(round(exp(model$coefficients[rows]), ndigit))) coeffTmp[which(as.numeric(coeffTmp) < min)] <- paste0("<", min) coeffTmp[which(as.numeric(coeffTmp) > max)] <- paste0(">", max) glmReturn$coeff <- c(glmReturn$coeff, paste(coeffTmp, collapse = "/")) ciModel <- as.matrix(exp(confint(model))) ciTmp <- character(0) for (row_i in rows) { ciRow <- as.character(as.vector(round(ciModel[row_i, ], ndigit))) ciRow[which(as.numeric(ciRow) < min)] <- paste0("<", min) ciRow[which(as.numeric(ciRow) > max)] <- paste0(">", max) ciTmp <- paste(ciTmp, paste(ciRow, collapse = cisep), sep = "/" ) } glmReturn$ci <- c(glmReturn$ci, gsub("^/", "", ciTmp)) } glmReturn$c_ci <- paste0(glmReturn$coeff, " (", glmReturn$ci, ")") return(glmReturn) } #' Correlations with significance #' #' \code{cortestR} computes correlations and their significance level #' based on \link{cor.test}. Coefficients and p-values may be combined or #' reported separately. #' #' @return Depending on parameters split and sign_symbol, #' either a single data frame with coefficient and p-values or significance symbols #' or a list with two data frames. #' #' @param cordata data frame or matrix with rawdata. #' @param method as in cor.test. #' @param digits rounding level for estimate. #' @param digits_p rounding level for p value. #' @param sign_symbol If true, use significance indicator instead of p-value. #' @param split logical, report correlation and p combined (default) #' or split in list. #' @param space character to fill empty upper triangle. #' @examples #' # with defaults #' cortestR(mtcars[, c("wt", "mpg", "qsec")], split = FALSE, sign_symbol = TRUE) #' # separate coefficients and p-values #' cortestR(mtcars[, c("wt", "mpg", "qsec")], split = TRUE, sign_symbol = FALSE) #' @export cortestR <- function(cordata, method = "pearson", digits = 3, digits_p = 3, sign_symbol = TRUE, split = FALSE, space = "") { if(!is.matrix(cordata)){ cordata <- as.matrix(cordata) } n <- ncol(cordata) corout <- as.data.frame( matrix(space, nrow = n, ncol = n) ) colnames(corout) <- colnames(cordata) rownames(corout) <- colnames(corout) if (split) { pout <- corout } for (row_i in 1:n) { for (col_i in 1:row_i) { ct <- cor.test(cordata[, row_i], cordata[, col_i], method = method ) corout[row_i, col_i] <- round(ct$estimate, digits) if (!split) { if (row_i != col_i) { if (sign_symbol) { corout[row_i, col_i] <- paste0( corout[row_i, col_i], markSign(ct$p.value) ) } else { corout[row_i, col_i] <- paste0( corout[row_i, col_i], " (", formatP(ct$p.value, ndigits = digits_p), ")" ) } } } else { if (sign_symbol) { pout[row_i, col_i] <- markSign(ct$p.value) |> as.character() } else { pout[row_i, col_i] <- formatP(ct$p.value) } } } } if (split) { return(list( corout = corout, pout = pout )) } else { return(corout) } } #' Independent sample t-test with test for equal variance #' #' \code{t_var_test} tests for equal variance based on \link{var.test} #' and calls t.test, setting the option var.equal accordingly. #' #' @param data Tibble or data_frame. #' @param formula Formula object with dependent and independent variable. #' @param cutoff is significance threshold for equal variances. #' #' @return #' A list from \link{t.test} #' #' @examples #' t_var_test(mtcars, wt ~ am) #' # may be used in pipes: #' mtcars |> t_var_test(wt ~ am) #' @export t_var_test <- function(data, formula, cutoff = .05) { formula <- as.formula(formula) t_out <- "" var.equal <- try( var.test( formula = formula, data = data )$p.value > cutoff, silent = TRUE ) if (is.logical(var.equal)) { t_out <- t.test( formula = formula, data = data, var.equal = var.equal ) } return(t_out) } #' Comparison for columns of numbers for 2 groups #' #' \code{compare2numvars} computes either \link{t_var_test} or \link{wilcox.test}, #' depending on parameter gaussian. Descriptive statistics, depending on distribution, #' are reported as well. #' #' @param data name of dataset (tibble/data.frame) to analyze. #' @param dep_vars vector of column names for independent variables. #' @param indep_var name of grouping variable, has to translate to 2 groups. If more levels are encountered, an error is produced. #' @param gaussian logical specifying normal or ordinal values. #' @param round_p level for rounding p-value. #' @param round_desc number of significant digits for rounding of descriptive stats. #' @param range include min/max? #' @param rangesep text between statistics and range or other elements. #' @param pretext for function [formatP]. #' @param mark for function [formatP]. #' @param n create columns for n per group? #' @param add_n add n to descriptive statistics? #' #' @return #' A tibble with variable names, descriptive statistics, and p-value, #' number of rows is number of dep_vars. #' #' @examples #' # Assuming Normal distribution: #' compare2numvars( #' data = mtcars, dep_vars = c("wt", "mpg", "qsec"), indep_var = "am", #' gaussian = TRUE #' ) #' # Ordinal scale: #' compare2numvars( #' data = mtcars, dep_vars = c("wt", "mpg", "qsec"), indep_var = "am", #' gaussian = FALSE #' ) #' # If dependent variable has more than 2 levels, consider fct_lump: #' mtcars |> dplyr::mutate(gear=factor(gear) |> forcats::fct_lump_n(n=1)) |> #' compare2numvars(dep_vars="wt",indep_var="gear",gaussian=TRUE) #' #' @export compare2numvars <- function(data, dep_vars, indep_var, gaussian, round_p = 3, round_desc = 2, range = FALSE, rangesep = " ", pretext = FALSE, mark = FALSE, n = FALSE, add_n = FALSE) { `.` <- Group <- Value <- Variable <- desc_groups <- NULL if (gaussian) { DESC <- meansd COMP <- t_var_test } else { DESC <- median_quart COMP <- wilcox.test } # descnames <- names(formals(DESC)) # pnames <- names(formals(COMP)) data_l <- data |> dplyr::select( Group = all_of(indep_var), all_of(dep_vars) ) |> mutate(Group = factor(Group) |> fct_drop()) |> pivot_longer(-Group,names_to = 'Variable',values_to = 'Value') |> # gather(key = Variable, value = Value, -Group) |> mutate(Variable = forcats::fct_inorder(Variable)) |> # na.omit() |> as_tibble() if(nlevels(data_l$Group)!=2){ stop(paste0('Other than 2 groups provided for ',indep_var,': ', paste(levels(data_l$Group),collapse='/'), ". Look into function compare_n_numvars.")) } data_l <- data_l |> filter(!is.na(Group)) out <- data_l |> group_by(Variable) |> do(summarise( .data = ., n_groups = paste(table(.$Group[which(!is.na(.$Value))]), collapse = ":"), desc_all = DESC(.$Value, roundDig = round_desc, range = range, rangesep = rangesep, add_n = add_n ), desc_groups = paste(try( DESC( x = .$Value, groupvar = .$Group, roundDig = round_desc, range = range, rangesep = rangesep, add_n = add_n ), silent = TRUE ), collapse = ":" ), p = formatP(try( suppressWarnings(COMP(formula = as.formula("Value~Group"), data = .)$p.value), silent = TRUE ), ndigits = round_p, pretext = pretext, mark = mark ) |> as.character() )) |> ungroup() out$desc_groups[!str_detect(out$desc_groups, ":")] <- " : " out <- separate(out, col = desc_groups, into = glue::glue("{indep_var} {levels(data_l$Group)}"), sep = ":" ) out <- separate(out, col = n_groups, into = glue::glue("n {indep_var} {levels(data_l$Group)}"), sep = ":" ) out$n <- apply(out[, 2:3], 1, function(x) { sum(as.numeric(x)) }) out <- out |> dplyr::select(1, n, starts_with("n "), everything()) if (n == FALSE) { out <- dplyr::select(out, -n, -starts_with("n ")) } return(out) } #' Comparison for columns of factors for 2 groups #' #' \code{compare2qualvars} computes \link{fisher.test} with simulated p-value and #' descriptive statistics for a group of categorical dependent variables. #' #' @param data name of data set (tibble/data.frame) to analyze. #' @param dep_vars vector of column names for dependent variables. #' @param indep_var name of grouping variable, has to translate to 2 groups. #' @param round_p level for rounding p-value. #' @param round_desc number of significant digits for rounding of descriptive stats. #' @param pretext for function [formatP]. #' @param mark for function [formatP]. #' @param singleline Put all group levels in a single line? #' @param spacer Text element to indent levels and fill empty cells, #' defaults to " ". #' @param linebreak place holder for newline. #' @param p_subgroups test subgroups by recoding other levels into other, default is not to do this. #' #' @return #' A tibble with variable names, descriptive statistics, and p-value, #' number of rows is number of dep_vars. #' #' @examples #' compare2qualvars( #' data = mtcars, dep_vars = c("gear", "cyl", "carb"), indep_var = "am", #' spacer = " " #' ) #' compare2qualvars( #' data = mtcars, dep_vars = c("gear", "cyl", "carb"), indep_var = "am", #' spacer = " ", singleline = TRUE #' ) #' compare2qualvars( #' data = mtcars, dep_vars = c("gear", "cyl", "carb"), indep_var = "am", #' spacer = " ", p_subgroups = TRUE #' ) #' @export compare2qualvars <- function(data, dep_vars, indep_var, round_p = 3, round_desc = 2, pretext = FALSE, mark = FALSE, singleline = FALSE, # newline=TRUE, spacer = " ", linebreak = "\n", p_subgroups = FALSE) { indentor <- paste0(rep(spacer, 5), collapse = "") if (!(is.factor(data |> pull(indep_var)))) { data <- data |> mutate(!!indep_var := factor(!!sym(indep_var))) } if(data |> pull(indep_var) |> nlevels() !=2){ stop(paste("Independent variable",indep_var, "has",data |> pull(indep_var) |> nlevels(), "levels but must have exactly 2.", "Look into function compare_n_qualvars.")) } for(var_i in dep_vars){ if (!(is.factor(data |> pull(var_i)))) { data <- data |> mutate(!!var_i := factor(!!sym(var_i))) } } freq <- purrr::map(data[dep_vars], .f = function(x) { cat_desc_stats( x, return_level = FALSE, singleline = singleline, ndigit = round_desc ) } ) |> purrr::map(as_tibble) levels <- purrr::map(data[dep_vars], .f = function(x) { cat_desc_stats(x, singleline = singleline )$level } ) |> purrr::map(as_tibble) freqBYgroup <- purrr::map(data[dep_vars], .f = function(x) { cat_desc_stats(x, groupvar = data[[indep_var]], return_level = FALSE, ndigit = round_desc, singleline = singleline ) } ) p <- purrr::map2(data[dep_vars], data[indep_var], .f = function(x, y) { try(formatP(try( fisher.test( x = x, y = y, simulate.p.value = TRUE, B = 10^5 )$p.value, silent = TRUE ), mark = mark, pretext = pretext ),silent=TRUE) |> as.character() } ) |> purrr::map(~case_when(str_detect(.,'.\\d+') ~ .,TRUE~'')) if(p_subgroups){ for(var_i in dep_vars){ freqBYgroup[[var_i]]$p <- NA_character_ subgroups=data |> pull(var_i) |> levels() for(sg_i in seq_along(subgroups)){ testdata <- data |> select(all_of(c(indep_var,var_i))) |> mutate(testvar=forcats::fct_collapse(!!sym(var_i), check=subgroups[sg_i], other_level = 'other')) |> select(all_of(indep_var),'testvar') |> table() if(ncol(testdata)>1) { p_sg <- fisher.test(testdata, simulate.p.value = TRUE, B = 10^5)$p.value |> formatP(mark = mark, pretext = pretext) } else{ p_sg <- '' } if(singleline){ freqBYgroup[[var_i]]$p <- paste(na.omit(freqBYgroup[[var_i]]$p),p_sg) |> str_squish()} else { freqBYgroup[[var_i]]$p[sg_i] <- p_sg } } } } out <- tibble( Variable = character(), desc_all = character(), g1 = character(), g2 = character(), p = character() ) if(p_subgroups){ out$pSubgroup <- NA_character_ } for (var_i in seq_along(dep_vars)) { if (!singleline) { out_tmp <- add_row(out[0,], Variable = c( dep_vars[var_i], glue::glue( "{indentor}{levels[[var_i]][[1]]}" ) ), desc_all = c(spacer, freq[[var_i]][[1]]), g1 = c(spacer, freqBYgroup[[var_i]][[1]]), g2 = c(spacer, freqBYgroup[[var_i]][[2]]), p = c( p[[var_i]][[1]], rep(spacer, nrow(freqBYgroup[[var_i]])) ) ) if(p_subgroups){ out_tmp$pSubgroup <- c(spacer,freqBYgroup[[var_i]]$p) } out <- rbind(out,out_tmp) } else { out_tmp <- add_row(out[0,], Variable = paste( dep_vars[var_i], # rep(spacer, # nrow(freqBYgroup[[var_i]])-1)), levels[[var_i]][[1]] ), desc_all = freq[[var_i]][[1]], g1 = freqBYgroup[[var_i]][[1]], g2 = freqBYgroup[[var_i]][[2]], p = p[[var_i]][[1]] ) if(p_subgroups){ out_tmp$pSubgroup <- freqBYgroup[[var_i]]$p } out <- rbind(out,out_tmp) } } colnames(out) <- colnames(out) |> str_replace_all( c( "g1" = paste( indep_var, data |> pull(indep_var) |> levels() |> first() ), "g2" = paste( indep_var, data |> pull(indep_var) |> levels() |> last() ) ) ) return(out) } #' Comparison for columns of factors for more than 2 groups with post-hoc #' @param data name of data set (tibble/data.frame) to analyze. #' @param dep_vars vector of column names. #' @param indep_var name of grouping variable. #' @param round_p level for rounding p-value. #' @param round_desc number of significant digits for rounding of descriptive stats #' @param pretext for function [formatP] #' @param mark for function [formatP] #' @param singleline Put all group levels in a single line? #' @param spacer Text element to indent levels, defaults to " ". #' @param linebreak place holder for newline. #' @param prettynum Apply prettyNum to results? #' #' @return #' A tibble with variable names, descriptive statistics, and p-value of \link{fisher.test} #' and \link{pairwise_fisher_test}, number of rows is number of dep_vars. #' #' @examples #' # Separate lines for each factor level: #' compare_n_qualvars( #' data = mtcars, dep_vars = c("am", "cyl", "carb"), indep_var = "gear", #' spacer = " " #' ) #' # All levels in one row but with linebreaks: #' compare_n_qualvars( #' data = mtcars, dep_vars = c("am", "cyl", "carb"), indep_var = "gear", #' singleline = TRUE #' ) #' # All levels in one row, separateted by ";": #' compare_n_qualvars( #' data = mtcars, dep_vars = c("am", "cyl", "carb"), indep_var = "gear", #' singleline = TRUE, linebreak = "; " #' ) #' @export compare_n_qualvars <- function(data, dep_vars, indep_var, round_p = 3, round_desc = 2, pretext = FALSE, mark = FALSE, singleline = FALSE, # newline=TRUE, spacer = " ", linebreak = "\n", prettynum = FALSE) { indentor <- paste0(rep(spacer, 5), collapse = "") if (!(is.factor(data |> pull(indep_var)))) { data <- data |> mutate(!!indep_var := factor(!!sym(indep_var))) } # groups <- levels(data[[indep_var]]) freq <- purrr::map(data[dep_vars], .f = function(x) { cat_desc_stats( x, return_level = FALSE, singleline = singleline, ndigit = round_desc, separator = linebreak, prettynum = prettynum ) } ) |> purrr::map(as_tibble) levels <- purrr::map(data[dep_vars], .f = function(x) { cat_desc_stats(x, singleline = singleline, separator = linebreak )$level } ) |> purrr::map(as_tibble) freqBYgroup <- purrr::map(data[dep_vars], .f = function(x) { cat_desc_stats(x, groupvar = data[[indep_var]], return_level = FALSE, ndigit = round_desc, singleline = singleline, separator = linebreak, prettynum = prettynum ) } ) p <- purrr::map2(data[dep_vars], data[indep_var], .f = function(x, y) { try( formatP( try( fisher.test( x = x, y = y, simulate.p.value = TRUE, B = 10^4 )$p.value, silent = TRUE ), mark = mark, pretext = pretext), silent=T) |> tidyr::replace_na('') } ) out <- tibble(Variable = character(), desc_all = character()) |> left_join(freqBYgroup[[1]] |> slice(0), by = character()) |> mutate(p = character()) out_template <- out groupcols <- 3:(ncol(out) - 1) for (var_i in seq_along(dep_vars)) { testdata <- data |> dplyr::select(all_of(c(indep_var, dep_vars[var_i]))) |> na.omit() pairwise_p <- pairwise_fisher_test(testdata[[2]], testdata[[1]])$sign_colwise |> str_replace("^ $", spacer) if (!singleline) { out_tmp <- add_row(out_template, Variable = c( dep_vars[var_i], str_glue( "{indentor}{levels[[var_i]][[1]]}" ) ), desc_all = c(spacer, freq[[var_i]][[1]]) ) out_tmp[1, groupcols] <- c(pairwise_p, spacer) |> as.list() out_tmp[-1, groupcols] <- freqBYgroup[[var_i]] out_tmp["p"] <- c( p[[var_i]][[1]], rep(spacer, nrow(freqBYgroup[[var_i]])) ) } else { out_tmp <- add_row(out_template, Variable = paste( dep_vars[var_i], # rep(spacer, # nrow(freqBYgroup[[var_i]])-1), levels[[var_i]][[1]] ), desc_all = freq[[var_i]][[1]] ) out_tmp[1, groupcols] <- paste(freqBYgroup[[var_i]], c(pairwise_p, spacer)) |> as.list() out_tmp["p"] <- p[[var_i]] } out <- out |> rbind(out_tmp) } return(out) } #' Pairwise Wilcoxon tests #' #' \code{pairwise_wilcox_test} calculates pairwise comparisons on ordinal data #' between all group levels with corrections for multiple testing based on #' \link{wilcox_test} from package 'coin'. #' #' @param dep_var dependent variable, containing the data. #' @param indep_var independent variable, should be factor. #' @param strat_var optional factor for stratification. #' @param adjmethod method for adjusting p values (see [p.adjust]) #' @param distr Computation of p-values, see \link{wilcox_test}. #' @param plevel threshold for significance. #' @param symbols predefined as b,c, d...; provides footnotes to mark group #' differences, e.g. b means different from group 2. #' @param sep text between statistics and range or other elements. #' #' @return #' A list with matrix of adjusted p-values and character vector with significance indicators. #' @examples #' pairwise_wilcox_test(dep_var = mtcars$wt, indep_var = mtcars$cyl) #' @export pairwise_wilcox_test <- function(dep_var, indep_var, strat_var = NA, adjmethod = "fdr", distr = "exact", plevel = .05, symbols = letters[-1], sep = "") { # if (!is.factor(indep_var)) # { indep_var <- factor(indep_var) # } ngroups <- length(levels(indep_var)) if (length(strat_var) == 1) { strat_var <- rep(1, length(dep_var)) } if (!is.factor(strat_var)) { strat_var <- factor(strat_var) } pwt_data <- tibble(dep_var, indep_var = as.numeric(indep_var), strat_var ) p_unadj <- matrix( nrow = ngroups - 1, ncol = ngroups - 1, dimnames = list(c(2:ngroups), c(1:(ngroups - 1))) ) for (firstgroup in 1:(ngroups - 1)) { for (secondgroup in (firstgroup + 1):ngroups) { tempdata <- pwt_data[c( which(pwt_data$indep_var == firstgroup), which(pwt_data$indep_var == secondgroup) ), ] tempdata$indep_var <- factor(tempdata$indep_var) # print(tempdata) if (length(levels(as.factor(tempdata$dep_var))) > 1) { p_unadj[secondgroup - 1, firstgroup] <- coin::pvalue(coin::wilcox_test(tempdata$dep_var ~ tempdata$indep_var | tempdata$strat_var, distribution = distr )) } else { p_unadj[secondgroup - 1, firstgroup] <- 1 } } } p_adj <- matrix(p.adjust(as.vector(p_unadj), method = adjmethod), byrow = FALSE, nrow = ngroups - 1, ncol = ngroups - 1, dimnames = list( group2 = levels(indep_var)[-1], group1 = levels(indep_var)[-ngroups] ) ) sign_colwise <- character() for (col_i in 1:ncol(p_adj)) { temp <- " " for (row_i in col_i:nrow(p_adj)) { if (!is.na(p_adj[row_i, col_i]) & p_adj[row_i, col_i] < plevel) { temp <- paste(temp, symbols[row_i], sep = sep) } } sign_colwise <- c(sign_colwise, temp) } return(list( p_adj = p_adj, sign_colwise = sign_colwise )) } #' Extended pairwise t-test #' #' \code{pairwise_t_test}calculate pairwise comparisons between group levels #' with corrections for multiple testing based on \link{pairwise.t.test} #' #' @param dep_var dependent variable, containing the data #' @param indep_var independent variable, should be factor #' @param adjmethod method for adjusting p values (see [p.adjust]) #' @param plevel threshold for significance #' @param symbols predefined as b,c, d...; provides footnotes to mark group #' differences, e.g. b means different from group 2 #' @return #' A list with method output of pairwise.t.test, #' matrix of p-values, and character vector with significance indicators. #' @examples #' pairwise_t_test(dep_var = mtcars$wt, indep_var = mtcars$cyl) #' @export pairwise_t_test <- function(dep_var, indep_var, adjmethod = "fdr", plevel = .05, symbols = letters[-1]) { t_out <- pairwise.t.test(x = dep_var, g = indep_var, p.adjust.method = adjmethod) p_colwise <- t_out$p.value sign_colwise <- character() for (col_i in 1:ncol(p_colwise)) { temp <- " " for (row_i in col_i:nrow(p_colwise)) { if (!is.na(p_colwise[row_i, col_i]) & p_colwise[row_i, col_i] < plevel) { temp <- paste0(temp, symbols[row_i]) } } sign_colwise <- c(sign_colwise, temp) } return(list( method = t_out$method, p.value = t_out$p.value, plevel = plevel, sign_colwise = sign_colwise )) } #' Comparison for columns of Gaussian or ordinal measures for n groups #' #' @description Some names were changed in August 2022, to reflect the update of the function to handle ordinal data using non-parametric equivalents. #' #' @param .data name of dataset (tibble/data.frame) to analyze, defaults to rawdata. #' @param dep_vars vector of column names. #' @param indep_var name of grouping variable. #' @param gaussian Logical specifying normal or ordinal indep_var (and chooses comparison tests accordingly) #' @param round_p level for rounding p-value. #' @param round_desc number of significant digits for rounding of descriptive stats. #' @param range include min/max? #' @param rangesep text between statistics and range or other elements. #' @param pretext,mark for function formatP. #' @param add_n add n to descriptive statistics? #' #' @return #' A list with elements "results": tibble with descriptive statistics, #' p-value from ANOVA/Kruskal-Wallis test, p-values for pairwise comparisons, significance #' indicators, and descriptives pasted with significance. #' "raw": nested list with output from all underlying analyses. #' #' @examples #' # Usually,only the result table is relevant: #' compare_n_numvars( #' .data = mtcars, dep_vars = c("wt", "mpg", "hp"), #' indep_var = "drat", #' gaussian = TRUE #' )$results #' # For a report, result columns may be filtered as needed: #' compare_n_numvars( #' .data = mtcars, dep_vars = c("wt", "mpg", "hp"), #' indep_var = "cyl", #' gaussian = FALSE #' )$results |> #' dplyr::select(Variable, `cyl 4 fn`:`cyl 8 fn`, multivar_p) #' @export compare_n_numvars <- function(.data = rawdata, dep_vars, indep_var, gaussian, round_desc = 2, range = FALSE, rangesep = " ", pretext = FALSE, mark = FALSE, round_p = 3, add_n = FALSE) { value <- Variable <- lm_out <- p_tout <- pANOVA <- NULL if(gaussian){ desc_fun <- wrappedtools::meansd grptest <- stats::lm } else { desc_fun <- wrappedtools::median_quart grptest <- stats::kruskal.test } # if (gaussian) { if (!is.factor(.data[[indep_var]]) | is.ordered(.data[[indep_var]])) { .data[[indep_var]] <- factor(.data[[indep_var]], ordered = FALSE )} glevel <- forcats::fct_inorder(levels(.data[[indep_var]])) .data <- dplyr::select( .data, all_of(dep_vars), all_of(indep_var) ) t <- .data |> tidyr::pivot_longer( cols = all_of(dep_vars), values_to = "value", names_to = "Variable" ) |> nest(data = c(all_of(indep_var), value)) |> mutate( Variable = forcats::fct_inorder(as.factor(Variable)), desc_tab = purrr::map_chr(data, ~ desc_fun(.$value, roundDig = round_desc, range = range, rangesep = rangesep, add_n = add_n )), desc_grp = purrr::map(data, ~ desc_fun(.$value, groupvar = .[indep_var], roundDig = round_desc, range = range, rangesep = rangesep, add_n = add_n )) |> purrr::map(~ set_names( .x, as.character(glevel) )), lm_out = if (gaussian) { purrr::map(data, ~ stats::lm(value ~ !!sym(indep_var), data = .x))}, anova_out= if (gaussian){purrr::map(lm_out, anova)} else { purrr::map(data, ~ stats::kruskal.test(value ~ !!sym(indep_var), data = .x)) }, `p_wcox/t_out` = if (gaussian) { purrr::map(data, ~ pairwise.t.test(.x[["value"]], g = .x[[indep_var]], pool.sd = TRUE, p.adjust.method = "none" )$p.value)} else { purrr::map(data, ~ pairwise.wilcox.test(.x[["value"]], g = .x[[indep_var]], p.adjust.method= "none", exact = FALSE)$p.value) }, p_wcox_t_out = if (gaussian) { purrr::map(data, ~ pairwise_t_test( .x[["value"]], .x[[indep_var]] )$sign_colwise)} else { purrr::map(data, ~ pairwise_wilcox_test( .x[["value"]], .x[[indep_var]], distr = "as" )$sign_colwise)}, p_wcox_t_out = purrr::map(p_wcox_t_out, ~ c(.x, "")) #add empty string for last column ) |> purrr::map(~ set_names(.x, dep_vars)) p_results <- NULL if (gaussian) { p_results <- "Pr(>F)" } else { p_results <- "p.value" } multivar_p <- NULL if (gaussian) { multivar_p <- "pANOVA" } else { multivar_p <- "pKW" } results <- NULL results <- tibble(Variable = forcats::fct_inorder(dep_vars), all = t$desc_tab) |> full_join(purrr::reduce(t$desc_grp, rbind) |> matrix(nrow = length(dep_vars), byrow = FALSE) |> as_tibble(.name_repair = "unique") |> mutate(Variable = dep_vars) |> dplyr::select(Variable, everything()) |> set_names(c( "Variable", paste(indep_var, glevel) ))) |> full_join(purrr::map_df(t$anova_out, p_results) |> slice(1) |> pivot_longer(everything(),names_to = 'Variable', values_to = 'multivar_p') |> # gather(key = "Variable", value = multivar_p)|> mutate(Variable = forcats::fct_inorder(Variable)) |> mutate(multivar_p = formatP(multivar_p, ndigits = round_p, pretext = pretext, mark = mark))) |> #as.vector()|> full_join(purrr::map_df(t$`p_wcox/t_out`, ~ paste(formatP( p.adjust(.x[lower.tri(.x, TRUE)], method = "fdr")), collapse = ";")) |> pivot_longer(everything(),names_to = 'Variable', values_to = 'p between groups')) |> # gather(key = "Variable", value = "p between groups")) |> full_join(purrr::reduce(t$p_wcox_t_out, rbind) |> matrix(nrow = length(dep_vars), byrow = FALSE) |> as_tibble(.name_repair = "unique") |> mutate(Variable = dep_vars) |> set_names(c(paste("sign", glevel), "Variable"))) |> full_join(purrr::map_df(t$`p_wcox/t_out`, ~ paste(formatP(p.adjust(.x[, 1], method = "fdr" )), collapse = ";" )) |> pivot_longer(everything(),names_to = 'Variable', values_to = 'p vs.ref')) # gather(key = "Variable", value = "p vs.ref")) results <- cbind( results, purrr::map2_df( .x = dplyr::select(results, starts_with(indep_var)), .y = dplyr::select(results, starts_with("sign")), .f = paste ) |> rename_all(paste, "fn") ) |> as_tibble(.name_repair = "unique") # todo: p vs. ref symbol return( list(results = results, raw = t)) } utils::globalVariables('p_wcox_t_out')
/scratch/gouwar.j/cran-all/cranData/wrappedtools/R/tests.R
#' @keywords internal "_PACKAGE" ## usethis namespace: start #' @importFrom lifecycle deprecated ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/wrappedtools/R/wrappedtools-package.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup, include=FALSE----------------------------------------------------- library(wrappedtools) ## ----include=FALSE------------------------------------------------------------ library(wrappedtools) ## ----example1----------------------------------------------------------------- # Standard functions to obtain median and quartiles: median(mtcars$mpg) quantile(mtcars$mpg,probs = c(.25,.75)) # wrappedtools adds rounding and pasting: median_quart(mtcars$mpg) # on a higher level, this logic leads to compare2numvars(data = mtcars, dep_vars = c('wt','mpg', "disp"), indep_var = 'am', gaussian = F, round_desc = 3) ## ----example2----------------------------------------------------------------- somedata <- rnorm(100) ks.test(x = somedata, 'pnorm', mean=mean(somedata), sd=sd(somedata)) ksnormal(somedata) ## ----example3----------------------------------------------------------------- gaussvars <- FindVars(varnames = c('wt','mpg'), allnames = colnames(mtcars)) gaussvars #Exclusion based on pattern factorvars <- FindVars(varnames = c('a','cy'), allnames = colnames(mtcars), exclude = c('t')) factorvars$names
/scratch/gouwar.j/cran-all/cranData/wrappedtools/inst/doc/wrappedtools.R
--- title: "Usage of 'wrappedtools'" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Usage of 'wrappedtools'} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: markdown: wrap: 72 --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup, include=FALSE} library(wrappedtools) ``` # 'wrappedtools' <a><img src='https://github.com/abusjahn/wrappedtools/blob/main/vignettes/wrappedtools_hex.png' align="right" height="139" /></a> <!-- badges: start --> <!-- badges: end --> The goal of 'wrappedtools' is to make my (and possibly your) life a bit easier by a set of convenience functions for many common tasks like e.g. computation of mean and SD and pasting them with ±. Instead of\ paste(round(mean(x),some_level), round(sd(x),some_level), sep='±')\ a simple meansd(x, roundDig = some_level) is enough. ## Installation You can install the released version of 'wrappedtools' from github with: ``` {.r} devtools::install_github("abusjahn/wrappedtools") ``` ```{r include=FALSE} library(wrappedtools) ``` ## Examples This is a basic example which shows you how to solve a common problem, that is, describe and test differences in some measures between 2 samples, rounding descriptive statistics to a reasonable precision in the process: ```{r example1} # Standard functions to obtain median and quartiles: median(mtcars$mpg) quantile(mtcars$mpg,probs = c(.25,.75)) # wrappedtools adds rounding and pasting: median_quart(mtcars$mpg) # on a higher level, this logic leads to compare2numvars(data = mtcars, dep_vars = c('wt','mpg', "disp"), indep_var = 'am', gaussian = F, round_desc = 3) ``` To explain the '**wrapper**' part of the package name, here is another example, using the ks.test as test for a Normal distribution, where ksnormal simply wrapps around the ks.test function: ```{r example2} somedata <- rnorm(100) ks.test(x = somedata, 'pnorm', mean=mean(somedata), sd=sd(somedata)) ksnormal(somedata) ``` Saving variable selections: Variables may fall into different groups: Some are following a Gaussian distribution, others are ordinal or factorial. There may be several grouping variables like treatment, gender... To refer to such variables, it is convenient to have their index and name stored. The name may be needed as character or , symbol, complex variable names like "size [cm]" may need to be surrounded by backticks in some function calls but must not have those in others.\ Function FindVars finds columns in tibbles or dataframes, based on name pattern. This is comparable to the selection helpers in 'tidyselect', but does not select the content of matching variables, but names, positions, and count: ```{r example3} gaussvars <- FindVars(varnames = c('wt','mpg'), allnames = colnames(mtcars)) gaussvars #Exclusion based on pattern factorvars <- FindVars(varnames = c('a','cy'), allnames = colnames(mtcars), exclude = c('t')) factorvars$names ``` This should give you the general idea, I'll try to expand this intro over time...
/scratch/gouwar.j/cran-all/cranData/wrappedtools/inst/doc/wrappedtools.Rmd
--- title: "Usage of 'wrappedtools'" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Usage of 'wrappedtools'} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: markdown: wrap: 72 --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup, include=FALSE} library(wrappedtools) ``` # 'wrappedtools' <a><img src='https://github.com/abusjahn/wrappedtools/blob/main/vignettes/wrappedtools_hex.png' align="right" height="139" /></a> <!-- badges: start --> <!-- badges: end --> The goal of 'wrappedtools' is to make my (and possibly your) life a bit easier by a set of convenience functions for many common tasks like e.g. computation of mean and SD and pasting them with ±. Instead of\ paste(round(mean(x),some_level), round(sd(x),some_level), sep='±')\ a simple meansd(x, roundDig = some_level) is enough. ## Installation You can install the released version of 'wrappedtools' from github with: ``` {.r} devtools::install_github("abusjahn/wrappedtools") ``` ```{r include=FALSE} library(wrappedtools) ``` ## Examples This is a basic example which shows you how to solve a common problem, that is, describe and test differences in some measures between 2 samples, rounding descriptive statistics to a reasonable precision in the process: ```{r example1} # Standard functions to obtain median and quartiles: median(mtcars$mpg) quantile(mtcars$mpg,probs = c(.25,.75)) # wrappedtools adds rounding and pasting: median_quart(mtcars$mpg) # on a higher level, this logic leads to compare2numvars(data = mtcars, dep_vars = c('wt','mpg', "disp"), indep_var = 'am', gaussian = F, round_desc = 3) ``` To explain the '**wrapper**' part of the package name, here is another example, using the ks.test as test for a Normal distribution, where ksnormal simply wrapps around the ks.test function: ```{r example2} somedata <- rnorm(100) ks.test(x = somedata, 'pnorm', mean=mean(somedata), sd=sd(somedata)) ksnormal(somedata) ``` Saving variable selections: Variables may fall into different groups: Some are following a Gaussian distribution, others are ordinal or factorial. There may be several grouping variables like treatment, gender... To refer to such variables, it is convenient to have their index and name stored. The name may be needed as character or , symbol, complex variable names like "size [cm]" may need to be surrounded by backticks in some function calls but must not have those in others.\ Function FindVars finds columns in tibbles or dataframes, based on name pattern. This is comparable to the selection helpers in 'tidyselect', but does not select the content of matching variables, but names, positions, and count: ```{r example3} gaussvars <- FindVars(varnames = c('wt','mpg'), allnames = colnames(mtcars)) gaussvars #Exclusion based on pattern factorvars <- FindVars(varnames = c('a','cy'), allnames = colnames(mtcars), exclude = c('t')) factorvars$names ``` This should give you the general idea, I'll try to expand this intro over time...
/scratch/gouwar.j/cran-all/cranData/wrappedtools/vignettes/wrappedtools.Rmd
#' Checks if variable exists in environment and returns back or creates a new variable #' #' @param var character. The name of the variable to check in the global environment. #' @param func function. A function that returns a value. #' @param ... Additional arguments to be passed to the param func. #' @param exists_func_args list. A list of arguments to use in base::exists. #' @param get_func_args list. A list of arguments to use in bass::get. #' @param warning_msg character. Message sent to stop function if an error occurs. #' #' @return Unknown. The return type from the param func or the existing variable in global environment. #' #' @examples #' \dontrun{ #' df <- data.frame(col_1 = c("a","b","c"), col_2 = c(1,2,3)) #' #' create_blank_df <- function() { #' #' data.frame(col_1 = NA_character_, col_2 = NA_integer_) #' #' } #' #' df_1 <- get_cache_or_create( #' "df", #' create_blank_df #' ) #' #' df_2 <- get_cache_or_create( #' "df_2", #' create_blank_df #' ) #' } #' @export get_cache_or_create <- function( var, func, ..., exists_func_args = NA, get_func_args = NA, warning_msg = NA_character_ ) { if (is.list(exists_func_args)) { exists_func_args$x <- var var_exists <- do.call(exists, exists_func_args) } else { var_exists <- exists(var) } if (!var_exists) { tryCatch({ return_var <- func(...) }, error = function(e) { if (!is.na(warning_msg) & is.character(warning_msg)) { warning(warning_msg) } stop(e$message, call. = FALSE) } ) } else { if (is.list(get_func_args)) { get_func_args$x <- var return_var <- do.call(get, get_func_args) } else { return_var <- get(var) } } return_var }
/scratch/gouwar.j/cran-all/cranData/wrappr/R/get_cache_or_create.R
#' save and Delay a function call with the option to change the function and arguments when called #' #' @importFrom methods is #' @param ... Additional arguments to be passed to the param .f. Also in closure function returned. #' @param .f function. A function that will be called when needed. Also in closure function returned. #' #' @return closure function with same param names plus the param names overwrite_args Boolean and return_new_closure Boolean. #' #' @examples #' #' numbers <- c(1,2,3,4,5) #' #' func <- lazy_eval(numbers, .f = sum) #' #' sum_result <- func() #' #' max_result <- func(.f = max) #' #' mean_result <- func(.f = mean) #' #' range_result <- func(.f = function(...) { max(...) - min(...)}) #' #' add_more_num_result <- func(4,5,6, NA, na.rm = TRUE) #' #' updated_func <- func(na.rm = TRUE, return_new_closure = TRUE) #' #' updated_func_result <- updated_func() #' #' @export lazy_eval <- function(..., .f) { if (!("function" %in% is(.f))) { stop("A function is required to be passed into the param `.f` in lazy_eval.") } current_func_args <- list(...) # Check if a list has been passed into the function so it can unlist the top list # without removing the original data types. Required if lazy_eval called via recursion. if (length(current_func_args) > 0) { if (is.list(current_func_args[[1]])) { current_func_args <- current_func_args[[1]] } } func <- .f return_func <- function(..., .f = NA, overwrite_args = FALSE, return_new_closure = FALSE) { new_func_args <- list(...) if (length(new_func_args) > 0) { if (overwrite_args) { current_func_args <- new_func_args } else { names_of_new_func_args <- names(new_func_args) for (name in names_of_new_func_args) { if (name %in% names(current_func_args)) { current_func_args[[name]] <- new_func_args[[name]] new_func_args[[name]] <- NULL } } if (length(new_func_args) > 0 ) { current_func_args <- c(current_func_args, new_func_args) } } } if("function" %in% is(.f)) { func <- .f } else if(!is.na(.f)) { current_function_name <- deparse(func) warning_msg_non_func_arg <- paste0( "A function was not passed into the closure function param `.f`", " The original function `", current_function_name, "` that was used ", "in lazy_eval function call has been used instead." ) warning(warning_msg_non_func_arg, call. = FALSE) } if (return_new_closure) { return(wrappr::lazy_eval(current_func_args, .f = func)) } return(do.call(func, current_func_args)) } return_func }
/scratch/gouwar.j/cran-all/cranData/wrappr/R/lazy_eval.R
#' Wraps a message before and/or after a function #' #' @param func function. #' @param ... Additional arguments to be passed into the param func. #' @param before_func_msg character. #' @param after_func_msg character. #' @param print_func function. The default is print. Can use related function like message. #' @param use_msg character. The default is "both". Selects which messages to print in the function. Use `before`, `after`, `both` or `none`. #' @param print_return_var Boolean. The default is FALSE. Prints the output from the called func using the print argument from param print_func. #' #' @return Unknown. The return type from the param func. #' #' @examples #' #' numbers <- c(1,2,3,4,5) #' #' answer <- msg_wrap( #' sum, #' numbers, #' before_func_msg = "Currently summing the numbers", #' after_func_msg = "Summing the numbers complete" #' ) #' #' numbers_with_na <- c(1,2,3,NA,5) #' #' answer_na_removed <- msg_wrap( #' sum, #' numbers, #' na.rm = TRUE, #' before_func_msg = "Sum with na.rm set to TRUE", #' use_msg = "before" #' ) # #' #' numbers_to_sum <- c(10,20,30) #' #' msg_wrap((function(x) sum(x[x%%2 == 1])), #' x = numbers_to_sum, #' before_func_msg = "Result from sum of odd numbers", #' use_msg = "before", #' print_return_var = TRUE #' ) #' #' @export msg_wrap <- function(func, ..., before_func_msg = "", after_func_msg = "", print_func = print, use_msg = "both", print_return_var = FALSE) { stopifnot(use_msg %in% c("before", "after", "both", "none")) if (any(use_msg == "before", use_msg == "both")) { print_func(before_func_msg) } return_var <- func(...) if (print_return_var) { print_func(return_var) } if (any(use_msg == "after", use_msg == "both")) { print_func(after_func_msg) } return_var }
/scratch/gouwar.j/cran-all/cranData/wrappr/R/msg_wrap.R
#' Sets a temporary working directory within the function scope #' #' @param temp_cwd character. Folder path to temporarily set the working directory #' @param func function. A function that used a directory path #' @param ... Additional arguments to be passed to the param func. #' @param err_msg character. Message sent to stop function if an error occurs. #' #' @return Unknown. The return type from the param func. #' #' @examples #' \dontrun{ #' #' temp_wd <- "example/folder/address/to/change" #' #' get_data <- set_temp_wd(temp_wd, read.csv, file = "file.csv") #' #' } #' @export set_temp_wd <- function(temp_cwd, func, ..., err_msg = "An error has occured in the function set_temp_wd") { current_wd <- getwd() on.exit(setwd(current_wd)) tryCatch({ setwd(temp_cwd) return_var <- func(...) }, error = function(e) { warning(e) stop(err_msg, call. = FALSE) }) setwd(current_wd) return_var }
/scratch/gouwar.j/cran-all/cranData/wrappr/R/set_temp_wd.R
#' Build a custom writeback function that writes state into a user named variable. #' #' #' @param varName character where to write captured state #' @return writeback function for use with functions such as \code{\link{DebugFnW}} #' #' @examples #' #' # user function #' f <- function(i) { (1:10)[[i]] } #' # capture last error in variable called "lastError" #' writeBack <- buildNameCallback('lastError') #' # wrap function with writeBack #' df <- DebugFnW(writeBack,f) #' # capture error (Note: tryCatch not needed for user code!) #' tryCatch( #' df(12), #' error = function(e) { print(e) }) #' # examine error #' str(lastError) #' # redo call, perhaps debugging #' tryCatch( #' do.call(lastError$fn_name, lastError$args), #' error = function(e) { print(e) }) #' #' @export buildNameCallback <- function(varName) { curEnv <- parent.frame() writeBack <- function(sit) { assign('lastError', sit, envir=curEnv) } attr(writeBack,'name') <- paste0('writing to variable: "', varName, '"') writeBack } #' Return an error to a file, environment (no names) or callback #' #' @param e caught exception #' @param saveDest where to save #' @param cap saved arguments #' @param wrapperName name of wrapper #' @param recallString how to call function again #' #' @keywords internal #' #' @export #' returnCapture <- function(e, saveDest, cap, wrapperName, recallString = 'do.call(p$fn, p$args)') { es <- trimws(paste(as.character(e), collapse = ' ')) if(is.null(saveDest)) { saveDest <- paste0(tempfile('debug'),'.RDS') } if(is.name(saveDest)) { curEnv <- globalenv() assign(as.character(saveDest), cap, envir=curEnv) return(paste0("wrapr::", wrapperName, ": wrote error to globalenv() variable '", as.character(saveDest), "'", "\n You can reproduce the error with:", "\n '", recallString, "' (replace 'p' with actual variable name)")) } if(is.function(saveDest)) { saveDest(cap) fName <- attr(saveDest, 'name') if(!is.null(fName)) { return(paste0("wrapr::", wrapperName, ": wrote error to user function: '", fName, "' on catching '", es, "'", "\n You can reproduce the error with:", "\n '", recallString, "' (replace 'p' with actual variable name)")) } return(paste0("wrapr::", wrapperName, ": wrote error to user function on catching '", es, "'", "\n You can reproduce the error with:", "\n '", recallString, "' (replace 'p' with actual variable name)")) } if(is.character(saveDest)) { saveRDS(object=cap, file=saveDest) return(paste0("wrapr::", wrapperName, ": wrote '",saveDest, "' on catching '",es,"'", "\n You can reproduce the error with:", "\n'p <- readRDS('",saveDest, "'); ", recallString, "'")) } return(paste0("wrapr::", wrapperName, ": don't know how to write error to '", paste(class(saveDest), collapse= " "), "' on catching '", es, "'")) } #' Capture arguments of exception throwing function call for later debugging. #' #' Run fn, save arguments on failure. #' Please see: \code{vignette("DebugFnW", package="wrapr")}. #' @seealso \code{\link[utils:debugger]{dump.frames}}, \code{\link{DebugFn}}, \code{\link{DebugFnW}}, \code{\link{DebugFnWE}}, \code{\link{DebugPrintFn}}, \code{\link{DebugFnE}}, \code{\link{DebugPrintFnE}} #' #' @param saveDest where to write captured state (determined by type): NULL random temp file, character temp file, name globalenv() variable, and function triggers callback. #' @param fn function to call #' @param ... arguments for fn #' @return fn(...) normally, but if fn(...) throws an exception save to saveDest RDS of list r such that do.call(r$fn,r$args) repeats the call to fn with args. #' #' @examples #' #' saveDest <- paste0(tempfile('debug'),'.RDS') #' f <- function(i) { (1:10)[[i]] } #' # correct run #' DebugFn(saveDest, f, 5) #' # now re-run #' # capture error on incorrect run #' tryCatch( #' DebugFn(saveDest, f, 12), #' error = function(e) { print(e) }) #' # examine details #' situation <- readRDS(saveDest) #' str(situation) #' # fix and re-run #' situation$args[[1]] <- 6 #' do.call(situation$fn_name,situation$args) #' # clean up #' file.remove(saveDest) #' #' @export DebugFn <- function(saveDest,fn,...) { args <- list(...) envir <- parent.frame() namedargs <- match.call() fn_name <- as.character(namedargs[['fn']]) force(saveDest) force(fn) tryCatch({ do.call(fn, args, envir=envir) }, error = function(e) { cap <- list(fn=fn, args=args, fn_name=fn_name) es <- wrapr::returnCapture(e, saveDest, cap, "DebugFn") stop(es) }) } #' Wrap a function for debugging. #' #' Wrap fn, so it will save arguments on failure. #' @seealso \code{\link[utils:debugger]{dump.frames}}, \code{\link{DebugFn}}, \code{\link{DebugFnW}}, \code{\link{DebugFnWE}}, \code{\link{DebugPrintFn}}, \code{\link{DebugFnE}}, \code{\link{DebugPrintFnE}} #' Operator idea from: https://gist.github.com/nassimhaddad/c9c327d10a91dcf9a3370d30dff8ac3d . #' Please see: \code{vignette("DebugFnW", package="wrapr")}. #' #' @param saveDest where to write captured state (determined by type): NULL random temp file, character temp file, name globalenv() variable, and function triggers callback. #' @param fn function to call #' @return wrapped function that saves state on error. #' #' @examples #' #' saveDest <- paste0(tempfile('debug'),'.RDS') #' f <- function(i) { (1:10)[[i]] } #' df <- DebugFnW(saveDest,f) #' # correct run #' df(5) #' # now re-run #' # capture error on incorrect run #' tryCatch( #' df(12), #' error = function(e) { print(e) }) #' # examine details #' situation <- readRDS(saveDest) #' str(situation) #' # fix and re-run #' situation$args[[1]] <- 6 #' do.call(situation$fn,situation$args) #' # clean up #' file.remove(saveDest) #' #' #' f <- function(i) { (1:10)[[i]] } #' curEnv <- environment() #' writeBack <- function(sit) { #' assign('lastError', sit, envir=curEnv) #' } #' attr(writeBack,'name') <- 'writeBack' #' df <- DebugFnW(writeBack,f) #' tryCatch( #' df(12), #' error = function(e) { print(e) }) #' str(lastError) #' #' #' @export DebugFnW <- function(saveDest,fn) { namedargs <- match.call() fn_name <- as.character(namedargs[['fn']]) force(saveDest) force(fn) f2 <- function(...) { args <- list(...) envir <- parent.frame() namedargs <- match.call() tryCatch({ do.call(fn, args, envir=envir) }, error = function(e) { cap <- list(fn=fn, args=args, namedargs=namedargs, fn_name=fn_name) es <- wrapr::returnCapture(e, saveDest, cap, "DebugFnW") stop(es) }) } newenv <- new.env(parent = environment(fn)) assign('fn', fn, envir = newenv) assign('fn_name', fn_name, envir = newenv) assign('saveDest', saveDest, envir = newenv) environment(f2) <- newenv f2 } #' Capture arguments of exception throwing function call for later debugging. #' #' Run fn and print result, save arguments on failure. Use on systems like \code{ggplot()} #' where some calculation is delayed until \code{print()}. #' Please see: \code{vignette("DebugFnW", package="wrapr")}. #' #' @seealso \code{\link[utils:debugger]{dump.frames}}, \code{\link{DebugFn}}, \code{\link{DebugFnW}}, \code{\link{DebugFnWE}}, \code{\link{DebugPrintFn}}, \code{\link{DebugFnE}}, \code{\link{DebugPrintFnE}} #' #' @param saveDest where to write captured state (determined by type): NULL random temp file, character temp file, name globalenv() variable, and function triggers callback. #' @param fn function to call #' @param ... arguments for fn #' @return fn(...) normally, but if fn(...) throws an exception save to saveDest RDS of list r such that do.call(r$fn,r$args) repeats the call to fn with args. #' #' @examples #' #' saveDest <- paste0(tempfile('debug'),'.RDS') #' f <- function(i) { (1:10)[[i]] } #' # correct run #' DebugPrintFn(saveDest, f, 5) #' # now re-run #' # capture error on incorrect run #' tryCatch( #' DebugPrintFn(saveDest, f, 12), #' error = function(e) { print(e) }) #' # examine details #' situation <- readRDS(saveDest) #' str(situation) #' # fix and re-run #' situation$args[[1]] <- 6 #' do.call(situation$fn,situation$args) #' # clean up #' file.remove(saveDest) #' #' @export DebugPrintFn <- function(saveDest,fn,...) { args <- list(...) namedargs <- match.call() fn_name <- as.character(namedargs[['fn']]) envir <- parent.frame() force(saveDest) force(fn) tryCatch({ res = do.call(fn, args, envir=envir) print(res) res }, error = function(e) { cap <- list(fn=fn, args=args, fn_name=fn_name) es <- wrapr::returnCapture(e, saveDest, cap, "DebugPrintFn") stop(es) }) } #' Capture arguments and environment of exception throwing function call for later debugging. #' #' Run fn, save arguments, and environment on failure. #' Please see: \code{vignette("DebugFnW", package="wrapr")}. #' @seealso \code{\link[utils:debugger]{dump.frames}}, \code{\link{DebugFn}}, \code{\link{DebugFnW}}, \code{\link{DebugFnWE}}, \code{\link{DebugPrintFn}}, \code{\link{DebugFnE}}, \code{\link{DebugPrintFnE}} #' #' @param saveDest where to write captured state (determined by type): NULL random temp file, character temp file, name globalenv() variable, and function triggers callback. #' @param fn function to call #' @param ... arguments for fn #' @return fn(...) normally, but if fn(...) throws an exception save to saveDest RDS of list r such that do.call(r$fn,r$args) repeats the call to fn with args. #' #' @examples #' #' saveDest <- paste0(tempfile('debug'),'.RDS') #' f <- function(i) { (1:10)[[i]] } #' # correct run #' DebugFnE(saveDest, f, 5) #' # now re-run #' # capture error on incorrect run #' tryCatch( #' DebugFnE(saveDest, f, 12), #' error = function(e) { print(e) }) #' # examine details #' situation <- readRDS(saveDest) #' str(situation) #' # fix and re-run #' situation$args[[1]] <- 6 #' do.call(situation$fn, situation$args, envir=situation$env) #' # clean up #' file.remove(saveDest) #' #' @export DebugFnE <- function(saveDest,fn,...) { args <- list(...) envir <- parent.frame() namedargs <- match.call() fn_name <- as.character(namedargs[['fn']]) force(saveDest) force(fn) tryCatch({ do.call(fn, args, envir=envir) }, error = function(e) { cap <- list(fn=fn, args=args, env=envir, fn_name=fn_name) es <- wrapr::returnCapture(e, saveDest, cap, "DebugFnE", recallString = 'do.call(p$fn, p$args, envir= p$env)') stop(es) }) } #' Wrap function to capture arguments and environment of exception throwing function call for later debugging. #' #' Wrap fn, so it will save arguments and environment on failure. #' Please see: \code{vignette("DebugFnW", package="wrapr")}. #' @seealso \code{\link[utils:debugger]{dump.frames}}, \code{\link{DebugFn}}, \code{\link{DebugFnW}}, \code{\link{DebugFnWE}}, \code{\link{DebugPrintFn}}, \code{\link{DebugFnE}}, \code{\link{DebugPrintFnE}} #' #' Idea from: https://gist.github.com/nassimhaddad/c9c327d10a91dcf9a3370d30dff8ac3d #' #' @param saveDest where to write captured state (determined by type): NULL random temp file, character temp file, name globalenv() variable, and function triggers callback. #' @param fn function to call #' @param ... arguments for fn #' @return wrapped function that captures state on error. #' #' @examples #' #' saveDest <- paste0(tempfile('debug'),'.RDS') #' f <- function(i) { (1:10)[[i]] } #' df <- DebugFnWE(saveDest, f) #' # correct run #' df(5) #' # now re-run #' # capture error on incorrect run #' tryCatch( #' df(12), #' error = function(e) { print(e) }) #' # examine details #' situation <- readRDS(saveDest) #' str(situation) #' # fix and re-run #' situation$args[[1]] <- 6 #' do.call(situation$fn, situation$args, envir=situation$env) #' # clean up #' file.remove(saveDest) #' #' @export DebugFnWE <- function(saveDest,fn,...) { namedargs <- match.call() fn_name <- as.character(namedargs[['fn']]) force(saveDest) force(fn) f2 <- function(...) { args <- list(...) envir <- parent.frame() namedargs <- match.call() tryCatch({ do.call(fn, args, envir=envir) }, error = function(e) { cap <- list(fn=fn, args=args, namedargs=namedargs, fn_name=fn_name, env=envir) es <- wrapr::returnCapture(e, saveDest, cap, "DebugFnWE", recallString = 'do.call(p$fn, p$args, envir= p$env)') stop(es) }) } newenv <- new.env(parent = environment(fn)) assign('fn', fn, envir = newenv) assign('fn_name', fn_name, envir = newenv) assign('saveDest', saveDest, envir = newenv) environment(f2) <- newenv f2 } #' Capture arguments and environment of exception throwing function call for later debugging. #' #' Run fn and print result, save arguments and environment on failure. Use on systems like ggplot() #' where some calculation is delayed until print(). #' Please see: \code{vignette("DebugFnW", package="wrapr")}. #' @seealso \code{\link[utils:debugger]{dump.frames}}, \code{\link{DebugFn}}, \code{\link{DebugFnW}}, \code{\link{DebugFnWE}}, \code{\link{DebugPrintFn}}, \code{\link{DebugFnE}}, \code{\link{DebugPrintFnE}} #' #' @param saveDest where to write captured state (determined by type): NULL random temp file, character temp file, name globalenv() variable, and function triggers callback. #' @param fn function to call #' @param ... arguments for fn #' @return fn(...) normally, but if fn(...) throws an exception save to saveDest RDS of list r such that do.call(r$fn,r$args) repeats the call to fn with args. #' #' @examples #' #' saveDest <- paste0(tempfile('debug'),'.RDS') #' f <- function(i) { (1:10)[[i]] } #' # correct run #' DebugPrintFnE(saveDest, f, 5) #' # now re-run #' # capture error on incorrect run #' tryCatch( #' DebugPrintFnE(saveDest, f, 12), #' error = function(e) { print(e) }) #' # examine details #' situation <- readRDS(saveDest) #' str(situation) #' # fix and re-run #' situation$args[[1]] <- 6 #' do.call(situation$fn, situation$args, envir=situation$env) #' # clean up #' file.remove(saveDest) #' #' @export DebugPrintFnE <- function(saveDest,fn,...) { args <- list(...) envir <- parent.frame() namedargs <- match.call() fn_name <- as.character(namedargs[['fn']]) force(saveDest) force(fn) tryCatch({ res = do.call(fn, args, envir=envir) print(res) res }, error = function(e) { cap <- list(fn=fn, args=args, env=envir, fn_name=fn_name) es <- wrapr::returnCapture(e, saveDest, cap, "DebugPrintFnE", recallString = 'do.call(p$fn, p$args, envir= p$env)') stop(es) }) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/DebugFn.R
#' Use function to reduce or expand arguments. #' #' \code{x \%.|\% f} stands for \code{f(x[[1]], x[[2]], ..., x[[length(x)]])}. #' \code{v \%|.\% x} also stands for \code{f(x[[1]], x[[2]], ..., x[[length(x)]])}. #' The two operators are the same, the variation just allowing the user to choose the order they write things. #' The mnemonic is: "data goes on the dot-side of the operator." #' #' Note: the reduce operation is implemented by \code{do.call()}, so has #' standard R named argument semantics. #' #' @param f function. #' @param args argument list or vector, entries expanded as function arguments. #' @return f(args) where args elements become individual arguments of f. #' #' @seealso \code{\link[base]{do.call}}, \code{\link[base]{list}}, \code{\link[base]{c}} #' #' @examples #' #' args <- list('prefix_', c(1:3), '_suffix') #' args %.|% paste0 #' # prefix_1_suffix" "prefix_2_suffix" "prefix_3_suffix" #' paste0 %|.% args #' # prefix_1_suffix" "prefix_2_suffix" "prefix_3_suffix" #' #' @name reduceexpand NULL reduceexpand <- function(f, args, env = parent.frame()) { force(env) fnam <- wrapr_deparse(f) if(is.name(f) || is.character(f)) { # name of function case as in c(1, 2, 3) %.|% sum f <- get(as.character(f), env) } else if(is.call(f) && (length(f)==3) && isTRUE(as.character(f[[1]])=="::") && is.name(f[[2]]) && is.name(f[[3]])) { # package qualified name of function as in c(1, 2, 3) %.|% base::sum f <- eval(f, envir = env, enclos = env) } else if(is.call(f) && isTRUE(as.character(f[[1]])=="function")) { # function def as in c(1, 2, 3) %.|% function(...) { sum(...) } f <- eval(f, envir = env, enclos = env) } if(!is.function(f)) { stop(paste("wrapr::reduceexpand function argument f (", fnam, ") must de-reference to a function")) } if(!is.list(args)) { args <- as.list(args) } do.call(f, args, envir = env) } #' @describeIn reduceexpand f reduce args #' @export `%|.%` <- function(f, args) { f <- substitute(f) env <- parent.frame() reduceexpand(f, args, env) } #' @describeIn reduceexpand args expand f #' @export `%.|%` <- function(args, f) { f <- substitute(f) env <- parent.frame() reduceexpand(f, args, env) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/Reduce.R
/scratch/gouwar.j/cran-all/cranData/wrapr/R/Untitled.R
#' Memoizing wrapper for parLapplyLB #' #' #' @seealso \code{\link[parallel:clusterApply]{parLapplyLB}}, \code{\link{lapplym}}, \code{\link{VectorizeM}}, \code{\link{vapplym}} #' #' @param cl cluster object #' @param X list or vector of inputs #' @param fun function to apply #' @param ... additional arguments passed to lapply #' @param chunk.size passed to \code{parallel::parLapplyLB} #' @return list of results. #' #' @examples #' #' if(requireNamespace("parallel", quietly = TRUE)) { #' cl <- parallel::makeCluster(2) #' fs <- function(x) { x <- x[[1]]; Sys.sleep(1); sin(x) } #' # without memoization should take 1000 seconds #' lst <- parLapplyLBm(cl, c(rep(0, 1000), rep(1, 1000)), fs) #' parallel::stopCluster(cl) #' } #' #' @export #' parLapplyLBm <- function(cl = NULL, X, fun, ..., chunk.size = NULL) { if(!requireNamespace("parallel", quietly = TRUE)) { stop("wrapr::parLapplyLBm requires the parallel package") } UX <- unique(X) first_indexes <- match(UX, X) all_indexes <- match(X, UX) if(length(chunk.size)<=0) { res <- parallel::parLapplyLB(cl, X[first_indexes], fun, ...) } else { res <- parallel::parLapplyLB(cl, X[first_indexes], fun, ..., chunk.size = chunk.size) } res2 <- res[all_indexes] names(res2) <- names(X) res2 } #' Memoizing wrapper for lapply. #' #' #' @seealso \code{\link{VectorizeM}}, \code{\link{vapplym}}, \code{\link{parLapplyLBm}} #' #' @param X list or vector of inputs #' @param FUN function to apply #' @param ... additional arguments passed to lapply #' @return list of results. #' #' @examples #' #' fs <- function(x) { x <- x[[1]]; print(paste("see", x)); sin(x) } #' # should only print "see" twice, not 6 times #' lapplym(c(0, 1, 1, 0, 0, 1), fs) #' #' @export #' lapplym <- function(X, FUN, ...) { UX <- unique(X) first_indexes <- match(UX, X) all_indexes <- match(X, UX) res <- lapply(X[first_indexes], FUN, ...) res2 <- res[all_indexes] names(res2) <- names(X) res2 } #' Memoizing wrapper for vapply. #' #' #' @seealso \code{\link{VectorizeM}}, \code{\link{lapplym}} #' #' @param X list or vector of inputs #' @param FUN function to apply #' @param FUN.VALUE type of vector to return #' @param ... additional arguments passed to lapply #' @param USE.NAMES passed to vapply #' @return vector of results. #' #' @examples #' #' fs <- function(x) { x <- x[[1]]; print(paste("see", x)); sin(x) } #' # should only print "see" twice, not 6 times #' vapplym(c(0, 1, 1, 0, 0, 1), fs, numeric(1)) #' #' @export #' vapplym <- function(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE) { UX <- unique(X) first_indexes <- match(UX, X) all_indexes <- match(X, UX) res <- vapply(X[first_indexes], FUN, FUN.VALUE, ..., USE.NAMES = USE.NAMES) res2 <- res[all_indexes] if(USE.NAMES) { names(res2) <- names(X) } res2 } #' Memoizing wrapper to base::Vectorize() #' #' Build a wrapped function that applies to each unique argument in a vector of arguments once. #' #' Only sensible for pure side-effect free deterministic functions. #' #' @seealso \code{\link[base]{Vectorize}}, \code{\link{vapplym}}, \code{\link{lapplym}} #' #' #' #' @param FUN function to apply #' @param vectorize.args a character vector of arguments which should be vectorized. Defaults to first argument of FUN. If set must be length 1. #' @param SIMPLIFY logical or character string; attempt to reduce the result to a vector, matrix or higher dimensional array; see the simplify argument of sapply. #' @param USE.NAMES logical; use names if the first ... argument has names, or if it is a character vector, use that character vector as the names. #' @param UNLIST logical; if TRUE try to unlist the result. #' @return adapted function (vectorized with one call per different value). #' #' @examples #' #' fs <- function(x) { x <- x[[1]]; print(paste("see", x)); sin(x) } #' fv <- VectorizeM(fs) #' # should only print "see" twice, not 6 times #' fv(c(0, 1, 1, 0, 0, 1)) #' #' @export #' VectorizeM <- function(FUN, vectorize.args = arg.names, SIMPLIFY = TRUE, USE.NAMES = TRUE, UNLIST = FALSE) { if(!is.function(FUN)) { stop("wrapr::VectorizeM FUN wasn't a function") } if(is.primitive(FUN)) { stop("wrapr::VectorizeM can not wrap FUN as is.primitive(FUN) is TRUE") } frmls <- formals(FUN) arg.names <- as.list(frmls) arg.names[["..."]] <- NULL arg.names <- names(arg.names) vectorize.args <- as.character(vectorize.args) if (length(vectorize.args)<=0) { return(FUN) } vectorize.args <- vectorize.args[[1]] force(FUN) force(SIMPLIFY) force(USE.NAMES) force(UNLIST) if (!all(vectorize.args %in% arg.names)) stop("must specify names of formal arguments for 'vectorize'") collisions <- arg.names %in% c("FUN", "SIMPLIFY", "USE.NAMES", "UNLIST", "vectorize.args") if (any(collisions)) stop(sQuote("FUN"), " may not have argument(s) named ", paste(sQuote(arg.names[collisions]), collapse = ", ")) if(length(vectorize.args)!=1) { stop(sQuote("FUN"), " can only vectorize one argument name") } rm(list = "arg.names") FUNV <- function() { args <- lapply(as.list(match.call())[-1L], eval, parent.frame()) if(length(args)!=1) { stop(sQuote("FUN"), "VectorizeM function: saw more than one argument group") } names <- if (is.null(names(args))) character(length(args)) else names(args) dovec <- names %in% vectorize.args vargs <- args[dovec] unique_values <- unique(vargs[[1]]) first_indexes <- match(unique_values, vargs[[1]]) all_indexes <- match(vargs[[1]], unique_values) vargs2 <- list() vargs2[[names]] <- vargs[[names]][first_indexes] res <- do.call("mapply", c(FUN = FUN, vargs2, MoreArgs = list(args[!dovec]), SIMPLIFY = SIMPLIFY, USE.NAMES = USE.NAMES)) res <- res[all_indexes] if(UNLIST) { attr <- attributes(res[[1]]) res <- unlist(res) attributes(res) <- attr } names(res) <- names(vargs[[1]]) res } formals(FUNV) <- formals(FUN) newenv <- new.env(parent = environment(FUN)) assign('vectorize.args', vectorize.args, envir = newenv) assign('FUN', FUN, envir = newenv) assign('SIMPLIFY', SIMPLIFY, envir = newenv) assign('FUN', FUN, envir = newenv) assign('USE.NAMES', USE.NAMES, envir = newenv) assign('UNLIST', UNLIST, envir = newenv) environment(FUNV) <- newenv FUNV }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/VectorizeM.R
#' Add list name as a column to a list of data.frames. #' #' @param dlist named list of data.frames #' @param destinationColumn character, name of new column to add #' @return list of data frames, each of which as the new destinationColumn. #' #' @examples #' #' dlist <- list(a = data.frame(x = 1), b = data.frame(x = 2)) #' add_name_column(dlist, 'name') #' #' @export #' add_name_column <- function(dlist, destinationColumn) { res <- dlist # since res list is pre-allocated, re-assigning into it # should be fast. # Please see: https://win-vector.com/2015/07/27/efficient-accumulation-in-r/ for(ni in names(dlist)) { vi <- dlist[[ni]] vi[[destinationColumn]] <- ni res[[ni]] <- vi } res }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/addNameCol.R
#' Capture named objects as a named list. #' #' Build a named list from a sequence of named arguments of the form NAME, or NAME = VALUE. #' This is intended to shorten forms such as \code{list(a = a, b = b)} to \code{as_named_list(a, b)}. #' #' @param ... argument names (must be names, not strings or values) plus possible assigned values. #' @return a named list mapping argument names to argument values #' #' @examples #' #' a <- data.frame(x = 1) #' b <- 2 #' #' str(as_named_list(a, b)) #' #' as_named_list(a, x = b, c = 1 + 1) #' #' # an example application for this function is managing saving and #' # loading values into the workspace. #' if(FALSE) { #' # remotes::install_github("WinVector/wrapr") #' library(wrapr) #' #' a <- 5 #' b <- 7 #' do_not_want <- 13 #' #' # save the elements of our workspace we want #' saveRDS(as_named_list(a, b), 'example_data.RDS') #' #' # clear values out of our workspace for the example #' rm(list = ls()) #' ls() #' # notice workspace environemnt now empty #' #' # read back while documenting what we expect to #' # read in #' unpack[a, b] <- readRDS('example_data.RDS') #' #' # confirm what we have, the extra unpack is a side #' # effect of the []<- notation. To avoid this instead #' # use one of: #' # unpack(readRDS('example_data.RDS'), a, b) #' # readRDS('example_data.RDS') %.>% unpack(., a, b) #' # readRDS('example_data.RDS') %.>% unpack[a, b] #' ls() #' # notice do_not_want is not present #' #' print(a) #' #' print(b) #' } #' #' @export #' as_named_list <- function(...) { # get environment to work in unpack_environment <- parent.frame(n = 1) # capture ... args dot_args <- as.list(substitute(list(...)))[-1] n_args <- length(dot_args) if(n_args <= 0) { stop("wrapr::as_named_list expected arguments") } arg_names <- names(dot_args) str_args <- character(n_args) for(i in seq_len(n_args)) { if((i <= length(arg_names)) && (nchar(arg_names[[i]]) > 0)) { arg_i <- arg_names[[i]] } else { arg_i <- dot_args[[i]] if(is.null(arg_i)) { stop("wrapr::as_named_list expected all unnamed arguments to not be NULL") } if(!(is.name(arg_i) || is.character(arg_i))) { stop("wrapr::as_named_list expected all unnamed arguments to be names or character") } } carg_i <- as.character(arg_i) if(length(carg_i) != 1) { stop("wrapr::as_named_list expect all arguments to be length 1") } if(is.na(carg_i)) { stop("wrapr::as_named_list expect all arguments to not be NA") } if(nchar(carg_i) <= 0) { stop("wrapr::as_named_list empty argument (often this means there is an extra comma in the function call)") } str_args[[i]] <- carg_i } if(length(unique(str_args)) != n_args) { stop("wrapr::as_named_list, expected all argument names to be unique") } # get the values values <- vector(mode = 'list', n_args) for(i in seq_len(n_args)) { vi <- eval(dot_args[[i]], envir = unpack_environment, enclos = unpack_environment) if(!is.null(vi)) { # get arround writing null deletes convention values[[i]] <- vi } } names(values) <- str_args return(values) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/as_named_list.R
#' Blank Concatenate. Parse argument as a vector of values allowing "blank separators". #' #' Separates string data on whitespace and separating symbols into an array. #' #' Can throw exception on lack of explicit value separators, example: \code{bc('"a""b"')} and non-matching portions. #' Whitespace is normalized to spaces. Attempts to split on obvious number format boundaries. #' Suggested by Emil Erik Pula Bellamy Begtrup-Bright \url{https://github.com/WinVector/wrapr/issues/12}. #' #' @param s string to parse #' @param ... force later arguments to be set by name #' @param sep_symbols characters to consider separators #' @param strict logical, if TRUE throw exception on confusing input #' @param convert logical, if TRUE try to convert from string type to other types #' @return vector of values #' #' @seealso \code{\link{qc}}, \code{\link{qe}}, \code{\link{qae}}, \code{\link[base]{bquote}}, \code{\link{sx}} #' #' @examples #' #' bc('1 2 "c", d') # returns c("1", "2", "c", "d") #' bc('1 2 3') # returns c(1, 2, 3) #' bc('1 2 "3"') # returns c("1", "2", "3") #' bc('1,2|3.4') # returns c(1, 2, 3.4) #' bc('01 02', convert=FALSE) # returns c("01", "02") #' #' @export #' bc <- function( s, ..., sep_symbols = ',|', strict = TRUE, convert = TRUE) { # check arguments if(!is.character(s)) { stop("wrapr::bc s must be character") } if(length(s)!=1) { stop("wrapr::bc s must be length 1") } wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::bc") # replace all white-space with space s <- gsub('\\s', ' ', s) # tear up string single_quote_str <- "('((\\\\.)|[^'])*')" # with escapes double_quote_str <- gsub("'", '"', single_quote_str, fixed = TRUE) number_l <- '([+-]?(\\d)+[.]?(\\d)*([eE][+-]?(\\d)+)?)' number_r <- '([+-]?(\\d)*[.]?(\\d)+([eE][+-]?(\\d)+)?)' # can overlap with other number: 1.1 hex <- '(0[xX][0-9a-fA-F]+)' symbol_regexp <- paste0('([^0-9 \\\'"', sep_symbols,'+-][^ \\\'"', sep_symbols,']*)') # can overlap with number: .4 sep_regexp <- paste0('([ ', sep_symbols, ']+)') pattern <- paste( single_quote_str, double_quote_str, number_l, number_r, hex, symbol_regexp, sep_regexp, sep = '|') toks <- strsplit_capture(s, split = pattern) # special case length 0 if(length(toks)<=0) { return(c()) } # special case empty-return if((length(toks)==1) && (nchar(toks[[1]])<=0)) { return(c()) } if(strict) { # insist all regions were recognized matched <- vapply( seq_len(length(toks)), function(i) { attr(toks[[i]], 'is_sep', exact = TRUE) }, logical(1)) if(!all(matched)) { min_index = which(!matched)[[1]] stop(paste0( "non-matched token: ", toks[min_index])) } } # limit down to non-separator regions is_waste <- paste0('^([ ', sep_symbols, ']*)$') indices <- grep(is_waste, toks, invert = TRUE) # special case length 0 if(length(indices)<=0) { return(c()) } if(strict) { # insist on non-consecutive value carrying indices if(length(intersect(indices, indices-1))) { min_index = min(intersect(indices, indices-1)) stop(paste0( "value boundaries possibly ambiguous, not safe to return value: ", toks[min_index], toks[min_index + 1])) } } got <- as.character(toks[indices]) # also dump attributes if(convert) { # see if we can convert to logical logical <- NULL tryCatch( logical <- as.logical(got), # currently as.logical does not warn warning = function(w) {}, error = function(e) {}) if((!is.null(logical)) && (all(!is.na(logical)))) { return(logical) } # see if we can convert to numeric num <- NULL tryCatch( num <- as.numeric(got), # currently as.numeric does warn warning = function(w) {}, error = function(e) {}) if((!is.null(num)) && (all(!is.na(num)))) { return(num) } } # remove extra quotes single_quote_str_all <- paste0('^', single_quote_str, '$') double_quote_str_all <- paste0('^', double_quote_str, '$') quoted <- paste( single_quote_str_all, double_quote_str_all, sep = '|') indices <- grep(quoted, got) for(i in indices) { ni <- nchar(got[[i]]) got[[i]] <- substr(got[[i]], 2, ni - 1) } return(got) } #' String eXplode. Parse argument as a vector of string allowing "blank separators". #' #' Separates string data on whitespace and separating symbols into an array. #' #' Can throw exception on lack of explicit value separators, example: \code{bc('"a""b"')} and non-matching portions. #' Whitespace is normalized to spaces. #' Suggested by Emil Erik Pula Bellamy Begtrup-Bright \url{https://github.com/WinVector/wrapr/issues/15}. #' #' @param s string to parse #' @param ... force later arguments to be set by name #' @param sep_symbols characters to consider separators #' @param strict logical, if TRUE throw exception on confusing input #' @return vector of values #' #' @seealso \code{\link{qc}}, \code{\link{qe}}, \code{\link{qae}}, \code{\link[base]{bquote}}, \code{\link{bc}} #' #' @examples #' #' sx('1 2 "c", d') # returns c("1", "2", "c", "d") #' sx('1 2 3') # returns c("1", "2", "3") #' sx('1 2 "3"') # returns c("1", "2", "3") #' sx('1,2|3.4') # returns c("1", "2", "3.4") #' sx('01 02') # returns c("01", "02") #' #' @export #' sx <- function( s, ..., sep_symbols = ',|', strict = TRUE) { # check arguments if(!is.character(s)) { stop("wrapr::sx s must be character") } if(length(s)!=1) { stop("wrapr::sx s must be length 1") } wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::sx") # replace all white-space with space s <- gsub('\\s', ' ', s) # tear up string single_quote_str <- "('((\\\\.)|[^'])*')" # with escapes double_quote_str <- gsub("'", '"', single_quote_str, fixed = TRUE) unquo_regexp <- paste0('([^ \\\'"', sep_symbols,'+-][^ \\\'"', sep_symbols,']*)') # can overlap with number: .4 sep_regexp <- paste0('([ ', sep_symbols, ']+)') pattern <- paste( single_quote_str, double_quote_str, unquo_regexp, sep_regexp, sep = '|') toks <- strsplit_capture(s, split = pattern) # special case length 0 if(length(toks)<=0) { return(c()) } # special case empty-return if((length(toks)==1) && (nchar(toks[[1]])<=0)) { return(c()) } if(strict) { # insist all regions were recognized matched <- vapply( seq_len(length(toks)), function(i) { attr(toks[[i]], 'is_sep', exact = TRUE) }, logical(1)) if(!all(matched)) { min_index = which(!matched)[[1]] stop(paste0( "non-matched token: ", toks[min_index])) } } # limit down to non-separator regions is_waste <- paste0('^([ ', sep_symbols, ']*)$') indices <- grep(is_waste, toks, invert = TRUE) # special case length 0 if(length(indices)<=0) { return(c()) } if(strict) { # insist on non-consecutive value carrying indices if(length(intersect(indices, indices-1))) { min_index = min(intersect(indices, indices-1)) stop(paste0( "value boundaries possibly ambiguous, not safe to return value: ", toks[min_index], toks[min_index + 1])) } } got <- as.character(toks[indices]) # also dump attributes # remove extra quotes single_quote_str_all <- paste0('^', single_quote_str, '$') double_quote_str_all <- paste0('^', double_quote_str, '$') quoted <- paste( single_quote_str_all, double_quote_str_all, sep = '|') indices <- grep(quoted, got) for(i in indices) { ni <- nchar(got[[i]]) got[[i]] <- substr(got[[i]], 2, ni - 1) } return(got) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/bc.R
#' S3 dispatch on class of pipe_left_arg. #' #' For formal documentation please see \url{https://github.com/WinVector/wrapr/blob/master/extras/wrapr_pipe.pdf}. #' #' @param pipe_left_arg left argument. #' @param pipe_right_arg substitute(pipe_right_arg) argument. #' @param pipe_environment environment to evaluate in. #' @param left_arg_name name, if not NULL name of left argument. #' @param pipe_string character, name of pipe operator. #' @param right_arg_name name, if not NULL name of right argument. #' @return result #' #' @seealso \code{\link{apply_left.default}} #' #' @examples #' #' apply_left.character <- function(pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) { #' if(is.language(pipe_right_arg)) { #' wrapr::apply_left_default(pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) #' } else { #' paste(pipe_left_arg, pipe_right_arg) #' } #' } #' setMethod( #' wrapr::apply_right_S4, #' signature = c(pipe_left_arg = "character", pipe_right_arg = "character"), #' function(pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) { #' paste(pipe_left_arg, pipe_right_arg) #' }) #' #' "a" %.>% 5 %.>% 7 #' #' "a" %.>% toupper(.) #' #' q <- "z" #' "a" %.>% q #' #' #' @export #' apply_left <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { force(pipe_environment) UseMethod("apply_left", pipe_left_arg) } # things we don't want to piple into forbidden_pipe_destination_names <- c("else", "return", "stop", "warning", "in", "next", "break", "TRUE", "FALSE", "NULL", "Inf", "NaN", "NA", "NA_integer_", "NA_real_", "NA_complex_", "NA_character_", "->", "->>", "<-", "<<-", "=", # precedence should ensure we do not see these "?", "...", ".", ";", ",", "list", "c", ":", "for") #' S3 dispatch on class of pipe_left_arg. #' #' Place evaluation of left argument in \code{.} and then evaluate right argument. #' #' @param pipe_left_arg left argument #' @param pipe_right_arg substitute(pipe_right_arg) argument #' @param pipe_environment environment to evaluate in #' @param left_arg_name name, if not NULL name of left argument. #' @param pipe_string character, name of pipe operator. #' @param right_arg_name name, if not NULL name of right argument. #' @return result #' #' @seealso \code{\link{apply_left}} #' #' @examples #' #' 5 %.>% sin(.) #' #' @export #' apply_left_default <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { force(pipe_environment) # remove some exceptional cases if(length(pipe_right_arg)<1) { stop("wrapr::apply_left.default does not allow direct piping into NULL/empty") } # check for piping into constants such as 4 %.>% 5 if(!is.language(pipe_right_arg)) { stop(paste("wrapr::apply_left.default does not allow piping into obvious concrete right-argument (clearly can't depend on left argument):\n", ifelse(is.null(left_arg_name), "", left_arg_name), paste(class(pipe_left_arg), collapse = ", "), "\n", ifelse(is.null(right_arg_name), "", right_arg_name), paste(class(pipe_right_arg), collapse = ", ")), call. = FALSE) } if(is.call(pipe_right_arg) && (is.name(pipe_right_arg[[1]]))) { call_text <- as.character(pipe_right_arg[[1]]) # mostly grabbing reserved words that are in the middle # of something, or try to alter control flow (like return). if(isTRUE(call_text %in% forbidden_pipe_destination_names)) { stop(paste0("to reduce surprising execution behavior wrapr::apply_left.default does not allow direct piping into some expressions (such as \"", wrapr_deparse(pipe_right_arg), "\").")) } } # eval by with pipe_left_arg's value in dot (simulates chaining) assign(".", pipe_left_arg, envir = pipe_environment, inherits = FALSE) eval(pipe_right_arg, envir = pipe_environment, enclos = pipe_environment) } #' S3 dispatch on class of pipe_left_arg. #' #' Place evaluation of left argument in \code{.} and then evaluate right argument. #' #' @param pipe_left_arg left argument #' @param pipe_right_arg substitute(pipe_right_arg) argument #' @param pipe_environment environment to evaluate in #' @param left_arg_name name, if not NULL name of left argument. #' @param pipe_string character, name of pipe operator. #' @param right_arg_name name, if not NULL name of right argument. #' @return result #' #' @seealso \code{\link{apply_left}} #' #' @examples #' #' 5 %.>% sin(.) #' #' @export #' apply_left.default <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { force(pipe_environment) apply_left_default(pipe_left_arg = pipe_left_arg, pipe_right_arg = pipe_right_arg, pipe_environment = pipe_environment, left_arg_name = left_arg_name, pipe_string = pipe_string, right_arg_name = right_arg_name) } #' S3 dispatch on class of pipe_right_argument. #' #' Triggered if right hand side of pipe stage was a name that does not resolve to a function. #' For formal documentation please see \url{https://github.com/WinVector/wrapr/blob/master/extras/wrapr_pipe.pdf}. #' #' #' @param pipe_left_arg left argument #' @param pipe_right_arg right argument #' @param pipe_environment environment to evaluate in #' @param left_arg_name name, if not NULL name of left argument. #' @param pipe_string character, name of pipe operator. #' @param right_arg_name name, if not NULL name of right argument. #' @return result #' #' @seealso \code{\link{apply_left}}, \code{\link{apply_right_S4}} #' #' @examples #' #' # simulate a function pointer #' apply_right.list <- function(pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) { #' pipe_right_arg$f(pipe_left_arg) #' } #' #' f <- list(f=sin) #' 2 %.>% f #' f$f <- cos #' 2 %.>% f #' #' @export #' apply_right <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { force(pipe_environment) UseMethod("apply_right", pipe_right_arg) } #' Default apply_right implementation. #' #' Default apply_right implementation: S4 dispatch to apply_right_S4. #' #' @param pipe_left_arg left argument #' @param pipe_right_arg pipe_right_arg argument #' @param pipe_environment environment to evaluate in #' @param left_arg_name name, if not NULL name of left argument. #' @param pipe_string character, name of pipe operator. #' @param right_arg_name name, if not NULL name of right argument. #' @return result #' #' @seealso \code{\link{apply_left}}, \code{\link{apply_right}}, \code{\link{apply_right_S4}} #' #' @examples #' #' # simulate a function pointer #' apply_right.list <- function(pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) { #' pipe_right_arg$f(pipe_left_arg) #' } #' #' f <- list(f=sin) #' 2 %.>% f #' f$f <- cos #' 2 %.>% f #' #' @export #' apply_right.default <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { force(pipe_environment) apply_right_S4(pipe_left_arg = pipe_left_arg, pipe_right_arg = pipe_right_arg, pipe_environment = pipe_environment, left_arg_name = left_arg_name, pipe_string = pipe_string, right_arg_name = right_arg_name) } #' S4 dispatch method for apply_right. #' #' Intended to be generic on first two arguments. #' #' @param pipe_left_arg left argument #' @param pipe_right_arg pipe_right_arg argument #' @param pipe_environment environment to evaluate in #' @param left_arg_name name, if not NULL name of left argument. #' @param pipe_string character, name of pipe operator. #' @param right_arg_name name, if not NULL name of right argument. #' @return result #' #' @seealso \code{\link{apply_left}}, \code{\link{apply_right}} #' #' @examples #' #' a <- data.frame(x = 1) #' b <- data.frame(x = 2) #' #' # a %.>% b # will (intentionally) throw #' #' setMethod( #' "apply_right_S4", #' signature("data.frame", "data.frame"), #' function(pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) { #' rbind(pipe_left_arg, pipe_right_arg) #' }) #' #' #' a %.>% b # should equal data.frame(x = c(1, 2)) #' #' @export #' apply_right_S4 <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { force(pipe_environment) # # go to default left S3 dispatch on apply_left() # apply_left(pipe_left_arg = pipe_left_arg, # pipe_right_arg = pipe_right_arg, # pipe_environment = pipe_environment, # left_arg_name = left_arg_name, # pipe_string = pipe_string, # right_arg_name = right_arg_name) stop(paste("wrapr::apply_right_S4 default called with classes:\n", ifelse(is.null(left_arg_name), "", left_arg_name), paste(class(pipe_left_arg), collapse = ", "), "\n", ifelse(is.null(right_arg_name), "", right_arg_name), paste(class(pipe_right_arg), collapse = ", "), "\n", " must have a more specific S4 method defined to dispatch\n"), call. = FALSE) } #' @importFrom methods setGeneric NULL # lash in S4 dispatch methods::setGeneric( name = "apply_right_S4") #' Pipe dispatch implementation. #' #' This is a helper for implementing additional pipes. #' #' @param pipe_left_arg possibily unevaluated left argument. #' @param pipe_right_arg possibly unevaluated right argument. #' @param pipe_environment environment to evaluate in. #' @param pipe_string character, name of pipe operator. #' @return result #' #' @examples #' #' # Example: how wrapr pipe is implemented #' #' print(`%.>%`) #' #' #' #' #' # Example: create a value that causes pipelines to record steps. #' #' # inject raw values into wrapped/annotated world #' unit_recording <- function(x, recording = paste(as.expression(substitute(x)), collapse = '\n')) { #' res <- list(value = x, recording = recording) #' class(res) <- "recording_value" #' res #' } #' #' # similar to bind or >>= #' # (takes U, f:U -> V to M(f(U)), instead of #' # U, f:U -> M(V) to M(f(U))) #' # so similar to a functor taking #' # f:U -> V to f':M(U) -> M(V) #' # followed by application. #' apply_left.recording_value <- function( #' pipe_left_arg, #' pipe_right_arg, #' pipe_environment, #' left_arg_name, #' pipe_string, #' right_arg_name) { #' force(pipe_environment) #' tmp <- wrapr::pipe_impl( #' pipe_left_arg = pipe_left_arg$value, #' pipe_right_arg = pipe_right_arg, #' pipe_environment = pipe_environment, #' pipe_string = pipe_string) #' unit_recording( #' tmp, #' paste0(pipe_left_arg$recording, #' ' %.>% ', #' paste(as.expression(pipe_right_arg), collapse = '\n'))) #' } #' #' # make available on standard S3 search path #' assign('apply_left.recording_value', #' apply_left.recording_value, #' envir = .GlobalEnv) #' #' unpack[value, recording] := 3 %.>% #' unit_recording(.) %.>% #' sin(.) %.>% #' cos(.) #' #' print(value) #' print(recording) #' #' # clean up #' rm(envir = .GlobalEnv, list = 'apply_left.recording_value') #' #' @export #' pipe_impl <- function(pipe_left_arg, pipe_right_arg, pipe_environment, pipe_string = NULL) { # make sure environment is available force(pipe_environment) # special case: parenthesis while(is.call(pipe_right_arg) && (length(pipe_right_arg)==2) && (length(as.character(pipe_right_arg[[1]]))==1) && (as.character(pipe_right_arg[[1]])=="(")) { pipe_right_arg <- pipe_right_arg[[2]] } # capture names left_arg_name <- NULL if(is.name(pipe_left_arg)) { left_arg_name <- pipe_left_arg } right_arg_name <- NULL if(is.name(pipe_right_arg)) { right_arg_name <- pipe_right_arg } # special case: name is_name <- is.name(pipe_right_arg) # special case: dereference names qualified_name <- is.call(pipe_right_arg) && (length(pipe_right_arg)==3) && (length(as.character(pipe_right_arg[[1]]))==1) && (as.character(pipe_right_arg[[1]]) %in% c("::", ":::", "$", "[[", "[", "@")) && (is.name(pipe_right_arg[[2]])) && (as.character(pipe_right_arg[[2]])!=".") && (is.name(pipe_right_arg[[3]]) || is.character(pipe_right_arg[[3]])) && (as.character(pipe_right_arg[[3]])!=".") # special case: anonymous funciton decl is_function_decl <- is.call(pipe_right_arg) && (length(as.character(pipe_right_arg[[1]]))==1) && (as.character(pipe_right_arg[[1]])=="function") dot_paren <- FALSE eager_expression_eval <- FALSE if(is.call(pipe_right_arg) && (length(as.character(pipe_right_arg[[1]]))==1)) { call_name <- as.character(pipe_right_arg[[1]])[[1]] if(call_name == ".") { # special-case .() on RHS dot_paren <- TRUE } else { if(call_name %in% c('[', '[[')) { # special case [, treat 2nd argument as controller if(length(pipe_right_arg) >= 2) { obj_found_name <- as.character(pipe_right_arg[[2]]) if(length(obj_found_name)==1) { obj_found <- mget(obj_found_name, envir = pipe_environment, mode = "any", inherits=TRUE, ifnotfound = list(NULL))[[1]] if(!is.null(obj_found)) { if(isTRUE(attr(obj_found, "dotpipe_eager_eval_bracket"))) { eager_expression_eval <- TRUE } } } } } else { fn_found <- mget(call_name, envir = pipe_environment, mode = "function", inherits=TRUE, ifnotfound = list(NULL))[[1]] if(!is.null(fn_found)) { if(isTRUE(attr(fn_found, "dotpipe_eager_eval_function"))) { eager_expression_eval <- TRUE } } } } } # check for right-apply situations if(is.function(pipe_right_arg) || is_name || qualified_name || is_function_decl || dot_paren || eager_expression_eval) { if(is_name) { if(as.character(pipe_right_arg) %in% forbidden_pipe_destination_names) { stop(paste("to reduce surprising behavior wrapr::pipe does not allow direct piping into some names, such as", as.character(pipe_right_arg))) } pipe_right_arg <- base::get(as.character(pipe_right_arg), envir = pipe_environment, mode = "any", inherits = TRUE) } else if(qualified_name || is_function_decl) { pipe_right_arg <- base::eval(pipe_right_arg, envir = pipe_environment, enclos = pipe_environment) } else if(dot_paren) { pipe_right_arg <- eval(pipe_right_arg[[2]], envir = pipe_environment, enclos = pipe_environment) } else if(eager_expression_eval) { pipe_right_arg <- eval(pipe_right_arg, envir = pipe_environment, enclos = pipe_environment) } # pipe_right_arg is now a value (as far as we are concerned) # special case: functions if(is.function(pipe_right_arg)) { if(!is.null(left_arg_name)) { # try to pass name forward to function # support NSE in functions, but don't encourage it in expressions res <- withVisible(do.call(pipe_right_arg, list(left_arg_name), envir = pipe_environment)) } else { # force pipe_left_arg pipe_left_arg <- eval(pipe_left_arg, envir = pipe_environment, enclos = pipe_environment) res <- withVisible(do.call(pipe_right_arg, list(pipe_left_arg), envir = pipe_environment)) } if(res$visible) { return(res$value) } else { return(invisible(res$value)) } } # force pipe_left_arg pipe_left_arg <- eval(pipe_left_arg, envir = pipe_environment, enclos = pipe_environment) # S3 dispatch on right argument, surrogate function res <- withVisible(apply_right(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name)) if(res$visible) { return(res$value) } else { return(invisible(res$value)) } } # force pipe_left_arg pipe_left_arg <- eval(pipe_left_arg, envir = pipe_environment, enclos = pipe_environment) # Go for standard (first argument) S3 dispatch res <- withVisible(apply_left(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name)) if(res$visible) { res$value } else { invisible(res$value) } } #' Pipe operator ("dot arrow", "dot pipe" or "dot arrow pipe"). #' #' Defined as roughly : \code{a \%>.\% b} ~ \code{\{ . <- a; b \};} #' (with visible .-side effects). #' #' The pipe operator has a couple of special cases. First: if the right hand side is a name, #' then we try to de-reference it and apply it as a function or surrogate function. #' #' The pipe operator checks for and throws an exception for a number of "piped into #' nothing cases" such as \code{5 \%.>\% sin()}, many of these checks can be turned #' off by adding braces. #' #' For some discussion, please see \url{https://win-vector.com/2017/07/07/in-praise-of-syntactic-sugar/}. #' For some more examples, please see the package README \url{https://github.com/WinVector/wrapr}. #' For formal documentation please see \url{https://github.com/WinVector/wrapr/blob/master/extras/wrapr_pipe.pdf}. #' For a base-R step-debuggable pipe please try the Bizarro Pipe \url{https://win-vector.com/2017/01/29/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/}. #' \code{\%>.\%} and \code{\%.>\%} are synonyms. #' #' The dot arrow pipe has S3/S4 dispatch (please see \url{https://journal.r-project.org/archive/2018/RJ-2018-042/index.html}). #' However as the right-hand side of the pipe is normally held unevaluated, we don't know the type except in special #' cases (such as the rigth-hand side being referred to by a name or variable). To force the evaluation of a pipe term, #' simply wrap it in .(). #' #' @param pipe_left_arg left argument expression (substituted into .) #' @param pipe_right_arg right argument expression (presumably including .) #' @return eval(\{ . <- pipe_left_arg; pipe_right_arg \};) #' #' @examples #' #' # both should be equal: #' cos(exp(sin(4))) #' 4 %.>% sin(.) %.>% exp(.) %.>% cos(.) #' #' f <- function() { sin } #' # returns f() ignoring dot, not what we want #' 5 %.>% f() #' # evaluates f() early then evaluates result with .-substitution rules #' 5 %.>% .(f()) #' #' @name dot_arrow NULL #' @describeIn dot_arrow dot arrow #' @export `%.>%` <- function(pipe_left_arg, pipe_right_arg) { pipe_left_arg <- substitute(pipe_left_arg) pipe_right_arg <- substitute(pipe_right_arg) pipe_environment <- parent.frame() pipe_string <- as.character(sys.call()[[1]]) pipe_impl(pipe_left_arg, pipe_right_arg, pipe_environment, pipe_string) } #' @describeIn dot_arrow alias for dot arrow #' @export `%>.%` <- function(pipe_left_arg, pipe_right_arg) { pipe_left_arg <- substitute(pipe_left_arg) pipe_right_arg <- substitute(pipe_right_arg) pipe_environment <- parent.frame() pipe_string <- as.character(sys.call()[[1]]) pipe_impl(pipe_left_arg, pipe_right_arg, pipe_environment, pipe_string) } #' @describeIn dot_arrow alias for dot arrow #' @export `%.%` <- function(pipe_left_arg, pipe_right_arg) { pipe_left_arg <- substitute(pipe_left_arg) pipe_right_arg <- substitute(pipe_right_arg) pipe_environment <- parent.frame() pipe_string <- as.character(sys.call()[[1]]) pipe_impl(pipe_left_arg, pipe_right_arg, pipe_environment, pipe_string) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/bpipe.R
build_minus_fn_env <- function(env) { force(env) orig_minus <- get('-', mode = 'function', envir = env) minus_fn_to_name <- function(e1, e2) { if(!missing(e2)) { return(orig_minus(e1, e2)) } if(is.name(e1)) { return(e1) } if(is.character(e1) && (length(e1)==1)) { return(as.name(e1)) } orig_minus(e1) } env2 <- new.env(parent = env) assign('-', minus_fn_to_name, envir = env2) return(env2) } #' Near \code{eval(bquote(expr))} shortcut. #' #' Evaluate \code{expr} with \code{bquote} \code{.()} substitution. #' Including \code{.(-x)} promoting \code{x}'s value from character to a name, #' which is called "quote negation" (hence the minus-sign). #' #' @param expr expression to evaluate. #' @param where environment to work in. #' @return evaluated substituted expression. #' #' @examples #' #' if(requireNamespace('graphics', quietly = TRUE)) { #' angle = 1:10 #' variable <- as.name("angle") #' fn_name <- 'sin' #' evalb( plot(x = .(variable), y = .(-fn_name)(.(variable))) ) #' } #' #' @export #' evalb <- function(expr, where = parent.frame()) { force(where) env2 <- build_minus_fn_env(where) expr <- substitute(expr) # can't set env, as that changes substitute's behavior exprq <- do.call(bquote, list(expr, where = env2)) eval(exprq, envir = env2, enclos = env2) } #' Treat call argument as bquoted-values. #' #' Re-write call to evaluate \code{expr} with \code{bquote} \code{.()} substitution. #' Uses convetion that := is considered a alias for =. #' Including \code{.(-x)} promoting \code{x}'s value from character to a name, #' which is called "quote negation" (hence the minus-sign). #' #' @param call result of match.call() #' @param env environment to perform lookups in. #' @return altered call #' #' @seealso \code{\link{bquote_function}}, \code{\link{bquote_call_args}} #' #' @keywords internal #' #' @export #' #' bquote_call <- function(call, env = parent.frame()) { force(env) # perform bquote transform env2 <- build_minus_fn_env(env) mc <- do.call(bquote, list(call, where = env2), envir = env2) # map a := b to name(a) = b fixpos <- which(vapply(mc[-1], function(ai) { is.call(ai) && (as.character(ai)[[1]]==":=") }, logical(1))) if(length(fixpos)>0) { fixpos <- fixpos + 1 if(length(intersect(names(mc)[fixpos], names(mc)[!fixpos]))>0) { stop("wrapr::bquote_call := and = names must be disjoint") } nms <- vapply(mc[fixpos], function(ai) { as.character(ai[[2]]) }, character(1)) vals <- lapply(mc[fixpos], function(ai) { ai[[3]] }) names(mc)[fixpos] <- nms mc[fixpos] <- vals } mc } #' Treat ... argument as bquoted-values. #' #' bquote_call_args is a helper to allow the user to write functions with bquote-enabled argument substitution. #' Uses convetion that := is considered a alias for =. #' Re-writes call args to evaluate \code{expr} with \code{bquote} \code{.()} substitution. #' Including \code{.(-x)} promoting \code{x}'s value from character to a name, #' which is called "quote negation" (hence the minus-sign). #' #' @param call result of match.call() #' @param env environment to perform lookups in. #' @return name list of values #' #' @seealso \code{\link{bquote_function}} #' #' #' @examples #' #' f <- function(q, ...) { #' env = parent.frame() #' # match.call() best called in function context. #' captured_call <- match.call() #' captured_args <- bquote_call_args(captured_call, env) #' captured_args #' } #' #' z <- "x" #' y <- 5 #' qv <- 3 #' #' # equivalent to f(3, x = 5) #' f(.(qv), .(z) := .(y)) #' #' # equivalent to f(q = 7) #' qname <- 'q' #' f(.(qname) := 7) #' #' #' @export #' #' bquote_call_args <- function(call, env = parent.frame()) { force(env) args <- as.list(wrapr::bquote_call(call, env)[-1]) resframe <- parent.frame() for(i in seq_len(length(args))) { nmi <- names(args)[[i]] if((!is.null(nmi)) && (!is.na(nmi)) && (nchar(nmi)>0)) { vali <- args[[i]] assign(nmi, vali, envir = resframe) } } args } #' Adapt a function to use bquote on its arguments. #' #' bquote_function is for adapting a function defined elsewhere for bquote-enabled argument substitution. #' Re-write call to evaluate \code{expr} with \code{bquote} \code{.()} substitution. #' Uses convetion that := is considered a alias for =. #' Including \code{.(-x)} promoting \code{x}'s value from character to a name, #' which is called "quote negation" (hence the minus-sign). #' #' @param fn function to adapt, must have non-empty formals(). #' @return new function. #' #' @seealso \code{\link{bquote_call_args}} #' #' @examples #' #' #' if(requireNamespace('graphics', quietly = TRUE)) { #' angle = 1:10 #' variable <- as.name("angle") #' plotb <- bquote_function(graphics::plot) #' plotb(x = .(variable), y = sin(.(variable))) #' } #' #' #' #' f1 <- function(x) { substitute(x) } #' f2 <- bquote_function(f1) #' arg <- "USER_ARG" #' f2(arg) # returns arg #' f2(.(arg)) # returns "USER_ARG" (character) #' f2(.(-arg)) # returns USER_ARG (name) #' #' #' @export #' bquote_function <- function(fn) { if(!is.function(fn)) { stop("wrapr::bquote_function fn wasn't a function") } if(is.primitive(fn)) { stop("wrapr::bquote_function can not wrap fn as is.primitive(fn) is TRUE") } frmls <- formals(fn) if(length(frmls)<=0) { return(fn) # take no args, nothing to do } .wrapr_wrapped_function_ <- NULL # don't look unbound f <- function() { call <- match.call() env <- parent.frame() mc <- wrapr::bquote_call(call, env) mc[[1]] <- .wrapr_wrapped_function_ eval(mc, envir = env) } formals(f) <- frmls newenv <- new.env(parent = environment(fn)) assign('.wrapr_wrapped_function_', fn, envir = newenv) environment(f) <- newenv f }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/bquotefn.R
#' Inline list/array concatenate. #' #' @param e1 first, or left argument. #' @param e2 second, or right argument. #' @return c(e1, c2) #' #' @examples #' #' 1:2 %c% 5:6 #' #' c("a", "b") %c% "d" #' #' @rdname inline_concat #' #' @export #' `%c%` <- function(e1, e2) { c(e1, e2) } #' Inline quoting list/array concatenate. #' #' @param e1 first, or left argument. #' @param e2 second, or right argument. #' @return qc(e1, c2) #' #' @examples #' #' 1:2 %qc% 5:6 #' #' c("a", "b") %qc% d #' #' a %qc% b %qc% c #' #' @rdname inline_qc #' #' @export #' `%qc%` <- function(e1, e2) { env <- parent.frame() do.call(qc, list(substitute(e1), substitute(e2)), envir = env) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/c.R
is_infix <- function(vi) { vi <- as.character(vi) if(nchar(vi)<=0) { return(FALSE) } if(substr(vi,1,1)=="`") { vi <- substr(vi,2,nchar(vi)-1) } if(nchar(vi)<=0) { return(FALSE) } if(substr(vi,1,1)=="%") { return(TRUE) } syms <- c("::", "$", "@", "^", ":", "*", "/", "+", "-", ">", ">=", "<", "<=", "==", "!=", "&", "&&", "|", "||", "~", "->", "->>", "=", "<-", "<<-") if(vi %in% syms) { return(TRUE) } return(FALSE) } # convert a list to a vector without losing type/class info # lst is a list of scalars to_vector <- function(lst) { n <- length(lst) if(n<1) { return(logical(0)) } vec <- rep(lst[[1]], n) for(i in seqi(2,n)) { vec[[i]] <- lst[[i]] } vec } #' Build a data.frame from the user's description. #' #' A convenient way to build a data.frame in legible transposed form. Position of #' first "|" (or other infix operator) determines number of columns #' (all other infix operators are aliases for ","). #' Names are de-referenced. #' #' @param ... cell names, first infix operator denotes end of header row of column names. #' @param cf_eval_environment environment to evaluate names in. #' @return character data.frame #' #' @seealso \code{\link{draw_frame}}, \code{\link{qchar_frame}} #' #' @examples #' #' tc_name <- "training" #' x <- build_frame( #' "measure", tc_name, "validation" | #' "minus binary cross entropy", 5, -7 | #' "accuracy", 0.8, 0.6 ) #' print(x) #' str(x) #' cat(draw_frame(x)) #' #' build_frame( #' "x" | #' -1 | #' 2 ) #' #' @export #' build_frame <- function(..., cf_eval_environment = parent.frame()) { v <- as.list(substitute(list(...))) lengths <- vapply( v, function(vi) {nchar(paste(as.character(vi), collapse = ''))}, numeric(1)) if(any(lengths <= 0)) { stop("empty entry, this is often caused by an extra comma") } v <- lapply(seqi(2, length(v)), function(i) {v[[i]]}) force(cf_eval_environment) lv <- length(v) # inspect input if(lv<1) { return(data.frame()) } # unpack unpack_val <- function(vi) { if(length(vi)<=0) { stop("wrapr::build_frame unexpected NULL/empty element") } if(is.name(vi)) { viv <- cf_eval_environment[[as.character(vi)]] if(is.name(viv)) { stop(paste("wrapr::build_frame name", vi, "resolved to another name:", viv)) } if(is.call(viv)) { stop(paste("wrapr::build_frame name", vi, "resolved to call", viv)) } if(length(viv)<=0) { stop(paste("wrapr::build_frame name", vi, "resolved to NULL")) } vi <- viv } if(is.call(vi)) { if((length(vi)==3) && (is_infix(vi[[1]]))) { vi <- list(unpack_val(vi[[2]]), as.name("sep"), unpack_val(vi[[3]])) } else { viv <- eval(vi, envir = cf_eval_environment, enclos = cf_eval_environment) if(is.name(viv)) { stop(paste("wrapr::build_frame eval", vi, "resolved to another name:", viv)) } if(length(viv)<=0) { stop(paste("wrapr::build_frame eval", vi, "resolved to NULL")) } vi <- viv } } Reduce(c, lapply(vi, as.list)) } vu <- lapply(v, unpack_val) vu <- Reduce(c, lapply(vu, as.list)) ncol <- length(vu) if(ncol<1) { stop("wrapr::build_frame() zero columns") } is_name <- vapply(vu, is.name, logical(1)) if(any(is_name)) { ncol <- which(is_name)[[1]]-1 vu <- vu[!is_name] # filter out names } nrow <- (length(vu)/ncol) - 1 if(abs(nrow - round(nrow))>0.1) { stop("wrapr::build_frame confused as to cell count") } if(nrow<=0) { fr <- data.frame(x = logical(0)) colnames(fr) <- as.character(vu[[1]]) if(ncol>1) { for(i in 2:ncol) { ci <- as.character(vu[[i]]) fr[[ci]] <- logical(0) } } } else { seq <- seq_len(nrow)*ncol fr <- data.frame(x = to_vector(vu[seq + 1]), stringsAsFactors = FALSE) colnames(fr) <- as.character(vu[[1]]) if(ncol>1) { for(i in 2:ncol) { ci <- as.character(vu[[i]]) fr[[ci]] <- to_vector(vu[seq + i]) } } } rownames(fr) <- NULL fr } #' Render a simple data.frame in build_frame format. #' #' @param x data.frame (with atomic types). #' @param ... not used for values, forces later arguments to bind by name. #' @param time_format character, format for "POSIXt" classes. #' @param formatC_options named list, options for formatC()- used on numerics. #' @param adjust_for_auto_indent integer additional after first row padding #' @return character #' #' @seealso \code{\link{build_frame}}, \code{\link{qchar_frame}} #' #' @examples #' #' tc_name <- "training" #' x <- build_frame( #' "measure" , tc_name, "validation", "idx" | #' "minus binary cross entropy", 5 , 7 , 1L | #' "accuracy" , 0.8 , 0.6 , 2L ) #' print(x) #' cat(draw_frame(x)) #' #' #' @export #' draw_frame <- function(x, ..., time_format = "%Y-%m-%d %H:%M:%S", formatC_options = list(), adjust_for_auto_indent = 2) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::draw_frame") formatC_args = list(digits = NULL, width = NULL, format = NULL, flag = "", mode = NULL, big.mark = "", big.interval = 3L, small.mark = "", small.interval = 5L, decimal.mark = getOption("OutDec"), preserve.width = "individual", zero.print = NULL, drop0trailing = FALSE) x_s <- substitute(x) for(oi in names(formatC_options)) { formatC_args[[oi]] <- formatC_options[[oi]] } if(!is.data.frame(x)) { stop("draw_frame x needs to be a data.frame") } res <- "wrapr::build_frame()" nrow <- nrow(x) ncol <- ncol(x) if((nrow>=1) && (ncol<1)) { stop("wrapr::draw_frame bad input: no columns, but has rows") } qts <- function(v) { # wayts to quote: dput(), shQuote(), deparse() vapply(as.character(v), function(vi) { deparse(vi) }, character(1)) } if((nrow<1) || (ncol<1)) { if(ncol>=1) { res <- paste(qts(colnames(x)), collapse = ", ") res <- paste0("wrapr::build_frame(", res, ")") } } else { # convert to character matrix xq <- x for(ci in colnames(x)) { if("Date" %in% class(x[[ci]])) { xq[[ci]] <- paste0("as.Date(\"", format(x[[ci]]), "\")") xq[[ci]][is.na(x[[ci]])] <- "NA_real_" } else if("POSIXt" %in% class(x[[ci]])) { # round tripping a time correctly through R is so unlikely, just fall back to string xq[[ci]] <- paste0("\"", format(x[[ci]], time_format), "\"") xq[[ci]][is.na(x[[ci]])] <- "NA_character_" } else if(is.character(x[[ci]]) || is.factor(x[[ci]])) { xq[[ci]] <- qts(as.character(x[[ci]])) xq[[ci]][is.na(x[[ci]])] <- "NA_character_" } else if(is.integer(x[[ci]])) { xq[[ci]] <- paste0(format(x[[ci]], scientific = FALSE), "L") xq[[ci]][is.na(x[[ci]])] <- "NA_integer_" } else if(is.numeric(x[[ci]])) { xq[[ci]] <- formatC(x[[ci]], digits = formatC_args$digits, width = formatC_args$width, format = formatC_args$format, flag = formatC_args$flag, mode = formatC_args$mode, big.mark = formatC_args$big.mark, big.interval = formatC_args$big.interval, small.mark = formatC_args$small.mark, small.interval = formatC_args$small.interval, decimal.mark = formatC_args$decimal.mark, preserve.width = formatC_args$preserve.width, zero.print = formatC_args$zero.print, drop0trailing = formatC_args$drop0trailing) xq[[ci]][is.na(x[[ci]])] <- "NA_real_" } else if(is.logical(x[[ci]])) { xq[[ci]] <- as.character(x[[ci]]) xq[[ci]][is.na(x[[ci]])] <- "NA" } else { xq[[ci]] <- as.character(x[[ci]]) xq[[ci]][is.na(x[[ci]])] <- "NA" } } xm <- as.matrix(xq) xm <- matrix(data = as.character(xm), nrow = nrow, ncol = ncol) # convert header to values xm <- rbind(matrix(data = qts(colnames(x)), nrow = 1, ncol = ncol), xm) # compute padding widths <- nchar(xm) widths[is.na(as.numeric(widths))] <- 2 colmaxes <- matrix(data = apply(widths, 2, max), nrow = nrow+1, ncol = ncol, byrow = TRUE) padlens <- colmaxes - widths pads <- matrix(data = vapply(padlens, function(vi) { paste(rep(' ', vi), collapse = '') }, character(1)), nrow = nrow+1, ncol = ncol) # get intermediates seps <- matrix(data = ", ", nrow = nrow+1, ncol = ncol) seps[, ncol] <- " |" seps[nrow+1, ncol] <- " )" # format fmt <- matrix(data = paste0(xm, pads, seps), nrow = nrow+1, ncol = ncol) if(adjust_for_auto_indent>0) { pad <- paste(rep(" ", adjust_for_auto_indent), collapse = "") fmt[1, 1] <- gsub(", $", paste0(pad, ", "), fmt[1, 1]) for(i in seqi(2, nrow(fmt))) { fmt[i, 1] <- paste0(pad, fmt[i, 1]) } } rlist <- vapply(seq_len(nrow+1), function(i) { paste(fmt[i, , drop=TRUE], collapse = '') }, character(1)) rlist <- paste0(" ", rlist) res <- paste(rlist, collapse = "\n") res <- paste0("wrapr::build_frame(\n", res, "\n") } if(is.name(x_s)) { res <- paste0(as.character(x_s), " <- ", res) } res } #' Build a quoted data.frame. #' #' A convenient way to build a character data.frame in legible transposed form. Position of #' first "|" (or other infix operator) determines number of columns #' (all other infix operators are aliases for ","). #' Names are treated as character types. #' #' qchar_frame() uses bquote() .() quasiquotation escaping notation. Because of this using dot #' as a name in some places may fail if the dot looks like a function call. #' #' @param ... cell names, first infix operator denotes end of header row of column names. #' @return character data.frame #' #' @seealso \code{\link{draw_frame}}, \code{\link{build_frame}} #' #' @examples #' #' loss_name <- "loss" #' x <- qchar_frame( #' measure, training, validation | #' "minus binary cross entropy", .(loss_name), val_loss | #' accuracy, acc, val_acc ) #' print(x) #' str(x) #' cat(draw_frame(x)) #' #' qchar_frame( #' x | #' 1 | #' 2 ) %.>% str(.) #' #' @export #' qchar_frame <- function(...) { env <- parent.frame() v <- do.call(bquote, list(substitute(alist(...)), where = env), envir = env) v <- lapply(seqi(2, length(v)), function(i) {v[[i]]}) lv <- length(v) if(lv<1) { return(data.frame()) } lengths <- vapply( v, function(vi) {nchar(paste(as.character(vi), collapse = ''))}, numeric(1)) if(any(lengths <= 0)) { stop("empty entry, this is often caused by an extra comma") } # inspect input cls <- vapply(v, class, character(1)) if(length(setdiff(cls, c("call", "character", "name", "numeric", "integer", "logical", "factor")))>0) { stop("wrapr::qchar_frame expects only strings, names, literals, operators, and commas") } if(sum(cls=="call") < 1) { # no rows case fr <- data.frame(x = character(0), stringsAsFactors = FALSE) colnames(fr) <- as.character(v[[1]]) if(lv>1) { for(i in 2:lv) { fr[[as.character(v[[i]])]] <- character(0) } } rownames(fr) <- NULL return(fr) } ncol <- match("call", cls) # unpack unpack_val <- function(vi) { if(length(vi)<=0) { stop("wrapr::qchar_frame unexpected NULL/empty element") } if(is.call(vi)) { if((length(vi)!=3) || (!is_infix(vi[[1]]))) { stop(paste("wrapr::qchar_frame unexpected operator", vi[[1]])) } vi <- lapply(as.list(vi)[-1], unpack_val) } as.character(unlist(vi)) } vu <- lapply(v, unpack_val) vu <- unlist(vu) ncell <- length(vu) nrow <- ncell/ncol if(abs(nrow - round(nrow))>0.1) { stop("wrapr::qchar_frame confused as to cell count (this can be an extra comma or mis-placed separator)") } fr <- as.data.frame(matrix(data = vu[-seq_len(ncol)], ncol=ncol, byrow = TRUE), stringsAsFactors = FALSE) colnames(fr) <- vu[seq_len(ncol)] rownames(fr) <- NULL fr } #' Render a simple data.frame in qchar_frame format. #' #' @param x data.frame (with character types). #' @param ... not used for values, forces later arguments to bind by name. #' @param unquote_cols character, columns to elide quotes from. #' @param adjust_for_auto_indent integer additional after first row padding. #' @return character #' #' @seealso \code{\link{build_frame}}, \code{\link{qchar_frame}} #' #' @examples #' #' controlTable <- wrapr::qchar_frame( #' "flower_part", "Length" , "Width" | #' "Petal" , Petal.Length , Petal.Width | #' "Sepal" , Sepal.Length , Sepal.Width ) #' cat(draw_framec(controlTable, unquote_cols = qc(Length, Width))) #' #' #' @export #' draw_framec <- function(x, ..., unquote_cols = character(0), adjust_for_auto_indent = 2) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::draw_framec") x_s <- substitute(x) if(!is.data.frame(x)) { stop("wrapr::draw_framec x needs to be a data.frame") } res <- "wrapr::qchar_frame()" nrow <- nrow(x) ncol <- ncol(x) if((nrow>=1) && (ncol<1)) { stop("wrapr::draw_framec bad input: no columns, but has rows") } qts <- function(v) { # wayts to quote: dput(), shQuote(), deparse() vapply(as.character(v), function(vi) { deparse(vi) }, character(1)) } if((nrow<1) || (ncol<1)) { if(ncol>=1) { res <- paste(qts(colnames(x)), collapse = ", ") res <- paste0("wrapr::qchar_frame(", res, ")") } } else { # convert to character matrix xq <- x for(ci in colnames(x)) { if(ci %in% unquote_cols) { xq[[ci]] <- as.character(x[[ci]]) } else { xq[[ci]] <- qts(as.character(x[[ci]])) } xq[[ci]][is.na(x[[ci]])] <- "NA_character_" } xm <- as.matrix(xq) xm <- matrix(data = as.character(xm), nrow = nrow, ncol = ncol) # convert header to values xm <- rbind(matrix(data = qts(colnames(x)), nrow = 1, ncol = ncol), xm) # compute padding widths <- nchar(xm) widths[is.na(as.numeric(widths))] <- 2 colmaxes <- matrix(data = apply(widths, 2, max), nrow = nrow+1, ncol = ncol, byrow = TRUE) padlens <- colmaxes - widths pads <- matrix(data = vapply(padlens, function(vi) { paste(rep(' ', vi), collapse = '') }, character(1)), nrow = nrow+1, ncol = ncol) # get intermediates seps <- matrix(data = ", ", nrow = nrow+1, ncol = ncol) seps[, ncol] <- " |" seps[nrow+1, ncol] <- " )" # format fmt <- matrix(data = paste0(xm, pads, seps), nrow = nrow+1, ncol = ncol) if(adjust_for_auto_indent>0) { pad <- paste(rep(" ", adjust_for_auto_indent), collapse = "") fmt[1, 1] <- gsub(", $", paste0(pad, ", "), fmt[1, 1]) for(i in wrapr::seqi(2, nrow(fmt))) { fmt[i, 1] <- paste0(pad, fmt[i, 1]) } } rlist <- vapply(seq_len(nrow+1), function(i) { paste(fmt[i, , drop=TRUE], collapse = '') }, character(1)) rlist <- paste0(" ", rlist) res <- paste(rlist, collapse = "\n") res <- paste0("wrapr::qchar_frame(\n", res, "\n") } if(is.name(x_s)) { res <- paste0(as.character(x_s), " <- ", res) } res }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/cf.R
#' Fit a stats::lm without carying back large structures. #' #' Please see \url{https://win-vector.com/2014/05/30/trimming-the-fat-from-glm-models-in-r/} for discussion. #' #' @param outcome character, name of outcome column. #' @param variables character, names of varaible columns. #' @param data data.frame, training data. #' @param ... not used, force later arguments to be used by name #' @param intercept logical, if TRUE allow an intercept term. #' @param weights passed to stats::glm() #' @param env environment to work in. #' @return list(model=model, summary=summary) #' #' @examples #' #' mk_data_example <- function(k) { #' data.frame( #' x1 = rep(c("a", "a", "b", "b"), k), #' x2 = rep(c(0, 0, 0, 1), k), #' y = rep(1:4, k), #' yC = rep(c(FALSE, TRUE, TRUE, TRUE), k), #' stringsAsFactors = FALSE) #' } #' #' res_lm <- clean_fit_lm("y", c("x1", "x2"), #' mk_data_example(1)) #' length(serialize(res_lm$model, NULL)) #' #' res_lm <- clean_fit_lm("y", c("x1", "x2"), #' mk_data_example(10000)) #' length(serialize(res_lm$model, NULL)) #' #' predict(res_lm$model, #' newdata = mk_data_example(1)) #' #' @export #' clean_fit_lm <- function(outcome, variables, data, ..., intercept = TRUE, weights = NULL, env = baseenv()) { force(env) wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::clean_fit_lm") if(is.null(weights)) { weights <- numeric(nrow(data)) + 1 } # work around this issue: # https://win-vector.com/2018/12/03/very-non-standard-calling-in-r/ wenv <- new.env(parent = env) assign("weights", weights, envir = wenv) f <- wrapr::mk_formula(outcome, variables, intercept = intercept, env = wenv) m <- stats::lm(f, data, weights = weights, model = FALSE, x = FALSE, y = FALSE) s <- stats::summary.lm(m) # take out large structures m$qr$qr <- NULL m$residuals <- NULL m$effects <- NULL m$fitted.values <- NULL m$call <- NULL m$model <- NULL m$weights <- NULL environment(m$terms) <- env list(model = m, summary = s) } #' Fit a stats::glm without carying back large structures. #' #' Please see \url{https://win-vector.com/2014/05/30/trimming-the-fat-from-glm-models-in-r/} for discussion. #' #' @param outcome character, name of outcome column. #' @param variables character, names of varaible columns. #' @param data data.frame, training data. #' @param ... not used, force later arguments to be used by name #' @param family passed to stats::glm() #' @param weights passed to stats::glm() #' @param intercept logical, if TRUE allow an intercept term. #' @param outcome_target scalar, if not NULL write outcome==outcome_target in formula. #' @param outcome_comparator one of "==", "!=", ">=", "<=", ">", "<", only use of outcome_target is not NULL. #' @param env environment to work in. #' @return list(model=model, summary=summary) #' #' @examples #' #' mk_data_example <- function(k) { #' data.frame( #' x1 = rep(c("a", "a", "b", "b"), k), #' x2 = rep(c(0, 0, 0, 1), k), #' y = rep(1:4, k), #' yC = rep(c(FALSE, TRUE, TRUE, TRUE), k), #' stringsAsFactors = FALSE) #' } #' #' res_glm <- clean_fit_glm("yC", c("x1", "x2"), #' mk_data_example(1), #' family = binomial) #' length(serialize(res_glm$model, NULL)) #' #' res_glm <- clean_fit_glm("yC", c("x1", "x2"), #' mk_data_example(10000), #' family = binomial) #' length(serialize(res_glm$model, NULL)) #' #' predict(res_glm$model, #' newdata = mk_data_example(1), #' type = "response") #' #' @export #' clean_fit_glm <- function(outcome, variables, data, ..., family, intercept = TRUE, outcome_target = NULL, outcome_comparator = "==", weights = NULL, env = baseenv()) { force(env) force(family) wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::clean_fit_glm") if(is.null(weights)) { weights <- numeric(nrow(data)) + 1 } # work around this issue: # https://win-vector.com/2018/12/03/very-non-standard-calling-in-r/ wenv <- new.env(parent = env) assign("weights", weights, envir = wenv) f <- wrapr::mk_formula(outcome, variables, intercept = intercept, outcome_target = outcome_target, outcome_comparator = outcome_comparator, env = wenv) m <- stats::glm(f, data, family = family, weights = weights) s <- stats::summary.glm(m) # take out large structures m$qr$qr <- NULL m$residuals <- NULL m$effects <- NULL m$fitted.values <- NULL m$call <- NULL m$linear.predictors <- NULL m$weights <- NULL m$prior.weights <- NULL m$data <- NULL m$model <- NULL m$y <- NULL environment(m$terms) <- env environment(m$formula) <- env list(model = m, summary = s) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/clean_fit.R
#' Coalesce values (NULL/NA on left replaced by values on the right). #' #' This is a simple "try to take values on the left, but fall back #' to the right if they are not available" operator. It is inspired #' by SQL coalesce and the notation is designed to #' evoke the idea of testing and the \code{C#} \code{??} null coalescing operator. #' \code{NA} and \code{NULL} are treated roughly equally: both are #' replaced regardless of available replacement value (with some exceptions). #' The exceptions are: if the left hand side is a non-zero length vector #' we preserve the vector type of the left-hand side and do not assign #' any values that vectors can not hold (NULLs and complex structures) and do not #' replace with a right argument list. #' #' This operator represents a compromise between the desire to replace #' length zero structures and NULL/NA values and the desire to preserve #' the first argument's structure (vector versus list). The order of #' operations has been chosen to be safe, convenient, and useful. Length zero #' lists are not treated as NULL (which is consistent with R in general). #' Note for non-vector operations on conditions we recommend looking into #' \code{\link[base:Logic]{isTRUE}}, which solves some problems even faster #' than coalesce style operators. #' #' When length(coalesce_left_arg)<=0 then #' return coalesce_right_arg if length(coalesce_right_arg)>0, otherwise #' return coalesce_left_arg. #' When length(coalesce_left_arg)>0: #' assume coalesce_left_arg is a list or vector and coalesce_right_arg #' is a list or vector that is either the same length as coalesce_left_arg #' or length 1. In this case replace NA/NULL elements of coalesce_left_arg #' with corresponding elements of coalesce_right_arg (re-cycling coalesce_right_arg #' when it is length 1). #' #' @param coalesce_left_arg vector or list. #' @param coalesce_right_arg vector or list. #' @return coalesce_left_arg with NA elements replaced. #' #' @examples #' #' c(NA, NA, NA) %?% 5 # returns c(5, 5, 5) #' c(1, NA, NA) %?% list(5) # returns c(1, 5, 5) #' c(1, NA, NA) %?% list(list(5)) # returns c(1, NA, NA) #' c(1, NA, NA) %?% c(NA, 20, NA) # returns c(1, 20, NA) #' NULL %?% list() # returns NULL #' NULL %?% c(1, NA) # returns c(1, NA) #' list(1, NULL, NULL) %?% c(3, 4, NA) # returns list(1, 4, NA_real_) #' list(1, NULL, NULL, NA, NA) %?% list(2, NULL, NA, NULL, NA) # returns list(1, NULL, NA, NULL, NA) #' c(1, NA, NA) %?% list(1, 2, list(3)) # returns c(1, 2, NA) #' c(1, NA) %?% list(1, NULL) # returns c(1, NA) #' c() %?% list(1, NA, NULL) # returns list(1, NA, NULL) #' c() %?% c(1, NA, 2) # returns c(1, NA, 2) #' #' @export #' coalesce <- function(coalesce_left_arg, coalesce_right_arg) { # avoid touching coalesce_right_arg if we can replace <- NULL nl <- length(coalesce_left_arg) if(nl>0) { replace <- is.na(coalesce_left_arg) | vapply(coalesce_left_arg, is.null, logical(1)) if(!any(replace)) { return(coalesce_left_arg) } } else { # zero length, prefer self unless coalesce_right_arg is non-trivial. if(length(coalesce_right_arg)>0) { return(coalesce_right_arg) } else { return(coalesce_left_arg) } } # now know nl>0 and some replacement is desired nr <- length(coalesce_right_arg) if(!(nr %in% c(1, nl))) { stop("wrapr::`%?%` (coalesce)` right argument must be same length as left or length 1") } # now know nl>0, nr = 1 or nl, and some replacement is desired. if(is.list(coalesce_left_arg)) { # treat left as a list, can hold NULLs. if(nr==nl) { # logical vector list assign coalesce_left_arg[replace] <- coalesce_right_arg[replace] } else { # logical vector assign of scalar coalesce_left_arg[replace] <- coalesce_right_arg[[1]] } } else { # treat left as a vector, can not hold NULLs or complex types if(nr==nl) { for(i in seq_len(nl)) { if(replace[[i]]) { v <- coalesce_right_arg[[i]] if(is.atomic(v) && length(v)==1) { coalesce_left_arg[[i]] <- v } } } } else { # logical vector with scalar v <- coalesce_right_arg[[1]] if(is.atomic(v) && length(v)==1) { coalesce_left_arg[replace] <- v } } } coalesce_left_arg } #' @describeIn coalesce coalesce operator #' @export `%?%` <- function(coalesce_left_arg, coalesce_right_arg) { coalesce(coalesce_left_arg, coalesce_right_arg) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/coalese_op.R
#' Check for duplicate rows. #' #' Check a simple data.frame (no list or exotic rows) for duplicate rows. #' #' @param data data.frame #' @return TRUE if there are no duplicate rows, else FALSE. #' #' @export #' has_no_dup_rows <- function(data) { if(!is.data.frame(data)) { stop("wrapr::has_no_dup_rows(data) data must be a data.frame") } ndata <- nrow(data) if(ndata<=1) { return(TRUE) } keyColNames <- colnames(data) nkey <- length(keyColNames) if(nkey<=0) { return(FALSE) } ## radix errors out in knitr situations https://github.com/WinVector/wrapr/issues/9 # idxs <- do.call(order, c(as.list(data), list(method = "radix"))) idxs <- do.call(order, as.list(data)) data <- data[idxs, , drop = FALSE] rownames(data) <- NULL new_value <- c(TRUE, rep(FALSE, ndata-1)) for(ki in keyColNames) { cA <- data[[ki]][-1] cB <- data[[ki]][-ndata] cAn <- is.na(cA) cBn <- is.na(cB) check <- ifelse(cAn | cBn, cAn != cBn, cA != cB) di <- c(TRUE, check) new_value <- new_value | di } return(isTRUE(all(new_value))) } # # timings back when we were using radix # n <- 1000 # set.seed(2352) # # d1 <- data.frame(x1 = sample(letters, n, replace = TRUE), # x2 = sample(letters, n, replace = TRUE), # x3 = sample(letters, n, replace = TRUE), # x4 = sample(letters, n, replace = TRUE)) # d1_decision <- anyDuplicated(d1)<=0 # d2 <- d1 # while((anyDuplicated(d2)<=0)==d1_decision) { # d2 <- data.frame(x1 = sample(letters, n, replace = TRUE), # x2 = sample(letters, n, replace = TRUE), # x3 = sample(letters, n, replace = TRUE), # x4 = sample(letters, n, replace = TRUE)) # } # # my_check <- function(values) { # all(sapply(values[-1], function(x) identical(values[[1]], x))) # } # # print(anyDuplicated(d1)<=0) # microbenchmark::microbenchmark( # any_dup = { anyDuplicated(d1)<=0 }, # has_no_dup = { wrapr::has_no_dup_rows(d1) }, # check = my_check # ) # # Unit: microseconds # # expr min lq mean median uq max neval cld # # any_dup 16528.260 21851.0965 31134.210 30628.08 39116.609 96021.977 100 b # # has_no_dup 728.621 900.9505 1031.029 964.23 1068.575 4182.615 100 a # # # print(anyDuplicated(d2)<=0) # microbenchmark::microbenchmark( # any_dup = { anyDuplicated(d2)<=0 }, # has_no_dup = { wrapr::has_no_dup_rows(d2) }, # check = my_check # ) # # Unit: microseconds # # expr min lq mean median uq max neval cld # # any_dup 16679.607 17874.35 20899.9830 19369.3610 21756.95 50894.236 100 b # # has_no_dup 735.003 859.79 973.4994 927.8125 1053.39 2099.416 100 a #' Check that a set of columns form unique keys. #' #' For local data.frame only. #' #' @param data data.frame to work with. #' @param keyColNames character array of column names to check. #' @return logical TRUE if the rows of data are unique addressable by the columns named in keyColNames. #' #' #' @examples #' #' d <- data.frame(key = c('a','a', 'b'), k2 = c(1 ,2, 2)) #' checkColsFormUniqueKeys(d, 'key') # should be FALSE #' checkColsFormUniqueKeys(d, c('key', 'k2')) # should be TRUE #' #' @export #' checkColsFormUniqueKeys <- function(data, keyColNames) { if(!is.data.frame(data)) { stop("wrapr::checkColsFormUniqueKeys data should be a data.frame") } if(length(keyColNames)!=length(unique(keyColNames, allowNAKeys=TRUE))) { stop("wrapr::checkColsFormUniqueKeys keyColNames must not have duplicates/NAs") } cn <- colnames(data) if(length(setdiff(keyColNames, cn))>0) { stop("wrapr::checkColsFormUniqueKeys all keyColNames must be columns of data") } # count the number of rows ndata <- nrow(data) if(ndata<=1) { return(TRUE) } if(length(keyColNames) <= 0) { return(FALSE) } data <- data[, keyColNames, drop = FALSE] rownames(data) <- NULL # identify duplicate rows, no duplicated is the obvious way, the # code below is an attempt at a speedup (at the cost of space). # return(anyDuplicated(data)<=0) return(has_no_dup_rows(data)) } #' Check two data.frames are equivalent after sorting columns and rows. #' #' Confirm two dataframes are equivalent after reordering columns and rows. #' #' @param d1 data.frame 1 #' @param d2 data.frame 2 #' @param ... force later arguments to bind by name #' @param tolerance numeric comparision tolerance #' @return logical TRUE if equivalent #' #' @export #' check_equiv_frames <- function(d1, d2, ..., tolerance = sqrt(.Machine$double.eps)) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::check_equiv_frames") if( (!is.data.frame(d1)) != (!is.data.frame(d2)) ) { return(FALSE) } d1 <- data.frame(d1) d2 <- data.frame(d2) if((nrow(d1)!=nrow(d2)) || (ncol(d1)!=ncol(d2))) { return(FALSE) } cols <- sort(colnames(d1)) c2 <- sort(colnames(d2)) if(!isTRUE(all.equal(cols, c2))) { return(FALSE) } d1 <- d1[, cols, drop=FALSE] d1 <- d1[orderv(d1), , drop=FALSE] rownames(d1) <- NULL d2 <- d2[, cols, drop=FALSE] d2 <- d2[orderv(d2), , drop=FALSE] rownames(d2) <- NULL for(c in cols) { c1 <- d1[[c]] c2 <- d2[[c]] if(is.numeric(c1) != is.numeric(c2)) { return(FALSE) } if(is.numeric(c1)) { if(!isTRUE(all.equal(c1, c2, tolerance=tolerance))) { return(FALSE) } } else { if(!isTRUE(all.equal(c1, c2))) { return(FALSE) } } } return(TRUE) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/compare_frames.R
#' Inline dot product. #' #' @param e1 first, or left argument. #' @param e2 second, or right argument. #' @return c(e1, c2) #' #' @examples #' #' c(1,2) %dot% c(3, 5) #' #' #' @rdname inline_dot #' #' @export #' `%dot%` <- function(e1, e2) { sum(e1 * e2) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/dot.R
#' Grep for column names from a \code{data.frame} #' #' #' #' @param pattern passed to \code{\link[base]{grep}} #' @param x data.frame to work with #' @param ... force later arguments to be passed by name #' @param ignore.case passed to \code{\link[base]{grep}} #' @param perl passed to \code{\link[base]{grep}} #' @param value passed to \code{\link[base]{grep}} #' @param fixed passed to \code{\link[base]{grep}} #' @param useBytes passed to \code{\link[base]{grep}} #' @param invert passed to \code{\link[base]{grep}} #' @return column names of x matching grep condition. #' #' @seealso \code{\link[base]{grep}}, \code{\link{grepv}} #' #' @examples #' #' #' d <- data.frame(xa=1, yb=2) #' #' # starts with #' grepdf('^x', d) #' #' # ends with #' grepdf('b$', d) #' #' @export #' grepdf <- function(pattern, x, ..., ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE ) { stop_if_dot_args(substitute(list(...)), "wrapr::grepdf") nms <- colnames(x) nms[base::grep(pattern, nms, ignore.case = ignore.case, perl = perl, value = value, fixed = fixed, useBytes = useBytes, invert = invert)] }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/grepdf.R
#' Return a vector of matches. #' #' @param pattern character scalar, pattern to match, passed to \code{\link[base]{grep}}. #' @param x character vector to match to, passed to \code{\link[base]{grep}}. #' @param ... not used, forced later arguments to bind by name. #' @param ignore.case logical, passed to \code{\link[base]{grep}}. #' @param perl logical, passed to \code{\link[base]{grep}}. #' @param fixed logical, passed to \code{\link[base]{grep}}. #' @param useBytes logical, passed \code{\link[base]{grep}}. #' @param invert passed to \code{\link[base]{grep}}. #' @return vector of matching values. #' #' @seealso \code{\link[base]{grep}}, \code{\link{grepdf}} #' #' @examples #' #' grepv("x$", c("sox", "xor")) #' #' @export #' grepv <- function(pattern, x, ..., ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE) { stop_if_dot_args(substitute(list(...)), "wrapr::grepv") x[base::grep(pattern = pattern, x = x, ignore.case = ignore.case, perl = perl, fixed = fixed, useBytes = useBytes, invert = invert)] }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/grepv.R
#' Build an anonymous function. #' #' #' @param params formal parameters of function, unbound names. #' @param body substituted body of function to map arguments into. #' @param env environment to work in. #' @return user defined function. #' #' @seealso \code{\link{lambda}}, \code{\link{defineLambda}}, \code{\link{named_map_builder}} #' #' @examples #' #' f <- makeFunction_se(as.name('x'), substitute({x*x})) #' f(7) #' #' #' g <- makeFunction_se(c(as.name('x'), as.name('y')), substitute({ x + 3*y })) #' g(1,100) #' #' #' @export #' makeFunction_se <- function(params, body, env = parent.frame()) { force(env) vars <- as.character(params) formals <- replicate(length(vars), quote(expr = )) names(formals) <- vars eval(call('function', as.pairlist(formals), body), envir = env, enclos = env) } #' Build an anonymous function of dot. #' #' @param body function body #' @param env environment to work in. #' @return user defined function. #' #' @seealso \code{\link{lambda}}, \code{\link{defineLambda}}, \code{\link{named_map_builder}}, \code{\link{makeFunction_se}} #' #' @examples #' #' f <- f.(sin(.) %.>% cos(.)) #' 7 %.>% f #' #' #' @export #' f. <- function(body, env = parent.frame()) { force(env) body <- substitute(body) wrapr::makeFunction_se('.', body, env) } #' Build an anonymous function. #' #' Mostly just a place-holder so lambda-symbol form has somewhere safe to hang its help entry. #' #' @param ... formal parameters of function, unbound names, followed by function body (code/language). #' @param env environment to work in #' @return user defined function. #' #' #' @seealso \code{\link{defineLambda}}, \code{\link{makeFunction_se}}, \code{\link{named_map_builder}} #' #' @examples #' #' #lambda-syntax: lambda(arg [, arg]*, body [, env=env]) #' # also works with lambda character as function name #' # print(intToUtf8(0x03BB)) #' #' # example: square numbers #' sapply(1:4, lambda(x, x^2)) #' #' # example more than one argument #' f <- lambda(x, y, x+y) #' f(2,4) #' #' #' @export #' lambda <- function(..., env = parent.frame()) { force(env) args <- base::substitute(list(...)) body <- args[[length(args)]] args <- args[-length(args)] params <- base::lapply(args[-1], base::as.name) wrapr::makeFunction_se(params, body, env) } #' Define lambda function building function. #' #' Use this to place a copy of the lambda-symbol #' function builder in your workspace. #' #' @param envir environment to work in. #' @param name character, name to assign to (defaults to Greek lambda). #' #' @seealso \code{\link{lambda}}, \code{\link{makeFunction_se}}, \code{\link{named_map_builder}} #' #' @examples #' #' defineLambda() #' # ls() #' #' @export #' defineLambda <- function(envir = parent.frame(), name = NULL) { force(envir) if(is.null(name)) { name <- intToUtf8(0x03BB) } assign(name, wrapr::lambda, envir = envir) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/lambda.R
# checking for valid unreserved names # this one is not vectorized # also don't allow dot to be used here as remapping that is problem in magrittr pipelines # this is essentially treating "." as reserved (which is more compatible with magrittr) # from: https://stackoverflow.com/questions/8396577/check-if-character-value-is-a-valid-r-object-name isValidAndUnreservedName <- function(string) { if(is.null(string)) { return(FALSE) } (is.character(string)) && (length(string)==1) && (string!='.') && (make.names(string,unique = FALSE, allow_ = TRUE) == string) } #' Restrict an alias mapping list to things that look like name assignments #' #' @param alias mapping list #' @param restrictToAllCaps logical, if true only use all-capitalized keys #' @return string to string mapping #' #' @examples #' #' alias <- list(region= 'east', str= "'seven'") #' aliasR <- restrictToNameAssignments(alias) #' print(aliasR) #' #' #' @export #' restrictToNameAssignments <- function(alias, restrictToAllCaps= FALSE) { # make sure alias is a list (not a named vector) alias <- as.list(alias) usableEntries <- vapply(names(alias), function(ai) { vi <- alias[[ai]] if(is.name(vi)) { vi <- as.character(vi) } isValidAndUnreservedName(ai) && isValidAndUnreservedName(vi) && ( (!restrictToAllCaps) || (toupper(ai)==ai)) }, logical(1)) # return sublist alias[usableEntries] } prepareAlias <- function(alias, strict) { # make sure alias is a list (not a named vector) alias <- as.list(alias) # skip any NULL slots nulls <- vapply(names(alias), is.null, logical(1)) | vapply(alias, is.null, logical(1)) alias <- alias[!nulls] if (length(unique(names(alias))) != length(names(alias))) { stop('wrapr::prepareAlias alias keys must be unique') } if(strict) { if ('.' %in% c(names(alias),as.character(alias))) { stop("wrapr::prepareAlias can not map to/from '.'") } } for (ni in names(alias)) { if (is.null(ni)) { stop('wrapr:let alias keys must not be null') } if (is.na(ni)) { stop('wrapr:let alias keys must not be NA') } if (!is.character(ni)) { stop('wrapr:let alias keys must all be strings') } if (length(ni) != 1) { stop('wrapr:let alias keys must all be scalars') } if (nchar(ni) <= 0) { stop('wrapr:let alias keys must be non-empty string') } if (strict && (!isValidAndUnreservedName(ni))) { stop(paste('wrapr:let alias key not a valid name: "', ni, '"')) } vi <- alias[[ni]] if (is.null(vi)) { stop('wrapr:let alias values must not be null') } if (is.name(vi)) { vi <- as.character(vi) } if (is.na(vi)) { stop('wrapr:let alias values must not be NA') } if (!is.character(vi)) { stop(paste('wrapr:let alias values must all be strings or names (', ni,'is class:', paste(class(vi), collapse=', '), ')')) } if (length(vi) != 1) { stop('wrapr:let alias values must all be single strings (not arrays or null)') } if (nchar(vi) <= 0) { stop('wrapr:let alias values must not be empty string') } if (strict && (!isValidAndUnreservedName(vi))) { stop(paste('wrapr:let alias value not a valid name: "', vi, '"')) } } alias <- lapply(alias, as.character) alias } #' Substitute text (note text can be a vector). #' #' @param alias mapping named list/vector to strings/names or general #' @param strexpr character vector source text to be re-written #' @return parsed R expression with substitutions #' #' @noRd #' letprep_str <- function(alias, strexpr) { if(!is.character(strexpr)) { stop("wrapr::letprep_str strexpr must be a character array") } body <- strexpr if(length(alias)>0) { # find a token not in alias or block testText <- paste(paste(c(names(alias), as.character(alias)), collapse = ' '), strexpr) tok <- "WRAPR_TOK" while(length(grep(tok,testText))>0) { tok <- paste0("WRAPR_TOK_",paste(sample(LETTERS, 15, replace = TRUE), collapse = '')) } # re-write the parse tree and prepare for execution in 2 stages to allows swaps alias1 <- paste(tok, seq_len(length(alias)), sep= '_') names(alias1) <- names(alias) alias2 <- as.character(alias) names(alias2) <- as.character(alias1) for(aliasi in list(alias1, alias2)) { for (ni in names(aliasi)) { value <- aliasi[[ni]] if(!is.null(value)) { value <- as.character(value) if(ni!=value) { pattern <- paste0("\\b", ni, "\\b") body <- gsub(pattern, value, body) } } } } } parse(text = body) } #' Substitute language elements. #' #' @param alias mapping named list/vector to strings/names or general #' @param lexpr language item #' @return R language element with substitutions #' #' @noRd #' letprep_lang <- function(alias, lexpr) { nexpr <- lexpr n <- length(nexpr) # just in case (establishes an invarient of n>=1) if(n<=0) { return(nexpr) } # left-hand sides of lists/calls are represented as keys nms <- names(nexpr) if(length(nms)>0) { for(i in seq_len(length(nms))) { ki <- as.character(nms[[i]]) if((length(ki)>0)&&(nchar(ki)>0)) { ri <- alias[[ki]] if((length(ri)>0)&&(ri!=ki)) { nms[[i]] <- ri } } } names(nexpr) <- nms } # special cases if(is.call(nexpr)) { callName <- as.character(nexpr[[1]]) if(length(callName)==1) { # get into special cases, # detect them very strictly and return out of them if((callName=='$') && (n==3)) { # special case a$"b" # let(c(x='y'), d$"x", eval=FALSE) # know length should be 3 from: # do.call('$',list(data.frame(x=1:3),'x','z')) # # Error in list(x = 1:3)$x : 3 arguments passed to '$' which requires 2 # know the 3rd argument can be treated as a name from: # data.frame(x=1:3)$1 # # Error: unexpected numeric constant in "data.frame(x=1:3)$1" nexpr[[2]] <- letprep_lang(alias, nexpr[[2]]) nexpr[[3]] <- letprep_lang(alias, as.name(nexpr[[3]])) return(nexpr) } } } # basic recurse, establish invariant n==1 if(n>1) { for(i in seq_len(n)) { # empty symbol (used to denote blank arguments like d[,1]) imitates missing on self call # also assigning null shortens expressions blankSym <- is.null(nexpr[[i]]) || (is.symbol(nexpr[[i]]) && (nchar(as.character(nexpr[[i]]))<=0)) if(!blankSym) { subi <- letprep_lang(alias, nexpr[[i]]) if(!is.null(subi)) { nexpr[[i]] <- subi } } } return(nexpr) } # don't re-map quoted strings (except above) if(is.character(nexpr)) { return(nexpr) } # this is the main re-mapper if(is.symbol(nexpr)) { # same as is.name() # symbol is not subsettable, so length==1 # as.name('x')[[1]] # # Error in as.name("x")[[1]] : object of type 'symbol' is not subsettable # and can't have names # names(as.name("x")) <- 'a' # ## Error in names(as.name("x")) <- "a" : # ## target of assignment expands to non-language object ki <- as.character(nexpr) ri <- alias[[ki]] if((length(ri)>0)&&(ri!=ki)) { return(as.name(ri)) } return(nexpr) } # fall-back return(nexpr) } #' Execute expr with name substitutions specified in alias. #' #' \code{let} implements a mapping from desired names (names used directly in the expr code) to names used in the data. #' Mnemonic: "expr code symbols are on the left, external data and function argument names are on the right." #' #' Please see the \code{wrapr} \code{vignette} for some discussion of let and crossing function call boundaries: \code{vignette('wrapr','wrapr')}. #' For formal documentation please see \url{https://github.com/WinVector/wrapr/blob/master/extras/wrapr_let.pdf}. #' Transformation is performed by substitution, so please be wary of unintended name collisions or aliasing. #' #' Something like \code{let} is only useful to get control of a function that is parameterized #' (in the sense it take column names) but non-standard (in that it takes column names from #' non-standard evaluation argument name capture, and not as simple variables or parameters). So \code{wrapr:let} is not #' useful for non-parameterized functions (functions that work only over values such as \code{base::sum}), #' and not useful for functions take parameters in straightforward way (such as \code{base::merge}'s "\code{by}" argument). #' \code{dplyr::mutate} is an example where #' we can use a \code{let} helper. \code{dplyr::mutate} is #' parameterized (in the sense it can work over user supplied columns and expressions), but column names are captured through non-standard evaluation #' (and it rapidly becomes unwieldy to use complex formulas with the standard evaluation equivalent \code{dplyr::mutate_}). #' \code{alias} can not include the symbol "\code{.}". #' #' #' The intent from is from the user perspective to have (if #' \code{a <- 1; b <- 2}): #' \code{let(c(z = 'a'), z+b)} to behave a lot like #' \code{eval(substitute(z+b, c(z=quote(a))))}. #' #' \code{let} deliberately checks that it is mapping only to legal \code{R} names; #' this is to discourage the use of \code{let} to make names to arbitrary values, as #' that is the more properly left to \code{R}'s environment systems. #' \code{let} is intended to transform #' "tame" variable and column names to "tame" variable and column names. Substitution #' outcomes that are not valid simple \code{R} variable names (produced with out use of #' back-ticks) are forbidden. It is suggested that substitution targets be written #' \code{ALL_CAPS} style to make them stand out. #' #' \code{let} was inspired by \code{gtools:strmacro()}. #' Please see \url{https://github.com/WinVector/wrapr/blob/master/extras/MacrosInR.md} for a discussion of macro tools in \code{R}. #' #' #' @param alias mapping from free names in expr to target names to use (mapping have both unique names and unique values). #' @param expr block to prepare for execution. #' @param ... force later arguments to be bound by name. #' @param envir environment to work in. #' @param subsMethod character substitution method, one of 'langsubs' (preferred), 'subsubs', or 'stringsubs'. #' @param strict logical if TRUE names and values must be valid un-quoted names, and not dot. #' @param eval logical if TRUE execute the re-mapped expression (else return it). #' @param debugPrint logical if TRUE print debugging information when in stringsubs mode. #' @return result of expr executed in calling environment (or expression if eval==FALSE). #' #' @seealso \code{\link[base]{bquote}}, \code{\link[base]{do.call}} #' #' @examples #' #' d <- data.frame( #' Sepal_Length=c(5.8,5.7), #' Sepal_Width=c(4.0,4.4), #' Species='setosa') #' #' mapping <- qc( #' AREA_COL = Sepal_area, #' LENGTH_COL = Sepal_Length, #' WIDTH_COL = Sepal_Width #' ) #' #' # let-block notation #' let( #' mapping, #' d %.>% #' transform(., AREA_COL = LENGTH_COL * WIDTH_COL) #' ) #' #' #' # Note: in packages can make assignment such as: #' # AREA_COL <- LENGTH_COL <- WIDTH_COL <- NULL #' # prior to code so targets don't look like unbound names. #' #' #' @export let <- function(alias, expr, ..., envir= parent.frame(), subsMethod= 'langsubs', strict= TRUE, eval= TRUE, debugPrint= FALSE) { force(envir) exprQ <- substitute(expr) # do this early before things enter local environment stop_if_dot_args(substitute(list(...)), "wrapr::let") allowedMethods <- c('langsubs', 'stringsubs', 'subsubs') if((!is.character(subsMethod)) || (length(subsMethod)!=1) || (!(subsMethod %in% allowedMethods))) { stop(paste("wrapr::let subsMethod must be one of:", paste(allowedMethods, collapse = ', '))) } alias <- prepareAlias(alias, strict=strict) exprS <- exprQ if(length(alias)>0) { if(subsMethod=='langsubs') { # recursive language implementation. # only replace matching symbols. exprS <- letprep_lang(alias, exprQ) } else if(subsMethod=='subsubs') { # substitute based solution, does not bind left-hand sides aliasN <- lapply(alias, as.name) exprS <- do.call(substitute, list(exprQ, aliasN)) } else if(subsMethod=='stringsubs') { # string substitution based implementation. # Similar to \code{gtools::strmacro} by Gregory R. Warnes. exprS <- letprep_str(alias, wrapr_deparse(exprQ)) } else { stop(paste("wrapr::let unexpected subsMethod '", subsMethod, "'")) } } if(debugPrint) { print(alias) print(exprS) } if(!eval) { return(exprS) } # try to execute expression in parent environment rm(list=setdiff(ls(), c('exprS', 'envir'))) eval(exprS, envir=envir, enclos=envir) } #' Inline let-block notation. #' #' Inline version of \code{let}-block. #' #' @param a (left argument) named character vector with target names as names, and replacement names as values. #' @param b (right argument) expression or block to evaluate under let substitution rules. #' @return evaluated block. #' #' @examples #' #' d <- data.frame( #' Sepal_Length=c(5.8,5.7), #' Sepal_Width=c(4.0,4.4), #' Species='setosa') #' #' # let-block notation #' let( #' qc( #' AREA_COL = Sepal_area, #' LENGTH_COL = Sepal_Length, #' WIDTH_COL = Sepal_Width #' ), #' d %.>% #' transform(., AREA_COL = LENGTH_COL * WIDTH_COL) #' ) #' #' # %in_block% notation #' qc( #' AREA_COL = Sepal_area, #' LENGTH_COL = Sepal_Length, #' WIDTH_COL = Sepal_Width #' ) %in_block% { #' d %.>% #' transform(., AREA_COL = LENGTH_COL * WIDTH_COL) #' } #' #' # Note: in packages can make assignment such as: #' # AREA_COL <- LENGTH_COL <- WIDTH_COL <- NULL #' # prior to code so targets don't look like unbound names. #' #' @export #' #' @seealso \code{\link{let}} #' `%in_block%` <- function(a, b) { env <- parent.frame() force(env) # probably do not need this step do.call(let, list( expr = substitute(b), alias = a, envir = env)) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/let.R
#' format a map. #' #' @param mp named vector or list #' @param ... not used, foce later arguments to bind by name. #' @param sep separator suffix, what to put after commas #' @param assignment assignment string #' @param quote_fn string quoting function #' @return character formatted representation #' #' @seealso \code{\link[base]{dput}}, \code{\link[utils]{capture.output}} #' #' @examples #' #' cat(map_to_char(c('a' = 'b', 'c' = 'd'))) #' cat(map_to_char(c('a' = 'b', 'd', 'e' = 'f'))) #' cat(map_to_char(c('a' = 'b', 'd' = NA, 'e' = 'f'))) #' cat(map_to_char(c(1, NA, 2))) #' #' @export #' map_to_char <- function(mp, ..., sep = " ", assignment = "=", quote_fn = base::shQuote) { stop_if_dot_args(substitute(list(...)), "wrapr::map_to_char") nms <- names(mp) vls <- as.character(mp) n <- length(vls) if(length(nms)<n) { nms <- c(nms, rep("", n - length(nms))) } nv <- character(n) for(i in seq_len(n)) { nmi <- nms[[i]] vli <- vls[[i]] qvli <- "NA" if(!is.na(vli)) { qvli <- quote_fn(vli) } if((!is.na(nmi))&&(nchar(nmi)>0)) { nv[[i]] <- paste(quote_fn(nmi), assignment, qvli) } else { nv[[i]] <- qvli } } paste0("c(", paste(nv, collapse = paste0(",", sep)), ")") }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/map_to_char.R
#' Map symbol names to referenced values if those values are string scalars (else throw). #' #' @param ... symbol names mapping to string scalars #' @return map from original symbol names to new names (names found in the current environment) #' #' @seealso \code{\link{let}} #' #' @examples #' #' x <- 'a' #' y <- 'b' #' print(mapsyms(x, y)) #' d <- data.frame(a = 1, b = 2) #' let(mapsyms(x, y), d$x + d$y) #' #' @export #' mapsyms <- function(...) { mapsyms_envir <- parent.frame() mapsyms_args <- as.list(substitute(list(...))) mapsyms_args <- lapply(seqi(2, length(mapsyms_args)), function(i) {mapsyms_args[[i]]}) mapsyms_names <- vapply(mapsyms_args, function(ai) { ai <- as.character(ai) if(length(ai)!=1) { stop("wrapr::mapsyms all arguments must be coercible into length-1 strings") } ai }, character(1)) mapsyms_dests <- lapply(mapsyms_names, function(ni) { get(ni, envir=mapsyms_envir)}) names(mapsyms_dests) <- mapsyms_names mapsyms_bads <- vapply(mapsyms_names, function(mavars_key_i) { mapsyms_val_i <- mapsyms_dests[[mavars_key_i]] (length(mapsyms_val_i)!=1) || (!is.character(mapsyms_val_i)) }, logical(1)) if(any(mapsyms_bads)) { stop(paste("wrapr::mapsyms columns not mapping to string scalars: ", paste(names(mapsyms_bads)[mapsyms_bads]))) } mapsyms_dests } #' Map up-cased symbol names to referenced values if those values are string scalars (else throw). #' #' @param ... symbol names mapping to string scalars #' @return map from original symbol names to new names (names found in the current environment) #' #' @seealso \code{\link{let}} #' #' @examples #' #' x <- 'a' #' print(map_upper(x)) #' d <- data.frame(a = "a_val") #' let(map_upper(x), paste(d$X, x)) #' #' @export #' map_upper <- function(...) { map_upper_envir <- parent.frame() map_upper_args <- as.list(substitute(list(...))) map_upper_args <- lapply(seqi(2, length(map_upper_args)), function(i) {map_upper_args[[i]]}) map_upper_names <- vapply(map_upper_args, function(ai) { ai <- as.character(ai) if(length(ai)!=1) { stop("wrapr::map_upper all arguments must be coercible into length-1 strings") } ai }, character(1)) map_upper_dests <- lapply(map_upper_names, function(ni) { get(ni, envir=map_upper_envir)}) names(map_upper_dests) <- map_upper_names map_upper_bads <- vapply(map_upper_names, function(mavars_key_i) { map_upper_val_i <- map_upper_dests[[mavars_key_i]] (length(map_upper_val_i)!=1) || (!is.character(map_upper_val_i)) }, logical(1)) if(any(map_upper_bads)) { stop(paste("wrapr::map_upper columns not mapping to string scalars: ", paste(names(map_upper_bads)[map_upper_bads]))) } names(map_upper_dests) <- toupper(names(map_upper_dests)) map_upper_dests }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/mapvars.R
#' Invert a permutation. #' #' For a permutation p build q such that p[q] == q[p] == seq_len(length(p)). #' Please see \url{https://win-vector.com/2017/05/18/on-indexing-operators-and-composition/} #' and \url{https://win-vector.com/2017/09/02/permutation-theory-in-action/}. #' #' @param p vector of length n containing each of seq_len(n) exactly once. #' @return vector q such that p[q] == q[p] == seq_len(length(p)) #' #' @examples #' #' p <- c(4, 5, 7, 8, 9, 6, 1, 3, 2, 10) #' q <- invert_perm(p) #' p[q] #' all.equal(p[q], seq_len(length(p))) #' q[p] #' all.equal(q[p], seq_len(length(p))) #' #' @export #' invert_perm <- function(p) { # see: https://win-vector.com/2017/05/18/on-indexing-operators-and-composition/ pinv <- seq_len(length(p)) pinv[p] <- seq_len(length(p)) pinv } #' Match one order to another. #' #' Build a permutation p such that ids1[p] == ids2. See \url{https://win-vector.com/2017/09/02/permutation-theory-in-action/}. #' #' @param ids1 unique vector of ids. #' @param ids2 unique vector of ids with sort(ids1)==sort(ids2). #' @return p integers such that ids1[p] == ids2 #' #' @examples #' #' ids1 <- c(4, 5, 7, 8, 9, 6, 1, 3, 2, 10) #' ids2 <- c(3, 6, 4, 8, 5, 7, 1, 9,10, 2) #' p <- match_order(ids1, ids2) #' ids1[p] #' all.equal(ids1[p], ids2) #' # note base::match(ids2, ids1) also solves this problem #' #' @export #' match_order <- function(ids1, ids2) { p1 <- order(ids1) p2 <- order(ids2) # invert p2 p2inv <- invert_perm(p2) # composition rule: (o1[p1])[p2inv] == o1[p1[p2inv]] # see: https://win-vector.com/2017/05/18/on-indexing-operators-and-composition/ p <- p1[p2inv] p }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/match_order.R
#' @importFrom stats update.formula lm NULL # build a sum as pluses for formula interface. r_plus <- function(vars, add_zero = FALSE) { res <- NULL if(add_zero) { res <- 0 } nv <- length(vars) if(nv<1) { if(is.null(res)) { res <- 1 } return(res) } if(is.null(res)) { firsti <- 2 res <- as.name(vars[[1]]) } else { firsti <- 1 } for(i in seqi(firsti, nv)) { res <- call("+", res, as.name(vars[[i]])) } res } #' Construct a formula. #' #' Safely construct a simple Wilkinson notation formula from the outcome (dependent variable) name #' and vector of input (independent variable) names. #' #' Note: outcome and variables #' are each intended to be simple variable names or column names (or .). They are not #' intended to specify #' interactions, I()-terms, transforms, general experessions or other complex formula terms. #' Essentially the same effect as \code{\link[stats:delete.response]{reformulate}}, but trying to avoid the #' \code{paste} currently in \code{\link[stats:delete.response]{reformulate}} by calling \code{\link[stats]{update.formula}} #' (which appears to work over terms). #' Another reasonable way to do this is just \code{paste(outcome, paste(variables, collapse = " + "), sep = " ~ ")}. #' #' Care must be taken with later arguments to functions like \code{lm()} whose help states: #' "All of weights, subset and offset are evaluated in the same way as variables in formula, that is first in data and then in the environment of formula." #' Also note \code{env} defaults to \code{baseenv()} to try and minimize refence leaks produced by the environemnt #' captured by the formal ending up stored in the resulting model for \code{lm()} and \code{glm()}. For #' behavior closer to \code{as.formula()} please set the \code{env} argument to \code{parent.frame()}. #' #' @param outcome character scalar, name of outcome or dependent variable. #' @param variables character vector, names of input or independent variables. #' @param ... not used, force later arguments to bind by name. #' @param intercept logical, if TRUE allow an intercept term. #' @param outcome_target scalar, if not NULL write outcome==outcome_target in formula. #' @param outcome_comparator one of "==", "!=", ">=", "<=", ">", "<", only use of outcome_target is not NULL. #' @param env environment to use in formula (unless extra_values is non empty, then this is a parent environemnt). #' @param extra_values if not empty extra values to be added to a new formula environment containing env. #' @param as_character if TRUE return formula as a character string. #' @return a formula object #' #' @seealso \code{\link[stats:delete.response]{reformulate}}, \code{\link[stats]{update.formula}} #' #' @examples #' #' f <- mk_formula("mpg", c("cyl", "disp")) #' print(f) #' (model <- lm(f, mtcars)) #' format(model$terms) #' #' f <- mk_formula("cyl", c("wt", "gear"), outcome_target = 8, outcome_comparator = ">=") #' print(f) #' (model <- glm(f, mtcars, family = binomial)) #' format(model$terms) #' #' @export #' mk_formula <- function(outcome, variables, ..., intercept = TRUE, outcome_target = NULL, outcome_comparator = "==", env = baseenv(), extra_values = NULL, as_character = FALSE) { force(env) wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::mk_formula") if((!is.character(outcome)) || (length(outcome)!=1)) { stop("wrapr::mk_formula outcome must be a length 1 character vector") } nv <- length(variables) if(nv>0) { if(!is.character(variables)) { stop("wrapr::mk_formula variables must be a character vector") } } outcome_name <- as.name(outcome) outcome_expr <- outcome_name if(length(extra_values)>0) { env <- new.env(parent = env) for(ni in names(extra_values)) { assign(ni, extra_values[[ni]], envir = env) } } if(!is.null(outcome_target)) { if(outcome_comparator=="==") { outcome_expr <- bquote((.(outcome_name) == .(outcome_target))) } else if(outcome_comparator=="!=") { outcome_expr <- bquote((.(outcome_name) != .(outcome_target))) } else if(outcome_comparator==">=") { outcome_expr <- bquote((.(outcome_name) >= .(outcome_target))) } else if(outcome_comparator=="<=") { outcome_expr <- bquote((.(outcome_name) <= .(outcome_target))) } else if(outcome_comparator==">") { outcome_expr <- bquote((.(outcome_name) > .(outcome_target))) } else if(outcome_comparator=="<") { outcome_expr <- bquote((.(outcome_name) < .(outcome_target))) } else { stop('wrapr::mk_formula outcome_comparator must be one of "==", "!=", ">=", "<=", ">", "<"') } } if(nv<1) { if(!intercept) { f <- do.call( "~", list(outcome_expr, 0), envir = env) } else { f <- do.call( "~", list(outcome_expr, 1), envir = env) } return(f) } rhs_expr <- r_plus(variables, !intercept) f <- do.call( "~", list(outcome_expr, rhs_expr), envir = env) if(as_character) { f <- paste(trimws(format(f)), collapse = ' ') } f }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/mk_formula.R
#' Named map builder. #' #' Set names of right-argument to be left-argument, and return right argument. #' Called from \code{:=} operator. #' #' @param targets names to set. #' @param values values to assign to names (and return). #' @return values with names set. #' #' @seealso \code{\link{lambda}}, \code{\link{defineLambda}}, \code{\link{makeFunction_se}} #' #' @examples #' #' #' c('a' := '4', 'b' := '5') #' # equivalent to: c(a = '4', b = '5') #' #' c('a', 'b') := c('1', '2') #' # equivalent to: c(a = '1', b = '2') #' #' # the important example #' name <- 'a' #' name := '5' #' # equivalent to: c('a' = '5') #' #' @export named_map_builder <- function(targets, values) { names <- as.character(targets) if(length(names)!=length(values)) { stop("wrapr::named_map_builder() names/values length mismatch") } names(values) <- names values } #' @rdname named_map_builder #' @export `:=` <- function(targets, values) { UseMethod(":=") } #' @export `:=.character` <- named_map_builder #' @export `:=.name` <- named_map_builder #' @export `:=.symbol` <- named_map_builder #' @export `:=.numeric` <- named_map_builder #' @export `:=.list` <- named_map_builder #' @export `:=.factor` <- named_map_builder #' @export `:=.logical` <- named_map_builder #' @rdname named_map_builder #' @export `%:=%` <- function(targets, values) { UseMethod("%:=%") } #' @export `%:=%.character` <- named_map_builder #' @export `%:=%.name` <- named_map_builder #' @export `%:=%.symbol` <- named_map_builder #' @export `%:=%.numeric` <- named_map_builder #' @export `%:=%.list` <- named_map_builder #' @export `%:=%.factor` <- named_map_builder #' @export `%:=%.logical` <- named_map_builder
/scratch/gouwar.j/cran-all/cranData/wrapr/R/namedMapBuilder.R
#' Order by a list of vectors. #' #' Produce an ordering permutation from a list of vectors. Essentially a non-\code{...} interface to \code{\link[base]{order}}. #' #' @param columns list of atomic columns to order on, can be a \code{data.frame}. #' @param ... not used, force later arguments to bind by name. #' @param na.last (passed to \code{\link[base]{order}}) for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed. #' @param decreasing (passed to \code{\link[base]{order}}) logical. Should the sort order be increasing or decreasing? For the "radix" method, this can be a vector of length equal to the number of arguments in \code{...}. For the other methods, it must be length one. #' @param method (passed to \code{\link[base]{order}}) the method to be used: partial matches are allowed. The default ("auto") implies "radix" for short numeric vectors, integer vectors, logical vectors and factors. Otherwise, it implies "shell". For details of methods "shell", "quick", and "radix", see the help for \code{\link[base]{sort}}. #' @return ordering permutation #' #' #' @seealso \code{\link[base]{order}}, \code{\link{sortv}} #' #' @examples #' #' d <- data.frame(x = c(2, 2, 3, 3, 1, 1), y = 6:1) #' d[order(d$x, d$y), , drop = FALSE] #' d[orderv(d), , drop = FALSE] #' #' @export #' orderv <- function(columns, ..., na.last = TRUE, decreasing = FALSE, method = c("auto", "shell", "radix")) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::orderv") if((!is.list(columns)) || (length(columns)<1)) { stop("wrapr::orderv columns must be a list containing at least one atomic vector") } columns <- as.list(columns) names(columns) <- NULL do.call(base::order, c( columns, list( na.last = na.last, decreasing = decreasing, method = method))) } #' Sort a data.frame. #' #' Sort a data.frame by a set of columns. #' #' @param data data.frame to sort. #' @param colnames column names to sort on. #' @param ... not used, force later arguments to bind by name. #' @param na.last (passed to \code{\link[base]{order}}) for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed. #' @param decreasing (passed to \code{\link[base]{order}}) logical. Should the sort order be increasing or decreasing? For the "radix" method, this can be a vector of length equal to the number of arguments in \code{...}. For the other methods, it must be length one. #' @param method (passed to \code{\link[base]{order}}) the method to be used: partial matches are allowed. The default ("auto") implies "radix" for short numeric vectors, integer vectors, logical vectors and factors. Otherwise, it implies "shell". For details of methods "shell", "quick", and "radix", see the help for \code{\link[base]{sort}}. #' @return ordering permutation #' #' #' @seealso \code{\link{orderv}} #' #' @examples #' #' d <- data.frame(x = c(2, 2, 3, 3, 1, 1), y = 6:1) #' sortv(d, c("x", "y")) #' #' @export #' sortv <- function(data, colnames, ..., na.last = TRUE, decreasing = FALSE, method = c("auto", "shell", "radix")) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::sortv") if(!is.data.frame(data)) { stop("wrapr::sortv data must be a data.frame") } if(length(colnames)<1) { return(data) } if(!is.character(colnames)) { stop("wrapr::sortv colnames must be of type character") } bads <- setdiff(colnames, colnames(data)) if(length(bads)>0) { stop(paste("wrapr::sortv data colnames that are not in colnames(data):", paste(bads, collapse = ", "))) } perm <- orderv(as.list(data[, colnames, drop = FALSE]), na.last = na.last, decreasing = decreasing, method = method) data[perm, , drop = FALSE] }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/orderv.R
#' Pack values into a named list. #' #' This function packs values given by name into a named list. #' #' @param ... values to pack, these should be specified by name (not as constants). #' @param .wrapr_private_var_env environment to evaluate in #' @return named list of values #' #' @seealso \code{\link{unpack}} #' #' @examples #' #' x <- 1 #' y <- 2 #' pack(x, y) # list(x = 1, y = 2) #' #' pack(a = x, y) # list(a = 1, y = 2) #' #' pack(a = 5, y) # list(a = 5, y = 2) #' #' pack(1, 2) # list('1' = 1, '2' = 2) #' #' v <- pack(x = 8, y = 9) # list(x = 8, y = 9) #' v -> unpack[x, y] #' print(x) # 8 #' print(y) # 9 #' #' @export #' pack <- function(..., .wrapr_private_var_env = parent.frame()) { force(.wrapr_private_var_env) values <- list(...) quoted <- qc(..., .wrapr_private_var_env = .wrapr_private_var_env) names <- names(quoted) if(is.null(names)) { names <- character(length(quoted)) } not_named <- nchar(names) <= 0 names[not_named] <- as.character(quoted[not_named]) if(length(names) != length(unique(names))) { stop("names were not unique") } names(values) <- names values }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/pack.R
#' @description #' \code{wrapr}: Wrap R Functions for Debugging and Parametric Programming #' #' #' Provides \code{DebugFnW()} to capture function context on error for #' debugging, and \code{let()} which converts non-standard evaluation interfaces to #' parametric standard evaluation interfaces. #' \code{DebugFnW()} captures the calling function and arguments prior to the #' call causing the exception, while #' the classic \code{options(error=dump.frames)} form captures at the #' moment of the exception #' itself (thus function arguments may not be at their starting values). #' \code{let()} rebinds (possibly unbound) names to names. #' #'For more information: #' \itemize{ #' \item \code{vignette('DebugFnW', package='wrapr')} #' \item \code{vignette('let', package='wrapr')} #' \item \code{vignette(package='wrapr')} #' \item Website: \url{https://github.com/WinVector/wrapr} #' \item \code{let} video: \url{https://youtu.be/iKLGxzzm9Hk?list=PLAKBwakacHbQp_Z66asDnjn-0qttTO-o9} #' \item Debug wrapper video: \url{https://youtu.be/zFEC9-1XSN8?list=PLAKBwakacHbQT51nPHex1on3YNCCmggZA}.} #' "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/wrapr/R/package.R
#' Partition as set of tables into a list. #' #' Partition a set of tables into a list of sets of tables. Note: removes rownames. #' #' @param tables_used character, names of tables to look for. #' @param partition_column character, name of column to partition by (tables should not have NAs in this column). #' @param ... force later arguments to bind by name. #' @param source_usage optional named map from tables_used names to sets of columns used. #' @param source_limit optional numeric scalar limit on rows wanted every source. #' @param tables named map from tables_used names to data.frames. #' @param env environment to also look for tables named by tables_used #' @return list of names maps of data.frames partitioned by partition_column. #' #' @seealso \code{\link{execute_parallel}} #' #' @examples #' #' d1 <- data.frame(a = 1:5, g = c(1, 1, 2, 2, 2)) #' d2 <- data.frame(x = 1:3, g = 1:3) #' d3 <- data.frame(y = 1) #' partition_tables(c("d1", "d2", "d3"), "g", tables = list(d1 = d1, d2 = d2, d3 = d3)) #' #' @export #' partition_tables <- function(tables_used, partition_column, ..., source_usage = NULL, source_limit = NULL, tables = NULL, env = NULL) { wrapr::stop_if_dot_args(substitute(list(...)), "rqdatatable::partition_tables") if((!is.character(partition_column)) || (length(partition_column)!=1)) { stop("rqdatatable::partition_tables partition column must be a single string") } # make sure all needed tables are in the ntables list ntables <- list() for(ni in tables_used) { if(!is.null(tables)) { ti <- tables[[ni]] } if(is.null(ti) && (!is.null(env))) { ti <- get(ni, envir = env) # should throw if not found } if(is.null(ti)) { stop(paste("rqdatatable::partition_tables could not find table:", ni)) } # front-load some error checking if(!is.data.frame(ti)) { stop(paste("rqdatatable::partition_tables all arguments must resolve to data.frames", ni, paste(class(ti), collapse = " "))) } nti <- colnames(ti) if(!is.null(source_usage)) { nsi <- source_usage[[ni]] missing <- setdiff(nsi, nti) if(length(missing)>0) { stop(paste("rqdatatable::ex_data_table_parallel missing required columns", ni, paste(missing, collapse = " "))) } if((partition_column %in% nti) && (!(partition_column %in% nsi))) { # preserve partition column nsi <- c(nsi, partition_column) } } else { nsi <- nti } if(is.null(source_limit) || (nrow(ti)>source_limit)) { ti <- ti[ , nsi, drop = FALSE] } else { ti <- ti[seq_len(source_limit), nsi, drop = FALSE] } rownames(ti) <- NULL ntables[[ni]] <- ti } ti <- NULL env <- NULL tables <- NULL # get a list of values of the partition column levels <- character(0) for(ni in names(ntables)) { ti <- ntables[[ni]] if(partition_column %in% colnames(ti)) { if(any(is.na(ti[[partition_column]]))) { stop(paste("rqdatatable::ex_data_table_parallel NAs in partation_column for table ", ni)) } levels <- unique(c(levels, as.character(ti[[partition_column]]))) } } if(length(levels)<=0) { stop(paste("rqdatatable::ex_data_table_parallel no values found for partition column", partition_column)) } split_tabs <- lapply( names(ntables), function(ni) { ti <- ntables[[ni]] if(partition_column %in% colnames(ti)) { split(ti, factor(as.character(ti[[partition_column]]), levels = levels), drop = FALSE) } else { NULL } }) names(split_tabs) <- names(ntables) # build a list of tablesets tablesets <- lapply(levels, function(li) { nti <- ntables for(ni in names(ntables)) { ti <- ntables[[ni]] if(partition_column %in% colnames(ti)) { ti <- split_tabs[[ni]][[li]] } rownames(ti) <- NULL nti[[ni]] <- ti } nti }) names(tablesets) <- levels tablesets } #' Execute f in parallel partitioned by partition_column. #' #' Execute f in parallel partitioned by \code{partition_column}, see #' \code{\link{partition_tables}} for details. #' #' @param tables named map of tables to use. #' @param partition_column character name of column to partition on #' @param f function to apply to each tableset signature is function takes a single argument that is a named list of data.frames. #' @param ... force later arguments to bind by name. #' @param cl parallel cluster. #' @param debug logical if TRUE use lapply instead of parallel::clusterApplyLB. #' @param env environment to look for values in. #' @return list of f evaluations. #' #' @seealso \code{\link{partition_tables}} #' #' @examples #' #' if(requireNamespace("parallel", quietly = TRUE)) { #' cl <- parallel::makeCluster(2) #' #' d <- data.frame(x = 1:5, g = c(1, 1, 2, 2 ,2)) #' f <- function(dl) { #' d <- dl$d #' d$s <- sqrt(d$x) #' d #' } #' r <- execute_parallel(list(d = d), f, #' partition_column = "g", #' cl = cl) %.>% #' do.call(rbind, .) %.>% #' print(.) #' #' parallel::stopCluster(cl) #' } #' #' @export #' execute_parallel <- function(tables, f, partition_column, ..., cl = NULL, debug = FALSE, env = parent.frame()) { force(env) tablesets <- partition_tables(names(tables), partition_column = partition_column, tables = tables, env = env) if(debug || (!requireNamespace("parallel", quietly = TRUE))) { res <- lapply(tablesets, f) } else { # dispatch the operation in parallel res <- parallel::clusterApplyLB(cl, tablesets, f) } names(res) <- names(tablesets) res }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/partition_tables.R
#' Inline character paste0. #' #' @param e1 first, or left argument. #' @param e2 second, or right argument. #' @return c(e1, c2) #' #' @examples #' #' "a" %p% "b" #' #' c("a", "b") %p% "_d" #' #' @rdname inline_paste0 #' #' @export #' `%p%` <- function(e1, e2) { paste0(e1, e2) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/plus.R
#' Pseudo aggregator. #' #' Take a vector or list and return the first element (pseudo-aggregation or projection). #' If the argument length is zero or there are different items throw in an error. #' #' This function is useful in some split by column situations as a safe and legible #' way to convert vectors to scalars. #' #' @param x should be a vector or list of items. #' @param ... force later arguments to be passed by name #' @param strict logical, should we check value uniqueness. #' @return x[[1]] (or throw if not all items are equal or this is an empty vector). #' #' @examples #' #' d <- data.frame( #' group = c("a", "a", "b"), #' stringsAsFactors = FALSE) #' dl <- lapply( #' split(d, d$group), #' function(di) { #' data.frame( #' # note: di$group is a possibly length>1 vector! #' # pseudo aggregate it to the value that is #' # constant for each group, confirming it is constant. #' group_label = psagg(di$group), #' group_count = nrow(di), #' stringsAsFactors = FALSE #' ) #' }) #' do.call(rbind, dl) #' #' @export #' psagg <- function(x, ..., strict = TRUE) { stop_if_dot_args(substitute(list(...)), "wrapr::psagg") len <- length(x) if(len<1) { stop("wrapr::psagg length zero argument") } v <- x[[1]] if(len>1) { null_pos <- vapply(x, is.null, logical(1)) if(any(null_pos)) { if(!all(null_pos)) { stop("wrapr::psagg argument mix of NULLs and non-NULLs") } return(v) } na_pos <- vapply(x, is.na, logical(1)) if(any(na_pos)) { if(!all(na_pos)) { stop("wrapr::psagg argument mix of NAs and non-NAs") } return(v) } if(strict) { if(length(unique(x))!=1) { stop("wrapr::psagg argument values are varying") } } } v }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/psagg.R
#' Quote expressions. #' #' Accepts arbitrary un-parsed expressions as #' to allow forms such as "Sepal.Length >= 2 * Sepal.Width". #' (without the quotes). #' #' \code{qe()} uses #' \code{bquote()} \code{.()} quasiquotation escaping notation, #' and \code{.(-)} "string quotes, string to name" notation. #' #' @param ... assignment expressions. #' @return array of quoted assignment expressions. #' #' @seealso \code{\link{qc}}, \code{\link{qae}} #' #' @examples #' #' ratio <- 2 #' #' exprs <- qe(Sepal.Length >= ratio * Sepal.Width, #' Petal.Length <= 3.5) #' print(exprs) #' #' exprs <- qe(Sepal.Length >= .(ratio) * Sepal.Width, #' Petal.Length <= 3.5) #' print(exprs) #' #' @export #' qe <- function(...) { #e_terms <- substitute(list(...)) .wrapr_private_var_env <- parent.frame() .wrapr_private_var_env <- build_minus_fn_env(.wrapr_private_var_env) e_terms <- do.call(bquote, list(substitute(list(...)), where = .wrapr_private_var_env), envir = .wrapr_private_var_env) if(length(setdiff(names(e_terms), ""))>0) { stop("wrapr::qe() unexpected names/arguments") } # e_terms is a list of k+1 items, first is "list" the rest are captured expressions len <- length(e_terms) # first slot is "list" if(len<=1) { return(character(0)) } rhs <- character(len-1) for(i in (2:len)) { ei <- e_terms[[i]] rhs[[i-1]] <- wrapr_deparse(ei) } rhs } #' Quote assignment expressions (name = expr, name := expr, name \%:=\% expr). #' #' Accepts arbitrary un-parsed expressions as #' assignments to allow forms such as "Sepal_Long := Sepal.Length >= 2 * Sepal.Width". #' (without the quotes). #' Terms are expressions of the form "lhs := rhs", "lhs = rhs", "lhs \%:=\% rhs". #' #' \code{qae()} uses #' \code{bquote()} \code{.()} quasiquotation escaping notation, #' and \code{.(-)} "string quotes, string to name" notation. #' #' @param ... assignment expressions. #' @return array of quoted assignment expressions. #' #' @seealso \code{\link{qc}}, \code{\link{qe}} #' #' @examples #' #' ratio <- 2 #' #' exprs <- qae(Sepal_Long := Sepal.Length >= ratio * Sepal.Width, #' Petal_Short = Petal.Length <= 3.5) #' print(exprs) #' #' exprs <- qae(Sepal_Long := Sepal.Length >= .(ratio) * Sepal.Width, #' Petal_Short = Petal.Length <= 3.5) #' print(exprs) #' #' # library("rqdatatable") #' # datasets::iris %.>% #' # extend_se(., exprs) %.>% #' # summary(.) #' #' @export #' qae <- function(...) { # convert char vector into spliceable vector # from: https://github.com/tidyverse/rlang/issues/116 #ae_terms <- substitute(list(...)) .wrapr_private_var_env <- parent.frame() .wrapr_private_var_env <- build_minus_fn_env(.wrapr_private_var_env) ae_terms <- do.call(bquote, list(substitute(list(...)), where = .wrapr_private_var_env), envir = .wrapr_private_var_env) # ae_terms is a list of k+1 items, first is "list" the rest are captured expressions len <- length(ae_terms) # first slot is "list" if(len<=1) { return(character()) } nms <- names(ae_terms) lhs <- character(len-1) rhs <- character(len-1) for(i in (2:len)) { ei <- ae_terms[[i]] if(missing(ei)) { stop("saw missing argument, often this is caused by an extra comma") } ni <- nms[[i]] li <- length(ei) vi <- "" if((!is.null(ni)) && (!is.na(ni)) && (is.character(ni)) && (nchar(ni)>0)) { vi <- wrapr_deparse(ei) } else { if((!(as.character(ei[[1]]) %in% c(':=', '%:=%'))) || (li<2)) { stop("wrapr::qae() terms must be of the form: sym := exprm, sym = expr, or sym %:=% expr") } ni <- as.character(ei[[2]])[[1]] if(li>2) { vi <- lapply(3:li, function(j) { wrapr_deparse(ei[[j]]) }) vi <- paste(vi, collapse = "\n") } } if(is.null(ni)) { stop("wrapr::qae terms must all have names (either from =, :=, or %:=%)") } lhs[[i-1]] <- ni rhs[[i-1]] <- vi } lhs := rhs } #' Quote argument as a string. #' #' qs() uses bquote() .() quasiquotation escaping notation. #' #' @param s expression to be quoted as a string. #' @return character #' #' @examples #' #' x <- 7 #' #' qs(a == x) #' #' qs(a == .(x)) #' #' @export #' qs <- function(s) { # wrapr_deparse(substitute(s)) .wrapr_private_var_env <- parent.frame() do.call(bquote, list(substitute(s), where = .wrapr_private_var_env), envir = .wrapr_private_var_env) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/qae.R
#' Quoting version of c() array concatenate. #' #' The qc() function is intended to help quote user inputs. #' #' qc() a convenience function allowing the user to elide #' excess quotation marks. It quotes its arguments instead #' of evaluating them, except in the case of a nested #' call to qc() or c(). Please see the examples for #' typical uses both for named and un-named character vectors. #' #' #' qc() uses bquote() .() quasiquotation escaping notation. #' Also take care: argumetns are parsed by R before being passed to #' qc(). This means 01 is interpreted as 1 and a string such as 0z1 #' is a syntax error. Some notes on this can be found here: #' https://github.com/WinVector/wrapr/issues/15#issuecomment-962092462 #' #' #' @param ... items to place into an array #' @param .wrapr_private_var_env environment to evaluate in #' @return quoted array of character items #' #' @seealso \code{\link{qe}}, \code{\link{qae}}, \code{\link[base]{bquote}}, \code{\link{bc}}, \code{\link{sx}} #' #' @examples #' #' a <- "x" #' #' qc(a) # returns the string "a" (not "x") #' #' qc(.(a)) # returns the string "x" (not "a") #' #' qc(.(a) := a) # returns c("x" = "a") #' #' qc("a") # return the string "a" (not "\"a\"") #' #' qc(sin(x)) # returns the string "sin(x)" #' #' qc(a, qc(b, c)) # returns c("a", "b", "c") #' #' qc(a, c("b", "c")) # returns c("a", "b", "c") #' #' qc(x=a, qc(y=b, z=c)) # returns c(x="a", y="b", z="c") #' #' qc('x'='a', wrapr::qc('y'='b', 'z'='c')) # returns c(x="a", y="b", z="c") #' #' c(a = c(a="1", b="2")) # returns c(a.a = "1", a.b = "2") #' qc(a = c(a=1, b=2)) # returns c(a.a = "1", a.b = "2") #' qc(a := c(a=1, b=2)) # returns c(a.a = "1", a.b = "2") #' #' #' @export #' qc <- function(..., .wrapr_private_var_env = parent.frame()) { # invariant: returns are always character vectors force(.wrapr_private_var_env) #.wrapr_private_var_args <- substitute(list(...)) .wrapr_private_var_args <- do.call(bquote, list(substitute(list(...)), where = .wrapr_private_var_env), envir = .wrapr_private_var_env) if(length(.wrapr_private_var_args)<=1) { return(character(0)) } .wrapr_private_var_names <- names(.wrapr_private_var_args) .wrapr_private_var_res <- lapply( 2:length(.wrapr_private_var_args), function(.wrapr_private_var_i) { .wrapr_private_var_ei <- .wrapr_private_var_args[[.wrapr_private_var_i]] if(missing(.wrapr_private_var_ei)) { stop("saw missing argument to qc, the cause is often an extra comma in the argument list") } .wrapr_private_var_ni <- NULL if(.wrapr_private_var_i<=length(.wrapr_private_var_names)) { .wrapr_private_var_ni <- .wrapr_private_var_names[[.wrapr_private_var_i]] if(nchar(.wrapr_private_var_ni)<=0) { .wrapr_private_var_ni <- NULL } } if(is.name(.wrapr_private_var_ei)) { # names are scalars .wrapr_private_var_ei <- as.character(.wrapr_private_var_ei) if(!is.null(.wrapr_private_var_ni)) { names(.wrapr_private_var_ei) <- .wrapr_private_var_ni } return(.wrapr_private_var_ei) } if(is.language(.wrapr_private_var_ei)) { if(is.call(.wrapr_private_var_ei)) { .wrapr_private_var_fnname <- deparse(.wrapr_private_var_ei[[1]]) .wrapr_private_var_fnname <- gsub("[[:space:]]+", "", .wrapr_private_var_fnname) if(isTRUE(.wrapr_private_var_fnname %in% c(":=", "%:=%"))) { v <- do.call(qc, c(list(.wrapr_private_var_ei[[3]]), list(.wrapr_private_var_env = .wrapr_private_var_env)), envir = .wrapr_private_var_env) nms <- do.call(qc, c(list(.wrapr_private_var_ei[[2]]), list(.wrapr_private_var_env = .wrapr_private_var_env)), envir = .wrapr_private_var_env) if((length(nms)==1)&&(length(nms)<length(v))) { nms <- nms[rep(1, length(v))] } if(length(names(v))>0) { nms <- paste(nms, names(v), sep=".") } names(v) <- nms return(v) } if(isTRUE(.wrapr_private_var_fnname %in% c("qc", "wrapr::qc", "c", "base::c", "%c%", "`%c%`", "%qc%", "`%qc%`"))) { # this is the recursive case qc('x'='a', qc('y'='b', 'z'='c')) .wrapr_private_var_ei <- eval(.wrapr_private_var_ei, envir = .wrapr_private_var_env, enclos = .wrapr_private_var_env) nms <- names(.wrapr_private_var_ei) .wrapr_private_var_ei <- as.character(.wrapr_private_var_ei) if(!is.null(.wrapr_private_var_ni)) { nms <- paste(.wrapr_private_var_ni, nms, sep = '.') } names(.wrapr_private_var_ei) <- nms return(.wrapr_private_var_ei) } } # other case: quote expression .wrapr_private_var_ei <- paste(deparse(.wrapr_private_var_ei), collapse = "\n") if(!is.null(.wrapr_private_var_ni)) { names(.wrapr_private_var_ei) <- .wrapr_private_var_ni } return(.wrapr_private_var_ei) } if(is.vector(.wrapr_private_var_ei) || is.list(.wrapr_private_var_ei)) { if(length(.wrapr_private_var_ei)<=0) { return(character(0)) } } # base case, character vectors, list, and objects .wrapr_private_var_ei <- paste(as.character(.wrapr_private_var_ei), collapse = " ") if(!is.null(.wrapr_private_var_ni)) { names(.wrapr_private_var_ei) <- .wrapr_private_var_ni } return(.wrapr_private_var_ei) }) do.call(c, .wrapr_private_var_res, envir = .wrapr_private_var_env) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/qc.R
#' Increasing whole-number sequence. #' #' Return an in increaing whole-number sequence from a to b inclusive (return integer(0) if none such). Allows for safe iteraton. #' #' @param a scalar lower bound #' @param b scalar upper bound #' @return whole number sequence #' #' @examples #' #' # print 3, 4, and then 5 #' for(i in seqi(3, 5)) { #' print(i) #' } #' #' # empty #' for(i in seqi(5, 2)) { #' print(i) #' } #' #' @export #' seqi <- function(a, b) { a = ceiling(a) b = floor(b) if(a>b) { return(integer(0)) } base::seq(a, b, by = 1L) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/seqi.R
#' Split strings at {}-pairs. #' #' @param s string or list of strings to split. #' @param open_symbol symbol to start marking. #' @param close_symbol symbol to end marking. #' @return array or list of split strings. #' #' @examples #' #' split_at_brace_pairs("{x} + y + {z}") #' #' @export #' split_at_brace_pairs <- function(s, open_symbol = "{", close_symbol = "}") { if(length(s)<1) { return(s) } if((is.list(s))||(length(s)>1)) { return(lapply(s, function(si) { split_at_brace_pairs(si, open_symbol = open_symbol, close_symbol = close_symbol) })) } if(!is.character(s)) { return(s) } nc <- nchar(s) if(nc<1) { return(s) } lefts <- as.numeric(gregexpr(open_symbol, s, fixed = TRUE)[[1]]) if(length(lefts)<=0) { return(s) } rights <- as.numeric(gregexpr(close_symbol, s, fixed = TRUE)[[1]]) ng = length(lefts) # lefts and rights are supposed to be alternating, starting with left if(length(rights)!=ng) { return(s) } rights = rights + nchar(close_symbol) - 1 if(!isTRUE(all(lefts<rights))) { return(s) } if(!isTRUE(all(lefts[-1]>rights[-ng]))) { return(s) } # extract the segments res <- character(0) next_to_take <- 1 for(i in seq_len(ng)) { # look for previous if(next_to_take<lefts[[i]]) { res <- c(res, substr(s, next_to_take, lefts[[i]]-1)) } # take symbol res <- c(res, substr(s, lefts[[i]], rights[[i]])) next_to_take <- rights[[i]] + 1 } if(next_to_take<=nc) { res <- c(res, substr(s, next_to_take, nc)) } Filter(function(p) {nchar(trimws(p, which="both"))>0}, res) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/split_at_brace_pairs.R
#' Stop with message if dot_args is a non-trivial list. #' #' Generate a stop with a good error message if the dots argument was a non-trivial list. #' Useful in writing functions that force named arguments. #' #' @param dot_args substitute(list(...)) from another function. #' @param msg character, optional message to prepend. #' @return NULL or stop() #' #' @examples #' #' f <- function(x, ..., inc = 1) { #' stop_if_dot_args(substitute(list(...)), "f") #' x + inc #' } #' f(7) #' f(7, inc = 2) #' tryCatch( #' f(7, 2), #' error = function(e) { print(e) } #' ) #' #' @export #' stop_if_dot_args <- function(dot_args, msg = "") { if(length(dot_args)>1) { unams <- names(dot_args)[-1] uvals <- as.character(dot_args)[-1] saw_blank <- any(nchar(uvals)<=0) uvals <- sQuote(uvals) unams[is.null(unams)] <- "" not_null <- nchar(unams)>0 unams[not_null] <- paste0(unams[not_null], " = ") unams[!not_null] <- "" str <- paste(paste0(unams, uvals), collapse = ", ") if(saw_blank) { str <- paste(str, "(empty arguments can be caused by having exta commas in the function call)") } stop(paste(msg, "unexpected arguments:", str), call. = FALSE) } NULL }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/stop_if_dot_args.R
#' Split a string, keeping separator regions #' #' @param x character string to split (length 1 vector) #' @param split split pattern #' @param ... force later arguments to bind by name #' @param ignore.case passed to \code{gregexpr} #' @param perl passed to \code{gregexpr} #' @param fixed passed to \code{gregexpr} #' @param useBytes passed to \code{gregexpr} #' @return list of string segments annotated with is_sep. #' #' @seealso \code{\link{sinterp}}, \code{\link{si}} #' #' @examples #' #' strsplit_capture("x is .(x) and x+1 is .(x+1)", "\\.\\([^()]+\\)") #' #' @export #' strsplit_capture <- function(x, split, ..., ignore.case = FALSE, fixed = FALSE, perl = FALSE, useBytes = FALSE) { if(!is.character(x)) { stop("wrapr::strsplit_capture x must be character") } if(length(x)!=1) { stop("wrapr::strsplit_capture x must be length 1") } wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::strsplit_capture") matches <- gregexpr(split, x, ignore.case = ignore.case, perl = perl, fixed = fixed, useBytes = useBytes)[[1]] lens <- attr(matches, "match.length", exact = TRUE) idxs <- as.integer(matches) if((length(idxs)<1) || (idxs[[1]]<1)) { attr(x, "is_sep") <- FALSE return(list(x)) } match_posns <- logical(nchar(x)+1) match_posns[idxs] <- TRUE intervals <- sort(unique(c(1, nchar(x)+1, idxs, idxs+lens))) pieces <- lapply( seq_len(length(intervals)-1), function(i) { is_match <- match_posns[[intervals[[i]]]] pi <- substr(x, intervals[[i]], intervals[[i+1]]-1) attr(pi, "is_sep") <- is_match pi }) pieces } #' Dot substitution string interpolation. #' #' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called. #' #' See also #' \url{https://CRAN.R-project.org/package=R.utils}, #' \url{https://CRAN.R-project.org/package=rprintf}, #' and \url{https://CRAN.R-project.org/package=glue}. #' #' #' @param str charater string(s) to be substituted into #' @param ... force later arguments to bind by name #' @param envir environemnt to look for values #' @param enclos enclosing evaluation environment #' @param match_pattern regexp to find substitution targets. #' @param removal_patterns regexps to remove markers from substitution targets. #' @return modified strings #' #' @seealso \code{\link{strsplit_capture}}, \code{\link{si}} #' #' @examples #' #' x <- 7 #' sinterp("x is .(x), x+1 is .(x+1)\n.(x) is odd is .(x%%2 == 1)") #' #' # Because matching is done by a regular expression we #' # can not use arbitrary depths of nested parenthesis inside #' # the interpolation region. The default regexp allows #' # one level of nesting (and one can use {} in place #' # of parens in many places). #' sinterp("sin(x*(x+1)) is .(sin(x*{x+1}))") #' #' # We can also change the delimiters, #' # in this case to !! through the first whitespace. #' sinterp(c("x is !!x , x+1 is !!x+1 \n!!x is odd is !!x%%2==1"), #' match_pattern = '!![^[:space:]]+[[:space:]]?', #' removal_patterns = c("^!!", "[[:space:]]?$")) #' #' @export #' sinterp <- function(str, ..., envir = parent.frame(), enclos = parent.frame(), match_pattern = "\\.\\((([^()]+)|(\\([^()]*\\)))+\\)", removal_patterns = c("^\\.\\(", "\\)$")) { force(envir) if(!is.environment(envir)) { envir <- list2env(as.list(envir), parent = parent.frame()) } force(enclos) if(!is.environment(enclos)) { enclos <- list2env(as.list(enclos), parent = parent.frame()) } wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::sinterp") if(!is.character(str)) { stop("wrapr::sinterp str must be of class character") } if(length(str) <= 0) { stop("wrapr::sinterp str must be of length at least 1") } orig_names <- names(str) res <- vapply( str, function(stri) { pi <- strsplit_capture(stri, match_pattern) npi <- length(pi) xlated <- list() for(j in seq_len(npi)) { pij <- pi[[j]] if(!isTRUE(attr(pij, "is_sep", exact = TRUE))) { xlated <- c(xlated, list(as.character(pij))) # strip attributes. } else { expr <- as.character(pij) # strip attributes. for(rp in removal_patterns) { expr <- as.character(gsub(rp, "", expr)) } val <- eval(parse(text = expr), envir = envir, enclos = enclos) val <- deparse(val) xlated <- c(xlated, list(val)) } } do.call(paste0, xlated) }, character(1)) if(length(orig_names) <= 0) { names(res) <- NULL } return(res) } #' Dot substitution string interpolation. #' #' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called. #' \code{sinterp} and \code{si} are synonyms. #' #' See also #' \url{https://CRAN.R-project.org/package=R.utils}, #' \url{https://CRAN.R-project.org/package=rprintf}, #' and \url{https://CRAN.R-project.org/package=glue}. #' #' #' @param str charater string to be substituted into #' @param ... force later arguments to bind by name #' @param envir environemnt to look for values #' @param enclos enclosing evaluation environment #' @param match_pattern regexp to find substitution targets. #' @param removal_patterns regexps to remove markers from substitution targets. #' @return modified strings #' #' @seealso \code{\link{strsplit_capture}}, \code{\link{sinterp}} #' #' @examples #' #' x <- 7 #' si("x is .(x), x+1 is .(x+1)\n.(x) is odd is .(x%%2 == 1)") #' #' # Because matching is done by a regular expression we #' # can not use arbitrary depths of nested parenthesis inside #' # the interpolation region. The default regexp allows #' # one level of nesting (and one can use {} in place #' # of parens in many places). #' si("sin(x*(x+1)) is .(sin(x*{x+1}))") #' #' # We can also change the delimiters, #' # in this case to !! through the first whitespace. #' si(c("x is !!x , x+1 is !!x+1 \n!!x is odd is !!x%%2==1"), #' match_pattern = '!![^[:space:]]+[[:space:]]?', #' removal_patterns = c("^!!", "[[:space:]]?$")) #' #' #' @export #' si <- sinterp #' Dot substitution string interpolation. #' #' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called. #' #' See also #' \url{https://CRAN.R-project.org/package=R.utils}, #' \url{https://CRAN.R-project.org/package=rprintf}, #' and \url{https://CRAN.R-project.org/package=glue}. #' #' #' @param str charater string to be substituted into #' @param envir environemnt to look for values #' @return modified strings #' #' @seealso \code{\link{strsplit_capture}}, \code{\link{si}} #' #' @examples #' #' "x is .(x)" %<s% list(x = 7) #' #' #' @export #' `%<s%` <- function(str, envir) { force(envir) sinterp(str, envir = envir, enclos = envir) } #' Dot substitution string interpolation. #' #' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called. #' #' See also #' \url{https://CRAN.R-project.org/package=R.utils}, #' \url{https://CRAN.R-project.org/package=rprintf}, #' and \url{https://CRAN.R-project.org/package=glue}. #' #' #' @param envir environemnt to look for values #' @param str charater string to be substituted into #' @return modified strings #' #' @seealso \code{\link{strsplit_capture}}, \code{\link{si}} #' #' @examples #' #' list(x = 7) %s>% "x is .(x)" #' #' #' @export #' `%s>%` <- function(envir, str) { force(envir) sinterp(str, envir = envir, enclos = envir) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/string_interpolation.R
#' Produce a temp name generator with a given prefix. #' #' Returns a function f where: f() returns a new temporary name, #' f(remove=vector) removes names in vector and returns what was removed, #' f(dumpList=TRUE) returns the list of names generated and clears the list, #' f(peek=TRUE) returns the list without altering anything. #' #' @param prefix character, string to prefix temp names with. #' @param ... force later argument to be bound by name. #' @param alphabet character, characters to choose from in building ids. #' @param size character, number of characters to build id portion of names from. #' @param sep character, separator between temp name fields. #' @return name generator function. #' #' @examples #' #' f <- mk_tmp_name_source('ex') #' print(f()) #' nm2 <- f() #' print(nm2) #' f(remove=nm2) #' print(f(dumpList=TRUE)) #' #' @export mk_tmp_name_source <- function(prefix = "tmpnam", ..., alphabet = as.character(0:9), size = 20, sep = "_") { stop_if_dot_args(substitute(list(...)), "wrapr::mk_tmp_name_source") force(prefix) force(alphabet) force(size) force(sep) if((length(prefix)!=1)||(!is.character(prefix))) { stop("wrapr::mk_tmp_name_source prefix must be a string") } idstr <- paste(base::sample(alphabet, size=size, replace= TRUE), collapse = '') count <- 0 nameList <- list() function(..., peek=FALSE, dumpList=FALSE, remove=NULL) { stop_if_dot_args(substitute(list(...)), "wrapr tmp name source") if(peek) { return(names(nameList)) } if(dumpList) { v <- names(nameList) nameList <<- list() return(v) } if(!is.null(remove)) { victims <- intersect(remove, names(nameList)) # this removes from lists nameList[victims] <<- NULL return(victims) } nm <- paste(prefix, idstr, sprintf('%010d',count), sep = sep) nameList[[nm]] <<- 1 count <<- count + 1 nm } }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/tempNameGenerator.R
#' Strict version of unique (without ...). #' #' Check that \code{...} is empty and if so call #' \code{base::unique(x, incomparables = incomparables, MARGIN = MARGIN, fromLast = fromLast)} #' (else throw an error) #' #' @param x items to be compared. #' @param ... not used, checked to be empty to prevent errors. #' @param incomparables passed to base::unique. #' @param MARGIN passed to base::unique. #' @param fromLast passed to base::unique. #' @return base::unique(x, incomparables = incomparables, MARGIN = MARGIN, fromLast = fromLast) #' #' #' @examples #' #' x = c("a", "b") #' y = c("b", "c") #' #' # task: get unique items in x plus y #' unique(c(x, y)) # correct answer #' unique(x, y) # oops forgot to wrap arguments, quietly get wrong answer #' tryCatch( #' uniques(x, y), # uniques catches the error #' error = function(e) { e }) #' uniques(c(x, y)) # uniques works like base::unique in most case #' #' @export #' uniques <- function(x, ..., incomparables = FALSE, MARGIN = 1, fromLast = FALSE) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::uniques") base::unique(x, incomparables = incomparables, MARGIN = MARGIN, fromLast) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/uniques.R
#' Re-write captured \code{...} arguments as assignments. #' #' Re-write captured \code{...} arguments as a \code{c(DESTINATION = TARGET)} character vector. #' Suggested capture code is: \code{substitute(list(...))}. Allows \code{bquote} \code{.()} substitution. #' #' @param captured_args captured \code{...}. #' @param unpack_environment environment to look in #' @param allow_dot_on_left logical if TRUE allow forms like \code{.(a) = a} and \code{.(a)}. #' @returns named character vector describing the desired mapping. #' #' @examples #' #' f <- function(...) { #' unpack_environment <- parent.frame(n = 1) #' orig_args <- substitute(list(...)) #' grab_assignments_from_dots(orig_args, unpack_environment) #' } #' f(a, c = d, e := f, g <- h, i -> j) #' # should equal c('a', 'c' = 'd', 'e' = 'f', 'g' = 'h', 'j' = 'i') #' #' @keywords internal #' #' @export #' grab_assignments_from_dots <- function(captured_args, unpack_environment = parent.frame(), allow_dot_on_left = FALSE) { force(unpack_environment) if(!allow_dot_on_left) { nms <- names(captured_args) for(i in seqi(2, length(captured_args))) { ai <- captured_args[[i]] if(missing(ai)) { stop("unexpected missing argument, this is often the symptom of an extra comma in your argument list") } # .(a) := a case if(is.call(ai) && (as.character(ai[[1]])[[1]] == ':=')) { if((length(ai) >= 2) && is.call(ai[[2]]) && (as.character(ai[[2]])[[1]] == '.')) { stop("bquote .() notation not allowed on left side of expressions") } } # .(a) case if(is.call(ai) && (as.character(ai[[1]])[[1]] == '.')) { if((i > length(nms)) || (nchar(nms[[i]]) == 0)) { stop("bquote .() notation allowed as whole expression") } } } } captured_dots <- as.list(do.call(bquote, list(captured_args, where = unpack_environment), envir = unpack_environment))[-1] nargs <- length(captured_dots) if(nargs <= 0) { return(character(0)) } names <- names(captured_dots) if(length(names) <= 0) { names <- character(nargs) names[seq_len(nargs)] <- "" } values <- character(nargs) for(i in seq_len(nargs)) { ni <- names[[i]] vi <- captured_dots[[i]] if(is.call(vi)) { if(nchar(ni) > 0) { stop("wrapr::grab_assignments_from_dots call-position can not also have a name") } if(length(vi) != 3) { stop("wrapr::grab_assignments_from_dots call-position must be length 3") } if(!(as.character(vi[[1]]) %in% c('=', '<-', '->', ':=', '%:=%'))) { stop("wrapr::grab_assignments_from_dots call must be one of '=', '<-', '->', ':=', or '%:=%'.") } ni <- vi[[2]] vi <- vi[[3]] } if(length(ni) != 1) { stop("wrapr::grab_assignments_from_dots, names must be length 1") } if(is.name(ni)) { ni <- as.character(ni)[[1]] } if(is.na(ni)) { stop("wrapr::grab_assignments_from_dots, names must not be NA") } if(!is.character(ni)) { stop("wrapr::grab_assignments_from_dots, names must names or character") } if(length(vi) != 1) { stop("wrapr::grab_assignments_from_dots, values must be length 1") } if(is.name(vi)) { vi <- as.character(vi)[[1]] } if(is.na(vi)) { vi <- NA_character_ } if(!is.character(vi)) { stop("wrapr::grab_assignments_from_dots, values must names or character") } if(nchar(vi) < 1) { stop("wrapr::grab_assignments_from_dots, values must not be empty (can happen with if an extra comma is present in call)") } names[[i]] <- ni values[[i]] <- vi } if(all(nchar(names) <= 0)) { names <- NULL } else { non_empty_names <- names[nchar(names)>0] if(length(unique(non_empty_names)) != length(non_empty_names)) { stop("wrapr::grab_assignments_from_dots, target names must be unique") } } names(values) <- names return(values) } validate_positional_targets <- function(target_names, extra_forbidden_names = NULL) { # extract and validate arguments as names of unpack targets nargs <- length(target_names) if(nargs < 1) { stop("no indices to wrapr::unpacker") } if(length(names(target_names)) > 0) { stop("unexpected names") } str_targets <- character(nargs) for(i in 1:nargs) { target_i <- target_names[[i]] char_target_i <- NA_character_ if(is.null(target_i)) { stop("wrapr::unpack expected all targets to not be NULL") } if(!(is.name(target_i) || is.character(target_i) || is.na(target_i))) { stop("wrapr::unpack expected all targets to be character, name, or NA") } char_target_i <- as.character(target_i) if(length(char_target_i) != 1) { stop("wrapr::unpack expected all targets to be length 1.") } if(!is.na(char_target_i)) { if(nchar(char_target_i) < 1) { stop("wrapr::unpack expected all targets to be non-empty strings") } tcargi <- trimws(char_target_i, which = "both") if(tcargi != char_target_i) { stop("wrapr::unpack expected all targets must not start or end with whitespace") } if(char_target_i == ".") { stop("wrapr::unpack expected all targets must not be .") } if(char_target_i %in% extra_forbidden_names) { stop(paste0("wrapr::unpack expected all targets must not be ", char_target_i)) } } str_targets[[i]] <- char_target_i } non_nas <- str_targets[!is.na(str_targets)] if(length(non_nas) <= 0) { stop("wrapr::unpack expected some non-NA targets") } if(length(non_nas) != length(unique(non_nas))) { stop("wrapr::unpack expected all non-NA targets must be unique") } return(str_targets) } validate_source_names <- function(source_names) { # extract and validate arguments as names of unpack sources nargs <- length(source_names) if(nargs < 1) { stop("no indices to wrapr::unpacker") } if(length(names(source_names)) > 0) { stop("unexpected names") } str_names <- character(nargs) for(i in 1:nargs) { source_i <- source_names[[i]] char_source_i <- NA_character_ if(is.null(source_i)) { stop("wrapr::unpack expected all sources to not be NULL") } if(!(is.name(source_i) || is.character(source_i) || is.na(source_i))) { stop("wrapr::unpack expected all sources to be character, name, or NA") } char_source_i <- as.character(source_i) if(length(char_source_i) != 1) { stop("wrapr::unpack expected all sources to be length 1.") } if(is.na(char_source_i)) { stop("wrapr::unpack expected all sources to not be NA.") } if(nchar(char_source_i) < 1) { stop("wrapr::unpack expected all sources to be non-empty strings") } tcargi <- trimws(char_source_i, which = "both") if(tcargi != char_source_i) { stop("wrapr::unpack expected all sources must not start or end with whitespace") } if(char_source_i == ".") { stop("wrapr::unpack expected all sources must not be .") } str_names[[i]] <- char_source_i } return(str_names) } # validate source and target naming validate_assignment_named_map <- function(args, extra_forbidden_names = NULL) { if(length(args) < 1) { stop("no mapping indices to wrapr::unpacker") } target_names <- names(args) source_names <- args names(source_names) <- NULL source_names <- validate_source_names(source_names) if(length(target_names) <= 0) { target_names <- source_names } else { if(length(target_names) != length(source_names)) { stop("expect same number of targets as sources") # should be unreachable, establish a local invarient } for(i in 1:length(source_names)) { if( is.null(target_names[[i]]) || (!is.character(target_names[i])) || is.na(target_names[[i]]) || (length(target_names[[i]]) != 1) || (nchar(target_names[[i]]) <= 0) ) { target_names[[i]] <- source_names[[i]] } } } target_names <- validate_positional_targets(target_names, extra_forbidden_names = extra_forbidden_names) if(any(is.na(target_names))) { # not checked for positional targets stop("all target names must not be NA") } names(source_names) <- target_names return(source_names) } #' write values into environment #' #' @param unpack_environment environment to write into #' @param str_args array of string-names to write to (either without names, or names as targets) #' @param value values to write #' #' @keywords internal #' @noRd #' write_values_into_env <- function(unpack_environment, str_args, value) { force(unpack_environment) nargs <- length(str_args) named_case <- length(names(str_args)) > 0 if(named_case) { unique_sources <- unique(str_args) # names lost here unique_sources <- unique_sources[!is.na(unique_sources)] # up-cycling NULL values case if(is.null(value)) { value <- vector(mode = 'list', length = length(unique_sources)) # list of NULLs names(value) <- unique_sources } missing_items <- c() for(source_i in str_args) { if(!is.na(source_i)) { if(!isTRUE(source_i %in% names(value))) { missing_items <- c(missing_items, source_i) } } } if(length(missing_items) > 0) { stop(paste0("wrapr::unpack all source names must be in value, missing: ", paste(sQuote(missing_items), collapse = ', '), '.')) } # write values for(i in 1:nargs) { dest_i <- names(str_args)[[i]] source_i <- str_args[[i]] value_i <- NA if(!is.na(source_i)) { value_i <-value[[source_i]] } assign(x = dest_i, value = value_i, envir = unpack_environment) } } else { nvalue <- length(value) if(nargs != nvalue) { stop(paste0("wrapr::unpack number of returned values is ", nvalue, ", but expecting ", nargs, " values.")) } # up-cycling NULL values case if(is.null(value)) { value <- vector(mode = 'list', length = nargs) # list of NULLs } # write values for(i in 1:nargs) { dest_i <- str_args[[i]] source_i <- i value_i <- value[[source_i]] if(!is.na(dest_i)) { assign(x = dest_i, value = value_i, envir = unpack_environment) } } } } unpack_impl <- function(..., unpack_environment, value, str_args, object_name = NULL, our_class = "Unpacker") { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr:::unpack_impl") force(unpack_environment) if(!is.null(object_name)) { old_value <- base::mget(object_name, envir = unpack_environment, mode = "any", ifnotfound = list(NULL), inherits = FALSE)[[1]] if(!is.null(old_value)) { if(!(our_class %in% class(old_value))) { stop(paste0("wrapr:::unpack_impl running upacker would overwrite ", object_name, " which is not an Unpacker")) } } old_value <- NULL } str_args <- validate_assignment_named_map(str_args, extra_forbidden_names = object_name) force(value) write_values_into_env(unpack_environment = unpack_environment, str_args = str_args, value = value) } mk_unpack_single_arg_fn <- function(str_args, object_name, our_class, unpack_environment) { force(str_args) force(object_name) force(our_class) force(unpack_environment) str_args <- validate_assignment_named_map(str_args, extra_forbidden_names = object_name) # build function return in a fairly clean environment f <- function(.) { unpack_impl(unpack_environment = unpack_environment, value = ., str_args = str_args, object_name = NULL, # this path doesn't write self our_class = our_class) invisible(.) } attr(f, 'object_name') <- object_name attr(f, 'str_args') <- str_args attr(f, 'unpack_environment') <- unpack_environment class(f) <- our_class return(f) } #' Create a value unpacking object (function version). #' #' Create a value unplacking object that records it is stored by name \code{object_name} (function version). #' #' Array-assign form can not use the names: \code{.}, \code{wrapr_private_self}, \code{value}, or the name stored in \code{object_name}. #' function form can not use the names: \code{.} or \code{wrapr_private_value}. #' Array-form with \code{=}, \code{<-}, \code{->} will write own name into working environment #' as a side-effect. Array-form with \code{:=} does not have the side-effect. #' #' #' @param object_name character, name the object is stored as #' @return an unpacker #' #' @keywords internal #' @export #' UnpackerF <- function(object_name = NULL) { force(object_name) if(!is.null(object_name)) { if(!is.character(object_name)) { stop("wrapr::UnpackerF object_name must be character when not NULL") } if(length(object_name) != 1) { stop("wrapr::UnpackerF object_name must be length 1 when not NULL") } } # build function return f <- function(wrapr_private_value, ...) { # get environment to work in unpack_environment <- parent.frame(n = 1) # get the targets # capture the arguments unevaluted, and run through bquote orig_args <- substitute(list(...)) str_args <- grab_assignments_from_dots(orig_args, unpack_environment) unpack_impl(unpack_environment = unpack_environment, value = wrapr_private_value, str_args = str_args, object_name = NULL, # this path doesn't cause an over-write our_class = "Unpacker") invisible(wrapr_private_value) } attr(f, 'object_name') <- object_name attr(f, 'dotpipe_eager_eval_bracket') <- TRUE attr(f, 'dotpipe_eager_eval_function') <- FALSE class(f) <- "Unpacker" return(f) } #' Create a value unpacking object (eager pipe version). #' #' Create a value unplacking object that records it is stored by name \code{object_name} (eager pipe version). #' #' Array-assign form can not use the names: \code{.}, \code{wrapr_private_self}, \code{value}, or the name stored in \code{object_name}. #' function form can not use the names: \code{.} or \code{wrapr_private_value}. #' Array-form with \code{=}, \code{<-}, \code{->} will write own name into working environment #' as a side-effect. Array-form with \code{:=} does not have the side-effect. #' #' #' @param object_name character, name the object is stored as #' @return an unpacker #' #' @keywords internal #' @export #' UnpackerP <- function(object_name = NULL) { force(object_name) if(!is.null(object_name)) { if(!is.character(object_name)) { stop("wrapr::UnpackerP object_name must be character when not NULL") } if(length(object_name) != 1) { stop("wrapr::UnpackerP object_name must be length 1 when not NULL") } } # build function return f <- function(...) { # get environment to work in unpack_environment <- parent.frame(n = 1) # get the targets # capture the arguments unevaluted, and run through bquote orig_args <- substitute(list(...)) str_args <- grab_assignments_from_dots(orig_args, unpack_environment) bound_f <- mk_unpack_single_arg_fn(str_args = str_args, object_name = object_name, our_class = "UnpackTarget", unpack_environment = unpack_environment) return(bound_f) } attr(f, 'object_name') <- object_name attr(f, 'dotpipe_eager_eval_bracket') <- TRUE attr(f, 'dotpipe_eager_eval_function') <- TRUE class(f) <- "Unpacker" return(f) } #' @export format.Unpacker <- function(x, ...) { object_name <- attr(x, 'object_name') q_name <- "NULL" if(!is.null(object_name)) { q_name <- sQuote(object_name) } dotpipe_eager_eval_function <- isTRUE(attr(x, 'dotpipe_eager_eval_function')) return(paste0("wrapr::Unpacker(object_name = ", q_name, ", dotpipe_eager_eval_function = ", dotpipe_eager_eval_function ,")", "\n # May have been written into your environment as a side-effect of ", "\n # ", object_name, '[...]<-', "\n # For details, please see:", "\n # https://winvector.github.io/wrapr/articles/multi_assign.html")) } #' @export as.character.Unpacker <- function(x, ...) { format(x, ...) } #' @export print.Unpacker <- function(x, ...) { cat(format(x, ...)) } #' Unpack or bind values into the calling environment. #' #' Unpacks or binds values into the calling environment. Uses \code{bquote} escaping. #' NULL is a special case that is unpacked to all targets. NA targets are skipped. #' All non-NA target names must be unique. #' #' Note: when using \code{[]<-} notation, a reference to the unpacker object is written into the unpacking environment as a side-effect #' of the implied array assignment. \code{:=} assigment does not have this side-effect. #' Array-assign form can not use the names: \code{.}, \code{wrapr_private_self}, \code{value}, or the name of the unpacker itself. #' For more details please see here \url{https://win-vector.com/2020/01/20/unpack-your-values-in-r/}. #' #' Related work includes \code{Python} tuple unpacking, \code{zeallot}'s arrow, and \code{vadr::bind}. #' #' @param wrapr_private_self object implementing the feature, wrapr::unpack #' @param ... names of to unpack to (can be escaped with bquote \code{.()} notation). #' @param value list to unpack into values, must have a number of entries equal to number of \code{...} arguments #' @return wrapr_private_self #' #' @examples #' #' # named unpacking #' # looks like assignment: DESTINATION = NAME_VALUE_USING #' d <- data.frame(x = 1:2, #' g=c('test', 'train'), #' stringsAsFactors = FALSE) #' to[train_set = train, test_set = test] := split(d, d$g) #' # train_set and test_set now correctly split #' print(train_set) #' print(test_set) #' rm(list = c('train_set', 'test_set')) #' #' # named unpacking NEWNAME = OLDNAME implicit form #' # values are matched by name, not index #' to[train, test] := split(d, d$g) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' # bquote example #' train_col_name <- 'train' #' test_col_name <- 'test' #' to[train = .(train_col_name), test = .(test_col_name)] := split(d, d$g) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' @export #' `[<-.Unpacker` <- function(wrapr_private_self, ..., value) { force(wrapr_private_self) # get environment to work in unpack_environment <- parent.frame(n = 1) # capture ... args orig_args <- substitute(list(...)) str_args <- grab_assignments_from_dots(orig_args, unpack_environment) # the array update is going to write an object into the # destination environment after returning from this method, # try to ensure it is obvious it is the exact # object that was already there. # arg name not passed this deep, the followign sees "*tmp*" # object_name <- as.character(deparse(substitute(wrapr_private_self)))[[1]] object_name <- attr(wrapr_private_self, 'object_name') unpack_impl(unpack_environment = unpack_environment, value = value, str_args = str_args, object_name = object_name, our_class = "Unpacker") # the return value gets written into executing environment after return # R expects this to be wrapr_private_self, so do that instead of returning old_value return(wrapr_private_self) } #' Prepare for unpack or bind values into the calling environment. #' #' Prepare for unpack or bind values into the calling environment. This makes pipe to behavior very #' close to assign to behavior for the Unpacker class. #' #' @param wrapr_private_self object implementing the feature, wrapr::unpack #' @param ... names of to unpack to (can be escaped with bquote \code{.()} notation). #' @return prepared unpacking object #' #' @export #' `[.Unpacker` <- function(wrapr_private_self, ...) { force(wrapr_private_self) # get environment to work in unpack_environment <- parent.frame(n = 1) # capture .. args orig_args <- substitute(list(...)) str_args <- grab_assignments_from_dots(orig_args, unpack_environment) object_name <- attr(wrapr_private_self, 'object_name') return(mk_unpack_single_arg_fn(str_args = str_args, object_name = object_name, our_class = "UnpackTarget", unpack_environment = unpack_environment)) } #' @export format.UnpackTarget <- function(x, ...) { object_name <- attr(x, 'object_name') str_args <- attr(x, 'str_args') unpack_environment <- attr(x, 'unpack_environment') q_name <- "NULL" if(!is.null(object_name)) { q_name <- sQuote(object_name) } return(paste0("wrapr::UnpackTarget(", "\n\tobject_name = ", q_name, ",\n\tstr_args = ", map_to_char(str_args), ",\n\tunpack_environment = ", format(unpack_environment), ")")) } #' @export as.character.UnpackTarget <- function(x, ...) { format(x, ...) } #' @export print.UnpackTarget <- function(x, ...) { cat(format(x, ...)) } #' Unpack or bind values by names into the calling environment, eager eval (no-dot) variation. #' #' Unpacks or binds values into the calling environment, eager eval (no-dot) variation. Uses \code{bquote} escaping. #' NULL is a special case that is unpacked to all targets. NA targets are skipped. #' All non-NA target names must be unique. #' #' Note: when using \code{[]<-} notation, a reference to the unpacker object is written into the unpacking environment as a side-effect #' of the implied array assignment. \code{:=} assigment does not have this side-effect. #' Array-assign form can not use the names: \code{.}, \code{wrapr_private_self}, \code{value}, or \code{to}. #' function form can not use the names: \code{.} or \code{wrapr_private_value}. #' For more detials please see here \url{https://win-vector.com/2020/01/20/unpack-your-values-in-r/}. #' #' Related work includes \code{Python} tuple unpacking, \code{zeallot}'s arrow, and \code{vadr::bind}. #' #' @param ... argument names to write to #' @return a UnpackTarget #' #' @examples #' #' # named unpacking #' # looks like assignment: DESTINATION = NAME_VALUE_USING #' d <- data.frame(x = 1:2, #' g=c('test', 'train'), #' stringsAsFactors = FALSE) #' to[train_set = train, test_set = test] := split(d, d$g) #' # train_set and test_set now correctly split #' print(train_set) #' print(test_set) #' rm(list = c('train_set', 'test_set')) #' #' # named unpacking NEWNAME = OLDNAME implicit form #' # values are matched by name, not index #' to[train, test] := split(d, d$g) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' # pipe version (notice no dot) #' split(d, d$g) %.>% to(train, test) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' # Note: above is wrapr dot-pipe, piping does not currently work with #' # magrittr pipe due to magrittr's introduction of temporary #' # intermediate environments during evaluation. #' #' # bquote example #' train_col_name <- 'train' #' test_col_name <- 'test' #' to[train = .(train_col_name), test = .(test_col_name)] := split(d, d$g) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' @export #' to <- UnpackerP(object_name = "to") #' Unpack or bind values by names into the calling environment. #' #' Unpacks or binds values into the calling environment. Uses \code{bquote} escaping. #' NULL is a special case that is unpacked to all targets. NA targets are skipped. #' All non-NA target names must be unique. #' #' Note: when using \code{[]<-} notation, a reference to the unpacker object is written into the unpacking environment as a side-effect #' of the implied array assignment. \code{:=} assigment does not have this side-effect. #' Array-assign form can not use the names: \code{.}, \code{wrapr_private_self}, \code{value}, or \code{unpack}. #' Function form can not use the names: \code{.} or \code{wrapr_private_value}. #' For more details please see here \url{https://win-vector.com/2020/01/20/unpack-your-values-in-r/}. #' #' Related work includes \code{Python} tuple unpacking, \code{zeallot}'s arrow, and \code{vadr::bind}. #' #' @param wrapr_private_value list of values to copy #' @param ... argument names to write to #' @return value passed in (invisible) #' #' @seealso \code{\link{pack}} #' #' @examples #' #' # named unpacking #' # looks like assignment: DESTINATION = NAME_VALUE_USING #' d <- data.frame(x = 1:2, #' g=c('test', 'train'), #' stringsAsFactors = FALSE) #' unpack[train_set = train, test_set = test] := split(d, d$g) #' # train_set and test_set now correctly split #' print(train_set) #' print(test_set) #' rm(list = c('train_set', 'test_set')) #' #' # named unpacking NEWNAME = OLDNAME implicit form #' # values are matched by name, not index #' unpack[train, test] := split(d, d$g) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' # function version #' unpack(split(d, d$g), train, test) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' # pipe version #' split(d, d$g) %.>% unpack(., train, test) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' # Note: above is wrapr dot-pipe, piping does not currently work with #' # magrittr pipe due to magrittr's introduction of temporary #' # intermediate environments during evaluation. #' #' # bquote example #' train_col_name <- 'train' #' test_col_name <- 'test' #' unpack(split(d, d$g), train = .(train_col_name), test = .(test_col_name)) #' print(train) #' print(test) #' rm(list = c('train', 'test')) #' #' @export #' unpack <- UnpackerF(object_name = "unpack") #' @export `:=.UnpackTarget` <- function(targets, values) { targets(values) } #' @export `%:=%.UnpackTarget` <- function(targets, values) { targets(values) }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/unpack.R
wrapr_deparse <- function(item) { if(missing(item)) { stop("saw missing argument, often this is caused by an extra comma") } paste(as.character(deparse(item, width.cutoff = 500L)), collapse = "\n ") }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/utils.R
#' @importFrom utils View head NULL #' Invoke a spreadsheet like viewer when appropriate. #' #' @param x R object to view #' @param ... force later arguments to bind by name. #' @param title title for viewer #' @param n number of rows to show #' @return invoke view or format object #' #' @examples #' #' view(mtcars) #' #' @export #' view <- function( x, ..., title = wrapr_deparse(substitute(x)), n = 200) { UseMethod("view", x) } #' @export view.data.frame <- function( x, ..., title = paste(deparse(substitute(x)), collapse = " "), n = 200) { wrapr::stop_if_dot_args(substitute(list(...)), "view.data.frame") if(interactive()) { do.call("View", list(x, title=title), envir = globalenv()) } else { if(requireNamespace("knitr", quietly = TRUE)) { knitr::kable(head(x, n = n), caption = title) } else { print(format(head(x, n = n))) } } } #' @export view.default <- function( x, ..., title = paste(deparse(substitute(x)), collapse = " "), n = 200) { wrapr::stop_if_dot_args(substitute(list(...)), "view.default") if(is.data.frame(x)) { return(view(as.data.frame(x), title = title, n = n)) } cls <- class(x) if((length(cls)==1) && (cls %in% qc(numeric, character, integer, logical))) { d <- data.frame(V1 = 1) d$V1 <- x colnames(d) <- title view(d, title = title, n = n) } else { view(as.data.frame(x), title = title, n = n) } }
/scratch/gouwar.j/cran-all/cranData/wrapr/R/view.R
## ----exdisj------------------------------------------------------------------- library("wrapr") X <- 1 Y <- 2 let( c(), debugPrint = TRUE, X + Y ) let( c(), debugPrint = TRUE, subsMethod = 'langsubs', X + Y ) let( c(), debugPrint = TRUE, subsMethod = 'stringsubs', X + Y ) let( c(), debugPrint = TRUE, subsMethod = 'subsubs', X + Y ) ## ----exswap------------------------------------------------------------------- library("wrapr") X <- 1 Y <- 2 let( c(X='Y', Y='X'), debugPrint = TRUE, X + Y ) let( c(X='Y', Y='X'), debugPrint = TRUE, subsMethod = 'langsubs', X + Y ) let( c(X='Y', Y='X'), debugPrint = TRUE, subsMethod = 'stringsubs', X + Y ) let( c(X='Y', Y='X'), debugPrint = TRUE, subsMethod = 'subsubs', X + Y )
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/CornerCases.R
--- title: "Corner Cases" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Corner Cases} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- `wrapr::let()` is designed to get several important corner cases correct: including substitutions that are disjoint from the expression and symbol swaps. ```{r exdisj} library("wrapr") X <- 1 Y <- 2 let( c(), debugPrint = TRUE, X + Y ) let( c(), debugPrint = TRUE, subsMethod = 'langsubs', X + Y ) let( c(), debugPrint = TRUE, subsMethod = 'stringsubs', X + Y ) let( c(), debugPrint = TRUE, subsMethod = 'subsubs', X + Y ) ``` ```{r exswap} library("wrapr") X <- 1 Y <- 2 let( c(X='Y', Y='X'), debugPrint = TRUE, X + Y ) let( c(X='Y', Y='X'), debugPrint = TRUE, subsMethod = 'langsubs', X + Y ) let( c(X='Y', Y='X'), debugPrint = TRUE, subsMethod = 'stringsubs', X + Y ) let( c(X='Y', Y='X'), debugPrint = TRUE, subsMethod = 'subsubs', X + Y ) ```
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/CornerCases.Rmd
## ----setup-------------------------------------------------------------------- # load package library("wrapr") # user function f <- function(i) { (1:10)[[i]] } ## ----unwrapped---------------------------------------------------------------- inputs = c(4,5,2,9,0,8) tryCatch( for(x in inputs) { f(x) }, error = function(e) { print(e) }) ## ----writeBackVersion2-------------------------------------------------------- # wrap function with writeBack df <- DebugFnW(as.name('lastError'), f) ## ----writeBackVersion3-------------------------------------------------------- # capture error (Note: tryCatch not needed for user code!) tryCatch( for(x in inputs) { df(x) }, error = function(e) { print(e) }) ## ----writeBackVersion4-------------------------------------------------------- # examine error str(lastError) lastError$args ## ----writeBackVersion5-------------------------------------------------------- # redo call, perhaps debugging tryCatch( do.call(lastError$fn_name, lastError$args), error = function(e) { print(e) }) # clean up rm(list='lastError') ## ----FileVersion, eval=FALSE-------------------------------------------------- # saveDest <- paste0(tempfile('debug'),'.RDS') # # wrap function with saveDeest # df <- DebugFnW(saveDest,f) # # capture error (Note: tryCatch not needed for user code!) # tryCatch( # for(x in inputs) { # df(x) # }, # error = function(e) { print(e) }) ## ----FileVersion2, eval=FALSE------------------------------------------------- # # load data # lastError <- readRDS(saveDest) # # examine error # str(lastError) # # redo call, perhaps debugging # tryCatch( # do.call(lastError$fn_name, lastError$args), # error = function(e) { print(e) }) # # clean up # file.remove(saveDest)
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/DebugFnW.R
--- title: "Debug Vignette" author: "John Mount, Nina Zumel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Debug Vignette} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- This vignette demonstrates debugging a user-created function with the `DebugFnW` call. For our example, we will use a simple function that takes an argument `i` and returns the `i`th index of a ten-element vector: ```{r setup} # load package library("wrapr") # user function f <- function(i) { (1:10)[[i]] } ``` Let's imagine that we are calling this function deep within another process; perhaps we are calling it repeatedly, on a long sequence of (possibly unknown to us) inputs. ```{r unwrapped} inputs = c(4,5,2,9,0,8) tryCatch( for(x in inputs) { f(x) }, error = function(e) { print(e) }) ``` Oops! We've crashed, and if this loop were deep in another process, we wouldn't know why, or where. If we suspect that the function `f` is the cause, then we can wrap `f` using `wrapr:DebugFn`. `DebugFnW(saveDest, fn)` wraps its function argument `fn`, captures any arguments that cause it to fail, and saved those arguments and other state to a specified destination `saveDest`. The state data is written to: * a random temp file (if `saveDest` is null) * a user chosen file (if `saveDest` is character) * a `globalenv()` variable (if `saveDest` is a name, as produced by `as.name()` or `quote()`) * passed to a user function (if `saveDest` is a function). Here, we wrap `f` and save error state into the global variable `lastError`. ```{r writeBackVersion2} # wrap function with writeBack df <- DebugFnW(as.name('lastError'), f) ``` Now we run the same loop as above, with the wrapped function `df` (note that the `tryCatch` is not strictly needed, this is just for running this example in a vignette). ```{r writeBackVersion3} # capture error (Note: tryCatch not needed for user code!) tryCatch( for(x in inputs) { df(x) }, error = function(e) { print(e) }) ``` We can then examine the error. Note in particular that `lastError$fn_name` records the name of the function that crashed, and `lastError$args` records the arguments that the function was called with. Also in these examples we are wrapping our code with a `tryCatch` block to capture exceptions; this is only to allow the `knitr` sheet to continue and *not* needed to use the debugging wrappers effectively. ```{r writeBackVersion4} # examine error str(lastError) lastError$args ``` In many situations, just knowing the arguments is enough information ("Oops, we tried to index the vector from zero!"). In more complicated cases, we can set a debug point on the offending function, and then call it again with the failing arguments in order to track down the bug. ```{r writeBackVersion5} # redo call, perhaps debugging tryCatch( do.call(lastError$fn_name, lastError$args), error = function(e) { print(e) }) # clean up rm(list='lastError') ``` In many cases you may prefer to save the failing state into an external file rather than into the current runtime environment. Below we show example code for saving state to an RDS file. ```{r FileVersion, eval=FALSE} saveDest <- paste0(tempfile('debug'),'.RDS') # wrap function with saveDeest df <- DebugFnW(saveDest,f) # capture error (Note: tryCatch not needed for user code!) tryCatch( for(x in inputs) { df(x) }, error = function(e) { print(e) }) ``` We can later read that file back into R, for debugging. ```{r FileVersion2, eval=FALSE} # load data lastError <- readRDS(saveDest) # examine error str(lastError) # redo call, perhaps debugging tryCatch( do.call(lastError$fn_name, lastError$args), error = function(e) { print(e) }) # clean up file.remove(saveDest) ``` For more practice, please view [our video on wrapper debugging](https://youtu.be/zFEC9-1XSN8?list=PLAKBwakacHbQT51nPHex1on3YNCCmggZA). Note: `wrapr` debug functionality rehashes some of the capabilities of `dump.frames` (see `help(dump.frames)`). Roughly `dump.frames` catches the exception (so trying to step or continue re-throws, and arguments may have moved from their starting values) and `wrapr` catches the call causing the exception in a state *prior* to starting the calculation (so arguments should be at their starting values). We have found some cases where `wrapr` is a bit more convenient in how it interacts with the `RStudio` visual debugger (please see this [screencast](https://youtu.be/2NCj4Hacm8E?list=PLAKBwakacHbQT51nPHex1on3YNCCmggZA) for some comparison). Also, please see [this article](https://win-vector.com/2012/10/09/error-handling-in-r/) for use of <code>tryCatch</code> and <code>withRestarts</code>.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/DebugFnW.Rmd
## ----------------------------------------------------------------------------- d <- data.frame( names = c("a", "b", "c", "d"), x = c(1, 2, 3, 4 ), y = c(1, 4, 9, 16 ), stringsAsFactors = FALSE) print(d) ## ----------------------------------------------------------------------------- str(d) ## ----------------------------------------------------------------------------- library("wrapr") ## ---- comment=''-------------------------------------------------------------- cat(draw_frame(d)) ## ----------------------------------------------------------------------------- d2 <- build_frame( "names", "x", "y" | "a" , 1 , 1 | "b" , 2 , 4 | "c" , 3 , 9 | "d" , 4 , 16 ) print(d2) ## ----------------------------------------------------------------------------- build_frame( "names", "x", "y" | "a" , 1 , 1 , "b" , 2 , 4 , "c" , 3 , 9 , "d" , 4 , 16 ) ## ---- comment=""-------------------------------------------------------------- cat(dump("d", "")) ## ---- comment=""-------------------------------------------------------------- cat(draw_frame(build_frame( "names", "x", "y" | "a", 1, 1, "b", 2, 4, "c", 3, 9, "d", 4, 16))) ## ----------------------------------------------------------------------------- qchar_frame( col_1, col_2, col_3 | a , b , c | d , e , "f g" ) ## ----------------------------------------------------------------------------- build_frame( "names", "x" , "y" | "a" , 1 , 1 | "b" , cos(2) , 4 | "c" , (3+2) , 9 | "d" , 4 , 16 )
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/FrameTools.R
--- title: "Frame Tools" author: "John Mount, Win-Vector LLC" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Frame Tools} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- [`wrapr`](https://winvector.github.io/wrapr/) supplies a few tools for creating example `data.frame`s. An important use case is: building the control table for `cdata::rowrecs_to_blocks()` and `cdata::blocks_to_rowrecs()` (example [here](https://winvector.github.io/cdata/articles/cdata.html)). Lets see how to create an example data frame. The idea is similar to that found in [`tibble::tribble()`](https://tibble.tidyverse.org/reference/tribble.html): for small tables a row oriented constructor can be quite legible, and avoids the cognitive load of taking a transpose. For example we can create a typical `data.frame` as follows: ```{r} d <- data.frame( names = c("a", "b", "c", "d"), x = c(1, 2, 3, 4 ), y = c(1, 4, 9, 16 ), stringsAsFactors = FALSE) print(d) ``` Notice how the table is specified by columns (which is close to how `data.frame`s are implemented), but printed by rows. `utils::str()` and `tibble::glimpse()` both print by columns. ```{r} str(d) ``` `wrapr` supplies the method [`draw_frame`](https://winvector.github.io/wrapr/articles/FrameTools.html) which at first glance appears to be a mere pretty-printer: ```{r} library("wrapr") ``` ```{r, comment=''} cat(draw_frame(d)) ``` However, the above rendering is actually executable `R` code. If we run it, we re-create the original `data.frame()`. ```{r} d2 <- build_frame( "names", "x", "y" | "a" , 1 , 1 | "b" , 2 , 4 | "c" , 3 , 9 | "d" , 4 , 16 ) print(d2) ``` The merit is: the above input is how it looks when printed. The technique is intended for typing small examples (or [`cdata`](https://github.com/WinVector/cdata) control tables) and only builds `data.frame`s with atomic types (characters, numerics, and logicals; no times, factors or list columns). The specification rule is the first appearance of an infix 2-argument function call (in this case the infix "or symbol" "<code>|</code>") is taken to mean the earlier arguments are part of the header or column names and later arguments are values. The other appearances of "<code>/</code>" are ignored. This means we could also write the frame as follows: ```{r} build_frame( "names", "x", "y" | "a" , 1 , 1 , "b" , 2 , 4 , "c" , 3 , 9 , "d" , 4 , 16 ) ``` This is more limited than `base::dump()`, but also more legible. ```{r, comment=""} cat(dump("d", "")) ``` One can use the combination of `build_frame()` and `draw_frame()` to neaten up by-hand examples for later use (via copy and paste): ```{r, comment=""} cat(draw_frame(build_frame( "names", "x", "y" | "a", 1, 1, "b", 2, 4, "c", 3, 9, "d", 4, 16))) ``` `build_frame()` allows for simple substitutions of values. In contrast the method `qchar_frame()` builds `data.frame`s containing only `character` types and doesn't require quoting (though it does allow it). ```{r} qchar_frame( col_1, col_2, col_3 | a , b , c | d , e , "f g" ) ``` `build_frame()` is intended to capture typed-in examples, and is only compatible with very limited in-place calculation and substitution, and that _must_ be in parenthesis: ```{r} build_frame( "names", "x" , "y" | "a" , 1 , 1 | "b" , cos(2) , 4 | "c" , (3+2) , 9 | "d" , 4 , 16 ) ``` Expressions not in parenthesis (such as "<code>3 + 2</code>") will confuse the language transform `build_frame()` uses to detect cell boundaries.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/FrameTools.Rmd
## ----------------------------------------------------------------------------- #' Increment x by inc. #' #' @param x item to add to #' @param ... not used for values, forces later arguments to bind by name #' @param inc (optional) value to add #' @return x+inc #' #' @examples #' #' f(7) # returns 8 #' f <- function(x, ..., inc = 1) { wrapr::stop_if_dot_args(substitute(list(...)), "f") x + inc } f(7) f(7, inc = 2) tryCatch( f(7, q = mtcars), error = function(e) { print(e) }) tryCatch( f(7, 2), error = function(e) { print(e) })
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/Named_Arguments.R
--- title: "Named Arguments" author: "John Mount, Win-Vector LLC" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Named Arguments} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- R's named function argument binding is a great aid in writing correct programs. It is a good idea, if practical, to force optional arguments to only be usable by name. To do this declare the additional arguments after "<code>...</code>" and enforce that none got lost in the "<code>...</code> trap" by using a checker such as <a href="https://winvector.github.io/wrapr/reference/stop_if_dot_args.html">wrapr::stop_if_dot_args()</a>. Example: ```{r} #' Increment x by inc. #' #' @param x item to add to #' @param ... not used for values, forces later arguments to bind by name #' @param inc (optional) value to add #' @return x+inc #' #' @examples #' #' f(7) # returns 8 #' f <- function(x, ..., inc = 1) { wrapr::stop_if_dot_args(substitute(list(...)), "f") x + inc } f(7) f(7, inc = 2) tryCatch( f(7, q = mtcars), error = function(e) { print(e) }) tryCatch( f(7, 2), error = function(e) { print(e) }) ``` By R function evaluation rules: any unexpected/undeclared arguments are captured by the "<code>...</code>" argument. Then "wrapr::stop_if_dot_args()" inspects for such values and reports an error if there are such. The &quot;f&quot; string is returned as part of the error, I chose the name of the function as in this case. The "substitute(list(...))" part is R's way of making the contents of "..." available for inspection. You can also use the technique on required arguments. <a href="https://winvector.github.io/wrapr/reference/stop_if_dot_args.html">wrapr::stop_if_dot_args()</a> is a simple low-dependency helper function intended to make writing code such as the above easier. This is under the rubric that hidden errors are worse than thrown exceptions. It is best to find and signal problems early, and near the cause. The idea is that you should not expect a user to remember the positions of more than 1 to 3 arguments, the rest should only be referable by name. Do not make your users count along large sequences of arguments, <a href="https://en.wikipedia.org/wiki/Subitizing">the human brain may have special cases for small sequences</a>. <blockquote> If you have a procedure with 10 parameters, you probably missed some. <p/>Alan Perlis, "Epigrams on Programming", ACM SIGPLAN Notices 17 (9), September 1982, pp. 7–13. </blockquote> Note that the "<code>substitute(list(...))</code>" part is the R idiom for capturing the unevaluated contents of "<code>...</code>", I felt it best to use standard R as much a possible in favor of introducing any <em>additional</em> magic invocations.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/Named_Arguments.Rmd
## ----------------------------------------------------------------------------- c("Petal.Width", "Petal.Length") ## ----------------------------------------------------------------------------- library("wrapr") qc(Petal.Width, Petal.Length) ## ----------------------------------------------------------------------------- iris[, qc(Petal.Width, Petal.Length)] %.>% head(.) ## ----------------------------------------------------------------------------- OTHER_SYMBOL <- "Petal.Length" qc(Petal.Width, OTHER_SYMBOL) qc(Petal.Width, .(OTHER_SYMBOL)) ## ----------------------------------------------------------------------------- qc(Petal.Width, c(OTHER_SYMBOL)) ## ----------------------------------------------------------------------------- qc(a = b) ## ----------------------------------------------------------------------------- LEFT_NAME = "a" qc(.(LEFT_NAME) := b)
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/QuotingConcatinate.R
--- title: "Quoting Concatinate" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Quoting Concatinate} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- In [`R`](https://www.r-project.org) data analysis code-capturing interfaces (or non-standard-evaluation/NSE interfaces are considered a fun convenience. These allow users to type column names in directly when working. However in functions and packages there can be a large interface price or code safety risk to pay for supplying the user the minor convenience of eliding a few quotation marks. Our package [`wrapr`](https://CRAN.R-project.org/package=wrapr) has the sensible design principle: NSE can be convenient to the user, but we are going to isolate it to a few methods (for safe and simple code). Users then pass the objects that those methods create as *values* to other methods. Computation is meant to be over values, so this is a good trade-off. The primary place code capturing shows up in our `wrapr` `R` package is in the [`qc()`](https://winvector.github.io/wrapr/reference/qc.html) and [`qchar_frame()`](https://winvector.github.io/wrapr/reference/qchar_frame.html) methods. `qc()` stands for "quoting concatenate" it is much like `R`'s `c()` (combine), but it quotes its arguments before concatenating vectors or lists. It lets you replace this: ```{r} c("Petal.Width", "Petal.Length") ``` with this: ```{r} library("wrapr") qc(Petal.Width, Petal.Length) ``` This, in turn, lets you replace this: ``` library("dplyr") iris %>% select(., Petal.Width, Petal.Length) %>% head(.) ``` with this: ```{r} iris[, qc(Petal.Width, Petal.Length)] %.>% head(.) ``` We still skipped the quotes, and the NSE stuff is safely isolated from the rest of the system. `wrapr` now incorporates `bquote()` based quasiquotation in a few of its interfaces. Quasiquotation was introduced into R by Thomas Lumley in 2003, and allows users to signal they want to turn off quotation for portions of their code. The user indicates they do not wish a portion of their code to be quoted (but instead want it evaluated for its value) by surrounding that portion with the function-notation "`.()`". An example of this is given here. ```{r} OTHER_SYMBOL <- "Petal.Length" qc(Petal.Width, OTHER_SYMBOL) qc(Petal.Width, .(OTHER_SYMBOL)) ``` This should be familiar to `data.table` users, as `data.table` has supported related notations for quite some time. Also, `qc()` is designed to have a simple "mutually recursive" relationship with `c()` (i.e. they call each other when they see one another). This means `c()` is also a quasiquotation escape-notation for `qc()`: ```{r} qc(Petal.Width, c(OTHER_SYMBOL)) ``` This escape notation arises as a natural consequence of a design of `qc()` that calls `c()` instead of quoting it (i.e. delegates `c()`-expressions to `c()`). The `bquote()-.()` should be the preferred notation for regularity, and to match any other `bquote()` quasiquotation interface (such as `qchar_frame()` or [even a variation of `dplyr`](https://win-vector.com/2018/10/16/quasiquotation-in-r-via-bquote/)). `qc()` also takes some trouble to work with named vectors: ```{r} qc(a = b) ``` And we can even re-map left-hand sizes of (or names) if we use the alternate "`:=`" assignment notation. ```{r} LEFT_NAME = "a" qc(.(LEFT_NAME) := b) ``` Notice syntactically `qc()` fills a general niche much like the specific function `ggplot2::aes()` fits in the `ggplot2` package. The `qc()` notation is very powerful and clearly indicates where which quoting rules are in effect when. We strongly suggest users look to it for code-capturing and package developers recommend it to their users.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/QuotingConcatinate.Rmd
## ----exlang------------------------------------------------------------------- library("wrapr") let( c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } }, eval = FALSE, subsMethod = 'langsubs') ## ----exstr-------------------------------------------------------------------- let( c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } }, eval = FALSE, subsMethod = 'stringsubs') ## ----exsubs------------------------------------------------------------------- let(c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } }, eval = FALSE, subsMethod = 'subsubs')
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/SubstitutionModes.R
--- title: "Substitution Modes" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Substitution Modes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## The substitution modes `wrapr::let()` now has three substitution implementations: * Language substitution (`subsMethod='langsubs'` the new default). In this mode user code is captured as an abstract syntax tree (or parse tree) and substitution is performed only on nodes known to be symbols or behaving in a symbol-role (`"X"` in `d$"X"` is one such example). * Substitute substitution (`subsMethod='subsubs'`). In this mode substitution is performed by `R`'s own `base::substitute()`. * String substitution (`subsMethod='stringsubs'`, the previous default now deprecated). In this mode user code is captured as text and then string replacement on word-boundaries is used to substitute in variable re-mappings. The semantics of the three methods can be illustrated by showing the effects of substituting the variable name "`y`" for "`X`" and the function "`sin`" for "`F`" in the somewhat complicated block of statements: ```r { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } } ``` This block a lot of different examples and corner-cases. #### Language substitution (`subsMethod='langsubs'`) ```{r exlang} library("wrapr") let( c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } }, eval = FALSE, subsMethod = 'langsubs') ``` Notice the substitution replaced all symbol-like uses of "`X`", and only these (including correctly working with some that were quoted!). #### String substitution (`subsMethod='stringsubs'`) ```{r exstr} let( c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } }, eval = FALSE, subsMethod = 'stringsubs') ``` Notice string substitution has a few flaws: it went after variable names that appeared to start with a word-boundary (the cases where the variable name started with a dot or a space). Substitution also occurred in some string constants (which as we have seen could be considered a good thing). These situations are all avoidable as both the code inside the `let`-block and the substitution targets are chosen by the programmer, so they can be chosen to be simple and mutually consistent. We suggest "`ALL_CAPS`" style substitution targets as they jump out as being macro targets. But, of course, it is better to have stricter control on substitution. Think of the language substitution implementation as a lower-bound on a perfect implementation (cautious, with a few corner cases to get coverage) and string substitution as an upper bound on a perfect implementation (aggressive, with a few over-reaches). #### Substitute substitution (`subsMethod='subsubs'`) ```{r exsubs} let(c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, F(1:2)) X$a "X"$a X = function(X, ...) { X + 1 } }, eval = FALSE, subsMethod = 'subsubs') ``` Notice `base::substitute()` doesn't re-write left-hand-sides of argument bindings. This is why I originally didn't consider using this implementation. Re-writing left-hand-sides of assignments is critical in expressions such as `dplyr::mutate( RESULTCOL = INPUTCOL + 1)`. Also `base::substitute()` doesn't special case the `d$"X"` situation (but that really isn't very important). ## Conclusion `wrapr::let()` when used prudently is a safe and powerful tool.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/SubstitutionModes.Rmd
## ----------------------------------------------------------------------------- library("wrapr") variable <- "angle" sinterp( 'variable name is .(variable)' ) ## ----------------------------------------------------------------------------- angle = 1:10 variable_name <- as.name("angle") if(requireNamespace("graphics", quietly = TRUE)) { evalb( plot(x = .(-variable_name), y = sin(.(-variable_name))) ) } ## ----------------------------------------------------------------------------- angle = 1:10 variable_string <- "angle" if(requireNamespace("graphics", quietly = TRUE)) { evalb( plot(x = .(-variable_string), y = sin(.(-variable_string))) ) } ## ----------------------------------------------------------------------------- plotb <- bquote_function(graphics::plot) if(requireNamespace("graphics", quietly = TRUE)) { plotb(x = .(-variable), y = sin(.(-variable))) } ## ----------------------------------------------------------------------------- f <- function() { sin } # pipe 5 to the value of f() # the .() says to evaluate f() before the # piping 5 %.>% .(f()) # evaluate "f()"" with . = 5 # not interesting as "f()"" is "dot free" 5 %.>% f() ## ----------------------------------------------------------------------------- attr(f, 'dotpipe_eager_eval_function') <- TRUE # now evalutates pipe on f() result. 5 %.>% f()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/bquote.R
--- title: "bquote" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{bquote} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- It would be nice if [<code>R</code>](https://www.r-project.org) [string-interpolation](https://en.wikipedia.org/wiki/String_interpolation) and [quasi-quotation](https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming) both used the same notation. They are related concepts. So some commonality of notation would actually be clarifying, and help teach the concepts. We will define both of the above terms, and demonstrate the relation between the two concepts. ## String-interpolation [String-interpolation](https://en.wikipedia.org/wiki/String_interpolation) is the name for substituting value into a string. For example: ```{r} library("wrapr") variable <- "angle" sinterp( 'variable name is .(variable)' ) ``` Notice the "<code>.(variable)</code>" portion was replaced with the actual variable name "<code>angle</code>". For string interpolation we are intentionally using the "<code>.()</code>" notation that Thomas Lumley’s picked in 2003 when he introduced quasi-quotation into <code>R</code> (a different concept than string-interpolation, but the topic of our next section). String interpolation is a common need, and there are many [<code>R</code>](https://www.r-project.org) packages that supply variations of such functionality: * <code>base::sprintf</code> * [<code>R.utils::gstring()</code>](https://CRAN.R-project.org/package=R.utils) * [<code>rprintf::rprintf()</code>](https://CRAN.R-project.org/package=rprintf) * [<code>stringr::str_interp()</code>](https://CRAN.R-project.org/package=stringr) * [<code>glue::glue()</code>](https://CRAN.R-project.org/package=glue) * [<code>wrapr::sinterp()</code>](https://winvector.github.io/wrapr/reference/sinterp.html). ## Quasi-quotation A related idea is ["quasi-quotation"](https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming) which substitutes a value into a general expression. For example: ```{r} angle = 1:10 variable_name <- as.name("angle") if(requireNamespace("graphics", quietly = TRUE)) { evalb( plot(x = .(-variable_name), y = sin(.(-variable_name))) ) } ``` Notice how in the above plot the actual variable name "<code>angle</code>" was substituted into the <code>graphics::plot()</code> arguments, allowing this name to appear on the axis labels. We can also use strings in place of names by using the `.(-)` "strip quotes to convert strings to name notation." ```{r} angle = 1:10 variable_string <- "angle" if(requireNamespace("graphics", quietly = TRUE)) { evalb( plot(x = .(-variable_string), y = sin(.(-variable_string))) ) } ``` <code>evalb()</code> is a very simple function built on top of <code>base::bquote()</code>. All <code>evalb()</code> does is: call <code>bquote()</code> as intended, with the extension that `.(-x)` is shorthand for `.(as.name(x))`. And we see the un-executed code with the substitutions performed. There are many <code>R</code> quasi-quotation systems including: * <code>base::bquote()</code> * [<code>gtools::strmacro()</code>](https://CRAN.R-project.org/package=gtools) * [<code>lazyeval</code>](https://CRAN.R-project.org/package=lazyeval) * [<code>wrapr::let()</code>](https://winvector.github.io/wrapr/reference/let.html) * <code>rlang::as_quosure()</code> * [<code>nseval</code>](https://CRAN.R-project.org/package=nseval) If you don't want to wrap your <code>plot()</code> call in <code>evalb()</code> you can instead pre-adapt the function. Below we create a new function <code>plotb()</code> that is intended as shorthand for <code>eval(bquote(plot(...)))</code>. ```{r} plotb <- bquote_function(graphics::plot) if(requireNamespace("graphics", quietly = TRUE)) { plotb(x = .(-variable), y = sin(.(-variable))) } ``` The `wrapr` [dot arrow pipe](https://winvector.github.io/wrapr/reference/dot_arrow.html) also uses the `bquote`-style escape to specify "extra execution". For example. ```{r} f <- function() { sin } # pipe 5 to the value of f() # the .() says to evaluate f() before the # piping 5 %.>% .(f()) # evaluate "f()"" with . = 5 # not interesting as "f()"" is "dot free" 5 %.>% f() ``` We can annotate any function as "eager eval" as follows. ```{r} attr(f, 'dotpipe_eager_eval_function') <- TRUE # now evalutates pipe on f() result. 5 %.>% f() ``` ## Conclusion When string-interpolation and quasi-quotation use the same notation we can teach them quickly as simple related concepts.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/bquote.Rmd
## ----pipe1s------------------------------------------------------------------- library("wrapr") cos(exp(sin(4))) 4 %.>% sin(.) %.>% exp(.) %.>% cos(.) ## ----pipe1-------------------------------------------------------------------- 1:4 %.>% .^2 ## ----pipe2-------------------------------------------------------------------- 5 %.>% sin(.) 5 %.>% base::sin(.) ## ----peager------------------------------------------------------------------- f <- function() { sin } # returns f() ignoring dot, not what we want 5 %.>% f() # evaluates f() early then evaluates result with .-substitution rules 5 %.>% .(f())
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/dot_pipe.R
--- title: "Dot Pipe" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Dot Pipe} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- [`%.>%` dot arrow pipe](https://winvector.github.io/wrapr/reference/dot_arrow.html) is a strict pipe with intended semantics: > "`a %.>% b`" is to be treated > as if the user had written "`{ . <- a; b };`" > with "`%.>%`" being treated as left-associative. That is: `%.>%` does not alter any function arguments that are not explicitly named. `%.>%` is designed to be explicit and simple. The following two expressions should be equivalent: ```{r pipe1s} library("wrapr") cos(exp(sin(4))) 4 %.>% sin(.) %.>% exp(.) %.>% cos(.) ``` The notation is quite powerful as it treats pipe stages as expression parameterized over the variable "`.`". This means you do not need to introduce functions to express stages. The following is a valid dot-pipe: ```{r pipe1} 1:4 %.>% .^2 ``` The notation is also very regular in that many variations of expression work as expected. Example: ```{r pipe2} 5 %.>% sin(.) 5 %.>% base::sin(.) ``` Regularity can be a *big* advantage in teaching and comprehension. Please see ["In Praise of Syntactic Sugar"](https://win-vector.com/2017/07/07/in-praise-of-syntactic-sugar/) for discussion. The dot arrow pipe has S3/S4 dispatch (please see ["Dot-Pipe: an S3 Extensible Pipe for R"](https://journal.r-project.org/archive/2018/RJ-2018-042/index.html)). However as the right-hand side of the pipe is normally held unevaluated, we don't know the type except in special cases (such as the rigth-hand side being referred to by a name or variable). To force the evaluation of a pipe term, simply wrap it in .(). A detail of R-style pipes is the right argument is held unevalauted (unless it is a name), so we can't always use the class of the right hand side to dispatch. To work around this we suggest using `.()` notation, which in the context of the pipe means "evaluate early." An example is given below: ```{r peager} f <- function() { sin } # returns f() ignoring dot, not what we want 5 %.>% f() # evaluates f() early then evaluates result with .-substitution rules 5 %.>% .(f()) ```
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/dot_pipe.Rmd
## ----wrapri------------------------------------------------------------------- library("wrapr") wrapr::defineLambda(name = "l") ls() ## ----fsq1--------------------------------------------------------------------- l(x, x^2) ## ----fsq2--------------------------------------------------------------------- sapply(1:4, l(x, x^2)) ## ----fsqp--------------------------------------------------------------------- 1:4 %.>% { .^2 } ## ----ft----------------------------------------------------------------------- l(x, y, x + 3*y)
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/lambda.R
--- title: "lambda Function Builder" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{lambda Function Builder} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- The [`CRAN`](https://cran.r-project.org) version of the [`R`](https://www.r-project.org) package [`wrapr`](https://CRAN.R-project.org/package=wrapr) package now includes a concise anonymous function constructor: `l()`. To use it please do the following: attach `wrapr` and ask it to place a definition for `l()` in your environment: ```{r wrapri} library("wrapr") wrapr::defineLambda(name = "l") ls() ``` Note: throughout this document we are using the letter "`l`" as a stand-in for the Greek letter lambda, as this non-ASCII character can cause formatting problems in some situations. You can use `l()` to define functions. The syntax is: `l(arg [, arg]*, body [, env=env])`. That is we write a `l()`-call (which you can do by cutting and pasting) and list the desired function arguments and then the function body. For example the function that squares numbers is: ```{r fsq1} l(x, x^2) ``` We can use such a function to square the first four positive integers as follows: ```{r fsq2} sapply(1:4, l(x, x^2)) ``` Dot-pipe style notation does not need the `l()` factory as it treats pipe stages as expressions parameterized over the variable "`.`": ```{r fsqp} 1:4 %.>% { .^2 } ``` And we can also build functions that take more than one argument as follows: ```{r ft} l(x, y, x + 3*y) ```
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/lambda.Rmd
## ----------------------------------------------------------------------------- x = 5 print(5 + 1) print(x + 1) ## ----------------------------------------------------------------------------- set.seed(1234) xvar = runif(100) - 0.5 yvar = dnorm(xvar) plot(xvar, yvar) ## ----------------------------------------------------------------------------- d <- data.frame(x=c(1,NA)) d$x ## ----------------------------------------------------------------------------- library("wrapr") xvariable = "xvar" yvariable = "yvar" let( c(XVARIABLE=xvariable, YVARIABLE=yvariable), { # since we have the names as strings, we can create a title title = paste(yvariable, "vs", xvariable) plot(XVARIABLE, YVARIABLE, main=title) } ) ## ----------------------------------------------------------------------------- a <- 1 b <- 2 let(c(z=quote(a)), z+b) eval(substitute(z+b, c(z=quote(a))))
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/let.R
--- title: "Let" author: "Nina Zumel, John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Let} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- The vignette demonstrates the use of `let` to standardize calls to functions that use non-standard evaluation. For a more formal description please see [here](https://github.com/WinVector/wrapr/blob/master/extras/wrapr_let.pdf). For the purposes of this discussion, *standard evaluation* of variables preserves referential transparency: that is, values and references to values behave the same. ```{r} x = 5 print(5 + 1) print(x + 1) ``` Some functions in R use *non-standard evaluation* (NSE) of variables, in order to snoop variable names (for example, `plot`), or to delay or even avoid argument evaluation (for example `library(foobar)` versus `library("foobar")`). In the case of `plot`, NSE lets `plot` use the variable names as the axis labels. ```{r} set.seed(1234) xvar = runif(100) - 0.5 yvar = dnorm(xvar) plot(xvar, yvar) ``` In the case of `library`, non-standard evaluation saves typing a couple of quotes. The dollar sign notation for accessing data frame columns also uses non standard evaluation. ```{r} d <- data.frame(x=c(1,NA)) d$x ``` Issues arise when you want to use functions that use non-standard evaluation -- for brevity, I'll call these *NSE expressions* -- but you don't know the name of the variable, as might happen when you are calling these expression from within another function. Generally in these situations, you are taking the name of the desired variable from a string. But how do you pass it to the NSE expression? For this discussion, we will demonstrate `let` to standardize calling `plot` with unknown variables. `let` takes two arguments: * A list of assignments *symname=varname*, where *symname* is the name used in the NSE expression, and *varname* is the name (as a string) of the desired variable. * The NSE expression. Enclose a block of multiple expressions in brackets. Here's the `plot` example again. ```{r} library("wrapr") xvariable = "xvar" yvariable = "yvar" let( c(XVARIABLE=xvariable, YVARIABLE=yvariable), { # since we have the names as strings, we can create a title title = paste(yvariable, "vs", xvariable) plot(XVARIABLE, YVARIABLE, main=title) } ) ``` In the above `let()` block we are using the `alias`-convention that we specify substitution target names (in this case `XVARIABLE` and `YVARIABLE`) as upper-case analogues of the substitution name values (in this case `xvariable` and `yvariable`). This convention is very legible and makes it easy to both use value interfaces (as we did in the title `paste()`) and name-capturing interfaces (`plot()` itself). ## Implementation details Roughly `wrapr::let(A, B)` behaves like a syntactic sugar for `eval(substitute(B, A))`. ```{r} a <- 1 b <- 2 let(c(z=quote(a)), z+b) eval(substitute(z+b, c(z=quote(a)))) ``` However, `wrapr::let()` is actually implemented in terms of a de-parse and safe language token substitution. `wrapr::let()` was inspired by `gtools::strmacro()` and `base::bquote()`, please see [here](https://github.com/WinVector/wrapr/blob/master/extras/bquote.md) for some notes on macro methods in `R`. ## More For more discussion please see: * [our video on non-standard evaluation and `let`](https://youtu.be/iKLGxzzm9Hk?list=PLAKBwakacHbQp_Z66asDnjn-0qttTO-o9). * [Standard nonstandard evaluation rules](https://developer.r-project.org/nonstandard-eval.pdf). * [technical article on let](https://github.com/WinVector/wrapr/blob/master/extras/wrapr_let.pdf).
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/let.Rmd
## ----------------------------------------------------------------------------- d <- data.frame( x = 1:9, group = c('train', 'calibrate', 'test'), stringsAsFactors = FALSE) knitr::kable(d) ## ----------------------------------------------------------------------------- parts <- split(d, d$group) train_data <- parts$train calibrate_data <- parts$calibrate test_data <- parts$test ## ----------------------------------------------------------------------------- knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data', 'parts')) ## ----------------------------------------------------------------------------- library(wrapr) to[ train_data <- train, calibrate_data <- calibrate, test_data <- test ] <- split(d, d$group) ## ----------------------------------------------------------------------------- knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data', 'to')) to[ train_data <- train, calibrate_data <- calibrate, test_data <- test ] := split(d, d$group) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ----------------------------------------------------------------------------- split(d, d$group) %.>% to[ train_data <- train, calibrate_data <- calibrate, test_data <- test ] ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ----------------------------------------------------------------------------- split(d, d$group) %.>% to( train_data <- train, calibrate_data <- calibrate, test_data <- test ) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ----------------------------------------------------------------------------- split(d, d$group) %.>% unpack( ., train_data <- train, calibrate_data <- calibrate, test_data <- test ) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ----------------------------------------------------------------------------- unpack( split(d, d$group), train_data <- train, calibrate_data <- calibrate, test_data <- test ) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ----------------------------------------------------------------------------- unpack( split(d, d$group), train_data = train, calibrate_data = calibrate, test_data = test ) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ----------------------------------------------------------------------------- unpack( split(d, d$group), train -> train_data, calibrate -> calibrate_data, test -> test_data ) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'calibrate_data', 'test_data')) ## ---- error=TRUE-------------------------------------------------------------- unpack( split(d, d$group), train_data <- train, calibrate_data <- calibrate_misspelled, test_data <- test ) ## ----------------------------------------------------------------------------- ls() ## ----------------------------------------------------------------------------- unpack( split(d, d$group), train_data <- train, test_data <- test ) ls() ## ----------------------------------------------------------------------------- rm(list = c('train_data', 'test_data')) ## ----------------------------------------------------------------------------- split(d, d$group) %.>% to[ train, test ] ls() ## ----------------------------------------------------------------------------- rm(list = c('train', 'test')) ## ----------------------------------------------------------------------------- train_source <- 'train' split(d, d$group) %.>% to[ train_result = .(train_source), test ] ls()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/multi_assign.R
--- title: "Multiple Assignment" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Multiple Assignment} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- [`wrapr`](https://github.com/WinVector/wrapr) now supplies a name based multiple assignment notation for [`R`](https://www.r-project.org). In `R` there are many functions that return named lists or other structures keyed by names. Let's start with a simple example: `base::split()`. First some example data. ```{r} d <- data.frame( x = 1:9, group = c('train', 'calibrate', 'test'), stringsAsFactors = FALSE) knitr::kable(d) ``` One way to use `base::split()` is to call it on a `data.frame` and then unpack the desired portions from the returned value. ```{r} parts <- split(d, d$group) train_data <- parts$train calibrate_data <- parts$calibrate test_data <- parts$test ``` ```{r} knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ``` If we use a multiple assignment notation we can collect some steps together, and avoid possibly leaving a possibly large temporary variable such as `parts` in our environment. Let's clear out our earlier results. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data', 'parts')) ``` And now let's apply `split()` and unpack the results in one step. ```{r} library(wrapr) to[ train_data <- train, calibrate_data <- calibrate, test_data <- test ] <- split(d, d$group) ``` ```{r} knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ``` The semantics of `[]<-` imply that an object named "`to`" is left in our workspace as a side effect. However, this object is small and if there is already an object name `to` in the workspace that is not of class `Unpacker` the unpacking is aborted prior to overwriting anything. The unpacker two modes: `unpack` (a function that needs a dot in pipes) and `to` (an eager function factory that does not require a dot in pipes). The side-effect can be avoided by using `:=` for assigment. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data', 'to')) to[ train_data <- train, calibrate_data <- calibrate, test_data <- test ] := split(d, d$group) ls() ``` Also the side-effect can be avoided by using alternate non-array update notations. We will demonstrate a few of these. First is pipe to array notation. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r} split(d, d$group) %.>% to[ train_data <- train, calibrate_data <- calibrate, test_data <- test ] ls() ``` Note the above is the [`wrapr` dot arrow pipe](https://journal.r-project.org/archive/2018/RJ-2018-042/index.html) (which requires explicit dots to denote pipe targets). In this case it is dispatching on the class of the right-hand side argument to get the effect. This is a common feature of the wrapr dot arrow pipe. We could get a similar effect by using right-assigment "`->`" instead of the pipe. We can also use a pipe function notation. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r} split(d, d$group) %.>% to( train_data <- train, calibrate_data <- calibrate, test_data <- test ) ls() ``` Notice piping to `to()` is like piping to `to[]`, no dot is needed. We can not currently use the `magrittr` pipe in the above as in that case the unpacked results are lost in a temporary intermediate environment `magrittr` uses during execution. A more conventional functional form is given in `unpack()`. `unpack()` requires a dot in `wrapr` pipelines. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r} split(d, d$group) %.>% unpack( ., train_data <- train, calibrate_data <- calibrate, test_data <- test ) ls() ``` Unpack also support the pipe to array and assign to array notations. In addition, with `unpack()` we could also use the conventional function notation. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r} unpack( split(d, d$group), train_data <- train, calibrate_data <- calibrate, test_data <- test ) ls() ``` `to()` can not be directly used as a function. It is *strongly* suggested that the objects returned by `to[]`, `to()`, and `unpack[]` *not ever* be stored in variables, but instead only produced, used, and discarded. The issue these are objects of class `"UnpackTarget"` and have the upack destination names already bound in. This means if one of these is used in code: a user reading the code can not tell where the side-effects are going without examining the contents of the object. The assignments in the unpacking block can be any of `<-`, `=`, `:=`, or even `->` (though the last one assigns left to right). ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r} unpack( split(d, d$group), train_data = train, calibrate_data = calibrate, test_data = test ) ls() ``` ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r} unpack( split(d, d$group), train -> train_data, calibrate -> calibrate_data, test -> test_data ) ls() ``` It is a caught and signaled error to attempt to unpack an item that is not there. ```{r} rm(list = c('train_data', 'calibrate_data', 'test_data')) ``` ```{r, error=TRUE} unpack( split(d, d$group), train_data <- train, calibrate_data <- calibrate_misspelled, test_data <- test ) ``` ```{r} ls() ``` The unpack attempts to be atomic: preferring to unpack all values or no values. Also, one does not have to unpack all slots. ```{r} unpack( split(d, d$group), train_data <- train, test_data <- test ) ls() ``` We can use a name alone as shorthand for `name <- name` (i.e. unpacking to the same name as in the incoming object). ```{r} rm(list = c('train_data', 'test_data')) ``` ```{r} split(d, d$group) %.>% to[ train, test ] ls() ``` We can also use `bquote` `.()` notation to use variables to specify where data is coming from. ```{r} rm(list = c('train', 'test')) ``` ```{r} train_source <- 'train' split(d, d$group) %.>% to[ train_result = .(train_source), test ] ls() ``` In all cases the user explicitly documents the intended data sources and data destinations at the place of assignment. This meas a later reader of the source code can see what the operation does, without having to know values of additional variables. Related work includes: <ul> <li> The <a href="https://CRAN.R-project.org/package=zeallot"><code>zeallot::%&lt;-%</code></a> arrow already supplies excellent positional or ordered unpacking. But we feel that style may be more appropriate in the Python world where many functions return un-named tuples of results. Python functions tend to have positional tuple return values <em>because</em> the Python language has had positional tuple unpacking as a core language feature for a very long time (thus positional structures have become "Pythonic"). R has not emphasized positional unpacking, so R functions tend to return named lists or named structures. For named lists or named structures it may not be safe to rely on value positions. So I feel it is more "R-like" to use named unpacking.</li> <li> <a href="https://github.com/crowding/vadr/blob/master/R/bind.R"><code>vadr::bind</code></a> supplies named unpacking, but appears to use a "<code>SOURCE = DESTINATION</code>" notation. That is the reverse of a "<code>DESTINATION = SOURCE</code>" which is how both R assignments and argument binding are already written.</li> <li><code>base::attach</code>. <code>base::attach</code> adds items to the search path with names controlled by the object being attached (instead of by the user).</li> <li><code>base::with()</code>. <code>unpack(list(a = 1, b = 2), x &lt;- a, y &lt;- b) </code> works a lot like <code> with(list(a = 1, b = 2), { x &lt;&lt;- a; y &lt;&lt;-b })</code>. </li> <li> <a href="https://CRAN.R-project.org/package=tidytidbits"><code>tidytidbits</code></a> supplies positional unpacking with a <code>%=%</code> notation. </li> <li><a href="https://winvector.github.io/wrapr/articles/let.html"><code>wrapr::let()</code></a>. <code>wrapr::let()</code> re-maps names during code execution using a "<code>TARGET = NEWNAME</code>" target replacement scheme, where <code>TARGET</code> acts as if it had the name stored in <code>NEWNAME</code> for the duration of the let-block. </li> </ul>
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/multi_assign.Rmd
## ----ex1---------------------------------------------------------------------- library("wrapr") 'a' := 5 c('a' := 5, 'b' := 6) c('a', 'b') := c(5, 6) ## ----key1--------------------------------------------------------------------- `:=` <- wrapr::`:=` # in case data.tables "catch calls" definition is active key = 'keycode' key := 'value' ## ----print, eval=FALSE-------------------------------------------------------- # help(`:=`, package = 'wrapr')
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/named_map_builder.R
--- title: "Named Map Builder" author: "John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Named Map Builder} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- "named map builder" is an operator written as "`:=`". Named map builder is a *very* simple bit of code that performs a very simple task: it adds names to vectors or lists (making them work more like maps). Here are some examples: ```{r ex1} library("wrapr") 'a' := 5 c('a' := 5, 'b' := 6) c('a', 'b') := c(5, 6) ``` The left-side argument of the `:=` operator is called "the names", and the right-side argument is called "the values". The `:=` operators returns the values with the names set to names. `:=` is a left-over assignment operator in `R`. It is part of the syntax, but by default not defined. `data.table` has long used `:=` to denote "in-place assignment" as in the following. ``` library("data.table") data.table(x = 1)[, y := x + 1][] # x y # 1: 1 2 ``` `dplyr` later adopted the `:=` notation as this allows for substitution on the left-hand sides of assignments. [`wrapr::qc()`](https://winvector.github.io/wrapr/articles/QuotingConcatinate.html) uses the `:=` for the same purpose. A key use of the named map builder is the following: ```{r key1} `:=` <- wrapr::`:=` # in case data.tables "catch calls" definition is active key = 'keycode' key := 'value' ``` Notice the value inside the variable `key` was used as the array name, this differs from what is easily done with `R`'s native `c(key = 'value')` style notation. ```{r print, eval=FALSE} help(`:=`, package = 'wrapr') ```
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/named_map_builder.Rmd
## ----------------------------------------------------------------------------- library(wrapr) # example data d <- data.frame( x = 1:9, group = c('train', 'calibrate', 'test'), stringsAsFactors = FALSE) knitr::kable(d) # split the d by group (parts <- split(d, d$group)) train_data <- parts$train calibrate_data <- parts$calibrate test_data <- parts$test knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ## ----------------------------------------------------------------------------- # clear out the earlier results rm(list = c('train_data', 'calibrate_data', 'test_data', 'parts')) # split d and unpack the smaller data frames into separate variables unpack(split(d, d$group), train_data = train, test_data = test, calibrate_data = calibrate) knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ## ----------------------------------------------------------------------------- # split d and unpack the smaller data frames into separate variables unpack[traind = train, testd = test, cald = calibrate] := split(d, d$group) knitr::kable(traind) knitr::kable(cald) knitr::kable(testd) ## ----------------------------------------------------------------------------- unpack(split(d, d$group), train, test, calibrate) knitr::kable(train) knitr::kable(calibrate) knitr::kable(test) # try the unpack[] assignment notation rm(list = c('train', 'test', 'calibrate')) unpack[test, train, calibrate] := split(d, d$group) knitr::kable(train) knitr::kable(calibrate) knitr::kable(test) ## ----------------------------------------------------------------------------- rm(list = c('train', 'test', 'calibrate')) unpack(split(d, d$group), train, holdout=test, calibrate) knitr::kable(train) knitr::kable(calibrate) knitr::kable(holdout) ## ----error=TRUE--------------------------------------------------------------- rm(list = c('train', 'holdout', 'calibrate')) unpack(split(d, d$group), train, test) knitr::kable(train) knitr::kable(test) # we didn't unpack the calibrate set calibrate ## ----error=TRUE--------------------------------------------------------------- # the split call will not return an element called "holdout" unpack(split(d, d$group), training = train, testing = holdout) # train was not unpacked either training
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/unpack_multiple_assignment.R
--- title: "Multiple Assignment with unpack" author: "Nina Zumel and John Mount" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Multiple Assignment with unpack} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- In `R` there are many functions that return named lists or other structures keyed by names. Often, you want to unpack the elements of such a list into separate variables, for ease of use. One example is the use of `split()` to partition a larger data frame into a named list of smaller data frames, each corresponding to some grouping. ```{r} library(wrapr) # example data d <- data.frame( x = 1:9, group = c('train', 'calibrate', 'test'), stringsAsFactors = FALSE) knitr::kable(d) # split the d by group (parts <- split(d, d$group)) train_data <- parts$train calibrate_data <- parts$calibrate test_data <- parts$test knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ``` A multiple assignment notation allows us to assign all the smaller data frames to variables in one step, and avoid leaving a possibly large temporary variable such as `parts` in our environment. One such notation is `unpack()`. ## Basic `unpack()` example ```{r} # clear out the earlier results rm(list = c('train_data', 'calibrate_data', 'test_data', 'parts')) # split d and unpack the smaller data frames into separate variables unpack(split(d, d$group), train_data = train, test_data = test, calibrate_data = calibrate) knitr::kable(train_data) knitr::kable(calibrate_data) knitr::kable(test_data) ``` You can also use `unpack` with an assignment notation similar to the notation used with the <a href="https://CRAN.R-project.org/package=zeallot"><code>zeallot::%&lt;-%</code></a> pipe: ```{r} # split d and unpack the smaller data frames into separate variables unpack[traind = train, testd = test, cald = calibrate] := split(d, d$group) knitr::kable(traind) knitr::kable(cald) knitr::kable(testd) ``` ### Reusing the list names as variables If you are willing to assign the elements of the list into variables with the same names, you can just use the names: ```{r} unpack(split(d, d$group), train, test, calibrate) knitr::kable(train) knitr::kable(calibrate) knitr::kable(test) # try the unpack[] assignment notation rm(list = c('train', 'test', 'calibrate')) unpack[test, train, calibrate] := split(d, d$group) knitr::kable(train) knitr::kable(calibrate) knitr::kable(test) ``` Mixed notation is allowed: ```{r} rm(list = c('train', 'test', 'calibrate')) unpack(split(d, d$group), train, holdout=test, calibrate) knitr::kable(train) knitr::kable(calibrate) knitr::kable(holdout) ``` ### Unpacking only parts of a list You can also unpack only a subset of the list's elements: ```{r error=TRUE} rm(list = c('train', 'holdout', 'calibrate')) unpack(split(d, d$group), train, test) knitr::kable(train) knitr::kable(test) # we didn't unpack the calibrate set calibrate ``` ### `unpack` checks for unknown elements If `unpack` is asked to unpack an element it doesn't recognize, it throws an error. In this case, none of the elements are unpacked, as `unpack` is deliberately an atomic operation. ```{r error=TRUE} # the split call will not return an element called "holdout" unpack(split(d, d$group), training = train, testing = holdout) # train was not unpacked either training ``` ## Other multiple assignment packages ### `zeallot` The [`zeallot`](https://CRAN.R-project.org/package=zeallot) package already supplies excellent positional or ordered unpacking. The primary difference between `zeallot`'s <a href="https://CRAN.R-project.org/package=zeallot"><code>%&lt;-%</code></a> pipe and `unpack` is that `%<-%` is a *positional* unpacker: you must unpack the list based on the *order* of the elements in the list. This style may be more appropriate in the Python world where many functions return un-named tuples of results. `unpack` is a *named* unpacker: assignments are based on the *names* of elements in the list, and the assignments can be in any order. We feel this is more appropriate for R, as R has not emphasized positional unpacking; R functions tend to return named lists or named structures. For named lists or named structures it may not be safe to rely on value positions. For unpacking named lists, we recommend `unpack`. For unpacking unnamed lists, use `%<-%`. ### `vadr` <a href="https://github.com/crowding/vadr/blob/master/R/bind.R"><code>vadr::bind</code></a> supplies named unpacking, but appears to use a "<code>SOURCE = DESTINATION</code>" notation. That is the reverse of a "<code>DESTINATION = SOURCE</code>" which is how both R assignments and argument binding are already written. ### `tidytidbits` <a href="https://CRAN.R-project.org/package=tidytidbits"><code>tidytidbits</a> supplies positional unpacking with a <code>%=%</code> notation.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/unpack_multiple_assignment.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----------------------------------------------------------------------------- library(wrapr) ## ----------------------------------------------------------------------------- lst <- list(sin) # without the attribute, the function is returned 4 %.>% lst[[1]] ## ----------------------------------------------------------------------------- # an outer .() signals for eager eval from the pipeline 4 %.>% .(lst[[1]]) ## ----------------------------------------------------------------------------- # with the attribute, the array is always de-referenced # before the pipe execution allowing the function # to be evaluated using the piped-in value. attr(lst, 'dotpipe_eager_eval_bracket') <- TRUE 4 %.>% lst[[1]] ## ----------------------------------------------------------------------------- # without the attribute the result is sin f <- function(...) { sin } 4 %.>% f() ## ----------------------------------------------------------------------------- # an outer .() signals for eager eval from the pipeline 4 %.>% .(f()) ## ----------------------------------------------------------------------------- # with the attribute the result is sin(4) attr(f, 'dotpipe_eager_eval_function') <- TRUE 4 %.>% f()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/wrapr_Eager.R
--- title: "wrapr Eager Evaluation" author: "John Mount, Win-Vector LLC" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{wrapr Eager Evaluation} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` [`wrapr`](https://github.com/WinVector/wrapr) dot arrow piping is designed to emphasize a `a %.>% b` "is nearly" `{. <- a; b}` semantics. In many cases this makes a piped expression of the form `a %.>% b(.)` look very much like `b(a)`. This leads to the observation that "wrapr explicit dot notation" appears to need one more dot than the common "[`magrittr`]( https://CRAN.R-project.org/package=magrittr) dot is a new implicit first argument notation." There are some special rules around things like names. For example `5 %.>% sin` is *not* valued as `sin`, which would be the strict interpretation of `{. <- 5; sin}`. Instead it is expanded to something closer `{. <- 5; sin(.)}`, which intentionally looks very much like `sin(5)`. In more complicated cases the user can signal they wish for an eager evaluation of this style by writing on outer `.()` container. And `wrapr` now also exposes an "eager" annotation such that function evaluations or array indexing operations so-annotated are interpreted as `a %.>% f(...)` is interpreted roughly as `{. <- a; _f <- eval(f(...)); _f(.)}`, where `_f` is a notional temporary variable (not visible or produces as a side-effect). This effect is used in `wrapr`'s "pipe to array" variation of the `unpack` notation (example [here](https://win-vector.com/2020/01/21/using-unpack-to-manage-your-r-environment/)). This eager effect can be gotten by setting the appropriate attribute as we see below. For array notation: ```{r} library(wrapr) ``` ```{r} lst <- list(sin) # without the attribute, the function is returned 4 %.>% lst[[1]] ``` ```{r} # an outer .() signals for eager eval from the pipeline 4 %.>% .(lst[[1]]) ``` ```{r} # with the attribute, the array is always de-referenced # before the pipe execution allowing the function # to be evaluated using the piped-in value. attr(lst, 'dotpipe_eager_eval_bracket') <- TRUE 4 %.>% lst[[1]] ``` For functions: ```{r} # without the attribute the result is sin f <- function(...) { sin } 4 %.>% f() ``` ```{r} # an outer .() signals for eager eval from the pipeline 4 %.>% .(f()) ``` ```{r} # with the attribute the result is sin(4) attr(f, 'dotpipe_eager_eval_function') <- TRUE 4 %.>% f() ``` Essentially objects with this attribute have an implicit `.()` "eager eval" on them.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/wrapr_Eager.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----use1--------------------------------------------------------------------- library("wrapr") 5 %.>% sin(.) ## ----nofn--------------------------------------------------------------------- 5 %.>% sin 5 %.>% base::sin ## ----sinfn-------------------------------------------------------------------- function_reference <- list(f = sin) class(function_reference) <- c("wrapr_applicable", "ourclass") apply_right.ourclass <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { pipe_right_arg$f(pipe_left_arg) } function_reference 5 %.>% function_reference function_reference$f <- sqrt 5 %.>% function_reference ## ----debug-------------------------------------------------------------------- apply_right.ourclass <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { print("pipe_left_arg") print(pipe_left_arg) print("pipe_right_arg") print(pipe_right_arg) print("pipe_environment") print(pipe_environment) print("left_arg_name") print(left_arg_name) print("pipe_string") print(pipe_string) print("right_arg_name") print(right_arg_name) pipe_right_arg$f(pipe_left_arg) } 5 %.>% function_reference a <- 5 a %.>% function_reference
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/wrapr_applicable.R
--- title: "wrapr_applicable" author: "John Mount, Win-Vector LLC" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{wrapr_applicable} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` `wrapr` includes de-referencing, function evaluation, and a new concept called `"wrapr_applicable"`. `"wrapr_applicable"` is dispatch by type of right hand side argument scheme. ## Basic `wrapr` The `wrapr` pipe operators (`%.>%` and `%>.%`) are roughly defined as: `a %>.% b ~ { . <- a; b };`. This works under the assumption that `b` is an expression with free-instances of "`.`". A typical use is: ```{r use1} library("wrapr") 5 %.>% sin(.) ``` The above is performed by standard `S3` dispatch on the left argument of an exported generic functions called `apply_left()` and `apply_right()`. A formal description of `wrapr` piping can be found [here](https://github.com/WinVector/wrapr/blob/master/extras/wrapr_pipe.pdf). ## Dereferencing and function evaluation `wrapr` works primarily over expressions and "`.`". `wrapr` does tries to de-reference names found in the right-hand side of pipe stages, and also dispatches functions. One can also write the following. ```{r nofn} 5 %.>% sin 5 %.>% base::sin ``` ## `"wrapr_applicable"` Arbitrary objects ask `wrapr` to treat them as special expressions by overriding one or more of `apply_left()` and `apply_right()` for the `S3` class they wish managed. For example: ```{r sinfn} function_reference <- list(f = sin) class(function_reference) <- c("wrapr_applicable", "ourclass") apply_right.ourclass <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { pipe_right_arg$f(pipe_left_arg) } function_reference 5 %.>% function_reference function_reference$f <- sqrt 5 %.>% function_reference ``` The signature arguments work as follows: * `pipe_left_arg`: The value moving down the pipeline. * `pipe_right_arg`: The right pipeline operator (essentially "`self`" or "`this`" in object oriented terms, used for `S3` dispatch). * `pipe_environment`: The environment the pipeline is working in (not usually needed). * `left_arg_name`: If the left arguement was passed in by name, what that name was. * `pipe_string`: The name of the pipe operator (not usually needed). * `right_arg_name`: If the right arguement was passed in by name, what that name was. This functionality allows arbitrary objects to directly specify their intended pipeline behavior. Let's use a debugging function to see the values of all of the arguments. ```{r debug} apply_right.ourclass <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { print("pipe_left_arg") print(pipe_left_arg) print("pipe_right_arg") print(pipe_right_arg) print("pipe_environment") print(pipe_environment) print("left_arg_name") print(left_arg_name) print("pipe_string") print(pipe_string) print("right_arg_name") print(right_arg_name) pipe_right_arg$f(pipe_left_arg) } 5 %.>% function_reference a <- 5 a %.>% function_reference ``` ## Conclusion `wrapr` values (left-hand sides of pipe expressions) are completely general. `wrapr` operators (right-hand sides of pipe expressions) are primarily intended to be expressions that have "`.`" as a free-reference. `wrapr` can also be used with right-hand sides that are function references or with arbitrary annotated objects.
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/doc/wrapr_applicable.Rmd
test_as_named_list <- function() { a <- data.frame(x = 1) b <- 2 l0 <- as_named_list(a) expect0 <- list(a = a) expect_equal(l0, expect0) l1 <- as_named_list(a, b) expect1 <- list(a = a, b = b) expect_equal(l1, expect1) l2 <- as_named_list(a, x = b, c = 1 + 1, d = NULL) expect2 <- list(a = a, x = b, c = 2, d = NULL) expect_equal(l2, expect2) expect_error(as_named_list(a, a)) expect_error(as_named_list(NULL)) expect_error(as_named_list(a, NULL)) expect_error(as_named_list(7)) invisible(NULL) } test_as_named_list()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_as_named_list.R
expect_equal( bc('1 2 "c", d'), c("1", "2", "c", "d")) expect_equal( bc('1 2 3'), c(1, 2, 3) ) expect_equal( bc('1 2 "3"'), c("1", "2", "3") ) expect_equal( bc('1,2|3.4'), c(1, 2, 3.4) ) expect_equal( bc('0xF7 10'), c(247, 10) ) expect_equal( bc(''), NULL ) expect_equal( bc('0x7,0x7'), c(7, 7) ) expect_error( bc('0x70x7') ) expect_equal( bc("'x\\''"), "x\\'" ) expect_error( bc("'x''") ) expect_equal( bc("TRUE FALSE"), c(TRUE, FALSE) ) expect_error( bc("'x' y 7 + 3") ) expect_equal( bc('"a|b" "c,d",f "g e"|q,"t\\"z"'), c("a|b", "c,d", "f", "g e", "q", "t\\\"z") ) expect_equal( bc('"a|b" "c,d" "f" "g e" "q" "t\\\"z"'), c("a|b", "c,d", "f", "g e", "q", "t\\\"z") ) # From Emil Bellamy Begtrup-Bright May 27, 2021 # test of lowercase non-english letters (Danish: æ, ø and å) expect_equal( bc('person_id, geography, danish_letter_æ, danish_letter_ø, danish_letter_å'), c("person_id", "geography", "danish_letter_æ", "danish_letter_ø", "danish_letter_å") ) # From Emil Bellamy Begtrup-Bright May 27, 2021 # test of mix of upcase non-english letters (Danish: Æ, Ø and Å) expect_equal( bc('person_id, geography, danish_letter_Æ, danish_letter_Ø, danish_letter_Å'), c("person_id", "geography", "danish_letter_Æ", "danish_letter_Ø", "danish_letter_Å") ) expect_equal( bc('01 02', convert=FALSE), c("01", "02") ) expect_equal( bc('01 02'), c(1, 2) )
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_bc.R
test_build_frame <- function() { testBFRT <- function(d) { txt <- draw_frame(d) d2 <- eval(parse(text = txt)) expect_equal(d, d2) } d <- data.frame( measure = c("minus binary cross entropy", "accuracy"), training = c(5, 0.8), validation = c(-7, 0.6), stringsAsFactors = FALSE) testBFRT(d) d <- data.frame(x = c(-1, 2)) testBFRT(d) d <- data.frame(x = 1) testBFRT(d) d <- data.frame(x = 1L) testBFRT(d) d1 <- qchar_frame( measure, training, validation | "minus binary cross entropy", loss, val_loss | accuracy, acc, val_acc ) d2 <- data.frame( measure = c("minus binary cross entropy", "accuracy"), training = c("loss", "acc"), validation = c("val_loss", "val_acc"), stringsAsFactors = FALSE) expect_equal(d1, d2) d1 <- qchar_frame( x | 1 | 2 ) d2 <- data.frame( x = c("1", "2"), stringsAsFactors = FALSE) expect_equal(d1, d2) d1 <- data.frame( idx = c(1L, 2L), time = strptime(c("02/27/92 23:03:20", "02/27/92 22:29:56"), "%m/%d/%y %H:%M:%S"), val = c(4, 10), lab = c("a", "b"), stringsAsFactors = FALSE) txt <- draw_frame(d1) invisible(NULL) } test_build_frame()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_build_frame.R
test_build_frame_dates <- function() { d1 <- wrapr::build_frame( "date", "measure", "value" | as.Date("2019-03-01") , "AUC" , as.Date("2019-03-11") | as.Date("2019-03-01") , "R2" , as.Date("2019-03-12") | as.Date("2019-03-02") , "AUC" , as.Date("2019-03-13") | as.Date("2019-03-02") , "R2" , as.Date("2019-03-14") ) d <- data.frame(date = c(as.Date("2019-03-01") , as.Date("2019-03-01"), as.Date("2019-03-02") , as.Date("2019-03-02") ), measure = c("AUC", "R2", "AUC", "R2"), value = c(as.Date("2019-03-11") , as.Date("2019-03-12"), as.Date("2019-03-13") , as.Date("2019-03-14") ), stringsAsFactors = FALSE) expect_true("Date" %in% class(d1$date)) expect_true("Date" %in% class(d1$value)) expect_true(wrapr::check_equiv_frames(d1, d)) invisible(NULL) } test_build_frame_dates()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_build_frame_dates.R
test_c <- function() { ` X` <- 3 y <- 7 X <- 2 X_ <- 5 let( c(X = 'y', F = 'sin'), { d <- data.frame("X" = "X", X2 = "XX", d = X*X, .X = X_, stringsAsFactors = FALSE) X <- list(X = d$X, X2 = d$"X", v1 = `X`, v2 = ` X`, fX = F(1:3)) }) expect_equal(y$X2, 'X') invisible(NULL) } test_c()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_c.R
test_coalesce <- function() { expect_equal(c(1, NA, NA) %?% 5 , c(1, 5, 5)) expect_equal(c(1, NA, NA) %?% list(5) , c(1, 5, 5)) expect_equal(c(1, NA, NA) %?% list(list(5)) , c(1, NA, NA)) expect_equal(c(1, NA, NA) %?% c(NA, 20, NA) , c(1, 20, NA)) expect_equal(NULL %?% list() , NULL) expect_equal(NULL %?% c(1, NA) , c(1, NA)) expect_equal(list(1, NULL, NULL) %?% c(3, 4, NA) , list(1, 4, NA_real_)) expect_equal(list(1, NULL, NULL, NA, NA) %?% list(2, NULL, NA, NULL, NA) , list(1, NULL, NA, NULL, NA)) expect_equal(c(1, NA, NA) %?% list(1, 2, list(3)) , c(1, 2, NA)) expect_equal(c(1, NA) %?% list(1, NULL) , c(1, NA)) expect_equal(list() %?% list(1, NA, NULL), list(1, NA, NULL) ) expect_equal(c() %?% list(1, NA, NULL) , list(1, NA, NULL) ) expect_equal(c() %?% c(1, NA, 2) , c(1, NA, 2)) expect_equal(c(a=1, b= NA) %?% list(3,4), c(a=1, b=4)) expect_equal(list(a=1, b= NA) %?% c(3,4), list(a=1, b=4)) expect_equal(NULL %?% 4, 4) invisible(NULL) } test_coalesce()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_coalesce.R
test_dot_quote <- function() { # # can't work due to the nature of bquote() # a <- wrapr::qchar_frame( # "." , "pred: FALSE", "pred: TRUE" | # "truth: FALSE", tFpF, tFpT , # "truth: TRUE" , tTpF, tTpT) # # b <- wrapr::build_frame( # "." , "pred: FALSE", "pred: TRUE" | # "truth: FALSE", "tFpF" , "tFpT" | # "truth: TRUE" , "tTpF" , "tTpT" ) # # expect_equal(a, b) c <- wrapr::qchar_frame( TRUE , FALSE | TRUE, FALSE ) d <- wrapr::build_frame( "TRUE" , "FALSE" | "TRUE", "FALSE" ) expect_equal(c, d) invisible(NULL) } test_dot_quote()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_dot_quote.R
test_draw_frame <- function() { ex <- data.frame(id = 1:3, x = c(0, 1, NA), res = c("not one", "one", NA), stringsAsFactors = FALSE) f <- build_frame( "id", "x", "res" | 1L , 0 , "not one" | 2L , 1 , "one" | 3L , NA , NA ) expect_equal(ex, f) df <- draw_frame(ex) f2 <- eval(parse(text = df)) expect_equal(ex, f2) invisible(NULL) } test_draw_frame()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_draw_frame.R
test_eager <- function() { lst <- list(sin) attr(lst, 'dotpipe_eager_eval_bracket') <- TRUE res <- 4 %.>% lst[[1]] expect_equal(sin(4), res) f <- function() { sin } attr(f, 'dotpipe_eager_eval_function') <- TRUE res2 <- 4 %.>% f() expect_equal(sin(4), res2) invisible(NULL) } test_eager()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_eager.R
test_fn_test <- function() { # make sure we see functions, even if they have other classes f <- function(x) { sin(x) } r1 <- 5 %.>% f expect_equal(sin(5), r1) class(f) <- "SOME_ODD_NAME" r2 <- 5 %.>% f expect_equal(sin(5), r2) invisible(NULL) } test_fn_test()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_fn_test.R
test_let <- function() { d <- data.frame( Sepal_Length = c(5.8, 5.7), Sepal_Width = c(4.0, 4.4), Species = 'setosa', rank = c(1, 2) ) mapping = list(RankColumn = 'rank', GroupColumn = 'Species') let(alias = mapping, expr = { # Notice code here can be written in terms of known or concrete # names "RankColumn" and "GroupColumn", but executes as if we # had written mapping specified columns "rank" and "Species". # restart ranks at zero. dres <- d dres$RankColumn <- dres$RankColumn - 1 }) expect_equal(dres$rank, c(0,1)) invisible(NULL) } test_let()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_let.R
test_let_null <- function() { e1 = as.character(let(c("z"= "z"), dDT[,"x":=NULL], eval=FALSE)) e2 = as.character(let(list(), dDT[,"x":=NULL], eval=FALSE)) expect_equal(e1, e2) invisible(NULL) } test_let_null()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_let_null.R
test_letl <- function() { d <- data.frame( year= c(2005, 2005), name= c('a', 'a'), stringsAsFactors = FALSE) dstr <- d let(list(NEWCOL='val'), dstr$NEWCOL <- 7, subsMethod= 'stringsubs' ) dlan <- d let(list(NEWCOL='val'), dlan$NEWCOL <- 7, subsMethod= 'langsubs' ) #expect_equal(dsub, dstr) expect_equal(dstr, dlan) invisible(NULL) } test_letl()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_letl.R
# Get some diversity of examples by using # issues submitted to magrittr test_magrittr_issues <- function() { # https://github.com/tidyverse/magrittr/issues/159 # note: magrittr works of compose() forces arguments compose <- function(f, g) { # force(f) # force(g) function(x) g(f(x)) } plus1 <- function(x) x + 1 plus2 <- plus1 %.>% compose(plus1, .) res <- plus2(5) expect_equal(7, res) # https://github.com/tidyverse/magrittr/issues/38 8 %.>% assign("x", .) expect_equal(8, x) # similar to # https://github.com/tidyverse/magrittr/issues/105 res <- 9 %.>% base::sin expect_equal(sin(9), res) # https://github.com/tidyverse/magrittr/issues/156 # not an issue for magritter with dot notations flist <- list(f = sin) res <- 5 %.>% flist$f expect_equal(sin(5), res) res <- 5 %.>% flist[['f']] expect_equal(sin(5), res) # https://github.com/tidyverse/magrittr/issues/32 expect_error( 5 %.>% return(.) ) # https://github.com/tidyverse/magrittr/issues/163 # wrapr doesn't comment to fully gauranteeing this, but nice to confirm rm(list=ls()) global <- 1 f <- function(x, env = parent.frame()) { ls(env) } v1 <- NA v2 <- NA v1 <- f(1) v2 <- 1 %.>% f expect_equal(v1, v2) # https://github.com/tidyverse/magrittr/issues/121 res <- 1:3 %.>% .[-1][-1] expect_equal(3, res) # # . getting captured in various environments # # wrapr is more explicit with . so has more of these dangling refs # https://github.com/tidyverse/magrittr/issues/146 invisible(NULL) } test_magrittr_issues()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_magrittr_issues.R
test_mk_formula <- function() { v <- format(wrapr:::r_plus(c(), add_zero = FALSE)) expect_equal("1", v) v <- format(wrapr:::r_plus(c(), add_zero = TRUE)) expect_equal("0", v) v <- as.character(wrapr:::r_plus(c('x1'), add_zero = FALSE)) expect_equal("x1", v) v <- format(wrapr:::r_plus(c('x1'), add_zero = TRUE)) expect_equal("0 + x1", v) v <- format(wrapr:::r_plus(c('x1', 'x2'), add_zero = FALSE)) expect_equal("x1 + x2", v) v <- format(wrapr:::r_plus(c('x1', 'x2'), add_zero = TRUE)) expect_equal("0 + x1 + x2", v) v <- format(mk_formula("y", c(), intercept = FALSE)) expect_equal("y ~ 0", v) v <- format(mk_formula("y", c(), intercept = TRUE)) expect_equal("y ~ 1", v) v <- format(mk_formula("y", c('x1'), intercept = TRUE)) expect_equal("y ~ x1", v) v <- format(mk_formula("y", c('x1'), intercept = FALSE)) expect_equal("y ~ 0 + x1", v) v <- format(mk_formula("y", c('x1', 'x2'), intercept = TRUE)) expect_equal("y ~ x1 + x2", v) v <- format(mk_formula("y", c('x1', 'x2'), intercept = FALSE)) expect_equal("y ~ 0 + x1 + x2", v) f <- mk_formula("mpg", c("cyl", "disp")) # print(f) model <- lm(f, mtcars) v <- format(model$terms) expect_equal("mpg ~ cyl + disp", v) f <- mk_formula("cyl", c("wt", "gear"), outcome_target = 8, outcome_comparator = ">=") # print(f) model <- glm(f, mtcars, family = binomial) v <- format(model$terms) expect_equal("(cyl >= 8) ~ wt + gear", v) invisible(NULL) } test_mk_formula()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_mk_formula.R
test_named_map_builder <- function() { names <- c("a", "b") vals <- c(1,2) expect_equal(names := vals, c(a = 1, b = 2)) expect_equal(c("a", "b") := c(1,2), c(a = 1, b = 2)) expect_equal("a" := "b", c(a = "b")) name <- "a" expect_equal(name := "b", c(a = "b")) f <- factor(c('a', 'b')) expect_equal(f := c(1, 2), c('a' = 1, 'b' = 2)) invisible(NULL) } test_named_map_builder()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_named_map_builder.R
test_pipe <- function() { # adapted from # library("magrittr") # library("wrapr") # # mtcars %>% # subset(hp > 100) %>% # transform(kpl = mpg %>% multiply_by(0.4251)) %>% # aggregate(. ~ cyl, data = ., FUN = . %>% mean %>% round(2)) %>% # draw_frame(., formatC_options = list(format = "f", digits = 2)) %>% # cat(.) expect <- build_frame( "cyl", "mpg", "disp", "hp" , "drat", "wt", "qsec", "vs", "am", "gear", "carb", "kpl" | 4.00 , 25.90, 108.05, 111.00, 3.94 , 2.15, 17.75 , 1.00, 1.00, 4.50 , 2.00 , 11.01 | 6.00 , 19.74, 183.31, 122.29, 3.59 , 3.12, 17.98 , 0.57, 0.43, 3.86 , 3.43 , 8.39 | 8.00 , 15.10, 353.10, 209.21, 3.23 , 4.00, 16.77 , 0.00, 0.14, 3.29 , 3.50 , 6.42 ) res <- mtcars %.>% subset(., hp > 100) %.>% transform(., kpl = mpg * 0.4251) %.>% aggregate(. ~ cyl, data = ., FUN = function(.) { mean(.) %.>% round(., 2) }) expect_equal(expect, res) lst <- list(h = sin) res <- 5 %.>% lst$h expect_equal(sin(5), res) res <- 5 %.>% lst[['h']] expect_equal(sin(5), res) invisible(NULL) } test_pipe()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_pipe.R
# For testing user S3 functions see: # https://github.com/r-lib/testthat/issues/266 # https://github.com/r-lib/testthat/issues/720 # https://stackoverflow.com/questions/28099185/how-do-i-re-register-s3-method-inside-r-package # But assign in namespace is not to be used in packages, so probably not in tests # So, instead: assign("apply_left.formula", apply_left.formula, envir = .GlobalEnv) test_pipe_paper <- function() { ################################################### ### code chunk number 2: wpipe1 ################################################### 5 %.>% sin(.) ################################################### ### code chunk number 3: wpipe1e ################################################### 5 %.>% {1 + .} 5 %.>% (1 + .) ################################################### ### code chunk number 11: extq1 ################################################### d <- data.frame(x=1:5, y = c(1, 1, 0, 1, 0)) model <- glm(y~x, family = binomial, data = d) apply_right.glm <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { predict(pipe_right_arg, newdata = pipe_left_arg, type = 'response') } if("apply_right.glm" %in% ls(.GlobalEnv)) { warning("not testing apply_right.glm as it already has definition") } else { assign("apply_right.glm", apply_right.glm, envir = .GlobalEnv) d %.>% model rm(list = "apply_right.glm", envir = .GlobalEnv) } ################################################### ### code chunk number 13: extq3 ################################################### apply_left.character <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { pipe_right_arg <- eval(pipe_right_arg, envir = pipe_environment, enclos = pipe_environment) paste0(pipe_left_arg, pipe_right_arg) } if("apply_left.character" %in% ls(.GlobalEnv)) { warning("not testing apply_left.character as it already has definition") } else { assign("apply_left.character", apply_left.character, envir = .GlobalEnv) `%+%` <- wrapr::`%.>%` res <- "a" %+% "b" %+% "c" expect_equal("abc", res) rm(list = "apply_left.character", envir = .GlobalEnv) } ################################################### ### code chunk number 14: extq4 ################################################### apply_left.formula <- function(pipe_left_arg, pipe_right_arg, pipe_environment, left_arg_name, pipe_string, right_arg_name) { pipe_right_arg <- eval(pipe_right_arg, envir = pipe_environment, enclos = pipe_environment) pipe_right_arg <- paste(pipe_right_arg, collapse = " + ") update(pipe_left_arg, paste(" ~ . +", pipe_right_arg)) } if("apply_left.formula" %in% ls(.GlobalEnv)) { warning("not testing apply_left.formula as it already has definition") } else { assign("apply_left.formula", apply_left.formula, envir = .GlobalEnv) `%+%` <- wrapr::`%.>%` (y~a) %+% c("b", "c", "d") %+% "e" rm(list = "apply_left.formula", envir = .GlobalEnv) } invisible(NULL) } test_pipe_paper()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_pipe_paper.R
test_pipe_quote_name <- function() { q1 <- x %.>% quote e1 <- quote(x) expect_equal(e1, q1) x <- -5 q2 <- x %.>% quote expect_equal(e1, q2) v0 <- x %.>% abs expect_equal(5, v0) # would like x %.>% substitute to equal # as.name("x"). Instead we have the slightly weaker # (x %.>% substitute) == substitute(x) # as both substitute quotes or un-quotes depending # if the eval environment is Global or not. vA <- substitute(x) # -5 in test, as.name("x") if run in global env vB <- x %.>% substitute # -5 in test, as.name("x") if run in global env expect_equal(vA, vB) f1 <- function() { x <- -5 v1 <- substitute(x) v1 } v1 <- f1() expect_equal(-5, v1) f2 <- function() { x <- -5 v2 <- x %.>% substitute v2 } v2 <- f2() expect_equal(-5, v2) expect_equal(v1, v2) invisible(NULL) } test_pipe_quote_name()
/scratch/gouwar.j/cran-all/cranData/wrapr/inst/tinytest/test_pipe_quote_name.R