content large_stringlengths 0 6.46M | path large_stringlengths 3 331 | license_type large_stringclasses 2 values | repo_name large_stringlengths 5 125 | language large_stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.46M | extension large_stringclasses 75 values | text stringlengths 0 6.46M |
|---|---|---|---|---|---|---|---|---|---|
## CONTINGENCY TABLE CHI-SQ TEST
#importing the C++ simulator
Rcpp::sourceCpp("C:/Users/angus/OneDrive/Desktop/urop/C++/simulation_2.cpp")
likelihood_test = function(p, q, size1, size2, dof = 2){
# Given the 2 vector of alleles frequencies and the final size2
# of the two population, and the degrees of freedom of the chi_sq distribution
# It returns the p-value for the likelihood ratio test I developed (see pdfs),
# which is indeed our joint r^2 measure
# creating the frequencies of the 2x2x2 cube from the single-population frequencies
p = p*size1/(size1+size2)
q = q*size2/(size1+size2)
#print(sum(p) + sum(q))
#creating a 3x2 matrix of the marginals for the 2x2x2 contingency table
marginals = marginals(p,q)
#print(marginals)
#initializing the vectors that contain the predicted frequencies under H0
# i.e. they are the product of the 3 marginals for each cell
exp_p = numeric(4)
exp_q = numeric(4)
exp_p[1] = marginals[1,1]*marginals[2,1]*marginals[3,1]
exp_p[2] = marginals[1,2]*marginals[2,1]*marginals[3,1]
exp_p[3] = marginals[1,1]*marginals[2,2]*marginals[3,1]
exp_p[4] = marginals[1,2]*marginals[2,2]*marginals[3,1]
exp_q[1] = marginals[1,1]*marginals[2,1]*marginals[3,2]
exp_q[2] = marginals[1,2]*marginals[2,1]*marginals[3,2]
exp_q[3] = marginals[1,1]*marginals[2,2]*marginals[3,2]
exp_q[4] = marginals[1,2]*marginals[2,2]*marginals[3,2]
#print(c('marginals', marginals))
#print(c('exp_p', exp_p))
#print(c('exp_q',exp_q))
#calculating the likelihood ratio test statistic (as illustrated in the pdf)
test_statistic = 0
for (i in 1:4){
if (p[i] != 0){
test_statistic = test_statistic + 2*p[i]*log(p[i]/exp_p[i])
}
if (q[i] != 0){
test_statistic = test_statistic + 2*q[i]*log(q[i]/exp_q[i])
}
}
#print(test_statistic)
return(pchisq(test_statistic, df = dof))
}
marginals = function(p,q){
# Given two vectors of size 4 (the allele frequencies for the 2 sub-populations,
# which we already normalize by size in the fnc above),
# it creates a 2x2x2 contingency table and return the marginals as a 3x2 matrix
arr = array(c(p, q), dim = c(2,2,2))
marginals = matrix(nrow = 3,ncol = 2)
marginals[1,1] = arr[1,1,1] + arr[1,2,1] + arr[1,1,2] + arr[1,2,2]
marginals[1,2] = arr[2,1,1] + arr[2,2,1] + arr[2,1,2] + arr[2,2,2]
marginals[2,1] = arr[1,1,1] + arr[2,1,1] + arr[1,1,2] + arr[2,1,2]
marginals[2,2] = arr[1,2,1] + arr[2,2,1] + arr[1,2,2] + arr[2,2,2]
marginals[3,1] = arr[1,1,1] + arr[2,1,1] + arr[1,2,1] + arr[2,2,1]
marginals[3,2] = arr[1,1,2] + arr[2,1,2] + arr[1,2,2] + arr[2,2,2]
return(marginals)
}
signal = function(p0, q0, N, M, c, migration, dof){
#Given the initial parameters, and the degrees of freedom of the chi_sq,
#it simulates the 2 populations, then considers the final generation (where
#we assume we have reached equilibrium), and performs a LR test on the final
#frequencies, and returns the p-value for the test
#running the individual based simulator
out = simulation(p0, q0, N, M, c, migration)
#find the population sizes at the final generation
final_generation_number = length(N)
N_size = N[final_generation_number]
M_size = M[final_generation_number]
#print(c('initial p', p0))
#print(c('initial q', q0))
#get the final generation allele frequencies for the 2 pop
p_values = matrix(unlist(out[1]), nrow = 4)[1:4,final_generation_number]
q_values = matrix(unlist(out[2]), nrow = 4)[1:4,final_generation_number]
#print(c('p', p_values))
#print(c('q', q_values))
#print(c('N_size', N_size))
#print(c('M_size', M_size))
#carry out the LR test
return (likelihood_test(p_values, q_values, N_size, M_size, dof))
}
create_pdf = function(p0, q0, N, M, c, migration, dof, simulations, no_breaks, title = 'no title'){
# Given initial inputs for the individual based simulator, the degrees of freedom
# of the chi_sq distr, how many simulations to carry out, and how many breaks (i.e. bars)
# the histogram should have,
# It plots an approximate probability distribution function for the test statistics, given these inputs
# And It returns a vector containing all the simulated p-values
#doing the iterations
values_of_tests = numeric(simulations)
for (i in 1:simulations){
values_of_tests[i] = signal(p0, q0, N, M, c, migration, dof)
}
#df = approxfun(density(values_of_tests))
#plot(density(values_of_tests))
#plotting the histogram
if (title != 'no title'){
tit = paste("m =", as.character(migration[1,2]), title, sep = " ")
}else{
tit = 'Distribution of the simulated r^2 values'
}
hist(values_of_tests, breaks = no_breaks, col = 'lightblue', xlab = 'r^2 simulated values',
main = tit)
return(values_of_tests)
}
compare_pdfs = function(simulated1, simulated2, number_breaks, migration_value = 'unknown'){
#We want to see how well the test manages to catch migration signals
#We plot two pdfs for different migration rates and see how well-separated they are
#In this case we plot the two histograms (with separate width of the bars), and then put it on the same
#axis
#inputs simulated1 and 2 are vectors containing all the simulated p_values using "create_pdf"
#number_breaks tells us how many bars should each histogram have
c1 <- rgb(173,216,230,max = 255, alpha = 80, names = "lt.blue")
c2 <- rgb(255,192,203, max = 255, alpha = 80, names = "lt.pink")
hist1 = hist(simulated1, breaks = number_breaks, plot = FALSE)
hist2 = hist(simulated2, breaks = number_breaks, plot = FALSE)
range_vec = range(c(hist1$breaks, hist2$breaks))
maximum = max(c(hist1$count, hist2$count))
plot(hist1, col = c1, xlim = range_vec, ylim = c(0,maximum), xlab = 'r^2 simulated values',
main = paste("m =", as.character(migration_value), sep = " "))
plot(hist2, add = TRUE, col = c2)
}
compare_pdfs2 = function(simulated1, simulated2, number_breaks, migration_value = 'unknown'){
#We want to see how well the test manages to catch migration signals
#We plot two pdfs for different migration rates and see how well-separated they are
#In this case we plot the two histograms (with a common width of the bars), and then put it on the same
#axis
#inputs simulated1 and 2 are vectors containing all the simulated p_values using "create_pdf"
#number_breaks tells us how many bars should each histogram have
c1 <- rgb(173,216,230,max = 255, alpha = 80, names = "lt.blue")
c2 <- rgb(255,192,203, max = 255, alpha = 80, names = "lt.pink")
b <- min(c(simulated1, simulated2)) - 0.01 # Set the minimum for the breakpoints
#print(b)
e <- max(c(simulated1, simulated2)) + 0.1 # Set the maximum for the breakpoints
#print(e)
ax <- seq(b,e, length.out = number_breaks)
#print(ax)
hist1 = hist(simulated1, breaks = ax, plot = FALSE)
hist2 = hist(simulated2, breaks = ax, plot = FALSE)
maximum = max(c(hist1$count, hist2$count))
plot(hist1, col = c1, xlim = c(b,e), ylim = c(0,maximum), xlab = 'r^2 simulated values',
main = paste("m =", as.character(migration_value), sep = " "))
plot(hist2, add = TRUE, col = c2)
}
| /joint_r^2_measure/likelihood_ratio_test/test_set_up.R | no_license | tinyuhui/UROP | R | false | false | 7,394 | r |
## CONTINGENCY TABLE CHI-SQ TEST
#importing the C++ simulator
Rcpp::sourceCpp("C:/Users/angus/OneDrive/Desktop/urop/C++/simulation_2.cpp")
likelihood_test = function(p, q, size1, size2, dof = 2){
# Given the 2 vector of alleles frequencies and the final size2
# of the two population, and the degrees of freedom of the chi_sq distribution
# It returns the p-value for the likelihood ratio test I developed (see pdfs),
# which is indeed our joint r^2 measure
# creating the frequencies of the 2x2x2 cube from the single-population frequencies
p = p*size1/(size1+size2)
q = q*size2/(size1+size2)
#print(sum(p) + sum(q))
#creating a 3x2 matrix of the marginals for the 2x2x2 contingency table
marginals = marginals(p,q)
#print(marginals)
#initializing the vectors that contain the predicted frequencies under H0
# i.e. they are the product of the 3 marginals for each cell
exp_p = numeric(4)
exp_q = numeric(4)
exp_p[1] = marginals[1,1]*marginals[2,1]*marginals[3,1]
exp_p[2] = marginals[1,2]*marginals[2,1]*marginals[3,1]
exp_p[3] = marginals[1,1]*marginals[2,2]*marginals[3,1]
exp_p[4] = marginals[1,2]*marginals[2,2]*marginals[3,1]
exp_q[1] = marginals[1,1]*marginals[2,1]*marginals[3,2]
exp_q[2] = marginals[1,2]*marginals[2,1]*marginals[3,2]
exp_q[3] = marginals[1,1]*marginals[2,2]*marginals[3,2]
exp_q[4] = marginals[1,2]*marginals[2,2]*marginals[3,2]
#print(c('marginals', marginals))
#print(c('exp_p', exp_p))
#print(c('exp_q',exp_q))
#calculating the likelihood ratio test statistic (as illustrated in the pdf)
test_statistic = 0
for (i in 1:4){
if (p[i] != 0){
test_statistic = test_statistic + 2*p[i]*log(p[i]/exp_p[i])
}
if (q[i] != 0){
test_statistic = test_statistic + 2*q[i]*log(q[i]/exp_q[i])
}
}
#print(test_statistic)
return(pchisq(test_statistic, df = dof))
}
marginals = function(p,q){
# Given two vectors of size 4 (the allele frequencies for the 2 sub-populations,
# which we already normalize by size in the fnc above),
# it creates a 2x2x2 contingency table and return the marginals as a 3x2 matrix
arr = array(c(p, q), dim = c(2,2,2))
marginals = matrix(nrow = 3,ncol = 2)
marginals[1,1] = arr[1,1,1] + arr[1,2,1] + arr[1,1,2] + arr[1,2,2]
marginals[1,2] = arr[2,1,1] + arr[2,2,1] + arr[2,1,2] + arr[2,2,2]
marginals[2,1] = arr[1,1,1] + arr[2,1,1] + arr[1,1,2] + arr[2,1,2]
marginals[2,2] = arr[1,2,1] + arr[2,2,1] + arr[1,2,2] + arr[2,2,2]
marginals[3,1] = arr[1,1,1] + arr[2,1,1] + arr[1,2,1] + arr[2,2,1]
marginals[3,2] = arr[1,1,2] + arr[2,1,2] + arr[1,2,2] + arr[2,2,2]
return(marginals)
}
signal = function(p0, q0, N, M, c, migration, dof){
#Given the initial parameters, and the degrees of freedom of the chi_sq,
#it simulates the 2 populations, then considers the final generation (where
#we assume we have reached equilibrium), and performs a LR test on the final
#frequencies, and returns the p-value for the test
#running the individual based simulator
out = simulation(p0, q0, N, M, c, migration)
#find the population sizes at the final generation
final_generation_number = length(N)
N_size = N[final_generation_number]
M_size = M[final_generation_number]
#print(c('initial p', p0))
#print(c('initial q', q0))
#get the final generation allele frequencies for the 2 pop
p_values = matrix(unlist(out[1]), nrow = 4)[1:4,final_generation_number]
q_values = matrix(unlist(out[2]), nrow = 4)[1:4,final_generation_number]
#print(c('p', p_values))
#print(c('q', q_values))
#print(c('N_size', N_size))
#print(c('M_size', M_size))
#carry out the LR test
return (likelihood_test(p_values, q_values, N_size, M_size, dof))
}
create_pdf = function(p0, q0, N, M, c, migration, dof, simulations, no_breaks, title = 'no title'){
# Given initial inputs for the individual based simulator, the degrees of freedom
# of the chi_sq distr, how many simulations to carry out, and how many breaks (i.e. bars)
# the histogram should have,
# It plots an approximate probability distribution function for the test statistics, given these inputs
# And It returns a vector containing all the simulated p-values
#doing the iterations
values_of_tests = numeric(simulations)
for (i in 1:simulations){
values_of_tests[i] = signal(p0, q0, N, M, c, migration, dof)
}
#df = approxfun(density(values_of_tests))
#plot(density(values_of_tests))
#plotting the histogram
if (title != 'no title'){
tit = paste("m =", as.character(migration[1,2]), title, sep = " ")
}else{
tit = 'Distribution of the simulated r^2 values'
}
hist(values_of_tests, breaks = no_breaks, col = 'lightblue', xlab = 'r^2 simulated values',
main = tit)
return(values_of_tests)
}
compare_pdfs = function(simulated1, simulated2, number_breaks, migration_value = 'unknown'){
#We want to see how well the test manages to catch migration signals
#We plot two pdfs for different migration rates and see how well-separated they are
#In this case we plot the two histograms (with separate width of the bars), and then put it on the same
#axis
#inputs simulated1 and 2 are vectors containing all the simulated p_values using "create_pdf"
#number_breaks tells us how many bars should each histogram have
c1 <- rgb(173,216,230,max = 255, alpha = 80, names = "lt.blue")
c2 <- rgb(255,192,203, max = 255, alpha = 80, names = "lt.pink")
hist1 = hist(simulated1, breaks = number_breaks, plot = FALSE)
hist2 = hist(simulated2, breaks = number_breaks, plot = FALSE)
range_vec = range(c(hist1$breaks, hist2$breaks))
maximum = max(c(hist1$count, hist2$count))
plot(hist1, col = c1, xlim = range_vec, ylim = c(0,maximum), xlab = 'r^2 simulated values',
main = paste("m =", as.character(migration_value), sep = " "))
plot(hist2, add = TRUE, col = c2)
}
compare_pdfs2 = function(simulated1, simulated2, number_breaks, migration_value = 'unknown'){
#We want to see how well the test manages to catch migration signals
#We plot two pdfs for different migration rates and see how well-separated they are
#In this case we plot the two histograms (with a common width of the bars), and then put it on the same
#axis
#inputs simulated1 and 2 are vectors containing all the simulated p_values using "create_pdf"
#number_breaks tells us how many bars should each histogram have
c1 <- rgb(173,216,230,max = 255, alpha = 80, names = "lt.blue")
c2 <- rgb(255,192,203, max = 255, alpha = 80, names = "lt.pink")
b <- min(c(simulated1, simulated2)) - 0.01 # Set the minimum for the breakpoints
#print(b)
e <- max(c(simulated1, simulated2)) + 0.1 # Set the maximum for the breakpoints
#print(e)
ax <- seq(b,e, length.out = number_breaks)
#print(ax)
hist1 = hist(simulated1, breaks = ax, plot = FALSE)
hist2 = hist(simulated2, breaks = ax, plot = FALSE)
maximum = max(c(hist1$count, hist2$count))
plot(hist1, col = c1, xlim = c(b,e), ylim = c(0,maximum), xlab = 'r^2 simulated values',
main = paste("m =", as.character(migration_value), sep = " "))
plot(hist2, add = TRUE, col = c2)
}
|
# Accession_Search_Functions.R
#
# Functions for searching for accessions within the three databases:
# GEO, SRA and SRR_GSM.
# These functions are used by higher level functions
# such as searchForAccessionAcrosDBs, convertAccession and searchForAccession
#
# CONTAINS:
# - .searchGEOForGSM()
# - .searchGEOForGSE()
#
# - .searchSRAForAccession()
#
# - .searchSRR_GSM()
#DATABASE CONNECTIONS ===*=== Come back and redo
#.GlobalEnv$sra_con <- dbConnect(SQLite(), dbname = 'SRAmetadb.sqlite')
#.GlobalEnv$geo_con <- dbConnect(SQLite(),'GEOmetadb.sqlite')
#.GlobalEnv$srr_gsm <- dbConnect(SQLite(),'SRR_GSM.sqlite')
#------------------------------------------------------
#------------------------------------------------------
#' Search for GSM in GEO
#'
#' @param acc_vector A character vector with accession numbers
#' @param geo_columns A character vector with columns to be returned
#' (from within gsm table)
#' @param gse_columns A character vector with columns to be returned
#' (from within gse table)
#' @return A data frame with results
#'
#' @examples
#'
#' # startSpiderSeqRDemo()
#' # .searchGEOForGSM("GSM1173367", "*", "*")
#'
#' @keywords internal
#'
.searchGEOForGSM <- function(acc_vector, geo_columns, gse_columns){
.mm("Running .searchGEOForGSM", "fn")
database_name <- "geo_con"
database_env <- ".GlobalEnv"
#Remove duplicates and order
acc_vector <- unique(acc_vector)
acc_vector <- acc_vector[orderAccessions(acc_vector)]
#Stop if list is not valid (i.e. non-gsm entries)
if (classifyAccession(acc_vector)!="gsm"){
stop("Only GSMs are allowed")
}
#Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
# Make sure that series_id and gsm are among the output columns
if (!("series_id" %in% geo_columns) | !("gsm" %in% geo_columns)){
if (!(length(geo_columns) == 1 & geo_columns[1] == "*")){
geo_columns <- c("gsm", "series_id", geo_columns)
geo_columns <- unique(geo_columns)
message(paste0("Added gsm and series_id columns ",
"to facilitate merging with gse table"))
}
}
# This is dealt with by .batchedAccSearch()
#geo_columns <- paste0(geo_columns, collapse = ", ")
search_count <- 0
#df <- data.frame()
#Search for GSMs
.mm("Searching in GEO for GSMs...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = database_name,
table_name = "gsm",
col_names = geo_columns)
# Rename GSM columns
df <- .renameGSMColumns(df)
#print(colnames(chunk))
#if (dim(df)[1]==0){
# df <- chunk
#}
df <- .appendGSEColumns(df, gse_columns)
# Implement a solution for counting matches ===*===
# print(paste0("Found results for ", search_count,
# " out of ", length(acc_vector), " accession search terms"))
# if (search_count!=length(acc_vector)){
# warning("Some accessions were not found in the GEO database")
# }
df <- unique(df)
.mm(".searchGEOForGSM completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' Search for GSE in GEO
#'
#' @param acc_vector A character vector with accession numbers
#' @param geo_columns A character vector with columns to be returned
#' (from within gsm table)
#' @param gse_columns A character vector with columns to be returned
#' (from within gse table)
#' @return A data frame with results
#'
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .searchGEOForGSE("GSE48253", "*", "*")
#'
#' @keywords internal
#'
.searchGEOForGSE <- function(acc_vector, geo_columns, gse_columns){
.mm("Running .searchGEOForGSE", "fn")
database_name <- "geo_con"
database_env <- ".GlobalEnv"
#Remove duplicates and order
acc_vector <- unique(acc_vector)
acc_vector <- acc_vector[orderAccessions(acc_vector)]
#Stop if list is not valid (i.e. non-gsm entries)
if (classifyAccession(acc_vector)!="series_id"){
stop("Only GSEs are allowed")
}
#Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
# Make sure that series_id and gsm are among the output columns
if (!("series_id" %in% geo_columns) | !("gsm" %in% geo_columns)){
if (!(length(geo_columns) == 1 & geo_columns[1] == "*")){
geo_columns <- c("gsm", "series_id", geo_columns)
geo_columns <- unique(geo_columns)
message(paste0("Added gsm and series_id columns to ",
"facilitate merging with gse table"))
}
}
# This is dealt with by .batchedAccSearch()
#geo_columns <- paste0(geo_columns, collapse = ", ")
search_count <- 0
#df <- data.frame()
#Search for GSEs
.mm("Searching in GEO for GSEs...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = database_name,
table_name = "gsm",
col_names = geo_columns)
# Rename GSM columns
df <- .renameGSMColumns(df)
df <- .appendGSEColumns(df, gse_columns)
# Implement a solution for counting matches ===*===
# print(paste0("Found results for ", search_count,
# " out of ", length(acc_vector), " accession search terms"))
# if (search_count!=length(acc_vector)){
# warning("Some accessions were not found in the GEO database")
# }
df <- unique(df)
.mm(".searchGEOForGSE completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
# Previously: searchForAccession. Adapted to only include SRA accessions
# .searchSRAForAccession <- function(acc_vector, sra_columns){
#' Search for SRA accessions
#'
#' @param acc_vector A character vector with accession numbers
#' @param sra_columns A character vector with columns to be returned
#' (from within sra table)
#' @return A data frame with results
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .searchSRAForAccession("SRP134708", "*")
#'
#' @keywords internal
#'
#'
.searchSRAForAccession <- function(acc_vector, sra_columns){
# Args: a character vector with accessions
# (needs to completely match to one accession class;
# no partial matches or mixed classes allowed)
#
# Returns: df from SRA with matches to the acc_vector
#
.mm("Running .searchSRAForAccession", "fn")
#------------------------------------------------
#------------------------------------------------
#TECHNICALITIES (taken from .searchSRA):
#------------------------------------------------
#------------------------------------------------
database_name <- "sra_con"
database_env <- ".GlobalEnv"
sra_table <- "sra"
# sra_columns <- c("experiment_name", "run_attribute",
# "experiment_accession", "experiment_url_link",
# "experiment_title", "library_strategy",
# "library_layout", "sample_alias", "taxon_id",
# "library_construction_protocol", "run_accession",
# "study_accession", "run_alias", "experiment_alias",
# "sample_name", "sample_attribute",
# "experiment_attribute")
# sra_columns <- c("experiment_title")
# sra_columns <- "*"
## This is dealt with by .batchedAccSearch()
# sra_columns <- paste(sra_columns, collapse = ", ")
#------------------------------------------------
x <- unique(acc_vector)
x <- x[orderAccessions(x)]
#Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
accession_class <- classifyAccession(x)
#search_count <- 0
#accession_df <- data.frame()
sra_accessions <- c("study_accession", "sample_accession",
"experiment_accession", "run_accession")
if (!(accession_class %in% sra_accessions)){
stop("Only SRA accessions are allowed")
}
# Search for SRA accessions
.mm("Searching in SRA...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = database_name,
table_name = "sra", col_names = sra_columns)
# print(paste0("Found results for ", search_count,
# " out of ", length(x), " accession search terms"))
# print(search_count)
# print(length(x))
# if (search_count!=length(x)){
# warning("Some accessions were not found in the SRA database")
# }
df <- unique(df)
# Rename SRA columns
df <- .renameSRAColumns(df)
.mm(".searchSRAForAccession completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
# .searchSRR_GSM <- function(acc_vector,
# srr_gsm_columns = c("run_accession",
# "gsm", "gsm_check")){
#' Search within SRR_GSM database
#'
#' @param acc_vector A character vector with accession numbers (GSM or SRR)
#' @param srr_gsm_columns A character vector with columns to be returned
#' (from within srr_gsm table)
#' @return A data frame with results
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .searchSRR_GSM("GSM1173367")
#'
#'
#' @keywords internal
#'
#'
#'
.searchSRR_GSM <- function(acc_vector,
srr_gsm_columns = c("run_accession", "gsm")){
.mm("Running .searchSRR_GSM", "fn")
database_name <- "srr_gsm"
database_env <- ".GlobalEnv"
accession_class <- classifyAccession(acc_vector)
# This is a safeguard in case incomplete SRA accessions
# had equivalents in GEO
# Can only remove it if it is certain that this is not the case
if (!(accession_class %in% c("run_accession", "gsm"))){
stop("Only SRRs and GSMs are accepted")
}
# Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
acc_vector <- unique(acc_vector)
acc_vector <- acc_vector[orderAccessions(acc_vector)]
srr_gsm_columns <- paste0(srr_gsm_columns, collapse = ", ")
search_count <- 0
accession_df <- data.frame()
.mm("Searching in SRR_GSM...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = "srr_gsm",
table_name = "srr_gsm",
col_names = srr_gsm_columns)
# query_beg <- paste0("SELECT ", srr_gsm_columns,
# " FROM srr_gsm WHERE ", accession_class, " = '")
# for (a in seq_along(acc_vector)){
# query <- paste0(query_beg, acc_vector[a], "'")
# print(query)
# chunk <- DBI::dbGetQuery(get(database_name,
# envir = get(database_env)), query)
# search_count <- search_count + as.integer(dim(chunk)[1]>=1)
# accession_df <- rbind(accession_df, chunk)
# }
# print(paste0("Found results for ", search_count,
# " out of ", length(acc_vector), " accession search terms"))
# if (search_count!=length(acc_vector)){
# warning("Some accessions were not found in the SRR_GSM database.
# You may wish to re-check for SRA-GEO correspondence manually")
# }
df <- unique(df)
.mm(".searchSRR_GSM completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' List all column names of SRA table
#'
#' @return Character vector containing column names of SRA table
#'
#'
#' @examples
#' # .listSRAFields()
#'
#' @keywords internal
#'
.listSRAFields <- function(){
database_name <- "sra_con"
database_env <- ".GlobalEnv"
sra_table <- "sra"
y <- DBI::dbListFields(get(database_name,
envir = get(database_env)), sra_table)
return(y)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' List all column names of the GSM table
#'
#' @return Character vector containing column names of GSM table
#'
#'
#' @examples
#' # .listGSMFields()
#'
#' @keywords internal
#'
.listGSMFields <- function(){
database_name <- "geo_con"
database_env <- ".GlobalEnv"
geo_table <- "gsm"
y <- DBI::dbListFields(get(database_name,
envir = get(database_env)), geo_table)
return(y)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' List all column names of the GSE table
#' @param omit_gse Logical indicating whether
#' to omit 'gse' column name from the output
#' @return Character vector containing column names of GSE table (except gse)
#'
#'
#' @examples
#' # .listGSEFields()
#'
#' @keywords internal
#'
.listGSEFields <- function(omit_gse = TRUE){
database_name <- "geo_con"
database_env <- ".GlobalEnv"
geo_table <- "gse"
y <- DBI::dbListFields(get(database_name,
envir = get(database_env)), geo_table)
if (omit_gse){
y <- y[!y %in% "gse"]
}
return(y)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' Make batched queries to databases
#'
#' @param acc_vector A character vector with accessions to search for
#' (must belong to the same type)
#' @param database_name A character with the name of the database connection
#' @param table_name A character with the name of the database table
#' @param col_names A character vector with column names to be returned
#' @param c_size Number of items to search for in a batch
#' (sqlite has a limit of 999 parameters within a single query)
#' @return Data frame with results of the query
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .batchedAccSearch(rep("SRR6823646", 10), "sra_con", "sra", "*", c_size = 1)
#'
#' @keywords internal
#'
.batchedAccSearch <- function(acc_vector, database_name,
table_name, col_names, c_size = 500){
database_env <- ".GlobalEnv"
sra_accessions <- c("run_accession", "experiment_accession",
"sample_accession", "study_accession")
# Classify acc_vector
acc_class <- classifyAccession(acc_vector)
# Define the strings before and after accession ####
# GSM
if (acc_class == "gsm"){
pre_el <- " gsm = '"
post_el <- "' OR "
end_char <- 4
}
# GSE
if (acc_class == "series_id"){
pre_el <- " (series_id LIKE '%"
mid_el <- "' OR series_id LIKE '%"
post_el <- ",%') OR "
end_char <- 4
}
# SRA
if (acc_class %in% sra_accessions){
pre_el <- paste0(" ", acc_class, " = '")
post_el <- "' OR "
end_char <- 4
}
# Collapse column names for sqlite query
col_names <- paste0(col_names, collapse = ", ")
# Split the vector into chunks
acc_vector_split <-
split(acc_vector, ceiling(seq_along(acc_vector)/c_size))
df <- data.frame()
# Beginning of the query
query_beg <- paste0("SELECT ", col_names, " FROM ", table_name, " WHERE (")
# Query construction and search ####
# Special case for srr_gsm ####
if (database_name == "srr_gsm"){
# For each batch
for (a in seq_along(acc_vector_split)){
query_el <- character()
# For each element in batch
for (i in seq_along(acc_vector_split[[a]])){
query_el <- paste0(query_el, pre_el,
acc_vector_split[[a]][i], post_el)
}
query_el <- substr(query_el, 1, nchar(query_el)-end_char)
query <- paste0(query_beg, query_el, " )")
.mm(query, "query")
chunk <- DBI::dbGetQuery(get(database_name,
envir = get(database_env)), query)
df <- rbind(df, chunk)
}
return(df)
}
if (acc_class %in% "series_id"){
# GSE - special treatment (acc_vector elements used twice) ####
# For each batch
for (a in seq_along(acc_vector_split)){
query_el <- character()
# For each element in batch
for (i in seq_along(acc_vector_split[[a]])){
query_el <- paste0(query_el, pre_el,
acc_vector_split[[a]][i], mid_el,
acc_vector_split[[a]][i], post_el)
}
query_el <- substr(query_el, 1, nchar(query_el)-end_char)
query <- paste0(query_beg, query_el, " )")
.mm(query, "query")
chunk <- DBI::dbGetQuery(get(database_name,
envir = get(database_env)), query)
df <- rbind(df, chunk)
}
} else if (acc_class %in% c(sra_accessions, "gsm")){
# GSM, SRA - standard treatment (acc_vector elements used once) ####
# For each batch
for (a in seq_along(acc_vector_split)){
query_el <- character()
# For each element in batch
for (i in seq_along(acc_vector_split[[a]])){
query_el <- paste0(query_el, pre_el,
acc_vector_split[[a]][i], post_el)
}
query_el <- substr(query_el, 1, nchar(query_el)-end_char)
query <- paste0(query_beg, query_el, " )")
.mm(query, "query")
chunk <- DBI::dbGetQuery(get(database_name,
envir = get(database_env)), query)
df <- rbind(df, chunk)
}
}
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
| /R/Accession_Search_Functions.R | no_license | ss-lab-cancerunit/SpiderSeqR | R | false | false | 19,657 | r | # Accession_Search_Functions.R
#
# Functions for searching for accessions within the three databases:
# GEO, SRA and SRR_GSM.
# These functions are used by higher level functions
# such as searchForAccessionAcrosDBs, convertAccession and searchForAccession
#
# CONTAINS:
# - .searchGEOForGSM()
# - .searchGEOForGSE()
#
# - .searchSRAForAccession()
#
# - .searchSRR_GSM()
#DATABASE CONNECTIONS ===*=== Come back and redo
#.GlobalEnv$sra_con <- dbConnect(SQLite(), dbname = 'SRAmetadb.sqlite')
#.GlobalEnv$geo_con <- dbConnect(SQLite(),'GEOmetadb.sqlite')
#.GlobalEnv$srr_gsm <- dbConnect(SQLite(),'SRR_GSM.sqlite')
#------------------------------------------------------
#------------------------------------------------------
#' Search for GSM in GEO
#'
#' @param acc_vector A character vector with accession numbers
#' @param geo_columns A character vector with columns to be returned
#' (from within gsm table)
#' @param gse_columns A character vector with columns to be returned
#' (from within gse table)
#' @return A data frame with results
#'
#' @examples
#'
#' # startSpiderSeqRDemo()
#' # .searchGEOForGSM("GSM1173367", "*", "*")
#'
#' @keywords internal
#'
.searchGEOForGSM <- function(acc_vector, geo_columns, gse_columns){
.mm("Running .searchGEOForGSM", "fn")
database_name <- "geo_con"
database_env <- ".GlobalEnv"
#Remove duplicates and order
acc_vector <- unique(acc_vector)
acc_vector <- acc_vector[orderAccessions(acc_vector)]
#Stop if list is not valid (i.e. non-gsm entries)
if (classifyAccession(acc_vector)!="gsm"){
stop("Only GSMs are allowed")
}
#Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
# Make sure that series_id and gsm are among the output columns
if (!("series_id" %in% geo_columns) | !("gsm" %in% geo_columns)){
if (!(length(geo_columns) == 1 & geo_columns[1] == "*")){
geo_columns <- c("gsm", "series_id", geo_columns)
geo_columns <- unique(geo_columns)
message(paste0("Added gsm and series_id columns ",
"to facilitate merging with gse table"))
}
}
# This is dealt with by .batchedAccSearch()
#geo_columns <- paste0(geo_columns, collapse = ", ")
search_count <- 0
#df <- data.frame()
#Search for GSMs
.mm("Searching in GEO for GSMs...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = database_name,
table_name = "gsm",
col_names = geo_columns)
# Rename GSM columns
df <- .renameGSMColumns(df)
#print(colnames(chunk))
#if (dim(df)[1]==0){
# df <- chunk
#}
df <- .appendGSEColumns(df, gse_columns)
# Implement a solution for counting matches ===*===
# print(paste0("Found results for ", search_count,
# " out of ", length(acc_vector), " accession search terms"))
# if (search_count!=length(acc_vector)){
# warning("Some accessions were not found in the GEO database")
# }
df <- unique(df)
.mm(".searchGEOForGSM completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' Search for GSE in GEO
#'
#' @param acc_vector A character vector with accession numbers
#' @param geo_columns A character vector with columns to be returned
#' (from within gsm table)
#' @param gse_columns A character vector with columns to be returned
#' (from within gse table)
#' @return A data frame with results
#'
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .searchGEOForGSE("GSE48253", "*", "*")
#'
#' @keywords internal
#'
.searchGEOForGSE <- function(acc_vector, geo_columns, gse_columns){
.mm("Running .searchGEOForGSE", "fn")
database_name <- "geo_con"
database_env <- ".GlobalEnv"
#Remove duplicates and order
acc_vector <- unique(acc_vector)
acc_vector <- acc_vector[orderAccessions(acc_vector)]
#Stop if list is not valid (i.e. non-gsm entries)
if (classifyAccession(acc_vector)!="series_id"){
stop("Only GSEs are allowed")
}
#Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
# Make sure that series_id and gsm are among the output columns
if (!("series_id" %in% geo_columns) | !("gsm" %in% geo_columns)){
if (!(length(geo_columns) == 1 & geo_columns[1] == "*")){
geo_columns <- c("gsm", "series_id", geo_columns)
geo_columns <- unique(geo_columns)
message(paste0("Added gsm and series_id columns to ",
"facilitate merging with gse table"))
}
}
# This is dealt with by .batchedAccSearch()
#geo_columns <- paste0(geo_columns, collapse = ", ")
search_count <- 0
#df <- data.frame()
#Search for GSEs
.mm("Searching in GEO for GSEs...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = database_name,
table_name = "gsm",
col_names = geo_columns)
# Rename GSM columns
df <- .renameGSMColumns(df)
df <- .appendGSEColumns(df, gse_columns)
# Implement a solution for counting matches ===*===
# print(paste0("Found results for ", search_count,
# " out of ", length(acc_vector), " accession search terms"))
# if (search_count!=length(acc_vector)){
# warning("Some accessions were not found in the GEO database")
# }
df <- unique(df)
.mm(".searchGEOForGSE completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
# Previously: searchForAccession. Adapted to only include SRA accessions
# .searchSRAForAccession <- function(acc_vector, sra_columns){
#' Search for SRA accessions
#'
#' @param acc_vector A character vector with accession numbers
#' @param sra_columns A character vector with columns to be returned
#' (from within sra table)
#' @return A data frame with results
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .searchSRAForAccession("SRP134708", "*")
#'
#' @keywords internal
#'
#'
.searchSRAForAccession <- function(acc_vector, sra_columns){
# Args: a character vector with accessions
# (needs to completely match to one accession class;
# no partial matches or mixed classes allowed)
#
# Returns: df from SRA with matches to the acc_vector
#
.mm("Running .searchSRAForAccession", "fn")
#------------------------------------------------
#------------------------------------------------
#TECHNICALITIES (taken from .searchSRA):
#------------------------------------------------
#------------------------------------------------
database_name <- "sra_con"
database_env <- ".GlobalEnv"
sra_table <- "sra"
# sra_columns <- c("experiment_name", "run_attribute",
# "experiment_accession", "experiment_url_link",
# "experiment_title", "library_strategy",
# "library_layout", "sample_alias", "taxon_id",
# "library_construction_protocol", "run_accession",
# "study_accession", "run_alias", "experiment_alias",
# "sample_name", "sample_attribute",
# "experiment_attribute")
# sra_columns <- c("experiment_title")
# sra_columns <- "*"
## This is dealt with by .batchedAccSearch()
# sra_columns <- paste(sra_columns, collapse = ", ")
#------------------------------------------------
x <- unique(acc_vector)
x <- x[orderAccessions(x)]
#Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
accession_class <- classifyAccession(x)
#search_count <- 0
#accession_df <- data.frame()
sra_accessions <- c("study_accession", "sample_accession",
"experiment_accession", "run_accession")
if (!(accession_class %in% sra_accessions)){
stop("Only SRA accessions are allowed")
}
# Search for SRA accessions
.mm("Searching in SRA...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = database_name,
table_name = "sra", col_names = sra_columns)
# print(paste0("Found results for ", search_count,
# " out of ", length(x), " accession search terms"))
# print(search_count)
# print(length(x))
# if (search_count!=length(x)){
# warning("Some accessions were not found in the SRA database")
# }
df <- unique(df)
# Rename SRA columns
df <- .renameSRAColumns(df)
.mm(".searchSRAForAccession completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
# .searchSRR_GSM <- function(acc_vector,
# srr_gsm_columns = c("run_accession",
# "gsm", "gsm_check")){
#' Search within SRR_GSM database
#'
#' @param acc_vector A character vector with accession numbers (GSM or SRR)
#' @param srr_gsm_columns A character vector with columns to be returned
#' (from within srr_gsm table)
#' @return A data frame with results
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .searchSRR_GSM("GSM1173367")
#'
#'
#' @keywords internal
#'
#'
#'
.searchSRR_GSM <- function(acc_vector,
srr_gsm_columns = c("run_accession", "gsm")){
.mm("Running .searchSRR_GSM", "fn")
database_name <- "srr_gsm"
database_env <- ".GlobalEnv"
accession_class <- classifyAccession(acc_vector)
# This is a safeguard in case incomplete SRA accessions
# had equivalents in GEO
# Can only remove it if it is certain that this is not the case
if (!(accession_class %in% c("run_accession", "gsm"))){
stop("Only SRRs and GSMs are accepted")
}
# Make sure that the query will not be empty
if (length(acc_vector)==0){
acc_vector <- "nth"
}
acc_vector <- unique(acc_vector)
acc_vector <- acc_vector[orderAccessions(acc_vector)]
srr_gsm_columns <- paste0(srr_gsm_columns, collapse = ", ")
search_count <- 0
accession_df <- data.frame()
.mm("Searching in SRR_GSM...", "prog")
df <- .batchedAccSearch(acc_vector = acc_vector,
database_name = "srr_gsm",
table_name = "srr_gsm",
col_names = srr_gsm_columns)
# query_beg <- paste0("SELECT ", srr_gsm_columns,
# " FROM srr_gsm WHERE ", accession_class, " = '")
# for (a in seq_along(acc_vector)){
# query <- paste0(query_beg, acc_vector[a], "'")
# print(query)
# chunk <- DBI::dbGetQuery(get(database_name,
# envir = get(database_env)), query)
# search_count <- search_count + as.integer(dim(chunk)[1]>=1)
# accession_df <- rbind(accession_df, chunk)
# }
# print(paste0("Found results for ", search_count,
# " out of ", length(acc_vector), " accession search terms"))
# if (search_count!=length(acc_vector)){
# warning("Some accessions were not found in the SRR_GSM database.
# You may wish to re-check for SRA-GEO correspondence manually")
# }
df <- unique(df)
.mm(".searchSRR_GSM completed", "fn")
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' List all column names of SRA table
#'
#' @return Character vector containing column names of SRA table
#'
#'
#' @examples
#' # .listSRAFields()
#'
#' @keywords internal
#'
.listSRAFields <- function(){
database_name <- "sra_con"
database_env <- ".GlobalEnv"
sra_table <- "sra"
y <- DBI::dbListFields(get(database_name,
envir = get(database_env)), sra_table)
return(y)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' List all column names of the GSM table
#'
#' @return Character vector containing column names of GSM table
#'
#'
#' @examples
#' # .listGSMFields()
#'
#' @keywords internal
#'
.listGSMFields <- function(){
database_name <- "geo_con"
database_env <- ".GlobalEnv"
geo_table <- "gsm"
y <- DBI::dbListFields(get(database_name,
envir = get(database_env)), geo_table)
return(y)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' List all column names of the GSE table
#' @param omit_gse Logical indicating whether
#' to omit 'gse' column name from the output
#' @return Character vector containing column names of GSE table (except gse)
#'
#'
#' @examples
#' # .listGSEFields()
#'
#' @keywords internal
#'
.listGSEFields <- function(omit_gse = TRUE){
database_name <- "geo_con"
database_env <- ".GlobalEnv"
geo_table <- "gse"
y <- DBI::dbListFields(get(database_name,
envir = get(database_env)), geo_table)
if (omit_gse){
y <- y[!y %in% "gse"]
}
return(y)
}
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#------------------------------------------------------
#' Make batched queries to databases
#'
#' @param acc_vector A character vector with accessions to search for
#' (must belong to the same type)
#' @param database_name A character with the name of the database connection
#' @param table_name A character with the name of the database table
#' @param col_names A character vector with column names to be returned
#' @param c_size Number of items to search for in a batch
#' (sqlite has a limit of 999 parameters within a single query)
#' @return Data frame with results of the query
#'
#' @examples
#' # startSpiderSeqRDemo()
#' # .batchedAccSearch(rep("SRR6823646", 10), "sra_con", "sra", "*", c_size = 1)
#'
#' @keywords internal
#'
.batchedAccSearch <- function(acc_vector, database_name,
table_name, col_names, c_size = 500){
database_env <- ".GlobalEnv"
sra_accessions <- c("run_accession", "experiment_accession",
"sample_accession", "study_accession")
# Classify acc_vector
acc_class <- classifyAccession(acc_vector)
# Define the strings before and after accession ####
# GSM
if (acc_class == "gsm"){
pre_el <- " gsm = '"
post_el <- "' OR "
end_char <- 4
}
# GSE
if (acc_class == "series_id"){
pre_el <- " (series_id LIKE '%"
mid_el <- "' OR series_id LIKE '%"
post_el <- ",%') OR "
end_char <- 4
}
# SRA
if (acc_class %in% sra_accessions){
pre_el <- paste0(" ", acc_class, " = '")
post_el <- "' OR "
end_char <- 4
}
# Collapse column names for sqlite query
col_names <- paste0(col_names, collapse = ", ")
# Split the vector into chunks
acc_vector_split <-
split(acc_vector, ceiling(seq_along(acc_vector)/c_size))
df <- data.frame()
# Beginning of the query
query_beg <- paste0("SELECT ", col_names, " FROM ", table_name, " WHERE (")
# Query construction and search ####
# Special case for srr_gsm ####
if (database_name == "srr_gsm"){
# For each batch
for (a in seq_along(acc_vector_split)){
query_el <- character()
# For each element in batch
for (i in seq_along(acc_vector_split[[a]])){
query_el <- paste0(query_el, pre_el,
acc_vector_split[[a]][i], post_el)
}
query_el <- substr(query_el, 1, nchar(query_el)-end_char)
query <- paste0(query_beg, query_el, " )")
.mm(query, "query")
chunk <- DBI::dbGetQuery(get(database_name,
envir = get(database_env)), query)
df <- rbind(df, chunk)
}
return(df)
}
if (acc_class %in% "series_id"){
# GSE - special treatment (acc_vector elements used twice) ####
# For each batch
for (a in seq_along(acc_vector_split)){
query_el <- character()
# For each element in batch
for (i in seq_along(acc_vector_split[[a]])){
query_el <- paste0(query_el, pre_el,
acc_vector_split[[a]][i], mid_el,
acc_vector_split[[a]][i], post_el)
}
query_el <- substr(query_el, 1, nchar(query_el)-end_char)
query <- paste0(query_beg, query_el, " )")
.mm(query, "query")
chunk <- DBI::dbGetQuery(get(database_name,
envir = get(database_env)), query)
df <- rbind(df, chunk)
}
} else if (acc_class %in% c(sra_accessions, "gsm")){
# GSM, SRA - standard treatment (acc_vector elements used once) ####
# For each batch
for (a in seq_along(acc_vector_split)){
query_el <- character()
# For each element in batch
for (i in seq_along(acc_vector_split[[a]])){
query_el <- paste0(query_el, pre_el,
acc_vector_split[[a]][i], post_el)
}
query_el <- substr(query_el, 1, nchar(query_el)-end_char)
query <- paste0(query_beg, query_el, " )")
.mm(query, "query")
chunk <- DBI::dbGetQuery(get(database_name,
envir = get(database_env)), query)
df <- rbind(df, chunk)
}
}
return(df)
}
#------------------------------------------------------
#------------------------------------------------------
|
rm(list=ls())
setwd("~/R/Regression/exercise")
# 단순 회귀분석 연습
# 광고비와 매출액간의 상관관계를 보기 위해서 최근 10개월간의 데이터를 수집한 자료
rt <- read.csv("1_sr_text.csv")
str(rt)
summary(rt)
qqnorm(rt$sales)
model<-lm(sales~ promo, data=rt)
summary(model)
model_simple<-lm(sales~ promo, data=rt)
anova(model, model_simple)
new_efficiency <-rnorm(10, mean=mean(rt$sales), sd=sd(rt$sales))
new_efficiency <-as.data.frame(new_efficiency)
colnames(new_efficiency)<-c("promo")
predict(model_simple, new_efficiency, interval="prediction")
| /simple regression.R | no_license | Joshuariver/regression | R | false | false | 620 | r | rm(list=ls())
setwd("~/R/Regression/exercise")
# 단순 회귀분석 연습
# 광고비와 매출액간의 상관관계를 보기 위해서 최근 10개월간의 데이터를 수집한 자료
rt <- read.csv("1_sr_text.csv")
str(rt)
summary(rt)
qqnorm(rt$sales)
model<-lm(sales~ promo, data=rt)
summary(model)
model_simple<-lm(sales~ promo, data=rt)
anova(model, model_simple)
new_efficiency <-rnorm(10, mean=mean(rt$sales), sd=sd(rt$sales))
new_efficiency <-as.data.frame(new_efficiency)
colnames(new_efficiency)<-c("promo")
predict(model_simple, new_efficiency, interval="prediction")
|
library(spatstat)
### Name: Extract.linim
### Title: Extract Subset of Pixel Image on Linear Network
### Aliases: [.linim
### Keywords: spatial manip
### ** Examples
M <- as.mask.psp(as.psp(simplenet))
Z <- as.im(function(x,y){x}, W=M)
Y <- linim(simplenet, Z)
X <- runiflpp(4, simplenet)
Y[X]
Y[square(c(0.3, 0.6))]
| /data/genthat_extracted_code/spatstat/examples/Extract.linim.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 336 | r | library(spatstat)
### Name: Extract.linim
### Title: Extract Subset of Pixel Image on Linear Network
### Aliases: [.linim
### Keywords: spatial manip
### ** Examples
M <- as.mask.psp(as.psp(simplenet))
Z <- as.im(function(x,y){x}, W=M)
Y <- linim(simplenet, Z)
X <- runiflpp(4, simplenet)
Y[X]
Y[square(c(0.3, 0.6))]
|
#Setting work directory
setwd("/Users/emilienielsen/Documents/Coursera/Project1")
#Read in data
data <- read.table("household_power_consumption.txt", header=T, sep=";")
#Subsetting data
sub <- subset(data, data$Date == "1/2/2007" | data$Date == "2/2/2007")
#Transforming sub metering variables into numeric
sub$Sub_metering_1 <- as.numeric(sub$Sub_metering_1)
sub$Sub_metering_2 <- as.numeric(sub$Sub_metering_2)
sub$Sub_metering_3 <- as.numeric(sub$Sub_metering_3)
#Making the plot and saving
png(filename="plot3.png", width = 480, height = 480)
plot(sub$Sub_metering_1, type="n", xaxt="n", xlab="", ylab="Energy sub metering")
lines(sub$Sub_metering_1, col="black")
lines(sub$Sub_metering_2, col="red")
lines(sub$Sub_metering_3, col="blue")
legend("topright", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lty=c(1,1,1), col=c("black", "red","blue"))
axis(1,at=c(1,1+1440,2880), labels=c("Thu", "Fri", "Sat"))
dev.off()
| /plot3.R | no_license | emilieprang/ExData_Plotting1 | R | false | false | 966 | r |
#Setting work directory
setwd("/Users/emilienielsen/Documents/Coursera/Project1")
#Read in data
data <- read.table("household_power_consumption.txt", header=T, sep=";")
#Subsetting data
sub <- subset(data, data$Date == "1/2/2007" | data$Date == "2/2/2007")
#Transforming sub metering variables into numeric
sub$Sub_metering_1 <- as.numeric(sub$Sub_metering_1)
sub$Sub_metering_2 <- as.numeric(sub$Sub_metering_2)
sub$Sub_metering_3 <- as.numeric(sub$Sub_metering_3)
#Making the plot and saving
png(filename="plot3.png", width = 480, height = 480)
plot(sub$Sub_metering_1, type="n", xaxt="n", xlab="", ylab="Energy sub metering")
lines(sub$Sub_metering_1, col="black")
lines(sub$Sub_metering_2, col="red")
lines(sub$Sub_metering_3, col="blue")
legend("topright", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lty=c(1,1,1), col=c("black", "red","blue"))
axis(1,at=c(1,1+1440,2880), labels=c("Thu", "Fri", "Sat"))
dev.off()
|
install.packages( "ggplot2" ) | /src/main/scripts/R/reinstall.R | no_license | MengsiLu/population-linkage-master | R | false | false | 30 | r |
install.packages( "ggplot2" ) |
########################################################
## HierarcHical Clustering
########################################################
#실습 1. iris 데이터셋을 이용한 계층형 군집화
iris2
## 계층형 군집화 함수: hclust()
## 거리 계산: dist(). default=euclidean
## 유사도 측정 방법: method 인자 값 -> single, complete, average
hc <- hclust(dist(iris2), method="average")
hc
##시각화
plot(hc, lables = iris$Species, hang = -1)
rect.hclust(hc, k=3)
##클러스터 분할
ghc <- cutree(hc, k=3)
ghc
table(iris$Species, ghc)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 실습 2. 계층형 군집화를 이용해 적절한 군집 수를 확인하고
# k-means 알고리즘을 적용해 군집별로 시각화
## 데이터: ggplot2::diamonds
dia <- ggplot2::diamonds
dim(dia)
## 1000개 샘플링
t <- sample(1:nrow(dia), 1000)
test <- dia[t, ]
dim(test)
str(test)
mydia <- test[c("price", "carat", "depth", "table")]
head(mydia)
## 계층형 군집화
result <- hclust(dist(mydia), method="average")
plot(result, hang=-1) ### hang = -1 -> line from the bottom
##3개 군집화
result2 <- kmeans(mydia, 3)
##데이터에 클러스터 할당
mydia$cluster <- result2$cluster
head(mydia)
##변수 간 상간관계
cor(mydia[, -5])
plot(mydia[, -5])
## 시각화
plot(mydia$carat, mydia$price, col=mydia$cluster+1)
## 중심점 표시
points(result2$centers[, c("carat", "price")], pch=8, cex=5)
#과제: 오늘 한 코드만이라도 잘 숙지하자. | /11_Clustering/src/3_HC.r | no_license | jimyungkoh/BigDataAnalysis | R | false | false | 1,528 | r | ########################################################
## HierarcHical Clustering
########################################################
#실습 1. iris 데이터셋을 이용한 계층형 군집화
iris2
## 계층형 군집화 함수: hclust()
## 거리 계산: dist(). default=euclidean
## 유사도 측정 방법: method 인자 값 -> single, complete, average
hc <- hclust(dist(iris2), method="average")
hc
##시각화
plot(hc, lables = iris$Species, hang = -1)
rect.hclust(hc, k=3)
##클러스터 분할
ghc <- cutree(hc, k=3)
ghc
table(iris$Species, ghc)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 실습 2. 계층형 군집화를 이용해 적절한 군집 수를 확인하고
# k-means 알고리즘을 적용해 군집별로 시각화
## 데이터: ggplot2::diamonds
dia <- ggplot2::diamonds
dim(dia)
## 1000개 샘플링
t <- sample(1:nrow(dia), 1000)
test <- dia[t, ]
dim(test)
str(test)
mydia <- test[c("price", "carat", "depth", "table")]
head(mydia)
## 계층형 군집화
result <- hclust(dist(mydia), method="average")
plot(result, hang=-1) ### hang = -1 -> line from the bottom
##3개 군집화
result2 <- kmeans(mydia, 3)
##데이터에 클러스터 할당
mydia$cluster <- result2$cluster
head(mydia)
##변수 간 상간관계
cor(mydia[, -5])
plot(mydia[, -5])
## 시각화
plot(mydia$carat, mydia$price, col=mydia$cluster+1)
## 중심점 표시
points(result2$centers[, c("carat", "price")], pch=8, cex=5)
#과제: 오늘 한 코드만이라도 잘 숙지하자. |
library(testthat)
library(koderkow)
test_check("koderkow")
| /tests/testthat.R | permissive | kowtest/koderkow | R | false | false | 60 | r | library(testthat)
library(koderkow)
test_check("koderkow")
|
rm(list=ls())
options <- NULL
options$nFieldLimit <- 800
options$listFields <- c("VAR", "DELTA")
#options$listFields <- c("DELTA")
require(reshape)
require(RODBC)
source("H:/user/R/RMG/TimeFunctions/add.date.R")
today <- as.Date(format(Sys.time(), "%Y-%m-%d"))
#today <- as.Date("2007-08-01")
options$dates <- add.date(today, "-1 b")
#options$dates <- as.Date("2007-08-31")
options$portfolio <- "Mark Orman Netted Portfolio"
source("H:/user/R/RMG/Energy/Trading/PortfolioAnalysis/mainPortfolioReportE_uat.r")
mainPortfolioReportE_uat(options) | /R Extension/RMG/Energy/Trading/PortfolioAnalysis/overnightPortfolioReport_uat.r | no_license | uhasan1/QLExtension-backup | R | false | false | 560 | r |
rm(list=ls())
options <- NULL
options$nFieldLimit <- 800
options$listFields <- c("VAR", "DELTA")
#options$listFields <- c("DELTA")
require(reshape)
require(RODBC)
source("H:/user/R/RMG/TimeFunctions/add.date.R")
today <- as.Date(format(Sys.time(), "%Y-%m-%d"))
#today <- as.Date("2007-08-01")
options$dates <- add.date(today, "-1 b")
#options$dates <- as.Date("2007-08-31")
options$portfolio <- "Mark Orman Netted Portfolio"
source("H:/user/R/RMG/Energy/Trading/PortfolioAnalysis/mainPortfolioReportE_uat.r")
mainPortfolioReportE_uat(options) |
################################################################################
# R SCRIPT FOR ANALYSIS
# Author:
# Date:
################################################################################ | /inst/structure/project_analysis/Do/04_analysis.R | no_license | lampk/Lmisc | R | false | false | 203 | r | ################################################################################
# R SCRIPT FOR ANALYSIS
# Author:
# Date:
################################################################################ |
library(data.table)
source("futil.R")
file_list = vector();
file_list = append(file_list,"submission-script-001-94.3.csv") # PB: 0.39319
#file_list = append(file_list,"submission-script-4-001-93.csv")
#file_list = append(file_list,"submit.wip.001-2.MEAN.csv")
#file_list = append(file_list,"./public/xgbsubmission08.csv")
#file_list = append(file_list,"./public/xgbsubmission09.csv")
#file_list = append(file_list,"./public/xgbsubmission10.csv")
#file_list = append(file_list,"./public/xgbsubmission20.csv")
file_list = append(file_list,"./public/xgbsubmission30.csv")
pred_file_list = list()
for ( i in 1:length(file_list))
pred_file_list = append(pred_file_list,fread(file_list[i],select = "Response"))
pred_file_total = 0
for (i in 1:length(pred_file_list))
{
pred_file_total = pred_file_total + pred_file_list[[i]]
}
for (i in 1:length(pred_file_list))
{
print(sum(pred_file_list[[i]]))
}
dt_ens = 0*pred_file_total
dt_ens[which(pred_file_total>=1)] = 1
print(sum(dt_ens))
dt <- data.table(Id=Id,Response = dt_ens)
print("Store prediction")
write.csv(dt, "submission.csv", row.names = F)
| /R/ensembler.02.R | no_license | tudor-m/Kaggle-Bosch | R | false | false | 1,108 | r | library(data.table)
source("futil.R")
file_list = vector();
file_list = append(file_list,"submission-script-001-94.3.csv") # PB: 0.39319
#file_list = append(file_list,"submission-script-4-001-93.csv")
#file_list = append(file_list,"submit.wip.001-2.MEAN.csv")
#file_list = append(file_list,"./public/xgbsubmission08.csv")
#file_list = append(file_list,"./public/xgbsubmission09.csv")
#file_list = append(file_list,"./public/xgbsubmission10.csv")
#file_list = append(file_list,"./public/xgbsubmission20.csv")
file_list = append(file_list,"./public/xgbsubmission30.csv")
pred_file_list = list()
for ( i in 1:length(file_list))
pred_file_list = append(pred_file_list,fread(file_list[i],select = "Response"))
pred_file_total = 0
for (i in 1:length(pred_file_list))
{
pred_file_total = pred_file_total + pred_file_list[[i]]
}
for (i in 1:length(pred_file_list))
{
print(sum(pred_file_list[[i]]))
}
dt_ens = 0*pred_file_total
dt_ens[which(pred_file_total>=1)] = 1
print(sum(dt_ens))
dt <- data.table(Id=Id,Response = dt_ens)
print("Store prediction")
write.csv(dt, "submission.csv", row.names = F)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/simulate.R
\name{simulate_pulse}
\alias{simulate_pulse}
\title{Simulate pulsatile hormone data}
\usage{
simulate_pulse(num_obs = 144, interval = 10, error_var = 0.005,
ipi_mean = 12, ipi_var = 40, ipi_min = 4, mass_mean = 3.5,
mass_sd = 1.6, width_mean = 35, width_sd = 5,
halflife_mean = NULL, halflife_var = NULL, baseline_mean = NULL,
baseline_var = NULL, constant_halflife = 45,
constant_baseline = 2.6)
}
\arguments{
\item{num_obs}{Number of observations to simulate. Duration of observation
window equals \code{num_obs} times \code{interval}.}
\item{interval}{Time in minutes between observations, typically 6-10.}
\item{error_var}{Variance of the error added at each observation, error ~ N(0, sqrt(error_var)).}
\item{ipi_mean}{Mean number of sampling units between pulses (mean inter-pulse interval).}
\item{ipi_var}{Variance of gamma for drawing interpulse interval}
\item{ipi_min}{Minimum number of units between pulses}
\item{mass_mean}{Mean pulse mass}
\item{mass_sd}{Standard deviation of pulse mass}
\item{width_mean}{Mean pulse width (in minutes)}
\item{width_sd}{Standard deviation of pulse width (in minutes)}
\item{halflife_mean}{Mean of half-life (in minutes)}
\item{halflife_var}{Variance of half-life (in minutes)}
\item{baseline_mean}{Mean of baseline}
\item{baseline_var}{Variance of baseline}
\item{constant_halflife}{To use a constant (specified) half-life, set this
to a constant value [0,inf) in minutes. Mean and variance of half-life are
not used if this is non-null.}
\item{constant_baseline}{To use a constant (specified) baseline, set this to
a constant [0,inf). Mean and variance of baseline are not used if this is
non-null.}
}
\value{
A object of class \code{pulse_sim} containing time-series dataset
and dataset of characteristics of each pulse
}
\description{
\code{\link{simulate_pulse}} simulates a time series dataset
representing blood concentration measurements of a pulsatile hormone. Both
the time series and a dataset of the individual pulse characteristics are
returned.
}
\examples{
this_pulse <- simulate_pulse()
str(this_pulse)
plot(this_pulse)
}
\seealso{
print.pulse_sim, plot.pulse_sim
}
\keyword{pulse}
\keyword{simulation}
| /R-package/man/simulate_pulse.Rd | no_license | BayesPulse/libpulsatile | R | false | true | 2,289 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/simulate.R
\name{simulate_pulse}
\alias{simulate_pulse}
\title{Simulate pulsatile hormone data}
\usage{
simulate_pulse(num_obs = 144, interval = 10, error_var = 0.005,
ipi_mean = 12, ipi_var = 40, ipi_min = 4, mass_mean = 3.5,
mass_sd = 1.6, width_mean = 35, width_sd = 5,
halflife_mean = NULL, halflife_var = NULL, baseline_mean = NULL,
baseline_var = NULL, constant_halflife = 45,
constant_baseline = 2.6)
}
\arguments{
\item{num_obs}{Number of observations to simulate. Duration of observation
window equals \code{num_obs} times \code{interval}.}
\item{interval}{Time in minutes between observations, typically 6-10.}
\item{error_var}{Variance of the error added at each observation, error ~ N(0, sqrt(error_var)).}
\item{ipi_mean}{Mean number of sampling units between pulses (mean inter-pulse interval).}
\item{ipi_var}{Variance of gamma for drawing interpulse interval}
\item{ipi_min}{Minimum number of units between pulses}
\item{mass_mean}{Mean pulse mass}
\item{mass_sd}{Standard deviation of pulse mass}
\item{width_mean}{Mean pulse width (in minutes)}
\item{width_sd}{Standard deviation of pulse width (in minutes)}
\item{halflife_mean}{Mean of half-life (in minutes)}
\item{halflife_var}{Variance of half-life (in minutes)}
\item{baseline_mean}{Mean of baseline}
\item{baseline_var}{Variance of baseline}
\item{constant_halflife}{To use a constant (specified) half-life, set this
to a constant value [0,inf) in minutes. Mean and variance of half-life are
not used if this is non-null.}
\item{constant_baseline}{To use a constant (specified) baseline, set this to
a constant [0,inf). Mean and variance of baseline are not used if this is
non-null.}
}
\value{
A object of class \code{pulse_sim} containing time-series dataset
and dataset of characteristics of each pulse
}
\description{
\code{\link{simulate_pulse}} simulates a time series dataset
representing blood concentration measurements of a pulsatile hormone. Both
the time series and a dataset of the individual pulse characteristics are
returned.
}
\examples{
this_pulse <- simulate_pulse()
str(this_pulse)
plot(this_pulse)
}
\seealso{
print.pulse_sim, plot.pulse_sim
}
\keyword{pulse}
\keyword{simulation}
|
skyarea=function(long=c(129,141),lat=c(-2,3),inunit='deg',outunit='deg2',sep=":"){
if(inunit %in% c('deg','amin','asec','rad','sex')==FALSE){stop('inunit must be one of deg, amin, asec, rad or sex')}
if(outunit %in% c('deg2','amin2','asec2','rad2','sr')==FALSE){stop('outunit must be one of deg2, amin2, asec2 or rad2')}
if(length(long)==1){long=c(0,long)}
if(length(lat)==1){lat=c(0,lat)}
fullsky=129600/pi
if(inunit=='sex'){long=hms2deg(long,sep=sep);lat=dms2deg(lat,sep=sep)}
if(inunit=='amin'){long=long/60;lat=lat/60}
if(inunit=='asec'){long=long/3600;lat=lat/3600}
if(inunit=='rad'){long=long*180/pi;lat=lat*180/pi}
areafrac=((sin(lat[2]*pi/180)-sin(lat[1]*pi/180))*(long[2]-long[1])/360)/2
if(areafrac<0){stop('Sky area is non-physical (negative)')}
if(areafrac>1){stop('Sky area is non-physical (bigger than the full sky)')}
area=areafrac*fullsky
if(outunit=='amin2'){area=area*3600}
if(outunit=='asec2'){area=area*12960000}
if(outunit=='rad2' | outunit=='sr'){area=area/(180/pi)^2}
return(c(area=area,areafrac=areafrac))
} | /R/skyarea.R | no_license | malpaslan/celestial | R | false | false | 1,065 | r | skyarea=function(long=c(129,141),lat=c(-2,3),inunit='deg',outunit='deg2',sep=":"){
if(inunit %in% c('deg','amin','asec','rad','sex')==FALSE){stop('inunit must be one of deg, amin, asec, rad or sex')}
if(outunit %in% c('deg2','amin2','asec2','rad2','sr')==FALSE){stop('outunit must be one of deg2, amin2, asec2 or rad2')}
if(length(long)==1){long=c(0,long)}
if(length(lat)==1){lat=c(0,lat)}
fullsky=129600/pi
if(inunit=='sex'){long=hms2deg(long,sep=sep);lat=dms2deg(lat,sep=sep)}
if(inunit=='amin'){long=long/60;lat=lat/60}
if(inunit=='asec'){long=long/3600;lat=lat/3600}
if(inunit=='rad'){long=long*180/pi;lat=lat*180/pi}
areafrac=((sin(lat[2]*pi/180)-sin(lat[1]*pi/180))*(long[2]-long[1])/360)/2
if(areafrac<0){stop('Sky area is non-physical (negative)')}
if(areafrac>1){stop('Sky area is non-physical (bigger than the full sky)')}
area=areafrac*fullsky
if(outunit=='amin2'){area=area*3600}
if(outunit=='asec2'){area=area*12960000}
if(outunit=='rad2' | outunit=='sr'){area=area/(180/pi)^2}
return(c(area=area,areafrac=areafrac))
} |
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
# test if there is at least one argument: if not, return an error
if (length(args)!=4) {
stop("NOPE! Bad args. ARGH!", call.=FALSE)
} else {
input_r = as.numeric(args[1])
input_p = as.numeric(args[2])
input_nsim = as.numeric(args[3])
input_seed = as.numeric(args[4])
}
library(tidyverse)
library(simulator)
library(rre)
library(stringr)
library(magrittr)
library(actuar)
logarithmic_FCT_list <- function(ccc, p_log, replicates) {
new_model(name = sprintf("logarithmic_fct-list"),
label = sprintf("Logarithmic draws from true C = %s, prob = %s, replicates = %s)", ccc, p_log, replicates),
params = list(ccc = ccc, p_log = p_log, replicates = replicates),
simulate = function(ccc, p_log, replicates, nsim) {
# this function must return a list of length nsim
x <- replicate(nsim,
(actuar::rlogarithmic(n = ccc*replicates,
prob = p_log) - 1) %>%
matrix(. ,nrow = ccc, ncol = replicates) %>%
split(.,col(.)) %>%
lapply(make_frequency_count_table),
simplify = F)
return(x);
})
}
# Method metrics:
# if/else here is because I changed the method return wording from "optimal" to "selected".
selected_lambda <- new_metric("selected_lambda", "selected_lambda",
metric = function(model,out) {
best <- out[["best"]]
namen <- names(best)
if ("optimal_lambda" %in% namen) {
rtn <- best[["optimal_lambda"]]
} else if ("selected_lambda" %in% namen) {
rtn <- best[["selected_lambda"]]
} else {
stop("Your 'out' object doesnt have the right names.")
}
return(rtn)
})
ccc_hat <- new_metric("ccc_hat", "ccc_hat",
metric = function(model,out) {
best <- out[["best"]]
if (!is.null(best[["ccc_hat"]])) {
chat <- best[["ccc_hat"]]
} else if (!is.null(best[["ccc"]])) {
chat <- best[["ccc"]]
} else {
stop("no chat?")
}
return(chat)
})
# Method 0:
mle_no_pen <- new_method("mle_no_pen", "mle_no_pen",
method = function(model, draw) {
result <- rre::unregularized_mle(draw,
c_seq_len = 20,
multiplier = 4)
return(result)
}
)
# Method 3
gof <- new_method("gof", "gof",
method = function(model, draw) {
result <- rre::gof_criterion(draw,
lambda_vec = c(seq(0, 20, by=5),
seq(30, 50, by=10),
seq(70, 140, by=35)),
c_seq_len = 20,
multiplier = 4)
return(result)
}
)
### determine what is the right tuning parameters to choose
my_sim <- new_simulation(name = "logarithmic_sims",
label = "logarithmic_sims") %>%
generate_model(seed= paste(input_seed, input_r, sep = ""),
make_model = logarithmic_FCT_list,
ccc = as.list(c(1000, 2000)),
p_log = input_p,
replicates = input_r,
vary_along = "ccc") %>%
simulate_from_model(nsim = input_nsim)
my_sim %<>%
run_method(list(mle_no_pen,
gof))
my_sim %<>%
evaluate(list(ccc_hat,
selected_lambda))
ev_df <- my_sim %>% evals %>% as.data.frame
model_df <- my_sim %>% model %>% as.data.frame
ev_with_model_params <- dplyr::right_join(model_df, ev_df, by = c("name" = "Model"))
write_csv(ev_with_model_params,
paste("logarithmic_r_", input_r,
"_p_", input_p,
"_nsim_", input_nsim,
"_seed_", input_seed, ".csv", sep = ""))
# expand.grid(c(30, 14, 6), c(0.99, 0.995), 4, 1:12) %>%
# as_tibble %>%
# mutate(all = paste(Var1, Var2, Var3, Var4)) %>%
# arrange(Var4) %>%
# select(all) %$% all %>%
# cat(sep="\n")
| /sdl-rre/scripts/logarithmic-03-r-p-nsim-seed.R | no_license | statdivlab/rre_sims | R | false | false | 4,946 | r | #!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
# test if there is at least one argument: if not, return an error
if (length(args)!=4) {
stop("NOPE! Bad args. ARGH!", call.=FALSE)
} else {
input_r = as.numeric(args[1])
input_p = as.numeric(args[2])
input_nsim = as.numeric(args[3])
input_seed = as.numeric(args[4])
}
library(tidyverse)
library(simulator)
library(rre)
library(stringr)
library(magrittr)
library(actuar)
logarithmic_FCT_list <- function(ccc, p_log, replicates) {
new_model(name = sprintf("logarithmic_fct-list"),
label = sprintf("Logarithmic draws from true C = %s, prob = %s, replicates = %s)", ccc, p_log, replicates),
params = list(ccc = ccc, p_log = p_log, replicates = replicates),
simulate = function(ccc, p_log, replicates, nsim) {
# this function must return a list of length nsim
x <- replicate(nsim,
(actuar::rlogarithmic(n = ccc*replicates,
prob = p_log) - 1) %>%
matrix(. ,nrow = ccc, ncol = replicates) %>%
split(.,col(.)) %>%
lapply(make_frequency_count_table),
simplify = F)
return(x);
})
}
# Method metrics:
# if/else here is because I changed the method return wording from "optimal" to "selected".
selected_lambda <- new_metric("selected_lambda", "selected_lambda",
metric = function(model,out) {
best <- out[["best"]]
namen <- names(best)
if ("optimal_lambda" %in% namen) {
rtn <- best[["optimal_lambda"]]
} else if ("selected_lambda" %in% namen) {
rtn <- best[["selected_lambda"]]
} else {
stop("Your 'out' object doesnt have the right names.")
}
return(rtn)
})
ccc_hat <- new_metric("ccc_hat", "ccc_hat",
metric = function(model,out) {
best <- out[["best"]]
if (!is.null(best[["ccc_hat"]])) {
chat <- best[["ccc_hat"]]
} else if (!is.null(best[["ccc"]])) {
chat <- best[["ccc"]]
} else {
stop("no chat?")
}
return(chat)
})
# Method 0:
mle_no_pen <- new_method("mle_no_pen", "mle_no_pen",
method = function(model, draw) {
result <- rre::unregularized_mle(draw,
c_seq_len = 20,
multiplier = 4)
return(result)
}
)
# Method 3
gof <- new_method("gof", "gof",
method = function(model, draw) {
result <- rre::gof_criterion(draw,
lambda_vec = c(seq(0, 20, by=5),
seq(30, 50, by=10),
seq(70, 140, by=35)),
c_seq_len = 20,
multiplier = 4)
return(result)
}
)
### determine what is the right tuning parameters to choose
my_sim <- new_simulation(name = "logarithmic_sims",
label = "logarithmic_sims") %>%
generate_model(seed= paste(input_seed, input_r, sep = ""),
make_model = logarithmic_FCT_list,
ccc = as.list(c(1000, 2000)),
p_log = input_p,
replicates = input_r,
vary_along = "ccc") %>%
simulate_from_model(nsim = input_nsim)
my_sim %<>%
run_method(list(mle_no_pen,
gof))
my_sim %<>%
evaluate(list(ccc_hat,
selected_lambda))
ev_df <- my_sim %>% evals %>% as.data.frame
model_df <- my_sim %>% model %>% as.data.frame
ev_with_model_params <- dplyr::right_join(model_df, ev_df, by = c("name" = "Model"))
write_csv(ev_with_model_params,
paste("logarithmic_r_", input_r,
"_p_", input_p,
"_nsim_", input_nsim,
"_seed_", input_seed, ".csv", sep = ""))
# expand.grid(c(30, 14, 6), c(0.99, 0.995), 4, 1:12) %>%
# as_tibble %>%
# mutate(all = paste(Var1, Var2, Var3, Var4)) %>%
# arrange(Var4) %>%
# select(all) %$% all %>%
# cat(sep="\n")
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/make_axes.R
\name{make_axes}
\alias{make_axes}
\title{Draw X and Y Axes on a Plot}
\usage{
make_axes(p, x_int = 0, y_int = 0)
}
\arguments{
\item{p}{A ggplot object}
\item{x_int}{X-intercept of the y-axis. Defaults to 0}
\item{y_int}{Y-intercept of the x-axis. Defaults to 0.}
}
\value{
A list of four geom_segment objects, each corresponding to one half-axis, that may be added to a ggplot object.
}
\description{
This function creates vertical and horizontal axes that may be added to a ggplot object. The intercepts for either or each may be specified.
Note the axes will not appear if they fall outside the limits of your plot.
This function is partly based on this StackOverflow post: https://stackoverflow.com/questions/17753101/center-x-and-y-axis-with-ggplot2
}
| /man/make_axes.Rd | permissive | ryan-heslin/matador | R | false | true | 850 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/make_axes.R
\name{make_axes}
\alias{make_axes}
\title{Draw X and Y Axes on a Plot}
\usage{
make_axes(p, x_int = 0, y_int = 0)
}
\arguments{
\item{p}{A ggplot object}
\item{x_int}{X-intercept of the y-axis. Defaults to 0}
\item{y_int}{Y-intercept of the x-axis. Defaults to 0.}
}
\value{
A list of four geom_segment objects, each corresponding to one half-axis, that may be added to a ggplot object.
}
\description{
This function creates vertical and horizontal axes that may be added to a ggplot object. The intercepts for either or each may be specified.
Note the axes will not appear if they fall outside the limits of your plot.
This function is partly based on this StackOverflow post: https://stackoverflow.com/questions/17753101/center-x-and-y-axis-with-ggplot2
}
|
library(shiny)
library(car)
shinyServer(function(input, output) {
values <- reactiveValues()
observe({
input$Calculate
values$bmi <- isolate({
input$num_weight/(input$num_height * input$num_height * 0.0001)
})
})
# if values$bmi < 18.5
# {
# values$status="Underweight"
# }
# else if values$bmi < 24.9
# {
# values$status="Normal weight"
# }
# else if values$bmi < 29.9
# {
# values$status="Overweight"
# }
# else
# {
# values$status="Obesity"
# }
# Display values entered
output$text_height <- renderText({
input$Calculate
paste("Height [CM] :", isolate(input$num_height))
})
output$text_weight <- renderText({
input$Calculate
paste("Weight [KG} : ", isolate(input$num_weight))
})
# Display calculated values
output$text_BMI <- renderText({
if(input$Calculate == 0) ""
else
paste("BMI is (Metric):", values$bmi)
})
# output$text_status <- renderText({
# if(input$Calculate == 0) ""
# else
#
# paste("BMI shows you are ", values$status)
# })
}) | /server.R | no_license | shivamgiri/Shinyapp-BMI-Calculator | R | false | false | 1,235 | r | library(shiny)
library(car)
shinyServer(function(input, output) {
values <- reactiveValues()
observe({
input$Calculate
values$bmi <- isolate({
input$num_weight/(input$num_height * input$num_height * 0.0001)
})
})
# if values$bmi < 18.5
# {
# values$status="Underweight"
# }
# else if values$bmi < 24.9
# {
# values$status="Normal weight"
# }
# else if values$bmi < 29.9
# {
# values$status="Overweight"
# }
# else
# {
# values$status="Obesity"
# }
# Display values entered
output$text_height <- renderText({
input$Calculate
paste("Height [CM] :", isolate(input$num_height))
})
output$text_weight <- renderText({
input$Calculate
paste("Weight [KG} : ", isolate(input$num_weight))
})
# Display calculated values
output$text_BMI <- renderText({
if(input$Calculate == 0) ""
else
paste("BMI is (Metric):", values$bmi)
})
# output$text_status <- renderText({
# if(input$Calculate == 0) ""
# else
#
# paste("BMI shows you are ", values$status)
# })
}) |
itm <- function() {
require(shiny)
require(gridBase)
runApp(list(
ui = pageWithSidebar(
headerPanel("Interactive treemap"),
sidebarPanel(
selectInput("size", "Size:",
list("turnover" = "turnover",
"employees" = "employees",
"turnover.prev" = "turnover.prev",
"employees.prev" = "employees.prev"))
),
mainPanel(
plotOutput("plot", hoverId="hover"),
tableOutput("record")
)
),
server = function(input, output){
data(business)
getRecord <- reactive({
x <- input$hover$x
y <- input$hover$y
x <- (x - .tm$vpCoorX[1]) / (.tm$vpCoorX[2] - .tm$vpCoorX[1])
y <- (y - .tm$vpCoorY[1]) / (.tm$vpCoorY[2] - .tm$vpCoorY[1])
l <- tmLocate(list(x=x, y=y), .tm)
l[, 1:(ncol(l)-5)]
})
output$plot <- renderPlot({
#cat(input$hover$x, "\n")
par(mar=c(0,0,0,0), xaxs='i', yaxs='i')
plot(c(0,1), c(0,1),axes=F, col="white")
vps <- baseViewports()
.tm <<- treemap(business,
index=c("NACE1", "NACE2"),
vSize=input$size, vp=vps$plot)
})
output$record <- renderTable({
getRecord()
})
}
))
}
itm()
| /test/shiny.R | no_license | mtennekes/treemap | R | false | false | 1,723 | r |
itm <- function() {
require(shiny)
require(gridBase)
runApp(list(
ui = pageWithSidebar(
headerPanel("Interactive treemap"),
sidebarPanel(
selectInput("size", "Size:",
list("turnover" = "turnover",
"employees" = "employees",
"turnover.prev" = "turnover.prev",
"employees.prev" = "employees.prev"))
),
mainPanel(
plotOutput("plot", hoverId="hover"),
tableOutput("record")
)
),
server = function(input, output){
data(business)
getRecord <- reactive({
x <- input$hover$x
y <- input$hover$y
x <- (x - .tm$vpCoorX[1]) / (.tm$vpCoorX[2] - .tm$vpCoorX[1])
y <- (y - .tm$vpCoorY[1]) / (.tm$vpCoorY[2] - .tm$vpCoorY[1])
l <- tmLocate(list(x=x, y=y), .tm)
l[, 1:(ncol(l)-5)]
})
output$plot <- renderPlot({
#cat(input$hover$x, "\n")
par(mar=c(0,0,0,0), xaxs='i', yaxs='i')
plot(c(0,1), c(0,1),axes=F, col="white")
vps <- baseViewports()
.tm <<- treemap(business,
index=c("NACE1", "NACE2"),
vSize=input$size, vp=vps$plot)
})
output$record <- renderTable({
getRecord()
})
}
))
}
itm()
|
histogram <-
function(x, col="grey40", ...) {
barplot(table(x), las=1, col=col, border="white", xaxt="n", col.axis=col, horiz=T, ...)
pos <- axis(1,col.axis=col, col.ticks=col,col=col,las=1)
abline(v=pos,col="white")
}
lastChar <- function(x, n=1) {
substr(x, nchar(x)-n+1,nchar(x))
}
mosaic <- function(tab, ...) {
if (ncol(tab) < 12) {
col <- brewer.pal(ncol(tab),"RdYlGn")
} else {
col <- "grey"
}
mosaicplot(t(tab), col=col, main="", las=1, ...)
}
effects.plot <- function(x1,x2,y,fun=mean, ...) {
lx1 <- levels(x1)
plot(by(y, list(x1,x2), fun) , c(1,2,1,2),pch=c(19,19,21,21), cex=table(x1,x2)/10, las=1, xlab="", ylab="", yaxt="n", ylim=c(0.5,1+length(lx1)), bty="n")
axis(2,1:length(lx1),levels(x1), las=1)
abline(h=1:length(lx1),col="grey",lty=3)
points(by(y, x1, mean) ,c(1,2),pch="|", cex=table(x1)/20, las=1, xlab="", ylab="", xaxt="n")
points(by(y, list(x1,x2), mean) , c(1,2,1,2),pch=c(19,19,21,21), cex=table(x1,x2)/10)
legend("top", rev(unique(x2)), pch=c(19,21), cex=1, pt.cex=2, bty="n", ncol=2)
}
kartezjanskie2biegunowe <- function(punkt, srodek) {
wynik <- c(sqrt((punkt[1] - srodek[1])^2 + (punkt[2] - srodek[2])^2),
180*atan2(punkt[1] - srodek[1], punkt[2] - srodek[2])/pi)
names(wynik) = c("odleglosc", "kat")
wynik
}
| /oldData/histogram.R | no_license | pbiecek/BetaBit | R | false | false | 1,298 | r | histogram <-
function(x, col="grey40", ...) {
barplot(table(x), las=1, col=col, border="white", xaxt="n", col.axis=col, horiz=T, ...)
pos <- axis(1,col.axis=col, col.ticks=col,col=col,las=1)
abline(v=pos,col="white")
}
lastChar <- function(x, n=1) {
substr(x, nchar(x)-n+1,nchar(x))
}
mosaic <- function(tab, ...) {
if (ncol(tab) < 12) {
col <- brewer.pal(ncol(tab),"RdYlGn")
} else {
col <- "grey"
}
mosaicplot(t(tab), col=col, main="", las=1, ...)
}
effects.plot <- function(x1,x2,y,fun=mean, ...) {
lx1 <- levels(x1)
plot(by(y, list(x1,x2), fun) , c(1,2,1,2),pch=c(19,19,21,21), cex=table(x1,x2)/10, las=1, xlab="", ylab="", yaxt="n", ylim=c(0.5,1+length(lx1)), bty="n")
axis(2,1:length(lx1),levels(x1), las=1)
abline(h=1:length(lx1),col="grey",lty=3)
points(by(y, x1, mean) ,c(1,2),pch="|", cex=table(x1)/20, las=1, xlab="", ylab="", xaxt="n")
points(by(y, list(x1,x2), mean) , c(1,2,1,2),pch=c(19,19,21,21), cex=table(x1,x2)/10)
legend("top", rev(unique(x2)), pch=c(19,21), cex=1, pt.cex=2, bty="n", ncol=2)
}
kartezjanskie2biegunowe <- function(punkt, srodek) {
wynik <- c(sqrt((punkt[1] - srodek[1])^2 + (punkt[2] - srodek[2])^2),
180*atan2(punkt[1] - srodek[1], punkt[2] - srodek[2])/pi)
names(wynik) = c("odleglosc", "kat")
wynik
}
|
# Test LDA VEM model from topicmodels
test_that("LDA VEM", {
lda_vem <- readRDS("test_data/test_lda_vem.RDS")
expect_equal(mean_token_length(lda_vem), c(5.1, 6.4, 5.3))
})
# Test LDA Gibbs model from topicmodels
test_that("LDA Gibbs", {
lda_gibbs <- readRDS("test_data/test_lda_gibbs.RDS")
expect_equal(mean_token_length(lda_gibbs), c(6.1, 5.8, 4.6))
})
# Test CTM VEM model from topicmodels
test_that("CTM VEM", {
ctm_vem <- readRDS("test_data/test_ctm_vem.RDS")
expect_equal(mean_token_length(ctm_vem), c(5.2, 7.0, 4.6))
})
| /tests/testthat/test-mean_token_length.R | permissive | doug-friedman/topicdoc | R | false | false | 540 | r | # Test LDA VEM model from topicmodels
test_that("LDA VEM", {
lda_vem <- readRDS("test_data/test_lda_vem.RDS")
expect_equal(mean_token_length(lda_vem), c(5.1, 6.4, 5.3))
})
# Test LDA Gibbs model from topicmodels
test_that("LDA Gibbs", {
lda_gibbs <- readRDS("test_data/test_lda_gibbs.RDS")
expect_equal(mean_token_length(lda_gibbs), c(6.1, 5.8, 4.6))
})
# Test CTM VEM model from topicmodels
test_that("CTM VEM", {
ctm_vem <- readRDS("test_data/test_ctm_vem.RDS")
expect_equal(mean_token_length(ctm_vem), c(5.2, 7.0, 4.6))
})
|
setwd ("C:\\Users\\Tom\\Desktop\\EAA_CA2_X00115013")
# Thomas Murray X00115013
# CA2 EAA
#Read in data from results.dat
perfdata <- read.table("results.dat", header=TRUE, )
#Set Time
timeTest <- 10
#Set Percentage
percent <- 100
#Get the average utilization
avgutil <- 100 - perfdata$IDLE;
#Users
n <- perfdata$N
#Calculate utilisation
calcUI <- function(){
ui <- avgutil/percent
}
#Calculate throughput
calcXO <- function(){
x0 <- perfdata$C0/timeTest;
}
#Calculate service demand
calcDI <- function(){
di <- calcUI()/calcXO()
}
#Calculate response time
calcR <- function(){
r <- n/calcXO()
}
dev.new()
# Creating a Graph for utilisation Vs Users
plot(n, calcUI(),type="l", col="blue", lty=5, ylab = 'UI' , xlab = 'N')
abline(lm(calcUI()~n))
title("Utilisation Vs Users")
dev.new()
# Creating a Graph for Throughput Vs Users
plot(n, calcXO(),type="l", col="blue", lty=5, ylab = 'XO' , xlab = 'N')
abline(lm(calcXO()~n))
title("Throughput Vs Users")
dev.new()
# Creating a Graph for Service Demand Vs Users
plot(n, calcDI(),type="l", col="blue", lty=5, ylab = 'DI' , xlab = 'N')
abline(lm(calcDI()~n))
title("Service Demand Vs Users")
dev.new()
# Creating a Graph for Response Time Vs Users
plot(n, calcR(),type="l", col="blue", lty=5, ylab = 'R' , xlab = 'N')
abline(lm(calcR()~n))
title("Response Time Vs Users")
#Print Utilisation Summary
print("Utilisation Summary")
print(summary(calcUI()))
#Print Throughput Summary
print("Throughput Summary")
print(summary(calcXO()))
#Print Service Demand Summary
print("Service Demand Summary")
print(summary(calcDI()))
#Print Response Time Summary
print("Response Time Summary")
print(summary(calcR()))
#Calculate utilisation average
print("Utilisation average")
ui <- mean(avgutil/percent)
print(ui)
#Calculate throughput average
print("Throughput average")
x0 <- mean(perfdata$C0/timeTest)
print(x0)
#Calculate service demand average
print("Service demand average")
di <- mean(ui/x0)
print(di)
#Calculate response time average
print("Response time average")
r <- mean(perfdata$N/x0)
print(r)
| /EAA_CA2_X00115013/script.r | no_license | X00115013/EAA.Comp.2016 | R | false | false | 2,067 | r | setwd ("C:\\Users\\Tom\\Desktop\\EAA_CA2_X00115013")
# Thomas Murray X00115013
# CA2 EAA
#Read in data from results.dat
perfdata <- read.table("results.dat", header=TRUE, )
#Set Time
timeTest <- 10
#Set Percentage
percent <- 100
#Get the average utilization
avgutil <- 100 - perfdata$IDLE;
#Users
n <- perfdata$N
#Calculate utilisation
calcUI <- function(){
ui <- avgutil/percent
}
#Calculate throughput
calcXO <- function(){
x0 <- perfdata$C0/timeTest;
}
#Calculate service demand
calcDI <- function(){
di <- calcUI()/calcXO()
}
#Calculate response time
calcR <- function(){
r <- n/calcXO()
}
dev.new()
# Creating a Graph for utilisation Vs Users
plot(n, calcUI(),type="l", col="blue", lty=5, ylab = 'UI' , xlab = 'N')
abline(lm(calcUI()~n))
title("Utilisation Vs Users")
dev.new()
# Creating a Graph for Throughput Vs Users
plot(n, calcXO(),type="l", col="blue", lty=5, ylab = 'XO' , xlab = 'N')
abline(lm(calcXO()~n))
title("Throughput Vs Users")
dev.new()
# Creating a Graph for Service Demand Vs Users
plot(n, calcDI(),type="l", col="blue", lty=5, ylab = 'DI' , xlab = 'N')
abline(lm(calcDI()~n))
title("Service Demand Vs Users")
dev.new()
# Creating a Graph for Response Time Vs Users
plot(n, calcR(),type="l", col="blue", lty=5, ylab = 'R' , xlab = 'N')
abline(lm(calcR()~n))
title("Response Time Vs Users")
#Print Utilisation Summary
print("Utilisation Summary")
print(summary(calcUI()))
#Print Throughput Summary
print("Throughput Summary")
print(summary(calcXO()))
#Print Service Demand Summary
print("Service Demand Summary")
print(summary(calcDI()))
#Print Response Time Summary
print("Response Time Summary")
print(summary(calcR()))
#Calculate utilisation average
print("Utilisation average")
ui <- mean(avgutil/percent)
print(ui)
#Calculate throughput average
print("Throughput average")
x0 <- mean(perfdata$C0/timeTest)
print(x0)
#Calculate service demand average
print("Service demand average")
di <- mean(ui/x0)
print(di)
#Calculate response time average
print("Response time average")
r <- mean(perfdata$N/x0)
print(r)
|
cot <- c("A","B","C","D")
a <- mean(10,15,8,12,15)
b <- mean(14,18,21,15)
c <- mean(17,16,14,15,17,15,18)
d <- mean(12,15,17,15,16,15)
cot
avg <- data.frame(a,b,c,d)
##
ma <- c(10,15,8,12,15,
14,18,21,15,
17,16,14,15,17,15,18,
12,15,17,15,16,15)
cotting <- c(rep("A",5),
rep("B",4),
rep("C",7),
rep("D",6))
boxplot(ma~cotting, col=2:5)
aov(ma~cotting)
fit2<-aov(ma~cotting)
summary(fit2)
# p값이 0.05보다 작음
# 귀무가설기각
#
# 마모도 코팅 사이에 평균의 차이가 1개 이상 있다는 결론이 나옴
# --> 어디에서 차이가 나는지 보기 위해
TukeyHSD(fit2)
# diff에서 차이값들을 볼 수 있음
# 그중 0.05보다 작은 건 1번과 2번
# b-a/ c-a 의 차이가 유의하다
| /day8/anova_ex2.R | no_license | jee0nnii/DataITGirlsR | R | false | false | 799 | r | cot <- c("A","B","C","D")
a <- mean(10,15,8,12,15)
b <- mean(14,18,21,15)
c <- mean(17,16,14,15,17,15,18)
d <- mean(12,15,17,15,16,15)
cot
avg <- data.frame(a,b,c,d)
##
ma <- c(10,15,8,12,15,
14,18,21,15,
17,16,14,15,17,15,18,
12,15,17,15,16,15)
cotting <- c(rep("A",5),
rep("B",4),
rep("C",7),
rep("D",6))
boxplot(ma~cotting, col=2:5)
aov(ma~cotting)
fit2<-aov(ma~cotting)
summary(fit2)
# p값이 0.05보다 작음
# 귀무가설기각
#
# 마모도 코팅 사이에 평균의 차이가 1개 이상 있다는 결론이 나옴
# --> 어디에서 차이가 나는지 보기 위해
TukeyHSD(fit2)
# diff에서 차이값들을 볼 수 있음
# 그중 0.05보다 작은 건 1번과 2번
# b-a/ c-a 의 차이가 유의하다
|
library(shiny)
data <- read.csv("trimmed_data.csv", stringsAsFactors = F)
neighborhoods <- unique(data$neighborhood)
team_ui <- fluidPage(
titlePanel("Its Raining Crime"), #title of the app
sidebarLayout(
sidebarPanel(
radioButtons(inputId ="toggle_rain", label = "Rainfall",
choices = c("Rain" = TRUE, "No Rain" = FALSE), selected = TRUE),
selectInput(inputId = "neighborhood", label = "Select a Neighborhood", choices = neighborhoods,
selected = "UNIVERSITY")
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Introduction", htmlOutput("intro")),
tabPanel("Fequency of Crime", plotOutput("plot1"), textOutput("text1")),
tabPanel("Precipitation and Specific Crime", plotOutput("plot2"), tags$strong(textOutput("disclaimer")), textOutput("text2")),
tabPanel("Precipitation and Overall Crime ", plotOutput("plot3"), tags$strong(textOutput("disclaimer2")), textOutput("text3")),
tabPanel("Temperature and Crime", plotOutput("plot4"), textOutput("text4")),
tabPanel("Crime and Time of Year", plotOutput("plot5"), textOutput("text5"))
)
)
)
)
| /team_ui.R | no_license | aarora0211/ItsRainingCrime | R | false | false | 1,268 | r | library(shiny)
data <- read.csv("trimmed_data.csv", stringsAsFactors = F)
neighborhoods <- unique(data$neighborhood)
team_ui <- fluidPage(
titlePanel("Its Raining Crime"), #title of the app
sidebarLayout(
sidebarPanel(
radioButtons(inputId ="toggle_rain", label = "Rainfall",
choices = c("Rain" = TRUE, "No Rain" = FALSE), selected = TRUE),
selectInput(inputId = "neighborhood", label = "Select a Neighborhood", choices = neighborhoods,
selected = "UNIVERSITY")
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Introduction", htmlOutput("intro")),
tabPanel("Fequency of Crime", plotOutput("plot1"), textOutput("text1")),
tabPanel("Precipitation and Specific Crime", plotOutput("plot2"), tags$strong(textOutput("disclaimer")), textOutput("text2")),
tabPanel("Precipitation and Overall Crime ", plotOutput("plot3"), tags$strong(textOutput("disclaimer2")), textOutput("text3")),
tabPanel("Temperature and Crime", plotOutput("plot4"), textOutput("text4")),
tabPanel("Crime and Time of Year", plotOutput("plot5"), textOutput("text5"))
)
)
)
)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/load_libs.R
\name{removeDupes}
\alias{removeDupes}
\title{Remove duplicate genes from gene set.}
\usage{
removeDupes(x)
}
\arguments{
\item{filename}{Genesetr library object.}
}
\value{
Returns library object with duplicate genes removed.
}
\description{
Remove duplicate genes from gene set.
}
\examples{
gmt = loadLongDF('/user/libs/mylib.tsv')
myLib = removeDupes(myLib)
}
| /man/removeDupes.Rd | no_license | MaayanLab/genesetr | R | false | true | 454 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/load_libs.R
\name{removeDupes}
\alias{removeDupes}
\title{Remove duplicate genes from gene set.}
\usage{
removeDupes(x)
}
\arguments{
\item{filename}{Genesetr library object.}
}
\value{
Returns library object with duplicate genes removed.
}
\description{
Remove duplicate genes from gene set.
}
\examples{
gmt = loadLongDF('/user/libs/mylib.tsv')
myLib = removeDupes(myLib)
}
|
library(readr)
library(xgboost)
set.seed(1)
cat("reading the train and test data\n")
train <- read_csv("/home/lijiajia/work/myproject/kaggle/springleaf/train.csv")
test <- read_csv("/home/lijiajia/work/myproject/kaggle/springleaf/test.csv")
feature.names <- names(train)[2:ncol(train)-1]
cat("assuming text variable are categorical & replacing them with numeric ids\n")
for (f in feature.names) {
if (class(train[[f]]) == "character") {
levels <- unique(c(train[[f]], test[[f]]))
train[[f]] <- as.integer(factor(train[[f]], levels = levels))
test[[f]] <- as.integer(factor(test[[f]], levels = levels))
}
}
cat("replacing missing vlaues with -1\n")
train[is.na(train)] <- -1
test[is.na(test)] <- -1
cat("sampling train to get around 8GB memory limitations\n")
train <- train[sample(nrow(train), 40000),]
gc()
cat("training a XGBoost classifier\n")
clf <- xgboost(data = data.matrix(train[, feature.names]),
label = train$target,
nrounds = 200,
max.deptp = 5,
objective = "binary:logistic",
eval_metric = "auc")
cat("making predictions in batches due to 8GB memory limitation\n")
submission <- data.frame(ID=test$ID)
submission$target <- NA
for (rows in split(1:nrow(test), ceiling((1:nrow(test))/10000))) {
submission[rows, "target"] <- predict(clf, data.matrix(test[rows, feature.names]))
}
cat("saving the submission file\n")
write_csv(submission, "/home/lijiajia/work/myproject/kaggle/springleaf/xgboost_submission.csv") | /springleaf/springleaf.R | no_license | lijiajia/mykaggle | R | false | false | 1,524 | r | library(readr)
library(xgboost)
set.seed(1)
cat("reading the train and test data\n")
train <- read_csv("/home/lijiajia/work/myproject/kaggle/springleaf/train.csv")
test <- read_csv("/home/lijiajia/work/myproject/kaggle/springleaf/test.csv")
feature.names <- names(train)[2:ncol(train)-1]
cat("assuming text variable are categorical & replacing them with numeric ids\n")
for (f in feature.names) {
if (class(train[[f]]) == "character") {
levels <- unique(c(train[[f]], test[[f]]))
train[[f]] <- as.integer(factor(train[[f]], levels = levels))
test[[f]] <- as.integer(factor(test[[f]], levels = levels))
}
}
cat("replacing missing vlaues with -1\n")
train[is.na(train)] <- -1
test[is.na(test)] <- -1
cat("sampling train to get around 8GB memory limitations\n")
train <- train[sample(nrow(train), 40000),]
gc()
cat("training a XGBoost classifier\n")
clf <- xgboost(data = data.matrix(train[, feature.names]),
label = train$target,
nrounds = 200,
max.deptp = 5,
objective = "binary:logistic",
eval_metric = "auc")
cat("making predictions in batches due to 8GB memory limitation\n")
submission <- data.frame(ID=test$ID)
submission$target <- NA
for (rows in split(1:nrow(test), ceiling((1:nrow(test))/10000))) {
submission[rows, "target"] <- predict(clf, data.matrix(test[rows, feature.names]))
}
cat("saving the submission file\n")
write_csv(submission, "/home/lijiajia/work/myproject/kaggle/springleaf/xgboost_submission.csv") |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dotPlotModules.R
\name{dotplotOutputFromGO}
\alias{dotplotOutputFromGO}
\title{Title}
\usage{
dotplotOutputFromGO(input, output, GO, objId = NULL, annotation)
}
\arguments{
\item{annotation}{}
}
\description{
Title
}
| /man/dotplotOutputFromGO.Rd | permissive | laderast/flowDashboard | R | false | true | 295 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dotPlotModules.R
\name{dotplotOutputFromGO}
\alias{dotplotOutputFromGO}
\title{Title}
\usage{
dotplotOutputFromGO(input, output, GO, objId = NULL, annotation)
}
\arguments{
\item{annotation}{}
}
\description{
Title
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/regexplainer.R
\name{regexplain}
\alias{regexplain}
\title{Function to explain the regex}
\usage{
regexplain(regx)
}
\arguments{
\item{regx}{Regular expression statement in strings}
}
\value{
a dataframe that returns the strings
}
\description{
Function to explain the regex
}
| /man/regexplain.Rd | permissive | ck2136/r_regex_tester_app | R | false | true | 355 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/regexplainer.R
\name{regexplain}
\alias{regexplain}
\title{Function to explain the regex}
\usage{
regexplain(regx)
}
\arguments{
\item{regx}{Regular expression statement in strings}
}
\value{
a dataframe that returns the strings
}
\description{
Function to explain the regex
}
|
fullargs <- commandArgs(trailingOnly=FALSE)
args <- commandArgs(trailingOnly=TRUE)
script.name <- normalizePath(sub("--file=", "", fullargs[grep("--file=", fullargs)]))
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(googlesheets))
####################################################################
in_f <- args[1]
out_f <- args[2]
gs_token <- args[3]
gs_sheet <- args[4]
####################################################################
gs_auth(token = gs_token)
map_df <- gs_sheet %>% gs_url() %>%
gs_read(ws = 'summarize.to.2digits.alleles') %>%
mutate(Locus = paste0('HLA-', Locus)) %>%
select(-revisit)
df <- fread(in_f)
df %>%
rename(!!str_replace(names(df)[1], '#', '') := names(df)[1] ) %>%
rename(group = names(df)[3]) %>%
filter(Locus != 'ABS') %>%
mutate(
Allele = str_replace_all(Allele, 'HLA-', '')
) %>%
left_join(
map_df,
by=c('Locus', 'Allele')
) %>%
mutate(Allele = Allele2digit) %>%
select(-Allele2digit)%>%
group_by(Locus, group, Allele) %>%
summarise_at(names(df)[4:ncol(df)], sum, na.rm = TRUE) %>%
ungroup() %>%
rename(!!names(df)[3] := 'group') %>%
filter(Locus != 'ABS') %>%
rename(!!names(df)[1] := str_replace(names(df)[1], '#', '')) %>%
select(names(df)) %>%
fwrite(out_f, sep='\t', na = "NA", quote=F)
| /HLA/summarize.to.2digits.R | no_license | rivas-lab/covid19 | R | false | false | 1,350 | r | fullargs <- commandArgs(trailingOnly=FALSE)
args <- commandArgs(trailingOnly=TRUE)
script.name <- normalizePath(sub("--file=", "", fullargs[grep("--file=", fullargs)]))
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(googlesheets))
####################################################################
in_f <- args[1]
out_f <- args[2]
gs_token <- args[3]
gs_sheet <- args[4]
####################################################################
gs_auth(token = gs_token)
map_df <- gs_sheet %>% gs_url() %>%
gs_read(ws = 'summarize.to.2digits.alleles') %>%
mutate(Locus = paste0('HLA-', Locus)) %>%
select(-revisit)
df <- fread(in_f)
df %>%
rename(!!str_replace(names(df)[1], '#', '') := names(df)[1] ) %>%
rename(group = names(df)[3]) %>%
filter(Locus != 'ABS') %>%
mutate(
Allele = str_replace_all(Allele, 'HLA-', '')
) %>%
left_join(
map_df,
by=c('Locus', 'Allele')
) %>%
mutate(Allele = Allele2digit) %>%
select(-Allele2digit)%>%
group_by(Locus, group, Allele) %>%
summarise_at(names(df)[4:ncol(df)], sum, na.rm = TRUE) %>%
ungroup() %>%
rename(!!names(df)[3] := 'group') %>%
filter(Locus != 'ABS') %>%
rename(!!names(df)[1] := str_replace(names(df)[1], '#', '')) %>%
select(names(df)) %>%
fwrite(out_f, sep='\t', na = "NA", quote=F)
|
### Lab 12
##1. Write a function that simulates this
## stochastic model of population dynamics.
## Your function should take three arguments:
## (i) r, (ii) k, (iii) the total number of
## generations to simulate, and (iv) the initial
## value of abundance. As default values of these
## parameters, I suggest using r = 0.1,
## k = 100, gens = 100, n_init = 10.
Stochapopdy <- function(r =0.1, k = 100, generations = 100, intit = 10) {
n <- rep(intit, generations)
for(i in 2:generations){
exp <- n[i -1] + r * n[i - 1] * (k - n[i - 1]) / k
real <- rpois(n = 1, exp)
n[i] <- real
}
return(n)
}
## run the modelll!!
n <- Stochapopdy()
| /Lab12/Lab12.R | no_license | alix12/CompBioLabsAndHomework | R | false | false | 667 | r | ### Lab 12
##1. Write a function that simulates this
## stochastic model of population dynamics.
## Your function should take three arguments:
## (i) r, (ii) k, (iii) the total number of
## generations to simulate, and (iv) the initial
## value of abundance. As default values of these
## parameters, I suggest using r = 0.1,
## k = 100, gens = 100, n_init = 10.
Stochapopdy <- function(r =0.1, k = 100, generations = 100, intit = 10) {
n <- rep(intit, generations)
for(i in 2:generations){
exp <- n[i -1] + r * n[i - 1] * (k - n[i - 1]) / k
real <- rpois(n = 1, exp)
n[i] <- real
}
return(n)
}
## run the modelll!!
n <- Stochapopdy()
|
#
# code: Dampier Technical Report Significance Tests
#
# github: WWF-ConsEvidence/MPAMystery/2_Social/TechnicalReports/BHS/SignificanceTestCodes
# --- Duplicate all code from "2_Social" onward, to maintain file structure for sourced code
#
# author: Kelly Claborn, clabornkelly@gmail.com
# created: November 2016
# modified: December 2017
#
#
# ---- inputs ----
# Dependencies: BHS_MPA_Mystery.R
#
# ---- code sections ----
# 1) Import Data
# 2) Define Lists of Settlements, to be used in functions
# 3) Plot Variable Distributions (to test normality assumption)
# 4) Non-parametric Significance Test Functions (using Mann-Whitney U test)
# 5) Chi-square Tests for Categorical Variables
#
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 1: Import Data ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 1.1 Subset continuous variable datasets from BHS_MPA_Mystery.R ----
MPA.TechReport.SigTest.Data <-
left_join(BigFive[,c(1,2,4:11,14)],
HHLivelihood[,c(1,15)],
by="HouseholdID")
# - "MPA Household Data" dataset
Damp.TechReport.MPAHouseholdData <-
left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$Treatment==1 &
MPA.TechReport.SigTest.Data$MonitoringYear== "4 Year Post" &
MPA.TechReport.SigTest.Data$MPAID==5,],
Days.unwell.treatment[Days.unwell.treatment$MPAID==5 &
Days.unwell.treatment$MonitoringYear=="4 Year Post",
c("HouseholdID","DaysUnwell")],
by="HouseholdID")
Damp.TechReport.MPAHouseholdData$SettlementName <-
factor(Damp.TechReport.MPAHouseholdData$SettlementName)
# - "MPA versus BHS" dataset
Damp.TechReport.MPAvBHS <-
rbind.data.frame(cbind.data.frame(left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$MPAID==5 &
MPA.TechReport.SigTest.Data$MonitoringYear=="4 Year Post" &
MPA.TechReport.SigTest.Data$Treatment==1,],
Days.unwell[Days.unwell$MPAID==5 &
Days.unwell$MonitoringYear=="4 Year Post" &
Days.unwell$Treatment==1,
c("HouseholdID","DaysUnwell")],
by="HouseholdID"),MPAvBHS="MPA"),
cbind.data.frame(left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$MonitoringYear=="4 Year Post" &
MPA.TechReport.SigTest.Data$Treatment==1,],
Days.unwell[Days.unwell$MonitoringYear=="4 Year Post" & Days.unwell$Treatment==1,
c("HouseholdID","DaysUnwell")],
by="HouseholdID"),MPAvBHS="BHS"))
# - "Settlement Means" dataset
Damp.TechReport.SettlementMeans <-
left_join(BigFive.SettleGroup[BigFive.SettleGroup$Treatment==1 &
BigFive.SettleGroup$MonitoringYear=="4 Year Post" &
BigFive.SettleGroup$MPAID==5,],
Techreport.BySett[Techreport.BySett$MPAID==5 &
Techreport.BySett$MonitoringYear=="4 Year Post",
c("SettlementID","SettlementName","TimeMarketMean")],
by=c("SettlementID","SettlementName"))
Damp.TechReport.SettlementMeans <-
left_join(Damp.TechReport.SettlementMeans,
Days.unwell.BySett[Days.unwell.BySett$MPAID==5 &
Days.unwell.BySett$MonitoringYear=="4 Year Post",c(1,4)],
by="SettlementID")
Damp.TechReport.SettlementMeans <-
Damp.TechReport.SettlementMeans[!is.na(Damp.TechReport.SettlementMeans$SettlementName),]
colnames(Damp.TechReport.SettlementMeans) <- c(colnames(Damp.TechReport.SettlementMeans)[1:5],
"FSIndex","FSErr","MAIndex","MAErr","PAIndex","PAErr",
"MTIndex","MTErr","SERate","SEErr","TimeMarketClean","DaysUnwell")
# - "Trend" dataset
Damp.Trend.Data <-
left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$Treatment==1 &
MPA.TechReport.SigTest.Data$MPAID==5,],
Days.unwell[Days.unwell$MPAID==5 &
Days.unwell$Treatment==1,1:2],
by="HouseholdID")
# ---- 1.2 Define list of settlement names in MPA ----
sett.names.Damp <- factor(Damp.TechReport.SettlementMeans$SettlementName)
# ---- 1.3 Subset categorical variable frequency tables from BHS_MPA_Mystery.R ----
# - "Trend" dataset
Damp.FreqTables <-
HHDemos.context[HHDemos.context$MPAID==5,] %>%
group_by(MonitoringYear) %>%
summarise(PrimaryOcc.Fish=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==3 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.Farm=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==1 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.WageLabor=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==7 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.HarvestForest=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==2 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.Tourism=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==6 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.Other=length(PrimaryLivelihoodClean[(PrimaryLivelihoodClean==996 | PrimaryLivelihoodClean==4 |
PrimaryLivelihoodClean==5) & !is.na(PrimaryLivelihoodClean)]),
FreqFish.AlmostNever=length(FreqFishClean[FreqFishClean==1 & !is.na(FreqFishClean)]),
FreqFish.FewTimesPer6Mo=length(FreqFishClean[FreqFishClean==2 & !is.na(FreqFishClean)]),
FreqFish.FewTimesPerMo=length(FreqFishClean[FreqFishClean==3 & !is.na(FreqFishClean)]),
FreqFish.FewTimesPerWk=length(FreqFishClean[FreqFishClean==4 & !is.na(FreqFishClean)]),
FreqFish.MoreFewTimesWk=length(FreqFishClean[FreqFishClean==5 & !is.na(FreqFishClean)]),
SellFish.AlmostNever=length(FreqSaleFishClean[FreqSaleFishClean==1 & !is.na(FreqSaleFishClean)]),
SellFish.FewTimesPer6Mo=length(FreqSaleFishClean[FreqSaleFishClean==2 & !is.na(FreqSaleFishClean)]),
SellFish.FewTimesPerMo=length(FreqSaleFishClean[FreqSaleFishClean==3 & !is.na(FreqSaleFishClean)]),
SellFish.FewTimesPerWk=length(FreqSaleFishClean[FreqSaleFishClean==4 & !is.na(FreqSaleFishClean)]),
SellFish.MoreFewTimesWk=length(FreqSaleFishClean[FreqSaleFishClean==5 & !is.na(FreqSaleFishClean)]),
IncFish.None=length(PercentIncFishClean[PercentIncFishClean==1 & !is.na(PercentIncFishClean)]),
IncFish.Some=length(PercentIncFishClean[PercentIncFishClean==2 & !is.na(PercentIncFishClean)]),
IncFish.Half=length(PercentIncFishClean[PercentIncFishClean==3 & !is.na(PercentIncFishClean)]),
IncFish.Most=length(PercentIncFishClean[PercentIncFishClean==4 & !is.na(PercentIncFishClean)]),
IncFish.All=length(PercentIncFishClean[PercentIncFishClean==5 & !is.na(PercentIncFishClean)]),
FishTech.ByHand=length(MajFishTechniqueClean[MajFishTechniqueClean==1 & !is.na(MajFishTechniqueClean)]),
FishTech.StatNet=length(MajFishTechniqueClean[MajFishTechniqueClean==2 & !is.na(MajFishTechniqueClean)]),
FishTech.MobileNet=length(MajFishTechniqueClean[MajFishTechniqueClean==3 & !is.na(MajFishTechniqueClean)]),
FishTech.StatLine=length(MajFishTechniqueClean[MajFishTechniqueClean==4 & !is.na(MajFishTechniqueClean)]),
FishTech.MobileLine=length(MajFishTechniqueClean[MajFishTechniqueClean==5 & !is.na(MajFishTechniqueClean)]),
Child.FS.no=length(Child.FS.category[Child.FS.category=="No or insufficient evidence" & !is.na(Child.FS.category)]),
Child.FS.yes=length(Child.FS.category[Child.FS.category=="Evidence" & !is.na(Child.FS.category)]),
ProteinFish.None=length(PercentProteinFishClean[PercentProteinFishClean==1 & !is.na(PercentProteinFishClean)]),
ProteinFish.Some=length(PercentProteinFishClean[PercentProteinFishClean==2 & !is.na(PercentProteinFishClean)]),
ProteinFish.Half=length(PercentProteinFishClean[PercentProteinFishClean==3 & !is.na(PercentProteinFishClean)]),
ProteinFish.Most=length(PercentProteinFishClean[PercentProteinFishClean==4 & !is.na(PercentProteinFishClean)]),
ProteinFish.All=length(PercentProteinFishClean[PercentProteinFishClean==5 & !is.na(PercentProteinFishClean)]))
Damp.FreqTables <-
as.data.frame(t(Damp.FreqTables[,-1]))
colnames(Damp.FreqTables) <- c("t0","t2","t4")
Damp.FreqTables$Category <- rownames(Damp.FreqTables)
Damp.FreqTables$Variable <- ifelse(grepl("PrimaryOcc",Damp.FreqTables$Category)==T,"PrimaryOcc",
ifelse(grepl("SellFish",Damp.FreqTables$Category)==T,"SellFish",
ifelse(grepl("IncFish",Damp.FreqTables$Category)==T,"IncFish",
ifelse(grepl("FishTech",Damp.FreqTables$Category)==T,"FishTech",
ifelse(grepl("FreqFish",Damp.FreqTables$Category)==T,"FreqFish",
ifelse(grepl("Child",Damp.FreqTables$Category)==T,"ChildFS",
ifelse(grepl("Protein",Damp.FreqTables$Category)==T,"Protein",NA)))))))
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 2: Define Lists of Settlements, to be used in functions ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 2.1 Create list of median settlement for each continuous variable (whether the variable is parametric or non-parametric) ----
even.number.setts.function.Damp <-
mapply(a=Damp.TechReport.SettlementMeans[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
b=Damp.TechReport.MPAHouseholdData[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
function(a,b){
med <- median(a,na.rm=T)
equal <- c(a[which(a==med)])
upper <- c(a[which(a>med)])
upper <- min(upper,na.rm=T)
lower <- c(a[which(a<med)])
lower <- max(lower,na.rm=T)
upper.sett <- Damp.TechReport.SettlementMeans$SettlementName[a==upper]
upper.sett <- ifelse(length(upper.sett)>1 & length(upper.sett)<3,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)]))),
as.character(upper.sett[1]),as.character(upper.sett[2])),
ifelse(length(upper.sett)>1 & length(upper.sett)<4,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3] & !is.na(b)]))),
as.character(upper.sett[1]),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3] & !is.na(b)]))),
as.character(upper.sett[2]),
as.character(upper.sett[3]))),
as.character(upper.sett)))
lower.sett <- Damp.TechReport.SettlementMeans$SettlementName[a==lower]
lower.sett <- ifelse(length(lower.sett)>1 & length(lower.sett)<3,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)]))),
as.character(lower.sett[1]),as.character(lower.sett[2])),
ifelse(length(lower.sett)>1 & length(lower.sett)<4,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3] & !is.na(b)]))),
as.character(lower.sett[1]),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3] & !is.na(b)]))),
as.character(lower.sett[2]),
as.character(lower.sett[3]))),
as.character(lower.sett)))
sett.equal.med <- Damp.TechReport.SettlementMeans$SettlementName[a==equal]
sett.equal.med <- ifelse(length(sett.equal.med)>1 & length(sett.equal.med)<3,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)]))),
as.character(sett.equal.med[1]),as.character(sett.equal.med[2])),
ifelse(length(sett.equal.med)>2 & length(sett.equal.med)<4,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3] & !is.na(b)]))),
as.character(sett.equal.med[1]),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3] & !is.na(b)]))),
as.character(sett.equal.med[2]),
as.character(sett.equal.med[3]))),
ifelse(is.na(sett.equal.med),
NA,
as.character(sett.equal.med))))
median.sett <- ifelse(!is.na(sett.equal.med),
as.character(sett.equal.med),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett & !is.na(b)]))),
as.character(upper.sett),
as.character(lower.sett)))
})
median.setts.Damp <-
mapply(i=Damp.TechReport.SettlementMeans[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
j=names(even.number.setts.function.Damp),
function(i,j){
med <- median(i,na.rm=T)
med.setts <- factor(ifelse(length(sett.names.Damp)%%2!=0,
as.character(Damp.TechReport.SettlementMeans$SettlementName[which(i==med)]),
as.character(even.number.setts.function.Damp[j])),
levels=levels(sett.names.Damp))})
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 3: Plot Variable Distributions (to test normality assumption) ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 3.1 Food security score distribution ----
dist.Damp.FS <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=FSIndex,y=..density..),
bins=5,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$FSIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$FSIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Food Security Scores\n(per household)",
y="Density",
title="Damp: Food Security Score Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$FSIndex)
qqline(Damp.TechReport.MPAHouseholdData$FSIndex,col="green")
# ---- 3.2 Material assets score distribution ----
dist.Damp.MA <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=MAIndex,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$MAIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$MAIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Material Assets\n(per household)",
y="Density",
title="Damp: HH Material Assets Distribution, 2014") +
dist.plot.theme
log.MA <- log(Damp.TechReport.MPAHouseholdData$MAIndex[Damp.TechReport.MPAHouseholdData$MAIndex!=0])
qqnorm(log.MA)
qqline(log.MA,col="green")
# ---- 3.3 Place attachment score distribution ----
dist.Damp.PA <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=PAIndex,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$PAIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$PAIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Place Attachment Score\nPer Household",
y="Density",
title="Damp: Place Attachment Score Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$PAIndex)
qqline(Damp.TechReport.MPAHouseholdData$PAIndex,col="green")
# ---- 3.4 Marine tenure score distribution ----
dist.Damp.MT <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=MTIndex,y=..density..),
binwidth=1,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$MTIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$MTIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Marine Tenure Score\n(per household)",
y="Density",
title="Damp: Marine Tenure Score Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$MTIndex)
qqline(Damp.TechReport.MPAHouseholdData$MTIndex,col="green")
# ---- 3.5 School enrollment rate distribution ----
dist.Damp.SE <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=SERate,y=..density..),
bins=15,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$SERate),
sd=sd(Damp.TechReport.MPAHouseholdData$SERate)),
colour="#262F52",size=1,na.rm=T) +
labs(x="School Enrollment Rate\n(per household)",
y="Density",
title="Damp: School Enrollment Rate Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$SERate)
qqline(Damp.TechReport.MPAHouseholdData$SERate,col="green")
# ---- 3.6 Time to market distribution ----
dist.Damp.TimeMarket <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=TimeMarketClean,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$TimeMarketClean),
sd=sd(Damp.TechReport.MPAHouseholdData$TimeMarketClean)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Average Time to Market\n(in hours)",
y="Density",
title="Damp: Time to Market Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$TimeMarketClean)
qqline(Damp.TechReport.MPAHouseholdData$TimeMarketClean,col="green")
# ---- 3.7 Days unwell distribution ----
dist.Damp.DaysUnwell <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=DaysUnwell,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$DaysUnwell),
sd=sd(Damp.TechReport.MPAHouseholdData$DaysUnwell)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Days Unwell\n(per household)",
y="Density",
title="Damp: HH Days Unwell Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$DaysUnwell)
qqline(Damp.TechReport.MPAHouseholdData$DaysUnwell,col="green")
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 4: Non-parametric Significance Test Functions (using Mann-Whitney U test) ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# NOTE: Typically, food security, material assets, marine tenure, enrollment rate, and place attachment end up being non-parametric;
# however, if the distribution appears to be normal, then PARAMETRIC tests are more powerful and the better choice.
# ---- 4.1 Create function that will output significance values for non-parametric variables, BY SETTLEMENT ----
# (for status plots)
non.parametric.test.settlements.Damp <-
data.frame(mapply(a=c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell"),
function(a){
results <-
list(cbind.data.frame(SettlementName=c(as.character(sett.names.Damp[which(sett.names.Damp!=median.setts.Damp[a])]),
as.character(median.setts.Damp[a])),
rbind.data.frame(t(data.frame(mapply(i=sett.names.Damp[which(sett.names.Damp!=median.setts.Damp[a])],
function(i){
var <-
Damp.TechReport.MPAHouseholdData[Damp.TechReport.MPAHouseholdData$SettlementName==i |
Damp.TechReport.MPAHouseholdData$SettlementName==median.setts.Damp[a],a]
test <-
wilcox.test(var~SettlementName,
data=Damp.TechReport.MPAHouseholdData[Damp.TechReport.MPAHouseholdData$SettlementName==i |
Damp.TechReport.MPAHouseholdData$SettlementName==median.setts.Damp[a],],
exact=F)
}))["p.value",]),
"median")))
}))
# - Alphabetize each column of settlement names. Now all settlement names are in same order.
sigvals.Sett.Damp <-
cbind.data.frame(non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"FSIndex.SettlementName"),
c("FSIndex.SettlementName","FSIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"MAIndex.SettlementName"),
c("MAIndex.SettlementName","MAIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"PAIndex.SettlementName"),
c("PAIndex.SettlementName","PAIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"MTIndex.SettlementName"),
c("MTIndex.SettlementName","MTIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"SERate.SettlementName"),
c("SERate.SettlementName","SERate.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"TimeMarketClean.SettlementName"),
c("TimeMarketClean.SettlementName","TimeMarketClean.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"DaysUnwell.SettlementName"),
c("DaysUnwell.SettlementName","DaysUnwell.p.value")])
# - Remove all settlement name columns except for one.
sigvals.Sett.Damp <-
sigvals.Sett.Damp[,c(1,2,4,6,8,10,12,14)]
colnames(sigvals.Sett.Damp) <- c("SettlementName","FS.pval","MA.pval","PA.pval","MT.pval","SE.pval","Time.pval","Unwell.pval")
# ---- 4.2 Create function that will output significance values for non-parametric variables, MPA VS. BHS ----
# (for status plots, comparing MPA households to all BHS households)
non.parametric.test.MPAvBHS.Damp <-
data.frame(mapply(a=c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell"),
function(a){
var <- Damp.TechReport.MPAvBHS[,a]
wilcox.test(var~MPAvBHS,
data=Damp.TechReport.MPAvBHS,
exact=F)}))["p.value",]
sigvals.MPA.Damp <-
cbind.data.frame("Selat Dampier\nMPA",non.parametric.test.MPAvBHS.Damp)
colnames(sigvals.MPA.Damp) <- colnames(sigvals.Sett.Damp)
null.row.sigvals.Damp <-
matrix(rep(NA,length(sigvals.MPA.Damp)),ncol=length(sigvals.MPA.Damp),
dimnames=list(NULL,colnames(sigvals.MPA.Damp)))
# - Define data frame with p-values for status plots
# (households in each settlement are compared to those in the median settlement for the given variable,
# using Mann Whitney U-Test -- so, interpretation is "compared to the median settlement, this settlement
# [is/is not] significantly different")
#
# (for MPA p-values, households in the MPA were compared to those in the control settlements (for the MPA),
# also using Mann-Whitney U test)
sigvals.Damp <-
rbind.data.frame(sigvals.MPA.Damp,
null.row.sigvals.Damp,
sigvals.Sett.Damp[rev(order(sigvals.Sett.Damp$SettlementName)),])
sigvals.Damp[,2:8] <- unlist(sigvals.Damp[,2:8])
# ---- 4.3 Create function that will output TREND significance values for non-parametric variables, BY MPA ----
# (for trend plots)
trend.non.parametric.test.byMPA.Damp <-
data.frame(mapply(i=Damp.Trend.Data[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
function(i){
MannKendall(c(i[Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[1]],
i[Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[2]],
i[Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[3]]))
}))
colnames(trend.non.parametric.test.byMPA.Damp) <- colnames(sigvals.Damp[2:8])
# - Define data frame with p-values for trend plots
# (all MPA households from each year of sampling are compared across time for the given variable,
# using monotonic trend test, Mann-Kendall -- so, interpretation is "across the sampling years,
# there [is/is not] a significant difference in this variable across the MPA")
trend.sigvals.Damp <-
cbind.data.frame(MonitoringYear="p.value",trend.non.parametric.test.byMPA.Damp["sl",1],NA,trend.non.parametric.test.byMPA.Damp["sl",2],
NA,trend.non.parametric.test.byMPA.Damp["sl",3],NA,trend.non.parametric.test.byMPA.Damp["sl",4],NA,trend.non.parametric.test.byMPA.Damp["sl",5],
NA,trend.non.parametric.test.byMPA.Damp["sl",6],NA,trend.non.parametric.test.byMPA.Damp["sl",7],NA)
colnames(trend.sigvals.Damp) <- c("MonitoringYear","FSMean","FSErr","MAMean","MAErr","PAMean","PAErr","MTMean","MTErr","SEMean","SEErr",
"TimeMarketMean","TimeMarketErr","UnwellMean","UnwellErr")
trend.sigvals.Damp <- unlist(trend.sigvals.Damp)
# ---- 4.4 Create function that will output TREND significance values for non-parametric variables, BY SETTLEMENT ----
# (for annex plots)
trend.non.parametric.test.bySett.Damp <-
cbind.data.frame(SettlementName=as.character(sett.names.Damp),
mapply(a=c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell"),
function(a){
t(data.frame(mapply(i=as.character(sett.names.Damp),
function(i){
MannKendall(c(Damp.Trend.Data[Damp.Trend.Data$SettlementName==i &
Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[1],a],
Damp.Trend.Data[Damp.Trend.Data$SettlementName==i &
Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[2],a],
Damp.Trend.Data[Damp.Trend.Data$SettlementName==i &
Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[3],a]))
}))["sl",])}))
colnames(trend.non.parametric.test.bySett.Damp) <- colnames(sigvals.Damp)
# - Define data frame with p-values for annex plots
# (households within each settlement from each year of sampling are compared across time for the given
# variable, using monotonic trend test, Mann-Kendall -- so, interpretation is "across the sampling years,
# there [is/is not] a significant difference in this variable across the settlement)
annex.sigvals.Damp <-
rbind.data.frame(cbind.data.frame(SettlementName="Selat Dampier\nMPA",trend.non.parametric.test.byMPA.Damp["sl",]),
null.row.sigvals.Damp,
trend.non.parametric.test.bySett.Damp[rev(order(trend.non.parametric.test.bySett.Damp$SettlementName)),])
annex.sigvals.Damp[2:8] <- unlist(annex.sigvals.Damp[2:8])
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 5: Chi-square Tests for Categorical Variables ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 5.1 Status plot, settlement-level chi-square tests ----
# (with MPA-level proportions serving as expected values/probabilities)
# !!! Have not figured out a viable statistical test for settlement-level variation from MPA-level proportions
# BECAUSE, sample sizes are too small (and many times zero) per category, at the settlement level
# ---- 5.2 Trend plot, chi-square tests on most recent monitoring year ----
# (with baseline proportions serving as expected values/probabilities)
propdata.trend.test.Damp <- data.frame(PrimaryOcc=NA,FreqFish=NA,SellFish=NA,IncFish=NA,FishTech=NA,ChildFS=NA,Protein=NA)
p.for.function <- NA
data.for.function <- NA
propdata.trend.test.Damp <-
as.data.frame(mapply(a=c("PrimaryOcc","FreqFish","SellFish","IncFish","FishTech","ChildFS","Protein"),
function(a) {
p.for.function <-
if(sum(Damp.FreqTables$t0[Damp.FreqTables$Variable==a])==0) {
Damp.FreqTables$t2[Damp.FreqTables$Variable==a &
Damp.FreqTables$t2!=0]
} else {Damp.FreqTables$t0[Damp.FreqTables$Variable==a &
Damp.FreqTables$t0!=0] }
data.for.function <-
if(sum(Damp.FreqTables$t0[Damp.FreqTables$Variable==a])==0) {
Damp.FreqTables$t4[Damp.FreqTables$Variable==a &
Damp.FreqTables$t2!=0]
} else {Damp.FreqTables$t4[Damp.FreqTables$Variable==a &
Damp.FreqTables$t0!=0]}
propdata.trend.test.Damp[a] <- ifelse(length(data.for.function)>1,
chisq.test(data.for.function,
p=p.for.function,
rescale.p=TRUE,correct=TRUE)["p.value"],
NA)
propdata.trend.test.Damp[a] <- ifelse(is.na(propdata.trend.test.Damp[a]),100,propdata.trend.test.Damp[a])
}))
colnames(propdata.trend.test.Damp) <- c("PrimaryOcc","FreqFish","SellFish","IncFish","FishTech","ChildFS","Protein")
# ---- Remove all unneeded dataframes from environment, to reduce clutter ----
rm(MPA.TechReport.SigTest.Data)
rm(Damp.TechReport.MPAHouseholdData)
rm(Damp.TechReport.MPAvBHS)
rm(Damp.TechReport.SettlementMeans)
rm(Damp.Trend.Data)
rm(Damp.FreqTables)
rm(even.number.setts.function.Damp)
rm(non.parametric.test.settlements.Damp)
rm(non.parametric.test.MPAvBHS.Damp)
rm(trend.non.parametric.test.byMPA.Damp)
rm(trend.non.parametric.test.bySett.Damp)
rm(null.row.sigvals.Damp)
rm(sigvals.MPA.Damp)
rm(sigvals.Sett.Damp)
rm(p.for.function)
rm(data.for.function) | /xx_Archive/3_Products/Status_trends/BHS_Dampier/Dampier.TechReport.SigTests.R | no_license | WWF-ConsEvidence/MPAMystery | R | false | false | 40,129 | r | #
# code: Dampier Technical Report Significance Tests
#
# github: WWF-ConsEvidence/MPAMystery/2_Social/TechnicalReports/BHS/SignificanceTestCodes
# --- Duplicate all code from "2_Social" onward, to maintain file structure for sourced code
#
# author: Kelly Claborn, clabornkelly@gmail.com
# created: November 2016
# modified: December 2017
#
#
# ---- inputs ----
# Dependencies: BHS_MPA_Mystery.R
#
# ---- code sections ----
# 1) Import Data
# 2) Define Lists of Settlements, to be used in functions
# 3) Plot Variable Distributions (to test normality assumption)
# 4) Non-parametric Significance Test Functions (using Mann-Whitney U test)
# 5) Chi-square Tests for Categorical Variables
#
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 1: Import Data ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 1.1 Subset continuous variable datasets from BHS_MPA_Mystery.R ----
MPA.TechReport.SigTest.Data <-
left_join(BigFive[,c(1,2,4:11,14)],
HHLivelihood[,c(1,15)],
by="HouseholdID")
# - "MPA Household Data" dataset
Damp.TechReport.MPAHouseholdData <-
left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$Treatment==1 &
MPA.TechReport.SigTest.Data$MonitoringYear== "4 Year Post" &
MPA.TechReport.SigTest.Data$MPAID==5,],
Days.unwell.treatment[Days.unwell.treatment$MPAID==5 &
Days.unwell.treatment$MonitoringYear=="4 Year Post",
c("HouseholdID","DaysUnwell")],
by="HouseholdID")
Damp.TechReport.MPAHouseholdData$SettlementName <-
factor(Damp.TechReport.MPAHouseholdData$SettlementName)
# - "MPA versus BHS" dataset
Damp.TechReport.MPAvBHS <-
rbind.data.frame(cbind.data.frame(left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$MPAID==5 &
MPA.TechReport.SigTest.Data$MonitoringYear=="4 Year Post" &
MPA.TechReport.SigTest.Data$Treatment==1,],
Days.unwell[Days.unwell$MPAID==5 &
Days.unwell$MonitoringYear=="4 Year Post" &
Days.unwell$Treatment==1,
c("HouseholdID","DaysUnwell")],
by="HouseholdID"),MPAvBHS="MPA"),
cbind.data.frame(left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$MonitoringYear=="4 Year Post" &
MPA.TechReport.SigTest.Data$Treatment==1,],
Days.unwell[Days.unwell$MonitoringYear=="4 Year Post" & Days.unwell$Treatment==1,
c("HouseholdID","DaysUnwell")],
by="HouseholdID"),MPAvBHS="BHS"))
# - "Settlement Means" dataset
Damp.TechReport.SettlementMeans <-
left_join(BigFive.SettleGroup[BigFive.SettleGroup$Treatment==1 &
BigFive.SettleGroup$MonitoringYear=="4 Year Post" &
BigFive.SettleGroup$MPAID==5,],
Techreport.BySett[Techreport.BySett$MPAID==5 &
Techreport.BySett$MonitoringYear=="4 Year Post",
c("SettlementID","SettlementName","TimeMarketMean")],
by=c("SettlementID","SettlementName"))
Damp.TechReport.SettlementMeans <-
left_join(Damp.TechReport.SettlementMeans,
Days.unwell.BySett[Days.unwell.BySett$MPAID==5 &
Days.unwell.BySett$MonitoringYear=="4 Year Post",c(1,4)],
by="SettlementID")
Damp.TechReport.SettlementMeans <-
Damp.TechReport.SettlementMeans[!is.na(Damp.TechReport.SettlementMeans$SettlementName),]
colnames(Damp.TechReport.SettlementMeans) <- c(colnames(Damp.TechReport.SettlementMeans)[1:5],
"FSIndex","FSErr","MAIndex","MAErr","PAIndex","PAErr",
"MTIndex","MTErr","SERate","SEErr","TimeMarketClean","DaysUnwell")
# - "Trend" dataset
Damp.Trend.Data <-
left_join(MPA.TechReport.SigTest.Data[MPA.TechReport.SigTest.Data$Treatment==1 &
MPA.TechReport.SigTest.Data$MPAID==5,],
Days.unwell[Days.unwell$MPAID==5 &
Days.unwell$Treatment==1,1:2],
by="HouseholdID")
# ---- 1.2 Define list of settlement names in MPA ----
sett.names.Damp <- factor(Damp.TechReport.SettlementMeans$SettlementName)
# ---- 1.3 Subset categorical variable frequency tables from BHS_MPA_Mystery.R ----
# - "Trend" dataset
Damp.FreqTables <-
HHDemos.context[HHDemos.context$MPAID==5,] %>%
group_by(MonitoringYear) %>%
summarise(PrimaryOcc.Fish=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==3 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.Farm=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==1 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.WageLabor=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==7 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.HarvestForest=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==2 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.Tourism=length(PrimaryLivelihoodClean[PrimaryLivelihoodClean==6 &
!is.na(PrimaryLivelihoodClean)]),
PrimaryOcc.Other=length(PrimaryLivelihoodClean[(PrimaryLivelihoodClean==996 | PrimaryLivelihoodClean==4 |
PrimaryLivelihoodClean==5) & !is.na(PrimaryLivelihoodClean)]),
FreqFish.AlmostNever=length(FreqFishClean[FreqFishClean==1 & !is.na(FreqFishClean)]),
FreqFish.FewTimesPer6Mo=length(FreqFishClean[FreqFishClean==2 & !is.na(FreqFishClean)]),
FreqFish.FewTimesPerMo=length(FreqFishClean[FreqFishClean==3 & !is.na(FreqFishClean)]),
FreqFish.FewTimesPerWk=length(FreqFishClean[FreqFishClean==4 & !is.na(FreqFishClean)]),
FreqFish.MoreFewTimesWk=length(FreqFishClean[FreqFishClean==5 & !is.na(FreqFishClean)]),
SellFish.AlmostNever=length(FreqSaleFishClean[FreqSaleFishClean==1 & !is.na(FreqSaleFishClean)]),
SellFish.FewTimesPer6Mo=length(FreqSaleFishClean[FreqSaleFishClean==2 & !is.na(FreqSaleFishClean)]),
SellFish.FewTimesPerMo=length(FreqSaleFishClean[FreqSaleFishClean==3 & !is.na(FreqSaleFishClean)]),
SellFish.FewTimesPerWk=length(FreqSaleFishClean[FreqSaleFishClean==4 & !is.na(FreqSaleFishClean)]),
SellFish.MoreFewTimesWk=length(FreqSaleFishClean[FreqSaleFishClean==5 & !is.na(FreqSaleFishClean)]),
IncFish.None=length(PercentIncFishClean[PercentIncFishClean==1 & !is.na(PercentIncFishClean)]),
IncFish.Some=length(PercentIncFishClean[PercentIncFishClean==2 & !is.na(PercentIncFishClean)]),
IncFish.Half=length(PercentIncFishClean[PercentIncFishClean==3 & !is.na(PercentIncFishClean)]),
IncFish.Most=length(PercentIncFishClean[PercentIncFishClean==4 & !is.na(PercentIncFishClean)]),
IncFish.All=length(PercentIncFishClean[PercentIncFishClean==5 & !is.na(PercentIncFishClean)]),
FishTech.ByHand=length(MajFishTechniqueClean[MajFishTechniqueClean==1 & !is.na(MajFishTechniqueClean)]),
FishTech.StatNet=length(MajFishTechniqueClean[MajFishTechniqueClean==2 & !is.na(MajFishTechniqueClean)]),
FishTech.MobileNet=length(MajFishTechniqueClean[MajFishTechniqueClean==3 & !is.na(MajFishTechniqueClean)]),
FishTech.StatLine=length(MajFishTechniqueClean[MajFishTechniqueClean==4 & !is.na(MajFishTechniqueClean)]),
FishTech.MobileLine=length(MajFishTechniqueClean[MajFishTechniqueClean==5 & !is.na(MajFishTechniqueClean)]),
Child.FS.no=length(Child.FS.category[Child.FS.category=="No or insufficient evidence" & !is.na(Child.FS.category)]),
Child.FS.yes=length(Child.FS.category[Child.FS.category=="Evidence" & !is.na(Child.FS.category)]),
ProteinFish.None=length(PercentProteinFishClean[PercentProteinFishClean==1 & !is.na(PercentProteinFishClean)]),
ProteinFish.Some=length(PercentProteinFishClean[PercentProteinFishClean==2 & !is.na(PercentProteinFishClean)]),
ProteinFish.Half=length(PercentProteinFishClean[PercentProteinFishClean==3 & !is.na(PercentProteinFishClean)]),
ProteinFish.Most=length(PercentProteinFishClean[PercentProteinFishClean==4 & !is.na(PercentProteinFishClean)]),
ProteinFish.All=length(PercentProteinFishClean[PercentProteinFishClean==5 & !is.na(PercentProteinFishClean)]))
Damp.FreqTables <-
as.data.frame(t(Damp.FreqTables[,-1]))
colnames(Damp.FreqTables) <- c("t0","t2","t4")
Damp.FreqTables$Category <- rownames(Damp.FreqTables)
Damp.FreqTables$Variable <- ifelse(grepl("PrimaryOcc",Damp.FreqTables$Category)==T,"PrimaryOcc",
ifelse(grepl("SellFish",Damp.FreqTables$Category)==T,"SellFish",
ifelse(grepl("IncFish",Damp.FreqTables$Category)==T,"IncFish",
ifelse(grepl("FishTech",Damp.FreqTables$Category)==T,"FishTech",
ifelse(grepl("FreqFish",Damp.FreqTables$Category)==T,"FreqFish",
ifelse(grepl("Child",Damp.FreqTables$Category)==T,"ChildFS",
ifelse(grepl("Protein",Damp.FreqTables$Category)==T,"Protein",NA)))))))
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 2: Define Lists of Settlements, to be used in functions ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 2.1 Create list of median settlement for each continuous variable (whether the variable is parametric or non-parametric) ----
even.number.setts.function.Damp <-
mapply(a=Damp.TechReport.SettlementMeans[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
b=Damp.TechReport.MPAHouseholdData[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
function(a,b){
med <- median(a,na.rm=T)
equal <- c(a[which(a==med)])
upper <- c(a[which(a>med)])
upper <- min(upper,na.rm=T)
lower <- c(a[which(a<med)])
lower <- max(lower,na.rm=T)
upper.sett <- Damp.TechReport.SettlementMeans$SettlementName[a==upper]
upper.sett <- ifelse(length(upper.sett)>1 & length(upper.sett)<3,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)]))),
as.character(upper.sett[1]),as.character(upper.sett[2])),
ifelse(length(upper.sett)>1 & length(upper.sett)<4,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3] & !is.na(b)]))),
as.character(upper.sett[1]),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[1] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett[3] & !is.na(b)]))),
as.character(upper.sett[2]),
as.character(upper.sett[3]))),
as.character(upper.sett)))
lower.sett <- Damp.TechReport.SettlementMeans$SettlementName[a==lower]
lower.sett <- ifelse(length(lower.sett)>1 & length(lower.sett)<3,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)]))),
as.character(lower.sett[1]),as.character(lower.sett[2])),
ifelse(length(lower.sett)>1 & length(lower.sett)<4,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3] & !is.na(b)]))),
as.character(lower.sett[1]),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[1] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett[3] & !is.na(b)]))),
as.character(lower.sett[2]),
as.character(lower.sett[3]))),
as.character(lower.sett)))
sett.equal.med <- Damp.TechReport.SettlementMeans$SettlementName[a==equal]
sett.equal.med <- ifelse(length(sett.equal.med)>1 & length(sett.equal.med)<3,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)]))),
as.character(sett.equal.med[1]),as.character(sett.equal.med[2])),
ifelse(length(sett.equal.med)>2 & length(sett.equal.med)<4,
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3] & !is.na(b)]))),
as.character(sett.equal.med[1]),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[1] & !is.na(b)]))) &
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[2] & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3]],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==sett.equal.med[3] & !is.na(b)]))),
as.character(sett.equal.med[2]),
as.character(sett.equal.med[3]))),
ifelse(is.na(sett.equal.med),
NA,
as.character(sett.equal.med))))
median.sett <- ifelse(!is.na(sett.equal.med),
as.character(sett.equal.med),
ifelse((sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==upper.sett & !is.na(b)])))<
(sd(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett],na.rm=T)/sqrt(length(b[Damp.TechReport.MPAHouseholdData$SettlementName==lower.sett & !is.na(b)]))),
as.character(upper.sett),
as.character(lower.sett)))
})
median.setts.Damp <-
mapply(i=Damp.TechReport.SettlementMeans[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
j=names(even.number.setts.function.Damp),
function(i,j){
med <- median(i,na.rm=T)
med.setts <- factor(ifelse(length(sett.names.Damp)%%2!=0,
as.character(Damp.TechReport.SettlementMeans$SettlementName[which(i==med)]),
as.character(even.number.setts.function.Damp[j])),
levels=levels(sett.names.Damp))})
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 3: Plot Variable Distributions (to test normality assumption) ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 3.1 Food security score distribution ----
dist.Damp.FS <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=FSIndex,y=..density..),
bins=5,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$FSIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$FSIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Food Security Scores\n(per household)",
y="Density",
title="Damp: Food Security Score Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$FSIndex)
qqline(Damp.TechReport.MPAHouseholdData$FSIndex,col="green")
# ---- 3.2 Material assets score distribution ----
dist.Damp.MA <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=MAIndex,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$MAIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$MAIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Material Assets\n(per household)",
y="Density",
title="Damp: HH Material Assets Distribution, 2014") +
dist.plot.theme
log.MA <- log(Damp.TechReport.MPAHouseholdData$MAIndex[Damp.TechReport.MPAHouseholdData$MAIndex!=0])
qqnorm(log.MA)
qqline(log.MA,col="green")
# ---- 3.3 Place attachment score distribution ----
dist.Damp.PA <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=PAIndex,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$PAIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$PAIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Place Attachment Score\nPer Household",
y="Density",
title="Damp: Place Attachment Score Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$PAIndex)
qqline(Damp.TechReport.MPAHouseholdData$PAIndex,col="green")
# ---- 3.4 Marine tenure score distribution ----
dist.Damp.MT <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=MTIndex,y=..density..),
binwidth=1,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$MTIndex),
sd=sd(Damp.TechReport.MPAHouseholdData$MTIndex)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Marine Tenure Score\n(per household)",
y="Density",
title="Damp: Marine Tenure Score Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$MTIndex)
qqline(Damp.TechReport.MPAHouseholdData$MTIndex,col="green")
# ---- 3.5 School enrollment rate distribution ----
dist.Damp.SE <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=SERate,y=..density..),
bins=15,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$SERate),
sd=sd(Damp.TechReport.MPAHouseholdData$SERate)),
colour="#262F52",size=1,na.rm=T) +
labs(x="School Enrollment Rate\n(per household)",
y="Density",
title="Damp: School Enrollment Rate Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$SERate)
qqline(Damp.TechReport.MPAHouseholdData$SERate,col="green")
# ---- 3.6 Time to market distribution ----
dist.Damp.TimeMarket <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=TimeMarketClean,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$TimeMarketClean),
sd=sd(Damp.TechReport.MPAHouseholdData$TimeMarketClean)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Average Time to Market\n(in hours)",
y="Density",
title="Damp: Time to Market Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$TimeMarketClean)
qqline(Damp.TechReport.MPAHouseholdData$TimeMarketClean,col="green")
# ---- 3.7 Days unwell distribution ----
dist.Damp.DaysUnwell <-
ggplot(Damp.TechReport.MPAHouseholdData) +
geom_histogram(aes(x=DaysUnwell,y=..density..),
bins=20,fill="#5971C7",colour="#262F52",na.rm=T) +
stat_function(fun=dnorm,args=list(mean=mean(Damp.TechReport.MPAHouseholdData$DaysUnwell),
sd=sd(Damp.TechReport.MPAHouseholdData$DaysUnwell)),
colour="#262F52",size=1,na.rm=T) +
labs(x="Days Unwell\n(per household)",
y="Density",
title="Damp: HH Days Unwell Distribution, 2014") +
dist.plot.theme
qqnorm(Damp.TechReport.MPAHouseholdData$DaysUnwell)
qqline(Damp.TechReport.MPAHouseholdData$DaysUnwell,col="green")
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 4: Non-parametric Significance Test Functions (using Mann-Whitney U test) ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# NOTE: Typically, food security, material assets, marine tenure, enrollment rate, and place attachment end up being non-parametric;
# however, if the distribution appears to be normal, then PARAMETRIC tests are more powerful and the better choice.
# ---- 4.1 Create function that will output significance values for non-parametric variables, BY SETTLEMENT ----
# (for status plots)
non.parametric.test.settlements.Damp <-
data.frame(mapply(a=c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell"),
function(a){
results <-
list(cbind.data.frame(SettlementName=c(as.character(sett.names.Damp[which(sett.names.Damp!=median.setts.Damp[a])]),
as.character(median.setts.Damp[a])),
rbind.data.frame(t(data.frame(mapply(i=sett.names.Damp[which(sett.names.Damp!=median.setts.Damp[a])],
function(i){
var <-
Damp.TechReport.MPAHouseholdData[Damp.TechReport.MPAHouseholdData$SettlementName==i |
Damp.TechReport.MPAHouseholdData$SettlementName==median.setts.Damp[a],a]
test <-
wilcox.test(var~SettlementName,
data=Damp.TechReport.MPAHouseholdData[Damp.TechReport.MPAHouseholdData$SettlementName==i |
Damp.TechReport.MPAHouseholdData$SettlementName==median.setts.Damp[a],],
exact=F)
}))["p.value",]),
"median")))
}))
# - Alphabetize each column of settlement names. Now all settlement names are in same order.
sigvals.Sett.Damp <-
cbind.data.frame(non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"FSIndex.SettlementName"),
c("FSIndex.SettlementName","FSIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"MAIndex.SettlementName"),
c("MAIndex.SettlementName","MAIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"PAIndex.SettlementName"),
c("PAIndex.SettlementName","PAIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"MTIndex.SettlementName"),
c("MTIndex.SettlementName","MTIndex.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"SERate.SettlementName"),
c("SERate.SettlementName","SERate.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"TimeMarketClean.SettlementName"),
c("TimeMarketClean.SettlementName","TimeMarketClean.p.value")],
non.parametric.test.settlements.Damp[order(non.parametric.test.settlements.Damp$"DaysUnwell.SettlementName"),
c("DaysUnwell.SettlementName","DaysUnwell.p.value")])
# - Remove all settlement name columns except for one.
sigvals.Sett.Damp <-
sigvals.Sett.Damp[,c(1,2,4,6,8,10,12,14)]
colnames(sigvals.Sett.Damp) <- c("SettlementName","FS.pval","MA.pval","PA.pval","MT.pval","SE.pval","Time.pval","Unwell.pval")
# ---- 4.2 Create function that will output significance values for non-parametric variables, MPA VS. BHS ----
# (for status plots, comparing MPA households to all BHS households)
non.parametric.test.MPAvBHS.Damp <-
data.frame(mapply(a=c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell"),
function(a){
var <- Damp.TechReport.MPAvBHS[,a]
wilcox.test(var~MPAvBHS,
data=Damp.TechReport.MPAvBHS,
exact=F)}))["p.value",]
sigvals.MPA.Damp <-
cbind.data.frame("Selat Dampier\nMPA",non.parametric.test.MPAvBHS.Damp)
colnames(sigvals.MPA.Damp) <- colnames(sigvals.Sett.Damp)
null.row.sigvals.Damp <-
matrix(rep(NA,length(sigvals.MPA.Damp)),ncol=length(sigvals.MPA.Damp),
dimnames=list(NULL,colnames(sigvals.MPA.Damp)))
# - Define data frame with p-values for status plots
# (households in each settlement are compared to those in the median settlement for the given variable,
# using Mann Whitney U-Test -- so, interpretation is "compared to the median settlement, this settlement
# [is/is not] significantly different")
#
# (for MPA p-values, households in the MPA were compared to those in the control settlements (for the MPA),
# also using Mann-Whitney U test)
sigvals.Damp <-
rbind.data.frame(sigvals.MPA.Damp,
null.row.sigvals.Damp,
sigvals.Sett.Damp[rev(order(sigvals.Sett.Damp$SettlementName)),])
sigvals.Damp[,2:8] <- unlist(sigvals.Damp[,2:8])
# ---- 4.3 Create function that will output TREND significance values for non-parametric variables, BY MPA ----
# (for trend plots)
trend.non.parametric.test.byMPA.Damp <-
data.frame(mapply(i=Damp.Trend.Data[,c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell")],
function(i){
MannKendall(c(i[Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[1]],
i[Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[2]],
i[Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[3]]))
}))
colnames(trend.non.parametric.test.byMPA.Damp) <- colnames(sigvals.Damp[2:8])
# - Define data frame with p-values for trend plots
# (all MPA households from each year of sampling are compared across time for the given variable,
# using monotonic trend test, Mann-Kendall -- so, interpretation is "across the sampling years,
# there [is/is not] a significant difference in this variable across the MPA")
trend.sigvals.Damp <-
cbind.data.frame(MonitoringYear="p.value",trend.non.parametric.test.byMPA.Damp["sl",1],NA,trend.non.parametric.test.byMPA.Damp["sl",2],
NA,trend.non.parametric.test.byMPA.Damp["sl",3],NA,trend.non.parametric.test.byMPA.Damp["sl",4],NA,trend.non.parametric.test.byMPA.Damp["sl",5],
NA,trend.non.parametric.test.byMPA.Damp["sl",6],NA,trend.non.parametric.test.byMPA.Damp["sl",7],NA)
colnames(trend.sigvals.Damp) <- c("MonitoringYear","FSMean","FSErr","MAMean","MAErr","PAMean","PAErr","MTMean","MTErr","SEMean","SEErr",
"TimeMarketMean","TimeMarketErr","UnwellMean","UnwellErr")
trend.sigvals.Damp <- unlist(trend.sigvals.Damp)
# ---- 4.4 Create function that will output TREND significance values for non-parametric variables, BY SETTLEMENT ----
# (for annex plots)
trend.non.parametric.test.bySett.Damp <-
cbind.data.frame(SettlementName=as.character(sett.names.Damp),
mapply(a=c("FSIndex","MAIndex","PAIndex","MTIndex","SERate","TimeMarketClean","DaysUnwell"),
function(a){
t(data.frame(mapply(i=as.character(sett.names.Damp),
function(i){
MannKendall(c(Damp.Trend.Data[Damp.Trend.Data$SettlementName==i &
Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[1],a],
Damp.Trend.Data[Damp.Trend.Data$SettlementName==i &
Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[2],a],
Damp.Trend.Data[Damp.Trend.Data$SettlementName==i &
Damp.Trend.Data$InterviewYear==unique(Damp.Trend.Data$InterviewYear)[3],a]))
}))["sl",])}))
colnames(trend.non.parametric.test.bySett.Damp) <- colnames(sigvals.Damp)
# - Define data frame with p-values for annex plots
# (households within each settlement from each year of sampling are compared across time for the given
# variable, using monotonic trend test, Mann-Kendall -- so, interpretation is "across the sampling years,
# there [is/is not] a significant difference in this variable across the settlement)
annex.sigvals.Damp <-
rbind.data.frame(cbind.data.frame(SettlementName="Selat Dampier\nMPA",trend.non.parametric.test.byMPA.Damp["sl",]),
null.row.sigvals.Damp,
trend.non.parametric.test.bySett.Damp[rev(order(trend.non.parametric.test.bySett.Damp$SettlementName)),])
annex.sigvals.Damp[2:8] <- unlist(annex.sigvals.Damp[2:8])
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- SECTION 5: Chi-square Tests for Categorical Variables ----
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ---- 5.1 Status plot, settlement-level chi-square tests ----
# (with MPA-level proportions serving as expected values/probabilities)
# !!! Have not figured out a viable statistical test for settlement-level variation from MPA-level proportions
# BECAUSE, sample sizes are too small (and many times zero) per category, at the settlement level
# ---- 5.2 Trend plot, chi-square tests on most recent monitoring year ----
# (with baseline proportions serving as expected values/probabilities)
propdata.trend.test.Damp <- data.frame(PrimaryOcc=NA,FreqFish=NA,SellFish=NA,IncFish=NA,FishTech=NA,ChildFS=NA,Protein=NA)
p.for.function <- NA
data.for.function <- NA
propdata.trend.test.Damp <-
as.data.frame(mapply(a=c("PrimaryOcc","FreqFish","SellFish","IncFish","FishTech","ChildFS","Protein"),
function(a) {
p.for.function <-
if(sum(Damp.FreqTables$t0[Damp.FreqTables$Variable==a])==0) {
Damp.FreqTables$t2[Damp.FreqTables$Variable==a &
Damp.FreqTables$t2!=0]
} else {Damp.FreqTables$t0[Damp.FreqTables$Variable==a &
Damp.FreqTables$t0!=0] }
data.for.function <-
if(sum(Damp.FreqTables$t0[Damp.FreqTables$Variable==a])==0) {
Damp.FreqTables$t4[Damp.FreqTables$Variable==a &
Damp.FreqTables$t2!=0]
} else {Damp.FreqTables$t4[Damp.FreqTables$Variable==a &
Damp.FreqTables$t0!=0]}
propdata.trend.test.Damp[a] <- ifelse(length(data.for.function)>1,
chisq.test(data.for.function,
p=p.for.function,
rescale.p=TRUE,correct=TRUE)["p.value"],
NA)
propdata.trend.test.Damp[a] <- ifelse(is.na(propdata.trend.test.Damp[a]),100,propdata.trend.test.Damp[a])
}))
colnames(propdata.trend.test.Damp) <- c("PrimaryOcc","FreqFish","SellFish","IncFish","FishTech","ChildFS","Protein")
# ---- Remove all unneeded dataframes from environment, to reduce clutter ----
rm(MPA.TechReport.SigTest.Data)
rm(Damp.TechReport.MPAHouseholdData)
rm(Damp.TechReport.MPAvBHS)
rm(Damp.TechReport.SettlementMeans)
rm(Damp.Trend.Data)
rm(Damp.FreqTables)
rm(even.number.setts.function.Damp)
rm(non.parametric.test.settlements.Damp)
rm(non.parametric.test.MPAvBHS.Damp)
rm(trend.non.parametric.test.byMPA.Damp)
rm(trend.non.parametric.test.bySett.Damp)
rm(null.row.sigvals.Damp)
rm(sigvals.MPA.Damp)
rm(sigvals.Sett.Damp)
rm(p.for.function)
rm(data.for.function) |
#' Create summary statistics for ZPDGrowthTrajectories
#'
#' \code{describeTrajectories} calculates summary statistics by time interval and version of the
#' school curriculum for for \code{ZPDGrowthTrajectories()} output.
#'
#' @param trajectories An object of class \code{ZPD} produced by the \code{ZPDGrowthTrajectories()}
#' function. If needed, this object will be converted internally to "long" format.
#'
#' @param byTransition Logical. Should descriptives be provided only at curricular transitions (as
#' well as the first and last time point)? Defaults to TRUE.
#'
#' @param byVersion Logical. Should descriptives be broken down by version of the curriculum (
#' e.g., typical, remedial)? Defaults to TRUE.
#'
#' @param times Optional. A vector of specific times at which descriptives should be computed.
#' Defaults to NULL.
#'
#' @return An object of class \code{tibble}
#'
#' @seealso \code{\link{visualizeTrajectories}} for plotting the trajectories.
#'
#' @seealso \code{\link{ZPDGrowthTrajectories}} for simulating growth trajectories.
#'
#' @importFrom utils tail
#' @importFrom dplyr summarise group_by n filter select everything
#' @importFrom stats median sd
#' @importFrom checkmate qtest
#'
#' @examples
#'
#' # learning rate
#' learn.rate <- c(.08, .10, .12, .18)
#'
#' # decay rate
#' decay.rate <- c(.04, .03, .02, .01)
#'
#' # initial achievement
#' initial.ach <- rep(0, times=4)
#'
#' # quality of home environment
#' home.env <- c(.06, .12, .15, .20)
#'
#' # assignment object simulating starting kindergarten on time 801
#' # Kindergarten for 200 days, followed by 100 days of summer
#' # then 200 days of first grade
#' assignment <- c(rep(0, times=800), rep(1, times=200),
#' rep(0, times=100), rep(2, times=200))
#'
#' # define school curriculum
#' curriculum.start.points <- list(
#' # "typical curriculum" start points for K and first grade
#' matrix(c(.2, .26), nrow=2, ncol=1),
#' # "advanced curriculum" start points for K and first grade
#' matrix(c(.22, .29), nrow=2, ncol=1)
#' )
#'
#' curriculum.widths <- list(
#' # "typical curriculum" widths for K and first grade
#' matrix(c(.04, .04), nrow=2, ncol=1),
#' # "advanced curriculum" widths for K and first grade
#' matrix(c(.05, .05), nrow=2, ncol=1)
#' )
#'
#' curriculum.review.slopes <- list(
#' # "typical curriculum" review slopes for K and first grade
#' matrix(c(30, 30), nrow=2, ncol=1),
#' # "advanced curriculum" review slopes for K and first grade
#' matrix(c(60, 60), nrow=2, ncol=1)
#' )
#'
#' curriculum.advanced.slopes <- list(
#' # "typical curriculum" advanced slopes for K and first grade
#' matrix(c(50, 50), nrow=2, ncol=1),
#' # "advanced curriculum" advanced slopes for K and first grade
#' matrix(c(25, 25), nrow=2, ncol=1)
#' )
#'
#' # students 1 and 2 get typical curriculum, 3 and 4 get advanced
#' which.curriculum <- c(1,1,2,2)
#'
#' y <- ZPDGrowthTrajectories(learn.rate=learn.rate, home.env=home.env,
#' decay.rate=decay.rate, initial.ach=initial.ach,
#' ZPD.width=.05, ZPD.offset=.02,
#' home.learning.decay.rate=6,
#' curriculum.start.points=curriculum.start.points,
#' curriculum.widths=curriculum.widths,
#' curriculum.review.slopes=curriculum.review.slopes,
#' curriculum.advanced.slopes=curriculum.advanced.slopes,
#' assignment=assignment, dosage=.8,
#' adaptive.curriculum=FALSE,
#' which.curriculum=which.curriculum,
#' school.weight=.5, home.weight=1, decay.weight=.05,
#' verbose=TRUE)
#
#' describeTrajectories(y, byVersion=FALSE)
#'
#' describeTrajectories(y, byTransition=FALSE, times=c(100, 300, 650))
#'
#' @export
describeTrajectories <- function(trajectories, byTransition=TRUE, byVersion=TRUE, times=NULL) {
`%notin%` <- Negate(`%in%`)
# check if trajectories is class ZPD, if not stop
if(!("ZPD" %in% class(trajectories))) {stop("Object supplied to trajectories argument is not ZPDGrowthTrajectories() output")}
# check arguments
# check if byVersion is logical, length one, not NA
if (checkmate::qtest(byVersion, "B1") == FALSE) {stop("byVersion must be TRUE or FALSE")}
# check if byTransition is logical, length one, not NA
if (checkmate::qtest(byTransition, "B1") == FALSE) {stop("byTransition must be TRUE or FALSE")}
# if times is not NULL, check that it is an integer-like object of length 1+ containing no NAs
if (!is.null(times)) {
if (checkmate::qtest(times, "X+[1,)") == FALSE) {stop("times must either be NULL or an integer vector containing positive values")}
if (any(times %notin% trajectories$time)) {stop("a value in times exceeds the range of time points included in trajectories")}
}
# get assignment object from ZPDGrowthTrajectories output
assignment <- trajectories$assignment[trajectories$version==1 & trajectories$id==1]
if (byTransition==FALSE & is.null(times)) {
warning("byTransition is FALSE and no values were supplied for times; computing descriptives for each time point.")
assignment <- unique(trajectories$time)
index <- assignment
noassignment.flag <- TRUE
} else if (byTransition==FALSE & !is.null(times)) {
index <- times
noassignment.flag <- FALSE #?
} else {
noassignment.flag <- FALSE
# find transitions in the assignment object
lag.assignment <- c(utils::tail(assignment,-1),NA)
# index of those transitions, appending first and last time point / time
index <- c(1, which(assignment != lag.assignment), length(assignment))
if (!is.null(times)) {
# append the values specified for times
index <- c(index, times)
# sort them
index <- index[order(index)]
}
}
if (byVersion == TRUE) {
summarytable <- dplyr::summarise(dplyr::group_by(dplyr::filter(trajectories, time %in% index),
time, version), n=dplyr::n(),
mean=mean(achievement, na.rm=TRUE),
median=stats::median(achievement, na.rm=TRUE),
stddev=stats::sd(achievement, na.rm=TRUE),
min=min(achievement, na.rm=TRUE),
max=max(achievement, na.rm=TRUE))
} else if (byVersion == FALSE) {
summarytable <- dplyr::summarise(dplyr::group_by(dplyr::filter(trajectories, time %in% index),
time), n=dplyr::n(),
mean=mean(achievement, na.rm=TRUE),
median=stats::median(achievement, na.rm=TRUE),
stddev=stats::sd(achievement, na.rm=TRUE),
min=min(achievement, na.rm=TRUE),
max=max(achievement, na.rm=TRUE))
}
if (noassignment.flag == FALSE) {
summarytable$assignment <- assignment[summarytable$time]
summarytable <- dplyr::select(summarytable, time, assignment, dplyr::everything())
}
return(summarytable)
}
| /R/describeTrajectories_function.r | no_license | mcbeem/ZPDGrowthTrajectories | R | false | false | 7,192 | r | #' Create summary statistics for ZPDGrowthTrajectories
#'
#' \code{describeTrajectories} calculates summary statistics by time interval and version of the
#' school curriculum for for \code{ZPDGrowthTrajectories()} output.
#'
#' @param trajectories An object of class \code{ZPD} produced by the \code{ZPDGrowthTrajectories()}
#' function. If needed, this object will be converted internally to "long" format.
#'
#' @param byTransition Logical. Should descriptives be provided only at curricular transitions (as
#' well as the first and last time point)? Defaults to TRUE.
#'
#' @param byVersion Logical. Should descriptives be broken down by version of the curriculum (
#' e.g., typical, remedial)? Defaults to TRUE.
#'
#' @param times Optional. A vector of specific times at which descriptives should be computed.
#' Defaults to NULL.
#'
#' @return An object of class \code{tibble}
#'
#' @seealso \code{\link{visualizeTrajectories}} for plotting the trajectories.
#'
#' @seealso \code{\link{ZPDGrowthTrajectories}} for simulating growth trajectories.
#'
#' @importFrom utils tail
#' @importFrom dplyr summarise group_by n filter select everything
#' @importFrom stats median sd
#' @importFrom checkmate qtest
#'
#' @examples
#'
#' # learning rate
#' learn.rate <- c(.08, .10, .12, .18)
#'
#' # decay rate
#' decay.rate <- c(.04, .03, .02, .01)
#'
#' # initial achievement
#' initial.ach <- rep(0, times=4)
#'
#' # quality of home environment
#' home.env <- c(.06, .12, .15, .20)
#'
#' # assignment object simulating starting kindergarten on time 801
#' # Kindergarten for 200 days, followed by 100 days of summer
#' # then 200 days of first grade
#' assignment <- c(rep(0, times=800), rep(1, times=200),
#' rep(0, times=100), rep(2, times=200))
#'
#' # define school curriculum
#' curriculum.start.points <- list(
#' # "typical curriculum" start points for K and first grade
#' matrix(c(.2, .26), nrow=2, ncol=1),
#' # "advanced curriculum" start points for K and first grade
#' matrix(c(.22, .29), nrow=2, ncol=1)
#' )
#'
#' curriculum.widths <- list(
#' # "typical curriculum" widths for K and first grade
#' matrix(c(.04, .04), nrow=2, ncol=1),
#' # "advanced curriculum" widths for K and first grade
#' matrix(c(.05, .05), nrow=2, ncol=1)
#' )
#'
#' curriculum.review.slopes <- list(
#' # "typical curriculum" review slopes for K and first grade
#' matrix(c(30, 30), nrow=2, ncol=1),
#' # "advanced curriculum" review slopes for K and first grade
#' matrix(c(60, 60), nrow=2, ncol=1)
#' )
#'
#' curriculum.advanced.slopes <- list(
#' # "typical curriculum" advanced slopes for K and first grade
#' matrix(c(50, 50), nrow=2, ncol=1),
#' # "advanced curriculum" advanced slopes for K and first grade
#' matrix(c(25, 25), nrow=2, ncol=1)
#' )
#'
#' # students 1 and 2 get typical curriculum, 3 and 4 get advanced
#' which.curriculum <- c(1,1,2,2)
#'
#' y <- ZPDGrowthTrajectories(learn.rate=learn.rate, home.env=home.env,
#' decay.rate=decay.rate, initial.ach=initial.ach,
#' ZPD.width=.05, ZPD.offset=.02,
#' home.learning.decay.rate=6,
#' curriculum.start.points=curriculum.start.points,
#' curriculum.widths=curriculum.widths,
#' curriculum.review.slopes=curriculum.review.slopes,
#' curriculum.advanced.slopes=curriculum.advanced.slopes,
#' assignment=assignment, dosage=.8,
#' adaptive.curriculum=FALSE,
#' which.curriculum=which.curriculum,
#' school.weight=.5, home.weight=1, decay.weight=.05,
#' verbose=TRUE)
#
#' describeTrajectories(y, byVersion=FALSE)
#'
#' describeTrajectories(y, byTransition=FALSE, times=c(100, 300, 650))
#'
#' @export
describeTrajectories <- function(trajectories, byTransition=TRUE, byVersion=TRUE, times=NULL) {
`%notin%` <- Negate(`%in%`)
# check if trajectories is class ZPD, if not stop
if(!("ZPD" %in% class(trajectories))) {stop("Object supplied to trajectories argument is not ZPDGrowthTrajectories() output")}
# check arguments
# check if byVersion is logical, length one, not NA
if (checkmate::qtest(byVersion, "B1") == FALSE) {stop("byVersion must be TRUE or FALSE")}
# check if byTransition is logical, length one, not NA
if (checkmate::qtest(byTransition, "B1") == FALSE) {stop("byTransition must be TRUE or FALSE")}
# if times is not NULL, check that it is an integer-like object of length 1+ containing no NAs
if (!is.null(times)) {
if (checkmate::qtest(times, "X+[1,)") == FALSE) {stop("times must either be NULL or an integer vector containing positive values")}
if (any(times %notin% trajectories$time)) {stop("a value in times exceeds the range of time points included in trajectories")}
}
# get assignment object from ZPDGrowthTrajectories output
assignment <- trajectories$assignment[trajectories$version==1 & trajectories$id==1]
if (byTransition==FALSE & is.null(times)) {
warning("byTransition is FALSE and no values were supplied for times; computing descriptives for each time point.")
assignment <- unique(trajectories$time)
index <- assignment
noassignment.flag <- TRUE
} else if (byTransition==FALSE & !is.null(times)) {
index <- times
noassignment.flag <- FALSE #?
} else {
noassignment.flag <- FALSE
# find transitions in the assignment object
lag.assignment <- c(utils::tail(assignment,-1),NA)
# index of those transitions, appending first and last time point / time
index <- c(1, which(assignment != lag.assignment), length(assignment))
if (!is.null(times)) {
# append the values specified for times
index <- c(index, times)
# sort them
index <- index[order(index)]
}
}
if (byVersion == TRUE) {
summarytable <- dplyr::summarise(dplyr::group_by(dplyr::filter(trajectories, time %in% index),
time, version), n=dplyr::n(),
mean=mean(achievement, na.rm=TRUE),
median=stats::median(achievement, na.rm=TRUE),
stddev=stats::sd(achievement, na.rm=TRUE),
min=min(achievement, na.rm=TRUE),
max=max(achievement, na.rm=TRUE))
} else if (byVersion == FALSE) {
summarytable <- dplyr::summarise(dplyr::group_by(dplyr::filter(trajectories, time %in% index),
time), n=dplyr::n(),
mean=mean(achievement, na.rm=TRUE),
median=stats::median(achievement, na.rm=TRUE),
stddev=stats::sd(achievement, na.rm=TRUE),
min=min(achievement, na.rm=TRUE),
max=max(achievement, na.rm=TRUE))
}
if (noassignment.flag == FALSE) {
summarytable$assignment <- assignment[summarytable$time]
summarytable <- dplyr::select(summarytable, time, assignment, dplyr::everything())
}
return(summarytable)
}
|
library(webshot)
library(leaflet)
library(htmlwidgets)
# library(ggmap)
library(RColorBrewer)
library(raster)
library(classInt)
library(stringr)
setwd("D:/website_MODIS/AOD_web/2016_AOD_tiff_1km")
# Load data
list_tiff <- list.files(pattern = "\\.tif$")
list_days <- str_sub(list_tiff, start = 1, end = -5)
df_AOD = data.frame(dates = list_days, image_tiff = list_tiff)
df_AOD$dates <- as.character(df_AOD$dates)
df_AOD$image_tiff <- as.character(df_AOD$image_tiff)
for (i in 1:nrow(df_AOD)) {
# for (i in 1:5) {
# AOD_raster_tiff <- raster(as.character(filter(df_AOD, dates == input$dates))[2])
AOD_raster_tiff <- raster(as.character(df_AOD$image_tiff)[i])
values(AOD_raster_tiff)[values(AOD_raster_tiff) < 0.05]<- 0.05
values(AOD_raster_tiff)[values(AOD_raster_tiff) > 1.6]<- 1.6
MIN_AOD <- 0.05
MAX_AOD <- 1.6
# pal_AOD <- colorNumeric(c("#9999FF", "#ffd699", "#FFFF00", "#ffbf00", "#ffc700", "#FF0000", "#994c00"),
# getValues(AOD_raster_tiff),na.color = "transparent")
pal_AOD <- colorNumeric(c("#9999FF", "#ffd699", "#FFFF00", "#ffbf00", "#ffc700", "#FF0000", "#994c00"),
c(MIN_AOD, MAX_AOD), na.color = "transparent")
# define popup for AOD
"h1 { font-size: 4px;}"
content <- paste('<h1><strong>', (df_AOD$dates)[i],'', sep = "")
map <- leaflet() %>%
addTiles() %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles("OpenStreetMap.Mapnik", group = "Road map") %>%
addProviderTiles("Thunderforest.Landscape", group = "Topographical") %>%
addProviderTiles("Esri.WorldImagery", group = "Satellite") %>%
addProviderTiles("Stamen.TonerLite", group = "Toner Lite") %>%
addPopups(53.37, 24.8, content,
options = popupOptions(closeButton = FALSE)) %>%
addRasterImage(AOD_raster_tiff,
colors = pal_AOD,
opacity = 0.5, group = "AOD") %>%
# addLegend("bottomright", pal = pal_AOD, values = getValues(AOD_raster_tiff),
# title = "<br><strong>AOD - MODIS: </strong>",
# labFormat = labelFormat(prefix = ""),
# opacity = 0.5) %>%
addLegend("bottomright", pal = pal_AOD, values = c(MIN_AOD, MAX_AOD),
title = "<br><strong>AOD - MODIS: </strong>",
labFormat = labelFormat(prefix = ""),
opacity = 0.5) %>%
addLayersControl(
baseGroups = c("Road map", "Topographical", "Satellite", "Toner Lite"),
overlayGroups = "AOD",
options = layersControlOptions(collapsed = TRUE))
## This is the png creation part
saveWidget(map, 'temp.html', selfcontained = FALSE)
webshot('temp.html', file = paste0((df_AOD$dates)[i],".png"), vwidth = 900, vheight = 900,
cliprect = 'viewport')
}
# to use with ImageMagik using the commnad line cmd in windows
# magick -delay 100 -loop 0 *.png MODIS_AOD_2016.gif
###############################################################################
###############################################################################
###############################################################################
| /animation_png.R | no_license | karafede/MODIS_UAE_AQ | R | false | false | 3,226 | r |
library(webshot)
library(leaflet)
library(htmlwidgets)
# library(ggmap)
library(RColorBrewer)
library(raster)
library(classInt)
library(stringr)
setwd("D:/website_MODIS/AOD_web/2016_AOD_tiff_1km")
# Load data
list_tiff <- list.files(pattern = "\\.tif$")
list_days <- str_sub(list_tiff, start = 1, end = -5)
df_AOD = data.frame(dates = list_days, image_tiff = list_tiff)
df_AOD$dates <- as.character(df_AOD$dates)
df_AOD$image_tiff <- as.character(df_AOD$image_tiff)
for (i in 1:nrow(df_AOD)) {
# for (i in 1:5) {
# AOD_raster_tiff <- raster(as.character(filter(df_AOD, dates == input$dates))[2])
AOD_raster_tiff <- raster(as.character(df_AOD$image_tiff)[i])
values(AOD_raster_tiff)[values(AOD_raster_tiff) < 0.05]<- 0.05
values(AOD_raster_tiff)[values(AOD_raster_tiff) > 1.6]<- 1.6
MIN_AOD <- 0.05
MAX_AOD <- 1.6
# pal_AOD <- colorNumeric(c("#9999FF", "#ffd699", "#FFFF00", "#ffbf00", "#ffc700", "#FF0000", "#994c00"),
# getValues(AOD_raster_tiff),na.color = "transparent")
pal_AOD <- colorNumeric(c("#9999FF", "#ffd699", "#FFFF00", "#ffbf00", "#ffc700", "#FF0000", "#994c00"),
c(MIN_AOD, MAX_AOD), na.color = "transparent")
# define popup for AOD
"h1 { font-size: 4px;}"
content <- paste('<h1><strong>', (df_AOD$dates)[i],'', sep = "")
map <- leaflet() %>%
addTiles() %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles("OpenStreetMap.Mapnik", group = "Road map") %>%
addProviderTiles("Thunderforest.Landscape", group = "Topographical") %>%
addProviderTiles("Esri.WorldImagery", group = "Satellite") %>%
addProviderTiles("Stamen.TonerLite", group = "Toner Lite") %>%
addPopups(53.37, 24.8, content,
options = popupOptions(closeButton = FALSE)) %>%
addRasterImage(AOD_raster_tiff,
colors = pal_AOD,
opacity = 0.5, group = "AOD") %>%
# addLegend("bottomright", pal = pal_AOD, values = getValues(AOD_raster_tiff),
# title = "<br><strong>AOD - MODIS: </strong>",
# labFormat = labelFormat(prefix = ""),
# opacity = 0.5) %>%
addLegend("bottomright", pal = pal_AOD, values = c(MIN_AOD, MAX_AOD),
title = "<br><strong>AOD - MODIS: </strong>",
labFormat = labelFormat(prefix = ""),
opacity = 0.5) %>%
addLayersControl(
baseGroups = c("Road map", "Topographical", "Satellite", "Toner Lite"),
overlayGroups = "AOD",
options = layersControlOptions(collapsed = TRUE))
## This is the png creation part
saveWidget(map, 'temp.html', selfcontained = FALSE)
webshot('temp.html', file = paste0((df_AOD$dates)[i],".png"), vwidth = 900, vheight = 900,
cliprect = 'viewport')
}
# to use with ImageMagik using the commnad line cmd in windows
# magick -delay 100 -loop 0 *.png MODIS_AOD_2016.gif
###############################################################################
###############################################################################
###############################################################################
|
#' survForm
#'
#' Turns a survival object into a dataframe for ggplot
#'
#' @param srv A Surv class object.
#' @param X A factor or character vector on which the survival should be split.
#' @return A data.frame with columns for time, n.risk, n.event, n.censor, surv, lower and upper. (95% confidence intervals)
#' @export
#' @examples
#' srv <- Surv(c(rchisq(1000,3)*10,
#' rchisq(1000,5)*10),
#' c(rbinom(1000,1,.9),
#' rbinom(1000,1,.9)))
#' X <- rep(c('A','B'),each=1000)
#' frm <- survForm(srv,X)
#' head(frm)
survForm <- function(srv,X=NULL){
if(class(srv) != 'Surv') stop('srv is not a Survival object.')
if(is.null(X)){
s <- survival::survfit(srv~1)
frm <- data.frame(time = c(0,s$time),
n.risk = c(s$n.risk[1],s$n.risk),
n.event = c(0,s$n.event),
n.censor = c(0,s$n.censor),
surv = c(1,s$surv),
lower = c(s$lower[1],s$lower),
upper = c(s$upper[1],s$upper))
return(frm)
}
data.frame(srv= srv,X=X) %>%
dplyr::group_by(X) %>%
dplyr::do(s = survival::survfit(.$srv~1)) %>%
dplyr::do(data.frame(
Group = .$X,
time = c(0,.$s$time),
n.risk = c(.$s$n.risk[1],.$s$n.risk),
n.event = c(0,.$s$n.event),
n.censor = c(0,.$s$n.censor),
surv = c(1,.$s$surv),
lower = c(.$s$lower[1],.$s$lower),
upper = c(.$s$upper[1],.$s$upper))) %>%
as.data.frame()
}
| /R/survForm.R | no_license | hennerw/ggSurvival | R | false | false | 1,468 | r | #' survForm
#'
#' Turns a survival object into a dataframe for ggplot
#'
#' @param srv A Surv class object.
#' @param X A factor or character vector on which the survival should be split.
#' @return A data.frame with columns for time, n.risk, n.event, n.censor, surv, lower and upper. (95% confidence intervals)
#' @export
#' @examples
#' srv <- Surv(c(rchisq(1000,3)*10,
#' rchisq(1000,5)*10),
#' c(rbinom(1000,1,.9),
#' rbinom(1000,1,.9)))
#' X <- rep(c('A','B'),each=1000)
#' frm <- survForm(srv,X)
#' head(frm)
survForm <- function(srv,X=NULL){
if(class(srv) != 'Surv') stop('srv is not a Survival object.')
if(is.null(X)){
s <- survival::survfit(srv~1)
frm <- data.frame(time = c(0,s$time),
n.risk = c(s$n.risk[1],s$n.risk),
n.event = c(0,s$n.event),
n.censor = c(0,s$n.censor),
surv = c(1,s$surv),
lower = c(s$lower[1],s$lower),
upper = c(s$upper[1],s$upper))
return(frm)
}
data.frame(srv= srv,X=X) %>%
dplyr::group_by(X) %>%
dplyr::do(s = survival::survfit(.$srv~1)) %>%
dplyr::do(data.frame(
Group = .$X,
time = c(0,.$s$time),
n.risk = c(.$s$n.risk[1],.$s$n.risk),
n.event = c(0,.$s$n.event),
n.censor = c(0,.$s$n.censor),
surv = c(1,.$s$surv),
lower = c(.$s$lower[1],.$s$lower),
upper = c(.$s$upper[1],.$s$upper))) %>%
as.data.frame()
}
|
set.seed( 44 )
library(mvtnorm)
library(fields)
library(Rcpp)
library(mclust)
library(kernlab)
library(ConsensusClusterPlus)
simu=function(s){
prob_glcm<-function(c,s=s,mc=30000){
mu<-c(2+c,14-c)
sigma<-matrix(s*c(1,-0.7,-0.7,1),nrow=2)
elip<-rmvnorm(mc,mu,sigma)
# par(xaxs='i',yaxs='i')
# plot(elip,xlim =c(0,16) ,ylim=c(0,16))
# abline(16,-1,col='red')
# abline(h=16);abline(h=15);abline(h=14);abline(h=13);abline(h=12);abline(h=11);abline(h=10);abline(h=9);
# abline(h=8);abline(h=7);abline(h=6);abline(h=5);abline(h=4);abline(h=3);abline(h=2);abline(h=1);abline(h=0)
# abline(v=16);abline(v=15);abline(v=14);abline(v=13);abline(v=12);abline(v=11);abline(v=10);abline(v=9);
# abline(v=0);abline(v=1);abline(v=2);abline(v=3);abline(v=4);abline(v=5);abline(v=6);abline(v=7);abline(v=8)
cell_count<-rep(0,16*16)
for (i in 1:mc)
{
for (m in 1:16) {
for (k in 16:1) {
if (( (m-1) <elip[i,1])&(elip[i,1]< m)&( (k-1) <elip[i,2])&(elip[i,2]< k)) {
cell_count[16-k+1+16*(m-1)]=cell_count[16-k+1+16*(m-1)]+1}
}
}
}
## -c(2:16,19:32,36:48,53:64,70:80,87:96,104:112,121:128,138:144,155:160,172:176,189:192,206:208,223:224,240)
z<-cell_count/sum(cell_count)
z_whole<-z[c(1,17,33,49,65,81,97,113,129,145,161,177,193,209,225,241,
17,18,34,50,66,82,98,114,130,146,162,178,194,210,226,242,
33,34,35,51,67,83,99,115,131,147,163,179,195,211,227,243,
49,50,51,52,68,84,100,116,132,148,164,180,196,212,228,244,
65,66,67,68,69,85,101,117,133,149,165,181,197,213,229,245,
81,82,83,84,85,86,102,118,134,150,166,182,198,214,230,246,
97,98,99,100,101,102,103,119,135,151,167,183,199,215,231,247,
113,114,115,116,117,118,119,120,136,152,168,184,200,216,232,248,
129,130,131,132,133,134,135,136,137,153,169,185,201,217,233,249,
145,146,147,148,149,150,151,152,153,154,170,186,202,218,234,250,
161,162,163,164,165,166,167,168,169,170,171,187,203,219,235,251,
177,178,179,180,181,182,183,184,185,186,187,188,204,220,236,252,
193,194,195,196,197,198,199,200,201,202,203,204,205,221,237,253,
209,210,211,212,213,214,215,216,217,218,219,220,221,222,238,254,
225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,255,
241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256)]
arg. <- expand.grid(c(0.5:15.5),c(15.5:0.5))
I = as.image( Z=z_whole, x=arg., grid=list(x=seq(0.5,15.5,1), y=seq(0.5,15.5,1)))
image(I)
smooth.I <- image.smooth(I, theta=1);
#################################################
### notice the order of this sommthed image ###
#################################################
den=c()
for (r in 1:16) {
for (w in 1:r) {
den=c(den,smooth.I$z[r,16-(w-1)])
}
}
prob<-den/sum(den)
return(prob)
}
prob1=prob_glcm(c=5,s=s)
prob2=prob_glcm(c=5.5,s=s)
prob3=prob_glcm(c=6,s=s)
prob4=prob_glcm(c=6.5,s=s)
prob5=prob_glcm(c=7,s=s)
glcm=matrix(0,nrow=20*5,ncol=136)
for (j in 1:20)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob1)
}
for (j in 21:40)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob2)
}
for (j in 41:60)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob3)
}
for (j in 61:80)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob4)
}
for (j in 81:100)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob5)
}
glcm
}
Z=simu(s=17)
Z_met=Z
T_met=nrow(Z_met)
n=ncol(Z_met)
X=apply(Z_met,1,sum)
X_met=X
sX_met=(X-mean(X))/sd(X)
R=array(data = NA,dim = c(2,n,T_met))
for (t in 1: nrow(Z_met)) R[,,t]=matrix(rep(c(1,sX_met[t]),times=n),byrow = FALSE,nrow=2,ncol=n)
############################################################################
########################## MCMC ########################
############################################################################
library(HI)
library(invgamma)
source('/gstore/scratch/u/lix233/RGSDP/sdp_functions_selfwriting_V12_cpp.R')
sourceCpp('/gstore/scratch/u/lix233/RGSDP/rgsdp.cpp')
D=read.csv('/gstore/scratch/u/lix233/RGSDP/D_16.csv',header=TRUE)
W=read.csv('/gstore/scratch/u/lix233/RGSDP/W_16.csv',header=TRUE)
N=20000;Burnin=N/2
Y_iter_met=Theta_iter_met=array(data=NA,dim = c(T_met,n,N))
try=matrix(0,nrow =T_met ,ncol = n)
for (i in 1:T_met){
for (j in 1:n){
if (Z_met[i,j]==0) {
try[i,j]=rnorm(1,mean=-10,sd=1)
} else {
try[i,j]=rnorm(1,mean=Z_met[i,j],sd=1)
}
}
}
g=update_Y(Z=Z_met,X=X_met,tau2=100,Theta = try,Beta =c(0.1,0.1),R)
sum(g==Inf)+sum(g==-Inf)
Theta_iter_met[,,1]=try
tau2_met=v_met=rho_met=sig2_met=rep(NA,N)
tau2_met[1]=50
v_met[1]=0.8
rho_met[1]=0.9
sig2_met[1]=10
# v_met=rep(1,N) # Fix v
av=bv=1
atau=0.0001 ;btau=0.0001
asig=0.0001 ;bsig=0.0001
Betam=c(0,0);Sigma_m=matrix(c(10^5,0,0,10^5),nrow=2,ncol=2)
Beta_iter_met=matrix(NA,nrow=N,ncol=nrow(R[,,1]))
Beta_iter_met[1,]=c(40,20)
for (iter in 2:N) {
Y_iter_met[,,iter]=update_Y(Z_met,X_met,tau2_met[iter-1],Theta_iter_met[,,iter-1],Beta_iter_met[iter-1,],R)
Theta_iter_met[,,iter]=update_theta(as.vector(X_met),Y_iter_met[,,iter],as.matrix(D),as.matrix(W),rho_met[iter-1],Theta_iter_met[,,iter-1],sig2_met[iter-1],tau2_met[iter-1],v_met[iter-1],Beta_iter_met[iter-1,],R)
Beta_iter_met[iter,]=update_Beta(Betam,Sigma_m,tau2_met[iter-1],X_met,Y_iter_met[,,iter],Theta_iter_met[,,iter],R)
tau2_met[iter] = update_tau2(X_met,Y_iter_met[,,iter],Theta_iter_met[,,iter],atau,btau,Beta_iter_met[iter,],R)
sig2_met[iter]= update_sig2(asig,bsig,D,W,rho_met[iter-1],Theta_iter_met[,,iter])
rho_met[iter] = update_rho(D,W,Theta_iter_met[,,iter],sig2_met[iter])
v_met[iter]=update_v(Z_met,v_met[iter-1],Tstar=nrow(unique.matrix(Theta_iter_met[,,iter])),av,bv)
}
library(coda)
mcmc_beta=mcmc(Beta_iter_met[(1+Burnin):N,])
pnorm(abs(geweke.diag(mcmc_beta)$z),lower.tail=FALSE)*2
mcmc_rho=mcmc(rho_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_rho)$z),lower.tail=FALSE)*2
mcmc_sig2=mcmc(sig2_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_sig2)$z),lower.tail=FALSE)*2
mcmc_tau2=mcmc(tau2_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_tau2)$z),lower.tail=FALSE)*2
mcmc_v=mcmc(v_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_v)$z),lower.tail=FALSE)*2
Theta_ave=Theta_sum=matrix(0,nrow=nrow(Theta_iter_met[,,1]),ncol=ncol(Theta_iter_met[,,1]))
for (i in (Burnin+1):N) {
Theta_sum=Theta_sum+Theta_iter_met[,,i]
}
Theta_ave=Theta_sum/(N-Burnin)
library('NbClust')
NbClust(Theta_ave,distance='euclidean',method='ward.D2',index='kl')
HRGSDP=NbClust(Theta_ave,distance='euclidean',method='ward.D2',index='kl')$Best.partition
glcm_whole=Z[,c(1,2,4,7,11,16,22,29,37,46,56,67,79,92,106,121,
2,3,5,8,12,17,23,30,38,47,57,68,80,93,107,122,
4,5,6,9,13,18,24,31,39,48,58,69,81,94,108,123,
7,8,9,10,14,19,25,32,40,49,59,70,82,95,109,124,
11,12,13,14,15,20,26,33,41,50,60,71,83,96,110,125,
16,17,18,19,20,21,27,34,42,51,61,72,84,97,111,126,
22,23,24,25,26,27,28,35,43,52,62,73,85,98,112,127,
29,30,31,32,33,34,35,36,44,53,63,74,86,99,113,128,
37,38,39,40,41,42,43,44,45,54,64,75,87,100,114,129,
46,47,48,49,50,51,52,53,54,55,65,76,88,101,115,130,
56,57,58,59,60,61,62,63,64,65,66,77,89,102,116,131,
67,68,69,70,71,72,73,74,75,76,77,78,90,103,117,132,
79,80,81,82,83,84,85,86,87,88,89,90,91,104,118,133,
92,93,94,95,96,97,98,99,100,101,102,103,104,105,119,134,
106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,135,
121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136)]
source('/gstore/scratch/u/lix233/RGSDP/cal_stat.R')
features=cal_stat(glcm_whole)
GMM=Mclust(features,5)
my.dist <- function(x) dist(x, method='euclidean')
my.hclust <- function(d) hclust(d, method='ward.D2')
HC<-cutree(my.hclust(my.dist(data.matrix(features))),k=5)
KM=kmeans(features,5)
SC=specc(features,5)
CO <- ConsensusClusterPlus(t(features),maxK=9,reps=100,pItem=0.90, pFeature=1,
clusterAlg='hc',distance='euclidean',plot=FALSE)
CO <- CO[[5]]$consensusClass
aa <- table(rep(1:5,each=20), CO)
bb <- table(rep(1:5,each=20), GMM$classification)
cc <- table(rep(1:5,each=20), HC)
dd <- table(rep(1:5,each=20), KM$cluster)
ee <- table(rep(1:5,each=20), SC)
ff <- table(rep(1:5,each=20), HRGSDP)
res_FeaCO=c(chisq.test(aa,correct = TRUE)$statistic,ncol(aa),error_rate(aa), 'FeaCO')
res_FeaGMM=c(chisq.test(bb,correct = TRUE)$statistic,ncol(bb),error_rate(bb), 'FeaGMM')
res_FeaHC=c(chisq.test(cc,correct = TRUE)$statistic,ncol(cc),error_rate(cc), 'FeaHC')
res_FeaKM=c(chisq.test(dd,correct = TRUE)$statistic,ncol(dd),error_rate(dd), 'FeaKM')
res_FeaSC=c(chisq.test(ee,correct = TRUE)$statistic,ncol(ee),error_rate(ee), 'FeaSC')
res_HRGSDP=c(chisq.test(ff,correct = TRUE)$statistic,ncol(ff),error_rate(ff), 'HRGSDP')
xx = rbind(res_FeaCO, res_FeaGMM, res_FeaHC, res_FeaKM, res_FeaSC, res_HRGSDP)
colnames(xx) = c('pearson.chi.sq', 'nunber of clusters', 'error.rate', 'method')
xx = as.data.frame(xx)
print(xx)
| /s=17/simu_44.R | no_license | mguindanigroup/Radiomics-Hierarchical-Rounded-Gaussian-Spatial-Dirichlet-Process | R | false | false | 9,293 | r | set.seed( 44 )
library(mvtnorm)
library(fields)
library(Rcpp)
library(mclust)
library(kernlab)
library(ConsensusClusterPlus)
simu=function(s){
prob_glcm<-function(c,s=s,mc=30000){
mu<-c(2+c,14-c)
sigma<-matrix(s*c(1,-0.7,-0.7,1),nrow=2)
elip<-rmvnorm(mc,mu,sigma)
# par(xaxs='i',yaxs='i')
# plot(elip,xlim =c(0,16) ,ylim=c(0,16))
# abline(16,-1,col='red')
# abline(h=16);abline(h=15);abline(h=14);abline(h=13);abline(h=12);abline(h=11);abline(h=10);abline(h=9);
# abline(h=8);abline(h=7);abline(h=6);abline(h=5);abline(h=4);abline(h=3);abline(h=2);abline(h=1);abline(h=0)
# abline(v=16);abline(v=15);abline(v=14);abline(v=13);abline(v=12);abline(v=11);abline(v=10);abline(v=9);
# abline(v=0);abline(v=1);abline(v=2);abline(v=3);abline(v=4);abline(v=5);abline(v=6);abline(v=7);abline(v=8)
cell_count<-rep(0,16*16)
for (i in 1:mc)
{
for (m in 1:16) {
for (k in 16:1) {
if (( (m-1) <elip[i,1])&(elip[i,1]< m)&( (k-1) <elip[i,2])&(elip[i,2]< k)) {
cell_count[16-k+1+16*(m-1)]=cell_count[16-k+1+16*(m-1)]+1}
}
}
}
## -c(2:16,19:32,36:48,53:64,70:80,87:96,104:112,121:128,138:144,155:160,172:176,189:192,206:208,223:224,240)
z<-cell_count/sum(cell_count)
z_whole<-z[c(1,17,33,49,65,81,97,113,129,145,161,177,193,209,225,241,
17,18,34,50,66,82,98,114,130,146,162,178,194,210,226,242,
33,34,35,51,67,83,99,115,131,147,163,179,195,211,227,243,
49,50,51,52,68,84,100,116,132,148,164,180,196,212,228,244,
65,66,67,68,69,85,101,117,133,149,165,181,197,213,229,245,
81,82,83,84,85,86,102,118,134,150,166,182,198,214,230,246,
97,98,99,100,101,102,103,119,135,151,167,183,199,215,231,247,
113,114,115,116,117,118,119,120,136,152,168,184,200,216,232,248,
129,130,131,132,133,134,135,136,137,153,169,185,201,217,233,249,
145,146,147,148,149,150,151,152,153,154,170,186,202,218,234,250,
161,162,163,164,165,166,167,168,169,170,171,187,203,219,235,251,
177,178,179,180,181,182,183,184,185,186,187,188,204,220,236,252,
193,194,195,196,197,198,199,200,201,202,203,204,205,221,237,253,
209,210,211,212,213,214,215,216,217,218,219,220,221,222,238,254,
225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,255,
241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256)]
arg. <- expand.grid(c(0.5:15.5),c(15.5:0.5))
I = as.image( Z=z_whole, x=arg., grid=list(x=seq(0.5,15.5,1), y=seq(0.5,15.5,1)))
image(I)
smooth.I <- image.smooth(I, theta=1);
#################################################
### notice the order of this sommthed image ###
#################################################
den=c()
for (r in 1:16) {
for (w in 1:r) {
den=c(den,smooth.I$z[r,16-(w-1)])
}
}
prob<-den/sum(den)
return(prob)
}
prob1=prob_glcm(c=5,s=s)
prob2=prob_glcm(c=5.5,s=s)
prob3=prob_glcm(c=6,s=s)
prob4=prob_glcm(c=6.5,s=s)
prob5=prob_glcm(c=7,s=s)
glcm=matrix(0,nrow=20*5,ncol=136)
for (j in 1:20)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob1)
}
for (j in 21:40)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob2)
}
for (j in 41:60)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob3)
}
for (j in 61:80)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob4)
}
for (j in 81:100)
{
t<-round(runif(1,500,20000),0)
glcm[j,]=round(t*prob5)
}
glcm
}
Z=simu(s=17)
Z_met=Z
T_met=nrow(Z_met)
n=ncol(Z_met)
X=apply(Z_met,1,sum)
X_met=X
sX_met=(X-mean(X))/sd(X)
R=array(data = NA,dim = c(2,n,T_met))
for (t in 1: nrow(Z_met)) R[,,t]=matrix(rep(c(1,sX_met[t]),times=n),byrow = FALSE,nrow=2,ncol=n)
############################################################################
########################## MCMC ########################
############################################################################
library(HI)
library(invgamma)
source('/gstore/scratch/u/lix233/RGSDP/sdp_functions_selfwriting_V12_cpp.R')
sourceCpp('/gstore/scratch/u/lix233/RGSDP/rgsdp.cpp')
D=read.csv('/gstore/scratch/u/lix233/RGSDP/D_16.csv',header=TRUE)
W=read.csv('/gstore/scratch/u/lix233/RGSDP/W_16.csv',header=TRUE)
N=20000;Burnin=N/2
Y_iter_met=Theta_iter_met=array(data=NA,dim = c(T_met,n,N))
try=matrix(0,nrow =T_met ,ncol = n)
for (i in 1:T_met){
for (j in 1:n){
if (Z_met[i,j]==0) {
try[i,j]=rnorm(1,mean=-10,sd=1)
} else {
try[i,j]=rnorm(1,mean=Z_met[i,j],sd=1)
}
}
}
g=update_Y(Z=Z_met,X=X_met,tau2=100,Theta = try,Beta =c(0.1,0.1),R)
sum(g==Inf)+sum(g==-Inf)
Theta_iter_met[,,1]=try
tau2_met=v_met=rho_met=sig2_met=rep(NA,N)
tau2_met[1]=50
v_met[1]=0.8
rho_met[1]=0.9
sig2_met[1]=10
# v_met=rep(1,N) # Fix v
av=bv=1
atau=0.0001 ;btau=0.0001
asig=0.0001 ;bsig=0.0001
Betam=c(0,0);Sigma_m=matrix(c(10^5,0,0,10^5),nrow=2,ncol=2)
Beta_iter_met=matrix(NA,nrow=N,ncol=nrow(R[,,1]))
Beta_iter_met[1,]=c(40,20)
for (iter in 2:N) {
Y_iter_met[,,iter]=update_Y(Z_met,X_met,tau2_met[iter-1],Theta_iter_met[,,iter-1],Beta_iter_met[iter-1,],R)
Theta_iter_met[,,iter]=update_theta(as.vector(X_met),Y_iter_met[,,iter],as.matrix(D),as.matrix(W),rho_met[iter-1],Theta_iter_met[,,iter-1],sig2_met[iter-1],tau2_met[iter-1],v_met[iter-1],Beta_iter_met[iter-1,],R)
Beta_iter_met[iter,]=update_Beta(Betam,Sigma_m,tau2_met[iter-1],X_met,Y_iter_met[,,iter],Theta_iter_met[,,iter],R)
tau2_met[iter] = update_tau2(X_met,Y_iter_met[,,iter],Theta_iter_met[,,iter],atau,btau,Beta_iter_met[iter,],R)
sig2_met[iter]= update_sig2(asig,bsig,D,W,rho_met[iter-1],Theta_iter_met[,,iter])
rho_met[iter] = update_rho(D,W,Theta_iter_met[,,iter],sig2_met[iter])
v_met[iter]=update_v(Z_met,v_met[iter-1],Tstar=nrow(unique.matrix(Theta_iter_met[,,iter])),av,bv)
}
library(coda)
mcmc_beta=mcmc(Beta_iter_met[(1+Burnin):N,])
pnorm(abs(geweke.diag(mcmc_beta)$z),lower.tail=FALSE)*2
mcmc_rho=mcmc(rho_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_rho)$z),lower.tail=FALSE)*2
mcmc_sig2=mcmc(sig2_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_sig2)$z),lower.tail=FALSE)*2
mcmc_tau2=mcmc(tau2_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_tau2)$z),lower.tail=FALSE)*2
mcmc_v=mcmc(v_met[(1+Burnin):N])
pnorm(abs(geweke.diag(mcmc_v)$z),lower.tail=FALSE)*2
Theta_ave=Theta_sum=matrix(0,nrow=nrow(Theta_iter_met[,,1]),ncol=ncol(Theta_iter_met[,,1]))
for (i in (Burnin+1):N) {
Theta_sum=Theta_sum+Theta_iter_met[,,i]
}
Theta_ave=Theta_sum/(N-Burnin)
library('NbClust')
NbClust(Theta_ave,distance='euclidean',method='ward.D2',index='kl')
HRGSDP=NbClust(Theta_ave,distance='euclidean',method='ward.D2',index='kl')$Best.partition
glcm_whole=Z[,c(1,2,4,7,11,16,22,29,37,46,56,67,79,92,106,121,
2,3,5,8,12,17,23,30,38,47,57,68,80,93,107,122,
4,5,6,9,13,18,24,31,39,48,58,69,81,94,108,123,
7,8,9,10,14,19,25,32,40,49,59,70,82,95,109,124,
11,12,13,14,15,20,26,33,41,50,60,71,83,96,110,125,
16,17,18,19,20,21,27,34,42,51,61,72,84,97,111,126,
22,23,24,25,26,27,28,35,43,52,62,73,85,98,112,127,
29,30,31,32,33,34,35,36,44,53,63,74,86,99,113,128,
37,38,39,40,41,42,43,44,45,54,64,75,87,100,114,129,
46,47,48,49,50,51,52,53,54,55,65,76,88,101,115,130,
56,57,58,59,60,61,62,63,64,65,66,77,89,102,116,131,
67,68,69,70,71,72,73,74,75,76,77,78,90,103,117,132,
79,80,81,82,83,84,85,86,87,88,89,90,91,104,118,133,
92,93,94,95,96,97,98,99,100,101,102,103,104,105,119,134,
106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,135,
121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136)]
source('/gstore/scratch/u/lix233/RGSDP/cal_stat.R')
features=cal_stat(glcm_whole)
GMM=Mclust(features,5)
my.dist <- function(x) dist(x, method='euclidean')
my.hclust <- function(d) hclust(d, method='ward.D2')
HC<-cutree(my.hclust(my.dist(data.matrix(features))),k=5)
KM=kmeans(features,5)
SC=specc(features,5)
CO <- ConsensusClusterPlus(t(features),maxK=9,reps=100,pItem=0.90, pFeature=1,
clusterAlg='hc',distance='euclidean',plot=FALSE)
CO <- CO[[5]]$consensusClass
aa <- table(rep(1:5,each=20), CO)
bb <- table(rep(1:5,each=20), GMM$classification)
cc <- table(rep(1:5,each=20), HC)
dd <- table(rep(1:5,each=20), KM$cluster)
ee <- table(rep(1:5,each=20), SC)
ff <- table(rep(1:5,each=20), HRGSDP)
res_FeaCO=c(chisq.test(aa,correct = TRUE)$statistic,ncol(aa),error_rate(aa), 'FeaCO')
res_FeaGMM=c(chisq.test(bb,correct = TRUE)$statistic,ncol(bb),error_rate(bb), 'FeaGMM')
res_FeaHC=c(chisq.test(cc,correct = TRUE)$statistic,ncol(cc),error_rate(cc), 'FeaHC')
res_FeaKM=c(chisq.test(dd,correct = TRUE)$statistic,ncol(dd),error_rate(dd), 'FeaKM')
res_FeaSC=c(chisq.test(ee,correct = TRUE)$statistic,ncol(ee),error_rate(ee), 'FeaSC')
res_HRGSDP=c(chisq.test(ff,correct = TRUE)$statistic,ncol(ff),error_rate(ff), 'HRGSDP')
xx = rbind(res_FeaCO, res_FeaGMM, res_FeaHC, res_FeaKM, res_FeaSC, res_HRGSDP)
colnames(xx) = c('pearson.chi.sq', 'nunber of clusters', 'error.rate', 'method')
xx = as.data.frame(xx)
print(xx)
|
.trapz <-
function(x,y){
n <- length(x)
return(sum((y[1:(n-1)]+y[2:n])/2*(x[2:n]-x[1:(n-1)])))
}
.intersection_onecolumn <-
function(alpha, SSN1, SSN2, nrow_S1, nrow_S2, Ncol, .quantile_intersection){
SP_inters <- .quantile_intersection(vec1 = SSN1, vec2 = SSN2, a = alpha/2, b = 1 - alpha/2, n = nrow_S1)
vol_intersect <- (SP_inters[6])
vol_B <- (SP_inters[3])
r <- 1
if (min(SP_inters[4] == SP_inters[1]) == 0 | min(SP_inters[5] == SP_inters[2]) == 0){
if (vol_intersect < vol_B) {r <- vol_intersect/vol_B}
if (vol_B == 0) {r <- 0}
}
return(r)
}
.intersection_severalcol <-
function(alpha,SSN1,SSN2,nrow_S1,nrow_S2,Ncol, .quantile_intersection){
SP_inters<-mapply(.quantile_intersection, vec1 = SSN1, vec2 = SSN2, MoreArgs = list(a=((1-(1-alpha)^(1/ncol(SSN1)))/2), b=(1-(1-(1-alpha)^(1/ncol(SSN1)))/2),n=nrow_S1))
product<-prod(SP_inters[6,])
vol_intersect<-c(product,mean(SP_inters[6,]),product^{1/length(SP_inters[6,])})
product<-prod(SP_inters[3,])
vol_B<-c(product,mean(SP_inters[3,]),product^{1/length(SP_inters[3,])})
r<-c(1,1,1)
if(min(SP_inters[4,]==SP_inters[1,])==0 | min(SP_inters[5,]==SP_inters[2,])==0){
r[vol_intersect<vol_B]<-vol_intersect[vol_intersect<vol_B]/vol_B[vol_intersect<vol_B]
r[vol_B==0]<-0
}
return(r)
}
.portionAinB_coordinates_full <-
function(S1,S2,steps=101 ){
nt<-ncol(S1)
integral_coord<-rep(0,length=nt)
portionAinB_function<-function(x1,x2,steps){
r<-.portionAinB_full_onecolumn(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$integral_approx)
}
portionAinB_function2<-function(x1,x2,steps){
r<-.portionAinB_full_onecolumn(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$overlap)
}
integral_coord<-mapply(portionAinB_function, x1=S1, x2=S2, MoreArgs =list(steps=steps))
plot_data_overlap<-mapply(portionAinB_function2, x1=S1, x2=S2, MoreArgs =list(steps=steps))
alpha_grid<-seq(0,1,length=steps)[1:(steps-1)]
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_data_overlap=plot_data_overlap)
return(erg)
}
.portionAinB_coordinates_full_dim1 <-
function(S1,S2,steps=101 ){
nt<-1
integral_coord<-rep(0,length=nt)
r<-.portionAinB_full_onecolumn(data.frame(v1=S1) ,data.frame(v1=S2),steps=steps )
integral_coord<-r$integral_approx
plot_data_overlap<-r$overlap
alpha_grid<-seq(0,1,length=steps)[1:(steps-1)]
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_data_overlap=plot_data_overlap)
return(erg)
}
.portionAinB_full_onecolumn <-
function (S1, S2, steps = 101) {
S <- rbind(S1, S2)
Ncol <- ncol(S1)
alpha_grid <- seq(0, 1, length = steps)
Spans <- data.frame(trait_nr = 1:Ncol, min = min(S, na.rm = TRUE), max = max(S, na.rm = TRUE))
ab <- Spans$max - Spans$min
SSN <- (S - Spans$min)/(ab)
SSN[, ab == 0] <- 0.5
nrow_S1 <- nrow(S1)
nrow_S2 <- nrow(S2)
z <- mapply(.intersection_onecolumn, alpha = alpha_grid, MoreArgs = list(SSN1 = SSN[1:nrow_S1, ], SSN2 = SSN[(nrow_S1 + 1):(nrow_S1 + nrow_S2), ], nrow_S1 = nrow_S1, nrow_S2 = nrow_S2, Ncol = Ncol, .quantile_intersection = .quantile_intersection))
integral_approx <- c(prod = .trapz(alpha_grid, z))
erg <- list(alpha_grid = alpha_grid, overlap = z, integral_approx = integral_approx)
return(erg)
}
.portionAinB2_full <-
function(S1,S2,steps=101,alpha_grid){
steps0<-steps
alpha_grid0<-alpha_grid
.portionAinB2_full_severalcol(S1,S2,steps=steps0,alpha_grid=alpha_grid0)
}
.portionAinB2_full_dim1 <-
function(S1,S2,steps=101,alpha_grid){
steps0<-steps
alpha_grid0<-alpha_grid
.portionAinB2_full_severalcol_dim1(S1,S2,steps=steps0,alpha_grid=alpha_grid0)
}
.portionAinB2_full_severalcol_dim1 <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)[1:(steps-1)]){
S<-c(S1,S2)
alpha_grid<-seq(0,1,length=steps)
Ncol<-1
ab<-max(S)-min(S)
SSN<-t((t(S)-min(S))/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
nrow_S1<-length(S1)
nrow_S2<-length(S2)
z<-mapply(.intersection_onecolumn, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow_S1,], SSN2=SSN[(nrow_S1+1):(nrow_S1+nrow_S2),],nrow_S1=nrow_S1,nrow_S2=nrow_S2,Ncol=Ncol,.quantile_intersection=.quantile_intersection))
integral_approx<-c(prod=.trapz(seq(0,1,length=steps), z),mean=.trapz(seq(0,1,length=steps),z),gmean=.trapz(seq(0,1,length=steps),z))
plot_data_prod<-z
erg<-list(alpha_grid=seq(0,1,length=steps)[1:(steps-1)],overlap=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.portionAinB2_full_severalcol <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)[1:(steps-1)]){
S<-rbind(S1,S2)
alpha_grid<-seq(0,1,length=steps)
Ncol<-ncol(S1)
Spans<-data.frame(trait_nr=1:Ncol,min=matrix(mapply(min, S, MoreArgs = list(na.rm = TRUE))),max=matrix(mapply(max, S, MoreArgs = list(na.rm = TRUE))))
ab<-Spans$max-Spans$min
SSN<-t((t(S)-Spans$min)/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
nrow_S1<-nrow(S1)
nrow_S2<-nrow(S2)
z<-mapply(.intersection_severalcol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow_S1,], SSN2=SSN[(nrow_S1+1):(nrow_S1+nrow_S2),],nrow_S1=nrow_S1,nrow_S2=nrow_S2,Ncol=Ncol,.quantile_intersection=.quantile_intersection))
integral_approx<-c(prod=.trapz(seq(0,1,length=steps), z[1,]),mean=.trapz(seq(0,1,length=steps),z[2,]),gmean=.trapz(seq(0,1,length=steps),z[3,]))
plot_data_prod<-z[1,]
erg<-list(alpha_grid=seq(0,1,length=steps)[1:(steps-1)],overlap=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.quantile_intersection <-
function(vec1,vec2,a,b,n){
x<-c( quantile(vec1, probs = c(a,b), na.rm = TRUE), quantile(vec2, probs = c(a,b), na.rm = TRUE) )
x<-c(x,x[4]-x[3])
x[5]<-ifelse(x[5]<=0,0,x[5])
r<-c(max(x[c(1,3)]),min(x[c(2,4)]))
r<-c(x[3:5],r,r[2]-r[1])
r[6]<-ifelse(r[6]<=0,0,r[6])
return(r)
}
.volume_onecol <-
function(alpha,SSN1){
SP1<-quantile(SSN1,probs=c(alpha/2,1-alpha/2),na.rm = TRUE)
vol<-(SP1[2]-SP1[1])
return(vol)
}
.volume_severalcol <-
function(alpha,SSN1){
alpha<-(1-(1-alpha)^(1/ncol(SSN1)))
a<-alpha/2
b<-1-alpha/2
SP1<-mapply(quantile, SSN1, MoreArgs = list(probs=c(a,b),na.rm=TRUE))
product<-prod(SP1[2,]-SP1[1,])
vol<-c(prod=product,mean=mean(SP1[2,]-SP1[1,]),gmean=product^{1/length(SP1[2,]-SP1[1,])})
return(vol)
}
.volumeA_coordinates_full_dim1 <-
function(S1,S2,steps=101 ){
nt<-1
names(S2)<-"v1"
r<-.volumeA_full_onecol(data.frame(v1=S1), data.frame(v1=S2), steps=steps)
integral_coord<-r$integral_approx
plot_volume<-r$volume
alpha_grid<-seq(0,1,length=steps)
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_volume=plot_volume)
return(erg)
}
.volumeA_coordinates_full <-
function(S1,S2,steps=101 ){
nt<-ncol(S1)
volumeA_function<-function(x1,x2,steps){
r<-.volumeA_full_onecol(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$integral_approx)
}
volumeA_function2<-function(x1,x2,steps){
r<-.volumeA_full_onecol(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$volume)
}
integral_coord<-mapply(volumeA_function, x1=S1, x2=S2, MoreArgs =list(steps=steps))
plot_volume<-mapply(volumeA_function2, x1=S1, x2=S2, MoreArgs =list(steps=steps))
alpha_grid<-seq(0,1,length=steps)
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_volume=plot_volume)
return(erg)
}
.volumeA_full_onecol <-
function(S1,S2,steps=101){
S<-rbind(S1,S2)
Ncol<-ncol(S1)
alpha_grid<-seq(0,1,length=steps)
Spans<-data.frame(trait_nr=1:Ncol,min=min(S,na.rm = TRUE),max=max(S,na.rm = TRUE))
ab<-Spans$max-Spans$min
SSN<-(S-Spans$min)/(ab)
SSN[,ab==0]<-0.5
z<-mapply(.volume_onecol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow(S1),]))
z<-1/(1-alpha_grid[-length(alpha_grid)])*z[-length(alpha_grid)]
z <- ifelse(z <= 1, z, 1)
integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z))
erg<-list(alpha_grid=alpha_grid,volume=z,integral_approx=integral_approx)
return(erg)
}
.volumeA2_full <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
steps0<-steps
alpha0_grid<-alpha_grid
.volumeA2_full_severalcol(S1,S2,steps=steps0,alpha_grid=alpha0_grid )
}
.volumeA2_full_dim1 <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
steps0<-steps
alpha0_grid<-alpha_grid
.volumeA2_full_severalcol_dim1(S1,S2,steps=steps0,alpha_grid=alpha0_grid )
}
.volumeA2_full_severalcol_dim1 <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
S<-c(S1,S2)
Ncol<-1
ab<-max(S)-min(S)
SSN<-t((t(S)-min(S))/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
z<-mapply(.volume_onecol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN))
z<-rbind(1/(1-alpha_grid[-length(alpha_grid)])*z[-length(alpha_grid)])
z <- ifelse(z <= 1, z, 1)
integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z),mean=.trapz(alpha_grid[-length(alpha_grid)],z),gmean=.trapz(alpha_grid[-length(alpha_grid)],z))
plot_data_prod<-z
erg<-list(alpha_grid=seq(0,1,length=steps),volume=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.volumeA2_full_severalcol <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
S<-rbind(S1,S2)
Ncol<-ncol(S1)
Spans<-data.frame(trait_nr=1:Ncol,min=matrix(mapply(min, S, MoreArgs = list(na.rm = TRUE))),max=matrix(mapply(max, S, MoreArgs = list(na.rm = TRUE))))
ab<-Spans$max-Spans$min
SSN<-t((t(S)-Spans$min)/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
z<-mapply(.volume_severalcol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow(S1),]))
z<-rbind(1/(1-alpha_grid[-length(alpha_grid)])*z[1,][-length(alpha_grid)],1/(1-alpha_grid[-length(alpha_grid)])*z[2,][-length(alpha_grid)],1/(1-alpha_grid[-length(alpha_grid)])*z[3,][-length(alpha_grid)])
z <- ifelse(z <= 1, z, 1)
integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z[1,]),mean=.trapz(alpha_grid[-length(alpha_grid)],z[2,]),gmean=.trapz(alpha_grid[-length(alpha_grid)],z[3,]))
plot_data_prod<-z[1,]
erg<-list(alpha_grid=seq(0,1,length=steps),volume=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.trpca <- function(data, va){ # data = dataset as for dynRB, va = how much variance (0-1) should included axes explain
PCA <- prcomp(data[,-1])
vars <- apply(PCA$x, 2, var)
prop <- cumsum(vars / sum(vars))
k <- which(prop >= va)[1]
k <- ifelse(k==1, 2, k)
data1 <- data.frame(data[,1], PCA$x[,1:k])
colnames(data1)[1] <- "Species"
return(data1)
}
.getVarianceEstimate <-function(x,y){
# X
x_smallerM = x[1:round(length(x)/2 + 0.1)] #x[x < median(x)]
x_greaterM = x[round(length(x)/2+1.1):length(x)] #x[x >= median(x)]
n = as.numeric(length(x))
k = as.numeric(length(x_smallerM))
x_smallerM_ranks = rank(x_smallerM)
x_greaterM_ranks = rank(x_greaterM)
# Y
y_smallerM = y[1:round(length(y)/2 +0.1)] # y[y < median(y)]
y_greaterM = y[round(length(y)/2+1.1):length(y)]# y[y >= median(y)]
m = as.numeric(length(y))
l = as.numeric(length(y_smallerM))
y_smallerM_ranks = rank(y_smallerM)
y_greaterM_ranks = rank(y_greaterM)
xy_smallerM_ranks = rank(c(x_smallerM,y_smallerM))[1:k]
yx_smallerM_ranks = rank(c(y_smallerM,x_smallerM))[1:l]
xy_greaterM_ranks = rank(c(x_greaterM,y_greaterM))[1:(n-k)]
yx_greaterM_ranks = rank(c(y_greaterM,x_greaterM))[1:(m-l)]
s2_X1 = 1/(l^2*(k-1)) * sum((xy_smallerM_ranks - x_smallerM_ranks - mean(xy_smallerM_ranks) + (k+1)/2)^2)
s2_X2 = 1/((m-l)^2*(n-k-1)) * sum((xy_greaterM_ranks - x_greaterM_ranks - mean(xy_greaterM_ranks) + (n-k+1)/2)^2)
s2_Y1 = 1/(k^2*(l-1)) * sum((yx_smallerM_ranks - y_smallerM_ranks - mean(yx_smallerM_ranks) + (l+1)/2)^2)
s2_Y2 = 1/((n-k)^2*(m-l-1)) * sum((yx_greaterM_ranks - y_greaterM_ranks - mean(yx_greaterM_ranks) + (m-l+1)/2)^2)
s2_2 = (l+k)*(s2_X1/k + s2_Y1/l) + (n+m-l-k)*(s2_X2/(n-k) + s2_Y2/(m-l))
return(s2_2)
}
.getRankedSingleOverlapIndex <- function(x,y){
x_length = as.numeric(length(x))
if(round(x_length/2)==x_length/2){
k=x_length/2
}else{
k=(x_length+1)/2
}
y_length = as.numeric(length(y))
x = sort(x)
xy_ranks = rank(c(x,y))
x_rank = xy_ranks[1:x_length]
y_rank = xy_ranks[(x_length+1):(x_length+y_length)]
rank_gtm = sum(x_rank[(k+1) : x_length])
rank_stm = sum(x_rank[1:k])
K= sum(rank(x)[1:k])
c = 2/((x_length)*(y_length)) * ( - x_length*(x_length+1) + K*4)
overlap_ranked = 2*(rank_gtm - rank_stm)/((x_length)*(y_length)) + c/2
return(overlap_ranked)
}
.geo.mean <- function (x){
n<-length(x)
mittelwert<-prod(x)^(1/n)
return (mittelwert)
} | /R/dynRB-internal.R | no_license | cran/dynRB | R | false | false | 14,099 | r | .trapz <-
function(x,y){
n <- length(x)
return(sum((y[1:(n-1)]+y[2:n])/2*(x[2:n]-x[1:(n-1)])))
}
.intersection_onecolumn <-
function(alpha, SSN1, SSN2, nrow_S1, nrow_S2, Ncol, .quantile_intersection){
SP_inters <- .quantile_intersection(vec1 = SSN1, vec2 = SSN2, a = alpha/2, b = 1 - alpha/2, n = nrow_S1)
vol_intersect <- (SP_inters[6])
vol_B <- (SP_inters[3])
r <- 1
if (min(SP_inters[4] == SP_inters[1]) == 0 | min(SP_inters[5] == SP_inters[2]) == 0){
if (vol_intersect < vol_B) {r <- vol_intersect/vol_B}
if (vol_B == 0) {r <- 0}
}
return(r)
}
.intersection_severalcol <-
function(alpha,SSN1,SSN2,nrow_S1,nrow_S2,Ncol, .quantile_intersection){
SP_inters<-mapply(.quantile_intersection, vec1 = SSN1, vec2 = SSN2, MoreArgs = list(a=((1-(1-alpha)^(1/ncol(SSN1)))/2), b=(1-(1-(1-alpha)^(1/ncol(SSN1)))/2),n=nrow_S1))
product<-prod(SP_inters[6,])
vol_intersect<-c(product,mean(SP_inters[6,]),product^{1/length(SP_inters[6,])})
product<-prod(SP_inters[3,])
vol_B<-c(product,mean(SP_inters[3,]),product^{1/length(SP_inters[3,])})
r<-c(1,1,1)
if(min(SP_inters[4,]==SP_inters[1,])==0 | min(SP_inters[5,]==SP_inters[2,])==0){
r[vol_intersect<vol_B]<-vol_intersect[vol_intersect<vol_B]/vol_B[vol_intersect<vol_B]
r[vol_B==0]<-0
}
return(r)
}
.portionAinB_coordinates_full <-
function(S1,S2,steps=101 ){
nt<-ncol(S1)
integral_coord<-rep(0,length=nt)
portionAinB_function<-function(x1,x2,steps){
r<-.portionAinB_full_onecolumn(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$integral_approx)
}
portionAinB_function2<-function(x1,x2,steps){
r<-.portionAinB_full_onecolumn(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$overlap)
}
integral_coord<-mapply(portionAinB_function, x1=S1, x2=S2, MoreArgs =list(steps=steps))
plot_data_overlap<-mapply(portionAinB_function2, x1=S1, x2=S2, MoreArgs =list(steps=steps))
alpha_grid<-seq(0,1,length=steps)[1:(steps-1)]
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_data_overlap=plot_data_overlap)
return(erg)
}
.portionAinB_coordinates_full_dim1 <-
function(S1,S2,steps=101 ){
nt<-1
integral_coord<-rep(0,length=nt)
r<-.portionAinB_full_onecolumn(data.frame(v1=S1) ,data.frame(v1=S2),steps=steps )
integral_coord<-r$integral_approx
plot_data_overlap<-r$overlap
alpha_grid<-seq(0,1,length=steps)[1:(steps-1)]
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_data_overlap=plot_data_overlap)
return(erg)
}
.portionAinB_full_onecolumn <-
function (S1, S2, steps = 101) {
S <- rbind(S1, S2)
Ncol <- ncol(S1)
alpha_grid <- seq(0, 1, length = steps)
Spans <- data.frame(trait_nr = 1:Ncol, min = min(S, na.rm = TRUE), max = max(S, na.rm = TRUE))
ab <- Spans$max - Spans$min
SSN <- (S - Spans$min)/(ab)
SSN[, ab == 0] <- 0.5
nrow_S1 <- nrow(S1)
nrow_S2 <- nrow(S2)
z <- mapply(.intersection_onecolumn, alpha = alpha_grid, MoreArgs = list(SSN1 = SSN[1:nrow_S1, ], SSN2 = SSN[(nrow_S1 + 1):(nrow_S1 + nrow_S2), ], nrow_S1 = nrow_S1, nrow_S2 = nrow_S2, Ncol = Ncol, .quantile_intersection = .quantile_intersection))
integral_approx <- c(prod = .trapz(alpha_grid, z))
erg <- list(alpha_grid = alpha_grid, overlap = z, integral_approx = integral_approx)
return(erg)
}
.portionAinB2_full <-
function(S1,S2,steps=101,alpha_grid){
steps0<-steps
alpha_grid0<-alpha_grid
.portionAinB2_full_severalcol(S1,S2,steps=steps0,alpha_grid=alpha_grid0)
}
.portionAinB2_full_dim1 <-
function(S1,S2,steps=101,alpha_grid){
steps0<-steps
alpha_grid0<-alpha_grid
.portionAinB2_full_severalcol_dim1(S1,S2,steps=steps0,alpha_grid=alpha_grid0)
}
.portionAinB2_full_severalcol_dim1 <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)[1:(steps-1)]){
S<-c(S1,S2)
alpha_grid<-seq(0,1,length=steps)
Ncol<-1
ab<-max(S)-min(S)
SSN<-t((t(S)-min(S))/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
nrow_S1<-length(S1)
nrow_S2<-length(S2)
z<-mapply(.intersection_onecolumn, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow_S1,], SSN2=SSN[(nrow_S1+1):(nrow_S1+nrow_S2),],nrow_S1=nrow_S1,nrow_S2=nrow_S2,Ncol=Ncol,.quantile_intersection=.quantile_intersection))
integral_approx<-c(prod=.trapz(seq(0,1,length=steps), z),mean=.trapz(seq(0,1,length=steps),z),gmean=.trapz(seq(0,1,length=steps),z))
plot_data_prod<-z
erg<-list(alpha_grid=seq(0,1,length=steps)[1:(steps-1)],overlap=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.portionAinB2_full_severalcol <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)[1:(steps-1)]){
S<-rbind(S1,S2)
alpha_grid<-seq(0,1,length=steps)
Ncol<-ncol(S1)
Spans<-data.frame(trait_nr=1:Ncol,min=matrix(mapply(min, S, MoreArgs = list(na.rm = TRUE))),max=matrix(mapply(max, S, MoreArgs = list(na.rm = TRUE))))
ab<-Spans$max-Spans$min
SSN<-t((t(S)-Spans$min)/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
nrow_S1<-nrow(S1)
nrow_S2<-nrow(S2)
z<-mapply(.intersection_severalcol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow_S1,], SSN2=SSN[(nrow_S1+1):(nrow_S1+nrow_S2),],nrow_S1=nrow_S1,nrow_S2=nrow_S2,Ncol=Ncol,.quantile_intersection=.quantile_intersection))
integral_approx<-c(prod=.trapz(seq(0,1,length=steps), z[1,]),mean=.trapz(seq(0,1,length=steps),z[2,]),gmean=.trapz(seq(0,1,length=steps),z[3,]))
plot_data_prod<-z[1,]
erg<-list(alpha_grid=seq(0,1,length=steps)[1:(steps-1)],overlap=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.quantile_intersection <-
function(vec1,vec2,a,b,n){
x<-c( quantile(vec1, probs = c(a,b), na.rm = TRUE), quantile(vec2, probs = c(a,b), na.rm = TRUE) )
x<-c(x,x[4]-x[3])
x[5]<-ifelse(x[5]<=0,0,x[5])
r<-c(max(x[c(1,3)]),min(x[c(2,4)]))
r<-c(x[3:5],r,r[2]-r[1])
r[6]<-ifelse(r[6]<=0,0,r[6])
return(r)
}
.volume_onecol <-
function(alpha,SSN1){
SP1<-quantile(SSN1,probs=c(alpha/2,1-alpha/2),na.rm = TRUE)
vol<-(SP1[2]-SP1[1])
return(vol)
}
.volume_severalcol <-
function(alpha,SSN1){
alpha<-(1-(1-alpha)^(1/ncol(SSN1)))
a<-alpha/2
b<-1-alpha/2
SP1<-mapply(quantile, SSN1, MoreArgs = list(probs=c(a,b),na.rm=TRUE))
product<-prod(SP1[2,]-SP1[1,])
vol<-c(prod=product,mean=mean(SP1[2,]-SP1[1,]),gmean=product^{1/length(SP1[2,]-SP1[1,])})
return(vol)
}
.volumeA_coordinates_full_dim1 <-
function(S1,S2,steps=101 ){
nt<-1
names(S2)<-"v1"
r<-.volumeA_full_onecol(data.frame(v1=S1), data.frame(v1=S2), steps=steps)
integral_coord<-r$integral_approx
plot_volume<-r$volume
alpha_grid<-seq(0,1,length=steps)
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_volume=plot_volume)
return(erg)
}
.volumeA_coordinates_full <-
function(S1,S2,steps=101 ){
nt<-ncol(S1)
volumeA_function<-function(x1,x2,steps){
r<-.volumeA_full_onecol(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$integral_approx)
}
volumeA_function2<-function(x1,x2,steps){
r<-.volumeA_full_onecol(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps )
return(r$volume)
}
integral_coord<-mapply(volumeA_function, x1=S1, x2=S2, MoreArgs =list(steps=steps))
plot_volume<-mapply(volumeA_function2, x1=S1, x2=S2, MoreArgs =list(steps=steps))
alpha_grid<-seq(0,1,length=steps)
erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_volume=plot_volume)
return(erg)
}
.volumeA_full_onecol <-
function(S1,S2,steps=101){
S<-rbind(S1,S2)
Ncol<-ncol(S1)
alpha_grid<-seq(0,1,length=steps)
Spans<-data.frame(trait_nr=1:Ncol,min=min(S,na.rm = TRUE),max=max(S,na.rm = TRUE))
ab<-Spans$max-Spans$min
SSN<-(S-Spans$min)/(ab)
SSN[,ab==0]<-0.5
z<-mapply(.volume_onecol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow(S1),]))
z<-1/(1-alpha_grid[-length(alpha_grid)])*z[-length(alpha_grid)]
z <- ifelse(z <= 1, z, 1)
integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z))
erg<-list(alpha_grid=alpha_grid,volume=z,integral_approx=integral_approx)
return(erg)
}
.volumeA2_full <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
steps0<-steps
alpha0_grid<-alpha_grid
.volumeA2_full_severalcol(S1,S2,steps=steps0,alpha_grid=alpha0_grid )
}
.volumeA2_full_dim1 <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
steps0<-steps
alpha0_grid<-alpha_grid
.volumeA2_full_severalcol_dim1(S1,S2,steps=steps0,alpha_grid=alpha0_grid )
}
.volumeA2_full_severalcol_dim1 <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
S<-c(S1,S2)
Ncol<-1
ab<-max(S)-min(S)
SSN<-t((t(S)-min(S))/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
z<-mapply(.volume_onecol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN))
z<-rbind(1/(1-alpha_grid[-length(alpha_grid)])*z[-length(alpha_grid)])
z <- ifelse(z <= 1, z, 1)
integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z),mean=.trapz(alpha_grid[-length(alpha_grid)],z),gmean=.trapz(alpha_grid[-length(alpha_grid)],z))
plot_data_prod<-z
erg<-list(alpha_grid=seq(0,1,length=steps),volume=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.volumeA2_full_severalcol <-
function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){
S<-rbind(S1,S2)
Ncol<-ncol(S1)
Spans<-data.frame(trait_nr=1:Ncol,min=matrix(mapply(min, S, MoreArgs = list(na.rm = TRUE))),max=matrix(mapply(max, S, MoreArgs = list(na.rm = TRUE))))
ab<-Spans$max-Spans$min
SSN<-t((t(S)-Spans$min)/(ab))
SSN[,ab==0]<-0.5
SSN<-as.data.frame(SSN)
z<-mapply(.volume_severalcol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow(S1),]))
z<-rbind(1/(1-alpha_grid[-length(alpha_grid)])*z[1,][-length(alpha_grid)],1/(1-alpha_grid[-length(alpha_grid)])*z[2,][-length(alpha_grid)],1/(1-alpha_grid[-length(alpha_grid)])*z[3,][-length(alpha_grid)])
z <- ifelse(z <= 1, z, 1)
integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z[1,]),mean=.trapz(alpha_grid[-length(alpha_grid)],z[2,]),gmean=.trapz(alpha_grid[-length(alpha_grid)],z[3,]))
plot_data_prod<-z[1,]
erg<-list(alpha_grid=seq(0,1,length=steps),volume=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod)
return(erg)
}
.trpca <- function(data, va){ # data = dataset as for dynRB, va = how much variance (0-1) should included axes explain
PCA <- prcomp(data[,-1])
vars <- apply(PCA$x, 2, var)
prop <- cumsum(vars / sum(vars))
k <- which(prop >= va)[1]
k <- ifelse(k==1, 2, k)
data1 <- data.frame(data[,1], PCA$x[,1:k])
colnames(data1)[1] <- "Species"
return(data1)
}
.getVarianceEstimate <-function(x,y){
# X
x_smallerM = x[1:round(length(x)/2 + 0.1)] #x[x < median(x)]
x_greaterM = x[round(length(x)/2+1.1):length(x)] #x[x >= median(x)]
n = as.numeric(length(x))
k = as.numeric(length(x_smallerM))
x_smallerM_ranks = rank(x_smallerM)
x_greaterM_ranks = rank(x_greaterM)
# Y
y_smallerM = y[1:round(length(y)/2 +0.1)] # y[y < median(y)]
y_greaterM = y[round(length(y)/2+1.1):length(y)]# y[y >= median(y)]
m = as.numeric(length(y))
l = as.numeric(length(y_smallerM))
y_smallerM_ranks = rank(y_smallerM)
y_greaterM_ranks = rank(y_greaterM)
xy_smallerM_ranks = rank(c(x_smallerM,y_smallerM))[1:k]
yx_smallerM_ranks = rank(c(y_smallerM,x_smallerM))[1:l]
xy_greaterM_ranks = rank(c(x_greaterM,y_greaterM))[1:(n-k)]
yx_greaterM_ranks = rank(c(y_greaterM,x_greaterM))[1:(m-l)]
s2_X1 = 1/(l^2*(k-1)) * sum((xy_smallerM_ranks - x_smallerM_ranks - mean(xy_smallerM_ranks) + (k+1)/2)^2)
s2_X2 = 1/((m-l)^2*(n-k-1)) * sum((xy_greaterM_ranks - x_greaterM_ranks - mean(xy_greaterM_ranks) + (n-k+1)/2)^2)
s2_Y1 = 1/(k^2*(l-1)) * sum((yx_smallerM_ranks - y_smallerM_ranks - mean(yx_smallerM_ranks) + (l+1)/2)^2)
s2_Y2 = 1/((n-k)^2*(m-l-1)) * sum((yx_greaterM_ranks - y_greaterM_ranks - mean(yx_greaterM_ranks) + (m-l+1)/2)^2)
s2_2 = (l+k)*(s2_X1/k + s2_Y1/l) + (n+m-l-k)*(s2_X2/(n-k) + s2_Y2/(m-l))
return(s2_2)
}
.getRankedSingleOverlapIndex <- function(x,y){
x_length = as.numeric(length(x))
if(round(x_length/2)==x_length/2){
k=x_length/2
}else{
k=(x_length+1)/2
}
y_length = as.numeric(length(y))
x = sort(x)
xy_ranks = rank(c(x,y))
x_rank = xy_ranks[1:x_length]
y_rank = xy_ranks[(x_length+1):(x_length+y_length)]
rank_gtm = sum(x_rank[(k+1) : x_length])
rank_stm = sum(x_rank[1:k])
K= sum(rank(x)[1:k])
c = 2/((x_length)*(y_length)) * ( - x_length*(x_length+1) + K*4)
overlap_ranked = 2*(rank_gtm - rank_stm)/((x_length)*(y_length)) + c/2
return(overlap_ranked)
}
.geo.mean <- function (x){
n<-length(x)
mittelwert<-prod(x)^(1/n)
return (mittelwert)
} |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#' Read Parquet file from disk
#'
#' '[Parquet](https://parquet.apache.org/)' is a columnar storage file format.
#' This function enables you to read Parquet files into R.
#'
#' @param file a file path
#' @param as_tibble Should the [arrow::Table][arrow__Table] be converted to a
#' tibble? Default is `TRUE`.
#' @param use_threads Use threads when converting to a tibble? Default is
#' '`TRUE`. Only relevant if `as_tibble` is `TRUE`.
#' @param ... Additional arguments, currently ignored
#'
#' @return A [arrow::Table][arrow__Table], or a `tbl_df` if `as_tibble` is
#' `TRUE`.
#' @examples
#'
#' \dontrun{
#' df <- read_parquet(system.file("v0.7.1.parquet", package="arrow"))
#' }
#'
#' @export
read_parquet <- function(file, as_tibble = TRUE, use_threads = TRUE, ...) {
tab <- shared_ptr(`arrow::Table`, read_parquet_file(file))
if (isTRUE(as_tibble)) {
tab <- as_tibble(tab, use_threads = use_threads)
}
tab
}
| /r/R/parquet.R | permissive | cesarob/arrow | R | false | false | 1,714 | r | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#' Read Parquet file from disk
#'
#' '[Parquet](https://parquet.apache.org/)' is a columnar storage file format.
#' This function enables you to read Parquet files into R.
#'
#' @param file a file path
#' @param as_tibble Should the [arrow::Table][arrow__Table] be converted to a
#' tibble? Default is `TRUE`.
#' @param use_threads Use threads when converting to a tibble? Default is
#' '`TRUE`. Only relevant if `as_tibble` is `TRUE`.
#' @param ... Additional arguments, currently ignored
#'
#' @return A [arrow::Table][arrow__Table], or a `tbl_df` if `as_tibble` is
#' `TRUE`.
#' @examples
#'
#' \dontrun{
#' df <- read_parquet(system.file("v0.7.1.parquet", package="arrow"))
#' }
#'
#' @export
read_parquet <- function(file, as_tibble = TRUE, use_threads = TRUE, ...) {
tab <- shared_ptr(`arrow::Table`, read_parquet_file(file))
if (isTRUE(as_tibble)) {
tab <- as_tibble(tab, use_threads = use_threads)
}
tab
}
|
# HW4: Exit handlers
#'
# 1. Write a function `print_row` that takes a data.frame `df` and an integer
# `row` and prints the corresponding row of `df`.
# Use `capture.output` and `print_row` to assign the printed first row of the
# data.frame `mtcars` to the variable `first_row`.
## Do not modify this line!
print_row <- function(df, row){
print (df[row,])
}
first_row <- capture.output(print_row(mtcars, 1))
# 2. Implement your own `capture.output2` that takes as arguments `code` and
# `file`, a piece of R code and a file path (string) respectively.
# Use `sink()` to divert the output to the file at path `file`.
# Use an exit handler to reset the default output using `on.exit()` and
# `sink()` (don't pass any argument to `sink()` here). Make sure you set
# arguments `add` and `after` to `TRUE`.
# Your function should also force the code execution (use `force()`) and read
# the file at `file` before exiting (using `readLines()`).
## Do not modify this line!
capture.output2 <- function(code, file){
sink(file)
on.exit(sink, add=T, after=T)
force(code)
readLines(file)
}
# 3. Now write a function `capture.output3` that only takes in one argument
# `code`. Your function should create a temp file using `tempfile()` - and make
# sure the file is removed upon exiting the function call using `on.exit` and
# `file.remove`. Use `sink()` to divert the output to this file - and make sure
# you reset the default output upon exiting using `on.exit`. Then force the
# `code` execution and read the temp file.
# Make sure you set arguments `add` and `after` to `TRUE` of your `on.exit`
# calls.
## Do not modify this line!
capture.output3 <- function(code){
temp <- tempfile()
on.exit(file.remove(temp), add=T, after=T)
on.exit(sink(), add = T, after=T)
sink(temp)
force(code)
readLines(temp)
}
capture.output3(print(mtcars[3, ]))
# 4. Write a function `capture.output4` that takes as inputs `code` and `file`
# (`file`'s default value should be set to `NULL`).
# Your function should check if `file` is `NULL`: if yes, assign a new tempfile
# to variable `temp` and if not assign the non-null `file` to `temp` - make
# sure to remove the file when exiting if a tempfile was created.
# Then it should implement the same functionality as before:
# - divert the output to `temp` using `sink()`,
# - force the `code` execution using `force()`
# - read the file using `readLines()`
# Make sure to re-divert the default output upon exiting using `sink()` with
# no argument.
#'
## Do not modify this line!
capture.output4 <- function(code, file=NULL){
if (is.null(file)){
temp <- tempfile(pattern="temp", fileext = "txt")
on.exit(sink(), add=T, after=T)
sink(temp)
on.exit(file.remove(temp), add=T, after=T)
force(code)
readLines(temp)
}
else{
sink(file)
on.exit(sink(), add=T, after=T)
force(code)
readLines(file)
}
} | /HW4/Exit_handler.R | no_license | lsjhome/GR5206 | R | false | false | 2,912 | r | # HW4: Exit handlers
#'
# 1. Write a function `print_row` that takes a data.frame `df` and an integer
# `row` and prints the corresponding row of `df`.
# Use `capture.output` and `print_row` to assign the printed first row of the
# data.frame `mtcars` to the variable `first_row`.
## Do not modify this line!
print_row <- function(df, row){
print (df[row,])
}
first_row <- capture.output(print_row(mtcars, 1))
# 2. Implement your own `capture.output2` that takes as arguments `code` and
# `file`, a piece of R code and a file path (string) respectively.
# Use `sink()` to divert the output to the file at path `file`.
# Use an exit handler to reset the default output using `on.exit()` and
# `sink()` (don't pass any argument to `sink()` here). Make sure you set
# arguments `add` and `after` to `TRUE`.
# Your function should also force the code execution (use `force()`) and read
# the file at `file` before exiting (using `readLines()`).
## Do not modify this line!
capture.output2 <- function(code, file){
sink(file)
on.exit(sink, add=T, after=T)
force(code)
readLines(file)
}
# 3. Now write a function `capture.output3` that only takes in one argument
# `code`. Your function should create a temp file using `tempfile()` - and make
# sure the file is removed upon exiting the function call using `on.exit` and
# `file.remove`. Use `sink()` to divert the output to this file - and make sure
# you reset the default output upon exiting using `on.exit`. Then force the
# `code` execution and read the temp file.
# Make sure you set arguments `add` and `after` to `TRUE` of your `on.exit`
# calls.
## Do not modify this line!
capture.output3 <- function(code){
temp <- tempfile()
on.exit(file.remove(temp), add=T, after=T)
on.exit(sink(), add = T, after=T)
sink(temp)
force(code)
readLines(temp)
}
capture.output3(print(mtcars[3, ]))
# 4. Write a function `capture.output4` that takes as inputs `code` and `file`
# (`file`'s default value should be set to `NULL`).
# Your function should check if `file` is `NULL`: if yes, assign a new tempfile
# to variable `temp` and if not assign the non-null `file` to `temp` - make
# sure to remove the file when exiting if a tempfile was created.
# Then it should implement the same functionality as before:
# - divert the output to `temp` using `sink()`,
# - force the `code` execution using `force()`
# - read the file using `readLines()`
# Make sure to re-divert the default output upon exiting using `sink()` with
# no argument.
#'
## Do not modify this line!
capture.output4 <- function(code, file=NULL){
if (is.null(file)){
temp <- tempfile(pattern="temp", fileext = "txt")
on.exit(sink(), add=T, after=T)
sink(temp)
on.exit(file.remove(temp), add=T, after=T)
force(code)
readLines(temp)
}
else{
sink(file)
on.exit(sink(), add=T, after=T)
force(code)
readLines(file)
}
} |
### Keywords.
library("ISIPTA.eProceedings")
library(plyr)
library(reshape2)
library(ggplot2)
library(wordcloud)
data("papers_keywords", package = "ISIPTA.eProceedings")
### Frequency of keywords ############################################
tabkeywords <- table(papers_keywords$keyword)[-1]
tabkeywords["NA"] <- 0
tabkeywords <- sort(tabkeywords, decreasing = TRUE)
## Overall
tabkeywords[tabkeywords > 1]
## number of keywords per paper
kwp <- ddply(papers_keywords, .(year,id), function(x) nrow(x))
## over all proceedings
ggplot(kwp, aes(V1)) + geom_bar(stat = "count") +
labs(x = "Keywords per paper", y = "Absolute frequency") +
labs(title = "Keywords per paper")
## over all proceedings per year
ggplot(kwp, aes(V1, fill = ordered(year))) +
geom_bar(stat = "count", position = position_stack(reverse = TRUE)) +
labs(fill = "Year", x = "Keywords per paper") +
labs(y = "Absolute frequency", title = "Keywords per paper")
kwy <- ddply(papers_keywords, .(year),
function(x) {
c(unique_keywords = length(unique(x$keyword)),
keywords = nrow(x),
papers = length(unique(x$id)))
}
)
kwy$uniqueKeywordsPerPaper <- kwy$unique_keywords/kwy$papers
kwy$KeywordsPerPaper <- kwy$keywords/kwy$papers
## Absolute frequency of (unique) keywords per paper
kwy_melt1 <- melt(kwy, id.vars = "year",
measure.vars = c("unique_keywords",
"keywords"))
levels(kwy_melt1$variable) <- c("unique keywords", "keywords")
ggplot(kwy_melt1,
aes(ordered(year), value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge", width = 0.75) +
labs(x = "Year", y = "Frequency", fill = "") +
labs(title = "Unique keywords")
## Average of (unique) keywords per paper
kwy_melt2 <- melt(kwy, id.vars = "year",
measure.vars = c("uniqueKeywordsPerPaper",
"KeywordsPerPaper"))
levels(kwy_melt2$variable) <- c("unique keywords", "keywords")
ggplot(kwy_melt2, aes(year, value, colour = variable)) +
geom_point() + geom_line() + labs(x = "Year") +
labs(y = "Proportion", colour = "") +
labs(title = "(Unique) Keywords per paper") +
scale_x_continuous(breaks = unique(kwy_melt2$year))
### Most frequent keywords development over time
papers_keywords_fac <- papers_keywords
papers_keywords_fac$keyword <- factor(papers_keywords_fac$keyword)
d1 <- ddply(papers_keywords_fac, .(year),
function(x) {
xtabs <- table(x$keyword)/length(unique(x$id))
xtabs
})
d1$'NA' <- d1$V1 <- NULL
ggplot(melt(d1[, sapply(d1, function(x) {max(x)>0.1})],
id.vars = "year"), aes(year, value, colour = variable)) +
geom_point() + geom_line() + labs(x = "Year") +
labs(y = "Frequency in conference papers", colour = "Keyword") +
labs(title = "Most frequent keywords (at least once >10% at any conference)") +
scale_y_continuous(labels = function(x) {paste0(x*100, "%")}) +
scale_x_continuous(breaks = unique(d1$year))
### Wordcloud ########################################################
names(tabkeywords) <- gsub("(imprecise) (probability)", "\\1\n\\2" , names(tabkeywords))
# Printing keywords of at least 3 occurences
opar <- par(bg = "grey10")
wordcloud(freq = tabkeywords, words = names(tabkeywords),
scale = c(2.5,0.5), min.freq = 3,
random.order = FALSE, colors = brewer.pal(9, "YlOrRd")[-(1:2)])
par(opar)
| /package/demo/keywords.R | no_license | paul-fink/ISIPTA | R | false | false | 3,475 | r | ### Keywords.
library("ISIPTA.eProceedings")
library(plyr)
library(reshape2)
library(ggplot2)
library(wordcloud)
data("papers_keywords", package = "ISIPTA.eProceedings")
### Frequency of keywords ############################################
tabkeywords <- table(papers_keywords$keyword)[-1]
tabkeywords["NA"] <- 0
tabkeywords <- sort(tabkeywords, decreasing = TRUE)
## Overall
tabkeywords[tabkeywords > 1]
## number of keywords per paper
kwp <- ddply(papers_keywords, .(year,id), function(x) nrow(x))
## over all proceedings
ggplot(kwp, aes(V1)) + geom_bar(stat = "count") +
labs(x = "Keywords per paper", y = "Absolute frequency") +
labs(title = "Keywords per paper")
## over all proceedings per year
ggplot(kwp, aes(V1, fill = ordered(year))) +
geom_bar(stat = "count", position = position_stack(reverse = TRUE)) +
labs(fill = "Year", x = "Keywords per paper") +
labs(y = "Absolute frequency", title = "Keywords per paper")
kwy <- ddply(papers_keywords, .(year),
function(x) {
c(unique_keywords = length(unique(x$keyword)),
keywords = nrow(x),
papers = length(unique(x$id)))
}
)
kwy$uniqueKeywordsPerPaper <- kwy$unique_keywords/kwy$papers
kwy$KeywordsPerPaper <- kwy$keywords/kwy$papers
## Absolute frequency of (unique) keywords per paper
kwy_melt1 <- melt(kwy, id.vars = "year",
measure.vars = c("unique_keywords",
"keywords"))
levels(kwy_melt1$variable) <- c("unique keywords", "keywords")
ggplot(kwy_melt1,
aes(ordered(year), value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge", width = 0.75) +
labs(x = "Year", y = "Frequency", fill = "") +
labs(title = "Unique keywords")
## Average of (unique) keywords per paper
kwy_melt2 <- melt(kwy, id.vars = "year",
measure.vars = c("uniqueKeywordsPerPaper",
"KeywordsPerPaper"))
levels(kwy_melt2$variable) <- c("unique keywords", "keywords")
ggplot(kwy_melt2, aes(year, value, colour = variable)) +
geom_point() + geom_line() + labs(x = "Year") +
labs(y = "Proportion", colour = "") +
labs(title = "(Unique) Keywords per paper") +
scale_x_continuous(breaks = unique(kwy_melt2$year))
### Most frequent keywords development over time
papers_keywords_fac <- papers_keywords
papers_keywords_fac$keyword <- factor(papers_keywords_fac$keyword)
d1 <- ddply(papers_keywords_fac, .(year),
function(x) {
xtabs <- table(x$keyword)/length(unique(x$id))
xtabs
})
d1$'NA' <- d1$V1 <- NULL
ggplot(melt(d1[, sapply(d1, function(x) {max(x)>0.1})],
id.vars = "year"), aes(year, value, colour = variable)) +
geom_point() + geom_line() + labs(x = "Year") +
labs(y = "Frequency in conference papers", colour = "Keyword") +
labs(title = "Most frequent keywords (at least once >10% at any conference)") +
scale_y_continuous(labels = function(x) {paste0(x*100, "%")}) +
scale_x_continuous(breaks = unique(d1$year))
### Wordcloud ########################################################
names(tabkeywords) <- gsub("(imprecise) (probability)", "\\1\n\\2" , names(tabkeywords))
# Printing keywords of at least 3 occurences
opar <- par(bg = "grey10")
wordcloud(freq = tabkeywords, words = names(tabkeywords),
scale = c(2.5,0.5), min.freq = 3,
random.order = FALSE, colors = brewer.pal(9, "YlOrRd")[-(1:2)])
par(opar)
|
library(data.table)
setwd("/home/mark/competitions/zindi-fowl/")
a17c<-fread("fastai_A17c.csv")[order(ID)] ## 1.5011
a17f<-fread("fastai_A17f.csv")[order(ID)] ## 1.4364
a17k<-fread("fastai_A17k.csv")[order(ID)] ## 1.5614
a18a<-fread("fastai_A18a.csv")[order(ID)] ## 1.4793
a18b<-fread("fastai_A18b.csv")[order(ID)] ## 1.4845
blend<-data.frame(a17f)
for(ic in 2:ncol(blend)){
blend[,ic]<-0.2*a17c[,ic,with=FALSE]+
0.2*a17f[,ic,with=FALSE]+
0.2*a17k[,ic,with=FALSE]+
0.2*a18a[,ic,with=FALSE]+
0.2*a18b[,ic,with=FALSE]
}
a17f[1,1:8,with=F]
blend[1,1:8]
write.csv(blend,"blend_top5_reproducibles.csv",row.names = FALSE)
| /blend.R | no_license | mlandry22/zindi-fowl-escapades | R | false | false | 638 | r | library(data.table)
setwd("/home/mark/competitions/zindi-fowl/")
a17c<-fread("fastai_A17c.csv")[order(ID)] ## 1.5011
a17f<-fread("fastai_A17f.csv")[order(ID)] ## 1.4364
a17k<-fread("fastai_A17k.csv")[order(ID)] ## 1.5614
a18a<-fread("fastai_A18a.csv")[order(ID)] ## 1.4793
a18b<-fread("fastai_A18b.csv")[order(ID)] ## 1.4845
blend<-data.frame(a17f)
for(ic in 2:ncol(blend)){
blend[,ic]<-0.2*a17c[,ic,with=FALSE]+
0.2*a17f[,ic,with=FALSE]+
0.2*a17k[,ic,with=FALSE]+
0.2*a18a[,ic,with=FALSE]+
0.2*a18b[,ic,with=FALSE]
}
a17f[1,1:8,with=F]
blend[1,1:8]
write.csv(blend,"blend_top5_reproducibles.csv",row.names = FALSE)
|
lpmlp <-
function(y, X, res, nsim, nburn) {
n <- length(y)
aux <- matrix(0,nrow=n,ncol=nsim-nburn)
cpoinv <- numeric(n)
for(k in 1:(nsim-nburn)) {
aux[,k] <- dnorm(y, mean = X%*%res[[1]][k+nburn,], sd = sqrt(res[[2]][k+nburn]))
}
cpoinv <- apply(aux, 1, function(x) mean(1/x))
cpo <- 1/cpoinv
lpml <- sum(log(cpo))
res <- list()
res$cpo <- cpo
res$lpml <- lpml
res
}
| /R/lpmlp.R | no_license | cran/AROC | R | false | false | 386 | r | lpmlp <-
function(y, X, res, nsim, nburn) {
n <- length(y)
aux <- matrix(0,nrow=n,ncol=nsim-nburn)
cpoinv <- numeric(n)
for(k in 1:(nsim-nburn)) {
aux[,k] <- dnorm(y, mean = X%*%res[[1]][k+nburn,], sd = sqrt(res[[2]][k+nburn]))
}
cpoinv <- apply(aux, 1, function(x) mean(1/x))
cpo <- 1/cpoinv
lpml <- sum(log(cpo))
res <- list()
res$cpo <- cpo
res$lpml <- lpml
res
}
|
#' Rebuilds the model matrix for MatchIt objects
#'
#' In order to use estimate Standard Errors with the Abadie and Imben's method
#' the MatchIt object needs to have a model matrix. The model matrix is created
#' based on the subclasses given by the full matching procedure.
#'
#' This function is experimental! Most methods for estimating standard errors
#' are only documented for NN matching. Please use with caution!
#'
#' @param fit MatchIt Object
#' @return MatchIt Object with added model matrix
#' @examples
#' \dontrun{
#' library(MatchIt)
#' data('lalonde')
#' m.out <- matchit(treat ~ educ + black, data = lalonde, method = 'full')
#' att(obj = m.out, Y = lalonde$re78)
#' abadie_imbens_se(m.out, lalonde$re78) # FAILS!
#' m.out <- add_model_matrix(m.out)
#' abadie_imbens_se(m.out, lalonde$re78)
#' }
#' @export
add_model_matrix <- function(fit){
warning("\nThis function is experimental!
Most methods for estimating standard errors are only
documented for NN matching.\nUse with caution!")
if (is.null(fit$call$method) || fit$call$method != "full") {
stop("This function only works for Full Matching")
}
p <- max(table(fit$subclass))
n <- sum(fit$treat)
mm <- matrix(NA, nrow = n, ncol = p)
ts <- fit$subclass[fit$treat == 1]
cs <- fit$subclass[fit$weights > 0 & fit$treat == 0]
for (i in 1:n){
if (!is.na(ts[i])){
indic.names <- names(cs)[which(cs == ts[i])]
mm[i,1:length(indic.names)] <- indic.names
}
}
rownames(mm) <- names(ts)
fit$match.matrix <- mm
return(fit)
}
| /R/rebuild-model-matrix.R | no_license | ehsanx/MatchItSE | R | false | false | 1,516 | r | #' Rebuilds the model matrix for MatchIt objects
#'
#' In order to use estimate Standard Errors with the Abadie and Imben's method
#' the MatchIt object needs to have a model matrix. The model matrix is created
#' based on the subclasses given by the full matching procedure.
#'
#' This function is experimental! Most methods for estimating standard errors
#' are only documented for NN matching. Please use with caution!
#'
#' @param fit MatchIt Object
#' @return MatchIt Object with added model matrix
#' @examples
#' \dontrun{
#' library(MatchIt)
#' data('lalonde')
#' m.out <- matchit(treat ~ educ + black, data = lalonde, method = 'full')
#' att(obj = m.out, Y = lalonde$re78)
#' abadie_imbens_se(m.out, lalonde$re78) # FAILS!
#' m.out <- add_model_matrix(m.out)
#' abadie_imbens_se(m.out, lalonde$re78)
#' }
#' @export
add_model_matrix <- function(fit){
warning("\nThis function is experimental!
Most methods for estimating standard errors are only
documented for NN matching.\nUse with caution!")
if (is.null(fit$call$method) || fit$call$method != "full") {
stop("This function only works for Full Matching")
}
p <- max(table(fit$subclass))
n <- sum(fit$treat)
mm <- matrix(NA, nrow = n, ncol = p)
ts <- fit$subclass[fit$treat == 1]
cs <- fit$subclass[fit$weights > 0 & fit$treat == 0]
for (i in 1:n){
if (!is.na(ts[i])){
indic.names <- names(cs)[which(cs == ts[i])]
mm[i,1:length(indic.names)] <- indic.names
}
}
rownames(mm) <- names(ts)
fit$match.matrix <- mm
return(fit)
}
|
rm(list=ls())
# runtime configuration
if (Sys.info()["sysname"] == "Linux") {
j <- "ADDRESS"
h <- "/ADDRESS/USERNAME/"
} else {
j <- "ADDRESS"
h <- "ADDRESS"
}
script <- file.path("FILEPATH/pop_extract.R")
sge.output.dir<-"-j y -o FILEPATH"
rshell<-file.path("FILEPATH/health_fin_forecasting_shell_singularity.sh")
#############################################################################################################################
YEARS<-seq(1990,2018,1)
mem <- "-l m_mem_free=40G"
fthread <- "-l fthread=4"
runtime <- "-l h_rt=24:00:00"
archive <- "-l archive=TRUE" # or "" if no jdrive access needed
project<-"-P proj_custom_models"
for (i in 1:length(YEARS)){
year<-YEARS[i]
args <- paste(year)
jname <- paste0("-N ","pop",year)
#NOTE: project, sge.output.dir, & rshell MUST be defined elsewhere in script
system(paste("qsub",jname,mem,fthread,runtime,archive,project,"-q all.q",sge.output.dir,rshell,script,args))
}
| /gbd_2019/risk_factors_code/temperature/4_PAF/pop_extract_parent.R | no_license | Nermin-Ghith/ihme-modeling | R | false | false | 964 | r |
rm(list=ls())
# runtime configuration
if (Sys.info()["sysname"] == "Linux") {
j <- "ADDRESS"
h <- "/ADDRESS/USERNAME/"
} else {
j <- "ADDRESS"
h <- "ADDRESS"
}
script <- file.path("FILEPATH/pop_extract.R")
sge.output.dir<-"-j y -o FILEPATH"
rshell<-file.path("FILEPATH/health_fin_forecasting_shell_singularity.sh")
#############################################################################################################################
YEARS<-seq(1990,2018,1)
mem <- "-l m_mem_free=40G"
fthread <- "-l fthread=4"
runtime <- "-l h_rt=24:00:00"
archive <- "-l archive=TRUE" # or "" if no jdrive access needed
project<-"-P proj_custom_models"
for (i in 1:length(YEARS)){
year<-YEARS[i]
args <- paste(year)
jname <- paste0("-N ","pop",year)
#NOTE: project, sge.output.dir, & rshell MUST be defined elsewhere in script
system(paste("qsub",jname,mem,fthread,runtime,archive,project,"-q all.q",sge.output.dir,rshell,script,args))
}
|
###############################################################################################
# An R function to calculate the candidates relevance score for Zero Chaos requisitions #
# These R functions are Copyright (C) of Pandera Systems LLP #
###############################################################################################
zindex_relevance <- function(ReqId,mongo,res3)
{
db <- "candidate_model"
coll <- "requisition_skills_from_parsed_requisitions"
ins1 <- paste(db,coll,sep=".")
buf <- mongo.bson.buffer.create()
T <- mongo.bson.buffer.append(buf,"requisitionId",ReqId)
query <- mongo.bson.from.buffer(buf)
cursor <- mongo.find(mongo, ins1, query,,list(requisitionId=1L,parsedWords.word=1L))
temp <- mongo.cursor.to.list(cursor)
for(i in 1:length(temp)){
temp[[i]][1]<-NULL
}
temp2<-unlist(temp)
l<-length(temp2)
if(l<=1){
return("No Requisition")
}
res<-ldply (temp, data.frame)
reqskill<-res
T1<-ncol(reqskill)
T1<-T1-2
query<-character()
if(T1!=0){
for(i in 1:T1){
c<-paste("parsedWords.word",i,sep=".")
query[i]<-c
}
}
T1<-"parsedWords.word"
query<-c(T1,query)
reqskill<-melt(reqskill,"requisitionId",query,value.name='Skill')
reqskill <- as.data.frame(reqskill[,3])
coll <- "requisition"
ins <- paste(db,coll,sep=".")
res<-data.frame()
buf <- mongo.bson.buffer.create()
T <- mongo.bson.buffer.append(buf,"requisition_id",ReqId)
query <- mongo.bson.from.buffer(buf)
cursor <- mongo.find(mongo, ins, query,,list(requisition_id=1L,job_skill_names.job_skill_name=1L))
temp <- mongo.cursor.to.list(cursor)
temp2<-unlist(temp)
ll<-length(temp2)
if(ll>2){
l<-length(temp)
for(j in 1:l){
temp[[j]][1]<-NULL
}
temp<-ldply (temp, data.frame)
temp<-melt(temp,id="requisition_id",value.name='Skill')
Skill<-data.frame(temp[,3])
colnames(Skill)<-"reqskill[, 3]"
reqskill<-rbind(reqskill,Skill)
}
Cand<-unique(res3[,"candidateID"])
Scores<-data.frame(Cand)
levels<-max(rank(Cand))
RScore<-integer()
for(i in 1:levels){
Temp <- res3[res3$candidateID==Cand[i],]
T <- Temp[,2]
T<- as.data.frame(table(T))
T <- arrange(T,desc(Freq))
count <- NROW(T)
Check<-reqskill$'reqskill[, 3]' %in% T$T
div<-0.8*length(Check)
RScore[i] <- ceiling(40*(sum(Check)/div))
}
Scores$RScore <- RScore
remove(db,coll,ins1,buf,query,T,cursor,temp,i,temp2,l,res,reqskill,T1,ins,llj,Skill,Cand,levels,RScore,Temp,count,Check,div)
return(Scores)
}
| /OldBkup/zindex_relevance.r | no_license | midunrajendranpandera/R | R | false | false | 2,848 | r | ###############################################################################################
# An R function to calculate the candidates relevance score for Zero Chaos requisitions #
# These R functions are Copyright (C) of Pandera Systems LLP #
###############################################################################################
zindex_relevance <- function(ReqId,mongo,res3)
{
db <- "candidate_model"
coll <- "requisition_skills_from_parsed_requisitions"
ins1 <- paste(db,coll,sep=".")
buf <- mongo.bson.buffer.create()
T <- mongo.bson.buffer.append(buf,"requisitionId",ReqId)
query <- mongo.bson.from.buffer(buf)
cursor <- mongo.find(mongo, ins1, query,,list(requisitionId=1L,parsedWords.word=1L))
temp <- mongo.cursor.to.list(cursor)
for(i in 1:length(temp)){
temp[[i]][1]<-NULL
}
temp2<-unlist(temp)
l<-length(temp2)
if(l<=1){
return("No Requisition")
}
res<-ldply (temp, data.frame)
reqskill<-res
T1<-ncol(reqskill)
T1<-T1-2
query<-character()
if(T1!=0){
for(i in 1:T1){
c<-paste("parsedWords.word",i,sep=".")
query[i]<-c
}
}
T1<-"parsedWords.word"
query<-c(T1,query)
reqskill<-melt(reqskill,"requisitionId",query,value.name='Skill')
reqskill <- as.data.frame(reqskill[,3])
coll <- "requisition"
ins <- paste(db,coll,sep=".")
res<-data.frame()
buf <- mongo.bson.buffer.create()
T <- mongo.bson.buffer.append(buf,"requisition_id",ReqId)
query <- mongo.bson.from.buffer(buf)
cursor <- mongo.find(mongo, ins, query,,list(requisition_id=1L,job_skill_names.job_skill_name=1L))
temp <- mongo.cursor.to.list(cursor)
temp2<-unlist(temp)
ll<-length(temp2)
if(ll>2){
l<-length(temp)
for(j in 1:l){
temp[[j]][1]<-NULL
}
temp<-ldply (temp, data.frame)
temp<-melt(temp,id="requisition_id",value.name='Skill')
Skill<-data.frame(temp[,3])
colnames(Skill)<-"reqskill[, 3]"
reqskill<-rbind(reqskill,Skill)
}
Cand<-unique(res3[,"candidateID"])
Scores<-data.frame(Cand)
levels<-max(rank(Cand))
RScore<-integer()
for(i in 1:levels){
Temp <- res3[res3$candidateID==Cand[i],]
T <- Temp[,2]
T<- as.data.frame(table(T))
T <- arrange(T,desc(Freq))
count <- NROW(T)
Check<-reqskill$'reqskill[, 3]' %in% T$T
div<-0.8*length(Check)
RScore[i] <- ceiling(40*(sum(Check)/div))
}
Scores$RScore <- RScore
remove(db,coll,ins1,buf,query,T,cursor,temp,i,temp2,l,res,reqskill,T1,ins,llj,Skill,Cand,levels,RScore,Temp,count,Check,div)
return(Scores)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/nn-dropout.R
\name{nn_dropout}
\alias{nn_dropout}
\title{Dropout module}
\usage{
nn_dropout(p = 0.5, inplace = FALSE)
}
\arguments{
\item{p}{probability of an element to be zeroed. Default: 0.5}
\item{inplace}{If set to \code{TRUE}, will do this operation in-place. Default: \code{FALSE}.}
}
\description{
During training, randomly zeroes some of the elements of the input
tensor with probability \code{p} using samples from a Bernoulli
distribution. Each channel will be zeroed out independently on every forward
call.
}
\details{
This has proven to be an effective technique for regularization and
preventing the co-adaptation of neurons as described in the paper
\href{https://arxiv.org/abs/1207.0580}{Improving neural networks by preventing co-adaptation of feature detectors}.
Furthermore, the outputs are scaled by a factor of :math:\verb{\\frac\{1\}\{1-p\}} during
training. This means that during evaluation the module simply computes an
identity function.
}
\section{Shape}{
\itemize{
\item Input: \eqn{(*)}. Input can be of any shape
\item Output: \eqn{(*)}. Output is of the same shape as input
}
}
\examples{
if (torch_is_installed()) {
m <- nn_dropout(p = 0.2)
input <- torch_randn(20, 16)
output <- m(input)
}
}
| /man/nn_dropout.Rd | permissive | mlverse/torch | R | false | true | 1,308 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/nn-dropout.R
\name{nn_dropout}
\alias{nn_dropout}
\title{Dropout module}
\usage{
nn_dropout(p = 0.5, inplace = FALSE)
}
\arguments{
\item{p}{probability of an element to be zeroed. Default: 0.5}
\item{inplace}{If set to \code{TRUE}, will do this operation in-place. Default: \code{FALSE}.}
}
\description{
During training, randomly zeroes some of the elements of the input
tensor with probability \code{p} using samples from a Bernoulli
distribution. Each channel will be zeroed out independently on every forward
call.
}
\details{
This has proven to be an effective technique for regularization and
preventing the co-adaptation of neurons as described in the paper
\href{https://arxiv.org/abs/1207.0580}{Improving neural networks by preventing co-adaptation of feature detectors}.
Furthermore, the outputs are scaled by a factor of :math:\verb{\\frac\{1\}\{1-p\}} during
training. This means that during evaluation the module simply computes an
identity function.
}
\section{Shape}{
\itemize{
\item Input: \eqn{(*)}. Input can be of any shape
\item Output: \eqn{(*)}. Output is of the same shape as input
}
}
\examples{
if (torch_is_installed()) {
m <- nn_dropout(p = 0.2)
input <- torch_randn(20, 16)
output <- m(input)
}
}
|
# This file is generated by make.paws. Please do not edit here.
#' @importFrom paws.common new_handlers new_service
NULL
#' AWS Shield
#'
#' @description
#' AWS Shield Advanced
#'
#' This is the *AWS Shield Advanced API Reference*. This guide is for
#' developers who need detailed information about the AWS Shield Advanced
#' API actions, data types, and errors. For detailed information about AWS
#' WAF and AWS Shield Advanced features and an overview of how to use the
#' AWS WAF and AWS Shield Advanced APIs, see the [AWS WAF and AWS Shield
#' Developer
#' Guide](https://docs.aws.amazon.com/waf/latest/developerguide/).
#'
#' @examples
#' \donttest{svc <- shield()
#' svc$associate_drt_log_bucket(
#' Foo = 123
#' )}
#'
#' @section Operations:
#' \tabular{ll}{
#' \link[=shield_associate_drt_log_bucket]{associate_drt_log_bucket} \tab Authorizes the DDoS Response team (DRT) to access the specified Amazon S3 bucket containing your flow logs \cr
#' \link[=shield_associate_drt_role]{associate_drt_role} \tab Authorizes the DDoS Response team (DRT), using the specified role, to access your AWS account to assist with DDoS attack mitigation during potential attacks \cr
#' \link[=shield_create_protection]{create_protection} \tab Enables AWS Shield Advanced for a specific AWS resource \cr
#' \link[=shield_create_subscription]{create_subscription} \tab Activates AWS Shield Advanced for an account \cr
#' \link[=shield_delete_protection]{delete_protection} \tab Deletes an AWS Shield Advanced Protection \cr
#' \link[=shield_delete_subscription]{delete_subscription} \tab Removes AWS Shield Advanced from an account \cr
#' \link[=shield_describe_attack]{describe_attack} \tab Describes the details of a DDoS attack \cr
#' \link[=shield_describe_drt_access]{describe_drt_access} \tab Returns the current role and list of Amazon S3 log buckets used by the DDoS Response team (DRT) to access your AWS account while assisting with attack mitigation\cr
#' \link[=shield_describe_emergency_contact_settings]{describe_emergency_contact_settings} \tab Lists the email addresses that the DRT can use to contact you during a suspected attack \cr
#' \link[=shield_describe_protection]{describe_protection} \tab Lists the details of a Protection object \cr
#' \link[=shield_describe_subscription]{describe_subscription} \tab Provides details about the AWS Shield Advanced subscription for an account \cr
#' \link[=shield_disassociate_drt_log_bucket]{disassociate_drt_log_bucket} \tab Removes the DDoS Response team's (DRT) access to the specified Amazon S3 bucket containing your flow logs \cr
#' \link[=shield_disassociate_drt_role]{disassociate_drt_role} \tab Removes the DDoS Response team's (DRT) access to your AWS account \cr
#' \link[=shield_get_subscription_state]{get_subscription_state} \tab Returns the SubscriptionState, either Active or Inactive \cr
#' \link[=shield_list_attacks]{list_attacks} \tab Returns all ongoing DDoS attacks or all DDoS attacks during a specified time period \cr
#' \link[=shield_list_protections]{list_protections} \tab Lists all Protection objects for the account \cr
#' \link[=shield_update_emergency_contact_settings]{update_emergency_contact_settings} \tab Updates the details of the list of email addresses that the DRT can use to contact you during a suspected attack \cr
#' \link[=shield_update_subscription]{update_subscription} \tab Updates the details of an existing subscription
#' }
#'
#' @rdname shield
#' @export
shield <- function() {
.shield$operations
}
# Private API objects: metadata, handlers, interfaces, etc.
.shield <- list()
.shield$operations <- list()
.shield$metadata <- list(
service_name = "shield",
endpoints = list("*" = "shield.{region}.amazonaws.com", "cn-*" = "shield.{region}.amazonaws.com.cn"),
service_id = "Shield",
api_version = "2016-06-02",
signing_name = NULL,
json_version = "1.1",
target_prefix = "AWSShield_20160616"
)
.shield$handlers <- new_handlers("jsonrpc", "v4")
.shield$service <- function() {
new_service(.shield$metadata, .shield$handlers)
}
| /cran/paws.security.identity/R/shield_service.R | permissive | peoplecure/paws | R | false | false | 4,075 | r | # This file is generated by make.paws. Please do not edit here.
#' @importFrom paws.common new_handlers new_service
NULL
#' AWS Shield
#'
#' @description
#' AWS Shield Advanced
#'
#' This is the *AWS Shield Advanced API Reference*. This guide is for
#' developers who need detailed information about the AWS Shield Advanced
#' API actions, data types, and errors. For detailed information about AWS
#' WAF and AWS Shield Advanced features and an overview of how to use the
#' AWS WAF and AWS Shield Advanced APIs, see the [AWS WAF and AWS Shield
#' Developer
#' Guide](https://docs.aws.amazon.com/waf/latest/developerguide/).
#'
#' @examples
#' \donttest{svc <- shield()
#' svc$associate_drt_log_bucket(
#' Foo = 123
#' )}
#'
#' @section Operations:
#' \tabular{ll}{
#' \link[=shield_associate_drt_log_bucket]{associate_drt_log_bucket} \tab Authorizes the DDoS Response team (DRT) to access the specified Amazon S3 bucket containing your flow logs \cr
#' \link[=shield_associate_drt_role]{associate_drt_role} \tab Authorizes the DDoS Response team (DRT), using the specified role, to access your AWS account to assist with DDoS attack mitigation during potential attacks \cr
#' \link[=shield_create_protection]{create_protection} \tab Enables AWS Shield Advanced for a specific AWS resource \cr
#' \link[=shield_create_subscription]{create_subscription} \tab Activates AWS Shield Advanced for an account \cr
#' \link[=shield_delete_protection]{delete_protection} \tab Deletes an AWS Shield Advanced Protection \cr
#' \link[=shield_delete_subscription]{delete_subscription} \tab Removes AWS Shield Advanced from an account \cr
#' \link[=shield_describe_attack]{describe_attack} \tab Describes the details of a DDoS attack \cr
#' \link[=shield_describe_drt_access]{describe_drt_access} \tab Returns the current role and list of Amazon S3 log buckets used by the DDoS Response team (DRT) to access your AWS account while assisting with attack mitigation\cr
#' \link[=shield_describe_emergency_contact_settings]{describe_emergency_contact_settings} \tab Lists the email addresses that the DRT can use to contact you during a suspected attack \cr
#' \link[=shield_describe_protection]{describe_protection} \tab Lists the details of a Protection object \cr
#' \link[=shield_describe_subscription]{describe_subscription} \tab Provides details about the AWS Shield Advanced subscription for an account \cr
#' \link[=shield_disassociate_drt_log_bucket]{disassociate_drt_log_bucket} \tab Removes the DDoS Response team's (DRT) access to the specified Amazon S3 bucket containing your flow logs \cr
#' \link[=shield_disassociate_drt_role]{disassociate_drt_role} \tab Removes the DDoS Response team's (DRT) access to your AWS account \cr
#' \link[=shield_get_subscription_state]{get_subscription_state} \tab Returns the SubscriptionState, either Active or Inactive \cr
#' \link[=shield_list_attacks]{list_attacks} \tab Returns all ongoing DDoS attacks or all DDoS attacks during a specified time period \cr
#' \link[=shield_list_protections]{list_protections} \tab Lists all Protection objects for the account \cr
#' \link[=shield_update_emergency_contact_settings]{update_emergency_contact_settings} \tab Updates the details of the list of email addresses that the DRT can use to contact you during a suspected attack \cr
#' \link[=shield_update_subscription]{update_subscription} \tab Updates the details of an existing subscription
#' }
#'
#' @rdname shield
#' @export
shield <- function() {
.shield$operations
}
# Private API objects: metadata, handlers, interfaces, etc.
.shield <- list()
.shield$operations <- list()
.shield$metadata <- list(
service_name = "shield",
endpoints = list("*" = "shield.{region}.amazonaws.com", "cn-*" = "shield.{region}.amazonaws.com.cn"),
service_id = "Shield",
api_version = "2016-06-02",
signing_name = NULL,
json_version = "1.1",
target_prefix = "AWSShield_20160616"
)
.shield$handlers <- new_handlers("jsonrpc", "v4")
.shield$service <- function() {
new_service(.shield$metadata, .shield$handlers)
}
|
#=============================================================================
# R code to create to explore the Information Theoretic properties of
# simple food webs. This creates a simple food web with an underlying dynamic
# model.
# 1. Food-web includes resource, herbivore, and predator:
# A. Resource is based on a consumer-resource model, with added predators
# 1. Competition between consumers and resources emerges from consumption
# 2. Parameters at each level can be made a function of temperature.
# B. Resources can be stochastic due to environmental fluctuations.
# C. Relative non-linearity allows 2 consumers per Resource
# 2. Generate a bunch of random food webs
# 3. Use information theory to track the resulting food-web structures.
# 4. This file has a lot of code for visualizing output of both the foodweb
# its information theoretic properties after the main loop.
#=============================================================================
#=============================================================================
# load libraries
#=============================================================================
library(deSolve)
library(fields)
library(tidyverse)
library(lubridate)
library(mgcv)
source("../info_theory_functions/food_web_functions.R")
source("../info_theory_functions/info_theory_functions.R")
source("../info_theory_functions/database_functions.R")
#=============================================================================
# Outer loop. Set the number of trials and determine how to generate
# combinations of species and parameters.
#=============================================================================
#Length and time steps of each model run
tend = 25
delta1 = 0.01
tl=tend/delta1
#The maximum block depth for dynamic info metrics (larger is more accurate, but
#slower and could cause crashing if too large)
k= 5
#Number of food webs to generate
nwebs = 1
#Output of each web
out1 = vector("list",nwebs)
#Converting the web to Rutledge's compartment model and calculating the information
#theoretic quantities: Shannon Entropy, Mutual Information, Conditional Entropy
rweb1 = vector("list",nwebs)
#Dynamic information metrics calculated from the (discretized) time series
di_web = vector("list",nwebs)
#Track the average transfer entropy and separable information between each pair of
#species as a way to build a network of information flow through the network.
te_web = vector("list",nwebs)
si_web = vector("list",nwebs)
aiE_web = vector("list",nwebs)
MMI_web = vector("list",nwebs)
#Random resources:
c1 = 1
amp1 = 0.25 #100000 #1/exp(1)
#Random consumers
c2 = 1
amp2 = 0.1
res_R = c(amp1,c1,amp2,c2)
for (w in 1:nwebs){
print(w)
#Assume 3 trophic levels unless otherwise specified.
nRsp = ceiling(runif(1)*4)
nCsp = ceiling(runif(1)*2)
nPsp = ceiling(runif(1)*1)
nspp = nRsp+nCsp+nPsp
#Randomly generate the species parameters for the model as well:
spp_prms = NULL
#Resource: Nearly identical resource dynamics:
spp_prms$rR = matrix(rnorm(nRsp,300,10), nRsp, 1) #intrinsic growth
spp_prms$Ki = matrix(rnorm(nRsp,500,10), nRsp, 1) #carrying capacity
#Consumers:
spp_prms$rC = matrix(rnorm(nCsp,.5,0.2), nCsp, 1) #intrisic growth
spp_prms$eFc = matrix(1,nCsp,nRsp) # just make the efficiency for everything 1 for now
spp_prms$muC = matrix(rnorm(nCsp,0.6,0.1), nCsp, 1) #mortality rates
#Consumption rates:
#Generate a hierarchy where each species predominantly feeds on particular resource.
dspp = abs((nCsp - nRsp))
hier1= seq(1/nRsp, (1-1/nRsp), length=nRsp)
spp_prms$cC = hier1
for( n in 1:nCsp) {
spp_prms$cC = cbind(spp_prms$cC, shifter(hier1,n))
}
spp_prms$cC = matrix(spp_prms$cC[1:nRsp,1:nCsp ],nRsp,nCsp)
#Predators:
spp_prms$rP = matrix(rnorm(nPsp,0.5,0.2), nPsp, 1) #intrisic growth
spp_prms$eFp = matrix(1,nPsp,nCsp) # just make the efficiency for everything 1 for now
spp_prms$muP = matrix(rnorm(nPsp,0.6,0.1), nPsp, 1) #mortality rates
#Consumption rates:
#Generate a hierarchy where each species predominantly feeds on particular resource.
dspp = ((nPsp - nCsp))
if(dspp<0){dspp = 0 }
hier1= seq(1/nCsp, (1-1/nCsp), length = nCsp)
spp_prms$cP = hier1
for( n in 1:nPsp) {
spp_prms$cP = cbind(spp_prms$cP, shifter(hier1,n))
}
spp_prms$cP = matrix(spp_prms$cP[1:nCsp,1:nPsp],nCsp,nPsp)
#=============================================================================
# Inner loop. Run the food web model, calculate information theoretic
# quantities.
#=============================================================================
#=============================================================================
# This function gives:
# out The time series for of population growth for each species in the web
# This can be set to just give the final 2 time steps of the web with
# "final = TRUE"
# spp_prms The parameters of all species in the food web
#=============================================================================
# tryCatch( {out1[w] = list(food_web_dynamics (spp_list = c(nRsp,nCsp,nPsp), spp_prms = spp_prms,
# tend, delta1, res_R = NULL,final = FALSE ))}, error = function(e){})
#Random resource fluctuations:
tryCatch( {out1[w] = list(food_web_dynamics (spp_list = c(nRsp,nCsp,nPsp), spp_prms = spp_prms,
tend, delta1, res_R = res_R) )
out1[w] = list(food_web_dynamics (spp_list = c(nRsp,nCsp,nPsp), spp_prms = spp_prms,
tend, delta1, res_R = NULL) )
# print( paste( "nRsp", sum(out1[[w]]$out[tl,1:nRsp]>1) ) )
# print( paste( "nCsp", sum(out1[[w]]$out[tl,(nRsp+1):nCsp]>1) ) )
# print( paste( "nPsp", sum(out1[[w]]$out[tl,(nCsp+1):nPsp]>1) ) )
plot(out1[[w]]$out[,2], t="l", ylim = c(0, max(out1[[w]]$out[tl,],na.rm=T) ),col="red" )
for(n in 2:(nRsp+1)) { lines(out1[[w]]$out[,n], col ="red") }
for(n in (nRsp+2):(nRsp+nCsp+1) ){ lines(out1[[w]]$out[,n], col ="blue") }
for(n in (nRsp+nCsp+1):(nspp+1) ){ lines(out1[[w]]$out[,n]) }
#=============================================================================
# Information theoretic assessment of the foodweb.
#=============================================================================
#=============================================================================
# This section is as per Rutledge, Basore, and Mulholland 1976
#=============================================================================
## This code takes the ODEs and converts them to a biomass balance matrix and
## transition matrix.
## This version creates a compartment for each "event" where biomass is gained
## or loss. This includes birth, death, and "inefficiency" in the form of the
## way that biomass consumed translates to new population biomass.
#=============================================================================
# This function gives:
# Qi(t) Biomass proportion flow through a node at time t
# fij(t) Probability of biomass flow between i and j at t
# fijQi(t) Total biomass flowing from i to j at t
# sD Shannon entropy
# mI_mean Average mutual information
# mI_per Mutual information per interaction
# ce Conditional entropy
#=============================================================================
rweb1[w] = list(rutledge_web( spp_list=c(nRsp,nCsp,nPsp), pop_ts = out1[[w]]$out[,2:(nspp+1)],
spp_prms = out1[[w]]$spp_prms) )
#=============================================================================
# Information processing networks
#=============================================================================
## This code takes the population time-series counts output by the ODEs and
## calculates Excess Entropy, Active Information Storage, and Transfer Entropy.
## Each quantity is calculated at both the average and local level.
#=============================================================================
# This function gives:
# EE_mean Average mutual information per species
# AI_mean Average active information per species
# TE_mean Average transfer entropy per species
#
# EE_local Local mutual information per species
# AI_local Local active information per species
# TE_local Local transfer entropy per species
#=============================================================================
#nt1 = 2/3*tl
nt1 = tl - 100
nt2 = tl
# di_web[w] = list(get_info_dynamics(pop_ts = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
# k=k,with_blocks=FALSE))
# ## This code takes the population time-series counts output by the ODEs and
# ## calculates the average Transfer Entropy from each species to every other
# ## species. The goal is to get an overview of the major information pathways
# ## in the web.
# #=============================================================================
# # This function gives:
# # te_web Average transfer entropy per species as a pairwise matrix
# #=============================================================================
# te_web[w] = list( get_te_web( pop_ts = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
# k=k) )
# ## This code takes the population time-series counts output by the ODEs and
# ## calculates the average Separable Information from each species to every other
# ## species. The goal is to get an overview of the major information pathways
# ## in the web.
# #=============================================================================
# # This function gives:
# # si_web Average separable information per species as a pairwise matrix
# #=============================================================================
# si_web[w] = list( get_si_web( pop_ts = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
# k=k) )
#=============================================================================
# This function gives:
# aiE_web The AI of the entire ensemble, treated as a single time series.
#=============================================================================
aiE_web[w] = list( get_ais ( series1 = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
k=k, ensemble = TRUE) )
#=============================================================================
# This function gives:
# MMI_web The MMI of the entire ensemble, treated as a single time series.
#=============================================================================
MMI_web[w] = list( get_ais ( series1 = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
k=k, ensemble = TRUE) )
}, error = function(e){})
}
#save(file = "rand_fwebmod6F.var", out1, di_web,te_web,si_web)
#save(file = "rand_fwebmod7G.var", out1, rweb1,aiE_web,MMI_web) #These are deterministic
save(file = "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod8C.var", out1, rweb1,aiE_web,MMI_web) #These are stochastic
#=============================================================================
# Load saved foodwebs and look at relationships between function and various
# measures of complexity.
#=============================================================================
#load("/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/rand_fwebmod7G.var")
#This requires user input!
variable.list=list("out1", "di_web", "te_web","si_web")
file.name.list=c(
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7A.var",
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7B.var",
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7C.var",
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7D.var",
"/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7E.var",
"/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7F.var",
"/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7G.var"
)
#Combine the variables from each scenario file into one variable
var.length=length(variable.list)
nscen = length(file.name.list)
out1_all=NULL
rweb1_all = NULL
aiE_web_all = NULL
MMI_web_all = NULL
for (g in 1:nscen){
load(file.name.list[[g]])
nwebs = (!sapply(aiE_web,is.null) )
rweb1_all=c(rweb1_all, rweb1[nwebs ])
aiE_web_all=c(aiE_web_all, aiE_web[nwebs])
MMI_web_all=c(MMI_web_all, MMI_web[nwebs ])
out1_all=c(out1_all, out1[nwebs])
}
#Re-run the loaded variables over a different range if need be:
ncells=length(aiE_web_all)
for (n in 1:ncells){
k=1
tlast = dim(out1_all[[n]]$out)[1] - 1 #Length of time series
nRsp = out1_all[[n]]$spp_prms$nRsp
nCsp = out1_all[[n]]$spp_prms$nCsp
nPsp = out1_all[[n]]$spp_prms$nPsp
nspp = nRsp+nCsp+nPsp
nt1 = tlast - 100
nt2 = tlast
# rweb1_all[n] = list(rutledge_web( spp_list=c(nRsp,nCsp,nPsp), pop_ts = out1_all[[n]]$out[nt1:nt2,2:(nspp+1)],
# spp_prms = out1_all[[n]]$spp_prms, if_conditional = FALSE) )
#=============================================================================
aiE_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,2:(nspp+1)]),
k=k, ensemble = TRUE) )
#=============================================================================
MMI_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,2:(nspp+1)]),
k=k, ensemble = TRUE) )
#Run these without any Resource species for comparison with the real data:
spp_prms1 = out1_all[[n]]$spp_prms
spp_prms1$rR = spp_prms1$rR[nRsp]
spp_prms1$Ki = spp_prms1$Ki[nRsp]
spp_prms1$cC = spp_prms1$cC[nRsp,]
rweb1_all[n] = list(rutledge_web( spp_list=c(1,nCsp,nPsp), pop_ts = out1_all[[n]]$out[nt1:nt2,(1+nRsp):(nspp+1)],
spp_prms = spp_prms1, if_conditional = FALSE) )
#=============================================================================
# aiE_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,(1+nRsp):(nspp+1)]),
# k=k, ensemble = TRUE) )
# #=============================================================================
# MMI_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,(1+nRsp):(nspp+1)]),
# k=k, ensemble = TRUE) )
}
#Take variables out of the lists to plot:
ncells=length(aiE_web_all)
rDIT_sim = data.frame(matrix(0, nrow=ncells, ncol =12) )
ncnames = c("fwno","Biomass", "var_Biomass", "Snspp", "Fnspp", "shannon", "rS","rCE","rMI", "MI",
"AI","eq_state" )
colnames(rDIT_sim) = ncnames
for (n in 1:ncells){
tlast1 = dim(out1_all[[n]]$out)[1] - 1 #Length of time series
tlast2 = dim(aiE_web_all[[n]]$local)[1] - 1 #Length of time series
rDIT_sim$fwno[n] = n
rDIT_sim$Snspp[n] = out1_all[[n]]$spp_prms$nspp #Starting number of species
#####This needs to match the code above -- Are the Rsp being counted or not?
nRsp = out1_all[[n]]$spp_prms$nRsp
rDIT_sim$Fnspp[n] = sum(out1_all[[n]]$out[tlast1,] > 0) - nRsp-1 #Final number of species
rDIT_sim$Biomass[n] = sum(out1_all[[n]]$out[tlast1, 2:(rDIT_sim$Snspp[n]+1) ]) #Biomass at last time
tbck = 1 #tlast*3/4 #Use a subset that excludes transient stage for variance
rDIT_sim$var_Biomass[n] = var( rowSums( out1_all[[n]]$out[ (tlast1-tbck):tlast, 2:(rDIT_sim$Snspp[n]+1) ]) )
#Shannon Diversity
pi = out1_all[[n]]$out[tlast1, 2:(rDIT_sim$Snspp[n]+1) ] / rDIT_sim$Biomass[n]
pi[pi <= 0 ] = NA
rDIT_sim$shannon[n] = - sum( pi*log(pi),na.rm=T )
#Rutledge Shannon Diversity, Conditional Entropy, and Mutual Information:
rDIT_sim$rS[n] = rweb1_all[[n]]$sD[tlast2]
rDIT_sim$rCE[n] = rweb1_all[[n]]$ce2[tlast2]
rDIT_sim$rMI[n] = rweb1_all[[n]]$mI_mean[tlast2]
#Multiple Mutual Information
rDIT_sim$MI[n] = MMI_web_all[[n]]$mean
#Ensemble active information
rDIT_sim$AI[n] = aiE_web_all[[n]]$mean
#Determine whether this was a web in equilibrium (0) or not (1).
eqtf = factor(levels=c(0,1))
eq_test = test_eq( foodweb = out1_all[[n]], eqtest =tlast-50, t_type = "deriv")
if(sum(eq_test)>1) {rDIT_sim$eq_state[n] = levels(eqtf)[2]} else { rDIT_sim$eq_state[n] = levels(eqtf)[1] }
}
rDIT_sim_eq = subset(rDIT_sim, eq_state == 0)
#Log-log
l_rDIT_sim_eq = log (rDIT_sim_eq[,1:9])
#l_rDIT_sim_eq[!is.finite(l_rDIT_sim_eq)] = NA
lm_nspp_sim = lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$Fnspp)
lm_nspp_log_sim = lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$Fnspp)
lm_H_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$shannon)
lm_rS_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rS)
lm_rCE_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rCE)
lm_rMI_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rMI)
lm_rCEMI_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rCE+l_rDIT_sim_eq$rMI)
lm_rSMI_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rS+l_rDIT_sim_eq$rMI)
#Predict data from models to fit to figure
pr_nspp_log_sim = data.frame( Biomass = exp(predict.lm ( lm_nspp_log_sim) ),
Fnspp = exp(l_rDIT_sim_eq$Fnspp ) )
pr_H_sim = data.frame( Biomass = exp(predict( lm_H_sim) ) , shannon =exp(l_rDIT_sim_eq$shannon ) )
pr_rS_sim =data.frame( Biomass = exp(predict (lm_rS_sim ) ), rS= exp(l_rDIT_sim_eq$rS ) )
pr_rCE_sim = data.frame( Biomass = exp(predict(lm_rCE_sim) ), rCE = exp(l_rDIT_sim_eq$rCE ) )
pr_rMI_sim = data.frame( Biomass = exp(predict(lm_rMI_sim) ), rMI = exp(l_rDIT_sim_eq$rMI ) )
#Plot of data with fitted lines:
ggplot ( ) +
geom_point (data= rDIT_sim_eq, aes(x = (Fnspp), y = (Biomass),color = "1" )) +
geom_line ( data = pr_nspp_log_sim, aes(x = (Fnspp), y = (Biomass),color = "1" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (shannon), y = (Biomass),color = "2")) +
geom_line ( data = pr_H_sim, aes(x = shannon, y = Biomass,color = "2" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (rS), y =(Biomass),color = "3")) +
geom_line ( data = pr_rS_sim, aes(x = rS, y = Biomass,color = "3" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rMI), y=(Biomass),color = "4" ) ) +
geom_line ( data = pr_rMI_sim, aes(x = rMI, y = Biomass,color = "4" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rCE), y=(Biomass),color = "5" ) ) +
geom_line ( data = pr_rCE_sim, aes(x = rCE, y = Biomass,color = "5" ) ) +
scale_y_log10()+ scale_x_log10() +
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rSD", "rMI","rCE") )
ggsave("./rsVbio_rands1_sub.pdf", width = 8, height = 10)
#Log-y
lm_nspp_sim = lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$Fnspp)
lm_nspp_log_sim = lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$Fnspp)
lm_H_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$shannon)
lm_rS_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rS)
lm_rCE_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rCE)
lm_rMI_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rMI)
lm_rCEMI_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rCE+rDIT_sim_eq$rMI)
lm_rSMI_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rS+rDIT_sim_eq$rMI)
summary(lm_nspp_sim )
summary(lm_nspp_log_sim )
summary(lm_H_sim )
summary(lm_rS_sim )
summary(lm_rCE_sim)
summary(lm_rMI_sim )
summary(lm_rCEMI_sim )
summary(lm_rSMI_sim )
#Predict data from models to fit to figure
pr_nspp_sim = data.frame( Biomass = coef(lm_nspp_sim)[1] + coef(lm_nspp_sim)[2]* (1:max(rDIT_sim_eq$Fnspp) ),
Fnspp = 1:max(rDIT_sim_eq$Fnspp) )
pr_nspp_log_sim = data.frame( Biomass = exp(coef(lm_nspp_log_sim)[1]) * exp(coef(lm_nspp_log_sim)[2]*(1:max(rDIT_sim_eq$Fnspp)) ),
Fnspp = (1:max(rDIT_sim_eq$Fnspp) ) )
pr_H_sim = data.frame( Biomass = exp(coef(lm_H_sim)[1] ) * exp( coef(lm_H_sim)[2]* seq(0.1,5,0.1) ) ,
shannon = seq(0.1,5,0.1) )
pr_rS_sim =data.frame( Biomass = exp(coef(lm_rS_sim)[1] ) * exp( coef(lm_rS_sim)[2]* seq(0.1,5,0.1) ) ,
rS= seq(0.1,5,0.1) )
pr_rCE_sim = data.frame( Biomass = exp(coef(lm_rCE_sim)[1] ) * exp(coef(lm_rCE_sim)[2]* seq(0.1,5,0.1) ),
rCE = seq(0.1,5,0.1) )
pr_rMI_sim = data.frame( Biomass = exp(coef(lm_rMI_sim)[1] ) * exp( coef(lm_rMI_sim)[2]* seq(0.1,5,0.1) ),
rMI= seq(0.1,5,0.1) )
# pr_rCEMI
#pr_rSMI
#Predict data from models to fit to figure
# pr_nspp_log = data.frame( Biomass = exp(predict.lm ( lm_nspp_log) ),
# Fnspp = exp(l_rDIT_sim_eq$Fnspp ) )
# pr_H = data.frame( Biomass = exp(predict( lm_H) ) , shannon =(l_rDIT_sim_eq$shannon ) )
# pr_rS =data.frame( Biomass = exp(predict (lm_rS ) ), rS= (l_rDIT_sim_eq$rS ) )
# pr_rCE = data.frame( Biomass = exp(predict(lm_rCE) ), rCE = (l_rDIT_sim_eq$rCE ) )
# pr_rMI = data.frame( Biomass = exp(predict(lm_rMI) ), rMI = (l_rDIT_sim_eq$rMI ) )
#Plot of data with fitted lines:
ggplot ( ) +
geom_point (data= rDIT_sim_eq, aes(x = (nspp), y = (Biomass),color = "1" )) +
geom_line ( data = pr_nspp_log_sim, aes(x = (nspp), y = (Biomass),color = "1" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (shannon), y = (Biomass),color = "2")) +
geom_line ( data = pr_H_sim, aes(x = shannon, y = Biomass,color = "2" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (rS), y =(Biomass),color = "3")) +
geom_line ( data = pr_rS_sim, aes(x = rS, y = Biomass,color = "3" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rMI), y=(Biomass),color = "4" ) ) +
geom_line ( data = pr_rMI_sim, aes(x = rMI, y = Biomass,color = "4" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rCE), y=(Biomass),color = "5" ) ) +
geom_line ( data = pr_rCE_sim, aes(x = rCE, y = Biomass,color = "5" ) ) +
scale_y_log10()+
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rSD", "rMI","rCE") )
rDIT_sim_non = subset(rDIT_sim, eq_state == 0)
lm_Snspp = lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$Snspp)
lm_Fnspp = lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$Fnspp)
lm_H=lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$shannon)
lm_rS=lm(I(log(rDIT_sim_eq$Biomass+1))~I(log(rDIT_sim_eq$rS+1) ))
lm_rCE=lm(I(log(rDIT_sim_eq$Biomass+1))~I(log(rDIT_sim_eq$rCE+1) ))
lm_rMI=lm(I(log(rDIT_sim_eq$Biomass+1))~I(log(rDIT_sim_eq$rMI+1) ))
lm_MI=lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$MI)
lm_AI=lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$AI)
summary(lm_Snspp )
summary(lm_Fnspp )
summary(lm_H )
summary(lm_rS )
summary(lm_rCE )
summary(lm_rMI )
summary(lm_MI )
summary(lm_AI )
lm_nspp2 = lm(rDIT_eq$Biomass~rDIT_eq$nspp+rDIT_eq$shannon)
lm_nspp3 = lm(rDIT_eq$Biomass~rDIT_eq$nspp+rDIT_eq$rMI)
lm_nspp4 = lm(rDIT_eq$Biomass~rDIT_eq$nspp+rDIT_eq$MI)
#Plots
ggplot ( ) +
geom_point (data= rDIT_eq, aes(x = Fnspp, y = Biomass,color = "1" )) +
geom_point (data= rDIT_eq,aes(x = shannon, y =Biomass,color = "2")) +
geom_point( data= rDIT_eq,aes (x = rMI, y=Biomass,color = "3" ) ) +
geom_point( data= rDIT_eq,aes (x = MI, y=Biomass,color = "4" ) ) +
geom_point( data= rDIT_eq,aes (x = AI, y=Biomass,color = "5" ) ) +
scale_y_log10()+ scale_x_log10() +
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rMI","MI","AI" ) )
#Plots
ggplot ( ) +
#geom_point (data= rDIT_eq, aes(y = Fnspp, x = Biomass,color = "1" )) +
geom_point (data= rDIT_eq,aes(y = shannon, x =Biomass,color = "2")) +
geom_point (data= rDIT_eq,aes(y = rS, x =Biomass,color = "3")) +
geom_point (data= rDIT_eq,aes(y = rCE, x =Biomass,color = "4")) +
geom_point( data= rDIT_eq,aes (y = rMI, x=Biomass,color = "5" ) ) +
# geom_point( data= rDIT_eq,aes (x = MI, y=Biomass,color = "6" ) ) +
# geom_point( data= rDIT_eq,aes (x = AI, y=Biomass,color = "7" ) ) +
#scale_y_log10()+ scale_x_log10() +
ylab("Complexity (Bits) ")+
xlab("Biomass")+
#scale_color_discrete(name ="", labels = c("# Species", "SDI", "rS","rCE", "rMI","MI","AI" ) )
scale_color_discrete(name ="", labels = c("ShannonDI", "rShannon","rConditional Entropy",
"rMutual Information") )
ggsave("./complexity_v_biomass_all.pdf", width = 8, height = 10)
ggplot ( ) +
geom_point (data= rDIT, aes(x = nspp, y = var_Biomass,color = "1" )) +
geom_point (data= rDIT,aes(x = shannon, y =var_Biomass,color = "2")) +
geom_point( data= rDIT,aes (x = rMI, y=var_Biomass,color = "3" ) ) +
geom_point( data= rDIT,aes (x = MI, y=var_Biomass,color = "4" ) ) +
geom_point( data= rDIT,aes (x = AI, y=var_Biomass,color = "5" ) ) +
#scale_y_log10()+ scale_x_log10() +
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rMI","MI","AI" ) )
lm_nsppv = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp)))
lm_Hv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$shannon)))
lm_rMIv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$rMI)))
lm_MIv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$MI)))
lm_AIv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$AI)))
summary(lm_nsppv )
summary(lm_Hv )
summary(lm_rMIv )
summary(lm_MIv )
summary(lm_AIv )
lm_nsppv2 = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp))+I(log(rDIT$shannon)))
lm_nsppv3 = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp))+I(log(rDIT$rMI)))
lm_nsppv4 = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp))+I(log(rDIT$MI)))
AIC(lm_nsppv,lm_nsppv2,lm_nsppv3,lm_nsppv4 )
#Check population plots:
n=89
n2=61
n3=88
tlast = dim(out1_all[[n]]$out)[1] - 1
nRsp = out1_all[[n]]$spp_prms$nRsp
nCsp = out1_all[[n]]$spp_prms$nCsp
nPsp = out1_all[[n]]$spp_prms$nPsp
plot(out1_all[[n]]$out[,1], t="l", ylim = c(0, max(out1_all[[n]]$out[tlast,],na.rm=T) ) )
for(w in 2:nRsp){ lines(out1_all[[n]]$out[,w], col ="red") }
for(w in (nRsp+2):(nRsp+nCsp+1) ){ lines(out1_all[[n]]$out[,w], col ="blue") }
for(w in (nRsp+nCsp+2):(nRsp+nCsp+nPsp+1) ){ lines(out1_all[[n]]$out[,w]) }
#Files to load
# file.name.list=c(
# "rand_fwebmod6A.var",
# "rand_fwebmod6B.var",
# "rand_fwebmod6C.var",
# "rand_fwebmod6D.var",
# "rand_fwebmod6E.var",
# "rand_fwebmod6F.var"
# )
# #Combine the variables from each scenario file into one variable
# var.length=length(variable.list)
# nscen = length(file.name.list)
# out1_all=NULL
# di_web_all = NULL
# te_web_all = NULL
# si_web_all = NULL
# for (g in 1:nscen){
# load(file.name.list[[g]])
# nwebs = length( di_web[(!sapply(di_web,is.null) ) ])
# di_web_all=c(di_web_all, di_web[(!sapply(di_web,is.null) ) ])
# te_web_all=c(te_web_all, te_web[(!sapply(te_web,is.null) ) ])
# si_web_all=c(si_web_all, si_web[(!sapply(si_web,is.null) ) ])
# out1_all=c(out1_all, out1[1:nwebs])
# }
# #Take variables out of the lists to plot:
# ncells=length(si_web_all)
# rDIT = data.frame(matrix(0, nrow=ncells, ncol =7) )
# ncnames = c("fwno","Biomass", "var_Biomass", "nspp", "shannon", "MI", "AI" )
# colnames(rDIT) = ncnames
# for (n in 1:ncells){
# rDIT$fwno[n] = n
# rDIT$nspp[n] = out1_all[[n]]$spp_prms$nspp #Number of species
# tlast = dim(out1_all[[n]]$out)[1] - 1 #Length of time series
# rDIT$Biomass[n] = sum(out1_all[[n]]$out[tlast, 2:(rDIT$nspp[n]+1) ]) #Biomass at last time
# tbck = tlast*3/4 #Use a subset that excludes transient stage for variance
# rDIT$var_Biomass[n] = var( rowSums( out1_all[[n]]$out[ (tlast-tbck):tlast, 2:(rDIT$nspp[n]+1) ]) )
# #Shannon Diversity
# pi = out1_all[[n]]$out[tlast, 2:(rDIT$nspp[n]+1) ] / rDIT$Biomass[n]
# pi[pi <= 0 ] = NA
# rDIT$shannon[n] = - sum( pi*log(pi),na.rm=T )
# #Sum of Active Information
# aip = (pi*di_web_all[[n]]$ai_means)
# rDIT$AI[n] = sum(aip, na.rm=T)
# }
# lm_nspp = lm(rDIT$Biomass~rDIT$nspp)
# lm_H=lm(rDIT$Biomass~rDIT$shannon)
# lm_AI=lm(rDIT$Biomass~rDIT$AI)
# #Plots
# ggplot (rDIT, aes(x = nspp, y = Biomass,color = "1" ) ) + geom_point () +
# geom_point (aes(x = shannon, y =Biomass,color = "2"))+
# geom_point( aes (x = AI, y=Biomass,color = "3" ) )+
# scale_color_discrete(name ="", labels = c("# Species", "SDI","AI" ) )
| /random_foodwebs/biodiv_info_foodwebs.R | permissive | jusinowicz/info_theory_eco | R | false | false | 27,385 | r | #=============================================================================
# R code to create to explore the Information Theoretic properties of
# simple food webs. This creates a simple food web with an underlying dynamic
# model.
# 1. Food-web includes resource, herbivore, and predator:
# A. Resource is based on a consumer-resource model, with added predators
# 1. Competition between consumers and resources emerges from consumption
# 2. Parameters at each level can be made a function of temperature.
# B. Resources can be stochastic due to environmental fluctuations.
# C. Relative non-linearity allows 2 consumers per Resource
# 2. Generate a bunch of random food webs
# 3. Use information theory to track the resulting food-web structures.
# 4. This file has a lot of code for visualizing output of both the foodweb
# its information theoretic properties after the main loop.
#=============================================================================
#=============================================================================
# load libraries
#=============================================================================
library(deSolve)
library(fields)
library(tidyverse)
library(lubridate)
library(mgcv)
source("../info_theory_functions/food_web_functions.R")
source("../info_theory_functions/info_theory_functions.R")
source("../info_theory_functions/database_functions.R")
#=============================================================================
# Outer loop. Set the number of trials and determine how to generate
# combinations of species and parameters.
#=============================================================================
#Length and time steps of each model run
tend = 25
delta1 = 0.01
tl=tend/delta1
#The maximum block depth for dynamic info metrics (larger is more accurate, but
#slower and could cause crashing if too large)
k= 5
#Number of food webs to generate
nwebs = 1
#Output of each web
out1 = vector("list",nwebs)
#Converting the web to Rutledge's compartment model and calculating the information
#theoretic quantities: Shannon Entropy, Mutual Information, Conditional Entropy
rweb1 = vector("list",nwebs)
#Dynamic information metrics calculated from the (discretized) time series
di_web = vector("list",nwebs)
#Track the average transfer entropy and separable information between each pair of
#species as a way to build a network of information flow through the network.
te_web = vector("list",nwebs)
si_web = vector("list",nwebs)
aiE_web = vector("list",nwebs)
MMI_web = vector("list",nwebs)
#Random resources:
c1 = 1
amp1 = 0.25 #100000 #1/exp(1)
#Random consumers
c2 = 1
amp2 = 0.1
res_R = c(amp1,c1,amp2,c2)
for (w in 1:nwebs){
print(w)
#Assume 3 trophic levels unless otherwise specified.
nRsp = ceiling(runif(1)*4)
nCsp = ceiling(runif(1)*2)
nPsp = ceiling(runif(1)*1)
nspp = nRsp+nCsp+nPsp
#Randomly generate the species parameters for the model as well:
spp_prms = NULL
#Resource: Nearly identical resource dynamics:
spp_prms$rR = matrix(rnorm(nRsp,300,10), nRsp, 1) #intrinsic growth
spp_prms$Ki = matrix(rnorm(nRsp,500,10), nRsp, 1) #carrying capacity
#Consumers:
spp_prms$rC = matrix(rnorm(nCsp,.5,0.2), nCsp, 1) #intrisic growth
spp_prms$eFc = matrix(1,nCsp,nRsp) # just make the efficiency for everything 1 for now
spp_prms$muC = matrix(rnorm(nCsp,0.6,0.1), nCsp, 1) #mortality rates
#Consumption rates:
#Generate a hierarchy where each species predominantly feeds on particular resource.
dspp = abs((nCsp - nRsp))
hier1= seq(1/nRsp, (1-1/nRsp), length=nRsp)
spp_prms$cC = hier1
for( n in 1:nCsp) {
spp_prms$cC = cbind(spp_prms$cC, shifter(hier1,n))
}
spp_prms$cC = matrix(spp_prms$cC[1:nRsp,1:nCsp ],nRsp,nCsp)
#Predators:
spp_prms$rP = matrix(rnorm(nPsp,0.5,0.2), nPsp, 1) #intrisic growth
spp_prms$eFp = matrix(1,nPsp,nCsp) # just make the efficiency for everything 1 for now
spp_prms$muP = matrix(rnorm(nPsp,0.6,0.1), nPsp, 1) #mortality rates
#Consumption rates:
#Generate a hierarchy where each species predominantly feeds on particular resource.
dspp = ((nPsp - nCsp))
if(dspp<0){dspp = 0 }
hier1= seq(1/nCsp, (1-1/nCsp), length = nCsp)
spp_prms$cP = hier1
for( n in 1:nPsp) {
spp_prms$cP = cbind(spp_prms$cP, shifter(hier1,n))
}
spp_prms$cP = matrix(spp_prms$cP[1:nCsp,1:nPsp],nCsp,nPsp)
#=============================================================================
# Inner loop. Run the food web model, calculate information theoretic
# quantities.
#=============================================================================
#=============================================================================
# This function gives:
# out The time series for of population growth for each species in the web
# This can be set to just give the final 2 time steps of the web with
# "final = TRUE"
# spp_prms The parameters of all species in the food web
#=============================================================================
# tryCatch( {out1[w] = list(food_web_dynamics (spp_list = c(nRsp,nCsp,nPsp), spp_prms = spp_prms,
# tend, delta1, res_R = NULL,final = FALSE ))}, error = function(e){})
#Random resource fluctuations:
tryCatch( {out1[w] = list(food_web_dynamics (spp_list = c(nRsp,nCsp,nPsp), spp_prms = spp_prms,
tend, delta1, res_R = res_R) )
out1[w] = list(food_web_dynamics (spp_list = c(nRsp,nCsp,nPsp), spp_prms = spp_prms,
tend, delta1, res_R = NULL) )
# print( paste( "nRsp", sum(out1[[w]]$out[tl,1:nRsp]>1) ) )
# print( paste( "nCsp", sum(out1[[w]]$out[tl,(nRsp+1):nCsp]>1) ) )
# print( paste( "nPsp", sum(out1[[w]]$out[tl,(nCsp+1):nPsp]>1) ) )
plot(out1[[w]]$out[,2], t="l", ylim = c(0, max(out1[[w]]$out[tl,],na.rm=T) ),col="red" )
for(n in 2:(nRsp+1)) { lines(out1[[w]]$out[,n], col ="red") }
for(n in (nRsp+2):(nRsp+nCsp+1) ){ lines(out1[[w]]$out[,n], col ="blue") }
for(n in (nRsp+nCsp+1):(nspp+1) ){ lines(out1[[w]]$out[,n]) }
#=============================================================================
# Information theoretic assessment of the foodweb.
#=============================================================================
#=============================================================================
# This section is as per Rutledge, Basore, and Mulholland 1976
#=============================================================================
## This code takes the ODEs and converts them to a biomass balance matrix and
## transition matrix.
## This version creates a compartment for each "event" where biomass is gained
## or loss. This includes birth, death, and "inefficiency" in the form of the
## way that biomass consumed translates to new population biomass.
#=============================================================================
# This function gives:
# Qi(t) Biomass proportion flow through a node at time t
# fij(t) Probability of biomass flow between i and j at t
# fijQi(t) Total biomass flowing from i to j at t
# sD Shannon entropy
# mI_mean Average mutual information
# mI_per Mutual information per interaction
# ce Conditional entropy
#=============================================================================
rweb1[w] = list(rutledge_web( spp_list=c(nRsp,nCsp,nPsp), pop_ts = out1[[w]]$out[,2:(nspp+1)],
spp_prms = out1[[w]]$spp_prms) )
#=============================================================================
# Information processing networks
#=============================================================================
## This code takes the population time-series counts output by the ODEs and
## calculates Excess Entropy, Active Information Storage, and Transfer Entropy.
## Each quantity is calculated at both the average and local level.
#=============================================================================
# This function gives:
# EE_mean Average mutual information per species
# AI_mean Average active information per species
# TE_mean Average transfer entropy per species
#
# EE_local Local mutual information per species
# AI_local Local active information per species
# TE_local Local transfer entropy per species
#=============================================================================
#nt1 = 2/3*tl
nt1 = tl - 100
nt2 = tl
# di_web[w] = list(get_info_dynamics(pop_ts = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
# k=k,with_blocks=FALSE))
# ## This code takes the population time-series counts output by the ODEs and
# ## calculates the average Transfer Entropy from each species to every other
# ## species. The goal is to get an overview of the major information pathways
# ## in the web.
# #=============================================================================
# # This function gives:
# # te_web Average transfer entropy per species as a pairwise matrix
# #=============================================================================
# te_web[w] = list( get_te_web( pop_ts = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
# k=k) )
# ## This code takes the population time-series counts output by the ODEs and
# ## calculates the average Separable Information from each species to every other
# ## species. The goal is to get an overview of the major information pathways
# ## in the web.
# #=============================================================================
# # This function gives:
# # si_web Average separable information per species as a pairwise matrix
# #=============================================================================
# si_web[w] = list( get_si_web( pop_ts = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
# k=k) )
#=============================================================================
# This function gives:
# aiE_web The AI of the entire ensemble, treated as a single time series.
#=============================================================================
aiE_web[w] = list( get_ais ( series1 = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
k=k, ensemble = TRUE) )
#=============================================================================
# This function gives:
# MMI_web The MMI of the entire ensemble, treated as a single time series.
#=============================================================================
MMI_web[w] = list( get_ais ( series1 = floor(out1[[w]]$out[nt1:tl,2:(nspp+1)]),
k=k, ensemble = TRUE) )
}, error = function(e){})
}
#save(file = "rand_fwebmod6F.var", out1, di_web,te_web,si_web)
#save(file = "rand_fwebmod7G.var", out1, rweb1,aiE_web,MMI_web) #These are deterministic
save(file = "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod8C.var", out1, rweb1,aiE_web,MMI_web) #These are stochastic
#=============================================================================
# Load saved foodwebs and look at relationships between function and various
# measures of complexity.
#=============================================================================
#load("/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/rand_fwebmod7G.var")
#This requires user input!
variable.list=list("out1", "di_web", "te_web","si_web")
file.name.list=c(
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7A.var",
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7B.var",
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7C.var",
# "/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7D.var",
"/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7E.var",
"/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7F.var",
"/Volumes/TOSHIBA\ EXT/backups/mac_2020/Documents/GitHub/info_theory_eco/random_foodwebs/rand_fwebmod7G.var"
)
#Combine the variables from each scenario file into one variable
var.length=length(variable.list)
nscen = length(file.name.list)
out1_all=NULL
rweb1_all = NULL
aiE_web_all = NULL
MMI_web_all = NULL
for (g in 1:nscen){
load(file.name.list[[g]])
nwebs = (!sapply(aiE_web,is.null) )
rweb1_all=c(rweb1_all, rweb1[nwebs ])
aiE_web_all=c(aiE_web_all, aiE_web[nwebs])
MMI_web_all=c(MMI_web_all, MMI_web[nwebs ])
out1_all=c(out1_all, out1[nwebs])
}
#Re-run the loaded variables over a different range if need be:
ncells=length(aiE_web_all)
for (n in 1:ncells){
k=1
tlast = dim(out1_all[[n]]$out)[1] - 1 #Length of time series
nRsp = out1_all[[n]]$spp_prms$nRsp
nCsp = out1_all[[n]]$spp_prms$nCsp
nPsp = out1_all[[n]]$spp_prms$nPsp
nspp = nRsp+nCsp+nPsp
nt1 = tlast - 100
nt2 = tlast
# rweb1_all[n] = list(rutledge_web( spp_list=c(nRsp,nCsp,nPsp), pop_ts = out1_all[[n]]$out[nt1:nt2,2:(nspp+1)],
# spp_prms = out1_all[[n]]$spp_prms, if_conditional = FALSE) )
#=============================================================================
aiE_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,2:(nspp+1)]),
k=k, ensemble = TRUE) )
#=============================================================================
MMI_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,2:(nspp+1)]),
k=k, ensemble = TRUE) )
#Run these without any Resource species for comparison with the real data:
spp_prms1 = out1_all[[n]]$spp_prms
spp_prms1$rR = spp_prms1$rR[nRsp]
spp_prms1$Ki = spp_prms1$Ki[nRsp]
spp_prms1$cC = spp_prms1$cC[nRsp,]
rweb1_all[n] = list(rutledge_web( spp_list=c(1,nCsp,nPsp), pop_ts = out1_all[[n]]$out[nt1:nt2,(1+nRsp):(nspp+1)],
spp_prms = spp_prms1, if_conditional = FALSE) )
#=============================================================================
# aiE_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,(1+nRsp):(nspp+1)]),
# k=k, ensemble = TRUE) )
# #=============================================================================
# MMI_web_all[n] = list( get_ais ( series1 = floor(out1_all[[n]]$out[nt1:nt2,(1+nRsp):(nspp+1)]),
# k=k, ensemble = TRUE) )
}
#Take variables out of the lists to plot:
ncells=length(aiE_web_all)
rDIT_sim = data.frame(matrix(0, nrow=ncells, ncol =12) )
ncnames = c("fwno","Biomass", "var_Biomass", "Snspp", "Fnspp", "shannon", "rS","rCE","rMI", "MI",
"AI","eq_state" )
colnames(rDIT_sim) = ncnames
for (n in 1:ncells){
tlast1 = dim(out1_all[[n]]$out)[1] - 1 #Length of time series
tlast2 = dim(aiE_web_all[[n]]$local)[1] - 1 #Length of time series
rDIT_sim$fwno[n] = n
rDIT_sim$Snspp[n] = out1_all[[n]]$spp_prms$nspp #Starting number of species
#####This needs to match the code above -- Are the Rsp being counted or not?
nRsp = out1_all[[n]]$spp_prms$nRsp
rDIT_sim$Fnspp[n] = sum(out1_all[[n]]$out[tlast1,] > 0) - nRsp-1 #Final number of species
rDIT_sim$Biomass[n] = sum(out1_all[[n]]$out[tlast1, 2:(rDIT_sim$Snspp[n]+1) ]) #Biomass at last time
tbck = 1 #tlast*3/4 #Use a subset that excludes transient stage for variance
rDIT_sim$var_Biomass[n] = var( rowSums( out1_all[[n]]$out[ (tlast1-tbck):tlast, 2:(rDIT_sim$Snspp[n]+1) ]) )
#Shannon Diversity
pi = out1_all[[n]]$out[tlast1, 2:(rDIT_sim$Snspp[n]+1) ] / rDIT_sim$Biomass[n]
pi[pi <= 0 ] = NA
rDIT_sim$shannon[n] = - sum( pi*log(pi),na.rm=T )
#Rutledge Shannon Diversity, Conditional Entropy, and Mutual Information:
rDIT_sim$rS[n] = rweb1_all[[n]]$sD[tlast2]
rDIT_sim$rCE[n] = rweb1_all[[n]]$ce2[tlast2]
rDIT_sim$rMI[n] = rweb1_all[[n]]$mI_mean[tlast2]
#Multiple Mutual Information
rDIT_sim$MI[n] = MMI_web_all[[n]]$mean
#Ensemble active information
rDIT_sim$AI[n] = aiE_web_all[[n]]$mean
#Determine whether this was a web in equilibrium (0) or not (1).
eqtf = factor(levels=c(0,1))
eq_test = test_eq( foodweb = out1_all[[n]], eqtest =tlast-50, t_type = "deriv")
if(sum(eq_test)>1) {rDIT_sim$eq_state[n] = levels(eqtf)[2]} else { rDIT_sim$eq_state[n] = levels(eqtf)[1] }
}
rDIT_sim_eq = subset(rDIT_sim, eq_state == 0)
#Log-log
l_rDIT_sim_eq = log (rDIT_sim_eq[,1:9])
#l_rDIT_sim_eq[!is.finite(l_rDIT_sim_eq)] = NA
lm_nspp_sim = lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$Fnspp)
lm_nspp_log_sim = lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$Fnspp)
lm_H_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$shannon)
lm_rS_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rS)
lm_rCE_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rCE)
lm_rMI_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rMI)
lm_rCEMI_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rCE+l_rDIT_sim_eq$rMI)
lm_rSMI_sim=lm(l_rDIT_sim_eq$Biomass~l_rDIT_sim_eq$rS+l_rDIT_sim_eq$rMI)
#Predict data from models to fit to figure
pr_nspp_log_sim = data.frame( Biomass = exp(predict.lm ( lm_nspp_log_sim) ),
Fnspp = exp(l_rDIT_sim_eq$Fnspp ) )
pr_H_sim = data.frame( Biomass = exp(predict( lm_H_sim) ) , shannon =exp(l_rDIT_sim_eq$shannon ) )
pr_rS_sim =data.frame( Biomass = exp(predict (lm_rS_sim ) ), rS= exp(l_rDIT_sim_eq$rS ) )
pr_rCE_sim = data.frame( Biomass = exp(predict(lm_rCE_sim) ), rCE = exp(l_rDIT_sim_eq$rCE ) )
pr_rMI_sim = data.frame( Biomass = exp(predict(lm_rMI_sim) ), rMI = exp(l_rDIT_sim_eq$rMI ) )
#Plot of data with fitted lines:
ggplot ( ) +
geom_point (data= rDIT_sim_eq, aes(x = (Fnspp), y = (Biomass),color = "1" )) +
geom_line ( data = pr_nspp_log_sim, aes(x = (Fnspp), y = (Biomass),color = "1" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (shannon), y = (Biomass),color = "2")) +
geom_line ( data = pr_H_sim, aes(x = shannon, y = Biomass,color = "2" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (rS), y =(Biomass),color = "3")) +
geom_line ( data = pr_rS_sim, aes(x = rS, y = Biomass,color = "3" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rMI), y=(Biomass),color = "4" ) ) +
geom_line ( data = pr_rMI_sim, aes(x = rMI, y = Biomass,color = "4" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rCE), y=(Biomass),color = "5" ) ) +
geom_line ( data = pr_rCE_sim, aes(x = rCE, y = Biomass,color = "5" ) ) +
scale_y_log10()+ scale_x_log10() +
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rSD", "rMI","rCE") )
ggsave("./rsVbio_rands1_sub.pdf", width = 8, height = 10)
#Log-y
lm_nspp_sim = lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$Fnspp)
lm_nspp_log_sim = lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$Fnspp)
lm_H_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$shannon)
lm_rS_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rS)
lm_rCE_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rCE)
lm_rMI_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rMI)
lm_rCEMI_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rCE+rDIT_sim_eq$rMI)
lm_rSMI_sim=lm(I(log(rDIT_sim_eq$Biomass))~rDIT_sim_eq$rS+rDIT_sim_eq$rMI)
summary(lm_nspp_sim )
summary(lm_nspp_log_sim )
summary(lm_H_sim )
summary(lm_rS_sim )
summary(lm_rCE_sim)
summary(lm_rMI_sim )
summary(lm_rCEMI_sim )
summary(lm_rSMI_sim )
#Predict data from models to fit to figure
pr_nspp_sim = data.frame( Biomass = coef(lm_nspp_sim)[1] + coef(lm_nspp_sim)[2]* (1:max(rDIT_sim_eq$Fnspp) ),
Fnspp = 1:max(rDIT_sim_eq$Fnspp) )
pr_nspp_log_sim = data.frame( Biomass = exp(coef(lm_nspp_log_sim)[1]) * exp(coef(lm_nspp_log_sim)[2]*(1:max(rDIT_sim_eq$Fnspp)) ),
Fnspp = (1:max(rDIT_sim_eq$Fnspp) ) )
pr_H_sim = data.frame( Biomass = exp(coef(lm_H_sim)[1] ) * exp( coef(lm_H_sim)[2]* seq(0.1,5,0.1) ) ,
shannon = seq(0.1,5,0.1) )
pr_rS_sim =data.frame( Biomass = exp(coef(lm_rS_sim)[1] ) * exp( coef(lm_rS_sim)[2]* seq(0.1,5,0.1) ) ,
rS= seq(0.1,5,0.1) )
pr_rCE_sim = data.frame( Biomass = exp(coef(lm_rCE_sim)[1] ) * exp(coef(lm_rCE_sim)[2]* seq(0.1,5,0.1) ),
rCE = seq(0.1,5,0.1) )
pr_rMI_sim = data.frame( Biomass = exp(coef(lm_rMI_sim)[1] ) * exp( coef(lm_rMI_sim)[2]* seq(0.1,5,0.1) ),
rMI= seq(0.1,5,0.1) )
# pr_rCEMI
#pr_rSMI
#Predict data from models to fit to figure
# pr_nspp_log = data.frame( Biomass = exp(predict.lm ( lm_nspp_log) ),
# Fnspp = exp(l_rDIT_sim_eq$Fnspp ) )
# pr_H = data.frame( Biomass = exp(predict( lm_H) ) , shannon =(l_rDIT_sim_eq$shannon ) )
# pr_rS =data.frame( Biomass = exp(predict (lm_rS ) ), rS= (l_rDIT_sim_eq$rS ) )
# pr_rCE = data.frame( Biomass = exp(predict(lm_rCE) ), rCE = (l_rDIT_sim_eq$rCE ) )
# pr_rMI = data.frame( Biomass = exp(predict(lm_rMI) ), rMI = (l_rDIT_sim_eq$rMI ) )
#Plot of data with fitted lines:
ggplot ( ) +
geom_point (data= rDIT_sim_eq, aes(x = (nspp), y = (Biomass),color = "1" )) +
geom_line ( data = pr_nspp_log_sim, aes(x = (nspp), y = (Biomass),color = "1" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (shannon), y = (Biomass),color = "2")) +
geom_line ( data = pr_H_sim, aes(x = shannon, y = Biomass,color = "2" ) ) +
geom_point (data= rDIT_sim_eq,aes(x = (rS), y =(Biomass),color = "3")) +
geom_line ( data = pr_rS_sim, aes(x = rS, y = Biomass,color = "3" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rMI), y=(Biomass),color = "4" ) ) +
geom_line ( data = pr_rMI_sim, aes(x = rMI, y = Biomass,color = "4" ) ) +
geom_point( data= rDIT_sim_eq,aes (x = (rCE), y=(Biomass),color = "5" ) ) +
geom_line ( data = pr_rCE_sim, aes(x = rCE, y = Biomass,color = "5" ) ) +
scale_y_log10()+
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rSD", "rMI","rCE") )
rDIT_sim_non = subset(rDIT_sim, eq_state == 0)
lm_Snspp = lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$Snspp)
lm_Fnspp = lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$Fnspp)
lm_H=lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$shannon)
lm_rS=lm(I(log(rDIT_sim_eq$Biomass+1))~I(log(rDIT_sim_eq$rS+1) ))
lm_rCE=lm(I(log(rDIT_sim_eq$Biomass+1))~I(log(rDIT_sim_eq$rCE+1) ))
lm_rMI=lm(I(log(rDIT_sim_eq$Biomass+1))~I(log(rDIT_sim_eq$rMI+1) ))
lm_MI=lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$MI)
lm_AI=lm(rDIT_sim_eq$Biomass~rDIT_sim_eq$AI)
summary(lm_Snspp )
summary(lm_Fnspp )
summary(lm_H )
summary(lm_rS )
summary(lm_rCE )
summary(lm_rMI )
summary(lm_MI )
summary(lm_AI )
lm_nspp2 = lm(rDIT_eq$Biomass~rDIT_eq$nspp+rDIT_eq$shannon)
lm_nspp3 = lm(rDIT_eq$Biomass~rDIT_eq$nspp+rDIT_eq$rMI)
lm_nspp4 = lm(rDIT_eq$Biomass~rDIT_eq$nspp+rDIT_eq$MI)
#Plots
ggplot ( ) +
geom_point (data= rDIT_eq, aes(x = Fnspp, y = Biomass,color = "1" )) +
geom_point (data= rDIT_eq,aes(x = shannon, y =Biomass,color = "2")) +
geom_point( data= rDIT_eq,aes (x = rMI, y=Biomass,color = "3" ) ) +
geom_point( data= rDIT_eq,aes (x = MI, y=Biomass,color = "4" ) ) +
geom_point( data= rDIT_eq,aes (x = AI, y=Biomass,color = "5" ) ) +
scale_y_log10()+ scale_x_log10() +
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rMI","MI","AI" ) )
#Plots
ggplot ( ) +
#geom_point (data= rDIT_eq, aes(y = Fnspp, x = Biomass,color = "1" )) +
geom_point (data= rDIT_eq,aes(y = shannon, x =Biomass,color = "2")) +
geom_point (data= rDIT_eq,aes(y = rS, x =Biomass,color = "3")) +
geom_point (data= rDIT_eq,aes(y = rCE, x =Biomass,color = "4")) +
geom_point( data= rDIT_eq,aes (y = rMI, x=Biomass,color = "5" ) ) +
# geom_point( data= rDIT_eq,aes (x = MI, y=Biomass,color = "6" ) ) +
# geom_point( data= rDIT_eq,aes (x = AI, y=Biomass,color = "7" ) ) +
#scale_y_log10()+ scale_x_log10() +
ylab("Complexity (Bits) ")+
xlab("Biomass")+
#scale_color_discrete(name ="", labels = c("# Species", "SDI", "rS","rCE", "rMI","MI","AI" ) )
scale_color_discrete(name ="", labels = c("ShannonDI", "rShannon","rConditional Entropy",
"rMutual Information") )
ggsave("./complexity_v_biomass_all.pdf", width = 8, height = 10)
ggplot ( ) +
geom_point (data= rDIT, aes(x = nspp, y = var_Biomass,color = "1" )) +
geom_point (data= rDIT,aes(x = shannon, y =var_Biomass,color = "2")) +
geom_point( data= rDIT,aes (x = rMI, y=var_Biomass,color = "3" ) ) +
geom_point( data= rDIT,aes (x = MI, y=var_Biomass,color = "4" ) ) +
geom_point( data= rDIT,aes (x = AI, y=var_Biomass,color = "5" ) ) +
#scale_y_log10()+ scale_x_log10() +
xlab("#Species, Bits")+
ylab("Biomass")+
scale_color_discrete(name ="", labels = c("# Species", "SDI", "rMI","MI","AI" ) )
lm_nsppv = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp)))
lm_Hv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$shannon)))
lm_rMIv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$rMI)))
lm_MIv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$MI)))
lm_AIv=lm(I(log(rDIT$var_Biomass))~I(log(rDIT$AI)))
summary(lm_nsppv )
summary(lm_Hv )
summary(lm_rMIv )
summary(lm_MIv )
summary(lm_AIv )
lm_nsppv2 = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp))+I(log(rDIT$shannon)))
lm_nsppv3 = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp))+I(log(rDIT$rMI)))
lm_nsppv4 = lm(I(log(rDIT$var_Biomass))~I(log(rDIT$nspp))+I(log(rDIT$MI)))
AIC(lm_nsppv,lm_nsppv2,lm_nsppv3,lm_nsppv4 )
#Check population plots:
n=89
n2=61
n3=88
tlast = dim(out1_all[[n]]$out)[1] - 1
nRsp = out1_all[[n]]$spp_prms$nRsp
nCsp = out1_all[[n]]$spp_prms$nCsp
nPsp = out1_all[[n]]$spp_prms$nPsp
plot(out1_all[[n]]$out[,1], t="l", ylim = c(0, max(out1_all[[n]]$out[tlast,],na.rm=T) ) )
for(w in 2:nRsp){ lines(out1_all[[n]]$out[,w], col ="red") }
for(w in (nRsp+2):(nRsp+nCsp+1) ){ lines(out1_all[[n]]$out[,w], col ="blue") }
for(w in (nRsp+nCsp+2):(nRsp+nCsp+nPsp+1) ){ lines(out1_all[[n]]$out[,w]) }
#Files to load
# file.name.list=c(
# "rand_fwebmod6A.var",
# "rand_fwebmod6B.var",
# "rand_fwebmod6C.var",
# "rand_fwebmod6D.var",
# "rand_fwebmod6E.var",
# "rand_fwebmod6F.var"
# )
# #Combine the variables from each scenario file into one variable
# var.length=length(variable.list)
# nscen = length(file.name.list)
# out1_all=NULL
# di_web_all = NULL
# te_web_all = NULL
# si_web_all = NULL
# for (g in 1:nscen){
# load(file.name.list[[g]])
# nwebs = length( di_web[(!sapply(di_web,is.null) ) ])
# di_web_all=c(di_web_all, di_web[(!sapply(di_web,is.null) ) ])
# te_web_all=c(te_web_all, te_web[(!sapply(te_web,is.null) ) ])
# si_web_all=c(si_web_all, si_web[(!sapply(si_web,is.null) ) ])
# out1_all=c(out1_all, out1[1:nwebs])
# }
# #Take variables out of the lists to plot:
# ncells=length(si_web_all)
# rDIT = data.frame(matrix(0, nrow=ncells, ncol =7) )
# ncnames = c("fwno","Biomass", "var_Biomass", "nspp", "shannon", "MI", "AI" )
# colnames(rDIT) = ncnames
# for (n in 1:ncells){
# rDIT$fwno[n] = n
# rDIT$nspp[n] = out1_all[[n]]$spp_prms$nspp #Number of species
# tlast = dim(out1_all[[n]]$out)[1] - 1 #Length of time series
# rDIT$Biomass[n] = sum(out1_all[[n]]$out[tlast, 2:(rDIT$nspp[n]+1) ]) #Biomass at last time
# tbck = tlast*3/4 #Use a subset that excludes transient stage for variance
# rDIT$var_Biomass[n] = var( rowSums( out1_all[[n]]$out[ (tlast-tbck):tlast, 2:(rDIT$nspp[n]+1) ]) )
# #Shannon Diversity
# pi = out1_all[[n]]$out[tlast, 2:(rDIT$nspp[n]+1) ] / rDIT$Biomass[n]
# pi[pi <= 0 ] = NA
# rDIT$shannon[n] = - sum( pi*log(pi),na.rm=T )
# #Sum of Active Information
# aip = (pi*di_web_all[[n]]$ai_means)
# rDIT$AI[n] = sum(aip, na.rm=T)
# }
# lm_nspp = lm(rDIT$Biomass~rDIT$nspp)
# lm_H=lm(rDIT$Biomass~rDIT$shannon)
# lm_AI=lm(rDIT$Biomass~rDIT$AI)
# #Plots
# ggplot (rDIT, aes(x = nspp, y = Biomass,color = "1" ) ) + geom_point () +
# geom_point (aes(x = shannon, y =Biomass,color = "2"))+
# geom_point( aes (x = AI, y=Biomass,color = "3" ) )+
# scale_color_discrete(name ="", labels = c("# Species", "SDI","AI" ) )
|
library(gsheet)
library(magrittr)
library(ggplot2)
##If you don't have the above packages installed, use: install.packages(c("gsheet", "magrittr", "ggplot2"))
#reading in URL from Scott's google drive
url1 <- "https://docs.google.com/spreadsheets/d/1zUaj1RRCJ5S4LzJaAOQvKrtOwWTDRYMXY3uIj5VQ57c/edit?usp=sharing"
#If you want to look at the data, this reads it in and converts it to a data.frame
data1 <- gsheet2tbl(url1) %>% as.data.frame()
library(dplyr)
data2 <- data1 %>% mutate(per.change = (peak.catch - current.catch)/peak.catch)
#plotting total catch change from peak and primary production
g1 <- data2 %>% ggplot(aes(primary.prod, per.change)) +
geom_point(size = 5, alpha = 0.5) +
theme_bw() +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18)) +
geom_text(aes(label = country), size = 7, vjust = -0.5);g1
g3 <- data2 %>% ggplot(aes(primary.prod, peak.catch)) +
geom_point(size = 5, alpha = 0.5) +
theme_bw() +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18)) +
geom_text(aes(label = country), size = 7, vjust = -0.5);g3
#plotting total catch change by continent
g2 <- data2 %>% ggplot(aes(continent, peak.year)) +
geom_boxplot() +
geom_point(size = 5, alpha = 0.7) +
theme_bw() +
xlab("Continent") +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18));g2
#plotting total catch change by continent
g4 <- data2 %>% ggplot(aes(continent, per.change)) +
geom_boxplot() +
geom_point(size = 5, alpha = 0.7) +
theme_bw() +
xlab("Continent") +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18));g4
| /Catch change and productivity.R | no_license | jspmccain/Cutting-Edge-in-Marine-Science---Course-Resources | R | false | false | 1,764 | r | library(gsheet)
library(magrittr)
library(ggplot2)
##If you don't have the above packages installed, use: install.packages(c("gsheet", "magrittr", "ggplot2"))
#reading in URL from Scott's google drive
url1 <- "https://docs.google.com/spreadsheets/d/1zUaj1RRCJ5S4LzJaAOQvKrtOwWTDRYMXY3uIj5VQ57c/edit?usp=sharing"
#If you want to look at the data, this reads it in and converts it to a data.frame
data1 <- gsheet2tbl(url1) %>% as.data.frame()
library(dplyr)
data2 <- data1 %>% mutate(per.change = (peak.catch - current.catch)/peak.catch)
#plotting total catch change from peak and primary production
g1 <- data2 %>% ggplot(aes(primary.prod, per.change)) +
geom_point(size = 5, alpha = 0.5) +
theme_bw() +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18)) +
geom_text(aes(label = country), size = 7, vjust = -0.5);g1
g3 <- data2 %>% ggplot(aes(primary.prod, peak.catch)) +
geom_point(size = 5, alpha = 0.5) +
theme_bw() +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18)) +
geom_text(aes(label = country), size = 7, vjust = -0.5);g3
#plotting total catch change by continent
g2 <- data2 %>% ggplot(aes(continent, peak.year)) +
geom_boxplot() +
geom_point(size = 5, alpha = 0.7) +
theme_bw() +
xlab("Continent") +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18));g2
#plotting total catch change by continent
g4 <- data2 %>% ggplot(aes(continent, per.change)) +
geom_boxplot() +
geom_point(size = 5, alpha = 0.7) +
theme_bw() +
xlab("Continent") +
theme(axis.title = element_text(size = 20),
axis.text = element_text(size = 18));g4
|
library("ggplot2")
library("dplyr")
df <- data_frame(x.to = c( 2, 3, 3, 2,-2,-3,-3,-2),
y.to = c( 3, 2,-2,-3,-3,-2, 2, 3),
x = 0,
y = 0,
x_gt_y = abs(x.to) > abs(y.to),
xy_sign = sign(x.to*y.to) == 1,
x_gt_y_equal_xy_sign = x_gt_y == xy_sign)
ggplot(df) +
geom_segment(aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y, linetype = !xy_sign),
arrow = arrow(length = unit(0.25,"cm"))) +
coord_equal()
ggplot(df) +
geom_curve(aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y_equal_xy_sign),
curvature = 0.75, angle = -45,
arrow = arrow(length = unit(0.25,"cm"))) +
coord_equal() +
theme(legend.position = "bottom") +
xlim(-4, 4) + ylim(-4,4)
ggplot() +
geom_curve(data = df %>% filter(x_gt_y_equal_xy_sign),
aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y_equal_xy_sign),
curvature = 0.75, angle = -45,
arrow = arrow(length = unit(0.25,"cm"))) +
geom_curve(data = df %>% filter(!x_gt_y_equal_xy_sign),
aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y_equal_xy_sign),
curvature =-0.75, angle = 45,
arrow = arrow(length = unit(0.25,"cm"))) +
coord_equal() +
theme(legend.position = "bottom") +
xlim(-4, 4) + ylim(-4,4)
| /028-chess-paths-viz/geom_curve.R | permissive | Poissonfish/r-posts | R | false | false | 1,450 | r | library("ggplot2")
library("dplyr")
df <- data_frame(x.to = c( 2, 3, 3, 2,-2,-3,-3,-2),
y.to = c( 3, 2,-2,-3,-3,-2, 2, 3),
x = 0,
y = 0,
x_gt_y = abs(x.to) > abs(y.to),
xy_sign = sign(x.to*y.to) == 1,
x_gt_y_equal_xy_sign = x_gt_y == xy_sign)
ggplot(df) +
geom_segment(aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y, linetype = !xy_sign),
arrow = arrow(length = unit(0.25,"cm"))) +
coord_equal()
ggplot(df) +
geom_curve(aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y_equal_xy_sign),
curvature = 0.75, angle = -45,
arrow = arrow(length = unit(0.25,"cm"))) +
coord_equal() +
theme(legend.position = "bottom") +
xlim(-4, 4) + ylim(-4,4)
ggplot() +
geom_curve(data = df %>% filter(x_gt_y_equal_xy_sign),
aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y_equal_xy_sign),
curvature = 0.75, angle = -45,
arrow = arrow(length = unit(0.25,"cm"))) +
geom_curve(data = df %>% filter(!x_gt_y_equal_xy_sign),
aes(x = x, y = y, xend = x.to, yend = y.to, color = x_gt_y_equal_xy_sign),
curvature =-0.75, angle = 45,
arrow = arrow(length = unit(0.25,"cm"))) +
coord_equal() +
theme(legend.position = "bottom") +
xlim(-4, 4) + ylim(-4,4)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/uncertMABC.R
\name{uncertMABC}
\alias{uncertMABC}
\title{Uncertainty of the Magnitude of the Air Buoyancy Correction factor}
\usage{
uncertMABC(rho = 0.998, rho_w = 8, rho_air = NULL, u_rho = 1e-04,
u_rho_w = 0.006, u_rho_air = NULL, plot = TRUE, printRelSD = TRUE)
}
\arguments{
\item{rho}{density of the sample in \eqn{g~cm^{-3}}}
\item{rho_w}{density of the weigths in \eqn{g~cm^{-3}}}
\item{rho_air}{density of the air in \eqn{g~cm^{-3}}.
If not provided, the value returned by the function \code{\link[=airDensity]{airDensity()}} with no
parameters is used. See \code{\link[=airDensity]{airDensity()}} for details.}
\item{u_rho}{standard uncertainty of the sample density.}
\item{u_rho_w}{standard uncertainty of the mass standard density.}
\item{u_rho_air}{standard uncertainty of air density.
See \code{\link[=uncertAirDensity]{uncertAirDensity()}}.}
\item{plot}{logical. If \code{TRUE} (the default), the relative
uncertainty contributions are shown in a \link[graphics]{barplot}.}
\item{printRelSD}{Logical. If \code{TRUE} (the default), a short
statement indicating relative standard uncertainty
of the air density estimation is printed.}
}
\value{
Numeric value of uncertainty for the Magnitude of the Air Buoyancy Correction factor.
}
\description{
Propagates density uncertainties in the calculation
of the Magnitude of Air Buoyancy Correction (See \code{\link[=MABC]{MABC()}}).
}
\details{
Calculations are made according to the
Guide to the Guide to the expression of uncertainty in
measurement (GUM, JCGM, 2008) as implemented
by the package \link[metRology]{metRology} (Ellison, 2018).
If air density and associated uncertainty
are not provided the default output values of the
functions \code{\link[=airDensity]{airDensity()}} and \code{\link[=uncertAirDensity]{uncertAirDensity()}}, respectively, are used.
}
\references{
BIMP JCGM (2008) Evaluation of measurement data — Guide
to the expression of uncertainty in measurement.
Andrej-Nikolai Spiess (2018). propagate: Propagation of
Uncertainty. R package version 1.0-6.
https://CRAN.R-project.org/package=propagate
}
| /man/uncertMABC.Rd | no_license | cran/masscor | R | false | true | 2,178 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/uncertMABC.R
\name{uncertMABC}
\alias{uncertMABC}
\title{Uncertainty of the Magnitude of the Air Buoyancy Correction factor}
\usage{
uncertMABC(rho = 0.998, rho_w = 8, rho_air = NULL, u_rho = 1e-04,
u_rho_w = 0.006, u_rho_air = NULL, plot = TRUE, printRelSD = TRUE)
}
\arguments{
\item{rho}{density of the sample in \eqn{g~cm^{-3}}}
\item{rho_w}{density of the weigths in \eqn{g~cm^{-3}}}
\item{rho_air}{density of the air in \eqn{g~cm^{-3}}.
If not provided, the value returned by the function \code{\link[=airDensity]{airDensity()}} with no
parameters is used. See \code{\link[=airDensity]{airDensity()}} for details.}
\item{u_rho}{standard uncertainty of the sample density.}
\item{u_rho_w}{standard uncertainty of the mass standard density.}
\item{u_rho_air}{standard uncertainty of air density.
See \code{\link[=uncertAirDensity]{uncertAirDensity()}}.}
\item{plot}{logical. If \code{TRUE} (the default), the relative
uncertainty contributions are shown in a \link[graphics]{barplot}.}
\item{printRelSD}{Logical. If \code{TRUE} (the default), a short
statement indicating relative standard uncertainty
of the air density estimation is printed.}
}
\value{
Numeric value of uncertainty for the Magnitude of the Air Buoyancy Correction factor.
}
\description{
Propagates density uncertainties in the calculation
of the Magnitude of Air Buoyancy Correction (See \code{\link[=MABC]{MABC()}}).
}
\details{
Calculations are made according to the
Guide to the Guide to the expression of uncertainty in
measurement (GUM, JCGM, 2008) as implemented
by the package \link[metRology]{metRology} (Ellison, 2018).
If air density and associated uncertainty
are not provided the default output values of the
functions \code{\link[=airDensity]{airDensity()}} and \code{\link[=uncertAirDensity]{uncertAirDensity()}}, respectively, are used.
}
\references{
BIMP JCGM (2008) Evaluation of measurement data — Guide
to the expression of uncertainty in measurement.
Andrej-Nikolai Spiess (2018). propagate: Propagation of
Uncertainty. R package version 1.0-6.
https://CRAN.R-project.org/package=propagate
}
|
## This function creates a special "matrix" object that can cache its inverse.
## it fist sets the value of the matrix
## gets the value of the matrix
## set the value of the inverse
## gets the value of the inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function computes the inverse of the special matrix returned by makeCacheMatrix
## If the matrix has already been solved and the matrix has not changed
## then it returns the solved matrix from cache
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data)
x$setinverse(m)
m
}
| /cachematrix.R | no_license | khehla/ProgrammingAssignment2 | R | false | false | 1,122 | r | ## This function creates a special "matrix" object that can cache its inverse.
## it fist sets the value of the matrix
## gets the value of the matrix
## set the value of the inverse
## gets the value of the inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function computes the inverse of the special matrix returned by makeCacheMatrix
## If the matrix has already been solved and the matrix has not changed
## then it returns the solved matrix from cache
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data)
x$setinverse(m)
m
}
|
vpAFC<-
function (X)
{
result <- dudi.coa(data.frame(matrix(X, nrow = nrow(X))),
scannf = FALSE, nf = 1)$eig[1]
result
}
| /RcmdrPlugin.pointG/R/vpAFC.R | no_license | ingted/R-Examples | R | false | false | 148 | r | vpAFC<-
function (X)
{
result <- dudi.coa(data.frame(matrix(X, nrow = nrow(X))),
scannf = FALSE, nf = 1)$eig[1]
result
}
|
library(plotrix)
#load "2132_CRISPR_KO_Plasmid-designs" as "PlasmidDesigns"
#load "2132_CRISPR_KO_Plasmid-genes" as "PlasmidGenes"
#quality assurance: plot number of reads vs. number of targets
read.distr.targets=function(PlasmidDesigns){ # new function that requires 1 dataset (PlasmidDesigns)
targetcount=c(PlasmidDesigns$match) # vector with all targetcounts
#meandesigns=mean(targetcount)
#cat("The mean of reads per target is",meandesigns,"\n")
hist(targetcount,breaks=100,col="blue",xlab="number of reads (per target)",ylab="number of targets",main="read distribution") # plot number of targets vs. number of reads (read distribution)
hist(targetcount,breaks=200,xlim=c(0,3000),col="blue",,xlab="number of reads (per target)",ylab="number of targets",main="read distribution") # with 2 different limits for the x-Axis
}
#quality assurance: plot number of reads vs. number of genes
read.distr.genes=function(PlasmidGenes){ # new function that requires 1 dataset (PlasmidGenes)
genecount=c(PlasmidGenes$match) # vector with all genecounts
#meangenes=mean(genecount)
#cat("The mean of reads per gene is",meangenes,"\n")
hist(genecount,breaks=100,col="blue",xlab="number of reads (per gene)",ylab="number of genes",main="read distribution") # plot number of genes vs. number of reads (read distribution)
hist(genecount,breaks=1000,xlim=c(0,15000),col="blue",,xlab="number of reads (per gene)",ylab="number of genes",main="read distribution") # with 2 different limits for the x-Axis
}
#quality assurance: plot number of targets vs. number of reads
read.depth.tar=function(PlasmidDesigns){ # new function that requires 1 dataset (PlasmidDesigns)
targetcount=c(PlasmidDesigns$match) # vector with all targetcounts
meantargets=mean(targetcount) # compute mean for all targetcounts
barplot(targetcount,xlab="targets",ylab="number of reads",main="read depth (targets)") # plot number of reads vs. targets
abline(h=meantargets,col="red",lty=2,lwd=2) # add mean line
legend("topright",c("mean"),cex=0.8,col="red",lty=2,lwd=2) # and a legend
}
#quality assurance: plot number of genes vs. number of reads
read.depth.gene=function(PlasmidGenes){ # new function that requires 1 dataset (PlasmidDesigns)
genecount=c(PlasmidGenes$match) # vector with all genecounts
meangenes=mean(genecount) # compute mean for all genecounts
barplot(genecount,xlab="genes",ylab="number of reads",main="read depth (genes)") # plot number of reads vs. genes
abline(h=meangenes,col="red",lty=2,lwd=2) # add mean line
legend("topleft",c("mean"),cex=0.8,col="red",lty=2,lwd=2) # and a legend
gap.barplot(genecount,gap=c(21000,160000),xlab="genes",ylab="number of reads",main="read depth (genes)",ytics=c(0,5000,10000,15000,20000,165000,170000)) # plot number of reads vs. genes with gaped y-Axis
abline(h=meangenes,col="red",lty=2,lwd=2) # add mean line
legend("topleft",c("mean"),cex=0.8,col="red",lty=2,lwd=2) # and a legend
}
#mean (per gene) vs. variance (per gene)
mean.var.pergene=function(PlasmidDesigns,PlasmidGenes){ # new function that requires 2 datasets (PlasmidDesigns,PlasmidGenes)
genecount=c(PlasmidGenes$match) # vector with all genecounts
designspergene=c(PlasmidGenes$X..designs.total) # vector with number of designs per gene
meanpergene=c(NA,NA)
for(i in 1:length(genecount)){ # compute mean
meanpergene[i]=genecount[i]/designspergene[i] # per design per gene
}
designcount=c(PlasmidDesigns$match) # vector with all targetcounts
varpergene=c(NA,NA) #
j=1 #
for(i in 1:length(genecount)){ # compute the variance
varpergene[i]=var(designcount[j:(j+(designspergene[i]-1))]) # between all targets of one gene
if(is.na(varpergene[i])){ #
varpergene[i]=0 # set variance=0 if there is only one target
} #
j=(j+designspergene[i]) #
}
cormeanvar=cor(meanpergene,varpergene,method="pearson") # compute corralation coefficient between mean and variance
cormeanvar=round(cormeanvar,digits=4) # round
plot(meanpergene,varpergene,xlab="mean (per gene)",ylab="variance (per gene)") # plot variance per gene vs. mean per gene
legend("topright",c("the correlation coefficient is:",cormeanvar),cex=0.6) # add correlation coefficient to the plot
#cat ("The pearson's correlation coefficient (mean per genes vs. variance per gene) is:",cormeanvar,"\n")
}
read.distr.targets(PlasmidDesigns) #
read.distr.genes(PlasmidGenes) #
read.depth.tar(PlasmidDesigns) # execute all the functions
read.depth.gene(PlasmidGenes) #
mean.var.pergene(PlasmidDesigns,PlasmidGenes) #
| /2.6.14 qual.assur.R | no_license | JulianKirschstein/GitHub-RScripts | R | false | false | 5,756 | r | library(plotrix)
#load "2132_CRISPR_KO_Plasmid-designs" as "PlasmidDesigns"
#load "2132_CRISPR_KO_Plasmid-genes" as "PlasmidGenes"
#quality assurance: plot number of reads vs. number of targets
read.distr.targets=function(PlasmidDesigns){ # new function that requires 1 dataset (PlasmidDesigns)
targetcount=c(PlasmidDesigns$match) # vector with all targetcounts
#meandesigns=mean(targetcount)
#cat("The mean of reads per target is",meandesigns,"\n")
hist(targetcount,breaks=100,col="blue",xlab="number of reads (per target)",ylab="number of targets",main="read distribution") # plot number of targets vs. number of reads (read distribution)
hist(targetcount,breaks=200,xlim=c(0,3000),col="blue",,xlab="number of reads (per target)",ylab="number of targets",main="read distribution") # with 2 different limits for the x-Axis
}
#quality assurance: plot number of reads vs. number of genes
read.distr.genes=function(PlasmidGenes){ # new function that requires 1 dataset (PlasmidGenes)
genecount=c(PlasmidGenes$match) # vector with all genecounts
#meangenes=mean(genecount)
#cat("The mean of reads per gene is",meangenes,"\n")
hist(genecount,breaks=100,col="blue",xlab="number of reads (per gene)",ylab="number of genes",main="read distribution") # plot number of genes vs. number of reads (read distribution)
hist(genecount,breaks=1000,xlim=c(0,15000),col="blue",,xlab="number of reads (per gene)",ylab="number of genes",main="read distribution") # with 2 different limits for the x-Axis
}
#quality assurance: plot number of targets vs. number of reads
read.depth.tar=function(PlasmidDesigns){ # new function that requires 1 dataset (PlasmidDesigns)
targetcount=c(PlasmidDesigns$match) # vector with all targetcounts
meantargets=mean(targetcount) # compute mean for all targetcounts
barplot(targetcount,xlab="targets",ylab="number of reads",main="read depth (targets)") # plot number of reads vs. targets
abline(h=meantargets,col="red",lty=2,lwd=2) # add mean line
legend("topright",c("mean"),cex=0.8,col="red",lty=2,lwd=2) # and a legend
}
#quality assurance: plot number of genes vs. number of reads
read.depth.gene=function(PlasmidGenes){ # new function that requires 1 dataset (PlasmidDesigns)
genecount=c(PlasmidGenes$match) # vector with all genecounts
meangenes=mean(genecount) # compute mean for all genecounts
barplot(genecount,xlab="genes",ylab="number of reads",main="read depth (genes)") # plot number of reads vs. genes
abline(h=meangenes,col="red",lty=2,lwd=2) # add mean line
legend("topleft",c("mean"),cex=0.8,col="red",lty=2,lwd=2) # and a legend
gap.barplot(genecount,gap=c(21000,160000),xlab="genes",ylab="number of reads",main="read depth (genes)",ytics=c(0,5000,10000,15000,20000,165000,170000)) # plot number of reads vs. genes with gaped y-Axis
abline(h=meangenes,col="red",lty=2,lwd=2) # add mean line
legend("topleft",c("mean"),cex=0.8,col="red",lty=2,lwd=2) # and a legend
}
#mean (per gene) vs. variance (per gene)
mean.var.pergene=function(PlasmidDesigns,PlasmidGenes){ # new function that requires 2 datasets (PlasmidDesigns,PlasmidGenes)
genecount=c(PlasmidGenes$match) # vector with all genecounts
designspergene=c(PlasmidGenes$X..designs.total) # vector with number of designs per gene
meanpergene=c(NA,NA)
for(i in 1:length(genecount)){ # compute mean
meanpergene[i]=genecount[i]/designspergene[i] # per design per gene
}
designcount=c(PlasmidDesigns$match) # vector with all targetcounts
varpergene=c(NA,NA) #
j=1 #
for(i in 1:length(genecount)){ # compute the variance
varpergene[i]=var(designcount[j:(j+(designspergene[i]-1))]) # between all targets of one gene
if(is.na(varpergene[i])){ #
varpergene[i]=0 # set variance=0 if there is only one target
} #
j=(j+designspergene[i]) #
}
cormeanvar=cor(meanpergene,varpergene,method="pearson") # compute corralation coefficient between mean and variance
cormeanvar=round(cormeanvar,digits=4) # round
plot(meanpergene,varpergene,xlab="mean (per gene)",ylab="variance (per gene)") # plot variance per gene vs. mean per gene
legend("topright",c("the correlation coefficient is:",cormeanvar),cex=0.6) # add correlation coefficient to the plot
#cat ("The pearson's correlation coefficient (mean per genes vs. variance per gene) is:",cormeanvar,"\n")
}
read.distr.targets(PlasmidDesigns) #
read.distr.genes(PlasmidGenes) #
read.depth.tar(PlasmidDesigns) # execute all the functions
read.depth.gene(PlasmidGenes) #
mean.var.pergene(PlasmidDesigns,PlasmidGenes) #
|
#Package&Source
source("DSC425-Util.R")
library("ggplot2")
library(tseries)
library(fBasics)
library(zoo)
library(lmtest)
library(TSA)
#Import data
myd=read.csv('Online Retail.csv', header=T)
#Check firsr six rows
head(myd)
#Create sales
myd$Sales=myd$UnitPrice*myd$Quantity
head(myd$Sales)
myd$InvoiceDate=as.Date(myd$InvoiceDate,"%m/%d/%Y")
head(myd)
myd$Sales=as.numeric(myd$Sales)
dim(myd)
#Select the sales and quantity that > 0
positive=subset(myd, Sales>0 & Quantity>0)
dim(positive)
#Plot
ggplot(positive, aes(x=positive$InvoiceDate, y=positive$Sales)) + geom_line(color="black")+ylim(c(0,500))+xlab("Invoice Date")+ylab("Sales")
acf(positive$Sales, lag=50, main="Sales")
pacf(positive$Sales, lag=50, main="Sales")
eacf(myd$Sales,10,10)
# AUTO.ARIMA SELECTS ARMA(P,Q) MODEL BASED ON AIC OR BIC
library(forecast)
# optimal w.r.t. BIC criterion
auto.arima(positive$Sales, max.P=8, max.Q=8, ic="bic")
# optimal w.r.t. AIC criterion
auto.arima(positive$Sales, max.P=8, max.Q=8, ic="aic")
m1= arima(myd$Sales, order=c(5,0,2), method='ML', include.mean=T)
coeftest(m1)
m2= arima(myd$Sales, order=c(5,0,3), method='ML', include.mean=T)
coeftest(m2)
loadPkg("fUnitRoots")
adfTest(positive$Sales, lags=50, type="nc") # Bare test for unit root
adfTest(positive$Sales, lags=50, type="c") # Is it stationary after subtracting drift
adfTest(positive$Sales, lags=50, type="ct") # Is it stationary after subtracting drift and trend
library(forecast)
# optimal w.r.t. BIC criterion
auto.arima(positive$Sales, max.P=8, max.Q=8)
m1=arima(positive$Sales, order=c(1,0,2))
coeftest(m1)
acf(m1$residuals, main="Series Residuals", lag.max = 50)
pacf(m1$residuals, main="Series Residuals")
normplot(m1$residuals)
Box.test(m1$residuals, lag = 10,ctype = "Ljung-Box")
ntest=round(length(positive$Sales)*0.8) #size of testing set
source("backtest.R")
pm3 = backtest(m1, positive$Sales, ntest, 1,inc.mean=F)
| /Assignment #3- Problem 1.R | no_license | ZehongZ/British-Online-Sales-Predictions | R | false | false | 1,916 | r | #Package&Source
source("DSC425-Util.R")
library("ggplot2")
library(tseries)
library(fBasics)
library(zoo)
library(lmtest)
library(TSA)
#Import data
myd=read.csv('Online Retail.csv', header=T)
#Check firsr six rows
head(myd)
#Create sales
myd$Sales=myd$UnitPrice*myd$Quantity
head(myd$Sales)
myd$InvoiceDate=as.Date(myd$InvoiceDate,"%m/%d/%Y")
head(myd)
myd$Sales=as.numeric(myd$Sales)
dim(myd)
#Select the sales and quantity that > 0
positive=subset(myd, Sales>0 & Quantity>0)
dim(positive)
#Plot
ggplot(positive, aes(x=positive$InvoiceDate, y=positive$Sales)) + geom_line(color="black")+ylim(c(0,500))+xlab("Invoice Date")+ylab("Sales")
acf(positive$Sales, lag=50, main="Sales")
pacf(positive$Sales, lag=50, main="Sales")
eacf(myd$Sales,10,10)
# AUTO.ARIMA SELECTS ARMA(P,Q) MODEL BASED ON AIC OR BIC
library(forecast)
# optimal w.r.t. BIC criterion
auto.arima(positive$Sales, max.P=8, max.Q=8, ic="bic")
# optimal w.r.t. AIC criterion
auto.arima(positive$Sales, max.P=8, max.Q=8, ic="aic")
m1= arima(myd$Sales, order=c(5,0,2), method='ML', include.mean=T)
coeftest(m1)
m2= arima(myd$Sales, order=c(5,0,3), method='ML', include.mean=T)
coeftest(m2)
loadPkg("fUnitRoots")
adfTest(positive$Sales, lags=50, type="nc") # Bare test for unit root
adfTest(positive$Sales, lags=50, type="c") # Is it stationary after subtracting drift
adfTest(positive$Sales, lags=50, type="ct") # Is it stationary after subtracting drift and trend
library(forecast)
# optimal w.r.t. BIC criterion
auto.arima(positive$Sales, max.P=8, max.Q=8)
m1=arima(positive$Sales, order=c(1,0,2))
coeftest(m1)
acf(m1$residuals, main="Series Residuals", lag.max = 50)
pacf(m1$residuals, main="Series Residuals")
normplot(m1$residuals)
Box.test(m1$residuals, lag = 10,ctype = "Ljung-Box")
ntest=round(length(positive$Sales)*0.8) #size of testing set
source("backtest.R")
pm3 = backtest(m1, positive$Sales, ntest, 1,inc.mean=F)
|
#module load Java/1.8.0_144
#database=/gstore/data/omni/crispr/flashfry/cas9_human
getDelta <- function(i){
time1 <- proc.time()
database <- "cas9_human"
input <- paste0("inputs/sequences_",i,".fasta")
output <- paste0("outputs/output.txt")
cmd <- paste0("java -Xmx4g -jar FlashFry-assembly-1.15.jar discover --database ",
database,
" --fasta ",input,
" --maximumOffTargets ", 100000L,
" --forceLinear ",
" --maxMismatch ", 2,
" --output ",output)
system(cmd)
time2 <- proc.time()
delta <- as.numeric(time2-time1)
return(delta)
}
results <- lapply(1:6, function(i){
print(i)
out <- getDelta(i)
out
})
save(results, file="resultsMm2.rda")
| /analyses/speed/flashfry/compute.R | no_license | crisprVerse/crisprVersePaper | R | false | false | 716 | r | #module load Java/1.8.0_144
#database=/gstore/data/omni/crispr/flashfry/cas9_human
getDelta <- function(i){
time1 <- proc.time()
database <- "cas9_human"
input <- paste0("inputs/sequences_",i,".fasta")
output <- paste0("outputs/output.txt")
cmd <- paste0("java -Xmx4g -jar FlashFry-assembly-1.15.jar discover --database ",
database,
" --fasta ",input,
" --maximumOffTargets ", 100000L,
" --forceLinear ",
" --maxMismatch ", 2,
" --output ",output)
system(cmd)
time2 <- proc.time()
delta <- as.numeric(time2-time1)
return(delta)
}
results <- lapply(1:6, function(i){
print(i)
out <- getDelta(i)
out
})
save(results, file="resultsMm2.rda")
|
#GreenSTEP_Sim_Outputs.r
#=======================
#Regional Strategic Planning Model (RSPM) GreenSTEP Version
#Copyright 2009 - 2016, Oregon Department of Transportation
#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.
#Version: 3.5.1
#Date: 2/4/16
#Author: Brian Gregor, Oregon Systems Analytics LLC, gregor@or-analytics.com
#Revisions
#=========
#2/4/16:
#Added tabulation of total parking cashout payments by district, income group, development type, and population type. The new array is named "HhCashout.DiIgDtPp" and is a component of the "Hh_" list.
#Added tabulation of the number of zero vehicle households. The new array is named NumZeroVehHh.DiIgDtPpHt and is a component of the "Hh_" list.
#Define functions for calculating water use and critical air pollutant emissions
#===============================================================================
#Function to calculate water use
calcWaterUse <- function( Den ) {
# Data to estimate a regression model
WaterUse.. <- data.frame( list( DuAc = c( 2, 3, 4, 5, 6, 7 ),
DailyPersonUse = c( 215, 160, 130, 110, 105, 100 ) ) )
WaterUse..$PopDen <- 2.5 * 640 * WaterUse..$DuAc
# Double log plot of water use and density is approximately linear
# Inflexion point at lot size of 5 units per acre
WaterUse..$LogPopDen <- log( WaterUse..$PopDen )
WaterUse..$LogUse <- log( WaterUse..$DailyPersonUse )
WaterUse1_LM <- lm( LogUse[1:4] ~ LogPopDen[1:4], data=WaterUse.. )
WaterUse2_LM <- lm( LogUse[4:6] ~ LogPopDen[4:6], data=WaterUse.. )
Coeff1. <- coefficients( WaterUse1_LM )
Coeff2. <- coefficients( WaterUse2_LM )
# Compute the water useage
if( Den == 0 ) Den <- NA
if( is.na( Den ) ){
result <- NA
} else {
if( Den < 8000 ) {
result <- exp( Coeff1.[1] + Coeff1.[2] * log( Den ) )
} else {
result <- exp( Coeff2.[1] + Coeff2.[2] * log( Den ) )
}
}
names( result ) <- NULL
result
}
# Define function to calculate criteria air pollution
calcEmissions <- function( HcDvmt, Year ) {
Po <- c( "Hydrocarbons", "CarbonMonoxide", "NitrogenOxides", "PM25" )
PolluteRates.PoYr <- cbind( c( 1.1351, 13.1728, 1.6118, 0.0299 ), c( 0.3423, 4.9117, 0.3785, 0.0133 ),
c( 0.1989, 3.7269, 0.1843, 0.0107 ), c( 0.1755, 3.4720, 0.1715, 0.0103 ) )
rownames( PolluteRates.PoYr ) <- Po
colnames( PolluteRates.PoYr ) <- c( "2005", "2020", "2035", "2050" )
Year <- as.numeric( Year )
Years. <- as.numeric( colnames( PolluteRates.PoYr ) )
if( Year %in% Years. ) {
PolluteRates.Po <- PolluteRates.PoYr[ , which( Year == Years. ) ]
Pollution.Po <- HcDvmt * PolluteRates.Po
} else {
YearBracket. <- Years.[ which( rank( abs( Years. - Year ) ) <= 2 ) ]
Weights. <- rev( abs( YearBracket. - Year ) ) / diff( YearBracket. )
PolluteRates.Po <- rowSums( sweep( PolluteRates.PoYr[ , as.character( YearBracket. ) ],
2, Weights., "*" ) )
Pollution.Po <- HcDvmt * PolluteRates.Po
}
Pollution.Po
}
#Define function to tabulate synthetic population data
tabulate <- function(TabField, ByFields_, Dims_, Function) {
if(length(Dims_) > 5) {
stop("Function does not support tabulating more than 5 dimensions.")
}
if(length(ByFields_) != length(Dims_)) {
stop("Number of ByFields_ must equal number of Dims_")
}
if(!(Function %in% c("Sum", "Mean", "Count"))) {
stop("Function must be Sum, Mean, or Count")
}
# Make array of all dimensions
Result. <- array(0, dim=sapply(Dims_, length), dimnames=Dims_)
# Tabulate
if(Function == "Mean") {
Tab. <- tapply(TabField, ByFields_, function(x) mean(x, na.rm=TRUE))
}
if(Function == "Sum") {
Tab. <- tapply(TabField, ByFields_, function(x) sum(x, na.rm=TRUE))
}
if(Function == "Count") {
Tab. <- tapply(TabField, ByFields_, length)
}
Tab.[is.na(Tab.)] <- 0
# Put results of tabulation in array
if(length(dim(Tab.)) == 2) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]]] <- Tab.
}
if(length(dim(Tab.)) == 3) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]],
dimnames(Tab.)[[3]]] <- Tab.
}
if(length(dim(Tab.)) == 4) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]],
dimnames(Tab.)[[3]], dimnames(Tab.)[[4]]] <- Tab.
}
if(length(dim(Tab.)) == 5) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]],
dimnames(Tab.)[[3]], dimnames(Tab.)[[4]],
dimnames(Tab.)[[5]]] <- Tab.
}
# Return the result
Result.
}
#Iterate through all years
#=========================
for( yr in RunYears ) {
# Print year and start time
print( paste(yr, " outputs running") )
print( Sys.time() )
# Identify the directory where outputs are stored
OutYearDir <- paste( OutputDir, "/Year", yr, sep="" )
#Make objects to store results
#=============================
# Define urban mixed use designation ( Yes:"1", No: "0" )
Mx <- c( "0", "1" )
# Define light vehicle types
Vt <- c( "Auto", "LtTruck" )
# Define age group
Ag <- as.factor( as.character(0:32) )
# Define powertrain types
Pt <- c( "Ice", "Hev", "Phev", "Ev" )
# Define the population types (household, group quarters)
Pp <- c( "Household", "GroupQtr" )
# Define the pollution types
Po <- c( "Hydrocarbons", "CarbonMonoxide", "NitrogenOxides", "PM25" )
# Define housing types
Ht <- c( "A24", "SFD", "MH", "A5P", "GQ", "SFA" )
# Set up dimensions for arrays by district, income group, development type, and population type
OutputDims. <- c( length( Di ), length( Ig ), length( Dt ), length( Pp ) )
OutputDimnames_ <- list( Di, Ig, Dt, Pp )
# Initialize arrays for storing household data cross-tabulations
#---------------------------------------------------------------
Hh_ <- list()
Hh_$AveDensity.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$Acres.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$AveVehAge.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$DrvAgePop.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$Dvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$ElecCo2e.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$ElecKwh.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$EvDvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$EvDvmt.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ),
dimnames=list( Di, Vt, Pt ) )
Hh_$Fuel.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$Fuel.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ), dimnames=list( Di, Vt, Pt ) )
Hh_$FuelCo2e.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HcDvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HcDvmt.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ), dimnames=list( Di, Vt, Pt ) )
Hh_$Hh.DiIgDtPpHt <- array( 0, dim=c(OutputDims.,length(Ht)), dimnames=c(OutputDimnames_, list(Ht)) )
Hh_$NumZeroVehHh.DiIgDtPpHt <- array( 0, dim=c(OutputDims.,length(Ht)), dimnames=c(OutputDimnames_, list(Ht)) )
Hh_$HhCo2e.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhInc.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhCashout.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhExtCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhOpCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhParkingCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhVehOwnCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$LtWtVehDvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$LtWtVehDvmt.DiDtPpMx <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Mx)),
dimnames=list(Di,Dt,Pp,Mx) )
Hh_$NumAuto.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$NumLtTruck.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$NumPowertrain.DiDtPpPt <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Pt) ),
dimnames=list( Di, Dt, Pp, Pt ) )
Hh_$NumPowertrain.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ), dimnames=list( Di, Vt, Pt ) )
Hh_$Pop.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$Pop.DiIgDtPpHt <- array( 0, dim=c(OutputDims.,length(Ht)), dimnames=c(OutputDimnames_, list(Ht)) )
Hh_$Pop.DiDtPpMx <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Mx)),
dimnames=list(Di,Dt,Pp,Mx) )
Hh_$VehAge.DiAg <- array( 0, dim=c( length(Di), length(Ag) ), dimnames=list( Di, Ag ) )
Hh_$WalkTrips.DiDtPpMx <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Mx)),
dimnames=list(Di,Dt,Pp,Mx) )
Hh_$WaterUse.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$CritAirPol.DiDtPo <- array( 0, dim=c( length(Di), length(Dt), length(Po)),
dimnames=list(Di,Dt,Po) )
#Save metropolitan area summary data tables
#==========================================
Metropolitan_ <- list()
# Data that was summarized for all years
TableNames. <- c( "ArtLnMiCap.Yr", "BusRevMi.Yr", "FwyLnMiCap.Yr", "Inc.DtYr",
"Pop.DiDtYr", "Pop.DtYr", "RailRevMi.Yr", "TranRevMiCap.Yr" )
for( tn in TableNames. ) {
TableFile <- paste( OutputDir, "/", tn, ".RData", sep="" )
Metropolitan_[[tn]] <- assignLoad( TableFile )
rm( TableFile )
}
rm( TableNames. )
# Data that was summarized for the year
TableNames. <- c( "BusHcCo2e", "BusFuel.Ft", "CostSummary.MdVa", "Dvmt.MdDt", "RailBusEvCo2e", "RailBusPower",
"RoadCostSummary.", "TruckCo2e", "TruckFuel.Ft", "VmtSurcharge.It" )
for( tn in TableNames. ) {
TableFile <- paste( OutYearDir, "/", tn, ".RData", sep="" )
Metropolitan_[[tn]] <- assignLoad( TableFile )
}
rm( TableNames. )
# Congestion results
load( paste0(OutYearDir, "/CongResults_.RData") )
for( name in names(CongResults_) ) {
Metropolitan_[[name]] <- CongResults_[[name]]
}
rm( CongResults_ )
#Iterate through metropolitan divisions and make summary tables for household data
#=================================================================================
for( md in Md ) { local( {
# Load county files
Filename <- paste( OutYearDir, "/", md, ".RData", sep="" )
SynPop.. <- assignLoad( Filename )
SynPop..$DevType <- factor( SynPop..$DevType, levels=c("Metropolitan", "Town", "Rural") )
SynPop..$Urban <- factor( as.character( SynPop..$Urban ), levels=c( "0", "1" ) )
# Create vector of population types and identify if any group quarters population
PopType. <- rep( "Household", nrow( SynPop.. ) )
PopType.[ SynPop..$HouseType == "GQ" ] <- "GroupQtr"
HasGQ <- any(PopType. == "GroupQtr")
# Identify districts in the division
Dx <- unique( SynPop..$District )
# Identify households having vehicles
HasVeh.Hh <- SynPop..$Hhvehcnt >= 1
# Calculate average densities
#============================
# Compute the average density by district and development type
Density.DxDt <- tabulate(SynPop..$Htppopdn,
list( SynPop..$District, SynPop..$DevType ),
list(Dx, Dt),
"Mean")
Hh_$AveDensity.DiDt[ Dx, ] <<- Density.DxDt
#Hh_$AveDensity.DiDt[ Dx, ] <- Density.DxDt
# Compute the population by district and development type
Pop.DxDt <- tabulate(SynPop..$Hhsize,
list( SynPop..$District, SynPop..$DevType ),
list(Dx, Dt),
"Sum" )
Pop.DxDt[ is.na( Pop.DxDt ) ] <- 0
# Compute the area in acres by district and development type
Acres.DxDt <- 640 * Pop.DxDt / Density.DxDt
Acres.DxDt[ is.na( Acres.DxDt ) ] <- 0
Hh_$Acres.DiDt[ Dx, ] <<- Acres.DxDt
#Hh_$Acres.DiDt[ Dx, ] <- Acres.DxDt
# Calculate water consumption by district and development type
WaterUse.DxDt <- apply( Density.DxDt, c(1,2), function(x) {
calcWaterUse( x ) } )
Hh_$WaterUse.DiDt[Dx,] <<- WaterUse.DxDt
#Hh_$WaterUse.DiDt[Dx,] <- WaterUse.DxDt
rm( WaterUse.DxDt )
# Tabulate household characteristics
#===================================
# Household population
Pop.5d <- tabulate(SynPop..$Hhsize,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType., SynPop..$HouseType),
list(Dx,Ig,Dt,Pp,Ht),
"Sum")
Hh_$Pop.DiIgDtPpHt[ Dx, , , , ] <<- Pop.5d
#Hh_$Pop.DiIgDtPpHt[ Dx, , , , ] <- Pop.5d
# Population by district and development type
Pop.2d <- tabulate(SynPop..$Hhsize,
list( SynPop..$District, SynPop..$DevType ),
list(Dx, Dt),
"Sum")
Hh_$Pop.DiDt[ Dx, ] <<- Pop.2d
#Hh_$Pop.DiDt[ Dx, ] <- Pop.2d
rm( Pop.2d )
# Household population by urban mixed use designation
Pop.4d <- tabulate(SynPop..$Hhsize,
list(SynPop..$District, SynPop..$DevType,
PopType., SynPop..$Urban ),
list(Dx,Dt,Pp,Mx),
"Sum")
Hh_$Pop.DiDtPpMx[Dx, , , ] <<- Pop.4d
#Hh_$Pop.DiDtPpMx[Dx, , , ] <- Pop.4d
rm( Pop.4d )
# Number of households
Tab.5d <- tabulate(SynPop..$Houseid,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType., SynPop..$HouseType ),
list(Dx,Ig,Dt,Pp,Ht),
"Count")
Hh_$Hh.DiIgDtPpHt[Dx, , , , ] <<- Tab.5d
#Hh_$Hh.DiIgDtPpHt[Dx, , , , ] <- Tab.5d
rm( Tab.5d )
# Number of zero-vehicle households
IsZeroVeh <- SynPop..$Hhvehcnt == 0
Tab.5d <- tabulate(SynPop..$Houseid[IsZeroVeh],
list(SynPop..$District[IsZeroVeh],
SynPop..$IncGrp[IsZeroVeh],
SynPop..$DevType[IsZeroVeh],
PopType.[IsZeroVeh],
SynPop..$HouseType[IsZeroVeh]),
list(Dx,Ig,Dt,Pp,Ht),
"Count")
Hh_$NumZeroVehHh.DiIgDtPpHt[Dx, , , , ] <<- Tab.5d
#Hh_$NumZeroVehHh.DiIgDtPpHt[Dx, , , , ] <- Tab.5d
rm( Tab.5d, IsZeroVeh )
# Driver age population
VehHhDrvPop.4d <- tabulate(SynPop..$DrvAgePop,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$DrvAgePop.DiIgDtPp[Dx, , , ] <<- VehHhDrvPop.4d
#Hh_$DrvAgePop.DiIgDtPp[Dx, , , ] <- VehHhDrvPop.4d
rm( VehHhDrvPop.4d )
# Household Dvmt
Dvmt.4d <- tabulate(SynPop..$Dvmt,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$Dvmt.DiIgDtPp[Dx, , , ] <<- Dvmt.4d[Dx, Ig, Dt, Pp]
#Hh_$Dvmt.DiIgDtPp[Dx, , , ] <- Dvmt.4d[Dx, Ig, Dt, Pp]
rm( Dvmt.4d )
# Light Vehicle (e.g. bicycle) Dvmt
LtWtVehDvmt.4d <- tabulate(SynPop..$LtVehDvmt,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$LtWtVehDvmt.DiIgDtPp[Dx, , , ] <<- LtWtVehDvmt.4d
#Hh_$LtWtVehDvmt.DiIgDtPp[Dx, , , ] <- LtWtVehDvmt.4d
rm(LtWtVehDvmt.4d)
# Household light weight vehicle (e.g. bicycle) DVMT
LtWtVehDvmt.4d <- tabulate(SynPop..$LtVehDvmt,
list(SynPop..$District, SynPop..$DevType,
PopType., SynPop..$Urban),
list(Dx, Dt, Pp, Mx),
"Sum")
Hh_$LtWtVehDvmt.DiDtPpMx[Dx, , , ] <<- LtWtVehDvmt.4d
#Hh_$LtWtVehDvmt.DiDtPpMx[Dx, , , ] <- LtWtVehDvmt.4d
rm(LtWtVehDvmt.4d)
# Household operating cost
TotCost.4d <- tabulate(SynPop..$HhTotCost,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhOpCost.DiIgDtPp[Dx, , , ] <<- TotCost.4d
#Hh_$HhOpCost.DiIgDtPp[Dx, , , ] <- TotCost.4d
rm(TotCost.4d)
# Household external cost
TotExtCost.4d <- tabulate(SynPop..$TotExtCost,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhExtCost.DiIgDtPp[Dx, , , ] <<- TotExtCost.4d
#Hh_$HhExtCost.DiIgDtPp[Dx, , , ] <- TotExtCost.4d
rm(TotExtCost.4d)
# Household vehicle ownership cost
VehOwnExp.4d <- tabulate(SynPop..$VehOwnExp,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhVehOwnCost.DiIgDtPp[Dx, , , ] <<- VehOwnExp.4d
#Hh_$HhVehOwnCost.DiIgDtPp[Dx, , , ] <- VehOwnExp.4d
rm( VehOwnExp.4d )
# Household parking cost
ParkingCost.4d <- tabulate(SynPop..$DailyPkgCost,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhParkingCost.DiIgDtPp[Dx, , , ] <<- ParkingCost.4d
#Hh_$HhParkingCost.DiIgDtPp[Dx, , , ] <- ParkingCost.4d
rm( ParkingCost.4d )
# Household income
HhInc.4d <- tabulate(SynPop..$Hhincttl,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhInc.DiIgDtPp[Dx, , , ] <<- HhInc.4d
#Hh_$HhInc.DiIgDtPp[Dx, , , ] <- HhInc.4d
rm(HhInc.4d)
# Household parking cashout income adjustment
HhCashout.4d <- tabulate(SynPop..$CashOutIncAdj,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhCashout.DiIgDtPp[Dx, , , ] <<- HhCashout.4d
#Hh_$HhCashout.DiIgDtPp[Dx, , , ] <- HhCashout.4d
rm(HhCashout.4d)
# Household CO2e
Co2e.Hh <- SynPop..$FuelCo2e + SynPop..$ElecCo2e
Co2e.4d <- tabulate(Co2e.Hh,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhCo2e.DiIgDtPp[Dx, , , ] <<- Co2e.4d
#Hh_$HhCo2e.DiIgDtPp[Dx, , , ] <- Co2e.4d
rm(Co2e.Hh, Co2e.4d)
# Household walk trips
AveWalkTrips.4d <- tabulate(SynPop..$AveWalkTrips,
list(SynPop..$District, SynPop..$DevType,
PopType., SynPop..$Urban),
list(Dx, Dt, Pp, Mx),
"Sum")
Hh_$WalkTrips.DiDtPpMx[Dx, , , ] <<- AveWalkTrips.4d
#Hh_$WalkTrips.DiDtPpMx[Dx, , , ] <- AveWalkTrips.4d
rm(AveWalkTrips.4d)
# Fuel consumed by household
Fuel.4d <- tabulate(SynPop..$FuelGallons,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$Fuel.DiIgDtPp[Dx, , , ] <<- Fuel.4d
#Hh_$Fuel.DiIgDtPp[Dx, , , ] <- Fuel.4d
rm( Fuel.4d )
# Electricity consumed by household
ElecKwh.4d <- tabulate(SynPop..$ElecKwh,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$ElecKwh.DiIgDtPp[Dx, , , ] <<- ElecKwh.4d
#Hh_$ElecKwh.DiIgDtPp[Dx, , , ] <- ElecKwh.4d
rm( ElecKwh.4d )
# Greenhouse gas emissions from fuel consumption
FuelCo2e.4d <- tabulate(SynPop..$FuelCo2e,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$FuelCo2e.DiIgDtPp[Dx, , , ] <<- FuelCo2e.4d
#Hh_$FuelCo2e.DiIgDtPp[Dx, , , ] <- FuelCo2e.4d
rm(FuelCo2e.4d)
# Greenhouse gas emissions from electricity consumption
ElecCo2e.4d <- tabulate(SynPop..$ElecCo2e,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$ElecCo2e.DiIgDtPp[Dx, , , ] <<- ElecCo2e.4d
#Hh_$ElecCo2e.DiIgDtPp[Dx, , , ] <- ElecCo2e.4d
rm( ElecCo2e.4d )
# Tabulate vehicle characteristics
#=================================
# Tabulate average vehicle age
Tab.4d <- tabulate(unlist(SynPop..$VehAge[ HasVeh.Hh ]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt)),
list(Dx, Ig, Dt, Pp),
"Mean")
Hh_$AveVehAge.DiIgDtPp[Dx, , , ] <<- Tab.4d
#Hh_$AveVehAge.DiIgDtPp[Dx, , , ] <- Tab.4d
rm(Tab.4d)
# Tabulate number of vehicles by type
Tab.5d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[ HasVeh.Hh])),
list(Dx, Ig, Dt, Pp, Vt),
"Count")
Hh_$NumAuto.DiIgDtPp[Dx, , , ] <<- Tab.5d[, , , , "Auto"]
Hh_$NumLtTruck.DiIgDtPp[Dx, , , ] <<- Tab.5d[, , , , "LtTruck"]
#Hh_$NumAuto.DiIgDtPp[Dx, , , ] <- Tab.5d[, , , , "Auto"]
#Hh_$NumLtTruck.DiIgDtPp[Dx, , , ] <- Tab.5d[, , , , "LtTruck"]
rm(Tab.5d)
# Tabulate EV DVMT
Tab.4d <- tabulate(unlist(SynPop..$EvVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt)),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$EvDvmt.DiIgDtPp[Dx, , , ] <<- Tab.4d
#Hh_$EvDvmt.DiIgDtPp[Dx, , , ] <- Tab.4d
rm( Tab.4d )
# Tabulate HC-vehicle DVMT
Tab.4d <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt)),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HcDvmt.DiIgDtPp[Dx, , , ] <<- Tab.4d
#Hh_$HcDvmt.DiIgDtPp[Dx, , , ] <- Tab.4d
rm( Tab.4d )
# Calculate criteria air pollution
HcDvmt.DxDt <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt)),
list(Dx, Dt),
"Sum")
CritAirPol.PoDxDt <- apply(HcDvmt.DxDt, c(1,2), function(x) {
calcEmissions( x, yr )})
CritAirPol.DxDtPo <- aperm(CritAirPol.PoDxDt, c(2,3,1))
Hh_$CritAirPol.DiDtPo[Dx, , ] <<- CritAirPol.DxDtPo
#Hh_$CritAirPol.DiDtPo[Dx, , ] <- CritAirPol.DxDtPo
rm(CritAirPol.PoDxDt, CritAirPol.DxDtPo, HcDvmt.DxDt)
# Tabulate vehicle age distributions
Tab.2d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehAge[HasVeh.Hh])),
list(Dx, Ag),
"Count")
Hh_$VehAge.DiAg[Dx, ] <<- Tab.2d
#Hh_$VehAge.DiAg[Dx, ] <- Tab.2d
rm( Tab.2d )
# Tabulate number of vehicles by powertrain
Tab.4d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt),
unlist(SynPop..$Powertrain[ HasVeh.Hh])),
list(Dx, Dt, Pp, Pt),
"Count")
Hh_$NumPowertrain.DiDtPpPt[Dx, , , ] <<- Tab.4d
#Hh_$NumPowertrain.DiDtPpPt[Dx, , , ] <- Tab.4d
rm(Tab.4d)
# Tabulate number of vehicles by vehicle type and powertrain
Tab.3d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt ),
"Count")
Hh_$NumPowertrain.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$NumPowertrain.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Tabulate VMT powered by hydrocarbon fuels by vehicle type and powertrain
Tab.3d <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt),
"Sum")
Hh_$HcDvmt.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$HcDvmt.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Tabulate VMT powered by electricity by vehicle type and powertrain
Tab.3d <- tabulate(unlist(SynPop..$EvVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt),
"Sum")
Hh_$EvDvmt.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$EvDvmt.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Tabulate fuel consumed by vehicle type and powertrain
Tab.3d <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]) / unlist(SynPop..$VehMpg[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt),
"Sum")
Hh_$Fuel.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$Fuel.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Close local function
} )
gc()
# Close loop through metropolitan divisions
}
#Calculate several totals for commercial service vehicles
#========================================================
Filename <- paste( OutYearDir, "/", "CommServ_.RData", sep="" )
load( Filename )
CommServ_$CommVehCo2e <- sum( CommServ_$CommServAutoEvCo2e.MdDt ) +
sum( CommServ_$CommServAutoHcCo2e.MdDt ) +
sum( CommServ_$CommServLtTruckEvCo2e.MdDt ) +
sum( CommServ_$CommServLtTruckHcCo2e.MdDt )
CommServ_$CommVehFuel <- sum( CommServ_$CommServAutoFuel.MdDt ) +
sum( CommServ_$CommServLtTruckFuel.MdDt )
CommServ_$CommVehHcDvmt <- sum( CommServ_$CommServAutoHcDvmt.MdDt ) +
sum( CommServ_$CommServLtTruckHcDvmt.MdDt )
CommServ_$CommVehEvDvmt <- sum( CommServ_$CommServAutoEvDvmt.MdDt ) +
sum( CommServ_$CommServLtTruckEvDvmt.MdDt )
#Calculate metropolitan area roadway critical air pollutants from light duty vehicles
#====================================================================================
HcDvmt <- sum( Hh_$HcDvmt.DiVtPt, na.rm=TRUE ) + CommServ_$CommVehHcDvmt
EvDvmt <- sum( Hh_$EvDvmt.DiVtPt, na.rm=TRUE ) + CommServ_$CommVehEvDvmt
PropHcDvmt <- HcDvmt / ( HcDvmt + EvDvmt )
HcRoadDvmt <- PropHcDvmt * Metropolitan_$Dvmt.Ty["LtVeh"]
Metropolitan_$LtVehRoadCritAirPol.Po <- calcEmissions( HcRoadDvmt, yr )
rm(HcDvmt, EvDvmt, PropHcDvmt, HcRoadDvmt)
#Save the results
#================
Filename <- paste( OutYearDir, "/", "Hh_.RData", sep="" )
save( Hh_, file=Filename )
Filename <- paste( OutYearDir, "/", "CommServ_.RData", sep="" )
save( CommServ_, file=Filename )
Filename <- paste( OutYearDir, "/", "Metropolitan_.RData", sep="" )
save( Metropolitan_, file=Filename )
Filename <- paste( OutYearDir, "/", "Inputs_.RData", sep="" )
save( Inputs_, file=Filename )
Filename <- paste( OutYearDir, "/", "Model_.RData", sep="" )
save( Model_, file=Filename )
#End the loop through years
#==========================
print( Sys.time() )
}
detach(Model_)
detach(Inputs_)
detach(GreenSTEP_)
detach(Abbr_)
rm(list=ls()[!(ls() %in% c("Dir_", "RunYears"))])
| /Version_3.5/Example/scripts/GreenSTEP_Sim_Outputs.r | permissive | gregorbj/RSPM | R | false | false | 31,514 | r | #GreenSTEP_Sim_Outputs.r
#=======================
#Regional Strategic Planning Model (RSPM) GreenSTEP Version
#Copyright 2009 - 2016, Oregon Department of Transportation
#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.
#Version: 3.5.1
#Date: 2/4/16
#Author: Brian Gregor, Oregon Systems Analytics LLC, gregor@or-analytics.com
#Revisions
#=========
#2/4/16:
#Added tabulation of total parking cashout payments by district, income group, development type, and population type. The new array is named "HhCashout.DiIgDtPp" and is a component of the "Hh_" list.
#Added tabulation of the number of zero vehicle households. The new array is named NumZeroVehHh.DiIgDtPpHt and is a component of the "Hh_" list.
#Define functions for calculating water use and critical air pollutant emissions
#===============================================================================
#Function to calculate water use
calcWaterUse <- function( Den ) {
# Data to estimate a regression model
WaterUse.. <- data.frame( list( DuAc = c( 2, 3, 4, 5, 6, 7 ),
DailyPersonUse = c( 215, 160, 130, 110, 105, 100 ) ) )
WaterUse..$PopDen <- 2.5 * 640 * WaterUse..$DuAc
# Double log plot of water use and density is approximately linear
# Inflexion point at lot size of 5 units per acre
WaterUse..$LogPopDen <- log( WaterUse..$PopDen )
WaterUse..$LogUse <- log( WaterUse..$DailyPersonUse )
WaterUse1_LM <- lm( LogUse[1:4] ~ LogPopDen[1:4], data=WaterUse.. )
WaterUse2_LM <- lm( LogUse[4:6] ~ LogPopDen[4:6], data=WaterUse.. )
Coeff1. <- coefficients( WaterUse1_LM )
Coeff2. <- coefficients( WaterUse2_LM )
# Compute the water useage
if( Den == 0 ) Den <- NA
if( is.na( Den ) ){
result <- NA
} else {
if( Den < 8000 ) {
result <- exp( Coeff1.[1] + Coeff1.[2] * log( Den ) )
} else {
result <- exp( Coeff2.[1] + Coeff2.[2] * log( Den ) )
}
}
names( result ) <- NULL
result
}
# Define function to calculate criteria air pollution
calcEmissions <- function( HcDvmt, Year ) {
Po <- c( "Hydrocarbons", "CarbonMonoxide", "NitrogenOxides", "PM25" )
PolluteRates.PoYr <- cbind( c( 1.1351, 13.1728, 1.6118, 0.0299 ), c( 0.3423, 4.9117, 0.3785, 0.0133 ),
c( 0.1989, 3.7269, 0.1843, 0.0107 ), c( 0.1755, 3.4720, 0.1715, 0.0103 ) )
rownames( PolluteRates.PoYr ) <- Po
colnames( PolluteRates.PoYr ) <- c( "2005", "2020", "2035", "2050" )
Year <- as.numeric( Year )
Years. <- as.numeric( colnames( PolluteRates.PoYr ) )
if( Year %in% Years. ) {
PolluteRates.Po <- PolluteRates.PoYr[ , which( Year == Years. ) ]
Pollution.Po <- HcDvmt * PolluteRates.Po
} else {
YearBracket. <- Years.[ which( rank( abs( Years. - Year ) ) <= 2 ) ]
Weights. <- rev( abs( YearBracket. - Year ) ) / diff( YearBracket. )
PolluteRates.Po <- rowSums( sweep( PolluteRates.PoYr[ , as.character( YearBracket. ) ],
2, Weights., "*" ) )
Pollution.Po <- HcDvmt * PolluteRates.Po
}
Pollution.Po
}
#Define function to tabulate synthetic population data
tabulate <- function(TabField, ByFields_, Dims_, Function) {
if(length(Dims_) > 5) {
stop("Function does not support tabulating more than 5 dimensions.")
}
if(length(ByFields_) != length(Dims_)) {
stop("Number of ByFields_ must equal number of Dims_")
}
if(!(Function %in% c("Sum", "Mean", "Count"))) {
stop("Function must be Sum, Mean, or Count")
}
# Make array of all dimensions
Result. <- array(0, dim=sapply(Dims_, length), dimnames=Dims_)
# Tabulate
if(Function == "Mean") {
Tab. <- tapply(TabField, ByFields_, function(x) mean(x, na.rm=TRUE))
}
if(Function == "Sum") {
Tab. <- tapply(TabField, ByFields_, function(x) sum(x, na.rm=TRUE))
}
if(Function == "Count") {
Tab. <- tapply(TabField, ByFields_, length)
}
Tab.[is.na(Tab.)] <- 0
# Put results of tabulation in array
if(length(dim(Tab.)) == 2) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]]] <- Tab.
}
if(length(dim(Tab.)) == 3) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]],
dimnames(Tab.)[[3]]] <- Tab.
}
if(length(dim(Tab.)) == 4) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]],
dimnames(Tab.)[[3]], dimnames(Tab.)[[4]]] <- Tab.
}
if(length(dim(Tab.)) == 5) {
Result.[dimnames(Tab.)[[1]], dimnames(Tab.)[[2]],
dimnames(Tab.)[[3]], dimnames(Tab.)[[4]],
dimnames(Tab.)[[5]]] <- Tab.
}
# Return the result
Result.
}
#Iterate through all years
#=========================
for( yr in RunYears ) {
# Print year and start time
print( paste(yr, " outputs running") )
print( Sys.time() )
# Identify the directory where outputs are stored
OutYearDir <- paste( OutputDir, "/Year", yr, sep="" )
#Make objects to store results
#=============================
# Define urban mixed use designation ( Yes:"1", No: "0" )
Mx <- c( "0", "1" )
# Define light vehicle types
Vt <- c( "Auto", "LtTruck" )
# Define age group
Ag <- as.factor( as.character(0:32) )
# Define powertrain types
Pt <- c( "Ice", "Hev", "Phev", "Ev" )
# Define the population types (household, group quarters)
Pp <- c( "Household", "GroupQtr" )
# Define the pollution types
Po <- c( "Hydrocarbons", "CarbonMonoxide", "NitrogenOxides", "PM25" )
# Define housing types
Ht <- c( "A24", "SFD", "MH", "A5P", "GQ", "SFA" )
# Set up dimensions for arrays by district, income group, development type, and population type
OutputDims. <- c( length( Di ), length( Ig ), length( Dt ), length( Pp ) )
OutputDimnames_ <- list( Di, Ig, Dt, Pp )
# Initialize arrays for storing household data cross-tabulations
#---------------------------------------------------------------
Hh_ <- list()
Hh_$AveDensity.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$Acres.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$AveVehAge.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$DrvAgePop.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$Dvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$ElecCo2e.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$ElecKwh.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$EvDvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$EvDvmt.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ),
dimnames=list( Di, Vt, Pt ) )
Hh_$Fuel.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$Fuel.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ), dimnames=list( Di, Vt, Pt ) )
Hh_$FuelCo2e.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HcDvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HcDvmt.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ), dimnames=list( Di, Vt, Pt ) )
Hh_$Hh.DiIgDtPpHt <- array( 0, dim=c(OutputDims.,length(Ht)), dimnames=c(OutputDimnames_, list(Ht)) )
Hh_$NumZeroVehHh.DiIgDtPpHt <- array( 0, dim=c(OutputDims.,length(Ht)), dimnames=c(OutputDimnames_, list(Ht)) )
Hh_$HhCo2e.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhInc.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhCashout.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhExtCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhOpCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhParkingCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$HhVehOwnCost.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$LtWtVehDvmt.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$LtWtVehDvmt.DiDtPpMx <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Mx)),
dimnames=list(Di,Dt,Pp,Mx) )
Hh_$NumAuto.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$NumLtTruck.DiIgDtPp <- array( 0, dim=OutputDims., dimnames=OutputDimnames_ )
Hh_$NumPowertrain.DiDtPpPt <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Pt) ),
dimnames=list( Di, Dt, Pp, Pt ) )
Hh_$NumPowertrain.DiVtPt <- array( 0, dim=c( length(Di), length(Vt), length(Pt) ), dimnames=list( Di, Vt, Pt ) )
Hh_$Pop.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$Pop.DiIgDtPpHt <- array( 0, dim=c(OutputDims.,length(Ht)), dimnames=c(OutputDimnames_, list(Ht)) )
Hh_$Pop.DiDtPpMx <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Mx)),
dimnames=list(Di,Dt,Pp,Mx) )
Hh_$VehAge.DiAg <- array( 0, dim=c( length(Di), length(Ag) ), dimnames=list( Di, Ag ) )
Hh_$WalkTrips.DiDtPpMx <- array( 0, dim=c( length(Di), length(Dt), length(Pp), length(Mx)),
dimnames=list(Di,Dt,Pp,Mx) )
Hh_$WaterUse.DiDt <- array( 0, dim=c( length(Di), length(Dt)), dimnames=list(Di,Dt) )
Hh_$CritAirPol.DiDtPo <- array( 0, dim=c( length(Di), length(Dt), length(Po)),
dimnames=list(Di,Dt,Po) )
#Save metropolitan area summary data tables
#==========================================
Metropolitan_ <- list()
# Data that was summarized for all years
TableNames. <- c( "ArtLnMiCap.Yr", "BusRevMi.Yr", "FwyLnMiCap.Yr", "Inc.DtYr",
"Pop.DiDtYr", "Pop.DtYr", "RailRevMi.Yr", "TranRevMiCap.Yr" )
for( tn in TableNames. ) {
TableFile <- paste( OutputDir, "/", tn, ".RData", sep="" )
Metropolitan_[[tn]] <- assignLoad( TableFile )
rm( TableFile )
}
rm( TableNames. )
# Data that was summarized for the year
TableNames. <- c( "BusHcCo2e", "BusFuel.Ft", "CostSummary.MdVa", "Dvmt.MdDt", "RailBusEvCo2e", "RailBusPower",
"RoadCostSummary.", "TruckCo2e", "TruckFuel.Ft", "VmtSurcharge.It" )
for( tn in TableNames. ) {
TableFile <- paste( OutYearDir, "/", tn, ".RData", sep="" )
Metropolitan_[[tn]] <- assignLoad( TableFile )
}
rm( TableNames. )
# Congestion results
load( paste0(OutYearDir, "/CongResults_.RData") )
for( name in names(CongResults_) ) {
Metropolitan_[[name]] <- CongResults_[[name]]
}
rm( CongResults_ )
#Iterate through metropolitan divisions and make summary tables for household data
#=================================================================================
for( md in Md ) { local( {
# Load county files
Filename <- paste( OutYearDir, "/", md, ".RData", sep="" )
SynPop.. <- assignLoad( Filename )
SynPop..$DevType <- factor( SynPop..$DevType, levels=c("Metropolitan", "Town", "Rural") )
SynPop..$Urban <- factor( as.character( SynPop..$Urban ), levels=c( "0", "1" ) )
# Create vector of population types and identify if any group quarters population
PopType. <- rep( "Household", nrow( SynPop.. ) )
PopType.[ SynPop..$HouseType == "GQ" ] <- "GroupQtr"
HasGQ <- any(PopType. == "GroupQtr")
# Identify districts in the division
Dx <- unique( SynPop..$District )
# Identify households having vehicles
HasVeh.Hh <- SynPop..$Hhvehcnt >= 1
# Calculate average densities
#============================
# Compute the average density by district and development type
Density.DxDt <- tabulate(SynPop..$Htppopdn,
list( SynPop..$District, SynPop..$DevType ),
list(Dx, Dt),
"Mean")
Hh_$AveDensity.DiDt[ Dx, ] <<- Density.DxDt
#Hh_$AveDensity.DiDt[ Dx, ] <- Density.DxDt
# Compute the population by district and development type
Pop.DxDt <- tabulate(SynPop..$Hhsize,
list( SynPop..$District, SynPop..$DevType ),
list(Dx, Dt),
"Sum" )
Pop.DxDt[ is.na( Pop.DxDt ) ] <- 0
# Compute the area in acres by district and development type
Acres.DxDt <- 640 * Pop.DxDt / Density.DxDt
Acres.DxDt[ is.na( Acres.DxDt ) ] <- 0
Hh_$Acres.DiDt[ Dx, ] <<- Acres.DxDt
#Hh_$Acres.DiDt[ Dx, ] <- Acres.DxDt
# Calculate water consumption by district and development type
WaterUse.DxDt <- apply( Density.DxDt, c(1,2), function(x) {
calcWaterUse( x ) } )
Hh_$WaterUse.DiDt[Dx,] <<- WaterUse.DxDt
#Hh_$WaterUse.DiDt[Dx,] <- WaterUse.DxDt
rm( WaterUse.DxDt )
# Tabulate household characteristics
#===================================
# Household population
Pop.5d <- tabulate(SynPop..$Hhsize,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType., SynPop..$HouseType),
list(Dx,Ig,Dt,Pp,Ht),
"Sum")
Hh_$Pop.DiIgDtPpHt[ Dx, , , , ] <<- Pop.5d
#Hh_$Pop.DiIgDtPpHt[ Dx, , , , ] <- Pop.5d
# Population by district and development type
Pop.2d <- tabulate(SynPop..$Hhsize,
list( SynPop..$District, SynPop..$DevType ),
list(Dx, Dt),
"Sum")
Hh_$Pop.DiDt[ Dx, ] <<- Pop.2d
#Hh_$Pop.DiDt[ Dx, ] <- Pop.2d
rm( Pop.2d )
# Household population by urban mixed use designation
Pop.4d <- tabulate(SynPop..$Hhsize,
list(SynPop..$District, SynPop..$DevType,
PopType., SynPop..$Urban ),
list(Dx,Dt,Pp,Mx),
"Sum")
Hh_$Pop.DiDtPpMx[Dx, , , ] <<- Pop.4d
#Hh_$Pop.DiDtPpMx[Dx, , , ] <- Pop.4d
rm( Pop.4d )
# Number of households
Tab.5d <- tabulate(SynPop..$Houseid,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType., SynPop..$HouseType ),
list(Dx,Ig,Dt,Pp,Ht),
"Count")
Hh_$Hh.DiIgDtPpHt[Dx, , , , ] <<- Tab.5d
#Hh_$Hh.DiIgDtPpHt[Dx, , , , ] <- Tab.5d
rm( Tab.5d )
# Number of zero-vehicle households
IsZeroVeh <- SynPop..$Hhvehcnt == 0
Tab.5d <- tabulate(SynPop..$Houseid[IsZeroVeh],
list(SynPop..$District[IsZeroVeh],
SynPop..$IncGrp[IsZeroVeh],
SynPop..$DevType[IsZeroVeh],
PopType.[IsZeroVeh],
SynPop..$HouseType[IsZeroVeh]),
list(Dx,Ig,Dt,Pp,Ht),
"Count")
Hh_$NumZeroVehHh.DiIgDtPpHt[Dx, , , , ] <<- Tab.5d
#Hh_$NumZeroVehHh.DiIgDtPpHt[Dx, , , , ] <- Tab.5d
rm( Tab.5d, IsZeroVeh )
# Driver age population
VehHhDrvPop.4d <- tabulate(SynPop..$DrvAgePop,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$DrvAgePop.DiIgDtPp[Dx, , , ] <<- VehHhDrvPop.4d
#Hh_$DrvAgePop.DiIgDtPp[Dx, , , ] <- VehHhDrvPop.4d
rm( VehHhDrvPop.4d )
# Household Dvmt
Dvmt.4d <- tabulate(SynPop..$Dvmt,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$Dvmt.DiIgDtPp[Dx, , , ] <<- Dvmt.4d[Dx, Ig, Dt, Pp]
#Hh_$Dvmt.DiIgDtPp[Dx, , , ] <- Dvmt.4d[Dx, Ig, Dt, Pp]
rm( Dvmt.4d )
# Light Vehicle (e.g. bicycle) Dvmt
LtWtVehDvmt.4d <- tabulate(SynPop..$LtVehDvmt,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$LtWtVehDvmt.DiIgDtPp[Dx, , , ] <<- LtWtVehDvmt.4d
#Hh_$LtWtVehDvmt.DiIgDtPp[Dx, , , ] <- LtWtVehDvmt.4d
rm(LtWtVehDvmt.4d)
# Household light weight vehicle (e.g. bicycle) DVMT
LtWtVehDvmt.4d <- tabulate(SynPop..$LtVehDvmt,
list(SynPop..$District, SynPop..$DevType,
PopType., SynPop..$Urban),
list(Dx, Dt, Pp, Mx),
"Sum")
Hh_$LtWtVehDvmt.DiDtPpMx[Dx, , , ] <<- LtWtVehDvmt.4d
#Hh_$LtWtVehDvmt.DiDtPpMx[Dx, , , ] <- LtWtVehDvmt.4d
rm(LtWtVehDvmt.4d)
# Household operating cost
TotCost.4d <- tabulate(SynPop..$HhTotCost,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhOpCost.DiIgDtPp[Dx, , , ] <<- TotCost.4d
#Hh_$HhOpCost.DiIgDtPp[Dx, , , ] <- TotCost.4d
rm(TotCost.4d)
# Household external cost
TotExtCost.4d <- tabulate(SynPop..$TotExtCost,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhExtCost.DiIgDtPp[Dx, , , ] <<- TotExtCost.4d
#Hh_$HhExtCost.DiIgDtPp[Dx, , , ] <- TotExtCost.4d
rm(TotExtCost.4d)
# Household vehicle ownership cost
VehOwnExp.4d <- tabulate(SynPop..$VehOwnExp,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhVehOwnCost.DiIgDtPp[Dx, , , ] <<- VehOwnExp.4d
#Hh_$HhVehOwnCost.DiIgDtPp[Dx, , , ] <- VehOwnExp.4d
rm( VehOwnExp.4d )
# Household parking cost
ParkingCost.4d <- tabulate(SynPop..$DailyPkgCost,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhParkingCost.DiIgDtPp[Dx, , , ] <<- ParkingCost.4d
#Hh_$HhParkingCost.DiIgDtPp[Dx, , , ] <- ParkingCost.4d
rm( ParkingCost.4d )
# Household income
HhInc.4d <- tabulate(SynPop..$Hhincttl,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhInc.DiIgDtPp[Dx, , , ] <<- HhInc.4d
#Hh_$HhInc.DiIgDtPp[Dx, , , ] <- HhInc.4d
rm(HhInc.4d)
# Household parking cashout income adjustment
HhCashout.4d <- tabulate(SynPop..$CashOutIncAdj,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhCashout.DiIgDtPp[Dx, , , ] <<- HhCashout.4d
#Hh_$HhCashout.DiIgDtPp[Dx, , , ] <- HhCashout.4d
rm(HhCashout.4d)
# Household CO2e
Co2e.Hh <- SynPop..$FuelCo2e + SynPop..$ElecCo2e
Co2e.4d <- tabulate(Co2e.Hh,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HhCo2e.DiIgDtPp[Dx, , , ] <<- Co2e.4d
#Hh_$HhCo2e.DiIgDtPp[Dx, , , ] <- Co2e.4d
rm(Co2e.Hh, Co2e.4d)
# Household walk trips
AveWalkTrips.4d <- tabulate(SynPop..$AveWalkTrips,
list(SynPop..$District, SynPop..$DevType,
PopType., SynPop..$Urban),
list(Dx, Dt, Pp, Mx),
"Sum")
Hh_$WalkTrips.DiDtPpMx[Dx, , , ] <<- AveWalkTrips.4d
#Hh_$WalkTrips.DiDtPpMx[Dx, , , ] <- AveWalkTrips.4d
rm(AveWalkTrips.4d)
# Fuel consumed by household
Fuel.4d <- tabulate(SynPop..$FuelGallons,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$Fuel.DiIgDtPp[Dx, , , ] <<- Fuel.4d
#Hh_$Fuel.DiIgDtPp[Dx, , , ] <- Fuel.4d
rm( Fuel.4d )
# Electricity consumed by household
ElecKwh.4d <- tabulate(SynPop..$ElecKwh,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$ElecKwh.DiIgDtPp[Dx, , , ] <<- ElecKwh.4d
#Hh_$ElecKwh.DiIgDtPp[Dx, , , ] <- ElecKwh.4d
rm( ElecKwh.4d )
# Greenhouse gas emissions from fuel consumption
FuelCo2e.4d <- tabulate(SynPop..$FuelCo2e,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$FuelCo2e.DiIgDtPp[Dx, , , ] <<- FuelCo2e.4d
#Hh_$FuelCo2e.DiIgDtPp[Dx, , , ] <- FuelCo2e.4d
rm(FuelCo2e.4d)
# Greenhouse gas emissions from electricity consumption
ElecCo2e.4d <- tabulate(SynPop..$ElecCo2e,
list(SynPop..$District, SynPop..$IncGrp,
SynPop..$DevType, PopType.),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$ElecCo2e.DiIgDtPp[Dx, , , ] <<- ElecCo2e.4d
#Hh_$ElecCo2e.DiIgDtPp[Dx, , , ] <- ElecCo2e.4d
rm( ElecCo2e.4d )
# Tabulate vehicle characteristics
#=================================
# Tabulate average vehicle age
Tab.4d <- tabulate(unlist(SynPop..$VehAge[ HasVeh.Hh ]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt)),
list(Dx, Ig, Dt, Pp),
"Mean")
Hh_$AveVehAge.DiIgDtPp[Dx, , , ] <<- Tab.4d
#Hh_$AveVehAge.DiIgDtPp[Dx, , , ] <- Tab.4d
rm(Tab.4d)
# Tabulate number of vehicles by type
Tab.5d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[ HasVeh.Hh])),
list(Dx, Ig, Dt, Pp, Vt),
"Count")
Hh_$NumAuto.DiIgDtPp[Dx, , , ] <<- Tab.5d[, , , , "Auto"]
Hh_$NumLtTruck.DiIgDtPp[Dx, , , ] <<- Tab.5d[, , , , "LtTruck"]
#Hh_$NumAuto.DiIgDtPp[Dx, , , ] <- Tab.5d[, , , , "Auto"]
#Hh_$NumLtTruck.DiIgDtPp[Dx, , , ] <- Tab.5d[, , , , "LtTruck"]
rm(Tab.5d)
# Tabulate EV DVMT
Tab.4d <- tabulate(unlist(SynPop..$EvVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt)),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$EvDvmt.DiIgDtPp[Dx, , , ] <<- Tab.4d
#Hh_$EvDvmt.DiIgDtPp[Dx, , , ] <- Tab.4d
rm( Tab.4d )
# Tabulate HC-vehicle DVMT
Tab.4d <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$IncGrp, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt)),
list(Dx, Ig, Dt, Pp),
"Sum")
Hh_$HcDvmt.DiIgDtPp[Dx, , , ] <<- Tab.4d
#Hh_$HcDvmt.DiIgDtPp[Dx, , , ] <- Tab.4d
rm( Tab.4d )
# Calculate criteria air pollution
HcDvmt.DxDt <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt)),
list(Dx, Dt),
"Sum")
CritAirPol.PoDxDt <- apply(HcDvmt.DxDt, c(1,2), function(x) {
calcEmissions( x, yr )})
CritAirPol.DxDtPo <- aperm(CritAirPol.PoDxDt, c(2,3,1))
Hh_$CritAirPol.DiDtPo[Dx, , ] <<- CritAirPol.DxDtPo
#Hh_$CritAirPol.DiDtPo[Dx, , ] <- CritAirPol.DxDtPo
rm(CritAirPol.PoDxDt, CritAirPol.DxDtPo, HcDvmt.DxDt)
# Tabulate vehicle age distributions
Tab.2d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehAge[HasVeh.Hh])),
list(Dx, Ag),
"Count")
Hh_$VehAge.DiAg[Dx, ] <<- Tab.2d
#Hh_$VehAge.DiAg[Dx, ] <- Tab.2d
rm( Tab.2d )
# Tabulate number of vehicles by powertrain
Tab.4d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
rep(SynPop..$DevType, SynPop..$Hhvehcnt),
rep(PopType., SynPop..$Hhvehcnt),
unlist(SynPop..$Powertrain[ HasVeh.Hh])),
list(Dx, Dt, Pp, Pt),
"Count")
Hh_$NumPowertrain.DiDtPpPt[Dx, , , ] <<- Tab.4d
#Hh_$NumPowertrain.DiDtPpPt[Dx, , , ] <- Tab.4d
rm(Tab.4d)
# Tabulate number of vehicles by vehicle type and powertrain
Tab.3d <- tabulate(rep(SynPop..$Houseid, SynPop..$Hhvehcnt),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt ),
"Count")
Hh_$NumPowertrain.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$NumPowertrain.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Tabulate VMT powered by hydrocarbon fuels by vehicle type and powertrain
Tab.3d <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt),
"Sum")
Hh_$HcDvmt.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$HcDvmt.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Tabulate VMT powered by electricity by vehicle type and powertrain
Tab.3d <- tabulate(unlist(SynPop..$EvVehDvmt[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt),
"Sum")
Hh_$EvDvmt.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$EvDvmt.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Tabulate fuel consumed by vehicle type and powertrain
Tab.3d <- tabulate(unlist(SynPop..$HcVehDvmt[HasVeh.Hh]) / unlist(SynPop..$VehMpg[HasVeh.Hh]),
list(rep(SynPop..$District, SynPop..$Hhvehcnt),
unlist(SynPop..$VehType[HasVeh.Hh]),
unlist(SynPop..$Powertrain[HasVeh.Hh])),
list(Dx, Vt, Pt),
"Sum")
Hh_$Fuel.DiVtPt[Dx, , ] <<- Tab.3d
#Hh_$Fuel.DiVtPt[Dx, , ] <- Tab.3d
rm(Tab.3d)
# Close local function
} )
gc()
# Close loop through metropolitan divisions
}
#Calculate several totals for commercial service vehicles
#========================================================
Filename <- paste( OutYearDir, "/", "CommServ_.RData", sep="" )
load( Filename )
CommServ_$CommVehCo2e <- sum( CommServ_$CommServAutoEvCo2e.MdDt ) +
sum( CommServ_$CommServAutoHcCo2e.MdDt ) +
sum( CommServ_$CommServLtTruckEvCo2e.MdDt ) +
sum( CommServ_$CommServLtTruckHcCo2e.MdDt )
CommServ_$CommVehFuel <- sum( CommServ_$CommServAutoFuel.MdDt ) +
sum( CommServ_$CommServLtTruckFuel.MdDt )
CommServ_$CommVehHcDvmt <- sum( CommServ_$CommServAutoHcDvmt.MdDt ) +
sum( CommServ_$CommServLtTruckHcDvmt.MdDt )
CommServ_$CommVehEvDvmt <- sum( CommServ_$CommServAutoEvDvmt.MdDt ) +
sum( CommServ_$CommServLtTruckEvDvmt.MdDt )
#Calculate metropolitan area roadway critical air pollutants from light duty vehicles
#====================================================================================
HcDvmt <- sum( Hh_$HcDvmt.DiVtPt, na.rm=TRUE ) + CommServ_$CommVehHcDvmt
EvDvmt <- sum( Hh_$EvDvmt.DiVtPt, na.rm=TRUE ) + CommServ_$CommVehEvDvmt
PropHcDvmt <- HcDvmt / ( HcDvmt + EvDvmt )
HcRoadDvmt <- PropHcDvmt * Metropolitan_$Dvmt.Ty["LtVeh"]
Metropolitan_$LtVehRoadCritAirPol.Po <- calcEmissions( HcRoadDvmt, yr )
rm(HcDvmt, EvDvmt, PropHcDvmt, HcRoadDvmt)
#Save the results
#================
Filename <- paste( OutYearDir, "/", "Hh_.RData", sep="" )
save( Hh_, file=Filename )
Filename <- paste( OutYearDir, "/", "CommServ_.RData", sep="" )
save( CommServ_, file=Filename )
Filename <- paste( OutYearDir, "/", "Metropolitan_.RData", sep="" )
save( Metropolitan_, file=Filename )
Filename <- paste( OutYearDir, "/", "Inputs_.RData", sep="" )
save( Inputs_, file=Filename )
Filename <- paste( OutYearDir, "/", "Model_.RData", sep="" )
save( Model_, file=Filename )
#End the loop through years
#==========================
print( Sys.time() )
}
detach(Model_)
detach(Inputs_)
detach(GreenSTEP_)
detach(Abbr_)
rm(list=ls()[!(ls() %in% c("Dir_", "RunYears"))])
|
\name{neuropathy}
\docType{data}
\alias{neuropathy}
\title{Acute Painful Diabetic Neuropathy}
\description{
The logarithm of the ratio of pain scores measured at baseline and after four
weeks in a control group and a treatment group.
}
\usage{neuropathy}
\format{
A data frame with 58 observations on 2 variables.
\describe{
\item{\code{pain}}{
pain scores: ln(baseline / final).
}
\item{\code{group}}{
a factor with levels \code{"control"} and \code{"treat"}.
}
}
}
\details{
Data from Conover and Salsburg (1988, Tab. 1).
}
\source{
Conover, W. J. and Salsburg, D. S. (1988). Locally most powerful tests for
detecting treatment effects when only a subset of patients can be expected to
\dQuote{respond} to treatment. \emph{Biometrics} \bold{44}(1), 189--196.
\doi{10.2307/2531906}
}
\examples{
## Conover and Salsburg (1988, Tab. 2)
## One-sided approximative Fisher-Pitman test
oneway_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000))
## One-sided approximative Wilcoxon-Mann-Whitney test
wilcox_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000))
## One-sided approximative Conover-Salsburg test
oneway_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000),
ytrafo = function(data)
trafo(data, numeric_trafo = consal_trafo))
## One-sided approximative maximum test for a range of 'a' values
it <- independence_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000),
ytrafo = function(data)
trafo(data, numeric_trafo = function(y)
consal_trafo(y, a = 2:7)))
pvalue(it, method = "single-step")
}
\keyword{datasets}
| /man/neuropathy.Rd | no_license | cran/coin | R | false | false | 2,019 | rd | \name{neuropathy}
\docType{data}
\alias{neuropathy}
\title{Acute Painful Diabetic Neuropathy}
\description{
The logarithm of the ratio of pain scores measured at baseline and after four
weeks in a control group and a treatment group.
}
\usage{neuropathy}
\format{
A data frame with 58 observations on 2 variables.
\describe{
\item{\code{pain}}{
pain scores: ln(baseline / final).
}
\item{\code{group}}{
a factor with levels \code{"control"} and \code{"treat"}.
}
}
}
\details{
Data from Conover and Salsburg (1988, Tab. 1).
}
\source{
Conover, W. J. and Salsburg, D. S. (1988). Locally most powerful tests for
detecting treatment effects when only a subset of patients can be expected to
\dQuote{respond} to treatment. \emph{Biometrics} \bold{44}(1), 189--196.
\doi{10.2307/2531906}
}
\examples{
## Conover and Salsburg (1988, Tab. 2)
## One-sided approximative Fisher-Pitman test
oneway_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000))
## One-sided approximative Wilcoxon-Mann-Whitney test
wilcox_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000))
## One-sided approximative Conover-Salsburg test
oneway_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000),
ytrafo = function(data)
trafo(data, numeric_trafo = consal_trafo))
## One-sided approximative maximum test for a range of 'a' values
it <- independence_test(pain ~ group, data = neuropathy,
alternative = "less",
distribution = approximate(nresample = 10000),
ytrafo = function(data)
trafo(data, numeric_trafo = function(y)
consal_trafo(y, a = 2:7)))
pvalue(it, method = "single-step")
}
\keyword{datasets}
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/flow_equalizePhase.R
\name{flow_equalizePhase}
\alias{flow_equalizePhase}
\title{Normalize Image Values}
\usage{
flow_equalizePhase(image, medianNew)
}
\arguments{
\item{image}{the image matrix to modify.}
\item{medianNew}{a new median value to set scale the image values against}
}
\value{
An image of the same dimensions.
}
\description{
Normalize a given image matrix based on median. The new median
value should be between 0 and 1, and will typically be between 0.2 and 0.6.
}
\note{
There are no hard-coded parameters in this function.
}
| /man/flow_equalizePhase.Rd | no_license | MazamaScience/TBCellGrowth | R | false | false | 632 | rd | % Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/flow_equalizePhase.R
\name{flow_equalizePhase}
\alias{flow_equalizePhase}
\title{Normalize Image Values}
\usage{
flow_equalizePhase(image, medianNew)
}
\arguments{
\item{image}{the image matrix to modify.}
\item{medianNew}{a new median value to set scale the image values against}
}
\value{
An image of the same dimensions.
}
\description{
Normalize a given image matrix based on median. The new median
value should be between 0 and 1, and will typically be between 0.2 and 0.6.
}
\note{
There are no hard-coded parameters in this function.
}
|
# there is a special case treated seporately on the bottom: d2015.1
cleaningData <- function(filename,newfile){
library(dplyr)
library(tidyr)
immidata <- read.csv(filename,
stringsAsFactors = F, na.strings=c(""," ", "NA"))
str(immidata)
attributes(immidata)
names(immidata)
colNum <- dim(immidata)[2]
#checking the columns for uselessnes.
useless <- c()
for (i in 1:colNum){
if(all(sapply(immidata[i],is.na)))
{
useless[i] = i
cat("The column number",i, "is useless!\n")
} else { cat(i,"is not empty\n")
if (dim(immidata[i])[1] > 10){
cat("more than 10 raws\n")
} else {
cat(i,"th raw has the following useful things")
}
}
}
# after the check, removing the column
if (!is.null(useless)){
useless <- useless[!is.na(useless)]
immidata[useless] = NULL
}
# creating a new DF with only the raws interested in
servCenter <- which(immidata[1] == "Service Center")
servCenterBottom <- servCenter + 5
# FOState <- which(immidata[1] == "Field Office by State6") + 1
FOStateBottom <- which(immidata[1] == "Field Office by Territory6")-1
immidata.US <- rbind(immidata[1:FOStateBottom, ] ,
immidata[servCenter:servCenterBottom, ])
# Filling the State column
immidata.US <- fill(immidata.US,1)
### Look into Bookmarks for an excelant post on droping NA raws!
# for now im just gonna use filter(v, is.na(w) & is.na(k))
# here I take only the raws that have NA in 2nd and 3rd columns
# by check if 2nd and 3rd column are NA, and then passin the resulting
# boolien vector to the main DF to select only those rows.
row.names(immidata.US[is.na(immidata.US[2]) & is.na(immidata.US[3]),])
# after chcking that this names actually give the empty raws, i just delete
# them, by revercing the resulting Boolien vecotr of
# is.na(immidata.US[2]) & is.na(immidata.US[3])
immidata.US <- immidata.US[!(is.na(immidata.US[2]) & is.na(immidata.US[3]) &
is.na(immidata.US[4])), ]
# Chopping the last 4 columns
immidata.US <- immidata.US[ ,-((dim(immidata.US)[2]-3):dim(immidata.US)[2])]
# Now i exported this final "half-read" data to Excel and did some
# retouching
write.csv(immidata.US, newfile, row.names = FALSE)
}
cleaningData("./USCIS/I130_performancedata_fy2014_qtr4.csv","d2014.4.csv")
# I manually deleted the raws in the 2014 data
# fixing the data in d2015.csv by adding the code column
df2 <- read.csv('d2015.44.csv')
df1 <- read.csv('d2014.4.csv')
# head(df2)
# tail(df2,10)
# head(df1)
df1$code = df2[ ,3]
# nrow(df2)
# nrow(df1)
# colnames(df1)
# colnames(df2)
# ncol(df1)
# ncol(df2)
df1 <- df1[ ,c(1,2,11,3:10)]
# colnames(df1)
# str(df1)
write.csv(df1,'d2014.4.csv', row.names = FALSE)
| /Shiny_Project/Project/cleaningData.R | no_license | shr264/Vacun.github.io | R | false | false | 2,889 | r | # there is a special case treated seporately on the bottom: d2015.1
cleaningData <- function(filename,newfile){
library(dplyr)
library(tidyr)
immidata <- read.csv(filename,
stringsAsFactors = F, na.strings=c(""," ", "NA"))
str(immidata)
attributes(immidata)
names(immidata)
colNum <- dim(immidata)[2]
#checking the columns for uselessnes.
useless <- c()
for (i in 1:colNum){
if(all(sapply(immidata[i],is.na)))
{
useless[i] = i
cat("The column number",i, "is useless!\n")
} else { cat(i,"is not empty\n")
if (dim(immidata[i])[1] > 10){
cat("more than 10 raws\n")
} else {
cat(i,"th raw has the following useful things")
}
}
}
# after the check, removing the column
if (!is.null(useless)){
useless <- useless[!is.na(useless)]
immidata[useless] = NULL
}
# creating a new DF with only the raws interested in
servCenter <- which(immidata[1] == "Service Center")
servCenterBottom <- servCenter + 5
# FOState <- which(immidata[1] == "Field Office by State6") + 1
FOStateBottom <- which(immidata[1] == "Field Office by Territory6")-1
immidata.US <- rbind(immidata[1:FOStateBottom, ] ,
immidata[servCenter:servCenterBottom, ])
# Filling the State column
immidata.US <- fill(immidata.US,1)
### Look into Bookmarks for an excelant post on droping NA raws!
# for now im just gonna use filter(v, is.na(w) & is.na(k))
# here I take only the raws that have NA in 2nd and 3rd columns
# by check if 2nd and 3rd column are NA, and then passin the resulting
# boolien vector to the main DF to select only those rows.
row.names(immidata.US[is.na(immidata.US[2]) & is.na(immidata.US[3]),])
# after chcking that this names actually give the empty raws, i just delete
# them, by revercing the resulting Boolien vecotr of
# is.na(immidata.US[2]) & is.na(immidata.US[3])
immidata.US <- immidata.US[!(is.na(immidata.US[2]) & is.na(immidata.US[3]) &
is.na(immidata.US[4])), ]
# Chopping the last 4 columns
immidata.US <- immidata.US[ ,-((dim(immidata.US)[2]-3):dim(immidata.US)[2])]
# Now i exported this final "half-read" data to Excel and did some
# retouching
write.csv(immidata.US, newfile, row.names = FALSE)
}
cleaningData("./USCIS/I130_performancedata_fy2014_qtr4.csv","d2014.4.csv")
# I manually deleted the raws in the 2014 data
# fixing the data in d2015.csv by adding the code column
df2 <- read.csv('d2015.44.csv')
df1 <- read.csv('d2014.4.csv')
# head(df2)
# tail(df2,10)
# head(df1)
df1$code = df2[ ,3]
# nrow(df2)
# nrow(df1)
# colnames(df1)
# colnames(df2)
# ncol(df1)
# ncol(df2)
df1 <- df1[ ,c(1,2,11,3:10)]
# colnames(df1)
# str(df1)
write.csv(df1,'d2014.4.csv', row.names = FALSE)
|
#
# Copyright 2007-2017 The OpenMx Project
#
# 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.
##' Reset global options to the default
mxSetDefaultOptions <- function() {
options('mxDefaultType' = 'default',
'mxOptions' = c(npsolOptions, checkpointOptions, otherOptions,
list("Default optimizer" = imxDetermineDefaultOptimizer())),
'mxByrow' = FALSE,
'mxCondenseMatrixSlots' = FALSE,
'mxShowDimnames' = TRUE,
'mxPrintUnitTests' = TRUE,
'swift.initialexpr' = "library(OpenMx)")
}
##' imxHasOpenMP
##'
##' This is an internal function exported for those people who know
##' what they are doing.
imxHasOpenMP <- function() .Call(hasOpenMP_wrapper)
.onLoad <- function(libname, pkgname) {
mxSetDefaultOptions()
}
.onAttach <- function(libname, pkgname) {
if (.Platform$GUI!="Rgui") {
.Call(.enableMxLog)
} else {
packageStartupMessage(paste("Notice: R GUI cannot display verbose output from the OpenMx backend.",
"If you need detail diagnostics then R CMD BATCH is one option."))
}
if (!imxHasOpenMP()) {
packageStartupMessage("OpenMx is not compiled to take advantage of computers with multiple cores.")
} else if (Sys.getenv("OMP_NUM_THREADS") == "") {
packageStartupMessage(paste0("To take full advantage of multiple cores, use:\n",
" mxOption(NULL, 'Number of Threads', parallel::detectCores())"))
}
if (!is.na(match("package:expm", search()))) {
packageStartupMessage(paste("** Holy cannoli! You must be a pretty advanced and awesome user.",
"The expm package is loaded.",
"Note that expm defines %^% as repeated matrix multiplication (matrix to a power)",
"whereas OpenMx defines the same operation as",
"elementwise powering of one matrix by another (Kronecker power)."))
}
}
#' Test thread-safe output code
#'
#' This is the code that the backend uses to write diagnostic
#' information to standard error. This function should not be called
#' from R. We make it available only for testing.
#'
#' @param str the character string to output
imxLog <- function(str) .Call(Log_wrapper, str)
#' OpenMx: An package for Structural Equation Modeling and Matrix Algebra Optimization
#'
#' OpenMx is a package for structural equation modeling, matrix algebra optimization and other statistical estimation problems.
#' Try the example below. We try and have useful help files: for instance help(\code{\link{mxRun}}) to learn more. Also the reference manual
#'
#' @details OpenMx solves algebra optimization and statistical estimation problems using matrix algebra.
#' Most users use it for Structural equation modeling.
#'
#' The core function is \code{\link{mxModel}}, which makes a model. Models are containers for data, matrices, \code{\link{mxPath}}s
#' algebras, bounds and constraints. Models most often have an expectation function (e.g., \code{\link{mxExpectationNormal}})
#' to calculate the expectations for the model. Models need a fit function. Several of these are built-in (e.g., \link{mxFitFunctionML} )
#' OpenMx also allows user-defined fit functions for purposes not covered by the built-in functions. (e.g., \link{mxFitFunctionR} or \link{mxFitFunctionAlgebra}).
#'
#' Once built, the resulting mxModel can be run (i.e., optimized) using \code{\link{mxRun}}. This returns the fitted model.
#'
#' You can see the resulting parameter estimates, algebra evaluation etc using \code{\link[=summary.MxModel]{summary}}(yourModel)
#'
#' The user's manual is online (see reference below), but functions \link{mxRun}, \link{mxModel}, \link{mxMatrix}
#' all have working examples to get you started as well.
#'
#' The main OpenMx functions are: \link{mxAlgebra}, \link{mxBounds}, \link{mxCI}, \link{mxConstraint}, \link{mxData},
#' \link{mxMatrix}, \link{mxModel}, and \link{mxPath}
#'
#' Expectation functions include \link{mxExpectationNormal}, \link{mxExpectationRAM}, \link{mxExpectationLISREL}, and \link{mxExpectationStateSpace};
#'
#' Fit functions include \link{mxFitFunctionML}, \link{mxFitFunctionAlgebra}, \link{mxFitFunctionRow} and \link{mxFitFunctionR}.
#'
#' OpenMx comes with several useful datasets built-in. Access them using data(package="OpenMx")
#'
#'
#' To cite package 'OpenMx' in publications use:
#'
#' Michael C. Neale, Michael D. Hunter, Joshua N. Pritikin, Mahsa Zahery, Timothy R. Brick Robert M.
#' Kickpatrick, Ryne Estabrook, Timothy C. Bates, Hermine H. Maes, Steven M. Boker. (in press).
#' OpenMx 2.0: Extended structural equation and statistical modeling. \emph{Psychometrika}.
#' DOI: 10.1007/s11336-014-9435-8
#'
#' Steven M. Boker, Michael C. Neale, Hermine H. Maes, Michael J. Wilde, Michael Spiegel, Timothy R. Brick,
#' Jeffrey Spies, Ryne Estabrook, Sarah Kenny, Timothy C. Bates, Paras Mehta, and John Fox. (2011)
#' OpenMx: An Open Source Extended Structural Equation Modeling Framework.
#' \emph{Psychometrika}, 306-317. DOI:10.1007/s11336-010-9200-6
#'
#' Steven M. Boker, Michael C. Neale, Hermine H. Maes, Michael J. Wilde, Michael Spiegel, Timothy R. Brick, Ryne
#' Estabrook, Timothy C. Bates, Paras Mehta, Timo von Oertzen, Ross J. Gore, Michael D. Hunter, Daniel C.
#' Hackett, Julian Karch, Andreas M. Brandmaier, Joshua N. Pritikin, Mahsa Zahery, Robert M. Kirkpatrick,
#' Yang Wang, and Charles Driver. (2016) OpenMx 2 User Guide.
#' http://openmx.psyc.virginia.edu/docs/OpenMx/latest/OpenMxUserGuide.pdf
#'
#' @references The OpenMx User's guide can be found at \url{http://openmx.psyc.virginia.edu/documentation}
#'
#' @examples
#' library(OpenMx)
#' data(demoOneFactor)
#' # ===============================
#' # = Make and run a 1-factor CFA =
#' # ===============================
#'
#' latents = c("G") # the latent factor
#' manifests = names(demoOneFactor) # manifest variables to be modeled
#' # ====================
#' # = Make the MxModel =
#' # ====================
#' m1 <- mxModel("One Factor", type = "RAM",
#' manifestVars = manifests, latentVars = latents,
#' mxPath(from = latents, to = manifests),
#' mxPath(from = manifests, arrows = 2),
#' mxPath(from = latents, arrows = 2, free = FALSE, values = 1.0),
#' mxData(cov(demoOneFactor), type = "cov", numObs = 500)
#' )
#'
#' # ===============================
#' # = mxRun it and get a summary! =
#' # ===============================
#'
#' m1 = mxRun(m1)
#' summary(m1, show = "std")
#'
#' @docType package
#' @name OpenMx
NULL
| /R/zzz.R | no_license | ktargows/OpenMx | R | false | false | 6,897 | r | #
# Copyright 2007-2017 The OpenMx Project
#
# 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.
##' Reset global options to the default
mxSetDefaultOptions <- function() {
options('mxDefaultType' = 'default',
'mxOptions' = c(npsolOptions, checkpointOptions, otherOptions,
list("Default optimizer" = imxDetermineDefaultOptimizer())),
'mxByrow' = FALSE,
'mxCondenseMatrixSlots' = FALSE,
'mxShowDimnames' = TRUE,
'mxPrintUnitTests' = TRUE,
'swift.initialexpr' = "library(OpenMx)")
}
##' imxHasOpenMP
##'
##' This is an internal function exported for those people who know
##' what they are doing.
imxHasOpenMP <- function() .Call(hasOpenMP_wrapper)
.onLoad <- function(libname, pkgname) {
mxSetDefaultOptions()
}
.onAttach <- function(libname, pkgname) {
if (.Platform$GUI!="Rgui") {
.Call(.enableMxLog)
} else {
packageStartupMessage(paste("Notice: R GUI cannot display verbose output from the OpenMx backend.",
"If you need detail diagnostics then R CMD BATCH is one option."))
}
if (!imxHasOpenMP()) {
packageStartupMessage("OpenMx is not compiled to take advantage of computers with multiple cores.")
} else if (Sys.getenv("OMP_NUM_THREADS") == "") {
packageStartupMessage(paste0("To take full advantage of multiple cores, use:\n",
" mxOption(NULL, 'Number of Threads', parallel::detectCores())"))
}
if (!is.na(match("package:expm", search()))) {
packageStartupMessage(paste("** Holy cannoli! You must be a pretty advanced and awesome user.",
"The expm package is loaded.",
"Note that expm defines %^% as repeated matrix multiplication (matrix to a power)",
"whereas OpenMx defines the same operation as",
"elementwise powering of one matrix by another (Kronecker power)."))
}
}
#' Test thread-safe output code
#'
#' This is the code that the backend uses to write diagnostic
#' information to standard error. This function should not be called
#' from R. We make it available only for testing.
#'
#' @param str the character string to output
imxLog <- function(str) .Call(Log_wrapper, str)
#' OpenMx: An package for Structural Equation Modeling and Matrix Algebra Optimization
#'
#' OpenMx is a package for structural equation modeling, matrix algebra optimization and other statistical estimation problems.
#' Try the example below. We try and have useful help files: for instance help(\code{\link{mxRun}}) to learn more. Also the reference manual
#'
#' @details OpenMx solves algebra optimization and statistical estimation problems using matrix algebra.
#' Most users use it for Structural equation modeling.
#'
#' The core function is \code{\link{mxModel}}, which makes a model. Models are containers for data, matrices, \code{\link{mxPath}}s
#' algebras, bounds and constraints. Models most often have an expectation function (e.g., \code{\link{mxExpectationNormal}})
#' to calculate the expectations for the model. Models need a fit function. Several of these are built-in (e.g., \link{mxFitFunctionML} )
#' OpenMx also allows user-defined fit functions for purposes not covered by the built-in functions. (e.g., \link{mxFitFunctionR} or \link{mxFitFunctionAlgebra}).
#'
#' Once built, the resulting mxModel can be run (i.e., optimized) using \code{\link{mxRun}}. This returns the fitted model.
#'
#' You can see the resulting parameter estimates, algebra evaluation etc using \code{\link[=summary.MxModel]{summary}}(yourModel)
#'
#' The user's manual is online (see reference below), but functions \link{mxRun}, \link{mxModel}, \link{mxMatrix}
#' all have working examples to get you started as well.
#'
#' The main OpenMx functions are: \link{mxAlgebra}, \link{mxBounds}, \link{mxCI}, \link{mxConstraint}, \link{mxData},
#' \link{mxMatrix}, \link{mxModel}, and \link{mxPath}
#'
#' Expectation functions include \link{mxExpectationNormal}, \link{mxExpectationRAM}, \link{mxExpectationLISREL}, and \link{mxExpectationStateSpace};
#'
#' Fit functions include \link{mxFitFunctionML}, \link{mxFitFunctionAlgebra}, \link{mxFitFunctionRow} and \link{mxFitFunctionR}.
#'
#' OpenMx comes with several useful datasets built-in. Access them using data(package="OpenMx")
#'
#'
#' To cite package 'OpenMx' in publications use:
#'
#' Michael C. Neale, Michael D. Hunter, Joshua N. Pritikin, Mahsa Zahery, Timothy R. Brick Robert M.
#' Kickpatrick, Ryne Estabrook, Timothy C. Bates, Hermine H. Maes, Steven M. Boker. (in press).
#' OpenMx 2.0: Extended structural equation and statistical modeling. \emph{Psychometrika}.
#' DOI: 10.1007/s11336-014-9435-8
#'
#' Steven M. Boker, Michael C. Neale, Hermine H. Maes, Michael J. Wilde, Michael Spiegel, Timothy R. Brick,
#' Jeffrey Spies, Ryne Estabrook, Sarah Kenny, Timothy C. Bates, Paras Mehta, and John Fox. (2011)
#' OpenMx: An Open Source Extended Structural Equation Modeling Framework.
#' \emph{Psychometrika}, 306-317. DOI:10.1007/s11336-010-9200-6
#'
#' Steven M. Boker, Michael C. Neale, Hermine H. Maes, Michael J. Wilde, Michael Spiegel, Timothy R. Brick, Ryne
#' Estabrook, Timothy C. Bates, Paras Mehta, Timo von Oertzen, Ross J. Gore, Michael D. Hunter, Daniel C.
#' Hackett, Julian Karch, Andreas M. Brandmaier, Joshua N. Pritikin, Mahsa Zahery, Robert M. Kirkpatrick,
#' Yang Wang, and Charles Driver. (2016) OpenMx 2 User Guide.
#' http://openmx.psyc.virginia.edu/docs/OpenMx/latest/OpenMxUserGuide.pdf
#'
#' @references The OpenMx User's guide can be found at \url{http://openmx.psyc.virginia.edu/documentation}
#'
#' @examples
#' library(OpenMx)
#' data(demoOneFactor)
#' # ===============================
#' # = Make and run a 1-factor CFA =
#' # ===============================
#'
#' latents = c("G") # the latent factor
#' manifests = names(demoOneFactor) # manifest variables to be modeled
#' # ====================
#' # = Make the MxModel =
#' # ====================
#' m1 <- mxModel("One Factor", type = "RAM",
#' manifestVars = manifests, latentVars = latents,
#' mxPath(from = latents, to = manifests),
#' mxPath(from = manifests, arrows = 2),
#' mxPath(from = latents, arrows = 2, free = FALSE, values = 1.0),
#' mxData(cov(demoOneFactor), type = "cov", numObs = 500)
#' )
#'
#' # ===============================
#' # = mxRun it and get a summary! =
#' # ===============================
#'
#' m1 = mxRun(m1)
#' summary(m1, show = "std")
#'
#' @docType package
#' @name OpenMx
NULL
|
##' Check if the probe set is "perfect"
##'
##' A "perfect" probe set is a probe set where all the 11 probes are
##' unequivocally mapping the same transcript, on the positive
##' strand and with no mismatches. This function returns TRUE if
##' the quality string of a probe set is such that the probe set
##' turns out to be "perfect"
##' @title Check if the quality string tells that the probe set is
##' "perfect"
##' @param s a quality string
##' @param n_probes integer. The number of probes composing a probeset.
##' \code{n_probes} is 11 in the old ADX platform and 12 in the new
##' Excel platform.
##' @return A logical value. If TRUE the probe set is "perfect".
##' @author Giovanni d'Ario
##' @export
is_perfect <- function(s, n_probes=NULL) {
if(is.null(n_probes))
stop("Please specify the number of probes composing a probeset")
x <- quality_string_to_table(s)
idx1 <- (nrow(x) == 1) & (ncol(x) == 1) # maps one single gene?
idx2 <- x[1,1] == n_probes
return(idx1 & idx2)
}
##' Check if all the probe sets associated with a particular
##' combination of Gene ID and Refseq ID are perfect
##'
##' @title Check if all the probe sets associated with a particular
##' combination of Gene ID and Refseq ID are perfect
##' @param gene_id a string of the format geneid:refseqid
##' @param annot an annotation data frame, obtained by applying
##' @param n_probes integer, the number of probes composing a probeset.
##' \code{n_probes} is 11 in the old ADX platform and 12 in the new
##' Excel platform.
##' \code{almac_reannotation} to the output of bowtie
##' @return a logical value: TRUE if all the probe sets associate with
##' the gene_id are 'perfect'.
##' @author Giovanni d'Ario
are_all_psets_perfect <- function(gene_id=NULL,
annot=NULL,
n_probes=NULL) {
if(is.null(n_probes))
stop("Please specify the number of probes composing a probeset")
idx <- grep(gene_id, annot$quality_string)
tmp <- annot[idx, ]
out <- sapply(tmp$quality_string, is_perfect, n_probes = n_probes)
return(all(out))
}
| /R/is_perfect.R | no_license | gdario/almacannot | R | false | false | 2,134 | r | ##' Check if the probe set is "perfect"
##'
##' A "perfect" probe set is a probe set where all the 11 probes are
##' unequivocally mapping the same transcript, on the positive
##' strand and with no mismatches. This function returns TRUE if
##' the quality string of a probe set is such that the probe set
##' turns out to be "perfect"
##' @title Check if the quality string tells that the probe set is
##' "perfect"
##' @param s a quality string
##' @param n_probes integer. The number of probes composing a probeset.
##' \code{n_probes} is 11 in the old ADX platform and 12 in the new
##' Excel platform.
##' @return A logical value. If TRUE the probe set is "perfect".
##' @author Giovanni d'Ario
##' @export
is_perfect <- function(s, n_probes=NULL) {
if(is.null(n_probes))
stop("Please specify the number of probes composing a probeset")
x <- quality_string_to_table(s)
idx1 <- (nrow(x) == 1) & (ncol(x) == 1) # maps one single gene?
idx2 <- x[1,1] == n_probes
return(idx1 & idx2)
}
##' Check if all the probe sets associated with a particular
##' combination of Gene ID and Refseq ID are perfect
##'
##' @title Check if all the probe sets associated with a particular
##' combination of Gene ID and Refseq ID are perfect
##' @param gene_id a string of the format geneid:refseqid
##' @param annot an annotation data frame, obtained by applying
##' @param n_probes integer, the number of probes composing a probeset.
##' \code{n_probes} is 11 in the old ADX platform and 12 in the new
##' Excel platform.
##' \code{almac_reannotation} to the output of bowtie
##' @return a logical value: TRUE if all the probe sets associate with
##' the gene_id are 'perfect'.
##' @author Giovanni d'Ario
are_all_psets_perfect <- function(gene_id=NULL,
annot=NULL,
n_probes=NULL) {
if(is.null(n_probes))
stop("Please specify the number of probes composing a probeset")
idx <- grep(gene_id, annot$quality_string)
tmp <- annot[idx, ]
out <- sapply(tmp$quality_string, is_perfect, n_probes = n_probes)
return(all(out))
}
|
/Practica 3/RCommander.R | no_license | josebummer/ugr_estadistica | R | false | false | 2,001 | r | ||
#Final Project
# import dataset
library(classInt)
library(readxl)
library(corrplot)
library(CCA)
library(yacca)
library(MASS)
library(ggplot2)
library(GGally)
Automobile <- read_excel("C:/Trupti MS/CSC424AdvDataAnalaysis/FinalProject/AutomobileFinal .xlsx")
View(Automobile)
head(Automobile)
str(Automobile)
dim(Automobile)
describe(Automobile)
range(Automobile$normalized_losses)
warnings()
as.numeric(Automobile$normalized_losses)
is.na(Automobile$normalized_losses)
sum(is.na(Automobile))
sum(is.na(Automobile$normalized_losses))
#need to fill in missing values for normalized_losses, checking if the data is normalized
#the data looks skewed to right and hence cannot use mean to fill in missing values.
hist(as.numeric(Automobile$normalized_losses))
# equla depth binning for normalized_losses 65 - 256
## Explanation of how missing values are filled in
# normalized_losses ( used SPSS to remove 37 missing values) used transformation in SPSS, we checked the data is skewed a little to right and hence used SPPS mean of near by points to come up with the missing value
# no. of doors have 1 missing value, we filled that value by checking other values of make,aspiration, engine location, wheel base etc.
# for the value of bore and stroke (displayed in inches) we did some research and found that for the model of mazda, hatchback with rear wheel drive what are the dimensions od bore and stroke and replaced by those values
# for horsepower and peak_rpm, the missing values where for renault car model and we have only two rows of data, hence here as well we just identified some renault model from internet and replaced the missing values
######################### PCA ###########
#considering all numeric variables
automobilenum = Automobile[,c(26,1,2,10:14,17,19:25)]
describe(automobilenum)
str(automobilenum)
# Box plots
boxplot(Automobile$price~Automobile$make,main="Boxplot of Price vs Make",xlab="Make of the car",ylab="Price of the car")
boxplot(Automobile$curb_weight~Automobile$make,main="Boxplot of Curb_Weight vs Make",xlab="Make of the car",ylab="CUrb-Weight")
boxplot(Automobile$peak_rpm~Automobile$make,main="Boxplot of peak-rpm vs Make",xlab="Make of the car",ylab="peak-rpm")
#correlation of numeric data
cor.pricecitympg = cor(automobilenum$price,automobilenum$city_mpg)
cor.pricecitympg
cor.autonum = cor(automobilenum)
cor.autonum
# plotting the correlations
corrplot(cor.autonum, method="square")
corrplot.mixed(cor.autonum, lower.col = "black", number.cex = .7)
#performing PCA/FA to come up with sets of variables.
pbfi <- prcomp(automobilenum,center=T,scale=T)
print(pbfi)
plot(pbfi)
abline(1,0)
screeplot(pbfi)
abline(1,0)
# carrying out factor analyis to come up with 2 factors which can be used as sets of variables
fit = factanal(automobilenum, 2)
print(fit$loadings, cutoff=.4, sort=T)
summary(fit)
#Carrying out CC on factor1 and factor2
## functions of CC
ccaWilks = function(set1, set2, cca)
{
ev = ((1 - cca$cor^2))
ev
n = dim(set1)[1]
p = length(set1)
q = length(set2)
k = min(p, q)
m = n - 3/2 - (p + q)/2
m
w = rev(cumprod(rev(ev)))
# initialize
d1 = d2 = f = vector("numeric", k)
for (i in 1:k)
{
s = sqrt((p^2 * q^2 - 4)/(p^2 + q^2 - 5))
si = 1/s
d1[i] = p * q
d2[i] = m * s - p * q/2 + 1
r = (1 - w[i]^si)/w[i]^si
f[i] = r * d2[i]/d1[i]
p = p - 1
q = q - 1
}
pv = pf(f, d1, d2, lower.tail = FALSE)
dmat = cbind(WilksL = w, F = f, df1 = d1, df2 = d2, p = pv)
}
str(automobilenum)
#set of IV
Factor1 = automobilenum[c(1,4,5,6,8,9,10,13,15,16)]
Factor1
# set of DV
Factor2 = automobilenum[c(2,7,12,14)]
Factor2
# correlation among the IV and DV factors
ggpairs(Factor1)
ggpairs(Factor2)
#correlations between the IV and DV factors
matcor(Factor1, Factor2)
#carrying oyt simple CCA
ccAutomobile = cc(Factor1, Factor2)
#displays canonical correlations
ccAutomobile$cor
# raw canonical coeffients
ccAutomobile[3:4]
ls(ccAutomobile)
# compute canonical loadings
cc2 <- comput(Factor1,Factor2,ccAutomobile)
cc2[3:6]
# to understand the significance of the variates
wilksCan = ccaWilks(Factor1,Factor2,ccAutomobile)
round(wilksCan, 2)
#compute the scores
loadingsAuto = comput(Factor1,Factor2,ccAutomobile)
ls(loadingsAuto)
loadingsAuto$corr.X.xscores
loadingsAuto$corr.Y.yscores
loadingsAuto$corr.X.yscores
loadingsAuto$corr.Y.xscores
loadingsAuto$xscores
loadingsAuto$yscores
#standardized coefficients
s1 = diag(sqrt(diag(cov(Factor1))))
s1 %*% ccAutomobile$xcoef
s2 = diag(sqrt(diag(cov(Factor2))))
s2 %*% ccAutomobile$ycoef
str(Factor1)
str(Factor2)
| /Car Price Prediction/CanonicalCorrelation.R | no_license | Nisarg94/Machine-Learning-Models | R | false | false | 4,652 | r | #Final Project
# import dataset
library(classInt)
library(readxl)
library(corrplot)
library(CCA)
library(yacca)
library(MASS)
library(ggplot2)
library(GGally)
Automobile <- read_excel("C:/Trupti MS/CSC424AdvDataAnalaysis/FinalProject/AutomobileFinal .xlsx")
View(Automobile)
head(Automobile)
str(Automobile)
dim(Automobile)
describe(Automobile)
range(Automobile$normalized_losses)
warnings()
as.numeric(Automobile$normalized_losses)
is.na(Automobile$normalized_losses)
sum(is.na(Automobile))
sum(is.na(Automobile$normalized_losses))
#need to fill in missing values for normalized_losses, checking if the data is normalized
#the data looks skewed to right and hence cannot use mean to fill in missing values.
hist(as.numeric(Automobile$normalized_losses))
# equla depth binning for normalized_losses 65 - 256
## Explanation of how missing values are filled in
# normalized_losses ( used SPSS to remove 37 missing values) used transformation in SPSS, we checked the data is skewed a little to right and hence used SPPS mean of near by points to come up with the missing value
# no. of doors have 1 missing value, we filled that value by checking other values of make,aspiration, engine location, wheel base etc.
# for the value of bore and stroke (displayed in inches) we did some research and found that for the model of mazda, hatchback with rear wheel drive what are the dimensions od bore and stroke and replaced by those values
# for horsepower and peak_rpm, the missing values where for renault car model and we have only two rows of data, hence here as well we just identified some renault model from internet and replaced the missing values
######################### PCA ###########
#considering all numeric variables
automobilenum = Automobile[,c(26,1,2,10:14,17,19:25)]
describe(automobilenum)
str(automobilenum)
# Box plots
boxplot(Automobile$price~Automobile$make,main="Boxplot of Price vs Make",xlab="Make of the car",ylab="Price of the car")
boxplot(Automobile$curb_weight~Automobile$make,main="Boxplot of Curb_Weight vs Make",xlab="Make of the car",ylab="CUrb-Weight")
boxplot(Automobile$peak_rpm~Automobile$make,main="Boxplot of peak-rpm vs Make",xlab="Make of the car",ylab="peak-rpm")
#correlation of numeric data
cor.pricecitympg = cor(automobilenum$price,automobilenum$city_mpg)
cor.pricecitympg
cor.autonum = cor(automobilenum)
cor.autonum
# plotting the correlations
corrplot(cor.autonum, method="square")
corrplot.mixed(cor.autonum, lower.col = "black", number.cex = .7)
#performing PCA/FA to come up with sets of variables.
pbfi <- prcomp(automobilenum,center=T,scale=T)
print(pbfi)
plot(pbfi)
abline(1,0)
screeplot(pbfi)
abline(1,0)
# carrying out factor analyis to come up with 2 factors which can be used as sets of variables
fit = factanal(automobilenum, 2)
print(fit$loadings, cutoff=.4, sort=T)
summary(fit)
#Carrying out CC on factor1 and factor2
## functions of CC
ccaWilks = function(set1, set2, cca)
{
ev = ((1 - cca$cor^2))
ev
n = dim(set1)[1]
p = length(set1)
q = length(set2)
k = min(p, q)
m = n - 3/2 - (p + q)/2
m
w = rev(cumprod(rev(ev)))
# initialize
d1 = d2 = f = vector("numeric", k)
for (i in 1:k)
{
s = sqrt((p^2 * q^2 - 4)/(p^2 + q^2 - 5))
si = 1/s
d1[i] = p * q
d2[i] = m * s - p * q/2 + 1
r = (1 - w[i]^si)/w[i]^si
f[i] = r * d2[i]/d1[i]
p = p - 1
q = q - 1
}
pv = pf(f, d1, d2, lower.tail = FALSE)
dmat = cbind(WilksL = w, F = f, df1 = d1, df2 = d2, p = pv)
}
str(automobilenum)
#set of IV
Factor1 = automobilenum[c(1,4,5,6,8,9,10,13,15,16)]
Factor1
# set of DV
Factor2 = automobilenum[c(2,7,12,14)]
Factor2
# correlation among the IV and DV factors
ggpairs(Factor1)
ggpairs(Factor2)
#correlations between the IV and DV factors
matcor(Factor1, Factor2)
#carrying oyt simple CCA
ccAutomobile = cc(Factor1, Factor2)
#displays canonical correlations
ccAutomobile$cor
# raw canonical coeffients
ccAutomobile[3:4]
ls(ccAutomobile)
# compute canonical loadings
cc2 <- comput(Factor1,Factor2,ccAutomobile)
cc2[3:6]
# to understand the significance of the variates
wilksCan = ccaWilks(Factor1,Factor2,ccAutomobile)
round(wilksCan, 2)
#compute the scores
loadingsAuto = comput(Factor1,Factor2,ccAutomobile)
ls(loadingsAuto)
loadingsAuto$corr.X.xscores
loadingsAuto$corr.Y.yscores
loadingsAuto$corr.X.yscores
loadingsAuto$corr.Y.xscores
loadingsAuto$xscores
loadingsAuto$yscores
#standardized coefficients
s1 = diag(sqrt(diag(cov(Factor1))))
s1 %*% ccAutomobile$xcoef
s2 = diag(sqrt(diag(cov(Factor2))))
s2 %*% ccAutomobile$ycoef
str(Factor1)
str(Factor2)
|
#*****************************************************************
#* Cary Institute of Ecosystem Studies (Millbrook, NY) *
#* *
#* TITLE: Sunapee_buoy_2009.r *
#* AUTHOR: Bethel Steele *
#* SYSTEM: Lenovo ThinkCentre, Win 10, R 3.5.2, RStudio 1.1.383 *
#* PROJECT: Lake Sunapee Buoy Data Cleaning *
#* PURPOSE: subset data for met/compare with L1 *
#* LAST MODIFIED: 05Sept2019 to create vertical dataset for *
#* master collation *
#*****************************************************************
source('library_func_lists.R')
#bring in 2009 buoy raw data
buoy2009_L0 <- read_csv('C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L0/Sunapee2009_rawData.csv',
col_names = c('datetime', 'AirTempC', 'DOppm', 'DOSat', 'DOSat2',
'PAR', 'DOTempC', 'TempC_0m', 'TempC_0p5m', 'TempC_1m',
'TempC_1p5m', 'TempC_2m', 'TempC_2p5m', 'TempC_3m', 'TempC_4m',
'TempC_5m', 'TempC_6m', 'TempC_7m', 'TempC_8m', 'TempC_9m',
'TempC_10m', 'TempC_11m', 'TempC_13m', 'AveWindDir', 'InstWindDir',
'InstWindSp', 'AveWindSp'),
col_types = 'cnnnnnnnnnnnnnnnnnnnnnnnnnn',
skip=1) %>%
select(-DOSat2) %>% #drop blank columns
mutate(datetime = as.POSIXct(datetime, format='%Y-%m-%d %H:%M:%S', tz='UTC'))
#create dummy timestamp so there are no blanks
alltimes_2009 <- as.data.frame(seq.POSIXt(as.POSIXct('2009-01-01 00:00', tz='UTC'), as.POSIXct('2009-12-31 23:50', tz='UTC'), '10 min')) %>%
rename("datetime" = !!names(.[1]))
buoy2009_L1 <- buoy2009_L0 %>%
right_join(., alltimes_2009) %>%
arrange(datetime)
#double check to make sure there are no DST issues
datelength2009 <- buoy2009_L1 %>%
mutate(date = format(datetime, '%Y-%m-%d')) %>%
group_by(date) %>%
summarize(length(datetime))
max(datelength2009$`length(datetime)`)
min(datelength2009$`length(datetime)`)
#should only be 144 or less if partial days included
#clean up workspace
rm(alltimes_2009, datelength2009)
#### thermistors ####
buoy2009_temp_vert <- buoy2009_L1 %>%
select(datetime, alltemp2007) %>%
gather(variable, value, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='2009 buoy temp raw',
# x=NULL,
# y='temp (deg C)') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89",
# "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(alltemp2007),
funs(case_when(. == -6999 ~ NA_real_,
. == -99.9 ~ NA_real_,
TRUE ~ .))) %>%
mutate(location = 'loon',
temp_flag = NA_character_)
buoy2009_temp_vert <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
ggplot(subset(buoy2009_temp_vert,
subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
datetime < as.POSIXct('2010-01-01', tz='UTC'))),
aes(x=datetime, y=value, color=(variable))) +
geom_point() +
final_theme +
labs(title='2009 buoy temp NAs recoded',
x=NULL,
y='temp (deg C)') +
scale_x_datetime(date_minor_breaks = '1 month') +
scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
"#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jan 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate(temp_flag = case_when(datetime < as.POSIXct('2009-01-15', tz='UTC') & is.na(temp_flag) ~ 'i,9.5d, 10.5d, 11.5d, 13.5d',
TRUE ~ temp_flag))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jan 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Feb 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# #data gap until jul
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-28', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# #look at beginning of record
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-28', tz='UTC') &
# datetime < as.POSIXct('2009-07-29', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-24', tz='UTC') &
# datetime < as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-01', tz='UTC') &
# datetime < as.POSIXct('2009-08-08', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-08', tz='UTC') &
# datetime < as.POSIXct('2009-08-15', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# #anomalous points Aug 11,13 and 24
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-11', tz='UTC') &
# datetime < as.POSIXct('2009-08-12', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-12', tz='UTC') &
# datetime < as.POSIXct('2009-08-13', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-13', tz='UTC') &
# datetime < as.POSIXct('2009-08-14', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-08-24', tz='UTC') &
# datetime < as.POSIXct('2009-08-25', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-08-31', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-01 12:00', tz='UTC') &
# datetime < as.POSIXct('2009-08-02 12:00', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-26', tz='UTC') &
# datetime < as.POSIXct('2009-08-27', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-31', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(TempC_0p5m:TempC_4m), #temp shifts
funs(case_when(is.na(TempC_5m) ~ NA_real_,
TRUE ~ .))) %>%
mutate_at(vars(TempC_6m:TempC_13m),
funs(case_when(TempC_13m > TempC_11m & datetime >= as.POSIXct('2009-07-28', tz='UTC') & datetime < as.POSIXct('2009-10-02 12:00', tz='UTC')~ NA_real_, # temp shifts
TempC_13m > TempC_6m & datetime >= as.POSIXct('2009-07-28', tz='UTC') & datetime < as.POSIXct('2009-10-02 12:00', tz='UTC')~ NA_real_, # temp shifts
TRUE ~ .))) %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime >= as.POSIXct('2009-02-01', tz='UTC') & datetime < as.POSIXct('2009-07-28', tz='UTC') ~ NA_real_,
TempC_8m < 7.5 & datetime > as.POSIXct('2009-08-01', tz='UTC') & datetime < as.POSIXct('2009-09-01', tz='UTC') ~ NA_real_, #temp shifts
TRUE ~ .))) %>%
mutate_at(vars(TempC_8m:TempC_11m),
funs(case_when(is.na(TempC_13m)~ NA_real_, #temp shifts
TRUE ~ .))) %>%
mutate(TempC_13m = case_when(is.na(TempC_1m) ~ NA_real_, #temp shifts
TRUE ~ TempC_13m)) %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime == as.POSIXct('2009-08-31 11:40', tz='UTC') ~ NA_real_,
TRUE ~ .)))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-28', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-09-01', tz='UTC') &
# datetime < as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Sept 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-10-01', tz='UTC') &
# datetime < as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Oct 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-11-01', tz='UTC') &
# datetime < as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Nov 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# #Nov 16
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-11-16', tz='UTC') &
# datetime < as.POSIXct('2009-11-17', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Nov 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime == as.POSIXct('2009-11-16 6:50', tz='UTC') ~ NA_real_,
TRUE ~ .)))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-11-01', tz='UTC') &
# datetime < as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Nov 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-12-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# # #Dec 8, 12, 17, 23/24
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-12-08', tz='UTC') &
# datetime < as.POSIXct('2009-12-09', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-12', tz='UTC') &
# datetime < as.POSIXct('2009-12-13', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-12-17', tz='UTC') &
# datetime < as.POSIXct('2009-12-18', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-21', tz='UTC') &
# datetime < as.POSIXct('2009-12-22', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-22', tz='UTC') &
# datetime < as.POSIXct('2009-12-23', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-23', tz='UTC') &
# datetime < as.POSIXct('2009-12-24', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-24', tz='UTC') &
# datetime < as.POSIXct('2009-12-25', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-29', tz='UTC') &
# datetime < as.POSIXct('2009-12-30', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime == as.POSIXct('2009-12-08 23:20', tz='UTC') ~ NA_real_, #anamolous shift
datetime >= as.POSIXct('2009-12-12 4:50', tz='UTC') & datetime < as.POSIXct('2009-12-12 9:00', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-17 4:00', tz='UTC') & datetime < as.POSIXct('2009-12-17 5:20', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-17 12:20', tz='UTC') & datetime < as.POSIXct('2009-12-17 15:00', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-21 19:30', tz='UTC') & datetime < as.POSIXct('2009-12-22 6:10', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-22 19:00', tz='UTC') & datetime < as.POSIXct('2009-12-22 22:00', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-29 9:50', tz='UTC') & datetime < as.POSIXct('2009-12-29 11:20', tz='UTC') ~ NA_real_, #flatline
is.na(TempC_1p5m) ~ NA_real_, #anamolous shift
TRUE ~ .)))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 month') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate(temp_flag = case_when(!is.na(temp_flag) & datetime>=as.POSIXct('2009-12-12', tz='UTC') ~ paste(temp_flag, 'i', sep = ', '),
is.na(temp_flag) & datetime>=as.POSIXct('2009-12-12', tz='UTC') ~ 'i',
TRUE ~ temp_flag))
#add flag for 11.5 and 13.5 as possibly in sediment
buoy2009_L1 <- buoy2009_L1 %>%
mutate(temp_flag = case_when(is.na(temp_flag) ~ '11.5b, 13.5b',
!is.na(temp_flag) ~ paste(temp_flag, '11.5b, 13.5b', sep = ', '),
TRUE ~ temp_flag))
unique(buoy2009_L1$temp_flag)
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007, temp_flag) %>%
gather(variable, value, -location, -datetime, -temp_flag) %>%
mutate(variable = factor(variable, levels=alltemp2007))
ggplot(subset(buoy2009_temp_vert_b,
subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
datetime < as.POSIXct('2010-01-01', tz='UTC'))),
aes(x=datetime, y=value, color=(variable), shape = temp_flag)) +
geom_point() +
final_theme +
labs(title='2009, clean',
x=NULL,
y='temp deg C') +
scale_x_datetime(date_minor_breaks = '1 month') +
scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
"#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#add in offline location
buoy2009_L1 <- buoy2009_L1 %>%
mutate(location = case_when(datetime < as.POSIXct('2009-01-01 7:50', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-01-14 18:00', tz='UTC') &
datetime < as.POSIXct('2009-02-06 11:10', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-02-06 12:00', tz='UTC') &
datetime < as.POSIXct('2009-02-18 0:10', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-02-19 12:50', tz='UTC') &
datetime < as.POSIXct('2009-02-23 13:00', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-04-15 3:00', tz='UTC') &
datetime < as.POSIXct('2009-07-28 13:30', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-12-31 0:10',tz='UTC') ~ 'offline',
TRUE ~ location)) %>%
mutate(temp_flag = case_when(location == 'offline' ~ NA_character_,
TRUE~temp_flag))
#clean up workspace
rm(buoy2009_temp_vert, buoy2009_temp_vert_b)
#correct thermistor depth for offset
buoy2009_L1 <- buoy2009_L1 %>%
rename(TempC_13p5m = TempC_13m,
TempC_11p5m = TempC_11m,
TempC_10p5m = TempC_10m,
TempC_9p5m = TempC_9m,
TempC_8p5m = TempC_8m,
TempC_7p5m = TempC_7m,
TempC_6p5m = TempC_6m,
TempC_5p5m = TempC_5m,
TempC_4p5m = TempC_4m,
TempC_3p5m = TempC_3m,
TempC_3m = TempC_2p5m,
TempC_2p5m = TempC_2m,
TempC_2m = TempC_1p5m,
TempC_1p5m = TempC_1m,
TempC_1m = TempC_0p5m,
TempC_0p5m = TempC_0m)
#### DO sensors ####
range(buoy2009_L1$DOSat, na.rm=T)
range(buoy2009_L1$DOppm, na.rm=T)
range(buoy2009_L1$DOTempC, na.rm=T)
do_vert <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime)
# ggplot(do_vert, aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = '2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 month')
buoy2009_L1 <- buoy2009_L1 %>%
mutate(DOTempC = case_when(DOTempC == -6999 ~ NA_real_,
TRUE ~ DOTempC))
do_vert <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC, location) %>%
gather(variable, value, -datetime, -location)
ggplot(do_vert, aes(x = datetime, y = value, color = location)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 DO data NA values recoded',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jan 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#start seeing intermittent readings dec 29 - adding flag of intermittent do data from then throught the end of the month
buoy2009_L1 <- buoy2009_L1 %>%
mutate(upper_do_flag = case_when(datetime < as.POSIXct('2009-01-15', tz='UTC') ~ 'i',
TRUE ~ NA_character_))
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#data before feb 23 recoded to NA
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(DOSat, DOppm, DOTempC),
funs(case_when(datetime >= as.POSIXct('2009-02-01', tz='UTC') &
datetime < as.POSIXct('2009-02-23', tz='UTC') ~ NA_real_,
TRUE ~ .)))
do_vert_b <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime)
# ggplot(subset(do_vert_b,
# subset = (datetime >= as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 DO data clean',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-03-01', tz='UTC') &
# datetime < as.POSIXct('2009-04-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'mar 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-04-01', tz='UTC') &
# datetime < as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# #errant readings beginning apr 5
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-04-05', tz='UTC') &
# datetime < as.POSIXct('2009-04-06', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(DOSat, DOppm, DOTempC),
funs(case_when(datetime >= as.POSIXct('2009-04-05 1:40', tz='UTC') &
datetime < as.POSIXct('2009-04-16', tz='UTC') ~ NA_real_,
TRUE ~ .)))
do_vert_b <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime)
# ggplot(subset(do_vert_b,
# subset = (datetime >= as.POSIXct('2009-04-01', tz='UTC') &
# datetime < as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 DO data clean',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-05-01', tz='UTC') &
# datetime < as.POSIXct('2009-06-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'may 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-06-01', tz='UTC') &
# datetime < as.POSIXct('2009-07-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jun 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-07-01', tz='UTC') &
# datetime < as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jul 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-08-01', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'aug 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-09-01', tz='UTC') &
# datetime < as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-10-01', tz='UTC') &
# datetime < as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'oct 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-11-01', tz='UTC') &
# datetime < as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'nov 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-12-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'dec 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
do_vert_b <- buoy2009_L1 %>%
select(datetime, location, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime, -location)
# ggplot(do_vert_b,
# aes(x = datetime, y = value, color = location)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = '2009 DO data clean',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 month')
# add presumed cleaning flags and possible non-calibration flags
buoy2009_L1 <- buoy2009_L1 %>%
mutate(upper_do_flag = case_when(datetime == as.POSIXct('2009-07-28 13:30', tz='UTC') ~ 'wp',
TRUE ~ upper_do_flag)) %>%
mutate(upper_do_flag = case_when(!is.na(upper_do_flag) ~ paste('x', upper_do_flag, sep = ', '),
TRUE ~ 'x')) %>%
mutate(upper_do_flag = case_when(location == 'offline' ~ NA_character_,
TRUE ~ upper_do_flag))
do_vert_b <- buoy2009_L1 %>%
select(datetime, location, DOSat, DOppm, DOTempC, upper_do_flag) %>%
gather(variable, value, -datetime, -location, - upper_do_flag)
ggplot(do_vert_b,
aes(x = datetime, y = value, shape = location, color = upper_do_flag)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 DO data clean',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
rm(do_vert, do_vert_b)
#### wind sensors ####
range(buoy2009_L1$InstWindDir, na.rm = T)
range(buoy2009_L1$InstWindSp, na.rm = T)
range(buoy2009_L1$AveWindDir, na.rm = T)
range(buoy2009_L1$AveWindSp, na.rm = T)
wind_vert <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp) %>%
gather(variable, value, -datetime)
# ggplot(wind_vert, aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = '2009 wind data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 month')
buoy2009_L1 <- buoy2009_L1 %>%
mutate(InstWindDir = case_when(InstWindDir==-6999 ~ NA_real_,
TRUE ~ InstWindDir))
wind_vert <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp) %>%
gather(variable, value, -datetime)
ggplot(wind_vert, aes(x = datetime, y = value)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 wind data NAs recoded',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime<as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jan 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-02-01', tz='UTC') &
# datetime<as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(InstWindSp, InstWindDir),
funs(case_when(datetime<as.POSIXct('2009-02-18 0:10', tz='UTC') ~ NA_real_,
TRUE ~ .)))
wind_vert_b <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp) %>%
gather(variable, value, -datetime)
# ggplot(subset(wind_vert_b,
# subset=(datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime<as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-03-01', tz='UTC') &
# datetime<as.POSIXct('2009-04-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'mar 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-04-01', tz='UTC') &
# datetime<as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-05-01', tz='UTC') &
# datetime<as.POSIXct('2009-06-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'may 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-06-01', tz='UTC') &
# datetime<as.POSIXct('2009-07-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jun 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-07-01', tz='UTC') &
# datetime<as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'july 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-08-01', tz='UTC') &
# datetime<as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'aug 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-09-01', tz='UTC') &
# datetime<as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-10-01', tz='UTC') &
# datetime<as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'oct 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-11-01', tz='UTC') &
# datetime<as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'nov 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
# # look at nov 27-28
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-11-27 12:00', tz='UTC') &
# datetime<as.POSIXct('2009-11-28 18:00', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
# odd to have so many 0 readings, but not a sensor frozen issue, leaving in
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-12-01', tz='UTC') &
# datetime<as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# #dec 26 sensor frozen
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-12-26', tz='UTC') &
# datetime<as.POSIXct('2009-12-27', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
# #dec 26 sensor frozen
# ggplot(subset(wind_vert_b,
# subset=(datetime>=as.POSIXct('2009-12-26 12:00', tz='UTC') &
# datetime<as.POSIXct('2009-12-27 12:00', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(InstWindSp, InstWindDir, AveWindSp, AveWindDir),
funs(case_when(datetime>=as.POSIXct('2009-12-26 19:40', tz='UTC') &
datetime<as.POSIXct('2009-12-26 21:50', tz='UTC') ~ NA_real_,
TRUE ~ .)))
wind_vert_b <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp, location) %>%
gather(variable, value, -datetime, -location)
# ggplot(subset(wind_vert_b,
# subset=(datetime>=as.POSIXct('2009-12-01', tz='UTC') &
# datetime<as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
# add flag to wind direction prior to jul 28 when buoy online
buoy2009_L1 <- buoy2009_L1 %>%
mutate(wind_dir_flag = case_when(datetime < as.POSIXct('2009-07-28', tz='UTC') & !is.na(InstWindDir) ~ 'e',
TRUE ~ NA_character_))
wind_vert_b <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp, location, wind_dir_flag) %>%
gather(variable, value, -datetime, -location, -wind_dir_flag)
ggplot(wind_vert_b,
aes(x = datetime, y = value, color = wind_dir_flag)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 wind data clean',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
rm(wind_vert, wind_vert_b)
#### PAR ####
range(buoy2009_L1$PAR, na.rm = T)
# ggplot(buoy2009_L1, aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme
buoy2009_L1 <- buoy2009_L1 %>%
mutate(PAR_flag = case_when(PAR <0 ~ 'z',
TRUE ~ NA_character_),
PAR = case_when(PAR <0 ~ 0,
TRUE ~ PAR))
ggplot(buoy2009_L1, aes(x = datetime, y = PAR)) +
geom_point() +
final_theme +
labs(title = '2009 PAR data below 0 recoded',
x = NULL,
y = 'PAR (umol/m2/s)') +
scale_x_datetime(date_minor_breaks = '1 month')
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime<as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'jan 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#jan data incomplete. flagging as intermittent
buoy2009_L1 <- buoy2009_L1 %>%
mutate(PAR_flag = case_when(datetime<as.POSIXct('2009-01-15', tz='UTC') & is.na(PAR_flag) ~ 'i',
datetime<as.POSIXct('2009-01-15', tz='UTC') & !is.na(PAR_flag) ~ paste('i', PAR_flag, sep = ', '),
TRUE ~ PAR_flag))
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-02-01', tz='UTC') &
# datetime<as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'feb 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#incomplete data through feb 23 midday
buoy2009_L1 <- buoy2009_L1 %>%
mutate(PAR = case_when(datetime>=as.POSIXct('2009-02-01', tz='UTC') & datetime<as.POSIXct('2009-02-17', tz='UTC') ~ NA_real_,
TRUE ~ PAR))
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-03-01', tz='UTC') &
# datetime<as.POSIXct('2009-04-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'mar 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-04-01', tz='UTC') &
# datetime<as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'apr 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-05-01', tz='UTC') &
# datetime<as.POSIXct('2009-06-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'may 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-06-01', tz='UTC') &
# datetime<as.POSIXct('2009-07-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'jun 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-07-01', tz='UTC') &
# datetime<as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'jul 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-08-01', tz='UTC') &
# datetime<as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'aug 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-09-01', tz='UTC') &
# datetime<as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'sept 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-10-01', tz='UTC') &
# datetime<as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'oct 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-11-01', tz='UTC') &
# datetime<as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'nov 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-12-01', tz='UTC') &
# datetime<as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'dec 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
ggplot(buoy2009_L1, aes(x = datetime, y = PAR)) +
geom_point() +
final_theme +
labs(title = '2009 PAR data clean',
x = NULL,
y = 'PAR (umol/m2/s)') +
scale_x_datetime(date_minor_breaks = '1 month')
#### Air Temp ####
range(buoy2009_L1$AirTempC, na.rm = T)
ggplot(buoy2009_L1, aes(x=datetime, y = AirTempC)) +
geom_point() +
final_theme +
labs(title = '2009 air temp raw',
x= NULL,
y= 'air temp (deg C)') +
scale_x_datetime(date_minor_breaks = '1 month')
# data intermittent - recode Feb intermittent data
# ggplot(subset(buoy2009_L1,
# subset=(datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x=datetime, y = AirTempC)) +
# geom_point() +
# final_theme +
# labs(title = 'feb 2009 air temp raw',
# x= NULL,
# y= 'air temp (deg C)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#flag through jan 15 as intermittent
buoy2009_L1 <- buoy2009_L1 %>%
mutate(airtemp_flag = case_when(datetime < as.POSIXct('2009-01-15', tz='UTC') ~ 'i',
TRUE ~ NA_character_))
# ggplot(subset(buoy2009_L1,
# subset=(datetime>=as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x=datetime, y = AirTempC)) +
# geom_point() +
# final_theme +
# labs(title = 'feb 2009 air temp raw',
# x= NULL,
# y= 'air temp (deg C)') +
# scale_x_datetime(date_minor_breaks = '1 day')
buoy2009_L1 <- buoy2009_L1 %>%
mutate(AirTempC = case_when(datetime >= as.POSIXct('2009-02-06', tz='UTC') &
datetime < as.POSIXct('2009-02-17', tz='UTC') ~ NA_real_,
TRUE ~ AirTempC))
ggplot(buoy2009_L1, aes(x=datetime, y = AirTempC, color = airtemp_flag)) +
geom_point() +
final_theme +
labs(title = '2009 air temp clean',
x= NULL,
y= 'air temp (deg C)') +
scale_x_datetime(date_minor_breaks = '1 month')
#### EXPORT L1 FILES ####
#recode flags to '' when the buoy is offline
buoy2009_L1 <-buoy2009_L1 %>%
mutate_at(vars(temp_flag, upper_do_flag, wind_dir_flag, PAR_flag, airtemp_flag),
funs(case_when(location == 'offline' ~ NA_character_,
TRUE ~ .)))
#export L1 tempstring file
buoy2009_L1 %>%
select(datetime, location, TempC_0p5m:TempC_13p5m, temp_flag) %>%
mutate(datetime = as.character(datetime)) %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/tempstring/2009_tempstring_L1.csv')
# export L1 do file
buoy2009_L1 %>%
select(datetime, location, DOSat, DOppm, DOTempC, upper_do_flag) %>%
mutate(datetime = as.character(datetime)) %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/do/2009_do_L1.csv')
# export L1 wind data
buoy2009_L1 %>%
select(datetime, location, InstWindDir, InstWindSp, AveWindDir, AveWindSp, wind_dir_flag) %>%
mutate(datetime = as.character(datetime)) %>%
rename(WindSp_ms = 'InstWindSp',
WindDir_deg = 'InstWindDir',
AveWindSp_ms = 'AveWindSp',
AveWindDir_deg = 'AveWindDir') %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/met/2009_wind_L1.csv')
# export PAR data
buoy2009_L1 %>%
select(datetime, location, PAR, PAR_flag) %>%
mutate(datetime = as.character(datetime)) %>%
rename(PAR_umolm2s = 'PAR') %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/met/2009_PAR_L1.csv')
# export L1 air temp data
buoy2009_L1 %>%
select(datetime, location, AirTempC, airtemp_flag) %>%
mutate(datetime = as.character(datetime)) %>%
rename(AirTemp_degC = 'AirTempC') %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/met/2009_AirTemp_L1.csv')
| /data/buoy-data/Sunapee_buoy_2009.R | no_license | tadhg-moore/Sunapee-GLM | R | false | false | 65,726 | r | #*****************************************************************
#* Cary Institute of Ecosystem Studies (Millbrook, NY) *
#* *
#* TITLE: Sunapee_buoy_2009.r *
#* AUTHOR: Bethel Steele *
#* SYSTEM: Lenovo ThinkCentre, Win 10, R 3.5.2, RStudio 1.1.383 *
#* PROJECT: Lake Sunapee Buoy Data Cleaning *
#* PURPOSE: subset data for met/compare with L1 *
#* LAST MODIFIED: 05Sept2019 to create vertical dataset for *
#* master collation *
#*****************************************************************
source('library_func_lists.R')
#bring in 2009 buoy raw data
buoy2009_L0 <- read_csv('C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L0/Sunapee2009_rawData.csv',
col_names = c('datetime', 'AirTempC', 'DOppm', 'DOSat', 'DOSat2',
'PAR', 'DOTempC', 'TempC_0m', 'TempC_0p5m', 'TempC_1m',
'TempC_1p5m', 'TempC_2m', 'TempC_2p5m', 'TempC_3m', 'TempC_4m',
'TempC_5m', 'TempC_6m', 'TempC_7m', 'TempC_8m', 'TempC_9m',
'TempC_10m', 'TempC_11m', 'TempC_13m', 'AveWindDir', 'InstWindDir',
'InstWindSp', 'AveWindSp'),
col_types = 'cnnnnnnnnnnnnnnnnnnnnnnnnnn',
skip=1) %>%
select(-DOSat2) %>% #drop blank columns
mutate(datetime = as.POSIXct(datetime, format='%Y-%m-%d %H:%M:%S', tz='UTC'))
#create dummy timestamp so there are no blanks
alltimes_2009 <- as.data.frame(seq.POSIXt(as.POSIXct('2009-01-01 00:00', tz='UTC'), as.POSIXct('2009-12-31 23:50', tz='UTC'), '10 min')) %>%
rename("datetime" = !!names(.[1]))
buoy2009_L1 <- buoy2009_L0 %>%
right_join(., alltimes_2009) %>%
arrange(datetime)
#double check to make sure there are no DST issues
datelength2009 <- buoy2009_L1 %>%
mutate(date = format(datetime, '%Y-%m-%d')) %>%
group_by(date) %>%
summarize(length(datetime))
max(datelength2009$`length(datetime)`)
min(datelength2009$`length(datetime)`)
#should only be 144 or less if partial days included
#clean up workspace
rm(alltimes_2009, datelength2009)
#### thermistors ####
buoy2009_temp_vert <- buoy2009_L1 %>%
select(datetime, alltemp2007) %>%
gather(variable, value, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='2009 buoy temp raw',
# x=NULL,
# y='temp (deg C)') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89",
# "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(alltemp2007),
funs(case_when(. == -6999 ~ NA_real_,
. == -99.9 ~ NA_real_,
TRUE ~ .))) %>%
mutate(location = 'loon',
temp_flag = NA_character_)
buoy2009_temp_vert <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
ggplot(subset(buoy2009_temp_vert,
subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
datetime < as.POSIXct('2010-01-01', tz='UTC'))),
aes(x=datetime, y=value, color=(variable))) +
geom_point() +
final_theme +
labs(title='2009 buoy temp NAs recoded',
x=NULL,
y='temp (deg C)') +
scale_x_datetime(date_minor_breaks = '1 month') +
scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
"#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jan 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate(temp_flag = case_when(datetime < as.POSIXct('2009-01-15', tz='UTC') & is.na(temp_flag) ~ 'i,9.5d, 10.5d, 11.5d, 13.5d',
TRUE ~ temp_flag))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jan 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Feb 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# #data gap until jul
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-28', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# #look at beginning of record
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-28', tz='UTC') &
# datetime < as.POSIXct('2009-07-29', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-24', tz='UTC') &
# datetime < as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-01', tz='UTC') &
# datetime < as.POSIXct('2009-08-08', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-08', tz='UTC') &
# datetime < as.POSIXct('2009-08-15', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# #anomalous points Aug 11,13 and 24
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-11', tz='UTC') &
# datetime < as.POSIXct('2009-08-12', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-12', tz='UTC') &
# datetime < as.POSIXct('2009-08-13', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-13', tz='UTC') &
# datetime < as.POSIXct('2009-08-14', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-08-24', tz='UTC') &
# datetime < as.POSIXct('2009-08-25', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-08-31', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-01 12:00', tz='UTC') &
# datetime < as.POSIXct('2009-08-02 12:00', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-26', tz='UTC') &
# datetime < as.POSIXct('2009-08-27', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-08-31', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(TempC_0p5m:TempC_4m), #temp shifts
funs(case_when(is.na(TempC_5m) ~ NA_real_,
TRUE ~ .))) %>%
mutate_at(vars(TempC_6m:TempC_13m),
funs(case_when(TempC_13m > TempC_11m & datetime >= as.POSIXct('2009-07-28', tz='UTC') & datetime < as.POSIXct('2009-10-02 12:00', tz='UTC')~ NA_real_, # temp shifts
TempC_13m > TempC_6m & datetime >= as.POSIXct('2009-07-28', tz='UTC') & datetime < as.POSIXct('2009-10-02 12:00', tz='UTC')~ NA_real_, # temp shifts
TRUE ~ .))) %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime >= as.POSIXct('2009-02-01', tz='UTC') & datetime < as.POSIXct('2009-07-28', tz='UTC') ~ NA_real_,
TempC_8m < 7.5 & datetime > as.POSIXct('2009-08-01', tz='UTC') & datetime < as.POSIXct('2009-09-01', tz='UTC') ~ NA_real_, #temp shifts
TRUE ~ .))) %>%
mutate_at(vars(TempC_8m:TempC_11m),
funs(case_when(is.na(TempC_13m)~ NA_real_, #temp shifts
TRUE ~ .))) %>%
mutate(TempC_13m = case_when(is.na(TempC_1m) ~ NA_real_, #temp shifts
TRUE ~ TempC_13m)) %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime == as.POSIXct('2009-08-31 11:40', tz='UTC') ~ NA_real_,
TRUE ~ .)))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-07-28', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Jul/Aug 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-09-01', tz='UTC') &
# datetime < as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Sept 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-10-01', tz='UTC') &
# datetime < as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Oct 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-11-01', tz='UTC') &
# datetime < as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Nov 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# #Nov 16
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-11-16', tz='UTC') &
# datetime < as.POSIXct('2009-11-17', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Nov 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime == as.POSIXct('2009-11-16 6:50', tz='UTC') ~ NA_real_,
TRUE ~ .)))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-11-01', tz='UTC') &
# datetime < as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Nov 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-12-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# # #Dec 8, 12, 17, 23/24
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-12-08', tz='UTC') &
# datetime < as.POSIXct('2009-12-09', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-12', tz='UTC') &
# datetime < as.POSIXct('2009-12-13', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert,
# subset=(datetime >=as.POSIXct('2009-12-17', tz='UTC') &
# datetime < as.POSIXct('2009-12-18', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-21', tz='UTC') &
# datetime < as.POSIXct('2009-12-22', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-22', tz='UTC') &
# datetime < as.POSIXct('2009-12-23', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-23', tz='UTC') &
# datetime < as.POSIXct('2009-12-24', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-24', tz='UTC') &
# datetime < as.POSIXct('2009-12-25', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-29', tz='UTC') &
# datetime < as.POSIXct('2009-12-30', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, NAs recoded',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 hour') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(alltemp2007),
funs(case_when(datetime == as.POSIXct('2009-12-08 23:20', tz='UTC') ~ NA_real_, #anamolous shift
datetime >= as.POSIXct('2009-12-12 4:50', tz='UTC') & datetime < as.POSIXct('2009-12-12 9:00', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-17 4:00', tz='UTC') & datetime < as.POSIXct('2009-12-17 5:20', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-17 12:20', tz='UTC') & datetime < as.POSIXct('2009-12-17 15:00', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-21 19:30', tz='UTC') & datetime < as.POSIXct('2009-12-22 6:10', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-22 19:00', tz='UTC') & datetime < as.POSIXct('2009-12-22 22:00', tz='UTC') ~ NA_real_, #flatline
datetime >= as.POSIXct('2009-12-29 9:50', tz='UTC') & datetime < as.POSIXct('2009-12-29 11:20', tz='UTC') ~ NA_real_, #flatline
is.na(TempC_1p5m) ~ NA_real_, #anamolous shift
TRUE ~ .)))
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007) %>%
gather(variable, value, -location, -datetime) %>%
mutate(variable = factor(variable, levels=alltemp2007))
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-12-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='Dec 2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 day') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#
# ggplot(subset(buoy2009_temp_vert_b,
# subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x=datetime, y=value, color=(variable))) +
# geom_point() +
# final_theme +
# labs(title='2009, clean',
# x=NULL,
# y='temp deg C') +
# scale_x_datetime(date_minor_breaks = '1 month') +
# scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
# "#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
buoy2009_L1 <- buoy2009_L1 %>%
mutate(temp_flag = case_when(!is.na(temp_flag) & datetime>=as.POSIXct('2009-12-12', tz='UTC') ~ paste(temp_flag, 'i', sep = ', '),
is.na(temp_flag) & datetime>=as.POSIXct('2009-12-12', tz='UTC') ~ 'i',
TRUE ~ temp_flag))
#add flag for 11.5 and 13.5 as possibly in sediment
buoy2009_L1 <- buoy2009_L1 %>%
mutate(temp_flag = case_when(is.na(temp_flag) ~ '11.5b, 13.5b',
!is.na(temp_flag) ~ paste(temp_flag, '11.5b, 13.5b', sep = ', '),
TRUE ~ temp_flag))
unique(buoy2009_L1$temp_flag)
buoy2009_temp_vert_b <- buoy2009_L1 %>%
select(datetime, location, alltemp2007, temp_flag) %>%
gather(variable, value, -location, -datetime, -temp_flag) %>%
mutate(variable = factor(variable, levels=alltemp2007))
ggplot(subset(buoy2009_temp_vert_b,
subset=(datetime >=as.POSIXct('2009-01-01', tz='UTC') &
datetime < as.POSIXct('2010-01-01', tz='UTC'))),
aes(x=datetime, y=value, color=(variable), shape = temp_flag)) +
geom_point() +
final_theme +
labs(title='2009, clean',
x=NULL,
y='temp deg C') +
scale_x_datetime(date_minor_breaks = '1 month') +
scale_color_manual(values=c("#000000", "#999999", "#997300", "#ffbf00", "#173fb5", "#587CE9", "#a5b8f3", "#004d13",
"#00e639", "#66ff8c", "#00664b", "#009E73", "#00e6a8", "#8d840c", "#d4c711", "#f5ee89", "#005180", "#0081cc", "#66c7ff")) #so you can adjust
#add in offline location
buoy2009_L1 <- buoy2009_L1 %>%
mutate(location = case_when(datetime < as.POSIXct('2009-01-01 7:50', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-01-14 18:00', tz='UTC') &
datetime < as.POSIXct('2009-02-06 11:10', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-02-06 12:00', tz='UTC') &
datetime < as.POSIXct('2009-02-18 0:10', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-02-19 12:50', tz='UTC') &
datetime < as.POSIXct('2009-02-23 13:00', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-04-15 3:00', tz='UTC') &
datetime < as.POSIXct('2009-07-28 13:30', tz='UTC') ~ 'offline',
datetime >= as.POSIXct('2009-12-31 0:10',tz='UTC') ~ 'offline',
TRUE ~ location)) %>%
mutate(temp_flag = case_when(location == 'offline' ~ NA_character_,
TRUE~temp_flag))
#clean up workspace
rm(buoy2009_temp_vert, buoy2009_temp_vert_b)
#correct thermistor depth for offset
buoy2009_L1 <- buoy2009_L1 %>%
rename(TempC_13p5m = TempC_13m,
TempC_11p5m = TempC_11m,
TempC_10p5m = TempC_10m,
TempC_9p5m = TempC_9m,
TempC_8p5m = TempC_8m,
TempC_7p5m = TempC_7m,
TempC_6p5m = TempC_6m,
TempC_5p5m = TempC_5m,
TempC_4p5m = TempC_4m,
TempC_3p5m = TempC_3m,
TempC_3m = TempC_2p5m,
TempC_2p5m = TempC_2m,
TempC_2m = TempC_1p5m,
TempC_1p5m = TempC_1m,
TempC_1m = TempC_0p5m,
TempC_0p5m = TempC_0m)
#### DO sensors ####
range(buoy2009_L1$DOSat, na.rm=T)
range(buoy2009_L1$DOppm, na.rm=T)
range(buoy2009_L1$DOTempC, na.rm=T)
do_vert <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime)
# ggplot(do_vert, aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = '2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 month')
buoy2009_L1 <- buoy2009_L1 %>%
mutate(DOTempC = case_when(DOTempC == -6999 ~ NA_real_,
TRUE ~ DOTempC))
do_vert <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC, location) %>%
gather(variable, value, -datetime, -location)
ggplot(do_vert, aes(x = datetime, y = value, color = location)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 DO data NA values recoded',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jan 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#start seeing intermittent readings dec 29 - adding flag of intermittent do data from then throught the end of the month
buoy2009_L1 <- buoy2009_L1 %>%
mutate(upper_do_flag = case_when(datetime < as.POSIXct('2009-01-15', tz='UTC') ~ 'i',
TRUE ~ NA_character_))
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#data before feb 23 recoded to NA
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(DOSat, DOppm, DOTempC),
funs(case_when(datetime >= as.POSIXct('2009-02-01', tz='UTC') &
datetime < as.POSIXct('2009-02-23', tz='UTC') ~ NA_real_,
TRUE ~ .)))
do_vert_b <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime)
# ggplot(subset(do_vert_b,
# subset = (datetime >= as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 DO data clean',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-03-01', tz='UTC') &
# datetime < as.POSIXct('2009-04-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'mar 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-04-01', tz='UTC') &
# datetime < as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# #errant readings beginning apr 5
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-04-05', tz='UTC') &
# datetime < as.POSIXct('2009-04-06', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(DOSat, DOppm, DOTempC),
funs(case_when(datetime >= as.POSIXct('2009-04-05 1:40', tz='UTC') &
datetime < as.POSIXct('2009-04-16', tz='UTC') ~ NA_real_,
TRUE ~ .)))
do_vert_b <- buoy2009_L1 %>%
select(datetime, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime)
# ggplot(subset(do_vert_b,
# subset = (datetime >= as.POSIXct('2009-04-01', tz='UTC') &
# datetime < as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 DO data clean',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-05-01', tz='UTC') &
# datetime < as.POSIXct('2009-06-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'may 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-06-01', tz='UTC') &
# datetime < as.POSIXct('2009-07-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jun 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-07-01', tz='UTC') &
# datetime < as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jul 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-08-01', tz='UTC') &
# datetime < as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'aug 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-09-01', tz='UTC') &
# datetime < as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-10-01', tz='UTC') &
# datetime < as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'oct 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-11-01', tz='UTC') &
# datetime < as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'nov 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(do_vert,
# subset = (datetime >= as.POSIXct('2009-12-01', tz='UTC') &
# datetime < as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'dec 2009 DO data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
do_vert_b <- buoy2009_L1 %>%
select(datetime, location, DOSat, DOppm, DOTempC) %>%
gather(variable, value, -datetime, -location)
# ggplot(do_vert_b,
# aes(x = datetime, y = value, color = location)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = '2009 DO data clean',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 month')
# add presumed cleaning flags and possible non-calibration flags
buoy2009_L1 <- buoy2009_L1 %>%
mutate(upper_do_flag = case_when(datetime == as.POSIXct('2009-07-28 13:30', tz='UTC') ~ 'wp',
TRUE ~ upper_do_flag)) %>%
mutate(upper_do_flag = case_when(!is.na(upper_do_flag) ~ paste('x', upper_do_flag, sep = ', '),
TRUE ~ 'x')) %>%
mutate(upper_do_flag = case_when(location == 'offline' ~ NA_character_,
TRUE ~ upper_do_flag))
do_vert_b <- buoy2009_L1 %>%
select(datetime, location, DOSat, DOppm, DOTempC, upper_do_flag) %>%
gather(variable, value, -datetime, -location, - upper_do_flag)
ggplot(do_vert_b,
aes(x = datetime, y = value, shape = location, color = upper_do_flag)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 DO data clean',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
rm(do_vert, do_vert_b)
#### wind sensors ####
range(buoy2009_L1$InstWindDir, na.rm = T)
range(buoy2009_L1$InstWindSp, na.rm = T)
range(buoy2009_L1$AveWindDir, na.rm = T)
range(buoy2009_L1$AveWindSp, na.rm = T)
wind_vert <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp) %>%
gather(variable, value, -datetime)
# ggplot(wind_vert, aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = '2009 wind data raw',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 month')
buoy2009_L1 <- buoy2009_L1 %>%
mutate(InstWindDir = case_when(InstWindDir==-6999 ~ NA_real_,
TRUE ~ InstWindDir))
wind_vert <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp) %>%
gather(variable, value, -datetime)
ggplot(wind_vert, aes(x = datetime, y = value)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 wind data NAs recoded',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime<as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jan 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-02-01', tz='UTC') &
# datetime<as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(InstWindSp, InstWindDir),
funs(case_when(datetime<as.POSIXct('2009-02-18 0:10', tz='UTC') ~ NA_real_,
TRUE ~ .)))
wind_vert_b <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp) %>%
gather(variable, value, -datetime)
# ggplot(subset(wind_vert_b,
# subset=(datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime<as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'feb 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-03-01', tz='UTC') &
# datetime<as.POSIXct('2009-04-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'mar 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-04-01', tz='UTC') &
# datetime<as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'apr 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-05-01', tz='UTC') &
# datetime<as.POSIXct('2009-06-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'may 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-06-01', tz='UTC') &
# datetime<as.POSIXct('2009-07-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'jun 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-07-01', tz='UTC') &
# datetime<as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'july 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-08-01', tz='UTC') &
# datetime<as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'aug 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-09-01', tz='UTC') &
# datetime<as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-10-01', tz='UTC') &
# datetime<as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'oct 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-11-01', tz='UTC') &
# datetime<as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'nov 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
# # look at nov 27-28
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-11-27 12:00', tz='UTC') &
# datetime<as.POSIXct('2009-11-28 18:00', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
# odd to have so many 0 readings, but not a sensor frozen issue, leaving in
#
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-12-01', tz='UTC') &
# datetime<as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# #dec 26 sensor frozen
# ggplot(subset(wind_vert,
# subset=(datetime>=as.POSIXct('2009-12-26', tz='UTC') &
# datetime<as.POSIXct('2009-12-27', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
# #dec 26 sensor frozen
# ggplot(subset(wind_vert_b,
# subset=(datetime>=as.POSIXct('2009-12-26 12:00', tz='UTC') &
# datetime<as.POSIXct('2009-12-27 12:00', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 hour')
buoy2009_L1 <- buoy2009_L1 %>%
mutate_at(vars(InstWindSp, InstWindDir, AveWindSp, AveWindDir),
funs(case_when(datetime>=as.POSIXct('2009-12-26 19:40', tz='UTC') &
datetime<as.POSIXct('2009-12-26 21:50', tz='UTC') ~ NA_real_,
TRUE ~ .)))
wind_vert_b <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp, location) %>%
gather(variable, value, -datetime, -location)
# ggplot(subset(wind_vert_b,
# subset=(datetime>=as.POSIXct('2009-12-01', tz='UTC') &
# datetime<as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = value)) +
# geom_point() +
# facet_grid(variable~., scales = 'free_y') +
# final_theme +
# labs(title = 'sept 2009 wind data NAs recoded',
# x = NULL,
# y = NULL) +
# scale_x_datetime(date_minor_breaks = '1 day')
# add flag to wind direction prior to jul 28 when buoy online
buoy2009_L1 <- buoy2009_L1 %>%
mutate(wind_dir_flag = case_when(datetime < as.POSIXct('2009-07-28', tz='UTC') & !is.na(InstWindDir) ~ 'e',
TRUE ~ NA_character_))
wind_vert_b <- buoy2009_L1 %>%
select(datetime, InstWindDir, AveWindDir,InstWindSp, AveWindSp, location, wind_dir_flag) %>%
gather(variable, value, -datetime, -location, -wind_dir_flag)
ggplot(wind_vert_b,
aes(x = datetime, y = value, color = wind_dir_flag)) +
geom_point() +
facet_grid(variable~., scales = 'free_y') +
final_theme +
labs(title = '2009 wind data clean',
x = NULL,
y = NULL) +
scale_x_datetime(date_minor_breaks = '1 month')
rm(wind_vert, wind_vert_b)
#### PAR ####
range(buoy2009_L1$PAR, na.rm = T)
# ggplot(buoy2009_L1, aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme
buoy2009_L1 <- buoy2009_L1 %>%
mutate(PAR_flag = case_when(PAR <0 ~ 'z',
TRUE ~ NA_character_),
PAR = case_when(PAR <0 ~ 0,
TRUE ~ PAR))
ggplot(buoy2009_L1, aes(x = datetime, y = PAR)) +
geom_point() +
final_theme +
labs(title = '2009 PAR data below 0 recoded',
x = NULL,
y = 'PAR (umol/m2/s)') +
scale_x_datetime(date_minor_breaks = '1 month')
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime<as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'jan 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#jan data incomplete. flagging as intermittent
buoy2009_L1 <- buoy2009_L1 %>%
mutate(PAR_flag = case_when(datetime<as.POSIXct('2009-01-15', tz='UTC') & is.na(PAR_flag) ~ 'i',
datetime<as.POSIXct('2009-01-15', tz='UTC') & !is.na(PAR_flag) ~ paste('i', PAR_flag, sep = ', '),
TRUE ~ PAR_flag))
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-02-01', tz='UTC') &
# datetime<as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'feb 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#incomplete data through feb 23 midday
buoy2009_L1 <- buoy2009_L1 %>%
mutate(PAR = case_when(datetime>=as.POSIXct('2009-02-01', tz='UTC') & datetime<as.POSIXct('2009-02-17', tz='UTC') ~ NA_real_,
TRUE ~ PAR))
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-03-01', tz='UTC') &
# datetime<as.POSIXct('2009-04-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'mar 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-04-01', tz='UTC') &
# datetime<as.POSIXct('2009-05-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'apr 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-05-01', tz='UTC') &
# datetime<as.POSIXct('2009-06-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'may 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-06-01', tz='UTC') &
# datetime<as.POSIXct('2009-07-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'jun 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-07-01', tz='UTC') &
# datetime<as.POSIXct('2009-08-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'jul 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-08-01', tz='UTC') &
# datetime<as.POSIXct('2009-09-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'aug 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-09-01', tz='UTC') &
# datetime<as.POSIXct('2009-10-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'sept 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-10-01', tz='UTC') &
# datetime<as.POSIXct('2009-11-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'oct 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-11-01', tz='UTC') &
# datetime<as.POSIXct('2009-12-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'nov 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#
# ggplot(subset(buoy2009_L1,
# subset = (datetime>=as.POSIXct('2009-12-01', tz='UTC') &
# datetime<as.POSIXct('2010-01-01', tz='UTC'))),
# aes(x = datetime, y = PAR)) +
# geom_point() +
# final_theme +
# labs(title = 'dec 2009 PAR data raw',
# x = NULL,
# y = 'PAR (umol/m2/s)') +
# scale_x_datetime(date_minor_breaks = '1 day')
ggplot(buoy2009_L1, aes(x = datetime, y = PAR)) +
geom_point() +
final_theme +
labs(title = '2009 PAR data clean',
x = NULL,
y = 'PAR (umol/m2/s)') +
scale_x_datetime(date_minor_breaks = '1 month')
#### Air Temp ####
range(buoy2009_L1$AirTempC, na.rm = T)
ggplot(buoy2009_L1, aes(x=datetime, y = AirTempC)) +
geom_point() +
final_theme +
labs(title = '2009 air temp raw',
x= NULL,
y= 'air temp (deg C)') +
scale_x_datetime(date_minor_breaks = '1 month')
# data intermittent - recode Feb intermittent data
# ggplot(subset(buoy2009_L1,
# subset=(datetime>=as.POSIXct('2009-01-01', tz='UTC') &
# datetime < as.POSIXct('2009-02-01', tz='UTC'))),
# aes(x=datetime, y = AirTempC)) +
# geom_point() +
# final_theme +
# labs(title = 'feb 2009 air temp raw',
# x= NULL,
# y= 'air temp (deg C)') +
# scale_x_datetime(date_minor_breaks = '1 day')
#flag through jan 15 as intermittent
buoy2009_L1 <- buoy2009_L1 %>%
mutate(airtemp_flag = case_when(datetime < as.POSIXct('2009-01-15', tz='UTC') ~ 'i',
TRUE ~ NA_character_))
# ggplot(subset(buoy2009_L1,
# subset=(datetime>=as.POSIXct('2009-02-01', tz='UTC') &
# datetime < as.POSIXct('2009-03-01', tz='UTC'))),
# aes(x=datetime, y = AirTempC)) +
# geom_point() +
# final_theme +
# labs(title = 'feb 2009 air temp raw',
# x= NULL,
# y= 'air temp (deg C)') +
# scale_x_datetime(date_minor_breaks = '1 day')
buoy2009_L1 <- buoy2009_L1 %>%
mutate(AirTempC = case_when(datetime >= as.POSIXct('2009-02-06', tz='UTC') &
datetime < as.POSIXct('2009-02-17', tz='UTC') ~ NA_real_,
TRUE ~ AirTempC))
ggplot(buoy2009_L1, aes(x=datetime, y = AirTempC, color = airtemp_flag)) +
geom_point() +
final_theme +
labs(title = '2009 air temp clean',
x= NULL,
y= 'air temp (deg C)') +
scale_x_datetime(date_minor_breaks = '1 month')
#### EXPORT L1 FILES ####
#recode flags to '' when the buoy is offline
buoy2009_L1 <-buoy2009_L1 %>%
mutate_at(vars(temp_flag, upper_do_flag, wind_dir_flag, PAR_flag, airtemp_flag),
funs(case_when(location == 'offline' ~ NA_character_,
TRUE ~ .)))
#export L1 tempstring file
buoy2009_L1 %>%
select(datetime, location, TempC_0p5m:TempC_13p5m, temp_flag) %>%
mutate(datetime = as.character(datetime)) %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/tempstring/2009_tempstring_L1.csv')
# export L1 do file
buoy2009_L1 %>%
select(datetime, location, DOSat, DOppm, DOTempC, upper_do_flag) %>%
mutate(datetime = as.character(datetime)) %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/do/2009_do_L1.csv')
# export L1 wind data
buoy2009_L1 %>%
select(datetime, location, InstWindDir, InstWindSp, AveWindDir, AveWindSp, wind_dir_flag) %>%
mutate(datetime = as.character(datetime)) %>%
rename(WindSp_ms = 'InstWindSp',
WindDir_deg = 'InstWindDir',
AveWindSp_ms = 'AveWindSp',
AveWindDir_deg = 'AveWindDir') %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/met/2009_wind_L1.csv')
# export PAR data
buoy2009_L1 %>%
select(datetime, location, PAR, PAR_flag) %>%
mutate(datetime = as.character(datetime)) %>%
rename(PAR_umolm2s = 'PAR') %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/met/2009_PAR_L1.csv')
# export L1 air temp data
buoy2009_L1 %>%
select(datetime, location, AirTempC, airtemp_flag) %>%
mutate(datetime = as.character(datetime)) %>%
rename(AirTemp_degC = 'AirTempC') %>%
write_csv(., 'C:/Users/steeleb/Dropbox/Lake Sunapee/monitoring/buoy data/data/all sensors/L1/met/2009_AirTemp_L1.csv')
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mason.R
\name{mason}
\alias{mason}
\title{Run a generator}
\usage{
mason(generator = NULL)
}
\arguments{
\item{generator}{The name of the generator to run. This is the initial
part of the package name that defines the generator.}
}
\description{
If no generator is given, then you can choose one interactively.
It will generate the application in the current working directory,
and it expects it to be empty.
}
| /man/mason.Rd | permissive | dulmaj12id/mason | R | false | true | 490 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mason.R
\name{mason}
\alias{mason}
\title{Run a generator}
\usage{
mason(generator = NULL)
}
\arguments{
\item{generator}{The name of the generator to run. This is the initial
part of the package name that defines the generator.}
}
\description{
If no generator is given, then you can choose one interactively.
It will generate the application in the current working directory,
and it expects it to be empty.
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{accidents}
\alias{accidents}
\title{Shunter accidents}
\format{A dataframe with 122 rows and 2 variables:
\describe{
\item{x}{Number of shunter accidents between 1937 and 1942}
\item{y}{Number of shunter accidents between 1943 and 1947}
}}
\source{
A. Arbous, J.E. Kerrick, Accident statistics and the concept of accident proneness, Biometrics 7 (1951) 340-432.
}
\usage{
accidents
}
\description{
The number of accidents incurred by 122 shunters in two consecutive year periods, namely 1937 - 1942 and 1943 - 1947
}
\keyword{datasets}
| /man/accidents.Rd | no_license | diagdavenport/multicmp | R | false | true | 644 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{accidents}
\alias{accidents}
\title{Shunter accidents}
\format{A dataframe with 122 rows and 2 variables:
\describe{
\item{x}{Number of shunter accidents between 1937 and 1942}
\item{y}{Number of shunter accidents between 1943 and 1947}
}}
\source{
A. Arbous, J.E. Kerrick, Accident statistics and the concept of accident proneness, Biometrics 7 (1951) 340-432.
}
\usage{
accidents
}
\description{
The number of accidents incurred by 122 shunters in two consecutive year periods, namely 1937 - 1942 and 1943 - 1947
}
\keyword{datasets}
|
LoadPackages <- function(){
library(rmsfuns)
corepacks <- c("tidyverse","tidyselect", "RcppRoll", "ggplot2", "lubridate",
"ggthemes", "purrr", "tbl2xts", "xts", "MTS", "devtools", "rugarch", "forecast", "PerformanceAnalytics", "xtable","readxl","ggthemes","ggsci","gridExtra")
load_pkg(corepacks)
}
| /code/LoadPackages.R | no_license | git-cgl/Financial-metrics | R | false | false | 346 | r | LoadPackages <- function(){
library(rmsfuns)
corepacks <- c("tidyverse","tidyselect", "RcppRoll", "ggplot2", "lubridate",
"ggthemes", "purrr", "tbl2xts", "xts", "MTS", "devtools", "rugarch", "forecast", "PerformanceAnalytics", "xtable","readxl","ggthemes","ggsci","gridExtra")
load_pkg(corepacks)
}
|
library(wux)
### Name: userinput_CMIP5_timeseries
### Title: Example userinput for models2wux
### Aliases: userinput_CMIP5_timeseries
### Keywords: datasets
### ** Examples
## thats what userinput_CMIP5_timeseries looks like:
## it contains a single list named user.input
## describing 2 CMIP5 models in the alpine region
data("userinput_CMIP5_timeseries")
is.list(userinput_CMIP5_timeseries)
str(userinput_CMIP5_timeseries)
data(modelinput_test)
## reading in these data and process them:
## Not run:
##D wux.test <- models2wux(userinput_CMIP5_timeseries,
##D modelinput = model.input)
## End(Not run)
## if you had a file "/tmp/userinput_CMIP5_timeseries.R" which contains a
## list 'user.input with the same content as 'userinput_CMIP5_timeseries'
## you could read the data also like this:
## Not run:
##D wux.test <- models2wux("/tmp/userinput_CMIP5_timeseries.R",
##D modelinput = model.input)
## End(Not run)
## the result is what the data.set would look like, if you ran the code
## above:
data(CMIP5_example_timeseries)
wux.test <- CMIP5_example_timeseries
## Not run:
##D require(lattice)
##D xyplot(air_temperature ~ year|season,
##D groups=acronym,
##D data = wux.test,
##D type = c("l", "g"),
##D main = "Temperature trends for Alpine Region" )
## End(Not run)
| /data/genthat_extracted_code/wux/examples/userinput_CMIP5_timeseries.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 1,372 | r | library(wux)
### Name: userinput_CMIP5_timeseries
### Title: Example userinput for models2wux
### Aliases: userinput_CMIP5_timeseries
### Keywords: datasets
### ** Examples
## thats what userinput_CMIP5_timeseries looks like:
## it contains a single list named user.input
## describing 2 CMIP5 models in the alpine region
data("userinput_CMIP5_timeseries")
is.list(userinput_CMIP5_timeseries)
str(userinput_CMIP5_timeseries)
data(modelinput_test)
## reading in these data and process them:
## Not run:
##D wux.test <- models2wux(userinput_CMIP5_timeseries,
##D modelinput = model.input)
## End(Not run)
## if you had a file "/tmp/userinput_CMIP5_timeseries.R" which contains a
## list 'user.input with the same content as 'userinput_CMIP5_timeseries'
## you could read the data also like this:
## Not run:
##D wux.test <- models2wux("/tmp/userinput_CMIP5_timeseries.R",
##D modelinput = model.input)
## End(Not run)
## the result is what the data.set would look like, if you ran the code
## above:
data(CMIP5_example_timeseries)
wux.test <- CMIP5_example_timeseries
## Not run:
##D require(lattice)
##D xyplot(air_temperature ~ year|season,
##D groups=acronym,
##D data = wux.test,
##D type = c("l", "g"),
##D main = "Temperature trends for Alpine Region" )
## End(Not run)
|
setwd('~/Documents/2nd semester/hands on bayesian data analysis/')
set.seed('100')
require(caret)
require(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
train.index <- createDataPartition(iris$Species, p = 0.8, list = F, times = 1)
train.data <- iris[train.index,]
test.data <- iris[-train.index,]
ndata = nrow(train.data)
X.train <- as.matrix(cbind(rep(1, ndata), train.data[,-c(1,5)]))
Y.train <- train.data$Sepal.Length
G.train <- as.integer(train.data$Species)
ndata_test = nrow(test.data)
X.test <- as.matrix(cbind(rep(1, ndata_test), test.data[,-c(1,5)]))
G.test <- as.integer(test.data$Species)
npar = ncol(X.train)
data.stan <- list(X = X.train, Y = Y.train,
ndata = ndata,G = G.train,
X_test = X.test,G_test = G.test, ndata_test = ndata_test,
npar = npar, gcount = 3)
linear.model <- stan(file = './rstan/iris.stan', data = data.stan)
| /bayesian_model.R | no_license | bhattarai842/iris-bayesian-model | R | false | false | 962 | r | setwd('~/Documents/2nd semester/hands on bayesian data analysis/')
set.seed('100')
require(caret)
require(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
train.index <- createDataPartition(iris$Species, p = 0.8, list = F, times = 1)
train.data <- iris[train.index,]
test.data <- iris[-train.index,]
ndata = nrow(train.data)
X.train <- as.matrix(cbind(rep(1, ndata), train.data[,-c(1,5)]))
Y.train <- train.data$Sepal.Length
G.train <- as.integer(train.data$Species)
ndata_test = nrow(test.data)
X.test <- as.matrix(cbind(rep(1, ndata_test), test.data[,-c(1,5)]))
G.test <- as.integer(test.data$Species)
npar = ncol(X.train)
data.stan <- list(X = X.train, Y = Y.train,
ndata = ndata,G = G.train,
X_test = X.test,G_test = G.test, ndata_test = ndata_test,
npar = npar, gcount = 3)
linear.model <- stan(file = './rstan/iris.stan', data = data.stan)
|
setwd("G:/vitek_sdgmm_preprint")
library(Cardinal)
library(stringr)
################################################################################
# functions #
################################################################################
# load in .imzML file and "Spot List" text file exported from Bruker flexImaging
load_datasets <- function(vector_of_datasets) {
listo <- list()
count <- 1
for (i in vector_of_datasets) {
imzml <- readMSIData(paste0(i, ".imzML"), mass.range=c(1,2000),
resolution=0.2, units="mz")
spots <- as.data.frame(read.table(paste0(i, ".txt"), sep=" ",
col.names=c("x", "y", "spot", "region")))
listo[[count]] <- list(imzml, spots)
count <- count + 1
}
return(listo)
}
# correct x and y coordinates based on "Spot List" text file
# update run names and add column for "condition" in object metadata
# level_list param == list of vectors containing region name and condition
process_metadata <- function(dataset, spot_table, level_list) {
spot_table$x <- as.integer(str_split(str_split(spot_table$spot, "X",
simplify=TRUE)[,2], "Y",
simplify=TRUE)[,1])
spot_table$y <- as.integer(str_split(spot_table$spot, "Y", simplify=TRUE)[,2])
for (i in level_list) {
tmp_table <- spot_table[which(spot_table$region==i[1]),]
tmp_table$condition <- factor(i[2])
if (exists("new_spot_table")) {
new_spot_table <- rbind(new_spot_table, tmp_table)
} else {
new_spot_table <- tmp_table
}
}
new_spot_table$region <- as.factor(new_spot_table$region)
new_spot_table$run <- paste(run(dataset)[1], new_spot_table$region, sep="_")
pd_tmp <- merge(new_spot_table, coord(pixelData(dataset)), by=c("x", "y"))
pixelData(dataset) <- PositionDataFrame(coord=pd_tmp[,1:2], run=pd_tmp$run,
region=pd_tmp$region,
condition=pd_tmp$condition)
return(dataset)
}
# preprocess dataset using the following settings
# note: both "tic" and "rms" normalization were attempted
preprocess_datasets <- function(dataset) {
preprocessed <- normalize(dataset, method="tic")
preprocessed <- smoothSignal(preprocessed, method="sgolay")
preprocessed <- reduceBaseline(preprocessed, method="median")
preprocessed <- process(preprocessed)
peaks <- peakPick(preprocessed, method="simple")
peaks <- peakAlign(peaks, tolerance=0.2, units="mz")
peaks <- peakFilter(peaks, freq.min=0.05)
peaks <- process(peaks)
bin <- peakBin(preprocessed, ref=mz(peaks), type="height")
processed <- process(bin)
return(processed)
}
################################################################################
# main() #
################################################################################
# load dataset
dataset_files <- c("G:/vitek_sdgmm_preprint/PA14_TLCA_2 DAYS_2016-06-09")
datasets <- load_datasets(dataset_files)
datasets[[1]][[3]] <- list(c("PA14", "meoh"),
c("PA14_250uM_TLCA", "tlca"),
c("No_TLCA_Control", "meoh"),
c("250uM_TLCA_Control", "tlca"))
# edit metadata
pseudo_1 <- process_metadata(datasets[[1]][[1]], datasets[[1]][[2]],
datasets[[1]][[3]])
# preprocess data
pseudo_1_proc <- preprocess_datasets(pseudo_1)
# run sdgmm
# note: k=4 and k=5 attempts required significant amounts of time and RAM
pseudo_1_sdgmm <- spatialDGMM(pseudo_1_proc, r=1, k=3, method="adaptive",
init="kmeans", iter.max=1000, tol=1e-11)
summary(pseudo_1_sdgmm)
# run segmentation test
pseudo_1_segtest <- segmentationTest(pseudo_1_sdgmm, ~ condition,
classControl="Ymax")
summary(pseudo_1_segtest)
topFeatures(pseudo_1_segtest, p.adjust="fdr", AdjP<0.05, n=1000)
# save segmentation test top features to dataframe and convert to vector
pseudo_1_segtest_features <- as.data.frame(topFeatures(pseudo_1_segtest,
p.adjust="fdr", AdjP<0.05, n=1000))
pseudo_1_features_vec <- as.vector(pseudo_1_segtest_features$feature)
# view ion images for all top features IDed by segmentation test
image(pseudo_1_segtest, model=list(feature=pseudo_1_features_vec),
values="mapping", layout=c(ceiling(length(pseudo_1_features_vec)/4), 4))
# view ion images from processed dataset for all top features IDed by
# segmentation test
pseudo_1_mz_vec <- as.vector(pseudo_1_segtest_features$mz)
image(pseudo_1_proc, mz=pseudo_1_mz_vec,
layout=c(ceiling(length(pseudo_1_mz_vec)/4), 4),
contrast.enhance="histogram", smooth.image="gaussian")
################################################################################
# main2() #
################################################################################
# subset for region: Pseudomonas aeruginosa w/ TLCA media supplementation
pseudo_1_roi <- pseudo_1_proc[,pixels(pseudo_1_proc,
run=="PA14_TLCA_2 DAYS_2016-06-09_PA14_250uM_TLCA")]
# run sdgmm
pseudo_1_roi_sdgmm <- spatialDGMM(pseudo_1_roi, r=1, k=2, method="adaptive",
init="kmeans", iter.max=1000,tol=1e-11)
summary(pseudo_1_roi_sdgmm)
# visualize various features
image(pseudo_1_roi_sdgmm, model=list(feature=c(302,303,304,320,321,322)),
contrast.enhance="histogram", smooth.image="gaussian")
image(pseudo_1_roi_sdgmm, contrast.enhance="histogram",
smooth.image="gaussian", layout=c(165,3))
| /pseudo/pseudomonas_sdgmm_v3.R | no_license | gtluu/vitek_sdgmm_preprint | R | false | false | 5,910 | r | setwd("G:/vitek_sdgmm_preprint")
library(Cardinal)
library(stringr)
################################################################################
# functions #
################################################################################
# load in .imzML file and "Spot List" text file exported from Bruker flexImaging
load_datasets <- function(vector_of_datasets) {
listo <- list()
count <- 1
for (i in vector_of_datasets) {
imzml <- readMSIData(paste0(i, ".imzML"), mass.range=c(1,2000),
resolution=0.2, units="mz")
spots <- as.data.frame(read.table(paste0(i, ".txt"), sep=" ",
col.names=c("x", "y", "spot", "region")))
listo[[count]] <- list(imzml, spots)
count <- count + 1
}
return(listo)
}
# correct x and y coordinates based on "Spot List" text file
# update run names and add column for "condition" in object metadata
# level_list param == list of vectors containing region name and condition
process_metadata <- function(dataset, spot_table, level_list) {
spot_table$x <- as.integer(str_split(str_split(spot_table$spot, "X",
simplify=TRUE)[,2], "Y",
simplify=TRUE)[,1])
spot_table$y <- as.integer(str_split(spot_table$spot, "Y", simplify=TRUE)[,2])
for (i in level_list) {
tmp_table <- spot_table[which(spot_table$region==i[1]),]
tmp_table$condition <- factor(i[2])
if (exists("new_spot_table")) {
new_spot_table <- rbind(new_spot_table, tmp_table)
} else {
new_spot_table <- tmp_table
}
}
new_spot_table$region <- as.factor(new_spot_table$region)
new_spot_table$run <- paste(run(dataset)[1], new_spot_table$region, sep="_")
pd_tmp <- merge(new_spot_table, coord(pixelData(dataset)), by=c("x", "y"))
pixelData(dataset) <- PositionDataFrame(coord=pd_tmp[,1:2], run=pd_tmp$run,
region=pd_tmp$region,
condition=pd_tmp$condition)
return(dataset)
}
# preprocess dataset using the following settings
# note: both "tic" and "rms" normalization were attempted
preprocess_datasets <- function(dataset) {
preprocessed <- normalize(dataset, method="tic")
preprocessed <- smoothSignal(preprocessed, method="sgolay")
preprocessed <- reduceBaseline(preprocessed, method="median")
preprocessed <- process(preprocessed)
peaks <- peakPick(preprocessed, method="simple")
peaks <- peakAlign(peaks, tolerance=0.2, units="mz")
peaks <- peakFilter(peaks, freq.min=0.05)
peaks <- process(peaks)
bin <- peakBin(preprocessed, ref=mz(peaks), type="height")
processed <- process(bin)
return(processed)
}
################################################################################
# main() #
################################################################################
# load dataset
dataset_files <- c("G:/vitek_sdgmm_preprint/PA14_TLCA_2 DAYS_2016-06-09")
datasets <- load_datasets(dataset_files)
datasets[[1]][[3]] <- list(c("PA14", "meoh"),
c("PA14_250uM_TLCA", "tlca"),
c("No_TLCA_Control", "meoh"),
c("250uM_TLCA_Control", "tlca"))
# edit metadata
pseudo_1 <- process_metadata(datasets[[1]][[1]], datasets[[1]][[2]],
datasets[[1]][[3]])
# preprocess data
pseudo_1_proc <- preprocess_datasets(pseudo_1)
# run sdgmm
# note: k=4 and k=5 attempts required significant amounts of time and RAM
pseudo_1_sdgmm <- spatialDGMM(pseudo_1_proc, r=1, k=3, method="adaptive",
init="kmeans", iter.max=1000, tol=1e-11)
summary(pseudo_1_sdgmm)
# run segmentation test
pseudo_1_segtest <- segmentationTest(pseudo_1_sdgmm, ~ condition,
classControl="Ymax")
summary(pseudo_1_segtest)
topFeatures(pseudo_1_segtest, p.adjust="fdr", AdjP<0.05, n=1000)
# save segmentation test top features to dataframe and convert to vector
pseudo_1_segtest_features <- as.data.frame(topFeatures(pseudo_1_segtest,
p.adjust="fdr", AdjP<0.05, n=1000))
pseudo_1_features_vec <- as.vector(pseudo_1_segtest_features$feature)
# view ion images for all top features IDed by segmentation test
image(pseudo_1_segtest, model=list(feature=pseudo_1_features_vec),
values="mapping", layout=c(ceiling(length(pseudo_1_features_vec)/4), 4))
# view ion images from processed dataset for all top features IDed by
# segmentation test
pseudo_1_mz_vec <- as.vector(pseudo_1_segtest_features$mz)
image(pseudo_1_proc, mz=pseudo_1_mz_vec,
layout=c(ceiling(length(pseudo_1_mz_vec)/4), 4),
contrast.enhance="histogram", smooth.image="gaussian")
################################################################################
# main2() #
################################################################################
# subset for region: Pseudomonas aeruginosa w/ TLCA media supplementation
pseudo_1_roi <- pseudo_1_proc[,pixels(pseudo_1_proc,
run=="PA14_TLCA_2 DAYS_2016-06-09_PA14_250uM_TLCA")]
# run sdgmm
pseudo_1_roi_sdgmm <- spatialDGMM(pseudo_1_roi, r=1, k=2, method="adaptive",
init="kmeans", iter.max=1000,tol=1e-11)
summary(pseudo_1_roi_sdgmm)
# visualize various features
image(pseudo_1_roi_sdgmm, model=list(feature=c(302,303,304,320,321,322)),
contrast.enhance="histogram", smooth.image="gaussian")
image(pseudo_1_roi_sdgmm, contrast.enhance="histogram",
smooth.image="gaussian", layout=c(165,3))
|
#' Fit a sNPLS model
#'
#' @description Fits a N-PLS regression model imposing sparsity on \code{wj} and \code{wk} matrices
#' @param XN A three-way array containing the predictors.
#' @param Y A matrix containing the response.
#' @param ncomp Number of components in the projection
#' @param threshold_j Threshold value on Wj. Scaled between [0, 1)
#' @param threshold_k Threshold value on Wk. scaled between [0, 1)
#' @param keepJ Number of variables to keep for each component, ignored if threshold_j is provided
#' @param keepK Number of 'times' to keep for each component, ignored if threshold_k is provided
#' @param scale.X Perform unit variance scaling on X?
#' @param center.X Perform mean centering on X?
#' @param scale.Y Perform unit variance scaling on Y?
#' @param center.Y Perform mean centering on Y?
#' @param conver Convergence criterion
#' @param max.iteration Maximum number of iterations
#' @param silent Show output?
#' @param method Select between L1 penalization (sNPLS), variable selection with Selectivity Ratio (sNPLS-SR) or variable selection with VIP (sNPLS-VIP)
#' @return A fitted sNPLS model
#' @references C. A. Andersson and R. Bro. The N-way Toolbox for MATLAB Chemometrics & Intelligent Laboratory Systems. 52 (1):1-4, 2000.
#' @references Hervas, D. Prats-Montalban, J. M., Garcia-Cañaveras, J. C., Lahoz, A., & Ferrer, A. (2019). Sparse N-way partial least squares by L1-penalization. Chemometrics and Intelligent Laboratory Systems, 185, 85-91.
#' @examples
#' X_npls<-array(rpois(7500, 10), dim=c(50, 50, 3))
#'
#' Y_npls <- matrix(2+0.4*X_npls[,5,1]+0.7*X_npls[,10,1]-0.9*X_npls[,15,1]+
#' 0.6*X_npls[,20,1]- 0.5*X_npls[,25,1]+rnorm(50), ncol=1)
#' #Discrete thresholding
#' fit <- sNPLS(X_npls, Y_npls, ncomp=3, keepJ = rep(2,3) , keepK = rep(1,3))
#' #Continuous thresholding
#' fit2 <- sNPLS(X_npls, Y_npls, ncomp=3, threshold_j=0.5, threshold_k=0.5)
#' #USe sNPLS-SR method
#' fit3 <- sNPLS(X_npls, Y_npls, ncomp=3, threshold_j=0.5, threshold_k=0.5, method="sNPLS-SR")
#' @importFrom stats sd
#' @export
sNPLS <- function(XN, Y, ncomp = 2, threshold_j=0.5, threshold_k=0.5, keepJ = NULL, keepK = NULL, scale.X=TRUE, center.X=TRUE,
scale.Y=TRUE, center.Y=TRUE, conver = 1e-16, max.iteration = 10000, silent = F, method="sNPLS"){
mynorm <- function(x) sqrt(sum(diag(crossprod(x))))
thresholding <- function(x, nj) {
ifelse(abs(x) > abs(x[order(abs(x))][nj]),
(abs(x) - abs(x[order(abs(x))][nj])) *
sign(x), 0)
}
rel_thresholding <- function(x, j_rel){
ifelse(abs(x)-max(abs(x))*j_rel <= 0, 0, sign(x)*(abs(x)-max(abs(x))*j_rel))
}
if(!method %in% c("sNPLS", "sNPLS-SR", "sNPLS-VIP")) stop("'method' not recognized")
if (length(dim(Y)) == 3) Y <- unfold3w(Y)
if (length(dim(XN)) != 3) stop("'XN' is not a three-way array")
if (!is.null(rownames(XN))){
y.names <- x.names <- rownames(XN)
} else {
y.names <- x.names <- 1:dim(XN)[1]
}
if (!is.null(colnames(XN))){
var.names <- colnames(XN)
} else {
var.names <- paste("X.", 1:dim(XN)[2], sep = "")
}
if (!is.null(dimnames(XN)[[3]])){
x3d.names <- dimnames(XN)[[3]]
} else {
x3d.names <- paste("Z.", 1:dim(XN)[3], sep = "")
}
if (!is.null(colnames(Y))){
yvar.names <- colnames(Y)
} else {
yvar.names <- paste("Y.", 1:dim(Y)[2], sep = "")
}
if(!center.X) center.X <- rep(0, ncol(XN)*dim(XN)[3])
if(!center.Y) center.Y <- rep(0, ncol(Y))
if(!scale.X) scale.X <- rep(1, ncol(XN)*dim(XN)[3])
if(!scale.Y) scale.Y <- rep(1, ncol(Y))
if(is.null(keepJ) | is.null(keepK) | method!="sNPLS"){
cont_thresholding <- TRUE
message(paste("Using continuous thresholding (", method, ")", sep=""))
} else {
cont_thresholding <- FALSE
message("Using discrete L1-thresholding")
}
if(length(threshold_j) == 1 & ncomp > 1) threshold_j <- rep(threshold_j, ncomp)
if(length(threshold_k) == 1 & ncomp > 1) threshold_k <- rep(threshold_k, ncomp)
# Matrices initialization
U <- Q <- X <- P <- NULL
if(method == "sNPLS"){
WsupraJ <- WsupraK <- Tm <- NULL
} else{
WsupraJ <- matrix(nrow=ncol(XN), ncol=ncomp)
WsupraK <- matrix(nrow=dim(XN)[3], ncol=ncomp)
Tm <- matrix(nrow=nrow(XN), ncol=ncomp)
}
Yorig <- Y
Y <- scale(Y, center = center.Y, scale = scale.Y)
y_center <- attr(Y, "scaled:center")
y_scale <- attr(Y, "scaled:scale")
B <- matrix(0, ncol = ncomp, nrow = ncomp)
Gu <- vector("list", ncomp)
S <- svd(Y)$d
u <- Y[, S == max(S)] #Column with the highest variance
# Unfolding of XN en 2-D
X <- unfold3w(XN)
#Check for zero variance columns and fix them with some noise
if(any(apply(X, 2, sd)==0)){
X[,apply(X, 2, sd)==0] <- apply(X[,apply(X, 2, sd)==0, drop=FALSE], 2, function(x) jitter(x))
}
# Center and scale
Xd <- scale(X, center = center.X, scale = scale.X)
x_center <- attr(Xd, "scaled:center")
x_scale <- attr(Xd, "scaled:scale")
# Main loop for each component
for (f in 1:ncomp) {
if(!cont_thresholding){
nj <- ncol(XN) - keepJ[f]
nk <- dim(XN)[3] - keepK[f]
}
if(method %in% c("sNPLS-VIP", "sNPLS-SR")){
nj <- ncol(XN)
nk <- dim(XN)[3]
wselj <- rep(1, nj)
wselk <- rep(1, nk)
}
it = 1
while (it < max.iteration) {
Zrow <- crossprod(u, Xd)
Z <- matrix(Zrow, nrow = dim(XN)[2], ncol = dim(XN)[3])
svd.z <- svd(Z)
wsupraj <- svd.z$u[, 1]
# L1 penalization for wsupraj
if(method == "sNPLS"){
if(cont_thresholding){
wsupraj <- rel_thresholding(wsupraj, threshold_j[f])
} else {
if (nj != 0) {
wsupraj <- thresholding(wsupraj, nj)
}
}
}
##########
wsuprak <- svd.z$v[, 1]
# L1 penalization for wsuprak
if(method == "sNPLS"){
if(cont_thresholding){
wsuprak <- rel_thresholding(wsuprak, threshold_k[f])
} else {
if (nk != 0) {
wsuprak <- thresholding(wsuprak, nk)
}
}
}
if(method %in% c("sNPLS-VIP", "sNPLS-SR")){
W <- kronecker(wsuprak, wsupraj) * kronecker(wselk, wselj)
tf <- Xd %*% W
qf <- crossprod(Y, tf)/mynorm(crossprod(Y, tf))
uf <- Y %*% qf
Tm[,f] <- tf
Q <- cbind(Q, qf)
WsupraJ[,f] <- wsupraj
WsupraK[,f] <- wsuprak
}
if(method == "sNPLS-VIP"){
#VIPj
SCE <- sum(sum(Tm[,1:f, drop=FALSE] %*% t(Q[,1:f, drop=FALSE])^2))
VIPj <- sqrt(nrow(WsupraJ)*((WsupraJ[,f, drop=FALSE]^2)*SCE)/sum(SCE))
VIPj_01 <- (VIPj-min(VIPj))/(max(VIPj)-min(VIPj))
#VIPk
SCE <- sum(sum(Tm[,1:f, drop=FALSE] %*% t(Q[,1:f, drop=FALSE])^2))
VIPk <- sqrt(nrow(WsupraK)*((WsupraK[,f, drop=FALSE]^2)*SCE)/sum(SCE))
VIPk_01 <- (VIPk-min(VIPk))/(max(VIPk)-min(VIPk))
wselk <- as.numeric(VIPk_01 > threshold_k[f])
wselj <- as.numeric(VIPj_01 > threshold_j[f])
}
if(method == "sNPLS-SR"){
TM <- MASS::ginv(crossprod(Tm[,1:f, drop=FALSE])) %*% t(Tm[,1:f, drop=FALSE])
WkM <- MASS::ginv(crossprod(WsupraK[,1:f, drop=FALSE])) %*% t(WsupraK[,1:f, drop=FALSE])
WjM <- MASS::ginv(crossprod(WsupraJ[,1:f, drop=FALSE])) %*% t(WsupraJ[,1:f, drop=FALSE])
Gu[[f]] <- TM %*% X %*% kronecker(t(WkM), t(WjM))
#SR
P[[f]] = t(as.matrix(Gu[[f]]) %*% t(kronecker(WsupraK[,1:f, drop=FALSE], WsupraJ[,1:f, drop=FALSE])))
Xres <- Xd - Tm[,1:f, drop=FALSE] %*% t(P[[f]])
xpred <- Tm[,1:f, drop=FALSE] %*% t(P[[f]])
SSexp <- xpred^2
SSres <- (Xd-xpred)^2
SSexp_cube <- array(SSexp, dim=c(nrow(SSexp), nj, nk))
SSres_cube <- array(SSres, dim=c(nrow(SSexp), nj, nk))
SR_k <- numeric(nk)
for(k in 1:nk){
SR_k[k] <- sum(SSexp_cube[,,k])/sum(SSres_cube[,,k])
}
SR_k_01 <- (SR_k-min(SR_k))/(max(SR_k)-min(SR_k))
SR_j <- numeric(nj)
for(j in 1:nj){
SR_j[j] <- sum(SSexp_cube[,j,])/sum(SSres_cube[,j,])
}
SR_j_01 <- (SR_j-min(SR_j))/(max(SR_j)-min(SR_j))
wselj <- rep(1, nj)
wselk <- rep(1, nk)
PFcalck <- SR_k_01
wselk <- as.numeric(PFcalck > threshold_k[f])
PFcalcj <- SR_j_01
wselj <- as.numeric(PFcalcj > threshold_j[f])
}
##########
if(method == "sNPLS"){
tf <- Xd %*% kronecker(wsuprak, wsupraj)
qf <- crossprod(Y, tf)/mynorm(crossprod(Y, tf))
uf <- Y %*% qf
}
if (sum((uf - u)^2) < conver) {
if (!silent) {
cat(paste("Component number ", f, "\n"))
cat(paste("Number of iterations: ", it, "\n"))
}
it <- max.iteration
if(method == "sNPLS"){
Tm <- cbind(Tm, tf)
WsupraJ <- cbind(WsupraJ, wsupraj)
WsupraK <- cbind(WsupraK, wsuprak)
bf <- MASS::ginv(crossprod(Tm)) %*% t(Tm) %*% uf
TM <- MASS::ginv(crossprod(Tm)) %*% t(Tm)
Q <- cbind(Q, qf)
} else {
Tm[,f] <- tf
WsupraJ[,f] <- wsupraj*wselj
WsupraK[,f] <- wsuprak*wselk
bf <- MASS::ginv(crossprod(Tm[,1:f, drop=FALSE])) %*% t(Tm[,1:f, drop=FALSE]) %*% uf
}
B[1:length(bf), f] <- bf
U <- cbind(U, uf)
if(method == "sNPLS-VIP"){
TM <- MASS::ginv(crossprod(Tm[,1:f, drop=FALSE])) %*% t(Tm[,1:f, drop=FALSE])
WkM <- MASS::ginv(crossprod(WsupraK[,1:f, drop=FALSE])) %*% t(WsupraK[,1:f, drop=FALSE])
WjM <- MASS::ginv(crossprod(WsupraJ[,1:f, drop=FALSE])) %*% t(WsupraJ[,1:f, drop=FALSE])
Gu[[f]] <- TM %*% X %*% kronecker(t(WkM), t(WjM))
P[[f]] = t(as.matrix(Gu[[f]]) %*% t(kronecker(WsupraK[,1:f, drop=FALSE], WsupraJ[,1:f, drop=FALSE])))
}
if(method == "sNPLS"){
TM <- MASS::ginv(crossprod(Tm)) %*% t(Tm)
WkM <- MASS::ginv(crossprod(WsupraK)) %*% t(WsupraK)
WjM <- MASS::ginv(crossprod(WsupraJ)) %*% t(WsupraJ)
Gu[[f]] <- TM %*% X %*% kronecker(t(WkM), t(WjM))
P[[f]] = t(as.matrix(Gu[[f]]) %*% t(kronecker(WsupraK, WsupraJ)))
}
if(method == "sNPLS"){
Y <- Y - Tm %*% bf %*% t(qf)
} else {
Y <- Y - Tm[,1:f, drop=FALSE] %*% bf %*% t(qf)
}
S <- svd(Y)$d
u <- Y[, S == max(S)]
} else {
u <- uf
it <- it + 1
}
}
}
Yadjsc <- Tm %*% B %*% t(Q)
Yadj <- Yadjsc * y_scale + y_center
SqrdE <- sum((Yorig - Yadj)^2)
rownames(WsupraJ) <- var.names
rownames(WsupraK) <- x3d.names
rownames(Q) <- yvar.names
rownames(Tm) <- rownames(U) <- x.names
colnames(Tm) <- colnames(WsupraJ) <- colnames(WsupraK) <- colnames(B) <-
colnames(U) <- colnames(Q) <- names(Gu) <- names(P) <- paste("Comp.", 1:ncomp)
output <- list(T = Tm, Wj = WsupraJ, Wk = WsupraK, B = B, U = U, Q = Q, P = P,
Gu = Gu, ncomp = ncomp, Xd=Xd, Yorig = Yorig, Yadj = Yadj, SqrdE = SqrdE,
Standarization = list(ScaleX = x_scale, CenterX = x_center,
ScaleY = y_scale, CenterY = y_center),
Method = method)
class(output)<-"sNPLS"
return(output)
}
#' R-matrix from a sNPLS model fit
#'
#' @description Builds the R-matrix from a sNPLS model fit
#' @param x A sNPLS model obtained from \code{sNPLS}
#' @return Returns the R-matrix of the model, needed to compute the coefficients
Rmatrix<-function(x) {
WsupraK <- x$Wk
WsupraJ <- x$Wj
R <- matrix(nrow = dim(x$Wj)[1] * dim(x$Wk)[1], ncol = x$ncomp)
ncomp <- x$ncomp
kroneckers<-sapply(1:x$ncomp, function(x) kronecker(WsupraK[, x], WsupraJ[, x]))
tkroneckers<-apply(kroneckers, 2, function(x) t(x))
R[,1] <- kroneckers[,1]
if(ncomp>1){
for(i in 2:ncomp){
pi <- pi0 <- Matrix::Matrix(diag(dim(R)[1]), sparse=TRUE)
for (j in 1:(i - 1)) {
pi <- Matrix::Matrix(pi %*% pi0 - kroneckers[,j] %*% t(tkroneckers[,j]), sparse=TRUE)
}
w <- kroneckers[, i]
pi <- pi %*% w
R[, i] <- Matrix::as.matrix(pi)
}
}
return(R)
}
#' Unfolding of three-way arrays
#'
#' @description Unfolds a three-way array into a matrix
#' @param x A three-way array
#' @return Returns a matrix with dimensions \code{dim(x)[1] x dim(x)[2]*dim(x([3]))}
unfold3w <- function(x) {
dim(x) <- c(dim(x)[1], dim(x)[2] * dim(x)[3])
return(x)
}
#' Cross-validation for a sNPLS model
#'
#' @description Performs cross-validation for a sNPLS model
#' @param X_npls A three-way array containing the predictors.
#' @param Y_npls A matrix containing the response.
#' @param ncomp A vector with the different number of components to test
#' @param samples Number of samples for performing random search in continuous thresholding
#' @param threshold_j Vector with threshold min and max values on Wj. Scaled between [0, 1)
#' @param threshold_k Vector with threshold min and max values on Wk. Scaled between [0, 1)
#' @param keepJ A vector with the different number of selected variables to test for discrete thresholding
#' @param keepK A vector with the different number of selected 'times' to test for discrete thresholding
#' @param nfold Number of folds for the cross-validation
#' @param parallel Should the computations be performed in parallel? Set up strategy first with \code{future::plan()}
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param metric Select between RMSE or AUC (for 0/1 response)
#' @param ... Further arguments passed to sNPLS
#' @return A list with the best parameters for the model and the CV error
#' @examples
#' \dontrun{
#' X_npls<-array(rpois(7500, 10), dim=c(50, 50, 3))
#'
#' Y_npls<-matrix(2+0.4*X_npls[,5,1]+0.7*X_npls[,10,1]-0.9*X_npls[,15,1]+
#' 0.6*X_npls[,20,1]- 0.5*X_npls[,25,1]+rnorm(50), ncol=1)
#' #Grid search for discrete thresholding
#' cv1<- cv_snpls(X_npls, Y_npls, ncomp=1:2, keepJ = 1:3, keepK = 1:2, parallel = FALSE)
#' #Random search for continuous thresholding
#' cv2<- cv_snpls(X_npls, Y_npls, ncomp=1:2, samples=20, parallel = FALSE)
#' }
#' @importFrom stats runif
#' @export
cv_snpls <- function(X_npls, Y_npls, ncomp = 1:3, samples = 20, threshold_j = c(0, 1),
threshold_k = c(0, 1), keepJ = NULL, keepK = NULL, nfold = 10,
parallel = TRUE, method="sNPLS", metric="RMSE", ...) {
if(parallel) message("Your parallel configuration is ", attr(future::plan(), "class")[3])
if(!method %in% c("sNPLS", "sNPLS-SR", "sNPLS-VIP")) stop("'method' not recognized")
if(length(dim(Y_npls)) == 3) Y_npls <- unfold3w(Y_npls)
top <- ceiling(dim(X_npls)[1]/nfold)
foldid <- sample(rep(1:nfold, top), dim(X_npls)[1], replace = F)
if(is.null(keepJ) | is.null(keepK)){
cont_thresholding <- TRUE
message("Using continuous thresholding")
} else {
cont_thresholding <- FALSE
message("Using discrete thresholding")
}
if(cont_thresholding){
search.grid <- expand.grid(list(ncomp = ncomp,
threshold_j = runif(samples, min = threshold_j[1], max = threshold_j[2]),
threshold_k = runif(samples, min = threshold_k[1], max = threshold_k[2])))
} else {
search.grid <- expand.grid(list(ncomp = ncomp, keepJ = keepJ,
keepK = keepK))
}
SqrdE <- numeric()
applied_fun <- function(y) {
sapply(1:nfold, function(x) {
suppressMessages(tryCatch(do.call(cv_fit, c(list(xtrain = X_npls[x != foldid, , ],
ytrain = Y_npls[x != foldid, , drop = FALSE],
xval = X_npls[x == foldid, , ],
yval = Y_npls[x == foldid, , drop = FALSE],
ncomp = y["ncomp"], method=method, metric=metric),
list(threshold_j=y["threshold_j"])[cont_thresholding],
list(threshold_k=y["threshold_k"])[cont_thresholding],
list(keepJ=rep(y["keepJ"], y["ncomp"]))[!cont_thresholding],
list(keepK=rep(y["keepK"], y["ncomp"]))[!cont_thresholding], ...)),
error=function(x) NA))
})
}
if (parallel) {
cv_res <- future.apply::future_apply(search.grid, 1, applied_fun, future.seed=TRUE)
} else {
cv_res <- pbapply::pbapply(search.grid, 1, applied_fun)
}
cv_mean <- apply(cv_res, 2, function(x) mean(x, na.rm = TRUE))
cv_se <- apply(cv_res, 2, function(x) sd(x, na.rm=TRUE)/sqrt(nfold))
if(metric == "RMSE"){
best_model <- search.grid[which.min(cv_mean), ]
} else{
best_model <- search.grid[which.max(cv_mean), ]
}
output <- list(best_parameters = best_model, cv_mean = cv_mean,
cv_se = cv_se, cv_grid = search.grid)
class(output)<-"cvsNPLS"
return(output)
}
#' Internal function for \code{cv_snpls}
#'
#' @param xtrain A three-way training array
#' @param ytrain A response training matrix
#' @param xval A three-way test array
#' @param yval A response test matrix
#' @param ncomp Number of components for the sNPLS model
#' @param threshold_j Threshold value on Wj. Scaled between [0, 1)
#' @param threshold_k Threshold value on Wk. Scaled between [0, 1)
#' @param keepJ Number of variables to keep for each component, ignored if threshold_j is provided
#' @param keepK Number of 'times' to keep for each component, ignored if threshold_k is provided
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param metric Performance metric (RMSE or AUC)
#' @param ... Further arguments passed to sNPLS
#' @return Returns the CV root mean squared error or AUC
#' @importFrom stats predict
#' @export
cv_fit <- function(xtrain, ytrain, xval, yval, ncomp, threshold_j=NULL, threshold_k=NULL, keepJ=NULL, keepK=NULL, method, metric, ...) {
fit <- sNPLS(XN = xtrain, Y = ytrain, ncomp = ncomp, keepJ=keepJ, keepK=keepK, threshold_j = threshold_j,
threshold_k = threshold_k, silent = TRUE, method=method, ...)
Y_pred <- predict(fit, xval)
if(!metric %in% c("RMSE", "AUC")) stop("Invalid metric for cross-validation")
if(metric == "RMSE"){
CVE <- sqrt(mean((Y_pred - yval)^2))
} else{
CVE <- as.numeric(pROC::roc(yval ~ Y_pred[,1])$auc)
}
return(CVE)
}
#' Plots for sNPLS model fits
#'
#' @description Different plots for sNPLS model fits
#' @param x A sNPLS model fit
#' @param comps Vector with the components to plot. It can be of length \code{ncomp} for types "time" and "variables" and of length 2 otherwise.
#' @param type The type of plot. One of those: "T", "U", "Wj", "Wk", "time" or "variables"
#' @param labels Should rownames be added as labels to the plot?
#' @param group Vector with categorical variable defining groups (optional)
#' @param ... Not used
#' @return A plot of the type specified in the \code{type} parameter
#' @export
plot.sNPLS <- function(x, type = "T", comps = c(1, 2), labels=TRUE, group=NULL, ...) {
if (type == "T")
p<-plot_T(x, comps = comps, labels=labels, group=group)
if (type == "U")
p<-plot_U(x, comps = comps, labels=labels, group=group)
if (type == "Wj")
p<-plot_Wj(x, comps = comps, labels=labels)
if (type == "Wk")
p<-plot_Wk(x, comps = comps, labels=labels)
if (type == "time")
p<-plot_time(x, comps = comps)
if (type == "variables")
p<-plot_variables(x, comps = comps)
p
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @param group Vector with categorical variable defining groups
#' @return A plot of the T matrix of a sNPLS model fit
plot_T <- function(x, comps, labels, group=NULL){
df <- data.frame(x$T)[comps]
if(!is.null(group)) df <- data.frame(df, group=as.factor(group))
names(df)[1:2] <- paste("Comp.", comps, sep="")
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=rownames(df)))
if(!is.null(group)) p1 <- p1 + ggplot2::geom_point(ggplot2::aes(color=group))
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @param group Vector with categorical variable defining groups
#' @return A plot of the U matrix of a sNPLS model fit
plot_U <- function(x, comps, labels, group=NULL){
df <- data.frame(x$U)[comps]
if(!is.null(group)) df <- data.frame(df, group=as.factor(group))
names(df)[1:2] <- paste("Comp.", comps, sep="")
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=rownames(df)))
if(!is.null(group)) p1 <- p1 + ggplot2::geom_point(ggplot2::aes(color=group))
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @return A plot of Wj coefficients
plot_Wj <- function(x, comps, labels){
df <- data.frame(x$Wj)[comps]
names(df) <- paste("Comp.", comps, sep="")
var_names_zero <- rownames(df)
var_names_zero[rowSums(df)==0]<- ""
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=var_names_zero), size=3)
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @return A plot of the Wk coefficients
plot_Wk <- function(x, comps, labels){
df <- data.frame(x$Wk)[comps]
names(df) <- paste("Comp.", comps, sep="")
var_names_zero <- rownames(df)
var_names_zero[rowSums(df)==0]<- ""
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=var_names_zero), size=4)
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector with the components to plot
#' @return A plot of Wk coefficients for each component
plot_time <- function(x, comps){
df <- clickR::forge(data.frame(row=1:nrow(x$Wk), x$Wk), affixes=as.character(comps),
var.name="Component")
ggplot2::ggplot(df, ggplot2::aes_string(x="row", y="Comp..", color="Component")) +
ggplot2::geom_line(lwd=1.05) + ggplot2::theme_bw() +
ggplot2::geom_hline(yintercept = 0, alpha=0.2) +
ggplot2::xlab("Time (index)") + ggplot2::ylab("Wk") +
ggplot2::theme(axis.text = ggplot2::element_text(size=12),
axis.title = ggplot2::element_text(size=12,face="bold"))
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector with the components to plot
#' @return A plot of Wj coefficients for each component
plot_variables <- function(x, comps){
df <- clickR::forge(data.frame(row=1:nrow(x$Wj), x$Wj), affixes=as.character(comps),
var.name="Component")
ggplot2::ggplot(df, ggplot2::aes_string(x="row", y="Comp..", color="Component")) +
ggplot2::geom_line(lwd=1.05) + ggplot2::theme_bw() +
ggplot2::geom_hline(yintercept = 0, alpha=0.2) +
ggplot2::xlab("Variable (index)") + ggplot2::ylab("Wj") +
ggplot2::theme(axis.text = ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
}
#' Predict for sNPLS models
#'
#' @description Predict function for sNPLS models
#' @param object A sNPLS model fit
#' @param newX A three-way array containing the new data
#' @param rescale Should the prediction be rescaled to the original scale?
#' @param ... Further arguments passed to \code{predict}
#' @return A matrix with the predictions
#' @export
predict.sNPLS <- function(object, newX, rescale = TRUE, ...) {
newX <- unfold3w(newX)
# Centrado y escalado
#Xstd <- t((t(newX) - object$Standarization$CenterX)/object$Standarization$ScaleX)
#Xstd <- sweep(sweep(newX, 2, object$Standarization$CenterX), 2, object$Standarization$ScaleX, "/")
Xstd <- scale(newX, center=object$Standarization$CenterX, scale=object$Standarization$ScaleX)
R <- Rmatrix(object)
Bnpls <- R %*% object$B %*% t(object$Q)
Yval <- Xstd %*% Bnpls
if (rescale) {
Yval <- Yval * object$Standarization$ScaleY + object$Standarization$CenterY
}
return(Yval)
}
#' Fitted method for sNPLS models
#'
#' @description Fitted method for sNPLS models
#' @param object A sNPLS model fit
#' @param ... Further arguments passed to \code{fitted}
#' @return Fitted values for the sNPLS model
#' @export
fitted.sNPLS <- function(object, ...){
return(object$Yadj)
}
#' Plot cross validation results for sNPLS objects
#'
#' @description Plot function for visualization of cross validation results for sNPLS models
#' @param x A cv_sNPLS object
#' @param ... Not used
#' @return A facet plot with the results of the cross validation
#' @export
plot.cvsNPLS <- function(x, ...) {
cont_thresholding <- names(x$cv_grid)[2] == "threshold_j"
df_grid <- data.frame(threshold_j=x$cv_grid[,2], threshold_k=x$cv_grid[,3], CVE=x$cv_mean, Ncomp=paste("Ncomp =", x$cv_grid$ncomp, sep=" "))
if(!cont_thresholding) names(df_grid)[c(1, 2)] <- c("KeepJ", "KeepK")
if(cont_thresholding){
ggplot2::ggplot(df_grid, ggplot2::aes_string(x="threshold_j", y="CVE"))+ggplot2::geom_point()+ggplot2::geom_smooth()+ggplot2::facet_grid(cut(threshold_k,10) ~ Ncomp)+
ggplot2::theme_bw()
} else {
ggplot2::ggplot(df_grid, ggplot2::aes_string(x="KeepJ", y="CVE"))+ggplot2::geom_point()+ggplot2::geom_line()+ggplot2::facet_grid(KeepK ~ Ncomp)+
ggplot2::theme_bw()
}
}
#' Coefficients from a sNPLS model
#'
#' @description Extract coefficients from a sNPLS model
#' @param object A sNPLS model fit
#' @param as.matrix Should the coefficients be presented as matrix or vector?
#' @param ... Further arguments passed to \code{coef}
#' @return A matrix (or vector) of coefficients
#' @export
coef.sNPLS <- function(object, as.matrix = FALSE, ...) {
R <- Rmatrix(object)
Bnpls <- R %*% object$B %*% t(object$Q)
colnames(Bnpls) <- paste("Estimate", colnames(Bnpls))
if (as.matrix){
dim(Bnpls) <- c(dim(object$Wj)[1], dim(object$Wk)[1], dim(Bnpls)[2])
rownames(Bnpls) <- rownames(object$Wj)
colnames(Bnpls) <- rownames(object$Wk)
}
return(Bnpls)
}
#' Repeated cross-validation for sNPLS models
#'
#' @description Performs repeated cross-validatiodn and represents results in a plot
#' @param X_npls A three-way array containing the predictors.
#' @param Y_npls A matrix containing the response.
#' @param ncomp A vector with the different number of components to test
#' @param samples Number of samples for performing random search in continuous thresholding
#' @param keepJ A vector with the different number of selected variables to test in discrete thresholding
#' @param keepK A vector with the different number of selected 'times' to test in discrete thresholding
#' @param threshold_j Vector with threshold min and max values on Wj. Scaled between [0, 1)
#' @param threshold_k Vector with threshold min and max values on Wk. Scaled between [0, 1)
#' @param nfold Number of folds for the cross-validation
#' @param times Number of repetitions of the cross-validation
#' @param parallel Should the computations be performed in parallel? Set up strategy first with \code{future::plan()}
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param metric Select between RMSE or AUC (for 0/1 response)
#' @param ... Further arguments passed to cv_snpls
#' @return A density plot with the results of the cross-validation and an (invisible) \code{data.frame} with these results
#' @importFrom stats var
#' @export
repeat_cv <- function(X_npls, Y_npls, ncomp = 1:3, samples=20, keepJ=NULL, keepK=NULL,
threshold_j = c(0, 1), threshold_k = c(0, 1), nfold = 10, times=30,
parallel = TRUE, method="sNPLS", metric="RMSE", ...){
if(!method %in% c("sNPLS", "sNPLS-SR", "sNPLS-VIP")) stop("'method' not recognized")
if(parallel) message("Your parallel configuration is ", attr(future::plan(), "class")[3])
if(is.null(keepJ) | is.null(keepK)){
cont_thresholding <- TRUE
message("Using continuous thresholding")
} else {
cont_thresholding <- FALSE
message("Using discrete thresholding")
}
if(parallel){
rep_cv<-future.apply::future_sapply(1:times, function(x) suppressMessages(cv_snpls(X_npls, Y_npls, ncomp=ncomp, parallel = FALSE, nfold = nfold, samples=samples, keepJ=keepJ, keepK=keepK, threshold_j=threshold_j, threshold_k=threshold_k, method=method, metric=metric, ...)), future.seed=TRUE)
} else {
rep_cv<-pbapply::pbreplicate(times, suppressMessages(cv_snpls(X_npls, Y_npls, ncomp=ncomp, parallel = FALSE, nfold = nfold, samples=samples, keepJ=keepJ, keepK=keepK, threshold_j=threshold_j, threshold_k=threshold_k, method=method, metric=metric, ...)))
}
resdata<-data.frame(ncomp=sapply(rep_cv[1,], function(x) x[[1]]), threshold_j=sapply(rep_cv[1,], function(x) x[[2]]),
threshold_k=sapply(rep_cv[1,], function(x) x[[3]]))
if(!cont_thresholding) names(resdata)[c(2, 3)] <- c("keepJ", "keepK")
class(resdata)<-c("repeatcv", "data.frame")
return(resdata)
}
#' Density plot for repeat_cv results
#'
#' @description Plots a grid of slices from the 3-D kernel denity estimates of the repeat_cv function
#' @param x A repeatcv object
#' @param ... Further arguments passed to plot
#' @return A grid of slices from a 3-D density plot of the results of the repeated cross-validation
#' @importFrom grDevices colorRampPalette
#' @importFrom stats ftable density setNames
#' @export
plot.repeatcv <- function(x, ...){
x.old <- x
x<-x[,sapply(x, function(x) var(x)>0), drop=FALSE]
if(ncol(x) < ncol(x.old)) warning(paste("\n", colnames(x.old)[!colnames(x.old) %in% colnames(x)], "is constant at", x.old[1,colnames(x.old)[!colnames(x.old) %in% colnames(x)]]))
if(ncol(x) == 1){
densities <- density(x[,1])
df_grid <- setNames(data.frame(densities$x, densities$y), c(colnames(x), "density"))
p <- ggplot2::ggplot(x, ggplot2::aes_string(x=colnames(x)))+ggplot2::geom_density(color="gray", fill="gray", alpha=0.3)+ggplot2::theme_classic()
} else{
H.pi <- ks::Hpi(x)
fhat <- ks::kde(x, H=H.pi, compute.cont=TRUE, gridsize = rep(151, ncol(x)))
if(ncol(x) == 3){
ncomp_values <- sapply(sort(unique(fhat$x[,1])), function(x) which.min(abs(fhat$eval.points[[1]]-x)))
positions <- as.data.frame(fhat$x)
positions$Ncomp <- factor(positions$ncomp)
df_grid <- setNames(expand.grid(fhat$eval.points[[2]], fhat$eval.points[[3]]), names(positions)[c(2,3)])
combl <- nrow(df_grid)
df_grid <- df_grid[rep(1:nrow(df_grid), length(ncomp_values)),]
df_grid$density <- unlist(lapply(ncomp_values, function(x) as.numeric(matrix(fhat$estimate[x,,], ncol=1))))
df_grid$Ncomp <- factor(rep(sort(unique(positions$ncomp)), each=combl))
p <- ggplot2::ggplot(df_grid, ggplot2::aes_string(names(df_grid)[1], names(df_grid)[2], fill="density"))+ggplot2::geom_raster()+
ggplot2::scale_fill_gradientn(colours =colorRampPalette(c("white", "blue", "red"))(10))+ggplot2::theme_classic()+
ggplot2::geom_count(inherit.aes = FALSE, ggplot2::aes_string(x=names(df_grid)[1], y=names(df_grid)[2]), data=positions) +ggplot2::facet_grid(~Ncomp)
if(names(df_grid)[1] == "threshold_j"){
p <- p + ggplot2::scale_x_continuous(limits=c(0, 1)) + ggplot2::scale_y_continuous(limits=c(0, 1))
} else {
p <- p + ggplot2::scale_x_continuous(breaks=if(round(diff(range(df_grid$keepJ)))<=10) round(max(0, min(df_grid$keepJ)):max(df_grid$keepJ)) else round(seq(max(0, min(df_grid$keepJ)), max(df_grid$keepJ), by= ceiling(max(df_grid$keepJ)/20)*2)))+
ggplot2::scale_y_continuous(breaks=if(round(diff(range(df_grid$keepK)))<=10) round(max(0, min(df_grid$keepK)):max(df_grid$keepK)) else round(seq(max(0, min(df_grid$keepK)), max(df_grid$keepK), by= ceiling(max(df_grid$keepK)/20)*2)))+
ggplot2::scale_size_area(breaks=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))],
labels=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))])
}
} else {
positions <- as.data.frame(fhat$x)
df_grid <- expand.grid(V1=fhat$eval.points[[1]], V2=fhat$eval.points[[2]])
names(df_grid)<-colnames(positions)
df_grid$density <- as.numeric(matrix(fhat$estimate, ncol=1))
p <- ggplot2::ggplot(df_grid, ggplot2::aes_string(colnames(df_grid)[1], colnames(df_grid)[2], fill="density"))+ggplot2::geom_raster()+
ggplot2::scale_fill_gradientn(colours =colorRampPalette(c("white", "blue", "red"))(10))+ggplot2::theme_classic()+
ggplot2::geom_count(inherit.aes = FALSE, ggplot2::aes_string(x=colnames(df_grid)[1], y=colnames(df_grid)[2]), data=positions)
if("threshold_j" %in% names(df_grid) | "threshold_k" %in% names(df_grid)){
p <- p + ggplot2::scale_x_continuous(limits=c(0, 1)) + ggplot2::scale_y_continuous(limits=c(0, 1))
} else {
p <- p + ggplot2::scale_x_continuous(breaks=if(round(diff(range(df_grid[,1])))<=10) round(max(0, min(df_grid[,1])):max(df_grid[,1])) else round(seq(max(0, min(df_grid[,1])), max(df_grid[,1]), by= ceiling(max(df_grid[,1])/20)*2)))+
ggplot2::scale_y_continuous(breaks=if(round(diff(range(df_grid[,2])))<=10) round(max(0, min(df_grid[,2])):max(df_grid[,2])) else round(seq(max(0, min(df_grid[,2])), max(df_grid[,2]), by= ceiling(max(df_grid[,2])/20)*2)))+
ggplot2::scale_size_continuous(breaks=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))],
labels=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))])
}
}
}
print(p)
data.frame(x.old[1, !colnames(x.old) %in% colnames(x), drop=FALSE], df_grid[which.max(df_grid$density),])
}
#' Summary for sNPLS models
#'
#' @description Summary of a sNPLS model fit
#' @param object A sNPLS object
#' @param ... Further arguments passed to summary.default
#' @return A summary inclunding number of components, squared error and coefficients of the fitted model
#' @importFrom stats coef
#' @export
summary.sNPLS <- function(object, ...){
cat(object$Method, "model with", object$ncomp, "components and squared error of", round(object$SqrdE,3), "\n", "\n")
cat("Coefficients: \n")
round(coef(object, as.matrix=TRUE), 3)
}
#' AUC for sNPLS-DA model
#'
#' @description AUC for a sNPLS-DA model
#' @param object A sNPLS object
#' @return The area under the ROC curve for the model
#' @export
auroc <- function(object){
as.numeric(pROC::roc(object$Yorig[,1] ~ object$Yadj[,1])$auc)
}
#' Compute Selectivity Ratio for a sNPLS model
#'
#' @description Estimates Selectivity Ratio for the different components of a sNPLS model fit
#' @param model A sNPLS model
#' @return A list of data.frames, each of them including the computed Selectivity Ratios for each variable
#' @export
SR <- function(model){
output <- lapply(1:model$ncomp, function(f){
Xres <- model$Xd - model$T[,1:f, drop=FALSE] %*% t(model$P[[f]])
Xpred <- model$T[,1:f, drop=FALSE] %*% t(model$P[[f]])
SSexp <- Xpred^2
SSres <- (model$Xd-Xpred)^2
SSexp_cube <- array(SSexp, dim=c(nrow(SSexp), nrow(model$Wj), nrow(model$Wk)))
SSres_cube <- array(SSres, dim=c(nrow(SSexp), nrow(model$Wj), nrow(model$Wk)))
SR_k <- sapply(1:nrow(model$Wk), function(x) sum(SSexp_cube[,,x])/sum(SSres_cube[,,x]))
SR_j <- sapply(1:nrow(model$Wj), function(x) sum(SSexp_cube[,x,])/sum(SSres_cube[,x,]))
list(SR_k=round(SR_k,3),
SR_j=round(SR_j,3))
})
SR_j <- do.call("cbind", sapply(output, function(x) x[2]))
SR_k <- do.call("cbind", sapply(output, function(x) x[1]))
rownames(SR_j) <- rownames(model$Wj)
rownames(SR_k) <- rownames(model$Wk)
colnames(SR_j) <- colnames(SR_k) <- paste("Component ", 1:model$ncomp, sep="")
list(SR_j=SR_j, SR_k=SR_k)
}
#' Genetic Algorithm for selection of hyperparameter values
#'
#' @description Runs a genetic algorithm to select the best combination of hyperparameter values
#' @param X A three-way array containing the predictors.
#' @param Y A matrix containing the response.
#' @param ncomp A vector with the minimum and maximum number of components to assess
#' @param threshold_j Vector with threshold min and max values on Wj. Scaled between [0, 1)
#' @param threshold_k Vector with threshold min and max values on Wk. Scaled between [0, 1)
#' @param maxiter Maximum number of iterations (generations) of the genetic algorithm
#' @param popSize Population size (see \code{GA::ga()} documentation)
#' @param parallel Should the computations be performed in parallel? (see \code{GA::ga()} documentation)
#' @param replicates Number of replicates for the cross-validation performed in the fitness function of the genetic algoritm
#' @param metric Select between RMSE or AUC (for 0/1 response)
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param ... Further arguments passed to \code{GA::ga()}
#' @return A summary of the genetic algorithm results
#' @importFrom GA ga
#' @importFrom pbapply pblapply
#' @export
ga_snpls <- function(X, Y, ncomp=c(1, 3), threshold_j=c(0, 1), threshold_k=c(0, 1), maxiter=20,
popSize=50, parallel=TRUE, replicates=10, metric="RMSE", method="sNPLS", ...){
fitness_function <- function(x) {
# Calculate the performance of the model with the hyperparameters
performance <- mean(pbapply::pbreplicate(replicates, suppressMessages(cv_snpls(X, Y, ncomp=round(x[1]), threshold_j = rep(x[2], 2), threshold_k = rep(x[3], 2), samples = 1, metric=metric, method = "sNPLS")$cv_mean)))
if(metric == "AUC") performance else -performance
}
res <- as.data.frame(GA::ga(type = "real-valued",
fitness = fitness_function,
lower = c(ncomp=ncomp[1]-0.5, threshold_j=threshold_j[1], threshold_k=threshold_k[1]),
upper = c(ncomp=ncomp[2]+0.5, threshold_j=threshold_j[2], threshold_k=threshold_k[2]),
maxiter = maxiter,
popSize = popSize,
parallel=parallel, ...)@summary)
if(metric == "RMSE"){
res <- res*-1
names(res) <- c("min", "mean", "q1", "median", "q3", "max")
}
res$iteration <- 1:nrow(res)
res
}
| /R/sNPLS_fit.R | no_license | David-Hervas/sNPLS | R | false | false | 41,241 | r | #' Fit a sNPLS model
#'
#' @description Fits a N-PLS regression model imposing sparsity on \code{wj} and \code{wk} matrices
#' @param XN A three-way array containing the predictors.
#' @param Y A matrix containing the response.
#' @param ncomp Number of components in the projection
#' @param threshold_j Threshold value on Wj. Scaled between [0, 1)
#' @param threshold_k Threshold value on Wk. scaled between [0, 1)
#' @param keepJ Number of variables to keep for each component, ignored if threshold_j is provided
#' @param keepK Number of 'times' to keep for each component, ignored if threshold_k is provided
#' @param scale.X Perform unit variance scaling on X?
#' @param center.X Perform mean centering on X?
#' @param scale.Y Perform unit variance scaling on Y?
#' @param center.Y Perform mean centering on Y?
#' @param conver Convergence criterion
#' @param max.iteration Maximum number of iterations
#' @param silent Show output?
#' @param method Select between L1 penalization (sNPLS), variable selection with Selectivity Ratio (sNPLS-SR) or variable selection with VIP (sNPLS-VIP)
#' @return A fitted sNPLS model
#' @references C. A. Andersson and R. Bro. The N-way Toolbox for MATLAB Chemometrics & Intelligent Laboratory Systems. 52 (1):1-4, 2000.
#' @references Hervas, D. Prats-Montalban, J. M., Garcia-Cañaveras, J. C., Lahoz, A., & Ferrer, A. (2019). Sparse N-way partial least squares by L1-penalization. Chemometrics and Intelligent Laboratory Systems, 185, 85-91.
#' @examples
#' X_npls<-array(rpois(7500, 10), dim=c(50, 50, 3))
#'
#' Y_npls <- matrix(2+0.4*X_npls[,5,1]+0.7*X_npls[,10,1]-0.9*X_npls[,15,1]+
#' 0.6*X_npls[,20,1]- 0.5*X_npls[,25,1]+rnorm(50), ncol=1)
#' #Discrete thresholding
#' fit <- sNPLS(X_npls, Y_npls, ncomp=3, keepJ = rep(2,3) , keepK = rep(1,3))
#' #Continuous thresholding
#' fit2 <- sNPLS(X_npls, Y_npls, ncomp=3, threshold_j=0.5, threshold_k=0.5)
#' #USe sNPLS-SR method
#' fit3 <- sNPLS(X_npls, Y_npls, ncomp=3, threshold_j=0.5, threshold_k=0.5, method="sNPLS-SR")
#' @importFrom stats sd
#' @export
sNPLS <- function(XN, Y, ncomp = 2, threshold_j=0.5, threshold_k=0.5, keepJ = NULL, keepK = NULL, scale.X=TRUE, center.X=TRUE,
scale.Y=TRUE, center.Y=TRUE, conver = 1e-16, max.iteration = 10000, silent = F, method="sNPLS"){
mynorm <- function(x) sqrt(sum(diag(crossprod(x))))
thresholding <- function(x, nj) {
ifelse(abs(x) > abs(x[order(abs(x))][nj]),
(abs(x) - abs(x[order(abs(x))][nj])) *
sign(x), 0)
}
rel_thresholding <- function(x, j_rel){
ifelse(abs(x)-max(abs(x))*j_rel <= 0, 0, sign(x)*(abs(x)-max(abs(x))*j_rel))
}
if(!method %in% c("sNPLS", "sNPLS-SR", "sNPLS-VIP")) stop("'method' not recognized")
if (length(dim(Y)) == 3) Y <- unfold3w(Y)
if (length(dim(XN)) != 3) stop("'XN' is not a three-way array")
if (!is.null(rownames(XN))){
y.names <- x.names <- rownames(XN)
} else {
y.names <- x.names <- 1:dim(XN)[1]
}
if (!is.null(colnames(XN))){
var.names <- colnames(XN)
} else {
var.names <- paste("X.", 1:dim(XN)[2], sep = "")
}
if (!is.null(dimnames(XN)[[3]])){
x3d.names <- dimnames(XN)[[3]]
} else {
x3d.names <- paste("Z.", 1:dim(XN)[3], sep = "")
}
if (!is.null(colnames(Y))){
yvar.names <- colnames(Y)
} else {
yvar.names <- paste("Y.", 1:dim(Y)[2], sep = "")
}
if(!center.X) center.X <- rep(0, ncol(XN)*dim(XN)[3])
if(!center.Y) center.Y <- rep(0, ncol(Y))
if(!scale.X) scale.X <- rep(1, ncol(XN)*dim(XN)[3])
if(!scale.Y) scale.Y <- rep(1, ncol(Y))
if(is.null(keepJ) | is.null(keepK) | method!="sNPLS"){
cont_thresholding <- TRUE
message(paste("Using continuous thresholding (", method, ")", sep=""))
} else {
cont_thresholding <- FALSE
message("Using discrete L1-thresholding")
}
if(length(threshold_j) == 1 & ncomp > 1) threshold_j <- rep(threshold_j, ncomp)
if(length(threshold_k) == 1 & ncomp > 1) threshold_k <- rep(threshold_k, ncomp)
# Matrices initialization
U <- Q <- X <- P <- NULL
if(method == "sNPLS"){
WsupraJ <- WsupraK <- Tm <- NULL
} else{
WsupraJ <- matrix(nrow=ncol(XN), ncol=ncomp)
WsupraK <- matrix(nrow=dim(XN)[3], ncol=ncomp)
Tm <- matrix(nrow=nrow(XN), ncol=ncomp)
}
Yorig <- Y
Y <- scale(Y, center = center.Y, scale = scale.Y)
y_center <- attr(Y, "scaled:center")
y_scale <- attr(Y, "scaled:scale")
B <- matrix(0, ncol = ncomp, nrow = ncomp)
Gu <- vector("list", ncomp)
S <- svd(Y)$d
u <- Y[, S == max(S)] #Column with the highest variance
# Unfolding of XN en 2-D
X <- unfold3w(XN)
#Check for zero variance columns and fix them with some noise
if(any(apply(X, 2, sd)==0)){
X[,apply(X, 2, sd)==0] <- apply(X[,apply(X, 2, sd)==0, drop=FALSE], 2, function(x) jitter(x))
}
# Center and scale
Xd <- scale(X, center = center.X, scale = scale.X)
x_center <- attr(Xd, "scaled:center")
x_scale <- attr(Xd, "scaled:scale")
# Main loop for each component
for (f in 1:ncomp) {
if(!cont_thresholding){
nj <- ncol(XN) - keepJ[f]
nk <- dim(XN)[3] - keepK[f]
}
if(method %in% c("sNPLS-VIP", "sNPLS-SR")){
nj <- ncol(XN)
nk <- dim(XN)[3]
wselj <- rep(1, nj)
wselk <- rep(1, nk)
}
it = 1
while (it < max.iteration) {
Zrow <- crossprod(u, Xd)
Z <- matrix(Zrow, nrow = dim(XN)[2], ncol = dim(XN)[3])
svd.z <- svd(Z)
wsupraj <- svd.z$u[, 1]
# L1 penalization for wsupraj
if(method == "sNPLS"){
if(cont_thresholding){
wsupraj <- rel_thresholding(wsupraj, threshold_j[f])
} else {
if (nj != 0) {
wsupraj <- thresholding(wsupraj, nj)
}
}
}
##########
wsuprak <- svd.z$v[, 1]
# L1 penalization for wsuprak
if(method == "sNPLS"){
if(cont_thresholding){
wsuprak <- rel_thresholding(wsuprak, threshold_k[f])
} else {
if (nk != 0) {
wsuprak <- thresholding(wsuprak, nk)
}
}
}
if(method %in% c("sNPLS-VIP", "sNPLS-SR")){
W <- kronecker(wsuprak, wsupraj) * kronecker(wselk, wselj)
tf <- Xd %*% W
qf <- crossprod(Y, tf)/mynorm(crossprod(Y, tf))
uf <- Y %*% qf
Tm[,f] <- tf
Q <- cbind(Q, qf)
WsupraJ[,f] <- wsupraj
WsupraK[,f] <- wsuprak
}
if(method == "sNPLS-VIP"){
#VIPj
SCE <- sum(sum(Tm[,1:f, drop=FALSE] %*% t(Q[,1:f, drop=FALSE])^2))
VIPj <- sqrt(nrow(WsupraJ)*((WsupraJ[,f, drop=FALSE]^2)*SCE)/sum(SCE))
VIPj_01 <- (VIPj-min(VIPj))/(max(VIPj)-min(VIPj))
#VIPk
SCE <- sum(sum(Tm[,1:f, drop=FALSE] %*% t(Q[,1:f, drop=FALSE])^2))
VIPk <- sqrt(nrow(WsupraK)*((WsupraK[,f, drop=FALSE]^2)*SCE)/sum(SCE))
VIPk_01 <- (VIPk-min(VIPk))/(max(VIPk)-min(VIPk))
wselk <- as.numeric(VIPk_01 > threshold_k[f])
wselj <- as.numeric(VIPj_01 > threshold_j[f])
}
if(method == "sNPLS-SR"){
TM <- MASS::ginv(crossprod(Tm[,1:f, drop=FALSE])) %*% t(Tm[,1:f, drop=FALSE])
WkM <- MASS::ginv(crossprod(WsupraK[,1:f, drop=FALSE])) %*% t(WsupraK[,1:f, drop=FALSE])
WjM <- MASS::ginv(crossprod(WsupraJ[,1:f, drop=FALSE])) %*% t(WsupraJ[,1:f, drop=FALSE])
Gu[[f]] <- TM %*% X %*% kronecker(t(WkM), t(WjM))
#SR
P[[f]] = t(as.matrix(Gu[[f]]) %*% t(kronecker(WsupraK[,1:f, drop=FALSE], WsupraJ[,1:f, drop=FALSE])))
Xres <- Xd - Tm[,1:f, drop=FALSE] %*% t(P[[f]])
xpred <- Tm[,1:f, drop=FALSE] %*% t(P[[f]])
SSexp <- xpred^2
SSres <- (Xd-xpred)^2
SSexp_cube <- array(SSexp, dim=c(nrow(SSexp), nj, nk))
SSres_cube <- array(SSres, dim=c(nrow(SSexp), nj, nk))
SR_k <- numeric(nk)
for(k in 1:nk){
SR_k[k] <- sum(SSexp_cube[,,k])/sum(SSres_cube[,,k])
}
SR_k_01 <- (SR_k-min(SR_k))/(max(SR_k)-min(SR_k))
SR_j <- numeric(nj)
for(j in 1:nj){
SR_j[j] <- sum(SSexp_cube[,j,])/sum(SSres_cube[,j,])
}
SR_j_01 <- (SR_j-min(SR_j))/(max(SR_j)-min(SR_j))
wselj <- rep(1, nj)
wselk <- rep(1, nk)
PFcalck <- SR_k_01
wselk <- as.numeric(PFcalck > threshold_k[f])
PFcalcj <- SR_j_01
wselj <- as.numeric(PFcalcj > threshold_j[f])
}
##########
if(method == "sNPLS"){
tf <- Xd %*% kronecker(wsuprak, wsupraj)
qf <- crossprod(Y, tf)/mynorm(crossprod(Y, tf))
uf <- Y %*% qf
}
if (sum((uf - u)^2) < conver) {
if (!silent) {
cat(paste("Component number ", f, "\n"))
cat(paste("Number of iterations: ", it, "\n"))
}
it <- max.iteration
if(method == "sNPLS"){
Tm <- cbind(Tm, tf)
WsupraJ <- cbind(WsupraJ, wsupraj)
WsupraK <- cbind(WsupraK, wsuprak)
bf <- MASS::ginv(crossprod(Tm)) %*% t(Tm) %*% uf
TM <- MASS::ginv(crossprod(Tm)) %*% t(Tm)
Q <- cbind(Q, qf)
} else {
Tm[,f] <- tf
WsupraJ[,f] <- wsupraj*wselj
WsupraK[,f] <- wsuprak*wselk
bf <- MASS::ginv(crossprod(Tm[,1:f, drop=FALSE])) %*% t(Tm[,1:f, drop=FALSE]) %*% uf
}
B[1:length(bf), f] <- bf
U <- cbind(U, uf)
if(method == "sNPLS-VIP"){
TM <- MASS::ginv(crossprod(Tm[,1:f, drop=FALSE])) %*% t(Tm[,1:f, drop=FALSE])
WkM <- MASS::ginv(crossprod(WsupraK[,1:f, drop=FALSE])) %*% t(WsupraK[,1:f, drop=FALSE])
WjM <- MASS::ginv(crossprod(WsupraJ[,1:f, drop=FALSE])) %*% t(WsupraJ[,1:f, drop=FALSE])
Gu[[f]] <- TM %*% X %*% kronecker(t(WkM), t(WjM))
P[[f]] = t(as.matrix(Gu[[f]]) %*% t(kronecker(WsupraK[,1:f, drop=FALSE], WsupraJ[,1:f, drop=FALSE])))
}
if(method == "sNPLS"){
TM <- MASS::ginv(crossprod(Tm)) %*% t(Tm)
WkM <- MASS::ginv(crossprod(WsupraK)) %*% t(WsupraK)
WjM <- MASS::ginv(crossprod(WsupraJ)) %*% t(WsupraJ)
Gu[[f]] <- TM %*% X %*% kronecker(t(WkM), t(WjM))
P[[f]] = t(as.matrix(Gu[[f]]) %*% t(kronecker(WsupraK, WsupraJ)))
}
if(method == "sNPLS"){
Y <- Y - Tm %*% bf %*% t(qf)
} else {
Y <- Y - Tm[,1:f, drop=FALSE] %*% bf %*% t(qf)
}
S <- svd(Y)$d
u <- Y[, S == max(S)]
} else {
u <- uf
it <- it + 1
}
}
}
Yadjsc <- Tm %*% B %*% t(Q)
Yadj <- Yadjsc * y_scale + y_center
SqrdE <- sum((Yorig - Yadj)^2)
rownames(WsupraJ) <- var.names
rownames(WsupraK) <- x3d.names
rownames(Q) <- yvar.names
rownames(Tm) <- rownames(U) <- x.names
colnames(Tm) <- colnames(WsupraJ) <- colnames(WsupraK) <- colnames(B) <-
colnames(U) <- colnames(Q) <- names(Gu) <- names(P) <- paste("Comp.", 1:ncomp)
output <- list(T = Tm, Wj = WsupraJ, Wk = WsupraK, B = B, U = U, Q = Q, P = P,
Gu = Gu, ncomp = ncomp, Xd=Xd, Yorig = Yorig, Yadj = Yadj, SqrdE = SqrdE,
Standarization = list(ScaleX = x_scale, CenterX = x_center,
ScaleY = y_scale, CenterY = y_center),
Method = method)
class(output)<-"sNPLS"
return(output)
}
#' R-matrix from a sNPLS model fit
#'
#' @description Builds the R-matrix from a sNPLS model fit
#' @param x A sNPLS model obtained from \code{sNPLS}
#' @return Returns the R-matrix of the model, needed to compute the coefficients
Rmatrix<-function(x) {
WsupraK <- x$Wk
WsupraJ <- x$Wj
R <- matrix(nrow = dim(x$Wj)[1] * dim(x$Wk)[1], ncol = x$ncomp)
ncomp <- x$ncomp
kroneckers<-sapply(1:x$ncomp, function(x) kronecker(WsupraK[, x], WsupraJ[, x]))
tkroneckers<-apply(kroneckers, 2, function(x) t(x))
R[,1] <- kroneckers[,1]
if(ncomp>1){
for(i in 2:ncomp){
pi <- pi0 <- Matrix::Matrix(diag(dim(R)[1]), sparse=TRUE)
for (j in 1:(i - 1)) {
pi <- Matrix::Matrix(pi %*% pi0 - kroneckers[,j] %*% t(tkroneckers[,j]), sparse=TRUE)
}
w <- kroneckers[, i]
pi <- pi %*% w
R[, i] <- Matrix::as.matrix(pi)
}
}
return(R)
}
#' Unfolding of three-way arrays
#'
#' @description Unfolds a three-way array into a matrix
#' @param x A three-way array
#' @return Returns a matrix with dimensions \code{dim(x)[1] x dim(x)[2]*dim(x([3]))}
unfold3w <- function(x) {
dim(x) <- c(dim(x)[1], dim(x)[2] * dim(x)[3])
return(x)
}
#' Cross-validation for a sNPLS model
#'
#' @description Performs cross-validation for a sNPLS model
#' @param X_npls A three-way array containing the predictors.
#' @param Y_npls A matrix containing the response.
#' @param ncomp A vector with the different number of components to test
#' @param samples Number of samples for performing random search in continuous thresholding
#' @param threshold_j Vector with threshold min and max values on Wj. Scaled between [0, 1)
#' @param threshold_k Vector with threshold min and max values on Wk. Scaled between [0, 1)
#' @param keepJ A vector with the different number of selected variables to test for discrete thresholding
#' @param keepK A vector with the different number of selected 'times' to test for discrete thresholding
#' @param nfold Number of folds for the cross-validation
#' @param parallel Should the computations be performed in parallel? Set up strategy first with \code{future::plan()}
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param metric Select between RMSE or AUC (for 0/1 response)
#' @param ... Further arguments passed to sNPLS
#' @return A list with the best parameters for the model and the CV error
#' @examples
#' \dontrun{
#' X_npls<-array(rpois(7500, 10), dim=c(50, 50, 3))
#'
#' Y_npls<-matrix(2+0.4*X_npls[,5,1]+0.7*X_npls[,10,1]-0.9*X_npls[,15,1]+
#' 0.6*X_npls[,20,1]- 0.5*X_npls[,25,1]+rnorm(50), ncol=1)
#' #Grid search for discrete thresholding
#' cv1<- cv_snpls(X_npls, Y_npls, ncomp=1:2, keepJ = 1:3, keepK = 1:2, parallel = FALSE)
#' #Random search for continuous thresholding
#' cv2<- cv_snpls(X_npls, Y_npls, ncomp=1:2, samples=20, parallel = FALSE)
#' }
#' @importFrom stats runif
#' @export
cv_snpls <- function(X_npls, Y_npls, ncomp = 1:3, samples = 20, threshold_j = c(0, 1),
threshold_k = c(0, 1), keepJ = NULL, keepK = NULL, nfold = 10,
parallel = TRUE, method="sNPLS", metric="RMSE", ...) {
if(parallel) message("Your parallel configuration is ", attr(future::plan(), "class")[3])
if(!method %in% c("sNPLS", "sNPLS-SR", "sNPLS-VIP")) stop("'method' not recognized")
if(length(dim(Y_npls)) == 3) Y_npls <- unfold3w(Y_npls)
top <- ceiling(dim(X_npls)[1]/nfold)
foldid <- sample(rep(1:nfold, top), dim(X_npls)[1], replace = F)
if(is.null(keepJ) | is.null(keepK)){
cont_thresholding <- TRUE
message("Using continuous thresholding")
} else {
cont_thresholding <- FALSE
message("Using discrete thresholding")
}
if(cont_thresholding){
search.grid <- expand.grid(list(ncomp = ncomp,
threshold_j = runif(samples, min = threshold_j[1], max = threshold_j[2]),
threshold_k = runif(samples, min = threshold_k[1], max = threshold_k[2])))
} else {
search.grid <- expand.grid(list(ncomp = ncomp, keepJ = keepJ,
keepK = keepK))
}
SqrdE <- numeric()
applied_fun <- function(y) {
sapply(1:nfold, function(x) {
suppressMessages(tryCatch(do.call(cv_fit, c(list(xtrain = X_npls[x != foldid, , ],
ytrain = Y_npls[x != foldid, , drop = FALSE],
xval = X_npls[x == foldid, , ],
yval = Y_npls[x == foldid, , drop = FALSE],
ncomp = y["ncomp"], method=method, metric=metric),
list(threshold_j=y["threshold_j"])[cont_thresholding],
list(threshold_k=y["threshold_k"])[cont_thresholding],
list(keepJ=rep(y["keepJ"], y["ncomp"]))[!cont_thresholding],
list(keepK=rep(y["keepK"], y["ncomp"]))[!cont_thresholding], ...)),
error=function(x) NA))
})
}
if (parallel) {
cv_res <- future.apply::future_apply(search.grid, 1, applied_fun, future.seed=TRUE)
} else {
cv_res <- pbapply::pbapply(search.grid, 1, applied_fun)
}
cv_mean <- apply(cv_res, 2, function(x) mean(x, na.rm = TRUE))
cv_se <- apply(cv_res, 2, function(x) sd(x, na.rm=TRUE)/sqrt(nfold))
if(metric == "RMSE"){
best_model <- search.grid[which.min(cv_mean), ]
} else{
best_model <- search.grid[which.max(cv_mean), ]
}
output <- list(best_parameters = best_model, cv_mean = cv_mean,
cv_se = cv_se, cv_grid = search.grid)
class(output)<-"cvsNPLS"
return(output)
}
#' Internal function for \code{cv_snpls}
#'
#' @param xtrain A three-way training array
#' @param ytrain A response training matrix
#' @param xval A three-way test array
#' @param yval A response test matrix
#' @param ncomp Number of components for the sNPLS model
#' @param threshold_j Threshold value on Wj. Scaled between [0, 1)
#' @param threshold_k Threshold value on Wk. Scaled between [0, 1)
#' @param keepJ Number of variables to keep for each component, ignored if threshold_j is provided
#' @param keepK Number of 'times' to keep for each component, ignored if threshold_k is provided
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param metric Performance metric (RMSE or AUC)
#' @param ... Further arguments passed to sNPLS
#' @return Returns the CV root mean squared error or AUC
#' @importFrom stats predict
#' @export
cv_fit <- function(xtrain, ytrain, xval, yval, ncomp, threshold_j=NULL, threshold_k=NULL, keepJ=NULL, keepK=NULL, method, metric, ...) {
fit <- sNPLS(XN = xtrain, Y = ytrain, ncomp = ncomp, keepJ=keepJ, keepK=keepK, threshold_j = threshold_j,
threshold_k = threshold_k, silent = TRUE, method=method, ...)
Y_pred <- predict(fit, xval)
if(!metric %in% c("RMSE", "AUC")) stop("Invalid metric for cross-validation")
if(metric == "RMSE"){
CVE <- sqrt(mean((Y_pred - yval)^2))
} else{
CVE <- as.numeric(pROC::roc(yval ~ Y_pred[,1])$auc)
}
return(CVE)
}
#' Plots for sNPLS model fits
#'
#' @description Different plots for sNPLS model fits
#' @param x A sNPLS model fit
#' @param comps Vector with the components to plot. It can be of length \code{ncomp} for types "time" and "variables" and of length 2 otherwise.
#' @param type The type of plot. One of those: "T", "U", "Wj", "Wk", "time" or "variables"
#' @param labels Should rownames be added as labels to the plot?
#' @param group Vector with categorical variable defining groups (optional)
#' @param ... Not used
#' @return A plot of the type specified in the \code{type} parameter
#' @export
plot.sNPLS <- function(x, type = "T", comps = c(1, 2), labels=TRUE, group=NULL, ...) {
if (type == "T")
p<-plot_T(x, comps = comps, labels=labels, group=group)
if (type == "U")
p<-plot_U(x, comps = comps, labels=labels, group=group)
if (type == "Wj")
p<-plot_Wj(x, comps = comps, labels=labels)
if (type == "Wk")
p<-plot_Wk(x, comps = comps, labels=labels)
if (type == "time")
p<-plot_time(x, comps = comps)
if (type == "variables")
p<-plot_variables(x, comps = comps)
p
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @param group Vector with categorical variable defining groups
#' @return A plot of the T matrix of a sNPLS model fit
plot_T <- function(x, comps, labels, group=NULL){
df <- data.frame(x$T)[comps]
if(!is.null(group)) df <- data.frame(df, group=as.factor(group))
names(df)[1:2] <- paste("Comp.", comps, sep="")
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=rownames(df)))
if(!is.null(group)) p1 <- p1 + ggplot2::geom_point(ggplot2::aes(color=group))
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @param group Vector with categorical variable defining groups
#' @return A plot of the U matrix of a sNPLS model fit
plot_U <- function(x, comps, labels, group=NULL){
df <- data.frame(x$U)[comps]
if(!is.null(group)) df <- data.frame(df, group=as.factor(group))
names(df)[1:2] <- paste("Comp.", comps, sep="")
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=rownames(df)))
if(!is.null(group)) p1 <- p1 + ggplot2::geom_point(ggplot2::aes(color=group))
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @return A plot of Wj coefficients
plot_Wj <- function(x, comps, labels){
df <- data.frame(x$Wj)[comps]
names(df) <- paste("Comp.", comps, sep="")
var_names_zero <- rownames(df)
var_names_zero[rowSums(df)==0]<- ""
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=var_names_zero), size=3)
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector of length two with the components to plot
#' @param labels Should rownames be added as labels to the plot?
#' @return A plot of the Wk coefficients
plot_Wk <- function(x, comps, labels){
df <- data.frame(x$Wk)[comps]
names(df) <- paste("Comp.", comps, sep="")
var_names_zero <- rownames(df)
var_names_zero[rowSums(df)==0]<- ""
p1 <- ggplot2::ggplot(df, ggplot2::aes_string(x=names(df)[1], y=names(df)[2])) +
ggplot2::geom_point() + ggplot2::theme_bw() + ggplot2::geom_vline(xintercept = 0,
lty=2) +
ggplot2::geom_hline(yintercept = 0, lty=2) + ggplot2::xlab(names(df)[1]) +
ggplot2::ylab(names(df)[2]) + ggplot2::theme(axis.text=ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
if(labels) p1 <- p1 + ggrepel::geom_text_repel(ggplot2::aes(label=var_names_zero), size=4)
p1
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector with the components to plot
#' @return A plot of Wk coefficients for each component
plot_time <- function(x, comps){
df <- clickR::forge(data.frame(row=1:nrow(x$Wk), x$Wk), affixes=as.character(comps),
var.name="Component")
ggplot2::ggplot(df, ggplot2::aes_string(x="row", y="Comp..", color="Component")) +
ggplot2::geom_line(lwd=1.05) + ggplot2::theme_bw() +
ggplot2::geom_hline(yintercept = 0, alpha=0.2) +
ggplot2::xlab("Time (index)") + ggplot2::ylab("Wk") +
ggplot2::theme(axis.text = ggplot2::element_text(size=12),
axis.title = ggplot2::element_text(size=12,face="bold"))
}
#' Internal function for \code{plot.sNPLS}
#'
#' @param x A sNPLS model fit
#' @param comps A vector with the components to plot
#' @return A plot of Wj coefficients for each component
plot_variables <- function(x, comps){
df <- clickR::forge(data.frame(row=1:nrow(x$Wj), x$Wj), affixes=as.character(comps),
var.name="Component")
ggplot2::ggplot(df, ggplot2::aes_string(x="row", y="Comp..", color="Component")) +
ggplot2::geom_line(lwd=1.05) + ggplot2::theme_bw() +
ggplot2::geom_hline(yintercept = 0, alpha=0.2) +
ggplot2::xlab("Variable (index)") + ggplot2::ylab("Wj") +
ggplot2::theme(axis.text = ggplot2::element_text(size=12),
axis.title=ggplot2::element_text(size=12,face="bold"))
}
#' Predict for sNPLS models
#'
#' @description Predict function for sNPLS models
#' @param object A sNPLS model fit
#' @param newX A three-way array containing the new data
#' @param rescale Should the prediction be rescaled to the original scale?
#' @param ... Further arguments passed to \code{predict}
#' @return A matrix with the predictions
#' @export
predict.sNPLS <- function(object, newX, rescale = TRUE, ...) {
newX <- unfold3w(newX)
# Centrado y escalado
#Xstd <- t((t(newX) - object$Standarization$CenterX)/object$Standarization$ScaleX)
#Xstd <- sweep(sweep(newX, 2, object$Standarization$CenterX), 2, object$Standarization$ScaleX, "/")
Xstd <- scale(newX, center=object$Standarization$CenterX, scale=object$Standarization$ScaleX)
R <- Rmatrix(object)
Bnpls <- R %*% object$B %*% t(object$Q)
Yval <- Xstd %*% Bnpls
if (rescale) {
Yval <- Yval * object$Standarization$ScaleY + object$Standarization$CenterY
}
return(Yval)
}
#' Fitted method for sNPLS models
#'
#' @description Fitted method for sNPLS models
#' @param object A sNPLS model fit
#' @param ... Further arguments passed to \code{fitted}
#' @return Fitted values for the sNPLS model
#' @export
fitted.sNPLS <- function(object, ...){
return(object$Yadj)
}
#' Plot cross validation results for sNPLS objects
#'
#' @description Plot function for visualization of cross validation results for sNPLS models
#' @param x A cv_sNPLS object
#' @param ... Not used
#' @return A facet plot with the results of the cross validation
#' @export
plot.cvsNPLS <- function(x, ...) {
cont_thresholding <- names(x$cv_grid)[2] == "threshold_j"
df_grid <- data.frame(threshold_j=x$cv_grid[,2], threshold_k=x$cv_grid[,3], CVE=x$cv_mean, Ncomp=paste("Ncomp =", x$cv_grid$ncomp, sep=" "))
if(!cont_thresholding) names(df_grid)[c(1, 2)] <- c("KeepJ", "KeepK")
if(cont_thresholding){
ggplot2::ggplot(df_grid, ggplot2::aes_string(x="threshold_j", y="CVE"))+ggplot2::geom_point()+ggplot2::geom_smooth()+ggplot2::facet_grid(cut(threshold_k,10) ~ Ncomp)+
ggplot2::theme_bw()
} else {
ggplot2::ggplot(df_grid, ggplot2::aes_string(x="KeepJ", y="CVE"))+ggplot2::geom_point()+ggplot2::geom_line()+ggplot2::facet_grid(KeepK ~ Ncomp)+
ggplot2::theme_bw()
}
}
#' Coefficients from a sNPLS model
#'
#' @description Extract coefficients from a sNPLS model
#' @param object A sNPLS model fit
#' @param as.matrix Should the coefficients be presented as matrix or vector?
#' @param ... Further arguments passed to \code{coef}
#' @return A matrix (or vector) of coefficients
#' @export
coef.sNPLS <- function(object, as.matrix = FALSE, ...) {
R <- Rmatrix(object)
Bnpls <- R %*% object$B %*% t(object$Q)
colnames(Bnpls) <- paste("Estimate", colnames(Bnpls))
if (as.matrix){
dim(Bnpls) <- c(dim(object$Wj)[1], dim(object$Wk)[1], dim(Bnpls)[2])
rownames(Bnpls) <- rownames(object$Wj)
colnames(Bnpls) <- rownames(object$Wk)
}
return(Bnpls)
}
#' Repeated cross-validation for sNPLS models
#'
#' @description Performs repeated cross-validatiodn and represents results in a plot
#' @param X_npls A three-way array containing the predictors.
#' @param Y_npls A matrix containing the response.
#' @param ncomp A vector with the different number of components to test
#' @param samples Number of samples for performing random search in continuous thresholding
#' @param keepJ A vector with the different number of selected variables to test in discrete thresholding
#' @param keepK A vector with the different number of selected 'times' to test in discrete thresholding
#' @param threshold_j Vector with threshold min and max values on Wj. Scaled between [0, 1)
#' @param threshold_k Vector with threshold min and max values on Wk. Scaled between [0, 1)
#' @param nfold Number of folds for the cross-validation
#' @param times Number of repetitions of the cross-validation
#' @param parallel Should the computations be performed in parallel? Set up strategy first with \code{future::plan()}
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param metric Select between RMSE or AUC (for 0/1 response)
#' @param ... Further arguments passed to cv_snpls
#' @return A density plot with the results of the cross-validation and an (invisible) \code{data.frame} with these results
#' @importFrom stats var
#' @export
repeat_cv <- function(X_npls, Y_npls, ncomp = 1:3, samples=20, keepJ=NULL, keepK=NULL,
threshold_j = c(0, 1), threshold_k = c(0, 1), nfold = 10, times=30,
parallel = TRUE, method="sNPLS", metric="RMSE", ...){
if(!method %in% c("sNPLS", "sNPLS-SR", "sNPLS-VIP")) stop("'method' not recognized")
if(parallel) message("Your parallel configuration is ", attr(future::plan(), "class")[3])
if(is.null(keepJ) | is.null(keepK)){
cont_thresholding <- TRUE
message("Using continuous thresholding")
} else {
cont_thresholding <- FALSE
message("Using discrete thresholding")
}
if(parallel){
rep_cv<-future.apply::future_sapply(1:times, function(x) suppressMessages(cv_snpls(X_npls, Y_npls, ncomp=ncomp, parallel = FALSE, nfold = nfold, samples=samples, keepJ=keepJ, keepK=keepK, threshold_j=threshold_j, threshold_k=threshold_k, method=method, metric=metric, ...)), future.seed=TRUE)
} else {
rep_cv<-pbapply::pbreplicate(times, suppressMessages(cv_snpls(X_npls, Y_npls, ncomp=ncomp, parallel = FALSE, nfold = nfold, samples=samples, keepJ=keepJ, keepK=keepK, threshold_j=threshold_j, threshold_k=threshold_k, method=method, metric=metric, ...)))
}
resdata<-data.frame(ncomp=sapply(rep_cv[1,], function(x) x[[1]]), threshold_j=sapply(rep_cv[1,], function(x) x[[2]]),
threshold_k=sapply(rep_cv[1,], function(x) x[[3]]))
if(!cont_thresholding) names(resdata)[c(2, 3)] <- c("keepJ", "keepK")
class(resdata)<-c("repeatcv", "data.frame")
return(resdata)
}
#' Density plot for repeat_cv results
#'
#' @description Plots a grid of slices from the 3-D kernel denity estimates of the repeat_cv function
#' @param x A repeatcv object
#' @param ... Further arguments passed to plot
#' @return A grid of slices from a 3-D density plot of the results of the repeated cross-validation
#' @importFrom grDevices colorRampPalette
#' @importFrom stats ftable density setNames
#' @export
plot.repeatcv <- function(x, ...){
x.old <- x
x<-x[,sapply(x, function(x) var(x)>0), drop=FALSE]
if(ncol(x) < ncol(x.old)) warning(paste("\n", colnames(x.old)[!colnames(x.old) %in% colnames(x)], "is constant at", x.old[1,colnames(x.old)[!colnames(x.old) %in% colnames(x)]]))
if(ncol(x) == 1){
densities <- density(x[,1])
df_grid <- setNames(data.frame(densities$x, densities$y), c(colnames(x), "density"))
p <- ggplot2::ggplot(x, ggplot2::aes_string(x=colnames(x)))+ggplot2::geom_density(color="gray", fill="gray", alpha=0.3)+ggplot2::theme_classic()
} else{
H.pi <- ks::Hpi(x)
fhat <- ks::kde(x, H=H.pi, compute.cont=TRUE, gridsize = rep(151, ncol(x)))
if(ncol(x) == 3){
ncomp_values <- sapply(sort(unique(fhat$x[,1])), function(x) which.min(abs(fhat$eval.points[[1]]-x)))
positions <- as.data.frame(fhat$x)
positions$Ncomp <- factor(positions$ncomp)
df_grid <- setNames(expand.grid(fhat$eval.points[[2]], fhat$eval.points[[3]]), names(positions)[c(2,3)])
combl <- nrow(df_grid)
df_grid <- df_grid[rep(1:nrow(df_grid), length(ncomp_values)),]
df_grid$density <- unlist(lapply(ncomp_values, function(x) as.numeric(matrix(fhat$estimate[x,,], ncol=1))))
df_grid$Ncomp <- factor(rep(sort(unique(positions$ncomp)), each=combl))
p <- ggplot2::ggplot(df_grid, ggplot2::aes_string(names(df_grid)[1], names(df_grid)[2], fill="density"))+ggplot2::geom_raster()+
ggplot2::scale_fill_gradientn(colours =colorRampPalette(c("white", "blue", "red"))(10))+ggplot2::theme_classic()+
ggplot2::geom_count(inherit.aes = FALSE, ggplot2::aes_string(x=names(df_grid)[1], y=names(df_grid)[2]), data=positions) +ggplot2::facet_grid(~Ncomp)
if(names(df_grid)[1] == "threshold_j"){
p <- p + ggplot2::scale_x_continuous(limits=c(0, 1)) + ggplot2::scale_y_continuous(limits=c(0, 1))
} else {
p <- p + ggplot2::scale_x_continuous(breaks=if(round(diff(range(df_grid$keepJ)))<=10) round(max(0, min(df_grid$keepJ)):max(df_grid$keepJ)) else round(seq(max(0, min(df_grid$keepJ)), max(df_grid$keepJ), by= ceiling(max(df_grid$keepJ)/20)*2)))+
ggplot2::scale_y_continuous(breaks=if(round(diff(range(df_grid$keepK)))<=10) round(max(0, min(df_grid$keepK)):max(df_grid$keepK)) else round(seq(max(0, min(df_grid$keepK)), max(df_grid$keepK), by= ceiling(max(df_grid$keepK)/20)*2)))+
ggplot2::scale_size_area(breaks=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))],
labels=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))])
}
} else {
positions <- as.data.frame(fhat$x)
df_grid <- expand.grid(V1=fhat$eval.points[[1]], V2=fhat$eval.points[[2]])
names(df_grid)<-colnames(positions)
df_grid$density <- as.numeric(matrix(fhat$estimate, ncol=1))
p <- ggplot2::ggplot(df_grid, ggplot2::aes_string(colnames(df_grid)[1], colnames(df_grid)[2], fill="density"))+ggplot2::geom_raster()+
ggplot2::scale_fill_gradientn(colours =colorRampPalette(c("white", "blue", "red"))(10))+ggplot2::theme_classic()+
ggplot2::geom_count(inherit.aes = FALSE, ggplot2::aes_string(x=colnames(df_grid)[1], y=colnames(df_grid)[2]), data=positions)
if("threshold_j" %in% names(df_grid) | "threshold_k" %in% names(df_grid)){
p <- p + ggplot2::scale_x_continuous(limits=c(0, 1)) + ggplot2::scale_y_continuous(limits=c(0, 1))
} else {
p <- p + ggplot2::scale_x_continuous(breaks=if(round(diff(range(df_grid[,1])))<=10) round(max(0, min(df_grid[,1])):max(df_grid[,1])) else round(seq(max(0, min(df_grid[,1])), max(df_grid[,1]), by= ceiling(max(df_grid[,1])/20)*2)))+
ggplot2::scale_y_continuous(breaks=if(round(diff(range(df_grid[,2])))<=10) round(max(0, min(df_grid[,2])):max(df_grid[,2])) else round(seq(max(0, min(df_grid[,2])), max(df_grid[,2]), by= ceiling(max(df_grid[,2])/20)*2)))+
ggplot2::scale_size_continuous(breaks=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))],
labels=if(length(sort(unique(as.numeric(ftable(positions))))[-1])<=7) sort(unique(as.numeric(ftable(positions))))[-1] else (1:max(as.numeric(ftable(positions))))[round(seq(1, max(as.numeric(ftable(positions))), length.out = 7))])
}
}
}
print(p)
data.frame(x.old[1, !colnames(x.old) %in% colnames(x), drop=FALSE], df_grid[which.max(df_grid$density),])
}
#' Summary for sNPLS models
#'
#' @description Summary of a sNPLS model fit
#' @param object A sNPLS object
#' @param ... Further arguments passed to summary.default
#' @return A summary inclunding number of components, squared error and coefficients of the fitted model
#' @importFrom stats coef
#' @export
summary.sNPLS <- function(object, ...){
cat(object$Method, "model with", object$ncomp, "components and squared error of", round(object$SqrdE,3), "\n", "\n")
cat("Coefficients: \n")
round(coef(object, as.matrix=TRUE), 3)
}
#' AUC for sNPLS-DA model
#'
#' @description AUC for a sNPLS-DA model
#' @param object A sNPLS object
#' @return The area under the ROC curve for the model
#' @export
auroc <- function(object){
as.numeric(pROC::roc(object$Yorig[,1] ~ object$Yadj[,1])$auc)
}
#' Compute Selectivity Ratio for a sNPLS model
#'
#' @description Estimates Selectivity Ratio for the different components of a sNPLS model fit
#' @param model A sNPLS model
#' @return A list of data.frames, each of them including the computed Selectivity Ratios for each variable
#' @export
SR <- function(model){
output <- lapply(1:model$ncomp, function(f){
Xres <- model$Xd - model$T[,1:f, drop=FALSE] %*% t(model$P[[f]])
Xpred <- model$T[,1:f, drop=FALSE] %*% t(model$P[[f]])
SSexp <- Xpred^2
SSres <- (model$Xd-Xpred)^2
SSexp_cube <- array(SSexp, dim=c(nrow(SSexp), nrow(model$Wj), nrow(model$Wk)))
SSres_cube <- array(SSres, dim=c(nrow(SSexp), nrow(model$Wj), nrow(model$Wk)))
SR_k <- sapply(1:nrow(model$Wk), function(x) sum(SSexp_cube[,,x])/sum(SSres_cube[,,x]))
SR_j <- sapply(1:nrow(model$Wj), function(x) sum(SSexp_cube[,x,])/sum(SSres_cube[,x,]))
list(SR_k=round(SR_k,3),
SR_j=round(SR_j,3))
})
SR_j <- do.call("cbind", sapply(output, function(x) x[2]))
SR_k <- do.call("cbind", sapply(output, function(x) x[1]))
rownames(SR_j) <- rownames(model$Wj)
rownames(SR_k) <- rownames(model$Wk)
colnames(SR_j) <- colnames(SR_k) <- paste("Component ", 1:model$ncomp, sep="")
list(SR_j=SR_j, SR_k=SR_k)
}
#' Genetic Algorithm for selection of hyperparameter values
#'
#' @description Runs a genetic algorithm to select the best combination of hyperparameter values
#' @param X A three-way array containing the predictors.
#' @param Y A matrix containing the response.
#' @param ncomp A vector with the minimum and maximum number of components to assess
#' @param threshold_j Vector with threshold min and max values on Wj. Scaled between [0, 1)
#' @param threshold_k Vector with threshold min and max values on Wk. Scaled between [0, 1)
#' @param maxiter Maximum number of iterations (generations) of the genetic algorithm
#' @param popSize Population size (see \code{GA::ga()} documentation)
#' @param parallel Should the computations be performed in parallel? (see \code{GA::ga()} documentation)
#' @param replicates Number of replicates for the cross-validation performed in the fitness function of the genetic algoritm
#' @param metric Select between RMSE or AUC (for 0/1 response)
#' @param method Select between sNPLS, sNPLS-SR or sNPLS-VIP
#' @param ... Further arguments passed to \code{GA::ga()}
#' @return A summary of the genetic algorithm results
#' @importFrom GA ga
#' @importFrom pbapply pblapply
#' @export
ga_snpls <- function(X, Y, ncomp=c(1, 3), threshold_j=c(0, 1), threshold_k=c(0, 1), maxiter=20,
popSize=50, parallel=TRUE, replicates=10, metric="RMSE", method="sNPLS", ...){
fitness_function <- function(x) {
# Calculate the performance of the model with the hyperparameters
performance <- mean(pbapply::pbreplicate(replicates, suppressMessages(cv_snpls(X, Y, ncomp=round(x[1]), threshold_j = rep(x[2], 2), threshold_k = rep(x[3], 2), samples = 1, metric=metric, method = "sNPLS")$cv_mean)))
if(metric == "AUC") performance else -performance
}
res <- as.data.frame(GA::ga(type = "real-valued",
fitness = fitness_function,
lower = c(ncomp=ncomp[1]-0.5, threshold_j=threshold_j[1], threshold_k=threshold_k[1]),
upper = c(ncomp=ncomp[2]+0.5, threshold_j=threshold_j[2], threshold_k=threshold_k[2]),
maxiter = maxiter,
popSize = popSize,
parallel=parallel, ...)@summary)
if(metric == "RMSE"){
res <- res*-1
names(res) <- c("min", "mean", "q1", "median", "q3", "max")
}
res$iteration <- 1:nrow(res)
res
}
|
#' Time Span Code Sheet
#'
#' Generates a time span coding sheet and coding format sheet.
#'
#' @param codes List of codes.
#' @param grouping.var The grouping variables. Also takes a single grouping
#' variable or a list of 1 or more grouping variables.
#' @param start A character string in the form of "00:00" indicating start time
#' (default is ":00").
#' @param end A character string in the form of "00:00" indicating end time.
#' @param file A connection, or a character string naming the file to print to
#' (.txt or .doc is recommended).
#' @param coding logical. If \code{TRUE} a coding list is provided with the
#' time span coding sheet. \code{coding} is ignored if \code{end = NULL}.
#' @param print logical. If \code{TRUE} the time spans are printed to the
#' console.
#' @references Miles, M. B. & Huberman, A. M. (1994). An expanded sourcebook:
#' Qualitative data analysis. 2nd ed. Thousand Oaks, CA: SAGE Publications.
#' @keywords coding
#' @seealso
#' \code{\link[qdap]{cm_range.temp}},
#' @export
#' @importFrom qdapTools pad
#' @examples
#' \dontrun{
#' ## cm_time.temp(qcv(AA, BB, CC), ":30", "7:40", file = "foo.txt")
#' ## library(reports); delete("foo.txt")
#' cm_time.temp(qcv(AA, BB, CC), ":30", "7:40")
#'
#' x <- list(
#' transcript_time_span = qcv(terms="00:00 - 1:12:00"),
#' A = qcv(terms="2.40:3.00, 5.01, 6.52:7.00, 9.00"),
#' B = qcv(terms="2.40, 3.01:3.02, 5.01, 6.52:7.00, 9.00, 1.12.00:1.19.01"),
#' C = qcv(terms="2.40:3.00, 5.01, 6.52:7.00, 9.00, 17.01")
#' )
#' cm_time2long(x)
#' cm_time.temp(qcv(AA, BB, CC))
#' }
cm_time.temp <-
function(codes, grouping.var = NULL, start = ":00", end = NULL, file=NULL,
coding = FALSE, print = TRUE) {
if (Sys.info()["sysname"] != "Windows") {
writeClipboard <- NULL
}
if (!is.null(end)) {
start <- hms2ms(start)
end <- hms2ms(end)
}
if (!is.null(grouping.var)) {
if (is.list(grouping.var)) {
m <- unlist(as.character(substitute(grouping.var))[-1])
G <- sapply(strsplit(m, "$", fixed=TRUE), function(x) {
x[length(x)]
}
)
} else {
G <- as.character(substitute(grouping.var))
G <- G[length(G)]
}
lvs <- lapply(grouping.var, unique)
if (missing(codes)) {
codes <- NULL
}
codes <- c(unlist(lapply(seq_along(G), function(i) {
paste(G[i], lvs[[i]], sep="_")
})), codes)
}
if (!is.null(end)) {
wid <- options()$width
wdth <- options()[["width"]]
on.exit(options(width = wdth))
options(width=1000)
if (!missing(codes)) {
x1 <- matrix(c("list(",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),",
paste0(" ", codes[1:(length(codes)-1)], " = qcv(terms=\"\"),"),
paste0(" ", codes[length(codes)], " = qcv(terms=\"\")"),
")"), ncol = 1)
} else {
x1 <- NULL
}
st <- unlist(strsplit(start, ":"))
en <- as.numeric(unlist(strsplit(end, ":")))
st[1] <- ifelse(st[1]=="", "0", st[1])
st <- as.numeric(st)
x <- (en[1] - st[1]) + 1
z <- matrix(rep(0:59, x), nrow = x, byrow = TRUE)
rownames(z) <- c(paste0("[", st[1]:en[1], "]"))
colnames(z) <- rep("", ncol(z))
if (st[2] > 0) {
z[1, 0:(st[2])] <- NA
}
if (en[2] < 59) {
z[x, (en[2] + 2):60] <- NA
}
zz <- matrix(capture.output(print(z, na.print=""))[-1], ncol =1)
if (print){
print(z, na.print=""); message("\n")
}
if (coding) {
message(paste0("list(\n",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),\n",
paste0(" ", paste0(paste(codes,
collapse = " = qcv(terms=\"\"),\n "), " = qcv(terms=\"\")")), "\n)"))
}
dimnames(zz) <- list(c(rep("", x)), c(""))
if (Sys.info()["sysname"] == "Windows") {
writeClipboard(noquote(rbind(zz, "", "", x1)), format = 1)
}
if (Sys.info()["sysname"] == "Darwin") {
j <- pipe("pbcopy", "w")
writeLines(noquote(rbind(zz, "", "", x1)), con = j)
close(j)
}
if (!is.null(file)) {
v <- paste0(zz, "\n")
cat(v[1], file=file)
lapply(2:x, function(i) cat(v[i], file=file, append = TRUE))
if (coding) {
cat(paste0("\nlist(\n",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),\n",
paste0(" ", paste0(paste(codes,
collapse = " = qcv(terms=\"\"),\n "), " = qcv(terms=\"\")")),
"\n)\n"), file = file, append = TRUE)
}
}
options(width=wid)
} else {
zz <- x1 <- matrix(c("list(",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),",
paste0(" ", codes[1:(length(codes)-1)], " = qcv(terms=\"\"),"),
paste0(" ", codes[length(codes)], " = qcv(terms=\"\")"),
")"), ncol = 1)
dimnames(zz) <- list(c(rep("", nrow(zz))), c(""))
print(noquote(zz))
if (Sys.info()["sysname"] == "Windows") {
writeClipboard(noquote(x1), format = 1)
}
if (Sys.info()["sysname"] == "Darwin") {
j <- pipe("pbcopy", "w")
writeLines(noquote(x1), con = j)
close(j)
}
if (!is.null(file)) {
cat(paste0("list(\n",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),\n",
paste0(" ", paste0(paste(codes,
collapse = " = qcv(terms=\"\"),\n "), " = qcv(terms=\"\")")),
"\n)\n"), file = file, append = TRUE)
}
}
}
hms2ms <-
function(x) {
hms <- as.character(x)
op <- FALSE
if (length(hms) == 1) {
hms <- c(hms, "00:00:00")
op <- TRUE
}
spl <- strsplit(hms, ":")
spl2 <- lapply(spl, function(x) {
if (length(x) == 1) {
if (x[1] == "") {
stop("An element is blank")
}
x <- c(rep("00", 2), x[1])
}
if (length(x) == 2) {
if (x[1] == "") {
x <- c(rep("00", 2), x[2])
} else {
x <- c(rep("00", 1), x[1:2])
}
}
if (x[1] == "") {
x <- c(rep("00", 1), x[1:2])
}
x
})
DF <- sapply(data.frame(do.call(rbind, spl2)), function(x){
as.numeric(as.character(x))
})
cmb <- apply(cbind(DF[, 1]*60 + DF[, 2], DF[, 3]), 2, pad, 2, sort=FALSE)
out <- paste2(cmb, sep=":")
if (op) {
out <- out[1]
}
out
}
| /R/cm_time.temp.R | no_license | jaredlander/qdaplite | R | false | false | 7,281 | r | #' Time Span Code Sheet
#'
#' Generates a time span coding sheet and coding format sheet.
#'
#' @param codes List of codes.
#' @param grouping.var The grouping variables. Also takes a single grouping
#' variable or a list of 1 or more grouping variables.
#' @param start A character string in the form of "00:00" indicating start time
#' (default is ":00").
#' @param end A character string in the form of "00:00" indicating end time.
#' @param file A connection, or a character string naming the file to print to
#' (.txt or .doc is recommended).
#' @param coding logical. If \code{TRUE} a coding list is provided with the
#' time span coding sheet. \code{coding} is ignored if \code{end = NULL}.
#' @param print logical. If \code{TRUE} the time spans are printed to the
#' console.
#' @references Miles, M. B. & Huberman, A. M. (1994). An expanded sourcebook:
#' Qualitative data analysis. 2nd ed. Thousand Oaks, CA: SAGE Publications.
#' @keywords coding
#' @seealso
#' \code{\link[qdap]{cm_range.temp}},
#' @export
#' @importFrom qdapTools pad
#' @examples
#' \dontrun{
#' ## cm_time.temp(qcv(AA, BB, CC), ":30", "7:40", file = "foo.txt")
#' ## library(reports); delete("foo.txt")
#' cm_time.temp(qcv(AA, BB, CC), ":30", "7:40")
#'
#' x <- list(
#' transcript_time_span = qcv(terms="00:00 - 1:12:00"),
#' A = qcv(terms="2.40:3.00, 5.01, 6.52:7.00, 9.00"),
#' B = qcv(terms="2.40, 3.01:3.02, 5.01, 6.52:7.00, 9.00, 1.12.00:1.19.01"),
#' C = qcv(terms="2.40:3.00, 5.01, 6.52:7.00, 9.00, 17.01")
#' )
#' cm_time2long(x)
#' cm_time.temp(qcv(AA, BB, CC))
#' }
cm_time.temp <-
function(codes, grouping.var = NULL, start = ":00", end = NULL, file=NULL,
coding = FALSE, print = TRUE) {
if (Sys.info()["sysname"] != "Windows") {
writeClipboard <- NULL
}
if (!is.null(end)) {
start <- hms2ms(start)
end <- hms2ms(end)
}
if (!is.null(grouping.var)) {
if (is.list(grouping.var)) {
m <- unlist(as.character(substitute(grouping.var))[-1])
G <- sapply(strsplit(m, "$", fixed=TRUE), function(x) {
x[length(x)]
}
)
} else {
G <- as.character(substitute(grouping.var))
G <- G[length(G)]
}
lvs <- lapply(grouping.var, unique)
if (missing(codes)) {
codes <- NULL
}
codes <- c(unlist(lapply(seq_along(G), function(i) {
paste(G[i], lvs[[i]], sep="_")
})), codes)
}
if (!is.null(end)) {
wid <- options()$width
wdth <- options()[["width"]]
on.exit(options(width = wdth))
options(width=1000)
if (!missing(codes)) {
x1 <- matrix(c("list(",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),",
paste0(" ", codes[1:(length(codes)-1)], " = qcv(terms=\"\"),"),
paste0(" ", codes[length(codes)], " = qcv(terms=\"\")"),
")"), ncol = 1)
} else {
x1 <- NULL
}
st <- unlist(strsplit(start, ":"))
en <- as.numeric(unlist(strsplit(end, ":")))
st[1] <- ifelse(st[1]=="", "0", st[1])
st <- as.numeric(st)
x <- (en[1] - st[1]) + 1
z <- matrix(rep(0:59, x), nrow = x, byrow = TRUE)
rownames(z) <- c(paste0("[", st[1]:en[1], "]"))
colnames(z) <- rep("", ncol(z))
if (st[2] > 0) {
z[1, 0:(st[2])] <- NA
}
if (en[2] < 59) {
z[x, (en[2] + 2):60] <- NA
}
zz <- matrix(capture.output(print(z, na.print=""))[-1], ncol =1)
if (print){
print(z, na.print=""); message("\n")
}
if (coding) {
message(paste0("list(\n",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),\n",
paste0(" ", paste0(paste(codes,
collapse = " = qcv(terms=\"\"),\n "), " = qcv(terms=\"\")")), "\n)"))
}
dimnames(zz) <- list(c(rep("", x)), c(""))
if (Sys.info()["sysname"] == "Windows") {
writeClipboard(noquote(rbind(zz, "", "", x1)), format = 1)
}
if (Sys.info()["sysname"] == "Darwin") {
j <- pipe("pbcopy", "w")
writeLines(noquote(rbind(zz, "", "", x1)), con = j)
close(j)
}
if (!is.null(file)) {
v <- paste0(zz, "\n")
cat(v[1], file=file)
lapply(2:x, function(i) cat(v[i], file=file, append = TRUE))
if (coding) {
cat(paste0("\nlist(\n",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),\n",
paste0(" ", paste0(paste(codes,
collapse = " = qcv(terms=\"\"),\n "), " = qcv(terms=\"\")")),
"\n)\n"), file = file, append = TRUE)
}
}
options(width=wid)
} else {
zz <- x1 <- matrix(c("list(",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),",
paste0(" ", codes[1:(length(codes)-1)], " = qcv(terms=\"\"),"),
paste0(" ", codes[length(codes)], " = qcv(terms=\"\")"),
")"), ncol = 1)
dimnames(zz) <- list(c(rep("", nrow(zz))), c(""))
print(noquote(zz))
if (Sys.info()["sysname"] == "Windows") {
writeClipboard(noquote(x1), format = 1)
}
if (Sys.info()["sysname"] == "Darwin") {
j <- pipe("pbcopy", "w")
writeLines(noquote(x1), con = j)
close(j)
}
if (!is.null(file)) {
cat(paste0("list(\n",
" transcript_time_span = qcv(terms=\"00:00 - 00:00\"),\n",
paste0(" ", paste0(paste(codes,
collapse = " = qcv(terms=\"\"),\n "), " = qcv(terms=\"\")")),
"\n)\n"), file = file, append = TRUE)
}
}
}
hms2ms <-
function(x) {
hms <- as.character(x)
op <- FALSE
if (length(hms) == 1) {
hms <- c(hms, "00:00:00")
op <- TRUE
}
spl <- strsplit(hms, ":")
spl2 <- lapply(spl, function(x) {
if (length(x) == 1) {
if (x[1] == "") {
stop("An element is blank")
}
x <- c(rep("00", 2), x[1])
}
if (length(x) == 2) {
if (x[1] == "") {
x <- c(rep("00", 2), x[2])
} else {
x <- c(rep("00", 1), x[1:2])
}
}
if (x[1] == "") {
x <- c(rep("00", 1), x[1:2])
}
x
})
DF <- sapply(data.frame(do.call(rbind, spl2)), function(x){
as.numeric(as.character(x))
})
cmb <- apply(cbind(DF[, 1]*60 + DF[, 2], DF[, 3]), 2, pad, 2, sort=FALSE)
out <- paste2(cmb, sep=":")
if (op) {
out <- out[1]
}
out
}
|
setClass("clickhouse_driver",
contains = "DBIDriver"
)
setClass("clickhouse_connection",
contains = "DBIConnection",
slots = list(
url = "character",
user = "character",
password = "character",
database = "character"
)
)
setClass("clickhouse_result",
contains = "DBIResult",
slots = list(
sql = "character",
env = "environment",
conn = "clickhouse_connection"
)
)
setMethod("dbGetInfo", "clickhouse_connection", def=function(dbObj, ...) {
envdata <- dbGetQuery(dbObj, "SELECT version() as version, uptime() as uptime,
currentDatabase() as database")
ll$name <- "clickhouse_connection"
ll$db.version <- envdata$version
ll$uptime <- envdata$uptime
ll$url <- dbObj@url
ll$dbname <- envdata$database
ll$username <- NA
ll$host <- NA
ll$port <- NA
ll
})
setMethod("dbIsValid", "clickhouse_driver", function(dbObj, ...) {
TRUE
})
setMethod("dbUnloadDriver", "clickhouse_driver", function(drv, ...) {
invisible(TRUE)
})
setMethod("dbIsValid", "clickhouse_connection", function(dbObj, ...) {
tryCatch({
dbGetQuery(dbObj, "select 1")
TRUE
}, error = function(e) {
print(e)
FALSE
})
})
clickhouse <- function() {
new("clickhouse_driver")
}
setMethod("dbConnect", "clickhouse_driver",
function(drv, host="localhost", port=8123L, user="default", password="", ssl = FALSE, database = "default", ...) {
schema <- if (ssl) {
"https"
} else {
"http"
}
con <- new("clickhouse_connection",
url = paste0(schema, "://", host, ":", port, "/"),
user = user,
password = password,
database = database
)
stopifnot(dbIsValid(con))
con
}
)
setMethod("dbListTables", "clickhouse_connection", function(conn, ...) {
as.character(dbGetQuery(conn, "SHOW TABLES")[[1]])
})
setMethod("dbExistsTable", "clickhouse_connection", function(conn, name, ...) {
as.logical(name %in% dbListTables(conn))
})
setMethod("dbReadTable", "clickhouse_connection", function(conn, name, ...) {
dbGetQuery(conn, paste0("SELECT * FROM ", name))
})
setMethod("dbRemoveTable", "clickhouse_connection", function(conn, name, ...) {
dbExecute(conn, paste0("DROP TABLE ", name))
invisible(TRUE)
})
setMethod("dbSendQuery", "clickhouse_connection", function(conn, statement, use = c("memory", "temp"), ...) {
# with use = "temp" we try to avoid exception with long vectors conversion in rawToChar
# <simpleError in rawToChar(req$content): long vectors are not supported yet: raw.c:68>
use <- match.arg(use)
q <- sub("[; ]*;\\s*$", "", statement, ignore.case=T, perl=T)
has_resultset <- grepl("^\\s*(SELECT|SHOW)\\s+", statement, perl=T, ignore.case=T)
if (has_resultset) {
if ( grepl(".*FORMAT\\s+\\w+\\s*$", statement, perl=T, ignore.case=T)) {
stop("Can't have FORMAT keyword in queries, query ", statement)
}
q <- paste0(q ," FORMAT TabSeparatedWithNames")
}
h <- curl::new_handle()
#let's ignore peer verification for now
curl::handle_setopt(h, copypostfields = q, userpwd = paste0(conn@user, ":", conn@password), httpauth = 1L, ssl_verifypeer = FALSE)
url <- paste0(conn@url, "?database=", URLencode(conn@database))
if (use == "memory") {
req <- curl::curl_fetch_memory(url, handle = h)
} else {
tmp <- tempfile()
req <- curl::curl_fetch_disk(url, tmp, handle = h)
}
if (req$status_code != 200) {
if (use == "memory") {
stop(rawToChar(req$content))
} else {
stop(readLines(tmp))
}
}
dataenv <- new.env(parent = emptyenv())
if (has_resultset) {
# try to avoid problems when select just one column that can contain ""
# without "blank.lines.skip" we'll get warning:
# Stopped reading at empty line ... but text exists afterwards (discarded): ...
# and not all rows will be read
if (use == "memory") {
dataenv$data <- data.table::fread(rawToChar(req$content), sep="\t", header=TRUE,
showProgress=FALSE,
blank.lines.skip = TRUE)
} else {
dataenv$data <- data.table::fread(tmp, sep = "\t", header = TRUE,
showProgress = FALSE,
blank.lines.skip = TRUE)
unlink(tmp)
}
}
dataenv$success <- TRUE
dataenv$delivered <- -1
dataenv$open <- TRUE
dataenv$rows <- nrow(dataenv$data)
new("clickhouse_result",
sql = statement,
env = dataenv,
conn = conn
)
})
setMethod("dbWriteTable", signature(conn = "clickhouse_connection", name = "character", value = "ANY"), definition = function(conn, name, value, overwrite=FALSE,
append=FALSE, engine="TinyLog", ...) {
if (is.vector(value) && !is.list(value)) value <- data.frame(x = value, stringsAsFactors = F)
if (length(value) < 1) stop("value must have at least one column")
if (is.null(names(value))) names(value) <- paste("V", 1:length(value), sep='')
if (length(value[[1]])>0) {
if (!is.data.frame(value)) value <- as.data.frame(value, row.names=1:length(value[[1]]) , stringsAsFactors=F)
} else {
if (!is.data.frame(value)) value <- as.data.frame(value, stringsAsFactors=F)
}
if (overwrite && append) {
stop("Setting both overwrite and append to TRUE makes no sense.")
}
qname <- name
if (dbExistsTable(conn, qname)) {
if (overwrite) dbRemoveTable(conn, qname)
if (!overwrite && !append) stop("Table ", qname, " already exists. Set overwrite=TRUE if you want
to remove the existing table. Set append=TRUE if you would like to add the new data to the
existing table.")
}
if (!dbExistsTable(conn, qname)) {
fts <- sapply(value, dbDataType, dbObj=conn)
fdef <- paste(names(value), fts, collapse=', ')
ct <- paste0("CREATE TABLE ", qname, " (", fdef, ") ENGINE=", engine)
dbExecute(conn, ct)
}
if (length(value[[1]])) {
classes <- unlist(lapply(value, function(v){
class(v)[[1]]
}))
for (c in names(classes[classes=="character"])) {
value[[c]] <- enc2utf8(value[[c]])
}
for (c in names(classes[classes=="factor"])) {
levels(value[[c]]) <- enc2utf8(levels(value[[c]]))
}
write.table(value, textConnection("value_str", open="w"), sep="\t", row.names=F, col.names=F, quote=F)
value_str2 <- paste0(get("value_str"), collapse="\n")
h <- curl::new_handle()
curl::handle_setopt(h, copypostfields = value_str2, userpwd = paste0(conn@user, ":", conn@password), httpauth = 1L, ssl_verifypeer = FALSE)
req <- curl::curl_fetch_memory(paste0(conn@url, "?database=", URLencode(conn@database), "&query=", URLencode(paste0("INSERT INTO ", qname, " FORMAT TabSeparated"))), handle = h)
if (req$status_code != 200) {
stop("Error writing data to table ", rawToChar(req$content))
}
}
return(invisible(TRUE))
})
setMethod("dbDataType", signature(dbObj="clickhouse_connection", obj = "ANY"), definition = function(dbObj,
obj, ...) {
if (is.logical(obj)) "UInt8"
else if (is.integer(obj)) "Int32"
else if (is.numeric(obj)) "Float64"
else "String"
}, valueClass = "character")
setMethod("dbBegin", "clickhouse_connection", definition = function(conn, ...) {
stop("Transactions are not supported.")
})
setMethod("dbCommit", "clickhouse_connection", definition = function(conn, ...) {
stop("Transactions are not supported.")
})
setMethod("dbRollback", "clickhouse_connection", definition = function(conn, ...) {
stop("Transactions are not supported.")
})
setMethod("dbDisconnect", "clickhouse_connection", function(conn, ...) {
invisible(TRUE)
})
setMethod("fetch", signature(res = "clickhouse_result", n = "numeric"), definition = function(res, n, ...) {
if (!dbIsValid(res) || dbHasCompleted(res)) {
stop("Cannot fetch results from exhausted, closed or invalid response.")
}
if (n == 0) {
stop("Fetch 0 rows? Really?")
}
if (res@env$delivered < 0) {
res@env$delivered <- 0
}
if (res@env$delivered >= res@env$rows) {
return(res@env$data[F,, drop=F])
}
if (n > -1) {
n <- min(n, res@env$rows - res@env$delivered)
res@env$delivered <- res@env$delivered + n
return(res@env$data[(res@env$delivered - n + 1):(res@env$delivered),, drop=F])
}
else {
start <- res@env$delivered + 1
res@env$delivered <- res@env$rows
return(res@env$data[start:res@env$rows,, drop=F])
}
})
setMethod("dbGetRowsAffected", "clickhouse_result", definition = function(res, ...) {
as.numeric(NA)
})
setMethod("dbClearResult", "clickhouse_result", definition = function(res, ...) {
res@env$open <- FALSE
invisible(TRUE)
})
setMethod("dbHasCompleted", "clickhouse_result", definition = function(res, ...) {
res@env$delivered >= res@env$rows
})
setMethod("dbIsValid", "clickhouse_result", definition = function(dbObj, ...) {
dbObj@env$success && dbObj@env$open
})
| /R/clickhouse.R | no_license | ssoudan/clickhouse-r | R | false | false | 8,824 | r | setClass("clickhouse_driver",
contains = "DBIDriver"
)
setClass("clickhouse_connection",
contains = "DBIConnection",
slots = list(
url = "character",
user = "character",
password = "character",
database = "character"
)
)
setClass("clickhouse_result",
contains = "DBIResult",
slots = list(
sql = "character",
env = "environment",
conn = "clickhouse_connection"
)
)
setMethod("dbGetInfo", "clickhouse_connection", def=function(dbObj, ...) {
envdata <- dbGetQuery(dbObj, "SELECT version() as version, uptime() as uptime,
currentDatabase() as database")
ll$name <- "clickhouse_connection"
ll$db.version <- envdata$version
ll$uptime <- envdata$uptime
ll$url <- dbObj@url
ll$dbname <- envdata$database
ll$username <- NA
ll$host <- NA
ll$port <- NA
ll
})
setMethod("dbIsValid", "clickhouse_driver", function(dbObj, ...) {
TRUE
})
setMethod("dbUnloadDriver", "clickhouse_driver", function(drv, ...) {
invisible(TRUE)
})
setMethod("dbIsValid", "clickhouse_connection", function(dbObj, ...) {
tryCatch({
dbGetQuery(dbObj, "select 1")
TRUE
}, error = function(e) {
print(e)
FALSE
})
})
clickhouse <- function() {
new("clickhouse_driver")
}
setMethod("dbConnect", "clickhouse_driver",
function(drv, host="localhost", port=8123L, user="default", password="", ssl = FALSE, database = "default", ...) {
schema <- if (ssl) {
"https"
} else {
"http"
}
con <- new("clickhouse_connection",
url = paste0(schema, "://", host, ":", port, "/"),
user = user,
password = password,
database = database
)
stopifnot(dbIsValid(con))
con
}
)
setMethod("dbListTables", "clickhouse_connection", function(conn, ...) {
as.character(dbGetQuery(conn, "SHOW TABLES")[[1]])
})
setMethod("dbExistsTable", "clickhouse_connection", function(conn, name, ...) {
as.logical(name %in% dbListTables(conn))
})
setMethod("dbReadTable", "clickhouse_connection", function(conn, name, ...) {
dbGetQuery(conn, paste0("SELECT * FROM ", name))
})
setMethod("dbRemoveTable", "clickhouse_connection", function(conn, name, ...) {
dbExecute(conn, paste0("DROP TABLE ", name))
invisible(TRUE)
})
setMethod("dbSendQuery", "clickhouse_connection", function(conn, statement, use = c("memory", "temp"), ...) {
# with use = "temp" we try to avoid exception with long vectors conversion in rawToChar
# <simpleError in rawToChar(req$content): long vectors are not supported yet: raw.c:68>
use <- match.arg(use)
q <- sub("[; ]*;\\s*$", "", statement, ignore.case=T, perl=T)
has_resultset <- grepl("^\\s*(SELECT|SHOW)\\s+", statement, perl=T, ignore.case=T)
if (has_resultset) {
if ( grepl(".*FORMAT\\s+\\w+\\s*$", statement, perl=T, ignore.case=T)) {
stop("Can't have FORMAT keyword in queries, query ", statement)
}
q <- paste0(q ," FORMAT TabSeparatedWithNames")
}
h <- curl::new_handle()
#let's ignore peer verification for now
curl::handle_setopt(h, copypostfields = q, userpwd = paste0(conn@user, ":", conn@password), httpauth = 1L, ssl_verifypeer = FALSE)
url <- paste0(conn@url, "?database=", URLencode(conn@database))
if (use == "memory") {
req <- curl::curl_fetch_memory(url, handle = h)
} else {
tmp <- tempfile()
req <- curl::curl_fetch_disk(url, tmp, handle = h)
}
if (req$status_code != 200) {
if (use == "memory") {
stop(rawToChar(req$content))
} else {
stop(readLines(tmp))
}
}
dataenv <- new.env(parent = emptyenv())
if (has_resultset) {
# try to avoid problems when select just one column that can contain ""
# without "blank.lines.skip" we'll get warning:
# Stopped reading at empty line ... but text exists afterwards (discarded): ...
# and not all rows will be read
if (use == "memory") {
dataenv$data <- data.table::fread(rawToChar(req$content), sep="\t", header=TRUE,
showProgress=FALSE,
blank.lines.skip = TRUE)
} else {
dataenv$data <- data.table::fread(tmp, sep = "\t", header = TRUE,
showProgress = FALSE,
blank.lines.skip = TRUE)
unlink(tmp)
}
}
dataenv$success <- TRUE
dataenv$delivered <- -1
dataenv$open <- TRUE
dataenv$rows <- nrow(dataenv$data)
new("clickhouse_result",
sql = statement,
env = dataenv,
conn = conn
)
})
setMethod("dbWriteTable", signature(conn = "clickhouse_connection", name = "character", value = "ANY"), definition = function(conn, name, value, overwrite=FALSE,
append=FALSE, engine="TinyLog", ...) {
if (is.vector(value) && !is.list(value)) value <- data.frame(x = value, stringsAsFactors = F)
if (length(value) < 1) stop("value must have at least one column")
if (is.null(names(value))) names(value) <- paste("V", 1:length(value), sep='')
if (length(value[[1]])>0) {
if (!is.data.frame(value)) value <- as.data.frame(value, row.names=1:length(value[[1]]) , stringsAsFactors=F)
} else {
if (!is.data.frame(value)) value <- as.data.frame(value, stringsAsFactors=F)
}
if (overwrite && append) {
stop("Setting both overwrite and append to TRUE makes no sense.")
}
qname <- name
if (dbExistsTable(conn, qname)) {
if (overwrite) dbRemoveTable(conn, qname)
if (!overwrite && !append) stop("Table ", qname, " already exists. Set overwrite=TRUE if you want
to remove the existing table. Set append=TRUE if you would like to add the new data to the
existing table.")
}
if (!dbExistsTable(conn, qname)) {
fts <- sapply(value, dbDataType, dbObj=conn)
fdef <- paste(names(value), fts, collapse=', ')
ct <- paste0("CREATE TABLE ", qname, " (", fdef, ") ENGINE=", engine)
dbExecute(conn, ct)
}
if (length(value[[1]])) {
classes <- unlist(lapply(value, function(v){
class(v)[[1]]
}))
for (c in names(classes[classes=="character"])) {
value[[c]] <- enc2utf8(value[[c]])
}
for (c in names(classes[classes=="factor"])) {
levels(value[[c]]) <- enc2utf8(levels(value[[c]]))
}
write.table(value, textConnection("value_str", open="w"), sep="\t", row.names=F, col.names=F, quote=F)
value_str2 <- paste0(get("value_str"), collapse="\n")
h <- curl::new_handle()
curl::handle_setopt(h, copypostfields = value_str2, userpwd = paste0(conn@user, ":", conn@password), httpauth = 1L, ssl_verifypeer = FALSE)
req <- curl::curl_fetch_memory(paste0(conn@url, "?database=", URLencode(conn@database), "&query=", URLencode(paste0("INSERT INTO ", qname, " FORMAT TabSeparated"))), handle = h)
if (req$status_code != 200) {
stop("Error writing data to table ", rawToChar(req$content))
}
}
return(invisible(TRUE))
})
setMethod("dbDataType", signature(dbObj="clickhouse_connection", obj = "ANY"), definition = function(dbObj,
obj, ...) {
if (is.logical(obj)) "UInt8"
else if (is.integer(obj)) "Int32"
else if (is.numeric(obj)) "Float64"
else "String"
}, valueClass = "character")
setMethod("dbBegin", "clickhouse_connection", definition = function(conn, ...) {
stop("Transactions are not supported.")
})
setMethod("dbCommit", "clickhouse_connection", definition = function(conn, ...) {
stop("Transactions are not supported.")
})
setMethod("dbRollback", "clickhouse_connection", definition = function(conn, ...) {
stop("Transactions are not supported.")
})
setMethod("dbDisconnect", "clickhouse_connection", function(conn, ...) {
invisible(TRUE)
})
setMethod("fetch", signature(res = "clickhouse_result", n = "numeric"), definition = function(res, n, ...) {
if (!dbIsValid(res) || dbHasCompleted(res)) {
stop("Cannot fetch results from exhausted, closed or invalid response.")
}
if (n == 0) {
stop("Fetch 0 rows? Really?")
}
if (res@env$delivered < 0) {
res@env$delivered <- 0
}
if (res@env$delivered >= res@env$rows) {
return(res@env$data[F,, drop=F])
}
if (n > -1) {
n <- min(n, res@env$rows - res@env$delivered)
res@env$delivered <- res@env$delivered + n
return(res@env$data[(res@env$delivered - n + 1):(res@env$delivered),, drop=F])
}
else {
start <- res@env$delivered + 1
res@env$delivered <- res@env$rows
return(res@env$data[start:res@env$rows,, drop=F])
}
})
setMethod("dbGetRowsAffected", "clickhouse_result", definition = function(res, ...) {
as.numeric(NA)
})
setMethod("dbClearResult", "clickhouse_result", definition = function(res, ...) {
res@env$open <- FALSE
invisible(TRUE)
})
setMethod("dbHasCompleted", "clickhouse_result", definition = function(res, ...) {
res@env$delivered >= res@env$rows
})
setMethod("dbIsValid", "clickhouse_result", definition = function(dbObj, ...) {
dbObj@env$success && dbObj@env$open
})
|
## Caching the Inverse of a Matrix:
## Matrix inversion is usually a costly computation and there may be some
## benefit to caching the inverse of a matrix rather than compute it repeatedly.
## Below are a pair of functions that are used to create a special object that
## stores a matrix and caches its inverse.
## This function creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function(inverse) inv <<- inverse
getInverse <- function() inv
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## This function computes the inverse of the special "matrix" created by
## makeCacheMatrix above. If the inverse has already been calculated (and the
## matrix has not changed), then it should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInverse()
if (!is.null(inv)) {
message("getting cached data")
return(inv)
}
mat <- x$get()
inv <- solve(mat, ...)
x$setInverse(inv)
inv
}
| /cachematrix.R | no_license | dacarrera5/ProgrammingAssignment2 | R | false | false | 1,301 | r | ## Caching the Inverse of a Matrix:
## Matrix inversion is usually a costly computation and there may be some
## benefit to caching the inverse of a matrix rather than compute it repeatedly.
## Below are a pair of functions that are used to create a special object that
## stores a matrix and caches its inverse.
## This function creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function(inverse) inv <<- inverse
getInverse <- function() inv
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## This function computes the inverse of the special "matrix" created by
## makeCacheMatrix above. If the inverse has already been calculated (and the
## matrix has not changed), then it should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInverse()
if (!is.null(inv)) {
message("getting cached data")
return(inv)
}
mat <- x$get()
inv <- solve(mat, ...)
x$setInverse(inv)
inv
}
|
# # this test can spoil loaded httr and RSelenium packages so it was renamed and testthat
# # does not see it anymore. Use '.rs.restartR()' after test to repair broken packages
# # Run this test using 'testthat::test_file('tests/testthat/checkInstallation.R')'
# context("Installation on clean machine")
#
#
# #### clean ####
# .libPaths(Sys.getenv('R_LIBS_USER'))
# invisible(suppressWarnings(lapply(paste('package:',names(sessionInfo()$otherPkgs),sep=""),
# detach, character.only=TRUE, unload=TRUE)))
# rm(list=ls())
# suppressPackageStartupMessages({
# library(devtools)
# library(stringi)
# library(RSelenium)
# library(testthat)
# library(curl)
# library(digest)
# library(httr)
# })
# initialLoadedPkgs <- names(sessionInfo()$loadedOnly)
#
#
# #### paths ####
# userLibRoot <- dirname(.libPaths()[1])
# testDir <- paste0(userLibRoot, '/test')
# predefPack <- paste0(userLibRoot, '/predefPack')
#
#
# #### prepare folders, workspace and libraries ####
# if (file.exists(testDir)) {
# unlink(testDir, T, T)
# if (file.exists(testDir)) {
# evalq({
# dlls <- getLoadedDLLs() %>% sapply(`[[`, 'path') %>%
# Filter(function(dll) grepl('/test/', dll) ,.) # for jsonlite.dll
# for (i in length(dlls)) {
# library.dynam.unload(names(dlls)[i], dirname(dirname(dirname(dlls[i]))))
# }
# # getLoadedDLLs() %>% sapply(`[[`, 'path') %>%
# # Filter(function(dll) grepl('/test/', dll) ,.) %>% sapply(dyn.unload)
# }, envir=.GlobalEnv)
# unlink(testDir, T, T)
# }
# if (file.exists(testDir)) {
# stop('Could not uninstall testDir. ',
# 'Restart R session (possibly with ".rs.restartR()") to release previous dlls')
# }
# }
#
# dir.create(testDir)
# .libPaths(testDir)
#
# if (file.exists(predefPack)) {
# invisible(file.copy(paste0(predefPack, '/', dir(predefPack)), testDir, recursive=T))
# } else {
# suppressPackageStartupMessages(install.packages(c('devtools', 'testthat')))
# rselenium_path <- find.package('RSelenium', quiet = T)
# if (nchar(rselenium_path)) {
# invisible(file.copy(rselenium_path, testDir), recursive=T)
# invisible(file.copy(rselenium_path, predefPack), recursive=T)
# } else {
# suppressPackageStartupMessages(install.packages('RSelenium'))
# invisible(file.copy(paste0(testDir, '/RSelenium'), predefPack), recursive=T)
# }
# invisible(file.copy(testDir, paste0(predefPack, '/', dir(predefPack)), recursive=T))
# }
#
#
# res <- try(library(ggraptR), silent=T)
# if (!(class(res) == 'try-error' && grepl("no package called .ggraptR", res[1]))) {
# debug_stop('no package called .ggraptR')
# }
#
#
# #### install ggraptR from git. Run it and check the initial plot ####
# install(dirname(dirname(getwd())))
# suppressPackageStartupMessages(library(ggraptR))
# source('script/checkInitPlot.R')
# release_externals()
#
#
# #### restore and clean ####
# for (pkg in paste('package:', names(sessionInfo()$otherPkgs), sep=""))
# suppressWarnings(detach(pkg, character.only=TRUE, unload=TRUE))
#
# for (i in 10:1) {
# pkgs <- setdiff(names(sessionInfo()$loadedOnly), initialLoadedPkgs)
# if (!length(pkgs)) break
# for (pkg in pkgs) try(unloadNamespace(pkg), T)
# }
#
# unlink(testDir, T, T)
# .libPaths(Sys.getenv('R_LIBS_USER'))
# closeAllConnections()
# print('Success')
| /tests/testthat/checkInstallation.R | no_license | cran/ggraptR | R | false | false | 3,466 | r | # # this test can spoil loaded httr and RSelenium packages so it was renamed and testthat
# # does not see it anymore. Use '.rs.restartR()' after test to repair broken packages
# # Run this test using 'testthat::test_file('tests/testthat/checkInstallation.R')'
# context("Installation on clean machine")
#
#
# #### clean ####
# .libPaths(Sys.getenv('R_LIBS_USER'))
# invisible(suppressWarnings(lapply(paste('package:',names(sessionInfo()$otherPkgs),sep=""),
# detach, character.only=TRUE, unload=TRUE)))
# rm(list=ls())
# suppressPackageStartupMessages({
# library(devtools)
# library(stringi)
# library(RSelenium)
# library(testthat)
# library(curl)
# library(digest)
# library(httr)
# })
# initialLoadedPkgs <- names(sessionInfo()$loadedOnly)
#
#
# #### paths ####
# userLibRoot <- dirname(.libPaths()[1])
# testDir <- paste0(userLibRoot, '/test')
# predefPack <- paste0(userLibRoot, '/predefPack')
#
#
# #### prepare folders, workspace and libraries ####
# if (file.exists(testDir)) {
# unlink(testDir, T, T)
# if (file.exists(testDir)) {
# evalq({
# dlls <- getLoadedDLLs() %>% sapply(`[[`, 'path') %>%
# Filter(function(dll) grepl('/test/', dll) ,.) # for jsonlite.dll
# for (i in length(dlls)) {
# library.dynam.unload(names(dlls)[i], dirname(dirname(dirname(dlls[i]))))
# }
# # getLoadedDLLs() %>% sapply(`[[`, 'path') %>%
# # Filter(function(dll) grepl('/test/', dll) ,.) %>% sapply(dyn.unload)
# }, envir=.GlobalEnv)
# unlink(testDir, T, T)
# }
# if (file.exists(testDir)) {
# stop('Could not uninstall testDir. ',
# 'Restart R session (possibly with ".rs.restartR()") to release previous dlls')
# }
# }
#
# dir.create(testDir)
# .libPaths(testDir)
#
# if (file.exists(predefPack)) {
# invisible(file.copy(paste0(predefPack, '/', dir(predefPack)), testDir, recursive=T))
# } else {
# suppressPackageStartupMessages(install.packages(c('devtools', 'testthat')))
# rselenium_path <- find.package('RSelenium', quiet = T)
# if (nchar(rselenium_path)) {
# invisible(file.copy(rselenium_path, testDir), recursive=T)
# invisible(file.copy(rselenium_path, predefPack), recursive=T)
# } else {
# suppressPackageStartupMessages(install.packages('RSelenium'))
# invisible(file.copy(paste0(testDir, '/RSelenium'), predefPack), recursive=T)
# }
# invisible(file.copy(testDir, paste0(predefPack, '/', dir(predefPack)), recursive=T))
# }
#
#
# res <- try(library(ggraptR), silent=T)
# if (!(class(res) == 'try-error' && grepl("no package called .ggraptR", res[1]))) {
# debug_stop('no package called .ggraptR')
# }
#
#
# #### install ggraptR from git. Run it and check the initial plot ####
# install(dirname(dirname(getwd())))
# suppressPackageStartupMessages(library(ggraptR))
# source('script/checkInitPlot.R')
# release_externals()
#
#
# #### restore and clean ####
# for (pkg in paste('package:', names(sessionInfo()$otherPkgs), sep=""))
# suppressWarnings(detach(pkg, character.only=TRUE, unload=TRUE))
#
# for (i in 10:1) {
# pkgs <- setdiff(names(sessionInfo()$loadedOnly), initialLoadedPkgs)
# if (!length(pkgs)) break
# for (pkg in pkgs) try(unloadNamespace(pkg), T)
# }
#
# unlink(testDir, T, T)
# .libPaths(Sys.getenv('R_LIBS_USER'))
# closeAllConnections()
# print('Success')
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/atacr.R
\name{target_count_coverage}
\alias{target_count_coverage}
\title{Read count and mean coverage hitting the bait and non bait windows}
\usage{
target_count_coverage(data)
}
\arguments{
\item{data}{a list of SummarizedExperiment objects from atacr::make_counts()}
}
\value{
a dataframe of on target and off target read counts
}
\description{
Read count and mean coverage hitting the bait and non bait windows
}
| /man/target_count_coverage.Rd | no_license | TeamMacLean/atacr | R | false | true | 495 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/atacr.R
\name{target_count_coverage}
\alias{target_count_coverage}
\title{Read count and mean coverage hitting the bait and non bait windows}
\usage{
target_count_coverage(data)
}
\arguments{
\item{data}{a list of SummarizedExperiment objects from atacr::make_counts()}
}
\value{
a dataframe of on target and off target read counts
}
\description{
Read count and mean coverage hitting the bait and non bait windows
}
|
list(
demo = 'svyby(~TOTEXP.yy., FUN = svytotal, by = ~.by., design = FYCdsgn)',
event = '
# Loop over event types
events <- c("TOT", "DVT", "RX", "OBV", "OBD", "OBO",
"OPT", "OPY", "OPZ", "ERT", "IPT", "HHT", "OMA")
results <- list()
for(ev in events) {
key <- paste0(ev, "EXP")
formula <- as.formula(sprintf("~%s.yy.", key))
results[[key]] <- svyby(formula, FUN = svytotal, by = ~.by., design = FYCdsgn)
}
print(results)',
sop = '
# Loop over sources of payment
sops <- c("EXP", "SLF", "PTR", "MCR", "MCD", "OTZ")
results <- list()
for(sp in sops) {
key <- paste0("TOT", sp)
formula <- as.formula(sprintf("~%s.yy.", key))
results[[key]] <- svyby(formula, FUN = svytotal, by = ~.by., design = FYCdsgn)
}
print(results)',
event_sop = '
# Loop over events, sops
events <- c("TOT", "DVT", "RX", "OBV", "OBD", "OBO",
"OPT", "OPY", "OPZ", "ERT", "IPT", "HHT", "OMA")
sops <- c("EXP", "SLF", "PTR", "MCR", "MCD", "OTZ")
results <- list()
for(ev in events) {
for(sp in sops) {
key <- paste0(ev, sp)
formula <- as.formula(sprintf("~%s.yy.", key))
results[[key]] <- svyby(formula, FUN = svytotal, by = ~.by., design = FYCdsgn)
}
}
print(results)'
)
| /code/r/stats_use/totEXP.R | permissive | abiener/MEPS-summary-tables | R | false | false | 1,265 | r | list(
demo = 'svyby(~TOTEXP.yy., FUN = svytotal, by = ~.by., design = FYCdsgn)',
event = '
# Loop over event types
events <- c("TOT", "DVT", "RX", "OBV", "OBD", "OBO",
"OPT", "OPY", "OPZ", "ERT", "IPT", "HHT", "OMA")
results <- list()
for(ev in events) {
key <- paste0(ev, "EXP")
formula <- as.formula(sprintf("~%s.yy.", key))
results[[key]] <- svyby(formula, FUN = svytotal, by = ~.by., design = FYCdsgn)
}
print(results)',
sop = '
# Loop over sources of payment
sops <- c("EXP", "SLF", "PTR", "MCR", "MCD", "OTZ")
results <- list()
for(sp in sops) {
key <- paste0("TOT", sp)
formula <- as.formula(sprintf("~%s.yy.", key))
results[[key]] <- svyby(formula, FUN = svytotal, by = ~.by., design = FYCdsgn)
}
print(results)',
event_sop = '
# Loop over events, sops
events <- c("TOT", "DVT", "RX", "OBV", "OBD", "OBO",
"OPT", "OPY", "OPZ", "ERT", "IPT", "HHT", "OMA")
sops <- c("EXP", "SLF", "PTR", "MCR", "MCD", "OTZ")
results <- list()
for(ev in events) {
for(sp in sops) {
key <- paste0(ev, sp)
formula <- as.formula(sprintf("~%s.yy.", key))
results[[key]] <- svyby(formula, FUN = svytotal, by = ~.by., design = FYCdsgn)
}
}
print(results)'
)
|
#Load packages
install.packages("httr")
install.packages("xml2")
install.packages("magrittr")
install.packages("pbapply")
install.packages("magick")
install.packages("jsonlite")
library(httr)
library(xml2)
library(magrittr)
library(pbapply)
library(magick)
library(jsonlite)
library(tidyverse)
#base url
url_api<-"https://images-assets.nasa.gov/image/as11-40-5874/collection.json"
#Check what we get back from here
reply <- GET(url_api)
http_status(reply)
reply
#extract info from body
reply_content<-content(reply)
class(reply_content)
# create products data.frame
reply.df<-as.data.frame(t(as.data.frame(reply_content, stringsAsFactors=FALSE)), row.names=FALSE, col.names="url", stringsAsFactors=FALSE)
View(reply.df)
# get all maps from our request
dir<- paste0(tempdir(), "/API_nasa")
dir.create(dir)
reply.df[,2] <- paste0(dir, "image_", 1:nrow(reply.df), "jpg")
reply.df<-reply.df[-6,]
colnames(reply.df)<-c("url", "file")
# check for URLs that do not work properly (server issues?)
working <- !sapply(reply.df[1,], http_error, USE.NAMES = F)
reply.df <- reply.df[,working]
# download and read images
images<-mapply(x=reply.df[1,], y=reply.df[2,], function(x,y){
catch<-GET(x,write_disk(y, overwrite = T))
image_read(y)
})
#Write image
images <- do.call(c, images)
image_write(images, "C:/Users/chofi/Documents/2019/Maestria/Advance_Programming/AdvProg/nasa.png")
View(images)
| /API_client.R | no_license | sofigdl/AdvProg | R | false | false | 1,399 | r | #Load packages
install.packages("httr")
install.packages("xml2")
install.packages("magrittr")
install.packages("pbapply")
install.packages("magick")
install.packages("jsonlite")
library(httr)
library(xml2)
library(magrittr)
library(pbapply)
library(magick)
library(jsonlite)
library(tidyverse)
#base url
url_api<-"https://images-assets.nasa.gov/image/as11-40-5874/collection.json"
#Check what we get back from here
reply <- GET(url_api)
http_status(reply)
reply
#extract info from body
reply_content<-content(reply)
class(reply_content)
# create products data.frame
reply.df<-as.data.frame(t(as.data.frame(reply_content, stringsAsFactors=FALSE)), row.names=FALSE, col.names="url", stringsAsFactors=FALSE)
View(reply.df)
# get all maps from our request
dir<- paste0(tempdir(), "/API_nasa")
dir.create(dir)
reply.df[,2] <- paste0(dir, "image_", 1:nrow(reply.df), "jpg")
reply.df<-reply.df[-6,]
colnames(reply.df)<-c("url", "file")
# check for URLs that do not work properly (server issues?)
working <- !sapply(reply.df[1,], http_error, USE.NAMES = F)
reply.df <- reply.df[,working]
# download and read images
images<-mapply(x=reply.df[1,], y=reply.df[2,], function(x,y){
catch<-GET(x,write_disk(y, overwrite = T))
image_read(y)
})
#Write image
images <- do.call(c, images)
image_write(images, "C:/Users/chofi/Documents/2019/Maestria/Advance_Programming/AdvProg/nasa.png")
View(images)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Passif-proj_1an.R
\docType{methods}
\name{proj_1an_passif}
\alias{proj_1an_passif}
\title{Fonction \code{proj_1an_passif}}
\usage{
proj_1an_passif(passif, an)
}
\arguments{
\item{passif}{est un objet de type \code{\link{Passif}}.}
\item{an}{est un objet de type \code{integer}.}
}
\description{
Cette fonction permet de projeter horizon 1 an le passif d'une compagnie d'assurance.
}
\author{
Damien Tichit pour Sia Partners
}
| /man/proj_1an_passif.Rd | no_license | DTichit/ALModel | R | false | true | 505 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Passif-proj_1an.R
\docType{methods}
\name{proj_1an_passif}
\alias{proj_1an_passif}
\title{Fonction \code{proj_1an_passif}}
\usage{
proj_1an_passif(passif, an)
}
\arguments{
\item{passif}{est un objet de type \code{\link{Passif}}.}
\item{an}{est un objet de type \code{integer}.}
}
\description{
Cette fonction permet de projeter horizon 1 an le passif d'une compagnie d'assurance.
}
\author{
Damien Tichit pour Sia Partners
}
|
downloadfile <- "household_power_consumption.zip"
file_url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
dir <- "Household_power_consumption"
# File download verification. If file does not exist, download to working directory.
if(!file.exists(downloadfile)){
download.file(file_url,downloadfile, mode = "wb")
}
# File unzip verification. If the directory does not exist, unzip the downloaded file.
if(!file.exists(dir)){
unzip("household_power_consumption.zip", files = NULL, dir=".")
}
#Read/write tabel, where "?" is a missing value
HPS <- data.table::fread(input = "household_power_consumption.txt"
, na.strings="?"
)
#Convert character in "Date" to date variable
HPS[, Date := lapply(.SD, as.Date, "%d/%m/%Y"), .SDcols = c("Date")]
#Filter: only given dates
HPS <- HPS[(Date >= "2007-02-01") & (Date <= "2007-02-02")]
#Create and save PNG plot
png(file="plot1.png", width=480, height=480)
with(HPS,hist(Global_active_power,col="red",main="Global Active Power",
xlab="Global Active Power (kilowatts)", ylab="Frequency"))
dev.off()
| /plot1.R | no_license | Jaco85/Exploratory-Data-Analysis | R | false | false | 1,140 | r | downloadfile <- "household_power_consumption.zip"
file_url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
dir <- "Household_power_consumption"
# File download verification. If file does not exist, download to working directory.
if(!file.exists(downloadfile)){
download.file(file_url,downloadfile, mode = "wb")
}
# File unzip verification. If the directory does not exist, unzip the downloaded file.
if(!file.exists(dir)){
unzip("household_power_consumption.zip", files = NULL, dir=".")
}
#Read/write tabel, where "?" is a missing value
HPS <- data.table::fread(input = "household_power_consumption.txt"
, na.strings="?"
)
#Convert character in "Date" to date variable
HPS[, Date := lapply(.SD, as.Date, "%d/%m/%Y"), .SDcols = c("Date")]
#Filter: only given dates
HPS <- HPS[(Date >= "2007-02-01") & (Date <= "2007-02-02")]
#Create and save PNG plot
png(file="plot1.png", width=480, height=480)
with(HPS,hist(Global_active_power,col="red",main="Global Active Power",
xlab="Global Active Power (kilowatts)", ylab="Frequency"))
dev.off()
|
utils::globalVariables(c("anio_ocur", "edad_des", "ent_ocurr","lista_mex_des",
"lista_mex_cve",
"loc_ocurr", "mun_ocurr", "n", "total"))
| /R/globals.R | permissive | fdzul/healthdiagr | R | false | false | 187 | r | utils::globalVariables(c("anio_ocur", "edad_des", "ent_ocurr","lista_mex_des",
"lista_mex_cve",
"loc_ocurr", "mun_ocurr", "n", "total"))
|
#!/usr/bin/Rscript
# *******************************************
# @author Pranay Sarkar
# Script for:
# a. Merging training dataset to create one single dataset.
# b. Extracting only measurements on the mean and standard deviation for each measurement
# c. Uses descriptive activits naems to name activities in the dataset
# d. appropriately labels dataset with descriptive variable names
# e. Creates a second, independent tidy data set with the average of each variable for each activity and each subject.
# A. Merges the training and the test sets to create one data set
temp_train <- read.table("train/X_train.txt")
temp_test <- read.table("test/X_test.txt")
X <- rbind( temp_train, temp_test )
temp_train <- read.table("train/y_train.txt")
temp_test <- read.table("test/y_test.txt")
Y <- rbind( temp_train, temp_test )
temp_train <- read.table("train/subject_train.txt")
temp_test <- read.table("test/subject_test.txt")
Subject <- rbind( temp_train, temp_test )
# B. Extracts only the measurements on the mean and standard deviation for each measurement
features <- read.table("features.txt")
index_of_good_features <- grep("-mean\\(\\)|-std\\(\\)", features[, 2])
X <- X[, index_of_good_features]
names(X) <- features[index_of_good_features, 2]
names(X) <- gsub("\\(|\\)", "", names(X))
names(X) <- tolower( names(X) )
# C. Uses descriptive activity names to name the activities in the data set
activity <- read.table("activity_labels.txt")
activity[, 2] = gsub("_", "", tolower(as.character(activity[, 2])))
Y[, 1] = activity[Y[ , 1], 2]
names(Y) <- "activity"
# D. Appropriately labels the data set with descriptive activity names
names(Subject) <- "subject"
clean <- cbind(Subject, Y, X)
write.table(clean, "merged_tidy_data.txt")
# E. Creates a 2nd, independent tidy data set with the average of each variable for each activity and each subject
uniqueSubjects <- unique(Subject)[, 1]
numSubjects <- length(unique(Subject)[, 1])
numActivities <- length(activity[, 1])
numColumns <- dim(clean)[2]
result <- clean[1:(numSubjects*numActivities), ]
row <- 1
for (s in 1:numSubjects){
for (a in 1:numActivities){
result[row, 1] <- uniqueSubjects[s]
result[row, 2] <- activity[a, 2]
temp <- clean[clean$subject == s & clean$activity == activity[a, 2], ]
result[row, 3:numColumns] <- colMeans(temp[, 3:numColumns])
row <- row + 1
}
}
write.table(result, "dataset_with_avg.txt")
| /Week 4/run_analysis.R | no_license | pranay22/Getting-and-Cleaning-Data | R | false | false | 2,487 | r | #!/usr/bin/Rscript
# *******************************************
# @author Pranay Sarkar
# Script for:
# a. Merging training dataset to create one single dataset.
# b. Extracting only measurements on the mean and standard deviation for each measurement
# c. Uses descriptive activits naems to name activities in the dataset
# d. appropriately labels dataset with descriptive variable names
# e. Creates a second, independent tidy data set with the average of each variable for each activity and each subject.
# A. Merges the training and the test sets to create one data set
temp_train <- read.table("train/X_train.txt")
temp_test <- read.table("test/X_test.txt")
X <- rbind( temp_train, temp_test )
temp_train <- read.table("train/y_train.txt")
temp_test <- read.table("test/y_test.txt")
Y <- rbind( temp_train, temp_test )
temp_train <- read.table("train/subject_train.txt")
temp_test <- read.table("test/subject_test.txt")
Subject <- rbind( temp_train, temp_test )
# B. Extracts only the measurements on the mean and standard deviation for each measurement
features <- read.table("features.txt")
index_of_good_features <- grep("-mean\\(\\)|-std\\(\\)", features[, 2])
X <- X[, index_of_good_features]
names(X) <- features[index_of_good_features, 2]
names(X) <- gsub("\\(|\\)", "", names(X))
names(X) <- tolower( names(X) )
# C. Uses descriptive activity names to name the activities in the data set
activity <- read.table("activity_labels.txt")
activity[, 2] = gsub("_", "", tolower(as.character(activity[, 2])))
Y[, 1] = activity[Y[ , 1], 2]
names(Y) <- "activity"
# D. Appropriately labels the data set with descriptive activity names
names(Subject) <- "subject"
clean <- cbind(Subject, Y, X)
write.table(clean, "merged_tidy_data.txt")
# E. Creates a 2nd, independent tidy data set with the average of each variable for each activity and each subject
uniqueSubjects <- unique(Subject)[, 1]
numSubjects <- length(unique(Subject)[, 1])
numActivities <- length(activity[, 1])
numColumns <- dim(clean)[2]
result <- clean[1:(numSubjects*numActivities), ]
row <- 1
for (s in 1:numSubjects){
for (a in 1:numActivities){
result[row, 1] <- uniqueSubjects[s]
result[row, 2] <- activity[a, 2]
temp <- clean[clean$subject == s & clean$activity == activity[a, 2], ]
result[row, 3:numColumns] <- colMeans(temp[, 3:numColumns])
row <- row + 1
}
}
write.table(result, "dataset_with_avg.txt")
|
# This file contains miscellaneous functions for use in app.R
# These functions may contain outsourced code chunks so as to reduce clutter in the Shiny app code structure
# This function returns a string description of the HOT Shiny app
getAppDescription <- function(){
description <- "Physical activity is one of the greatest modifiable risk behaviors
for many chronic, non-communicable diseases such as cancer and heart disease.
Due to the associated health benefits to increased physical activity,
policies that promote such behavior will improve public health. This
analysis, performed by the Initiative for Health-Oriented Transportation (HOT) team,
examines the health benefit gained from increase in active transportation
(walking and cycling) as it translates to an increase in physical activity.
The health benefit is estimated as the change in the annual mortality rate associated
with a change in active transportation. We may apply the HOT model to any location
where one finds the requisite data and can wrangle them into the specified form (found on the next page.)"
return(description)
}
getMetricDescription <- function(){
description <- paste("All options return a \"heat\" map of the selected statistic.",
"CRA: Comparative Risk Assessment contrasts current levels of physical activity (participation) with a hypothetical scenarios: full participation and zero particpation.",
"Particpation: gives proportion of population that is active at a weekly minimum by borough.",
"Frequency: returns the likelyhood that an average person in a given borough is active on any day of the week.",
"Intensity: calculates the mean and standard deviation of physical activity among active travelers.",
"Duration: returns average trip length (in minutes) by mode (walking or cycling).",
"Trips: shows average number trips per day by mode.", sep = "\n")
return(description)
}
# This function returns a HOT map for use in Shiny
getShinyMap <- function(inputSurvey = NULL,
inputCustom = NULL,
inputMetric = NULL,
inputMode = NULL,
inputScenario = NULL,
inputAuthor = NULL,
inputIncome = NULL){
# Load TS based on user selection
switch(inputSurvey,
"London" = { ts <- readRDS(file = paste0("./data/LTDS.ts.rds")) },
"France" = { ts <- readRDS(file = paste0("./data/ENTD.fr.ts.rds")) },
"USA" = {}, # update later once USA integrated
"Custom" = { ts <- inputCustom })
# Load GIS
switch(inputSurvey,
"London" = { GIS.df <- readRDS(file = paste0("./data/LondonGIS.rds")) },
"France" = { GIS.df <- readRDS(file = paste0("./data/FranceGIS.rds")) },
"USA" = {}, # update later once USA integrated
"Custom" = {}) # update later once custom/GIS developed
# Translate input into proper strings for processing
if( inputMetric %in% c("Duration", "Trips") ){ mode <- tolower(inputMode) }else{ mode <- NULL} # need lowercase mode if provided
if( inputMetric != "CRA" ){
metric <- tolower(inputMetric) # need lowercase string for non-CRA metrics
scen <- NULL # need scen set to null for non-CRA metrics
}else{
metric <- inputMetric
switch(inputScenario,
"Zero" = { scen <- "rho.s.1" },
"Full" = { scen <- "rho.s.2" },
"Custom" = {})} # update later once custom scenario integrated
# CRA treated separately
if( metric == "CRA"){
# Load CRA.ts results, if available. If unavailable, generate.
switch(inputSurvey,
"London" = { filename <- paste0("./data/craTSLondon.rds") },
"France" = { filename <- paste0("./data/craTSFrance.rds") },
"USA" = {}, # update later once USA integrated
"Custom" = { filename <- inputCustom })
# Add progress bar message "Analyzing..." to CRA load process
withProgress(message = 'Analyzing...', value = 2, {
if( file.exists(filename) ){ craTS <- readRDS(file = filename) }else{ craTS <- CRA.ts(ts) ; saveRDS(craTS, file = filename) }
})
# Filter CRA.ts results by author
data.df <- craTS %>% dplyr::filter(author == inputAuthor)
# If author is Lear, filter results by income
if( inputAuthor == "Lear" ){ data.df <- data.df %>% dplyr::filter(income == inputIncome) }
# Join results with GIS
map.df <- left_join(GIS.df, data.df, by = "location")
# Generate map with progress bar message "Mapping.."
withProgress(message = 'Mapping...', value = 3, {
getMap(map.df, metric, mode = mode, scenario = scen, author = inputAuthor, income = inputIncome, interactive = FALSE)
})
}
# Everything besides CRA, but written such that this works for CRA in future
else{
# Create temp file directory (if does not already exist) -- reinstalling HOT package will remove the directory without error
dir.create("./data/temp_files", showWarnings = FALSE)
# Check if local results file exists -- if so, load. If not, compute, load, and store locally.
filename <- paste0( "./data/temp_files/", metric, mode, inputSurvey, ".rds")
# Add progress bar message "Analyzing..." to metric data load process
withProgress(message = 'Analyzing...', value = 4, {
if( file.exists(filename) ){ data.df <- readRDS(file = filename) }
else{ data.df <- getHOT(ts, metric, mode = mode, scenario = scen, author = inputAuthor, income = inputIncome) ; saveRDS(data.df, file = filename) }
})
# Join results with GIS
map.df <- left_join(GIS.df, data.df, by = "location")
# Generate map with progress bar message "Mapping.."
withProgress(message = 'Mapping...', value = 5, {
getMap(map.df, metric, mode = mode, scenario = scen, author = inputAuthor, income = inputIncome, interactive = FALSE)
})
}
}
# This function clears all generated files from the HOT Shiny app
cleanup <- function(){
# Clear locally generated files
filenames <- list.files(paste0("./data/temp_files/"), full.names = TRUE)
foo <- file.remove(filenames)
# # Retaining CRA-related cleanup code for future development
# if( file.exists(paste0(getHOTdirectory(), "/craTSLondon.rds")) ){ file.remove(paste0(getHOTdirectory(), "/craTSLondon.rds")) }
# if( file.exists(paste0(getHOTdirectory(), "/craTSFrance.rds")) ){ file.remove(paste0(getHOTdirectory(), "/craTSFrance.rds")) }
}
| /allFunctions.R | no_license | hfremont/Hosted-Hot-Tool | R | false | false | 6,724 | r | # This file contains miscellaneous functions for use in app.R
# These functions may contain outsourced code chunks so as to reduce clutter in the Shiny app code structure
# This function returns a string description of the HOT Shiny app
getAppDescription <- function(){
description <- "Physical activity is one of the greatest modifiable risk behaviors
for many chronic, non-communicable diseases such as cancer and heart disease.
Due to the associated health benefits to increased physical activity,
policies that promote such behavior will improve public health. This
analysis, performed by the Initiative for Health-Oriented Transportation (HOT) team,
examines the health benefit gained from increase in active transportation
(walking and cycling) as it translates to an increase in physical activity.
The health benefit is estimated as the change in the annual mortality rate associated
with a change in active transportation. We may apply the HOT model to any location
where one finds the requisite data and can wrangle them into the specified form (found on the next page.)"
return(description)
}
getMetricDescription <- function(){
description <- paste("All options return a \"heat\" map of the selected statistic.",
"CRA: Comparative Risk Assessment contrasts current levels of physical activity (participation) with a hypothetical scenarios: full participation and zero particpation.",
"Particpation: gives proportion of population that is active at a weekly minimum by borough.",
"Frequency: returns the likelyhood that an average person in a given borough is active on any day of the week.",
"Intensity: calculates the mean and standard deviation of physical activity among active travelers.",
"Duration: returns average trip length (in minutes) by mode (walking or cycling).",
"Trips: shows average number trips per day by mode.", sep = "\n")
return(description)
}
# This function returns a HOT map for use in Shiny
getShinyMap <- function(inputSurvey = NULL,
inputCustom = NULL,
inputMetric = NULL,
inputMode = NULL,
inputScenario = NULL,
inputAuthor = NULL,
inputIncome = NULL){
# Load TS based on user selection
switch(inputSurvey,
"London" = { ts <- readRDS(file = paste0("./data/LTDS.ts.rds")) },
"France" = { ts <- readRDS(file = paste0("./data/ENTD.fr.ts.rds")) },
"USA" = {}, # update later once USA integrated
"Custom" = { ts <- inputCustom })
# Load GIS
switch(inputSurvey,
"London" = { GIS.df <- readRDS(file = paste0("./data/LondonGIS.rds")) },
"France" = { GIS.df <- readRDS(file = paste0("./data/FranceGIS.rds")) },
"USA" = {}, # update later once USA integrated
"Custom" = {}) # update later once custom/GIS developed
# Translate input into proper strings for processing
if( inputMetric %in% c("Duration", "Trips") ){ mode <- tolower(inputMode) }else{ mode <- NULL} # need lowercase mode if provided
if( inputMetric != "CRA" ){
metric <- tolower(inputMetric) # need lowercase string for non-CRA metrics
scen <- NULL # need scen set to null for non-CRA metrics
}else{
metric <- inputMetric
switch(inputScenario,
"Zero" = { scen <- "rho.s.1" },
"Full" = { scen <- "rho.s.2" },
"Custom" = {})} # update later once custom scenario integrated
# CRA treated separately
if( metric == "CRA"){
# Load CRA.ts results, if available. If unavailable, generate.
switch(inputSurvey,
"London" = { filename <- paste0("./data/craTSLondon.rds") },
"France" = { filename <- paste0("./data/craTSFrance.rds") },
"USA" = {}, # update later once USA integrated
"Custom" = { filename <- inputCustom })
# Add progress bar message "Analyzing..." to CRA load process
withProgress(message = 'Analyzing...', value = 2, {
if( file.exists(filename) ){ craTS <- readRDS(file = filename) }else{ craTS <- CRA.ts(ts) ; saveRDS(craTS, file = filename) }
})
# Filter CRA.ts results by author
data.df <- craTS %>% dplyr::filter(author == inputAuthor)
# If author is Lear, filter results by income
if( inputAuthor == "Lear" ){ data.df <- data.df %>% dplyr::filter(income == inputIncome) }
# Join results with GIS
map.df <- left_join(GIS.df, data.df, by = "location")
# Generate map with progress bar message "Mapping.."
withProgress(message = 'Mapping...', value = 3, {
getMap(map.df, metric, mode = mode, scenario = scen, author = inputAuthor, income = inputIncome, interactive = FALSE)
})
}
# Everything besides CRA, but written such that this works for CRA in future
else{
# Create temp file directory (if does not already exist) -- reinstalling HOT package will remove the directory without error
dir.create("./data/temp_files", showWarnings = FALSE)
# Check if local results file exists -- if so, load. If not, compute, load, and store locally.
filename <- paste0( "./data/temp_files/", metric, mode, inputSurvey, ".rds")
# Add progress bar message "Analyzing..." to metric data load process
withProgress(message = 'Analyzing...', value = 4, {
if( file.exists(filename) ){ data.df <- readRDS(file = filename) }
else{ data.df <- getHOT(ts, metric, mode = mode, scenario = scen, author = inputAuthor, income = inputIncome) ; saveRDS(data.df, file = filename) }
})
# Join results with GIS
map.df <- left_join(GIS.df, data.df, by = "location")
# Generate map with progress bar message "Mapping.."
withProgress(message = 'Mapping...', value = 5, {
getMap(map.df, metric, mode = mode, scenario = scen, author = inputAuthor, income = inputIncome, interactive = FALSE)
})
}
}
# This function clears all generated files from the HOT Shiny app
cleanup <- function(){
# Clear locally generated files
filenames <- list.files(paste0("./data/temp_files/"), full.names = TRUE)
foo <- file.remove(filenames)
# # Retaining CRA-related cleanup code for future development
# if( file.exists(paste0(getHOTdirectory(), "/craTSLondon.rds")) ){ file.remove(paste0(getHOTdirectory(), "/craTSLondon.rds")) }
# if( file.exists(paste0(getHOTdirectory(), "/craTSFrance.rds")) ){ file.remove(paste0(getHOTdirectory(), "/craTSFrance.rds")) }
}
|
# Plots some of the output of a C. elegans germline simulation, as recorded in the file gonadData.txt
#
# A NaN warning will be generated when this script runs, because the distance to the first meiotic cell
# is undefined before meiotic cells appear. Usually the warning can be safely ignored.
# UNCOMMENT HERE AND AT END OF FILE FOR POSTSCRIPT OUTPUT-----------------------------------------------
# library("extrafont")
# postscript("GonadDataPrelim.eps", height = 4.5, width = 6.83, family = "Arial", paper = "special", onefile = FALSE, horizontal = FALSE)
#------------------------------------------------------------------------------------------------------
#USER INPUT - FILL IN THESE FIELDS:
resultsDirectory = "../exampleOutput/production_2.8/"
plotMultipleFiles = TRUE # If true we plot the mean and standard deviation of gonadData.txt
# files from a collection of directories
fileNumbers = seq(0,29) # Input directories should be located under resultsDirectory and
# should be named <baseFileName> + <number>
baseFileName = ""
useManuallyCountedCellRows = TRUE # If true, manual cell row count data is expected to be
# provided in each results directory, in a file called
# ZoneLengths.txt (see our example data)
useManuallyCountedProlifCells = FALSE # If true, manual proliferative cell counts are expected
# to be provided in each results directory, in a file called
# CorrectedProlifCounts.txt (see our example data)
showMicronZoneLengths = FALSE # Whether to output the position of certain significant cells
# in microns from the DTC, in addition to cell rows
# from the DTC
nStandardDeviations = 1 # Number of standard deviations to shade either side of the mean
MAXTIME = 82 # Only plot simulations with data up to time 82. Useful for
# visualising incomplete sets of runs.
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
# SETUP GRAPH PROPERTIES AND GRAPH PLOTTING FUNCTIONS
if(showMicronZoneLengths){
rowsOfGraphs = 1
}else{
rowsOfGraphs = 2
}
par(mfrow=c(rowsOfGraphs,3), lwd=2, ps=12, bg="white", mar=c(5,5,5,5))
plotLarvalStageMarkers = function(ytop){
polygon(c(31.5,35.5,35.5,31.5), c(0,0,ytop,ytop), col=gray(0.8), lty=0)
segments(18.5,0,18.5, ytop, lty = 3,lwd = 1)
segments(26,0,26, ytop, lty = 3,lwd = 1)
segments(35.5,0,35.5, ytop, lty = 3,lwd = 1)
}
# LOOP THROUGH RESULTS FILES AND CALCULATE A MEAN AND STANDARD DEVIATION FOR EACH PIECE OF DATA
sum <-data.frame()
sumSquares<-data.frame()
count =0
if(!plotMultipleFiles){
fileNumbers = 0;
meandata = read.table(paste(resultsDirectory,baseFileName,"/results_from_time_0/GonadData.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
stddevdata = meandata - meandata #zero this out
}else{
for(n in fileNumbers){
dataCurrent<-read.table(paste(resultsDirectory,baseFileName,n,"/results_from_time_0/GonadData.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
print(length(dataCurrent$V1))
dataCurrent=dataCurrent[dataCurrent$V1 <= MAXTIME,]
if(sum(dataCurrent$V1<=MAXTIME)<MAXTIME){
}else{
count = count+1
if(length(sum)==0){
sum = dataCurrent;
sumSquares = dataCurrent^2;
timepoints = (dataCurrent$V1 + 18.5) # <- corrects for the fact that the simulation starts
# at 18.5 hrs post-hatching
}else{
sum = sum + dataCurrent;
sumSquares = sumSquares + dataCurrent^2;
}
}
}
meandata = sum / count;#length(fileNumbers);
stddevdata = sqrt((sumSquares/count) - meandata^2)#length(fileNumbers)) - meandata^2 );
print("No. runs = ")
print(count)
}
# READ IN MANUALLY COUNTED CELL ROW MEASUREMENTS IF REQUESTED. THE ALTERNATIVE IS TO TRUST THE SIMULATION'S
# BUILT IN CELL ROW COUNTING ALGORITHM (USUALLY UNDERESTIMATES THE TRUE ROW NUMBER)
if(useManuallyCountedCellRows){
if(!plotMultipleFiles){
rowData <- read.table(paste(resultsDirectory,baseFileName,"/ZoneLengths.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
rowTimePoints = rowData[,1]
rowMeioticMean = rowData[,2]
rowMitoticMean = rowData[,3]
rowMeioticStd = rowMeioticMean - rowMeioticMean
rowMitoticStd = rowMitoticMean - rowMitoticMean
}else{
for(n in fileNumbers){
rowDataCurrent <- read.table(paste(resultsDirectory,baseFileName,n,"/ZoneLengths.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
rowTimePoints = rowDataCurrent[,1] + 18.5
if(n == fileNumbers[1]){
rowMeioticMean = rowDataCurrent[,2]
rowMitoticMean = rowDataCurrent[,3]
rowMeioticSquare = rowDataCurrent[,2]*rowDataCurrent[,2]
rowMitoticSquare = rowDataCurrent[,3]*rowDataCurrent[,3]
}else{
rowMeioticMean = rowMeioticMean + rowDataCurrent[,2]
rowMitoticMean = rowMitoticMean + rowDataCurrent[,3]
rowMeioticSquare = rowMeioticSquare + rowDataCurrent[,2]*rowDataCurrent[,2]
rowMitoticSquare = rowMitoticSquare + rowDataCurrent[,3]*rowDataCurrent[,3]
}
}
rowMeioticMean = rowMeioticMean/length(fileNumbers)
rowMitoticMean = rowMitoticMean/length(fileNumbers)
rowMeioticStd = sqrt((rowMeioticSquare/length(fileNumbers)) - rowMeioticMean*rowMeioticMean)
rowMitoticStd = sqrt((rowMitoticSquare/length(fileNumbers)) - rowMitoticMean*rowMitoticMean)
}
}
# READ IN MANUAL PROLIFERATIVE CELL COUNTS IF REQUESTED. THE SIMULATION COUNTS ALL NON-MEIOTIC CELLS AS
# PROLIFERATIVE BY DEFAULT. MANUAL COUNTS MADE IN PARAVIEW CAN BE PROVIDED INSTEAD, FOR EXAMPLE, TO BETTER
# MIMIC THE WAY PROLIFERATIVE CELLS ARE COUNTED EXPERIMENTALLY (counting stops after first row containing
# 2 meiotic cells)
if(useManuallyCountedProlifCells){
if(!plotMultipleFiles){
cellDataMean <- read.table(paste(resultsDirectory,baseFileName,"/CorrectedProlifCounts.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
cellTimePoints = cellDataMean$V1
cellDataStd = cellDataMean - cellDataMean
}else{
for(n in fileNumbers){
cellDataCurrent <- read.table(paste(resultsDirectory,baseFileName,n,"/CorrectedProlifCounts.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
cellTimePoints = cellDataCurrent$V1 + 18.5
if(n == fileNumbers[1]){
cellDataMean = cellDataCurrent$V2
cellDataSquare = (cellDataCurrent$V2)*(cellDataCurrent$V2)
}else{
cellDataMean = cellDataMean+cellDataCurrent$V2
cellDataSquare = cellDataSquare+(cellDataCurrent$V2)*(cellDataCurrent$V2)
}
}
cellDataMean = cellDataMean/length(fileNumbers)
cellDataStd = sqrt((cellDataSquare/length(fileNumbers)) - cellDataMean*cellDataMean)
}
}
if(!showMicronZoneLengths){
#PLOT TOTAL CELLS, +- 2 STDDEV
ytop = max(meandata$V7 + nStandardDeviations*stddevdata[,7])*1.05 # <- max y
plot(0,0, xlab='Time (hph)', ylab="Total cells (count)", xlim=c(18.5,100), ylim=c(0,ytop)) # <- initialise plot
plotLarvalStageMarkers(ytop)
polygon(c(timepoints, rev(timepoints)), c(meandata$V7 + nStandardDeviations*stddevdata[,7], rev(meandata$V7 - nStandardDeviations*stddevdata[,7]) ), col=gray(0.4), lty=0) # <- confidence region
points(timepoints, meandata$V7, type='l') # <- simulated mean
points(c(0,2.5,5.5,7.5,11.5,12.5,17)+18.5, c(16,40,63,110,154,177,308), type='l', col='firebrick2', lty=1) # <- experimental result
mtext("(A)", 3, at=15, padj=-0.5)
print(timepoints)
print(meandata$V7)
#PLOT PROLIFERATIVE CELLS, +- 2 STDDEV
if(useManuallyCountedProlifCells){
ytop = max(cellDataMean + nStandardDeviations*cellDataStd)*1.05
plot(0,0, xlab='Time (hph)', ylab="Proliferative cells (count)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(cellTimePoints, rev(cellTimePoints)), c(cellDataMean + nStandardDeviations*cellDataStd, rev(cellDataMean - nStandardDeviations*cellDataStd)), col=gray(0.4),lty=0)
points(cellTimePoints, cellDataMean, type='l')
}else{
ytop = max(meandata$V5 + nStandardDeviations*stddevdata[,5])*1.05
plot(0,0, xlab='Time (hph)', ylab="Proliferative cells (count)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V5 + nStandardDeviations*stddevdata[,5], rev(meandata$V5 - nStandardDeviations*stddevdata[,5])), col=gray(0.4),lty=0)
points(timepoints, meandata$V5, type='l')
}
points(c(0,2.5,5.5,7.5,11.5,12.5,17)+18.5, c(16,40,63,103,126,134,204), type='l', lty=1, col='firebrick2')
points(c(35.5,41.5,48.5,62.5,91.5), c(201,244,251,220,157), type='l', lty=1, col='firebrick2')
mtext("(B)", 3, at=15, padj=-0.5)
#PLOT SPERM COUNT, +- 2 STDDEV
ytop = max((meandata$V4 + nStandardDeviations*stddevdata[,4]),140)*1.05
plot(0,0, xlab='Time (hph)', ylab="Sperm cells (count)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V4 + nStandardDeviations*stddevdata[,4], rev(meandata$V4 - nStandardDeviations*stddevdata[,4])), col=gray(0.4), lty=0)
points(timepoints, meandata$V4, type='l')
points(c(0,2.5,5.5,7.5,11.5,12.5,17,19.5)+18.5, c(0,0,0,0,4,41,85,140), type='l', lty=1, col='firebrick2')
points(seq(19.5,118,by=0.1)+18.5, 140-2.7*(seq(19.5,118,by=0.1)-19.5), type='l', lty=2, col='firebrick2')
mtext("(C)", 3, at=15, padj=-0.5)
print(meandata$V4)
#PLOT ORGAN LENGTH, +- 2 STDDEV
ytop = max((meandata$V2 + nStandardDeviations*stddevdata[,2]),405)*1.05
plot(0,0, xlab='Time (hph)', type='l', ylab=expression(paste("Length of gonad arm (", mu, "m)")), xlim=c(18.5,118.5), ylim =c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V2 + nStandardDeviations*stddevdata[,2], rev(meandata$V2 - nStandardDeviations*stddevdata[,2])), col=gray(0.4), lty=0)
points(timepoints, meandata$V2, type='l')
points(c(18.5,22,26,31,35.5), c(32,61.7,91.4,198,405), lty=1, col="firebrick2", type='l')
points(c(35.5,118), c(405,405), lty=2, col="firebrick2", type='l')
mtext("(D)",3, at=15, padj=-0.5)
# PLOT CELL ROW DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
# NOTE: the automated row counting algorithm in our code counts the endcap as one row. We therefore add 2 to the output
# to correct for this systematic error (the endcap usually contains about 3 cell rows by eye).
if(useManuallyCountedCellRows){
ytop = 35#max(rowMeioticMean + nStandardDeviations*rowMeioticStd)*1.05
plot(0,0, xlab='Time (hph)', ylab="Distance to 1st row containing\n >1 meiotic cell (CD)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(rowTimePoints,rev(rowTimePoints)), c(rowMeioticMean-nStandardDeviations*rowMeioticStd, rev(rowMeioticMean+nStandardDeviations*rowMeioticStd)), col=gray(0.4), lty=0)
points(rowTimePoints, rowMeioticMean, type='l')
}else{
ytop = max(meandata$V15[meandata$V1>10] + stddevdata[,15][meandata$V1>10])*1.05
plot(0,0, xlab='Time (hph)', ylab="1st row containing two meiotic cells", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V15+2 + nStandardDeviations*stddevdata[,15], rev(meandata$V15+2 - nStandardDeviations*stddevdata[,15])), col=gray(0.4), lty=0)
points(timepoints, meandata$V15+2, type='l')
}
points(c(35.5,118), c(20,20), type='l', lty=2, col='firebrick2')
mtext("(E)",3, at=15, padj=-0.5)
#PLOT CELL ROW DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
#NOTE: the automated row counting algorithm in our code counts the endcap as one row. We therefore add 2 to the output
#to correct for this systematic error (the endcap usually contains about 3 cell rows by eye).
if(useManuallyCountedCellRows){
ytop = 35#max(rowMitoticMean + nStandardDeviations*rowMitoticStd)*1.05
plot(0,0,xlab='Time (hph)',ylab=expression(paste("Distance to last row containing\n a proliferative cell (CD)")),xlim=c(18.5,100),ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(rowTimePoints, rev(rowTimePoints)), c(rowMitoticMean-nStandardDeviations*rowMitoticStd,rev(rowMitoticMean+nStandardDeviations*rowMitoticStd)), col=gray(0.4), lty=0)
points(rowTimePoints, rowMitoticMean, type='l')
}else{
ytop = max(meandata$V16 + nStandardDeviations*stddevdata[,16])*1.05
plot(0,0,xlab='Time (hph)',ylab=expression(paste("Last row containing a prolif. cell")),xlim=c(18.5,100),ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V16+2 + nStandardDeviations*stddevdata[,16], rev(meandata$V16+2 - nStandardDeviations*stddevdata[,16])), col=gray(0.4), lty=0)
points(timepoints, meandata$V16+2, type='l')
}
points(c(35.5,118), c(28,28), type='l',lty=2,col='firebrick2')
mtext("(F)",3, at=15, padj=-0.5)
}else{
#PLOT MICRON DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
ytop = max(meandata$V8 + nStandardDeviations*stddevdata[,8])*1.05
plot(0,0, ann=FALSE, xlab='Time (hph)', ylab=expression(paste("Furthest mitotic cell from DTC (", mu, "m)")), xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V8 + nStandardDeviations*stddevdata[,8], rev(meandata$V8 - nStandardDeviations*stddevdata[,8])), col=gray(0.4),lty=0)
points(timepoints, meandata$V8, type='l')
points(c(35.5,118), c(70,70), type='l', lty=2, col='firebrick2')
mtext(side = 2, line = 3, expression(paste("Furthest mitotic cell from DTC (", mu, "m)")), padj=1, cex=0.7)
mtext(side = 1, line = 3, "Time (hph)", padj=-0.5, cex=0.7)
mtext("(A)", 3, at=15, padj=-0.5)
#PLOT MICRON DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
ytop = max(meandata$V9[meandata$V9<1000] + nStandardDeviations*stddevdata[,9][meandata$V9<1000])*1.05
plot(0,0, ann=FALSE, xlab='Time (hph)', ylab=expression(paste("Closest meiotic cell to DTC (", mu, "m)")), xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints[meandata$V9<1000],rev(timepoints[meandata$V9<1000])), c(meandata$V9[meandata$V9<1000] + nStandardDeviations*stddevdata[meandata$V9<1000,9],
rev(meandata$V9[meandata$V9<1000] - nStandardDeviations*stddevdata[meandata$V9<1000,9])),col=gray(0.4),lty=0)
points(timepoints[meandata$V9<1000], meandata$V9[meandata$V9<1000], type='l')
points(c(35.5,118), c(40,40), type='l', lty=2, col='firebrick2')
mtext(side = 2, line = 3, expression(paste("Closest meiotic cell to DTC (", mu, "m)")), padj=1, cex=0.7)
mtext(side = 1, line = 3, "Time (hph)", padj=-0.5, cex=0.7)
mtext("(B)",3, at=15, padj=-0.5)
#PLOT MICRON DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
ytop = max(meandata$V8[meandata$V9<1000] - meandata$V9[meandata$V9<1000])*1.05
plot(0,0, ann=FALSE, xlab='Time (hph)', ylab=expression(paste("Meiotic entry region length (", mu, "m)")), xlim=c(18.5,100), ylim=c(0,ytop))
variance = stddevdata^2;
combined=nStandardDeviations*sqrt(variance[,8] + variance[,9])
plotLarvalStageMarkers(ytop)
polygon(c(timepoints[!is.nan(combined)],rev(timepoints[!is.nan(combined)])),
c(meandata$V8[!is.nan(combined)]-meandata$V9[!is.nan(combined)] + combined[!is.nan(combined)],
rev(meandata$V8[!is.nan(combined)]-meandata$V9[!is.nan(combined)] - combined[!is.nan(combined)])), col=gray(0.4),lty=0)
points(timepoints[meandata$V9<1000], meandata$V8[meandata$V9<1000] - meandata$V9[meandata$V9<1000],type='l')
points(c(35.5,118), c(30,30), type='l', lty=2, col='firebrick2')
mtext(side = 2, line = 3, expression(paste("Meiotic entry region length (", mu, "m)")), padj=1, cex=0.7)
mtext(side = 1, line = 3, "Time (hph)", padj=-0.5, cex=0.7)
mtext("(C)",3, at=15, padj=-0.5)
}
# UNCOMMENT FOR POSTSCRIPT OUTPUT-----------------------------------------------------------------------
# dev.off()
# embed_fonts("./GonadDataPrelim.eps", outfile = "./GonadData.eps",options = "-dEPSCrop")
#------------------------------------------------------------------------------------------------------
| /RScripts/plotGonadData.R | no_license | Katwell/ElegansGermline | R | false | false | 15,855 | r | # Plots some of the output of a C. elegans germline simulation, as recorded in the file gonadData.txt
#
# A NaN warning will be generated when this script runs, because the distance to the first meiotic cell
# is undefined before meiotic cells appear. Usually the warning can be safely ignored.
# UNCOMMENT HERE AND AT END OF FILE FOR POSTSCRIPT OUTPUT-----------------------------------------------
# library("extrafont")
# postscript("GonadDataPrelim.eps", height = 4.5, width = 6.83, family = "Arial", paper = "special", onefile = FALSE, horizontal = FALSE)
#------------------------------------------------------------------------------------------------------
#USER INPUT - FILL IN THESE FIELDS:
resultsDirectory = "../exampleOutput/production_2.8/"
plotMultipleFiles = TRUE # If true we plot the mean and standard deviation of gonadData.txt
# files from a collection of directories
fileNumbers = seq(0,29) # Input directories should be located under resultsDirectory and
# should be named <baseFileName> + <number>
baseFileName = ""
useManuallyCountedCellRows = TRUE # If true, manual cell row count data is expected to be
# provided in each results directory, in a file called
# ZoneLengths.txt (see our example data)
useManuallyCountedProlifCells = FALSE # If true, manual proliferative cell counts are expected
# to be provided in each results directory, in a file called
# CorrectedProlifCounts.txt (see our example data)
showMicronZoneLengths = FALSE # Whether to output the position of certain significant cells
# in microns from the DTC, in addition to cell rows
# from the DTC
nStandardDeviations = 1 # Number of standard deviations to shade either side of the mean
MAXTIME = 82 # Only plot simulations with data up to time 82. Useful for
# visualising incomplete sets of runs.
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
# SETUP GRAPH PROPERTIES AND GRAPH PLOTTING FUNCTIONS
if(showMicronZoneLengths){
rowsOfGraphs = 1
}else{
rowsOfGraphs = 2
}
par(mfrow=c(rowsOfGraphs,3), lwd=2, ps=12, bg="white", mar=c(5,5,5,5))
plotLarvalStageMarkers = function(ytop){
polygon(c(31.5,35.5,35.5,31.5), c(0,0,ytop,ytop), col=gray(0.8), lty=0)
segments(18.5,0,18.5, ytop, lty = 3,lwd = 1)
segments(26,0,26, ytop, lty = 3,lwd = 1)
segments(35.5,0,35.5, ytop, lty = 3,lwd = 1)
}
# LOOP THROUGH RESULTS FILES AND CALCULATE A MEAN AND STANDARD DEVIATION FOR EACH PIECE OF DATA
sum <-data.frame()
sumSquares<-data.frame()
count =0
if(!plotMultipleFiles){
fileNumbers = 0;
meandata = read.table(paste(resultsDirectory,baseFileName,"/results_from_time_0/GonadData.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
stddevdata = meandata - meandata #zero this out
}else{
for(n in fileNumbers){
dataCurrent<-read.table(paste(resultsDirectory,baseFileName,n,"/results_from_time_0/GonadData.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
print(length(dataCurrent$V1))
dataCurrent=dataCurrent[dataCurrent$V1 <= MAXTIME,]
if(sum(dataCurrent$V1<=MAXTIME)<MAXTIME){
}else{
count = count+1
if(length(sum)==0){
sum = dataCurrent;
sumSquares = dataCurrent^2;
timepoints = (dataCurrent$V1 + 18.5) # <- corrects for the fact that the simulation starts
# at 18.5 hrs post-hatching
}else{
sum = sum + dataCurrent;
sumSquares = sumSquares + dataCurrent^2;
}
}
}
meandata = sum / count;#length(fileNumbers);
stddevdata = sqrt((sumSquares/count) - meandata^2)#length(fileNumbers)) - meandata^2 );
print("No. runs = ")
print(count)
}
# READ IN MANUALLY COUNTED CELL ROW MEASUREMENTS IF REQUESTED. THE ALTERNATIVE IS TO TRUST THE SIMULATION'S
# BUILT IN CELL ROW COUNTING ALGORITHM (USUALLY UNDERESTIMATES THE TRUE ROW NUMBER)
if(useManuallyCountedCellRows){
if(!plotMultipleFiles){
rowData <- read.table(paste(resultsDirectory,baseFileName,"/ZoneLengths.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
rowTimePoints = rowData[,1]
rowMeioticMean = rowData[,2]
rowMitoticMean = rowData[,3]
rowMeioticStd = rowMeioticMean - rowMeioticMean
rowMitoticStd = rowMitoticMean - rowMitoticMean
}else{
for(n in fileNumbers){
rowDataCurrent <- read.table(paste(resultsDirectory,baseFileName,n,"/ZoneLengths.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
rowTimePoints = rowDataCurrent[,1] + 18.5
if(n == fileNumbers[1]){
rowMeioticMean = rowDataCurrent[,2]
rowMitoticMean = rowDataCurrent[,3]
rowMeioticSquare = rowDataCurrent[,2]*rowDataCurrent[,2]
rowMitoticSquare = rowDataCurrent[,3]*rowDataCurrent[,3]
}else{
rowMeioticMean = rowMeioticMean + rowDataCurrent[,2]
rowMitoticMean = rowMitoticMean + rowDataCurrent[,3]
rowMeioticSquare = rowMeioticSquare + rowDataCurrent[,2]*rowDataCurrent[,2]
rowMitoticSquare = rowMitoticSquare + rowDataCurrent[,3]*rowDataCurrent[,3]
}
}
rowMeioticMean = rowMeioticMean/length(fileNumbers)
rowMitoticMean = rowMitoticMean/length(fileNumbers)
rowMeioticStd = sqrt((rowMeioticSquare/length(fileNumbers)) - rowMeioticMean*rowMeioticMean)
rowMitoticStd = sqrt((rowMitoticSquare/length(fileNumbers)) - rowMitoticMean*rowMitoticMean)
}
}
# READ IN MANUAL PROLIFERATIVE CELL COUNTS IF REQUESTED. THE SIMULATION COUNTS ALL NON-MEIOTIC CELLS AS
# PROLIFERATIVE BY DEFAULT. MANUAL COUNTS MADE IN PARAVIEW CAN BE PROVIDED INSTEAD, FOR EXAMPLE, TO BETTER
# MIMIC THE WAY PROLIFERATIVE CELLS ARE COUNTED EXPERIMENTALLY (counting stops after first row containing
# 2 meiotic cells)
if(useManuallyCountedProlifCells){
if(!plotMultipleFiles){
cellDataMean <- read.table(paste(resultsDirectory,baseFileName,"/CorrectedProlifCounts.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
cellTimePoints = cellDataMean$V1
cellDataStd = cellDataMean - cellDataMean
}else{
for(n in fileNumbers){
cellDataCurrent <- read.table(paste(resultsDirectory,baseFileName,n,"/CorrectedProlifCounts.txt",sep=""), as.is=TRUE, header=FALSE, sep="\t");
cellTimePoints = cellDataCurrent$V1 + 18.5
if(n == fileNumbers[1]){
cellDataMean = cellDataCurrent$V2
cellDataSquare = (cellDataCurrent$V2)*(cellDataCurrent$V2)
}else{
cellDataMean = cellDataMean+cellDataCurrent$V2
cellDataSquare = cellDataSquare+(cellDataCurrent$V2)*(cellDataCurrent$V2)
}
}
cellDataMean = cellDataMean/length(fileNumbers)
cellDataStd = sqrt((cellDataSquare/length(fileNumbers)) - cellDataMean*cellDataMean)
}
}
if(!showMicronZoneLengths){
#PLOT TOTAL CELLS, +- 2 STDDEV
ytop = max(meandata$V7 + nStandardDeviations*stddevdata[,7])*1.05 # <- max y
plot(0,0, xlab='Time (hph)', ylab="Total cells (count)", xlim=c(18.5,100), ylim=c(0,ytop)) # <- initialise plot
plotLarvalStageMarkers(ytop)
polygon(c(timepoints, rev(timepoints)), c(meandata$V7 + nStandardDeviations*stddevdata[,7], rev(meandata$V7 - nStandardDeviations*stddevdata[,7]) ), col=gray(0.4), lty=0) # <- confidence region
points(timepoints, meandata$V7, type='l') # <- simulated mean
points(c(0,2.5,5.5,7.5,11.5,12.5,17)+18.5, c(16,40,63,110,154,177,308), type='l', col='firebrick2', lty=1) # <- experimental result
mtext("(A)", 3, at=15, padj=-0.5)
print(timepoints)
print(meandata$V7)
#PLOT PROLIFERATIVE CELLS, +- 2 STDDEV
if(useManuallyCountedProlifCells){
ytop = max(cellDataMean + nStandardDeviations*cellDataStd)*1.05
plot(0,0, xlab='Time (hph)', ylab="Proliferative cells (count)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(cellTimePoints, rev(cellTimePoints)), c(cellDataMean + nStandardDeviations*cellDataStd, rev(cellDataMean - nStandardDeviations*cellDataStd)), col=gray(0.4),lty=0)
points(cellTimePoints, cellDataMean, type='l')
}else{
ytop = max(meandata$V5 + nStandardDeviations*stddevdata[,5])*1.05
plot(0,0, xlab='Time (hph)', ylab="Proliferative cells (count)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V5 + nStandardDeviations*stddevdata[,5], rev(meandata$V5 - nStandardDeviations*stddevdata[,5])), col=gray(0.4),lty=0)
points(timepoints, meandata$V5, type='l')
}
points(c(0,2.5,5.5,7.5,11.5,12.5,17)+18.5, c(16,40,63,103,126,134,204), type='l', lty=1, col='firebrick2')
points(c(35.5,41.5,48.5,62.5,91.5), c(201,244,251,220,157), type='l', lty=1, col='firebrick2')
mtext("(B)", 3, at=15, padj=-0.5)
#PLOT SPERM COUNT, +- 2 STDDEV
ytop = max((meandata$V4 + nStandardDeviations*stddevdata[,4]),140)*1.05
plot(0,0, xlab='Time (hph)', ylab="Sperm cells (count)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V4 + nStandardDeviations*stddevdata[,4], rev(meandata$V4 - nStandardDeviations*stddevdata[,4])), col=gray(0.4), lty=0)
points(timepoints, meandata$V4, type='l')
points(c(0,2.5,5.5,7.5,11.5,12.5,17,19.5)+18.5, c(0,0,0,0,4,41,85,140), type='l', lty=1, col='firebrick2')
points(seq(19.5,118,by=0.1)+18.5, 140-2.7*(seq(19.5,118,by=0.1)-19.5), type='l', lty=2, col='firebrick2')
mtext("(C)", 3, at=15, padj=-0.5)
print(meandata$V4)
#PLOT ORGAN LENGTH, +- 2 STDDEV
ytop = max((meandata$V2 + nStandardDeviations*stddevdata[,2]),405)*1.05
plot(0,0, xlab='Time (hph)', type='l', ylab=expression(paste("Length of gonad arm (", mu, "m)")), xlim=c(18.5,118.5), ylim =c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V2 + nStandardDeviations*stddevdata[,2], rev(meandata$V2 - nStandardDeviations*stddevdata[,2])), col=gray(0.4), lty=0)
points(timepoints, meandata$V2, type='l')
points(c(18.5,22,26,31,35.5), c(32,61.7,91.4,198,405), lty=1, col="firebrick2", type='l')
points(c(35.5,118), c(405,405), lty=2, col="firebrick2", type='l')
mtext("(D)",3, at=15, padj=-0.5)
# PLOT CELL ROW DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
# NOTE: the automated row counting algorithm in our code counts the endcap as one row. We therefore add 2 to the output
# to correct for this systematic error (the endcap usually contains about 3 cell rows by eye).
if(useManuallyCountedCellRows){
ytop = 35#max(rowMeioticMean + nStandardDeviations*rowMeioticStd)*1.05
plot(0,0, xlab='Time (hph)', ylab="Distance to 1st row containing\n >1 meiotic cell (CD)", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(rowTimePoints,rev(rowTimePoints)), c(rowMeioticMean-nStandardDeviations*rowMeioticStd, rev(rowMeioticMean+nStandardDeviations*rowMeioticStd)), col=gray(0.4), lty=0)
points(rowTimePoints, rowMeioticMean, type='l')
}else{
ytop = max(meandata$V15[meandata$V1>10] + stddevdata[,15][meandata$V1>10])*1.05
plot(0,0, xlab='Time (hph)', ylab="1st row containing two meiotic cells", xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V15+2 + nStandardDeviations*stddevdata[,15], rev(meandata$V15+2 - nStandardDeviations*stddevdata[,15])), col=gray(0.4), lty=0)
points(timepoints, meandata$V15+2, type='l')
}
points(c(35.5,118), c(20,20), type='l', lty=2, col='firebrick2')
mtext("(E)",3, at=15, padj=-0.5)
#PLOT CELL ROW DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
#NOTE: the automated row counting algorithm in our code counts the endcap as one row. We therefore add 2 to the output
#to correct for this systematic error (the endcap usually contains about 3 cell rows by eye).
if(useManuallyCountedCellRows){
ytop = 35#max(rowMitoticMean + nStandardDeviations*rowMitoticStd)*1.05
plot(0,0,xlab='Time (hph)',ylab=expression(paste("Distance to last row containing\n a proliferative cell (CD)")),xlim=c(18.5,100),ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(rowTimePoints, rev(rowTimePoints)), c(rowMitoticMean-nStandardDeviations*rowMitoticStd,rev(rowMitoticMean+nStandardDeviations*rowMitoticStd)), col=gray(0.4), lty=0)
points(rowTimePoints, rowMitoticMean, type='l')
}else{
ytop = max(meandata$V16 + nStandardDeviations*stddevdata[,16])*1.05
plot(0,0,xlab='Time (hph)',ylab=expression(paste("Last row containing a prolif. cell")),xlim=c(18.5,100),ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V16+2 + nStandardDeviations*stddevdata[,16], rev(meandata$V16+2 - nStandardDeviations*stddevdata[,16])), col=gray(0.4), lty=0)
points(timepoints, meandata$V16+2, type='l')
}
points(c(35.5,118), c(28,28), type='l',lty=2,col='firebrick2')
mtext("(F)",3, at=15, padj=-0.5)
}else{
#PLOT MICRON DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
ytop = max(meandata$V8 + nStandardDeviations*stddevdata[,8])*1.05
plot(0,0, ann=FALSE, xlab='Time (hph)', ylab=expression(paste("Furthest mitotic cell from DTC (", mu, "m)")), xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints,rev(timepoints)), c(meandata$V8 + nStandardDeviations*stddevdata[,8], rev(meandata$V8 - nStandardDeviations*stddevdata[,8])), col=gray(0.4),lty=0)
points(timepoints, meandata$V8, type='l')
points(c(35.5,118), c(70,70), type='l', lty=2, col='firebrick2')
mtext(side = 2, line = 3, expression(paste("Furthest mitotic cell from DTC (", mu, "m)")), padj=1, cex=0.7)
mtext(side = 1, line = 3, "Time (hph)", padj=-0.5, cex=0.7)
mtext("(A)", 3, at=15, padj=-0.5)
#PLOT MICRON DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
ytop = max(meandata$V9[meandata$V9<1000] + nStandardDeviations*stddevdata[,9][meandata$V9<1000])*1.05
plot(0,0, ann=FALSE, xlab='Time (hph)', ylab=expression(paste("Closest meiotic cell to DTC (", mu, "m)")), xlim=c(18.5,100), ylim=c(0,ytop))
plotLarvalStageMarkers(ytop)
polygon(c(timepoints[meandata$V9<1000],rev(timepoints[meandata$V9<1000])), c(meandata$V9[meandata$V9<1000] + nStandardDeviations*stddevdata[meandata$V9<1000,9],
rev(meandata$V9[meandata$V9<1000] - nStandardDeviations*stddevdata[meandata$V9<1000,9])),col=gray(0.4),lty=0)
points(timepoints[meandata$V9<1000], meandata$V9[meandata$V9<1000], type='l')
points(c(35.5,118), c(40,40), type='l', lty=2, col='firebrick2')
mtext(side = 2, line = 3, expression(paste("Closest meiotic cell to DTC (", mu, "m)")), padj=1, cex=0.7)
mtext(side = 1, line = 3, "Time (hph)", padj=-0.5, cex=0.7)
mtext("(B)",3, at=15, padj=-0.5)
#PLOT MICRON DISTANCES TO POINTS OF INTEREST, +- 2 STDDEV
ytop = max(meandata$V8[meandata$V9<1000] - meandata$V9[meandata$V9<1000])*1.05
plot(0,0, ann=FALSE, xlab='Time (hph)', ylab=expression(paste("Meiotic entry region length (", mu, "m)")), xlim=c(18.5,100), ylim=c(0,ytop))
variance = stddevdata^2;
combined=nStandardDeviations*sqrt(variance[,8] + variance[,9])
plotLarvalStageMarkers(ytop)
polygon(c(timepoints[!is.nan(combined)],rev(timepoints[!is.nan(combined)])),
c(meandata$V8[!is.nan(combined)]-meandata$V9[!is.nan(combined)] + combined[!is.nan(combined)],
rev(meandata$V8[!is.nan(combined)]-meandata$V9[!is.nan(combined)] - combined[!is.nan(combined)])), col=gray(0.4),lty=0)
points(timepoints[meandata$V9<1000], meandata$V8[meandata$V9<1000] - meandata$V9[meandata$V9<1000],type='l')
points(c(35.5,118), c(30,30), type='l', lty=2, col='firebrick2')
mtext(side = 2, line = 3, expression(paste("Meiotic entry region length (", mu, "m)")), padj=1, cex=0.7)
mtext(side = 1, line = 3, "Time (hph)", padj=-0.5, cex=0.7)
mtext("(C)",3, at=15, padj=-0.5)
}
# UNCOMMENT FOR POSTSCRIPT OUTPUT-----------------------------------------------------------------------
# dev.off()
# embed_fonts("./GonadDataPrelim.eps", outfile = "./GonadData.eps",options = "-dEPSCrop")
#------------------------------------------------------------------------------------------------------
|
library(quantmod)
library(lubridate)
library(e1071)
library(rpart)
library(rpart.plot)
library(ROCR)
options(warn = -1)
library("quantmod")
SYM2 <- 'CVS'
print(paste('Predicting the output for', SYM, sep = ' '))
startDate = as.Date("1990-01-01")
endDate = as.Date("2020-11-01")
STOCK2 <- getSymbols(
SYM2,
src = "yahoo",
from = startDate,
to = endDate
)
RSICvs <- RSI(Op(CVS), n = 3)
#Calculate a 3-period relative strength index (RSI) off the open price
EMA5Cvs <- EMA(Op(CVS), n = 5)
#Calculate a 5-period exponential moving average (EMA)
EMAcrossCvs <- Op(CVS) - EMA5Cvs
#Let us explore the difference between the open price and our 5-period EMA
MACDCvs <- MACD(Op(CVS),
fast = 12,
slow = 26,
signal = 9)
#Calculate a MACD with standard parameters
MACDCvs <- MACDCvs[, 2]
#Grab just the signal line to use as our indicator.
SMICvs <- SMI(
Op(CVS),
n = 13,
slow = 25,
fast = 2,
signal = 9
)
#Stochastic Oscillator with standard parameters
SMICvs <- SMICvs[, 1]
#Grab just the oscillator to use as our indicator
WPRCvs <- WPR(Cl(CVS), n = 14)
WPRCvs <- WPRCvs[, 1]
#Williams %R with standard parameters
ADXCvs <- ADX(CVS, n = 14)
ADXCvs <- ADXCvs[, 1]
#Average Directional Index with standard parameters
CCICvs <- CCI(Cl(CVS), n = 14)
CCICvs <- CCICvs[, 1]
#Commodity Channel Index with standard parameters
CMOCvs <- CMO(Cl(CVS), n = 14)
CMOCvs <- CMOCvs[, 1]
#Collateralized Mortgage Obligation with standard parameters
ROCCvs <- ROC(Cl(CVS), n = 2)
ROCCvs <- ROCCvs[, 1]
#Price Rate Of Change with standard parameters
PriceChangeCvs <- Cl(CVS) - Op(CVS)
#Calculate the difference between the close price and open price
ClassCvs <- ifelse(PriceChangeCvs > 0, 'UP', 'DOWN')
#Create a binary classification variable, the variable we are trying to predict
DataSetCvs <-
data.frame(ClassCvs, RSICvs, EMAcrossCvs, MACDCvs, SMICvs, WPRCvs, ADXCvs, CCICvs, CMOCvs, ROCCvs)
#Create our data set
colnames(DataSetCvs) <-
c("Class",
"RSI",
"EMAcross",
"MACD",
"SMI",
"WPR",
"ADX",
"CCI",
"CMO",
"ROC")
#Name the columns
#DataSet <- DataSet[-c(1:33), ]
#Get rid of the data where the indicators are being calculated
SYM1 <- 'MSFT'
print(paste('Predicting the output for', SYM1, sep = ' '))
STOCK1 <- getSymbols(
SYM1,
src = "yahoo",
from = startDate,
to = endDate
)
RSIMicrosoft <- RSI(Op(MSFT), n = 3)
#Calculate a 3-period relative strength index (RSI) off the open price
EMA5Microsoft <- EMA(Op(MSFT), n = 5)
#Calculate a 5-period exponential moving average (EMA)
EMAcrossMicrosoft <- Op(MSFT) - EMA5Microsoft
#Let us explore the difference between the open price and our 5-period EMA
MACDMicrosoft <- MACD(Op(MSFT),
fast = 12,
slow = 26,
signal = 9)
#Calculate a MACD with standard parameters
MACDMicrosoft <- MACDMicrosoft[, 2]
#Grab just the signal line to use as our indicator.
SMIMicrosoft <- SMI(
Op(MSFT),
n = 13,
slow = 25,
fast = 2,
signal = 9
)
#Stochastic Oscillator with standard parameters
SMIMicrosoft <- SMIMicrosoft[, 1]
#Grab just the oscillator to use as our indicator
WPRMicrosoft <- WPR(Cl(MSFT), n = 14)
Microsoft <- WPRMicrosoft[, 1]
#Williams %R with standard parameters
ADXMicrosoft <- ADX(MSFT, n = 14)
ADXMicrosoft <- ADXMicrosoft[, 1]
#Average Directional Index with standard parameters
CCIMicrosoft <- CCI(Cl(MSFT), n = 14)
CCIMicrosoft <- CCIMicrosoft[, 1]
#Commodity Channel Index with standard parameters
CMOMicrosoft <- CMO(Cl(MSFT), n = 14)
CMOMicrosoft <- CMOMicrosoft[, 1]
#Collateralized Mortgage Obligation with standard parameters
ROCMicrosoft <- ROC(Cl(MSFT), n = 2)
ROCMicrosoft <- ROCMicrosoft[, 1]
#Price Rate Of Change with standard parameters
PriceChangeMicrosoft <- Cl(MSFT) - Op(MSFT)
#Calculate the difference between the close price and open price
ClassMicrosoft <- ifelse(PriceChangeMicrosoft > 0, 'UP', 'DOWN')
#Create a binary classification variable, the variable we are trying to pre
#dict.
DataSetMicrosoft <-
data.frame(ClassMicrosoft, RSIMicrosoft, EMAcrossMicrosoft, MACDMicrosoft, SMIMicrosoft, WPRMicrosoft, ADXMicrosoft, CCIMicrosoft, CMOMicrosoft, ROCMicrosoft)
#Create our data set
colnames(DataSetMicrosoft) <-
c("Class",
"RSI",
"EMAcross",
"MACD",
"SMI",
"WPR",
"ADX",
"CCI",
"CMO",
"ROC")
#Name the columns
#DataSet <- DataSetMicrosoft[-c(1:33), ]
#Get rid of the data where the indicators are being calculated
SYM3 <- 'WMT'
print(paste('Predicting the output for', SYM, sep = ' '))
STOCK3 <- getSymbols(
SYM3,
src = "yahoo",
from = startDate,
to = endDate
)
RSIWalmart <- RSI(Op(WMT), n = 3)
#Calculate a 3-period relative strength index (RSI) off the open price
EMA5Walmart <- EMA(Op(WMT), n = 5)
#Calculate a 5-period exponential moving average (EMA)
EMAcrossWalmart <- Op(WMT) - EMA5
#Let us explore the difference between the open price and our 5-period EMA
MACDWalmart <- MACD(Op(WMT),
fast = 12,
slow = 26,
signal = 9)
#Calculate a MACD with standard parameters
MACDWalmart <- MACDWalmart[, 2]
#Grab just the signal line to use as our indicator.
SMIWalmart <- SMI(
Op(WMT),
n = 13,
slow = 25,
fast = 2,
signal = 9
)
#Stochastic Oscillator with standard parameters
SMIWalmart <- SMIWalmart[, 1]
#Grab just the oscillator to use as our indicator
WPRWalmart <- WPR(Cl(WMT), n = 14)
WPRWalmart <- WPRWalmart[, 1]
#Williams %R with standard parameters
ADXWalmart <- ADX(WMT, n = 14)
ADXWalmart <- ADXWalmart[, 1]
#Average Directional Index with standard parameters
CCIWalmart <- CCI(Cl(WMT), n = 14)
CCIWalmart <- CCIWalmart[, 1]
#Commodity Channel Index with standard parameters
CMOWalmart <- CMO(Cl(WMT), n = 14)
CMOWalmart <- CMOWalmart[, 1]
#Collateralized Mortgage Obligation with standard parameters
ROCWalmart <- ROC(Cl(WMT), n = 2)
ROCWalmart <- ROCWalmart[, 1]
#Price Rate Of Change with standard parameters
PriceChangeWalmart <- Cl(WMT) - Op(WMT)
#Calculate the difference between the close price and open price
ClassWalmart <- ifelse(PriceChangeWalmart > 0, 'UP', 'DOWN')
#Create a binary classification variable, the variable we are trying to pre
#dict.
DataSetWalmart <-
data.frame(ClassWalmart, RSIWalmart, EMAcrossWalmart, MACDWalmart, SMIWalmart, WPRWalmart, ADXWalmart, CCIWalmart, CMOWalmart, ROCWalmart)
#Create our data set
colnames(DataSetWalmart) <-
c("Class",
"RSI",
"EMAcross",
"MACD",
"SMI",
"WPR",
"ADX",
"CCI",
"CMO",
"ROC")
#Name the columns
#DataSet <- DataSetWalmart[-c(1:33), ]
#Get rid of the data where the indicators are being calculated
ncol(DataSetMicrosoft)
ncol(DataSetCvs)
ncol(DataSetWalmart)
combinedDfs <- rbind(DataSetMicrosoft, DataSetCvs,DataSetWalmart)
combinedDfs <- rbind(DataSetMicrosoft)
combinedDfs$Class <- as.factor(combinedDfs$Class)
combinedDfs$RSI <- as.numeric(combinedDfs$RSI)
combinedDfs$ROC <- as.numeric(combinedDfs$ROC)
combinedDfs$CMO <- as.numeric(combinedDfs$CMO)
combinedDfs$CCI <- as.numeric(combinedDfs$CCI)
combinedDfs$EMAcross <- as.numeric(combinedDfs$EMAcross)
combinedDfs$MACD <- as.numeric(combinedDfs$MACD)
combinedDfs$SMI <- as.numeric(combinedDfs$SMI)
combinedDfs$WPR <- as.numeric(combinedDfs$WPR)
combinedDfs$ADX <- as.numeric(combinedDfs$ADX)
combinedDfs[is.na(combinedDfs$RSI), "RSI"] <- 0
combinedDfs[is.na(combinedDfs$ROC), "ROC"] <- 0
combinedDfs[is.na(combinedDfs$CMO), "CMO"] <- 0
combinedDfs[is.na(combinedDfs$CCI), "CCI"] <- 0
combinedDfs[is.na(combinedDfs$EMAcross), "EMAcross"] <- 0
combinedDfs[is.na(combinedDfs$MACD), "MACD"] <- 0
combinedDfs[is.na(combinedDfs$SMI), "SMI"] <- 0
combinedDfs[is.na(combinedDfs$WPR), "WPR"] <- 0
combinedDfs[is.na(combinedDfs$ADX), "ADX"] <- 0
set.seed(212)
trainIndexSVM <- createDataPartition(combinedDfs$Class, p = 0.8, list=FALSE, times=3)
subTrainSVM <- combinedDfs[trainIndexSVM,]
subTestSVM <- combinedDfs[-trainIndexSVM,]
# SVM Classifier using Linear Kernel
trctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 2)
set.seed(323)
grid <- expand.grid(C = c( 0.25, 0.5, 1))
svm_Linear_Grid <- train( Class ~ RSI + EMAcross + WPR + ADX + CMO + CCI + ROC, data = subTrainSVM, method = "svmLinear",
trControl=trctrl, preProcess = c("center", "scale"),
tuneGrid = grid,
tuneLength = 10)
svm_Linear_Grid
plot(svm_Linear_Grid)
predictionsvm <- predict(svm_Linear_Grid, subTestSVM[-1])
table(predictionsvm, subTestSVM$Class)
accuracysvm <- sum(predictionsvm == (subTestSVM$Class))/length(subTestSVM$Class)
print(accuracysvm)
#confusionNNSvm <-confusionMatrix(as.factor(predictionsvm),as.factor(subTestSVM$Term_Deposit))
#print(confusionNNSvm)
# SVM Classifier using Non-Linear Kernel
set.seed(323)
grid_radial <- expand.grid(sigma = c(0.25, 0.5,0.9),
C = c(0.25, 0.5,1))
svm_Radial <- train(Class ~ RSI + EMAcross + WPR + ADX + CMO + CCI + ROC, data = subTrainSVM, method = "svmRadial",
trControl=trctrl,
preProcess = c("center", "scale"),tuneGrid = grid_radial,
tuneLength = 10)
svm_Radial
predictionnonlinearsvm <- predict(svm_Radial, subTestSVM[-14])
accuracynonlinearsvm <- sum(predictionnonlinearsvm == (subTestSVM$Class))/length(subTestSVM$Class)
print(accuracynonlinearsvm)
algo_results <- resamples(list(SVM_RADIAL=svm_Radial, SVM_LINEAR=svm_Linear_Grid))
summary(algo_results)
scales <- list(x=list(relation="free"), y=list(relation="free"))
bwplot(algo_results, scales=scales)
splom(algo_results)
| /MLScripts/SVM.R | no_license | nselvar/RealTimeMLStockMarketAnalysis | R | false | false | 9,691 | r | library(quantmod)
library(lubridate)
library(e1071)
library(rpart)
library(rpart.plot)
library(ROCR)
options(warn = -1)
library("quantmod")
SYM2 <- 'CVS'
print(paste('Predicting the output for', SYM, sep = ' '))
startDate = as.Date("1990-01-01")
endDate = as.Date("2020-11-01")
STOCK2 <- getSymbols(
SYM2,
src = "yahoo",
from = startDate,
to = endDate
)
RSICvs <- RSI(Op(CVS), n = 3)
#Calculate a 3-period relative strength index (RSI) off the open price
EMA5Cvs <- EMA(Op(CVS), n = 5)
#Calculate a 5-period exponential moving average (EMA)
EMAcrossCvs <- Op(CVS) - EMA5Cvs
#Let us explore the difference between the open price and our 5-period EMA
MACDCvs <- MACD(Op(CVS),
fast = 12,
slow = 26,
signal = 9)
#Calculate a MACD with standard parameters
MACDCvs <- MACDCvs[, 2]
#Grab just the signal line to use as our indicator.
SMICvs <- SMI(
Op(CVS),
n = 13,
slow = 25,
fast = 2,
signal = 9
)
#Stochastic Oscillator with standard parameters
SMICvs <- SMICvs[, 1]
#Grab just the oscillator to use as our indicator
WPRCvs <- WPR(Cl(CVS), n = 14)
WPRCvs <- WPRCvs[, 1]
#Williams %R with standard parameters
ADXCvs <- ADX(CVS, n = 14)
ADXCvs <- ADXCvs[, 1]
#Average Directional Index with standard parameters
CCICvs <- CCI(Cl(CVS), n = 14)
CCICvs <- CCICvs[, 1]
#Commodity Channel Index with standard parameters
CMOCvs <- CMO(Cl(CVS), n = 14)
CMOCvs <- CMOCvs[, 1]
#Collateralized Mortgage Obligation with standard parameters
ROCCvs <- ROC(Cl(CVS), n = 2)
ROCCvs <- ROCCvs[, 1]
#Price Rate Of Change with standard parameters
PriceChangeCvs <- Cl(CVS) - Op(CVS)
#Calculate the difference between the close price and open price
ClassCvs <- ifelse(PriceChangeCvs > 0, 'UP', 'DOWN')
#Create a binary classification variable, the variable we are trying to predict
DataSetCvs <-
data.frame(ClassCvs, RSICvs, EMAcrossCvs, MACDCvs, SMICvs, WPRCvs, ADXCvs, CCICvs, CMOCvs, ROCCvs)
#Create our data set
colnames(DataSetCvs) <-
c("Class",
"RSI",
"EMAcross",
"MACD",
"SMI",
"WPR",
"ADX",
"CCI",
"CMO",
"ROC")
#Name the columns
#DataSet <- DataSet[-c(1:33), ]
#Get rid of the data where the indicators are being calculated
SYM1 <- 'MSFT'
print(paste('Predicting the output for', SYM1, sep = ' '))
STOCK1 <- getSymbols(
SYM1,
src = "yahoo",
from = startDate,
to = endDate
)
RSIMicrosoft <- RSI(Op(MSFT), n = 3)
#Calculate a 3-period relative strength index (RSI) off the open price
EMA5Microsoft <- EMA(Op(MSFT), n = 5)
#Calculate a 5-period exponential moving average (EMA)
EMAcrossMicrosoft <- Op(MSFT) - EMA5Microsoft
#Let us explore the difference between the open price and our 5-period EMA
MACDMicrosoft <- MACD(Op(MSFT),
fast = 12,
slow = 26,
signal = 9)
#Calculate a MACD with standard parameters
MACDMicrosoft <- MACDMicrosoft[, 2]
#Grab just the signal line to use as our indicator.
SMIMicrosoft <- SMI(
Op(MSFT),
n = 13,
slow = 25,
fast = 2,
signal = 9
)
#Stochastic Oscillator with standard parameters
SMIMicrosoft <- SMIMicrosoft[, 1]
#Grab just the oscillator to use as our indicator
WPRMicrosoft <- WPR(Cl(MSFT), n = 14)
Microsoft <- WPRMicrosoft[, 1]
#Williams %R with standard parameters
ADXMicrosoft <- ADX(MSFT, n = 14)
ADXMicrosoft <- ADXMicrosoft[, 1]
#Average Directional Index with standard parameters
CCIMicrosoft <- CCI(Cl(MSFT), n = 14)
CCIMicrosoft <- CCIMicrosoft[, 1]
#Commodity Channel Index with standard parameters
CMOMicrosoft <- CMO(Cl(MSFT), n = 14)
CMOMicrosoft <- CMOMicrosoft[, 1]
#Collateralized Mortgage Obligation with standard parameters
ROCMicrosoft <- ROC(Cl(MSFT), n = 2)
ROCMicrosoft <- ROCMicrosoft[, 1]
#Price Rate Of Change with standard parameters
PriceChangeMicrosoft <- Cl(MSFT) - Op(MSFT)
#Calculate the difference between the close price and open price
ClassMicrosoft <- ifelse(PriceChangeMicrosoft > 0, 'UP', 'DOWN')
#Create a binary classification variable, the variable we are trying to pre
#dict.
DataSetMicrosoft <-
data.frame(ClassMicrosoft, RSIMicrosoft, EMAcrossMicrosoft, MACDMicrosoft, SMIMicrosoft, WPRMicrosoft, ADXMicrosoft, CCIMicrosoft, CMOMicrosoft, ROCMicrosoft)
#Create our data set
colnames(DataSetMicrosoft) <-
c("Class",
"RSI",
"EMAcross",
"MACD",
"SMI",
"WPR",
"ADX",
"CCI",
"CMO",
"ROC")
#Name the columns
#DataSet <- DataSetMicrosoft[-c(1:33), ]
#Get rid of the data where the indicators are being calculated
SYM3 <- 'WMT'
print(paste('Predicting the output for', SYM, sep = ' '))
STOCK3 <- getSymbols(
SYM3,
src = "yahoo",
from = startDate,
to = endDate
)
RSIWalmart <- RSI(Op(WMT), n = 3)
#Calculate a 3-period relative strength index (RSI) off the open price
EMA5Walmart <- EMA(Op(WMT), n = 5)
#Calculate a 5-period exponential moving average (EMA)
EMAcrossWalmart <- Op(WMT) - EMA5
#Let us explore the difference between the open price and our 5-period EMA
MACDWalmart <- MACD(Op(WMT),
fast = 12,
slow = 26,
signal = 9)
#Calculate a MACD with standard parameters
MACDWalmart <- MACDWalmart[, 2]
#Grab just the signal line to use as our indicator.
SMIWalmart <- SMI(
Op(WMT),
n = 13,
slow = 25,
fast = 2,
signal = 9
)
#Stochastic Oscillator with standard parameters
SMIWalmart <- SMIWalmart[, 1]
#Grab just the oscillator to use as our indicator
WPRWalmart <- WPR(Cl(WMT), n = 14)
WPRWalmart <- WPRWalmart[, 1]
#Williams %R with standard parameters
ADXWalmart <- ADX(WMT, n = 14)
ADXWalmart <- ADXWalmart[, 1]
#Average Directional Index with standard parameters
CCIWalmart <- CCI(Cl(WMT), n = 14)
CCIWalmart <- CCIWalmart[, 1]
#Commodity Channel Index with standard parameters
CMOWalmart <- CMO(Cl(WMT), n = 14)
CMOWalmart <- CMOWalmart[, 1]
#Collateralized Mortgage Obligation with standard parameters
ROCWalmart <- ROC(Cl(WMT), n = 2)
ROCWalmart <- ROCWalmart[, 1]
#Price Rate Of Change with standard parameters
PriceChangeWalmart <- Cl(WMT) - Op(WMT)
#Calculate the difference between the close price and open price
ClassWalmart <- ifelse(PriceChangeWalmart > 0, 'UP', 'DOWN')
#Create a binary classification variable, the variable we are trying to pre
#dict.
DataSetWalmart <-
data.frame(ClassWalmart, RSIWalmart, EMAcrossWalmart, MACDWalmart, SMIWalmart, WPRWalmart, ADXWalmart, CCIWalmart, CMOWalmart, ROCWalmart)
#Create our data set
colnames(DataSetWalmart) <-
c("Class",
"RSI",
"EMAcross",
"MACD",
"SMI",
"WPR",
"ADX",
"CCI",
"CMO",
"ROC")
#Name the columns
#DataSet <- DataSetWalmart[-c(1:33), ]
#Get rid of the data where the indicators are being calculated
ncol(DataSetMicrosoft)
ncol(DataSetCvs)
ncol(DataSetWalmart)
combinedDfs <- rbind(DataSetMicrosoft, DataSetCvs,DataSetWalmart)
combinedDfs <- rbind(DataSetMicrosoft)
combinedDfs$Class <- as.factor(combinedDfs$Class)
combinedDfs$RSI <- as.numeric(combinedDfs$RSI)
combinedDfs$ROC <- as.numeric(combinedDfs$ROC)
combinedDfs$CMO <- as.numeric(combinedDfs$CMO)
combinedDfs$CCI <- as.numeric(combinedDfs$CCI)
combinedDfs$EMAcross <- as.numeric(combinedDfs$EMAcross)
combinedDfs$MACD <- as.numeric(combinedDfs$MACD)
combinedDfs$SMI <- as.numeric(combinedDfs$SMI)
combinedDfs$WPR <- as.numeric(combinedDfs$WPR)
combinedDfs$ADX <- as.numeric(combinedDfs$ADX)
combinedDfs[is.na(combinedDfs$RSI), "RSI"] <- 0
combinedDfs[is.na(combinedDfs$ROC), "ROC"] <- 0
combinedDfs[is.na(combinedDfs$CMO), "CMO"] <- 0
combinedDfs[is.na(combinedDfs$CCI), "CCI"] <- 0
combinedDfs[is.na(combinedDfs$EMAcross), "EMAcross"] <- 0
combinedDfs[is.na(combinedDfs$MACD), "MACD"] <- 0
combinedDfs[is.na(combinedDfs$SMI), "SMI"] <- 0
combinedDfs[is.na(combinedDfs$WPR), "WPR"] <- 0
combinedDfs[is.na(combinedDfs$ADX), "ADX"] <- 0
set.seed(212)
trainIndexSVM <- createDataPartition(combinedDfs$Class, p = 0.8, list=FALSE, times=3)
subTrainSVM <- combinedDfs[trainIndexSVM,]
subTestSVM <- combinedDfs[-trainIndexSVM,]
# SVM Classifier using Linear Kernel
trctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 2)
set.seed(323)
grid <- expand.grid(C = c( 0.25, 0.5, 1))
svm_Linear_Grid <- train( Class ~ RSI + EMAcross + WPR + ADX + CMO + CCI + ROC, data = subTrainSVM, method = "svmLinear",
trControl=trctrl, preProcess = c("center", "scale"),
tuneGrid = grid,
tuneLength = 10)
svm_Linear_Grid
plot(svm_Linear_Grid)
predictionsvm <- predict(svm_Linear_Grid, subTestSVM[-1])
table(predictionsvm, subTestSVM$Class)
accuracysvm <- sum(predictionsvm == (subTestSVM$Class))/length(subTestSVM$Class)
print(accuracysvm)
#confusionNNSvm <-confusionMatrix(as.factor(predictionsvm),as.factor(subTestSVM$Term_Deposit))
#print(confusionNNSvm)
# SVM Classifier using Non-Linear Kernel
set.seed(323)
grid_radial <- expand.grid(sigma = c(0.25, 0.5,0.9),
C = c(0.25, 0.5,1))
svm_Radial <- train(Class ~ RSI + EMAcross + WPR + ADX + CMO + CCI + ROC, data = subTrainSVM, method = "svmRadial",
trControl=trctrl,
preProcess = c("center", "scale"),tuneGrid = grid_radial,
tuneLength = 10)
svm_Radial
predictionnonlinearsvm <- predict(svm_Radial, subTestSVM[-14])
accuracynonlinearsvm <- sum(predictionnonlinearsvm == (subTestSVM$Class))/length(subTestSVM$Class)
print(accuracynonlinearsvm)
algo_results <- resamples(list(SVM_RADIAL=svm_Radial, SVM_LINEAR=svm_Linear_Grid))
summary(algo_results)
scales <- list(x=list(relation="free"), y=list(relation="free"))
bwplot(algo_results, scales=scales)
splom(algo_results)
|
test_that("We can get sheets to skip", {
tool <- "Data Pack"
cop_year <- 2022
test_schema <- pick_schema(cop_year, tool)
this_skip <- getSkipSheets(test_schema, tool, cop_year)
expect_named(this_skip, c("package_skip", "num", "names")) })
flubSkippedSheets <- function(schema) {
schema %>% dplyr::filter(sheet_name != "Spectrum")
}
test_that("We can flag missing sheets which are skipped", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
#Simulate deleting the Spectrum tab
bad_schema <- flubSkippedSheets(ref_schema)
test_results <- checkSchema_SkippedSheets(bad_schema, tool, cop_year)
expect_true(length(test_results) > 0)
expect_named(test_results, c("error", "data"))
})
test_that("We can pass when all skip sheets are present in the schema", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_SkippedSheets(ref_schema, tool, cop_year)
expect_true(length(test_results) == 0)
expect_null(names(test_results))
})
test_that("We can pass when schema sheets are ordered sequentially", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_SheetNums(ref_schema)
expect_true(length(test_results) == 0)
expect_null(names(test_results))
})
test_that("We can flag when sheets are not ordered sequentially", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::filter(sheet_num != 2)
test_results <- checkSchema_SheetNums(bad_schema)
expect_true(length(test_results) > 0)
expect_named(test_results, c("error", "data"), ignore.order = TRUE)
})
test_that("We can pass when schema names match the package", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_SheetNames(ref_schema, ref_schema)
expect_true(length(test_results) == 0)
expect_null(names(test_results))
})
test_that("We can flag when sheet names do not match the reference schema", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::filter(sheet_num != 2)
test_results <- checkSchema_SheetNames(ref_schema, bad_schema)
expect_true(length(test_results) > 0)
expect_named(test_results, c("error", "data"), ignore.order = TRUE)
})
test_that("We can pass when data sets are valid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_InvalidDatasets(ref_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "data_structure", "col", "indicator_code", "dataset", "col_type"),
ignore.order = TRUE)
})
test_that("We can flag when data sets are invalid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(dataset = dplyr::case_when(col_type == "reference" ~ "foobar",
TRUE ~ dataset))
test_results <- checkSchema_InvalidDatasets(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "data_structure", "col", "indicator_code", "dataset", "col_type"),
ignore.order = TRUE)
# Skipped sheets should have no data set
this_skip <- getSkipSheets(ref_schema, tool, cop_year)
bad_schema <- ref_schema %>%
dplyr::mutate(dataset = dplyr::case_when(sheet_name %in% this_skip$names ~ "foobar",
TRUE ~ dataset))
test_results <- checkSchema_InvalidDatasets(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "data_structure", "col", "indicator_code", "dataset", "col_type"),
ignore.order = TRUE)
})
test_that("We can pass valid column types", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_InvalidColType(ref_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "data_structure", "col_type"),
ignore.order = TRUE)
})
flubColumnTypes <- function(schema) {
schema %>%
dplyr::mutate(col_type = dplyr::case_when(col_type == "reference" ~ "foobar",
TRUE ~ col_type))
}
test_that("We can flag when column types are invalid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- flubColumnTypes(ref_schema)
test_results <- checkSchema_InvalidColType(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "data_structure", "col_type"),
ignore.order = TRUE)
})
test_that("We can pass valid value types", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_InvalidValueType(ref_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "value_type"),
ignore.order = TRUE)
})
test_that("We can flag invalid value types", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(value_type = dplyr::case_when(value_type == "integer" ~ "foobar",
TRUE ~ value_type))
test_results <- checkSchema_InvalidValueType(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "value_type"),
ignore.order = TRUE)
})
test_that("We can pass valid ages", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_ValidAges(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can flag invalid ages", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
modify_age <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(name == "15-19" ~ "abc123", TRUE ~ name))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_ages = purrr::map(valid_ages, modify_age))
test_results <- checkSchema_ValidAges(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
modify_id <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(grepl("^tt", id) ~ "abc123", TRUE ~ id))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_ages = purrr::map(valid_ages, modify_id))
test_results <- checkSchema_ValidAges(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can pass valid sex identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_ValidSexes(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can flag invalid sexes", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
modify_males <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(name == "Male" ~ "Malez", TRUE ~ name))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_sexes = purrr::map(valid_sexes, modify_males))
test_results <- checkSchema_ValidSexes(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
modify_id <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, id = dplyr::case_when(name == "Male" ~ "abc123", TRUE ~ id))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_sexes = purrr::map(valid_sexes, modify_id))
test_results <- checkSchema_ValidSexes(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can pass valid KP identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_ValidKPs(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can flag KP identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
modify_pwid <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(name == "PWID" ~ "DIWP", TRUE ~ name))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_kps = purrr::map(valid_kps, modify_pwid))
test_results <- checkSchema_ValidKPs(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
modify_id <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, id = dplyr::case_when(name == "PWID" ~ "abc123", TRUE ~ id))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_kps = purrr::map(valid_kps, modify_id))
test_results <- checkSchema_ValidKPs(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can pass valid formulas", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_Formulas(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("col", "formula", "indicator_code", "sheet_name"),
ignore.order = TRUE)
})
test_that("We can flag invalid formulas´", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_formulas <- sample(seq_len(NROW(ref_schema)), 10)
ref_schema$formula[bad_formulas] <- "#REF"
test_results <- checkSchema_Formulas(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 10)
expect_named(test_results,
c("col", "formula", "indicator_code", "sheet_name"),
ignore.order = TRUE)
})
test_that("We can pass valid data element identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_DataElementSyntax(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(
test_results,
c(
"col",
"dataelement_dsd",
"dataelement_ta",
"dataset",
"indicator_code",
"invalid_DSD_DEs",
"invalid_TA_DEs",
"sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can flag invalid data elements´", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(dataelement_dsd = dplyr::case_when(col %% 4 == 0 ~ "foobar",
TRUE ~ dataelement_dsd),
dataelement_ta = dplyr::case_when(col %% 5 == 0 ~ "abc123",
TRUE ~ dataelement_ta))
test_results <- checkSchema_DataElementSyntax(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0)
expect_named(
test_results,
c(
"col",
"dataelement_dsd",
"dataelement_ta",
"dataset",
"indicator_code",
"invalid_DSD_DEs",
"invalid_TA_DEs",
"sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can pass valid category option identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_COsSyntax(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(
test_results,
c(
"categoryoption_specified", "col", "indicator_code", "invalid_COs", "sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can flag invalid data elements´", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(categoryoption_specified = dplyr::case_when(col %% 4 == 0 ~ "foobar",
TRUE ~ categoryoption_specified))
test_results <- checkSchema_COsSyntax(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0)
expect_named(
test_results,
c(
"categoryoption_specified", "col", "indicator_code", "invalid_COs", "sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can pass when a schema is valid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema(schema = ref_schema, cop_year = cop_year, tool = tool, season = "COP")
expect_true(length(test_results) == 0)
})
test_that("We can flag when a schema is invalid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
flubSkippedSheets(.) %>%
flubColumnTypes(.)
test_results <- checkSchema(schema = bad_schema, cop_year = cop_year, tool = tool, season = "COP")
expect_true(length(test_results) > 0)
})
| /tests/testthat/test-unPackSchema.R | permissive | pepfar-datim/datapackr | R | false | false | 15,226 | r |
test_that("We can get sheets to skip", {
tool <- "Data Pack"
cop_year <- 2022
test_schema <- pick_schema(cop_year, tool)
this_skip <- getSkipSheets(test_schema, tool, cop_year)
expect_named(this_skip, c("package_skip", "num", "names")) })
flubSkippedSheets <- function(schema) {
schema %>% dplyr::filter(sheet_name != "Spectrum")
}
test_that("We can flag missing sheets which are skipped", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
#Simulate deleting the Spectrum tab
bad_schema <- flubSkippedSheets(ref_schema)
test_results <- checkSchema_SkippedSheets(bad_schema, tool, cop_year)
expect_true(length(test_results) > 0)
expect_named(test_results, c("error", "data"))
})
test_that("We can pass when all skip sheets are present in the schema", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_SkippedSheets(ref_schema, tool, cop_year)
expect_true(length(test_results) == 0)
expect_null(names(test_results))
})
test_that("We can pass when schema sheets are ordered sequentially", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_SheetNums(ref_schema)
expect_true(length(test_results) == 0)
expect_null(names(test_results))
})
test_that("We can flag when sheets are not ordered sequentially", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::filter(sheet_num != 2)
test_results <- checkSchema_SheetNums(bad_schema)
expect_true(length(test_results) > 0)
expect_named(test_results, c("error", "data"), ignore.order = TRUE)
})
test_that("We can pass when schema names match the package", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_SheetNames(ref_schema, ref_schema)
expect_true(length(test_results) == 0)
expect_null(names(test_results))
})
test_that("We can flag when sheet names do not match the reference schema", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::filter(sheet_num != 2)
test_results <- checkSchema_SheetNames(ref_schema, bad_schema)
expect_true(length(test_results) > 0)
expect_named(test_results, c("error", "data"), ignore.order = TRUE)
})
test_that("We can pass when data sets are valid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_InvalidDatasets(ref_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "data_structure", "col", "indicator_code", "dataset", "col_type"),
ignore.order = TRUE)
})
test_that("We can flag when data sets are invalid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(dataset = dplyr::case_when(col_type == "reference" ~ "foobar",
TRUE ~ dataset))
test_results <- checkSchema_InvalidDatasets(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "data_structure", "col", "indicator_code", "dataset", "col_type"),
ignore.order = TRUE)
# Skipped sheets should have no data set
this_skip <- getSkipSheets(ref_schema, tool, cop_year)
bad_schema <- ref_schema %>%
dplyr::mutate(dataset = dplyr::case_when(sheet_name %in% this_skip$names ~ "foobar",
TRUE ~ dataset))
test_results <- checkSchema_InvalidDatasets(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "data_structure", "col", "indicator_code", "dataset", "col_type"),
ignore.order = TRUE)
})
test_that("We can pass valid column types", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_InvalidColType(ref_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "data_structure", "col_type"),
ignore.order = TRUE)
})
flubColumnTypes <- function(schema) {
schema %>%
dplyr::mutate(col_type = dplyr::case_when(col_type == "reference" ~ "foobar",
TRUE ~ col_type))
}
test_that("We can flag when column types are invalid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- flubColumnTypes(ref_schema)
test_results <- checkSchema_InvalidColType(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "data_structure", "col_type"),
ignore.order = TRUE)
})
test_that("We can pass valid value types", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_InvalidValueType(ref_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "value_type"),
ignore.order = TRUE)
})
test_that("We can flag invalid value types", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(value_type = dplyr::case_when(value_type == "integer" ~ "foobar",
TRUE ~ value_type))
test_results <- checkSchema_InvalidValueType(bad_schema, tool, cop_year)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "value_type"),
ignore.order = TRUE)
})
test_that("We can pass valid ages", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_ValidAges(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can flag invalid ages", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
modify_age <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(name == "15-19" ~ "abc123", TRUE ~ name))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_ages = purrr::map(valid_ages, modify_age))
test_results <- checkSchema_ValidAges(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
modify_id <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(grepl("^tt", id) ~ "abc123", TRUE ~ id))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_ages = purrr::map(valid_ages, modify_id))
test_results <- checkSchema_ValidAges(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can pass valid sex identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_ValidSexes(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can flag invalid sexes", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
modify_males <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(name == "Male" ~ "Malez", TRUE ~ name))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_sexes = purrr::map(valid_sexes, modify_males))
test_results <- checkSchema_ValidSexes(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
modify_id <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, id = dplyr::case_when(name == "Male" ~ "abc123", TRUE ~ id))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_sexes = purrr::map(valid_sexes, modify_id))
test_results <- checkSchema_ValidSexes(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can pass valid KP identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_ValidKPs(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can flag KP identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
modify_pwid <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, name = dplyr::case_when(name == "PWID" ~ "DIWP", TRUE ~ name))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_kps = purrr::map(valid_kps, modify_pwid))
test_results <- checkSchema_ValidKPs(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
modify_id <- function(x) {
if (is.null(x)) {
return(NULL)
}
dplyr::mutate(x, id = dplyr::case_when(name == "PWID" ~ "abc123", TRUE ~ id))
}
bad_schema <- ref_schema %>%
dplyr::mutate(valid_kps = purrr::map(valid_kps, modify_id))
test_results <- checkSchema_ValidKPs(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0L)
expect_named(test_results,
c("sheet_name", "col", "indicator_code", "name", "id"),
ignore.order = TRUE)
})
test_that("We can pass valid formulas", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_Formulas(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(test_results,
c("col", "formula", "indicator_code", "sheet_name"),
ignore.order = TRUE)
})
test_that("We can flag invalid formulas´", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_formulas <- sample(seq_len(NROW(ref_schema)), 10)
ref_schema$formula[bad_formulas] <- "#REF"
test_results <- checkSchema_Formulas(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 10)
expect_named(test_results,
c("col", "formula", "indicator_code", "sheet_name"),
ignore.order = TRUE)
})
test_that("We can pass valid data element identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_DataElementSyntax(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(
test_results,
c(
"col",
"dataelement_dsd",
"dataelement_ta",
"dataset",
"indicator_code",
"invalid_DSD_DEs",
"invalid_TA_DEs",
"sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can flag invalid data elements´", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(dataelement_dsd = dplyr::case_when(col %% 4 == 0 ~ "foobar",
TRUE ~ dataelement_dsd),
dataelement_ta = dplyr::case_when(col %% 5 == 0 ~ "abc123",
TRUE ~ dataelement_ta))
test_results <- checkSchema_DataElementSyntax(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0)
expect_named(
test_results,
c(
"col",
"dataelement_dsd",
"dataelement_ta",
"dataset",
"indicator_code",
"invalid_DSD_DEs",
"invalid_TA_DEs",
"sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can pass valid category option identifiers", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema_COsSyntax(ref_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) == 0)
expect_named(
test_results,
c(
"categoryoption_specified", "col", "indicator_code", "invalid_COs", "sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can flag invalid data elements´", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
dplyr::mutate(categoryoption_specified = dplyr::case_when(col %% 4 == 0 ~ "foobar",
TRUE ~ categoryoption_specified))
test_results <- checkSchema_COsSyntax(bad_schema)
expect_true(is.data.frame(test_results))
expect_true(NROW(test_results) > 0)
expect_named(
test_results,
c(
"categoryoption_specified", "col", "indicator_code", "invalid_COs", "sheet_name"
),
ignore.order = TRUE
)
})
test_that("We can pass when a schema is valid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
test_results <- checkSchema(schema = ref_schema, cop_year = cop_year, tool = tool, season = "COP")
expect_true(length(test_results) == 0)
})
test_that("We can flag when a schema is invalid", {
tool <- "Data Pack"
cop_year <- 2022
ref_schema <- pick_schema(cop_year, tool)
bad_schema <- ref_schema %>%
flubSkippedSheets(.) %>%
flubColumnTypes(.)
test_results <- checkSchema(schema = bad_schema, cop_year = cop_year, tool = tool, season = "COP")
expect_true(length(test_results) > 0)
})
|
#' Print `fmt_table1` objects
#'
#' @param x object of class `fmt_table1` object from \code{\link{fmt_table1}} function
#' @param ... further arguments passed to or from other methods.
#' @name print.fmt_table1
#' @export
#' @examples
#' fmt_table1(trial, by = "trt") %>% print()
print.fmt_table1 <- function(x, ...) {
cat("\n")
x %>%
purrr::pluck("table1") %>%
dplyr::select(-dplyr::one_of("row_type", ".variable")) %>%
dplyr::mutate_all(function(x) ifelse(is.na(x), " ", x)) %T>% {
names(.) <- NULL
} %>%
MASS::write.matrix()
}
#' Print `fmt_regression` objects
#'
#' @param x object of class `fmt_regression` object from
#' \code{\link{fmt_regression}} function
#' @param ... further arguments passed to or from other methods.
#' @name print.fmt_regression
#' @export
#' @examples
#' lm(hp ~ mpg + factor(cyl), mtcars) %>%
#' fmt_regression() %>%
#' print()
print.fmt_regression <- function(x, ...) {
cat("\n")
x %>%
purrr::pluck("model_tbl") %>%
dplyr::select(dplyr::one_of("label", "est", "ci", "pvalue")) %>%
dplyr::mutate_all(function(x) ifelse(is.na(x), "", x)) %T>% {
names(.) <- NULL
} %>%
MASS::write.matrix()
}
#' Print `fmt_uni_regression` objects
#'
#' @param x object of class \code{fmt_uni_regression} object from \code{fmt_uni_regression()} function
#' @param ... further arguments passed to or from other methods.
#' @name print.fmt_uni_regression
#' @export
#' @examples
#' fmt_uni_regression(
#' trial,
#' method = "glm",
#' y = "response",
#' method.args = list(family = binomial),
#' exponentiate = TRUE
#' ) %>%
#' print()
print.fmt_uni_regression <- function(x, ...) {
cat("\n")
x %>%
purrr::pluck("model_tbl") %>%
dplyr::select(-c("row_type", "var_type", "variable", "ll", "ul", "pvalue_exact", "p_pvalue")) %>%
dplyr::mutate_all(function(x) ifelse(is.na(x), "", x)) %T>% {
names(.) <- NULL
} %>%
MASS::write.matrix()
}
| /R/print.R | permissive | shijianasdf/clintable | R | false | false | 1,956 | r | #' Print `fmt_table1` objects
#'
#' @param x object of class `fmt_table1` object from \code{\link{fmt_table1}} function
#' @param ... further arguments passed to or from other methods.
#' @name print.fmt_table1
#' @export
#' @examples
#' fmt_table1(trial, by = "trt") %>% print()
print.fmt_table1 <- function(x, ...) {
cat("\n")
x %>%
purrr::pluck("table1") %>%
dplyr::select(-dplyr::one_of("row_type", ".variable")) %>%
dplyr::mutate_all(function(x) ifelse(is.na(x), " ", x)) %T>% {
names(.) <- NULL
} %>%
MASS::write.matrix()
}
#' Print `fmt_regression` objects
#'
#' @param x object of class `fmt_regression` object from
#' \code{\link{fmt_regression}} function
#' @param ... further arguments passed to or from other methods.
#' @name print.fmt_regression
#' @export
#' @examples
#' lm(hp ~ mpg + factor(cyl), mtcars) %>%
#' fmt_regression() %>%
#' print()
print.fmt_regression <- function(x, ...) {
cat("\n")
x %>%
purrr::pluck("model_tbl") %>%
dplyr::select(dplyr::one_of("label", "est", "ci", "pvalue")) %>%
dplyr::mutate_all(function(x) ifelse(is.na(x), "", x)) %T>% {
names(.) <- NULL
} %>%
MASS::write.matrix()
}
#' Print `fmt_uni_regression` objects
#'
#' @param x object of class \code{fmt_uni_regression} object from \code{fmt_uni_regression()} function
#' @param ... further arguments passed to or from other methods.
#' @name print.fmt_uni_regression
#' @export
#' @examples
#' fmt_uni_regression(
#' trial,
#' method = "glm",
#' y = "response",
#' method.args = list(family = binomial),
#' exponentiate = TRUE
#' ) %>%
#' print()
print.fmt_uni_regression <- function(x, ...) {
cat("\n")
x %>%
purrr::pluck("model_tbl") %>%
dplyr::select(-c("row_type", "var_type", "variable", "ll", "ul", "pvalue_exact", "p_pvalue")) %>%
dplyr::mutate_all(function(x) ifelse(is.na(x), "", x)) %T>% {
names(.) <- NULL
} %>%
MASS::write.matrix()
}
|
dirpath <- 'E:/ICHTHYOP/10kmparent/Fisica-DEB/out/lati220/results_DEB/'
dat <- read.table(paste0(dirpath,'ichthyop_output.csv'), header = T, sep = ';')
# MEAN ( month, lati-zone [norte/centro/sur] )
latis <- c(-20, -2) # Latitude extension of the area
lat1 <- seq(latis[2], latis[1], by = -6)
lat2 <- lat1 - 6
lty <- c(2,1,3)
lat_mean <- NULL
rowhead <- NULL
for(i in 1:(length(lat1)-1)){
month_mean <- NULL
for(j in 1:12){
reg <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$Day == j)
month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
}
lat_mean <- rbind(lat_mean, month_mean)
rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
}
rownames(lat_mean) <- rowhead
colnames(lat_mean) <- 1:12
png(filename = paste0(dirpath, 'recruitment_month_zone.png'), height = 850, width = 850, res = 120)
par(mar = c(3,3,1,1))
plot( 1:12, lat_mean[1,], lty = 2, type = 'l', ylim = c(0,20), xlab = '', ylab = '', axes = F, yaxs = 'i')
lines(1:12, lat_mean[2,], lty = 1)
lines(1:12, lat_mean[3,], lty = 3)
axis(1)
axis(2, las = 2)
box()
mtext(side = 1, line = 2, text = 'Release Month')
mtext(side = 2, line = 2, text = 'Recruitment (%)')
legend('topright', legend = rowhead, bty = 'n', lty = lty)
dev.off()
# MEAN ( dist-coast, lati-zone [norte/centro/sur] )
pixels <- levels(factor(dat$PixelCoast))
lat_mean <- NULL
rowhead <- NULL
for(i in 1:(length(lat1)-1)){
month_mean <- NULL
for(j in 1:length(pixels)){
reg <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$PixelCoast == pixels[j])
month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
}
lat_mean <- rbind(lat_mean, month_mean)
rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
}
rownames(lat_mean) <- rowhead
colnames(lat_mean) <- pixels
png(filename = paste0(dirpath, 'recruitment_distcoast_zone.png'), height = 850, width = 850, res = 120)
par(mar = c(3,3,1,1))
plot (as.numeric(pixels)*10, lat_mean[1,], lty = 2, type = 'l', ylim = c(0,40), xlab = '', ylab = '', axes = F, yaxs = 'i')
lines(as.numeric(pixels)*10, lat_mean[2,], lty = 1)
lines(as.numeric(pixels)*10, lat_mean[3,], lty = 3)
axis(1)
axis(2, las = 2)
box()
mtext(side = 1, line = 2, text = 'Distance to the Coast (km)')
mtext(side = 2, line = 2, text = 'Recruitment (%)')
legend('topright', legend = rowhead, bty = 'n', lty = lty)
dev.off()
# MEAN (month, dist-coast, lati-zone [norte/centro/sur] )
pixels <- levels(factor(dat$PixelCoast))
lat_mean <- array(data = NA, dim = c(3, 12, 25))
rowhead <- NULL
rowhead
for(i in 1:(length(lat1)-1)){
for(j in 1:12){
for(k in 1:length(pixels)){
sub1 <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$Day == j & dat$PixelCoast == pixels[k])
sub1 <- (sum(sub1$IfRecruited)*100)/dim(sub1)[1]
lat_mean[i,j,k] <- sub1
}
}
rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
}
png(filename = paste0(dirpath, 'recruitment_month_distcoast_zone.png'), height = 700, width = 1650, res = 120)
par(mfrow = c(1,3), mar = c(3,4,3,1))
cols <- rep(c('red','blue','green','yellow'), each = 3)
pch <- rep(1:3, times = 4)
for(i in 1:3){
zona <- lat_mean[i,,]
plot (as.numeric(pixels)*10, as.numeric(pixels)*10, type = 'n', ylim = c(0,50), xlab = '', ylab = '')
mtext(side = 1, line = 2, text = 'Distance to the Coast (km)')
mtext(side = 2, line = 2, text = 'Recruitment (%)')
mtext(side = 3, line = .5, text = paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
grid()
for(j in 1:12){
mon <- zona[j,]
lines(as.numeric(pixels)*10, mon, col = cols[j])
points(as.numeric(pixels)*10, mon, col = cols[j], pch = pch[j])
}
legend('topright', legend = paste0('M',1:12), col = cols, lty = 1, , pch = pch, bty = 'n')
}
dev.off()
# # Promedio por mes y por zona [norte, centro, sur] y distancia a la costa
# lat_mean <- NULL
# rowhead <- NULL
# for(i in 1:(length(lat1)-1)){
# month_mean <- NULL
# for(j in 1:12){
# reg <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$Day == j)
# month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
# }
# lat_mean <- rbind(lat_mean, month_mean)
# rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
# }
# rownames(lat_mean) <- rowhead
# colnames(lat_mean) <- 1:12
# cols <- c('grey90', 'grey60', 'grey30')
# barplot(lat_mean, beside = T, col = cols)
# legend('topright', legend = rowhead, bty = 'n', col = cols, fill = cols)
#
#
#
#
#
# # Promedio por mes y distancia a la costa
#
# pixel_mean <- NULL
# for(i in 1:length(pixels)){
# month_mean <- NULL
# for(j in 1:12){
# reg <- subset(dat, dat$PixelCoast == pixels[i] & dat$Day == j)
# month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
# }
# pixel_mean <- rbind(pixel_mean, month_mean)
# }
# rownames(pixel_mean) <- pixels
# colnames(pixel_mean) <- 1:12 | /revisar para borrar/ich17.R | no_license | jfloresvaliente/ichthyop-processing | R | false | false | 4,897 | r | dirpath <- 'E:/ICHTHYOP/10kmparent/Fisica-DEB/out/lati220/results_DEB/'
dat <- read.table(paste0(dirpath,'ichthyop_output.csv'), header = T, sep = ';')
# MEAN ( month, lati-zone [norte/centro/sur] )
latis <- c(-20, -2) # Latitude extension of the area
lat1 <- seq(latis[2], latis[1], by = -6)
lat2 <- lat1 - 6
lty <- c(2,1,3)
lat_mean <- NULL
rowhead <- NULL
for(i in 1:(length(lat1)-1)){
month_mean <- NULL
for(j in 1:12){
reg <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$Day == j)
month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
}
lat_mean <- rbind(lat_mean, month_mean)
rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
}
rownames(lat_mean) <- rowhead
colnames(lat_mean) <- 1:12
png(filename = paste0(dirpath, 'recruitment_month_zone.png'), height = 850, width = 850, res = 120)
par(mar = c(3,3,1,1))
plot( 1:12, lat_mean[1,], lty = 2, type = 'l', ylim = c(0,20), xlab = '', ylab = '', axes = F, yaxs = 'i')
lines(1:12, lat_mean[2,], lty = 1)
lines(1:12, lat_mean[3,], lty = 3)
axis(1)
axis(2, las = 2)
box()
mtext(side = 1, line = 2, text = 'Release Month')
mtext(side = 2, line = 2, text = 'Recruitment (%)')
legend('topright', legend = rowhead, bty = 'n', lty = lty)
dev.off()
# MEAN ( dist-coast, lati-zone [norte/centro/sur] )
pixels <- levels(factor(dat$PixelCoast))
lat_mean <- NULL
rowhead <- NULL
for(i in 1:(length(lat1)-1)){
month_mean <- NULL
for(j in 1:length(pixels)){
reg <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$PixelCoast == pixels[j])
month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
}
lat_mean <- rbind(lat_mean, month_mean)
rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
}
rownames(lat_mean) <- rowhead
colnames(lat_mean) <- pixels
png(filename = paste0(dirpath, 'recruitment_distcoast_zone.png'), height = 850, width = 850, res = 120)
par(mar = c(3,3,1,1))
plot (as.numeric(pixels)*10, lat_mean[1,], lty = 2, type = 'l', ylim = c(0,40), xlab = '', ylab = '', axes = F, yaxs = 'i')
lines(as.numeric(pixels)*10, lat_mean[2,], lty = 1)
lines(as.numeric(pixels)*10, lat_mean[3,], lty = 3)
axis(1)
axis(2, las = 2)
box()
mtext(side = 1, line = 2, text = 'Distance to the Coast (km)')
mtext(side = 2, line = 2, text = 'Recruitment (%)')
legend('topright', legend = rowhead, bty = 'n', lty = lty)
dev.off()
# MEAN (month, dist-coast, lati-zone [norte/centro/sur] )
pixels <- levels(factor(dat$PixelCoast))
lat_mean <- array(data = NA, dim = c(3, 12, 25))
rowhead <- NULL
rowhead
for(i in 1:(length(lat1)-1)){
for(j in 1:12){
for(k in 1:length(pixels)){
sub1 <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$Day == j & dat$PixelCoast == pixels[k])
sub1 <- (sum(sub1$IfRecruited)*100)/dim(sub1)[1]
lat_mean[i,j,k] <- sub1
}
}
rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
}
png(filename = paste0(dirpath, 'recruitment_month_distcoast_zone.png'), height = 700, width = 1650, res = 120)
par(mfrow = c(1,3), mar = c(3,4,3,1))
cols <- rep(c('red','blue','green','yellow'), each = 3)
pch <- rep(1:3, times = 4)
for(i in 1:3){
zona <- lat_mean[i,,]
plot (as.numeric(pixels)*10, as.numeric(pixels)*10, type = 'n', ylim = c(0,50), xlab = '', ylab = '')
mtext(side = 1, line = 2, text = 'Distance to the Coast (km)')
mtext(side = 2, line = 2, text = 'Recruitment (%)')
mtext(side = 3, line = .5, text = paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
grid()
for(j in 1:12){
mon <- zona[j,]
lines(as.numeric(pixels)*10, mon, col = cols[j])
points(as.numeric(pixels)*10, mon, col = cols[j], pch = pch[j])
}
legend('topright', legend = paste0('M',1:12), col = cols, lty = 1, , pch = pch, bty = 'n')
}
dev.off()
# # Promedio por mes y por zona [norte, centro, sur] y distancia a la costa
# lat_mean <- NULL
# rowhead <- NULL
# for(i in 1:(length(lat1)-1)){
# month_mean <- NULL
# for(j in 1:12){
# reg <- subset(dat, dat$Lat >= lat2[i] & dat$Lat < lat1[i] & dat$Day == j)
# month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
# }
# lat_mean <- rbind(lat_mean, month_mean)
# rowhead <- c(rowhead, paste0(abs(lat1[i]), 'º-', abs(lat2[i]),'º'))
# }
# rownames(lat_mean) <- rowhead
# colnames(lat_mean) <- 1:12
# cols <- c('grey90', 'grey60', 'grey30')
# barplot(lat_mean, beside = T, col = cols)
# legend('topright', legend = rowhead, bty = 'n', col = cols, fill = cols)
#
#
#
#
#
# # Promedio por mes y distancia a la costa
#
# pixel_mean <- NULL
# for(i in 1:length(pixels)){
# month_mean <- NULL
# for(j in 1:12){
# reg <- subset(dat, dat$PixelCoast == pixels[i] & dat$Day == j)
# month_mean <- c(month_mean, (sum(reg$IfRecruited)*100)/dim(reg)[1])
# }
# pixel_mean <- rbind(pixel_mean, month_mean)
# }
# rownames(pixel_mean) <- pixels
# colnames(pixel_mean) <- 1:12 |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/DEgenes.R
\name{DEgenesCross}
\alias{DEgenesCross}
\title{DEgenesCross}
\usage{
DEgenesCross(
sce_list,
altExp_name = "none",
exprs_value = "logcounts",
method = "wilcox",
colData_name = NULL,
group_to_test = NULL,
exprs_pct = 0.1,
exprs_threshold = 0,
return_all = FALSE,
pval_adj = 0.05,
mean_diff = 0,
pct_diff = 0.1,
topN = 10
)
}
\arguments{
\item{sce_list}{A Slist of ingleCellExperiment object}
\item{altExp_name}{A character indicates which expression matrix is
used. by default is none (i.e. RNA).}
\item{exprs_value}{A character indicates which expression value in
assayNames is used.}
\item{method}{A character indicates the method used in DE analysis}
\item{colData_name}{A vector of character indicates the colData that
stored the group information of each sce of the sce_list}
\item{group_to_test}{A vector of character indicates which group in each
sce is used to compared across the sce list.}
\item{exprs_pct}{A numeric indicates the threshold expression percentage
of a gene to be considered in DE analysis}
\item{exprs_threshold}{A numeric indicates the threshold of expression.
By default is 0.}
\item{return_all}{Whether return full list of DE genes}
\item{pval_adj}{A numeric indicates the threshold of adjusted p-value.}
\item{mean_diff}{A numeric indicates the threshold of difference of
average expression.}
\item{pct_diff}{A numeric indicates the threshold of difference of
percentage expression.}
\item{topN}{A numeric indicates the top number of genes will be
included in the list.}
}
\value{
A SingleCellExeperiment with DE results stored in meta data DE_res
}
\description{
A function to perform DE analysis on a list of CITE seq data
}
| /man/DEgenesCross.Rd | no_license | ycao6928/CiteFuse | R | false | true | 1,783 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/DEgenes.R
\name{DEgenesCross}
\alias{DEgenesCross}
\title{DEgenesCross}
\usage{
DEgenesCross(
sce_list,
altExp_name = "none",
exprs_value = "logcounts",
method = "wilcox",
colData_name = NULL,
group_to_test = NULL,
exprs_pct = 0.1,
exprs_threshold = 0,
return_all = FALSE,
pval_adj = 0.05,
mean_diff = 0,
pct_diff = 0.1,
topN = 10
)
}
\arguments{
\item{sce_list}{A Slist of ingleCellExperiment object}
\item{altExp_name}{A character indicates which expression matrix is
used. by default is none (i.e. RNA).}
\item{exprs_value}{A character indicates which expression value in
assayNames is used.}
\item{method}{A character indicates the method used in DE analysis}
\item{colData_name}{A vector of character indicates the colData that
stored the group information of each sce of the sce_list}
\item{group_to_test}{A vector of character indicates which group in each
sce is used to compared across the sce list.}
\item{exprs_pct}{A numeric indicates the threshold expression percentage
of a gene to be considered in DE analysis}
\item{exprs_threshold}{A numeric indicates the threshold of expression.
By default is 0.}
\item{return_all}{Whether return full list of DE genes}
\item{pval_adj}{A numeric indicates the threshold of adjusted p-value.}
\item{mean_diff}{A numeric indicates the threshold of difference of
average expression.}
\item{pct_diff}{A numeric indicates the threshold of difference of
percentage expression.}
\item{topN}{A numeric indicates the top number of genes will be
included in the list.}
}
\value{
A SingleCellExeperiment with DE results stored in meta data DE_res
}
\description{
A function to perform DE analysis on a list of CITE seq data
}
|
require(datasets) # load necessary package for DAX index data
dax = EuStockMarkets[, 1] # DAX index
r.dax = diff(log(dax)) # DAX log-returns
r.dax_m = mean(r.dax)
r.dax_sd = sd(r.dax) # mean and standard deviation
r.dax_st = (r.dax - r.dax_m)/r.dax_sd # standardised log-returns
ftse = EuStockMarkets[, 4] # FTSE index
r.ftse = diff(log(ftse)) # FTSE log-returns
r.ftse_m = mean(r.ftse)
r.ftse_sd = sd(r.ftse) # mean and standard deviation
r.ftse_st = (r.ftse - r.ftse_m)/r.ftse_sd # standardised log-returns
# graphical parameters
par(lwd = 3, cex = 1, cex.axis = 1.4, cex.lab = 1.5, mfrow = c(1, 2))
# plot for the edfs of DAX and FTSE log-returns
plot(ecdf(r.dax), xlim = c(-0.05, 0.05), main = "", xlab = "log-returns", ylab = "edf of log-returns")
lines(ecdf(r.ftse), col = "blue") # add edf of FTSE log-returns to plot
# plot for the edfs of DAX and FTSE standardised log-returns
plot(ecdf(r.dax_st), xlim = c(-5, 5), main = "", xlab = "standardised log-returns", ylab = "edf of standardised log-returns")
lines(ecdf(r.ftse_st), col = "blue") # add edf of FTSE standardised log-returns to plot | /BCS_EdfsDAXFTSE/BCS_EdfsDAXFTSE.R | no_license | QuantLet/BCS | R | false | false | 1,114 | r | require(datasets) # load necessary package for DAX index data
dax = EuStockMarkets[, 1] # DAX index
r.dax = diff(log(dax)) # DAX log-returns
r.dax_m = mean(r.dax)
r.dax_sd = sd(r.dax) # mean and standard deviation
r.dax_st = (r.dax - r.dax_m)/r.dax_sd # standardised log-returns
ftse = EuStockMarkets[, 4] # FTSE index
r.ftse = diff(log(ftse)) # FTSE log-returns
r.ftse_m = mean(r.ftse)
r.ftse_sd = sd(r.ftse) # mean and standard deviation
r.ftse_st = (r.ftse - r.ftse_m)/r.ftse_sd # standardised log-returns
# graphical parameters
par(lwd = 3, cex = 1, cex.axis = 1.4, cex.lab = 1.5, mfrow = c(1, 2))
# plot for the edfs of DAX and FTSE log-returns
plot(ecdf(r.dax), xlim = c(-0.05, 0.05), main = "", xlab = "log-returns", ylab = "edf of log-returns")
lines(ecdf(r.ftse), col = "blue") # add edf of FTSE log-returns to plot
# plot for the edfs of DAX and FTSE standardised log-returns
plot(ecdf(r.dax_st), xlim = c(-5, 5), main = "", xlab = "standardised log-returns", ylab = "edf of standardised log-returns")
lines(ecdf(r.ftse_st), col = "blue") # add edf of FTSE standardised log-returns to plot |
library(MatrixModels)
### Name: glm4
### Title: Fitting Generalized Linear Models (using S4)
### Aliases: glm4
### Keywords: models regression
### ** Examples
### All the following is very experimental -- and probably will change: -------
data(CO2, package="datasets")
## dense linear model
str(glm4(uptake ~ 0 + Type*Treatment, data=CO2, doFit = FALSE), 4)
## sparse linear model
str(glm4(uptake ~ 0 + Type*Treatment, data=CO2, doFit = FALSE,
sparse = TRUE), 4)
## From example(glm): -----------------
## Dobson (1990) Page 93: Randomized Controlled Trial :
str(trial <- data.frame(counts=c(18,17,15,20,10,20,25,13,12),
outcome=gl(3,1,9,labels=LETTERS[1:3]),
treatment=gl(3,3,labels=letters[1:3])))
glm.D93 <- glm(counts ~ outcome + treatment, family=poisson, data=trial)
summary(glm.D93)
c.glm <- unname(coef(glm.D93))
glmM <- glm4(counts ~ outcome + treatment, family = poisson, data=trial)
glmM2 <- update(glmM, quick = FALSE) # slightly more accurate
glmM3 <- update(glmM, quick = FALSE, finalUpdate = TRUE)
# finalUpdate has no effect on 'coef'
stopifnot( identical(glmM2@pred@coef, glmM3@pred@coef),
all.equal(glmM @pred@coef, c.glm, tolerance=1e-7),
all.equal(glmM2@pred@coef, c.glm, tolerance=1e-12))
## Don't show:
All.eq <- function(x,y, ...) all.equal(x,y, tolerance= 1e-12, ...)
stopifnot( ## ensure typos are *caught* :
inherits(try(glm4(counts ~ outcome + treatment, family=poisson, data=trial,
fooBar = FALSE)), "try-error"),
## check formula(.): {environments differ - FIXME?}
formula(glmM) == formula(glm.D93),
identical(coef(glmM2), coefficients(glmM3)),
All.eq (coef(glmM2), coefficients(glm.D93)),
identical(fitted.values(glmM2), fitted(glmM3)),
All.eq (residuals(glmM2), resid(glm.D93), check.attributes=FALSE),# names()% FIXME ??
identical(residuals(glmM2), resid(glmM3))
)
## End(Don't show)
## Watch the iterations --- and use no intercept --> more sparse X
## 1) dense generalized linear model
glmM <- glm4(counts ~ 0+outcome + treatment, poisson, trial,
verbose = TRUE)
## 2) sparse generalized linear model
glmS <- glm4(counts ~ 0+outcome + treatment, poisson, trial,
verbose = TRUE, sparse = TRUE)
str(glmS, max.lev = 4)
stopifnot( all.equal(glmM@pred@coef, glmS@pred@coef),
all.equal(glmM@pred@Vtr, glmS@pred@Vtr) )
## A Gamma example, from McCullagh & Nelder (1989, pp. 300-2)
clotting <- data.frame(u = c(5,10,15,20,30,40,60,80,100),
lot1 = c(118,58,42,35,27,25,21,19,18),
lot2 = c(69,35,26,21,18,16,13,12,12))
str(gMN <- glm4(lot1 ~ log(u), data=clotting, family=Gamma, verbose=TRUE))
glm. <- glm(lot1 ~ log(u), data=clotting, family=Gamma)
stopifnot( all.equal(gMN@pred@coef, unname(coef(glm.)), tolerance=1e-7) )
| /data/genthat_extracted_code/MatrixModels/examples/glm4.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 2,913 | r | library(MatrixModels)
### Name: glm4
### Title: Fitting Generalized Linear Models (using S4)
### Aliases: glm4
### Keywords: models regression
### ** Examples
### All the following is very experimental -- and probably will change: -------
data(CO2, package="datasets")
## dense linear model
str(glm4(uptake ~ 0 + Type*Treatment, data=CO2, doFit = FALSE), 4)
## sparse linear model
str(glm4(uptake ~ 0 + Type*Treatment, data=CO2, doFit = FALSE,
sparse = TRUE), 4)
## From example(glm): -----------------
## Dobson (1990) Page 93: Randomized Controlled Trial :
str(trial <- data.frame(counts=c(18,17,15,20,10,20,25,13,12),
outcome=gl(3,1,9,labels=LETTERS[1:3]),
treatment=gl(3,3,labels=letters[1:3])))
glm.D93 <- glm(counts ~ outcome + treatment, family=poisson, data=trial)
summary(glm.D93)
c.glm <- unname(coef(glm.D93))
glmM <- glm4(counts ~ outcome + treatment, family = poisson, data=trial)
glmM2 <- update(glmM, quick = FALSE) # slightly more accurate
glmM3 <- update(glmM, quick = FALSE, finalUpdate = TRUE)
# finalUpdate has no effect on 'coef'
stopifnot( identical(glmM2@pred@coef, glmM3@pred@coef),
all.equal(glmM @pred@coef, c.glm, tolerance=1e-7),
all.equal(glmM2@pred@coef, c.glm, tolerance=1e-12))
## Don't show:
All.eq <- function(x,y, ...) all.equal(x,y, tolerance= 1e-12, ...)
stopifnot( ## ensure typos are *caught* :
inherits(try(glm4(counts ~ outcome + treatment, family=poisson, data=trial,
fooBar = FALSE)), "try-error"),
## check formula(.): {environments differ - FIXME?}
formula(glmM) == formula(glm.D93),
identical(coef(glmM2), coefficients(glmM3)),
All.eq (coef(glmM2), coefficients(glm.D93)),
identical(fitted.values(glmM2), fitted(glmM3)),
All.eq (residuals(glmM2), resid(glm.D93), check.attributes=FALSE),# names()% FIXME ??
identical(residuals(glmM2), resid(glmM3))
)
## End(Don't show)
## Watch the iterations --- and use no intercept --> more sparse X
## 1) dense generalized linear model
glmM <- glm4(counts ~ 0+outcome + treatment, poisson, trial,
verbose = TRUE)
## 2) sparse generalized linear model
glmS <- glm4(counts ~ 0+outcome + treatment, poisson, trial,
verbose = TRUE, sparse = TRUE)
str(glmS, max.lev = 4)
stopifnot( all.equal(glmM@pred@coef, glmS@pred@coef),
all.equal(glmM@pred@Vtr, glmS@pred@Vtr) )
## A Gamma example, from McCullagh & Nelder (1989, pp. 300-2)
clotting <- data.frame(u = c(5,10,15,20,30,40,60,80,100),
lot1 = c(118,58,42,35,27,25,21,19,18),
lot2 = c(69,35,26,21,18,16,13,12,12))
str(gMN <- glm4(lot1 ~ log(u), data=clotting, family=Gamma, verbose=TRUE))
glm. <- glm(lot1 ~ log(u), data=clotting, family=Gamma)
stopifnot( all.equal(gMN@pred@coef, unname(coef(glm.)), tolerance=1e-7) )
|
library(lubridate); # Will make working with dates easier
# Starting with some constants.
fileURL = "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
fileZip = "power_consumption.zip";
fileTxt = "household_power_consumption.txt";
# Will need to use internet2.dll for Windows
if (.Platform$OS.type=="windows"){
setInternet2(T);
}
# Download and unzip
download.file(fileURL, fileZip);
unzip(fileZip);
# Actually, read.csv2 has most default parameters correct, but let's make it more verbose.
# Separator - ;, there is header row, NA represented by "?", dot is used for decimal
powerConsAll <- read.table(file = fileTxt, sep = ";", header = T, na.strings = "?", dec = ".");
# Merging date and time together, parsing it to a timestamp and saving timestamp to new column.
powerConsAll$Timestamp <- dmy_hms(paste(powerConsAll$Date, powerConsAll$Time));
#Picking 2007-02-01 and 2007-02-02
powerCons <- subset(powerConsAll,
(powerConsAll$Timestamp >= ymd_hms("2007-02-01 00:00:00")) &
(powerConsAll$Timestamp < ymd_hms("2007-02-03 00:00:00")) )
# I need days of the week in English, not any other language.
Sys.setlocale("LC_TIME", "English");
# Now subsetting is complete. Time to recreate plot 3.
# Example plot 3 is 504x504, but we are explicitly asked to make
# the plot 480x480
png("plot3.png", width=480, height=480);
par(bg=NA); # Example plot has transparent background. Doing it.
# Plot 3 is a plot of submetering over time, which has 3 lines:
# Submetering 1
plot(powerCons$Timestamp, powerCons$Sub_metering_1,
col = "black", # black
type = "l", # line
ylab = "Energy sub metering", # following y-axis label
xlab = NA); # ... no x-axis label
# Submetering 2
lines(powerCons$Timestamp, powerCons$Sub_metering_2,
col = "red"); # red line (no need to set type = "l" for "lines")
# Submetering 3
lines(powerCons$Timestamp, powerCons$Sub_metering_3,
col = "blue"); # blue line (no need to set type = "l" for "lines")
#Legend
legend("topright", #In topright corner
legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), #Here is legend text
lty = 1, # Show lines in left part of legend
col=c("black","red","blue")); #Line colors (should match with legend text)
dev.off();
| /plot3.R | no_license | andreyboytsov/ExData_Plotting1 | R | false | false | 2,320 | r | library(lubridate); # Will make working with dates easier
# Starting with some constants.
fileURL = "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
fileZip = "power_consumption.zip";
fileTxt = "household_power_consumption.txt";
# Will need to use internet2.dll for Windows
if (.Platform$OS.type=="windows"){
setInternet2(T);
}
# Download and unzip
download.file(fileURL, fileZip);
unzip(fileZip);
# Actually, read.csv2 has most default parameters correct, but let's make it more verbose.
# Separator - ;, there is header row, NA represented by "?", dot is used for decimal
powerConsAll <- read.table(file = fileTxt, sep = ";", header = T, na.strings = "?", dec = ".");
# Merging date and time together, parsing it to a timestamp and saving timestamp to new column.
powerConsAll$Timestamp <- dmy_hms(paste(powerConsAll$Date, powerConsAll$Time));
#Picking 2007-02-01 and 2007-02-02
powerCons <- subset(powerConsAll,
(powerConsAll$Timestamp >= ymd_hms("2007-02-01 00:00:00")) &
(powerConsAll$Timestamp < ymd_hms("2007-02-03 00:00:00")) )
# I need days of the week in English, not any other language.
Sys.setlocale("LC_TIME", "English");
# Now subsetting is complete. Time to recreate plot 3.
# Example plot 3 is 504x504, but we are explicitly asked to make
# the plot 480x480
png("plot3.png", width=480, height=480);
par(bg=NA); # Example plot has transparent background. Doing it.
# Plot 3 is a plot of submetering over time, which has 3 lines:
# Submetering 1
plot(powerCons$Timestamp, powerCons$Sub_metering_1,
col = "black", # black
type = "l", # line
ylab = "Energy sub metering", # following y-axis label
xlab = NA); # ... no x-axis label
# Submetering 2
lines(powerCons$Timestamp, powerCons$Sub_metering_2,
col = "red"); # red line (no need to set type = "l" for "lines")
# Submetering 3
lines(powerCons$Timestamp, powerCons$Sub_metering_3,
col = "blue"); # blue line (no need to set type = "l" for "lines")
#Legend
legend("topright", #In topright corner
legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), #Here is legend text
lty = 1, # Show lines in left part of legend
col=c("black","red","blue")); #Line colors (should match with legend text)
dev.off();
|
# get() function
u <- cbind(c(1, 2, 3), c(1, 2, 4))
v <- cbind(c(8, 12, 20), c(15, 10, 2))
for (m in c("u", "v")){
z <- get(m)
print(lm(z[, 2] ~ z[, 1]))
}
| /general-info/get.R | no_license | abhi8893/Intensive-R | R | false | false | 163 | r | # get() function
u <- cbind(c(1, 2, 3), c(1, 2, 4))
v <- cbind(c(8, 12, 20), c(15, 10, 2))
for (m in c("u", "v")){
z <- get(m)
print(lm(z[, 2] ~ z[, 1]))
}
|
plot.GPCE.quad <- function(x,...) {
ylim = c(0, 1)
if (!is.null(x$Sensitivity)) {
p <- x$Args$InputDim
pch = c(21, 24)
nodeplot(matrix(x$Sensitivity$S,ncol=p), xlim = c(1, p + 1), ylim = ylim, pch = pch[1],...)
nodeplot(matrix(x$Sensitivity$ST,ncol=p), xlim = c(1, p + 1), ylim = ylim, labels = FALSE,
pch = pch[2], at = (1:p)+.3, add = TRUE,...)
legend(x = "topright", legend = c("main effect", "total effect"), pch = pch)
S <- rbind(x$Sensitivity$S, x$Sensitivity$ST - x$Sensitivity$S)
colnames(S) <- paste("X", 1:p, sep = "")
bar.col <- c("white","grey")
barplot(S, ylim = ylim, col = bar.col)
legend("topright", c("main effect", "interactions"), fill = bar.col)
}
}
| /GPC/R/plot.GPCE.quad.R | no_license | ingted/R-Examples | R | false | false | 738 | r | plot.GPCE.quad <- function(x,...) {
ylim = c(0, 1)
if (!is.null(x$Sensitivity)) {
p <- x$Args$InputDim
pch = c(21, 24)
nodeplot(matrix(x$Sensitivity$S,ncol=p), xlim = c(1, p + 1), ylim = ylim, pch = pch[1],...)
nodeplot(matrix(x$Sensitivity$ST,ncol=p), xlim = c(1, p + 1), ylim = ylim, labels = FALSE,
pch = pch[2], at = (1:p)+.3, add = TRUE,...)
legend(x = "topright", legend = c("main effect", "total effect"), pch = pch)
S <- rbind(x$Sensitivity$S, x$Sensitivity$ST - x$Sensitivity$S)
colnames(S) <- paste("X", 1:p, sep = "")
bar.col <- c("white","grey")
barplot(S, ylim = ylim, col = bar.col)
legend("topright", c("main effect", "interactions"), fill = bar.col)
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/icons.R
\name{tablerIcon}
\alias{tablerIcon}
\title{Create a Boostrap 4 icon}
\usage{
tablerIcon(name, lib = c("feather", "font-awesome", "payment"))
}
\arguments{
\item{name}{Name of icon. See \url{https://preview.tabler.io/icons.html} for all valid icons.}
\item{lib}{Icon library ("feather", "font-awesome", "payment").}
}
\description{
Build a tabler icon
}
\author{
David Granjon, \email{dgranjon@ymail.com}
}
| /man/tablerIcon.Rd | no_license | RinteRface/tablerDash | R | false | true | 494 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/icons.R
\name{tablerIcon}
\alias{tablerIcon}
\title{Create a Boostrap 4 icon}
\usage{
tablerIcon(name, lib = c("feather", "font-awesome", "payment"))
}
\arguments{
\item{name}{Name of icon. See \url{https://preview.tabler.io/icons.html} for all valid icons.}
\item{lib}{Icon library ("feather", "font-awesome", "payment").}
}
\description{
Build a tabler icon
}
\author{
David Granjon, \email{dgranjon@ymail.com}
}
|
library(raster)
library(ntbox)
library(rgdal)
library(foreach)
# Occurrence data
bd.per <- read.csv("BD-occurrence/Peru/Bd-prevalence-data.csv")
bd.glob <- read.csv("BD-occurrence/Global/Bd-global-data.csv")
chels.pca <- stack(list.files("../../Chelsa/PCA", "tif", full.names = T))
peru <- readOGR("../Admin-layers/PER_adm0.shp")
ref.r <- raster("Prevalence-maps/Prevalence-median-m2.tif")
chels.peru <- crop(chels.pca, extent(peru))
chels.peru <- projectRaster(chels.peru, ref.r)
chels.peru <- raster::mask(chels.peru, ref.r)
# Fitting ellipsoid
bd.glob.pres <- subset(bd.glob, SppDet > 0, Country != "Peru")
env.bd.glob <- na.omit(data.frame(extract(chels.pca, bd.glob.pres[, c("longitude", "latitude")])))
combs <- combn(1:10, m = 4)
centres <- foreach(i = 1:ncol(combs)) %do% {
cov_center(env.bd.glob, mve = T, vars = names(env.bd.glob)[combs[, i]], level = 0.95)
}
dir.create("Bd-Suitability")
saveRDS(centres, "Bd-Suitability/Centres-covariances.rds")
ellip <- foreach(i = seq_along(centres), .combine = c) %do% {
lay <- dropLayer(chels.peru, i = which(!names(chels.peru) %in% names(env.bd.glob)[combs[, i]]))
fit <- ellipsoidfit(envlayers = lay,
centroid = centres[[i]]$centroid,
covar = centres[[i]]$covariance,
level = 0.95,
size = 1, plot = F)
return(fit$suitRaster)
}
bd.pres <- subset(bd.per, N.positive > 0)
coordinates(bd.pres) <- ~ Longitude + Latitude
proj4string(bd.pres) <- CRS("+init=epsg:4326")
bd.pres <- spTransform(bd.pres, CRSobj = CRS(proj4string(chels.peru)))
roc.tests <- lapply(ellip,
function(x){
pROC(continuous_mod = x,
test_data = coordinates(bd.pres),
n_iter = 1000,
E_percent = 5,
boost_percent = 50,
parallel = F,
rseed = 63193)
})
roc.results <- foreach(i = seq_along(roc.tests), .combine = rbind) %do%{
roc.tests[[i]]$pROC_summary
}
roc.results <- data.frame(roc.results)
roc.results$Model <- paste0("DNC-", seq_along(roc.tests))
best.10 <- sort(roc.results$Mean_pAUC_ratio_at_5., decreasing = T)[1:10]
best.suits <- ellip[which(roc.results$Mean_pAUC_ratio_at_5. %in% best.10)]
write.csv(roc.results, "Bd-Suitability/Partial-roc-results.csv", row.names = F)
write.csv(roc.results[which(roc.results$Mean_pAUC_ratio_at_5. %in% best.10),],
"Bd-Suitability/Partial-roc-Best.csv", row.names = F)
for(i in 1:10){writeRaster(best.suits[[i]],
paste0("Bd-Suitability/DNC-",
which(roc.results$Mean_pAUC_ratio_at_5. %in% best.10)[i],
".csv"), "GTiff", overwrite = T)}
# Weighted mean model
best.suits.s <- stack(best.suits)
## Harmonic weighted mean
w.model <- 1/(weighted.mean(1/best.suits.s, exp(best.10)))
writeRaster(w.model, "Bd-Suitability/DNC-weighted-mean", "GTiff", overwrite = T)
| /Bd-suitability.R | no_license | gerardommc/Bd-Peru | R | false | false | 3,157 | r | library(raster)
library(ntbox)
library(rgdal)
library(foreach)
# Occurrence data
bd.per <- read.csv("BD-occurrence/Peru/Bd-prevalence-data.csv")
bd.glob <- read.csv("BD-occurrence/Global/Bd-global-data.csv")
chels.pca <- stack(list.files("../../Chelsa/PCA", "tif", full.names = T))
peru <- readOGR("../Admin-layers/PER_adm0.shp")
ref.r <- raster("Prevalence-maps/Prevalence-median-m2.tif")
chels.peru <- crop(chels.pca, extent(peru))
chels.peru <- projectRaster(chels.peru, ref.r)
chels.peru <- raster::mask(chels.peru, ref.r)
# Fitting ellipsoid
bd.glob.pres <- subset(bd.glob, SppDet > 0, Country != "Peru")
env.bd.glob <- na.omit(data.frame(extract(chels.pca, bd.glob.pres[, c("longitude", "latitude")])))
combs <- combn(1:10, m = 4)
centres <- foreach(i = 1:ncol(combs)) %do% {
cov_center(env.bd.glob, mve = T, vars = names(env.bd.glob)[combs[, i]], level = 0.95)
}
dir.create("Bd-Suitability")
saveRDS(centres, "Bd-Suitability/Centres-covariances.rds")
ellip <- foreach(i = seq_along(centres), .combine = c) %do% {
lay <- dropLayer(chels.peru, i = which(!names(chels.peru) %in% names(env.bd.glob)[combs[, i]]))
fit <- ellipsoidfit(envlayers = lay,
centroid = centres[[i]]$centroid,
covar = centres[[i]]$covariance,
level = 0.95,
size = 1, plot = F)
return(fit$suitRaster)
}
bd.pres <- subset(bd.per, N.positive > 0)
coordinates(bd.pres) <- ~ Longitude + Latitude
proj4string(bd.pres) <- CRS("+init=epsg:4326")
bd.pres <- spTransform(bd.pres, CRSobj = CRS(proj4string(chels.peru)))
roc.tests <- lapply(ellip,
function(x){
pROC(continuous_mod = x,
test_data = coordinates(bd.pres),
n_iter = 1000,
E_percent = 5,
boost_percent = 50,
parallel = F,
rseed = 63193)
})
roc.results <- foreach(i = seq_along(roc.tests), .combine = rbind) %do%{
roc.tests[[i]]$pROC_summary
}
roc.results <- data.frame(roc.results)
roc.results$Model <- paste0("DNC-", seq_along(roc.tests))
best.10 <- sort(roc.results$Mean_pAUC_ratio_at_5., decreasing = T)[1:10]
best.suits <- ellip[which(roc.results$Mean_pAUC_ratio_at_5. %in% best.10)]
write.csv(roc.results, "Bd-Suitability/Partial-roc-results.csv", row.names = F)
write.csv(roc.results[which(roc.results$Mean_pAUC_ratio_at_5. %in% best.10),],
"Bd-Suitability/Partial-roc-Best.csv", row.names = F)
for(i in 1:10){writeRaster(best.suits[[i]],
paste0("Bd-Suitability/DNC-",
which(roc.results$Mean_pAUC_ratio_at_5. %in% best.10)[i],
".csv"), "GTiff", overwrite = T)}
# Weighted mean model
best.suits.s <- stack(best.suits)
## Harmonic weighted mean
w.model <- 1/(weighted.mean(1/best.suits.s, exp(best.10)))
writeRaster(w.model, "Bd-Suitability/DNC-weighted-mean", "GTiff", overwrite = T)
|
# -- ============================================================
# -- Josh
# -- no project
# -- 2018/07/17
# -- suppress warnings globally
# comments go here
#
# -- ============================================================
# expression
suppressWarnings(expr)
# example usage
suppressWarnings(library(dplyr))
# do it globally
options(warn = -1)
# turn it back on
options(warn = 0)
# related
suppressForeignCheck()
suppressMessages()
suppressPackageStartupMessages()
| /R_Scripts/options__suppress.R | permissive | joshuakevinjones/Code_Files | R | false | false | 492 | r |
# -- ============================================================
# -- Josh
# -- no project
# -- 2018/07/17
# -- suppress warnings globally
# comments go here
#
# -- ============================================================
# expression
suppressWarnings(expr)
# example usage
suppressWarnings(library(dplyr))
# do it globally
options(warn = -1)
# turn it back on
options(warn = 0)
# related
suppressForeignCheck()
suppressMessages()
suppressPackageStartupMessages()
|
#' @importFrom dplyr filter select group_by rename mutate if_else full_join left_join arrange summarise right_join ungroup distinct summarize bind_cols
#' @importFrom tidyr pivot_wider
#' @importFrom tibble as_tibble tibble deframe
#' @importFrom stringr str_to_title
#' @importFrom stats na.omit
#' @importFrom purrr map
#' @importFrom magrittr %>%
#' @importFrom Rdpack reprompt
#' @importFrom ggparliament parliament_data
#' @importFrom ggplot2 ggplot aes geom_tile scale_fill_manual labs theme element_text theme_minimal
vars <- c('elecciones_uy', 'eleccion', 'concurrente', 'partido', 'fecha', 'cant_votos', 'Cant_votos',
'departamento', 'camara', 'Senadores', 'Diputados', 'sum_votos_par', 'por_deptos', 'seats', 'Freq',
'por_nacional', 'sum_diputados', 'sum_senadores', 'Por_nacional', 'Sum_diputados', 'Sum_senadores',
'votos', 'Votos', 'total', 'Porcentaje', 'partidos_uy', 'Por_deptos', 'bancas_diputados', 'bancas_senado',
'corte', 'Eleccion', 'Departamento', 'Partido', 'Sigla', 'Fecha', 'anio_eleccion', 'Var2', 'Var1',
'Sum_votos_par', 'election', 'unit', 'sum_partidos', 'votes', 'votes_nac'
)
if(getRversion() >= "2.15.1"){
utils::globalVariables(c('.', vars))
utils::suppressForeignCheck(c('.', vars))
}
sigla <- function(dat){
p <- partidos_uy
p[nrow(p) + 1, c(1:2)] <- c('Voto en Blanco', 'VB')
p[nrow(p) + 1, c(1:2)] <- c('Voto Anulado', 'VA')
u <- which(names(dat) == 'Partido')
left_join(dat, p[, 1:2], by = 'Partido') %>%
select(1:u, Sigla, (u+1):ncol(.))
}
ap <- function(datos, umbral = 2, departamental){
if(departamental){
datos1 <- datos %>%
summarise(Votos = sum(Votos),
Porcentaje = sum(Porcentaje)) %>%
rename(Partido = corte) %>%
left_join(., partidos_uy[,c("Partido","Sigla")], by = 'Partido')
} else {
datos1 <- datos %>%
summarise(Votos = sum(Votos),
Porcentaje = sum(Porcentaje),
Diputados = sum(Diputados),
Senadores = sum(Senadores)) %>%
rename(Partido = corte) %>%
left_join(., partidos_uy[,c("Partido","Sigla")], by = 'Partido')
}
datos1
}
header <- function(base){
total <- sum(base == "X")
parcial <- apply(base, 2, function(x){sum(x == 'X', na.rm = TRUE)})
porcen <- paste0(" (", round(parcial/total*100), "%)")
cat("\n\n--- Cantidad de elecciones ------------------------------------\n\n")
cat(crayon::green$bold("-->"), " Presidencial :", crayon::blue$bold(parcial[1], porcen[1]),"\n")
cat(crayon::green$bold("-->"), " Balotaje :", crayon::blue$bold(parcial[2], " ", porcen[2]) ,"\n")
cat(crayon::green$bold("-->"), " Departamental :", crayon::blue$bold(parcial[3], porcen[3]) ,"\n")
cat(crayon::green$bold("-->"), " Legislativa :", crayon::blue$bold(parcial[4], porcen[4]) ,"\n")
cat(crayon::green$bold("-->"), " Consejo Nacional de Administracion :", crayon::blue$bold(parcial[5], " ", porcen[5]) ,"\n\n")
cat("---------------------------------------------------------------\n\n")
}
#init_summ <- function(){
# j <- elecciones_uy %>% select(anio_eleccion, eleccion) %>% distinct()
# table(j$anio_eleccion, j$eleccion) %>% as.data.frame()
#}
init_summ <- function(){
j <- elecciones_uy %>% select(anio_eleccion, eleccion, concurrente) %>% distinct()
j <- rbind(j[, -3], data.frame(anio_eleccion = j[which(j$concurrente == 1), "anio_eleccion"], eleccion = "Legislativa"))
table(j$anio_eleccion, j$eleccion) %>% as.data.frame()
}
pre_out <- function(datos, eleccion, vbva.rm) {
d <- datos %>% dplyr::filter(anio_eleccion == {{eleccion}})
if(vbva.rm){
ubic <- which(d$partido %in% c('Voto en Blanco', 'Voto Anulado'))
d <- d[-ubic, ]
}
d %>%
group_by(departamento, partido, fecha) %>%
summarise(
cant_votos = sum(votos, na.rm = TRUE),
Diputados = sum(bancas_diputados, na.rm = TRUE),
Senadores = sum(bancas_senado, na.rm = TRUE)/length(unique(departamento))
) %>%
ungroup() %>%
group_by(departamento) %>%
mutate (por_deptos = round((cant_votos / sum(cant_votos, na.rm = TRUE)) * 100, 2)) %>%
ungroup() %>%
mutate(total = sum(cant_votos, na.rm = TRUE)) %>%
group_by(partido) %>%
mutate(
por_nacional = (sum(cant_votos, na.rm = TRUE) / total) * 100,
sum_diputados = sum(Diputados, na.rm = TRUE),
sum_senadores = sum(Senadores, na.rm = TRUE)/length(unique(departamento)),
sum_votos_par = sum(cant_votos, na.rm = TRUE),
fecha = as.Date(fecha)
) %>%
ungroup() %>%
select(-c(total))
}
concurrente <- function(eleccion, tipo){
elecciones_uy %>%
filter(eleccion == {{tipo}}, anio_eleccion == {{eleccion}}) %>%
select(concurrente) %>%
unique() %>%
deframe()
}
e1962_66 <- function(x){
x[x$election == 1962 & x$party == "Partido Democrata Cristiano" ,"party"] <- "Union Civica"
x[x$election == 1962 & x$party == "Frente Izquierda de Liberacion","party"] <- "Partido Comunista del Uruguay"
x[x$election == 1962 & x$party == "Union Popular" ,"party"] <- "Partido Socialista"
x[x$election == 1966 & x$party == "Partido Democrata Cristiano" ,"party"] <- "Union Civica"
x[x$election == 1966 & x$party == "Frente Izquierda de Liberacion","party"] <- "Partido Comunista del Uruguay"
#x[x$election == 1966 & x$party == "Union Popular" ,"party"] <- "Partido Socialista"
return(x)
}
zero <- function(.X){.X[.X$Votos != 0,]}
#' @title departamentos
#' @description contiene los nombres de los 19 departamentos de Uruguay
#' @export
departamentos <- c(
"Artigas",
"Canelones",
"Cerro Largo",
"Colonia",
"Durazno",
"Flores",
"Florida",
"Lavalleja",
"Maldonado",
"Montevideo",
"Paysandu",
"Rio Negro",
"Rivera",
"Rocha",
"Salto",
"San Jose",
"Soriano",
"Tacuarembo",
"Treinta y Tres"
)
| /R/utils.R | no_license | egiacometti/Boreluy | R | false | false | 6,317 | r |
#' @importFrom dplyr filter select group_by rename mutate if_else full_join left_join arrange summarise right_join ungroup distinct summarize bind_cols
#' @importFrom tidyr pivot_wider
#' @importFrom tibble as_tibble tibble deframe
#' @importFrom stringr str_to_title
#' @importFrom stats na.omit
#' @importFrom purrr map
#' @importFrom magrittr %>%
#' @importFrom Rdpack reprompt
#' @importFrom ggparliament parliament_data
#' @importFrom ggplot2 ggplot aes geom_tile scale_fill_manual labs theme element_text theme_minimal
vars <- c('elecciones_uy', 'eleccion', 'concurrente', 'partido', 'fecha', 'cant_votos', 'Cant_votos',
'departamento', 'camara', 'Senadores', 'Diputados', 'sum_votos_par', 'por_deptos', 'seats', 'Freq',
'por_nacional', 'sum_diputados', 'sum_senadores', 'Por_nacional', 'Sum_diputados', 'Sum_senadores',
'votos', 'Votos', 'total', 'Porcentaje', 'partidos_uy', 'Por_deptos', 'bancas_diputados', 'bancas_senado',
'corte', 'Eleccion', 'Departamento', 'Partido', 'Sigla', 'Fecha', 'anio_eleccion', 'Var2', 'Var1',
'Sum_votos_par', 'election', 'unit', 'sum_partidos', 'votes', 'votes_nac'
)
if(getRversion() >= "2.15.1"){
utils::globalVariables(c('.', vars))
utils::suppressForeignCheck(c('.', vars))
}
sigla <- function(dat){
p <- partidos_uy
p[nrow(p) + 1, c(1:2)] <- c('Voto en Blanco', 'VB')
p[nrow(p) + 1, c(1:2)] <- c('Voto Anulado', 'VA')
u <- which(names(dat) == 'Partido')
left_join(dat, p[, 1:2], by = 'Partido') %>%
select(1:u, Sigla, (u+1):ncol(.))
}
ap <- function(datos, umbral = 2, departamental){
if(departamental){
datos1 <- datos %>%
summarise(Votos = sum(Votos),
Porcentaje = sum(Porcentaje)) %>%
rename(Partido = corte) %>%
left_join(., partidos_uy[,c("Partido","Sigla")], by = 'Partido')
} else {
datos1 <- datos %>%
summarise(Votos = sum(Votos),
Porcentaje = sum(Porcentaje),
Diputados = sum(Diputados),
Senadores = sum(Senadores)) %>%
rename(Partido = corte) %>%
left_join(., partidos_uy[,c("Partido","Sigla")], by = 'Partido')
}
datos1
}
header <- function(base){
total <- sum(base == "X")
parcial <- apply(base, 2, function(x){sum(x == 'X', na.rm = TRUE)})
porcen <- paste0(" (", round(parcial/total*100), "%)")
cat("\n\n--- Cantidad de elecciones ------------------------------------\n\n")
cat(crayon::green$bold("-->"), " Presidencial :", crayon::blue$bold(parcial[1], porcen[1]),"\n")
cat(crayon::green$bold("-->"), " Balotaje :", crayon::blue$bold(parcial[2], " ", porcen[2]) ,"\n")
cat(crayon::green$bold("-->"), " Departamental :", crayon::blue$bold(parcial[3], porcen[3]) ,"\n")
cat(crayon::green$bold("-->"), " Legislativa :", crayon::blue$bold(parcial[4], porcen[4]) ,"\n")
cat(crayon::green$bold("-->"), " Consejo Nacional de Administracion :", crayon::blue$bold(parcial[5], " ", porcen[5]) ,"\n\n")
cat("---------------------------------------------------------------\n\n")
}
#init_summ <- function(){
# j <- elecciones_uy %>% select(anio_eleccion, eleccion) %>% distinct()
# table(j$anio_eleccion, j$eleccion) %>% as.data.frame()
#}
init_summ <- function(){
j <- elecciones_uy %>% select(anio_eleccion, eleccion, concurrente) %>% distinct()
j <- rbind(j[, -3], data.frame(anio_eleccion = j[which(j$concurrente == 1), "anio_eleccion"], eleccion = "Legislativa"))
table(j$anio_eleccion, j$eleccion) %>% as.data.frame()
}
pre_out <- function(datos, eleccion, vbva.rm) {
d <- datos %>% dplyr::filter(anio_eleccion == {{eleccion}})
if(vbva.rm){
ubic <- which(d$partido %in% c('Voto en Blanco', 'Voto Anulado'))
d <- d[-ubic, ]
}
d %>%
group_by(departamento, partido, fecha) %>%
summarise(
cant_votos = sum(votos, na.rm = TRUE),
Diputados = sum(bancas_diputados, na.rm = TRUE),
Senadores = sum(bancas_senado, na.rm = TRUE)/length(unique(departamento))
) %>%
ungroup() %>%
group_by(departamento) %>%
mutate (por_deptos = round((cant_votos / sum(cant_votos, na.rm = TRUE)) * 100, 2)) %>%
ungroup() %>%
mutate(total = sum(cant_votos, na.rm = TRUE)) %>%
group_by(partido) %>%
mutate(
por_nacional = (sum(cant_votos, na.rm = TRUE) / total) * 100,
sum_diputados = sum(Diputados, na.rm = TRUE),
sum_senadores = sum(Senadores, na.rm = TRUE)/length(unique(departamento)),
sum_votos_par = sum(cant_votos, na.rm = TRUE),
fecha = as.Date(fecha)
) %>%
ungroup() %>%
select(-c(total))
}
concurrente <- function(eleccion, tipo){
elecciones_uy %>%
filter(eleccion == {{tipo}}, anio_eleccion == {{eleccion}}) %>%
select(concurrente) %>%
unique() %>%
deframe()
}
e1962_66 <- function(x){
x[x$election == 1962 & x$party == "Partido Democrata Cristiano" ,"party"] <- "Union Civica"
x[x$election == 1962 & x$party == "Frente Izquierda de Liberacion","party"] <- "Partido Comunista del Uruguay"
x[x$election == 1962 & x$party == "Union Popular" ,"party"] <- "Partido Socialista"
x[x$election == 1966 & x$party == "Partido Democrata Cristiano" ,"party"] <- "Union Civica"
x[x$election == 1966 & x$party == "Frente Izquierda de Liberacion","party"] <- "Partido Comunista del Uruguay"
#x[x$election == 1966 & x$party == "Union Popular" ,"party"] <- "Partido Socialista"
return(x)
}
zero <- function(.X){.X[.X$Votos != 0,]}
#' @title departamentos
#' @description contiene los nombres de los 19 departamentos de Uruguay
#' @export
departamentos <- c(
"Artigas",
"Canelones",
"Cerro Largo",
"Colonia",
"Durazno",
"Flores",
"Florida",
"Lavalleja",
"Maldonado",
"Montevideo",
"Paysandu",
"Rio Negro",
"Rivera",
"Rocha",
"Salto",
"San Jose",
"Soriano",
"Tacuarembo",
"Treinta y Tres"
)
|
# the model is following:
# logit(y_j/n_j) = a + b * x, where p_j = y_j / n_j
# y ~ binomial(n_j,p_j)
# logistic regression
y <- c(1346,577,337,208,149,136,111,69,67,75,52,46,54,28,27,31,33,20,24)
n <- c(1443,674,455,353,272,256,240,217,200,237,202,192,174,167,201,193,191,147,152)
x <- 1:19
J <- 19
data <- list(y=y,x=x,n=n,J=J)
library(rstan)
options(mc.cores=parallel::detectCores())
rstan_options(auto_write=TRUE)
result <- stan('golf.stan',data=data)
print(result,digit=2)
p_hat <- y / n
fit <- extract(result)
a_mean <- mean(fit$a)
b_mean <- mean(fit$b)
n_of_simulation <- length(fit$a)
plot(x,p_hat)
curve(exp(a_mean + b_mean*x)/(1+exp(a_mean + b_mean*x)),add=T,col='red',lwd=1)
for ( i in sample(n_of_simulation,20)){
a_post <- fit$a[i]
b_post <- fit$b[i]
curve(exp(a_post + b_post*x)/(1+exp(a_post + b_post*x)),add=T,col='blue',lwd=0.5)
}
# model from first principle
data <- list(y=y,x=x,n=n,J=J,r=1.68*0.0833333,R=4.25*0.0833333) ### inch to feet
result_2 <- stan('golf_first.stan',data=data)
print(result_2,digit=2)
fit_2 <- extract(result_2)
sigma_mean <- mean(fit_2$sigma)
plot(x,p_hat)
curve(exp(a_mean + b_mean*x)/(1+exp(a_mean + b_mean*x)),add=T,col='red',lwd=1)
curve(2*pnorm(asin((data$R-data$r)/x)/sigma_mean)-1, add=T,col='blue',lwd=1)
| /bayesian-data-analysis/stan textbook/chapter3/golf.r | no_license | yc3356/courses | R | false | false | 1,276 | r | # the model is following:
# logit(y_j/n_j) = a + b * x, where p_j = y_j / n_j
# y ~ binomial(n_j,p_j)
# logistic regression
y <- c(1346,577,337,208,149,136,111,69,67,75,52,46,54,28,27,31,33,20,24)
n <- c(1443,674,455,353,272,256,240,217,200,237,202,192,174,167,201,193,191,147,152)
x <- 1:19
J <- 19
data <- list(y=y,x=x,n=n,J=J)
library(rstan)
options(mc.cores=parallel::detectCores())
rstan_options(auto_write=TRUE)
result <- stan('golf.stan',data=data)
print(result,digit=2)
p_hat <- y / n
fit <- extract(result)
a_mean <- mean(fit$a)
b_mean <- mean(fit$b)
n_of_simulation <- length(fit$a)
plot(x,p_hat)
curve(exp(a_mean + b_mean*x)/(1+exp(a_mean + b_mean*x)),add=T,col='red',lwd=1)
for ( i in sample(n_of_simulation,20)){
a_post <- fit$a[i]
b_post <- fit$b[i]
curve(exp(a_post + b_post*x)/(1+exp(a_post + b_post*x)),add=T,col='blue',lwd=0.5)
}
# model from first principle
data <- list(y=y,x=x,n=n,J=J,r=1.68*0.0833333,R=4.25*0.0833333) ### inch to feet
result_2 <- stan('golf_first.stan',data=data)
print(result_2,digit=2)
fit_2 <- extract(result_2)
sigma_mean <- mean(fit_2$sigma)
plot(x,p_hat)
curve(exp(a_mean + b_mean*x)/(1+exp(a_mean + b_mean*x)),add=T,col='red',lwd=1)
curve(2*pnorm(asin((data$R-data$r)/x)/sigma_mean)-1, add=T,col='blue',lwd=1)
|
########################################################
# baseflow hydrograph
########################################################
output$hydgrph.bf <- renderDygraph({
if (input$bf.shwall) {
isolate(
if (!is.null(sta$hyd)){
if (!sta$BFbuilt) separateHydrograph()
build_hydrograph(c('Flow','BF.min','BF.max',
'BF.LH','BF.CM','BF.BE','BF.JH','BF.Cl',
'BF.UKn','BF.UKm','BF.UKx',
'BF.HYSEP.FI','BF.HYSEP.SI','BF.HYSEP.LM',
'BF.PART1','BF.PART2','BF.PART3'))
}
)
} else {
isolate(
if (!is.null(sta$hyd)){
if (!sta$BFbuilt) separateHydrograph()
build_hydrograph(c('Flow','BF.min','BF.max'))
}
)
}
})
build_hydrograph <- function(sset){
# sset <- c('Flow','BF.min','BF.max')
qxts <- xts(sta$hyd[,sset], order.by = sta$hyd$Date)
showNotification('plot rendering, please be patient..', duration = 10)
p <- dygraph(qxts) %>%
dySeries(c('BF.min','Flow','BF.max'),label='Discharge',strokeWidth=3) %>%
dyOptions(axisLineWidth = 1.5) %>%
dyAxis(name='y', label=dylabcms) %>%
dyLegend(width = 500) %>%
dyRangeSelector(height=80)
return(p)
}
select_hydrographs <- function(){
showNotification('asdfasdf')
s <- c('Flow','BF.min','BF.max')
if (input$BF.LH) s <- append(s, 'BF.LH')
return(s)
}
separateHydrograph <- function(){
# progress bar
progress <- shiny::Progress$new()
progress$set(message = "separating hydrograph..", detail = 'initializing..', value = 0.1)
on.exit(progress$close())
updateProgress <- function(value = NULL, detail = NULL) {
if (is.null(value)) {
value <- progress$getValue()
value <- value + (progress$getMax() - value) / 5
}
progress$set(value = value, detail = detail)
}
if (!is.null(sta$hyd) & !sta$BFbuilt){
sta$hyd <- baseflow_range(sta$hyd,sta$carea,sta$k,BFp,updateProgress)
sta$BFbuilt <- TRUE
progress$set(value = 1)
}
}
| /server/hydrograph/separation.R | permissive | tanxuezhi/sHydrology_analysis | R | false | false | 2,032 | r |
########################################################
# baseflow hydrograph
########################################################
output$hydgrph.bf <- renderDygraph({
if (input$bf.shwall) {
isolate(
if (!is.null(sta$hyd)){
if (!sta$BFbuilt) separateHydrograph()
build_hydrograph(c('Flow','BF.min','BF.max',
'BF.LH','BF.CM','BF.BE','BF.JH','BF.Cl',
'BF.UKn','BF.UKm','BF.UKx',
'BF.HYSEP.FI','BF.HYSEP.SI','BF.HYSEP.LM',
'BF.PART1','BF.PART2','BF.PART3'))
}
)
} else {
isolate(
if (!is.null(sta$hyd)){
if (!sta$BFbuilt) separateHydrograph()
build_hydrograph(c('Flow','BF.min','BF.max'))
}
)
}
})
build_hydrograph <- function(sset){
# sset <- c('Flow','BF.min','BF.max')
qxts <- xts(sta$hyd[,sset], order.by = sta$hyd$Date)
showNotification('plot rendering, please be patient..', duration = 10)
p <- dygraph(qxts) %>%
dySeries(c('BF.min','Flow','BF.max'),label='Discharge',strokeWidth=3) %>%
dyOptions(axisLineWidth = 1.5) %>%
dyAxis(name='y', label=dylabcms) %>%
dyLegend(width = 500) %>%
dyRangeSelector(height=80)
return(p)
}
select_hydrographs <- function(){
showNotification('asdfasdf')
s <- c('Flow','BF.min','BF.max')
if (input$BF.LH) s <- append(s, 'BF.LH')
return(s)
}
separateHydrograph <- function(){
# progress bar
progress <- shiny::Progress$new()
progress$set(message = "separating hydrograph..", detail = 'initializing..', value = 0.1)
on.exit(progress$close())
updateProgress <- function(value = NULL, detail = NULL) {
if (is.null(value)) {
value <- progress$getValue()
value <- value + (progress$getMax() - value) / 5
}
progress$set(value = value, detail = detail)
}
if (!is.null(sta$hyd) & !sta$BFbuilt){
sta$hyd <- baseflow_range(sta$hyd,sta$carea,sta$k,BFp,updateProgress)
sta$BFbuilt <- TRUE
progress$set(value = 1)
}
}
|
# Simulated process for 1 Month ahead
M3_sim_1M_func <- function(x){
mysim_M3 <- ugarchsim(x, n.sim = 22, m.sim =100, startMethod = "sample")
M3_sim <- fitted(mysim_M3) %>% # extract simulated values
as.data.frame() #covert to data frame
# create simulation path dates and bind them with simulations
date_col <- dateconverter(as.Date("2018-09-14"), as.Date("2018-10-15"),
"weekdays")
date_col <- data.frame(Date = date_col)
M3_sim <- cbind(date_col, M3_sim) %>%
as.tbl() %>% tbl_xts() # make xts to work with performance analytics package
# NB!! Data is in untidy format to create portfolio in performance analytics package
} | /Final Project/code/M3_sim_1M_func.R | no_license | Richard19leigh93/Financial-Econometrics | R | false | false | 721 | r | # Simulated process for 1 Month ahead
M3_sim_1M_func <- function(x){
mysim_M3 <- ugarchsim(x, n.sim = 22, m.sim =100, startMethod = "sample")
M3_sim <- fitted(mysim_M3) %>% # extract simulated values
as.data.frame() #covert to data frame
# create simulation path dates and bind them with simulations
date_col <- dateconverter(as.Date("2018-09-14"), as.Date("2018-10-15"),
"weekdays")
date_col <- data.frame(Date = date_col)
M3_sim <- cbind(date_col, M3_sim) %>%
as.tbl() %>% tbl_xts() # make xts to work with performance analytics package
# NB!! Data is in untidy format to create portfolio in performance analytics package
} |
# Membership changes in time analysis.
gid1 = groups.ids[1]
gid2 = groups.ids[2]
group1.rows = train[,group.id]==gid1
group2.rows = train[,group.id]==gid2
time0.rows = train[,time.id]==time.t0
time1.rows = train[,time.id]==time.t1
g1.t0.colsums = colSums(membership.matrix[group1.rows & time0.rows, ])
g2.t0.colsums = colSums(membership.matrix[group2.rows & time0.rows, ])
g1.t1.colsums = colSums(membership.matrix[group1.rows & time1.rows, ])
g2.t1.colsums = colSums(membership.matrix[group2.rows & time1.rows, ])
print("GROUPS IN DIFFERENT TIME MOMENTS IN CLUSTERS:")
print(paste("Group", gid1, "time ", time.t0))
print(g1.t0.colsums)
print(paste("Group", gid2, "time ", time.t0))
print(g2.t0.colsums)
print(paste("Group", gid1, "time ", time.t1))
print(g1.t1.colsums)
print(paste("Group", gid2, "time ", time.t1))
print(g2.t1.colsums)
print(paste("Difference between groups (#",gid2,"- #",gid1,") in ", time.t0))
print(g2.t0.colsums-g1.t0.colsums)
print(paste("Relative change in group", gid1))
print((g1.t1.colsums-g1.t0.colsums ) / g1.t0.colsums )
print(paste("Relative change in group", gid2))
print((g2.t1.colsums-g2.t0.colsums ) / g2.t0.colsums )
source(file="groups_clusters_distribution.r")
p.value = CompareGroupsInClusters(train, membership.matrix,
gid1, gid2,
num.repetitions.comp.distribution.changes,
statistic.calculator = GroupsInClustersRelativeChangeStat,
histogramtitle="RDC Statistic distribution",
xlab = "RDC value")
print(paste("CompareGroupsInClusters (GroupsInClustersRelativeChangeStat): Group",
gid1," vs Group",gid2,"-> p.value =", p.value))
StorePlot(paste(output.dir,'/pvalues_CompareGroupsInClusters',sep=''), dpi=90, w=640, h=480)
| /clustering/routine_group_distributions_change.r | no_license | mlukasik/spines | R | false | false | 1,904 | r | # Membership changes in time analysis.
gid1 = groups.ids[1]
gid2 = groups.ids[2]
group1.rows = train[,group.id]==gid1
group2.rows = train[,group.id]==gid2
time0.rows = train[,time.id]==time.t0
time1.rows = train[,time.id]==time.t1
g1.t0.colsums = colSums(membership.matrix[group1.rows & time0.rows, ])
g2.t0.colsums = colSums(membership.matrix[group2.rows & time0.rows, ])
g1.t1.colsums = colSums(membership.matrix[group1.rows & time1.rows, ])
g2.t1.colsums = colSums(membership.matrix[group2.rows & time1.rows, ])
print("GROUPS IN DIFFERENT TIME MOMENTS IN CLUSTERS:")
print(paste("Group", gid1, "time ", time.t0))
print(g1.t0.colsums)
print(paste("Group", gid2, "time ", time.t0))
print(g2.t0.colsums)
print(paste("Group", gid1, "time ", time.t1))
print(g1.t1.colsums)
print(paste("Group", gid2, "time ", time.t1))
print(g2.t1.colsums)
print(paste("Difference between groups (#",gid2,"- #",gid1,") in ", time.t0))
print(g2.t0.colsums-g1.t0.colsums)
print(paste("Relative change in group", gid1))
print((g1.t1.colsums-g1.t0.colsums ) / g1.t0.colsums )
print(paste("Relative change in group", gid2))
print((g2.t1.colsums-g2.t0.colsums ) / g2.t0.colsums )
source(file="groups_clusters_distribution.r")
p.value = CompareGroupsInClusters(train, membership.matrix,
gid1, gid2,
num.repetitions.comp.distribution.changes,
statistic.calculator = GroupsInClustersRelativeChangeStat,
histogramtitle="RDC Statistic distribution",
xlab = "RDC value")
print(paste("CompareGroupsInClusters (GroupsInClustersRelativeChangeStat): Group",
gid1," vs Group",gid2,"-> p.value =", p.value))
StorePlot(paste(output.dir,'/pvalues_CompareGroupsInClusters',sep=''), dpi=90, w=640, h=480)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.