content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
# Epaker kernel function
#
# Kernel function for grid windows
#
# @param x value to apply kernel to
# @author Bonsoo Koo and Kai-Yang Goh
epaker <- function(x) {
(3/4)*(1-x^2)*(abs(x)<=1)
# (1-x^2)*(abs(x)<=1)
}
# Create a bond price list from the data
#
# Tranforms data into a format suitable for estimation
#
# This function converts and extracts bond prices over
# quotation days and different bonds from the raw data
# into a list of sparse matrices for estimation
#
# @param data a bond data. See \code{?USbonds} for an example data structure.
#
# @return If all the required information is present, then the
# output will be a list with length equal to the number of quotation
# days in the data. Each element of the output will be a sparseMatrix
# object for a quotation day with the number of rows being the number of bonds
# and the number of columns being the maximum of time-to-maturity.
# Each row is a bond with price indicated at the corresponding column (time).
# @examples
# \donttest{
# price <- calc_price_slist(USbonds)
# }
# @author Bonsoo Koo and Kai-Yang Goh
#' @importFrom dplyr group_by
#' @importFrom dplyr group_split
calc_price_slist <- function(data) {
price_list <- data %>%
mutate(mid.price = .data$mid.price + as.numeric(as.character(.data$accint))) %>%
select(.data$qdate, .data$crspid, .data$tupq, .data$mid.price)
price_list <- price_list %>%
group_by(.data$qdate) %>%
group_split()
id <- unique(data$crspid)
id_len <- length(id)
tupq_len <- as.integer(max(data$tupq))
qdate_len <- length(unique(data$qdate))
price_slist <- vector(mode = "list", length = qdate_len)
seq_tupq <- 1:tupq_len
for (i in 1:qdate_len) {
x_list <- price_list[[i]]
price_slist[[i]] <- sparseMatrix(i = match(x_list$crspid, id),
j = match(x_list$tupq, seq_tupq),
x = x_list$mid.price,
dims = c(id_len, tupq_len),
dimnames = list(id, seq_tupq))
}
names(price_slist) <- unique(data$qdate)
return(price_slist)
}
# Create a list of sparse matrices to represent cash flows
#
# Tranforms data into a format suitable for estimation
#
# This function converts and extracts coupon payments over
# quotation days and different bonds from the raw data
# into a list of sparse matrices for estimation
#
# @param data data for bonds including quotation days, bond id,
# time until payment and payment amount.
#
# @return If all the required information is present, then the
# output will be a list with length equal to the number of quotation
# days in the data. Each element of the output will be a sparseMatrix
# object for a quotation day with the number of rows being the number of bonds
# and the number of columns being the maximum of time-to-maturity.
# Each row is a bond with cash flow indicated at the corresponding column (time).
# @examples
# \donttest{
# cf <- calc_cf_slist(USbonds)
# }
# @author Bonsoo Koo and Kai-Yang Goh
#' @importFrom dplyr group_by
#' @importFrom dplyr group_split
calc_cf_slist <- function(data) {
cf_list <- select(data, .data$qdate, .data$crspid, .data$tupq, .data$pdint)
cf_list <- cf_list %>%
group_by(.data$qdate) %>%
group_split()
id <- unique(data$crspid)
id_len <- length(id)
tupq_len <- as.integer(max(data$tupq))
qdate_len <- length(unique(data$qdate))
cf_slist <- vector(mode = "list", length = qdate_len)
seq_tupq <- 1:tupq_len
for (u in 1:qdate_len) {
x_list <- cf_list[[u]]
cf_slist[[u]] <- sparseMatrix(i = match(x_list$crspid, id),
j = match(x_list$tupq, seq_tupq),
x = x_list$pdint,
dims = c(id_len, tupq_len)#)
,dimnames=list(id,seq_tupq))
}
names(cf_slist) <- unique(data$qdate)
return(cf_slist)
}
calc_window_epaker <- function(gamma, grid, bandwidth) {
uu <- mapply(function(grid, bandwidth) {(grid-gamma)/bandwidth},
grid = grid,
bandwidth = bandwidth)
epaker(uu)
}
# Weights time grid
#
# Generate kernel weights using Epaker kernal function in relation to time grids
#
# This function generates a weight function attached to each quotation date grid
# for the estimation of a discount function
#
# @param data a bond dataframe
# @param xgrid vector of the quotation date grid
# @param hx vector of quotation date bandwidth
#
# @return Matrix with number of columns being the length of \code{ugrid} and number of rows being the number of unique qdates.
# Each column represents the weights of each qdate for that \code{rgrid}.
# Each column is a \code{ugrid} date with the weights of the qdates used in discount function estimation. qdates correspond to rows.
#
# @author Bonsoo Koo and Kai-Yang Goh
# @examples
# xgrid <- c(0.2,0.4)
# hx <- c(0.18,0.18)
# out <- calc_uu_window(data = USbonds, xgrid = xgrid,hx = hx)
calc_uu_window <- function(data, xgrid, hx) {
#ugrid = values you want to compute dbar and hhat for
#hu = bandwidth parameter
qdate_len <- length(unique(data$qdate))
gamma <- seq(1, qdate_len, 1) / qdate_len
calc_window_epaker(gamma, xgrid, hx) %>%
as.matrix()
}
# Weights interest rate grid
#
# Generate a kernel weight function in relation to interest rate grids
#
# This function generates a weight function attached to each interest rate grid
# for the estimation of a discount function
#
# @param interest vector of daily interest rates
# @param rgrid vector of interest rate grid
# @param hr vector of interest rate bandwidth
#
# @return Matrix with number of columns being the length of \code{rgrid} and number of rows being the number of unique qdates.
# Each column represents the weights of each qdate for that \code{rgrid}.
# Each column is a \code{rgrid} date with the weights of the qdates used in discount function estimation. qdates correspond to rows.
#
# @author Bonsoo Koo, Kai-Yang Goh and Nathaniel Tomasetti
# @examples
# interest <- c(1.01, 1.02)
# rgrid <- c(0.2,0.4)
# hr <- c(0.18,0.18)
# out <- calc_r_window(interest = interest, rgrid = rgrid,hr = hr)
calc_r_window <- function(interest, rgrid, hr) {
calc_window_epaker(interest, rgrid, hr)
}
# Provide indices in relation to time grids
#
# This function provide indices for the start and end of the qdates included in the kernel windows for each \code{ugrid}.
#
# @param data a bond data frame. See \code{?USbonds} for an example data structure.
# @param ugrid vector of quotation date grid
# @param hu vector of quotation date bandwidth
#
# @return Matrix. The start and end of the qdates included in the ugrid kernel windows
#
# @author Bonsoo Koo and Kai-Yang Goh
# @examples
# ugrid <- c(0.2,0.4)
# hu <- c(0.18,0.18)
# out <- calc_day_idx(data = USbonds, ugrid = ugrid, hu = hu)
calc_day_idx <- function(data, ugrid, hu) {
u <- calc_uu_window(data, ugrid, hu)
dim(u) <- c(length(unique(data$qdate)), length(ugrid))
apply(u, 2, function(y) {
window_idx <- which(y != 0)
return(c(window_idx[1], window_idx[length(window_idx)]))
}) %>%
t()
}
# Weights time to maturity grid
#
# Apply kernel in relation to time-to-maturity grids
#
# This function generates a weight function attached to each time grid
# for the estimation of a discount function
#
# @param data a bond data frame
# @param tau vector of the time-to-maturity grid
# @param ht vector of the time-to-maturity grid bandwidth
#
# @return Matrix with number of columns being the length of \code{tau} and number of rows being the number of unique qdates.
# Each column represents the weights of each qdate for that \code{tau}.
# Each column is a \code{tau} date with the weights of the qdates used in discount function estimation. qdates correspond to rows.
# @author Bonsoo Koo and Kai-Yang Goh
# @examples
# tau <- c(30, 60, 90) / 365
# ht <- c(15, 15 , 15) / 365
# out <- calc_ux_window(data = USbonds, tau = tau, ht = ht)
calc_ux_window <- function(data, tau, ht, units = 365) {
#x = values you want to compute dbar and hhat for
#h = bandwidth parameter
tupq_len<- as.integer(max(data$tupq))
gamma <- seq_len(tupq_len)/ units
calc_window_epaker(gamma, tau, ht)
}
# Provide indices in relation to time-to-maturity grids
#
# This function provides indices for the first and last tau included in the kernel window of each \code{tau}.
#
# @param data Bond dataframe
# @param tau vector of the time-to-maturity grid
# @param ht vector of the time-to-maturity grid bandwidth
#
# @return Matrix. The first and last tau included in the current kernel window.
#
# @author Bonsoo Koo and Kai-Yang Goh
# @examples
# tau <- c(30, 60, 90) / 365
# ht <- c(15, 15 , 15) / 365
# out <- calc_tupq_idx(data = USbonds, tau = tau, ht = ht)
calc_tupq_idx <- function(data, tau, ht, units = 365) {
x <- calc_ux_window(data,tau,ht, units)
apply(x, 2, function(y) {
window_idx <- which(y > 0.01)
lth <- length(window_idx)
if(lth==0) lth <- 1
return(c(window_idx[1], window_idx[lth]))
}) %>%
t()
}
# Automatic selection of tau and ht values
#
# Selects tau and ht from values of tau_p and htp with a given number of maturing bonds
#
# Automatically select values for sparse time to maturity \code{tau} and \code{ht}
# for a given dense time to maturity value of tau_p and htp and quotation date xgrid and hx.
# The length of the provided tau may change for different xgrid values, so it is recommended
# that the function is called separately for different values of xgrid.
# @param data Bond dataframe. See \code{?USbonds} for an example data strcture..
# @param xgrid A single value for xgrid between 0 and 1
# @param hx A single value for the bandwidth of the xgrid value
# @param tau_p vector of dense time to maturity grid
# @param htp vector of dense time to maturity bandwidth
# @param min_points Integer, minimum number of maturing bonds in a tau_p range to be included in tau.
# @param rgrid Optional, a single value for rgrid
# @param hr Optional, A single value for the bandwidth of the rgrid value
# @param interest, Optional, a vector of daily interest rates for use with rgrid. Must have a length equal to the number of unique qdates in data
# @param units, Optional, number of units per period. Eg 365 for daily data, 12 for monthly.
# Grid values without maturing bonds do not have sufficient data for stable estimates.
# @return List of \code{tau}, \code{ht}, \code{tau_p} and \code{htp}. \code{tau_p} and \code{htp} is the same as input.
# For the usage of created \code{tau} and \code{ht}, see \code{\link{estimate_yield}}.
# @examples
# xgrid <- 0.2
# hx <- 0.18
# tau_p <- c(30, 60, 90) / 365
# htp <- c(15, 15 , 15) / 365
# out <- create_tau_ht(data = USbonds, xgrid = xgrid, hx = hx, tau_p = tau_p,htp =htp, min_points = 5)
# @author Nathaniel Tomasetti
create_xgrid_hx <- function(data, xgrid, hx, tau, ht, min_points, rgrid = NULL, hr = NULL, interest = NULL, units = 365){
tau_p <- tau
htp <- ht
points <- num_points_mat(data, xgrid, hx, tau, ht, rgrid, hr, interest, units)
# Shrink window if there is not enough bonds at the end
while(points[length(points)] < min_points){
points <- points[seq_len(length(points)-1)]
htp <- ht[seq_along(points)]
tau_p <- tau[seq_along(points)]
}
# Set ht to htp, but exclude points where there are not many bonds maturing
ht <- htp
ht[points < min_points] <- NA
# Find where the gaps start: the indices of elements of ht that are non na, but are followed by an na, and where the gap ends: a non-na ht that follows an na ht
gap_start <- which(!is.na(ht) & dplyr::lead(is.na(ht)))
gap_end <- which(!is.na(ht) & dplyr::lag(is.na(ht)))
# Amount of time in each gap
gap_size <- tau_p[gap_end] - tau_p[gap_start]
# ht at the edges of missing values are extended so half the gap is covered by each end
ht[gap_start] <- gap_size / 2
ht[gap_end] <- gap_size / 2
# Remove NA values
ht <- ht[!is.na(ht)]
# Set tau to be tau_p without the area without much data
tau <- tau_p[points >= min_points]
list(tau = tau, ht = ht, tau_p = tau_p, htp = htp)
}
| /scratch/gouwar.j/cran-all/cranData/ycevo/R/preparation.R |
# @title Calculates number of bonds that mature in each tau
# @param data A data frame; bond data to estimate discount curve from.
# @param xgrid A single value for xgrid between 0 and 1
# @param hx A single value for the bandwidth of the xgrid value
# @param tau A numeric vector of the time-to-maturity grid
# for the discount function at the corresponding time.
# @param ht A numeric vector matching tau, bandwidth parameter determining the size of the window
# that corresponds to each time-to-maturity.
# @param rgrid Optional, a single value for rgrid
# @param hr Optional, A single value for the bandwidth of the rgrid value for use with rgrid
# @param interest Optional, A vector of daily interest rates for use with rgrid
# @keywords internal
# @author Bonsoo Koo, Kai-Yang Goh and Nathaniel Tomasetti
#
num_points_mat <- function(data, xgrid, hx, tau, ht, rgrid = NULL, hr = NULL, interest = NULL, units = 365) {
# Check dates in data matches interest rate
dates <- unique(data$qdate)
if(!is.null(interest)){
if(length(interest) != length(dates)){
stop('Length of interest rate vector does not match number of unique qdates')
}
}
# Calculate the u and r windows (if r is provided)
window <- calc_uu_window(data, xgrid, hx)
if(!is.null(rgrid) & !is.null(hr) & !is.null(interest)){
windowR <- calc_r_window(interest, rgrid, hr)
window <- window * windowR
}
# Find subset of data with positive kernel
kernel <- data.frame(qdate = dates, k = window)
if("k" %in% colnames(data)) colnames(data)[colnames(data) == "k"] <- "original_k"
data_sub <- data %>%
left_join(kernel, by = 'qdate') %>%
filter(.data$k > 0)
# Calculate number of maturing bonds in each x window
### Highly rely on the notion that tupq and tau are in days
x_idx <- calc_tupq_idx(data, tau, ht, units)
sapply(seq_along(tau),
function(j) sum(
dplyr::between(
as.numeric(data_sub$tupq),
x_idx[j,1],
x_idx[j,2]) &
data_sub$pdint >= 100)
)
}
#' Generate a yield curve with cubic time evolution
#'
#' Generate a yield curve using the extended version of Nelson & Siegel model (Nelson, C. R., & Siegel, A. F., 1987).
#' This has been used in the simulation setting (Equation (30)) of Koo, B., La Vecchia, D., & Linton, O. (2021).
#' See \code{Details} and \code{References}.
#'
#' Returns a matrix where each column corresponds to a yield curve at a different point in time.
#' The initial curve at time to maturity zero is estimated from the following equation
#' \deqn{Yield_{i, 0} = b_0 + b_1 * ((1 - \exp(-\tau_i / t_1)) / (\tau / t_1)) + b_2 * ((1 - \exp(-\tau_i / t_2)) / (\tau_i / t_2) - \exp(-\tau_i / t_2))}
#' where \eqn{\tau_i} is the time to maturity, usually measured in years. This defines the yield curve for the quotation date = 0.
#' The yield curve for quotation dates = 1, 2, ... , max_q_date multiplies this curve by the cubic equation,
#' \deqn{Yield_{i, t} = Yield_{i, 0} * (1 + linear * t + quadratic * t^2 + cubic * t^3)}
#' so the yield curve slowly changes over different quotation dates.
#'
#' @param n_qdate Integer giving the number of quotation dates to use in the data. Defaults to 12.
#' @param periods Integer giving the maximum number of time-to-maturity periods the yield curve is estimated for each quotation date. Defaults to 36
#' @param b0 Level term in yield curve equation, Defaults to 0. See \code{Details}.
#' @param b1 Slope term in yield curve equation, Defaults to 0.05. See \code{Details}.
#' @param b2 Curvature term in yield curve equation, Defaults to 2. See \code{Details}.
#' @param t1 Scaling parameter in yield curve equation, Defaults to 0.75. See \code{Details}.
#' @param t2 Scaling parameter in yield curve equation, Defaults to 125. See \code{Details}.
#' @param linear Linear term in yield curve evolution, Defaults to -0.55. See \code{Details}.
#' @param quadratic Quadratic term in yield curve evolution. Defaults to 0.55. See \code{Details}.
#' @param cubic Cubic term in yield curve evolution. Defaults to -0.55. See \code{Details}.
#'
#' @return
#' \describe{
#' \item{\code{generate_yield}}{
#' Numeric matrix. Each column is a yield curve in a point in time (a quotation date). Each row is for a time-to-maturity.
#' For example, the number in the second column third row is the yield for the yield curve at the second quotation date,
#' for the third time-to-maturity ranking from shortest to longest. See \code{Details} for the equation to generate the yield curve.
#' See \code{Examples} for a example with the code to visually inspect the yield curves.}
#' }
#' @examples
#' out <- generate_yield()
#'
#' # plots
#' library(tidyverse)
#' out <- data.frame(out)
#' colnames(out) <- 1:12
#' out <- mutate(out, time = 1:36)
#' out <- pivot_longer(out, -time, names_to = "qdate", values_to = "yield")
#' ggplot(out) +
#' geom_line(aes(x=time, y=yield, color = qdate))
#'
#' @references Nelson, C. R., & Siegel, A. F. (1987). Parsimonious Modeling of Yield Curves. The Journal of Business, 60(4), 473-489.
#' @references Koo, B., La Vecchia, D., & Linton, O. (2021). Estimation of a nonparametric model for bond prices from cross-section and time series information. Journal of Econometrics, 220(2), 562-588.
#' @export
generate_yield <- function(n_qdate = 12, periods = 36,
b0 = 0, b1 = 0.05, b2 = 2,
t1 = 0.75, t2 = 125,
linear = -0.55, quadratic = 0.55, cubic = -0.55){
tauSeq <- (1:periods)/(periods/10)
yieldInit <- b0 + b1 * ((1 - exp(- tauSeq / t1)) / ( tauSeq / t1)) +
b2 * ((1 - exp(- tauSeq / t2)) / (tauSeq / t2) - exp(- tauSeq / t2))
yield <- matrix(0, periods, n_qdate)
for(i in 1:n_qdate){
t <- i / n_qdate
yield[,i] <- yieldInit * (1 + cubic * t^3 + quadratic * t^2 + linear * t)
}
yield
}
#' @param time Numeric value.
#' @param maturity Numeric value. Maturity in years.
#' @describeIn generate_yield Return the yield at a specific point in time of a specific maturity.
#' @return
#' \describe{
#' \item{\code{get_yield_at}}{Numeric scalar.}
#' }
#' @export
get_yield_at <- function(time, maturity,
b0 = 0, b1 = 0.05, b2 = 2,
t1 = 0.75, t2 = 125,
linear = -0.55, quadratic = 0.55, cubic = -0.55) {
yieldInit <- b0 + b1 * ((1 - exp(- maturity / t1)) / ( maturity / t1)) +
b2 * ((1 - exp(- maturity / t2)) / (maturity / t2) - exp(- maturity / t2))
yieldInit * (1 + cubic * time^3 + quadratic * time^2 + linear * time)
}
#' @param time Numeric value.
#' @param maturity Numeric value. Maturity in years.
#' @return
#' \describe{
#' \item{\code{get_yield_at_vec}}{Numeric vector.}
#' }
#' @describeIn generate_yield Vectorised version of \code{get_yield_at}.
#' @export
get_yield_at_vec <- function(time, maturity,
b0 = 0, b1 = 0.05, b2 = 2,
t1 = 0.75, t2 = 125,
linear = -0.55, quadratic = 0.55, cubic = -0.55) {
mapply(get_yield_at, time, maturity,
b0 = b0, b1 = b1, b2 = b2,
t1 = t1, t2 = t2,
linear = linear, quadratic = quadratic, cubic = cubic)
}
| /scratch/gouwar.j/cran-all/cranData/ycevo/R/util.R |
#' Nonparametric Estimation of the Yield Curve Evolution
#'
#' Nonparametric estimation of the discount rate and yield curve.
#' @aliases ycevo-package
#' @docType package
#' @keywords package
#'
#' @author Bonsoo Koo \email{bonsoo.koo@@monash.edu}
#' @author Kai-Yang Goh \email{kai-yang.goh@@monash.edu}
#' @author Nathaniel Tomasetti \email{nathaniel.tomasetti@@gmail.com}
#' @author Yangzhuoran Fin Yang (Maintainer) \email{fin.yang@@monash.edu}
#'
#' @importClassesFrom Matrix dgCMatrix
#' @importFrom Rcpp evalCpp
#' @importFrom Matrix colSums rowSums sparseMatrix t
#' @importFrom dplyr filter left_join mutate select group_by lead lag group_split ungroup
#' @importFrom rlang !! sym .data
#' @importFrom stats var
#' @importFrom magrittr %>%
#' @importFrom Rcpp sourceCpp
#' @useDynLib ycevo
#' @references Koo, B., La Vecchia, D., & Linton, O. (2021). Estimation of a nonparametric model for bond prices from cross-section and time series information. Journal of Econometrics, 220(2), 562-588.
"_PACKAGE"
utils::globalVariables(c(".")) | /scratch/gouwar.j/cran-all/cranData/ycevo/R/ycevo-package.R |
#' Estimate yield function
#'
#' @md
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Nonparametric estimation of discount functions at given dates, time-to-maturities,
#' and interest rates (experienced users only) and their transformation to the yield curves.
#'
#' @details
#' Suppose that a bond \eqn{i} has a price \eqn{p_i} at time t with a set of cash payments,
#' say \eqn{c_1, c_2, \ldots, c_m} with a set of corresponding discount values
#' \eqn{d_1, d_2, \ldots, d_m}. In the bond pricing literature, the market price of
#' a bond should reflect the discounted value of cash payments. Thus, we want to minimise
#' \deqn{(p_i-\sum^m_{j=1}c_j\times d_j)^2.}
#' For the estimation of \eqn{d_k(k=1, \ldots, m)}, solving the first order condition yields
#' \deqn{(p_i-\sum^m_{j=1}c_j \times d_j)c_k = 0, }
#' and
#' \deqn{\hat{d}_k = \frac{p_i c_k}{c_k^2} - \frac{\sum^m_{j=1,k\neq k}c_k c_j d_j}{c_k^2}.}
#'
#' There are challenges:
#' \eqn{\hat{d}_k} depends on all the relevant discount values for the cash payments of the bond.
#' Our model contains random errors and our interest lies in expected value of \eqn{d(.)} where
#' the expected value of errors is zero.
#' \eqn{d(.)} is an infinite-dimensional function not a discrete finite-dimensional vector.
#' Generally, cash payments are made biannually, not dense at all. Moreover, cash payment schedules
#' vary over different bonds.
#'
#' Let \eqn{d(\tau, X_t)} be the discount function at given covariates \eqn{X_t} (dates \code{xgrid} and
#' interest rates \code{rgrid}), and given time-to-maturities \eqn{\tau} (\code{tau}).
#' \eqn{y(\tau, X_t)} is the yield curve at given covariates \eqn{X_t} (dates \code{xgrid} and
#' interest rates \code{rgrid}), and given time-to-maturities \eqn{\tau} (\code{tau}).
#'
#' We pursue the minimum of the following
#' smoothed sample least squares objective function for any smooth function \eqn{d(.)}:
#' \deqn{Q(d) = \sum^T_{t=1}\sum^n_{i=1}\int\{p_{it}-\sum^{m_{it}}_{j=1}c_{it}(\tau_{ij})d(s_{ij}, x)\}^2 \sum^{m_{it}}_{k=1}\{K_h(s_{ik}-\tau_{ik})ds_{ik}\}K_h(x-X_t)dx,}
#' where a bond \eqn{i} has a price \eqn{p_i} at time t with a set of cash payments \eqn{c_1, c_2, \ldots, c_m} with a set of corresponding discount values
#' \eqn{d_1, d_2, \ldots, d_m},
#' \eqn{K_h(.) = K(./h)} is the kernel function with a bandwidth parameter \eqn{h},
#' the first kernel function is the kernel in space with bonds whose maturities \eqn{s_{ik}}
#' are close to the sequence \eqn{\tau_{ik}},
#' the second kernel function is the kernel in time and in interest rates with \eqn{x},
#' which are close to the sequence \eqn{X_t}.
#' This means that bonds with similar cash flows, and traded in contiguous days,
#' where the short term interest rates in the market are similar,
#' are combined for the estimation of the discount function at a point in space, in time, and in "interest rates".
#'
#' The estimator for the discount function over time to maturity and time is
#' \deqn{\hat{d}=\arg\min_d Q(d).}
#' This function provides a data frame of the estimated yield and discount rate at each combination of the
#' provided grids. The estimated yield is transformed from the estimated discount rate.
#'
#' For more information on the estimation method, please refer to \code{References}.
#'
#'
#'
#' @param data Data frame; bond data to estimate discount curve from. See \code{?USbonds} for an example bond data structure.
#' @param xgrid Numeric vector of values between 0 and 1.
#' Time grids over the entire time horizon (percentile) of the data at which the discount curve is evaluated.
#' @param tau Numeric vector that
#' represents time-to-maturities in years where discount function and yield curve will be found
#' for each time point \code{xgrid}.
#' See \code{Details}.
#' @param ... Reserved for exogenous variables.
#' @param loess Logical. Whether the output estimated discount and yield are to be smoothed using locally estimated scatterplot smoothing (LOESS)
#' @examples
#' library(dplyr)
#' # Simulate 4 bonds issued at 2020-01-01
#' # with maturity 180, 360, 540, 720 days
#' # Apart from the first one,
#' # each has coupon 2,
#' # of which half is paid every 180 days.
#' # The yield curve is sumulated fron `get_yield_at_vec`
#' # Quotation date is also at 2020-01-01
#' exp_data <- tibble(
#' qdate = "2020-01-01",
#' crspid = rep(1:4, 1:4),
#' pdint = c(100, 1, 101, 1, 1, 101, 1, 1, 1, 101),
#' tupq = unlist(sapply(1:4, seq_len)) * 180,
#' accint = 0
#' ) %>%
#' mutate(discount = exp(-tupq/365 * get_yield_at_vec(0, tupq/365))) %>%
#' group_by(crspid) %>%
#' mutate(mid.price = sum(pdint * discount)) %>%
#' ungroup()
#'
#' # Only one quotation date so time grid is set to 1
#' xgrid <- 1
#' # Discount function is evaluated at time to maturity of each payment in the data
#' tau <- unique(exp_data$tupq/365)
#'
#' ycevo(
#' exp_data,
#' xgrid = xgrid,
#' tau = tau
#' )
#'
#' @references Koo, B., La Vecchia, D., & Linton, O. (2021). Estimation of a nonparametric model for bond prices from cross-section and time series information. Journal of Econometrics, 220(2), 562-588.
#' @order 1
#' @export
ycevo <- function(data,
xgrid,
tau,
...,
loess = length(tau)>10){
if(anyDuplicated(xgrid)){
stop("Duplicated xgrid found.")
}
if(anyDuplicated(tau)){
stop("Duplicated tau found.")
}
hx <- find_bindwidth_from_xgrid(xgrid, data)
ht <- find_bindwidth_from_tau(tau)
estimate_yield(
data = data ,
xgrid = xgrid,
hx = hx,
tau = tau,
ht = ht,
loess = loess)
}
find_bindwidth_from_tau <- function(tau){
laggap <- tau - lag(tau)
leadgap <- lead(tau) - tau
vapply(
1:length(tau),
function(x) max(laggap[x], leadgap[x], na.rm = TRUE),
1)
}
find_bindwidth_from_xgrid <- function(xgrid, data){
hx <- 1/length(xgrid)
if(sum(calc_uu_window(data, xgrid, hx)) == 0) {
recommend <- seq_along(xgrid)/length(xgrid)
stop("Inappropriate xgrid. Recommend to choose value(s) from: ", paste(recommend, collapse = ", "))
}
hx
}
| /scratch/gouwar.j/cran-all/cranData/ycevo/R/ycevo.R |
#' Yes No with Variable Responses
#'
#' Asks a custom yes-no question with randomly varying responses.
#' Returns a flag indicating whether the user answered yes or no.
#' It is designed to be used in situations where the users needs to confirm
#' an affirmative action.
#'
#' The objects are first pasted without separators
#' and collapsed using `[paste0](..., collapse = "")`
#' before being output using [cat()].
#'
#' The order and phrasing of the possible responses varies randomly to ensure
#' the user consciously chooses
#' (as opposed to automatically types their response).
#'
#' A total of three responses are offered - two of which correspond to No and
#' one of which corresponds to Yes.
#' The possible responses are skewed to No to reduce the chances that
#' a blindly-typing
#' user mistakenly chooses an affirmative action.
#' For the same reason, selection of uncertain responses such as
#' 'Uhhh... Maybe?'
#' is considered to be a No.
#' Selection of a 0 (to exit) is also considered to be No.
#' Questions should be phrased accordingly.
#'
#' @param ... Objects to paste and then output to produce the question.
#' @return A flag indicating whether the user answered yes or no.
#' @seealso [yesno2()]
#' @export
#' @examples
#' \dontrun{
#' yesno("Do you like ", R.Version()$nickname, "?")
#' }
yesno <- function(...) {
yeses <- c(
"Yes", "Definitely", "For sure", "Yup", "Yeah",
"I agree", "Absolutely"
)
nos <- c("No way", "Not yet", "I forget", "No", "Nope", "Uhhhh... Maybe?")
qs <- c(sample(yeses, 1), sample(nos, 2))
rand <- sample(length(qs))
cat(paste0(..., collapse = ""))
utils::menu(qs[rand]) == which(rand == 1)
}
| /scratch/gouwar.j/cran-all/cranData/yesno/R/yesno.R |
#' Yes No with Two Custom Responses
#'
#' Asks a custom yes-no question with two responses (by default 'Yes' or 'No').
#' Returns a flag indicating which response the user choose.
#' It is designed to be used in situations where a user needs to choose
#' one of two affirmative options.
#'
#' The objects are first pasted without separators
#' and collapsed using `[paste0](..., collapse = "")`
#' before being output using [cat()].
#'
#' Selection of a 0 (to exit) causes the code to throw an error.
#'
#' @inheritParams yesno
#' @param yes A string of the first response.
#' @param no A string of the second response.
#' @return A flag indicating whether the user selected the first (TRUE) or
#' second (FALSE) response.
#' @seealso [yesno()]
#' @export
#' @examples
#' \dontrun{
#' yesno2("Do you like this question?", yes = "I really do")
#' }
yesno2 <- function(..., yes = "Yes", no = "No") {
if (!(is.character(yes) && identical(length(yes), 1L)) &&
isTRUE(!is.na(yes))) {
stop("yes must be a string", call. = FALSE)
}
if (!(is.character(no) && identical(length(no), 1L)) &&
isTRUE(!is.na(no))) {
stop("no must be a string", call. = FALSE)
}
cat(paste0(..., collapse = ""))
response <- utils::menu(c(yes, no))
if (response == 0) stop("user choose to exit")
response == 1
}
| /scratch/gouwar.j/cran-all/cranData/yesno/R/yesno2.R |
# global file set up for removing CRAN check messages
# "no visible binding for global variable"
# source: https://community.rstudio.com/t/how-to-solve-no-visible-binding-
# for-global-variable-note/28887
my_globals <- c(
"Date", "Open", "High", "Low", "Close",
"Adj Close", "Volume", "ref_date",
"price_open", "price_high", "price_low",
"price_close", "price_adjusted", "volume",
"EPIC", "Company", "Symbol", "Security",
"GICS Sector", "ticker", "company", "sector",
"time_groups", "first", "last",
"Ticker", "Industry", "Headquarters",
# from yf_live_prices
"meta", "symbol", "regularMarketTime", "regularMarketPrice",
"time_stamp","previousClose","price","last_price",
# from yf_live_prices
"amount"
)
utils::globalVariables(my_globals)
| /scratch/gouwar.j/cran-all/cranData/yfR/R/globals.R |
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
#' @param lhs A value or the magrittr placeholder.
#' @param rhs A function call using the magrittr semantics.
#' @return The result of calling `rhs(lhs)`.
NULL
| /scratch/gouwar.j/cran-all/cranData/yfR/R/utils-pipe.R |
#' Returns the default folder for caching
#'
#' By default, yfR uses a temp dir to store files.
#'
#' @return a path (string)
#' @export
#'
#' @examples
#' print(yf_cachefolder_get())
yf_cachefolder_get <- function() {
path_cache <- file.path(tempdir(), "yf_cache")
return(path_cache)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_cache.R |
#' Downloads a collection of data from Yahoo Finance
#'
#' This function will use a set collection of YF data, such as index components
#' and will download all data from Yahoo Finance using \code{\link{yf_get}}.
#'
#' @param collection A collection to fetch data (e.g. "SP500", "IBOV", "FTSE" ).
#' See function \code{\link{yf_get_available_collections}} for finding all
#' available collections
#' @param ... Other arguments passed to \code{\link{yf_get}}
#' @inheritParams yf_get
#'
#' @return A data frame with financial prices from collection
#' @export
#'
#' @examples
#'
#' \donttest{
#' df_yf <- yf_collection_get(collection = "IBOV",
#' first_date = Sys.Date() - 30,
#' last_date = Sys.Date()
#' )
#' }
#'
yf_collection_get <- function(collection,
first_date = Sys.Date() - 30,
last_date = Sys.Date(),
do_parallel = FALSE,
do_cache = TRUE,
cache_folder = yf_cachefolder_get(),
...) {
cli::cli_h1('Fetching price collection for {collection}')
av_collections <- yf_get_available_collections()
if (!collection %in% av_collections) {
stop(
"Check input collection. Available collections are ",
paste0(av_collections, collapse = ", ")
)
}
df_collection <- yf_index_composition(mkt_index = collection)
ticker_index <- df_collection$index_ticker[1]
# fix tickers for BR/IBOV
if (collection == "IBOV") {
# all ibov tickers finish with .SA
my_tickers <- stringr::str_c(df_collection$ticker, ".SA")
} else {
my_tickers <- df_collection$ticker
}
# ok, now fetch data for collection
df_yf <- yf_get(
tickers = my_tickers,
first_date = first_date,
last_date = last_date,
do_cache = do_cache,
do_parallel = do_parallel,
bench_ticker = ticker_index,
cache_folder = cache_folder,
...
)
return(df_yf)
}
#' Returns available collections
#'
#' @inheritParams yf_index_list
#' @return A string vector with available collections
#' @export
#'
#' @examples
#'
#' print(yf_get_available_collections())
yf_get_available_collections <- function(print_description = FALSE) {
available_indices <- yf_index_list(print_description)
return(invisible(available_indices))
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_collections.R |
#' Transforms a long (stacked) data frame into a list of wide data frames
#'
#' @param df_in dataframe in the long format (probably the output of yf_get())
#'
#' @return A list with dataframes in the wide format (each element is a
#' different column)
#' @export
#'
#' @examples
#'
#' my_f <- system.file("extdata/example_data_yfR.rds", package = "yfR")
#' df_tickers <- readRDS(my_f)
#'
#' print(df_tickers)
#'
#' l_wide <- yf_convert_to_wide(df_tickers)
#' l_wide
yf_convert_to_wide <- function(df_in) {
cols_to_keep <- c("ref_date", "ticker")
my_cols <- setdiff(names(df_in), cols_to_keep)
fct_format_wide <- function(name_in, df_in) {
temp_df <- df_in[, c("ref_date", "ticker", name_in)]
# make sure data points are unique
# always fetch first ocurrence
temp_df <- unique(temp_df)
# convert
temp_df_wide <- tidyr::pivot_wider(
data = temp_df,
names_from = ticker,
values_from = tidyselect::all_of(name_in)
)
return(temp_df_wide)
}
l_out <- lapply(my_cols,
fct_format_wide,
df_in = df_in)
# fix names in columns
names(l_out) <- my_cols
return(l_out)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_data_convert_to_wide.R |
#' Get clean data from yahoo/google using quantmod::getSymbols
#' @noRd
yf_data_get_raw <- function(ticker,
first_date,
last_date) {
# dont push luck with yahoo servers
# No problem in my testings, so far. You can safely leave it unrestricted
# Sys.sleep(0.5)
# set empty df for errors
df_raw <- dplyr::tibble()
# 2021-06-18 use quantmod::getSymbol
suppressMessages({
suppressWarnings({
try({
df_raw <- quantmod::getSymbols(Symbols = ticker,
src = 'yahoo',
from = first_date,
to = last_date,
auto.assign = FALSE)
},
silent = TRUE)
})
})
# in case of error, return empty df
if (nrow(df_raw) == 0) return(df_raw)
# fix df_raw
ref_date <- zoo::index(df_raw)
df_raw <- as.data.frame(df_raw) %>%
dplyr::mutate(ref_date = ref_date,
ticker = ticker)
#%>%
# as.data.frame(df_raw[!duplicated(zoo::index(df_raw))])
colnames(df_raw) <- c('price_open','price_high','price_low',
'price_close','volume','price_adjusted',
'ref_date', 'ticker')
# further organization
df_raw <- df_raw %>%
dplyr::arrange(ref_date) %>% # make sure dates are sorted,
dplyr::relocate(ticker, ref_date) # relocate columns
# make sure each date point only appear once
# sometimes, yf outputs two data points for the same date (not sure why)
df_raw <- df_raw %>%
dplyr::group_by(ref_date, ticker) %>%
dplyr::filter(dplyr::row_number() == 1)
# make sure only unique rows are returned
df_raw <- unique(df_raw)
# remove rows with NA
idx <- !is.na(df_raw$price_adjusted)
df_raw <- df_raw[idx, ]
return(df_raw)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_data_get_raw.R |
#' Download financial data from Yahoo Finance
#'
#' Based on a ticker (id of a stock) and time period, this function will
#' download stock price data from Yahoo Finance and organizes it in the long
#' format. Yahoo Finance <https://finance.yahoo.com/> provides a vast repository of
#' stock price data around the globe. It cover a significant number of markets
#' and assets, being used extensively in academic research and teaching. In
#' the website you can lookup the ticker of a company.
#'
#' @section The cache system:
#'
#' The yfR`s cache system is basically a bunch of rds files that are saved every time
#' data is imported from YF. It indexes all data by ticker and time period. Whenever
#' a user asks for a dataset, it first checks if the ticker/time period exists in
#' cache and, if it does, loads the data from the rds file.
#'
#' By default, a temporary folder is used (see function
#' \link{yf_cachefolder_get}, which means that all cache files are
#' session-persistent. In practice, whenever you restart your R/RStudio session,
#' all cache files are lost. This is a choice I've made due to the fact that
#' merging adjusted stock price data after corporate events (dividends/splits)
#' is a mess and prone to errors. This only happens for stock price data,
#' and not indices data.
#'
#' If you really need a persistent cache folder, which is Ok for indices data,
#' simply set a path with argument cache_folder (see warning section).
#'
#' @section Warning:
#'
#' Be aware that when using cache system in a local folder (and not the default
#' tempdir()), the aggregate prices series might not match if
#' a split or dividends event happens in between cache files.
#'
#' @param tickers A single or vector of tickers. If not sure whether the ticker is
#' available, search for it in YF <https://finance.yahoo.com/>.
#' @param first_date The first date of query (Date or character as YYYY-MM-DD)
#' @param last_date The last date of query (Date or character as YYYY-MM-DD)
#' @param bench_ticker The ticker of the benchmark asset used to compare dates.
#' My suggestion is to use the main stock index of the market from where the
#' data is coming from (default = ^GSPC (SP500, US market))
#' @param type_return Type of price return to calculate:
#' 'arit' - arithmetic (default), 'log' - log returns.
#' @param freq_data Frequency of financial data: 'daily' (default),
#' 'weekly', 'monthly', 'yearly'
#' @param how_to_aggregate Defines whether to aggregate the data using the
#' first observations of the aggregating period or last ('first', 'last').
#' For example, if freq_data = 'yearly' and how_to_aggregate = 'last', the
#' last available day of the year will be used for all
#' aggregated values such as price_adjusted. (Default = "last")
#' @param thresh_bad_data A percentage threshold for defining bad data. The
#' dates of the benchmark ticker are compared to each asset. If the percentage
#' of non-missing dates with respect to the benchmark ticker is lower than
#' thresh_bad_data, the function will ignore the asset (default = 0.75)
#' @param do_complete_data Return a complete/balanced dataset? If TRUE, all
#' missing pairs of ticker-date will be replaced by NA or closest price
#' (see input do_fill_missing_prices). Default = FALSE.
#' @param do_cache Use cache system? (default = TRUE)
#' @param cache_folder Where to save cache files?
#' (default = yfR::yf_cachefolder_get() )
#' @param do_parallel Flag for using parallel or not (default = FALSE).
#' Before using parallel, make sure you call function future::plan() first.
#' See <https://furrr.futureverse.org/> for more details.
#' @param be_quiet Flag for not printing statements (default = FALSE)
#'
#' @return A dataframe with the financial data for working days, when markets
#' are open. All price data is \strong{measured} at the unit of the financial
#' exchange. For example, price
#' data for META (NYSE/US) is measures in dollars, while price data for
#' PETR3.SA (B3/BR) is measured in Reais (Brazilian currency).
#'
#' The return dataframe contains the following columns:
#'
#' \describe{
#' \item{ticker}{The requested tickers (ids of stocks)}
#' \item{ref_date}{The reference day (this can also be year/month/week when
#' using argument freq_data)}
#' \item{price_open}{The opening price of the day/period}
#' \item{price_high}{The highest price of the day/period}
#' \item{price_close}{The close/last price of the day/period}
#' \item{volume}{The financial volume of the day/period}
#' \item{price_adjusted}{The stock price adjusted for corporate events such
#' as splits, dividends and others -- this is usually what you want/need for
#' studying stocks as it represents the actual financial performance of
#' stockholders}
#' \item{ret_adjusted_prices}{The arithmetic or log return (see input type_return) for
#' the adjusted stock prices}
#' \item{ret_adjusted_prices}{The arithmetic or log return (see input type_return) for
#' the closing stock prices}
#' \item{cumret_adjusted_prices}{The accumulated arithmetic/log return for the period (starts at 100\%)}
#' }
#'
#' @export
#'
#' @examples
#'
#' \donttest{
#' tickers <- c("TSLA", "MMM")
#'
#' first_date <- Sys.Date() - 30
#' last_date <- Sys.Date()
#'
#' df_yf <- yf_get(
#' tickers = tickers,
#' first_date = first_date,
#' last_date = last_date
#' )
#'
#' print(df_yf)
#' }
yf_get <- function(tickers,
first_date = Sys.Date() - 30,
last_date = Sys.Date(),
thresh_bad_data = 0.75,
bench_ticker = "^GSPC",
type_return = "arit",
freq_data = "daily",
how_to_aggregate = "last",
do_complete_data = FALSE,
do_cache = TRUE,
cache_folder = yf_cachefolder_get(),
do_parallel = FALSE,
be_quiet = FALSE) {
# check for internet
if (!pingr::is_online()) {
stop("Can't find an active internet connection...")
}
# check cache folder
if ((do_cache) & (!dir.exists(cache_folder))) dir.create(cache_folder,
recursive = TRUE)
# check options
possible_values <- c("arit", "log")
if (!any(type_return %in% possible_values)) {
stop(paste0("Input type.ret should be one of:\n\n",
paste0(possible_values,
collapse = "\n")
)
)
}
possible_values <- c("first", "last")
if (!any(how_to_aggregate %in% possible_values)) {
stop(paste0("Input how_to_aggregate should be one of:\n\n",
paste0(possible_values, collapse = "\n")))
}
# check for NA
if (any(is.na(tickers))) {
my_msg <- paste0(
"Found NA value in ticker vector.",
"You need to remove it before running yfR::yf_get()."
)
stop(my_msg)
}
possible_values <- c("daily", "weekly", "monthly", "yearly")
if (!any(freq_data %in% possible_values)) {
stop(paste0("Input freq_data should be one of:\n\n",
paste0(possible_values, collapse = "\n")))
}
# check date class
first_date <- as.Date(first_date)
last_date <- as.Date(last_date)
if (!methods::is(first_date, "Date")) {
stop("can't change class of first_date to 'Date'")
}
if (!methods::is(last_date, "Date")) {
stop("can't change class of last_date to 'Date'")
}
if (last_date <= first_date) {
stop(paste0("The last_date is lower (less recent) or equal to first_date.",
" Please check your dates!"))
}
# check tickers
if (!is.null(tickers)) {
tickers <- as.character(tickers)
if (!methods::is(tickers, "character")) {
stop("The input tickers should be a character object.")
}
}
# sort tickers (makes sure acum ret is correct)
tickers <- sort(tickers)
# check threshold
if ((thresh_bad_data < 0) | (thresh_bad_data > 1)) {
stop("Input thresh_bad_data should be a proportion between 0 and 1")
}
# disable dplyr group message and respect user choice
# will be null if options is not set
default_dplyr_summ <- options("dplyr.summarise.inform")[[1]]
# disable and enable at end with on exit
options(dplyr.summarise.inform = FALSE)
on.exit({
if (is.logical(default_dplyr_summ)) {
options(dplyr.summarise.inform = default_dplyr_summ)
}
})
# check if using do_parallel = TRUE
# 20220501 Yahoo finance started setting limits to api calls, which
# invalidates the use of any parallel computation
if (do_parallel) {
my_message <- stringr::str_glue(
"Since 2022-04-25, Yahoo Finance started to set limits to api calls, ",
"resulting in 401 errors. When using parallel computations for fetching ",
"data, the limit is reached easily. Said that, the parallel option is now",
" disabled by default. Please set do_parallel = FALSE to use this function.",
"\n\n",
"Returning empty dataframe.")
cli::cli_alert_danger(my_message)
return(data.frame())
}
# first screen msgs
if (!be_quiet) {
days_diff <- as.numeric(last_date - first_date)
# cli::cli_h1('yfR -- Yahoo Finance for R')
my_msg <- paste0(
"\nRunning yfR for {length(tickers)} stocks | ",
"{as.character(first_date)} --> ",
"{as.character(last_date)} ({days_diff} days)"
)
cli::cli_h2(my_msg)
my_msg <- set_cli_msg(
"Downloading data for benchmark ticker {bench_ticker}",
level = 0
)
cli::cli_alert_info(my_msg)
}
# get benchmark ticker data
df_bench <- yf_data_single(
ticker = bench_ticker,
i_ticker = 1,
length_tickers = 1,
first_date = first_date,
last_date = last_date,
do_cache = do_cache,
cache_folder = cache_folder,
be_quiet = TRUE
)
# run fetching function for all tickers
l_args <- list(
ticker = tickers,
i_ticker = seq_along(tickers),
length_tickers = length(tickers),
first_date = first_date,
last_date = last_date,
do_cache = do_cache,
cache_folder = cache_folder,
df_bench = rep(list(df_bench), length(tickers)),
thresh_bad_data = thresh_bad_data,
be_quiet = be_quiet
)
if (!do_parallel) {
my_l <- purrr::pmap(
.l = l_args,
.f = yf_data_single
)
} else {
# available cores in R session
available_cores <- future::availableCores()
used_cores <- future::nbrOfWorkers()
if (!be_quiet) {
cli::cli_h3(
'Running yfR with parallel backend (using {used_cores} of {available_cores} available cores)')
}
# test if plan() was called
msg <- utils::capture.output(future::plan())
# "sequential is the default plan
flag <- stringr::str_detect(msg[1], "sequential")
if (flag) {
stop(paste0(
"When using do_parallel = TRUE, you need to call future::plan() to ',
configure your parallel settings. \n",
"A suggestion, write the following lines:\n\n",
"future::plan(future::multisession, ",
"workers = floor(parallel::detectCores()/2))",
"\n\n",
"The last line should be placed just before calling get_yf_data. ",
"Notice it will use half of your available cores so that your OS has ",
"some room to breathe."
))
}
my_l <- furrr::future_pmap(
.l = l_args,
.f = yf_data_single,
.progress = TRUE,
# fixes warnings about seed
.options = furrr::furrr_options(seed = TRUE)
)
}
# remove any element that is not a list
l_classes <- purrr::map_chr(my_l, class)
idx <- l_classes != "list"
my_l[idx] <- NULL
if (!be_quiet) cli::cli_alert_info('Binding price data')
df_tickers <- dplyr::bind_rows(purrr::map(my_l, 1))
df_control <- dplyr::bind_rows(purrr::map(my_l, 2))
# make sure data is in the output
if (nrow(df_tickers) == 0) {
stop(
paste0(
"Resulting data has 0 rows.. Are your tickers and date ranges correct?",
" Search your ticker at <https://finance.yahoo.com/>."
)
)
}
# remove tickers with bad data
tickers_to_keep <- df_control$ticker[df_control$threshold_decision == "KEEP"]
idx <- df_tickers$ticker %in% tickers_to_keep
df_tickers <- df_tickers[idx, ]
# do data manipulations
if (do_complete_data) {
cli::cli_alert_info("\nCompleting data points (do_complete_data = TRUE)")
# makes sure each data point is ticker/ref_date is available in output
# missing are set as NA
df_tickers <- df_tickers %>%
dplyr::group_by(ticker, ref_date) %>%
tidyr::complete()
}
# change frequency of data
if (freq_data != "daily") {
str_freq <- switch(freq_data,
"weekly" = "1 week",
"monthly" = "1 month",
"yearly" = "1 year"
)
# find the first monday (see issue #19 in BatchGetsymbols)
# https://github.com/msperlin/BatchGetSymbols/issues/19
min_year <- as.Date(paste0(
lubridate::year(min(df_tickers$ref_date)),
"-01-01"
)
)
max_year <- as.Date(paste0(
lubridate::year(max(df_tickers$ref_date)) + 1,
"-12-31"
)
)
temp_dates <- seq(min_year, max_year,
by = "1 day"
)
temp_weekdays <- lubridate::wday(temp_dates, week_start = 1)
first_idx <- min(which(temp_weekdays == 1))
first_monday <- temp_dates[first_idx]
if (freq_data == "weekly") {
# make sure it starts on a monday
week_vec <- seq(first_monday,
as.Date(paste0(
lubridate::year(max(df_tickers$ref_date)) + 1, "-12-31")
),
by = str_freq
)
} else {
# every other case
week_vec <- seq(as.Date(paste0(
lubridate::year(min(df_tickers$ref_date)), "-01-01")
),
as.Date(paste0(
lubridate::year(max(df_tickers$ref_date)) + 1, "-12-31")
),
by = str_freq
)
}
df_tickers$time_groups <- cut(
x = df_tickers$ref_date,
breaks = week_vec,
right = FALSE
)
if (how_to_aggregate == "first") {
df_tickers <- df_tickers %>%
dplyr::group_by(time_groups, ticker) %>%
dplyr::summarise(
ref_date = min(ref_date),
price_open = dplyr::first(price_open),
price_high = max(price_high),
price_low = min(price_low),
price_close = dplyr::first(price_close),
price_adjusted = dplyr::first(price_adjusted),
volume = sum(volume, na.rm = TRUE)
) %>%
dplyr::ungroup() %>%
dplyr::arrange(ticker, ref_date)
} else if (how_to_aggregate == "last") {
df_tickers <- df_tickers %>%
dplyr::group_by(time_groups, ticker) %>%
dplyr::summarise(
ref_date = min(ref_date),
volume = sum(volume, na.rm = TRUE),
price_open = dplyr::last(price_open),
price_high = max(price_high),
price_low = min(price_low),
price_close = dplyr::last(price_close),
price_adjusted = dplyr::last(price_adjusted)
) %>%
dplyr::ungroup() %>%
dplyr::arrange(ticker, ref_date)
}
df_tickers$time_groups <- NULL
}
# calculate returns
df_tickers$ret_adjusted_prices <- calc_ret(
df_tickers$price_adjusted,
df_tickers$ticker,
type_return
)
df_tickers$ret_closing_prices <- calc_ret(
df_tickers$price_close,
df_tickers$ticker,
type_return
)
# calculate acumulated returns
df_tickers$cumret_adjusted_prices <- calc_cum_ret(
df_tickers$ret_adjusted_prices,
df_tickers$ticker,
type_return
)
# fix for issue with repeated rows (see git issue 16)
# https://github.com/msperlin/BatchGetSymbols/issues/16
df_tickers <- unique(df_tickers)
# remove rownames from output (see git issue #18)
# https://github.com/msperlin/BatchGetSymbols/issues/18
rownames(df_tickers) <- NULL
my_l <- list(
df_control = df_control,
df_tickers = df_tickers
)
# check if cache folder is tempdir()
flag <- stringr::str_detect(cache_folder,
pattern = stringr::fixed(tempdir())
)
if (!flag) {
warning(stringr::str_glue(
"\nIt seems you are using a non-default cache folder at {cache_folder}. ",
"Be aware that, for individual stocks, yfR **does not** garantee price integrity ",
"in between days. Some stock events adjust prices recursively, meaning that one ",
"can have a different adjusted price for queries executed in different days. ",
"For safety and reproducibility, my suggestion ",
"is to use the default cache_folder at tempdir(). ",
"\n\n",
"This issue only affects individual stocks. For market indices, such as SP500,",
" I dont expect any problem in having a persistent cache folder, outside .",
"of tempdir()."
))
}
# check number of rows of requested data
# setup final output (ungrouped tibble)
df_out <- df_tickers %>%
dplyr::ungroup()
attributes(df_out)$df_control <- df_control
# last message -- Diagnostics
if (!be_quiet) {
cli::cli_h1("Diagnostics")
n_requested <- length(tickers)
n_got <- dplyr::n_distinct(df_out$ticker)
this_morale <- get_morale_boost()
cli::cli_alert_success(
paste0(
"Returned dataframe with {nrow(df_out)} rows",
" -- {this_morale}"
)
)
# check cache size
if (do_cache) {
cache_files <- list.files(cache_folder, full.names = TRUE)
size_files <- sum(sapply(cache_files, file.size))
size_str <- humanize::natural_size(size_files)
n_files <- length(list.files(cache_folder))
cli::cli_alert_info("Using {size_str} at {cache_folder} for {n_files} cache files")
}
success_rate <- n_got/n_requested
cli::cli_alert_info(
paste0("Out of {n_requested} requested tickers, you got {n_got}",
" ({scales::percent(success_rate)})")
)
if (success_rate < 0.75) {
extra_msg <- paste0(
"You either inputed wrong tickers, or ranned into YF call limit? My advice:",
" check your input tickers, wait 15 minutes and try again."
)
cli::cli_alert_danger(
paste0(
'You got data on less than {scales::percent(0.75)} of requested tickers. ',
"{extra_msg}"
)
)
idx <- !tickers %in% unique(df_tickers$ticker)
missing_tickers <- tickers[idx]
cli::cli_alert_info(
paste0("Missing tickers: ",
paste0(missing_tickers, collapse = ", "))
)
}
}
return(df_out)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_get.R |
#' Get Yahoo Finance Dividends from a single stock
#'
#' This function will use the json api to retrieve dividends from Yahoo finance.
#'
#' @param ticker a single ticker symbol
#' @param first_date The first date of query (Date or character as YYYY-MM-DD)
#' @param last_date The last date of query (Date or character as YYYY-MM-DD)
#'
#' @return a tibble with dividends
#' @export
#'
#' @examples
#' yf_get_dividends(ticker = "PETR4.SA")
#'
yf_get_dividends <- function(ticker,
first_date = Sys.Date() - 365,
last_date = Sys.Date()) {
cli::cli_alert_info(
paste0("Be aware that YF does not provide a consistent dividend database.",
" Use this function with caution.")
)
if (length(ticker) > 1) {
cli::cli_abort("input ticker should have only one symbol (found >1)")
}
# check for internet
if (!pingr::is_online()) {
stop("Can't find an active internet connection...")
}
first_date <- base::as.Date(first_date)
last_date <- base::as.Date(last_date)
if (!methods::is(first_date, "Date")) {
stop("can't change class of first_date to 'Date'")
}
if (!methods::is(last_date, "Date")) {
stop("can't change class of last_date to 'Date'")
}
first_date_number <- base::as.numeric(
lubridate::as_datetime(first_date,
tz = "America/Sao_Paulo"
)
)
last_date_number <- base::as.numeric(
lubridate::as_datetime(last_date,
tz = "America/Sao_Paulo")
)
link <- glue::glue("https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?formatted=true&crumb=DUrcw6zrjLP&lang=en-US®ion=US&includeAdjustedClose=true&interval=1d&period1={first_date_number}&period2={last_date_number}&events=capitalGain%7Cdiv%7Csplit&useYfid=true&corsDomain=finance.yahoo.com")
dividends <- tibble::tibble()
dividends <- try({
httr::RETRY(verb = "GET",url = link,) %>%
httr::content("text") %>%
jsonlite::fromJSON() %>%
purrr::pluck("chart", "result", "events", "dividends")
})
if(base::is.null(dividends)){
cli::cli_abort("Can't find ticker {ticker} or don\u00B4t have dividends..")
} else if (base::nrow(dividends) == 0) {
cli::cli_abort("Can't find ticker {ticker} or don\u00B4t have dividends..")
} else {
dividends <- dividends %>%
purrr::map_dfr(
.f = ~{.x}) %>%
dplyr::as_tibble() %>%
dplyr::mutate(
date = base::as.POSIXct(date, origin = "1970-01-01"),
date = base::as.Date(date),
ticker = stringr::str_to_upper(string = ticker)
) %>%
dplyr::select(
ref_date = date,
ticker,
dividend = amount
)
}
return(dividends)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_get_dividends.R |
#' Get current composition of stock indices
#'
#' @param mkt_index the index (e.g. IBOV, SP500, FTSE)
#' @inheritParams yf_get
#' @param force_fallback Logical (TRUE/FALSE). Forces the function to use the
#' fallback system
#'
#' @return A dataframe with the index composition (column might vary)
#' @export
#'
#' @examples
#' df_sp500 <- yf_index_composition("SP500")
yf_index_composition <- function(mkt_index,
do_cache = TRUE,
cache_folder = yf_cachefolder_get(),
force_fallback = FALSE) {
available_indices <- yf_index_list()
if (!any(mkt_index %in% available_indices)) {
stop(stringr::str_glue(
"Index {mkt_index} is no available within the options: ",
' {paste0(available_indices, collapse = ", ")}'
))
}
if (force_fallback) {
df_index <- read_fallback(mkt_index)
return(df_index)
}
df_index <- data.frame()
try({
if (mkt_index == "IBOV") {
df_index <- yf_index_ibov(
do_cache = do_cache,
cache_folder = cache_folder,
max_tries = 10
)
} else if (mkt_index == "SP500") {
df_index <- yf_index_sp500()
} else if (mkt_index == "FTSE") {
df_index <- yf_index_ftse()
} else if (mkt_index == "DOW") {
df_index <- yf_index_dow()
} else if (mkt_index == "testthat-collection") {
df_index <- yf_index_test()
}
})
if (nrow(df_index) == 0) {
cli::cli_alert_info("Failed to import current composition for {mkt_index}. Using fallback index")
df_index <- read_fallback(mkt_index)
}
# fix tickers manually (isse #18)
df_index <- substitute_tickers(df_index)
return(df_index)
}
#' Read fallback/static market indices composition from package
#'
#' @noRd
read_fallback <- function(mkt_index) {
this_fallback_file <- system.file(
stringr::str_glue("extdata/fallback-indices/{mkt_index}.rds"),
package = "yfR"
)
df_index <- readr::read_rds(this_fallback_file)
fallback_date <- df_index$fetched_at[1]
cli::cli_alert_success(
"Using fallback {mkt_index} composition from {fallback_date}"
)
return(df_index)
}
#' Get available indices in package
#'
#' This function will return all available market indices that are registered
#' in the package.
#'
#' @param print_description Logical (TRUE/FALSE) - flag for printing description of
#' available indices/collections
#'
#' @return A vector of mkt indices
#' @export
#'
#' @examples
#'
#' indices <- yf_index_list()
#' indices
yf_index_list <- function(print_description = FALSE) {
available_indices <- c("SP500", "IBOV", "FTSE",
"DOW",
"testthat-collection")
df_indices <- dplyr::tibble(
available_indices,
description = c(
"The SP500 index (US MARKET) - Ticker = ^GSPC",
"The Ibovespa index (BR MARKET) - Ticker = ^BVSP",
"The FTSE index (UK MARKET) - Ticker = ^FTSE",
"The DOW index (US MARKET) - Ticker = ^DJI",
"A (small) testing index for testthat() -- dev stuff, dont use it!"
)
)
if (print_description) {
cli::cli_h2("Description of Available Collections")
for (i_row in 1:nrow(df_indices)) {
cli::cli_alert_info(
"{df_indices$available_indices[i_row]}: {df_indices$description[i_row]}"
)
}
}
return(invisible(available_indices))
}
#' Function to download the current components of the
#' FTSE100 index from Wikipedia
#' @noRd
yf_index_ftse <- function(do_cache = TRUE,
cache_folder = yf_cachefolder_get()) {
cache_file <- file.path(
cache_folder,
paste0("yf_ftse100_Composition_", Sys.Date(), ".rds")
)
if (do_cache) {
# check if file exists
flag <- file.exists(cache_file)
if (flag) {
df_ftse <- readr::read_rds(cache_file)
return(df_ftse)
}
}
my_url <- "https://en.wikipedia.org/wiki/FTSE_100_Index"
my_xpath <- '//*[@id="mw-content-text"]/div/table[2]' # old xpath
my_xpath <- '//*[@id="constituents"]'
df_ftse <- my_url %>%
rvest::read_html() %>%
rvest::html_nodes(xpath = my_xpath) %>%
rvest::html_table()
df_ftse <- df_ftse[[1]]
df_ftse <- df_ftse %>%
dplyr::rename(
ticker = Ticker,
company = Company,
sector = names(df_ftse)[3]
) %>%
dplyr::mutate(
index = "FTSE",
index_ticker = "^FTSE"
)
if (do_cache) {
if (!dir.exists(cache_folder)) dir.create(cache_folder)
readr::write_rds(df_ftse, cache_file)
}
yf_index_format_msg("FTSE", nrow(df_ftse))
return(df_ftse)
}
#' Function to download the current components of the
#' Ibovespa index from B3 website
#' @noRd
yf_index_ibov <- function(do_cache = TRUE,
cache_folder = yf_cachefolder_get(),
max_tries = 10) {
cache_file <- file.path(
cache_folder,
paste0("Ibov_Composition_", Sys.Date(), ".rds")
)
# get list of ibovespa's tickers from wbsite
if (do_cache) {
# check if file exists
flag <- file.exists(cache_file)
if (flag) {
df_ibov_comp <- readr::read_rds(cache_file)
return(df_ibov_comp)
}
}
for (i_try in seq(max_tries)) {
my_url <- 'https://en.wikipedia.org/wiki/List_of_companies_listed_on_B3'
df_ibov_comp <- rvest::read_html(my_url) %>%
rvest::html_table()
df_ibov_comp <- df_ibov_comp[[1]]
Sys.sleep(0.5)
if (nrow(df_ibov_comp) > 0) break()
}
df_ibov_comp <- df_ibov_comp %>%
dplyr::rename(ticker = Ticker,
company = Company,
industry = Industry) %>%
dplyr::mutate(type_stock = NA,
quantity = NA,
percentage_participation = NA,
ref_date = Sys.Date(),
index = "IBOV",
index_ticker = "^BVSP") %>%
dplyr::select(-Headquarters)
if (do_cache) {
if (!dir.exists(cache_folder)) dir.create(cache_folder)
readr::write_rds(df_ibov_comp, cache_file)
}
yf_index_format_msg("IBOV", nrow(df_ibov_comp))
return(df_ibov_comp)
}
#' Function for fetching test tickers
#' @noRd
yf_index_test <- function(do_cache = TRUE,
cache_folder = yf_cachefolder_get()) {
df_test <- dplyr::tibble(
ticker = c("^GSPC", "^FTSE"),
index_ticker = "^GSPC" # simply keep it there for placeholder
)
return(df_test)
}
#' Function to download the current components of the SP500 index from Wikipedia
#' @noRd
yf_index_sp500 <- function(do_cache = TRUE,
cache_folder = yf_cachefolder_get()) {
cache_file <- file.path(
cache_folder,
paste0("SP500_Composition_", Sys.Date(), ".rds")
)
if (do_cache) {
# check if file exists
flag <- file.exists(cache_file)
if (flag) {
df_sp500 <- readr::read_rds(cache_file)
return(df_sp500)
}
}
my_url <- "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
read_html <- 0 # fix for global variable nagging from BUILD
my_xpath <- '//*[@id="constituents"]'
df_sp500 <- my_url %>%
rvest::read_html() %>%
rvest::html_nodes(xpath = my_xpath) %>%
rvest::html_table(fill = TRUE)
df_sp500 <- df_sp500[[1]]
df_sp500 <- df_sp500 %>%
dplyr::rename(
ticker = Symbol,
company = Security,
sector = `GICS Sector`
) %>%
dplyr::select(ticker, company, sector) %>%
dplyr::mutate(
index = "SP500",
index_ticker = "^GSPC"
)
if (do_cache) {
if (!dir.exists(cache_folder)) dir.create(cache_folder)
readr::write_rds(df_sp500, cache_file)
}
yf_index_format_msg("SP500", nrow(df_sp500))
return(df_sp500)
}
#' Function to download the current components of the dOW index from Wikipedia
#' @noRd
yf_index_dow <- function(do_cache = TRUE,
cache_folder = yf_cachefolder_get()) {
cache_file <- file.path(
cache_folder,
paste0("DOW30_Composition_", Sys.Date(), ".rds")
)
if (do_cache) {
# check if file exists
flag <- file.exists(cache_file)
if (flag) {
df_dow <- readr::read_rds(cache_file)
return(df_dow)
}
}
my_url <- "https://en.wikipedia.org/wiki/Dow_Jones_Industrial_Average#Components"
read_html <- 0 # fix for global variable nagging from BUILD
my_xpath <- '//*[@id="constituents"]'
df_dow <- my_url %>%
rvest::read_html() %>%
rvest::html_nodes(xpath = my_xpath) %>%
rvest::html_table(fill = TRUE)
df_dow <- df_dow[[1]]
df_dow <- df_dow %>%
dplyr::rename(
ticker = Symbol,
company = Company,
sector = Industry
) %>%
dplyr::select(ticker, company, sector) %>%
dplyr::mutate(
index = "DOW",
index_ticker = "^DJI"
)
if (do_cache) {
if (!dir.exists(cache_folder)) dir.create(cache_folder)
readr::write_rds(df_dow, cache_file)
}
yf_index_format_msg("DOW", nrow(df_dow))
return(df_dow)
}
#' Builds index message
#' @noRd
yf_index_format_msg <- function(index_in, my_n) {
cli::cli_alert_success("Got {index_in} composition with {my_n} rows")
return(invisible(TRUE))
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_get_index_components.R |
#' function to import a single ticker
#' @noRd
yf_data_single <- function(ticker,
i_ticker,
length_tickers,
first_date,
last_date,
do_cache = TRUE,
cache_folder = yf_cachefolder_get(),
df_bench = NULL,
be_quiet = FALSE,
thresh_bad_data) {
if (!be_quiet) {
my_msg <- set_cli_msg("({i_ticker}/{length_tickers}) Fetching data for {ticker}")
cli::cli_alert_info(my_msg)
}
# do cache
if (do_cache) {
# check if data is in cache files
my_cache_files <- list.files(cache_folder, full.names = TRUE)
if (length(my_cache_files) > 0) {
l_out <- stringr::str_split(
tools::file_path_sans_ext(basename(my_cache_files)),
"_"
)
df_cache_files <- dplyr::tibble(
filename = my_cache_files,
ticker = purrr::map_chr(l_out, function(x) x[1]),
first_date = as.Date(purrr::map_chr(l_out, function(x) x[3])),
last_date = as.Date(purrr::map_chr(l_out, function(x) x[4]))
)
} else {
# empty df
df_cache_files <- dplyr::tibble(
filename = "",
ticker = "",
first_date = first_date,
last_date = last_date
)
}
# check dates
fixed_ticker <- fix_ticker_name(ticker)
temp_cache <- dplyr::filter(
df_cache_files,
ticker == fixed_ticker
)
if (nrow(temp_cache) > 1) {
my_msg <- paste0(
"Found more than one file in cache for ", ticker,
"\nYou must manually remove one of \n\n",
paste0(temp_cache$filename,
collapse = "\n")
)
stop(my_msg)
stop()
}
if (nrow(temp_cache) != 0) {
flag_dates <- TRUE
df_cache <- readr::read_rds(temp_cache$filename)
if (!be_quiet) {
this_fd <- as.character(min(df_cache$ref_date))
this_ld <- as.character(max(df_cache$ref_date))
my_msg <- set_cli_msg("found cache file ({this_fd} --> {this_ld})",
level = 1
)
cli::cli_alert_success(my_msg)
}
# check if data matches
max_diff_dates <- 0
flag_dates <- ((first_date - temp_cache$first_date) < -max_diff_dates) |
((last_date - temp_cache$last_date) > max_diff_dates)
df_out <- data.frame()
if (flag_dates) {
if (!be_quiet) {
my_msg <- set_cli_msg("need new data (cache doesnt match query)",
level = 1
)
cli::cli_alert_warning(my_msg)
}
flag_date_bef <- ((first_date - temp_cache$first_date) <
-max_diff_dates)
df_out_bef <- data.frame()
if (flag_date_bef) {
df_out_bef <- yf_data_get_raw(
ticker,
first_date,
temp_cache$first_date
)
}
flag_date_aft <- ((last_date - temp_cache$last_date) > max_diff_dates)
df_out_aft <- data.frame()
if (flag_date_aft) {
df_out_aft <- yf_data_get_raw(
ticker,
temp_cache$last_date,
last_date
)
}
df_out <- rbind(df_out_bef, df_out_aft)
}
# merge with cache
df_out <- unique(rbind(df_cache, df_out))
# sort it
if (nrow(df_out) > 0) {
idx <- order(df_out$ticker, df_out$ref_date)
df_out <- df_out[idx, ]
}
# remove old file
file.remove(temp_cache$filename)
my_f_out <- paste0(
fixed_ticker, "_",
"yfR_",
min(c(temp_cache$first_date, first_date)), "_",
max(c(temp_cache$last_date, last_date)), ".rds"
)
readr::write_rds(df_out, file.path(cache_folder, my_f_out))
# filter for dates
ref_date <- NULL
df_out <- dplyr::filter(
df_out,
ref_date >= first_date,
ref_date <= last_date
)
} else {
if (!be_quiet) {
my_msg <- set_cli_msg("not cached",
level = 1
)
cli::cli_alert_warning(my_msg)
}
my_f_out <- paste0(
fixed_ticker, "_",
"yfR_",
first_date, "_",
last_date, ".rds"
)
df_out <- yf_data_get_raw(
ticker,
first_date,
last_date
)
# only saves if there is data
if (nrow(df_out) > 1) {
if (!be_quiet) {
my_msg <- set_cli_msg("cache saved successfully",
level = 1
)
cli::cli_alert_success(my_msg)
}
readr::write_rds(df_out, file = file.path(cache_folder, my_f_out))
}
}
} else {
df_out <- yf_data_get_raw(
ticker,
first_date,
last_date
)
}
# control for ERROR in download
if (nrow(df_out) == 0) {
dl_status <- "NOT OK"
n_rows <- 0
perc_benchmark_dates <- 0
threshold_decision <- "OUT"
df_out <- data.frame()
if (!be_quiet) {
my_msg <- set_cli_msg("error in download..",
level = 1
)
cli::cli_alert_danger(my_msg)
}
} else {
# control for returning data when importing bench ticker
if (is.null(df_bench)) {
return(df_out)
}
dl_status <- "OK"
n_rows <- nrow(df_out)
perc_benchmark_dates <- sum(df_out$ref_date %in% df_bench$ref_date) /
length(df_bench$ref_date)
if (perc_benchmark_dates >= thresh_bad_data) {
threshold_decision <- "KEEP"
} else {
threshold_decision <- "OUT"
}
# a morale boost phrase
morale_boost <- get_morale_boost()
if (!be_quiet) {
if (threshold_decision == "KEEP") {
this_fd <- as.character(min(df_out$ref_date))
this_ld <- as.character(max(df_out$ref_date))
my_msg <- set_cli_msg(
"got {nrow(df_out)} valid rows ({this_fd} --> {this_ld})",
level = 1
)
cli::cli_alert_success(my_msg)
my_msg <- set_cli_msg(paste0(
"got {scales::percent(perc_benchmark_dates)} ",
"of valid prices -- {morale_boost}"
),
level = 1
)
cli::cli_alert_success(my_msg)
} else {
my_msg <- set_cli_msg(paste0(
"**REMOVED** found only {scales::percent(perc_benchmark_dates)} of ",
"valid prices (thresh_bad_data = {scales::percent(thresh_bad_data)})"
),
level = 1
)
cli::cli_alert_danger(my_msg)
}
}
df_control <- tibble::tibble(
ticker = ticker,
dl_status,
n_rows,
perc_benchmark_dates,
threshold_decision
)
l_out <- list(df_tickers = df_out,
df_control = df_control)
# check if returned dataframe only has one row
if (nrow(df_out) == 1) {
cli::cli_warn(
paste0(
"Returned dataframe for {ticker} between {first_date} and {last_date} has only ONE row. ",
" Perhaps you should check your inputs dates?")
)
}
return(l_out)
}
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_get_single_ticker.R |
#' Yahoo Finance Live Prices
#'
#' This function will use the json api to retrieve live prices from Yahoo finance.
#'
#' @param ticker a single ticker symbol
#'
#' @return a tibble with live prices
#' @export
#'
#' @examples
#' yfR::yf_live_prices("PETR4.SA")
#'
yf_live_prices <- function(ticker){
if (length(ticker) > 1) {
cli::cli_abort("input ticker should have only one symbol (found >1)")
}
url <- glue::glue("https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?region=US&lang=pt-BR&includePrePost=false&interval=1m&useYfid=true&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance")
df_prices <- tibble::tibble()
try({
df_prices <- httr::GET(url) %>%
httr::content("text") %>%
jsonlite::fromJSON() %>%
purrr::pluck("chart","result") %>%
dplyr::select(meta) %>%
tidyr::unnest(meta) %>%
dplyr::select(
ticker = symbol,
time_stamp = regularMarketTime,
price = regularMarketPrice,
last_price = previousClose) %>%
dplyr::mutate(daily_change = (price - last_price)/last_price) %>%
dplyr::mutate(time_stamp = (as.POSIXct(time_stamp, origin="1970-01-01")))
})
if (nrow(df_prices) == 0) {
cli::cli_abort("Can't find ticker {ticker}..")
}
return(df_prices)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_live_price.R |
#' Fix name of ticker
#' @noRd
fix_ticker_name <- function(ticker_in) {
ticker_in <- stringr::str_replace_all(ticker_in, stringr::fixed("."), "")
ticker_in <- stringr::str_replace_all(ticker_in, stringr::fixed("^"), "")
return(ticker_in)
}
#' returns a morale phrase (used in cli messages)
#' @noRd
get_morale_boost <- function() {
my_user <- Sys.getenv("USER")
morale_boost <- c(
rep(c(
"All OK!",
"Time for some tea?",
"Got it!", "Nice!", "Good stuff!",
"Looking good!", "Good job {my_user}!",
"Well done {my_user}!",
"You got it {my_user}!", "Youre doing good!"
), 10),
"Boa!", "Mas bah tche, que coisa linda!",
"Parabens {my_user}, tudo certo!",
"Mais contente que cusco de cozinheira!",
"Feliz que nem lambari de sanga!",
"Mais faceiro que guri de bombacha nova!"
)
return(stringr::str_glue(sample(morale_boost, 1)))
}
#' Converts string date to unix date (used in yf query)
#' @noRd
date_to_unix <- function(date_in) {
out <- as.numeric(
as.POSIXct(as.Date(date_in,
origin = "1970-01-01"
))
)
return(out)
}
#' Converses unix date to string date
#' @noRd
unix_to_date <- function(unix_date_in) {
out <- as.Date(as.POSIXct(unix_date_in, origin="1970-01-01"))
return(out)
}
#' Function to calculate returns from a price and ticker vector
#' @noRd
calc_ret <- function(P,
tickers = rep("ticker", length(P)),
type_return = "arit") {
my_length <- length(P)
if (my_length == 1) {
return(NA)
}
ret <- switch(type_return,
"arit" = P / dplyr::lag(P) - 1,
"log" = log(P / dplyr::lag(P))
)
idx <- (tickers != dplyr::lag(tickers))
ret[idx] <- NA
return(ret)
}
#' Function to calculate accumulated returns from a price and ticker vector
#' @noRd
calc_cum_ret <- function(ret,
tickers = rep("ticker", length(ret)),
type_return = "arit") {
# replace all NAs by 0
idx <- is.na(ret)
ret[idx] <- 0
l_ret <- split(ret, tickers)
calc_cum <- function(x, type_return) {
this_cum_ret <- switch(type_return,
"arit" = cumprod(1 + x),
"log" = 1 + cumsum(x))
return(this_cum_ret)
}
l_cum_ret <- purrr::map(l_ret,
calc_cum,
type_return = type_return)
cum_ret <- do.call(c, l_cum_ret)
names(cum_ret) <- NULL
return(cum_ret)
}
# 20220328 - removed startup message due to ropensci practices
# https://devguide.ropensci.org/building.html
# .onAttach <- function(libname, pkgname) {
# do_color <- crayon::make_style("#FF4141")
# this_pkg <- "yfR"
#
# if (interactive()) {
# msg <- paste0(
# "\nWant to learn more about ",
# do_color(this_pkg), " (formerly BatchGetSymbols) and other R packages",
# "for Finance and Economics?",
# " Check out my book at ", do_color("https://www.msperlin.com/afedR/")
# )
# } else {
# msg <- ""
# }
#
# packageStartupMessage(msg)
# }
#' Function for building cli messages
#' @noRd
set_cli_msg <- function(msg_in, level = 0) {
tab_in <- paste0(rep("\t", level), collapse = "")
if (level == 1) {
tab_in <- paste0(tab_in, "- ")
}
msg_in <- paste0(tab_in, msg_in)
return(msg_in)
}
#' Fixes ticker manually
#'
#' This function will be used as a dictionary to fix wrong tickers from index compositions
#'
#' @param df_index
#'
#' @return Another dataframe
#'
#' @noRd
substitute_tickers <- function(df_index) {
df_fix <- dplyr::tibble(
old = c("BF.B"),
new = c("BF-B")
)
idx <- match(df_fix$old, df_index$ticker)
df_index$ticker[idx] <- df_fix$new
return(df_index)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/R/yf_utils.R |
---
title: "yfR and BatchGetSymbols"
author: "Marcelo Perlin"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{yfR and BatchGetSymbols}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Differences from [BatchGetSymbols](https://github.com/msperlin/BatchGetSymbols)
Package `BatchgetSymbols` was developed back in 2016, with many bad structural choices from my part. Since then, I learned more about R and its ecosystem, resulting in better and more maintainable code. However, it is impossible to keep compatibility with the changes I wanted to make, which is why I decided to develop a new (and fresh) package.
Here are the main differences between `yfR` (new) and `BatchGetSymbols` (old):
- All input arguments are now formatted as "snake_case" and not "dot.case". For example, the argument for the first date of data importation in `yfR::yf_get()` is `first_date`, and not `first.date`, as used in `BatchGetSymbols::BatchGetSymbols`.
- A new feature called "collection", which allows for easy download of a collection of tickers. For example, you can download price data for all components of the SP500 by simply calling `yfR::yf_collection_get("SP500")`.
- All function have been renamed for a common API notation. For example, `BatchGetSymbols::BatchGetSymbols` is now `yfR::yf_get()`. Likewise, the function for fetching collections is `yfR::yf_collection_get()`.
- The output of `yfR::yf_get()` is always a tibble with the price data (and not a list as in `BatchGetSymbols::BatchGetSymbols`). If one wants the tibble with a summary of the importing process, it is available as an attribute of the output (see function `base::attributes`)
- New and prettier status messages using package `cli`
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/doc/diff-batchgetsymbols.Rmd |
## ---- include=FALSE-----------------------------------------------------------
knitr::opts_chunk$set(message = FALSE)
## ---- results='hold'----------------------------------------------------------
library(yfR)
# set options for algorithm
my_ticker <- 'GM'
first_date <- Sys.Date() - 30
last_date <- Sys.Date()
# fetch data
df_yf <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
# output is a tibble with data
head(df_yf)
## -----------------------------------------------------------------------------
library(yfR)
library(ggplot2)
my_ticker <- c('TSLA', 'GM', 'MMM')
first_date <- Sys.Date() - 100
last_date <- Sys.Date()
df_yf_multiple <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
p <- ggplot(df_yf_multiple, aes(x = ref_date, y = price_adjusted,
color = ticker)) +
geom_line()
p
## -----------------------------------------------------------------------------
library(yfR)
library(ggplot2)
library(dplyr)
my_ticker <- 'GE'
first_date <- '2005-01-01'
last_date <- Sys.Date()
df_dailly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'daily') %>%
mutate(freq = 'daily')
df_weekly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'weekly') %>%
mutate(freq = 'weekly')
df_monthly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'monthly') %>%
mutate(freq = 'monthly')
df_yearly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'yearly') %>%
mutate(freq = 'yearly')
# bind it all together for plotting
df_allfreq <- bind_rows(
list(df_dailly, df_weekly, df_monthly, df_yearly)
) %>%
mutate(freq = factor(freq,
levels = c('daily',
'weekly',
'monthly',
'yearly'))) # make sure the order in plot is right
p <- ggplot(df_allfreq, aes(x = ref_date, y = price_adjusted)) +
geom_line() +
facet_grid(freq ~ ticker) +
theme_minimal() +
labs(x = '', y = 'Adjusted Prices')
print(p)
## -----------------------------------------------------------------------------
library(yfR)
library(ggplot2)
my_ticker <- c('TSLA', 'GM', 'MMM')
first_date <- Sys.Date() - 100
last_date <- Sys.Date()
df_yf_multiple <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
print(df_yf_multiple)
l_wide <- yf_convert_to_wide(df_yf_multiple)
names(l_wide)
prices_wide <- l_wide$price_adjusted
head(prices_wide)
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/doc/getting-started.R |
---
title: "Getting Started"
author: "Marcelo Perlin"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Getting Started}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include=FALSE}
knitr::opts_chunk$set(message = FALSE)
```
## Examples
Here you'll find a series of example of calls to `yf_get()`. Most arguments
are self-explanatory, but you can find more details at the help files.
The steps of the algorithm are:
1. check cache files for existing data
2. if not in cache, fetch stock prices from YF and clean up the raw data
3. write cache file if not available
4. calculate all returns
5. build diagnostics
6. return the data to the user
### Fetching a single stock price
```{r, results='hold'}
library(yfR)
# set options for algorithm
my_ticker <- 'GM'
first_date <- Sys.Date() - 30
last_date <- Sys.Date()
# fetch data
df_yf <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
# output is a tibble with data
head(df_yf)
```
### Fetching many stock prices
```{r}
library(yfR)
library(ggplot2)
my_ticker <- c('TSLA', 'GM', 'MMM')
first_date <- Sys.Date() - 100
last_date <- Sys.Date()
df_yf_multiple <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
p <- ggplot(df_yf_multiple, aes(x = ref_date, y = price_adjusted,
color = ticker)) +
geom_line()
p
```
### Fetching daily/weekly/monthly/yearly price data
```{r}
library(yfR)
library(ggplot2)
library(dplyr)
my_ticker <- 'GE'
first_date <- '2005-01-01'
last_date <- Sys.Date()
df_dailly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'daily') %>%
mutate(freq = 'daily')
df_weekly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'weekly') %>%
mutate(freq = 'weekly')
df_monthly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'monthly') %>%
mutate(freq = 'monthly')
df_yearly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'yearly') %>%
mutate(freq = 'yearly')
# bind it all together for plotting
df_allfreq <- bind_rows(
list(df_dailly, df_weekly, df_monthly, df_yearly)
) %>%
mutate(freq = factor(freq,
levels = c('daily',
'weekly',
'monthly',
'yearly'))) # make sure the order in plot is right
p <- ggplot(df_allfreq, aes(x = ref_date, y = price_adjusted)) +
geom_line() +
facet_grid(freq ~ ticker) +
theme_minimal() +
labs(x = '', y = 'Adjusted Prices')
print(p)
```
### Changing format to wide
```{r}
library(yfR)
library(ggplot2)
my_ticker <- c('TSLA', 'GM', 'MMM')
first_date <- Sys.Date() - 100
last_date <- Sys.Date()
df_yf_multiple <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
print(df_yf_multiple)
l_wide <- yf_convert_to_wide(df_yf_multiple)
names(l_wide)
prices_wide <- l_wide$price_adjusted
head(prices_wide)
```
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/doc/getting-started.Rmd |
## -----------------------------------------------------------------------------
available_collections <- yfR::yf_get_available_collections(
print_description = TRUE
)
available_collections
## ---- eval=FALSE--------------------------------------------------------------
# library(yfR)
#
# # be patient, it takes a while
# df_yf <- yf_collection_get("SP500")
#
# head(df_yf)
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/doc/using-collections.R |
---
title: "Using Collections"
author: "Marcelo Perlin"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using Collections}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Fetching collections of prices
Collections are just a bundle of tickers pre-organized in the package. For example, collection `SP500` represents the current composition of the SP500 index.
The available collections are:
```{r}
available_collections <- yfR::yf_get_available_collections(
print_description = TRUE
)
available_collections
```
One can download the composition of the collection with `yf_collection_get`:
```{r, eval=FALSE}
library(yfR)
# be patient, it takes a while
df_yf <- yf_collection_get("SP500")
head(df_yf)
```
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/doc/using-collections.Rmd |
available <- yfR::yf_index_list()
for (i_available in available) {
df <- yfR::yf_index_composition(i_available)
df$fetched_at <- Sys.Date()
this_file <- fs::path(
'inst/extdata/fallback-indices/',
stringr::str_glue("{i_available}.rds")
)
readr::write_rds(df,
file = this_file)
}
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/scripts/S_create_fallback_indices.R |
library(hexSticker)
library(yfR)
df_sp500 <- yfR::yf_get('^GSPC', first_date = '1950-01-01') %>%
dplyr::ungroup() %>%
dplyr::select(ref_date, price_adjusted)
s <- sticker(~plot(df_sp500, cex=.5, cex.axis=.5, mgp=c(0,.3,0),
xlab="", ylab="SP500"),
package="yfR",
p_size=11,
s_x=1,
s_y=.8,
s_width=1.4,
s_height=1.2,
filename="inst/figures/yfr_logo.png")
| /scratch/gouwar.j/cran-all/cranData/yfR/inst/scripts/S_create_logo.R |
---
title: "yfR and BatchGetSymbols"
author: "Marcelo Perlin"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{yfR and BatchGetSymbols}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Differences from [BatchGetSymbols](https://github.com/msperlin/BatchGetSymbols)
Package `BatchgetSymbols` was developed back in 2016, with many bad structural choices from my part. Since then, I learned more about R and its ecosystem, resulting in better and more maintainable code. However, it is impossible to keep compatibility with the changes I wanted to make, which is why I decided to develop a new (and fresh) package.
Here are the main differences between `yfR` (new) and `BatchGetSymbols` (old):
- All input arguments are now formatted as "snake_case" and not "dot.case". For example, the argument for the first date of data importation in `yfR::yf_get()` is `first_date`, and not `first.date`, as used in `BatchGetSymbols::BatchGetSymbols`.
- A new feature called "collection", which allows for easy download of a collection of tickers. For example, you can download price data for all components of the SP500 by simply calling `yfR::yf_collection_get("SP500")`.
- All function have been renamed for a common API notation. For example, `BatchGetSymbols::BatchGetSymbols` is now `yfR::yf_get()`. Likewise, the function for fetching collections is `yfR::yf_collection_get()`.
- The output of `yfR::yf_get()` is always a tibble with the price data (and not a list as in `BatchGetSymbols::BatchGetSymbols`). If one wants the tibble with a summary of the importing process, it is available as an attribute of the output (see function `base::attributes`)
- New and prettier status messages using package `cli`
| /scratch/gouwar.j/cran-all/cranData/yfR/vignettes/diff-batchgetsymbols.Rmd |
---
title: "Getting Started"
author: "Marcelo Perlin"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Getting Started}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include=FALSE}
knitr::opts_chunk$set(message = FALSE)
```
## Examples
Here you'll find a series of example of calls to `yf_get()`. Most arguments
are self-explanatory, but you can find more details at the help files.
The steps of the algorithm are:
1. check cache files for existing data
2. if not in cache, fetch stock prices from YF and clean up the raw data
3. write cache file if not available
4. calculate all returns
5. build diagnostics
6. return the data to the user
### Fetching a single stock price
```{r, results='hold'}
library(yfR)
# set options for algorithm
my_ticker <- 'GM'
first_date <- Sys.Date() - 30
last_date <- Sys.Date()
# fetch data
df_yf <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
# output is a tibble with data
head(df_yf)
```
### Fetching many stock prices
```{r}
library(yfR)
library(ggplot2)
my_ticker <- c('TSLA', 'GM', 'MMM')
first_date <- Sys.Date() - 100
last_date <- Sys.Date()
df_yf_multiple <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
p <- ggplot(df_yf_multiple, aes(x = ref_date, y = price_adjusted,
color = ticker)) +
geom_line()
p
```
### Fetching daily/weekly/monthly/yearly price data
```{r}
library(yfR)
library(ggplot2)
library(dplyr)
my_ticker <- 'GE'
first_date <- '2005-01-01'
last_date <- Sys.Date()
df_dailly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'daily') %>%
mutate(freq = 'daily')
df_weekly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'weekly') %>%
mutate(freq = 'weekly')
df_monthly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'monthly') %>%
mutate(freq = 'monthly')
df_yearly <- yf_get(tickers = my_ticker,
first_date, last_date,
freq_data = 'yearly') %>%
mutate(freq = 'yearly')
# bind it all together for plotting
df_allfreq <- bind_rows(
list(df_dailly, df_weekly, df_monthly, df_yearly)
) %>%
mutate(freq = factor(freq,
levels = c('daily',
'weekly',
'monthly',
'yearly'))) # make sure the order in plot is right
p <- ggplot(df_allfreq, aes(x = ref_date, y = price_adjusted)) +
geom_line() +
facet_grid(freq ~ ticker) +
theme_minimal() +
labs(x = '', y = 'Adjusted Prices')
print(p)
```
### Changing format to wide
```{r}
library(yfR)
library(ggplot2)
my_ticker <- c('TSLA', 'GM', 'MMM')
first_date <- Sys.Date() - 100
last_date <- Sys.Date()
df_yf_multiple <- yf_get(tickers = my_ticker,
first_date = first_date,
last_date = last_date)
print(df_yf_multiple)
l_wide <- yf_convert_to_wide(df_yf_multiple)
names(l_wide)
prices_wide <- l_wide$price_adjusted
head(prices_wide)
```
| /scratch/gouwar.j/cran-all/cranData/yfR/vignettes/getting-started.Rmd |
---
title: "Using Collections"
author: "Marcelo Perlin"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using Collections}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Fetching collections of prices
Collections are just a bundle of tickers pre-organized in the package. For example, collection `SP500` represents the current composition of the SP500 index.
The available collections are:
```{r}
available_collections <- yfR::yf_get_available_collections(
print_description = TRUE
)
available_collections
```
One can download the composition of the collection with `yf_collection_get`:
```{r, eval=FALSE}
library(yfR)
# be patient, it takes a while
df_yf <- yf_collection_get("SP500")
head(df_yf)
```
| /scratch/gouwar.j/cran-all/cranData/yfR/vignettes/using-collections.Rmd |
aps <- function (dataMatrix, dv, ivlist){
k<-length(ivlist)
numcc<-2**k-1
ivlist <- unlist(ivlist)
ilist<-match(ivlist,colnames(dataMatrix))
ilist<-na.omit(ilist)
ilist<-colnames(dataMatrix)[ilist]
dataMatrix<-na.omit(dataMatrix[,c(dv,ilist)])
## Generate an ID for each independent variable to 2^(k-1).
ivID <- matrix(nrow=k,ncol=1)
ivID[,1]<-2^(0:(k-1))
rownames(ivID)<-ivlist
## Generate a matrix containing the bit representation of each subset.
PredBitMap<-matrix(0, k, numcc)
x<-proc.time()
for (i in 1:numcc){
n<-i
j<-1
while (n != 0){
if ((n %% 2) == 1) PredBitMap[j,i]<-1
n <- n%/%2
j<-j+1
}
}
rownames(PredBitMap)<-ivlist
apsBitMap<-matrix(nrow=numcc,ncol=1)
apsBitMap[,1]<-t(order(colSums(PredBitMap[,])))
APSMatrix <- matrix(nrow=numcc,ncol=2)
for (i in 1: numcc){
formula=paste(dv,"~", sep="")
for (j in 1: k){
bit = PredBitMap[j,i]
if (bit == 1){
formula=paste(formula,paste("+",ivlist[[j]], sep=""), sep="")
}
}
APSMatrix[i,2]<-summary(lm(formula,dataMatrix))$r.squared
APSMatrix[i,1]<-sum(PredBitMap[,i])
}
APSMatrixc<-APSMatrix[apsBitMap[,1],]
## Use the bitmap matrix to generate row headings.
rnl<-vector(mode="character",length=ncol(PredBitMap))
for (i in 1:ncol(PredBitMap)){
vars<-as.data.frame(PredBitMap[,i])
colnames(vars)<-"var"
vars<-subset(vars,var==1)
rn<-rownames(vars)[1]
if (nrow(vars)>1){
for (k in 2:nrow(vars)){
rn<-paste(rn,rownames(vars)[k],sep=",")
}
}
rnl[i]<-rn
}
rownames(APSMatrixc)<-rownames(apsBitMap)<-rnl[apsBitMap[,1]]
colnames(APSMatrixc)<-c("k","R2")
return (list(ivID=ivID, PredBitMap=PredBitMap, apsBitMap=apsBitMap, APSMatrix=APSMatrixc))
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/aps.r |
boot.yhat<-function(data,indices,lmOut,regrout0){
data<-data[indices,]
blmOut<-lm(formula=lmOut$call$formula,data=data)
regrout<-calc.yhat(blmOut)
pm<-as.vector(regrout$PredictorMetrics[-nrow(regrout$PredictorMetrics),])
apsm<-as.vector(as.matrix(regrout$APSRelatedMetrics[-nrow(regrout$APSRelatedMetrics),-2]))
pdm<-as.vector(as.matrix(regrout$PairedDominanceMetrics))
tau<-vector(length=ncol(regrout$PredictorMetrics))
for (i in 1:length(tau)){
s1<-(regrout0$PredictorMetrics[1:(nrow(regrout0$PredictorMetrics)-1),i])
s2<-(regrout$PredictorMetrics[1:(nrow(regrout$PredictorMetrics)-1),i])
tau[i]<-cor.test(s1,s2,method="kendall",exact=FALSE)$estimate
}
c(pm,pdm,apsm,tau)
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/boot.yhat.r |
booteval.yhat<-function(regrOut,boot.out,bty="perc",level=.95,prec=3){
if((bty != "perc") & (bty != "norm") & (bty != "basic") & (bty != "bca")) stop ("Only norm, basic, perc, and bca interval types are supported")
l<-nrow(regrOut$PredictorMetrics)-1
m<-ncol(regrOut$PredictorMetrics)
n<-nrow(regrOut$APSRelatedMetrics)-1
o<-ncol(regrOut$APSRelatedMetrics)-1
lowerCIpm<-upperCIpm<-regrOut$PredictorMetrics[-(l+1),]
for (i in 1: l){
for (j in 1:m){
indpm<-(j-1)*l+i
CI<-boot.ci(boot.out,index=indpm,type=bty,conf=level)
CIl<-ci.yhat(bty,CI)
lowerCIpm[i,j]<-CIl[1]
upperCIpm[i,j]<-CIl[2]
}
}
lowerCIpm<-round(lowerCIpm,digits=prec)
upperCIpm<-round(upperCIpm,digits=prec)
combCIpm<-combCI(lowerCIpm,upperCIpm,regrOut$PredictorMetrics[-nrow(regrOut$PredictorMetrics),])
pmc<-combn(1:l,2)
upperCIpmDiff<-lowerCIpmDiff<-pmDiff<-matrix(nrow=ncol(pmc),ncol=m)
colnames(upperCIpmDiff)<-colnames(lowerCIpmDiff)<-colnames(pmDiff)<-colnames(regrOut$PredictorMetrics)
rownames(upperCIpmDiff)<-rownames(lowerCIpmDiff)<-rownames(pmDiff)<-paste(rownames(regrOut$PredictorMetrics)[pmc[1,]],
rownames(regrOut$PredictorMetrics)[pmc[2,]],sep="-")
boot.outl<-boot.out
for (i in 1:m){
for (j in 1:ncol(pmc)){
pmDiff[j,i]<-boot.outl$t0<-boot.out$t0[l*(i-1)+pmc[1,j]]-boot.out$t0[l*(i-1)+pmc[2,j]]
boot.outl$t<-as.matrix(boot.out$t[,l*(i-1)+pmc[1,j]]-boot.out$t[,l*(i-1)+pmc[2,j]])
CI<-boot.ci(boot.outl,index=1,type=bty,conf=level)
CIl<-ci.yhat(bty,CI)
lowerCIpmDiff[j,i]<-CIl[1]
upperCIpmDiff[j,i]<-CIl[2]
}
}
pmDiff<-round(pmDiff,digits=prec)
lowerCIpmDiff<-round(lowerCIpmDiff,digits=prec)
upperCIpmDiff<-round(upperCIpmDiff,digits=prec)
combCIpmDiff<-combCI(lowerCIpmDiff,upperCIpmDiff,pmDiff,TRUE)
nd<-nrow(regrOut$PairedDominanceMetrics)
domboot<-matrix(nrow=nd*3,ncol=7)
rownames(domboot)<-c(paste("Com_",rownames(regrOut$PairedDominanceMetrics),sep=""),
paste("Con_",rownames(regrOut$PairedDominanceMetrics),sep=""),
paste("Gen_",rownames(regrOut$PairedDominanceMetrics),sep=""))
colnames(domboot)<-c("Dij","Mean","SE","Pij","Pji","Pijno","Reprod")
domboot<-as.data.frame(domboot)
inds<-indpm+1
inde<-indpm+(l*(l-1)/2)*ncol(regrOut$PairedDominanceMetrics)
ind<-indpm
boots<-nrow(boot.out$t)
domboot$Dij<-boot.out$t0[inds:inde]
domboot$Mean<-colMeans(boot.out$t[,c(inds:inde)])
for (i in 1:(nd*3)){
domboot$SE[i]<-sd(boot.out$t[,(ind+i)])
domboot$Pij[i]<-sum(boot.out$t[,(ind+i)] == 1)/boots
domboot$Pji[i]<-sum(boot.out$t[,(ind+i)] == 0)/boots
domboot$Pijno[i]<-sum(boot.out$t[,(ind+i)] == .5)/boots
if (domboot$Dij[i]==1)
domboot$Reprod[i]<-domboot$Pij[i]
else if (domboot$Dij[i]==0)
domboot$Reprod[i]<-domboot$Pji[i]
else
domboot$Reprod[i]<-domboot$Pijno[i]
}
lowerCIaps<-upperCIaps<-regrOut$APSRelatedMetrics[-(n+1),-2]
for (i in 1: ncol(lowerCIaps)){
for (j in 1:nrow(lowerCIaps)){
ind<-inde+(i-1)*n+j
if (!is.na(lowerCIaps[j,i])){
CI<-boot.ci(boot.out,index=ind,type=bty,conf=level)
CIl<-ci.yhat(bty,CI)
lowerCIaps[j,i]<-CIl[1]
upperCIaps[j,i]<-CIl[2]
}
}
}
lowerCIaps<-round(lowerCIaps,digits=prec)
upperCIaps<-round(upperCIaps,digits=prec)
combCIaps<-combCI(lowerCIaps,upperCIaps,regrOut$APSRelatedMetrics[-nrow(regrOut$APSRelatedMetrics),-2])
s<-1
e<-l
d<-NULL
for (i in 1:(l-1)){
d<-rbind(d,t(combn(s:e,2)))
s<-e+1
e<-e+ncol(combn(1:l,(i+1)))
}
upperCIapsDiff<-lowerCIapsDiff<-apsDiff<-matrix(nrow=nrow(d),ncol=2)
colnames(upperCIapsDiff)<-colnames(lowerCIapsDiff)<-colnames(apsDiff)<-colnames(regrOut$APSRelatedMetrics)[c(1,3)]
rownames(upperCIapsDiff)<-rownames(lowerCIapsDiff)<-rownames(apsDiff)<-paste(rownames(regrOut$APSRelatedMetrics)[d[,1]],
rownames(regrOut$APSRelatedMetrics)[d[,2]],sep="-")
for (i in 1:2){
for (j in 1:nrow(d)){
apsDiff[j,i]<-boot.outl$t0<-boot.out$t0[inde+n*(i-1)+d[j,1]]-boot.out$t0[inde+n*(i-1)+d[j,2]]
boot.outl$t<-as.matrix(boot.out$t[,inde+n*(i-1)+d[j,1]]-boot.out$t[,inde+n*(i-1)+d[j,2]])
if (!is.na(boot.outl$t0)){
CI<-boot.ci(boot.outl,index=1,type=bty,conf=level)
CIl<-ci.yhat(bty,CI)
lowerCIapsDiff[j,i]<-CIl[1]
upperCIapsDiff[j,i]<-CIl[2]
}
}
}
apsDiff<-round(apsDiff,digits=prec)
lowerCIapsDiff<-round(lowerCIapsDiff,digits=prec)
upperCIapsDiff<-round(upperCIapsDiff,digits=prec)
combCIapsDiff<-combCI(lowerCIapsDiff,upperCIapsDiff,apsDiff,TRUE)
p<-nrow(regrOut$APSRelatedMetrics)-ncol(combn(1:l,l-1))-2
upperCIincDiff<-lowerCIincDiff<-incDiff<-combCIincDiff<-matrix(nrow=p,ncol=nrow(combCIpmDiff))
if (p>0){
indi<-inde+n*2
for (i in 1:ncol(incDiff)){
for (j in 1:nrow(incDiff)){
incDiff[j,i]<-boot.outl$t0<-boot.out$t0[indi+n*(pmc[1,i]-1)+j]-boot.out$t0[indi+n*(pmc[2,i]-1)+j]
boot.outl$t<-as.matrix(boot.out$t[,indi+n*(pmc[1,i]-1)+j]-boot.out$t[,indi+n*(pmc[2,i]-1)+j])
if (!is.na(boot.outl$t0)){
CI<-boot.ci(boot.outl,index=1,type=bty,conf=level)
CIl<-ci.yhat(bty,CI)
lowerCIincDiff[j,i]<-CIl[1]
upperCIincDiff[j,i]<-CIl[2]
}
}
}
incDiff<-round(rbind(pmDiff[,"CD:0"],incDiff),digits=prec)
lowerCIincDiff<-round(rbind(lowerCIpmDiff[,"CD:0"],lowerCIincDiff),digits=prec)
upperCIincDiff<-round(rbind(upperCIpmDiff[,"CD:0"],upperCIincDiff),digits=prec)
rownames(upperCIincDiff)<-rownames(lowerCIincDiff)<-rownames(incDiff)<-c(".",rownames(regrOut$APSRelatedMetrics)[1:p])
colnames(upperCIincDiff)<-colnames(lowerCIincDiff)<-colnames(incDiff)<-paste(colnames(regrOut$APSRelatedMetrics)[pmc[1,]+3],
colnames(regrOut$APSRelatedMetrics)[pmc[2,]+3],sep="-")
combCIincDiff<-combCI(lowerCIincDiff,upperCIincDiff,incDiff,TRUE)
}
tauds<-matrix(ncol=2,nrow=m)
colnames(tauds)<-c("Mean","SD")
rownames(tauds)<-colnames(regrOut$PredictorMetrics)
for (i in 1:m){
tauds[i,"Mean"]<-mean(boot.out$t[,(ind+i)],na.rm=TRUE)
tauds[i,"SD"]<-sd(boot.out$t[,(ind+i)],na.rm=TRUE)
}
return(list(combCIpm=combCIpm,lowerCIpm=lowerCIpm,upperCIpm=upperCIpm,
combCIaps=combCIaps,lowerCIaps=lowerCIaps,upperCIaps=upperCIaps,
domBoot=round(domboot,digits=prec),tauDS=t(round(tauds,digits=prec)),
combCIpmDiff=combCIpmDiff,lowerCIpmDiff=lowerCIpmDiff,upperCIpmDiff=upperCIpmDiff,
combCIapsDiff=combCIapsDiff,lowerCIapsDiff=lowerCIapsDiff,upperCIapsDiff=upperCIapsDiff,
combCIincDiff=combCIincDiff,lowerCIincDiff=lowerCIincDiff,upperCIincDiff=upperCIincDiff))
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/booteval.yhat.r |
calc.yhat<-function (lm.out,prec=3)
{
ifelse(length(lm.out$call) > 2, new.data <- eval(as.name(lm.out$call[[3]]),
parent.frame()), new.data <- model.frame(lm.out$call[[2]]))
new.scale <- model.matrix(lm.out)
v <- as.numeric(as.factor(row.names(new.scale)))
# new.data <- new.data[v, ]
IV <- attr(lm.out$terms, "term.labels")
DV <- dimnames(attr(lm.out$terms, "factors"))[[1]][1]
IVx <- dimnames(attr(lm.out$terms, "factors"))[[1]][-1]
new.data<-na.omit(new.data[,c(DV,IVx)])
new.scale[, 1] <- lm.out$model[, 1]
new.scale <- data.frame(new.scale)
colnames(new.scale) <- c(DV, IV)
betaOut <- coef(lm.out)[-1] * sapply(new.scale[IV], "sd")/sapply(new.scale[DV], "sd")
structure.coef <- cor(na.omit(fitted.values(lm.out)), new.scale[IV])
rownames(structure.coef)<-""
apsOut<-aps(new.data,DV,IV)
domOut<-dominance(apsOut)
dombinOut<-dombin(domOut)
comOut<-commonality(apsOut)
rlwOut<-t(rlw(new.data,DV,IV))
corOut<-cor(new.scale)
corOut<-corOut[,1]
corOut<-corOut[-1]
a<-rbind(lm.out$coef[-1],betaOut,corOut,structure.coef,structure.coef^2,u<-comOut[c(1:length(betaOut)),1],corOut^2-u,
domOut$CD,domOut$GD, corOut*betaOut,rlwOut)
rownames(a)<-c("b","Beta","r","rs","rs2","Unique","Common",rownames(domOut$CD),"GenDom","Pratt","RLW")
a<-round(t(a),digits=prec)
a<-rbind(a,colSums(a))
l<-nrow(a)
rownames(a)[l]<-"Total"
a[l,c(1:4)]<-NA
apsanal<-cbind(comOut,domOut$DA)
rownames(apsanal)<-rownames(domOut$DA)
colnames(apsanal)[1]<-"Commonality"
apsanal<-rbind(apsanal,Total=colSums(apsanal))
apsanal[nrow(apsanal),3:ncol(apsanal)]<-NA
apsanal<-apsanal[,-3]
opm<-a[-nrow(a),]
for (i in 1:ncol(opm)){
o<-order(abs(opm[,i]),decreasing=TRUE)
opm[o,i]<-1:nrow(opm)
}
return(list(PredictorMetrics= a, OrderedPredictorMetrics=opm,PairedDominanceMetrics=dombinOut, APSRelatedMetrics=round(apsanal,digits=prec)) )
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/calc.yhat.r |
canonCommonality<-function(A,B,nofns=1){
CCdataR <- vector("list", 2)
canon <- cca(A, B)
Blist <- dimnames(B)[[2]]
CCdata <- vector("list", nofns)
for (i in 1:nofns) {
CVA <- canon$canvarx[, i]
data <- cbind(B, CVA)
CCdata[[i]] <- commonalityCoefficients(data, "CVA", Blist,
"F")
}
CCdataR[[1]] <- CCdata
Blist <- dimnames(A)[[2]]
CCdata <- vector("list", nofns)
for (i in 1:nofns) {
CVA <- canon$canvary[, i]
data <- cbind(A, CVA)
CCdata[[i]] <- commonalityCoefficients(data, "CVA", Blist,
"F")
}
CCdataR[[2]] <- CCdata
return(CCdataR)
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/canonCommonality.R |
canonVariate <-
function(A,B,nofns){
##Perform canonical correlation
canon<-cca(A,B)
##Determine names of variables in set B
Blist<-dimnames(B)[[2]]
##Build output object
CCdata<-vector("list",nofns)
##For each function requested:
## Get commonality data
for (i in 1:nofns)
{
CVA<-canon$canvarx[,i]
data<-cbind(B,CVA)
CCdata[[i]]<-commonalityCoefficients(data,"CVA", Blist, "F")
}
return(CCdata)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/canonVariate.R |
ci.yhat<-function(bty,CI){
switch(bty,
perc=
{
return(c(CI$perc[4],CI$perc[5]))
},
basic=
{
return(c(CI$basic[4],CI$basic[5]))
},
bca=
{
return(c(CI$bca[4],CI$bca[5]))
},
norm=
{
return(c(CI$norm[2],CI$norm[3]))
})
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/ci.yhat.r |
combCI<-function(lowerCI,upperCI,est,star=FALSE){
lowerCI<-format(lowerCI,3,format="f")
upperCI<-format(upperCI,3,format="f")
est<-format(est,3,format="f")
combCI<-est
for (i in 1:nrow(combCI)){
for (j in 1: ncol(combCI)){
if (combCI[i,j]!="NA"){
combCI[i,j]<-paste(combCI[i,j],lowerCI[i,j],sep="(")
combCI[i,j]<-paste(combCI[i,j],upperCI[i,j],sep=",")
combCI[i,j]<-paste(combCI[i,j],")",sep="")
if (star){
if ((lowerCI[i,j] < 0) & (upperCI[i,j] > 0))
combCI[i,j]<-paste(combCI[i,j]," ",sep="")
else
combCI[i,j]<-paste(combCI[i,j],"*",sep="")
}
combCI[i,j]<-toString(combCI[i,j])
}
}
}
combCI<-as.data.frame(combCI)
return(combCI)
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/combCI.r |
commonality <- function (apsOut){
ivID<-apsOut$ivID
nvar<-length(ivID)
if (nvar < 2)return ("Commonality analysis not conducted. Insufficient number of regressors specified.")
numcc<-2**nvar-1
effectBitMap<-apsOut$PredBitMap
apsBitMap<-apsOut$apsBitMap
commonalityMatrix <- matrix(nrow=numcc,ncol=3)
commonalityMatrix[,1]<-apsOut$APSMatrix[order(apsBitMap),2]
## Use the bitmap matrix to generate the list of R2 values needed.
commonalityList<-vector("list", numcc)
for (i in 1: numcc){
bit = effectBitMap[1,i]
if (bit == 1) ilist <-c(0,-ivID[1])
else ilist<-ivID[1]
for (j in 2: nvar){
bit = effectBitMap[j,i]
if (bit == 1){
alist<-ilist
blist<-genList(ilist,-ivID[j])
ilist<-c(alist,blist)
}
else ilist<-genList(ilist,ivID[j])
}
ilist<-ilist*-1
commonalityList[[i]]<-ilist
}
## Use the list of R2 values to compute each commonality coefficient.
for (i in 1: numcc){
r2list <- unlist(commonalityList[i])
numlist = length(r2list)
ccsum=0
for (j in 1:numlist){
indexs = r2list[[j]]
indexu = abs (indexs)
if (indexu !=0) {
ccvalue = commonalityMatrix[indexu,1]
if (indexs < 0)ccvalue = ccvalue*-1
ccsum=ccsum+ccvalue
}
}
commonalityMatrix[i,2]=ccsum
}
commonalityMatrix<-commonalityMatrix[,-1]
commonalityMatrix[,1]<-commonalityMatrix[apsBitMap[,1],1]
commonalityMatrix[,2]<-commonalityMatrix[,1]/apsOut$APSMatrix[numcc,2]
colnames(commonalityMatrix)<-c("Coefficient", " % Total")
rownames(commonalityMatrix)<-rownames(apsBitMap)
return (commonalityMatrix)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/commonality.r |
commonalityCoefficients<-
function (dataMatrix, dv, ivlist, imat = FALSE)
{
ivlist <- unlist(ivlist)
ilist<-match(ivlist,colnames(dataMatrix))
ilist<-na.omit(ilist)
ilist<-colnames(dataMatrix)[ilist]
dataMatrix<-na.omit(dataMatrix[,c(dv,ilist)])
nvar = length(ivlist)
if (nvar < 2)
return("Commonality analysis not conducted. Insufficient number of regressors.")
ivID <- matrix(nrow = nvar, ncol = 1)
for (i in 0:nvar - 1) {
ivID[i + 1] = 2^i
}
if (imat)
print(ivID)
numcc = 2^nvar - 1
effectBitMap <- matrix(0, nvar, numcc)
for (i in 1:numcc) {
effectBitMap <- setBits(i, effectBitMap)
}
if (imat)
print(effectBitMap)
commonalityMatrix <- matrix(nrow = numcc, ncol = 3)
for (i in 1:numcc) {
formula = paste(dv, "~", sep = "")
for (j in 1:nvar) {
bit = effectBitMap[j, i]
if (bit == 1) {
formula = paste(formula, paste("+", ivlist[[j]],
sep = ""), sep = "")
}
}
commonalityMatrix[i, 2] <- summary(lm(formula, dataMatrix))$r.squared
}
if (imat)
print(commonalityMatrix)
commonalityList <- vector("list", numcc)
for (i in 1:numcc) {
bit = effectBitMap[1, i]
if (bit == 1)
ilist <- c(0, -ivID[1])
else ilist <- ivID[1]
for (j in 2:nvar) {
bit = effectBitMap[j, i]
if (bit == 1) {
alist <- ilist
blist <- genList(ilist, -ivID[j])
ilist <- c(alist, blist)
}
else ilist <- genList(ilist, ivID[j])
}
ilist <- ilist * -1
commonalityList[[i]] <- ilist
}
if (imat)
print(commonalityList)
for (i in 1:numcc) {
r2list <- unlist(commonalityList[i])
numlist = length(r2list)
ccsum = 0
for (j in 1:numlist) {
indexs = r2list[[j]]
indexu = abs(indexs)
if (indexu != 0) {
ccvalue = commonalityMatrix[indexu, 2]
if (indexs < 0)
ccvalue = ccvalue * -1
ccsum = ccsum + ccvalue
}
}
commonalityMatrix[i, 3] = ccsum
}
if (imat)
print(commonalityMatrix)
orderList <- vector("list", numcc)
index = 0
for (i in 1:nvar) {
for (j in 1:numcc) {
nbits = sum(effectBitMap[, j])
if (nbits == i) {
index = index + 1
commonalityMatrix[index, 1] <- j
}
}
}
if (imat)
print(commonalityMatrix)
outputCommonalityMatrix <- matrix(nrow = numcc + 1, ncol = 2)
totalRSquare <- sum(commonalityMatrix[, 3])
for (i in 1:numcc) {
outputCommonalityMatrix[i, 1] <- round(commonalityMatrix[commonalityMatrix[i,
1], 3], digits = 4)
outputCommonalityMatrix[i, 2] <- round((commonalityMatrix[commonalityMatrix[i,
1], 3]/totalRSquare) * 100, digits = 2)
}
outputCommonalityMatrix[numcc + 1, 1] <- round(totalRSquare,
digits = 4)
outputCommonalityMatrix[numcc + 1, 2] <- round(100, digits = 4)
rowNames = NULL
for (i in 1:numcc) {
ii = commonalityMatrix[i, 1]
nbits = sum(effectBitMap[, ii])
cbits = 0
if (nbits == 1)
rowName = "Unique to "
else rowName = "Common to "
for (j in 1:nvar) {
if (effectBitMap[j, ii] == 1) {
if (nbits == 1)
rowName = paste(rowName, ivlist[[j]], sep = "")
else {
cbits = cbits + 1
if (cbits == nbits) {
rowName = paste(rowName, "and ", sep = "")
rowName = paste(rowName, ivlist[[j]], sep = "")
}
else {
rowName = paste(rowName, ivlist[[j]], sep = "")
rowName = paste(rowName, ", ", sep = "")
}
}
}
}
rowNames = c(rowNames, rowName)
}
rowNames = c(rowNames, "Total")
rowNames <- format.default(rowNames, justify = "left")
colNames <- format.default(c("Coefficient", " % Total"),
justify = "right")
dimnames(outputCommonalityMatrix) <- list(rowNames, colNames)
if (imat)
print(outputCommonalityMatrix)
outputCCbyVar <- matrix(nrow = nvar, ncol = 3)
for (i in 1:nvar) {
outputCCbyVar[i, 1] = outputCommonalityMatrix[i, 1]
outputCCbyVar[i, 3] = round(sum(effectBitMap[i, ] * commonalityMatrix[,
3]), digits = 4)
outputCCbyVar[i, 2] = outputCCbyVar[i, 3] - outputCCbyVar[i,
1]
}
dimnames(outputCCbyVar) <- list(ivlist, c("Unique", "Common",
"Total"))
outputList <- list(CC = outputCommonalityMatrix, CCTotalbyVar = outputCCbyVar)
return(outputList)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/commonalityCoefficients.R |
dombin<-function(domOut){
nvar<-length(domOut$GD)
dombinout<-matrix(ncol=3,nrow=nvar*(nvar-1)/2)
colnames(dombinout)<-c("Comp","Cond","Gen")
dombinout<-data.frame(dombinout)
pair<-combn(1:nvar,2)
compDA<-domOut$DA[,c(-1,-2)]
compDA<-rbind(compDA,domOut$CD[1,])
for (i in 1:ncol(pair)){
rownames(dombinout)[i]<-paste(names(domOut$GD)[pair[1,i]],names(domOut$GD)[pair[2,i]],sep=">")
if (domOut$GD[pair[1,i]]>domOut$GD[pair[2,i]])
dombinout$Gen[i]<-1
else
dombinout$Gen[i]<-0
cdchk<-(domOut$CD[,pair[1,i]]>domOut$CD[,pair[2,i]])
if (sum(cdchk) == nvar)
dombinout$Cond[i]<-1
else if (sum(cdchk) == 0)
dombinout$Cond[i]<-0
else
dombinout$Cond[i]<-.5
compDAl<-compDA[,c(pair[1,i],pair[2,i])]
compDAl<-na.omit(compDAl)
cdchk<-compDAl[,1]>compDAl[,2]
if (sum(cdchk) == length(cdchk))
dombinout$Comp[i]<-1
else if (sum(cdchk) == 0)
dombinout$Comp[i]<-0
else
dombinout$Comp[i]<-.5
}
return(dombinout)
} | /scratch/gouwar.j/cran-all/cranData/yhat/R/dombin.r |
dominance <- function (apsOut){
varid<-apsOut$ivID
PredBitMap<-apsOut$PredBitMap
indin<-ind<-apsOut$apsBitMap
ind[indin[,1],1]<-1:nrow(indin)
APSMatrix<-apsOut$APSMatrix
nvar<-length(varid)
numcc<-2**nvar-1
dom<-matrix(nrow=2^nvar-1,ncol=nvar+2)
cd<-matrix(nrow=nvar-1,ncol=nvar)
varnames<-paste(rownames(PredBitMap),"-Inc",sep="")
colnames(cd)<-rownames(PredBitMap)
colnames(dom)<-c("k","R2",varnames)
rownames(dom)<-rownames(APSMatrix)
dom[,1:2]<-APSMatrix[,1:2]
for (j in 2:nvar){
co1<-combn(varid[,1],j)
for (k in 1:ncol(co1)){
m<-sum(co1[,k])
r2m<-dom[ind[m],2]
co2<-combn(co1[,k],j-1)
for (l in 1:ncol(co2)){
n<-sum(co2[,l])
r2n<-dom[ind[n],2]
dom[ind[n],(log(m-n)/log(2))+3]<-r2m-r2n
}
}
}
dom<-data.frame(dom)
for (i in 1:nrow(cd)){
ss<-subset(dom,k == i)
cd[i,]<-colMeans(ss[,3:(nvar+2)],na.rm=TRUE)
}
cd<-insertRow(cd,1,APSMatrix[c(1:nvar),2])
rownames(cd)<-paste("CD:",c(0:(nvar-1)),sep="")
gd<-colMeans(cd)
return(list(DA=dom,CD=cd,GD=gd))
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/dominance.r |
effect.size <-
function(lm.out){
n<-length(lm.out$resid)
p<-length(lm.out$coef)
rsquared<-summary(lm.out)$r.sq
es<-matrix(ncol=2,nrow=6)
rowNames=format(c("Wherry1","Claudy3","Smith","Wherry2","Olkin & Pratt","Pratt"),justify="left")
colNames=format(c("Effect Size","Recommended"),justify="left")
dimnames(es)<-list(rowNames,colNames)
####Compute Effect Sizes using Correction Formulas
####Wherry:
es[1,1]= ((1 - (((n-1)/(n-p-1)) * (1 - rsquared))))
####Claudy3:
es[2,1]=((1 - (((n-4)*(1-rsquared))/(n-p-1)) * (1 + (2*(1-rsquared))/(n-p+1))))
####Smith:
es[3,1]=((1-((n/(n-p)) * (1-rsquared))))
####Wherry2:
es[4,1]=((1- (((n-1)/(n-p)) * (1-rsquared))))
####Olin & Pratt:
es[5,1]=((1-(((n-3)*(1-rsquared))/(n-p-1))*(1 + (2*(1-rsquared))/(n-p+1))))
####Pratt:
es[6,1]=((1-(((n-3)*(1-rsquared))/(n-p-1))*(1 + (2*(1-rsquared))/(n-p-2.3))))
####Identify recommended correction formula:
es[,2]="No"
if (n<=30)es[6,2]="Yes"
else
{
if (n <=50)
{
if (p<=2) es[6,2]="Yes"
else
{
if (p<=6) es[5,2]="Yes"
else es[5,2]=es[6,2]="Yes"
}
}
else
{
if (n<=80)
{
if (p<=2)es[6,2]=es[2,2]="Yes"
else ifelse((p<=6),es[1,2]<-"Yes", es[6,2]<-"Yes")
}
else
{
if (n <=150)
{
if (p<=2) es[4,2]<-"Yes"
else es[6,2]<-"Yes"
}
else
{
if (p<=2)es[1,2]=es[3,2]="Yes"
else ifelse((p<=6),es[2,2]<-"Yes", es[4,2]<-"Yes")
}
}
}
}
es<-data.frame(es)
return(es)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/effect.size.R |
genList <-
function(ivlist, value){
########################################################################################
numlist = length(ivlist)
newlist<-ivlist
newlist=0
for (i in 1:numlist){
newlist[i]=abs(ivlist[i])+abs(value)
if (((ivlist[i]<0) && (value >= 0))|| ((ivlist[i]>=0) && (value <0)))newlist[i]=newlist[i]*-1
}
return(newlist)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/genList.R |
odd <-
function(val) {
########################################################################################
##DESCRIPTION
##Returns true if value is odd; false if true
##REQUIRED ARGUMENTS
##val Value to check
##Returns true if val is odd
if (((as.integer(val/2))*2)!=val) return(TRUE)
return (FALSE)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/odd.R |
plotCI.yhat<-function(sampStat, upperCI, lowerCI, pid=1:ncol(sampStat),nr=2,nc=2){
par(mfrow=c(nr,nc))
for (j in 1:length(pid)){
i<-pid[j]
k<-nrow(sampStat)
plotCI(x=sampStat[1:k,i],uiw=upperCI[1:k,i]-sampStat[1:k,i],
liw=sampStat[1:k,i]-lowerCI[1:k,i],ylab="", xlab="",
col="black",xaxt="n",xlim=c(0,(k+1)), ylim=c(min(na.omit(lowerCI[1:k,i])),max(na.omit(upperCI[1:k,i]))),pch=21,pt.bg=par("bg"))
axis(side=1,at=1:k,labels=rownames(sampStat),las=2)
title(main=colnames(sampStat)[[i]])
}
return()
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/plotCI.yhat.r |
regr<-function (lm.out)
{
ifelse(length(lm.out$call) > 2, new.data <- eval(as.name(lm.out$call[[3]]),
parent.frame()), new.data <- model.frame(lm.out$call[[2]]))
new.scale <- model.matrix(lm.out)
v <- as.numeric(row.names(new.scale))
# new.data <- new.data[v, ]
IV <- attr(lm.out$terms, "term.labels")
DV <- dimnames(attr(lm.out$terms, "factors"))[[1]][1]
IVx <- dimnames(attr(lm.out$terms, "factors"))[[1]][-1]
new.data<-na.omit(new.data[,c(DV,IVx)])
new.scale[, 1] <- lm.out$model[, 1]
new.scale <- data.frame(new.scale)
colnames(new.scale) <- c(DV, IV)
beta.out <- coef(lm.out)[-1] * sapply(new.scale[IV], "sd")/sapply(new.scale[DV],
"sd")
structure.coef <- cor(na.omit(fitted.values(lm.out)), new.scale[IV])
CCdata = commonalityCoefficients(new.data, DV, IV, "F")
es = effect.size(lm.out)
return(list(LM_Output = summary(lm.out), Beta_Weights = beta.out,
Structure_Coefficients = structure.coef, Commonality_Data = CCdata,
Effect_Size = es, Comment = "The Effect Size recommendations are based on Yin and Fan (2001). Your dataset may take on a different covariance structure, thus making another effect size estimate more appropriate."))
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/regr.R |
rlw <- function (dataMatrix, dv, ivlist){
ivlist <- unlist(ivlist)
ilist<-match(ivlist,colnames(dataMatrix))
ilist<-na.omit(ilist)
ilist<-colnames(dataMatrix)[ilist]
dataMatrix<-na.omit(dataMatrix[,c(dv,ilist)])
k<-length(ivlist)
ds<-matrix(ncol=k+1,nrow=nrow(dataMatrix))
ds[,1]<-dataMatrix[,dv]
for (i in 1:k){
ds[,i+1]<-dataMatrix[,ivlist[i]]
}
colnames(ds)<-c(dv,ivlist)
rxx<-cor(ds[,2:(k+1)])
rxy<-cor(ds[,2:(k+1)],ds[,1])
evm<-eigen(rxx)
ev<-evm$values
evec<-evm$vectors
d<-diag(ev)
delta<-sqrt(d)
lambda<-evec %*% delta %*% t(evec)
lambdasq<-lambda^2
beta<-solve(lambda) %*% rxy
rawrl<-lambdasq %*% beta^2
return(rawrl)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/rlw.r |
setBits <-
function(col, effectBitMap) {
########################################################################################
##DESCRIPTION
##Creates the binary representation of n and stores it in the nth column of the matrix
##REQUIRED ARGUMENTS
##col Column of matrix to represent in binary image
##effectBitMap Matrix of mean combinations in binary form
##Initialize variables
row<-1
val<-col
##Create the binary representation of col and store it in its associated column
##One is stored in col 1; Two is stored in col 2; etc.
##While (val >= 1)
## If the LSB of val is 1; increment the appropriate entry in combo matrix
## Shift the LSB of val to the right
while (val!=0){
if (odd(val)) {
effectBitMap[row,col]=1
}
val<-as.integer(val/2)
row<-row+1
}
##Return matrix
return(effectBitMap)
}
| /scratch/gouwar.j/cran-all/cranData/yhat/R/setBits.R |
#' Private predicate function that checks if the protocol of a url
#' is https.
#'
#' @param x is a url string
is.https <- function(x) {
m <- regexec("^https?://", x)
matches <- regmatches(x, m)
if (matches=="https://") {
h <- TRUE
} else {
h <- FALSE
}
h
}
#' Private function for performing a GET request
#'
#' @param endpoint /path for REST request
#' @param query url parameters for request
yhat.get <- function(endpoint, query=c()) {
AUTH <- get("yhat.config")
if (length(AUTH)==0) {
stop("Please specify your account credentials using yhat.config.")
}
if ("env" %in% names(AUTH)) {
url <- AUTH[["env"]]
usetls <- FALSE
if (is.https(url)) {
usetls <- TRUE
}
url <- stringr::str_replace_all(url, "^https?://", "")
url <- stringr::str_replace_all(url, "/$", "")
if (usetls) {
url <- sprintf("https://%s/", url)
} else {
url <- sprintf("http://%s/", url)
}
AUTH <- AUTH[!names(AUTH)=="env"]
query <- c(query, AUTH)
query <- paste(names(query), query, collapse="&", sep="=")
url <- paste(url, endpoint, "?", query, sep="")
httr::GET(url, httr::authenticate(AUTH[["username"]], AUTH[["apikey"]], 'basic'))
} else {
message("Please specify 'env' parameter in yhat.config.")
}
}
#' Private function for verifying username and apikey
yhat.verify <- function() {
tryCatch({
AUTH <- get("yhat.config")
}, error = function(e) {
stop("Please define a yhat.config object")
})
env <- AUTH[["env"]]
usetls <- FALSE
if (is.https(env)) {
usetls <- TRUE
}
env <- stringr::str_replace_all(env, "^https?://", "")
env <- stringr::str_replace_all(env, "/$", "")
username <- AUTH[["username"]]
apikey <- AUTH[["apikey"]]
if (usetls) {
url <- sprintf("https://%s/verify?username=%s&apikey=%s",
env, username, apikey)
} else {
url <- sprintf("http://%s/verify?username=%s&apikey=%s",
env, username, apikey)
}
rsp <- httr::POST(url)
if (rsp$status_code != 200) {
cat(httr::content(rsp, "text"), "\n")
stop(sprintf("Bad response from http://%s/", env))
}
status <- httr::content(rsp)$success
if (is.null(status)) {
stop("Invalid apikey/username combination!")
}
if (status != "true") {
stop("Invalid apikey/username combination!")
}
}
#' Private function for performing a POST request
#'
#' @param endpoint /path for REST request
#' @param query url parameters for request
#' @param data payload to be converted to raw JSON
#' @param silent should output of url to console be silenced?
#' Default is \code{FALSE}.
#' @param bulk is this a bulk style request? Default is \code{FALSE}.
yhat.post <- function(endpoint, query=c(), data, silent = TRUE, bulk = FALSE) {
if(!is.logical(silent)) stop("Argument 'silent' must be logical!")
AUTH <- get("yhat.config")
if (length(AUTH)==0) {
stop("Please specify your account credentials using yhat.config.")
}
if ("env" %in% names(AUTH)) {
url <- AUTH[["env"]]
usetls <- FALSE
if (is.https(url)) {
usetls <- TRUE
}
url <- stringr::str_replace_all(url, "^https?://", "")
url <- stringr::str_replace_all(url, "/$", "")
if (usetls) {
url <- sprintf("https://%s/", url)
} else {
url <- sprintf("http://%s/", url)
}
AUTH <- AUTH[!names(AUTH)=="env"]
query <- c(query, AUTH)
query <- paste(names(query), query, collapse="&", sep="=")
url <- paste(url, endpoint, "?", query, sep="")
if(silent==FALSE) {
message(url)
}
# bullk sends back line delimited JSON
if (bulk==TRUE) {
out <- textConnection("data.json", "w")
jsonlite::stream_out(data, con = out)
close(out)
} else {
data.json <- jsonlite::toJSON(data, dataframe = "columns")
}
httr::POST(url, body = data.json,
config = c(
httr::authenticate(AUTH[["username"]], AUTH[["apikey"]], 'basic'),
httr::add_headers("Content-Type" = "application/json")
)
)
} else {
message("Please specify 'env' parameter in yhat.config.")
}
}
#' Private function for checking the size of the user's image.
#'
#' @importFrom utils object.size
check.image.size <- function() {
bytes.in.a.mb <- 2 ^ 20
model.size <- list()
for (obj in yhat.ls()) {
model.size[[obj]] <- object.size(get(obj))
}
# lets get this into a data.frame
df <- data.frame(unlist(model.size))
model.size <- data.frame(obj=rownames(df),size.mb=df[[1]] / bytes.in.a.mb)
model.size
}
#' Checks dependencies and makes sure all are installed.
#'
check.dependencies <- function() {
is.function(jsonlite::validate)
}
#' Calls Yhat's REST API and returns a JSON document containing both the prediction
#' and associated metadata.
#'
#' @param model_name the name of the model you want to call
#' @param data input data for the model
#' @param model_owner the owner of the model [optional]
#' @param raw_input when true, incoming data will NOT be coerced into data.frame
#' @param silent should output of url to console (via \code{yhat.post})
#' be silenced? Default is \code{FALSE}.
#' @param bulk should the bulk api be used Default is \code{FALSE}.
#'
#' @export
#' @examples
#' yhat.config <- c(
#' username = "your username",
#' apikey = "your apikey"
#' )
#' \dontrun{
#' yhat.predict_raw("irisModel", iris)
#' }
yhat.predict_raw <- function(model_name, data, model_owner, raw_input = FALSE, silent = TRUE, bulk = FALSE) {
usage <- "usage: yhat.predict(<model_name>,<data>)"
if(missing(model_name)){
stop(paste("Please specify the model name you'd like to call",usage,sep="\n"))
}
if(missing(data)){
stop(paste("You didn't pass any data to predict on!",usage,sep="\n"))
}
AUTH <- get("yhat.config")
if ("env" %in% names(AUTH)) {
user <- AUTH[["username"]]
if(!missing(model_owner)){
user <- model_owner
}
endpoint <- sprintf("%s/models/%s/", user, model_name)
} else {
stop("Please specify an env in yhat.config")
}
# build the model url for the error message
url <- AUTH[["env"]]
usetls <- FALSE
if (is.https(url)) {
usetls <- TRUE
}
url <- stringr::str_replace_all(url, "^https?://", "")
url <- stringr::str_replace_all(url, "/$", "")
if (usetls) {
model_url <- sprintf("https://%s/model/%s/", url, model_name)
} else {
model_url <- sprintf("http://%s/model/%s/", url, model_name)
}
query <- list()
if (raw_input==TRUE) {
query[["raw_input"]] <- "true"
}
if (bulk==TRUE) {
query[["bulk"]] <- "true"
}
error_msg <- paste("Invalid response: are you sure your model is built?\nHead over to",
model_url,"to see you model's current status.")
tryCatch(
{
rsp <- yhat.post(endpoint, query = query, data = data, silent = silent, bulk = bulk)
httr::content(rsp)
},
error = function(e){
print(e)
stop(error_msg)
},
exception = function(e){
print(e)
stop(error_msg)
}
)
}
#' Make a prediction using Yhat.
#'
#' This function calls Yhat's REST API and returns a response formatted as a
#' data frame.
#'
#' @param model_name the name of the model you want to call
#' @param data input data for the model
#' @param model_owner the owner of the model [optional]
#' @param raw_input when true, incoming data will NOT be coerced into data.frame
#' @param silent should output of url to console (via \code{yhat.post})
#' be silenced? Default is \code{FALSE}.
#'
#' @keywords predict
#' @export
#' @examples
#' yhat.config <- c(
#' username = "your username",
#' apikey = "your apikey",
#' env = "http://sandbox.yhathq.com/"
#' )
#' \dontrun{
#' yhat.predict("irisModel", iris)
#' }
yhat.predict <- function(model_name, data, model_owner, raw_input = FALSE, silent = TRUE) {
raw_rsp <- yhat.predict_raw(model_name, data, model_owner, raw_input = raw_input, silent = silent)
tryCatch({
if (raw_input==TRUE) {
raw_rsp
} else if ("result" %in% names(raw_rsp)) {
data.frame(lapply(raw_rsp$result, unlist))
} else {
data.frame(raw_rsp)
}
},
error = function(e){
stop("Invalid response: are you sure your model is built?")
},
exception = function(e){
stop("Invalid response: are you sure your model is built?")
})
}
#' Make bulk predictions using Yhat.
#'
#' This function calls Yhat's bulk API and returns a response formatted as a
#' data frame.
#'
#' @param model_name the name of the model you want to call
#' @param data input rows of data to be scored
#' @param model_owner the owner of the model [optional]
#' @param raw_input when true, incoming data will NOT be coerced into data.frame
#' @param silent should output of url to console (via \code{yhat.post})
#' be silenced? Default is \code{FALSE}.
#'
#' @keywords bulk
#' @export
#' @examples
#' yhat.config <- c(
#' username = "your username",
#' apikey = "your apikey",
#' env = "http://sandbox.yhathq.com/"
#' )
#' \dontrun{
#' yhat.predict_bulk("irisModel", iris)
#' }
yhat.predict_bulk <- function(model_name, data, model_owner, raw_input = FALSE, silent = TRUE) {
raw_rsp <- yhat.predict_raw(model_name, data, model_owner, raw_input = raw_input, silent = silent, bulk = TRUE)
tryCatch({
# this is weird but it's the only way I could figure out how to turn raw_rsp
# into a connection() type (which is basically a stream). we create a tempfile,
# write raw_rsp to that file, then read it back in using jsonlite
f <- file(tmp <- tempfile())
write(raw_rsp, f)
close(f)
output <- jsonlite::stream_in(file(tmp))
unlink(tmp)
output
},
error = function(e){
stop(paste("Invalid response: are you sure your model is built?", e))
},
exception = function(e){
stop("Invalid response: are you sure your model is built?")
})
}
# Create a new environment in order to namespace variables that hold the package state
yhat <- new.env(parent = emptyenv())
# Packages that need to be installed for the model to run - this will almost always
# include all the packages listed in imports
yhat$dependencies <- data.frame()
# Private function for storing requirements that will be imported on
# the ScienceOps server
yhat$model.require <- function() {
}
#' Import one or more libraries and add them to the Yhat model's
#' dependency list
#'
#' @param name name of the package to be added
#' @param src source from which the package will be installed on ScienceOps (github or CRAN)
#' @param version version of the package to be added
#' @param user Github username associated with the package
#' @param install Whether the package should also be installed into the model on the
#' ScienceOps server; this is typically set to False when the package has already been
#' added to the ScienceOps base image.
#' @keywords import
#' @export
#' @examples
#' \dontrun{
#' yhat.library("MASS")
#' yhat.library(c("wesanderson", "stringr"))
#' yhat.library("cats", src="github", user="hilaryparker")
#' yhat.library("hilaryparker/cats")
#' yhat.library("my_proprietary_package", install=FALSE)
#' }
#' @importFrom utils packageDescription
yhat.library <- function(name, src="CRAN", version=NULL, user=NULL, install=TRUE) {
# If a vector of CRAN packages is passed, add each of them
if (length(name) > 1) {
for (n in name) {
yhat.library(n, install=install)
}
return()
}
if (!src %in% c("CRAN", "github")) {
stop(cat(src, "is not a valid package type"))
}
if (src == "github") {
if (is.null(user)) {
stop(cat("no github username specified"))
}
installName <- paste(user, "/", name, sep="")
} else {
installName <- name
}
if (grepl("/", name)) {
src <- "github"
nameAndUser <- unlist(strsplit(name, "/"))
user <- nameAndUser[[1]]
name <- nameAndUser[[2]]
}
library(name, character.only = TRUE)
# If a version wasn't manually specified, get this info from the session
if (is.null(version)) {
version <- packageDescription(name)$Version
}
add.dependency(installName, name, src, version, install)
set.model.require()
}
#' Removes a library from the Yhat model's dependency list
#'
#' @param name of the package to be removed
#'
#' @export
#' @examples
#' \dontrun{
#' yhat.unload("wesanderson")
#' }
yhat.unload <- function(name) {
deps <- yhat$dependencies
yhat$dependencies <- deps[deps$importName != name,]
set.model.require()
}
#' Private function that adds a package to the list of dependencies
#' that will be installed on the ScienceOps server
#' @param name name of the package to be installed
#' @param importName name under which the package is imported (for a github package,
#' this may be different from the name used to install it)
#' @param src source that the package is installed from (CRAN or github)
#' @param version version of the package
#' @param install whether or not the package should be installed in the model image
add.dependency <- function(name, importName, src, version, install) {
# Don't add the dependency if it's already there
dependencies <- yhat$dependencies
if (!any(dependencies$name == name)) {
newRow <- data.frame(name=name, importName=importName, src=src, version=version, install=install)
dependencies <- rbind(dependencies, newRow)
yhat$dependencies <- dependencies
}
}
#' Private function that generates a model.require function based on
#' the libraries that have been imported in this session.
set.model.require <- function() {
imports <- yhat$dependencies$importName
yhat$model.require <- function() {
for (pkg in imports) {
library(pkg, character.only = TRUE)
}
}
}
confirm.deployment <- function() {
deps <- yhat$dependencies
deps$importName <- NULL
cat("Model will be deployed with the following dependencies:\n")
print(deps)
needsConfirm <- TRUE
while (needsConfirm) {
sure <- readline("Are you sure you want to deploy? y/n ")
if (sure == "n" || sure == "N") {
needsConfirm <- FALSE
stop("Deployment cancelled")
} else if (sure == "y" || sure == "Y") {
needsConfirm <- FALSE
}
}
}
#' Deploy a model to Yhat's servers
#'
#' This function takes model.transform and model.predict and creates
#' a model on Yhat's servers which can be called from any programming language
#' via Yhat's REST API (see \code{\link{yhat.predict}}).
#'
#' @param model_name name of your model
#' @param packages list of packages to install using apt-get
#' @param confirm boolean indicating whether to prompt before deploying
#' @param custom_image name of the image you'd like your model to use
#' @keywords deploy
#' @export
#' @examples
#' yhat.config <- c(
#' username = "your username",
#' apikey = "your apikey",
#' env = "http://sandbox.yhathq.com/"
#' )
#' iris$Sepal.Width_sq <- iris$Sepal.Width^2
#' fit <- glm(I(Species)=="virginica" ~ ., data=iris)
#'
#' model.require <- function() {
#' # require("randomForest")
#' }
#'
#' model.transform <- function(df) {
#' df$Sepal.Width_sq <- df$Sepal.Width^2
#' df
#' }
#' model.predict <- function(df) {
#' data.frame("prediction"=predict(fit, df, type="response"))
#' }
#' \dontrun{
#' yhat.deploy("irisModel")
#' yhat.deploy("irisModelCustomImage", custom_image="myImage:latest")
#' }
yhat.deploy <- function(model_name, packages=c(), confirm=TRUE, custom_image=NULL) {
if(missing(model_name)){
stop("Please specify 'model_name' argument")
}
if (length(grep("^[A-Za-z_0-9]+$", model_name))==0) {
stop("Model name can only contain following characters: A-Za-z_0-9")
}
yhat.verify()
img.size.mb <- check.image.size()
AUTH <- get("yhat.config")
if (length(AUTH)==0) {
stop("Please specify your account credentials using yhat.config.")
}
if ("env" %in% names(AUTH)) {
env <- AUTH[["env"]]
usetls <- FALSE
if (is.https(env)) {
usetls <- TRUE
}
env <- stringr::str_replace_all(env, "^https?://", "")
env <- stringr::str_replace_all(env, "/$", "")
AUTH <- AUTH[!names(AUTH)=="env"]
query <- AUTH
query <- paste(names(query), query, collapse="&", sep="=")
if (usetls) {
url <- sprintf("https://%s/deployer/model?%s", env, query)
} else {
url <- sprintf("http://%s/deployer/model?%s", env, query)
}
image_file <- tempfile(pattern="scienceops_deployment")
all_objects <- yhat.ls()
# Consolidate local environment with global one
deployEnv <- new.env(parent = emptyenv())
print("I AM HERE")
deployEnv$model.require <- yhat$model.require
for (obj in all_objects) {
print("obj")
print(obj)
deployEnv[[obj]] <- globalenv()[[obj]]
}
# if model.transform is not provided give it a default value
if (!("model.transform" %in% all_objects)) {
model.transform <- function(data) { data }
deployEnv$model.transform <- function(data) { data }
all_objects <- c(all_objects, "model.transform")
}
all_funcs <- all_objects[lapply(all_objects, function(name){
class(globalenv()[[name]])
}) == "function"]
all_objects <- c("model.require", all_objects)
save(list=all_objects, envir=deployEnv, file=image_file)
cat("objects detected\n")
sizes <- lapply(all_objects, function(name) {
format( object.size(globalenv()[[name]]) , units="auto")
})
sizes <- unlist(sizes)
print(data.frame(name=all_objects, size=sizes))
cat("\n")
if (confirm && interactive()) {
confirm.deployment()
}
dependencies <- yhat$dependencies[yhat$dependencies$install,]
print("your dependencies")
print(yhat$dependencies[yhat$dependencies$install,])
err.msg <- paste("Could not connect to ScienceOps. Please ensure that your",
"specified server is online. Contact info [at] yhathq [dot] com",
"for further support.",
"-----------------------",
"Specified endpoint:",
env,
sep="\n")
rsp <- httr::POST(url, httr::authenticate(AUTH[["username"]], AUTH[["apikey"]], 'basic'),
body=list(
"model_image" = httr::upload_file(image_file),
"modelname" = model_name,
"packages" = jsonlite::toJSON(dependencies),
"apt_packages" = packages,
"code" = capture.src(all_funcs),
"custom_image" = custom_image
)
)
body <- httr::content(rsp)
if (rsp$status_code != 200) {
unlink(image_file)
stop("deployment error: ", body)
}
rsp.df <- data.frame(body)
unlink(image_file)
cat("deployment successful\n")
rsp.df
} else {
message("Please specify 'env' parameter in yhat.config.")
}
}
#' Deploy a batch model to Yhat servers
#'
#' This function will deploy your batch model to the yhat servers
#'
#' @param job_name name of batch job
#' @param confirm boolean indicating whether to prompt before deploying
#' @keywords deploy
#' @export
#' @examples
#' yhat.config <- c(
#' username = "your username",
#' apikey = "your apikey",
#' env = "http://sandbox.yhathq.com/"
#' )
#' yhat.batch <- function() {
#' name <- "ross"
#' greeting <- paste("Hello", name)
#' print(greeting)
#' }
#' \dontrun{
#' yhat.batchDeploy("helloworld")
#' }
#' @importFrom utils tar
yhat.batchDeploy <- function(job_name, confirm=TRUE) {
if(missing(job_name)) {
stop("Please specify 'job_name' argument")
}
if (length(grep("^[a-z_0-9]+$", job_name))==0) {
stop("Model name can only contain following characters: a-z_0-9")
}
yhat.verify()
AUTH <- get("yhat.config")
if (length(AUTH)==0) {
stop("Please specify your account credentials using yhat.config.")
}
# Check if we have a yhat.yaml file, if we don't then ask the user to try again
if (!file.exists('yhat.yaml')) {
stop("Please provide a yhat.yaml file in the working directory to specify the job config.")
}
if ("env" %in% names(AUTH)) {
env <- AUTH[["env"]]
usetls <- FALSE
if (is.https(env)) {
usetls <- TRUE
}
env <- stringr::str_replace_all(env, "^https?://", "")
env <- stringr::str_replace_all(env, "/$", "")
AUTH <- AUTH[!names(AUTH)=="env"]
query <- AUTH
query <- paste(names(query), query, collapse="&", sep="=")
if (usetls) {
url <- sprintf("https://%s/batch/deploy?%s", env, query)
} else {
url <- sprintf("http://%s/batch/deploy?%s", env, query)
}
all_objects <- yhat.ls(batchMode=TRUE)
all_funcs <- all_objects[lapply(all_objects, function(name){
class(globalenv()[[name]])
}) == "function"]
all_objects <- c("model.require", all_objects)
cat("objects detected\n")
sizes <- lapply(all_objects, function(name) {
format( object.size(globalenv()[[name]]) , units="auto")
})
sizes <- unlist(sizes)
print(data.frame(name=all_objects, size=sizes))
cat("\n")
if (confirm && interactive()) {
confirm.deployment()
}
dependencies <- yhat$dependencies[yhat$dependencies$install,]
err.msg <- paste("Could not connect to ScienceOps. Please ensure that your",
"specified server is online. Contact info [at] yhathq [dot] com",
"for further support.",
"-----------------------",
"Specified endpoint:",
env,
sep="\n")
# Create the bundle.json and requirements.txt files
bundleFrame <- list(
code = jsonlite::unbox(capture.src(all_funcs, capture.model.require=FALSE)),
language = jsonlite::unbox("R")
)
bundleJson <- jsonlite::toJSON(bundleFrame)
f = file("bundle.json", open="wb")
write(bundleJson, f)
close(f)
depList = list(dependencies=dependencies)
depJson <- jsonlite::toJSON(depList, dataframe=c("rows"))
f = file("requirements.txt", open="wb")
write(depJson, f)
close(f)
# Create the bundle
sysName <- Sys.info()["sysname"]
zip <- ""
if (sysName == "Darwin" || sysName == "Linux") {
# OSX workaround...
bundle_name <- "yhat_job.tar.gz"
filenames <- c('bundle.json', 'yhat.yaml', 'requirements.txt')
filenames.fmt <- paste(filenames, collapse=" ")
cmd <- sprintf("/usr/bin/tar -czvf %s %s", bundle_name, filenames.fmt)
system(cmd, ignore.stdout = TRUE, ignore.stderr = TRUE)
} else if (sysName == "Windows") {
bundle_name <- "yhat_job.zip"
zip(bundle_name, c("bundle.json", 'yhat.yaml', 'requirements.txt'))
zip <- "true"
} else {
bundle_name <- "yhat_job.tar.gz"
tar(bundle_name, c("bundle.json", 'yhat.yaml', 'requirements.txt'), compression = 'gzip', tar='tar')
}
rsp <- httr::POST(url,
httr::authenticate(AUTH[["username"]], AUTH[["apikey"]], 'basic'),
body=list(
"job" = httr::upload_file(bundle_name),
"job_name" = job_name,
"zip" = zip
)
)
body <- httr::content(rsp)
if (rsp$status_code != 200) {
unlink(bundle_name)
stop("deployment error: ", body)
}
rsp.df <- data.frame(body)
# After the upload, clean up
unlink(bundle_name)
unlink("bundle.json")
unlink("requirements.txt")
cat("deployment successful\n")
rsp.df
} else {
message("Please specify 'env' parameter in yhat.config.")
}
}
#' Private function for catpuring the source code of model
#'
#' @param funcs functions to capture, defaults to required yhat model functions
#' @param capture.model.require flag to capture the model.require function
#' @importFrom utils capture.output
capture.src <- function(funcs, capture.model.require=TRUE){
yhat$model.require()
if(missing(funcs)){
funcs <- c("model.transform","model.predict")
}
global.vars <- ls(.GlobalEnv)
src <- ""
if (capture.model.require==TRUE) {
src <- paste(capture.output(yhat$model.require),collapse="\n")
}
for(func in funcs){
if(func %in% global.vars){
func.src <- paste(capture.output(.GlobalEnv[[func]]), collapse="\n")
func.src <- paste(func,"<-", func.src)
src <- paste(src, func.src,sep="\n\n")
}
}
src
}
#' Private function for recursively looking for variables
#'
#' @param block code block to spider
#' @param defined.vars variables which have already been defined within the
#' scope of the block. e.g. function argument
yhat.spider.block <- function(block,defined.vars=c()){
# if block is a symbol, just return that symbol
if(typeof(block) == "symbol") {
return(c(block))
}
symbols <- c()
n <- length(block)
if(n == 0) {
return(symbols)
}
for(i in 1:n){
node <- block[[i]]
# Really weird bug that comes from assigning the "empty" symbol to a
# variable. No obvious way to test for this case other than a try/catch
is.valid.symbol <- tryCatch({
node
TRUE
}, error = function(e) {
FALSE
})
if(!is.valid.symbol){ next }
node.type <- typeof(node)
# if node type is "symbol" then it might be a variable
if(node.type == "symbol"){
# if symbol not already defined then it might be a dependency
if(!any(node == defined.vars)){
symbols <- c(symbols,node)
}
# if node type is "language" then it is another block we'll want to spider
} else if (node.type == "language"){
# is the block an assignment statement? if so we'll want to add the
# assignment result to the list of defined variables
if ((node[[1]] == as.symbol("<-")) || (node[[1]] == as.symbol("="))){
# Code will look like this:
# `assign.to` <- `assign.from`
assign.from <- node[[3]]
assign.from.type <- typeof(assign.from)
if (assign.from.type == "symbol"){
# if symbol not already defined then it might be a dependency
if (!any(assign.from == defined.vars)){
symbols <- c(symbols, assign.from)
}
} else if (assign.from.type == "language") {
symbols <- c(symbols, yhat.spider.block(assign.from, defined.vars))
}
assign.to <- node[[2]]
assign.to.type <- typeof(assign.to)
if (assign.to.type == "symbol"){
# yay! the user has defined a variable
defined.vars <- c(assign.to,defined.vars)
} else if (assign.to.type == "language"){
# Wait, what?!?! are you assigning to a block of code?
symbols <- c(symbols,yhat.spider.block(assign.to, defined.vars))
}
} else {
# if the block isn't an assignment, recursively crawl
symbols <- c(symbols,yhat.spider.block(node,defined.vars))
}
}
}
# return a list of symbols which are candidates for global dependency
symbols
}
#' Private function for spidering function source code
#'
#' @param func.name name of function you want to spider
#' @importFrom utils getAnywhere
yhat.spider.func <- function(func.name){
# parse function to pull out main block and argument names
func <- parse(text=getAnywhere(func.name))[[2]][[2]]
# we will be comparing symbols not strings
args <- lapply(names(func[[2]]),as.symbol)
block <- func[[3]]
# get all symbols used during function which are dependencies
func.vars <- unique(yhat.spider.block(block,defined.vars=args))
# return dependency candidates which are defined in the global scope
# (these are all variables we'll want to capture)
intersect(func.vars,names(as.list(.GlobalEnv)))
}
#' Private function for determining model dependencies
#'
#' List all object names which are dependencies of `model.transform`
#' and `model.predict` or `yhat.batch` if this is a batch mode deploy
#'
#' @param batchMode boolean to capture yhat.batch code for a batch job
yhat.ls <- function(batchMode=FALSE){
funcs <- c("model.predict") # function queue to spider
global.vars <- ls(.GlobalEnv,all.names=T)
if ("model.transform" %in% global.vars) {
funcs <- c(funcs, "model.transform")
}
if (batchMode) {
funcs <- c("yhat.batch")
if (!("yhat.batch" %in% global.vars)){
err.msg <- "ERROR: You must define \"yhat.batch\" before deploying a batch job"
stop(err.msg)
}
} else {
if (!("model.predict" %in% global.vars)){
err.msg <- "ERROR: You must define \"model.predict\" before deploying a model"
stop(err.msg)
}
}
dependencies <- funcs
while(length(funcs) > 0){
# pop first function from queue
func.name <- funcs[[1]]
n.funcs <- length(funcs)
if(n.funcs > 1){
funcs <- funcs[2:length(funcs)]
} else {
funcs <- c()
}
# spider a function and get all variable dependencies
func.vars <- yhat.spider.func(func.name)
n.vars <- length(func.vars)
if(n.vars > 0){
for(i in 1:n.vars){
var <- func.vars[[i]]
# is variable already a dependency?
if(!(var %in% dependencies)){
dependencies <- c(var,dependencies)
# if this variable is a function we're going to
# want to spider it as well
if(typeof(.GlobalEnv[[var]]) == "closure"){
# add function to function queue
funcs <- c(var,funcs)
}
}
}
}
}
if("model.require" %in% global.vars){
stop("Warning: model.require is deprecated as of yhatr 0.13.9 - please use yhat.library to specify model dependencies")
}
dependencies
}
| /scratch/gouwar.j/cran-all/cranData/yhatr/R/yhatR.R |
library(yhatr)
iris$Sepal.Width_sq <- iris$Sepal.Width^2
fit <- glm(I(Species)=="virginica" ~ ., data=iris)
model.require <- function() {
}
model.transform <- function(df) {
df$Sepal.Width_sq <- df$Sepal.Width^2
df
}
model.predict <- function(df) {
data.frame("prediction"=predict(fit, df, type="response"))
}
yhat.config <- c(username = "your username", apikey = "your apikey", env="http://cloud.yhathq.com")
deployment <- yhat.deploy("irisModel")
lapply(1:nrow(iris), function(i) {
print(yhat.predict("irisModel", iris[i,]))
})
| /scratch/gouwar.j/cran-all/cranData/yhatr/demo/iris-glm.R |
library(yhatr)
library(randomForest)
library(plyr)
iris$Sepal.Width_sq <- iris$Sepal.Width^2
fit <- randomForest(Species ~ ., data=iris)
model.require <- function() {
require("randomForest")
}
model.transform <- function(df) {
df$Sepal.Width_sq <- df$Sepal.Width^2
df
}
model.predict <- function(df) {
data.frame("prediction"=predict(fit, df, type="response"))
}
yhat.config <- c(username = "your username", apikey = "your apikey", env = "http://cloud.yhathq.com/")
(deployment <- yhat.deploy("irisModel"))
predict(fit, iris[1,])
yhat.predict("irisModel", iris[1,])
results <- ldply(1:nrow(iris), function(i) {
data.frame(idx=i,
yhat=yhat.predict("irisModel", iris[i,])$prediction,
local=predict(fit, iris[i,]))
})
table(results$yhat==results$local)
| /scratch/gouwar.j/cran-all/cranData/yhatr/demo/iris-rf.R |
#' Compute average years of life lost (YLL)
#'
#' \code{avg_yll} computes the average expected years of life lost (YLL), given
#' the number of deaths, the average age of death and the standard life
#' expectancy.
#'
#' \code{avg_yll} computes the average expected years of life lost (YLL). The
#' average YLL, which highlights premature causes of death and brings attention
#' to preventable deaths is computed by dividing the standard YLL by the number
#' of deaths (Aragon et al., 2008). The number of deaths, the average age of
#' death and the standard life expectancy at least must be provided (as numeric
#' vectors). Other arguments are provided to incorporate time discounting and
#' age weighting.
#'
#' @param ndeaths Number of deaths (numeric).
#' @param avg.age.death Average age of death (numeric).
#' @param life.expectancy The interpolated life expectancy at that age. In other
#' words, the expected remaining number of years to live (numeric).
#' @param discount.rate Discount rate (default is set to 0.03) (numeric).
#' @param beta Age-weighting constant (default is set to 0.04) (numeric).
#' @param modulation Age-weighting modulation constant (= 0, no weighting; = 1,
#' weighting, default is set to 0) (numeric).
#' @param adjustment Adjustment constant for age-weights (default is set to
#' 0.1658) (numeric).
#'
#' @return Since all inputs are numeric vectors, the output will be a numeric
#' vector.
#'
#' @references Aragon, T. J., Lichtensztajn, D. Y., Katcher, B. S., Reiter, R.,
#' & Katz, M. H. (2008). Calculating expected years of life lost for assessing
#' local ethnic disparities in causes of premature death. \emph{BMC public
#' health, 8}(1), 116.
#'
#' @seealso \code{\link{yll}} for the standard measure of years of life lost.
#'
#' @examples
#' # For 100 deaths with an average age of death of 60 years
#' # and an expected remaining number of years to live of 20 years:
#'
#' avg_yll(100, 60, 20)
#'
#' # Without discounting:
#'
#' avg_yll(100, 60, 20, discount.rate = 0)
#'
#' \dontrun{
#' avg_yll("a", "b", "c") # arguments must be numeric
#' avg_yll(100) # avg.age.death and life.expectancy are missing,
#' # with no default
#' avg_yll(100, 60) # life.expectancy is missing,
#' # with no default
#' }
#'
#' @author Antoine Soetewey \email{antoine.soetewey@@uclouvain.be}
# Set the function to compute YLL
avg_yll <- function(ndeaths, avg.age.death, life.expectancy,
discount.rate = 0.03, beta = 0.04,
modulation = 0, adjustment = 0.1658){
# abbreviate inputs
N <- ndeaths; a <- avg.age.death
L <- life.expectancy; r <- discount.rate
b <- beta; K <- modulation
CC <- adjustment
# do calculations
if(discount.rate==0){
(N*(K*CC*((exp(-b*a))/b^2)*((exp(-b*L))*
(-b*(L+a)-1)-(-b*a-1))+((1-K)*L)))/N
} else {
(N*(K*((CC*exp(r*a))/(-(r+b)^2))*((exp(-(r+b)*(L+a))*(-(r+b)*
(L+a)-1))-(exp(-(r+b)*a)*(-(r+b)*a-1)))+((1-K)/r)*((1-exp(-r*L)))))/N
}
}
| /scratch/gouwar.j/cran-all/cranData/yll/R/avg_yll.R |
#' Compute years of life lost (YLL)
#'
#' \code{yll} computes the standard expected years of life lost (YLL), given the
#' number of deaths, the average age of death and the standard life expectancy.
#'
#' \code{yll} computes the standard expected years of life lost (YLL) as
#' developed by the Global Burden of Disease Study (Murray, C.J., Lopez, A.D.
#' and World Health Organization, 1996). The YLL is based on comparing the age
#' of death to an external standard life expectancy curve (Aragon et al., 2008).
#' The number of deaths, the average age of death and the standard life
#' expectancy at least must be provided (as numeric vectors). Other arguments
#' are provided to incorporate time discounting and age weighting.
#'
#' @param ndeaths Number of deaths (numeric).
#' @param avg.age.death Average age of death (numeric).
#' @param life.expectancy The interpolated life expectancy at that age. In other
#' words, the expected remaining number of years to live (numeric).
#' @param discount.rate Discount rate (default is set to 0.03) (numeric).
#' @param beta Age-weighting constant (default is set to 0.04) (numeric).
#' @param modulation Age-weighting modulation constant (= 0, no weighting; = 1,
#' weighting, default is set to 0) (numeric).
#' @param adjustment Adjustment constant for age-weights (default is set to
#' 0.1658) (numeric).
#'
#' @return Since all inputs are numeric vectors, the output will be a numeric
#' vector.
#'
#' @references Aragon, T. J., Lichtensztajn, D. Y., Katcher, B. S., Reiter, R.,
#' & Katz, M. H. (2008). Calculating expected years of life lost for assessing
#' local ethnic disparities in causes of premature death. \emph{BMC public
#' health, 8}(1), 116.
#' @references Murray, C. J., Lopez, A. D., & World Health
#' Organization. (1996). The global burden of disease: a comprehensive
#' assessment of mortality and disability from diseases, injuries, and risk
#' factors in 1990 and projected to 2020: summary.
#'
#' @seealso \code{\link{avg_yll}} for the average years of life lost.
#'
#' @examples
#' # For 100 deaths with an average age of death of 60 years
#' # and an expected remaining number of years to live of 20 years:
#'
#' yll(100, 60, 20)
#'
#' # Without discounting:
#'
#' yll(100, 60, 20, discount.rate = 0)
#'
#' \dontrun{
#' yll("a", "b", "c") # arguments must be numeric
#' yll(100) # avg.age.death and life.expectancy are missing,
#' # with no default
#' yll(100, 60) # life.expectancy is missing,
#' # with no default
#' }
#'
#' @author Antoine Soetewey \email{antoine.soetewey@@uclouvain.be}
# Set the function to compute YLL
yll <- function(ndeaths, avg.age.death, life.expectancy,
discount.rate = 0.03, beta = 0.04,
modulation = 0, adjustment = 0.1658){
# abbreviate inputs
N <- ndeaths; a <- avg.age.death
L <- life.expectancy; r <- discount.rate
b <- beta; K <- modulation
CC <- adjustment
# do calculations
if(discount.rate==0){
N*(K*CC*((exp(-b*a))/b^2)*((exp(-b*L))*
(-b*(L+a)-1)-(-b*a-1))+((1-K)*L))
} else {
N*(K*((CC*exp(r*a))/(-(r+b)^2))*((exp(-(r+b)*(L+a))*(-(r+b)*
(L+a)-1))-(exp(-(r+b)*a)*(-(r+b)*a-1)))+((1-K)/r)*((1-exp(-r*L))))
}
}
| /scratch/gouwar.j/cran-all/cranData/yll/R/yll.R |
#' Find the Beginning or End of Period
#'
#' Each of `bop` and `eop` contains a list of functions, whose names all
#' consist of two letters, the first of which stands for **l**ast, **t**his, **n**ext
#' while the second stands for **y**ear, **q**uarter, **m**onth, **w**eek.
#' For example, `eop$ty()` means "the **e**nding **o**f **p**eriod of **t**his **y**ear"
#' and `bop$lm()` means "the **b**eginning **o**f **p**eriod of **l**ast **m**onth".
#' @details All functions' signatures are the same, with only one argument
#' `x`, which could be a `Date` or values that can be converted to `Date` via [ymd()].
#' @usage NULL
#' @format NULL
#' @examples
#' bop$ty(as.Date("2021-03-02"))
#' ## supports 'YMD' formatted integer or string
#' bop$ty(210302)
#' eop$tm(200201)
#'
#' @name beop
#' @export
eop <- list(
ly = function(x = Sys.Date()) period_begin(x, 'year') - 1,
ty = function(x = Sys.Date()) period_end(x, 'year'),
ny = function(x = Sys.Date()) period_end(period_end(x, 'year') + 1, 'year'),
lq = function(x = Sys.Date()) period_begin(x, 'quarter') - 1,
tq = function(x = Sys.Date()) period_end(x, 'quarter'),
nq = function(x = Sys.Date()) period_end(period_end(x, 'quarter') + 1, 'quarter'),
lm = function(x = Sys.Date()) period_begin(x, 'month') - 1,
tm = function(x = Sys.Date()) period_end(x, 'month'),
nm = function(x = Sys.Date()) period_end(period_end(x, 'month') + 1, 'month'),
lw = function(x = Sys.Date()) period_begin(x, 'week') - 1,
tw = function(x = Sys.Date()) period_end(x, 'week'),
nw = function(x = Sys.Date()) period_end(period_end(x, 'week') + 1, 'week')
)
#' @usage NULL
#' @format NULL
#' @name beop
#' @export
bop <- list(
ly = function(x = Sys.Date()) period_begin(period_begin(x, 'year') - 1, 'year'),
ty = function(x = Sys.Date()) period_begin(x, 'year'),
ny = function(x = Sys.Date()) period_end(x, 'year') + 1,
lq = function(x = Sys.Date()) period_begin(period_begin(x, 'quarter') - 1, 'quarter'),
tq = function(x = Sys.Date()) period_begin(x, 'quarter'),
nq = function(x = Sys.Date()) period_end(x, 'quarter') + 1,
lm = function(x = Sys.Date()) period_begin(period_begin(x, 'month') - 1, 'month'),
tm = function(x = Sys.Date()) period_begin(x, 'month'),
nm = function(x = Sys.Date()) period_end(x, 'month') + 1,
lw = function(x = Sys.Date()) period_begin(period_begin(x, 'week') - 1, 'week'),
tw = function(x = Sys.Date()) period_begin(x, 'week'),
nw = function(x = Sys.Date()) period_end(x, 'week') + 1
)
| /scratch/gouwar.j/cran-all/cranData/ymd/R/beop.R |
#' Fast Date Part Extracting
#'
#' These date helper functions provide the similar functionalities like in `data.table` or
#' `lubridate` package. They are implemented by the Rust Lang's standard library and very
#' fast.
#'
#' @param ref_date, a Date vector. It will try to convert the input to date via [ymd()],
#' if the input is not a Date.
#' @return an integer vector
#' @details
#' * year, month, quarter: get the year, month, quarter part
#' * yday: the day of year
#' * mday: the day of month
#' * wday: the day of the week (Sunday is 1)
#' * isoweek: ISO 8601 week
#' * isowday: the day of week (ISO 8601 weekday number, Monday is 1)
#' @references
#' ISO week day, https://en.wikipedia.org/wiki/ISO_week_date
#' ISO 8601, https://en.wikipedia.org/wiki/ISO_8601
#' @examples
#' year(210205)
#' month(210205)
#' quarter(210205)
#' yday(210205)
#' mday(210205)
#' wday(210117)
#' isowday(210117)
#' isoweek(210101)
#'
#' @name date_part
NULL
| /scratch/gouwar.j/cran-all/cranData/ymd/R/date-part.R |
# Generated by extendr: Do not edit by hand
# nolint start
#
# This file was created with the following call:
# .Call("wrap__make_ymd_wrappers", use_symbols = TRUE, package_name = "ymd")
#' @docType package
#' @usage NULL
#' @useDynLib ymd, .registration = TRUE
NULL
rust_ymd <- function(x) .Call(wrap__rust_ymd, x)
period_begin <- function(x, unit) .Call(wrap__period_begin, x, unit)
period_end <- function(x, unit) .Call(wrap__period_end, x, unit)
#' Calculate the date before / after months
#' @param ref_date a Date vector
#' @param months the number of months that's added to `ref_date`
#' @note The function name is the same as the Excel function `EDATE()` and
#' does the same. It returns the date that is the indicated number of months
#' before or after the ref date.
#' @examples
#' edate(as.Date("2020-01-31"), 1)
#' ## supports 'YMD' formatted integer or string
#' edate(200131, 1)
#' edate(200229, -12)
#'
#' @export
edate <- function(ref_date, months) .Call(wrap__edate, ref_date, months)
#' @rdname date_part
#' @export
year <- function(ref_date) .Call(wrap__year, ref_date)
#' @rdname date_part
#' @export
month <- function(ref_date) .Call(wrap__month, ref_date)
#' @rdname date_part
#' @export
quarter <- function(ref_date) .Call(wrap__quarter, ref_date)
#' @rdname date_part
#' @export
isoweek <- function(ref_date) .Call(wrap__isoweek, ref_date)
#' @rdname date_part
#' @export
isowday <- function(ref_date) .Call(wrap__isowday, ref_date)
#' @rdname date_part
#' @export
wday <- function(ref_date) .Call(wrap__wday, ref_date)
#' @rdname date_part
#' @export
mday <- function(ref_date) .Call(wrap__mday, ref_date)
#' @rdname date_part
#' @export
yday <- function(ref_date) .Call(wrap__yday, ref_date)
# nolint end
| /scratch/gouwar.j/cran-all/cranData/ymd/R/extendr-wrappers.R |
#' Convert 'YMD' format integer or string to Date
#'
#' Transform integer or strings vectors in 'YMD' format to Date objects.
#' It intends to only support limited formats (no separator or one of
#' '.', ' ', '-' and '/' separators). See the possible formats in examples.
#'
#' @param x An integer or string vector in 'YMD' format. Double
#' values without the decimal part are allowed.
#' @param ... The same as `x`. It will be merged into one vector with `x`.
#' It's convinient for interactive use.
#'
#' @return A Date object. When the parse fails for certain input,
#' the value returned would be `NA`, silently.
#'
#' @examples
#' ymd(c(210326, 19981225))
#' ymd(c("2020/1/8", "20 1 7", "1998.7.1", "1990-02-03"))
#' ymd(210420, 180322)
#'
#' @export
ymd <- function(x, ...) {
if (...length()) {
x <- c(x, unlist(list(...)))
}
rust_ymd(x)
}
| /scratch/gouwar.j/cran-all/cranData/ymd/R/ymd.R |
.onLoad <- function(libname, pkgname) {
}
| /scratch/gouwar.j/cran-all/cranData/ymd/R/zzz.R |
# The following fields in DESCRIPTION can be used for customizing the behavior.
#
# Config/<package name>/MSRV (optional):
# Minimum Supported Rust version (e.g. 1.41.0). If this is specified, errors
# when the installed cargo is newer than the requirement.
SYSINFO_OS <- tolower(Sys.info()[["sysname"]])
SYSINFO_MACHINE <- Sys.info()[["machine"]]
HAS_32BIT_R <- dir.exists(file.path(R.home(), "bin", "i386"))
USE_UCRT <- identical(R.version$crt, "ucrt")
# Utilities ---------------------------------------------------------------
#' Read a field of the package's DESCRIPTION file
#'
#' The field should have the prefix
#'
#' @param field
#' Name of a field without prefix (e.g. `"check_cargo"`).
#' @param prefix
#' Prefix of the field (e.g. `"Config/rextendr/`).
#' @param optional
#' If `TRUE`, return `NA` when there's no field. Otherwise raise an error.
#'
get_desc_field <- function(field, prefix = DESC_FIELD_PREFIX, optional = TRUE) {
field <- paste0(prefix, field)
if (length(field) != 1) {
stop("Field must be length one of character vector")
}
# `read.dcf()` always succeeds even when the field is missing.
# Detect the failure by checking NA
x <- read.dcf("DESCRIPTION", fields = field)[[1]]
if (isTRUE(is.na(x)) && !isTRUE(optional)) {
stop("Failed to get the field ", field, " from DESCRIPTION")
}
x
}
# This is tricky; while DESC_FIELD_PREFIX is used in get_desc_field()'s default,
# this variable is defined by get_desc_field(). It's no problem as long as the
# default is not used before it exists!
DESC_FIELD_PREFIX <- paste0("Config/", get_desc_field("Package", prefix = ""), "/")
safe_system2 <- function(cmd, args) {
result <- list(success = FALSE, output = "")
output_tmp <- tempfile()
on.exit(unlink(output_tmp, force = TRUE))
suppressWarnings(ret <- system2(cmd, args, stdout = output_tmp))
if (!identical(ret, 0L)) {
return(result)
}
result$output <- readLines(output_tmp)
result$success <- TRUE
result
}
# check_cargo -------------------------------------------------------------
#' Check if the cargo command exists and the version is above the requirements
#'
#' @return
#' `TRUE` invisibly if no error was found.
check_cargo <- function() {
### Check if cargo command works without error ###
cat("*** Checking if cargo is installed\n")
cargo_cmd <- "cargo"
cargo_args <- "version"
res_version <- safe_system2(cargo_cmd, cargo_args)
if (!isTRUE(res_version$success)) {
stop(errorCondition("cargo command is not available", class = c("error_cargo_check", "error")))
}
### Check the version ###
msrv <- get_desc_field("MSRV", optional = TRUE)
if (isTRUE(!is.na(msrv))) {
cat("*** Checking if cargo is newer than the required version\n")
version <- res_version$output
ptn <- "cargo\\s+(\\d+\\.\\d+\\.\\d+)"
m <- regmatches(version, regexec(ptn, version))[[1]]
if (length(m) != 2) {
stop(errorCondition("cargo version returned unexpected result", class = c("error_cargo_check", "error")))
}
if (package_version(m[2]) < package_version(msrv)) {
msg <- sprintf("The installed version of cargo (%s) is older than the requirement (%s)", m[2], msrv)
stop(errorCondition(msg, class = c("error_cargo_check", "error")))
}
}
### Check the targets ###
if (identical(SYSINFO_OS, "windows")) {
cat("*** Checking if the required Rust target is installed\n")
targets <- safe_system2("rustup", c("target", "list", "--installed"))
# rustup might not exist if Rust is installed directly via the .msi installer
# in that case, just ignore and pray that the compilation will succeed.
if (!isTRUE(targets$success)) {
return(invisible(TRUE))
}
if (!isTRUE("x86_64-pc-windows-gnu" %in% targets$output)) {
msg <- "The required target x86_64-pc-windows-gnu is not installed"
stop(errorCondition(msg, class = c("error_cargo_check", "error")))
}
}
invisible(TRUE)
}
# MAIN --------------------------------------------------------------------
### Check cargo toolchain ###
cargo_check_result <- tryCatch(
check_cargo(),
# Defer errors if it's raised by functions here
error_cargo_check = function(e) e$message
)
# If cargo is confirmed fine, exit here. But, even if the cargo is not available
# or too old, it's not the end of the world. There might be a pre-compiled
# binary available for the platform.
if (isTRUE(cargo_check_result)) {
cat("*** cargo is ok\n")
quit("no", status = 0)
}
cat(sprintf("
-------------- ERROR: CONFIGURATION FAILED --------------------
[cargo check result]
%s
Please refer to <https://www.rust-lang.org/tools/install> to install Rust.
---------------------------------------------------------------
", cargo_check_result))
quit("no", status = 2)
| /scratch/gouwar.j/cran-all/cranData/ymd/tools/configure.R |
devel_prefix <- if (isTRUE(grepl("devel", R.version$status, fixed = TRUE))) "-devel" else ""
r_version <- sprintf("%s.%s%s", R.version$major, R.version$minor, devel_prefix)
cat(r_version)
| /scratch/gouwar.j/cran-all/cranData/ymd/tools/print_r_version.R |
#' @importFrom utils getFromNamespace
launch_yaml_addin <- function() {
stop_if_not_installed(c("miniUI", "shinyBS"))
addin_dir <- system.file("addin", "new_yaml", package = "ymlthis")
app <- shiny::shinyAppDir(addin_dir)
shiny::runGadget(
app,
viewer = shiny::dialogViewer("New YAML", height = 700)
)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/addins.R |
#' Read and write to JSON and TOML
#'
#' Read JSON and TOML files in as `yml` objects with `read_*()`. Write `yml`
#' objects out as JSON and YAML files with `write_as_*()`. You can also provide
#' `write_as_*()` a path to an existing `.yml` file to translate to JSON or
#' TOML. These functions rely on Hugo and blogdown, so you must have blogdown
#' installed.
#'
#' @template describe_yml_param
#' @param path a path to a JSON or TOML file
#' @param out The path to write out to. If `NULL`, will write to the `path` but
#' change the file extension to `.toml` or `.json`.
#' @param quiet Logical. Whether to message about what is happening.
#' @inheritParams use_yml_file
#'
#' @return a `yml` object (if reading) or the path (if writing)
#' @export
read_json <- function(path) {
convert_metadata(path = path, to = "YAML")
}
#' @export
#' @rdname read_json
read_toml <- function(path) {
convert_metadata(path = path, to = "YAML")
}
#' @export
#' @rdname read_json
write_as_json <- function(.yml = NULL, path = NULL, out = NULL, build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
write_as_metadata(
.yml = .yml,
path = path,
out = out,
extension = ".json",
to = "JSON",
build_ignore = build_ignore,
git_ignore = git_ignore,
quiet = quiet
)
}
#' @export
#' @rdname read_json
write_as_toml <- function(.yml = NULL, path = NULL, out = NULL, build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
write_as_metadata(
.yml = .yml,
path = path,
out = out,
extension = ".toml",
to = "TOML",
build_ignore = build_ignore,
git_ignore = git_ignore,
quiet = quiet
)
}
write_as_metadata <- function(.yml, path, out, extension, to, build_ignore, git_ignore, quiet = FALSE) {
stop_if_both_args_given(.yml, path)
if (!is.null(.yml)) {
path <- write_temp_yaml(.yml)
on.exit(unlink(path), add = TRUE)
}
if (is.null(out)) out <- swap_extension(path, extension)
if (build_ignore) usethis::use_build_ignore(out)
if (git_ignore) usethis::use_git_ignore(out)
convert_metadata(path = path, to = to, out = out, quiet = FALSE)
}
swap_extension <- function(path, ext) paste0(fs::path_ext_remove(path), ext)
stop_if_both_args_given <- function(.yml, path) {
if (!is.null(.yml) && !is.null(path)) {
stop(
"You cannot specify both a `yml` object and a file to convert",
call. = FALSE
)
}
}
write_temp_yaml <- function(.yml) {
.file <- tempfile(fileext = ".yml")
yml_txt <- yaml::as.yaml(
.yml,
handlers = yml_handlers(),
column.major = FALSE
)
writeLines(yml_txt, .file)
.file
}
convert_metadata <- function(path, to = c("YAML", "TOML", "JSON"), out = NULL, quiet = FALSE) {
stop_if_blogdown_not_installed()
on.exit(unlink_temporary_dir(), add = TRUE)
to <- match.arg(to)
file_to_convert <- fs::path_file(path) %>%
fs::path_ext_remove() %>%
paste0(".md")
file_to_convert <- file.path(temporary_dir(), "content", file_to_convert)
file_type <- fs::path_ext(path) %>%
tolower()
fs::dir_create(file.path(temporary_dir(), "content"))
rewrite_with_fences(path, file_to_convert, file_type = file_type)
writeLines(
c("baseurl = \"/\"", "builddrafts = true"),
file.path(temporary_dir(), "config.toml")
)
withr::with_dir(
temporary_dir(),
blogdown::hugo_cmd(
args = c("convert", paste0("to", to), "--unsafe"),
stdout = TRUE
)
)
if (to == "YAML") {
post_yml <- yaml::yaml.load_file(file_to_convert) %>%
as_yml()
return(post_yml)
}
file_txt <- readLines(file_to_convert) %>%
purrr::discard(~.x %in% c("---", "+++", "..."))
usethis::write_over(out, file_txt, quiet = quiet)
invisible(out)
}
rewrite_with_fences <- function(from, to, file_type) {
fences <- switch(
file_type,
yml = "---",
yaml = "---",
toml = "+++",
json = NULL
)
file_txt <- readLines(from)
if (!is.null(fences) && file_txt[[1]] != fences) {
file_txt <- c(fences, file_txt, fences)
}
writeLines(file_txt, to)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/convert_metadata.R |
#' Draw an tree of YAML hierarchy
#'
#' `draw_yml_tree()` draws an ASCII tree of the hierarchy of a given `yml`
#' object to the console.
#'
#' @template describe_yml_param
#' @param indent a character vector used to indent the tree
#'
#' @return invisibly, `.yml`
#' @export
#'
#' @examples
#' # draw the most recently used `yml`
#' draw_yml_tree()
#'\donttest{
#' yml() %>%
#' yml_output(
#' pdf_document(keep_tex = TRUE),
#' html_document()
#' ) %>%
#' draw_yml_tree()
#'}
draw_yml_tree <- function(.yml = last_yml(), indent = "") {
any_vectors <- any(purrr::map_lgl(.yml, is_long_vector))
if (any_vectors) {
print_vector_leaves(.yml, indent)
return(invisible(.yml))
}
nested <- purrr::map_lgl(.yml, is.list)
for (i in seq_along(.yml)) {
if (i == length(.yml)) {
if (nested[i]) {
if (!rlang::is_named(.yml[i])) {
print_vector_leaves(.yml[[i]], indent)
next
}
if (is_long_vector(.yml[[i]])) {
print_vector_leaves(.yml[[i]], indent)
next
}
leaf <- .yml[i] %>%
color_yml() %>%
split_pluck() %>%
purrr::pluck(1)
cat(paste0(indent, end_tab(), leaf, "\n"))
draw_yml_tree(.yml[[i]], paste0(indent, " "))
} else {
leaf <- color_yml(.yml[i])
cat(paste0(indent, end_tab(), leaf))
}
} else {
if (nested[i]) {
if (!rlang::is_named(.yml[i])) {
print_vector_leaves(.yml[[i]], indent)
next
}
if (is_long_vector(.yml[[i]])) {
marker <- ifelse(i != length(.yml), pipe(), " ")
print_vector_leaves(.yml[[i]], paste0(indent, marker, " "))
next
}
leaf <- .yml[i] %>%
color_yml() %>%
split_pluck() %>%
purrr::pluck(1)
cat(paste0(indent, tab(), leaf, "\n"))
draw_yml_tree(.yml[[i]], paste0(indent, pipe(), " "))
} else {
if (!rlang::is_named(.yml[i])) {
print_vector_leaves(.yml[[i]], indent)
next
}
if (is_long_vector(.yml[[i]])) {
return(invisible(.yml))
}
leaf <- color_yml(.yml[i])
leaf_indent <- paste0(indent, tab())
cat(paste0(leaf_indent, leaf))
}
}
}
invisible(.yml)
}
is_long_vector <- function(x) {
is.atomic(x) && length(x) > 1
}
print_vector_leaves <- function(x, indent) {
if (is.atomic(x)) {
leaf <- color_yml(x) %>%
split_pluck()
} else {
leaf <- vector("character", length(x))
for (i in seq_along(x)) {
leaf[i] <- color_yml(x[i]) %>%
split_pluck() %>%
purrr::pluck(1)
}
}
for (i in seq_along(x)) {
if (i == length(x)) {
cat(paste0(indent, end_tab(), leaf[i], "\n"))
} else {
cat(paste0(indent, tab(), leaf[i], "\n"))
}
if (is_long_vector(x[[i]])) {
marker <- ifelse(i != length(x), pipe(), " ")
print_vector_leaves(x[[i]], paste0(indent, marker, " "))
}
if (is.list(x[[i]])) {
marker <- ifelse(i != length(x), pipe(), " ")
draw_yml_tree(x[[i]], paste0(indent, marker, " "))
}
}
}
pipe <- function() box_chars("v")
tab <- function() paste0(box_chars("j"), box_chars("h"), box_chars("h"), " ")
end_tab <- function() paste0(box_chars("l"), box_chars("h"), box_chars("h"), " ")
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/draw_tree.R |
#' Write code chunks programmatically
#'
#' `code_chunk()` assembles a knitr code chunk as a character vector.
#' `setup_chunk()` is a wrapper around `code_chunk()` to create setup chunks. By
#' default it uses `include = FALSE` and inserts `knitr::opts_chunk$set(echo =
#' TRUE)` into the chunk body. These are helper functions to write R Markdown
#' bodies for [use_rmarkdown()].
#'
#' @param chunk_code An expression. Surround with `{}` to capture multiple
#' lines.
#' @param chunk_name The name of the chunk
#' @param chunk_args A `list` of chunk options
#'
#' @return a character vector
#' @export
#'
#' @examples
#' \donttest{
#'setup_chunk()
#'
#' code_chunk({
#' yml() %>%
#' yml_output(pdf_document())
#' }, chunk_name = "yml_example")
#' }
code_chunk <- function(chunk_code, chunk_name = NULL, chunk_args = NULL) {
chunk_args <- splice_args(rlang::enquo(chunk_args))
if (!is.null(chunk_name) && chunk_args != "") {
chunk_name <- glue::glue("{chunk_name}, ")
}
chunk_code <- rlang::enexpr(chunk_code) %>%
rlang::expr_text() %>%
stringr::str_replace_all("^\\{\n|\\}$", "") %>%
stringr::str_trim() %>%
stringr::str_replace("\n$", "") %>%
split_pluck() %>%
stringr::str_replace("^\\s{4}", "") %>%
glue::glue_collapse("\n")
chunk_header <- paste0(
"r",
ifelse(is.null(chunk_name) && chunk_args == "", "", " "),
chunk_name,
chunk_args
)
glue::glue(
"```{<<chunk_header>>}\n<<chunk_code>>\n```",
.open = "<<",
.close = ">>"
)
}
#' @rdname code_chunk
#' @export
setup_chunk <- function(chunk_code = NULL, chunk_args = list(include = FALSE)) {
arg_null <- rlang::enquo(chunk_code) %>%
rlang::quo_is_null()
if (arg_null) {
code_chunk_txt <- code_chunk(
chunk_code = {knitr::opts_chunk$set(echo = TRUE)},
chunk_name = "setup",
chunk_args = !!rlang::enquo(chunk_args)
)
} else {
code_chunk_txt <- code_chunk(
chunk_code = chunk_code,
chunk_name = "setup",
chunk_args = !!rlang::enquo(chunk_args)
)
}
code_chunk_txt
}
splice_args <- function(x) {
# preserve calls without evaluating
if (rlang::quo_is_null(x)) return("")
args <- rlang::call_args(x)
purrr::map2_chr(names(args), args, glue_args) %>%
glue::glue_collapse(", ")
}
glue_args <- function(.x, .y) {
if (is.character(.y)) {
glue::glue("{.x} = \"{.y}\"")
} else {
glue::glue("{.x} = {.y}")
}
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/markdownr.R |
read_rmd <- function(path, output = c("frontmatter", "body")) {
output <- match.arg(output)
input_lines <- readLines(path)
delimiters <- grep("^(---|\\.\\.\\.)\\s*$", input_lines)
if (!validate_front_matter(delimiters, input_lines)) {
return(yml_blank())
}
return_lines <- (delimiters[1]):(delimiters[2])
if (output == "body") return_lines <- -return_lines
input_lines[return_lines]
}
is_blank <- function(x) {
purrr::is_empty(x) || all(grepl("^\\s*$", x))
}
validate_front_matter <- function(delimiters, input_lines) {
# a few conditions
more_than_one <- length(delimiters) >= 2
two_after_one <- (delimiters[2] - delimiters[1] > 1)
all_spaces <- grepl("^---\\s*$", input_lines[delimiters[1]])
if (more_than_one && two_after_one && all_spaces) {
valid <- ifelse(
# if first line, valid
delimiters[1] == 1,
TRUE,
# if not, check that what's before is blank
is_blank(input_lines[1:delimiters[1] - 1])
)
return(valid)
}
# if none of these, YAML is not validated
FALSE
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/read_yaml.R |
#' Use pandoc templates and custom highlight themes
#'
#' Pandoc has several built in templates and code highlighting themes that can
#' be customized and included in the `template` and `highlight-style` YAML
#' fields, respectively. `pandoc_template_types()` and
#' `pandoc_highlight_styles()` return the available templates and highlight
#' styles in pandoc, respectively. `use_pandoc_template()` creates a new file
#' based on a template from pandoc or R Markdown and
#' `use_pandoc_highlight_style()` creates a new highlight theme file based on an
#' existing pandoc theme.
#'
#' @param theme The name of the theme
#' @param type The template type
#' @param source The template source ("pandoc" or "rmarkdown")
#' @param path The path to write the file to
#'
#' @return a character vector
#' @export
pandoc_template_types <- function() {
c(
"asciidoc",
"asciidoctor",
"commonmark",
"context",
"docbook4",
"docbook5",
"dokuwiki",
"dzslides",
"epub2",
"epub3",
"haddock",
"html4",
"html5",
"icml",
"jats",
"jira",
"latex",
"latex.orig",
"latex.rej",
"man",
"markdown",
"mediawiki",
"ms",
"muse",
"opendocument",
"opml",
"org",
"plain",
"revealjs",
"rst",
"rtf",
"s5",
"slideous",
"slidy",
"tei",
"texinfo",
"textile",
"xwiki",
"zimwiki"
)
}
#' @export
#' @rdname pandoc_template_types
pandoc_highlight_styles <- function() {
stop_if_pandoc_not_installed()
system2(rmarkdown::pandoc_exec(), "--list-highlight-styles", stdout = TRUE)
}
#' @export
#' @rdname pandoc_template_types
use_pandoc_template <- function(type, path, source = c("rmarkdown", "pandoc")) {
stop_if_pandoc_not_installed()
source <- match.arg(source)
if (source == "rmarkdown") {
x <- switch(
type,
latex = read_file("latex", "default.tex"),
html = read_file("h", "default.html"),
slidy = read_file("slidy", "default.html"),
ioslides = read_file("ioslides", "default.html"),
html_fragment = read_file("fragment", "default.html"),
latex_fragment = read_file("fragment", "default.tex"),
)
}
if (source == "pandoc") {
args <- glue::glue("--print-default-template={type}")
x <- system2(rmarkdown::pandoc_exec(), args = args, stdout = TRUE)
}
usethis::write_over(path, x)
}
read_file <- function(...) {
readLines(
system.file(
"rmd",
...,
package = "rmarkdown",
mustWork = TRUE
)
)
}
#' @export
#' @rdname pandoc_template_types
use_pandoc_highlight_style <- function(theme, path) {
stop_if_pandoc_not_installed()
if (!grepl("\\.theme$", path)) {
stop("`path` must end in `.theme`", call. = FALSE)
}
args <- glue::glue("--print-highlight-style={theme}")
x <- system2(rmarkdown::pandoc_exec(), args = args, stdout = TRUE)
usethis::write_over(path, x)
}
stop_if_pandoc_not_installed <- function() {
stop_if_rmarkdown_not_installed()
if (!rmarkdown::pandoc_available()) {
stop("pandoc must be installed to use this function")
}
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/use_pandoc.R |
#' Copy YAML code to your clipboard or write to a new R Markdown file
#'
#' `use_yml()` takes a `yml` object and puts the resulting YAML on your
#' clipboard to paste into an R Markdown or YAML file. `use_rmarkdown()` takes
#' the `yml` object and writes it to a new R Markdown file. You can add text to
#' include in the body of the file. If it's not specified, `use_rmarkdown()`
#' will use [`setup_chunk()`] by default. You can also set a default for `body`
#' using `options(ymlthis.rmd_body = "{your text}")`; see [use_rmd_defaults()].
#' Together with specifying default YAML (see [use_yml_defaults()]),
#' `use_rmarkdown()` also serves as an ad-hoc way to make R Markdown templates.
#' You may also supply `use_rmarkdown()` with an existing R Markdown file from
#' which to read the YAML header; the YAML header from the template is then
#' combined with `.yml`, if it's supplied, and written to a new file.
#' `use_index_rmd()` is a wrapper around `use_rmarkdown()` that specifically
#' writes to a file called `index.Rmd`. By default, `use_yml()` and
#' `use_rmarkdown()` use the most recently printed YAML via [`last_yml()`].
#'
#' @template describe_yml_param
#' @param path A file path to write R Markdown file to
#' @param template An existing R Markdown file to read YAML from
#' @param include_yaml Logical. Include the template YAML?
#' @param include_body Logical. Include the template body?
#' @param body A character vector to use in the body of the R Markdown file. If
#' no template is set, checks `getOption("ymlthis.rmd_body")` (see
#' [`use_rmd_defaults()`]) and otherwise uses [`setup_chunk()`].
#' @param quiet Logical. Whether to message about what is happening.
#' @param open_doc Logical. Open the document after it's created? By default,
#' this is `TRUE` if it is an interactive session and `FALSE` if not. Also
#' checks that RStudio is available.
#' @param overwrite Logical. If `TRUE`, overwrites the file without asking for
#' permission. If `FALSE`, asks interactively if the user wishes to do so.
#' Checks the user's `usethis.overwrite` option if set and is otherwise
#' `FALSE` by default.
#'
#' @return `use_yml()` invisibly returns the input `yml` object
#' @export
#' @seealso [`code_chunk()`] [`setup_chunk()`]
use_yml <- function(.yml = last_yml()) {
return_yml_code(.yml)
}
#' @rdname use_yml
#' @export
use_rmarkdown <- function(.yml = last_yml(), path, template = NULL, include_yaml = TRUE,
include_body = TRUE, body = NULL, quiet = FALSE,
open_doc = interactive(),
overwrite = getOption("usethis.overwrite", FALSE)) {
if (!is.null(template) && fs::is_dir(template)) {
template_skeleton <- file.path(template, "skeleton", "skeleton.Rmd")
if (!file.exists(template_skeleton)) {
stop("A directory must include an R Markdown template in `skeleton/skleton.Rmd`", call. = FALSE)
}
template <- template_skeleton
}
if (!is.null(template) && include_yaml) {
existing_yaml <- read_rmd(template) %>%
yml_load()
.yml <- combine_yml(.yml, existing_yaml)
}
rmarkdown_txt <- capture_yml(.yml)
if (is.null(template) && is.null(body)) body <- getOption("ymlthis.rmd_body")
if (is.null(template) && is.null(body)) body <- c("", setup_chunk())
rmarkdown_txt <- c(rmarkdown_txt, body)
if (!is.null(template) && include_body) {
existing_body <- read_rmd(template, output = "body")
rmarkdown_txt <- c(rmarkdown_txt, existing_body)
}
if (fs::file_exists(path) && isTRUE(overwrite)) {
fs::file_delete(path)
}
usethis::write_over(path, rmarkdown_txt, quiet = quiet)
if (rstudioapi::isAvailable() && open_doc) rstudioapi::navigateToFile(path, line = 2)
invisible(path)
}
#' @rdname use_yml
#' @export
use_index_rmd <- function(.yml = last_yml(), path, template = NULL, include_yaml = TRUE,
include_body = TRUE, body = NULL, quiet = FALSE, open_doc = interactive()) {
index_rmd_path <- file_path(path, "index.Rmd")
use_rmarkdown(
.yml = .yml,
path = index_rmd_path,
template = template,
include_yaml = include_yaml,
include_body = include_body,
body = body,
quiet = quiet,
open_doc = open_doc
)
}
combine_yml <- function(x, y) {
x[names(y)] <- y
x
}
return_yml_code <- function(.yml) {
yaml_text <- capture_yml(.yml)
usethis::ui_code_block(yaml_text)
usethis::ui_todo("Paste into R Markdown or YAML file")
invisible(.yml)
}
#' Write YAML to file
#'
#' Write `yml` objects to a file. `use_yml_file()` writes to any given file
#' name. `use_output_yml()` creates file `_output.yml`, which can be used by
#' multiple R Markdown documents. All documents located in the same directory as
#' `_output.yml` will inherit its output options. Options defined within
#' document YAML headers will override those specified in `_output.yml`. Note
#' that `use_output_yml()` plucks the output field from `yml`; any other YAML
#' top-level fields will be ignored. `use_site_yml` creates `_site.yml` for use
#' with R Markdown websites and third-party tools like the distill package (see
#' [the R Markdown book for
#' more](https://bookdown.org/yihui/rmarkdown/rmarkdown-site.html#)).
#' `use_navbar_yml` is a special type of site YAML that only specifies the
#' navbar in `_navbar.yml` `use_pkgdown_yml()` and `use_bookdown_yml()` write
#' YAML files specific to those packages; see the
#' [pkgdown](https://pkgdown.r-lib.org/articles/pkgdown.html) and
#' [blogdown](https://bookdown.org/yihui/bookdown/configuration.html)
#' documentation for more.
#'
#' By default, the yaml package adds a new line to the end of files. Some
#' environments, such as RStudio Projects, allow you to append new lines
#' automatically. Thus, you may end up with 2 new lines at the end of your file.
#' If you'd like to automatically remove the last new line in the file, set
#' `options(ymlthis.remove_blank_line = TRUE)`.
#'
#' @template describe_yml_param
#' @param path a file path to write the file to
#' @param build_ignore Logical. Should the file be added to the `.Rbuildignore`
#' file?
#' @param git_ignore Logical. Should the file be added to the `.gitignore` file?
#' @param quiet Logical. Whether to message about what is happening.
#'
#' @seealso yml_bookdown_opts yml_bookdown_site yml_pkgdown yml_pkgdown_articles
#' yml_pkgdown_docsearch yml_pkgdown_figures yml_pkgdown_news
#' yml_pkgdown_reference
#' @export
#' @rdname use_file_yml
use_yml_file <- function(.yml = NULL, path, build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
write_yml_file(.yml, path, build_ignore = build_ignore, git_ignore = git_ignore, quiet = quiet)
}
#' @export
#' @rdname use_file_yml
use_output_yml <- function(.yml = NULL, path = ".", build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
yml_file_path <- file_path(path, "_output.yml")
if ("output" %nin% names(.yml)) stop("No output field found. Specify with `yml_output()`", call. = FALSE)
output <- yml_pluck(.yml, "output")
write_yml_file(output, yml_file_path, build_ignore = build_ignore, git_ignore = git_ignore, quiet = quiet)
}
#' @export
#' @rdname use_file_yml
use_site_yml <- function(.yml = NULL, path = ".", build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
yml_file_path <- file_path(path, "_site.yml")
write_yml_file(.yml, yml_file_path, build_ignore = build_ignore, git_ignore = git_ignore, quiet = quiet)
}
#' @export
#' @rdname use_file_yml
use_navbar_yml <- function(.yml = NULL, path = ".", build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
yml_file_path <- file_path(path, "_navbar.yml")
write_yml_file(.yml, yml_file_path, build_ignore = build_ignore, git_ignore = git_ignore, quiet = quiet)
}
#' @export
#' @rdname use_file_yml
use_pkgdown_yml <- function(.yml = NULL, path = ".", build_ignore = TRUE, git_ignore = FALSE, quiet = FALSE) {
yml_file_path <- file_path(path, "_pkgdown.yml")
write_yml_file(.yml, yml_file_path, build_ignore = build_ignore, git_ignore = git_ignore, quiet = quiet)
}
#' @export
#' @rdname use_file_yml
use_bookdown_yml <- function(.yml = NULL, path = ".", build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
yml_file_path <- file_path(path, "_bookdown.yml")
write_yml_file(.yml, yml_file_path, build_ignore = build_ignore, git_ignore = git_ignore, quiet = quiet)
}
write_yml_file <- function(.yml, path, build_ignore = FALSE, git_ignore = FALSE, quiet = FALSE) {
if (build_ignore) usethis::use_build_ignore(path)
if (git_ignore) usethis::use_git_ignore(path)
if (file.exists(path)) {
question <- glue::glue("Overwrite pre-existing file {usethis::ui_path(path)}?")
go_ahead <- usethis::ui_yeah(question)
if (!go_ahead) return(invisible(path))
fs::file_delete(path)
}
if (!is.null(.yml)) {
if (is.character(.yml) && length(.yml) == 1) {
if (check_remove_blank_line()) .yml <- remove_blank_line(.yml)
usethis::write_over(path, .yml, quiet = quiet)
return(invisible(path))
}
yml_txt <- yaml::as.yaml(
.yml,
handlers = yml_handlers(),
column.major = FALSE
)
if (check_remove_blank_line()) yml_txt <- remove_blank_line(yml_txt)
usethis::write_over(path, yml_txt, quiet = quiet)
return(invisible(path))
}
fs::file_create(path)
usethis::ui_done("Writing {usethis::ui_path(path)}")
invisible(path)
}
file_path <- function(path, .file) {
file.path(normalizePath(path), .file)
}
check_remove_blank_line <- function() {
remove_line_opt <- getOption("ymlthis.remove_blank_line")
option_set <- !is.null(remove_line_opt)
if (option_set) {
if (!is.logical(remove_line_opt)) stop("option `ymlthis.remove_blank_line` must be either logical or `NULL`")
return(remove_line_opt)
}
FALSE
}
remove_blank_line <- function(x) {
stringr::str_remove(x, "\n$")
}
#' Set up default YAML
#'
#' `use_yml_defaults()` takes a `yml` object and places code on the clipboard
#' that will save the resulting YAML as the default for `yml()`. The code that
#' is placed on the clipboard is raw YAML passed to `ymlthis.default_yml` via
#' `options()`. Saving this code to your `.Rprofile` (see
#' [`usethis::edit_r_profile()`])) will allow [`yml()`] or
#' [`get_yml_defaults()`] to return the saved YAML. `use_rmd_defaults()` does
#' the same for `ymlthis.rmd_body`, which is used in [use_rmarkdown()] as the
#' body text of the created R Markdown file.
#'
#' @template describe_yml_param
#' @param x a character vector to use as the body text in [use_rmarkdown()].
#'
#' @seealso [yml()] [get_yml_defaults()]
#' @export
use_yml_defaults <- function(.yml) {
if (!is_yml(.yml) && !is.character(.yml)) {
usethis::ui_stop(
"`{usethis::ui_code(.yml)}` must be a `{usethis::ui_code(yml)}` \\
object or a `{usethis::ui_code(character)}` vector containing \\
valid YAML text"
)
}
if (is.character(.yml)) .yml <- as_yml(.yml)
.yml_text <- capture_yml(.yml) %>%
purrr::discard(~ .x == "---") %>%
glue::glue_collapse(sep = "\n")
.yml_code <- glue::glue("options(ymlthis.default_yml = \"{.yml_text}\")")
usethis::ui_code_block(.yml_code)
usethis::ui_todo(
"Run interactively or paste into .Rprofile \\
(perhaps using {usethis::ui_code('usethis::edit_r_profile()')})"
)
invisible(.yml)
}
#' @export
#' @rdname use_yml_defaults
use_rmd_defaults <- function(x) {
rmd_text <- glue::glue_collapse(x, sep = "\n")
usethis::ui_code_block("options(ymlthis.rmd_body = \"{rmd_text}\")")
usethis::ui_todo(
"Run interactively or paste into .Rprofile \\
(perhaps using {usethis::ui_code('usethis::edit_r_profile()')})"
)
invisible(x)
}
#' @export
#' @rdname use_yml_defaults
get_yml_defaults <- function() {
.yml <- getOption("ymlthis.default_yml")
if (is.null(.yml)) return(NULL)
if (is.character(.yml)) .yml <- yaml::yaml.load(.yml)
as_yml(.yml)
}
#' @export
#' @rdname use_yml_defaults
get_rmd_defaults <- function() {
getOption("ymlthis.rmd_body")
}
raw_yml <- function(x) {
if (isTRUE(getOption("knitr.in.progress"))) return(knitr::asis_output(x))
x
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/use_yml.R |
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
NULL
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/utils-pipe.R |
stop_if_not_installed <- function(pkg) {
rlang::check_installed(pkg, "Must be installed to use this function.")
}
stop_if_shiny_not_installed <- function() {
stop_if_not_installed("shiny")
}
stop_if_rmarkdown_not_installed <- function() {
stop_if_not_installed("rmarkdown")
}
stop_if_blogdown_not_installed <- function() {
stop_if_not_installed("blogdown")
}
stop_if_not_type <- function(x, type) {
if (is_yml_blank(x)) return(invisible(x))
if (!inherits(x, type)) {
x_text <- rlang::quo_text(rlang::quo(x))
stop_must_be_type(x_text, type)
}
invisible(x)
}
stop_if_not_all_type <- function(x, type) {
x_text <- rlang::quo_text(rlang::quo(x))
all_type <- all(purrr::map_lgl(x, inherits, type))
if (!all_type) {
x_text <- rlang::quo_text(rlang::quo(x))
stop_must_be_type(x_text, type)
}
}
stop_must_be_type <- function(x, type) {
usethis::ui_stop(
"{usethis::ui_code(x)} must be of type {usethis::ui_code(type)}"
)
}
warn_if_duplicate_fields <- function(yml_object, new_fields) {
fields <- names(new_fields)
duplicate_fields <- any(names(yml_object) %in% fields)
if (duplicate_fields) {
fields <- glue::glue("`{fields}`") %>%
glue::glue_collapse(sep = ", ", last = " and ")
msg <- glue::glue(
"Top-level fields {fields} already present. \\
Replacing the existing fields. \\
Use `yml_replace() if you want to replace fields without a warning."
)
warning(msg, call. = FALSE)
}
invisible(yml_object)
}
capture_yml <- function(.yml) {
withr::local_envvar(NO_COLOR = TRUE)
utils::capture.output(print(.yml))
}
split_pluck <- function(string) {
x <- stringr::str_split(string, "\n")
x[[1]]
}
prepend_namespace <- function(function_namespace, function_name) {
ifelse(
is.null(function_namespace),
function_name,
paste0(function_namespace, "::", function_name)
)
}
`%nin%` <- Negate("%in%")
# These are derived from https://github.com/r-lib/cli/blob/e9acc82b0d20fa5c64dd529400b622c0338374ed/R/tree.R#L111
box_chars <- function(.subset = NULL) {
if (is_utf8_output()) {
x <- list(
"h" = "\u2500", # horizontal
"v" = "\u2502", # vertical
"l" = "\u2514",
"j" = "\u251C"
)
} else {
x <- list(
"h" = "-", # horizontal
"v" = "|", # vertical
"l" = "\\",
"j" = "+"
)
}
if (!is.null(.subset)) {
return(x[[.subset]])
}
x
}
is_latex_output <- function() {
if (!("knitr" %in% loadedNamespaces())) return(FALSE)
get("is_latex_output", asNamespace("knitr"))()
}
is_utf8_output <- function() {
opt <- getOption("cli.unicode", NULL)
if (!is.null(opt)) {
isTRUE(opt)
} else {
l10n_info()$`UTF-8` && !is_latex_output()
}
}
temporary_dir <- function() {
tmp_dir_path <- file.path(tempdir(), "ymlthis_temp_dir__")
if (!fs::dir_exists(tmp_dir_path)) {
fs::dir_create(tmp_dir_path)
}
tmp_dir_path
}
unlink_temporary_dir <- function() {
tmp_dir_path <- file.path(tempdir(), "ymlthis_temp_dir__")
unlink(tmp_dir_path, recursive = TRUE, force = TRUE)
invisible(tmp_dir_path)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/utils.R |
#' Create a new yml object
#'
#' `yml()` initializes a `yml` object. `yml` objects create valid YAML and print
#' it cleanly to the console. By default, `yml()` looks for your name (using `
#' getOption("usethis.full_name")`, `getOption("devtools.name")`, and
#' `whoami::fullname()`) and uses today's date to use in the `author` and `date`
#' fields, respectively. If you've set default YAML in
#' `getOption("ymlthis.default_option")` (see [use_yml_defaults()]), `yml()`
#' will also use include those fields by default. `yml_empty()` is a wrapper
#' that doesn't use any of these default YAML fields. `yml()` and all
#' related`yml_*()` functions validate that the results are indeed valid YAML
#' syntax, although not every function is able to check that the input fields
#' are valid for the setting they are used in.
#'
#' @details
#'
#' `.yml` accepts a character vector of YAML, such as "author: Hadley Wickham",
#' an object returned by ymlthis functions that start with `yml_*()`, or a
#' `list` object (e.g. `list(author = "Hadley Wickham")`). `.yml` objects are
#' processed with [`as_yml()`], a wrapper around [`yaml::yaml.load()`]. See that
#' function for more details.
#'
#' @param .yml a character vector, `yml` object, or YAML-like list. See details.
#' @param get_yml logical. Use YAML stored in
#' `getOption("ymlthis.default_option")`? By default, `yml()` includes if it
#' exists.
#' @param author logical. Get default author name?
#' @param date logical. Get default date?
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml()
#'
#' yml(date = FALSE)
#'
#' "author: Hadley Wickham\ndate: 2014-09-12" %>%
#' yml() %>%
#' yml_title("Tidy Data") %>%
#' yml_keywords(
#' c("data cleaning", "data tidying", "relational databases", "R")
#' )
#'\donttest{
#' yml() %>%
#' yml_author(
#' c("Yihui Xie", "Hadley Wickham"),
#' affiliation = rep("RStudio", 2)
#' ) %>%
#' yml_date("07/04/2019") %>%
#' yml_output(
#' pdf_document(
#' keep_tex = TRUE,
#' includes = includes2(after_body = "footer.tex")
#' )
#' ) %>%
#' yml_latex_opts(biblio_style = "apalike")
#'}
yml <- function(.yml = NULL, get_yml = TRUE, author = TRUE, date = TRUE) {
if (is.null(.yml)) .yml <- list()
.yml <- as_yml(.yml)
if (!is.null(.yml$author)) author <- FALSE
if (!is.null(.yml$date)) date <- FALSE
if (get_yml) default_yml <- get_yml_defaults()
if (get_yml && !is.null(default_yml)) {
default_fields <- names(default_yml)
if ("author" %in% default_fields) author <- FALSE
if ("date" %in% default_fields) date <- FALSE
.yml[default_fields] <- default_yml
}
if (author) {
author_name <- tryCatch(
get_author_name(),
error = function(e) yml_blank()
)
if (!is_yml_blank(author_name)) .yml$author <- author_name
}
if (date) .yml$date <- format_sys_date()
.yml
}
#' @rdname yml
#' @export
yml_empty <- function() {
yml(get_yml = FALSE, author = FALSE, date = FALSE)
}
#' Convert to yml object
#'
#' `as_yml` is a wrapper for [`yaml::yaml.load()`] that stores YAML as a `yml`
#' object, which prints cleanly to the console and is easy to work with using
#' ymlthis functions.
#'
#' @param x An object, either a character vector of length 1 or list, to convert
#' to `yml`.
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' x <- as_yml("
#' author: Hadley Wickham
#' date: '2014-09-12'
#' title: Tidy Data
#' keywords:
#' - data cleaning
#' - data tidying
#' - relational databases
#' - R")
#'
#' x
#'
#' x %>%
#' yml_subtitle("Hadley's Tidy Data Paper")
#'
as_yml <- function(x) {
UseMethod("as_yml")
}
#' @export
as_yml.default <- function(x) {
yaml::as.yaml(x) %>%
as_yml()
}
#' @export
as_yml.list <- function(x) {
structure(
x,
class = "yml"
)
}
#' @export
as_yml.character <- function(x) {
if (length(x) == 1) {
.yml <- yaml::yaml.load(x)
if (is.character(.yml)) return(.yml)
return(as_yml(.yml))
}
structure(
x,
class = "yml"
)
}
#' @export
as_yml.print_yaml <- function(x) {
.yml <- unclass(x)
as_yml(.yml)
}
#' Load YAML from string
#'
#' `yml_load()` is a wrapper for [yaml::yaml.load()] that also converts the
#' object to the `yml` class.
#'
#' @param x an object to pass to [yaml::yaml.load()]
#'
#' @examples
#' c("title: my title", "author: Malcolm Barrett") %>%
#' yml_load()
#'
#' @export
yml_load <- function(x) {
as_yml(yaml::yaml.load(x))
}
#' Set handlers to process the way YAML is printed
#'
#' ymlthis uses the yaml package to process and validate YAML; this package also
#' lets you specify how fields and values are printed using a list of handler
#' functions. `yml_handlers()` specifies defaults for the package used in the
#' print statement. See [yaml::yaml.load()] for more on specifying handlers.
#'
#' @export
yml_handlers <- function() {
list(
NULL = function(x) yml_verbatim("null"),
glue = function(x) as.character(x),
Date = function(x) as.character(x),
logical = function(x) yml_verbatim(ifelse(x, "true", "false"))
)
}
#' @export
print.yml <- function(x, ..., handlers = yml_handlers()) {
# save to be grabbed by last_yml()
.ymlthis$.yml <- x
yml_txt <- color_yml(x, handlers = handlers)
cat_silver("---\n")
cat(yml_txt, ...)
cat_silver("---\n")
invisible(x)
}
color_yml <- function(x, handlers = yml_handlers()) {
yml_txt <- yaml::as.yaml(
x,
handlers = handlers,
column.major = FALSE
)
if (!isTRUE(getOption("crayon.enabled", TRUE))) {
return(yml_txt)
}
field_names <- x %>%
flatten_yml_names() %>%
paste(collapse = "|")
# start with `-`, spaces, or beginning line, and end with a colon
field_names <- paste0("(?:(?<=[- ])|^)(", field_names, ")(?=:)")
yml_txt <- yml_txt %>%
# color fields green
split_pluck() %>%
stringr::str_replace(field_names, crayon::green) %>%
paste(collapse = "\n") %>%
# color list hyphens and single colons silver
stringr::str_replace_all("-\\s", crayon::silver) %>%
stringr::str_replace_all("(?<!\\:)\\:(?!\\:)", crayon::silver)
yml_txt
}
flatten_yml_names <- function(x) {
seq(from = 0, to = purrr::vec_depth(x) - 1) %>%
purrr::map(~purrr::map_depth(x, .x, names, .ragged = TRUE)) %>%
unlist(use.names = FALSE)
}
cat_silver <- function(x) {
if (!isTRUE(getOption("crayon.enabled", TRUE))) {
cat(x)
} else {
cat(crayon::silver(x))
}
}
#' Export yml object as a YAML knitr code chunk
#'
#' `asis_yaml_output()` exports a `yml` object as a YAML knitr code chunk
#' instead of as an R object. Doing so adds code highlighting for YAML syntax.
#'
#' @template describe_yml_param
#' @param fences Logical. Write fences ("---") before and after YAML?
#'
#' @export
asis_yaml_output <- function(.yml, fences = TRUE) {
x <- .yml %>%
capture_yml()
if (!fences) x <- x[which(x != "---")]
x <- glue::glue_collapse(x, "\n")
glue::glue("```yaml\n{x}\n```") %>%
knitr::asis_output()
}
#' Is object a yml object?
#'
#' @param x An object to test
#'
#' @return A logical vector
#' @export
is_yml <- function(x) inherits(x, "yml")
# set environment to store last yml
.ymlthis <- new.env(parent = emptyenv())
.ymlthis$.yml <- list()
#' Return the most recently printed YAML
#'
#' ymlthis stores the most recently printed `yml` object; you can use
#' `last_yml()` to retrieve it to modify, pass to `use_*()` functions, and so
#' on.
#'
#' @export
#'
#' @examples
#' yml() %>%
#' yml_author("Yihui Xie")
#'
#' last_yml()
#'
last_yml <- function() {
if (rlang::is_empty(.ymlthis$.yml)) .ymlthis$.yml <- yml()
.ymlthis$.yml
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml.R |
#' Set Top-level YAML options for blogdown
#'
#' YAML in blogdown comes from a variety of sources. Most YAML will be for your
#' posts, as described in the [blogdown
#' book](https://bookdown.org/yihui/blogdown/content.html#yaml-metadata)).
#' Common R Markdown fields can be used, but there are two other main sources
#' for YAML fields: Hugo itself and the Hugo theme you are using. Hugo has
#' numerous top-level YAML to control the output (see the [Hugo
#' documentation](https://gohugo.io/content-management/front-matter/)).
#' `yml_blogdown_opts()` supports Hugo YAML. Your Hugo theme may also add fields
#' to use. To find YAML specific to your theme, see [blogdown_template()]. In
#' addition to these sources of YAML, the configuration file for your blog can
#' also be in YAML, but this is not very common; most use a `config.toml` file,
#' based on TOML (see the [blogdown
#' book](https://bookdown.org/yihui/blogdown/configuration.html) for more).
#'
#' @template describe_yml_param
#' @param draft Logical. Set post as a draft? Draft posts will not be rendered
#' if the site is built via `blogdown::build_site()` or
#' `blogdown::hugo_build()` but will be rendered in the local preview mode.
#' See [Section D.3 of the blogdown
#' book](https://bookdown.org/yihui/blogdown/local-preview.html#local-preview).
#'
#' @param publishdate A future date to publish the post. Future posts are only
#' rendered in the local preview mode
#' @param weight This field can take a numeric value to tell Hugo the order of
#' pages when sorting them, e.g., when you generate a list of all pages under
#' a directory, and two posts have the same date, you may assign different
#' weights to them to get your desired order on the list
#' @param slug A character string used as the tail of the post URL. It is
#' particularly useful when you define custom rules for permanent URLs. See
#' [Section 2.2.2 of the blogdown
#' book](https://bookdown.org/yihui/blogdown/configuration.html#options).
#' @param aliases A character vector of one or more aliases (e.g., old published
#' paths of renamed content) that will be created in the output directory
#' structure
#' @param audio A character vector of paths to audio files related to the page
#' @param date The date assigned to this page. This is usually fetched from the
#' `date` field in front matter, but this behavior is configurable.
#' @param description The description for the content
#' @param expiration_date the date at which the content should no longer be
#' published by Hugo. Note that the actual YAML field is `expiryDate`
#' @param headless if `TRUE`, sets a leaf bundle to be
#' [headless](https://gohugo.io/content-management/page-bundles/#headless-bundle).
#'
#' @param images A character vector of paths to images related to the page
#' @param keywords A character vector of the keywords for the content.
#' @param layout The layout Hugo should use while rendering the content. By
#' default, `layout` matches `type` and is thus based on the directory.
#' However, it's possible to use additional layouts within a type. See [Hugo's
#' Defining a Content Type
#' documentation](https://gohugo.io/content-management/types/#defining-a-content-type).
#'
#' @param lastmod The date the content was last modified at
#' @param link_title used for creating links to content. Note that the actual
#' YAML field is `linkTitle`
#' @param resources A named list. Used for configuring page bundle resources.
#' See [Hugo's Page Resources
#' documentation](https://gohugo.io/content-management/page-resources/)
#' @param series A character vector of series this page belongs to
#' @param summary A summary of the content in the `.Summary` Hugo page variable;
#' see the
#' [content-summaries](https://gohugo.io/content-management/summaries/)
#' section of Hugo's documentation.
#' @param title The title for the content
#' @param type The type of the content, which is based on the from the directory
#' of the content if not specified
#' @param url The full path to the content from the web root
#' @param videos A character vector of paths to videos related to the page
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_blogdown_opts(
#' draft = TRUE,
#' slug = "blog-post"
#' )
yml_blogdown_opts <- function(
.yml,
draft = yml_blank(),
publishdate = yml_blank(),
weight = yml_blank(),
slug = yml_blank(),
aliases = yml_blank(),
audio = yml_blank(),
date = yml_blank(),
description = yml_blank(),
expiration_date = yml_blank(),
headless = yml_blank(),
images = yml_blank(),
keywords = yml_blank(),
layout = yml_blank(),
lastmod = yml_blank(),
link_title = yml_blank(),
resources = yml_blank(),
series = yml_blank(),
summary = yml_blank(),
title = yml_blank(),
type = yml_blank(),
url = yml_blank(),
videos = yml_blank(),
...
) {
blogdown_opts <- list(
draft = draft,
publishdate = publishdate,
weight = weight,
slug = slug,
aliases = aliases,
audio = audio,
date = date,
description = description,
draft = draft,
expiryDate = expiration_date,
headless = headless,
images = images,
keywords = keywords,
layout = layout,
lastmod = lastmod,
linkTitle = link_title,
resources = resources,
series = series,
summary = summary,
title = title,
type = type,
url = url,
videos = videos,
...
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, blogdown_opts)
.yml[names(blogdown_opts)] <- blogdown_opts
.yml
}
#' Create YAML based on blogdown theme archetypes
#'
#' `blogdown_template()` creates YAML based on your blogdown theme archetypes.
#' blogdown is based on Hugo, which supports many custom themes. Each theme uses
#' YAML in a different way. However, many come with archetypes that define the
#' YAML or TOML. To find out which types your theme has, use
#' `blogdown_archetypes()` to see what's available. Use `blogdown_template()` to
#' specify the archetype and it will convert the template to YAML that you can
#' use in your post.
#'
#' @param type an archetype
#' @param path the path to your blogdown site
#' @param theme the theme to check for archetypes. By default,
#' `blogdown_template()` will attempt to read your theme from your `config`
#' file.
#'
#' @template describe_yml_output
#' @export
blogdown_template <- function(type, path = ".", theme = NULL) {
stop_if_blogdown_not_installed()
on.exit(unlink_temporary_dir(), add = TRUE)
if (is.null(theme)) theme <- get_theme(path)
archetype_path <- file.path(path, "themes", theme, "archetypes")
if (!file.exists(file.path(archetype_path, paste0(type, ".md")))) {
stop("archetype ", type, " does not exist", call. = FALSE)
}
fs::dir_create(file.path(temporary_dir(), "content"))
fs::file_copy(
file.path(archetype_path, paste0(type, ".md")),
file.path(temporary_dir(), "content")
)
writeLines(
c("baseurl = \"/\"", "builddrafts = true"),
file.path(temporary_dir(), "config.toml")
)
file_to_yamlify <- file.path(
temporary_dir(),
"content",
paste0(type, ".md")
)
clean_archetype_files(file_to_yamlify)
withr::with_dir(
temporary_dir(),
blogdown::hugo_cmd(
args = c("convert", "toYAML", "--unsafe"),
stdout = TRUE
)
)
post_yml <- yaml::yaml.load_file(file_to_yamlify) %>%
as_yml()
post_yml
}
#' @export
#' @rdname blogdown_template
blogdown_archetypes <- function(path = ".", theme = NULL) {
if (is.null(theme)) theme <- get_theme(path)
file.path(path, "themes", theme, "archetypes") %>%
fs::dir_ls() %>%
basename() %>%
stringr::str_remove(".md$")
}
clean_archetype_files <- function(path) {
readLines(path) %>%
# remove {{expr}} functions
stringr::str_replace_all('\\{\\{.+\\}\\}', '\\"\\"') %>%
stringr::str_replace_all('\\"\\"\\"\\"', '\\"\\"') %>%
writeLines(path)
}
get_theme <- function(path) {
config_path <- fs::dir_ls(path) %>%
stringr::str_subset("config\\.(toml|yaml|yml)$")
config_file <- readLines(config_path)
theme <- config_file %>%
stringr::str_subset("^theme") %>%
stringr::str_remove_all("theme|=|\\s*") %>%
stringr::str_remove_all("\"|\'")
theme
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_blogdown.R |
#' Set Top-level YAML options for bookdown
#'
#' bookdown uses YAML in three main places, as described in the [bookdown
#' book](https://bookdown.org/yihui/rmarkdown/bookdown-project.html):
#' `index.Rmd`, `_output.yml`, and `_bookdown.yml`. `index.Rmd` can take most
#' YAML. `_output.yml` is intended for output-related YAML, such as that
#' produced by `yml() %>% yml_output(bookdown::pdf_book())`. `_bookdown.yml` is
#' intended for configuring the build of the book. Pass the results of the
#' `yml_*()` functions to `use_index_rmd()`, `use_bookdown_yml()`,
#' `use_output_yml()` to write them to these files. `yml_bookdown_site()` adds
#' the `site: "bookdown::bookdown_site"` to the YAML metadata.
#'
#' @template describe_yml_param
#' @param book_filename A character vector, the filename of the main `.Rmd`
#' file, the `.Rmd` file that is created by merging all chapters. By default,
#' it is called "_main.Rmd".
#' @param delete_merged_file Logical. Delete the main `.Rmd` file if it exists?
#' @param before_chapter_script,after_chapter_script A character vector of one
#' or more R scripts to be executed before or after each chapter
#' @param edit A URL that collaborators can click to edit the `.Rmd` source
#' document of the current page, usually a link to a GitHub repository. This
#' link should have `%s` where the actual `.Rmd` filename for each page will
#' go.
#' @param history Similar to `edit`, a link to the edit/commit history of the
#' current page.
#' @param rmd_files A character vector, the order order of `.Rmd` files for the
#' book. `rmd_files` can also be a named list where each element of the list
#' is named for the output type, e.g. "html" or "latex". By default, bookdown
#' merges all `.Rmd` files by the order of filenames.
#' @param rmd_subdir whether to search for book source `.Rmd` files in
#' subdirectories (by default, only the root directory is searched). This may
#' be either a boolean (e.g. `TRUE` will search for book source `.Rmd` files
#' in the project directory and all subdirectories) or vector of paths if you
#' want to search for book source `.Rmd` files in a subset of subdirectories.
#' @param output_dir the output directory of the book ("_book" by default)
#' @param clean a character vector of files and directories to be cleaned by the
#' `bookdown::clean_book()` function.
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml_empty() %>%
#' yml_bookdown_opts(
#' book_filename = "my-book.Rmd",
#' before_chapter_script = c("script1.R", "script2.R"),
#' after_chapter_script = "script3.R",
#' edit = "https =//github.com/rstudio/bookdown-demo/edit/master/%s",
#' output_dir = "book-output",
#' clean = c("my-book.bbl", "R-packages.bib")
#' )
#'
#' yml_empty() %>%
#' yml_bookdown_opts(
#' rmd_files = list(
#' html = c("index.Rmd", "abstract.Rmd", "intro.Rmd"),
#' latex = c("abstract.Rmd", "intro.Rmd")
#' )
#' )
#'
#' x <- yml_empty() %>%
#' yml_title("A Minimal Book Example") %>%
#' yml_date(yml_code(Sys.Date())) %>%
#' yml_author("Yihui Xie") %>%
#' yml_bookdown_site() %>%
#' yml_latex_opts(
#' documentclass = "book",
#' bibliography = c("book.bib", "packages.bib"),
#' biblio_style = "apalike"
#' ) %>%
#' yml_citations(
#' link_citations = TRUE
#' ) %>%
#' yml_description("This is a minimal example of using
#' the bookdown package to write a book.")
#'
#' x
#'
#'
#'\donttest{
#' output_yml <- yml_empty() %>%
#' yml_output(
#' bookdown::gitbook(
#' lib_dir = "assets",
#' split_by = "section",
#' config = gitbook_config(toolbar_position = "static")
#' ),
#' bookdown::pdf_book(keep_tex = TRUE),
#' bookdown::html_book(css = "toc.css")
#' )
#' output_yml
#'}
#'
#'
#' @family bookdown
#' @seealso [`use_index_rmd()`] [`use_bookdown_yml()`] [`use_output_yml()`]
yml_bookdown_opts <- function(
.yml,
book_filename = yml_blank(),
delete_merged_file = yml_blank(),
before_chapter_script = yml_blank(),
after_chapter_script = yml_blank(),
edit = yml_blank(),
history = yml_blank(),
rmd_files = yml_blank(),
rmd_subdir = yml_blank(),
output_dir = yml_blank(),
clean = yml_blank(),
...
) {
bookdown_opts <- list(
book_filename = book_filename,
delete_merged_file = delete_merged_file,
before_chapter_script = before_chapter_script,
after_chapter_script = after_chapter_script,
edit = edit,
history = history,
rmd_files = rmd_files,
rmd_subdir = rmd_subdir,
output_dir = output_dir,
clean = clean,
...
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, bookdown_opts)
.yml[names(bookdown_opts)] <- bookdown_opts
.yml
}
#' @export
#' @rdname yml_bookdown_opts
yml_bookdown_site <- function(.yml) {
warn_if_duplicate_fields(.yml, list(site = ""))
.yml$site <- "bookdown::bookdown_site"
.yml
}
#' Configure `bookdown::gitbook()` output
#'
#' `gitbook_config()` is a helper function to specify the `config` argument in
#' [bookdown::gitbook()], as described in the [bookdown
#' book](https://bookdown.org/yihui/bookdown/html.html).
#'
#' @param toc_collapse Collapse some items initially when a page is loaded via
#' the collapse option. Its possible values are "subsection" (the default),
#' "section", "none", or `NULL`.
#' @param toc_scroll_highlight Logical. Enable highlighting of TOC items as you
#' scroll the book body? The default is `TRUE`.
#' @param toc_before,toc_after a character vector of HTML to add more items
#' before and after the TOC using the HTML tag `<li>`. These items will be
#' separated from the TOC using a horizontal divider.
#' @param toolbar_position The toolbar position: "fixed" or "static." The
#' default ("fixed") is that the toolbar will be fixed at the top of the page,
#' whereas when set to "static" the toolbar will not scroll with the page.
#' @param edit If not empty, an edit button will be added to the toolbar.
#' @param download This option takes either a character vector or a list of
#' character vectors with the length of each vector being 2. When it is a
#' character vector, it should be either a vector of filenames or filename
#' extensions. When you only provide the filename extensions, the filename is
#' derived from the book filename of the configuration file `_bookdown.yml`
#' @param search Include a search bar?
#' @param fontsettings_theme The theme. "White" (the default), "Sepia", or
#' "Night".
#' @param fontsettings_family The font family. "sans" (the default) or "serif".
#' @param fontsettings_size The font size. Default is 2.
#' @param sharing_facebook Logical. Include Facebook share link? Default is
#' `TRUE`.
#' @param sharing_twitter Logical. Include Twitter share link? Default is
#' `TRUE`.
#' @param sharing_google Logical. Include Google share link? Default is `FALSE`.
#' @param sharing_linkedin Logical. Include LinkedIn share link? Default is
#' `FALSE`.
#' @param sharing_weibo Logical. Include Weibo share link? Default is `FALSE`.
#' @param sharing_instapaper Logical. Include Instapaper share link? Default is
#' `FALSE`.
#' @param sharing_vk Logical. Include VK share link? Default is `FALSE`.
#' @param sharing_all Logical. Include all share links? Default is `FALSE`.
#' @template describe_dots_param
#'
#' @return a list to use in the `config` argument of [bookdown::gitbook()]
#' @export
#'
#' @family bookdown
gitbook_config <- function(
toc_collapse = yml_blank(),
toc_scroll_highlight = yml_blank(),
toc_before = yml_blank(),
toc_after = yml_blank(),
toolbar_position = yml_blank(),
edit = yml_blank(),
download = yml_blank(),
search = yml_blank(),
fontsettings_theme = yml_blank(),
fontsettings_family = yml_blank(),
fontsettings_size = yml_blank(),
sharing_facebook = yml_blank(),
sharing_twitter = yml_blank(),
sharing_google = yml_blank(),
sharing_linkedin = yml_blank(),
sharing_weibo = yml_blank(),
sharing_instapaper = yml_blank(),
sharing_vk = yml_blank(),
sharing_all = yml_blank(),
...
) {
list(
toc = list(
collapse = toc_collapse,
scroll_highlight = toc_scroll_highlight,
before = toc_before,
after = toc_after
) %>%
purrr::discard(is_yml_blank),
toolbar = list(position = toolbar_position) %>%
purrr::discard(is_yml_blank),
edit = edit,
download = download,
search = search,
fontsettings = list(
theme = fontsettings_theme,
family = fontsettings_family,
size = fontsettings_size
) %>%
purrr::discard(is_yml_blank),
sharing = list(
facebook = sharing_facebook,
twitter = sharing_twitter,
google = sharing_google,
linkedin = sharing_linkedin,
weibo = sharing_weibo,
instapaper = sharing_instapaper,
vk = sharing_vk,
all = sharing_all
) %>%
purrr::discard(is_yml_blank),
...
) %>%
purrr::discard(is_yml_blank) %>%
purrr::discard(purrr::is_empty)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_bookdown.R |
#' Set citation-related YAML options
#'
#' `yml_citations()` sets citation-related YAML fields, such as specifying a
#' bibliography file or style. For controlling the citation engine in PDF
#' documents, see the `citation_package` argument in
#' `rmarkdown::pdf_document()`.
#'
#' @template describe_yml_param
#' @param bibliography a path to a bibliography file, such as a .bib file
#' @param csl a path to a Citation Style Language (CSL) file. CSL files are used
#' to specify the citation style; see the [CSL
#' repository](https://github.com/citation-style-language/styles) for the CSL
#' files of dozens of journals.
#' @param citation_abbreviations Path to a CSL abbreviations JSON file. See the
#' [pandoc-citeproc
#' documentation](https://manpages.ubuntu.com/manpages/xenial/man1/pandoc-citeproc.1.html).
#' Note that the actual YAML field is `citation-abbreviations`.
#' @param link_citations Logical. Add citations hyperlinks to the corresponding
#' bibliography entries? Note that the actual YAML field is `link-citations`.
#' @param nocite Citation IDs (`"@item1"`) to include in the bibliography even if
#' they are not cited in the document. Including the wildcard pattern `"@*"`
#' will include all citations in the bibliography regardless of if they're
#' cited in the document.
#' @param suppress_bibliography Logical. Suppress bibliography?
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_citations(bibliography = "references.bib", csl = "aje.csl")
#'
#' @family citations
#' @inheritParams yml_latex_opts
yml_citations <- function(
.yml,
bibliography = yml_blank(),
biblio_style = yml_blank(),
biblio_title = yml_blank(),
csl = yml_blank(),
citation_abbreviations = yml_blank(),
link_citations = yml_blank(),
nocite = yml_blank(),
suppress_bibliography = yml_blank()
) {
citation_opts <- list(
bibliography = bibliography,
"biblio-style" = biblio_style,
"biblio-title" = biblio_title,
csl = csl,
"citation-abbreviations" = citation_abbreviations,
"link-citations" = link_citations,
nocite = nocite,
"suppress-bibliography" = suppress_bibliography
)
citation_opts <- purrr::discard(citation_opts, is_yml_blank)
warn_if_duplicate_fields(.yml, citation_opts)
.yml[names(citation_opts)] <- citation_opts
.yml
}
#' Write references as YAML fields
#'
#' `yml_reference()` creates YAML fields for references to be used in citation.
#' `reference()` is a simple function to add references to `yml_reference()`. The
#' easiest way to add references to an R Markdown file is to use a bibliography
#' file, such as .bib, in the `bibliography` field (see [yml_citations()]). For
#' documents with very few references, however, it might be useful to make the
#' references self-contained in the YAML. `yml_reference()` can also transform to
#' YAML `bibentry` and `citation` objects created by[bibentry()] and
#' [citation()]. To cite many R packages and convert the references to YAML,
#' it may be better to use [knitr::write_bib()] to write a bibliography file and
#' convert it with [`bib2yml()`].
#'
#' @template describe_yml_param
#' @param ... Fields relevant to the citation (e.g. bibtex fields)
#' @param .bibentry An object created by `bibentry()` or `citation()`. Note that
#' this requires pandoc-citeproc to be installed.
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' ref <- reference(
#' id = "fenner2012a",
#' title = "One-click science marketing",
#' author = list(
#' family = "Fenner",
#' given = "Martin"
#' ),
#' `container-title` = "Nature Materials",
#' volume = 11L,
#' URL = "https://doi.org/10.1038/nmat3283",
#' DOI = "10.1038/nmat3283",
#' issue = 4L,
#' publisher = "Nature Publishing Group",
#' page = "261-263",
#' type = "article-journal",
#' issued = list(
#' year = 2012,
#' month = 3
#' )
#' )
#'
#' yml() %>%
#' yml_reference(ref)
#'
#' # from ?bibentry
#' bref <- c(
#' bibentry(
#' bibtype = "Manual",
#' title = "boot: Bootstrap R (S-PLUS) Functions",
#' author = c(
#' person("Angelo", "Canty", role = "aut",
#' comment = "S original"),
#' person(c("Brian", "D."), "Ripley", role = c("aut", "trl", "cre"),
#' comment = "R port, author of parallel support",
#' email = "[email protected]")
#' ),
#' year = "2012",
#' note = "R package version 1.3-4",
#' url = "https://CRAN.R-project.org/package=boot",
#' key = "boot-package"
#' ),
#'
#' bibentry(
#' bibtype = "Book",
#' title = "Bootstrap Methods and Their Applications",
#' author = as.person("Anthony C. Davison [aut], David V. Hinkley [aut]"),
#' year = "1997",
#' publisher = "Cambridge University Press",
#' address = "Cambridge",
#' isbn = "0-521-57391-2",
#' url = "http://statwww.epfl.ch/davison/BMA/",
#' key = "boot-book"
#' )
#' )
#' \donttest{
#' # requires pandoc-citeproc to be installed
#' yml() %>%
#' yml_reference(.bibentry = bref)
#'
#' yml() %>%
#' yml_reference(.bibentry = citation("purrr"))
#'}
#'@family citations
yml_reference <- function(.yml, ..., .bibentry = NULL) {
warn_if_duplicate_fields(.yml, list(reference = ""))
if (!is.null(.bibentry)) {
stop_if_not_type(.bibentry, "bibentry")
# remove citation class if present
if (inherits(.bibentry, "citation")) .bibentry <- as_bibentry(.bibentry)
bib_yml <- bibentry2yml(.bibentry)
.yml[names(bib_yml)] <- bib_yml
return(.yml)
}
.yml$reference <- list(...)
.yml
}
#' @export
#' @param id a character vector to use as the reference ID
#' @rdname yml_reference
reference <- function(id = NULL, ...) {
stop_if_not_type(id, "character")
list(
id = id,
...
)
}
bibentry2yml <- function(.bibentry) {
on.exit(unlink_temporary_dir(), add = TRUE)
.bibtex <- format(.bibentry, style = "Bibtex")
writeLines(.bibtex, file.path(temporary_dir(), "bibtex.bib"))
bib2yml(path = file.path(temporary_dir(), "bibtex.bib"))
}
as_bibentry <- function(x) {
class(x) <- "bibentry"
if (is.null(x$key)) {
pkg_attr <- attr(x, "package")
pkg_name <- ifelse(!is.null(pkg_attr), pkg_attr, "pkg")
x$key <- glue::glue("R-{pkg_name}")
}
x
}
#' Convert bib files to YAML
#'
#' `bib2yml()` uses pandoc to convert a .bib file to YAML. It also accepts an
#' optional `yml` object to prepend to the the YAML from the .bib file. If you
#' want to cite several R packages, see [knitr::write_bib()] to write a
#' bibliography file and convert it with `bib2yml()`.
#'
#' @template describe_yml_param
#' @param path a path to the .bib file
#'
#' @template describe_yml_output
#' @export
#'
#' @family citations
bib2yml <- function(.yml = NULL, path) {
bib_yml <- rmarkdown::pandoc_citeproc_convert(path, type = "yaml") %>%
as_yml()
if (!is.null(.yml)) {
warn_if_duplicate_fields(.yml, bib_yml)
.yml[names(bib_yml)] <- bib_yml
return(.yml)
}
bib_yml
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_citations.R |
#' Set Top-level YAML options for distill
#'
#' distill uses many custom YAML fields to create some of its unique features,
#' such as article metadata and citations. In addition to the arguments in
#' `yml_distill_opts()`, ymlthis supports distill in a number of other ways.
#' `yml_distill_author()` wraps [`yml_author()`] to include these extra used in
#' distill. For a distill blog, you can specify the listings page a post belongs
#' to, including an optional vector of other posts to list with it;
#' `distill_listing()` is a helper function to pass to the `listing` argument to
#' specify such pages. distill uses the same approach to navbars as R Markdown.
#' [`yml_navbar()`] and friends will help you write the YAML for that. YAML
#' specifying the site build, like the output field and navbars, can also be
#' placed in `_site.yml`; see [`yml_site_opts()`] for further R Markdown website
#' build options and [`use_site_yml()`] for creating that file based on a `yml`
#' object. distill's YAML options are discussed in greater detail in the
#' [articles on the distill website](https://rstudio.github.io/distill/).
#'
#' @template describe_yml_param
#' @param draft Logical. Set the post to be a draft? Draft posts won't be
#' published.
#' @param slug The abbreviated version of the citation included in the BibTeX
#' entry. If you don’t provide a slug then one will be automatically
#' generated.
#' @param categories A character vector, the post categories
#' @param listing The listing a post is under; either a character vector, the
#' output of `distill_listing()`, or a named list.
#' @param collection Specify the RSS, sharing, and other settings of a listing;
#' use `distill_collection()` or a named list.
#' @param preview a path or link to the preview image for your article. You can
#' also set this by including `preview = TRUE` in an R Markdown code chunk in
#' your document.
#' @param repository_url A URL where the source code for your article can be
#' found
#' @param citation_url A URL to the article; automatically generated for blog
#' articles
#' @param compare_updates_url a URL that will show the differences between the
#' article’s current version and the version that was initially published
#' @param base_url Base (root) URL for the location where the website will be
#' deployed (used for providing preview images for Open Graph and Twitter
#' Card)
#' @param creative_commons Designate articles that you create as Creative
#' Commons licensed by specifying one of the standard Creative Commons
#' licenses. Common options include "CC BY", "CC BY-SA", "CC BY-ND", and "CC
#' BY-NC". See the [distill
#' vignette](https://rstudio.github.io/distill/metadata.html) for more
#' details.
#' @param twitter_site The Twitter handle for the site
#' @param twitter_creator The Twitter handle for the creator
#' @param journal_title The title of the journal
#' @param journal_issn The issn of the journal
#' @param journal_publisher The publisher of the journal
#' @param volume The volume the article is on
#' @param issue The issue the article is on
#' @param doi The article Digital Object Identifier (DOI)
#' @param resources Files to include or exclude while publishing. Use
#' `distill_resources()` or a named list to specify.
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#' post_listing <- distill_listing(
#' slugs = c(
#' "2016-11-08-sharpe-ratio",
#' "2017-11-09-visualizing-asset-returns",
#' "2017-09-13-asset-volatility"
#' )
#' )
#'
#' yml() %>%
#' yml_title("Gallery of featured posts") %>%
#' yml_distill_opts(listing = post_listing)
#'
#' yml_empty() %>%
#' yml_title("Reproducible Finance with R") %>%
#' yml_description("Exploring reproducible finance with the R statistical,
#' computing environment.") %>%
#' yml_site_opts(name = "reproducible-finance-with-r") %>%
#' yml_distill_opts(
#' base_url = "https://beta.rstudioconnect.com/content/3776/",
#' collection = distill_collection(
#' feed_items_max = 30,
#' disqus_name = "reproducible-finance-with-r",
#' disqus_hidden = FALSE,
#' share = c("twitter", "linkedin")
#' )
#' )
#'
#' @family distill
#' @family websites
#' @seealso [`use_site_yml()`] [`use_rmarkdown()`]
yml_distill_opts <- function(
.yml,
draft = yml_blank(),
slug = yml_blank(),
categories = yml_blank(),
listing = yml_blank(),
collection = yml_blank(),
citation_url = yml_blank(),
preview = yml_blank(),
repository_url = yml_blank(),
base_url = yml_blank(),
compare_updates_url = yml_blank(),
creative_commons = yml_blank(),
twitter_site = yml_blank(),
twitter_creator = yml_blank(),
journal_title = yml_blank(),
journal_issn = yml_blank(),
journal_publisher = yml_blank(),
volume = yml_blank(),
issue = yml_blank(),
doi = yml_blank(),
resources = yml_blank(),
...
) {
twitter <- yml_blank()
if (!is_yml_blank(journal_issn) || !is_yml_blank(journal_publisher)) {
journal_title <- list(
title = journal_title,
issn = journal_issn,
publisher = journal_title
) %>%
purrr::discard(is_yml_blank)
}
if (!is_yml_blank(twitter_site) || !is_yml_blank(twitter_creator)) {
twitter <- list(
site = twitter_site,
creator = twitter_creator
) %>% purrr::discard(is_yml_blank)
}
distill_opts <- list(
draft = draft,
slug = slug,
categories = categories,
listing = listing,
collection = collection,
preview = preview,
repository_url = repository_url,
citation_url = citation_url,
base_url = base_url,
compare_updates_url = compare_updates_url,
creative_commons = creative_commons,
twitter = twitter,
journal = journal_title,
volume = volume,
issue = issue,
doi = doi,
resources = resources,
...
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, distill_opts)
.yml[names(distill_opts)] <- distill_opts
.yml
}
#' @inheritParams yml_author
#' @param url the author URL
#' @param affiliation_url the affiliation URL
#' @param orcid_id the author's ORCID ID
#'
#' @export
#'
#' @rdname yml_distill_opts
yml_distill_author <- function(
.yml,
name = yml_blank(),
url = yml_blank(),
affiliation = yml_blank(),
affiliation_url = yml_blank(),
orcid_id = yml_blank()
) {
yml_author(
.yml,
name = name,
url = url,
affiliation = affiliation,
affiliation_url = affiliation_url,
orcid_id = orcid_id
)
}
#' @param listing_name A character vector, the name of the listing
#' @param slugs A character vector of the posts to include in the listing
#'
#' @export
#' @rdname yml_distill_opts
distill_listing <- function(listing_name = "posts", slugs = NULL) {
if (is.null(slugs)) {
return(listing_name)
}
x <- list(slugs)
names(x) <- listing_name
x
}
#' @export
#'
#' @param collection_name A character vector, the name of the collection
#' @param feed_items_max Number of articles to include in the RSS feed (default:
#' 20). Specify `FALSE` to have no limit on the number of items included in
#' the feed.
#' @param disqus_name A shortname for the disqus comments section (`base_url`
#' field is required in order to use Disqus)
#' @param disqus_hidden Logical. Show full text of disqus comments? By default,
#' this is `FALSE` so as not to obscure the bibliography and other appendices.
#' @param share Share buttons to include. Choices: "twitter", "linkedin",
#' "facebook", "google-plus", and "pinterest". (`base_url` field is required
#' in order to use sharing links)
#' @param citations Logical. If your `_site.yml` file provides a `base_url`
#' field, an article citation appendix and related metadata will be included
#' automatically within all published posts. Set to `FALSE` to disable this
#' behavior.
#' @param subscribe a path to a HTML file enabling readers to subscribe. See the
#' [distill vignette on blog
#' posts](https://rstudio.github.io/distill/blog.html#creating-a-blog) for
#' more details.
#'
#' @rdname yml_distill_opts
distill_collection <- function(
collection_name = "post",
feed_items_max = yml_blank(),
disqus_name = yml_blank(),
disqus_hidden = yml_blank(),
share = yml_blank(),
citations = yml_blank(),
subscribe = yml_blank()
) {
if (!is_yml_blank(disqus_hidden)) {
disqus_name <- list(
shortname = disqus_name,
hiden = disqus_hidden
)
}
x <- list(
feed_items_max = feed_items_max,
disqus = disqus_name,
share = share,
citations = citations,
subscribe = subscribe
) %>%
purrr::discard(is_yml_blank)
if (purrr::is_empty(x)) {
return(collection_name)
}
x <- list(x)
names(x) <- collection_name
x
}
#' @param include,exclude a character vector of files to explicitly include or
#' exclude when publishing a post. Can use wild cards, such as "*.csv".
#'
#' @export
#' @rdname yml_distill_opts
distill_resources <- function(include = yml_blank(), exclude = yml_blank()) {
list(include = include, exclude = exclude) %>%
purrr::discard(is_yml_blank)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_distill.R |
#' Return a blank object to be discarded from YAML
#'
#' ymlthis treats `NULL`, `NA`, and other common argument defaults as literal
#' (e.g. `author = NULL` will produce "author: null"). `yml_blank()` is a helper
#' function to indicate that the field should not be included. `yml_blank()` is
#' primarily used as a default argument for fields that should not be included
#' by default.
#'
#' @param x a field from a `yml` object
#' @return a `yml_blank` object
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_replace(author = yml_blank()) %>%
#' yml_discard(~is_yml_blank(.x))
#'
#'
#' @rdname yml_blank
#' @seealso [yml_discard()], [yml_replace()]
yml_blank <- function() {
structure(list(), class = "yml_blank")
}
null_if_blank <- function(.x) {
if (is_yml_blank(.x)) {
return(NULL)
}
.x
}
#' @export
#' @rdname yml_blank
is_yml_blank <- function(x) {
inherits(x, "yml_blank")
}
#' Write YAML field or content verbatim
#'
#' `yml_verbatim()` is a helper function to write YAML precisely as given to the
#' `yml_*()` function rather than the defaults in ymlthis and yaml. ymlthis uses
#' the yaml package to check for valid syntax; yaml and ymlthis together make
#' decisions about how to write syntax, which can often be done in numerous
#' valid ways. See [yaml::as.yaml()] for more details.
#'
#' @param x a character vector
#'
#' @return an object of class `verbatim`
#' @export
#'
#' @examples
#' # "yes" and "no" serve as alternatives to `true` and `false`. This writes
#' # "yes" literally.
#' yml_verbatim("yes")
yml_verbatim <- function(x) {
structure(x, class = "verbatim")
}
#' Take code and write it as valid YAML
#'
#' `yml_code()` takes R code and writes it as valid YAML to be evaluated during
#' knitting. Note that `yml_code()` does not evaluate or validate the R code but
#' only captures it to use in the YAML field. R code needs to be formatted
#' differently when using in the `params` field for parameterized reports;
#' `yml_params_code` will format this correctly for you.
#'
#' @param x valid R code
#'
#' @return a character vector with class `verbatim`
#' @export
#'
#' @examples
#'
#' yml_empty() %>%
#' yml_date(yml_code(sys.Date()))
#'
#' yml_empty() %>%
#' yml_params(date = yml_params_code(sys.Date()))
#'
#' @seealso [yml_verbatim()]
yml_code <- function(x) {
x <- rlang::enquo(x)
glue::glue("`r {rlang::quo_text(x)} `") %>%
yml_verbatim()
}
#' @export
#' @rdname yml_code
yml_params_code <- function(x) {
x <- rlang::enquo(x)
x <- rlang::quo_text(x)
attr(x, "tag") <- "!r"
x
}
#' Include content within output
#'
#' `includes2()` is a version of the `includes()` helper function from rmarkdown
#' that uses `yml_blank()` instead of `NULL` as the argument defaults, as
#' ymlthis treats NULLs as literal YAML syntax ("null").
#'
#' @param in_header One or more files with content to be included in the header
#' of the document.
#' @param before_body One or more files with content to be included before the
#' document body.
#' @param after_body One or more files with content to be included after the
#' document body.
#'
#' @return a list
#' @export
#'
#' @examples
#'\donttest{
#' yml() %>%
#' yml_output(
#' pdf_document(includes = includes2(after_body = "footer.tex"))
#' )
#'}
includes2 <- function(in_header = yml_blank(), before_body = yml_blank(), after_body = yml_blank()) {
includes_list <- list(
in_header = in_header,
before_body = before_body,
after_body = after_body
)
purrr::discard(includes_list, is_yml_blank)
}
#' Check if field exists in YAML
#'
#' `has_field()` retrieves the names of all fields (including nested fields) and
#' checks if `field` is among them.
#'
#' @template describe_yml_param
#' @param field A character vector, the name of the field(s) to check for
#'
#' @return logical
#' @export
#'
#' @examples
#'
#' has_field(yml(), "author")
#' has_field(yml(), "toc")
#'
has_field <- function(.yml, field) {
fields <- flatten_yml_names(.yml)
field %in% fields
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_helpers.R |
#' Set LaTeX YAML options for PDF output
#'
#' `yml_latex_opts()` sets top-level YAML fields for LaTeX options used by
#' pandoc ([see the documentation](https://pandoc.org/MANUAL.html), from which
#' these descriptions were derived), as when making a PDF document with
#' `pdf_document()`.
#'
#' @template describe_yml_param
#' @param block_headings make paragraph and subparagraph (fourth- and
#' fifth-level headings, or fifth- and sixth-level with book classes)
#' free-standing rather than run-in; requires further formatting to
#' distinguish from subsubsection (third- or fourth-level headings). Note that
#' the YAML field is actually called `block-headings`.
#' @param classoption a character vector of options for document class, e.g.
#' "oneside"
#' @param documentclass the document class usually "article", "book", or
#' "report"
#' @param geometry a character vector of options for the [geometry LaTeX
#' package](https://ctan.org/pkg/geometry?lang=en), e.g. "margin=1in"
#' @param indent Logical. Use document class settings for indentation? The
#' default LaTeX template otherwise removes indentation and adds space between
#' paragraphs.
#' @param linestretch adjusts line spacing using the [setspace LaTeX
#' package](https://ctan.org/pkg/setspace?lang=en), e.g. 1.25, 1.5
#' @param margin_left,margin_right,margin_top,margin_bottom sets margins if
#' `geometry` is not used, otherwise `geometry` overrides these. Note that the
#' actual YAML fields use `-` instead of `_`, e.g. `margin-left`.
#' @param pagestyle control the `pagestyle` LaTeX command: the default article
#' class supports "plain" (default), "empty" (no running heads or page
#' numbers), and "headings" (section titles in running heads)
#' @param papersize paper size, e.g. letter, a4
#' @param secnumdepth numbering depth for sections (with `--number-sections`
#' pandoc)
#' @param fontenc allows font encoding to be specified through [fontenc LaTeX
#' package](https://www.ctan.org/pkg/fontenc) (with pdflatex); default is "T1"
#' (see [LaTeX font encodings guide](https://ctan.org/pkg/encguide))
#' @param fontfamily font package for use with pdflatex: TeX Live includes many
#' options, documented in the [LaTeX Font
#' Catalogue](https://tug.org/FontCatalogue/). The default is "Latin Modern".
#' @param fontfamilyoptions a character vector of options for `fontfamily`.
#' @param fontsize font size for body text. The standard classes allow "10pt",
#' "11pt", and "12pt".
#' @param mainfont,sansfont,monofont,mathfont,CJKmainfont font families for use
#' with xelatex or lualatex: take the name of any system font, using the
#' [fontspec LaTeX package](https://www.ctan.org/pkg/fontspec). CJKmainfont
#' uses the [xecjk LaTeX package.](https://www.ctan.org/pkg/xecjk).
#' @param
#' mainfontoptions,sansfontoptions,monofontoptions,mathfontoptions,CJKoptions a
#' character vector of options to use with mainfont, sansfont, monofont,
#' mathfont, CJKmainfont in xelatex and lualatex. Allow for any choices
#' available through fontspec.
#' @param microtypeoptions a character vector of options to pass to the
#' [microtype LaTeX package](https://www.ctan.org/pkg/microtype).
#' @param colorlinks Logical. Add color to link text? Automatically enabled if
#' any of `linkcolor`, `filecolor`, `citecolor`, `urlcolor`, or `toccolor` are
#' set.
#' @param linkcolor,filecolor,citecolor,urlcolor,toccolor color for internal
#' links, external links, citation links, linked URLs, and links in table of
#' contents, respectively: uses options allowed by
#' [xcolor](https://ctan.org/pkg/xcolor?lang=en), including the dvipsnames,
#' svgnames, and x11names lists
#' @param links_as_notes Logical. Print links as footnotes? Note that the actual
#' YAML field is `links-as-notes`
#' @param lof,lot Logical. Include list of figures or list of tables?
#' @param thanks contents of acknowledgments footnote after document title
#' @param toc include table of contents
#' @param toc_depth level of section to include in table of contents. Note that
#' the actual YAML field is `toc-depth`
#' @param biblatexoptions list of options for
#' [biblatex](https://ctan.org/pkg/biblatex).
#' @param biblio_style bibliography style, when used with
#' [natbib](https://ctan.org/pkg/natbib) and
#' [biblatex](https://ctan.org/pkg/biblatex). Note that the actual YAML field
#' is `biblio-style`
#' @param biblio_title bibliography title, when used with
#' [natbib](https://ctan.org/pkg/natbib) and
#' [biblatex](https://ctan.org/pkg/biblatex). Note that the actual YAML field
#' is `biblio-title`
#' @param bibliography a path to the bibliography file to use for references
#' @param natbiboptions a character vector of options for
#' [natbib](https://ctan.org/pkg/natbib)
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'\donttest{
#' yml() %>%
#' yml_output(pdf_document()) %>%
#' yml_latex_opts(
#' fontfamily = "Fira Sans Thin",
#' fontsize = "11pt",
#' links_as_notes = TRUE
#' )
#'}
yml_latex_opts <- function(
.yml,
block_headings = yml_blank(),
classoption = yml_blank(),
documentclass = yml_blank(),
geometry = yml_blank(),
indent = yml_blank(),
linestretch = yml_blank(),
margin_left = yml_blank(),
margin_right = yml_blank(),
margin_top = yml_blank(),
margin_bottom = yml_blank(),
pagestyle = yml_blank(),
papersize = yml_blank(),
secnumdepth = yml_blank(),
fontenc = yml_blank(),
fontfamily = yml_blank(),
fontfamilyoptions = yml_blank(),
fontsize = yml_blank(),
mainfont = yml_blank(),
sansfont = yml_blank(),
monofont = yml_blank(),
mathfont = yml_blank(),
CJKmainfont = yml_blank(),
mainfontoptions = yml_blank(),
sansfontoptions = yml_blank(),
monofontoptions = yml_blank(),
mathfontoptions = yml_blank(),
CJKoptions = yml_blank(),
microtypeoptions = yml_blank(),
colorlinks = yml_blank(),
linkcolor = yml_blank(),
filecolor = yml_blank(),
citecolor = yml_blank(),
urlcolor = yml_blank(),
toccolor = yml_blank(),
links_as_notes = yml_blank(),
lof = yml_blank(),
lot = yml_blank(),
thanks = yml_blank(),
toc = yml_blank(),
toc_depth = yml_blank(),
biblatexoptions = yml_blank(),
biblio_style = yml_blank(),
biblio_title = yml_blank(),
bibliography = yml_blank(),
natbiboptions = yml_blank()
) {
latex_opts <- list(
"block-headings" = block_headings,
classoption = classoption,
documentclass = documentclass,
geometry = geometry,
indent = indent,
linestretch = linestretch,
"margin-left" = margin_left,
"margin-right" = margin_right,
"margin-top" = margin_top,
"margin-bottom" = margin_bottom,
pagestyle = pagestyle,
papersize = papersize,
secnumdepth = secnumdepth,
fontenc = fontenc,
fontfamily = fontfamily,
fontfamilyoptions = fontfamilyoptions,
fontsize = fontsize,
mainfont = mainfont,
sansfont = sansfont,
monofont = monofont,
mathfont = mathfont,
CJKmainfont = CJKmainfont,
mainfontoptions = mainfontoptions,
sansfontoptions = sansfontoptions,
monofontoptions = monofontoptions,
mathfontoptions = mathfontoptions,
CJKoptions = CJKoptions,
microtypeoptions = microtypeoptions,
colorlinks = colorlinks,
linkcolor = linkcolor,
filecolor = filecolor,
citecolor = citecolor,
urlcolor = urlcolor,
toccolor = toccolor,
"links-as-notes" = links_as_notes,
lof = lof,
lot = lot,
thanks = thanks,
toc = toc,
"toc-depth" = toc_depth,
biblatexoptions = biblatexoptions,
"biblio-style" = biblio_style,
"biblio-title" = biblio_title,
bibliography = bibliography,
natbiboptions = natbiboptions
)
latex_opts <- purrr::discard(latex_opts, is_yml_blank)
warn_if_duplicate_fields(.yml, latex_opts)
.yml[names(latex_opts)] <- latex_opts
.yml
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_latex.R |
#' Capture, validate, and write output YAML
#'
#' `yml_output()` writes valid YAML for the `output` field of R Markdown YAML.
#' `yml_output()` captures the actual output functions, such as
#' `pdf_document()`, and translates them to YAML. This function accepts multiple
#' output formats (separated by commas) and validates each by evaluating the
#' function internally. The YAML fields in under `output` come from arguments in
#' their respective R functions. If you wanted to see the available fields in
#' `pdf_document()`, for instance, you would read the documentation for that
#' function using `?pdf_document`.
#'
#' @template describe_yml_param
#' @param ... valid R code calling functions that return objects of class
#' `rmarkdown_output_format`, such as the `*_document()` functions in
#' rmarkdown.
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'\donttest{
#' yml() %>%
#' yml_output(html_document())
#'
#' yml() %>%
#' yml_output(
#' pdf_document(keep_tex = TRUE, includes = includes2(after_body = "footer.tex")),
#' bookdown::html_document2()
#' )
#'}
yml_output <- function(.yml, ...) {
x <- rlang::enquos(...)
validate_output_yml(x)
args_list <- purrr::map(x, rlang::call_args)
function_name_list <- purrr::map(x, rlang::call_name)
# add namespaces to functions when used
function_namespaces <- purrr::map(x, rlang::call_ns)
function_name_list <- purrr::map2(
function_namespaces,
function_name_list,
prepend_namespace
)
if (length(x) == 1) {
.yml$output <- parse_output_yml(args_list[[1]], function_name_list[[1]])
return(.yml)
}
warn_if_duplicate_fields(.yml, list(output = ""))
.yml$output <- purrr::map2(
args_list,
function_name_list,
parse_output_yml,
use_default = TRUE
) %>%
purrr::flatten()
.yml
}
eval_with_rmarkdown <- function(x, check_type = TRUE) {
msg <- "rmarkdown must be installed to use outputs"
if (!requireNamespace("rmarkdown", quietly = TRUE)) stop(msg, call. = FALSE)
x <- withr::with_namespace(
"rmarkdown",
rlang::eval_tidy(x)
)
if (check_type && !inherits(x, "rmarkdown_output_format")) {
stop(
"`output` must return object of class `rmarkdown_output_format`",
call. = FALSE
)
}
x
}
parse_output_yml <- function(args, function_name, use_default = FALSE) {
if (!rlang::has_length(args) && !use_default) {
return(function_name)
}
if (!rlang::has_length(args) && use_default) {
output_yml <- list("default")
names(output_yml) <- function_name
return(output_yml)
}
yml_list <- list(
purrr::map_if(args, rlang::is_call, eval_with_rmarkdown, check_type = FALSE))
names(yml_list) <- function_name
yml_list
}
stop_yml_eval <- function(e, x) {
stop(
"Invalid argument in YAML output function ",
rlang::quo_text(x),
"\n",
as.character(e),
call. = FALSE
)
}
eval_tidy_yml <- function(x) {
out <- rlang::catch_cnd(
eval_with_rmarkdown(x),
classes = "error"
)
if (!is.null(out)) stop_yml_eval(out, x)
out
}
validate_output_yml <- function(.function_calls) {
purrr::walk(.function_calls, eval_tidy_yml)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_output.R |
#' Top-level YAML options for pagedown
#'
#' pagedown offers several output functions for paginated output, resumes,
#' business cards, theses, and morem as described in the [pagedown
#' vignette](https://pagedown.rbind.io/). pagedown also accepts a few custom
#' top-level YAML. See [pagedown_business_card_template()] for more on setting
#' up the YAML for a business card.
#'
#' @template describe_yml_param
#' @param toc Logical. Use a table of contents?
#' @param toc_title The title for the table of contents. Note that the actual
#' YAML field is `toc-title`
#' @param lot Logical. Use a list of figures?
#' @param lot_title The title for the list of figures. Note that the actual YAML
#' field is `lot-title`
#' @param chapter_name The chapter title prefix
#' @param links_to_footnotes Logical. Transform all the URLs to footnotes? Note
#' that the actual YAML field is `links-to-footnotes`
#' @param paged_footnotes Logical. Render notes as footnotes? Note that the
#' actual YAML field is `paged-footnotes`
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_pagedown_opts(
#' toc = TRUE,
#' toc_title = "TOC",
#' chapter_name = c("CHAPTER\\ ", "."),
#' links_to_footnotes = TRUE
#' )
#'
#' @family pagedown
yml_pagedown_opts <- function(
.yml,
toc = yml_blank(),
toc_title = yml_blank(),
lot = yml_blank(),
lot_title = yml_blank(),
chapter_name = yml_blank(),
links_to_footnotes = yml_blank(),
paged_footnotes = yml_blank()
) {
pagedown_opts <- list(
toc = toc,
"toc-title" = toc_title,
lot = lot,
"lot-title" = lot_title,
chapter_name = chapter_name,
"links-to-footnotes" = links_to_footnotes,
"paged-footnotes" = paged_footnotes
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pagedown_opts)
.yml[names(pagedown_opts)] <- pagedown_opts
.yml
}
#' Generate a full YAML template for your pagedown business card
#'
#' pagedown has a unique output type to make business cards:
#' `pagedown::business_card()`. `pagedown_business_card_template()` creates a
#' YAML template to use for this output. What's unique about this output type is
#' that almost all of the contents are supplied through YAML. An R Markdown file
#' that only contains YAML related to the business card is enough to produce the
#' output, although you can also customize the output in the body of the
#' document (see the [pagedown vignette](https://pagedown.rbind.io/)). A good
#' workflow to write a business card is to use
#' `pagedown_business_card_template()` to specify the YAML and pass it to
#' [use_rmarkdown()], which you can then to knit into business cards.
#'
#' @param name The name
#' @param person When you are creating business cards for numerous people with
#' shared information, passing values to the `person` field can override the
#' default values, which can be any of the values accepted by this function.
#' Use `pagedown_person()` to do so or manually provide them using `list(field
#' = value)`.
#' @param title The title of the person
#' @param phone A phone number
#' @param email An email address
#' @param url A website URL
#' @param address The address
#' @param logo A path to a logo file
#' @param .repeat The number of cards to repeat. Note that the actual YAML field
#' is `repeat`.
#' @param paperwidth The paper width
#' @param paperheight The paper height
#' @param cardwidth The width of the card
#' @param cardheight The height of the card
#' @param cols The number of columns in the card grid
#' @param rows The rows of columns in the card grid
#' @param mainfont The font
#' @param googlefonts A character vector of Google Fonts
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#' pagedown_business_card_template(
#' name = "Jane Doe",
#' title = "Miss Nobody",
#' phone = "+1 123-456-7890",
#' email = "[email protected]",
#' url = "www.example.com",
#' address = "2020 South Street,
#' Sunshine, CA 90000",
#' logo = "logo.png",
#' .repeat = 12
#' )
#'
#' pagedown_business_card_template(
#' phone = "+1 123-456-7890",
#' url = "www.example.com",
#' address = "2020 South Street,
#' Sunshine, CA 90000",
#' logo = "logo.png",
#' person = list(
#' pagedown_person(
#' name = "Jane Doe",
#' title = "Miss Nobody",
#' email = "[email protected]",
#' .repeat = 6
#' ),
#' pagedown_person(
#' name = "John Doe",
#' title = "Mister Nobody",
#' phone = "+1 777-777-7777", # overrides the default phone
#' email = "[email protected]",
#' .repeat = 6
#' )
#' ),
#' paperwidth = "8.5in",
#' paperheight = "11in",
#' cols = 4,
#' rows = 3
#' )
#'
#' @seealso [`use_rmarkdown()`]
#' @family pagedown
pagedown_business_card_template <- function(
name = yml_blank(),
person = yml_blank(),
title = yml_blank(),
phone = yml_blank(),
email = yml_blank(),
url = yml_blank(),
address = yml_blank(),
logo = yml_blank(),
.repeat = yml_blank(),
paperwidth = yml_blank(),
paperheight = yml_blank(),
cardwidth = yml_blank(),
cardheight = yml_blank(),
cols = yml_blank(),
rows = yml_blank(),
mainfont = yml_blank(),
googlefonts = yml_blank(),
...
) {
list(
name = name,
person = person,
title = title,
phone = phone,
email = email,
url = url,
address = address,
logo = logo,
"repeat" = .repeat,
paperwidth = paperwidth,
paperheight = paperheight,
cardwidth = cardwidth,
cardheight = cardheight,
cols = cols,
rows = rows,
mainfont = mainfont,
googlefonts = googlefonts,
output = "pagedown::business_card",
...
) %>%
purrr::discard(is_yml_blank) %>%
as_yml()
}
#' @export
#' @rdname pagedown_business_card_template
pagedown_person <- function(...) {
pagedown_business_card_template(...) %>%
yml_discard("output") %>%
unclass()
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_pagedown.R |
#' Parameterize an R Markdown report using Shiny components
#'
#' R Markdown lets you add dynamic parameters to your report using the `params`
#' YAML field (see the [R Markdown
#' book](https://bookdown.org/yihui/rmarkdown/parameterized-reports.html) for
#' examples); parameterized reports are also used in RStudio Connect. The values
#' of these variables can be called inside your R Markdown document using
#' `params$field_name`. [There are several ways to change the values of the
#' parameters](https://bookdown.org/yihui/rmarkdown/params-knit.html): manually
#' change the YAML, use the `params` argument in `rmarkdown::render()`, or knit
#' with parameters, which launches a Shiny app to select values for each.
#' `yml_params()` accepts any number of named R objects to set as YAML fields.
#' You can also pass arguments to the underlying Shiny functions using YAML. To
#' set a shiny component, use the `shiny_*()` helper functions. `shiny_params()`
#' captures a Shiny output function and transforms it to YAML. However, R
#' Markdown supports only a limited number of components; each of these is
#' included as a function starting with `shiny_*()`, e.g. `shiny_checkbox()`
#'
#' @template describe_yml_param
#' @param .shiny a Shiny function call to capture and convert to YAML
#' @param width The width of the input, e.g. '400px', or '100%'; see
#' [shiny::validateCssUnit()]
#' @template describe_dots_param
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_params(
#' z = "z",
#' x = shiny_numeric("Starting value", 23),
#' no = shiny_checkbox("No option?"),
#' y = shiny_slider("Data range", 0, 1, .5, round = TRUE)
#' )
#'
#' @family R Markdown
#' @family shiny
#' @seealso [`yml_params_code()`]
yml_params <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(params = ""))
.yml$params <- list(...)
.yml
}
#' @export
#' @rdname yml_params
shiny_params <- function(.shiny) {
x <- rlang::enquo(.shiny)
args <- rlang::call_args(x)
arg_names <- names(args)
args <- purrr::map(args, rlang::eval_tidy)
names(args) <- arg_names
function_name <- rlang::call_name(x)
function_namspace <- rlang::call_ns(x)
function_name <- ifelse(
!is.null(function_namspace),
paste0(function_namspace, "::", function_name),
function_name
)
validate_shiny_yml(function_name, args)
parse_shiny_yml(args, switch_shiny_param(function_name))
}
switch_shiny_param <- function(x) {
switch(
x,
checkboxInput = "checkbox",
numericInput = "numeric",
sliderInput = "slider",
dateInput = "date",
textInput = "text",
fileInput = "file",
radioButtons = "radio",
selectInput = "select",
passwordInput = "password",
"shiny::checkboxInput" = "checkbox",
"shiny::numericInput" = "numeric",
"shiny::sliderInput" = "slider",
"shiny::dateInput" = "date",
"shiny::textInput" = "text",
"shiny::fileInput" = "file",
"shiny::radioButtons" = "radio",
"shiny::selectInput" = "select",
"shiny::passwordInput" = "password"
)
}
parse_shiny_yml <- function(args, function_name) {
yml_list <- purrr::map_if(args, rlang::is_call, rlang::eval_tidy)
input_type <- list(input = function_name)
yml_list <- c(input_type, yml_list)
# drop `inputId` argument if needed
.keep <- names(yml_list) != "inputId"
yml_list[.keep]
}
stop_yml_eval_shiny <- function(e, x) {
stop(
"Invalid argument in YAML Shiny parameter function ",
paste0(x, "()"),
"\n",
as.character(e),
call. = FALSE
)
}
eval_tidy_shiny_yml <- function(.function_call, .function_name) {
out <- rlang::catch_cnd(
.function_call()
)
if (!is.null(out)) stop_yml_eval_shiny(out, .function_name)
out
}
validate_shiny_yml <- function(.function_name, .args) {
stop_if_not_shiny_param(.function_name)
# parse & evaluate string "pkg::func" to retrieve actual function object
.f <- rlang::parse_expr(.function_name) %>%
rlang::eval_tidy()
# create a call using `purrr::partial` to set arguments
.function_call <- purrr::partial(
.f,
inputId = "inputId",
!!!.args
)
.function_call <- eval_tidy_shiny_yml(.function_call, .function_name)
invisible(.function_call)
}
stop_if_not_shiny_param <- function(.function_name) {
valid_fs <- c(
"checkboxInput",
"numericInput",
"sliderInput",
"dateInput",
"textInput",
"fileInput",
"radioButtons",
"selectInput",
"passwordInput"
)
valid_functions <- c(valid_fs, paste0("shiny::", valid_fs))
if (!(.function_name %in% valid_functions)) {
valid_functions <- valid_fs %>%
paste0("()") %>%
glue::glue_collapse(sep = ", ", last = ", or ")
stop(
"Invalid Shiny function ",
.function_name,
"\n",
"Must be one of: ",
valid_functions,
call. = FALSE
)
}
invisible(.function_name)
}
#' @inheritParams shiny::checkboxInput
#' @export
#' @rdname yml_params
shiny_checkbox <- function(label, value = FALSE, width = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::checkboxInput(inputId = "id", label = !!label, value = !!value, width = !!width)
)
remove_default_values(param_list, shiny::checkboxInput)
}
#' @inheritParams shiny::numericInput
#' @export
#' @rdname yml_params
shiny_numeric <- function(label, value, min = NA, max = NA, step = NA, width = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::numericInput(
inputId = "id",
label = !!label,
value = !!value,
min = !!min,
max = !!max,
step = !!step,
width = !!width
)
)
remove_default_values(param_list, shiny::numericInput)
}
#' @inheritParams shiny::sliderInput
#' @param animate `TRUE` to show simple animation controls with default
#' settings; `FALSE` not to; or a custom settings list, such as those created
#' using [shiny::animationOptions()]
#' @export
#' @rdname yml_params
shiny_slider <- function(label, min, max, value, step = NULL,
round = FALSE, format = NULL, ticks = TRUE,
animate = FALSE, width = NULL, sep = ",", pre = NULL,
post = NULL, timeFormat = NULL, timezone = NULL,
dragRange = TRUE) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::sliderInput(
inputId = "id",
label = !!label,
min = !!min,
max = !!max,
value = !!value,
step = !!step,
round = !!round,
ticks = !!ticks,
animate = !!animate,
width = !!width,
sep = !!sep,
pre = !!pre,
post = !!post,
timeFormat = !!timeFormat,
timezone = !!timezone,
dragRange = !!dragRange
)
)
remove_default_values(param_list, shiny::sliderInput)
}
#' @inheritParams shiny::dateInput
#' @export
#' @rdname yml_params
shiny_date <- function(label, value = NULL, min = NULL, max = NULL,
format = "yyyy-mm-dd", startview = "month", weekstart = 0,
language = "en", width = NULL, autoclose = TRUE,
datesdisabled = NULL, daysofweekdisabled = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::dateInput(
inputId = "id",
label = !!label,
value = !!value,
min = !!min,
max = !!max,
format = !!format,
startview = !!startview,
weekstart = !!weekstart,
language = !!language,
width = !!width,
autoclose = !!autoclose,
datesdisabled = !!datesdisabled,
daysofweekdisabled = !!daysofweekdisabled
)
)
remove_default_values(param_list, shiny::dateInput)
}
#' @inheritParams shiny::textInput
#' @export
#' @rdname yml_params
shiny_text <- function(label, value = "", width = NULL, placeholder = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::textInput(
inputId = "id",
label = !!label,
value = !!value,
width = !!width,
placeholder = !!placeholder
)
)
remove_default_values(param_list, shiny::textInput)
}
#' @inheritParams shiny::fileInput
#' @export
#' @rdname yml_params
shiny_file <- function(label, multiple = FALSE, accept = NULL, width = NULL,
buttonLabel = "Browse...", placeholder = "No file selected") {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::fileInput(
inputId = "id",
label = !!label,
multiple = !!multiple,
accept = !!accept,
width = !!width,
buttonLabel = !!buttonLabel,
placeholder = !!placeholder
)
)
remove_default_values(param_list, shiny::fileInput)
}
#' @inheritParams shiny::radioButtons
#' @export
#' @rdname yml_params
shiny_radio <- function(label, choices = NULL, selected = NULL, inline = FALSE,
width = NULL, choiceNames = NULL, choiceValues = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::radioButtons(
inputId = "id",
label = !!label,
choices = !!choices,
selected = !!selected,
inline = !!inline,
width = !!width,
choiceNames = !!choiceNames,
choiceValues = !!choiceValues
)
)
remove_default_values(param_list, shiny::radioButtons)
}
#' @inheritParams shiny::selectInput
#' @export
#' @rdname yml_params
shiny_select <- function(label, choices, selected = NULL, multiple = FALSE,
selectize = TRUE, width = NULL, size = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::selectInput(
inputId = "id",
label = !!label,
choices = !!choices,
selected = !!selected,
multiple = !!multiple,
selectize = !!selectize,
width = !!width,
size = !!size
)
)
remove_default_values(param_list, shiny::selectInput)
}
#' @inheritParams shiny::passwordInput
#' @export
#' @rdname yml_params
shiny_password <- function(label, value = "", width = NULL, placeholder = NULL) {
stop_if_shiny_not_installed()
param_list <- shiny_params(
shiny::passwordInput(
inputId = "id",
label = !!label,
value = !!value,
width = !!width,
placeholder = !!placeholder
)
)
remove_default_values(param_list, shiny::passwordInput)
}
remove_default_values <- function(args, .f) {
fmls <- as.list(formals(.f))
# The first argument (input/inputId) is required, so always include it
result <- args[1]
for (nm in names(args)[-1]) {
if (!nm %in% names(fmls)) {
stop(
"The following arguments don't exist in the function that they're",
" trying to be used in: ", nm,
call. = FALSE
)
}
if (!identical(args[nm], fmls[nm])) {
result <- c(result, args[nm])
}
}
result
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_params.R |
#' Generate a full YAML template for your pkgdown site
#'
#' pkgdown includes three helpful `pkgdown::template_*()` functions to generate
#' the navbar, reference, and article YAML for the `_pkgdown.yml` file.
#' `pkgdown_template()` is a wrapper function that runs all three, combines
#' them, and converts them to a `yml` object. You may also pass
#' `pkgdown::template_*()` functions to `as_yml()` to convert the individual
#' sections. `pkgdown_template()` is particularly useful with
#' `use_pkgdown_yml()` to write directly to the `_pkgdown.yml` file.
#'
#' @param path The path to your package directory
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#' \dontrun{
#' # requires this to be a package directory
#' pkgdown_template() %>%
#' use_pkgdown_yml()
#' }
#'
#' @family pkgdown
#' @seealso [`use_pkgdown_yml()`]
pkgdown_template <- function(path = ".") {
stop_if_not_installed("pkgdown")
reference <- pkgdown::template_reference(path = path)
articles <- pkgdown::template_articles(path = path)
navbar <- pkgdown::template_navbar(path = path)
c(reference, articles, navbar) %>%
as_yml()
}
#' Set Top-level YAML options for pkgdown
#'
#' These functions set YAML for various pkgdown options to be used in
#' `_pkgdown.yml`. The options are described in greater depth in the [pkgdown
#' vignette](https://pkgdown.r-lib.org/articles/pkgdown.html) and in the help
#' pages for `pkgdown::build_site()`, `pkgdown::build_articles()`, `pkgdown::build_reference()`, and `pkgdown::build_tutorials()`.
#' Essentially, they control the build of vignettes and function references.
#' pkgdown also uses the same approach to navbars as R Markdown.
#' [`yml_navbar()`] and friends will help you write the YAML for that. A useful
#' approach to writing pkgdown YAML might be to use `pkgdown_template()` to
#' build a template based on your package directory, modify with
#' `yml_pkgdown_*()` and `pkgdown_*()` functions or [yml_replace()] and
#' [yml_discard()], then pass the results to [use_pkgdown_yml()] to write to
#' `_pkgdown.yml`
#'
#'
#' @template describe_yml_param
#' @template describe_dots_param
#' @param as_is Logical. Use the `output_format` and options that you have
#' specified?
#' @param extension The output extension, e.g. "pdf".
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml_empty() %>%
#' yml_pkgdown(
#' as_is = TRUE,
#' extension = "pdf"
#' ) %>%
#' yml_pkgdown_reference(
#' pkgdown_ref(
#' title = "pkgdown functions",
#' contents = "contains('function_name')"
#' )
#' ) %>%
#' yml_pkgdown_articles(
#' pkgdown_article(
#' title = "Introduction to the package"
#' )
#' )
#'
#' @family pkgdown
#' @family websites
#' @seealso [use_pkgdown_yml()] [yml_navbar()]
yml_pkgdown <- function(.yml, as_is = yml_blank(), extension = yml_blank()) {
.yml$pkgdown <- list(as_is = as_is, extension = extension)
.yml
}
#' @param site_title The title of the website (by default, this is the package
#' name). Note that the actual YAML is `title` (specified as `site_title` to
#' avoid duplication with content titles).
#' @param destination The path where the site should be rendered ("docs/" by
#' default)
#' @param url URL where the site will be published; setting the URL will allow
#' other pkgdown sites to link to your site when needed, generate a
#' `sitemap.xml` to increase the searchability of your site, and generate a
#' `CNAME`.
#' @param toc_depth The depth of the headers included in the Table of Contents.
#' Note that the actual YAML is `depth` and is nested under `toc`.
#'
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_opts <- function(
.yml,
site_title = yml_blank(),
destination = yml_blank(),
url = yml_blank(),
toc_depth = yml_blank()
) {
pkgdown_opts <- list(
title = site_title,
destination = destination,
url = url,
toc = list(depth = toc_depth) %>% purrr::discard(is_yml_blank)
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pkgdown_opts)
.yml[names(pkgdown_opts)] <- pkgdown_opts
.yml
}
#' @param mode The development mode of the site, one of: "auto", "release",
#' "development", or "unreleased". `development` controls where the site is
#' built; the color of the package version; the optional tooltip associated
#' with the version; and the indexing of the site by search engines. See
#' `?pkgdown::build_site()` for more details.
#' @param dev_destination The subdirectory used for the development site, which
#' defaults to "dev/". Note that the actual YAML is `destination` and is
#' nested under `development`.
#' @param version_label Label to display for "development" and "unreleased"
#' mode. One of: "danger" (the default), "default", "info", or "warning".
#' @param version_tooltip A custom message to include in the version tooltip
#'
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_development <- function(
.yml,
mode = yml_blank(),
dev_destination = yml_blank(),
version_label = yml_blank(),
version_tooltip = yml_blank()
) {
pkgdown_development_opts <- list(
mode = mode,
destination = dev_destination,
version_label = version_label,
version_tooltip = version_tooltip
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pkgdown_development_opts)
.yml[names(pkgdown_development_opts)] <- pkgdown_development_opts
.yml
}
#' @param bootswatch A bootswatch theme for the site. See the options at
#' <https://rstudio.github.io/shinythemes/>.
#'
#' @param ganalytics A Google Analytics tracking id
#' @param noindex Logical. Suppress indexing of your pages by web robots?
#' @param package an R package with with directories `inst/pkgdown/assets` and
#' `inst/pkgdown/templates` to override the default templates and add
#' additional assets; alternatively, you can specify this in `path` and
#' `assets`
#' @param path A path to templates with which to override the default pkgdown
#' templates
#' @param assets A path to additional assets to include
#' @param default_assets Logical. Include default assets?
#'
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_template <- function(
.yml,
bootswatch = yml_blank(),
ganalytics = yml_blank(),
noindex = yml_blank(),
package = yml_blank(),
path = yml_blank(),
assets = yml_blank(),
default_assets = yml_blank()
) {
pkgdown_template_opts <- list(
bootswatch = bootswatch,
ganalytics = ganalytics,
noindex = noindex,
package = package,
path = path,
assets = assets,
default_assets = default_assets
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pkgdown_template_opts)
.yml[names(pkgdown_template_opts)] <- pkgdown_template_opts
.yml
}
#' @param title The title of the article, reference, tutorial, or other resource
#' @param desc A description of the article or reference
#' @param contents The contents, which can also be dplyr-style tidy selectors
#' (e.g `"contains('index')"`).
#' @param exclude What to exclude of the what's captured by `contents`
#'
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_reference <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(references = ""))
.yml$references <- c(...)
.yml
}
#' @export
#' @rdname yml_pkgdown
pkgdown_ref <- function(
title = yml_blank(),
desc = yml_blank(),
contents = yml_blank(),
exclude = yml_blank(),
...
) {
list(
title = title,
desc = desc,
contents = contents,
exclude = exclude,
...
) %>%
purrr::discard(is_yml_blank)
}
#' @param one_page Logical. Create one page per release for `NEWS.md`?
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_news <- function(.yml, one_page = yml_blank()) {
warn_if_duplicate_fields(.yml, list(news = ""))
.yml$news <- list(one_page = one_page)
.yml
}
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_articles <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(articles = ""))
.yml$articles <- c(...)
.yml
}
#' @export
#' @rdname yml_pkgdown
pkgdown_article <- function(
title = yml_blank(),
desc = yml_blank(),
contents = yml_blank(),
exclude = yml_blank(),
...
) {
list(
title = title,
desc = desc,
contents = contents,
exclude = exclude,
...
) %>%
purrr::discard(is_yml_blank)
}
#' @param name The name of the file
#' @param tutorial_url The tutorial URL to embed in an iframe
#' @param source A URL to the source code of the tutorial
#'
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_tutorial <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(references = ""))
.yml$references <- c(...)
.yml
}
#' @export
#' @rdname yml_pkgdown
pkgdown_tutorial <- function(
name = yml_blank(),
title = yml_blank(),
tutorial_url = yml_blank(),
source = yml_blank(),
...
) {
list(
name = name,
title = title,
url = tutorial_url,
source = source,
...
) %>%
purrr::discard(is_yml_blank)
}
#' @param dev The graphics device (default: "grDevices::png")
#' @param dpi The DPI (default: 96)
#' @param dev.args A vector of arguments to pass to `dev`
#' @param fig.ext The figure extension (default: "png")
#' @param fig.width The figure width (default: 7.2916667)
#' @param fig.height The figure height (default: `NULL`)
#' @param fig.retina The figure retina value (default: 2)
#' @param fig.asp The aspect ratio (default: 1.618)
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_figures <- function(
.yml,
dev = yml_blank(),
dpi = yml_blank(),
dev.args = yml_blank(),
fig.ext = yml_blank(),
fig.width = yml_blank(),
fig.height = yml_blank(),
fig.retina = yml_blank(),
fig.asp = yml_blank(),
...
) {
warn_if_duplicate_fields(.yml, list(figures = ""))
.yml$figures <- list(
dev = dev,
dpi = dpi,
dev.args = dev.args,
fig.ext = fig.ext,
fig.width = fig.width,
fig.height = fig.height,
fig.retina = fig.retina,
fig.asp = fig.asp,
...
) %>%
purrr::discard(is_yml_blank)
.yml
}
#' @param api_key The API key provided by docsearch (see the [pkgdown
#' vignette](https://pkgdown.r-lib.org/articles/pkgdown.html))
#' @param index_name The index name provided by docsearch (see the [pkgdown
#' vignette](https://pkgdown.r-lib.org/articles/pkgdown.html))
#' @param doc_url the URL specifying the location of your documentation. Note that the actual YAML field is `url` but is nested.
#' @export
#' @rdname yml_pkgdown
yml_pkgdown_docsearch <- function(.yml, api_key = yml_blank(), index_name = yml_blank(), doc_url = yml_blank()) {
docsearch <- list(
template = list(
params = list(
docsearch = list(
api_key = api_key,
index_name = index_name
) %>%
purrr::discard(is_yml_blank)
)
),
url = doc_url
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, docsearch)
.yml[names(docsearch)] <- docsearch
.yml
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_pkgdown.R |
#' Replace, pluck, or discard top-level YAML fields
#'
#' `yml_replace()` replaces a named field with another value. As opposed to
#' duplicating top-level fields with other functions, explicitly replacing them
#' with `yml_replace()` will not raise a warning. `yml_discard()` removes values
#' given either a character vector of names or a purrr-style lambda with a
#' predicate (~ predicate); see the examples. `yml_pluck()` and `yml_chuck()`
#' are wrappers around [purrr::pluck()] and [purrr::chuck()] that return `yml`
#' objects.
#'
#' @template describe_yml_param
#' @param .rid a character vector of fields to remove or a purrr-style lambda
#' with a predicate (~ predicate) where fields that are `TRUE` will be
#' discarded
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'\donttest{
#' yml() %>%
#' yml_clean(TRUE) %>%
#' yml_replace(clean = FALSE) %>%
#' yml_discard("author")
#'
#' yml() %>%
#' yml_output(
#' pdf_document(),
#' html_document()
#' )%>%
#' yml_discard(~ length(.x) > 1)
#'}
#'
yml_replace <- function(.yml, ...) {
new <- list(...)
.yml[names(new)] <- new
.yml
}
#' @export
#' @rdname yml_replace
yml_discard <- function(.yml, .rid) {
if (is.character(.rid)) {
return(
.yml[names(.yml) %nin% .rid] %>%
as_yml()
)
}
if (is.numeric(.rid)) {
return(
.yml[-.rid] %>%
as_yml()
)
}
if (rlang::is_formula(.rid)) {
return(
purrr::discard(.yml, .rid) %>%
as_yml()
)
}
msg <- glue::glue(
"`.rid` must be a character vector of field names \\
or a formula specifying a predicate"
)
stop(msg, call. = FALSE)
}
#' @export
#' @rdname yml_replace
yml_pluck <- function(.yml, ...) {
purrr::pluck(.yml, ..., .default = list()) %>%
as_yml()
}
#' @export
#' @rdname yml_replace
yml_chuck <- function(.yml, ...) {
purrr::chuck(.yml, ...) %>%
as_yml()
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_replace.R |
#' Activate Shiny in R Markdown
#'
#' The `runtime` field lets you use Shiny in your R Markdown document, making it
#' interactive. See the [R Markdown
#' book](https://bookdown.org/yihui/rmarkdown/interactive-documents.html) for
#' examples.
#'
#' @template describe_yml_param
#' @param runtime The runtime target for rendering. `static`, the default,
#' renders static documents; `shiny` allows you to include use Shiny in your
#' document. `shiny_prerendered` is a subset of the `shiny` runtime that
#' allows pre-rendering of app components (see the [R Markdown
#' site](https://rmarkdown.rstudio.com/authoring_shiny_prerendered.html) for
#' more)
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_runtime("shiny")
#'
#' @family R Markdown
#' @family shiny
yml_runtime <- function(.yml, runtime = c("static", "shiny", "shiny_prerendered")) {
warn_if_duplicate_fields(.yml, list(runtime = ""))
.yml$runtime <- match.arg(runtime)
.yml
}
#' Remove intermediate rendering files
#'
#' R Markdown may create many documents while rendering the final product, for
#' instance by using knitr to turn the R Markdown file to a Markdown file and
#' then using Pandoc to convert to the final output. The `clean` field tells R
#' Markdown whether or not to remove these files.
#'
#' @template describe_yml_param
#' @param clean Logical. Remove intermediate files that are created while making
#' the R Markdown document?
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' # keep intermediate files
#' yml_clean(FALSE)
#'
#' @family R Markdown
yml_clean <- function(.yml, clean) {
stop_if_not_type(clean, "logical")
warn_if_duplicate_fields(.yml, list(clean = ""))
.yml$clean <- clean
.yml
}
#' Set up a package vignette
#'
#' To use an R Markdown file as a vignette, you need to specify an output format
#' appropriate for inclusion in a package (for example, the lightweight
#' `html_vignette()` output function included in rmarkdown) and to specify the
#' `vignette` field, which specifies the title, engine, and encoding type of the
#' vignette. See also [usethis::use_vignette()] for setting up a package
#' vignette.
#'
#' @template describe_yml_param
#' @param title The title of the vignette
#' @param engine The rendering engine for the vignette ("knitr::rmarkdown" by
#' default)
#' @param encoding The character encoding for the document ("UTF-8" by default).
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_output(html_vignette()) %>%
#' yml_vignette("An introduction to R Markdown")
#'
#' @family R Markdown
yml_vignette <- function(.yml, title, engine = "knitr::rmarkdown", encoding = "UTF-8") {
warn_if_duplicate_fields(.yml, list(vignette = ""))
.yml$vignette <- glue::glue(
"%\\VignetteIndexEntry{<<title>>} \n\\
%\\VignetteEngine{<<engine>>} \n\\
%\\VignetteEncoding{<<encoding>>})",
.open = "<<",
.close = ">>"
)
.yml
}
#' Specify Table of Contents options
#'
#' It's generally better to specify Table of Contents in the output function you
#' are using so you have a clearer idea of your options (e.g. `html_document(toc
#' = TRUE, toc_float = TRUE)`). However, you can also generally specify at the
#' top level of YAML.
#'
#' @template describe_yml_param
#' @param toc Logical. Use a Table of Contents?
#' @param toc_depth An integer. The depth of headers to use in the TOC. Note
#' that the actual YAML field is `toc-depth`.
#' @param toc_title The title of the TOC. Note that the actual YAML field is
#' `toc-title`.
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_toc(toc = TRUE, toc_depth = 1, toc_title = "Article Outline")
#'
yml_toc <- function(
.yml,
toc = yml_blank(),
toc_depth = yml_blank(),
toc_title = yml_blank(),
...
) {
toc_opts <- list(
toc = toc,
"toc-depth" = toc_depth,
"toc-title" = toc_title,
...
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, toc_opts)
.yml[names(toc_opts)] <- toc_opts
.yml
}
#' Add external resource files to R Markdown document
#'
#' The `resource_files` field specifies a character vectors of paths to external
#' resources to include in the output, e.g. files that are necessary for
#' rendering. These files are handled with
#' `rmarkdown::find_external_resources()`.
#'
#' @template describe_yml_param
#' @param resource_files A path to a file, directory, or a wildcard pattern
#' (such as "data/*.csv")
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_resource_files(c("data/mydata.csv", "images/figure.png"))
yml_resource_files <- function(.yml, resource_files) {
stop_if_not_type(resource_files, "character")
warn_if_duplicate_fields(.yml, list(resource_files = ""))
.yml$resource_files <- resource_files
.yml
}
#' Add site options for `_site.yml` and navbars for R Markdown websites
#'
#' R Markdown has a simple website builder baked in (see the R [Markdown
#' book](https://bookdown.org/yihui/rmarkdown/rmarkdown-site.html#site_navigation)
#' for a detailed description). An R Markdown website must have at least have an
#' `index.Rmd` file and a `_site.yml` file (which can be empty). Including YAML
#' in `_site.yml` will apply it to all R Markdown files for the website, e.g.
#' setting the output format here will tell R Markdown to use that format across
#' the website. R Markdown websites also support navbars, which you can specify
#' with YAML (see [yml_navbar()], as well as ?rmarkdown::render_site and
#' ?rmarkdown::html_document). Pass `navbar_page()` to the `left` or `right`
#' field to set up page tabs and use `navbar_separator()` to include a
#' separators. In addition to writing YAML with `yml_*()` functions,
#' `use_site_yml()` will take the a `yml` object and write it to a `_site.yml`
#' file for you.
#'
#' @template describe_yml_param
#' @param name The name of the website
#' @param favicon Path to a file to use as the favicon
#' @param output_dir Directory to copy site content into ("_site" is the default
#' if none is specified)
#' @param include,exclude Files to include or exclude from the copied into
#' `output_dir`. You can use `*` to indicate a wildcard selection, e.g.
#' "*.csv".
#' @param new_session Logical. Should each website file be rendered in a new
#' R session?
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#' yml_empty() %>%
#' yml_site_opts(
#' name = "my-website",
#' output_dir = "_site",
#' include = "demo.R",
#' exclude = c("docs.txt", "*.csv")
#' ) %>%
#' yml_navbar(
#' title = "My Website",
#' left = list(
#' navbar_page("Home", href = "index.html"),
#' navbar_page(navbar_separator(), href = "about.html")
#' )
#' ) %>%
#' yml_output(html_document(toc = TRUE, highlight = "textmate"))
#'
#' @family R Markdown
#' @family websites
#' @seealso [use_site_yml()] [use_navbar_yml()] [use_index_rmd()]
yml_site_opts <- function(
.yml,
name = yml_blank(),
favicon = yml_blank(),
output_dir = yml_blank(),
include = yml_blank(),
exclude = yml_blank(),
new_session = yml_blank(),
...
) {
site_opts <- list(
name = name,
favicon = favicon,
output_dir = output_dir,
include = include,
exclude = exclude,
new_session = new_session,
...
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, site_opts)
.yml[names(site_opts)] <- site_opts
.yml
}
#' @param title The title of the website
#' @param type The color scheme for the navigation bar: either "default" or "inverse".
#' @param left,right the side of the navbar a `navbar_page()` should go (see example)
#' @export
#' @rdname yml_site_opts
yml_navbar <- function(.yml, title = yml_blank(), type = yml_blank(),
left = yml_blank(), right = yml_blank(), ...) {
navbar <- list(
title = title,
type = type,
left = left,
right = right,
...
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, list(navbar = ""))
.yml$navbar <- navbar
.yml
}
#' @param text The link text
#' @param href The link URL
#' @param icon An icon to include
#' @param menu drop-down menus specified by including another `navbar_page()`
#'
#' @export
#' @rdname yml_site_opts
navbar_page <- function(text = yml_blank(), href = yml_blank(), icon = yml_blank(), menu = yml_blank(), ...) {
list(
text = text,
href = href,
icon = icon,
menu = menu,
...
) %>%
purrr::discard(is_yml_blank)
}
#' @export
#' @rdname yml_site_opts
navbar_separator <- function() {
"---------"
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_rmarkdown.R |
#' Set YAML for Scheduled Emails in RStudio Connect
#'
#' RStudio Connect allows you to schedule emails to send using R Markdown. It
#' uses a special type of YAML using the top-level field `rmd_output_metadata`
#' that tells RStudio Connect about the email output. Several `rsc_*` fields
#' exist to specify different components of the email, which can be set in the
#' YAML header or programmatically using `rmarkdown::output_metadata()`. See the
#' [RStudio Connect
#' documentation](https://docs.rstudio.com/connect/1.7.2/user/r-markdown.html)
#' for more. `yml_output_metadata()` allows you to add any type of content to
#' the `rmd_output_metadata` field.
#'
#' @template describe_yml_param
#' @param rsc_email_subject The subject of the email. A report without an
#' `rsc_email_subject` entry uses its published document name.
#' @param rsc_email_body_html,rsc_email_body_text The body of the email, either
#' in plain text or HTML. A report with neither entry uses an automatically
#' generated, plain-text body with a link to the report’s URL.
#' @param rsc_email_images Images to embed in the email. The embedded image must
#' have a Content ID that is used in the body of the HTML and when providing
#' the image to `rsc_email_images`, and the image itself must be
#' base64-encoded, e.g. with the base64enc package.
#' @param rsc_output_files A vector of file names that should be available after
#' the report has rendered. If you list a file that does not exist after
#' rendering your report, Connect will log a message but continue trying to
#' processing the other files listed. If the output files are not generated
#' during the rendering of your report, then you will also need to list them
#' in `resource_files` when you upload your report to Connect.
#' @param rsc_email_attachments A vector of file names that should be attached
#' to the email.
#' @param rsc_email_suppress_scheduled Logical. Should the email schedule be
#' suppressed? Default is `FALSE`.
#' @param rsc_email_suppress_report_attachment Logical. Should the rendered
#' document be included as an attachment? Default is `TRUE`.
#' @param resource_files A file or files to host on RStudio Connect that is
#' *not* generated by your report, e.g. an existing file.
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_rsconnect_email(
#' rsc_email_subject = "Quarterly report",
#' rsc_output_files = "data.csv",
#' rsc_email_attachments = c("attachment_1.csv", "attachment_2.csv")
#' )
yml_rsconnect_email <- function(
.yml,
rsc_email_subject = yml_blank(),
rsc_email_body_html = yml_blank(),
rsc_email_body_text = yml_blank(),
rsc_email_images = yml_blank(),
rsc_output_files = yml_blank(),
rsc_email_attachments = yml_blank(),
rsc_email_suppress_scheduled = yml_blank(),
rsc_email_suppress_report_attachment = yml_blank(),
resource_files = yml_blank(),
...
) {
rsconnect_email_opts <- list(
rmd_output_metadata = list(
rsc_email_subject = rsc_email_subject,
rsc_email_body_html = rsc_email_body_html,
rsc_email_body_text = rsc_email_body_text,
rsc_email_images = rsc_email_images,
rsc_output_files = rsc_output_files,
rsc_email_attachments = rsc_email_attachments,
rsc_email_suppress_scheduled = rsc_email_suppress_scheduled,
rsc_email_suppress_report_attachment = rsc_email_suppress_report_attachment,
...
) %>% purrr::discard(is_yml_blank),
resource_files = resource_files
) %>% purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, rsconnect_email_opts)
.yml[names(rsconnect_email_opts)] <- rsconnect_email_opts
.yml
}
#' @export
#' @rdname yml_rsconnect_email
yml_output_metadata <- function(
.yml,
...
) {
rmd_output_metadata_list <- list(
rmd_output_metadata = list(
...
) %>% purrr::discard(is_yml_blank)
)
warn_if_duplicate_fields(.yml, rmd_output_metadata_list)
.yml[names(rmd_output_metadata_list)] <- rmd_output_metadata_list
.yml
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_rsconnect.R |
#' Set YAML related to rticles output formats
#'
#' The rticles package include numerous output formats specific to academic
#' journals. All of these can take YAML similar to `pdf_document()`.
#' Additionally, two templates include custom YAML, `rticles::sage_article()`
#' and `rticles::sim_article()`. See the help pages for these functions for more
#' details and the sources of the LaTeX templates used for each.
#'
#' @template describe_yml_param
#' @param title Title of the manuscript
#' @param runninghead A character vector, a short author list for the header
#' (sage_article)
#' @param author A list of authors, containing `name` and `num` fields
#' (sage_article, sim_article). Use `rticles_author()` or a list to specify.
#' @param authormark A character vector, the short author list for the header
#' (sim_article)
#' @param address list containing `num` and `org` for defining author
#' affiliations (sage_article, sim_article). Use `rticles_address()` or a list
#' to specify.
#' @param corrauth corresponding author `name` and `address` (sage_article). Use
#' `rticles_corr_author()` or a list to specify.
#' @param corres `author` and `address` for correspondence (sim_article). Use
#' `rticles_corr_author()` or a list to specify.
#' @param email The email of the correspondence author (sage_article)
#' @param abstract The abstract, limited to 200 words (sage_article), 250 words
#' (sim_article)
#' @param received,revised,accepted The dates of submission, revision, and
#' acceptance of the manuscript (sim_article)
#' @param keywords The keywords for the article (sage_article), up to 6 keywords
#' (sim_article)
#' @param bibliography BibTeX `.bib` file name (sage_article, sim_article)
#' @param longtable Logical. Include the longtable package? Used by default from
#' pandoc to convert markdown to LaTeX code (sim_article)
#' @param classoption a character vector of `classoption` options for the
#' `sagej` class (sage_article)
#' @param header_includes additional LaTeX code to include in the header, before
#' the `\\begin\{document\}` statement (sage_article, sim_article). Note that
#' the actual YAML field is `header-includes`
#' @param include_after additional LaTeX code to include before the
#' `\\end\{document\}` statement (sage_article, sim_article). Note that the
#' actual YAML field is `include-after`.
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#'
#' yml() %>%
#' yml_rticles_opts(received = "09-12-2014")
#'
yml_rticles_opts <- function(
.yml,
title = yml_blank(),
runninghead = yml_blank(),
author = yml_blank(),
authormark = yml_blank(),
address = yml_blank(),
corrauth = yml_blank(),
corres = yml_blank(),
email = yml_blank(),
abstract = yml_blank(),
received = yml_blank(),
revised = yml_blank(),
accepted = yml_blank(),
keywords = yml_blank(),
bibliography = yml_blank(),
longtable = yml_blank(),
classoption = yml_blank(),
header_includes = yml_blank(),
include_after = yml_blank(),
...
) {
rticles_opts <- list(
title = title,
runninghead = runninghead,
author = author,
address = address,
authormark = authormark,
corrauth = corrauth,
corres = corres,
email = email,
abstract = abstract,
received = received,
revised = revised,
accepted = accepted,
keywords = keywords,
bibliography = bibliography,
longtable = longtable,
classoption = classoption,
"header-includes" = header_includes,
"include-after" = include_after,
...
)
rticles_opts <- purrr::discard(rticles_opts, is_yml_blank)
warn_if_duplicate_fields(.yml, rticles_opts)
.yml[names(rticles_opts)] <- rticles_opts
.yml
}
#' @param name The author's name
#' @param num The author's number or address number
#'
#' @export
#' @rdname yml_rticles_opts
rticles_author <- function(name = yml_blank(), num = yml_blank()) {
list(
name = name,
num = num
) %>%
purrr::discard(is_yml_blank)
}
#' @param org The author's organization
#'
#' @export
#' @rdname yml_rticles_opts
rticles_address <- function(name = yml_blank(), org = yml_blank()) {
list(
name = name,
org = org
) %>%
purrr::discard(is_yml_blank)
}
#' @export
#' @rdname yml_rticles_opts
rticles_corr_author <- function(name = yml_blank(), author = yml_blank(), address = yml_blank()) {
list(
name = name,
author = author,
address = address
) %>%
purrr::discard(is_yml_blank)
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_rticles.R |
#' Set Top-level R Markdown YAML Fields
#'
#' These functions add common top-level YAML fields for R Markdown documents,
#' such as `author`, `date`, and `title`. Each takes a `yml` object and adds
#' fields related to the function, as well as checking for duplicate fields and
#' (where possible) checking for valid entries. `yml_toplevel()` is a catch-all
#' function that will take any named R object and put in the top level of the
#' YAML; it checks for duplicate fields but is unable to validate the input
#' beyond that it is valid YAML syntax. Some R Markdown templates allow for
#' additional variations of the YAML here. For instance, the distill package
#' adds `url` and `affiliation_url` to the `author` field (see
#' [yml_distill_author], which wraps [yml_author]). Several `yml_*()` functions
#' also contain `...` which allow for these unique fields.
#'
#' @template describe_yml_param
#' @param name A character vector, name of the author(s)
#' @param affiliation The author's affiliation; must match length of `name`,
#' e.g. if `name` has length of two, `affiliation` must as well; use `NA` if
#' you don't want to include an affiliation for a given author.Note that not
#' all formats support the `affiliation` field.
#' @param email The author email address. Note that not all formats support the
#' `email` field.
#' @param date The date; by default this is "`` `r format(Sys.Date())` ``",
#' which will populate the date automatically.
#' @param format When the default `date` is used, the format passed to
#' [`format.Date()`].
#' @param title A character vector, the title of the document
#' @param subtitle A character vector, the subtitle of the document. Not all R
#' Markdown formats use subtitles, so it may depend on what you use in the
#' output field (see [yml_output()]). It is available in `pdf_document()`,
#' `html_document()`, and `word_document()` by default.
#' @param abstract A character vector, the abstract. Long character vectors are
#' automatically wrapped using valid YAML syntax. This field is not available
#' in all output formats; it is available in `pdf_document()` and
#' `html_document()` by default.
#' @param keywords A character vector of keywords. This field is not available
#' in all output formats; it is available in `pdf_document()`,
#' `html_document()`, `word_document()`, `odt_document()`, and
#' `powerpoint_presentation()` by default.
#' @param subject A character vector, the subject of the document. This field is
#' not available in all output formats; it is available in `pdf_document()`,
#' `html_document()`, `word_document()`, `odt_document()`, and
#' `powerpoint_presentation()` by default.
#' @param description A character vector, a description of the document. This
#' field is not available in all output formats; it is available in
#' `word_document()`, `odt_document()`, and `powerpoint_presentation()` by
#' default.
#' @param category A character vector, the category of the document. This field
#' is not available in all output formats; it is available in
#' `word_document()` and `powerpoint_presentation()` by default.
#' @param lang The document language using IETF language tags such as "en" or
#' "en-US". The [Language subtag lookup
#' tool](https://r12a.github.io/app-subtags/) can help find the appropriate
#' tag.
#' @template describe_dots_param
#'
#' @template describe_yml_output
#' @export
#'
#' @examples
#' yml_empty() %>%
#' yml_author("Yihui Xie") %>%
#' yml_date("02-02-2002") %>%
#' yml_title("R Markdown: An Introduction") %>%
#' yml_subtitle("Introducing ymlthis") %>%
#' yml_abstract("This paper will discuss a very important topic") %>%
#' yml_keywords(c("r", "reproducible research")) %>%
#' yml_subject("R Markdown") %>%
#' yml_description("An R Markdown reader") %>%
#' yml_category("r") %>%
#' yml_lang("en-US")
#'
yml_author <- function(.yml, name = NULL, affiliation = NULL, email = NULL, ...) {
non_null_args <- purrr::map_lgl(list(name, affiliation, email, ...), Negate(is.null)) %>%
sum()
if (!is.null(name) && non_null_args == 1) {
stop_if_not_all_type(name, "character")
.yml$author <- name
return(.yml)
}
if (non_null_args > 1) {
stop_if_not_all_type(name, "character")
stop_if_not_all_type(affiliation, "character")
# use unnamed inner list to create `-` group:
# - author
# affiliation
arg_list <- list(
name = null_if_blank(name),
affiliation = null_if_blank(affiliation),
email = null_if_blank(email),
...
) %>%
purrr::map_if(is.null, ~NA) %>%
purrr::discard(is_yml_blank)
.yml$author <- arg_list %>%
purrr::pmap(author_list)
return(.yml)
}
extra_args <- c(...) %>%
purrr::discard(is_yml_blank)
author_list <- list(author = get_author_name(), extra_args)
warn_if_duplicate_fields(.yml, author_list)
.yml[names(author_list)] <- author_list
.yml
}
author_list <- function(name, affiliation, email, ...) {
list(name = name, affiliation = affiliation, email = email, ...) %>%
purrr::discard(is.na)
}
get_author_name <- function() {
name <- getOption("usethis.full_name")
if (!is.null(name)) {
return(name)
}
name <- getOption("devtools.name")
if (!is.null(name) && name != "Your name goes here") {
return(name)
}
name <- whoami::fullname(fallback = NA)
if (!is.na(name)) {
return(name)
}
usethis::ui_stop(
"
`{usethis::ui_code(name)}` argument is missing.
Set it globally with {usethis::ui_code('options(usethis.full_name = \"My name\")')} \\
(perhaps using {usethis::ui_code('usethis::edit_r_profile()')}).
"
)
}
#' @export
#' @rdname yml_author
yml_date <- function(.yml, date = NULL, format = "") {
if (!is.null(date)) {
.yml$date <- date
return(.yml)
}
warn_if_duplicate_fields(.yml, list(date = ""))
.yml$date <- format_sys_date(format = format)
.yml
}
format_sys_date <- function(format = "") {
if (format == "") {
return("`r format(Sys.Date())`")
}
glue::glue("`r format(Sys.Date(), format = \"{format}\")`")
}
#' @export
#' @rdname yml_author
yml_title <- function(.yml, title) {
stop_if_not_type(title, "character")
warn_if_duplicate_fields(.yml, list(title = ""))
.yml$title <- title
.yml
}
#' @export
#' @rdname yml_author
yml_subtitle <- function(.yml, subtitle) {
stop_if_not_type(subtitle, "character")
warn_if_duplicate_fields(.yml, list(subtitle = ""))
.yml$subtitle <- subtitle
.yml
}
#' @export
#' @rdname yml_author
yml_abstract <- function(.yml, abstract) {
stop_if_not_type(abstract, "character")
warn_if_duplicate_fields(.yml, list(abstract = ""))
.yml$abstract <- abstract
.yml
}
#' @export
#' @rdname yml_author
yml_keywords <- function(.yml, keywords) {
stop_if_not_all_type(keywords, "character")
warn_if_duplicate_fields(.yml, list(keywords = ""))
.yml$keywords <- keywords
.yml
}
#' @export
#' @rdname yml_author
yml_subject <- function(.yml, subject) {
stop_if_not_all_type(subject, "character")
warn_if_duplicate_fields(.yml, list(subject = ""))
.yml$subject <- subject
.yml
}
#' @export
#' @rdname yml_author
yml_description <- function(.yml, description) {
stop_if_not_all_type(description, "character")
warn_if_duplicate_fields(.yml, list(description = ""))
.yml$description <- description
.yml
}
#' @export
#' @rdname yml_author
yml_category <- function(.yml, category) {
stop_if_not_all_type(category, "character")
warn_if_duplicate_fields(.yml, list(category = ""))
.yml$category <- category
.yml
}
#' @export
#' @rdname yml_author
yml_lang <- function(.yml, lang) {
stop_if_not_all_type(lang, "character")
warn_if_duplicate_fields(.yml, list(lang = ""))
.yml$lang <- lang
.yml
}
#' @export
#' @rdname yml_author
yml_toplevel <- function(.yml, ...) {
toplevel_yml <- c(...)
warn_if_duplicate_fields(.yml, toplevel_yml)
.yml[names(toplevel_yml)] <- toplevel_yml
.yml
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/R/yml_top.R |
# Resources ---------------------------------------------------------------
library(ymlthis)
shiny::addResourcePath("sbs", system.file("www", package = "shinyBS"))
# Functions ---------------------------------------------------------------
author_name <- function() {
tryCatch(
ymlthis:::get_author_name(),
error = function(e) ""
)
}
args_as_char <- function(x) {
if (is.null(x)) return("NULL")
if (is.call(x)) return(rlang::quo_text(x))
as.character(x)
}
arg_textInput <- function(arg_name, arg_val, f_name, id = NULL) {
if (is.null(id)) id <- f_name
input_id <- glue::glue("{id}_{arg_name}")
ph <- args_as_char(arg_val)
arg_name <- glue::glue("<code>{arg_name}</code>")
shiny::textInput(input_id, shiny::HTML(arg_name), placeholder = ph)
}
ui_function_args <- function(f_name, id = NULL, ns = "rmarkdown") {
args <- rlang::fn_fmls(utils::getFromNamespace(f_name, ns))
if (ns == "shiny") args[c("inputId", "label", "value")] <- NULL
tags <- purrr::map2(
names(args),
args,
arg_textInput,
f_name = f_name,
id = id
)
shiny::tagList(tags)
}
output_buttons <- function(f_name, short_name) {
if (is.na(f_name)) return(NULL)
id <- glue::glue("button_{f_name}")
txt <- glue::glue("Set {short_name} options")
shiny::conditionalPanel(
condition = glue::glue("input.output_function.includes('{f_name}')"),
shiny::actionButton(id, txt, style = "margin-top:4px; margin-right:2px"),
style = "display:inline-block"
)
}
output_modal <- function(f_name, modal_name = NULL, title = "Output options", id = NULL, ns = "rmarkdown") {
if (is.null(modal_name)) modal_name <- f_name
shinyBS::bsModal(
glue::glue("modal_{modal_name}"),
glue::glue("{title}: {f_name}"),
glue::glue("button_{modal_name}"),
ui_function_args(f_name, id = id, ns = ns),
size = "small"
)
}
ui_output_action_buttons <- function(x) {
tags <- purrr::map2(x, names(x), output_buttons)
shiny::tagList(tags)
}
ui_output_modals <- function(x) {
tags <- purrr::map(x, output_modal)
shiny::tagList(tags)
}
param_label <- function(label, x) {
if (x == "" || is.null(x)) return(NULL)
p_html <- "<code style = 'color:black;background-color:#F0F0F0;'><label>{label}:</label>{x}</code>"
shiny::div(shiny::HTML(glue::glue(p_html)))
}
ui_param <- function(param, value, shiny_function, label) {
input_button <- shiny::actionButton(
glue::glue("button_param_{param}"),
glue::glue("options")
)
if ((shiny_function == "" || is.null(shiny_function))) input_button <- NULL
param_row <- shiny::fillRow(
param_label("param", param),
param_label("value", value),
param_label("label", label),
input_button,
shinyBS::bsButton(glue::glue("remove_param_{param}"), "Remove", style = "danger"),
height = 70
)
shiny::tags$div(param_row, id = glue::glue("param_{param}"))
}
rmarkdown_outputs <- c(
"html" = "html_document",
"pdf" = "pdf_document",
"word" = "word_document",
"odt" = "odt_document",
"rtf" = "rtf_document",
"md" = "md_document",
"ioslides" = "ioslides_presentation",
"slidy" = "slidy_presentation",
"beamer" = "beamer_presentation",
"powerpoint" = "powerpoint_presentation"
)
shiny_functions <- c(
"",
"checkbox" = "shiny_checkbox",
"date" = "shiny_date",
"file" = "shiny_file",
"numeric" = "shiny_numeric",
"password" = "shiny_password",
"radio" = "shiny_radio",
"select" = "shiny_select",
"slider" = "shiny_slider",
"text" = "shiny_text"
)
shiny_switch <- function(x) {
switch(
x,
"shiny_checkbox" = "checkboxInput",
"shiny_numeric" = "numericInput",
"shiny_slider" = "sliderInput",
"shiny_date" = "dateInput",
"shiny_text" = "textInput",
"shiny_file" = "fileInput",
"shiny_radio" = "radioButtons",
"shiny_select" = "selectInput",
"shiny_password" = "passwordInput"
)
}
swap_arg <- function(x, .default = NULL) {
if (purrr::is_empty(x) || x == "") return(yml_blank())
if (identical(.default, x)) return(yml_blank())
x
}
pass_if <- function(x, pred, .f, ...) {
if (pred) return(x)
.f(x, ...)
}
input_starts_with <- function(input, .match) {
matches <- names(input)[startsWith(names(input), .match)]
matched_inputs <- purrr::map(matches, ~input[[.x]])
names(matched_inputs) <- matches
matched_inputs
}
capture_arg <- function(x) {
if (x == "" || stringr::str_detect(x, "[\"\']{2}")) return(x)
arg_guess <- type.convert(x, as.is = TRUE)
if (is.character(arg_guess)) arg_guess <- glue::glue("\"{arg_guess}\"")
arg_guess
}
parse_arguments <- function(x) {
if (purrr::is_empty(x) || x == "") return("")
args <- purrr::map2_chr(x, names(x), ~glue::glue("{.y} = {capture_arg(.x)}"))
glue::glue_collapse(args, ", ")
}
parse_dots <- function(fn_args) {
dot_col <- stringr::str_detect(names(fn_args), "\\.\\.\\.")
if (!any(dot_col)) return(fn_args)
dot_txt <- fn_args[[which(dot_col)]]
dot_list <- glue::glue("list({dot_txt})") %>%
rlang::parse_expr() %>%
rlang::eval_tidy()
x <- fn_args[!dot_col]
x[names(dot_list)] <- dot_list
x
}
parse_output <- function(input, .f, .match = NULL, value = NULL, label = NULL) {
if (is.null(.match)) .match <- .f
fn_args <- input_starts_with(input, .match) %>%
purrr::map(swap_arg) %>%
purrr::discard(is_yml_blank) %>%
parse_dots()
fn_args <- fn_args[names(fn_args) != .match]
names(fn_args) <- stringr::str_remove_all(names(fn_args), glue::glue("{.match}_?"))
if (.f %in% shiny_functions) {
fn_args <- c(value = value, label = label, fn_args)
}
.call <- glue::glue("{.f}({parse_arguments(fn_args)})")
.call
}
capture_output_functions <- function(.yml, input) {
.fs <- input$output_function
if (purrr::is_empty(.fs) || .fs == "") return(.yml)
fn_calls <- purrr::map_chr(.fs, parse_output, input = input) %>%
glue::glue_collapse(sep = ", ")
glue::glue(".yml %>% yml_output({fn_calls})") %>%
rlang::parse_expr() %>%
rlang::eval_tidy()
}
parse_param <- function(param, value, shiny_input, input, label) {
if (is_yml_blank(swap_arg(shiny_input))) {
return(glue::glue("\"{param}\" = {capture_arg(value)}"))
}
.match <- glue::glue("modal_param_{param}")
shiny_call <- parse_output(
input,
shiny_input,
.match = .match,
value = value,
label = label
)
glue::glue("\"{param}\" = {shiny_call}")
}
capture_params <- function(.yml, params_handlers, input) {
if (purrr::is_empty(params_handlers$params)) {
return(.yml)
}
index <- c("params", "value", "input", "label")
rv_list <- shiny::reactiveValuesToList(params_handlers)[index]
names(rv_list) <- c("param", "value", "shiny_input", "label")
param_list <- purrr::pmap_chr(
rv_list,
parse_param,
input = input
) %>%
glue::glue_collapse(sep = ", ")
glue::glue(".yml %>% yml_params({param_list})") %>%
rlang::parse_expr() %>%
rlang::eval_tidy()
}
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/addin/new_yaml/global.R |
# Server ------------------------------------------------------------------
library(shiny)
library(miniUI)
shiny::shinyServer(function(input, output, session){
shiny::observe({
if (input$export_file %in% c("YAML", "R Markdown")) {
file_name <- ifelse(input$export_file == "YAML", "_output.yml", "Untitled.Rmd")
shiny::updateTextInput(session, "file_path", value = file_name)
}
})
params_handlers <- shiny::reactiveValues(
params = list(),
value = list(),
input = list(),
label = list(),
created = list()
)
params_observers <- shiny::reactiveValues(observers = list())
shiny::observeEvent(
input$add_param, {
shiny::req(input$param)
shiny::req(input$param_value)
if (!is.null(params_handlers$params[[input$param]])) {
shiny::removeUI(glue::glue("#param_{input$param}"))
shiny::removeUI(glue::glue("#modal_param_{input$param}"))
params_observers$observers[[input$param]]$destroy()
for (x in names(params_handlers)) params_handlers[[x]][[input$param]] <- NULL
}
selector <- ifelse(
purrr::is_empty(params_handlers$params),
"holder",
glue::glue("{params_handlers$params[[length(params_handlers$params)]]}")
)
shiny::insertUI(
selector = glue::glue("#param_{selector}"),
where = "afterEnd",
ui = ui_param(
input$param,
input$param_value,
stringr::str_remove(input$shiny_fun, "shiny_"),
input$param_label
)
)
if (!is.null(input$shiny_fun) && input$shiny_fun != "") {
shiny::insertUI(
selector = "#modal_holder",
where = "afterEnd",
ui = output_modal(
shiny_switch(input$shiny_fun),
modal_name = glue::glue("param_{input$param}"),
title = "Input options",
id = glue::glue("modal_param_{input$param}"),
ns = "shiny"
)
)
}
purrr::walk(
c("param", "param_value", "param_label"),
shiny::updateTextInput,
value = "",
session = session
)
params_handlers$params[[input$param]] <- input$param
params_handlers$value[[input$param]] <- input$param_value
params_handlers$input[[input$param]] <- input$shiny_fun
params_handlers$label[[input$param]] <- ifelse(
input$param_label == "" | purrr::is_empty(input$param_label),
input$param, input$param_label
)
})
shiny::observeEvent(params_handlers$params, {
for (i in seq_along(params_handlers$params)) {
param <- params_handlers$params[[i]]
rmv_button <- glue::glue("remove_param_{param}")
if (is.null(params_handlers$created[[param]])) {
params_observers$observers[[param]] <- shiny::observeEvent(
input[[rmv_button]], {
shiny::removeUI(glue::glue("#param_{param}"))
params_handlers$created[[param]] <- NULL
params_handlers$params[[param]] <- NULL
},
ignoreInit = TRUE,
once = TRUE
)
params_handlers$created[[param]] <- TRUE
}
}
})
shiny::observeEvent(input$done, {
input_date <- swap_arg(as.character(input$date))
if (input$use_date) input_date <- NULL
shiny_yml <- yml_empty() %>%
yml_author(swap_arg(input$author)) %>%
yml_date(input_date) %>%
yml_title(swap_arg(input$title)) %>%
yml_subtitle(swap_arg(input$subtitle)) %>%
capture_output_functions(input) %>%
capture_params(params_handlers, input) %>%
yml_keywords(swap_arg(input$keywords)) %>%
yml_subject(swap_arg(input$subject)) %>%
yml_category(swap_arg(input$category)) %>%
yml_abstract(swap_arg(input$abstract)) %>%
yml_description(swap_arg(input$description)) %>%
yml_lang(swap_arg(input$lang)) %>%
yml_resource_files(swap_arg(input$resource_files$name)) %>%
yml_clean(swap_arg(input$clean, .default = TRUE)) %>%
pass_if(
is_yml_blank(swap_arg(input$runtime)),
yml_runtime,
swap_arg(input$runtime)
) %>%
yml_latex_opts(
fontsize = swap_arg(input$fontsize),
fontfamily = swap_arg(input$fontfamily),
linkcolor = swap_arg(input$linkcolor),
citecolor = swap_arg(input$citecolor),
urlcolor = swap_arg(input$urlcolor),
documentclass = swap_arg(input$documentclass),
classoption = swap_arg(input$classoption),
indent = swap_arg(input$indent, .default = FALSE),
geometry = swap_arg(input$geometry),
links_as_notes = swap_arg(input$links_as_notes, .default = FALSE),
lof = swap_arg(input$lof, .default = FALSE),
lot = swap_arg(input$lot, .default = FALSE),
thanks = swap_arg(input$thanks),
biblio_title = swap_arg(input$biblio_title),
biblio_style = swap_arg(input$biblio_style),
natbiboptions = swap_arg(input$natbiboptions),
biblatexoptions = swap_arg(input$biblatexoptions)
) %>%
yml_citations(
bibliography = swap_arg(input$bibliography$name),
csl = swap_arg(input$csl$name),
link_citations = swap_arg(input$link_citations, .default = FALSE),
suppress_bibliography = swap_arg(input$suppress_bibliography, .default = FALSE)
) %>%
yml_discard(~is_yml_blank(.x))
export_f <- switch(
input$export_file,
"R Markdown" = use_rmarkdown,
"YAML" = use_yml_file,
"Place YAML on clipboard" = use_yml
)
if (input$export_file == "R Markdown") {
path <- input$file_path
template <- input$rmd_template$name
export_f <- purrr::partial(export_f, path = path, template = template)
}
if (input$export_file == "YAML") {
path <- input$file_path
export_f <- purrr::partial(export_f, path = path)
}
shiny::onStop(function() export_f(shiny_yml))
shiny::stopApp()
})
})
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/addin/new_yaml/server.R |
library(shiny)
library(miniUI)
# YAML panel --------------------------------------------------------------
main_yaml_panel <- miniUI::miniTabPanel(
"YAML",
icon = shiny::icon("sliders"),
miniUI::miniContentPanel(
shiny::fillRow(
shiny::textInput("author", "Author", value = author_name(), width = "95%"),
shiny::fillCol(
shiny::dateInput("date", "Date", value = "`r Sys.Date()`", width = "95%"),
shiny::checkboxInput("use_date", "Use system date", value = TRUE)
),
height = 100
),
shiny::fillRow(
shiny::textInput("title", "Title", value = "Untitled", width = "95%"),
shiny::textInput("subtitle", "Subtitle", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::selectizeInput(
"output_function",
"Output",
choices = rmarkdown_outputs,
selected = "html_document",
multiple = TRUE,
width = "95%"
),
miniUI::miniContentPanel(
ui_output_action_buttons(rmarkdown_outputs),
padding = 4
),
height = 120
),
ui_output_modals(rmarkdown_outputs),
shiny::fillRow(
shiny::fillCol(
shiny::selectizeInput(
"export_file",
"Export to",
choices = c(
"R Markdown",
"YAML",
"Place YAML on clipboard"
),
width = "95%"
),
shiny::conditionalPanel(
condition = "input.export_file == 'R Markdown'",
shiny::fileInput(
"rmd_template",
"R Markdown Template",
placeholder = "Template (optional)",
width = "95%"
)
)
),
shiny::conditionalPanel(
condition = "input.export_file != 'Place YAML on clipboard'",
shiny::textInput(
"file_path",
"Path",
value = "Untitled.Rmd",
width = "95%"
)
),
height = 150
),
scrollable = TRUE
)
)
# R Markdown Options Panel ------------------------------------------------
rmarkdown_opts_panel <- miniUI::miniTabPanel(
"R Markdown Options",
miniUI::miniContentPanel(
shiny::fillRow(
shiny::textInput("keywords", "Keywords", width = "95%"),
shiny::textInput("subject", "Subject", width = "95%"),
shiny::textInput("category", "Categories", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::fillCol(
shiny::textAreaInput("abstract", "Abstract", width = "400px", height = "60px"),
shiny::textAreaInput("description", "Description", width = "400px", height = "60px")
),
height = 200
),
shiny::fillRow(
shiny::selectizeInput(
"runtime",
"Runtime",
choices = c("", "static", "shiny", "shiny_prerendered"),
width = "95%"
),
shiny::textInput("lang", "Language (IETF tag)", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::fileInput("resource_files", "Resource files", multiple = TRUE, width = "80%"),
shiny::checkboxInput("clean", "Clean intermediate files", value = TRUE, width = "95%"),
height = 70
),
scrollable = TRUE
),
icon = shiny::icon("data")
)
# LaTeX Options Panel -----------------------------------------------------
latex_opts_panel <- miniUI::miniTabPanel(
"LaTeX Options",
miniUI::miniContentPanel(
shiny::fillRow(
shiny::selectizeInput("fontsize", "Font Size", choices = c("", "10pt", "11pt", "12pt"), width = "95%"),
shiny::textInput("fontfamily", "Font Family", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::textInput("linkcolor", "Internal Link Color", width = "95%"),
shiny::textInput("citecolor", "Citation Link Color", width = "95%"),
shiny::textInput("urlcolor", "External Link Color", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::fillCol(
shiny::textInput("documentclass", "Document Class", width = "95%"),
shiny::checkboxInput("indent", "Use Document Class Indentation")
),
shiny::textInput("classoption", "Class Options", width = "95%"),
height = 100
),
shiny::fillRow(
shiny::textInput("geometry", "Geometry", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::checkboxInput("links_as_notes", "Links as footnotes"),
shiny::checkboxInput("lof", "Include List of Figures"),
shiny::checkboxInput("lot", "Include List of Tables"),
height = 45
),
shiny::fillRow(
shiny::textInput("thanks", "Thanks", width = "95%"),
height = 70
),
scrollable = TRUE
),
icon = shiny::icon("data")
)
# Citations Panel --------------------------------------------------------
citations_panel <- miniUI::miniTabPanel(
"Citations",
miniUI::miniContentPanel(
shiny::fillRow(
shiny::fileInput("bibliography", "Bibliography", width = "95%"),
shiny::fileInput("csl", "CSL", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::checkboxInput("link_citations", "Add citations hyperlinks", width = "95%"),
shiny::checkboxInput("suppress_bibliography", "Suppress bibliography", width = "95%"),
height = 45
),
shiny::h4("LaTeX Citations"),
shiny::hr(),
shiny::fillRow(
shiny::textInput("biblio_title", "Bibliography Title", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::textInput("biblio_style", "Bibliography style", width = "95%"),
height = 70
),
shiny::fillRow(
shiny::textInput("natbiboptions", "natbib options", width = "95%"),
shiny::textInput("biblatexoptions", "biblatex options", width = "95%"),
height = 70
),
scrollable = TRUE
),
icon = shiny::icon("data")
)
# Parameterized Reports Panel ---------------------------------------------
params_panel <- miniUI::miniTabPanel(
"Parameterized Reports",
miniUI::miniContentPanel(
shiny::fillCol(
flex = c(NA, 1, 0),
shiny::fillRow(
shiny::textInput("param", "Parameter", width = "95%"),
shiny::textInput("param_value", "Value", width = "95%"),
shiny::selectizeInput("shiny_fun", "Input", choices = shiny_functions, width = "95%"),
shiny::textInput("param_label", "Label", width = "95%"),
shiny::actionButton("add_param", "Add", style = "margin-top:25px"),
height = 70,
flex = c(rep(3, 4), 1)
),
shiny::fillRow(
shiny::tags$div(id = 'param_holder')
),
shiny::fillRow(
shiny::tags$div(id = 'modal_holder')
)
)
),
icon = shiny::icon("data")
)
# UI ----------------------------------------------------------------------
shiny::shinyUI(miniUI::miniPage(
miniUI::gadgetTitleBar(
"Set up YAML",
right = NULL
),
miniUI::miniTabstripPanel(
main_yaml_panel,
rmarkdown_opts_panel,
latex_opts_panel,
citations_panel,
params_panel
),
miniUI::miniButtonBlock(
miniUI::miniTitleBarButton("done", "Done", primary = TRUE)
)
))
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/addin/new_yaml/ui.R |
## ----setup, echo=FALSE--------------------------------------------------------
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE
)
check <- function() "<span style='color:green'>\u2713</span>"
cross <- function() "<span style='color:red'>\u2717</span>"
knit_print.yml <- function(x, ...) {
ymlthis::asis_yaml_output(x)
}
## ----pandoc_check, echo=FALSE-------------------------------------------------
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
## -----------------------------------------------------------------------------
yml()
## -----------------------------------------------------------------------------
yml() %>%
yml_title("An introduction to ymlthis")
## -----------------------------------------------------------------------------
yml() %>%
yml_output(pdf_document())
## ---- warning = FALSE---------------------------------------------------------
yml() %>%
yml_output(pdf_document(toc = TRUE))
## -----------------------------------------------------------------------------
yml() %>%
yml_output(
pdf_document(toc = TRUE),
html_document()
)
## -----------------------------------------------------------------------------
yml() %>%
yml_author(
c("Yihui Xie", "Hadley Wickham"),
affiliation = "RStudio"
) %>%
yml_date("07/04/2019") %>%
yml_title("Reproducible Research in R") %>%
yml_category(c("r", "reprodicibility")) %>%
yml_output(
pdf_document(
keep_tex = TRUE,
includes = includes2(after_body = "footer.tex")
)
) %>%
yml_latex_opts(biblio_style = "apalike")
## -----------------------------------------------------------------------------
yml() %>%
yml_params(country = "Turkey")
## -----------------------------------------------------------------------------
yml() %>%
yml_params(
data = shiny_file("Upload Data (.csv)"),
n = shiny_numeric("n to sample", 10),
date = shiny_date("Date"),
show_plot = shiny_checkbox("Plot the data?", TRUE)
)
## -----------------------------------------------------------------------------
yml() %>%
yml_citations(bibliography = "refs.bib")
## -----------------------------------------------------------------------------
ref <- reference(
id = "fenner2012a",
title = "One-click science marketing",
author = list(
family = "Fenner",
given = "Martin"
),
`container-title` = "Nature Materials",
volume = 11L,
URL = "https://doi.org/10.1038/nmat3283",
DOI = "10.1038/nmat3283",
issue = 4L,
publisher = "Nature Publishing Group",
page = "261-263",
type = "article-journal",
issued = list(
year = 2012,
month = 3
)
)
yml() %>%
yml_reference(ref)
## -----------------------------------------------------------------------------
yml() %>%
yml_reference(.bibentry = citation("purrr"))
## -----------------------------------------------------------------------------
yml() %>%
yml_title("Presentation Ninja") %>%
yml_subtitle("with xaringan") %>%
yml_output(
xaringan::moon_reader(
lib_dir = "libs",
nature = list(
highlightStyle = "github",
highlightLines = TRUE,
countIncrementalSlides = FALSE
)
)
)
## -----------------------------------------------------------------------------
navbar_yaml <- yml_empty() %>%
yml_site_opts(
name = "my-website",
output_dir = "_site",
include = "demo.R",
exclude = c("docs.txt", "*.csv")
) %>%
yml_navbar(
title = "My Website",
left = list(
navbar_page("Home", href = "index.html"),
navbar_page(navbar_separator(), href = "about.html")
)
) %>%
yml_output(html_document(toc = TRUE, highlight = "textmate"))
# save to temporary directory since this is not interactive
path <- tempfile()
fs::dir_create(path)
use_navbar_yml(navbar_yaml, path = path)
## -----------------------------------------------------------------------------
old <- options(
ymlthis.default_yml = "author: Malcolm Barrett
date: '`r format(Sys.Date())`'
output: bookdown::pdf_document2",
ymlthis.rmd_body = c(
"",
ymlthis::setup_chunk(),
"",
ymlthis::code_chunk(
library(ymlthis)
)
)
)
# use temporary path set above
use_rmarkdown(path = file.path(path, "analysis.Rmd"))
# reset previous option defaults
options(old)
## -----------------------------------------------------------------------------
x <-
yml() %>%
yml_author(
c("Yihui Xie", "Hadley Wickham"),
affiliation = "RStudio"
) %>%
yml_date("07/04/2019") %>%
yml_title("Reproducible Research in R") %>%
yml_category(c("r", "reprodicibility")) %>%
yml_output(
pdf_document(
keep_tex = TRUE,
includes = includes2(after_body = "footer.tex")
),
html_document()
) %>%
yml_latex_opts(biblio_style = "apalike")
## ----echo=FALSE---------------------------------------------------------------
x %>% ymlthis::asis_yaml_output()
## -----------------------------------------------------------------------------
x %>%
yml_discard("category")
## -----------------------------------------------------------------------------
x %>%
yml_discard(~ length(.x) > 1)
## -----------------------------------------------------------------------------
x %>%
yml_pluck("output", "pdf_document")
## ---- include=FALSE-----------------------------------------------------------
options(oldoption)
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/doc/introduction-to-ymlthis.R |
---
title: "An Introduction to ymlthis"
output:
prettydoc::html_pretty:
theme: tactile
vignette: |-
>
%\VignetteIndexEntry{An Introduction to ymlthis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, echo=FALSE}
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE
)
check <- function() "<span style='color:green'>\u2713</span>"
cross <- function() "<span style='color:red'>\u2717</span>"
knit_print.yml <- function(x, ...) {
ymlthis::asis_yaml_output(x)
}
```
```{r pandoc_check, echo=FALSE}
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
```
**ymlthis** is a package to help you write YAML metadata for **R Markdown** documents and related tools like **blogdown**, **bookdown**, and **pkgdown**. YAML serves two main roles: to pass information to be printed in the document, such as the title and author, and to control how the document is rendered, anything from the output type (HTML vs. PDF) and typesetting options to what should happen with files created while rendering. See the [YAML: An Overview](yaml-overview.html) for a more general introduction to YAML and the [YAML Fieldguide](yaml-fieldguide.html) for YAML field documentation.
# Writing YAML with **ymlthis**
**ymlthis** makes it easy to write valid YAML by handling the syntax and documenting the majority of YAML fields in one place. `yml()` creates a `yml` object that, by default, sets the author name and date. **ymlthis** uses name options in **devtools** and **usethis** (`options(devtools.name = "name")` and `options(usethis.full_name = "name")`, respectively), as well as the **whoami** package, to try to find the author's name. By default, the date is set to `` `r knitr::inline_expr('format(Sys.Date())')` ``, which will update the date when knitting.
```{r}
yml()
```
Functions that start with `yml_*()` take and return `yml` objects, so they can be used to add or modify YAML fields. For instance, to add a title, use `yml_title()`
```{r }
yml() %>%
yml_title("An introduction to ymlthis")
```
An essential use of YAML in **R Markdown** is to set the output type. By default, the `output` YAML field looks like
``` yaml
output: html_document
```
which calls `rmarkdown::html_document()` when knitting. All of the nested fields passed to `output` come from the output function you are using (so you can check `?pkg::output_function()` to see what the options are). **ymlthis** writes and validates output YAML by parsing calls to these functions. We can, for example, nest **R Markdown**'s `pdf_document()` inside `yml_output()`:
```{r}
yml() %>%
yml_output(pdf_document())
```
Passing arguments to the output functions will nest them correctly for YAML.
```{r, warning = FALSE}
yml() %>%
yml_output(pdf_document(toc = TRUE))
```
And we can pass multiple output functions to facilitate rendering R Markdown files to multiple formats:
```{r}
yml() %>%
yml_output(
pdf_document(toc = TRUE),
html_document()
)
```
YAML fields can come from a variety of places: **R Markdown** itself, the output function, Pandoc (for example, as options used in LaTeX), and custom templates. Many of these fields are documented in `yml_*()` functions.
```{r}
yml() %>%
yml_author(
c("Yihui Xie", "Hadley Wickham"),
affiliation = "RStudio"
) %>%
yml_date("07/04/2019") %>%
yml_title("Reproducible Research in R") %>%
yml_category(c("r", "reprodicibility")) %>%
yml_output(
pdf_document(
keep_tex = TRUE,
includes = includes2(after_body = "footer.tex")
)
) %>%
yml_latex_opts(biblio_style = "apalike")
```
You can also use `yml_toplevel()` to append any YAML fields not covered in **ymlthis**.
## Parameterized reports
[Parameterized reports](https://bookdown.org/yihui/rmarkdown/parameterized-reports.html) are a powerful feature of **R Markdown** that lets you specify variables in the YAML metadata used in your report, letting you re-use reports for a variety of settings. To set parameters, you use the `params` YAML field and access the parameter in your report by calling `params$variable_name`. Basic YAML for parameters looks like this
```yaml
params:
country: "Turkey"
```
Calling `params$country` in the **R Markdown** document will thus return `"Turkey"`. `yml_params()` will write this for you:
```{r}
yml() %>%
yml_params(country = "Turkey")
```
You can also fill in parameters using a **Shiny** app with the "Knit with Parameters" button in the RStudio IDE or by passing `"ask"` to the `params` argument in `rmarkdown::render()`. While **R Markdown** will try to guess the Shiny widget type by the value of the parameter, you can specify them yourself with **ymlthis** functions that start with `shiny_*()`.
```{r}
yml() %>%
yml_params(
data = shiny_file("Upload Data (.csv)"),
n = shiny_numeric("n to sample", 10),
date = shiny_date("Date"),
show_plot = shiny_checkbox("Plot the data?", TRUE)
)
```
## References and citations
[**R Markdown** has excellent support for citations](https://bookdown.org/yihui/rmarkdown/markdown-syntax.html). The simplest way to use references in an **R Markdown** file is to add a bibliography file using the `bibliography` field.
```{r}
yml() %>%
yml_citations(bibliography = "refs.bib")
```
However, if you only have a few references and want to keep your file self-contained, you can also specify references directly in your YAML using `yml_reference()` and `reference()`.
```{r}
ref <- reference(
id = "fenner2012a",
title = "One-click science marketing",
author = list(
family = "Fenner",
given = "Martin"
),
`container-title` = "Nature Materials",
volume = 11L,
URL = "https://doi.org/10.1038/nmat3283",
DOI = "10.1038/nmat3283",
issue = 4L,
publisher = "Nature Publishing Group",
page = "261-263",
type = "article-journal",
issued = list(
year = 2012,
month = 3
)
)
yml() %>%
yml_reference(ref)
```
`yml_reference()` also supports package citation using the `.bibentry` argument and `citation()`.
```{r}
yml() %>%
yml_reference(.bibentry = citation("purrr"))
```
If you have an existing `.bib` file, but you want to specify it in the YAML, instead, you can convert it with `bib2yml()`. For instance, if you wrote a `.bib` file for the packages used in your document with `knitr::write_bib()`, `bib2yml()` will translate the file to YAML you can include directly in the metadata.
# R Markdown extensions
Packages that extend **R Markdown**, such as **bookdown** and **blogdown**, also extend the YAML used to make documents. One of the main ways that other packages introduce YAML is through new output functions. [**xaringan**](https://bookdown.org/yihui/rmarkdown/xaringan.html), for instance, doesn't use custom YAML outside of its output function, so **ymlthis** supports it out-of-box. Passing `xaringan::moon_reader()` to `yml_output()` will write the YAML for you.
```{r}
yml() %>%
yml_title("Presentation Ninja") %>%
yml_subtitle("with xaringan") %>%
yml_output(
xaringan::moon_reader(
lib_dir = "libs",
nature = list(
highlightStyle = "github",
highlightLines = TRUE,
countIncrementalSlides = FALSE
)
)
)
```
**ymlthis** can process any output function. Other packages also add additional YAML; **ymlthis** supports six **R Markdown** packages: **bookdown**, **blogdown**, **pkgdown**, **pagedown**, **rticles**, and **distill**. **ymlthis** also supports YAML for writing scheduled emails with RStudio Connect. You can find functions supporting these packages with the patterns `yml_packagename_*()` and `packagename_*()` (`rsconnect`, in the case of RStudio Connect functions). Functions that start with `yml_packagename_*()` document YAML fields and return `yml` objects, while functions that start with `packagename_*()` are helper functions. There are also a few template functions. `pkgdown_template()`, for instance, will assemble a full template for `_pkgdown.yml` and return it as a `yml` object, and `blogdown_template()` will return YAML templates matching your Hugo theme.
| package| output function | top-level YAML |
|--:|--:|--:|
| bookdown | `r check()` | `r check()` |
| blogdown | `r check()` | `r check()` |
| pkgdown | `r check()` | `r check()` |
| pagedown | `r check()` | `r check()` |
| rticles | `r check()` | `r check()` |
| distill | `r check()` | `r check()` |
| learnr | `r check()` | `r cross()`|
| xaringan | `r check()` | `r cross()`|
| revealjs | `r check()` | `r cross()`|
| flexdashboard | `r check()` | `r cross()`|
Table: Sources of YAML in R Markdown Extension
# R Markdown workflows
**ymlthis** prints YAML cleanly to the console such that you could copy and paste it into an **R Markdown** document. However, **ymlthis** also provides a number of other workflows.
### YAML add-in
The easiest way is to use the Shiny add-in included with **ymlthis**; the add-in supports the most commonly used R Markdown options, citations, LaTeX options, and parameterized reports. You can then export the YAML to an R Markdown file, YAML file, or have it placed on your clipboard.
For more flexibility or to use R Markdown extension packages, you'll have to write code, as we've been doing in this vignette. Your main options are to write the YAML to a file or to place it on your clipboard.
### Writing to files
`use_rmarkdown()`, `use_yml_file()`, and friends will take a `yml` object and write to a file for you. Passing `yml` objects to `use_rmarkdown()` is often the simplest approach: it will translate the `yml` object into YAML and open a new R Markdown file for you with the metadata already written.
**ymlthis** also supports YAML files. For instance, using `pkgdown_template() %>% use_pkgdown_yml()` will write the YAML for your **pkgdown** site to `_pkgdown.yml` based on your package directory. **ymlthis** also has some helper functions for working with Pandoc templates and highlighting themes.
As an example, let's set up the navbar YAML for an **R Markdown** website and then pass it to `use_navbar_yml()`.
```{r}
navbar_yaml <- yml_empty() %>%
yml_site_opts(
name = "my-website",
output_dir = "_site",
include = "demo.R",
exclude = c("docs.txt", "*.csv")
) %>%
yml_navbar(
title = "My Website",
left = list(
navbar_page("Home", href = "index.html"),
navbar_page(navbar_separator(), href = "about.html")
)
) %>%
yml_output(html_document(toc = TRUE, highlight = "textmate"))
# save to temporary directory since this is not interactive
path <- tempfile()
fs::dir_create(path)
use_navbar_yml(navbar_yaml, path = path)
```
In addition to writing to files, you can save YAML to your `.Rprofile` using `options(ymlthis.defaults = "{YAML}")`. `yml()` will return the stored YAML by default. If you pass a `yml` object to `use_yml_defaults()`, the code to do this will be placed on your clipboard, which you should paste into your `.Rprofile`. Open that file with `usethis::edit_r_profile()`. You can also set a default for body text for `use_rmarkdown()` by setting the `ymlthis.rmd_body()` option, e.g. `options(ymlthis.rmd_body = "{your text}")` (or take advantage of `use_rmd_defaults()`). Together with specifying default YAML, `use_rmarkdown()` also serves as an ad-hoc way to make R Markdown templates.
```{r}
old <- options(
ymlthis.default_yml = "author: Malcolm Barrett
date: '`r format(Sys.Date())`'
output: bookdown::pdf_document2",
ymlthis.rmd_body = c(
"",
ymlthis::setup_chunk(),
"",
ymlthis::code_chunk(
library(ymlthis)
)
)
)
# use temporary path set above
use_rmarkdown(path = file.path(path, "analysis.Rmd"))
# reset previous option defaults
options(old)
```
| function | action |
|--:|--:|
| `use_yml_file()` | Write `yml` to a file |
| `use_bookdown_yml()`| Write `yml` to `_bookdown.yml` |
| `use_navbar_yml()` | Write `yml` to `_navbar.yml` |
| `use_output_yml()` | Write `yml` to `_output.yml` |
| `use_pkgdown_yml()` | Write `yml` to `_pkgdown.yml` |
| `use_site_yml()` | Write `yml` to `_site.yml` |
Table: ymlthis `use_*()` functions to write to `.yml` files
| function | action |
|--:|--:|
| `use_rmarkdown()` | Write `yml` to a `.Rmd` file |
| `use_index_rmd()` | Write `yml` to `Index.Rmd` |
Table: ymlthis `use_*()` to write to `.Rmd` files
### Placing YAML on your clipboard
A final way to use **ymlthis** is to put YAML on your clipboard to paste into a file or other setting. To place rendered YAML on your clipboard, simply pass a `yml` object to `use_yml()`.
| function | action |
|--:|--:|
| `use_yml()` | Place `yml` on your clipboard |
| `use_yml_defaults()` | Place code on your clipboard to save `yml` to your default options |
| `use_pandoc_highlight_style()` | Write pandoc theme templates to a `.theme` file |
| `use_pandoc_template()` | Write pandoc templates to a file |
Table: Additional **ymlthis** `use_*()` functions
# Working with yml objects
Under the hood, `yml` objects are lists of types that match the corresponding YAML and are only converted to YAML when printing or writing to files. Because `yml` objects are just lists, you can work with them as such. **ymlthis** also includes several **purrr**-like functions for working with `yml` objects. Let's define a `yml` object that has a fairly comprehensive set of options:
```{r}
x <-
yml() %>%
yml_author(
c("Yihui Xie", "Hadley Wickham"),
affiliation = "RStudio"
) %>%
yml_date("07/04/2019") %>%
yml_title("Reproducible Research in R") %>%
yml_category(c("r", "reprodicibility")) %>%
yml_output(
pdf_document(
keep_tex = TRUE,
includes = includes2(after_body = "footer.tex")
),
html_document()
) %>%
yml_latex_opts(biblio_style = "apalike")
```
The resulting YAML of `x` is:
```{r echo=FALSE}
x %>% ymlthis::asis_yaml_output()
```
We can use `yml_discard()` to remove the `category` option:
```{r}
x %>%
yml_discard("category")
```
We can use **purrr**-style lambdas to express what to discard. How about any YAML fields with a length greater than one?
```{r}
x %>%
yml_discard(~ length(.x) > 1)
```
The `yml_pluck()` function is useful for selectively acquiring a nested portion of the YAML:
```{r}
x %>%
yml_pluck("output", "pdf_document")
```
```{r, include=FALSE}
options(oldoption)
```
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/doc/introduction-to-ymlthis.Rmd |
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
collapse = TRUE,
comment = "",
warning = FALSE
)
## ----pandoc_check, echo=FALSE-------------------------------------------------
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
## ----roxygen_check, echo=FALSE------------------------------------------------
if (!requireNamespace("roxygen2")) {
cat("roxygen2 is required to render this vignette: `install.packages('roxygen2'`")
knitr::knit_exit()
}
## ----setup--------------------------------------------------------------------
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
function_name <- function(x) {
function_call <- x$call
ifelse(rlang::has_length(function_call), as.character(function_call[[2]]), NA)
}
block_names <- function(x) x$tags %>% purrr::map_chr(~.x$tag)
get_doc_name <- function(x) {
tags <- block_names(x)
rdname_index <- which(tags == "rdname")
if (purrr::is_empty(rdname_index)) return(function_name(x))
x$tags[[rdname_index]]$val
}
get_params <- function(x) {
param_lists <- which(block_names(x) == "param")
f <- get_doc_name(x)
if (!rlang::has_length(param_lists) || is.na(f)) return(data.frame())
params_desc <- x$tags[param_lists] %>%
purrr::map(~as.data.frame(.x$val, stringsAsFactors = FALSE)) %>%
do.call(rbind, .)
params_desc$description <- stringr::str_replace_all(
params_desc$description,
"\n",
" "
)
params_desc$name <- params_desc$name %>%
stringr::str_split(",") %>%
purrr::map_chr(
~paste0("`", .x, "`") %>% paste(collapse = ", ")
)
cbind(func = f, params_desc, stringsAsFactors = FALSE)
}
link_help_page <- function(x) {
url <- "https://ymlthis.r-lib.org/"
glue::glue("<a href='{url}/reference/{x}.html'>{x}</a>")
}
filter_kable <- function(.tbl, .pattern = NULL, caption = NULL) {
if (!is.null(.pattern)) {
index <- stringr::str_detect(.tbl$func, .pattern)
.tbl <- .tbl[index, ]
}
.tbl$func <- link_help_page(.tbl$func)
knitr::kable(
.tbl,
col.names = c("Help Page", "Argument", "Description"),
row.names = FALSE,
caption = caption
)
}
fields_df <- roxygen2::parse_package("../") %>%
purrr::map(get_params) %>%
do.call(rbind, .)
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("yml_author|yml_runtime|yml_clean|yml_toc", caption = "Basic YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("latex", caption = "LaTeX/PDF Options")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("site|navbar|vignette", caption = "R Markdown Websites")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("citations", caption = "Citations")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("yml_blogdown_opts", caption = "blogdown YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("bookdown", caption = "bookdown YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("yml_pkgdown", caption = "pkgdown YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("pagedown", caption = "pagedown YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("distill", caption = "distill YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("rticles", caption = "rticles YAML")
## -----------------------------------------------------------------------------
fields_df %>%
filter_kable("rsconnect", caption = "RStudio Connect Scheduled Email YAML")
## ---- include=FALSE-----------------------------------------------------------
options(oldoption)
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/doc/yaml-fieldguide.R |
---
title: "The YAML Fieldguide"
output:
prettydoc::html_pretty:
theme: tactile
vignette: >
%\VignetteIndexEntry{The YAML Fieldguide}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
collapse = TRUE,
comment = "",
warning = FALSE
)
```
```{r pandoc_check, echo=FALSE}
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
```
```{r roxygen_check, echo=FALSE}
if (!requireNamespace("roxygen2")) {
cat("roxygen2 is required to render this vignette: `install.packages('roxygen2'`")
knitr::knit_exit()
}
```
```{r setup}
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
function_name <- function(x) {
function_call <- x$call
ifelse(rlang::has_length(function_call), as.character(function_call[[2]]), NA)
}
block_names <- function(x) x$tags %>% purrr::map_chr(~.x$tag)
get_doc_name <- function(x) {
tags <- block_names(x)
rdname_index <- which(tags == "rdname")
if (purrr::is_empty(rdname_index)) return(function_name(x))
x$tags[[rdname_index]]$val
}
get_params <- function(x) {
param_lists <- which(block_names(x) == "param")
f <- get_doc_name(x)
if (!rlang::has_length(param_lists) || is.na(f)) return(data.frame())
params_desc <- x$tags[param_lists] %>%
purrr::map(~as.data.frame(.x$val, stringsAsFactors = FALSE)) %>%
do.call(rbind, .)
params_desc$description <- stringr::str_replace_all(
params_desc$description,
"\n",
" "
)
params_desc$name <- params_desc$name %>%
stringr::str_split(",") %>%
purrr::map_chr(
~paste0("`", .x, "`") %>% paste(collapse = ", ")
)
cbind(func = f, params_desc, stringsAsFactors = FALSE)
}
link_help_page <- function(x) {
url <- "https://ymlthis.r-lib.org/"
glue::glue("<a href='{url}/reference/{x}.html'>{x}</a>")
}
filter_kable <- function(.tbl, .pattern = NULL, caption = NULL) {
if (!is.null(.pattern)) {
index <- stringr::str_detect(.tbl$func, .pattern)
.tbl <- .tbl[index, ]
}
.tbl$func <- link_help_page(.tbl$func)
knitr::kable(
.tbl,
col.names = c("Help Page", "Argument", "Description"),
row.names = FALSE,
caption = caption
)
}
fields_df <- roxygen2::parse_package("../") %>%
purrr::map(get_params) %>%
do.call(rbind, .)
```
**ymlthis** attempts to write common YAML for you in the right way and to document the many YAML field options in one place. The fieldguide is a collection of all the fields documented in the **ymlthis** help pages, organized by source. Note that some argument names do not match the YAML field name exactly in order because not all field names are valid R names (e.g. the `link-citations` YAML field needs to be `link_citations` in R); these differences are noted in the argument description. Additionally, not all of these arguments are top-level YAML; see the linked help pages for more details.
## Basic YAML
```{r}
fields_df %>%
filter_kable("yml_author|yml_runtime|yml_clean|yml_toc", caption = "Basic YAML")
```
The nested fields for the `output` field are based on the arguments of the output function. See the help page for the function you are using, e.g., `?rmarkdown::pdf_document`.
## LaTeX/PDF Options
```{r}
fields_df %>%
filter_kable("latex", caption = "LaTeX/PDF Options")
```
## R Markdown Websites
```{r}
fields_df %>%
filter_kable("site|navbar|vignette", caption = "R Markdown Websites")
```
## Citations
```{r}
fields_df %>%
filter_kable("citations", caption = "Citations")
```
## blogdown YAML
```{r}
fields_df %>%
filter_kable("yml_blogdown_opts", caption = "blogdown YAML")
```
## bookdown YAML
```{r}
fields_df %>%
filter_kable("bookdown", caption = "bookdown YAML")
```
## pkgdown YAML
```{r}
fields_df %>%
filter_kable("yml_pkgdown", caption = "pkgdown YAML")
```
## pagedown YAML
```{r}
fields_df %>%
filter_kable("pagedown", caption = "pagedown YAML")
```
## distill YAML
```{r}
fields_df %>%
filter_kable("distill", caption = "distill YAML")
```
## rticles YAML
```{r}
fields_df %>%
filter_kable("rticles", caption = "rticles YAML")
```
## RStudio Connect Scheduled Email YAML
```{r}
fields_df %>%
filter_kable("rsconnect", caption = "RStudio Connect Scheduled Email YAML")
```
```{r, include=FALSE}
options(oldoption)
```
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/doc/yaml-fieldguide.Rmd |
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
collapse = TRUE,
comment = "",
warning = FALSE
)
## ----setup--------------------------------------------------------------------
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
## ----pandoc_check, echo=FALSE-------------------------------------------------
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
## -----------------------------------------------------------------------------
yml(date = FALSE) %>%
asis_yaml_output()
## ---- warning = FALSE---------------------------------------------------------
yml_empty() %>%
yml_output(pdf_document(toc = TRUE)) %>%
asis_yaml_output()
## ---- warning = FALSE---------------------------------------------------------
yml_empty() %>%
yml_output(pdf_document(toc = TRUE)) %>%
draw_yml_tree()
## -----------------------------------------------------------------------------
list(output = list(pdf_document = NULL), toc = TRUE) %>%
as_yml() %>%
draw_yml_tree()
## -----------------------------------------------------------------------------
yml_empty() %>%
yml_output(html_document()) %>%
asis_yaml_output()
## ---- warning = FALSE---------------------------------------------------------
yml_empty() %>%
yml_output(html_document(), pdf_document(toc = TRUE)) %>%
asis_yaml_output()
## -----------------------------------------------------------------------------
yml_empty() %>%
yml_category(c("R", "Reprodicible Research")) %>%
asis_yaml_output()
## -----------------------------------------------------------------------------
yml_empty() %>%
yml_params(
list(a = 1, input = "numeric"),
list(data = "data.csv", input = "text")
) %>%
asis_yaml_output()
## -----------------------------------------------------------------------------
yml_empty() %>%
yml_params(
list(a = 1, input = "numeric"),
list(data = "data.csv", input = "text")
) %>%
draw_yml_tree()
## -----------------------------------------------------------------------------
yml_empty() %>%
yml_title("R Markdown: An Introduction") %>%
asis_yaml_output()
## -----------------------------------------------------------------------------
yml_empty() %>%
yml_params(x = "yes") %>%
asis_yaml_output()
## ---- include=FALSE-----------------------------------------------------------
options(oldoption)
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/doc/yaml-overview.R |
---
title: "YAML: an Overview"
output:
prettydoc::html_pretty:
theme: tactile
vignette: |
%\VignetteIndexEntry{YAML: an Overview}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
collapse = TRUE,
comment = "",
warning = FALSE
)
```
```{r setup}
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
```
```{r pandoc_check, echo=FALSE}
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
```
# Basic syntax
The basic syntax of YAML is to use key-value pairs in the format `key: value`. A YAML code block should be fenced in with `---` before and after (you can also use `...` to end the YAML block, but this is not very common in **R Markdown**).
```{r}
yml(date = FALSE) %>%
asis_yaml_output()
```
In R, the equivalent structure is a list with named character vector: `list(author = "Malcolm Barrett")`. In fact, you can call this list in **R Markdown** using the `metadata` object; in this case, `metadata$author` will return `"Malcolm Barrett"`
In YAML, spaces are used to indicate nesting. When we want to specify the output function `pdf_document(toc = TRUE)`, we need to nest it under the `output` field. We also need to nest `toc` under `pdf_document` so that it gets passed to that function correctly.
```{r, warning = FALSE}
yml_empty() %>%
yml_output(pdf_document(toc = TRUE)) %>%
asis_yaml_output()
```
In R, the equivalent structure is a nested list, each with a name: `list(output = list(pdf_document = list(toc = TRUE)))`. Similarly, you can call this in R Markdown using the `metadata` object, e.g. `metadata$output$pdf_document$toc`. The hierarchical structure (which you can see with `draw_yml_tree()`) looks like this:
```{r, warning = FALSE}
yml_empty() %>%
yml_output(pdf_document(toc = TRUE)) %>%
draw_yml_tree()
```
Without the extra indents, YAML doesn't know `toc` is connected to `pdf_document` and thinks the value of `pdf_document` is `NULL`. YAML that looks like this:
```yaml
---
output:
pdf_document:
toc: true
---
```
has a hierarchy that looks like this:
```{r}
list(output = list(pdf_document = NULL), toc = TRUE) %>%
as_yml() %>%
draw_yml_tree()
```
If you use output functions without additional arguments, the value of `output` can simply be the name of the function.
```{r}
yml_empty() %>%
yml_output(html_document()) %>%
asis_yaml_output()
```
However, if you're specifying more than one output type, you must use the nesting syntax. If you don't want to include additional arguments, use `"default"` as the function's value.
```{r, warning = FALSE}
yml_empty() %>%
yml_output(html_document(), pdf_document(toc = TRUE)) %>%
asis_yaml_output()
```
Some YAML fields take unnamed vectors as their value. You can specify an element of the vector by adding a new line and `-` (note that the values are not indented below `category` here).
```{r}
yml_empty() %>%
yml_category(c("R", "Reprodicible Research")) %>%
asis_yaml_output()
```
In R, the equivalent structure is a list with a named vector: `list(categories = c("R", "Reprodicible Research"))`. `metadata$category` will return `c("R", "Reprodicible Research")`. Another way to specify vectors is to use `[]` with each object separated by a column, as in the syntax for `c()`. This YAML is equivalent to the YAML above:
```yaml
---
category: [R, Reprodicible Research]
---
```
By default, **ymlthis** uses the `-` syntax for vectors.`-` is also used to group elements together. For instance, in the `params` field for parameterized reports, we group parameter information together by using `-`. The first line is the name and value of the parameter, while all the lines until the next `-` are extra information about the parameter. While you can use `metadata` to call objects in `params`, `params` has it's own object you can call directly: `params$a` and `params$data` will return the values of `a` and `data`.
```{r}
yml_empty() %>%
yml_params(
list(a = 1, input = "numeric"),
list(data = "data.csv", input = "text")
) %>%
asis_yaml_output()
```
In R, the equivalent structure is a nested list that contains a list of unnamed lists: `list(param = list(list(a = 1, input = numeric), list(data = "data.csv", input = "file")))`. The inner-most lists group items together, e.g. `list(a = 1, input = numeric)` groups `a` and `input`.
```{r}
yml_empty() %>%
yml_params(
list(a = 1, input = "numeric"),
list(data = "data.csv", input = "text")
) %>%
draw_yml_tree()
```
# Types in YAML
You may have noticed that strings in YAML don't always need to be quoted. However, it can be useful to explicitly wrap strings in quotes when they contain special characters like `:` and `@`.
```{r}
yml_empty() %>%
yml_title("R Markdown: An Introduction") %>%
asis_yaml_output()
```
R code can be written as inline expressions `` `r knitr::inline_expr('expr')` ``. `yml_code()` will capture R code for you and put it in a valid format. R code in `params` needs to be slightly different: use `!r` (e.g. `!r expr`) to call an R object.
```yaml
author: '`r knitr::inline_expr('whoami::fullname()')`'
params:
date: !r Sys.Date()
```
Logical values in YAML are unusual: `true/false`, `yes/no`, and `on/off` are all equivalent to `TRUE/FALSE` in R. Any of these turn on the table of contents:
```yaml
toc: true
toc: yes
toc: on
```
By default, **ymlthis** uses `true/false`. If you want to use any of these values literally (e.g. you want a string equal to `"yes"`), you need to wrap them in quotation marks:
```{r}
yml_empty() %>%
yml_params(x = "yes") %>%
asis_yaml_output()
```
`NULL` can be specified using `null` or `~`. By default, **ymlthis** uses `null`. If you want to specify an empty vector, use `[]`, e.g. `category: []`. For an empty string, just use empty quotation marks (`""`).
# Sources of YAML
Where do the YAML fields you use in **R Markdown** come from? Many YAML fields that we use come from Pandoc from the **rmarkdown** package. These both use YAML to specify the build of the document and to pass information to be printed in a template. Pandoc templates can also be customized to add new YAML. The most common sources of YAML are:
1. Pandoc
1. **R Markdown**
1. Output functions (such as `rmarkdown::pdf_document()`)
1. Custom Pandoc templates
1. **R Markdown** extension packages (such as **blogdown**)
1. Hugo (in the case of **blogdown**)
Because YAML is an extensible approach to metadata, and there is often no way to validate that your YAML is correct. YAML will often fail silently if you, for instance, make a typo in the field name or misspecify the nesting between fields. For more information on the fields available in R Markdown and friends, see the [YAML Fieldguide](yaml-fieldguide.html).
```{r, include=FALSE}
options(oldoption)
```
| /scratch/gouwar.j/cran-all/cranData/ymlthis/inst/doc/yaml-overview.Rmd |
---
title: "An Introduction to ymlthis"
output:
prettydoc::html_pretty:
theme: tactile
vignette: |-
>
%\VignetteIndexEntry{An Introduction to ymlthis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, echo=FALSE}
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE
)
check <- function() "<span style='color:green'>\u2713</span>"
cross <- function() "<span style='color:red'>\u2717</span>"
knit_print.yml <- function(x, ...) {
ymlthis::asis_yaml_output(x)
}
```
```{r pandoc_check, echo=FALSE}
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
```
**ymlthis** is a package to help you write YAML metadata for **R Markdown** documents and related tools like **blogdown**, **bookdown**, and **pkgdown**. YAML serves two main roles: to pass information to be printed in the document, such as the title and author, and to control how the document is rendered, anything from the output type (HTML vs. PDF) and typesetting options to what should happen with files created while rendering. See the [YAML: An Overview](yaml-overview.html) for a more general introduction to YAML and the [YAML Fieldguide](yaml-fieldguide.html) for YAML field documentation.
# Writing YAML with **ymlthis**
**ymlthis** makes it easy to write valid YAML by handling the syntax and documenting the majority of YAML fields in one place. `yml()` creates a `yml` object that, by default, sets the author name and date. **ymlthis** uses name options in **devtools** and **usethis** (`options(devtools.name = "name")` and `options(usethis.full_name = "name")`, respectively), as well as the **whoami** package, to try to find the author's name. By default, the date is set to `` `r knitr::inline_expr('format(Sys.Date())')` ``, which will update the date when knitting.
```{r}
yml()
```
Functions that start with `yml_*()` take and return `yml` objects, so they can be used to add or modify YAML fields. For instance, to add a title, use `yml_title()`
```{r }
yml() %>%
yml_title("An introduction to ymlthis")
```
An essential use of YAML in **R Markdown** is to set the output type. By default, the `output` YAML field looks like
``` yaml
output: html_document
```
which calls `rmarkdown::html_document()` when knitting. All of the nested fields passed to `output` come from the output function you are using (so you can check `?pkg::output_function()` to see what the options are). **ymlthis** writes and validates output YAML by parsing calls to these functions. We can, for example, nest **R Markdown**'s `pdf_document()` inside `yml_output()`:
```{r}
yml() %>%
yml_output(pdf_document())
```
Passing arguments to the output functions will nest them correctly for YAML.
```{r, warning = FALSE}
yml() %>%
yml_output(pdf_document(toc = TRUE))
```
And we can pass multiple output functions to facilitate rendering R Markdown files to multiple formats:
```{r}
yml() %>%
yml_output(
pdf_document(toc = TRUE),
html_document()
)
```
YAML fields can come from a variety of places: **R Markdown** itself, the output function, Pandoc (for example, as options used in LaTeX), and custom templates. Many of these fields are documented in `yml_*()` functions.
```{r}
yml() %>%
yml_author(
c("Yihui Xie", "Hadley Wickham"),
affiliation = "RStudio"
) %>%
yml_date("07/04/2019") %>%
yml_title("Reproducible Research in R") %>%
yml_category(c("r", "reprodicibility")) %>%
yml_output(
pdf_document(
keep_tex = TRUE,
includes = includes2(after_body = "footer.tex")
)
) %>%
yml_latex_opts(biblio_style = "apalike")
```
You can also use `yml_toplevel()` to append any YAML fields not covered in **ymlthis**.
## Parameterized reports
[Parameterized reports](https://bookdown.org/yihui/rmarkdown/parameterized-reports.html) are a powerful feature of **R Markdown** that lets you specify variables in the YAML metadata used in your report, letting you re-use reports for a variety of settings. To set parameters, you use the `params` YAML field and access the parameter in your report by calling `params$variable_name`. Basic YAML for parameters looks like this
```yaml
params:
country: "Turkey"
```
Calling `params$country` in the **R Markdown** document will thus return `"Turkey"`. `yml_params()` will write this for you:
```{r}
yml() %>%
yml_params(country = "Turkey")
```
You can also fill in parameters using a **Shiny** app with the "Knit with Parameters" button in the RStudio IDE or by passing `"ask"` to the `params` argument in `rmarkdown::render()`. While **R Markdown** will try to guess the Shiny widget type by the value of the parameter, you can specify them yourself with **ymlthis** functions that start with `shiny_*()`.
```{r}
yml() %>%
yml_params(
data = shiny_file("Upload Data (.csv)"),
n = shiny_numeric("n to sample", 10),
date = shiny_date("Date"),
show_plot = shiny_checkbox("Plot the data?", TRUE)
)
```
## References and citations
[**R Markdown** has excellent support for citations](https://bookdown.org/yihui/rmarkdown/markdown-syntax.html). The simplest way to use references in an **R Markdown** file is to add a bibliography file using the `bibliography` field.
```{r}
yml() %>%
yml_citations(bibliography = "refs.bib")
```
However, if you only have a few references and want to keep your file self-contained, you can also specify references directly in your YAML using `yml_reference()` and `reference()`.
```{r}
ref <- reference(
id = "fenner2012a",
title = "One-click science marketing",
author = list(
family = "Fenner",
given = "Martin"
),
`container-title` = "Nature Materials",
volume = 11L,
URL = "https://doi.org/10.1038/nmat3283",
DOI = "10.1038/nmat3283",
issue = 4L,
publisher = "Nature Publishing Group",
page = "261-263",
type = "article-journal",
issued = list(
year = 2012,
month = 3
)
)
yml() %>%
yml_reference(ref)
```
`yml_reference()` also supports package citation using the `.bibentry` argument and `citation()`.
```{r}
yml() %>%
yml_reference(.bibentry = citation("purrr"))
```
If you have an existing `.bib` file, but you want to specify it in the YAML, instead, you can convert it with `bib2yml()`. For instance, if you wrote a `.bib` file for the packages used in your document with `knitr::write_bib()`, `bib2yml()` will translate the file to YAML you can include directly in the metadata.
# R Markdown extensions
Packages that extend **R Markdown**, such as **bookdown** and **blogdown**, also extend the YAML used to make documents. One of the main ways that other packages introduce YAML is through new output functions. [**xaringan**](https://bookdown.org/yihui/rmarkdown/xaringan.html), for instance, doesn't use custom YAML outside of its output function, so **ymlthis** supports it out-of-box. Passing `xaringan::moon_reader()` to `yml_output()` will write the YAML for you.
```{r}
yml() %>%
yml_title("Presentation Ninja") %>%
yml_subtitle("with xaringan") %>%
yml_output(
xaringan::moon_reader(
lib_dir = "libs",
nature = list(
highlightStyle = "github",
highlightLines = TRUE,
countIncrementalSlides = FALSE
)
)
)
```
**ymlthis** can process any output function. Other packages also add additional YAML; **ymlthis** supports six **R Markdown** packages: **bookdown**, **blogdown**, **pkgdown**, **pagedown**, **rticles**, and **distill**. **ymlthis** also supports YAML for writing scheduled emails with RStudio Connect. You can find functions supporting these packages with the patterns `yml_packagename_*()` and `packagename_*()` (`rsconnect`, in the case of RStudio Connect functions). Functions that start with `yml_packagename_*()` document YAML fields and return `yml` objects, while functions that start with `packagename_*()` are helper functions. There are also a few template functions. `pkgdown_template()`, for instance, will assemble a full template for `_pkgdown.yml` and return it as a `yml` object, and `blogdown_template()` will return YAML templates matching your Hugo theme.
| package| output function | top-level YAML |
|--:|--:|--:|
| bookdown | `r check()` | `r check()` |
| blogdown | `r check()` | `r check()` |
| pkgdown | `r check()` | `r check()` |
| pagedown | `r check()` | `r check()` |
| rticles | `r check()` | `r check()` |
| distill | `r check()` | `r check()` |
| learnr | `r check()` | `r cross()`|
| xaringan | `r check()` | `r cross()`|
| revealjs | `r check()` | `r cross()`|
| flexdashboard | `r check()` | `r cross()`|
Table: Sources of YAML in R Markdown Extension
# R Markdown workflows
**ymlthis** prints YAML cleanly to the console such that you could copy and paste it into an **R Markdown** document. However, **ymlthis** also provides a number of other workflows.
### YAML add-in
The easiest way is to use the Shiny add-in included with **ymlthis**; the add-in supports the most commonly used R Markdown options, citations, LaTeX options, and parameterized reports. You can then export the YAML to an R Markdown file, YAML file, or have it placed on your clipboard.
For more flexibility or to use R Markdown extension packages, you'll have to write code, as we've been doing in this vignette. Your main options are to write the YAML to a file or to place it on your clipboard.
### Writing to files
`use_rmarkdown()`, `use_yml_file()`, and friends will take a `yml` object and write to a file for you. Passing `yml` objects to `use_rmarkdown()` is often the simplest approach: it will translate the `yml` object into YAML and open a new R Markdown file for you with the metadata already written.
**ymlthis** also supports YAML files. For instance, using `pkgdown_template() %>% use_pkgdown_yml()` will write the YAML for your **pkgdown** site to `_pkgdown.yml` based on your package directory. **ymlthis** also has some helper functions for working with Pandoc templates and highlighting themes.
As an example, let's set up the navbar YAML for an **R Markdown** website and then pass it to `use_navbar_yml()`.
```{r}
navbar_yaml <- yml_empty() %>%
yml_site_opts(
name = "my-website",
output_dir = "_site",
include = "demo.R",
exclude = c("docs.txt", "*.csv")
) %>%
yml_navbar(
title = "My Website",
left = list(
navbar_page("Home", href = "index.html"),
navbar_page(navbar_separator(), href = "about.html")
)
) %>%
yml_output(html_document(toc = TRUE, highlight = "textmate"))
# save to temporary directory since this is not interactive
path <- tempfile()
fs::dir_create(path)
use_navbar_yml(navbar_yaml, path = path)
```
In addition to writing to files, you can save YAML to your `.Rprofile` using `options(ymlthis.defaults = "{YAML}")`. `yml()` will return the stored YAML by default. If you pass a `yml` object to `use_yml_defaults()`, the code to do this will be placed on your clipboard, which you should paste into your `.Rprofile`. Open that file with `usethis::edit_r_profile()`. You can also set a default for body text for `use_rmarkdown()` by setting the `ymlthis.rmd_body()` option, e.g. `options(ymlthis.rmd_body = "{your text}")` (or take advantage of `use_rmd_defaults()`). Together with specifying default YAML, `use_rmarkdown()` also serves as an ad-hoc way to make R Markdown templates.
```{r}
old <- options(
ymlthis.default_yml = "author: Malcolm Barrett
date: '`r format(Sys.Date())`'
output: bookdown::pdf_document2",
ymlthis.rmd_body = c(
"",
ymlthis::setup_chunk(),
"",
ymlthis::code_chunk(
library(ymlthis)
)
)
)
# use temporary path set above
use_rmarkdown(path = file.path(path, "analysis.Rmd"))
# reset previous option defaults
options(old)
```
| function | action |
|--:|--:|
| `use_yml_file()` | Write `yml` to a file |
| `use_bookdown_yml()`| Write `yml` to `_bookdown.yml` |
| `use_navbar_yml()` | Write `yml` to `_navbar.yml` |
| `use_output_yml()` | Write `yml` to `_output.yml` |
| `use_pkgdown_yml()` | Write `yml` to `_pkgdown.yml` |
| `use_site_yml()` | Write `yml` to `_site.yml` |
Table: ymlthis `use_*()` functions to write to `.yml` files
| function | action |
|--:|--:|
| `use_rmarkdown()` | Write `yml` to a `.Rmd` file |
| `use_index_rmd()` | Write `yml` to `Index.Rmd` |
Table: ymlthis `use_*()` to write to `.Rmd` files
### Placing YAML on your clipboard
A final way to use **ymlthis** is to put YAML on your clipboard to paste into a file or other setting. To place rendered YAML on your clipboard, simply pass a `yml` object to `use_yml()`.
| function | action |
|--:|--:|
| `use_yml()` | Place `yml` on your clipboard |
| `use_yml_defaults()` | Place code on your clipboard to save `yml` to your default options |
| `use_pandoc_highlight_style()` | Write pandoc theme templates to a `.theme` file |
| `use_pandoc_template()` | Write pandoc templates to a file |
Table: Additional **ymlthis** `use_*()` functions
# Working with yml objects
Under the hood, `yml` objects are lists of types that match the corresponding YAML and are only converted to YAML when printing or writing to files. Because `yml` objects are just lists, you can work with them as such. **ymlthis** also includes several **purrr**-like functions for working with `yml` objects. Let's define a `yml` object that has a fairly comprehensive set of options:
```{r}
x <-
yml() %>%
yml_author(
c("Yihui Xie", "Hadley Wickham"),
affiliation = "RStudio"
) %>%
yml_date("07/04/2019") %>%
yml_title("Reproducible Research in R") %>%
yml_category(c("r", "reprodicibility")) %>%
yml_output(
pdf_document(
keep_tex = TRUE,
includes = includes2(after_body = "footer.tex")
),
html_document()
) %>%
yml_latex_opts(biblio_style = "apalike")
```
The resulting YAML of `x` is:
```{r echo=FALSE}
x %>% ymlthis::asis_yaml_output()
```
We can use `yml_discard()` to remove the `category` option:
```{r}
x %>%
yml_discard("category")
```
We can use **purrr**-style lambdas to express what to discard. How about any YAML fields with a length greater than one?
```{r}
x %>%
yml_discard(~ length(.x) > 1)
```
The `yml_pluck()` function is useful for selectively acquiring a nested portion of the YAML:
```{r}
x %>%
yml_pluck("output", "pdf_document")
```
```{r, include=FALSE}
options(oldoption)
```
| /scratch/gouwar.j/cran-all/cranData/ymlthis/vignettes/introduction-to-ymlthis.Rmd |
---
title: "The YAML Fieldguide"
output:
prettydoc::html_pretty:
theme: tactile
vignette: >
%\VignetteIndexEntry{The YAML Fieldguide}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
collapse = TRUE,
comment = "",
warning = FALSE
)
```
```{r pandoc_check, echo=FALSE}
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
```
```{r roxygen_check, echo=FALSE}
if (!requireNamespace("roxygen2")) {
cat("roxygen2 is required to render this vignette: `install.packages('roxygen2'`")
knitr::knit_exit()
}
```
```{r setup}
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
function_name <- function(x) {
function_call <- x$call
ifelse(rlang::has_length(function_call), as.character(function_call[[2]]), NA)
}
block_names <- function(x) x$tags %>% purrr::map_chr(~.x$tag)
get_doc_name <- function(x) {
tags <- block_names(x)
rdname_index <- which(tags == "rdname")
if (purrr::is_empty(rdname_index)) return(function_name(x))
x$tags[[rdname_index]]$val
}
get_params <- function(x) {
param_lists <- which(block_names(x) == "param")
f <- get_doc_name(x)
if (!rlang::has_length(param_lists) || is.na(f)) return(data.frame())
params_desc <- x$tags[param_lists] %>%
purrr::map(~as.data.frame(.x$val, stringsAsFactors = FALSE)) %>%
do.call(rbind, .)
params_desc$description <- stringr::str_replace_all(
params_desc$description,
"\n",
" "
)
params_desc$name <- params_desc$name %>%
stringr::str_split(",") %>%
purrr::map_chr(
~paste0("`", .x, "`") %>% paste(collapse = ", ")
)
cbind(func = f, params_desc, stringsAsFactors = FALSE)
}
link_help_page <- function(x) {
url <- "https://ymlthis.r-lib.org/"
glue::glue("<a href='{url}/reference/{x}.html'>{x}</a>")
}
filter_kable <- function(.tbl, .pattern = NULL, caption = NULL) {
if (!is.null(.pattern)) {
index <- stringr::str_detect(.tbl$func, .pattern)
.tbl <- .tbl[index, ]
}
.tbl$func <- link_help_page(.tbl$func)
knitr::kable(
.tbl,
col.names = c("Help Page", "Argument", "Description"),
row.names = FALSE,
caption = caption
)
}
fields_df <- roxygen2::parse_package("../") %>%
purrr::map(get_params) %>%
do.call(rbind, .)
```
**ymlthis** attempts to write common YAML for you in the right way and to document the many YAML field options in one place. The fieldguide is a collection of all the fields documented in the **ymlthis** help pages, organized by source. Note that some argument names do not match the YAML field name exactly in order because not all field names are valid R names (e.g. the `link-citations` YAML field needs to be `link_citations` in R); these differences are noted in the argument description. Additionally, not all of these arguments are top-level YAML; see the linked help pages for more details.
## Basic YAML
```{r}
fields_df %>%
filter_kable("yml_author|yml_runtime|yml_clean|yml_toc", caption = "Basic YAML")
```
The nested fields for the `output` field are based on the arguments of the output function. See the help page for the function you are using, e.g., `?rmarkdown::pdf_document`.
## LaTeX/PDF Options
```{r}
fields_df %>%
filter_kable("latex", caption = "LaTeX/PDF Options")
```
## R Markdown Websites
```{r}
fields_df %>%
filter_kable("site|navbar|vignette", caption = "R Markdown Websites")
```
## Citations
```{r}
fields_df %>%
filter_kable("citations", caption = "Citations")
```
## blogdown YAML
```{r}
fields_df %>%
filter_kable("yml_blogdown_opts", caption = "blogdown YAML")
```
## bookdown YAML
```{r}
fields_df %>%
filter_kable("bookdown", caption = "bookdown YAML")
```
## pkgdown YAML
```{r}
fields_df %>%
filter_kable("yml_pkgdown", caption = "pkgdown YAML")
```
## pagedown YAML
```{r}
fields_df %>%
filter_kable("pagedown", caption = "pagedown YAML")
```
## distill YAML
```{r}
fields_df %>%
filter_kable("distill", caption = "distill YAML")
```
## rticles YAML
```{r}
fields_df %>%
filter_kable("rticles", caption = "rticles YAML")
```
## RStudio Connect Scheduled Email YAML
```{r}
fields_df %>%
filter_kable("rsconnect", caption = "RStudio Connect Scheduled Email YAML")
```
```{r, include=FALSE}
options(oldoption)
```
| /scratch/gouwar.j/cran-all/cranData/ymlthis/vignettes/yaml-fieldguide.Rmd |
---
title: "YAML: an Overview"
output:
prettydoc::html_pretty:
theme: tactile
vignette: |
%\VignetteIndexEntry{YAML: an Overview}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
collapse = TRUE,
comment = "",
warning = FALSE
)
```
```{r setup}
library(ymlthis)
oldoption <- options(devtools.name = "Malcolm Barrett", crayon.enabled = FALSE)
```
```{r pandoc_check, echo=FALSE}
if (!rmarkdown::pandoc_available()) {
cat("pandoc is required to use ymlthis. Please visit https://pandoc.org/ for more information.")
knitr::knit_exit()
}
```
# Basic syntax
The basic syntax of YAML is to use key-value pairs in the format `key: value`. A YAML code block should be fenced in with `---` before and after (you can also use `...` to end the YAML block, but this is not very common in **R Markdown**).
```{r}
yml(date = FALSE) %>%
asis_yaml_output()
```
In R, the equivalent structure is a list with named character vector: `list(author = "Malcolm Barrett")`. In fact, you can call this list in **R Markdown** using the `metadata` object; in this case, `metadata$author` will return `"Malcolm Barrett"`
In YAML, spaces are used to indicate nesting. When we want to specify the output function `pdf_document(toc = TRUE)`, we need to nest it under the `output` field. We also need to nest `toc` under `pdf_document` so that it gets passed to that function correctly.
```{r, warning = FALSE}
yml_empty() %>%
yml_output(pdf_document(toc = TRUE)) %>%
asis_yaml_output()
```
In R, the equivalent structure is a nested list, each with a name: `list(output = list(pdf_document = list(toc = TRUE)))`. Similarly, you can call this in R Markdown using the `metadata` object, e.g. `metadata$output$pdf_document$toc`. The hierarchical structure (which you can see with `draw_yml_tree()`) looks like this:
```{r, warning = FALSE}
yml_empty() %>%
yml_output(pdf_document(toc = TRUE)) %>%
draw_yml_tree()
```
Without the extra indents, YAML doesn't know `toc` is connected to `pdf_document` and thinks the value of `pdf_document` is `NULL`. YAML that looks like this:
```yaml
---
output:
pdf_document:
toc: true
---
```
has a hierarchy that looks like this:
```{r}
list(output = list(pdf_document = NULL), toc = TRUE) %>%
as_yml() %>%
draw_yml_tree()
```
If you use output functions without additional arguments, the value of `output` can simply be the name of the function.
```{r}
yml_empty() %>%
yml_output(html_document()) %>%
asis_yaml_output()
```
However, if you're specifying more than one output type, you must use the nesting syntax. If you don't want to include additional arguments, use `"default"` as the function's value.
```{r, warning = FALSE}
yml_empty() %>%
yml_output(html_document(), pdf_document(toc = TRUE)) %>%
asis_yaml_output()
```
Some YAML fields take unnamed vectors as their value. You can specify an element of the vector by adding a new line and `-` (note that the values are not indented below `category` here).
```{r}
yml_empty() %>%
yml_category(c("R", "Reprodicible Research")) %>%
asis_yaml_output()
```
In R, the equivalent structure is a list with a named vector: `list(categories = c("R", "Reprodicible Research"))`. `metadata$category` will return `c("R", "Reprodicible Research")`. Another way to specify vectors is to use `[]` with each object separated by a column, as in the syntax for `c()`. This YAML is equivalent to the YAML above:
```yaml
---
category: [R, Reprodicible Research]
---
```
By default, **ymlthis** uses the `-` syntax for vectors.`-` is also used to group elements together. For instance, in the `params` field for parameterized reports, we group parameter information together by using `-`. The first line is the name and value of the parameter, while all the lines until the next `-` are extra information about the parameter. While you can use `metadata` to call objects in `params`, `params` has it's own object you can call directly: `params$a` and `params$data` will return the values of `a` and `data`.
```{r}
yml_empty() %>%
yml_params(
list(a = 1, input = "numeric"),
list(data = "data.csv", input = "text")
) %>%
asis_yaml_output()
```
In R, the equivalent structure is a nested list that contains a list of unnamed lists: `list(param = list(list(a = 1, input = numeric), list(data = "data.csv", input = "file")))`. The inner-most lists group items together, e.g. `list(a = 1, input = numeric)` groups `a` and `input`.
```{r}
yml_empty() %>%
yml_params(
list(a = 1, input = "numeric"),
list(data = "data.csv", input = "text")
) %>%
draw_yml_tree()
```
# Types in YAML
You may have noticed that strings in YAML don't always need to be quoted. However, it can be useful to explicitly wrap strings in quotes when they contain special characters like `:` and `@`.
```{r}
yml_empty() %>%
yml_title("R Markdown: An Introduction") %>%
asis_yaml_output()
```
R code can be written as inline expressions `` `r knitr::inline_expr('expr')` ``. `yml_code()` will capture R code for you and put it in a valid format. R code in `params` needs to be slightly different: use `!r` (e.g. `!r expr`) to call an R object.
```yaml
author: '`r knitr::inline_expr('whoami::fullname()')`'
params:
date: !r Sys.Date()
```
Logical values in YAML are unusual: `true/false`, `yes/no`, and `on/off` are all equivalent to `TRUE/FALSE` in R. Any of these turn on the table of contents:
```yaml
toc: true
toc: yes
toc: on
```
By default, **ymlthis** uses `true/false`. If you want to use any of these values literally (e.g. you want a string equal to `"yes"`), you need to wrap them in quotation marks:
```{r}
yml_empty() %>%
yml_params(x = "yes") %>%
asis_yaml_output()
```
`NULL` can be specified using `null` or `~`. By default, **ymlthis** uses `null`. If you want to specify an empty vector, use `[]`, e.g. `category: []`. For an empty string, just use empty quotation marks (`""`).
# Sources of YAML
Where do the YAML fields you use in **R Markdown** come from? Many YAML fields that we use come from Pandoc from the **rmarkdown** package. These both use YAML to specify the build of the document and to pass information to be printed in a template. Pandoc templates can also be customized to add new YAML. The most common sources of YAML are:
1. Pandoc
1. **R Markdown**
1. Output functions (such as `rmarkdown::pdf_document()`)
1. Custom Pandoc templates
1. **R Markdown** extension packages (such as **blogdown**)
1. Hugo (in the case of **blogdown**)
Because YAML is an extensible approach to metadata, and there is often no way to validate that your YAML is correct. YAML will often fail silently if you, for instance, make a typo in the field name or misspecify the nesting between fields. For more information on the fields available in R Markdown and friends, see the [YAML Fieldguide](yaml-fieldguide.html).
```{r, include=FALSE}
options(oldoption)
```
| /scratch/gouwar.j/cran-all/cranData/ymlthis/vignettes/yaml-overview.Rmd |
#' Argument assertions
#'
# -------------------------------------------------------------------------
#' Assertions for function arguments. Motivated by `vctrs::vec_assert()` but
#' with lower overhead at a cost of less informative error messages. Designed to
#' make it easy to identify the top level calling function whether used within a
#' user facing function or internally.
#'
# -------------------------------------------------------------------------
#' @param x
#'
#' Argument to check.
#'
#' @param arg `[character]`
#'
#' Name of argument being checked (used in error message).
#'
#' @param call `[call]`
#'
#' Call to use in error message.
#'
# -------------------------------------------------------------------------
#' @return
#'
#' NULL if the assertion succeeds (error otherwise).
#'
# -------------------------------------------------------------------------
#' @examples
#'
#' # Use in a user facing function
#' fun <- function(i, d, l, chr, b) {
#' .assert_scalar_int(i)
#' TRUE
#' }
#' fun(i=1L)
#' try(fun())
#' try(fun(i="cat"))
#'
#' # Use in an internal function
#' internal_fun <- function(a) {
#' .assert_string(a, arg = deparse(substitute(a)), call = sys.call(-1L))
#' TRUE
#' }
#' external_fun <- function(b) {
#' internal_fun(a=b)
#' }
#' external_fun(b="cat")
#' try(external_fun())
#' try(external_fun(b = letters))
#'
# -------------------------------------------------------------------------
#' @noRd
NULL
# -------------------------------------------------------------------------
.assert_integer <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.integer(x))
stopf("`%s` must be an integer vector.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_int <- .assert_integer
# -------------------------------------------------------------------------
.assert_double <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.double(x))
stopf("`%s` must be a double vector.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_dbl <- .assert_double
# -------------------------------------------------------------------------
.assert_numeric <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_num <- .assert_numeric
# -------------------------------------------------------------------------
.assert_logical <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.logical(x))
stopf("`%s` must be a logical vector.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_lgl <- .assert_logical
# -------------------------------------------------------------------------
.assert_character <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.character(x))
stopf("`%s` must be a character vector.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_chr <- .assert_character
# -------------------------------------------------------------------------
.assert_data_frame <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.data.frame(x))
stopf("`%s` must be a data frame.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_list <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.list(x))
stopf("`%s` must be a list.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_integer <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.integer(x) && length(x) == 1L))
stopf("`%s` must be an integer vector of length 1.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_int <- .assert_scalar_integer
# -------------------------------------------------------------------------
.assert_scalar_integer_not_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.integer(x) && length(x) == 1L) || is.na(x))
stopf("`%s` must be an integer vector of length 1 and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_int_not_na <- .assert_scalar_integer_not_na
# -------------------------------------------------------------------------
.assert_scalar_double <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.double(x) && length(x) == 1L))
stopf("`%s` must be a double vector of length 1.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_dbl <- .assert_scalar_double
# -------------------------------------------------------------------------
.assert_scalar_double_not_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.double(x) && length(x) == 1L) || is.na(x))
stopf("`%s` must be a double vector of length 1 and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_dbl_not_na <- .assert_scalar_double_not_na
# -------------------------------------------------------------------------
.assert_scalar_numeric <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.numeric(x) && length(x) == 1L))
stopf("`%s` must be a numeric vector of length 1.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_num <- .assert_scalar_numeric
# -------------------------------------------------------------------------
.assert_scalar_numeric_not_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.numeric(x) && length(x) == 1L) || is.na(x))
stopf("`%s` must be a numeric vector of length 1 and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_num_not_na <- .assert_scalar_numeric_not_na
# -------------------------------------------------------------------------
.assert_scalar_logical <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.logical(x) && length(x) == 1L))
stopf("`%s` must be a logical vector of length 1.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_lgl <- .assert_scalar_logical
# -------------------------------------------------------------------------
.assert_bool <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.logical(x) && length(x) == 1L) || is.na(x))
stopf("`%s` must be boolean (TRUE/FALSE).", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_boolean <- .assert_bool
# -------------------------------------------------------------------------
.assert_scalar_character <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.character(x) && length(x) == 1L))
stopf("`%s` must be a character vector of length 1.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_chr <- .assert_scalar_character
# -------------------------------------------------------------------------
.assert_scalar_character_not_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!(is.character(x) && length(x) == 1L) || is.na(x))
stopf("`%s` must be a character vector of length 1 and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_scalar_chr_not_na <- .assert_scalar_character_not_na
# -------------------------------------------------------------------------
.assert_string <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_scalar_chr(x = x, arg = arg, call = call)
}
# -------------------------------------------------------------------------
.assert_non_negative_or_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_non_negative_or_na(x))
stopf("`%s` values must be non-negative or NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_non_positive_or_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_non_positive_or_na(x))
stopf("`%s` values must be non-positive or NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_non_negative <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_non_negative(x))
stopf("`%s` values must be non-negative and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_non_positive <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_non_positive(x))
stopf("`%s` values must be non-positive and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_positive <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_positive(x))
stopf("`%s` values must be positive and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_negative <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_negative(x))
stopf("`%s` values must be negative and not NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_positive_or_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_positive_or_na(x))
stopf("`%s` values must be positive or NA.", arg, .call = call)
}
# -------------------------------------------------------------------------
.assert_negative_or_na <- function(x, arg = deparse(substitute(x)), call = sys.call(-1L)) {
.assert_not_missing(x = x, arg = arg, call = call)
if (!is.numeric(x))
stopf("`%s` must be a numeric vector.", arg, .call = call)
if (!.all_negative_or_na(x))
stopf("`%s` values must be negative or NA.", arg, .call = call)
}
# ------------------------------------------------------------------------- #
# ------------------------------------------------------------------------- #
# -------------------------------- INTERNALS ------------------------------ #
# ------------------------------------------------------------------------- #
# ------------------------------------------------------------------------- #
.assert_not_missing <- function(x, arg, call) {
if (missing(x))
stopf("argument `%s` is missing, with no default.", arg, .call = call)
}
# -------------------------------------------------------------------------
.all_non_negative_or_na <- function(x) {
min(0, x, na.rm = TRUE) >= 0
}
# -------------------------------------------------------------------------
.all_non_positive_or_na <- function(x) {
max(0, x, na.rm = TRUE) <= 0
}
# -------------------------------------------------------------------------
.all_non_negative <- function(x) {
if (length(x) == 0L)
return(TRUE)
min <- min(x)
if (is.na(min))
return(FALSE)
if (min >= 0) TRUE else FALSE
}
# -------------------------------------------------------------------------
.all_non_positive <- function(x) {
if (length(x) == 0L)
return(TRUE)
max <- max(x)
if (is.na(max))
return(FALSE)
if (max <= 0) TRUE else FALSE
}
# -------------------------------------------------------------------------
.all_positive <- function(x) {
if (length(x) == 0L)
return(TRUE)
min <- min(x)
if (is.na(min))
return(FALSE)
if (min > 0) TRUE else FALSE
}
# -------------------------------------------------------------------------
.all_negative <- function(x) {
if (length(x) == 0L)
return(TRUE)
max <- max(x)
if (is.na(max))
return(FALSE)
if (max < 0) TRUE else FALSE
}
# -------------------------------------------------------------------------
.all_positive_or_na <- function(x) {
if (length(x) == 0L)
return(TRUE)
nax <- is.na(x)
if (sum(nax) == length(x))
return(TRUE)
if (min(x, na.rm = TRUE) <= 0) FALSE else TRUE
}
# -------------------------------------------------------------------------
.all_negative_or_na <- function(x) {
if (length(x) == 0L)
return(TRUE)
nax <- is.na(x)
if (sum(nax) == length(x))
return(TRUE)
if (max(x, na.rm = TRUE) >= 0) FALSE else TRUE
}
# -------------------------------------------------------------------------
| /scratch/gouwar.j/cran-all/cranData/ympes/R/assert.R |
#' Quote names
#'
# -------------------------------------------------------------------------
#' `cc()` quotes comma separated names whilst trimming outer whitespace. It is
#' intended for interactive use only.
#'
# -------------------------------------------------------------------------
#' @param ...
#'
#' Unquoted names (separated by commas) that you wish to quote.
#'
#' Empty arguments (e.g. third item in `one,two,,four`) will be returned as `""`.
#'
#' @param .clip `[bool]`
#'
#' Should the code to generate the constructed character vector be copied to
#' your system clipboard.
#'
#' Defaults to FALSE unless the option "imp.clipboard" is set to TRUE.
#'
#' Note that copying to clipboard requires the availability of package
#' [clipr](https://cran.r-project.org/package=clipr).
#'
# -------------------------------------------------------------------------
#' @return
#'
#' A character vector of the quoted input.
#'
# -------------------------------------------------------------------------
#' @examples
#'
#' cc(dale, audrey, laura, hawk)
#'
# -------------------------------------------------------------------------
#' @importFrom utils capture.output
#' @export
cc <- function(..., .clip = getOption("imp.clipboard", FALSE)) {
res <- substitute(list(...))
# we use as.character rather than deparse as we simply want quoted names
res <- as.character(res[-1])
if (interactive() && isTRUE(.clip)) {
if (!requireNamespace("clipr", quietly = TRUE)) {
message("Unable to copy to clipboard: install 'clipr' for this functionality.")
} else if (clipr::clipr_available()) {
clipr::write_clip(capture.output(dput(res, control = "all")))
} else {
message("Unable to copy to clipboard.")
}
}
res
}
| /scratch/gouwar.j/cran-all/cranData/ympes/R/cc.R |
#' Capture string tokens into a data frame
#'
# -------------------------------------------------------------------------
#' `fstrcapture()` is a replacement for [strcapture()] with better performance
#' when `perl = TRUE`.
#'
# -------------------------------------------------------------------------
#' @param perl Should Perl-compatible regexps be used?
#'
#' @param useBytes If TRUE the matching is done byte-by-byte rather than
#' character-by-character.
#'
#' @inheritParams utils::strcapture
#'
# -------------------------------------------------------------------------
#' @note
#' Compared to [strcapture()], `fstrcapture()` sets the default value for `perl`
#' to `TRUE`. Apart from this it can be used as a drop-in replacement.
#'
# -------------------------------------------------------------------------
#' @return
#'
#' A tabular data structure of the same type as proto, so typically a data.frame,
#' containing a column for each capture expression. The column types and names
#' are inherited from proto. Cases in x that do not match pattern have NA in
#' every column.
#'
# -------------------------------------------------------------------------
#' @examples
#'
#' x <- "chr1:1-1000"
#' pattern <- "(.*?):([[:digit:]]+)-([[:digit:]]+)"
#' proto <- data.frame(chr=character(), start=integer(), end=integer())
#' fstrcapture(pattern, x, proto)
#'
# -------------------------------------------------------------------------
#' @seealso [strcapture()] for further details.
#'
# -------------------------------------------------------------------------
#' @export
fstrcapture <- function(pattern, x, proto, perl = TRUE, useBytes = FALSE) {
if (isTRUE(perl)) {
m <- regexpr(pattern = pattern, text = x, perl = TRUE, useBytes = useBytes)
nomatch <- is.na(m) | m == -1L
ntokens <- length(proto)
if (!all(nomatch)) {
length <- attr(m, "match.length")
start <- attr(m, "capture.start")
length <- attr(m, "capture.length")
end <- start + length - 1L
end[nomatch, ] <- start[nomatch, ] <- NA
res <- substring(x, start, end)
out <- matrix(res, length(m))
if (ncol(out) != ntokens) {
stop("The number of captures in 'pattern' != 'length(proto)'")
}
} else {
out <- matrix(NA_character_, length(m), ntokens)
}
conformToProto(out, proto)
} else {
utils::strcapture(pattern, x, proto, perl, useBytes)
}
}
conformToProto <- function(mat, proto) {
ans <- lapply(seq_along(proto), function(i) {
if (isS4(proto[[i]])) {
methods::as(mat[,i], class(proto[[i]]))
} else {
fun <- match.fun(paste0("as.", class(proto[[i]])))
fun(mat[,i])
}
})
names(ans) <- names(proto)
if (isS4(proto)) {
methods::as(ans, class(proto))
} else {
as.data.frame(ans, optional=TRUE, stringsAsFactors=FALSE)
}
}
| /scratch/gouwar.j/cran-all/cranData/ympes/R/fstrcapture.R |
#' Pattern matching on data frame rows
#'
# -------------------------------------------------------------------------
#' `greprows()` searches for pattern matches within a data frames columns and
#' returns the related rows or row indices.
#'
# -------------------------------------------------------------------------
#' @param dat Data frame
#'
#' @param cols `[character]`
#'
#' Character vector of columns to search.
#'
#' If `NULL` (default) all character and factor columns will be searched.
#'
#' @param value `[logical]`
#'
#' Should a data frame of rows be returned.
#'
#' If `FALSE` row indices will be returned instead of the rows themselves.
#'
#' @inheritParams base::grep
#'
# -------------------------------------------------------------------------
#' @return
#'
#' A data frame of the corresponding rows or, if `value = FALSE`, the
#' corresponding row numbers.
#'
# -------------------------------------------------------------------------
#' @examples
#'
#' dat <- data.frame(
#' first = letters,
#' second = factor(rev(LETTERS)),
#' third = "Q"
#' )
#' greprows(dat, "A|b")
#' greprows(dat, "A|b", ignore.case = TRUE)
#' greprows(dat, "c", value = FALSE)
#'
# -------------------------------------------------------------------------
#' @seealso [grep()]
#'
# -------------------------------------------------------------------------
#' @export
greprows <- function(
dat,
pattern,
cols = NULL,
value = TRUE,
ignore.case = FALSE,
perl = FALSE,
fixed = FALSE,
invert = FALSE
) {
if (!is.data.frame(dat))
stop("`dat` must be a data frame.")
if (!(is.character(pattern) && length(pattern) == 1L))
stop("`pattern` must be a character string.")
if (!(is.logical(value) && length(value) == 1L && !is.na(value)))
stop("`value` must be TRUE or FALSE.")
# pull out specified columns or characters and factors if NULL
if (is.null(cols)) {
cols <- vapply(dat, function(x) is.character(x) || is.factor(x), TRUE)
} else if (is.character(cols)) {
invalid <- cols[!cols %in% names(dat)]
if (length(invalid))
stopf("%s is not a valid column name", sQuote(invalid[1]))
} else {
stop("`cols` must be a character vector")
}
cols <- .subset(dat, cols)
# get the matching rows across each column
idx <- lapply(
cols,
grep,
pattern = pattern,
ignore.case = ignore.case,
perl = perl,
fixed = fixed,
invert = invert,
value = FALSE,
useBytes = FALSE
)
# Combine the idx and pull out the unique ones
idx <- unique(Reduce(c, idx))
# return the values or the index
if (value) dat[idx,,drop = FALSE] else idx
}
| /scratch/gouwar.j/cran-all/cranData/ympes/R/greprows.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.