code
stringlengths 1
13.8M
|
---|
model.frame.gls <- function(object, ...) model.frame(formula(object), nlme::getData(object),...)
model.frame.lme <- function(object, ...) object$data
model.matrix.aovlist <- function(object, ...)
stop(sQuote("predicted.means"), " does not support objects of class ",
sQuote("aovlist"))
model.matrix.gls <- function(object, ...)
model.matrix(terms(object), data = nlme::getData(object), ...)
model.matrix.lme <- function(object, ...)
model.matrix(terms(object), data = model.frame(object), ...)
terms.gls <- function(object, ...) terms(model.frame(object),...)
terms.lme <- function (object, ...) {
v <- object$terms
if (is.null(v)) stop("no terms component")
return(v)
} |
library(qgisprocess)
qgis_configure()
has_qgis()
if (is_macos()) qgis_detect_macos()
if (is_windows()) qgis_detect_windows()
if (has_qgis()) qgis_path()
if (has_qgis()) qgis_version()
if (has_qgis()) cat(qgis_run()$stdout)
if (has_qgis()) cat(qgis_run()$stderr)
if (has_qgis()) qgis_providers()
if (has_qgis()) qgis_algorithms()
if (has_qgis()) qgis_algorithms()$algorithm |
antoch.test=function(formula, data, chngpt.var, plot.=FALSE) {
DNAME = deparse(substitute(data))
dat.1=data[order(data[[chngpt.var]]),]
tmp=model.frame(formula, dat.1)
y=tmp[[1]]
fit=keepWarnings(glm(formula, data=dat.1, family="binomial"))
if(length(fit$warning)!=0) {
return (NA)
} else {
fit=fit$value
}
n = nrow(dat.1)
mu.hat = expit(predict(fit))
T. = sapply (1:(n-1), function(k) {
S.k.0 = sum((y-mu.hat)[1:k])
V.hat = mean(mu.hat*(1-mu.hat)) * k * (n-k) / n
abs(S.k.0)/sqrt(V.hat)
})
if(plot.) plot(T., type="b")
T.max=max(T.)
names(T.max)="Maximum statisticsZ"
loglogn=log(log(n))
T1=sqrt(2*loglogn)*T.max - 2*loglogn - 1/2*log(loglogn) + 1/2*log(pi)
p.value=1-exp(-2*exp(-T1))
res=list()
res$statistic=T.max
res$p.value=p.value
res$k=which.max(T.)
res$parameter=NULL
res$conf.int=NULL
res$estimate=NULL
res$null.value=NULL
res$alternative="two-sided"
res$method="Antoch Change Point Test"
res$data.name=DNAME
class(res)=c("htest",class(res))
res
} |
knitr::opts_chunk$set(
comment = "
collapse = TRUE,
cache = TRUE
)
options(
rlang_trace_top_env = rlang::current_env(),
rlang_backtrace_on_error = "none"
) |
compare_biclusters <- function(bc1, bc2) {
if(inherits(bc1, "biclustermd") & inherits(bc2, "biclustermd")) {
P1 <- part_matrix_to_vector(bc1$P)
P2 <- part_matrix_to_vector(bc2$P)
Q1 <- part_matrix_to_vector(bc1$Q)
Q2 <- part_matrix_to_vector(bc2$Q)
P_similarity <- c(
"Rand" = RRand(P1, P2)[[1]],
"HA" = RRand(P1, P2)[[2]],
"Jaccard" = jaccard_similarity(P1, P2)
)
Q_similarity <- c(
"Rand" = RRand(Q1, Q2)[[1]],
"HA" = RRand(Q1, Q2)[[2]],
"Jaccard" = jaccard_similarity(Q1, Q2)
)
list(
"P Similarity" = P_similarity,
"Q Similarity" = Q_similarity
)
} else if(inherits(bc1, "matrix") & inherits(bc2, "matrix")) {
c(
"Rand" = RRand(part_matrix_to_vector(bc1), part_matrix_to_vector(bc2))[[1]],
"HA" = RRand(part_matrix_to_vector(bc1), part_matrix_to_vector(bc2))[[2]],
"Jaccard" = jaccard_similarity(part_matrix_to_vector(bc1), part_matrix_to_vector(bc2))
)
}
} |
vaggregate <- function(.value, .group, .fun, ..., .default = NULL, .n = nlevels(.group)) {
if (!is.integer(.group)) {
if (is.list(.group)) {
.group <- id(.group)
} else {
.group <- id(list(.group))
}
}
if (is.null(.default)) {
.default <- .fun(.value[0], ...)
}
fun <- function(i) {
if (length(i) == 0) return(.default)
.fun(.value[i], ...)
}
indices <- split_indices(.group, .n)
vapply(indices, fun, .default)
}
nlevels <- function(x) {
n <- attr(x, "n")
if (!is.null(n)) n else max(x)
} |
bigquestmotif<-function(mat,ns,nd,sd,alpha)
{
size<-4
nr<-nrow(mat)
ques<- rep(FALSE,ncol(mat))
pers<- rep(FALSE,nrow(mat))
for(i in 1:ns)
{
ri<-sample(1:nr,1)
logr<-rep(TRUE,nrow(mat))
logr[ri]<-FALSE
for(j in 1:nd)
{
D<-sample(1:nr,sd,prob=logr)
gri<-mat[ri,]
griD<-c(D,ri)
cS<-rowSums(t(mat[griD,])==gri)
gij<-cS==length(griD)
if(sum(gij)>= max(sum(ques),2))
{
rri<-mat[ri,gij]
rS<-colSums(t(mat[,gij])==rri)
rij<-rS==sum(gij)
if((sum(rij)>=(alpha*nr)) & ((sum(gij)*sum(rij))>size) )
{
ques<-gij
pers<-rij
size <- sum(ques)*sum(pers)
}
}
}
}
erg<-list(pers,ques)
erg
}
questmotif<-function(mat,ns,nd,sd,alpha,number)
{
MYCALL <- match.call()
x<-matrix(FALSE,nrow=nrow(mat),ncol=number)
y<-matrix(FALSE,nrow=number,ncol=ncol(mat))
matstore<-mat
Stop <- FALSE
logr<-rep(TRUE,nrow(mat))
for(i in 1:number)
{
erg<-bigquestmotif(mat,ns,nd,sd,alpha)
if(sum(erg[[1]])==0)
{
Stop <- TRUE
break
}
else{
x[logr,i]<-erg[[1]]
y[i,]<-erg[[2]]
logr[logr][erg[[1]]]<-FALSE
mat<-matstore[logr,]
if(sum(logr)<(sd+1))
{
Stop <- TRUE
break
}
}
}
if(Stop)
{return(BiclustResult(as.list(MYCALL),as.matrix(x[,1:(i-1)]),as.matrix(y[1:(i-1),]),(i-1),list(0)))
}
else{
return(BiclustResult(as.list(MYCALL),as.matrix(x),as.matrix(y),i,list(0)))
}
} |
mcnby_ni_pp <- function(N,DEL0,N10,N01) {
ppost<- ppost_singleobs(N,DEL0,N10,N01)
cat(" n =",N," del0 =",DEL0," n10 =",N10," n01 =",N01,
"\n", "PPOST =", ppost)
} |
plot_glucose <- function(df) {
ggplot2::ggplot(df) +
ggplot2::geom_point(data = df, ggplot2::aes(x = df$time_of_day, y = df$glucose),
col = "orange", cex = 0.5) +
ggplot2::geom_line(data = df, ggplot2::aes(x = df$time_of_day, y = df$glucose),
col = "orange") +
ggplot2::facet_grid(df$Date ~ ., scale = "fixed") +
ggplot2::theme_bw() +
ggplot2::ylab("Glucose Level") +
ggplot2::xlab("Time of Day") +
ggplot2::labs(title = "CGM data for Participant")
} |
source("setup.R")
expect_error(BEDMatrix("NOT_FOUND"), "File not found\\.")
expect_error(BEDMatrix("test-BEDMatrix.R"))
for (path in c(paste0(extdataPath, "/example"), paste0(extdataPath, "/example.bed"))) {
bed <- suppressMessages(BEDMatrix(path = path))
expect_equal(nrow(bed), nrow(raw))
expect_message(BEDMatrix(path = path), "Extracting number of samples and rownames from example\\.fam\\.\\.\\.")
expect_error(BEDMatrix(path = standalonePath), "standalone.fam not found\\. Provide number of samples \\(n\\)\\.")
bed <- suppressMessages(BEDMatrix(path = path))
expect_equal(rownames(bed), rownames(raw))
expect_message(BEDMatrix(path = path), "Extracting number of samples and rownames from example\\.fam\\.\\.\\.")
bed <- suppressMessages(BEDMatrix(path = path))
expect_equal(ncol(bed), ncol(raw))
expect_message(BEDMatrix(path = path), "Extracting number of variants and colnames from example\\.bim\\.\\.\\.")
expect_error(BEDMatrix(path = standalonePath), "standalone.fam not found\\. Provide number of samples \\(n\\)\\.")
bed <- suppressMessages(BEDMatrix(path = path))
expect_equal(colnames(bed), colnames(raw))
expect_message(BEDMatrix(path = path), "Extracting number of variants and colnames from example\\.bim\\.\\.\\.")
bed <- BEDMatrix(path = path, n = nrow(raw), p = ncol(raw))
expect_equal(dimnames(bed), list(NULL, NULL))
bed <- BEDMatrix(path = standalonePath, n = 3, p = 6)
expect_equal(dimnames(bed), list(NULL, NULL))
expect_error(BEDMatrix(path = path, n = 10, p = 5), "n or p does not match the dimensions of the file\\.")
} |
NULL
predictFailureModel = function(model, newdata) {
lrn = model$learner
type = lrn$type
ptype = lrn$predict.type
n = nrow(newdata)
if (type == "classif") {
levs = model$task.desc$class.levels
res = if (ptype == "response") {
factor(rep(NA_character_, n), levels = levs)
} else {
matrix(NA_real_, nrow = n, ncol = length(levs), dimnames = list(NULL, levs))
}
} else if (type == "regr") {
res = if (ptype == "response") {
rep(NA_real_, n)
} else {
matrix(NA_real_, nrow = n, ncol = 2L, dimnames = list(NULL, c("response", "se")))
}
} else if (type == "surv") {
if (ptype == "response") {
res = rep.int(NA_real_, n)
} else {
stop("Predict type 'prob' for survival not yet supported")
}
} else if (type == "costsens") {
levs = model$task.desc$class.levels
res = factor(rep(NA_character_, n), levels = levs)
} else if (type == "cluster") {
res = rep(NA_character_, n)
}
return(res)
}
print.FailureModel = function(x, ...) {
print.WrappedModel(x)
catf("Training failed: %s", getFailureModelMsg(x))
}
isFailureModel.FailureModel = function(model) {
return(TRUE)
}
getFailureModelMsg.FailureModel = function(model) {
return(as.character(model$learner.model))
}
getFailureModelDump.FailureModel = function(model) {
return(model$dump)
} |
testthat::teardown({
unlink("iris.tsv.gz")
unlink("iris2.tsv.gz")
unlink("iris3.tsv.gz")
}
) |
aftreg <- function (formula = formula(data),
data = parent.frame(),
na.action = getOption("na.action"),
dist = "weibull",
init,
shape = 0,
id,
param = c("lifeAcc", "lifeExp"),
control = list(eps = 1e-8, maxiter = 20, trace = FALSE),
singular.ok = TRUE,
model = FALSE,
x = FALSE,
y = TRUE)
{
param <- param[1]
if (param == "survreg"){
param <- "lifeExp"
warning("'survreg' is a deprecated argument value")
}else if (param == "canonical"){
param <- "lifeExp"
warning("'canonical' is a deprecated argument value")
}else{
if (!(param %in% c("lifeAcc", "lifeExp"))){
stop(paste(param, "is not a valid parametrization."))
}
}
pfixed <- any(shape > 0)
call <- match.call()
m <- match.call(expand.dots = FALSE)
temp <- c("", "formula", "data", "id", "na.action")
m <- m[match(temp, names(m), nomatch = 0)]
special <- "strata"
Terms <- if (missing(data))
terms(formula, special)
else terms(formula, special, data = data)
m$formula <- Terms
m[[1]] <- as.name("model.frame")
m <- eval(m, parent.frame())
Y <- model.extract(m, "response")
if (!inherits(Y, "Surv"))
stop("Response must be a survival object")
if (missing(id)) id <- 1:nrow(Y)
else id <- model.extract(m, "id")
offset <- attr(Terms, "offset")
tt <- length(offset)
offset <- if (tt == 0)
rep(0, nrow(Y))
else if (tt == 1)
m[[offset]]
else {
ff <- m[[offset[1]]]
for (i in 2:tt) ff <- ff + m[[offset[i]]]
ff
}
attr(Terms, "intercept") <- 1
strats <- attr(Terms, "specials")$strata
dropx <- NULL
if (length(strats)) {
temp <- survival::untangle.specials(Terms, "strata", 1)
dropx <- c(dropx, temp$terms)
if (length(temp$vars) == 1)
strata.keep <- m[[temp$vars]]
else strata.keep <- strata(m[, temp$vars], shortlabel = TRUE)
strats <- as.numeric(strata.keep)
}
if (length(dropx))
newTerms <- Terms[-dropx]
else newTerms <- Terms
X <- model.matrix(newTerms, m)
assign <- lapply(survival::attrassign(X, newTerms)[-1], function(x) x - 1)
X <- X[, -1, drop = FALSE]
ncov <- NCOL(X)
if (ncov){
if (length(dropx)){
covars <- names(m)[-c(1, (dropx + 1))]
}else{
covars <- names(m)[-1]
}
isF <- logical(length(covars))
for (i in 1:length(covars)){
if (length(dropx)){
if (is.logical(m[, -(dropx + 1)][, (i + 1)])){
m[, -(dropx + 1)][, (i + 1)] <-
as.factor(m[, -(dropx + 1)][, (i + 1)])
}
isF[i] <- is.factor(m[, -(dropx + 1)][, (i + 1)])
}else{
if (is.logical(m[, (i + 1)])){
m[, (i + 1)] <- as.factor(m[, (i + 1)])
}
isF[i] <- is.factor(m[, (i + 1)])
}
}
if (ant.fak <- sum(isF)){
levels <- list()
index <- 0
for ( i in 1:length(covars) ){
if (isF[i]){
index <- index + 1
if (length(dropx)){
levels[[i]] <- levels(m[, -(dropx + 1)][, (i + 1)])
}else{
levels[[i]] <- levels(m[, (i + 1)])
}
}else{
levels[[i]] <- NULL
}
}
}else{
levels <- NULL
}
}
nullModel <- ncov == 0
type <- attr(Y, "type")
if (type != "right" && type != "counting")
stop(paste("This model doesn't support \"", type, "\" survival data",
sep = ""))
if (NCOL(Y) == 2){
Y <- cbind(numeric(NROW(Y)), Y)
}
n.events <- sum(Y[, 3] != 0)
if (n.events == 0) stop("No events; no sense in continuing!")
if (missing(init))
init <- NULL
if (is.list(control)){
if (is.null(control$eps)) control$eps <- 1e-8
if (is.null(control$maxiter)) control$maxiter <- 10
if (is.null(control$trace)) control$trace <- FALSE
}else{
stop("control must be a list")
}
fit <- aftreg.fit(X,
Y,
dist,
param,
strats,
offset,
init,
shape,
id,
control,
pfixed)
if (!is.null(fit$overlap)) return(fit$overlap)
if (ncov){
fit$linear.predictors <- offset + X %*% fit$coefficients[1:ncov]
fit$means <- apply(X, 2, mean)
}else{
fit$linear.predictors <- offset
fit$means <- NULL
}
if (!fit$fail){
fit$fail <- NULL
}else{
out <- paste("Singular hessian; suspicious variable No. ",
as.character(fit$fail), ":\n",
names(coefficients)[fit$fail], " = ",
as.character(fit$value),
"\nTry running with fixed shape", sep = "")
stop(out)
}
fit$convergence <- as.logical(fit$conver)
fit$conver <- NULL
if (is.character(fit)) {
fit <- list(fail = fit)
class(fit) <- "mlreg"
}
else if (is.null(fit$fail)){
if (!is.null(fit$coef) && any(is.na(fit$coef))) {
vars <- (1:length(fit$coef))[is.na(fit$coef)]
msg <- paste("X matrix deemed to be singular; variable",
paste(vars, collapse = " "))
if (singular.ok)
warning(msg)
else stop(msg)
}
fit$n <- nrow(Y)
fit$terms <- Terms
fit$assign <- assign
if (FALSE){
if (length(fit$coef) && is.null(fit$wald.test)) {
nabeta <- !is.na(fit$coef)
if (is.null(init))
temp <- fit$coef[nabeta]
else temp <- (fit$coef - init)[nabeta]
}
}
na.action <- attr(m, "na.action")
if (length(na.action))
fit$na.action <- na.action
if (model)
fit$model <- m
if (x) {
fit$x <- X
if (length(strats))
fit$strata <- strata.keep
}
if (y)
fit$y <- Y
}
s.wght <- (Y[, 2] - Y[, 1])
fit$ttr <- sum(s.wght)
if (ncov){
fit$isF <- isF
fit$covars <- covars
fit$w.means <- list()
for (i in 1:length(fit$covars)){
nam <- fit$covars[i]
col.m <- which(nam == names(m))
if (isF[i]){
n.lev <- length(levels[[i]])
fit$w.means[[i]] <- numeric(n.lev)
for (j in 1:n.lev){
who <- m[, col.m] == levels[[i]][j]
fit$w.means[[i]][j] <-
sum( s.wght[who] ) / fit$ttr
}
}else{
fit$w.means[[i]] <- weighted.mean(m[, col.m], s.wght)
}
}
fit$means <- colMeans(X)
}
fit$ttr <- sum(s.wght)
fit$levels <- levels
fit$formula <- formula(Terms)
fit$call <- call
fit$dist <- dist
fit$n.events <- n.events
class(fit) <- c("aftreg", "phreg")
fit$param <- param
if (dist == "gompertz"){
baselineMean <- numeric(fit$n.strata)
for (j in 1:fit$n.strata){
scale <- exp(fit$coef[ncov + 2 * j - 1])
shape <- exp(fit$coef[ncov + 2 * j])
baselineMean[j] <- mean(rgompertz(100000, param = "canonical",
scale = scale, shape = shape))
}
fit$baselineMean <- baselineMean
}else{
fit$baselineMean <- NULL
}
fit$nullModel <- nullModel
fit$pfixed <- pfixed
if (pfixed) fit$shape <- shape
fit
} |
snpgrid2 <-
function(nsnp, x, y, theta){
stopifnot(nargs() == 4, nsnp > 0, length(x) == length(y))
out <- .Fortran("snpgrid", n=as.integer(nsnp), x=as.integer(x), y=as.integer(y), theta=as.double(theta), k = double(1))
return(out[["k"]])
}
snpgrid <-
function(X, theta){
stopifnot(nargs() == 2)
nid <- nrow(X)
nsnp <- ncol(X)
DK <- matrix(0, ncol=nid, nrow=nid)
for (i in 1:(nid-1)){
DK[i,i] <- snpgrid2(nsnp, X[i,], X[i,], theta)
for (j in (i+1):nid){
xy <- snpgrid2(nsnp, X[i,], X[j,], theta)
DK[i,j] <- DK[j,i] <- xy
}
}
DK[nid, nid] <- snpgrid2(nsnp, X[nid,], X[nid,], theta)
return(DK)
} |
if (getRversion() >= "2.15.1")
globalVariables(c("."))
"jagst"
"lc50" |
test_that("registerAppOptions works as expected", {
se <- SummarizedExperiment()
se <- registerAppOptions(se, factor.maxlevels=10, color.maxlevels=20)
expect_identical(getAppOption("factor.maxlevels", se), 10)
expect_identical(getAppOption("color.maxlevels", se), 20)
expect_null(getAppOption("random", se))
expect_identical(getAppOption("random", se, default="A"), "A")
expect_identical(getAllAppOptions(se), list(factor.maxlevels=10, color.maxlevels=20))
se <- registerAppOptions(se, list(factor.maxlevels=100, color.maxlevels=24))
expect_identical(getAppOption("factor.maxlevels", se), 100)
expect_identical(getAppOption("color.maxlevels", se), 24)
})
test_that("registerAppOptions properly appends", {
se <- SummarizedExperiment()
se <- registerAppOptions(se, factor.maxlevels=50)
se <- registerAppOptions(se, color.maxlevels=20)
se <- registerAppOptions(se, other.maxlevels=10)
expect_identical(getAppOption("factor.maxlevels", se), 50)
expect_identical(getAppOption("color.maxlevels", se), 20)
expect_identical(getAppOption("other.maxlevels", se), 10)
se <- registerAppOptions(se, color.maxlevels=10, factor.maxlevels=100)
expect_identical(getAppOption("color.maxlevels", se), 10)
expect_identical(getAppOption("factor.maxlevels", se), 100)
expect_identical(getAppOption("other.maxlevels", se), 10)
se2 <- registerAppOptions(se)
expect_identical(se2, se)
se2 <- registerAppOptions(se, list())
expect_identical(unname(getAllAppOptions(se2)), list())
})
test_that("registerAppOptions works with the globals", {
se <- SummarizedExperiment()
se <- registerAppOptions(se, factor.maxlevels=10, color.maxlevels=20)
.activateAppOptionRegistry(se)
expect_identical(getAppOption("factor.maxlevels"), 10)
expect_identical(getAppOption("color.maxlevels"), 20)
expect_null(getAppOption("random"))
expect_identical(getAppOption("random", default="A"), "A")
expect_identical(getAllAppOptions(), list(factor.maxlevels=10, color.maxlevels=20))
.deactivateAppOptionRegistry()
expect_null(getAppOption("factor.maxlevels"))
expect_null(getAppOption("color.maxlevels"))
expect_identical(unname(getAllAppOptions()), list())
})
test_that("registerAppOptions works with iSEEOptions for back-compatibility's sake", {
expect_null(getAppOption("panel.color"))
expect_warning(iSEEOptions$set(panel.color="A"))
expect_identical(getAppOption("panel.color"), "A")
iSEEOptions$restore()
}) |
tabExpand <- function(x) {
srcref <- attr(x, "srcref")
if (is.null(srcref)) start <- 0L
else start <- srcref[5L] - 1L
.Call(doTabExpand, x, start)
}
Rd2txt_options <- local({
opts <- list(width = 80L,
minIndent = 10L,
extraIndent = 4L,
sectionIndent = 5L,
sectionExtra = 2L,
itemBullet = "* ",
enumFormat = function(n) sprintf("%d. ", n),
showURLs = FALSE,
code_quote = TRUE,
underline_titles = TRUE)
function(...) {
args <- list(...)
if (!length(args))
return(opts)
else {
if (is.list(args[[1L]])) args <- args[[1L]]
result <- opts[names(args)]
opts[names(args)] <<- args
invisible(result)
}
}
})
transformMethod <- function(i, blocks, Rdfile) {
editblock <- function(block, newtext)
list(structure(newtext, Rd_tag = attr(block, "Rd_tag"),
srcref = attr(block, "srcref")))
chars <- NULL
char <- NULL
j <- NULL
findOpen <- function(i) {
j <- i
char <- NULL
while (j < length(blocks)) {
j <- j + 1L
tag <- attr(blocks[[j]], "Rd_tag")
if (tag == "RCODE") {
chars <- strsplit(blocks[[j]], "")[[1]]
parens <- cumsum( (chars == "(") - (chars == ")") )
if (any(parens > 0)) {
char <- which.max(parens > 0)
break
}
}
}
if (is.null(char))
stopRd(block, Rdfile, sprintf("no parenthesis following %s", blocktag))
chars <<- chars
char <<- char
j <<- j
}
findComma <- function(i) {
j <- i
level <- 1L
char <- NULL
while (j < length(blocks)) {
j <- j + 1L
tag <- attr(blocks[[j]], "Rd_tag")
if (tag == "RCODE") {
chars <- strsplit(blocks[[j]], "")[[1]]
parens <- level + cumsum( (chars == "(") - (chars == ")") )
if (any(parens == 1 & chars == ",")) {
char <- which.max(parens == 1 & chars == ",")
break
}
if (any(parens == 0))
break
level <- parens[length(parens)]
}
}
if (is.null(char))
stopRd(block, Rdfile, sprintf("no comma in argument list following %s", blocktag))
chars <<- chars
char <<- char
j <<- j
}
findClose <- function(i) {
j <- i
level <- 1L
char <- NULL
while (j < length(blocks)) {
j <- j + 1L
tag <- attr(blocks[[j]], "Rd_tag")
if (tag == "RCODE") {
chars <- strsplit(blocks[[j]], "")[[1]]
parens <- level + cumsum( (chars == "(") - (chars == ")") )
if (any(parens == 0)) {
char <- which(parens == 0)[1]
break
}
level <- parens[length(parens)]
}
}
if (is.null(char))
stopRd(block, Rdfile, sprintf("no closing parenthesis following %s", blocktag))
chars <<- chars
char <<- char
j <<- j
}
rewriteBlocks <- function()
c(blocks[seq_len(j-1L)],
editblock(blocks[[j]],
paste(chars[seq_len(char)], collapse="")),
if (char < length(chars))
editblock(blocks[[j]],
paste(chars[-seq_len(char)], collapse="")),
if (j < length(blocks)) blocks[-seq_len(j)])
deleteBlanks <- function() {
while (char < length(chars)) {
if (chars[char + 1] == " ") {
char <- char + 1
chars[char] <- ""
} else
break
}
char <<- char
chars <<- chars
}
block <- blocks[[i]]
blocktag <- attr(block, "Rd_tag")
srcref <- attr(block, "srcref")
class <- block[[2L]]
generic <- as.character(block[[1L]])
default <- as.character(class) == "default"
if(generic %in% c("[", "[[", "$")) {
findOpen(i)
chars[char] <- ""
blocks <- c(blocks[seq_len(j-1L)],
editblock(blocks[[j]],
paste(chars[seq_len(char)], collapse="")),
if (char < length(chars))
editblock(blocks[[j]],
paste(chars[-seq_len(char)], collapse="")),
if (j < length(blocks)) blocks[-seq_len(j)])
findComma(j)
chars[char] <- generic
deleteBlanks()
blocks <- rewriteBlocks()
findClose(j)
chars[char] <- switch(generic,
"[" = "]",
"[[" = "]]",
"$" = "")
blocks[j] <- editblock(blocks[[j]],
paste(chars, collapse=""))
methodtype <- if (grepl("<-", blocks[[j]])) "replacement " else ""
} else if(grepl(sprintf("^%s$",
paste(c("\\+", "\\-", "\\*",
"\\/", "\\^", "<=?",
">=?", "!=?", "==",
"\\&", "\\|", "!",
"\\%[[:alnum:][:punct:]]*\\%"),
collapse = "|")),
generic)) {
findOpen(i)
if (generic != "!") {
chars[char] <- ""
blocks <- rewriteBlocks()
findComma(j)
chars[char] <- paste0(" ", generic, " ")
deleteBlanks()
blocks <- rewriteBlocks()
} else {
chars[char] <- "!"
blocks <- rewriteBlocks()
}
findClose(j)
chars[char] <- ""
blocks[j] <- editblock(blocks[[j]],
paste(chars, collapse=""))
methodtype <- ""
} else {
findOpen(i)
chars[char] <- paste0(generic, "(")
blocks <- rewriteBlocks()
findClose(j)
methodtype <- if (grepl("<-", blocks[[j]])) "replacement " else ""
}
if (blocktag == "\\S4method") {
blocks <- if(nchar(class) > 50L) {
cl <- paste0("'", as.character(class), "'")
if(nchar(cl) > 70L) {
cl <- strsplit(cl, ",")[[1L]]
ncl <- length(cl)
cl[-ncl] <- paste0(cl[-ncl], ",")
cl[-1L] <- paste0(" ", cl[-1L])
}
cl <- paste("
c( blocks[seq_len(i-1L)],
list(structure(paste0("
Rd_tag="RCODE", srcref=srcref)),
list(structure(cl, Rd_tag="TEXT", srcref=srcref)),
list(structure("\n", Rd_tag="RCODE", srcref=srcref)),
blocks[-seq_len(i)] )
} else
c( blocks[seq_len(i-1L)],
list(structure(paste0("
Rd_tag="RCODE", srcref=srcref)),
class,
list(structure("'\n", Rd_tag="RCODE", srcref=srcref)),
blocks[-seq_len(i)] )
} else if (default)
blocks <- c( blocks[seq_len(i-1)],
list(structure(paste0("
Rd_tag="RCODE", srcref=srcref)),
blocks[-seq_len(i)] )
else
blocks <- c( blocks[seq_len(i-1)],
list(structure(paste0("
Rd_tag="RCODE", srcref=srcref)),
class,
list(structure("'\n", Rd_tag="RCODE", srcref=srcref)),
blocks[-seq_len(i)] )
blocks
}
Rd2txt <-
function(Rd, out="", package = "", defines=.Platform$OS.type,
stages = "render", outputEncoding = "",
fragment = FALSE, options, ...)
{
buffer <- character()
linestart <- TRUE
indent <- 0L
wrapping <- TRUE
keepFirstIndent <- FALSE
dropBlank <- FALSE
haveBlanks <- 0L
enumItem <- 0L
inEqn <- FALSE
sectionLevel <- 0
saveOpts <- Rd2txt_options()
on.exit(Rd2txt_options(saveOpts))
if (!missing(options)) Rd2txt_options(options)
WIDTH <- 0.9 * Rd2txt_options()$width
HDR_WIDTH <- WIDTH - 2L
startCapture <- function() {
save <- list(buffer=buffer, linestart=linestart, indent=indent,
wrapping=wrapping, keepFirstIndent=keepFirstIndent,
dropBlank=dropBlank, haveBlanks=haveBlanks,
enumItem=enumItem, inEqn=inEqn)
buffer <<- character()
linestart <<- TRUE
indent <<- 0L
wrapping <<- TRUE
keepFirstIndent <<- FALSE
dropBlank <<- FALSE
haveBlanks <<- 0L
enumItem <<- 0L
inEqn <<- FALSE
save
}
endCapture <- function(saved) {
result <- buffer
buffer <<- saved$buffer
linestart <<- saved$linestart
indent <<- saved$indent
wrapping <<- saved$wrapping
keepFirstIndent <<- saved$keepFirstIndent
dropBlank <<- saved$dropBlank
haveBlanks <<- saved$haveBlanks
enumItem <<- saved$enumItem
inEqn <<- saved$inEqn
result
}
WriteLines <-
if(outputEncoding == "UTF-8" ||
(outputEncoding == "" && l10n_info()[["UTF-8"]])) {
function(x, con, outputEncoding, ...)
writeLines(x, con, useBytes = TRUE, ...)
} else {
function(x, con, outputEncoding, ...) {
x <- iconv(x, "UTF-8", outputEncoding, sub="byte", mark=FALSE)
writeLines(x, con, useBytes = TRUE, ...)
}
}
frmt <- function(x, justify="left", width = 0L) {
justify <- match.arg(justify, c("left", "right", "centre", "none"))
w <- sum(nchar(x, "width"))
if(w < width && justify != "none") {
excess <- width - w
left <- right <- 0L
if(justify == "left") right <- excess
else if(justify == "right") left <- excess
else if(justify == "centre") {
left <- excess %/% 2
right <- excess-left
}
paste(c(rep_len(" ", left), x, rep_len(" ", right)), collapse = "")
} else x
}
wrap <- function(doWrap = TRUE)
if (doWrap != wrapping) { flushBuffer(); wrapping <<- doWrap }
putw <- function(...) { wrap(TRUE); put(...) }
putf <- function(...) { wrap(FALSE); put(...) }
put <- function(...) {
txt <- paste0(..., collapse="")
trail <- grepl("\n$", txt)
txt <- strsplit(txt, "\n", fixed = TRUE)[[1L]]
if (dropBlank) {
while(length(txt) && grepl("^[[:space:]]*$", txt[1L]))
txt <- txt[-1L]
if (length(txt)) dropBlank <<- FALSE
}
if(!length(txt)) return()
haveBlanks <<- 0
if (linestart) buffer <<- c(buffer, txt)
else if (length(buffer)) {
buffer[length(buffer)] <<-
paste0(buffer[length(buffer)], txt[1L])
buffer <<- c(buffer, txt[-1L])
}
else buffer <<- txt
linestart <<- trail
}
flushBuffer <- function() {
if (!length(buffer)) return()
if (wrapping) {
if (keepFirstIndent) {
first <- nchar(psub1("[^ ].*", "", buffer[1L]))
keepFirstIndent <<- FALSE
} else
first <- indent
buffer <<- c(buffer, "")
blankLines <- grep("^[[:space:]]*$", buffer)
result <- character()
start <- 1L
for (i in seq_along(blankLines)) {
if (blankLines[i] > start) {
result <- c(result,
strwrap(paste(buffer[start:(blankLines[i]-1L)],
collapse = " "),
WIDTH, indent = first, exdent = indent))
first <- indent
}
result <- c(result, "")
start <- blankLines[i]+1L
}
buffer <<- result[-length(result)]
empty <- !nzchar(buffer)
drop <- empty & c(FALSE, empty[-length(empty)])
buffer <<- buffer[!drop]
} else {
if (keepFirstIndent) {
if (length(buffer) > 1L)
buffer[-1L] <<- paste0(strrep(" ", indent), buffer[-1L])
keepFirstIndent <- FALSE
} else
buffer <<- paste0(strrep(" ", indent), buffer)
}
if (length(buffer)) WriteLines(buffer, con, outputEncoding)
buffer <<- character()
linestart <<- TRUE
}
encoding <- "unknown"
li <- l10n_info()
use_fancy_quotes <-
(.Platform$OS.type == "windows" &&
((li$codepage >= 1250 && li$codepage <= 1258) || li$codepage == 874)) ||
li[["UTF-8"]]
if(!identical(getOption("useFancyQuotes"), FALSE) &&
use_fancy_quotes) {
LSQM <- intToUtf8("0x2018")
RSQM <- intToUtf8("0x2019")
LDQM <- intToUtf8("0x201c")
RDQM <- intToUtf8("0x201d")
} else {
LSQM <- RSQM <- "'"
LDQM <- RDQM <- '"'
}
trim <- function(x) {
x <- psub1("^\\s*", "", x)
psub1("\\s*$", "", x)
}
txt_header <- function(header) {
opts <- Rd2txt_options()
header <- paste(strwrap(header, WIDTH), collapse="\n")
if (opts$underline_titles) {
letters <- strsplit(header, "", fixed = TRUE)[[1L]]
isaln <- grep("[[:alnum:]]", letters)
letters[isaln] <- paste0("_\b", letters[isaln])
paste(letters, collapse = "")
} else header
}
unescape <- function(x) {
x <- psub("(---|--)", "-", x)
x
}
writeCode <- function(x) {
txt <- as.character(x)
if(inEqn) txt <- txt_eqn(txt)
txt <- fsub('"\\{"', '"{"', txt)
txt <- fsub("\\dots", "...", txt)
put(txt)
}
blankLine <- function(n = 1L) {
while (length(buffer) &&
grepl("^[[:blank:]]*$", buffer[length(buffer)]))
buffer <<- buffer[-length(buffer)]
flushBuffer()
if (n > haveBlanks) {
buffer <<- rep_len("", n - haveBlanks)
flushBuffer()
haveBlanks <<- n
}
dropBlank <<- TRUE
}
txt_eqn <- function(x) {
x <- psub("\\\\(Alpha|Beta|Gamma|Delta|Epsilon|Zeta|Eta|Theta|Iota|Kappa|Lambda|Mu|Nu|Xi|Omicron|Pi|Rho|Sigma|Tau|Upsilon|Phi|Chi|Psi|Omega|alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|sum|prod|sqrt)", "\\1", x)
x <- psub("\\\\(dots|ldots)", "...", x)
x <- fsub("\\le", "<=", x)
x <- fsub("\\ge", ">=", x)
x <- fsub("\\infty", "Inf", x)
x <- psub("\\\\(bold|strong|emph|var)\\{([^}]*)\\}", "\\2", x)
x <- psub("\\\\(code|samp)\\{([^}]*)\\}", "'\\2'", x)
x
}
writeDR <- function(block, tag) {
if (length(block) > 1L) {
putf('
writeCodeBlock(block, tag)
blankLine(0L)
putf('
} else {
putf('
writeCodeBlock(block, tag)
blankLine(0L)
}
}
writeQ <- function(block, tag, quote=tag)
{
if (use_fancy_quotes) {
if (quote == "\\sQuote") {
put(LSQM); writeContent(block, tag); put(RSQM)
} else {
put(LDQM); writeContent(block, tag); put(RDQM)
}
} else {
if (quote == "\\sQuote") {
put("'"); writeContent(block, tag); put("'")
} else {
put("\""); writeContent(block,tag); put("\"")
}
}
}
writeBlock <- function(block, tag, blocktag) {
switch(tag,
UNKNOWN =,
VERB =,
RCODE = writeCode(tabExpand(block)),
TEXT = if(blocktag == "\\command") putw(block) else putw(unescape(tabExpand(block))),
USERMACRO =,
"\\newcommand" =,
"\\renewcommand" =,
COMMENT = {},
LIST = writeContent(block, tag),
"\\describe" = {
blankLine(0L)
writeContent(block, tag)
blankLine()
},
"\\itemize"=,
"\\enumerate"= {
blankLine(0L)
enumItem0 <- enumItem
enumItem <<- 0L
indent0 <- indent
opts <- Rd2txt_options()
indent <<- max(opts$minIndent,
indent + opts$extraIndent)
dropBlank <<- TRUE
writeContent(block, tag)
blankLine()
indent <<- indent0
enumItem <<- enumItem0
},
"\\code"=,
"\\command"=,
"\\env"=,
"\\file"=,
"\\kbd"=,
"\\option"=,
"\\pkg"=,
"\\samp" = {
opts <- Rd2txt_options()
if(opts$code_quote)
writeQ(block, tag, quote="\\sQuote")
else writeContent(block,tag)
},
"\\email" = {
put("<email: ",
trimws(gsub("\n", "",
paste(as.character(block),
collapse=""))),
">")
},
"\\url" = {
put("<URL: ",
trimws(gsub("\n", "",
paste(as.character(block),
collapse=""))),
">")
},
"\\href" = {
opts <- Rd2txt_options()
writeContent(block[[2L]], tag)
if (opts$showURLs)
put(" (URL: ",
trimws(gsub("\n", "",
paste(as.character(block[[1L]]),
collapse=""))),
")")
},
"\\Sexpr"= put(as.character.Rd(block, deparse=TRUE)),
"\\acronym" =,
"\\cite"=,
"\\dfn"= ,
"\\special" = ,
"\\var" = writeContent(block, tag),
"\\bold"=,
"\\strong"= {
put("*")
writeContent(block, tag)
put("*")
},
"\\emph"= {
put("_")
writeContent(block, tag)
put("_")
},
"\\sQuote" =,
"\\dQuote"= writeQ(block, tag) ,
"\\preformatted"= {
putf("\n")
writeCodeBlock(block, tag)
},
"\\verb"= put(block),
"\\linkS4class" =,
"\\link" = writeContent(block, tag),
"\\cr" = {
flushBuffer()
dropBlank <<- TRUE
},
"\\dots" =,
"\\ldots" = put("..."),
"\\R" = put("R"),
"\\enc" = {
txt <- as.character(block[[1L]])
test <- iconv(txt, "UTF-8", outputEncoding, mark = FALSE)
txt <- if(!is.na(test)) txt else as.character(block[[2L]])
put(txt)
} ,
"\\eqn" = {
block <- block[[length(block)]]
inEqn0 <- inEqn
inEqn <<- TRUE
writeContent(block, tag)
inEqn <<- inEqn0
},
"\\deqn" = {
blankLine()
block <- block[[length(block)]]
save <- startCapture()
inEqn <<- TRUE
writeContent(block, tag)
eqn <- endCapture(save)
eqn <- frmt(eqn, justify="centre", width=WIDTH-indent)
putf(paste(eqn, collapse="\n"))
blankLine()
},
"\\figure" = {
blankLine()
save <- startCapture()
writeContent(block[[length(block)]], tag)
alt <- endCapture(save)
if (length(alt)) {
alt <- frmt(alt, justify = "centre",
width = WIDTH - indent)
putf(paste(alt, collapse = "\n"))
blankLine()
}
},
"\\tabular" = writeTabular(block),
"\\subsection" = writeSection(block, tag),
"\\if"=,
"\\ifelse" =
if (testRdConditional("text", block, Rdfile))
writeContent(block[[2L]], tag)
else if (tag == "\\ifelse")
writeContent(block[[3L]], tag),
"\\out" = for (i in seq_along(block))
put(block[[i]]),
stopRd(block, Rdfile, "Tag ", tag, " not recognized")
)
}
writeTabular <- function(table) {
formats <- table[[1L]]
content <- table[[2L]]
if (length(formats) != 1L || RdTags(formats) != "TEXT")
stopRd(table, Rdfile, "\\tabular format must be simple text")
formats <- strsplit(formats[[1L]], "", fixed = TRUE)[[1L]]
tags <- RdTags(content)
entries <- list()
row <- 1L
col <- 1L
save <- startCapture()
dropBlank <<- TRUE
newEntry <- function() {
entries <<- c(entries, list(list(text=trim(endCapture(save)),
row=row, col=col)))
save <<- startCapture()
dropBlank <<- TRUE
}
for (i in seq_along(tags)) {
switch(tags[i],
"\\tab" = {
newEntry()
col <- col + 1
if (col > length(formats))
stopRd(content[[i]], Rdfile,
sprintf("too many columns for format '%s'",
table[[1L]]))
},
"\\cr" = {
newEntry()
row <- row + 1L
col <- 1L
},
writeBlock(content[[i]], tags[i], "\\tabular")
)
}
newEntry()
endCapture(save)
entries <- with(entries[[length(entries)]],
{
if (!length(text) && col == 1L)
entries[-length(entries)]
else
entries
})
rows <- entries[[length(entries)]]$row
cols <- max(sapply(entries, function(e) e$col))
widths <- rep_len(0L, cols)
lines <- rep_len(1L, rows)
for (i in seq_along(entries)) {
e <- entries[[i]]
while(length(e$text) && !nzchar(e$text[length(e$text)])) {
e$text <- e$text[-length(e$text)]
entries[[i]] <- e
}
if (any(nzchar(e$text)))
widths[e$col] <- max(widths[e$col], max(nchar(e$text, "w")))
lines[e$row] <- max(lines[e$row], length(e$text))
}
result <- matrix("", sum(lines), cols)
for (i in seq_len(cols))
result[, i] <- strrep(" ", widths[i])
firstline <- c(1L, 1L+cumsum(lines))
for (i in seq_along(entries)) {
e <- entries[[i]]
if(!length(e$text)) next
text <- frmt(e$text, justify=formats[e$col], width=widths[e$col])
for (j in seq_along(text))
result[firstline[e$row] + j - 1L, e$col] <- text[j]
}
blankLine()
indent0 <- indent
indent <<- indent + 1L
for (i in seq_len(nrow(result))) {
putf(paste0(" ", result[i,], " ", collapse=""))
putf("\n")
}
blankLine()
indent <<- indent0
}
writeCodeBlock <- function(blocks, blocktag)
{
tags <- RdTags(blocks)
i <- 0
while (i < length(tags)) {
i <- i + 1
block <- blocks[[i]]
tag <- tags[i]
switch(tag,
"\\method" =,
"\\S3method" =,
"\\S4method" = {
blocks <- transformMethod(i, blocks, Rdfile)
tags <- RdTags(blocks)
i <- i - 1
},
UNKNOWN =,
VERB =,
RCODE =,
TEXT = writeCode(tabExpand(block)),
"\\donttest" =,
"\\special" =,
"\\var" = writeCodeBlock(block, tag),
"\\dots" =,
"\\ldots" = put("..."),
"\\dontrun"= writeDR(block, tag),
USERMACRO =,
"\\newcommand" =,
"\\renewcommand" =,
COMMENT =,
"\\dontshow" =,
"\\testonly" = {},
stopRd(block, Rdfile, "Tag ", tag,
" not expected in code block")
)
}
}
writeContent <- function(blocks, blocktag) {
itemskip <- FALSE
tags <- RdTags(blocks)
for (i in seq_along(tags)) {
tag <- tags[i]
block <- blocks[[i]]
switch(tag,
"\\item" = {
switch(blocktag,
"\\describe"= {
blankLine()
save <- startCapture()
dropBlank <<- TRUE
writeContent(block[[1L]], tag)
DLlab <- endCapture(save)
indent0 <- indent
opts <- Rd2txt_options()
indent <<- max(opts$minIndent,
indent + opts$extraIndent)
keepFirstIndent <<- TRUE
putw(strrep(" ", indent0),
frmt(paste0(DLlab),
justify="left", width=indent),
" ")
writeContent(block[[2L]], tag)
blankLine(0L)
indent <<- indent0
},
"\\value"=,
"\\arguments"= {
blankLine()
save <- startCapture()
dropBlank <<- TRUE
writeContent(block[[1L]], tag)
DLlab <- endCapture(save)
indent0 <- indent
opts <- Rd2txt_options()
indent <<- max(opts$minIndent, indent + opts$extraIndent)
keepFirstIndent <<- TRUE
putw(frmt(paste0(DLlab, ": "),
justify="right", width=indent))
writeContent(block[[2L]], tag)
blankLine(0L)
indent <<- indent0
},
"\\itemize" =,
"\\enumerate" = {
blankLine()
keepFirstIndent <<- TRUE
opts <- Rd2txt_options()
if (blocktag == "\\itemize")
label <- opts$itemBullet
else {
enumItem <<- enumItem + 1L
label <- opts$enumFormat(enumItem)
}
putw(frmt(label, justify="right",
width=indent))
})
itemskip <- TRUE
},
{
if (itemskip) {
itemskip <- FALSE
if (tag == "TEXT") {
txt <- psub("^ ", "", as.character(tabExpand(block)))
put(txt)
} else writeBlock(block, tag, blocktag)
} else writeBlock(block, tag, blocktag)
})
}
}
writeSection <- function(section, tag) {
if (tag %in% c("\\alias", "\\concept", "\\encoding", "\\keyword"))
return()
save <- c(indent, sectionLevel, keepFirstIndent, dropBlank, wrapping)
blankLine(min(sectionLevel, 1L))
titlePrefix <- strrep(" ", sectionLevel)
opts <- Rd2txt_options()
indent <<- opts$sectionIndent + opts$sectionExtra*sectionLevel
sectionLevel <<- sectionLevel + 1
keepFirstIndent <<- TRUE
if (tag == "\\section" || tag == "\\subsection") {
title <- .Rd_format_title(.Rd_get_text(section[[1L]]))
putf(titlePrefix, txt_header(title), ":")
blankLine()
dropBlank <<- TRUE
wrapping <<- TRUE
keepFirstIndent <<- FALSE
writeContent(section[[2L]], tag)
} else if (tag %in% c("\\usage", "\\examples")) {
putf(txt_header(sectionTitles[tag]), ":")
blankLine()
dropBlank <<- TRUE
wrapping <<- FALSE
keepFirstIndent <<- FALSE
writeCodeBlock(section, tag)
} else {
putf(txt_header(sectionTitles[tag]), ":")
blankLine()
dropBlank <<- TRUE
wrapping <<- TRUE
keepFirstIndent <<- FALSE
writeContent(section, tag)
}
blankLine()
indent <<- save[1L]
sectionLevel <<- save[2L]
keepFirstIndent <<- save[3L]
dropBlank <<- save[4L]
wrapping <<- save[5L]
}
if (is.character(out)) {
if(out == "") {
con <- stdout()
} else {
con <- file(out, "wt")
on.exit(close(con), add=TRUE)
}
} else {
con <- out
out <- summary(con)$description
}
Rd <- prepare_Rd(Rd, defines=defines, stages=stages, fragment=fragment, ...)
Rdfile <- attr(Rd, "Rdfile")
sections <- RdTags(Rd)
if (fragment) {
if (sections[1L] %in% names(sectionOrder))
for (i in seq_along(sections))
writeSection(Rd[[i]], sections[i])
else
for (i in seq_along(sections))
writeBlock(Rd[[i]], sections[i], "")
} else {
title <- .Rd_format_title(.Rd_get_title(Rd))
name <- trim(Rd[[2L]][[1L]])
if(nzchar(package)) {
left <- name
mid <- if(nzchar(package)) paste0("package:", package) else ""
right <- "R Documentation"
if(encoding != "unknown")
right <- paste0(right, "(", encoding, ")")
pad <- max(HDR_WIDTH - nchar(left, "w") - nchar(mid, "w") - nchar(right, "w"), 0)
pad0 <- pad %/% 2L
pad1 <- strrep(" ", pad0)
pad2 <- strrep(" ", pad - pad0)
putf(paste0(left, pad1, mid, pad2, right, "\n\n"))
}
putf(txt_header(title))
blankLine()
for (i in seq_along(sections)[-(1:2)])
writeSection(Rd[[i]], sections[i])
}
blankLine(0L)
invisible(out)
} |
test_that("Error when league is not supplied", {
expect_error(geom_baseball())
expect_error(geom_basketball())
expect_error(geom_football())
expect_error(geom_hockey())
expect_error(geom_soccer())
}) |
ffmatch <- function(x, table, nomatch = NA_integer_, incomparables = NULL, trace=FALSE, ...){
stopifnot(inherits(x, "ff_vector") & inherits(table, "ff_vector"))
nomatch <- as.integer(nomatch)
xchunk <- chunk(x, ...)
tablechunk <- chunk(table, ...)
if(trace) {
message(sprintf("%s, x has %s chunks, table has %s chunks", Sys.time(), length(xchunk), length(tablechunk)))
}
res <- ff(nomatch, length=length(x), vmode="integer")
for (i in xchunk){
Log$chunk(i)
xi <- x[i]
unmatched <- TRUE
if (trace){
message(sprintf("%s, working on x chunk %s:%s", Sys.time(), min(i), max(i)))
}
m <- rep(NA_integer_, sum(i))
for (j in tablechunk){
Log$chunk(j)
if(trace) {
message(sprintf("%s, working on table chunk %s:%s", Sys.time(), min(j), max(j)))
}
m[unmatched] <- fmatch(x=xi[unmatched], table=table[j], incomparables=incomparables) + min(j) - 1L
unmatched <- is.na(m)
if (!any(unmatched)) break
}
m[unmatched] <- nomatch
res[i] <- m
}
res
}
ffdfmatch <- function(x, table, nomatch = NA_integer_, incomparables = NULL, trace=FALSE, ...){
stopifnot(inherits(x, "ffdf") & inherits(table, "ffdf"))
nomatch <- as.integer(nomatch)
xchunk <- chunk(x, ...)
tablechunk <- chunk(table, ...)
if(trace) {
message(sprintf("%s, x has %s chunks, table has %s chunks", Sys.time(), length(xchunk), length(tablechunk)))
}
res <- ff(nomatch, length=nrow(x), vmode="integer")
for (i in xchunk){
Log$chunk(i)
xi <- x[i, , drop=FALSE]
unmatched <- TRUE
if (trace){
message(sprintf("%s, working on x chunk %s:%s", Sys.time(), min(i), max(i)))
}
m <- rep(NA_integer_, sum(i))
for (j in tablechunk){
if(trace) {
message(sprintf("%s, working on table chunk %s:%s", Sys.time(), min(j), max(j)))
}
m[unmatched] <- fmatch(x=do.call(paste, xi[unmatched, , drop=FALSE]), table=do.call(paste, table[j, , drop=FALSE]), incomparables=incomparables) + min(j) - 1L
unmatched <- is.na(m)
if (!any(unmatched)) break
}
m[unmatched] <- nomatch
res[i] <- m
}
res
}
in.default <- get(x="%in%")
"%in%" <- function(x, table){
if(inherits(x, "ff_vector")){
ffmatch(x=x, table=as.ff(table), nomatch = 0L) > 0L
} else if(inherits(x, "ffdf") && inherits(table, "ffdf")){
ffdfmatch(x=x, table=as.ffdf(table), nomatch = 0L) > 0L
} else{
in.default(x=x, table=table)
}
} |
setGeneric('p', function(x) standardGeneric('p'), package="gaston")
setMethod('p', signature = 'bed.matrix', def = function(x) x@p)
setGeneric('p<-', function(x,value) standardGeneric('p<-'), package="gaston")
setReplaceMethod('p', 'bed.matrix', function(x,value) {
if(length(value) != ncol(x)) stop("dimensions mismatch")
x@p <- value;
x} )
setGeneric('mu', function(x) standardGeneric('mu'), package="gaston")
setMethod('mu', signature = 'bed.matrix', def = function(x) x@mu)
setGeneric('mu<-', function(x,value) standardGeneric('mu<-'), package="gaston")
setReplaceMethod('mu', 'bed.matrix', function(x,value) {
if(length(value) != ncol(x)) stop("dimensions mismatch")
x@mu <- value;
x} )
setGeneric('sigma', function(x) standardGeneric('sigma'), package="gaston")
setMethod('sigma', signature = 'bed.matrix', def = function(x) x@sigma)
setGeneric('sigma<-', function(x,value) standardGeneric('sigma<-'), package="gaston")
setReplaceMethod('sigma', 'bed.matrix', function(x,value) {
if(length(sigma) != ncol(x)) stop("dimensions mismatch")
x@sigma <- value;
x} )
setGeneric('standardize', function(x) standardGeneric('standardize'), package="gaston")
setMethod('standardize', signature = 'bed.matrix',
def = function(x) if(x@standardize_p) "p" else if(x@standardize_mu_sigma) "mu_sigma" else "none"
)
setGeneric('standardize<-', function(x,value) standardGeneric('standardize<-'), package="gaston")
setReplaceMethod('standardize', 'bed.matrix', function(x,value=c("p","mu_sigma","none")) {
switch(match.arg(value),
p = { if(length(x@p) != ncol(x))
stop("x@p must be defined and have the appropriate length");
x@standardize_p <- TRUE; x@standardize_mu_sigma <- FALSE;
} ,
mu_sigma = { if(length(x@mu) != ncol(x) | length(x@sigma) != ncol(x))
stop("x@mu and x@sigma must be defined and have the appropriate length");
x@standardize_p <- FALSE; x@standardize_mu_sigma <- TRUE;
} ,
none = {x@standardize_p <- FALSE; x@standardize_mu_sigma <- FALSE;}
);
x } ) |
NULL
setMethod(
f = "plot_rank",
signature = signature(object = "matrix"),
definition = function(object, log = NULL, facet = FALSE) {
object <- object / rowSums(object)
data <- prepare_rank(object)
log_x <- ggplot2::scale_x_continuous(name = "Rank")
log_y <- ggplot2::scale_y_continuous(name = "Frequency")
if (!is.null(log)) {
if (log == "x" || log == "xy" || log == "yx")
log_x <- ggplot2::scale_x_log10(name = "Rank")
if (log == "y" || log == "xy" || log == "yx")
log_y <- ggplot2::scale_y_log10(name = "Frequency")
}
if (facet) {
facet <- ggplot2::facet_wrap(
facets = ggplot2::vars(.data$row),
ncol = nrow(object)
)
aes_plot <- ggplot2::aes(x = .data$x, y = .data$y)
} else {
facet <- NULL
aes_plot <- ggplot2::aes(x = .data$x, y = .data$y, colour = .data$row)
}
ggplot2::ggplot(data = data, mapping = aes_plot) +
ggplot2::geom_point() +
ggplot2::geom_line() +
log_x + log_y + facet
}
)
prepare_rank <- function(object) {
rk <- apply(
X = object,
MARGIN = 1,
FUN = function(x) rank(-x)
)
data <- arkhe::as_long(object, factor = TRUE)
data$x <- as.vector(t(rk))
data$y <- data$value
data <- data[data$value > 0, ]
return(data)
} |
"geoRdefunct" <-
function()
{
cat("\n")
cat("The following functions are no longer used in geoR:")
cat("---------------------------------------------------")
cat("\nolsfit: use variofit() instead")
cat("\nwlsfit: use variofit() instead")
cat("\nlikfit.old: use likfit() instead")
cat("\n")
}
"olsfit" <- function(...)
stop("this function is now obsolete.\nuse variofit() instead.")
"wlsfit" <- function(...)
stop("this function is now obsolete.\nuse variofit() instead.")
"distdiag" <-
function(coords)
{
coords <- as.matrix(coords)
dimc <- dim(coords)
if(dimc[2] == 1 & dimc[1] == 2)
return(0)
else{
if(dimc[2] != 2)
stop("coords must have two columns")
nc <- dimc[1]
.C("distdiag",
as.double(coords[,1]),
as.double(coords[,2]),
as.integer(nc),
out = as.double(rep(0, (nc * (nc+1)/2))),
PACKAGE = "geoR")$out
}
} |
`dprime.ABX` <-function(Hits, FA, zdiff, Pc.unb,
method = "diff") {
Call <- match.call()
if (pmatch("Hits", names(Call), 0) > 0) {
if (pmatch("FA", names(Call), 0) > 0) {
zdiff <- qnorm(Hits) - qnorm(FA)
Pc.unb <- pnorm(zdiff/2)
} else {
zdiff <- qnorm(Hits) - qnorm(1-Hits)
Pc.unb <- pnorm(zdiff/2)
} } else {
if (pmatch("zdiff", names(Call), 0) > 0)
{ Pc.unb <- pnorm(zdiff/2) }
}
if (Pc.unb < 0.5) stop("Only valid for Pc.unb > 0.5")
root2 <- sqrt(2)
if (method == "diff") {
root6 <- sqrt(6)
est.dp <- function(dp) {
Pc.unb - pnorm(dp/root2)*pnorm(dp/root6) -
pnorm(-dp/root2)*pnorm(-dp/root6)
}
dp.res <- uniroot(est.dp, interval=c(0,10))
dprime <- dp.res$root
} else
{
if (method == "IO") {
est.dp <- function(dp) {
Pc.unb - pnorm(dp/root2)*pnorm(dp/2) -
pnorm(-dp/root2)*pnorm(-dp/2)
}
dp.res <- uniroot(est.dp, interval=c(0,10))
dprime <- dp.res$root
} else
{stop("method not defined; must be either diff or IO") } }
dprime
} |
perm.ds.grp <- function(df, scan, ctrlf = NULL, method = "sri", perm, progress = TRUE) {
test <- check.df(df)
if (test == "df ok") {
result <- perm.dataStream.group(df, scan = scan, control_factor = ctrlf, method = method, perm = perm, progress = progress)
attr(result, "ANT") <- "ANT data stream group sampling single matrix"
attr(result, "scan") <- scan
attr(result, "ctrlf") <- ctrlf
attr(result, "method") <- method
return(result)
}
if (test == "df list ok") {
result <- lapply(df, perm.dataStream.group, scan = scan, control_factor = ctrlf, method = method, perm = perm, progress = progress)
attr(result, "ANT") <- "ANT data stream group sampling multiple matrices"
attr(result, "scan") <- scan
attr(result, "ctrlf") <- ctrlf
attr(result, "method") <- method
return(result)
}
} |
`summary.isomap` <-
function (object, axes=4, ...)
{
axes <- min(axes, ncol(object$points))
out <- list()
out$call <- object$call
out$points <- object$points[,1:axes]
out$net <- object$net
n <- nrow(object$points)
out$ndis <- n * (n-1) / 2
out$nnet <- nrow(object$net)
class(out) <- "summary.isomap"
out
} |
mskall<-function(cvstr="unstructured",Dep,Id,Time,m,n,data)
{
InD<-Dep
dat1<-data
dat2<-dat1[,-c(which(colnames(dat1)==c(Id)),which(colnames(dat1)==c(InD)),which(colnames(dat1)==c(Time)))][c(m:n)]
dat1<-data.frame(id=dat1[,which(colnames(dat1)==c(Id))],t=dat1[,which(colnames(dat1)==c(Time))]
,y=dat1[,which(colnames(dat1)==c(InD))],dat2)
dat1$y[is.na(dat1$y)]<-mean(dat1$y,na.rm=TRUE)
dat1<-as.data.frame(dat1)
id1<-dat1$id
id2<-dat1$id[1]
tm<-dat1$t[dat1$id==dat1$id[1]]
id3<-length(id1[id1==id2])
f<-unique(dat1$id)
if(is.null(cvstr)==T){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
sig1<-cov(ustr)
}else if(cvstr=="unstructured"){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
sig1<-cov(ustr)
}else if(cvstr=="compound"){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
vr<-sum(unlist(lapply(as.data.frame(ustr),function(x){var(x)}))*(length(f)-1))
sig<-vr/((nrow(ustr)-1)*ncol(ustr))
ro<-cor(ustr[,1],ustr[,2])
sig1<-(ro*matrix(1,nrow=id3,ncol=id3)+(1-ro)*diag(1,nrow=id3,ncol=id3))*sig
}else if(cvstr=="AR1"){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
vr<-sum(unlist(lapply(as.data.frame(ustr),function(x){var(x)}))*(length(f)-1))
sig<-vr/((nrow(ustr)-1)*ncol(ustr))
ro<-cor(ustr[,1],ustr[,2])
sig1<-matrix(nrow=id3,ncol=id3)
for(i in 1:id3){
for(j in 1:id3 ){
if(i!=j){
sig1[i,j]=sig*(ro^(max(i,j)-min(i,j)))}
else{sig1[i,j]=sig}
}}
}else if(cvstr=="ToE"){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
vr<-sum(unlist(lapply(as.data.frame(ustr),function(x){var(x)}))*(length(f)-1))
sig<-vr/((nrow(ustr)-1)*ncol(ustr))
sig1<-matrix(nrow=id3,ncol=id3)
for(i in 1:id3){
for(j in 1:id3 ){
if(i!=j){
sig1[i,j]=sig*(cor(ustr[,i],ustr[,j]))}
else{sig1[i,j]=sig}
}
}
}else if(cvstr=="independence"){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
sig1<-matrix(nrow=id3,ncol=id3)
for(i in 1:id3){
for(j in 1:id3 ){
if(i==j){
sig1[i,j]=cov(ustr[,i],ustr[,j])}
else{sig1[i,j]=0}
}
}
}else if(cvstr=="markov"){
ustr<-matrix(dat1$y,byrow = F,nrow=length(id1)/id3,ncol=id3)
vr<-sum(unlist(lapply(as.data.frame(ustr),function(x){var(x)}))*(length(f)-1))
sig<-vr/((nrow(ustr)-1)*ncol(ustr))
ro<-cor(ustr[,1],ustr[,2])
sig1<-matrix(nrow=id3,ncol=id3)
for(i in 1:id3){
for(j in 1:id3 ){
if(i!=j){
sig1[i,j]=sig*(ro^(abs(tm[i]-tm[j])))}
else{sig1[i,j]=sig}
}}
}
ms<-function(dat){
d<-function(x){
dlt1<-c()
for(j in 1:ncol(x)){
if(anyNA.data.frame(x[,j])==T){
dlt1[j]<-0
}
else{
dlt1[j]<-1
}
}
dlt1
}
dlt<-d(t(dat))
dlt1<-d(dat)
if(sum(dlt)!=0){
cc<-as.matrix(t(dat)[,which(dlt==1)])
if(0%in%dlt){
nc<-as.matrix(t(dat)[,-which(dlt==1)])
ncc<-as.matrix(nc[which(dlt1==1),])
ccc<-as.matrix(cc[which(dlt1==1),])
phik<-function(u,w){
v=matrix(nrow=ncol(w),ncol=ncol(u))
for(i in 1:ncol(w)){
for(j in 1:ncol(u)){
if(identical(u[,j],w[,i])==T){
v[i,j]=1
}else{
v[i,j]=0
}
}
}
k=list()
for(j in 1:ncol(v)){
k[[j]]=which(v[,j]==1)
}
k}
k<-phik(u=ncc,w=ccc)
y1<- cc[1,]
dsg=rbind(1,as.matrix(cc[-1,]))
k2=list()
for(j in 1:length(k)){
if(length(k[[j]])!=0){
k2[[j]]=as.matrix(dsg[,k[[j]]])%*%Ginv(as.matrix(sig1[k[[j]],k[[j]]]))%*%as.matrix(y1[k[[j]]])/length(k[[j]])}
else{k2[[j]]=0}}
k3=list()
for(j in 1:length(k)){
if(length(k[[j]])!=0){
k3[[j]]=as.matrix(dsg[,k[[j]]])%*%Ginv(as.matrix(sig1[k[[j]],k[[j]]]))%*%t(as.matrix(dsg[,k[[j]]]))/length(k[[j]])
}else{k3[[j]]=0}
}
if(length(k2)!=0){
h2=Reduce("+",k2)
}else{h2=0}
if(length(k3)!=0){h3=Reduce("+",k3)}else{ h3=0}
xy1<-as.matrix(dsg)%*%Ginv(as.matrix(sig1[which(dlt==1),which(dlt==1)]))%*%as.matrix(cc[1,])+h2
xx1<-as.matrix(dsg)%*%Ginv(as.matrix(sig1[which(dlt==1),which(dlt==1)]))%*%t(dsg)+h3
}else{
dsg=rbind(1,as.matrix(cc[-1,]))
xy1<-as.matrix(dsg)%*%Ginv(as.matrix(sig1[which(dlt==1),which(dlt==1)]))%*%as.matrix(cc[1,])
xx1<-as.matrix(dsg)%*%Ginv(as.matrix(sig1[which(dlt==1),which(dlt==1)]))%*%t(dsg)
}}else{xx1<-NULL;xy1<-NULL}
list(xx1,xy1)
}
l1<-list()
l2<-list()
dat1<-data.frame(dat1)
for(i in 1:length(unique(dat1$id))){
l1[i]<-ms(subset(dat1,dat1$id==unique(dat1$id)[i])[,-c(1,2)])[1]
l2[i]<-ms(subset(dat1,dat1$id==unique(dat1$id)[i])[,-c(1,2)])[2]
}
l1[sapply(l1,is.null)]<-NULL
l2[sapply(l2,is.null)]<-NULL
xx<-Reduce("+",l1)
xy<-Reduce("+",l2)
n<-nrow(xx)
a<-matrix(unlist(xx),nrow=n,ncol=n,byrow = T)
b<-matrix(unlist(xy),nrow=n,ncol=1,byrow = T)
parm<-Ginv(a)%*%b
rslt<-list()
name1<-which(colnames(dat1)=="id")
name2<-which(colnames(dat1)=="t")
name3<-which(colnames(dat1)=="y")
coefficients<-c("intercept",names(dat1)[-c(name1,name2,name3)])
estimate<-parm
rslt$coff<-data.frame(coefficients,estimate)
fit<-cbind(1,dat1[,-c(name1,name2,name3)])
resid<-na.omit(dat1$y-as.matrix(fit)%*%parm)
Aic<- nrow(na.omit(dat1))*(log(2*pi)+1+log((sum(resid^2)/nrow(na.omit(dat1)))))+((n+1)*2)
rslt$aic<-Aic
Bic<-nrow(na.omit(dat1))*log((sum(resid^2)/nrow(na.omit(dat1))))+n*log(nrow(na.omit(dat1)))
rslt$Bic<-Bic
rslt
}
utils::globalVariables(c("cov","var","cor","na.omit")) |
png2 <- function(filename, width=480, height=480, res=144, type="png256", ...) {
bitmap(file=filename, type=type, width=width/res, height=height/res, res=res, ...)
} |
cfba_moment <- function (model,mod2=NULL, Kcat,MW=NULL,selected_rxns=NULL,verboseMode=2,objVal=NULL,
RHS=NULL,solver=SYBIL_SETTINGS("SOLVER"),medval=NULL,runFVA=FALSE,fvaRxn=NULL){
geneCol=NULL;
Kcat[,2]<-as.numeric(Kcat[,2])*60*60 ;
MW[,2]=as.numeric(MW[,2]);
if(length(mod2)==0){
mod2=mod2irrev(model)
}
if(length(medval)==0) medval=median(Kcat[,2])
if(length(selected_rxns)==0)
{selected_rxns=react_id(model)[gpr(model)!="" & gpr(model)!="s0001"]}
print("Preparing LP ... ");
prob <- sysBiolAlg(mod2, algorithm = "fba",solver=solver)
n=react_num(mod2)
m=met_num(mod2)
colid=n+1
rowind=m+1
aux_id=1
for( g in allGenes(mod2)){
if(g!="s0001"){
geneCol=rbind(geneCol,cbind(gene=g,Col=colid))
addCols(lp = problem(prob),1)
changeColsBnds(lp = problem(prob),colid,lb=0,ub=1000)
colid=colid+1;
}}
rxnkcatRow=NULL;
for (r in selected_rxns){
rl=gpr(model)[react_id(model)==r]
if (rl=='( b0875 or s0001 )') rl='b0875';
if (rl=='( b1377 or b0929 or b2215 or b0241 or s0001 or b3875 or b1319 or b0957 )')
rl='( b1377 or b0929 or b2215 or b0241 or b3875 or b1319 or b0957 )';
if (rl=='( s0001 or b0451 )') rl='(b0451)';
if (rl=='( s0001 or b3927 )') rl='( b3927 )';
if(rl=="(b3927 or s0001)") rl="b3927";
if(rl=="(s0001 or b0957 or b3875 or b2215 or b0241 or b1319 or b1377 or b0929)" )
rl="(b0957 or b3875 or b2215 or b0241 or b1319 or b1377 or b0929)"
if(rl=="(s0001 or b0875)") rl="b0875";
if(rl=="(b0451 or s0001)") rl="b0451";
if(rl=="(b1377 or b0241 or b3875 or s0001 or b0957 or b2215 or b1319 or b0929)"){rl<-"(b1377 or b0241 or b3875 or b0957 or b2215 or b1319 or b0929)"}
if(rl=="(b1377 or b2215 or b1319 or b3875 or s0001 or b0957 or b0241 or b0929)") rl="(b1377 or b2215 or b1319 or b3875 or b0957 or b0241 or b0929)";
if(rl=="(s0001 or b0451)") rl="b0451";
if(rl=="(s0001 or b3927)") rl="b3927";
if(rl=="(s0001 or b1779)") rl="b1779";
if(rl=="(b1779 or s0001)") rl="b1779";
if(rl=="(b0875 or s0001)") rl="b0875";
if (verboseMode > 2){ print(r)}
if(r %in% Kcat[Kcat[,"dirxn"]==1,1]){
kval=as.numeric(Kcat[Kcat[,"dirxn"]==1 & Kcat[,1]==r,"val"]);
}else{kval=medval;}
if(r %in% Kcat[Kcat[,"dirxn"]==-1,1]){
rkval=as.numeric(Kcat[Kcat[,"dirxn"]==-1 & Kcat[,1]==r,"val"]);
}else{rkval=medval;}
if(!react_rev(model)[react_id(model)==r]){
vind=which(react_id(mod2)==r)
vind_b=0
lnz=1
}else{
vind=which(react_id(mod2)==paste(r,"_f",sep=""))
vind_b=which(react_id(mod2)==paste(r,"_b",sep=""))
lnz=1
}
rl=gsub("\\)"," ) ",rl)
rl=gsub("\\("," ( ",rl)
rl=gsub(" OR "," or ",rl)
rl=gsub(" AND "," and ",rl)
pr=lapply(strsplit(unlist(strsplit(rl," or "))," and "),function(x) gsub("[() ]","",x))
if (verboseMode > 2){
print(pr)
print(length(pr[[1]]))
}
if( length(pr)==1) {
if(length(pr[[1]])==1){
gene=pr[[1]]
colind=as.numeric(geneCol[geneCol[,"gene"]==gene,"Col"])
if (verboseMode > 2){print(list(vind,colind))}
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(c(vind,colind)),
nzval = list(c(lnz,-1*kval))
,rnames = r
)
rowind=rowind+1;
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind, rxn_id = r, dirxn=1,
rowind=rowind-1,colind,kval));
if(vind_b>0){
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(c(vind_b,colind)),
nzval = list(c(lnz,-1*rkval))
,rnames = paste(r,"_b",sep="")
)
rowind=rowind+1;
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind_b, rxn_id = r, dirxn=-1,
rowind=rowind-1,colind,kval=rkval));
}
}else{
if(verboseMode>2) print(sprintf("Rxn:%s gpr: %s, straight ANDs",r,rl));
addCols(lp = problem(prob),1)
aux_id=colid
colid=colid+1;
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(c(vind,aux_id)),
nzval = list(c(lnz,-1*kval))
,rnames = r
)
rowind=rowind+1;
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind, rxn_id = r, dirxn=1,
rowind=rowind-1,colind=aux_id,kval));
if(react_rev(model)[react_id(model)==r]){
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(c(vind_b,aux_id)),
nzval = list(c(lnz,-1*rkval))
,rnames = paste(r,"_b",sep="")
)
rowind=rowind+1;
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind_b, rxn_id = r, dirxn=-1,
rowind=rowind-1,colind=aux_id,kval=rkval));
}
for(gene in pr[[1]]){
colind=as.numeric(geneCol[geneCol[,"gene"]==gene,"Col"])
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(c(aux_id,colind)),
nzval = list(c(1,-1))
)
rowind=rowind+1;
}
}
}else{
row_vals=rep(0,colid+length(pr))
row_vals[vind]=lnz
row_vals_b=rep(0,colid+length(pr))
row_vals_b[vind_b]=lnz
for( p in 1:length(pr)){
if( length(pr[[p]])==1 ){
gene=pr[[p]]
colind=as.numeric(geneCol[geneCol[,"gene"]==gene,"Col"])
row_vals[colind]=-1*kval
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind, rxn_id = r, dirxn=1,
rowind=NA,colind=colind,kval));
if(react_rev(model)[react_id(model)==r]){
row_vals_b[colind]=-1*rkval
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind_b, rxn_id = r, dirxn=-1,
rowind=NA,colind=colind,kval=rkval));
}
}else{
if(verboseMode > 2) print(sprintf("Rxn:%s gpr: %s, auxiliary ANDs",r,rl));
addCols(lp = problem(prob),1)
aux_id=colid
colid=colid+1;
row_vals[aux_id]=-1*kval
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind, rxn_id = r, dirxn=1,
rowind=NA,colind=aux_id,kval));
if(react_rev(model)[react_id(model)==r]){
row_vals_b[aux_id]=-1*rkval
rxnkcatRow = rbind(rxnkcatRow,data.frame(stringsAsFactors=FALSE,rsn=vind_b, rxn_id = r, dirxn=-1,
rowind=NA,colind=aux_id,kval=rkval));
}
for(g in pr[[p]]){
colind=as.numeric(geneCol[geneCol[,"gene"]==g,"Col"])
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(c(aux_id,colind)), nzval = list(c(1,-1))
,rnames = paste("Aux_",aux_id,sep="")
)
rowind=rowind+1;
}
if (verboseMode > 2){ print(p)}
}
}
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(which(row_vals!=0)), nzval = list(row_vals[which(row_vals!=0)])
,rnames = r
)
rowind=rowind+1;
rxnkcatRow[is.na(rxnkcatRow[,'rowind']) & rxnkcatRow[,'rxn_id']==r & rxnkcatRow[,'dirxn']==1,'rowind']=rowind-1;
if(react_rev(model)[react_id(model)==r]){
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = 0,
cind = list(which(row_vals_b!=0)), nzval = list(row_vals_b[which(row_vals_b!=0)])
,rnames = paste(r,"_b",sep="")
)
rowind=rowind+1;
rxnkcatRow[is.na(rxnkcatRow[,'rowind']) & rxnkcatRow[,'rxn_id']==r & rxnkcatRow[,'dirxn']==-1,'rowind']=rowind-1;
}
}
}
if(length(MW )>0 ){
lnz=NULL
lcind=NULL
if (verboseMode > 2){ print('Setting column bounds ...') }
for(v in c((n+1):(colid-1))){
changeColsBnds(lp = problem(prob),v,lb=0,ub=1000)
}
for(g in geneCol[,"gene"]) {
colind=as.numeric(geneCol[geneCol[,"gene"]==g,"Col"])
if(g %in% MW[,1]){
lnz=cbind(lnz,MW[MW[,1]==g,2])
if (verboseMode > 2){print(c(g,MW[MW[,1]==g,2]))}
lcind=cbind(lcind,colind)
}
}
if(!is.null(RHS) ){
addRowsToProb(lp = problem(prob),
i = rowind , type = "U",
lb = 0, ub = RHS,
cind = list(lcind), nzval = list(lnz)
,rnames = "MW"
)
} else {
if(is.null(objVal) ){
tmp_sol = optimizeProb(mod2,solver=solver,retOptSol=FALSE);
if(tmp_sol$ok!=0 || length(checkSolStat(stat=tmp_sol$stat,solver=solver))!=0 ) {
if(is.na(checkSolStat(stat=tmp_sol$stat,solver=solver)[1])) print("couldn't check solution status");
stop(sprintf("Failed to calculate objective value, sol status: %s", getMeanStatus(code=tmp_sol$stat,solver=solver) ));
}
objVal = tmp_sol$obj;
print(sprintf('Objective value to be used: %f',objVal))
}
objc=getObjCoefs(problem(prob),j=c(1:n))
cind=which(objc!=0)
nzval=objc[cind]
addRowsToProb(lp = problem(prob),
i = rowind , type = "L",
lb = objVal, ub = Inf,
cind = list(cind), nzval = list(nzval)
,rnames = paste("ObjC_",rowind,sep="")
)
rowind=rowind+1;
changeObjCoefs(lp = problem(prob),j=c(1:n),obj_coef=rep(0,n))
changeObjCoefs(lp = problem(prob),j=as.numeric(lcind),obj_coef=lnz)
setObjDir(lp = problem(prob),"min")
}
}
if (verboseMode > 2) {
fname=format(Sys.time(), "moment_%Y%m%d_%H%M.lp");
print(sprintf("Writing the problem to: %s/%s...",getwd(),fname));
writeProb(lp=problem(prob), fname)
if(solver=="cplexAPI"){
Nnz=NULL
nr=getNumRows(problem(prob))
lp=problem(prob)
for(r in c(1:nr)){
rv=cplexAPI::getRowsCPLEX(env = lp@oobj@env, lp = lp@oobj@lp, begin = r-1, end = r-1)
for(cl in 1:length(rv$matind)){
Nnz=rbind(Nnz,cbind(i=r,j=rv$matind[cl],val=rv$matval[cl]))
}
}
write.csv(file="nnz.csv",Nnz)
}
}
print("Solving ... ");
sol=optimizeProb(prob)
if(sol$ok!=0 || length(checkSolStat(stat=sol$stat,solver=solver))!=0 ) {
if(is.na(checkSolStat(stat=sol$stat,solver=solver)[1])) print("couldn't check solution status");
warning(sprintf("Solution is not optimal: %s", getMeanStatus(code=sol$stat,solver=solver) ));
}
actual_C = matrix(lnz,nrow=1) %*% matrix(sol$fluxes[lcind],ncol=1);
if(!runFVA){
return(list(sol=sol,geneCol=geneCol,prob=prob,actual_C=actual_C,rxnkcatRow=rxnkcatRow))
}else{
if (verboseMode > 1) {print("Calculating FVA ...")}
main_flx = sol$fluxes[1:react_num(mod2)]
tol = SYBIL_SETTINGS("TOLERANCE");
bm_rxn = which(obj_coef(mod2)==1)
main_sol = sol
model_objVal = main_flx[bm_rxn]
print(sprintf('Main sol obj rxn: %s, objVal:%f',react_id(mod2)[bm_rxn],main_flx[bm_rxn]))
changeColsBnds(lp = problem(prob), bm_rxn, lb=model_objVal-tol, ub=model_objVal+tol)
changeObjCoefs(lp = problem(prob),j=bm_rxn,obj_coef=0)
bLP = backupProb(lp = problem(prob))
if(!is.null(fvaRxn)){intReact = fvaRxn}
else{ intReact = 1:react_num(mod2)}
nObj <- 2 * length(intReact)
obj <- numeric(nObj)
ok <- integer(nObj)
stat <- integer(nObj)
oppositFlx <- numeric(nObj)
bmFlx <- numeric(nObj)
for (i in seq(along = intReact)) {
prob1=prob
prob@problem@oobj = bLP@oobj
bLP <- backupProb(bLP)
remove(prob1)
solpl <- i
sol <- optimizeProb(prob, lpdir = "min",
react = intReact[i], obj_coef = 1)
obj[solpl] <- sol$obj
ok[solpl] <- sol$ok
stat[solpl] <- sol$stat
bmFlx[solpl] <- sol$fluxes[bm_rxn]
if (matchrev(mod2)[intReact[i]] !=0 ){
oppositFlx[solpl] <- sol$fluxes[matchrev(mod2)[intReact[i]]];
}
if(sol$stat != 5){
print('bad status')
}
solpl <- length(intReact) + i
sol <- optimizeProb(prob, lpdir = "max",
react = intReact[i], obj_coef = 1)
obj[solpl] <- sol$obj
ok[solpl] <- sol$ok
stat[solpl] <- sol$stat
bmFlx[solpl] <- sol$fluxes[bm_rxn]
if (matchrev(mod2)[intReact[i]] !=0 ){
oppositFlx[solpl] <- sol$fluxes[matchrev(mod2)[intReact[i]]];
}
if(sol$stat != 5){
print('bad status')
}
}
fva <- cbind (ok =ok, stat=stat, lpdir=c(rep('min',length(intReact)),rep('max',length(intReact))),fv=obj, mainFlx=main_flx[c(intReact,intReact)],
oppositFlx=oppositFlx, bmFlx=bmFlx, rxns=c(intReact,intReact), rxnid=react_id(mod2)[c(intReact,intReact)],
gpr=gpr(mod2)[c(intReact,intReact)],oposid=matchrev(mod2)[c(intReact,intReact)]);
return(list(sol=main_sol,geneCol=geneCol,prob=prob,actual_C=actual_C,fva=fva));
}
} |
context("as.data.frame.dust")
test_that(
"FR 1: Accepts an object of class `dust`",
{
skip_on_cran()
expect_silent(
as.data.frame.dust(dust(mtcars))
)
}
)
test_that(
"FR 1: Accepts an object of class `dust_list`",
{
skip_on_cran()
expect_silent(
split(mtcars, mtcars$am) %>%
dust() %>%
as.data.frame()
)
}
)
test_that(
"FR 1: Casts an error when passed an object not of class `dust` or `dust_list`",
{
skip_on_cran()
expect_error(
pixiedust:::as.data.frame.dust(mtcars)
)
}
)
test_that(
"FR 1: Casts an error when passed an object not of class `dust` or `dust_list`",
{
skip_on_cran()
expect_error(
pixiedust:::as.data.frame.dust_list(mtcars)
)
}
)
test_that(
"FR 2: Accepts a logical indicating if sprinkles should be applied.",
{
skip_on_cran()
expect_silent(
dust(mtcars) %>%
as.data.frame(sprinkled = TRUE)
)
}
)
test_that(
"FR 2: Accepts a logical indicating if sprinkles should be applied (dust_list).",
{
skip_on_cran()
expect_silent(
split(mtcars, mtcars$am) %>%
dust() %>%
as.data.frame(sprinkled = TRUE)
)
}
)
test_that(
"FR 2: Casts error when `sprinkled` is not logical",
{
skip_on_cran()
expect_error(
dust(mtcars) %>%
as.data.frame(sprinkled = 1)
)
}
)
test_that(
"FR 2: Casts error when `sprinkled` is not logical (dust_list)",
{
skip_on_cran()
expect_error(
split(mtcars, mtcars$am) %>%
dust() %>%
as.data.frame(sprinkled = 1)
)
}
)
test_that(
"FR 3: Return a data frame object",
{
skip_on_cran()
fit <- lm(mpg ~ qsec + factor(am) + wt * factor(gear), data = mtcars)
Dust <- dust(fit) %>%
sprinkle(cols = 2:4, round = 2) %>%
sprinkle(cols = 5, fn = quote(pvalString(value))) %>%
sprinkle(cols = 3, font_color = "
sprinkle_print_method("html")
expect_true("data.frame" %in% class(as.data.frame(Dust)))
}
)
test_that(
"FR 3: Return a data frame object when unsprinkled",
{
skip_on_cran()
fit <- lm(mpg ~ qsec + factor(am) + wt * factor(gear), data = mtcars)
Dust <- dust(fit) %>%
sprinkle(cols = 2:4, round = 2) %>%
sprinkle(cols = 5, fn = quote(pvalString(value))) %>%
sprinkle(cols = 3, font_color = "
sprinkle_print_method("html")
expect_true("data.frame" %in% class(as.data.frame(Dust, sprinkled = FALSE)))
}
)
test_that(
"FR 4: Return a list of data frames (dust_list)",
{
skip_on_cran()
Dust <- split(mtcars, mtcars$am) %>%
dust() %>%
as.data.frame()
dust_class <- vapply(Dust,
function(x) "data.frame" %in% class(x),
logical(1))
expect_true(all(dust_class))
}
)
test_that(
"FR 4: Return a list of data frames when unsprinkled (dust_list)",
{
skip_on_cran()
Dust <- split(mtcars, mtcars$am) %>%
dust() %>%
as.data.frame(sprinkled = FALSE)
dust_class <- vapply(Dust,
function(x) "data.frame" %in% class(x),
logical(1))
expect_true(all(dust_class))
}
) |
buildScoreCache.mle <- function(data.df = NULL, data.dists = NULL, max.parents = NULL,
adj.vars = NULL, cor.vars = NULL, dag.banned = NULL,
dag.retained = NULL, which.nodes = NULL, maxit = 100,
tol = 10^-8, centre = TRUE, defn.res = NULL, dry.run = FALSE, verbose = FALSE,
seed = 9062019,
ncores = 1 ) {
set.seed(seed)
if (!is.null(which.nodes)) {
data.df <- data.df[, which.nodes]
data.dists <- data.dists[which.nodes]
}
n <- length(data.dists)
nobs <- dim(data.df)[1]
group.var <- NULL
if (Reduce("|", names(data.dists) != names(data.dists[colnames(data.df)]))) {
stop("data.dists, data.df do not have the same names or the same names' order")
}
data.df.lvl <- data.df
if (centre && !is.null(data.dists == "gaussian")) {
for (i in names(data.dists)[(data.dists == "gaussian")]) {
data.df[, i] <- (data.df[, i] - mean(data.df[, i]))/sd(data.df[, i])
}
}
for (i in 1:n) {
if (data.dists[[i]] == "binomial" & class(data.df[, i]) != "numeric") {
data.df[, i] <- as.numeric(factor(data.df[, i])) - 1
}
if (data.dists[[i]] == "multinomial") {
data.df[, i] <- factor(data.df[, i])
}
}
if (!is.null(adj.vars)) {
data.df.adj <- data.df
data.df <- data.df[, -adj.vars]
n <- n - length(adj.vars)
}
if (!is.null(dag.banned)) {
if (is.matrix(dag.banned)) {
dag.banned <- check.valid.dag(dag.m = dag.banned, data.df = data.df,
is.ban.matrix = TRUE, group.var = group.var)
} else {
if (grepl("~", as.character(dag.banned)[1], fixed = TRUE)) {
dag.banned <- formula.abn(f = dag.banned, name = colnames(data.df))
dag.banned <- check.valid.dag(dag.m = dag.banned, data.df = data.df,
is.ban.matrix = TRUE, group.var = group.var)
}
}
} else {
dag.banned <- check.valid.dag(dag.m = dag.banned, data.df = data.df,
is.ban.matrix = TRUE, group.var = group.var)
}
if (!is.null(dag.retained)) {
if (is.matrix(dag.retained)) {
dag.retained <- check.valid.dag(dag.m = dag.retained, data.df = data.df,
is.ban.matrix = FALSE, group.var = group.var)
} else {
if (grepl("~", as.character(dag.retained)[1], fixed = TRUE)) {
dag.retained <- formula.abn(f = dag.retained, name = colnames(data.df))
dag.retained <- check.valid.dag(dag.m = dag.retained, data.df = data.df,
is.ban.matrix = FALSE, group.var = group.var)
}
}
} else {
dag.retained <- check.valid.dag(dag.m = dag.retained, data.df = data.df,
is.ban.matrix = FALSE, group.var = group.var)
}
if (!is.null(defn.res)) {
max.parents <- max(apply(defn.res[["node.defn"]], 1, sum))
} else {
if (is.null(max.parents)) {
max.parents <- 1
}
if (is.numeric(max.parents)) {
if (max.parents >= n) {
max.parents <- n - 1
}
}
max.parent.list <- NULL
if (is.list(max.parents)) {
if (do.call(max, max.parents) > (n)) {
stop("max.parent should be an integer or a list with a maximum possible of number of node-1 and the length of the list should not exceed the number of nodes.")
} else {
max.parent.list <- max.parents
max.parents <- do.call(max, max.parents)
}
}
fun.return <- function(x) {
v <- rep(0, n - 1)
v[x] <- 1
return(v)
}
node.defn <- matrix(data = as.integer(0), nrow = 1L, ncol = n)
children <- 1
for (j in 1:n) {
if (j != 1) {
node.defn <- rbind(node.defn, matrix(data = as.integer(0),
nrow = 1L, ncol = n))
children <- cbind(children, j)
}
for (i in 1:(max.parents)) {
tmp <- t(combn(n - 1, i, FUN = fun.return, simplify = TRUE))
tmp <- t(apply(X = tmp, MARGIN = 1, FUN = function(x) append(x = x, values = 0, after = j - 1)))
node.defn <- rbind(node.defn, tmp)
children <- cbind(children, t(rep(j, length(tmp[, 1]))))
}
}
colnames(node.defn) <- colnames(data.df)
node.defn <- apply(node.defn, c(1, 2), function(x) {
(as.integer(x))
})
children <- as.integer(children)
for (i in 1:n) {
for (j in 1:n) {
if (dag.retained[i, j] != 0) {
tmp.indices <- which(children == i & node.defn[, j] == 0)
if (length(tmp.indices) != 0) {
node.defn <- node.defn[-tmp.indices, ]
children <- children[-tmp.indices]
}
}
if (dag.banned[i, j] != 0) {
tmp.indices <- which(children == i & node.defn[, j] == 1)
if (length(tmp.indices) != 0) {
node.defn <- node.defn[-tmp.indices, ]
children <- children[-tmp.indices]
}
}
}
}
mycache <- list(children = as.integer(children), node.defn = (node.defn))
if (!is.null(max.parent.list)) {
for (z in 1:n) {
tmp <- mycache[["node.defn"]][mycache[["children"]] == z, ]
if (is.null(dim(tmp))) stop("Increase parents for node ",z," (due to retain)")
if (any(diff(unlist(max.parents)) !=0))
stop("For method='mle', unique number of parents required")
mycache[["node.defn"]][mycache[["children"]] == z, ] <- tmp[rowSums(tmp) <= unlist(max.parent.list[z]), ]
}
}
if (!is.null(adj.vars)) {
mycache$node.defn <- cbind(mycache$node.defn, matrix(data = 0, nrow = dim(mycache$node.defn)[1], ncol = length(adj.vars)))
if (is.null(cor.vars)) {
cor.vars <- colnames(data.df)
}
mycache$node.defn[mycache$children[match(cor.vars, colnames(data.df))], dim(data.df)[2]:dim(data.df.adj)] <- 1
colnames(mycache$node.defn) <- c(colnames(data.df), adj.vars)
mycache$node.defn <- mycache$node.defn[, names(data.df.adj)]
data.df <- data.df.adj
}
repetition.multi <- vector(length = n)
for (i in 1:n) {
if (data.dists[[i]] %in% c("binomial", "poisson", "gaussian")) {
repetition.multi[i] <- 1
} else {
repetition.multi[i] <- nlevels(data.df.lvl[, i])
}
}
if (!is.null(adj.vars)) {
mycache$node.defn.multi <- mycache$node.defn.adj[, rep(1:n, repetition.multi)]
data.df <- data.df.adj[, colnames(mycache$node.defn.adj)]
} else {
mycache$node.defn.multi <- mycache$node.defn[, rep(1:n, repetition.multi)]
}
data.df.multi <- NULL
for (i in 1:n) {
if (data.dists[[i]] %in% c("binomial", "poisson", "gaussian")) {
data.df.multi <- as.data.frame(cbind(data.df.multi, data.df[, i]))
colnames(data.df.multi)[length(colnames(data.df.multi))] <- colnames(data.df)[i]
} else {
tmp <- model.matrix(~-1 + factor(data.df.lvl[, i]))
colnames(tmp) <- paste0(names(data.df.lvl)[i], levels(factor(data.df.lvl[, i])))
data.df.multi <- as.data.frame(cbind(data.df.multi, tmp))
}
}
}
if (dry.run) {
return(mycache)
}
out <- list()
rows <- length(mycache[["children"]])
cl <- makeCluster(ncores)
registerDoParallel(cl)
row.num <- NULL
suppressWarnings(
res <- foreach( row.num = 1:rows, .combine='rbind' ) %dopar% {
child <- mycache[["children"]][row.num]
distribution <- data.dists[child]
Y <- data.matrix(data.df[, child])
if (is.null(adj.vars)) {
if ("multinomial" %in% data.dists[as.logical(mycache$node.defn[row.num, ])]) {
X <- data.matrix(cbind(data.df.multi[, as.logical(mycache[["node.defn.multi"]][row.num, ])]))
} else {
X <- data.matrix(cbind(rep(1, length(data.df[, 1])), data.df.multi[, as.logical(mycache[["node.defn.multi"]][row.num, ])]))
}
} else {
if ("multinomial" %in% data.dists[as.logical(mycache$node.defn.adj[row.num, ])]) {
X <- data.matrix(cbind(data.df.multi[, as.logical(mycache[["node.defn.multi"]][row.num, ])]))
} else {
X <- data.matrix(cbind(rep(1, length(data.df[, 1])), data.df.multi[, as.logical(mycache[["node.defn.multi"]][row.num, ])]))
}
}
num.na <- 0
Y1 <- as.numeric(as.character(Y))
R <- rank_cpp(X)
r <- ncol(X)
R_col <- R/r
if (R_col != 1 & as.character(distribution) == "binomial") {
tryCatch(fit <- irls_binomial_cpp_fast_br(A = X, b = Y1, maxit = maxit, tol = tol), error = function(e) {
while (rank_cpp(X)/ncol(X) != 1) {
X <- X[, -1]
num.na <- num.na + 1
if (is.null(ncol(X)))
X <- as.matrix(X)
}
fit <- irls_binomial_cpp_fast_br(A = X, b = Y1, maxit = maxit, tol = tol)
}, finally = fit)
} else {
switch(as.character(distribution), binomial = {
fit <- irls_binomial_cpp_fast_br(A = X, b = Y1, maxit = maxit, tol = tol)
if (is.na(sum(fit[[1]]))) fit <- irls_binomial_cpp_fast_br(A = X, b = Y, maxit = maxit, tol = tol)
}, gaussian = {
suppressWarnings(fit <- irls_gaussian_cpp_fast(A = X, b = Y, maxit = maxit, tol = tol))
}, poisson = {
suppressWarnings(fit <- irls_poisson_cpp_fast(A = X, b = Y, maxit = maxit, tol = tol))
}, multinomial = {
Ymulti <- data.matrix(model.matrix(~-1 + data.df.lvl[, child]))
p <- ncol(Ymulti)
mask <- c(rep(FALSE, r + 1L), rep(c(FALSE, rep(TRUE, r)), p - 1L))
tmp <- nnet.default(x = X, y = Ymulti, mask = mask, size = 0,
skip = TRUE, softmax = TRUE, rang = 0, trace = FALSE)
fit <- NULL
fit$loglik <- -tmp$value
edf <- ifelse(length(tmp$lev) == 2L, 1, length(tmp$lev) - 1) * R
fit$aic <- 2 * tmp$value + 2 * edf
fit$bic <- 2 * tmp$value + edf * log(nobs)
})
}
c( fit$loglik, fit$aic, fit$bic,
fit$bic + (1 + sum(mycache[["node.defn.multi"]][row.num, ]) - num.na) * log(n) )
}
)
out[["children"]] <- mycache[["children"]]
out[["node.defn"]] <- mycache$node.defn
out[["mlik"]] <- as.numeric( res[,1] )
out[["error.code"]] <- list()
out[["hessian.accuracy"]] <- list()
out[["used.INLA"]] <- list()
out[["error.code.desc"]] <- list()
out[["data.df"]] <- data.df.lvl
out[["data.dists"]] <- data.dists
out[["max.parents"]] <- max.parents
out[["dag.retained"]] <- dag.retained
out[["dag.banned"]] <- dag.banned
out[["group.ids"]] <- list()
out[["aic"]] <- as.numeric( res[,2] )
out[["bic"]] <- as.numeric( res[,3] )
out[["mdl"]] <- as.numeric( res[,4] )
out[["method"]] <- "mle"
stopCluster(cl)
return(out)
} |
make.exptrans <- function()
{
exptrans.fun <- function(times,y,p,more)
{
y = exp(y)
x = more$fn(times,y,p,more$more)
return(x)
}
exptrans.dfdx <- function(times,y,p,more)
{
y = exp(y)
x = more$dfdx(times,y,p,more$more)
for(i in 1:dim(x)[2]){
for(j in 1:dim(x)[3]){
x[,i,j] = x[,i,j]*y[,j]
}
}
return(x)
}
exptrans.dfdp <- function(times,y,p,more)
{
y = exp(y)
x = more$dfdp(times,y,p,more$more)
return(x)
}
exptrans.d2fdx2 <- function(times,y,p,more)
{
x1 = exptrans.dfdx(times,y,p,more)
y = exp(y)
x = more$d2fdx2(times,y,p,more$more)
for(i in 1:dim(x)[2]){
for(j in 1:dim(x)[3]){
for(k in 1:dim(x)[4]){
x[,i,j,k] = x[,i,j,k]*y[,j]*y[,k]
}
x[,i,j,j] = x[,i,j,j] + x1[,i,j]
}
}
return(x)
}
exptrans.d2fdxdp <- function(times,y,p,more)
{
y = exp(y)
x = more$d2fdxdp(times,y,p,more$more)
for(i in 1:dim(x)[2]){
for(j in 1:dim(x)[3]){
for(k in 1:dim(x)[4]){
x[,i,j,k] = x[,i,j,k]*y[,j]
}
}
}
return(x)
}
more = list(fn = exptrans.fun,
dfdx = exptrans.dfdx,
dfdp = exptrans.dfdp,
d2fdx2 = exptrans.d2fdx2,
d2fdxdp = exptrans.d2fdxdp,
extras = NULL)
} |
popMprojHigh <- read.delim(file='popMprojHigh.txt', comment.char=' |
print.model_performance <- function(x, ...) {
cat("Measures for: ", x$type)
cat(paste0("\n", substr(paste0(names(x$measures), " "), 1, 11), ": ", sapply(x$measures, prettyNum)))
cat("\n\nResiduals:\n")
print(quantile(x$residuals$diff, seq(0, 1, 0.1)))
} |
context("test-ets.R")
forecast_fit <- USAccDeaths %>% forecast::ets()
test_that("Automatic ETS selection", {
fable_fit <- USAccDeaths_tbl %>% model(ets = ETS(value))
expect_equivalent(
tidy(fable_fit$ets[[1]]$fit)$estimate,
c(coef(forecast_fit), -sum(coef(forecast_fit)[-(1:3)]))
)
expect_equal(
tidy(model(UKLungDeaths[1:24, ], ETS(mdeaths)))$estimate,
c(1, 2134),
tolerance = 0.5
)
})
test_that("Manual ETS selection", {
fable_fit <- USAccDeaths_tbl %>% model(ets = ETS(value ~ error("A") + trend("N") + season("A")))
expect_equivalent(
tidy(fable_fit$ets[[1]]$fit)$estimate,
c(coef(forecast_fit), -sum(coef(forecast_fit)[-(1:3)]))
)
expect_identical(
model_sum(fable_fit$ets[[1]]),
"ETS(A,N,A)"
)
fable_fc <- fable_fit %>% forecast()
forecast_fc <- forecast_fit %>% forecast::forecast()
expect_equivalent(
fc_mean(fable_fc$value),
unclass(forecast_fc$mean)
)
fable_fit %>%
generate(USAccDeaths_tbl)
fable_fit %>%
generate(USAccDeaths_tbl %>%
dplyr::mutate(index = index + 72))
expect_identical(
tidy(refit(fable_fit, USAccDeaths_tbl))$estimate == tidy(fable_fit)$estimate,
c(rep(TRUE, 2), rep(FALSE, 13))
)
expect_identical(
tidy(refit(fable_fit, USAccDeaths_tbl, reinitialise = FALSE))$estimate,
tidy(fable_fit)$estimate
)
cmp <- components(fable_fit)
expect_identical(
tidy(fable_fit)$estimate[3:14],
c(cmp$level[12], cmp$season[12:2])
)
expect_s3_class(
cmp, "dcmp_ts"
)
expect_output(
report(fable_fit),
"sigma\\^2: 85667.86"
)
aug <- augment(fable_fit)
expect_equal(
aug$value,
aug$.fitted + aug$.resid
)
coef <- USAccDeaths_tbl %>%
model(ETS(value ~ error("A") + season("A", gamma = 0.0001) +
trend("Ad", alpha = 0.5, beta = 0.006, phi = 0.975))) %>%
tidy()
expect_identical(
coef$estimate[1:4],
c(0.5, 0.006, 0.0001, 0.975)
)
expect_identical(
coef$term,
c("alpha", "beta", "gamma", "phi", "l[0]", "b[0]", sprintf("s[%i]", 0:-11))
)
})
test_that("ETS with bad inputs", {
expect_warning(
USAccDeaths_tbl %>% model(ETS(value ~ error("A") + error("A"))),
"Only one special of each type is allowed for ETS"
)
expect_warning(
USAccDeaths_tbl %>% model(ETS(value ~ trend(alpha = 1.5))),
"Inconsistent parameter boundaries"
)
expect_warning(
USAccDeaths_tbl %>% model(ETS(value ~ error("A") + trend("A", alpha = 0.2, beta = 0.5) + season("N"))),
"Parameters out of range"
)
expect_warning(
UKLungDeaths %>%
model(ETS(vars(mdeaths, fdeaths))),
"Only univariate responses are supported by ETS"
)
UK_missing <- UKLungDeaths
UK_missing[["mdeaths"]][3:5] <- NA
expect_warning(
UK_missing %>%
model(ETS(mdeaths)),
"ETS does not support missing values"
)
expect_warning(
UKLungDeaths %>%
model(ETS(mdeaths ~ trend("M") + season("A"))),
"No valid ETS models have been allowed"
)
expect_warning(
UKLungDeaths[1:2, ] %>%
model(ETS(mdeaths)),
"Not enough data to estimate this ETS model"
)
})
test_that("Multiplicative ETS models", {
fable_fit <- USAccDeaths_tbl %>%
model(ets = ETS(value ~ error("M") + trend("N") + season("N")))
expect_true(
is.constant(fc_mean(forecast(fable_fit)$value))
)
expect_s3_class(
USAccDeaths_tbl %>%
model(ets = ETS(value ~ error("M") + trend("A") + season("M"))) %>%
forecast(),
"fbl_ts"
)
expect_s3_class(
USAccDeaths_tbl %>%
model(ets = ETS(value ~ error("M") + trend("M") + season("M"))) %>%
forecast(times = 5),
"fbl_ts"
)
}) |
pairdepb <- function(y, groups, blocks, tr = 0.2, nboot = 599, ...){
cols1 <- deparse(substitute(y))
cols2 <- deparse(substitute(groups))
cols3 <- deparse(substitute(blocks))
dat <- data.frame(y, groups, blocks)
colnames(dat) <- c(cols1, cols2, cols3)
cl <- match.call()
x <- reshape(dat, idvar = cols3, timevar = cols2, direction = "wide")[-1]
grp <- c(1:length(x))
alpha=.05
grp=0
if(is.data.frame(x)) x <- as.matrix(x)
if(!is.list(x) && !is.matrix(x))stop("Data must be stored in a matrix or in list mode.")
if(is.list(x)){
if(sum(grp)==0)grp<-c(1:length(x))
mat<-matrix(0,length(x[[1]]),length(grp))
for (j in 1:length(grp))mat[,j]<-x[[grp[j]]]
}
if(is.matrix(x)){
if(sum(grp)==0)grp<-c(1:ncol(x))
mat<-x[,grp]
}
if(sum(is.na(mat)>=1))stop("Missing values are not allowed.")
J<-ncol(mat)
connum<-(J^2-J)/2
bvec<-matrix(0,connum,nboot)
data<-matrix(sample(nrow(mat),size=nrow(mat)*nboot,replace=TRUE),nrow=nboot)
xcen<-matrix(0,nrow(mat),ncol(mat))
for (j in 1:J)xcen[,j]<-mat[,j]-mean(mat[,j],tr)
it<-0
for (j in 1:J){
for (k in 1:J){
if(j<k){
it<-it+1
bvec[it,]<-apply(data,1,tsub,xcen[,j],xcen[,k],tr)
}}}
bvec<-abs(bvec)
icrit<-round((1-alpha)*nboot)
critvec<-apply(bvec,2,max)
critvec<-sort(critvec)
crit<-critvec[icrit]
psihat<-matrix(0,connum,5)
dimnames(psihat)<-list(NULL,c("Group","Group","psihat","ci.lower","ci.upper"))
test<-matrix(NA,connum,4)
dimnames(test)<-list(NULL,c("Group","Group","test","se"))
it<-0
for (j in 1:J){
for (k in 1:J){
if(j<k){
it<-it+1
estse<-yuend(mat[,j],mat[,k])$se
dif<-mean(mat[,j],tr)-mean(mat[,k],tr)
psihat[it,1]<-grp[j]
psihat[it,2]<-grp[k]
psihat[it,3]<-dif
psihat[it,4]<-dif-crit*estse
psihat[it,5]<-dif+crit*estse
test[it,1]<-grp[j]
test[it,2]<-grp[k]
test[it,3]<-yuend(mat[,j],mat[,k])$test
test[it,4]<-estse
}}}
fnames <- as.character(unique(groups))
psihat1 <- cbind(psihat, test[,3], crit)
result <- list(comp = psihat1, fnames = fnames, call = cl)
class(result) <- "mcp1"
result
} |
guide_stringlegend <- function(
title = waiver(),
title.position = NULL,
title.theme = NULL,
title.hjust = NULL,
title.vjust = NULL,
label.theme = NULL,
label.hjust = NULL,
label.vjust = NULL,
family = NULL,
face = NULL,
size = NULL,
spacing.x = NULL,
spacing.y = NULL,
spacing = NULL,
default.units = "pt",
direction = NULL,
nrow = NULL,
ncol = NULL,
byrow = FALSE,
reverse = FALSE,
order = 0,
...
) {
if (!is.null(spacing.x) & !is.unit(spacing.x)) {
spacing.x <- unit(spacing.x, default.units)
}
if (!is.null(spacing.y) & !is.unit(spacing.y)) {
spacing.y <- unit(spacing.y, default.units)
}
if (!is.null(spacing) & !is.unit(spacing)) {
spacing <- unit(spacing, default.units)
}
spacing.x <- spacing.x %||% spacing
spacing.y <- spacing.y %||% spacing
structure(
list(
title = title,
title.position = title.position,
title.theme = title.theme,
title.hjust = title.hjust,
title.vjust = title.vjust,
label.theme = label.theme,
label.hjust = label.hjust,
label.vjust = label.vjust,
label.family = family,
label.face = face,
label.size = size,
label.spacing.x = spacing.x,
label.spacing.y = spacing.y,
direction = direction,
nrow = nrow,
ncol = ncol,
byrow = byrow,
reverse = reverse,
order = order,
available_aes = c("colour", "fill"),
...,
name = "stringlegend"
),
class = c("guide", "stringlegend", "legend")
)
}
guide_gengrob.stringlegend <- function(guide, theme) {
nbreak <- nrow(guide$key)
if (!is.null(guide$nrow) && !is.null(guide$ncol) &&
guide$nrow * guide$ncol < nbreak) {
stop("`nrow` * `ncol` need to be larger than the number of breaks.")
}
if (is.null(guide$nrow) && is.null(guide$ncol)) {
if (guide$direction == "horizontal") {
guide$nrow <- ceiling(nbreak / 5)
} else {
guide$ncol <- ceiling(nbreak / 20)
}
}
legend.nrow <- guide$nrow %||% ceiling(nbreak / guide$ncol)
legend.ncol <- guide$ncol %||% ceiling(nbreak / guide$nrow)
legend.dim <- c(legend.nrow, legend.ncol)
title <- render_legend_title(guide, theme)
default_gap <- 0.5 * unit(title$fontsize, "pt")
hgap <- width_cm(theme$legend.spacing.x %||% default_gap)
vgap <- height_cm(theme$legend.spacing.y %||% default_gap)
xgap <- width_cm(guide$label.spacing.x %||% default_gap)
ygap <- height_cm(guide$label.spacing.y %||% default_gap)
labels <- render_stringlegend_labels(guide, theme,
legend.dim, nbreak)
if (guide$byrow) {
vps <- .int$new_data_frame(list(
R = ceiling(seq(nbreak) / legend.ncol),
C = (seq(nbreak) - 1) %% legend.ncol + 1
))
} else {
vps <- arrayInd(seq(nbreak), legend.dim)
vps <- .int$new_data_frame(list(R = vps[, 1], C = vps[, 2]))
}
vps <- transform(vps, label.row = R * 2 - 1, label.col = C * 2 - 1)
widths <- head(.int$interleave(labels$width, xgap), -1)
heights <- head(.int$interleave(labels$height, ygap), -1)
switch(
guide$title.position,
"top" = {
widths <- c(widths, max(0, title$width - sum(widths)))
heights <- c(title$height, vgap, heights)
vps <- transform(vps, label.row = label.row + 2)
vps.title.row <- 1; vps.title.col <- 1:length(widths)
},
"bottom" = {
widths <- c(widths, max(0, title$width - sum(widths)))
heights <- c(heights, vgap, title$height)
vps.title.row <- length(heights); vps.title.col <- 1:length(widths)
},
"left" = {
widths <- c(title$width, hgap, widths)
heights <- c(heights, max(0, title$height - sum(heights)))
vps <- transform(vps, label.col = label.col + 2)
vps.title.row <- 1:length(heights); vps.title.col <- 1
},
"right" = {
widths <- c(widths, hgap, title$width)
heights <- c(heights, max(0, title$height - sum(heights)))
vps.title.row <- 1:length(heights); vps.title.col <- length(widths)
}
)
background <- element_render(theme, "legend.background")
padding <- convertUnit(theme$legend.margin %||% margin(),
"cm", valueOnly = TRUE)
widths <- c(padding[4], widths, padding[2])
heights <- c(padding[1], heights, padding[3])
gt <- gtable(widths = unit(widths, "cm"),
heights = unit(heights, "cm"))
gt <- gtable_add_grob(gt, background, name = "background", clip = "off",
t = 1, r = -1, b = -1, l = 1)
gt <- gtable_add_grob(
gt,
.int$justify_grobs(
title$grob, hjust = title$hjust, vjust = title$vjust,
int_angle = title$theme$angle, debug = title$theme$debug
),
name = "title", clip = "off",
t = 1 + min(vps.title.row), r = 1 + max(vps.title.col),
b = 1 + max(vps.title.row), l = 1 + min(vps.title.col)
)
gt <- gtable_add_grob(
gt,
.int$justify_grobs(
labels$grob, hjust = labels$hjust, vjust = labels$vjust,
int_angle = labels$theme$angle, debug = labels$theme$debug
),
name = paste("label", vps$label.row, vps$label.col, sep = "-"),
clip = "off",
t = 1 + vps$label.row, r = 1 + vps$label.col,
b = 1 + vps$label.row, l = 1 + vps$label.col
)
gt
}
render_stringlegend_labels <- function(guide, theme, dim, n) {
label.theme <- guide$label.theme %||% calc_element("legend.text", theme)
key_nrow <- nrow(guide$key)
if (is.null(guide$key$.label)) {
grob <- rep(list(zeroGrob()), key_nrow)
hjust <- vjust <- NULL
} else {
just_defaults <- list(hjust = 0, vjust = 0.5)
if (just_defaults$hjust == 0 && any(is.expression(guide$key$.label))) {
just_defaults$hjust <- 1
}
if (is.null(guide$label.theme$hjust) && is.null(theme$legend.text$hjust)) {
label.theme$hjust <- NULL
}
if (is.null(guide$label.theme$vjust) && is.null(theme$legend.text$vjust)) {
label.theme$vjust <- NULL
}
hjust <- guide$label.hjust %||% theme$legend.text.align %||%
label.theme$hjust %||% just_defaults$hjust
vjust <- guide$label.vjust %||% label.theme$vjust %||% just_defaults$vjust
colour <- guide$key$fill %||% guide$key$colour %||% "black"
face <- guide$label.face %||% label.theme$face
family <- guide$label.family %||% label.theme$family
size <- guide$label.size %||% label.theme$size
grob <- lapply(seq_len(key_nrow), function(i, ...) {
g <- element_grob(
element = label.theme,
label = guide$key$.label[[i]],
colour = colour[[i]],
face = face,
family = family,
size = size,
hjust = hjust,
vjust = vjust,
margin_x = TRUE,
margin_y = TRUE
)
g$name <- grobName(g, "guide.label")
g
})
}
widths <- width_cm(grob)
heights <- height_cm(grob)
blanks <- rep(0, prod(dim) - n)
widths <- apply(
matrix(c(widths, blanks), dim[1], dim[2], byrow = guide$byrow), 2, max
)
heights <- apply(
matrix(c(heights, blanks), dim[1], dim[2], byrow = guide$byrow), 1, max
)
list(grob = grob,
width = widths,
height = heights,
hjust = hjust,
vjust = vjust,
theme = label.theme)
}
render_legend_title <- function(guide, theme) {
title.theme <- guide$title.theme %||% calc_element("legend.title", theme)
hjust <- guide$title.hjust %||% theme$legend.title.align %||%
title.theme$hjust %||% 0
vjust <- guide$title.vjust %||% title.theme$vjust %||% 0.5
grob <- element_grob(
title.theme,
label = guide$title,
hjust = hjust,
vjust = vjust,
margin_x = TRUE,
margin_y = TRUE
)
grob$name <- grobName(grob, "guide.title")
width <- width_cm(grob)
height <- height_cm(grob)
fontsize <- title.theme$size %||%
calc_element("legend.title", theme)$xize %||%
calc_element("text", theme)$size %||% 11
list(grob = grob,
width = width,
height = height,
fontsize = fontsize,
hjust = hjust,
vjust = vjust,
theme = title.theme)
}
utils::globalVariables(c("C", "R", "label.row", "label.col"))
height_cm <- function(x) {
if (is.grob(x)) {
convertHeight(grobHeight(x), "cm", TRUE)
} else if (is.unit(x)) {
convertHeight(x, "cm", TRUE)
} else if (is.list(x)) {
vapply(x, height_cm, numeric(1))
} else {
rlang::abort("Unknown input")
}
}
width_cm <- function(x) {
if (is.grob(x)) {
convertWidth(grobWidth(x), "cm", TRUE)
} else if (is.unit(x)) {
convertWidth(x, "cm", TRUE)
} else if (is.list(x)) {
vapply(x, width_cm, numeric(1))
} else {
rlang::abort("Unknown input")
}
} |
cadence.predict <-
function(x, fit)
{
if(!is.matrix(x)) stop("\"x\" must be a matrix")
if("W1" %in% names(fit)) fit <- list(fit=fit)
pred <- list()
for(i in seq_along(fit)){
nh <- names(fit)[i]
hidden.fcn <- attr(fit[[nh]], "hidden.fcn")
distribution <- attr(fit[[nh]], "distribution")
x.center <- attr(fit[[nh]], "x.center")
x.scale <- attr(fit[[nh]], "x.scale")
if(attr(fit[[nh]], "stationary")) x <- x[,1,drop=FALSE]
x.pred <- sweep(x, 2, x.center, "-")
x.pred <- sweep(x.pred, 2, x.scale, "/")
pred[[nh]] <- cadence.evaluate(x.pred, fit[[nh]]$W1, fit[[nh]]$W2,
hidden.fcn, distribution)
}
if(i==1) pred <- pred[[1]]
pred
} |
supportsExpat <-
function()
{
@SUPPORTS_EXPAT@
}
supportsLibxml <-
function()
{
@SUPPORTS_LIBXML@
}
ADD_XML_OUTPUT_BUFFER = @ADD_XML_OUTPUT_BUFFER@ > 0 |
test_that("special cases are correct", {
expect_equal(str_split(NA, "")[[1]], NA_character_)
expect_equal(str_split(character(), ""), list())
})
test_that("str_split functions as expected", {
expect_equal(
str_split(c("bab", "cac", "dadad"), "a"),
list(c("b", "b"), c("c", "c"), c("d", "d", "d"))
)
})
test_that("str_split() can split by special patterns", {
expect_equal(str_split("ab", ""), list(c("a", "b")))
expect_equal(str_split("this that.", boundary("word")), list(c("this", "that")))
expect_equal(str_split("a-b", fixed("-")), list(c("a", "b")))
expect_equal(str_split("aXb", coll("X", ignore_case = TRUE)), list(c("a", "b")))
})
test_that("str_split() can control maximum number of splits", {
expect_equal(
str_split(c("a", "a-b"), n = 1, "-"),
list("a", "a-b")
)
expect_equal(
str_split(c("a", "a-b"), n = 3, "-"),
list("a", c("a", "b"))
)
})
test_that("str_split() checks its inputs", {
expect_snapshot(error = TRUE, {
str_split(letters[1:3], letters[1:2])
str_split("x", 1)
str_split("x", "x", n = 0)
})
})
test_that("str_split_1 takes string and returns character vector", {
expect_equal(str_split_1("abc", ""), c("a", "b", "c"))
expect_snapshot_error(str_split_1(letters, ""))
})
test_that("str_split_fixed pads with NA", {
expect_equal(
str_split_fixed(c("a", "a-b"), "-", 1),
cbind(c("a", "a-b")))
expect_equal(
str_split_fixed(c("a", "a-b"), "-", 2),
cbind(c("a", "a"), c(NA, "b"))
)
expect_equal(
str_split_fixed(c("a", "a-b"), "-", 3),
cbind(c("a", "a"), c(NA, "b"), c(NA, NA))
)
})
test_that("str_split_fixed check its inputs", {
expect_snapshot(str_split_fixed("x", "x", 0), error = TRUE)
})
test_that("str_split_i returns NA for absent components", {
expect_equal(str_split_i(c("a", "b-c"), "-", 1), c("a", "b"))
expect_equal(str_split_i(c("a", "b-c"), "-", 2), c(NA, "c"))
expect_equal(str_split_i(c("a", "b-c"), "-", 3), c(NA_character_, NA))
})
test_that("str_split_i check its inputs", {
expect_snapshot(str_split_i("x", "x", 0), error = TRUE)
}) |
cor.table <- function (x, cor.method = c("pearson","spearman"),
cor.type = c("standard", "contrast"))
{
cor.method <- match.arg(cor.method)
cor.type <- match.arg(cor.type)
if (identical(cor.type, "standard")) {
concorr <- list()
concorr$r <- cor(x, method = cor.method)
concorr$df <- dim(x)[1] - 2
}
else {
concorr <- list()
concorr$r <- cor(rbind(x, x * -1), method = cor.method)
concorr$df <- length(x[, 1]) - 1
}
t <- concorr$r * sqrt(concorr$df/(1 - concorr$r^2))
concorr$P <- 2*pt(t, concorr$df)
concorr$P[concorr$r>0]<-2*pt(t[concorr$r>0], concorr$df,lower.tail=FALSE)
concorr
} |
zip.reg <- function(target, dataset, wei = NULL, lgy = NULL) {
n <- length(target)
oop <- options(warn = -1)
on.exit( options(oop) )
if ( NCOL(dataset) == 0 ) {
if ( is.null(wei) ) {
mod <- Rfast::zip.mle(target)
lam <- mod$param[1]
prop <- mod$param[2]
res <- list(be = lam, prop = prop, loglik = mod$loglik, est = (1 - prop) * lam)
} else {
mod <- zipmle.wei(target, wei)
res <- list(be = mod$lam, prop = mod$prop, loglik = mod$loglik)
}
} else {
x <- model.matrix(target ~ ., as.data.frame(dataset) )
poia <- which(target == 0)
n0 <- length(poia) ; n1 <- n - n0
target1 <- target[ -poia ]
if ( is.null(wei) ) {
mod <- glm.fit(x[-poia, ], target1, family = poisson(log) )
p1 <- ( n0 - sum( exp( - mod$fitted.values ) ) ) / n
g1 <- log( p1 / ( 1 - p1 ) )
pa <- c( g1, mod$coefficients)
pa[is.na(pa)] <- rnorm( sum(is.na(pa)) )
lik <- nlm( regzip, pa, y1 = target1, x = x, n1 = n1, poia = poia, iterlim = 10000 )
lik2 <- optim( lik$estimate, regzip, y1 = target1, x = x, n1 = n1, poia = poia, control = list(maxit = 10000) )
if ( is.null(lgy) ) lgy <- sum( lgamma(target1 + 1) )
} else {
wei <- wei / sum(wei)
w0 <- wei[poia] ; w1 <- wei[-poia]
mod <- glm.fit(x[-poia, ], target1, family = poisson(log), weights = w1 )
p1 <- ( n0 - sum( exp( - mod$fitted.values ) ) ) / n
g1 <- log( p1 / ( 1 - p1 ) )
pa <- c( g1, mod$coefficients)
pa[is.na(pa)] <- rnorm( sum(is.na(pa)) )
lik <- nlm( regzipwei, pa, y1 = target1, x = x, n1 = n1, w1 = w1, w0 = w0, iterlim = 10000 )
lik2 <- optim( lik$estimate, regzipwei, y1 = target1, x = x, n1 = n1, w1 = w1, w0 = w0, control = list(maxit = 10000) )
if ( is.null(lgy) ) lgy <- sum( w1 * lgamma(target1 + 1) )
}
prop <- exp(lik2$par[1]) / ( 1 + exp(lik2$par[1]) )
res <- list(be = lik2$par[-1], prop = prop, loglik = -lik2$value - lgy)
}
res
} |
ChaoSpecies <- function(data, datatype = c("abundance","abundance_freq_count", "incidence_freq", "incidence_freq_count", "incidence_raw"), k = 10, conf = 0.95)
{
if (is.matrix(data) == T || is.data.frame(data) == T){
if(datatype != "incidence_raw"){
if (ncol(data) == 1){
data <- data[, 1]
} else {
data <- data[1, ]
}
} else{
t <- ncol(data)
dat <- rowSums(data)
dat <- as.integer(dat)
t_infreq <- sum(colSums(data[which(dat<k),])>=1)
data <- dat
data <- c(t_infreq, t , data)
}
}
if(datatype == "abundance_freq_count"){
data <- as.integer(data)
length4b <- length(data)
data <- rep(data[seq(1,length4b,2)],data[seq(2,length4b,2)])
names(data) <- paste("x",1:length(data),sep="")
datatype <- "abundance"
}
if (datatype == "incidence_freq_count"){
t <- as.integer(data[1])
data <- data[-c(1)]
data <- as.integer(data)
lengthdat <- length(data)
data <- rep(data[seq(1,lengthdat,2)],data[seq(2,lengthdat,2)])
data <- c(t,data)
names(data) <- c("T", paste("y",1:(length(data)-1),sep=""))
datatype <- "incidence_freq"
}
method <- "all"
if (k != round(k) || k < 0)
stop("Error: The cutoff t to define less abundant species must be non-negative integer!")
if (is.numeric(conf) == FALSE || conf > 1 || conf < 0)
stop("Error: confidence level must be a numerical value between 0 and 1, e.g. 0.95")
if (datatype == "abundance"){
f <- function(i, data){length(data[which(data == i)])}
if (f(1, data) == sum(data)){
stop("Error: The information of data is not enough.")}
z <- (list(Basic_data_information = basicAbun(data, k)[[1]], Rare_species_group = RareSpeciesGroup(data, k),
Species_table = round(SpecAbunOut(data, method, k, conf), 3)))
} else if (datatype == "incidence_raw"){
dat <- data[-1]; Q <- function(i, data){length(data[which(data == i)])}
if (Q(1, dat) == sum(dat)){
stop("Error: The information of data is not enough.")}
z <- (list(Basic_data_information = basicInci(data[-1], k)[[1]], Infreq_species_group = InfreqSpeciesGroup(data[-1], k),
Species_table = round(SpecInciOut_raw(data, method, k, conf),3)))
} else if (datatype == "incidence_freq"){
dat <- data[-1];
Q <- function(i, data){length(data[which(data == i)])}
if (Q(1, dat) == sum(dat)){
stop("Error: The information of data is not enough.")}
z <- (list(Basic_data_information = basicInci(data, k)[[1]], Infreq_species_group = InfreqSpeciesGroup(data, k),
Species_table = round(SpecInciOut(data, method, k, conf),3)))
}
else{
stop("Error: The data type is wrong.")
}
class(z) <- c("ChaoSpecies")
z
}
ChaoShared <-
function(data, datatype = c("abundance", "incidence_freq", "incidence_raw"), units,
se = TRUE, nboot = 200, conf = 0.95) {
method <- "all"
if (se == TRUE) {
if (nboot < 1)
nboot <- 1
if (nboot == 1)
cat("Warning: When \"nboot\" =" ,nboot, ", the bootstrap s.e. and confidence interval can't be calculated.",
"\n\n")
}
if (is.numeric(conf) == FALSE || conf > 1 || conf < 0) {
cat("Warning: \"conf\"(confidence level) must be a numerical value between 0 and 1, e.g. 0.95.",
"\n")
cat(" We use \"conf\" = 0.95 to calculate!",
"\n\n")
conf <- 0.95
}
datatype <- match.arg(datatype)
if (datatype == "abundance") {
if(class(data)=="list"){data <-cbind(data[[1]],data[[2]]) }
x1 <- data[, 1]
x2 <- data[, 2]
Basic <- BasicFun(x1, x2, nboot, datatype)
output <- ChaoShared.Ind(x1, x2, method, nboot, conf, se)
colnames(output) <- c("Estimate", "s.e.", paste(conf*100,"%Lower",sep=""), paste(conf*100,"%Upper",sep=""))
}
if (datatype == "incidence_freq") {
if(class(data)=="list"){data <-cbind(data[[1]],data[[2]]) }
y1 <- data[, 1]
y2 <- data[, 2]
Basic <- BasicFun(y1, y2, B=nboot, datatype)
output <- ChaoShared.Sam(y1, y2, method, conf, se)
colnames(output) <- c("Estimate", "s.e.", paste(conf*100,"%Lower",sep=""), paste(conf*100,"%Upper",sep=""))
}
if (datatype=="incidence_raw"){
t = units
if(ncol(data) != sum(t)) stop("Number of columns does not euqal to the sum of key in sampling units")
dat <- matrix(0, ncol = length(t), nrow = nrow(data))
n <- 0
for(i in 1:length(t)){
dat[, i] <- as.integer(rowSums(data[,(n+1):(n+t[i])] ) )
n <- n+t[i]
}
t <- as.integer(t)
dat <- apply(dat, MARGIN = 2, as.integer)
dat <- data.frame(rbind(t, dat),row.names = NULL)
y1 <- dat[,1]
y2 <- dat[,2]
datatype = "incidence_freq"
Basic <- BasicFun(y1, y2, B=nboot, datatype)
output <- ChaoShared.Sam(y1, y2, method, conf, se)
colnames(output) <- c("Estimate", "s.e.", paste(conf*100,"%Lower",sep=""), paste(conf*100,"%Upper",sep=""))
}
out <- list(Basic_data_information=Basic,
Estimation_results=output)
class(out) <- c("ChaoShared")
return(out)
}
Diversity=function(data, datatype=c("abundance","abundance_freq_count", "incidence_freq", "incidence_freq_count", "incidence_raw"), q=NULL)
{
if (is.matrix(data) == T || is.data.frame(data) == T){
if(datatype != "incidence_raw"){
if (ncol(data) == 1){
data <- data[, 1]
} else {
data <- as.vector(data[1, ])
}
} else{
t <- ncol(data)
dat <- rowSums(data)
dat <- as.integer(dat)
data <- c(t , dat)
}
}
X <- data
if(datatype == "abundance_freq_count"){
data <- as.integer(data)
length4b <- length(data)
data <- rep(data[seq(1,length4b,2)],data[seq(2,length4b,2)])
names(data) <- paste("x",1:length(data),sep="")
datatype <- "abundance"
X <- data
}
if(datatype=="abundance"){
type="abundance"
if(!is.vector(X)) X <- as.numeric(unlist(c(X)))
BASIC.DATA <- matrix(round(c(sum(X), sum(X>0), 1-sum(X==1)/sum(X), CV.Ind(X)),3), ncol = 1)
nickname <- matrix(c("n", "D", "C", "CV"), ncol = 1)
BASIC.DATA <- cbind(nickname, BASIC.DATA)
colnames(BASIC.DATA) <- c("Variable", "Value")
rownames(BASIC.DATA) <- c(" Sample size", " Number of observed species",
" Estimated sample coverage",
" Estimated CV")
BASIC.DATA <- data.frame(BASIC.DATA)
table0 <- matrix(0,5,4)
table0[1,]=c(Chao1(X)[-5])
table0[2,]=c(Chao1_bc(X))
table0[3,]=round(SpecAbuniChao1(X, k=10, conf=0.95)[1,],1)
table0[4,]=round(c(SpecAbunAce(X)),1)
table0[5,]=round(c(SpecAbunAce1(X)),1)
colnames(table0) <- c("Estimate", "s.e.", paste(Chao1(X)[5]*100,"%Lower", sep=""), paste(Chao1(X)[5]*100,"%Upper", sep=""))
rownames(table0) <- c(" Chao1 (Chao, 1984)"," Chao1-bc ", " iChao1"," ACE (Chao & Lee, 1992)",
" ACE-1 (Chao & Lee, 1992)")
SHANNON=Shannon_index(X)
table1=round(SHANNON[c(1:5),],3)
table1=table1[-2,]
colnames(table1) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table1) <- c(" MLE"," Jackknife",
" Chao & Shen"," Chao et al. (2013)")
table1_exp=round(SHANNON[c(6:10),],3)
table1_exp=table1_exp[-2,]
colnames(table1_exp) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table1_exp) <- c(" MLE"," Jackknife",
" Chao & Shen"," Chao et al. (2013)")
table2=round(Simpson_index(X)[c(1:2),],5)
colnames(table2) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table2) <- c(" MVUE"," MLE")
table2_recip=round(Simpson_index(X)[c(3:4),],5)
colnames(table2_recip) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table2_recip) <- c(" MVUE"," MLE")
if(is.null(q)){Hill <- reshapeChaoHill(ChaoHill(X, datatype = "abundance", q=NULL, from=0, to=3, interval=0.25, B=50, conf=0.95))}
if(!is.null(q)){Hill <- reshapeChaoHill(ChaoHill(X, datatype = "abundance", q=q, from=0, to=3, interval=0.25, B=50, conf=0.95))}
q_length<-length(Hill[,1])/2
Chao.LCL <- Hill[(q_length+1):(2*q_length),3] - 1.96*Hill[(q_length+1):(2*q_length),4]
Chao.UCL <- Hill[(q_length+1):(2*q_length),3] + 1.96*Hill[(q_length+1):(2*q_length),4]
Emperical.LCL <- Hill[1:q_length,3] - 1.96*Hill[1:q_length,4]
Emperical.UCL <- Hill[1:q_length,3] + 1.96*Hill[1:q_length,4]
Hill<-cbind(Hill[1:q_length,1],Hill[(q_length+1):(2*q_length),3],Chao.LCL,Chao.UCL,Hill[1:q_length,3],Emperical.LCL,Emperical.UCL)
Hill<-round(Hill,3)
Hill <- data.frame(Hill)
colnames(Hill)<-c("q","ChaoJost","95%Lower","95%Upper","Empirical","95%Lower","95%Upper")
q_hill <- nrow(Hill)
rownames(Hill) <- paste(" ",1:q_hill)
z <- list("datatype"= type,"Basic_data"=BASIC.DATA,"Species_richness"=table0,
"Shannon_index"=table1,"Shannon_diversity"=table1_exp,
"Simpson_index"=table2,"Simpson_diversity"=table2_recip,
"Hill_numbers"= Hill)
}
if(datatype == "incidence_freq_count"){
t <- as.integer(data[1])
data <- data[-c(1)]
data <- as.integer(data)
lengthdat <- length(data)
data <- rep(data[seq(1,lengthdat,2)],data[seq(2,lengthdat,2)])
data <- c(t,data)
names(data) <- c("T", paste("y",1:(length(data)-1),sep=""))
datatype <- "incidence_freq"
X <- data
}
if(datatype=="incidence_freq"){
if(!is.vector(X)) X <- as.numeric(unlist(c(X)))
type="incidence"
U<-sum(X[-1])
D<-sum(X[-1]>0)
T<-X[1]
C<-Chat.Sam(X,T)
CV_squre<-max( D/C*T/(T-1)*sum(X[-1]*(X[-1]-1))/U^2-1, 0)
CV<-CV_squre^0.5
BASIC.DATA <- matrix(round(c(D,T,U, C, CV),3), ncol = 1)
nickname <- matrix(c("D", "T","U", "C", "CV"), ncol = 1)
BASIC.DATA <- cbind(nickname, BASIC.DATA)
colnames(BASIC.DATA) <- c("Variable", "Value")
rownames(BASIC.DATA) <- c(" Number of observed species", " Number of Sampling units"," Total number of incidences",
" Estimated sample coverage",
" Estimated CV")
BASIC.DATA <- data.frame(BASIC.DATA)
table0=SpecInci(X, k=10, conf=0.95)
rownames(table0) <- c(" Chao2 (Chao, 1987)"," Chao2-bc ", " iChao2"," ICE (Lee & Chao, 1994)",
" ICE-1 (Lee & Chao, 1994)")
SHANNON=Shannon_Inci_index(X)
table1=round(SHANNON[c(1,4),],3)
colnames(table1) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table1) <- c(" MLE"," Chao et al. (2013)")
table1_exp=round(SHANNON[c(5,8),],3)
colnames(table1_exp) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table1_exp) <- c(" MLE"," Chao et al. (2013)")
SIMPSON=Simpson_Inci_index(X)
table2=round(SIMPSON[c(1:2),],5)
colnames(table2) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table2) <- c(" MVUE"," MLE")
table2_recip=round(SIMPSON[c(3:4),],5)
colnames(table2_recip) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table2_recip) <- c(" MVUE"," MLE")
if(is.null(q)){Hill <- reshapeChaoHill(ChaoHill(X, datatype = "incidence_freq", q=NULL, from=0, to=3, interval=0.25, B=50, conf=0.95))}
if(!is.null(q)){Hill <- reshapeChaoHill(ChaoHill(X, datatype = "incidence_freq", q=q, from=0, to=3, interval=0.25, B=50, conf=0.95))}
q_length<-length(Hill[,1])/2
Chao.LCL <- Hill[(q_length+1):(2*q_length),3] - 1.96*Hill[(q_length+1):(2*q_length),4]
Chao.UCL <- Hill[(q_length+1):(2*q_length),3] + 1.96*Hill[(q_length+1):(2*q_length),4]
Emperical.LCL <- Hill[1:q_length,3] - 1.96*Hill[1:q_length,4]
Emperical.UCL <- Hill[1:q_length,3] + 1.96*Hill[1:q_length,4]
Hill<-cbind(Hill[1:q_length,1],Hill[(q_length+1):(2*q_length),3],Chao.LCL,Chao.UCL,Hill[1:q_length,3],Emperical.LCL,Emperical.UCL)
Hill<-round(Hill,3)
Hill <- data.frame(Hill)
colnames(Hill)<-c("q","ChaoJost","95%Lower","95%Upper","Empirical","95%Lower","95%Upper")
q_hill <- nrow(Hill)
rownames(Hill) <- paste(" ",1:q_hill)
z <- list("datatype"= type,"Basic_data"=BASIC.DATA,"Species_richness"=table0,
"Shannon_index"=table1,"Shannon_diversity"=table1_exp,
"Simpson_index"=table2,"Simpson_diversity"=table2_recip,
"Hill_numbers"= Hill)
}
if(datatype=="incidence_raw"){
type="incidence"
datatype = "incidence_freq"
U<-sum(X[-1])
D<-sum(X[-1]>0)
T<-X[1]
C<-Chat.Sam(X,T)
CV_squre<-max( D/C*T/(T-1)*sum(X[-1]*(X[-1]-1))/U^2-1, 0)
CV<-CV_squre^0.5
BASIC.DATA <- matrix(round(c(D,T,U, C, CV),3), ncol = 1)
nickname <- matrix(c("D", "T","U", "C", "CV"), ncol = 1)
BASIC.DATA <- cbind(nickname, BASIC.DATA)
colnames(BASIC.DATA) <- c("Variable", "Value")
rownames(BASIC.DATA) <- c(" Number of observed species", " Number of Sampling units"," Total number of incidences",
" Estimated sample coverage",
" Estimated CV")
BASIC.DATA <- data.frame(BASIC.DATA)
table0=SpecInci(X, k=10, conf=0.95)
rownames(table0) <- c(" Chao2 (Chao, 1987)"," Chao2-bc ", " iChao2"," ICE (Lee & Chao, 1994)",
" ICE-1 (Lee & Chao, 1994)")
SHANNON=Shannon_Inci_index(X)
table1=round(SHANNON[c(1,4),],3)
colnames(table1) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table1) <- c(" MLE"," Chao et al. (2013)")
table1_exp=round(SHANNON[c(5,8),],3)
colnames(table1_exp) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table1_exp) <- c(" MLE"," Chao et al. (2013)")
SIMPSON=Simpson_Inci_index(X)
table2=round(SIMPSON[c(1:2),],5)
colnames(table2) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table2) <- c(" MVUE"," MLE")
table2_recip=round(SIMPSON[c(3:4),],5)
colnames(table2_recip) <- c("Estimate", "s.e.", paste("95%Lower"), paste("95%Upper"))
rownames(table2_recip) <- c(" MVUE"," MLE")
if(is.null(q)){Hill <- reshapeChaoHill(ChaoHill(X, datatype = "incidence", q=NULL, from=0, to=3, interval=0.25, B=50, conf=0.95))}
if(!is.null(q)){Hill <- reshapeChaoHill(ChaoHill(X, datatype = "incidence", q=q, from=0, to=3, interval=0.25, B=50, conf=0.95))}
q_length<-length(Hill[,1])/2
Chao.LCL <- Hill[(q_length+1):(2*q_length),3] - 1.96*Hill[(q_length+1):(2*q_length),4]
Chao.UCL <- Hill[(q_length+1):(2*q_length),3] + 1.96*Hill[(q_length+1):(2*q_length),4]
Emperical.LCL <- Hill[1:q_length,3] - 1.96*Hill[1:q_length,4]
Emperical.UCL <- Hill[1:q_length,3] + 1.96*Hill[1:q_length,4]
Hill<-cbind(Hill[1:q_length,1],Hill[(q_length+1):(2*q_length),3],Chao.LCL,Chao.UCL,Hill[1:q_length,3],Emperical.LCL,Emperical.UCL)
Hill<-round(Hill,3)
Hill <- data.frame(Hill)
colnames(Hill)<-c("q","ChaoJost","95%Lower","95%Upper","Empirical","95%Lower","95%Upper")
q_hill <- nrow(Hill)
rownames(Hill) <- paste(" ",1:q_hill)
z <- list("datatype"= type,"Basic_data"=BASIC.DATA,"Species_richness"=table0,
"Shannon_index"=table1,"Shannon_diversity"=table1_exp,
"Simpson_index"=table2,"Simpson_diversity"=table2_recip,
"Hill_numbers"= Hill)
}
class(z) <- c("spadeDiv")
return(z)
}
SimilarityPair=function(X, datatype = c("abundance","incidence_freq", "incidence_raw"), units,nboot=200)
{
if(datatype=="abundance")
{
if(class(X)=="list"){X <- do.call(cbind,X)}
type <- "abundance"
info1 <- c("S.total"=sum(rowSums(X)>0), "n1"=sum(X[,1]), "n2"=sum(X[,2]),
"D1"=sum(X[,1]>0), "D2"=sum(X[,2]>0), "D12"=sum(X[,1]>0 & X[,2]>0),
"nboot"=nboot)
info2 <- c("f[11]"=sum(X[,1]==1 & X[,2]==1),
"f[1+]"=sum(X[,1]==1 & X[,2]>0), "f[+1]"=sum(X[,1]>0 & X[,2]==1),
"f[2+]"=sum(X[,1]==2 & X[,2]>0), "f[+2]"=sum(X[,1]>0 & X[,2]==2),"f[22]"=sum(X[,1]==2 & X[,2]==2))
info <- c(info1, info2)
plus_CI <-function(x){
if(x[1] >= 1) x[1] <- 1
if(x[1] <= 0) x[1] <- 0
c(x, max(0,x[1]-1.96*x[2]), min(1,x[1]+1.96*x[2]))
}
temp <- list()
weight <- c(sum(X[,1])/(sum(X[,1])+sum(X[,2])), sum(X[,2])/(sum(X[,1])+sum(X[,2])))
weight <- - sum(weight*log(weight)) / log(2)
mat <- Jaccard_Sorensen_Abundance_equ(datatype,X[, 1],X[, 2], nboot)[, c(1, 2)]
mat <- cbind(mat, mat[, 1]-1.96*mat[, 2], mat[, 1]+1.96*mat[, 2])
MLE_Jaccard <- mat[1, ]
Est_Jaccard <- mat[2, ]
MLE_Sorensen <- mat[3, ]
Est_Sorensen <- mat[4, ]
mat2 <- Two_Horn_equ(X[,1], X[,2], method="all", weight="unequal", nboot = nboot)
MLE_Ee_Horn <- mat2$mle
MLE_Ee_Horn <- plus_CI(c(MLE_Ee_Horn[1],MLE_Ee_Horn[2]))
Est_Ee_Horn <- mat2$est
MLE_Ee_U12 <- plus_CI(c(weight*MLE_Ee_Horn[1],MLE_Ee_Horn[2]))
Est_Ee_U12 <- plus_CI(c(weight*Est_Ee_Horn[1],Est_Ee_Horn[2]))
mat3 <- Two_BC_equ(X[, 1],X[, 2], datatype="abundance", nboot)
MLE_Ee_Braycurtis <- mat3$mle
Est_Ee_Braycurtis <- mat3$est
mat4 <- SimilarityTwo(X,2,nboot,method="unequal weight")
MLE_Ee_C22 <- mat4$CqN[1, ]
Est_Ee_C22 <- mat4$CqN[2, ]
MLE_Ee_U22 <- mat4$UqN[1, ]
Est_Ee_U22 <- mat4$UqN[2, ]
mat5 <- Two_Horn_equ(X[,1], X[,2], method="all", weight="equal", nboot = nboot)
MLE_ew_Horn <- mat5$mle
Est_ew_Horn <- mat5$est
mat6 <- SimilarityTwo(X,2,nboot,method="equal weight")
MLE_ew_C22 <- mat6$CqN[1, ]
Est_ew_C22 <- mat6$CqN[2, ]
MLE_ew_U22 <- mat6$UqN[1, ]
Est_ew_U22 <- mat6$UqN[2, ]
MLE_ew_ChaoSoresen <- mat[11,]
Est_ew_ChaoSoresen <- mat[12, ]
MLE_ew_ChaoJaccard <- mat[9, ]
Est_ew_ChaoJaccard <- mat[10, ]
temp[[1]] <- rbind(MLE_Sorensen, MLE_Jaccard)
rownames(temp[[1]]) <- c("C02(q=0,Sorensen)","U02(q=0,Jaccard)")
temp[[2]] <- rbind(MLE_ew_Horn, MLE_ew_C22, MLE_ew_U22, MLE_ew_ChaoJaccard, MLE_ew_ChaoSoresen)
rownames(temp[[2]]) <- c("C12=U12(q=1,Horn)","C22(q=2,Morisita)","U22(q=2,Regional overlap)",
"ChaoJaccard","ChaoSorensen")
temp[[3]] <- t(as.matrix(MLE_Ee_Horn))
rownames(temp[[3]]) <- c("Horn size weighted(q=1)")
temp[[4]] <- rbind(MLE_Ee_U12, MLE_Ee_C22, MLE_Ee_U22, MLE_Ee_Braycurtis)
rownames(temp[[4]]) <- c("C12=U12(q=1)","C22(Morisita)", "U22(Regional overlap)","Bray-Curtis")
temp[[5]] <- rbind(Est_Sorensen, Est_Jaccard)
rownames(temp[[5]]) <- c("C02(q=0,Sorensen)","U02(q=0,Jaccard)")
temp[[6]] <- rbind(Est_ew_Horn, Est_ew_C22, Est_ew_U22, Est_ew_ChaoJaccard, Est_ew_ChaoSoresen)
rownames(temp[[6]]) <- c("C12=U12(q=1,Horn)","C22(q=2,Morisita)","U22(q=2,Regional overlap)",
"ChaoJaccard","ChaoSorensen")
temp[[7]] <- t(as.matrix(Est_Ee_Horn))
rownames(temp[[7]]) <- c("Horn size weighted(q=1)")
temp[[8]] <- rbind(Est_Ee_U12, Est_Ee_C22, Est_Ee_U22, Est_Ee_Braycurtis)
temp <- lapply(temp, FUN = function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL")
return(x)
})
rownames(temp[[8]]) <- c("C12=U12(q=1)","C22(Morisita)", "U22(Regional overlap)","Bray-Curtis")
z <- list("datatype"=type,"info"=info, "Empirical_richness"=temp[[1]], "Empirical_relative"=temp[[2]], "Empirical_WtRelative"=temp[[3]],
"Empirical_absolute"=temp[[4]], "estimated_richness"=temp[[5]], "estimated_relative"=temp[[6]], "estimated_WtRelative"=temp[[7]], "estimated_absolute"=temp[[8]])
}
if(datatype=="incidence_raw"){
data <- X
t = units
if(ncol(data) != sum(t)) stop("Number of columns does not euqal to the sum of key in sampling units")
dat <- matrix(0, ncol = length(t), nrow = nrow(data))
n <- 0
for(i in 1:length(t)){
dat[, i] <- as.integer(rowSums(data[,(n+1):(n+t[i])] ) )
n <- n+t[i]
}
t <- as.integer(t)
dat <- apply(dat, MARGIN = 2, as.integer)
dat <- data.frame(rbind(t, dat),row.names = NULL)
y1 <- dat[,1]
y2 <- dat[,2]
X <- cbind(y1, y2)
type <- "incidence_freq"
X <- as.data.frame(X)
}
if(datatype=="incidence_freq") type <- "incidence_freq"
if(datatype=="incidence_freq" | type == "incidence_freq")
{
if(class(X)=="list"){X <- do.call(cbind,X)}
no.assemblage=length(X[1,])
Y=X[-1,]
type="incidence"
info1 <- c("S.total"=sum(rowSums(Y)>0), "T1"=X[1,1], "T2"=X[1,2], "U1"=sum(Y[,1]), "U2"=sum(Y[,2]),
"D1"=sum(Y[,1]>0), "D2"=sum(Y[,2]>0), "D12"=sum(Y[,1]>0 & Y[,2]>0),
"nboot"=nboot)
info2 <- c("Q[11]"=sum(Y[,1]==1 & Y[,2]==1),
"Q[1+]"=sum(Y[,1]==1 & Y[,2]>0), "Q[+1]"=sum(Y[,1]>0 & Y[,2]==1),
"Q[2+]"=sum(Y[,1]==2 & Y[,2]>0), "Q[+2]"=sum(Y[,1]>0 & Y[,2]==2), "Q[22]"=sum(Y[,1]==2 & Y[,2]==2))
info <- c(info1, info2)
plus_CI <-function(x){
if(x[1] >= 1) x[1] <- 1
if(x[1] <= 0) x[1] <- 0
c(x, max(0,x[1]-1.96*x[2]), min(1,x[1]+1.96*x[2]))
}
temp <- list()
weight <- c(sum(Y[,1])/(sum(Y[,1])+sum(Y[,2])), sum(Y[,2])/(sum(Y[,1])+sum(Y[,2])))
weight <- - sum(weight*log(weight)) / log(2)
mat <- Jaccard_Sorensen_Abundance_equ(datatype="incidence",X[, 1],X[, 2], nboot)[, c(1, 2)]
mat <- cbind(mat, mat[, 1]-1.96*mat[, 2], mat[, 1]+1.96*mat[, 2])
MLE_Jaccard <- mat[1, ]
Est_Jaccard <- mat[2, ]
MLE_Sorensen <- mat[3, ]
Est_Sorensen <- mat[4, ]
mat2 <- Two_Horn_equ(X[,1], X[,2], datatype = "incidence", method="all", weight="unequal", nboot)
MLE_Ee_Horn <- mat2$mle
MLE_Ee_Horn <- plus_CI(c(MLE_Ee_Horn[1],MLE_Ee_Horn[2]))
Est_Ee_Horn <- mat2$est
MLE_Ee_U12 <- plus_CI(c(weight*MLE_Ee_Horn[1],MLE_Ee_Horn[2]))
Est_Ee_U12 <- plus_CI(c(weight*Est_Ee_Horn[1],Est_Ee_Horn[2]))
mat3 <- C2N_ee_se_inc(X, nboot)
MLE_Ee_C22 <- plus_CI(mat3[1,])
Est_Ee_C22 <- plus_CI(mat3[3,])
MLE_Ee_U22 <- plus_CI(mat3[2,])
Est_Ee_U22 <- plus_CI(mat3[4,])
mat4 <- Two_Horn_equ(X[,1], X[,2], datatype = "incidence", method="all", weight="equal", nboot)
MLE_ew_Horn <- mat4$mle
Est_ew_Horn <- mat4$est
mat5 <- SimilarityTwo(X, 2, nboot, method="equal weight", datatype="incidence")
MLE_ew_C22 <- mat5$CqN[1, ]
Est_ew_C22 <- mat5$CqN[2, ]
MLE_ew_U22 <- mat5$UqN[1, ]
Est_ew_U22 <- mat5$UqN[2, ]
MLE_ew_ChaoSoresen <- mat[11,]
Est_ew_ChaoSoresen <- mat[12, ]
MLE_ew_ChaoJaccard <- mat[9, ]
Est_ew_ChaoJaccard <- mat[10, ]
mat5 <- Two_BC_equ(X[, 1],X[, 2], datatype="incidence", nboot)
MLE_Ee_Braycurtis <- mat5$mle
Est_Ee_Braycurtis <- mat5$est
temp[[1]] <- rbind(MLE_Sorensen, MLE_Jaccard)
rownames(temp[[1]]) <- c("C02(q=0,Sorensen)","U02(q=0,Jaccard)")
temp[[2]] <- rbind(MLE_ew_Horn, MLE_ew_C22, MLE_ew_U22, MLE_ew_ChaoJaccard, MLE_ew_ChaoSoresen)
rownames(temp[[2]]) <- c("C12=U12(q=1,Horn)","C22(q=2,Morisita)","U22(q=2,Regional overlap)",
"ChaoJaccard","ChaoSorensen")
temp[[3]] <- t(as.matrix(MLE_Ee_Horn))
rownames(temp[[3]]) <- c("Horn size weighted(q=1)")
temp[[4]] <- rbind(MLE_Ee_U12, MLE_Ee_C22, MLE_Ee_U22, MLE_Ee_Braycurtis)
rownames(temp[[4]]) <- c("C12=U12(q=1)","C22(Morisita)", "U22(Regional overlap)","Bray-Curtis")
temp[[5]] <- rbind(Est_Sorensen, Est_Jaccard)
rownames(temp[[5]]) <- c("C02(q=0,Sorensen)","U02(q=0,Jaccard)")
temp[[6]] <- rbind(Est_ew_Horn, Est_ew_C22, Est_ew_U22, Est_ew_ChaoJaccard, Est_ew_ChaoSoresen)
rownames(temp[[6]]) <- c("C12=U12(q=1,Horn)","C22(q=2,Morisita)","U22(q=2,Regional overlap)",
"ChaoJaccard","ChaoSorensen")
temp[[7]] <- t(as.matrix(Est_Ee_Horn))
rownames(temp[[7]]) <- c("Horn size weighted(q=1)")
temp[[8]] <- rbind(Est_Ee_U12, Est_Ee_C22, Est_Ee_U22, Est_Ee_Braycurtis)
rownames(temp[[8]]) <- c("C12=U12(q=1)","C22(Morisita)", "U22(Regional overlap)","Bray-Curtis")
temp <- lapply(temp, FUN = function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL")
return(x)
})
z <- list("datatype"=type,"info"=info, "Empirical_richness"=temp[[1]], "Empirical_relative"=temp[[2]], "Empirical_WtRelative"=temp[[3]],
"Empirical_absolute"=temp[[4]], "estimated_richness"=temp[[5]], "estimated_relative"=temp[[6]], "estimated_WtRelative"=temp[[7]], "estimated_absolute"=temp[[8]])
}
class(z) <- c("spadeTwo")
return(z)
}
SimilarityMult=function(X,datatype=c("abundance","incidence_freq", "incidence_raw"),units,q=2,nboot=200,goal="relative")
{
method <- goal
if(datatype=="abundance"){
if(class(X)=="list"){X <- do.call(cbind,X)}
type <- "abundance"
N <- no.community <- ncol(X)
temp <- c("N"=ncol(X), "S.total"=sum(rowSums(X)>0))
n <- apply(X,2,sum)
D <- apply(X,2,function(x)sum(x>0))
if(N > 2){
temp1 <- temp2 <- rep(0, N*(N-1)/2)
k <- 1
for(i in 1:(N-1)){
for(j in (i+1):N){
temp1[k] <- paste('D',i,j,sep="")
temp2[k] <- sum(X[,i]>0 & X[,j]>0)
k <- k + 1
}
}
}
names(temp2) <- temp1
names(n) <- paste('n',1:N, sep="")
names(D) <- paste('D',1:N, sep="")
info <- c(temp, n, D, temp2)
if(N == 3) info <- c(temp, n, D, temp2, D123=sum(X[,1]>0 & X[,2]>0 & X[,3]>0))
info <- c(info, nboot=nboot)
temp <- list()
plus_CI <-function(x){
if(x[1] >= 1) x[1] <- 1
if(x[1] <= 0) x[1] <- 0
c(x, max(0,x[1]-1.96*x[2]), min(1,x[1]+1.96*x[2]))
}
n <- apply(X = X, MARGIN = 2, FUN = sum)
weight <- n/sum(n)
weight <- - sum(weight*log(weight)) / log(N)
mat <- SimilarityMul(X, 0, nboot, method ="unequal weight")
MLE_Jaccard <- mat$UqN[1, ]
Est_Jaccard <- mat$UqN[2, ]
MLE_Sorensen <- mat$CqN[1, ]
Est_Sorensen <- mat$CqN[2, ]
mat2 <- Horn_Multi_equ(X, datatype="abundance", nboot, method=c("unequal"))
MLE_Ee_Horn <- mat2$mle
Est_Ee_Horn <- mat2$est
Est_Ee_U12 <- plus_CI(c(weight*Est_Ee_Horn[1], Est_Ee_Horn[2]))
MLE_Ee_U12 <- plus_CI(c(weight*MLE_Ee_Horn[1], MLE_Ee_Horn[2]))
mat3 <- BC_equ(X, datatype="abundance", nboot)
MLE_Ee_Braycurtis <- mat3$mle
Est_Ee_Braycurtis <- mat3$est
mat4 <- SimilarityMul(X,2,nboot,method="unequal weight")
MLE_Ee_C22 <- mat4$CqN[1, ]
Est_Ee_C22 <- mat4$CqN[2, ]
MLE_Ee_U22 <- mat4$UqN[1, ]
Est_Ee_U22 <- mat4$UqN[2, ]
mat5 <- Horn_Multi_equ(X, datatype="abundance", nboot, method=c("equal"))
MLE_ew_Horn <- mat5$mle
Est_ew_Horn <- mat5$est
mat6 <- SimilarityMul(X,2,nboot,method="equal weight")
MLE_ew_C22 <- mat6$CqN[1, ]
Est_ew_C22 <- mat6$CqN[2, ]
MLE_ew_U22 <- mat6$UqN[1, ]
Est_ew_U22 <- mat6$UqN[2, ]
temp[[1]] <- rbind(MLE_Sorensen, MLE_Jaccard)
rownames(temp[[1]]) <- c("C0N(q=0,Sorensen)","U0N(q=0,Jaccard)")
temp[[2]] <- rbind(MLE_ew_Horn, MLE_ew_C22, MLE_ew_U22)
rownames(temp[[2]]) <- c("C1N=U1N(q=1,Horn)","C2N(q=2,Morisita)","U2N(q=2,Regional overlap)")
temp[[3]] <- t(as.matrix(MLE_Ee_Horn))
rownames(temp[[3]]) <- c("Horn size weighted(q=1)")
temp[[4]] <- rbind(MLE_Ee_U12, MLE_Ee_C22, MLE_Ee_U22, MLE_Ee_Braycurtis)
rownames(temp[[4]]) <- c("C1N=U1N(q=1)","C2N(Morisita)", "U2N(Regional overlap)","Bray-Curtis")
temp[[5]] <- rbind(Est_Sorensen, Est_Jaccard)
rownames(temp[[5]]) <- c("C0N(q=0,Sorensen)","U0N(q=0,Jaccard)")
temp[[6]] <- rbind(Est_ew_Horn, Est_ew_C22, Est_ew_U22)
rownames(temp[[6]]) <- c("C1N=U1N(q=1,Horn)","C2N(q=2,Morisita)","U2N(q=2,Regional overlap)")
temp[[7]] <- t(as.matrix(Est_Ee_Horn))
rownames(temp[[7]]) <- c("Horn size weighted(q=1)")
temp[[8]] <- rbind(Est_Ee_U12, Est_Ee_C22, Est_Ee_U22, Est_Ee_Braycurtis)
rownames(temp[[8]]) <- c("C1N=U1N(q=1)","C2N(Morisita)", "U2N(Regional overlap)","Bray-Curtis")
temp <- lapply(temp, FUN = function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL")
return(x)
})
if(q == 0){
temp_PC <- rep(0, N*(N-1)/2)
C02=matrix(0,choose(no.community,2),4)
U02=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
mat <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal effort')
C02[k,] <- mat[1, ]
U02[k,] <- mat[2, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C02[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- U02[k,1]
k <- k+1
}
}
Cqn_PC <- list("C02"=C02, "U02"=U02)
C_SM <- list("C02"=C_SM_1, "U02"=C_SM_2)
}
if(q == 1 & method=="relative"){
temp_PC <- rep(0, N*(N-1)/2)
C12=matrix(0,choose(no.community,2),4)
Horn=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
C12[k,] <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal weight')[1, ]
Horn[k,] <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal effort')[2, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C12[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- Horn[k,1]
k <- k+1
}
}
Cqn_PC <- list("C12"=C12, "Horn"=Horn)
C_SM <- list("C12"=C_SM_1, "Horn"=C_SM_2)
}
if(q == 1 & method=="absolute"){
temp_PC <- rep(0, N*(N-1)/2)
k=1
C_SM_1=matrix(1,N,N)
C12=matrix(0,choose(no.community,2),4)
for(i in 1:(N-1)){
for(j in (i+1):N){
C12[k,] <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal effort')[1, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C12[k,1]
k <- k+1
}
}
Cqn_PC <- list("C12"=C12)
C_SM <- list("C12"=C_SM_1)
}
if(q == 2){
temp_PC <- rep(0, N*(N-1)/2)
if(method=="absolute") method2 <- 'equal effort'
if(method=="relative") method2 <- 'equal weight'
C22=matrix(0,choose(no.community,2),4)
U22=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
mat <- Cq2_est_equ(X[,c(i,j)], q, nboot, method=method2)
C22[k,] <- mat[1, ]
U22[k,] <- mat[2, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C22[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- U22[k,1]
k <- k+1
}
}
Cqn_PC <- list("C22"=C22, "U22"=U22)
C_SM <- list("C22"=C_SM_1,"U22"=C_SM_2)
}
Cqn_PC <- lapply(Cqn_PC, function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL") ; rownames(x) <- temp_PC
return(x)
})
z <- list("datatype"=datatype,"info"=info, "Empirical_richness"=temp[[1]], "Empirical_relative"=temp[[2]], "Empirical_WtRelative"=temp[[3]],
"Empirical_absolute"=temp[[4]], "estimated_richness"=temp[[5]], "estimated_relative"=temp[[6]], "estimated_WtRelative"=temp[[7]], "estimated_absolute"=temp[[8]], "pairwise"=Cqn_PC, "similarity.matrix"=C_SM, "goal"=method, "q"=q)
}
if(datatype == "incidence_raw"){
data <- X
t = units
if(ncol(data) != sum(t)) stop("Number of columns does not euqal to the sum of key in sampling units")
dat <- matrix(0, ncol = length(t), nrow = nrow(data))
n <- 0
for(i in 1:length(t)){
dat[, i] <- as.integer(rowSums(data[,(n+1):(n+t[i])] ) )
n <- n+t[i]
}
t <- as.integer(t)
dat <- apply(dat, MARGIN = 2, as.integer)
X <- data.frame(rbind(t, dat),row.names = NULL)
if(ncol(X) <= 2) stop("Multiple Commumity measures is only for the data which has three community or more")
type = "incidence_freq"
}
if(datatype=="incidence_freq") type <- "incidence_freq"
if(datatype=="incidence_freq" | type == "incidence_freq"){
if(class(X)=="list"){X <- do.call(cbind,X)}
type <- "incidence"
Y <- X
X <- X[-1,]
t <- as.vector(Y[1,])
N <- no.community <- ncol(X)
temp <- c("N"=ncol(X), "S.total"=sum(rowSums(X)>0))
n <- apply(X,2,sum)
D <- apply(X,2,function(x)sum(x>0))
if(N > 2){
temp1 <- temp2 <- rep(0, N*(N-1)/2)
k <- 1
for(i in 1:(N-1)){
for(j in (i+1):N){
temp1[k] <- paste('D',i,j,sep="")
temp2[k] <- sum(X[,i]>0 & X[,j]>0)
k <- k + 1
}
}
}
names(temp2) <- temp1
names(t) <- paste('T',1:N, sep="")
names(n) <- paste('u',1:N, sep="")
names(D) <- paste('D',1:N, sep="")
info <- c(temp, t, n, D, temp2)
if(N == 3) info <- c(temp, t, n, D, temp2, D123=sum(X[,1]>0 & X[,2]>0 & X[,3]>0))
info <- unlist(c(info, nboot=nboot))
temp <- list()
plus_CI <-function(x){
if(x[1] >= 1) x[1] <- 1
if(x[1] <= 0) x[1] <- 0
c(x, max(0,x[1]-1.96*x[2]), min(1,x[1]+1.96*x[2]))
}
n <- apply(X = X, MARGIN = 2, FUN = sum)
weight <- n/sum(n)
weight <- - sum(weight*log(weight)) / log(N)
mat <- SimilarityMul(Y, 0, nboot, method ="unequal weight", datatype="incidence")
MLE_Jaccard <- mat$UqN[1, ]
Est_Jaccard <- mat$UqN[2, ]
MLE_Sorensen <- mat$CqN[1, ]
Est_Sorensen <- mat$CqN[2, ]
mat2 <- Horn_Multi_equ(Y, datatype="incidence", nboot, method=c("unequal"))
MLE_Ee_Horn <- mat2$mle
Est_Ee_Horn <- mat2$est
Est_Ee_U12 <- plus_CI(c(weight*Est_Ee_Horn[1], Est_Ee_Horn[2]))
MLE_Ee_U12 <- plus_CI(c(weight*MLE_Ee_Horn[1], MLE_Ee_Horn[2]))
mat3 <- BC_equ(Y, datatype="incidence", nboot)
MLE_Ee_Braycurtis <- mat3$mle
Est_Ee_Braycurtis <- mat3$est
mat4 <- C2N_ee_se_inc(Y, nboot)
MLE_Ee_C22 <- plus_CI(mat4[1, ])
Est_Ee_C22 <- plus_CI(mat4[3, ])
MLE_Ee_U22 <- plus_CI(mat4[2, ])
Est_Ee_U22 <- plus_CI(mat4[4, ])
mat5 <- Horn_Multi_equ(Y, datatype="incidence", nboot, method=c("equal"))
MLE_ew_Horn <- mat5$mle
Est_ew_Horn <- mat5$est
mat6 <- SimilarityMul(Y, 2, nboot, datatype = "incidence", method="equal weight")
MLE_ew_C22 <- mat6$CqN[1, ]
Est_ew_C22 <- mat6$CqN[2, ]
MLE_ew_U22 <- mat6$UqN[1, ]
Est_ew_U22 <- mat6$UqN[2, ]
temp[[1]] <- rbind(MLE_Sorensen, MLE_Jaccard)
rownames(temp[[1]]) <- c("C0N(q=0,Sorensen)","U0N(q=0,Jaccard)")
temp[[2]] <- rbind(MLE_ew_Horn, MLE_ew_C22, MLE_ew_U22)
rownames(temp[[2]]) <- c("C1N=U1N(q=1,Horn)","C2N(q=2,Morisita)","U2N(q=2,Regional overlap)")
temp[[3]] <- t(as.matrix(MLE_Ee_Horn))
rownames(temp[[3]]) <- c("Horn size weighted(q=1)")
temp[[4]] <- rbind(MLE_Ee_U12, MLE_Ee_C22, MLE_Ee_U22, MLE_Ee_Braycurtis)
rownames(temp[[4]]) <- c("C1N=U1N(q=1)","C2N(Morisita)", "U2N(Regional overlap)","Bray-Curtis")
temp[[5]] <- rbind(Est_Sorensen, Est_Jaccard)
rownames(temp[[5]]) <- c("C0N(q=0,Sorensen)","U0N(q=0,Jaccard)")
temp[[6]] <- rbind(Est_ew_Horn, Est_ew_C22, Est_ew_U22)
rownames(temp[[6]]) <- c("C1N=U1N(q=1,Horn)","C2N(q=2,Morisita)","U2N(q=2,Regional overlap)")
temp[[7]] <- t(as.matrix(Est_Ee_Horn))
rownames(temp[[7]]) <- c("Horn size weighted(q=1)")
temp[[8]] <- rbind(Est_Ee_U12, Est_Ee_C22, Est_Ee_U22, Est_Ee_Braycurtis)
rownames(temp[[8]]) <- c("C1N=U1N(q=1)","C2N(Morisita)", "U2N(Regional overlap)","Bray-Curtis")
temp <- lapply(temp, FUN = function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL")
return(x)
})
if(q == 0){
temp_PC <- rep(0, N*(N-1)/2)
C02=matrix(0,choose(no.community,2),4)
U02=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
mat <- Cq2_est_equ(Y[,c(i,j)], q, nboot,datatype="incidence", method='equal effort')
C02[k,] <- mat[1, ]
U02[k,] <- mat[2, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C02[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- U02[k,1]
k <- k+1
}
}
Cqn_PC <- list("C02"=C02, "U02"=U02)
C_SM <- list("C02"=C_SM_1, "U02"=C_SM_2)
}
if(q == 1 & method=="relative"){
temp_PC <- rep(0, N*(N-1)/2)
C12=matrix(0,choose(no.community,2),4)
Horn=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
C12[k,] <- Cq2_est_equ(Y[,c(i,j)], q, nboot,datatype="incidence", method='equal weight')[1, ]
Horn[k,] <- Cq2_est_equ(Y[,c(i,j)], q, nboot,datatype="incidence", method='equal effort')[2, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C12[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- Horn[k,1]
k <- k+1
}
}
Cqn_PC <- list("C12"=C12, "Horn"=Horn)
C_SM <- list("C12"=C_SM_1, "Horn"=C_SM_2)
}
if(q == 1 & method=="absolute"){
temp_PC <- rep(0, N*(N-1)/2)
k=1
C_SM_1=matrix(1,N,N)
C12=matrix(0,choose(no.community,2),4)
for(i in 1:(N-1)){
for(j in (i+1):N){
C12[k,] <- Cq2_est_equ(Y[,c(i,j)], q, nboot,datatype="incidence", method='equal effort')[1, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C12[k,1]
k <- k+1
}
}
Cqn_PC <- list("C12"=C12)
C_SM <- list("C12"=C_SM_1)
}
if(q == 2){
temp_PC <- rep(0, N*(N-1)/2)
if(method=="absolute") method2 <- 'equal effort'
if(method=="relative") method2 <- 'equal weight'
C22=matrix(0,choose(no.community,2),4)
U22=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
mat <- Cq2_est_equ(Y[,c(i,j)], q, nboot,datatype="incidence", method=method2)
C22[k,] <- mat[1, ]
U22[k,] <- mat[2, ]
temp_PC[k] <- paste("C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C22[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- U22[k,1]
k <- k+1
}
}
Cqn_PC <- list("C22"=C22, "U22"=U22)
C_SM <- list("C22"=C_SM_1,"U22"=C_SM_2)
}
Cqn_PC <- lapply(Cqn_PC, function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL") ; rownames(x) <- temp_PC
return(x)
})
z <- list("datatype"=datatype,"info"=info, "Empirical_richness"=temp[[1]], "Empirical_relative"=temp[[2]], "Empirical_WtRelative"=temp[[3]],
"Empirical_absolute"=temp[[4]], "estimated_richness"=temp[[5]], "estimated_relative"=temp[[6]], "estimated_WtRelative"=temp[[7]], "estimated_absolute"=temp[[8]], "pairwise"=Cqn_PC, "similarity.matrix"=C_SM, "goal"=method, "q"=q)
}
class(z) <- c("spadeMult")
z
}
Genetics=function(X,q=2,nboot=200)
{
type <- "abundance"
N <- no.community <- ncol(X)
temp <- c("N"=ncol(X), "S.total"=sum(rowSums(X)>0))
n <- apply(X,2,sum)
D <- apply(X,2,function(x)sum(x>0))
if(N > 2){
temp1 <- temp2 <- rep(0, N*(N-1)/2)
k <- 1
for(i in 1:(N-1)){
for(j in (i+1):N){
temp1[k] <- paste('D',i,j,sep="")
temp2[k] <- sum(X[,i]>0 & X[,j]>0)
k <- k + 1
}
}
}
names(temp2) <- temp1
names(n) <- paste('n',1:N, sep="")
names(D) <- paste('D',1:N, sep="")
info <- c(temp, n, D, temp2)
if(N == 3) info <- c(temp, n, D, temp2, D123=sum(X[,1]>0 & X[,2]>0 & X[,3]>0))
info <- c(info, nboot=nboot)
temp <- list()
n <- apply(X = X, MARGIN = 2, FUN = sum)
weight <- n/sum(n)
weight <- - sum(weight*log(weight)) / log(N)
plus_CI <-function(x){
if(x[1] >= 1) x[1] <- 1
if(x[1] <= 0) x[1] <- 0
c(x, max(0,x[1]-1.96*x[2]), min(1,x[1]+1.96*x[2]))
}
mat2 <- GST_se_equ(X,nboot)
MLE_ew_Gst <- mat2[1, ]
Est_ew_Gst <- mat2[2, ]
mat <- SimilarityMul(X,0,nboot,method="unequal weight")
MLE_Jaccard <- plus_CI(c(1-mat$UqN[1, 1],mat$UqN[1, 2]))
Est_Jaccard <- plus_CI(c(1-mat$UqN[2, 1],mat$UqN[2, 2]))
MLE_Sorensen <- plus_CI(c(1-mat$CqN[1, 1],mat$CqN[1, 2]))
Est_Sorensen <- plus_CI(c(1-mat$CqN[2, 1],mat$CqN[2, 2]))
mat3 <- Horn_Multi_equ(X, datatype="abundance", nboot, method=c("unequal"))
MLE_Ee_Horn <- mat3$mle
MLE_Ee_Horn <- plus_CI(c(1-MLE_Ee_Horn[1],MLE_Ee_Horn[2]))
Est_Ee_Horn <- mat3$est
Est_Ee_Horn <- plus_CI(c(1-Est_Ee_Horn[1],Est_Ee_Horn[2]))
mat4 <- SimilarityMul(X,2,nboot,method="equal weight")
mat5 <- Horn_Multi_equ(X, datatype="abundance", nboot, method=c("equal"))
MLE_ew_Horn <- mat5$mle
Est_ew_Horn <- mat5$est
MLE_ew_Horn <- plus_CI(c(1-MLE_ew_Horn[1],MLE_ew_Horn[2]))
Est_ew_Horn <- plus_CI(c(1-Est_ew_Horn[1],Est_ew_Horn[2]))
MLE_ew_C22 <- plus_CI(c(1-mat4$CqN[1, 1],mat4$CqN[1, 2]))
Est_ew_C22 <- plus_CI(c(1-mat4$CqN[2, 1],mat4$CqN[2, 2]))
MLE_ew_U22 <- plus_CI(c(1-mat4$UqN[1, 1],mat4$UqN[1, 2]))
Est_ew_U22 <- plus_CI(c(1-mat4$UqN[2, 1],mat4$UqN[2, 2]))
temp[[1]] <- rbind(MLE_Sorensen, MLE_Jaccard)
rownames(temp[[1]]) <- c("1-C0N(q=0,Sorensen)","1-U0N(q=0,Jaccard)")
temp[[2]] <- rbind(MLE_ew_Horn, MLE_ew_C22, MLE_ew_U22,MLE_ew_Gst)
rownames(temp[[2]]) <- c("1-C1N=1-U1N(q=1,Horn)","1-C2N(q=2,Morisita)","1-U2N(q=2,Regional overlap)","Gst")
temp[[3]] <- t(as.matrix(MLE_Ee_Horn))
rownames(temp[[3]]) <- c("Horn size weighted(q=1)")
temp[[4]] <- rbind(Est_Sorensen, Est_Jaccard)
rownames(temp[[4]]) <- c("1-C0N(q=0,Sorensen)","1-U0N(q=0,Jaccard)")
temp[[5]] <- rbind(Est_ew_Horn, Est_ew_C22, Est_ew_U22, Est_ew_Gst)
rownames(temp[[5]]) <- c("1-C1N=1-U1N(q=1,Horn)","1-C2N(q=2,Morisita)","1-U2N(q=2,Regional overlap)","Gst")
temp[[6]] <- t(as.matrix(Est_Ee_Horn))
rownames(temp[[6]]) <- c("Horn size weighted(q=1)")
temp <- lapply(temp, FUN = function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL")
return(x)
})
if(q == 0){
temp_PC <- rep(0, N*(N-1)/2)
C02=matrix(0,choose(no.community,2),4)
U02=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(1,N,N)
C_SM_2=matrix(1,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
if(sum( X[,i]>0 & X[,j]>0)==0){
mat <- rbind(c(0, 0), c(0 ,0))
}else{
mat <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal effort')
}
C02[k,] <- plus_CI(c(1-mat[1, 1],mat[1, 2]))
U02[k,] <- plus_CI(c(1-mat[2, 1],mat[2, 2]))
temp_PC[k] <- paste("1-C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C02[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- U02[k,1]
k <- k+1
}
}
Cqn_PC <- list("C02"=C02, "U02"=U02)
C_SM <- list("C02"=C_SM_1, "U02"=C_SM_2)
}
if(q == 1){
temp_PC <- rep(0, N*(N-1)/2)
C12=matrix(0,choose(no.community,2),4)
Horn=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(0,N,N)
C_SM_2=matrix(0,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
mat <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal weight')
mat2 <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal effort')
C12[k,] <- plus_CI(c(1-mat[1, 1],mat[1, 2]))
Horn[k,] <- plus_CI(c(1-mat2[2, 1],mat2[2, 2]))
temp_PC[k] <- paste("1-C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C12[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- Horn[k,1]
k <- k+1
}
}
Cqn_PC <- list("C12"=C12, "Horn"=Horn)
C_SM <- list("C12"=C_SM_1, "Horn"=C_SM_2)
}
if(q == 2){
temp_PC <- rep(0, N*(N-1)/2)
C22=matrix(0,choose(no.community,2),4)
U22=matrix(0,choose(no.community,2),4)
C_SM_1=matrix(0,N,N)
C_SM_2=matrix(0,N,N)
k=1
for(i in 1:(N-1)){
for(j in (i+1):N){
mat <- Cq2_est_equ(X[,c(i,j)], q, nboot, method='equal weight')
C22[k,] <- plus_CI(c(1-mat[1, 1],mat[1, 2]))
U22[k,] <- plus_CI(c(1-mat[2, 1],mat[2, 2]))
temp_PC[k] <- paste("1-C",q,"2(",i,",",j,")", sep="")
C_SM_1[i,j] <- C_SM_1[j,i] <- C22[k,1]
C_SM_2[i,j] <- C_SM_2[j,i] <- U22[k,1]
k <- k+1
}
}
Cqn_PC <- list("C22"=C22, "U22"=U22)
C_SM <- list("C22"=C_SM_1,"U22"=C_SM_2)
}
Cqn_PC <- lapply(Cqn_PC, function(x){
colnames(x) <- c("Estimate", "s.e.", "95%.LCL", "95%.UCL") ; rownames(x) <- temp_PC
return(x)
})
z <- list("info"=info, "Empirical_richness"=temp[[1]], "Empirical_relative"=temp[[2]], "Empirical_WtRelative"=temp[[3]],
"estimated_richness"=temp[[4]], "estimated_relative"=temp[[5]], "estimated_WtRelative"=temp[[6]], "pairwise"=Cqn_PC, "dissimilarity_matrix"=C_SM, "q"=q)
class(z) <- c("spadeGenetic")
z
} |
`printMEC` <-
function(x, digits = max(3, getOption("digits") - 3), ...)
{
cat("Plane 1: ")
print.default(format(c(x$F$az, x$F$dip), digits = digits), print.gap = 2,
quote = FALSE)
cat("Plane 2: ")
print.default(format(c(x$G$az, x$G$dip), digits = digits), print.gap = 2,
quote = FALSE)
cat("Vector 1: ")
print.default(format(c(x$U$az, x$U$dip), digits = digits), print.gap = 2,
quote = FALSE)
cat("Vector 2: ")
print.default(format(c(x$V$az, x$V$dip), digits = digits), print.gap = 2,
quote = FALSE)
cat("P-axis: ")
print.default(format(c(x$P$az, x$P$dip), digits = digits), print.gap = 2,
quote = FALSE)
cat("T-axis: ")
print.default(format(c(x$T$az, x$T$dip), digits = digits), print.gap = 2,
quote = FALSE)
cat("\n")
} |
zls <- setRefClass("Zelig-ls", contains = "Zelig")
zls$methods(
initialize = function() {
callSuper()
.self$name <- "ls"
.self$year <- 2007
.self$category <- "continuous"
.self$description <- "Least Squares Regression for Continuous Dependent Variables"
.self$packageauthors <- "R Core Team"
.self$fn <- quote(stats::lm)
.self$outcome <- "continous"
.self$wrapper <- "ls"
.self$acceptweights <- TRUE
}
)
zls$methods(
zelig = function(formula, data, ..., weights = NULL, by = NULL,
bootstrap = FALSE) {
.self$zelig.call <- match.call(expand.dots = TRUE)
.self$model.call <- .self$zelig.call
callSuper(formula = formula, data = data, ...,
weights = weights, by = by, bootstrap = bootstrap)
rse <- lapply(.self$zelig.out$z.out, (function(x) vcovHC(x, type = "HC0")))
rse.se <- sqrt(diag(rse[[1]]))
est.se <- sqrt(diag(.self$get_vcov()[[1]]))
quickGim <- any( est.se > 1.5*rse.se | rse.se > 1.5*est.se )
.self$test.statistics<- list(robust.se = rse, gim.criteria = quickGim)
}
)
zls$methods(
param = function(z.out, method="mvn") {
if(identical(method,"mvn")){
return(list(simparam = mvrnorm(.self$num, coef(z.out), vcov(z.out)),
simalpha = rep( summary(z.out)$sigma, .self$num) ) )
} else if(identical(method,"point")){
return(list(simparam = t(as.matrix(coef(z.out))),
simalpha=summary(z.out)$sigma))
} else {
stop("param called with method argument of undefined type.")
}
}
)
zls$methods(
qi = function(simparam, mm) {
ev <- simparam$simparam %*% t(mm)
pv <- as.matrix(rnorm(n=length(ev), mean=ev, sd=simparam$simalpha),
nrow=length(ev), ncol=1)
return(list(ev = ev, pv = pv))
}
)
zls$methods(
gim = function(B=50, B2=50) {
ll.normal.bsIM <- function(par,y,X,sigma){
beta <- par[1:length(X)]
sigma2 <- sigma
-1/2 * (sum(log(sigma2) + (y -(X%*%beta))^2/sigma2))
}
getVb<-function(Dboot){
Dbar <- matrix(apply(Dboot,2,mean),nrow=B, ncol=length(Dhat), byrow=TRUE)
Diff <- Dboot - Dbar
Vb <- (t(Diff) %*% Diff) / (nrow(Dboot)-1)
return(Vb)
}
getSigma<-function(lm.obj){
return(sum(lm.obj$residuals^2)/(nrow(model.matrix(lm.obj))-ncol(model.matrix(lm.obj))))
}
D.est<-function(formula,data){
lm1 <- lm(formula,data, y=TRUE)
mm <- model.matrix(lm1)
y <- lm1$y
sigma <- getSigma(lm1)
grad <- apply(cbind(y,mm),1,function(x) numericGradient(ll.normal.bsIM, lm1$coefficients, y=x[1], X=x[2:length(x)], sigma=sigma))
meat <- grad%*%t(grad)
bread <- -solve(vcov(lm1))
Dhat <- nrow(mm)^(-1/2)* as.vector(diag(meat + bread))
return(Dhat)
}
D.est.vb<-function(formula,data){
lm1 <- lm(formula,data, y=TRUE)
mm <- model.matrix(lm1)
y <- lm1$y
sigma <- getSigma(lm1)
grad <- apply(cbind(y,mm),1,function(x) numericGradient(ll.normal.bsIM, lm1$coefficients, y=x[1], X=x[2:length(x)], sigma=sigma))
meat <- grad%*%t(grad)
bread <- -solve(vcov(lm1))
Dhat <- nrow(mm)^(-1/2)* as.vector(diag(meat + bread))
muB<-lm1$fitted.values
DB <- matrix(NA, nrow=B2, ncol=length(Dhat))
for(j in 1:B2){
yB2 <- rnorm(nrow(data), muB, sqrt(sigma))
lm1B2 <- lm(yB2 ~ mm-1)
sigmaB2 <- getSigma(lm1B2)
grad <- apply(cbind(yB2,model.matrix(lm1B2)),1,function(x) numericGradient(ll.normal.bsIM, lm1B2$coefficients, y=x[1], X=x[2:length(x)], sigma=sigmaB2))
meat <- grad%*%t(grad)
bread <- -solve(vcov(lm1B2))
DB[j,] <- nrow(mm)^(-1/2)*diag((meat + bread))
}
Vb <- getVb(DB)
T<- t(Dhat)%*%solve(Vb)%*%Dhat
return(list(Dhat=Dhat,T=T))
}
Dhat <- D.est(formula=.self$formula, data=.self$data)
lm1 <- lm(formula=.self$formula, data=.self$data)
mu <- lm1$fitted.values
sigma <- getSigma(lm1)
n <- length(mu)
yname <- all.vars(.self$formula[[2]])
Dboot <- matrix(NA, nrow=B, ncol=length(Dhat))
bootdata<-data
for(i in 1:B){
yB <- rnorm(n, mu, sqrt(sigma))
bootdata[yname] <- yB
result <- D.est.vb(formula=.self$formula, data=bootdata)
Dboot[i,] <- result$Dhat
T[i] <- result$T
}
Vb <- getVb(Dboot)
omega <- t(Dhat) %*% solve(Vb) %*% Dhat
pb = (B+1-sum(T< as.numeric(omega)))/(B+1)
.self$test.statistics$gim <- list(stat=omega, pval=pb)
gimreference <- bibentry(
bibtype="Article",
title = "How Robust Standard Errors Expose Methodological Problems They Do Not Fix, and What to Do About It",
author = c(
person("Gary", "King"),
person("Margret E.", "Roberts")
),
journal = "Political Analysis",
year = 2014,
pages = "1-21",
url = "http://j.mp/InK5jU")
.self$refs <- c(.self$refs, gimreference)
}
)
zls$methods(
mcfun = function(x, b0=0, b1=1, alpha=1, sim=TRUE){
y <- b0 + b1*x + sim * rnorm(n=length(x), sd=alpha)
return(y)
}
) |
gaussian.MVCARar2 <- function(formula, data=NULL, W, burnin, n.sample, thin=1, prior.mean.beta=NULL, prior.var.beta=NULL, prior.nu2=NULL, prior.Sigma.df=NULL, prior.Sigma.scale=NULL, rho.S=NULL, rho.T=NULL, verbose=TRUE)
{
a <- common.verbose(verbose)
frame.results <- common.frame.MVST(formula, data, "gaussian")
NK <- frame.results$n
p <- frame.results$p
X <- frame.results$X
X.standardised <- frame.results$X.standardised
X.sd <- frame.results$X.sd
X.mean <- frame.results$X.mean
X.indicator <- frame.results$X.indicator
offset <- frame.results$offset
Y <- frame.results$Y
N.all <- length(Y)
J <- ncol(Y)
which.miss <- frame.results$which.miss
n.miss <- N.all - sum(which.miss)
Y.DA <- Y
if(n.miss>0)
{
miss.locator <- array(NA, c(n.miss, 2))
colnames(miss.locator) <- c("row", "column")
locations <- which(which.miss==0)
miss.locator[ ,1] <- ceiling(locations/J)
miss.locator[ ,2] <- locations - (miss.locator[ ,1]-1) * J
}else
{}
if(!is.matrix(W)) stop("W is not a matrix.", call.=FALSE)
K <- nrow(W)
N <- NK / K
if(ceiling(N)!= floor(N)) stop("The number of data points in Y divided by the number of rows in W is not a whole number.", call.=FALSE)
if(is.null(rho.S))
{
rho <- runif(1)
fix.rho.S <- FALSE
}else
{
rho <- rho.S
fix.rho.S <- TRUE
}
if(!is.numeric(rho)) stop("rho.S is fixed but is not numeric.", call.=FALSE)
if(rho<0 ) stop("rho.S is outside the range [0, 1].", call.=FALSE)
if(rho>1 ) stop("rho.S is outside the range [0, 1].", call.=FALSE)
if(is.null(rho.T))
{
alpha <- c(runif(1), runif(1))
fix.rho.T <- FALSE
}else
{
alpha <- rho.T
fix.rho.T <- TRUE
}
if(!is.numeric(alpha)) stop("rho.T is fixed but is not numeric.", call.=FALSE)
if(length(alpha)!=2) stop("rho.T is fixed but is not of length 2.", call.=FALSE)
if(is.null(prior.mean.beta)) prior.mean.beta <- rep(0, p)
if(is.null(prior.var.beta)) prior.var.beta <- rep(100000, p)
if(is.null(prior.Sigma.df)) prior.Sigma.df <- J+1
if(is.null(prior.Sigma.scale)) prior.Sigma.scale <- diag(rep(1/1000,J))
if(is.null(prior.nu2)) prior.nu2 <- c(1, 0.01)
prior.beta.check(prior.mean.beta, prior.var.beta, p)
common.prior.varmat.check(prior.Sigma.scale, J)
prior.var.check(prior.nu2)
common.burnin.nsample.thin.check(burnin, n.sample, thin)
beta <- array(NA, c(p, J))
nu2 <- rep(NA, J)
for(i in 1:J)
{
mod.glm <- lm(Y[ ,i]~X.standardised-1, offset=offset[ ,i])
beta.mean <- mod.glm$coefficients
beta.sd <- sqrt(diag(summary(mod.glm)$cov.unscaled)) * summary(mod.glm)$sigma
beta[ ,i] <- rnorm(n=p, mean=beta.mean, sd=beta.sd)
nu2[i] <- runif(1, var(mod.glm$residuals)*0.5, var(mod.glm$residuals))
}
res.temp <- Y - X.standardised %*% beta - offset
res.sd <- sd(res.temp, na.rm=TRUE)/5
phi.vec <- rnorm(n=N.all, mean=0, sd=res.sd)
phi <- matrix(phi.vec, ncol=J, byrow=TRUE)
Sigma <- cov(phi)
Sigma.inv <- solve(Sigma)
regression <- X.standardised %*% beta
fitted <- regression + phi + offset
n.keep <- floor((n.sample - burnin)/thin)
samples.beta <- array(NA, c(n.keep, J*p))
samples.nu2 <- array(NA, c(n.keep, J))
samples.phi <- array(NA, c(n.keep, N.all))
samples.Sigma <- array(NA, c(n.keep, J, J))
if(!fix.rho.S) samples.rho <- array(NA, c(n.keep, 1))
if(!fix.rho.T) samples.alpha <- array(NA, c(n.keep, 2))
samples.loglike <- array(NA, c(n.keep, N.all))
samples.fitted <- array(NA, c(n.keep, N.all))
if(n.miss>0) samples.Y <- array(NA, c(n.keep, n.miss))
accept <- rep(0,4)
accept.all <- rep(0,4)
proposal.sd.phi <- 0.1
proposal.sd.rho <- 0.02
Sigma.post.df <- prior.Sigma.df + K * N
nu2.posterior.shape <- prior.nu2[1] + 0.5 * K * N
W.quants <- common.Wcheckformat.leroux(W)
W <- W.quants$W
W.triplet <- W.quants$W.triplet
n.triplet <- W.quants$n.triplet
W.triplet.sum <- W.quants$W.triplet.sum
n.neighbours <- W.quants$n.neighbours
W.begfin <- W.quants$W.begfin
Wstar <- diag(apply(W,1,sum)) - W
Q <- rho * Wstar + diag(rep(1-rho,K))
if(!fix.rho.S)
{
Wstar.eigen <- eigen(Wstar)
Wstar.val <- Wstar.eigen$values
det.Q <- sum(log((rho * Wstar.val + (1-rho))))
}else
{}
W.list<- mat2listw(W)
W.nb <- W.list$neighbours
W.islands <- n.comp.nb(W.nb)
islands <- W.islands$comp.id
n.islands <- max(W.islands$nc)
if(rho==1 & alpha[1]==2 & alpha[2]==-1)
{
Sigma.post.df <- prior.Sigma.df + ((N-2) * (K-n.islands))/2
}else if(rho==1)
{
Sigma.post.df <- prior.Sigma.df + (N * (K-n.islands))/2
}else if(alpha[1]==2 & alpha[2]==-1)
{
Sigma.post.df <- prior.Sigma.df + ((N-2) * K)/2
}else
{}
data.precision <- t(X.standardised) %*% X.standardised
if(length(prior.var.beta)==1)
{
prior.precision.beta <- 1 / prior.var.beta
}else
{
prior.precision.beta <- solve(diag(prior.var.beta))
}
if(verbose)
{
cat("Generating", n.keep, "post burnin and thinned (if requested) samples.\n", sep = " ")
progressBar <- txtProgressBar(style = 3)
percentage.points<-round((1:100/100)*n.sample)
}else
{
percentage.points<-round((1:100/100)*n.sample)
}
for(j in 1:n.sample)
{
if(n.miss>0)
{
Y.DA[miss.locator] <- rnorm(n=n.miss, mean=fitted[miss.locator], sd=sqrt(nu2[miss.locator[ ,2]]))
}else
{}
fitted.current <- regression + phi + offset
nu2.posterior.scale <- prior.nu2[2] + 0.5 * apply((Y.DA - fitted.current)^2, 2, sum)
nu2 <- 1 / rgamma(J, nu2.posterior.shape, scale=(1/nu2.posterior.scale))
for(r in 1:J)
{
fc.precision <- prior.precision.beta + data.precision / nu2[r]
fc.var <- solve(fc.precision)
fc.temp1 <- t(((Y.DA[, r] - phi[ , r] - offset[ , r]) %*% X.standardised) / nu2[r]) + prior.precision.beta %*% prior.mean.beta
fc.mean <- fc.var %*% fc.temp1
chol.var <- t(chol(fc.var))
beta[ ,r] <- fc.mean + chol.var %*% rnorm(p)
}
regression <- X.standardised %*% beta
den.offset <- rho * W.triplet.sum + 1 - rho
phi.offset <- Y.DA - regression - offset
Chol.Sigma <- t(chol(proposal.sd.phi*Sigma))
z.mat <- matrix(rnorm(n=N.all, mean=0, sd=1), nrow=J, ncol=NK)
innovations <- t(Chol.Sigma %*% z.mat)
temp1 <- gaussianmvar2carupdateRW(W.triplet, W.begfin, W.triplet.sum, K, N, J, phi, alpha[1], alpha[2], rho, Sigma.inv, nu2, innovations, phi.offset, den.offset)
phi <- temp1[[1]]
for(r in 1:J)
{
phi[ ,r] <- phi[ ,r] - mean(phi[ ,r])
}
accept[1] <- accept[1] + temp1[[2]]
accept[2] <- accept[2] + NK
Sigma.post.scale <- prior.Sigma.scale + t(phi[1:K, ]) %*% Q %*% phi[1:K, ] + t(phi[(K+1):(2*K), ]) %*% Q %*% phi[(K+1):(2*K), ]
for(t in 3:N)
{
phit <- phi[((t-1)*K+1):(t*K), ]
phitminus1 <- phi[((t-2)*K+1):((t-1)*K), ]
phitminus2 <- phi[((t-3)*K+1):((t-2)*K), ]
temp1 <- phit - alpha[1] * phitminus1 - alpha[2] * phitminus2
Sigma.post.scale <- Sigma.post.scale + t(temp1) %*% Q %*% temp1
}
Sigma <- riwish(Sigma.post.df, Sigma.post.scale)
Sigma.inv <- solve(Sigma)
if(!fix.rho.T)
{
temp <- MVSTrhoTAR2compute(W.triplet, W.triplet.sum, n.triplet, den.offset, K, N, J, phi, rho, Sigma.inv)
alpha.precision <- matrix(c(temp[[1]], temp[[2]], temp[[2]], temp[[3]]), nrow=2, ncol=2)
alpha.var <- solve(alpha.precision)
alpha.mean <- rep(NA, 2)
alpha.mean[2] <- (temp[[1]] * temp[[5]] - temp[[2]] * temp[[4]]) / (temp[[1]] * temp[[3]] - temp[[2]]^2)
alpha.mean[1] <- (temp[[5]] - temp[[3]] * alpha.mean[2]) / temp[[2]]
alpha <- mvrnorm(n=1, mu=alpha.mean, Sigma=alpha.var)
}else
{}
if(!fix.rho.S)
{
proposal.rho <- rtruncnorm(n=1, a=0, b=1, mean=rho, sd=proposal.sd.rho)
proposal.Q <- proposal.rho * Wstar + diag(rep(1-proposal.rho), K)
proposal.det.Q <- sum(log((proposal.rho * Wstar.val + (1-proposal.rho))))
proposal.den.offset <- proposal.rho * W.triplet.sum + 1 - proposal.rho
temp1.QF <- MVSTrhoSAR2compute(W.triplet, W.triplet.sum, n.triplet, den.offset, K, N, J, phi, rho, alpha[1], alpha[2], Sigma.inv)
temp2.QF <- MVSTrhoSAR2compute(W.triplet, W.triplet.sum, n.triplet, proposal.den.offset, K, N, J, phi, proposal.rho, alpha[1], alpha[2], Sigma.inv)
logprob.current <- 0.5 * J * N * det.Q - 0.5 * temp1.QF
logprob.proposal <- 0.5 * J * N * proposal.det.Q - 0.5 * temp2.QF
hastings <- log(dtruncnorm(x=rho, a=0, b=1, mean=proposal.rho, sd=proposal.sd.rho)) - log(dtruncnorm(x=proposal.rho, a=0, b=1, mean=rho, sd=proposal.sd.rho))
prob <- exp(logprob.proposal - logprob.current + hastings)
if(prob > runif(1))
{
rho <- proposal.rho
det.Q <- proposal.det.Q
Q <- proposal.Q
accept[3] <- accept[3] + 1
}else
{}
accept[4] <- accept[4] + 1
}else
{}
fitted <- regression + phi + offset
loglike <- dnorm(x=as.numeric(t(Y)), mean=as.numeric(t(fitted)), sd=rep(sqrt(nu2), K*N), log=TRUE)
if(j > burnin & (j-burnin)%%thin==0)
{
ele <- (j - burnin) / thin
samples.beta[ele, ] <- as.numeric(beta)
samples.nu2[ele, ] <- nu2
samples.phi[ele, ] <- as.numeric(t(phi))
samples.Sigma[ele, , ] <- Sigma
if(!fix.rho.S) samples.rho[ele, ] <- rho
if(!fix.rho.T) samples.alpha[ele, ] <- alpha
samples.loglike[ele, ] <- loglike
samples.fitted[ele, ] <- as.numeric(t(fitted))
if(n.miss>0) samples.Y[ele, ] <- Y.DA[miss.locator]
}else
{}
k <- j/100
if(ceiling(k)==floor(k))
{
proposal.sd.phi <- common.accceptrates1(accept[1:2], proposal.sd.phi, 40, 50)
if(!fix.rho.S)
{
proposal.sd.rho <- common.accceptrates2(accept[3:4], proposal.sd.rho, 40, 50, 0.5)
}
accept.all <- accept.all + accept
accept <- c(0,0,0,0)
}else
{}
if(j %in% percentage.points & verbose)
{
setTxtProgressBar(progressBar, j/n.sample)
}
}
if(verbose)
{
cat("\nSummarising results.")
close(progressBar)
}else
{}
accept.beta <- 100
accept.phi <- 100 * accept.all[1] / accept.all[2]
if(!fix.rho.S)
{
accept.rho <- 100 * accept.all[3] / accept.all[4]
}else
{
accept.rho <- NA
}
accept.Sigma <- 100
if(!fix.rho.T)
{
accept.alpha <- 100
}else
{
accept.alpha <- NA
}
accept.final <- c(accept.beta, accept.phi, accept.rho, accept.Sigma, accept.alpha)
names(accept.final) <- c("beta", "phi", "rho.S", "Sigma", "rho.T")
mean.beta <- matrix(apply(samples.beta, 2, mean), nrow=p, ncol=J, byrow=F)
mean.phi <- matrix(apply(samples.phi, 2, mean), nrow=NK, ncol=J, byrow=T)
fitted.mean <- X.standardised %*% mean.beta + mean.phi + offset
nu2.mean <- apply(samples.nu2,2,mean)
deviance.fitted <- -2 * sum(dnorm(as.numeric(t(Y)), mean = as.numeric(t(fitted.mean)), sd=rep(sqrt(nu2.mean), K*N), log = TRUE), na.rm=TRUE)
modelfit <- common.modelfit(samples.loglike, deviance.fitted)
samples.beta.orig <- samples.beta
for(r in 1:J)
{
samples.beta.orig[ ,((r-1)*p+1):(r*p)] <- common.betatransform(samples.beta[ ,((r-1)*p+1):(r*p) ], X.indicator, X.mean, X.sd, p, FALSE)
}
samples.beta.orig <- mcmc(samples.beta.orig)
summary.beta <- t(apply(samples.beta.orig, 2, quantile, c(0.5, 0.025, 0.975)))
summary.beta <- cbind(summary.beta, rep(n.keep, p), rep(accept.beta,p), effectiveSize(samples.beta.orig), geweke.diag(samples.beta.orig)$z)
col.name <- rep(NA, p*(J-1))
if(is.null(colnames(Y)))
{
for(r in 1:J)
{
col.name[((r-1)*p+1):(r*p)] <- paste("Variable ", r, " - ", colnames(X), sep="")
}
}else
{
for(r in 1:J)
{
col.name[((r-1)*p+1):(r*p)] <- paste(colnames(Y)[r], " - ", colnames(X), sep="")
}
}
rownames(summary.beta) <- col.name
colnames(summary.beta) <- c("Median", "2.5%", "97.5%", "n.sample", "% accept", "n.effective", "Geweke.diag")
summary.hyper <- array(NA, c((2*J+3) ,7))
summary.hyper[1:J, 1:3] <-t(apply(samples.nu2, 2, quantile, c(0.5, 0.025, 0.975)))
summary.hyper[1:J, 4] <- rep(n.keep, J)
summary.hyper[1:J, 5] <- rep(100, J)
summary.hyper[1:J, 6] <- apply(samples.nu2, 2, effectiveSize)
summary.hyper[1:J, 7] <- geweke.diag(samples.nu2)$z
summary.hyper[(J+1):(2*J), 1] <- diag(apply(samples.Sigma, c(2,3), quantile, c(0.5)))
summary.hyper[(J+1):(2*J), 2] <- diag(apply(samples.Sigma, c(2,3), quantile, c(0.025)))
summary.hyper[(J+1):(2*J), 3] <- diag(apply(samples.Sigma, c(2,3), quantile, c(0.975)))
summary.hyper[(J+1):(2*J), 4] <- rep(n.keep, J)
summary.hyper[(J+1):(2*J), 5] <- rep(100, J)
summary.hyper[(J+1):(2*J), 6] <- diag(apply(samples.Sigma, c(2,3), effectiveSize))
for(r in 1:J)
{
summary.hyper[J+r, 7] <- geweke.diag(samples.Sigma[ ,r,r])$z
}
if(!fix.rho.S)
{
summary.hyper[(2*J+1), 1:3] <- quantile(samples.rho, c(0.5, 0.025, 0.975))
summary.hyper[(2*J+1), 4:5] <- c(n.keep, accept.rho)
summary.hyper[(2*J+1), 6:7] <- c(effectiveSize(samples.rho), geweke.diag(samples.rho)$z)
}else
{
summary.hyper[(2*J+1), 1:3] <- c(rho, rho, rho)
summary.hyper[(2*J+1), 4:5] <- rep(NA, 2)
summary.hyper[(2*J+1), 6:7] <- rep(NA, 2)
}
if(!fix.rho.T)
{
summary.hyper[(2*J+2), 1:3] <- quantile(samples.alpha[ ,1], c(0.5, 0.025, 0.975))
summary.hyper[(2*J+2), 4:5] <- c(n.keep, accept.alpha)
summary.hyper[(2*J+2), 6:7] <- c(effectiveSize(samples.alpha[ ,1]), geweke.diag(samples.alpha[ ,1])$z)
summary.hyper[(2*J+3), 1:3] <- quantile(samples.alpha[ ,2], c(0.5, 0.025, 0.975))
summary.hyper[(2*J+3), 4:5] <- c(n.keep, accept.alpha)
summary.hyper[(2*J+3), 6:7] <- c(effectiveSize(samples.alpha[ ,2]), geweke.diag(samples.alpha[ ,2])$z)
}else
{
summary.hyper[(2*J+2), 1:3] <- c(alpha[1], alpha[1], alpha[1])
summary.hyper[(2*J+2), 4:5] <- rep(NA, 2)
summary.hyper[(2*J+2), 6:7] <- rep(NA, 2)
summary.hyper[(2*J+3), 1:3] <- c(alpha[2], alpha[2], alpha[2])
summary.hyper[(2*J+3), 4:5] <- rep(NA, 2)
summary.hyper[(2*J+3), 6:7] <- rep(NA, 2)
}
summary.results <- rbind(summary.beta, summary.hyper)
rownames(summary.results)[((J*p)+1): nrow(summary.results)] <- c(paste(rep("nu2",J), 1:J, sep=""), paste(rep("Sigma",J), 1:J, 1:J, sep=""), "rho.S", "rho1.T", "rho2.T")
summary.results[ , 1:3] <- round(summary.results[ , 1:3], 4)
summary.results[ , 4:7] <- round(summary.results[ , 4:7], 1)
fitted.values <- matrix(apply(samples.fitted, 2, mean), nrow=NK, ncol=J, byrow=T)
response.residuals <- Y - fitted.values
nu.mat <- matrix(rep(sqrt(nu2.mean), N*K), nrow=N*K, byrow=T)
pearson.residuals <- response.residuals / nu.mat
residuals <- list(response=response.residuals, pearson=pearson.residuals)
model.string <- c("Likelihood model - Gaussian (identity link function)", "\nRandom effects model - Multivariate Autoregressive order 2 CAR model\n")
if(fix.rho.S & fix.rho.T)
{
samples.rhoext <- NA
}else if(fix.rho.S & !fix.rho.T)
{
samples.rhoext <- samples.alpha
colnames(samples.rhoext) <- c("rho1.T", "rho2.T")
}else if(!fix.rho.S & fix.rho.T)
{
samples.rhoext <- samples.rho
names(samples.rhoext) <- "rho.S"
}else
{
samples.rhoext <- cbind(samples.rho, samples.alpha)
colnames(samples.rhoext) <- c("rho.S", "rho1.T", "rho2.T")
}
if(n.miss==0) samples.Y = NA
samples <- list(beta=samples.beta.orig, phi=mcmc(samples.phi), Sigma=samples.Sigma, nu2=mcmc(samples.nu2), rho=mcmc(samples.rhoext), fitted=mcmc(samples.fitted), Y=mcmc(samples.Y))
results <- list(summary.results=summary.results, samples=samples, fitted.values=fitted.values, residuals=residuals, modelfit=modelfit, accept=accept.final, localised.structure=NULL, formula=formula, model=model.string, X=X)
class(results) <- "CARBayesST"
if(verbose)
{
b<-proc.time()
cat("Finished in ", round(b[3]-a[3], 1), "seconds.\n")
}else
{}
return(results)
} |
DF2 <- rbind(DF, DF[7:8,, drop=FALSE]) |
ModifyInputFile <- function(
ParamID,
newvalue,
filename,
row,
col.ini,
col.fin,
decimals,
verbose=TRUE) {
if (!file.exists(filename))
stop( paste("Invalid argument: the file '", filename, "' doesn't exist!", sep="") )
lines <- readLines(filename)
myline <- lines[row]
L.trg <- col.fin - col.ini + 1
newvalue.stg <- as.character(round(newvalue, decimals))
L <- nchar(newvalue.stg)
if (L < L.trg) newvalue.stg <- format(newvalue, justify="right", width=L.trg, nsmall=decimals)
if (L > L.trg) {
nexp <- 2
if (abs(newvalue) >= 1E100) nexp <- 3
dig <- max(decimals-(L - L.trg)-3-nexp, 0)
suppressWarnings(
newvalue.stg <- formatC(newvalue, width=L.trg, format="E", digits=dig)
)
}
substr(myline, col.ini, col.fin) <- newvalue.stg
lines[row] <- myline
writeLines(lines, filename)
if (verbose)
message( paste("[", ParamID, ": '", round(newvalue,5), "' was successfully put into '", basename(filename), "']", sep="") )
} |
unknown <- function() {
quote(unknown())
}
is_unknown <- function(x) {
if(length(x) == 1)
return(is_unknown_val(x))
map_lgl(x, is_unknown_val)
}
is_unknown_val <- function(x)
isTRUE(all.equal(x, quote(unknown())))
has_unknowns <- function(object) {
if (inherits(object, "param"))
return(has_unknowns_val(object))
map_lgl(object, has_unknowns_val)
}
has_unknowns_val <- function(object) {
if (all(is.na(object))) {
return(FALSE)
}
if (any(names(object) == "range")) {
rng_check <- any(is_unknown(object$range))
} else {
rng_check <- FALSE
}
val_check <- any(is_unknown(object$values))
any(rng_check) | any(val_check)
}
check_for_unknowns <- function(x, label = "") {
err_txt <- paste0("Unknowns not allowed in `", label, "`.")
if (length(x) == 1 && is_unknown(x))
rlang::abort(err_txt)
is_ukn <- map_lgl(x, is_unknown)
if (any(is_ukn))
rlang::abort(err_txt)
invisible(TRUE)
} |
SLTCA <- function(k = 20,dat,num_class,id,time,num_obs,features,Y_dist,covx,ipw,stop,tol=0.005,max=50,varest=TRUE,balanced=TRUE,MSC='EQIC',verbose=TRUE){
requireNamespace("Matrix")
requireNamespace("VGAM")
requireNamespace("geepack")
IC = Inf
if(MSC == 'AQIC'){
for (i in 1:k){
if(verbose) cat('random initialization',i,'\n')
sol <- pointest(dat,num_class,id,time,num_obs,features,Y_dist,covx,ipw,stop,tol,max,varest,balanced,verbose)
if (sol$qic[[1]] < IC){
best_sol <- sol
IC = sol$qic[[1]]
}
}
}else if (MSC == 'BQIC'){
for (i in 1:k){
if(verbose) cat('random initialization',i,'\n')
sol <- pointest(dat,num_class,id,time,num_obs,features,Y_dist,covx,ipw,stop,tol,max,varest,balanced,verbose)
if (sol$qic[[2]] < IC){
best_sol <- sol
IC = sol$qic[[2]]
}
}
}else if (MSC == 'EQIC'){
for (i in 1:k){
if (verbose) cat('random initialization',i,'\n')
sol <- pointest(dat,num_class,id,time,num_obs,features,Y_dist,covx,ipw,stop,tol,max,varest,balanced,verbose)
if (sol$qic[[3]] < IC){
best_sol <- sol
IC = sol$qic[[3]]
}
}
}else{
print('Error: MSC undefined.')
}
return(best_sol)
} |
DIMEplot <-
function(x){
dime=x$dime
dime_data=x$dime_data
DIME.plot.fit(dime_data,dime)
} |
require(OpenMx)
data1 <- mxData(matrix(1, dimnames = list('a', 'a')), type="cov", numObs=100)
data2 <- mxData(matrix(2, dimnames = list('a', 'a')), type="cov", numObs=100)
S1 <- mxMatrix("Full", 1.5, free=TRUE, nrow=1, ncol=1, labels="parameter", name="S")
S2 <- mxMatrix("Full", 1.5, free=TRUE, nrow=1, ncol=1, labels="parameter", name="S")
matrixA <- mxMatrix("Zero", nrow=1, ncol=1, name="A")
matrixF <- mxMatrix("Iden", nrow=1, name="F", dimnames = list('a', 'a'))
objective <- mxExpectationRAM("A", "S", "F")
model1<-mxModel("first", matrixA, S1, matrixF, objective, data1, mxFitFunctionML())
model2<-mxModel("second", matrixA, S2, matrixF, objective, data2, mxFitFunctionML())
output1<-mxRun(model1, suppressWarnings=TRUE)
output2<-mxRun(model2, suppressWarnings=TRUE)
alg<-mxAlgebra(first.objective + second.objective, name="alg")
obj <- mxFitFunctionAlgebra("alg")
model <- mxModel("both", alg, obj, model1, model2)
output<-mxRun(model, suppressWarnings=TRUE)
print(output1$output$estimate)
print(output2$output$estimate)
print(output$output$estimate)
omxCheckCloseEnough(output1$output$estimate, .99 * c(1), 0.001)
omxCheckCloseEnough(output2$output$estimate, .99 * c(2), 0.001)
omxCheckCloseEnough(output$output$estimate, .99 * c(1.5), 0.001) |
library(drfit)
data(XY)
rXY <- drfit(XY,logit=TRUE,weibull=TRUE,chooseone=FALSE)
print(rXY,digits=5) |
'.con.skeleton' <- function()
{
obj <- list(driver=NA_character_
,samples=NA_integer_,lines=NA_integer_,bands=NA_integer_
,datatype=NA_integer_,interleave=NA_character_,byteorder=NA_integer_
,endian=NA_character_,swap=NA_integer_,signed=NA
,offset=NA_integer_,wkt=FALSE,nodata=NA_real_,mode="raw"
,sizeof=NA_integer_,indexC=NA_integer_,indexR=NA_integer_,indexZ=NA_integer_
,posC=NA_integer_,posR=NA_integer_,posZ=NA_integer_
,fname=NA_character_,connection=NA_character_
,compress=0L,seek=NA,handle=NA)
class(obj) <- c("ursaConnection")
obj
}
'.is.con' <- function(obj) inherits(obj,"ursaConnection")
'.ursa_connection'<- function(x) {
if (.is.con(x))
return(x)
if (is.ursa(x))
return(x$con)
return(NULL)
}
'print.ursaConnection' <- function(x,...) str(x,...)
'seek.ursaConnection' <- function(con,where=NA,origin="start",rw="",...)
{
if ((1)||(con$seek))
return(seek(con$handle,where=round(where),origin=origin,rw=rw,...))
stop("Reopenning is needed here, but it seems that connection doesn't support seek")
F <- con$handle
if (isOpen(F))
{
close(F)
con$handle <- with(con,do.call(connection,list(fname,"rb")))
}
readBin(con$handle,raw(),n=as.integer(where))
where
} |
power.4 <- function(cost.model = TRUE, expr = NULL, constraint = NULL,
sig.level = 0.05, two.tailed = TRUE,
d = NULL, power = NULL, m = NULL,
n = NULL, J = NULL, K = NULL, L = NULL, p = NULL,
icc2 = NULL, icc3 = NULL, icc4 = NULL,
r12 = NULL, r22 = NULL, r32 = NULL, r42 = NULL, q = NULL,
c1 = NULL, c2 = NULL, c3 = NULL, c4 = NULL,
c1t = NULL, c2t = NULL, c3t = NULL, c4t = NULL,
dlim = NULL, powerlim = NULL, Llim = NULL, mlim = NULL,
rounded = TRUE) {
funName <- "power.4"
designType <- "four-level CRTs"
if (cost.model == TRUE) {
if (sum(sapply(list(m, d, power), is.null)) != 1)
stop("exactly one of 'm', 'd', and 'power' must be NULL
when cost.model is TRUE")
if (!is.null(L))
stop("'L' must be NULL when cost.model is TRUE")
} else {
if (sum(sapply(list(L, d, power), is.null)) != 1)
stop("exactly one of 'L', 'd', and 'power' must be NULL
when cost.model is FALSE")
if (!is.null(m))
stop("'m' must be NULL when cost.model is FALSE")
}
if (!is.null(expr)) {
if (expr$funName != "od.4") {
stop("'expr' can only be NULL or
the return from the function of 'od.4'")
} else {
if (sum(sapply(list(icc2, icc3, icc4, r12, r22, r32, r42, c1, c2, c3, c4,
c1t, c2t, c3t, c4t, n, J, K, p), function(x) {!is.null(x)})) >= 1)
stop("parameters of 'icc2', 'icc3', 'icc4', 'r12', 'r22', 'r32', 'r42',
'c1', 'c2', 'c3', 'c4', 'c1t', 'c2t', 'c3t', 'c4t', 'n', 'J', 'K', and 'p'
have been specified in expr of 'od.4'")
icc2 <- expr$par$icc2
icc3 <- expr$par$icc3
icc4 <- expr$par$icc4
r12 <- expr$par$r12
r22 <- expr$par$r22
r32 <- expr$par$r32
r42 <- expr$par$r42
c1 <- expr$par$c1
c2 <- expr$par$c2
c3 <- expr$par$c3
c4 <- expr$par$c4
c1t <- expr$par$c1t
c2t <- expr$par$c2t
c3t <- expr$par$c3t
c4t <- expr$par$c4t
if (rounded == TRUE) {
n <- round(expr$out$n, 0)
J <- round(expr$out$J, 0)
K <- round(expr$out$K, 0)
p <- round(expr$out$p, 2)
} else {
n <- expr$out$n
J <- expr$out$J
K <- expr$out$K
p <- expr$out$p
}
}
} else {
if (!is.null(constraint))
stop("'constraint' must be NULL when 'expr' is NULL")
}
NumberCheck <- function(x) {!is.null(x) && !is.numeric(x)}
if (!is.null(constraint) && !is.list(constraint))
stop("'constraint' must be in list format
(e.g., constraint = list(p = 0.5, K = 20))")
if (length(constraint) > 4)
stop("'constraint' must be limited to 'n', 'J', 'K', and/or 'p'")
if (!is.null(constraint$n)) {
if(NumberCheck(constraint$n) || constraint$n <= 0)
stop("constrained 'n' must be numeric with n > 0")
n <- constraint$n
}
if (!is.null(constraint$J)) {
if(NumberCheck(constraint$J) || constraint$J <= 0)
stop("constrained 'J' must be numeric with J > 0")
J <- constraint$J
}
if (!is.null(constraint$K)) {
if(NumberCheck(constraint$K) || constraint$K <= 0)
stop("constrained 'K' must be numeric with K > 0")
K <- constraint$K
}
if (!is.null(constraint$p)) {
if(NumberCheck(constraint$p) ||
any (0 >= constraint$p | constraint$p >= 1))
stop("constrained 'p' must be numeric in (0, 1)")
p <- constraint$p
}
if (sum(sapply(list(icc2, icc3, icc4, p, power, sig.level), function(x) {
NumberCheck(x) || any(0 > x | x >= 1)
})) >= 1) stop("'icc2', 'icc3', 'icc4', 'p', 'power', and 'sig.level'
must be numeric in (0, 1)")
if (sum(sapply(list(r12, r22, r32, r42), function(x) {
NumberCheck(x) || any(0 > x | x >= 1)
})) >= 1) stop("'r12', 'r22', 'r32', and 'r42' must be numeric in [0, 1)")
if (cost.model == TRUE){
if (sum(sapply(list(c1, c2, c3, c4, c1t, c2t, c3t, c4t), function(x) {
NumberCheck(x) || x < 0})) >= 1)
stop("'c1', 'c2', 'c3', 'c4', 'c1t', 'c2t', 'c3t', 'c4t' must be numeric in [0, Inf)")
if (NumberCheck(m))
stop("'m' must be numeric in [0, Inf)")
}
if (NumberCheck(q) | q < 0)
stop("'q' must be numeric with q >= 0")
if (NumberCheck(n) || n <= 0)
stop("'n' must be numeric with n > 0")
if (NumberCheck(J) || J <= 0)
stop("'J' must be numeric with J > 0")
if (NumberCheck(K) || K <= 0)
stop("'K' must be numeric with K > 0")
if (NumberCheck(d) || any(0 > d | d > 5))
stop("'d' must be numeric in [0, 5],
please transfer negative effect size to positive one if needed")
par <- list(cost.model = cost.model,
sig.level = sig.level,
two.tailed = two.tailed,
d = d, icc2 = icc2, icc3 = icc3, icc4 = icc4,
r12 = r12, r22 = r22, r32 = r32, r42 = r42,
c1 = c1, c2 = c2, c3 = c3, c4 = c4,
c1t = c1t, c2t = c2t, c3t = c3t, c4t = c4t,
n = n, J = J, K = K, L = L, p = p,
q = q, m = m, power = power)
tside <- ifelse(two.tailed == TRUE, 2, 1)
if (cost.model == TRUE) {
if (two.tailed == TRUE) {
pwr.expr <- quote({
L <- m / ((1 - p) * (c1 * n * J * K + c2 * J * K + c3 * K + c4) +
p * (c1t * n * J * K + c2t * J * K + c3t * K + c4t));
lambda <- d * sqrt(p * (1 - p) * m /
((1 - p) * (c1 * n * J * K + c2 * J * K + c3 * K + c4) +
p * (c1t * n * J * K + c2t * J * K + c3t * K + c4t))) /
sqrt(icc4 * (1 - r42) + icc3 * (1 - r32) / K + icc2 * (1 - r22) / (J * K ) +
(1 - icc2 - icc3 - icc4) * (1 - r12) / (n * J * K));
1 - pt(qt(1 - sig.level / tside, df = L - q - 2) ,
df = L - q - 2, lambda) +
pt(qt(sig.level / tside, df = L - q - 2),
df = L - q - 2, lambda)
})
} else {
pwr.expr <- quote({
L <- m / ((1 - p) * (c1 * n * J * K + c2 * J * K + c3 * K + c4) +
p * (c1t * n * J * K + c2t * J * K + c3t * K + c4t));
lambda <- d * sqrt(p * (1 - p) * m /
((1 - p) * (c1 * n * J * K + c2 * J * K + c3 * K + c4) +
p * (c1t * n * J * K + c2t * J * K + c3t * K + c4t))) /
sqrt(icc4 * (1 - r42) + icc3 * (1 - r32) / K + icc2 * (1 - r22) / (J * K ) +
(1 - icc2 - icc3 - icc4) * (1 - r12) / (n * J * K));
1 - pt(qt(1 - sig.level / tside, df = L - q - 2),
df = L - q - 2, lambda)
})
}
} else {
if (two.tailed == TRUE) {
pwr.expr <- quote({
lambda <- d * sqrt(p * (1 - p) * L) /
sqrt(icc4 * (1 - r42) + icc3 * (1 - r32) / K + icc2 * (1 - r22) / (J * K ) +
(1 - icc2 - icc3 - icc4) * (1 - r12) / (n * J * K));
1 - pt(qt(1 - sig.level / tside, df = L - q - 2),
df = L - q - 2, lambda) +
pt(qt(sig.level / tside, df = L - q - 2),
df = L - q - 2, lambda)
})
} else {
pwr.expr <- quote({
lambda <- d * sqrt(p * (1 - p) * L) /
sqrt(icc4 * (1 - r42) + icc3 * (1 - r32) / K + icc2 * (1 - r22) / (J * K ) +
(1 - icc2 - icc3 - icc4) * (1 - r12) / (n * J * K));
1 - pt(qt(1 - sig.level / tside, df = L - q - 2),
df = L - q - 2, lambda)
})
}
}
limFun <- function(x, y) {
if (!is.null(x) && length(x) == 2 && is.numeric(x)) {x} else {y}
}
Llim <- limFun(x = Llim, y = c(4, 1e+10))
powerlim <- limFun(x = powerlim, y = c(1e-10, 1 - 1e-10))
dlim <- limFun(x = dlim, y = c(0, 5))
if(cost.model == TRUE) {
if (is.null(power)) {
out <- list(power = eval(pwr.expr))
} else if (is.null(m)) {
Lcost <- ((1 - p) * (c1 * n * J * K + c2 * J * K + c3 * K + c4) +
p * (c1t * n * J * K + c2t * J * K + c3t * K + c4t))
mlim <- limFun(x = mlim, y = c(Llim[1] * Lcost, Llim[2] * Lcost))
out <- list(m = stats::uniroot(function(m)
eval(pwr.expr) - power, mlim)$root)
out <- c(out, list(L = out$m / ((1 - p) * (c1 * n * J * K + c2 * J * K + c3 * K + c4) +
p * (c1t * n * J * K + c2t * J * K + c3t * K + c4t))))
} else if (is.null(d)) {
out <- list(d = stats::uniroot(function(d)
eval(pwr.expr) - power, dlim)$root)
}
} else {
if (is.null(power)) {
out <- list(power = eval(pwr.expr))
} else if (is.null(L)) {
out <- list(L = stats::uniroot(function(L)
eval(pwr.expr) - power, Llim)$root)
} else if (is.null(d)) {
out <- list(d = stats::uniroot(function(d)
eval(pwr.expr) - power, dlim)$root)
}
}
power.out <- list(funName = funName,
designType = designType,
par = par, out = out)
return(power.out)
} |
library(RSQLite)
temp_dir <- tempdir()
test_that("The `x_write_disk()` and `x_read_disk()` functions works as expected", {
agent <-
create_agent(tbl = small_table) %>%
rows_distinct() %>%
interrogate()
expect_length(agent$extracts, 1)
expect_equal(names(agent$extracts), "1")
expect_equal(
names(agent$extracts[[1]]),
c("date_time", "date", "a", "b", "c", "d", "e", "f")
)
expect_s3_class(
agent %>%
unclass() %>%
.$validation_set %>%
.$tbl_checked %>%
.[[1]] %>%
.[[1]],
"tbl_df"
)
agent %>% x_write_disk(filename = "agent_test_1", path = temp_dir)
expect_true("agent_test_1" %in% list.files(path = temp_dir))
agent_test_1 <- x_read_disk(filename = file.path(temp_dir, "agent_test_1"))
expect_s3_class(agent_test_1, "ptblank_agent")
expect_s3_class(agent_test_1, "has_intel")
expect_null(agent_test_1$tbl)
agent_test_1 <- agent_test_1 %>% set_tbl(small_table)
expect_s3_class(agent_test_1$tbl, "tbl_df")
expect_type(agent_test_1$extracts, "list")
expect_identical(agent_test_1$extracts, list())
expect_null(
agent_test_1 %>%
unclass() %>%
.$validation_set %>%
.$tbl_checked %>%
.[[1]]
)
agent %>%
x_write_disk(filename = "agent_test_2", path = temp_dir, keep_tbl = TRUE)
expect_true("agent_test_2" %in% list.files(path = temp_dir))
agent_test_2 <- x_read_disk(filename = file.path(temp_dir, "agent_test_2"))
expect_s3_class(agent_test_2, "ptblank_agent")
expect_s3_class(agent_test_2, "has_intel")
expect_s3_class(agent_test_2$tbl, "tbl_df")
expect_equivalent(agent_test_2$tbl, small_table)
expect_type(agent_test_2$extracts, "list")
expect_identical(agent_test_2$extracts, list())
agent <-
create_agent(tbl = small_table_sqlite()) %>%
rows_distinct() %>%
interrogate()
agent %>% x_write_disk(filename = "agent_test_3", path = temp_dir)
expect_true("agent_test_3" %in% list.files(path = temp_dir))
agent_test_3 <- x_read_disk(filename = file.path(temp_dir, "agent_test_3"))
expect_s3_class(agent_test_3, "ptblank_agent")
expect_s3_class(agent_test_3, "has_intel")
expect_null(agent_test_3$tbl)
agent_test_3 <- agent_test_3 %>% set_tbl(small_table_sqlite())
expect_s3_class(agent_test_3$tbl, "tbl_dbi")
expect_type(agent_test_3$extracts, "list")
expect_identical(agent_test_3$extracts, list())
expect_warning(
agent %>%
x_write_disk(filename = "agent_test_4", path = temp_dir, keep_tbl = TRUE)
)
expect_true("agent_test_4" %in% list.files(path = temp_dir))
agent_test_4 <- x_read_disk(filename = file.path(temp_dir, "agent_test_4"))
expect_s3_class(agent_test_4, "ptblank_agent")
expect_s3_class(agent_test_4, "has_intel")
expect_null(agent_test_4$tbl)
expect_type(agent_test_4$extracts, "list")
expect_identical(agent_test_4$extracts, list())
agent_test_4 <- agent_test_4 %>% set_tbl(tbl = small_table)
expect_s3_class(agent_test_4$tbl, "tbl_df")
expect_equivalent(agent_test_4$tbl, small_table)
expect_equal(agent_test_4$tbl_name, "small_table_sqlite()")
expect_equal(agent_test_4$db_tbl_name, NA_character_)
expect_equal(agent_test_4$tbl_src, "tbl_df")
expect_equal(agent_test_4$tbl_src_details, NA_character_)
agent_test_4 <- agent_test_4 %>% remove_tbl()
expect_null(agent_test_4$tbl)
agent_test_4 <- small_table %>% set_tbl(x = agent_test_4, tbl = .)
expect_s3_class(agent_test_4$tbl, "tbl_df")
expect_equivalent(agent_test_4$tbl, small_table)
expect_equal(agent_test_4$tbl_name, "small_table_sqlite()")
expect_equal(agent_test_4$db_tbl_name, NA_character_)
expect_equal(agent_test_4$tbl_src, "tbl_df")
expect_equal(agent_test_4$tbl_src_details, NA_character_)
agent_test_4 <-
agent_test_4 %>%
remove_tbl() %>%
set_tbl(tbl = ~ small_table)
expect_null(agent_test_4$tbl)
expect_true(rlang::is_formula(agent_test_4$read_fn))
expect_true(rlang::is_bare_formula(agent_test_4$read_fn))
agent_test_4 <- agent_test_4 %>% remove_tbl()
expect_null(agent_test_4$tbl)
expect_null(agent_test_4$read_fn)
})
test_that("The `set_tbl()` function works as expected", {
agent <- create_agent(tbl = specifications)
expect_s3_class(agent$tbl, "tbl_df")
expect_equivalent(agent$tbl, specifications)
expect_null(agent$read_fn)
expect_equal(agent$tbl_name, "specifications")
expect_match(agent$label, "\\[.*?\\]")
expect_equal(agent$col_names, colnames(specifications))
agent_replace_1 <- agent %>% set_tbl(tbl = game_revenue)
expect_s3_class(agent_replace_1$tbl, "tbl_df")
expect_equivalent(agent_replace_1$tbl, game_revenue)
expect_null(agent_replace_1$read_fn)
expect_equal(agent_replace_1$tbl_name, "specifications")
expect_equal(agent_replace_1$label, agent$label)
expect_equal(agent_replace_1$col_names, colnames(game_revenue))
agent_replace_2 <-
agent %>%
set_tbl(
tbl = game_revenue,
tbl_name = "game_revenue",
label = "Checking the game revenue table."
)
expect_s3_class(agent_replace_2$tbl, "tbl_df")
expect_equivalent(agent_replace_2$tbl, game_revenue)
expect_null(agent_replace_2$read_fn)
expect_equal(agent_replace_2$tbl_name, "game_revenue")
expect_match(agent_replace_2$label, "Checking the game revenue table.")
expect_equal(agent_replace_2$col_names, colnames(game_revenue))
agent_replace_3 <-
agent %>%
set_tbl(
tbl = ~ pointblank::game_revenue,
tbl_name = "game_revenue",
label = "Checking the game revenue table."
)
expect_null(agent_replace_3$tbl)
expect_true(rlang::is_formula(agent_replace_3$read_fn))
expect_true(rlang::is_bare_formula(agent_replace_3$read_fn))
expect_equal(agent_replace_3$tbl_name, "game_revenue")
expect_match(agent_replace_3$label, "Checking the game revenue table.")
expect_equal(agent_replace_3$col_names, colnames(game_revenue))
}) |
psimplex <-
function (q, mu, sig) {
ll<-length(q)
pp<-rep(0,ll)
dsimp <- function(x){1/sqrt(2*pi*sig^2*(x*(1-x))^3)*exp(-1/2/sig^2*(x-mu)^2/(x*(1-x)*mu^2*(1-mu)^2))}
for (i in 1:ll) {
if (sig < 0.001 | (1-mu)*sig < 0.01) {pp[i] <- psimplex.norm(q[i], mu, sig)}
else {
tem<-integrate(Vectorize(dsimp), lower=0, upper=q[i])
pp[i]<-tem$value
}
}
return(pp)
} |
tidy.htest <- function(x, ...) {
ret <- x[c("estimate", "statistic", "p.value", "parameter")]
if (length(ret$estimate) > 1) {
names(ret$estimate) <- paste0("estimate", seq_along(ret$estimate))
ret <- c(ret$estimate, ret)
ret$estimate <- NULL
if (x$method %in% c("Welch Two Sample t-test", " Two Sample t-test")) {
ret <- c(estimate = ret$estimate1 - ret$estimate2, ret)
}
}
if (length(x$parameter) > 1) {
ret$parameter <- NULL
if (is.null(names(x$parameter))) {
warning("Multiple unnamed parameters in hypothesis test; dropping them")
} else {
np <- names(x$parameter)
np <- stringr::str_replace(np, "num df", "num.df")
np <- stringr::str_replace(np, "denom df", "den.df")
names(x$parameter) <- np
message(
"Multiple parameters; naming those columns ",
paste(np, collapse = ", ")
)
ret <- append(ret, x$parameter, after = 1)
}
}
ret <- purrr::compact(ret)
if (!is.null(x$conf.int)) {
ret <- c(ret, conf.low = x$conf.int[1], conf.high = x$conf.int[2])
}
if (!is.null(x$method)) {
ret <- c(ret, method = trimws(as.character(x$method)))
}
if (!is.null(x$alternative)) {
ret <- c(ret, alternative = as.character(x$alternative))
}
as_tibble(ret)
}
glance.htest <- function(x, ...) tidy(x)
augment.htest <- function(x, ...) {
if (all(c("observed", "expected", "residuals", "stdres") %in% names(x))) {
return(augment_chisq_test(x, ...))
}
stop(
"Augment is only defined for chi squared hypothesis tests.",
call. = FALSE
)
}
augment_chisq_test <- function(x, ...) {
d <- length(dimnames(as.table(x$observed)))
ret <- as.data.frame(as.table(x$observed))
names(ret)[d + 1] <- ".observed"
ret <- cbind(
ret,
.prop = as.data.frame(prop.table(as.table(x$observed)))[[d + 1]]
)
if (d == 2) {
ret <- cbind(
ret,
.row.prop = as.data.frame(prop.table(as.table(x$observed), 1))[[d + 1]]
)
ret <- cbind(
ret,
.col.prop = as.data.frame(prop.table(as.table(x$observed), 2))[[d + 1]]
)
}
ret <- cbind(ret, .expected = as.data.frame(as.table(x$expected))[[d + 1]])
ret <- cbind(ret, .resid = as.data.frame(as.table(x$residuals))[[d + 1]])
ret <- cbind(ret, .std.resid = as.data.frame(as.table(x$stdres))[[d + 1]])
as_tibble(ret)
}
tidy.pairwise.htest <- function(x, ...) {
tibble(group1 = rownames(x$p.value)) %>%
cbind(x$p.value) %>%
pivot_longer(
cols = c(dplyr::everything(), -group1),
names_to = "group2",
values_to = "p.value"
) %>%
stats::na.omit() %>%
as_tibble()
}
tidy.power.htest <- function(x, ...) {
cols <- purrr::compact(x[c("n", "delta", "sd", "sig.level", "power", "p1", "p2")])
as_tibble(cols)
} |
local({
dependencies <- c(
"fortunes",
"stringr",
"sos",
"XLConnect",
"reshape2",
"ggplot2",
"foreign"
)
for (pkg in dependencies) {
if (!require(pkg, character.only = TRUE)) install.packages(pkg)
}
})
list.files(here::here("inst"))
local({
source(here::here("inst/cleanscripts.R"), local = TRUE)
source(here::here("inst/chapters.R"), local = TRUE)
.generateChapters()
})
devtools::load_all()
devtools::document()
devtools::check_man()
devtools::test()
devtools::run_examples(run = FALSE)
devtools::check()
covr::package_coverage()
library(foreach)
oldwd <- getwd()
foreach(
ch = paste0("ch", 1:20),
.errorhandling = "pass",
.combine = c
) %do% {
system.time(devtools::dev_example(ch))[[3]]
}
sapply(
paste0("ch", 1:20),
function(ch) {
system.time(devtools::dev_example(ch))[[3]]
}
)
setwd(oldwd)
devtools::dev_example("ch1")
devtools::run_examples("rfordummies", fresh = TRUE, start = "ch7")
devtools::run_examples("rfordummies", fresh = TRUE)
tools::showNonASCIIfile("rfordummies/inst/scripts/2-clean/ch13.R")
tools::showNonASCII
showPDFmanual <- function(package, lib.loc = NULL) {
path <- find.package(package, lib.loc)
system(paste(
shQuote(file.path(R.home("bin"), "R")),
"CMD", "Rd2pdf",
shQuote(path)
))
}
showPDFmanual("rfordummies") |
loon_defaultSerialaxesSettings_args <- function() {
list(
titleFontsize = 18,
parallelXlim = c(-0.1, 1.12),
parallelYlim = c(-0.1, 1.12),
radialXlim = c(-0.2, 1.2),
radialYlim = c(-0.2, 1.2),
radius = 0.2,
guidesBackground = loon::l_getOption("canvas_bg_guides"),
lineColor1 = loon::l_getOption("background"),
lineColor2 = loon::l_getOption("foreground"),
guideLineWidth = 2,
labelFontsize = 9,
linewidthDefault = 1,
radiusOffset = 0.1,
margins = rep(0,4)
)
} |
context("Aus pop qtr")
test_that("Returns correct values", {
skip("Slight differences temporarily")
expect_equal(aus_pop_qtr("2016-Q1"), 24122701)
expect_gte(aus_pop_qtr("2018-Q1"), 24122701)
expect_gte(aus_pop_qtr("2018-Q4"), 25e6)
expect_equivalent(grattan:::aust_pop_by_age_yearqtr, aus_pop_qtr_age(tbl = TRUE))
expect_equal(aus_pop_qtr_age(age = 1)[1:139], c(226775L, 228838L, 230676L, 232589L, 233901L, 235023L, 236046L,
237097L, 238209L, 239285L, 240219L, 241246L, 241007L, 240648L,
240264L, 239865L, 240552L, 241269L, 241865L, 242597L, 242144L,
241668L, 241309L, 241123L, 242094L, 242863L, 243728L, 244292L,
245486L, 246449L, 247244L, 247817L, 248769L, 249652L, 250492L,
251302L, 252949L, 254438L, 256051L, 257523L, 258352L, 258949L,
259498L, 259878L, 259595L, 259090L, 258538L, 257688L, 257979L,
258087L, 258236L, 258426L, 258483L, 258180L, 257992L, 258057L,
258215L, 258393L, 258260L, 258399L, 257840L, 257119L, 256177L,
255188L, 255039L, 254899L, 254705L, 254452L, 253480L, 252544L,
251516L, 250579L, 250989L, 251449L, 251866L, 252358L, 252563L,
252868L, 253285L, 253737L, 253484L, 253209L, 252893L, 252634L,
252156L, 251629L, 251016L, 250356L, 250391L, 250477L, 250464L,
250613L, 251432L, 252241L, 253063L, 253896L, 255230L, 256526L,
257695L, 258624L, 261571L, 264477L, 267518L, 270527L, 274659L,
278285L, 281747L, 284625L, 286620L, 288335L, 290044L, 291342L,
292237L, 292749L, 293227L, 293410L, 294011L, 294311L, 294550L,
294616L, 294397L, 293969L, 293637L, 293110L, 296848L, 300623L,
304219L, 307681L, 308917L, 309894L, 310986L, 311858L, 310855L,
309617L, 308503L, 307228L, 307658L, 307941L, 308384L),
tol = 5000,
scale = 1)
expect_equal(aus_pop_qtr_age(date = as.Date("2015-01-01")),
c(309617L, 312599L, 306541L, 303699L, 305330L, 303537L, 300446L,
297943L, 293234L, 286061L, 282031L, 279984L, 281517L, 284300L,
285830L, 287508L, 291708L, 299841L, 311240L, 318711L, 321363L,
327558L, 338210L, 348732L, 350418L, 347623L, 348155L, 351251L,
354769L, 354764L, 353178L, 347888L, 339953L, 330734L, 320947L,
314057L, 310080L, 309487L, 311774L, 317426L, 324486L, 334968L,
344388L, 337275L, 325377L, 316584L, 306372L, 302143L, 302689L,
307728L, 313202L, 314544L, 313673L, 307614L, 299841L, 293950L,
286990L, 281536L, 275374L, 266933L, 261028L, 254757L, 248233L,
243826L, 237515L, 234429L, 239057L, 224090L, 200610L, 191115L,
176760L, 165396L, 157278L, 147678L, 140354L, 132014L, 124122L,
117245L, 109200L, 100965L, 94738L, 89194L, 85082L, 80922L, 74057L,
66857L, 59752L, 52432L, 45257L, 38161L, 31289L, 25353L, 20199L,
15161L, 10386L, 6943L, 5041L, 3669L, 2590L, 4130L),
tol = 10e3,
scale = 1)
})
test_that("Multiple unordered", {
expect_equal(aus_pop_qtr_age(date = as.Date(c("2015-12-01", "2013-12-01", "2014-12-01")),
age = c(2, 1, 3)),
c(311984, 309894, 306541),
tol = 5000,
scale = 1)
})
test_that("Rolls work as expected", {
expect_equal(aus_pop_qtr_age(date = as.Date("2015-01-01")),
aus_pop_qtr_age(date = as.Date("2015-01-02"), roll = TRUE))
})
test_that("Error handling", {
expect_error(aus_pop_qtr("2016 Q0"), "Entry 1 was not in the correct form")
expect_error(aus_pop_qtr(c("2016 Q0", "2016-Q2", "19999")), "Entries 1 and 3 were not in the correct form")
expect_error(aus_pop_qtr(c("2016 Q0", "2016-Q-", "19999")), "There were 2 other bad entries.")
expect_error(aus_pop_qtr(c("2016 Q0", "2016 q1")), "Entries 1 and 2 were not in the correct form")
expect_error(aus_pop_qtr_age(age = "45"))
expect_error(aus_pop_qtr_age(age = 101))
expect_error(aus_pop_qtr_age(age = -99))
expect_warning(aus_pop_qtr_age(date = as.Date("2099-01-01"), age = 1, roll = TRUE, roll.beyond = FALSE))
expect_warning(aus_pop_qtr("2050-Q1", allow.projections = FALSE),
regexp = "Using an earlier date than specified")
expect_error(aus_pop_qtr_age(age = 50:52, date = rep(as.Date("2015-01-01"), 2)),
regexp = "`date` and `age` can only have different lengths when the smaller length is 1.",
fixed = TRUE)
expect_error(aus_pop_qtr_age(age = 50:51, date = rep(as.Date("2015-01-01"), 3)),
regexp = "`date` and `age` can only have different lengths when the smaller length is 1.",
fixed = TRUE)
}) |
Read.PeakList<-function(mSetObj=NA, foldername="upload"){
mSetObj <- .get.mSet(mSetObj);
if(.on.public.web){
dyn.load(.getDynLoadPath());
}
msg <- c("The uploaded files are peak lists and intensities data.");
files<-dir(foldername, pattern=".[Cc][Ss][Vv]$", recursive=T, full.names=TRUE)
if (length(files) == 0) {
AddErrMsg("No peak list files (.csv) were found.");
return(0);
}
snames <- gsub("\\.[^.]*$", "", basename(files));
msg<-c(msg, paste("A total of ", length(files), "samples were found."));
sclass <- gsub("^\\.$", "sample", dirname(files));
scomp <- strsplit(substr(sclass, 1, min(nchar(sclass))), "", fixed=TRUE);
scomp <- matrix(c(scomp, recursive = TRUE), ncol = length(scomp));
i <- 1
while(all(scomp[i,1] == scomp[i,-1]) && i < nrow(scomp)){
i <- i + 1;
}
i <- min(i, tail(c(0, which(scomp[1:i,1] == .Platform$file.sep)), n = 1) + 1)
if (i > 1 && i <= nrow(scomp)){
sclass <- substr(sclass, i, max(nchar(sclass)))
}
sclass <- as.factor(sclass);
if(length(levels(sclass))<2){
AddErrMsg("You must provide classes labels (at least two classes)!");
return(0);
}
if(min(table(sclass)) < 3){
AddErrMsg("At least three replicates are required in each group!");
return(0);
}
if(length(unique(snames))!=length(snames)){
AddErrMsg("Duplcate sample names are not allowed!");
dup.nm <- paste(snames[duplicated(snames)], collapse=" ");
AddErrMsg("Duplicate sample names are not allowed!");
AddErrMsg(dup.nm);
return(0);
}
samp.num<-seq(1:length(snames));
names(samp.num)<-snames;
pks<- .readDataTable(files[1]);
if(class(pks) == "try-error") {
AddErrMsg("The CSV file is not formatted correctly!");
return(0);
};
pks <- as.matrix(pks);
n.col<-ncol(pks);
if(n.col==2){
add=TRUE;
}else if(n.col==3){
add=FALSE;
}else{
AddErrMsg("The peak list file can only contain 2 or 3 columns.");
return(0);
}
all.peaks<-NULL;
for(i in 1:length(files)){
print(files[i]);
pks<- as.matrix(.readDataTable(files[i]));
if(ncol(pks)!=n.col){
AddErrMsg("The number of columns in each file are not the same!");
return(0);
}
if(add){
pks<-cbind(pks[,1], 1000, pks[,2],samp.num[i]);
}else{
pks<-cbind(pks,samp.num[i]);
}
all.peaks<-rbind(all.peaks, pks);
}
all.peaks <- apply(all.peaks, 2, as.numeric);
gd.inx <- complete.cases(all.peaks);
all.peaks <- all.peaks[gd.inx,]
if(sum(!gd.inx) > 0){
msg<-c(msg, paste("<font color='red'>A total of", sum(!gd.inx), "peaks were excluded due to non-numeric values. </font>" ));
}
msg<-c(msg, paste("These samples contain a total of ", dim(all.peaks)[1], "peaks," ));
msg<-c(msg, paste("with an average of ", round(dim(all.peaks)[1]/length(files), 1), "peaks per sample" ));
colnames(all.peaks)<-c("mz","rt","int","sample");
peakSet<-list(
peaks = all.peaks,
ncol = n.col,
sampclass = sclass,
sampnames = snames
);
qs::qsave(peakSet, "peakSet.qs");
mSetObj$msgSet$read.msg <- msg;
return(.set.mSet(mSetObj));
}
Read.mzTab <- function(mSetObj=NA, filename, identifier = "name") {
mSetObj <- .get.mSet(mSetObj);
msg <- NULL;
ncol <- max(stats::na.omit(utils::count.fields(file=filename, sep = "\t")))
mztab.table = utils::read.table(file=filename, header=FALSE,
row.names=NULL, dec = ".", fill = TRUE,
col.names = paste0("V", seq_len(ncol)),
sep="\t", na.strings="null", quote = "",
stringsAsFactors = FALSE)
if(sum(sapply(c("MTD", "SMH", "SML"), grepl, unique(mztab.table$V1))) == 3){
msg <- ("mzTab format ok!")
}else{
AddErrMsg("Invalid mzTab format! Make sure mzTab file has been validated!")
return(0)
}
metadata <- mztab.table[startsWith(as.character(mztab.table$V1), "MTD"),]
variables <- metadata[grepl("study_variable", metadata$V2),]
if(length(variables) < 1){
AddErrMsg("Invalid mzTab format! Make sure mzTab file has been validated!")
return(0)
}
variables.groups <- unique(gsub("-.*", "", variables$V2))
group.names <- metadata$V3[match(variables.groups, metadata$V2)]
variables.list <- vector("list", length=length(variables.groups))
names(variables.list) <- variables.groups
for(i in 1:length(variables.groups)){
group2match <- gsub("\\[", "\\\\[", variables.groups[i])
group2match <- gsub("\\]", "\\\\]", group2match)
all.info <- variables[grepl(group2match, variables$V2),]
assay.refs <- all.info$V3[grepl("assay_refs", all.info$V2)]
variables.list[i] <- assay.refs
}
smh <- mztab.table[startsWith(as.character(mztab.table$V1), "SMH"),,drop=FALSE]
sml <- mztab.table[startsWith(as.character(mztab.table$V1), "SML"),,drop=FALSE]
if(nrow(sml) < 1){
AddErrMsg("Invalid mzTab format! Make sure mzTab file has been validated!")
return(0)
}
sml.data.frame <- data.frame(sml, stringsAsFactors = FALSE)
colnames(sml.data.frame) <- as.character(smh[1,])
if(sum(is.null(sml.data.frame$chemical_name))/length(sml.data.frame$chemical_name) > 0.1) {
msg <- c(msg, "Too many missing chemical names, will use theoretical neutral mass instead!")
identifier <- "mass"
}else if(sum(is.null(sml.data.frame$theoretical_neutral_mass))/length(sml.data.frame$theoretical_neutral_mass) > 0.1){
msg <- c(msg, "Too many missing m/z, will use mzTab SML_ID instead!")
identifier <- "sml_id"
}else if(sum(is.na(sml.data.frame$theoretical_neutral_mass))/length(sml.data.frame$theoretical_neutral_mass) > 0.1){
msg <- c(msg, "Too many missing m/z, will use mzTab SML_ID instead!")
identifier <- "sml_id"
}
if(identifier == "name"){
id.og <- id <- sml.data.frame$chemical_name
dup.id <- paste(sml.data.frame$chemical_name, sml.data.frame$adduct_ions, sep="_")
id[which(duplicated(id, fromLast = TRUE) | duplicated(id))] <- dup.id[which(duplicated(id, fromLast = TRUE) | duplicated(id))]
}else if(identifier == "mass"){
id.og <- id <- round(as.numeric(sml.data.frame$theoretical_neutral_mass), 5)
dup.id <- paste( round(as.numeric(sml.data.frame$theoretical_neutral_mass), 5), sml.data.frame$adduct_ions, sep="_")
id[which(duplicated(id, fromLast = TRUE) | duplicated(id))] <- dup.id[which(duplicated(id, fromLast = TRUE) | duplicated(id))]
}else{
id <- sml.data.frame$SML_ID;
}
if(sum(duplicated(id)) > 1){
id <- paste(id.og, sml.data.frame$SML_ID, sep="_")
}
assay_data <- trimws(unlist( lapply(variables.list, function(x) strsplit(x, "\\|")) ))
assay_data <- paste("abundance_", assay_data, sep="")
assay_df <- sml.data.frame[,match(assay_data, colnames(sml.data.frame))]
assay_table <- cbind.data.frame(Sample=id, assay_df, stringsAsFactors = FALSE)
samples <- colnames(assay_table)[-1]
samples_base <- gsub("abundance_", "", samples)
variables.list <- lapply(variables.list, function(x) trimws(unlist(strsplit(x, "\\|"))))
samples2groups <- vector(length = length(samples_base))
for(i in 1:length(samples_base)){
samples2groups[i] <- group.names[sapply(variables.list, function(x) samples_base[i] %in% x)]
}
blank.inx <- grepl("blank", samples2groups, ignore.case = TRUE)
if(sum(blank.inx) > 0){
samples2groups <- samples2groups[!blank.inx]
assay_table <- cbind.data.frame(Sample=id, assay_df[,!blank.inx], stringsAsFactors = FALSE)
}
assay_table_all <- rbind.data.frame(c("Group", samples2groups), assay_table)
colnames(assay_table_all) <- gsub("\\[|\\]", "", colnames(assay_table_all))
fast.write.csv(assay_table_all, "mzTab_parsed.csv", row.names = F)
mSetObj$dataSet$cls.type <- "disc";
mSetObj$dataSet$format <- "colu";
dat <- assay_table_all
msg <- c(msg, "Samples are in columns and features in rows.");
var.nms <- dat[-1,1];
dat[,1] <- NULL;
smpl.nms <- colnames(dat);
cls.lbl <- unname(unlist(dat[1,]));
conc <- t(dat[-1,]);
mSetObj$dataSet$type.cls.lbl <- class(cls.lbl);
dat <- NULL;
msg <- c(msg, "The uploaded file is in the mzTab format.");
empty.inx <- is.na(smpl.nms) | smpl.nms == ""
if(sum(empty.inx) > 0){
msg <- c(msg, paste("<font color=\"red\">", sum(empty.inx), "empty rows</font> were detected and excluded from your data."));
smpl.nms <- smpl.nms[!empty.inx];
cls.lbl <- cls.lbl[!empty.inx];
conc <- conc[!empty.inx, ];
}
empty.inx <- is.na(cls.lbl) | cls.lbl == ""
if(sum(empty.inx) > 0){
if(mSetObj$analSet$type != "roc"){
msg <- c(msg, paste("<font color=\"red\">", sum(empty.inx), "empty labels</font> were detected and excluded from your data."));
smpl.nms <- smpl.nms[!empty.inx];
cls.lbl <- cls.lbl[!empty.inx];
conc <- conc[!empty.inx, ];
}else{
cls.lbl[is.na(cls.lbl)] <- "";
msg <- c(msg, paste("<font color=\"orange\">", sum(empty.inx), "new samples</font> were detected from your data."));
}
}
if(length(unique(smpl.nms))!=length(smpl.nms)){
dup.nm <- paste(smpl.nms[duplicated(smpl.nms)], collapse=" ");
AddErrMsg("Duplicate sample names are not allowed!");
AddErrMsg(dup.nm);
return(0);
}
empty.inx <- is.na(var.nms) | var.nms == "";
if(sum(empty.inx) > 0){
msg <- c(msg, paste("<font color=\"red\">", sum(empty.inx), "empty features</font> were detected and excluded from your data."));
var.nms <- var.nms[!empty.inx];
conc <- conc[,!empty.inx];
}
if(length(unique(var.nms))!=length(var.nms)){
dup.nm <- paste(var.nms[duplicated(var.nms)], collapse=" ");
AddErrMsg("Duplicate feature names are not allowed!");
AddErrMsg(dup.nm);
return(0);
}
if(sum(is.na(iconv(smpl.nms)))>0){
na.inx <- is.na(iconv(smpl.nms));
nms <- paste(smpl.nms[na.inx], collapse="; ");
AddErrMsg(paste("No special letters (i.e. Latin, Greek) are allowed in sample names!", nms, collapse=" "));
return(0);
}
if(sum(is.na(iconv(var.nms)))>0){
na.inx <- is.na(iconv(var.nms));
nms <- paste(var.nms[na.inx], collapse="; ");
AddErrMsg(paste("No special letters (i.e. Latin, Greek) are allowed in feature names!", nms, collapse=" "));
return(0);
}
url.smp.nms <- CleanNames(smpl.nms);
names(url.smp.nms) <- smpl.nms;
url.var.nms <- CleanNames(var.nms);
names(url.var.nms) <- var.nms;
cls.lbl <- ClearStrings(as.vector(cls.lbl));
rownames(conc) <- smpl.nms;
colnames(conc) <- var.nms;
qs::qsave(conc, file="data_orig.qs");
if(min(table(cls.lbl)) < 3){
AddErrMsg(paste ("A total of", length(levels(as.factor(cls.lbl))), "groups found with", length(smpl.nms), "samples."));
AddErrMsg("At least three replicates are required in each group!");
AddErrMsg("Or maybe you forgot to specify the data format?");
return(0);
}
if(length(unique(cls.lbl)) == 1){
AddErrMsg("At least two groups are required for statistical analysis!");
return(0);
}
mSetObj$dataSet$orig.cls <- mSetObj$dataSet$cls <- as.factor(as.character(cls.lbl));
mSetObj$dataSet$mumType <- "table";
mSetObj$dataSet$url.var.nms <- url.var.nms;
mSetObj$dataSet$url.smp.nms <- url.smp.nms;
mSetObj$msgSet$read.msg <- c(msg, paste("The uploaded data file contains ", nrow(conc),
" (samples) by ", ncol(conc), " (", tolower(GetVariableLabel(mSetObj$dataSet$type)), ") data matrix.", sep=""));
return(.set.mSet(mSetObj));
}
GroupPeakList <- function(mSetObj=NA, mzwid = 0.25, bw = 30, minfrac = 0.5, minsamp = 1, max = 50) {
mSetObj <- .get.mSet(mSetObj);
peakSet <- qs::qread("peakSet.qs");
samples <- peakSet$sampnames;
classlabel <- peakSet$sampclass;
classnames <- levels(classlabel)
classlabel <- as.vector(unclass(classlabel))
classnum <- integer(max(classlabel))
for (i in seq(along = classnum)){
classnum[i] <- sum(classlabel == i)
}
peakmat <- peakSet$peaks;
porder <- order(peakmat[,"mz"]);
peakmat <- peakmat[porder,,drop=F]
rownames(peakmat) <- NULL
retrange <- range(peakmat[,"rt"])
minpeakmat <- min(classnum)/2
mass <- seq(peakmat[1,"mz"], peakmat[nrow(peakmat),"mz"] + mzwid, by = mzwid/2)
masspos <- findEqualGreaterM(peakmat[,"mz"], mass)
groupmat <- matrix(nrow = 512, ncol = 7 + length(classnum))
groupindex <- vector("list", 512)
endidx <- 0
num <- 0
gcount <- integer(length(classnum))
for (i in seq(length = length(mass)-2)) {
startidx <- masspos[i]
endidx <- masspos[i+2]-1
if (endidx - startidx + 1 < minpeakmat)
next
speakmat <- peakmat[startidx:endidx,,drop=FALSE]
den <- density(speakmat[,"rt"], bw, from = retrange[1]-3*bw, to = retrange[2]+3*bw)
maxden <- max(den$y)
deny <- den$y
gmat <- matrix(nrow = 5, ncol = 2+length(classnum))
snum <- 0
while (deny[maxy <- which.max(deny)] > maxden/20 && snum < max) {
grange <- descendMin(deny, maxy)
deny[grange[1]:grange[2]] <- 0
gidx <- which(speakmat[,"rt"] >= den$x[grange[1]] & speakmat[,"rt"] <= den$x[grange[2]])
gnum <- classlabel[unique(speakmat[gidx,"sample"])]
for (j in seq(along = gcount))
gcount[j] <- sum(gnum == j)
if (! any(gcount >= classnum*minfrac & gcount >= minsamp))
next
snum <- snum + 1
num <- num + 1
if (num > nrow(groupmat)) {
groupmat <- rbind(groupmat, matrix(nrow = nrow(groupmat), ncol = ncol(groupmat)))
groupindex <- c(groupindex, vector("list", length(groupindex)))
}
groupmat[num, 1] <- median(speakmat[gidx, "mz"])
groupmat[num, 2:3] <- range(speakmat[gidx, "mz"])
groupmat[num, 4] <- median(speakmat[gidx, "rt"])
groupmat[num, 5:6] <- range(speakmat[gidx, "rt"])
groupmat[num, 7] <- length(gidx)
groupmat[num, 7+seq(along = gcount)] <- gcount
groupindex[[num]] <- sort(porder[(startidx:endidx)[gidx]])
}
}
colnames(groupmat) <- c("mzmed", "mzmin", "mzmax", "rtmed", "rtmin", "rtmax",
"npeaks", classnames)
groupmat <- groupmat[seq(length = num),]
groupindex <- groupindex[seq(length = num)]
numsamp <- rowSums(groupmat[,(match("npeaks", colnames(groupmat))+1):ncol(groupmat),drop=FALSE])
uorder <- order(-numsamp, groupmat[,"npeaks"])
uindex <- rectUnique(groupmat[,c("mzmin","mzmax","rtmin","rtmax"),drop=FALSE],uorder)
peakSet$groups <- groupmat[uindex,];
peakSet$groupidx<- groupindex[uindex];
qs::qsave(peakSet, "peakSet.qs");
return(.set.mSet(mSetObj));
}
SetPeakList.GroupValues <- function(mSetObj=NA) {
mSetObj <- .get.mSet(mSetObj);
peakSet <- qs::qread("peakSet.qs");
msg <- mSetObj$msgSet$peakMsg;
peakmat <- peakSet$peaks;
groupmat <- peakSet$groups;
groupindex <- peakSet$groupidx;
sampnum <- seq(length = length(peakSet$sampnames))
intcol <- match("int", colnames(peakmat))
sampcol <- match("sample", colnames(peakmat))
values <- matrix(nrow = length(groupindex), ncol = length(sampnum))
for (i in seq(along = groupindex)) {
for(m in sampnum){
samp.inx<-which(peakmat[groupindex[[i]], sampcol]==m)
if(length(samp.inx)>0){
values[i, m] <- sum(peakmat[groupindex[[i]][samp.inx], intcol]);
}else{
values[i, m] <- NA;
}
}
}
msg<-c(msg, paste("A total of", length(groupindex), "peak groups were formed. "));
msg<-c(msg, paste("Peaks of the same group were summed if they are from one sample. "));
msg<-c(msg, paste("Peaks appearing in less than half of all samples in each group were ignored."));
colnames(values) <- peakSet$sampnames;
if(peakSet$ncol==2){
rownames(values) <- paste(round(groupmat[,paste("mz", "med", sep="")],5));
}else{
rownames(values) <- paste(round(groupmat[,paste("mz", "med", sep="")],5), "/", round(groupmat[,paste("rt", "med", sep="")],2), sep="");
mSetObj$dataSet$three.col <- TRUE;
}
qs::qsave(t(values), file="data_orig.qs");
mSetObj$msgSet$proc.msg <- msg
mSetObj$dataSet$orig.cls <- as.factor(peakSet$sampclass);
mSetObj$dataSet$type.cls.lbl <- class(peakSet$sampclass);
return(.set.mSet(mSetObj));
}
descendMin <- function(y, istart = which.max(y)) {
if (!is.double(y)) y <- as.double(y)
unlist(.C("DescendMin",
y,
length(y),
as.integer(istart-1),
ilower = integer(1),
iupper = integer(1))[4:5]) + 1
}
findEqualGreaterM <- function(x, values) {
if (!is.double(x)) x <- as.double(x)
if (!is.double(values)) values <- as.double(values)
.C("FindEqualGreaterM",
x,
length(x),
values,
length(values),
index = integer(length(values)))$index + 1
}
rectUnique <- function(m, order = seq(length = nrow(m)), xdiff = 0, ydiff = 0) {
nr <- nrow(m)
nc <- ncol(m)
if (!is.double(m))
m <- as.double(m)
.C("RectUnique",
m,
as.integer(order-1),
nr,
nc,
as.double(xdiff),
as.double(ydiff),
logical(nrow(m)))[[7]]
} |
library(devtools)
dev_mode(on = TRUE)
lapply(list("utils", "db", "settings", "visualization", "modules/priors", "modules/meta.analysis",
"modules/uncertainty", "modules/data.land", "modules/data.atmosphere", "modules/assim.batch",
"modules/assim.sequential", "models/ed", "models/sipnet", "models/biocro", "all"),
function(x) install(x, quick = TRUE, local = TRUE, quiet = TRUE)) |
getRiceParam <-
function(xy, level=0.95, doRob=FALSE, type=c("LiZhangDai", "MOM")) {
UseMethod("getRiceParam")
}
getRiceParam.data.frame <-
function(xy, level=0.95, doRob=FALSE, type=c("LiZhangDai", "MOM")) {
xy <- getXYmat(xy)
NextMethod("getRiceParam")
}
getRiceParam.default <-
function(xy, level=0.95, doRob=FALSE, type=c("LiZhangDai", "MOM")) {
xy <- as.matrix(xy)
p <- ncol(xy)
if(!is.numeric(xy)) { stop("xy must be numeric") }
if(!(p %in% (1:3))) { stop("x must be (n x 1/2/3)-matrix") }
type <- match.arg(type)
haveRob <- if(nrow(xy) < 4L) {
if(doRob) {
warning("We need >= 4 points for robust estimations")
}
FALSE
} else {
rob <- robustbase::covMcd(xy, cor=FALSE)
TRUE
}
ctr <- if(doRob && haveRob) {
rob[["center"]]
} else {
colMeans(xy)
}
sigmaHat <- getRayParam(xy=xy, level=level, doRob=doRob)[["sigma"]]
N <- nrow(xy)
bias <- (p/N)*sigmaHat["sigma"]^2
ce <- sum(ctr^2) - bias
nuSqHat <- if(type == "MOM") {
max(ce, 0)
} else if(type == "LiZhangDai") {
max(ce, (1/(bias+1)) * sum(ctr^2))
}
nuHat <- (1/c4(p*N+1))*sqrt(nuSqHat)
MSD <- getMSDfromRice(nu=nuHat, sigma=sigmaHat["sigma"])
return(list(nu=setNames(nuHat, NULL),
sigma=sigmaHat,
MR=setNames(MSD$mean, NULL),
RSD=setNames(MSD$sd, NULL)))
}
LaguerreHalf <-
function(x) {
a <- -x/2
bI0 <- exp(log(besselI(a, nu=0, expon.scaled=TRUE)) + a)
bI1 <- exp(log(besselI(a, nu=1, expon.scaled=TRUE)) + a)
exp(x/2) * ((1-x)*bI0 - x*bI1)
}
doubleFactorial <-
function(x, log=FALSE) {
y <- (x + 1)/2
lDF <- lgamma(2*y) - (lgamma(y) + (y-1) * log(2))
if(log) {
lDF
} else {
exp(lDF)
}
}
getMSDfromRice <-
function(nu, sigma) {
is.na(nu) <- (nu < 0) | !is.finite(nu)
is.na(sigma) <- (sigma <= 0) | !is.finite(sigma)
argL <- recycle(nu, sigma)
nu <- argL[[1]]
sigma <- argL[[2]]
L05 <- LaguerreHalf(-0.5 * nu^2 / sigma^2)
rMean <- sigma * sqrt(pi/2) * L05
rVar <- 2*sigma^2 + nu^2 - (pi * sigma^2 / 2) * L05^2
s2nr <- nu/sigma
idxS2NR52 <- s2nr > 52
rMean[idxS2NR52] <- nu[idxS2NR52] + sigma[idxS2NR52]^2/(2*nu[idxS2NR52])
rVar[idxS2NR52] <- sigma[idxS2NR52]^2 - sigma[idxS2NR52]^4/(2*nu[idxS2NR52]^2)
return(list(mean=rMean, sd=sqrt(rVar)))
}
dRice <-
function(x, nu, sigma) {
is.na(x) <- is.nan(x)
is.na(nu) <- (nu < 0) | !is.finite(nu)
is.na(sigma) <- (sigma <= 0) | !is.finite(sigma)
argL <- recycle(x, nu, sigma)
x <- argL[[1]]
nu <- argL[[2]]
sigma <- argL[[3]]
dens <- numeric(length(x))
keep <- which((x >= 0) | !is.finite(x))
if(length(keep) < 1L) { return(dens) }
lfac1 <- log(x[keep]) - 2*log(sigma[keep])
lfac2 <- -(x[keep]^2 + nu[keep]^2) / (2*sigma[keep]^2)
bArg <- abs(x[keep] * nu[keep] / sigma[keep]^2)
lfac3 <- log(besselI(bArg, nu=0, expon.scaled=TRUE)) + bArg
res <- exp(lfac1+lfac2+lfac3)
dens[keep] <- ifelse(is.nan(res), 0, res)
s2nr <- nu/sigma
rMSD <- getMSDfromRice(nu, sigma)
keepS2NR24 <- keep[keep %in% which(s2nr > 24)]
keepS2NR52 <- keep[keep %in% which(s2nr > 52)]
dens[keepS2NR24] <- dnorm(x[keepS2NR24], mean=rMSD$mean[keepS2NR24], sd=rMSD$sd[keepS2NR24])
dens[keepS2NR52] <- dnorm(x[keepS2NR52], mean=nu[keepS2NR52], sd=sigma[keepS2NR52])
return(dens)
}
pRice <-
function(q, nu, sigma, lower.tail=TRUE) {
is.na(nu) <- (nu < 0) | !is.finite(nu)
is.na(sigma) <- (sigma <= 0) | !is.finite(sigma)
argL <- recycle(q, nu, sigma)
q <- argL[[1]]
nu <- argL[[2]]
sigma <- argL[[3]]
pp <- numeric(length(q))
keep <- which((q >= 0) | !is.finite(q))
aQ <- nu/sigma
bQ <- q/sigma
pp[keep] <- marcumQ(aQ[keep], bQ[keep], nu=1, lower.tail=lower.tail)
if(lower.tail) {
pp[which(q == -Inf)] <- 0
pp[which(q == Inf)] <- 1
} else {
pp[which(q < 0)] <- 1
pp[which(q == Inf)] <- 0
}
s2nr <- nu/sigma
rMSD <- getMSDfromRice(nu, sigma)
keepS2NR24 <- keep[keep %in% which(s2nr > 24)]
keepS2NR52 <- keep[keep %in% which(s2nr > 52)]
pp[keepS2NR24] <- pnorm(q[keepS2NR24], mean=rMSD$mean[keepS2NR24],
sd=rMSD$sd[keepS2NR24], lower.tail=lower.tail)
pp[keepS2NR52] <- pnorm(q[keepS2NR52], mean=nu[keepS2NR52],
sd=sigma[keepS2NR52], lower.tail=lower.tail)
return(pp)
}
qRice <-
function(p, nu, sigma, lower.tail=TRUE) {
is.na(nu) <- (nu < 0) | !is.finite(nu)
is.na(sigma) <- (sigma <= 0) | !is.finite(sigma)
args <- recycle(p, nu, sigma)
p <- args[[1]]
nu <- args[[2]]
sigma <- args[[3]]
keep <- which((p >= 0) & (p < 1))
qq <- sqrt(qchisq(p, df=2, ncp=(nu/sigma)^2)) * sigma
s2nr <- nu/sigma
rMSD <- getMSDfromRice(nu, sigma)
keepS2NR24 <- keep[keep %in% which(s2nr > 24)]
keepS2NR52 <- keep[keep %in% which(s2nr > 52)]
qq[keepS2NR24] <- qnorm(p[keepS2NR24], mean=rMSD$mean[keepS2NR24],
sd=rMSD$sd[keepS2NR24], lower.tail=lower.tail)
qq[keepS2NR52] <- qnorm(p[keepS2NR52], mean=nu[keepS2NR52],
sd=sigma[keepS2NR52], lower.tail=lower.tail)
return(qq)
}
rRice <-
function(n, nu, sigma, method=c("eigen", "chol", "cdf")) {
is.na(nu) <- (nu < 0) | !is.finite(nu)
is.na(sigma) <- (sigma <= 0) | !is.finite(sigma)
method <- match.arg(method)
n <- if(length(n) > 1) { length(n) } else { n }
nu <- nu[1]
sigma <- sigma[1]
rn <- if(method == "eigen") {
X <- matrix(rnorm(n*2), nrow=n)
xy <- X %*% diag(rep(sigma, 2))
xyMove <- sweep(xy, 2, nu, FUN="+")
sqrt(rowSums(xyMove^2))
} else if(method == "chol") {
covMat <- diag(rep(sigma^2, 2))
CF <- chol(covMat, pivot=TRUE)
idx <- order(attr(CF, "pivot"))
CFord <- CF[, idx]
xy <- matrix(rnorm(n*2), nrow=n) %*% CFord
xyMove <- sweep(xy, 2, nu, FUN="+")
sqrt(rowSums(xyMove^2))
} else if(method == "cdf") {
u <- runif(n)
sqrt(qchisq(u, df=2, ncp=(nu/sigma)^2)) * sigma
}
return(rn)
} |
cut.pts <- function(cov, circ = TRUE, .n.reg) {
hobj <- graphics::hist(cov, breaks = "FD", plot = FALSE)
brks <- hobj$breaks
cnts <- hobj$counts
id.cand <- which(cnts == 0)
if (length(id.cand) > 0) {
loc.cut <- c()
if (circ & brks[1] <= 0 & brks[length(brks)] >= 360) {
if (length(id.cand) == 1)
loc.cut <- (brks[id.cand] + brks[id.cand + 1])/2
else {
id.diff <- diff(id.cand)
n.cons <- rle(id.diff)
vals <- n.cons$values
lens <- n.cons$lengths
if (any(vals == 1)) {
id.pos <- which(lens == max(lens[which(vals == 1)]))
if (id.pos == 1)
id.rng <- c(id.cand[1], id.cand[sum(lens[1:(id.pos)]) + 1])
else
id.rng <- id.cand[c(sum(lens[1:(id.pos - 1)]), sum(lens[1:(id.pos)])) + 1]
} else id.rng <- rep(id.cand[1], 2)
loc.cut <- (brks[id.rng[1]] + brks[(id.rng[2] + 1)])/2
}
cov[which(cov < loc.cut)] <- cov[which(cov < loc.cut)] + 360
}
gmm <- mixtools::normalmixEM(cov, k = .n.reg, verb = FALSE)
if(length(which(gmm$posterior[, 1] > gmm$posterior[, 2])) > 0 & length(which(gmm$posterior[, 1] < gmm$posterior[, 2])) > 0) {
if (gmm$mu[1] < gmm$mu[2])
id.clust <- which(gmm$posterior[, 1] > gmm$posterior[, 2])
else
id.clust <- which(gmm$posterior[, 1] < gmm$posterior[, 2])
bnd1 <- max(cov[id.clust])
bnd2 <- min(cov[-id.clust])
loc.cut <- c(loc.cut, ((bnd1 + bnd2)/2))
}
if (circ & any(loc.cut > 360))
loc.cut[which(loc.cut > 360)] <- loc.cut[which(loc.cut > 360)] - 360
loc.cut <- sort(loc.cut)
loc.cut <- c(brks[1], loc.cut, brks[length(brks)])
return(loc.cut)
} else {
return(NA)
}
} |
expected <- eval(parse(text="TRUE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE), .Names = c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\")))"));
do.call(`is.atomic`, argv);
}, o=expected); |
quadvaraux <- function(Z){
if ((is.numeric(Z)==FALSE)||(is.matrix(Z)==FALSE)){
stop("Message from quadvaraux.R: Z is not of valid type")}
Nl <- dim(Z)[1]
Ml <- Nl-1
Nc <- dim(Z)[2]
Mc <- Nc-1
V2 <- rep(0,2)
for (m in 1:2){
K <- floor(Ml/2^(m-1))
i2 <- 1:Nc
j1 <- seq(from=(2*2^(m-1)+1), to=(2^(m-1)*K+1), by=2^(m-1))
j2 <- seq(from=(2^(m-1)+1), to=(2^(m-1)*(K-1)+1), by=2^(m-1))
j3 <- seq(from=1, to=(2^(m-1)*(K-2)+1), by=2^(m-1))
Delta21 <- Z[j1,i2]-2*Z[j2,i2]+Z[j3,i2]
j4 <- 1:(K-1)
K <- floor(Mc/2^(m-1))
j1 <- seq(from=(2*2^(m-1)+1), to=(2^(m-1)*K+1), by=2^(m-1))
j2 <- seq(from=(2^(m-1)+1), to=(2^(m-1)*(K-1)+1), by=2^(m-1))
j3 <- seq(from=1, to=(2^(m-1)*(K-2)+1), by=2^(m-1))
Delta2 <- Delta21[j4,j1]- 2*Delta21[j4,j2]+Delta21[j4,j3]
V2[m] <- sum(sum((Delta2)^2))
}
H <- log(V2[2]/V2[1])/(2*log(2))+1
return(H)} |
library(twitteR)
hilton.tweets=searchTwitter('@hilton',n=1500)
hilton.tweets=searchTwitter('@narendramodi',n=15)
hilton.tweets
length(hilton.tweets)
class(hilton.tweets)
tweet=hilton.tweets[[1]]
class(tweet)
tweet$getScreenName()
tweet$getText()
library("plyr")
hilton.text=laply(hilton.tweets,function(t)t$getText())
length(hilton.text)
head(hilton.text,5)
hu.liu.pos=scan('/Users/marcinkulakowski/Downloads/r/positive-words.txt',what='character',comment.char=';')
hu.liu.neg=scan('/Users/marcinkulakowski/Downloads/r/negative-words.txt',what='character',comment.char=';')
pos.words=c(hu.liu.pos,'upgrade')
neg.words=c(hu.liu.neg,'wtf','wait','waiting','epicfail','mechanical')
sample=c("You'reawesomeandIloveyou","Ihateandhateandhate.Soangry.Die!","Impressedandamazed:youarepeerlessinyourachievementofunparalleledmediocrity.")
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
require(plyr)
require(stringr)
scores = laply(sentences, function(sentence, pos.words, neg.words) {
sentence = gsub('[[:punct:]]', '', sentence)
sentence = gsub('[[:cntrl:]]', '', sentence)
sentence = gsub('\\d+', '', sentence)
sentence = tolower(sentence)
word.list = str_split(sentence, '\\s+')
words = unlist(word.list)
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
score = sum(pos.matches) - sum(neg.matches)
return(score)
}, pos.words, neg.words, .progress=.progress )
scores.df = data.frame(score=scores, text=sentences)
return(scores.df)
}
> result=score.sentiment(sample,pos.words,neg.words)
> class(result)
[1] "data.frame"
> result$score
[1] 0 0 0
> hilton.scores=score.sentiment(hilton.text,pos.words,neg.words,.progress='text')
> hilton.scores$hotel='Hilton'
> hilton.scores$code='HL'
> hist(hilton.scores$score)
> library("ggplot2")
> qplot(hilton.scores$score)
intercontinental.tweets=searchTwitter('@intercontinental',n=1500)
class(tweet)
intercontinental.text=laply(intercontinental.tweets,function(t)t$getText())
intercontinental.scores=score.sentiment(intercontinental.text,pos.words,neg.words,.progress='text')
intercontinental.scores$hotel='Intercontinental'
intercontinental.scores$code='IC'
wyndham.tweets=searchTwitter('@wyndham',n=1500)
class(tweet)
wyndham.text=laply(wyndham.tweets,function(t)t$getText())
wyndham.scores=score.sentiment(wyndham.text,pos.words,neg.words,.progress='text')
wyndham.scores$hotel='Wyndham'
wyndham.scores$code='WY'
marriott.tweets=searchTwitter('@marriott',n=1500)
class(tweet)
marriott.text=laply(marriott.tweets,function(t)t$getText())
marriott.scores=score.sentiment(marriott.text,pos.words,neg.words,.progress='text')
marriott.scores$hotel='Marriott'
marriott.scores$code='MI'
bestwestern.tweets=searchTwitter('@bestwestern',n=1500)
class(tweet)
bestwestern.text=laply(bestwestern.tweets,function(t)t$getText())
bestwestern.scores=score.sentiment(bestwestern.text,pos.words,neg.words,.progress='text')
bestwestern.scores$hotel='Bestwestern'
bestwestern.scores$code='BW'
starwood.tweets=searchTwitter('@starwood',n=1500)
class(tweet)
starwood.text=laply(starwood.tweets,function(t)t$getText())
starwood.scores=score.sentiment(starwood.text,pos.words,neg.words,.progress='text')
starwood.scores$hotel='Starwood'
starwood.scores$code='SW'
hyatt.tweets=searchTwitter('@hyatt',n=1500)
class(tweet)
hyatt.text=laply(hyatt.tweets,function(t)t$getText())
hyatt.scores=score.sentiment(hyatt.text,pos.words,neg.words,.progress='text')
hyatt.scores$hotel='Hyatt'
hyatt.scores$code='HY'
> all.scores=rbind(intercontinental.scores,wyndham.scores,hilton.scores,marriott.scores,bestwestern.scores,starwood.scores,hyatt.scores)
> ggplot(data=all.scores)+
geom_bar(mapping=aes(x=score,fill=hotel),binwidth=1)+
facet_grid(hotel~.)+
theme_bw()+scale_fill_brewer()
> all.scores$very.pos=as.numeric(all.scores$score>=2)
> all.scores$very.neg=as.numeric(all.scores$score twitter.df=ddply(all.scores,c('hotel','code'),summarise,pos.count=sum(very.pos),neg.count=sum(very.neg))
> twitter.df$all.count=twitter.df$pos.count+twitter.df$neg.count
> twitter.df$score=round(100*twitter.df$pos.count/twitter.df$all.count)
> install.packages("doBy")
> library("doBy")
> orderBy(~-score,twitter.df)
hotel code pos.count neg.count all.count score
1 Bestwestern BW 6 0 6 100
5 Starwood SW 7 0 7 100
6 Wyndham WY 2 0 2 100
3 Hyatt HY 7 1 8 88
2 Hilton HL 15 3 18 83
4 Marriott MI 13 4 17 76
> install.packages("XML")
> library(XML)
> acsi.url='http://www.theacsi.org/index.php?option=com_content&view=article&id=147&catid=&Itemid=212&i=Hotels'
> acsi.df=readHTMLTable(acsi.url,header=T,which=1,stringsAsFactors=F)
> acsi.df=acsi.df[,c(1,18)]
> head(acsi.df,1)
> colnames(acsi.df)=c('hotel','score')
> acsi.df$score=as.numeric(acsi.df$score)
> View(acsi.df) |
"Earthquakes" |
PST.setlayout <- function(nplot, prows, pcols, withlegend, axes,
legend.prop=NA) {
if (withlegend==TRUE) withlegend <- "auto"
if (is.na(pcols)) pcols <- min(nplot,2)
if (is.na(prows)) prows <- ceiling(nplot/pcols)
pheight <- 1
pwidth <- 1
widths <- rep(pwidth/pcols,pcols)
heights <- rep(pheight/prows,prows)
layrow <- prows
laycol <- pcols
laymat <- matrix(1:(layrow*laycol), nrow=layrow, ncol=laycol, byrow=TRUE)
axisp <- 0
legpos=NULL
freecells <- (prows*pcols)-nplot
if (withlegend=="auto") {
if (freecells==0) {
if (is.na(legend.prop)) legend.prop <- 0.15
layrow <- layrow+1
pheight <- pheight-legend.prop
heights <- rep(pheight/prows,prows)
heights <- c(heights,legend.prop)
widths <- rep(pwidth/laycol,laycol)
legpos="bottom"
laymat <- rbind(laymat, rep(nplot+1,ncol(laymat)))
}
else {
legpos="center"
heights <- rep(pheight/prows,prows)
widths <- rep(pwidth/laycol,laycol)
}
}
else if (withlegend=="right") {
if (is.na(legend.prop)) legend.prop <- 0.25
laycol <- laycol+1
pwidth <- pwidth-legend.prop
legpos="center"
widths <- rep(pwidth/pcols,pcols)
widths <- c(widths, legend.prop)
heights <- rep(pheight/prows,prows)
laymat <- cbind(laymat, rep(nplot+1,nrow(laymat)))
}
if (axes=="bottom") {
for (nc in 1:ncol(laymat))
axisp <- c(axisp, max(laymat[laymat[,nc]<=nplot,nc]))
}
else if (axes=="all") axisp <- 1:nplot
laylist <- list(laymat=laymat, widths=widths, heights=heights, axisp=axisp, legpos=legpos)
return(laylist)
} |
cat("\014")
rm(list = ls())
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
library(scales)
library(readxl)
library(lubridate)
library(ggrepel)
library(gganimate)
library(tidylog)
library(tidyverse)
folder_name <- "0160_bottom_length"
out_path <- paste0(exportdir, folder_name)
dir.create(file.path(paste0(out_path)), showWarnings = FALSE)
raw <- read.csv(paste0(importdir, "0160_dow_bottom_length/ycharts_dji_data.csv"), skip = 1,
col.names = c("date","index_dow")) %>%
mutate(date = as.Date(substr(date, 1, 10), format = "%Y-%m-%d")) %>%
select(date, index_dow) %>%
arrange(date) %>%
filter(date <= "2020-12-31")
first_year <- min(year(raw$date))
df <- raw %>%
arrange(desc(date))
absolute_minumum <- 10^8
for(i in 1:nrow(df)){
current_p <- df[i, "index_dow"]
if (current_p < absolute_minumum){
df[i, "low_watermark"] <- current_p
absolute_minumum <- current_p
} else{
df[i, "low_watermark"] <- absolute_minumum
}
}
df <- df %>%
arrange(date)
daily_cash <- 1
for(i in 1:nrow(df)){
if(i == 1){
df[i, "value_dca"] <- daily_cash
df[i, "value_ab_cash"] <- daily_cash
df[i, "value_ab_vest"] <- 0
df[i, "avg_dca"] <- NA
df[i, "avg_ab"] <- NA
} else{
ret <- df[i, "index_dow"]/df[(i-1), "index_dow"]
df[i, "avg_dca"] <- mean(df[1:i, "index_dow"], na.rm = TRUE)
df[i, "avg_ab"] <- mean(df[1:i, "low_watermark"], na.rm = TRUE)
df[i, "value_dca"] <- (df[(i-1), "value_dca"] + daily_cash) * ret
if(df[(i-1), "index_dow"] > df[(i-1), "low_watermark"]){
df[i, "value_ab_cash"] <- df[(i-1), "value_ab_cash"] + daily_cash
df[i, "value_ab_vest"] <- df[(i-1), "value_ab_vest"] * ret
} else{
df[i, "ab_purchase"] <- 1
df[i, "value_ab_vest"] <- (df[(i-1), "value_ab_vest"] + df[(i-1), "value_ab_cash"] + daily_cash) * ret
df[i, "value_ab_cash"] <- 0
}
}
df[i, "value_ab"] <- df[i, "value_ab_cash"] + df[i, "value_ab_vest"]
df[i, "pct_ab_over_dca"] <- df[i, "value_ab"]/df[i, "value_dca"]
}
summary <- df %>%
arrange(date) %>%
mutate(lower_future = ifelse(low_watermark < index_dow, 1, 0),
lag_days_to_bottom = lag(value_ab_cash))
bottoms <- summary %>%
filter(value_ab_cash == 0)
n_bottoms <- nrow(bottoms)
to_plot <- df %>%
select(date, index_dow, low_watermark) %>%
gather(-date, key=key, value=value)
file_path <- paste0(out_path, "/dow_lower_watermark_ycharts.jpeg")
source_string <- "Source: YCharts, 1970-2019 (OfDollarsAndData.com)"
plot <- ggplot(to_plot, aes(x=date, y=value, col = key)) +
geom_line() +
scale_y_continuous(label = comma, trans = log10_trans()) +
scale_color_manual(guide = FALSE, values = c("black", "red")) +
of_dollars_and_data_theme +
ggtitle(paste0("Dow Index and Low Watermark")) +
labs(x="Date", y="Index Value",
caption = paste0(source_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
to_plot <- df %>%
select(date, index_dow, low_watermark) %>%
gather(-date, key=key, value=value)
file_path <- paste0(out_path, "/dow_lower_watermark_buys_ycharts.jpeg")
source_string <- "Source: YCharts, 1970-2019 (OfDollarsAndData.com)"
plot <- ggplot(to_plot, aes(x=date, y=value, col = key)) +
geom_line() +
geom_point(data = select(bottoms, date, low_watermark), aes(x=date, y=low_watermark), col = "blue", size = 1) +
scale_y_continuous(label = comma, trans = log10_trans()) +
scale_color_manual(guide = FALSE, values = c("black", "red")) +
of_dollars_and_data_theme +
ggtitle(paste0("Dow Index and Low Watermark")) +
labs(x="Date", y="Index Value",
caption = paste0(source_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
to_plot <- df %>%
select(date, value_dca, value_ab) %>%
rename(`DCA` = value_dca,
`Absolute-Bottom` = value_ab) %>%
gather(-date, key=key, value=value)
final_diff <- df[nrow(df), "value_ab"] - df[nrow(df), "value_dca"]
final_diff_pct <- df[nrow(df), "value_ab"]/df[nrow(df), "value_dca"] - 1
text_labels <- data.frame(date = c(as.Date("2014-07-01"), as.Date("2014-07-01")),
value = c(df[nrow(df), "value_ab"] + 2000, 60000),
key = c("Absolute-Bottom", "DCA"),
label = c(paste0("Absolute Bottom\n+$", formatC(final_diff, digits = 0, format = "f", big.mark = ","),
"\n(+",
round(100*final_diff_pct, 1), "%)"),
"DCA")
)
file_path <- paste0(out_path, "/dow_dca_vs_ab_ycharts.jpeg")
source_string <- "Source: YCharts, 1970-2019 (OfDollarsAndData.com)"
plot <- ggplot(to_plot, aes(x=date, y=value, col = key)) +
geom_line() +
geom_text_repel(data = text_labels,
aes(x = date,
y = value,
col = key,
label = text_labels$label,
family = "my_font"),
size = 3,
segment.colour = "transparent",
max.iter = 1
) +
scale_y_continuous(label = dollar) +
scale_color_manual(values = c("red", "blue"), guide = FALSE) +
of_dollars_and_data_theme +
ggtitle(paste0("DCA vs. Absolute-Bottom Buying Strategy")) +
labs(x="Date", y="Portfolio Value",
caption = paste0(source_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
to_plot <- df %>%
select(date, avg_dca, avg_ab) %>%
rename(DCA = avg_dca,
`Absolute-Bottom` = avg_ab) %>%
gather(-date, key=key, value=value)
file_path <- paste0(out_path, "/avg_price_dca_vs_ab_ycharts.jpeg")
source_string <- "Source: YCharts, 1970-2019 (OfDollarsAndData.com)"
plot <- ggplot(to_plot, aes(x=date, y=value, col = key)) +
geom_line() +
scale_y_continuous(label = comma, trans = log10_trans()) +
scale_color_manual(values = c("red", "blue")) +
of_dollars_and_data_theme +
theme(legend.position = "bottom",
legend.title = element_blank()) +
ggtitle(paste0("Average Purchase Prices\nDCA vs. Absolute-Bottom Buying Strategy")) +
labs(x="Date", y="Average Index Value",
caption = paste0(source_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
print(paste0(round(100*mean(summary$lower_future), 1), "% of days will see a lower value in the future."))
print(paste0("There are only ",
n_bottoms,
" absolute bottoms (",
round(100*(n_bottoms/nrow(summary)), 1),
"% of all days) since ",
first_year, "."))
print(paste0("The average number of days before a bottom is ", mean(df$value_ab_cash), "."))
print(paste0("The median number of days before a bottom is ", quantile(df$value_ab_cash, probs = 0.5), ".")) |
source("incl/start.R")
getOption2 <- parallelly:::getOption2
getEnvVar2 <- parallelly:::getEnvVar2
options(parallelly.some.option = NULL)
options(parallelly.some.option = NULL)
Sys.unsetenv("R_FUTURE_SOME_ENVVAR")
Sys.unsetenv("R_PARALLELLY_SOME_ENVVAR")
message("*** Options and environment variables ...")
showall <- function() {
utils::str(list(
future.some.setting = getOption("future.some.setting", NULL),
parallelly.some.setting = getOption("parallelly.some.setting", NULL),
R_FUTURE_SOME_SETTING = Sys.getenv("R_FUTURE_SOME_SETTING", ""),
R_PARALLELLY_SOME_SETTING = Sys.getenv("R_PARALLELLY_SOME_SETTING", "")
))
}
for (what in c("option", "envvar")) {
if (what == "option") {
setvalue <- function(name, value) {
name <- sprintf("%s.some.setting", tolower(name))
if (is.null(value)) {
args <- list(NULL)
} else {
args <- as.list(value)
}
names(args) <- name
do.call(options, args = args)
class(args) <- "option"
args
}
} else if (what == "envvar") {
setvalue <- function(name, value) {
name <- sprintf("R_%s_SOME_SETTING", toupper(name))
if (is.null(value)) {
Sys.unsetenv(name)
args <- list(NULL)
names(args) <- name
} else {
args <- as.list(value)
names(args) <- name
do.call(Sys.setenv, args = args)
}
class(args) <- "envvar"
args
}
}
for (name in c("future", "parallelly")) {
for (value0 in list(NULL, TRUE)) {
args <- setvalue(name, value0)
stopifnot(inherits(args, what))
showall()
if (is.null(value0)) {
message("- getOption2()")
value <- getOption2("future.some.setting", NA)
stopifnot(is.na(value))
value <- getOption2("parallelly.some.setting", NA)
stopifnot(is.na(value))
message("- getEnvVar2()")
value <- getEnvVar2("R_FUTURE_SOME_ENVVAR", NA)
stopifnot(is.na(value))
value <- getEnvVar2("R_PARALLELLY_SOME_ENVVAR", NA)
stopifnot(is.na(value))
} else if (isTRUE(value0)) {
if (what == "option") {
message("- getOption2()")
value1 <- getOption2("future.some.setting", NA)
stopifnot(isTRUE(value1))
value2 <- getOption2("parallelly.some.setting", NA)
stopifnot(isTRUE(value2))
} else if (what == "envvar") {
message("- getEnvVar2()")
value1 <- getEnvVar2("R_FUTURE_SOME_SETTING", NA)
stopifnot(value1 == "TRUE")
value2 <- getEnvVar2("R_PARALLELLY_SOME_SETTING", NA)
stopifnot(value2 == "TRUE")
}
stopifnot(identical(value1, value2))
}
args <- setvalue(name, NULL)
stopifnot(inherits(args, what), is.null(args[[1]]))
}
}
}
message("*** Options and environment variables ... DONE")
source("incl/end.R") |
ring_matrix <- function(nr_max, nc, type, environment = TRUE) {
type <- match.arg(type, names(ring:::sizes))
if (environment) {
buf <- ring::ring_buffer_env(nr_max)
} else {
buf <- ring::ring_buffer_bytes_typed(nr_max, type, nc)
}
ret <- list(buf = buf, nr_max = as.integer(nr_max), nc = as.integer(nc),
type = type, environment = environment)
class(ret) <- "ring_matrix"
ret
}
ring_matrix_push <- function(buffer, data, check = TRUE, ...) {
if (check) {
ring_matrix_compatible(buffer, data)
}
if (buffer$environment) {
if (is.matrix(data)) {
for (i in seq_len(nrow(data))) {
buffer$buf$push(data[i, ], FALSE)
}
} else {
buffer$buf$push(data, FALSE)
}
} else {
buffer$buf$push(if (is.matrix(data)) t(data) else data)
}
}
ring_matrix_compatible <- function(x, data) {
if (storage.mode(data) != x$type) {
stop("Expected storage.mode of ", x$type)
}
if (is.matrix(data)) {
if (ncol(data) != x$nc) {
stop(sprintf("Expected a matrix of '%d' columns", x$nc))
}
} else {
if (length(data) != x$nc) {
stop(sprintf("Expected a matrix of '%d' columns", x$nc))
}
}
TRUE
}
ring_matrix_get <- function(x, i = NULL) {
if (is.null(i)) {
dat <- x$buf$read(x$buf$used())
if (x$environment) {
if (length(dat) == 0L) {
dat <- create[[x$type]]()
} else {
dat <- unlist(dat)
}
}
ret <- matrix(dat, ncol = x$nc, byrow = TRUE)
} else {
len <- x$buf$used()
i <- ring_vector_index(i, len)
ret <- matrix(create[[x$type]](length(i) * x$nc), length(i), x$nc)
for (j in seq_along(i)) {
k <- i[[j]]
ret[j, ] <- if (k <= len) x$buf$tail_offset(k - 1L) else NA
}
}
if (!is.null(x$colnames)) {
colnames(ret) <- x$colnames
}
ret
}
push.ring_matrix <- ring_matrix_push
dim.ring_matrix <- function(x, ...) {
c(x$buf$used(), x$nc)
}
head.ring_matrix <- function(x, n = 6L, ...) {
head.matrix(x, n, ...)
}
tail.ring_matrix <- function(x, n = 6L, ...) {
tail.matrix(x, n, FALSE, ...)
}
`[.ring_matrix` <- function(x, i, j, ..., drop = TRUE) {
if (missing(i)) {
if (missing(j)) {
ring_matrix_get(x, NULL)
} else {
ring_matrix_get(x, NULL)[, j, drop = drop]
}
} else if (is.matrix(i)) {
if (!missing(j)) {
stop("subscript out of bounds")
}
j <- sort(unique(i[, 1L]))
ring_matrix_get(x, j)[cbind(match(i[, 1L], j), i[, 2L])]
} else {
ring_matrix_get(x, i)[, j, drop = drop]
}
}
dimnames.ring_matrix <- function(x, ...) {
if (is.null(x$colnames)) {
NULL
} else {
list(NULL, x$colnames)
}
}
`dimnames<-.ring_matrix` <- function(x, value) {
if (is.null(value)) {
x$colnames <- NULL
} else if (!is.list(value) || length(value) != 2L) {
stop("Invalid input for dimnames")
} else {
if (!is.null(value[[1L]])) {
stop("Cannot set rownames of a ring matrix")
}
val <- value[[2L]]
if (!is.null(val) && length(val) != x$nc) {
stop("Invalid length dimnames")
}
x$colnames <- val
}
x
}
as.matrix.ring_matrix <- function(x, ...) {
ring_matrix_get(x, NULL)
}
cbind.ring_matrix <- function(...) {
stop("It is not possible to cbind() ring_matrices (use as.matrix first?)")
}
rbind.ring_matrix <- function(...) {
if (!inherits(..1, "ring_matrix")) {
args <- list(...)
i <- vapply(args, inherits, logical(1), "ring_matrix")
args[i] <- lapply(args[i], as.matrix)
eval(as.call(c(quote(rbind), args)))
} else {
x <- ..1
args <- list(...)[-1]
lapply(args, ring_matrix_compatible, x = x)
for (m in args) {
ring_matrix_push(x, m)
}
x
}
}
length.ring_matrix <- function(x) {
x$buf$used() * x$nc
}
registerS3method("[", "ring_matrix", `[.ring_matrix`, environment())
registerS3method("dim", "ring_matrix", dim.ring_matrix, environment())
registerS3method("dimnames", "ring_matrix", dimnames.ring_matrix, environment())
registerS3method("dimnames<-", "ring_matrix", `dimnames<-.ring_matrix`,
environment())
registerS3method("as.matrix", "ring_matrix", cbind.ring_matrix, environment())
registerS3method("cbind", "ring_matrix", cbind.ring_matrix, environment())
registerS3method("rbind", "ring_matrix", rbind.ring_matrix, environment()) |
?outer
outer(1:4, 4:6)
1:4 %o% 4:6
outer(1:4, 4:6, FUN=paste)
x=1:4 ; y=4:6 ; z=c(10,11,12)
x;y;z
outer(x,y, FUN='*')
outer(x,y, FUN=paste)
outer(x,y, FUN='+')
outer(x,y, FUN='-')
x;y
outer(x,-y, FUN=paste)
outer(x,y, FUN='-')
outer(x,y, FUN='^')
outer(x,rep('^',3),y, FUN=paste0)
outer(x,y, FUN='/')
z = |
context("unnest_sentences_")
test_that("correct ouput class and str", {
df <- data.frame(doc_id = 1:3,
text = c("Testing the system. Second sentence for you.",
"System testing the tidy documents df.",
"Documents will be parsed and lexranked."),
stringsAsFactors = FALSE)
test_result <- unnest_sentences_(df, "out", "text")
expect_equal(dim(test_result), c(4,3))
expect_true(is.data.frame(test_result))
expect_equal(names(test_result), c("doc_id","sent_id","out"))
test_result <- unnest_sentences_(df, "out", "text", drop=FALSE)
expect_equal(dim(test_result), c(4,4))
expect_equal(names(test_result), c("doc_id","text","sent_id","out"))
})
test_that("test input checking", {
df <- data.frame(doc_id = 1:3,
text = c("Testing the system. Second sentence for you.",
"System testing the tidy documents df.",
"Documents will be parsed and lexranked."),
stringsAsFactors = FALSE)
expect_error(unnest_sentences_(df, "out", "fake"))
expect_error(unnest_sentences_(NULL, "out", "text"))
expect_error(unnest_sentences_(df, "out", "text", drop = NULL))
expect_error(unnest_sentences(df, "out", "text", doc_id = "fake"))
expect_warning(unnest_sentences_(df, "out", "text", output_id=c("test","test2")))
})
test_that("output value", {
df <- data.frame(doc_id = 1:3,
text = c("Testing the system. Second sentence for you.",
"System testing the tidy documents df.",
"Documents will be parsed and lexranked."),
stringsAsFactors = FALSE)
test_result <- unnest_sentences_(df, "out", "text")
expected_result <- data.frame(doc_id = c(1L, 1L, 2L, 3L),
sent_id = c(1L, 2L, 1L, 1L),
out = c("Testing the system.",
"Second sentence for you.",
"System testing the tidy documents df.",
"Documents will be parsed and lexranked."),
stringsAsFactors = FALSE)
expect_equal(test_result, expected_result)
df <- data.frame(doc_id = c(1,1,3),
text = c("Testing the system. Second sentence for you.",
"System testing the tidy documents df.",
"Documents will be parsed and lexranked."),
stringsAsFactors = FALSE)
test_result <- unnest_sentences_(df, "out", "text", doc_id = "doc_id")
expected_result <- data.frame(doc_id = c(1L, 1L, 1L, 3L),
sent_id = c(1L, 2L, 3L, 1L),
out = c("Testing the system.",
"Second sentence for you.",
"System testing the tidy documents df.",
"Documents will be parsed and lexranked."),
stringsAsFactors = FALSE)
expect_equal(test_result, expected_result)
}) |
simulate.transectHolder <- function(object, nsim = 1, seed = NULL, ...) {
if (!is.null(seed)) set.seed(seed)
distances <- c()
while(length(distances) < nsim) {
unfiltered <- do.call(object$rng,
as.list(c(10*nsim, object$parameters)))
filter <- runif(10*nsim, 0, max(unfiltered))
distances <- c(distances, unfiltered[unfiltered > filter])
}
distances <- distances[1:nsim]
angles <- runif(nsim, 0, 2*pi)
return(data.frame(distances = distances,
angles = angles,
x = cos(angles) * distances,
y = sin(angles) * distances))
} |
ParseTotalEffects <-
function(OutFile,FileName,Directry){
z1=which(match(OutFile,"Total")==1)[seq(1,length(which(match(OutFile,"Total")==1)),2)]
z=(mapply(seq,z1-5,z1+10))
AllNameTotTotIndList=OutFile[z[1:nrow(z),]]
P1=seq(10,length(AllNameTotTotIndList),16)
PT=as.numeric(AllNameTotTotIndList[P1])
Summs<-CreateSummaryMats(FileName=FileName,OutputSE=FALSE,OutputPVal=TRUE,Directry=Directry,OutputFinalMat=FALSE)
o=c()
for(i in 1:length(Summs[[1]])){
o=c(o,rep(Summs[[1]][i],length(Summs[[2]][[i]])))
}
M=matrix(c(o,unlist(Summs[[2]])),nrow=length(o))
Mn=cbind(M[,2],rep("to",length(M[,2])),M[,1])
Mn<-Mn
P2=Mn
PD=unlist(Summs[[3]])
I1=seq(3,length(AllNameTotTotIndList),16)
I2=rep(0,length(I1)*3)
I2[which(mod(seq(1,length(I2)),3)==0)-0]=I1+2
I2[which(mod(seq(1,length(I2)),3)==0)-1]=I1+1
I2[which(mod(seq(1,length(I2)),3)==0)-2]=I1
INDNameMat=matrix(AllNameTotTotIndList[I2],byrow=TRUE,ncol=3)
PI1=seq(16,length(AllNameTotTotIndList),16)
PTI=as.numeric(AllNameTotTotIndList[PI1])
EntireF=c("TotalPVals"=list(PT),"INDPVals"=list(PTI),"INDNames"=list(INDNameMat),"DirectPVals"=list(PD),"DirectNames"=list(P2))
return(EntireF)} |
test_that("fredr() aliases fredr_series_observations()", {
skip_if_no_key()
expect_identical(
fredr(series_id = "GNPCA", limit = 2),
fredr_series_observations(series_id = "GNPCA", limit = 2)
)
})
test_that("fredr_series_observations() works", {
skip_if_no_key()
series <- fredr_series_observations(series_id = "GNPCA", limit = 20L)
expect_s3_class(series, c("tbl_df", "tbl", "data.frame"))
expect_s3_class(series$date, "Date")
expect_type(series$series_id, "character")
expect_type(series$value, "double")
expect_s3_class(series$realtime_start, "Date")
expect_s3_class(series$realtime_end, "Date")
expect_true(ncol(series) == 5)
expect_true(nrow(series) == 20)
})
test_that("fredr_series_observations() properly returns zero row tibble", {
skip_if_no_key()
series <- fredr::fredr_series_observations(
series_id = "GNPCA",
observation_start = as.Date("2050-01-01")
)
expect_s3_class(series, c("tbl_df", "tbl", "data.frame"))
expect_s3_class(series$date, "Date")
expect_type(series$series_id, "character")
expect_type(series$value, "double")
expect_s3_class(series$realtime_start, "Date")
expect_s3_class(series$realtime_end, "Date")
expect_true(ncol(series) == 5)
expect_true(nrow(series) == 0)
})
test_that("fredr_series_observations() throws errors for bad parameters", {
expect_error(fredr_series_observations())
expect_error(fredr_series_observations(foo = "bar"))
expect_error(fredr_series_observations(series_id = 1))
expect_error(fredr_series_observations(series_id = c("a", "b")))
})
test_that("vintage_dates parameter accepts a vector of dates", {
skip_if_no_key()
vintage_dates <- as.Date(c("2001-07-25", "2001-07-28"))
result <- fredr_series_observations(
series_id = "GDPC1",
observation_start = as.Date("2000-01-01"),
observation_end = as.Date("2000-01-01"),
vintage_dates = vintage_dates
)
expect_realtime_start <- as.Date(c("2001-07-25", "2001-07-27"))
expect_realtime_end <- as.Date(c("2001-07-26", "2001-07-28"))
expect_identical(nrow(result), 2L)
expect_identical(result$realtime_start, expect_realtime_start)
expect_identical(result$realtime_end, expect_realtime_end)
})
test_that("validate_series_id() throws proper errors", {
expect_error(validate_series_id(NULL))
expect_error(validate_series_id(1))
expect_error(validate_series_id(c("a", "b")))
}) |
library("GeneNet")
data("arth800")
summary(arth800.expr)
plot(arth800.expr, 1:9)
panel.cor = function(x, y, digits=2, prefix="", cex.cor)
{
usr = par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r = abs(cor(x, y))
txt = format(c(r, 0.123456789), digits=digits)[1]
txt = paste(prefix, txt, sep="")
if(missing(cex.cor)) cex = 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex * r)
}
pairs(arth800.expr[,1:9], lower.panel=panel.smooth, upper.panel=panel.cor)
pcor.dyn = ggm.estimate.pcor(arth800.expr, method = "dynamic")
arth.edges = network.test.edges(pcor.dyn,direct=TRUE)
dim(arth.edges)
arth.net = extract.network(arth.edges, method.ggm="number", cutoff.ggm=150)
library("graph")
node.labels = as.character(1:ncol(arth800.expr))
gr = network.make.graph( arth.net, node.labels, drop.singles=TRUE)
num.nodes(gr)
edge.info(gr)$weight
table( edge.info(gr)$dir )
sort(node.degree(gr), decreasing=TRUE)[1:10]
arth800.descr[570]
arth800.descr[81]
arth800.descr[558]
arth800.descr[539]
arth800.descr[783]
library("Rgraphviz")
globalAttrs = list()
globalAttrs$edge = list(color = "black", lty = "solid", lwd = 1, arrowsize=1)
globalAttrs$node = list(fillcolor = gray(.95), shape = "ellipse", fixedsize = FALSE)
nodeAttrs = list()
nodeAttrs$fillcolor = c('570' = "red", "81" = "red")
edi = edge.info(gr)
edgeAttrs = list()
edgeAttrs$dir = edi$dir
cutoff = quantile(abs(edi$weight), c(0.2, 0.8))
edgeAttrs$lty = ifelse(edi$weight < 0, "dotted", "solid")
edgeAttrs$color = ifelse( abs(edi$weight <= cutoff[1]), "grey", "black")
edgeAttrs$lwd = ifelse(abs(edi$weight >= cutoff[2]), 2, 1)
plot(gr, attrs = globalAttrs, nodeAttrs = nodeAttrs, edgeAttrs = edgeAttrs, "fdp") |
con2.vals <-
function(x, y, n, j, k)
{
a <- con2.parms(x, y, n, j, k, 1, 1)
nr <- nrow(a$theta)
est <- a$theta[nr, ]
b <- con2.est(x[j], x[k], est)
eta <- c(b$eta1, b$eta2)
beta <- c(b$a0, b$a1, b$b0, b$b1, b$b2, b$c0, b$c1)
tau <- c(x[j], x[k])
list(eta = eta, beta = beta, tau = tau)
} |
rbwATE <- function(treatment, data, baseline_x, base_weights,
max_iter = 200, print_level = 1, tol = 1e-6) {
cl <- match.call()
if(missing(treatment)) stop("'treatment' must be provided.")
treatment <- ensym(treatment)
if(missing(data)) stop("'data' must be provided.")
if(!is.data.frame(data)) stop("'data' must be a data frame.")
n <- nrow(data)
if(missing(base_weights)){
bweights <- rep(1, n)
} else{
bweights <- eval_tidy(enquo(base_weights), data)
if(length(bweights) != n) stop("'base_weights' must have the same length as 'data'.")
}
if(!missing(baseline_x)) {
nl <- as.list(seq_along(data))
names(nl) <- names(data)
vars <- eval_tidy(enexpr(baseline_x), nl)
xnames <- names(data)[vars]
xform <- paste("~", paste(xnames, collapse = "+"))
x <- model.matrix(eval_tidy(parse_expr(xform)), data)[, -1, drop = FALSE]
xmodels <- apply(x, 2, function(y) lm(y ~ 1, weights = bweights))
xnames <- names(xmodels)
} else {
stop("Baseline confounders are not provided.")
}
a_mat <- eval_tidy(quo(model.matrix(~ !!treatment, data)))
a <- `colnames<-`(a_mat[, -1, drop = FALSE], colnames(a_mat)[-1])
if(nrow(a) != n) stop("'treatment' must have the same length as 'data'.")
res_prods_xa <- Reduce(cbind, mapply(rmat, xmodels, xnames, MoreArgs = list(a = a),
SIMPLIFY = FALSE))
res_prods <- res_prods_xa
res_prods_indep <- pivot(res_prods)
C <- as.matrix(res_prods_indep)
eb_out <- eb2(C = C, M = rep(0, ncol(C)), Q = bweights/sum(bweights),
max_iter = max_iter, print_level = print_level, tol = tol)
weights <- eb_out$W
list(weights = weights, constraints = res_prods_indep, eb_out = eb_out, call = cl)
} |
context("Test implementation of chebyshev distance ...")
P <- 1:10 / sum(1:10)
Q <- 20:29 / sum(20:29)
V <- -10:10
W <- -20:0
test_dist_matrix <- function(x, FUN) {
dist.fun <- match.fun(FUN)
res.dist.matrix <- matrix(NA_real_, nrow(x), nrow(x))
for (i in 1:nrow(x)) {
for (j in 1:nrow(x)) {
res.dist.matrix[i, j] <- dist.fun(x[i, ], x[j, ])
}
}
return(res.dist.matrix[lower.tri(res.dist.matrix, diag = FALSE)])
}
test_that("distance(method = 'chebyshev') computes the correct distance value.",
{
expect_equal(as.vector(philentropy::distance(rbind(P, Q), method = "chebyshev")),
max(abs((P) - (Q))))
expect_equal(as.vector(philentropy::distance(rbind(P, Q), method = "chebyshev")),
as.vector(stats::dist(base::rbind(P, Q), method = "maximum")))
distMat <-
rbind(rep(0.2, 5), rep(0.1, 5), c(5, 1, 7, 9, 5))
dist.vals <-
distance(distMat, method = "chebyshev")
expect_equal(dist.vals[lower.tri(dist.vals, diag = FALSE)],
as.vector(dist(distMat, method = "maximum")))
})
test_that("Correct chebyshev distance is computed when vectors contain 0 values ...", {
P1 <- c(1,0)
P2 <- c(0.5, 0.5)
Q1 <- c(0.5,0.5)
Q2 <- c(1,0)
expect_equal(as.vector(philentropy::distance(rbind(P1, Q1), method = "chebyshev")),
as.vector(stats::dist(base::rbind(P1, Q1), method = "maximum")))
expect_equal(as.vector(philentropy::distance(rbind(P2, Q2), method = "chebyshev")),
as.vector(stats::dist(base::rbind(P2, Q2), method = "maximum")))
}) |
file_summary_ui <- function(id) {
ns <- NS(id)
tagList(
selectInput(
ns("file_to_summarize"),
label = "Choose file to view",
choices = ""
),
tabsetPanel(
tabPanel(
"File Overview",
plotOutput(ns("datafilevisdat"))
),
tabPanel(
"File Details",
br(),
reactable::reactableOutput(ns("data_details"))
)
)
)
}
file_summary_server <- function(input, output, session, file_data) {
inputs <- reactiveVal(c())
observe({
non_null <- vapply(
file_data(),
function(x) !is.null(x),
logical(1)
)
inputs(names(which(non_null)))
updateSelectInput(
session,
"file_to_summarize",
label = "Choose file to view",
choices = inputs()
)
})
observeEvent(input$file_to_summarize, {
if (input$file_to_summarize != "") {
output$datafilevisdat <- renderPlot({
visualize_data_types(file_data()[[input$file_to_summarize]])
})
file_summary <- data_summary(file_data()[[input$file_to_summarize]])
column_defs <- get_column_definitions(file_summary)
output$data_details <- reactable::renderReactable({
reactable::reactable(
file_summary,
highlight = TRUE,
searchable = TRUE,
resizable = TRUE,
columns = column_defs
)
})
}
})
}
visualize_data_types <- function(data) {
if (!inherits(data, "tbl_df") && !inherits(data, "data.frame")) {
return(NULL)
}
visdat::vis_dat(data) +
ggplot2::theme(text = ggplot2::element_text(size = 16))
}
data_summary <- function(data) {
if (!inherits(data, "tbl_df") && !inherits(data, "data.frame")
|| nrow(data) == 0) {
return(NULL)
}
data_sum <- tibble::as_tibble(skimr::skim(data))
desired_cols <- c(
"skim_variable",
"skim_type",
"n_missing",
"complete_rate",
"character.n_unique",
"numeric.mean",
"numeric.sd",
"numeric.hist"
)
data_sum <- data_sum[, names(data_sum) %in% desired_cols]
data_sum <- tibble::add_column(data_sum, value_occurrence = NA)
for (var in data_sum$skim_variable) {
var_col <- which(names(data) == var)
val_summary <- summarize_values(data[[var_col]])
data_sum$value_occurrence[data_sum$skim_variable == var] <- val_summary
}
data_sum
}
summarize_values <- function(values) {
if (all(purrr::map_lgl(values, function(x) {
is.na(x) || is.null(x)
}))
) {
return(NA)
}
glue::glue_collapse(
purrr::imap_chr(table(values), ~ glue::glue("{.y} ({.x})")),
sep = ", "
)
}
get_column_definitions <- function(data) {
columns <- list(
skim_variable = reactable::colDef(
name = "Variable",
width = 125
),
skim_type = reactable::colDef(
name = "Type",
width = 80
),
n_missing = reactable::colDef(
name = "Missing",
maxWidth = 60,
align = "center"
),
complete_rate = reactable::colDef(
name = "% Complete",
maxWidth = 90,
align = "center",
cell = function(value) {
percentage <- value * 100
format(percentage, digits = 3)
}
)
)
types <- unique(data$skim_type)
if ("character" %in% types) {
columns$character.n_unique <- reactable::colDef(
name = "Unique",
maxWidth = 70,
align = "center",
cell = function(value) {
if (is.na(value)) {
"-"
} else {
format(value, digits = 3)
}
}
)
}
if ("numeric" %in% types) {
columns$numeric.mean <- reactable::colDef(
name = "Mean",
maxWidth = 60,
align = "center",
cell = function(value) {
if (is.na(value)) {
"-"
} else {
format(value, digits = 3)
}
}
)
columns$numeric.sd <- reactable::colDef(
name = "\U3C3",
maxWidth = 60,
align = "center",
cell = function(value) {
if (is.na(value)) {
"-"
} else {
format(value, digits = 3)
}
}
)
columns$numeric.hist <- reactable::colDef(
name = "Histogram",
maxWidth = 80,
align = "center"
)
}
columns$value_occurrence <- reactable::colDef(
name = "Value (
cell = function(value) {
if (!is.na(value) && nchar(value) > 40) {
return(glue::glue("{substr(value, 1, 40)}..."))
} else {
return(value)
}
},
details = function(index) {
value <- data[index, "value_occurrence"]
if (!is.na(value) && nchar(value) > 40) {
return(htmltools::div(
glue::glue("{value[[1]]}"),
width = 12,
class = "detailbox"
))
} else {
return(NULL)
}
}
)
columns
} |
.build_address <-
function(data, end_slug, end_slugs, address_parts, return_message = T) {
if (return_message) {
glue("Building location for {end_slug}") %>% message()
}
parts <-
address_parts[address_parts %>% str_detect(end_slug)]
remove_parts <-
end_slugs[!end_slugs %in% end_slug] %>% str_c(collapse = "|")
if (!end_slug %>% str_detect("Mailing|Alternate|Alt") & remove_parts != "") {
parts <-
parts %>% str_remove_all(remove_parts)
}
parts <- parts[parts %>% str_detect(end_slug)]
new_col <- glue("location{end_slug}") %>% as.character()
if (data %>% hasName(new_col)) {
return(data)
}
city_state <- glue("cityState{end_slug}") %>% as.character()
address <-
parts[parts %>% str_detect("addressStreet|address_street")]
if (length(address) > 0) {
address <- address[[1]]
}
address1 <- parts[parts %>% str_detect("addressStreet1|address_street_1")]
if (length(address1) > 0) {
address1 <- address1[[1]]
}
address2 <- parts[parts %>% str_detect("addressStreet2|address_street_2")]
if (length(address2) > 0) {
address2 <- address2[[1]]
}
city <- parts[parts %>% str_detect("city|City")]
if (length(city) > 0) {
city <- city[[1]]
}
state <- parts[parts %>% str_detect("state|State")]
if (length(state) > 0) {
state <- state[[1]]
}
zip <-
parts[parts %>% str_detect("zip")]
zip <- zip[!zip %>% str_detect("zipcode4|zip4")]
if (length(zip) > 0) {
zip <- zip[[1]]
}
country <- parts[parts %>% str_detect("country")]
if (length(country) > 0) {
country <- country[[1]]
}
df_locs <-
data %>%
select(one_of(address, address1, address2, city, state, zip, country)) %>%
distinct()
if (length(city) + length(state) == 2) {
df_locs <-
df_locs %>%
unite(!!sym(city_state),
city,
state,
sep = ", ",
,
remove = F) %>%
filter(!!sym(city_state) != "NA, NA")
df_locs <-
df_locs %>%
mutate_if(is.character,
list(function(x) {
x %>% coalesce("")
})) %>%
unite(
!!sym(new_col),
c(address, city_state, zip, country),
sep = " ",
remove = F
) %>%
mutate_at(new_col, str_squish) %>%
mutate_if(is.character,
list(function(x) {
case_when(x == "" ~ NA_character_,
TRUE ~ x)
}))
} else {
df_locs <-
df_locs %>%
mutate_if(is.character,
list(function(x) {
x %>% coalesce("")
})) %>%
unite(
!!sym(new_col),
c(address, city, state, zip, country),
sep = " ",
remove = F
) %>%
mutate_at(new_col, str_squish) %>%
mutate_if(is.character,
list(function(x) {
case_when(x == "" ~ NA_character_,
TRUE ~ x)
}))
}
join_cols <- names(df_locs)[names(df_locs) %in% names(data)]
data <-
data %>%
left_join(df_locs, by = join_cols)
data
}
build_address <-
function(data,
address_search_slugs = c("^address", "^streetAddress", "^city", "^state", "^codeState", "^codeCountry", "^country", "^zipcode"),
include_snake_versions = T,
part_threshold = 3,
snake_names = F,
return_message = T) {
if (include_snake_versions) {
clean_n <- address_search_slugs %>% make_clean_names()
clean_n <- glue("^{clean_n}") %>% as.character()
address_search_slugs <- c(address_search_slugs,clean_n) %>% unique()
}
address_slugs <-
str_c(address_search_slugs, collapse = "|")
address_parts <-
data %>% select(matches(address_slugs)) %>% names()
if (length(address_parts) == 0) {
return(data)
}
end_slugs <-
tibble(part = address_parts %>%
str_remove_all(address_slugs)) %>%
count(part, sort = T) %>%
filter(n >= part_threshold) %>%
pull(part)
end_slugs %>%
walk(function(x) {
data <<-
.build_address(
data = data,
end_slug = x,
end_slugs = end_slugs,
address_parts = address_parts,
return_message = return_message
)
})
if (snake_names) {
data <- data %>% clean_names()
}
data
}
munge_tbl <-
function(data, snake_names = F, unformat = F, convert_case = T,
amount_digits = 2,
include_address = T) {
data <- data %>%
mutate_if(is.character,
list(function(x) {
x %>% str_squish()
})) %>%
mutate_if(is.character,
list(function(x) {
case_when(x == "" ~ NA_character_,
TRUE ~ x)
}))
is_has <-
data %>%
select_if(is.character) %>%
dplyr::select(dplyr::matches("^is|^has")) %>% names()
if (length(is_has) > 0) {
data <- data %>%
mutate_at(is_has,
list(function(x){
case_when(x %in% c("Y", "YES", "TRUE", "1") ~ TRUE,
TRUE ~ FALSE)
}))
}
to_num <-
data %>%
select_if(is.character) %>%
select(matches("amount|price|value|ratio|count[A-Z]|number|shares")) %>%
select(-matches("country|county")) %>%
names()
if (length(to_num) > 0) {
data <- data %>%
mutate_at(to_num, readr::parse_number)
}
if (convert_case) {
upper_cols <-
data %>% select_if(is.character) %>%
select(-matches("^url")) %>%
names()
data <-
data %>%
mutate_at(upper_cols,
str_to_upper)
}
if (!unformat) {
pct_names <-
data %>%
select_if(is.numeric) %>%
select(matches("^percent|^pct")) %>% names()
count_names <-
data %>%
select_if(is.numeric) %>%
select(matches("^count|^number")) %>% names()
amt_names <-
data %>%
select_if(is.numeric) %>%
select(matches("^amount|^amt|^price|^earnings")) %>% names()
if (length(pct_names) > 0) {
data <- data %>%
mutate_at(pct_names,
list(function(x){
x %>% percent(digits = 2)
}))
}
if (length(amt_names) > 0) {
data <- data %>%
mutate_at(pct_names,
list(function(x){
x %>% currency(digits = amount_digits)
}))
}
if (length(count_names) > 0) {
data <- data %>%
mutate_at(count_names,
list(function(x){
x %>% comma(digits = 0)
}))
}
}
if (include_address) {
data <-
data %>%
build_address()
}
if (snake_names) {
data <-
data %>%
janitor::clean_names()
}
if (unformat) {
data <- data %>%
mutate_if(is.numeric, as.numeric)
}
data
}
.get_cik_url_df <-
function(cik = 1138621) {
slugs <-
c(
'general',
'filings',
'private',
'fundraising',
'traders',
'clevel',
'mda',
'owners',
'subsidiaries'
)
url_json <-
list('http://rankandfiled.com/data/filer/', cik, '/', slugs) %>%
purrr::invoke(paste0, .)
url_df <-
dplyr::tibble(
nameTable = c(
'General',
'Filings',
'Private',
'Fundraising',
'Traders',
'C Level',
'MDA',
'Owners',
'Subsidiaries'
),
urlJSON = url_json
)
return(url_df)
}
.parse_json_general_filing <-
function(url = "http://rankandfiled.com/data/filer/1468327/general",
nest_data = TRUE,
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
data <-
url %>%
jsonlite::fromJSON(simplifyDataFrame = TRUE) %>%
data.frame(stringsAsFactors = FALSE) %>%
as_tibble()
is_company <-
'company' %in% names(data)
is_insider <-
'insider' %in% names(data)
is_fund <-
'fund' %in% names(data)
data <-
data %>%
.resolve_name_df()
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/', '') %>%
str_replace_all('\\/general', '') %>%
as.numeric()
data <-
data %>%
mutate(idCIK = cik)
if (!'nameEntity' %in% names(data)) {
if (is_company) {
ticker <-
data$company
company_name_df <-
ticker %>%
.parse_company_general_safe() %>%
suppressWarnings()
has_rows <-
company_name_df %>% nrow > 0
if (has_rows) {
return(company_name_df)
} else {
entity_name <-
NA
}
}
if (is_insider) {
insider_df <-
.parse_json_general_insider(cik = cik, return_message = return_message) %>%
mutate(nameEntity = nameEntity %>% str_to_upper())
return(insider_df)
}
if (is_fund) {
fund_df <-
.parse_json_fund_general(cik = cik, return_message = return_message) %>%
mutate(nameEntity = nameEntity %>% str_to_upper())
return(fund_df)
}
data <-
data %>%
mutate(nameEntity = entity_name,
idTicker = ticker) %>%
select(-dplyr::matches("company"))
}
data <-
data %>%
select(-dplyr::matches("object")) %>%
mutate_at(.vars = data %>% select(dplyr::matches("idCIK|idIRS")) %>% names(),
as.numeric) %>%
mutate(urlJSONGeneral = url,
nameEntity = nameEntity %>% stringr::str_to_upper())
has_address <-
names(data) %in% c('addressStreet1Entity',
'stateEntity',
'cityEntity',
'zipcodeEntity') %>% sum() == 4
if (has_address) {
data <-
data %>%
mutate(
addressEntity = list(
addressStreet1Entity,
' ',
cityEntity,
' ',
stateEntity,
', ',
zipcodeEntity
) %>% purrr::invoke(paste0, .)
) %>%
select(idCIK, dplyr::matches("nameEntity"), addressEntity, everything())
}
if ('detailsOwnedBy' %in% names(data)) {
data <-
data %>%
dplyr::rename(detailsOwns = detailsOwnedBy)
}
if ('detailsOwns' %in% names(data)) {
detail_df <-
seq_along(data$detailsOwns) %>%
future_map_dfr(function(x) {
detail_value <-
data$detailsOwns[[x]]
if (detail_value %>% is.na()) {
df <-
tibble(idRow = x, nameCompanyOwns = NA)
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataCompaniesOwns)
}
return(df)
}
values <-
detail_value %>% str_replace('\\|', '') %>%
str_split('\\|') %>%
flatten_chr()
df_data <-
tibble(value = values) %>%
tidyr::separate(value,
into = c('idTickerOwns', 'other'),
sep = '\\:') %>%
tidyr::separate(other,
into = c('nameCompanyOwns', 'other'),
sep = '\\_') %>%
tidyr::separate(other,
into = c('roleOwner', 'dateOwner'),
sep = '\\
mutate(nameCompanyOwns = nameCompanyOwns %>% str_to_upper(),
idRow = x) %>%
gather(item, value, -idRow, na.rm = TRUE) %>%
group_by(item) %>%
mutate(count = 1:n() - 1) %>%
ungroup() %>%
arrange((count)) %>%
mutate(item = ifelse(count == 0, item, paste0(item, count))) %>%
select(-count)
column_order <-
c('idRow', df_data$item)
df_data <-
df_data %>%
spread(item, value) %>%
select(one_of(column_order))
}) %>%
suppressWarnings()
detail_df <-
detail_df %>%
mutate_at(.vars = detail_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% ymd())) %>%
suppressWarnings()
if (nest_data) {
detail_df <-
detail_df %>%
nest(-idRow, .key = dataCompaniesOwns)
}
data <-
data %>%
mutate(idRow = 1:n()) %>%
select(-detailsOwns) %>%
left_join(detail_df) %>%
select(-idRow) %>%
suppressMessages()
}
data <-
data %>%
select(
nameEntity,
idCIK,
dplyr::matches("typeCategory"),
dplyr::matches("idtypeCompany"),
everything()
)
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(data)
}
.parse_json_filings <-
function(url = "http://rankandfiled.com/data/filer/1138621/filings",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/filings', '') %>%
as.numeric()
json_data <-
url %>%
jsonlite::fromJSON(simplifyDataFrame = TRUE) %>%
data.frame(stringsAsFactors = FALSE) %>%
as_tibble() %>%
tidyr::separate(
filings,
sep = '\\*',
into = c(
'dateFiling',
'codeFiling',
'typeForm',
'baseIndex',
'detailOffering',
'slugSEC',
'idSECSlug'
)
) %>%
mutate(
dateFiling = dateFiling %>% as.numeric() %>% lubridate::ymd,
idCIK = cik,
urlJSONFilings = url,
urlSEC = ifelse(
slugSEC == "None",
NA,
list(
"https://www.sec.gov/Archives/edgar/data/",
idCIK,
'/',
slugSEC
) %>% purrr::invoke(paste0, .)
),
pageSlug = idSECSlug %>% str_replace_all('\\-',''),
urlSECFilingDirectory = ifelse(
idSECSlug %>% str_detect('\\-'),
list(
"https://www.sec.gov/Archives/edgar/data/",
idCIK,
'/',
pageSlug,
'/',
idSECSlug,
'-index.htm'
) %>% purrr::reduce(paste0),
NA
)
) %>%
select(-dplyr::matches("^X")) %>%
suppressMessages() %>%
select(-c(slugSEC, pageSlug)) %>%
select(idCIK, dateFiling, everything())
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(json_data)
}
.parse_json_private <-
function(url = "http://rankandfiled.com/data/filer/1438171/private",
nest_data = TRUE,
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
status_df <-
json_data$status_history %>% flatten_df() %>%
mutate(date = date %>% lubridate::ymd())
offering_history_class_df <-
json_data$offering_history %>% future_map_dfr(class) %>%
gather(column, type) %>%
mutate(idName = 1:n())
offering_data <-
json_data$offering_history %>%
select(offering_history_class_df %>%
filter(!type == 'list') %>%
.$idName)
offering_data <-
offering_data %>%
as_tibble() %>%
mutate_all(funs(. %>% str_replace('\\|', '')))
offering_data <-
offering_data %>%
.resolve_name_df() %>%
resolve_names_to_upper()
if (offering_data %>% ncol >= 9) {
offering_data <-
offering_data %>%
separate_column(column_name = 'idExemption') %>%
separate_column(column_name = 'dateAmmended') %>%
separate_column(column_name = 'amountFindersFee') %>%
separate_column(column_name = 'countInvestors') %>%
separate_column(column_name = 'countInvestorsNonAccredited') %>%
separate_column(column_name = 'amountOffered') %>%
separate_column(column_name = 'amountRemaining') %>%
separate_column(column_name = 'amountSold')
offering_data <-
offering_data %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^is")) %>% names,
funs(. %>% as.logical())) %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^amount|^count|^idCIK")) %>% names,
funs(. %>% as.numeric())) %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^date")) %>% names,
funs(. %>% lubridate::ymd())) %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^amount")) %>% names,
funs(. %>% formattable::currency(digits = 0))) %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^count")) %>% names,
funs(. %>% formattable::comma(digits = 0))) %>%
mutate_if(is.numeric, as.numeric)
} else {
offering_data <-
offering_data %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^amount|^count|^idCIK")) %>% names,
funs(. %>% as.numeric())) %>%
mutate_at(.vars = offering_data %>% select(dplyr::matches("^date")) %>% names,
funs(. %>% lubridate::ymd()))
}
has_relations <-
'_related_people' %in% names(json_data$offering_history)
if (has_relations) {
relation_df <-
1:(json_data$offering_history$amended %>% length()) %>%
future_map_dfr(function(x) {
if (!json_data$offering_history$`_related_people`[[x]] %>% purrr::is_null()) {
relation_data <-
json_data$offering_history$`_related_people`[[x]] %>% mutate(
name =
ifelse(
name %>% substr(1, 3) %>% str_detect('\\-'),
name %>% str_replace_all('\\-', '') %>% str_trim,
name %>% str_trim
)
) %>%
tidyr::unite(nameRelation, name, relation, sep = '-') %>%
.$nameRelation %>% paste0(collapse = '&')
} else {
relation_data <-
NA
}
tibble(nameRelation = relation_data)
}) %>%
resolve_names_to_upper()
relation_df <-
1:nrow(relation_df) %>%
future_map_dfr(function(x) {
person_title <-
relation_df$nameRelation[[x]] %>%
str_split('\\&') %>%
flatten_chr() %>%
str_to_upper() %>%
str_trim()
df <-
tibble(idRow = x, person_title) %>%
tidyr::separate(
person_title,
sep = '\\-',
into = c('nameRelatedParty', 'titleRelatedParty')
) %>%
mutate(countItem = 1:n() - 1) %>%
gather(item, value, -c(idRow, countItem)) %>%
arrange(countItem)
df <-
df %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
select(-countItem)
column_order <-
c('idRow', df$item)
df <-
df %>%
spread(item, value) %>%
select(one_of(column_order))
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataRelations)
}
return(df)
})
offering_data <-
offering_data %>%
mutate(idRow = 1:n()) %>%
left_join(relation_df) %>%
suppressMessages() %>%
select(-idRow)
}
has_brokers <-
'_brokers' %in% names(json_data$offering_history)
if (has_brokers) {
broker_df <-
1:(json_data$offering_history$amended %>% length()) %>%
map_dfr(function(x) {
empty_value <-
json_data$offering_history$`_brokers`[[x]] %>% length() ==0
if (empty_value) {
broker_crd <-
NA
} else {
broker_crd <-
json_data$offering_history$`_brokers`[[x]] %>%
tidyr::unite(nameBrokerCRD, name, crd, sep = '&') %>%
.$nameBrokerCRD %>%
paste0(collapse = ' | ')
}
tibble(nameBrokerCRD = broker_crd)
}) %>%
resolve_names_to_upper()
broker_df <-
1:nrow(broker_df) %>%
future_map_dfr(function(x) {
broker_crd <-
broker_df$nameBrokerCRD[[x]] %>%
str_split('\\|') %>%
flatten_chr() %>%
str_to_upper() %>%
str_trim()
if (broker_crd %>% is.na() %>% sum() > 0) {
df <-
tibble(
idRow = x,
nameBroker = "NONE",
idCRDBroker = NA
)
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataBrokers)
}
return(tibble())
}
df <-
tibble(idRow = x, broker_crd) %>%
tidyr::separate(broker_crd,
sep = '\\&',
into = c('nameBroker', 'idCRDBroker')) %>%
mutate(countItem = 1:n() - 1) %>%
gather(item, value, -c(idRow, countItem)) %>%
arrange(countItem) %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
select(-countItem)
column_order <-
c('idRow', df$item)
df <-
df %>%
spread(item, value) %>%
select(one_of(column_order))
df <-
df %>%
mutate_at(df %>% select(dplyr::matches("idCRD")) %>% names(),
funs(. %>% as.numeric())) %>%
resolve_names_to_upper()
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataBrokers)
}
return(df)
})
offering_data <-
offering_data %>%
mutate(idRow = 1:n()) %>%
left_join(broker_df) %>%
suppressMessages() %>%
select(-idRow)
}
if ('date' %in% names(status_df)) {
initial_date <-
status_df$date
} else {
initial_date <-
NA
}
if ('entity_type' %in% names(status_df)) {
typeEntity <-
status_df$entity_type
} else {
typeEntity <-
NA
}
if ('jurisdiction' %in% names(status_df)) {
jurisdiction <-
status_df$jurisdiction
} else {
jurisdiction <-
NA
}
if ('over_five' %in% names(status_df)) {
has_five <-
status_df$over_five
} else {
has_five <-
FALSE
}
offering_data <-
offering_data %>%
mutate(
dateInitialFiling = initial_date,
typeEntity = typeEntity,
locationJurisdiction = jurisdiction,
hasOver5FileFilings = has_five,
urlJSONFilings = url
) %>%
select(
idCIK,
dateInitialFiling,
typeEntity,
locationJurisdiction,
hasOver5FileFilings,
dplyr::matches("nameIndustry"),
dplyr::matches("typeFund"),
dplyr::matches("^is"),
dplyr::matches("^amount"),
dplyr::matches("^count"),
everything()
) %>%
resolve_names_to_upper() %>%
select(which(colMeans(is.na(.)) < 1))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(offering_data)
}
.parse_json_fundraising <-
function(url = "http://rankandfiled.com/data/filer/1138621/fundraising",
nest_data = TRUE,
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
fundraising_df <-
json_data$results %>%
as_tibble() %>%
purrr::set_names(c(
'idCIKs',
'nameCompanies',
'isCIKFiler',
'namePerson',
'offeringsValues'
)) %>%
mutate(
idPerson = 1:n(),
idCIK = url %>% str_replace_all('http://rankandfiled.com/data/filer/|/fundraising', '') %>% as.numeric(),
namePerson = namePerson %>% str_replace_all('\\-', '') %>% stringr::str_to_upper() %>% str_trim(),
urlJSONFundraising = url
) %>%
suppressWarnings()
company_name_df <-
seq_along(fundraising_df$nameCompanies) %>%
future_map_dfr(function(x) {
company_name_data <-
fundraising_df$nameCompanies[[x]]
company_name_data <-
company_name_data %>%
str_split('\\*') %>%
flatten_chr() %>%
str_to_upper()
df <-
tibble(value = company_name_data) %>%
mutate(item = 'nameCompanyFundraisingRelated') %>%
mutate(countRow = 1:n()) %>%
mutate(
countRow = countRow - 1,
item = ifelse(countRow == 0, item, item %>% paste0(countRow)),
idPerson = x
) %>%
select(-countRow)
col_order <-
c('idPerson', df$item)
df <-
df %>%
spread(item, value) %>%
select(one_of(col_order)) %>%
resolve_names_to_upper()
if (nest_data) {
df <-
df %>%
nest(-idPerson, .key = dataCompaniesRelated)
}
return(df)
})
offering_value_df <-
seq_along(fundraising_df$offeringsValues) %>%
future_map_dfr(function(x) {
offering_value_data <-
fundraising_df$offeringsValues[[x]]
offering_value_data <-
offering_value_data %>%
str_split('\\*') %>%
flatten_chr()
df <-
tibble(offering = offering_value_data) %>%
tidyr::separate(
offering,
into = c(
'idCIKRelatedCompanyFundraising',
'idIndustryRelatedCompanyFundRaising',
'amountRaisedRelatedCompanyFundRaising'
),
sep = '\\|'
) %>%
mutate(countRow = 1:n()) %>%
gather(item, value, -countRow) %>%
mutate(
countRow = countRow - 1,
value = value %>% as.numeric(),
item = ifelse(countRow == 0, item, item %>% paste0(countRow)),
idPerson = x
) %>%
select(-countRow)
col_order <-
c('idPerson', df$item)
df <-
df %>%
spread(item, value) %>%
select(one_of(col_order)) %>%
resolve_names_to_upper()
if (nest_data) {
df <-
df %>%
nest(-idPerson, .key = dataOfferingValues)
}
return(df)
})
fundraising_df <-
fundraising_df %>%
left_join(company_name_df) %>%
left_join(offering_value_df) %>%
select(-c(idCIKs, nameCompanies, idPerson, offeringsValues)) %>%
select(idCIK, namePerson, isCIKFiler, everything()) %>%
suppressMessages() %>%
suppressWarnings()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(fundraising_df)
}
.parse_json_traders <-
function(url = "http://rankandfiled.com/data/filer/1326801/traders",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/traders', '') %>%
as.numeric()
traders <-
json_data$owners$count
df <-
json_data$owners$owners %>%
as_tibble() %>%
purrr::set_names(c('nameEntityTrader', 'idCIKTrader', 'titleEntityTrader')) %>%
mutate(
nameEntityTrader = nameEntityTrader %>% str_to_upper(),
idCIKTrader = idCIKTrader %>% as.numeric(),
idCIK = cik
) %>%
select(idCIK, everything()) %>%
mutate(countTraders = traders) %>%
resolve_names_to_upper()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
.parse_json_clevel <-
function(url = "http://rankandfiled.com/data/filer/1326801/clevel",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/clevel', '') %>%
as.numeric()
clevel_df <-
json_data$clevel %>%
as_tibble() %>%
tidyr::separate(
value,
into = c(
"idCIKCSuite",
"nameEntityCSuite",
"dateStartCSuite",
"dateEndCSuite",
"nameCSuiteRole",
'codeCSuiteRole'
),
sep = '\\*'
) %>%
mutate(
idCIKCSuite = idCIKCSuite %>% as.numeric(),
nameEntityCSuite = nameEntityCSuite %>% str_to_upper(),
idCIK = cik,
dateStartCSuite = dateStartCSuite %>% lubridate::ymd(),
dateEndCSuite = dateEndCSuite %>% lubridate::ymd()
) %>%
select(idCIK,
idCIKCSuite,
nameEntityCSuite,
codeCSuiteRole,
everything()) %>%
mutate(isActiveCSuite = ifelse(dateEndCSuite %>% is.na(), TRUE, FALSE)) %>%
resolve_names_to_upper()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(clevel_df)
}
.parse_json_mda <-
function(url = "http://rankandfiled.com/data/filer/1326801/mda",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/mda', '') %>%
as.numeric()
data <-
json_data$results$matrix %>%
as_tibble()
names(data) <-
json_data$results$dates %>% lubridate::ymd()
words <-
json_data$results$words
data <-
data %>%
mutate(nameWord = words) %>%
gather(date10K, countWord, -nameWord) %>%
mutate(date10K = date10K %>% lubridate::ymd(),
idCIK = cik) %>%
select(idCIK, date10K, nameWord, countWord) %>%
arrange(desc(date10K)) %>%
resolve_names_to_upper()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(data)
}
.parse_json_owners <-
function(url = "http://rankandfiled.com/data/filer/1326801/owners",
nest_data = TRUE,
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/owners', '') %>%
as.numeric()
general_df <-
tibble(idCIK = cik,
idCIKOwned = json_data$insiders$cik %>% as.numeric())
has_filer <-
'filer' %in% names(json_data$insiders)
if (has_filer) {
filing_df <-
json_data$insiders$filer %>%
as_tibble()
filing_df <-
filing_df %>%
.resolve_name_df()
filing_df <-
filing_df %>%
mutate_at(.vars = filing_df %>% select(dplyr::matches("nameEntity")) %>% names(),
funs(. %>% str_to_upper())) %>%
resolve_names_to_upper()
if ('name' %in% names(filing_df)) {
filing_df <-
filing_df %>%
select(-name)
}
if ('sic' %in% names(filing_df)) {
filing_df <-
filing_df %>%
dplyr::rename(idSIC = sic) %>%
mutate(idSIC = idSIC %>% as.numeric())
}
names(filing_df) <-
names(filing_df) %>% str_replace('OwnedBy', '') %>%
paste0('Owner')
if ('detailsOwner' %in% names(filing_df)) {
detail_df <-
seq_along(filing_df$detailsOwner) %>%
future_map_dfr(function(x) {
detail_value <-
filing_df$detailsOwner[[x]]
if (detail_value %>% is.na()) {
df <-
tibble(idRow = x, nameCompanyOwned = NA)
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataCompaniesOwned)
}
return(df)
}
values <-
detail_value %>% str_replace('\\|', '') %>%
str_split('\\|') %>%
flatten_chr()
df_data <-
tibble(value = values) %>%
tidyr::separate(value,
into = c('idTickerOwned', 'other'),
sep = '\\:') %>%
tidyr::separate(other,
into = c('nameCompanyOwned', 'other'),
sep = '\\_') %>%
tidyr::separate(other,
into = c('roleOwned', 'dateOwned'),
sep = '\\
mutate(nameCompanyOwned = nameCompanyOwned %>% str_to_upper(),
idRow = x) %>%
gather(item, value, -idRow, na.rm = TRUE) %>%
group_by(item) %>%
mutate(count = 1:n() - 1) %>%
ungroup() %>%
arrange((count)) %>%
mutate(item = ifelse(count == 0, item, paste0(item, count))) %>%
select(-count)
column_order <-
c('idRow', df_data$item)
df_data <-
df_data %>%
spread(item, value) %>%
select(one_of(column_order)) %>%
resolve_names_to_upper()
if (nest_data) {
df_data <-
df_data %>%
nest(-idRow, .key = dataCompaniesOwned)
}
return(df_data)
}) %>%
suppressWarnings()
detail_df <-
detail_df %>%
mutate_at(.vars = detail_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% ymd())) %>%
suppressWarnings()
filing_df <-
filing_df %>%
mutate(idRow = 1:n()) %>%
select(-detailsOwner) %>%
left_join(detail_df) %>%
select(-idRow) %>%
suppressMessages()
}
general_df <-
general_df %>%
bind_cols(filing_df)
}
has_companies <-
'companies' %in% names(json_data$insiders)
if (has_companies) {
company_df <-
1:nrow(general_df) %>%
future_map_dfr(function(x) {
has_no_data <-
json_data$insiders$companies[[x]] %>%
nrow() == 0
if (has_no_data) {
df <-
tibble(idRow = x, nameFiler = NA)
if (nest_data) {
df <-
df %>%
nest(idRow, .key = dataInsiderCompaniesOwned)
}
}
company_df <-
json_data$insiders$companies[[x]] %>%
as_tibble() %>%
.resolve_name_df() %>%
mutate(idRow = x) %>%
mutate(nameFiler = nameFiler %>% str_to_upper())
if ('sic' %in% names(company_df)) {
company_df <-
company_df %>%
dplyr::rename(idSICCompanyOwned = sic) %>%
mutate(idSICCompanyOwned = idSICCompanyOwned %>% as.numeric())
}
df_data <-
company_df %>%
gather(item, value, -c(nameFiler, idRow)) %>%
group_by(item) %>%
mutate(count = 1:n() - 1) %>%
ungroup() %>%
arrange((count)) %>%
mutate(item = ifelse(count == 0, item, paste0(item, count))) %>%
select(-count)
column_order <-
c('idRow', 'nameFiler', df_data$item)
df_data <-
df_data %>%
spread(item, value) %>%
select(one_of(column_order)) %>%
resolve_names_to_upper()
if (nest_data) {
df_data <-
df_data %>%
nest(-idRow, .key = dataInsiderCompaniesOwned)
}
return(df_data)
})
company_df <-
company_df %>%
mutate_at(.vars =
company_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% lubridate::ymd())) %>%
mutate_at(.vars =
company_df %>% select(dplyr::matches("idCIK")) %>% names(),
.funs = as.numeric) %>%
mutate_at(
.vars =
company_df %>% select(dplyr::matches("nameCompany")) %>% names(),
.funs = stringr::str_to_upper
)
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
left_join(company_df %>% select(-dplyr::matches("idCIKOwned"))) %>%
select(-idRow) %>%
suppressMessages()
}
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
general_df <-
general_df %>%
select(idCIK,
idCIKOwned,
nameEntityOwner,
dplyr::matches("nameFiler"),
everything()) %>%
resolve_names_to_upper()
return(general_df)
}
.parse_json_public_filers <-
function(url = "http://rankandfiled.com/data/filer/1680780/all?start=0",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/all', '') %>%
str_split('\\?') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
filing_df <-
json_data$filings %>%
as_tibble()
filing_df <-
filing_df %>%
separate(
value,
into = c(
"idRF",
"idForm",
"detailForm",
"typeReport",
"typeFiling",
"slugSEC",
"idSECSlug",
"dateFiling",
"X9"
),
sep = '\\*'
) %>%
select(-dplyr::matches("X")) %>%
suppressMessages() %>%
suppressWarnings()
filing_df <-
filing_df %>%
mutate(
idCIK = cik,
pageSlug = idSECSlug %>% str_replace_all('\\-',''),
urlSECFilingDirectory = ifelse(
idSECSlug %>% str_detect('\\-'),
list(
"https://www.sec.gov/Archives/edgar/data/",
idCIK,
'/',
pageSlug,
'/',
idSECSlug,
'-index.htm'
) %>% purrr::reduce(paste0),
NA
),
urlSEC = ifelse(
slugSEC == "None",
NA,
list(
"https://www.sec.gov/Archives/edgar/data/",
idCIK,
'/',
slugSEC
) %>% purrr::invoke(paste0, .)
)
) %>%
select(-pageSlug) %>%
suppressWarnings()
filing_df <-
filing_df %>%
mutate(
typeFiling = typeFiling %>% str_to_upper(),
dateFiling = dateFiling %>% as.numeric() %>% lubridate::ymd(),
detailForm = ifelse(detailForm == '', NA, detailForm),
typeReport = ifelse(typeReport == '', NA, typeReport),
is13FFiling = (urlSEC %>% str_detect("xslForm13F")) &
(typeFiling == "HOLDINGS")
) %>%
tidyr::fill(dateFiling) %>%
tidyr::fill(detailForm) %>%
select(-slugSEC) %>%
left_join(dictionary_sec_form_codes()) %>%
tidyr::fill(nameForm) %>%
select(idCIK, idRF, idForm, nameForm, everything()) %>%
suppressMessages() %>%
suppressWarnings() %>%
resolve_names_to_upper()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(filing_df)
}
.parse_json_subsidiaries <-
function(url = "http://rankandfiled.com/data/filer/34088/subsidiaries",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
options(scipen = 9999)
name_df <-
tibble(
nameRF = c(
"cik",
"country",
"first_filed",
"last_filed",
"name",
"percent"
),
nameActual = c(
'idCIK',
'locationOrganizationSubsidiary',
'dateFirstFiled',
'dateLastFiled',
'nameSubsidiary',
'pctSubsidiaryOwned'
)
) %>%
mutate(idRow = 1:n())
data <-
url %>%
jsonlite::fromJSON() %>%
.$subsidiaries %>%
as_tibble()
rf_names <-
data %>% names()
has_missing_names <-
rf_names[!rf_names %in% name_df$nameRF] %>% length() > 0
if (has_missing_names) {
df_has <-
data %>%
select(one_of(rf_names[rf_names %in% name_df$nameRF]))
has_names <-
names(df_has) %>%
map_chr(function(x) {
name_df %>%
filter(nameRF == x) %>%
filter(idRow == min(idRow)) %>%
.$nameActual
})
df_has <-
df_has %>%
purrr::set_names(has_names)
data <-
df_has %>%
bind_cols(data %>%
select(one_of(rf_names[!rf_names %in% name_df$nameRF])))
data <-
data %>%
mutate_at(.vars =
data %>% select(
dplyr::matches(
"idCIK|idMidas|idIRS|^count|^price|^amount|^ratio|^pct|idMDA|^dateiso|idRF|price|amount|^year"
)
) %>% names,
funs(. %>% as.character() %>% readr::parse_number())) %>%
suppressWarnings()
return(data)
}
actual_names <-
names(data) %>%
map_chr(function(x) {
name_df %>%
filter(nameRF == x) %>%
filter(idRow == min(idRow)) %>%
.$nameActual
})
data <-
data %>%
purrr::set_names(actual_names)
data <-
data %>%
mutate(
idCIK = idCIK %>% as.numeric(),
nameSubsidiary = nameSubsidiary %>% str_to_upper(),
locationOrganizationSubsidiary = locationOrganizationSubsidiary %>% str_to_upper()
)
has_pct <-
'pctSubsidiaryOwned' %in% names(data)
if (has_pct) {
data <-
data %>%
mutate(
pctSubsidiaryOwned = pctSubsidiaryOwned %>% as.numeric(),
pctSubsidiaryOwned = pctSubsidiaryOwned / 100
)
}
data <-
data %>%
mutate_at(.vars = data %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% lubridate::ymd()))
data <-
data %>%
filter(!locationOrganizationSubsidiary %>% is.na()) %>%
resolve_names_to_upper()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(data)
}
.parse_cik_filings <-
function(cik = 1527559,
return_message = TRUE) {
general_url <-
list('http://rankandfiled.com/data/filer/', cik, '/general') %>%
purrr::invoke(paste0, .)
data_js <-
general_url %>% jsonlite::fromJSON() %>% data.frame(stringsAsFactors = FALSE)
is_public_company <-
'company' %in% (data_js %>% names())
is_insider <-
'insider' %in% (data_js %>% names())
if (is_public_company) {
company_df <-
general_url %>% jsonlite::fromJSON() %>% data.frame(stringsAsFactors = FALSE) %>%
as_tibble()
general_df <-
.parse_company_general_safe(ticker = company_df$company)
}
if (is_insider) {
general_df <-
.parse_json_general_insider(cik = cik)
}
is_private_filer <-
(!is_public_company) & (!is_insider)
if (is_private_filer) {
general_df <-
general_url %>%
.parse_json_general_filing()
}
filing_pages <-
general_df$countFilings %/% 50
if (filing_pages > 0) {
filing_urls <-
list(
'http://rankandfiled.com/data/filer/',
cik,
'/all?start=',
seq(0, by = 50, length.out = filing_pages)
) %>%
purrr::invoke(paste0, .)
}
if (filing_pages == 0) {
filing_urls <-
list('http://rankandfiled.com/data/filer/',
cik,
'/all?start=0') %>%
purrr::invoke(paste0, .)
}
.parse_json_public_filers_safe <-
purrr::possibly(.parse_json_public_filers, NULL)
.all_filings <-
filing_urls %>%
future_map_dfr(function(x) {
.parse_json_public_filers_safe(url = x, return_message = return_message)
}) %>%
distinct() %>%
suppressWarnings()
entity <-
general_df$nameEntity %>%
str_to_upper()
.all_filings <-
.all_filings %>%
mutate(nameEntity = entity) %>%
select(idCIK, nameEntity, dateFiling,
dplyr::matches("idRF"),
everything())
if ('typeReport' %in% names(.all_filings)) {
report_dict_df <-
dictionary_sec_filing_codes()
report_df <-
.all_filings %>%
mutate(idRow = 1:n()) %>%
select(typeReport, idRow) %>%
filter(!typeReport %>% is.na())
report_df <-
1:nrow(report_df) %>%
future_map_dfr(function(x) {
is_none <-
report_df$typeReport[[x]] == 'None'
if (is_none) {
return(tibble(
idRow = report_df$idRow[[x]],
idFormType = 'None',
nameFormType = NA
))
}
row_df <-
report_df %>%
slice(x)
reports <-
row_df$typeReport %>%
str_split('\\|') %>%
flatten_chr()
item_df <-
tibble(idFormType = reports, idRow = row_df$idRow) %>%
left_join(report_dict_df) %>%
gather(item, value, -idRow) %>%
group_by(item) %>%
mutate(countItems = 1:n() - 1) %>%
ungroup() %>%
mutate(item = ifelse(countItems == 0, item, paste0(item, countItems))) %>%
arrange(countItems) %>%
select(-countItems) %>%
suppressMessages()
col_order <-
c('idRow', item_df$item)
item_df <-
item_df %>%
spread(item, value) %>%
select(one_of(col_order))
return(item_df)
})
.all_filings <-
.all_filings %>%
mutate(idRow = 1:n()) %>%
dplyr::rename(typesReport = typeReport) %>%
left_join(report_df) %>%
suppressMessages() %>%
select(-idRow)
}
if (return_message) {
list(
"Parsed ",
.all_filings %>% nrow() %>% formattable::comma(digits = 0),
' SEC Filings for ',
entity
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
.all_filings <-
.all_filings %>%
resolve_names_to_upper()
return(.all_filings)
}
.parse_cik_data <-
function(cik = 899689,
nest_data = TRUE,
tables = NULL,
return_message = TRUE) {
url_df <-
cik %>%
.get_cik_url_df()
table_options <-
c(
'General',
'CIK Filings',
'Filings',
'Private Offerings',
'Related Parties',
'Traders',
'C Level',
'MDA',
'Owners',
'Insider Trades',
'Trades',
'Subsidiaries'
)
null_tables <-
length(tables) == 0
if (null_tables) {
tables <-
c(
'General',
'CIK Filings',
'Filings',
'Private Offerings',
'Related Parties',
'Traders',
'C Level',
'MDA',
'Owners',
'Insider Trades',
'Trades',
'Subsidiaries'
)
}
missing_tables <-
(tables %>% str_to_upper()) %in% (table_options %>% str_to_upper()) %>% sum() == 0
if (missing_tables) {
stop(list(
"Sorry Tables Can Only Be:",
'\n',
paste0(table_options, collapse = '\n')
) %>%
purrr::invoke(paste0, .))
}
table_options <-
table_options %>% str_to_upper()
tables <-
tables %>% str_to_upper()
if (!'GENERAL' %in% tables) {
tables <-
tables %>%
append('GENERAL')
}
has_general <-
'general' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_filings <-
'filings' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_cik_filings <-
'cik filings' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_private <-
'private offerings' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_related <-
'related parties' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_traders <-
'traders' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_clevel <-
'c level' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_mda <-
'mda' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_owners <-
'owners' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_insider_trades <-
'insider trades' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
has_subs <-
'subsidiaries' %>% str_to_upper() %>% str_detect(tables) %>% sum() > 0
if (has_general) {
.parse_json_general_filing_safe <-
purrr::possibly(.parse_json_general_filing, tibble())
general_df <-
url_df$urlJSON[[1]] %>%
.parse_json_general_filing(nest_data = nest_data,
return_message = return_message) %>%
mutate(nameEntity = nameEntity %>% str_to_upper()) %>%
as_tibble()
if (general_df %>% nrow() == 0) {
general_df <-
tibble(idCIK = cik,
nameEntity = NA)
}
} else {
general_df <-
tibble(idCIK = cik)
}
if (has_filings) {
.parse_json_filings_safe <-
purrr::possibly(.parse_json_filings, tibble())
filing_df <-
url_df$urlJSON[[2]] %>%
.parse_json_filings_safe(return_message = return_message) %>%
mutate_if(is_character,
str_to_upper)
has_rows <-
filing_df %>% nrow() > 0
if (has_rows) {
filing_df <-
filing_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
filing_df <-
tibble(idCIK = cik)
}
if (has_private) {
.parse_json_private_safe <-
purrr::possibly(.parse_json_private, tibble())
private_df <-
url_df$urlJSON[[3]] %>%
.parse_json_private_safe(nest_data = nest_data,
return_message = return_message)
has_rows <-
private_df %>% nrow() > 0
if (has_rows) {
private_df <-
private_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
private_df <-
tibble(idCIK = cik)
}
if (has_related) {
.parse_json_fundraising_safe <-
purrr::possibly(.parse_json_fundraising, tibble())
fundraising_df <-
url_df$urlJSON[[4]] %>%
.parse_json_fundraising_safe(nest_data = nest_data,
return_message = return_message)
has_rows <-
fundraising_df %>% nrow() > 0
if (has_rows) {
fundraising_df <-
fundraising_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
fundraising_df <-
tibble(idCIK = cik)
}
if (has_traders) {
.parse_json_traders_safe <-
purrr::possibly(.parse_json_traders, tibble())
traders_df <-
url_df$urlJSON[[5]] %>%
.parse_json_traders_safe(return_message = return_message)
has_rows <-
traders_df %>% nrow() > 0
if (has_rows) {
traders_df <-
traders_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
traders_df <-
tibble(idCIK = cik)
}
if (has_clevel) {
.parse_json_clevel_safe <-
purrr::possibly(.parse_json_clevel, tibble())
clevel_df <-
url_df$urlJSON[[6]] %>%
.parse_json_clevel_safe(return_message = return_message)
has_rows <-
clevel_df %>% nrow() > 0
if (has_rows) {
clevel_df <-
clevel_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
clevel_df <-
tibble(idCIK = cik)
}
if (has_mda) {
.parse_json_mda_safe <-
purrr::possibly(.parse_json_mda, tibble())
mda_df <-
url_df$urlJSON[[7]] %>%
.parse_json_mda_safe(return_message = return_message)
has_rows <-
mda_df %>% nrow() > 0
if (has_rows) {
mda_df <-
mda_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
mda_df <-
tibble(idCIK = cik)
}
if (has_owners) {
.parse_json_owners_safe <-
purrr::possibly(.parse_json_owners, tibble())
owners_df <-
url_df$urlJSON[[8]] %>%
.parse_json_owners_safe(nest_data = nest_data,
return_message = return_message)
if ('idTypeFilerOwner' %in% names(owners_df)) {
owners_df <-
owners_df %>%
left_join(.filer_type_df()) %>%
select(idCIK:nameEntityOwner, typeFilerOwner, everything()) %>%
suppressMessages()
}
has_rows <-
owners_df %>% nrow() > 0
if (has_rows) {
owners_df <-
owners_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
select(-dplyr::matches("dateiso")) %>%
suppressMessages()
}
} else {
owners_df <-
tibble(idCIK = cik)
}
if (has_cik_filings) {
.parse_cik_filings_safe <-
purrr::possibly(.parse_cik_filings, tibble())
cik_filing_df <-
.parse_cik_filings_safe(cik = cik, return_message = return_message)
} else {
cik_filing_df <-
tibble(idCIK = cik)
}
if (has_insider_trades) {
parse_insider_trades_safe <-
purrr::possibly(.parse_insider_trades, tibble())
insider_trade_df <-
parse_insider_trades_safe(cik = cik,
nest_data = nest_data,
return_message = return_message)
has_rows <-
insider_trade_df %>% nrow() > 0
if (has_rows) {
insider_trade_df <-
insider_trade_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
insider_trade_df <-
tibble(idCIK = cik)
}
if (has_subs) {
.parse_json_subsidiaries_safe <-
purrr::possibly(.parse_json_subsidiaries, tibble())
sub_df <-
url_df$urlJSON[[9]] %>%
.parse_json_subsidiaries(return_message = return_message)
has_rows <-
sub_df %>% nrow() > 0
if (has_rows) {
sub_df <-
sub_df %>%
left_join(general_df %>% select(idCIK, nameEntity)) %>%
select(nameEntity, idCIK, everything()) %>%
suppressMessages()
}
} else {
sub_df <-
tibble(idCIK = cik)
}
if ('nameEntity' %in% names(general_df)) {
nameEntity <-
general_df$nameEntity %>%
str_to_upper()
} else {
nameEntity <-
NA
}
all_data <-
tibble(
idCIK = cik,
nameEntity,
nameTable = c(
'General',
'CIK Filings',
'Filings',
'Private Offerings',
'Related Parties',
'Traders',
'C Level',
'MDA',
'Owners',
'Insider Trades',
'Subsidiaries'
),
dataTable = list(
general_df,
cik_filing_df,
filing_df,
private_df,
fundraising_df,
traders_df,
clevel_df,
mda_df,
owners_df,
insider_trade_df,
sub_df
)
)
if (return_message) {
list("\nParsed SEC Private Filing Data for CIK: ",
cik,
' - ',
nameEntity,
"\n") %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
all_data <-
all_data %>%
mutate(countCols = dataTable %>% purrr::map_dbl(ncol)) %>%
filter(countCols > 1) %>%
suppressWarnings() %>%
select(-dplyr::matches("countCols")
)
all_data
}
sec_filer <-
function(entity_names = NULL,
tickers = NULL,
ciks = NULL,
tables = NULL,
nest_data = FALSE,
parse_all_filing_url_data = FALSE,
parse_xbrl = FALSE,
parse_subsidiaries = FALSE,
parse_13F = FALSE,
parse_asset_files = FALSE,
parse_small_offerings = FALSE,
parse_complete_text_filings = FALSE,
parse_form_d = FALSE,
parse_form_3_4s = FALSE,
assign_to_environment = TRUE,
return_message = TRUE) {
has_entities <-
(('entity_names' %>% exists()) &
(!entity_names %>% purrr::is_null()))
has_ciks <-
(('ciks' %>% exists()) & (!ciks %>% purrr::is_null()))
has_tickers <-
(('tickers' %>% exists()) & (!tickers %>% purrr::is_null()))
has_nothing <-
((!has_ciks) & (!has_entities) & (!has_tickers))
has_tables <-
(!tables %>% purrr::is_null())
if (has_nothing) {
stop("Please enter a CIK, ticker, or an entity name")
}
all_ciks <-
c()
if (has_entities) {
sec_filing_entities_safe <-
purrr::possibly(sec_filing_entities, tibble())
search_df <-
entity_names %>%
sec_filing_entities_safe(return_message = return_message)
has_rows <-
search_df %>% nrow() > 0
if (has_rows) {
search_ciks <-
search_df %>%
.$idCIK
all_ciks <-
all_ciks %>%
append(search_ciks)
}
}
if (has_ciks) {
all_ciks <-
all_ciks %>%
append(ciks)
}
.parse_cik_data_safe <-
possibly(.parse_cik_data, NULL)
if (all_ciks %>% length() > 0) {
all_data <-
all_ciks %>%
sort() %>%
future_map_dfr(function(x) {
.parse_cik_data_safe(
tables = tables,
nest_data = nest_data,
cik = x,
return_message = return_message
)
}) %>%
mutate(
urlRankAndFiled =
list('http://rankandfiled.com/
) %>%
select(idCIK, nameEntity, urlRankAndFiled, nameTable, dataTable) %>%
distinct() %>%
suppressWarnings()
}
if (has_tickers) {
.parse_ticker_data_safe <-
purrr::possibly(.parse_ticker_data, tibble())
table_exists <-
'all_data' %>% exists()
if (table_exists) {
all_ticker_data <-
tickers %>%
future_map_dfr(function(x) {
.parse_ticker_data(
ticker = x,
nest_data = nest_data,
tables = tables,
return_message = return_message
)
}) %>%
suppressWarnings()
all_data <-
all_data %>%
bind_rows(all_ticker_data)
} else {
all_data <-
tickers %>%
future_map_dfr(function(x) {
.parse_ticker_data_safe(ticker = x,
tables = tables,
return_message = return_message)
}) %>%
suppressWarnings()
}
}
if (has_tables) {
table_options <-
c(
'General',
'CIK Filings',
'Filings',
'Private Offerings',
'Related Parties',
'Traders',
'C Level',
'MDA',
'Owners',
'Insider Trades',
'Trades'
)
table_names <-
tables %>% str_to_lower() %>% paste0(collapse = "|")
wrong_table <-
table_options %>% str_to_lower() %>% str_count(table_names) %>% sum() == 0
if (wrong_table) {
stop("Sorry tables can only be:\n" %>% paste0(paste0(table_options, collapse = '\n')))
}
all_data <-
all_data %>%
mutate(table = nameTable %>% str_to_lower()) %>%
filter(table %>% str_detect(table_names)) %>%
select(-table)
}
if (!'all_data' %>% exists()) {
return(tibble())
}
missing_ciks <-
all_ciks[!all_ciks %in% all_data$idCIK] %>% length() > 0
if (missing_ciks) {
list("Missing ", all_ciks[!all_ciks %in% all_data$idCIK] %>% paste(collapse = ', ')) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
all_data <-
all_data %>%
select(-dplyr::matches("urlRankAndFiled"))
has_filings <-
c('CIK Filings', 'Filings') %in% all_data$nameTable %>% sum() > 0
if (has_filings) {
filing_df <-
all_data %>%
filter(nameTable %in% c('Filings', 'CIK Filings')) %>%
select(dataTable) %>%
unnest() %>%
distinct()
filing_df <-
filing_df %>%
mutate_at(filing_df %>% select(dplyr::matches("^url")) %>% names(),
funs(. %>% str_to_lower()))
filing_df <-
filing_df %>%
mutate_at(filing_df %>% select(dplyr::matches("url^[A-Z]")) %>% names(),
funs(. %>% str_replace_all('archives', 'Archives')))
filing_df <-
filing_df %>%
mutate(
urlSECFilingDirectory = urlSECFilingDirectory %>% gsub('archives', 'Archives', .),
urlSEC = urlSEC %>% gsub('archives', 'Archives', .)
)
has_subsidiaries <-
(filing_df %>%
filter(typeFiling == "SUBSIDIARIES OF THE REGISTRANT") %>%
nrow() > 0) & (parse_subsidiaries)
if (has_subsidiaries) {
parse_sec_subsidiary_url_safe <-
purrr::possibly(.parse_sec_subsidiary_url, tibble())
has_list <-
filing_df %>%
filter(typeFiling == "LIST OF SUBSIDIARIES") %>%
nrow() > 0
sub_url_df <-
filing_df %>%
filter(
typeFiling %in% c(
"SUBSIDIARIES OF THE REGISTRANT",
"SUBSIDIARIES OF HOLDING COMPANY"
)
) %>%
select(dateFiling, nameEntity, urlSEC) %>%
distinct()
if (has_list) {
sub_url_list_df <-
filing_df %>%
filter(
typeFiling %>% str_detect(
"LIST OF SUBSIDIARIES|LIST OF SIGNIFICANT SUBSIDIARIES|LIST OF SIGNIFCANT"
)
) %>%
select(dateFiling, nameEntity, urlSEC) %>%
distinct()
if ('sub_url_df' %>% exists()) {
sub_url_df <-
sub_url_list_df %>%
bind_rows(sub_url_df)
} else {
sub_url_df <-
sub_url_list_df
}
}
sub_df <-
sub_url_df %>%
arrange(dateFiling) %>%
.$urlSEC %>%
future_map_dfr(function(x) {
parse_sec_subsidiary_url_safe(url = x, return_message = return_message)
}) %>%
suppressWarnings()
if (sub_df %>% nrow() > 0) {
sub_df <-
sub_df %>%
select(-dplyr::matches("X|date")) %>%
filter(
!nameSubsidiary %in% c(
'(I)',
'(II)',
'(III)',
'(IV)',
'(V)',
'(VI)',
'(VII)',
'(VIII)',
'(IX)',
'(X)',
'PART A'
)
) %>%
left_join(sub_url_df) %>%
select(idCIK, dateFiling, everything()) %>%
suppressMessages() %>%
distinct()
active_date_df <-
sub_df %>%
group_by(nameSubsidiary) %>%
summarise(
dateFirstFiled = min(dateFiling, na.rm = TRUE),
dateLastFiled = max(dateFiling, na.rm = TRUE),
isActiveSubsidiary = ifelse(
dateLastFiled == sub_df$dateFiling %>% max(na.rm = TRUE),
TRUE,
FALSE
)
) %>%
ungroup()
sub_df <-
sub_df %>%
left_join(active_date_df) %>%
left_join(sub_url_df) %>%
suppressMessages()
sub_df <-
sub_df %>%
mutate(nameSubsidiaryRF = nameSubsidiary %>% str_replace_all('\\,|\\.', '')) %>%
select(idCIK, nameEntity, dateFiling, everything()) %>%
suppressMessages()
has_sub_df <-
'Subsidiaries' %in% all_data$nameTable
if (has_sub_df) {
ad_sub_df <-
all_data %>%
filter(nameTable == 'Subsidiaries') %>%
select(dataTable) %>%
unnest()
if ('pctSubsidiaryOwned' %in% names(ad_sub_df)) {
sub_df <-
sub_df %>%
left_join(
ad_sub_df %>%
select(nameSubsidiaryRF = nameSubsidiary, pctSubsidiaryOwned) %>%
distinct()
) %>%
suppressMessages() %>%
select(-nameSubsidiaryRF)
}
if (nest_data) {
sub_df <-
sub_df %>%
nest(-c(dateFiling, idCIK, nameEntity), .key = dataSubsidiaries)
}
a_sub_df <-
sub_df %>%
group_by(idCIK, nameEntity) %>%
nest(-c(idCIK, nameEntity), .key = dataTable) %>%
ungroup() %>%
mutate(nameTable = 'Subsidiaries')
all_data <-
all_data %>%
filter(!nameTable == 'Subsidiaries') %>%
bind_rows(a_sub_df)
} else {
if (nest_data) {
sub_df <-
sub_df %>%
nest(-c(dateFiling, idCIK, nameEntity), .key = dataSubsidiaries)
}
a_sub_df <-
sub_df %>%
group_by(idCIK, nameEntity) %>%
nest(-c(idCIK, nameEntity), .key = dataTable) %>%
ungroup() %>%
mutate(nameTable = 'Subsidiaries')
all_data <-
all_data %>%
filter(!nameTable == 'Subsidiaries') %>%
bind_rows(a_sub_df)
}
}
}
parse_for_tables_rf_safe <-
purrr::possibly(.parse_for_tables_rf, tibble())
tables_edgar <-
parse_for_tables_rf_safe(
filing_df = filing_df,
parse_complete_text_filings = parse_complete_text_filings,
parse_form_d = parse_form_d,
parse_13F = parse_13F,
parse_small_offerings = parse_small_offerings,
parse_form_3_4s = parse_form_3_4s,
parse_asset_files = parse_asset_files,
parse_xbrl = parse_xbrl
)
has_edgar_tables <-
tables_edgar %>% nrow() > 0
if (has_edgar_tables) {
all_data <-
all_data %>%
nest(-nameTable, .key = dataTable) %>%
bind_rows(tables_edgar)
}
}
if (assign_to_environment) {
table_name_df <-
all_data %>%
select(nameTable) %>%
distinct() %>%
mutate(
nameDF =
list('dataFiler', nameTable %>% str_replace_all('\\ ', '')) %>% purrr::invoke(paste0, .)
)
1:nrow(table_name_df) %>%
walk(function(x) {
df_name <-
table_name_df %>% slice(x) %>% .$nameDF
df_name %>% cat(fill = T)
df_data <-
all_data %>%
filter(nameTable == table_name_df$nameTable[[x]]) %>%
select(dplyr::matches(c('idCIK|nameEntity|dataTable'))) %>%
unnest() %>%
suppressWarnings() %>%
remove_duplicate_columns()
has_unnest2 <-
names(df_data) %>% str_detect('data') %>% sum(na.rm = TRUE) > 1
if (has_unnest2) {
base_names <-
df_data %>% remove_duplicate_columns() %>% dplyr::select(-dplyr::matches("data")) %>% names()
df_data_names <-
names(df_data)[names(df_data) %>% str_detect('data')]
for (x in seq_along(df_data_names)) {
df_data_name <-
df_data_names[[x]]
table <-
df_data %>%
select(one_of(c(base_names, df_data_name))) %>%
remove_duplicate_columns()
is_null_col <-
table[,df_data_name] %>% magrittr::extract2(1) %>% map_lgl(is_null)
table <-
table %>%
mutate(is_null_col) %>%
filter(!is_null_col) %>%
unnest() %>%
remove_duplicate_columns() %>%
select(which(colMeans(is.na(.)) < 1)) %>%
select(-dplyr::matches('is_null_col')) %>%
distinct()
df_table_name <-
list(df_name, df_data_name %>% str_replace_all('data', '')) %>% purrr::reduce(paste0)
assign(x = df_table_name,
eval(table),
envir = .GlobalEnv)
}
} else {
has_unnest <-
df_data %>% names() %>% str_detect('data') %>% sum(na.rm = TRUE) > 0
if (has_unnest) {
if (df_name %>% str_detect("General")) {
table <-
df_data %>%
remove_duplicate_columns() %>%
select(-dplyr::matches("data")) %>%
select(which(colMeans(is.na(.)) < 1)) %>%
distinct()
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
}
if (df_name %in% 'dataFilerTextFilings') {
table <-
df_data %>%
unnest() %>%
select(which(colMeans(is.na(.)) < 1)) %>%
tidy_column_formats() %>%
distinct()
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
}
if (df_name %in% 'dataFilerFilingDirectories') {
table <-
df_data %>%
select(-dplyr::matches('data')) %>%
filter(!idCIK %>% is.na()) %>%
select(which(colMeans(is.na(.)) < 1)) %>%
distinct()
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
}
other <-
(!df_name %>% str_detect("General")) & (!df_name %in% c('dataFilerFilingDirectories', 'dataFilerTextFilings'))
if (other) {
df_data <-
df_data %>%
remove_duplicate_columns() %>%
unnest()
select_cols <-
tibble(nameData = names(df_data)) %>%
mutate(idColumn = 1:n()) %>%
group_by(nameData) %>%
mutate(countColumn = 1:n()) %>%
ungroup() %>%
filter(countColumn == min(countColumn)) %>%
.$idColumn
df_data <-
df_data[, select_cols]
table <-
df_data %>%
select(which(colMeans(is.na(.)) < 1)) %>%
distinct()
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
}
} else {
table <-
df_data %>%
select(which(colMeans(is.na(.)) < 1)) %>%
distinct()
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
}
}
})
}
return(all_data)
}
.parse_json_general_insider <-
function(cik = 1354879,
nest_data = TRUE,
return_message = TRUE) {
url <-
list('http://rankandfiled.com/data/insider/', cik, '/general') %>%
purrr::invoke(paste0, .)
if (!url %>% httr::url_ok()) {
return(tibble())
}
data <-
url %>%
jsonlite::fromJSON() %>%
.[['insider']]
general_cols <-
data %>% future_map_dfr(class) %>%
gather(item, value) %>%
filter(!value %>% str_detect(c('list', 'data.frame'))) %>%
.$item %>%
suppressWarnings()
general_df <-
data %>%
data.frame(stringsAsFactors = FALSE) %>%
dplyr::select(one_of(general_cols)) %>%
.resolve_name_df() %>%
distinct()
has_filer <-
'filer' %in% names(data)
if (has_filer) {
filing_df <-
data$filer %>%
flatten_df() %>%
.resolve_name_df()
if ('name' %in% names(filing_df)) {
filing_df <-
filing_df %>%
select(-name)
}
if ('detailsOwnedBy' %in% names(filing_df)) {
filing_df <-
filing_df %>%
dplyr::rename(detailsOwns = detailsOwnedBy)
}
if ('detailsOwns' %in% names(filing_df)) {
detail_df <-
seq_along(filing_df$detailsOwns) %>%
future_map_dfr(function(x) {
detail_value <-
filing_df$detailsOwns[[x]]
if (detail_value %>% is.na()) {
df <-
tibble(idRow = x, nameCompanyOwns = NA)
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataInsiderCompanies)
}
return(df)
}
values <-
detail_value %>% str_replace('\\|', '') %>%
str_split('\\|') %>%
flatten_chr()
df_data <-
tibble(value = values) %>%
tidyr::separate(value,
into = c('idTickerOwns', 'other'),
sep = '\\:') %>%
tidyr::separate(other,
into = c('nameCompanyOwns', 'other'),
sep = '\\_') %>%
tidyr::separate(other,
into = c('roleOwner', 'dateOwner'),
sep = '\\
mutate(nameCompanyOwns = nameCompanyOwns %>% str_to_upper(),
idRow = x) %>%
gather(item, value, -idRow, na.rm = TRUE) %>%
group_by(item) %>%
mutate(count = 1:n() - 1) %>%
ungroup() %>%
arrange((count)) %>%
mutate(item = ifelse(count == 0, item, paste0(item, count))) %>%
select(-count)
column_order <-
c('idRow', df_data$item)
df_data <-
df_data %>%
spread(item, value) %>%
select(one_of(column_order))
if (nest_data) {
df_data <-
df_data %>%
nest(-idRow, .key = dataInsiderCompanies)
}
return(df_data)
}) %>%
suppressWarnings()
detail_df <-
detail_df %>%
mutate_at(.vars = detail_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% ymd())) %>%
suppressWarnings()
filing_df <-
filing_df %>%
mutate(idRow = 1:n()) %>%
select(-detailsOwns) %>%
left_join(detail_df) %>%
select(-idRow) %>%
suppressMessages()
}
general_df <-
general_df %>%
left_join(filing_df) %>%
suppressMessages()
}
has_companies <-
'companies' %in% names(data)
if (has_companies) {
companies_df <-
data$companies %>%
as_tibble() %>%
.resolve_name_df()
company_name_df <-
companies_df %>%
select(-dplyr::matches("status_history")) %>%
gather(item, value, -c(idCIK, nameFiler)) %>%
group_by(item) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup() %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
select(-countItem) %>%
suppressWarnings() %>%
suppressMessages()
col_order <-
c('idCIK', 'nameFiler', company_name_df$item)
company_name_df <-
company_name_df %>%
spread(item, value) %>%
select(one_of(col_order))
company_name_df <-
company_name_df %>%
mutate_at(company_name_df %>% select(dplyr::matches("idCIK")) %>% names(),
funs(. %>% as.numeric()))
companies_df <-
companies_df %>%
mutate(idRow = 1:n())
if ('status_history' %in% names(companies_df)) {
status_df <-
seq_along(companies_df$status_history) %>%
future_map_dfr(function(x) {
df <-
companies_df$status_history[[x]] %>%
as_tibble() %>%
mutate(idRow = x) %>%
select(-dplyr::matches("other|pair_id")) %>%
gather(item, value, -idRow) %>%
left_join(tibble(
item = c('date', 'officer', 'title', 'ten_percent', 'director'),
nameItem = c(
'dateAppointment',
'isOfficer',
'titleOfficer',
'is10PercentOwner',
'isDirector'
)
)) %>%
select(-item) %>%
group_by(nameItem) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup() %>%
mutate(item = ifelse(countItem == 0, nameItem, nameItem %>% paste0(countItem))) %>%
select(idRow, item, value) %>%
spread(item, value) %>%
suppressMessages() %>%
suppressWarnings()
return(df)
})
status_df <-
status_df %>%
mutate_at(status_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% lubridate::ymd())) %>%
mutate_at(status_df %>% select(dplyr::matches("is")) %>% names(),
funs(. %>% as.logical())) %>%
mutate_at(status_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% as.character()))
companies_df <-
companies_df %>%
select(-dplyr::matches("status")) %>%
left_join(status_df) %>%
suppressWarnings() %>%
suppressMessages() %>%
gather(item, value, -c(idCIK, nameFiler, idRow)) %>%
group_by(item, idRow) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup() %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
select(-countItem) %>%
suppressWarnings()
col_order <-
c('idCIK', 'nameFiler', companies_df$item)
companies_df <-
companies_df %>%
spread(item, value) %>%
select(one_of(col_order)) %>%
suppressWarnings()
companies_df <-
companies_df %>%
mutate_at(status_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% lubridate::ymd())) %>%
mutate_at(status_df %>% select(dplyr::matches("^is|^has")) %>% names(),
funs(. %>% as.logical()))
} else {
companies_df <-
company_name_df
}
if (nest_data) {
companies_df <-
companies_df %>%
mutate(idRow = 1:n()) %>%
nest(-c(idRow, idCIK), .key = dataDetailsCompaniesOwned) %>%
as_tibble()
}
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
left_join(companies_df) %>%
select(-idRow) %>%
suppressMessages()
}
general_df <-
general_df %>%
mutate(urlJSONGeneral = url)
if ('typeCompany' %in% names(general_df)) {
general_df <-
general_df %>%
dplyr::rename(typeFiler = typeCompany)
}
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(general_df)
}
.parse_insider_trade_json_url <-
function(url = "http://rankandfiled.com/data/insider/1070844/trades?start=0",
return_message = TRUE) {
if (!url %>% httr::url_ok()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/insider/|/trades', '') %>%
str_split('\\?') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
trade_df <-
json_data$trades %>%
as_tibble() %>%
dplyr::rename(dateTrade = date) %>%
mutate(dateTrade = dateTrade %>% lubridate::ymd())
count_columns <-
trade_df$trade %>%
map_dbl(function(x) {
x %>%
str_count('\\*')
}) %>%
max() + 1
column_names <-
list("X", 1:count_columns) %>%
purrr::invoke(paste0, .)
trade_df <-
trade_df %>%
separate(trade, column_names, sep = '\\*') %>%
suppressWarnings()
trade_df_names <-
c(
'dateTrade',
"idCIK",
"idCIKOwns",
"idInsiderType",
"countSharesOwned",
"descriptionOption",
"idTypeInsiderTransaction",
"amountPrice",
"countShares",
"idInsiderTransaction",
"X10",
"detailOwnershipIndirect",
"priceExcercised",
"dateOptionExcercisable",
"dateOptionExpiry",
"countSharesOptions",
"typeSecurityOption",
"X17"
)
trade_df <-
trade_df %>%
purrr::set_names((trade_df_names)[1:ncol(trade_df)]) %>%
select(-dplyr::matches("X"))
trade_df <-
trade_df %>%
mutate_at(.vars =
trade_df %>% select(dplyr::matches("date")) %>% names(),
.funs = lubridate::ymd) %>%
mutate_at(.vars =
trade_df %>% select(dplyr::matches("idCIK|count|amount|price")) %>% names(),
funs(. %>% as.character() %>% readr::parse_number())) %>%
left_join(tibble(
idInsiderType = c("D", "ND"),
typeInsider = c("Director", "Non-Director")
)) %>%
left_join(get_insider_code_df()) %>%
left_join(
tibble(
idTypeInsiderTransaction = c("A", "D", "None"),
typeInsiderTransaction = c('Purchase', 'Sale', 'None'),
isBought = c(TRUE, FALSE, NA)
)
) %>%
suppressMessages() %>%
suppressWarnings()
trade_df <-
trade_df %>%
mutate(
countShares = ifelse(isBought == T, countShares, -countShares),
amountTransaction = countShares * amountPrice,
urlJSON = url
)
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(trade_df)
}
.parse_insider_trades <-
function(cik = 1070844,
nest_data = TRUE,
return_message = TRUE) {
url_general <-
list('http://rankandfiled.com/data/insider/', cik, '/general') %>%
purrr::invoke(paste0, .)
general_df <-
.parse_json_general_insider(cik = cik,
nest_data = nest_data,
return_message = TRUE)
cik <-
general_df$idCIK
insider <-
general_df$nameEntity %>%
str_to_upper()
count_trades <-
general_df$countTrades %/% 50
trade_urls <-
list(
'http://rankandfiled.com/data/insider/',
cik,
'/trades?start=',
seq(0, by = 50, length.out = count_trades)
) %>%
purrr::invoke(paste0, .)
parse_insider_trade_json_url_safe <-
purrr::possibly(.parse_insider_trade_json_url, tibble())
all_data <-
trade_urls %>%
future_map_dfr(function(x) {
.parse_insider_trade_json_url(url = x, return_message = return_message)
}) %>%
distinct()
ciks_owned <-
all_data$idCIKOwns %>% unique()
company_urls_general <-
list('http://rankandfiled.com/data/filer/',
ciks_owned,
'/general') %>%
purrr::invoke(paste0, .)
owned_company_df <-
company_urls_general %>%
future_map_dfr(function(x) {
.parse_json_general_filing(url = x,
return_message = TRUE,
nest_data = nest_data)
})
owned_df <-
owned_company_df %>%
select(dplyr::matches('idCIK|nameEntity|idTicker')) %>%
select(-dplyr::matches("idCIKOwnedBy"))
names(owned_df) <-
names(owned_df) %>% paste0('Owns')
all_data <-
all_data %>%
mutate(nameInsider = insider) %>%
left_join(owned_df) %>%
select(
dateTrade,
nameInsider,
idCIK,
nameEntityOwns,
dplyr::matches('idCIKOwns|idTickerOwns'),
everything()
) %>%
suppressWarnings() %>%
suppressMessages()
all_data <-
all_data %>%
mutate_at(.vars = all_data %>% select(dplyr::matches("amount|price")) %>% names(),
funs(. %>% formattable::currency(digits = 2))) %>%
mutate_at(.vars = all_data %>% select(dplyr::matches("count")) %>% names(),
funs(. %>% formattable::comma(digits = 0))) %>%
mutate_if(is.numeric, as.numeric)
if (return_message) {
list(
"Parsed ",
all_data %>% nrow() %>% formattable::comma(digits = 0),
' insider transactions for ',
insider
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(all_data)
}
.parse_insider_filings <-
function(cik = 1070844,
nest_data = TRUE,
return_message = TRUE) {
general_df <-
.parse_json_general_insider(cik = cik,
nest_data = nest_data,
return_messag = TRUE)
cik <-
general_df$idCIK
insider <-
general_df$nameEntity %>%
str_to_upper()
count_filings <-
general_df$countFilings %/% 50
filing_urls <-
list(
'http://rankandfiled.com/data/filer/',
cik,
'/all?start=',
seq(0, by = 50, length.out = count_filings)
) %>%
purrr::invoke(paste0, .)
.parse_json_public_filers_safe <-
purrr::possibly(.parse_json_public_filers, NULL)
.all_filings <-
filing_urls %>%
future_map_dfr(function(x) {
.parse_json_public_filers_safe(url = x, return_message = return_message)
}) %>%
distinct() %>%
suppressWarnings() %>%
mutate(nameInsider = insider) %>%
select(idCIK, nameInsider, everything())
if (return_message) {
list("Parsed ", .all_filings %>% nrow(), ' SEC Filings for ', insider) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(.all_filings)
}
.generate_fund_general_url <-
function(cik = 1034621) {
glue("http://rankandfiled.com/data/fund/{cik}/general") %>% as.character()
}
.parse_json_fund_general <-
function(cik = 1034621,
return_message = TRUE) {
url <-
cik %>%
.generate_fund_general_url()
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
general_cols <-
json_data %>% future_map_dfr(class) %>%
gather(item, value) %>%
filter(!value %in% (c('list', 'data.frame'))) %>%
.$item %>%
suppressWarnings()
general_df <-
json_data %>%
data.frame(stringsAsFactors = FALSE) %>%
dplyr::select(one_of(general_cols)) %>%
.resolve_name_df() %>%
distinct() %>%
select(-dplyr::matches("descriptionClasses"))
has_funds <-
'funds' %in% names(json_data)
if (has_funds) {
general_df <-
general_df %>%
left_join(json_data$funds %>%
.resolve_name_df() %>%
mutate(idCIK = cik)) %>%
suppressMessages()
}
has_filer <-
'filer' %in% names(json_data)
if (has_filer) {
filer_df <-
json_data$filer %>%
as_tibble()
filer_df <-
filer_df %>%
.resolve_name_df()
if (!'idCIK' %in% names(filer_df)) {
filer_df <-
filer_df %>%
mutate(idCIK = cik)
}
if ('name' %in% names(filer_df)) {
filer_df <-
filer_df %>%
mutate(nameEntity = nameEntity %>% stringr::str_to_upper()) %>%
select(-name)
}
filer_df <-
filer_df %>%
mutate_at(filer_df %>% select(dplyr::matches("idRF|idCIK")) %>% names(),
funs(. %>% as.numeric()))
merge_cols <-
c('idCIKFiler', 'idRow', names(filer_df)[!names(filer_df) %in% names(general_df)])
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
left_join(
filer_df %>%
mutate(idRow = 1:n()) %>%
dplyr::rename(idCIKFiler = idCIK) %>%
select(one_of(merge_cols))
) %>%
select(-dplyr::matches("^object|idRow")) %>%
distinct() %>%
suppressMessages()
}
general_df <-
general_df %>%
select(idCIK,
nameEntity,
dplyr::matches("name"),
dplyr::matches("id"),
everything())
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(general_df)
}
.parse_for_tables_rf <-
function(filing_df,
parse_complete_text_filings = TRUE,
parse_form_d = TRUE,
parse_13F = TRUE,
parse_small_offerings = TRUE,
parse_form_3_4s = TRUE,
parse_asset_files = TRUE,
parse_xbrl = TRUE,
nest_data = TRUE,
return_message = TRUE) {
all_tables <-
tibble()
parse_all_filings <-
c(
parse_complete_text_filings,
parse_form_d,
parse_13F,
parse_small_offerings,
parse_form_3_4s,
parse_asset_files,
parse_xbrl
) %>%
sum() > 0
parse_form_data_safe <-
purrr::possibly(.parse_form_data, tibble())
if (parse_all_filings) {
if (!'typeFile' %in% names(filing_df)) {
filing_df <-
filing_df %>%
mutate(typeFile = ifelse(urlSECFilingDirectory %>% str_detect('htm'),
'html', NA))
}
search_df <-
filing_df %>%
select(dateFiling,
dplyr::matches("typeFile"),
dplyr::matches("idForm"),
urlSECFilingDirectory) %>%
distinct() %>%
filter(!urlSECFilingDirectory %>% is.na()) %>%
distinct()
df_all_filing_urls <-
search_df$urlSECFilingDirectory %>%
unique() %>%
future_map_dfr(function(x){
.parse_sec_filing_index(urls = x)
})
df_all_filing_urls <-
df_all_filing_urls %>%
mutate(isForm3_4 = ifelse(typeForm %in% c("3", "4") &
typeFile == "xml", TRUE, FALSE))
df_urls <-
df_all_filing_urls %>%
mutate(nameTable = 'Filing Directories') %>%
nest(-nameTable, .key = dataTable)
all_tables <-
all_tables %>%
bind_rows(df_urls)
if (parse_complete_text_filings) {
if (!'urlTextFilingFull' %in% names(df_all_filing_urls)) {
df_all_filing_urls <-
df_all_filing_urls %>%
mutate(urlTextFilingFull = urlSECFilingDirectory %>% str_replace_all("-index.htm", ".txt"))
}
urls <-
df_all_filing_urls$urlTextFilingFull %>%
unique()
sec_complete_filings_safe <-
purrr::possibly(.sec_complete_filings, tibble())
all_text_df <-
.sec_complete_filings(urls = urls)
all_tables <-
all_tables %>%
bind_rows(tibble(
nameTable = 'Text Filings',
dataTable = list(all_text_df %>% nest(-c(idCIK), .key = dataFilings))
))
}
if (parse_form_d) {
df_form_ds <-
df_all_filing_urls %>%
parse_form_data_safe(filter_parameter = 'isFormD')
all_tables <-
all_tables %>%
bind_rows(tibble(
nameTable = 'FormDs',
dataTable = list(df_form_ds)
))
}
if (parse_13F) {
df_13F <-
df_all_filing_urls %>%
parse_form_data_safe(filter_parameter = 'is13FFiling')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = '13Fs', dataTable = list(df_13F)))
}
if (parse_small_offerings) {
df_small_offerings <-
df_all_filing_urls %>%
parse_form_data_safe(filter_parameter = 'hasSmallOfferingData')
all_tables <-
all_tables %>%
bind_rows(tibble(
nameTable = 'Small Offerings',
dataTable = list(df_small_offerings)
))
}
if (parse_form_3_4s) {
df_form3_4 <-
df_all_filing_urls %>%
parse_form_data_safe(filter_parameter = 'isForm3_4')
all_tables <-
all_tables %>%
bind_rows(tibble(
nameTable = 'Form 3 and 4',
dataTable = list(df_form3_4)
))
}
if (parse_asset_files) {
df_assets <-
df_all_filing_urls %>%
parse_form_data_safe(filter_parameter = 'hasAssetFile')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Asset Data', dataTable = list(df_assets)))
}
if (parse_xbrl) {
df_xbrl <-
df_all_filing_urls %>%
parse_form_data_safe(filter_parameter = 'isXBRLInstanceFile')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'XBRL', dataTable = list(df_xbrl)))
}
}
all_tables <-
all_tables %>%
mutate(countCols = dataTable %>% map_dbl(ncol)) %>%
filter(countCols > 0) %>%
select(-countCols)
return(all_tables)
}
.get_most_recent_rf_id <-
function(url = "http://rankandfiled.com/data/latest") {
json_data <-
url %>%
jsonlite::fromJSON()
json_data$filings$id %>% as.numeric() %>% max()
}
.parse_filing_stream <-
function(url = "http://rankandfiled.com/data/latest?group=ALL&filer=All",
nest_data = TRUE,
return_message = TRUE) {
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
filing_class_df <-
json_data$filings %>% future_map_dfr(class) %>%
gather(column, type) %>%
mutate(idName = 1:n())
general_df <-
json_data$filings %>%
select(filing_class_df %>%
filter(!type %in% c('list', 'data.frame')) %>%
.$idName)
general_df <-
general_df %>%
as_tibble() %>%
mutate_all(funs(. %>% str_replace('\\|', '')))
general_df <-
general_df %>%
.resolve_name_df() %>%
distinct()
general_df <-
general_df %>%
mutate_at(general_df %>% select(dplyr::matches("^datetime[A-Z]")) %>% names(),
funs(. %>% lubridate::ymd_hms())) %>%
mutate_at(general_df %>% select(dplyr::matches("dateFiled")) %>% names(),
funs(. %>% lubridate::ymd())) %>%
mutate_at(general_df %>% select(dplyr::matches("idRF|idCIK")) %>% names(),
funs(. %>% as.numeric())) %>%
mutate_at(general_df %>% select(dplyr::matches("^is|^has")) %>% names(),
funs(. %>% as.logical())) %>%
mutate_at(general_df %>% select(dplyr::matches("^description|^type")) %>% names(),
funs(. %>% stringr::str_to_upper())) %>%
mutate(urlSEC = ifelse(
slugSEC == "None",
NA,
list(
"https://www.sec.gov/Archives/edgar/data/",
idCIK,
'/',
slugSEC
) %>% purrr::invoke(paste0, .)
))
if ('idFormType' %in% names(general_df)) {
general_df %>%
left_join(dictionary_sec_filing_codes()) %>%
suppressMessages()
}
has_filer <-
'filer' %in% names(json_data$filings)
if (has_filer) {
filer_df <-
json_data$filings$filer %>%
as_tibble()
filer_df <-
filer_df %>%
.resolve_name_df()
if ('name' %in% names(filer_df)) {
filer_df <-
filer_df %>%
dplyr::rename(nameLegal = name) %>%
mutate(nameEntity = nameEntity %>% stringr::str_to_upper())
}
filer_df <-
filer_df %>%
mutate_at(filer_df %>% select(dplyr::matches("idRF|idCIK")) %>% names(),
funs(. %>% as.numeric())) %>%
mutate_at(filer_df %>% select(dplyr::matches("^name|^industry|^typeFund|^details")) %>% names(),
funs(. %>% stringr::str_to_upper()))
if ('detailsOwnedBy' %in% names(filer_df)) {
filer_df <-
filer_df %>%
dplyr::rename(detailsOwns = detailsOwnedBy)
filer_df <-
filer_df %>%
mutate(idRow = 1:n(),
detailsOwns = detailsOwns %>% str_replace("\\|", ''))
owns_df <-
1:nrow(filer_df) %>%
future_map_dfr(function(x) {
owns <-
filer_df$detailsOwns[[x]] %>%
str_split("\\|") %>%
flatten_chr()
df <-
tibble(idRow = x, owns) %>%
tidyr::separate(owns,
into = c('idTickerOwns', 'owns'),
sep = '\\:') %>%
tidyr::separate(owns,
into = c('nameCompanyOwns', 'owns'),
sep = '\\_') %>%
tidyr::separate(
owns,
into = c('typeOwnerOwns', 'dateOwnershipOwns'),
sep = '\\
) %>%
mutate(countItem = 1:n() - 1) %>%
mutate(
nameCompanyOwns = nameCompanyOwns %>% str_to_upper(),
idTickerOwns = idTickerOwns %>% str_to_upper()
) %>%
gather(item, value, -c(idRow, countItem)) %>%
mutate(value = ifelse(value == '', NA, value)) %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
arrange(countItem) %>%
select(-countItem)
col_order <-
c('idRow', df$item)
df <-
df %>%
spread(item, value) %>%
select(one_of(col_order))
df <-
df %>%
mutate_at(df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% lubridate::ymd()))
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataCompaniesOwns)
}
return(df)
}) %>%
suppressWarnings()
filer_df <-
filer_df %>%
left_join(owns_df) %>%
select(-idRow) %>%
suppressMessages()
}
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
left_join(
filer_df %>%
mutate(idRow = 1:n()) %>%
dplyr::rename(idCIKFiler = idCIK) %>%
select(one_of(
c('idCIKFiler', 'idRow'), names(filer_df)[!names(filer_df) %in% names(general_df)]
))
) %>%
select(-dplyr::matches("^object|idRow")) %>%
distinct() %>%
suppressMessages()
}
has_offerings <-
'offerings' %in% names(json_data$filings)
if (has_offerings) {
general_df <-
general_df %>%
mutate(idRow = 1:n())
offering_df <-
1:nrow(general_df) %>%
future_map_dfr(function(x) {
offering <-
json_data$filings$offerings[[x]]
has_no_data <-
length(offering) == 0
if (has_no_data) {
return(tibble(idRow = x))
}
has_no_rows <-
offering %>% nrow() == 0
if (has_no_rows) {
return(tibble(idRow = x))
}
offering_long <-
offering %>% .resolve_name_df() %>%
mutate(idRow = x) %>%
gather(item, value, -idRow) %>%
group_by(item) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup() %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
arrange(countItem) %>%
select(-countItem)
col_order <-
offering_long$item
offering <-
offering_long %>%
spread(item, value) %>%
select(one_of(c('idRow', col_order)))
offering <-
offering %>%
mutate_at(offering %>% select(dplyr::matches("^count[A-Z]|^amount")) %>% names(),
funs(. %>% as.numeric())) %>%
mutate_at(offering %>% select(dplyr::matches("^date")) %>% names(),
funs(. %>% lubridate::ymd()))
if (nest_data) {
offering <-
offering %>%
nest(-idRow, .key = dataOfferings)
}
return(offering)
}) %>%
select(idRow, everything())
offering_df <-
offering_df %>%
mutate_at(dplyr::matches("^nameIndustry"),
funs(. %>% str_to_upper()))
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
select(-dplyr::matches("nameIndustry")) %>%
left_join(offering_df) %>%
select(-idRow) %>%
suppressWarnings() %>%
suppressMessages()
if ('nameIndustry' %in% names(general_df)) {
general_df <-
general_df %>%
dplyr::rename(nameIndustryOffering = nameIndustry)
}
}
has_trades <-
'trades' %in% names(json_data$filings)
if (has_trades) {
general_df <-
general_df %>%
mutate(idRow = 1:n())
trade_df <-
1:nrow(general_df) %>%
future_map_dfr(function(x) {
trades <-
json_data$filings$trades[[x]]
has_no_data <-
length(trades) == 0
if (has_no_data) {
return(tibble(idRow = x))
}
has_no_rows <-
trades %>% nrow() == 0
if (has_no_rows) {
return(tibble(idRow = x))
}
trades <-
trades %>% .resolve_name_df() %>%
mutate(idRow = x) %>%
dplyr::rename(idInsiderTransaction = codeTransaction)
trades <-
trades %>%
mutate_at(.vars = trades %>% select(dplyr::matches("amount|count")) %>% names,
funs(. %>% as.numeric())) %>%
left_join(get_insider_code_df()) %>%
suppressWarnings() %>%
suppressMessages()
if ('amountPrice' %in% names(trades)) {
if (!'isBought' %in% names(trades)) {
trades <-
trades %>%
mutate(isBought = FALSE)
}
trades <-
trades %>%
mutate(
isBought = ifelse(isBought %>% is.na(), FALSE, TRUE),
countShares = ifelse(isBought == T, countShares, -countShares),
amountTransaction = countShares * amountPrice
)
}
trades_long <-
trades %>%
gather(item, value, -idRow) %>%
group_by(item) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
arrange(countItem) %>%
select(-countItem)
col_order <-
trades_long$item
trades <-
trades_long %>%
spread(item, value) %>%
select(one_of(c('idRow', col_order)))
trades <-
trades %>%
mutate_at(trades %>% select(dplyr::matches("^count[A-Z]|^amount")) %>% names(),
funs(. %>% as.numeric())) %>%
mutate_at(trades %>% select(dplyr::matches("^date")) %>% names(),
funs(. %>% lubridate::ymd()))
if (nest_data) {
trades <-
trades %>%
nest(-idRow, .key = dataTrades)
}
return(trades)
}) %>%
select(idRow, everything())
names(trade_df)[names(trade_df) %>% str_detect('dateFiling')] <-
trade_df %>% select(dplyr::matches("dateFiling")) %>% names() %>%
str_replace_all("dateFiling", 'dateFilingInsider')
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
select(-dplyr::matches("nameIndustry")) %>%
left_join(trade_df %>% select(-dplyr::matches("idTicker")), by = 'idRow') %>%
select(-idRow) %>%
suppressWarnings() %>%
suppressMessages()
}
general_df <-
general_df %>%
mutate_at(.vars = general_df %>% select(dplyr::matches("nameEntity")) %>% names(),
funs(. %>% str_to_upper())) %>%
suppressWarnings() %>%
ungroup() %>%
select(-dplyr::matches("^object[A-Z]|^slug|dateiso")) %>%
select(idCIK,
nameEntity,
dplyr::matches("name"),
dplyr::matches("id"),
everything())
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
general_df
}
.sec_filing_stream <-
function(filers = 'All',
filing_name = 'Registrations',
nest_data = TRUE,
return_message = TRUE) {
both_all <-
filers == 'All' & filing_name == 'All'
if (both_all) {
rf_id <-
.get_most_recent_rf_id()
start <-
rf_id - 3500
rf_ds <-
seq(start, rf_id, by = 30)
urls <-
list('http://rankandfiled.com/data/latest?id=',
rf_ds) %>%
purrr::invoke(paste0, .)
parse_filing_stream_safe <-
purrr::possibly(.parse_filing_stream, tibble())
data <-
urls %>%
future_map_dfr(function(x) {
parse_filing_stream_safe(url = x, nest_data = nest_data)
}) %>%
distinct() %>%
select(
idRF,
idCIK,
dplyr::matches("nameEntity"),
dplyr::matches("idTicker"),
dplyr::matches("dateFiled"),
dplyr::matches("datetimeFiled"),
dplyr::matches("^name"),
dplyr::matches("^date"),
dplyr::matches("^id"),
dplyr::matches("^type"),
dplyr::matches("^description"),
everything()
) %>%
mutate(
urlRankAndFiled = list('http://rankandfiled.com/
purrr::invoke(paste0, .)
)
} else {
filer_names <-
c('All',
'Corporate Insider',
'Companies',
'Investment Company') %>%
str_to_upper()
filing_names <-
c(
'Annual Reports',
'Quarterly Reports',
'Current Reports',
'Other Reports',
'Registrations',
'Private Offerings',
'Ownership',
'Prospectuses',
'Exemptions',
'Withdrawals',
'Correspondence',
'Proxy Statements',
'Confidential',
'All'
) %>% str_to_upper()
no_filers <-
!filers %>% str_to_upper() %in% filer_names
if (no_filers) {
stop(
list(
"Filers can only be:\n",
filer_names %>% stringr::str_to_title() %>% paste0(collapse = '\n')
) %>%
purrr::invoke(paste0, .)
)
}
no_filing_names <-
!filing_name %>% str_to_upper() %in% filing_names
if (no_filing_names) {
stop(
list(
"Filing names can only be:\n",
filing_names %>% stringr::str_to_title() %>% paste0(collapse = '\n')
) %>%
purrr::invoke(paste0, .)
)
}
.filer_type_df <-
tibble(
codeFiler = c('All', 'insider', 'company', 'inv_co'),
nameFiler = filer_names
)
slug_filer <-
.filer_type_df %>%
filter(nameFiler == filers %>% str_to_upper()) %>%
.$codeFiler
filing_name_df <-
tibble(
codeFiling = c(
"A",
"Q",
"CR",
"R",
"REG",
"REGX",
"O",
"P",
"X",
"W",
"SEC",
"PROXY",
"CT",
"ALL"
),
nameFiling = filing_names
)
slug_type <-
filing_name_df %>%
filter(nameFiling == filing_name %>% str_to_upper()) %>%
.$codeFiling
mr_id <-
.get_most_recent_rf_id()
url_json <-
list(
'http://rankandfiled.com/data/latest?id=',
mr_id,
'&group=',
slug_type,
'&filer=',
slug_filer
) %>%
purrr::invoke(paste0, .)
data <-
url_json %>%
.parse_filing_stream() %>%
select(
idRF,
idCIK,
dplyr::matches("nameEntity"),
dplyr::matches("idTicker"),
dplyr::matches("dateFiled"),
dplyr::matches("datetimeFiled"),
dplyr::matches("^name"),
dplyr::matches("^date"),
dplyr::matches("^id"),
dplyr::matches("^type"),
dplyr::matches("^description"),
everything()
) %>%
mutate(
urlRankAndFiled = list('http://rankandfiled.com/
purrr::invoke(paste0, .)
)
}
if (return_message) {
list("\nParsed Most Recent filings for ",
filers,
' Filers\n',
filing_name,
' Form Type\n') %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(data)
}
sec_filing_streams_rf <-
function(filers = c('All', 'Corporate Insider', 'Companies', 'Investment Company'),
filing_names = c(
'All',
'Annual Reports',
'Quarterly Reports',
'Current Reports',
'Other Reports',
'Registrations',
'Private Offerings',
'Ownership',
'Prospectuses',
'Exemptions',
'Withdrawals',
'Correspondence',
'Proxy Statements',
'Confidential'
),
nest_data = TRUE,
return_message = TRUE) {
type_df <-
expand.grid(
nameFiler = filers,
nameFiling = filing_names,
stringsAsFactors = FALSE
) %>%
as_tibble()
sec_filing_stream_safe <-
purrr::possibly(.sec_filing_stream, NULL)
all_data <-
1:nrow(type_df) %>%
future_map_dfr(function(x) {
sec_filing_stream_safe(
filers = type_df$nameFiler[[x]],
filing_name = type_df$nameFiling[[x]],
nest_data = nest_data,
return_message = return_message
)
}) %>%
distinct() %>%
mutate(idRow = 1:n()) %>%
group_by(idRF) %>%
filter(idRow == min(idRow)) %>%
ungroup() %>%
select(-idRow)
all_data <-
all_data %>%
select(-dplyr::matches("dateiso")) %>%
mutate_at(all_data %>% select(dplyr::matches("^name|^description|^industry|^typeEntity")) %>% names(),
funs(. %>% stringr::str_to_upper()))
return(all_data)
}
.generate_ticker_general_url <-
function(ticker = "FB") {
glue("http://rankandfiled.com/data/company/{ticker}/general") %>% as.character()
}
.parse_json_public_general <-
function(url = "http://rankandfiled.com/data/company/BX/general",
nest_data = TRUE,
return_message = TRUE) {
if (!url %>% httr::url_ok()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
ticker <-
url %>% str_replace("http://rankandfiled.com/data/company/", '') %>%
str_split('\\/') %>% flatten_chr() %>%
.[[1]]
general_class_df <-
json_data %>% future_map_dfr(class) %>%
gather(column, type) %>%
mutate(idName = 1:n())
general_df <-
json_data[general_class_df %>%
filter(!type %in% c('list', 'data.frame')) %>%
.$idName] %>%
flatten_df() %>%
.resolve_name_df() %>%
select(-dplyr::matches("idTicker")) %>%
mutate(idTicker = ticker)
has_market <-
'market' %in% names(json_data)
if (has_market) {
general_df <-
general_df %>%
bind_cols(json_data$market %>%
flatten_df() %>%
.resolve_name_df() %>%
select(-dplyr::matches("codeExchange")))
if ('amountEquityMarketCap' %in% names(general_df)) {
general_df <-
general_df %>%
mutate(amountEquityMarketCap = amountEquityMarketCap %>% formattable::currency(digits = 0))
}
if ('nameIndustry' %in% names(general_df)) {
has_semi <-
general_df$nameIndustry %>% str_detect('\\:')
if (has_semi) {
general_df <-
general_df %>%
tidyr::separate(
nameIndustry,
into = c('nameIndustry', 'nameSubIndustry'),
sep = '\\: '
) %>%
suppressWarnings()
}
}
general_df <-
general_df %>%
mutate_if(is_character,
str_to_upper)
}
has_snap_shot <-
'snapshot' %in% names(json_data)
if (has_snap_shot) {
snap_shot_df <-
json_data$snapshot %>%
as_tibble()
if ('ebitda' %in% names(snap_shot_df)) {
snap_shot_df <-
snap_shot_df %>%
mutate(digitEBITDA = ebitda %>% substr(
start = (ebitda %>% nchar()) ,
stop = ebitda %>% nchar()
))
}
snap_shot_df <-
snap_shot_df %>%
.resolve_name_df() %>%
select(-dplyr::matches("amountEquityMarketCap"))
if ('digitEBITDA' %in% names(snap_shot_df)) {
snap_shot_df <-
snap_shot_df %>%
mutate(
amountEBITDA = ifelse(
digitEBITDA == "B",
amountEBITDA * 1000000000,
amountEBITDA * 1000000
)
) %>%
select(-digitEBITDA)
}
snap_shot_df <-
snap_shot_df %>%
mutate_at(.vars = snap_shot_df %>% select(dplyr::matches("price|amount")) %>% names,
funs(. %>% currency(digits = 2))) %>%
mutate_at(.vars = snap_shot_df %>% select(dplyr::matches("amountEBITDA")) %>% names,
funs(. %>% currency(digits = 0)))
general_df <-
general_df %>%
bind_cols(snap_shot_df)
}
has_filer <-
((
'filer' %in% names(json_data) &
json_data$filer %>% as_tibble() %>% ncol > 2
))
if (has_filer) {
filer_df <-
json_data$filer %>%
as_tibble()
filer_df <-
filer_df %>%
.resolve_name_df()
if ('detailsOwnedBy' %in% names(filer_df)) {
filer_df <-
filer_df %>%
dplyr::rename(detailsOwns = detailsOwnedBy)
filer_df <-
filer_df %>%
mutate(idRow = 1:n(),
detailsOwns = detailsOwns %>% str_replace("\\|", ''))
owns_df <-
1:nrow(filer_df) %>%
future_map_dfr(function(x) {
owns <-
filer_df$detailsOwns[[x]] %>%
str_split("\\|") %>%
flatten_chr()
df <-
tibble(idRow = x, owns) %>%
tidyr::separate(owns,
into = c('idTickerOwns', 'owns'),
sep = '\\:') %>%
tidyr::separate(owns,
into = c('nameCompanyOwns', 'owns'),
sep = '\\_') %>%
tidyr::separate(
owns,
into = c('typeOwnerOwns', 'dateOwnershipOwns'),
sep = '\\
) %>%
mutate(countItem = 1:n() - 1) %>%
mutate(
nameCompanyOwns = nameCompanyOwns %>% str_to_upper(),
idTickerOwns = idTickerOwns %>% str_to_upper()
) %>%
gather(item, value, -c(idRow, countItem)) %>%
mutate(value = ifelse(value == '', NA, value)) %>%
mutate(item = ifelse(countItem == 0, item, item %>% paste0(countItem))) %>%
arrange(countItem) %>%
select(-countItem)
col_order <-
c('idRow', df$item)
df <-
df %>%
spread(item, value) %>%
select(one_of(col_order))
df <-
df %>%
mutate_at(df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% lubridate::ymd()))
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataCompaniesOwns)
}
return(df)
}) %>%
suppressWarnings()
filer_df <-
filer_df %>%
left_join(owns_df) %>%
select(-idRow) %>%
suppressMessages()
}
filer_df <-
filer_df %>%
mutate_at(filer_df %>% select(dplyr::matches("nameEntity")) %>% names(),
funs(. %>% stringr::str_to_upper())) %>%
select(
dplyr::matches("nameEntity"),
dplyr::matches("^id"),
dplyr::matches("industry"),
dplyr::matches("name"),
dplyr::matches("type"),
everything()
) %>%
select(-dplyr::matches("object"))
if ('addressStreet1Entity' %in% names(filer_df)) {
filer_df <-
filer_df %>%
mutate(
addressEntity = list(
addressStreet1Entity,
' ',
cityEntity,
' ',
stateEntity,
', ',
zipcodeEntity
) %>% purrr::invoke(paste0, .)
) %>%
select(nameEntity, addressEntity, everything())
}
filer_cols <-
names(filer_df)[!names(filer_df) %in% names(general_df)]
general_df <-
general_df %>%
bind_cols(filer_df %>% select(one_of(filer_cols))) %>%
select(idCIK, dplyr::matches("nameEntity"), everything()) %>%
select(-dplyr::matches("detailsOwns"))
}
if ('detailsOwns' %in% names(general_df)) {
detail_df <-
seq_along(general_df$detailsOwns) %>%
future_map_dfr(function(x) {
detail_value <-
general_df$detailsOwns[[x]]
if (detail_value %>% is.na()) {
df <-
tibble(idRow = x, nameCompanyOwns = NA)
if (nest_data) {
df <-
df %>%
nest(-idRow, .key = dataCompaniesOwns)
}
return(df)
}
values <-
detail_value %>% str_replace('\\|', '') %>%
str_split('\\|') %>%
flatten_chr()
df_data <-
tibble(value = values) %>%
tidyr::separate(value,
into = c('idTickerOwns', 'other'),
sep = '\\:') %>%
tidyr::separate(other,
into = c('nameCompanyOwns', 'other'),
sep = '\\_') %>%
tidyr::separate(other,
into = c('roleOwner', 'dateOwner'),
sep = '\\
mutate(nameCompanyOwns = nameCompanyOwns %>% str_to_upper(),
idRow = x) %>%
gather(item, value, -idRow, na.rm = TRUE) %>%
group_by(item) %>%
mutate(value = ifelse(value == '', NA, value),
count = 1:n() - 1) %>%
ungroup() %>%
arrange((count)) %>%
mutate(item = ifelse(count == 0, item, paste0(item, count))) %>%
select(-count)
column_order <-
c('idRow', df_data$item)
df_data <-
df_data %>%
spread(item, value) %>%
select(one_of(column_order))
if (nest_data) {
df_data <-
df_data %>%
nest(-idRow, .key = dataCompaniesOwns)
}
return(df_data)
}) %>%
suppressWarnings()
detail_df <-
detail_df %>%
mutate_at(.vars = detail_df %>% select(dplyr::matches("date")) %>% names(),
funs(. %>% ymd())) %>%
suppressWarnings()
general_df <-
general_df %>%
mutate(idRow = 1:n()) %>%
select(-detailsOwns) %>%
left_join(detail_df) %>%
select(-idRow) %>%
suppressMessages()
}
general_df <-
general_df %>%
mutate(
urlTickerRankandFiled = list('http://rankandfiled.com/
urlJSON = url
)
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(general_df)
}
.parse_company_general <-
function(ticker = "FB",
nest_data = TRUE,
return_message = TRUE) {
options(warn = -1)
data <-
.generate_ticker_general_url(ticker = ticker) %>%
.parse_json_public_general(nest_data = nest_data,
return_message = return_message)
if ('nameEntity' %in% names(data)) {
data <-
data %>%
mutate(nameCompany = nameEntity) %>%
select(idCIK, idTicker, nameEntity, nameCompany, everything()) %>%
select(-dplyr::matches("dateiso"))
} else {
df_name <-
list('http://rankandfiled.com/data/filer/',
data$idCIK,
'/general') %>%
purrr::invoke(paste0, .) %>%
.parse_json_general_filing()
entity <-
df_name$nameEntity
data <-
data %>%
mutate(nameEntity = entity,
nameCompany = nameEntity) %>%
select(idCIK, idTicker, nameEntity, nameCompany, everything()) %>%
select(-dplyr::matches("dateiso"))
}
data <-
data %>%
resolve_names_to_upper()
return(data)
}
.parse_company_general_safe <-
purrr::possibly(.parse_company_general, tibble())
.parse_json_trades <-
function(url = "http://rankandfiled.com/data/filer/1326801/trades?start=0",
return_message = TRUE) {
if (!url %>% httr::url_ok() %>% suppressWarnings()) {
return(tibble())
}
json_data <-
url %>%
jsonlite::fromJSON()
options(scipen = 9999)
cik <-
url %>% str_replace_all('http://rankandfiled.com/data/filer/|/trades', '') %>%
str_split('\\?') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
trade_df <-
json_data$trades %>%
as_tibble() %>%
dplyr::rename(dateTrade = date) %>%
mutate(dateTrade = dateTrade %>% lubridate::ymd())
trade_df <-
trade_df %>%
separate(
trade,
into = c(
"idCIKOwner",
"idCIK",
"idInsiderType",
"countSharesOwned",
"descriptionOption",
"idTypeInsiderTransaction",
"amountPrice",
"countShares",
"idInsiderTransaction",
"X10",
"detailOwnershipIndirect",
"priceExcercised",
"dateOptionExcercisable",
"dateOptionExpiry",
"countSharesOptions",
"typeSecurityOption",
"X17"
),
sep = '\\*'
) %>%
suppressWarnings() %>%
select(-dplyr::matches("X"))
trade_df <-
trade_df %>%
mutate_at(.vars =
trade_df %>% select(dplyr::matches("date")) %>% names(),
.funs = lubridate::ymd) %>%
mutate_at(.vars =
trade_df %>% select(dplyr::matches("idCIK|count|amount|price")) %>% names(),
funs(. %>% as.character() %>% readr::parse_number())) %>%
left_join(tibble(
idInsiderType = c("D", "ND"),
typeInsider = c("Director", "Non-Director")
)) %>%
left_join(get_insider_code_df()) %>%
left_join(
tibble(
idTypeInsiderTransaction = c("A", "D", "None"),
typeInsiderTransaction = c('Purchase', 'Sale', 'None'),
isBought = c(TRUE, FALSE, NA)
)
) %>%
suppressMessages()
trade_df <-
trade_df %>%
mutate(
countShares = ifelse(isBought == T, countShares, -countShares),
amountTransaction = countShares * amountPrice,
urlJSON = url
)
has_indirect_owner <-
trade_df$detailOwnershipIndirect %>% str_count("By") %>% sum() > 0
if (has_indirect_owner) {
trade_df <-
trade_df %>%
tidyr::separate(
detailOwnershipIndirect,
into = c('remove', "nameOwnerIndirect"),
remove = FALSE,
sep = 'By '
) %>%
mutate(nameOwnerIndirect = nameOwnerIndirect %>% str_trim() %>% str_to_upper()) %>%
select(-remove) %>%
suppressWarnings()
}
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(trade_df)
}
.parse_trades <-
function(ticker = "FB",
nest_data = TRUE,
return_message = TRUE) {
general_df <-
.parse_company_general_safe(ticker = ticker, nest_data)
cik <-
general_df$idCIK
trader_url <-
list("http://rankandfiled.com/data/filer/", cik, '/traders') %>%
purrr::invoke(paste0, .)
count_trades <-
.parse_json_traders(url = trader_url) %>%
.$countTraders %>% unique() %/% 50
trade_urls <-
list(
'http://rankandfiled.com/data/filer/',
cik,
'/trades?start=',
seq(0, by = 50, length.out = count_trades)
) %>%
purrr::invoke(paste0, .)
.parse_json_trades_safe <-
purrr::possibly(.parse_json_trades, NULL)
all_trades <-
trade_urls %>%
future_map_dfr(function(x) {
.parse_json_trades_safe(url = x, return_message = return_message)
}) %>%
distinct() %>%
suppressWarnings()
owners_df <-
list("http://rankandfiled.com/data/filer/", cik, '/owners') %>%
purrr::invoke(paste0, .) %>%
.parse_json_owners(nest_data = nest_data)
entity <-
general_df$nameEntity
all_trades <-
all_trades %>%
left_join(owners_df %>%
select(idCIKOwner = idCIKOwned, nameEntityOwner) %>%
distinct()) %>%
suppressMessages()
entity_name <-
general_df$nameEntity
all_trades <-
all_trades %>%
mutate(nameEntity = entity_name,
idTicker = ticker) %>%
select(idCIK,
nameEntity,
idTicker,
dateTrade,
idCIKOwner,
nameEntityOwner,
everything()) %>%
suppressWarnings() %>%
suppressMessages()
all_trades <-
all_trades %>%
mutate_at(.vars = all_trades %>% select(dplyr::matches("count")) %>% names,
funs(. %>% formattable::comma(digits = 0))) %>%
mutate_at(.vars = all_trades %>% select(dplyr::matches("amount|price")) %>% names,
funs(. %>% formattable::currency(digits = 2))) %>%
select(idCIK:countShares, amountTransaction, everything()) %>%
resolve_names_to_upper()
if (return_message) {
list("Parsed ", all_trades %>% nrow(), ' trades for ', entity) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(all_trades)
}
.parse_public_filings <-
function(ticker = "FB",
return_message = TRUE) {
general_df <-
.parse_company_general_safe(ticker = ticker)
cik <-
general_df$idCIK
filing_pages <-
general_df$countFilings %/% 50
filing_urls <-
list(
'http://rankandfiled.com/data/filer/',
cik,
'/all?start=',
seq(0, by = 50, length.out = filing_pages)
) %>%
purrr::invoke(paste0, .)
.parse_json_public_filers_safe <-
purrr::possibly(.parse_json_public_filers, NULL)
.all_filings <-
filing_urls %>%
future_map_dfr(function(x) {
.parse_json_public_filers_safe(url = x, return_message = return_message)
}) %>%
distinct() %>%
suppressWarnings()
entity <-
general_df$nameEntity
.all_filings <-
.all_filings %>%
mutate(idTicker = ticker,
nameCompany = entity,
nameEntity = entity) %>%
select(idCIK,
idTicker,
nameEntity,
nameCompany,
dateFiling,
idRF,
everything())
if (return_message) {
list("Parsed ", .all_filings %>% nrow(), ' SEC Filings for ', entity) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(.all_filings)
}
.parse_ticker_data <-
function(ticker = "VNO",
nest_data = TRUE,
tables = NULL,
return_message = TRUE) {
if (length(tables) == 0) {
tables <-
c(
'General',
'CIK Filings',
'Filings',
'Private Offerings',
'Related Parties',
'Traders',
'C Level',
'MDA',
'Owners',
'Insider Trades',
'Trades',
'Subsidiaries'
)
}
ticker <-
ticker %>% str_to_upper()
.parse_company_general_safe <-
purrr::possibly(.parse_company_general, NULL)
.parse_trades_safe <-
purrr::possibly(.parse_trades, NULL)
.parse_public_filings_safe <-
purrr::possibly(.parse_public_filings, NULL)
general <-
.parse_company_general_safe(ticker = ticker,
nest_data = nest_data,
return_message = return_message) %>%
suppressWarnings()
has_trades <-
"TRADES" %>% str_detect(tables %>% str_to_upper()) %>% sum() > 0
if (has_trades) {
trades <-
.parse_trades_safe(ticker = ticker,
nest_data = nest_data,
return_message = return_message) %>%
suppressWarnings()
} else {
trades <-
tibble(idTicker = ticker)
}
cik_data <-
general$idCIK %>%
.parse_cik_data(tables = tables,
nest_data = nest_data,
return_message = return_message)
if ('General' %in% cik_data$nameTable) {
cik_data <-
cik_data %>%
filter(!nameTable == 'General')
}
all_data <-
tibble(
nameEntity = general$nameEntity,
idCIK = general$idCIK,
nameTable = c('Company Profile', 'Insider Trades'),
dataTable = list(general, trades)
) %>%
bind_rows(cik_data) %>%
mutate(countCols = dataTable %>% map_dbl(ncol)) %>%
filter(countCols > 1) %>%
select(-countCols)
if (return_message) {
list("Acquired all data for ", all_data$nameEntity %>% unique()) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(all_data)
}
us_public_companies <-
function(merge_type = NULL,
return_message = TRUE) {
no_merge <-
(!'merge_type' %>% exists()) |
(merge_type %>% purrr::is_null())
if (no_merge) {
merge_type <-
'MATCH'
}
json_data <-
"http://rankandfiled.com/data/public_companies" %>%
jsonlite::fromJSON()
company_data <-
tibble(df = json_data$result$data %>%
str_split(pattern = '\\|') %>%
flatten_chr()) %>%
tidyr::separate(
df,
sep = '\\*',
into = c("X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9")
) %>%
mutate_at(
.vars = c("X5", "X6", "X7", "X8", "X9"),
funs(. %>% as.character() %>% readr::parse_number())
) %>%
purrr::set_names(
c(
'idTicker',
'idExchange',
'codeLocationBusiness',
'codeLocationIncorporation',
'idSector',
'amountEquityMarketCap',
'priceOpen',
'price52WeekLow',
'price52WeekHigh'
)
) %>%
left_join(tibble(
idSector = 1:12,
nameSector = c(
'Finance',
'Capital Goods',
'Technology',
'Transportation',
'Consumer Services',
'Health Care',
'Consumer Durables',
'Public Utilities',
'Miscellaneous',
'Basic Industries',
'Energy',
'Consumer Non Durables'
)
)) %>%
suppressMessages() %>%
left_join(tibble(
idExchange = c('N', 'Q', 'A'),
nameExchange = c('NYSE', 'NASDAQ', 'NYSE ARCA')
)) %>%
mutate(
amountEquityMarketCap = ifelse(
idTicker == 'BRK-A',
amountEquityMarketCap * 100000000000,
amountEquityMarketCap
),
codeLocationBusiness = ifelse(
codeLocationBusiness == '',
codeLocationIncorporation,
codeLocationBusiness
),
codeLocationIncorporation = ifelse(codeLocationIncorporation == '',
NA,
codeLocationIncorporation),
countSharesOutstanding = ifelse(priceOpen > 0,
((
amountEquityMarketCap / priceOpen
)),
NA),
pct52WeekHigh = ifelse(priceOpen > 0,
((
priceOpen / price52WeekHigh
)),
NA),
pct52WeekLow = ifelse(priceOpen > 0,
((
priceOpen / price52WeekLow
)),
NA),
amountEquityMarketCap = (amountEquityMarketCap),
urlTickerRankandFiled = list('http://rankandfiled.com/
) %>%
select(idTicker:idSector, nameSector, everything()) %>%
suppressMessages()
countries <-
location_codes()
company_data <-
company_data %>%
left_join(
countries %>%
dplyr::rename(
codeLocationBusiness = codeLocation,
nameLocationBusiness = nameLocation
)
) %>%
left_join(
countries %>%
dplyr::rename(
codeLocationIncorporation = codeLocation,
nameLocationIncorporation = nameLocation
)
) %>%
suppressMessages()
company_data <-
company_data %>%
filter(priceOpen > 0) %>%
filter(!priceOpen %>% is.na()) %>%
group_by(idTicker, nameSector) %>%
filter(amountEquityMarketCap == max(amountEquityMarketCap, na.rm = TRUE)) %>%
ungroup() %>%
arrange(idTicker)
ticker_count_df <-
company_data %>%
count(idTicker, sort = TRUE)
fine_tickers <-
ticker_count_df %>% filter(n < 2) %>% .$idTicker
fine_df <-
company_data %>%
filter(idTicker %in% (fine_tickers))
dup_count_df <-
ticker_count_df %>% filter(n > 1)
dup_df <-
company_data %>%
filter(idTicker %in% dup_count_df$idTicker) %>%
arrange(idTicker)
dup_general_df <-
dup_count_df$idTicker %>%
future_map_dfr(function(x) {
.parse_company_general_safe(ticker = x)
}) %>%
arrange(idTicker)
dup_df <-
dup_general_df %>%
select(idTicker, nameLocationBusiness = stateEntity, nameSector) %>%
left_join(countries %>% dplyr::rename(nameLocationBusiness = nameLocation)) %>%
dplyr::rename(codeLocationBusiness = codeLocation) %>%
left_join(dup_df) %>%
suppressMessages()
company_data <-
fine_df %>%
bind_rows(dup_df) %>%
arrange(idTicker)
is_merge_all <-
merge_type %>% str_to_upper() == 'ALL'
is_match <-
merge_type %>% str_to_upper() == 'MATCH'
if (is_merge_all) {
general_data <-
company_data$idTicker %>%
unique() %>%
future_map_dfr(function(x) {
.parse_company_general_safe(ticker = x, return_message = return_message)
}) %>%
suppressWarnings()
company_data <-
company_data %>%
inner_join(general_data %>%
select(-one_of(
c(
"idExchange",
"nameSector",
"amountEquityMarketCap",
"priceOpen",
"price52WeekLow",
"price52WeekHigh",
"urlTickerRankandFiled"
)
))) %>%
dplyr::rename(nameCompany = nameEntity) %>%
select(idTicker,
nameCompany,
idCIK,
idSector,
nameSector,
nameExchange,
everything())
if (return_message) {
list(
"Acquired data for ",
company_data %>% nrow() %>% formattable::comma(digits = 0),
' US stocks with a combined market capitalization of ',
company_data$amountEquityMarketCap %>% sum(na.rm = TRUE) %>% formattable::currency(digits = 0)
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
return(company_data)
}
if (is_match) {
all_tickers <-
rf_us_tickers()
company_data <-
company_data %>%
left_join(
all_tickers %>%
filter(!urlTickerRankandFiled %>% is.na()) %>%
select(
idTicker,
idCIK,
nameCompany,
codeLocationBusiness,
idSIC,
classificationSIC
)
) %>%
suppressMessages()
count_df <-
company_data %>%
count(idTicker, sort = TRUE)
dup_tickers <-
count_df %>%
filter(n > 1) %>%
.$idTicker %>%
unique()
fine_df <-
company_data %>%
filter(!idTicker %in% dup_tickers)
dup_df <-
company_data %>%
filter(idTicker %in% dup_tickers)
.parse_company_general_safe <-
purrr::possibly(.parse_company_general, tibble)
dup_general_df <-
dup_tickers %>%
future_map_dfr(function(x) {
.parse_company_general_safe(ticker = x)
}) %>%
arrange(idTicker) %>%
suppressWarnings()
dup_df <-
dup_df %>%
select(-c(nameCompany, idCIK, idSIC, classificationSIC)) %>%
distinct() %>%
left_join(dup_general_df %>%
select(idTicker, idCIK, nameCompany = nameEntity)) %>%
left_join(all_tickers %>%
select(idCIK, idSIC, classificationSIC)) %>%
suppressWarnings() %>%
suppressMessages()
company_data <-
fine_df %>%
bind_rows(dup_df) %>%
distinct()
match_df <-
company_data %>%
filter(!nameCompany %>% is.na())
missing_name_df <-
company_data %>%
filter(nameCompany %>% is.na()) %>%
select(-c(nameCompany, idCIK)) %>%
inner_join(all_tickers %>% select(idTicker, nameCompany, idCIK)) %>%
suppressMessages()
count_df <-
missing_name_df %>%
count(idTicker, sort = TRUE)
dup_tickers <-
count_df %>%
filter(n > 1) %>%
.$idTicker %>%
unique()
fine_df <-
missing_name_df %>%
filter(!idTicker %in% dup_tickers)
dup_df <-
missing_name_df %>%
filter(idTicker %in% dup_tickers)
dup_general_df <-
dup_tickers %>%
future_map_dfr(function(x) {
.parse_company_general_safe(ticker = x)
}) %>%
arrange(idTicker) %>%
suppressWarnings()
dup_df <-
dup_df %>%
select(-c(nameCompany, idCIK)) %>%
distinct() %>%
left_join(dup_general_df %>% select(idTicker, nameCompany = nameEntity, idCIK)) %>%
suppressMessages()
missing_name_df <-
fine_df %>%
bind_rows(dup_df) %>%
select(-c(idSIC, classificationSIC)) %>%
left_join(all_tickers %>%
select(idCIK, idSIC, classificationSIC)) %>%
suppressMessages()
company_data <-
match_df %>%
bind_rows(missing_name_df) %>%
arrange(desc(amountEquityMarketCap)) %>%
select(
idCIK,
idTicker,
nameCompany,
idExchange,
idSector,
nameSector,
idSIC,
classificationSIC,
everything()
)
company_data <-
company_data %>%
mutate_at(
company_data %>% select(dplyr::matches("price")) %>% names(),
funs(. %>% formattable::currency(digits = 2))
) %>%
mutate_at(
company_data %>% select(dplyr::matches("amount")) %>% names(),
funs(. %>% formattable::currency(digits = 0))
) %>%
mutate_at(
company_data %>% select(dplyr::matches("pct")) %>% names(),
funs(. %>% formattable::percent(digits = 2))
)
if (return_message) {
list(
"Acquired data for ",
company_data %>% nrow() %>% formattable::comma(digits = 0),
' US Stocks with a combined market capitalization of ',
company_data$amountEquityMarketCap %>% sum(na.rm = TRUE) %>% formattable::currency(digits = 0)
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
company_data <-
company_data %>%
resolve_names_to_upper()
return(company_data)
}
}
.parse_sec_url_for_cik <-
function(url) {
url %>%
str_replace_all("https://www.sec.gov/Archives/edgar/data/", '') %>%
str_split('\\/') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
}
.get_loc_df <-
function() {
tibble(
nameLocation = c(
"AFGHANISTAN",
"ALAND ISLANDS",
"ALBANIA",
"ALGERIA",
"AMERICAN SAMOA",
"ANDORRA",
"ANGOLA",
"ANGUILLA",
"ANTARCTICA",
"ANTIGUA AND BARBUDA",
"ARGENTINA",
"ARMENIA",
"ARUBA",
"AUSTRALIA",
"AUSTRIA",
"AUSTRIA-HUNGARY",
"AZERBAIJAN",
"BADEN",
"BAHAMAS",
"BAHRAIN",
"BANGLADESH",
"BARBADOS",
"BAVARIA",
"BELARUS",
"BELGIUM",
"BELIZE",
"BENIN",
"BERMUDA",
"BHUTAN",
"BOLIVIA, PLURINATIONAL STATE OF",
"BONAIRE, SINT EUSTATIUS AND SABA",
"BOSNIA AND HERZEGOVINA",
"BOTSWANA",
"BOUVET ISLAND",
"BRAZIL",
"BRITISH INDIAN OCEAN TERRITORY",
"BRUNEI DARUSSALAM",
"BULGARIA",
"BURKINA FASO",
"BURUNDI",
"CAMBODIA",
"CAMEROON",
"CANADA",
"CABO VERDE",
"CAYMAN ISLANDS",
"CENTRAL AFRICAN REPUBLIC",
"CHAD",
"CHILE",
"CHINA",
"CHRISTMAS ISLAND",
"COCOS (KEELING) ISLANDS",
"COLOMBIA",
"COMOROS",
"CONGO, THE DEMOCRATIC REPUBLIC OF THE",
"CONGO",
"COOK ISLANDS",
"COSTA RICA",
"COTE D'IVOIRE",
"CROATIA",
"CUBA",
"CURACAO",
"CYPRUS",
"CZECH REPUBLIC",
"CZECHOSLOVAKIA",
"DENMARK",
"DJIBOUTI",
"DOMINICA",
"DOMINICAN REPUBLIC",
"ECUADOR",
"EGYPT",
"EL SALVADOR",
"EQUATORIAL GUINEA",
"ERITREA",
"ESTONIA",
"ETHIOPIA",
"FALKLAND ISLANDS (MALVINAS)",
"FAROE ISLANDS",
"FIJI",
"FINLAND",
"FRANCE",
"FRENCH GUIANA",
"FRENCH POLYNESIA",
"FRENCH SOUTHERN TERRITORIES",
"GABON",
"GAMBIA",
"GEORGIA",
"GERMAN DEMOCRATIC REPUBLIC",
"FEDERAL REPUBLIC OF GERMANY",
"GERMANY",
"GHANA",
"GIBRALTAR",
"GREECE",
"GREENLAND",
"GRENADA",
"GUADELOUPE",
"GUAM",
"GUATEMALA",
"GUERNSEY",
"GUINEA",
"GUINEA-BISSAU",
"GUYANA",
"HAITI",
"HANOVER",
"HEARD ISLAND AND MCDONALD ISLANDS",
"HESSE ELECTORAL",
"HESSE GRAND DUCAL",
"HOLY SEE (VATICAN CITY STATE)",
"HONDURAS",
"HONG KONG",
"HUNGARY",
"ICELAND",
"INDIA",
"INDONESIA",
"IRAN, ISLAMIC REPUBLIC OF",
"IRAQ",
"IRELAND",
"ISLE OF MAN",
"ISRAEL",
"ITALY",
"JAMAICA",
"JAPAN",
"JERSEY",
"JORDAN",
"KAZAKHSTAN",
"KENYA",
"KIRIBATI",
"KOREA",
"KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF",
"KOREA, REPUBLIC OF",
"KOSOVO",
"KUWAIT",
"KYRGYZSTAN",
"LAO PEOPLE'S DEMOCRATIC REPUBLIC",
"LATVIA",
"LEBANON",
"LESOTHO",
"LIBERIA",
"LIBYA",
"LIECHTENSTEIN",
"LITHUANIA",
"LUXEMBOURG",
"MACAO",
"MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF",
"MADAGASCAR",
"MALAWI",
"MALAYSIA",
"MALDIVES",
"MALI",
"MALTA",
"MARSHALL ISLANDS",
"MARTINIQUE",
"MAURITANIA",
"MAURITIUS",
"MAYOTTE",
"MECKLENBURG SCHWERIN",
"MEXICO",
"MICRONESIA, FEDERATED STATES OF",
"MODENA",
"MOLDOVA, REPUBLIC OF",
"MONACO",
"MONGOLIA",
"MONTENEGRO",
"MONTSERRAT",
"MOROCCO",
"MOZAMBIQUE",
"MYANMAR",
"NAMIBIA",
"NAURU",
"NEPAL",
"NETHERLANDS",
"NETHERLANDS ANTILLES",
"NEW CALEDONIA",
"NEW ZEALAND",
"NICARAGUA",
"NIGER",
"NIGERIA",
"NIUE",
"NORFOLK ISLAND",
"NORTHERN MARIANA ISLANDS",
"NORWAY",
"OMAN",
"PAKISTAN",
"PALAU",
"PALESTINE, STATE OF",
"PANAMA",
"PAPUA NEW GUINEA",
"PARAGUAY",
"PARMA",
"PERU",
"PHILIPPINES",
"PITCAIRN",
"POLAND",
"PORTUGAL",
"PUERTO RICO",
"QATAR",
"REPUBLIC OF VIETNAM",
"REUNION",
"ROMANIA",
"RUSSIAN FEDERATION",
"RWANDA",
"SAINT BARTHELEMY",
"SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA",
"SAINT KITTS AND NEVIS",
"SAINT LUCIA",
"SAINT MARTIN (FRENCH PART)",
"SAINT PIERRE AND MIQUELON",
"SAINT VINCENT AND THE GRENADINES",
"SAMOA",
"SAN MARINO",
"SAO TOME AND PRINCIPE",
"SAUDI ARABIA",
"SAXONY",
"SENEGAL",
"SERBIA",
"SEYCHELLES",
"SIERRA LEONE",
"SINGAPORE",
"SINT MAARTEN (DUTCH PART)",
"SLOVAKIA",
"SLOVENIA",
"SOLOMON ISLANDS",
"SOMALIA",
"SOUTH AFRICA",
"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS",
"SOUTH SUDAN",
"SPAIN",
"SRI LANKA",
"SUDAN",
"SURINAME",
"SVALBARD AND JAN MAYEN",
"SWAZILAND",
"SWEDEN",
"SWITZERLAND",
"SYRIAN ARAB REPUBLIC",
"TAIWAN, PROVINCE OF CHINA",
"TAJIKISTAN",
"TANZANIA, UNITED REPUBLIC OF",
"THAILAND",
"TIMOR-LESTE",
"TOGO",
"TOKELAU",
"TONGA",
"TRINIDAD AND TOBAGO",
"TUNISIA",
"TURKEY",
"TURKMENISTAN",
"TURKS AND CAICOS ISLANDS",
"TUSCANY",
"TUVALU",
"TWO SICILIES",
"UGANDA",
"UKRAINE",
"UNITED ARAB EMIRATES",
"UNITED KINGDOM",
"UNITED STATES",
"UNITED STATES MINOR OUTLYING ISLANDS",
"URUGUAY",
"UZBEKISTAN",
"VANUATU",
"VENEZUELA, BOLIVARIAN REPUBLIC OF",
"VIET NAM",
"VIRGIN ISLANDS, BRITISH",
"VIRGIN ISLANDS, U.S.",
"WALLIS AND FUTUNA",
"WESTERN SAHARA",
"WUERTTEMBURG",
"YEMEN",
"YEMEN ARAB REPUBLIC",
"YEMEN PEOPLE'S REPUBLIC",
"YUGOSLAVIA",
"ZAMBIA",
"ZANZIBAR",
"ZIMBABWE",
"ALABAMA",
"ALASKA",
"ARIZONA",
"ARKANSAS",
"CALIFORNIA",
"COLORADO",
"CONNECTICUT",
"DELAWARE",
"FLORIDA",
"GEORGIA",
"HAWAII",
"IDAHO",
"ILLINOIS",
"INDIANA",
"IOWA",
"KANSAS",
"KENTUCKY",
"LOUISIANA",
"MAINE",
"MARYLAND",
"MASSACHUSETTS",
"MICHIGAN",
"MINNESOTA",
"MISSISSIPPI",
"MISSOURI",
"MONTANA",
"NEBRASKA",
"NEVADA",
"NEW HAMPSHIRE",
"NEW JERSEY",
"NEW MEXICO",
"NEW YORK",
"NORTH CAROLINA",
"NORTH DAKOTA",
"OHIO",
"OKLAHOMA",
"OREGON",
"PENNSYLVANIA",
"RHODE ISLAND",
"SOUTH CAROLINA",
"SOUTH DAKOTA",
"TENNESSEE",
"TEXAS",
"UTAH",
"VERMONT",
"VIRGINIA",
"WASHINGTON",
"WEST VIRGINIA",
"WISCONSIN",
"WYOMING",
"DISTRICT OF COLUMBIA",
"ENGLAND",
"BRITISH VIRGIN ISLANDS",
"NETHERLAND ANTILLES",
"RUSSIA",
"SOUTH KOREA",
'TAIWAN',
"VENEZUELA",
'CHANNEL ISLANDS'
)
)
}
.parse_page_sub_multi_item_html <-
function(page) {
locations <-
.get_loc_df() %>%
.$nameLocation
subsidiaries <-
page %>%
html_nodes('td div') %>%
html_text() %>%
str_replace_all('\u0095 |\u0096|\u0095\n', '') %>%
str_trim()
subsidiaries <-
subsidiaries[!subsidiaries == '']
data_nodes <-
page %>%
html_nodes('td') %>%
html_text() %>%
str_replace_all('\u0095 |\u0096|\u0095\n', '') %>%
str_trim() %>%
str_to_upper()
data_nodes <-
data_nodes[!data_nodes == '']
location_items <-
data_nodes[data_nodes %in% locations]
pct_vals <-
tibble(value = data_nodes) %>%
filter(!value %>% str_detect("\\([(1-9)]\\)")) %>%
mutate(pctSubsidiaryOwned = value %>% as.numeric()) %>%
filter(!pctSubsidiaryOwned %>% is.na()) %>%
slice(seq_along(subsidiaries)) %>%
.$pctSubsidiaryOwned / 100 %>%
suppressWarnings() %>%
suppressMessages()
all_data <-
tibble(
nameSubsidiary = subsidiaries,
nameLocationSubsidiary = location_items,
pctSubsidiaryOwned = pct_vals
) %>%
mutate(nameSubsidiary = nameSubsidiary %>% str_to_upper())
return(all_data)
}
.parse_page_subsidiary_table_html <-
function(page,
numbers = 1:10,
hit_terms = c(
"Organized",
"STATE OR|STATE OF|JURISDICTION OF|JURISDICTION OF INCORPORATION OR ORGANIZATION|JURISDICTION|JURISDICTION OF INCORPORATION OR\nORGANIZATION",
"NAME|ORGANIZED UNDER THE LAWS OF",
'STATE OF ORGANIZATION',
'STATE OR COUNTRY OF ORGANIZATION',
'NAME OF SUBSIDIARY',
'NAME',
'ENTITY NAME',
'the laws of',
'Percentage of voting',
'securities owned by',
'immediate parent',
'CERTAIN INTERMEDIARY SUBSIDIARIES',
'Note:',
'Organized',
'Under the',
'Laws of',
'OWNED BY',
'IMMEDIATE',
'PARENT',
"OWNS",
"CERTAIN INTERMEDIARY SUBSIDIARIES",
'PERCENTAGE',
'OF VOTING',
'SECURITIES'
)) {
is_ib1 <-
page %>%
html_nodes('b font') %>%
html_text() %>% length() > 0
if (is_ib1) {
items_bold <-
page %>%
html_nodes('b font') %>%
html_text() %>%
str_to_upper() %>%
str_replace_all('\n', ' ')
items_bold <-
stringi::stri_trans_general(items_bold, "Latin-ASCII")
items_bold <-
items_bold %>%
str_split('\\-') %>%
flatten_chr() %>%
str_trim()
} else {
items_bold <-
page %>%
html_nodes('b') %>%
html_text() %>%
str_to_upper() %>%
str_replace_all('\n', ' ') %>%
stringi::stri_trans_general("Latin-ASCII")
items_bold <-
items_bold %>%
str_split('\\-') %>%
flatten_chr() %>%
str_trim() %>%
unique()
}
has_date <-
items_bold %>% grep(month.name %>% str_to_upper() %>% paste(collapse = '|'), .) %>% length > 0
if (has_date) {
date_data <-
items_bold[items_bold %>% grep(month.name %>% str_to_upper() %>% paste(collapse = '|'), .)] %>%
lubridate::mdy()
} else {
date_data <-
NA
}
hit_terms <-
hit_terms %>%
append(items_bold) %>%
str_to_upper() %>%
unique() %>%
append(list('(', letters, ')') %>%
purrr::invoke(paste0, .)) %>%
paste0(collapse = '|')
hit_terms_in <-
hit_terms %>% str_split('\\|') %>%
flatten_chr()
locations <-
.get_loc_df() %>%
.$nameLocation
all_data <-
numbers %>%
future_map_dfr(function(x) {
css_selector <-
paste0('td:nth-child(', x, ')')
has_length <-
page %>%
html_nodes(css_selector) %>% length() > 0
if (has_length) {
item <-
paste0("X" , x)
value <-
page %>%
html_nodes(css_selector) %>%
html_text() %>%
str_trim()
tibble(item, value)
}
}) %>%
mutate(
value = value %>% str_to_upper() %>% str_replace_all('\n ', ' ') %>% str_replace_all('\u0096 ', '')
) %>%
filter(!value == '')
has_loc_key <-
all_data %>%
filter(value %in% locations) %>%
nrow() > 0
if (has_loc_key) {
loc_cols <-
all_data %>%
filter(value %in% locations) %>%
.$item %>%
unique()
if (loc_cols %>% length == 1) {
loc_col <-
loc_cols[[1]]
}
}
has_pct <-
all_data %>%
filter(value %>% str_detect("PERCENT")) %>%
.$item %>% unique() %>% length() > 0
if (has_pct) {
pct_col <-
all_data %>%
filter(value %>% str_detect("PERCENT")) %>%
.$item %>% unique()
} else {
pct_col <-
NA
}
is_whack <-
pct_col[[1]] %in% loc_cols
if (is_whack) {
all_data <-
page %>%
.parse_page_sub_multi_item_html() %>%
mutate(dateSubsidiaryAsOf = date_data)
return(all_data)
}
all_data <-
all_data %>%
filter(!value %in% items_bold) %>%
filter(!value %>% str_detect(paste0(items_bold %>% unique(), collapse = '|'))) %>%
filter(!value %in% hit_terms_in) %>%
filter(!value %>% str_detect(hit_terms))
count_df <-
all_data %>% count(item, sort = T) %>%
arrange(item) %>%
spread(item, n)
off_one <-
(count_df[, 2] %>% extract2(1)) - (count_df[, 1] %>% extract2(1)) == 1
min_item <-
count_df %>% gather(item, value) %>% filter(value == min(value)) %>% .$item
change_pct <-
has_pct & (pct_col == min_item) %>% sum() > 0
if (change_pct) {
pct_col <-
names(count_df)[[3]]
}
if (off_one) {
df <-
all_data$item %>% unique() %>%
future_map_dfr(function(x) {
has_data <-
all_data %>%
filter(item == x) %>%
filter(!value %>% is.na()) %>%
filter(!value == '') %>%
nrow()
if (has_data) {
all_data %>%
filter(item == x) %>%
filter(!value %>% is.na()) %>%
filter(!value == '') %>%
filter(!value %>% str_detect(hit_terms)) %>%
mutate(idSubsidiary = 1:n())
}
}) %>%
filter(!value %>% str_detect(hit_terms)) %>%
spread(item, value)
if (change_pct) {
df <-
df %>%
select(-one_of(min_item))
}
}
if (!off_one) {
has_property <-
items_bold %>% str_detect('PROPERTY') %>% sum() > 0
if (has_property) {
tables <-
page %>%
html_table(fill = T)
df <-
seq_along(tables) %>%
future_map_dfr(function(x) {
table_df <-
tables[[x]] %>%
data.frame(stringsAsFactors = FALSE) %>%
as_tibble()
column_df <-
table_df %>% slice(1) %>%
gather(column, value) %>%
mutate(idColumn = 1:n()) %>%
filter(!value %>% is.na()) %>%
left_join(tibble(
value = c(
"PROPERTY",
"ENTITIES",
"STATE OF FORMATION",
"DATE OF FORMATION",
" ",
'General Information:'
),
nameItem = c(
'nameProperty',
'nameSubsidiary',
'locationOrganizationSubsidiary',
'dateSubsidiaryFormed',
'locationOrganizationSubsidiary',
'nameSubsidiary'
)
)) %>%
suppressMessages()
two_col <-
column_df %>% nrow() == 2
if (two_col) {
column_df$nameItem[[2]] <-
'locationOrganizationSubsidiary'
}
columns_keep <-
column_df$idColumn
table_df <-
table_df <-
table_df %>%
select(columns_keep) %>%
slice(-1) %>%
purrr::set_names(column_df$nameItem)
table_df <-
table_df %>%
mutate_all(funs(. %>% str_trim() %>% str_to_upper())) %>%
mutate(nameSubsidiary = ifelse(nameSubsidiary == '', NA, nameSubsidiary)) %>%
filter(!nameSubsidiary %>% is.na())
if (two_col) {
table_df <-
table_df %>%
tidyr::separate(
locationOrganizationSubsidiary,
into = c(
'locationOrganizationSubsidiary',
'dateSubsidiaryFormed'
),
sep = 'FORMED'
) %>%
suppressWarnings() %>%
mutate(locationOrganizationSubsidiary = locationOrganizationSubsidiary %>% str_replace_all('\\,', '')) %>%
mutate_all(funs(. %>% str_replace('\n', '') %>% str_trim()))
}
if ('nameProperty' %in% names(table_df)) {
table_df <-
table_df %>%
mutate(nameProperty = ifelse(nameProperty == '', NA, nameProperty)) %>%
mutate_all(funs(. %>% str_replace('\n|\n |\n ', '') %>% str_trim())) %>%
mutate_all(funs(. %>% str_replace('\n', '') %>% str_trim())) %>%
mutate_all(funs(. %>% str_replace(' ', ' ') %>% str_trim())) %>%
fill(nameProperty)
}
return(table_df)
})
if ('dateSubsidiaryFormed' %in% names(df)) {
df <-
df %>%
mutate(dateSubsidiaryFormed = dateSubsidiaryFormed %>% lubridate::mdy())
}
df <-
df %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(idCIK, nameSubsidiary, everything()) %>%
mutate(
locationOrganizationSubsidiary = locationOrganizationSubsidiary %>% str_replace_all(
'A |LIMITED LIABILITY COMPANY|CORPORATION|LIMITED PARTNERSHIP'
) %>% str_trim()
)
return(df)
}
if (!has_property) {
df <-
all_data %>%
mutate(value = ifelse(value == '', NA, value)) %>%
filter(!value %>% is.na()) %>%
group_by(item) %>%
mutate(idSubsidiary = 1:n()) %>%
spread(item, value) %>%
filter(!X1 == '') %>%
mutate(idSubsidiary = 1:n()) %>%
gather(item, value, -c(X1, idSubsidiary)) %>%
ungroup() %>%
filter(!value %>% str_detect(hit_terms)) %>%
spread(item, value)
}
}
df <-
df %>%
dplyr::rename(nameSubsidiary = X1) %>%
tidyr::separate(nameSubsidiary,
sep = '\\(',
into = c('nameSubsidiary', 'remove')) %>%
select(-dplyr::matches("remove")) %>%
mutate(nameSubsidiary = nameSubsidiary %>% str_trim()) %>%
suppressWarnings() %>%
select(-dplyr::matches("idSubsidiary"))
if (has_pct) {
names(df)[names(df) %>% grep(pct_col, .)] <-
'pctSubsidiaryOwned'
df <-
df %>%
mutate_at(df %>% select(dplyr::matches('pct')) %>% names(),
funs(. %>% as.numeric() / 100)) %>%
suppressWarnings()
}
if (has_loc_key) {
names(df)[names(df) %>% grep(loc_col, .)] <-
'locationOrganizationSubsidiary'
}
df <-
df %>%
select(-dplyr::matches("X"))
return(df)
}
.parse_sec_subsidiary_url_html <-
function(url = "https://www.sec.gov/Archives/edgar/data/34088/000003408816000065/xomexhibit21.htm",
return_message = TRUE) {
cik <-
url %>%
.parse_sec_url_for_cik()
page <-
url %>%
read_html()
is_zero <-
page %>%
html_nodes(paste0('td:nth-child(', 1, ')')) %>%
length() == 0
locations <-
.get_loc_df() %>%
.$nameLocation
if (is_zero) {
data <-
page %>%
html_nodes('font') %>%
html_text() %>%
str_replace_all('\\ ', ' ')
data <-
data[!data == '']
is_parenth <-
data %>% str_detect('\\(') %>% sum() / length(data) > .25
if (is_parenth) {
data <-
data[data %>% str_detect('\\(')]
df <-
tibble(data) %>%
separate(
data,
sep = '\\(',
into = c('nameSubsidiary', 'locationOrganizationSubsidiary')
) %>%
separate(
locationOrganizationSubsidiary,
sep = '\\)',
into = c('locationOrganizationSubsidiary', 'remove')
) %>%
select(-remove) %>%
mutate_all(funs(. %>% str_trim() %>% str_to_upper())) %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary"))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
is_nested <-
page %>%
html_nodes('b font') %>%
html_text() %>% length() > 2
if (is_nested) {
locations_raw <-
page %>%
html_nodes('b font') %>%
html_text() %>%
str_replace_all('\\:', '') %>%
str_to_upper()
locations <-
locations_raw[!locations_raw %>% str_detect('EXHIBIT|SUBSIDIARY|SUBSIDIARIES')]
data <-
data[data %>% nchar() > 3] %>% str_to_upper()
df <-
tibble(nameSubsidiary = data) %>%
mutate(idRow = 1:n())
.loc_df <-
tibble(nameSubsidiary = locations) %>%
inner_join(df %>% select(idRow, nameSubsidiary)) %>%
mutate(idRow = idRow + 1) %>%
select(locationOrganizationSubsidiary = nameSubsidiary, idRow) %>%
suppressMessages()
df <-
df %>%
filter(!nameSubsidiary %>% str_detect('SUBSIDIARY|SUBSIDIARIES')) %>%
filter(!nameSubsidiary %>% str_detect(paste0(locations_raw, collapse = '|'))) %>%
suppressWarnings()
df <-
df %>%
left_join(.loc_df) %>%
fill(locationOrganizationSubsidiary) %>%
mutate(urlSEC = url, idCIK = cik) %>%
select(idCIK,
nameSubsidiary,
locationOrganizationSubsidiary,
everything()) %>%
select(-idRow) %>%
suppressMessages() %>%
select(-dplyr::matches("idSubsidiary"))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
}
is_font_table <-
page %>%
html_nodes('b') %>%
html_text() %>% length() == 0
if (is_font_table) {
all_data <-
1:10 %>%
future_map_dfr(function(x) {
css_selector <-
paste0('td:nth-child(', x, ')')
has_length <-
page %>%
html_nodes(css_selector) %>% length() > 0
if (has_length) {
item <-
paste0("X" , x)
value <-
page %>%
html_nodes(css_selector) %>%
html_text() %>%
str_trim()
tibble(item, value)
}
}) %>%
mutate(
value = value %>% str_to_upper() %>% str_replace_all('\n ', ' ') %>% str_replace_all('\u0096 ', '')
) %>%
filter(!value == '')
has_loc_key <-
all_data %>%
filter(value %in% locations) %>%
nrow() > 0
if (has_loc_key) {
loc_col <-
all_data %>%
filter(value %in% locations) %>%
.$item %>%
unique()
}
hit_terms_in <-
c(
"Organized",
"STATE OR|STATE OF|JURISDICTION OF|JURISDICTION OF INCORPORATION OR ORGANIZATION|JURISDICTION|JURISDICTION OF INCORPORATION OR\nORGANIZATION",
"NAME|ORGANIZED UNDER THE LAWS OF",
'STATE OF ORGANIZATION',
'STATE OR COUNTRY OF ORGANIZATION',
'NAME OF SUBSIDIARY',
'NAME',
'ENTITY NAME',
'the laws of',
'Percentage of voting',
'securities owned by',
'immediate parent',
'CERTAIN INTERMEDIARY SUBSIDIARIES',
'PERCENT OWNED'
)
hit_terms <-
hit_terms %>%
str_to_upper() %>%
paste0(collapse = '|')
hit_terms_in <-
hit_terms %>% str_split('\\|') %>%
flatten_chr()
has_pct_col <-
all_data %>%
filter(value %in% "100") %>%
nrow() > 0 |
(all_data %>% filter(value %>% str_detect('PERCENT')) %>% nrow() > 0)
if (has_pct_col) {
pct_col <-
all_data %>%
filter((value %in% "100") |
(value %>% str_detect("PERCENT"))) %>%
.$item %>%
unique() %>%
.[[1]]
}
all_data <-
all_data %>%
filter(!value %in% hit_terms_in) %>%
filter(!value %>% str_detect(hit_terms)) %>%
filter(!value == '') %>%
mutate(valueNC = value %>% nchar()) %>%
filter(!value %>% str_detect("PERCENT"))
if (!has_pct_col) {
all_data <-
all_data %>%
filter(valueNC > 3)
}
all_data <-
all_data %>%
select(-valueNC) %>%
group_by(item) %>%
mutate(idSubsidiary = 1:n()) %>%
spread(item, value) %>%
ungroup() %>%
dplyr::rename(nameSubsidiary = X1)
if (has_loc_key) {
names(all_data)[names(all_data) %in% loc_col] <-
'locationOrganizationSubsidiary'
}
if (has_pct_col) {
names(all_data)[names(all_data) %in% pct_col] <-
'pctSubsidiaryOwned'
all_data <-
all_data %>%
mutate(pctSubsidiaryOwned = pctSubsidiaryOwned %>% as.numeric() / 100)
}
all_data <-
all_data %>%
mutate(idCIK = cik,
dateSubsidiaryAsOf = NA,
urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary|^X"))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(all_data)
}
df <-
page %>%
.parse_page_subsidiary_table_html() %>%
suppressWarnings()
df <-
df %>%
filter(!nameSubsidiary == '') %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary")) %>%
select(idCIK, everything())
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df %>% select(-dplyr::matches("idSubsidiary")))
}
.parse_sec_subsidiary_url_text <-
function(url = "https://www.sec.gov/Archives/edgar/data/899689/000104746903007996/a2104897zex-21.txt",
return_message = TRUE) {
cik <-
url %>%
.parse_sec_url_for_cik()
data <-
url %>%
read_lines()
data <-
data[!data == '']
has_s <-
data %>% str_detect("<S>") %>% sum() > 0
if (has_s) {
data <-
data[(data %>% grep("<S>", .) %>% .[[1]] + 1):length(data)]
}
data <-
data[!data %>% str_detect("STATE OF|NAME OF|---|NAME OF SUBSIDIARY|ORGANIZED UNDER|THE LAWS OF|<")]
data <-
data[data %>% nchar() > 3]
df <-
seq_along(data) %>%
future_map_dfr(function(x) {
item <-
data[[x]]
items <-
item %>%
str_replace_all('\\ ', '\\:') %>%
str_split('\\:') %>%
flatten_chr() %>%
str_trim() %>%
str_to_upper()
items <-
items[!items == '']
if (items %>% length() == 1) {
return(tibble())
}
two_items <-
items %>% length() == 2
if (two_items) {
table_data <-
tibble(
idSubsidiary = x,
nameSubsidiary = items[[1]],
locationOrganizationSubsidiary = items[[2]]
)
}
three_items <-
items %>% length() == 3
if (three_items) {
table_data <-
tibble(
idSubsidiary = x,
nameSubsidiary = items[[1]],
locationOrganizationSubsidiary = items[[2]],
pctSubsidiaryOwned = items[[3]] %>% as.numeric() / 100
)
}
table_data <-
table_data %>%
mutate(
isChildSubsidiary = ifelse(nameSubsidiary %>% substr(1, 1) == "-", TRUE, FALSE),
nameSubsidiary = nameSubsidiary %>% str_replace('\\-', '') %>% str_trim()
)
return(table_data)
}) %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary")) %>%
select(idCIK,
nameSubsidiary,
locationOrganizationSubsidiary,
everything()) %>%
filter(!nameSubsidiary %in% c('NAME', 'ORGANIZED UNDER'))
df <-
df %>%
filter(!nameSubsidiary == '')
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
.parse_sec_subsidiary_url <-
function(url = "https://www.sec.gov/Archives/edgar/data/34088/000003408816000065/xomexhibit21.htm",
return_message = TRUE) {
is_text <-
url %>%
str_detect("txt")
is_html <-
url %>%
str_detect("html|htm")
parse_sec_subsidiary_url_text_safe <-
purrr::possibly(.parse_sec_subsidiary_url_text, tibble())
parse_sec_subsidiary_url_html_safe <-
purrr::possibly(.parse_sec_subsidiary_url_html, tibble())
if (is_text) {
data <-
url %>%
parse_sec_subsidiary_url_text_safe()
}
if (is_html) {
data <-
url %>%
parse_sec_subsidiary_url_html_safe()
}
return(data)
}
.parse_full_form_names <-
function(sec_names) {
df_names <-
seq_along(sec_names) %>%
future_map_dfr(function(x) {
sec_name <-
sec_names[[x]]
name_pieces <-
sec_name %>% str_replace_all('\\.value|\\.item', '')
pieces <-
name_pieces %>%
str_split('\\.') %>%
flatten_chr()
pieces_no_num <-
pieces[!pieces %>% str_detect("[0-9]")]
peice_length <-
pieces_no_num %>% length()
is_street <-
pieces %>% str_detect("street1|street2|Street1|Street2") %>% sum(na.rm = T) > 0
name_item <-
pieces_no_num[length(pieces_no_num)]
if (sec_name %>% str_detect('filingManager')) {
name_item <-
pieces %>% paste0(collapse = '')
df <-
tibble(nameSECFull = sec_name,
nameSEC = name_item)
return(df)
}
if (is_street) {
name_item <-
pieces[pieces %>% str_detect("street1|street2|Street1|Street2")]
}
is_sig <-
name_pieces %>% str_detect('signature') & peice_length == 1
is_footnote <-
sec_name %>% str_detect('footnote')
is_issuer <-
sec_name %>% str_detect('\\issuer.[A-Z]')
is_federal <-
sec_name %>% str_detect(pattern = "federalExemptionsExclusions")
if (is_federal) {
df <-
tibble(
nameSECFull = sec_name,
nameTable = pieces[[1]],
nameSEC = name_item
)
return(df)
}
if (is_issuer) {
items <-
sec_name %>% str_split('\\.') %>% flatten_chr()
countItem <-
pieces[2] %>% as.character() %>% readr::parse_number() %>% suppressWarnings()
name_item <-
items[length(items)]
df <-
tibble(
nameSECFull = sec_name,
nameTable = 'issuer',
countItem,
nameSEC = name_item
)
return(df)
}
if (is_footnote) {
if (pieces %>% length() == 1) {
countItem <-
0
item <-
pieces[[1]]
} else {
item <-
pieces[[1]]
countItem <-
pieces[2] %>%as.character() %>% readr::parse_number() %>% suppressWarnings()
}
return(tibble(nameTable = 'footnotes', nameSECFull = sec_name, nameSEC = item, countItem))
}
if (is_sig) {
df <-
tibble(nameTable = 'signatures', nameSECFull = sec_name, nameSEC = name_item)
return(df)
}
if (peice_length == 1) {
df <-
tibble(nameSECFull = sec_name, nameSEC = name_item)
return(df)
}
piece_count <-
length(pieces)
if (piece_count == 1) {
df <-
tibble(nameSECFull = sec_name, nameSEC = sec_name)
return(df)
}
if (piece_count == 2 &!is_footnote) {
df <-
tibble(nameSECFull = sec_name,
nameTable = pieces[[1]] ,
nameSEC = name_item)
return(df)
}
if (piece_count > 2) {
countItem <-
pieces[2] %>%as.character() %>% readr::parse_number() %>% suppressWarnings()
df <-
tibble(
nameSECFull = sec_name,
nameTable = pieces[[1]] ,
countItem,
nameSEC = name_item
)
return(df)
}
}) %>%
filter(!nameSEC == '')
df_dictionary <-
.sec_form_title_df()
has_missing_names <-
df_names$nameSEC[!df_names$nameSEC %in% df_dictionary$nameSEC] %>%
length() > 0
if (has_missing_names) {
missing <-
df_names$nameSEC[!df_names$nameSEC %in% df_dictionary$nameSEC] %>%
unique()
missing_names <-
missing %>%
paste0(collapse = '\n')
stop(list("Missing:\n", missing_names) %>%
purrr::reduce(paste0))
}
df_names <-
df_names %>%
left_join(df_dictionary) %>%
suppressWarnings() %>%
suppressMessages()
if (!'nameTable' %in% names(df_names)) {
df_names <-
df_names %>%
mutate(nameTable = 'asset')
}
df_names <-
df_names %>%
select(nameTable, nameSECFull, nameSEC, nameActual, everything()) %>%
mutate(nameTable = nameTable %>% str_replace('Id',''),
nameTable = ifelse(nameTable %in% c('issuerCredentials','securitiesIssued'), NA, nameTable)) %>%
suppressWarnings() %>%
suppressMessages()
}
.parse_xml_tables <-
function(url = "https://www.sec.gov/Archives/edgar/data/61004/000114036117000046/doc1.xml"){
page <-
url %>%
xml2::read_xml()
tables <-
page %>%
xml_contents() %>%
xml_name() %>%
unique()
data <-
seq_along(tables) %>%
future_map_dfr(function(x){
table <-
tables[[x]]
if (table %in% c('headerData', 'formData')) {
form_tables <-
page %>% xml_contents() %>% xml_name()
table_loc <-
table %>% grep(form_tables)
xml_nodes <-
page %>%
xml_contents() %>% .[[table_loc]]
}
if (table %in% c('infoTable' , 'assets')) {
xml_nodes <-
page %>%
xml_contents()
}
if (table == 'comment') {
value <-
page %>% xml_contents() %>% xml_text()
df <-
tibble(idTable = x, nameSECFull = table, value)
return(df)
}
tables_special <- c('headerData', 'formData', 'infoTable', 'assets')
if (!table %in% tables_special) {
value_search <-
list('//', table) %>% purrr::reduce(paste0)
xml_nodes <-
page %>%
xml_contents() %>%
xml_find_all(value_search)
}
if (xml_nodes %>% length() > 100) {
list("Be patient there are ", xml_nodes %>% length() %>% formattable::comma(digits = 0), ' nodes to parse') %>%
purrr::reduce(paste0) %>% cat(fill = T)
}
value_list <-
xml_nodes %>% as_list()
value_list <-
value_list[value_list %>% future_map(length) %>% flatten_dbl() > 0]
json_data <-
value_list %>%
jsonlite::toJSON(force = FALSE, dataframe = 'values') %>%
jsonlite::fromJSON(simplifyDataFrame = TRUE, flatten = TRUE)
wrong_output <-
json_data %>% class() == 'array'
if (wrong_output) {
item <-
xml_nodes %>% xml_name()
value <-
xml_nodes %>% xml_text()
json_data <-
tibble(item, value) %>%
spread(item, value)
}
if (json_data %>% length() == 0) {
return(tibble())
}
if ('summaryInfo' %in% names(json_data)) {
json_data <-
seq_along(json_data) %>% map(
function(x){
js_d <- json_data[x]
if ('summaryInfo' %in% names(js_d)) {
if (js_d$summaryInfo$clarificationResponses %>% length() == 0) {
js_d$summaryInfo$clarificationResponses <-
NULL
}
}
return(js_d)
}) %>%
flatten()
json_data <-
json_data[json_data %>% future_map(function(x){data.frame(x, stringsAsFactors = F)} %>% nrow()) > 0]
}
json_data <-
json_data %>%
data.frame(stringsAsFactors = FALSE) %>%
as_tibble() %>%
mutate_all(as.character) %>%
mutate(idTable = x) %>%
gather(nameSECFull, value, -idTable) %>%
arrange(idTable)
return(json_data)
})
data <-
data %>%
mutate(isList = value %>% str_detect('list')) %>%
filter(!isList) %>%
select(-isList) %>%
mutate(
nameSECFull = nameSECFull %>% str_replace_all(
"filerInfo.flags.|filerInfo.filer.|coverPage.|.filer.|\\flags.|filer.credentials.",
''
),
nameSECFull = nameSECFull %>% str_replace_all('filerInfo.|issuerCredentials.', '')
)
rm(tables)
rm(page)
rm(url)
return(data)
}
.parse_sec_form <-
function(url = "https://www.sec.gov/Archives/edgar/data/61004/000114036117000046/doc1.xml",
return_message = TRUE) {
data <-
.parse_xml_tables(url = url)
if (!'nameSECFull' %in% names(data)) {
data <-
data %>%
mutate(nameSECFull = nameSEC)
}
cik <-
url %>% str_replace_all('https://www.sec.gov/Archives/edgar/data/', '') %>% str_split('/') %>% flatten_chr() %>% .[[1]] %>% as.character() %>% readr::parse_number() %>% suppressMessages()
df_title <-
.sec_form_title_df()
is_13FInfo <-
url %>% str_detect('form13fInfoTable.xml|infotable.xml')
sec_names <-
data$nameSECFull %>% unique()
df_names <-
.parse_full_form_names(sec_names = sec_names)
df_names <-
df_names %>%
mutate(nameTable = ifelse(
nameSECFull %>% str_detect("issuerAddress"),
"issuerAddress",
nameTable),
nameTable = ifelse(
nameSECFull %>% str_detect("reportingOwner"),
"reportingOwner",
nameTable)
) %>%
mutate(nameTable = ifelse(nameSECFull %>% str_detect("issuerInfo."), 'issuerInfo', nameTable),
nameTable = ifelse(nameSECFull %>% str_detect("securitiesIssued."), 'securitiesIssued', nameTable),
nameTable = ifelse(nameSECFull %>% str_detect("summaryInfo."), 'summaryInfo', nameTable),
nameTable = ifelse(nameSECFull %>% str_detect("^comment[A-Z]"), 'Comments', nameTable)
)
if (is_13FInfo) {
df_names <-
df_names %>%
mutate(nameTable = 'holdingsInformation')
}
if (!'nameSEC' %in% names(data)) {
data <- data %>%
mutate(nameSEC = nameSECFull)
}
data <-
data %>%
select(-nameSEC) %>%
left_join(df_names) %>%
mutate(nameActual = ifelse(nameSECFull == "X.1.A.A.", 'idForm', nameActual)) %>%
suppressMessages()
if ('countItem' %in% names(data)) {
data <-
data %>%
select(nameTable, countItem, nameSECFull, nameActual, everything()) %>%
mutate(countItem = countItem - 1) %>%
suppressMessages()
}
if ('property' %in% data$nameTable) {
data <-
data %>%
mutate(nameTable = ifelse(nameTable %>% is.na(), 'Asset', nameTable))
}
has_metadata <-
data %>%
filter(nameTable %>% is.na()) %>% nrow() > 0
if (has_metadata) {
df_metadata <-
data %>%
filter(nameTable %>% is.na()) %>%
select(nameActual, value) %>%
group_by(nameActual) %>%
mutate(countItem = 1:n() - 1) %>%
arrange(countItem) %>%
ungroup() %>%
filter(!nameActual %>% str_detect('idCCC')) %>%
mutate(nameActual = ifelse(countItem == 0, nameActual, nameActual %>% paste0(countItem))) %>%
select(-countItem)
col_order <-
df_metadata$nameActual
df_metadata <-
df_metadata %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
mutate(urlSECFiling = url) %>%
.resolve_form_columns()
} else {
df_metadata <-
tibble(idCIKFiler = cik,
urlSECFiling = url)
}
tables <-
data %>%
filter(!nameTable %>% is.na()) %>%
.$nameTable %>%
unique()
data <-
seq_along(tables) %>%
future_map(function(x) {
table <-
tables[[x]]
table_name <-
list('data',
table %>% substr(1, 1) %>% str_to_upper(),
table %>% substr(2, nchar(table))) %>%
purrr::reduce(paste0)
table_df <-
data %>%
filter(nameTable == table) %>%
select(dplyr::matches("countItem"), nameActual, value) %>%
select(which(colMeans(is.na(.)) < 1)) %>%
group_by(nameActual) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup()
has_counts <-
table_df$countItem %>% max(na.rm = TRUE) > 0
if (has_counts) {
table_df <-
table_df %>%
arrange(countItem)
col_order <- c('countItem', table_df$nameActual)
table_df <-
table_df %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
mutate(urlSECFiling = url) %>%
.resolve_form_columns()
table_df <-
table_df %>%
nest(-urlSECFiling, .key = data)
} else {
table_df <-
table_df %>%
select(-countItem)
col_order <- c(table_df$nameActual)
table_df <-
table_df %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
.resolve_form_columns() %>%
mutate(urlSECFiling = url)
table_df <-
table_df %>%
nest(-urlSECFiling, .key = data)
}
names(table_df)[[2]] <-
table_name
df_metadata <-
df_metadata %>%
left_join(table_df) %>%
suppressMessages()
}) %>%
reduce(left_join) %>%
suppressMessages()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
rm(df_metadata)
return(data)
}
.parse_form_data <-
function(.all_filings, filter_parameter = 'isXBRLInstanceFile', return_message = TRUE) {
df_search <-
.all_filings %>%
filter_(.dots = filter_parameter)
if (filter_parameter == 'isXBRLInstanceFile') {
if (df_search %>% nrow() == 0) {
return(tibble())
}
parse_xbrl_filer_url_safe <-
purrr::possibly(.parse_xbrl_filer_url, tibble())
all_data <-
df_search$urlSECFiling %>%
unique() %>%
future_map_dfr(function(x) {
.parse_xbrl_filer_url(url = x, return_message = return_message)
})
all_data <-
all_data %>%
select(-dplyr::matches("idCIK1|nameFiler1")) %>%
left_join(df_search %>% select(idForm, idAccession, nameFile, dateFiling, urlSECFiling)) %>%
select(
dplyr::matches("idCIK"),
dplyr::matches("name[Entity]|name[Filer]"),
dateFiling,
idForm,
idAccession,
nameFile,
everything()
) %>%
suppressMessages()
return(all_data)
}
if (filter_parameter == 'isFormD') {
if ('idForm' %in% names(df_search)){
df_search <-
df_search %>%
filter(!idForm %>% str_detect("10"))
}
}
if (df_search %>% nrow() == 0) {
return(tibble())
}
all_data <-
df_search$urlSECFiling %>%
unique() %>%
future_map_dfr(function(x) {
.parse_sec_form(url = x, return_message = return_message)
})
all_data <-
all_data %>%
select(-dplyr::matches("idCIK1|nameFiler1")) %>%
left_join(df_search %>% select(dplyr::matches("idForm"), dplyr::matches("idAccession"), dplyr::matches("nameFile"), dplyr::matches("dateFiling"), urlSECFiling)) %>%
select(
dplyr::matches("idCIK"),
dplyr::matches("name[Entity]|name[Filer]"),
dateFiling,
dplyr::matches("idForm"),
dplyr::matches("idAccession"),
dplyr::matches("nameFile"),
everything()
) %>%
suppressMessages()
if (filter_parameter == 'hasAssetFile') {
if('dataComments' %in% names(all_data)) {
df_comments <-
all_data %>%
select(idCIKFiler, idAccession, dataComments) %>%
mutate(isNULL = dataComments %>% map_lgl(is_null)) %>%
filter(!isNULL) %>%
distinct() %>%
select(-isNULL)
all_data <-
all_data %>%
select(-dataComments) %>%
mutate(isNULL = dataAsset %>% map_lgl(is_null)) %>%
filter(!isNULL) %>%
filter(!nameFile == "ASSET RELATED DOCUMENT") %>%
distinct() %>%
select(-isNULL) %>%
left_join(df_comments) %>%
suppressMessages()
}
}
return(all_data)
}
.parse_xbrl_filer_url <-
function(url = "https://www.sec.gov/Archives/edgar/data/1037540/000165642316000023/bxp-20160930.xml",
return_message = TRUE) {
options(stringsAsFactors = FALSE, scipen = 999999)
cik <-
url %>%
str_split('data/') %>%
flatten_chr() %>%
.[[2]] %>%
str_split('/') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
td <-
tempdir()
tf <-
tempfile(tmpdir = td, fileext = ".xml")
url %>%
curl::curl_download(destfile = tf)
doc <-
tf %>%
XBRL::xbrlParse()
df_fct <-
XBRL::xbrlProcessFacts(doc) %>%
as_tibble()
df_fct <-
df_fct %>%
mutate(
isNumber = ifelse(!fact %>% as.character() %>% readr::parse_number() %>% is.na(), TRUE, FALSE),
amountFact = ifelse(isNumber == TRUE, fact %>% as.character() %>% readr::parse_number(), NA)
) %>%
separate(elementId,
c('codeElement', 'nameElement'),
sep = '\\_',
remove = FALSE) %>%
suppressWarnings()
df_cts <-
XBRL::xbrlProcessContexts(doc) %>%
as_tibble()
df_unt <-
XBRL::xbrlProcessUnits(doc) %>%
as_tibble()
df_sch <-
XBRL::xbrlGetSchemaName(doc) %>%
as_tibble()
df_footnotes <-
XBRL::xbrlProcessFootnotes(doc) %>%
as_tibble()
XBRL::xbrlFree(doc)
url_xsd <-
url %>% str_replace(".xml", ".xsd")
url_xsd %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_rls <-
docS %>%
XBRL::xbrlProcessRoles() %>%
as_tibble()
url_cal <-
url %>% str_replace(".xml", "_cal.xml")
if (httr::url_ok(url_cal) %>% suppressWarnings()){
url_cal %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_calcs <-
docS %>%
XBRL::xbrlProcessArcs(arcType = 'calculation') %>%
as_tibble()
} else {
df_calcs <-
tibble()
}
url_def <-
url %>% str_replace(".xml", "_def.xml")
url_def %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_defs <-
docS %>%
XBRL::xbrlProcessArcs(arcType = 'definition') %>%
as_tibble()
url_lab <-
url %>% str_replace(".xml", "_lab.xml")
url_lab %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_labels <-
docS %>%
XBRL::xbrlProcessLabels() %>%
as_tibble()
url_pre <-
url %>% str_replace(".xml", "_pre.xml")
url_pre %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
tf %>%
unlink()
data <-
tibble(
idCIK = cik,
urlSECFiling = url,
dataFacts = list(df_fct),
dataContexts = list(df_cts),
dataUnits = list(df_unt),
dataFootnotes = list(df_footnotes),
dataRoles = list(df_rls),
dataCalculations = list(df_calcs) ,
dataDefinitions = list(df_defs),
dataLabel = list(df_labels)
)
td %>% unlink()
tf %>% unlink()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(data)
}
.sec_form_title_df <-
function() {
tibble(
nameSEC = c(
"conversionOrExercisePrice",
"deemedExecutionDate",
"directOrIndirectOwnership",
"documentType",
"equitySwapInvolved",
"exerciseDate",
"expirationDate",
"footnote",
"isDirector",
"isOfficer",
"isOther",
"issuerCik",
"issuerName",
"issuerTradingSymbol",
"isTenPercentOwner",
"natureOfOwnership",
"noSecuritiesOwned",
"notSubjectToSection16",
"officerTitle",
"otherText",
"periodOfReport",
"postTransactionAmountsOwnedFollowingTransaction",
"remarks",
"rptOwnerCik",
"rptOwnerCity",
"rptOwnerName",
"rptOwnerState",
"rptOwnerStateDescription",
"rptOwnerStreet1",
"rptOwnerStreet2",
"rptOwnerZipCode",
"schemaVersion",
"securityTitle",
"sharesOwnedFollowingTransaction",
"signatureDate",
"signatureName",
"transactionAcquiredDisposedCode",
"transactionCode",
"transactionDate",
"transactionFormType",
"transactionPricePerShare",
"transactionShares",
"transactionTimeliness",
"transactionTotalValue",
"underlyingSecurityShares",
"underlyingSecurityTitle",
"clarificationOfResponse", "isBusinessCombinationTransaction",
"cik", "moreThanOneYear", "previousName", "edgarPreviousNameList",
"entityName", "entityType", "entityTypeOtherDesc", "federalExemptionsExclusions",
"industryGroupType", "investmentFundType", "investmentFundInfo",
"hasNonAccreditedInvestors", "numberNonAccreditedInvestors",
"totalNumberAlreadyInvested", "city", "stateOrCountry", "stateOrCountryDescription",
"street1", "street2", "zipCode", "issuerPhoneNumber", "issuerPreviousNameList",
"jurisdictionOfInc", "overFiveYears", "yearOfInc", "withinFiveYears",
"yetToBeFormed", "aggregateNetAssetValueRange", "revenueRange",
"minimumInvestmentAccepted", "totalAmountSold", "totalOfferingAmount",
"totalRemaining", "firstName", "lastName", "middleName", "relationship",
"relationshipClarification", "dollarAmount", "isEstimate", "associatedBDCRDNumber",
"associatedBDName", "foreignSolicitation", "recipientCRDNumber",
"recipientName", "description", "state", "statesOfSolicitationList",
"authorizedRepresentative", "nameOfSigner", "signatureTitle",
"submissionType", "testOrLive", "dateOfFirstSale", "yetToOccur",
"isAmendment", "descriptionOfOtherType", "isDebtType", "isEquityType",
"isMineralPropertyType", "isOptionToAcquireType", "isOtherType",
"isPooledInvestmentFundType", "isSecurityToBeAcquiredType", "isTenantInCommonType",
'notSubjectToSection16', 'rptOwnerStreet1', 'rptOwnerStreet2',
"liveTestFlag", "confirmingCopyFlag", "returnCopyFlag", "overrideInternetFlag",
"ccc", "reportCalendarOrQuarter", "filingManagername", "filingManageraddressstreet1",
"filingManageraddressstreet2", "filingManageraddresscity", "filingManageraddressstateOrCountry",
'filingManagerstateOrCountryDescription',
"filingManageraddresszipCode", "reportType", "form13FFileNumber",
"provideInfoForInstruction5", "name", "title", "phone", "signature",
"otherIncludedManagersCount", "tableEntryTotal", "tableValueTotal",
"isConfidentialOmitted",
"nameOfIssuer", "titleOfClass", "cusip", "value", "investmentDiscretion",
"otherManager", "putCall", "sshPrnamt", "sshPrnamtType", "Sole",
"Shared", "None",
"offeringFileNumber", "sinceLastFiling", "jurisdictionOrganization",
"yearIncorporation", "sicCode", "irsNum", "fullTimeEmployees",
"partTimeEmployees", "phoneNumber", "connectionName", "industryGroup",
"cashEquivalents", "investmentSecurities", "accountsReceivable",
"propertyPlantEquipment", "totalAssets", "accountsPayable", "longTermDebt",
"totalLiabilities", "totalStockholderEquity", "totalLiabilitiesAndEquity",
"totalRevenues", "costAndExpensesApplToRevenues", "depreciationAndAmortization",
"netIncome", "earningsPerShareBasic", "earningsPerShareDiluted",
"nameAuditor", "commonEquityClassName", "outstandingCommonEquity",
"commonCusipEquity", "publiclyTradedCommonEquity", "preferredEquityClassName",
"outstandingPreferredEquity", "preferredCusipEquity", "publiclyTradedPreferredEquity",
"debtSecuritiesClassName", "outstandingDebtSecurities", "cusipDebtSecurities",
"publiclyTradedDebtSecurities", "certifyIfTrue", "certifyIfNotDisqualified",
"summaryInfo", "financialStatementAuditStatus", "securitiesOfferedTypes",
"offerDelayedContinuousFlag", "offeringYearFlag", "offeringAfterQualifFlag",
"offeringBestEffortsFlag", "solicitationProposedOfferingFlag",
"resaleSecuritiesAffiliatesFlag", "securitiesOffered", "outstandingSecurities",
"pricePerSecurity", "issuerAggregateOffering", "securityHolderAggegate",
"qualificationOfferingAggregate", "concurrentOfferingAggregate",
"totalAggregateOffering", "underwritersServiceProviderName",
"underwritersFees", "auditorServiceProviderName", "auditorFees",
"legalServiceProviderName", "legalFees", "promotersServiceProviderName",
"promotersFees", "brokerDealerCrdNumber", "estimatedNetAmount",
"clarificationResponses", "jurisdictionsOfSecOfferedSame", "issueJuridicationSecuritiesOffering",
"dealersJuridicationSecuritiesOffering", "securitiesIssuerName",
"securitiesIssuerTitle", "securitiesIssuedTotalAmount", "securitiesPrincipalHolderAmount",
"securitiesIssuedAggregateAmount", "securitiesActExcemption",
"certifyIfBadActor", "salesCommissionsServiceProviderName",
"salesCommissionsServiceProviderFees", "jurisdictionsOfSecOfferedNone",
"ifUnregsiteredNone", "blueSkyServiceProviderName", "blueSkyFees",
'indicateTier1Tier2Offering', 'X.1.A.A.', 'X.1.A.A.', 'aggregateConsiderationBasis',
'findersFeesServiceProviderName' , 'finderFeesFee',
'loans', 'propertyAndEquipment', 'deposits', 'totalInterestIncome',
'totalInterestExpenses', 'securitiesOfferedOtherDesc', 'comment',
"assetTypeNumber",
"assetNumber",
"assetGroupNumber",
"reportPeriodBeginningDate",
"reportPeriodEndDate",
"issuerName",
"originalIssuanceDate",
"originalSecurityAmount",
"originalSecurityTermNumber",
"securityMaturityDate",
"originalAmortizationTermNumber",
"originalInterestRatePercentage",
"accrualTypeCode",
"interestRateTypeCode",
"originalInterestOnlyTermNumber",
"firstPaymentDate",
"underwritingIndicator",
"securityTitleName",
"denominationNumber",
"currencyName",
"trusteeName",
"secFileNumber",
"cik",
"callableIndicator",
"paymentFrequencyCode",
"zeroCouponIndicator",
"assetAddedIndicator",
"assetModifiedIndicator",
"reportPeriodBeginningAssetBalanceAmount",
"reportPeriodBeginningScheduledAssetBalanceAmount",
"reportPeriodScheduledPaymentAmount",
"reportPeriodInterestRatePercentage",
"totalActualPaidAmount",
"actualInterestCollectionPercentage",
"actualPrincipalCollectedAmount",
"actualOtherCollectionAmount",
"otherPrincipalAdjustmentAmount",
"otherInterestAdjustmentAmount",
"scheduledInterestAmount",
"scheduledPrincipalAmount",
"endReportingPeriodActualBalanceAmount",
"endReportingPeriodScheduledBalanceAmount",
"servicingFeePercentage",
"servicingFlatFeeAmount",
"zeroBalanceCode",
"zeroBalanceEffectiveDate",
"remainingTermToMaturityNumber",
"currentDelinquentStatusNumber",
"paymentPastDueDaysNumber",
"paymentPastDueNumber",
"nextReportPeriodPaymentDueAmount",
"nextDueDate",
"primaryLoanServicerName",
"mostRecentServicingTransferReceivedDate",
"assetSubjectToDemandIndicator",
"statusAssetSubjectToDemandCode",
"repurchaseAmount",
"demandResolutionDate",
"repurchaserName",
"repurchaseReplacementReasonCode",
"reportPeriodBeginDate",
"originalLoanPurposeCode",
"originatorName",
"originalLoanAmount",
"originalLoanMaturityDate",
"originalInterestRateTypeCode",
"originalLienPositionCode",
"mostRecentJuniorLoanBalanceAmount",
"mostRecentJuniorLoanBalanceDate",
"mostRecentSeniorLoanAmount",
"mostRecentSeniorLoanAmountDate",
"loanTypeMostSeniorLienCode",
"mostSeniorLienHybridPeriodNumber",
"mostSeniorLienNegativeAmortizationLimitPercentage",
"mostSeniorLienOriginationDate",
"prepaymentPenaltyIndicator",
"negativeAmortizationIndicator",
"modificationIndicator",
"modificationNumber",
"mortgageInsuranceRequirementIndicator",
"balloonIndicator",
"coveredHighCostCode",
"servicerHazardInsuranceCode",
"refinanceCashOutAmount",
"totalOriginationDiscountAmount",
"brokerIndicator",
"channelCode",
"nationalMortgageLicenseSystemCompanyNumber",
"buyDownNumber",
"loanDelinquencyAdvanceNumber",
"originationARMIndexCode",
"armMarginPercentage",
"fullyIndexedRatePercentage",
"initialFixedRatePeriodHybridARMNumber",
"initialInterestRateDecreasePercentage",
"initialInterestRateIncreasePercentage",
"indexLookbackNumber",
"subsequentInterestRateResetNumber",
"lifetimeRateCeilingPercentage",
"lifetimeRateFloorPercentage",
"subsequentInterestRateDecreasePercentage",
"subsequentInterestRateIncreasePercentage",
"subsequentPaymentResetNumber",
"armRoundCode",
"armRoundPercentage",
"optionArmIndicator",
"paymentMethodAfterRecastCode",
"initialMinimumPaymentAmount",
"convertibleIndicator",
"HELOCIndicator",
"HELOCDrawNumber",
"prepaymentPenaltyCalculationCode",
"prepaymentPenaltyTypeCode",
"prepaymentPenaltyTotalTermNumber",
"prepaymentPenaltyHardTermNumber",
"negativeAmortizationLimitAmount",
"negativeAmortizationInitialRecastNumber",
"negativeAmortizationSubsequentRecastNumber",
"negativeAmortizationBalanceAmount",
"initialFixedPaymentNumber",
"initialPaymentCapPercentage",
"subsequentPaymentCapPercentage",
"initialMinimumPaymentResetNumber",
"subsequentMinimumPaymentResetNumber",
"minimumPaymentAmount",
"geographicalLocation",
"occupancyStatusCode",
"mostRecentOccupancyStatusCode",
"propertyTypeCode",
"mostRecentPropertyValueAmount",
"mostRecentPropertyValueTypeCode",
"mostRecentPropertyValueDate",
"mostRecentAVMModelCode",
"mostRecentAVMConfidenceNumber",
"originalCLTVPercentage",
"originalLTVPercentage",
"originalObligorNumber",
"originalObligorCreditScoreNumber",
"originalObligorCreditScoreType",
"mostRecentObligorCreditScoreNumber",
"mostRecentObligorCreditScoreType",
"mostRecentObligorCreditScoreDate",
"obligorIncomeVerificationLevelCode",
"IRSForm4506TIndicator",
"originatorFrontEndDTIPercentage",
"originatorBackEndDTIPercentage",
"obligorEmploymentVerificationCode",
"obligorEmploymentLengthCode",
"obligorAssetVerificationCode",
"originalPledgedAssetsAmount",
"qualificationMethodCode",
"mortgageInsuranceCompanyName",
"mortgageInsuranceCoveragePercentage",
"poolInsuranceCompanyName",
"poolInsuranceStopLossPercentage",
"mortgageInsuranceCoverageTypeCode",
"modificationIndicatorReportingPeriod",
"nextPaymentDueDate",
"advancingMethodCode",
"servicingAdvanceMethodologyCode",
"stopPrincipalInterestAdvancingDate",
"reportingPeriodBeginningLoanBalanceAmount",
"reportingPeriodBeginningScheduledLoanBalanceAmount",
"nextReportingPeriodPaymentDueAmount",
"reportingPeriodInterestRatePercentage",
"nextInterestRatePercentage",
"otherAssessedUncollectedServicerFeeamount",
"otherServicingFeeRetainedByServicerAmount",
"reportingPeriodEndActualBalanceAmount",
"reportingPeriodEndScheduledBalanceAmount",
"reportingPeriodScheduledPaymentAmount",
"actualInterestCollectedAmount",
"actualOtherCollectedAmount",
"paidThroughDate",
"interestPaidThroughDate",
"paidFullAmount",
"servicerAdvancedPrincipalAmount",
"servicerAdvancedRepaidPrincipalAmount",
"servicerAdvancedCumulativePrincipalAmount",
"servicerAdvanceInterestAmount",
"servicerAdvanceRepaidInterestAmount",
"servicerAdvanceCumulativeInterestAmount",
"servicerAdvanceTaxesInsuranceAmount",
"servicerAdvanceRepaidTaxesInsuranceAmount",
"servicerAdvanceCumulativeTaxesInsuranceAmount",
"servicerAdvanceCorporateAmount",
"servicerAdvanceRepaidCorporateAmount",
"servicerAdvanceCumulativeCorporateAmount",
"mostRecentTwelveMonthHistoryCode",
"nextResetRatePercentage",
"nextPaymentChangeDate",
"nextInterestRateChangeDate",
"nextResetPaymentAmount",
"exercisedArmConversionOptionIndicator",
"primaryServicerName",
"masterServicerName",
"specialServicerName",
"subServicerName",
"assetSubjectDemandIndicator",
"assetSubjectDemandStatusCode",
"repurchaseReplacementCode",
"chargeOffPrincipalAmount",
"chargeOffInterestAmount",
"lossMitigationTypeCode",
"mostRecentLoanModificationEventCode",
"mostRecentLoanModificationEffectiveDate",
"postModificationMaturityDate",
"postModificationInterestRateTypeCode",
"postModificationAmortizationTypeCode",
"postModificationInterestPercentage",
"postModificationFirstPaymentDate",
"postModificationLoanBalanceAmount",
"postModificationPrincipalInterestPaymentAmount",
"totalCapAmount",
"incomeVerificationIndicatorAtModification",
"modificationFrontEndDebtToIncomePercentage",
"modificationBackEndDebtToIncomePercentage",
"totalDeferredAmount",
"forgivenPrincipalCumulativeAmount",
"forgivenPrincipalReportingPeriodAmount",
"forgivenInterestCumulativeAmount",
"forgivenInterestReportingPeriodAmount",
"actualEndingBalanceTotalDebtAmount",
"scheduledEndingBalanceTotalDebtAmount",
"postModificationARMCode",
"postModificationARMIndexCode",
"postModificationMarginPercentage",
"postModificationInterestResetNumber",
"postModificationNextResetDate",
"postModificationIndexLookbackNumber",
"postModificationARMRoundingCode",
"postModificationARMRoundingPercentage",
"postModificationInitialMinimumPayment",
"postModificationNextPaymentAdjustmentDate",
"postModificationARMPaymentRecastFrequency",
"postModificationLifetimeFloorPercentage",
"postModificationLifetimeCeilingPercentage",
"postModificationInitialInterestRateIncreasePercentage",
"postModificationInitialInterestRateDecreasePercentage",
"postModificationSubsequentInterestIncreasePercentage",
"postModificationSubsequentInterestRateDecreasePercentage",
"postModificationPaymentCapPercentage",
"postModificationPaymentMethodAfterRecastCode",
"postModificationARMInterestRateTeaserNumber",
"postModificationARMPaymentTeaserNumber",
"postModificationARMNegativeAmortizationIndicator",
"postModificationARMNegativeAmortizationCapPercentage",
"postModificationInterestOnlyTermNumber",
"postModificationInterestOnlyLastPaymentDate",
"postModificationBalloonAmount",
"postModificationInterestRateStepIndicator",
"postModificationStepInterestPercentage",
"postModificationStepDate",
"postModificationStepPrincipalInterestPaymentAmount",
"postModificationStepNumber",
"postModificationMaximumFutureStepAgreementPercentage",
"postModificationMaximumStepAgreementRateDate",
"nonInterestBearingDeferredPrincipalCumulativeAmount",
"nonInterestBearingDeferredPrincipalReportingPeriodAmount",
"recoveryDeferredPrincipalReportingPeriodAmount",
"nonInterestBearingDeferredPaidFullAmount",
"nonInterestBearingDeferredInterestFeeReportingPeriodAmount",
"nonInterestBearingDeferredInterestFeeCumulativeAmount",
"recoveryDeferredInterestFeeReportingPeriodAmount",
"mostRecentForbearancePlanOrTrialModificationStartDate",
"mostRecentForbearancePlanOrTrialModificationScheduledEndDate",
"mostRecentTrialModificationViolatedDate",
"mostRecentRepaymentPlanStartDate",
"mostRecentRepaymentPlanScheduledEndDate",
"mostRecentRepaymentPlanViolatedDate",
"shortSaleAcceptedOfferAmount",
"mostRecentLossMitigationExitDate",
"mostRecentLossMitigationExitCode",
"attorneyReferralDate",
"foreclosureDelayReasonCode",
"foreclosureExitDate",
"foreclosureExitReasonCode",
"noticeOfIntentDate",
"mostRecentAcceptedREOOfferAmount",
"mostRecentAcceptedREOOfferDate",
"grossLiquidationProceedsAmount",
"netSalesProceedsAmount",
"reportingPeriodLossPassedToIssuingEntityAmount",
"cumulativeTotalLossPassedToIssuingEntityAmount",
"subsequentRecoveryAmount",
"evictionIndicator",
"reoExitDate",
"reoExitReasonCode",
"UPBLiquidationAmount",
"servicingFeesClaimedAmount",
"servicerAdvanceReimbursedPrincipalAmount",
"servicerAdvanceReimbursedInterestAmount",
"servicerAdvanceReimbursedTaxesInsuranceAmount",
"servicerAdvanceReimbursedCorporateAmount",
"REOManagementFeesAmount",
"cashKeyDeedAmount",
"performanceIncentiveFeesAmount",
"mortgageInsuranceClaimFiledDate",
"mortgageInsuranceClaimAmount",
"mortgageInsuranceClaimPaidDate",
"mortgageInsuranceClaimPaidAmount",
"mortgageInsuranceClaimDeniedRescindedDate",
"marketableTitleTransferDate",
"nonPayStatusCode",
"reportingActionCode",
"GroupID",
"reportingPeriodBeginningDate",
"reportingPeriodEndDate",
"originationDate",
"originalTermLoanNumber",
"maturityDate",
"interestRateSecuritizationPercentage",
"interestAccrualMethodCode",
"firstLoanPaymentDueDate",
"lienPositionSecuritizationCode",
"loanStructureCode",
"paymentTypeCode",
"periodicPrincipalAndInterestPaymentSecuritizationAmount",
"scheduledPrincipalBalanceSecuritizationAmount",
"NumberPropertiesSecuritization",
"NumberProperties",
"graceDaysAllowedNumber",
"interestOnlyIndicator",
"prepaymentPremiumIndicator",
"modifiedIndicator",
"armIndexCode",
"firstRateAdjustmentDate",
"firstPaymentAdjustmentDate",
"armMarginNumber",
"lifetimeRateCapPercentage",
"periodicRateIncreaseLimitPercentage",
"periodicRateDecreaseLimitPercentage",
"periodicPaymentAdjustmentMaximumAmount",
"periodicPaymentAdjustmentMaximumPercent",
"rateResetFrequencyCode",
"paymentResetFrequencyCode",
"indexLookbackDaysNumber",
"prepaymentLockOutEndDate",
"yieldMaintenanceEndDate",
"prepaymentPremiumsEndDate",
"maximumNegativeAmortizationAllowedPercentage",
"maximumNegativeAmortizationAllowedAmount",
"negativeAmortizationDeferredInterestCapAmount",
"deferredInterestCumulativeAmount",
"deferredInterestCollectedAmount",
"property",
"reportPeriodModificationIndicator",
"reportPeriodBeginningScheduleLoanBalanceAmount",
"totalScheduledPrincipalInterestDueAmount",
"servicerTrusteeFeeRatePercentage",
"unscheduledPrincipalCollectedAmount",
"reportPeriodEndActualBalanceAmount",
"reportPeriodEndScheduledLoanBalanceAmount",
"hyperAmortizingDate",
"servicingAdvanceMethodCode",
"nonRecoverabilityIndicator",
"totalPrincipalInterestAdvancedOutstandingAmount",
"totalTaxesInsuranceAdvancesOutstandingAmount",
"otherExpensesAdvancedOutstandingAmount",
"paymentStatusLoanCode",
"armIndexRatePercentage",
"nextInterestRateChangeAdjustmentDate",
"nextPaymentAdjustmentDate",
"mostRecentSpecialServicerTransferDate",
"mostRecentMasterServicerReturnDate",
"realizedLossToTrustAmount",
"liquidationPrepaymentCode",
"liquidationPrepaymentDate",
"prepaymentPremiumYieldMaintenanceReceivedAmount",
"workoutStrategyCode",
"lastModificationDate",
"modificationCode",
"postModificationPaymentAmount",
"postModificationAmortizationPeriodAmount",
"propertyName",
"propertyAddress",
"propertyCity",
"propertyState",
"propertyZip",
"propertyCounty",
"netRentableSquareFeetNumber",
"netRentableSquareFeetSecuritizationNumber",
"unitsBedsRoomsNumber",
"unitsBedsRoomsSecuritizationNumber",
"yearBuiltNumber",
"yearLastRenovated",
"valuationSecuritizationAmount",
"valuationSourceSecuritizationCode",
"valuationSecuritizationDate",
"mostRecentValuationAmount",
"mostRecentValuationDate",
"mostRecentValuationSourceCode",
"physicalOccupancySecuritizationPercentage",
"mostRecentPhysicalOccupancyPercentage",
"propertyStatusCode",
"defeasanceOptionStartDate",
"DefeasedStatusCode",
"largestTenant",
"squareFeetLargestTenantNumber",
"leaseExpirationLargestTenantDate",
"secondLargestTenant",
"squareFeetSecondLargestTenantNumber",
"leaseExpirationSecondLargestTenantDate",
"thirdLargestTenant",
"squareFeetThirdLargestTenantNumber",
"leaseExpirationThirdLargestTenantDate",
"financialsSecuritizationDate",
"mostRecentFinancialsStartDate",
"mostRecentFinancialsEndDate",
"revenueSecuritizationAmount",
"mostRecentRevenueAmount",
"operatingExpensesSecuritizationAmount",
"operatingExpensesAmount",
"netOperatingIncomeSecuritizationAmount",
"mostRecentNetOperatingIncomeAmount",
"netCashFlowFlowSecuritizationAmount",
"mostRecentNetCashFlowAmount",
"netOperatingIncomeNetCashFlowSecuritizationCode",
"netOperatingIncomeNetCashFlowCode",
"mostRecentDebtServiceAmount",
"debtServiceCoverageNetOperatingIncomeSecuritizationPercentage",
"mostRecentDebtServiceCoverageNetOperatingIncomePercentage",
"debtServiceCoverageNetCashFlowSecuritizationPercentage",
"mostRecentDebtServiceCoverageNetCashFlowpercentage",
"debtServiceCoverageSecuritizationCode",
"mostRecentDebtServiceCoverageCode",
"mostRecentAnnualLeaseRolloverReviewDate",
"reportingPeriodEndingDate",
"originalLoanTerm",
"loanMaturityDate",
"interestCalculationTypeCode",
"originalFirstPaymentDate",
"gracePeriodNumber",
"subvented",
"vehicleManufacturerName",
"vehicleModelName",
"vehicleNewUsedCode",
"vehicleModelYear",
"vehicleTypeCode",
"vehicleValueAmount",
"vehicleValueSourceCode",
"obligorCreditScoreType",
"obligorCreditScore",
"coObligorIndicator",
"paymentToIncomePercentage",
"obligorGeographicLocation",
"reportingPeriodModificationIndicator",
"nextReportingPeriodPaymentAmountDue",
"otherServicerFeeRetainedByServicer",
"otherAssessedUncollectedServicerFeeAmount",
"reportingPeriodActualEndBalanceAmount",
"totalActualAmountPaid",
"servicerAdvancedAmount",
"currentDelinquencyStatus",
"chargedoffPrincipalAmount",
"recoveredAmount",
"modificationTypeCode",
"paymentExtendedNumber",
"repossessedIndicator",
"repossessedProceedsAmount",
"reportingPeriodBeginDate",
"acquisitionCost",
"originalLeaseTermNumber",
"scheduledTerminationDate",
"gracePeriod",
"baseResidualValue",
"baseResidualSourceCode",
"contractResidualValue",
"lesseeCreditScoreType",
"lesseeCreditScore",
"lesseeIncomeVerificationLevelCode",
"lesseeEmploymentVerificationCode",
"coLesseePresentIndicator",
"lesseeGeographicLocation",
"remainingTermNumber",
"reportingPeriodSecuritizationValueAmount",
"securitizationDiscountRate",
"otherLeaseLevelServicingFeesRetainedAmount",
"reportingPeriodEndingActualBalanceAmount",
"reportingPeriodEndActualSecuritizationAmount",
"primaryLeaseServicerName",
"DemandResolutionDate",
"repurchaseOrReplacementReasonCode",
"chargedOffAmount",
"leaseExtended",
"terminationIndicator",
"excessFeeAmount",
"liquidationProceedsAmount",
"commentNumber", "commentColumn", "commentDescription",
'previousAccessionNumber', 'itemNumber', 'fieldName', 'notes'
),
nameActual = c(
"priceExerciseConversion",
"dateDeemedExecution",
"codeOwnershipDirectIndirect",
"idDocument",
"isEquitySwapInvolved",
"dateExercised",
"dateExpiration",
"descriptionFootnote",
"isDirector",
"isOfficer",
"isOther",
"idCIKIssuer",
"nameIssuer",
"idTickerIssuer",
"isTenPercentOwner",
"descriptionNatureOfOwnership",
"isNoSecuritiesOwned",
"isNotSubjectToSection16",
"titleOfficer",
"descriptionOtherText",
"dateReport",
"countSharesOwnedPostTransaction",
"descriptionRemarks",
"idCIKOwner",
"cityOwenr",
"nameOwner",
"stateOwner",
"descriptionStateOwner",
"addressStreet1Owner",
"addressStreet2Owner",
"zipcodeOwner",
"idSchema",
"titleSecurity",
"countSharesOwnedPostTransaction",
"dateSignature",
"nameSignature",
"codeTransactionAcquiredDisposed",
"codeTransaction",
"dateTransaction",
"idFormTransaction",
"pricePerShareTransaction",
"countSharesTransaction",
"idCodeTimelinessTransaction",
"amountTransaction",
"countSharesUnderlying",
"titleSecurityUnderlying",
"descriptionResponse", "isBusinessCombinationTransaction",
"idCIK", "isMoreThanOneYear", "nameEntityPrevius", "listNameEntityPreviousEDGAR",
"nameEntity", "typeEntity", "descriptionEntityTypeOther", "idFederalExemptionsExclusions",
"typeIndustryGroup", "typeInvestmentFund", "descriptionInvestmentFund",
"hasNonAccreditedInvestors", "countInvestorsNonAccredited",
"countInvestorsActive", "cityEntity", "stateEntity", "descriptionStateEntity",
"addressStreet1Entity", "addressStreet2Entity", "zipcodeEntity", "phoneNumberEntity", "listIssuerPreviousName",
"jurisdictionOfInc", "isOverFiveYearsOld", "hasYearOfInc", "isFormedWithinFiveYears",
"isYetToBeFormed", "rangeAgregateNetAssetValue", "rangeRevenue",
"amountInvestmentMinimum", "amountSoldTotal", "amountOfferingTotal",
"amountRemaining", "nameFirst", "nameLast", "nameMiddle", "relationshipEntity",
"descriptionRelationship", "amountDollars", "isEstimate", "idCRDBroker",
"nameBroker", "isForeignSolicitation", "idCRDRecipient",
"nameRecipient", "stateDescription", "state", "listStatesSolicitation",
"isAuthorizedRepresentative", "nameSignatory", "titleSignatory",
"idForm", "codeTestOrLive", "dateFirstSale", "isYetToOccur",
"isAmendment", "descriptionOtherType", "isDebtType", "isEquityType",
"isMineralPropertyType", "isOptionToAcquireType", "isOtherType",
"isPooledInvestmentFundType", "isSecurityToBeAcquiredType", "isTenantInCommonType",
'isNotSubjectToSection16', 'addressStreet1Owner', 'addressStreet2Owner',
"isLiveTestFlag", "isConfirmingCopyFlag", "isReturnCopyFlag", "isOverrideInternetFlag",
"idCCC", "dateReportCalendarOrQuarter", "nameFilingManager", "addressStreet1FilingManager",
"addressStreet2FilingManager", "cityFilingManager", "stateFilingManager",
'descriptionStateFilingManager',
"zipcodeFilingManager", "typeReport", "idSEC",
"codeProvideInfoForInstruction5", "nameEntity", "titleEntity", "phoneEntity", "signatureEntity",
"countOtherIncludedManagers", "countTableEntries", "amountValueHoldings",
"isConfidentialOmitted", "nameIssuer", "classSecurities", "idCUSIP", "valueSecurities", "typeInvestmentDiscretion",
"descriptionOtherManager", "codePutCall", "countSharesPrincipal", "codeSharesPrincipal", "countSharesVotingSole",
"countSharesVotingShared", "countSharesVotingNone",
"idSEC", "isSinceLastFiling", "codeJurisdictionOrganization",
"yearIncorporation", "idSIC", "idIRS", "countEmployeesFullTime",
"countEmployeesPartTime", "phoneEntity", "nameConnection", "nameIndustry",
"amountCashEquivalents", "amountInvestmentSecurities", "amountAccountsReceivable",
"amountPropertyPlantEquipment", "amountAssetsTotal", "amountAccountsPayable", "amountLongTermDebt",
"amountLiabilitiesTotal", "amountStockholderEquityTotal", "amountLiabilitiesAndEquityTotal",
"amountRevenuesTotal", "amountCostAndExpensesOfRevenue", "amountDepreciationAndAmortization",
"amountNetIncome", "pershareEarningsBasic", "pershareEarningsDiluted",
"nameAuditor", "nameCommonEquityClass", "amountCommonEquityOutstanding",
"idCUSIPCommonEquity", "isCommonEquityPublic", "namePreferredEquityClass",
"amountPreferredEquityOutstanding", "idCusipPreferrdEquity", "isdPreferredEquityPublic",
"nameDebtSecuritiesClass", "amountOutstandingDebtSecurities", "idCUSIPDebtSecurities",
"isDebtSecuritiesPublic", "isCertifyIfTrue", "isCertifyIfNotDisqualified",
"codeTier1Tier2Offering", "codeFinancialStatementAuditStatus", "codeSecuritiesOfferedTypes",
"codeOfferDelayedContinuous", "codeOfferingYearFlag", "codeOfferingAfterQualifFlag",
"codeOfferingBestEffortsFlag", "codeSolicitationProposedOfferingFlag",
"codeResaleSecuritiesAffiliates", "countSecuritiesOffered", "countSecuritiesOutstanding",
"persharePrice", "amountOfferingIssuer", "amountOfferingExistingShareholdersSelling",
"amountOfferingSold12MonthQualifiedOffering", "amountOfferingSoldConcurrent",
"amountOfferingTotal", "nameUnderwritr",
"amountUnderwritersFees", "nameAuditor", "amountAuditorFees",
"nameLegal", "amountLegalFees", "namePromoter",
"amountPromotersFees", "idCRDBroker", "amountOfferringProceedsNet",
"descriptionResponse", "isJurisdictionsOfSecOfferedSame", "locatonJuridicationSecuritiesOffering",
"locationDealersJuridicationSecuritiesOffering", "nameSecuritiesIssuer",
"titleSecuritiesOffered", "amountSecuritiesIssued", "amountSecuritiesPrincipalHolder",
"amountSecuritiesIssuedTotal", "nameSecuritiesActExemption",
"isBadActor", "nameSalesCommissionsServiceProvider",
"amountSalesCommissionsFees", "isJurisdictionsSecuritiesOfferingNone",
"isUnRegisteredNone",
"nameBlueSkyServiceProvider", "amountBlueSkyFees",
'isTier1Tier2Offering', 'idForm', 'idForm', 'amountOfferingConsiderationBasis',
'nameFindersFeeProvider' , 'amountFindersFee',
'amountLoans', 'amountPropertyAndEquipment', 'amountDeposits', 'amountInterestIncomeTotal',
'amountInterestExpenseTotal', 'descriptionOtherSecuritiesOffered',
'commentFiling',
"numberAssetType",
"numberAsset",
"numberAssetGroup",
"dateReportPeriodBeginning",
"dateReportPeriodEnd",
"nameIssuer",
"dateOriginalIssuance",
"amountOriginalSecurity",
"numberOriginalSecurityTerm",
"dateSecurityMaturity",
"numberOriginalAmortizationTerm",
"percentageOriginalInterestRate",
"codeAccrualType",
"codeInterestRateType",
"numberOriginalInterestOnlyTerm",
"dateFirstPayment",
"hasUnderwriting",
"nameSecurityTitle",
"numberDenomination",
"nameCurrency",
"nameTrustee",
"numberSecFile",
"idCIK",
"hasCallable",
"codePaymentFrequency",
"hasZeroCoupon",
"hasAssetAdded",
"hasAssetModified",
"amountReportPeriodBeginningAssetBalance",
"amountReportPeriodBeginningScheduledAssetBalance",
"amountReportPeriodScheduledPayment",
"percentageReportPeriodInterestRate",
"amountTotalActualPaid",
"percentageActualInterestCollection",
"amountActualPrincipalCollected",
"amountActualOtherCollection",
"amountOtherPrincipalAdjustment",
"amountOtherInterestAdjustment",
"amountScheduledInterest",
"amountScheduledPrincipal",
"amountEndReportingPeriodActualBalance",
"amountEndReportingPeriodScheduledBalance",
"percentageServicingFee",
"amountServicingFlatFee",
"codeZeroBalance",
"dateZeroBalanceEffective",
"numberRemainingTermToMaturity",
"numberCurrentDelinquentStatus",
"numberPaymentPastDueDays",
"numberPaymentPastDue",
"amountNextReportPeriodPaymentDue",
"dateNextDue",
"namePrimaryLoanServicer",
"dateMostRecentServicingTransferReceived",
"hasAssetSubjectToDemand",
"codeStatusAssetSubjectToDemand",
"amountRepurchase",
"dateDemandResolution",
"nameRepurchaser",
"codeRepurchaseReplacementReason",
"dateReportPeriodBegin",
"codeOriginalLoanPurpose",
"nameOriginator",
"amountOriginalLoan",
"dateOriginalLoanMaturity",
"codeOriginalInterestRateType",
"codeOriginalLienPosition",
"amountMostRecentJuniorLoanBalance",
"dateMostRecentJuniorLoanBalance",
"amountMostRecentSeniorLoan",
"dateMostRecentSeniorLoanAmount",
"codeLoanTypeMostSeniorLien",
"numberMostSeniorLienHybridPeriod",
"percentageMostSeniorLienNegativeAmortizationLimit",
"dateMostSeniorLienOrigination",
"hasPrepaymentPenalty",
"hasNegativeAmortization",
"hasModification",
"numberModification",
"hasMortgageInsuranceRequirement",
"hasBalloon",
"codeCoveredHighCost",
"codeServicerHazardInsurance",
"amountRefinanceCashOut",
"amountTotalOriginationDiscount",
"hasBroker",
"codeChannel",
"numberNationalMortgageLicenseSystemCompany",
"numberBuyDown",
"numberLoanDelinquencyAdvance",
"codeOriginationARMIndex",
"percentageArmMargin",
"percentageFullyIndexedRate",
"numberInitialFixedRatePeriodHybridARM",
"percentageInitialInterestRateDecrease",
"percentageInitialInterestRateIncrease",
"numberIndexLookback",
"numberSubsequentInterestRateReset",
"percentageLifetimeRateCeiling",
"percentageLifetimeRateFloor",
"percentageSubsequentInterestRateDecrease",
"percentageSubsequentInterestRateIncrease",
"numberSubsequentPaymentReset",
"codeArmRound",
"percentageArmRound",
"hasOptionArm",
"codePaymentMethodAfterRecast",
"amountInitialMinimumPayment",
"hasConvertible",
"hasHELOC",
"numberHELOCDraw",
"codePrepaymentPenaltyCalculation",
"codePrepaymentPenaltyType",
"numberPrepaymentPenaltyTotalTerm",
"numberPrepaymentPenaltyHardTerm",
"amountNegativeAmortizationLimit",
"numberNegativeAmortizationInitialRecast",
"numberNegativeAmortizationSubsequentRecast",
"amountNegativeAmortizationBalance",
"numberInitialFixedPayment",
"percentageInitialPaymentCap",
"percentageSubsequentPaymentCap",
"numberInitialMinimumPaymentReset",
"numberSubsequentMinimumPaymentReset",
"amountMinimumPayment",
"locationGeographical",
"codeOccupancyStatus",
"codeMostRecentOccupancyStatus",
"codePropertyType",
"amountMostRecentPropertyValue",
"codeMostRecentPropertyValueType",
"dateMostRecentPropertyValue",
"codeMostRecentAVMModel",
"numberMostRecentAVMConfidence",
"percentageOriginalCLTV",
"percentageOriginalLTV",
"numberOriginalObligor",
"numberOriginalObligorCreditScore",
"typeOriginalObligorCreditScore",
"numberMostRecentObligorCreditScore",
"typeMostRecentObligorCreditScore",
"dateMostRecentObligorCreditScore",
"codeObligorIncomeVerificationLevel",
"hasIRSForm4506T",
"percentageOriginatorFrontEndDTI",
"percentageOriginatorBackEndDTI",
"codeObligorEmploymentVerification",
"codeObligorEmploymentLength",
"codeObligorAssetVerification",
"amountOriginalPledgedAssets",
"codeQualificationMethod",
"nameMortgageInsuranceCompany",
"percentageMortgageInsuranceCoverage",
"namePoolInsuranceCompany",
"percentagePoolInsuranceStopLoss",
"codeMortgageInsuranceCoverageType",
"periodModificationHasReporting",
"dateNextPaymentDue",
"codeAdvancingMethod",
"codeServicingAdvanceMethodology",
"dateStopPrincipalInterestAdvancing",
"amountReportingPeriodBeginningLoanBalance",
"amountReportingPeriodBeginningScheduledLoanBalance",
"amountNextReportingPeriodPaymentDue",
"percentageReportingPeriodInterestRate",
"percentageNextInterestRate",
"feeamountOtherAssessedUncollectedServicer",
"amountOtherServicingFeeRetainedByServicer",
"amountReportingPeriodEndActualBalance",
"amountReportingPeriodEndScheduledBalance",
"amountReportingPeriodScheduledPayment",
"amountActualInterestCollected",
"amountActualOtherCollected",
"datePaidThrough",
"dateInterestPaidThrough",
"amountPaidFull",
"amountServicerAdvancedPrincipal",
"amountServicerAdvancedRepaidPrincipal",
"amountServicerAdvancedCumulativePrincipal",
"amountServicerAdvanceInterest",
"amountServicerAdvanceRepaidInterest",
"amountServicerAdvanceCumulativeInterest",
"amountServicerAdvanceTaxesInsurance",
"amountServicerAdvanceRepaidTaxesInsurance",
"amountServicerAdvanceCumulativeTaxesInsurance",
"amountServicerAdvanceCorporate",
"amountServicerAdvanceRepaidCorporate",
"amountServicerAdvanceCumulativeCorporate",
"codeMostRecentTwelveMonthHistory",
"percentageNextResetRate",
"dateNextPaymentChange",
"dateNextInterestRateChange",
"amountNextResetPayment",
"hasExercisedArmConversionOption",
"namePrimaryServicer",
"nameMasterServicer",
"nameSpecialServicer",
"nameSubServicer",
"hasAssetSubjectDemand",
"codeAssetSubjectDemandStatus",
"codeRepurchaseReplacement",
"amountChargeOffPrincipal",
"amountChargeOffInterest",
"codeLossMitigationType",
"codeMostRecentLoanModificationEvent",
"dateMostRecentLoanModificationEffective",
"datePostModificationMaturity",
"codePostModificationInterestRateType",
"codePostModificationAmortizationType",
"percentagePostModificationInterest",
"datePostModificationFirstPayment",
"amountPostModificationLoanBalance",
"amountPostModificationPrincipalInterestPayment",
"amountTotalCap",
"modificationIncomeVerificationHasAt",
"percentageModificationFrontEndDebtToIncome",
"percentageModificationBackEndDebtToIncome",
"amountTotalDeferred",
"amountForgivenPrincipalCumulative",
"amountForgivenPrincipalReportingPeriod",
"amountForgivenInterestCumulative",
"amountForgivenInterestReportingPeriod",
"amountActualEndingBalanceTotalDebt",
"amountScheduledEndingBalanceTotalDebt",
"codePostModificationARM",
"codePostModificationARMIndex",
"percentagePostModificationMargin",
"numberPostModificationInterestReset",
"datePostModificationNextReset",
"numberPostModificationIndexLookback",
"codePostModificationARMRounding",
"percentagePostModificationARMRounding",
"paymentPostModificationInitialMinimum",
"datePostModificationNextPaymentAdjustment",
"frequencyPostModificationARMPaymentRecast",
"percentagePostModificationLifetimeFloor",
"percentagePostModificationLifetimeCeiling",
"percentagePostModificationInitialInterestRateIncrease",
"percentagePostModificationInitialInterestRateDecrease",
"percentagePostModificationSubsequentInterestIncrease",
"percentagePostModificationSubsequentInterestRateDecrease",
"percentagePostModificationPaymentCap",
"codePostModificationPaymentMethodAfterRecast",
"numberPostModificationARMInterestRateTeaser",
"numberPostModificationARMPaymentTeaser",
"hasPostModificationARMNegativeAmortization",
"percentagePostModificationARMNegativeAmortizationCap",
"numberPostModificationInterestOnlyTerm",
"datePostModificationInterestOnlyLastPayment",
"amountPostModificationBalloon",
"hasPostModificationInterestRateStep",
"percentagePostModificationStepInterest",
"datePostModificationStep",
"amountPostModificationStepPrincipalInterestPayment",
"numberPostModificationStep",
"percentagePostModificationMaximumFutureStepAgreement",
"datePostModificationMaximumStepAgreementRate",
"amountNonInterestBearingDeferredPrincipalCumulative",
"amountNonInterestBearingDeferredPrincipalReportingPeriod",
"amountRecoveryDeferredPrincipalReportingPeriod",
"amountNonInterestBearingDeferredPaidFull",
"amountNonInterestBearingDeferredInterestFeeReportingPeriod",
"amountNonInterestBearingDeferredInterestFeeCumulative",
"amountRecoveryDeferredInterestFeeReportingPeriod",
"dateMostRecentForbearancePlanOrTrialModificationStart",
"dateMostRecentForbearancePlanOrTrialModificationScheduledEnd",
"dateMostRecentTrialModificationViolated",
"dateMostRecentRepaymentPlanStart",
"dateMostRecentRepaymentPlanScheduledEnd",
"dateMostRecentRepaymentPlanViolated",
"amountShortSaleAcceptedOffer",
"dateMostRecentLossMitigationExit",
"codeMostRecentLossMitigationExit",
"dateAttorneyReferral",
"codeForeclosureDelayReason",
"dateForeclosureExit",
"codeForeclosureExitReason",
"dateNoticeOfIntent",
"amountMostRecentAcceptedREOOffer",
"dateMostRecentAcceptedREOOffer",
"amountGrossLiquidationProceeds",
"amountNetSalesProceeds",
"amountReportingPeriodLossPassedToIssuingEntity",
"amountCumulativeTotalLossPassedToIssuingEntity",
"amountSubsequentRecovery",
"hasEviction",
"dateReoExit",
"codeReoExitReason",
"amountUPBLiquidation",
"amountServicingFeesClaimed",
"amountServicerAdvanceReimbursedPrincipal",
"amountServicerAdvanceReimbursedInterest",
"amountServicerAdvanceReimbursedTaxesInsurance",
"amountServicerAdvanceReimbursedCorporate",
"amountREOManagementFees",
"amountCashKeyDeed",
"amountPerformanceIncentiveFees",
"dateMortgageInsuranceClaimFiled",
"amountMortgageInsuranceClaim",
"dateMortgageInsuranceClaimPaid",
"amountMortgageInsuranceClaimPaid",
"dateMortgageInsuranceClaimDeniedRescinded",
"dateMarketableTitleTransfer",
"codeNonPayStatus",
"codeReportingAction",
"idGroup",
"dateReportingPeriodBeginning",
"dateReportingPeriodEnd",
"dateOrigination",
"numberOriginalTermLoan",
"dateMaturity",
"percentageInterestRateSecuritization",
"codeInterestAccrualMethod",
"dateFirstLoanPaymentDue",
"codeLienPositionSecuritization",
"codeLoanStructure",
"codePaymentType",
"amountPeriodicPrincipalAndInterestPaymentSecuritization",
"amountScheduledPrincipalBalanceSecuritization",
"securitizationNumberProperties",
"propertiesNumber",
"numberGraceDaysAllowed",
"hasInterestOnly",
"hasPrepaymentPremium",
"hasModified",
"codeArmIndex",
"dateFirstRateAdjustment",
"dateFirstPaymentAdjustment",
"numberArmMargin",
"percentageLifetimeRateCap",
"percentagePeriodicRateIncreaseLimit",
"percentagePeriodicRateDecreaseLimit",
"amountPeriodicPaymentAdjustmentMaximum",
"percentPeriodicPaymentAdjustmentMaximum",
"codeRateResetFrequency",
"codePaymentResetFrequency",
"numberIndexLookbackDays",
"datePrepaymentLockOutEnd",
"dateYieldMaintenanceEnd",
"datePrepaymentPremiumsEnd",
"percentageMaximumNegativeAmortizationAllowed",
"amountMaximumNegativeAmortizationAllowed",
"amountNegativeAmortizationDeferredInterestCap",
"amountDeferredInterestCumulative",
"amountDeferredInterestCollected",
"propertyProperty",
"hasReportPeriodModification",
"amountReportPeriodBeginningScheduleLoanBalance",
"amountTotalScheduledPrincipalInterestDue",
"percentageServicerTrusteeFeeRate",
"amountUnscheduledPrincipalCollected",
"amountReportPeriodEndActualBalance",
"amountReportPeriodEndScheduledLoanBalance",
"dateHyperAmortizing",
"codeServicingAdvanceMethod",
"hasNonRecoverability",
"amountTotalPrincipalInterestAdvancedOutstanding",
"amountTotalTaxesInsuranceAdvancesOutstanding",
"amountOtherExpensesAdvancedOutstanding",
"codePaymentStatusLoan",
"percentageArmIndexRate",
"dateNextInterestRateChangeAdjustment",
"dateNextPaymentAdjustment",
"dateMostRecentSpecialServicerTransfer",
"dateMostRecentMasterServicerReturn",
"amountRealizedLossToTrust",
"codeLiquidationPrepayment",
"dateLiquidationPrepayment",
"amountPrepaymentPremiumYieldMaintenanceReceived",
"codeWorkoutStrategy",
"dateLastModification",
"codeModification",
"amountPostModificationPayment",
"amountPostModificationAmortizationPeriod",
"nameProperty",
"addressProperty",
"cityProperty",
"stateProperty",
"zipcodeProperty",
"countyProperty",
"numberNetRentableSquareFeet",
"numberNetRentableSquareFeetSecuritization",
"numberUnitsBedsRooms",
"numberUnitsBedsRoomsSecuritization",
"yearBuilt",
"yearLastRenovated",
"amountValuationSecuritization",
"codeValuationSourceSecuritization",
"dateValuationSecuritization",
"amountMostRecentValuation",
"dateMostRecentValuation",
"codeMostRecentValuationSource",
"percentagePhysicalOccupancySecuritization",
"percentageMostRecentPhysicalOccupancy",
"codePropertyStatus",
"dateDefeasanceOptionStart",
"codeDefeasedStatus",
"tenantLargest",
"numberSquareFeetLargestTenant",
"dateLeaseExpirationLargestTenant",
"tenantSecondLargest",
"numberSquareFeetSecondLargestTenant",
"dateLeaseExpirationSecondLargestTenant",
"tenantThirdLargest",
"numberSquareFeetThirdLargestTenant",
"dateLeaseExpirationThirdLargestTenant",
"dateFinancialsSecuritization",
"dateMostRecentFinancialsStart",
"dateMostRecentFinancialsEnd",
"amountRevenueSecuritization",
"amountMostRecentRevenue",
"amountOperatingExpensesSecuritization",
"amountOperatingExpenses",
"amountNetOperatingIncomeSecuritization",
"amountMostRecentNetOperatingIncome",
"amountNetCashFlowFlowSecuritization",
"amountMostRecentNetCashFlow",
"codeNetOperatingIncomeNetCashFlowSecuritization",
"codeNetOperatingIncomeNetCashFlow",
"amountMostRecentDebtService",
"percentageDebtServiceCoverageNetOperatingIncomeSecuritization",
"percentageMostRecentDebtServiceCoverageNetOperatingIncome",
"percentageDebtServiceCoverageNetCashFlowSecuritization",
"percentageMostRecentDebtServiceCoverageNetCash",
"codeDebtServiceCoverageSecuritization",
"codeMostRecentDebtServiceCoverage",
"dateMostRecentAnnualLeaseRolloverReview",
"dateReportingPeriodEnding",
"termOriginalLoan",
"dateLoanMaturity",
"codeInterestCalculationType",
"dateOriginalFirstPayment",
"numberGracePeriod",
"subventedSubvented",
"nameVehicleManufacturer",
"nameVehicleModel",
"codeVehicleNewUsed",
"yearVehicleModel",
"codeVehicleType",
"amountVehicleValue",
"codeVehicleValueSource",
"typeObligorCreditScore",
"scoreObligorCredit",
"hasCoObligor",
"percentagePaymentToIncome",
"locationObligorGeographic",
"hasReportingPeriodModification",
"amountPaymentDueNextReportingPeriod",
"servicerOtherServicerFeeRetainedBy",
"amountOtherAssessedUncollectedServicerFee",
"amountReportingPeriodActualEndBalance",
"amountPaidTotalActual",
"amountServicerAdvanced",
"isDelinquent",
"amountChargedoffPrincipal",
"amountRecovered",
"codeModificationType",
"numberPaymentExtended",
"hasRepossessed",
"amountRepossessedProceeds",
"dateReportingPeriodBegin",
"costAcquisition",
"numberOriginalLeaseTerm",
"dateScheduledTermination",
"periodGrace",
"valueBaseResidual",
"codeBaseResidualSource",
"valueContractResidual",
"typeLesseeCreditScore",
"scoreLesseeCredit",
"codeLesseeIncomeVerificationLevel",
"codeLesseeEmploymentVerification",
"hasCoLesseePresent",
"locationLesseeGeographic",
"numberRemainingTerm",
"amountReportingPeriodSecuritizationValue",
"rateSecuritizationDiscount",
"amountOtherLeaseLevelServicingFeesRetained",
"amountReportingPeriodEndingActualBalance",
"amountReportingPeriodEndActualSecuritization",
"namePrimaryLeaseServicer",
"dateDemandResolution",
"codeRepurchaseOrReplacementReason",
"amountChargedOff",
"extendedLease",
"hasTermination",
"amountExcessFee",
"amountLiquidationProceeds",
"detailNumberComment", "columnComment", "descriptionComment",
'idAccessionPrevious',
'numberItem', 'nameField', 'descriptionNotes'
)
)}
.filer_type_df <-
function() {
tibble(
idTypeFilerOwner = c(
'insider',
'private' ,
'broker_dealer',
'transfer_agent',
'ia',
'msd',
'bank',
'inv_co'
),
typeFilerOwner = c(
'Insider',
'Private Placement',
'Broker Dealer',
'Transfer Agent',
'Investment Advisor',
'Bank',
'Municipal Securities Dealer',
'Investment Company'
)
) %>%
mutate_all(str_to_upper)
}
dictionary_form_d_categories <-
function() {
category_df <-
dplyr::tibble(
idIndustry = 1:35,
nameIndustry = c(
"AGRICULTURE",
"AIRLINES AND AIRPORTS",
"BIOTECHNOLOGY",
"BUSINESS SERVICES",
"COAL MINING",
"COMMERCIAL REAL ESTATE",
"COMMERCIAL BANKING",
"COMPUTERS",
"CONSTRUCTION",
"ELECTRIC UTILITIES",
"ENERGY CONSERVATION",
"ENVIORNMENTAL SERVICES",
"HEALTH INSURANCE",
"HOSPITALS AND PHYSICIANS",
"INSURANCE",
"INVESTING",
"INVESTMENT BANKING",
"LODGING AND CONVETION",
"MANUFACTURING",
"OIL AND GAS",
"OTHER",
"OTHER BANKING AND FINANCIAL SERVICES",
"OTHER ENERGY",
"OTHER HEALTH CARE",
"OTHER REAL ESTATE",
"OTHER TECHNOLOGY",
"OTHER TRAVEL",
"PHARMACEUTICALS",
"POOLED INVESTMENT FUND",
"REITS AND FINANCE",
"RESIDENTIAL REAL ESTATE",
"RESTAURANTS",
"RETAIL",
"TELECOMMUNICATIONS",
"TRAVEL AND TOURISM"
),
codeIndustryParent = c(
"OTHER",
"TRAVEL",
"HEALTH",
"OTHER",
"ENERGY",
"REAL",
"FINANCE",
"TECH",
"REAL",
"ENERGY",
"ENERGY",
"ENERGY",
"HEALTH",
"HEALTH",
"FINANCE",
"FINANCE",
"FINANCE",
"TRAVEL",
"OTHER",
"ENERGY",
"OTHER",
"FINANCE",
"ENERGY",
"HEALTH",
"REAL",
"TECH",
"TRAVEL",
"HEALTH",
"FINANCE",
"REAL",
"REAL",
"OTHER",
"OTHER",
"TECH",
"TRAVEL"
),
nameIndustryParent = c(
"OTHER",
"TRAVEL AND LEISURE",
"HEALTHCARE",
"OTHER",
"ENERGY",
"REAL ESTATE",
"FINANCIAL",
"TECHNOLOGY",
"REAL ESTATE",
"ENERGY",
"ENERGY",
"ENERGY",
"HEALTHCARE",
"HEALTHCARE",
"FINANCIAL",
"FINANCIAL",
"FINANCIAL",
"TRAVEL AND LEISURE",
"OTHER",
"ENERGY",
"OTHER",
"FINANCIAL",
"ENERGY",
"HEALTHCARE",
"REAL ESTATE",
"TECHNOLOGY",
"TRAVEL AND LEISURE",
"HEALTHCARE",
"FINANCIAL",
"REAL ESTATE",
"REAL ESTATE",
"OTHER",
"OTHER",
"TECHNOLOGY",
"TRAVEL AND LEISURE"
)
)
return(category_df)
}
.insider_code_df <-
function() {
insider_df <-
tibble(
idInsiderTransaction =
c(
"A",
"C",
"D",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"NONE",
"O",
"P",
"S",
"U",
"V",
"W",
"X",
"Z"
),
nameInsiderTransaction = c(
"AWARD",
"CONVEYANCE",
"DISPOSITION TO ISSUER",
"PAYMENT WITH SECURITIES",
"GIFT",
"EXPIRATION OF LONG DERIVATIVE POSITION",
"DISCRETIONARY TRANSACTION",
"OTHER",
"EQUITY SWAP OR SIMILAR",
"SMALL ACQUISITIONS",
"EXEMPT",
NA,
"OTM EXERCISE",
"PURCHASE",
"SALE",
"MERGER AND ACQUISITION",
"REPORTED EARLY",
"WILL OR LAWS OF DESCENT",
"ITM OR ATM EXERCISE",
"DEPOSIT INTO/WITHDRAWAL FROM VOTING TRUST"
),
idTypeInsiderTransaction = c(
"A",
"D",
"D",
"D",
"D",
NA,
NA,
NA,
NA,
"A",
"A",
NA,
"A",
"A",
"D",
NA,
NA,
"D",
"A",
"D"
)
)
return(insider_df)
}
dictionary_sec_filing_codes <-
function() {
tibble(
idFormType = c(
"1.01",
"1.02",
"1.03",
"1.04",
"2.01",
"2.02",
"2.03",
"2.04",
"2.05",
"2.06",
"3.01",
"3.02",
"3.03",
"4.01",
"4.02",
"5.01",
"5.02",
"5.03",
"5.04",
"5.05",
"5.06",
"5.07",
"5.08",
"6.01",
"6.02",
"6.03",
"6.04",
"6.05",
"7.01",
"8.01",
"9.01"
),
nameFormType = c(
"Entry into a Material Definitive Agreement",
"Termination of a Material Definitive Agreement",
"Bankruptcy or Receivership",
"Mine Safety Reporting of Shutdowns and Patterns of Violations",
"Completion of Acquisition or Disposition of Assets",
"Results of Operations and Financial Condition",
"Creation of a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement of a Registrant",
"Triggering Events That Accelerate or Increase a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement",
"Costs Associated with Exit or Disposal Activities",
"Material Impairments",
"Notice of Delisting or Failure to Satisfy a Continued Listing Rule or Standard; Transfer of Listing",
"Unregistered Sales of Equity Securities",
"Material Modification to Rights of Security Holders",
"Changes in Registrant's Certifying Accountant",
"Non-Reliance on Previously Issued Financial Statements or a Related Audit Report or Completed Interim Review",
"Changes in Control of Registrant",
"Departure of Directors or Certain Officers; Election of Directors; Appointment of Certain Officers; Compensatory Arrangements of Certain Officers",
"Amendments to Articles of Incorporation or Bylaws; Change in Fiscal Year",
"Temporary Suspension of Trading Under Registrant's Employee Benefit Plans",
"Amendments to the Registrant's Code of Ethics, or Waiver of a Provision of the Code of Ethics",
"Change in Shell Company Status",
"Submission of Matters to a Vote of Security Holders",
"Shareholder Director Nominations",
"ABS Informational and Computational Material",
"Change of Servicer or Trustee",
"Change in Credit Enhancement or Other External Support",
"Failure to Make a Required Distribution",
"Securities Act Updating Disclosure",
"Regulation FD Disclosure",
"Other Events",
"Financial Statements and Exhibits"
) %>% stringr::str_to_upper()
)
}
dictionary_sec_form_codes <-
function() {
tibble(
idForm = c(
"R",
"A",
"Q",
"CR",
"REG",
"REGX",
"O",
"P",
"X",
"W",
"SEC",
"PROXY",
"CT",
"IS",
"CO",
"T"
),
nameForm = c(
"Other Report",
"Annual Report",
"Quarterly Report",
"Current Report",
"Registration",
"Private Offering",
"Ownership",
"Prospectus",
"Exemption",
"Withdrawal",
"SEC Correspondence",
"Proxy Statement",
"Confidential Treatment",
"Initial Statement",
"Change in Ownership",
"Trades"
) %>% stringr::str_to_upper()
)
}
.company_type_df <-
function() {
tibble(
idCompanyType = c(
"ic",
"i",
"ia",
"bd",
"m",
"t",
"b",
"c",
"p",
"etf",
"mmf",
"mf",
"uit",
"cef"
),
nameCompanyType = c(
"Investment Company",
"Insider",
"Investment Adviser",
"Broker-dealer",
"Municipal Securities Dealer",
"Transfer Agent",
"Bank",
"Company",
"Private Issuer",
"ETF",
"Money Market Fund",
"Mutual Fund",
"UIT",
"Closed-end Fund"
)
)
}
dictionary_sec_rules <-
function() {
tibble(
idRule = c(
"06",
"3C",
"3C.7",
"3C.1",
"06b",
"04",
"46",
"04.1",
"04.2",
"04.3",
"05",
"3C.6",
"3C.5",
"06c",
"4a5",
"3C.11",
"3C.2",
"3C.3",
"3C.9",
"3C.10",
"3C.4",
"3C.12",
"3C.",
"3C.14",
"3"
),
nameRule = c(
"Rule 506",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Rule 506b",
"Rule 504",
"Rule 506c",
"Rule 504b(1)(i)",
"Rule 504b(1)(ii)",
"Rule 504b(1)(iii)",
"Rule 505",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Rule 506c",
"Securities Act Section 4(a)(5)",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c"
)
) %>%
mutate_all(str_to_upper)
}
.parse_full_form_names <-
function(sec_names) {
df_names <-
seq_along(sec_names) %>%
future_map_dfr(function(x) {
sec_name <-
sec_names[[x]]
name_pieces <-
sec_name %>% str_replace_all('\\.value|\\.item', '')
pieces <-
name_pieces %>%
str_split('\\.') %>%
flatten_chr()
pieces_no_num <-
pieces[!pieces %>% str_detect("[0-9]")]
peice_length <-
pieces_no_num %>% length()
is_street <-
pieces %>% str_detect("street1|street2|Street1|Street2") %>% sum(na.rm = T) > 0
name_item <-
pieces_no_num[length(pieces_no_num)]
if (sec_name %>% str_detect('filingManager')) {
name_item <-
pieces %>% paste0(collapse = '')
df <-
tibble(nameSECFull = sec_name,
nameSEC = name_item)
return(df)
}
if (is_street) {
name_item <-
pieces[pieces %>% str_detect("street1|street2|Street1|Street2")]
}
is_sig <-
name_pieces %>% str_detect('signature') & peice_length == 1
is_footnote <-
sec_name %>% str_detect('footnote')
is_issuer <-
sec_name %>% str_detect('\\issuer.[A-Z]')
is_federal <-
sec_name %>% str_detect(pattern = "federalExemptionsExclusions")
if (is_federal) {
df <-
tibble(
nameSECFull = sec_name,
nameTable = pieces[[1]],
nameSEC = name_item
)
return(df)
}
if (is_issuer) {
items <-
sec_name %>% str_split('\\.') %>% flatten_chr()
countItem <-
pieces[2] %>% as.character() %>% readr::parse_number() %>% suppressWarnings()
name_item <-
items[length(items)]
df <-
tibble(
nameSECFull = sec_name,
nameTable = 'issuer',
countItem,
nameSEC = name_item
)
return(df)
}
if (is_footnote) {
if (pieces %>% length() == 1) {
countItem <-
0
item <-
pieces[[1]]
} else {
item <-
pieces[[1]]
countItem <-
pieces[2] %>% as.character() %>% readr::parse_number() %>% suppressWarnings()
}
return(tibble(nameTable = 'footnotes', nameSECFull = sec_name, nameSEC = item, countItem))
}
if (is_sig) {
df <-
tibble(nameTable = 'signatures', nameSECFull = sec_name, nameSEC = name_item)
return(df)
}
if (peice_length == 1) {
df <-
tibble(nameSECFull = sec_name, nameSEC = name_item)
return(df)
}
piece_count <-
length(pieces)
if (piece_count == 1) {
df <-
tibble(nameSECFull = sec_name, nameSEC = sec_name)
return(df)
}
if (piece_count == 2 &!is_footnote) {
df <-
tibble(nameSECFull = sec_name,
nameTable = pieces[[1]] ,
nameSEC = name_item)
return(df)
}
if (piece_count > 2) {
countItem <-
pieces[2] %>%
as.character() %>%
readr::parse_number() %>% suppressWarnings()
df <-
tibble(
nameSECFull = sec_name,
nameTable = pieces[[1]] ,
countItem,
nameSEC = name_item
)
return(df)
}
}) %>%
filter(!nameSEC == '')
df_dictionary <-
.sec_form_title_df()
has_missing_names <-
df_names$nameSEC[!df_names$nameSEC %in% df_dictionary$nameSEC] %>%
length() > 0
if (has_missing_names) {
missing <-
df_names$nameSEC[!df_names$nameSEC %in% df_dictionary$nameSEC] %>%
unique()
missing_names <-
missing %>%
paste0(collapse = '\n')
stop(list("Missing:\n", missing_names) %>%
purrr::reduce(paste0))
}
df_names <-
df_names %>%
left_join(df_dictionary) %>%
suppressWarnings() %>%
suppressMessages()
if (!'nameTable' %in% names(df_names)) {
df_names <-
df_names %>%
mutate(nameTable = 'asset')
}
df_names <-
df_names %>%
select(nameTable, nameSECFull, nameSEC, nameActual, everything()) %>%
mutate(nameTable = nameTable %>% str_replace('Id',''),
nameTable = ifelse(nameTable %in% c('issuerCredentials','securitiesIssued'), NA, nameTable)) %>%
suppressWarnings() %>%
suppressMessages()
}
.parse_xml_tables <-
function(url = "https://www.sec.gov/Archives/edgar/data/61004/000114036117000046/doc1.xml"){
page <-
url %>%
xml2::read_xml()
tables <-
page %>%
xml_contents() %>%
xml_name() %>%
unique()
data <-
seq_along(tables) %>%
future_map_dfr(function(x){
table <-
tables[[x]]
if (table %in% c('headerData', 'formData')) {
form_tables <-
page %>% xml_contents() %>% xml_name()
table_loc <-
table %>% grep(form_tables)
xml_nodes <-
page %>%
xml_contents() %>% .[[table_loc]]
}
if (table %in% c('infoTable' , 'assets')) {
xml_nodes <-
page %>%
xml_contents()
}
if (table == 'comment') {
value <-
page %>% xml_contents() %>% xml_text()
df <-
tibble(idTable = x, nameSECFull = table, value)
return(df)
}
tables_special <-
c('headerData', 'formData', 'infoTable', 'assets')
if (!table %in% tables_special) {
value_search <-
list('//', table) %>% purrr::reduce(paste0)
xml_nodes <-
page %>%
xml_contents() %>%
xml_find_all(value_search)
}
if (xml_nodes %>% length() > 100) {
list("Be patient there are ", xml_nodes %>% length() %>% formattable::comma(digits = 0), ' nodes to parse') %>%
purrr::reduce(paste0) %>% cat(fill = T)
}
value_list <-
xml_nodes %>%
as_list()
value_list <-
value_list[value_list %>% future_map(length) %>% flatten_dbl() > 0]
json_data <-
value_list %>%
jsonlite::toJSON(force = FALSE, dataframe = 'values') %>%
jsonlite::fromJSON(simplifyDataFrame = TRUE, flatten = TRUE)
wrong_output <-
json_data %>% class() == 'array'
if (wrong_output) {
item <-
xml_nodes %>% xml_name()
value <-
xml_nodes %>% xml_text()
json_data <-
tibble(item, value) %>%
spread(item, value)
}
if (json_data %>% length() == 0) {
return(tibble())
}
if ('summaryInfo' %in% names(json_data)) {
json_data <-
seq_along(json_data) %>% map(
function(x){
js_d <- json_data[x]
if ('summaryInfo' %in% names(js_d)) {
if (js_d$summaryInfo$clarificationResponses %>% length() == 0) {
js_d$summaryInfo$clarificationResponses <-
NULL
}
}
return(js_d)
}) %>%
flatten()
json_data <-
json_data[json_data %>% future_map(function(x){data.frame(x, stringsAsFactors = F)} %>% nrow()) > 0]
}
json_data <-
json_data %>%
data.frame(stringsAsFactors = FALSE) %>%
as_tibble() %>%
mutate_all(as.character) %>%
mutate(idTable = x) %>%
gather(nameSECFull, value, -idTable) %>%
arrange(idTable)
return(json_data)
})
data <-
data %>%
mutate(isList = value %>% str_detect('list')) %>%
filter(!isList) %>%
select(-isList) %>%
mutate(
nameSECFull = nameSECFull %>% str_replace_all(
"filerInfo.flags.|filerInfo.filer.|coverPage.|.filer.|\\flags.|filer.credentials.",
''
),
nameSECFull = nameSECFull %>% str_replace_all('filerInfo.|issuerCredentials.', '')
)
rm(tables)
rm(page)
rm(url)
return(data)
}
.parse_sec_form <-
function(url = "https://www.sec.gov/Archives/edgar/data/61004/000114036117000046/doc1.xml",
return_message = TRUE) {
data <-
.parse_xml_tables(url = url)
if (!'nameSECFull' %in% names(data)) {
data <-
data %>%
mutate(nameSECFull = nameSEC)
}
cik <-
url %>% str_replace_all('https://www.sec.gov/Archives/edgar/data/', '') %>% str_split('/') %>% flatten_chr() %>% .[[1]] %>% as.character() %>% readr::parse_number() %>% suppressMessages()
df_title <-
.sec_form_title_df()
is_13FInfo <-
url %>% str_detect('form13fInfoTable.xml|infotable.xml')
sec_names <-
data$nameSECFull %>% unique()
df_names <-
.parse_full_form_names(sec_names = sec_names)
df_names <-
df_names %>%
mutate(nameTable = ifelse(
nameSECFull %>% str_detect("issuerAddress"),
"issuerAddress",
nameTable),
nameTable = ifelse(
nameSECFull %>% str_detect("reportingOwner"),
"reportingOwner",
nameTable)
) %>%
mutate(nameTable = ifelse(nameSECFull %>% str_detect("issuerInfo."), 'issuerInfo', nameTable),
nameTable = ifelse(nameSECFull %>% str_detect("securitiesIssued."), 'securitiesIssued', nameTable),
nameTable = ifelse(nameSECFull %>% str_detect("summaryInfo."), 'summaryInfo', nameTable),
nameTable = ifelse(nameSECFull %>% str_detect("^comment[A-Z]"), 'Comments', nameTable)
)
if (is_13FInfo) {
df_names <-
df_names %>%
mutate(nameTable = 'holdingsInformation')
}
if (!'nameSEC' %in% names(data)) {
data <- data %>%
mutate(nameSEC = nameSECFull)
}
data <-
data %>%
select(-nameSEC) %>%
left_join(df_names) %>%
mutate(nameActual = ifelse(nameSECFull == "X.1.A.A.", 'idForm', nameActual)) %>%
suppressMessages()
if ('countItem' %in% names(data)) {
data <-
data %>%
select(nameTable, countItem, nameSECFull, nameActual, everything()) %>%
mutate(countItem = countItem - 1) %>%
suppressMessages()
}
if ('property' %in% data$nameTable) {
data <-
data %>%
mutate(nameTable = ifelse(nameTable %>% is.na(), 'Asset', nameTable))
}
has_metadata <-
data %>%
filter(nameTable %>% is.na()) %>% nrow() > 0
if (has_metadata) {
df_metadata <-
data %>%
filter(nameTable %>% is.na()) %>%
select(nameActual, value) %>%
group_by(nameActual) %>%
mutate(countItem = 1:n() - 1) %>%
arrange(countItem) %>%
ungroup() %>%
filter(!nameActual %>% str_detect('idCCC')) %>%
mutate(nameActual = ifelse(countItem == 0, nameActual, nameActual %>% paste0(countItem))) %>%
select(-countItem)
col_order <-
df_metadata$nameActual
df_metadata <-
df_metadata %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
mutate(urlSECFiling = url) %>%
.resolve_form_columns()
} else {
df_metadata <-
tibble(idCIKFiler = cik,
urlSECFiling = url)
}
tables <-
data %>%
filter(!nameTable %>% is.na()) %>%
.$nameTable %>%
unique()
data <-
seq_along(tables) %>%
future_map(function(x) {
table <-
tables[[x]]
table_name <-
list('data',
table %>% substr(1, 1) %>% str_to_upper(),
table %>% substr(2, nchar(table))) %>%
purrr::reduce(paste0)
table_df <-
data %>%
filter(nameTable == table) %>%
select(dplyr::matches("countItem"), nameActual, value) %>%
select(which(colMeans(is.na(.)) < 1)) %>%
group_by(nameActual) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup()
has_counts <-
table_df$countItem %>% max(na.rm = TRUE) > 0
if (has_counts) {
table_df <-
table_df %>%
arrange(countItem)
col_order <- c('countItem', table_df$nameActual)
table_df <-
table_df %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
mutate(urlSECFiling = url) %>%
.resolve_form_columns()
table_df <-
table_df %>%
nest(-urlSECFiling, .key = data)
} else {
table_df <-
table_df %>%
select(-countItem)
col_order <- c(table_df$nameActual)
table_df <-
table_df %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
.resolve_form_columns() %>%
mutate(urlSECFiling = url)
table_df <-
table_df %>%
nest(-urlSECFiling, .key = data)
}
names(table_df)[[2]] <-
table_name
df_metadata <-
df_metadata %>%
left_join(table_df) %>%
suppressMessages()
}) %>%
reduce(left_join) %>%
suppressMessages()
rm(df_metadata)
return(data)
}
.parse_form_data <-
function(.all_filings, filter_parameter = 'isXBRLInstanceFile', return_message = TRUE) {
df_search <-
.all_filings %>%
filter_(.dots = filter_parameter)
if (filter_parameter == 'isXBRLInstanceFile') {
if (df_search %>% nrow() == 0) {
return(tibble())
}
parse_xbrl_filer_url_safe <-
purrr::possibly(.parse_xbrl_filer_url, tibble())
all_data <-
df_search$urlSECFiling %>%
unique() %>%
future_map_dfr(function(x) {
.parse_xbrl_filer_url(url = x, return_message = return_message)
})
all_data <-
all_data %>%
select(-dplyr::matches("idCIK1|nameFiler1")) %>%
left_join(df_search %>% select(dplyr::matches("idForm"), dplyr::matches("idAccession"), dplyr::matches("nameFile"), dateFiling, urlSECFiling)) %>%
select(
dplyr::matches("idCIK"),
dplyr::matches("name[Entity]|name[Filer]"),
dateFiling,
dplyr::matches("idForm"),
dplyr::matches("idAccession"),
dplyr::matches("nameFile"),
everything()
) %>%
suppressMessages()
return(all_data)
}
if (filter_parameter == 'is13FFiling') {
urls_df <-
df_search %>% select(urlSECFiling, urlSECFilingDirectory)
df_13f_urls <-
1:nrow(urls_df) %>%
future_map_dfr(function(x){
row_df <-
urls_df %>% slice(x)
url <- row_df$urlSECFiling
urlSECFilingDirectory <-
row_df$urlSECFilingDirectory
parts <-
url %>%
str_replace_all("https://www.sec.gov/Archives/edgar/data/", '') %>%
str_split('\\/') %>%
flatten_chr()
idCIKFiler <-
parts[[1]] %>% as.numeric()
slugAccession <-
parts[[2]]
isPrimary <-
parts[[3]] %>% str_detect("primary")
tibble(idCIKFiler, slugAccession, isPrimary, urlSECFiling = url, urlSECFilingDirectory)
})
slugs <-
df_13f_urls$slugAccession %>% unique()
df_13fs <-
seq_along(slugs) %>%
future_map_dfr(function(x){
slug <-
slugs[[x]]
df_period <-
df_13f_urls %>%
filter(slugAccession == slug)
if (df_period %>% nrow() == 2) {
primary_url <-
df_period %>% filter(isPrimary) %>%
.$urlSECFiling
df_primary <-
.parse_sec_form(url = primary_url, return_message = return_message) %>%
mutate(urlSECFiling = primary_url)
df_primary <-
df_primary %>%
left_join(df_13f_urls) %>%
suppressWarnings()
no_primary_url <-
df_period %>% filter(!isPrimary) %>%
.$urlSECFiling
urlSECFilingDirectory <-
df_period %>% filter(!isPrimary) %>%
.$urlSECFilingDirectory
df_primary_no <-
.parse_sec_form(url = no_primary_url, return_message = return_message) %>%
mutate(urlSECFiling = no_primary_url)
data <-
df_primary %>%
select(-dplyr::matches("urlSECFiling")) %>%
left_join(df_primary_no %>% select(-dplyr::matches("urlSECFiling"))) %>%
mutate(urlSECFilingDirectory = urlSECFilingDirectory) %>%
suppressMessages()
return(data)
} else {
period_url <-
df_period$urlFiling
urlSECFilingDirectory <-
df_period$urlSECFilingDirectory
data <-
.parse_sec_form(url = period_url, return_message = return_message) %>%
mutate(urlFiling = period_url) %>%
left_join(df_period) %>%
mutate(urlSECFilingDirectory = urlSECFilingDirectory)
return(data)
}
})
df_13fs <-
df_13fs %>%
left_join(urls_df) %>%
left_join(df_search %>% select(dateFiling, datePeriodReport, datetimeAccepted, urlSECFilingDirectory, dplyr::matches("urlTextFilingFull"))) %>%
select(-dplyr::matches("slugAcession")) %>%
select(dplyr::matches("idCIKFiler"), dplyr::matches("nameFilingManager"), everything()) %>%
select(dateFiling, everything()) %>%
suppressMessages()
return(df_13fs)
}
if (filter_parameter == 'isFormD') {
if ('idForm' %in% names(df_search)){
df_search <-
df_search %>%
filter(!idForm %>% str_detect("10"))
}
}
if (df_search %>% nrow() == 0) {
return(tibble())
}
parse_sec_form_safe <-
purrr::possibly(.parse_sec_form, tibble())
all_data <-
df_search$urlSECFiling %>%
unique() %>%
future_map_dfr(function(x) {
parse_sec_form_safe(url = x, return_message = return_message)
})
if (all_data %>% nrow() == 0) {
return(all_data)
}
all_data <-
all_data %>%
select(-dplyr::matches("idCIK1|nameFiler1")) %>%
left_join(df_search %>% select(dplyr::matches("idForm"), dplyr::matches("idAccession"), dplyr::matches("nameFile"), dateFiling, urlSECFiling)) %>%
select(
dplyr::matches("idCIK"),
dplyr::matches("name[Entity]|name[Filer]"),
dateFiling,
dplyr::matches("idForm"),
dplyr::matches("idAccession"),
dplyr::matches("nameFile"),
everything()
) %>%
suppressMessages()
if (filter_parameter == 'hasAssetFile') {
if('dataComments' %in% names(all_data)) {
df_comments <-
all_data %>%
select(idCIKFiler, dplyr::matches("idAccession"), dplyr::matches("dataComments")) %>%
mutate(isNULL = dataComments %>% map_lgl(is_null)) %>%
filter(!isNULL) %>%
distinct() %>%
select(-isNULL)
all_data <-
all_data %>%
select(-dataComments) %>%
mutate(isNULL = dataAsset %>% map_lgl(is_null)) %>%
filter(!isNULL) %>%
filter(!nameFile == "ASSET RELATED DOCUMENT") %>%
distinct() %>%
select(-isNULL) %>%
left_join(df_comments) %>%
suppressMessages()
}
}
all_data <-
all_data %>%
select(which(colMeans(is.na(.)) < 1))
return(all_data)
}
.parse_sec_filing_index <-
function(urls, return_message = TRUE) {
df <-
tibble()
success <- function(res) {
if (return_message) {
list("Parsing: ", res$url) %>% purrr::reduce(paste0) %>% cat(fill = T)
}
page <-
res$content %>%
read_html()
not_503 <-
!res$status_code == 503
cik <-
res$url %>%
str_split('data/') %>%
flatten_chr() %>%
.[[2]] %>%
str_split('/') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
if (not_503){
values <-
page %>%
html_nodes('.info') %>%
html_text()
if (length(values) == 0) {
return(tibble())
}
items <-
page %>%
html_nodes('.infoHead') %>%
html_text()
all_items <-
items %>%
map_chr(function(x) {
is_zero <-
x %>% str_count('\\ ') == 0
if (x == 'Accepted') {
return("datetimeAccepted")
}
if (x == 'Documents') {
return('countDocuments')
}
if (x == "items") {
return('descriptionItems')
}
if (is_zero) {
return('item' %>% paste0(x))
}
if (x == "Period of Report") {
return("datePeriodReport")
}
if (x == "429 Reference" | x %>% str_detect("Reference")) {
return("reference429")
}
name_items <-
x %>% str_split('\\ ') %>%
flatten_chr()
first <-
name_items[name_items %>% length()] %>% str_to_lower()
end <-
name_items[1:(name_items %>% length() - 1)] %>%
paste0(collapse = '') %>%
str_to_title()
final_name <-
list(first, end) %>% purrr::invoke(paste0, .)
return(final_name)
})
search_url <-
res$url
df_metadata <-
tibble(item = all_items,
value = values) %>%
mutate(urlSECFilingDirectory = search_url) %>%
spread(item, value)
df_metadata <-
df_metadata %>%
mutate_at(df_metadata %>% select(dplyr::matches('count')) %>% names(),
funs(. %>% as.numeric())) %>%
mutate_at(
df_metadata %>% select(dplyr::matches('^date[A-Z]')) %>% select(-dplyr::matches("datetime")) %>% names(),
funs(. %>% lubridate::ymd())
) %>%
mutate_at(
df_metadata %>% select(dplyr::matches('^datetime')) %>% select(-dplyr::matches("datetime")) %>% names(),
funs(. %>% lubridate::ymd_hms())
)
urlSECFiling <-
page %>%
html_nodes('
html_attr('href') %>%
paste0('https://www.sec.gov', .)
namehref <-
page %>%
html_nodes('
html_text()
files <-
page %>%
html_nodes('
html_text() %>%
str_to_upper()
wrong_length <-
!(namehref %>% length() == files %>% length())
if (wrong_length) {
namehref <-
namehref[namehref %>% str_detect("\\.")]
urlSECFiling <-
urlSECFiling[2:length(urlSECFiling)]
}
files <-
files %>%
str_trim()
types_form <-
page %>%
html_nodes('td:nth-child(4)') %>%
html_text() %>%
str_trim()
types_form[types_form == ''] <-
NA
types_form <-
types_form[seq_along(files)]
files[files == ''] <-
NA
search_url <-
res$url
data <-
tibble(
nameFile = files,
nameHref = namehref,
typeForm = types_form,
urlSECFiling
) %>%
mutate(
isXML = nameHref %>% str_detect("xml"),
isForm3_4 = nameHref %>% str_detect('doc3.xml|doc4.xml'),
isFormD = ifelse(
isXML & typeForm %in% c("D", "D/A"),
TRUE,
FALSE
),
is13FFiling = ifelse(
isXML& typeForm %>% str_detect("13F-HR|INFORMATION TABLE"),
TRUE,
FALSE
),
hasSmallOfferingData = ifelse(isXML &
typeForm %>% str_detect("1-A|1-A/A"),
TRUE,
FALSE),
hasSmallOfferingData = ifelse(typeForm == "C" & isXML, TRUE, hasSmallOfferingData),
hasAssetFile = typeForm %>% str_detect("EX-102|EX-103")
) %>%
tidyr::separate(nameHref,
into = c('nameHREF', 'typeFile'),
sep = '\\.') %>%
mutate(urlSECFilingDirectory = search_url) %>%
mutate(
nameFile = ifelse(nameFile == '', NA, nameFile %>% str_to_upper()),
isCompleteTextFiling = nameFile %>% str_detect("COMPLETE SUBMISSION"),
isXBRLInstanceFile = ifelse(nameFile %>% str_detect("XBRL INSTANCE"), TRUE, FALSE),
isImage = ifelse(typeFile %in% c('jpg', 'gif', 'tiff', 'png'), TRUE, FALSE),
isPDF = ifelse(typeFile %in% c('pdf'), TRUE, FALSE)
)
data <-
data %>%
left_join(df_metadata) %>%
mutate(idCIK = cik) %>%
select(idCIK, dplyr::matches("date"), dplyr::matches("count"), everything()) %>%
suppressWarnings() %>%
suppressMessages()
} else {
search_url <-
res$url
data <-
tibble(idCIK = cik,
urlSECFilingDirectory = search_url)
}
df <<-
df %>%
bind_rows(data)
}
failure <- function(msg){
tibble()
}
urls %>%
walk(function(x){
curl_fetch_multi(url = x, success, failure)
})
multi_run()
df
}
.all_filings <-
function(urls, return_message = TRUE) {
df_filings <-
urls %>%
future_map_dfr(function(x){
.parse_sec_filing_index(urls = x, return_message = return_message)
})
return(df_filings)
}
.all_filing_urls <-
function(data, nest_data = TRUE,
return_message = TRUE) {
if (!'urlSECFilingDirectory' %in% names(data)) {
stop("urlSECFilingDirectory needs to be in the data fields")
}
if (!'idAccession' %in% names(data)) {
df_accession <-
data$urlSECFilingDirectory %>%
unique() %>%
future_map_dfr(function(x){
urlSECFilingDirectory <-
x
idAccession <-
x %>% str_replace_all('https://www.sec.gov/Archives/edgar/data/', '') %>%
str_split('\\/') %>%
flatten_chr() %>% {
.[length(.)] %>% str_replace_all('-index.htm', '')
}
tibble(idAccession, urlSECFilingDirectory)
})
data <-
data %>%
left_join(df_accession) %>%
suppressMessages()
}
data <-
data %>%
select(-dplyr::matches("hasAssetFile|isFormD|is13F|isForm3_4|hasSmallOfferingData")) %>%
filter(typeFile %>% str_detect("htm")) %>%
group_by(idAccession) %>%
mutate(countAccension = 1:n()) %>%
filter(countAccension == max(countAccension)) %>%
ungroup() %>%
arrange(dateFiling)
urls <-
data$urlSECFilingDirectory
df_all_filings <-
.all_filings(urls = urls, return_message = return_message)
df_all_filings <-
df_all_filings %>%
left_join(data %>% select(urlSECFilingDirectory, countAccension, idAccession)) %>%
suppressMessages()
if (nest_data) {
df_all_filings <-
df_all_filings %>%
nest(-c(idAccession, countAccension, urlSECFilingDirectory), .key = dataFilings)
}
df_all_filings
}
.header_names <-
function() {
tibble(
nameSEC = c(
"ACCEPTANCE-DATETIME",
"ACCESSION NUMBER",
"CONFORMED SUBMISSION TYPE",
"PUBLIC DOCUMENT COUNT",
"FILED AS OF DATE",
"DATE AS OF CHANGE",
"COMPANY CONFORMED NAME",
"CENTRAL INDEX KEY",
"STANDARD INDUSTRIAL CLASSIFICATION",
"IRS NUMBER",
"STATE OF INCORPORATION",
"FISCAL YEAR END",
"FORM TYPE",
"SEC ACT",
"SEC FILE NUMBER",
"FILM NUMBER",
"STREET 1",
"CITY",
"STATE",
"ZIP",
"BUSINESS PHONE",
"FORMER CONFORMED NAME",
"DATE OF NAME CHANGE",
"STREET 2",
"CONFORMED PERIOD OF REPORT",
"ITEM INFORMATION"
),
nameActual = c(
"datetimeAccepted",
"idAccession",
"idForm",
"countPublicDocuments",
"dateFiling",
"dateFilingChange",
"nameCompany",
"idCIK",
"nameCodeSIC",
"idIRS",
"stateIncorporation",
"monthdayFiscalYearEnd",
"typeForm",
"idSECAct",
"idSEC",
"idFilm",
"addressStreet1",
"city",
"state",
"zipcode",
"telephone",
"nameCompanyFormer",
"dateNameChange",
'addressStreet2',
'dateReportPeriod',
'descriptionItem'
)
)
}
.section_names <-
function() {
tibble(nameSectionSEC = c(NA, "SUBJECT COMPANY", "FILED BY", 'ISSUER', 'REPORTING-OWNER'),
nameSectionActual = c('', '', 'FilingEntity', 'Issuer', 'ownerReporting')
)
}
.parent_names <-
function() {
tibble(nameParentSEC = c(NA, "COMPANY DATA", "FILING VALUES", "BUSINESS ADDRESS", "MAIL ADDRESS",
"FORMER COMPANY"),
nameParentActual = c('', '', '', 'Business', 'Mailing', ''))
}
.parse_text_headers <-
function(text_blob){
header_start <-
text_blob %>% grep("<SEC-HEADER>",.) + 1
header_end <-
text_blob %>% grep("</SEC-HEADER>",.) - 1
header_text <-
text_blob[header_start:header_end]
header_text <-
header_text %>% str_replace_all('\\<','') %>% str_replace_all('\\>',':')
df_headers <- tibble(text = header_text) %>%
tidyr::separate(col = text, into = c('nameSEC', 'value'), sep = '\\:') %>%
mutate(value = value %>% str_replace_all("\t", '')) %>%
mutate(idRow = 1:n())
df_parents <-
df_headers %>%
filter(value == '') %>%
mutate(idRow = idRow + 1) %>%
dplyr::rename(nameParentSEC = nameSEC) %>%
select(-value)
df_section <-
df_parents %>%
filter(nameParentSEC %in% c("SUBJECT COMPANY", "FILED BY")) %>%
select(nameSectionSEC = nameParentSEC, idRow) %>%
mutate(idRow = idRow + 1)
df_parents <-
df_parents %>%
filter(!nameParentSEC %in% c("SUBJECT COMPANY", "FILED BY")) %>%
left_join(df_section) %>%
fill(nameSectionSEC) %>%
select(nameSectionSEC, nameParentSEC, idRow) %>%
suppressMessages()
data <-
df_headers %>%
filter(!value == '') %>%
left_join(df_parents) %>%
select(idRow, nameSectionSEC, nameParentSEC, everything()) %>%
tidyr::fill(nameSectionSEC) %>%
tidyr::fill(nameParentSEC) %>%
select(-idRow) %>%
distinct() %>%
suppressWarnings() %>%
suppressMessages()
df_parents <-
.parent_names()
df_names <-
.header_names()
df_sections <-
.section_names()
has_missing_names <-
data$nameSEC[!data$nameSEC %in% df_names$nameSEC] %>% length() > 0
if (has_missing_names) {
df_missing <-
data$nameSEC[!data$nameSEC %in% df_names$nameSEC] %>% unique() %>%
future_map_dfr(function(x){
parts <-
x %>% str_replace_all('\\-', ' ') %>%
str_split('\\ ') %>% flatten_chr()
first <-
parts[length(parts)] %>%
str_to_lower()
is_cik <-
first %>% str_detect('cik') %>% sum(na.rm = TRUE) > 0
if (is_cik) {
first <-
'idCIK'
}
other <-
list(parts[1:(length(parts) - 1)] %>% str_to_title) %>%
purrr::reduce(paste0) %>%
paste0(collapse = '')
actual <-
list(first,other) %>%
purrr::reduce(paste0)
tibble(nameSEC = x, nameActual = actual)
})
df_names <- df_names %>%
bind_rows(df_missing)
}
data <-
data %>%
left_join(df_parents) %>%
left_join(df_sections) %>%
left_join(df_names) %>%
mutate(nameParentActual = ifelse(nameParentActual %>% is.na(), '', nameParentActual)) %>%
suppressMessages() %>%
unite(nameItem, nameActual, nameParentActual, nameSectionActual, sep = '') %>%
select(nameItem, value) %>%
suppressWarnings() %>%
group_by(nameItem) %>%
mutate(countItem = 1:n() - 1) %>%
ungroup() %>%
mutate(nameItem = ifelse(countItem == 0, nameItem, paste0(nameItem, countItem))) %>%
suppressMessages() %>%
select(-countItem)
col_order <-
data$nameItem
data <-
data %>%
spread(nameItem, value) %>%
select(one_of(col_order))
data <-
data %>%
mutate_at(data %>% select(dplyr::matches("datetime")) %>% names(),
funs(. %>% lubridate::ymd_hms())) %>%
mutate_at(data %>% select(dplyr::matches("^date[A-Z]")) %>% select(-dplyr::matches("datetime")) %>% names(),
funs(. %>% lubridate::ymd())) %>%
mutate_at(data %>% select(dplyr::matches("idCIK|count|monthdayFiscalYearEnd")) %>% names(),
funs(. %>% as.numeric())) %>%
mutate_at(data %>% select(dplyr::matches("name[A-Z]|type[A-Z]|description|class")) %>% names(),
funs(. %>% stringr::str_to_upper()))
if ('nameCodeSIC' %in% names(data)) {
data <-
data %>%
separate(nameCodeSIC, into = c('nameIndustry', 'idSIC'), sep = '\\[') %>%
mutate(nameIndustry = nameIndustry %>% str_trim() %>% str_to_upper(),
idSIC = idSIC %>% as.character() %>% readr::parse_number()) %>%
suppressWarnings()
}
return(data)
}
.parse_for_text <-
function(text_blob) {
text_start <-
text_blob %>% grep("<TEXT>",.) %>% .[[1]] + 1
text_end <-
text_blob %>% grep("</TEXT>",.)
text_end <-
text_end %>% max() - 1
df_text <-
tibble(textRow = text_blob[text_start:text_end]) %>%
mutate(idRow = 1:n()) %>%
select(idRow, everything())
return(df_text)
}
.parse_text_filing <-
function(url = "https://www.sec.gov/Archives/edgar/data/732712/000119312517025716/0001193125-17-025716.txt") {
text_blob <-
url %>%
readr::read_lines() %>% {
.[!. == ''] %>%
str_trim()
}
has_html <-
text_blob %>% str_count("<HTML>") %>% sum(na.rm = TRUE) > 0
has_xml <-
text_blob %>% str_count("<XML>") %>% sum(na.rm = TRUE) > 0
df_headers <-
.parse_text_headers(text_blob = text_blob)
df_text <-
.parse_for_text(text_blob = text_blob) %>%
mutate(idAccession = df_headers$idAccession) %>%
nest(-idAccession, .key = textFiling)
data <-
df_headers %>%
left_join(df_text) %>%
mutate(urlSECFiling = url,
hasHTML = has_html,
hasXML = has_xml) %>%
select(dplyr::matches("idCIK"), dplyr::matches("dateFiling"), idAccession, dplyr::matches("idForm"), dplyr::matches("nameCompany"), everything())
return(data)
}
.sec_complete_filings <-
function(urls = c("https://www.sec.gov/Archives/edgar/data/732712/000119312517030264/0001193125-17-030264.txt", "https://www.sec.gov/Archives/edgar/data/732712/000161159317000024/0001611593-17-000024.txt", "https://www.sec.gov/Archives/edgar/data/1629703/000161159317000025/0001611593-17-000025.txt", "https://www.sec.gov/Archives/edgar/data/1284999/000161159317000014/0001611593-17-000014.txt"),
return_message = TRUE) {
df <-
tibble()
success <- function(res) {
url <-
res$url
if (return_message) {
list("Parsing: ", url, "\n") %>% purrr::reduce(paste0) %>% cat(fill = T)
}
data <-
.parse_text_filing(url = url)
df <<-
df %>%
bind_rows(data)
}
failure <- function(msg) {
tibble()
}
urls %>%
walk(function(x) {
curl_fetch_multi(url = x, success, failure)
})
multi_run()
df
}
.parse_xbrl_filer_url <-
function(url = "https://www.sec.gov/Archives/edgar/data/1037540/000165642316000023/bxp-20160930.xml",
return_message = TRUE) {
options(stringsAsFactors = FALSE, scipen = 999999)
cik <-
url %>%
str_split('data/') %>%
flatten_chr() %>%
.[[2]] %>%
str_split('/') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
td <-
tempdir()
tf <-
tempfile(tmpdir = td, fileext = ".xml")
url %>%
curl::curl_download(destfile = tf)
doc <-
tf %>%
XBRL::xbrlParse()
df_fct <-
XBRL::xbrlProcessFacts(doc) %>%
as_tibble()
df_fct <-
df_fct %>%
mutate(
isNumber = ifelse(!fact %>% readr::parse_number() %>% is.na(), TRUE, FALSE),
amountFact = ifelse(isNumber == TRUE, fact %>%as.character() %>% readr::parse_number(), NA)
) %>%
separate(elementId,
c('codeElement', 'nameElement'),
sep = '\\_',
remove = FALSE) %>%
suppressWarnings()
df_cts <-
XBRL::xbrlProcessContexts(doc) %>%
as_tibble()
df_unt <-
XBRL::xbrlProcessUnits(doc) %>%
as_tibble()
df_sch <-
XBRL::xbrlGetSchemaName(doc) %>%
as_tibble()
df_footnotes <-
XBRL::xbrlProcessFootnotes(doc) %>%
as_tibble()
XBRL::xbrlFree(doc)
url_xsd <-
url %>% str_replace(".xml", ".xsd")
url_xsd %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_rls <-
docS %>%
XBRL::xbrlProcessRoles() %>%
as_tibble()
url_cal <-
url %>% str_replace(".xml", "_cal.xml")
if (suppressWarnings(httr::url_ok(url_cal))){
url_cal %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_calcs <-
docS %>%
XBRL::xbrlProcessArcs(arcType = 'calculation') %>%
as_tibble()
} else {
df_calcs <-
tibble()
}
url_def <-
url %>% str_replace(".xml", "_def.xml")
url_def %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_defs <-
docS %>%
XBRL::xbrlProcessArcs(arcType = 'definition') %>%
as_tibble()
url_lab <-
url %>% str_replace(".xml", "_lab.xml")
url_lab %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
df_labels <-
docS %>%
XBRL::xbrlProcessLabels() %>%
as_tibble()
url_pre <-
url %>% str_replace(".xml", "_pre.xml")
url_pre %>%
curl_download(destfile = tf)
docS <-
tf %>%
XBRL::xbrlParse()
tf %>%
unlink()
data <-
tibble(
idCIK = cik,
urlSECFiling = url,
dataFacts = list(df_fct),
dataContexts = list(df_cts),
dataUnits = list(df_unt),
dataFootnotes = list(df_footnotes),
dataRoles = list(df_rls),
dataCalculations = list(df_calcs) ,
dataDefinitions = list(df_defs),
dataLabel = list(df_labels)
)
td %>% unlink()
tf %>% unlink()
return(data)
}
.sec_form_title_df <-
function() {
tibble(
nameSEC = c(
"conversionOrExercisePrice",
"deemedExecutionDate",
"directOrIndirectOwnership",
"documentType",
"equitySwapInvolved",
"exerciseDate",
"expirationDate",
"footnote",
"isDirector",
"isOfficer",
"isOther",
"issuerCik",
"issuerName",
"issuerTradingSymbol",
"isTenPercentOwner",
"natureOfOwnership",
"noSecuritiesOwned",
"notSubjectToSection16",
"officerTitle",
"otherText",
"periodOfReport",
"postTransactionAmountsOwnedFollowingTransaction",
"remarks",
"rptOwnerCik",
"rptOwnerCity",
"rptOwnerName",
"rptOwnerState",
"rptOwnerStateDescription",
"rptOwnerStreet1",
"rptOwnerStreet2",
"rptOwnerZipCode",
"schemaVersion",
"securityTitle",
"sharesOwnedFollowingTransaction",
"signatureDate",
"signatureName",
"transactionAcquiredDisposedCode",
"transactionCode",
"transactionDate",
"transactionFormType",
"transactionPricePerShare",
"transactionShares",
"transactionTimeliness",
"transactionTotalValue",
"underlyingSecurityShares",
"underlyingSecurityTitle",
"clarificationOfResponse", "isBusinessCombinationTransaction",
"cik", "moreThanOneYear", "previousName", "edgarPreviousNameList",
"entityName", "entityType", "entityTypeOtherDesc", "federalExemptionsExclusions",
"industryGroupType", "investmentFundType", "investmentFundInfo",
"hasNonAccreditedInvestors", "numberNonAccreditedInvestors",
"totalNumberAlreadyInvested", "city", "stateOrCountry", "stateOrCountryDescription",
"street1", "street2", "zipCode", "issuerPhoneNumber", "issuerPreviousNameList",
"jurisdictionOfInc", "overFiveYears", "yearOfInc", "withinFiveYears",
"yetToBeFormed", "aggregateNetAssetValueRange", "revenueRange",
"minimumInvestmentAccepted", "totalAmountSold", "totalOfferingAmount",
"totalRemaining", "firstName", "lastName", "middleName", "relationship",
"relationshipClarification", "dollarAmount", "isEstimate", "associatedBDCRDNumber",
"associatedBDName", "foreignSolicitation", "recipientCRDNumber",
"recipientName", "description", "state", "statesOfSolicitationList",
"authorizedRepresentative", "nameOfSigner", "signatureTitle",
"submissionType", "testOrLive", "dateOfFirstSale", "yetToOccur",
"isAmendment", "descriptionOfOtherType", "isDebtType", "isEquityType",
"isMineralPropertyType", "isOptionToAcquireType", "isOtherType",
"isPooledInvestmentFundType", "isSecurityToBeAcquiredType", "isTenantInCommonType",
'notSubjectToSection16', 'rptOwnerStreet1', 'rptOwnerStreet2',
"liveTestFlag", "confirmingCopyFlag", "returnCopyFlag", "overrideInternetFlag",
"ccc", "reportCalendarOrQuarter", "filingManagername", "filingManageraddressstreet1",
"filingManageraddressstreet2", "filingManageraddresscity", "filingManageraddressstateOrCountry",
'filingManagerstateOrCountryDescription',
"filingManageraddresszipCode", "reportType", "form13FFileNumber",
"provideInfoForInstruction5", "name", "title", "phone", "signature",
"otherIncludedManagersCount", "tableEntryTotal", "tableValueTotal",
"isConfidentialOmitted",
"nameOfIssuer", "titleOfClass", "cusip", "value", "investmentDiscretion",
"otherManager", "putCall", "sshPrnamt", "sshPrnamtType", "Sole",
"Shared", "None",
"offeringFileNumber", "sinceLastFiling", "jurisdictionOrganization",
"yearIncorporation", "sicCode", "irsNum", "fullTimeEmployees",
"partTimeEmployees", "phoneNumber", "connectionName", "industryGroup",
"cashEquivalents", "investmentSecurities", "accountsReceivable",
"propertyPlantEquipment", "totalAssets", "accountsPayable", "longTermDebt",
"totalLiabilities", "totalStockholderEquity", "totalLiabilitiesAndEquity",
"totalRevenues", "costAndExpensesApplToRevenues", "depreciationAndAmortization",
"netIncome", "earningsPerShareBasic", "earningsPerShareDiluted",
"nameAuditor", "commonEquityClassName", "outstandingCommonEquity",
"commonCusipEquity", "publiclyTradedCommonEquity", "preferredEquityClassName",
"outstandingPreferredEquity", "preferredCusipEquity", "publiclyTradedPreferredEquity",
"debtSecuritiesClassName", "outstandingDebtSecurities", "cusipDebtSecurities",
"publiclyTradedDebtSecurities", "certifyIfTrue", "certifyIfNotDisqualified",
"summaryInfo", "financialStatementAuditStatus", "securitiesOfferedTypes",
"offerDelayedContinuousFlag", "offeringYearFlag", "offeringAfterQualifFlag",
"offeringBestEffortsFlag", "solicitationProposedOfferingFlag",
"resaleSecuritiesAffiliatesFlag", "securitiesOffered", "outstandingSecurities",
"pricePerSecurity", "issuerAggregateOffering", "securityHolderAggegate",
"qualificationOfferingAggregate", "concurrentOfferingAggregate",
"totalAggregateOffering", "underwritersServiceProviderName",
"underwritersFees", "auditorServiceProviderName", "auditorFees",
"legalServiceProviderName", "legalFees", "promotersServiceProviderName",
"promotersFees", "brokerDealerCrdNumber", "estimatedNetAmount",
"clarificationResponses", "jurisdictionsOfSecOfferedSame", "issueJuridicationSecuritiesOffering",
"dealersJuridicationSecuritiesOffering", "securitiesIssuerName",
"securitiesIssuerTitle", "securitiesIssuedTotalAmount", "securitiesPrincipalHolderAmount",
"securitiesIssuedAggregateAmount", "securitiesActExcemption",
"certifyIfBadActor", "salesCommissionsServiceProviderName",
"salesCommissionsServiceProviderFees", "jurisdictionsOfSecOfferedNone",
"ifUnregsiteredNone", "blueSkyServiceProviderName", "blueSkyFees",
'indicateTier1Tier2Offering', 'X.1.A.A.', 'X.1.A.A.', 'aggregateConsiderationBasis',
'findersFeesServiceProviderName' , 'finderFeesFee',
'loans', 'propertyAndEquipment', 'deposits', 'totalInterestIncome',
'totalInterestExpenses', 'securitiesOfferedOtherDesc', 'comment',
"assetTypeNumber",
"assetNumber",
"assetGroupNumber",
"reportPeriodBeginningDate",
"reportPeriodEndDate",
"issuerName",
"originalIssuanceDate",
"originalSecurityAmount",
"originalSecurityTermNumber",
"securityMaturityDate",
"originalAmortizationTermNumber",
"originalInterestRatePercentage",
"accrualTypeCode",
"interestRateTypeCode",
"originalInterestOnlyTermNumber",
"firstPaymentDate",
"underwritingIndicator",
"securityTitleName",
"denominationNumber",
"currencyName",
"trusteeName",
"secFileNumber",
"cik",
"callableIndicator",
"paymentFrequencyCode",
"zeroCouponIndicator",
"assetAddedIndicator",
"assetModifiedIndicator",
"reportPeriodBeginningAssetBalanceAmount",
"reportPeriodBeginningScheduledAssetBalanceAmount",
"reportPeriodScheduledPaymentAmount",
"reportPeriodInterestRatePercentage",
"totalActualPaidAmount",
"actualInterestCollectionPercentage",
"actualPrincipalCollectedAmount",
"actualOtherCollectionAmount",
"otherPrincipalAdjustmentAmount",
"otherInterestAdjustmentAmount",
"scheduledInterestAmount",
"scheduledPrincipalAmount",
"endReportingPeriodActualBalanceAmount",
"endReportingPeriodScheduledBalanceAmount",
"servicingFeePercentage",
"servicingFlatFeeAmount",
"zeroBalanceCode",
"zeroBalanceEffectiveDate",
"remainingTermToMaturityNumber",
"currentDelinquentStatusNumber",
"paymentPastDueDaysNumber",
"paymentPastDueNumber",
"nextReportPeriodPaymentDueAmount",
"nextDueDate",
"primaryLoanServicerName",
"mostRecentServicingTransferReceivedDate",
"assetSubjectToDemandIndicator",
"statusAssetSubjectToDemandCode",
"repurchaseAmount",
"demandResolutionDate",
"repurchaserName",
"repurchaseReplacementReasonCode",
"reportPeriodBeginDate",
"originalLoanPurposeCode",
"originatorName",
"originalLoanAmount",
"originalLoanMaturityDate",
"originalInterestRateTypeCode",
"originalLienPositionCode",
"mostRecentJuniorLoanBalanceAmount",
"mostRecentJuniorLoanBalanceDate",
"mostRecentSeniorLoanAmount",
"mostRecentSeniorLoanAmountDate",
"loanTypeMostSeniorLienCode",
"mostSeniorLienHybridPeriodNumber",
"mostSeniorLienNegativeAmortizationLimitPercentage",
"mostSeniorLienOriginationDate",
"prepaymentPenaltyIndicator",
"negativeAmortizationIndicator",
"modificationIndicator",
"modificationNumber",
"mortgageInsuranceRequirementIndicator",
"balloonIndicator",
"coveredHighCostCode",
"servicerHazardInsuranceCode",
"refinanceCashOutAmount",
"totalOriginationDiscountAmount",
"brokerIndicator",
"channelCode",
"nationalMortgageLicenseSystemCompanyNumber",
"buyDownNumber",
"loanDelinquencyAdvanceNumber",
"originationARMIndexCode",
"armMarginPercentage",
"fullyIndexedRatePercentage",
"initialFixedRatePeriodHybridARMNumber",
"initialInterestRateDecreasePercentage",
"initialInterestRateIncreasePercentage",
"indexLookbackNumber",
"subsequentInterestRateResetNumber",
"lifetimeRateCeilingPercentage",
"lifetimeRateFloorPercentage",
"subsequentInterestRateDecreasePercentage",
"subsequentInterestRateIncreasePercentage",
"subsequentPaymentResetNumber",
"armRoundCode",
"armRoundPercentage",
"optionArmIndicator",
"paymentMethodAfterRecastCode",
"initialMinimumPaymentAmount",
"convertibleIndicator",
"HELOCIndicator",
"HELOCDrawNumber",
"prepaymentPenaltyCalculationCode",
"prepaymentPenaltyTypeCode",
"prepaymentPenaltyTotalTermNumber",
"prepaymentPenaltyHardTermNumber",
"negativeAmortizationLimitAmount",
"negativeAmortizationInitialRecastNumber",
"negativeAmortizationSubsequentRecastNumber",
"negativeAmortizationBalanceAmount",
"initialFixedPaymentNumber",
"initialPaymentCapPercentage",
"subsequentPaymentCapPercentage",
"initialMinimumPaymentResetNumber",
"subsequentMinimumPaymentResetNumber",
"minimumPaymentAmount",
"geographicalLocation",
"occupancyStatusCode",
"mostRecentOccupancyStatusCode",
"propertyTypeCode",
"mostRecentPropertyValueAmount",
"mostRecentPropertyValueTypeCode",
"mostRecentPropertyValueDate",
"mostRecentAVMModelCode",
"mostRecentAVMConfidenceNumber",
"originalCLTVPercentage",
"originalLTVPercentage",
"originalObligorNumber",
"originalObligorCreditScoreNumber",
"originalObligorCreditScoreType",
"mostRecentObligorCreditScoreNumber",
"mostRecentObligorCreditScoreType",
"mostRecentObligorCreditScoreDate",
"obligorIncomeVerificationLevelCode",
"IRSForm4506TIndicator",
"originatorFrontEndDTIPercentage",
"originatorBackEndDTIPercentage",
"obligorEmploymentVerificationCode",
"obligorEmploymentLengthCode",
"obligorAssetVerificationCode",
"originalPledgedAssetsAmount",
"qualificationMethodCode",
"mortgageInsuranceCompanyName",
"mortgageInsuranceCoveragePercentage",
"poolInsuranceCompanyName",
"poolInsuranceStopLossPercentage",
"mortgageInsuranceCoverageTypeCode",
"modificationIndicatorReportingPeriod",
"nextPaymentDueDate",
"advancingMethodCode",
"servicingAdvanceMethodologyCode",
"stopPrincipalInterestAdvancingDate",
"reportingPeriodBeginningLoanBalanceAmount",
"reportingPeriodBeginningScheduledLoanBalanceAmount",
"nextReportingPeriodPaymentDueAmount",
"reportingPeriodInterestRatePercentage",
"nextInterestRatePercentage",
"otherAssessedUncollectedServicerFeeamount",
"otherServicingFeeRetainedByServicerAmount",
"reportingPeriodEndActualBalanceAmount",
"reportingPeriodEndScheduledBalanceAmount",
"reportingPeriodScheduledPaymentAmount",
"actualInterestCollectedAmount",
"actualOtherCollectedAmount",
"paidThroughDate",
"interestPaidThroughDate",
"paidFullAmount",
"servicerAdvancedPrincipalAmount",
"servicerAdvancedRepaidPrincipalAmount",
"servicerAdvancedCumulativePrincipalAmount",
"servicerAdvanceInterestAmount",
"servicerAdvanceRepaidInterestAmount",
"servicerAdvanceCumulativeInterestAmount",
"servicerAdvanceTaxesInsuranceAmount",
"servicerAdvanceRepaidTaxesInsuranceAmount",
"servicerAdvanceCumulativeTaxesInsuranceAmount",
"servicerAdvanceCorporateAmount",
"servicerAdvanceRepaidCorporateAmount",
"servicerAdvanceCumulativeCorporateAmount",
"mostRecentTwelveMonthHistoryCode",
"nextResetRatePercentage",
"nextPaymentChangeDate",
"nextInterestRateChangeDate",
"nextResetPaymentAmount",
"exercisedArmConversionOptionIndicator",
"primaryServicerName",
"masterServicerName",
"specialServicerName",
"subServicerName",
"assetSubjectDemandIndicator",
"assetSubjectDemandStatusCode",
"repurchaseReplacementCode",
"chargeOffPrincipalAmount",
"chargeOffInterestAmount",
"lossMitigationTypeCode",
"mostRecentLoanModificationEventCode",
"mostRecentLoanModificationEffectiveDate",
"postModificationMaturityDate",
"postModificationInterestRateTypeCode",
"postModificationAmortizationTypeCode",
"postModificationInterestPercentage",
"postModificationFirstPaymentDate",
"postModificationLoanBalanceAmount",
"postModificationPrincipalInterestPaymentAmount",
"totalCapAmount",
"incomeVerificationIndicatorAtModification",
"modificationFrontEndDebtToIncomePercentage",
"modificationBackEndDebtToIncomePercentage",
"totalDeferredAmount",
"forgivenPrincipalCumulativeAmount",
"forgivenPrincipalReportingPeriodAmount",
"forgivenInterestCumulativeAmount",
"forgivenInterestReportingPeriodAmount",
"actualEndingBalanceTotalDebtAmount",
"scheduledEndingBalanceTotalDebtAmount",
"postModificationARMCode",
"postModificationARMIndexCode",
"postModificationMarginPercentage",
"postModificationInterestResetNumber",
"postModificationNextResetDate",
"postModificationIndexLookbackNumber",
"postModificationARMRoundingCode",
"postModificationARMRoundingPercentage",
"postModificationInitialMinimumPayment",
"postModificationNextPaymentAdjustmentDate",
"postModificationARMPaymentRecastFrequency",
"postModificationLifetimeFloorPercentage",
"postModificationLifetimeCeilingPercentage",
"postModificationInitialInterestRateIncreasePercentage",
"postModificationInitialInterestRateDecreasePercentage",
"postModificationSubsequentInterestIncreasePercentage",
"postModificationSubsequentInterestRateDecreasePercentage",
"postModificationPaymentCapPercentage",
"postModificationPaymentMethodAfterRecastCode",
"postModificationARMInterestRateTeaserNumber",
"postModificationARMPaymentTeaserNumber",
"postModificationARMNegativeAmortizationIndicator",
"postModificationARMNegativeAmortizationCapPercentage",
"postModificationInterestOnlyTermNumber",
"postModificationInterestOnlyLastPaymentDate",
"postModificationBalloonAmount",
"postModificationInterestRateStepIndicator",
"postModificationStepInterestPercentage",
"postModificationStepDate",
"postModificationStepPrincipalInterestPaymentAmount",
"postModificationStepNumber",
"postModificationMaximumFutureStepAgreementPercentage",
"postModificationMaximumStepAgreementRateDate",
"nonInterestBearingDeferredPrincipalCumulativeAmount",
"nonInterestBearingDeferredPrincipalReportingPeriodAmount",
"recoveryDeferredPrincipalReportingPeriodAmount",
"nonInterestBearingDeferredPaidFullAmount",
"nonInterestBearingDeferredInterestFeeReportingPeriodAmount",
"nonInterestBearingDeferredInterestFeeCumulativeAmount",
"recoveryDeferredInterestFeeReportingPeriodAmount",
"mostRecentForbearancePlanOrTrialModificationStartDate",
"mostRecentForbearancePlanOrTrialModificationScheduledEndDate",
"mostRecentTrialModificationViolatedDate",
"mostRecentRepaymentPlanStartDate",
"mostRecentRepaymentPlanScheduledEndDate",
"mostRecentRepaymentPlanViolatedDate",
"shortSaleAcceptedOfferAmount",
"mostRecentLossMitigationExitDate",
"mostRecentLossMitigationExitCode",
"attorneyReferralDate",
"foreclosureDelayReasonCode",
"foreclosureExitDate",
"foreclosureExitReasonCode",
"noticeOfIntentDate",
"mostRecentAcceptedREOOfferAmount",
"mostRecentAcceptedREOOfferDate",
"grossLiquidationProceedsAmount",
"netSalesProceedsAmount",
"reportingPeriodLossPassedToIssuingEntityAmount",
"cumulativeTotalLossPassedToIssuingEntityAmount",
"subsequentRecoveryAmount",
"evictionIndicator",
"reoExitDate",
"reoExitReasonCode",
"UPBLiquidationAmount",
"servicingFeesClaimedAmount",
"servicerAdvanceReimbursedPrincipalAmount",
"servicerAdvanceReimbursedInterestAmount",
"servicerAdvanceReimbursedTaxesInsuranceAmount",
"servicerAdvanceReimbursedCorporateAmount",
"REOManagementFeesAmount",
"cashKeyDeedAmount",
"performanceIncentiveFeesAmount",
"mortgageInsuranceClaimFiledDate",
"mortgageInsuranceClaimAmount",
"mortgageInsuranceClaimPaidDate",
"mortgageInsuranceClaimPaidAmount",
"mortgageInsuranceClaimDeniedRescindedDate",
"marketableTitleTransferDate",
"nonPayStatusCode",
"reportingActionCode",
"GroupID",
"reportingPeriodBeginningDate",
"reportingPeriodEndDate",
"originationDate",
"originalTermLoanNumber",
"maturityDate",
"interestRateSecuritizationPercentage",
"interestAccrualMethodCode",
"firstLoanPaymentDueDate",
"lienPositionSecuritizationCode",
"loanStructureCode",
"paymentTypeCode",
"periodicPrincipalAndInterestPaymentSecuritizationAmount",
"scheduledPrincipalBalanceSecuritizationAmount",
"NumberPropertiesSecuritization",
"NumberProperties",
"graceDaysAllowedNumber",
"interestOnlyIndicator",
"prepaymentPremiumIndicator",
"modifiedIndicator",
"armIndexCode",
"firstRateAdjustmentDate",
"firstPaymentAdjustmentDate",
"armMarginNumber",
"lifetimeRateCapPercentage",
"periodicRateIncreaseLimitPercentage",
"periodicRateDecreaseLimitPercentage",
"periodicPaymentAdjustmentMaximumAmount",
"periodicPaymentAdjustmentMaximumPercent",
"rateResetFrequencyCode",
"paymentResetFrequencyCode",
"indexLookbackDaysNumber",
"prepaymentLockOutEndDate",
"yieldMaintenanceEndDate",
"prepaymentPremiumsEndDate",
"maximumNegativeAmortizationAllowedPercentage",
"maximumNegativeAmortizationAllowedAmount",
"negativeAmortizationDeferredInterestCapAmount",
"deferredInterestCumulativeAmount",
"deferredInterestCollectedAmount",
"property",
"reportPeriodModificationIndicator",
"reportPeriodBeginningScheduleLoanBalanceAmount",
"totalScheduledPrincipalInterestDueAmount",
"servicerTrusteeFeeRatePercentage",
"unscheduledPrincipalCollectedAmount",
"reportPeriodEndActualBalanceAmount",
"reportPeriodEndScheduledLoanBalanceAmount",
"hyperAmortizingDate",
"servicingAdvanceMethodCode",
"nonRecoverabilityIndicator",
"totalPrincipalInterestAdvancedOutstandingAmount",
"totalTaxesInsuranceAdvancesOutstandingAmount",
"otherExpensesAdvancedOutstandingAmount",
"paymentStatusLoanCode",
"armIndexRatePercentage",
"nextInterestRateChangeAdjustmentDate",
"nextPaymentAdjustmentDate",
"mostRecentSpecialServicerTransferDate",
"mostRecentMasterServicerReturnDate",
"realizedLossToTrustAmount",
"liquidationPrepaymentCode",
"liquidationPrepaymentDate",
"prepaymentPremiumYieldMaintenanceReceivedAmount",
"workoutStrategyCode",
"lastModificationDate",
"modificationCode",
"postModificationPaymentAmount",
"postModificationAmortizationPeriodAmount",
"propertyName",
"propertyAddress",
"propertyCity",
"propertyState",
"propertyZip",
"propertyCounty",
"netRentableSquareFeetNumber",
"netRentableSquareFeetSecuritizationNumber",
"unitsBedsRoomsNumber",
"unitsBedsRoomsSecuritizationNumber",
"yearBuiltNumber",
"yearLastRenovated",
"valuationSecuritizationAmount",
"valuationSourceSecuritizationCode",
"valuationSecuritizationDate",
"mostRecentValuationAmount",
"mostRecentValuationDate",
"mostRecentValuationSourceCode",
"physicalOccupancySecuritizationPercentage",
"mostRecentPhysicalOccupancyPercentage",
"propertyStatusCode",
"defeasanceOptionStartDate",
"DefeasedStatusCode",
"largestTenant",
"squareFeetLargestTenantNumber",
"leaseExpirationLargestTenantDate",
"secondLargestTenant",
"squareFeetSecondLargestTenantNumber",
"leaseExpirationSecondLargestTenantDate",
"thirdLargestTenant",
"squareFeetThirdLargestTenantNumber",
"leaseExpirationThirdLargestTenantDate",
"financialsSecuritizationDate",
"mostRecentFinancialsStartDate",
"mostRecentFinancialsEndDate",
"revenueSecuritizationAmount",
"mostRecentRevenueAmount",
"operatingExpensesSecuritizationAmount",
"operatingExpensesAmount",
"netOperatingIncomeSecuritizationAmount",
"mostRecentNetOperatingIncomeAmount",
"netCashFlowFlowSecuritizationAmount",
"mostRecentNetCashFlowAmount",
"netOperatingIncomeNetCashFlowSecuritizationCode",
"netOperatingIncomeNetCashFlowCode",
"mostRecentDebtServiceAmount",
"debtServiceCoverageNetOperatingIncomeSecuritizationPercentage",
"mostRecentDebtServiceCoverageNetOperatingIncomePercentage",
"debtServiceCoverageNetCashFlowSecuritizationPercentage",
"mostRecentDebtServiceCoverageNetCashFlowpercentage",
"debtServiceCoverageSecuritizationCode",
"mostRecentDebtServiceCoverageCode",
"mostRecentAnnualLeaseRolloverReviewDate",
"reportingPeriodEndingDate",
"originalLoanTerm",
"loanMaturityDate",
"interestCalculationTypeCode",
"originalFirstPaymentDate",
"gracePeriodNumber",
"subvented",
"vehicleManufacturerName",
"vehicleModelName",
"vehicleNewUsedCode",
"vehicleModelYear",
"vehicleTypeCode",
"vehicleValueAmount",
"vehicleValueSourceCode",
"obligorCreditScoreType",
"obligorCreditScore",
"coObligorIndicator",
"paymentToIncomePercentage",
"obligorGeographicLocation",
"reportingPeriodModificationIndicator",
"nextReportingPeriodPaymentAmountDue",
"otherServicerFeeRetainedByServicer",
"otherAssessedUncollectedServicerFeeAmount",
"reportingPeriodActualEndBalanceAmount",
"totalActualAmountPaid",
"servicerAdvancedAmount",
"currentDelinquencyStatus",
"chargedoffPrincipalAmount",
"recoveredAmount",
"modificationTypeCode",
"paymentExtendedNumber",
"repossessedIndicator",
"repossessedProceedsAmount",
"reportingPeriodBeginDate",
"acquisitionCost",
"originalLeaseTermNumber",
"scheduledTerminationDate",
"gracePeriod",
"baseResidualValue",
"baseResidualSourceCode",
"contractResidualValue",
"lesseeCreditScoreType",
"lesseeCreditScore",
"lesseeIncomeVerificationLevelCode",
"lesseeEmploymentVerificationCode",
"coLesseePresentIndicator",
"lesseeGeographicLocation",
"remainingTermNumber",
"reportingPeriodSecuritizationValueAmount",
"securitizationDiscountRate",
"otherLeaseLevelServicingFeesRetainedAmount",
"reportingPeriodEndingActualBalanceAmount",
"reportingPeriodEndActualSecuritizationAmount",
"primaryLeaseServicerName",
"DemandResolutionDate",
"repurchaseOrReplacementReasonCode",
"chargedOffAmount",
"leaseExtended",
"terminationIndicator",
"excessFeeAmount",
"liquidationProceedsAmount",
"commentNumber", "commentColumn", "commentDescription",
'previousAccessionNumber', 'itemNumber', 'fieldName', 'notes', 'sequenceNumber',
"amendmentNo",
"amendmentType",
"confDeniedExpired",
'additionalInformation',
'fileNumber'
),
nameActual = c(
"priceExerciseConversion",
"dateDeemedExecution",
"codeOwnershipDirectIndirect",
"idDocument",
"isEquitySwapInvolved",
"dateExercised",
"dateExpiration",
"descriptionFootnote",
"isDirector",
"isOfficer",
"isOther",
"idCIKIssuer",
"nameIssuer",
"idTickerIssuer",
"isTenPercentOwner",
"descriptionNatureOfOwnership",
"isNoSecuritiesOwned",
"isNotSubjectToSection16",
"titleOfficer",
"descriptionOtherText",
"dateReport",
"countSharesOwnedPostTransaction",
"descriptionRemarks",
"idCIKOwner",
"cityOwenr",
"nameOwner",
"stateOwner",
"descriptionStateOwner",
"addressStreet1Owner",
"addressStreet2Owner",
"zipcodeOwner",
"idSchema",
"titleSecurity",
"countSharesOwnedPostTransaction",
"dateSignature",
"nameSignature",
"codeTransactionAcquiredDisposed",
"codeTransaction",
"dateTransaction",
"idFormTransaction",
"pricePerShareTransaction",
"countSharesTransaction",
"idCodeTimelinessTransaction",
"amountTransaction",
"countSharesUnderlying",
"titleSecurityUnderlying",
"descriptionResponse", "isBusinessCombinationTransaction",
"idCIK", "isMoreThanOneYear", "nameEntityPrevius", "listNameEntityPreviousEDGAR",
"nameEntity", "typeEntity", "descriptionEntityTypeOther", "idFederalExemptionsExclusions",
"typeIndustryGroup", "typeInvestmentFund", "descriptionInvestmentFund",
"hasNonAccreditedInvestors", "countInvestorsNonAccredited",
"countInvestorsActive", "cityEntity", "stateEntity", "descriptionStateEntity",
"addressStreet1Entity", "addressStreet2Entity", "zipcodeEntity", "phoneNumberEntity", "listIssuerPreviousName",
"jurisdictionOfInc", "isOverFiveYearsOld", "hasYearOfInc", "isFormedWithinFiveYears",
"isYetToBeFormed", "rangeAgregateNetAssetValue", "rangeRevenue",
"amountInvestmentMinimum", "amountSoldTotal", "amountOfferingTotal",
"amountRemaining", "nameFirst", "nameLast", "nameMiddle", "relationshipEntity",
"descriptionRelationship", "amountDollars", "isEstimate", "idCRDBroker",
"nameBroker", "isForeignSolicitation", "idCRDRecipient",
"nameRecipient", "stateDescription", "state", "listStatesSolicitation",
"isAuthorizedRepresentative", "nameSignatory", "titleSignatory",
"idForm", "codeTestOrLive", "dateFirstSale", "isYetToOccur",
"isAmendment", "descriptionOtherType", "isDebtType", "isEquityType",
"isMineralPropertyType", "isOptionToAcquireType", "isOtherType",
"isPooledInvestmentFundType", "isSecurityToBeAcquiredType", "isTenantInCommonType",
'isNotSubjectToSection16', 'addressStreet1Owner', 'addressStreet2Owner',
"isLiveTestFlag", "isConfirmingCopyFlag", "isReturnCopyFlag", "isOverrideInternetFlag",
"idCCC", "dateReportCalendarOrQuarter", "nameFilingManager", "addressStreet1FilingManager",
"addressStreet2FilingManager", "cityFilingManager", "stateFilingManager",
'descriptionStateFilingManager',
"zipcodeFilingManager", "typeReport", "idSEC",
"codeProvideInfoForInstruction5", "nameEntity", "titleEntity", "phoneEntity", "signatureEntity",
"countOtherIncludedManagers", "countTableEntries", "amountValueHoldings",
"isConfidentialOmitted", "nameIssuer", "classSecurities", "idCUSIP", "valueSecurities", "typeInvestmentDiscretion",
"descriptionOtherManager", "codePutCall", "countSharesPrincipal", "codeSharesPrincipal", "countSharesVotingSole",
"countSharesVotingShared", "countSharesVotingNone",
"idSEC", "isSinceLastFiling", "codeJurisdictionOrganization",
"yearIncorporation", "idSIC", "idIRS", "countEmployeesFullTime",
"countEmployeesPartTime", "phoneEntity", "nameConnection", "nameIndustry",
"amountCashEquivalents", "amountInvestmentSecurities", "amountAccountsReceivable",
"amountPropertyPlantEquipment", "amountAssetsTotal", "amountAccountsPayable", "amountLongTermDebt",
"amountLiabilitiesTotal", "amountStockholderEquityTotal", "amountLiabilitiesAndEquityTotal",
"amountRevenuesTotal", "amountCostAndExpensesOfRevenue", "amountDepreciationAndAmortization",
"amountNetIncome", "pershareEarningsBasic", "pershareEarningsDiluted",
"nameAuditor", "nameCommonEquityClass", "amountCommonEquityOutstanding",
"idCUSIPCommonEquity", "isCommonEquityPublic", "namePreferredEquityClass",
"amountPreferredEquityOutstanding", "idCusipPreferrdEquity", "isdPreferredEquityPublic",
"nameDebtSecuritiesClass", "amountOutstandingDebtSecurities", "idCUSIPDebtSecurities",
"isDebtSecuritiesPublic", "isCertifyIfTrue", "isCertifyIfNotDisqualified",
"codeTier1Tier2Offering", "codeFinancialStatementAuditStatus", "codeSecuritiesOfferedTypes",
"codeOfferDelayedContinuous", "codeOfferingYearFlag", "codeOfferingAfterQualifFlag",
"codeOfferingBestEffortsFlag", "codeSolicitationProposedOfferingFlag",
"codeResaleSecuritiesAffiliates", "countSecuritiesOffered", "countSecuritiesOutstanding",
"persharePrice", "amountOfferingIssuer", "amountOfferingExistingShareholdersSelling",
"amountOfferingSold12MonthQualifiedOffering", "amountOfferingSoldConcurrent",
"amountOfferingTotal", "nameUnderwritr",
"amountUnderwritersFees", "nameAuditor", "amountAuditorFees",
"nameLegal", "amountLegalFees", "namePromoter",
"amountPromotersFees", "idCRDBroker", "amountOfferringProceedsNet",
"descriptionResponse", "isJurisdictionsOfSecOfferedSame", "locatonJuridicationSecuritiesOffering",
"locationDealersJuridicationSecuritiesOffering", "nameSecuritiesIssuer",
"titleSecuritiesOffered", "amountSecuritiesIssued", "amountSecuritiesPrincipalHolder",
"amountSecuritiesIssuedTotal", "nameSecuritiesActExemption",
"isBadActor", "nameSalesCommissionsServiceProvider",
"amountSalesCommissionsFees", "isJurisdictionsSecuritiesOfferingNone",
"isUnRegisteredNone",
"nameBlueSkyServiceProvider", "amountBlueSkyFees",
'isTier1Tier2Offering', 'idForm', 'idForm', 'amountOfferingConsiderationBasis',
'nameFindersFeeProvider' , 'amountFindersFee',
'amountLoans', 'amountPropertyAndEquipment', 'amountDeposits', 'amountInterestIncomeTotal',
'amountInterestExpenseTotal', 'descriptionOtherSecuritiesOffered',
'commentFiling',
"numberAssetType",
"numberAsset",
"numberAssetGroup",
"dateReportPeriodBeginning",
"dateReportPeriodEnd",
"nameIssuer",
"dateOriginalIssuance",
"amountOriginalSecurity",
"numberOriginalSecurityTerm",
"dateSecurityMaturity",
"numberOriginalAmortizationTerm",
"percentageOriginalInterestRate",
"codeAccrualType",
"codeInterestRateType",
"numberOriginalInterestOnlyTerm",
"dateFirstPayment",
"hasUnderwriting",
"nameSecurityTitle",
"numberDenomination",
"nameCurrency",
"nameTrustee",
"numberSecFile",
"idCIK",
"hasCallable",
"codePaymentFrequency",
"hasZeroCoupon",
"hasAssetAdded",
"hasAssetModified",
"amountReportPeriodBeginningAssetBalance",
"amountReportPeriodBeginningScheduledAssetBalance",
"amountReportPeriodScheduledPayment",
"percentageReportPeriodInterestRate",
"amountTotalActualPaid",
"percentageActualInterestCollection",
"amountActualPrincipalCollected",
"amountActualOtherCollection",
"amountOtherPrincipalAdjustment",
"amountOtherInterestAdjustment",
"amountScheduledInterest",
"amountScheduledPrincipal",
"amountEndReportingPeriodActualBalance",
"amountEndReportingPeriodScheduledBalance",
"percentageServicingFee",
"amountServicingFlatFee",
"codeZeroBalance",
"dateZeroBalanceEffective",
"numberRemainingTermToMaturity",
"numberCurrentDelinquentStatus",
"numberPaymentPastDueDays",
"numberPaymentPastDue",
"amountNextReportPeriodPaymentDue",
"dateNextDue",
"namePrimaryLoanServicer",
"dateMostRecentServicingTransferReceived",
"hasAssetSubjectToDemand",
"codeStatusAssetSubjectToDemand",
"amountRepurchase",
"dateDemandResolution",
"nameRepurchaser",
"codeRepurchaseReplacementReason",
"dateReportPeriodBegin",
"codeOriginalLoanPurpose",
"nameOriginator",
"amountOriginalLoan",
"dateOriginalLoanMaturity",
"codeOriginalInterestRateType",
"codeOriginalLienPosition",
"amountMostRecentJuniorLoanBalance",
"dateMostRecentJuniorLoanBalance",
"amountMostRecentSeniorLoan",
"dateMostRecentSeniorLoanAmount",
"codeLoanTypeMostSeniorLien",
"numberMostSeniorLienHybridPeriod",
"percentageMostSeniorLienNegativeAmortizationLimit",
"dateMostSeniorLienOrigination",
"hasPrepaymentPenalty",
"hasNegativeAmortization",
"hasModification",
"numberModification",
"hasMortgageInsuranceRequirement",
"hasBalloon",
"codeCoveredHighCost",
"codeServicerHazardInsurance",
"amountRefinanceCashOut",
"amountTotalOriginationDiscount",
"hasBroker",
"codeChannel",
"numberNationalMortgageLicenseSystemCompany",
"numberBuyDown",
"numberLoanDelinquencyAdvance",
"codeOriginationARMIndex",
"percentageArmMargin",
"percentageFullyIndexedRate",
"numberInitialFixedRatePeriodHybridARM",
"percentageInitialInterestRateDecrease",
"percentageInitialInterestRateIncrease",
"numberIndexLookback",
"numberSubsequentInterestRateReset",
"percentageLifetimeRateCeiling",
"percentageLifetimeRateFloor",
"percentageSubsequentInterestRateDecrease",
"percentageSubsequentInterestRateIncrease",
"numberSubsequentPaymentReset",
"codeArmRound",
"percentageArmRound",
"hasOptionArm",
"codePaymentMethodAfterRecast",
"amountInitialMinimumPayment",
"hasConvertible",
"hasHELOC",
"numberHELOCDraw",
"codePrepaymentPenaltyCalculation",
"codePrepaymentPenaltyType",
"numberPrepaymentPenaltyTotalTerm",
"numberPrepaymentPenaltyHardTerm",
"amountNegativeAmortizationLimit",
"numberNegativeAmortizationInitialRecast",
"numberNegativeAmortizationSubsequentRecast",
"amountNegativeAmortizationBalance",
"numberInitialFixedPayment",
"percentageInitialPaymentCap",
"percentageSubsequentPaymentCap",
"numberInitialMinimumPaymentReset",
"numberSubsequentMinimumPaymentReset",
"amountMinimumPayment",
"locationGeographical",
"codeOccupancyStatus",
"codeMostRecentOccupancyStatus",
"codePropertyType",
"amountMostRecentPropertyValue",
"codeMostRecentPropertyValueType",
"dateMostRecentPropertyValue",
"codeMostRecentAVMModel",
"numberMostRecentAVMConfidence",
"percentageOriginalCLTV",
"percentageOriginalLTV",
"numberOriginalObligor",
"numberOriginalObligorCreditScore",
"typeOriginalObligorCreditScore",
"numberMostRecentObligorCreditScore",
"typeMostRecentObligorCreditScore",
"dateMostRecentObligorCreditScore",
"codeObligorIncomeVerificationLevel",
"hasIRSForm4506T",
"percentageOriginatorFrontEndDTI",
"percentageOriginatorBackEndDTI",
"codeObligorEmploymentVerification",
"codeObligorEmploymentLength",
"codeObligorAssetVerification",
"amountOriginalPledgedAssets",
"codeQualificationMethod",
"nameMortgageInsuranceCompany",
"percentageMortgageInsuranceCoverage",
"namePoolInsuranceCompany",
"percentagePoolInsuranceStopLoss",
"codeMortgageInsuranceCoverageType",
"periodModificationHasReporting",
"dateNextPaymentDue",
"codeAdvancingMethod",
"codeServicingAdvanceMethodology",
"dateStopPrincipalInterestAdvancing",
"amountReportingPeriodBeginningLoanBalance",
"amountReportingPeriodBeginningScheduledLoanBalance",
"amountNextReportingPeriodPaymentDue",
"percentageReportingPeriodInterestRate",
"percentageNextInterestRate",
"feeamountOtherAssessedUncollectedServicer",
"amountOtherServicingFeeRetainedByServicer",
"amountReportingPeriodEndActualBalance",
"amountReportingPeriodEndScheduledBalance",
"amountReportingPeriodScheduledPayment",
"amountActualInterestCollected",
"amountActualOtherCollected",
"datePaidThrough",
"dateInterestPaidThrough",
"amountPaidFull",
"amountServicerAdvancedPrincipal",
"amountServicerAdvancedRepaidPrincipal",
"amountServicerAdvancedCumulativePrincipal",
"amountServicerAdvanceInterest",
"amountServicerAdvanceRepaidInterest",
"amountServicerAdvanceCumulativeInterest",
"amountServicerAdvanceTaxesInsurance",
"amountServicerAdvanceRepaidTaxesInsurance",
"amountServicerAdvanceCumulativeTaxesInsurance",
"amountServicerAdvanceCorporate",
"amountServicerAdvanceRepaidCorporate",
"amountServicerAdvanceCumulativeCorporate",
"codeMostRecentTwelveMonthHistory",
"percentageNextResetRate",
"dateNextPaymentChange",
"dateNextInterestRateChange",
"amountNextResetPayment",
"hasExercisedArmConversionOption",
"namePrimaryServicer",
"nameMasterServicer",
"nameSpecialServicer",
"nameSubServicer",
"hasAssetSubjectDemand",
"codeAssetSubjectDemandStatus",
"codeRepurchaseReplacement",
"amountChargeOffPrincipal",
"amountChargeOffInterest",
"codeLossMitigationType",
"codeMostRecentLoanModificationEvent",
"dateMostRecentLoanModificationEffective",
"datePostModificationMaturity",
"codePostModificationInterestRateType",
"codePostModificationAmortizationType",
"percentagePostModificationInterest",
"datePostModificationFirstPayment",
"amountPostModificationLoanBalance",
"amountPostModificationPrincipalInterestPayment",
"amountTotalCap",
"modificationIncomeVerificationHasAt",
"percentageModificationFrontEndDebtToIncome",
"percentageModificationBackEndDebtToIncome",
"amountTotalDeferred",
"amountForgivenPrincipalCumulative",
"amountForgivenPrincipalReportingPeriod",
"amountForgivenInterestCumulative",
"amountForgivenInterestReportingPeriod",
"amountActualEndingBalanceTotalDebt",
"amountScheduledEndingBalanceTotalDebt",
"codePostModificationARM",
"codePostModificationARMIndex",
"percentagePostModificationMargin",
"numberPostModificationInterestReset",
"datePostModificationNextReset",
"numberPostModificationIndexLookback",
"codePostModificationARMRounding",
"percentagePostModificationARMRounding",
"paymentPostModificationInitialMinimum",
"datePostModificationNextPaymentAdjustment",
"frequencyPostModificationARMPaymentRecast",
"percentagePostModificationLifetimeFloor",
"percentagePostModificationLifetimeCeiling",
"percentagePostModificationInitialInterestRateIncrease",
"percentagePostModificationInitialInterestRateDecrease",
"percentagePostModificationSubsequentInterestIncrease",
"percentagePostModificationSubsequentInterestRateDecrease",
"percentagePostModificationPaymentCap",
"codePostModificationPaymentMethodAfterRecast",
"numberPostModificationARMInterestRateTeaser",
"numberPostModificationARMPaymentTeaser",
"hasPostModificationARMNegativeAmortization",
"percentagePostModificationARMNegativeAmortizationCap",
"numberPostModificationInterestOnlyTerm",
"datePostModificationInterestOnlyLastPayment",
"amountPostModificationBalloon",
"hasPostModificationInterestRateStep",
"percentagePostModificationStepInterest",
"datePostModificationStep",
"amountPostModificationStepPrincipalInterestPayment",
"numberPostModificationStep",
"percentagePostModificationMaximumFutureStepAgreement",
"datePostModificationMaximumStepAgreementRate",
"amountNonInterestBearingDeferredPrincipalCumulative",
"amountNonInterestBearingDeferredPrincipalReportingPeriod",
"amountRecoveryDeferredPrincipalReportingPeriod",
"amountNonInterestBearingDeferredPaidFull",
"amountNonInterestBearingDeferredInterestFeeReportingPeriod",
"amountNonInterestBearingDeferredInterestFeeCumulative",
"amountRecoveryDeferredInterestFeeReportingPeriod",
"dateMostRecentForbearancePlanOrTrialModificationStart",
"dateMostRecentForbearancePlanOrTrialModificationScheduledEnd",
"dateMostRecentTrialModificationViolated",
"dateMostRecentRepaymentPlanStart",
"dateMostRecentRepaymentPlanScheduledEnd",
"dateMostRecentRepaymentPlanViolated",
"amountShortSaleAcceptedOffer",
"dateMostRecentLossMitigationExit",
"codeMostRecentLossMitigationExit",
"dateAttorneyReferral",
"codeForeclosureDelayReason",
"dateForeclosureExit",
"codeForeclosureExitReason",
"dateNoticeOfIntent",
"amountMostRecentAcceptedREOOffer",
"dateMostRecentAcceptedREOOffer",
"amountGrossLiquidationProceeds",
"amountNetSalesProceeds",
"amountReportingPeriodLossPassedToIssuingEntity",
"amountCumulativeTotalLossPassedToIssuingEntity",
"amountSubsequentRecovery",
"hasEviction",
"dateReoExit",
"codeReoExitReason",
"amountUPBLiquidation",
"amountServicingFeesClaimed",
"amountServicerAdvanceReimbursedPrincipal",
"amountServicerAdvanceReimbursedInterest",
"amountServicerAdvanceReimbursedTaxesInsurance",
"amountServicerAdvanceReimbursedCorporate",
"amountREOManagementFees",
"amountCashKeyDeed",
"amountPerformanceIncentiveFees",
"dateMortgageInsuranceClaimFiled",
"amountMortgageInsuranceClaim",
"dateMortgageInsuranceClaimPaid",
"amountMortgageInsuranceClaimPaid",
"dateMortgageInsuranceClaimDeniedRescinded",
"dateMarketableTitleTransfer",
"codeNonPayStatus",
"codeReportingAction",
"idGroup",
"dateReportingPeriodBeginning",
"dateReportingPeriodEnd",
"dateOrigination",
"numberOriginalTermLoan",
"dateMaturity",
"percentageInterestRateSecuritization",
"codeInterestAccrualMethod",
"dateFirstLoanPaymentDue",
"codeLienPositionSecuritization",
"codeLoanStructure",
"codePaymentType",
"amountPeriodicPrincipalAndInterestPaymentSecuritization",
"amountScheduledPrincipalBalanceSecuritization",
"securitizationNumberProperties",
"propertiesNumber",
"numberGraceDaysAllowed",
"hasInterestOnly",
"hasPrepaymentPremium",
"hasModified",
"codeArmIndex",
"dateFirstRateAdjustment",
"dateFirstPaymentAdjustment",
"numberArmMargin",
"percentageLifetimeRateCap",
"percentagePeriodicRateIncreaseLimit",
"percentagePeriodicRateDecreaseLimit",
"amountPeriodicPaymentAdjustmentMaximum",
"percentPeriodicPaymentAdjustmentMaximum",
"codeRateResetFrequency",
"codePaymentResetFrequency",
"numberIndexLookbackDays",
"datePrepaymentLockOutEnd",
"dateYieldMaintenanceEnd",
"datePrepaymentPremiumsEnd",
"percentageMaximumNegativeAmortizationAllowed",
"amountMaximumNegativeAmortizationAllowed",
"amountNegativeAmortizationDeferredInterestCap",
"amountDeferredInterestCumulative",
"amountDeferredInterestCollected",
"propertyProperty",
"hasReportPeriodModification",
"amountReportPeriodBeginningScheduleLoanBalance",
"amountTotalScheduledPrincipalInterestDue",
"percentageServicerTrusteeFeeRate",
"amountUnscheduledPrincipalCollected",
"amountReportPeriodEndActualBalance",
"amountReportPeriodEndScheduledLoanBalance",
"dateHyperAmortizing",
"codeServicingAdvanceMethod",
"hasNonRecoverability",
"amountTotalPrincipalInterestAdvancedOutstanding",
"amountTotalTaxesInsuranceAdvancesOutstanding",
"amountOtherExpensesAdvancedOutstanding",
"codePaymentStatusLoan",
"percentageArmIndexRate",
"dateNextInterestRateChangeAdjustment",
"dateNextPaymentAdjustment",
"dateMostRecentSpecialServicerTransfer",
"dateMostRecentMasterServicerReturn",
"amountRealizedLossToTrust",
"codeLiquidationPrepayment",
"dateLiquidationPrepayment",
"amountPrepaymentPremiumYieldMaintenanceReceived",
"codeWorkoutStrategy",
"dateLastModification",
"codeModification",
"amountPostModificationPayment",
"amountPostModificationAmortizationPeriod",
"nameProperty",
"addressProperty",
"cityProperty",
"stateProperty",
"zipcodeProperty",
"countyProperty",
"numberNetRentableSquareFeet",
"numberNetRentableSquareFeetSecuritization",
"numberUnitsBedsRooms",
"numberUnitsBedsRoomsSecuritization",
"yearBuilt",
"yearLastRenovated",
"amountValuationSecuritization",
"codeValuationSourceSecuritization",
"dateValuationSecuritization",
"amountMostRecentValuation",
"dateMostRecentValuation",
"codeMostRecentValuationSource",
"percentagePhysicalOccupancySecuritization",
"percentageMostRecentPhysicalOccupancy",
"codePropertyStatus",
"dateDefeasanceOptionStart",
"codeDefeasedStatus",
"tenantLargest",
"numberSquareFeetLargestTenant",
"dateLeaseExpirationLargestTenant",
"tenantSecondLargest",
"numberSquareFeetSecondLargestTenant",
"dateLeaseExpirationSecondLargestTenant",
"tenantThirdLargest",
"numberSquareFeetThirdLargestTenant",
"dateLeaseExpirationThirdLargestTenant",
"dateFinancialsSecuritization",
"dateMostRecentFinancialsStart",
"dateMostRecentFinancialsEnd",
"amountRevenueSecuritization",
"amountMostRecentRevenue",
"amountOperatingExpensesSecuritization",
"amountOperatingExpenses",
"amountNetOperatingIncomeSecuritization",
"amountMostRecentNetOperatingIncome",
"amountNetCashFlowFlowSecuritization",
"amountMostRecentNetCashFlow",
"codeNetOperatingIncomeNetCashFlowSecuritization",
"codeNetOperatingIncomeNetCashFlow",
"amountMostRecentDebtService",
"percentageDebtServiceCoverageNetOperatingIncomeSecuritization",
"percentageMostRecentDebtServiceCoverageNetOperatingIncome",
"percentageDebtServiceCoverageNetCashFlowSecuritization",
"percentageMostRecentDebtServiceCoverageNetCash",
"codeDebtServiceCoverageSecuritization",
"codeMostRecentDebtServiceCoverage",
"dateMostRecentAnnualLeaseRolloverReview",
"dateReportingPeriodEnding",
"termOriginalLoan",
"dateLoanMaturity",
"codeInterestCalculationType",
"dateOriginalFirstPayment",
"numberGracePeriod",
"subventedSubvented",
"nameVehicleManufacturer",
"nameVehicleModel",
"codeVehicleNewUsed",
"yearVehicleModel",
"codeVehicleType",
"amountVehicleValue",
"codeVehicleValueSource",
"typeObligorCreditScore",
"scoreObligorCredit",
"hasCoObligor",
"percentagePaymentToIncome",
"locationObligorGeographic",
"hasReportingPeriodModification",
"amountPaymentDueNextReportingPeriod",
"servicerOtherServicerFeeRetainedBy",
"amountOtherAssessedUncollectedServicerFee",
"amountReportingPeriodActualEndBalance",
"amountPaidTotalActual",
"amountServicerAdvanced",
"isDelinquent",
"amountChargedoffPrincipal",
"amountRecovered",
"codeModificationType",
"numberPaymentExtended",
"hasRepossessed",
"amountRepossessedProceeds",
"dateReportingPeriodBegin",
"costAcquisition",
"numberOriginalLeaseTerm",
"dateScheduledTermination",
"periodGrace",
"valueBaseResidual",
"codeBaseResidualSource",
"valueContractResidual",
"typeLesseeCreditScore",
"scoreLesseeCredit",
"codeLesseeIncomeVerificationLevel",
"codeLesseeEmploymentVerification",
"hasCoLesseePresent",
"locationLesseeGeographic",
"numberRemainingTerm",
"amountReportingPeriodSecuritizationValue",
"rateSecuritizationDiscount",
"amountOtherLeaseLevelServicingFeesRetained",
"amountReportingPeriodEndingActualBalance",
"amountReportingPeriodEndActualSecuritization",
"namePrimaryLeaseServicer",
"dateDemandResolution",
"codeRepurchaseOrReplacementReason",
"amountChargedOff",
"extendedLease",
"hasTermination",
"amountExcessFee",
"amountLiquidationProceeds",
"detailNumberComment", "columnComment", "descriptionComment",
'idAccessionPrevious',
'numberItem', 'nameField', 'descriptionNotes', 'idSequence',
"numberAmendment",
"typeAmendmentType",
"confDeniedExpired",
'descriptionInformationAdditional',
'numberFile'
)
)}
.filer_type_df <-
function() {
tibble(
idTypeFilerOwner = c(
'insider',
'private' ,
'broker_dealer',
'transfer_agent',
'ia',
'msd',
'bank',
'inv_co'
),
typeFilerOwner = c(
'Insider',
'Private Placement',
'Broker Dealer',
'Transfer Agent',
'Investment Advisor',
'Bank',
'Municipal Securities Dealer',
'Investment Company'
)
) %>%
mutate_all(str_to_upper)
}
dictionary_form_d_categories <-
function() {
category_df <-
dplyr::tibble(
idIndustry = 1:35,
nameIndustry = c(
"AGRICULTURE",
"AIRLINES AND AIRPORTS",
"BIOTECHNOLOGY",
"BUSINESS SERVICES",
"COAL MINING",
"COMMERCIAL REAL ESTATE",
"COMMERCIAL BANKING",
"COMPUTERS",
"CONSTRUCTION",
"ELECTRIC UTILITIES",
"ENERGY CONSERVATION",
"ENVIORNMENTAL SERVICES",
"HEALTH INSURANCE",
"HOSPITALS AND PHYSICIANS",
"INSURANCE",
"INVESTING",
"INVESTMENT BANKING",
"LODGING AND CONVETION",
"MANUFACTURING",
"OIL AND GAS",
"OTHER",
"OTHER BANKING AND FINANCIAL SERVICES",
"OTHER ENERGY",
"OTHER HEALTH CARE",
"OTHER REAL ESTATE",
"OTHER TECHNOLOGY",
"OTHER TRAVEL",
"PHARMACEUTICALS",
"POOLED INVESTMENT FUND",
"REITS AND FINANCE",
"RESIDENTIAL REAL ESTATE",
"RESTAURANTS",
"RETAIL",
"TELECOMMUNICATIONS",
"TRAVEL AND TOURISM"
),
codeIndustryParent = c(
"OTHER",
"TRAVEL",
"HEALTH",
"OTHER",
"ENERGY",
"REAL",
"FINANCE",
"TECH",
"REAL",
"ENERGY",
"ENERGY",
"ENERGY",
"HEALTH",
"HEALTH",
"FINANCE",
"FINANCE",
"FINANCE",
"TRAVEL",
"OTHER",
"ENERGY",
"OTHER",
"FINANCE",
"ENERGY",
"HEALTH",
"REAL",
"TECH",
"TRAVEL",
"HEALTH",
"FINANCE",
"REAL",
"REAL",
"OTHER",
"OTHER",
"TECH",
"TRAVEL"
),
nameIndustryParent = c(
"OTHER",
"TRAVEL AND LEISURE",
"HEALTHCARE",
"OTHER",
"ENERGY",
"REAL ESTATE",
"FINANCIAL",
"TECHNOLOGY",
"REAL ESTATE",
"ENERGY",
"ENERGY",
"ENERGY",
"HEALTHCARE",
"HEALTHCARE",
"FINANCIAL",
"FINANCIAL",
"FINANCIAL",
"TRAVEL AND LEISURE",
"OTHER",
"ENERGY",
"OTHER",
"FINANCIAL",
"ENERGY",
"HEALTHCARE",
"REAL ESTATE",
"TECHNOLOGY",
"TRAVEL AND LEISURE",
"HEALTHCARE",
"FINANCIAL",
"REAL ESTATE",
"REAL ESTATE",
"OTHER",
"OTHER",
"TECHNOLOGY",
"TRAVEL AND LEISURE"
)
)
return(category_df)
}
.insider_code_df <-
function() {
insider_df <-
tibble(
idInsiderTransaction =
c(
"A",
"C",
"D",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"NONE",
"O",
"P",
"S",
"U",
"V",
"W",
"X",
"Z"
),
nameInsiderTransaction = c(
"AWARD",
"CONVEYANCE",
"DISPOSITION TO ISSUER",
"PAYMENT WITH SECURITIES",
"GIFT",
"EXPIRATION OF LONG DERIVATIVE POSITION",
"DISCRETIONARY TRANSACTION",
"OTHER",
"EQUITY SWAP OR SIMILAR",
"SMALL ACQUISITIONS",
"EXEMPT",
NA,
"OTM EXERCISE",
"PURCHASE",
"SALE",
"MERGER AND ACQUISITION",
"REPORTED EARLY",
"WILL OR LAWS OF DESCENT",
"ITM OR ATM EXERCISE",
"DEPOSIT INTO/WITHDRAWAL FROM VOTING TRUST"
),
idTypeInsiderTransaction = c(
"A",
"D",
"D",
"D",
"D",
NA,
NA,
NA,
NA,
"A",
"A",
NA,
"A",
"A",
"D",
NA,
NA,
"D",
"A",
"D"
)
)
return(insider_df)
}
dictionary_sec_filing_codes <-
function() {
tibble(
idFormType = c(
"1.01",
"1.02",
"1.03",
"1.04",
"2.01",
"2.02",
"2.03",
"2.04",
"2.05",
"2.06",
"3.01",
"3.02",
"3.03",
"4.01",
"4.02",
"5.01",
"5.02",
"5.03",
"5.04",
"5.05",
"5.06",
"5.07",
"5.08",
"6.01",
"6.02",
"6.03",
"6.04",
"6.05",
"7.01",
"8.01",
"9.01"
),
nameFormType = c(
"Entry into a Material Definitive Agreement",
"Termination of a Material Definitive Agreement",
"Bankruptcy or Receivership",
"Mine Safety Reporting of Shutdowns and Patterns of Violations",
"Completion of Acquisition or Disposition of Assets",
"Results of Operations and Financial Condition",
"Creation of a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement of a Registrant",
"Triggering Events That Accelerate or Increase a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement",
"Costs Associated with Exit or Disposal Activities",
"Material Impairments",
"Notice of Delisting or Failure to Satisfy a Continued Listing Rule or Standard; Transfer of Listing",
"Unregistered Sales of Equity Securities",
"Material Modification to Rights of Security Holders",
"Changes in Registrant's Certifying Accountant",
"Non-Reliance on Previously Issued Financial Statements or a Related Audit Report or Completed Interim Review",
"Changes in Control of Registrant",
"Departure of Directors or Certain Officers; Election of Directors; Appointment of Certain Officers; Compensatory Arrangements of Certain Officers",
"Amendments to Articles of Incorporation or Bylaws; Change in Fiscal Year",
"Temporary Suspension of Trading Under Registrant's Employee Benefit Plans",
"Amendments to the Registrant's Code of Ethics, or Waiver of a Provision of the Code of Ethics",
"Change in Shell Company Status",
"Submission of Matters to a Vote of Security Holders",
"Shareholder Director Nominations",
"ABS Informational and Computational Material",
"Change of Servicer or Trustee",
"Change in Credit Enhancement or Other External Support",
"Failure to Make a Required Distribution",
"Securities Act Updating Disclosure",
"Regulation FD Disclosure",
"Other Events",
"Financial Statements and Exhibits"
) %>% stringr::str_to_upper()
)
}
dictionary_sec_form_codes <-
function() {
tibble(
idForm = c(
"R",
"A",
"Q",
"CR",
"REG",
"REGX",
"O",
"P",
"X",
"W",
"SEC",
"PROXY",
"CT",
"IS",
"CO",
"T"
),
nameForm = c(
"Other Report",
"Annual Report",
"Quarterly Report",
"Current Report",
"Registration",
"Private Offering",
"Ownership",
"Prospectus",
"Exemption",
"Withdrawal",
"SEC Correspondence",
"Proxy Statement",
"Confidential Treatment",
"Initial Statement",
"Change in Ownership",
"Trades"
) %>% stringr::str_to_upper()
)
}
.company_type_df <-
function() {
tibble(
idCompanyType = c(
"ic",
"i",
"ia",
"bd",
"m",
"t",
"b",
"c",
"p",
"etf",
"mmf",
"mf",
"uit",
"cef"
),
nameCompanyType = c(
"Investment Company",
"Insider",
"Investment Adviser",
"Broker-dealer",
"Municipal Securities Dealer",
"Transfer Agent",
"Bank",
"Company",
"Private Issuer",
"ETF",
"Money Market Fund",
"Mutual Fund",
"UIT",
"Closed-end Fund"
)
)
}
dictionary_sec_rules <-
function() {
tibble(
idRule = c(
"06",
"3C",
"3C.7",
"3C.1",
"06b",
"04",
"46",
"04.1",
"04.2",
"04.3",
"05",
"3C.6",
"3C.5",
"06c",
"4a5",
"3C.11",
"3C.2",
"3C.3",
"3C.9",
"3C.10",
"3C.4",
"3C.12",
"3C.",
"3C.14",
"3"
),
nameRule = c(
"Rule 506",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Rule 506b",
"Rule 504",
"Rule 506c",
"Rule 504b(1)(i)",
"Rule 504b(1)(ii)",
"Rule 504b(1)(iii)",
"Rule 505",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Rule 506c",
"Securities Act Section 4(a)(5)",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c",
"Investment Company Act Section 3c"
)
) %>%
mutate_all(str_to_upper)
}
edgar_tickers <-
function(include_ticker_information = F,
join_sic = T,
snake_names = F,
return_message = T) {
json_data <-
"https://www.sec.gov/data/company_tickers.json" %>%
jsonlite::fromJSON(simplifyDataFrame = TRUE, flatten = F)
data <-
seq_along(json_data) %>%
map_dfr(function(x) {
json_data[[x]] %>% flatten_dfr()
}) %>%
setNames(c('idCIK',
'idTicker',
"nameCompany")) %>%
distinct() %>%
mutate(nameCompany = nameCompany %>% str_to_upper())
if (include_ticker_information) {
"\n\nAcquiring ticker information\n\n" %>% cat(fill = T)
sec_tickers_info_safe <-
possibly(sec_tickers_info, tibble())
df_tickers <-
sec_tickers_info(tickers = data$idTicker, return_message = return_message, join_sic = join_sic, unformat = T, snake_names = F, convert_case = T, include_address = T)
df_tickers <-
df_tickers %>%
rename(nameCompanyTicker = nameCompany,
idCIKTicker = idCIK)
data <-
data %>%
left_join(
df_tickers, by = "idTicker"
)
}
data <- data %>% munge_tbl(snake_names = snake_names)
data
}
.cik_filing_count <-
function(cik = 886982,
return_message = TRUE) {
code_cik <-
cik %>%
pad_cik()
url <-
list("https://www.sec.gov/cgi-bin/srch-edgar?text=CIK%3D",
code_cik,'&first=1994&last=',
Sys.Date() %>% lubridate::year() %>% as.numeric()
) %>%
purrr::reduce(paste0)
page <-
url %>%
read_html()
no_data <-
page %>%
html_nodes(css = 'p+ b') %>%
html_text() %>% length() == 0
if (no_data) {
return(tibble(idCIK = cik))
}
filings <-
page %>%
html_nodes(css = 'p+ b') %>%
html_text() %>%
as.character() %>%
readr::parse_number()
pages <-
ceiling(filings/100)
df <-
tibble(idCIK = cik,
countFilings = filings,
countPages = pages) %>%
mutate(isMultiSearch = pages > 20)
if (return_message) {
list("CIK: ", cik, " has ", filings %>% formattable::comma(digits = 0), ' Filings') %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
df
}
cik_filing_counts <-
function(cik, return_message = T) {
.cik_filing_count_safe <-
possibly(.cik_filing_count, tibble())
cik %>%
future_map_dfr(function(x){
.cik_filing_count_safe(cik = x,
return_message = return_message)
})
}
.sic_filing_count <-
function(sic = 800,
return_message = TRUE) {
code_sic <-
sic %>%
pad_sic()
url <-
list("https://www.sec.gov/cgi-bin/srch-edgar?text=ASSIGNED-SIC%3D",
code_sic,'&first=1994&last=',
Sys.Date() %>% lubridate::year() %>% as.numeric()
) %>%
purrr::reduce(paste0)
page <-
url %>%
read_html()
no_data <-
page %>%
html_nodes(css = 'p+ b') %>%
html_text() %>% length() == 0
if (no_data) {
return(tibble(idCIK = cik))
}
filings <-
page %>%
html_nodes(css = 'p+ b') %>%
html_text() %>%
as.character() %>%
readr::parse_number()
pages <-
ceiling(filings/100)
df <-
tibble(idSIC = sic,
countFilings = filings,
countPages = pages) %>%
mutate(isMultiSearch = pages > 20)
if (return_message) {
list("SIC: ", sic, " has ", filings %>% formattable::comma(digits = 0), ' Filings') %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
df
}
sic_filing_count <-
function(sic = NULL, join_sic = T, snake_names = F,
use_all_sice_codes = F,
return_message = T,
unformat = F) {
if (use_all_sice_codes) {
sic <-
dictionary_sic_codes() %>%
pull(idSIC)
}
if (length(sic) == 0) {
"Enter SIC Codes"
}
.sic_filing_count_safe <- possibly(.sic_filing_count, tibble())
data <-
sic %>%
future_map_dfr(function(x){
.sic_filing_count_safe(sic = x, return_message = return_message)
})
if (join_sic) {
data <-
data %>%
left_join(dictionary_sic_codes(), by = "idSIC")
}
data <-
data %>%
munge_tbl(snake_names = snake_names, unformat = F)
data
}
.resolve_form_columns <-
function(data) {
data %>%
mutate_if(is.character,
funs(ifelse(. %in% c('_', "NULL"), NA, .))) %>%
mutate_at(data %>% select(
dplyr::matches(
"^name|^description|^idDay|^type|^title|^description|^code|^address|^city|^state|^relationship"
)
) %>% names(),
funs(. %>% str_to_upper())) %>%
mutate_at(data %>% select(
dplyr::matches("^price|^count|^amount|^value|^idCIK|^yearIncorporation|^idSIC|^pershare|^number|^percent|^term|^pct|^score|^year")
) %>% names(),
funs(. %>% as.character() %>% readr::parse_number())) %>%
mutate_at(data %>% select(dplyr::matches("^is|^has")) %>% names(),
funs(
ifelse(
. %in% c('true', 'false'),
. %>% as.logical(),
. %>% as.numeric() %>% as.logical()
)
)) %>%
mutate_at(data %>% select(dplyr::matches("^date")) %>% names(),
funs(. %>% lubridate::ymd())) %>%
mutate_at(data %>% select(dplyr::matches("^amountValueHoldings|^valueSecurities")) %>% names(),
funs(. * 1000)) %>%
suppressWarnings() %>%
suppressMessages() %>%
select(which(colMeans(is.na(.)) < 1))
}
dictionary_sic_codes <-
memoise::memoise(function() {
page <-
"https://www.sec.gov/info/edgar/siccodes.htm" %>%
read_html()
page %>% html_table(fill = T) %>% first() %>% as_tibble() %>%
setNames(c("idSIC", "nameOfficeAD", "nameIndustry")) %>%
munge_tbl(convert_case = T)
})
dictionary_sec_forms <-
function() {
page <-
"https://www.sec.gov/forms" %>%
read_html()
forms <-
page %>%
html_nodes('.release-number-content') %>%
html_text() %>%
str_trim() %>%
str_to_upper() %>%
str_replace_all('NUMBER:', '')
form_names <-
page %>%
html_nodes('.views-field-field-display-title a') %>%
html_text() %>%
str_to_upper() %>%
str_trim() %>%
str_replace_all('\r|\n|\u0092|\u0097', '') %>%
str_replace_all('(PDF)', '') %>%
str_replace_all('\\(', '') %>%
str_replace_all('\\)', '') %>%
str_trim()
url_description_form <-
page %>%
html_nodes('.views-field-field-display-title a') %>%
html_attr('href') %>%
paste0('https://www.sec.gov', .)
date_updated <-
page %>%
html_nodes('.datetime') %>%
html_text() %>%
list("01-", .) %>%
purrr::reduce(paste0) %>%
lubridate::dmy()
sec_ids <-
page %>%
html_nodes('.list-page-detail-content') %>%
html_text() %>%
str_trim() %>%
str_replace_all('SEC Number:', '') %>%
str_trim()
sec_ids[sec_ids == ''] <-
NA
reference <-
page %>%
html_nodes('td.views-field-term-node-tid') %>%
html_text() %>%
str_trim() %>%
str_to_upper() %>%
str_replace_all('\\TOPIC(S):','') %>%
str_split('\\:') %>%
future_map(function(x){
x %>% str_split('\\:') %>% purrr::flatten_chr() %>% .[[2]]
}) %>%
purrr::flatten_chr()
data <-
tibble(
idForm = forms,
nameForm = form_names,
urlFormDescription = url_description_form,
dateFormUpdate = date_updated,
idSECNumber = sec_ids,
referenceForm = reference
) %>%
arrange(desc(dateFormUpdate))
data
}
parse_for_tables <-
function(all_data,
table_name_initial = "All Filings",
parse_all_filings = TRUE,
parse_complete_text_filings = TRUE,
parse_form_d = TRUE,
parse_13F = TRUE,
parse_small_offerings = TRUE,
parse_form_3_4s = TRUE,
parse_asset_files = TRUE,
parse_xbrl = TRUE,
assign_to_environment = FALSE,
nest_data = TRUE,
return_message = TRUE) {
all_tables <-
tibble()
parse_form_data_safe <-
purrr::possibly(.parse_form_data, tibble())
parse_all_filings <-
c(
parse_complete_text_filings,
parse_form_d,
parse_13F,
parse_small_offerings,
parse_form_3_4s,
parse_asset_files,
parse_xbrl
) %>%
sum() > 0
if ('termSearch' %in% names(all_data)) {
df_general <-
all_data %>%
select(termSearch, countFilings) %>%
distinct()
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Summary', dataTable = list(df_general)))
all_data <-
all_data %>% select(-c(termSearch, countFilings))
} else {
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Summary', dataTable = list(tibble())))
}
if (parse_all_filings) {
all_data <-
all_data %>%
select(-dplyr::matches(
"hasAssetFile|isFormD|is13F|isForm3_4|hasSmallOfferingData"
)) %>%
distinct()
if (!'typeFile' %in% names(all_data)) {
all_data <-
all_data %>%
mutate(typeFile = ifelse(urlSECFilingDirectory %>% str_detect('htm'),
'html', NA))
}
search_df <-
all_data %>%
select(dateFiling,
dplyr::matches("typeFile"),
dplyr::matches("idForm"),
urlSECFilingDirectory) %>%
distinct()
df_all_filings <-
search_df$urlSECFilingDirectory %>%
unique() %>%
future_map_dfr(function(x){
.parse_sec_filing_index(urls = x)
})
df_all_filings <-
df_all_filings %>%
nest(-c(idCIK, urlSECFilingDirectory, dplyr::matches("idAccession")), .key = dataFilings)
all_data <-
all_data %>%
select(-dplyr::matches("dataFilings")) %>%
left_join(df_all_filings %>% select(-one_of(c('idCIK', 'idAccession')))) %>%
mutate(hasNoFilings = dataFilings %>% map_lgl(is_null)) %>%
suppressMessages()
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = table_name_initial, dataTable = list(all_data)))
.all_filings <-
all_data %>%
filter(!hasNoFilings) %>%
select(idCIK:typeFile, dataFilings)
if (!'idCIKFiler' %in% names(.all_filings)) {
.all_filings <-
.all_filings %>%
dplyr::rename(idCIKFiler = idCIK)
}
if (!'typeFileFiler' %in% names(.all_filings)) {
.all_filings <-
.all_filings %>%
dplyr::rename(typeFileFiler = typeFile)
}
.all_filings <-
.all_filings %>%
select(dplyr::matches("idCIK|data")) %>%
unnest() %>%
distinct()
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'All Filing URLS', dataTable = list(.all_filings)))
if (parse_complete_text_filings) {
if (!'urlTextFilingFull' %in% names(all_data)) {
all_data <-
all_data %>%
mutate(urlTextFilingFull = urlSECFilingDirectory %>% str_replace_all("-index.htm", ".txt"))
}
urls <-
all_data$urlTextFilingFull %>%
unique()
sec_complete_filings_safe <-
purrr::possibly(.sec_complete_filings, tibble())
all_text_df <-
.sec_complete_filings(urls = urls)
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Text Filings', dataTable = list(all_text_df)))
}
if (parse_form_d) {
df_form_ds <-
.all_filings %>%
parse_form_data_safe(filter_parameter = 'isFormD')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'FormDs', dataTable = list(df_form_ds)))
}
if (parse_13F) {
df_13F <-
.all_filings %>%
parse_form_data_safe(filter_parameter = 'is13FFiling')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = '13Fs', dataTable = list(df_13F)))
}
if (parse_small_offerings) {
df_small_offerings <-
.all_filings %>%
parse_form_data_safe(filter_parameter = 'hasSmallOfferingData')
all_tables <-
all_tables %>%
bind_rows(tibble(
nameTable = 'Small Offerings',
dataTable = list(df_small_offerings)
))
}
if (parse_form_3_4s) {
df_form3_4 <-
.all_filings %>%
parse_form_data_safe(filter_parameter = 'isForm3_4')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Form 3 and 4', dataTable = list(df_form3_4)))
}
if (parse_asset_files) {
df_assets <-
.all_filings %>%
.parse_form_data(filter_parameter = 'hasAssetFile')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Asset Data', dataTable = list(df_assets)))
}
if (parse_xbrl) {
df_xbrl <-
.all_filings %>%
parse_form_data_safe(filter_parameter = 'isXBRLInstanceFile')
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'XBRL', dataTable = list(df_xbrl)))
}
} else {
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'TermsFilings', dataTable = list(all_data)))
}
all_tables <-
all_tables %>%
mutate(countCols = dataTable %>% map_dbl(ncol)) %>%
filter(countCols > 0) %>%
select(-countCols)
if (assign_to_environment) {
table_name_df <-
all_tables %>%
select(nameTable) %>%
distinct() %>%
mutate(
nameDF =
list('data', nameTable %>% str_replace_all('\\ ', ''), 'EDGAR') %>% purrr::invoke(paste0, .)
)
1:nrow(table_name_df) %>%
walk(function(x) {
df_data <-
all_tables %>%
slice(x) %>%
select(dataTable) %>%
unnest()
df_name <-
table_name_df %>% slice(x) %>% .$nameDF
df_data <-
df_data %>%
mutate_at(.vars =
df_data %>% select(dplyr::matches("^amount|^price|^value")) %>% names(),
funs(. %>% formattable::currency(digits = 2))) %>%
mutate_at(
.vars =
df_data %>% select(dplyr::matches("^count[A-Z]|^number")) %>% select(-dplyr::matches("country")) %>% names(),
funs(. %>% as.numeric() %>% formattable::comma(digits = 0))
) %>%
mutate_at(
.vars = df_data %>% select(dplyr::matches("^percent|^pct")) %>% select(-dplyr::matches("country")) %>% names(),
funs(. %>% as.numeric() %>% formattable::percent(digits = 0))
) %>%
select(which(colMeans(is.na(.)) < 1)) %>%
tidy_column_formats()
assign(x = df_name,
eval(df_data),
envir = .GlobalEnv)
})
}
return(all_tables)
}
.generate_ft_search_urls <-
function(search_term = c('"Rockwood Capital"'),
return_message = TRUE) {
term <-
search_term %>%
URLencode()
base_url <-
list("https://searchwww.sec.gov/EDGARFSClient/jsp/EDGAR_MainAccess.jsp?search_text=", term, "&sort=Date&startDoc=0&numResults=100&isAdv=true&formType=1&fromDate=mm/dd/yyyy&toDate=mm/dd/yyyy&stemming=true") %>%
purrr::reduce(paste0)
page <-
base_url %>%
read_html()
page_total <-
page %>%
html_nodes('
html_text() %>%
as.character() %>%
readr::parse_number() %>%
max(na.rm = TRUE)
length_out <-
ceiling(page_total/100)
times <-
seq(0,by = 100, length.out = length_out)
urls <-
list("https://searchwww.sec.gov/EDGARFSClient/jsp/EDGAR_MainAccess.jsp?search_text=", term, "&sort=Date&startDoc=", times,"&numResults=100&isAdv=true&formType=1&fromDate=mm/dd/yyyy&toDate=mm/dd/yyyy&stemming=true") %>%
purrr::reduce(paste0)
if (return_message) {
glue("Found SEC free text urls for {search_term}") %>% cat()
}
tibble(termSearch = search_term, urlSECSearch = urls)
}
.parse_ft_filing_page <-
function(urls, return_message = TRUE) {
df <-
tibble()
success <- function(res) {
if (return_message) {
list("Parsing: ", res$url) %>% purrr::reduce(paste0) %>% cat(fill = T)
}
page <-
res$content %>%
read_html()
search_url <-
res$url
dates <-
page %>%
html_nodes('i.blue') %>%
html_text() %>%
lubridate::mdy()
search_items <-
page %>%
html_nodes('.infoBorder+ tr td+ td
html_text() %>%
str_trim() %>%
str_to_upper()
urlFiling <-
page %>%
html_nodes('.infoBorder+ tr td+ td
html_attr('href') %>%
str_replace_all("javascript:opennew",'') %>%
str_replace_all("'|\\(",'') %>%
map_chr(function(x){
x %>%
str_split('\\,') %>%
flatten_chr() %>%
.[[1]]
})
ciks <-
urlFiling %>%
map_dbl(function(x){
x %>% str_replace_all('http://www.sec.gov/Archives/edgar/data/','') %>%
str_split('/') %>%
flatten_chr() %>%
.[[1]] %>%
as.character() %>%
readr::parse_number()
})
text <-
page %>%
html_nodes('.small') %>%
html_text() %>%
str_to_upper()
data <-
tibble(
dateFiling = dates[seq_along(ciks)],
idCIKFiler = ciks,
nameFilerFilingExhibit = search_items,
descriptionText = text[seq_along(ciks)],
urlSECFiling = urlFiling
) %>%
tidyr::separate(nameFilerFilingExhibit, sep = '\\ FOR ',
into = c('exhibitFiling', 'nameFiler'), remove = FALSE) %>%
tidyr::separate(exhibitFiling, sep = '\\ OF ',
into = c('idExhibit', 'idForm'), remove = TRUE) %>%
suppressWarnings()
data <-
data %>%
mutate(idForm = ifelse(idForm %>% is.na(), idExhibit, idForm),
idExhibit = ifelse(idForm == idExhibit, NA, idExhibit),
urlSECSearch = search_url) %>%
select(dateFiling, idCIKFiler, nameFiler, idForm, idExhibit, everything()) %>%
suppressWarnings() %>%
suppressMessages()
df <<-
df %>%
bind_rows(data)
}
failure <- function(msg){
tibble()
}
urls %>%
walk(function(x){
curl_fetch_multi(url = x, success, failure)
})
multi_run()
df
}
edgar_ft_terms <-
function(search_terms = c('"Jared Kushner"', '"EJF Capital"', '"Blackstone Real Estate"'),
include_counts = F,
nest_data = FALSE,
return_message = TRUE) {
.generate_ft_search_urls_safe <-
purrr::possibly(.generate_ft_search_urls, tibble())
df_urls <-
search_terms %>%
future_map_dfr(function(x) {
.generate_ft_search_urls_safe(search_term = x)
})
all_data <-
.parse_ft_filing_page(urls = df_urls$urlSECSearch, return_message = return_message) %>%
left_join(df_urls) %>%
select(termSearch, everything()) %>%
suppressMessages() %>%
arrange(desc(termSearch), desc(dateFiling)) %>%
find_target_filings()
if (include_counts) {
.cik_filing_count_safe <-
purrr::possibly(.cik_filing_count, tibble())
df_counts <-
all_data %>%
pull(idCIKFiler) %>%
unique() %>%
future_map_dfr(function(x){
.cik_filing_count_safe(cik = x)
})
all_data <-
all_data %>%
left_join(df_counts %>%
dplyr::rename(idCIKFiler = idCIK) %>%
select(idCIKFiler, countFilings)) %>%
select(termSearch:idCIKFiler, countFilings, everything()) %>%
suppressMessages() %>%
arrange(dateFiling, termSearch)
}
if (return_message) {
results <-
all_data %>% group_by(termSearch) %>% count(termSearch) %>% mutate(n = n %>% formattable::comma(digits = 0)) %>%
unite(termMessage, termSearch, n, sep = ': ') %>%
.$termMessage
list(
"\nSEC free text search filing mentions in the last 4 years:\n",
results %>% paste0(collapse = '\n')
) %>%
purrr::reduce(paste0) %>% cat(fill = T)
}
if (nest_data) {
all_data <-
all_data %>%
nest(-c(termSearch), .key = dataFilings)
}
return(all_data)
}
.sec_parameter_df <- function() {
tibble(
nameParameter = c(
"Company Name",
"Company CIK",
"Public Document Count",
"Accession Number",
"Form Type",
"Period",
"Filing Date",
"Company Name Confirmed",
"CIK",
"SIC",
"IRS Number",
"State of Incorporation",
"Fiscal Year End",
"Form Type Exact",
"SEC Act",
"File Number",
"Business Address",
"Mailing Address",
"Former Company Name",
"Date of Company Name Change",
"Company",
"form"
),
slugParameter = c(
"company-name",
"company-cik",
"Public-Document-Count",
"Accession-Number",
"type",
"period",
"Filing-Date",
"Company-Name-Confirmed",
"cik",
"ASSIGNED-SIC",
"irs-number",
"STATE-OF-INCORPORATION",
"Fiscal-Year-End",
"Form-Type",
"Act",
"File-Number",
"Business-Address",
"Mailing-Address",
"FORMER-CONFORMED-NAME",
"DATE-CHANGED",
'company-name',
"type"
)
)
}
.parse_boolean_search_page <-
function(urls, return_message = TRUE) {
df <-
tibble()
success <- function(res){
if (return_message) {
list("Parsing: ", res$url, "\n") %>% purrr::reduce(paste0) %>% cat(fill = T)
}
page <-
res$content %>%
read_html()
use_url <-
page %>%
html_nodes('div td:nth-child(2) a') %>%
html_text() %>%
str_to_upper() %>% length() == 0
if (use_url) {
page <-
res$url %>%
read_html()
}
entities <-
page %>%
html_nodes('div td:nth-child(2) a') %>%
html_text() %>%
str_to_upper()
stems <-
page %>%
html_nodes('div td:nth-child(2) a') %>%
html_attr('href')
if (stems %>% length() > 0 ) {
data <-
seq_along(stems) %>%
future_map_dfr(function(x){
stem <-
stems[[x]]
url_filing <-
'https://www.sec.gov' %>% paste0(stem)
items <-
stem %>%
str_replace_all('/Archives/edgar/data/','') %>%
str_split('/') %>%
flatten_chr()
cik <-
items[[1]] %>% as.numeric()
accession <-
items[length(items)]
is_html <-
accession %>% str_detect(".htm|.html")
tibble(idRow = x, idCIK = cik,
isHTML = is_html,
slugAccension = accession,
urlSECFilingDirectory = url_filing)
})
} else {
data <-
tibble(idRow = x, idCIK = NA)
}
form <-
page %>%
html_nodes('td:nth-child(4)') %>%
html_text() %>%
str_to_upper()
if (!length(form) == nrow(data)) {
form <-
form[2:length(form)]
}
date_filing <-
page %>%
html_nodes('td:nth-child(5)') %>%
html_text() %>%
lubridate::mdy()
file_size <-
page %>%
html_nodes('td:nth-child(6)') %>%
html_text() %>%
as.character() %>%
readr::parse_number()
data <-
data %>%
mutate(
nameEntityLegal = entities,
idForm = form,
dateFiling = date_filing,
sizeFile = file_size
) %>%
resolve_legal_name() %>%
select(-idRow) %>%
select(dateFiling, idCIK, nameEntity, idForm, everything()) %>%
find_target_filings()
search_url <-
res$url
data <-
data %>%
separate(slugAccension,
sep = '\\.',
into = c('idAccession', 'typeFile'),
extra = "merge",
fill = "right"
) %>%
mutate(idAccession = idAccession %>% str_replace_all('-index', '')) %>%
separate(
idAccession,
into = c('idCIKFilerSubmission', 'codeYear', 'countFilerYearFilings'),
sep = '\\-',
remove = FALSE
) %>%
mutate_at(
c('idCIKFilerSubmission', 'codeYear', 'countFilerYearFilings'),
funs(. %>% as.character() %>% readr::parse_number())
) %>%
suppressMessages() %>%
suppressWarnings() %>%
mutate(
urlSECSearch = search_url,
isSameFiler = ifelse(idCIK == idCIKFilerSubmission, TRUE, FALSE),
urlTextFilingFull = ifelse(
typeFile %>% str_detect('htm'),
urlSECFilingDirectory %>% str_replace_all("-index.htm", ".txt"),
urlSECFilingDirectory
)
)
df <<-
df %>%
bind_rows(data)
}
failure <- function(msg){
tibble()
}
urls %>%
walk(function(x){
curl_fetch_multi(url = x, success, failure)
})
multi_run()
df
}
.generate_edgar_search_url <-
function(search_term = '"Corona Virus"',
parameter = NULL,
year_start = NULL,
year_end = NULL,
page_start = 0) {
if (length(search_term) == 0) {
stop("Please enter a search term")
}
base <-
'https://www.sec.gov/cgi-bin/srch-edgar?text='
is_non_numeric <-
class(search_term) != "numeric"
if (is_non_numeric) {
term <-
search_term %>%
URLencode()
} else {
term <-
search_term
}
term <-
term %>% str_replace_all('\\=', '%3D')
has_parameter <-
length(parameter) > 0
if (has_parameter) {
df_params <-
.sec_parameter_df() %>%
mutate_all(str_to_lower)
parameter <-
parameter %>% str_to_lower()
wrong_param <-
!parameter %in% df_params$nameParameter
if (wrong_param) {
stop(
list(
"SEC boolean search parameters can only be\n",
paste0(df_params$nameParameter, collapse = '\n')
) %>% purrr::reduce(paste0)
)
}
param_slug <-
df_params %>%
filter(nameParameter == parameter) %>%
.$slugParameter
if (parameter %>% str_to_lower() %in% c('cik', 'company cik')) {
term <-
term %>%
pad_cik()
}
if (parameter %>% str_to_lower() %>% str_detect('date')) {
term <-
term <-
lubridate::ymd() %>% as.character() %>% str_replace_all('\\-', '')
}
if (parameter %>% str_to_lower() == 'sic') {
term <-
term %>%
pad_sic()
}
slug_term <-
list(param_slug, '%3D', term) %>%
purrr::reduce(paste0)
} else {
slug_term <-
term
}
if (length(year_start) == 0) {
year_start <-
1994
}
if (length(year_end) == 0) {
year_end <-
Sys.Date() %>% lubridate::year() %>%
as.numeric()
}
url <-
list(base, slug_term, '&start=', page_start, '&count=100',
'&first=', year_start, '&last=', year_end) %>%
purrr::reduce(paste0)
url
}
.generate_search_term_urls <-
function(search_term = c('"Rockwood Capital"'),
parameter = NULL,
year_start = NULL,
year_end = NULL){
url <-
.generate_edgar_search_url(
search_term = search_term,
parameter = parameter,
year_start = year_start,
year_end = year_end,
page_start = 0
)
page <-
url %>%
read_html()
filings <-
page %>%
html_nodes(css = 'p+ b') %>%
html_text() %>%
as.character() %>%
readr::parse_number()
if (length(parameter) == 0){
search_message <-
search_term
} else {
search_message <-
list(parameter, ' = ', search_term) %>% purrr::reduce(paste0)
}
pages <-
ceiling(filings / 100)
list('\n',filings %>% formattable::comma(digits = 0), " total filings for search term: ",
search_message, ' to parse'
) %>%
purrr::reduce(paste0) %>%
cat(fill = T)
page_count <-
seq(0, by = 100, length.out = pages)
if (page_count %>% length() == 0) {
page_count <-
0
}
urls <-
page_count %>%
map_chr(function(x) {
.generate_edgar_search_url(
search_term = search_term,
parameter = parameter,
year_start = year_start,
year_end = year_end,
page_start = x
)
})
rm(page)
df_urls <-
tibble(termSearch = search_term,
countFilings = filings, urlSECSearch = urls)
return(df_urls)
}
.sec_search_term <-
function(search_term = "Boston Properties",
parameter = NULL,
year_start = NULL,
year_end = NULL,
return_message = TRUE){
url_df <-
.generate_search_term_urls(
search_term = search_term,
parameter = parameter,
year_start = year_start,
year_end = year_end
)
urls <-
url_df$urlSECSearch
all_data <-
.parse_boolean_search_page(urls = urls)
all_data <-
all_data %>%
left_join(url_df, by = "urlSECSearch") %>%
suppressMessages() %>%
select(termSearch, countFilings, everything())
if (return_message) {
list(
"\nFound ",
all_data %>% nrow() %>% formattable::comma(digits = 0),
' SEC filings for ',
search_term,
'\n'
) %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
all_data <-
all_data %>%
arrange(desc(dateFiling))
all_data
}
edgar_search_terms <-
function(search_terms = NULL,
parameter = NULL,
year_start = NULL,
year_end = NULL,
table_name_initial = "All Filings",
parse_all_filings = TRUE,
parse_complete_text_filings = FALSE,
parse_form_d = FALSE,
parse_13F = FALSE,
parse_small_offerings = FALSE,
parse_form_3_4s = FALSE,
parse_asset_files = FALSE,
parse_xbrl = FALSE,
assign_to_environment = TRUE,
nest_data = TRUE,
return_message = TRUE) {
sec_search_term_safe <-
purrr::possibly(.sec_search_term, tibble())
all_data <-
search_terms %>%
future_map_dfr(function(x) {
sec_search_term_safe(
search_term = x,
parameter = parameter,
year_start = year_start,
year_end = year_end
)
}) %>%
dplyr::select(-dplyr::matches("urlSECSearch")) %>%
distinct()
if (all_data %>% nrow() == 0) {
return(tibble())
}
parse_for_tables_safe <-
purrr::possibly(parse_for_tables, tibble())
all_tables <-
parse_for_tables_safe(
all_data = all_data,
table_name_initial = table_name_initial,
parse_all_filings = parse_all_filings,
parse_complete_text_filings = parse_complete_text_filings,
parse_form_d = parse_form_d,
parse_13F = parse_13F,
parse_small_offerings = parse_small_offerings,
parse_form_3_4s = parse_form_3_4s,
parse_asset_files = parse_asset_files,
parse_xbrl = parse_xbrl,
nest_data = nest_data,
return_message = return_message
)
if (all_tables %>% nrow() == 0) {
return(all_data)
}
all_tables <-
all_tables %>%
bind_rows(tibble(nameTable = 'Search Filings', dataTable = list(all_data)))
if (assign_to_environment) {
table_name_df <-
all_tables %>%
select(nameTable) %>%
distinct() %>%
mutate(
nameDF =
list('dataFiler', nameTable %>% str_replace_all('\\ ', '')) %>% purrr::invoke(paste0, .)
)
1:nrow(table_name_df) %>%
walk(function(x) {
df_name <-
table_name_df %>% slice(x) %>% .$nameDF
df_data <-
all_tables %>%
filter(nameTable == table_name_df$nameTable[[x]]) %>%
select(dplyr::matches(c('idCIK|nameEntity|dataTable'))) %>%
unnest() %>%
suppressWarnings()
has_unnest <-
names(df_data) %>% str_detect('data') %>% sum(na.rm = TRUE) > 1
if (has_unnest) {
base_names <-
df_data %>% select(-dplyr::matches("data")) %>% names()
df_data_names <-
names(df_data)[names(df_data) %>% str_detect('data')]
for (df_data_name in df_data_names) {
table <-
df_data %>%
select(one_of(c(base_names, df_data_name))) %>%
unnest() %>%
select(which(
colMeans(is.na(.)) < 1
))
df_table_name <-
list(df_name, df_data_name %>% str_replace_all('data', '')) %>% purrr::reduce(paste0)
assign(x = df_table_name,
eval(table),
envir = .GlobalEnv)
}
} else {
has_unnest <-
df_data %>% names() %>% str_detect('data') %>% sum(na.rm = TRUE) > 0
if (has_unnest) {
df_data <-
df_data %>%
unnest()
select_cols <- tibble(nameData = names(df_data)) %>%
mutate(idColumn = 1:n()) %>%
group_by(nameData) %>%
mutate(countColumn = 1:n()) %>%
ungroup() %>%
filter(countColumn == min(countColumn)) %>%
.$idColumn
df_data <-
df_data[, select_cols]
table <-
df_data %>%
select(which(
colMeans(is.na(.)) < 1
))
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
} else {
table <-
df_data %>%
select(which(
colMeans(is.na(.)) < 1
))
assign(x = df_name,
eval(table),
envir = .GlobalEnv)
}
}
})
}
return(all_tables)
}
.parse_most_recent_filing_form_page <-
function(url = "https://www.sec.gov/cgi-bin/current?q1=0&q2=6&q3=10-D", return_message = F) {
page <-
url %>%
read_html()
data <-
page %>%
html_nodes(css = 'td pre') %>%
html_text() %>%
str_replace_all('Date Filed Form CIK Code Company Name','') %>%
read_table(col_names = FALSE) %>%
purrr::set_names(c('dateFiling', 'idForm', 'idCIK', 'nameFiler')) %>%
mutate(nameFiler = nameFiler %>% str_to_upper()) %>%
suppressWarnings() %>%
suppressMessages()
urls <-
page %>%
html_nodes('pre a') %>%
html_attr('href') %>%
paste0('https://www.sec.gov',.)
data_match <-
urls %>% length() / 2 == (nrow(data))
if (data_match) {
data <-
data %>%
mutate(idRow = 1:n()) %>%
left_join(
tibble(urlCIKFiler = urls[c(FALSE,TRUE)] %>% paste0('&start=0&count=100'),
urlSECFilingDirectory = urls[c(FALSE, TRUE)]) %>%
mutate(idRow = 1:n())
) %>%
suppressWarnings() %>%
suppressMessages()
}
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)}
data
}
.parse_most_recent_stream <-
function(url = "https://www.sec.gov/cgi-bin/browse-edgar?company=&CIK=&type=&owner=include&count=100&action=getcurrent",
return_message = TRUE) {
page <-
url %>%
xml2::read_html()
url_directory <-
page %>%
html_nodes('a+ table td:nth-child(2) a:nth-child(1)') %>%
html_attr(name = 'href') %>%
paste0('https://www.sec.gov', .)
urlTextFilingFull <-
page %>%
html_nodes('div a+ a') %>%
html_attr(name = 'href') %>%
paste0('https://www.sec.gov', .)
forms <-
page %>%
html_nodes('a+ table td:nth-child(1)') %>%
html_text() %>%
str_trim()
forms <-
forms[!forms == '']
url_directory <-
page %>%
html_nodes('a+ table td:nth-child(2) a:nth-child(1)') %>%
html_attr('href') %>%
paste0('https://www.sec.gov',.)
filing_descriptions <-
page %>%
html_nodes('.small') %>%
html_text() %>%
str_trim()
df_descriptions <-
seq_along(filing_descriptions) %>%
future_map_dfr(function(x){
description <-
filing_descriptions[[x]] %>%
str_to_upper()
has_act <-
description %>% str_detect("ACT:")
if (has_act) {
items <-
description %>%
str_split("ACCESSION NUMBER: ") %>%
flatten_chr() %>%
str_replace_all('\n','')
filing_description <-
items[[1]]
items <-
items[[2]] %>%
str_split('ACT:') %>%
flatten_chr() %>%
str_trim()
accession <-
items[1]
items <-
items[[2]] %>%
str_split("SIZE:") %>%
flatten_chr() %>%
str_trim()
df <-
tibble(idRow = x,
descriptionFiling = filing_description,
idAccession = accession,
idSECAct = items[[1]],
descriptionFileSize = items[[2]])
return(df)
}
items <-
description %>%
str_split("ACCESSION NUMBER: ") %>%
flatten_chr() %>%
str_replace_all('\n','')
filing_description <-
items[[1]]
items <-
items[[2]] %>%
str_split('SIZE:') %>%
flatten_chr() %>%
str_trim()
df <-
tibble(idRow = x,
descriptionFiling = filing_description,
idAccession = items[[1]],
descriptionFileSize = items[[2]])
return(df)
})
filer_description <-
page %>%
html_nodes('td:nth-child(3) a') %>%
html_text()
df_filers <-
seq_along(filer_description) %>%
future_map_dfr(function(x){
filer <-
filer_description[[x]] %>%
str_to_upper()
is_messed <-
filer %>% str_count("\\(") > 2
if (!is_messed) {
values <-
filer %>%
str_split('\\(') %>%
flatten_chr() %>%
str_replace_all('[\\)]','') %>%
str_trim()
df <-
tibble(idRow = x, item = c('nameEntityLegal', 'idCIK', 'typeSECEntity'), value = values) %>%
spread(item, value) %>%
mutate(idCIK = idCIK %>% as.numeric())
df <-
df %>%
resolve_legal_name() %>%
select(idCIK, nameEntity, everything())
return(df)
}
if (is_messed) {
values <-
filer %>%
str_split('\\(') %>%
flatten_chr() %>%
str_replace_all('[\\)]','') %>%
str_trim()
values <-
c(list(values[1], values[2]) %>%
purrr::reduce(paste), values[3], values[4])
df <-
tibble(idRow = x, item = c('nameEntityLegal', 'idCIK', 'typeSECEntity'), value = values) %>%
spread(item, value) %>%
mutate(idCIK = idCIK %>% as.numeric())
df <-
df %>%
resolve_legal_name() %>%
select(idCIK, nameEntity, everything())
return(df)
}
})
url_cik_filer <-
page %>%
html_nodes('td:nth-child(3) a') %>%
html_attr('href') %>%
paste0('https://www.sec.gov',.) %>%
paste0(., '&start=0')
datetime_accepted <-
page %>%
html_nodes(css = '.small+ td') %>%
html_text() %>%
lubridate::ymd_hms()
date_filed <-
page %>%
html_nodes('td:nth-child(5)') %>%
html_text() %>%
lubridate::ymd()
file_film <- page %>%
html_nodes('td:nth-child(6)') %>%
html_text()
df_films <-
seq_along(file_film) %>%
future_map_dfr(function(x){
parts <-
file_film[[x]] %>% str_split('\n') %>% flatten_chr()
tibble(
idRow = x,
idFile = parts[[1]] %>% stringr::str_trim(),
idSECFiling = parts[[2]] %>% as.numeric()
) %>%
mutate(
urlSECFile = list(
"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=",
idFile,
'&owner=include&count=100000'
) %>% purrr::reduce(paste0)
)
})
data <-
df_filers %>%
left_join(df_descriptions, by = "idRow") %>%
select(-idRow) %>%
mutate(urlTextFilingFull,
dateFiling = date_filed,
datetimeAccepted = datetime_accepted,
idForm = forms,
urlSECFilingDirectory = url_directory,
urlCIKFIler = url_cik_filer,
urlSearch = url) %>%
select(idForm, everything()) %>%
find_target_filings()
if (df_films %>% nrow() == data %>% nrow()) {
data <-
data %>%
mutate(idRow = 1:n()) %>%
left_join(df_films, by = "idRow") %>%
select(-idRow)
}
if(return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
data <-
data %>%
mutate_at(
data %>% select_if(is.character) %>% select(-dplyr::matches("url")) %>% names(),
funs(ifelse(. == '', NA, .) %>% str_to_upper())
)
if ('descriptionFileSize' %in% names(data)) {
data <-
data %>%
mutate(
typeFileDocument = descriptionFileSize %>% map_chr(stringi::stri_extract_last_boundaries),
sizeFile = readr::parse_number(as.character(descriptionFileSize)),
sizeFileBytes = ifelse(typeFileDocument == "MB", sizeFile * 1024, 1048576 * sizeFile)
) %>%
select(-c(typeFileDocument, descriptionFileSize, sizeFile))
}
return(data)
}
.get_most_recent_filing_urls <-
function(filing_type = NULL, pages_out = 20) {
start_pages <-
seq(0, by = 100, length.out = pages_out)
if ('dfEnd' %>% exists()) {
eval(rm(dfEnd))
}
if (length(filing_type) == 0) {
slug_filing <-
''
} else {
if (filing_type %>% str_to_lower() == 'all') {
slug_filing <-
''
} else {
slug_filing <-
filing_type
}
}
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&datea=&dateb=&company=&type=',slug_filing, '&SIC=&State=&Country=&CIK=&owner=include&accno=&start=',
start_pages, '&count=100') %>%
purrr::reduce(paste0)
is_on <-
TRUE
for (url in urls) {
if (!is_on) {
invisible()
}
if('dfEnd' %>% exists()) {
invisible()
} else {
df_end <-
.guess_page_ongoing(url = url, override = FALSE)
is_over_zero <-
df_end %>% length() > 0
if (is_over_zero) {
assign('dfEnd', eval(df_end), envir = .GlobalEnv)
assign('is_on', eval(FALSE), envir = .GlobalEnv)
rm(is_over_zero)
}
}
}
still_none <-
df_end %>% length() == 0
if (still_none) {
df_end <-
urls %>%
future_map_dfr(function(x){
.guess_page_ongoing(url = x, override = TRUE)
})
df_end <-
df_end %>%
slice(nrow(df_end))
}
if ('countPage' %in% names(df_end)) {
df_end <-
df_end %>%
dplyr::rename(countStart = countPage)
}
if (df_end$countStart < 0) {
df_end <-
df_end %>%
mutate(countStart = 0)
}
if (slug_filing == '') {
df_end <-
df_end %>%
mutate(countStart = 2000)
}
length_actual_pages <-
ceiling(df_end$countStart/100)
length_actual <-
seq(0, by = 100, length.out = length_actual_pages)
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&datea=&dateb=&company=&type=',slug_filing, '&SIC=&State=&Country=&CIK=&owner=include&accno=&start=',
length_actual, '&count=100') %>%
purrr::reduce(paste0)
df_mr_urls <-
tibble(urlPageFiling = urls) %>%
mutate(countPage = 1:n())
if (length(filing_type) > 0) {
df_mr_urls <-
df_mr_urls %>%
mutate(idForm = filing_type) %>%
select(idForm, everything())
}
if('dfEnd' %>% exists()){
rm(list = c('dfEnd'), pos = ".GlobalEnv")
}
return(df_mr_urls)
}
.sec_filing_most_recent <-
function(filing_type = NULL, return_message = TRUE) {
get_most_recent_filing_urls_safe <-
purrr::possibly(.get_most_recent_filing_urls, tibble())
url_df <-
get_most_recent_filing_urls_safe(filing_type = filing_type)
if (length(filing_type) == 0) {
filing_name <-
'all'
} else {
filing_name <-
filing_type
}
parse_most_recent_stream_safe <-
purrr::possibly(.parse_most_recent_stream, tibble())
all_data <-
url_df$urlPageFiling %>%
future_map_dfr(function(x){
parse_most_recent_stream_safe(url = x, return_message = return_message)
}) %>%
mutate(idFormName = filing_name) %>%
select(idFormName, everything())
if (return_message) {
list("\nReturned ", all_data %>% nrow() %>% formattable::comma(digits = 0),
' of the most recent filings from ', filing_type, ' forms\n') %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
return(all_data)
}
edgar_recent_filings <-
function(forms = c("All", "10-D", "10-K"),
table_name_initial = "Recent Filings",
parse_all_filings = TRUE,
parse_form_d = FALSE,
parse_complete_text_filings = FALSE,
parse_13F = FALSE,
parse_small_offerings = FALSE,
parse_form_3_4s = FALSE,
parse_asset_files = FALSE,
parse_xbrl = FALSE,
assign_to_environment = TRUE,
nest_data = FALSE,
return_message = TRUE) {
sec_filing_most_recent_safe <-
purrr::possibly(.sec_filing_most_recent, tibble())
all_data <-
forms %>%
future_map_dfr(function(x) {
x %>% message()
.sec_filing_most_recent(filing_type = x,
return_message = return_message)
}) %>%
select(dplyr::matches("dateFiling"),
idCIK,
nameEntity,
idForm,
everything())
all_data <-
all_data %>%
select(-dplyr::matches("datetimeAccepted|^is[A-Z]|^has[A-Z]|is13FFiling")) %>%
parse_for_tables(
table_name_initial = table_name_initial,
parse_all_filings = parse_all_filings,
parse_complete_text_filings = parse_complete_text_filings,
parse_form_d = parse_form_d,
parse_13F = parse_13F,
parse_small_offerings = parse_small_offerings,
parse_form_3_4s = parse_form_3_4s,
parse_asset_files = parse_asset_files,
parse_xbrl = parse_xbrl,
assign_to_environment = assign_to_environment,
nest_data = nest_data,
return_message = return_message
)
return(all_data)
}
.get_year_index_urls <-
function(url = "https://www.sec.gov/Archives/edgar/daily-index/2016/") {
yearData <-
url %>%
str_replace_all('https://www.sec.gov/Archives/edgar/daily-index|/','') %>%
as.character() %>%
readr::parse_number()
page <-
url %>%
read_html()
quarters <-
page %>%
html_nodes('td a') %>%
html_attr('href') %>%
str_replace_all('\\QTR|/','') %>%
as.character() %>%
readr::parse_number()
urls <-
page %>%
html_nodes('td a') %>%
html_attr('href') %>%
list(url, .) %>%
purrr::reduce(paste0)
url_df <-
tibble(idQuarter =quarters, yearData,
urlQuarter = urls)
return(url_df)
}
.parse_quarter_urls <-
function(url = "https://www.sec.gov/Archives/edgar/daily-index/2012/QTR4/",
index_type = 'master',
return_message = TRUE) {
page <-
url %>%
read_html()
slugs <-
page %>%
html_nodes('td a') %>%
html_attr('href')
slugs <-
slugs[!slugs %>% str_detect("xml")]
urls <-
list(url, slugs) %>%
purrr::reduce(paste0)
df_urls <-
tibble(slugs, urlSECIndex = urls) %>%
tidyr::separate(slugs,
into = c('typeIndex', 'dateData', 'remove'),
sep = '\\.')
if (df_urls$dateData[[1]] %>% lubridate::ymd() %>% is.na()) {
df_urls <-
df_urls %>%
mutate(dateIndex = dateData %>% lubridate::mdy()) %>%
select(-c(remove)) %>%
mutate(urlQuarter = url)
} else {
df_urls <-
df_urls %>%
mutate(dateIndex = dateData %>% lubridate::ymd()) %>%
select(-c(remove)) %>%
mutate(urlQuarter = url)
}
if (length(index_type) == 0) {
df_urls <-
df_urls %>%
filter(typeIndex == 'master')
} else {
df_urls <-
df_urls %>%
filter(typeIndex == index_type)
}
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df_urls)
}
.parse_index_filing_page <-
function(url = "https://www.sec.gov/Archives/edgar/daily-index/1994/QTR3/company.070194.idx",
return_message = TRUE) {
start_skip <-
url %>%
read_lines() %>%
grep('------', .)
url_slug <-
url %>%
str_split('\\/') %>%
flatten_chr() %>%
.[length(.)] %>%
str_replace_all('\\.idx', '') %>%
str_split('\\.') %>%
flatten_chr()
index_type <-
url_slug[[1]]
index_date <-
url_slug[[2]] %>%
as.numeric() %>%
lubridate::ymd() %>%
suppressMessages()
if (index_date %>% is.na()) {
index_date <-
url_slug[[2]] %>%
as.numeric() %>%
lubridate::mdy()
}
df <-
url %>%
readr::read_table(skip = start_skip,
col_names = FALSE,
progress = FALSE) %>%
suppressMessages() %>%
suppressWarnings()
if (df %>% ncol() == 1) {
df <-
df %>%
separate(X1, sep = '\\|',
c(
'idCIK',
'nameEntityLegal',
'idForm',
'dateFiling',
'slugAccension'
))
df <-
df %>%
mutate(idCIK = idCIK %>% as.numeric()) %>%
mutate(nameEntity = nameEntityLegal %>% str_to_upper() %>% str_replace_all('\\.|\\,', '') %>% str_trim(),
dateIndex = index_date,
typeIndex = index_type) %>%
separate(nameEntity,
sep = '\\ /',
into = c('nameEntity', 'idLocationEntity')) %>%
mutate(
dateFiling = dateFiling %>% lubridate::ymd(),
idLocationEntity = idLocationEntity %>% str_replace_all('\\/', '') %>% str_trim()
) %>%
suppressWarnings() %>%
suppressMessages() %>%
mutate(
urlSECFilingText = list("https://www.sec.gov/Archives/", slugAccension) %>%
purrr::reduce(paste0),
urlSECFilingDirectory = urlSECFilingText %>% str_replace_all(".txt", '-index.html')
) %>%
select(nameEntity, idLocationEntity, everything()) %>%
suppressWarnings()
df <-
df %>%
mutate(
dataAccension = slugAccension %>% str_replace_all('edgar/data/|.txt', ''),
urlSECIndex = url
) %>%
tidyr::separate(dataAccension,
sep = '\\/',
into = c('remove', 'idAccession')) %>%
select(-remove) %>%
tidyr::separate(
idAccession,
into = c('idCIKFiler', 'codeYear', 'countFilerYearFilings'),
remove = FALSE,
sep = '\\-'
) %>%
mutate_at(
c('idCIKFiler', 'codeYear', 'countFilerYearFilings'),
funs(. %>% as.numeric())
) %>%
mutate(hasDifferentSECFiler = ifelse(!idCIK == idCIKFiler, TRUE, FALSE)) %>%
select(
typeIndex,
dateIndex,
dateFiling,
idCIK,
nameEntity,
idForm,
idAccession,
countFilerYearFilings,
hasDifferentSECFiler,
everything()
) %>%
suppressWarnings() %>%
suppressMessages()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
is_form <-
index_type == 'form'
if (is_form) {
if (df %>% ncol() == 6) {
df <-
df %>%
tidyr::unite(X2, X2, X3, sep = ' ')
}
df <-
df %>%
purrr::set_names(c(
'idForm',
'nameEntityLegal',
'idCIK',
'dateFiling',
'slugAccension'
))
}
if (!is_form) {
if (df %>% ncol() == 6) {
df <-
df %>%
tidyr::unite(X1, X1, X2, sep = ' ')
}
df <-
df %>%
purrr::set_names(c(
'nameEntityLegal',
'idForm',
'idCIK',
'dateFiling',
'slugAccension'
))
}
df <-
df %>%
mutate(nameEntity = nameEntityLegal %>% str_to_upper() %>% str_replace_all('\\.|\\,', '') %>% str_trim(),
dateIndex = index_date,
typeIndex = index_type) %>%
separate(nameEntity,
sep = '\\ /',
into = c('nameEntity', 'idLocationEntity')) %>%
mutate(
dateFiling = dateFiling %>% lubridate::ymd(),
idLocationEntity = idLocationEntity %>% str_replace_all('\\/', '') %>% str_trim()
) %>%
suppressWarnings() %>%
suppressMessages()
is_http <-
df$slugAccension %>% str_count('\\.htm') %>% sum() / nrow(df) > .5
if (is_http) {
df <-
df %>%
dplyr::rename(urlSECFilingDirectory = slugAccension) %>%
select(
typeIndex,
dateIndex,
dateFiling,
idCIK,
nameEntity,
everything())
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
df <-
df %>%
mutate(
urlSECFilingText = list("https://www.sec.gov/Archives/", slugAccension) %>%
purrr::reduce(paste0),
urlSECFilingDirectory = urlSECFilingText %>% str_replace_all(".txt", '-index.html')
) %>%
select(nameEntity, idLocationEntity, everything()) %>%
suppressWarnings()
df <-
df %>%
mutate(
dataAccension = slugAccension %>% str_replace_all('edgar/data/|.txt', ''),
urlSECIndex = url
) %>%
tidyr::separate(dataAccension,
sep = '\\/',
into = c('remove', 'idAccession')) %>%
select(-remove) %>%
tidyr::separate(
idAccession,
into = c('idCIKFiler', 'codeYear', 'countFilerYearFilings'),
remove = FALSE,
sep = '\\-'
) %>%
mutate_at(
c('idCIKFiler', 'codeYear', 'countFilerYearFilings'),
funs(. %>% as.numeric())
) %>%
mutate(hasDifferentSECFiler = ifelse(!idCIK == idCIKFiler, TRUE, FALSE)) %>%
select(
typeIndex,
dateIndex,
dateFiling,
idCIK,
nameEntity,
idAccession,
countFilerYearFilings,
hasDifferentSECFiler,
everything()
) %>%
suppressWarnings() %>%
suppressMessages()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
.get_years_page_urls <-
function(years = 1994:2017,
index_type = 'master',
return_message = TRUE) {
wrong_years <-
(years < 1993) %>% as.numeric() %>% sum(na.rm = TRUE) > 0
if (wrong_years) {
stop("Years to search start in 1994")
}
urls <-
list('https://www.sec.gov/Archives/edgar/daily-index/',
years,
'/') %>%
purrr::reduce(paste0)
df_urls <-
urls %>%
future_map_dfr(function(x) {
.get_year_index_urls(url = x)
})
all_url_df <-
df_urls$urlQuarter %>%
future_map_dfr(function(x) {
.parse_quarter_urls(url = x,
index_type = index_type,
return_message = return_message)
}) %>%
suppressWarnings()
all_url_df <-
all_url_df %>%
left_join(df_urls) %>%
select(yearData, idQuarter, everything()) %>%
suppressMessages() %>%
select(-dateData)
return(all_url_df)
}
edgar_filing_streams <-
function(start_date = "2017-02-15",
end_date = Sys.Date(),
only_most_recent_data = FALSE,
index_type = 'master',
table_name_initial = "Filing Logs",
parse_all_filings = FALSE,
parse_complete_text_filings = FALSE,
parse_form_d = FALSE,
parse_13F = FALSE,
parse_small_offerings = FALSE,
parse_form_3_4s = FALSE,
parse_asset_files = FALSE,
parse_xbrl = FALSE,
assign_to_environment = TRUE,
nest_data = TRUE,
return_message = TRUE) {
start_date <-
start_date %>%
lubridate::ymd()
end_date <-
end_date %>%
lubridate::ymd()
start_year <-
lubridate::year(start_date)
end_year <-
end_date %>% lubridate::year()
search_years <-
start_year:end_year
if (only_most_recent_data) {
search_years <-
Sys.Date() %>% lubridate::year()
df_urls <-
.get_years_page_urls(years = search_years,
index_type = index_type,
return_message = return_message)
urls <-
df_urls %>%
slice(nrow(df_urls)) %>%
.$urlSECIndex
}
if (!only_most_recent_data) {
df_urls <-
.get_years_page_urls(years = search_years,
index_type = index_type,
return_message = return_message)
urls <-
df_urls %>%
filter(dateIndex >= start_date) %>%
filter(dateIndex <= end_date) %>%
.$urlSECIndex
}
parse_index_filing_page_safe <-
purrr::possibly(.parse_index_filing_page, tibble())
all_data <-
seq_along(urls) %>%
future_map_dfr(function(x) {
parse_index_filing_page_safe(url = urls[[x]], return_message = return_message)
})
all_data <-
all_data %>%
left_join(df_urls %>% select(urlSECIndex, yearData, idQuarter)) %>%
select(yearData, idQuarter, dateIndex, everything())
all_data <-
all_data %>%
mutate_at(all_data %>% select(dplyr::matches("count")) %>% names(),
funs(. %>% formattable::comma(digits = 0))) %>%
select(-dplyr::matches("slugAccension"))
if (return_message) {
list(
"Parsed ",
all_data %>% nrow() %>% formattable::comma(digits = 0),
" SEC filings from ",
all_data$dateIndex %>% min(na.rm = T),
' to ',
all_data$dateIndex %>% max(na.rm = TRUE)
) %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
all_data <-
all_data %>%
parse_for_tables(
table_name_initial = table_name_initial,
parse_all_filings = parse_all_filings,
parse_form_d = parse_form_d,
parse_13F = parse_13F,
parse_small_offerings = parse_small_offerings,
parse_form_3_4s = parse_form_3_4s,
parse_asset_files = parse_asset_files,
parse_xbrl = parse_xbrl,
nest_data = nest_data,
return_message = return_message
)
all_data
}
.guess_page_ongoing <-
function(url = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=1184765&type=&dateb=&owner=include&start=0&count=100",
override = FALSE) {
page <-
url %>%
read_html()
page_count <-
url %>% str_split('start=') %>%
flatten_chr() %>%
.[[2]] %>%
str_split('&') %>%
flatten_chr() %>%
.[[1]] %>%
as.character() %>%
readr::parse_number()
items <-
page %>%
html_nodes('input') %>%
html_attr('value') %>% str_to_upper() %>%
unique()
if (items %>% length() == 0){
return(invisible())
}
no_page <-
page %>%
html_nodes('h1') %>%
html_text() %>%
str_to_lower() == 'invalid parameter'
no_page <-
no_page %>%
length() > 0
is_end <-
!items %>% str_detect("NEXT 100") %>% sum(na.rm = T) > 0
if (is_end & (!no_page)) {
return(tibble(isEnd = TRUE, countStart = page_count))
}
if (!override) {
if (!is_end) {
return(tibble())
}
} else {
return(tibble(countStart = page_count))
}
tibble(isEnd = is_end, countPage = page_count -100)
}
.parse_search_page <-
function(urls = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&company=Bank&owner=exclude&match=&start=500&count=100&hidefilings=0",
return_message = TRUE) {
df <-
tibble()
success <- function(res){
if (return_message) {
list("Parsing: ", res$url, "\n") %>% purrr::reduce(paste0) %>% cat(fill = T)
}
page <-
res$content %>%
read_html()
cik <-
page %>%
html_nodes('td:nth-child(1) a') %>%
html_text() %>%
as.numeric()
entities <-
page %>%
html_nodes('td:nth-child(2)') %>%
html_text() %>%
str_to_upper()
locations <-
page %>%
html_nodes('td:nth-child(3)') %>%
html_text() %>%
str_to_title() %>%
str_trim()
locations[locations == ''] <-
NA
data <-
tibble(
idCIK = cik,
nameEntityLegal = entities,
codeLocationBusiness = locations
) %>%
mutate(codeLocationBusiness = codeLocationBusiness %>% str_to_upper()) %>%
separate(nameEntityLegal,
into = c('nameEntityLegal', 'sic'),
sep = 'SIC: ') %>%
separate(sic,
into = c('idSIC', 'nameIndustry'),
sep = '-') %>%
mutate(
idSIC = idSIC %>% str_trim() %>% as.numeric(),
nameIndustry = nameIndustry %>% str_trim()
) %>%
suppressWarnings() %>%
suppressMessages() %>%
select(which(colMeans(is.na(.)) < 1)) %>%
mutate(nameEntity = nameEntityLegal %>% str_to_upper() %>% str_replace_all('\\.|\\,', '') %>% str_trim()) %>%
select(idCIK, nameEntity, everything()) %>%
separate(nameEntity,
sep = '\\ /',
into = c('nameEntity', 'idLocationEntity')) %>%
mutate(
nameEntity = nameEntity %>% gsub('/', '', .),
idLocationEntity = idLocationEntity %>% str_replace_all('\\/', '') %>% str_trim()
) %>%
suppressWarnings() %>%
suppressMessages() %>%
select(-dplyr::matches("idLocationEntity"))
df <<-
df %>%
bind_rows(data)
}
failure <- function(msg){
tibble()
}
urls %>%
walk(function(x) {
curl_fetch_multi(url = x, success, failure)
})
multi_run()
df
}
.parse_search_page_length <-
function(search_term = "BREA", pages_out = 5) {
term <-
search_term %>% URLencode()
start_pages <-
seq(0, by = 100, length.out = pages_out)
if ('dfEnd' %>% exists()) {
eval(rm(dfEnd))
}
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&company=',term, '&type=&dateb=&owner=include&start=',
start_pages, '&count=100') %>%
purrr::reduce(paste0)
is_on <-
TRUE
for (url in urls) {
if (!is_on) {
invisible()
}
if('dfEnd' %>% exists()) {
invisible()
} else {
df_end <-
.guess_page_ongoing(url = url, override = FALSE)
is_over_zero <-
df_end %>% length() > 0
if (is_over_zero) {
assign('dfEnd', eval(df_end), envir = .GlobalEnv)
assign('is_on', eval(FALSE), envir = .GlobalEnv)
rm(is_over_zero)
}
}
}
still_none <-
df_end %>% length() == 0
if (still_none) {
df_end <-
urls %>%
future_map_dfr(function(x){
.guess_page_ongoing(url = x, override = TRUE)
})
df_end <-
df_end %>%
slice(nrow(df_end))
}
if (df_end %>% ncol() == 0) {
df_end <-
tibble(countStart = 0)
}
length_actual_pages <-
ceiling(df_end$countStart/100)
length_actual <-
seq(0, by = 100, length.out = length_actual_pages)
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&company=',term, '&type=&dateb=&owner=include&start=',
length_actual, '&count=100') %>%
purrr::reduce(paste0)
df_filing_urls <-
tibble(nameSearch = search_term, urlCIKPageFiling = urls) %>%
mutate(countPage = 1:n())
if('dfEnd' %>% exists()){
rm(list = c('dfEnd'), pos = ".GlobalEnv")
}
if ('is_on' %>% exists()) {
rm(list = c('is_on'), pos = ".GlobalEnv")
}
return(df_filing_urls)
}
.entity_ciks <-
function(search_term = "BREA", return_message = TRUE) {
url_df <-
.parse_search_page_length(search_term = search_term)
data <-
url_df$urlCIKPageFiling %>%
future_map_dfr(function(x) {
.parse_search_page(url = x, return_message = FALSE)
}) %>%
mutate(nameSearch = search_term) %>%
select(nameSearch, everything())
if (return_message) {
list("Returned ", nrow(data) %>% formattable::comma(digits = 0),
' SEC registered entities for the term ', search_term) %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
return(data)
}
edgar_entities_cik <-
function(search_names,
nest_data = FALSE,
return_message = TRUE) {
.sec_entity_safe <-
purrr::possibly(.entity_ciks, tibble())
all_data <-
search_names %>%
future_map_dfr(function(x) {
.sec_entity_safe(search_term = x, return_message = return_message)
}) %>%
select(which(colMeans(is.na(.)) < 1))
if (data %>% hasName("nameEntity")) {
all_data <-
all_data %>%
mutate(nameEntity = nameEntityLegal %>% str_to_upper() %>% str_replace_all('\\.|\\,', '') %>% str_trim())
}
all_data <-
all_data %>%
select(-dplyr::matches("idLocationEntity")) %>%
separate(nameEntity,
sep = '\\ /',
into = c('nameEntity', 'idLocationEntity')) %>%
mutate(idLocationEntity = idLocationEntity %>% str_replace_all('\\/', '') %>% str_trim()) %>%
select(nameSearch, idCIK, nameEntity, everything())
all_data <-
all_data %>%
separate(nameEntity, sep = 'FORMERLY: ', c('nameEntity', 'nameEntityFormer')) %>%
dplyr::select(which(colMeans(is.na(.)) < 1))
if (nest_data) {
all_data <-
all_data %>%
nest(-c(nameSearch), .key = dataSearch)
}
}
.extract_info <- function(page, css_node) {
page %>%
html_nodes(css = css_node) %>%
html_text()
}
.parse_city_state <-
function(x = "MENLO PARK CA 94025") {
parts <- x %>% str_split('\\ ') %>% flatten_chr()
over_2 <- parts %>% length() > 2
if (over_2) {
zipcode <- parts[parts %>% length()]
state_city <- parts[!parts %in% c(zipcode)]
state <- state_city[length(state_city)]
city <-
state_city[!state_city %in% state] %>% str_c(collapse = ' ')
data <-
tibble(
cityCompany = city,
stateCompany = state,
zipcodeCompany = zipcode
)
return(data)
}
tibble()
}
.generate_url <- function(ticker = "FB") {
glue::glue("https://www.sec.gov/cgi-bin/browse-edgar?CIK={ticker}&owner=exclude&action=getcompany&Find=Search")
}
.parse_company_info <-
function(url = "https://www.sec.gov/cgi-bin/browse-edgar?CIK=FB&owner=exclude&action=getcompany&Find=Search") {
page <-
url %>%
read_html()
name_parts <-
page %>%
.extract_info(css_node = '.companyName') %>%
str_split('\\ CIK') %>%
flatten_chr()
if (length(name_parts) == 0) {
stop("Invalid company symbol")
}
company_name <- name_parts[[1]]
cik <-
page %>% .extract_info(".companyName a") %>% str_split("\\(") %>%
flatten_chr() %>%
str_trim() %>%
.[[1]]
SIC <-
page %>%
.extract_info(".identInfo acronym+ a") %>%
as.character() %>%
readr::parse_number()
street.address <-
page %>%
.extract_info(".mailer:nth-child(1) .mailerAddress:nth-child(1)")
city.state.raw <-
page %>%
.extract_info(".mailer:nth-child(1) .mailerAddress+ .mailerAddress") %>%
str_trim()
city.state <- sub("\\s+$", "", city.state.raw)
city.state <- gsub("\n", "", city.state)
if (length(city.state) == 2) {
street.address <- paste(street.address, city.state[1])
city.state <- city.state[2]
}
df_city_state <-
city.state %>% .parse_city_state() %>%
mutate(addressStreetCompany = street.address) %>%
dplyr::select(addressStreetCompany, everything())
company.details <-
page %>%
.extract_info(".identInfo")
fiscal.year.end <-
gsub("^.*Fiscal Year End: ", "", company.details) %>%
substr(1, 4)
if (fiscal.year.end == "SIC:") {
fiscal.year.end <- NA
}
state <- gsub("^.*State location: ", "", company.details) %>%
substr(1, 2)
state.inc <- gsub("^.*State of Inc.: ", "", company.details) %>%
substr(1, 2)
if (state.inc == "SI") {
state.inc <- NA
}
data <-
tibble(
nameCompany = company_name,
slugCIK = cik,
idCIK = readr::parse_number(as.character(cik)),
idSIC = SIC,
stateIncorporated = state.inc,
monthDayFiscalYearEnd = fiscal.year.end
) %>%
bind_cols(df_city_state)
data
}
.parse_company_pages <-
function(urls,
return_message = TRUE) {
df <-
tibble()
success <- function(res) {
parse_company_info_safe <-
purrr::possibly(.parse_company_info, tibble())
data <-
.parse_company_info(url = res$url)
df <<-
df %>%
bind_rows(data)
}
failure <- function(msg) {
cat(sprintf("Fail: %s (%s)\n", res$url, msg))
}
urls %>%
walk(function(x) {
curl_fetch_multi(url = x, success, failure)
})
multi_run()
df
}
.sec_ticker_info <-
function(ticker = "VNO",
return_message = TRUE) {
if (return_message) {
glue::glue("Acquiring company information for {ticker}") %>% cat(fill = T)
}
.parse_company_pages_safe <-
purrr::possibly(.parse_company_pages, tibble())
url <- ticker %>%
.generate_url()
data <-
url %>%
.parse_company_pages_safe() %>%
mutate(idTicker = ticker) %>%
dplyr::select(idTicker, everything()) %>%
mutate_if(is.character,
str_to_upper)
data
}
sec_tickers_info <-
function(tickers = c("VNO", "NVDA", "FB"),
join_sic = T,
snake_names = F,
unformat = F,
convert_case = T,
amount_digits = 2,
include_address = T,
return_message = TRUE) {
all_data <-
tickers %>%
future_map_dfr(function(x) {
.sec_ticker_info(ticker = x, return_message = return_message)
}) %>%
dplyr::select(which(colMeans(is.na(.)) < 1))
if (join_sic) {
all_data <-
all_data %>%
left_join(dictionary_sic_codes(), by = "idSIC")
}
all_data %>%
munge_tbl(
snake_names = snake_names,
unformat = unformat,
convert_case = convert_case,
amount_digits = amount_digits,
include_address = include_address
)
all_data
}
.sec_filer_name_page_df <-
function(){
tibble(
nameSEC = c("dateFiled", "filingHREF", "formName", "type", "XBRLREF"),
nameActual = c(
"dateFiling",
"urlSECFilingDirectory",
"nameForm",
"idForm",
"urlXBRL"
)
)
}
.guess_page_ongoing <-
function(url = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=1184765&type=&dateb=&owner=include&start=0&count=100",
override = FALSE) {
page <-
url %>%
read_html()
page_count <-
url %>%
str_split('count=') %>%
flatten_chr() %>%
.[[2]] %>%
str_split('&') %>%
flatten_chr() %>%
.[[1]] %>%
as.character() %>%
readr::parse_number()
items <-
page %>%
html_nodes('input') %>%
html_attr('value') %>% str_to_upper() %>%
unique()
if (items %>% length() == 0){
return(invisible())
}
no_page <-
page %>%
html_nodes('h1') %>%
html_text() %>%
str_to_lower() == 'invalid parameter'
no_page <-
no_page %>%
length() > 0
is_end <-
!items %>% str_detect("NEXT 100") %>% sum(na.rm = T) > 0
if (is_end & (!no_page)) {
return(tibble(isEnd = TRUE, countStart = page_count))
}
if (!override) {
if (!is_end) {
return(tibble())
}
} else {
return(tibble(countStart = page_count))
}
tibble(isEnd = is_end, countPage = page_count -100)
}
.cik_filer_page_urls <-
function(cik = 1184765, pages_out = 20) {
start_pages <-
seq(0, by = 100, length.out = pages_out)
if ('dfEnd' %>% exists()) {
eval(rm(dfEnd))
}
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=',cik, '&type=&dateb=&owner=include&start=',
start_pages, '&count=100') %>%
purrr::reduce(paste0)
is_on <-
TRUE
for (url in urls) {
if (!is_on) {
invisible()
}
if('dfEnd' %>% exists()) {
invisible()
} else {
df_end <-
.guess_page_ongoing(url = url, override = FALSE)
is_over_zero <-
df_end %>% length() > 0
if (is_over_zero) {
assign('dfEnd', eval(df_end), envir = .GlobalEnv)
assign('is_on', eval(FALSE), envir = .GlobalEnv)
rm(is_over_zero)
}
}
}
still_none <-
df_end %>% length() == 0
if (still_none) {
df_end <-
urls %>%
future_map_dfr(function(x){
.guess_page_ongoing(url = x, override = TRUE)
})
df_end <-
df_end %>%
slice(nrow(df_end))
}
length_actual_pages <-
ceiling(df_end$countStart/100)
length_actual <-
seq(0, by = 100, length.out = length_actual_pages)
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=',cik, '&type=&dateb=&owner=include&start=',
length_actual, '&count=100', '&output=xml') %>%
purrr::reduce(paste0)
df_filing_urls <-
tibble(idCIK = cik, urlCIKPageFiling = urls) %>%
mutate(countPage = 1:n())
if('dfEnd' %>% exists()){
rm(list = c('dfEnd'), pos = ".GlobalEnv")
}
return(df_filing_urls)
}
.parse_cik_filer_page <-
function(url = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=899689&type=&dateb=&owner=include&start=600&count=100&output=xml",
return_message = TRUE) {
page <-
url %>%
read_xml()
xml_nodes <-
page %>%
xml_contents() %>%
.[[2]]
filing_count <-
xml_nodes %>%
xml_contents() %>%
xml_name()
df_page_items <-
seq_along(filing_count) %>%
future_map_dfr(function(x) {
xml_node <-
xml_nodes %>%
xml_contents() %>%
.[[x]]
items <-
xml_node %>%
xml_children() %>%
xml_name()
values <-
xml_node %>%
xml_children() %>%
xml_text()
return(tibble(
countPageFiling = x,
nameSEC = items,
value = values
))
}) %>%
left_join(.sec_filer_name_page_df()) %>%
suppressWarnings() %>%
suppressMessages() %>%
select(-nameSEC)
df_page_items <-
df_page_items %>%
spread(nameActual, value) %>%
.resolve_form_columns() %>%
mutate(urlCIKPageFiling = url)
df_page_items <-
df_page_items %>%
find_target_filings()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df_page_items)
}
.df_general_name_df <-
function() {
tibble(nameSEC = c("CIK", "CIKHREF", "Location", "SIC", "SICDescription", "SICHREF",
"businessAddresscity", "businessAddressphoneNumber", "businessAddressstate",
"businessAddressstreet", "businessAddresszipCode", "fiscalYearEnd",
"mailingAddresscity", "mailingAddressstate", "mailingAddressstreet",
"mailingAddresszipCode", "name", "stateOfIncorporation", "businessAddressstreet2", "mailingAddressstreet2", 'formerNames',
'businessAddress', 'formerNamedate', 'formerNamename',
'mailingAddress'),
nameActual = c("idCIK", "urlCIKFiling", "locationEntity", "idSICEntity", "nameIndustry", "urlSICMembers",
"cityAddressBusiness", "phoneAddressBusiness", "stateAddressBusiness",
"addressStreet1Business", "zipcodeBusiness", "periodFiscalYearEnd",
"cityAddressMailing", "stateAddressMailing", "addressStreet1Mailing",
"zipcodeMailing", "nameEntity", "stateIncorporation",
"addressStreet2Mailing", "addressStreet2Business", 'nameEntity',
'addressBusiness', 'dateFormerName', 'nameEntity',
'addressMailing')
)
}
.parse_cik_filer_general_info <-
function(url = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=1326801&type=&dateb=&owner=include&start=0&count=100&output=xml") {
page <-
url %>%
read_xml()
xml_nodes <-
page %>%
xml_contents() %>%
.[[1]]
items <-
xml_nodes %>%
xml_children() %>%
xml_name()
df_names <-
.df_general_name_df()
df_general <-
seq_along(items) %>%
future_map_dfr(function(x){
xml_node <-
xml_nodes %>%
xml_contents() %>%
.[[x]]
item <-
items[[x]]
xml_search <-
list('//', item, '/value') %>%
purrr::reduce(paste0)
value <-
xml_node %>%
xml_find_all(xml_search) %>%
xml_text()
no_val <-
value %>% length() == 0
if (item == 'formerNames') {
value_search <-
list('//', item) %>% purrr::reduce(paste0)
item_parent <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_name()
items <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_children() %>%
xml_name()
values <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_children() %>%
xml_text()
df <-
tibble(
countItem = x,
itemParent = item_parent[seq_along(item)],
nameSEC = items,
value = values
) %>%
unite(nameSEC, itemParent, nameSEC, sep = '')
return(df)
}
if (item == 'name') {
value_search <-
list('//', item) %>% purrr::reduce(paste0)
items <-
xml_node %>%
xml_find_all(value_search) %>%
xml_name()
items <-
items[length(items)]
values <-
xml_node %>%
xml_find_all(value_search) %>%
xml_text()
values <-
values[length(values)]
df <-
tibble(
countItem = x,
nameSEC = items,
value = values
)
return(df)
}
if (no_val) {
value_search <-
list('//', item) %>% purrr::reduce(paste0)
has_children <-
xml_node %>%
xml_find_all(value_search) %>% xml_children() %>% xml_length() %>% length() > 1
if (has_children) {
has_more_children <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_children() %>% xml_length() %>% length() > 1
if (has_more_children) {
item_parent <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_name()
items <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_children() %>%
xml_name()
values <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_children() %>%
xml_text()
df <-
tibble(
countItem = x,
itemParent = item_parent[seq_along(item)],
nameSEC = items,
value = values
) %>%
unite(nameSEC, itemParent, nameSEC, sep = '')
return(df)
}
item_parent <-
xml_node %>%
xml_find_all(value_search) %>%
xml_name()
item <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_name()
values <-
xml_node %>%
xml_find_all(value_search) %>%
xml_children() %>%
xml_text()
df <-
tibble(
countItem = x,
itemParent = item_parent,
nameSEC = item,
value = values
) %>%
unite(nameSEC, itemParent, nameSEC, sep = '')
return(df)
}
if (!has_children) {
values <-
xml_node %>%
xml_find_all(value_search) %>%
xml_text()
}
df <-
tibble(
countItem = x,
nameSEC = item,
value = values
)
return(df)
}
nameSEC <-
xml_node %>%
xml_find_all(list('//', item) %>% purrr::reduce(paste0)) %>%
xml_name()
tibble(idRow = countRow, nameSEC, value = value)
})
df_general <-
df_general %>%
left_join(df_names) %>%
suppressMessages()
missing_names <-
df_general$nameSEC[!df_general$nameSEC %in% df_names$nameSEC] %>%
length() >0
if (missing_names) {
missing_n <-
df_general$nameSEC[!df_general$nameSEC %in% df_names$nameSEC]
stop(list("Missing ", missing_n) %>%
purrr::reduce(paste0))
}
df_general <-
df_general %>%
select(-c(nameSEC,countItem)) %>%
group_by(nameActual) %>%
mutate(idRow = 1:n()) %>%
filter(idRow == min(idRow)) %>%
ungroup() %>%
suppressMessages()
col_order <-
df_general$nameActual
df_general <-
df_general %>%
spread(nameActual, value) %>%
select(one_of(col_order)) %>%
dplyr::rename(nameEntityLegal = nameEntity) %>%
mutate(nameEntity = nameEntityLegal %>% str_to_upper() %>% str_replace_all('\\.|\\,', '') %>% str_trim()) %>%
separate(nameEntity,
sep = '\\ /',
into = c('nameEntity', 'idLocationEntity')) %>%
mutate(
idLocationEntity = idLocationEntity %>% str_replace_all('\\/', '') %>% str_trim()
) %>%
select(nameEntity, everything()) %>%
suppressWarnings() %>%
suppressMessages()
return(df_general)
}
.cik_filer_filings <-
function(cik = 899689) {
df_urls <-
.cik_filer_page_urls(cik = cik) %>%
suppressWarnings() %>%
suppressMessages()
parse_cik_filer_page_safe <-
purrr::possibly(.parse_cik_filer_page, tibble())
df_filings <-
df_urls$urlCIKPageFiling %>%
future_map_dfr(function(x) {
parse_cik_filer_page_safe(url = x)
}) %>%
mutate(idCIK = cik) %>%
select(idCIK, everything())
df_general <-
df_urls$urlCIKPageFiling[[1]] %>%
.parse_cik_filer_general_info() %>%
mutate_all(funs(ifelse(. == '', NA, .))) %>%
.resolve_form_columns() %>%
select(which(colMeans(is.na(.)) < 1))
df_filings <-
df_filings %>%
left_join(df_general %>% select(idCIK, nameEntity)) %>%
suppressMessages()
df_filings <-
df_filings %>%
select(-countPageFiling) %>%
arrange(dateFiling) %>%
mutate(countFilingEntity = 1:n()) %>%
arrange(desc(dateFiling)) %>%
select(countFilingEntity, idCIK, nameEntity, everything())
if ('urlXBRL' %in% names(df_filings)) {
df_filings <-
df_filings %>%
mutate(hasXBRL = ifelse(!urlXBRL %>% is.na(), TRUE, FALSE))
}
df_filings
}
.sic_filer_page_urls <-
function(sic = 6798, pages_out = 20) {
start_pages <-
seq(0, by = 100, length.out = pages_out)
if ('dfEnd' %>% exists()) {
eval(rm(dfEnd))
}
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&SIC=',sic, '&type=&dateb=&owner=include&start=',
start_pages, '&count=100') %>%
purrr::reduce(paste0)
is_on <-
TRUE
for (url in urls) {
if (!is_on) {
invisible()
}
if('dfEnd' %>% exists()) {
invisible()
} else {
df_end <-
.guess_page_ongoing(url = url, override = FALSE)
is_over_zero <-
df_end %>% length() > 0
if (is_over_zero) {
assign('dfEnd', eval(df_end), envir = .GlobalEnv)
assign('is_on', eval(FALSE), envir = .GlobalEnv)
rm(is_over_zero)
}
}
}
still_none <-
df_end %>% length() == 0
if (still_none) {
df_end <-
tibble(countStart = 0)
}
length_actual_pages <-
ceiling(df_end$countStart/100)
length_actual <-
seq(0, by = 100, length.out = length_actual_pages)
urls <-
list('https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&SIC=',sic, '&type=&dateb=&owner=include&start=',
length_actual, '&count=100', '&output=xml') %>%
purrr::reduce(paste0)
df_sic_urls <-
tibble(idSIC = sic, urlSICPageFiling = urls) %>%
mutate(countPage = 1:n())
if('dfEnd' %>% exists()){
rm(list = c('dfEnd'), pos = ".GlobalEnv")
}
return(df_sic_urls)
}
.sic_code_filer <-
function(sic = 6798,
return_message = TRUE) {
sic_filer_page_urls_safe <-
purrr::possibly(.sic_filer_page_urls, tibble())
url_df <-
sic_filer_page_urls_safe(sic = sic)
parse_search_page_safe <-
purrr::possibly(.parse_search_page, tibble())
all_data <-
url_df$urlSICPageFiling %>%
future_map_dfr(function(x){
parse_search_page_safe(url = x, return_message = return_message)
}) %>%
mutate(idSIC = sic) %>%
select(idSIC, everything())
if (return_message) {
list('\nReturned ', all_data %>% nrow() %>% formattable::comma(digits = 0),
' SEC registered entities for SIC industry code ', sic,'\n') %>%
purrr::reduce(paste0) %>%
cat(fill = T)
}
return(all_data)
}
edgar_sic_filers <-
function(sic_codes = NULL,
merge_names = TRUE,
return_message = TRUE,
nest_data = FALSE) {
if (length(sic_codes) == 0) {
stop("Please enter SIC codes to search")
}
sic_code_filer_safe <-
purrr::possibly(.sic_code_filer, tibble())
all_data <-
sic_codes %>%
future_map_dfr(function(x){
sic_code_filer_safe(sic = x, return_message = return_message)
})
if (merge_names) {
if (!'dataSICCodes' %>% exists()) {
assign(x = 'dataSICCodes', value = eval(dictionary_sic_codes()),
envir = .GlobalEnv)
}
all_data <-
all_data %>%
left_join(
dataSICCodes %>% select(-nameOfficeAD)
) %>%
select(idSIC, nameIndustry, everything()) %>%
suppressMessages()
}
return(all_data)
}
.parse_sec_url_for_cik <-
function(url) {
url %>%
str_replace_all("https://www.sec.gov/Archives/edgar/data/", '') %>%
str_split('\\/') %>%
flatten_chr() %>%
.[[1]] %>%
as.numeric()
}
.loc_df <-
function() {
tibble(
nameLocation = c(
"AFGHANISTAN",
"ALAND ISLANDS",
"ALBANIA",
"ALGERIA",
"AMERICAN SAMOA",
"ANDORRA",
"ANGOLA",
"ANGUILLA",
"ANTARCTICA",
"ANTIGUA AND BARBUDA",
"ARGENTINA",
"ARMENIA",
"ARUBA",
"AUSTRALIA",
"AUSTRIA",
"AUSTRIA-HUNGARY",
"AZERBAIJAN",
"BADEN",
"BAHAMAS",
"BAHRAIN",
"BANGLADESH",
"BARBADOS",
"BAVARIA",
"BELARUS",
"BELGIUM",
"BELIZE",
"BENIN",
"BERMUDA",
"BHUTAN",
"BOLIVIA, PLURINATIONAL STATE OF",
"BONAIRE, SINT EUSTATIUS AND SABA",
"BOSNIA AND HERZEGOVINA",
"BOTSWANA",
"BOUVET ISLAND",
"BRAZIL",
"BRITISH INDIAN OCEAN TERRITORY",
"BRUNEI DARUSSALAM",
"BULGARIA",
"BURKINA FASO",
"BURUNDI",
"CAMBODIA",
"CAMEROON",
"CANADA",
"CABO VERDE",
"CAYMAN ISLANDS",
"CENTRAL AFRICAN REPUBLIC",
"CHAD",
"CHILE",
"CHINA",
"CHRISTMAS ISLAND",
"COCOS (KEELING) ISLANDS",
"COLOMBIA",
"COMOROS",
"CONGO, THE DEMOCRATIC REPUBLIC OF THE",
"CONGO",
"COOK ISLANDS",
"COSTA RICA",
"COTE D'IVOIRE",
"CROATIA",
"CUBA",
"CURACAO",
"CYPRUS",
"CZECH REPUBLIC",
"CZECHOSLOVAKIA",
"DENMARK",
"DJIBOUTI",
"DOMINICA",
"DOMINICAN REPUBLIC",
"ECUADOR",
"EGYPT",
"EL SALVADOR",
"EQUATORIAL GUINEA",
"ERITREA",
"ESTONIA",
"ETHIOPIA",
"FALKLAND ISLANDS (MALVINAS)",
"FAROE ISLANDS",
"FIJI",
"FINLAND",
"FRANCE",
"FRENCH GUIANA",
"FRENCH POLYNESIA",
"FRENCH SOUTHERN TERRITORIES",
"GABON",
"GAMBIA",
"GEORGIA",
"GERMAN DEMOCRATIC REPUBLIC",
"FEDERAL REPUBLIC OF GERMANY",
"GERMANY",
"GHANA",
"GIBRALTAR",
"GREECE",
"GREENLAND",
"GRENADA",
"GUADELOUPE",
"GUAM",
"GUATEMALA",
"GUERNSEY",
"GUINEA",
"GUINEA-BISSAU",
"GUYANA",
"HAITI",
"HANOVER",
"HEARD ISLAND AND MCDONALD ISLANDS",
"HESSE ELECTORAL",
"HESSE GRAND DUCAL",
"HOLY SEE (VATICAN CITY STATE)",
"HONDURAS",
"HONG KONG",
"HUNGARY",
"ICELAND",
"INDIA",
"INDONESIA",
"IRAN, ISLAMIC REPUBLIC OF",
"IRAQ",
"IRELAND",
"ISLE OF MAN",
"ISRAEL",
"ITALY",
"JAMAICA",
"JAPAN",
"JERSEY",
"JORDAN",
"KAZAKHSTAN",
"KENYA",
"KIRIBATI",
"KOREA",
"KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF",
"KOREA, REPUBLIC OF",
"KOSOVO",
"KUWAIT",
"KYRGYZSTAN",
"LAO PEOPLE'S DEMOCRATIC REPUBLIC",
"LATVIA",
"LEBANON",
"LESOTHO",
"LIBERIA",
"LIBYA",
"LIECHTENSTEIN",
"LITHUANIA",
"LUXEMBOURG",
"MACAO",
"MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF",
"MADAGASCAR",
"MALAWI",
"MALAYSIA",
"MALDIVES",
"MALI",
"MALTA",
"MARSHALL ISLANDS",
"MARTINIQUE",
"MAURITANIA",
"MAURITIUS",
"MAYOTTE",
"MECKLENBURG SCHWERIN",
"MEXICO",
"MICRONESIA, FEDERATED STATES OF",
"MODENA",
"MOLDOVA, REPUBLIC OF",
"MONACO",
"MONGOLIA",
"MONTENEGRO",
"MONTSERRAT",
"MOROCCO",
"MOZAMBIQUE",
"MYANMAR",
"NAMIBIA",
"NAURU",
"NEPAL",
"NETHERLANDS",
"NETHERLANDS ANTILLES",
"NEW CALEDONIA",
"NEW ZEALAND",
"NICARAGUA",
"NIGER",
"NIGERIA",
"NIUE",
"NORFOLK ISLAND",
"NORTHERN MARIANA ISLANDS",
"NORWAY",
"OMAN",
"PAKISTAN",
"PALAU",
"PALESTINE, STATE OF",
"PANAMA",
"PAPUA NEW GUINEA",
"PARAGUAY",
"PARMA",
"PERU",
"PHILIPPINES",
"PITCAIRN",
"POLAND",
"PORTUGAL",
"PUERTO RICO",
"QATAR",
"REPUBLIC OF VIETNAM",
"REUNION",
"ROMANIA",
"RUSSIAN FEDERATION",
"RWANDA",
"SAINT BARTHELEMY",
"SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA",
"SAINT KITTS AND NEVIS",
"SAINT LUCIA",
"SAINT MARTIN (FRENCH PART)",
"SAINT PIERRE AND MIQUELON",
"SAINT VINCENT AND THE GRENADINES",
"SAMOA",
"SAN MARINO",
"SAO TOME AND PRINCIPE",
"SAUDI ARABIA",
"SAXONY",
"SENEGAL",
"SERBIA",
"SEYCHELLES",
"SIERRA LEONE",
"SINGAPORE",
"SINT MAARTEN (DUTCH PART)",
"SLOVAKIA",
"SLOVENIA",
"SOLOMON ISLANDS",
"SOMALIA",
"SOUTH AFRICA",
"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS",
"SOUTH SUDAN",
"SPAIN",
"SRI LANKA",
"SUDAN",
"SURINAME",
"SVALBARD AND JAN MAYEN",
"SWAZILAND",
"SWEDEN",
"SWITZERLAND",
"SYRIAN ARAB REPUBLIC",
"TAIWAN, PROVINCE OF CHINA",
"TAJIKISTAN",
"TANZANIA, UNITED REPUBLIC OF",
"THAILAND",
"TIMOR-LESTE",
"TOGO",
"TOKELAU",
"TONGA",
"TRINIDAD AND TOBAGO",
"TUNISIA",
"TURKEY",
"TURKMENISTAN",
"TURKS AND CAICOS ISLANDS",
"TUSCANY",
"TUVALU",
"TWO SICILIES",
"UGANDA",
"UKRAINE",
"UNITED ARAB EMIRATES",
"UNITED KINGDOM",
"UNITED STATES",
"UNITED STATES MINOR OUTLYING ISLANDS",
"URUGUAY",
"UZBEKISTAN",
"VANUATU",
"VENEZUELA, BOLIVARIAN REPUBLIC OF",
"VIET NAM",
"VIRGIN ISLANDS, BRITISH",
"VIRGIN ISLANDS, U.S.",
"WALLIS AND FUTUNA",
"WESTERN SAHARA",
"WUERTTEMBURG",
"YEMEN",
"YEMEN ARAB REPUBLIC",
"YEMEN PEOPLE'S REPUBLIC",
"YUGOSLAVIA",
"ZAMBIA",
"ZANZIBAR",
"ZIMBABWE",
"ALABAMA",
"ALASKA",
"ARIZONA",
"ARKANSAS",
"CALIFORNIA",
"COLORADO",
"CONNECTICUT",
"DELAWARE",
"FLORIDA",
"GEORGIA",
"HAWAII",
"IDAHO",
"ILLINOIS",
"INDIANA",
"IOWA",
"KANSAS",
"KENTUCKY",
"LOUISIANA",
"MAINE",
"MARYLAND",
"MASSACHUSETTS",
"MICHIGAN",
"MINNESOTA",
"MISSISSIPPI",
"MISSOURI",
"MONTANA",
"NEBRASKA",
"NEVADA",
"NEW HAMPSHIRE",
"NEW JERSEY",
"NEW MEXICO",
"NEW YORK",
"NORTH CAROLINA",
"NORTH DAKOTA",
"OHIO",
"OKLAHOMA",
"OREGON",
"PENNSYLVANIA",
"RHODE ISLAND",
"SOUTH CAROLINA",
"SOUTH DAKOTA",
"TENNESSEE",
"TEXAS",
"UTAH",
"VERMONT",
"VIRGINIA",
"WASHINGTON",
"WEST VIRGINIA",
"WISCONSIN",
"WYOMING",
"DISTRICT OF COLUMBIA",
"ENGLAND",
"BRITISH VIRGIN ISLANDS",
"NETHERLAND ANTILLES",
"RUSSIA",
"SOUTH KOREA",
'TAIWAN',
"VENEZUELA",
'CHANNEL ISLANDS'
)
)
}
.parse_page_sub_multi_item_html <-
function(page) {
locations <-
.loc_df() %>%
.$nameLocation
subsidiaries <-
page %>%
html_nodes('td div') %>%
html_text() %>%
str_replace_all('\u0095 |\u0096|\u0095\n', '') %>%
str_trim()
subsidiaries <-
subsidiaries[!subsidiaries == '']
data_nodes <-
page %>%
html_nodes('td') %>%
html_text() %>%
str_replace_all('\u0095 |\u0096|\u0095\n', '') %>%
str_trim() %>%
str_to_upper()
data_nodes <-
data_nodes[!data_nodes == '']
location_items <-
data_nodes[data_nodes %in% locations]
pct_vals <-
tibble(value = data_nodes) %>%
filter(!value %>% str_detect("\\([(1-9)]\\)")) %>%
mutate(pctSubsidiaryOwned = value %>% as.numeric()) %>%
filter(!pctSubsidiaryOwned %>% is.na()) %>%
slice(seq_along(subsidiaries)) %>%
.$pctSubsidiaryOwned / 100 %>%
suppressWarnings() %>%
suppressMessages()
all_data <-
tibble(
nameSubsidiary = subsidiaries,
nameLocationSubsidiary = location_items,
pctSubsidiaryOwned = pct_vals
) %>%
mutate(nameSubsidiary = nameSubsidiary %>% str_to_upper())
return(all_data)
}
.parse_page_subsidiary_table_html <-
function(page,
numbers = 1:10,
hit_terms = c(
"Organized",
"STATE OR|STATE OF|JURISDICTION OF|JURISDICTION OF INCORPORATION OR ORGANIZATION|JURISDICTION|JURISDICTION OF INCORPORATION OR\nORGANIZATION",
"NAME|ORGANIZED UNDER THE LAWS OF",
'STATE OF ORGANIZATION',
'STATE OR COUNTRY OF ORGANIZATION',
'NAME OF SUBSIDIARY',
'NAME',
'ENTITY NAME',
'the laws of',
'Percentage of voting',
'securities owned by',
'immediate parent',
'CERTAIN INTERMEDIARY SUBSIDIARIES',
'Note:',
'Organized',
'Under the',
'Laws of',
'OWNED BY',
'IMMEDIATE',
'PARENT',
"OWNS",
"CERTAIN INTERMEDIARY SUBSIDIARIES",
'PERCENTAGE',
'OF VOTING',
'SECURITIES'
)) {
is_ib1 <-
page %>%
html_nodes('b font') %>%
html_text() %>% length() > 0
if (is_ib1) {
items_bold <-
page %>%
html_nodes('b font') %>%
html_text() %>%
str_to_upper() %>%
str_replace_all('\n', ' ') %>%
stringi::stri_trans_general("Latin-ASCII")
str_split('\\-') %>%
flatten_chr() %>%
str_trim()
} else {
items_bold <-
page %>%
html_nodes('b') %>%
html_text() %>%
str_to_upper() %>%
str_replace_all('\n', ' ') %>%
stringi::stri_trans_general("Latin-ASCII") %>%
str_split('\\-') %>%
flatten_chr() %>%
str_trim() %>%
unique()
}
has_date <-
items_bold %>% grep(month.name %>% str_to_upper() %>% paste(collapse = '|'), .) %>% length > 0
if (has_date) {
date_data <-
items_bold[items_bold %>% grep(month.name %>% str_to_upper() %>% paste(collapse = '|'), .)] %>%
lubridate::mdy()
} else {
date_data <-
NA
}
hit_terms <-
hit_terms %>%
append(items_bold) %>%
str_to_upper() %>%
unique() %>%
append(list('(', letters, ')') %>%
purrr::invoke(paste0, .)) %>%
paste0(collapse = '|')
hit_terms_in <-
hit_terms %>% str_split('\\|') %>%
flatten_chr()
locations <-
.loc_df() %>%
.$nameLocation
all_data <-
numbers %>%
future_map_dfr(function(x) {
css_selector <-
paste0('td:nth-child(', x, ')')
has_length <-
page %>%
html_nodes(css_selector) %>% length() > 0
if (has_length) {
item <-
paste0("X" , x)
value <-
page %>%
html_nodes(css_selector) %>%
html_text() %>%
str_trim()
tibble(item, value)
}
}) %>%
mutate(
value = value %>% str_to_upper() %>% str_replace_all('\n ', ' ') %>% str_replace_all('\u0096 ', '')
) %>%
filter(!value == '')
has_loc_key <-
all_data %>%
filter(value %in% locations) %>%
nrow() > 0
if (has_loc_key) {
loc_cols <-
all_data %>%
filter(value %in% locations) %>%
.$item %>%
unique()
if (loc_cols %>% length == 1) {
loc_col <-
loc_cols[[1]]
}
}
has_pct <-
all_data %>%
filter(value %>% str_detect("PERCENT")) %>%
.$item %>% unique() %>% length() > 0
if (has_pct) {
pct_col <-
all_data %>%
filter(value %>% str_detect("PERCENT")) %>%
.$item %>% unique()
} else {
pct_col <-
NA
}
is_whack <-
pct_col[[1]] %in% loc_cols
if (is_whack) {
all_data <-
page %>%
.parse_page_sub_multi_item_html() %>%
mutate(dateSubsidiaryAsOf = date_data)
return(all_data)
}
all_data <-
all_data %>%
filter(!value %in% items_bold) %>%
filter(!value %>% str_detect(paste0(items_bold %>% unique(), collapse = '|'))) %>%
filter(!value %in% hit_terms_in) %>%
filter(!value %>% str_detect(hit_terms))
count_df <-
all_data %>% count(item, sort = T) %>%
arrange(item) %>%
spread(item, n)
off_one <-
(count_df[, 2] %>% extract2(1)) - (count_df[, 1] %>% extract2(1)) == 1
min_item <-
count_df %>% gather(item, value) %>% filter(value == min(value)) %>% .$item
change_pct <-
has_pct & (pct_col == min_item) %>% sum() > 0
if (change_pct) {
pct_col <-
names(count_df)[[3]]
}
if (off_one) {
df <-
all_data$item %>% unique() %>%
future_map_dfr(function(x) {
has_data <-
all_data %>%
filter(item == x) %>%
filter(!value %>% is.na()) %>%
filter(!value == '') %>%
nrow()
if (has_data) {
all_data %>%
filter(item == x) %>%
filter(!value %>% is.na()) %>%
filter(!value == '') %>%
filter(!value %>% str_detect(hit_terms)) %>%
mutate(idSubsidiary = 1:n())
}
}) %>%
filter(!value %>% str_detect(hit_terms)) %>%
spread(item, value)
if (change_pct) {
df <-
df %>%
select(-one_of(min_item))
}
}
if (!off_one) {
has_property <-
items_bold %>% str_detect('PROPERTY') %>% sum() > 0
if (has_property) {
tables <-
page %>%
html_table(fill = T)
df <-
seq_along(tables) %>%
future_map_dfr(function(x) {
table_df <-
tables[[x]] %>%
data.frame(stringsAsFactors = FALSE) %>%
as_tibble()
column_df <-
table_df %>% slice(1) %>%
gather(column, value) %>%
mutate(idColumn = 1:n()) %>%
filter(!value %>% is.na()) %>%
left_join(tibble(
value = c(
"PROPERTY",
"ENTITIES",
"STATE OF FORMATION",
"DATE OF FORMATION",
" ",
'General Information:'
),
nameItem = c(
'nameProperty',
'nameSubsidiary',
'locationOrganizationSubsidiary',
'dateSubsidiaryFormed',
'locationOrganizationSubsidiary',
'nameSubsidiary'
)
)) %>%
suppressMessages()
two_col <-
column_df %>% nrow() == 2
if (two_col) {
column_df$nameItem[[2]] <-
'locationOrganizationSubsidiary'
}
columns_keep <-
column_df$idColumn
table_df <-
table_df <-
table_df %>%
select(columns_keep) %>%
slice(-1) %>%
purrr::set_names(column_df$nameItem)
table_df <-
table_df %>%
mutate_all(funs(. %>% str_trim() %>% str_to_upper())) %>%
mutate(nameSubsidiary = ifelse(nameSubsidiary == '', NA, nameSubsidiary)) %>%
filter(!nameSubsidiary %>% is.na())
if (two_col) {
table_df <-
table_df %>%
tidyr::separate(
locationOrganizationSubsidiary,
into = c(
'locationOrganizationSubsidiary',
'dateSubsidiaryFormed'
),
sep = 'FORMED'
) %>%
suppressWarnings() %>%
mutate(locationOrganizationSubsidiary = locationOrganizationSubsidiary %>% str_replace_all('\\,', '')) %>%
mutate_all(funs(. %>% str_replace('\n', '') %>% str_trim()))
}
if ('nameProperty' %in% names(table_df)) {
table_df <-
table_df %>%
mutate(nameProperty = ifelse(nameProperty == '', NA, nameProperty)) %>%
mutate_all(funs(. %>% str_replace('\n|\n |\n ', '') %>% str_trim())) %>%
mutate_all(funs(. %>% str_replace('\n', '') %>% str_trim())) %>%
mutate_all(funs(. %>% str_replace(' ', ' ') %>% str_trim())) %>%
fill(nameProperty)
}
return(table_df)
})
if ('dateSubsidiaryFormed' %in% names(df)) {
df <-
df %>%
mutate(dateSubsidiaryFormed = dateSubsidiaryFormed %>% lubridate::mdy())
}
df <-
df %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(idCIK, nameSubsidiary, everything()) %>%
mutate(
locationOrganizationSubsidiary = locationOrganizationSubsidiary %>% str_replace_all(
'A |LIMITED LIABILITY COMPANY|CORPORATION|LIMITED PARTNERSHIP'
) %>% str_trim()
)
return(df)
}
if (!has_property) {
df <-
all_data %>%
mutate(value = ifelse(value == '', NA, value)) %>%
filter(!value %>% is.na()) %>%
group_by(item) %>%
mutate(idSubsidiary = 1:n()) %>%
spread(item, value) %>%
filter(!X1 == '') %>%
mutate(idSubsidiary = 1:n()) %>%
gather(item, value, -c(X1, idSubsidiary)) %>%
ungroup() %>%
filter(!value %>% str_detect(hit_terms)) %>%
spread(item, value)
}
}
df <-
df %>%
dplyr::rename(nameSubsidiary = X1) %>%
tidyr::separate(nameSubsidiary,
sep = '\\(',
into = c('nameSubsidiary', 'remove')) %>%
select(-dplyr::matches("remove")) %>%
mutate(nameSubsidiary = nameSubsidiary %>% str_trim()) %>%
suppressWarnings() %>%
select(-dplyr::matches("idSubsidiary"))
if (has_pct) {
names(df)[names(df) %>% grep(pct_col, .)] <-
'pctSubsidiaryOwned'
df <-
df %>%
mutate_at(df %>% select(dplyr::matches('pct')) %>% names(),
funs(. %>% as.numeric() / 100)) %>%
suppressWarnings()
}
if (has_loc_key) {
names(df)[names(df) %>% grep(loc_col, .)] <-
'locationOrganizationSubsidiary'
}
df <-
df %>%
select(-dplyr::matches("X"))
return(df)
}
.parse_sec_subsidiary_url_html <-
function(url = "https://www.sec.gov/Archives/edgar/data/34088/000003408816000065/xomexhibit21.htm",
return_message = TRUE) {
cik <-
url %>%
.parse_sec_url_for_cik()
page <-
url %>%
read_html()
is_zero <-
page %>%
html_nodes(paste0('td:nth-child(', 1, ')')) %>%
length() == 0
locations <-
.loc_df() %>%
.$nameLocation
if (is_zero) {
data <-
page %>%
html_nodes('font') %>%
html_text() %>%
str_replace_all('\\ ', ' ')
data <-
data[!data == '']
is_parenth <-
data %>% str_detect('\\(') %>% sum() / length(data) > .25
if (is_parenth) {
data <-
data[data %>% str_detect('\\(')]
df <-
tibble(data) %>%
separate(
data,
sep = '\\(',
into = c('nameSubsidiary', 'locationOrganizationSubsidiary')
) %>%
separate(
locationOrganizationSubsidiary,
sep = '\\)',
into = c('locationOrganizationSubsidiary', 'remove')
) %>%
select(-remove) %>%
mutate_all(funs(. %>% str_trim() %>% str_to_upper())) %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary"))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
is_nested <-
page %>%
html_nodes('b font') %>%
html_text() %>% length() > 2
if (is_nested) {
locations_raw <-
page %>%
html_nodes('b font') %>%
html_text() %>%
str_replace_all('\\:', '') %>%
str_to_upper()
locations <-
locations_raw[!locations_raw %>% str_detect('EXHIBIT|SUBSIDIARY|SUBSIDIARIES')]
data <-
data[data %>% nchar() > 3] %>% str_to_upper()
df <-
tibble(nameSubsidiary = data) %>%
mutate(idRow = 1:n())
.loc_df <-
tibble(nameSubsidiary = locations) %>%
inner_join(df %>% select(idRow, nameSubsidiary)) %>%
mutate(idRow = idRow + 1) %>%
select(locationOrganizationSubsidiary = nameSubsidiary, idRow) %>%
suppressMessages()
df <-
df %>%
filter(!nameSubsidiary %>% str_detect('SUBSIDIARY|SUBSIDIARIES')) %>%
filter(!nameSubsidiary %>% str_detect(paste0(locations_raw, collapse = '|'))) %>%
suppressWarnings()
df <-
df %>%
left_join(.loc_df) %>%
fill(locationOrganizationSubsidiary) %>%
mutate(urlSEC = url, idCIK = cik) %>%
select(idCIK,
nameSubsidiary,
locationOrganizationSubsidiary,
everything()) %>%
select(-idRow) %>%
suppressMessages() %>%
select(-dplyr::matches("idSubsidiary"))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
}
is_font_table <-
page %>%
html_nodes('b') %>%
html_text() %>% length() == 0
if (is_font_table) {
all_data <-
1:10 %>%
future_map_dfr(function(x) {
css_selector <-
paste0('td:nth-child(', x, ')')
has_length <-
page %>%
html_nodes(css_selector) %>% length() > 0
if (has_length) {
item <-
paste0("X" , x)
value <-
page %>%
html_nodes(css_selector) %>%
html_text() %>%
str_trim()
tibble(item, value)
}
}) %>%
mutate(
value = value %>% str_to_upper() %>% str_replace_all('\n ', ' ') %>% str_replace_all('\u0096 ', '')
) %>%
filter(!value == '')
has_loc_key <-
all_data %>%
filter(value %in% locations) %>%
nrow() > 0
if (has_loc_key) {
loc_col <-
all_data %>%
filter(value %in% locations) %>%
.$item %>%
unique()
}
hit_terms_in <-
c(
"Organized",
"STATE OR|STATE OF|JURISDICTION OF|JURISDICTION OF INCORPORATION OR ORGANIZATION|JURISDICTION|JURISDICTION OF INCORPORATION OR\nORGANIZATION",
"NAME|ORGANIZED UNDER THE LAWS OF",
'STATE OF ORGANIZATION',
'STATE OR COUNTRY OF ORGANIZATION',
'NAME OF SUBSIDIARY',
'NAME',
'ENTITY NAME',
'the laws of',
'Percentage of voting',
'securities owned by',
'immediate parent',
'CERTAIN INTERMEDIARY SUBSIDIARIES',
'PERCENT OWNED'
)
hit_terms <-
hit_terms %>%
str_to_upper() %>%
paste0(collapse = '|')
hit_terms_in <-
hit_terms %>% str_split('\\|') %>%
flatten_chr()
has_pct_col <-
all_data %>%
filter(value %in% "100") %>%
nrow() > 0 |
(all_data %>% filter(value %>% str_detect('PERCENT')) %>% nrow() > 0)
if (has_pct_col) {
pct_col <-
all_data %>%
filter((value %in% "100") |
(value %>% str_detect("PERCENT"))) %>%
.$item %>%
unique() %>%
.[[1]]
}
all_data <-
all_data %>%
filter(!value %in% hit_terms_in) %>%
filter(!value %>% str_detect(hit_terms)) %>%
filter(!value == '') %>%
mutate(valueNC = value %>% nchar()) %>%
filter(!value %>% str_detect("PERCENT"))
if (!has_pct_col) {
all_data <-
all_data %>%
filter(valueNC > 3)
}
all_data <-
all_data %>%
select(-valueNC) %>%
group_by(item) %>%
mutate(idSubsidiary = 1:n()) %>%
spread(item, value) %>%
ungroup() %>%
dplyr::rename(nameSubsidiary = X1)
if (has_loc_key) {
names(all_data)[names(all_data) %in% loc_col] <-
'locationOrganizationSubsidiary'
}
if (has_pct_col) {
names(all_data)[names(all_data) %in% pct_col] <-
'pctSubsidiaryOwned'
all_data <-
all_data %>%
mutate(pctSubsidiaryOwned = pctSubsidiaryOwned %>% as.numeric() / 100)
}
all_data <-
all_data %>%
mutate(idCIK = cik,
dateSubsidiaryAsOf = NA,
urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary|^X"))
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(all_data)
}
df <-
page %>%
.parse_page_subsidiary_table_html() %>%
suppressWarnings()
df <-
df %>%
filter(!nameSubsidiary == '') %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary")) %>%
select(idCIK, everything())
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df %>% select(-dplyr::matches("idSubsidiary")))
}
.parse_sec_subsidiary_url_text <-
function(url = "https://www.sec.gov/Archives/edgar/data/899689/000104746903007996/a2104897zex-21.txt",
return_message = TRUE) {
cik <-
url %>%
.parse_sec_url_for_cik()
data <-
url %>%
read_lines()
data <-
data[!data == '']
has_s <-
data %>% str_detect("<S>") %>% sum() > 0
if (has_s) {
data <-
data[(data %>% grep("<S>", .) %>% .[[1]] + 1):length(data)]
}
data <-
data[!data %>% str_detect("STATE OF|NAME OF|---|NAME OF SUBSIDIARY|ORGANIZED UNDER|THE LAWS OF|<")]
data <-
data[data %>% nchar() > 3]
df <-
seq_along(data) %>%
future_map_dfr(function(x) {
item <-
data[[x]]
items <-
item %>%
str_replace_all('\\ ', '\\:') %>%
str_split('\\:') %>%
flatten_chr() %>%
str_trim() %>%
str_to_upper()
items <-
items[!items == '']
if (items %>% length() == 1) {
return(tibble())
}
two_items <-
items %>% length() == 2
if (two_items) {
table_data <-
tibble(
idSubsidiary = x,
nameSubsidiary = items[[1]],
locationOrganizationSubsidiary = items[[2]]
)
}
three_items <-
items %>% length() == 3
if (three_items) {
table_data <-
tibble(
idSubsidiary = x,
nameSubsidiary = items[[1]],
locationOrganizationSubsidiary = items[[2]],
pctSubsidiaryOwned = items[[3]] %>% as.numeric() / 100
)
}
table_data <-
table_data %>%
mutate(
isChildSubsidiary = ifelse(nameSubsidiary %>% substr(1, 1) == "-", TRUE, FALSE),
nameSubsidiary = nameSubsidiary %>% str_replace('\\-', '') %>% str_trim()
)
return(table_data)
}) %>%
mutate(idCIK = cik, urlSEC = url) %>%
select(-dplyr::matches("idSubsidiary")) %>%
select(idCIK,
nameSubsidiary,
locationOrganizationSubsidiary,
everything()) %>%
filter(!nameSubsidiary %in% c('NAME', 'ORGANIZED UNDER'))
df <-
df %>%
filter(!nameSubsidiary == '')
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
.parse_sec_subsidiary_url <-
function(url = "https://www.sec.gov/Archives/edgar/data/34088/000003408816000065/xomexhibit21.htm",
return_message = TRUE) {
is_text <-
url %>%
str_detect("txt")
is_html <-
url %>%
str_detect("html|htm")
parse_sec_subsidiary_url_text_safe <-
purrr::possibly(.parse_sec_subsidiary_url_text, tibble())
parse_sec_subsidiary_url_html_safe <-
purrr::possibly(.parse_sec_subsidiary_url_html, tibble())
if (is_text) {
data <-
url %>%
parse_sec_subsidiary_url_text_safe()
}
if (is_html) {
data <-
url %>%
parse_sec_subsidiary_url_html_safe()
}
data
} |
context("check_TF")
test_that("check_TF", {
expect_null(check_TF(TRUE))
expect_null(check_TF(FALSE))
mustBe <- NA
expect_error(check_TF(mustBe),
'`mustBe = NA` but must be TRUE or FALSE. Change `mustBe` to be TRUE or FALSE.')
mustBe <- 1
expect_error(check_TF(mustBe),
'`mustBe` was type double but must be logical. Change `mustBe` to be TRUE or FALSE.')
mustBe <- c(TRUE, FALSE)
expect_error(check_TF(mustBe),
'`mustBe` had length 2 but must be length-one. Change `mustBe` to be TRUE or FALSE.')
})
test_that("check_num1", {
expect_null(check_num1(1L))
expect_null(check_num1(1))
mm <- 1:5
expect_error(check_num1(mm),
"`mm` had length 5 but must be length-one.",
fixed = TRUE)
mm <- "mm"
expect_error(check_num1(mm),
"`mm` was type character",
fixed = TRUE)
mm <- NA_real_
expect_error(check_num1(mm),
"`mm = NA` but must be a non-missing numeric.",
fixed = TRUE)
}) |
ribbon3D <- function(x = seq(0, 1, length.out = nrow(z)),
y = seq(0, 1, length.out = ncol(z)),
z, ...,
colvar = z, phi = 40, theta = 40,
col = NULL, NAcol = "white", breaks = NULL,
border = NA, facets = TRUE,
colkey = NULL, resfac = 1,
image = FALSE, contour = FALSE, panel.first = NULL,
clim = NULL, clab = NULL, bty = "b",
lighting = FALSE, shade = NA, ltheta = -135, lphi = 0,
space = 0.4, along = "x",
curtain = FALSE, add = FALSE, plot = TRUE) {
plist <- initplist(add)
if (any(space > 0.9))
stop("'space' too large, should be smaller than or equal to 0.9")
else if (any(space < 0.1))
stop("'space' cannot be smaller than 0.1")
space <- rep(space, length.out = 2)
if (length(grep("x", along)) == 0 & length(grep("y", along)) == 0)
stop ("'along' should contain at least one of 'x' or 'y'")
if (! is.vector(x) & length(dim(x)) != 1)
stop("'x' should be a vector")
if (! is.vector(y) & length(dim(y)) != 1)
stop("'y' should be a vector")
if (length(x) != nrow(z))
stop("'x' should be of length = nrow(z)")
if (length(y) != ncol(z))
stop("'y' should be of length = ncol(z)")
if (any(resfac != 1)) {
res <- changeres(resfac, x, y, z, colvar)
x <- res$x ; y <- res$y ; z <- res$z
colvar <- res$colvar
}
rx <- range(x)
ry <- range(y)
if (length(grep("x", along)) > 0) {
dY <- 0.5*(1 - space[2]) * diff(y)
dY <- c(dY[1], dY, dY[length(dY)])
ry <- ry + c(- dY[1], dY[length(dY)])
}
if (length(grep("y", along)) > 0) {
dX <- 0.5*(1 - space[1]) * diff(x)
dX <- c(dX[1], dX, dX[length(dX)])
rx <- rx + c(- dX[1], dX[length(dX)])
}
dot <- splitdotpersp(list(...), bty, lighting,
rx, ry, z, plist = plist, shade, lphi, ltheta, breaks = breaks)
if (! is.matrix(x) & all(diff(x) < 0)) {
if (is.null(dot$persp$xlim))
dot$persp$xlim <- rev(range(x))
x <- rev(x)
if (ispresent(colvar))
colvar <- colvar[nrow(colvar):1, ]
z <- z[nrow(z):1, ]
}
if (! is.matrix(y) & all(diff(y) < 0)) {
if (is.null(dot$persp$ylim))
dot$persp$ylim <- rev(range(y))
y <- rev(y)
if (ispresent(colvar))
colvar <- colvar[, (ncol(colvar):1)]
z <- z[, (ncol(z):1)]
}
image <- check.args(image)
contour <- check.args(contour)
if (contour$add)
cv <- colvar
if (is.null(col) & is.null(breaks))
col <- jet.col(100)
else if (is.null(col))
col <- jet.col(length(breaks)-1)
breaks <- check.breaks(breaks,col)
CC <- check.colvar.2(colvar, z, col, clim, dot$alpha)
colvar <- CC$colvar
col <- CC$col
if (ispresent(colvar)) {
if (is.null(clim))
clim <- range(colvar, na.rm = TRUE)
if (dot$clog) {
colvar <- log(colvar)
clim <- log(clim)
}
iscolkey <- is.colkey(colkey, col)
if (iscolkey)
colkey <- check.colkey(colkey)
} else
iscolkey <- FALSE
rx <- range(x)
ry <- range(y)
if (is.null(plist)) {
do.call("perspbox", c(alist(x = range(x), y = range(y),
z = range(z, na.rm = TRUE),
phi = phi, theta = theta, plot = plot, colkey = colkey, col = col),
dot$persp))
plist <- getplist()
}
if (is.function(panel.first))
panel.first(plist$mat)
shade <- dot$shade$shade
if (is.null(dot$shade$shade))
dot$shade$shade <- NA
Nx <- dim(z) [1]
Ny <- dim(z) [2]
lwd <- dot$points$lwd
if (is.null(lwd))
lwd <- 1
lty <- dot$points$lty
if (is.null(lty))
lty <- 1
Poly <- list(x = NULL, y = NULL, col = NULL, border = NULL,
lwd = NULL, lty = NULL,
img = NULL, alpha = NULL, proj = NULL)
zmin <- min(plist$zlim[1], min(z, na.rm = TRUE))
if (curtain & zmin == min(z, na.rm = TRUE))
zmin <- as.double(zmin - diff(range(plist$zlim)) * 1e-6)
if (length(grep("x", along)) > 0) {
X <- cbind(x, x)
for (i in 1 : Ny) {
ind <- length(Poly$col) + 1
Y <- cbind(rep(y[i]+dY[i+1], Nx), rep(y[i]-dY[i], Nx))
Poly <- add.poly(Poly, X, Y, cbind(z[,i], z[,i]),
colvar[,i], col, NAcol, breaks,
clim, facets, border)
if (curtain) {
Poly <- add.poly(Poly, X,
cbind(rep(y[i]-dY[i], Nx), rep(y[i]-dY[i], Nx)),
cbind(rep(zmin, Nx), z[,i]), colvar[,i],
col, NAcol, breaks, clim, facets, border)
Poly <- add.poly(Poly, X,
cbind(rep(y[i]+dY[i+1], Nx), rep(y[i]+dY[i+1], Nx)),
cbind(rep(zmin, Nx), z[,i]), colvar[,i],
col, NAcol, breaks, clim, facets, border)
ye1 <- y[i]-dY[i]
ye2 <- y[i]+dY[i+1]
Poly <-
list(x = cbind(Poly$x, c(x[1], x[1], x[1], x[1], NA)),
y = cbind(Poly$y, c(ye1, ye2, ye2, ye1, NA)),
z = cbind(Poly$z, c(zmin, zmin, z[1,i], z[1,i], NA)),
col = c(Poly$col, Poly$col[ind]),
border = c(Poly$border, Poly$border[ind]),
img = Poly$img)
ind <- length(Poly$col)
Poly <-
list(x = cbind(Poly$x, c(x[Nx], x[Nx], x[Nx], x[Nx], NA)),
y = cbind(Poly$y, c(ye1, ye2, ye2, ye1, NA)),
z = cbind(Poly$z, c(zmin, zmin, z[Nx,i], z[Nx,i], NA)),
col = c(Poly$col, Poly$col[ind]),
border = c(Poly$border, Poly$border[ind]),
img = Poly$img)
}
}
}
if (length(grep("y", along)) > 0) {
Y <- cbind(y, y)
for (i in 1 : Nx) {
ind <- length(Poly$col) + 1
X <- cbind(rep(x[i]+dX[i+1], Ny), rep(x[i]-dX[i], Ny))
Poly <- add.poly(Poly, X, Y, cbind(z[i,], z[i,]),
colvar[i,], col, NAcol, breaks,
clim, facets, border)
if (curtain) {
Poly <- add.poly(Poly,
cbind(rep(x[i]-dX[i], Ny), rep(x[i]-dX[i], Ny)), Y,
cbind(rep(zmin, Ny), z[i,]), colvar[i,],
col, NAcol, breaks, clim, facets, border)
Poly <- add.poly(Poly,
cbind(rep(x[i]+dX[i+1], Ny), rep(x[i]+dX[i+1], Ny)), Y,
cbind(rep(zmin, Ny), z[i,]), colvar[i,],
col, NAcol, breaks, clim, facets, border)
xe1 <- x[i]-dX[i]
xe2 <- x[i]+dX[i+1]
Poly <-
list(x = cbind(Poly$x, c(xe1, xe2, xe2, xe1, NA)),
y = cbind(Poly$y, c(y[1], y[1], y[1], y[1], NA)),
z = cbind(Poly$z, c(zmin, zmin, z[i,1], z[i,1], NA)),
col = c(Poly$col, Poly$col[ind]),
border = c(Poly$border, Poly$border[ind]),
img = Poly$img)
ind <- length(Poly$col)
Poly <-
list(x = cbind(Poly$x, c(xe1, xe2, xe2, xe1, NA)),
y = cbind(Poly$y, c(y[Ny], y[Ny], y[Ny], y[Ny], NA)),
z = cbind(Poly$z, c(zmin, zmin, z[i,Ny], z[i,Ny], NA)),
col = c(Poly$col, Poly$col[ind]),
border = c(Poly$border, Poly$border[ind]),
img = Poly$img)
}
}
}
alpha <- dot$alpha; if (is.null(alpha)) alpha <- NA
Poly$alpha <- rep(alpha, length.out = length(Poly$col))
if (! dot$shade$type == "none")
Poly <- color3D(Poly, plist$scalefac, dot$shade, lighting)
Poly$proj <- project(colMeans(Poly$x, na.rm = TRUE),
colMeans(Poly$y, na.rm = TRUE),
colMeans(Poly$z, na.rm = TRUE), plist)
Poly$lwd <- rep(lwd , length.out = length(Poly$col))
Poly$lty <- rep(lty , length.out = length(Poly$col))
Poly$isimg <- rep(0 , length.out = length(Poly$col))
class(Poly) <- "poly"
if (image$add)
Poly <- XYimage (Poly, image, x, y, z, plist, col, breaks = breaks)
if (contour$add)
segm <- contourfunc(contour, x, y, z, plist, cv, clim)
else
segm <- NULL
if (iscolkey)
plist <- plistcolkey(plist, colkey, col, clim, clab, dot$clog,
type = "ribbon3D", breaks = breaks)
plist <- plot.struct.3D(plist, poly = Poly, segm = segm, plot = plot)
setplist(plist)
invisible(plist$mat)
} |
nse_stock_most_traded <- function(clean_names = TRUE) {
url <- "https://www1.nseindia.com/products/dynaContent/equities/equities/json/mostActiveMonthly.json"
url %>%
nse_base() %>%
nse_format_num(1, 2:6) %>%
nse_format(1, 2:6) -> result
if (clean_names) {
names(result) <- c("security", "share_turnover", "traded_quantity",
"no_of_trades", "avg_daily_turnonver", "turnover")
}
result
}
NULL
nse_stock_year_high <- function(clean_names = TRUE) {
url <- "https://www1.nseindia.com/products/dynaContent/equities/equities/json/online52NewHigh.json"
result <- nse_stock_year_base(url)
if (clean_names) {
names(result) <- c("symbol", "symbol_desc", "date", "new_high", "year",
"last_traded_price", "prev_high", "prev_close", "change",
"percent_change")
}
result
}
nse_stock_year_low <- function(clean_names = TRUE) {
url <- "https://www1.nseindia.com/products/dynaContent/equities/equities/json/online52NewLow.json"
result <- nse_stock_year_base(url)
if (clean_names) {
names(result) <- c("symbol", "symbol_desc", "date", "new_low", "year",
"last_traded_price", "prev_low", "prev_close", "change",
"percent_change")
}
result
}
nse_stock_code <- function(clean_names = TRUE) {
url <- "https://www1.nseindia.com/content/equities/EQUITY_L.csv"
url %>%
utils::read.csv() %>%
magrittr::extract(., 1:2) %>%
lapply(as.character) %>%
as.data.frame() -> result
if (clean_names) {
names(result) <- c("symbol", "company")
}
result
}
nse_stock_valid <- function(stock_code) {
valid_stock <- nse_stock_code()[[1]]
toupper(stock_code) %in% valid_stock
}
NULL
nse_stock_top_gainers <- function(clean_names = TRUE) {
url <- "https://www1.nseindia.com/live_market/dynaContent/live_analysis/gainers/niftyGainers1.json"
nse_fo_base(url, clean_names)
}
nse_stock_top_losers <- function(clean_names = TRUE) {
url <- "https://www1.nseindia.com/live_market/dynaContent/live_analysis/losers/niftyLosers1.json"
nse_fo_base(url, clean_names)
}
nse_stock_quote <- function(stock_code, source = c("yahoo", "rediff")) {
source_type <- match.arg(source)
if (nse_stock_valid(stock_code)) {
is_spec <- grepl("[-&]", stock_code)
if (is_spec) {
pos_spec <- regexpr("[-&]", stock_code)
pos_sym <- substr(stock_code, pos_spec, pos_spec)
split_code <- unlist(strsplit(stock_code, pos_sym))
stock_code <- paste0(split_code[1], "%", charToRaw(pos_sym), split_code[2])
}
if (source_type == "yahoo") {
nse_stock_quote_yahoo(stock_code)
} else {
nse_stock_quote_rediff(stock_code)
}
} else {
stop("Please check the stock code. \n Use nse_stock_code() to fetch stock symbol from NSE \n and nse_stock_valid() to check if stock code is valid. ", call. = FALSE)
}
} |
tar_prune <- function(
callr_function = callr::r,
callr_arguments = targets::callr_args_default(callr_function),
envir = parent.frame(),
script = targets::tar_config_get("script"),
store = targets::tar_config_get("store")
) {
force(envir)
tar_assert_callr_function(callr_function)
tar_assert_list(callr_arguments)
path_scratch_del(store)
out <- callr_outer(
targets_function = tar_prune_inner,
targets_arguments = list(path_store = store),
callr_function = callr_function,
callr_arguments = callr_arguments,
envir = envir,
script = script,
store = store,
fun = "tar_prune"
)
invisible(out)
}
tar_prune_inner <- function(pipeline, path_store) {
tar_assert_store(path_store)
names <- pipeline_get_names(pipeline)
meta <- meta_init(path_store = path_store)
data <- meta$database$read_condensed_data()
imports <- data$name[data$type %in% c("function", "object")]
children <- unlist(data$children[data$name %in% names])
children <- unique(children[!is.na(children)])
keep <- c(names, children, imports)
discard <- setdiff(data$name, keep)
dynamic_files <- data$name[data$format == "file"]
discard <- setdiff(discard, dynamic_files)
data <- as_data_frame(data)[data$name %in% keep, ]
meta$database$overwrite_storage(data)
unlink(file.path(path_objects_dir(path_store), discard), recursive = TRUE)
invisible()
} |
str_order <- function(x,
decreasing = FALSE,
na_last = TRUE,
locale = "en",
numeric = FALSE,
...) {
opts <- stri_opts_collator(locale, numeric = numeric, ...)
stri_order(x,
decreasing = decreasing,
na_last = na_last,
opts_collator = opts
)
}
str_rank <- function(x,
locale = "en",
numeric = FALSE,
...) {
opts <- stri_opts_collator(locale, numeric = numeric, ...)
stri_rank(x,
opts_collator = opts
)
}
str_sort <- function(x,
decreasing = FALSE,
na_last = TRUE,
locale = "en",
numeric = FALSE,
...) {
opts <- stri_opts_collator(locale, numeric = numeric, ...)
stri_sort(x,
decreasing = decreasing,
na_last = na_last,
opts_collator = opts
)
} |
adapt_parameters <-
function(data=stop("Datasets is mandatory for this function"), parameters=stop("Set of parameters is mandatory for this function")) {
x <- names(parameters)
x <- gsub("^Max_", "", x)
x <- gsub("^Peak_", "", x)
x <- gsub("^Min_", "", x)
x <- gsub("^MinB_", "", x)
x <- gsub("^MinE_", "", x)
y <- names(data)
y <- c(y, "Peak", "Length", "LengthB", "LengthE", "Begin", "End", "Phi", "Delta", "Alpha", "Beta", "Tau",
"PMin", "PMinB", "PMinE",
"Phi1", "Delta1", "Alpha1", "Beta1", "Tau1",
"Phi2", "Delta2", "Alpha2", "Beta2", "Tau2", "Theta")
parred <- NULL
for (i in 1:length(y)) {
parred <- c(parred, parameters[x==y[i]])
}
return(parred)
} |
d2r <- function(deg) pi/180 * deg
|
getMCerror <- function(object, n.chains, SDpc=FALSE) {
mcmcOutput::getMCE(x=object, pc=SDpc, bad=NA, sort=FALSE)
} |
recombination_bin <- function(X, M, recpars) {
if (!assertthat::has_name(recpars, "minchange")) recpars$minchange <- TRUE
assertthat::assert_that(is.matrix(X), is.numeric(X),
is.matrix(M), is.numeric(M),
assertthat::are_equal(dim(X), dim(M)),
assertthat::has_name(recpars, "cr"),
is.numeric(recpars$cr),
is_within(recpars$cr, 0, 1),
assertthat::is.flag(recpars$minchange))
R <- randM(X) < recpars$cr
if (recpars$minchange){
indx <- which(rowSums(R) == 0)
cor.mat <- cbind(indx,
sample.int(n = ncol(X),
size = length(indx),
replace = TRUE))
R[cor.mat[,1],cor.mat[,2]] <- TRUE
}
return(R*M + (1 - R)*X)
} |
.runThisTest <- Sys.getenv("RunAllggeffectsTests") == "yes"
if (.runThisTest) {
if (suppressWarnings(
require("testthat") &&
require("rstanarm") &&
require("ggeffects")
)) {
x <- rnorm(30, 0)
b <- runif(2)
s <- ifelse(diag(2) == 0, 0.23, 1)
er <- cbind(rnorm(30, 0, s), rnorm(30, 0, s))
y <- apply(t(b), 2, `*`, x) + er
d <- data.frame(y1 = y[,1], y2 = y[,2], x)
d$group <- sample(c("a", "b", "c"), size = nrow(d), replace = TRUE)
m1 <- suppressWarnings(rstanarm::stan_mvmer(
list(
y1 ~ x + (1 | group),
y2 ~ x + (1 | group)
),
data = d,
chains = 2,
iter = 500,
refresh = 0
))
m2 <- suppressWarnings(rstanarm::stan_glm(y1 ~ x, data = d, chains = 2, iter = 500, refresh = 0))
test_that("ggpredict, rstanarm-ppd", {
expect_s3_class(ggpredict(m1, ppd = TRUE), "ggalleffects")
expect_s3_class(ggpredict(m1, "x", ppd = TRUE), "data.frame")
expect_s3_class(ggpredict(m2, ppd = TRUE), "ggalleffects")
expect_s3_class(ggpredict(m2, "x", ppd = TRUE), "data.frame")
})
test_that("ggpredict, rstanarm-ppd", {
expect_error(ggpredict(m1, ppd = FALSE))
expect_error(ggpredict(m1, "x", ppd = FALSE))
expect_s3_class(ggpredict(m2, ppd = FALSE), "ggalleffects")
expect_s3_class(ggpredict(m2, "x", ppd = FALSE), "data.frame")
})
}
} |
html_document_base <- function(theme = NULL,
self_contained = TRUE,
lib_dir = NULL,
mathjax = "default",
pandoc_args = NULL,
template = "default",
dependency_resolver = NULL,
copy_resources = FALSE,
extra_dependencies = NULL,
css = NULL,
bootstrap_compatible = FALSE,
...) {
if (is.null(dependency_resolver))
dependency_resolver <- html_dependency_resolver
args <- c()
if (self_contained) {
if (copy_resources)
stop("Local resource copying is incompatible with self-contained documents.")
validate_self_contained(mathjax)
args <- c(args, "--self-contained")
}
args <- c(args, pandoc_args)
preserved_chunks <- character()
output_dir <- ""
theme <- resolve_theme(theme)
old_theme <- NULL
pre_knit <- function(input, ...) {
if (is_bs_theme(theme)) {
for (f in css) theme <<- bslib::bs_add_rules(theme, xfun::read_utf8(f))
css <<- NULL
old_theme <<- bslib::bs_global_set(theme)
}
}
post_knit <- function(metadata, input_file, runtime, ...) {}
on_exit <- function() {
if (is_bs_theme(theme)) bslib::bs_global_set(old_theme)
}
pre_processor <- function(metadata, input_file, runtime, knit_meta,
files_dir, output_dir) {
args <- c()
if (is.null(lib_dir))
lib_dir <<- files_dir
output_dir <<- output_dir
if (!is.null(theme)) {
theme_arg <- if (is.list(theme)) "bootstrap" else theme
args <- c(args, pandoc_variable_arg("theme", theme_arg))
}
for (f in css) {
if (grepl("\\.s[ac]ss$", f)) {
if (!xfun::loadable("sass")) {
stop2("Using `.sass` or `.scss` file in `css` argument requires the sass package.")
}
f <- sass::sass(
sass::sass_file(f),
output = sass::output_template(
basename = xfun::sans_ext(basename(f)),
dirname = "sass",
path = lib_dir
),
options = sass::sass_options(output_style = "compressed")
)
f <- normalized_relative_to(output_dir, f)
}
args <- c(args, "--css", pandoc_path_arg(f, backslash = FALSE))
}
format_deps <- list()
format_deps <- append(format_deps, html_dependency_header_attrs())
if (!is.null(theme)) {
format_deps <- append(format_deps, list(html_dependency_jquery()))
if (is_bs_theme(theme)) {
theme <- bslib::bs_global_get()
}
bootstrap_deps <- if (is_bs_theme(theme) && is_shiny(runtime, metadata[["server"]])) {
list(shiny_bootstrap_lib(theme))
} else {
bootstrap_dependencies(theme)
}
format_deps <- append(format_deps, htmltools::resolveDependencies(bootstrap_deps))
}
else if (isTRUE(bootstrap_compatible) && is_shiny(runtime, metadata[["server"]])) {
format_deps <- append(format_deps, bootstrap_dependencies("bootstrap"))
}
format_deps <- append(format_deps, extra_dependencies)
extras <- html_extras_for_document(knit_meta, runtime, dependency_resolver,
format_deps)
args <- c(args, pandoc_html_extras_args(extras, self_contained, lib_dir,
output_dir))
args <- c(args, pandoc_mathjax_args(mathjax,
template,
self_contained,
lib_dir,
output_dir))
preserved_chunks <<- extract_preserve_chunks(input_file)
args
}
intermediates_generator <- function(original_input, intermediates_dir) {
copy_render_intermediates(original_input, intermediates_dir, !self_contained)
}
post_processor <- function(metadata, input_file, output_file, clean, verbose) {
output_str <- read_utf8(output_file)
s1 <- '<span class="sc">|</span><span class="er">></span>'
s2 <- '<span class="ot">=</span><span class="er">></span>'
if ((length(preserved_chunks) == 0 && !isTRUE(copy_resources) && self_contained) &&
!length(c(grep(s1, output_str, fixed = TRUE), grep(s2, output_str, fixed = TRUE))))
return(output_file)
if (length(preserved_chunks) > 0) {
for (i in names(preserved_chunks)) {
output_str <- gsub(paste0("<p>", i, "</p>"), i, output_str,
fixed = TRUE, useBytes = TRUE)
output_str <- gsub(paste0(' id="[^"]*?', i, '[^"]*?" '), ' ', output_str,
useBytes = TRUE)
}
output_str <- restorePreserveChunks(output_str, preserved_chunks)
}
if (copy_resources) {
output_str <- copy_html_resources(one_string(output_str), lib_dir, output_dir)
} else if (!self_contained) {
image_relative <- function(img_src, src) {
in_file <- utils::URLdecode(src)
if (grepl('^[.][.]', in_file)) return(img_src)
if (length(in_file) && file.exists(in_file)) {
img_src <- sub(
src, utils::URLencode(normalized_relative_to(output_dir, in_file)),
img_src, fixed = TRUE)
}
img_src
}
output_str <- process_images(output_str, image_relative)
}
output_str <- gsub(s1, '<span class="sc">|></span>', output_str, fixed = TRUE)
output_str <- gsub(s2, '<span class="ot">=></span>', output_str, fixed = TRUE)
write_utf8(output_str, output_file)
output_file
}
if (!is.null(theme)) {
bs3 <- identical("3", theme_version(theme))
args <- c(args, pandoc_variable_arg("bs3", bs3))
}
output_format(
knitr = NULL,
pandoc = pandoc_options(
to = "html", from = NULL, args = args,
lua_filters = pkg_file_lua(c("pagebreak.lua", "latex-div.lua"))
),
keep_md = FALSE,
clean_supporting = FALSE,
pre_knit = pre_knit,
post_knit = post_knit,
on_exit = on_exit,
pre_processor = pre_processor,
intermediates_generator = intermediates_generator,
post_processor = post_processor
)
}
extract_preserve_chunks <- function(input_file, extract = extractPreserveChunks) {
input_str <- read_utf8(input_file)
preserve <- extract(input_str)
if (!identical(preserve$value, input_str)) write_utf8(preserve$value, input_file)
preserve$chunks
} |
context("summary.pcadata")
test_that("correct info about class structure", {
data = read.morphodata("../testFiles/samplePlnaMatica.txt")
pcaRes = pca.calc(data)
output = capture.output(summary(pcaRes))
expect_equal(output[1], "Object of class 'pcadata'; storing results of principal component analysis")
}) |
context("latex table structure")
test_that("white spaces are protected", {
ft <- flextable(data.frame(x = ""))
ft <- delete_part(ft, part = "header")
ft <- mk_par(ft, 1, 1, as_paragraph("foo", " ", "bar"))
str <- flextable:::latex_str(ft)
expect_true(grepl("{\\ }", str, fixed = TRUE))
}) |
subdata<-
function(xx,sg){
m<-nrow(xx)
data<-xx[with(xx,order(Gene)),]
gm<-table(data$Gene)
gm<-gm[gm>0]
gn<-length(gm)
gg<-rep(0,m)
a<-0
for(i in seq(gn)){
for(j in seq(gm[i])){
a<-a+1
gg[a]<-gm[i]
}
}
data<-cbind(as.data.frame(data),gg)
if(sg==1){
x<-subset(data,data$gg==1)
}else{
x<-subset(data,data$gg>1)
}
nc<-ncol(x)
x<-x[,-nc]
return(x)
} |
fred_category <- function(..., key=NULL){
if (is.null(key)) key <- .use_default_key()
ids <- as.character(Reduce(c, list(...)))
.loop_general_rbind(ids, .fred_category, key, "")
}
fred_category_children <- function(..., key=NULL, realtime_start=NULL, realtime_end=NULL){
if (is.null(key)) key <- .use_default_key()
realtime <- .real_parse(realtime_start, realtime_end)
ids <- as.character(Reduce(c, list(...)))
.loop_general_rbind(ids, .fred_category_children, key, realtime)
}
fred_category_related <- function(..., key=NULL, realtime_start=NULL, realtime_end=NULL){
if (is.null(key)) key <- .use_default_key()
realtime <- .real_parse(realtime_start, realtime_end)
ids <- as.character(Reduce(c, list(...)))
.loop_general_rbind(ids, .fred_category_related, key, realtime)
}
fred_category_series <- function(..., key=NULL, args = list()){
if (is.null(key)) key <- .use_default_key()
other <- .args_parse(args)
ids <- as.character(Reduce(c, list(...)))
.loop_general_rbind(ids, .fred_category_series, key, other)
}
fred_category_tags <- function(..., key=NULL, args = list()){
if (is.null(key)) key <- .use_default_key()
other <- .args_parse(args)
ids <- as.character(Reduce(c, list(...)))
.loop_general_rbind(ids, .fred_category_tags, key, other)
}
fred_category_related_tags <- function(..., key=NULL, args = list()){
if (is.null(key)) key <- .use_default_key()
other <- .args_parse(args)
ids <- as.character(Reduce(c, list(...)))
.loop_general_rbind(ids, .fred_category_related_tags, key, other)
} |
NULL
if (getRversion() >= "2.15.1") utils::globalVariables(c(".")) |
"difshannonbio" <-
function(dat1,dat2,R=1000,probs=c(0.025,0.975)){
myboot1<-boot(dat1,function(dat1,i) shannonbio(dat1[i,]),R=R)
myboot2<-boot(dat2,function(dat1,i) shannonbio(dat1[i,]),R=R)
differ<-myboot1$t-myboot2$t
x<-quantile(differ[,1],probs=probs)
y<-quantile(differ[,2],probs=probs)
return(list(deltaH=x,deltaJ=y))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.