blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
327
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
91
| license_type
stringclasses 2
values | repo_name
stringlengths 5
134
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 46
values | visit_date
timestamp[us]date 2016-08-02 22:44:29
2023-09-06 08:39:28
| revision_date
timestamp[us]date 1977-08-08 00:00:00
2023-09-05 12:13:49
| committer_date
timestamp[us]date 1977-08-08 00:00:00
2023-09-05 12:13:49
| github_id
int64 19.4k
671M
⌀ | star_events_count
int64 0
40k
| fork_events_count
int64 0
32.4k
| gha_license_id
stringclasses 14
values | gha_event_created_at
timestamp[us]date 2012-06-21 16:39:19
2023-09-14 21:52:42
⌀ | gha_created_at
timestamp[us]date 2008-05-25 01:21:32
2023-06-28 13:19:12
⌀ | gha_language
stringclasses 60
values | src_encoding
stringclasses 24
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 7
9.18M
| extension
stringclasses 20
values | filename
stringlengths 1
141
| content
stringlengths 7
9.18M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9d32b5c3643743c353d9bb8823c333fc23ef0942
|
912886d0fe7a726f4946ef38395a5bfbf9e58f13
|
/R/cv.gsvcm.R
|
93073fdaba82bee74c185b27a2fa05f6e13eecdf
|
[] |
no_license
|
FIRST-Data-Lab/gsvcm
|
533f31bbfa5d53471f1c3e2d2ece6aac043055b1
|
afa07506d94fee523b9db623ad747bf03fdc3914
|
refs/heads/master
| 2022-07-04T10:04:37.039922
| 2020-05-08T17:57:16
| 2020-05-08T17:57:16
| 262,356,872
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,037
|
r
|
cv.gsvcm.R
|
#' k-fold cross-validation MSPE for generalized spatially varying coefficient regression
#'
#' \code{cv.gsvcm} implements k-fold cross-validation MSPE for generalized spartially varying coefficient regression, and returns the mean squared prediction error (MSPE).
#'
#' @importFrom BPST basis
#' @param y The response of dimension \code{n} by one, where \code{n} is the number of observations.
#' \cr
#' @param X The design matrix of dimension \code{n} by \code{p}, with an intercept. Each row is an observation vector.
#' \cr
#' @param S The cooridinates of dimension \code{n} by two. Each row is the coordinates of an observation.
#' \cr
#' @param V The \code{N} by two matrix of vertices of a triangulation, where \code{N} is the number of vertices. Each row is the coordinates for a vertex.
#' \cr
#' @param Tr The triangulation matrix of dimention \code{nT} by three, where \code{nT} is the number of triangles in the triangulation. Each row is the indices of vertices in \code{V}.
#' \cr
#' @param d The degree of piecewise polynomials -- default is 2.
#' \cr
#' @param r The smoothness parameter -- default is 1, and 0 \eqn{\le} \code{r} \eqn{<} \code{d}.
#' \cr
#' @param lambda The vector of the candidates of penalty parameter -- default is grid points of 10 to the power of a sequence from -6 to 6 by 0.5.
#' \cr
#' @param family The family object, specifying the distribution and link to use.
#' \cr
#' @param off offset -- default is 0.
#' \cr
#' @param r.theta The endpoints of an interval to search for an additional parameter \code{theta} for negative binomial scenario -- default is c(2,8).
#' \cr
#' @param nfold The number of folds -- default is 10. Although \code{nfold} can be as large as the sample size (leave-one-out CV), it is not recommended for large datasets. Smallest value allowable for \code{nfolds} is 3.
#' \cr
#' @param initial The seed used for cross-validation sample -- default is 123.
#' \cr
#' @param eps.sigma Error tolerance for the Pearson estimate of the scale parameter, which is as close as possible to 1, when estimating an additional parameter \code{theta} for negative binomial scenario -- default is 0.01.
#' \cr
#' @param method GSVCM or GSVCMQR. GSVCM is based on Algorithm 1 in Subsection 3.1 and GSVCMQR is based on Algorithm 2 in Subsection 3.2 -- default is GSVCM.
#' \cr
#' @param Cp TRUE or FALSE. There are two modified measures based on the QRGSVCM method for smoothness parameters in the manuscript. TRUE is for Cp measure and FALSE is for GCV measure.
#' \cr
#' @return The k-fold cross-validation (CV) mean squared prediction error (MSPE).
#' \cr
#' @details This R package is the implementation program for manuscript entitled "Generalized Spatially Varying Coefficinet Models" by Myungjin Kim and Li Wang.
#' @examples
#' # See an example of fit.gsvcm.
#' @export
#'
cv.gsvcm =
function(y, X, S, V, Tr, d = 2, r = 1, lambda = 10^seq(-6, 6, by = 0.5),
family, off = 0, r.theta = c(2, 8), nfold = 10, initial = 123, eps.sigma = 0.01, method = "GSVCM", Cp =TRUE)
{
linkinv = family$linkinv;
if(nfold < 3){
warning("The number of folds in CV is too small. Instead, the default 10-fold CV is used.")
nfold = 10
}
if(!is.matrix(X)){
warning("The explanatory variable, X, should be a matrix.")
X = as.matrix(X)
}
if(!is.matrix(S)){
warning("The coordinates, S, should be a matrix.")
S = as.matrix(S)
}
Ball = basis(V, Tr, d, r, S)
K = Ball$K
Q2 = Ball$Q2
B = Ball$B
ind.inside = Ball$Ind.inside
tria.all = Ball$tria.all
BQ2 = B %*% Q2
P = t(Q2) %*% K %*% Q2
y = y[ind.inside]
X = X[ind.inside, ]
S = S[ind.inside, ]
n = length(y)
sfold = round(n / nfold)
set.seed(initial)
Test = sample(1:n)
cv.error = c()
for(ii in 1:nfold){
if(ii < nfold){
Test.set = sort(Test[((ii - 1) * sfold + 1):(ii * sfold)])
}
if(ii == nfold){
Test.set = sort(Test[((ii - 1) * sfold + 1):n])
}
Train.set = setdiff(1:n, Test.set)
# Consider univariate case.
if(is.vector(X) == 1){
X.test = as.matrix(X[Test.set])
X.train = as.matrix(X[Train.set])
} else {
X.test = X[Test.set, ]
X.train = X[Train.set, ]
}
B.test = B[Test.set, ]
B.train = B[Train.set, ]
BQ2.test = BQ2[Test.set, ]
BQ2.train = BQ2[Train.set, ]
y.test = y[Test.set]
y.train = y[Train.set]
if(method == "GSVCM"){
mfit.ii = gsvcm.est(y.train, X.train, BQ2.train, P, lambda, family, off, r.theta, eps.sigma)
} else if (method =="GSVCMQR"){
mfit.ii = gsvcm.est.qr(y.train, X.train, BQ2.train, P, lambda, family, off, r.theta, eps.sigma, Cp)
}
W.test = as.matrix(kr(X.test, BQ2.test, byrow = TRUE))
eta = W.test %*% as.vector(mfit.ii$theta_hat)
ypred.ii = linkinv(eta)
pred.error = mean((y.test - ypred.ii)^2)
cv.error = c(cv.error, pred.error)
}
return(cv.error)
}
|
041cb1c4e7edea389dacfaa56902cd6d3a361bb0
|
e321702ba009728989416776a51628382542af5f
|
/R/readOpenArray.R
|
5d83aff30ab5ed4d8df4c11736a53bf075b80d3c
|
[] |
no_license
|
alexbaras/openArray
|
306c3fd749248555dec2ad1be97dd21766b1e46a
|
7087ce105eeffff2900e8f5ed1cc03ae01ef2629
|
refs/heads/master
| 2021-01-09T07:42:38.937269
| 2014-08-29T17:18:37
| 2014-08-29T17:18:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,063
|
r
|
readOpenArray.R
|
readOpenArray <- function(filename, fileFormat="default") {
# read in raw data table
if (fileFormat=="default") {
d <- read.table(filename, header=TRUE, dec=".", sep=",", comment.char="")
} else if (fileFormat=="LifeTech") {
d <- read.table(filename, skip=15, header=TRUE, dec=".", sep=",", comment.char="")
names(d)[names(d)=="Barcode"] <- "Chip.Id"
names(d)[names(d)=="Well"] <- "Chip.Well"
d[,c("Sample.Id","Feature.Set")] <- read.table(text=as.character(d$Sample.Name),sep='_')
names(d)[names(d)=="Target.Name"] <- "Feature.Id"
names(d)[names(d)=="Cycle.Number"] <- "Cycle"
names(d)[names(d)=="Rn"] <- "Value"
} else {
stop("Error: Input file format not recognized.")
}
d = d[,c("Chip.Id","Chip.Well","Sample.Id","Feature.Set","Feature.Id","Cycle","Value")];
#Some basic error check
if(is.null(d$Value)){
stop("Error: You must have a Value column for the raw fluorescence values.");
}
d = split(d,paste(d$Chip.Id,d$Chip.Well,d$Sample.Id,d$Feature.Set,d$Feature.Id,sep="::"))
return(d)
}
|
19c9c4d0acf640d422296d207f08e60fe689bc86
|
98a24df7b9453c2045376ef2114bf6af09a50418
|
/sandbox/parallel-evaluation/hcsb-05-script-tpf-par.R
|
6982d177bce2bf2d47de7ad5d53d00806735130e
|
[
"CC-BY-4.0"
] |
permissive
|
sdufault15/case-only-crtnd
|
35fe7819bffe4e426c8062c31b683615a630462c
|
dc5b5865de1452664a29828d25431225b2381877
|
refs/heads/master
| 2021-08-27T16:46:17.872236
| 2021-08-24T21:42:36
| 2021-08-24T21:42:36
| 149,684,299
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,887
|
r
|
hcsb-05-script-tpf-par.R
|
###############################
# Suzanne Dufault
# All HCSB runs for Test-Postive Fraction and Random Effects
# October 9, 2018
# Sequential
###############################
load("Random10000Allocations.RData")
dta <- subset(Random10000Allocations, select = -X)
source("lib/txtSetFunction.R")
source("lib/quadraticFunction.R")
source("lib/hcsb-tpf-function-par.R")
period1 <- c("03_05", "05_06", "06_07", "07_08", "08_10", "10_11", "11_12", "12_13", "13_14")
library(doParallel)
cl <- makeCluster(8)
registerDoParallel(cl)
# High HCSB (50%)
rr1h.tpf <- foreach(per = period1, .combine = "rbind") %dopar% {hcsb_tpf_function(data = dta, period = per, n.obs.pos = 1000, n.obs.neg = 1000, lambda.int = 1, lambda.hcsb = 0.5)}
save(rr1h.tpf, file = "case-only-comparison/par-tpf-comp-rr1-hcsb-HIGH-1082018.RData")
rr6h.tpf <- foreach(per = period1, .combine = "rbind") %dopar% {hcsb_tpf_function(data = dta, period = per, n.obs.pos = 1000, n.obs.neg = 1000, lambda.int = 0.6, lambda.hcsb = 0.5)}
save(rr6h.tpf, file = "case-only-comparison/par-tpf-comp-rr6-hcsb-HIGH-1082018.RData")
rr5h.tpf <- foreach(per = period1, .combine = "rbind") %dopar% {hcsb_tpf_function(data = dta, period = per, n.obs.pos = 1000, n.obs.neg = 1000, lambda.int = 0.5, lambda.hcsb = 0.5)}
save(rr5h.tpf, file = "case-only-comparison/par-tpf-comp-rr5-hcsb-HIGH-1082018.RData")
rr4h.tpf <- foreach(per = period1, .combine = "rbind") %dopar% {hcsb_tpf_function(data = dta, period = per, n.obs.pos = 1000, n.obs.neg = 1000, lambda.int = 0.4, lambda.hcsb = 0.5)}
save(rr4h.tpf, file = "case-only-comparison/par-tpf-comp-rr4-hcsb-HIGH-1082018.RData")
rr3h.tpf <- foreach(per = period1, .combine = "rbind") %dopar% {hcsb_tpf_function(data = dta, period = per, n.obs.pos = 1000, n.obs.neg = 1000, lambda.int = 0.3, lambda.hcsb = 0.5)}
save(rr3h.tpf, file = "case-only-comparison/par-tpf-comp-rr3-hcsb-HIGH-1082018.RData")
|
da2d1c3a751fb0e08e2f40e3c844826def1af085
|
1dda40f8a1956e68ebbe4cda8f51dd73635f23cc
|
/R/highlightHTMLmaster.r
|
62aa05719369fa7a0d4880792e1e40493b1ea7ce
|
[] |
no_license
|
cran/highlightHTML
|
b99f13528ef90dc18a2a9f1145e90cef54a366be
|
3c17dd0bc47741be6ebb9da44af5d1a2264e9a88
|
refs/heads/master
| 2021-01-13T04:08:43.893134
| 2020-04-21T11:20:18
| 2020-04-21T11:20:18
| 77,862,875
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,687
|
r
|
highlightHTMLmaster.r
|
#' Master highlight HTML function
#'
#' This function inputs a markdown or rmarkdown document and exports an HTML file.
#' The HTML file is then processed to search for tags that inject CSS automatically
#' into the HTML file.
#'
#' A function that allows the alteration of HTML using CSS. This may be helpful
#' coming from a markdown or R markdown file to alter aspects of the page based on
#' a specific criteria. This function handles both tables as well as normal text.
#' The options are only limited based on your knowledge of CSS.
#'
#' @param input File name of markdown or rmarkdown file to highlight the cells of the table or text.
#' Alternatively, if render = FALSE, a HTML file can be specified as the input.
#' @param output Output file name of highlighted HTML file
#' @param tags character vector with CSS tags to be added
#' @param browse logical, If TRUE (default) output file opens in default browser, if FALSE,
#' file is written, but not opened in browser.
#' @param print logical, if TRUE print output to R console, if false (default) output is
#' filtered to other methods (see browse or output).
#' @param render logical, if TRUE (default) will call the rmarkdown::render() function to
#' convert Rmd or md files to html prior to injecting CSS.
#' @examples
#' # Setting path for example html files
#' # To see path where these are saved, type file or file1 in the
#' # r console.
#' \dontrun{
#' file <- system.file('examples', 'bgtable.html', package = 'highlightHTML')
#'
#' # Creating CSS tags to inject into HTML document
#' tags <- c("#bgred {background-color: #FF0000;}",
#' "#bgblue {background-color: #0000FF;}")
#'
#' # Command to post-process HTML file - Writes to temporary file
#' highlight_html(input = file, output = tempfile(fileext = ".html"),
#' tags = tags, browse = FALSE)
#' }
#' @export
highlight_html <- function(input, output, tags, browse = TRUE, print = FALSE,
render = TRUE) {
if(missing(output)) {
output <- gsub("\\.md$|\\.Rmd", "_out\\.html", input)
message("output file path not specified, file saved to ", output)
}
if(render) {
rmarkdown::render(input = input, output_format = 'html_document',
output_file = output)
text_output <- readLines(output)
} else {
text_output <- readLines(input)
}
text_output <- highlight_html_cells(input = text_output, output = output, tags,
update_css = FALSE,
browse = FALSE, print = TRUE)
highlight_html_text(input = text_output, output, tags, update_css = TRUE,
browse, print)
}
|
4894a34a7a618f6a556c456f301930d4e8325337
|
40085e8ec7f302204d2aa460b6be1cf9cb9a3098
|
/R/ListExperimentFunctions.R
|
6e1b02495cd874f8625e3369d397947502aef7f5
|
[] |
no_license
|
cran/misreport
|
9102430b755712998d4a05436f60a2ac01cc78c6
|
b541a33492924a56171063ca0fecc933c80083ec
|
refs/heads/master
| 2020-06-11T19:14:11.260959
| 2017-02-27T07:15:34
| 2017-02-27T07:15:34
| 75,629,243
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 98,324
|
r
|
ListExperimentFunctions.R
|
#' Add two numbers
#'
#' The function \code{logAdd} adds together two numbers using their log
#' to prevent under-/over-flow
#'
#' @param x log of the first number.
#' @param y log of the second number.
#' @return Log of the sum of \code{exp(x)} and \code{exp(y)}.
#'
#' @keywords internal
logAdd <- function(lx, ly) {
max(lx, ly) + log1p(exp(-abs(lx - ly)))
}
#' Misreport sub-model m-step
#'
#' The maximization step in the EM algorithm called by \code{\link{listExperiment}}
#' for the misreport sub-model.
#'
#' @keywords internal
#'
#' @importFrom stats .getXlevels as.formula binomial coef
#' cov dbinom model.matrix model.frame model.response
#' na.pass plogis pt pnorm rnorm runif glm
#' @importFrom mvtnorm rmvnorm
mstepMisreport <- function(y, x.misreport, w, treat,
misreport.treatment, weight) {
lrep <- rep(c(1, 0), each = length(y)) # Misreport is the first column of w
if(misreport.treatment == TRUE) {
xrep <- as.matrix(rbind(cbind(x.misreport, treat), cbind(x.misreport, treat)))
} else if(misreport.treatment == FALSE) {
xrep <- as.matrix(rbind(x.misreport, x.misreport))
}
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight)) # Misreport is the first column of w
lrep <- lrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) {
fit.misreport <- glm(cbind(lrep, 1 - lrep) ~ 1, weights = exp(wrep), family = binomial)
} else if(ncol(X) > 1) {
fit.misreport <- glm(cbind(lrep, 1 - lrep) ~ -1 + X, weights = exp(wrep), family = binomial)
}
coefs <- coef(fit.misreport)
names(coefs) <- gsub("^X1|^X2|^X3|^X", "", names(coefs))
return(coefs)
}
#' Sensitive-item sub-model m-step
#'
#' The maximization step in the EM algorithm called by \code{\link{listExperiment}}
#' for the sensitive-item sub-model.
#'
#' @keywords internal
#'
mstepSensitive <- function(y, treat, x.sensitive, w, d, sensitive.response,
weight, model.misreport) {
if(model.misreport == TRUE) {
zrep <- rep(c(sensitive.response, abs(1 - sensitive.response)), each = length(y))
xrep <- as.matrix(rbind(x.sensitive, x.sensitive))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
# wrep <- c(apply(w[, 1:2], 1, sum) * weight, w[, 3] * weight)
zrep <- zrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) fit <- glm(cbind(zrep, 1 - zrep) ~ 1, weights = exp(wrep), family = binomial)
if(ncol(X) > 1) fit <- glm(cbind(zrep, 1 - zrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(fit)
} else {
zrep <- rep(c(1, 0), each = length(y))
xrep <- as.matrix(rbind(x.sensitive, x.sensitive))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
zrep <- zrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) fit <- glm(cbind(zrep, 1 - zrep) ~ 1, weights = exp(wrep), family = binomial)
if(ncol(X) > 1) fit <- glm(cbind(zrep, 1 - zrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(fit)
}
names(coefs) <- gsub("^X1|^X2|^X3|^X", "", names(coefs))
return(coefs)
}
#' Control-items sub-model m-step
#'
#' The maximization step in the EM algorithm called by \code{\link{listExperiment}}
#' for the control-items sub-model.
#'
#' @keywords internal
#'
mstepControl <- function(y, treat, J, x.control, w, d, sensitive.response,
weight, model.misreport, control.constraint) {
if(model.misreport == TRUE) {
if(control.constraint == "none") {
yrep <- c((y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 0)))
xrep <- as.matrix(rbind(x.control, x.control, x.control))
zrep1 <- rep(c(1, 0, 0), each = length(y)) # Misreport sensitive
zrep2 <- rep(c(sensitive.response,
sensitive.response,
1 - sensitive.response), each = length(y)) # Truthful sensitive
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight), w[, 3] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
zrep2 <- zrep2[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, U = zrep1, Z = zrep2)
control.fit <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(control.fit)
} else if(control.constraint == "partial") { # U* = 0
yrep <- c((y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 0)))
xrep <- as.matrix(rbind(x.control, x.control))
zrep1 <- rep(c(sensitive.response, 1 - sensitive.response), each = length(y)) # Sensitive
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, Z = zrep1)
control.fit <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(control.fit)
} else if(control.constraint == "full") { # U* = Z* = 0
yrep <- c((y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 0)))
xrep <- as.matrix(rbind(x.control, x.control))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) control.fit <- glm(cbind(yrep, J - yrep) ~ 1 , weights = exp(wrep), family = binomial)
if(ncol(X) > 1) control.fit <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(control.fit)
}
} else {
yrep <- c(y - treat, y)
xrep <- as.matrix(rbind(x.control, x.control))
zrep1 <- rep(c(1, 0), each = length(y))
zrep2 <- rep(c(0, 1), each = length(y))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
zrep2 <- zrep2[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
if(control.constraint == "none") {
X <- cbind(xrep, Z = zrep1)
fit.partial <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- c(coef(fit.partial))
}
if(control.constraint == "full") {
X <- xrep
if(ncol(X) == 1) fit.full <- glm(cbind(yrep, J - yrep) ~ 1 , weights = exp(wrep), family = binomial)
if(ncol(X) > 1) fit.full <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- c(coef(fit.full))
}
}
names(coefs) <- gsub("^X1|^X2|^X3|^X", "", names(coefs))
names(coefs)[names(coefs) == "(Intercept):1"] <- "(Intercept)"
return(coefs)
}
#' Outcome sub-model m-step
#'
#' The maximization step in the EM algorithm called by \code{\link{listExperiment}}
#' for the outcome sub-model.
#'
#' @keywords internal
#'
mstepOutcome <- function(y, treat, x.outcome, w, d, sensitive.response, o,
trials, weight, outcome.model, model.misreport,
outcome.constrained, control.constraint) {
coefs.aux <- NULL
if(outcome.constrained == TRUE) {
if(model.misreport == TRUE) {
xrep <- as.matrix(rbind(x.outcome, x.outcome))
zrep <- rep(c(1, 0), each = length(y))
orep <- as.matrix(c(o, o))
trialsrep <- as.matrix(c(trials, trials))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
} else {
xrep <- as.matrix(rbind(x.outcome, x.outcome))
zrep <- rep(c(1, 0), each = length(y))
orep <- as.matrix(c(o, o))
trialsrep <- as.matrix(c(trials, trials))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
}
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep <- zrep[wrep > -Inf]
orep <- orep[wrep > -Inf]
trialsrep <- trialsrep[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, Z = zrep)[, -1, drop = FALSE]
if(outcome.model == "logistic") {
fit.constrained.logistic <- glm(cbind(orep, 1 - orep) ~ 1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(fit.constrained.logistic)
} else if(outcome.model == "binomial") {
fit.constrained.binomial <- glm(cbind(orep, trialsrep - orep) ~ 1 + X, family = binomial, weights = exp(wrep))
coefs <- coef(fit.constrained.binomial)
} else if(outcome.model == "betabinomial") {
fit.constrained.betabinomial <- VGAM::vglm(cbind(orep, trialsrep - orep) ~ 1 + X, VGAM::betabinomial, weights = exp(wrep))
coefs <- coef(fit.constrained.betabinomial)[-2]
coefs.aux <- c(rho = mean(fit.constrained.betabinomial@misc$rho))
}
} else if(outcome.constrained == FALSE) {
if(model.misreport == TRUE) {
xrep <- as.matrix(rbind(x.outcome, x.outcome, x.outcome))
zrep1 <- rep(c(1, 0, 0), each = length(y))
zrep2 <- rep(c(1, 1, 0), each = length(y))
orep <- as.matrix(c(o, o, o))
trialsrep <- as.matrix(c(trials, trials, trials))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight), w[, 3] + log(weight))
} else {
stop("\noutcome.constrained = TRUE is only possible when a direct question is included.")
}
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
zrep2 <- zrep2[wrep > -Inf]
orep <- orep[wrep > -Inf]
trialsrep <- trials[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, U = zrep1, Z = zrep2)[, -1, drop = FALSE]
if(outcome.model == "logistic") {
fit.unconstrained.logitistic <- glm(cbind(orep, 1 - orep) ~ 1 + X, weights = log(wrep), family = binomial)
coefs <- coef(fit.unconstrained.logitistic)
} else if(outcome.model == "binomial") {
fit.unconstrained.binomial <- glm(cbind(orep, trialsrep - orep) ~ 1 + X, family = binomial, weights = log(wrep))
coefs <- coef(fit.unconstrained.binomial)
} else if(outcome.model == "betabinomial") {
fit.constrained.betabinomial <- VGAM::vglm(cbind(orep, trialsrep - orep) ~ 1 + X, VGAM::betabinomial, weights = log(wrep))
coefs <- coef(fit.constrained.betabinomial)[-2]
coefs.aux <- c(rho = mean(fit.constrained.betabinomial@misc$rho))
}
}
names(coefs) <- gsub("^X", "", names(coefs))
names(coefs)[names(coefs) == ""] <- "Z"
names(coefs)[names(coefs) == "(Intercept):1"] <- "(Intercept)"
return(list(coefs = coefs, coefs.aux = coefs.aux))
}
#' E-step
#'
#' The expectation step in the EM algorithm called by \code{\link{listExperiment}}.
#'
#' @keywords internal
#'
estep <- function(y, w, x.control, x.sensitive, x.outcome, x.misreport, treat, J,
par.sensitive, par.control, par.outcome,
par.outcome.aux, par.misreport,
d, sensitive.response, model.misreport,
o, trials, outcome.model, weight,
outcome.constrained, control.constraint, respondentType,
misreport.treatment) {
log.lik <- rep(as.numeric(NA), length(y))
if(model.misreport == TRUE) {
# CONTROL ITEMS
if(control.constraint == "none") {
hX.misreport.sensitive <- plogis(cbind(x.control, 1, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.sensitive <- plogis(cbind(x.control, 0, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.nonsensitive <- plogis(cbind(x.control, 0, 1 - sensitive.response) %*% par.control, log.p = TRUE)
}
if(control.constraint == "partial") {
hX.misreport.sensitive <- plogis(cbind(x.control, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.sensitive <- plogis(cbind(x.control, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.nonsensitive <- plogis(cbind(x.control, 1 - sensitive.response) %*% par.control, log.p = TRUE)
}
if(control.constraint == "full") {
hX.misreport.sensitive <- plogis(x.control %*% par.control, log.p = TRUE)
hX.truthful.sensitive <- plogis(x.control %*% par.control, log.p = TRUE)
hX.truthful.nonsensitive <- plogis(x.control %*% par.control, log.p = TRUE)
}
hX.misreport.sensitive <- dbinom((y - treat * as.numeric(sensitive.response == 1)), size = J, prob = exp(hX.misreport.sensitive), log = TRUE)
hX.truthful.sensitive <- dbinom((y - treat * as.numeric(sensitive.response == 1)), size = J, prob = exp(hX.truthful.sensitive), log = TRUE)
hX.truthful.nonsensitive <- dbinom((y - treat * as.numeric(sensitive.response == 0)), size = J, prob = exp(hX.truthful.nonsensitive), log = TRUE)
# OUTCOME
if(outcome.model != "none") {
if(outcome.constrained == TRUE) {
if(outcome.model %in% c("logistic", "binomial", "betabinomial")) {
fX.misreport.sensitive <- plogis(cbind(x.outcome, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.sensitive <- plogis(cbind(x.outcome, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.nonsensitive <- plogis(cbind(x.outcome, 0) %*% par.outcome, log.p = TRUE)
}
} else {
if(outcome.model %in% c("logistic", "binomial", "betabinomial")) {
fX.misreport.sensitive <- plogis(cbind(x.outcome, 1, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.sensitive <- plogis(cbind(x.outcome, 0, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.nonsensitive <- plogis(cbind(x.outcome, 0, 0) %*% par.outcome, log.p = TRUE)
}
}
} else {
fX.misreport.sensitive <- rep(0, length(y))
fX.truthful.sensitive <- rep(0, length(y))
fX.truthful.nonsensitive <- rep(0, length(y))
}
if(outcome.model == "logistic") {
fX.misreport.sensitive <- dbinom(o, size = 1, prob = exp(fX.misreport.sensitive), log = TRUE)
fX.truthful.sensitive <- dbinom(o, size = 1, prob = exp(fX.truthful.sensitive), log = TRUE)
fX.truthful.nonsensitive <- dbinom(o, size = 1, prob = exp(fX.truthful.nonsensitive), log = TRUE)
} else if(outcome.model == "binomial") {
fX.misreport.sensitive <- dbinom(o, size = trials, prob = exp(fX.misreport.sensitive), log = TRUE)
fX.truthful.sensitive <- dbinom(o, size = trials, prob = exp(fX.truthful.sensitive), log = TRUE)
fX.truthful.nonsensitive <- dbinom(o, size = trials, prob = exp(fX.truthful.nonsensitive), log = TRUE)
} else if(outcome.model == "betabinomial") {
fX.misreport.sensitive <- VGAM::dbetabinom(o, size = trials, prob = exp(fX.misreport.sensitive), rho = par.outcome.aux["rho"], log = TRUE)
fX.truthful.sensitive <- VGAM::dbetabinom(o, size = trials, prob = exp(fX.truthful.sensitive), rho = par.outcome.aux["rho"], log = TRUE)
fX.truthful.nonsensitive <- VGAM::dbetabinom(o, size = trials, prob = exp(fX.truthful.nonsensitive), rho = par.outcome.aux["rho"], log = TRUE)
}
# SENSITIVE ITEM
if(sensitive.response == 1) {
gX.misreport.sensitive <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
gX.truthful.sensitive <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
gX.truthful.nonsensitive <- log1p(-exp(plogis(x.sensitive %*% par.sensitive, log.p = TRUE))) # log(1 - plogis(x.sensitive %*% par.sensitive))
} else {
gX.misreport.sensitive <- log1p(-exp(plogis(x.sensitive %*% par.sensitive, log.p = TRUE))) # log(1 - plogis(x.sensitive %*% par.sensitive))
gX.truthful.sensitive <- log1p(-exp(plogis(x.sensitive %*% par.sensitive, log.p = TRUE))) # log(1 - plogis(x.sensitive %*% par.sensitive))
gX.truthful.nonsensitive <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
}
# MISREPORTING
if(misreport.treatment == TRUE) {
lX.misreport.sensitive <- plogis(cbind(x.misreport, treat) %*% par.misreport, log.p = TRUE)
lX.truthful.sensitive <- log1p(-exp(plogis(cbind(x.misreport, treat) %*% par.misreport, log.p = TRUE))) # log(1 - exp(plogis(x.misreport %*% par.misreport, log.p = TRUE)))
lX.truthful.nonsensitive <- log(rep(1, length(y))) # Non-sensitive don't misreport it (monotonicity)
} else {
lX.misreport.sensitive <- plogis(x.misreport %*% par.misreport, log.p = TRUE)
lX.truthful.sensitive <- log1p(-exp(plogis(x.misreport %*% par.misreport, log.p = TRUE))) # log(1 - exp(plogis(x.misreport %*% par.misreport, log.p = TRUE)))
lX.truthful.nonsensitive <- log(rep(1, length(y))) # Non-sensitive don't misreport it (monotonicity)
}
w[, 1] <- lX.misreport.sensitive + gX.misreport.sensitive + hX.misreport.sensitive + fX.misreport.sensitive
w[, 2] <- lX.truthful.sensitive + gX.truthful.sensitive + hX.truthful.sensitive + fX.truthful.sensitive
w[, 3] <- lX.truthful.nonsensitive + gX.truthful.nonsensitive + hX.truthful.nonsensitive + fX.truthful.nonsensitive
w[respondentType == "Misreport sensitive", 1] <- log(1)
w[respondentType == "Misreport sensitive", 2] <- log(0)
w[respondentType == "Misreport sensitive", 3] <- log(0)
w[respondentType == "Truthful sensitive", 1] <- log(0)
w[respondentType == "Truthful sensitive", 2] <- log(1)
w[respondentType == "Truthful sensitive", 3] <- log(0)
w[respondentType == "Non-sensitive", 1] <- log(0)
w[respondentType == "Non-sensitive", 2] <- log(0)
w[respondentType == "Non-sensitive", 3] <- log(1)
w[respondentType == "Non-sensitive or misreport sensitive", 2] <- log(0)
denominator <- apply(w, 1, function(x) logAdd(logAdd(x[1], x[2]), x[3]))
w[, 1] <- w[, 1] - denominator
w[, 2] <- w[, 2] - denominator
w[, 3] <- w[, 3] - denominator
w[respondentType == "Misreport sensitive", 1] <- log(1)
w[respondentType == "Misreport sensitive", 2] <- log(0)
w[respondentType == "Misreport sensitive", 3] <- log(0)
w[respondentType == "Truthful sensitive", 1] <- log(0)
w[respondentType == "Truthful sensitive", 2] <- log(1)
w[respondentType == "Truthful sensitive", 3] <- log(0)
w[respondentType == "Non-sensitive", 1] <- log(0)
w[respondentType == "Non-sensitive", 2] <- log(0)
w[respondentType == "Non-sensitive", 3] <- log(1)
w[respondentType == "Non-sensitive or misreport sensitive", 2] <- log(0)
# w <- exp(w) / apply(exp(w), 1, sum)
# Non-sensitive or misreport sensitive
log.lik[respondentType == "Non-sensitive or misreport sensitive"] <- apply(data.frame(lX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"] +
gX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"] +
hX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"] +
fX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"],
lX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"] +
gX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"] +
hX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"] +
fX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"]),
1, function(x) logAdd(x[1], x[2]))
# Truthful sensitive
log.lik[respondentType == "Truthful sensitive"] <- lX.truthful.sensitive[respondentType == "Truthful sensitive"] +
gX.truthful.sensitive[respondentType == "Truthful sensitive"] +
hX.truthful.sensitive[respondentType == "Truthful sensitive"] +
fX.truthful.sensitive[respondentType == "Truthful sensitive"]
# Non-sensitive
log.lik[respondentType == "Non-sensitive"] <- lX.truthful.nonsensitive[respondentType == "Non-sensitive"] +
gX.truthful.nonsensitive[respondentType == "Non-sensitive"] +
hX.truthful.nonsensitive[respondentType == "Non-sensitive"] +
fX.truthful.nonsensitive[respondentType == "Non-sensitive"]
# Misreport sensitive
log.lik[respondentType == "Misreport sensitive"] <- lX.misreport.sensitive[respondentType == "Misreport sensitive"] +
gX.misreport.sensitive[respondentType == "Misreport sensitive"] +
hX.misreport.sensitive[respondentType == "Misreport sensitive"] +
fX.misreport.sensitive[respondentType == "Misreport sensitive"]
}
if(model.misreport == FALSE) {
# CONTROL ITEMS
if(control.constraint == "none") {
hX.1 <- plogis(cbind(x.control, 1) %*% par.control)
hX.0 <- plogis(cbind(x.control, 0) %*% par.control)
}
if(control.constraint == "full") {
hX.1 <- plogis(x.control %*% par.control)
hX.0 <- plogis(x.control %*% par.control)
}
hX.1 <- dbinom((y - treat), size = J, prob = hX.1, log = TRUE)
hX.0 <- dbinom(y, size = J, prob = hX.0, log = TRUE)
# OUTCOME
if(outcome.model %in% c("logistic", "binomial", "betabinomial")) {
fX.1 <- plogis(cbind(x.outcome, 1) %*% par.outcome)
fX.0 <- plogis(cbind(x.outcome, 0) %*% par.outcome)
} else {
fX.1 <- rep(0, length(y))
fX.0 <- rep(0, length(y))
}
if(outcome.model == "logistic") {
fX.1 <- dbinom(o, size = 1, prob = fX.1, log = TRUE)
fX.0 <- dbinom(o, size = 1, prob = fX.0, log = TRUE)
} else if(outcome.model == "binomial") {
fX.1 <- dbinom(o, size = trials, prob = fX.1, log = TRUE)
fX.0 <- dbinom(o, size = trials, prob = fX.0, log = TRUE)
} else if(outcome.model == "betabinomial") {
fX.1 <- VGAM::dbetabinom(o, size = trials, prob = fX.1, rho = par.outcome.aux["rho"], log = TRUE)
fX.0 <- VGAM::dbetabinom(o, size = trials, prob = fX.0, rho = par.outcome.aux["rho"], log = TRUE)
}
# SENSITIVE ITEM
gX.1 <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
gX.0 <- log(1 - exp(gX.1))
w[, 1] <- gX.1 + hX.1 + fX.1
w[, 2] <- gX.0 + hX.0 + fX.0
w[respondentType == "1", 1] <- log(1)
w[respondentType == "1", 2] <- log(0)
w[respondentType == "0", 1] <- log(0)
w[respondentType == "0", 2] <- log(1)
denominator <- apply(w, 1, function(x) logAdd(x[1], x[2]))
w[, 1] <- w[, 1] - denominator
w[, 2] <- w[, 2] - denominator
w[respondentType == "1", 1] <- log(1)
w[respondentType == "1", 2] <- log(0)
w[respondentType == "0", 1] <- log(0)
w[respondentType == "0", 2] <- log(1)
# Log likelihood
log.lik[respondentType == "0"] <- gX.0[respondentType == "0"] +
hX.0[respondentType == "0"] +
fX.0[respondentType == "0"]
log.lik[respondentType == "1"] <- gX.1[respondentType == "1"] +
hX.1[respondentType == "1"] +
fX.1[respondentType == "1"]
log.lik[respondentType == "0 or 1"] <- apply(data.frame(gX.1[respondentType == "0 or 1"] +
hX.1[respondentType == "0 or 1"] +
fX.1[respondentType == "0 or 1"],
gX.0[respondentType == "0 or 1"] +
hX.0[respondentType == "0 or 1"] +
fX.0[respondentType == "0 or 1"]),
1, function(x) logAdd(x[1], x[2]))
log.lik[respondentType == "0 or 1"] <- log(exp(gX.1[respondentType == "0 or 1"] +
hX.1[respondentType == "0 or 1"] +
fX.1[respondentType == "0 or 1"]) +
exp(gX.0[respondentType == "0 or 1"] +
hX.0[respondentType == "0 or 1"] +
fX.0[respondentType == "0 or 1"]))
}
return(list(w = w, ll = sum(weight * log.lik)))
}
#' List experiment regression
#'
#' Regression analysis for sensitive survey questions using a list experiment and direct question.
#'
#' @param formula An object of class "\code{\link{formula}}": a symbolic description of the model to be fitted.
#' @param data A data frame containing the variables to be used in the model.
#' @param treatment A string indicating the name of the treatment indicator in the data. This variable must be coded as a binary, where 1 indicates assignment to treatment and 0 indicates assignment to control.
#' @param J An integer indicating the number of control items in the list experiment.
#' @param direct A string indicating the name of the direct question response in the data. The direct question must be coded as a binary variable. If NULL (default), a misreport sub-model is not fit.
#' @param sensitive.response A value 0 or 1 indicating whether the response that is considered sensitive in the list experiment/direct question is 0 or 1.
#' @param outcome A string indicating the variable name in the data to use as the outcome in an outcome sub-model. If NULL (default), no outcome sub-model is fit. [\emph{experimental}]
#' @param outcome.trials An integer indicating the number of trials in a binomial/betabinomial model if both an outcome sub-model is used and if the argument \code{outcome.model} is set to "binomial" or "betabinomial". [\emph{experimental}]
#' @param outcome.model A string indicating the model type to fit for the outcome sub-model ("logistic", "binomial", "betabinomial"). [\emph{experimental}]
#' @param outcome.constrained A logical value indicating whether to constrain U* = 0 in the outcome sub-model. Defaults to TRUE. [\emph{experimental}]
#' @param control.constraint A string indicating the constraint to place on Z* and U* in the control-items sub-model:
#' \describe{
#' \item{"none" (default)}{Estimate separate parameters for Z* and U*.}
#' \item{"partial"}{Constrain U* = 0.}
#' \item{"full"}{Constrain U* = Z* = 0.}
#' }
#' @param misreport.treatment A logical value indicating whether to include a parameter for the treatment indicator in the misreport sub-model. Defaults to TRUE.
#' @param weights A string indicating the variable name of survey weights in the data (note: standard errors are not currently output when survey weights are used).
#' @param se A logical value indicating whether to calculate standard errors. Defaults to TRUE.
#' @param tolerance The desired accuracy for EM convergence. The EM loop breaks after the change in the log-likelihood is less than the value of \code{tolerance}. Defaults to 1e-08.
#' @param max.iter The maximum number of iterations for the EM algorithm. Defaults to 10000.
#' @param n.runs The total number of times that the EM algorithm is run (can potentially help avoid local maxima). Defaults to 1.
#' @param verbose A logical value indicating whether to print information during model fitting. Defaults to TRUE.
#' @param get.data For internal use. Used by wrapper function \code{\link{bootListExperiment}}.
#' @param par.control A vector of starting parameters for the control-items sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2).
#' @param par.sensitive A vector of starting parameters for the sensitive-item sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2).
#' @param par.misreport A vector of starting parameters for the misreport sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2).
#' @param par.outcome A vector of starting parameters for the outcome sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2). [experimental]
#' @param par.outcome.aux A vector of starting parameters for the outcome sub-model in which \code{outcome.model} is "betabinomial". i.e. c(alpha, beta). If NULL (default), randomly generated starting points are used, drawn from uniform(0, 1). [experimental]
#' @param formula.control An object of class "\code{\link{formula}}" used to specify a control-items sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2)
#' @param formula.sensitive An object of class "\code{\link{formula}}" used to specify a sensitive-item sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2)
#' @param formula.misreport An object of class "\code{\link{formula}}" used to specify a misreport sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2)
#' @param formula.outcome An object of class "\code{\link{formula}}" used to specify an outcome sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2) [\emph{experimental}]
#' @param get.boot For internal use. An integer, which if greater than 0 requests that \code{listExperiment()} generate a non-parametric bootstrap sample and fit a model to that sample. Used by the function \code{\link{bootListExperiment}}.
#' @param ... Additional options.
#'
#' @details The \code{listExperiment} function allows researchers to fit a model
#' for a list experiment and direct question simultaneously, as
#' described in Eady (2017). The primary aim of the function is
#' to allow researchers to model the probability that respondents
#' provides one response to the sensitive item in a list experiment
#' but respond otherwise when asked about the same sensitive item on a
#' direct question. When a direct question response is excluded from
#' the function, the model is functionally equivalent to that proposed
#' by Imai (2011), as implemented as the \code{\link[list]{ictreg}} function
#' in the \code{list} package (\url{https://CRAN.R-project.org/package=list}).
#'
#' @return \code{listExperiment} returns an object of class "listExperiment".
#' A summary of this object is given using the \code{\link{summary.listExperiment}}
#' function. All components in the "listExperiment" class are listed below.
#' @slot par.control A named vector of coefficients from the control-items sub-model.
#' @slot par.sensitive A named vector of coefficients from the sensitive-item sub-model.
#' @slot par.misreport A named vector of coefficients from the misreport sub-model.
#' @slot par.outcome A named vector of coefficients from the outcome sub-model.
#' @slot par.outcome.aux A named vector of (auxiliary) coefficients from the outcome sub-model (if \code{outcome.model} = "betabinomial").
#' @slot df Degrees of freedom.
#' @slot se.sensitive Standard errors for parameters in the sensitive-item sub-model.
#' @slot se.control Standard errors for parameters in the control-items sub-model.
#' @slot se.misreport Standard errors for parameters in the misreport sub-model.
#' @slot se.outcome Standard errors for parameters in the outcome sub-model.
#' @slot se.outcome.aux Standard errors for the auxiliary parameters in the outcome sub-model (if \code{outcome.model} = "betabinomial").
#' @slot vcov.mle Variance-covariance matrix.
#' @slot w The matrix of posterior predicted probabilities for each observation in the data used for model fitting.
#' @slot data The data frame used for model fitting.
#' @slot direct The string indicating the variable name of the direct question.
#' @slot treatment The string indicating the variable name of the treatment indicator.
#' @slot model.misreport A logical value indicating whether a misreport sub-model was fit.
#' @slot outcome.model The type of model used as the outcome sub-model.
#' @slot outcome.constrained A logical value indicating whether the parameter U* was constrained to 0 in the outcome sub-model.
#' @slot control.constraint A string indicating the constraints placed on the parameters Z* and U* in the control-items sub-model.
#' @slot misreport.treatment A logical value indicating whether a treatment indicator was included in the misreport sub-model.
#' @slot weights A string indicating the variable name of the survey weights.
#' @slot formula The model formula.
#' @slot formula.control The model specification of the control-items sub-model.
#' @slot formula.sensitive The model specification of the sensitive-item sub-model.
#' @slot formula.misreport The model specification of the misreport sub-model.
#' @slot formula.outcome The model specification of the outcome sub-model.
#' @slot sensitive.response The value 0 or 1 indicating the response to the list experiment/direct question that is considered sensitive.
#' @slot xlevels The factor levels of the variables used in the model.
#' @slot llik The model log-likelihood.
#' @slot n The sample size of the data used for model fitting (this value excludes rows removed through listwise deletion).
#' @slot J The number of control items in the list experiment.
#' @slot se A logical value indicating whether standard errors were calculated.
#' @slot runs The parameter estimates from each run of the EM algorithm (note: the parameters that result in the highest log-likelihood are used as the model solution).
#' @slot call The method call.
#' @slot boot A logical value indicating whether non-parametric bootstrapping was used to calculate model parameters and standard errors.
#'
#' @references Eady, Gregory. 2017 "The Statistical Analysis of Misreporting on Sensitive Survey Questions."
#' @references Imai, Kosuke. 2011. "Multivariate Regression Analysis for the Item Count Technique." \emph{Journal of the American Statistical Association} 106 (494): 407-416.
#'
#' @examples
#'
#' ## EXAMPLE 1: Simulated list experiment and direct question
#' n <- 10000
#' J <- 4
#'
#' # Covariates
#' x <- cbind(intercept = rep(1, n), continuous1 = rnorm(n),
#' continuous2 = rnorm(n), binary1 = rbinom(n, 1, 0.5))
#'
#' treatment <- rbinom(n, 1, 0.5)
#'
#' # Simulate Z*
#' param_sensitive <- c(0.25, -0.25, 0.5, 0.25)
#' prob_sensitive <- plogis(x %*% param_sensitive)
#' true_belief <- rbinom(n, 1, prob = prob_sensitive)
#'
#' # Simulate whether respondent misreports (U*)
#' param_misreport <- c(-0.25, 0.25, -0.5, 0.5)
#' prob_misreport <- plogis(x %*% param_misreport) * true_belief
#' misreport <- rbinom(n, 1, prob = prob_misreport)
#'
#' # Simulate control items Y*
#' param_control <- c(0.25, 0.25, -0.25, 0.25, U = -0.5, Z = 0.25)
#' prob.control <- plogis(cbind(x, misreport, true_belief) %*% param_control)
#' control_items <- rbinom(n, J, prob.control)
#'
#' # List experiment and direct question responses
#' direct <- true_belief
#' direct[misreport == 1] <- 0
#' y <- control_items + true_belief * treatment
#'
#' A <- data.frame(y, direct, treatment,
#' continuous1 = x[, "continuous1"],
#' continuous2 = x[, "continuous2"],
#' binary1 = x[, "binary1"])
#'
#' \dontrun{
#' model.sim <- listExperiment(y ~ continuous1 + continuous2 + binary1,
#' data = A, treatment = "treatment", direct = "direct",
#' J = 4, control.constraint = "none",
#' sensitive.response = 1)
#' summary(model.sim, digits = 3)
#' }
#'
#'
#' ## EXAMPLE 2: Data from Eady (2017)
#' data(gender)
#'
#' \dontrun{
#' # Note: substantial computation time
#' model.gender <- listExperiment(y ~ gender + ageGroup + education +
#' motherTongue + region + selfPlacement,
#' data = gender, J = 4,
#' treatment = "treatment", direct = "direct",
#' control.constraint = "none",
#' sensitive.response = 0,
#' misreport.treatment = TRUE)
#' summary(model.gender)
#' }
#'
#' @export
#'
listExperiment <- function(formula, data, treatment, J,
direct = NULL, sensitive.response = NULL,
outcome = NULL, outcome.trials = NULL,
outcome.model = "logistic",
outcome.constrained = TRUE,
control.constraint = "none",
misreport.treatment = TRUE,
weights = NULL, se = TRUE, tolerance = 1E-8,
max.iter = 10000, n.runs = 3, verbose = TRUE,
get.data = FALSE,
par.control = NULL, par.sensitive = NULL,
par.misreport = NULL, par.outcome = NULL,
par.outcome.aux = NULL,
formula.control = NULL, formula.sensitive = NULL,
formula.misreport = NULL, formula.outcome = NULL,
get.boot = 0, ...) {
function.call <- match.call(expand.dots = FALSE)
if(missing(data)) data <- environment(formula)
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "na.action"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf$na.action <- "na.pass"
mf[[1]] <- quote(model.frame)
mt <- attr(eval(mf, parent.frame()), "terms")
xlevels.formula <- .getXlevels(attr(eval(mf, parent.frame()), "terms"), eval(mf, parent.frame()))
if(!is.null(formula.control)) {
mf.control <- mf
mf.control$formula <- formula.control
xlevels.formula.control <- .getXlevels(attr(eval(mf.control, parent.frame()), "terms"), eval(mf.control, parent.frame()))
mf.control <- eval(mf.control, parent.frame())
x.control <- model.matrix(attr(mf.control, "terms"), data = mf.control)
} else {
formula.control <- as.formula(mf$formula)
xlevels.formula.control <- xlevels.formula
mf.control <- eval(mf, parent.frame())
x.control <- model.matrix(attr(mf.control, "terms"), data = mf.control)
}
if(!is.null(formula.sensitive)) {
mf.sensitive <- mf
mf.sensitive$formula <- formula.sensitive
xlevels.formula.sensitive <- .getXlevels(attr(eval(mf.sensitive, parent.frame()), "terms"), eval(mf.sensitive, parent.frame()))
mf.sensitive <- eval(mf.sensitive, parent.frame())
x.sensitive <- model.matrix(attr(mf.sensitive, "terms"), data = mf.sensitive)
} else {
formula.sensitive <- as.formula(mf$formula)
xlevels.formula.sensitive <- xlevels.formula
mf.sensitive <- eval(mf, parent.frame())
x.sensitive <- model.matrix(attr(mf.sensitive, "terms"), data = mf.sensitive)
}
if(!is.null(formula.misreport)) {
mf.misreport <- mf
mf.misreport$formula <- formula.misreport
xlevels.formula.misreport <- .getXlevels(attr(eval(mf.misreport, parent.frame()), "terms"), eval(mf.misreport, parent.frame()))
mf.misreport <- eval(mf.misreport, parent.frame())
x.misreport <- model.matrix(attr(mf.misreport, "terms"), data = mf.misreport)
} else {
formula.misreport <- as.formula(mf$formula)
xlevels.formula.misreport <- xlevels.formula
mf.misreport <- eval(mf, parent.frame())
x.misreport <- model.matrix(attr(mf.misreport, "terms"), data = mf.misreport)
}
if(!is.null(formula.outcome)) {
mf.outcome <- mf
mf.outcome$formula <- formula.outcome
xlevels.formula.outcome <- .getXlevels(attr(eval(mf.outcome, parent.frame()), "terms"), eval(mf.outcome, parent.frame()))
mf.outcome <- eval(mf.outcome, parent.frame())
x.outcome <- model.matrix(attr(mf.outcome, "terms"), data = mf.outcome)
} else {
formula.outcome <- as.formula(mf$formula)
xlevels.formula.outcome <- xlevels.formula
mf.outcome <- eval(mf, parent.frame())
x.outcome <- model.matrix(attr(mf.outcome, "terms"), data = mf.outcome)
}
mf <- eval(mf, parent.frame())
y <- model.response(mf, type = "any")
treat <- data[, paste(treatment)]
xlevels <- c(xlevels.formula,
xlevels.formula.control,
xlevels.formula.sensitive,
xlevels.formula.misreport,
xlevels.formula.outcome)
xlevels <- xlevels[-which(duplicated(xlevels))]
# x.na <- apply(x, 1, function(X) all(!is.na(X)))
x.control.na <- apply(x.control, 1, function(X) all(!is.na(X)))
x.sensitive.na <- apply(x.sensitive, 1, function(X) all(!is.na(X)))
x.misreport.na <- apply(x.misreport, 1, function(X) all(!is.na(X)))
x.outcome.na <- apply(x.outcome, 1, function(X) all(!is.na(X)))
y.na <- !is.na(y)
treat.na <- !is.na(treat)
if(!is.null(direct)) {
d <- data[, paste(direct)]
d.na <- !is.na(d)
model.misreport <- TRUE
} else {
model.misreport <- FALSE
d <- rep(NA, length(y))
d.na <- rep(TRUE, length(y))
}
if(!is.null(outcome) & outcome.model %in% c("logistic")) {
o <- data[, paste(outcome)]
trials <- rep(NA, length(y))
o.na <- !is.na(o)
} else if(!is.null(outcome) & outcome.model %in% c("binomial", "betabinomial")) {
o <- data[, paste(outcome)]
trials <- data[, paste(outcome.trials)]
o.na <- !is.na(o) & !is.na(trials)
} else {
o <- rep(NA, length(y))
trials <- rep(NA, length(y))
o.na <- rep(TRUE, length(y))
outcome.model <- "none"
}
if(!is.null(weights)) {
weight <- data[, paste(weights)]
weight.na <- !is.na(weight)
} else {
weight <- rep(1, length(y))
weight.na <- !is.na(weight)
}
y <- y[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
x.control <- as.matrix(x.control[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
x.sensitive <- as.matrix(x.sensitive[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
x.outcome <- as.matrix(x.outcome[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
x.misreport <- as.matrix(x.misreport[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
treat <- treat[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
d <- d[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
o <- o[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
trials <- trials[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
weight <- weight[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
n <- nrow(x.control)
# For testing whether arguments are correctly interpreted:
# return(list(y = y, x.control = x.control, x.sensitive = x.sensitive,
# x.outcome = x.outcome, x.misreport = x.misreport, treat = treat,
# d = d, o = o, trials = trials, weight = weight,
# control.constraint = control.constraint, misreport.treatment = misreport.treatment,
# model.misreport = model.misreport, outcome.model = outcome.model, se = se,
# sensitive.response = sensitive.response, J = J,
# par.control = par.control, par.sensitive = par.sensitive,
# par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport))}
# y <- model$y
# x.control <- model$x.control
# x.sensitive <- model$x.sensitive
# x.outcome <- model$x.outcome
# x.misreport <- model$x.misreport
# treat <- model$treat
# d <- model$d
# o <- model$o
# trials <- model$trials
# weight <- model$weight
# control.constraint <- model$control.constraint
# misreport.treatment <- model$misreport.treatment
# model.misreport <- model$model.misreport
# outcome.model <- model$outcome.model
# se <- model$se
# sensitive.response <- model$sensitive.response
# J <- model$J
# max.iter <- 2000
# par.control <- NULL
# par.sensitive <- NULL
# par.outcome <- NULL
# par.outcome.aux <- NULL
# par.misreport <- NULL
###########
# max.iter <- 5000
# verbose <- TRUE
# tolerance <- 1E-08
# j <- 1
# i <- 1
# n.runs <- 1
# get.boot <- 0
# get.data <- FALSE
# Draw a non-parametric boot-strap sample if
# requested by the bootListExperiment wrapper
if(get.boot > 0) {
boot.sample <- sample(1:length(weight), prob = weight, replace = TRUE)
y <- as.matrix(y)[boot.sample, , drop = FALSE]
x.control <- as.matrix(x.control)[boot.sample, , drop = FALSE]
x.sensitive <- as.matrix(x.sensitive)[boot.sample, , drop = FALSE]
x.outcome <- as.matrix(x.outcome)[boot.sample, , drop = FALSE]
x.misreport <- as.matrix(x.misreport)[boot.sample, , drop = FALSE]
treat <- as.matrix(treat)[boot.sample]
d <- as.matrix(d)[boot.sample, , drop = FALSE]
o <- as.matrix(o)[boot.sample, , drop = FALSE]
trials <- as.matrix(trials)[boot.sample, , drop = FALSE]
weight <- rep(1, length(y))
se <- FALSE
}
respondentType <- rep(as.character(NA), length(y))
if(model.misreport == TRUE) {
# Treat == 0, Y == control only, direct == Non-sensitive
respondentType[treat == 0 & d != sensitive.response] <- "Non-sensitive or misreport sensitive"
# Treat == 0, Y == control only, direct == Sensitive
respondentType[treat == 0 & d == sensitive.response] <- "Truthful sensitive"
# Treat == 1, Y == (J+1) or 0, direct == Non-sensitive
if(sensitive.response == 1) respondentType[treat == 1 & y == 0 & d != sensitive.response] <- "Non-sensitive"
if(sensitive.response == 0) respondentType[treat == 1 & y == (J + 1) & d != sensitive.response] <- "Non-sensitive"
# Treat == 1, 0 < Y < (J + 1), direct == Non-sensitive
respondentType[treat == 1 & y > 0 & y < (J + 1) & d != sensitive.response] <- "Non-sensitive or misreport sensitive"
# Treat == 1, Y == (J + 1) or 0, direct == Non-sensitive
if(sensitive.response == 1) respondentType[treat == 1 & y == (J + 1) & d != sensitive.response] <- "Misreport sensitive"
if(sensitive.response == 0) respondentType[treat == 1 & y == 0 & d != sensitive.response] <- "Misreport sensitive"
# Treat == 1, Y == (J + 1) or 0, direct == Sensitive
if(sensitive.response == 1) respondentType[treat == 1 & y == (J + 1) & d == sensitive.response] <- "Truthful sensitive"
if(sensitive.response == 0) respondentType[treat == 1 & y == 0 & d == sensitive.response] <- "Truthful sensitive"
# Treat == 1, Y == (J + 1) or 0, direct == Sensitive (not possible by assumption; error check for this)
if(sensitive.response == 1) respondentType[treat == 1 & y == 0 & d == sensitive.response] <- "Violates assumption"
if(sensitive.response == 0) respondentType[treat == 1 & y == (J + 1) & d == sensitive.response] <- "Violates assumption"
# Treat == 1, 0 < Y < (J + 1), direct == Sensitive
respondentType[treat == 1 & y > 0 & y < (J + 1) & d == sensitive.response] <- "Truthful sensitive"
} else {
# Treat == 1 0 < Y < (J + 1) is a "0 or a 1"
respondentType[treat == 1 & y > 0 & y < (J + 1)] <- "0 or 1"
# Treat == 0 Y == 0 is a 0 or a "1"
respondentType[treat == 0] <- "0 or 1"
# Treat == 1 Y == 0 is a "0"
respondentType[treat == 1 & y == 0] <- "0"
# Treat == 1 Y == (J + 1) is a "1"
respondentType[(treat == 1 & y == (J + 1))] <- "1"
}
if("Violates assumption" %in% respondentType) {
stop("\nSome observations violate the monotonicity assumption.")
}
# SET UP THE POSTERIOR PROBABILITIES
if(model.misreport == TRUE) {
w <- as.matrix(data.frame(as.numeric(respondentType %in% c("Non-sensitive or misreport sensitive", "Misreport sensitive")),
as.numeric(respondentType == "Truthful sensitive"),
as.numeric(respondentType %in% c("Non-sensitive or misreport sensitive", "Non-sensitive"))))
w <- w / apply(w, 1, sum)
colnames(w) <- c("Misreport sensitive", "Truthful sensitive", "Non-sensitive")
} else {
w <- as.matrix(data.frame(as.numeric(respondentType %in% c("1", "0 or 1")),
as.numeric(respondentType %in% c("0", "0 or 1"))))
w <- w / apply(w, 1, sum)
colnames(w) <- c("1", "0")
}
w <- log(w)
if(get.data == TRUE) {
estep.out <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment)
return(list(w = estep.out$w,
ll = estep.out$ll,
x.control = x.control,
x.sensitive = x.sensitive,
x.misreport = x.misreport,
x.outcome = x.outcome))
}
if(model.misreport == TRUE) {
if(misreport.treatment == TRUE) par.misreport <- rep(0, ncol(x.misreport) + 1) # +1 for treatment (consistency bias)
if(misreport.treatment == FALSE) par.misreport <- rep(0, ncol(x.misreport))
} else {
par.misreport <- NULL
}
if(is.null(par.sensitive)) par.sensitive <- rep(0, ncol(x.sensitive))
if(is.null(par.control)) {
if(control.constraint == "none" & model.misreport == FALSE) {
par.control <- rep(0, ncol(x.control) + 1)
} else if(control.constraint == "none" & model.misreport == TRUE) {
par.control <- rep(0, ncol(x.control) + 2)
} else if(control.constraint == "partial" & model.misreport == FALSE) {
stop("If not modeling misreporting, set argument control.constraint to 'none' or 'full'")
} else if(control.constraint == "partial" & model.misreport == TRUE) {
par.control <- rep(0, ncol(x.control) + 1)
} else if(control.constraint == "full") {
par.control <- rep(0, ncol(x.control))
}
}
if(is.null(par.outcome)) {
if(outcome.model != "none") {
if(outcome.constrained == TRUE) par.outcome <- rep(0, ncol(x.outcome) + 1)
if(outcome.constrained == FALSE) par.outcome <- rep(0, ncol(x.outcome) + 2)
} else {
par.outcome <- NULL
}
}
if(is.null(par.outcome.aux)) {
if(outcome.model %in% c("none", "logistic")) {
par.outcome.aux <- NULL
} else if(outcome.model == "betabinomial") {
par.outcome.aux <- list(rho = 0)
}
}
runs <- list()
# EXPECTATION MAXIMIZATION LOOP
for(j in 1:n.runs) {
if(j > 1 & verbose == TRUE) cat("\n")
logLikelihood <- rep(as.numeric(NA), max.iter)
# Get starting points on uniform(-2, 2)
while(TRUE) {
par.control <- runif(length(par.control), -2, 2)
par.sensitive <- runif(length(par.sensitive), -2, 2)
if(model.misreport == TRUE) par.misreport <- runif(length(par.misreport), -2, 2)
if(outcome.model != "none") par.outcome <- runif(length(par.outcome), -2, 2)
if(outcome.model != "none" & length(par.outcome.aux) > 0) par.outcome.aux <- runif(length(par.outcome.aux), 0, 1)
templl <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment)$ll
templl
if(!is.nan(templl) & templl > -Inf) break()
}
for(i in 1:max.iter) { # E-M loop
estep.out <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment)
w <- estep.out$w
logLikelihood[i] <- estep.out$ll
if(i > 1 & verbose == TRUE & get.boot == 0) {
cat("\r\rRun:", paste0(j, "/", n.runs), "Iter:", i,
"llik:", sprintf("%.2f", logLikelihood[i]),
"llik change:", sprintf("%.8f", (logLikelihood[i] - logLikelihood[i-1])),
"(tol =", paste0(as.character(tolerance), ") "))
}
if(i > 1 & verbose == TRUE & get.boot > 0) {
cat("\r\rBoot:", get.boot, "Run:", paste0(j, "/", n.runs), "Iter:", i,
"llik:", sprintf("%.2f", logLikelihood[i]),
"llik change:", sprintf("%.8f", (logLikelihood[i] - logLikelihood[i-1])),
"(tol =", paste0(as.character(tolerance), ") "))
}
if(i > 1 && (logLikelihood[i] - logLikelihood[i - 1]) < 0) {
stop("Log-likelihood increasing.")
}
if(i > 1 && (logLikelihood[i] - logLikelihood[i - 1]) < tolerance) {
break()
}
par.sensitive <- mstepSensitive(y = y, treat = treat, x.sensitive = x.sensitive, w = w,
d = d, sensitive.response = sensitive.response,
weight = weight, model.misreport = model.misreport)
par.control <- mstepControl(y = y, J = J, treat = treat, x.control = x.control, w = w,
d = d, sensitive.response = sensitive.response,
weight = weight, model.misreport = model.misreport,
control.constraint = control.constraint)
if(outcome.model != "none") {
outcome <- mstepOutcome(y = y, treat = treat, x.outcome = x.outcome, w = w,
d = d, sensitive.response = sensitive.response,
o = o, trials = trials, weight = weight,
model.misreport = model.misreport,
outcome.model = outcome.model,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint)
par.outcome <- outcome$coefs
par.outcome.aux <- outcome$coefs.aux
}
if(model.misreport == TRUE) {
par.misreport <- mstepMisreport(y = y, x.misreport = x.misreport,
w = w, treat = treat,
misreport.treatment = misreport.treatment,
weight = weight)
}
}
runs[[j]] <- list(logLikelihood = logLikelihood[i],
par.control = par.control,
par.sensitive = par.sensitive,
par.misreport = par.misreport,
par.outcome = par.outcome,
par.outcome.aux = par.outcome.aux)
}
if(verbose == TRUE) cat("\n")
max.ll <- which(sapply(runs, function(X) X$logLikelihood) == max(sapply(runs, function(X) X$logLikelihood)))
llik <- runs[[max.ll]]$logLikelihood
par.control <- runs[[max.ll]]$par.control
par.sensitive <- runs[[max.ll]]$par.sensitive
par.misreport <- runs[[max.ll]]$par.misreport
par.outcome <- runs[[max.ll]]$par.outcome
par.outcome.aux <- runs[[max.ll]]$par.outcome.aux
par <- c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux)
num <- c(length(par.control), length(par.sensitive), length(par.misreport), length(par.outcome), length(par.outcome.aux))
llik.wrapper <- function(par, num, y, w,
x.control, x.sensitive, x.outcome, x.misreport, treat, J,
d, sensitive.response, model.misreport,
o, trials, outcome.model,
weight, respondentType,
outcome.constrained,
control.constraint,
misreport.treatment) {
par.control <- par[1:num[1]]
par.sensitive <- par[(num[1]+1):sum(num[1:2])]
if(model.misreport == TRUE) {
par.misreport <- par[(sum(num[1:2])+1):sum(num[1:3])]
} else{
par.misreport <- NULL
}
if(outcome.model != "none") {
par.outcome <- par[(sum(num[1:3])+1):sum(num[1:4])]
if(outcome.model %in% c("betabinomial", "linear")) {
par.outcome.aux <- par[(sum(num[1:4])+1):sum(num[1:5])]
} else {
par.outcome.aux <- NULL
}
} else {
par.outcome <- NULL
}
llik <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment)$ll
return(llik)
}
# For testing:
# par = c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux)
# num = c(length(par.control), length(par.sensitive), length(par.misreport), length(par.outcome))
# J = J
# y = y
# treat = treat
# x = x
# x.misreport = x.misreport
# d = d
# sensitive.response = sensitive.response
# model.misreport = model.misreport
# o = o
# outcome.model = outcome.model
# weight = weight
# respondentType = respondentType
# control.constraint = control.constraint
# llik.wrapper(par = par, num = num, y = y,
# x.control = x.control, x.sensitive = x.sensitive,
# x.outcome = x.outcome, x.misreport = x.misreport, treat = treat,
# J = J, d = d, sensitive.response = sensitive.response,
# model.misreport = model.misreport, o = o, outcome.model = outcome.model,
# outcome.constrained = outcome.constrained, weight = weight, respondentType = respondentType,
# control.constraint = control.constraint)
if(se == TRUE & all(weight == 1)) {
# hess <- optimHess(c(par.control, par.sensitive, par.misreport, par.outcome), obs.llik.wrapper,
# num = c(length(par.control), length(par.sensitive), length(par.misreport), length(par.outcome)),
# J = J, y = y, treat = treat,
# x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport,
# d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
# o = o, outcome.model = outcome.model,
# outcome.constrained = outcome.constrained,
# weight = weight,
# respondentType = respondentType,
# control.constraint = control.constraint,
# control = list(reltol = 1E-16))
num <- c(length(par.control),
length(par.sensitive),
length(par.misreport),
length(par.outcome),
length(par.outcome.aux))
hess <- numDeriv::hessian(llik.wrapper, c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux),
num = num, J = J, y = y, w = w, treat = treat,
x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, outcome.model = outcome.model,
outcome.constrained = outcome.constrained,
weight = weight,
respondentType = respondentType,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment,
method.args = list(zero.tol = 1e-10))
vcov.mle <- solve(-hess)
se.mle <- sqrt(diag(vcov.mle))
se.control <- se.mle[1:num[1]]
names(se.control) <- names(par.control)
se.sensitive <- se.mle[(num[1]+1):sum(num[1:2])]
names(se.sensitive) <- names(par.sensitive)
if(model.misreport == TRUE) {
se.misreport <- se.mle[(sum(num[1:2])+1):sum(num[1:3])]
names(se.misreport) <- names(par.misreport)
} else {
se.misreport <- NULL
}
if(outcome.model != "none") {
se.outcome <- se.mle[(sum(num[1:3])+1):sum(num[1:4])]
names(se.outcome) <- names(par.outcome)
if(outcome.model %in% c("linear", "betabinomial")) {
se.outcome.aux <- se.mle[(sum(num[1:4])+1):sum(num[1:5])]
names(se.outcome.aux) <- names(par.outcome.aux)
} else {
se.outcome.aux <- NULL
}
} else {
se.outcome <- NULL
se.outcome.aux <- NULL
}
} else {
se.control <- se.sensitive <- se.misreport <- se.outcome <- se.outcome.aux <- vcov.mle <- NULL
if(se == TRUE) {
warning("Standard errors are not implemented for models with survey weights.")
se <- FALSE
}
}
return.object <- list("par.control" = par.control,
"par.sensitive" = par.sensitive,
"par.misreport" = par.misreport,
"par.outcome" = par.outcome,
"par.outcome.aux" = par.outcome.aux,
"df" = n - length(c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux)),
"se.sensitive" = se.sensitive,
"se.control" = se.control,
"se.misreport" = se.misreport,
"se.outcome" = se.outcome,
"se.outcome.aux" = se.outcome.aux,
"vcov.mle" = vcov.mle,
"w" = exp(w), # Convert log posterior predicted probabilities
"data" = data,
"direct" = direct,
"treatment" = treatment,
"model.misreport" = model.misreport,
"outcome.model" = outcome.model,
"outcome.constrained" = outcome.constrained,
"control.constraint" = control.constraint,
"misreport.treatment" = misreport.treatment,
"weights" = weights,
"formula" = formula,
"formula.control" = formula.control,
"formula.sensitive" = formula.sensitive,
"formula.misreport" = formula.misreport,
"formula.outcome" = formula.outcome,
"sensitive.response" = sensitive.response,
"xlevels" = xlevels,
"llik" = llik,
"n" = n,
"J" = J,
"se" = se,
"runs" = runs,
"call" = function.call,
"boot" = FALSE)
class(return.object) <- "listExperiment"
return(return.object)
}
#' List experiment regression with bootstrapped standard errors
#'
#' A wrapper function that makes repeated calls to \code{\link{listExperiment}}
#' to calculate parameter estimates and standard errors through non-parametric boot-strapping.
#'
#' @param formula An object of class "\code{\link{formula}}": a symbolic description of the model to be fitted.
#' @param data A data frame containing the variables to be used in the model.
#' @param treatment A string indicating the name of the treatment indicator in the data. This variable must be coded as a binary, where 1 indicates assignment to treatment and 0 indicates assignment to control.
#' @param J An integer indicating the number of control items in the list experiment.
#' @param direct A string indicating the name of the direct question response in the data. The direct question must be coded as a binary variable. If NULL (default), a misreport sub-model is not fit.
#' @param sensitive.response A value 0 or 1 indicating whether the response that is considered sensitive in the list experiment/direct question is 0 or 1.
#' @param outcome A string indicating the variable name in the data to use as the outcome in an outcome sub-model. If NULL (default), no outcome sub-model is fit. [\emph{experimental}]
#' @param outcome.trials An integer indicating the number of trials in a binomial/betabinomial model if both an outcome sub-model is used and if the argument \code{outcome.model} is set to "binomial" or "betabinomial". [\emph{experimental}]
#' @param outcome.model A string indicating the model type to fit for the outcome sub-model ("logistic", "binomial", "betabinomial"). [\emph{experimental}]
#' @param outcome.constrained A logical value indicating whether to constrain U* = 0 in the outcome sub-model. Defaults to TRUE. [\emph{experimental}]
#' @param control.constraint A string indicating the constraint to place on Z* and U* in the control-items sub-model:
#' \describe{
#' \item{"none" (default)}{Estimate separate parameters for Z* and U*.}
#' \item{"partial"}{Constrain U* = 0.}
#' \item{"full"}{Constrain U* = Z* = 0.}
#' }
#' @param misreport.treatment A logical value indicating whether to include a parameter for the treatment indicator in the misreport sub-model. Defaults to TRUE.
#' @param weights A string indicating the variable name of survey weights in the data (note: standard errors are not currently output when survey weights are used).
#' @param se A logical value indicating whether to calculate standard errors. Defaults to TRUE.
#' @param tolerance The desired accuracy for EM convergence. The EM loop breaks after the change in the log-likelihood is less than the value of \code{tolerance}. Defaults to 1e-08.
#' @param max.iter The maximum number of iterations for the EM algorithm. Defaults to 10000.
#' @param n.runs The total number of times that the EM algorithm is run (can potentially help avoid local maxima). Defaults to 1.
#' @param verbose A logical value indicating whether to print information during model fitting. Defaults to TRUE.
#' @param get.data For internal use. Used by wrapper function \code{\link{bootListExperiment}}.
#' @param par.control A vector of starting parameters for the control-items sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2).
#' @param par.sensitive A vector of starting parameters for the sensitive-item sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2).
#' @param par.misreport A vector of starting parameters for the misreport sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2).
#' @param par.outcome A vector of starting parameters for the outcome sub-model. Must be in the order of the parameters in the resulting regression output. If NULL (default), randomly generated starting points are used, drawn from uniform(-2, 2). [experimental]
#' @param par.outcome.aux A vector of starting parameters for the outcome sub-model in which \code{outcome.model} is "betabinomial". i.e. c(alpha, beta). If NULL (default), randomly generated starting points are used, drawn from uniform(0, 1). [experimental]
#' @param formula.control An object of class "\code{\link{formula}}" used to specify a control-items sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2)
#' @param formula.sensitive An object of class "\code{\link{formula}}" used to specify a sensitive-item sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2)
#' @param formula.misreport An object of class "\code{\link{formula}}" used to specify a misreport sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2)
#' @param formula.outcome An object of class "\code{\link{formula}}" used to specify an outcome sub-model that is different from that given in \code{formula}. (e.g. ~ x1 + x2) [\emph{experimental}]
#' @param boot.iter The number of boot strap samples to generate.
#' @param parallel A logical value indicating whether to run bootstraping in parallel on a multi-core computer.
#' @param n.cores The number of cores/threads on which to generate bootstrap samples (when \code{parallel} = TRUE). Defaults to 2.
#' @param cluster An optional cluster object using makeCluster() from the \code{parallel} package (useful if running on an MPI server).
#'
#' @details \code{bootListExperiment} is a wrapper for the function
#' \code{listExperiment} that allows researchers to fit a bootstrapped
#' model. The arguments for this function include those for the
#' \code{\link{listExperiment}} function, in addition to a small number
#' of arguments specific to the bootstrap.
#'
#' @return \code{listExperiment} returns an object of class "listExperiment".
#' A summary of this object is given using the \code{\link{summary.listExperiment}}
#' function. All components in the "listExperiment" class are listed below.
#' @slot par.control A named vector of coefficients from the control-items sub-model.
#' @slot par.sensitive A named vector of coefficients from the sensitive-item sub-model.
#' @slot par.misreport A named vector of coefficients from the misreport sub-model.
#' @slot par.outcome A named vector of coefficients from the outcome sub-model.
#' @slot par.outcome.aux A named vector of (auxiliary) coefficients from the outcome sub-model (if \code{outcome.model} = "betabinomial").
#' @slot df Degrees of freedom.
#' @slot se.sensitive Standard errors for parameters in the sensitive-item sub-model.
#' @slot se.control Standard errors for parameters in the control-items sub-model.
#' @slot se.misreport Standard errors for parameters in the misreport sub-model.
#' @slot se.outcome Standard errors for parameters in the outcome sub-model.
#' @slot se.outcome.aux Standard errors for the auxiliary parameters in the outcome sub-model (if \code{outcome.model} = "betabinomial").
#' @slot vcov.mle Variance-covariance matrix.
#' @slot w The matrix of posterior predicted probabilities for each observation in the data used for model fitting.
#' @slot data The data frame used for model fitting.
#' @slot direct The string indicating the variable name of the direct question.
#' @slot treatment The string indicating the variable name of the treatment indicator.
#' @slot model.misreport A logical value indicating whether a misreport sub-model was fit.
#' @slot outcome.model The type of model used as the outcome sub-model.
#' @slot outcome.constrained A logical value indicating whether the parameter U* was constrained to 0 in the outcome sub-model.
#' @slot control.constraint A string indicating the constraints placed on the parameters Z* and U* in the control-items sub-model.
#' @slot misreport.treatment A logical value indicating whether a treatment indicator was included in the misreport sub-model.
#' @slot weights A string indicating the variable name of the survey weights.
#' @slot formula The model formula.
#' @slot formula.control The model specification of the control-items sub-model.
#' @slot formula.sensitive The model specification of the sensitive-item sub-model.
#' @slot formula.misreport The model specification of the misreport sub-model.
#' @slot formula.outcome The model specification of the outcome sub-model.
#' @slot sensitive.response The value 0 or 1 indicating the response to the list experiment/direct question that is considered sensitive.
#' @slot xlevels The factor levels of the variables used in the model.
#' @slot llik The model log-likelihood.
#' @slot n The sample size of the data used for model fitting (this value excludes rows removed through listwise deletion).
#' @slot J The number of control items in the list experiment.
#' @slot se A logical value indicating whether standard errors were calculated.
#' @slot runs The parameter estimates from each run of the EM algorithm (note: the parameters that result in the highest log-likelihood are used as the model solution).
#' @slot call The method call.
#' @slot boot A logical value indicating whether non-parametric bootstrapping was used to calculate model parameters and standard errors.
#'
#' @references Eady, Gregory. 2017 "The Statistical Analysis of Misreporting on Sensitive Survey Questions."
#' @references Imai, Kosuke. 2011. "Multivariate Regression Analysis for the Item Count Technique." \emph{Journal of the American Statistical Association} 106 (494): 407-416.
#'
#' @examples
#'
#' ## Simulated list experiment and direct question
#' n <- 10000
#' J <- 4
#'
#' # Covariates
#' x <- cbind(intercept = rep(1, n), continuous1 = rnorm(n),
#' continuous2 = rnorm(n), binary1 = rbinom(n, 1, 0.5))
#'
#' treatment <- rbinom(n, 1, 0.5)
#'
#' # Simulate Z*
#' param_sensitive <- c(0.25, -0.25, 0.5, 0.25)
#' prob_sensitive <- plogis(x %*% param_sensitive)
#' true_belief <- rbinom(n, 1, prob = prob_sensitive)
#'
#' # Simulate whether respondent misreports (U*)
#' param_misreport <- c(-0.25, 0.25, -0.5, 0.5)
#' prob_misreport <- plogis(x %*% param_misreport) * true_belief
#' misreport <- rbinom(n, 1, prob = prob_misreport)
#'
#' # Simulate control items Y*
#' param_control <- c(0.25, 0.25, -0.25, 0.25, U = -0.5, Z = 0.25)
#' prob.control <- plogis(cbind(x, misreport, true_belief) %*% param_control)
#' control_items <- rbinom(n, J, prob.control)
#'
#' # List experiment and direct question responses
#' direct <- true_belief
#' direct[misreport == 1] <- 0
#' y <- control_items + true_belief * treatment
#'
#' A <- data.frame(y, direct, treatment,
#' continuous1 = x[, "continuous1"],
#' continuous2 = x[, "continuous2"],
#' binary1 = x[, "binary1"])
#'
#' \dontrun{
#' # Note: substantial computation time
#' model.sim <- bootListExperiment(y ~ continuous1 + continuous2 + binary1,
#' data = A, treatment = "treatment",
#' direct = "direct",
#' J = 4, control.constraint = "none",
#' sensitive.response = 1,
#' boot.iter = 500, parallel = TRUE, n.cores = 2)
#' summary(model.sim, digits = 3)
#' }
#'
#' @export
#'
bootListExperiment <- function(formula, data, treatment, J,
direct = NULL, sensitive.response = NULL,
outcome = NULL, outcome.trials = NULL, outcome.model = "logistic",
outcome.constrained = TRUE, control.constraint = "partial",
misreport.treatment = TRUE,
weights = NULL, se = TRUE, tolerance = 1E-8, max.iter = 5000,
n.runs = 1, verbose = TRUE, get.data = FALSE,
par.control = NULL, par.sensitive = NULL, par.misreport = NULL,
par.outcome = NULL, par.outcome.aux = NULL,
formula.control = NULL, formula.sensitive = NULL,
formula.misreport = NULL, formula.outcome = NULL,
boot.iter = 1000, parallel = FALSE, n.cores = 2, cluster = NULL) {
function.call <- match.call()
args.call <- as.list(function.call)[-1]
args.call$se <- FALSE
args.call$get.boot <- 1
args.call <- lapply(args.call, eval)
data <- args.call$data
args.call$data <- as.name("data")
# For testing:
# return(args.call)}
if(parallel == FALSE) {
boot.out <- list()
for(i in 1:boot.iter) {
args.call$get.boot <- i
boot.out[[i]] <- do.call(listExperiment, args.call)
}
}
if(parallel == TRUE) {
args.call$verbose <- FALSE
cat("Running bootstrap in parallel on ", n.cores, " cores/threads (", parallel::detectCores(), " available)...\n", sep = ""); Sys.sleep(0.2)
if(!is.null(cluster)) cl <- cluster
if(is.null(cluster)) cl <- parallel::makeCluster(n.cores)
parallel::clusterExport(cl,
list("args.call", "data", "listExperiment", "logAdd", "estep",
"mstepControl", "mstepSensitive", "mstepMisreport", "mstepOutcome"),
envir = environment())
boot.out <- parallel::parLapply(cl, 1:boot.iter, function(x) do.call(listExperiment, args.call))
parallel::stopCluster(cl)
}
getPars <- function(varName) {
X <- do.call(rbind, sapply(boot.out, function(x) x[varName]))
cov.var <- cov(X)
par.var <- colMeans(X)
se.var <- as.vector(as.matrix(sqrt(diag(cov.var))))
names(se.var) <- row.names(cov.var)
return(list(par = par.var, se = se.var))
}
# Control items
par.control <- getPars("par.control")$par
se.control <- getPars("par.control")$se
# Sensitive items
par.sensitive <- getPars("par.sensitive")$par
se.sensitive <- getPars("par.sensitive")$se
# Misreport
if(!is.null(boot.out[[1]]$par.misreport)) {
par.misreport <- getPars("par.misreport")$par
se.misreport <- getPars("par.misreport")$se
} else {
par.misreport <- se.misreport <- NULL
}
# Outcome
if(!is.null(boot.out[[1]]$par.outcome)) {
par.outcome <- getPars("par.outcome")$par
se.outcome <- getPars("par.outcome")$se
} else {
par.outcome <- se.outcome <- NULL
}
# Outcome (auxiliary parameters)
if(!is.null(boot.out[[1]]$outcome.model.aux)) {
par.outcome <- getPars("par.outcome.aux")$par
se.outcome <- getPars("par.outcome.aux")$se
} else {
par.outcome.aux <- se.outcome.aux <- NULL
}
se <- TRUE
# Get log-likelihood and posterior probabilities with bootstrap estimates
args.call$get.boot <- 0
args.call$get.data <- TRUE
args.call$par.control <- par.control
args.call$par.sensitive <- par.sensitive
args.call$par.misreport <- par.misreport
args.call$par.outcome <- par.outcome
args.call$par.outcome.aux <- par.outcome.aux
llik <- do.call(listExperiment, args.call)$ll
w <- do.call(listExperiment, args.call)$w
return.object <- boot.out[[1]] # Use the first iteration object as a container
return.object$par.control <- par.control
return.object$par.sensitive <- par.sensitive
return.object$par.misreport <- par.misreport
return.object$par.outcome <- par.outcome
return.object$par.outcome.aux <- par.outcome.aux
return.object$df <- return.object$n - length(c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux))
return.object$se.control <- se.control
return.object$se.sensitive <- se.sensitive
return.object$se.misreport <- se.misreport
return.object$se.outcome <- se.outcome
return.object$se.outcome.aux <- se.outcome.aux
return.object$vcov.model <- NULL
return.object$data <- data
return.object$se <- TRUE
return.object$w <- exp(w) # Convert log posterior predicted probabilities
return.object$llik <- llik
return.object$call <- function.call
return.object$boot.iter <- boot.iter
return.object$boot.out <- boot.out
return.object$boot <- TRUE
class(return.object) <- "listExperiment"
return(return.object)
}
#' Predict method for the list experiment
#'
#' Obtains predictions from a fitted list experiment model of the class \code{listExperiment}.
#'
#' @param object Object of class "listExperiment"
#' @param newdata An optional data frame from which to calculate predictions.
#' @param treatment.misreport Value of the treatment variable covariate in the misreport sub-model (if included in the model).
#' \describe{
#' \item{0}{treatment indicator in the misreport sub-model is set to 0 for all individuals (default).}
#' \item{1}{treatment indicator in the misreport sub-model is set to 1 for all individuals.}
#' \item{"observed"}{treatment indicator in the misreport sub-model is set to the observed treatment value.}
#' }
#' @param par.control An optional set of control-items sub-model parameters to use in place of those from the fitted model.
#' @param par.sensitive An optional set of sensitive-item sub-model parameters to use in place of those from the fitted model.
#' @param par.misreport An optional set of misreport sub-model parameters to use in place of those from the fitted model.
#' @param ... Additional arguments
#'
#' @details If \code{newdata} is omitted, predictions will be made with
#' the data used for model fitting.
#'
#' @slot z.hat Predicted probability of answering affirmatively to the sensitive item in the list experiment.
#' @slot u.hat Predicted probability of misreporting (assuming respondent holds the sensitive belief).
#'
#' @references Eady, Gregory. 2017 "The Statistical Analysis of Misreporting on Sensitive Survey Questions."
#'
#' @examples
#'
#' data(gender)
#'
#' \dontrun{
#' # Note: substantial computation time
#' model.gender <- listExperiment(y ~ gender + ageGroup + education +
#' motherTongue + region + selfPlacement,
#' data = gender, J = 4,
#' treatment = "treatment", direct = "direct",
#' control.constraint = "none",
#' sensitive.response = 0,
#' misreport.treatment = TRUE)
#' predict(model.gender, treatment.misreport = 0)
#' }
#'
#' @export
predict.listExperiment <- function(object, newdata = NULL,
treatment.misreport = 0,
par.control = NULL,
par.sensitive = NULL,
par.misreport = NULL,
...) {
if(!is.null(par.control)) object$par.control <- par.control
if(!is.null(par.sensitive)) object$par.sensitive <- par.sensitive
if(!is.null(par.misreport)) object$par.misreport <- par.misreport
if(is.null(newdata)) {
data <- object$data
} else data <- newdata
if(as.character(object$formula[[2]]) %in% names(data)) {
y <- data[, paste(object$formula[[2]])]
} else stop(paste0("The list experiment response ", as.character(object$formula[[2]]), " not found in data."))
if(treatment.misreport == "observed") {
if(object$treatment %in% names(data)) {
treatment <- data[, paste(object$treatment)]
} else {
stop(paste0("Argument treatment.misreport was set to \"observed\", but treatment variable \"", object$treatment, "\" is not in the data."))
}
} else {
treatment <- rep(treatment.misreport, nrow(data))
}
if(!is.null(object$direct)) {
if(object$direct %in% names(data)) {
d <- data[, paste(object$direct)]
} else {
stop(paste0("Direct question variable", object$direct, "\" is not in the data."))
}
} else{
d <- rep(NA, nrow(data))
}
if(!is.null(object$outcome)) {
if(object$outcome %in% names(data)) {
o <- data[, paste(object$outcome)]
} else {
stop(paste0("Outcome variable", object$outcome, "\" is not in the data."))
}
} else {
o <- rep(NA, nrow(data))
}
if(all(all.vars(object$formula.sensitive)[-1] %in% names(data))) {
x.sensitive <- model.matrix(object$formula.sensitive[-2], data = model.frame(~ ., data, na.action = na.pass, xlev = object$xlevels))
} else {
stop(paste0("Not all variables used in the sensitive-item sub-model are available in the data"))
}
if(!is.null(object$par.misreport)) {
if(all(all.vars(object$formula.misreport)[-1] %in% names(data))) {
x.misreport <- model.matrix(object$formula.misreport[-2], data = model.frame(~ ., data, na.action = na.pass, xlev = object$xlevels))
} else {
stop(paste0("Not all variables used in the misreport sub-model are available in the data"))
}
} else {
x.misreport <- rep(NA, nrow(data))
}
# Prediction for Z*
z.hat <- as.numeric(plogis(x.sensitive %*% object$par.sensitive))
# Prediction for U*
if(object$model.misreport == TRUE) {
if(object$misreport.treatment == TRUE) {
u.hat <- as.numeric(plogis(as.matrix(data.frame(x.misreport, treatment)) %*% object$par.misreport))
} else {
u.hat <- as.numeric(plogis(as.matrix(data.frame(x.misreport)) %*% object$par.misreport))
}
} else u.hat <- NULL
return(list(z.hat = z.hat, u.hat = u.hat))
}
#' Object summary of the listExperiment class
#'
#' Summarizes results from a list experiment regression fit using \code{\link{listExperiment}} or \code{\link{bootListExperiment}}.
#'
#' @param object Object of class "listExperiment".
#' @param digits Number of significant digits to print.
#' @param ... Additional arguments.
#'
#' @details \code{summary.listExperiment} summarizes the information contained
#' in a listExperiment object for each list experiment regression sub-model.
#'
#' @references Eady, Gregory. 2017 "The Statistical Analysis of Misreporting on Sensitive Survey Questions."
#'
#' @examples
#' data(gender)
#'
#' \dontrun{
#' # Note: substantial computation time
#' model.gender <- listExperiment(y ~ gender + ageGroup + education +
#' motherTongue + region + selfPlacement,
#' data = gender, J = 4,
#' treatment = "treatment", direct = "direct",
#' control.constraint = "none",
#' sensitive.response = 0,
#' misreport.treatment = TRUE)
#' summary(model.gender)
#' }
#'
#' @export
summary.listExperiment <- function(object, digits = 4, ...) {
cat("\nList experiment sub-models\n\n")
cat("Call: ")
print(object$call)
if(object$se == TRUE) {
cat("\nCONTROL ITEMS Pr(Y* = y)\n")
matrix.control <- cbind(round(object$par.control, digits),
round(object$se.control, digits),
round(object$par.control/object$se.control, digits),
round(2 * pnorm(abs(object$par.control/object$se.control), lower.tail = FALSE), digits))
colnames(matrix.control) <- c("est.", "se", "z", "p")
print(formatC(matrix.control, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
cat("\nSENSITIVE ITEM Pr(Z* = 1)\n")
matrix.sensitive <- cbind(round(object$par.sensitive, digits),
round(object$se.sensitive, digits),
round(object$par.sensitive/object$se.sensitive, digits),
round(2 * pnorm(abs(object$par.sensitive/object$se.sensitive), lower.tail = FALSE), digits))
colnames(matrix.sensitive) <- c("est.", "se", "z", "p")
print(formatC(matrix.sensitive, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
if(object$model.misreport == TRUE) {
cat("\nMISREPORT Pr(U* = 1)\n")
matrix.misreport <- cbind(round(object$par.misreport, digits),
round(object$se.misreport, digits),
round(object$par.misreport/object$se.misreport, digits),
round(2 * pnorm(abs(object$par.misreport/object$se.misreport), lower.tail = FALSE), digits))
colnames(matrix.misreport) <- c("est.", "se", "z", "p")
print(formatC(matrix.misreport, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
}
if(object$outcome.model != "none") {
cat("\nOUTCOME\n")
matrix.outcome <- cbind(round(object$par.outcome, digits),
round(object$se.outcome, digits),
round(object$par.outcome/object$se.outcome, digits),
round(2 * pnorm(abs(object$par.outcome/object$se.outcome), lower.tail = FALSE), digits))
colnames(matrix.outcome) <- c("est.", "se", "z", "p")
print(formatC(matrix.outcome, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---")
}
} else if(object$se == FALSE) {
cat("\nCONTROL ITEMS Pr(Y* = y)\n")
matrix.control <- cbind(round(object$par.control, digits))
colnames(matrix.control) <- c("est.")
print(formatC(matrix.control, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
cat("\nSENSITIVE ITEM Pr(Z* = 1)\n")
matrix.sensitive <- cbind(round(object$par.sensitive, digits))
colnames(matrix.sensitive) <- c("est.")
print(formatC(matrix.sensitive, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
if(object$model.misreport == TRUE) {
cat("\nMISREPORT Pr(U* = 1)\n")
matrix.misreport <- cbind(round(object$par.misreport, digits))
colnames(matrix.misreport) <- c("est.")
print(formatC(matrix.misreport, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
}
if(object$outcome.model != "none") {
cat("\nOUTCOME\n")
matrix.outcome <- cbind(round(object$par.outcome, digits))
colnames(matrix.outcome) <- c("est.")
print(formatC(matrix.outcome, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---")
}
}
if(object$boot == TRUE) {
cat("\nStandard errors calculated by non-parametric bootstrap (", format(object$boot.iter, big.mark = ","), " draws).", sep = "")
}
cat("\nObservations:", format(object$n, big.mark = ","))
# if(nrow(object$data)-object$n != 0)
cat(" (", format(nrow(object$data)-object$n, big.mark = ","), " of ", format(nrow(object$data), big.mark = ","), " observations removed due to missingness)", sep = "")
cat("\nLog-likelihood", object$llik)
}
#' Print object summary of listExperiment class
#'
#' Calls \code{\link{summary.listExperiment}}.
#'
#' @param x Object of class "listExperiment".
#' @param ... Additional arguments.
#'
#' @details Prints the object summary of the listExperiment class by calling the
#' \code{\link{summary.listExperiment}} function.
#'
#' @export
print.listExperiment <- function(x, ...) {
summary.listExperiment(x, ...)
}
# simPredict <- function(object, var, values, newdata = NULL, treatment.misreport = 0, n.sims = 1000, weight = NULL) {
# ### Get (new)data
# if(is.null(newdata)) {
# data <- object$data
# } else data <- newdata
# if(object$treatment %in% names(data)) {
# treat <- data[, paste(object$treatment)]
# } else {
# treat <- NULL
# }
# if(treatment.misreport == "observed") {
# if(!is.null(treat)) {
# treatment.predict <- treat
# } else {
# stop(paste0("treatment.misreport set to \"observed\", but treatment variable \"", object$treatment, "\" not found in data"))
# }
# } else treatment.predict <- treatment.misreport
# if(all(all.vars(object$formula.control)[-1] %in% names(data))) {
# x.control <- model.matrix(object$formula.control[-2], data = data, na.action = na.pass)
# } else {
# x.control <- matrix(NA, nrow = nrow(data), ncol = length(object$par.control))
# }
# if(all(all.vars(object$formula.sensitive)[-1] %in% names(data))) {
# x.sensitive <- model.matrix(object$formula.sensitive[-2], data = data, na.action = na.pass)
# } else{
# x.sensitive <- matrix(NA, nrow = nrow(data), ncol = length(object$par.sensitive))
# }
# if(!is.null(object$par.misreport) & all(all.vars(object$formula.misreport)[-1] %in% names(data))) {
# x.misreport <- model.matrix(object$formula.misreport[-2], data = data, na.action = na.pass)
# } else {
# x.misreport <- matrix(NA, nrow = nrow(data), ncol = length(object$par.misreport))
# }
# if(!is.null(object$par.outcome) & all(all.vars(object$formula.outcome)[-1] %in% names(data))) {
# x.outcome <- model.matrix(object$formula.outcome[-2], data = data, na.action = na.pass)
# } else {
# x.outcome <- matrix(NA, nrow = nrow(data), ncol = length(object$par.outcome))
# }
# ### Simulate coefficients
# coefs <- c(object$par.control, object$par.sens, object$par.misreport)
# par_sim <- mvtnorm::rmvnorm(n.sims, coefs, object$vcov.mle)
# # Coefficients for control-items sub-model
# par_sim_control <- par_sim[, 1:length(object$par.control)]
# # Coefficients for sensitive-item sub-model
# par_sim_sensitive <- par_sim[, (length(object$par.control) + 1):(length(coefs) - length(object$par.misreport))]
# # Coefficients for misreport sub-model
# par_sim_misreport <- par_sim[, (length(coefs) - length(object$par.misreport) + 1):length(coefs)]
# O <- data.frame(var = var, value = values,
# mean.sensitive = NA, lower.sensitive = NA, upper.sensitive = NA,
# mean.diff.sensitive = NA, lower.diff.sensitive = NA, upper.diff.sensitive = NA,
# mean.misreport = NA, lower.misreport = NA, upper.misreport = NA,
# mean.diff.misreport = NA, lower.diff.misreport = NA, upper.diff.misreport = NA)
# x.sensitive[, which(colnames(x.sensitive) == var)] <- values[1]
# x.misreport[, which(colnames(x.misreport) == var)] <- values[1]
# x.sensitive.1 <- x.sensitive
# x.misreport.1 <- x.misreport
# for(i in 1:length(values)) {
# cat(paste0("\rSimulating for ", var, " = ", values[i], " "))
# x.sensitive[, which(colnames(x.sensitive) == var)] <- values[i]
# x.misreport[, which(colnames(x.misreport) == var)] <- values[i]
# out_sensitive <- apply(par_sim_sensitive, 1, function(x) mean(plogis(x.sensitive %*% x)))
# out_sensitive.diff <- apply(par_sim_sensitive, 1, function(x) mean(plogis(x.sensitive %*% x) - plogis(x.sensitive.1 %*% x)))
# out_misreport <- apply(par_sim_misreport, 1, function(x) mean(plogis(x.misreport %*% x)))
# out_misreport.diff <- apply(par_sim_misreport, 1, function(x) mean(plogis(x.misreport %*% x) - plogis(x.misreport.1 %*% x)))
# O$mean.sensitive[i] <- mean(out_sensitive)
# O$lower.sensitive[i] <- quantile(out_sensitive, 0.05)
# O$upper.sensitive[i] <- quantile(out_sensitive, 0.95)
# O$mean.diff.sensitive[i] <- mean(out_sensitive.diff)
# O$lower.diff.sensitive[i] <- quantile(out_sensitive.diff, 0.05)
# O$upper.diff.sensitive[i] <- quantile(out_sensitive.diff, 0.95)
# O$mean.misreport[i] <- mean(out_misreport)
# O$lower.misreport[i] <- quantile(out_misreport, 0.05)
# O$upper.misreport[i] <- quantile(out_misreport, 0.95)
# O$mean.diff.misreport[i] <- mean(out_sensitive.diff)
# O$lower.diff.misreport[i] <- quantile(out_misreport.diff, 0.05)
# O$upper.diff.misreport[i] <- quantile(out_misreport.diff, 0.95)
# }
# ggplot(O, aes(x = value, y = mean.sensitive,
# ymin = lower.sensitive, ymax = upper.sensitive)) +
# my.theme() +
# geom_ribbon(fill = "grey94", color = "grey90", size = 0.25) +
# geom_line()
# }
|
8e1ee736c938ecda57e58eac8e15895f725bded3
|
429043e07554ff6f860fe2c6507d2670519b6b1f
|
/R/refactor.R
|
7dc6c1faf911b59b68cb2c6496438c75240a396f
|
[] |
no_license
|
nicolaroberts/nrmisc
|
d393402f41e5620c1ccda8f2928b5bda38650241
|
ffc82d1d6192d2d80fd20f65e962c026b868ece1
|
refs/heads/master
| 2020-04-05T08:08:40.120753
| 2018-08-01T13:22:17
| 2018-08-01T13:22:17
| 42,860,158
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 305
|
r
|
refactor.R
|
#' Refactor factor variables in a data.frame
#'
#'
#' @param df data.frame
#'
#' @return A data.frame with each factor variable re-factored (old unused levels are dropped)
#'
#' @export
#'
refactor <- function(df){
cat <- sapply(df, is.factor)
df[cat] <- lapply(df[cat], factor)
return(df)
}
|
631fd3400bb586f19c3d118d00f2b5a8e6708648
|
986b80d564588d1d702aac13e2eb24a91cacfc05
|
/man/write_fitted_parameters.Rd
|
d609aa4272557405802b8bd1e73b30991ba9121c
|
[] |
no_license
|
strathclyde-marine-resource-modelling/StrathE2E2
|
592b73968d3f19513d3fffb435916605f7c47237
|
a5f5c0507e92cd8c48afc75c14bffa91d4132cc5
|
refs/heads/master
| 2020-05-18T06:33:23.756987
| 2019-06-20T15:43:55
| 2019-06-20T15:43:55
| 184,236,707
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 467
|
rd
|
write_fitted_parameters.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/write_fitted_parameters.R
\name{write_fitted_parameters}
\alias{write_fitted_parameters}
\title{Save current set of fitted parameters to file}
\usage{
write_fitted_parameters(model, parhistory)
}
\arguments{
\item{parhistory}{parameter set history}
\item{model.path}{path to model}
}
\value{
list of fitted model parameters
}
\description{
Save current set of fitted parameters to file
}
|
a992998522823e96047a02ca19cb2afb60d7aadc
|
87760ba06690cf90166a879a88a09cd2e64f3417
|
/R/modeltime-accuracy.R
|
e789c7c0e4d9d164f095f339513d0aa4384ac419
|
[
"MIT"
] |
permissive
|
topepo/modeltime
|
1189e5fe6c86ee3a70aec0f100387a495f8add5f
|
bff0b3784d1d8596aa80943b221eb621481534e1
|
refs/heads/master
| 2022-12-27T07:11:58.979836
| 2020-10-08T16:07:27
| 2020-10-08T16:07:27
| 289,933,114
| 1
| 0
|
NOASSERTION
| 2020-08-24T13:17:10
| 2020-08-24T13:17:10
| null |
UTF-8
|
R
| false
| false
| 6,563
|
r
|
modeltime-accuracy.R
|
# MODELTIME ACCURACY ----
#' Calculate Accuracy Metrics
#'
#' This is a wrapper for `yardstick` that simplifies time series regression accuracy metric
#' calculations from a fitted `workflow` (trained workflow) or `model_fit` (trained parsnip model).
#'
#' @param object A Modeltime Table
#' @param new_data A `tibble` to predict and calculate residuals on.
#' If provided, overrides any calibration data.
#' @param metric_set A `yardstick::metric_set()` that is used to summarize one or more
#' forecast accuracy (regression) metrics.
#' @param quiet Hide errors (`TRUE`, the default), or display them as they occur?
#' @param ... Not currently used
#'
#'
#' @return A tibble with accuracy estimates.
#'
#' @details
#'
#' The following accuracy metrics are included by default via [default_forecast_accuracy_metric_set()]:
#'
#' - MAE - Mean absolute error, [mae()]
#' - MAPE - Mean absolute percentage error, [mape()]
#' - MASE - Mean absolute scaled error, [mase()]
#' - SMAPE - Symmetric mean absolute percentage error, [smape()]
#' - RMSE - Root mean squared error, [rmse()]
#' - RSQ - R-squared, [rsq()]
#'
#'
#'
#' @examples
#' library(tidyverse)
#' library(lubridate)
#' library(timetk)
#' library(parsnip)
#' library(rsample)
#'
#' # Data
#' m750 <- m4_monthly %>% filter(id == "M750")
#'
#' # Split Data 80/20
#' splits <- initial_time_split(m750, prop = 0.9)
#'
#' # --- MODELS ---
#'
#' # Model 1: auto_arima ----
#' model_fit_arima <- arima_reg() %>%
#' set_engine(engine = "auto_arima") %>%
#' fit(value ~ date, data = training(splits))
#'
#'
#' # ---- MODELTIME TABLE ----
#'
#' models_tbl <- modeltime_table(
#' model_fit_arima
#' )
#'
#' # ---- ACCURACY ----
#'
#' models_tbl %>%
#' modeltime_calibrate(new_data = testing(splits)) %>%
#' modeltime_accuracy(
#' metric_set = metric_set(mae, rmse, rsq)
#' )
#'
#'
#' @name modeltime_accuracy
NULL
#' @export
#' @rdname modeltime_accuracy
modeltime_accuracy <- function(object, new_data = NULL,
metric_set = default_forecast_accuracy_metric_set(),
quiet = TRUE, ...) {
if (!is_calibrated(object)) {
if (is.null(new_data)) {
rlang::abort("Modeltime Table must be calibrated (see 'modeltime_calbirate()') or include 'new_data'.")
}
}
UseMethod("modeltime_accuracy")
}
#' @export
modeltime_accuracy.default <- function(object, new_data = NULL,
metric_set = default_forecast_accuracy_metric_set(),
quiet = TRUE, ...) {
rlang::abort(stringr::str_glue("Received an object of class: {class(object)[1]}. Expected an object of class:\n 1. 'mdl_time_tbl' - A Model Time Table made with 'modeltime_table()' and calibrated with 'modeltime_calibrate()'."))
}
#' @export
modeltime_accuracy.mdl_time_tbl <- function(object, new_data = NULL,
metric_set = default_forecast_accuracy_metric_set(),
quiet = TRUE, ...) {
data <- object
# Handle New Data ----
if (!is.null(new_data)) {
data <- data %>%
modeltime_calibrate(new_data = new_data)
}
# Accuracy Calculation ----
safe_calc_accuracy <- purrr::safely(calc_accuracy_2, otherwise = NA, quiet = quiet)
ret <- data %>%
dplyr::ungroup() %>%
dplyr::mutate(.nested.col = purrr::map(
.x = .calibration_data,
.f = function(.data) {
ret <- safe_calc_accuracy(
test_data = .data,
metric_set = metric_set,
...
)
ret <- ret %>% purrr::pluck("result")
return(ret)
})
) %>%
dplyr::select(-.model, -.calibration_data) %>%
tidyr::unnest(cols = .nested.col)
if (".nested.col" %in% names(ret)) {
ret <- ret %>%
dplyr::select(-.nested.col)
}
return(ret)
}
# DEFAULT METRIC SET ----
#' Forecast Accuracy Metrics Sets
#'
#'
#' This is a wrapper for [metric_set()] with several common forecast / regression
#' accuracy metrics included. These are the default time series accuracy
#' metrics used with [modeltime_accuracy()].
#'
#' @details
#'
#' The primary purpose is to use the default accuracy metrics to calculate the following
#' forecast accuracy metrics using [modeltime_accuracy()]:
#' - MAE - Mean absolute error, [mae()]
#' - MAPE - Mean absolute percentage error, [mape()]
#' - MASE - Mean absolute scaled error, [mase()]
#' - SMAPE - Symmetric mean absolute percentage error, [smape()]
#' - RMSE - Root mean squared error, [rmse()]
#' - RSQ - R-squared, [rsq()]
#'
#' @examples
#' library(tibble)
#' library(dplyr)
#' library(timetk)
#'
#' set.seed(1)
#' data <- tibble(
#' time = tk_make_timeseries("2020", by = "sec", length_out = 10),
#' y = 1:10 + rnorm(10),
#' y_hat = 1:10 + rnorm(10)
#' )
#'
#' # Default Metric Specification
#' default_forecast_accuracy_metric_set()
#'
#' # Create a metric summarizer function from the metric set
#' calc_default_metrics <- default_forecast_accuracy_metric_set()
#'
#' # Apply the metric summarizer to new data
#' calc_default_metrics(data, y, y_hat)
#'
#' @export
#' @importFrom yardstick mae mape mase smape rmse rsq
default_forecast_accuracy_metric_set <- function() {
yardstick::metric_set(
mae,
mape,
mase,
smape,
rmse,
rsq
)
}
# UTILITIES ----
calc_accuracy_2 <- function(train_data = NULL, test_data = NULL, metric_set, ...) {
# Training Metrics
train_metrics_tbl <- tibble::tibble()
# Testing Metrics
test_metrics_tbl <- tibble::tibble()
if (!is.null(test_data)) {
# print(test_data)
test_metrics_tbl <- test_data %>%
summarize_accuracy_metrics(.actual, .prediction, metric_set) %>%
dplyr::ungroup()
}
metrics_tbl <- dplyr::bind_rows(train_metrics_tbl, test_metrics_tbl)
return(metrics_tbl)
}
summarize_accuracy_metrics <- function(data, truth, estimate, metric_set) {
truth_expr <- rlang::enquo(truth)
estimate_expr <- rlang::enquo(estimate)
metric_summarizer_fun <- metric_set
data %>%
metric_summarizer_fun(!! truth_expr, !! estimate_expr) %>%
dplyr::select(-.estimator) %>%
# mutate(.metric = toupper(.metric)) %>%
tidyr::pivot_wider(names_from = .metric, values_from = .estimate)
}
|
e643a3cda4b5f2bf612206f10a306ffae5773306
|
5c8a76902901cf21d4ae0a478469148f7686950f
|
/00functions/measures.R
|
23cfa3d1c8ff921e1045c79b06d90effbcee09bc
|
[] |
no_license
|
markvanderloo/nsnet
|
35e24440e85a46c4c3cda74d7ec15ffd3ea56388
|
858155b6de42b1bcea9f06ac71b4ed058c2eb791
|
refs/heads/master
| 2020-03-10T04:55:59.556690
| 2018-08-10T12:02:33
| 2018-08-10T12:02:33
| 129,204,912
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,778
|
r
|
measures.R
|
#' efficiency of a graph, according to Latora (2001)
#' @param g a graph
#'
efficiency <- function(g){
n <- length(V(g))
if (n==1) return(0)
nd <- igraph::distance_table(g)$res
d <- seq_along(nd)
N <- n*(n-1)
2*sum(nd/d)/N
}
#' local efficiency of a graph, according to Latora (2001)
#' @param g, a graph
local_efficiency <- function(g){
sapply(V(g),function(node){
h <- induced_subgraph(g,c(neighbors(g,node)))
efficiency(h)
})
}
#' Network vulnerability per node, according to Gol'dshtein (2004) and
#' Latora et al (2005).
#' @param g a graph
vulnerability <- function(g){
e <- efficiency(g)
nodes <- V(g)
sapply(seq_along(nodes), function(i){
h <- delete_edges(g, incident_edges(g,nodes[i])[[1]])
1-efficiency(h)/e
})
}
harmonic <- function(n){
sum(1/seq_len(n))
}
#' efficiency of the line graph
#' @param n number of nodes (can be a vector of values)
line_efficiency <- function(n){
sapply(n, function(ni) 2*harmonic(ni-1)/(ni-1) - 2/ni)
}
circle_efficiency <- function(n){
ce <- function(x){
h <- if (x%%2==0){
2*harmonic(x/2-1)/(x-1) + 2/(x*(x-1))
} else {
2*harmonic((x-1)/2)/(x-1)
}
}
sapply(n,ce)
}
#' Topological information content
#' @param g a graph
#'
#' @details
#' The topological information content is defined as
#' the logarithm of the size of the automorphism group to the base of 2.
#'
information_content <- function(g){
log2(as.numeric(igraph::automorphisms(h)$group_size))
}
# return a vector of graph characterizations
measures <- function(g){
c(
global_efficiency = efficiency(g)
, local_efficiency = mean(local_efficiency(g))
, vulnerability = max(vulnerability(g))
, topological_informatioin_content = information_content(g)
)
}
|
c021257eff48058c6c232195b99fd5ad90dc4fb1
|
5f93c27bf3ad41c2adbc4f2e6e56b3ff3b31cf89
|
/mmm_process_code/mmm_process_functions/gen_mmm_params.R
|
afcd70922dd8ddcd567d17d161b564c4fcccbfbe
|
[] |
no_license
|
jbischof/HPC_model
|
fd6726abf3130075e1354d2139212c00b04ee4b0
|
5dd2c6ae7e36e31a4a71751e38b9fe4ef88c0fcf
|
refs/heads/master
| 2021-01-01T19:07:31.094310
| 2014-05-06T04:18:26
| 2014-05-06T04:18:41
| 2,614,499
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,014
|
r
|
gen_mmm_params.R
|
# Script to generate the parameters of the MMM
gen.mmm.params <- function(nchildren,nlevels,ndocs,nwords,
psi,gamma,nu,sigma2,
eta.vec=NULL,lambda2=NULL,
Sigma=NULL,full.Sigma=FALSE,
gp="dirichlet",verbose=FALSE){
# Translate function inputs into model's inputs
J <- nchildren
D <- ndocs
V <- nwords
# Total number of active topics (this determined by nlevels and nchildren)
K <- count.active.topics(nlevels,J)
# Generate alpha vector
alpha <- as.vector(rdirichlet(1,rep(1,K)))
# Generate theta parameters
# If unrestricted Sigma not requested, make a diag matrix
if(!full.Sigma){Sigma <- lambda2*diag(K)}
theta.out <- gen.theta.param.vecs(alpha=alpha,eta.vec=eta.vec,Sigma=Sigma,
D=D,gp=gp,verbose=verbose)
theta.param.vecs <- theta.out$theta.param.vecs
I.vecs <- theta.out$I.vecs
xi.param.vecs <- theta.out$xi.vecs
# For now, get rid of documents without assigned labels
# Draw list of tau2s for every word in vocabulary
tau2.param.list <- tau2.param.gen(V=V,nchild=J,nu=nu,sigma2=sigma2)
tau2.param.vecs <- get.tau2.matrix(tau2.param.list)
rownames(tau2.param.vecs) <- 1:nrow(tau2.param.vecs)
colnames(tau2.param.vecs)[1] <- "CORPUS"
# Draw list of mus for every word in vocabulary
mu.param.list <- mu.param.gen(nchild=J,psi=psi,gamma=gamma,
tau2.param.list=tau2.param.list)
# Get vector of rates for each feature that will generate the counts
mu.params.out <- get.mu.matrix(mu.param.list)
mu.param.vecs <- mu.params.out$mu.param.vecs
rownames(mu.param.vecs) <- 1:V
mu.corpus.vec <- mu.params.out$mu.corpus.vec
names(mu.corpus.vec) <- 1:V
# Get labeled topics for each document
topics <- colnames(mu.param.vecs)
names(alpha) <- topics
colnames(theta.param.vecs) <- colnames(xi.param.vecs) <- topics
rownames(theta.param.vecs) <-rownames(xi.param.vecs) <- 1:nrow(theta.param.vecs)
# Create data address book and parent.child.list
topic.address.book <- gen.topic.address.book(topics)
parent.child.list <- get.parent.child.list(topic.address.book)
true.param.list <- list(alpha=alpha,mu.param.vecs=mu.param.vecs,
mu.corpus.vec=mu.corpus.vec,
tau2.param.vecs=tau2.param.vecs,
theta.param.vecs=theta.param.vecs,
I.vecs=I.vecs,xi.param.vecs=xi.param.vecs,
K=K,D=D,V=V,psi=psi,gamma=gamma,nu=nu,
sigma2=sigma2,parent.child.list=parent.child.list)
if(any(gp=="logit.norm",gp=="mv.probit")){
names(eta.vec) <- topics
true.param.list$eta.vec <- eta.vec
true.param.list$lambda2 <- lambda2
true.param.list$Sigma <- Sigma
true.param.list$full.Sigma <- full.Sigma
}
return(list(true.param.list=true.param.list,
topic.address.book=topic.address.book))
}
|
83556f8f38443ca781410ef7c8379d062d844913
|
73a92011ba758b076352909339084935e63c85c9
|
/plot4.R
|
71b8196801e2c98b9fd1ca5ef186df627ea18d5c
|
[] |
no_license
|
DWdapengwang/ExData_Plotting1
|
dccf6171b9ad423449c1c6db02665bf437f0efe5
|
744cf9007863de778e8f552ea1066c959d7c2b9c
|
refs/heads/master
| 2021-01-16T20:48:34.928949
| 2015-06-02T18:15:08
| 2015-06-02T18:15:08
| 36,750,566
| 0
| 0
| null | 2015-06-02T17:43:36
| 2015-06-02T17:43:35
| null |
UTF-8
|
R
| false
| false
| 1,451
|
r
|
plot4.R
|
##Reading the data
data <- read.table("household_power_consumption.txt", , sep = ";", skip = 66637, nrows = 2880, col.names = c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dataf <- data.frame(data)
dataf[["Date_Time"]] <- paste(dataf[["Date"]], dataf[["Time"]], sep=" ")
dataf[["Date_Time"]] <- strptime(dataf[["Date_Time"]], format= "%d/%m/%Y %H:%M:%S" )
##plot4
png(filename = "plot4.png")
par(mfcol = c(2, 2))
with(dataf,{
plot(dataf[["Date_Time"]], dataf[["Global_active_power"]], type="l", xlab = "", ylab = "Global Active Power")
{
with(dataf, plot(Date_Time, Sub_metering_1, type = "n", ylab = "Energy sub metering", xlab =""))
with(dataf, points(Date_Time, Sub_metering_1, col = "BLACK", type ="l"))
with(dataf, points(Date_Time, Sub_metering_2, col = "RED", type = "l"))
with(dataf, points(Date_Time, Sub_metering_3, col = "BLUE", type = "l"))
legend("topright", col = c("BLACK", "RED", "BLUE"), lty=c(1,1), cex = 0.9, bty = "n", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
}
plot(dataf[["Date_Time"]], dataf[["Voltage"]], type = "l", xlab = "datetime", ylab = "Voltage")
plot(dataf[["Date_Time"]], dataf[["Global_reactive_power"]], type = "l", xlab = "datetime", ylab = "Global_reactive_power")
})
dev.off()
|
255e2458b489337aa7fdf2693a627777e6b703ec
|
f58d0680a57f8c62d0d10431f6a747e4b81eae19
|
/tests/testthat/test-get_net_long.R
|
c99d14fa0d04d316dd2d10e924a3f7e50a5973df
|
[] |
no_license
|
awekim/WIODnet
|
fc99cb1cf1272bd73ac2ee5b90e44a2901b1a638
|
07966a9e856820667ef069be4a1f19592d7be3ae
|
refs/heads/master
| 2020-08-13T15:25:17.406570
| 2019-10-14T12:31:47
| 2019-10-14T12:31:47
| 214,992,045
| 0
| 0
| null | 2019-10-14T08:42:33
| 2019-10-14T08:42:33
| null |
UTF-8
|
R
| false
| false
| 211
|
r
|
test-get_net_long.R
|
test_that("obtain long network table", {
## network matrix
w2002.IO <<- get(load("./wide_IO_w2002.rda"))
mini.long <- getNetLong(w2002.IO)
expect_equal(dim(mini.long), c(6888, 3))
})
|
5d8deba20002fe3536650f99585a61da18107419
|
7af0777279264ca1b68d1a226199b0fe06b464a3
|
/exemplos/lendo_dados_csv_analise_descritiva.R
|
60bf0d06c9df0a6c62a42dd639d64a94f3621d2d
|
[] |
no_license
|
futxicaiadatec/mini-curso-r
|
388ed6c0d39c327850e988c9223ed1759c7bbe40
|
441eca58857cc00ba4e30f90f9decf1b4615e6b4
|
refs/heads/master
| 2021-07-05T13:42:09.454697
| 2017-09-29T01:43:43
| 2017-09-29T01:43:43
| 105,052,319
| 0
| 1
| null | null | null | null |
ISO-8859-1
|
R
| false
| false
| 602
|
r
|
lendo_dados_csv_analise_descritiva.R
|
planilha=read.csv('dados.csv',header=TRUE,sep=',',dec='.')
temperatura = planilha$T_z1 #extraindo um vetor de dados (temperatura) a partir da coluna T_z1
minT = min(temperatura) #valor mínimo no vetor temperatura
maxT = max(temperatura) #valor máximo no vetor temperatura
meanT = mean(temperatura) #média de valores no vetor temperatura
sdT = sd(temperatura) #desvio padrão dos valores no vetor temperatura
medianaT = median(temperatura) #mediana dos valores no vetor temperatura
quantidade = length(temperatura[temperatura>meanT]) #temperaturas maiores que a média
|
e21361210c2deef12bf5da83f8813f3d584a4d02
|
26c7e13e0e52e7dab57f9e92b167b91a00760f05
|
/plot2.R
|
4e9b712b1e2e05cb11af950e63834886ea467005
|
[] |
no_license
|
aruneema/ExData_Plotting1
|
e04d819a2717ffa32011ee8724e18780db3b5ec1
|
c1417217165cb072fec4136b0292adca694ebd06
|
refs/heads/master
| 2021-01-15T18:41:47.054326
| 2014-08-08T05:38:01
| 2014-08-08T05:38:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 583
|
r
|
plot2.R
|
## Getting full dataset
data_full <- read.csv("household_power_consumption.txt", sep=';', na.strings="?", nrows=2075259)
data_full$Date <- as.Date(data_full$Date, format="%d/%m/%Y")
## Subsetting the data
data <- subset(data_full, subset=(Date >= "2007-02-01" & Date <= "2007-02-02"))
## Converting dates
datetime <- paste(data$Date, data$Time)
data$Datetime <- as.POSIXct(datetime)
## Plot 2
plot(data$Global_active_power~data$Datetime, type="l", ylab="Global Active Power (kilowatts)", xlab="")
## Saving to file
dev.copy(png, file="plot2.png", height=480, width=480)
dev.off()
|
efb6ed1b08d9caf0143cbe9c49e3da6a809ac053
|
d7ff71e8ffb07419aad458fb2114a752c5bf562c
|
/tests/testthat/test-public_api-0.R
|
e0d46f1050469e6c3736fea0d87634632dc098cd
|
[
"MIT"
] |
permissive
|
r-lib/styler
|
50dcfe2a0039bae686518959d14fa2d8a3c2a50b
|
ca400ad869c6bc69aacb2f18ec0ffae8a195f811
|
refs/heads/main
| 2023-08-24T20:27:37.511727
| 2023-08-22T13:27:51
| 2023-08-22T13:27:51
| 81,366,413
| 634
| 79
|
NOASSERTION
| 2023-09-11T08:24:43
| 2017-02-08T19:16:37
|
R
|
UTF-8
|
R
| false
| false
| 2,433
|
r
|
test-public_api-0.R
|
test_that("styler can style package", {
capture_output(expect_false({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"))
any(styled$changed)
}))
})
test_that("styler can style package and exclude some directories", {
capture_output(
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests"
)
)
expect_true(nrow(styled) == 1)
expect_false(any(grepl("tests/testthat/test-package-xyz.R", styled$file)))
})
test_that("styler can style package and exclude some sub-directories", {
capture_output(
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests/testthat"
)
)
expect_true(nrow(styled) == 2)
expect_true(any(grepl("tests/testthat.R", styled$file)))
expect_false(any(grepl("tests/testthat/test-package-xyz.R", styled$file)))
})
test_that("styler can style package and exclude some directories and files", {
capture_output(expect_true({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests",
exclude_files = ".Rprofile"
)
nrow(styled) == 1
}))
capture_output(expect_true({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests",
exclude_files = "./.Rprofile"
)
nrow(styled) == 1
}))
})
test_that("styler can style directory", {
capture_output(expect_false({
styled <- style_dir(testthat_file("public-api", "xyzdir"))
any(styled$changed)
}))
})
test_that("styler can style directories and exclude", {
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = "renv"
)
nrow(styled) == 2
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = c("renv", "tests/testthat")
)
nrow(styled) == 1
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = "./renv"
)
nrow(styled) == 2
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = "./renv", recursive = FALSE
)
nrow(styled) == 0
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
recursive = FALSE
)
nrow(styled) == 0
}))
})
|
444fc8682ddc5be83e74f04b572996985f524874
|
fab43c4a98e556b83716ab892f3479c9720dc866
|
/RiskMap/R/plotRisk.R
|
9ce924caecccbc2932ad7a3b31a0e45f2eec596d
|
[] |
no_license
|
bvanhezewijk/DynamicRiskMap
|
a8e3ef15cf334463c6e98f825cd3495e52a022be
|
2684402e7c3dd39de5285366ac8039d7d3a22af1
|
refs/heads/master
| 2021-01-21T10:59:44.470862
| 2018-01-30T21:35:21
| 2018-01-30T21:35:21
| 83,509,927
| 0
| 0
| null | 2017-03-01T04:26:24
| 2017-03-01T04:03:30
| null |
UTF-8
|
R
| false
| false
| 9,182
|
r
|
plotRisk.R
|
# plotRisk()
# Function to create risk raster for each data layer
# Agruments: projectList
# KSchurmann March 10, 2017
#
## for layers plot - color scale not same for each layer
#
#' Plotting total risk
#'
#' Plots region showing total risk. Shows subregion map of total risk,
#' google map and risk of individual layers.
#'
#' @param x List created by \code{projectList} function
#' @param plot Character string; specifies which devices to plot: \code{'all'} (default),
#' \code{'totalRisk'}, or \code{'layers'}
#' @param plotLayers List of layers to be plotted, or \code{'all'} (default)
#' @param basemap Basemap type: \code{'satellite'}, \code{'roadmap'}, \code{'hybrid'} (default),
#' or \code{'terrain'} for google map window
#' @return Graphics devices showing total risk.
#' @details Device 2 plots the totalRisk raster for the entire \code{ROI} extent. Device 3
#' plots the \code{ROIsub} extent of the totalRisk raster. Device 4 calls \code{dismo::gmap} to
#' get a google map layer of the \code{ROIsub} and overplots the totalRisk raster. Device
#' 5 plots the risk raster \code{ROIsub} for each data layer listed in \code{plotLayers}
#' or all layers if \code{'all'} was specified (default).
#'
#' Devices 3 & 5 uses the \code{Plot} function from the SpaDES package.
#' @seealso \code{zoomRisk}, \code{plotHiRisk}, \code{plotTraps}, \code{SpaDES::Plot}, \code{dismo::gmap}
#' @export
plotRisk <- function(x, plot='all', plotLayers='all',
basemap='hybrid'){
if("water" %in% names(x$layers)) setColors(x$layers$water$raster) <- "lightblue"
switch(plot,
all = {
graphics.off()
windows(w=3.5, h=4, xpos=1685, ypos=0) #totalRisk
windows(w=3.5, h=4, xpos=2115, ypos=0) #subROI
windows(w=3.5, h=4, xpos=2545, ypos=0) #google
windows(w=10.5, h=3, xpos=1690, ypos=560) #risk layers
# plotting totalRisk
dev.set(2)
clearPlot()
Plot(x$totalRisk, title=names(x$totalRisk) ,cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)) Plot(x$layers$water$raster, addTo="x$totalRisk")
box <- as(x$ROIs$ROIsub, 'SpatialPolygons')
Plot(box, addTo="x$totalRisk")
# plotting subROI & totalRisk
dev.set(3)
clearPlot()
subROI <- raster::crop(x$totalRisk, x$ROIs$ROIsub)
if("water" %in% names(x$layers)) subWater <- raster::crop(x$layers$water$raster, x$ROIs$ROIsub)
Plot(subROI, cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)) Plot(subWater, addTo="subROI")
# plotting individual layers
dev.set(5)
clearPlot()
if(plotLayers=="all"){
temp <- list()
for(i in 1:length(x$layers)){
dataLayer <- paste(names(x$layers)[i])
temp[[dataLayer]] <- x$layers[[dataLayer]]$risk
}
temp2 <- list()
for(k in 1:length(temp)){
dataLayer <- paste(names(temp)[k])
temp2[[dataLayer]] <- raster::crop(temp[[k]], x$ROIs$ROIsub)
}
Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)))
#Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)){
setColors(x$layers$water$raster) <- "lightblue"
for(m in names(temp)) {
waterCrop <- raster::crop(x$layers$water$raster, x$ROIs$ROIsub)
Plot(waterCrop, addTo=m) } }
} else {
temp <- list()
for(i in 1:length(x$layers)){
if(names(x$layers[i]) %in% plotLayers){
dataLayer <- paste(names(x$layers)[i])
temp[[dataLayer]] <- x$layers[[dataLayer]]$risk
}
}
temp2 <- list()
for(k in 1:length(temp)){
dataLayer <- paste(names(temp)[k])
temp2[[dataLayer]] <- raster::crop(temp[[k]], x$ROIs$ROIsub)
}
Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)))
#Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)){
setColors(x$layers$water$raster) <- "lightblue"
for(m in names(temp)) {
waterCrop <- raster::crop(x$layers$water$raster, x$ROIs$ROIsub)
Plot(waterCrop, addTo=m) } }
}
#plotting Google Maps image
dev.set(4)
googlemap <- dismo::gmap(x = raster::crop(x$totalRisk, x$ROIs$ROIsub), type = basemap, lonlat=TRUE)
temp <- raster::projectRaster(x$totalRisk, googlemap, method="ngb")
if("water" %in% names(x$layers)) waterMask <- raster::projectRaster(x$layers$water$raster, googlemap, method="ngb")
temp[temp<=0] <- NA
if("water" %in% names(x$layers)) temp <- raster::mask(temp, waterMask, inverse=TRUE)
plot(googlemap, main="Google Maps subROI")
plot(temp, breaks=seq(0, 1, 1/16), col=rev(heat.colors(16, alpha = 0.35)), add=T, legend = F)},
totalRisk = {
graphics.off()
windows(w=3.5, h=4, xpos=1685, ypos=0) #totalRisk
windows(w=3.5, h=4, xpos=2115, ypos=0) #subROI
windows(w=3.5, h=4, xpos=2545, ypos=0) #google
# plotting totalRisk
dev.set(2)
clearPlot()
Plot(x$totalRisk, title=names(x$totalRisk) ,cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)) Plot(x$layers$water$raster, addTo="x$totalRisk")
box <- as(x$ROIs$ROIsub, 'SpatialPolygons')
Plot(box, addTo="x$totalRisk")
# plotting subROI & totalRisk
dev.set(3)
clearPlot()
subROI <- raster::crop(x$totalRisk, x$ROIs$ROIsub)
Plot(subROI, cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)) subWater <- raster::crop(x$layers$water$raster, x$ROIs$ROIsub)
if("water" %in% names(x$layers)) Plot(subWater, addTo="subROI")
#plotting Google Maps image
dev.set(4)
googlemap <- dismo::gmap(x = raster::crop(x$totalRisk, x$ROIs$ROIsub), type = basemap, lonlat=TRUE)
temp <- raster::projectRaster(x$totalRisk, googlemap, method="ngb")
if("water" %in% names(x$layers)) waterMask <- raster::projectRaster(x$layers$water$raster, googlemap, method="ngb")
temp[temp<=0] <- NA
if("water" %in% names(x$layers)) temp <- raster::mask(temp, waterMask, inverse=TRUE)
plot(googlemap, main="Google Maps subROI")
plot(temp, breaks=seq(0, 1, 1/16), col=rev(heat.colors(16, alpha = 0.35)), add=T, legend = F) },
layers = {
if(plotLayers=="all"){
windows(w=10.5, h=3, xpos=1690, ypos=560)
clearPlot()
temp <- list()
for(i in 1:length(x$layers)){
dataLayer <- paste(names(x$layers)[i])
temp[[dataLayer]] <- x$layers[[dataLayer]]$risk
}
temp2 <- list()
for(k in 1:length(temp)){
dataLayer <- paste(names(temp)[k])
temp2[[dataLayer]] <- raster::crop(temp[[k]], x$ROIs$ROIsub)
}
Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)))
#Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)) {
setColors(x$layers$water$raster) <- "lightblue"
for(m in names(temp)) {
waterCrop <- raster::crop(x$layers$water$raster, x$ROIs$ROIsub)
Plot(waterCrop, addTo=m) } }
} else {
temp <- list()
for(i in 1:length(x$layers)){
if(names(x$layers[i]) %in% plotLayers){
dataLayer <- paste(names(x$layers)[i])
temp[[dataLayer]] <- x$layers[[dataLayer]]$risk
}
}
temp2 <- list()
for(k in 1:length(temp)){
dataLayer <- paste(names(temp)[k])
temp2[[dataLayer]] <- raster::crop(temp[[k]], x$ROIs$ROIsub)
}
Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)))
#Plot(temp2, title=TRUE ,cols=rev(heat.colors(16)), legendRange = 0:1)
if("water" %in% names(x$layers)) {
setColors(x$layers$water$raster) <- "lightblue"
for(m in names(temp)) {
waterCrop <- raster::crop(x$layers$water$raster, x$ROIs$ROIsub)
Plot(waterCrop, addTo=m) } }
}
}
)
}
|
1bb02b7e43fc9a9fed1af9798d21465266908bd9
|
3c14ce20f358d8382395a2ddc4bc3e06001624cf
|
/man/cf.Rd
|
d1ee60428cb8e18294a4aca42786d8a3d1643acb
|
[] |
no_license
|
pittlerf/hadron
|
1900fb27a6382227036c02c9e70032f95f12ef1c
|
281becdebc1551d2ac520b68ca6520eff8dfceed
|
refs/heads/master
| 2022-03-08T14:52:23.194120
| 2018-12-22T07:34:14
| 2018-12-22T07:34:14
| 146,309,078
| 0
| 0
| null | 2018-08-27T14:29:20
| 2018-08-27T14:29:19
| null |
UTF-8
|
R
| false
| true
| 1,119
|
rd
|
cf.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cf.R
\name{cf}
\alias{cf}
\title{Correlation function container}
\usage{
cf()
}
\description{
This function \code{cf()} creates containers for correlation functions
of class \code{cf}. This class is particularly designed to deal with
correlation functions emerging in statistical and quantum field theory
simulations. Arithmetic operations are defined for this class in
several ways, as well as concatenation and \link{is.cf} and \link{as.cf}.
}
\details{
And last but not least, these are the fields that are used somewhere in the library but we have not figured out which mixin these should belong to:
\itemize{
\item \code{conf.index}: TODO
\item \code{N}: Integer, number of measurements.
\item \code{blockind}: TODO
\item \code{jack.boot.se}: TODO
}
}
\seealso{
Other cf constructors: \code{\link{cf_boot}},
\code{\link{cf_meta}}, \code{\link{cf_orig}},
\code{\link{cf_principal_correlator}},
\code{\link{cf_shifted}}, \code{\link{cf_smeared}},
\code{\link{cf_subtracted}}, \code{\link{cf_weighted}}
}
\concept{cf constructors}
|
8c7de242e70b4923c92ea1845e82a78190e527e6
|
69766ac65a6c48196d9340f1b6d661baa13ecefd
|
/test/0511.R
|
4496dbe63430f0b72544ceb0913e994e63d6eedd
|
[] |
no_license
|
JamesYeh2017/R
|
0944abc42dded45f531ded2cae40560b0227de47
|
dcae81f1169582eae54cb4b0ee9706781eacb460
|
refs/heads/master
| 2021-06-20T23:24:25.889671
| 2017-08-14T13:42:22
| 2017-08-14T13:42:22
| 90,741,993
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,032
|
r
|
0511.R
|
getwd()
setwd("./data/")
match_txt = read.table("./match.txt" ,header = FALSE, sep="|")
match_txt
match_fun = function(match_txt=read.table("./match.txt" ,header = FALSE, sep="|")){
mat = matrix(rep(-1,length(levels(match_txt[i,1]))^2), nrow=5)
#return(mat)
#rownames(mat) = c("A","B","C","D","E")
#colnames(mat) = c("A","B","C","D","E")
rownames(mat) = levels(match_txt[i,1])
colnames(mat) = levels(match_txt[i,2])
#return(mat)
for (i in 1:nrow(match_txt)){
mat[match_txt[i,1], match_txt[i,2]] = match_txt[i,3];
#matrix可以用 idx[1,1];names[A,A] 取值
}
return(mat)
}
match_fun()
# 各種機率分配的中央極限定裡
CLT = function(x) {
op<-par(mfrow=c(2,2)) # 設為 2*2 的四格繪圖版
hist(x, breaks=50) # 繪製 x 序列的直方圖 (histogram)。
m2 <- matrix(x, nrow=2 ) # 將 x 序列分為 2*k 兩個一組的矩陣 m2。
xbar2 <- apply(m2, 2, mean) # 取每兩個一組的平均值 (x1+x2)/2 放入 xbar2 中。 col平均
hist(xbar2, breaks=50) # 繪製 xbar2 序列的直方圖 (histogram)。
m10 <- matrix(x, nrow=10 ) # 將 x 序列分為 10*k 兩個一組的矩陣 m10。
xbar10 <- apply(m10, 2, mean) # 取每10個一組的平均值 (x1+..+x10)/10 放入 xbar10 中。
hist(xbar10, breaks=50) # 繪製 xbar10 序列的直方圖 (histogram)。
m20 <- matrix(x, nrow=20 ) # 將 x 序列分為 25*k 兩個一組的矩陣 m25。
xbar20 <- apply(m20, 2, mean) # 取每20個一組的平均值 (x1+..+x20)/20 放入 xbar20 中。
hist(xbar20, breaks=50) # 繪製 xbar20 序列的直方圖 (histogram)。
}
CLT(rbinom(n=100000, size = 20, prob = 0.1)) # 用參數為 n=20, p=0.5 的二項分布驗證中央極限定理。
CLT(runif(n=100000,min = 0,max = 1)) # 用參數為 a=0, b=1 的均等分布驗證中央極限定理。
CLT(rpois(n=100000, lambda = 4)) # 用參數為 lambda=4 的布瓦松分布驗證中央極限定理。
CLT(rgeom(n=100000, prob = 0.7)) # 用參數為 p=0.5 的幾何分布驗證中央極限定理。
|
c6e97ef10a8b1a3123d6071a4504114f6e74dd03
|
4df2640f0b6503bab3a21482013581258f957325
|
/Wegan/src/main/webapp/resources/rscripts/metaboanalystr/general_load_libs.R
|
23771c42ae06781aa6f44e921015db23ab094295
|
[] |
no_license
|
Sam-Stuart/WeganTest
|
c7223b9286af7559aa03520982dcbfde3da93923
|
5dd591c40df6e2a89c0f3b0ca41f759f4d17787e
|
refs/heads/master
| 2022-04-08T11:12:29.355917
| 2020-03-13T20:20:06
| 2020-03-13T20:20:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,238
|
r
|
general_load_libs.R
|
# Load lattice, necessary for power analysis
load_lattice <- function(){
suppressMessages(library(lattice))
}
# Load igraph, necessary for network analysis
load_igraph <- function(){
suppressMessages(library(igraph))
}
# Load reshape, necessary for graphics
load_reshape <- function(){
suppressMessages(library(reshape))
}
# Load gplots, necessary for heatmap
load_gplots <- function(){
suppressMessages(library(gplots))
}
# Load R color brewer, necessary for heatmap
load_rcolorbrewer <- function(){
suppressMessages(library(RColorBrewer))
}
# Load siggenes, necessary for SAM/EBAM
load_siggenes <- function(){
suppressMessages(library(siggenes))
}
# Load RSQLite, necessary for network analysis
load_rsqlite <- function(){
suppressMessages(library(RSQLite))
}
# Load caret, necessary for stats module
load_caret <- function(){
suppressMessages(library(caret))
}
# Load pls, necessary for stats module
load_pls <- function(){
suppressMessages(library(pls))
}
# Load KEGGgraph
load_kegggraph <- function(){
suppressMessages(library(KEGGgraph))
}
# Load RGraphviz
load_rgraphwiz <- function(){
suppressMessages(library(Rgraphviz))
}
# Load XCMS
load_xcms <- function(){
suppressMessages(library(xcms))
}
|
7e4249fa8106ba1d420f5b8160aff8e6a683b400
|
ac7209e01bd00ae436fc0c691c3dc164a3a00c42
|
/upscale_disconnections/run_tests.R
|
72bd8454e5111225f79acd9996313cdb129db9aa
|
[
"MIT"
] |
permissive
|
Taru-AEMO/DER_disturbance_analysis
|
8408eeb9b74847e6dc1bd6de725e10682a95ca8d
|
2df8b2f469c3f05a010100cd567db25e42415678
|
refs/heads/master
| 2021-09-20T07:37:50.683738
| 2021-09-17T00:06:14
| 2021-09-17T00:06:14
| 162,227,323
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 95
|
r
|
run_tests.R
|
library(testthat)
source("load_tool_environment.R")
test_dir("upscale_disconnections/tests")
|
1cae18402867d8b687586e12daf60175e8b2367d
|
c5c850791e054f5e4bcc559abf9fb71c22b79e80
|
/R/bootPair2.R
|
d2fefc2875e9e758e57575a41389b4990942ffaa
|
[] |
no_license
|
cran/generalCorr
|
3412664373559d8f03d0b668bb6a5b6bdac40f2b
|
6a26d66ddee3b518f34a64d25fdaa5e13a5a45a1
|
refs/heads/master
| 2023-08-31T09:59:03.135328
| 2023-08-16T16:24:36
| 2023-08-16T18:30:25
| 57,865,966
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,355
|
r
|
bootPair2.R
|
#' Compute matrix of n999 rows and p-1 columns of bootstrap `sum'
#' (scores from Cr1 to Cr3).
#'
#' The `2' in the name of the function suggests a second implementation of `bootPair,'
#' where exact stochastic dominance, decileVote, and momentVote are used.
#' Maximum entropy bootstrap (meboot) package is used for statistical inference
#' using the sum of three signs sg1 to sg3, from the three criteria Cr1 to Cr3, to
#' assess preponderance of evidence in favor of a sign, (+1, 0, -1).
#' The bootstrap output can be analyzed to assess the approximate
#' preponderance of a particular sign which determines
#' the causal direction.
#'
#' @param mtx {data matrix with two or more columns}
#' @param ctrl {data matrix having control variable(s) if any}
#' @param n999 {Number of bootstrap replications (default=9)}
#' @importFrom meboot meboot
#' @importFrom stats complete.cases
#' @return Function creates a matrix called `out'. If
#' the input to the function called \code{mtx} has p columns, the output \code{out}
#' of \code{bootPair2(mtx)} is a matrix of n999 rows and p-1 columns,
#' each containing resampled `sum' values summarizing the weighted sums
#' associated with all three criteria from the function \code{silentPair2(mtx)}
#' applied to each bootstrap sample separately.
#'
#' @note This computation is computer-intensive and generally very slow.
#' It may be better to use
#' it later in the investigation, after a preliminary
#' causal determination
#' is already made.
#' A positive sign for j-th weighted sum reported in the column `sum' means
#' that the first variable listed in the argument matrix \code{mtx} is the
#' `kernel cause' of the variable in the (j+1)-th column of \code{mtx}.
#' @author Prof. H. D. Vinod, Economics Dept., Fordham University, NY
#' @seealso See Also \code{\link{silentPair2}}.
#' @references Vinod, H. D. `Generalized Correlation and Kernel Causality with
#' Applications in Development Economics' in Communications in
#' Statistics -Simulation and Computation, 2015,
#' \doi{10.1080/03610918.2015.1122048}
#' @references Zheng, S., Shi, N.-Z., and Zhang, Z. (2012). Generalized measures
#' of correlation for asymmetry, nonlinearity, and beyond.
#' Journal of the American Statistical Association, vol. 107, pp. 1239-1252.
#' @references Vinod, H. D. and Lopez-de-Lacalle, J. (2009). 'Maximum entropy bootstrap
#' for time series: The meboot R package.' Journal of Statistical Software,
#' Vol. 29(5), pp. 1-19.
#' @references Vinod, H. D. Causal Paths and Exogeneity Tests
#' in {Generalcorr} Package for Air Pollution and Monetary Policy
#' (June 6, 2017). Available at SSRN: \url{https://www.ssrn.com/abstract=2982128}
#'
#' @references Vinod, Hrishikesh D., R Package GeneralCorr
#' Functions for Portfolio Choice
#' (November 11, 2021). Available at SSRN:
#' https://ssrn.com/abstract=3961683
#'
#' @references Vinod, Hrishikesh D., Stochastic Dominance
#' Without Tears (January 26, 2021). Available at
#' SSRN: https://ssrn.com/abstract=3773309
#' @concept maximum entropy bootstrap
#' @examples
#' \dontrun{
#' options(np.messages = FALSE)
#' set.seed(34);x=sample(1:10);y=sample(2:11)
#' bb=bootPair2(cbind(x,y),n999=29)
#' apply(bb,2,summary) #gives summary stats for n999 bootstrap sum computations
#'
#' bb=bootPair2(airquality,n999=999);options(np.messages=FALSE)
#' apply(bb,2,summary) #gives summary stats for n999 bootstrap sum computations
#'
#' data('EuroCrime')
#' attach(EuroCrime)
#' bootPair2(cbind(crim,off),n999=29)#First col. crim causes officer deployment,
#' #hence positives signs are most sensible for such call to bootPairs
#' #note that n999=29 is too small for real problems, chosen for quickness here.
#' }
#' @export
bootPair2 = function(mtx, ctrl = 0, n999 = 9) {
ok= complete.cases(mtx)
p = NCOL(mtx[ok,])
n = NROW(mtx[ok,])
out = matrix(NA, nrow = n999, ncol = p - 1)
Memtx <- array(NA, dim = c(n, n999, p)) #3 dimensional matrix
for (i in 1:p) {
Memtx[, , i] = meboot(x=mtx[ok, i], reps = n999)$ensem
}
for (k in 1:n999) {
out[k, ] = silentPair2(mtx = Memtx[, k, 1:p], ctrl = ctrl)
if (k%%50 ==1) print(c("k=",k)) #track the progress
}
colnames(out) =colnames(mtx)[2:p]
return(out)
}
|
968c3edc838329f7956e69239c30cb39f09b0626
|
379b0d997ecfd40bc353db9abf5d3652929f36cc
|
/kmeans_cluster.R
|
33485d00d9356f94efe4c534e6fafec3da652e52
|
[] |
no_license
|
Broccolito/kmeans_clustering
|
1060dec3b7d4fbab8b6e3ea4b2798c3714fc6491
|
be90c676c91594e4cdb9762df0ebfeb8d7b6e8e6
|
refs/heads/master
| 2020-06-16T06:38:26.793103
| 2019-07-06T06:06:13
| 2019-07-06T06:06:13
| 195,504,007
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,522
|
r
|
kmeans_cluster.R
|
kmeans_cluster = function(x, y, n, graphic = TRUE){
# Define distance function
distance = function(point1, point2){
return(((point1[1] - point2[1]) ^ 2 + (point1[2] - point2[2]) ^ 2)^ 0.5)
}
# Setup pointset
pointset = cbind(x,y)
for(it in 1:100){
# Starting position of two points
starting_points = matrix(data = rep(0, 2 * n), nrow = n, ncol = 2)
for(i in 1:n){
starting_points[i,] = c(quantile(x, (i-0.5)/n),quantile(y, (i-0.5)/n))
}
dist_mat = matrix(data = rep(0, dim(pointset)[1] * n), nrow = dim(pointset)[1], ncol = n)
for(i in 1:n){
dist_pi = vector()
for(j in 1:dim(pointset)[1]){
dist_pi = c(dist_pi, distance(pointset[j,], starting_points[i,]))
}
dist_mat[,i] = dist_pi
}
which_group = vector()
for(i in 1:dim(pointset)[1]){
which_group[i] = which.min(dist_mat[i,])
}
for(i in 1:n){
one_group = pointset[which_group == i,]
if(length(one_group) > 0){
starting_points[i,] = c(mean(one_group[,1]), mean(one_group[,2]))
}
}
}
if(graphic){
plot(x, y, col = which_group + 1, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), pch = 16)
# Plot out centers
for(i in 1:n){
points(starting_points[i,1], starting_points[i,2], cex = 2.5, col = i + 1, pch = 8)
}
}
return(which_group)
}
kmeans_cluster(cars$dist, cars$speed, 5)
|
1bdd7a2ddc1babef048fb14fb3545b3be3e36f18
|
e00fff4abb7dad3a49a12bc17900bad3435398b8
|
/man/PredictionsBarplot.Rd
|
67110e75eefb663d2e888556cbbe715f5f6b54a1
|
[] |
no_license
|
bhklab/MM2S
|
ea5a9a97cb9947b0aa6e0bdab12a7890efcdb6c6
|
4085384eb38f60603b0f12c2db234c59290b8c5d
|
refs/heads/master
| 2021-12-31T08:46:20.585192
| 2021-12-14T21:27:42
| 2021-12-14T21:27:42
| 37,701,292
| 0
| 1
| null | 2015-06-19T04:21:07
| 2015-06-19T04:21:07
| null |
UTF-8
|
R
| false
| false
| 1,965
|
rd
|
PredictionsBarplot.Rd
|
\name{PredictionsBarplot}
\alias{PredictionsBarplot}
\title{
Stacked Barplot of MM2S Subtype Predictions for Given Samples
}
\description{
This function generates a stacked barplot of MM2S subtype predictions for samples of interest.
Users are provided the option to save this heatmap as a PDF file.
}
\usage{
PredictionsBarplot(InputMatrix,pdf_output,pdfheight,pdfwidth)
}
\arguments{
\item{InputMatrix}{Matrix with samples in rows, and columns with MM2S percentage predictions for each subtype (Gr4,Gr3,Sonic hedgehog (SHH),Wingless (WNT), and Normal)}
\item{pdf_output}{Option to save the heatmap as a PDF file}
\item{pdfheight}{User-defined specification for PDF height size}
\item{pdfwidth}{User-defined specification for PDF width size}
}
\value{
Generated Stacked Barplot of MM2S subtype predictions. Samples are in columns. Stacks are reflective of prediction percentages across MB subtypes for a given sample.
}
\references{
Gendoo, D. M., Smirnov, P., Lupien, M. & Haibe-Kains, B. Personalized diagnosis of medulloblastoma subtypes across patients and model systems.
Genomics, doi:10.1016/j.ygeno.2015.05.002 (2015)
Manuscript URL: http://www.sciencedirect.com/science/article/pii/S0888754315000774
}
\author{Deena M.A. Gendoo}
\examples{
# Generate heatmap from already-computed predictions for the GTML Mouse Model
## load computed MM2S predictions for GTML mouse model
data(GTML_Mouse_Preds)
## Generate Barplot
PredictionsBarplot(InputMatrix=GTML_Mouse_Preds, pdf_output=TRUE,pdfheight=5,pdfwidth=5)
\donttest{
# Generate heatmap after running raw expression data through MM2S
# load Mouse gene expression data for the potential WNT mouse model
data(WNT_Mouse_Expr)
SubtypePreds<-MM2S.mouse(InputMatrix=WNT_Mouse_Expr[2:3],parallelize=1, seed = 12345)
# Generate Heatmap
PredictionsBarplot(InputMatrix=SubtypePreds$Predictions,pdf_output=TRUE,pdfheight=5,pdfwidth=5)
}
}
\keyword{ heatmap }
|
e4787c390ef331044aa84155932ea86bcda5c527
|
fbe57536cc2d84e69a5bf799c88fcb784e853558
|
/R/unitconversion.siprefix.deka.to.base.R
|
340503717d3413adb64fd1b7b15ca8a2a64da267
|
[
"MIT"
] |
permissive
|
burrm/lolcat
|
78edf19886fffc02e922b061ce346fdf0ee2c80f
|
abd3915791d7e63f3827ccb10b1b0895aafd1e38
|
refs/heads/master
| 2023-04-02T11:27:58.636616
| 2023-03-24T02:33:34
| 2023-03-24T02:33:34
| 49,685,593
| 5
| 2
| null | 2016-10-21T05:14:49
| 2016-01-15T00:56:55
|
R
|
UTF-8
|
R
| false
| false
| 7,040
|
r
|
unitconversion.siprefix.deka.to.base.R
|
#' Unit Conversion - SI Prefixes - Deka- to Base
#'
#' Deka- tens, 10, or 10^1
#'
#' Performs a conversion from deka-units to base units (ex. dekagrams to grams).
#'
#' @param x Vector - Values in units of deka-units
#'
#' @return x, but converted to base units
#'
#' @references
#' NIST. Metric (SI) Prefixes. 2022. Accessed 4/7/2022.
#' https://www.nist.gov/pml/weights-and-measures/metric-si-prefixes
unitconversion.siprefix.deka.to.base <- function(
x = 1
) {
x * 10
}
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekasecond.to.second <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.das.to.s <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekameter.to.meter <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dam.to.m <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekagram.to.gram <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dag.to.g <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekaampere.to.ampere <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daA.to.A <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekakelvin.to.kelvin <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daK.to.K <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekamole.to.mole <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.damol.to.mol <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekacandela.to.candela <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dacd.to.cd <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekaradian.to.radian <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.darad.to.rad <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekasteradian.to.steradian <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dasr.to.sr <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekahertz.to.hertz <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daHz.to.Hz <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekanewton.to.newton <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daN.to.N <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekapascal.to.pascal <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daPa.to.Pa <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekajoule.to.joule <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daJ.to.J <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekawatt.to.watt <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daW.to.W <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekacoulomb.to.coulomb <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daC.to.C <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekavolt.to.volt <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daV.to.V <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekafarad.to.farad <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daF.to.F <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekaohm.to.ohm <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekasiemens.to.siemens <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daS.to.S <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekaweber.to.weber <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daWb.to.Wb <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekatesla.to.tesla <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daT.to.T <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekahenry.to.henry <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daH.to.H <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekalumen.to.lumen <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dalm.to.lm <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekalux.to.lux <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dalx.to.lx <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekabecquerel.to.becquerel <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daBq.to.Bq <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekagray.to.gray <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daGy.to.Gy <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekasievert.to.sievert <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.daSv.to.Sv <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dekakatal.to.katal <- unitconversion.siprefix.deka.to.base
#' @rdname unitconversion.siprefix.deka.to.base
unitconversion.dakat.to.kat <- unitconversion.siprefix.deka.to.base
|
39ba44c4835d307af210b31a8e7a00d7e93c6195
|
fb8a11ec829b5ce524158608ca7ff02d03354ea2
|
/R/cum_hist.R
|
078ce74e4b649dc41ad04595cd863881455265e4
|
[] |
no_license
|
pacoalonso/alonsaRp
|
840461cc444d6767408303d9829ac49f49218e4e
|
14df264ed8d7b0e66f58e84c01da9050367d9e95
|
refs/heads/master
| 2022-02-09T21:24:31.219260
| 2020-05-09T19:59:48
| 2020-05-09T19:59:48
| 233,576,698
| 0
| 1
| null | 2020-02-13T22:56:47
| 2020-01-13T11:08:27
|
R
|
UTF-8
|
R
| false
| false
| 810
|
r
|
cum_hist.R
|
#' Función para hacer histogramas acumulados
#'
#' @param x Vector of values
#' @param probability If TRUE shows probability instead of frequency
#' @param xlab Etiqueta para el eje de abcisas
#' @param ylab Etiqueta para el eje de ordenadas
#' @param main Tïtulo principal
#'
#'
#' @export
#'
cumHist <- function(x, probability=FALSE, main=NULL, xlab=deparse(substitute(x)), ylab=NULL) {
xx = table(x)
f = cumsum(as.numeric(xx))
v = as.numeric(names(xx))
ff = c(rep(f,each=2),0)
vv = c(min(v),rep(v,each=2))
if (probability) ff=ff/max(ff)
if (is.null(ylab)) {if (probability) ylab="probability" else ylab="frequency"}
plot(vv,ff,type="l", xlab=xlab, ylab=ylab, main=main)
for (i in 2:(length(vv)-1)) lines(c(vv[i],vv[i]),c(0,ff[i]))
lines(c(min(v),max(v)),c(0,0))
}
|
009fbe5325aa574ea03dfa99d21d1dd57eec9102
|
4771e621e79287a22331ebd650cf81185cbf9fed
|
/Warton_2011_analysis_of_proportions_in_ecology/glmmeg.R
|
10591735ca724bb6608338f95b582c49ecd87cae
|
[] |
no_license
|
bniebuhr/learning-stats
|
085e394a91983348e382901c7829aeabd9648e07
|
1ff502d8c8089c93e622d39d29c982cb92136e9a
|
refs/heads/master
| 2022-10-12T23:53:22.401435
| 2020-06-08T07:17:20
| 2020-06-08T07:17:20
| 270,564,638
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
R
| false
| false
| 7,132
|
r
|
glmmeg.R
|
## glmmeg.R: R code demonstrating how to fit a logistic regression model, with a random intercept term, to randomly generated overdispersed binomial data.
## David I. Warton and Francis K. C. Hui
## School of Mathematics and Statistics
## The University of New South Wales
## Last modified: 27/7/10
## Some brief details: GLMM’s are fitted in the following code using the lme4 package on R, which you will need to have installed from CRAN. This package fits GLMM’s using Laplace quadrature, which usually provides a good approximation, particularly when fitting a model with one or two random effects terms. If you get a warning that convergence has not been achieved, try using the nAGQ argument (e.g. add ", nAGQ=4" to the line where you call the glmer function) to fit the model using a more accurate but more computationally intensive approach known as adaptive quadrature.
## REFERENCES ##
## For a general introduction to GLMM:
## Benjamin M. Bolker, Mollie E. Brooks, Connie J. Clark, Shane W. Geange, John R. Poulsen, M. Henry H. Stevens and Jada-Simone S. White (2009) Generalized linear mixed models: a practical guide for ecology and evolution. Trends in Ecology & Evolution, 24 (3), 127-135.
## For further details on implementing GLMM in R or S-Plus:
## José C. Pinheiro, Douglas M. Bates (2009) Mixed-Effects Models in S and S-PLUS, Second edition. Springer-Verlag, New York, USA.
## For details on implementing GLMM in SAS:
## Ramon C. Littell, George A. Milliken, Walter W. Stroup, Russell D. Wolfinger, Oliver Schabenberber (2006) SAS for Mixed Models, Second Edition. SAS Institute, Cary, USA.
## NOTE - the below code currently does not run when using R 2.9.1 or a later version, instead returning the error "Number of levels of a grouping factor for the random effects must be less than the number of observations". This error message should not appear, and if it does appear the problem can be avoided by expanding the dataset out into a Bernoulli response (see end of code), or by downloading and installing an older version of the package:
## Matrix Package:- R package version 0.999375-24
## lme4 Package: - R package version 0.999375-31
## Enjoy massaging your data!
#########################################################################################
## GENERATING AN EXAMPLE DATASET FOR ANALYSIS ##
## In order to illustrate the used of GLMM, over-dispersed binomial data are generated here according to a balanced one-way ANOVA design, with 15 “species” at each of four levels of the factor “location”.
species = 1:60 # We assume that the 60 rows of the dataset correspond to 60 different species.
location = c(rep("australia",15), rep("canada",15), rep("argentina",15), rep("china",15))
sample.size = 12
p = c(rep(0.3,15), rep(0.4,15), rep(0.5,15), rep(0.6,15))
eta = log( p/(1-p) ) + rnorm(60)
p = exp(eta) / ( exp(eta) + 1 )
success = rbinom(60, size=sample.size, prob=p)
failure = sample.size - success
location = factor(location)
dataset = data.frame(location, species, sample.size, success, failure)
rm(location, species, success, failure)
#########################################################################################
## ANALYSIS OF EXAMPLE DATASET ##
attach(dataset)
## Plot the sample proportions against location
plot(success/sample.size ~ location)
## Logistic regression (fixed effects)
fit.glm = glm(cbind(success, failure) ~ location, family = binomial)#, dataset=dataset)
anova(fit.glm, test = "Chisq")
summary(fit.glm)
(fit.p.hat <- exp(coef(fit.glm)) / (exp(coef(fit.glm)) + 1)) # expected probabilities
## Check to see if residual deviance is large relative to residual df.
## Note that for the data generated above, the residual deviance is over twice as large as the residual df, so there is clear evidence that the data are overdispersed.
## This means that a GLMM should be fitted, with a random term for species (row):
## GLMM
library(lme4)
fit.glmm = glmer(cbind(success, failure) ~ location + (1|species), family = binomial, data=dataset)
fit.glmm.intercept = glmer(cbind(success, failure) ~ 1 + (1|species), family = binomial, data=dataset)
anova(fit.glmm.intercept, fit.glmm)
## Note the significant evidence of a location effect.
## If you got the error message "Number of levels of a grouping factor for the random effects must be less than the number of observations", see code at the end.
#########################################################################################
## PRODUCING DIAGNOSTIC PLOTS ##
## Logistic regression
plot(fit.glm$fit, residuals(fit.glm), pch = 19, las = 1, cex = 1.4)
abline(0,0,lwd = 1.5)
## check for no pattern
## GLMM
par(mfrow=c(1,2))
## first we plot random effects against the predicted values from the fixed effect component of the model and check for no trend:
m = model.matrix(fit.glmm)
ft.fix = m %*% fixef(fit.glmm)
plot(ft.fix, ranef(fit.glmm, drop = T)$species, pch = 19, las = 1, cex = 1.4)
abline(0,0,lwd = 1.5)
## now check for approximate normality of random effects:
qqnorm(ranef(fit.glmm, drop = T)$species, pch = 19, las = 1, cex = 1.4)
#########################################################################################
## WORK_AROUND IF YOU GOT AN ERROR RUNNING GLMM ##
## If you got the error message "Number of levels of a grouping factor for the random effects must be less than the number of observations": this is because lme4 has a bug in R version 2.9.1 (which we hope will be fixed soon)! You can either use an older version of lme4 for analysis or as a work-around you can expand your dataset out and fit the glmm as in the below:
detach(dataset)
## Create an expanded dataset based on dataset (this can readily be used on your own data, it just requires a data.frame called "dataset" containing successes and failures labelled as "success" and "failure"):
dataset.expanded = dataset[0,]
for (i in 1:length(dataset$success))
{
if(dataset$success[i]>0)
{
dataset.add.succ = dataset[rep(i,dataset$success[i]),]
dataset.add.succ$success=1
dataset.add.succ$failure=0
dataset.expanded=rbind(dataset.expanded, dataset.add.succ)
}
if(dataset$failure[i]>0)
{
dataset.add.fail = dataset[rep(i,dataset$failure[i]),]
dataset.add.fail$success=0
dataset.add.fail$failure=1
dataset.expanded=rbind(dataset.expanded, dataset.add.fail)
}
}
## Fit the GLMM’s
fit.glmm = glmer(success ~ location + (1|species), family = binomial, data=dataset.expanded)
fit.glmm.intercept = glmer(success ~ 1 + (1|species), family = binomial, data=dataset.expanded)
anova(fit.glmm.intercept, fit.glmm)
## Construct residual plots:
par(mfrow=c(1,2))
## first plot random effects against the predicted values and check for no trend:
m = model.matrix(fit.glmm)
ft.fix = m%*%fixef(fit.glmm)
rans = t(as.matrix(fit.glmm@Zt)) %*% ranef(fit.glmm)$species[[1]]
plot(ft.fix, rans, pch = 19, las = 1, cex = 1.4)
abline(0,0,lwd = 1.5)
## now check for approximate normality of random effects:
qqnorm(ranef(fit.glmm, drop = T)$species, pch = 19, las = 1, cex = 1.4)
|
284564395488a11945f2736898f741f22a42ba17
|
3a666fae684fd17095328e2972e367e7d596c925
|
/week8/code/Models.R
|
b1fd7db77f7f181cd9a88b370ce8a29262b32148
|
[] |
no_license
|
emmadeeks/CMEECourseWork
|
65a9628626a8216f622fa6fd3043086814729f71
|
c21dd8545930ef50c3ceef5a4d4a1d6d92a2786b
|
refs/heads/master
| 2021-07-12T09:36:33.989736
| 2020-10-20T15:23:59
| 2020-10-20T15:23:59
| 212,302,148
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,908
|
r
|
Models.R
|
rm(list=ls()) #Clear global environment
#Set working directory
setwd("/Users/emmadeeks/Desktop/CMEECourseWork/week8/data")
# Get thee required packages
require('minpack.lm')
#Explore the data
data <- read.csv('modified_CRat.csv')
head(data)
<<<<<<< HEAD
#Subset data with a nice looking curve to model with
Data2Fit <- subset(data, ID == 39982) #One curve
# Plot the curve
#plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
#This is basically cutting the last points of the graph off
# After the highest point
# Because a needs to fit to just the slope
a.line <- subset(Data2Fit, ResDensity <= mean(ResDensity))
#plot(a.line$ResDensity, a.line$N_TraitValue)
lm <- summary(lm(N_TraitValue ~ ResDensity, a.line))
# Extracts slope value
a <- lm$coefficients[2]
# h parameter is the maximum of the slope so you take the biggest value
h <- max(Data2Fit$N_TraitValue)
q = 078
PowFit <- nlsLM(N_TraitValue ~ powMod(ResDensity, a, h), data = Data2Fit, start = list(a=a, h=h))
# optimising a and h values
Lengths <- seq(min(Data2Fit$ResDensity),max(Data2Fit$ResDensity))
Predic2PlotPow <- powMod(Lengths,coef(PowFit)["a"],coef(PowFit)["h"])
QuaFit <- lm(N_TraitValue ~ poly(ResDensity,2), data = Data2Fit)
Predic2PlotQua <- predict.lm(QuaFit, data.frame(ResDensity = Lengths))
GenFit <- nlsLM(N_TraitValue ~ GenMod(ResDensity, a, h, q), data = Data2Fit, start = list(a=a, h=h, q= q))
Predic2PlotGen <- GenMod(Lengths,coef(GenFit)["a"],coef(GenFit)["h"], coef(GenFit)["q"])
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
lines(Lengths, Predic2PlotGen, col = 'green', lwd = 2.5)
lines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)
lines(Lengths, Predic2PlotQua, col = 'red', lwd = 2.5)
# Get the dimensionsof the curve
=======
#Subset data with a nice looking curve to model with
Data2Fit <- subset(data, ID == 39982) #One curve
# Plot the curve
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
# Get the dimensions of the curve
>>>>>>> 0d7590ae85f1493548f944ace5922e4c47068ab7
dim(Data2Fit) # Get dimensions of curve
#Holling type II functional response
#This is making a function of the second model we looked at
powMod <- function(x, a, h) { #These are parameters
return( (a*x ) / (1+ (h*a*x))) # This is the equation
}
<<<<<<< HEAD
=======
#This is basically cutting the last points of the graph off
# After the highest point
# Because a needs to fit to just the slope
a.line <- subset(Data2Fit, ResDensity <= mean(ResDensity))
plot(a.line$ResDensity, a.line$N_TraitValue)
>>>>>>> 0d7590ae85f1493548f944ace5922e4c47068ab7
#plot slope/ linear regressopn of cut slope
lm <- summary(lm(N_TraitValue ~ ResDensity, a.line))
# Extracts slope value
a <- lm$coefficients[2]
# h parameter is the maximum of the slope so you take the biggest value
h <- max(Data2Fit$N_TraitValue)
#This is fitting the actual model in the function
# This was based on the example but values substituted
PowFit <- nlsLM(N_TraitValue ~ powMod(ResDensity, a, h), data = Data2Fit, start = list(a=a, h=h))
# optimising a and h values
Lengths <- seq(min(Data2Fit$ResDensity),max(Data2Fit$ResDensity))
coef(PowFit)["a"]
coef(PowFit)["h"]
#Apply function on length
Predic2PlotPow <- powMod(Lengths,coef(PowFit)["a"],coef(PowFit)["h"])
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
lines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)
paraopt = as.data.frame(matrix(nrow = 1, ncol = 4))
for(i in 1:100){
anew = rnorm(1, mean = a, sd=1)
hnew = rnorm(1, mean = h, sd=1)
PowFit <- nlsLM(N_TraitValue ~ powMod(ResDensity, a, h), data = Data2Fit, start = list(a= anew, h= hnew))
AIC = AIC(PowFit)
p <- c(i, anew, hnew, AIC)
paraopt = rbind(paraopt, p)
}
min_values <- paraopt[which.min(paraopt$V4), ]
hN <- min_values$V3
aN <- min_values$V2
PowFit <- nlsLM(N_TraitValue ~ powMod(ResDensity, a, h), data = Data2Fit, start = list(a= aN, h= hN))
Predic2PlotPow <- powMod(Lengths,coef(PowFit)["a"],coef(PowFit)["h"])
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
lines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)
# Phenomenological quadratic model
QuaFit <- lm(N_TraitValue ~ poly(ResDensity,2), data = Data2Fit)
Predic2PlotQua <- predict.lm(QuaFit, data.frame(ResDensity = Lengths))
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
lines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)
lines(Lengths, Predic2PlotQua, col = 'red', lwd = 2.5)
AIC(PowFit) - AIC(QuaFit)
#Generalised functional response model
GenMod <- function(x, a, h, q) { #These are parameters
return( (a* x^(q+1) ) / (1+ (h*a*x^(q+1))))
}
<<<<<<< HEAD
GenFit <- nlsLM(N_TraitValue ~ GenMod(ResDensity, a, h, q), data = Data2Fit, start = list(a=a, h=h, q=1))
=======
GenFit <- nlsLM(N_TraitValue ~ GenMod(ResDensity, a, h, q), data = Data2Fit, start = list(a=a, h=h, q= q))
>>>>>>> 0d7590ae85f1493548f944ace5922e4c47068ab7
Predic2PlotGen <- GenMod(Lengths,coef(GenFit)["a"],coef(GenFit)["h"], coef(GenFit)["q"])
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
lines(Lengths, Predic2PlotGen, col = 'green', lwd = 2.5)
lines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)
lines(Lengths, Predic2PlotQua, col = 'red', lwd = 2.5)
q = -1
GenFit <- nlsLM(N_TraitValue ~ GenMod(a, h, ResDensity, q), data = Data2Fit, start = list(a=a, h=h, q=q))
Predic2PlotPow <- GenMod(Lengths,coef(GenFit)["a"],coef(GenFit)["q"],coef(GenFit)["h"])
plot(Data2Fit$ResDensity, Data2Fit$N_TraitValue)
lines(Lengths, Predic2PlotPow, col = 'pink', lwd = 2.5)
#########################################################################
for(i in range(1:100)){
anew = rnorm(1, mean = a, sd=1)
hnew = rnorm(1, mean = h, sd=1)
PowFit <- nlsLM(N_TraitValue ~ powMod(ResDensity, a, h), data = Data2Fit, start = list(a= anew, h=hnew))
AIC = AIC(PowFit)
p <- c(i, anew, hnew, AIC)
paraopt[i,] = c(i, anew, hnew, AIC)
}
|
01f2602b4ba3f4839bf2e908cfc575c26d89cf1c
|
faea5910e781dbefb973a76350ee7c9bd72548a4
|
/07_eda.R
|
d3201c06d1cb7c6e927503ac6537b9dd52614339
|
[] |
no_license
|
lwawrowski/googlenews
|
ddaec3f2e63cb81436599692223adeaddde8c12e
|
beba5aa3620e5b6a07896e9ddd90322cc1d7f2a2
|
refs/heads/master
| 2020-07-04T06:43:10.647162
| 2020-01-16T17:37:47
| 2020-01-16T17:37:47
| 202,191,296
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 604
|
r
|
07_eda.R
|
library(tidyverse)
load("data/googlenews.RData")
googlenews %>%
count(name) %>%
top_n(10, n) %>%
mutate(name=fct_reorder(name, n)) %>%
ggplot(aes(x=name, y=n)) +
geom_col() +
coord_flip()
author_count <- googlenews %>%
count(author)
library(lubridate)
googlenews <- googlenews %>%
mutate(published=as_datetime(publishedAt),
date=date(published),
weekday=wday(published))
googlenews %>%
count(date) %>%
ggplot(aes(x=date, y=n)) +
geom_line()
googlenews %>%
count(weekday) %>%
ggplot(aes(x=as.factor(weekday), y=n)) +
geom_col()
|
1a41b01b966f489ba6ebb1ac435e72a1adacee08
|
d61b84cd394da5e7d63fa983fab0cb7eb33512a6
|
/analytics2/agePrediction2.R
|
e377980f4957711f80a670433e922606ebe84c60
|
[] |
no_license
|
sixitingting/KapowskiChronicles
|
4fd25a9568e654ffe9dee316b97a47f4f131ac15
|
4d7aafaa39135c29bfb073d0d17fa0c0166b01ad
|
refs/heads/master
| 2021-08-14T13:32:21.933757
| 2017-11-15T20:49:24
| 2017-11-15T20:49:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,216
|
r
|
agePrediction2.R
|
library( kernlab )
library( caret )
library( randomForest )
library( ggplot2 )
nPermutations <- 1000
trainingPortions <- c( 0.5 )
for( p in trainingPortions )
{
trainingPortion <- p
cat( "trainingPortion = ", trainingPortion, "\n", sep = '' )
resultsData <- data.frame( Pipeline = character( 0 ), Correlation = numeric( 0 ), MeanErrors = numeric( 0 ) )
for( n in seq( 1, nPermutations, by = 1 ) )
{
cat( " Permutation ", n, "\n", sep = '' )
thicknessTypes = c( 'ANTs', 'FreeSurfer' )
for( whichPipeline in thicknessTypes )
{
resultsIXI <- read.csv( paste0( 'labelresults', whichPipeline, 'I.csv' ) )
resultsKirby <- read.csv( paste0( 'labelresults', whichPipeline, 'K.csv' ) )
resultsNKI <- read.csv( paste0( 'labelresults', whichPipeline, 'N.csv' ) )
resultsOasis <- read.csv( paste0( 'labelresults', whichPipeline, 'O.csv' ) )
resultsCombined <- rbind( resultsIXI, resultsKirby, resultsNKI, resultsOasis )
resultsCombined$SITE <- as.factor( resultsCombined$SITE )
resultsCombined$SEX <- as.factor( resultsCombined$SEX )
resultsCombined <- resultsCombined[which( resultsCombined$AGE >= 20 & resultsCombined$AGE <= 80 ),]
corticalLabels <- tail( colnames( resultsCombined ), n = 62 )
drops <- c( "ID", "SITE" )
resultsCombined <- resultsCombined[, !( names( resultsCombined ) %in% drops )]
trainingIndices <- createDataPartition( resultsCombined$SEX, p = trainingPortion, list = FALSE, times = 1 )
trainingData <- resultsCombined[trainingIndices,]
testingData <- resultsCombined[-trainingIndices,]
brainAgeRF <- randomForest( AGE ~ ., data = trainingData,
na.action = na.omit, replace = FALSE, ntree = 200 )
predictedAge <- predict( brainAgeRF, testingData )
# regionalQuadraticTerms <- paste0( "I(", corticalLabels, collapse = "^2) * SEX + " )
# myFormula <- as.formula( paste( "AGE ~ SEX + ", regionalTerms, " + ", regionalQuadraticTerms, "^2) + VOLUME ", sep = '' ) )
# regionalTerms <- paste( corticalLabels, collapse = " + " )
# myFormula <- as.formula( paste( "AGE ~ SEX + ", regionalTerms, " + VOLUME ", sep = '' ) )
# brainAgeLM <- lm( myFormula, data = trainingData, na.action = na.omit )
# predictedAge <- predict( brainAgeLM, testingData )
rmse <- sqrt( mean( ( ( testingData$AGE - predictedAge )^2 ), na.rm = TRUE ) )
oneData <- data.frame( Pipeline = whichPipeline, RMSE = rmse )
resultsData <- rbind( resultsData, oneData )
}
}
rmsePlot <- ggplot( resultsData, aes( x = RMSE, fill = Pipeline ) ) +
scale_y_continuous( "Density" ) +
scale_x_continuous( "RMSE", limits = c( 9, 14. ) ) +
geom_density( alpha = 0.5 )
ggsave( filename = paste( "~/Desktop/rfRmse", p, ".pdf", sep = "" ), plot = rmsePlot, width = 6, height = 6, units = 'in' )
cat( "Mean FS rmse = ", mean( resultsData$RMSE[which( resultsData$Pipeline == 'FreeSurfer' )], na.rm = TRUE ), "\n", sep = '' );
cat( "Mean ANTs rmse = ", mean( resultsData$RMSE[which( resultsData$Pipeline == 'ANTs' )], na.rm = TRUE ), "\n", sep = '' );
}
|
807efc78bedd859cfba36bbe697012d0185edb85
|
6e3c81e90730c199a0536854374010f3527bc292
|
/analysis_scripts/ggcorr.R
|
755b849839605c678006ef4f8be45c4c377933c2
|
[] |
no_license
|
camposfa/plhdbR
|
0d01acc33a5d4878c9ddf3d2857396d837dc8fca
|
4472c22d45835dde05debf4c0659c21a19c3bdcd
|
refs/heads/master
| 2020-05-17T23:51:35.521989
| 2017-09-12T13:26:02
| 2017-09-12T13:26:02
| 32,407,178
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 12,823
|
r
|
ggcorr.R
|
ggcorr_fc <- function (data, method = c("pairwise", "pearson"), cor_matrix = NULL,
nbreaks = NULL, digits = 2, name = "", low = "#3B9AB2", mid = "#EEEEEE",
high = "#F21A00", midpoint = 0, palette = NULL, geom = "tile", tile_color = "white",
min_size = 2, max_size = 6, label = FALSE, label_alpha = FALSE,
label_color = "black", label_round = 1, label_size = 4, limits = c(-1, 1),
drop = is.null(limits) || identical(limits, FALSE),
layout.exp = 0, legend.position = "right", legend.size = 9,
...)
{
if (is.numeric(limits)) {
if (length(limits) != 2) {
stop("'limits' must be of length 2 if numeric")
}
}
if (is.logical(limits)) {
if (limits) {
limits <- c(-1, 1)
}
else {
limits <- NULL
}
}
if (length(geom) > 1 || !geom %in% c("blank", "circle", "text",
"tile")) {
stop("incorrect geom value")
}
if (length(method) == 1) {
method = c(method, "pearson")
}
if (!is.null(data)) {
if (!is.data.frame(data)) {
data = as.data.frame(data)
}
x = which(!sapply(data, is.numeric))
if (length(x) > 0) {
warning(paste("data in column(s)", paste0(paste0("'",
names(data)[x], "'"), collapse = ", "), "are not numeric and were ignored"))
data = data[, -x]
}
}
if (is.null(cor_matrix)) {
cor_matrix = cor(data, use = method[1], method = method[2])
}
m = cor_matrix
colnames(m) = rownames(m) = gsub(" ", "_", colnames(m))
m = data.frame(m * lower.tri(m))
rownames(m) = names(m)
m$.ggally_ggcorr_row_names = rownames(m)
m = reshape2::melt(m, id.vars = ".ggally_ggcorr_row_names")
names(m) = c("x", "y", "coefficient")
m$coefficient[m$coefficient == 0] = NA
if (!is.null(nbreaks)) {
x = seq(-1, 1, length.out = nbreaks + 1)
if (!nbreaks%%2) {
x = sort(c(x, 0))
}
m$breaks = cut(m$coefficient, breaks = unique(x), include.lowest = TRUE,
dig.lab = digits)
}
if (is.null(midpoint)) {
midpoint = median(m$coefficient, na.rm = TRUE)
message(paste("Color gradient midpoint set at median correlation to",
round(midpoint, 2)))
}
m$label = round(m$coefficient, label_round)
p = ggplot(na.omit(m), aes(x, y))
if (geom == "tile") {
if (is.null(nbreaks)) {
p = p + geom_tile(aes(fill = coefficient), color = tile_color)
}
else {
p = p + geom_tile(aes(fill = breaks), color = tile_color)
}
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_fill_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_fill_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_fill_manual(name, values = x, drop = drop)
}
else {
p = p + scale_fill_manual(name, values = palette, drop = FALSE)
}
}
else if (geom == "circle") {
p = p + geom_point(aes(size = abs(coefficient) * 1.25),
color = "grey50")
if (is.null(nbreaks)) {
p = p + geom_point(aes(size = abs(coefficient), color = coefficient))
}
else {
p = p + geom_point(aes(size = abs(coefficient), color = breaks))
}
p = p + scale_size_continuous(range = c(min_size, max_size)) +
guides(size = FALSE)
r = list(size = (min_size + max_size)/2)
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_color_manual(name, values = x, drop = drop) +
guides(color = guide_legend(override.aes = r))
}
else {
p = p + scale_color_gradientn(colors = palette) + guides(color = guide_legend(override.aes = r))
}
}
else if (geom == "text") {
if (is.null(nbreaks)) {
p = p + geom_text(aes(label = label, color = coefficient),
size = label_size)
}
else {
p = p + geom_text(aes(label = label, color = breaks),
size = label_size)
}
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_color_manual(name, values = x, drop = drop)
}
else {
p = p + scale_color_gradientn(colors = palette)
}
}
if (label) {
if (isTRUE(label_alpha)) {
p = p + geom_text(aes(x, y, label = label, alpha = abs(coefficient)),
color = label_color, size = label_size, show.legend = FALSE)
}
else if (label_alpha > 0) {
p = p + geom_text(aes(x, y, label = label, show_guide = FALSE),
alpha = label_alpha, color = label_color, size = label_size)
}
else {
p = p + geom_text(aes(x, y, label = label), color = label_color,
size = label_size)
}
}
textData <- m[m$x == m$y & is.na(m$coefficient), ]
xLimits <- levels(textData$y)
textData$diagLabel <- textData$x
if (!is.numeric(layout.exp) || layout.exp < 0) {
stop("incorrect layout.exp value")
}
else if (layout.exp > 0) {
layout.exp <- as.integer(layout.exp)
textData <- rbind(textData[1:layout.exp, ], textData)
spacer <- paste(".ggally_ggcorr_spacer_value", 1:layout.exp,
sep = "")
textData$x[1:layout.exp] <- spacer
textData$diagLabel[1:layout.exp] <- NA
xLimits <- c(spacer, levels(m$y))
}
p = p + geom_text(data = textData, aes_string(label = "diagLabel"),
..., na.rm = TRUE) + scale_x_discrete(breaks = NULL,
limits = xLimits) + scale_y_discrete(breaks = NULL, limits = levels(m$y)) +
labs(x = NULL, y = NULL) + coord_equal() + theme(panel.background = element_blank(),
legend.key = element_blank(), legend.position = legend.position,
legend.title = element_text(size = legend.size), legend.text = element_text(size = legend.size))
return(p)
}
ggcorr_fc2 <- function (data, nbreaks = NULL, digits = 2, name = "", low = "#3B9AB2", mid = "#EEEEEE",
high = "#F21A00", midpoint = 0, palette = NULL, geom = "tile", tile_color = "white",
min_size = 2, max_size = 6, label = FALSE, label_alpha = FALSE,
label_color = "black", label_round = 1, label_size = 4, limits = c(-1, 1),
drop = is.null(limits) || identical(limits, FALSE),
layout.exp = 0, legend.position = "right", legend.size = 9,
...)
{
if (is.numeric(limits)) {
if (length(limits) != 2) {
stop("'limits' must be of length 2 if numeric")
}
}
if (is.logical(limits)) {
if (limits) {
limits <- c(-1, 1)
}
else {
limits <- NULL
}
}
if (length(geom) > 1 || !geom %in% c("blank", "circle", "text",
"tile")) {
stop("incorrect geom value")
}
m <- data
p = ggplot(na.omit(m), aes(x, y))
if (geom == "tile") {
if (is.null(nbreaks)) {
p = p + geom_tile(aes(fill = coefficient), color = tile_color)
}
else {
p = p + geom_tile(aes(fill = breaks), color = tile_color)
}
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_fill_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_fill_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_fill_manual(name, values = x, drop = drop)
}
else {
p = p + scale_fill_manual(name, values = palette, drop = FALSE)
}
}
else if (geom == "circle") {
p = p + geom_point(aes(size = abs(coefficient) * 1.25),
color = "grey50")
if (is.null(nbreaks)) {
p = p + geom_point(aes(size = abs(coefficient), color = coefficient))
}
else {
p = p + geom_point(aes(size = abs(coefficient), color = breaks))
}
p = p + scale_size_continuous(range = c(min_size, max_size)) +
guides(size = FALSE)
r = list(size = (min_size + max_size)/2)
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_color_manual(name, values = x, drop = drop) +
guides(color = guide_legend(override.aes = r))
}
else {
p = p + scale_color_gradientn(colors = palette) + guides(color = guide_legend(override.aes = r))
}
}
else if (geom == "text") {
if (is.null(nbreaks)) {
p = p + geom_text(aes(label = label, color = coefficient),
size = label_size)
}
else {
p = p + geom_text(aes(label = label, color = breaks),
size = label_size)
}
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_color_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_color_manual(name, values = x, drop = drop)
}
else {
p = p + scale_color_gradientn(colors = palette)
}
}
if (label) {
if (isTRUE(label_alpha)) {
p = p + geom_text(aes(x, y, label = label, alpha = abs(coefficient)),
color = label_color, size = label_size, show.legend = FALSE)
}
else if (label_alpha > 0) {
p = p + geom_text(aes(x, y, label = label, show_guide = FALSE),
alpha = label_alpha, color = label_color, size = label_size)
}
else {
p = p + geom_text(aes(x, y, label = label), color = label_color,
size = label_size)
}
}
textData <- m[m$x == m$y & is.na(m$coefficient), ]
xLimits <- levels(textData$y)
textData$diagLabel <- textData$x
if (!is.numeric(layout.exp) || layout.exp < 0) {
stop("incorrect layout.exp value")
}
else if (layout.exp > 0) {
layout.exp <- as.integer(layout.exp)
textData <- rbind(textData[1:layout.exp, ], textData)
spacer <- paste(".ggally_ggcorr_spacer_value", 1:layout.exp,
sep = "")
textData$x[1:layout.exp] <- spacer
textData$diagLabel[1:layout.exp] <- NA
xLimits <- c(spacer, levels(m$y))
}
p = p + geom_text(data = textData, aes_string(label = "diagLabel"),
..., na.rm = TRUE) + scale_x_discrete(breaks = NULL,
limits = xLimits) + scale_y_discrete(breaks = NULL, limits = levels(m$y)) +
labs(x = NULL, y = NULL) + coord_equal() + theme(panel.background = element_blank(),
legend.key = element_blank(), legend.position = legend.position,
legend.title = element_text(size = legend.size), legend.text = element_text(size = legend.size))
return(p)
}
|
03daa0e2a5c1e05efb646955d298750875762842
|
1eec56205889241fc9e47443f5534216acbac52c
|
/man/smargins.Rd
|
eb94646f6ed883595c34e6f24ec7de23eef9e6aa
|
[] |
no_license
|
izahn/smargins
|
fac638a907e5ca75452bd399de27d007162ea68e
|
949f8fc9e4729c19a22e2512c701fae2c422e69e
|
refs/heads/master
| 2021-05-07T02:52:32.980547
| 2019-09-10T19:33:53
| 2019-09-10T19:33:53
| 110,725,408
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 835
|
rd
|
smargins.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/smargin.R
\name{smargins}
\alias{smargins}
\title{Calculate average marginal effects from a fitted model object.}
\usage{
smargins(model, ..., n = 1000)
}
\arguments{
\item{model}{A fitted model object.}
\item{...}{Further arguments passed to or from other methods.}
\item{n}{Number of simulations to run.}
\item{at}{A named list of values to set predictor variables to.}
}
\value{
A data.frame containing predictor variables values and
expected values of the dependant variable.
}
\description{
Calculate average marginal effects from a fitted model object.
}
\examples{
library(smargins)
lm.out <- lm(Fertility ~ Education, data = swiss)
smargins(lm.out, at = list(Education = quantile(swiss$Education, c(.25, .50, .75))))
}
\author{
Ista Zahn
}
|
9adfc62a139f6f41e9933108d90de45d9c9fa811
|
a3a6cd9ca2730c4b9807eceb99eb77e18e15d6ce
|
/example.R
|
9c14bfad87c46296f8c3f2c492374770a26903fa
|
[] |
no_license
|
Shaun-Roberts/Honors-Dissertation-2017
|
820041eed57a3bf75adcb5ea0e1f4a36242619c5
|
908b27a1d1881f7072e42fda806c349b0bccf3af
|
refs/heads/master
| 2021-07-22T02:32:33.425820
| 2017-10-30T04:26:13
| 2017-10-30T04:26:13
| 91,649,868
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,530
|
r
|
example.R
|
example = function(ylimits = c(0,100), step_size = 25){
data = c("sampson", "kapferer", "samplk", "faux.mesa.high")
lincol = c("#D7191C", "#FDAE61", "#ABD9E9", "#c351e2")
linewidth = 2
ydiffs = diff(ylimits)
yupper = ylimits[2]
ylower = ylimits[1]
layout(c(1,1,1,2))
plot.new()
plot.window(xlim = c(0,100), ylim = c(0,3*ydiffs), xaxs = "i", yaxs = "i")
#Axes
{
axis(1,
at = seq(0,100, 10),
labels = c(seq(0, 40, 10), seq(0, 50, 10)),
las = 1
)
axis(2,
at = seq(0,ydiffs, step_size),
labels = seq(ylower, yupper, step_size),
las = 1
)
axis(2,
at = seq(0,ydiffs, step_size) + 2*ydiffs,
labels = seq(ylower, yupper, step_size),
las = 1
)
axis(3,
at = 50,
labels = "",
lwd = 2
)
axis(1,
at = 50,
labels = "",
lwd = 2
)
axis(4,
at = seq(0,ydiffs, step_size) + ydiffs,
labels = seq(ylower, yupper, step_size),
las = 1
)
}
# Horizontal dividing lines:
abline(h = c(ydiffs, 2*ydiffs), lwd = 1)
#Titles
title(xlab = "False Negative Rate",
ylab = "Metric Mean or Standard Deviation",
main = "Metric Mean or Standard Deviation \nNetwork Size (n)")
#Vertical dividing lines and box
abline(v = 50, lwd = 2)
box(lwd = 1)
text(25 , 250,"False positive rate of 0")
text(75 , 250,"False positive rate of 0.01")
text(25 , 150,"False positive rate of 0.05")
text(75 , 150,"False positive rate of 0.10")
text(25 , 50,"False positive rate of 0.15")
text(75 , 50,"False positive rate of 0.20")
# legend("top", legend = data, col = lincol, lty = rep(1,4), pch = "", horiz = T, text.width = 17.3, lwd = 2, cex = 1, x.intersp = 0.2)
# legend("topleft", legend = data[1:2], col = lincol[1:2], lty = rep(1,2), pch = "", bty = "n", horiz = F, text.width = 10, lwd = 2, cex = 1)#, adj = 0.2)
# legend("top", legend = data[3:4], col = lincol[3:4], lty = rep(1,2), pch = "", bty = "n", horiz = F, text.width = 10, lwd = 2, cex = 1)#, adj = 0.2)
# legend("top", legend = data, col = lincol, lty = rep(1,4), pch = "", bty = "n", horiz = T, text.width = 1, lwd = 2)
plot.new()
#box()
legend("top", legend = data, col = lincol, lty = rep(1,4), pch = "", horiz = T, text.width = 0.22, lwd = 6, cex = 1, x.intersp = 0.2)
}
example()
pdf("example_plots.pdf")
par(mar = c(2,4,3,3))
example()
dev.off()
|
7822b7cca2ebbafc4efa1eb1e15911f76b7077b8
|
a23c67bdf8ed4d329ede8264ad34c555123ab16c
|
/R/getDesignWgts.R
|
4674d55173937fd0664b0a56913d053af3a641e6
|
[] |
no_license
|
hunter-stanke/rFIA
|
49af16f35f6322e950c404ef94f90464fff3aaa3
|
22458bafa6ca6c10b739e96aa01ae51e1fc34157
|
refs/heads/master
| 2023-05-01T15:34:29.888205
| 2023-04-09T03:25:37
| 2023-04-09T03:25:37
| 200,692,052
| 47
| 18
| null | 2023-04-14T15:37:04
| 2019-08-05T16:33:04
|
R
|
UTF-8
|
R
| false
| false
| 7,530
|
r
|
getDesignWgts.R
|
#' @export
## Pull strata and estimation units weights for a given inventory
getDesignInfo <- function(db,
type = c('ALL','CURR','VOL','GROW','MORT',
'REMV','CHNG','DWM','REGEN'),
mostRecent = TRUE,
evalid = NULL) {
## Must have an FIA.Database or a remote one
if (!c(class(db) %in% c('FIA.Database', 'Remote.FIA.Database'))) {
stop('Must provide an `FIA.Database` or `Remote.FIA.Database`. See `readFIA` and/or `getFIA` to read and load your FIA data.')
}
## Type must exist
if (all(!c(class(type) == 'character'))) {
stop('`type` must be a character vector. Please choose one of (or a combination of): `ALL`, `CURR`, `VOL`, `GROW`, `MORT`, `REMV`, `CHNG`, `DWM`,` REGEN`.')
}
type <- unique(stringr::str_to_upper(type))
if (sum(type %in% c('ALL','CURR','VOL','GROW','MORT', 'REMV','CHNG','DWM','REGEN')) < length(type)) {
bad.type = type[!c(type %in% c('ALL','CURR','VOL','GROW','MORT', 'REMV','CHNG','DWM','REGEN'))]
stop(paste0("Don't recognize `type`: ", paste(as.character(bad.type), collapse = ', '), ". Please choose one of (or a combination of): `ALL`, `CURR`, `VOL`, `GROW`, `MORT`, `REMV`, `CHNG`, `DWM`,` REGEN`."))
}
## Most recent must be logical
if (!c(mostRecent %in% 0:1)) {
stop('`mostRecent` must be logical, i.e., TRUE or FALSE.')
}
## Make the sure the necessary tables are present in db
req.tables <- c('PLOT', 'POP_EVAL', 'POP_EVAL_TYP', 'POP_ESTN_UNIT', 'POP_STRATUM', 'POP_PLOT_STRATUM_ASSGN')
if (class(db) == 'FIA.Database') {
if (sum(req.tables %in% names(db)) < length(req.tables)) {
missing.tables <- req.tables[!c(req.tables %in% names(db))]
stop(paste(paste (as.character(missing.tables), collapse = ', '), 'tables not found in object db.'))
}
} else {
## Read the tables we need, readFIA will throw a warning if they are missing
db <- readFIA(dir = db$dir,
con = db$con,
schema = db$schema,
common = db$common,
tables = c('PLOT', 'POP_EVAL', 'POP_EVAL_TYP', 'POP_ESTN_UNIT', 'POP_STRATUM', 'POP_PLOT_STRATUM_ASSGN'),
states = db$states)
}
## Use clipFIA to handle the most recent subset if desired
if (mostRecent) {
db <- clipFIA(db)
}
## Fix TX problems with incomplete labeling of E v. W TX
db <- handleTX(db)
## WY and NM list early FHM inventories, but they don't work, so dropping
if (any(c(35, 56) %in% unique(db$POP_EVAL$STATECD))) {
db$POP_EVAL <- db$POP_EVAL %>%
dplyr::mutate(cut.these = dplyr::case_when(STATECD %in% c(35, 56) & END_INVYR < 2001 ~ 1,
TRUE ~ 0)) %>%
dplyr::filter(cut.these == 0) %>%
dplyr::select(-c(cut.these))
}
## Pull together info for all evals listed in db
evals <- db$POP_EVAL %>%
## Slim it down
dplyr::select(EVAL_CN = CN, STATECD, YEAR = END_INVYR, EVALID, ESTN_METHOD) %>%
## Join eval type
dplyr::left_join(dplyr::select(db$POP_EVAL_TYP, EVAL_CN, EVAL_TYP), by = 'EVAL_CN') %>%
dplyr::filter(!is.na(EVAL_TYP))
## If EVALID given, make sure it doesn't conflict w/ type
if ( !is.null(evalid) ) {
## Does the EVALID exist?
if (!c(evalid %in% evals$EVALID)) {
if (mostRecent) {
stop(paste0('Specified `evalid` (', evalid, ') not found in `db`. Are you sure you want the most recent inventory (i.e., mostRecent=TRUE)?'))
} else {
stop(paste0('Specified `evalid` (', evalid, ') not found in `db`.'))
}
}
## Subset evals
evals <- dplyr::filter(evals, EVALID %in% evalid)
implied.type <- stringr::str_sub(evals$EVAL_TYP, 4, -1)
if (!c(implied.type %in% type)) {
stop(paste0('Specified `evalid` (', evalid, ') implies `type` ', implied.type, ', which conflicts with specified `type`: ', paste(as.character(type), collapse = ', '), '.' ))
}
## If EVALID not given, then subset by type. EVALID does this automatically
} else {
## Check that the type is available for all states
states <- unique(evals$STATECD)
for (i in states) {
check.states <- evals %>%
dplyr::filter(STATECD == i) %>%
dplyr::left_join(intData$stateNames, by = 'STATECD')
state.types <- stringr::str_sub(unique(check.states$EVAL_TYP), 4, -1)
if (sum(type %in% state.types) < length(type) & length(type) < 9) {
bad.type = type[!c(type %in% state.types)]
warning(paste0(check.states$STATEAB[1], " doesn't include `type`(s): ", paste(as.character(bad.type), collapse = ', '), "."))
}
}
## Subset evals
evals <- dplyr::filter(evals, EVAL_TYP %in% paste0('EXP', type))
}
## Get remaining design info
strata <- evals %>%
## Drop all periodic inventories
dplyr::filter(YEAR >= 2003) %>%
## Join estimation unit
dplyr::left_join(dplyr::select(db$POP_ESTN_UNIT, ESTN_UNIT_CN = CN,
P1PNTCNT_EU, AREA_USED, EVAL_CN), by = 'EVAL_CN') %>%
## Join stratum
dplyr::left_join(dplyr::select(db$POP_STRATUM, ESTN_UNIT_CN,
STRATUM_CN = CN, P1POINTCNT,
P2POINTCNT, ADJ_FACTOR_MICR,
ADJ_FACTOR_SUBP, ADJ_FACTOR_MACR),
by = c('ESTN_UNIT_CN')) %>%
## Proportionate size of strata w/in estimation units
dplyr::mutate(STRATUM_WGT = P1POINTCNT / P1PNTCNT_EU) %>%
## Join plots to stratum
dplyr::left_join(dplyr::select(db$POP_PLOT_STRATUM_ASSGN, PLT_CN, STRATUM_CN,
UNITCD, COUNTYCD, PLOT), by = 'STRATUM_CN') %>%
## pltID is used to track plots through time
dplyr::left_join(dplyr::select(db$PLOT, PLT_CN = CN), by = 'PLT_CN') %>%
dplyr::mutate(pltID = stringr::str_c(UNITCD, STATECD, COUNTYCD, PLOT, sep = "_")) %>%
dplyr::select(STATECD, YEAR, EVAL_TYP, EVALID, EVAL_TYP, ESTN_METHOD,
ESTN_UNIT_CN, AREA_USED,
STRATUM_CN, P2POINTCNT:ADJ_FACTOR_MACR, STRATUM_WGT,
pltID, PLT_CN) %>%
dplyr::distinct()
## If a CHNG inventory, then add GROWTH_ACCT
if (any(paste0('EXP', type) %in% c('EXPMORT', 'EXPREMV', 'EXPGROW'))) {
strata <- strata %>%
dplyr::left_join(dplyr::select(db$POP_EVAL, EVALID, GROWTH_ACCT), by = 'EVALID') %>%
dplyr::relocate(GROWTH_ACCT, .after = EVALID)
}
# ## Add non-response adjustment factors, n plots per stratum and estimation unit
# strata <- strata %>%
# dplyr::left_join(dplyr::select(db$POP_STRATUM, STRATUM_CN = CN, P2POINTCNT,
# ADJ_FACTOR_MACR, ADJ_FACTOR_SUBP, ADJ_FACTOR_MICR),
# by = 'STRATUM_CN') %>%
# dplyr::relocate(P2POINTCNT:ADJ_FACTOR_MICR, .after = STRATUM_CN) %>%
# dplyr::left_join(dplyr::select(db$POP_EVAL, EVALID, ESTN_METHOD),
# by = 'EVALID') %>%
# dplyr::relocate(c(EVAL_TYP, ESTN_METHOD), .after = EVALID)
## Sum up number of plots per estimation unit
p2eu <- strata %>%
dplyr::distinct(ESTN_UNIT_CN, STRATUM_CN, P2POINTCNT) %>%
dplyr::group_by(ESTN_UNIT_CN) %>%
dplyr::summarise(P2PNTCNT_EU = sum(P2POINTCNT, na.rm = TRUE)) %>%
dplyr::ungroup()
# Add to original table
strata <- strata %>%
dplyr::left_join(p2eu, by = 'ESTN_UNIT_CN') %>%
dplyr::relocate(P2PNTCNT_EU, .after = ESTN_UNIT_CN)
return(strata)
}
|
f0fff1965832339f407ddaa3f91727943e3baab6
|
0675a7da09eeca4377887549dcaa3ed4a2e24d43
|
/inst/doc/how_to.R
|
855ef6b7d4a529bec764647bd50e7f8bad5f677e
|
[] |
no_license
|
cran/PropensitySub
|
40fc763f32e0f755bea4c14d3ea34b81de1850b9
|
7daf869c4fcb7bce826396cd1ddd84492d40297f
|
refs/heads/master
| 2023-06-25T19:44:54.655226
| 2021-07-29T07:50:11
| 2021-07-29T07:50:11
| 390,773,073
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 9,755
|
r
|
how_to.R
|
## ---- message=FALSE, warning=FALSE, comment=""--------------------------------
library(PropensitySub)
library(dplyr)
head(biomarker, 3)
# Control arm subjects have no STRATUM measurments
# Experimental arm subjects partially miss STRATUM measurement.
table(biomarker$Arm, biomarker$STRATUM, useNA = "ifany")
## ---- message=FALSE-----------------------------------------------------------
biomarker <- biomarker %>%
mutate(
indicator_1 = case_when(
STRATUM == "Positive" ~ 1,
STRATUM == "Negative" ~ 0,
# impute missing as "Negative" in Experimental Arm
Arm == "Experimental" & is.na(STRATUM) ~ 0,
is.na(STRATUM) & Arm == "Control" ~ -1
),
indicator_2 = case_when(
STRATUM == "Positive" ~ 1,
STRATUM == "Negative" ~ 0,
# keep missing as a seperate stratum in Experimental Arm
Arm == "Experimental" & is.na(STRATUM) ~ 2,
is.na(STRATUM) & Arm == "Control" ~ -1
),
# treatment group needs to be factor
Arm = factor(Arm, levels = c("Control", "Experimental"))
)
## ---- message=FALSE, comment=""-----------------------------------------------
# `plain` model with IPW method and aggressive imputation where missing is imputated as negative
ipw_plain_str2 <- ipw_strata(
data.in = biomarker, formula = indicator_1 ~ ECOG + Sex + Age, model = "plain",
indicator.var = "indicator_1", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0)
)
# get weighted HRs
ipw_plain_str2$stat
# check model converge
ipw_plain_str2$converged
# get weights
ipw_plain_str2$data %>%
dplyr::select(Patient.ID, Arm, STRATUM, ECOG, Sex, Age, indicator_1, pred1, pred0) %>%
head()
# `plain` model with IPW method and missing is kept as another stratum
ipw_plain_str3 <- ipw_strata(
data.in = biomarker, formula = indicator_2 ~ ECOG + Sex + Age, model = "plain",
indicator.var = "indicator_2", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0, "Unknown" = 2)
)
# get weighted HRs
ipw_plain_str3$stat
# `plain` model with PSM method and aggressive imputation
ps_plain_str2 <- ps_match_strata(
data.in = biomarker, formula = indicator_1 ~ ECOG + Sex + Age, model = "plain",
indicator.var = "indicator_1", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0)
)
# get weighted HRs
ps_plain_str2$stat
## ---- message=FALSE, comment=""-----------------------------------------------
# dwc model with IPW method
ipw_dwc <- ipw_strata(
data.in = biomarker, formula = indicator_2 ~ ECOG + Sex + Age, model = "dwc",
indicator.var = "indicator_2", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0)
)
# get weighted HRs
ipw_dwc$stat
# dwc model with PSM method
ps_dwc <- ps_match_strata(
data.in = biomarker, formula = indicator_2 ~ ECOG + Sex + Age, model = "dwc",
indicator.var = "indicator_2", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0, "Missing" = 2)
)
# get weighted HRs
ps_dwc$stat
## ---- message=FALSE, comment=""-----------------------------------------------
# data process: create a numeric version of next STRATUM to learn from
biomarker <- biomarker %>%
mutate(
indicator_next_2 = case_when(
STRATUM.next == "Positive" ~ 1,
STRATUM.next == "Negative" ~ 0,
Arm == "Experimental" & is.na(STRATUM.next) ~ 2,
is.na(STRATUM.next) & Arm == "Control" ~ -1
)
)
ipw_wri <- ipw_strata(
data.in = biomarker, formula = indicator_2 ~ ECOG + Sex + Age, model = "wri",
indicator.var = "indicator_2", indicator.next = "indicator_next_2",
tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0)
)
# get weighted HRs
ipw_wri$stat
## ---- message=FALSE, fig.width=6, fig.height=5, comment=""--------------------
# for ipw_plain model results
km_plot_weight(
data.in = ipw_plain_str2$data,
indicator.var = "indicator_1", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0)
)
# to get weights from model result for further usage
ipw_plain_str2$data %>%
dplyr::select(Patient.ID, Arm, STRATUM, ECOG, Sex, Age, indicator_1, pred1, pred0) %>%
head()
# for ipw_wri model results
km_plot_weight(
data.in = ipw_wri$data,
indicator.var = "indicator_2", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0)
)
# for ps_dwc model results
km_plot_weight(
data.in = ps_dwc$data,
indicator.var = "indicator_2", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0, "Missing" = 2)
)
## ---- message=FALSE, fig.width=6, fig.height=5, comment=""--------------------
ipw_plain_diff <- std_diff(
data.in = ipw_plain_str2$data, vars = c("ECOG", "Sex", "Age"),
indicator.var = "indicator_1", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0),
usubjid.var = "Patient.ID"
)
ipw_plain_diff$Positive
ipw_plain_diff$Negative
# Visualize differences
std_diff_plot(ipw_plain_diff, legend.pos = "bottom")
## ---- message=FALSE, fig.width=6, fig.height=5, comment=""--------------------
ps_dwc_diff <- std_diff(
data.in = ps_dwc$data, vars = c("ECOG", "Sex", "Age"),
indicator.var = "indicator_2", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0, "Missing" = 2),
usubjid.var = "Patient.ID"
)
ps_dwc_diff$Missing
# Visualize differences
std_diff_plot(ps_dwc_diff)
## ---- message=FALSE, comment=""-----------------------------------------------
vars <- c("ECOG", "Sex", "Age")
thresholds <- c(0.15, 0.2)
class_int_list <- list("Positive" = 1, "Negative" = 0)
rand_ratio <- 2 # randomization ratio
n_arms <- lapply(class_int_list, function(x) nrow(biomarker %>% filter(indicator_1 %in% x)))
exp_diff <- sapply(n_arms, function(x) {
expected_feature_diff(
n.feature = length(vars),
n.arm1 = x,
n.arm2 = x / rand_ratio,
threshold = thresholds
)
}) %>% t()
# Expected imbalanced features
exp_diff
# Calculate the observed imbalanced features in model ipw_plain_diff
obs_diff_cnt <- sapply(thresholds, function(th){
sapply(ipw_plain_diff, function(gp){
ft <- as.character(subset(gp, type=="adjusted difference" & absolute_std_diff>=th)$var)
length(unique(sapply(ft, function(ff)strsplit(ff, split="\\.")[[1]][1])))
})
})
colnames(obs_diff_cnt) <- paste0("Observed # features > ", thresholds)
rownames(obs_diff_cnt) <- names(ipw_plain_diff)
# the number of observed imbalanced features for each threshold
# Compare expected to observed # of imbalanced features to check model fit
obs_diff_cnt
obs_diff_fac <- sapply(thresholds, function(th) {
sapply(ipw_plain_diff, function(gp) {
ft <- as.character(subset(gp, type=="adjusted difference" & absolute_std_diff>=th)$var)
paste(ft, collapse=",")
})
})
colnames(obs_diff_fac) <- paste0("features > ", thresholds)
rownames(obs_diff_fac) <- names(ipw_plain_diff)
# the observed individual features that are imbalanced for each threshold
obs_diff_fac
## ---- message=FALSE, comment=""-----------------------------------------------
boot_ipw_plain <- bootstrap_propen(
data.in = biomarker, formula = indicator_1 ~ ECOG + Sex + Age,
indicator.var = "indicator_1", tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0),
estimate.res = ipw_plain_str2, method = "ipw", n.boot = 100
)
# get bootstrap CI
boot_ipw_plain$est.ci.mat
# summary statistics from bootstraps
boot_ipw_plain$boot.out.est
# error status and convergence status
boot_ipw_plain$error.est
boot_ipw_plain$conv.est
## ---- message=FALSE, comment=""-----------------------------------------------
boot_ipw_wri <- bootstrap_propen(
data.in = biomarker, formula = indicator_2 ~ ECOG + Sex + Age,
indicator.var = "indicator_2", indicator.next = "indicator_next_2",
tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0),
estimate.res = ipw_wri, method = "ipw", n.boot = 100
)
# get bootstrap CI
boot_ipw_wri$est.ci.mat
## ---- message=FALSE, comment=""-----------------------------------------------
boot_ps_dwc <- bootstrap_propen(
data.in = biomarker, formula = indicator_2 ~ ECOG + Sex + Age,
indicator.var = "indicator_2",
tte = "OS", event = "OS.event", trt = "Arm",
class.of.int = list("Positive" = 1, "Negative" = 0),
estimate.res = ps_dwc, method = "ps", n.boot = 100
)
# get bootstrap CI
boot_ps_dwc$est.ci.mat
## ---- message=FALSE, fig.width=7, fig.height=6, comment=""--------------------
boot_models <- list(
ipw_plain = boot_ipw_plain,
ipw_wri = boot_ipw_wri,
ps_dwc = boot_ps_dwc
)
cols <- c("Estimate", "Bootstrap CI low", "Bootstrap CI high")
# get HRs and bootstrap CIs
boots_dp <- lapply(boot_models, function(x){
cis <- x$est.ci.mat[ , cols, drop = FALSE] %>%
exp() %>% round(2) %>% as.data.frame()
colnames(cis) <- c("HR", "LOWER", "UPPER")
cis %>% mutate(
Group = rownames(cis)
)
})
boots_dp <- do.call(`rbind`, boots_dp) %>%
mutate(
Methods = rep(c("IPW plain", "IPW wri", "PS dwc"), 2),
Methods_Group = paste(Methods, Group),
Group = factor(Group, levels = c("Positive", "Negative")),
Methods = factor(Methods, levels = c("IPW plain", "IPW wri", "PS dwc"))
) %>%
arrange(Methods, Group)
forest_bygroup(
data = boots_dp, summarystat = "HR", upperci = "UPPER", lowerci = "LOWER",
population.name = "Methods_Group", group.name = "Methods",
color.group.name = "Group",
stat.label = "Hazard Ratio",
stat.type.hr = TRUE, log.scale = FALSE,
endpoint.name = "OS", study.name = "Example Study", draw = TRUE
)
|
6a66fa7fb7872a3224f9ecd726d1c1441d21b377
|
ed6c1cb4aa9b816c904ed52e22ef716409f3e62e
|
/Single Period Outliers/scripts/Single Period xG.R
|
504813f0e7896a3eeae681c5afcd5693d239d80b
|
[] |
no_license
|
loserpoints/Hockey
|
ecfca68be8d14d0fca5169cfbbcac3c46b54f262
|
94444b6fb04b7900930f918e432764993bbf6b1f
|
refs/heads/master
| 2021-01-04T02:14:12.336819
| 2020-12-31T15:40:52
| 2020-12-31T15:40:52
| 240,337,779
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,414
|
r
|
Single Period xG.R
|
### load required packages
library(tidyverse)
library(extrafont)
library(RMariaDB)
### load fonts for viz
loadfonts(device = "win")
### query local mysql db for shot data
shots_db <-
dbConnect(
MariaDB(),
user = "root",
password = password,
dbname = "nhl_shots_eh",
host = "localhost"
)
shots_query <- "SELECT * FROM shots"
shots_table <- dbSendQuery(shots_db, shots_query)
period_xg <- dbFetch(shots_table) %>%
filter(!is.na(pred_goal), game_strength_state == "5v5", game_period < 4) %>%
select(season, game_id, game_period, event_team, home_team, away_team, pred_goal, pred_goal_home_weight, pred_goal_away_weight) %>%
mutate(team_xg = ifelse(event_team == home_team, pred_goal*pred_goal_home_weight, pred_goal*pred_goal_away_weight),
opponent = ifelse(event_team == home_team, away_team, home_team)) %>%
select(season, game_id, game_period, team = event_team, opponent, team_xg) %>%
group_by(season, game_id, game_period, team, opponent) %>%
summarize_all(sum) %>%
group_by(season, game_id, game_period) %>%
mutate(total_xg = sum(team_xg), xg_share = team_xg/total_xg, xg_diff = team_xg-(total_xg-team_xg)) %>%
ungroup() %>%
pivot_longer(-c(season, game_id, game_period, team, opponent), names_to = "metric", values_to = "value") %>%
filter(metric == "xg_share" | metric == "xg_diff") %>%
mutate(metric = gsub("xg_share", "Expected Goal Share", metric),
metric = gsub("xg_diff", "Expected Goal Differential", metric),
metric = factor(metric, levels = c("Expected Goal Share", "Expected Goal Differential")))
lightning_game <- data.frame(season = 20192020,
game_id = NA,
game_period = 2,
team = "T.B",
opponent = "DAL",
metric = c("Expected Goal Share", "Expected Goal Differential"),
value = c(0.984, 1.26),
x = c(0.88, 2.3),
y = c(1.065, 0.5))
ggplot(period_xg, aes(value)) +
facet_wrap(~metric, scales = "free") +
geom_density(fill = "gray81") +
geom_vline(data = lightning_game, aes(xintercept = value), linetype = "dashed", color = "dodgerblue3", size = 1.5) +
geom_text(data = lightning_game, aes(x = x, y = y, label = paste0(label = "Tampa Bay Lighnting\nSecond Period\nGame 2 2020 SCF\n", value)), size = 4, family = "Trebuchet MS") +
theme_ipsum_ps() +
ggtitle("Distribution of NHL single period 5v5 adjusted expected goal share and differential",
subtitle = "Distributions based on regular season data via Evolving Hockey") +
xlab("") +
ylab("") +
theme(plot.title = element_text(size = 24, face = "bold"),
plot.subtitle = element_text(size = 18),
axis.text.y = element_blank(),
axis.text.x = element_text(size = 14),
axis.title.x = element_text(size = 18, hjust = 0.5),
axis.title.y = element_text(size = 18, hjust = 0.5),
panel.grid.major = element_line(colour = "grey90"),
panel.grid.minor = element_line(colour = "grey90"),
strip.text = element_text(hjust = 0.5, size = 18),
strip.background = element_rect(color = "gray36"))
ggsave(filename = "viz/lightning_2020.png", width = 21.333, height = 10.66)
|
3077b90e45912d9c8c09417f4e92841b688c1ac9
|
87502e5d65358d4069dfab82a6c8aafea627f936
|
/Code/KNN/01/knn_final_full_test.R
|
e5a9aa265639a7d86c68fe2d876087c4c51ee48e
|
[] |
no_license
|
niive12/SML
|
4c5dc361480d24652dff4602db4b84e96d7ef306
|
a21570b8b2e6995dbcee083901160c718424ff8c
|
refs/heads/master
| 2020-06-05T08:55:59.875092
| 2015-06-25T09:38:43
| 2015-06-25T09:38:43
| 30,865,578
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,869
|
r
|
knn_final_full_test.R
|
# run full test on the best dataset, easy and hard problem
library("gplots") # for colorpanel
source("load_people_data.R")
source("pca_test.R")
source("normalize.R")
source("confusion_matrix.R")
trainSetSize = 400
testSetSize = 400
s_k = 1
s_size = 5
s_sigma = 0.9
s_pc = 40
s_crossrefs = 10
people = getPeople()
noPeople = length(people)
success_hard = 1:noPeople
success_easy = 1:s_crossrefs
confus_easy = matrix(0,10,10)
confus_hard = matrix(0,10,10)
if(F){
# data easy problem
data_easy = prepareAllMixedCrossVal(split = 0.9, crossValRuns = s_crossrefs, filter = "gaussian", size = s_size, sigma = s_sigma, make_new = 1, peopleToLoad = people)
for(i in 1:s_crossrefs){
data_easy_s = normalizeData(data_easy[[i]], normMethod = "z-score")
data_easy_s = pca_simplification(data_easy_s, noPC = s_pc)
data_easy_s = normalizeData(data_easy_s, normMethod = "z-score")
knn_easy = run_knn(data_easy_s, s_k)
success_easy[i] = knn_easy$success
confus_easy = confus_easy + knn_easy$confus
}
print("Easy problem done.")
# data hard problem
for(person in 1:noPeople){
data_hard = prepareOneAlone(people[[person]][1], people[[person]][2], trainPartSize = trainSetSize, testSize = testSetSize, make_new = 1, filter = "gaussian", size = s_size, sigma = s_sigma, peopleToLoad = people)
data_hard = normalizeData(data_hard, normMethod = "z-score")
data_hard = pca_simplification(data_hard, noPC = s_pc)
data_hard = normalizeData(data_hard, normMethod = "z-score")
knn_hard = run_knn(data_hard, s_k)
success_hard[person] = knn_hard$success
confus_hard = confus_hard + knn_hard$confus
}
#save adata
save(success_hard, success_easy, confus_hard, confus_easy, file = "KNN_final_full_test.RData")
} else{
# load old data
load("KNN_final_full_test.RData")
}
# plot hard
x_lab <- 1:noPeople
for(i in 1:noPeople){
x_lab[i] <- paste(c(people[[i]][1],":",people[[i]][2]),collapse="")
}
setEPS()
postscript("../../../Report/graphics/knn_final_full_hard.eps",height = 6, width = 8)
plot(1:noPeople,success_hard, xaxt="n",type="b",xlab="Person",ylab="Success Rate")
abline(h=mean(success_hard), col = "red")
axis(1, at=1:noPeople, labels=x_lab, las = 2)
dev.off()
#plot easy
setEPS()
postscript("../../../Report/graphics/knn_final_full_easy.eps",height = 4, width = 8)
par(mar=c(1, 4, 4, 1) + 0.1)
boxplot(success_easy,ylab="Success Rate", outline = F)
dev.off()
# plot confusions
confusion_matrix(confus_easy, filename="../../../Report/graphics/knn_confusion_bestparam_easy.eps")
confusion_matrix(confus_hard, filename="../../../Report/graphics/knn_confusion_bestparam_hard.eps")
print(paste(c("Mean / Var of the hard: ", mean(success_hard*100), " / ", var(success_hard*100)), collapse = ""))
print(paste(c("Mean / Var of the easy: ", mean(success_easy*100), " / ", var(success_easy*100)), collapse = ""))
print(success_hard)
|
d5089bc9c244b50f7bc54a23c0129a18ee4e9957
|
39a3b1f5d27882ea8364e94c484e14c603cb88e2
|
/R/globals.R
|
3e9e65ef30f685f0e8951c2e83d86a06a53ebfd2
|
[] |
no_license
|
MatthiasPucher/staRdom
|
49c23ebfd977c9321fc09600c29d84ed872f0090
|
af51796fff49a5dc670244066c2f18dd6badc9a3
|
refs/heads/master
| 2023-06-25T00:46:52.968743
| 2023-06-15T08:18:13
| 2023-06-15T08:18:13
| 128,365,215
| 16
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 708
|
r
|
globals.R
|
#' @import utils
globalVariables(c(
"eem",
".",
"samp",
"S275_295",
"S350_400",
"wavelength",
"a250",
"a365",
"a465",
"a665",
"ex",
"em",
"eemnam",
"eem_list",
"comp",
"amount",
"value",
"component",
"comps",
"fit",
"leverage",
"x",
"label",
"max_pos",
"max_em",
"max_ex",
"emn",
"exn",
"type",
"Sample",
"em2",
"e",
"selection",
"comp1",
"o",
"comp2",
"tcc_em",
"tcc_ex",
"set",
"y",
"comb",
"Freq",
"parameter",
"meta",
"i",
"z",
"mod_name",
"control",
"modname",
"B",
"C",
"TCC",
"emission",
"excitation",
"spec",
"spectrum",
"wl",
"absorbance",
"error",
"SAE"
), package = "staRdom")
|
5f76860b290791bf9281a7d78977b80218748f23
|
34cc0de8269856373e4ccd1bf2f97d67de979169
|
/man/cols_exist.Rd
|
5571bee26cb310755f63d483fe4938603c5e5d10
|
[] |
no_license
|
mmp3/deltacomp
|
0a120e9bdd40937f304cdc4709d40e529a128c13
|
366e689c0dcde7782858121384d43bc412d2af0d
|
refs/heads/master
| 2023-06-04T11:29:05.434094
| 2021-05-28T07:36:22
| 2021-05-28T07:36:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 617
|
rd
|
cols_exist.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cols_exist.R
\name{cols_exist}
\alias{cols_exist}
\title{Check whether columns exist in a data.frame}
\usage{
cols_exist(dataf, cols)
}
\arguments{
\item{dataf}{a data.frame}
\item{cols}{character vector of columns to be checked in \code{dataf}}
}
\value{
An error if all \code{cols} not present in \code{dataf}.
Returns \code{TRUE} invisibly otherwise.
}
\description{
Check whether columns exist in a data.frame
}
\examples{
data(fat_data)
cols_exist(fat_data, c("lpa", "sl"))
# not run (throws error):
# cols_exist(fat_data, "a")
}
|
9663a3cb46c5b10b0aef21fd221fec7a38a103fd
|
53ef0750de68471ee0b49537b3170df204a3c69a
|
/paper_code_compilation/Table S24.R
|
2e0780dc59f7b8cbf5f370fde157589987f4cc22
|
[] |
no_license
|
rajkumarkarthik/weak_ties_data_and_code
|
ce10a1ff9326c0997a5870088786ebee0c31220f
|
b4c74c3cf9c46d67c634f82a6c13c6e7bb63662c
|
refs/heads/main
| 2023-04-06T20:13:45.786011
| 2022-05-09T21:44:54
| 2022-05-09T21:44:54
| 485,168,828
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 560
|
r
|
Table S24.R
|
library(tidyverse)
library(data.table)
library(xtable)
# Get engagement metrics data
engagement <- fread("engagement.csv")
# Show metrics: messages, posts, likes and shares
# Including standard error
engagement %>%
group_by(expt_id, metricName, variant) %>% select(lift, std_err, pval) %>%
unique() %>%
pivot_wider(names_from = metricName, values_from = c("lift", "std_err", "pval")) %>%
arrange(expt_id) %>% ungroup() %>% select(-expt_id) %>%
mutate(variant = LETTERS[1:7]) %>%
xtable(digits = 3) %>% print(include.rownames = FALSE)
|
a4b0b9633a431ffd2b14bf6062cd4ce40ab692a6
|
eb490b4d0e974854d80f9a9e0a99cb340e19b387
|
/data-raw/r4ds.R
|
ba714bfe26506092317ad75a97d1e116e985e417
|
[] |
no_license
|
echasnovski/jeroha
|
a64958d8ede4c0a2b2725e8eb16f6fec4acf63e1
|
929ca17e5ea3462a3bd7780787ddbe99968b5126
|
refs/heads/master
| 2021-05-05T18:35:04.995239
| 2017-10-08T12:43:36
| 2017-10-08T12:43:36
| 103,638,357
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,308
|
r
|
r4ds.R
|
library(jeroha)
library(dplyr)
# Get rmd files -----------------------------------------------------------
# For folder "r4ds" go to https://github.com/hadley/r4ds ,
# download the repository, unpack and rename it to "r4ds", put into
# "data-raw" folder
# Get files used to knit the book
r4ds_file_names <- readLines(
file.path("data-raw", "r4ds", "_bookdown.yml")
) %>%
paste0(collapse = " ") %>%
stringr::str_extract_all('\\".*\\.[Rr]md\\"') %>%
`[[`(1) %>%
stringr::str_replace_all('"', '') %>%
stringr::str_split(",[:space:]*") %>%
`[[`(1)
r4ds_pages <- tibble(
page = seq_len(length(r4ds_file_names)),
file = r4ds_file_names,
pageName = file_base_name(r4ds_file_names)
)
# Tidy book ---------------------------------------------------------------
r4ds <- file.path("data-raw", "r4ds", r4ds_pages[["file"]]) %>%
lapply(tidy_rmd) %>%
bind_rows() %>%
rename(pageName = name) %>%
# Remove md emphasis before filtering words with only alphabetic characters.
mutate(word = remove_md_emphasis(word)) %>%
filter_good_words() %>%
mutate(
id = seq_len(n()),
book = rep("R4DS", n())
) %>%
left_join(y = r4ds_pages %>% select(page, pageName),
by = "pageName") %>%
select(id, book, page, pageName, word)
devtools::use_data(r4ds, overwrite = TRUE)
|
16563fb1949ef38d6b51ab64b5bf842492a54065
|
f16be4c611930661ca523ea4b02af50b520509df
|
/inst/benchmarks/cma.r
|
fc6c854bab7a561cae960585182070591e1c15a3
|
[
"BSD-2-Clause"
] |
permissive
|
wrathematics/fastmap
|
ca9f516e77f34c0f0889ad7ba3371f6eac7b6a2b
|
bdee0e043fced0cfe1106b53484ade24758eb993
|
refs/heads/master
| 2021-01-02T23:52:02.408944
| 2017-08-06T21:15:17
| 2017-08-06T21:15:17
| 99,512,417
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 211
|
r
|
cma.r
|
library(rbenchmark)
cols <- c("test", "replications", "elapsed", "relative")
reps <- 5
x = matrix(rnorm(10000*1250), 10000)
benchmark(fastmap:::.cma(x, 2), fastmap::cma(x, 2), replications=reps, columns=cols)
|
cea859c78c5e0ae718351e228f94f07660466929
|
a127e9e7abef8a3b5ba170cb02a68f3c3f2b3e6d
|
/Poczatki.R
|
b539ad284c17868a06401e487620472788cb475d
|
[] |
no_license
|
Ida962/Super-Trio
|
5771301fd662f24ac18076eaf5239984988ef441
|
9c5068ebdd373f5bebc647c03534b39539edaaee
|
refs/heads/master
| 2021-08-17T00:57:54.058607
| 2017-11-20T16:14:53
| 2017-11-20T16:14:53
| 111,432,180
| 0
| 0
| null | 2017-11-20T16:14:35
| 2017-11-20T16:01:47
|
R
|
UTF-8
|
R
| false
| false
| 28
|
r
|
Poczatki.R
|
x = c(2,5,7,1,3,9)
length(x)
|
a8171f75dac87108c28b143c337cb4b4ded1a230
|
e939dc354287ac51d763977887afbff50a6ef4df
|
/process_Smit2008_for_validation.R
|
a8e9fe452dff37b4a8fabd7c1b7349ad01ec298a
|
[] |
no_license
|
JanBlanke/pasture_management
|
2e6dc5bc12d9911adafcc7fdcb5e6ff906fdc6ed
|
b5c6f2376d9f191e7b0f9580dad82de992607054
|
refs/heads/master
| 2016-08-12T20:30:39.325992
| 2016-04-08T09:33:16
| 2016-04-08T09:33:16
| 55,766,776
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,157
|
r
|
process_Smit2008_for_validation.R
|
library(raster)
library(rgdal)
eu.nuts.2010 <- readOGR("/home/jan/Dropbox/Data/NUTS_2010_60M_SH/Data", "NUTS_RG_60M_2010")
### check netcdf files
smit.regions <- stack("/home/jan/Dropbox/Data/Smit_2008/map_nuts2_vector_new.nc", varname="nuts")
# 280 regions/layer, indexed as 0s
smit.ids <- stack("/home/jan/Dropbox/Data/Smit_2008/map_nuts2_vector_new.nc", varname="id")
smit.ids[[100]][]
### read Smit data
library(gdata)
df = read.xls ("/home/jan/Dropbox/Data/Smit_2008/PROD_area_smit_nuts2.xlsx", sheet = 1, header = TRUE)
idx <- which(df$productivity_smit == -9999)
df[idx, 3] <- NA
## read NUTS2 shape files
eu.nuts <- readOGR("/home/jan/Dropbox/Paper_2_nitro/Data/", "NUTS_WGS84")
eu.nuts <- eu.nuts[!is.na(eu.nuts$CAPRI_NUTS), ]
names(eu.nuts)[1] <- "NUTS2_id"
eu.nuts.2010 <- spTransform(eu.nuts.2010, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
names(eu.nuts.2010)[1] <- "NUTS2"
eu.nuts.2010$NUTS2_id <- eu.nuts.2010$NUTS2
## merge
eu.new <- merge(eu.nuts.2010, df, by = "NUTS2_id")
class(eu.new)
spplot(eu.new["productivity_smit"], xlim = bbox(eu.new)[1, ] + c(30, 4), ylim = bbox(eu.new)[2, ] + c(40, 5))
|
bd812ac967d2ef4b25d7f87fdcd3f4b78544c359
|
d302b1738f57360ca73fc0aac1f380774bae72b2
|
/app.R
|
1d376c6a8b6dd742685006a795b4c4050fb56c32
|
[] |
no_license
|
CristianPachacama/Dgip
|
f586e3614ca4ebe8caf89fe6a03f5613e4156d7c
|
d5a7a9243e8b408ab84dec1d81c618e151255907
|
refs/heads/master
| 2020-03-17T02:48:57.359208
| 2018-05-17T21:31:34
| 2018-05-17T21:31:34
| 133,207,118
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 21,381
|
r
|
app.R
|
#########################################################################
##### Installing packages into ‘/usr/local/lib/R/site-library’ ########
#########################################################################
### Instalcion de Paquetes para Shiny Server
# sudo su - -c "R -e \"install.packages('shiny')\""
# sudo su - -c "R -e \"install.packages('shinythemes')\""
# sudo su - -c "R -e \"install.packages('flexdashboard')\""
# sudo su - -c "R -e \"install.packages('DT')\""
# sudo su - -c "R -e \"install.packages('highcharter')\""
# sudo su - -c "R -e \"install.packages('plotly')\""
# sudo su - -c "R -e \"install.packages('tidyverse')\""
# sudo su - -c "R -e \"install.packages('reshape2')\""
# sudo su - -c "R -e \"install.packages('tseries')\""
# sudo su - -c "R -e \"install.packages('forecast')\""
#########################################################################
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#------------------- MODELO PREDICTIVO V10 DGIP ------------------------
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
library(shiny)
library(shinythemes)
library(flexdashboard)
#Tablas y Graficos
library(DT)
library(highcharter)
library(plotly)
#Bases de Datos
library(tidyverse)
library(dplyr)
library(reshape2)
#Proyeccion Series Tiempo
library(tseries)
library(forecast)
#>> Carga de Datos
load('Data/Datos_SAE_Act.RData')
# PARAMETROS INICIALES -----------------------------------------
source("Code/ParametrosIniciales.R",local = TRUE)
# ========================================================================
# !!!!!!!!!!!!!!!!!!!!!! USER INTERFACE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# ========================================================================
ui <- navbarPage(title = "Modelo Predictivo DGIP",
header = tags$h2("Header-Plataforma",tags$head(tags$link(rel='shortcut icon', href='epn.ico', type='image/x-icon'))),
position = "fixed-top",#theme=shinytheme('flatly'),#theme = 'estilo.css',
footer = fluidRow(column(12,img(src='epn_logo.png',width='30px',align='center'),
tags$b('Proyecto: '),' "Modelo Predictivo para Reprobación de Estudiantes"' ,
'-',tags$a('DGIP-EPN (2018)',href='http://www.epn.edu.ec'),
tags$b(' || '),tags$b('Desarrollado por: '),
tags$a('C. Pachacama &',href='http://www.linkedin.com/in/cristian-david-pachacama'),
tags$a('M. Sanchez',href='http://www.linkedin.com/in/miguel-ángel-sánchez-epn')
)
),
#Header de la Pagina
#tags$head(tags$link(rel='shortcut icon', href='iconoEPN.ico', type='image/x-icon')),
#INTRODUCCION E INFORMACION DEL PROYECTO ----------------
tabPanel('Introducción',icon=icon('home'),
fluidRow(
sidebarPanel(img(src='epn_logo2.png',width='90%',align='center' ),
fluidRow(' '),shiny::hr(),
fluidRow(
column(3,tags$b('Proyecto:')),column(1),
column(8,'Modelo Predictivo para Reprobación de estudiantes.')
),shiny::hr(),
fluidRow(
column(3,tags$b('Unidad:')),column(1),
column(8,'Dirección de Gestión de la Información')
),shiny::hr(),
fluidRow(
column(3,tags$b('Director:')),column(1),
column(8,'Msc. Roberto Andrade')
),shiny::hr(),
fluidRow(
column(3,tags$b('Analístas:')),column(1),
column(8,'Miguel Angel Sánchez & Cristian Pachacama')
),shiny::hr()
),
mainPanel(
tags$h3('Modelo Predictivo para Reprobación de estudiantes.'),
shiny::hr(),#tags$h4('Resumen'),
fluidRow(' '),
tags$p('El propósito de esta plataforma es el integrar en una sola interfaz
un modelo que permita predecir el número de estudiantes que tomarán
determinada materia, basados en su comportamiento histórico y el de
los estudiantes que han tomado dicha materia. Esto con la finalidad
que es necesario conoceer esto para el adecuado provisionamiento de
recursos tales como aulas. profesores, materiales, etc. La plataforma
se compone de dos partes, referentes a análisis MACRO y MICRO del modelo.'),
tags$h4('Modelo MACRO'),
tags$p('La parte MACRO del modelo es en donde se aborda desde un
enfoque general la reprobación de estudiantes, resumiendo esta
información (histórica y predicciones) en un reporte asociado a las
materias de cada Carrera. Se abordan dentro de este modelo dos
metodologías,la primera basada en el ', tags$i('Promedio') ,'de reprobación
historíca de las materias, para realizar las predicciones.'),
tags$p('La segunda metodología basada en un modelo predictivo llamado ',
tags$i('ARIMA,'), 'que de igual manera utiliza los porcentajes de reprobación
histórico de las materias para realizar la predicción.'),
tags$p(tags$i('Observación. '),'Estas dos metodologías muestran resultados parecidos,
en algunos casos el modelo de Promedios realiza mejores predicciones que el modelo ARIMA,
usualmente por que el modelo ARIMA requiere de que exista suficiente información histórica de la materia,
en cambio el modelo de Promedios funciona bien inclusive cuando se dispone de poca información
histórica de una materia.'),
tags$h4('Modelo MICRO'),
tags$p('El otro enfoque, que llamamos MICRO, es un análisis desagregado de la
información de cada uno de los alumnos y el "Riesgo de Reprobación" del
mismo, esto para cada una de las materias de las distintas Carreras.'),
tags$h4(tags$b('Conclusiones')),
tags$p('El modelo MICRO resulta ser más preciso que el MACRO,
se recomienda usarlo excepto en materias de Titulación, Cursos de Actualización, Posgrados y Laboratorios.')
)
),shiny::hr()
),
#MODELO MACRO ===============================================
navbarMenu("Modelo MACRO",
#Modelo Usando PROMEDIO de Porcentajes -----------
tabPanel('Promedio',
fluidRow(
sidebarPanel(width=4,
#Panel de Control INFORME MACRO --------
tags$h3('Panel de Control'),
tags$p('Para obtener un informe de reprobación por materia,
primero especifique la siguiente información.'),
tags$p(tags$b('Observación. '),'Las predicciones se realizan para el Periodo Seleccionado, y
se basan únicamente en información histórica del porcentaje de Reprobación.'),
selectInput(inputId='facultad_in',label='Seleccione Facultad',choices = facultad_lista_shy0),
selectInput(inputId='carrera_in',label='Seleccione Carrera',choices = NULL),
selectInput(inputId='periodo_in',label='Seleccione Periodo',choices = NULL),
#selectInput(inputId='n_periodo_in',label='Número de Periodos (Histórico)',choices = NULL),
sliderInput(inputId='n_periodo_in',label = 'Número de Periodos (Histórico)',min = 1,max = 10,value = 5),
actionButton('Informe_boton',label='Generar Informe',icon = icon('newspaper-o')),shiny::hr(),
#Grafico Histórico Reprobacion ------------
highchartOutput('graf_mini_reprob',height = '280px'),
tags$p('Este gráfico muestra el porcentaje de reprobación histórico de la materia seleccionada.')
),
mainPanel(
#Titulo Informe MACRO promedio
tags$h2(textOutput("titulo_macro")),shiny::hr(),
tags$h4(textOutput("facultad_macro")),
tags$h4(textOutput("carrera_macro")),
tags$h4(textOutput("periodos_macro")),shiny::hr(),
#Tabla Informe MACRO promedio
fluidRow(DT::dataTableOutput("informe_reprob"))
)
),shiny::hr()
),
#Modelo usando ARIMA de Porcentajes -----------------
tabPanel('ARIMA',
fluidRow(
sidebarPanel(width=4,
#Panel de Control INFORME MACRO2 ---------
tags$h3('Panel de Control'),
tags$p('Para obtener un informe de reprobación por materia,
primero especifique la siguiente información.'),
tags$p(tags$b('Observación. '),'Las predicciones se realizan para el Periodo Seleccionado, y
se basan únicamente en información histórica del porcentaje de Reprobación.'),
selectInput(inputId='facultad_in2',label='Seleccione Facultad',choices = facultad_lista_shy0),
selectInput(inputId='carrera_in2',label='Seleccione Carrera',choices = NULL),
selectInput(inputId='periodo_in2',label='Seleccione Periodo',choices = NULL),
selectInput(inputId='n_periodo_in2',label='Número de Periodos (Histórico)',choices = NULL),
actionButton('Informe_boton2',label='Generar Informe',icon = icon('newspaper-o')),shiny::hr(),
#Grafico Histórico Reprobacion
# highchartOutput('graf_mini_reprob2',height = '280px')
plotlyOutput('graf_mini_reprob2',height = '300px'),
tags$p('Este gráfico muestra el porcentaje de reprobación histórico de la materia seleccionada.')
),
mainPanel(
tags$h3(textOutput("titulo_macro2")),shiny::hr(),
# Botón de descarga
downloadButton("downloadData2", "Descargar Arima"), shiny::hr(),
fluidRow(DT::dataTableOutput("informe_reprob2")),shiny::hr()
)
),shiny::hr()
)
),
#MODELO MICRO ===============================================
tabPanel("Modelo MICRO",
fluidRow(
sidebarPanel(width=4,
#Panel de Control INFORME MACRO --------
tags$h3('Panel de Control'),
tags$p('Para obtener un informe los estudiantes reprobados por materia,
primero especifique la siguiente información.'),
tags$p(tags$b('Observación. '),'Las predicciones se realizan para el Periodo Seleccionado, y
es necesaria la información de la Calificación del primer Bimestre del estudiante',tags$i('(Calificación 1).')),
selectInput(inputId='facultad_in3',label='Seleccione Facultad',choices = facultad_lista_shy0),
selectInput(inputId='carrera_in3',label='Seleccione Carrera',choices = NULL),
selectInput(inputId='periodo_in3',label='Seleccione Período',choices = NULL),
#selectInput(inputId='n_periodo_in3',label='Número de Periodos (Histórico)',choices = NULL),
sliderInput(inputId = 'n_periodo_in3',label='Número de Periodos (Histórico)',min = 1,max = 10,value = 7),
tags$p('Presione el botón ',tags$i('Generar Informe'),' y posteriormente seleccione (dando click)
una de las materias de la lista, y se generará un reporte con la prediccion
de los estudiantes Aprobados/Reprobados de dicha materia.'),
actionButton('Informe_boton3',label='Generar Informe',icon = icon('newspaper-o')),shiny::hr(),
#Grafico Histórico Reprobacion ------------
highchartOutput('graf_mini_reprob3',height = '300px'),
tags$p('Este gráfico muestra el porcentaje de reprobación histórico de la materia seleccionada.')
),
mainPanel(
# Informe Resumen por Carrera -------------------
tags$h2(textOutput("titulo_micro3")),shiny::hr(),
tags$h4(textOutput("facultad_micro3")),
tags$h4(textOutput("carrera_micro3")),
tags$h4(textOutput("periodos_micro3")),shiny::hr(),
fluidRow(DT::dataTableOutput("informe_reprob3")),shiny::hr(),
#Informe LOGIT por Materia(Seleccionada) --------
tags$h2('Predicción de Aprobados y Reprobados'),shiny::hr(),
fluidRow(
column(width = 7,
tags$h4(textOutput("materia_logit3")),
tags$h4(textOutput("periodo_logit3")),
tags$h4(textOutput("precision_logit3"))
),
column(width = 2,
tags$h4('Porcentaje Reprobación (Predicción): ')
),
column(width = 3,
gaugeOutput(outputId = "velocimetro",height = "100px")
)
),
shiny::hr(),
#Tabla por Profesor y Paralelo
fluidRow(DT::dataTableOutput("informe_profesor3")),shiny::hr(),
#Infome Logit
fluidRow(DT::dataTableOutput("informe_logit3")),shiny::hr(),
#Validacion Modelo
tags$h2('Resumen del Modelo'),
fluidRow(verbatimTextOutput("validacion_logit3"))
)
),shiny::hr()
)
)
# ========================================================================
# !!!!!!!!!!!!!!!!!!!!!!!! SERVER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# ========================================================================
server <- function(input, output,session) {
# ANALISIS MACRO
# >> PROMEDIOS ========================================================
#Generacion de Listas de Carreras y Periodos -----------------
source("Code/ListasInputPanel.R",local = TRUE)
#Reactividad de Inputs Panel ---------------------------------
source("Code/Promedios/ReactividadInput.R",local = TRUE)
#Generación de Informe Reprobacion ---------------------------
source("Code/Promedios/Informe.R",local = TRUE)
#Grafico de Reprobación Historica ----------------------------
source("Code/Promedios/Grafico.R",local = TRUE)
# >> PREDICCION ARIMA =================================================
#Reactividad de Inputs Panel ---------------------------------
source("Code/Arima/ReactividadInput.R",local = TRUE)
#Generación de Informe Reprobacion ---------------------------
source("Code/Arima/Informe.R",local = TRUE)
#Grafico de Reprobación Historica ----------------------------
source("Code/Arima/Grafico.R",local = TRUE)
# >> MODELO MICRO - Logistico =========================================
#Reactividad de Inputs Panel ---------------------------------
source("Code/ModeloMicro/ReactividadInput.R",local = TRUE)
#Generación de Informe Reprobacion ---------------------------
source("Code/ModeloMicro/Informe.R",local = TRUE)
#Grafico de Reprobación Historica ----------------------------
source("Code/ModeloMicro/Grafico.R",local = TRUE)
#Generación de LOGIT por Materia ----------------------------
source("Code/ModeloMicro/InformeLogit.R",local = TRUE)
}
# ========================================================================
# !!!!!!!!!!!!!!!!!!!!!!!! RUN APP !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# ========================================================================
shinyApp(ui = ui, server = server)
|
60e1856d3825b8387fd8cea89d5d99837fb8e683
|
2233e696495f16a59b4cd49e45c56e178861ace0
|
/R/cobot.R
|
1fa05c3feb2a60f9e52998d7784dba3c4199112a
|
[] |
no_license
|
vubiostat/PResiduals
|
293558270c9ac0d63627ab9bf671b30c6b76f20a
|
5c12221e58fd3e01a1f7b88b9efdfadbdf6a9dec
|
refs/heads/master
| 2021-01-19T10:57:33.296753
| 2015-07-07T19:55:32
| 2015-07-07T19:55:32
| 17,527,736
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 27,285
|
r
|
cobot.R
|
ordinal.scores.logit = function(y, X) {
## y is a numeric vector
## X is a vector or matrix with one or more columns.
## Ensure code works if called from somewhere else (not COBOT.scores()).
## Make X a matrix if it is a vector. This makes later coding consistent.
if(!is.matrix(X)) X = matrix(X, ncol=1)
## N: number of subjects; ny: number of y categories
N = length(y)
ny = length(table(y))
## na, nb: number of parameters in alpha and beta
na = ny - 1
nb = ncol(X)
npar = na + nb
## Z is defined as in McCullagh (1980) JRSSB 42:109-142
Z = outer(y, 1:ny, "<=")
## Fit proportional odds model and obtain the MLEs of parameters.
mod = lrm(y ~ X, tol=1e-50, maxit=100)
alpha = -mod$coeff[1:na]
beta = -mod$coeff[-(1:na)]
## Scores are stored for individuals.
dl.dtheta = matrix(NA, N, npar)
## Information matrices are stored as sums over all individuals.
d2l.dalpha.dalpha = matrix(0,na,na)
d2l.dalpha.dbeta = matrix(0,na,nb)
d2l.dbeta.dbeta = matrix(0,nb,nb)
d2l.dbeta.dalpha = matrix(0,nb,na)
## Predicted probabilities p0 and dp0.dtheta are stored for individuals.
p0 = matrix(,N,ny)
dp0.dtheta = array(0,c(N,ny,npar))
## Cumulative probabilities
Gamma = matrix(0,N,na)
dgamma.dtheta = array(0,c(N,na,npar))
for (i in 1:N) {
z = Z[i,] ## z has length ny
x = X[i,]
## gamma and phi are defined as in McCullagh (1980)
gamma = 1 - 1/(1 + exp(alpha + sum(beta*x))) ## gamma has length na
diffgamma = diff(c(gamma,1))
invgamma = 1/gamma
invgamma2 = invgamma^2
invdiffgamma = 1/diffgamma
invdiffgamma2 = invdiffgamma^2
phi = log(gamma / diffgamma) ## phi has length na
Gamma[i,] = gamma
#### Some intermediate derivatives
## g(phi) = log(1+exp(phi))
dg.dphi = 1 - 1/(1 + exp(phi))
## l is the log likelihood (6.3) in McCullagh (1980)
dl.dphi = z[-ny] - z[-1] * dg.dphi
t.dl.dphi = t(dl.dphi)
## dphi.dgamma is a na*na matrix with rows indexed by phi
## and columns indexed by gamma
dphi.dgamma = matrix(0,na,na)
diag(dphi.dgamma) = invgamma + invdiffgamma
if(na > 1)
dphi.dgamma[cbind(1:(na-1), 2:na)] = -invdiffgamma[-na]
dgamma.base = gamma * (1-gamma)
dgamma.dalpha = diagn(dgamma.base)
dgamma.dbeta = dgamma.base %o% x
dgamma.dtheta[i,,] = cbind(dgamma.dalpha, dgamma.dbeta)
d2gamma.base = gamma * (1-gamma) * (1-2*gamma)
##
d2l.dphi.dphi = diagn(-z[-1] * dg.dphi * (1-dg.dphi))
d2l.dphi.dalpha = d2l.dphi.dphi %*% dphi.dgamma %*% dgamma.dalpha
d2l.dphi.dbeta = d2l.dphi.dphi %*% dphi.dgamma %*% dgamma.dbeta
##
d2phi.dgamma.dalpha = array(0,c(na,na,na))
d2phi.dgamma.dalpha[cbind(1:na,1:na,1:na)] = (-invgamma2 + invdiffgamma2) * dgamma.base
if(na > 1) {
d2phi.dgamma.dalpha[cbind(1:(na-1),1:(na-1),2:na)] = -invdiffgamma2[-na] * dgamma.base[-1]
d2phi.dgamma.dalpha[cbind(1:(na-1),2:na,1:(na-1))] = -invdiffgamma2[-na] * dgamma.base[-na]
d2phi.dgamma.dalpha[cbind(1:(na-1),2:na,2:na)] = invdiffgamma2[-na] * dgamma.base[-1]
}
##
d2phi.dgamma.dbeta = array(0,c(na,na,nb))
rowdiff = matrix(0,na,na)
diag(rowdiff) = 1
if(na > 1) rowdiff[cbind(1:(na-1),2:na)] = -1
d2phi.dgamma.dbeta.comp1 = diagn(-invdiffgamma2) %*% rowdiff %*% dgamma.dbeta
d2phi.dgamma.dbeta.comp2 = diagn(-invgamma2) %*% dgamma.dbeta - d2phi.dgamma.dbeta.comp1
for(j in 1:na) {
d2phi.dgamma.dbeta[j,j,] = d2phi.dgamma.dbeta.comp2[j,]
if(j < na)
d2phi.dgamma.dbeta[j,j+1,] = d2phi.dgamma.dbeta.comp1[j,]
}
##
d2gamma.dalpha.dbeta = array(0,c(na,na,nb))
for(j in 1:na)
d2gamma.dalpha.dbeta[j,j,] = d2gamma.base[j] %o% x
##
d2gamma.dbeta.dbeta = d2gamma.base %o% x %o% x
#### First derivatives of log-likelihood (score functions)
dl.dalpha = dl.dphi %*% dphi.dgamma %*% dgamma.dalpha
dl.dbeta = dl.dphi %*% dphi.dgamma %*% dgamma.dbeta
dl.dtheta[i,] = c(dl.dalpha, dl.dbeta)
#### Second derivatives of log-likelihood
#### Since first derivative is a sum of terms each being a*b*c,
#### second derivative is a sum of terms each being (a'*b*c+a*b'*c+a*b*c').
#### d2l.dalpha.dalpha
## Obtain aprime.b.c
## Transpose first so that matrix multiplication is meaningful.
## Then transpose so that column is indexed by second alpha.
aprime.b.c = t(crossprod(d2l.dphi.dalpha, dphi.dgamma %*% dgamma.dalpha))
## Obtain a.bprime.c
## run through the index of second alpha
a.bprime.c = matrix(,na,na)
for(j in 1:na)
a.bprime.c[,j] = t.dl.dphi %*% d2phi.dgamma.dalpha[,,j] %*% dgamma.dalpha
## Obtain a.b.cprime
## cprime = d2gamma.dalpha.dalpha = 0 if indices of the two alphas differ.
d2gamma.dalpha.dalpha = diagn(d2gamma.base)
a.b.cprime = diagn(as.vector(dl.dphi %*% dphi.dgamma %*% d2gamma.dalpha.dalpha))
## summing over individuals
d2l.dalpha.dalpha = aprime.b.c + a.bprime.c + a.b.cprime + d2l.dalpha.dalpha
#### d2l.dalpha.dbeta
aprime.b.c = t(crossprod(d2l.dphi.dbeta, dphi.dgamma %*% dgamma.dalpha))
a.bprime.c = a.b.cprime = matrix(,na,nb)
for(j in 1:nb) {
a.bprime.c[,j] = t.dl.dphi %*% d2phi.dgamma.dbeta[,,j] %*% dgamma.dalpha
a.b.cprime[,j] = t.dl.dphi %*% dphi.dgamma %*% d2gamma.dalpha.dbeta[,,j]
}
d2l.dalpha.dbeta = aprime.b.c + a.bprime.c + a.b.cprime + d2l.dalpha.dbeta
#### d2l.dbeta.dalpha
# dl.dbeta = dl.dphi %*% dphi.dgamma %*% dgamma.dbeta
# aprime.b.c = t(crossprod(d2l.dphi.dalpha, dphi.dgamma %*% dgamma.dbeta))
# a.bprime.c = a.b.cprime = matrix(,na,nb)
# for(j in 1:nb) {
# a.bprime.c[,j] = t.dl.dphi %*% d2phi.dgamma.dalpha[,,j] %*% dgamma.dbeta
# a.b.cprime[,j] = t.dl.dphi %*% dphi.dgamma %*% d2gamma.dbeta.dalpha[,,j]
# }
# d2l.dbeta.dalpha = aprime.b.c + a.bprime.c + a.b.cprime + d2l.dbeta.dalpha
#### d2l.dbeta.dbeta
aprime.b.c = t(crossprod(d2l.dphi.dbeta, dphi.dgamma %*% dgamma.dbeta))
a.bprime.c = a.b.cprime = matrix(,nb,nb)
for(j in 1:nb) {
a.bprime.c[,j] = t.dl.dphi %*% d2phi.dgamma.dbeta[,,j] %*% dgamma.dbeta
a.b.cprime[,j] = t.dl.dphi %*% dphi.dgamma %*% d2gamma.dbeta.dbeta[,,j]
}
d2l.dbeta.dbeta = aprime.b.c + a.bprime.c + a.b.cprime + d2l.dbeta.dbeta
#### Derivatives of predicted probabilities
p0[i,] = diff(c(0, gamma, 1))
rowdiff = matrix(0,ny,na)
diag(rowdiff) = 1
rowdiff[cbind(2:ny,1:na)] = -1
dp0.dalpha = rowdiff %*% dgamma.dalpha
dp0.dbeta = rowdiff %*% dgamma.dbeta
dp0.dtheta[i,,] = cbind(dp0.dalpha, dp0.dbeta)
}
#### Final assembly
d2l.dtheta.dtheta = rbind(
cbind(d2l.dalpha.dalpha, d2l.dalpha.dbeta),
cbind(t(d2l.dalpha.dbeta), d2l.dbeta.dbeta))
## sandwich variance estimate: ABA', where
## A = (-d2l.dtheta.dtheta/N)^(-1)
## B = B0/N
## One way of coding:
## A0 = solve(d2l.dtheta.dtheta)
## B0 = t(dl.dtheta) %*% dl.dtheta
## var.theta = A0 %*% B0 %*% t(A0)
## Suggested coding for better efficiency and accuracy
SS = solve(d2l.dtheta.dtheta, t(dl.dtheta))
var.theta = tcrossprod(SS, SS)
## The sum of scores should be zero at the MLE.
## apply(dl.dtheta, 2, sum)
## Sandwich variance estimate should be similar to information matrix, I,
## which is the same as the lrm() output mod$var.
## I = -solve(d2l.dtheta.dtheta)
## print(I)
## print(mod$var)
## print(var.theta)
## dlow.dtheta and dhi.dtheta
npar.z = dim(dl.dtheta)[2]
dlow.dtheta = dhi.dtheta = matrix(, npar.z, N)
for(i in 1:N) {
if (y[i] == 1) {
dlow.dtheta[,i] <- 0
} else {
dlow.dtheta[,i] <- dgamma.dtheta[i,y[i]-1,]
}
if (y[i] == ny) {
dhi.dtheta[,i] <- 0
} else {
dhi.dtheta[,i] <- -dgamma.dtheta[i,y[i],]
}
}
low.x = cbind(0, Gamma)[cbind(1:N, y)]
hi.x = cbind(1-Gamma, 0)[cbind(1:N, y)]
presid <- low.x - hi.x
dpresid.dtheta <- dlow.dtheta - dhi.dtheta
list(mod = mod,
presid=presid,
dl.dtheta = dl.dtheta,
d2l.dtheta.dtheta = d2l.dtheta.dtheta,
var.theta = var.theta,
p0 = p0,
dp0.dtheta = dp0.dtheta,
Gamma = Gamma,
dgamma.dtheta = dgamma.dtheta,
dlow.dtheta=dlow.dtheta,
dhi.dtheta=dhi.dtheta,
dpresid.dtheta=dpresid.dtheta)
}
ordinal.scores <- function(mf, mm, method) {
## mf is the model.frame of the data
if (method[1]=='logit'){
return(ordinal.scores.logit(y=as.numeric(model.response(mf)),X=mm))
}
## Fit proportional odds model and obtain the MLEs of parameters.
mod <- newpolr(mf, Hess=TRUE, method=method,control=list(reltol=1e-50,maxit=100))
y <- model.response(mf)
## N: number of subjects; ny: number of y categories
N = length(y)
ny = length(mod$lev)
## na, nb: number of parameters in alpha and beta
na = ny - 1
x <- mm
nb = ncol(x)
npar = na + nb
alpha = mod$zeta
beta = -coef(mod)
eta <- mod$lp
## Predicted probabilities p0 and dp0.dtheta are stored for individuals.
p0 = mod$fitted.values
dp0.dtheta = array(dim=c(N, ny, npar))
Y <- matrix(nrow=N,ncol=ny)
.Ycol <- col(Y)
edcumpr <- cbind(mod$dcumpr, 0)
e1dcumpr <- cbind(0,mod$dcumpr)
for(i in seq_len(na)) {
dp0.dtheta[,,i] <- (.Ycol == i) * edcumpr - (.Ycol == i + 1)*e1dcumpr
}
for(i in seq_len(nb)) {
dp0.dtheta[,,na+i] <- mod$dfitted.values * x[,i]
}
## Cumulative probabilities
Gamma = mod$cumpr
dcumpr <- mod$dcumpr
## Scores are stored for individuals.
dl.dtheta = mod$grad
## dlow.dtheta and dhigh.dtheta
y <- as.integer(y)
dcumpr.x <- cbind(0, dcumpr, 0)
dlow.dtheta <- t(cbind((col(dcumpr) == (y - 1L)) * dcumpr,
dcumpr.x[cbind(1:N,y)] * x))
dhi.dtheta <- t(-cbind((col(dcumpr) == y) * dcumpr,
dcumpr.x[cbind(1:N,y + 1L)] * x))
d2l.dtheta.dtheta <- mod$Hessian
low.x = cbind(0, Gamma)[cbind(1:N, y)]
hi.x = cbind(1-Gamma, 0)[cbind(1:N, y)]
presid <- low.x - hi.x
dpresid.dtheta <- dlow.dtheta - dhi.dtheta
list(mod = mod,
presid=presid,
dl.dtheta = dl.dtheta,
d2l.dtheta.dtheta = d2l.dtheta.dtheta,
p0 = p0,
dp0.dtheta = dp0.dtheta,
Gamma = Gamma,
dcumpr=dcumpr,
dlow.dtheta=dlow.dtheta,
dhi.dtheta=dhi.dtheta,
dpresid.dtheta=dpresid.dtheta)
}
#' Conditional ordinal by ordinal tests for association.
#'
#' \code{cobot} tests for independence between two ordered categorical
#' variables, \var{X} and \var{Y} conditional on other variables,
#' \var{Z}. The basic approach involves fitting models of \var{X} on
#' \var{Z} and \var{Y} on \var{Z} and determining whether there is any
#' remaining information between \var{X} and \var{Y}. This is done by
#' computing one of 3 test statistics. \code{T1} compares empirical
#' distribution of \var{X} and \var{Y} with the joint fitted
#' distribution of \var{X} and \var{Y} under independence conditional
#' on \var{Z}. \code{T2} computes the correlation between ordinal
#' (probability-scale) residuals from both models and tests the null
#' of no residual correlation. \code{T3} evaluates the
#' concordance--disconcordance of data drawn from the joint fitted
#' distribution of \var{X} and \var{Y} under conditional independence
#' with the empirical distribution. Details are given in \cite{Li C and
#' Shepherd BE, Test of association between two ordinal variables
#' while adjusting for covariates. Journal of the American Statistical
#' Association 2010, 105:612-620}.
#'
#' formula is specified as \code{\var{X} | \var{Y} ~ \var{Z}}.
#' This indicates that models of \code{\var{X} ~ \var{Z}} and
#' \code{\var{Y} ~ \var{Z}} will be fit. The null hypothsis to be
#' tested is \eqn{H_0 : X}{H0 : X} independant of \var{Y} conditional
#' on \var{Z}.
#'
#' Note that \code{T2} can be thought of as an adjusted rank
#' correlation.(\cite{Li C and Shepherd BE, A new residual for ordinal
#' outcomes. Biometrika 2012; 99:473-480})
#'
#' @param formula an object of class \code{\link{Formula}} (or one
#' that can be coerced to that class): a symbolic description of the
#' model to be fitted. The details of model specification are given
#' under \sQuote{Details}.
#' @param link The link family to be used for ordinal models of both
#' \var{X} and \var{Y}. Defaults to \samp{logit}. Other options are
#' \samp{probit}, \samp{cloglog}, and \samp{cauchit}.
#' @param link.x The link function to be used for a model of the first
#' ordered variable. Defaults to value of \code{link}.
#' @param link.y The link function to be used for a model of the
#' second variable. Defaults to value of \code{link}.
#' @param data an optional data frame, list or environment (or object
#' coercible by \code{\link{as.data.frame}} to a data frame)
#' containing the variables in the model. If not found in
#' \code{data}, the variables are taken from
#' \code{environment(formula)}, typically the environment from which
#' \code{cobot} is called.
#' @param subset an optional vector specifying a subset of
#' observations to be used in the fitting process.
#' @param na.action how \code{NA}s are treated.
#' @param fisher logical; if \code{TRUE}, Fisher transformation and delta method a
#' used to compute p value for the test statistic based on correlation of
#' residuals.
#' @param conf.int numeric specifying confidence interval coverage.
#' @return object of \samp{cobot} class.
#' @references Li C and Shepherd BE, Test of association between two
#' ordinal variables while adjusting for covariates. Journal of the
#' American Statistical Association 2010, 105:612-620.
#' @references Li C and Shepherd BE, A new residual for ordinal
#' outcomes. Biometrika 2012; 99:473-480
#' @import Formula
#' @export
#' @seealso \code{\link{Formula}}, \code{\link{as.data.frame}}
#' @include newPolr.R
#' @include diagn.R
#' @include GKGamma.R
#' @include pgumbel.R
#' @examples
#' data(PResidData)
#' cobot(x|y~z, data=PResidData)
cobot <- function(formula, link=c("logit", "probit", "cloglog", "cauchit"),
link.x=link,
link.y=link,
data, subset, na.action=na.fail,fisher=FALSE,conf.int=0.95) {
F1 <- Formula(formula)
Fx <- formula(F1, lhs=1)
Fy <- formula(F1, lhs=2)
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "weights", "na.action",
"offset"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf$na.action <- na.action
# We set xlev to a benign non-value in the call so that it won't get partially matched
# to any variable in the formula. For instance a variable named 'x' could possibly get
# bound to xlev, which is not what we want.
mf$xlev <- integer(0)
mf[[1L]] <- as.name("model.frame")
mx <- my <- mf
# NOTE: we add the opposite variable to each model frame call so that
# subsetting occurs correctly. Later we strip them off.
mx[["formula"]] <- Fx
yName <- paste0('(', all.vars(Fy[[2]])[1], ')')
mx[[yName]] <- Fy[[2]]
my[["formula"]] <- Fy
xName <- paste0('(', all.vars(Fx[[2]])[1], ')')
my[[xName]] <- Fx[[2]]
mx <- eval(mx, parent.frame())
mx[[paste0('(',yName,')')]] <- NULL
my <- eval(my, parent.frame())
my[[paste0('(',xName,')')]] <- NULL
data.points <- nrow(mx)
Terms <- attr(mx, "terms")
zz <- model.matrix(Terms, mx, contrasts)
zzint <- match("(Intercept)", colnames(zz), nomatch = 0L)
if(zzint > 0L) {
zz <- zz[, -zzint, drop = FALSE]
}
score.xz <- ordinal.scores(mx, zz, method=link.x)
score.yz <- ordinal.scores(my, zz, method=link.y)
npar.xz = dim(score.xz$dl.dtheta)[2]
npar.yz = dim(score.yz$dl.dtheta)[2]
xx = as.integer(model.response(mx)); yy = as.integer(model.response(my))
nx = length(table(xx))
ny = length(table(yy))
N = length(yy)
#### Asymptotics for T3 = mean(Cprob) - mean(Dprob)
## If gamma.x[0]=0 and gamma.x[nx]=1, then
## low.x = gamma.x[x-1], hi.x = (1-gamma.x[x])
low.x = cbind(0, score.xz$Gamma)[cbind(1:N, xx)]
low.y = cbind(0, score.yz$Gamma)[cbind(1:N, yy)]
hi.x = cbind(1-score.xz$Gamma, 0)[cbind(1:N, xx)]
hi.y = cbind(1-score.yz$Gamma, 0)[cbind(1:N, yy)]
Cprob = low.x*low.y + hi.x*hi.y
Dprob = low.x*hi.y + hi.x*low.y
mean.Cprob = mean(Cprob)
mean.Dprob = mean(Dprob)
T3 = mean.Cprob - mean.Dprob
dCsum.dthetax = score.xz$dlow.dtheta %*% low.y + score.xz$dhi.dtheta %*% hi.y
dCsum.dthetay = score.yz$dlow.dtheta %*% low.x + score.yz$dhi.dtheta %*% hi.x
dDsum.dthetax = score.xz$dlow.dtheta %*% hi.y + score.xz$dhi.dtheta %*% low.y
dDsum.dthetay = score.yz$dlow.dtheta %*% hi.x + score.yz$dhi.dtheta %*% low.x
dT3sum.dtheta = c(dCsum.dthetax-dDsum.dthetax, dCsum.dthetay-dDsum.dthetay)
## Estimating equations for (theta, p3)
## theta is (theta.xz, theta.yz) and the equations are score functions.
## p3 is the "true" value of test statistic, and the equation is
## p3 - (Ci-Di)
bigphi = cbind(score.xz$dl.dtheta, score.yz$dl.dtheta, T3-(Cprob-Dprob))
## sandwich variance estimate of var(thetahat)
Ntheta = npar.xz + npar.yz + 1
A = matrix(0,Ntheta,Ntheta)
A[1:npar.xz, 1:npar.xz] = score.xz$d2l.dtheta.dtheta
A[npar.xz+(1:npar.yz), npar.xz+(1:npar.yz)] = score.yz$d2l.dtheta.dtheta
A[Ntheta, -Ntheta] = -dT3sum.dtheta
A[Ntheta, Ntheta] = N
## One way of coding:
##B = t(bigphi) %*% bigphi
##var.theta = solve(A) %*% B %*% solve(A)
## Suggested coding for better efficiency and accuracy:
SS = solve(A, t(bigphi))
var.theta = tcrossprod(SS, SS)
varT3 = var.theta[Ntheta, Ntheta]
pvalT3 = 2 * pnorm(-abs(T3)/sqrt(varT3))
#### Asymptotics for T4 = (mean(Cprob)-mean(Dprob))/(mean(Cprob)+mean(Dprob))
T4 = (mean.Cprob - mean.Dprob)/(mean.Cprob + mean.Dprob)
## Estimating equations for (theta, P4)
## theta is (theta.xz, theta.yz) and the equations are score functions.
## P4 is a vector of (cc, dd, p4). Their corresponding equations are:
## cc - Ci
## dd - Di
## p4 - (cc-dd)/(cc+dd)
## Then p4 is the "true" value of test statistic.
bigphi = cbind(score.xz$dl.dtheta, score.yz$dl.dtheta,
mean.Cprob - Cprob, mean.Dprob - Dprob, 0)
## sandwich variance estimate of var(thetahat)
Ntheta = npar.xz + npar.yz + 3
A = matrix(0,Ntheta,Ntheta)
A[1:npar.xz, 1:npar.xz] = score.xz$d2l.dtheta.dtheta
A[npar.xz+(1:npar.yz), npar.xz+(1:npar.yz)] = score.yz$d2l.dtheta.dtheta
A[Ntheta-3+(1:3), Ntheta-3+(1:3)] = diag(N, 3)
A[Ntheta-2, 1:(npar.xz+npar.yz)] = -c(dCsum.dthetax, dCsum.dthetay)
A[Ntheta-1, 1:(npar.xz+npar.yz)] = -c(dDsum.dthetax, dDsum.dthetay)
revcpd = 1/(mean.Cprob + mean.Dprob)
dT4.dcpd = (mean.Cprob-mean.Dprob)*(-revcpd^2)
A[Ntheta, Ntheta-3+(1:2)] = -N * c(revcpd+dT4.dcpd, -revcpd+dT4.dcpd)
## One way of coding:
##B = t(bigphi) %*% bigphi
##var.theta = solve(A) %*% B %*% solve(A)
## Suggested coding for better efficiency and accuracy:
SS = solve(A, t(bigphi))
var.theta = tcrossprod(SS, SS)
varT4 = var.theta[Ntheta, Ntheta]
pvalT4 = 2 * pnorm(-abs(T4)/sqrt(varT4))
#### Asymptotics for T2 = cor(hi.x - low.x, hi.y - low.y)
xresid = hi.x - low.x
yresid = hi.y - low.y
T2 = cor(xresid, yresid)
xbyyresid = xresid * yresid
xresid2 = xresid^2
yresid2 = yresid^2
mean.xresid = mean(xresid)
mean.yresid = mean(yresid)
mean.xbyyresid = mean(xbyyresid)
## T2 also equals numT2 / sqrt(varprod) = numT2 * revsvp
numT2 = mean.xbyyresid - mean.xresid * mean.yresid
var.xresid = mean(xresid2) - mean.xresid^2
var.yresid = mean(yresid2) - mean.yresid^2
varprod = var.xresid * var.yresid
revsvp = 1/sqrt(varprod)
dT2.dvarprod = numT2 * (-0.5) * revsvp^3
## Estimating equations for (theta, P5)
## theta is (theta.xz, theta.yz) and the equations are score functions.
## P5 is a vector (ex, ey, crossxy, ex2, ey2, p5).
## Their corresponding equations are:
## ex - (hi.x-low.x)[i]
## ey - (hi.y-low.y)[i]
## crossxy - ((hi.x-low.x)*(hi.y-low.y))[i]
## ex2 - (hi.x-low.x)[i]^2
## ey2 - (hi.y-low.y)[i]^2
## p5 - (crossxy-ex*ey)/sqrt((ex2-ex^2)*(ey2-ey^2))
## Then p5 is the "true" value of test statistic
bigphi = cbind(score.xz$dl.dtheta, score.yz$dl.dtheta,
mean.xresid - xresid, mean.yresid - yresid, mean.xbyyresid - xbyyresid,
mean(xresid2) - xresid2, mean(yresid2) - yresid2, 0)
## sandwich variance estimate of var(thetahat)
Ntheta = npar.xz + npar.yz + 6
A = matrix(0,Ntheta,Ntheta)
A[1:npar.xz, 1:npar.xz] = score.xz$d2l.dtheta.dtheta
A[npar.xz+(1:npar.yz), npar.xz+(1:npar.yz)] = score.yz$d2l.dtheta.dtheta
A[Ntheta-6+(1:6), Ntheta-6+(1:6)] = diag(N, 6)
dxresid.dthetax = score.xz$dhi.dtheta - score.xz$dlow.dtheta
dyresid.dthetay = score.yz$dhi.dtheta - score.yz$dlow.dtheta
bigpartial = rbind(c(dxresid.dthetax %*% rep(1, N), rep(0, npar.yz)),
c(rep(0, npar.xz), dyresid.dthetay %*% rep(1, N)),
c(dxresid.dthetax %*% yresid, dyresid.dthetay %*% xresid),
c(dxresid.dthetax %*% (2*xresid), rep(0, npar.yz)),
c(rep(0, npar.xz), dyresid.dthetay %*% (2*yresid)))
A[Ntheta-6+(1:5), 1:(npar.xz+npar.yz)] = -bigpartial
smallpartial = N *
c(-mean.yresid * revsvp + dT2.dvarprod * (-2*mean.xresid*var.yresid),
-mean.xresid * revsvp + dT2.dvarprod * (-2*mean.yresid*var.xresid),
revsvp,
dT2.dvarprod * var.yresid,
dT2.dvarprod * var.xresid)
A[Ntheta, Ntheta-6+(1:5)] = -smallpartial
## One way of coding:
##B = t(bigphi) %*% bigphi
##var.theta = solve(A) %*% B %*% solve(A)
## Suggested coding for better efficiency and accuracy:
SS = solve(A, t(bigphi))
var.theta = tcrossprod(SS, SS)
varT2 = var.theta[Ntheta, Ntheta]
if (fisher==TRUE){
####Fisher's transformation
## TS_f: transformed the test statistics
## var.TS_f: variance estimate for ransformed test statistics
## pvalT2: p-value based on transformed test statistics
TS_f <- log( (1+T2)/(1-T2) )
var.TS_f <- varT2*(2/(1-T2^2))^2
pvalT2 <- 2 * pnorm( -abs(TS_f)/sqrt(var.TS_f))
} else {
pvalT2 = 2 * pnorm(-abs(T2)/sqrt(varT2))
}
#### Asymptotics for T1 = tau - tau0
## dtau0/dtheta
## P0 is the sum of product predicted probability matrix with dim(nx,ny)
P0 = crossprod(score.xz$p0, score.yz$p0) / N
cdtau0 = GKGamma(P0)
C0 = cdtau0$scon
D0 = cdtau0$sdis
## C0 = sum_{l>j,m>k} {P0[j,k] * P0[l,m]}
## D0 = sum_{l>j,m<k} {P0[j,k] * P0[l,m]}
dC0.dP0 = matrix(,nx,ny)
dD0.dP0 = matrix(,nx,ny)
for(i in 1:nx)
for(j in 1:ny) {
dC0.dP0[i,j] = ifelse(i>1 & j>1, sum(P0[1:(i-1), 1:(j-1)]), 0) +
ifelse(i<nx & j<ny, sum(P0[(i+1):nx, (j+1):ny]), 0)
dD0.dP0[i,j] = ifelse(i>1 & j<ny, sum(P0[1:(i-1), (j+1):ny]), 0) +
ifelse(i<nx & j>1, sum(P0[(i+1):nx, 1:(j-1)]), 0)
}
## tau0 = (C0-D0)/(C0+D0)
dtau0.dC0 = 2*D0/(C0+D0)^2
dtau0.dD0 =-2*C0/(C0+D0)^2
## ## P0 is already a matrix
dP0.dtheta.x = array(0, c(nx, ny, npar.xz))
for(j in 1:ny) {
aa = matrix(0, nx, npar.xz)
for(i in 1:N)
aa = aa + score.xz$dp0.dtheta[i,,] * score.yz$p0[i,j]
dP0.dtheta.x[,j,] = aa/N
## simpler but mind-tickling version
#dP0.dtheta.x[,j,] = (score.yz$p0[,j] %*% matrix(score.xz$dp0.dtheta,N))/N
}
dP0.dtheta.y = array(0, c(nx, ny, npar.yz))
for(j in 1:nx) {
aa = matrix(0, ny, npar.yz)
for(i in 1:N)
aa = aa + score.yz$dp0.dtheta[i,,] * score.xz$p0[i,j]
dP0.dtheta.y[j,,] = aa/N
}
## dC0.dtheta and dD0.dtheta
dC0.dtheta.x = as.numeric(dC0.dP0) %*% matrix(dP0.dtheta.x, nx*ny)
dD0.dtheta.x = as.numeric(dD0.dP0) %*% matrix(dP0.dtheta.x, nx*ny)
dC0.dtheta.y = as.numeric(dC0.dP0) %*% matrix(dP0.dtheta.y, nx*ny)
dD0.dtheta.y = as.numeric(dD0.dP0) %*% matrix(dP0.dtheta.y, nx*ny)
## dtau0/dtheta
dtau0.dtheta.x = dtau0.dC0 * dC0.dtheta.x + dtau0.dD0 * dD0.dtheta.x
dtau0.dtheta.y = dtau0.dC0 * dC0.dtheta.y + dtau0.dD0 * dD0.dtheta.y
## dtau/dPa
## tau = (C-D)/(C+D)
Pa = table(xx, yy) / N
cdtau = GKGamma(Pa)
C = cdtau$scon
D = cdtau$sdis
dtau.dC = 2*D/(C+D)^2
dtau.dD =-2*C/(C+D)^2
## Pa[nx,ny] is not a parameter, but = 1 - all other Pa parameters.
## Thus, d.Pa[nx,ny]/d.Pa[i,j] = -1.
## Also, d.sum(Pa[-nx,-ny]).dPa[i,j] = 1 when i<nx and j<ny, and 0 otherwise.
##
## In C = sum_{l>j,m>k} {Pa[j,k] * Pa[l,m]}, Pa[i,j] appears in
## Pa[i,j] * XX (minus Pa[nx,ny] if i<nx & j<ny), and in
## sum(Pa[-nx,-ny]) * Pa[nx,ny].
## So, dC.dPa[i,j] = XX (minus Pa[nx,ny] if i<nx & j<ny)
## + d.sum(Pa[-nx,-ny]).dPa[i,j] * Pa[nx,ny]
## - sum(Pa[-nx,-ny])
## = XX (with Pa[nx,ny] if present) - sum(Pa[-nx,-ny])
##
## D = sum_{l>j,m<k} {Pa[j,k] * Pa[l,m]} doesn't contain Pa[nx,ny]
dC.dPa = matrix(,nx,ny)
dD.dPa = matrix(,nx,ny)
for(i in 1:nx)
for(j in 1:ny) {
dC.dPa[i,j] = ifelse(i>1 & j>1, sum(Pa[1:(i-1), 1:(j-1)]), 0) +
ifelse(i<nx & j<ny, sum(Pa[(i+1):nx, (j+1):ny]), 0) - sum(Pa[-nx,-ny])
dD.dPa[i,j] = ifelse(i>1 & j<ny, sum(Pa[1:(i-1), (j+1):ny]), 0) +
ifelse(i<nx & j>1, sum(Pa[(i+1):nx, 1:(j-1)]), 0)
}
dtau.dPa = dtau.dC * dC.dPa + dtau.dD * dD.dPa
dtau.dPa = dtau.dPa[-length(dtau.dPa)] ## remove the last value
## Estimating equations for (theta, phi)
## theta is (theta.xz, theta.yz) and the equations are score functions.
## phi is (p_ij) for (X,Y), and the equations are
## I{subject in cell (ij)} - p_ij
phi.Pa = matrix(0, N, nx*ny)
phi.Pa[cbind(1:N, xx+(yy-1)*nx)] = 1
phi.Pa = phi.Pa - rep(1,N) %o% as.numeric(Pa)
phi.Pa = phi.Pa[,-(nx*ny)]
bigphi = cbind(score.xz$dl.dtheta, score.yz$dl.dtheta, phi.Pa)
## sandwich variance estimate of var(thetahat, phihat)
Ntheta = npar.xz + npar.yz + nx*ny-1
A = matrix(0,Ntheta,Ntheta)
A[1:npar.xz, 1:npar.xz] = score.xz$d2l.dtheta.dtheta
A[npar.xz+(1:npar.yz), npar.xz+(1:npar.yz)] = score.yz$d2l.dtheta.dtheta
A[-(1:(npar.xz+npar.yz)), -(1:(npar.xz+npar.yz))] = -diag(N, nx*ny-1)
## One way of coding:
##B = t(bigphi) %*% bigphi
##var.theta = solve(A) %*% B %*% solve(A)
## Suggested coding for better efficiency and accuracy:
##SS = solve(A, t(bigphi))
##var.theta = SS %*% t(SS)
## Or better yet, no need to explicitly obtain var.theta. See below.
## Test statistic T1 = tau - tau0
T1 = cdtau$gamma - cdtau0$gamma
## dT.dtheta has length nx + ny + nx*ny-1
dT1.dtheta = c(-dtau0.dtheta.x, -dtau0.dtheta.y, dtau.dPa)
## variance of T, using delta method
##varT = t(dT.dtheta) %*% var.theta %*% dT.dtheta
SS = crossprod(dT1.dtheta, solve(A, t(bigphi)))
varT1 = sum(SS^2)
pvalT1 = 2 * pnorm(-abs(T1)/sqrt(varT1))
ans <- structure(
list(
TS=list(
T1=list(ts=T1, var=varT1, pval=pvalT1, label="Gamma(Obs) - Gamma(Exp)"),
T2=list(ts=T2, var=varT2, pval=pvalT2, label="Correlation of Residuals"),
T3=list(ts=T3, var=varT3, pval=pvalT3, label="Covariance of Residuals")
),
fisher=fisher,
conf.int=conf.int,
data.points=data.points
),
class="cobot")
# Apply confidence intervals
for (i in seq_len(length(ans$TS))){
ts_ci <- getCI(ans$TS[[i]]$ts,ans$TS[[i]]$var,ans$fisher,conf.int)
ans$TS[[i]]$lower <- ts_ci[1]
ans$TS[[i]]$upper <- ts_ci[2]
}
ans
}
|
1113fd7e5e7f2c86e7673b56d4aabddeb651df27
|
634b4702b2f15e302015d4b961fcb9f8625d3d41
|
/section6.within.jackknife.evaluation.normal.R
|
fd61dc05f38c00488258d25fc2967a39b0e6ba81
|
[] |
no_license
|
raduvro/TOCHI-supplementary
|
bef0bfe61e6a5ff54be611cced52154aca528569
|
aca58c37dcdbc839fd62c5cbe6ab467c8a5375ba
|
refs/heads/master
| 2020-06-10T15:34:24.583765
| 2018-10-19T10:10:53
| 2018-10-19T10:10:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,476
|
r
|
section6.within.jackknife.evaluation.normal.R
|
#===========================================================================================
# Simuation experiment for evaluating the Type I error of the jackknife technique
# Theophanis Tsandilas
#======================================================================================
rm(list=ls()) # Clean up R's memory
source("coefficients/agreement.coefficients.R")
source("coefficients/agreement.CI.R")
################################################
################################################
################################################
# Code for simulating the creation of populations with specific AR levels
######################
######################
library("Rmisc")
library("zipfR") # Check http://www.r-bloggers.com/the-zipf-and-zipf-mandelbrot-distributions/
crossesZero <- function(ci){
if(ci[2] <= 0 && ci[3] >=0) TRUE
else FALSE
}
typeI.estimation <- function(N, sds, R = 100, alpha = .05){
L <- length(sds)
errors <- rep(0, L)
conflev = 1 - alpha
for(r in 1:R){
cat("\r", r, " out of ", R, " : ", errors/r)
# 1st random sample of size N (1st referent)
samples1 <- mapply(population.create, rep(N, L), sds)
# 2nd random sample of size N (2nd referent)
samples2 <- mapply(population.create, rep(N, L), sds)
for(i in 1:L){
ci <- jack.CI.diff.random.raters(as.data.frame(t(samples1[, i])),
as.data.frame(t(samples2[, i])), percent.agreement, confint = conflev)
if(!crossesZero(ci)) errors[i] <- errors[i] + 1
}
flush.console()
}
cat("\n")
estimates <- list()
for(i in 1:L){
res <- binom.test(errors[i], R)
estimates[[i]] <- c(res$estimate, res$conf.int[1], res$conf.int[2])
}
estimates
}
# Create a population of size N from a normal frequency distribution with mean = 1 and std. dev = sd
# P is the size of the population - any large enough value will suffice
population.create <- function(N, sd, P = 10000){
sample <- sample(c(1:P), N, replace = TRUE, prob=dnorm(mean=1,sd=sd,c(1:P)))
sample
}
########################################################################
########################################################################
###### Running this whole script can take long...
# These are parameters for the normal distribution.
# They have been empirically approximated to produce distributions that correspond to different AR levels (AR = .1, .2, ..., .9)
sds <- c(5.42, 2.56, 1.63, 1.15, .88, .69, .576, .493, .416)
R <- 1600 # Number of trials for estimating the Type I error
#################################################################
#################################################################
#################################################################
alpha <- .05
errors <- typeI.estimation(20, sds, R, alpha)
cat("\n=========== Results for n = 20 and alpha = .05 (mean and 95% CIs) for AR = .1, .2, ..., .9 =================\n")
print(errors)
cat("=================================================\n\n")
#################################################################
#################################################################
#################################################################
|
0f377b28da6219c2322b060a6336f9096adac8e9
|
00daf46a1286c20caa103a95b111a815ea539d73
|
/AnalyzeCCode/class.R
|
aa595960796d0ec7ac0bbb51537afa7f3fd55106
|
[] |
no_license
|
duncantl/Rllvm
|
5e24ec5ef50641535895de4464252d6b8430e191
|
27ae840015619c03b2cc6713bde71367edb1486d
|
refs/heads/master
| 2023-01-10T15:12:40.759998
| 2023-01-02T18:05:26
| 2023-01-02T18:05:26
| 3,893,906
| 65
| 14
| null | 2017-03-09T07:59:25
| 2012-04-01T16:57:16
|
R
|
UTF-8
|
R
| false
| false
| 334
|
r
|
class.R
|
library(Rllvm)
source("getType.R")
m = parseIR("foo.ir")
setMethod("show", "Value", function(x) print(as(x,'character')))
o = compReturnType(m$rklass)
if(FALSE) {
ii = as(nm, "Instruction")
v = .Call("R_GlobalVariable_getInitializer", ii[[1]])
getClassName(v)
.Call("R_ConstantDataSequential_getAsCString", v)
}
|
98ac280bdad91be47ff5c4e1cd9b67f9e0cfb119
|
0bf034ee0fce24b754878e59c67c3c4a0d33cd92
|
/app/global.R
|
6aafdb33b9a427466d4c0e115afea8d4d6dae5ec
|
[] |
no_license
|
mllewis/langLearnVar
|
16c7761df7a4879c358ece8ab5cbd2d035e73612
|
adb3540de81c0caa57e0fd910c652858f62e4b0a
|
refs/heads/master
| 2020-12-14T23:39:16.397044
| 2017-07-18T21:05:10
| 2017-07-18T21:05:10
| 49,292,588
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,392
|
r
|
global.R
|
# Variables that can be put on the x and y axes
axis_vars <- c(
"Area (log)" = "area_log",
"Complexity bias"= "complexity.bias",
"Complexity bias (partialing out frequency)" = "p.complexity.bias",
"Complexity bias (monomorphemic words only)" = "mono.complexity.bias",
"Complexity bias (open class words only)" = "open.complexity.bias",
"Consonant diversity" = "normalized.consonant.diversity",
"Distance from origin" = "distance.from.origin",
"Growing season" = "growing.season",
"Information density" = "information.density",
"Information rate" = "information.rate",
"Lexical diversity (entropy)" = "scaled.LDT.H",
"Lexical diversity (type-token ratio)" = "scaled.LDT.TTR",
"Lexical diversity (ZM law parameters)" = "scaled.LDT.ZM",
"Latitude" = "lat",
"Longitude" = "lon",
"Mean AoA" = "mean.aoa",
"Mean dependency length" = "mean.dependency.length",
"Mean length"= "mean.length",
"Mean temperature (celsius)" = "mean.temp",
"Morphological complexity" = "morphological.complexity",
"Number consonants (log)" = "n.consonants_log",
"Number of ling neighbors (log)" = "n.neighbors_log",
"Number L1 speakers (log)" = "n.L1.speakers_log",
"Number L2 speakers (log)" = "n.L2.speakers_log",
"Number monophthongs (log)" = "n.monophthongs_log",
"Number obstruents (log)" = "n.obstruents_log",
"Number phonemes (log)" = "n.phonemes_log",
"Number q. monophthongs (log)" = "n.qual.monophthongs_log",
"Number sonorants (log)" = "n.sonorants_log",
"Number tones (log)" = "n.tones_log",
"Number vowels (log)" = "n.vowels_log",
"Phoneme diversity" = "normalized.phoneme.diversity",
"Perimeter (log)" = "perimeter_log",
"Ratio L2:L1 (log)" = "ratio.L2.L1_log",
"SD precipitation (cm; log)" = "sd.precip_log",
"SD temperature (celsius)" = "sd.temp",
"Sum precipitation (cm)" = "sum.precip",
"Syllable rate" = "syllable.rate",
"Tone diversity" = "normalized.tone.diversity",
"Total population (log) " = "pop_log",
"Vowel diversity" = "normalized.vowel.diversity"
)
|
5479a2c4914a82b7e2415a283fb0458923cadc71
|
91634073099e254722a3bf759108429913e73d89
|
/plot3.R
|
3649c1d0eec6420d2d2ebf1a4bb525edaac08001
|
[] |
no_license
|
anushav85/ExData_Plotting1
|
508e49a34c884c9507c86765c358f1563194f8ca
|
9d4f077c28becad356e982be8eb06ab5c3b245ef
|
refs/heads/master
| 2020-12-25T09:38:13.971551
| 2014-06-08T22:50:07
| 2014-06-08T22:50:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 797
|
r
|
plot3.R
|
png("plot3.png")
rawfile <- file("household_power_consumption.txt","r")
cat(grep("(^Date)|(^[1|2]/2/2007)", readLines(rawfile), value = TRUE), sep="\n", file="filtered.txt")
close(rawfile)
powerdata <- read.csv2("filtered.txt", na.strings = "?")
datetime <- strptime(paste(powerdata$Date, powerdata$Time), format = "%d/%m/%Y %H:%M:%S")
plot(datetime, as.numeric(as.character(powerdata$Sub_metering_1)), type = 'l',xlab ='', ylab="Energy sub metering")
lines(datetime, as.numeric(as.character(powerdata$Sub_metering_2)), type = 'l', col = "red")
lines(datetime, as.numeric(as.character(powerdata$Sub_metering_3)), type = 'l', col = "blue")
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black","red","blue"),lty=c(1,1,1),pt.cex = cex,cex=1)
dev.off()
|
a7688b5938e7a3f65036f33af2343f4ab9042258
|
9a31e99c6e6c5fcee3be719a2cf5cc77c233e5ab
|
/docs/demo/basic-use-of-r/Data_Visualization.R
|
86791442215c360fc49e14a50906ed8326b15ab1
|
[] |
no_license
|
NErler/BST02
|
e7f26c6db87aeb790006a94a717cb68513971e56
|
35afe3d44c41f169da754c8acb4a6204829cf0a6
|
refs/heads/master
| 2021-06-25T01:37:13.798487
| 2021-03-02T14:01:17
| 2021-03-02T14:01:17
| 211,871,452
| 1
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 10,895
|
r
|
Data_Visualization.R
|
#' ---
#' title: "Demo: Data Visualization"
#' subtitle: "NIHES BST02"
#' author: "Eleni-Rosalina Andrinopoulou, Department of Biostatistics, Erasmus Medical Center"
#' date: "`r Sys.setenv(LANG = 'en_US.UTF-8'); format(Sys.Date(), '%d %B %Y')`"
#' output:
#' html_document:
#' toc: true
#' toc_float:
#' collapsed: false
#' ---
#'
#' ## Load packages
#' If you are using the package for the first time, you will first have to install it. \
# install.packages("survival")
# install.packages("lattice")
# install.packages("ggplot2")
# install.packages("emojifont")
# install.packages("gtrendsR")
#' If you have already downloaded this package in the current version of R, you will only have to load the package.
library(survival)
library(lattice)
library(ggplot2)
library(emojifont)
library(gtrendsR)
#' ## Get the data
#' Load a data set from a package.\
#' You can use the double colon symbol (:), to return the pbc and pbcseq objects from the package survival. We store these data sets to new objects with the names pbc and pbcseq.
pbc <- survival::pbc
pbcseq <- survival::pbcseq
#' ## Basic plots
#' Basic plot with 1 continuous variable using the function `plot()`. For example, investigate the variable `bili` of the pbc data set.
plot(x = pbc$bili)
#' Basic plot with 2 continuous variables. For example, Check the correlation between `age` and `bili` of the pbc data set.
plot(x = pbc$age, y = pbc$bili)
#' Basic plot with 2 continuous variables. Now, insert labels for the x and y-axis (use the argument xlab).
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age")
#' Basic plot with 2 continuous variables. Now, insert labels for the x and y-axis and change the size of the axis and labels (use the arguments cex.axis and cex.lab).
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.2, cex.lab = 1.4)
#' Basic plot with 2 continuous variables. Insert axis labels and change the size and type of points.
#' Change also the size and the type of the points (use the arguments cex and pch).
#' If you are not sure which arguments to use, check the help page.
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.2, cex.lab = 1.4,
cex = 2, pch = 16)
#' Basic plot with 2 continuous variables. Insert labels for the x and y-axis and change the size of the axis and labels. Change also the colour of the points. \
#' Note that we can set the colours in different ways:\
#' * using numbers that correspond to a colour \
#' * using the name of the colour \
#' * using the RGB colour specification (Red Green Blue) `?rgb` \
#' * using the HEX colour code
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.2, cex.lab = 1.4,
col = 2)
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.2, cex.lab = 1.4,
col = "red")
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.2, cex.lab = 1.4,
col = rgb(1,0,0))
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.2, cex.lab = 1.4,
col = "#FF0000")
#' Basic plot with 3 variables (2 continuous and 1 categorical). X-axis represents `age`, y-axis represents `serum bilirubin` and colours represent `sex`.
plot(x = pbc$age, y = pbc$bili, ylab = "Serum bilirubin", xlab = "Age",
cex.axis = 1.5, cex.lab = 1.4, col = pbc$sex, pch = 16)
legend(30, 25, legend = c("male", "female"), col = c(1,2), pch = 16)
#' Histogram for continuous variables. Check the distribution of `bili` and investigate the argument breaks and length.
hist(x = pbc$bili, breaks = 50)
hist(x = pbc$bili, breaks = seq(min(pbc$bili), max(pbc$bili), length = 20))
#' Multiple panels (using the `par()` function).
par(mfrow=c(2,2))
hist(x = pbc$bili, freq = TRUE)
hist(x = pbc$chol, freq = TRUE)
hist(x = pbc$albumin, freq = TRUE)
hist(x = pbc$alk.phos, freq = TRUE)
#' Check what the argument freq does.\
#' Tip: Note that sometimes you will have to clear all plots in order to get 1 panel again (brush icon in `Plots` tab).
#' Barchart for categorical variables using the function `plot()`. Check the frequency of `males` and `females`.
plot(x = pbc$sex)
#' Piechart for categorical variables using the functions `pie()` and `table()`. Check the frequency of `males` and `females`.
pie(x = table(pbc$sex))
#' Boxplot for investigating the distribution of a continuous variable per group using the function `boxplot()`. Check the distribution of `age` per `sex` group.
boxplot(formula = pbc$age ~ pbc$sex, ylab = "Age", xlab = "Gender")
#' Multivariate plot of the variables `bili`, `chol` and `albumin`.
#' We first need to create a matrix/data.frame.
pairs(x = data.frame(pbc$bili, pbc$chol, pbc$albumin))
pairs(x = cbind(pbc$bili, pbc$chol, pbc$albumin))
pairs(formula = ~ bili + chol + albumin, data = pbc)
#' In the last case we set the data set to pbc. That means that we do not have to specify pbc every time we select a variable.
#' The function knows that it has to look in the pbc data set for these names.
#' Density plots of `bili` per `sex` group to investigate the distribution. \
#' Several ways exist to obtain this plot.
# Here we start by assigning the `bili` values for `males` and `females` to a new object.
pbc_male_bili <- pbc$bili[pbc$sex == "m"]
pbc_female_bili <- pbc$bili[pbc$sex == "f"]
# We first plot the `bili` values for `males`.
plot(density(pbc_male_bili), col = rgb(0,0,1,0.5), ylim = c(0,0.40),
main = "Density plots", xlab = "bili", ylab = "")
# Then we fill in the area under the curve using the function `polygon()`.
polygon(density(pbc_male_bili), col = rgb(0,0,1,0.5), border = "blue")
# Then we add the `bili` values for `females`. Since a plot has been already specified we can use the function `lines()` to add a line.
lines(density(pbc_female_bili), col = rgb(1,0,0,0.5))
# Then we fill in the area under the curve using the function `polygon()`.
polygon(density(pbc_female_bili), col = rgb(1,0,0,0.5), border = "red")
# Finally, we add a legend using the `legend()` function.
legend(5,0.3, legend = c("male", "female"),
col = c(rgb(0,0,1,0.5), rgb(1,0,0,0.5)), lty = 1)
#' ## Lattice family
#' Correlation between `bili` and `age`. Investigate the arguments type and lwd.
xyplot(x = bili ~ age, data = pbc, type = "p", lwd = 2)
#' Smooth evolution of `bili` with `age`. To change the type of plot use the argument type.
xyplot(x = bili ~ age, data = pbc, type = c("p", "smooth"), lwd = 2)
#' Smooth evolution of `bili` with `age` per `sex`. Assume different colours for each `sex` category using the group argument.
xyplot(x = bili ~ age, group = sex, data = pbc, type = "smooth",
lwd = 2, col = c("red", "blue"))
#' Smooth evolution with points of `bili` with `age` per `sex`. Assume different colours for each `sex` category.
xyplot(x = bili ~ age, group = sex, data = pbc, type = c("p", "smooth"),
lwd = 2, col = c("red", "blue"))
#' Smooth evolution with points of `bili` with `age` per `sex` (as separate panel).
xyplot(x = bili ~ age | sex, data = pbc, type = c("p", "smooth"),
lwd = 2, col = c("red"))
#' Smooth evolution with points of `bili` with `age` per `status` (as separate panel).
xyplot(x = bili ~ age | status, data = pbc, type = c("p", "smooth"),
lwd = 2, col = c("red"))
#' Smooth evolution with points of `bili` with `age` per `status` (as separate panel - change layout).
xyplot(x = bili ~ age | status, data = pbc, type = c("p", "smooth"),
lwd = 2, col = c("red"), layout = c(2,2))
#' Smooth evolution with points of `bili` with `age` per `status` (as separate panel - change layout). \
#' Transform `status` into a factor with labels and run the plot again.
pbc$status <- factor(x = pbc$status, levels = c(0, 1, 2),
labels = c("censored", "transplant", "dead"))
xyplot(x = bili ~ age | status, data = pbc, type = c("p", "smooth"),
lwd = 2, col = c("red"), layout = c(3,1))
#' Individual patient plot.
xyplot(x = bili ~ day, group = id, data = pbcseq, type = "l", col = "black")
#' Individual patient plot per `status`.
pbcseq$status <- factor(x = pbcseq$status, levels = c(0, 1, 2),
labels = c("censored", "transplant", "dead"))
xyplot(x = bili ~ day | status, group = id, data = pbcseq, type = "l",
col = "black", layout = c(3,1),
grid = TRUE, xlab = "Days", ylab = "Serum bilirubin")
#' Barchart for categorical variables using the function `barchart()`. Checking the frequency of `males` and `females`.
barchart(x = pbc$sex)
#' Boxplot of `serum bilirubin` per `sex` group using the function `bwplot()`.
bwplot(x = pbc$bili ~ pbc$sex)
#' ## Ggplot family
#' Correlation between `age` with `bili`. \
#' Each `sex` has a different colour.
ggplot(data = pbc, mapping = aes(age, bili, colour = sex)) +
geom_point()
ggplot(data = pbc, mapping = aes(age, bili, colour = sex)) +
geom_point(alpha = 0.3) +
geom_smooth()
#' Correlation between `day` with `bili` for patient 93. \
#' A smoothed curve is added in blue.
ggplot(data = pbcseq[pbcseq$id == 93,], mapping = aes(day, bili)) +
geom_line() +
geom_smooth(colour = "blue", span = 0.4) +
labs(title = "Patient 93", subtitle = "Evolution over time",
y = "Serum bilirubin", x = "Days")
#' Correlation between `serum bilirubin` per `stage`.
ggplot(data = pbc, mapping = aes(stage, bili, group = stage)) +
geom_boxplot() +
labs(y = "Serum bilirubin", x = "Stage")
#' Density plot of `serum bilirubin` per `sex` to investigate the distribution. \
#' Be aware that a plot is an object in R, so you can save it.
p <- ggplot(data = pbc, mapping = aes(bili, fill = sex)) +
geom_density(alpha = 0.25)
p
p + scale_fill_manual(values = c("#999999", "#E69F00"))
#' ## Let's have some fun
set.seed(123)
x1 <- rnorm(10)
y1 <- rnorm(10)
x2 <- rnorm(10)
y2 <- rnorm(10)
plot(x = x1, y = y1, cex = 0)
points(x = x1, y = y1, pch = 16)
plot(x = x1, y1, cex = 0)
text(x = x1, y = y1, cex = 1.5, col = "red")
plot(x = x1, y = y1, cex = 0)
text(x = x1, y = y1, labels = emoji("heartbeat"), cex = 1.5, col = "red", family = "EmojiOne")
text(x = x2, y = y2, labels = emoji("cow"), cex = 1.5, col = "steelblue", family = "EmojiOne")
search_emoji("face")
plot(x = x1, y = y1, cex = 0)
text(x = x1, y = y1, labels = emoji("nerd_face"), cex = 1.5, col = "red", family = "EmojiOne")
plot(x = x1, y = y1, cex = 0)
text(x = x1, y = y1, labels = emoji("face_with_head_bandage"),
cex = 1.5, col = "blue", family = "EmojiOne")
#' Using google data
google.trends1 = gtrends(c("feyenoord"), gprop = "web", time = "all")[[1]]
ggplot(data = google.trends1, mapping = aes(x = date, y = hits)) +
geom_line() +
labs(y = "Feyenoord", x = "Time") +
ggtitle("Hits on Google")
|
84d1d2d2305bcab18044250428b74cd8c915af4e
|
c59f494aacfd20a71b4a44c1c1bc7fa91da60977
|
/R/irf.svarest.R
|
167f9f8dc28a42a8ce83c55c790dc8dd692dd612
|
[] |
no_license
|
cran/vars
|
32a6b2be807d55b0dfaba321056ac460770c7eb6
|
3f80033a4a9169c13dc55c481ed3ba0b89256703
|
refs/heads/master
| 2023-04-06T11:14:54.671093
| 2023-03-22T21:20:03
| 2023-03-22T21:20:03
| 17,700,726
| 8
| 16
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,822
|
r
|
irf.svarest.R
|
"irf.svarest" <-
function(x, impulse=NULL, response=NULL, n.ahead=10, ortho=TRUE, cumulative=FALSE, boot=TRUE, ci=0.95, runs=100, seed=NULL, ...){
if(!is(x, "svarest")){
stop("\nPlease provide an object of class 'svarest', generated by 'SVAR()'.\n")
}
y.names <- colnames(x$var$y)
if(is.null(impulse)){
impulse <- y.names
} else {
impulse <- as.vector(as.character(impulse))
if(any(!(impulse %in% y.names))) {
stop("\nPlease provide variables names in impulse\nthat are in the set of endogenous variables.\n")
}
impulse <- subset(y.names, subset = y.names %in% impulse)
}
if(is.null(response)){
response <- y.names
} else {
response <- as.vector(as.character(response))
if(any(!(response %in% y.names))){
stop("\nPlease provide variables names in response\nthat are in the set of endogenous variables.\n")
}
response <- subset(y.names, subset = y.names %in% response)
}
## Getting the irf
irs <- .irf(x = x, impulse = impulse, response = response, y.names = y.names, n.ahead = n.ahead, ortho = ortho, cumulative = cumulative)
## Bootstrapping
Lower <- NULL
Upper <- NULL
if(boot){
ci <- as.numeric(ci)
if((ci <= 0)|(ci >= 1)){
stop("\nPlease provide a number between 0 and 1 for the confidence interval.\n")
}
ci <- 1 - ci
BOOT <- .boot(x = x, n.ahead = n.ahead, runs = runs, ortho = ortho, cumulative = cumulative, impulse = impulse, response = response, ci = ci, seed = seed, y.names = y.names)
Lower <- BOOT$Lower
Upper <- BOOT$Upper
}
result <- list(irf=irs, Lower=Lower, Upper=Upper, response=response, impulse=impulse, ortho=ortho, cumulative=cumulative, runs=runs, ci=ci, boot=boot, model = class(x))
class(result) <- "varirf"
return(result)
}
|
9d982851250cd4e33a212b5858a6fa7940b22141
|
494c71f56647f6695bd8b046372fd42c7f1b9040
|
/man/roxygen/templates/ignore_case.R
|
16e8473e8c78a0a3d7e9b129f0bd3175f0e0a3e5
|
[] |
no_license
|
minghao2016/tidysq
|
1e813a019878dac2bb1cb239d05fa97e37bc93b4
|
953b1d3c1ce1e250f9afcb3f8fe044c6f7391c76
|
refs/heads/master
| 2023-03-23T20:03:08.700872
| 2021-03-12T17:03:05
| 2021-03-12T17:03:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 375
|
r
|
ignore_case.R
|
#' @param ignore_case [\code{logical(1)}]\cr
#' If turned on, lowercase letters are turned into respective uppercase ones
#' and interpreted as such. If not, either \code{sq} object must be of type
#' \strong{unt} or all lowercase letters are interpreted as \code{NA} values.
#' Default value is \code{FALSE}. Ignoring case does not work with \strong{atp}
#' alphabets.
|
2ae9c85a93130a60ff6337feffa53aa405ee7b57
|
39b974a89bac599687f4a777cad54edf18866584
|
/R/lazy_plot.R
|
f0505efb72ab6ff26bfca21df74f2fde06c530a8
|
[
"MIT"
] |
permissive
|
XanderHorn/lazy
|
cde252acdf12b67f9e8f5dd5201785aec3d0c2bd
|
f83085477ad2275e53ab45095f187fbb7c34fbfe
|
refs/heads/master
| 2022-04-10T15:37:07.500066
| 2020-02-28T08:54:50
| 2020-02-28T08:54:50
| 176,108,807
| 1
| 1
| null | 2019-06-26T06:21:25
| 2019-03-17T13:57:11
|
R
|
UTF-8
|
R
| false
| false
| 5,720
|
r
|
lazy_plot.R
|
#' Lazy ggplot plotting
#'
#' Quickly produces specifc plots using the ggplot library. This function is exported but its main purpose is to be used in the eda function.
#'
#' @param data [required | data.frame] Dataset containing predictor and / or target features.
#' @param x [optional | character | default=NULL] A vector of feature names present in the dataset used to predict the target feature. If NULL then all columns in the dataset is used.
#' @param y [required | character | default=NULL] The name of the target feature contained in the dataset.
#' @param type [optional | character | default="histogram"] The type of plot to be produced. For numeric feature types histogram, density, boxplot and violin are available. For categorical bar and stackedbar are available.
#' @param transparency [optional | numeric | default = 1] Transparency applied to plots.
#' @param theme [optional | numeric | default=1] Color theme applied to plot, options range from 1 to 4.
#' @return Plot of ggplot2 type
#' @export
#' @examples
#' lazy.plot(iris, x = "Sepal.Length", y = "Species", type = "density")
#' lazy.plot(iris, x = "Sepal.Length", y = "Species", type = "violin")
#' @author
#' Xander Horn
lazy.plot <- function(data, x = NULL, y = NULL, type = "histogram", transparency = 1, theme = 1){
library(ggplot2)
library(RColorBrewer)
if(missing(data)){
stop("Provide data to function")
}
if(is.null(x) == TRUE){
x <- names(data)
}
if(is.null(y) == FALSE){
x <- setdiff(x, y)
data[,y] <- as.character(data[,y])
}
tol8qualitative <- c("#332288", "#88CCEE", "#44AA99", "#117733","#999933", "#DDCC77", "#CC6677", "#AA4499")
set8equal <- c("#66C2A5", "#8DA0CB", "#A6D854", "#B3B3B3", "#E5C494", "#E78AC3", "#FC8D62", "#FFD92F")
redmono = c("#99000D", "#CB181D", "#EF3B2C", "#FB6A4A", "#FC9272", "#FCBBA1", "#FEE0D2")
greenmono = c("#005A32", "#238B45", "#41AB5D", "#74C476", "#A1D99B", "#C7E9C0", "#E5F5E0")
bluemono = c("#084594", "#2171B5", "#4292C6", "#6BAED6", "#9ECAE1", "#C6DBEF", "#DEEBF7")
greymono = c("#000000", "#252525", "#525252", "#737373", "#969696", "#BDBDBD", "#D9D9D9")
if(theme == 1){
theme <- c(brewer.pal(9, "Set1"), brewer.pal(12, "Paired"))
} else if(theme == 2){
theme <- c(brewer.pal(12, "Paired"), brewer.pal(8, "Accent"))
} else if(theme == 3){
theme <- c(brewer.pal(8, "Dark2"), set8equal, tol8qualitative)
} else if(theme == 4){
theme <- c("#4527A0", "#B39DDB", bluemono, redmono, greenmono, greymono)
}
p <- ggplot(data = data)
if(type == "histogram"){
if(is.null(y) == TRUE){
p <- p +
aes(x = data[,x]) +
geom_histogram(alpha = transparency, fill = theme[2], color = "white", bins = 25) +
labs(x = x, y = "Frequency") +
theme_light()
} else {
p <- p +
aes(x = data[,x], fill = data[,y]) +
geom_histogram(alpha = transparency, color = "white", bins = 25) +
labs(x = x, y = "Frequency") +
guides(colour = FALSE, fill = guide_legend(title = y)) +
scale_fill_manual(values = theme) +
scale_color_manual(values = theme) +
theme_light()
}
}
if(type == "density"){
if(is.null(y) == TRUE){
p <- p +
aes(x = data[,x]) +
geom_density(alpha = transparency, fill = theme[2], color = theme[2]) +
labs(x = x, y = "Density") +
theme_light()
} else {
p <- p +
aes(x = data[,x], fill = data[,y], color = data[,y]) +
geom_density(alpha = 0.5) +
labs(x = x, y = "Density") +
guides(colour = FALSE, fill = guide_legend(title = y)) +
scale_fill_manual(values = theme) +
scale_color_manual(values = theme) +
theme_light()
}
}
if(type == "boxplot"){
p <- p +
aes(x = data[,y], y = data[,x], color = data[,y]) +
geom_boxplot(lwd = 0.8, outlier.colour = "black",outlier.shape = 16, outlier.size = 2, alpha = transparency) +
labs(x = y, y = x) +
guides(fill = FALSE, colour = FALSE) +
scale_color_manual(values = theme) +
theme_light()
}
if(type == "violin"){
p <- p +
aes(x = data[,y], y = data[,x], fill = data[,y]) +
geom_violin(alpha = transparency, color = "white") +
labs(x = y, y = x) +
guides(fill = FALSE, colour = FALSE) +
scale_fill_manual(values = theme) +
theme_light()
}
if(type == "bar"){
props <- as.data.frame(prop.table(table(data[,x])))
props <- props[order(props$Freq), ]
if(is.null(y) == TRUE){
p <- p +
aes(x = factor(data[,x], levels = props$Var1)) +
geom_bar(aes(y = (..count..)/sum(..count..)), fill = theme[2], alpha = transparency) +
scale_y_continuous(labels = scales::percent) +
labs(x = x, y = "Percentage") +
coord_flip() +
theme_light()
} else {
p <- p +
aes(x = factor(data[,x], levels = props$Var1), fill = data[,y]) +
geom_bar(aes(y = (..count..)/sum(..count..)), alpha = transparency) +
scale_y_continuous(labels = scales::percent) +
labs(x = x, y = "Percentage") +
guides(fill = guide_legend(title = y)) +
scale_fill_manual(values = theme) +
coord_flip() +
theme_light()
}
}
if(type == "stackedbar"){
p <- p +
aes(x = data[,y], fill = data[,x]) +
geom_bar(aes(y = (..count..)/sum(..count..)), position = "fill", alpha = transparency) +
scale_y_continuous(labels = scales::percent) +
labs(x = y, y = "Percentage") +
guides(fill = guide_legend(title = x)) +
scale_fill_manual(values = theme) +
theme_light()
}
return(p)
}
|
7c612608a49ed1a7797093f7b9f8e0cd1cd9f4ac
|
1e912c54cb17be1e24fe47072498f3e7bbc37a1e
|
/R/derCOPinv.R
|
34ff86aeb0925d178e6f8cab97ec3226aff57ee3
|
[] |
no_license
|
cran/copBasic
|
a3149fffc343130a77e693dae608dde9ca50cd05
|
84adb528160d3cd5abb83e06da276a6df9af382f
|
refs/heads/master
| 2023-06-23T14:32:12.974136
| 2023-06-19T15:50:02
| 2023-06-19T15:50:02
| 17,695,240
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 973
|
r
|
derCOPinv.R
|
"derCOPinv" <-
function(cop=NULL, u, t, trace=FALSE,
delu=.Machine$double.eps^0.50, para=NULL, ...) {
func <- function(x,u,LHS,cop,delu=delu,para=para, ...) {
LHS - derCOP(cop=cop, u=u, v=x, delu=delu, para=para, ...)
}
f.lower <- func(0,u,t,cop,delu=delu,para=para, ...)
f.upper <- func(1,u,t,cop,delu=delu,para=para, ...)
if(sign(f.lower) == sign(f.upper)) {
if(trace) message("not opposite signs for f.lower=",f.lower,
" and f.upper=",f.upper,
" at u=",u, " and t=",t,
"\nThis might be because of degenerate derivative on the section at u.")
return(NA)
}
my.rt <- NULL
try(my.rt <- uniroot(func,interval=c(0,1), u=u, LHS=t,
cop=cop, delu=delu, para=para, ...))
if(is.null(my.rt)) return(NA) # Now the returned root is "v"
ifelse(length(my.rt$root) != 0, return(my.rt$root), return(NA))
}
|
12da2b356ac3366022a9f3b6a09a18aeeb331cb0
|
69a2266141c50abf94e525391fbddaadb45b9169
|
/plot3.R
|
21a41e6e10bf77fb3cb10b18d3a4e18681b955f2
|
[] |
no_license
|
casco/ExData_Plotting1
|
1982789fbeaffba7fa76bda4b76e5eac70aad983
|
c16b154254076215973895e8bd098d1da6abbe3f
|
refs/heads/master
| 2020-12-28T23:34:54.469002
| 2014-05-09T04:38:52
| 2014-05-09T04:38:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 962
|
r
|
plot3.R
|
data <- read.table("household_power_consumption.txt", sep=";", header=T,
colClasses=c(rep("character",2),rep("numeric",7)),
na.strings = "?")
data$Date <- strptime(data$Date, format="%d/%m/%Y")
period.start <- strptime("01/02/2007", format="%d/%m/%Y")
period.end <- strptime("02/02/2007", format="%d/%m/%Y")
data.selected <- data[(period.start <= data$Date) & (data$Date <= period.end),]
#Plot 3
png(file = "plot3.png", width = 480, height = 480)
par(xaxt = 'n')
plot(data.selected$Sub_metering_1, type="n", ylab="Energy sub metering", xlab="")
lines(data.selected$Sub_metering_1)
lines(data.selected$Sub_metering_2, col="red")
lines(data.selected$Sub_metering_3, col="blue")
legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=c(1,1,1), , col=c("black","red", "blue"))
par(xaxt = 's')
axis(1, labels=c("Thu", "Fri", "Sat"), at=c(1, nrow(data.selected) / 2, nrow(data.selected)))
dev.off()
|
a7a1fedf6ab2e68de7b79a37912b2002fc200be2
|
6334b663b9508cf0cda2d992f3efdffc4b4ec2cf
|
/man/data.diag.Rd
|
f47bd4a9b3af910d9f2e1a8212a164eba3197856
|
[] |
no_license
|
cran/fdm2id
|
40f7fb015f3ae231ca15ea7f5c5626187f753e1b
|
c55e577541b49e878f581b44dd2a8bae205779d0
|
refs/heads/master
| 2023-06-29T00:54:58.024554
| 2023-06-12T12:10:02
| 2023-06-12T12:10:02
| 209,820,600
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 959
|
rd
|
data.diag.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dataset.R
\name{data.diag}
\alias{data.diag}
\title{Square dataset}
\usage{
data.diag(
n = 200,
min = 0,
max = 1,
f = function(x) x,
levels = NULL,
graph = TRUE,
seed = NULL
)
}
\arguments{
\item{n}{Number of observations in the dataset.}
\item{min}{Minimum value on each variables.}
\item{max}{Maximum value on each variables.}
\item{f}{The fucntion that separate the classes.}
\item{levels}{Name of each class.}
\item{graph}{A logical indicating whether or not a graphic should be plotted.}
\item{seed}{A specified seed for random number generation.}
}
\value{
A randomly generated dataset.
}
\description{
Generate a random dataset shaped like a square divided by a custom function
}
\examples{
data.diag ()
}
\seealso{
\code{\link{data.parabol}}, \code{\link{data.target1}}, \code{\link{data.target2}}, \code{\link{data.twomoons}}, \code{\link{data.xor}}
}
|
bb926ad9661e7ef9e97ea46a6c2f3b1a3bb1f882
|
840c55a1b087be2e7d7d0750bcb66ec4415c686f
|
/Data meeting and cleaning/Archive/BSOC-STEP1.R
|
5be463e79eca94f72ee39173410c24e7f7f98257
|
[] |
no_license
|
DecisionNeurosciencePsychopathology/redcap_in_r
|
70cdfe116d16774444ec0262e5619f11d5c8de2a
|
b1668e85454eefb113e29e57d172a2865ce47e53
|
refs/heads/master
| 2021-05-15T04:04:47.938822
| 2021-04-09T17:21:01
| 2021-04-09T17:21:01
| 119,751,789
| 3
| 4
| null | 2020-08-14T16:04:48
| 2018-01-31T22:29:27
|
R
|
UTF-8
|
R
| false
| false
| 14,671
|
r
|
BSOC-STEP1.R
|
#################################### SAME ####################################
## startup
rootdir="~/Box/skinner/projects_analyses/suicide_trajectories/data/soloff_csv_new/"
source('~/Documents/github/UPMC/startup.R')
var_map<-read.csv('~/Box/skinner/data/Redcap Transfer/variable map/kexin_practice.csv',stringsAsFactors = FALSE)
var_map[which(var_map=="",arr.ind = T)]<-NA
## verify Morgan's var_map.
####for the col is.box. NA should mean represent unecessary variables. i.e.
# if redcap_var and access_var both exist, is.checkbox cannot be NA
chckmg<-subset(var_map,select = c('redcap_var','access_var'),is.na(is.checkbox))
chckmg[which(!is.na(chckmg$redcap_var)&(!is.na(chckmg$access_var))),] #shoule give us nothing
# vice versa
chckmg<-subset(var_map,select = c('redcap_var','access_var','is.checkbox','FIX'),!is.na(is.checkbox)&as.logical(FIX))
#which(is.na(chckmg),arr.ind = T) # should give us nothing. if yes, try run the following line of code
sum(is.na(var_map$is.checkbox)) #of unecessary variabels (based on rows. duplicates included)
#var_map$is.checkbox[which(is.na(var_map$redcap_var)&!var_map$is.checkbox)]<-NA
#var_map$is.checkbox[which(is.na(var_map$access_var)&!var_map$is.checkbox)]<-NA
#sum(is.na(var_map$is.checkbox)) #of unecessary variabels (based on rows. duplicates included)
####remove all blank rows
#var_map[[8]]<-sapply(var_map[[8]], function(x) gsub("\"", "", x))###TEMP
## TEMP so that NA in 'is.checkbox' means that
remove_dupid = FALSE # if T, only keep duplicated id with the earliest date
#Initialize reports
log_out_of_range <- data.frame(id=as.character(),var_name=as.character(),wrong_val=as.character(),
which_form=as.character(),comments=as.character(),stringsAsFactors = F) #Report out-of-range values
log_replace <- data.frame(id=as.character(),var_name=as.character(),wrong_val=as.character(),
which_form=as.character(),comments=as.character(),stringsAsFactors = F) # Report wrong values/datatypes, correct and report
log_comb_fm <- data.frame(id=as.character(),var_name=as.character(),wrong_val=as.character(),
which_form=as.character(),comments=as.character(),stringsAsFactors = F) # Report issues during combining forms
deleted_rows<-list()
report_wrong <- function(id = NA, which_var = NA, wrong_val = NA, which_form = NA, comments = NA,
report = wrong_val_report,rbind=T){
new_repo <- data.frame(id = id, stringsAsFactors = F)
new_repo[1:nrow(new_repo),2]<- which_var
new_repo[1:nrow(new_repo),3]<- wrong_val
new_repo[1:nrow(new_repo),4]<- which_form
new_repo[1:nrow(new_repo),5]<- comments
colnames(new_repo)<-c('id','var_name','wrong_val', 'which_form','comments')
ifelse(rbind,return(rbind(report,new_repo)),return(new_repo))
}
# PREPARE variable: forms
all_formnm<-with(var_map,unique(Form_name[!is.na(Form_name)])) #get all redcap formnames
if (is.null(forms)){
forms<-all_formnm
} else {
# check if form names can be found in variable mapping
if (!is.vector(forms)){stop(message('`forms` must be a vector. Use "c("example1","example2")" or "example".'))}
if (sum(!forms %in% all_formnm)>1) {
stop(message('One of the formnames cannot be found in the variable mapping. Please note that form names are case sensitive and space sensitive.'))
}
# removed duplicates and NA from `forms`
forms<-unique(forms[!is.na(forms)])
}
rm(all_formnm)
#################################### SAME ####################################
#STEP1: Select a RC form, get an integrated RC form with complete variables, right variable names, splited ordinary variables with checkbox variables.
for (form_i in 1:length(forms)) {
#TEMPfor (form_i in 8) {
STEP1<-function(){
#STEP1.1 Select a RC form. Check if multiple origianl forms need to be combined into one form
formname <- forms[form_i] #formname(a character)
message(paste0("Cleaning form:",formname," now..."))
vm<-subset(var_map, Form_name==formname) #subset of var mapping for the current form
acvar_nonch<-with(vm,split(access_var,is.checkbox))$'FALSE' #non-checkbox var
acvar_chk<-with(vm,split(access_var,is.checkbox))$'TRUE' #checkbox var
fm_dir<-unique(vm$path) #path of forms
if (any(is.na(vm$path))){
stop(message('At least one row in var mapping does not give the path of directory for the original forms')) # path cannot be NA
}else{if(any(!file.exists(paste0(rootdir,fm_dir)))){stop(message('At least one row of path in var mapping does not exist.'))}}#path must be valid
#STEP1.2 Get raw. Grab forms, remove unecessary variables, combine forms by common cols and remove rows with different values in the common cols. If not need to combine multiple forms, jump to STEP1.3.
if (length(fm_dir)>1){
comb_fm_list<-lapply(fm_dir, function(fm_dir){read.csv(paste0(rootdir,fm_dir), stringsAsFactors = F)}) # grab forms
#comb_fm_list<-lapply(comb_fm_list, function(x){x[,-which(colnames(x)=='X')]}) # remove col 'X'
comb_fm_list<-lapply(comb_fm_list, function(x){x<-x[,which(colnames(x)%in%c(acvar_nonch,acvar_chk))]}) #remove unnecessary variables
#STEP1.2.1 Report or remove duplicated ID. No NAs in common cols
temp_dup_id<-as.vector(unlist(sapply(comb_fm_list, function(x){x[which(duplicated(x[[1]])),1]}))) # get duplicated ID
if (length(temp_dup_id)>0){
if (!as.logical(remove_dupid)){ # report duplicated ID
log_comb_fm<-report_wrong(id=temp_dup_id,which_var = 'ID',report = log_comb_fm,which_form = formname,comments = 'Duplicated ID. Note: it\'s possible that they are duplicated in each form.')
log_comb_fm<-unique(log_comb_fm)
message('Duplicated IDs exist. Refer to log_comb_fm for more info. Forms are stored as comb_fm_list.
Viewing details of duplicated ID...')}
temp_chck_dupid<-lapply(comb_fm_list,function(x){x[which(x[[1]]%in%temp_dup_id),]}); # Viewing details of duplicated ID
View(temp_chck_dupid[[1]]);View(temp_chck_dupid[[2]]);View(temp_chck_dupid[[3]]) #Viewing details of duplicated ID
remove_dupid<-readline(prompt = 'Enter T to remove duplciated ID; F to just report: ') # to remove duplicated ID based on date
if(as.logical(remove_dupid)){
temp_var_date<-unique(sapply(comb_fm_list, function(x){colnames(x)[2]}))
if(length(temp_var_date)>1){stop(message('For the forms to be combined, do they have the same 2nd-colname (should be the date)?'))}
temp_confirm<-readline(prompt = paste(
'Will remove duplicated ID and keep IDs with the earliest completion date. Please confirm that', temp_var_date,'are the dates.
Enter T to continue, F to stop:'))
if(as.logical(temp_confirm)){ #removed replicated id
new_deleted_rows<-lapply(comb_fm_list,function(comb_fm){
df<-do.call('rbind',lapply(split(comb_fm,comb_fm[1]),function(rows_by_id){rows_by_id[-which.min(as.Date(rows_by_id[[2]])),]}))
df$formname<-formname
df$whydeleted<-'Duplicated ID'
df})
names(new_deleted_rows)<-paste0(formname,"_dupID_",1:length(new_deleted_rows))
deleted_rows<-append(deleted_rows,new_deleted_rows)
comb_fm_list<-lapply(comb_fm_list,function(comb_fm){do.call('rbind',lapply(split(comb_fm,comb_fm[1]),function(rows_by_id){rows_by_id[which.min(as.Date(rows_by_id[[2]])),]}))}) # select ID with the earlist date
message('Checking duplicated ID...')
if(length(as.vector(unlist(sapply(comb_fm_list, function(x){x[which(duplicated(x[[1]])),1]}))))==0){
message('Duplicated ID removed.')
}else{stop(message('Duplicated ID not removed! Check codes.'))}
}
remove_dupid<-F # foreced to report dup ids for the next form
}
}
#STEP1.2.2 Get common cols. Each form should have the same number of rows
comm_var<-Reduce(intersect,lapply(comb_fm_list,names)) # get a vector of the names of common cols.
temp_comm_col_list<-lapply(comb_fm_list, function(x){x<-x[comm_var]}) # get the common cols for each form. all common cols are saved in one list.
if(!nlevels(sapply(comb_fm_list, nrow))==0){ # nrows of each AC form should be the same
stop(message(paste('For the access forms that needs combining:', formname,'do not have the same number of rows. The forms are stored as "comb_fm_list"')))
}else{message(paste("Good. Access forms",formname, "have the same number of rows."))}
temp_na_in_comm_col<-sum(is.na(unlist(temp_comm_col_list))) # should have no NAs in common cols
if(temp_na_in_comm_col>1){
stop(message(paste0('For the access forms that needs combining: ', formname,', there are ', temp_na_in_comm_col,' NAs in the common columns. The common columns are stored as "temp_comm_col_list".')))
}else{message(paste("Good. Access forms",formname, "do not have NAs in the common cols."))}
if(any(unlist(sapply(comb_fm_list,function(df){duplicated(df[[1]])})))){ # should be no duplciated IDs in the common cols
stop(message(paste0('For the access forms that needs combining: ', formname,', there are duplicated IDs. The common columns are stored as "temp_comm_col_list".')))
}else{message(paste("Good. Access forms",formname, "do note have duplicated IDs."))}
temp_confirm2<-readline(prompt = paste("Enter T to confirm this variable:",comm_var[2],"refers to date: "))
#STEP1.2.3 replace dates using dates of the first form
if(!as.logical(temp_confirm2)){stop()}else{
iddate<-temp_comm_col_list[[1]][,1:2]#;iddate<-iddate[order(iddate[1]),]
new_log_replace<-do.call("rbind",lapply(temp_comm_col_list,function(x){ #log replacement
temp_repo<-dplyr::anti_join(x[1:2],iddate)
if(nrow(temp_repo)>1){report_wrong(id=temp_repo[[1]],which_var = comm_var[2], wrong_val = temp_repo[[2]],which_form = formname,comments = "The date is changed when combing with other forms",report = log_replace,rbind = F)}
}))
if(is.null(new_log_replace)){
message(paste("No date data is replaced when combining forms for", formname))
}else{message(paste("Some date data is replaced when combining forms for", formname,". Refer to log_replace for details."))}
log_replace<-rbind(log_replace,new_log_replace)
temp_comm_col_list<-lapply(temp_comm_col_list,function(x){x[2]<-plyr::mapvalues(x[[1]],from = iddate[[1]], to = iddate[[2]]); x}) #update dates for common cols
for(i in 1:length(temp_comm_col_list)){comb_fm_list[[i]][comm_var]<-temp_comm_col_list[[i]]} #update dates for the combined_forms_list
}
#STEP1.2.4 Remove rows that have different values in the common cols.
new_comm_col<-Reduce(dplyr::inner_join,temp_comm_col_list) # innerjoin common cols
removed_rows<-nrow(temp_comm_col_list[[1]])-nrow(new_comm_col)
if(removed_rows>0){ #report removed rows
message(paste(removed_rows,"rows are removed when combining the forms for",formname,".
They have severl weird values (eg: mistype of id (7162->7165)) in the common cols but are probably usable. Refer to log_replace and deleted_rows for details"))
removedid<-unique(unlist(sapply(temp_comm_col_list,function(x){setdiff(x[[1]],new_comm_col[[1]])})))
new_deleted_rows<-lapply(comb_fm_list,function(comb_fm){
df<-comb_fm[which(!comb_fm[[1]]%in%new_comm_col[[1]]),]
df$formname<-formname
df$whydeleted<-'Different values in the common cols across forms'
df})
names(new_deleted_rows)<-paste0(formname,"_CommCol_",1:length(new_deleted_rows))
deleted_rows<-append(deleted_rows,new_deleted_rows)
log_replace<-report_wrong(id = removedid,which_var = "REMOVED", wrong_val = "REMOVED",which_form = formname, comments = "DELETED ROWS when importing/combining forms",report = log_replace,rbind = T)
}
#if(any(!sapply(temp_comm_col_list,function(x){identical(temp_comm_col_list[[1]],x)}))){stop(message(paste("Combining forms for",formname,"Common cols not identical.")))} #Check if common cols have identical values
comb_fm_list<-lapply(comb_fm_list,function(x){x<-dplyr::inner_join(x,new_comm_col)}) #remove some rows where the common rows have different values across forms
#STEP1.2.5 get 'raw' -- necessary vars from all multiple forms. IDs are unique.
raw<-comb_fm_list[[1]]
for (comb_i in 2:length(comb_fm_list)){raw<-dplyr::left_join(raw,comb_fm_list[[comb_i]],by=comm_var)}
if(!nrow(raw)==nrow(new_comm_col)){stop(message(paste("Some thing is wrong with",formname,"when combining forms. Check codes.")))}
}else{#STEP1.3 get 'raw'-- necessary vars. IDs can be duplicated
raw <- read.csv(paste0(rootdir,fm_dir), stringsAsFactors = F) #grab form
raw<-raw[,which(colnames(raw)%in%c(acvar_nonch,acvar_chk))] #remove unncessary var
}
#STEP1.4 save chkbx vars to 'raw_nonch' and non-chkbx varsto df: 'raw_chk'
raw_nonch<-raw[,which(colnames(raw)%in%acvar_nonch)] #keep only non-checkbx variables
if(!is.null(acvar_chk)){
raw_chk<-raw[1]
raw_chk<-cbind(raw_chk,raw[,which(colnames(raw)%in%acvar_chk)])
raw_chk$matching_id<-1:nrow(raw) #give checkbox df a matching id
}
#STEP1.5 remove calculated fields
cal_var<-subset(vm,fix_what=='calculated_field')$access_var
if(length(cal_var)>0){raw_nonch<-raw_nonch[,-which(colnames(raw_nonch)%in%cal_var)]}
#STEP1.6 get 'raw_nonch' for non-chckbx vars: rename AC var using RC varnames
VMAP<-subset(vm,select=c(access_var,redcap_var),is.checkbox=='FALSE')
##STEP special: for IPDE, keep some original access variable names to fix "check_equal", "multi_field", "special_2" issues later
if(formname=="IPDE"){for (tempvar in c("APDa5","APDa6","BPD3","BPD4","SPD5","STPD8")){VMAP[which(VMAP$access_var==tempvar),2]<-tempvar}}
colnames(raw_nonch)<-plyr::mapvalues(colnames(raw_nonch),from = VMAP$access_var, to = VMAP$redcap_var)
if(any(duplicated(colnames(raw_nonch)))){stop(message(paste0("Stop: ",formname,": Duplicated colnames.")))}
if(!is.null(acvar_chk)){raw_nonch$matching_id<-1:nrow(raw)} #get non-check df a matching id if needed
vm<<-vm
formname<<-formname
acvar_chk<<-acvar_chk
rawdata<<-raw
deleted_rows<<-deleted_rows
if(!is.null(acvar_chk)){raw_chk<<-raw_chk}
raw_nonch<<-raw_nonch
log_replace<<-log_replace
log_comb_fm<<-log_comb_fm
message(paste0(formname,": STEP1 done."))
}
} # remove this
|
190c742970d3f9da48e246593cba936b066ef9ec
|
0836236c143346a53bbc505f0f13870fdb7bd393
|
/pollutantmean.R
|
270d6b7d66c2086b829a01196b0fc364cce53212
|
[] |
no_license
|
bethegeek/Hello_world
|
034d5791bb02611930bdd766814b51df72573922
|
b8c3b4a501acfb84d02bfbacf503faebb67bdd56
|
refs/heads/master
| 2021-01-10T14:06:41.584513
| 2016-02-08T10:01:03
| 2016-02-08T10:01:03
| 51,280,465
| 0
| 0
| null | 2016-02-08T05:25:25
| 2016-02-08T05:14:27
| null |
UTF-8
|
R
| false
| false
| 243
|
r
|
pollutantmean.R
|
pollutantmean <- function (directory, pollutant, id = 1:332){
my_files <- list.files(directory, full.names = TRUE)
dat <- data.frame()
for (i in id){
dat <- rbind(dat, read.csv(my_files[i]))
}
mean(dat[,pollutant], na.rm=TRUE)
}
|
69da7a7957477959920d4006d2ad61c6f27bd3dc
|
b8b3443e3b7021e9ac458bc12166f3e6f470843d
|
/man/attribute_filter.Rd
|
9b6a2a321b020a945ebf690d57e0e2cd3fc42932
|
[
"MIT"
] |
permissive
|
taylorpourtaheri/nr
|
e745a5734ca244e642ef089d9dfd20b957f00852
|
5c2710c197533ecf8b439d58d3d317bc203ac990
|
refs/heads/main
| 2023-07-14T04:53:48.773417
| 2021-08-11T22:15:55
| 2021-08-11T22:15:55
| 386,658,478
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 593
|
rd
|
attribute_filter.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/attribute_filter.R
\name{attribute_filter}
\alias{attribute_filter}
\title{Return subgraph where attributes match conditions}
\usage{
attribute_filter(graph, attr_expression)
}
\arguments{
\item{graph}{Graph of class '\code{igraph}'}
\item{attr_expression}{A logical expression defined in terms of the attribute names of \code{graph}.
only vertices where the expression evaluates to \code{TRUE} are kept.}
}
\description{
Use `attribute_filter()` to find cases where conditions are true given vertex attributes.
}
|
474e556d461703d6d3004446f7905850ca10aca7
|
4041a4778ca91606294a9a1c879a921606ac597b
|
/R/functions/dms_to_decimal.R
|
b538c8b15a1aa5468a527212f4c810430576d2bb
|
[] |
no_license
|
jeremieboudreault/flow_data_cehq
|
83c2dff3d6d6e67f8f872c8e5f2b2f6e69e3008b
|
3ef172089f2893635e7f1d2b8ab0726e971ff797
|
refs/heads/master
| 2023-08-25T11:00:13.777002
| 2021-11-02T14:32:08
| 2021-11-02T14:32:08
| 360,889,788
| 1
| 0
| null | 2021-05-01T13:43:10
| 2021-04-23T13:16:01
|
R
|
UTF-8
|
R
| false
| false
| 464
|
r
|
dms_to_decimal.R
|
# dms_to_decimal.R
#' @author Jeremie Boudreault.
#'
#' @export
dms_to_decimal <- function(dms) {
# Split DMS string to c(D, M, S)
dms_split <- as.numeric(strsplit(dms, split = c("º |\' |\""))[[1L]][1:3])
# Apply the minus symbol to all terms.
if (dms_split[1L] < 0L) {
dms_split[2L] <- dms_split[2L] * -1L
dms_split[3L] <- dms_split[3L] * -1L
}
# Convert to decimals.
return(sum(dms_split / c(1L, 60L, 3600L)))
}
|
10ca846912bea292b70556e3b910798348d96e1f
|
411c0a855450e1e17445bdc73ab48144512b4ee4
|
/tests/testthat/test_rescale.R
|
963590d3ac8d6e86ddde8bf57ccd4d1b7996519e
|
[] |
no_license
|
Gootjes/likerrt
|
e71c7893345a871011d6834122090fdab3c543bc
|
e294617d06320115ed3bc845f5e2bd9476ce7100
|
refs/heads/master
| 2020-05-24T22:35:25.348798
| 2020-03-29T15:51:10
| 2020-03-29T15:51:10
| 187,499,444
| 0
| 0
| null | 2020-03-29T15:26:24
| 2019-05-19T16:11:22
|
R
|
UTF-8
|
R
| false
| false
| 1,678
|
r
|
test_rescale.R
|
context("rescale")
library(tidyverse)
library(rlang)
library(haven)
n1 <- 100
values1 <- 1:10
gen <- function(values, n) sample(values, n, replace=TRUE, prob=rbeta(length(values), 1, 1))
d1 <- data.frame(A = gen(values1, n1), B = gen(values1, n1), C = gen(values1, n1)) %>%
as_likert(A, B, C, .labels = c("lowest" = 1, 2, 3, 4, 5, 6, 7, 8, 9, "highest"=10))
i_na <- sort(sample(1:nrow(d1), size = nrow(d1)/4, replace = FALSE))
d2 <- d1
d2$A[i_na] <- NA
a <- d1 %>% likert_rescale(A, B, C, .min = 0, .max = 1) %>% zap_labels()
b <- d1 %>% mutate_all(~ (. - 1)/9) %>% zap_labels()
testthat::expect_equal(a, b)
a <- d1 %>% likert_rescale(A, B, C, .min = 1, .max = 0) %>% zap_labels()
b <- d1 %>% mutate_all(~ 1-((. - 1)/9)) %>% zap_labels()
testthat::expect_equal(a, b)
a <- d1 %>% likert_rescale(A, .min = 1, .max = -1, .suffix = "rec") %>% zap_labels()
b <- d1 %>% mutate(Arec = 1+(((A - 1)/9)*-1)*2) %>% zap_labels()
testthat::expect_equal(a, b)
a <- d1 %>% likert_rescale(A, B, C, .min = 0, .max = 1)
a_labels <- a %>% get_labels()
testthat::expect_equal(a_labels$A %>% unclass() %>% as.vector(), seq(from = 0, to = 1, length.out = 10))
testthat::expect_equal(a %>% as_factor(), d1 %>% as_factor()) # TODO: Is this desired?
a <- d2 %>% likert_rescale(A, B, C, .min = 1, .max = -1) %>% zap_labels()
b <- d2 %>% mutate_all(~ 1+(((. - 1)/9)*-1)*2) %>% zap_labels()
testthat::expect_equal(a, b)
a <- d2 %>% likert_rescale(A, .min = 1, .max = -1) %>% likert_scale(A, B, .name = "C", .assumptions = c('none'))
b <- d2 %>% mutate(A = 1+(((A - 1)/9)*-1)*2) %>% likert_scale(A, B, .name = "C")
testthat::expect_equal(a %>% zap_labels(), b %>% zap_labels())
|
8cf3ecda117c083e19031a395b34134dfb80db41
|
43468850099f4b805f44a726db2c402ea0891f07
|
/findTradedBHCs v1.0.R
|
dc23d9654229a59c0d33ebe92e5f3e1d754207da
|
[] |
no_license
|
jmalbornoz/Bank-Names-Reconciliation
|
3a6ca27b23e456250043649d398213150e199f62
|
7a90ff942c97d795d6e74d9b37e65ad38e7236e1
|
refs/heads/master
| 2021-01-10T09:50:52.340552
| 2016-02-01T17:44:20
| 2016-02-01T17:44:20
| 50,854,808
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,086
|
r
|
findTradedBHCs v1.0.R
|
# Find publicly traded BHCs in FDICs data
#
# JM Albornoz
# January 2016
#
# clear everything
rm(list=ls(all=TRUE))
# invokes libraries
library(dplyr)
library(stringdist)
# invokes utility functions
source("utility1.R")
############################################################
############################################################
# reads list of publicly traded BHCs
theData <- read.csv("BHCsAndTickers.csv")
theDataC <- mutate(theData, sig = sapply(theData$names, clean1))
# read FDIC's list of BHCs
BHCsList <- read.csv("ActiveNonMutual_short.csv", stringsAsFactors = FALSE)
BHCsList <- unique(BHCsList)
names(BHCsList) <- "names"
# pre-processes list of BHCs
BHCsListC <- mutate(BHCsList, sig = sapply(BHCsList$names, clean1)) # 4073 records
# eliminates duplicated BHCs
BHCsListC <- filter(BHCsListC, !duplicated(BHCsListC$sig))
# saves list of BHCs
write.table(BHCsListC, "BHC_List.csv", row.names = FALSE, col.names = FALSE, sep = ",")
# finds traded BHCs
tradedBHCs <- inner_join(BHCsListC, theDataC, by = "sig")
# BHCs whose names are not recognised
notRecognised <- anti_join(theDataC, tradedBHCs, by = "sig")
# find partial matches between the list of BHCs and list of not recognised BHCs
notRecognised <- mutate(notRecognised, parMatch = as.character(sapply(notRecognised$sig, ClosestMatch2, BHCsListC$sig)))
partials <- filter(notRecognised, !is.na(parMatch))
# finds corresponding BHCs
partialBHCs <- inner_join(theDataC, partials, by = "tickers")
# assembles resulting list of traded BHCs
tradedBHCs <- select(tradedBHCs, tickers)
partialBHCs <- select(partialBHCs, tickers)
tradedBHCs <- rbind(tradedBHCs, partialBHCs)
# list of traded BHCs
listOfTradedBHCs <- inner_join(tradedBHCs, theData, by = "tickers")
# saves list of traded BHCs
write.table(listOfTradedBHCs, "tradedBHCs.csv", row.names = FALSE, col.names = FALSE, sep = ",")
# the ones that did not match
notMatching <- filter(theData, !theData$tickers %in% listOfTradedBHCs$tickers)
write.table(notMatching, "notListed.csv", row.names = FALSE, col.names = FALSE, sep = ",")
|
9d3d7e6f4113ee0f43942a067bf1fa4d5477ef80
|
9b52eb78cc08d42310da9b9d3f00d239a9be8b20
|
/Solutions_for_Tasks/Task_from_Excel_Table_One/Code_I_Used_for_Calculations.r
|
45c2d1e965df92d21f0c3835f401acf36c6d6fff
|
[] |
no_license
|
richardrex/Mattoni_Data_Analyzation
|
5007eb7e197726851cf6b29d90a184408c858e31
|
adddea63032267c7934e21eef9c7d2b0206b9f07
|
refs/heads/main
| 2023-09-04T09:06:10.164400
| 2021-10-22T14:56:25
| 2021-10-22T14:56:25
| 412,146,900
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,379
|
r
|
Code_I_Used_for_Calculations.r
|
getwd()
setwd("F:/folder")
install.packages("readxl")
library(readxl)
library(sqldf)
my_data = read_excel("task1_data.xlsx")
#1)
V1_fuzz = sqldf('SELECT * from my_data WHERE ITEM = "FUZETEA-GR.TEA LIME&MINT 1.5L PB" AND MARKET = "CZ Hypermarkets"' )
Answer1 = V1_fuzz[3,9]
### ANSWER : 90.51300
#2. Jaka byla prumerna cena produktu AQUILA-PRVNI VODA KOJENECKA 1.5L PB NS K v CZ Hypermarkets letech 2014, 2015, 2016?
# choose AQUILA-PRVNI VODA KOJENECKA 1.5L PB NS K in CZ Hyper and calculate avg price
AVG_AQ = sqldf('SELECT * from my_data WHERE ITEM = "AQUILA-PRVNI VODA KOJENECKA 1.5L PB NS K" AND MARKET = "CZ Hypermarkets"' )
Total = AVG_AQ[4,]
Answer2_2014 = AVG_AQ[4,9]
Answer2_2015 = AVG_AQ[4,10]
Answer2_2016 = AVG_AQ[4,11]
#3. Kolik se prodalo v CZK (Value in 1 000 000 CZK) produktu 7UP-1L PB na CZ Petrol Stations v roce 2015?
CZK_7UP = sqldf('SELECT * FROM my_data WHERE ITEM = "7UP-1L PB" AND MARKET = "CZ Petrol Stations"')
Answer3 = CZK_7UP[2,10]
# 4. Kolik se prodalo kusu (Units in 1000 PCS) 0.5L PET lahvi ve WATER kategorii behem roku 2014?
names(my_data)[names(my_data) == 'PACKAGE TYPE'] <- 'PACKAGE_TYPE'
PET_2014 = sqldf('SELECT * FROM my_data WHERE CATEGORY = "TOTAL WATER" AND PACKAGE_TYPE = "BOTTLE PET" AND SIZE = "0.5L" AND FACT = "Units (in 1000 PCS)"')
Answer4 = sum(PET_2014[, "2014.0"]) ### In 1000 PCS
|
7ffb0b6e85e6e1008887344e6b5cbb5f2b1cad8f
|
383aca5c78267160efa1d69f409edd6fac4f90d4
|
/R/cm.clopper.pearson.ci.R
|
3904bccb3754179dd2c583718456daf989414e1f
|
[] |
no_license
|
cran/GenBinomApps
|
e6b45f777136c21212c08fd8fb5e4926b8a4245f
|
d6fa7ae17c5f99fa8f2d0b8858db8893e2aa445c
|
refs/heads/master
| 2022-07-07T04:14:17.488479
| 2022-06-21T12:30:02
| 2022-06-21T12:30:02
| 17,679,556
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,695
|
r
|
cm.clopper.pearson.ci.R
|
cm.clopper.pearson.ci <-
function(n,size,cm.effect,alpha=0.1,
CI="upper",uniroot.lower=0,uniroot.upper=1,uniroot.maxiter=100000,uniroot.tol=1e-10){
k=sum(size)
l<-round(size)
if (any(is.na(size) | (size < 0)) || max(abs(size - l)) > 1e-07)
stop("'size' must be nonnegative and integer")
m<-round(n)
if (is.na(n) || n < k || max(abs(n - m)) > 1e-07)
stop("'n' must be nonnegative and integer >= k")
if(alpha<0 || alpha>1) {
stop("'alpha' must be a number between 0 and 1")}
K<-c(0:k)
xi<-dgbinom(K,size,cm.effect)
xi<-rev(xi)
if (CI=="upper")
{ll<-0
ul<-uniroot(function(pii) xi%*%pbeta(pii,K+1,n-K)-(1-alpha),lower=uniroot.lower,upper=uniroot.upper,tol=uniroot.tol,maxiter=uniroot.maxiter)$root
}
else if (CI=="lower")
{ul<-1
if (xi[1]>=(1-alpha)){
ll<-0 }
else{
K <- c(1:k)
ll <- uniroot(function(pii) xi %*% c(pbeta(pii,1e-100,1+n), pbeta(pii, K, 1 +
n - K)) - alpha, lower = uniroot.lower, upper = uniroot.upper,
tol = uniroot.tol, maxiter = uniroot.maxiter)$root
}
}
else if (CI=="two.sided")
{
if (xi[1]>=(1-alpha/2)){
ll<-0 }
else{
Kl <- c(1:k)
ll <- uniroot(function(pii) xi %*% c(pbeta(pii,1e-100,1+n), pbeta(pii, Kl,
1 + n - Kl)) - alpha/2, lower = uniroot.lower, upper = uniroot.upper,
tol = uniroot.tol, maxiter = uniroot.maxiter)$root
}
ul<-uniroot(function(pii) xi%*%pbeta(pii,K+1,n-K)-(1-alpha/2),lower=uniroot.lower,upper=uniroot.upper,tol=uniroot.tol,maxiter=uniroot.maxiter)$root
}
else stop("undefined CI detected")
data.frame(Confidence.Interval=CI,Lower.limit=ll,Upper.limit=ul,alpha=alpha,row.names="")
}
|
fb30e3b8ef8bdd52b82215a8f30fb02532786265
|
f2dc702fa270bf83e1b3263e93517b3196e73f81
|
/R-Microvan factor and cluster analysis .R
|
d8a7b8dad2e34962a6834b5a91429e13a1e0103b
|
[] |
no_license
|
yiwenjulie/data-analysis
|
bdecbc2741dcd250bc622d279985fa04a3e84d5a
|
70d318f6c1d775bd548b9bc0bf324975b8e5b50d
|
refs/heads/master
| 2023-07-19T04:57:02.409271
| 2021-09-13T13:25:41
| 2021-09-13T13:25:41
| 405,952,249
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,663
|
r
|
R-Microvan factor and cluster analysis .R
|
library(foreign)
library(haven)
library(ggplot2)
# import data
data <- read.dta("microvan.dta")
str(data)
summary(data)
# exploratory analysis
variables <- colnames(data[,3:32])
p = ggplot(data)
p1 = p+geom_bar(aes_string(x=variables[1]))
p2 = p+geom_bar(aes_string(x=variables[2]))
p3 = p+geom_bar(aes_string(x=variables[3]))
p4 = p+geom_bar(aes_string(x=variables[4]))
p5 = p+geom_bar(aes_string(x=variables[5]))
p6 = p+geom_bar(aes_string(x=variables[6]))
p7 = p+geom_bar(aes_string(x=variables[7]))
p8 = p+geom_bar(aes_string(x=variables[8]))
p9 = p+geom_bar(aes_string(x=variables[9]))
p10 = p+geom_bar(aes_string(x=variables[10]))
p11 = p+geom_bar(aes_string(x=variables[11]))
p12 = p+geom_bar(aes_string(x=variables[12]))
p13 = p+geom_bar(aes_string(x=variables[13]))
p14 = p+geom_bar(aes_string(x=variables[14]))
p15 = p+geom_bar(aes_string(x=variables[15]))
p16 = p+geom_bar(aes_string(x=variables[16]))
p17 = p+geom_bar(aes_string(x=variables[17]))
p18 = p+geom_bar(aes_string(x=variables[18]))
p19 = p+geom_bar(aes_string(x=variables[19]))
p20 = p+geom_bar(aes_string(x=variables[20]))
p21 = p+geom_bar(aes_string(x=variables[21]))
p22 = p+geom_bar(aes_string(x=variables[22]))
p23 = p+geom_bar(aes_string(x=variables[23]))
p24 = p+geom_bar(aes_string(x=variables[24]))
p25 = p+geom_bar(aes_string(x=variables[25]))
p26 = p+geom_bar(aes_string(x=variables[26]))
p27 = p+geom_bar(aes_string(x=variables[27]))
p28 = p+geom_bar(aes_string(x=variables[28]))
p29 = p+geom_bar(aes_string(x=variables[29]))
p30 = p+geom_bar(aes_string(x=variables[30]))
library(gridExtra)
grid.arrange(p1,p2,p3,p4,p5,p6)
grid.arrange(p7,p8,p9,p10,p11,p12)
grid.arrange(p13,p14,p15,p16,p17,p18)
grid.arrange(p19,p20,p21,p22,p23,p24)
grid.arrange(p25,p26,p27,p28,p29,p30)
#create regression against 30 explanatory variables
z.full <- lm(mvliking ~ kidtrans+miniboxy+lthrbetr
+secbiggr+safeimpt+buyhghnd
+pricqual+prmsound+perfimpt
+tkvacatn+noparkrm+homlrgst
+envrminr+needbetw+suvcmpct
+next2str+carefmny+shdcarpl
+imprtapp+lk4whldr+kidsbulk
+wntguzlr+nordtrps+stylclth
+strngwrn+passnimp+twoincom
+nohummer+aftrschl+accesfun
, data=data)
summary(z.full)
##################
# factor analysis
library(REdaS)
# Bartlett test of sphericity
# chi square test
# H0: there is no significant correlation between variables
bart_spher(data[,3:32])
# Kaiser-Meyer-Olkin Measure of sampling adequacy
# wheter samples are adequate or not
# looking for critical value > 0.6
KMOS(data[,3:32])
# calculate eigen values
ev <- eigen(cor(data[,3:32]))$values
e <- data.frame(Eigenvalue = ev, PropOfVar = ev / length(ev), CumPropOfVar = cumsum(ev / length(ev)))
round(e, 4)
# Draw a scree plot
p <- ggplot()
p <- p + geom_line(aes(x = 1:length(ev), y = ev))
p <- p + geom_point(aes(x = 1:length(ev), y = ev))
p <- p + geom_hline(yintercept = 1, colour = "red")
p <- p + labs(x = "Number", y = "Eigen values", title = "Scree Plot of Eigen values")
p <- p + scale_x_continuous(breaks = 1:length(ev), minor_breaks = NULL)
p <- p + theme_bw()
p
# Select number of factors
n <- 5
library(psych)
# Do factor analysis using principal component
pc <- principal(data[,3:32], nfactors = n, rotate="varimax")
# Create a factor loadings table; Sort based on uniqueness
fl <- cbind.data.frame(pc$loadings[,], Uniqueness = pc$uniquenesses)
round(fl[order(pc$uniquenesses),], 4)
# Check how the factors predict the overall preference ratings
factor_scores <- cbind(data[,1:2],pc$scores)
head(factor_scores)
# regression using factor scores
z.fscore <- lm(mvliking ~ RC1 + RC2 + RC3 + RC4 + RC5, data=factor_scores)
summary(z.fscore)
###############
# Hierarchical Clustering
# Calculate Euclidian distances between rows, considering factors 1 to 5
d <- dist(factor_scores[,3:7])
# Apply Ward's linkage clustering
h <- hclust(d, method = "ward.D2")
# view dendogram
plot(h, xlab = "Respondent")
######################
# k-means clustering
# First, standardize the input variables (z-scores)
z <- scale(factor_scores[,3:7], center = TRUE, scale = TRUE)
# Since the k-means algorithm starts with a random set of centers, setting the seed helps ensure the results are reproducible
set.seed(7)
# Cluster based on factor scores
#k <- kmeans(factor_scores[,3:7], centers = 4)
k <- kmeans(z,centers=3)
# Cluster sizes
k$size
# Cluster means
k$centers
# add cluster back into dataset
factor_scores$cluster <- k$cluster
data$cluster <- k$cluster
#####################
# Regression by Segments
z.clust.reg <- lm(mvliking ~ as.factor(cluster), data=factor_scores)
summary(z.clust.reg)
# Plot the score distribution by segments
# Reshape from wide to long format (required for use of ggplot2)
plotdata <- reshape(factor_scores, varying = c("RC1", "RC2", "RC3", "RC4", "RC5"), v.names = "score", timevar = "attribute", times = c("Price Premium for Quality", "Medium Car Size", "Kid's Needs for Vehicle", "Safety", "Environmental Impact"), direction = "long")
head(plotdata)
# Build plot
p <- ggplot(data = plotdata)
p <- p + geom_density(aes(x = score, colour = as.factor(cluster), fill = as.factor(cluster)), size = 1, alpha = 0.3)
p <- p + facet_wrap(~ attribute, ncol = 3)
p <- p + labs(title = "Cluster histogram diagnostics")
#p <- p + xlim(c(0,8))
p <- p + theme_bw()
p
######################
# Cross Tab
library(gmodels)
CrossTable(x = data$cluster, y = data$mvliking, expected = TRUE, prop.r = FALSE, prop.c = FALSE, prop.t = FALSE)
######################
# Demographic Profile
# Reshape data into long form
plotdata2 <- reshape(data[,33:40],varying = c("age", "income", "miles", "numkids", "educ","recycle"), v.names = "value", timevar = "demographic", times = c("Age", "Income", "Miles", "Number of Kids", "Education","Recycle"), direction = "long")
head(plotdata2)
# plot demographic distribution
p <- ggplot(data = plotdata2)
p <- p + geom_density(aes(x = value, colour = as.factor(cluster), fill = as.factor(cluster)), size = 1, alpha = 0.3)
p <- p + facet_wrap(~ demographic, ncol = 3,scales="free")
p <- p + labs(title = "Cluster Demographics")
p <- p + theme_bw()
p
#separate demographic data into each clusters
cluster1.demo <- data[data$cluster==1,c("age","income","miles","numkids","female","educ","recycle","cluster")]
cluster2.demo <- data[data$cluster==2,c("age","income","miles","numkids","female","educ","recycle","cluster")]
cluster3.demo <- data[data$cluster==3,c("age","income","miles","numkids","female","educ","recycle","cluster")]
#Summary for each cluster demographic
summary(cluster1.demo)
summary(cluster2.demo)
summary(cluster3.demo)
|
e14edc1f624bb244852575a6bbe6aeaa3c980c4e
|
8f67330a4700bc888d13dd92c62220e20e6b6828
|
/tests/testthat/test_normalization1.R
|
c6cd3625b5f6620d0f6096026f2ba4d34cd60677
|
[] |
no_license
|
cran/clusterSim
|
cfcc584e368fa9f6d1d86887b0f61cc2f3676b32
|
54764dbd65330165e71fc1af2fadf75942915769
|
refs/heads/master
| 2023-06-25T15:51:42.061284
| 2023-06-10T17:30:02
| 2023-06-10T17:30:02
| 17,695,119
| 2
| 6
| null | 2015-12-05T19:09:43
| 2014-03-13T04:16:30
|
R
|
UTF-8
|
R
| false
| false
| 475
|
r
|
test_normalization1.R
|
context("normalization1")
test_that("normalization1", {
a<-matrix(runif(10,1,10),10,1)
b<-as.vector(a[,1])
for(i in 0:13){
t=paste("n",i,sep="")
an<-data.Normalization(a,type=t)
bn<-data.Normalization(b,type=t)
expect_equal(as.vector(an[,1]),as.vector(bn))
}
for(i in c(3,5,6,9,12)){
t=paste("n",i,"a",sep="")
an<-data.Normalization(a,type=t)
bn<-data.Normalization(b,type=t)
expect_equal(as.vector(an[,1]),as.vector(bn))
}
})
|
ddd133eb573a189edcd15afc6c08eb45957c1696
|
3cb5ff85950ca7fbe3414684853c3b2e29f1fd76
|
/handy/eda.R
|
a54d0e67534ffbadb32c67e17e3977c118900315
|
[] |
no_license
|
wal/R-Code
|
007fba7b25e9b1a6d30e9a0bc9ce4427141eb71f
|
49baf272e76367e7561d7725c7e1c52f817c9560
|
refs/heads/master
| 2021-07-04T23:13:03.395752
| 2020-09-30T10:02:31
| 2020-09-30T10:02:31
| 19,870,363
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,502
|
r
|
eda.R
|
# EDA : To find patterns, reveal, structure, and make tentative model assessments
## Variables
# What are the variables, types, missing data, unique values
### Variables Table
create_variables_table <- function(data) {
join_all(list(
data %>% summarise_all(~ class(.)[[1]]) %>% gather(Name, class),
data %>% summarise_all(~ length(unique(.))) %>% gather(Name, 'Unique Values'),
data %>% summarise_all(~ sum(is.na(.))) %>% gather(Name, 'Missing Count'),
data %>% summarise_all(~ mean(is.na(.))) %>% gather(Name, 'Missing %')
), by='Name', type='left')
}
create_variables_table(data) %>% arrange(Name)
## Variation
# Visualise Distribution of variables
# Investigate Typical Values
# Investigate Unusual Values / Outliers
# Investigate Missing values
## Covariation
# Categorical v Continuous
# geom_freqpoly / geom_bar ..density..
# boxplots
# Categorical v Categorical
# geom_tile / geom_count
# Continuous v Continuous
# geom_point
# cut one into bins (cut_width) + boxplot
## Patterns
# Is there a pattern / relationship ?
# How strong ?
# What direction ? - describe it ?
# Could it be due to random chance ?
# Does it change when sub-groups are examined ?
# Simple count of values
table(train$Survived) # count of survivors
prop.table(table(train$Survived)) # proportion of survivors
# Proportions using two variables - total or rowwise
prop.table(table(train$Sex, train$Survived)) # Totals for all samples
prop.table(table(train$Sex, train$Survived), 1) # Off the rows
# Counts & Proportions for groups
train %>%
group_by(Survived, Child, Sex) %>%
summarise(count = n()) %>%
mutate(proportion = count / sum(count))
# Number of rows missing data
sum(complete.cases(diamonds)) / sum(!complete.cases(diamonds))
# % Missing data by column
train %>% summarise_all(function(x) mean(is.na(x) * 100))
# Percentages of missing data by column
test_data %>%
summarise_all(function(x) round(mean(is.na(x) * 100),1)) %>%
select_if(function(x) sum(x) > 1) %>%
t() %>%
as.tibble(rownames = "Variable") %>%
rename(Missing=V1) %>%
arrange(desc(Missing))
# Gather rows with missing data
missing_row <- train[!complete.cases(train),]
# Simple histogram
diamonds %>% count(cut)
# continuous variable histogram (cut into bins)
diamonds %>% count(cut_width(carat, 0.5)) # Bin of certain size
diamonds %>% count(cut_number(carat, 5)) # 5 equal bins
# Compare two categorical variables - geom_count (size of count)
ggplot(data = diamonds) + geom_count(mapping = aes(x = cut, y = color))
# Data Explorer
install.packages('DataExplorer')
library(DataExplorer)
## Plot Missing Values names(airquality)
plot_missing(airquality)
plot_histogram(airquality) # All Variables
plot_density(airquality) # All Variables
plot_correlation(airquality)
plot_bar(diamonds)
create_report(airquality) # Generate report
# Keep/Discard numeric columns
numeric_cols <- iowa_data %>% purrr::keep(is.numeric)
non_numeric_cols <- iowa_data %>% purrr::discard(is.numeric)
# GGally
library(GGally)
ggpairs(diamonds)
ggscatmat(diamonds)
# Normally Distributed
ggplot(test_data, aes(lSalePrice)) +
geom_histogram(bins = 100) +
geom_freqpoly(bins = 50)
ggplot(test_data, aes(sample = SalePrice)) +
geom_qq() +
geom_qq_line()
# Correlation between all variables in handy df
library(reshape2)
library(reshape2)
melt(cor(test_data.numeric_variables)) %>%
filter(Var1 != Var2, (Var1 == "SalePrice" | Var2 == "SalePrice"), value > 0.5) %>%
arrange(desc(value))
|
dc678d64a7e9649b48a66c08d55737fbd41430b0
|
6fbe95a40778339a65d0500e3f51269d25f216bf
|
/man/maxlevels.Rd
|
857e465abfa768558600c9a8070651081b374603
|
[] |
no_license
|
zeta1999/OneR
|
82e5d2fe5b63c2439b3c798dea97cb8d40f8bba4
|
72dd03301b552d928ddc6bccf3d246c01918f17d
|
refs/heads/master
| 2021-09-15T14:41:38.819687
| 2018-06-04T17:09:36
| 2018-06-04T17:09:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,237
|
rd
|
maxlevels.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/OneR.R
\name{maxlevels}
\alias{maxlevels}
\title{Remove factors with too many levels}
\usage{
maxlevels(data, maxlevels = 20, na.omit = TRUE)
}
\arguments{
\item{data}{data frame which contains the data.}
\item{maxlevels}{number of maximum factor levels.}
\item{na.omit}{logical value whether missing values should be treated as a level, defaults to omit missing values before counting.}
}
\value{
A data frame.
}
\description{
Removes all columns of a data frame where a factor (or character string) has more than a maximum number of levels.
}
\details{
Often categories that have very many levels are not useful in modelling OneR rules because they result in too many rules and tend to overfit.
Examples are IDs or names.
Character strings are treated as factors although they keep their datatype. Numeric data is left untouched.
If data contains unused factor levels (e.g. due to subsetting) these are ignored and a warning is given.
}
\examples{
df <- data.frame(numeric = c(1:26), alphabet = letters)
str(df)
str(maxlevels(df))
}
\references{
\url{https://github.com/vonjd/OneR}
}
\seealso{
\code{\link{OneR}}
}
\author{
Holger von Jouanne-Diedrich
}
|
62136f662eaf3137ae1f943516bfc7c729e8f792
|
8ee4947786144359eb66ad9f8718c0e673ba4166
|
/man/check_schema_for_duplicates.Rd
|
b561a4cec51c3fd7681ce265907bcb30a8315f22
|
[
"MIT"
] |
permissive
|
antonmalko/ettools
|
263e4ef67202b9abf7aea5389ede2a52b5f73a38
|
fe57227850faecff4afbc081e95077972403cf71
|
refs/heads/master
| 2021-09-09T21:14:53.376409
| 2018-03-19T18:35:36
| 2018-03-19T18:35:36
| 113,387,855
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 945
|
rd
|
check_schema_for_duplicates.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/naming_functions.R
\name{check_schema_for_duplicates}
\alias{check_schema_for_duplicates}
\title{A validation function for schemas. Checks whether names of the list element
contain duplicates, throws an error if they do. A wrapper around
\code{check_for_duplicates}.}
\usage{
check_schema_for_duplicates(schema, check.values.for.dups = FALSE)
}
\arguments{
\item{schema}{List with a schema to be checked for duplicates}
\item{check.values.for.dups}{logical. If FALSE, only names are checked
(usuful for checking values schemas - values can be duplicated);
if TRUE, names and values of the list elements are checked
(useful for checking tagging schemas - tags should be unique)}
}
\description{
A validation function for schemas. Checks whether names of the list element
contain duplicates, throws an error if they do. A wrapper around
\code{check_for_duplicates}.
}
|
7b6a5723d9ae72560dcf1a48120b18a9044f959f
|
fa60f8262586afbf25096cfb954e5a9d391addf7
|
/R_Machine_Learning/hw_Emp_SVM_Tune_DecTree_RandFor_.R
|
fee5d94f1447fec35c03c07b01bcfa800593649e
|
[] |
no_license
|
pprasad14/Data_Science_with_R
|
ce5a2526dad5f6fa2c1fdff9f97c71d2655b2570
|
3b61e54b7b4b0c6a6ed0a5cc8243519481bb11b9
|
refs/heads/master
| 2020-05-05T08:56:39.708519
| 2019-04-06T20:42:11
| 2019-04-06T20:42:11
| 179,884,402
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,540
|
r
|
hw_Emp_SVM_Tune_DecTree_RandFor_.R
|
# Emp dataset : Decision Tree, Random Forest using SVM and tuning
dataset = read.csv("Emp.csv")
#select around 3k observations, since 32K observations is computationally expensive
library(caTools)
set.seed(123)
split = sample.split(dataset$Emp_Sal, 0.90)
dataset = subset(dataset, split == F)
#changin Emp_Sal to 'High' or 'Low'
dataset$Emp_Sal = factor(dataset$Emp_Sal, labels = c("Low","High"))
# spit data using caret package
#library(caret)
#partition = createDataPartition(dataset$y, times = 1, p = 0.80)
#length(partition$Resample1) # partition$Resample contains the training set
#split using caTools
library(caTools)
split = sample.split(dataset$Emp_Sal, 0.80)
training_set = subset(dataset, split == T)
test_set = subset(dataset, split == F)
# Fit model
library(e1071)
classifier = svm(Emp_Sal ~ . , data = training_set, kernel = "radial")
classifier #default radial
#Predictions
pred = predict(classifier, newdata = test_set)
cm = table(test_set$Emp_Sal, pred)
cm
# Mis-classification rate
1 - sum(diag(cm))/ sum(cm) # around 15.5% mis-classification
#Tuning
tune = tune(svm, Emp_Sal ~ ., data = training_set,
ranges = list(gamma = seq(0,1,0.25), cost = (2^(3:7))))
tune # best is 0.17 with gamma: 0.25 and cost:8
#plot tuned model
plot(tune)
summary(tune) # gives all combinations of cost and gamma models, total: 5*5=25
attributes(tune)
#Best Model
mymodel = tune$best.model # our new model
summary(mymodel)
#Predictions
pred = predict(mymodel, data = training_set)
#should take test_set, but getting error
# CM
cm = table(training_set$Emp_Sal, pred)
#should take test_set, but getting error
#why is length of pred not equal to length of test_set$Emp_Sal??
cm
# Mis-classification rate
1 - sum(diag(cm))/ sum(cm) #mis-classification rate is 2.49 %
# tune$best.model$fitted
set.seed(123)
tune = tune(svm, Emp_Sal ~ ., data = training_set,
ranges = list(epsilon = seq(0,0.5,0.05), cost = (2^(3:7))))
tune #now best is 0.14 from 0.17 with epsilon:0 and cost:8, while using training_set for pred
#plot tuned model
plot(tune) # more dark, less error
summary(tune) # gives all combinations of cost and gamma models, total: 11*5=55
attributes(tune)
#Best Model
mymodel = tune$best.model # our new model
summary(mymodel)
#Predictions
pred = predict(mymodel, data = training_set[,-15])
# CM
cm = table(training_set$Emp_Sal, pred)
#using training_set instead of test_set bc getting error
#Error in table(test_set$y, pred) :
#all arguments must have the same length
cm
# Mis-classification rate
1 - sum(diag(cm))/ sum(cm) # mis-classification rate is 13.58 %
###############################
#fitting decision tree classification
#install.packages("rpart")
library(rpart)
set.seed(123)
classifier = rpart(formula = Emp_Sal ~ ., data = training_set)
# Plot tree
plot(classifier, margin = 0.1)
text(classifier)
# install rpart.plot
#install.packages("rpart.plot")
library(rpart.plot)
rpart.plot(classifier, type = 3, digits = 3, fallen.leaves = T,
cex = 0.6)
############################
#install.packages("randomForest")
library(randomForest)
classifier = randomForest(Emp_Sal ~ ., data = training_set)
classifier # no of variables tried at split is sqrt of no. of variables
#OOB is Out Of Bag error, or just error in simple
# Predictin test results
y_pred = predict(classifier, newdata = test_set[-15])
head(y_pred)
#CM
library(caret)
confusionMatrix(test_set[,15], y_pred) # accuracy of 82.49%
|
89652f170dcd9d7ef6f2d0ed81140b7da7616f06
|
42e359d703bdb6ddfac67cb2ec3dcf38d01bb494
|
/grids/NASIS/m_NASIS.R
|
e377f7b57a03c125402be211b8b821dcf6da5275
|
[] |
no_license
|
avijeet1132/SoilGrids250m
|
d27311960bc5c9959d4b6f28d53605f629f6290c
|
67603870af79ffe774a9344d84c442aa56d2e131
|
refs/heads/master
| 2020-04-06T04:36:17.046925
| 2016-04-29T06:35:51
| 2016-04-29T06:35:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,754
|
r
|
m_NASIS.R
|
## Fit models for GreatGroups based on NASIS points (ca 350,000)
## Code by Tom.Hengl@isric.org / points prepared by Travis Nauman (tnauman@usgs.gov)
setwd("/data/NASIS")
library(aqp)
library(plyr)
library(stringr)
library(dplyr)
library(sp)
library(devtools)
library(caret)
#devtools::install_github("imbs-hl/ranger/ranger-r-package/ranger", ref="forest_memory") ## version to deal with Memory problems
library(ranger)
library(nnet)
library(ROCR)
library(snowfall)
library(mda)
library(psych)
library(rgdal)
library(utils)
library(R.utils)
library(plotKML)
library(GSIF)
library(rgeos)
plotKML.env(convert="convert", show.env=FALSE)
gdalwarp = "/usr/local/bin/gdalwarp"
gdalbuildvrt = "/usr/local/bin/gdalbuildvrt"
system("/usr/local/bin/gdal-config --version")
source("/data/models/extract.equi7t3.R")
source("/data/models/saveRDS_functions.R")
source("/data/models/wrapper.predict_cs.R")
load("/data/models/equi7t3.rda")
load("/data/models/equi7t1.rda")
des <- read.csv("/data/models/SoilGrids250m_COVS250m.csv")
## Great groups
unzip("NASIS_L48_gg.zip")
NASISgg.pnts <- readOGR("nasispts16_gg_L48.shp", "nasispts16_gg_L48")
## 304,454 points
#summary(NASISgg.pnts$gg)
## Remove smaller classes:
xg = summary(NASISgg.pnts$gg, maxsum=length(levels(NASISgg.pnts$gg)))
selg.levs = attr(xg, "names")[xg > 5]
NASISgg.pnts$soiltype <- NASISgg.pnts$gg
NASISgg.pnts$soiltype[which(!NASISgg.pnts$gg %in% selg.levs)] <- NA
NASISgg.pnts$soiltype <- droplevels(NASISgg.pnts$soiltype)
str(summary(NASISgg.pnts$soiltype, maxsum=length(levels(NASISgg.pnts$soiltype))))
## 245 classes
## soil texture data:
unzip("nasispts16_pscs_L48.zip")
NASISpscs.pnts <- readOGR("nasispts16_pscs_L48.shp", "nasispts16_pscs_L48")
## 299,487 points
str(NASISpscs.pnts@data)
xs = summary(NASISpscs.pnts$pscs, maxsum=length(levels(NASISpscs.pnts$pscs)))
sel.levs = attr(xs, "names")[xs > 5]
NASISpscs.pnts$textype <- NASISpscs.pnts$pscs
NASISpscs.pnts$textype[which(!NASISpscs.pnts$pscs %in% sel.levs)] <- NA
NASISpscs.pnts$textype <- droplevels(NASISpscs.pnts$textype)
## OVERLAY AND FIT MODELS:
ov <- extract.equi7(x=NASISgg.pnts, y=des$WORLDGRIDS_CODE, equi7=equi7t3, path="/data/covs", cpus=48)
write.csv(ov, file="ov.NASISgg_SoilGrids250m.csv")
unlink("ov.NASISgg_SoilGrids250m.csv.gz")
gzip("ov.NASISgg_SoilGrids250m.csv")
save(ov, file="ov.NASISgg.rda")
summary(ov$soiltype)
#load("ov.NASISgg.rda")
ov2 <- extract.equi7(x=NASISpscs.pnts, y=des$WORLDGRIDS_CODE, equi7=equi7t3, path="/data/covs", cpus=48)
save(ov2, file="ov.NASISpscs.rda")
## ------------- MODEL FITTING -----------
pr.lst <- des$WORLDGRIDS_CODE
formulaString.USDA = as.formula(paste('soiltype ~ ', paste(pr.lst, collapse="+")))
#formulaString.USDA
ovA <- ov[complete.cases(ov[,all.vars(formulaString.USDA)]),]
formulaString.pscs = as.formula(paste('textype ~ ', paste(pr.lst, collapse="+")))
ovA2 <- ov2[complete.cases(ov2[,all.vars(formulaString.pscs)]),]
str(ovA2)
## Ranger package (https://github.com/imbs-hl/ranger)
mrfX_NASISgg <- ranger::ranger(formulaString.USDA, ovA, importance="impurity", write.forest=TRUE, probability=TRUE)
mrfX_NASISpscs <- ranger::ranger(formulaString.pscs, ovA2, importance="impurity", write.forest=TRUE, probability=TRUE)
cat("Results of model fitting 'randomForest':\n", file="NASIS_resultsFit.txt")
cat("\n", file="NASIS_resultsFit.txt", append=TRUE)
cat(paste("Variable: USDA Great Group"), file="NASIS_resultsFit.txt", append=TRUE)
cat("\n", file="NASIS_resultsFit.txt", append=TRUE)
sink(file="NASIS_resultsFit.txt", append=TRUE, type="output")
cat("\n Random forest model:", file="NASIS_resultsFit.txt", append=TRUE)
print(mrfX_NASISgg)
cat("\n Variable importance:\n", file="NASIS_resultsFit.txt", append=TRUE)
xl <- as.list(ranger::importance(mrfX_NASISgg))
print(t(data.frame(xl[order(unlist(xl), decreasing=TRUE)[1:15]])))
cat("\n", file="NASIS_resultsFit.txt", append=TRUE)
cat(paste("Variable: SPCS classes"), file="NASIS_resultsFit.txt", append=TRUE)
cat("\n", file="NASIS_resultsFit.txt", append=TRUE)
cat("\n Random forest model:", file="NASIS_resultsFit.txt", append=TRUE)
print(mrfX_NASISpscs)
cat("\n Variable importance:\n", file="NASIS_resultsFit.txt", append=TRUE)
xl <- as.list(ranger::importance(mrfX_NASISpscs))
print(t(data.frame(xl[order(unlist(xl), decreasing=TRUE)[1:15]])))
sink()
## save objects in parallel:
saveRDS.gz(mrfX_NASISgg, file="mrfX_NASISgg.rds")
saveRDS.gz(mrfX_NASISpscs, file="mrfX_NASISpscs.rds")
save.image()
## ------------- PREDICTIONS -----------
## Predict for the whole of USA:
library(maps)
library(maptools)
usa.m <- map('state', plot=FALSE, fill=TRUE)
IDs <- sapply(strsplit(usa.m$names, ":"), function(x) x[1])
prj = "+proj=utm +zone=15 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
state = map2SpatialPolygons(usa.m, IDs=IDs)
proj4string(state) = "+proj=longlat +datum=WGS84"
state <- spTransform(state, CRS(proj4string(equi7t1[["NA"]])))
ov.state <- over(y=state, x=equi7t1[["NA"]])
#ov.state <- gIntersection(state, equi7t1[["NA"]], byid = TRUE)
#str(ov.state@data)
new.dirs = unique(paste0("NA_", equi7t1[["NA"]]$TILE[which(!is.na(ov.state))])) #levels(as.factor(ov$equi7))
## 906 tiles
x <- lapply(paste0("./", new.dirs), dir.create, recursive=TRUE, showWarnings=FALSE)
## Split models otherwise too large in size:
num_splits=20
#mrfX_NASISgg = readRDS.gz("mrfX_NASISgg.rds")
mrfX_NASISgg_final <- split_rf(mrfX_NASISgg, num_splits)
for(j in 1:length(mrfX_NASISgg_final)){
gm = mrfX_NASISgg_final[[j]]
saveRDS.gz(gm, file=paste0("mrfX_NASISgg_", j,".rds"))
}
rm(mrfX_NASISgg); rm(mrfX_NASISgg_final)
gc(); gc()
save.image()
#mrfX_NASISpscs = readRDS.gz("mrfX_NASISpscs.rds")
mrfX_NASISpscs_final <- split_rf(mrfX_NASISpscs, num_splits)
for(j in 1:length(mrfX_NASISpscs_final)){
gm = mrfX_NASISpscs_final[[j]]
saveRDS.gz(gm, file=paste0("mrfX_NASISpscs_", j,".rds"))
}
rm(mrfX_NASISpscs); rm(mrfX_NASISpscs_final)
gc(); gc()
save.image()
#del.lst <- list.files(path="/data/NASIS", pattern=glob2rx("^TAXgg_*_*_*_*.rds$"), full.names=TRUE, recursive=TRUE)
#unlink(del.lst)
#del.lst <- list.files(path="/data/NASIS", pattern=glob2rx("^PSCS_*_*_*_*.tif"), full.names=TRUE, recursive=TRUE)
#unlink(del.lst)
del.lst <- list.files(path="/data/NASIS", pattern=glob2rx("^TAXgg_*_*_*_*.tif"), full.names=TRUE, recursive=TRUE)
unlink(del.lst)
#model.n = "mrfX_NASISgg_"
#varn = "TAXgg"
model.n = "mrfX_NASISpscs_"
varn = "PSCS"
out.path = "/data/NASIS"
for(j in 1:num_splits){
gm = readRDS.gz(paste0(model.n, j,".rds"))
cpus = unclass(round((256-30)/(3.5*(object.size(gm)/1e9))))
sfInit(parallel=TRUE, cpus=ifelse(cpus>46, 46, cpus))
sfExport("gm", "new.dirs", "split_predict_c", "j", "varn", "out.path")
sfLibrary(ranger)
x <- sfLapply(new.dirs, fun=function(x){ if(length(list.files(path = paste0(out.path, "/", x, "/"), glob2rx("*.rds$")))<j){ try( split_predict_c(x, gm, in.path="/data/covs1t", out.path=out.path, split_no=j, varn=varn) ) } } ) ## , num.threads=5
sfStop()
rm(gm)
}
## Test it:
#sum_predict_ranger(i="NA_060_036", in.path="/data/covs1t", out.path="/data/NASIS", varn="TAXgg", num_splits)
#sum_predict_ranger(i="NA_060_036", in.path="/data/covs1t", out.path="/data/NASIS", varn="PSCS", num_splits)
## Sum up predictions:
sfInit(parallel=TRUE, cpus=30)
sfExport("new.dirs", "sum_predict_ranger", "num_splits", "varn")
sfLibrary(rgdal)
sfLibrary(plyr)
x <- sfLapply(new.dirs, fun=function(x){ try( sum_predict_ranger(x, in.path="/data/covs1t", out.path="/data/NASIS", varn=varn, num_splits) ) } )
sfStop()
## Create mosaics:
mosaic_tiles_NASIS <- function(j, in.path, varn, tr=0.002083333, r="bilinear", ot="Byte", dstnodata=255, out.path){
out.tif <- paste0(out.path, varn, "_", j, '_250m_ll.tif')
if(!file.exists(out.tif)){
tmp.lst <- list.files(path=in.path, pattern=glob2rx(paste0(varn, "_", j, "_*_*.tif$")), full.names=TRUE, recursive=TRUE)
out.tmp <- tempfile(fileext = ".txt")
vrt.tmp <- tempfile(fileext = ".vrt")
cat(tmp.lst, sep="\n", file=out.tmp)
system(paste0(gdalbuildvrt, ' -input_file_list ', out.tmp, ' ', vrt.tmp))
system(paste0(gdalwarp, ' ', vrt.tmp, ' ', out.tif, ' -t_srs \"+proj=longlat +datum=WGS84\" -r \"', r,'\" -ot \"', ot, '\" -dstnodata \"', dstnodata, '\" -tr ', tr, ' ', tr, ' -co \"BIGTIFF=YES\" -wm 2000 -co \"COMPRESS=DEFLATE\"'))
}
}
levs = list.files(path="./NA_060_036", pattern=glob2rx(paste0("^",varn,"_*_*_*_*.tif$")))
levs = sapply(basename(levs), function(x){strsplit(x, "_")[[1]][2]})
sfInit(parallel=TRUE, cpus=ifelse(length(levs)>46, 46, length(levs)))
sfExport("gdalbuildvrt", "gdalwarp", "levs", "mosaic_tiles_NASIS", "varn")
out <- sfClusterApplyLB(levs, function(x){try( mosaic_tiles_NASIS(x, in.path="/data/NASIS/", varn=varn, out.path="/data/NASIS/") )})
sfStop()
save.image()
|
ae3f23b45fe29fc8cb6040ecd11df364985e7f1e
|
05b3d551133a9f5f56a54fced65778c3c670e52f
|
/s05_multiple_linear_regression.R
|
64dc45ecb293ddbccdbffae6cb2f5ac936b269da
|
[] |
no_license
|
mbeveridge/SDS_MachineLearning
|
dd4a90692bbbdf02e7d60f2980533139e25b05ea
|
b33287c7adabc9bea526d7934a1da667f174488f
|
refs/heads/master
| 2021-07-10T03:20:18.803325
| 2019-01-21T16:35:59
| 2019-01-21T16:35:59
| 135,911,406
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,878
|
r
|
s05_multiple_linear_regression.R
|
# Multiple Linear Regression
# Importing the dataset
dataset = read.csv('data/s5_50_Startups.csv')
# dataset = dataset[, 2:3]
# Encoding categorical data [§5 Lect48: "MLR - R pt1" ...@3min00]
dataset$State = factor(dataset$State,
levels = c('New York', 'California', 'Florida'),
labels = c(1, 2, 3))
# Splitting the dataset into the Training set and Test set
# install.packages('caTools')
library(caTools)
set.seed(123)
split = sample.split(dataset$Profit, SplitRatio = 0.8)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
# Feature Scaling
# training_set = scale(training_set)
# test_set = scale(test_set)
# Fitting Multiple Linear Regression to the Training set [§5 Lect49: "MLR - R pt2"]
regressor = lm(formula = Profit ~ .,
data = training_set)
# Predicting the Test set results [§5 Lect50: "MLR - R pt3"]
y_pred = predict(regressor, newdata = test_set)
# Building the optimal model using Backward Elimination [§5 Lect51: "MLR - R (Backward Elimination): HOMEWORK !"]
regressor = lm(formula = Profit ~ R.D.Spend + Administration + Marketing.Spend + State,
data = dataset)
summary(regressor)
# Optional Step: Remove State2 only (as opposed to removing State directly)
# regressor = lm(formula = Profit ~ R.D.Spend + Administration + Marketing.Spend + factor(State, exclude = 2),
# data = dataset)
# summary(regressor)
regressor = lm(formula = Profit ~ R.D.Spend + Administration + Marketing.Spend,
data = dataset)
summary(regressor)
# cont'd [§5 Lect52: "MLR - R (Backward Elimination): Homework solution"]
regressor = lm(formula = Profit ~ R.D.Spend + Marketing.Spend,
data = dataset)
summary(regressor)
regressor = lm(formula = Profit ~ R.D.Spend,
data = dataset)
summary(regressor)
|
7d12d5b856345be0015db325464ad98292e1ba58
|
a7045f6708f8bd65a54a946a544682325a4ae004
|
/man/figLayout.rd
|
4cea2df84438c7c125519d537874a563052a16da
|
[] |
no_license
|
jjcurtin/lmSupport
|
a621e2a38211e4aacd4e41597d92df6ac303f97c
|
1ba8feed959abd9c01c7041f8457d775cb59bb24
|
refs/heads/main
| 2023-04-06T01:36:59.490682
| 2021-05-06T02:12:53
| 2021-05-06T02:12:53
| 364,758,953
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,468
|
rd
|
figLayout.rd
|
\name{figLayout}
\alias{figLayout}
\title{Wrapper for standarized use of layout()}
\description{
Wrapper function for standardized use of layout() and layout.show()
}
\usage{figLayout(nRows, nCols, heights=rep(1,nRows), widths=rep(1,nCols),
layout.display=NULL)}
\arguments{
\item{nRows, nCols}{integers specifying number of rows and columns in matrix}
\item{heights}{vector indicating relative heights of rows; Default is equal heights}
\item{widths}{vector indicating relative widtsh of columns; Default is equal widths}
\item{layout.display}{Boolean if outlines and numbers of panels should be displayed}
}
\value{
None
}
\seealso{
layout(), layout.show(), figLabDefaults(), figSetDefaults(), figNewDevice(), figLines(),figLines()
}
\examples{
X = rep(2:9,4)+jitter(rep(0,32))
Y = X + rnorm(length(X),0,5)
m = lm(Y ~ X)
dNew = data.frame(X=seq(2,9,by=.01))
p = modelPredictions(m,dNew)
figNewDevice()
figLayout(2,1)
figPlotRegion(x=c(0,10),y=c(0,10))
figConfidenceBand(p$X,p$Predicted,p$CILo,p$CIHi)
figLines(p$X,p$Predicted)
figAxis(side=1,lab.text='X-axis 1', scale.at=seq(from=0,to=10,by=2))
figAxis(side=2,lab.text='Startle Response', scale.at=seq(from=0,to=10,by=2))
figPlotRegion(x=c(0,10),y=c(0,10))
figPoints(X,Y)
figAxis(side=1,lab.text='X-axis 1', scale.at=seq(from=0,to=10,by=2))
figAxis(side=2,lab.text='Startle Response', scale.at=seq(from=0,to=10,by=2))
}
\author{John J. Curtin \email{jjcurtin@wisc.edu}}
\keyword{graphic}
|
d115f6ce93adad09e8fa8f60ab4c3712c9030348
|
a09b27e16aac0233f01567851eb99a99c6116af3
|
/sesion_3/retos/Entrega_retos_sesion3/reto_3_p3.R
|
78a2a5ce4c5f5e0a0f3bc01578fa02e9a3190630
|
[] |
no_license
|
raqueljimenezm/ecoinformatica_2014_2015
|
2f974bb87ecb7236fffc7d4796373daa49942c00
|
d0123683a7bfd61aae34bb4fb56a5c3d97fa7a73
|
refs/heads/master
| 2021-01-16T20:57:52.332052
| 2015-02-09T00:39:35
| 2015-02-09T00:39:35
| 30,033,204
| 0
| 0
| null | 2015-01-29T17:54:20
| 2015-01-29T17:54:20
| null |
UTF-8
|
R
| false
| false
| 157
|
r
|
reto_3_p3.R
|
# Introduzco la cantidad de datos de temperaturas de los cuales quiero hacer la media
temp<-scan(n=10)
# Hago la media de esas 10 temperaturas.
mean(temp)
|
71312fb688cea42192f3e30323b5c852b2fcbf30
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/QFRM/examples/BarrierLT.Rd.R
|
acec65eaa04943c53acc88227f4f767b7507ed76
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,291
|
r
|
BarrierLT.Rd.R
|
library(QFRM)
### Name: BarrierLT
### Title: Barrrier option valuation via lattice tree (LT)
### Aliases: BarrierLT
### ** Examples
# default Up and Knock-in Call Option with H=60, approximately 7.09
(o = BarrierLT())$PxLT
#Visualization of price changes as Nsteps change.
o = Opt(Style="Barrier")
visual=sapply(10:200,function(n) BarrierLT(OptPx(o,NSteps=n))$PxLT)
c=(10:200)
plot(visual~c,type="l",xlab="NSteps",ylab="Price",main="Price converence with NSteps")
# Down and Knock-out Call Option with H=40
o = OptPx(o=Opt(Style="Barrier"))
BarrierLT(o,dir="Down",knock="Out",H=40)
# Down and Knock-in Call Option with H=40
o = OptPx(o=Opt(Style="Barrier"))
BarrierLT(o,dir="Down",knock="In",H=40)
# Up and Knock-out Call Option with H=60
o = OptPx(o=Opt(Style="Barrier"))
BarrierLT(o,dir='Up',knock="Out")
# Down and Knock-out Put Option with H=40
o = OptPx(o=Opt(Style="Barrier",Right="Put"))
BarrierLT(o,dir="Down",knock="Out",H=40)
# Down and Knock-in Put Option with H=40
o = OptPx(o=Opt(Style="Barrier",Right="Put"))
BarrierLT(o,dir="Down",knock="In",H=40)
# Up and Knock-out Put Option with H=60
o = OptPx(o=Opt(Style="Barrier",Right="Put"))
BarrierLT(o,dir='Up',knock="Out")
# Up and Knock-in Put Option with H=60
BarrierLT(OptPx(o=Opt(Style="Barrier",Right="Put")))
|
2ca3e9025d449f5edd187a870b23bd9695b9d187
|
37ac06cf0247ccf7af1553e8098643b7350102db
|
/tests/testthat/test_subset_points.R
|
c446f0024f498243b29cc843ccbe941fbf0202e3
|
[
"MIT"
] |
permissive
|
shenyang1981/iSEE
|
7c6606889e97594d76f7532ff1b1aeef03cdf2fa
|
3f81ffcdd12bf457a280f5a4df0d2dd5e440a62c
|
refs/heads/master
| 2020-04-15T17:46:41.172946
| 2019-12-31T10:26:14
| 2019-12-31T10:26:14
| 164,887,242
| 0
| 0
|
MIT
| 2019-12-31T10:26:15
| 2019-01-09T15:21:35
|
R
|
UTF-8
|
R
| false
| false
| 1,000
|
r
|
test_subset_points.R
|
context("subset_points")
# This tests the subsetPointsByGrid function.
# library(testthat); library(iSEE); source("test_subset_points.R")
set.seed(110001)
test_that("subsetPointsByGrid works correctly", {
x <- rnorm(20000)
y <- rnorm(20000)
chosen <- subsetPointsByGrid(x, y, resolution=200)
expect_true(sum(chosen) < length(chosen))
expect_true(sum(chosen) > 1L)
# Checking the correctness of the result.
xid <- as.integer(cut(x, 200))
yid <- as.integer(cut(y, 200))
combined <- sprintf("%i-%i", xid, yid)
ref <- !duplicated(combined, fromLast=TRUE)
expect_identical(ref, chosen)
# Checking extremes.
chosen.low <- subsetPointsByGrid(x, y, resolution=20)
expect_true(sum(chosen) > sum(chosen.low))
chosen.high <- subsetPointsByGrid(x, y, resolution=2000)
expect_true(sum(chosen.high) > sum(chosen))
# Checking silly inputs.
expect_identical(suppressWarnings(subsetPointsByGrid(integer(0L), integer(0L))), logical(0L))
})
|
fe502504cd37617bc658c66a6226d95490ca8161
|
8f8494b8b2da1d7191b30905ed35ef37e4b7f21b
|
/Project2-TxtMining_v2.R
|
ae2c1f84d02f789933e5d61e2f871f66a336aa99
|
[] |
no_license
|
Leesann1987/Tweet-Text-Mining
|
c007ed46991348e2f9a7d0d2a8d34737790facd9
|
59b9ee19d7a5d0dcdf0f3cd9820f194cd62ab154
|
refs/heads/master
| 2022-05-25T04:05:19.466467
| 2020-04-30T14:33:05
| 2020-04-30T14:33:05
| 260,234,416
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 9,757
|
r
|
Project2-TxtMining_v2.R
|
########################### PROJECT 2 - TEXT MINING ################################
library(textclean)
library(twitteR)
library(tm)
library(stopwords)
library(wordcloud)
library(topicmodels)
library(ggplot2)
library(data.table)
library(sentimentr)
library(dplyr)
library(tidyverse)
library(ggthemes)
library(ggcorrplot)
library(Hmisc)
library(VIM)
library(stringr)
df <- read.csv(file.choose(), na.strings=c("", "NA"))
dim(df)
summary(df)
glimpse(df)
################## CLEANING #################
#Not certain we need the columns: airline_senitment_confidence, negativereason_confidence, airline_sentiment-gold, negativereason_gold, tweet_created or user_timezone
#Removing these
df <- subset(df, select = -c(airline_sentiment_confidence, negativereason_confidence, airline_sentiment_gold, negativereason_gold, tweet_created, user_timezone))
glimpse(df)
summary (df)
#Looking for NA's
sum(is.na(df)) #23816
missing_values <- aggr(df, col=c('navyblue','red'), numbers=TRUE, sortVars=TRUE, labels=names(df), cex.axis=0.5, gap=2, ylab=c("Histogram of missing data","Pattern"))
# All Na's are located in the tweet_coord, negativereason and tweet_location columns
#Exploring why the negative comment reason have NA
NA_Reasons <- df %>%
select(airline_sentiment, negativereason, airline) %>%
filter(is.na(negativereason))
summary(NA_Reasons)
# NA given to positive and neutral reviews
#Replacing NA with blank spaces
na_vals1 <- which(is.na(df$negativereason)) #Rows where NAs are located
df$negativereason <- as.character(df$negativereason) #first convert to character strings
df[na_vals1,]$negativereason <- ""
df$negativereason <- as.factor(df$negativereason) #convert back to factors
summary(df$negativereason)
#Clean!
#Exploring NA Values in tweet_coord and tweet_location
na_locals <- df %>%
select(tweet_coord, tweet_location)
summary(na_locals)
#Lots of NA in coordinates, will remove column and treat tweet location
df <- subset(df, select = -c(tweet_coord)) #removing coordinate column
na_vals2 <- which(is.na(df$tweet_location)) #Rows where NAs are located
df$tweet_location <- as.character(df$tweet_location) #first convert to character strings
df[na_vals2,]$tweet_location <- "Unspecified"
df$tweet_location <- as.factor(df$tweet_location) #convert back to factors
summary(df$tweet_location)
#################################################
#### What should we do to organize these??? ####
tweet_locations <- df %>%
select(tweet_location) %>%
arrange(tweet_location)
#################################################
############# Data Exploration ################
### Looking at the count of airline sentiments per airline ###
sentiments <- df %>%
select(airline, airline_sentiment) %>%
group_by(airline, airline_sentiment) %>%
summarise(freq = n())
ggplot(sentiments, aes(x = airline, y = freq, fill = airline_sentiment)) +
geom_bar(stat="identity", position = position_dodge()) +
theme_set(theme_bw()) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(title="Distribution of Airline Sentiments", x = 'Airline', y = 'Frequency')
### Looking at the distribution of negative comments ###
neg_reasons <- df %>%
filter(airline_sentiment == "negative") %>%
select(airline, negativereason) %>%
group_by(airline, negativereason) %>%
summarise(freq = n())
ggplot(neg_reasons, aes(x = negativereason, y = freq)) +
geom_bar(stat="identity", fill="blue") +
theme_set(theme_bw()) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(title="Reasons for the Negative Sentiments", x = 'Negative Reasons', y = 'Frequency') +
facet_wrap(~ airline)
### Looking at retweet counts and airline
retweet_1 <- df %>%
select(airline, airline_sentiment, retweet_count) %>%
group_by(airline, airline_sentiment) %>%
summarise(total = sum(retweet_count))
ggplot(retweet_1, aes(x = airline, y = total, fill = airline_sentiment)) +
geom_bar(stat="identity", position = position_dodge()) +
theme_set(theme_bw()) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(title="Total number of Retweets by Airline", x = 'Airline', y = 'Number of Retweets')
### Looking at retweet counts and negative reasons
retweet_2 <- df %>%
filter(airline_sentiment == "negative") %>%
select(airline, negativereason, retweet_count) %>%
group_by(airline, negativereason) %>%
summarise(total = sum(retweet_count))
ggplot(retweet_2, aes(x = negativereason, y = total)) +
geom_bar(stat="identity", fill="blue") +
theme_set(theme_bw()) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(title="Total number of Retweets by Negative Reason", x = 'Negative Reasons', y = 'Number of Retweets') +
facet_wrap(~ airline)
#retweet count for positive reasons
retweet_3 <- df %>%
filter(airline_sentiment == "positive") %>%
select(airline, retweet_count) %>%
group_by(airline) %>%
summarise(total = sum(retweet_count))
ggplot(retweet_3, aes(x = airline, y= total)) +
geom_bar(stat= "identity", fill = "blue") +
theme_set(theme_bw()) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(title = "Total Number of Retweets by Positive Sentiment", x = "Airline", y = "Number of Retweets")
##Exploring the negative sentiments in the reviews
library(tidytext)
library(textdata)
review <- tidytext::unnest_tokens(read.csv(file.choose(), stringsAsFactors = FALSE), word, text)
data(stop_words)
review <- review %>%#remove stop words
anti_join(stop_words)
review %>%
count(word, sort=TRUE)
###counting negative sentiments
negative <- get_sentiments('bing') %>%
filter(sentiment == "negative")
neg_reviews <- review %>%
inner_join(negative) %>%
count(word, sort=TRUE)
head(neg_reviews, 10)
####Put word cloud here
###counting positive sentiments
positive <- get_sentiments('bing') %>%
filter(sentiment == "positive")
pos_reviews <- review %>%
inner_join(positive) %>%
count(word, sort=TRUE)
head(pos_reviews, 10)
#unsurprisingly, there are almost half as many positive reviews as there are negative ones
#Let's look at a wordcloud of our most prominent sentiments
pal <- brewer.pal(10, "Paired")
neg_reviews <- review %>%
inner_join(negative) %>%
count(word) %>%
with(wordcloud(word, n,
rot.per = .15,
scale=c(5, .3),
max.words = 50,
random.order = F,
random.color = F,
colors = pal))
pos_reviews <- review %>%
inner_join(positive) %>%
count(word) %>%
with(wordcloud(word, n,
rot.per = .15,
scale = c(5, .3),
max.words = 50,
random.order = F,
random.color = F,
colors = pal))
#Let's look at which airlines had the most complaints with delayed flights
#First, we'll change all 'delay' and 'delays' to 'delayed'
review$word[grepl('delays', review$word)] <- 'delayed'
review$word[grepl('delay', review$word)] <- 'delayed'
#next, we plot the data for delayed complaints by airline
delayed <- review %>%
filter(word == 'delayed') %>%
select(airline) %>%
group_by(airline) %>%
summarise(freq = n())
ggplot(delayed, aes(x = airline, y = freq)) +
geom_bar(stat = 'identity', fill='blue') +
theme_set(theme_bw()) +
theme(axis.title.x = element_text(angle = 90, hjust = 1)) +
labs(title = "Delayed Complaints by Airline", x="Airline", y="Number of Complaints")
#we can see 'refund' is a pretty high pos review, let's check how many people were refunded by airline
sum(review$word=='refunded')#refunded shows up 19 times. Let's change that to refund
review$word[grepl('refunded', review$word)] <- 'refund'
refund <- review %>%
filter(word == 'refund') %>%
select(airline) %>%
group_by(airline) %>%
summarise(freq = n())
ggplot(refund, aes(x = airline, y = freq)) +
geom_bar(stat = 'identity', fill='red') +
theme_set(theme_bw()) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(title="Refunded Tickets by Airline", x="Airline", y="Number of Recorded Refunds")
#let's see if certain words have an impact on sentiment
#we'll subset the data to get rid of certain columns
review <- subset(review, select = -c(airline_sentiment_confidence, negativereason_confidence, airline_sentiment_gold, negativereason_gold, tweet_created, user_timezone))
delayed_review <- review %>%
filter(word=='delayed') %>%
select(airline, airline_sentiment) %>%
group_by(airline, airline_sentiment) %>%
summarise(freq = n())
ggplot(delayed_review, aes(x = airline, y = freq, fill = airline_sentiment)) +
geom_bar(stat = 'identity', position = position_dodge()) +
theme_set(theme_bw()) +
theme(axis.title.x = element_text(angle = 0, hjust = 1)) +
labs(title="Distribution of Airline Sentiment with Delays", x="Airline", y="Frequency")
#we'll check how airline sentiment was affected for people who were given refunds
refund_review <- review %>%
filter(word == 'refund') %>%
select(airline, airline_sentiment) %>%
group_by(airline, airline_sentiment) %>%
summarise(freq = n())
ggplot(refund_review, aes(x=airline, y=freq, fill=airline_sentiment)) +
geom_bar(stat = 'identity', position = position_dodge()) +
theme_set(theme_bw()) +
theme(axis.title.x = element_text(angle = 0, hjust = 1)) +
labs(title="Distribution of Airline Sentiment with Refunds", x="Airline", y="Frequency")
|
2e77f776dfa5a8297a94182e243b996d191ef417
|
7bb3f64824627ef179d5f341266a664fd0b69011
|
/Basic_Engineering_Mathematics_by_John_Bird/CH16/EX16.18/Ex16_18.R
|
0b76afb01bae295db257f35b2e549fb759044ef5
|
[
"MIT"
] |
permissive
|
prashantsinalkar/R_TBC_Uploads
|
8bd0f71834814b1d03df07ce90b2eae3b7d357f8
|
b3f3a8ecd454359a2e992161844f2fb599f8238a
|
refs/heads/master
| 2020-08-05T23:06:09.749051
| 2019-10-04T06:54:07
| 2019-10-04T06:54:07
| 212,746,586
| 0
| 0
|
MIT
| 2019-10-04T06:03:49
| 2019-10-04T06:03:48
| null |
UTF-8
|
R
| false
| false
| 659
|
r
|
Ex16_18.R
|
#page no. 147
#problem 18
#load package --->measurements
library(measurements)
#formula used: alpha = (1/theta)log(R/R0)
#
#function:
find_alpha = function(theta,R,R0)
{
return((1/theta)*log(R/R0))
}
find_theta = function(alpha,R,R0)
{
return((1/alpha)*log(R/R0))
}
#given:
r0 = 5 #kilo_ohms
R0 = conv_unit(r0,'km','m') # resistance in ohms
r = 6 #kilo_ohms
R = conv_unit(r,'km','m') # resistance in ohms
theta = 1500 #temperature in C
alpha = find_alpha(theta,R,R0)
r_new = 5.4 #kilo_ohm
R_new = conv_unit(r_new,'km','m')
theta_new = find_theta(alpha,R_new,R0)
print(theta_new) # temperature to nearest degree
|
88cbaaff0a2690aba90d118ae5798b36a71fdfed
|
d76e36ad72d9d8775d1c7f084c16e8d3335ae943
|
/R/Poisson Distribution.R
|
08b814aad4bc6b0e02bfeaef2f84d330210e6612
|
[
"MIT"
] |
permissive
|
natitaw/write-to-learn
|
73f84f2703fccae35c94c2b5d0984c75355af44d
|
3744d25d1cbeb8a4d056cb853431c3212118d56e
|
refs/heads/master
| 2022-12-02T05:23:24.214468
| 2022-12-01T16:05:32
| 2022-12-01T16:05:32
| 272,259,522
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 343
|
r
|
Poisson Distribution.R
|
# Poisson Distribution
# X follows a POISSON distribution with a known
# rate of lambda = 7
# X ~ POISSON(lambda=7)
# Probability x=4
dpois(x=4, lambda=7)
# P(X=0) & P(X=1) & ... & P(X=4)
dpois(x=0:4, lambda=7)
# P(X<=4)
sum(dpois(x=0:4, lambda=7))
# OR
ppois(q=4, lambda=7, lower.tail=T)
# P (X>=12)
ppois(q=12, lambda=7, lower.tail=F)
|
a50eb46497ab78afac69bec6d96dd27013e99ead
|
a5a653041e1d3455c920b19c277cc8826e1fb707
|
/man/fars_read.Rd
|
8fbe8808d81c9a657df62086172ea9929f58e136
|
[] |
no_license
|
demydd/Rpackagebuild
|
dbdbf8bbe0ff5426d70f6d6097599b93220734ff
|
4ed2ba8ad339be7e9a5773e3f0e85f1ebfbafe0c
|
refs/heads/master
| 2020-03-10T23:17:38.311759
| 2018-04-17T22:17:59
| 2018-04-17T22:17:59
| 129,638,140
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,132
|
rd
|
fars_read.Rd
|
\name{fars_read}
\alias{fars_read}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Read files
}
\description{
The function read data from files specified by the user
}
\usage{
fars_read(filename)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{filename}{
the file name of the data source is the input character vector. I could be defined by the user of other application. If the file does not exist the function is terminated and the proper message is generated.
}
}
\details{
The function uses readr::read_csv() to read input data
}
\value{
the function return the dataframe of 'tbl_df' class.
}
\references{
No references are assumed.
}
\author{
Demyd Dzyuban
}
\note{
%% ~~further notes~~
}
\section{Warning }{
Stop reading if the file does not exist.
}
\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
}
\examples{
# input_data <- fars_read("data_source.txt")
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }% use one of RShowDoc("KEYWORDS")
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
|
c3f7ffba51da87161b3cb3ddff7ffb085f379b3e
|
fac4706f542ff0c4e96625597008aeeab12509e8
|
/shiny_arboc-score/app.R
|
3d6a9f20746aa1cd298668c8fee36079cd1ad4d5
|
[
"MIT"
] |
permissive
|
alwinw/arboc-score
|
e1897687caff4e5b07ae4d5231f55f6bd88601ed
|
0761dd4cf30afd11fdbd313ea17eca4320c29055
|
refs/heads/main
| 2023-05-10T05:26:17.587201
| 2021-06-05T12:10:39
| 2021-06-05T12:10:39
| 374,060,891
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,935
|
r
|
app.R
|
library(shiny)
library(DT)
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel("AKI risk based on creatinine (ARBOC) score"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
checkboxGroupInput(
inputId = "factors",
label = "Risk Factors:",
choiceNames =
list(
"Cardiac Surgery",
"Vasopressor Use",
"Chronic Liver Disease",
"Cr change =1µmol/L/h over 4-5.8 hours"
),
choiceValues =
list("PCs", "Vas", "CLD", "Crch")
),
textOutput("score")
),
mainPanel(
dataTableOutput("table")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
points_table <- c(PCs = 1, Vas = 3, CLD = 1, Crch = 1)
raw_table <- data.frame(
`Total Points` = c("0", "1", "2", "3", "4", "5", "6"),
`Risk` = c("Low", "Low", "Medium", "Medium", "High", "High", "High"),
`Risk of stages 2 or 3 AKI in 8.7 to 25.6 hours` = c("0.7%", "2.3%", "12.7%", "26.5%", "42.4%", "85.3%", ">85.3%"),
check.names = FALSE
)
score_table <- datatable(
raw_table,
rownames = FALSE, selection = "none",
options = list(dom = "t", pageLength = 10)
) %>%
formatStyle(
"Total Points",
target = "row",
backgroundColor = styleEqual(
0:6, c("#97FF97", "#97FF97", "#FFFFA7", "#FFFFA7", "#FFA7A7", "#FFA7A7", "#FFA7A7")
)
)
output$score = renderText({
score = sum(points_table[input$factors], 0, na.rm = TRUE)
paste("ARBOC Score:", score)
})
output$table <- renderDataTable({
row = sum(points_table[input$factors], 0, na.rm = TRUE)
score_table %>%
formatStyle(
"Total Points",
target = "row",
fontWeight = styleEqual(row, "bold")
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
|
a57ef623dac4189c82d4384c8c7502b5f70d71d6
|
29585dff702209dd446c0ab52ceea046c58e384e
|
/HistogramTools/inst/unitTests/runit.subset.R
|
8b34e9c45de43c243537e8edddc2d26e3d33c055
|
[] |
no_license
|
ingted/R-Examples
|
825440ce468ce608c4d73e2af4c0a0213b81c0fe
|
d0917dbaf698cb8bc0789db0c3ab07453016eab9
|
refs/heads/master
| 2020-04-14T12:29:22.336088
| 2016-07-21T14:01:14
| 2016-07-21T14:01:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,604
|
r
|
runit.subset.R
|
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: mstokely@google.com (Murray Stokely)
TestSubsetHistogram <- function() {
hist.1 <- hist(c(1,1,2,2,7), breaks=0:9, plot=FALSE)
hist.subset <- SubsetHistogram(hist.1, maxbreak=3)
checkEquals(hist.subset$breaks, c(0, 1, 2, 3))
checkEquals(hist.subset$counts, c(2, 2, 0))
# Fail if we get get a break point out of range:
checkException(SubsetHistogram(hist.1, minbreak=-100))
checkException(SubsetHistogram(hist.1, maxbreak=100))
# Or if its in range but not an existing breakpoint:
checkException(SubsetHistogram(hist.1, minbreak=0.5))
checkException(SubsetHistogram(hist.1, maxbreak=6.5))
# Return original histogram if new breakpoints are existing ends.
hist.nosubset <- SubsetHistogram(hist.1, minbreak=0)
checkEquals(hist.nosubset$breaks, hist.1$breaks)
checkEquals(hist.nosubset$counts, hist.1$counts)
hist.nosubset <- SubsetHistogram(hist.1, maxbreak=9)
checkEquals(hist.nosubset$breaks, hist.1$breaks)
checkEquals(hist.nosubset$counts, hist.1$counts)
}
|
90cf95c97802f8f56bd4c1e26f7b79f8ea8c3350
|
ee3186683b1576e011a5c1935b8a95b6b05a2ee5
|
/Classification Models Dataset & Code/SVM.R
|
f2f3867b2a2f5d5b3e777ce1c83d15850ac67ea7
|
[] |
no_license
|
SrishtiIssrani/DissertationProject
|
70136613dfd696b7cb296af9aa343df79d44ebc9
|
dfda7a3f4bba5d74662690747e353914ac364a89
|
refs/heads/master
| 2020-05-18T02:49:07.069391
| 2019-04-29T19:17:05
| 2019-04-29T19:17:05
| 184,128,508
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,244
|
r
|
SVM.R
|
install.packages('caTools')
install.packages('e1071')
install.packages('caret')
install.packages('randomForest')
library(caTools)
library(e1071)
library(caret)
library(randomForest)
dataset = read.csv('DataPrepforClassification copy 3.csv')
dataset = dataset[3:14]
#Encoding Categorical Data Verdict
dataset$Verdict = factor(dataset$Verdict,
levels = c('Flop', 'Hit'),
labels = c(0,1))
dataset$CBFCRating = factor(dataset$CBFCRating,
levels = c('U', 'UA', 'A'),
labels = c(1,2,3))
# Splitting the dataset into the Training set and Test set
set.seed(123)
split = sample.split(dataset$Verdict, SplitRatio = 2/3)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
#Feature Scaling
training_set[, 1:10] = scale(training_set[, 1:10])
test_set[, 1:10] = scale(test_set[, 1:10])
#creating the classifier
classifier = svm(formula = Verdict ~ .,
data = training_set,
type = 'C-classification',
kernel = 'linear')
#making the predictions on the test set
y_pred = predict(classifier, newdata = test_set[-12])
#creating the confusion matrix
cm <-confusionMatrix(y_pred, test_set$Verdict)
fourfoldplot(cm$table)
draw_confusion_matrix <- function(cm) {
layout(matrix(c(1,1,2)))
par(mar=c(2,2,2,2))
plot(c(100, 345), c(300, 450), type = "n", xlab="", ylab="", xaxt='n', yaxt='n')
title('CONFUSION MATRIX', cex.main=2)
# create the matrix
rect(150, 430, 240, 370, col='#3F97D0')
text(195, 435, 'Hit', cex=1.2)
rect(250, 430, 340, 370, col='#F7AD50')
text(295, 435, 'Flop', cex=1.2)
text(125, 370, 'Actual', cex=1.3, srt=90, font=2)
text(245, 450, 'Predicted', cex=1.3, font=2)
rect(150, 305, 240, 365, col='#F7AD50')
rect(250, 305, 340, 365, col='#3F97D0')
text(140, 400, 'Hit', cex=1.2, srt=90)
text(140, 335, 'Flop', cex=1.2, srt=90)
# add in the cm results
res <- as.numeric(cm$table)
text(195, 400, res[4], cex=1.6, font=2, col='white')
text(195, 335, res[2], cex=1.6, font=2, col='white')
text(295, 400, res[3], cex=1.6, font=2, col='white')
text(295, 335, res[1], cex=1.6, font=2, col='white')
# add in the specifics
plot(c(100, 0), c(100, 0), type = "n", xlab="", ylab="", main = "DETAILS", xaxt='n', yaxt='n')
text(10, 85, names(cm$byClass[1]), cex=1.2, font=2)
text(10, 70, round(as.numeric(cm$byClass[1]), 3), cex=1.2)
text(30, 85, names(cm$byClass[2]), cex=1.2, font=2)
text(30, 70, round(as.numeric(cm$byClass[2]), 3), cex=1.2)
text(50, 85, names(cm$byClass[5]), cex=1.2, font=2)
text(50, 70, round(as.numeric(cm$byClass[5]), 3), cex=1.2)
text(70, 85, names(cm$byClass[6]), cex=1.2, font=2)
text(70, 70, round(as.numeric(cm$byClass[6]), 3), cex=1.2)
text(90, 85, names(cm$byClass[7]), cex=1.2, font=2)
text(90, 70, round(as.numeric(cm$byClass[7]), 3), cex=1.2)
# add in the accuracy information
text(30, 35, names(cm$overall[1]), cex=1.5, font=2)
text(30, 20, round(as.numeric(cm$overall[1]), 3), cex=1.4)
text(70, 35, names(cm$overall[2]), cex=1.5, font=2)
text(70, 20, round(as.numeric(cm$overall[2]), 3), cex=1.4)
}
draw_confusion_matrix(cm)
|
db177a7c21b55747589f857ec13fb0751cf90581
|
65061d49c0c51ab8db342adfd28df593ef8cf361
|
/best.r
|
af67b9d44146772d3a5a81e3a41a415c25839de0
|
[] |
no_license
|
ahmed007/RAssignment3
|
b1d85a961aabd196fe983cdcc652caf618672d18
|
128d45bd2fb86aae504cddd93028e8c83c5cf59c
|
refs/heads/master
| 2021-01-19T01:02:32.477237
| 2016-07-14T15:41:01
| 2016-07-14T15:41:01
| 63,348,433
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,909
|
r
|
best.r
|
#Write a function called best that take two arguments: the 2-character abbreviated name of a state and an outcome name. The function reads the
#outcome-of-care-measures.csv le and returns a character vector with the name of the hospital that has the best (i.e. lowest) 30-day mortality for the speci ed outcome
#in that state. The hospital name is the name provided in the Hospital.Name variable. The outcomes can be one of \heart attack", \heart failure", or \pneumonia". Hospitals that do #not have data on a particular outcome should be excluded from the set of hospitals when deciding the rankings. Handling ties . If there is a tie for the best hospital for a given #outcome, then the hospital names should be sorted in alphabetical order and the rst hospital in that set should be chosen (i.e. if hospitals \b", \c", and \f" are tied for best, then #hospital \b" should be returned).
best <- function(st, outcome) {
if(nchar(st)<2 || nchar(st)> 2)
{
stop("Invalid State")
}
outcsv <- read.csv("outcome-of-care-measures.csv");
hospitalname <- outcsv[,2]
state <- outcsv[,"State"]
HeartAttack <- as.numeric(as.character(outcsv[,11]))
HeartFailure <- as.numeric(as.character(outcsv[,17]))
Pneumonia <- as.numeric(as.character(outcsv[,23]))
#DatatobeManipulated<-data.frame(hospitalname,state,HeartAttack,HeartFailure,Pneumonia)
if(outcome == "heart attack"){
DatatobeManipulated<-data.frame(hospitalname,state,metrics=HeartAttack)
DatatobeManipulated<-DatatobeManipulated[order(hospitalname,state,DatatobeManipulated$metrics,decreasing = FALSE,na.last=NA),]
}
else if(outcome == "heart failure"){
DatatobeManipulated<-data.frame(hospitalname,state,metrics=HeartFailure)
DatatobeManipulated<-DatatobeManipulated[order(hospitalname,state,DatatobeManipulated$metrics,decreasing = FALSE,na.last=NA),]
}
else if(outcome == "pneumonia"){
DatatobeManipulated<-data.frame(hospitalname,state,metrics=Pneumonia)
DatatobeManipulated<-DatatobeManipulated[order(hospitalname,state,DatatobeManipulated$metrics,decreasing = FALSE,na.last=NA),]
}
#count the number of unique states
#states<-sort(unique(DatatobeManipulated[,"state"]))
#rankedhospitals <- vector()
#rankedhospitals <- data.frame(hospitalName = character(), State = character(), stringsAsFactors = FALSE)
#for(i in 1:length(states)){
statesSpecificData<-DatatobeManipulated[which(DatatobeManipulated$state == st),]
bes<-min(statesSpecificData$metrics)
hosNM<-as.character(statesSpecificData[which(statesSpecificData$metrics==bes),1])[1]
#}#end for
## Return a data frame with the hospital names and the (abbreviated)
## state name
# rankedhospitals <- as.data.frame(matrix(rankedhospitals, length(states), 2, byrow = TRUE))
#colnames(rankedhospitals) <- c("hospital", "state")
return(hosNM)
}
|
6a3c9d9a5d83dd5d4db86e31f1276be6c2532da3
|
8213941f015535abc4eda6aabaad02a6f31736de
|
/App.R
|
b4d64a7a921981abb2bf696863487bc79d9c6e52
|
[] |
no_license
|
mayank221/TABA-Assignment
|
515c40c820f322011fedb607c87b5452e47fc6b1
|
30822abd1a306e2dc4480a8a81eaaa0cf35a26c9
|
refs/heads/master
| 2020-06-25T11:02:57.629882
| 2019-07-28T19:51:16
| 2019-07-28T19:51:16
| 199,291,247
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,057
|
r
|
App.R
|
library("shiny")
shinyUI(
fluidPage(
titlePanel("Udipipe Shiny App"),
sidebarLayout(
sidebarPanel(
fileInput("Text_Input", "Upload English Text File in .txt format:"),
checkboxGroupInput("checkGroup", label = h3("Speech Tags"),
choices = list("Adjective" = "JJ" ,"Adverb" = "RB", "Proper Noun" = "NNP", "Noun" = "NN", "Verb" = "VB"),
selected = c("JJ","NN","NNP")),
hr(),
fluidRow(column(3, verbatimTextOutput("value"))),
submitButton(text = "Submit", icon("refresh"))),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Overview",
h4(p("Data input")),
p("This app supports only text files (.txt) data file.Please ensure that the text files are saved in UTF-8 Encoding format.",align="justify"),
h4('How to use this App'),
p("To use this app you need a english document in txt file format.\n\n
To upload the article text, click on Browse in left-sidebar panel and upload the txt file from your local machine. \n\n
Once the file is uploaded, the shinyapp will compute a text summary in the back-end with default inputs and accordingly results will be displayed in various tabs.", align = "justify"),
p('To use this app, click on',
span(strong("Upload Sample Text File for Analysis in .txt format:")))),
tabPanel("Annotated Documents", DT::dataTableOutput("mytable1"),downloadLink('Data', 'Download')),
tabPanel("Word Cloud",plotOutput('Word_Cloud_PLot')),tabPanel("Co-Occurence Plot",plotOutput('cooccurrence_plot')))
)
)
)
)
library(shiny)
library(udpipe)
library(textrank)
library(lattice)
library(igraph)
library(ggraph)
library(ggplot2)
library(wordcloud)
library(stringr)
library(readr)
library(rvest)
shinyServer(function(input, output) {
Text_Input_Data <- reactive({
if (is.null(input$Text_Input)) {
return(NULL) } else{
Data1 <- readLines(input$Text_Input$datapath,encoding = "UTF-8")
return(Data1)
}
})
output$cooccurrence_plot = renderPlot({
inputText <- as.character(Text_Input_Data())
model <- udpipe_download_model(language = "english")
model <- udpipe_load_model(model$file_model)
Data <- udpipe_annotate(model, x = inputText, doc_id = seq_along(inputText))
Data <- as.data.frame(Data)
print(Data)
co_occ <- cooccurrence(
x = subset(Data, Data$xpos %in% input$checkGroup), term = "lemma",
group = c("doc_id", "paragraph_id", "sentence_id"))
wordnetwork <- head(co_occ, 50)
wordnetwork <- igraph::graph_from_data_frame(wordnetwork)
ggraph(wordnetwork, layout = "fr") +
geom_edge_link(aes(width = cooc, edge_alpha = cooc), edge_colour = "orange") +
geom_node_text(aes(label = name), col = "darkgreen", size = 4) +
theme_graph(base_family = "Arial Narrow") +
theme(legend.position = "none") +
labs(title = "Cooccurrence Plot")
})
output$mytable1 <- DT::renderDataTable({
inputText <- as.character(Text_Input_Data())
model <- udpipe_download_model(language = "english")
model <- udpipe_load_model(model$file_model)
Data <- udpipe_annotate(model, x = inputText, doc_id = seq_along(inputText))
Data <- as.data.frame(Data)
Data <-Data[,-4]
DT::datatable(Data,options = list(pageLength = 100,orderClasses = TRUE),rownames = FALSE)
})
output$Data <- downloadHandler(
filename <- "Data.csv",
content = function(file) {
inputText <- as.character(Text_Input_Data())
model <- udpipe_download_model(language = "english")
model <- udpipe_load_model(model$file_model)
Data <- udpipe_annotate(model, x = inputText, doc_id = seq_along(inputText))
Data <- as.data.frame(Data)
Data <-Data[,-4]
write.csv(Data, file, row.names = FALSE)
}
)
output$Word_Cloud_PLot = renderPlot({
inputText <- as.character(Text_Input_Data())
inputText
model <- udpipe_download_model(language = "english")
model <- udpipe_load_model(model$file_model)
Data <- udpipe_annotate(model, x = inputText, doc_id = seq_along(inputText))
Data <- as.data.frame(Data)
Words = Data %>% subset(., xpos %in% input$checkGroup);
popular_words = txt_freq(Words$lemma)
wordcloud(words = popular_words$key,
freq = popular_words$freq,
min.freq = 2,
max.words = 100,
random.order = FALSE,
colors = brewer.pal(6, "Dark2"))
})
})
# Create Shiny app ----
shinyApp(ui, server)
|
5003529d520a7c492b6fcf68f672450768440642
|
8f98e70fef3d9e7f3dd1fd07f687e01995d0b6d7
|
/HW1/hw1_4_matrix2.R
|
ae6e17af255835d7cf693d244dbaa801f59e6868
|
[] |
no_license
|
QihangYang/Computational-Statistics
|
63814aa9ce6763f905db3665f1ed8f37391e7dfb
|
d26c30c3cdddecc7962144da1266439507cecfab
|
refs/heads/master
| 2020-12-22T00:14:32.193964
| 2020-04-10T00:02:23
| 2020-04-10T00:02:23
| 236,611,768
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,405
|
r
|
hw1_4_matrix2.R
|
# HW1: matrix3
#
# 1. Set the random seed as 5206. (hint: check the set.seed function)
# Save the random seed vector to `seed`.(hint: use the command seed <- .Random.seed)
# 2. Create a vector `v1` of length 30 by sampling from 1 to 30 without replacement.(hint: check the sample function)
# 3. Convert the vector `v1` into a 5 x 6 matrix `m1` filled by row.
# 4. Calculate the L-1 norm of matrix `m1` defined as the the maximum absolute column sum of the matrix and assign it to `n1`.
# 5. Calculate the L-infinity norm of matrix `m1` defined as the maximum absolute row sum of the matrix and assign it to `n2`.
# 6. Calculate the Frobenius norm of matrix `m1` defined as the square root of the sum of the squares of its elements and assign it to `n3`.
## Do not modify this line! ## Write your code for 1. after this line! ##
set.seed(5206)
seed <- .Random.seed
## Do not modify this line! ## Write your code for 2. after this line! ##
v1 <- sample(1:30, size = 30, replace = FALSE)
## Do not modify this line! ## Write your code for 3. after this line! ##
m1 <- t(matrix(v1, nrow = 6, ncol = 5))
## Do not modify this line! ## Write your code for 4. after this line! ##
n1 <- norm(m1, type = "1")
## Do not modify this line! ## Write your code for 5. after this line! ##
n2 <- norm(m1, type = "i")
## Do not modify this line! ## Write your code for 6. after this line! ##
n3 <- norm(m1, type = "f")
|
e17ac9457a3ccdf615b4b25c1cf2982c2ebe987b
|
6464efbccd76256c3fb97fa4e50efb5d480b7c8c
|
/paws/man/computeoptimizer_get_enrollment_status.Rd
|
02b01a6b2bd66af904097018dd9f83070fc07589
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
johnnytommy/paws
|
019b410ad8d4218199eb7349eb1844864bd45119
|
a371a5f2207b534cf60735e693c809bd33ce3ccf
|
refs/heads/master
| 2020-09-14T23:09:23.848860
| 2020-04-06T21:49:17
| 2020-04-06T21:49:17
| 223,286,996
| 1
| 0
|
NOASSERTION
| 2019-11-22T00:29:10
| 2019-11-21T23:56:19
| null |
UTF-8
|
R
| false
| true
| 711
|
rd
|
computeoptimizer_get_enrollment_status.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/computeoptimizer_operations.R
\name{computeoptimizer_get_enrollment_status}
\alias{computeoptimizer_get_enrollment_status}
\title{Returns the enrollment (opt in) status of an account to the AWS Compute
Optimizer service}
\usage{
computeoptimizer_get_enrollment_status()
}
\description{
Returns the enrollment (opt in) status of an account to the AWS Compute
Optimizer service.
}
\details{
If the account is a master account of an organization, this operation
also confirms the enrollment status of member accounts within the
organization.
}
\section{Request syntax}{
\preformatted{svc$get_enrollment_status()
}
}
\keyword{internal}
|
a089e2ba20f50978e39b5ceb6a724a07702fae55
|
8fe9874a997b45c0aaad7344ed63114b1e0aa3ca
|
/final/4_w2v_final.R
|
b6b12b639b48e35f971a387a6172a22f4ec6728b
|
[] |
no_license
|
Dongwoooon/BA562_cleaned
|
87a0a227e83f61fd74fcf286de6f462288eaaca3
|
11b022a6339107df24cdcf072a3f11f3dd3edee8
|
refs/heads/master
| 2021-01-23T10:35:59.103751
| 2017-09-27T05:50:33
| 2017-09-27T05:50:33
| 102,622,456
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,011
|
r
|
4_w2v_final.R
|
library(dplyr)
library(data.table)
library(wordVectors)
setwd('J:/data/BA562/final/2_Data')
dic = read.csv('keyword_dict.csv',stringsAsFactors=F)
load("train_str.Rdata") # train.str
load("test_str.Rdata") # test.str
tr.train <- merge(train.str,dic,by="QRY",all.x=FALSE, all.y=TRUE) ## 검색어 중 dictionary에 있는 단어에 대한 관측치만 남긴 것
tr.test <- merge(test.str,dic,by="QRY",all.x=FALSE, all.y=TRUE)
tr.train$CUS_ID <- as.numeric(as.character(tr.train$CUS_ID))
tr.test$CUS_ID <- as.numeric(as.character(tr.test$CUS_ID))
#### Convert data.frame to data.table for fast computing
#### cs data
cs <- read.csv("cs_merge_train_cut.csv",stringsAsFactors=F) %>%
select(CUS_ID, GENDER, AGE, GROUP)
cs <- cs %>% mutate(AGE_GROUP = substr(GROUP,2,3)) %>% select(-AGE)
cs.dt <- data.table(cs, key="CUS_ID") ### key를 지정해줌 / key를 통한 연산을 빠르게 가능
tr.dt <- data.table(tr.train, key="CUS_ID")
md.dt <- merge(cs.dt, tr.dt)
md.dt$QRY <- as.character(md.dt$QRY)
md.dt$GROUP <- as.character(md.dt$GROUP)
md.dt <- select(md.dt, -Freq)
######### search keyword를 잘 grouping 해주어서 분석해야함. 노가다로
# Make sites sentences
fgen <- function(x) {
grp <- md.dt[CUS_ID==x, GENDER][1] ###cus_id=x 인 애의 gender
act <- unique(md.dt[CUS_ID==x, QRY])
as.vector((sapply(1:20, function(x) c(grp, sample(act, length(act))))))
}
fage <- function(x) {
grp <- md.dt[CUS_ID==x, AGE_GROUP][1] ###cus_id=x 인 애의 age
act <- unique(md.dt[CUS_ID==x, QRY])
as.vector((sapply(1:20, function(x) c(grp, sample(act, length(act))))))
}
fgrp <- function(x){
grp <- md.dt[CUS_ID==x, GROUP][1] ###cus_id=x 인 애의 group
act <- unique(md.dt[CUS_ID==x, QRY])
as.vector((sapply(1:20, function(x) c(grp, sample(act, length(act))))))
}
items_gen <- unlist(sapply(unique(md.dt[,CUS_ID]), fgen))
items_age <- unlist(sapply(unique(md.dt[,CUS_ID]), fage))
items_grp <- unlist(sapply(unique(md.dt[,CUS_ID]), fgrp))
write.table(items_gen, "items_gen.txt", eol = " ", quote = F, row.names = F, col.names = F)
write.table(items_age, "items_age.txt", eol = " ", quote = F, row.names = F, col.names = F)
write.table(items_grp, "items_grp.txt", eol = " ", quote = F, row.names = F, col.names = F)
# Train site2vec model
model_gen = train_word2vec("items_gen.txt","vec_gen.bin",vectors=300,threads=3,window=5,cbow=1,negative_samples=10,iter=5,force = T)
model_age = train_word2vec("items_age.txt","vec_age.bin",vectors=300,threads=4,window=5,cbow=1,negative_samples=10,iter=5,force = T)
model_grp = train_word2vec("items_grp.txt","vec_grp.bin",vectors=300,threads=4,window=5,cbow=1,negative_samples=10,iter=5,force = T)
# Explore the model
for (v in unique(cs.dt[,GENDER])) print(closest_to(model_gen, v, n=31))
for (v in unique(cs.dt[,AGE_GROUP])) print(closest_to(model_age, v, n=31))
for (v in unique(cs.dt[,GROUP])) print(closest_to(model_grp, v, n=31))
|
9253fca43c9a809c87aefbc452b0f80e8c426dbe
|
6a28ba69be875841ddc9e71ca6af5956110efcb2
|
/Probability_And_Statistics_For_Engineers_And_Scientists_by_Ronald_E._Walpole,_Raymond_H._Myers,_Sharon_L._Myers,_Keying_Ye/CH1/EX1.2/Ex1_2.R
|
b577f66875be7c1da9738b250b9151e2b9373006
|
[] |
permissive
|
FOSSEE/R_TBC_Uploads
|
1ea929010b46babb1842b3efe0ed34be0deea3c0
|
8ab94daf80307aee399c246682cb79ccf6e9c282
|
refs/heads/master
| 2023-04-15T04:36:13.331525
| 2023-03-15T18:39:42
| 2023-03-15T18:39:42
| 212,745,783
| 0
| 3
|
MIT
| 2019-10-04T06:57:33
| 2019-10-04T05:57:19
| null |
UTF-8
|
R
| false
| false
| 619
|
r
|
Ex1_2.R
|
# Chapter 1
# Example 1.2 page no, 4 from the Pdf..
# To plot the Dotplot for the above data..
# package used "ggplot2" if not installed can be done using install.packages("ggplot2")
library(ggplot2)
obs <- c(0.32,0.53,0.28,0.37,0.47,0.43,0.36,0.42,0.38,0.43,0.26,0.43,0.47,0.49,0.52,0.75,0.79,0.86,0.62,0.46)
cat <- c(rep("no_nit",10),rep("nit",10))
data1 <- data.frame(obs,cat) # making it a data frame.
data1$f <- factor(data1$obs) # adding another variable to the data frame.
# Plot..
ggplot(data1,aes(x = f, y = obs, fill = cat)) + geom_dotplot(binaxis = 'y',stackdir = 'center')
|
e8760e1c3ed93ddcfe11908f4f127f02a907f06f
|
3f312cabe37e69f3a2a8c2c96b53e4c5b7700f82
|
/ver_devel/bio3d/man/pca.xyz.Rd
|
8b08f6a5795a9dbad60b9397973809462179b0a3
|
[] |
no_license
|
Grantlab/bio3d
|
41aa8252dd1c86d1ee0aec2b4a93929ba9fbc3bf
|
9686c49cf36d6639b51708d18c378c8ed2ca3c3e
|
refs/heads/master
| 2023-05-29T10:56:22.958679
| 2023-04-30T23:17:59
| 2023-04-30T23:17:59
| 31,440,847
| 16
| 8
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,820
|
rd
|
pca.xyz.Rd
|
\name{pca.xyz}
\alias{pca.xyz}
\alias{print.pca}
\title{ Principal Component Analysis }
\description{
Performs principal components analysis (PCA) on a \code{xyz}
numeric data matrix.
}
\usage{
\method{pca}{xyz}(xyz, subset = rep(TRUE, nrow(as.matrix(xyz))),
use.svd = FALSE, rm.gaps=FALSE, mass = NULL, \dots)
\method{print}{pca}(x, nmodes=6, \dots)
}
\arguments{
\item{xyz}{ numeric matrix of Cartesian coordinates with a row per
structure. }
\item{subset}{ an optional vector of numeric indices that selects a
subset of rows (e.g. experimental structures vs molecular dynamics
trajectory structures) from the full \code{xyz} matrix. Note: the
full \code{xyz} is projected onto this subspace.}
\item{use.svd}{ logical, if TRUE singular value decomposition (SVD) is
called instead of eigenvalue decomposition. }
\item{rm.gaps}{ logical, if TRUE gap positions (with missing
coordinate data in any input structure) are removed before
calculation. This is equivalent to removing NA cols from xyz. }
\item{x}{ an object of class \code{pca}, as obtained from function
\code{pca.xyz}. }
\item{nmodes}{ numeric, number of modes to be printed. }
\item{mass}{ a \sQuote{pdb} object or numeric vector of residue/atom masses.
By default (\code{mass=NULL}), mass is ignored. If provided
with a \sQuote{pdb} object, masses of all amino acids obtained from
\code{\link{aa2mass}} are used. }
\item{\dots}{ additional arguments to \code{\link{fit.xyz}}
(for \code{pca.xyz}) or to \code{print} (for \code{print.pca}). }
}
\note{
If \code{mass} is provided, mass weighted coordinates will be considered,
and iteration of fitting onto the mean structure is performed internally.
The extra fitting process is to remove external translation and rotation
of the whole system. With this option, a direct comparison can be made
between PCs from \code{\link{pca.xyz}} and vibrational modes from
\code{\link{nma.pdb}}, with the fact that
\deqn{A=k_BTF^{-1}}{A=k[B]TF^-1},
where \eqn{A} is the variance-covariance matrix, \eqn{F} the Hessian
matrix, \eqn{k_B}{k[B]} the Boltzmann's constant, and \eqn{T} the
temperature.
}
\value{
Returns a list with the following components:
\item{L }{eigenvalues.}
\item{U }{eigenvectors (i.e. the x, y, and z variable loadings).}
\item{z }{scores of the supplied \code{xyz} on the pcs.}
\item{au }{atom-wise loadings (i.e. xyz normalized eigenvectors).}
\item{sdev }{the standard deviations of the pcs.}
\item{mean }{the means that were subtracted.}
}
\references{
Grant, B.J. et al. (2006) \emph{Bioinformatics} \bold{22}, 2695--2696.
}
\author{ Barry Grant }
\seealso{
\code{\link{pca}}, \code{\link{pca.pdbs}},
\code{\link{plot.pca}}, \code{\link{mktrj.pca}},
\code{\link{pca.tor}}, \code{\link{project.pca}} }
\examples{
\dontrun{
#-- Read transducin alignment and structures
aln <- read.fasta(system.file("examples/transducin.fa",package="bio3d"))
pdbs <- read.fasta.pdb(aln)
# Find core
core <- core.find(pdbs,
#write.pdbs = TRUE,
verbose=TRUE)
rm(list=c("pdbs", "core"))
}
#-- OR for demo purposes just read previously saved transducin data
attach(transducin)
# Previously fitted coordinates based on sub 1.0A^3 core. See core.find() function.
xyz <- pdbs$xyz
#-- Do PCA ignoring gap containing positions
pc.xray <- pca.xyz(xyz, rm.gaps=TRUE)
# Plot results (conformer plots & scree plot overview)
plot(pc.xray, col=annotation[, "color"])
# Plot a single conformer plot of PC1 v PC2
plot(pc.xray, pc.axes=1:2, col=annotation[, "color"])
## Plot atom wise loadings
plot.bio3d(pc.xray$au[,1], ylab="PC1 (A)")
\donttest{
# PDB server connection required - testing excluded
## Plot loadings in relation to reference structure 1TAG
pdb <- read.pdb("1tag")
ind <- grep("1TAG", pdbs$id) ## location in alignment
resno <- pdbs$resno[ind, !is.gap(pdbs)] ## non-gap residues
tpdb <- trim.pdb(pdb, resno=resno)
op <- par(no.readonly=TRUE)
par(mfrow = c(3, 1), cex = 0.6, mar = c(3, 4, 1, 1))
plot.bio3d(pc.xray$au[,1], resno, ylab="PC1 (A)", sse=tpdb)
plot.bio3d(pc.xray$au[,2], resno, ylab="PC2 (A)", sse=tpdb)
plot.bio3d(pc.xray$au[,3], resno, ylab="PC3 (A)", sse=tpdb)
par(op)
}
\dontrun{
# Write PC trajectory
resno = pdbs$resno[1, !is.gap(pdbs)]
resid = aa123(pdbs$ali[1, !is.gap(pdbs)])
a <- mktrj.pca(pc.xray, pc=1, file="pc1.pdb",
resno=resno, resid=resid )
b <- mktrj.pca(pc.xray, pc=2, file="pc2.pdb",
resno=resno, resid=resid )
c <- mktrj.pca(pc.xray, pc=3, file="pc3.pdb",
resno=resno, resid=resid )
}
detach(transducin)
}
\keyword{ utilities }
\keyword{ multivariate }
|
562096e200566c93ae1b1f91623323ef6e55214e
|
256f220648296026714d24947d25be71c9d5cf09
|
/gen_supplmentary_figure.R
|
ecf1bdf73ca2f169d84a9c820634d07d2b3344c5
|
[] |
no_license
|
Xiaojieqiu/Census_BEAM
|
f07f9d37f20646469a14f9e88d459b1b6046d662
|
b84a377f5890bc7829dc1565c4c4d2dc2c824f83
|
refs/heads/master
| 2021-03-22T05:03:42.708956
| 2015-11-14T20:12:17
| 2015-11-14T20:12:17
| 45,900,189
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 42,551
|
r
|
gen_supplmentary_figure.R
|
library(monocle)
library(xacHelper)
load_all_libraries()
# load('analysis_other_supplementary_data.RData')
# load('analysis_lung_data.RData')
load('analysis_HSMM_data.RData')
##############################################################################################################
####generate the SI figures for HSMM data:
pdf('eLife_figSI_fpkm_HSMM_tree.pdf', width = 1.5, height = 1.2)
plot_spanning_tree(std_HSMM, color_by="Time", show_backbone=T, backbone_color = 'black',
markers=NULL, show_cell_names = F, show_all_lineages = F, cell_size = 1, cell_link_size = 0.2) + nm_theme() #+ scale_size(range = c(0.5, .5))
dev.off()
pdf('eLife_figSI_abs_HSMM_tree.pdf', width = 1.5, height = 1.2)
plot_spanning_tree(HSMM_myo, color_by="Time", show_backbone=T, backbone_color = 'black',
markers=NULL, show_cell_names = F, show_all_lineages = F, cell_size = 1, cell_link_size = 0.2) + nm_theme() #+ scale_size(range = c(0.5, .5))
dev.off()
plot_tree_pairwise_cor2 <- function (std_tree_cds, absolute_tree_cds)
{
maturation_df <- data.frame(cell = rep(colnames(std_tree_cds),
2), maturation_level = 100 * c(pData(std_tree_cds)$Pseudotime/max(pData(std_tree_cds)$Pseudotime),
pData(absolute_tree_cds)$Pseudotime/max(pData(absolute_tree_cds)$Pseudotime)),
Type = rep(c("FPKM", "Transcript counts (vst)"), each = ncol(std_tree_cds)), rownames = colnames(absolute_tree_cds))
cor.coeff <- cor(pData(absolute_tree_cds)$Pseudotime, pData(std_tree_cds)$Pseudotime,
method = "spearman")
message(cor.coeff)
p <- ggplot(aes(x = maturation_level, y = Type, group = cell),
data = maturation_df) + geom_point(size = 1) + geom_line(color = "blue", alpha = .3) +
xlab("Pseudotime") + ylab("Type of tree construction") + monocle_theme_opts()
return(p)
}
pdf('eLife_figSI_cmpr_tree.pdf', width = 4, height = 2)
plot_tree_pairwise_cor2(std_HSMM, HSMM_myo) + nm_theme()
dev.off()
element_all <- c(row.names(HSMM_myo_size_norm_res[HSMM_myo_size_norm_res$qval <0.1, ]),
row.names(std_HSMM_myo_pseudotime_res_ori[std_HSMM_myo_pseudotime_res_ori$qval <0.1, ]))
sets_all <- c(rep(paste('Transcript counts (Size + VST)', sep = ''), nrow(HSMM_myo_size_norm_res[HSMM_myo_size_norm_res$qval <0.1, ])),
rep(paste('FPKM', sep = ''), nrow(std_HSMM_myo_pseudotime_res_ori[std_HSMM_myo_pseudotime_res_ori$qval <0.1, ])))
pdf('eLife_figSI_transcript_counts_HSMM_overlapping.pdf')
venneuler_venn(element_all, sets_all)
dev.off()
table(sets_all) #number of genes
muscle_df$data_type = c("Transcript (size normalization)", "Transcript (size normalization)", "FPKM", "FPKM")
muscle_df$class = '3relative'
muscle_df.1 <- muscle_df
muscle_df.1 <- muscle_df[1:2, ]
#qplot(factor(Type), value, stat = "identity", geom = 'bar', position = 'dodge', fill = I("red"), data = melt(muscle_df)) + #facet_wrap(~variable) +
# ggtitle(title) + scale_fill_discrete('Type') + xlab('Type') + ylab('') + facet_wrap(~variable, scales = 'free_x') + theme(axis.text.x = element_text(angle = 30, hjust = .9)) +
# ggtitle('') + monocle_theme_opts() + theme(strip.text.x = element_blank(), strip.text.y = element_blank()) + theme(strip.background = element_blank())
# muscle_df <- muscle_df[1:2, ] #select only the transcript counts data:
muscle_df[, 'Type'] <- c('Monocle', 'DESeq', 'DESeq', 'Monocle')
colnames(muscle_df)[1:3] <- c('Precision', 'Recall', 'F1')
pdf('muscle_cmpr_pseudotime_test.pdf')
qplot(factor(Type), value, stat = "identity", geom = 'bar', position = 'dodge', fill = data_type, data = melt(muscle_df), log = 'y') + #facet_wrap(~variable) +
ggtitle(title) + scale_fill_discrete('Type') + xlab('') + ylab('') + facet_wrap(~variable, scales = 'free_x') + theme(axis.text.x = element_text(angle = 30, hjust = .9)) +
ggtitle('') + monocle_theme_opts() + theme(strip.text.x = element_blank(), strip.text.y = element_blank()) + theme(strip.background = element_blank()) + ylim(0, 1) +
theme(strip.background = element_blank(), strip.text.x = element_blank()) + nm_theme()
dev.off()
##############################################################################################################
# # figure b:
# #concordance between alernative analysis improves when absolute copy numbers are used:
# #(overlapping plot between absolute copy / read counts)
# #read counts:
# default_deseq_p[is.na(default_deseq_p)] <- 1
# default_deseq2_p[is.na(default_deseq2_p)] <- 1
# default_edgeR_p[is.na(default_edgeR_p)] <- 1
# element_all <- c(
# names(default_edgeR_p[default_edgeR_p < 0.01]),
# names(default_deseq2_p[default_deseq2_p < 0.01]),
# names(readcount_permutate_pval[which(readcount_permutate_pval < .01)]),
# names(default_deseq_p[default_deseq_p < 0.01]),
# names(monocle_p_readcount[monocle_p_readcount < 0.01]),
# names(scde_p[scde_p < 0.01]))
# sets_all <- c(
# rep(paste('edgeR', sep = ''), sum(default_edgeR_p < 0.01, na.rm = T)),
# rep(paste('DESeq2', sep = ''), sum(default_deseq2_p < 0.01, na.rm = T)),
# rep(paste('Permutation test', sep = ''), length(which(readcount_permutate_pval < .01))),
# rep(paste('DESeq', sep = ''), length(default_deseq_p[default_deseq_p < 0.01])),
# rep(paste('Monocle', sep = ''), length(monocle_p_readcount[monocle_p_readcount < 0.01])),
# rep(paste('SCDE', sep = ''), length(scde_p[scde_p < 0.01])))
# pdf(paste(elife_directory, 'eLife_fig2c.1.pdf', sep = ''))
# venneuler_venn(element_all, sets_all)
# table(sets_all)
# dev.off()
# #absolute transcript counts:
# abs_default_deseq_p[is.na(abs_default_deseq_p)] <- 1
# abs_default_deseq2_p[is.na(abs_default_deseq2_p)] <- 1
# abs_default_edgeR_p[is.na(abs_default_edgeR_p)] <- 1
# abs_element_all <- c(
# names(abs_default_edgeR_p[abs_default_edgeR_p < 0.01]),
# names(abs_default_deseq2_p[abs_default_deseq2_p < 0.01]),
# names(new_abs_size_norm_monocle_p_ratio_by_geometric_mean[which(new_abs_size_norm_monocle_p_ratio_by_geometric_mean < .01)]),
# names(abs_default_deseq_p[abs_default_deseq_p < 0.01]),
# names(abs_scde_p[abs_scde_p < 0.01]),
# names(mode_size_norm_permutate_ratio_by_geometric_mean[which(mode_size_norm_permutate_ratio_by_geometric_mean < 0.01)]))
# abs_sets_all <- c(
# rep(paste('edgeR', sep = ''), sum(abs_default_edgeR_p < 0.01, na.rm = T)),
# rep(paste('DESeq2', sep = ''), sum(abs_default_deseq2_p < 0.01, na.rm = T)),
# rep(paste('Monocle', sep = ''), length(new_abs_size_norm_monocle_p_ratio_by_geometric_mean[new_abs_size_norm_monocle_p_ratio_by_geometric_mean < 0.01])),
# rep(paste('DESeq', sep = ''), sum(abs_default_deseq_p < 0.01, na.rm = T)),
# rep(paste('SCDE', sep = ''), length(abs_scde_p[abs_scde_p < 0.01])),
# rep(paste('Permutation test', sep = ''), length(which(mode_size_norm_permutate_ratio_by_geometric_mean < 0.01))))
# pdf(paste(elife_directory, 'eLife_fig2c.2.pdf', sep = ''))
# venneuler_venn(abs_element_all, abs_sets_all)
# dev.off()
# table(sets_all)
# #add the barplot for the overlapping genes:
# element_all_list <- list(
# names(default_edgeR_p[default_edgeR_p < 0.01]),
# names(default_deseq2_p[default_deseq2_p < 0.01]),
# names(readcount_permutate_pval[which(readcount_permutate_pval < .01)]),
# names(default_deseq_p[default_deseq_p < 0.01]),
# names(monocle_p_readcount[monocle_p_readcount < 0.01]))
# abs_element_all_list <- list(
# names(abs_default_edgeR_p[abs_default_edgeR_p < 0.01]),
# names(abs_default_deseq2_p[abs_default_deseq2_p < 0.01]),
# names(new_abs_size_norm_monocle_p_ratio_by_geometric_mean[which(new_abs_size_norm_monocle_p_ratio_by_geometric_mean < .01)]),
# names(abs_default_deseq_p[abs_default_deseq_p < 0.01]),
# names(mode_size_norm_permutate_ratio_by_geometric_mean[which(mode_size_norm_permutate_ratio_by_geometric_mean < 0.01)]))
# readcount_overlap <- Reduce(intersect, element_all_list)
# readcount_union <- Reduce(union, element_all_list)
# abs_overlap <- Reduce(intersect, abs_element_all_list)
# abs_union <- Reduce(union, abs_element_all_list)
# overlap_df <- data.frame(read_counts = length(readcount_overlap), transcript_counts = length(abs_overlap))
# union_df <- data.frame(read_counts = length(readcount_union), transcript_counts = length(abs_union))
# pdf('eLife_fig_SI_DEG_overlapping.pdf', width = 1, height = 1.1)
# qplot(variable, value, geom = 'bar', stat = 'identity', fill = variable, data = melt(overlap_df)) + xlab('') + ylab('number') + nm_theme() + theme(axis.text.x = element_text(angle = 30, hjust = .9))
# dev.off()
# pdf('eLife_fig_SI_DEG_union.pdf', width = 1, height = 1.1)
# qplot(variable, value, geom = 'bar', stat = 'identity', fill = variable, data = melt(union_df)) + xlab('') + ylab('number') + nm_theme() + theme(axis.text.x = element_text(angle = 30, hjust = .9))
# dev.off()
# #
# #test the cell cycle:
# #cyclin E, CDK2, Cyclin A, CDK1, CDK2, Cyclin B, CDK1
# #CCNE1, CCNE2;
# #CDK2
# #CCNA1, CCNA2
# #CCNB1, CCNB2
# cc_markers <- which(fData(abs_AT12_cds_subset_all_gene)$gene_short_name %in% c('Ccne1', 'Ccne2', 'Cdk2', 'Ccna1', 'Ccna2', 'Ccnb1', 'Ccnb2', 'Cdk1'))
# colour_cell <- rep(0, length(new_cds$Lineage))
# names(colour_cell) <- as.character(new_cds$Time)
# colour_cell[names(colour_cell) == 'E14.5'] <- "#7CAF42"
# colour_cell[names(colour_cell) == 'E16.5'] <- "#00BCC3"
# colour_cell[names(colour_cell) == 'E18.5'] <- "#A680B9"
# colour_cell[names(colour_cell) == 'Adult'] <- "#F3756C"
# colour <- rep(0, length(new_cds$Lineage))
# names(colour) <- as.character(new_cds$Lineage)
# colour[names(colour) == 'AT1'] <- AT1_Lineage
# colour[names(colour) == 'AT2'] <- AT2_Lineage
# pdf('Cell_cycle.pdf', width = 2, height = 3)
# plot_genes_branched_pseudotime2(abs_AT12_cds_subset_all_gene[cc_markers, ], cell_color_by = "Time", trajectory_color_by = "Lineage", fullModelFormulaStr = '~sm.ns(Pseudotime, df = 3)*Lineage', normalize = F, stretch = T, lineage_labels = c('AT1', 'AT2'), cell_size = 1, ncol = 2) + ylab('Transcript counts') ##nm_theme()
# dev.off()
# #Shalek. show all the cells on the same graph:
# Shalek_abs_subset <- Shalek_abs[,pData(Shalek_abs)$experiment_name %in% c('Ifnar1_KO_LPS', 'Stat1_KO_LPS', "LPS", "LPS_GolgiPlug", "Unstimulated_Replicate")]
# pData(Shalek_abs_subset)$Total_mRNAs <- colSums(exprs(Shalek_abs_subset))
# Shalek_abs_subset <- Shalek_abs_subset[, pData(Shalek_abs_subset)$Total_mRNAs < 75000]
# DEG_union <- c(row.names(subset(Shalek_LPS_subset_DEG_res, qval < qval_thrsld)))
# Shalek_abs_subset <- setOrderingFilter(Shalek_abs_subset, DEG_union)
# Shalek_abs_subset <- reduceDimension(Shalek_abs_subset, use_vst = T, use_irlba=F, pseudo_expr = 0, covariates = as.vector(pData(Shalek_abs_subset)$num_genes_expressed) )
# Shalek_abs_subset <- orderCells(Shalek_abs_subset, num_path = 5)
# pdf('figure_SI_all_cells_tree.pdf', width = 12, height = 7)
# monocle::plot_spanning_tree(Shalek_abs_subset, color_by="interaction(experiment_name, time)", cell_size=5) +
# scale_color_manual(values=shalek_custom_color_scale_plus_states)
# dev.off()
# pdf('all_shalek_cell.pdf', width = 20, height = 20)
# plot_spanning_tree(Shalek_abs_subset, color_by="interaction(experiment_name, time)", cell_size=5) + #x = 1, y = 2,
# scale_color_manual(values=shalek_custom_color_scale_plus_states)
# dev.off()
# #Explaining why E16.5d cell has bad correspondence:
# #fraction of clusters in each biotype:
# valid_class <- c("lincRNA", "processed_transcript", "protein_coding", "pseudogene", 'spike', "rRNA")
# gene_class <- fData(read_countdata_cds)$biotype
# read_countdata_cds_biotype <- apply(read_countdata_cds, 2, function(x) {
# sum_x <- sum(x)
# c(lincRNA = sum(x[gene_class == valid_class[1]]) / sum_x,
# processed_transcript = sum(x[gene_class == valid_class[2]]) / sum_x,
# protein_coding = sum(x[gene_class == valid_class[3]]) / sum_x,
# pseudogene = sum(x[gene_class == valid_class[4]]) / sum_x,
# MT_RNA = sum(x[gene_class %in% c('Mt_rRNA', 'Mt_tRNA')]) / sum_x,
# spike = sum(x[gene_class == valid_class[5]]) / sum_x,
# rRNA = sum(x[gene_class == valid_class[6]]) / sum_x,
# others = sum(x[!(gene_class %in% c(valid_class, 'Mt_rRNA', 'Mt_tRNA'))]) / sum_x
# )
# })
# mlt_read_countdata_cds_biotype <- melt(read_countdata_cds_biotype)
# mlt_read_countdata_cds_biotype$Time <- pData(standard_cds)[mlt_read_countdata_cds_biotype$Var2, 'Time']
# pdf('gene_type_percentage.pdf', width = 2, height = 3)
# qplot(Var2, value, geom = 'histogram', fill = Var1, data = mlt_read_countdata_cds_biotype, stat = 'identity', group = Time) + facet_wrap(~Time, scale = 'free_x') + monocle_theme_opts()
# dev.off()
# #number of read counts for spikein data:
# df <- data.frame(Time = pData(read_countdata_cds)$Time, sum_readcounts = esApply(read_countdata_cds[fData(read_countdata_cds)$biotype == 'spike', ], 2, sum))
# # qplot(sum_readcounts, fill = Time, log = 'x') + facet_wrap(~Time)
# pdf('read_countdata_cds_sum_spikein.pdf', width = 2, height = 3)
# qplot(sum_readcounts, fill = Time, log = 'x', data = df) + facet_wrap(~Time, ncol = 1, scales = 'free_y') + nm_theme()
# dev.off()
# #number of ERCC spike-in detected in each cell
# ercc_controls_detected_df <- data.frame(loss = esApply(ercc_controls, 2, function(x) sum(x > 0)), Time = pData(absolute_cds[, colnames(loss_ercc_spikein)])$Time)
# qplot(loss, fill = Time, data = ercc_controls_detected_df) + facet_wrap(~Time, ncol = 1) + nm_theme()
# ggsave(filename = paste(elife_directory, '/SI/spikein_detected.pdf', sep = ''), width = 2, height = 3)
# #readcount for the Shalek data: The Shalek data is great
# #read the read count data for the genes:
# dir = "/net/trapnell/vol1/ajh24/proj/2015shalek_et_al_reanalysis/results/ahill/2015_05_07_input_files_for_monocle/cuffnorm_output_files/"
# Shalek_sample_table <- read.delim(paste(dir, "/samples.table", sep = ''))
# Shalek_norm_count <- read.delim(paste(dir, "/genes.count_table", sep = ''))
# row.names(Shalek_norm_count) <- Shalek_norm_count$tracking_id
# Shalek_norm_count <- Shalek_norm_count[, -1]
# Shalek_read_countdata <- round(t(t(Shalek_norm_count) * Shalek_sample_table$internal_scale)) #convert back to the raw counts
# Shalek_read_countdata <- Shalek_read_countdata[row.names(Shalek_abs), paste(colnames(Shalek_abs), '_0', sep = '')]
# colnames(Shalek_read_countdata) <- colnames(Shalek_abs)
# Shalek_read_countdata_cds <- newCellDataSet(as.matrix(Shalek_read_countdata),
# phenoData = new("AnnotatedDataFrame", data = pData(Shalek_abs)),
# featureData = new("AnnotatedDataFrame", data = fData(Shalek_abs)),
# expressionFamily = negbinomial(),
# lowerDetectionLimit = 1)
# pData(Shalek_read_countdata_cds)$Total_mRNAs <- esApply(Shalek_read_countdata_cds, 2, sum)
# pData(Shalek_read_countdata_cds)$endogenous_RNA <- esApply(Shalek_read_countdata_cds, 2, sum)
# Shalek_gene_df <- data.frame(experiment_name = pData(Shalek_read_countdata_cds[, c(colnames(Shalek_abs_subset_ko_LPS), colnames(Shalek_golgi_update))])$experiment_name,
# sum_readcounts = esApply(Shalek_read_countdata_cds[, c(colnames(Shalek_abs_subset_ko_LPS), colnames(Shalek_golgi_update))], 2, sum))
# pdf('Shalek_readcounts.pdf', width = 2, height = 3)
# qplot(sum_readcounts, fill = experiment_name, log = 'x', data = Shalek_gene_df) + facet_wrap(~Time, ncol = 1, scales = 'free_y') + nm_theme()
# dev.off()
# # gene_names <- row.names(abs_branchTest_res_stretch[(abs_branchTest_res_stretch$qval < 0.05 & !is.na(abs_branchTest_res_stretch$ABCs)), ])[1:2881]
# #fit of distributions
# #test this:
# # abs_gd_fit_res <- mcesApply(absolute_cds[ ], 1, gd_fit_pval, cores = detectCores(), required_packages = c('VGAM', 'fitdistrplus', 'MASS', 'pscl'), exprs_thrsld = 10, pseudo_cnt = 0.01)
# # closeAllConnections()
# # std_gd_fit_res <- mcesApply(standard_cds[, ], 1, gd_fit_pval, cores = detectCores(), required_packages = c('VGAM', 'fitdistrplus', 'MASS', 'pscl'), exprs_thrsld = 10, pseudo_cnt = 0.01)
# # closeAllConnections()
# # tpm_gd_fit_res <- mcesApply(TPM_cds[, ], 1, gd_fit_pval, cores = detectCores(), required_packages = c('VGAM', 'fitdistrplus', 'MASS', 'pscl'), exprs_thrsld = 10, pseudo_cnt = 0.01)
# # closeAllConnections()
# # read_gd_fit_res <- mcesApply(count_cds[, ], 1, gd_fit_pval, cores = detectCores(), required_packages = c('VGAM', 'fitdistrplus', 'MASS', 'pscl'), exprs_thrsld = 10, pseudo_cnt = 0.01)
# abs_gd_fit_res <- unlist(abs_gd_fit_res)
# read_gd_fit_res <- unlist(read_gd_fit_res)
# abs_gd_fit_df <- matrix(abs_gd_fit_res, nrow(absolute_cds), ncol = 11, byrow = T)
# dimnames(abs_gd_fit_df) <- list(row.names(absolute_cds), c("ln_pvalue", "nb_pvalue", "ln_pvalue.glm.link", "ln_pvalue.glm.log", "ln_pvalue.chisq", "nb_pvalue.glm", "nb_pvalue.chisq", "zinb_pvalue.chisq", "zanb_pvalue.chisq", "zinb_pvalue", "zanb_pvalue"))
# read_gd_fit_df <- matrix(read_gd_fit_res, nrow(absolute_cds), ncol = 11, byrow = T)
# dimnames(read_gd_fit_df) <- list(row.names(absolute_cds), c("ln_pvalue", "nb_pvalue", "ln_pvalue.glm.link", "ln_pvalue.glm.log", "ln_pvalue.chisq", "nb_pvalue.glm", "nb_pvalue.chisq", "zinb_pvalue.chisq", "zanb_pvalue.chisq", "zinb_pvalue", "zanb_pvalue"))
# #
# # select only nb and zinb and calculate the number of genes pass goodness of fit and number of genes can be fitted:
# valid_gene_id_20_cell <- row.names(absolute_cds[which(rowSums(exprs(standard_cds) >= 1) > 50), ])
# abs_gd_fit_res <- cal_gd_statistics(abs_gd_fit_df[, c('nb_pvalue', 'zinb_pvalue')], percentage = F, type = 'absolute')#, gene_list = valid_gene_id_20_cell)
# readcount_gd_fit_res <- cal_gd_statistics(read_gd_fit_df[, c('nb_pvalue', 'zinb_pvalue')], percentage = F, type = 'readcount')#, gene_list = valid_gene_id_20_cell)
# gd_fit_res <- rbind(abs_gd_fit_res, readcount_gd_fit_res)
# gd_fit_res <- cbind(gd_fit_res, data_type = row.names(gd_fit_res))
# row.names(gd_fit_res) <- NULL
# gd_fit_res <- as.data.frame(gd_fit_res)
# gd_fit_res_num <- subset(gd_fit_res, data_type == 'gd_fit_num')
# gd_fit_res_success_num <- subset(gd_fit_res, data_type == 'success_fit_num')
# #
# #generate the result of goodness of fit for each gene:
# colnames(gd_fit_res_num)[1:2] <- c('NB', 'ZINB')
# test <- melt(gd_fit_res_num[, 1:3], id.vars = 'type')
# p1 <- qplot(as.factor(variable), as.numeric(value), geom = 'bar', stat = 'identity', data = test, fill = type) + facet_wrap('type') + nm_theme() +
# theme(legend.position = 'none') + xlab('Fit types') + ylab('number of genes') + theme(strip.background = element_blank(),
# strip.text.x = element_blank()) + theme(axis.text.x = element_text(angle = 30, hjust = .9))
# pdf('goodness_fit.pdf', height = 1.5, width = 1)
# p1 + xlab('')
# dev.off()
# colnames(gd_fit_res_success_num)[1:2] <- c('NB', 'ZINB')
# test <- melt(gd_fit_res_success_num[, 1:3], id.vars = 'type')
# p2 <- qplot(as.factor(variable), as.numeric(value), geom = 'bar', stat = 'identity', data = test, fill = type) + facet_wrap('type') + nm_theme() +
# theme(legend.position = 'none') + xlab('Fit types') + ylab('number of genes') + theme(strip.background = element_blank(),
# strip.text.x = element_blank()) + theme(axis.text.x = element_text(angle = 30, hjust = .9))
# pdf('goodness_fit2.pdf', width = 2, height = 3)
# p2 + xlab('')
# dev.off()
# #fig 3 SI:
# quake_all_modes <- estimate_t(exprs(isoform_count_cds), return_all = T)
# cell_nanmes <- c("SRR1033974_0", "SRR1033922_0", "SRR1033866_0")
# cell_id <- which(colnames(isoform_count_cds) %in% cell_nanmes)
# three_cell_iso_df <- data.frame(Cell_id = rep(row.names(quake_all_modes)[cell_id], each = nrow(isoform_count_cds)),
# log10_FPKM = log10(c(exprs(isoform_count_cds)[, cell_id[1]], exprs(isoform_count_cds)[, cell_id[2]], exprs(isoform_count_cds)[, cell_id[3]])),
# Cell_mode = rep(log10(quake_all_modes[cell_id, 1]), each = nrow(isoform_count_cds)))
# three_cell_iso_df <- data.frame(Cell_id = rep(row.names(quake_all_modes)[which(quake_all_modes$best_cov_dmode <= 2)], each = nrow(isoform_count_cds)),
# log10_FPKM = log10(c(exprs(isoform_count_cds)[, which(quake_all_modes$best_cov_dmode <= 2)])),
# Cell_mode = rep(log10(quake_all_modes[which(quake_all_modes$best_cov_dmode <= 2), 1]), each = nrow(isoform_count_cds)))
# pdf('eLife_fig4_SI.pdf', width = 2, height = 3)
# qplot(x = log10_FPKM, geom = 'histogram', data = three_cell_iso_df[, ], binwidth = .05, color = I('red')) +
# geom_vline(aes(xintercept=log10(Cell_mode)), color = 'blue') + facet_wrap(~Cell_id) + xlim(-3, 5) + monocle_theme_opts() + xlab('log10 FPKM') + ylab('Isoform counts') + nm_theme()
# dev.off()
# 10^mapply(function(cell_dmode, model) {
# predict(model, newdata = data.frame(log_fpkm = cell_dmode), type = 'response')
# }, as.list(unique(three_cell_iso_df$Cell_mode)), molModels_select[c(1,9,14)])
# #################### generate the figures for FigSC6: ###################
# #test on three other datasets for the differential gene expression:
# #quake new data:
# #NBt data:
# #molecular cell data:
# #several UMI data (use two Drop-seq):
# #test mode, and the regression relationship between FPKM and UMI dataset (are the k/b also on a line)
# #differential gene expression test and comparing fitting of NB
# #check the influence of spike-in free estimation:
# spike_free_standard_cds <- exprs(standard_cds)[1:transcript_num, ]
# pd <- new("AnnotatedDataFrame", data = pData(standard_cds)[colnames(spike_free_standard_cds),])
# fd <- new("AnnotatedDataFrame", data = fData(standard_cds)[rownames(spike_free_standard_cds),])
# spike_free_TPM <- newCellDataSet(apply(spike_free_standard_cds, 2, function(x) x / sum(x) * 10^6),
# phenoData = pd,
# featureData = fd,
# expressionFamily=tobit(),
# lowerDetectionLimit=1)
# pd <- new("AnnotatedDataFrame", data = pData(isoform_count_cds)[colnames(isoform_count_cds),])
# fd <- new("AnnotatedDataFrame", data = fData(isoform_count_cds)[rownames(isoform_count_cds)[1:(nrow(TPM_isoform_count_cds) - 97)],])
# spike_free_TPM_isoform_count_cds <- newCellDataSet(esApply(TPM_isoform_count_cds[1:(nrow(TPM_isoform_count_cds) - 97), ], 2, function(x) x / sum(x) * 10^6),
# phenoData = pd,
# featureData = fd,
# expressionFamily = tobit(),
# lowerDetectionLimit=1)
# #recover the transcript counts with the new algorithm (lower end ladder removed):
# spike_free_Quake_norm_cds_optim_weight_fix_c <- relative2abs_optim_fix_c(relative_expr_matrix = exprs(spike_free_TPM), t_estimate = estimate_t(spike_free_TPM_isoform_count_cds, relative_expr_thresh = .1),
# alpha_v = 1, total_RNAs = 50000, weight = 0.01,
# verbose = T, return_all = T, cores = 2, m = -4.864207, c = mean(mean_m_c_select[1, ]))
# spike_free_optim_sum <- apply(Quake_norm_cds_optim_weight_fix_c$norm_cds[1:transcript_num, ], 2, sum)
# pdf('endogenous_RNA.pdf', width = 2, height = 3)
# qplot(pData(absolute_cds)$endogenous_RNA[pData(absolute_cds)$endogenous_RNA > 1e3],
# spike_free_optim_sum[pData(absolute_cds)$endogenous_RNA > 1e3], log="xy", color=pData(absolute_cds)$Time[pData(absolute_cds)$endogenous_RNA > 1e3], size = I(1)) +
# geom_smooth(method="rlm", color="black", size = .1) + geom_abline(color="red") +
# xlab("Total endogenous mRNA \n (spike-in)") +
# ylab("Total endogenous mRNA \n (spike-in free algorithm)") + #scale_size(range = c(0.25, 0.25)) +
# scale_color_discrete(name = "Time points") + nm_theme()
# dev.off()
# #benchmark the branching test (overlapping with group test as well as pseudotime tests):
# #AT12_cds_subset_all_gene: remove the Cilia and Clara cells
# abs_group_test_res <- differentialGeneTest(abs_AT12_cds_subset_all_gene,
# fullModelFormulaStr = "~Time",
# reducedModelFormulaStr = "~1", cores = detectCores(), relative = F)
# abs_pseudotime_test_res <- differentialGeneTest(abs_AT12_cds_subset_all_gene,
# fullModelFormulaStr = "~sm.ns(Pseudotime, df = 3)",
# reducedModelFormulaStr = "~1", cores = detectCores(), relative = F)
# #test whether or not the weight influence the results:
# abs_AT12_cds_subset_all_gene_res_no_weight <- branchTest(abs_AT12_cds_subset_all_gene[, ], cores = detectCores(), relative_expr = F, weighted = F)
# abs_AT12_cds_subset_all_gene_res_no_weight_relative <- branchTest(abs_AT12_cds_subset_all_gene[, ], cores = detectCores(), relative_expr = T, weighted = F)
# DEG_time_sets <- list(abs_group_test_res = row.names(abs_group_test_res[which(abs_group_test_res$qval < .01), ]),
# abs_pseudotime_test_res = row.names(abs_pseudotime_test_res[abs_pseudotime_test_res$qval < 0.01, ]),
# abs_AT12_cds_subset_all_gene_res = row.names(abs_AT12_cds_subset_all_gene_res[abs_AT12_cds_subset_all_gene_res$qval < 0.01, ]),
# abs_AT12_cds_subset_all_gene_res_no_weight = row.names(abs_AT12_cds_subset_all_gene_res_no_weight[abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01, ]))
# overlap_genes <- Reduce(intersect, DEG_time_sets)
# pseudotime_element_all <- c(row.names(abs_group_test_res[which(abs_group_test_res$qval < .01), ]),
# row.names(abs_pseudotime_test_res[abs_pseudotime_test_res$qval < 0.01, ]),
# row.names(abs_AT12_cds_subset_all_gene_res[abs_AT12_cds_subset_all_gene_res$qval < 0.01, ]),
# row.names(abs_AT12_cds_subset_all_gene_res_no_weight[abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01, ]))
# pseudotime_sets_all <- c(rep(paste('Multiple timepoint test', sep = ''), length(which(abs_group_test_res$qval < .01))),
# rep(paste('Pseudotime test', sep = ''), length(which(abs_pseudotime_test_res$qval < 0.01))),
# rep(paste('Branch test', sep = ''), length(which(abs_AT12_cds_subset_all_gene_res$qval < 0.01))),
# rep(paste('Branch test (no weight)', sep = ''), length(which(abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01))))
# pdf('pseudotime.pdf', width = 2, height = 3)
# venneuler_venn(pseudotime_element_all, pseudotime_sets_all)
# dev.off()
# #supplementary figures:
# branch_pseudotime_element_all <- c(
# #row.names(abs_group_test_res[which(abs_group_test_res$qval < .01), ]),
# # row.names(abs_pseudotime_test_res[abs_pseudotime_test_res$qval < 0.01, ]),
# row.names(relative_abs_AT12_cds_subset_all_gene[relative_abs_AT12_cds_subset_all_gene$qval < 0.01, ]),
# # row.names(abs_AT12_cds_subset_all_gene_res_no_weight[abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01, ]),
# # row.names(abs_AT12_cds_subset_all_gene_res_no_weight_relative[abs_AT12_cds_subset_all_gene_res_no_weight_relative$qval < 0.01, ]),
# row.names(abs_pseudotime_test_lineage2_res[abs_pseudotime_test_lineage2_res$qval < 0.01, ]),
# row.names(abs_pseudotime_test_lineage3_res[abs_pseudotime_test_lineage3_res$qval < 0.01, ])
# )
# branch_pseudotime_sets_all <- c(
# #ep(paste('Multiple timepoint test', sep = ''), length(which(abs_group_test_res$qval < .01))),
# # rep(paste('Pseudotime test', sep = ''), length(which(abs_pseudotime_test_res$qval < 0.01))),
# rep(paste('Branch test', sep = ''), length(which(relative_abs_AT12_cds_subset_all_gene$qval < 0.01))),
# # rep(paste('Branch test (no weight)', sep = ''), length(which(abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01))),
# # rep(paste('Branch test (no weight, relative)', sep = ''), length(which(abs_AT12_cds_subset_all_gene_res_no_weight_relative$qval < 0.01))),
# rep(paste('Pseudotime test (AT1 lineage)', sep = ''), length(which(abs_pseudotime_test_lineage2_res$qval < 0.01))),
# rep(paste('Pseudotime test (AT2 lineage)', sep = ''), length(which(abs_pseudotime_test_lineage3_res$qval < 0.01)))
# )
# # save(branch_pseudotime_element_all, branch_pseudotime_sets_all, file = 'branchTest_cmpr_subset')
# # pdf(file = paste(elife_directory, 'eLife_fig_SI_branchTest_cmpr.pdf', sep = ''), height = 2, width = 3)
# pdf(file = paste(elife_directory, 'eLife_fig_SI_branchTest_cmpr1.pdf', sep = ''))
# venneuler_venn(branch_pseudotime_element_all, branch_pseudotime_sets_all)
# dev.off()
# #see the branch genes outside of AT1/2 pseudotime genes:
# branchGenes_example <- setdiff(row.names(subset(relative_abs_AT12_cds_subset_all_gene, qval < 0.01)),
# c(row.names(abs_pseudotime_test_lineage2_res[abs_pseudotime_test_lineage2_res$qval < 0.01, ]),
# row.names(abs_pseudotime_test_lineage3_res[abs_pseudotime_test_lineage3_res$qval < 0.01, ])))
# plot_genes_branched_pseudotime2(abs_AT12_cds_subset_all_gene[branchGenes_example[6:10], ], color_by = "State", trajectory_color_by = 'Lineage', fullModelFormulaStr = '~sm.ns(Pseudotime, df = 3)*Lineage', normalize = T, stretch = T, lineage_labels = c('AT1', 'AT2'), cell_size = 1, ncol = 2, add_pval = T, reducedModelFormulaStr = '~sm.ns(Pseudotime, df = 3)') + nm_theme()+ ylab('Transcript counts') + xlab('Pseudotime')
# plot_genes_branched_pseudotime2(abs_AT12_cds_subset_all_gene[branchGenes_example[6:10], ], color_by = "State", trajectory_color_by = 'Lineage', fullModelFormulaStr = '~sm.ns(Pseudotime, df = 3)*Lineage', normalize = T, stretch = T, lineage_labels = c('AT1', 'AT2'), cell_size = 1, ncol = 2, add_pval = T, reducedModelFormulaStr = '~sm.ns(Pseudotime, df = 3)') + nm_theme()+ ylab('Transcript counts') + xlab('Pseudotime')
# pseudotime_element_all <- c(row.names(abs_group_test_res[which(abs_group_test_res$qval < .01), ]),
# row.names(abs_pseudotime_test_res[abs_pseudotime_test_res$qval < 0.01, ]),
# row.names(abs_AT12_cds_subset_all_gene_res[abs_AT12_cds_subset_all_gene_res$qval < 0.01, ])
# # row.names(abs_AT12_cds_subset_all_gene_res_no_weight[abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01, ])
# )
# pseudotime_sets_all <- c(rep(paste('Multiple timepoint test', sep = ''), length(which(abs_group_test_res$qval < .01))),
# rep(paste('Pseudotime test', sep = ''), length(which(abs_pseudotime_test_res$qval < 0.01))),
# rep(paste('Branch test', sep = ''), length(which(abs_AT12_cds_subset_all_gene_res$qval < 0.01)))
# # rep(paste('Branch test (no weight)', sep = ''), length(which(abs_AT12_cds_subset_all_gene_res_no_weight$qval < 0.01)))
# )
# pdf(file = paste(elife_directory, 'eLife_fig_SI_branchTest_cmpr2.pdf', sep = ''))
# venneuler_venn(pseudotime_element_all, pseudotime_sets_all)
# dev.off()
# #############################################
# #pseudotime benchmark test on the HSMM data:
# pdf('eLife_figSI_fpkm_HSMM_tree.pdf', width = 1.5, height = 1.2)
# plot_spanning_tree(std_HSMM, color_by="Time", show_backbone=T, backbone_color = 'black',
# markers=markers, show_cell_names = F, show_all_lineages = F, cell_size = 1, cell_link_size = 0.2) + nm_theme() #+ scale_size(range = c(0.5, .5))
# dev.off()
# pdf('eLife_figSI_abs_HSMM_tree.pdf', width = 1.5, height = 1.2)
# plot_spanning_tree(HSMM_myo, color_by="Time", show_backbone=T, backbone_color = 'black',
# markers=markers, show_cell_names = F, show_all_lineages = F, cell_size = 1, cell_link_size = 0.2) + nm_theme() #+ scale_size(range = c(0.5, .5))
# dev.off()
# pdf('eLife_figSI_tree_cmpr.pdf', width = 1.5, height = 1.2)
# plot_tree_pairwise_cor(std_HSMM, HSMM_myo) + nm_theme()
# dev.off()
# element_all <- c(row.names(HSMM_myo_size_norm_res[HSMM_myo_size_norm_res$qval <0.1, ]),
# row.names(std_HSMM_myo_pseudotime_res_ori[std_HSMM_myo_pseudotime_res_ori$qval <0.1, ]))
# sets_all <- c(rep(paste('Transcript counts (Size + VST)', sep = ''), nrow(HSMM_myo_size_norm_res[HSMM_myo_size_norm_res$qval <0.1, ])),
# rep(paste('FPKM', sep = ''), nrow(std_HSMM_myo_pseudotime_res_ori[std_HSMM_myo_pseudotime_res_ori$qval <0.1, ])))
# pdf('eLife_figSI_transcript_counts_HSMM_overlapping.pdf')
# venneuler_venn(element_all, sets_all)
# dev.off()
# table(sets_all) #number of genes
# # add a vertical line for the early / late lineage dependent genes to represent the bifurcation time points
# # ILR heatmap: don’t use blue / red color scheme for better representation of the idea of ILRs
# # tree branch plots with all cells on a lineage collapse to one branch
# # alpha - FDR plots for the two-group tests
# # alpha_fdr <- function(alpha_vec, est_pval, true_pval, est_pval_name, true_q_thrsld = 0.05, type = c('precision', 'recall', 'fdr')) {
# # qval <- p.adjust(est_pval, method = 'BH')
# # names(qval) <- est_pval_name
# # true_qval <- p.adjust(true_pval, method = 'BH')
# # P <- names(true_pval[true_qval <= true_q_thrsld])
# # N <- names(true_qval[true_qval > true_q_thrsld])
# # #FDR = v / (v + s)
# # unlist(lapply(alpha_vec, function(alpha, type, qval, P, N) {
# # fp <- setdiff(names(qval[qval <= alpha]), P) #false positive
# # tp <- intersect(names(qval[qval <= alpha]), P) #true positive
# # fn <- setdiff(names(qval[qval > alpha]), N)
# # if(type == 'precision') length(tp) / length(union(fp, tp)) #precision = tp / (tp + fp)
# # else if(type =='recall') length(tp) / length(union(fp, fn)) #recall = tp / (tp + fn)
# # else if(type == 'fdr') length(fp) / length(union(fp, tp)) #fdr: fp / (fp + tp)
# # }, type = type, qval, P, N)) #/ sum(true_pval < alpha, na.rm = T)
# # }
# # alpha_fdr2 <- function() {
# # gene_list_true_data_list <- gene_list_true_data(p_thrsld = p_thrsld,
# # permutate_pval = permutate_pval[[ind]][gene_list],
# # na.rm = na.rm)
# # gene_list_new <- gene_list_true_data_list$gene_list
# # true_data <- gene_list_true_data_list$true_data
# # test_p_vec <- test_p_list[[ind]][gene_list_new]
# # TF_PN <- TF_PN_vec(true_data, test_p_vec)
# # }
# # alpha_vec <- seq(0, 1, length.out = 1000)
# # true_pval <- permutate_pval #permutation_pval
# # true_pval <- true_pval[gene_list] #gene_list
# # #pval_df
# # # fdr <- lapply(alpha_vec, function(x) alpha_fdr(pval_df[, 1], p.adjust(true_pval, method = 'BH'), x))
# # # result <- mcmapply(alpha_fdr, split(t(alpha_vec), col(t(alpha_vec), as.factor = T)), split(as.matrix(pval_df), col(as.matrix(pval_df), as.factor = T)), true_pval, mc.cores = 8)
# # monocle_p <- new_std_diff_test_res[, 'pval']
# # names(monocle_p) <- row.names(new_std_diff_test_res)
# # df3_pval_df <- data.frame(#monocle_p = monocle_p,
# # monocle_p_readcount = monocle_p_readcount,
# # #mode_size_norm_permutate_ratio_by_geometric_mean = new_abs_size_norm_monocle_p_ratio_by_geometric_mean,
# # #mc_mode_size_norm_permutate_ratio_by_geometric_mean = new_mc_size_norm_monocle_p_ratio_by_geometric_mean,
# # default_edgeR_p = default_edgeR_p,
# # #abs_default_edgeR_p = abs_default_edgeR_p,
# # default_deseq2_p = default_deseq2_p,
# # #abs_default_deseq2_p = abs_default_deseq2_p,
# # default_deseq_p = default_deseq_p,
# # #abs_default_deseq_p = abs_default_deseq_p,
# # scde_p = scde_p#,
# # #abs_scde_p = abs_scde_p
# # )
# # alpha_fdr_res <- apply(df3_pval_df, 2, function(x) alpha_fdr(alpha_vec, x, readcount_permutate_pval, row.names(df3_pval_df), type = 'fdr'))
# # #alpha_fdr_res <- apply(pval_df, 2, function(x) alpha_fdr(alpha_vec, x, true_pval, row.names(pval_df), type = 'fdr'))
# # p_alpha_fdr <-
# # qplot(Var1 / 1000, value, geom = 'line', data = melt(alpha_fdr_res), color = Var2, linetype = Var2) + monocle_theme_opts() +
# # geom_abline(color = 'red') + ggtitle('alpha VS fdr') + facet_wrap(~Var2, scale = 'free_y', ncol = round(sqrt(dim(alpha_fdr_res)))) + xlab('alpha') + ylab('fdr')
# # abs_df3_pval_df <- data.frame(#monocle_p = monocle_p,
# # #monocle_p_readcount = monocle_p_readcount,
# # mode_size_norm_permutate_ratio_by_geometric_mean = new_abs_size_norm_monocle_p_ratio_by_geometric_mean,
# # mc_mode_size_norm_permutate_ratio_by_geometric_mean = new_mc_size_norm_monocle_p_ratio_by_geometric_mean,
# # #default_edgeR_p = default_edgeR_p,
# # abs_default_edgeR_p = abs_default_edgeR_p,
# # #default_deseq2_p = default_deseq2_p,
# # abs_default_deseq2_p = abs_default_deseq2_p,
# # #default_deseq_p = default_deseq_p,
# # abs_default_deseq_p = abs_default_deseq_p,
# # #scde_p = scde_p#,
# # abs_scde_p = abs_scde_p
# # )
# # abs_alpha_fdr_res <- apply(abs_df3_pval_df, 2, function(x) alpha_fdr(alpha_vec, x, mode_size_norm_permutate_ratio_by_geometric_mean, row.names(abs_df3_pval_df), type = 'fdr'))
# # #alpha_fdr_res <- apply(pval_df, 2, function(x) alpha_fdr(alpha_vec, x, true_pval, row.names(pval_df), type = 'fdr'))
# # p_abs_alpha_fdr <-
# # qplot(Var1 / 1000, value, geom = 'line', data = melt(abs_alpha_fdr_res), color = Var2, linetype = Var2) + monocle_theme_opts() +
# # geom_abline(color = 'red') + ggtitle('alpha VS fdr') + facet_wrap(~Var2, scale = 'free_y', ncol = round(sqrt(dim(abs_alpha_fdr_res)))) + xlab('alpha') + ylab('fdr')
# # #find genes with expression goes up:
# # #or use the pval / qval from the global tests:
# ######################################################################################################
# # #fig b
# # ABCs_df <- subset(ABCs_df, abs(ABCs) > 5)
# # ABCs <- ABCs_df[, 'ABCs']
# # names(ABCs) <- ABCs_df[, 'gene_short_name']
# # pval <- abs_AT12_cds_subset_all_gene_res[ABCs_df[, 'gene_id'], 'pval']
# # names(pval) <- names(ABCs)
# # pval <- pval[!is.na(pval)]
# # ABCs <- ABCs[names(pval)]
# # gasRes <- auto_make_enrichment(gsaRes_go, 15, F, F, F, T, T)
# # gasRes + nm_theme()
# # ggsave(paste(elife_directory, 'eLife_fig3a.pdf', sep = ''), width = 6.5, height = 2.5)
# # enrich_data_non_direction <- make_enrichment_df(std_bif_time_gsaRes_go, extract_num = 100,
# # custom_p_adjust = F, add_terms = F, direction = F)
# # enrich_data_non_direction
# # enrich_data_non_direction <- enrich_data_non_direction[sort(as.vector(enrich_data_non_direction$"Stat (non-dir.)"),
# # index.return = T)$ix, ]
# # qplot(x = 1:nrow(enrich_data_non_direction), y = abs(log(enrich_data_non_direction[, 'Stat (non-dir.)'])),
# # data = enrich_data_non_direction, geom = "bar", stat = "identity") +
# # coord_flip() + scale_x_discrete(limits = 1:nrow(enrich_data_non_direction),
# # labels = enrich_data_non_direction$Name) +
# # xlab("") + ylab("Normalized Enrichment Score") + nm_theme()
# # ggsave(paste(elife_directory, 'eLife_fig3a.pdf', sep = ''), height = 2, width = 4)
# # #debug buildLineageBranchCellDataSet for weight_constant:
# # str_logfc_df_list <- calILRs(cds = std_AT12_cds_subset_all_gene[add_quake_gene_all_marker_ids, ], lineage_states = c(2, 3), stretch = T, cores = 1,
# # trend_formula = "~sm.ns(Pseudotime, df = 3)*Lineage", ILRs_limit = 3,
# # relative_expr = F, weighted = FALSE, label_by_short_name = F,
# # useVST = FALSE, round_exprs = FALSE, pseudocount = 0, output_type = "all", file = "str_logfc_df", return_all = T)
# # #calILRs for all genes is not feasible...
# # #fig c
# # str_logfc_df <- t(str_logfc_df)
# # str_logfc_df <- str_logfc_df[!is.na(str_logfc_df[, 1]), ]
# # str_logfc_df <- str_logfc_df[abs(str_logfc_df[, 100]) > 1, ]
# # plot_ILRs_heatmap(absolute_cds, str_logfc_df, abs_AT12_cds_subset_all_gene_ABCs, relative_abs_AT12_cds_subset_quake_gene, "ensemble_id", ABC_type = "all",
# # dist_method = "euclidean", hclust_method = "ward", ILRs_limit = 3,
# # cluster_num = 4)
# # pdf(file = paste(elife_directory, 'eLife_fig3b.pdf', sep = ''))
# # #fig 3e:
# # #test the the AT1/2 early late group with the proportity score:
# # c('Clic5', 'Muc1', 'S100g', 'Soat1')
# # bifurcation_time[c('Clic5', 'Muc1', 'S100g', 'Soat1')]
# # bifurcation_time <- detectBifurcationPoint(abs_AT12_cds_subset_all_gene_ILRs[, 27:100])
# # valid_bifurcation_time <- bifurcation_time[!is.na(bifurcation_time)]
# # valid_bifurcation_time <- valid_bifurcation_time[unique(names(valid_bifurcation_time))]
# # bif_time_gsaRes_go <- runGSA(valid_bifurcation_time, gsc = mouse_go_gsc, ncpus = 1)
|
10832804433d4aa2fa0bdbccd9b770d265664ae3
|
a5d834452097b7cce7d001b057b9636c5a737bf2
|
/R/utils.R
|
dae8650e56e7456f252eb13167c7559dac650109
|
[] |
no_license
|
a-benini/mdepriv
|
0a8b21bd66167bbf9a980dbe7a5816fd26de05ff
|
484adce29b6677fb5f65dcc7d10ff6cd88a36bb2
|
refs/heads/master
| 2021-10-23T21:33:33.810404
| 2021-10-09T10:57:54
| 2021-10-09T10:57:54
| 233,093,633
| 5
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,296
|
r
|
utils.R
|
corr_mat_ <- function(data, items, corr_type, sampling_weights) {
weightedCorr_automated <- function(x, y, corr_type, sampling_weights) {
n_distinct_x <- length(unique(x))
n_distinct_y <- length(unique(y))
if (n_distinct_x < n_distinct_y) {
x_temp <- x
y_temp <- y
x <- y_temp
y <- x_temp
n_distinct_x <- length(unique(x))
n_distinct_y <- length(unique(y))
}
if (corr_type == "mixed") {
if (n_distinct_x <= 10 & n_distinct_y <= 10) {
corr_type <- "polychoric"
} else if (n_distinct_x > 10 & n_distinct_y <= 10) {
corr_type <- "polyserial"
} else {
corr_type <- "pearson"
}
}
if (all(x == y)) {
1
} else if (n_distinct_x == n_distinct_y) {
corr_xy <- wCorr::weightedCorr(x = x, y = y, method = corr_type, weights = sampling_weights)
corr_yx <- wCorr::weightedCorr(x = y, y = x, method = corr_type, weights = sampling_weights)
mean(c(corr_xy, corr_yx))
} else {
wCorr::weightedCorr(x = x, y = y, method = corr_type, weights = sampling_weights)
}
}
corr_mat <- matrix(NA, length(items), length(items), dimnames = list(items, items))
diag(corr_mat) <- 1
for (i in items) {
for (j in items) {
if (is.na(corr_mat[i, j]) & is.na(corr_mat[j, i])) {
corr_mat[i, j] <- weightedCorr_automated(x = data[[i]], y = data[[j]], corr_type = corr_type, sampling_weights = sampling_weights)
corr_mat[j, i] <- corr_mat[i, j]
}
}
}
corr_mat
}
# ------------------------------------------------------------------------
corr_mat_type_ <- function(data, items, corr_type) {
corr_type_ <- function(x, y, corr_type) {
n_distinct_x <- length(unique(x))
n_distinct_y <- length(unique(y))
if (n_distinct_x < n_distinct_y) {
x_temp <- x
y_temp <- y
x <- y_temp
y <- x_temp
rm(x_temp, y_temp)
n_distinct_x <- length(unique(x))
n_distinct_y <- length(unique(y))
}
if (corr_type == "mixed") {
if (n_distinct_x <= 10 & n_distinct_y <= 10) {
corr_type <- "polychoric"
} else if (n_distinct_x > 10 & n_distinct_y <= 10) {
corr_type <- "polyserial"
} else {
corr_type <- "pearson"
}
}
corr_type
}
corr_mat_type <- matrix(NA, length(items), length(items), dimnames = list(items, items))
for (i in items) {
for (j in items) {
if (is.na(corr_mat_type[i, j]) & is.na(corr_mat_type[j, i])) {
corr_mat_type[i, j] <- corr_type_(x = data[[i]], y = data[[j]], corr_type = corr_type)
corr_mat_type[j, i] <- corr_mat_type[i, j]
}
}
}
corr_mat_type
}
# ------------------------------------------------------------------------
wb_general_ <- function(data, items, corr_type, sampling_weights, rhoH) {
if (corr_type != "diagonal" & length(items) > 1) {
corr_mat__ <- corr_mat_(data = data, items = items, corr_type = corr_type, sampling_weights = sampling_weights)
wb_j <- function(x, rhoH) {
sum_l <- 1 + sum(x[x < rhoH])
sum_h <- sum(x[x >= rhoH])
1 / (sum_l * sum_h)
}
apply(corr_mat__, 2, wb_j, rhoH = rhoH)
} else {
rep(1, length(items))
}
}
# ------------------------------------------------------------------------
|
ab6578770660ba1a12db5d77a9702c6e6824d0d1
|
0fcbf5c651245a85ced0c6ecaacc34a483a83afd
|
/tests/testthat/test_object.R
|
7bb9e2ff9765a7378e203cee8c77ca70a6f36eed
|
[
"MIT"
] |
permissive
|
AndersenLab/cegwas2
|
48a0c2bd8e840d97c680ceab7513116893754b30
|
3717c0236f398b0fb819bf2a83ee947db4f95625
|
refs/heads/master
| 2021-06-03T15:26:16.323174
| 2020-08-23T23:11:17
| 2020-08-23T23:11:17
| 113,356,402
| 0
| 2
|
MIT
| 2020-02-24T22:29:49
| 2017-12-06T19:06:00
|
R
|
UTF-8
|
R
| false
| false
| 1,109
|
r
|
test_object.R
|
testthat::context("tests/testthat/test_object.R")
options(stringsAsFactors = FALSE)
df <- data.table::fread(system.file("extdata",
"test_phenotype.tsv",
package = "cegwas2",
mustWork = TRUE)) %>%
dplyr::select(strain, trait1)
test_trait <- ceGWAS$new(phenotype = df)
test_that("Test ceGWAS doesn't change input data", {
remakedf <- data.frame(strain = as.character(test_trait$strains),
trait1 = test_trait$phenotype)
dftest <- data.frame(na.omit(df))
expect_true(identical(dftest,remakedf))
})
test_trait$set_markers(genotype_matrix = cegwas2::snps,
kinship_matrix = cegwas2::kinship)
test_trait$run_mapping(P3D = TRUE)
blup_message <- capture.output(gmap <- perform_mapping(phenotype = test_trait$processed_phenotype,
P3D = TRUE, min.MAF = 0.1, mapping_cores = 1))
test_that("Test ceGWAS mappings", {
expect_equal(colnames(test_trait$mapping), colnames(gmap))
})
|
ce3babc06b720afe0ec6eaf150f988502e86ab6e
|
82f22590405a457c63cb9f9baeafee96ac9eb431
|
/apa_tools/apa_tools.R
|
68bd93af4ddf3df1e5c2b68bbf2e6b603c7c4f90
|
[] |
no_license
|
zm-git-dev/apa_bin
|
df5026b74fe02f4f6d6f948dad8d12867bd3afad
|
73816825db72a1f7203b625a7651507afd25142f
|
refs/heads/master
| 2022-09-13T07:04:40.922889
| 2018-07-24T20:37:08
| 2018-07-24T20:37:08
| 191,887,492
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 41
|
r
|
apa_tools.R
|
/home/apa/local/git/apa_tools/apa_tools.R
|
0962fd4c114fda62effde6db2b57f42da0080960
|
04a7c98ebecf2db764395c90455e8058711d8443
|
/man/pvdiv_gwas.Rd
|
1d357846f4681e408270ddc1a30d1142bb2f3c39
|
[] |
no_license
|
Alice-MacQueen/switchgrassGWAS
|
f9be4830957952c7bba26be4f953082c6979fdf2
|
33264dc7ba0b54aff031620af171aeedb4d8a82d
|
refs/heads/master
| 2022-02-01T01:12:40.807451
| 2022-01-17T20:56:20
| 2022-01-17T20:56:20
| 198,465,914
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,637
|
rd
|
pvdiv_gwas.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pvdiv_gwas.R
\name{pvdiv_gwas}
\alias{pvdiv_gwas}
\title{Wrapper for bigsnpr for GWAS on Panicum virgatum.}
\usage{
pvdiv_gwas(
df,
type = c("linear", "logistic"),
snp,
covar = NA,
ncores = 1,
npcs = 10,
saveoutput = FALSE
)
}
\arguments{
\item{df}{Dataframe of phenotypes where the first column is PLANT_ID.}
\item{type}{Character string. Type of univarate regression to run for GWAS.
Options are "linear" or "logistic".}
\item{snp}{Genomic information to include for Panicum virgatum. SNP data
is available at doi:10.18738/T8/ET9UAU#'}
\item{covar}{Optional covariance matrix to include in the regression. You
can generate these using \code{bigsnpr::snp_autoSVD()}.}
\item{ncores}{Number of cores to use. Default is one.}
\item{npcs}{Number of principle components to use. Default is 10.}
\item{saveoutput}{Logical. Should output be saved as a rds to the
working directory?}
}
\value{
The gwas results for the last phenotype in the dataframe. That
phenotype, as well as the remaining phenotypes, are saved as RDS objects
in the working directory.
}
\description{
Given a dataframe of phenotypes associated with PLANT_IDs, this
function is a wrapper around bigsnpr functions to conduct linear or
logistic regression on Panicum virgatum. The main advantages of this
function over just using the bigsnpr functions is that it automatically
removes individual genotypes with missing phenotypic data, that it
converts switchgrass chromosome names to the format bigsnpr requires,
and that it can run GWAS on multiple phenotypes sequentially.
}
|
04d41c77f6f5f4c01486233045caabcfdc6ca551
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/riverdist/examples/addverts.Rd.R
|
69ad2be0548cea51529ca3fe61b30cfe457b860a
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 420
|
r
|
addverts.Rd.R
|
library(riverdist)
### Name: addverts
### Title: Add Vertices To Maintain a Minimum Distance Between Vertices
### Aliases: addverts
### ** Examples
data(Kenai3)
Kenai3split <- addverts(Kenai3,mindist=200)
zoomtoseg(seg=c(47,74,78), rivers=Kenai3)
points(Kenai3$lines[[74]]) # vertices before adding
zoomtoseg(seg=c(47,74,78), rivers=Kenai3split)
points(Kenai3split$lines[[74]]) # vertices after adding
|
7d4e2fa760f4f49b95e6438664201999992c9f6a
|
3819c5c65f13b185b8fb714d7349abfecb793a72
|
/man/BOWLBasic-class.Rd
|
7aa27b899fcfc274192b86e41702c5858652f66f
|
[] |
no_license
|
cran/DynTxRegime
|
ed877579c6ffc6156fb6c84298a58d1db5940dff
|
9ecb35dfd9abf9617e0179d3d4d552dce22314e5
|
refs/heads/master
| 2023-06-25T03:37:01.776586
| 2023-04-25T13:50:11
| 2023-04-25T13:50:11
| 37,244,072
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,287
|
rd
|
BOWLBasic-class.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/R_class_BOWLBasic.R
\docType{class}
\name{BOWLBasic-class}
\alias{BOWLBasic-class}
\title{Class \code{BOWLBasic}}
\description{
Class \code{BOWLBasic} contains the results for a single OWL analysis and the
weights needed for next iteration
}
\section{Slots}{
\describe{
\item{\code{analysis}}{Contains a Learning or LearningMulti object.}
\item{\code{analysis@txInfo}}{Feasible tx information.}
\item{\code{analysis@propen}}{Propensity regression analysis.}
\item{\code{analysis@outcome}}{Outcome regression analysis.}
\item{\code{analysis@cvInfo}}{Cross-validation analysis if single regime.}
\item{\code{analysis@optim}}{Optimization analysis if single regime.}
\item{\code{analysis@optimResult}}{list of cross-validation and optimization results
if multiple regimes. optimResult[[i]]@cvInfo and optimResult[[i]]@optim.}
\item{\code{analysis@optimal}}{Estimated optimal Tx and value.}
\item{\code{analysis@call}}{Unevaluated call to statistical method.}
\item{\code{prodPi}}{Vector of the products of the propensity for the tx received}
\item{\code{sumR}}{Vector of the sum of the rewards}
\item{\code{index}}{Vector indicating compliance with estimated optimal regime}
}}
\keyword{internal}
|
8c63773bc387ba75b21b1dbf2a9ad0457bb861ce
|
8cca3a9614dcce73ed38663972ea60de19ef75d8
|
/analyses/analyses_decision_making/OLD_/functions/plot_measures.R
|
68793023e923d4ecc16350f4c284395050e2590d
|
[] |
no_license
|
moramaldonado/MouseTracking
|
e418396511042fc78b9ea910f962e5f21e4b12d3
|
474c9297ab7d9c797219ad7ef362a46b7b0a81da
|
refs/heads/master
| 2021-12-15T12:30:51.668939
| 2021-12-13T12:44:39
| 2021-12-13T12:44:39
| 75,234,939
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,586
|
r
|
plot_measures.R
|
##PLOTTING different measures
#Input: data= data, measure = 'measure', division = 'division'
#Output: multiplot with plots for histogram, density and bar graph taken from means + print of means + SE
plot_measure <- function(data, measure, division){
histogram <- ggplot(data, aes_string(x=measure, fill=division), environment = environment()) +
geom_histogram(bins=12, position="dodge")+
scale_fill_brewer(palette="Set1")+
theme_minimal() +
theme(legend.position = "none")
density <-ggplot(data, aes_string(x=measure, fill=division), environment = environment()) +
geom_density(alpha=.5)+
scale_fill_brewer(palette="Set1")+
theme_minimal() +theme(legend.position = "none")
mydata.agreggated <- ddply(data, c(division, "Subject"),
function(x,ind){mean(x[,ind])},measure)
mydata.agreggated.overall <- ddply(mydata.agreggated, c(division),
function(mydata.agreggated)c(mean=mean(mydata.agreggated$V1, na.rm=T), se=se(mydata.agreggated$V1, na.rm=T) ))
mean.plot <- ggplot(mydata.agreggated.overall, aes(x=mydata.agreggated.overall[,1], y=mean, fill=mydata.agreggated.overall[,1])) +
geom_bar(position=position_dodge(), stat="identity") +
scale_fill_brewer(palette="Set1")+
theme_minimal()+
xlab(' ') +
theme(legend.position = "none") +
geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.2, position=position_dodge(.9))
print(mydata.agreggated.overall)
return(multiplot(density, mean.plot,
cols=2)) }
|
74e3554011c9878c70422efe3d79eb3799d68850
|
32f251147606d865a04834ba8f08f8be75410738
|
/man/check_species_byclass.Rd
|
9eeed94c489b4bd717aaad99873453b214858aeb
|
[] |
no_license
|
cdv04/ACTR
|
4e17aaab32d319b1b609b6c1c0c553a0f7e41317
|
d1762dc8884eb37b023cf146a71c05a96508cc08
|
refs/heads/master
| 2021-01-01T05:11:47.528297
| 2017-04-07T10:16:40
| 2017-04-07T10:16:40
| 59,212,181
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 582
|
rd
|
check_species_byclass.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/check_levels.R
\name{check_species_byclass}
\alias{check_species_byclass}
\title{Print all the levels (modalities) of Species for each Class of for each Dose Type}
\usage{
check_species_byclass(dataset)
}
\arguments{
\item{dataset}{A dataframe containing DoseType, Class and SpeciesComp variables}
}
\description{
Aim : check that species names are always writtten with the
same orthography (needed for the ACT method)
}
\details{
Outputs are printed in file
}
\examples{
check_species_byclass(cipr)
}
|
093868c5eff16220e92eedcc77f5dc7edf415ace
|
91168649462ac9871e31d45491021e9909080023
|
/pruebas_iniciales_R.r
|
d04aa9504d5130cab300b582651b22745b795812
|
[] |
no_license
|
giss-ignacio/data-science
|
0da6a6a8df46613d7a2cd640aa8669bddb80c9b2
|
350803273e2c84b0176c48c8f94a5a01ca73a620
|
refs/heads/master
| 2021-01-21T11:40:00.302280
| 2018-06-03T23:54:12
| 2018-06-03T23:54:12
| 42,420,598
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,357
|
r
|
pruebas_iniciales_R.r
|
#directorio donde están los set de datos. Lo mismo que ir a Session->Set Working Directory -> Choose Directory
setwd("C:/Dev/Datos/TP/Data")
# lee el csv train y lo asigna a la variable train
train <- read.csv("train.csv")
# lee el csv test y lo asigna a la variable test
test <- read.csv("test.csv")
# ------------------------------
# obtener información con R.
# Finger #1
# de lo que subieron al fb
# --------------------------------
# 1) ¿Cuales son los 10 (diez) delitos más comunes en la ciudad de San Francisco?
# Mira la columna Category ($Category)
# sumariza o extrae y suma todas las apariciones de cada "categoría de delito" (Category)
# orden decreciente
# selecciona las primeras 10, "[1:10]"
sort(summary(train$Category),decreasing = TRUE)[1:10]
# 2) En qué día de la semana hay más casos de “Driving under the influence”
# a la variable duti le asigna un subconjunto de todas las entradas que SOLO tienen la Category: "DRIVING UNDER THE INFLUENCE"
# van a ser muchas menos filas
# después suma todas las veces que aparece cada día, "summary(duti$Day)"
# en la misma línea ordena decrecientemente y pide el primer valor , "[1]"
duti <- subset(train,train$Category == "DRIVING UNDER THE INFLUENCE")
sort(summary(duti$Day),decreasing= TRUE)[1]
# 3) ¿Cuáles son los tres distritos con mayor cantidad de crímenes
# suma todas las veces que aparece cada distrito, "PdDistrict", ordena, saca los 3 primeros
sort(summary(train$PdDistrict),decreasing= TRUE)[1:3]
# 4) ¿Cuáles son los crímenes que tienen mayor porcentaje de resolución “Not Prosecuted”
# forma del fb, a la variable npro le asigna un subconjunto de todas las entradas que SOLO tienen Resolution: "NOT PROSECUTED"
# van a ser menos filas
# lo sumariza, lo ordena y lo asigna a la variable nproSum
npro <- subset(train,train$Resolution=="NOT PROSECUTED")
nproSum <- sort(summary(npro$Category),decreasing= TRUE)
#subset(nproSum,nproSum>0) esto estaba, muestra solo los delitos que tienen al menos 1 proceso judicial
# iria algo así
prop.table(nproSum)
# forma copada (?)
table(train$Category, train$Resolution =="NOT PROSECUTED" )
notpros <- notpros[,c(0,2)]
prop.table(sort(notpros, decreasing= TRUE))
# 5) Crear un histograma (o gráfico de barras) que muestre la cantidad de delitos por día de la semana.
barplot(sort(table(train$Day)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.