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
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/apigateway_operations.R \name{apigateway_update_method_response} \alias{apigateway_update_method_response} \title{Updates an existing MethodResponse resource} \usage{ apigateway_update_method_response(restApiId, resourceId, httpMethod, statusCode, patchOperations) } \arguments{ \item{restApiId}{[required] [Required] The string identifier of the associated RestApi.} \item{resourceId}{[required] [Required] The Resource identifier for the MethodResponse resource.} \item{httpMethod}{[required] [Required] The HTTP verb of the Method resource.} \item{statusCode}{[required] [Required] The status code for the MethodResponse resource.} \item{patchOperations}{A list of update operations to be applied to the specified resource and in the order specified in this list.} } \value{ A list with the following syntax:\preformatted{list( statusCode = "string", responseParameters = list( TRUE|FALSE ), responseModels = list( "string" ) ) } } \description{ Updates an existing MethodResponse resource. } \section{Request syntax}{ \preformatted{svc$update_method_response( restApiId = "string", resourceId = "string", httpMethod = "string", statusCode = "string", patchOperations = list( list( op = "add"|"remove"|"replace"|"move"|"copy"|"test", path = "string", value = "string", from = "string" ) ) ) } } \keyword{internal}
/cran/paws.networking/man/apigateway_update_method_response.Rd
permissive
TWarczak/paws
R
false
true
1,464
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/apigateway_operations.R \name{apigateway_update_method_response} \alias{apigateway_update_method_response} \title{Updates an existing MethodResponse resource} \usage{ apigateway_update_method_response(restApiId, resourceId, httpMethod, statusCode, patchOperations) } \arguments{ \item{restApiId}{[required] [Required] The string identifier of the associated RestApi.} \item{resourceId}{[required] [Required] The Resource identifier for the MethodResponse resource.} \item{httpMethod}{[required] [Required] The HTTP verb of the Method resource.} \item{statusCode}{[required] [Required] The status code for the MethodResponse resource.} \item{patchOperations}{A list of update operations to be applied to the specified resource and in the order specified in this list.} } \value{ A list with the following syntax:\preformatted{list( statusCode = "string", responseParameters = list( TRUE|FALSE ), responseModels = list( "string" ) ) } } \description{ Updates an existing MethodResponse resource. } \section{Request syntax}{ \preformatted{svc$update_method_response( restApiId = "string", resourceId = "string", httpMethod = "string", statusCode = "string", patchOperations = list( list( op = "add"|"remove"|"replace"|"move"|"copy"|"test", path = "string", value = "string", from = "string" ) ) ) } } \keyword{internal}
rankhospital <- function(state, outcome, num = "best") { ## Read outcome data datFile <- "outcome-of-care-measures.csv" dat <- read.table(datFile, header = TRUE, colClasses = "character", sep = ",", check.names = FALSE) ## Clean up column names (strip extraneous spaces and convert ## to upper for search purposes); convert columns 11,17,23 (30 day mortality data) ## to numeric columns nameList <- names(dat) tNameList <- gsub(" ", " ", nameList) tNameList <- toupper(tNameList) colnames(dat) <- tNameList suppressWarnings(dat[,11] <- as.numeric(dat[,11])) suppressWarnings(dat[,17] <- as.numeric(dat[,17])) suppressWarnings(dat[,23] <- as.numeric(dat[,23])) ## Check that state and outcome are valid ## Validate State foundState <- dat[dat[, 7] == state, ] if (nrow(foundState) == 0) { stop("invalid state") } ## Validate outcome foundOutcome <- grep(outcome, tNameList, ignore.case = TRUE) if (length(foundOutcome) == 0) { stop("invalid outcome") } ## Subset data to selected state stateDat <- dat[(dat[ , 7] == toupper(state)), ] ## Return hospital name in that state with lowest 30-day death rate ## bestHospital <- min(dat[ochdr], na.rm = TRUE) ochdr <- paste("Hospital 30-Day Death (Mortality) Rates from", outcome, sep = " ") ucochdr <- toupper(ochdr) ## Get the column index for the appropriate outcome colidx <- which(colnames(stateDat) == ucochdr) ## Rank the data rankDat <- stateDat[order(stateDat[,colidx], stateDat[,2]),c(2,colidx) ] ## Append the rank order numReturned <- nrow(rankDat) rankOrderVector <- 1:numReturned rankDat <- cbind(rankDat,rankOrderVector) ## Add column names colnames(rankDat) <- c("Hospital.Name", "Rate", "Rank") ## Return the appropriate ranked hospital if (is.numeric(num) && num > numReturned) { return("NA") } else if (num == "best") { idx <- 1 } else if (num == "worst") { worstVal <- max(rankDat[, 2], na.rm = TRUE) worstDat <- rankDat[which(rankDat["Rate"] == worstVal), ] idx <- max(worstDat[,"Rank"], na.rm = TRUE) } else { idx <- num } ##rankDat <- stateDat[with(stateDat, order(stateDat[,colidx], stateDat[,2])), ] return(rankDat[idx, 1]) }
/Assignments/Assignment3/rankhospital.R
no_license
kboulas/RProgramming
R
false
false
2,728
r
rankhospital <- function(state, outcome, num = "best") { ## Read outcome data datFile <- "outcome-of-care-measures.csv" dat <- read.table(datFile, header = TRUE, colClasses = "character", sep = ",", check.names = FALSE) ## Clean up column names (strip extraneous spaces and convert ## to upper for search purposes); convert columns 11,17,23 (30 day mortality data) ## to numeric columns nameList <- names(dat) tNameList <- gsub(" ", " ", nameList) tNameList <- toupper(tNameList) colnames(dat) <- tNameList suppressWarnings(dat[,11] <- as.numeric(dat[,11])) suppressWarnings(dat[,17] <- as.numeric(dat[,17])) suppressWarnings(dat[,23] <- as.numeric(dat[,23])) ## Check that state and outcome are valid ## Validate State foundState <- dat[dat[, 7] == state, ] if (nrow(foundState) == 0) { stop("invalid state") } ## Validate outcome foundOutcome <- grep(outcome, tNameList, ignore.case = TRUE) if (length(foundOutcome) == 0) { stop("invalid outcome") } ## Subset data to selected state stateDat <- dat[(dat[ , 7] == toupper(state)), ] ## Return hospital name in that state with lowest 30-day death rate ## bestHospital <- min(dat[ochdr], na.rm = TRUE) ochdr <- paste("Hospital 30-Day Death (Mortality) Rates from", outcome, sep = " ") ucochdr <- toupper(ochdr) ## Get the column index for the appropriate outcome colidx <- which(colnames(stateDat) == ucochdr) ## Rank the data rankDat <- stateDat[order(stateDat[,colidx], stateDat[,2]),c(2,colidx) ] ## Append the rank order numReturned <- nrow(rankDat) rankOrderVector <- 1:numReturned rankDat <- cbind(rankDat,rankOrderVector) ## Add column names colnames(rankDat) <- c("Hospital.Name", "Rate", "Rank") ## Return the appropriate ranked hospital if (is.numeric(num) && num > numReturned) { return("NA") } else if (num == "best") { idx <- 1 } else if (num == "worst") { worstVal <- max(rankDat[, 2], na.rm = TRUE) worstDat <- rankDat[which(rankDat["Rate"] == worstVal), ] idx <- max(worstDat[,"Rank"], na.rm = TRUE) } else { idx <- num } ##rankDat <- stateDat[with(stateDat, order(stateDat[,colidx], stateDat[,2])), ] return(rankDat[idx, 1]) }
library(mvtnorm) source("FP_sup.R") #load data dat <- data.load(pheno="pheno.csv",marker="genotype.csv",time=1:31) #Null hypothesis H0 <- mle_curve(pheno=dat$phenotype,times=dat$time) #Alternative hypothesis ret <- mle_H1(dat,times=dat$time) head(ret) #P-value of all markers P <- ret[,2] P
/example.R
no_license
FFP-FM/Version1
R
false
false
328
r
library(mvtnorm) source("FP_sup.R") #load data dat <- data.load(pheno="pheno.csv",marker="genotype.csv",time=1:31) #Null hypothesis H0 <- mle_curve(pheno=dat$phenotype,times=dat$time) #Alternative hypothesis ret <- mle_H1(dat,times=dat$time) head(ret) #P-value of all markers P <- ret[,2] P
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/converter.R \name{db_type_converter} \alias{db_type_converter} \title{db_type_converter} \usage{ db_type_converter(data, dbname) } \arguments{ \item{data}{The actual data.frame to convert.} \item{dbname}{The name of the database. Used to distinguish data.} } \value{ The modified data.frame } \description{ This function converts the type to align with the requirement. See requirement online. } \examples{ # data is the output from any get_from_db function data <- get_from_db_usr("SELECT loadid FROM hedonics_new.sd_hedonics_new") # convert the type of the columns data <- db_type_converter(data) # ... or you can specify the database data <- db_type_converter(data, dbname = "zillow_2017_nov") }
/BDEEPZillow/man/db_type_converter.Rd
no_license
uiuc-bdeep/Zillow_Housing_Database
R
false
true
778
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/converter.R \name{db_type_converter} \alias{db_type_converter} \title{db_type_converter} \usage{ db_type_converter(data, dbname) } \arguments{ \item{data}{The actual data.frame to convert.} \item{dbname}{The name of the database. Used to distinguish data.} } \value{ The modified data.frame } \description{ This function converts the type to align with the requirement. See requirement online. } \examples{ # data is the output from any get_from_db function data <- get_from_db_usr("SELECT loadid FROM hedonics_new.sd_hedonics_new") # convert the type of the columns data <- db_type_converter(data) # ... or you can specify the database data <- db_type_converter(data, dbname = "zillow_2017_nov") }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/calc_streak.R \name{calc_streak} \alias{calc_streak} \title{Calculate hit streaks.} \usage{ calc_streak(x) } \arguments{ \item{x}{A data frame or character vector of hits (\code{"H"}) and misses (\code{"M"}).} } \value{ A data frame with one column, \code{length}, containing the length of each hit streak. } \description{ Calculate hit streaks. } \examples{ data(kobe_basket) calc_streak(kobe_basket$shot) }
/man/calc_streak.Rd
no_license
aaronbaggett/labs4316
R
false
true
489
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/calc_streak.R \name{calc_streak} \alias{calc_streak} \title{Calculate hit streaks.} \usage{ calc_streak(x) } \arguments{ \item{x}{A data frame or character vector of hits (\code{"H"}) and misses (\code{"M"}).} } \value{ A data frame with one column, \code{length}, containing the length of each hit streak. } \description{ Calculate hit streaks. } \examples{ data(kobe_basket) calc_streak(kobe_basket$shot) }
testlist <- list(data = structure(c(5.61333727981723e+112, 5.61333710690645e+112, 2.84809454419421e-306, 6.95335622242639e-310, 4.73673289555467e-299, 2.84809454946091e-306, 3.48604089790333e+30, 4.94065645841247e-324, 4.94065645841247e-324, 2.65249474364725e-315, 2.64227521380929e-308, 2.58981145570564e-307, 2.41766164638173e+35, 2.13916038880747e+30, 4.94065645841247e-324, 2.41737052174616e+35, 1.6259749693639e-260, 3.52953696534134e+30, 2.67356514185607e+29, 3.52953696534134e+30, 3.49284780194396e+30, 2.4173705217461e+35, 1.66880624265276e-307, 7.18522588728097e-304, 2.84809453888986e-306), .Dim = c(5L, 5L )), q = 1.58457842668591e+29) result <- do.call(biwavelet:::rcpp_row_quantile,testlist) str(result)
/biwavelet/inst/testfiles/rcpp_row_quantile/libFuzzer_rcpp_row_quantile/rcpp_row_quantile_valgrind_files/1610555092-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
724
r
testlist <- list(data = structure(c(5.61333727981723e+112, 5.61333710690645e+112, 2.84809454419421e-306, 6.95335622242639e-310, 4.73673289555467e-299, 2.84809454946091e-306, 3.48604089790333e+30, 4.94065645841247e-324, 4.94065645841247e-324, 2.65249474364725e-315, 2.64227521380929e-308, 2.58981145570564e-307, 2.41766164638173e+35, 2.13916038880747e+30, 4.94065645841247e-324, 2.41737052174616e+35, 1.6259749693639e-260, 3.52953696534134e+30, 2.67356514185607e+29, 3.52953696534134e+30, 3.49284780194396e+30, 2.4173705217461e+35, 1.66880624265276e-307, 7.18522588728097e-304, 2.84809453888986e-306), .Dim = c(5L, 5L )), q = 1.58457842668591e+29) result <- do.call(biwavelet:::rcpp_row_quantile,testlist) str(result)
pkgname <- "DivE" source(file.path(R.home("share"), "R", "examples-header.R")) options(warn = 1) options(pager = "console") base::assign(".ExTimings", "DivE-Ex.timings", pos = 'CheckExEnv') base::cat("name\tuser\tsystem\telapsed\n", file=base::get(".ExTimings", pos = 'CheckExEnv')) base::assign(".format_ptime", function(x) { if(!is.na(x[4L])) x[1L] <- x[1L] + x[4L] if(!is.na(x[5L])) x[2L] <- x[2L] + x[5L] options(OutDec = '.') format(x[1L:3L], digits = 7L) }, pos = 'CheckExEnv') ### * </HEADER> library('DivE') base::assign(".oldSearch", base::search(), pos = 'CheckExEnv') base::assign(".old_wd", base::getwd(), pos = 'CheckExEnv') cleanEx() nameEx("Bact1") ### * Bact1 flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: Bact1 ### Title: Count of Medically Important Bacteria Species in a Sample ### Aliases: Bact1 Bact2 ### Keywords: datasets ### ** Examples data(Bact1) hist(Bact1[,2], breaks=20, main="Bacterial diversity of a sample", xlab="Number of bacteria of a given species", ylab="Number of bacterial species") base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("Bact1", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("CombDM") ### * CombDM flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: CombDM ### Title: CombDM ### Aliases: CombDM ### Keywords: diversity ### ** Examples # See DiveMaster documentation for examples. base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("CombDM", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("Curvature") ### * Curvature flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: Curvature ### Title: Curvature ### Aliases: Curvature ### Keywords: diversity ### ** Examples # See DivSubsamples documentation for examples. base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("Curvature", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("DivSampleNum") ### * DivSampleNum flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: DivSampleNum ### Title: DivSampleNum ### Aliases: DivSampleNum ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) DivSampleNum(Bact1, 3) DivSampleNum(Bact1, 6) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("DivSampleNum", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("DivSubsamples") ### * DivSubsamples flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: DivSubsamples ### Title: DivSubsamples ### Aliases: DivSubsamples print.DivSubsamples summary.DivSubsamples ### print.summary.DivSubsamples ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) dss_1 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=100, NResamples=10) dss_2 <- DivSubsamples(Bact1, nrf=20, minrarefac=1, maxrarefac=100, NResamples=10) # Default NResamples=1000; low value of NResamples=10 is a set for quick evaluation dss_1 dss_2 summary(dss_1) dss_1$div_sd dss_1$NResamples Curvature(dss_1) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("DivSubsamples", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("DiveMaster") ### * DiveMaster flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: DiveMaster ### Title: DiveMaster ### Aliases: DiveMaster print.DiveMaster summary.DiveMaster ### print.summary.DiveMaster ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) data(ModelSet) data(ParamSeeds) data(ParamRanges) testmodels <- list() testmeta <- list() paramranges <- list() # Choose a single model testmodels <- c(testmodels, ModelSet[1]) #testmeta[[1]] <- (ParamSeeds[[1]]) # Commented out for sake of brevity) testmeta[[1]] <- matrix(c(0.9451638, 0.007428265, 0.9938149, 1.0147441, 0.009543598, 0.9870419), nrow=2, byrow=TRUE, dimnames=list(c(), c("a1", "a2", "a3"))) # Example seeds paramranges[[1]] <- ParamRanges[[1]] # Create DivSubsamples object (NB: For quick illustration only -- not default parameters) dss_1 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=40, NResamples=5) dss_2 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=65, NResamples=5) dss <- list(dss_2, dss_1) # Implement the function (NB: For quick illustration only -- not default parameters) out <- DiveMaster(models=testmodels, init.params=testmeta, param.ranges=paramranges, main.samp=Bact1, subsizes=c(65, 40), NResamples=5, fitloops=1, dssamp=dss, numit=2, varleft=10) # DiveMaster Outputs out out$estimate out$fmm$logistic out$fmm$logistic$global out$ssm summary(out) ## Combining two DiveMaster objects (assuming a second object 'out2'): # out3 <- CombDM(list(out, out2)) ## To calculate the diversity for a different population size # PopDiversity(dm=out, popsize=10^5, TopX=1) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("DiveMaster", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("FitSingleMod") ### * FitSingleMod flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: FitSingleMod ### Title: FitSingleMod ### Aliases: FitSingleMod print.FitSingleMod summary.FitSingleMod ### print.summary.FitSingleMod plot.FitSingleMod ### Keywords: diversity ### ** Examples # See documentation of \code{ScoreSingleMod} for examples base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("FitSingleMod", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ModelSet") ### * ModelSet flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ModelSet ### Title: List of 58 candidate models to fit to data ### Aliases: ModelSet ### Keywords: datasets ### ** Examples data(ModelSet) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ModelSet", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ParamRanges") ### * ParamRanges flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ParamRanges ### Title: List of 58 sets of upper and lower bounds for models evaluated ### by DivE ### Aliases: ParamRanges ### Keywords: datasets ### ** Examples data(ParamRanges) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ParamRanges", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ParamSeeds") ### * ParamSeeds flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ParamSeeds ### Title: List of 58 matrices of model seeding parameters. ### Aliases: ParamSeeds ### Keywords: datasets ### ** Examples data(ParamSeeds) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ParamSeeds", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("PopDiversity") ### * PopDiversity flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: PopDiversity ### Title: PopDiversity ### Aliases: PopDiversity ### Keywords: diversity ### ** Examples # See DiveMaster documentation for examples. base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("PopDiversity", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ScoreSingleMod") ### * ScoreSingleMod flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ScoreSingleMod ### Title: ScoreSingleMod ### Aliases: ScoreSingleMod print.ScoreSingleMod summary.ScoreSingleMod ### print.summary.ScoreSingleMod ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) data(ModelSet) data(ParamSeeds) data(ParamRanges) testmodels <- list() testmeta <- list() paramranges <- list() # Choose a single model testmodels <- c(testmodels, ModelSet[1]) # testmeta <- (ParamSeeds[[1]]) # Commented out for sake of brevity) testmeta <- matrix(c(0.9451638, 0.007428265, 0.9938149, 1.0147441, 0.009543598, 0.9870419), nrow=2, byrow=TRUE, dimnames=list(c(), c("a1", "a2", "a3"))) # Example seeds paramranges <- ParamRanges[[1]] # Create DivSubsamples object (NB: For quick illustration only -- not default parameters) dss_1 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=40, NResamples=5) dss_2 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=65, NResamples=5) dss <- list(dss_2, dss_1) # Fit the model (NB: For quick illustration only -- not default parameters) fsm <- FitSingleMod(model.list=testmodels, init.param=testmeta, param.range=paramranges, main.samp=Bact1, dssamps=dss, fitloops=1, data.default=FALSE, subsizes=c(65, 40), numit=2) # numit chosen to be extremely small to speed up example # Score the model ssm <- ScoreSingleMod(fsm) ssm summary(ssm) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ScoreSingleMod", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") ### * <FOOTER> ### cleanEx() options(digits = 7L) base::cat("Time elapsed: ", proc.time() - base::get("ptime", pos = 'CheckExEnv'),"\n") grDevices::dev.off() ### ### Local variables: *** ### mode: outline-minor *** ### outline-regexp: "\\(> \\)?### [*]+" *** ### End: *** quit('no')
/DivE.Rcheck/DivE-Ex.R
no_license
dlaydon/DivE
R
false
false
11,362
r
pkgname <- "DivE" source(file.path(R.home("share"), "R", "examples-header.R")) options(warn = 1) options(pager = "console") base::assign(".ExTimings", "DivE-Ex.timings", pos = 'CheckExEnv') base::cat("name\tuser\tsystem\telapsed\n", file=base::get(".ExTimings", pos = 'CheckExEnv')) base::assign(".format_ptime", function(x) { if(!is.na(x[4L])) x[1L] <- x[1L] + x[4L] if(!is.na(x[5L])) x[2L] <- x[2L] + x[5L] options(OutDec = '.') format(x[1L:3L], digits = 7L) }, pos = 'CheckExEnv') ### * </HEADER> library('DivE') base::assign(".oldSearch", base::search(), pos = 'CheckExEnv') base::assign(".old_wd", base::getwd(), pos = 'CheckExEnv') cleanEx() nameEx("Bact1") ### * Bact1 flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: Bact1 ### Title: Count of Medically Important Bacteria Species in a Sample ### Aliases: Bact1 Bact2 ### Keywords: datasets ### ** Examples data(Bact1) hist(Bact1[,2], breaks=20, main="Bacterial diversity of a sample", xlab="Number of bacteria of a given species", ylab="Number of bacterial species") base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("Bact1", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("CombDM") ### * CombDM flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: CombDM ### Title: CombDM ### Aliases: CombDM ### Keywords: diversity ### ** Examples # See DiveMaster documentation for examples. base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("CombDM", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("Curvature") ### * Curvature flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: Curvature ### Title: Curvature ### Aliases: Curvature ### Keywords: diversity ### ** Examples # See DivSubsamples documentation for examples. base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("Curvature", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("DivSampleNum") ### * DivSampleNum flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: DivSampleNum ### Title: DivSampleNum ### Aliases: DivSampleNum ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) DivSampleNum(Bact1, 3) DivSampleNum(Bact1, 6) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("DivSampleNum", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("DivSubsamples") ### * DivSubsamples flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: DivSubsamples ### Title: DivSubsamples ### Aliases: DivSubsamples print.DivSubsamples summary.DivSubsamples ### print.summary.DivSubsamples ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) dss_1 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=100, NResamples=10) dss_2 <- DivSubsamples(Bact1, nrf=20, minrarefac=1, maxrarefac=100, NResamples=10) # Default NResamples=1000; low value of NResamples=10 is a set for quick evaluation dss_1 dss_2 summary(dss_1) dss_1$div_sd dss_1$NResamples Curvature(dss_1) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("DivSubsamples", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("DiveMaster") ### * DiveMaster flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: DiveMaster ### Title: DiveMaster ### Aliases: DiveMaster print.DiveMaster summary.DiveMaster ### print.summary.DiveMaster ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) data(ModelSet) data(ParamSeeds) data(ParamRanges) testmodels <- list() testmeta <- list() paramranges <- list() # Choose a single model testmodels <- c(testmodels, ModelSet[1]) #testmeta[[1]] <- (ParamSeeds[[1]]) # Commented out for sake of brevity) testmeta[[1]] <- matrix(c(0.9451638, 0.007428265, 0.9938149, 1.0147441, 0.009543598, 0.9870419), nrow=2, byrow=TRUE, dimnames=list(c(), c("a1", "a2", "a3"))) # Example seeds paramranges[[1]] <- ParamRanges[[1]] # Create DivSubsamples object (NB: For quick illustration only -- not default parameters) dss_1 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=40, NResamples=5) dss_2 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=65, NResamples=5) dss <- list(dss_2, dss_1) # Implement the function (NB: For quick illustration only -- not default parameters) out <- DiveMaster(models=testmodels, init.params=testmeta, param.ranges=paramranges, main.samp=Bact1, subsizes=c(65, 40), NResamples=5, fitloops=1, dssamp=dss, numit=2, varleft=10) # DiveMaster Outputs out out$estimate out$fmm$logistic out$fmm$logistic$global out$ssm summary(out) ## Combining two DiveMaster objects (assuming a second object 'out2'): # out3 <- CombDM(list(out, out2)) ## To calculate the diversity for a different population size # PopDiversity(dm=out, popsize=10^5, TopX=1) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("DiveMaster", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("FitSingleMod") ### * FitSingleMod flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: FitSingleMod ### Title: FitSingleMod ### Aliases: FitSingleMod print.FitSingleMod summary.FitSingleMod ### print.summary.FitSingleMod plot.FitSingleMod ### Keywords: diversity ### ** Examples # See documentation of \code{ScoreSingleMod} for examples base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("FitSingleMod", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ModelSet") ### * ModelSet flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ModelSet ### Title: List of 58 candidate models to fit to data ### Aliases: ModelSet ### Keywords: datasets ### ** Examples data(ModelSet) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ModelSet", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ParamRanges") ### * ParamRanges flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ParamRanges ### Title: List of 58 sets of upper and lower bounds for models evaluated ### by DivE ### Aliases: ParamRanges ### Keywords: datasets ### ** Examples data(ParamRanges) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ParamRanges", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ParamSeeds") ### * ParamSeeds flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ParamSeeds ### Title: List of 58 matrices of model seeding parameters. ### Aliases: ParamSeeds ### Keywords: datasets ### ** Examples data(ParamSeeds) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ParamSeeds", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("PopDiversity") ### * PopDiversity flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: PopDiversity ### Title: PopDiversity ### Aliases: PopDiversity ### Keywords: diversity ### ** Examples # See DiveMaster documentation for examples. base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("PopDiversity", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("ScoreSingleMod") ### * ScoreSingleMod flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: ScoreSingleMod ### Title: ScoreSingleMod ### Aliases: ScoreSingleMod print.ScoreSingleMod summary.ScoreSingleMod ### print.summary.ScoreSingleMod ### Keywords: diversity ### ** Examples require(DivE) data(Bact1) data(ModelSet) data(ParamSeeds) data(ParamRanges) testmodels <- list() testmeta <- list() paramranges <- list() # Choose a single model testmodels <- c(testmodels, ModelSet[1]) # testmeta <- (ParamSeeds[[1]]) # Commented out for sake of brevity) testmeta <- matrix(c(0.9451638, 0.007428265, 0.9938149, 1.0147441, 0.009543598, 0.9870419), nrow=2, byrow=TRUE, dimnames=list(c(), c("a1", "a2", "a3"))) # Example seeds paramranges <- ParamRanges[[1]] # Create DivSubsamples object (NB: For quick illustration only -- not default parameters) dss_1 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=40, NResamples=5) dss_2 <- DivSubsamples(Bact1, nrf=2, minrarefac=1, maxrarefac=65, NResamples=5) dss <- list(dss_2, dss_1) # Fit the model (NB: For quick illustration only -- not default parameters) fsm <- FitSingleMod(model.list=testmodels, init.param=testmeta, param.range=paramranges, main.samp=Bact1, dssamps=dss, fitloops=1, data.default=FALSE, subsizes=c(65, 40), numit=2) # numit chosen to be extremely small to speed up example # Score the model ssm <- ScoreSingleMod(fsm) ssm summary(ssm) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("ScoreSingleMod", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") ### * <FOOTER> ### cleanEx() options(digits = 7L) base::cat("Time elapsed: ", proc.time() - base::get("ptime", pos = 'CheckExEnv'),"\n") grDevices::dev.off() ### ### Local variables: *** ### mode: outline-minor *** ### outline-regexp: "\\(> \\)?### [*]+" *** ### End: *** quit('no')
# Read data for 2007-02-01 and 2007-02-02 consumptionInitial <- read.csv("household_power_consumption.txt",sep=";",na.strings="?",nrows=70000) ## 70000 lines is enough to include the required range consumptionInitial$Date <- as.Date(consumptionInitial$Date,"%d/%m/%Y") consumption <- subset(consumptionInitial,consumptionInitial$Date=="2007-02-01" | consumptionInitial$Date=="2007-02-02") rm(consumptionInitial) ## no longer needed # Convert Date/Time formats consumption$datetime <- paste(consumption$Date,consumption$Time,sep=" ") ## create combined "datetime" variable consumption$datetime <- strptime(consumption$datetime, "%Y-%m-%d %H:%M:%S") # Create Global Active Power histogram hist(consumption$Global_active_power,col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)", ylab="Frequency") dev.copy(png, file="plot1.png", width=480, height=480) ## generate PNG file output dev.off()
/plot1.R
no_license
gmastro71/ExData_Plotting1
R
false
false
920
r
# Read data for 2007-02-01 and 2007-02-02 consumptionInitial <- read.csv("household_power_consumption.txt",sep=";",na.strings="?",nrows=70000) ## 70000 lines is enough to include the required range consumptionInitial$Date <- as.Date(consumptionInitial$Date,"%d/%m/%Y") consumption <- subset(consumptionInitial,consumptionInitial$Date=="2007-02-01" | consumptionInitial$Date=="2007-02-02") rm(consumptionInitial) ## no longer needed # Convert Date/Time formats consumption$datetime <- paste(consumption$Date,consumption$Time,sep=" ") ## create combined "datetime" variable consumption$datetime <- strptime(consumption$datetime, "%Y-%m-%d %H:%M:%S") # Create Global Active Power histogram hist(consumption$Global_active_power,col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)", ylab="Frequency") dev.copy(png, file="plot1.png", width=480, height=480) ## generate PNG file output dev.off()
# Script to analyze PRS-pheWAS # Depends library(data.table) library(ggplot2) # Load PRS prs <- fread(file='prs_processed.csv') # Load LV mass seg <- fread(file='lvmi_seg_adjusted.tsv') # Load processed LV mass seg_lvm <- fread(file='seg_lvm.csv') seg_lvm[c(!is.na(sex) & !is.na(lvmi_seg_adjusted)), ':='(lvh_ukbb = ifelse(c((sex=='Female') & (lvmi_seg_adjusted > 55)),1, ifelse(lvmi_seg_adjusted > 72,1,0)))] # Join setkey(prs,sample_id); setkey(seg,IID); setkey(seg_lvm,sample_id) seg[prs,':='(prs_std = i.prs_std)] seg[seg_lvm,lvh_ukbb := i.lvh_ukbb] # Remove non-white/no PRS seg <- seg[!is.na(prs_std)] # Check exposure ~ PRS mod <- lm(lvmi_seg_adjusted ~ prs_std,data=seg) mod_adj <- lm(lvmi_seg_adjusted ~ prs_std + male + age_at_mri + PC1 + PC2 + PC3 + PC4 + PC5,data=seg) # Corr corr <- cor.test(seg$prs_std,y=seg$lvmi_seg_adjusted) # Plot pdf(file='prs_lvmi_corr_ukbb.pdf',height=3,width=3,pointsize=5) par(mar=c(3,3,1,1),oma=c(2,2,1,1)) plot(x=seg$prs_std,y=seg$lvmi_seg_adjusted,bty='n',xlab='',ylab='',xaxt='n',yaxt='n',pch=19,col='#2171b58C', xlim=c(-5,5),ylim=c(0,150)) axis(1,cex.axis=1,at=c(-4:4)) axis(2,cex.axis=1,at=seq(0,150,25),las=2) mtext("Standardized PRS",1,line=3,cex=1.5) mtext(expression(paste("Indexed LV mass (g/m"^2,")")),2,line=3,cex=1.5) text(-2.5,145,labels="r=0.29, p<0.01") text(-2.5,138,labels="95% CI 0.28-0.30") dev.off() # Plot distribution stratified by LVH lvh <- seg[lvh_ukbb==1] no_lvh <- seg[lvh_ukbb==0] x <- list(v1=lvh$prs_std,v2=no_lvh$prs_std) data <- melt(x) ggplot() + geom_density(data=data,aes(x=value,fill=L1),alpha=0.55) + scale_x_continuous(breaks=seq(-3.5,3.5,0.5),expand=c(0.01,0),limits=c(-3.5,3.5)) + scale_y_continuous(breaks=seq(0,0.5,0.1),expand=c(0,0),limits=c(0,0.5)) + scale_fill_manual(values=c("#2b8cbe","#f03b20"),name='',labels=c('LVH','No LVH')) + theme(panel.background=element_blank(),axis.line=element_line(color='black'),legend.position=c(0.20,0.90), axis.text=element_text(size=20,color='black'),plot.margin=unit(c(0.5,0.6,0.5,0.5),'cm'), axis.title.y = element_text(size=20,margin = margin(t = 0, r = 10, b = 0, l = 0)), axis.title.x = element_text(size=20),legend.text=element_text(size=20)) + labs(x=expression(paste("LVMI Standardized PRS")),y='Density') ggsave(filename='prs_std_density_lvh_strat_eur.pdf',height=1.8,width=2.53, scale=4,device='pdf')
/misc/test_prs.R
permissive
shaankhurshid/lvmass_gwas
R
false
false
2,428
r
# Script to analyze PRS-pheWAS # Depends library(data.table) library(ggplot2) # Load PRS prs <- fread(file='prs_processed.csv') # Load LV mass seg <- fread(file='lvmi_seg_adjusted.tsv') # Load processed LV mass seg_lvm <- fread(file='seg_lvm.csv') seg_lvm[c(!is.na(sex) & !is.na(lvmi_seg_adjusted)), ':='(lvh_ukbb = ifelse(c((sex=='Female') & (lvmi_seg_adjusted > 55)),1, ifelse(lvmi_seg_adjusted > 72,1,0)))] # Join setkey(prs,sample_id); setkey(seg,IID); setkey(seg_lvm,sample_id) seg[prs,':='(prs_std = i.prs_std)] seg[seg_lvm,lvh_ukbb := i.lvh_ukbb] # Remove non-white/no PRS seg <- seg[!is.na(prs_std)] # Check exposure ~ PRS mod <- lm(lvmi_seg_adjusted ~ prs_std,data=seg) mod_adj <- lm(lvmi_seg_adjusted ~ prs_std + male + age_at_mri + PC1 + PC2 + PC3 + PC4 + PC5,data=seg) # Corr corr <- cor.test(seg$prs_std,y=seg$lvmi_seg_adjusted) # Plot pdf(file='prs_lvmi_corr_ukbb.pdf',height=3,width=3,pointsize=5) par(mar=c(3,3,1,1),oma=c(2,2,1,1)) plot(x=seg$prs_std,y=seg$lvmi_seg_adjusted,bty='n',xlab='',ylab='',xaxt='n',yaxt='n',pch=19,col='#2171b58C', xlim=c(-5,5),ylim=c(0,150)) axis(1,cex.axis=1,at=c(-4:4)) axis(2,cex.axis=1,at=seq(0,150,25),las=2) mtext("Standardized PRS",1,line=3,cex=1.5) mtext(expression(paste("Indexed LV mass (g/m"^2,")")),2,line=3,cex=1.5) text(-2.5,145,labels="r=0.29, p<0.01") text(-2.5,138,labels="95% CI 0.28-0.30") dev.off() # Plot distribution stratified by LVH lvh <- seg[lvh_ukbb==1] no_lvh <- seg[lvh_ukbb==0] x <- list(v1=lvh$prs_std,v2=no_lvh$prs_std) data <- melt(x) ggplot() + geom_density(data=data,aes(x=value,fill=L1),alpha=0.55) + scale_x_continuous(breaks=seq(-3.5,3.5,0.5),expand=c(0.01,0),limits=c(-3.5,3.5)) + scale_y_continuous(breaks=seq(0,0.5,0.1),expand=c(0,0),limits=c(0,0.5)) + scale_fill_manual(values=c("#2b8cbe","#f03b20"),name='',labels=c('LVH','No LVH')) + theme(panel.background=element_blank(),axis.line=element_line(color='black'),legend.position=c(0.20,0.90), axis.text=element_text(size=20,color='black'),plot.margin=unit(c(0.5,0.6,0.5,0.5),'cm'), axis.title.y = element_text(size=20,margin = margin(t = 0, r = 10, b = 0, l = 0)), axis.title.x = element_text(size=20),legend.text=element_text(size=20)) + labs(x=expression(paste("LVMI Standardized PRS")),y='Density') ggsave(filename='prs_std_density_lvh_strat_eur.pdf',height=1.8,width=2.53, scale=4,device='pdf')
context("emission") test_that("final emission works", { expect_equal(emission(totalEmission(vehicles(example = TRUE,verbose = F), emissionFactor(example = TRUE,verbose = F), pol = c("CO"),verbose = T), "FISH", list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "SP",verbose = F), RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "RJ",verbose = F)), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), verbose = F), cat(paste("FISH","not found in total !\n"))) # expect_equal(drop_units(emission(totalEmission(vehicles(example = TRUE,verbose = F), # emissionFactor(example = TRUE,verbose = F), # pol = c("CO"),verbose = T), # "CO", # list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "SP",verbose = F), # RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "RJ",verbose = F)), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), # mm=1, # verbose = T, # aerosol = F))/28, # drop_units(emission(totalEmission(vehicles(example = TRUE,verbose = F), # emissionFactor(example = TRUE,verbose = F), # pol = c("CO"),verbose = T), # "CO", # list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "SP",verbose = F), # RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "RJ",verbose = F)), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), # mm=28, # verbose = T, # aerosol = F))) expect_equal(sum(emission(totalEmission(vehicles(example = TRUE,verbose = F), emissionFactor(example = TRUE,verbose = F), pol = c("CO"),verbose = T), "CO", list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "SP",verbose = F), RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "RJ",verbose = F)), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), mm=28, verbose = T, aerosol = T, plot = T) ), units::as_units(362.58086806097963972206343896687030792236328125, "ug*m^-2*s^-1")) expect_equal(sum(emission(totalEmission(vehicles(example = TRUE,verbose = F), emissionFactor(example = TRUE,verbose = F), pol = c("CO"),verbose = F), "CO", list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "SP",verbose = F)), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), mm=28, verbose = T, aerosol = F, plot = T) ), units::as_units(306.59299639647224466898478567600250244140625, "ug*m^-2*s^-1")) expect_equal(nrow(emission(inventory = read("edgar_co_test.nc"),pol = "FISH", grid = gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"), verbose = F), mm=1,plot = T,verbose = T) ), nrow(emission(inventory = read("edgar_co_test.nc"),pol = "FISH", grid = gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"), verbose = F), mm=1,plot = T, aerosol = T) )) })
/tests/testthat/test-emission.R
permissive
ctfysh/EmissV
R
false
false
7,524
r
context("emission") test_that("final emission works", { expect_equal(emission(totalEmission(vehicles(example = TRUE,verbose = F), emissionFactor(example = TRUE,verbose = F), pol = c("CO"),verbose = T), "FISH", list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "SP",verbose = F), RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "RJ",verbose = F)), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), verbose = F), cat(paste("FISH","not found in total !\n"))) # expect_equal(drop_units(emission(totalEmission(vehicles(example = TRUE,verbose = F), # emissionFactor(example = TRUE,verbose = F), # pol = c("CO"),verbose = T), # "CO", # list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "SP",verbose = F), # RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "RJ",verbose = F)), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), # mm=1, # verbose = T, # aerosol = F))/28, # drop_units(emission(totalEmission(vehicles(example = TRUE,verbose = F), # emissionFactor(example = TRUE,verbose = F), # pol = c("CO"),verbose = T), # "CO", # list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "SP",verbose = F), # RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], # raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), # name = "RJ",verbose = F)), # gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), # mm=28, # verbose = T, # aerosol = F))) expect_equal(sum(emission(totalEmission(vehicles(example = TRUE,verbose = F), emissionFactor(example = TRUE,verbose = F), pol = c("CO"),verbose = T), "CO", list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "SP",verbose = F), RJ = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[17,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "RJ",verbose = F)), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), mm=28, verbose = T, aerosol = T, plot = T) ), units::as_units(362.58086806097963972206343896687030792236328125, "ug*m^-2*s^-1")) expect_equal(sum(emission(totalEmission(vehicles(example = TRUE,verbose = F), emissionFactor(example = TRUE,verbose = F), pol = c("CO"),verbose = F), "CO", list(SP = areaSource(raster::shapefile(paste0(system.file("extdata", package = "EmissV"),"/BR.shp"))[22,1], raster::raster(paste0(system.file("extdata", package = "EmissV"),"/dmsp.tiff")), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01")), name = "SP",verbose = F)), gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"),verbose = F), mm=28, verbose = T, aerosol = F, plot = T) ), units::as_units(306.59299639647224466898478567600250244140625, "ug*m^-2*s^-1")) expect_equal(nrow(emission(inventory = read("edgar_co_test.nc"),pol = "FISH", grid = gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"), verbose = F), mm=1,plot = T,verbose = T) ), nrow(emission(inventory = read("edgar_co_test.nc"),pol = "FISH", grid = gridInfo(paste0(system.file("extdata", package = "EmissV"),"/wrfinput_d01"), verbose = F), mm=1,plot = T, aerosol = T) )) })
#' Split a Character String Across 2 Lines #' #' @description This function splits a character string across two lines, keeping lines as even as possible. #' Replaces the middlemost " " (determined by string length) with "\\n"; and does not perform replacement if #' lines would have words with 3 or fewer characters. #' #' @param text A vector of character strings. #' #' @export #' #' @note To use with ggplot2 add \code{scale_x_discrete(labels = split_line)} to your ggobject. #' #' @examples #' split_line(c('Hello World!', 'Goodbye Cruel World', 'To Myself')) #' # Returns: 'Hello\nWorld!' 'Goodbye\nCruel World' 'To Myself' split_line <- function(text){ sapply(text, function(i){ n <- nchar(i) spaces <- as.numeric(gregexpr(' ', i)[[1]]) spaces <- spaces[spaces > 4 & (n - spaces) > 3] if(length(spaces) > 0){ place <- spaces[which.min(abs(spaces - n/2))] substr(i, place, place) <- '\n' } i }, USE.NAMES = F) }
/R/split_line.r
permissive
joshua-ruf/fidelis
R
false
false
980
r
#' Split a Character String Across 2 Lines #' #' @description This function splits a character string across two lines, keeping lines as even as possible. #' Replaces the middlemost " " (determined by string length) with "\\n"; and does not perform replacement if #' lines would have words with 3 or fewer characters. #' #' @param text A vector of character strings. #' #' @export #' #' @note To use with ggplot2 add \code{scale_x_discrete(labels = split_line)} to your ggobject. #' #' @examples #' split_line(c('Hello World!', 'Goodbye Cruel World', 'To Myself')) #' # Returns: 'Hello\nWorld!' 'Goodbye\nCruel World' 'To Myself' split_line <- function(text){ sapply(text, function(i){ n <- nchar(i) spaces <- as.numeric(gregexpr(' ', i)[[1]]) spaces <- spaces[spaces > 4 & (n - spaces) > 3] if(length(spaces) > 0){ place <- spaces[which.min(abs(spaces - n/2))] substr(i, place, place) <- '\n' } i }, USE.NAMES = F) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkMechanismValidity.R \name{checkMechanismValidity} \alias{checkMechanismValidity} \title{checkMechanismPeriodValidity(data,organisationUnit)} \usage{ checkMechanismValidity(data, organisationUnit = NA, return_violations = TRUE) } \arguments{ \item{data}{A data frame which has been parsed by either d2Parser or sims2Parser} \item{organisationUnit}{UID of the operating unit.} \item{return_violations}{Should the function return a list of violations?} } \value{ Returns a data frame of invalid period-mechanism combinations. Returns TRUE if there are no violations. } \description{ This function will return an object of invalid mechanisms and periods. All data which is reported must have a period within the valid start and end dates of the attribute option combination to which it is assigned. The mechanism must also be associated with the operating unit. If either of these two conditions are not met, the data will be flagged as being invalid. }
/man/checkMechanismValidity.Rd
permissive
oitigeorge/datim-validation
R
false
true
1,040
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkMechanismValidity.R \name{checkMechanismValidity} \alias{checkMechanismValidity} \title{checkMechanismPeriodValidity(data,organisationUnit)} \usage{ checkMechanismValidity(data, organisationUnit = NA, return_violations = TRUE) } \arguments{ \item{data}{A data frame which has been parsed by either d2Parser or sims2Parser} \item{organisationUnit}{UID of the operating unit.} \item{return_violations}{Should the function return a list of violations?} } \value{ Returns a data frame of invalid period-mechanism combinations. Returns TRUE if there are no violations. } \description{ This function will return an object of invalid mechanisms and periods. All data which is reported must have a period within the valid start and end dates of the attribute option combination to which it is assigned. The mechanism must also be associated with the operating unit. If either of these two conditions are not met, the data will be flagged as being invalid. }
\name{getFriendlyName} \alias{getFriendlyName} \title{Change a camelCase name to a friendlier version} \description{ Takes a string like "fooBarBaz" and returns "Foo Bar Baz". } \usage{ getFriendlyName(camelName) } \arguments{ \item{camelName}{ The "camelCased" name to make friendly. } } \value{ The friendly version of the camel-cased name. } \seealso{ \code{\link{galaxy}}, \code{\link{GalaxyParam}}, \code{\link{GalaxyConfig}}, \code{\link{GalaxyOutput}} } \details{ Used by \code{galaxy()} to create default labels based on function and parameter names. } \examples{ getFriendlyName("fooBarBaz") }
/man/getFriendlyName.Rd
no_license
dtenenba/RGalaxy-vignette-changes
R
false
false
641
rd
\name{getFriendlyName} \alias{getFriendlyName} \title{Change a camelCase name to a friendlier version} \description{ Takes a string like "fooBarBaz" and returns "Foo Bar Baz". } \usage{ getFriendlyName(camelName) } \arguments{ \item{camelName}{ The "camelCased" name to make friendly. } } \value{ The friendly version of the camel-cased name. } \seealso{ \code{\link{galaxy}}, \code{\link{GalaxyParam}}, \code{\link{GalaxyConfig}}, \code{\link{GalaxyOutput}} } \details{ Used by \code{galaxy()} to create default labels based on function and parameter names. } \examples{ getFriendlyName("fooBarBaz") }
\name{SCsim-package} \alias{SCsim-package} \alias{SCsim} \docType{package} \title{ What the package does (short line) ~~ package title ~~ } \description{ More about what it does (maybe more than one line) ~~ A concise (1-5 lines) description of the package ~~ } \details{ \tabular{ll}{ Package: \tab SCsim\cr Type: \tab Package\cr Version: \tab 1.0\cr Date: \tab 2013-08-05\cr License: \tab What license is it under?\cr } ~~ An overview of how to use the package, including the most important ~~ ~~ functions ~~ } \author{ Who wrote it Maintainer: Who to complain to <yourfault@somewhere.net> ~~ The author and/or maintainer of the package ~~ } \references{ ~~ Literature or other references for background information ~~ } ~~ Optionally other standard keywords, one per line, from file KEYWORDS in ~~ ~~ the R documentation directory ~~ \keyword{ package } \seealso{ ~~ Optional links to other man pages, e.g. ~~ ~~ \code{\link[<pkg>:<pkg>-package]{<pkg>}} ~~ } \examples{ ~~ simple examples of the most important functions ~~ }
/man/SCsim-package.Rd
no_license
RobertWSmith/SCsim
R
false
false
1,031
rd
\name{SCsim-package} \alias{SCsim-package} \alias{SCsim} \docType{package} \title{ What the package does (short line) ~~ package title ~~ } \description{ More about what it does (maybe more than one line) ~~ A concise (1-5 lines) description of the package ~~ } \details{ \tabular{ll}{ Package: \tab SCsim\cr Type: \tab Package\cr Version: \tab 1.0\cr Date: \tab 2013-08-05\cr License: \tab What license is it under?\cr } ~~ An overview of how to use the package, including the most important ~~ ~~ functions ~~ } \author{ Who wrote it Maintainer: Who to complain to <yourfault@somewhere.net> ~~ The author and/or maintainer of the package ~~ } \references{ ~~ Literature or other references for background information ~~ } ~~ Optionally other standard keywords, one per line, from file KEYWORDS in ~~ ~~ the R documentation directory ~~ \keyword{ package } \seealso{ ~~ Optional links to other man pages, e.g. ~~ ~~ \code{\link[<pkg>:<pkg>-package]{<pkg>}} ~~ } \examples{ ~~ simple examples of the most important functions ~~ }
x010b_fit <- function(list.in, item.noise.mag = 0.0, image.noise.mag = 0.0, fix.seed=TRUE) { # Workflow: run C#/NUnit; copy to clipboard; nnna_raw<-get.cs(); nnna_list<-fit_nnna(nnna_raw). # Model: InstMag ~ CI (~centered) + airmass(~centered) # parms: list.in is list obtained from get.ForR(), # noise.mag = added Gaussian noise per data point (sigma in magnitudes). # image.noise.mag = added Gaussian noise per image (sigma in magnitudes). # fix.seed = TRUE if random-number seed fixed (for same results per run; # this should be FALSE for bootstrapping, repeated calls, e.g.) # N.B.: if fit() is called repeatedly by another fn, that fn should first set.seed(). # This fn appends to input these list items: # summary of model output (itself a list), and # text lines representing this function (fit.R) # This fn return this expanded list. # --------------------------------------------------------- df <- list.in[["df.cs"]] # double bracket to un-list item (to create a data.frame) df <- df[df$CI.VI90 < 1.6,] # eliminate very red stars. Mag <- df$InstMag - df$starMagV90 # correct Mag for inherent star mag if (item.noise.mag > 0) { if (fix.seed == TRUE) set.seed(234) # arbitrary but reproducible seed. Mag <- Mag + rnorm(nrow(df),0,item.noise.mag) # add noise to all stars. } # if. if (image.noise.mag > 0) { if (fix.seed == TRUE) set.seed(135) # arbitrary but reproducible seed. imageList <- unique(df$imageID) for (image in imageList) { rows = (df$imageID == image) # select all rows belonging to this image. fluctuation.this.image = rnorm(1,0,image.noise.mag) Mag[rows] <- Mag[rows] + fluctuation.this.image # add same error to all stars in this image. } # for } # if. Centering.CI <- 0.6 # to approximately center CI values. CI <- df$CI.VI90 - Centering.CI # NB: we are now using color index V-I, not B-V. Centering.SecantZA <- 2.0 # to approx. center Airmass values. Airmass <- df$SecantZA - Centering.SecantZA model <- lm(formula = Mag ~ CI + Airmass + CI:Airmass) # THE MODEL. list.out <- list.in # Capture and append to list the R Code generating raw data (this .R file) connection <- file("010b_fit.R") # *this* code file as text list.out$code.fit <- readLines(connection) # record this code file as next list item. close(connection) # Capture and append to list the fit's results. list.out$summary <- summary(model,correlation=TRUE) # append model results as next list item. print (list.out$summary) # print model results to screen. list.out$model <- model save(list.out, file="010b_list") # saves updated list as a file. return (list.out) # returns as a list. }
/Statistics/010b_fit.R
permissive
edose/Spectral
R
false
false
2,830
r
x010b_fit <- function(list.in, item.noise.mag = 0.0, image.noise.mag = 0.0, fix.seed=TRUE) { # Workflow: run C#/NUnit; copy to clipboard; nnna_raw<-get.cs(); nnna_list<-fit_nnna(nnna_raw). # Model: InstMag ~ CI (~centered) + airmass(~centered) # parms: list.in is list obtained from get.ForR(), # noise.mag = added Gaussian noise per data point (sigma in magnitudes). # image.noise.mag = added Gaussian noise per image (sigma in magnitudes). # fix.seed = TRUE if random-number seed fixed (for same results per run; # this should be FALSE for bootstrapping, repeated calls, e.g.) # N.B.: if fit() is called repeatedly by another fn, that fn should first set.seed(). # This fn appends to input these list items: # summary of model output (itself a list), and # text lines representing this function (fit.R) # This fn return this expanded list. # --------------------------------------------------------- df <- list.in[["df.cs"]] # double bracket to un-list item (to create a data.frame) df <- df[df$CI.VI90 < 1.6,] # eliminate very red stars. Mag <- df$InstMag - df$starMagV90 # correct Mag for inherent star mag if (item.noise.mag > 0) { if (fix.seed == TRUE) set.seed(234) # arbitrary but reproducible seed. Mag <- Mag + rnorm(nrow(df),0,item.noise.mag) # add noise to all stars. } # if. if (image.noise.mag > 0) { if (fix.seed == TRUE) set.seed(135) # arbitrary but reproducible seed. imageList <- unique(df$imageID) for (image in imageList) { rows = (df$imageID == image) # select all rows belonging to this image. fluctuation.this.image = rnorm(1,0,image.noise.mag) Mag[rows] <- Mag[rows] + fluctuation.this.image # add same error to all stars in this image. } # for } # if. Centering.CI <- 0.6 # to approximately center CI values. CI <- df$CI.VI90 - Centering.CI # NB: we are now using color index V-I, not B-V. Centering.SecantZA <- 2.0 # to approx. center Airmass values. Airmass <- df$SecantZA - Centering.SecantZA model <- lm(formula = Mag ~ CI + Airmass + CI:Airmass) # THE MODEL. list.out <- list.in # Capture and append to list the R Code generating raw data (this .R file) connection <- file("010b_fit.R") # *this* code file as text list.out$code.fit <- readLines(connection) # record this code file as next list item. close(connection) # Capture and append to list the fit's results. list.out$summary <- summary(model,correlation=TRUE) # append model results as next list item. print (list.out$summary) # print model results to screen. list.out$model <- model save(list.out, file="010b_list") # saves updated list as a file. return (list.out) # returns as a list. }
################################################################################################ # Prepared for the textbook: # Data Analysis for Business, Economics, and Policy # by Gabor BEKES and Gabor KEZDI # Cambridge University Press 2021 # # License: Free to share, modify and use for educational purposes. Not to be used for business purposes. # ###############################################################################################x # CHAPTER 03 # CH03B Comparing hotel prices in Europe: Vienna vs. London # hotels-europe dataset # version 0.9 2020-08-28 # ------------------------------------------------------------------------------------------------------ #### SET UP # It is advised to start a new session for every case study # CLEAR MEMORY rm(list=ls()) # Import libraries library(tidyverse) #install.packages("arm") library(arm) #install.packages("pastecs") library(pastecs) #install.packages("DataCombine") library(DataCombine) library(janitor) # set working directory # option A: open material as project # option B: set working directory for da_case_studies # example: setwd("C:/Users/bekes.gabor/Documents/github/da_case_studies/") # set data dir, data used source("set-data-directory.R") # data_dir must be first defined # alternative: give full path here, # example data_dir="C:/Users/bekes.gabor/Dropbox (MTA KRTK)/bekes_kezdi_textbook/da_data_repo" # load theme and functions source("ch00-tech-prep/theme_bg.R") source("ch00-tech-prep/da_helper_functions.R") data_in <- paste(data_dir,"sp500","clean/", sep = "/") use_case_dir <- "ch05-stock-market-loss-generalize/" data_out <- use_case_dir output <- paste0(use_case_dir,"output/") create_output_if_doesnt_exist(output) #----------------------------------------------------------------------------------------- # LOAD DATA sp500 <- read_csv(paste0(data_in,"SP500_2006_16_data.csv"),na = c("", "#N/A")) # From web # sp500 <- read_csv("https://osf.io/h64z2/download" , na = c("", "#N/A") ) sp500 <- subset(sp500, VALUE != "NA") # CREATE PERCENT RETURN sp500<- sp500 %>% mutate(pct_return = (VALUE - lag(VALUE)) / lag(VALUE) * 100) # CREATE DATE VARIABLE sp500$year <- format(sp500$DATE, "%Y") sp500$month <- format(sp500$DATE, "%m") sp500$year <- as.numeric(sp500$year) sp500$month <- as.numeric(sp500$month) sp500$yearmonth <- sp500$year*100 + sp500$month # Distribution # Figure 5.1 returns_histogram <-ggplot(sp500,aes(pct_return))+ geom_histogram_da(binwidth = 0.25, type="frequency")+ geom_vline(xintercept = -5, size = 0.7, color=color[2])+ labs(x = "Daily return (percent)", y = "Frequency") + coord_cartesian(xlim = c(-10, 10), ylim = c(0, 400)) + scale_y_continuous(expand = c(0, 0)) + geom_segment(aes(x = -6, y = 220, xend = -5, yend = 220), arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = -8, y = 220, label = "5% loss", size=2.5)+ theme_bg() returns_histogram #save_fig("returns_histogram_R", output, "small") save_fig("ch05-figure-1-returns-histogram", output, "small") # Figure 5.2 prep # Create 10 000 samples, with 500 and 1000 observations in each sample, taken from sp500$pct_return # in every sample: for each observation, check if it is a loss of 5% or more. Then calculate the percentage of observations out of 500 or 1000 # where the loss exceeds 5%. E.g. for the 233rd sample, 9 out of 1000 obs had larger than 5% losses. # remove first row as it has NA in pct_return pct_return <- sp500 %>% filter(!is.na(pct_return)) %>% pull(pct_return) # function for a specified number of samples: draws a specified number of observations from a vector, calculates the percentage of obs with greater than 5% losses # 3 inputs: 'vector' is a vector of the source data, in this case pct_return. 'n_samples' is the number of samples we want to use. # 'n_obs' is the number of observations in each sample # output is a vector create_samples <- function(vector, n_samples, n_obs) { samples_pcloss <- c() for (i in 1:n_samples){ single_sample <- sample(vector,n_obs, replace = FALSE) samples_pcloss[i] <- sum(single_sample < -5)/n_obs*100 } samples_pcloss } set.seed(123) # Figure 5.2, 5.3, 5.4 input nobs_1000 <- create_samples(pct_return, 10000, 1000) nobs_500 <- create_samples(pct_return, 10000, 500) #nobs_df <- as.data.frame(cbind(nobs_500, nobs_1000)) nobs_df <- tibble(nobs_500,nobs_1000) error <- qnorm(0.975)*sd(nobs_df$nobs_1000)/sqrt(length(nobs_df$nobs_1000)) left <- mean(nobs_df$nobs_1000)-error right <- mean(nobs_df$nobs_1000)+error # Figure 5.2 options(digits = 2) resample1000<-ggplot(nobs_df,aes(nobs_1000)) + geom_histogram(binwidth = 0.1, color = color.outline, fill = color[1], alpha = 0.8, boundary=0, closed='left') + labs(x = "Percent of days with losses of 5% or more", y = "Frequency") + geom_vline(aes(xintercept = mean(nobs_500)), color =color[2], size = 0.7) + coord_cartesian(xlim = c(0, 1.5), ylim = c(0, 2500)) + scale_x_continuous(expand=c(0.01, 0.01), limits = c(0,1.5), breaks = seq(0, 1.5, by = 0.25)) + scale_y_continuous(expand=c(0.00, 0.00), limits = c(0,2500),breaks = seq(0, 2500, by = 500)) + geom_segment(aes(x = 0.8, y = 2000, xend = 0.53, yend = 2000), arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = 0.85, y = 2200, label = "Mean", size=2.5)+ theme_bg() resample1000 save_fig("ch05-figure-2-resample1000", output, "small") # Figure 5.3 ggplot(nobs_df,aes(nobs_1000))+ stat_density(geom="line", aes(color = 'n1000'), bw = 0.45,size = 1,kernel = "epanechnikov")+ stat_density(geom="line",aes(nobs_500, color = "n500"), bw=0.45,linetype="twodash", size = 1,kernel = "epanechnikov")+ labs(x="Percent of days with losses over 5%", y="Density")+ geom_vline(xintercept = 0.5,colour=color[3], size = 0.7, linetype="dashed")+ geom_segment(aes(x = 0.9, y = 0.72, xend = 0.65, yend = 0.72), size = 0.5, arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = 1.1, y = 0.72, label = "Larger sample", size=2)+ geom_segment(aes(x = 0.9, y = 0.68, xend = 0.65, yend = 0.68), size = 0.5, arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = 1.1, y = 0.68, label = "Smaller sample", size=2) + scale_x_continuous(expand=c(0.01, 0.01), limits = c(0,1.5), breaks = seq(0, 1.5, by = 0.25)) + scale_y_continuous(expand=c(0.00, 0.00), limits = c(0,0.8),breaks = seq(0, 0.8, by = 0.2)) + scale_color_manual(name = "", values = c(n1000= color[1], n500 = color[2]))+ theme_bg()+ theme(legend.position = "none") #save_fig("ch05-figure-3-resample-densities", output, "small") gh<-ggplot(data=nobs_df)+ geom_histogram( aes(x=nobs_500, y = (..count..)/sum(..count..)*100, color = "n500", fill = "n500"), binwidth = 0.2, boundary=0, closed='left', alpha=0.7) + geom_histogram( aes(x=nobs_1000, y = (..count..)/sum(..count..)*100, color = "n1000", fill = "n1000"), binwidth = 0.2, boundary=0, closed='left', alpha=0.1, size=0.7) + ylab("Percent") + xlab("Percent of days with losses over 5%") + scale_x_continuous(expand=c(0.01, 0.01), limits = c(0,1.6), breaks = seq(0, 1.6, by = 0.2)) + scale_y_continuous(expand=c(0.00, 0.00), limits = c(0,50)) + scale_color_manual(name = "", values = c(color[2], color[1])) + scale_fill_manual(name = "", values = c(color[2], color[1])) + theme_bg() + theme(legend.position = c(0.7,0.9), legend.key.size = unit(x = 0.4, units = "cm"), legend.direction = "horizontal") gh save_fig("ch05-figure-3-resample-hist", output, "small") options(digits = 1) #table janitor::tabyl(nobs_df$nobs_500, sort = TRUE) #summarytools::freq(nobs_df$nobs_500, order = "freq") janitor::tabyl(nobs_df$nobs_1000, sort = TRUE) #################################### #BOOTSRTAP SAMPLES set.seed(573164) M <- 10000 Results <- matrix(rep(0,(M*10)),nrow=M,ncol=10) for (i in 1:M){ bsample <- sample(sp500$pct_return,size=dim(sp500)[1], replace = TRUE) for (j in 1:10){ loss <- as.numeric(bsample<(-j))*100 Results[i,j] <- mean(loss, na.rm=T) } } Results <- as_tibble(Results) names(Results) <- c("loss1","loss2","loss3","loss4","loss5","loss6", "loss7","loss8","loss9","loss10") # Figure 5.5 bootstrap<- ggplot(Results,aes(loss5))+ geom_histogram_da(type="frequency", binwidth = 0.04, boundary=0, closed='left')+ scale_y_continuous(expand=c(0,0),limits = c(0,1200), breaks = seq(0,1200,200)) + scale_x_continuous(expand=c(0.01,0.01),limits=c(0,1.2), breaks = seq(0,1.2,0.1)) + labs(x = "Percent of days with losses of 5% or more", y = "Frequency")+ theme_bg() bootstrap save_fig("ch05-figure-5-bootstrap", output, "small")
/ch05-stock-market-loss-generalize/ch05-stock-market-loss-generalize.R
no_license
AlmaAlbrecht/da_case_studies
R
false
false
8,701
r
################################################################################################ # Prepared for the textbook: # Data Analysis for Business, Economics, and Policy # by Gabor BEKES and Gabor KEZDI # Cambridge University Press 2021 # # License: Free to share, modify and use for educational purposes. Not to be used for business purposes. # ###############################################################################################x # CHAPTER 03 # CH03B Comparing hotel prices in Europe: Vienna vs. London # hotels-europe dataset # version 0.9 2020-08-28 # ------------------------------------------------------------------------------------------------------ #### SET UP # It is advised to start a new session for every case study # CLEAR MEMORY rm(list=ls()) # Import libraries library(tidyverse) #install.packages("arm") library(arm) #install.packages("pastecs") library(pastecs) #install.packages("DataCombine") library(DataCombine) library(janitor) # set working directory # option A: open material as project # option B: set working directory for da_case_studies # example: setwd("C:/Users/bekes.gabor/Documents/github/da_case_studies/") # set data dir, data used source("set-data-directory.R") # data_dir must be first defined # alternative: give full path here, # example data_dir="C:/Users/bekes.gabor/Dropbox (MTA KRTK)/bekes_kezdi_textbook/da_data_repo" # load theme and functions source("ch00-tech-prep/theme_bg.R") source("ch00-tech-prep/da_helper_functions.R") data_in <- paste(data_dir,"sp500","clean/", sep = "/") use_case_dir <- "ch05-stock-market-loss-generalize/" data_out <- use_case_dir output <- paste0(use_case_dir,"output/") create_output_if_doesnt_exist(output) #----------------------------------------------------------------------------------------- # LOAD DATA sp500 <- read_csv(paste0(data_in,"SP500_2006_16_data.csv"),na = c("", "#N/A")) # From web # sp500 <- read_csv("https://osf.io/h64z2/download" , na = c("", "#N/A") ) sp500 <- subset(sp500, VALUE != "NA") # CREATE PERCENT RETURN sp500<- sp500 %>% mutate(pct_return = (VALUE - lag(VALUE)) / lag(VALUE) * 100) # CREATE DATE VARIABLE sp500$year <- format(sp500$DATE, "%Y") sp500$month <- format(sp500$DATE, "%m") sp500$year <- as.numeric(sp500$year) sp500$month <- as.numeric(sp500$month) sp500$yearmonth <- sp500$year*100 + sp500$month # Distribution # Figure 5.1 returns_histogram <-ggplot(sp500,aes(pct_return))+ geom_histogram_da(binwidth = 0.25, type="frequency")+ geom_vline(xintercept = -5, size = 0.7, color=color[2])+ labs(x = "Daily return (percent)", y = "Frequency") + coord_cartesian(xlim = c(-10, 10), ylim = c(0, 400)) + scale_y_continuous(expand = c(0, 0)) + geom_segment(aes(x = -6, y = 220, xend = -5, yend = 220), arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = -8, y = 220, label = "5% loss", size=2.5)+ theme_bg() returns_histogram #save_fig("returns_histogram_R", output, "small") save_fig("ch05-figure-1-returns-histogram", output, "small") # Figure 5.2 prep # Create 10 000 samples, with 500 and 1000 observations in each sample, taken from sp500$pct_return # in every sample: for each observation, check if it is a loss of 5% or more. Then calculate the percentage of observations out of 500 or 1000 # where the loss exceeds 5%. E.g. for the 233rd sample, 9 out of 1000 obs had larger than 5% losses. # remove first row as it has NA in pct_return pct_return <- sp500 %>% filter(!is.na(pct_return)) %>% pull(pct_return) # function for a specified number of samples: draws a specified number of observations from a vector, calculates the percentage of obs with greater than 5% losses # 3 inputs: 'vector' is a vector of the source data, in this case pct_return. 'n_samples' is the number of samples we want to use. # 'n_obs' is the number of observations in each sample # output is a vector create_samples <- function(vector, n_samples, n_obs) { samples_pcloss <- c() for (i in 1:n_samples){ single_sample <- sample(vector,n_obs, replace = FALSE) samples_pcloss[i] <- sum(single_sample < -5)/n_obs*100 } samples_pcloss } set.seed(123) # Figure 5.2, 5.3, 5.4 input nobs_1000 <- create_samples(pct_return, 10000, 1000) nobs_500 <- create_samples(pct_return, 10000, 500) #nobs_df <- as.data.frame(cbind(nobs_500, nobs_1000)) nobs_df <- tibble(nobs_500,nobs_1000) error <- qnorm(0.975)*sd(nobs_df$nobs_1000)/sqrt(length(nobs_df$nobs_1000)) left <- mean(nobs_df$nobs_1000)-error right <- mean(nobs_df$nobs_1000)+error # Figure 5.2 options(digits = 2) resample1000<-ggplot(nobs_df,aes(nobs_1000)) + geom_histogram(binwidth = 0.1, color = color.outline, fill = color[1], alpha = 0.8, boundary=0, closed='left') + labs(x = "Percent of days with losses of 5% or more", y = "Frequency") + geom_vline(aes(xintercept = mean(nobs_500)), color =color[2], size = 0.7) + coord_cartesian(xlim = c(0, 1.5), ylim = c(0, 2500)) + scale_x_continuous(expand=c(0.01, 0.01), limits = c(0,1.5), breaks = seq(0, 1.5, by = 0.25)) + scale_y_continuous(expand=c(0.00, 0.00), limits = c(0,2500),breaks = seq(0, 2500, by = 500)) + geom_segment(aes(x = 0.8, y = 2000, xend = 0.53, yend = 2000), arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = 0.85, y = 2200, label = "Mean", size=2.5)+ theme_bg() resample1000 save_fig("ch05-figure-2-resample1000", output, "small") # Figure 5.3 ggplot(nobs_df,aes(nobs_1000))+ stat_density(geom="line", aes(color = 'n1000'), bw = 0.45,size = 1,kernel = "epanechnikov")+ stat_density(geom="line",aes(nobs_500, color = "n500"), bw=0.45,linetype="twodash", size = 1,kernel = "epanechnikov")+ labs(x="Percent of days with losses over 5%", y="Density")+ geom_vline(xintercept = 0.5,colour=color[3], size = 0.7, linetype="dashed")+ geom_segment(aes(x = 0.9, y = 0.72, xend = 0.65, yend = 0.72), size = 0.5, arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = 1.1, y = 0.72, label = "Larger sample", size=2)+ geom_segment(aes(x = 0.9, y = 0.68, xend = 0.65, yend = 0.68), size = 0.5, arrow = arrow(length = unit(0.1, "cm")))+ annotate("text", x = 1.1, y = 0.68, label = "Smaller sample", size=2) + scale_x_continuous(expand=c(0.01, 0.01), limits = c(0,1.5), breaks = seq(0, 1.5, by = 0.25)) + scale_y_continuous(expand=c(0.00, 0.00), limits = c(0,0.8),breaks = seq(0, 0.8, by = 0.2)) + scale_color_manual(name = "", values = c(n1000= color[1], n500 = color[2]))+ theme_bg()+ theme(legend.position = "none") #save_fig("ch05-figure-3-resample-densities", output, "small") gh<-ggplot(data=nobs_df)+ geom_histogram( aes(x=nobs_500, y = (..count..)/sum(..count..)*100, color = "n500", fill = "n500"), binwidth = 0.2, boundary=0, closed='left', alpha=0.7) + geom_histogram( aes(x=nobs_1000, y = (..count..)/sum(..count..)*100, color = "n1000", fill = "n1000"), binwidth = 0.2, boundary=0, closed='left', alpha=0.1, size=0.7) + ylab("Percent") + xlab("Percent of days with losses over 5%") + scale_x_continuous(expand=c(0.01, 0.01), limits = c(0,1.6), breaks = seq(0, 1.6, by = 0.2)) + scale_y_continuous(expand=c(0.00, 0.00), limits = c(0,50)) + scale_color_manual(name = "", values = c(color[2], color[1])) + scale_fill_manual(name = "", values = c(color[2], color[1])) + theme_bg() + theme(legend.position = c(0.7,0.9), legend.key.size = unit(x = 0.4, units = "cm"), legend.direction = "horizontal") gh save_fig("ch05-figure-3-resample-hist", output, "small") options(digits = 1) #table janitor::tabyl(nobs_df$nobs_500, sort = TRUE) #summarytools::freq(nobs_df$nobs_500, order = "freq") janitor::tabyl(nobs_df$nobs_1000, sort = TRUE) #################################### #BOOTSRTAP SAMPLES set.seed(573164) M <- 10000 Results <- matrix(rep(0,(M*10)),nrow=M,ncol=10) for (i in 1:M){ bsample <- sample(sp500$pct_return,size=dim(sp500)[1], replace = TRUE) for (j in 1:10){ loss <- as.numeric(bsample<(-j))*100 Results[i,j] <- mean(loss, na.rm=T) } } Results <- as_tibble(Results) names(Results) <- c("loss1","loss2","loss3","loss4","loss5","loss6", "loss7","loss8","loss9","loss10") # Figure 5.5 bootstrap<- ggplot(Results,aes(loss5))+ geom_histogram_da(type="frequency", binwidth = 0.04, boundary=0, closed='left')+ scale_y_continuous(expand=c(0,0),limits = c(0,1200), breaks = seq(0,1200,200)) + scale_x_continuous(expand=c(0.01,0.01),limits=c(0,1.2), breaks = seq(0,1.2,0.1)) + labs(x = "Percent of days with losses of 5% or more", y = "Frequency")+ theme_bg() bootstrap save_fig("ch05-figure-5-bootstrap", output, "small")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/simulation.R \name{ComputePropCnst} \alias{ComputePropCnst} \title{Compute Proportionality Constant} \usage{ ComputePropCnst(n, traj, lim) } \arguments{ \item{n}{Number of samples.} \item{traj}{A function of time (intensity).} \item{lim}{A numeric tuple of start and end time.} } \value{ A numeric scalar as proportionality constant. } \description{ Compute proportionality constant to produce a correct expected number of samples }
/man/ComputePropCnst.Rd
permissive
Mamie/PILAF
R
false
true
513
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/simulation.R \name{ComputePropCnst} \alias{ComputePropCnst} \title{Compute Proportionality Constant} \usage{ ComputePropCnst(n, traj, lim) } \arguments{ \item{n}{Number of samples.} \item{traj}{A function of time (intensity).} \item{lim}{A numeric tuple of start and end time.} } \value{ A numeric scalar as proportionality constant. } \description{ Compute proportionality constant to produce a correct expected number of samples }
\name{heartrate} \alias{heartrate} \docType{data} \title{Heart rate baroreflexes for rabbits} \description{ The dataset contains measurements of mean arterial pressure (mmHG) and heart rate (b/min) for a baroreflex curve. } \usage{data(heartrate)} \format{ A data frame with 18 observations on the following 2 variables. \describe{ \item{\code{pressure}}{a numeric vector containing measurements of arterial pressure.} \item{\code{rate}}{a numeric vector containing measurements of heart rate.} } } \details{ The dataset is an example of an asymmetric dose-response curve, that is not easily handled using the log-logistic or Weibull models. } \source{ Ricketts, J. H. and Head, G. A. (1999) A five-parameter logistic equation for investigating asymmetry of curvature in baroreflex studies, \emph{Am. J. Physiol. (Regulatory Integrative Comp. Physiol. 46)}, \bold{277}, 441--454. } \examples{ \dontrun{ library(drc) ## Fitting the baro5 model heartrate.m1 <- drm(rate~pressure, data=heartrate, fct=baro5()) plot(heartrate.m1) coef(heartrate.m1) #Output: #b1:(Intercept) b2:(Intercept) c:(Intercept) d:(Intercept) e:(Intercept) # 11.07984 46.67492 150.33588 351.29613 75.59392 ## Inserting the estimated baro5 model function in deriv() baro5Derivative <- deriv(~ 150.33588 + ((351.29613 - 150.33588)/ (1 + (1/(1 + exp((2 * 11.07984 * 46.67492/(11.07984 + 46.67492)) * (log(x) - log(75.59392 ))))) * (exp(11.07984 * (log(x) - log(75.59392)))) + (1 - (1/(1 + exp((2 * 11.07984 * 46.67492/(11.07984 + 46.67492)) * (log(x) - log(75.59392 )))))) * (exp(46.67492 * (log(x) - log(75.59392 )))))), "x", function(x){}) ## Plotting the derivative #pressureVector <- 50:100 pressureVector <- seq(50, 100, length.out=300) derivativeVector <- attr(baro5Derivative(pressureVector), "gradient") plot(pressureVector, derivativeVector, type = "l") ## Finding the minimum pressureVector[which.min(derivativeVector)] } } \keyword{datasets}
/man/heartrate.Rd
no_license
DoseResponse/drcData
R
false
false
1,996
rd
\name{heartrate} \alias{heartrate} \docType{data} \title{Heart rate baroreflexes for rabbits} \description{ The dataset contains measurements of mean arterial pressure (mmHG) and heart rate (b/min) for a baroreflex curve. } \usage{data(heartrate)} \format{ A data frame with 18 observations on the following 2 variables. \describe{ \item{\code{pressure}}{a numeric vector containing measurements of arterial pressure.} \item{\code{rate}}{a numeric vector containing measurements of heart rate.} } } \details{ The dataset is an example of an asymmetric dose-response curve, that is not easily handled using the log-logistic or Weibull models. } \source{ Ricketts, J. H. and Head, G. A. (1999) A five-parameter logistic equation for investigating asymmetry of curvature in baroreflex studies, \emph{Am. J. Physiol. (Regulatory Integrative Comp. Physiol. 46)}, \bold{277}, 441--454. } \examples{ \dontrun{ library(drc) ## Fitting the baro5 model heartrate.m1 <- drm(rate~pressure, data=heartrate, fct=baro5()) plot(heartrate.m1) coef(heartrate.m1) #Output: #b1:(Intercept) b2:(Intercept) c:(Intercept) d:(Intercept) e:(Intercept) # 11.07984 46.67492 150.33588 351.29613 75.59392 ## Inserting the estimated baro5 model function in deriv() baro5Derivative <- deriv(~ 150.33588 + ((351.29613 - 150.33588)/ (1 + (1/(1 + exp((2 * 11.07984 * 46.67492/(11.07984 + 46.67492)) * (log(x) - log(75.59392 ))))) * (exp(11.07984 * (log(x) - log(75.59392)))) + (1 - (1/(1 + exp((2 * 11.07984 * 46.67492/(11.07984 + 46.67492)) * (log(x) - log(75.59392 )))))) * (exp(46.67492 * (log(x) - log(75.59392 )))))), "x", function(x){}) ## Plotting the derivative #pressureVector <- 50:100 pressureVector <- seq(50, 100, length.out=300) derivativeVector <- attr(baro5Derivative(pressureVector), "gradient") plot(pressureVector, derivativeVector, type = "l") ## Finding the minimum pressureVector[which.min(derivativeVector)] } } \keyword{datasets}
## load required packages. require(tsne) require(pheatmap) require(MASS) require(cluster) require(mclust) require(flexmix) require(lattice) require(fpc) require(amap) require(RColorBrewer) require(locfit) require(vegan) ## class definition SCseq <- setClass("SCseq", slots = c(expdata = "data.frame", ndata = "data.frame", fdata = "data.frame", distances = "matrix", tsne = "data.frame", cluster = "list", background = "list", out = "list", cpart = "vector", fcol = "vector", filterpar = "list", clusterpar = "list", outlierpar ="list" )) setValidity("SCseq", function(object) { msg <- NULL if ( ! is.data.frame(object@expdata) ){ msg <- c(msg, "input data must be data.frame") }else if ( nrow(object@expdata) < 2 ){ msg <- c(msg, "input data must have more than one row") }else if ( ncol(object@expdata) < 2 ){ msg <- c(msg, "input data must have more than one column") }else if (sum( apply( is.na(object@expdata),1,sum ) ) > 0 ){ msg <- c(msg, "NAs are not allowed in input data") }else if (sum( apply( object@expdata,1,min ) ) < 0 ){ msg <- c(msg, "negative values are not allowed in input data") } if (is.null(msg)) TRUE else msg } ) setMethod("initialize", signature = "SCseq", definition = function(.Object, expdata ){ .Object@expdata <- expdata .Object@ndata <- expdata .Object@fdata <- expdata validObject(.Object) return(.Object) } ) setGeneric("filterdata", function(object, mintotal=3000, minexpr=5, minnumber=1, maxexpr=Inf, downsample=TRUE, dsn=1, rseed=17000) standardGeneric("filterdata")) setMethod("filterdata", signature = "SCseq", definition = function(object,mintotal,minexpr,minnumber,maxexpr,downsample,dsn,rseed) { if ( ! is.numeric(mintotal) ) stop( "mintotal has to be a positive number" ) else if ( mintotal <= 0 ) stop( "mintotal has to be a positive number" ) if ( ! is.numeric(minexpr) ) stop( "minexpr has to be a non-negative number" ) else if ( minexpr < 0 ) stop( "minexpr has to be a non-negative number" ) if ( ! is.numeric(minnumber) ) stop( "minnumber has to be a non-negative integer number" ) else if ( round(minnumber) != minnumber | minnumber < 0 ) stop( "minnumber has to be a non-negative integer number" ) if ( ! ( is.numeric(downsample) | is.logical(downsample) ) ) stop( "downsample has to be logical (TRUE/FALSE)" ) if ( ! is.numeric(dsn) ) stop( "dsn has to be a positive integer number" ) else if ( round(dsn) != dsn | dsn <= 0 ) stop( "dsn has to be a positive integer number" ) object@filterpar <- list(mintotal=mintotal, minexpr=minexpr, minnumber=minnumber, maxexpr=maxexpr, downsample=downsample, dsn=dsn) object@ndata <- object@expdata[,apply(object@expdata,2,sum,na.rm=TRUE) >= mintotal] if ( downsample ){ set.seed(rseed) object@ndata <- downsample(object@expdata,n=mintotal,dsn=dsn) }else{ x <- object@ndata object@ndata <- as.data.frame( t(t(x)/apply(x,2,sum))*median(apply(x,2,sum,na.rm=TRUE)) + .1 ) } x <- object@ndata object@fdata <- x[apply(x>=minexpr,1,sum,na.rm=TRUE) >= minnumber,] x <- object@fdata object@fdata <- x[apply(x,1,max,na.rm=TRUE) < maxexpr,] return(object) } ) downsample <- function(x,n,dsn){ x <- round( x[,apply(x,2,sum,na.rm=TRUE) >= n], 0) nn <- min( apply(x,2,sum) ) for ( j in 1:dsn ){ z <- data.frame(GENEID=rownames(x)) rownames(z) <- rownames(x) initv <- rep(0,nrow(z)) for ( i in 1:dim(x)[2] ){ y <- aggregate(rep(1,nn),list(sample(rep(rownames(x),x[,i]),nn)),sum) na <- names(x)[i] names(y) <- c("GENEID",na) rownames(y) <- y$GENEID z[,na] <- initv k <- intersect(rownames(z),y$GENEID) z[k,na] <- y[k,na] z[is.na(z[,na]),na] <- 0 } rownames(z) <- as.vector(z$GENEID) ds <- if ( j == 1 ) z[,-1] else ds + z[,-1] } ds <- ds/dsn + .1 return(ds) } dist.gen <- function(x,method="euclidean", ...) if ( method %in% c("spearman","pearson","kendall") ) as.dist( 1 - cor(t(x),method=method,...) ) else dist(x,method=method,...) dist.gen.pairs <- function(x,y,...) dist.gen(t(cbind(x,y)),...) binompval <- function(p,N,n){ pval <- pbinom(n,round(N,0),p,lower.tail=TRUE) pval[!is.na(pval) & pval > 0.5] <- 1-pval[!is.na(pval) & pval > 0.5] return(pval) } setGeneric("plotgap", function(object) standardGeneric("plotgap")) setMethod("plotgap", signature = "SCseq", definition = function(object){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before plotgap") if ( sum(is.na(object@cluster$gap$Tab[,3])) > 0 ) stop("run clustexp with do.gap = TRUE first") plot(object@cluster$gap,ylim=c( min(object@cluster$gap$Tab[,3] - object@cluster$gap$Tab[,4]), max(object@cluster$gap$Tab[,3] + object@cluster$gap$Tab[,4]))) } ) setGeneric("plotjaccard", function(object) standardGeneric("plotjaccard")) setMethod("plotjaccard", signature = "SCseq", definition = function(object){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before plotjaccard") if ( length(unique(object@cluster$kpart)) < 2 ) stop("only a single cluster: no Jaccard's similarity plot") barplot(object@cluster$jaccard,names.arg=1:length(object@cluster$jaccard),ylab="Jaccard's similarity") } ) setGeneric("plotoutlierprobs", function(object) standardGeneric("plotoutlierprobs")) setMethod("plotoutlierprobs", signature = "SCseq", definition = function(object){ if ( length(object@cpart) == 0 ) stop("run findoutliers before plotoutlierprobs") p <- object@cluster$kpart[ order(object@cluster$kpart,decreasing=FALSE)] x <- object@out$cprobs[names(p)] fcol <- object@fcol for ( i in 1:max(p) ){ y <- -log10(x + 2.2e-16) y[p != i] <- 0 if ( i == 1 ) b <- barplot(y,ylim=c(0,max(-log10(x + 2.2e-16))*1.1),col=fcol[i],border=fcol[i],names.arg=FALSE,ylab="-log10prob") else barplot(y,add=TRUE,col=fcol[i],border=fcol[i],names.arg=FALSE,axes=FALSE) } abline(-log10(object@outlierpar$probthr),0,col="black",lty=2) d <- b[2,1] - b[1,1] y <- 0 for ( i in 1:max(p) ) y <- append(y,b[sum(p <=i),1] + d/2) axis(1,at=(y[1:(length(y)-1)] + y[-1])/2,lab=1:max(p)) box() } ) setGeneric("plotbackground", function(object) standardGeneric("plotbackground")) setMethod("plotbackground", signature = "SCseq", definition = function(object){ if ( length(object@cpart) == 0 ) stop("run findoutliers before plotbackground") m <- apply(object@fdata,1,mean) v <- apply(object@fdata,1,var) fit <- locfit(v~lp(m,nn=.7),family="gamma",maxk=500) plot(log2(m),log2(v),pch=20,xlab="log2mean",ylab="log2var",col="grey") lines(log2(m[order(m)]),log2(object@background$lvar(m[order(m)],object)),col="red",lwd=2) lines(log2(m[order(m)]),log2(fitted(fit)[order(m)]),col="orange",lwd=2,lty=2) legend("topleft",legend=substitute(paste("y = ",a,"*x^2 + ",b,"*x + ",d,sep=""),list(a=round(coef(object@background$vfit)[3],2),b=round(coef(object@background$vfit)[2],2),d=round(coef(object@background$vfit)[3],2))),bty="n") } ) setGeneric("plotsensitivity", function(object) standardGeneric("plotsensitivity")) setMethod("plotsensitivity", signature = "SCseq", definition = function(object){ if ( length(object@cpart) == 0 ) stop("run findoutliers before plotsensitivity") plot(log10(object@out$thr), object@out$stest, type="l",xlab="log10 Probability cutoff", ylab="Number of outliers") abline(v=log10(object@outlierpar$probthr),col="red",lty=2) } ) setGeneric("diffgenes", function(object,cl1,cl2,mincount=5) standardGeneric("diffgenes")) setMethod("diffgenes", signature = "SCseq", definition = function(object,cl1,cl2,mincount){ part <- object@cpart cl1 <- c(cl1) cl2 <- c(cl2) if ( length(part) == 0 ) stop("run findoutliers before diffgenes") if ( ! is.numeric(mincount) ) stop("mincount has to be a non-negative number") else if ( mincount < 0 ) stop("mincount has to be a non-negative number") if ( length(intersect(cl1, part)) < length(unique(cl1)) ) stop( paste("cl1 has to be a subset of ",paste(sort(unique(part)),collapse=","),"\n",sep="") ) if ( length(intersect(cl2, part)) < length(unique(cl2)) ) stop( paste("cl2 has to be a subset of ",paste(sort(unique(part)),collapse=","),"\n",sep="") ) f <- apply(object@ndata[,part %in% c(cl1,cl2)],1,max) > mincount x <- object@ndata[f,part %in% cl1] y <- object@ndata[f,part %in% cl2] if ( sum(part %in% cl1) == 1 ) m1 <- x else m1 <- apply(x,1,mean) if ( sum(part %in% cl2) == 1 ) m2 <- y else m2 <- apply(y,1,mean) if ( sum(part %in% cl1) == 1 ) s1 <- sqrt(x) else s1 <- sqrt(apply(x,1,var)) if ( sum(part %in% cl2) == 1 ) s2 <- sqrt(y) else s2 <- sqrt(apply(y,1,var)) d <- ( m1 - m2 )/ apply( cbind( s1, s2 ),1,mean ) names(d) <- rownames(object@ndata)[f] if ( sum(part %in% cl1) == 1 ){ names(x) <- names(d) x <- x[order(d,decreasing=TRUE)] }else{ x <- x[order(d,decreasing=TRUE),] } if ( sum(part %in% cl2) == 1 ){ names(y) <- names(d) y <- y[order(d,decreasing=TRUE)] }else{ y <- y[order(d,decreasing=TRUE),] } return(list(z=d[order(d,decreasing=TRUE)],cl1=x,cl2=y,cl1n=cl1,cl2n=cl2)) } ) plotdiffgenes <- function(z,gene=g){ if ( ! is.list(z) ) stop("first arguments needs to be output of function diffgenes") if ( length(z) < 5 ) stop("first arguments needs to be output of function diffgenes") if ( sum(names(z) == c("z","cl1","cl2","cl1n","cl2n")) < 5 ) stop("first arguments needs to be output of function diffgenes") if ( length(gene) > 1 ) stop("only single value allowed for argument gene") if ( !is.numeric(gene) & !(gene %in% names(z$z)) ) stop("argument gene needs to be within rownames of first argument or a positive integer number") if ( is.numeric(gene) ){ if ( gene < 0 | round(gene) != gene ) stop("argument gene needs to be within rownames of first argument or a positive integer number") } x <- if ( is.null(dim(z$cl1)) ) z$cl1[gene] else t(z$cl1[gene,]) y <- if ( is.null(dim(z$cl2)) ) z$cl2[gene] else t(z$cl2[gene,]) plot(1:length(c(x,y)),c(x,y),ylim=c(0,max(c(x,y))),xlab="",ylab="Expression",main=gene,cex=0,axes=FALSE) axis(2) box() u <- 1:length(x) rect(u - .5,0,u + .5,x,col="red") v <- c(min(u) - .5,max(u) + .5) axis(1,at=mean(v),lab=paste(z$cl1n,collapse=",")) lines(v,rep(mean(x),length(v))) lines(v,rep(mean(x)-sqrt(var(x)),length(v)),lty=2) lines(v,rep(mean(x)+sqrt(var(x)),length(v)),lty=2) u <- ( length(x) + 1 ):length(c(x,y)) v <- c(min(u) - .5,max(u) + .5) rect(u - .5,0,u + .5,y,col="blue") axis(1,at=mean(v),lab=paste(z$cl2n,collapse=",")) lines(v,rep(mean(y),length(v))) lines(v,rep(mean(y)-sqrt(var(y)),length(v)),lty=2) lines(v,rep(mean(y)+sqrt(var(y)),length(v)),lty=2) abline(v=length(x) + .5) } setGeneric("plottsne", function(object,final=TRUE) standardGeneric("plottsne")) setMethod("plottsne", signature = "SCseq", definition = function(object,final){ if ( length(object@tsne) == 0 ) stop("run comptsne before plottsne") if ( final & length(object@cpart) == 0 ) stop("run findoutliers before plottsne") if ( !final & length(object@cluster$kpart) == 0 ) stop("run clustexp before plottsne") part <- if ( final ) object@cpart else object@cluster$kpart plot(object@tsne,xlab="Dim 1",ylab="Dim 2",pch=20,cex=1.5,col="lightgrey") for ( i in 1:max(part) ){ if ( sum(part == i) > 0 ) text(object@tsne[part == i,1],object@tsne[part == i,2],i,col=object@fcol[i],cex=.75,font=4) } } ) setGeneric("plotlabelstsne", function(object,labels=NULL) standardGeneric("plotlabelstsne")) setMethod("plotlabelstsne", signature = "SCseq", definition = function(object,labels){ if ( is.null(labels ) ) labels <- names(object@ndata) if ( length(object@tsne) == 0 ) stop("run comptsne before plotlabelstsne") plot(object@tsne,xlab="Dim 1",ylab="Dim 2",pch=20,cex=1.5,col="lightgrey") text(object@tsne[,1],object@tsne[,2],labels,cex=.5) } ) setGeneric("plotsymbolstsne", function(object,types=NULL) standardGeneric("plotsymbolstsne")) setMethod("plotsymbolstsne", signature = "SCseq", definition = function(object,types){ if ( is.null(types) ) types <- names(object@fdata) if ( length(object@tsne) == 0 ) stop("run comptsne before plotsymbolstsne") if ( length(types) != ncol(object@fdata) ) stop("types argument has wrong length. Length has to equal to the column number of object@ndata") coloc <- rainbow(length(unique(types))) syms <- c() plot(object@tsne,xlab="Dim 1",ylab="Dim 2",pch=20,col="grey") for ( i in 1:length(unique(types)) ){ f <- types == sort(unique(types))[i] syms <- append( syms, ( (i-1) %% 25 ) + 1 ) points(object@tsne[f,1],object@tsne[f,2],col=coloc[i],pch=( (i-1) %% 25 ) + 1,cex=1) } legend("topleft", legend=sort(unique(types)), col=coloc, pch=syms) } ) setGeneric("plotexptsne", function(object,g,n="",logsc=FALSE) standardGeneric("plotexptsne")) setMethod("plotexptsne", signature = "SCseq", definition = function(object,g,n="",logsc=FALSE){ if ( length(object@tsne) == 0 ) stop("run comptsne before plottsne") if ( length(intersect(g,rownames(object@ndata))) < length(unique(g)) ) stop("second argument does not correspond to set of rownames slot ndata of SCseq object") if ( !is.numeric(logsc) & !is.logical(logsc) ) stop("argument logsc has to be logical (TRUE/FALSE)") if ( n == "" ) n <- g[1] l <- apply(object@ndata[g,] - .1,2,sum) + .1 if (logsc) { f <- l == 0 l <- log2(l) l[f] <- NA } mi <- min(l,na.rm=TRUE) ma <- max(l,na.rm=TRUE) ColorRamp <- colorRampPalette(rev(brewer.pal(n = 7,name = "RdYlBu")))(100) ColorLevels <- seq(mi, ma, length=length(ColorRamp)) v <- round((l - mi)/(ma - mi)*99 + 1,0) layout(matrix(data=c(1,3,2,4), nrow=2, ncol=2), widths=c(5,1,5,1), heights=c(5,1,1,1)) par(mar = c(3,5,2.5,2)) plot(object@tsne,xlab="Dim 1",ylab="Dim 2",main=n,pch=20,cex=0,col="grey") for ( k in 1:length(v) ){ points(object@tsne[k,1],object@tsne[k,2],col=ColorRamp[v[k]],pch=20,cex=1.5) } par(mar = c(3,2.5,2.5,2)) image(1, ColorLevels, matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1), col=ColorRamp, xlab="",ylab="", xaxt="n") layout(1) } ) plot.err.bars.y <- function(x, y, y.err, col="black", lwd=1, lty=1, h=0.1){ arrows(x,y-y.err,x,y+y.err,code=0, col=col, lwd=lwd, lty=lty) arrows(x-h,y-y.err,x+h,y-y.err,code=0, col=col, lwd=lwd, lty=lty) arrows(x-h,y+y.err,x+h,y+y.err,code=0, col=col, lwd=lwd, lty=lty) } clusGapExt <-function (x, FUNcluster, K.max, B = 100, verbose = interactive(), method="euclidean",random=TRUE, ...) { stopifnot(is.function(FUNcluster), length(dim(x)) == 2, K.max >= 2, (n <- nrow(x)) >= 1, (p <- ncol(x)) >= 1) if (B != (B. <- as.integer(B)) || (B <- B.) <= 0) stop("'B' has to be a positive integer") if (is.data.frame(x)) x <- as.matrix(x) ii <- seq_len(n) W.k <- function(X, kk) { clus <- if (kk > 1) FUNcluster(X, kk, ...)$cluster else rep.int(1L, nrow(X)) 0.5 * sum(vapply(split(ii, clus), function(I) { xs <- X[I, , drop = FALSE] sum(dist.gen(xs,method=method)/nrow(xs)) }, 0)) } logW <- E.logW <- SE.sim <- numeric(K.max) if (verbose) cat("Clustering k = 1,2,..., K.max (= ", K.max, "): .. ", sep = "") for (k in 1:K.max) logW[k] <- log(W.k(x, k)) if (verbose) cat("done\n") xs <- scale(x, center = TRUE, scale = FALSE) m.x <- rep(attr(xs, "scaled:center"), each = n) V.sx <- svd(xs)$v rng.x1 <- apply(xs %*% V.sx, 2, range) logWks <- matrix(0, B, K.max) if (random){ if (verbose) cat("Bootstrapping, b = 1,2,..., B (= ", B, ") [one \".\" per sample]:\n", sep = "") for (b in 1:B) { z1 <- apply(rng.x1, 2, function(M, nn) runif(nn, min = M[1], max = M[2]), nn = n) z <- tcrossprod(z1, V.sx) + m.x ##z <- apply(x,2,function(m) runif(length(m),min=min(m),max=max(m))) ##z <- apply(x,2,function(m) sample(m)) for (k in 1:K.max) { logWks[b, k] <- log(W.k(z, k)) } if (verbose) cat(".", if (b%%50 == 0) paste(b, "\n")) } if (verbose && (B%%50 != 0)) cat("", B, "\n") E.logW <- colMeans(logWks) SE.sim <- sqrt((1 + 1/B) * apply(logWks, 2, var)) }else{ E.logW <- rep(NA,K.max) SE.sim <- rep(NA,K.max) } structure(class = "clusGap", list(Tab = cbind(logW, E.logW, gap = E.logW - logW, SE.sim), n = n, B = B, FUNcluster = FUNcluster)) } clustfun <- function(x,clustnr=20,bootnr=50,metric="pearson",do.gap=FALSE,sat=TRUE,SE.method="Tibs2001SEmax",SE.factor=.25,B.gap=50,cln=0,rseed=17000,FUNcluster="kmedoids",distances=NULL,link="single") { if ( clustnr < 2) stop("Choose clustnr > 1") di <- if ( FUNcluster == "kmedoids" ) t(x) else dist.gen(t(x),method=metric) if ( nrow(di) - 1 < clustnr ) clustnr <- nrow(di) - 1 if ( do.gap | sat | cln > 0 ){ gpr <- NULL f <- if ( cln == 0 ) TRUE else FALSE if ( do.gap ){ set.seed(rseed) if ( FUNcluster == "kmeans" ) gpr <- clusGapExt(as.matrix(di), FUN = kmeans, K.max = clustnr, B = B.gap, iter.max=100) if ( FUNcluster == "kmedoids" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k) pam(dist.gen(x,method=metric),k), K.max = clustnr, B = B.gap, method=metric) if ( FUNcluster == "hclust" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k){ y <- hclusterCBI(x,k,link=link,scaling=FALSE); y$cluster <- y$partition; y }, K.max = clustnr, B = B.gap) if ( f ) cln <- maxSE(gpr$Tab[,3],gpr$Tab[,4],method=SE.method,SE.factor) } if ( sat ){ if ( ! do.gap ){ if ( FUNcluster == "kmeans" ) gpr <- clusGapExt(as.matrix(di), FUN = kmeans, K.max = clustnr, B = B.gap, iter.max=100, random=FALSE) if ( FUNcluster == "kmedoids" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k) pam(dist.gen(x,method=metric),k), K.max = clustnr, B = B.gap, random=FALSE, method=metric) if ( FUNcluster == "hclust" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k){ y <- hclusterCBI(x,k,link=link,scaling=FALSE); y$cluster <- y$partition; y }, K.max = clustnr, B = B.gap, random=FALSE) } g <- gpr$Tab[,1] y <- g[-length(g)] - g[-1] mm <- numeric(length(y)) nn <- numeric(length(y)) for ( i in 1:length(y)){ mm[i] <- mean(y[i:length(y)]) nn[i] <- sqrt(var(y[i:length(y)])) } if ( f ) cln <- max(min(which( y - (mm + nn) < 0 )),1) } if ( cln <= 1 ) { clb <- list(result=list(partition=rep(1,dim(x)[2])),bootmean=1) names(clb$result$partition) <- names(x) return(list(x=x,clb=clb,gpr=gpr,di=if ( FUNcluster == "kmedoids" ) dist.gen(di,method=metric) else di)) } if ( FUNcluster == "kmeans" ) clb <- clusterboot(di,B=bootnr,distances=FALSE,bootmethod="boot",clustermethod=kmeansCBI,krange=cln,scaling=FALSE,multipleboot=FALSE,bscompare=TRUE,seed=rseed) if ( FUNcluster == "kmedoids" ) clb <- clusterboot(dist.gen(di,method=metric),B=bootnr,bootmethod="boot",clustermethod=pamkCBI,k=cln,multipleboot=FALSE,bscompare=TRUE,seed=rseed) if ( FUNcluster == "hclust" ) clb <- clusterboot(di,B=bootnr,distances=FALSE,bootmethod="boot",clustermethod=hclusterCBI,k=cln,link=link,scaling=FALSE,multipleboot=FALSE,bscompare=TRUE,seed=rseed) return(list(x=x,clb=clb,gpr=gpr,di=if ( FUNcluster == "kmedoids" ) dist.gen(di,method=metric) else di)) } } setGeneric("clustexp", function(object,clustnr=20,bootnr=50,metric="pearson",do.gap=FALSE,sat=TRUE,SE.method="Tibs2001SEmax",SE.factor=.25,B.gap=50,cln=0,rseed=17000,FUNcluster="kmedoids") standardGeneric("clustexp")) setMethod("clustexp", signature = "SCseq", definition = function(object,clustnr,bootnr,metric,do.gap,sat,SE.method,SE.factor,B.gap,cln,rseed,FUNcluster) { if ( ! is.numeric(clustnr) ) stop("clustnr has to be a positive integer") else if ( round(clustnr) != clustnr | clustnr <= 0 ) stop("clustnr has to be a positive integer") if ( ! is.numeric(bootnr) ) stop("bootnr has to be a positive integer") else if ( round(bootnr) != bootnr | bootnr <= 0 ) stop("bootnr has to be a positive integer") if ( ! ( metric %in% c( "spearman","pearson","kendall","euclidean","maximum","manhattan","canberra","binary","minkowski") ) ) stop("metric has to be one of the following: spearman, pearson, kendall, euclidean, maximum, manhattan, canberra, binary, minkowski") if ( ! ( SE.method %in% c( "firstSEmax","Tibs2001SEmax","globalSEmax","firstmax","globalmax") ) ) stop("SE.method has to be one of the following: firstSEmax, Tibs2001SEmax, globalSEmax, firstmax, globalmax") if ( ! is.numeric(SE.factor) ) stop("SE.factor has to be a non-negative integer") else if ( SE.factor < 0 ) stop("SE.factor has to be a non-negative integer") if ( ! ( is.numeric(do.gap) | is.logical(do.gap) ) ) stop( "do.gap has to be logical (TRUE/FALSE)" ) if ( ! ( is.numeric(sat) | is.logical(sat) ) ) stop( "sat has to be logical (TRUE/FALSE)" ) if ( ! is.numeric(B.gap) ) stop("B.gap has to be a positive integer") else if ( round(B.gap) != B.gap | B.gap <= 0 ) stop("B.gap has to be a positive integer") if ( ! is.numeric(cln) ) stop("cln has to be a non-negative integer") else if ( round(cln) != cln | cln < 0 ) stop("cln has to be a non-negative integer") if ( ! is.numeric(rseed) ) stop("rseed has to be numeric") if ( !do.gap & !sat & cln == 0 ) stop("cln has to be a positive integer or either do.gap or sat has to be TRUE") if ( ! ( FUNcluster %in% c("kmeans","hclust","kmedoids") ) ) stop("FUNcluster has to be one of the following: kmeans, hclust,kmedoids") object@clusterpar <- list(clustnr=clustnr,bootnr=bootnr,metric=metric,do.gap=do.gap,sat=sat,SE.method=SE.method,SE.factor=SE.factor,B.gap=B.gap,cln=cln,rseed=rseed,FUNcluster=FUNcluster) y <- clustfun(object@fdata,clustnr,bootnr,metric,do.gap,sat,SE.method,SE.factor,B.gap,cln,rseed,FUNcluster) object@cluster <- list(kpart=y$clb$result$partition, jaccard=y$clb$bootmean, gap=y$gpr, clb=y$clb) object@distances <- as.matrix( y$di ) set.seed(111111) object@fcol <- sample(rainbow(max(y$clb$result$partition))) return(object) } ) setGeneric("findoutliers", function(object,outminc=5,outlg=2,probthr=1e-3,thr=2**-(1:40),outdistquant=.95) standardGeneric("findoutliers")) setMethod("findoutliers", signature = "SCseq", definition = function(object,outminc,outlg,probthr,thr,outdistquant) { if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before findoutliers") if ( ! is.numeric(outminc) ) stop("outminc has to be a non-negative integer") else if ( round(outminc) != outminc | outminc < 0 ) stop("outminc has to be a non-negative integer") if ( ! is.numeric(outlg) ) stop("outlg has to be a non-negative integer") else if ( round(outlg) != outlg | outlg < 0 ) stop("outlg has to be a non-negative integer") if ( ! is.numeric(probthr) ) stop("probthr has to be a number between 0 and 1") else if ( probthr < 0 | probthr > 1 ) stop("probthr has to be a number between 0 and 1") if ( ! is.numeric(thr) ) stop("thr hast to be a vector of numbers between 0 and 1") else if ( min(thr) < 0 | max(thr) > 1 ) stop("thr hast to be a vector of numbers between 0 and 1") if ( ! is.numeric(outdistquant) ) stop("outdistquant has to be a number between 0 and 1") else if ( outdistquant < 0 | outdistquant > 1 ) stop("outdistquant has to be a number between 0 and 1") object@outlierpar <- list( outminc=outminc,outlg=outlg,probthr=probthr,thr=thr,outdistquant=outdistquant ) ### calibrate background model m <- log2(apply(object@fdata,1,mean)) v <- log2(apply(object@fdata,1,var)) f <- m > -Inf & v > -Inf m <- m[f] v <- v[f] mm <- -8 repeat{ fit <- lm(v ~ m + I(m^2)) if( coef(fit)[3] >= 0 | mm >= 3){ break } mm <- mm + .5 f <- m > mm m <- m[f] v <- v[f] } object@background <- list() object@background$vfit <- fit object@background$lvar <- function(x,object) 2**(coef(object@background$vfit)[1] + log2(x)*coef(object@background$vfit)[2] + coef(object@background$vfit)[3] * log2(x)**2) object@background$lsize <- function(x,object) x**2/(max(x + 1e-6,object@background$lvar(x,object)) - x) ### identify outliers out <- c() stest <- rep(0,length(thr)) cprobs <- c() for ( n in 1:max(object@cluster$kpart) ){ if ( sum(object@cluster$kpart == n) == 1 ){ cprobs <- append(cprobs,.5); names(cprobs)[length(cprobs)] <- names(object@cluster$kpart)[object@cluster$kpart == n]; next } x <- object@fdata[,object@cluster$kpart == n] x <- x[apply(x,1,max) > outminc,] z <- t( apply(x,1,function(x){ apply( cbind( pnbinom(round(x,0),mu=mean(x),size=object@background$lsize(mean(x),object)) , 1 - pnbinom(round(x,0),mu=mean(x),size=object@background$lsize(mean(x),object)) ),1, min) } ) ) cp <- apply(z,2,function(x){ y <- p.adjust(x,method="BH"); y <- y[order(y,decreasing=FALSE)]; return(y[outlg]);}) f <- cp < probthr cprobs <- append(cprobs,cp) if ( sum(f) > 0 ) out <- append(out,names(x)[f]) for ( j in 1:length(thr) ) stest[j] <- stest[j] + sum( cp < thr[j] ) } object@out <-list(out=out,stest=stest,thr=thr,cprobs=cprobs) ### cluster outliers clp2p.cl <- c() cols <- names(object@fdata) cpart <- object@cluster$kpart di <- as.data.frame(object@distances) for ( i in 1:max(cpart) ) { tcol <- cols[cpart == i] if ( sum(!(tcol %in% out)) > 1 ) clp2p.cl <- append(clp2p.cl,as.vector(t(di[tcol[!(tcol %in% out)],tcol[!(tcol %in% out)]]))) } clp2p.cl <- clp2p.cl[clp2p.cl>0] cadd <- list() if ( length(out) > 0 ){ if (length(out) == 1){ cadd <- list(out) }else{ n <- out m <- as.data.frame(di[out,out]) for ( i in 1:length(out) ){ if ( length(n) > 1 ){ o <- order(apply(cbind(m,1:dim(m)[1]),1,function(x) min(x[1:(length(x)-1)][-x[length(x)]])),decreasing=FALSE) m <- m[o,o] n <- n[o] f <- m[,1] < quantile(clp2p.cl,outdistquant) | m[,1] == min(clp2p.cl) ind <- 1 if ( sum(f) > 1 ) for ( j in 2:sum(f) ) if ( apply(m[f,f][j,c(ind,j)] > quantile(clp2p.cl,outdistquant) ,1,sum) == 0 ) ind <- append(ind,j) cadd[[i]] <- n[f][ind] g <- ! n %in% n[f][ind] n <- n[g] m <- m[g,g] if ( sum(g) == 0 ) break }else if (length(n) == 1){ cadd[[i]] <- n break } } } for ( i in 1:length(cadd) ){ cpart[cols %in% cadd[[i]]] <- max(cpart) + 1 } } ### determine final clusters for ( i in 1:max(cpart) ){ if ( sum(cpart == i) == 0 ) next f <- cols[cpart == i] d <- object@fdata if ( length(f) == 1 ){ cent <- d[,f] }else{ if ( object@clusterpar$FUNcluster == "kmedoids" ){ x <- apply(as.matrix(dist.gen(t(d[,f]),method=object@clusterpar$metric)),2,mean) cent <- d[,f[which(x == min(x))[1]]] }else{ cent <- apply(d[,f],1,mean) } } if ( i == 1 ) dcent <- data.frame(cent) else dcent <- cbind(dcent,cent) if ( i == 1 ) tmp <- data.frame(apply(d,2,dist.gen.pairs,y=cent,method=object@clusterpar$metric)) else tmp <- cbind(tmp,apply(d,2,dist.gen.pairs,y=cent,method=object@clusterpar$metric)) } cpart <- apply(tmp,1,function(x) order(x,decreasing=FALSE)[1]) for ( i in max(cpart):1){if (sum(cpart==i)==0) cpart[cpart>i] <- cpart[cpart>i] - 1 } object@cpart <- cpart set.seed(111111) object@fcol <- sample(rainbow(max(cpart))) return(object) } ) setGeneric("comptsne", function(object,rseed=15555,sammonmap=FALSE,initial_cmd=TRUE,...) standardGeneric("comptsne")) setMethod("comptsne", signature = "SCseq", definition = function(object,rseed,sammonmap,...){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before comptsne") set.seed(rseed) di <- if ( object@clusterpar$FUNcluster == "kmedoids") as.dist(object@distances) else dist.gen(as.matrix(object@distances)) if ( sammonmap ){ object@tsne <- as.data.frame(sammon(di,k=2)$points) }else{ ts <- if ( initial_cmd ) tsne(di,initial_config=cmdscale(di,k=2),...) else tsne(di,k=2,...) object@tsne <- as.data.frame(ts) } return(object) } ) setGeneric("clustdiffgenes", function(object,pvalue=.01) standardGeneric("clustdiffgenes")) setMethod("clustdiffgenes", signature = "SCseq", definition = function(object,pvalue){ if ( length(object@cpart) == 0 ) stop("run findoutliers before clustdiffgenes") if ( ! is.numeric(pvalue) ) stop("pvalue has to be a number between 0 and 1") else if ( pvalue < 0 | pvalue > 1 ) stop("pvalue has to be a number between 0 and 1") cdiff <- list() x <- object@ndata y <- object@expdata[,names(object@ndata)] part <- object@cpart for ( i in 1:max(part) ){ if ( sum(part == i) == 0 ) next m <- if ( sum(part != i) > 1 ) apply(x[,part != i],1,mean) else x[,part != i] n <- if ( sum(part == i) > 1 ) apply(x[,part == i],1,mean) else x[,part == i] no <- if ( sum(part == i) > 1 ) median(apply(y[,part == i],2,sum))/median(apply(x[,part == i],2,sum)) else sum(y[,part == i])/sum(x[,part == i]) m <- m*no n <- n*no pv <- binompval(m/sum(m),sum(n),n) d <- data.frame(mean.ncl=m,mean.cl=n,fc=n/m,pv=pv)[order(pv,decreasing=FALSE),] cdiff[[paste("cl",i,sep=".")]] <- d[d$pv < pvalue,] } return(cdiff) } ) setGeneric("plotsaturation", function(object,disp=FALSE) standardGeneric("plotsaturation")) setMethod("plotsaturation", signature = "SCseq", definition = function(object,disp){ if ( length(object@cluster$gap) == 0 ) stop("run clustexp before plotsaturation") g <- object@cluster$gap$Tab[,1] y <- g[-length(g)] - g[-1] mm <- numeric(length(y)) nn <- numeric(length(y)) for ( i in 1:length(y)){ mm[i] <- mean(y[i:length(y)]) nn[i] <- sqrt(var(y[i:length(y)])) } cln <- max(min(which( y - (mm + nn) < 0 )),1) x <- 1:length(y) if (disp){ x <- 1:length(g) plot(x,g,pch=20,col="grey",xlab="k",ylab="log within cluster dispersion") f <- x == cln points(x[f],g[f],col="blue") }else{ plot(x,y,pch=20,col="grey",xlab="k",ylab="Change in log within cluster dispersion") points(x,mm,col="red",pch=20) plot.err.bars.y(x,mm,nn,col="red") points(x,y,col="grey",pch=20) f <- x == cln points(x[f],y[f],col="blue") } } ) setGeneric("plotsilhouette", function(object) standardGeneric("plotsilhouette")) setMethod("plotsilhouette", signature = "SCseq", definition = function(object){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before plotsilhouette") if ( length(unique(object@cluster$kpart)) < 2 ) stop("only a single cluster: no silhouette plot") kpart <- object@cluster$kpart distances <- if ( object@clusterpar$FUNcluster == "kmedoids" ) as.dist(object@distances) else dist.gen(object@distances) si <- silhouette(kpart,distances) plot(si) } ) compmedoids <- function(x,part,metric="pearson"){ m <- c() for ( i in sort(unique(part)) ){ f <- names(x)[part == i] if ( length(f) == 1 ){ m <- append(m,f) }else{ y <- apply(as.matrix(dist.gen(t(x[,f]),method=metric)),2,mean) m <- append(m,f[which(y == min(y))[1]]) } } m } setGeneric("clustheatmap", function(object,final=FALSE,hmethod="single") standardGeneric("clustheatmap")) setMethod("clustheatmap", signature = "SCseq", definition = function(object,final,hmethod){ if ( final & length(object@cpart) == 0 ) stop("run findoutliers before clustheatmap") if ( !final & length(object@cluster$kpart) == 0 ) stop("run clustexp before clustheatmap") x <- object@fdata part <- if ( final ) object@cpart else object@cluster$kpart na <- c() j <- 0 for ( i in 1:max(part) ){ if ( sum(part == i) == 0 ) next j <- j + 1 na <- append(na,i) d <- x[,part == i] if ( sum(part == i) == 1 ) cent <- d else cent <- apply(d,1,mean) if ( j == 1 ) tmp <- data.frame(cent) else tmp <- cbind(tmp,cent) } names(tmp) <- paste("cl",na,sep=".") ld <- if ( object@clusterpar$FUNcluster == "kmedoids" ) dist.gen(t(tmp),method=object@clusterpar$metric) else dist.gen(as.matrix(dist.gen(t(tmp),method=object@clusterpar$metric))) if ( max(part) > 1 ) cclmo <- hclust(ld,method=hmethod)$order else cclmo <- 1 q <- part for ( i in 1:max(part) ){ q[part == na[cclmo[i]]] <- i } part <- q di <- if ( object@clusterpar$FUNcluster == "kmedoids" ) object@distances else as.data.frame( as.matrix( dist.gen(t(object@distances)) ) ) pto <- part[order(part,decreasing=FALSE)] ptn <- c() for ( i in 1:max(pto) ){ pt <- names(pto)[pto == i]; z <- if ( length(pt) == 1 ) pt else pt[hclust(as.dist(t(di[pt,pt])),method=hmethod)$order]; ptn <- append(ptn,z) } col <- object@fcol mi <- min(di,na.rm=TRUE) ma <- max(di,na.rm=TRUE) layout(matrix(data=c(1,3,2,4), nrow=2, ncol=2), widths=c(5,1,5,1), heights=c(5,1,1,1)) ColorRamp <- colorRampPalette(brewer.pal(n = 7,name = "RdYlBu"))(100) ColorLevels <- seq(mi, ma, length=length(ColorRamp)) if ( mi == ma ){ ColorLevels <- seq(0.99*mi, 1.01*ma, length=length(ColorRamp)) } par(mar = c(3,5,2.5,2)) image(as.matrix(di[ptn,ptn]),col=ColorRamp,axes=FALSE) abline(0,1) box() tmp <- c() for ( u in 1:max(part) ){ ol <- (0:(length(part) - 1)/(length(part) - 1))[ptn %in% names(x)[part == u]] points(rep(0,length(ol)),ol,col=col[cclmo[u]],pch=15,cex=.75) points(ol,rep(0,length(ol)),col=col[cclmo[u]],pch=15,cex=.75) tmp <- append(tmp,mean(ol)) } axis(1,at=tmp,lab=cclmo) axis(2,at=tmp,lab=cclmo) par(mar = c(3,2.5,2.5,2)) image(1, ColorLevels, matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1), col=ColorRamp, xlab="",ylab="", xaxt="n") layout(1) return(cclmo) } ) ## class definition Ltree <- setClass("Ltree", slots = c(sc = "SCseq", ldata = "list", entropy = "vector", trproj = "list", par = "list", prback = "data.frame", prbacka = "data.frame", ltcoord = "matrix", prtree = "list", sigcell = "vector", cdata = "list" )) setValidity("Ltree", function(object) { msg <- NULL if ( class(object@sc)[1] != "SCseq" ){ msg <- c(msg, "input data must be of class SCseq") } if (is.null(msg)) TRUE else msg } ) setMethod("initialize", signature = "Ltree", definition = function(.Object, sc ){ .Object@sc <- sc validObject(.Object) return(.Object) } ) setGeneric("compentropy", function(object) standardGeneric("compentropy")) setMethod("compentropy", signature = "Ltree", definition = function(object){ probs <- t(t(object@sc@ndata)/apply(object@sc@ndata,2,sum)) object@entropy <- -apply(probs*log(probs)/log(nrow(object@sc@ndata)),2,sum) return(object) } ) compproj <- function(pdiloc,lploc,cnloc,mloc,d=NULL){ pd <- data.frame(pdiloc) k <- paste("X",sort(rep(1:nrow(pdiloc),length(mloc))),sep="") pd$k <- paste("X",1:nrow(pdiloc),sep="") pd <- merge(data.frame(k=k),pd,by="k") if ( is.null(d) ){ cnv <- t(matrix(rep(t(cnloc),nrow(pdiloc)),nrow=ncol(pdiloc))) pdcl <- paste("X",lploc[as.numeric(sub("X","",pd$k))],sep="") rownames(cnloc) <- paste("X",mloc,sep="") pdcn <- cnloc[pdcl,] v <- cnv - pdcn }else{ v <- d$v pdcn <- d$pdcn } w <- pd[,names(pd) != "k"] - pdcn h <- apply(cbind(v,w),1,function(x){ x1 <- x[1:(length(x)/2)]; x2 <- x[(length(x)/2 + 1):length(x)]; x1s <- sqrt(sum(x1**2)); x2s <- sqrt(sum(x2**2)); y <- sum(x1*x2)/x1s/x2s; return( if (x1s == 0 | x2s == 0 ) NA else y ) }) rma <- as.data.frame(matrix(h,ncol=nrow(pdiloc))) names(rma) <- unique(pd$k) pdclu <- lploc[as.numeric(sub("X","",names(rma)))] pdclp <- apply(t(rma),1,function(x) if (sum(!is.na(x)) == 0 ) NA else mloc[which(abs(x) == max(abs(x),na.rm=TRUE))[1]]) pdclh <- apply(t(rma),1,function(x) if (sum(!is.na(x)) == 0 ) NA else x[which(abs(x) == max(abs(x),na.rm=TRUE))[1]]) pdcln <- names(lploc)[as.numeric(sub("X","",names(rma)))] names(rma) <- pdcln rownames(rma) <- paste("X",mloc,sep="") res <- data.frame(o=pdclu,l=pdclp,h=pdclh) rownames(res) <- pdcln return(list(res=res[names(lploc),],rma=as.data.frame(t(rma[,names(lploc)])),d=list(v=v,pdcn=pdcn))) } pdishuffle <- function(pdi,lp,cn,m,all=FALSE){ if ( all ){ d <- as.data.frame(pdi) y <- t(apply(pdi,1,function(x) runif(length(x),min=min(x),max=max(x)))) names(y) <- names(d) rownames(y) <- rownames(d) return(y) }else{ fl <- TRUE for ( i in unique(lp)){ if ( sum(lp == i) > 1 ){ y <-data.frame( t(apply(as.data.frame(pdi[,lp == i]),1,sample)) ) }else{ y <- as.data.frame(pdi[,lp == i]) } names(y) <- names(lp)[lp == i] rownames(y) <- names(lp) z <- if (fl) y else cbind(z,y) fl <- FALSE } z <- t(z[,names(lp)]) return(z) } } setGeneric("projcells", function(object,cthr=0,nmode=FALSE) standardGeneric("projcells")) setMethod("projcells", signature = "Ltree", definition = function(object,cthr,nmode){ if ( ! is.numeric(cthr) ) stop( "cthr has to be a non-negative number" ) else if ( cthr < 0 ) stop( "cthr has to be a non-negative number" ) if ( ! length(object@sc@cpart == 0) ) stop( "please run findoutliers on the SCseq input object before initializing Ltree" ) if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") object@par$cthr <- cthr object@par$nmode <- nmode lp <- object@sc@cpart ld <- object@sc@distances n <- aggregate(rep(1,length(lp)),list(lp),sum) n <- as.vector(n[order(n[,1],decreasing=FALSE),-1]) m <- (1:length(n))[n>cthr] f <- lp %in% m lp <- lp[f] ld <- ld[f,f] pdil <- sc@tsne[f,] cnl <- aggregate(pdil,by=list(lp),median) cnl <- cnl[order(cnl[,1],decreasing=FALSE),-1] pdi <- suppressWarnings( cmdscale(as.matrix(ld),k=ncol(ld)-1) ) cn <- as.data.frame(pdi[compmedoids(sc@fdata[,names(lp)],lp),]) rownames(cn) <- 1:nrow(cn) x <- compproj(pdi,lp,cn,m) res <- x$res if ( nmode ){ rma <- x$rma z <- paste("X",t(as.vector(apply(cbind(lp,ld),1,function(x){ f <- lp != x[1]; lp[f][which(x[-1][f] == min(x[-1][f]))[1]] }))),sep="") k <- apply(cbind(z,rma),1,function(x) (x[-1])[names(rma) == x[1]]) rn <- res rn$l <- as.numeric(sub("X","",z)) rn$h <- as.numeric(k) res <- rn x$res <- res } object@ldata <- list(lp=lp,ld=ld,m=m,pdi=pdi,pdil=pdil,cn=cn,cnl=cnl) object@trproj <- x return(object) } ) setGeneric("projback", function(object,pdishuf=2000,nmode=FALSE,rseed=17000) standardGeneric("projback")) setMethod("projback", signature = "Ltree", definition = function(object,pdishuf,nmode,rseed){ if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( ! is.numeric(pdishuf) ) stop( "pdishuf has to be a non-negative integer number" ) else if ( round(pdishuf) != pdishuf | pdishuf < 0 ) stop( "pdishuf has to be a non-negative integer number" ) if ( length(object@trproj) == 0 ) stop("run projcells before projback") object@par$pdishuf <- pdishuf object@par$rseed <- rseed if ( ! nmode ){ set.seed(rseed) for ( i in 1:pdishuf ){ cat("pdishuffle:",i,"\n") x <- compproj(pdishuffle(object@ldata$pdi,object@ldata$lp,object@ldata$cn,object@ldata$m,all=TRUE),object@ldata$lp,object@ldata$cn,object@ldata$m,d=object@trproj$d)$res y <- if ( i == 1 ) t(x) else cbind(y,t(x)) } ##important object@prback <- as.data.frame(t(y)) x <- object@prback x$n <- as.vector(t(matrix(rep(1:(nrow(x)/nrow(object@ldata$pdi)),nrow(object@ldata$pdi)),ncol=nrow(object@ldata$pdi)))) object@prbacka <- aggregate(data.frame(count=rep(1,nrow(x))),by=list(n=x$n,o=x$o,l=x$l),sum) } return( object ) } ) setGeneric("lineagetree", function(object,pthr=0.01,nmode=FALSE) standardGeneric("lineagetree")) setMethod("lineagetree", signature = "Ltree", definition = function(object,pthr,nmode){ if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( length(object@trproj) == 0 ) stop("run projcells before lineagetree") if ( max(dim(object@prback)) == 0 & ! nmode ) stop("run projback before lineagetree") if ( ! is.numeric(pthr) ) stop( "pthr has to be a non-negative number" ) else if ( pthr < 0 ) stop( "pthr has to be a non-negative number" ) object@par$pthr <- pthr cnl <- object@ldata$cnl pdil <- object@ldata$pdil cn <- object@ldata$cn pdi <- object@ldata$pdi m <- object@ldata$m lp <- object@ldata$lp res <- object@trproj$res rma <- object@trproj$rma prback <- object@prback cm <- as.matrix(dist(cnl))*0 linl <- list() linn <- list() for ( i in 1:length(m) ){ for ( j in i:length(m) ){ linl[[paste(m[i],m[j],sep=".")]] <- c() linn[[paste(m[i],m[j],sep=".")]] <- c() } } sigcell <- c() for ( i in 1:nrow(res) ){ a <- which( m == res$o[i]) if ( sum( lp == m[a] ) == 1 ){ k <- t(cnl)[,a] k <- NA sigcell <- append(sigcell, FALSE) }else{ b <- which(m == res$l[i] ) h <- res$h[i] if ( nmode ){ sigcell <- append(sigcell, FALSE) }else{ f <- prback$o == m[a] & prback$l == m[b] if ( sum(f) > 0 ){ ql <- quantile(prback[f,"h"],pthr,na.rm=TRUE) qh <- quantile(prback[f,"h"],1 - pthr,na.rm=TRUE) }else{ ql <- 0 qh <- 0 } sigcell <- if (is.na(h) ) append(sigcell, NA) else if ( h > qh | h < min(0,ql) ) append(sigcell, TRUE) else append(sigcell, FALSE) } if ( !is.na(res$h[i]) ){ w <- t(pdil)[,i] - t(cnl)[,a] v <- t(cnl)[,b] - t(cnl)[,a] wo <- t(pdi)[,i] - t(cn)[,a] vo <- t(cn)[,b] - t(cn)[,a] df <-( h*sqrt(sum(wo*wo)) )/sqrt(sum(vo*vo))*v k <- df + t(cnl)[,a] cm[a,b] <- cm[a,b] + 1 so <- m[sort(c(a,b))] dfl <- sign(h)*sqrt( sum( df*df ) )/sqrt(sum(v*v)) if ( a > b ) dfl <- 1 - dfl linn[[paste(so[1],so[2],sep=".")]] <- append( linn[[paste(so[1],so[2],sep=".")]], rownames(pdi)[i] ) linl[[paste(so[1],so[2],sep=".")]] <- append( linl[[paste(so[1],so[2],sep=".")]], dfl ) }else{ k <- t(cnl)[,a] for ( j in unique(lp[lp != m[a]]) ){ b <- which(j == m) so <- m[sort(c(a,b))] dfl <- 0 if ( a > b ) dfl <- 1 - dfl linn[[paste(so[1],so[2],sep=".")]] <- append( linn[[paste(so[1],so[2],sep=".")]], rownames(pdi)[i] ) linl[[paste(so[1],so[2],sep=".")]] <- append( linl[[paste(so[1],so[2],sep=".")]], dfl ) } } } lt <- if ( i == 1 ) data.frame(k) else cbind(lt,k) } lt <- t(lt) cm <- as.data.frame(cm) names(cm) <- paste("cl",m,sep=".") rownames(cm) <- paste("cl",m,sep=".") lt <- as.data.frame(lt) rownames(lt) <- rownames(res) object@ltcoord <- as.matrix(lt) object@prtree <- list(n=linn,l=linl) object@cdata$counts <- cm names(sigcell) <- rownames(res) object@sigcell <- sigcell return( object ) } ) setGeneric("comppvalue", function(object,pethr=0.01,nmode=FALSE) standardGeneric("comppvalue")) setMethod("comppvalue", signature = "Ltree", definition = function(object,pethr,nmode){ if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( length(object@prtree) == 0 ) stop("run lineagetree before comppvalue") if ( ! is.numeric(pethr) ) stop( "pethr has to be a non-negative number" ) else if ( pethr < 0 ) stop( "pethr has to be a non-negative number" ) object@par$pethr <- pethr cm <- object@cdata$counts cmpv <- cm*NA cmpvd <- cm*NA cmbr <- cm*NA cmpvn <- cm*NA cmpvnd <- cm*NA cmfr <- cm/apply(cm,1,sum) if ( nmode ){ N <- apply(cm,1,sum) + 1 N0 <- sum(N) - N n0 <- t(matrix(rep(N,length(N)),ncol=length(N))) p <- n0/N0 n <- cm k <- cbind(N,p,n) cmpv <- apply(k,1,function(x){N <- x[1]; p <- x[2:( ncol(cm) + 1 )]; n <- x[( ncol(cm) + 2 ):( 2*ncol(cm) + 1)]; apply(cbind(n,p),1,function(x,N) binom.test(x[1],N,min(1,x[2]),alternative="g")$p.value,N=N)}) cmpvd <- apply(k,1,function(x){N <- x[1]; p <- x[2:( ncol(cm) + 1 )]; n <- x[( ncol(cm) + 2 ):( 2*ncol(cm) + 1)]; apply(cbind(n,p),1,function(x,N) binom.test(x[1],N,min(1,x[2]),alternative="l")$p.value,N=N)}) cmpvn <- cmpv cmpvnd <- cmpvd cmbr <- as.data.frame(n0/N0*N) names(cmbr) <- names(cm) rownames(cmbr) <- rownames(cm) }else{ for ( i in 1:nrow(cm) ){ for ( j in 1:ncol(cm) ){ f <- object@prbacka$o == object@ldata$m[i] & object@prbacka$l == object@ldata$m[j] x <- object@prbacka$count[f] if ( sum(f) < object@par$pdishuf ) x <- append(x,rep(0, object@par$pdishuf - sum(f))) cmbr[i,j] <- if ( sum(f) > 0 ) mean(x) else 0 cmpv[i,j] <- if ( quantile(x,1 - pethr) < cm[i,j] ) 0 else 0.5 cmpvd[i,j] <- if ( quantile(x,pethr) > cm[i,j] ) 0 else 0.5 cmpvn[i,j] <- sum( x >= cm[i,j])/length(x) cmpvnd[i,j] <- sum( x <= cm[i,j])/length(x) } } } diag(cmpv) <- .5 diag(cmpvd) <- .5 diag(cmpvn) <- NA diag(cmpvnd) <- NA object@cdata$counts.br <- cmbr object@cdata$pv.e <- cmpv object@cdata$pv.d <- cmpvd object@cdata$pvn.e <- cmpvn object@cdata$pvn.d <- cmpvnd m <- object@ldata$m linl <- object@prtree$l ls <- as.data.frame(matrix(rep(NA,length(m)**2),ncol=length(m))) names(ls) <- rownames(ls) <- paste("cl",m,sep=".") for ( i in 1:( length(m) - 1 )){ for ( j in (i + 1):length(m) ){ na <- paste(m[i],m[j],sep=".") if ( na %in% names(linl) & min(cmpv[i,j],cmpv[j,i],na.rm=TRUE) < pethr ){ y <- sort(linl[[na]]) nn <- ( 1 - max(y[-1] - y[-length(y)]) ) }else{ nn <- 0 } ls[i,j] <- nn } } object@cdata$linkscore <- ls return(object) } ) setGeneric("plotlinkpv", function(object) standardGeneric("plotlinkpv")) setMethod("plotlinkpv", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotlinkpv") pheatmap(-log2(object@cdata$pvn.e + 1/object@par$pdishuf/2)) } ) setGeneric("plotlinkscore", function(object) standardGeneric("plotlinkscore")) setMethod("plotlinkscore", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotlinkscore") pheatmap(object@cdata$linkscore,cluster_rows=FALSE,cluster_cols=FALSE) } ) setGeneric("plotmapprojections", function(object) standardGeneric("plotmapprojections")) setMethod("plotmapprojections", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmapprojections") cent <- object@sc@fdata[,compmedoids(object@sc@fdata,object@sc@cpart)] dc <- as.data.frame(1 - cor(cent)) names(dc) <- sort(unique(object@sc@cpart)) rownames(dc) <- sort(unique(object@sc@cpart)) trl <- spantree(dc[object@ldata$m,object@ldata$m]) u <- object@ltcoord[,1] v <- object@ltcoord[,2] cnl <- object@ldata$cnl plot(u,v,cex=1.5,col="grey",pch=20,xlab="Dim 1",ylab="Dim 2") for ( i in unique(object@ldata$lp) ){ f <- object@ldata$lp == i; text(u[f],v[f],i,cex=.75,font=4,col=object@sc@fcol[i]) } points(cnl[,1],cnl[,2]) text(cnl[,1],cnl[,2],object@ldata$m,cex=2) for ( i in 1:length(trl$kid) ){ lines(c(cnl[i+1,1],cnl[trl$kid[i],1]),c(cnl[i+1,2],cnl[trl$kid[i],2]),col="black") } } ) setGeneric("plotmap", function(object) standardGeneric("plotmap")) setMethod("plotmap", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmap") cent <- object@sc@fdata[,compmedoids(object@sc@fdata,object@sc@cpart)] dc <- as.data.frame(1 - cor(cent)) names(dc) <- sort(unique(object@sc@cpart)) rownames(dc) <- sort(unique(object@sc@cpart)) trl <- spantree(dc[object@ldata$m,object@ldata$m]) u <- object@ldata$pdil[,1] v <- object@ldata$pdil[,2] cnl <- object@ldata$cnl plot(u,v,cex=1.5,col="grey",pch=20,xlab="Dim 1",ylab="Dim 2") for ( i in unique(object@ldata$lp) ){ f <- object@ldata$lp == i; text(u[f],v[f],i,cex=.75,font=4,col=object@sc@fcol[i]) } points(cnl[,1],cnl[,2]) text(cnl[,1],cnl[,2],object@ldata$m,cex=2) for ( i in 1:length(trl$kid) ){ lines(c(cnl[i+1,1],cnl[trl$kid[i],1]),c(cnl[i+1,2],cnl[trl$kid[i],2]),col="black") } } ) setGeneric("plottree", function(object,showCells=TRUE,nmode=FALSE,scthr=0) standardGeneric("plottree")) setMethod("plottree", signature = "Ltree", definition = function(object,showCells,nmode,scthr){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmap") if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( !is.numeric(showCells) & !is.logical(showCells) ) stop("argument showCells has to be logical (TRUE/FALSE)") if ( ! is.numeric(scthr) ) stop( "scthr has to be a non-negative number" ) else if ( scthr < 0 | scthr > 1 ) stop( "scthr has to be a number between 0 and 1" ) ramp <- colorRamp(c("darkgreen", "yellow", "brown")) mcol <- rgb( ramp(seq(0, 1, length = 101)), max = 255) co <- object@cdata fc <- (co$counts/( co$counts.br + .5))*(co$pv.e < object@par$pethr) fc <- fc*(fc > t(fc)) + t(fc)*(t(fc) >= fc) fc <- log2(fc + (fc == 0)) k <- -log10(sort(unique(as.vector(t(co$pvn.e))[as.vector(t(co$pv.e))<object@par$pethr])) + 1/object@par$pdishuf) if (length(k) == 1) k <- c(k - k/100,k) mlpv <- -log10(co$pvn.e + 1/object@par$pdishuf) diag(mlpv) <- min(mlpv,na.rm=TRUE) dcc <- t(apply(round(100*(mlpv - min(k))/(max(k) - min(k)),0) + 1,1,function(x){y <- c(); for ( n in x ) y <- append(y,if ( n < 1 ) NA else mcol[n]); y })) cx <- c() cy <- c() va <- c() m <- object@ldata$m for ( i in 1:( length(m) - 1 ) ){ for ( j in ( i + 1 ):length(m) ){ if ( min(co$pv.e[i,j],co$pv.e[j,i],na.rm=TRUE) < object@par$pethr ){ if ( mlpv[i,j] > mlpv[j,i] ){ va <- append(va,dcc[i,j]) }else{ va <- append(va,dcc[j,i]) } cx <- append(cx,i) cy <- append(cy,j) } } } cnl <- object@ldata$cnl u <- object@ltcoord[,1] v <- object@ltcoord[,2] layout( cbind(c(1, 1), c(2, 3)),widths=c(5,1,1),height=c(5,5,1)) par(mar = c(12,5,1,1)) if ( showCells ){ plot(u,v,cex=1.5,col="grey",pch=20,xlab="Dim 1",ylab="Dim 2") if ( !nmode ) points(u[object@sigcell],v[object@sigcell],col="black") }else{ plot(u,v,cex=0,xlab="Dim 1",ylab="Dim 2") } if ( length(va) > 0 ){ f <- order(va,decreasing=TRUE) for ( i in 1:length(va) ){ if ( object@cdata$linkscore[cx[i],cy[i]] > scthr ){ if ( showCells ){ lines(cnl[c(cx[i],cy[i]),1],cnl[c(cx[i],cy[i]),2],col=va[i],lwd=2) }else{ ##nn <- min(10,fc[cx[i],cy[i]]) lines(cnl[c(cx[i],cy[i]),1],cnl[c(cx[i],cy[i]),2],col=va[i],lwd=5*object@cdata$linkscore[cx[i],cy[i]]) } } } } en <- aggregate(object@entropy,list(object@sc@cpart),median) en <- en[en$Group.1 %in% m,] mi <- min(en[,2],na.rm=TRUE) ma <- max(en[,2],na.rm=TRUE) w <- round((en[,2] - mi)/(ma - mi)*99 + 1,0) ramp <- colorRamp(c("red","orange", "pink","purple", "blue")) ColorRamp <- rgb( ramp(seq(0, 1, length = 101)), max = 255) ColorLevels <- seq(mi, ma, length=length(ColorRamp)) if ( mi == ma ){ ColorLevels <- seq(0.99*mi, 1.01*ma, length=length(ColorRamp)) } for ( i in m ){ f <- en[,1] == m points(cnl[f,1],cnl[f,2],cex=5,col=ColorRamp[w[f]],pch=20) } text(cnl[,1],cnl[,2],m,cex=1.25,font=4,col="white") par(mar = c(5, 4, 1, 2)) image(1, ColorLevels, matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1), col=ColorRamp, xlab="",ylab="", xaxt="n") coll <- seq(min(k), max(k), length=length(mcol)) image(1, coll, matrix(data=coll, ncol=length(mcol),nrow=1), col=mcol, xlab="",ylab="", xaxt="n") layout(1) } ) setGeneric("plotdistanceratio", function(object) standardGeneric("plotdistanceratio")) setMethod("plotdistanceratio", signature = "Ltree", definition = function(object){ if ( length(object@ldata) <= 0 ) stop("run projcells before plotdistanceratio") l <- as.matrix(dist(object@ldata$pdi)) z <- (l/object@ldata$ld) hist(log2(z),breaks=100,xlab=" log2 emb. distance/distance",main="") } ) setGeneric("getproj", function(object,i) standardGeneric("getproj")) setMethod("getproj", signature = "Ltree", definition = function(object,i){ if ( length(object@ldata) <= 0 ) stop("run projcells before plotdistanceratio") if ( ! i %in% object@ldata$m ) stop(paste("argument i has to be one of",paste(object@ldata$m,collapse=","))) x <- object@trproj$rma[names(object@ldata$lp)[object@ldata$lp == i],] x <- x[,names(x) != paste("X",i,sep="")] f <- !is.na(x[,1]) x <- x[f,] if ( nrow(x) > 1 ){ y <- x y <- as.data.frame(t(apply(y,1,function(x) (x - mean(x))/sqrt(var(x))))) } names(x) = sub("X","cl.",names(x)) names(y) = sub("X","cl.",names(y)) return(list(pr=x,prz=y)) } ) setGeneric("projenrichment", function(object) standardGeneric("projenrichment")) setMethod("projenrichment", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmap") ze <- ( object@cdata$pv.e < object@par$pethr | object@cdata$pv.d < object@par$pethr) * (object@cdata$counts + .1)/( object@cdata$counts.br + .1 ) pheatmap(log2(ze + ( ze == 0 ) ),cluster_rows=FALSE,cluster_cols=FALSE) } ) setGeneric("compscore", function(object,nn=1) standardGeneric("compscore")) setMethod("compscore", signature = "Ltree", definition = function(object,nn){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before compscore") if ( ! is.numeric(nn) ) stop( "nn has to be a non-negative integer number" ) else if ( round(nn) != nn | nn < 0 ) stop( "nn has to be a non-negative integer number" ) x <- object@cdata$counts*(object@cdata$pv.e < object@par$pethr)>0 y <- x | t(x) if ( max(y) > 0 ){ z <- apply(y,1,sum) nl <- list() n <- list() for ( i in 1:nn ){ if ( i == 1 ){ n[[i]] <- as.list(apply(y,1,function(x) grep(TRUE,x))) nl <- data.frame( apply(y,1,sum) ) } if ( i > 1 ){ v <- rep(0,nrow(nl)) n[[i]] <- list() for ( j in 1:length(n[[i-1]]) ){ cl <- n[[i-1]][[j]] if ( length(cl) == 0 ){ n[[i]][[paste("d",j,sep="")]] <- NA v[j] <- 0 }else{ k <- if ( length(cl) > 1 ) apply(y[cl,],2,sum) > 0 else if ( length(cl) == 1 ) y[cl,] n[[i]][[paste("d",j,sep="")]] <- sort(unique(c(cl,grep(TRUE,k)))) v[j] <- length(n[[i]][[paste("d",j,sep="")]]) } } names(n[[i]]) <- names(z) nl <- cbind(nl,v) } } x <- nl[,i] names(x) <- rownames(nl) }else{ x <- rep(0,length(object@ldata$m)) names(x) <- paste("cl",object@ldata$m,sep=".") } v <- aggregate(object@entropy,list(object@sc@cpart),median) v <- v[v$Group.1 %in% object@ldata$m,] w <- as.vector(v[,-1]) names(w) <- paste("cl.",v$Group.1,sep="") w <- w - min(w) return(list(links=x,entropy=w,StemIDscore=x*w)) } ) setGeneric("plotscore", function(object,nn=1) standardGeneric("plotscore")) setMethod("plotscore", signature = "Ltree", definition = function(object,nn){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotscore") x <- compscore(object,nn) layout(1:3) barplot(x$links,names.arg=sub("cl\\.","",object@ldata$m),xlab="Cluster",ylab="Number of links",cex.names=1) barplot(x$entropy,names.arg=sub("cl\\.","",object@ldata$m),xlab="Cluster",ylab="Delta-Entropy",cex.names=1) barplot(x$StemIDscore,names.arg=sub("cl\\.","",object@ldata$m),xlab="Cluster",ylab="Number of links * Delta-Entropy",cex.names=1) layout(1) } ) setGeneric("branchcells", function(object,br) standardGeneric("branchcells")) setMethod("branchcells", signature = "Ltree", definition = function(object,br){ if ( length(object@ldata) <= 0 ) stop("run projcells before branchcells") msg <- paste("br needs to be list of length two containing two branches, where each has to be one of", paste(names(object@prtree$n),collapse=",")) if ( !is.list(br) ) stop(msg) else if ( length(br) != 2 ) stop(msg) else if ( ! br[[1]] %in% names(object@prtree$n) | ! br[[2]] %in% names(object@prtree$n) ) stop(msg) n <- list() scl <- object@sc k <- c() cl <- intersect( as.numeric(strsplit(br[[1]],"\\.")[[1]]), as.numeric(strsplit(br[[2]],"\\.")[[1]])) if ( length(cl) == 0 ) stop("the two branches in br need to have one cluster in common.") for ( i in 1:length(br) ){ f <- object@sc@cpart[ object@prtree$n[[br[[i]]]] ] %in% cl if ( sum(f) > 0 ){ n[[i]] <- names(object@sc@cpart[ object@prtree$n[[br[[i]]]] ])[f] k <- append(k, max( scl@cpart ) + 1) scl@cpart[n[[i]]] <- max( scl@cpart ) + 1 }else{ stop(paste("no cells on branch",br[[i]],"fall into clusters",cl)) } } set.seed(111111) scl@fcol <- sample(rainbow(max(scl@cpart))) z <- diffgenes(scl,k[1],k[2]) return( list(n=n,scl=scl,k=k,diffgenes=z) ) } )
/RaceID2_StemID_class.R
no_license
gruenD/StemID
R
false
false
67,517
r
## load required packages. require(tsne) require(pheatmap) require(MASS) require(cluster) require(mclust) require(flexmix) require(lattice) require(fpc) require(amap) require(RColorBrewer) require(locfit) require(vegan) ## class definition SCseq <- setClass("SCseq", slots = c(expdata = "data.frame", ndata = "data.frame", fdata = "data.frame", distances = "matrix", tsne = "data.frame", cluster = "list", background = "list", out = "list", cpart = "vector", fcol = "vector", filterpar = "list", clusterpar = "list", outlierpar ="list" )) setValidity("SCseq", function(object) { msg <- NULL if ( ! is.data.frame(object@expdata) ){ msg <- c(msg, "input data must be data.frame") }else if ( nrow(object@expdata) < 2 ){ msg <- c(msg, "input data must have more than one row") }else if ( ncol(object@expdata) < 2 ){ msg <- c(msg, "input data must have more than one column") }else if (sum( apply( is.na(object@expdata),1,sum ) ) > 0 ){ msg <- c(msg, "NAs are not allowed in input data") }else if (sum( apply( object@expdata,1,min ) ) < 0 ){ msg <- c(msg, "negative values are not allowed in input data") } if (is.null(msg)) TRUE else msg } ) setMethod("initialize", signature = "SCseq", definition = function(.Object, expdata ){ .Object@expdata <- expdata .Object@ndata <- expdata .Object@fdata <- expdata validObject(.Object) return(.Object) } ) setGeneric("filterdata", function(object, mintotal=3000, minexpr=5, minnumber=1, maxexpr=Inf, downsample=TRUE, dsn=1, rseed=17000) standardGeneric("filterdata")) setMethod("filterdata", signature = "SCseq", definition = function(object,mintotal,minexpr,minnumber,maxexpr,downsample,dsn,rseed) { if ( ! is.numeric(mintotal) ) stop( "mintotal has to be a positive number" ) else if ( mintotal <= 0 ) stop( "mintotal has to be a positive number" ) if ( ! is.numeric(minexpr) ) stop( "minexpr has to be a non-negative number" ) else if ( minexpr < 0 ) stop( "minexpr has to be a non-negative number" ) if ( ! is.numeric(minnumber) ) stop( "minnumber has to be a non-negative integer number" ) else if ( round(minnumber) != minnumber | minnumber < 0 ) stop( "minnumber has to be a non-negative integer number" ) if ( ! ( is.numeric(downsample) | is.logical(downsample) ) ) stop( "downsample has to be logical (TRUE/FALSE)" ) if ( ! is.numeric(dsn) ) stop( "dsn has to be a positive integer number" ) else if ( round(dsn) != dsn | dsn <= 0 ) stop( "dsn has to be a positive integer number" ) object@filterpar <- list(mintotal=mintotal, minexpr=minexpr, minnumber=minnumber, maxexpr=maxexpr, downsample=downsample, dsn=dsn) object@ndata <- object@expdata[,apply(object@expdata,2,sum,na.rm=TRUE) >= mintotal] if ( downsample ){ set.seed(rseed) object@ndata <- downsample(object@expdata,n=mintotal,dsn=dsn) }else{ x <- object@ndata object@ndata <- as.data.frame( t(t(x)/apply(x,2,sum))*median(apply(x,2,sum,na.rm=TRUE)) + .1 ) } x <- object@ndata object@fdata <- x[apply(x>=minexpr,1,sum,na.rm=TRUE) >= minnumber,] x <- object@fdata object@fdata <- x[apply(x,1,max,na.rm=TRUE) < maxexpr,] return(object) } ) downsample <- function(x,n,dsn){ x <- round( x[,apply(x,2,sum,na.rm=TRUE) >= n], 0) nn <- min( apply(x,2,sum) ) for ( j in 1:dsn ){ z <- data.frame(GENEID=rownames(x)) rownames(z) <- rownames(x) initv <- rep(0,nrow(z)) for ( i in 1:dim(x)[2] ){ y <- aggregate(rep(1,nn),list(sample(rep(rownames(x),x[,i]),nn)),sum) na <- names(x)[i] names(y) <- c("GENEID",na) rownames(y) <- y$GENEID z[,na] <- initv k <- intersect(rownames(z),y$GENEID) z[k,na] <- y[k,na] z[is.na(z[,na]),na] <- 0 } rownames(z) <- as.vector(z$GENEID) ds <- if ( j == 1 ) z[,-1] else ds + z[,-1] } ds <- ds/dsn + .1 return(ds) } dist.gen <- function(x,method="euclidean", ...) if ( method %in% c("spearman","pearson","kendall") ) as.dist( 1 - cor(t(x),method=method,...) ) else dist(x,method=method,...) dist.gen.pairs <- function(x,y,...) dist.gen(t(cbind(x,y)),...) binompval <- function(p,N,n){ pval <- pbinom(n,round(N,0),p,lower.tail=TRUE) pval[!is.na(pval) & pval > 0.5] <- 1-pval[!is.na(pval) & pval > 0.5] return(pval) } setGeneric("plotgap", function(object) standardGeneric("plotgap")) setMethod("plotgap", signature = "SCseq", definition = function(object){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before plotgap") if ( sum(is.na(object@cluster$gap$Tab[,3])) > 0 ) stop("run clustexp with do.gap = TRUE first") plot(object@cluster$gap,ylim=c( min(object@cluster$gap$Tab[,3] - object@cluster$gap$Tab[,4]), max(object@cluster$gap$Tab[,3] + object@cluster$gap$Tab[,4]))) } ) setGeneric("plotjaccard", function(object) standardGeneric("plotjaccard")) setMethod("plotjaccard", signature = "SCseq", definition = function(object){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before plotjaccard") if ( length(unique(object@cluster$kpart)) < 2 ) stop("only a single cluster: no Jaccard's similarity plot") barplot(object@cluster$jaccard,names.arg=1:length(object@cluster$jaccard),ylab="Jaccard's similarity") } ) setGeneric("plotoutlierprobs", function(object) standardGeneric("plotoutlierprobs")) setMethod("plotoutlierprobs", signature = "SCseq", definition = function(object){ if ( length(object@cpart) == 0 ) stop("run findoutliers before plotoutlierprobs") p <- object@cluster$kpart[ order(object@cluster$kpart,decreasing=FALSE)] x <- object@out$cprobs[names(p)] fcol <- object@fcol for ( i in 1:max(p) ){ y <- -log10(x + 2.2e-16) y[p != i] <- 0 if ( i == 1 ) b <- barplot(y,ylim=c(0,max(-log10(x + 2.2e-16))*1.1),col=fcol[i],border=fcol[i],names.arg=FALSE,ylab="-log10prob") else barplot(y,add=TRUE,col=fcol[i],border=fcol[i],names.arg=FALSE,axes=FALSE) } abline(-log10(object@outlierpar$probthr),0,col="black",lty=2) d <- b[2,1] - b[1,1] y <- 0 for ( i in 1:max(p) ) y <- append(y,b[sum(p <=i),1] + d/2) axis(1,at=(y[1:(length(y)-1)] + y[-1])/2,lab=1:max(p)) box() } ) setGeneric("plotbackground", function(object) standardGeneric("plotbackground")) setMethod("plotbackground", signature = "SCseq", definition = function(object){ if ( length(object@cpart) == 0 ) stop("run findoutliers before plotbackground") m <- apply(object@fdata,1,mean) v <- apply(object@fdata,1,var) fit <- locfit(v~lp(m,nn=.7),family="gamma",maxk=500) plot(log2(m),log2(v),pch=20,xlab="log2mean",ylab="log2var",col="grey") lines(log2(m[order(m)]),log2(object@background$lvar(m[order(m)],object)),col="red",lwd=2) lines(log2(m[order(m)]),log2(fitted(fit)[order(m)]),col="orange",lwd=2,lty=2) legend("topleft",legend=substitute(paste("y = ",a,"*x^2 + ",b,"*x + ",d,sep=""),list(a=round(coef(object@background$vfit)[3],2),b=round(coef(object@background$vfit)[2],2),d=round(coef(object@background$vfit)[3],2))),bty="n") } ) setGeneric("plotsensitivity", function(object) standardGeneric("plotsensitivity")) setMethod("plotsensitivity", signature = "SCseq", definition = function(object){ if ( length(object@cpart) == 0 ) stop("run findoutliers before plotsensitivity") plot(log10(object@out$thr), object@out$stest, type="l",xlab="log10 Probability cutoff", ylab="Number of outliers") abline(v=log10(object@outlierpar$probthr),col="red",lty=2) } ) setGeneric("diffgenes", function(object,cl1,cl2,mincount=5) standardGeneric("diffgenes")) setMethod("diffgenes", signature = "SCseq", definition = function(object,cl1,cl2,mincount){ part <- object@cpart cl1 <- c(cl1) cl2 <- c(cl2) if ( length(part) == 0 ) stop("run findoutliers before diffgenes") if ( ! is.numeric(mincount) ) stop("mincount has to be a non-negative number") else if ( mincount < 0 ) stop("mincount has to be a non-negative number") if ( length(intersect(cl1, part)) < length(unique(cl1)) ) stop( paste("cl1 has to be a subset of ",paste(sort(unique(part)),collapse=","),"\n",sep="") ) if ( length(intersect(cl2, part)) < length(unique(cl2)) ) stop( paste("cl2 has to be a subset of ",paste(sort(unique(part)),collapse=","),"\n",sep="") ) f <- apply(object@ndata[,part %in% c(cl1,cl2)],1,max) > mincount x <- object@ndata[f,part %in% cl1] y <- object@ndata[f,part %in% cl2] if ( sum(part %in% cl1) == 1 ) m1 <- x else m1 <- apply(x,1,mean) if ( sum(part %in% cl2) == 1 ) m2 <- y else m2 <- apply(y,1,mean) if ( sum(part %in% cl1) == 1 ) s1 <- sqrt(x) else s1 <- sqrt(apply(x,1,var)) if ( sum(part %in% cl2) == 1 ) s2 <- sqrt(y) else s2 <- sqrt(apply(y,1,var)) d <- ( m1 - m2 )/ apply( cbind( s1, s2 ),1,mean ) names(d) <- rownames(object@ndata)[f] if ( sum(part %in% cl1) == 1 ){ names(x) <- names(d) x <- x[order(d,decreasing=TRUE)] }else{ x <- x[order(d,decreasing=TRUE),] } if ( sum(part %in% cl2) == 1 ){ names(y) <- names(d) y <- y[order(d,decreasing=TRUE)] }else{ y <- y[order(d,decreasing=TRUE),] } return(list(z=d[order(d,decreasing=TRUE)],cl1=x,cl2=y,cl1n=cl1,cl2n=cl2)) } ) plotdiffgenes <- function(z,gene=g){ if ( ! is.list(z) ) stop("first arguments needs to be output of function diffgenes") if ( length(z) < 5 ) stop("first arguments needs to be output of function diffgenes") if ( sum(names(z) == c("z","cl1","cl2","cl1n","cl2n")) < 5 ) stop("first arguments needs to be output of function diffgenes") if ( length(gene) > 1 ) stop("only single value allowed for argument gene") if ( !is.numeric(gene) & !(gene %in% names(z$z)) ) stop("argument gene needs to be within rownames of first argument or a positive integer number") if ( is.numeric(gene) ){ if ( gene < 0 | round(gene) != gene ) stop("argument gene needs to be within rownames of first argument or a positive integer number") } x <- if ( is.null(dim(z$cl1)) ) z$cl1[gene] else t(z$cl1[gene,]) y <- if ( is.null(dim(z$cl2)) ) z$cl2[gene] else t(z$cl2[gene,]) plot(1:length(c(x,y)),c(x,y),ylim=c(0,max(c(x,y))),xlab="",ylab="Expression",main=gene,cex=0,axes=FALSE) axis(2) box() u <- 1:length(x) rect(u - .5,0,u + .5,x,col="red") v <- c(min(u) - .5,max(u) + .5) axis(1,at=mean(v),lab=paste(z$cl1n,collapse=",")) lines(v,rep(mean(x),length(v))) lines(v,rep(mean(x)-sqrt(var(x)),length(v)),lty=2) lines(v,rep(mean(x)+sqrt(var(x)),length(v)),lty=2) u <- ( length(x) + 1 ):length(c(x,y)) v <- c(min(u) - .5,max(u) + .5) rect(u - .5,0,u + .5,y,col="blue") axis(1,at=mean(v),lab=paste(z$cl2n,collapse=",")) lines(v,rep(mean(y),length(v))) lines(v,rep(mean(y)-sqrt(var(y)),length(v)),lty=2) lines(v,rep(mean(y)+sqrt(var(y)),length(v)),lty=2) abline(v=length(x) + .5) } setGeneric("plottsne", function(object,final=TRUE) standardGeneric("plottsne")) setMethod("plottsne", signature = "SCseq", definition = function(object,final){ if ( length(object@tsne) == 0 ) stop("run comptsne before plottsne") if ( final & length(object@cpart) == 0 ) stop("run findoutliers before plottsne") if ( !final & length(object@cluster$kpart) == 0 ) stop("run clustexp before plottsne") part <- if ( final ) object@cpart else object@cluster$kpart plot(object@tsne,xlab="Dim 1",ylab="Dim 2",pch=20,cex=1.5,col="lightgrey") for ( i in 1:max(part) ){ if ( sum(part == i) > 0 ) text(object@tsne[part == i,1],object@tsne[part == i,2],i,col=object@fcol[i],cex=.75,font=4) } } ) setGeneric("plotlabelstsne", function(object,labels=NULL) standardGeneric("plotlabelstsne")) setMethod("plotlabelstsne", signature = "SCseq", definition = function(object,labels){ if ( is.null(labels ) ) labels <- names(object@ndata) if ( length(object@tsne) == 0 ) stop("run comptsne before plotlabelstsne") plot(object@tsne,xlab="Dim 1",ylab="Dim 2",pch=20,cex=1.5,col="lightgrey") text(object@tsne[,1],object@tsne[,2],labels,cex=.5) } ) setGeneric("plotsymbolstsne", function(object,types=NULL) standardGeneric("plotsymbolstsne")) setMethod("plotsymbolstsne", signature = "SCseq", definition = function(object,types){ if ( is.null(types) ) types <- names(object@fdata) if ( length(object@tsne) == 0 ) stop("run comptsne before plotsymbolstsne") if ( length(types) != ncol(object@fdata) ) stop("types argument has wrong length. Length has to equal to the column number of object@ndata") coloc <- rainbow(length(unique(types))) syms <- c() plot(object@tsne,xlab="Dim 1",ylab="Dim 2",pch=20,col="grey") for ( i in 1:length(unique(types)) ){ f <- types == sort(unique(types))[i] syms <- append( syms, ( (i-1) %% 25 ) + 1 ) points(object@tsne[f,1],object@tsne[f,2],col=coloc[i],pch=( (i-1) %% 25 ) + 1,cex=1) } legend("topleft", legend=sort(unique(types)), col=coloc, pch=syms) } ) setGeneric("plotexptsne", function(object,g,n="",logsc=FALSE) standardGeneric("plotexptsne")) setMethod("plotexptsne", signature = "SCseq", definition = function(object,g,n="",logsc=FALSE){ if ( length(object@tsne) == 0 ) stop("run comptsne before plottsne") if ( length(intersect(g,rownames(object@ndata))) < length(unique(g)) ) stop("second argument does not correspond to set of rownames slot ndata of SCseq object") if ( !is.numeric(logsc) & !is.logical(logsc) ) stop("argument logsc has to be logical (TRUE/FALSE)") if ( n == "" ) n <- g[1] l <- apply(object@ndata[g,] - .1,2,sum) + .1 if (logsc) { f <- l == 0 l <- log2(l) l[f] <- NA } mi <- min(l,na.rm=TRUE) ma <- max(l,na.rm=TRUE) ColorRamp <- colorRampPalette(rev(brewer.pal(n = 7,name = "RdYlBu")))(100) ColorLevels <- seq(mi, ma, length=length(ColorRamp)) v <- round((l - mi)/(ma - mi)*99 + 1,0) layout(matrix(data=c(1,3,2,4), nrow=2, ncol=2), widths=c(5,1,5,1), heights=c(5,1,1,1)) par(mar = c(3,5,2.5,2)) plot(object@tsne,xlab="Dim 1",ylab="Dim 2",main=n,pch=20,cex=0,col="grey") for ( k in 1:length(v) ){ points(object@tsne[k,1],object@tsne[k,2],col=ColorRamp[v[k]],pch=20,cex=1.5) } par(mar = c(3,2.5,2.5,2)) image(1, ColorLevels, matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1), col=ColorRamp, xlab="",ylab="", xaxt="n") layout(1) } ) plot.err.bars.y <- function(x, y, y.err, col="black", lwd=1, lty=1, h=0.1){ arrows(x,y-y.err,x,y+y.err,code=0, col=col, lwd=lwd, lty=lty) arrows(x-h,y-y.err,x+h,y-y.err,code=0, col=col, lwd=lwd, lty=lty) arrows(x-h,y+y.err,x+h,y+y.err,code=0, col=col, lwd=lwd, lty=lty) } clusGapExt <-function (x, FUNcluster, K.max, B = 100, verbose = interactive(), method="euclidean",random=TRUE, ...) { stopifnot(is.function(FUNcluster), length(dim(x)) == 2, K.max >= 2, (n <- nrow(x)) >= 1, (p <- ncol(x)) >= 1) if (B != (B. <- as.integer(B)) || (B <- B.) <= 0) stop("'B' has to be a positive integer") if (is.data.frame(x)) x <- as.matrix(x) ii <- seq_len(n) W.k <- function(X, kk) { clus <- if (kk > 1) FUNcluster(X, kk, ...)$cluster else rep.int(1L, nrow(X)) 0.5 * sum(vapply(split(ii, clus), function(I) { xs <- X[I, , drop = FALSE] sum(dist.gen(xs,method=method)/nrow(xs)) }, 0)) } logW <- E.logW <- SE.sim <- numeric(K.max) if (verbose) cat("Clustering k = 1,2,..., K.max (= ", K.max, "): .. ", sep = "") for (k in 1:K.max) logW[k] <- log(W.k(x, k)) if (verbose) cat("done\n") xs <- scale(x, center = TRUE, scale = FALSE) m.x <- rep(attr(xs, "scaled:center"), each = n) V.sx <- svd(xs)$v rng.x1 <- apply(xs %*% V.sx, 2, range) logWks <- matrix(0, B, K.max) if (random){ if (verbose) cat("Bootstrapping, b = 1,2,..., B (= ", B, ") [one \".\" per sample]:\n", sep = "") for (b in 1:B) { z1 <- apply(rng.x1, 2, function(M, nn) runif(nn, min = M[1], max = M[2]), nn = n) z <- tcrossprod(z1, V.sx) + m.x ##z <- apply(x,2,function(m) runif(length(m),min=min(m),max=max(m))) ##z <- apply(x,2,function(m) sample(m)) for (k in 1:K.max) { logWks[b, k] <- log(W.k(z, k)) } if (verbose) cat(".", if (b%%50 == 0) paste(b, "\n")) } if (verbose && (B%%50 != 0)) cat("", B, "\n") E.logW <- colMeans(logWks) SE.sim <- sqrt((1 + 1/B) * apply(logWks, 2, var)) }else{ E.logW <- rep(NA,K.max) SE.sim <- rep(NA,K.max) } structure(class = "clusGap", list(Tab = cbind(logW, E.logW, gap = E.logW - logW, SE.sim), n = n, B = B, FUNcluster = FUNcluster)) } clustfun <- function(x,clustnr=20,bootnr=50,metric="pearson",do.gap=FALSE,sat=TRUE,SE.method="Tibs2001SEmax",SE.factor=.25,B.gap=50,cln=0,rseed=17000,FUNcluster="kmedoids",distances=NULL,link="single") { if ( clustnr < 2) stop("Choose clustnr > 1") di <- if ( FUNcluster == "kmedoids" ) t(x) else dist.gen(t(x),method=metric) if ( nrow(di) - 1 < clustnr ) clustnr <- nrow(di) - 1 if ( do.gap | sat | cln > 0 ){ gpr <- NULL f <- if ( cln == 0 ) TRUE else FALSE if ( do.gap ){ set.seed(rseed) if ( FUNcluster == "kmeans" ) gpr <- clusGapExt(as.matrix(di), FUN = kmeans, K.max = clustnr, B = B.gap, iter.max=100) if ( FUNcluster == "kmedoids" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k) pam(dist.gen(x,method=metric),k), K.max = clustnr, B = B.gap, method=metric) if ( FUNcluster == "hclust" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k){ y <- hclusterCBI(x,k,link=link,scaling=FALSE); y$cluster <- y$partition; y }, K.max = clustnr, B = B.gap) if ( f ) cln <- maxSE(gpr$Tab[,3],gpr$Tab[,4],method=SE.method,SE.factor) } if ( sat ){ if ( ! do.gap ){ if ( FUNcluster == "kmeans" ) gpr <- clusGapExt(as.matrix(di), FUN = kmeans, K.max = clustnr, B = B.gap, iter.max=100, random=FALSE) if ( FUNcluster == "kmedoids" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k) pam(dist.gen(x,method=metric),k), K.max = clustnr, B = B.gap, random=FALSE, method=metric) if ( FUNcluster == "hclust" ) gpr <- clusGapExt(as.matrix(di), FUN = function(x,k){ y <- hclusterCBI(x,k,link=link,scaling=FALSE); y$cluster <- y$partition; y }, K.max = clustnr, B = B.gap, random=FALSE) } g <- gpr$Tab[,1] y <- g[-length(g)] - g[-1] mm <- numeric(length(y)) nn <- numeric(length(y)) for ( i in 1:length(y)){ mm[i] <- mean(y[i:length(y)]) nn[i] <- sqrt(var(y[i:length(y)])) } if ( f ) cln <- max(min(which( y - (mm + nn) < 0 )),1) } if ( cln <= 1 ) { clb <- list(result=list(partition=rep(1,dim(x)[2])),bootmean=1) names(clb$result$partition) <- names(x) return(list(x=x,clb=clb,gpr=gpr,di=if ( FUNcluster == "kmedoids" ) dist.gen(di,method=metric) else di)) } if ( FUNcluster == "kmeans" ) clb <- clusterboot(di,B=bootnr,distances=FALSE,bootmethod="boot",clustermethod=kmeansCBI,krange=cln,scaling=FALSE,multipleboot=FALSE,bscompare=TRUE,seed=rseed) if ( FUNcluster == "kmedoids" ) clb <- clusterboot(dist.gen(di,method=metric),B=bootnr,bootmethod="boot",clustermethod=pamkCBI,k=cln,multipleboot=FALSE,bscompare=TRUE,seed=rseed) if ( FUNcluster == "hclust" ) clb <- clusterboot(di,B=bootnr,distances=FALSE,bootmethod="boot",clustermethod=hclusterCBI,k=cln,link=link,scaling=FALSE,multipleboot=FALSE,bscompare=TRUE,seed=rseed) return(list(x=x,clb=clb,gpr=gpr,di=if ( FUNcluster == "kmedoids" ) dist.gen(di,method=metric) else di)) } } setGeneric("clustexp", function(object,clustnr=20,bootnr=50,metric="pearson",do.gap=FALSE,sat=TRUE,SE.method="Tibs2001SEmax",SE.factor=.25,B.gap=50,cln=0,rseed=17000,FUNcluster="kmedoids") standardGeneric("clustexp")) setMethod("clustexp", signature = "SCseq", definition = function(object,clustnr,bootnr,metric,do.gap,sat,SE.method,SE.factor,B.gap,cln,rseed,FUNcluster) { if ( ! is.numeric(clustnr) ) stop("clustnr has to be a positive integer") else if ( round(clustnr) != clustnr | clustnr <= 0 ) stop("clustnr has to be a positive integer") if ( ! is.numeric(bootnr) ) stop("bootnr has to be a positive integer") else if ( round(bootnr) != bootnr | bootnr <= 0 ) stop("bootnr has to be a positive integer") if ( ! ( metric %in% c( "spearman","pearson","kendall","euclidean","maximum","manhattan","canberra","binary","minkowski") ) ) stop("metric has to be one of the following: spearman, pearson, kendall, euclidean, maximum, manhattan, canberra, binary, minkowski") if ( ! ( SE.method %in% c( "firstSEmax","Tibs2001SEmax","globalSEmax","firstmax","globalmax") ) ) stop("SE.method has to be one of the following: firstSEmax, Tibs2001SEmax, globalSEmax, firstmax, globalmax") if ( ! is.numeric(SE.factor) ) stop("SE.factor has to be a non-negative integer") else if ( SE.factor < 0 ) stop("SE.factor has to be a non-negative integer") if ( ! ( is.numeric(do.gap) | is.logical(do.gap) ) ) stop( "do.gap has to be logical (TRUE/FALSE)" ) if ( ! ( is.numeric(sat) | is.logical(sat) ) ) stop( "sat has to be logical (TRUE/FALSE)" ) if ( ! is.numeric(B.gap) ) stop("B.gap has to be a positive integer") else if ( round(B.gap) != B.gap | B.gap <= 0 ) stop("B.gap has to be a positive integer") if ( ! is.numeric(cln) ) stop("cln has to be a non-negative integer") else if ( round(cln) != cln | cln < 0 ) stop("cln has to be a non-negative integer") if ( ! is.numeric(rseed) ) stop("rseed has to be numeric") if ( !do.gap & !sat & cln == 0 ) stop("cln has to be a positive integer or either do.gap or sat has to be TRUE") if ( ! ( FUNcluster %in% c("kmeans","hclust","kmedoids") ) ) stop("FUNcluster has to be one of the following: kmeans, hclust,kmedoids") object@clusterpar <- list(clustnr=clustnr,bootnr=bootnr,metric=metric,do.gap=do.gap,sat=sat,SE.method=SE.method,SE.factor=SE.factor,B.gap=B.gap,cln=cln,rseed=rseed,FUNcluster=FUNcluster) y <- clustfun(object@fdata,clustnr,bootnr,metric,do.gap,sat,SE.method,SE.factor,B.gap,cln,rseed,FUNcluster) object@cluster <- list(kpart=y$clb$result$partition, jaccard=y$clb$bootmean, gap=y$gpr, clb=y$clb) object@distances <- as.matrix( y$di ) set.seed(111111) object@fcol <- sample(rainbow(max(y$clb$result$partition))) return(object) } ) setGeneric("findoutliers", function(object,outminc=5,outlg=2,probthr=1e-3,thr=2**-(1:40),outdistquant=.95) standardGeneric("findoutliers")) setMethod("findoutliers", signature = "SCseq", definition = function(object,outminc,outlg,probthr,thr,outdistquant) { if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before findoutliers") if ( ! is.numeric(outminc) ) stop("outminc has to be a non-negative integer") else if ( round(outminc) != outminc | outminc < 0 ) stop("outminc has to be a non-negative integer") if ( ! is.numeric(outlg) ) stop("outlg has to be a non-negative integer") else if ( round(outlg) != outlg | outlg < 0 ) stop("outlg has to be a non-negative integer") if ( ! is.numeric(probthr) ) stop("probthr has to be a number between 0 and 1") else if ( probthr < 0 | probthr > 1 ) stop("probthr has to be a number between 0 and 1") if ( ! is.numeric(thr) ) stop("thr hast to be a vector of numbers between 0 and 1") else if ( min(thr) < 0 | max(thr) > 1 ) stop("thr hast to be a vector of numbers between 0 and 1") if ( ! is.numeric(outdistquant) ) stop("outdistquant has to be a number between 0 and 1") else if ( outdistquant < 0 | outdistquant > 1 ) stop("outdistquant has to be a number between 0 and 1") object@outlierpar <- list( outminc=outminc,outlg=outlg,probthr=probthr,thr=thr,outdistquant=outdistquant ) ### calibrate background model m <- log2(apply(object@fdata,1,mean)) v <- log2(apply(object@fdata,1,var)) f <- m > -Inf & v > -Inf m <- m[f] v <- v[f] mm <- -8 repeat{ fit <- lm(v ~ m + I(m^2)) if( coef(fit)[3] >= 0 | mm >= 3){ break } mm <- mm + .5 f <- m > mm m <- m[f] v <- v[f] } object@background <- list() object@background$vfit <- fit object@background$lvar <- function(x,object) 2**(coef(object@background$vfit)[1] + log2(x)*coef(object@background$vfit)[2] + coef(object@background$vfit)[3] * log2(x)**2) object@background$lsize <- function(x,object) x**2/(max(x + 1e-6,object@background$lvar(x,object)) - x) ### identify outliers out <- c() stest <- rep(0,length(thr)) cprobs <- c() for ( n in 1:max(object@cluster$kpart) ){ if ( sum(object@cluster$kpart == n) == 1 ){ cprobs <- append(cprobs,.5); names(cprobs)[length(cprobs)] <- names(object@cluster$kpart)[object@cluster$kpart == n]; next } x <- object@fdata[,object@cluster$kpart == n] x <- x[apply(x,1,max) > outminc,] z <- t( apply(x,1,function(x){ apply( cbind( pnbinom(round(x,0),mu=mean(x),size=object@background$lsize(mean(x),object)) , 1 - pnbinom(round(x,0),mu=mean(x),size=object@background$lsize(mean(x),object)) ),1, min) } ) ) cp <- apply(z,2,function(x){ y <- p.adjust(x,method="BH"); y <- y[order(y,decreasing=FALSE)]; return(y[outlg]);}) f <- cp < probthr cprobs <- append(cprobs,cp) if ( sum(f) > 0 ) out <- append(out,names(x)[f]) for ( j in 1:length(thr) ) stest[j] <- stest[j] + sum( cp < thr[j] ) } object@out <-list(out=out,stest=stest,thr=thr,cprobs=cprobs) ### cluster outliers clp2p.cl <- c() cols <- names(object@fdata) cpart <- object@cluster$kpart di <- as.data.frame(object@distances) for ( i in 1:max(cpart) ) { tcol <- cols[cpart == i] if ( sum(!(tcol %in% out)) > 1 ) clp2p.cl <- append(clp2p.cl,as.vector(t(di[tcol[!(tcol %in% out)],tcol[!(tcol %in% out)]]))) } clp2p.cl <- clp2p.cl[clp2p.cl>0] cadd <- list() if ( length(out) > 0 ){ if (length(out) == 1){ cadd <- list(out) }else{ n <- out m <- as.data.frame(di[out,out]) for ( i in 1:length(out) ){ if ( length(n) > 1 ){ o <- order(apply(cbind(m,1:dim(m)[1]),1,function(x) min(x[1:(length(x)-1)][-x[length(x)]])),decreasing=FALSE) m <- m[o,o] n <- n[o] f <- m[,1] < quantile(clp2p.cl,outdistquant) | m[,1] == min(clp2p.cl) ind <- 1 if ( sum(f) > 1 ) for ( j in 2:sum(f) ) if ( apply(m[f,f][j,c(ind,j)] > quantile(clp2p.cl,outdistquant) ,1,sum) == 0 ) ind <- append(ind,j) cadd[[i]] <- n[f][ind] g <- ! n %in% n[f][ind] n <- n[g] m <- m[g,g] if ( sum(g) == 0 ) break }else if (length(n) == 1){ cadd[[i]] <- n break } } } for ( i in 1:length(cadd) ){ cpart[cols %in% cadd[[i]]] <- max(cpart) + 1 } } ### determine final clusters for ( i in 1:max(cpart) ){ if ( sum(cpart == i) == 0 ) next f <- cols[cpart == i] d <- object@fdata if ( length(f) == 1 ){ cent <- d[,f] }else{ if ( object@clusterpar$FUNcluster == "kmedoids" ){ x <- apply(as.matrix(dist.gen(t(d[,f]),method=object@clusterpar$metric)),2,mean) cent <- d[,f[which(x == min(x))[1]]] }else{ cent <- apply(d[,f],1,mean) } } if ( i == 1 ) dcent <- data.frame(cent) else dcent <- cbind(dcent,cent) if ( i == 1 ) tmp <- data.frame(apply(d,2,dist.gen.pairs,y=cent,method=object@clusterpar$metric)) else tmp <- cbind(tmp,apply(d,2,dist.gen.pairs,y=cent,method=object@clusterpar$metric)) } cpart <- apply(tmp,1,function(x) order(x,decreasing=FALSE)[1]) for ( i in max(cpart):1){if (sum(cpart==i)==0) cpart[cpart>i] <- cpart[cpart>i] - 1 } object@cpart <- cpart set.seed(111111) object@fcol <- sample(rainbow(max(cpart))) return(object) } ) setGeneric("comptsne", function(object,rseed=15555,sammonmap=FALSE,initial_cmd=TRUE,...) standardGeneric("comptsne")) setMethod("comptsne", signature = "SCseq", definition = function(object,rseed,sammonmap,...){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before comptsne") set.seed(rseed) di <- if ( object@clusterpar$FUNcluster == "kmedoids") as.dist(object@distances) else dist.gen(as.matrix(object@distances)) if ( sammonmap ){ object@tsne <- as.data.frame(sammon(di,k=2)$points) }else{ ts <- if ( initial_cmd ) tsne(di,initial_config=cmdscale(di,k=2),...) else tsne(di,k=2,...) object@tsne <- as.data.frame(ts) } return(object) } ) setGeneric("clustdiffgenes", function(object,pvalue=.01) standardGeneric("clustdiffgenes")) setMethod("clustdiffgenes", signature = "SCseq", definition = function(object,pvalue){ if ( length(object@cpart) == 0 ) stop("run findoutliers before clustdiffgenes") if ( ! is.numeric(pvalue) ) stop("pvalue has to be a number between 0 and 1") else if ( pvalue < 0 | pvalue > 1 ) stop("pvalue has to be a number between 0 and 1") cdiff <- list() x <- object@ndata y <- object@expdata[,names(object@ndata)] part <- object@cpart for ( i in 1:max(part) ){ if ( sum(part == i) == 0 ) next m <- if ( sum(part != i) > 1 ) apply(x[,part != i],1,mean) else x[,part != i] n <- if ( sum(part == i) > 1 ) apply(x[,part == i],1,mean) else x[,part == i] no <- if ( sum(part == i) > 1 ) median(apply(y[,part == i],2,sum))/median(apply(x[,part == i],2,sum)) else sum(y[,part == i])/sum(x[,part == i]) m <- m*no n <- n*no pv <- binompval(m/sum(m),sum(n),n) d <- data.frame(mean.ncl=m,mean.cl=n,fc=n/m,pv=pv)[order(pv,decreasing=FALSE),] cdiff[[paste("cl",i,sep=".")]] <- d[d$pv < pvalue,] } return(cdiff) } ) setGeneric("plotsaturation", function(object,disp=FALSE) standardGeneric("plotsaturation")) setMethod("plotsaturation", signature = "SCseq", definition = function(object,disp){ if ( length(object@cluster$gap) == 0 ) stop("run clustexp before plotsaturation") g <- object@cluster$gap$Tab[,1] y <- g[-length(g)] - g[-1] mm <- numeric(length(y)) nn <- numeric(length(y)) for ( i in 1:length(y)){ mm[i] <- mean(y[i:length(y)]) nn[i] <- sqrt(var(y[i:length(y)])) } cln <- max(min(which( y - (mm + nn) < 0 )),1) x <- 1:length(y) if (disp){ x <- 1:length(g) plot(x,g,pch=20,col="grey",xlab="k",ylab="log within cluster dispersion") f <- x == cln points(x[f],g[f],col="blue") }else{ plot(x,y,pch=20,col="grey",xlab="k",ylab="Change in log within cluster dispersion") points(x,mm,col="red",pch=20) plot.err.bars.y(x,mm,nn,col="red") points(x,y,col="grey",pch=20) f <- x == cln points(x[f],y[f],col="blue") } } ) setGeneric("plotsilhouette", function(object) standardGeneric("plotsilhouette")) setMethod("plotsilhouette", signature = "SCseq", definition = function(object){ if ( length(object@cluster$kpart) == 0 ) stop("run clustexp before plotsilhouette") if ( length(unique(object@cluster$kpart)) < 2 ) stop("only a single cluster: no silhouette plot") kpart <- object@cluster$kpart distances <- if ( object@clusterpar$FUNcluster == "kmedoids" ) as.dist(object@distances) else dist.gen(object@distances) si <- silhouette(kpart,distances) plot(si) } ) compmedoids <- function(x,part,metric="pearson"){ m <- c() for ( i in sort(unique(part)) ){ f <- names(x)[part == i] if ( length(f) == 1 ){ m <- append(m,f) }else{ y <- apply(as.matrix(dist.gen(t(x[,f]),method=metric)),2,mean) m <- append(m,f[which(y == min(y))[1]]) } } m } setGeneric("clustheatmap", function(object,final=FALSE,hmethod="single") standardGeneric("clustheatmap")) setMethod("clustheatmap", signature = "SCseq", definition = function(object,final,hmethod){ if ( final & length(object@cpart) == 0 ) stop("run findoutliers before clustheatmap") if ( !final & length(object@cluster$kpart) == 0 ) stop("run clustexp before clustheatmap") x <- object@fdata part <- if ( final ) object@cpart else object@cluster$kpart na <- c() j <- 0 for ( i in 1:max(part) ){ if ( sum(part == i) == 0 ) next j <- j + 1 na <- append(na,i) d <- x[,part == i] if ( sum(part == i) == 1 ) cent <- d else cent <- apply(d,1,mean) if ( j == 1 ) tmp <- data.frame(cent) else tmp <- cbind(tmp,cent) } names(tmp) <- paste("cl",na,sep=".") ld <- if ( object@clusterpar$FUNcluster == "kmedoids" ) dist.gen(t(tmp),method=object@clusterpar$metric) else dist.gen(as.matrix(dist.gen(t(tmp),method=object@clusterpar$metric))) if ( max(part) > 1 ) cclmo <- hclust(ld,method=hmethod)$order else cclmo <- 1 q <- part for ( i in 1:max(part) ){ q[part == na[cclmo[i]]] <- i } part <- q di <- if ( object@clusterpar$FUNcluster == "kmedoids" ) object@distances else as.data.frame( as.matrix( dist.gen(t(object@distances)) ) ) pto <- part[order(part,decreasing=FALSE)] ptn <- c() for ( i in 1:max(pto) ){ pt <- names(pto)[pto == i]; z <- if ( length(pt) == 1 ) pt else pt[hclust(as.dist(t(di[pt,pt])),method=hmethod)$order]; ptn <- append(ptn,z) } col <- object@fcol mi <- min(di,na.rm=TRUE) ma <- max(di,na.rm=TRUE) layout(matrix(data=c(1,3,2,4), nrow=2, ncol=2), widths=c(5,1,5,1), heights=c(5,1,1,1)) ColorRamp <- colorRampPalette(brewer.pal(n = 7,name = "RdYlBu"))(100) ColorLevels <- seq(mi, ma, length=length(ColorRamp)) if ( mi == ma ){ ColorLevels <- seq(0.99*mi, 1.01*ma, length=length(ColorRamp)) } par(mar = c(3,5,2.5,2)) image(as.matrix(di[ptn,ptn]),col=ColorRamp,axes=FALSE) abline(0,1) box() tmp <- c() for ( u in 1:max(part) ){ ol <- (0:(length(part) - 1)/(length(part) - 1))[ptn %in% names(x)[part == u]] points(rep(0,length(ol)),ol,col=col[cclmo[u]],pch=15,cex=.75) points(ol,rep(0,length(ol)),col=col[cclmo[u]],pch=15,cex=.75) tmp <- append(tmp,mean(ol)) } axis(1,at=tmp,lab=cclmo) axis(2,at=tmp,lab=cclmo) par(mar = c(3,2.5,2.5,2)) image(1, ColorLevels, matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1), col=ColorRamp, xlab="",ylab="", xaxt="n") layout(1) return(cclmo) } ) ## class definition Ltree <- setClass("Ltree", slots = c(sc = "SCseq", ldata = "list", entropy = "vector", trproj = "list", par = "list", prback = "data.frame", prbacka = "data.frame", ltcoord = "matrix", prtree = "list", sigcell = "vector", cdata = "list" )) setValidity("Ltree", function(object) { msg <- NULL if ( class(object@sc)[1] != "SCseq" ){ msg <- c(msg, "input data must be of class SCseq") } if (is.null(msg)) TRUE else msg } ) setMethod("initialize", signature = "Ltree", definition = function(.Object, sc ){ .Object@sc <- sc validObject(.Object) return(.Object) } ) setGeneric("compentropy", function(object) standardGeneric("compentropy")) setMethod("compentropy", signature = "Ltree", definition = function(object){ probs <- t(t(object@sc@ndata)/apply(object@sc@ndata,2,sum)) object@entropy <- -apply(probs*log(probs)/log(nrow(object@sc@ndata)),2,sum) return(object) } ) compproj <- function(pdiloc,lploc,cnloc,mloc,d=NULL){ pd <- data.frame(pdiloc) k <- paste("X",sort(rep(1:nrow(pdiloc),length(mloc))),sep="") pd$k <- paste("X",1:nrow(pdiloc),sep="") pd <- merge(data.frame(k=k),pd,by="k") if ( is.null(d) ){ cnv <- t(matrix(rep(t(cnloc),nrow(pdiloc)),nrow=ncol(pdiloc))) pdcl <- paste("X",lploc[as.numeric(sub("X","",pd$k))],sep="") rownames(cnloc) <- paste("X",mloc,sep="") pdcn <- cnloc[pdcl,] v <- cnv - pdcn }else{ v <- d$v pdcn <- d$pdcn } w <- pd[,names(pd) != "k"] - pdcn h <- apply(cbind(v,w),1,function(x){ x1 <- x[1:(length(x)/2)]; x2 <- x[(length(x)/2 + 1):length(x)]; x1s <- sqrt(sum(x1**2)); x2s <- sqrt(sum(x2**2)); y <- sum(x1*x2)/x1s/x2s; return( if (x1s == 0 | x2s == 0 ) NA else y ) }) rma <- as.data.frame(matrix(h,ncol=nrow(pdiloc))) names(rma) <- unique(pd$k) pdclu <- lploc[as.numeric(sub("X","",names(rma)))] pdclp <- apply(t(rma),1,function(x) if (sum(!is.na(x)) == 0 ) NA else mloc[which(abs(x) == max(abs(x),na.rm=TRUE))[1]]) pdclh <- apply(t(rma),1,function(x) if (sum(!is.na(x)) == 0 ) NA else x[which(abs(x) == max(abs(x),na.rm=TRUE))[1]]) pdcln <- names(lploc)[as.numeric(sub("X","",names(rma)))] names(rma) <- pdcln rownames(rma) <- paste("X",mloc,sep="") res <- data.frame(o=pdclu,l=pdclp,h=pdclh) rownames(res) <- pdcln return(list(res=res[names(lploc),],rma=as.data.frame(t(rma[,names(lploc)])),d=list(v=v,pdcn=pdcn))) } pdishuffle <- function(pdi,lp,cn,m,all=FALSE){ if ( all ){ d <- as.data.frame(pdi) y <- t(apply(pdi,1,function(x) runif(length(x),min=min(x),max=max(x)))) names(y) <- names(d) rownames(y) <- rownames(d) return(y) }else{ fl <- TRUE for ( i in unique(lp)){ if ( sum(lp == i) > 1 ){ y <-data.frame( t(apply(as.data.frame(pdi[,lp == i]),1,sample)) ) }else{ y <- as.data.frame(pdi[,lp == i]) } names(y) <- names(lp)[lp == i] rownames(y) <- names(lp) z <- if (fl) y else cbind(z,y) fl <- FALSE } z <- t(z[,names(lp)]) return(z) } } setGeneric("projcells", function(object,cthr=0,nmode=FALSE) standardGeneric("projcells")) setMethod("projcells", signature = "Ltree", definition = function(object,cthr,nmode){ if ( ! is.numeric(cthr) ) stop( "cthr has to be a non-negative number" ) else if ( cthr < 0 ) stop( "cthr has to be a non-negative number" ) if ( ! length(object@sc@cpart == 0) ) stop( "please run findoutliers on the SCseq input object before initializing Ltree" ) if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") object@par$cthr <- cthr object@par$nmode <- nmode lp <- object@sc@cpart ld <- object@sc@distances n <- aggregate(rep(1,length(lp)),list(lp),sum) n <- as.vector(n[order(n[,1],decreasing=FALSE),-1]) m <- (1:length(n))[n>cthr] f <- lp %in% m lp <- lp[f] ld <- ld[f,f] pdil <- sc@tsne[f,] cnl <- aggregate(pdil,by=list(lp),median) cnl <- cnl[order(cnl[,1],decreasing=FALSE),-1] pdi <- suppressWarnings( cmdscale(as.matrix(ld),k=ncol(ld)-1) ) cn <- as.data.frame(pdi[compmedoids(sc@fdata[,names(lp)],lp),]) rownames(cn) <- 1:nrow(cn) x <- compproj(pdi,lp,cn,m) res <- x$res if ( nmode ){ rma <- x$rma z <- paste("X",t(as.vector(apply(cbind(lp,ld),1,function(x){ f <- lp != x[1]; lp[f][which(x[-1][f] == min(x[-1][f]))[1]] }))),sep="") k <- apply(cbind(z,rma),1,function(x) (x[-1])[names(rma) == x[1]]) rn <- res rn$l <- as.numeric(sub("X","",z)) rn$h <- as.numeric(k) res <- rn x$res <- res } object@ldata <- list(lp=lp,ld=ld,m=m,pdi=pdi,pdil=pdil,cn=cn,cnl=cnl) object@trproj <- x return(object) } ) setGeneric("projback", function(object,pdishuf=2000,nmode=FALSE,rseed=17000) standardGeneric("projback")) setMethod("projback", signature = "Ltree", definition = function(object,pdishuf,nmode,rseed){ if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( ! is.numeric(pdishuf) ) stop( "pdishuf has to be a non-negative integer number" ) else if ( round(pdishuf) != pdishuf | pdishuf < 0 ) stop( "pdishuf has to be a non-negative integer number" ) if ( length(object@trproj) == 0 ) stop("run projcells before projback") object@par$pdishuf <- pdishuf object@par$rseed <- rseed if ( ! nmode ){ set.seed(rseed) for ( i in 1:pdishuf ){ cat("pdishuffle:",i,"\n") x <- compproj(pdishuffle(object@ldata$pdi,object@ldata$lp,object@ldata$cn,object@ldata$m,all=TRUE),object@ldata$lp,object@ldata$cn,object@ldata$m,d=object@trproj$d)$res y <- if ( i == 1 ) t(x) else cbind(y,t(x)) } ##important object@prback <- as.data.frame(t(y)) x <- object@prback x$n <- as.vector(t(matrix(rep(1:(nrow(x)/nrow(object@ldata$pdi)),nrow(object@ldata$pdi)),ncol=nrow(object@ldata$pdi)))) object@prbacka <- aggregate(data.frame(count=rep(1,nrow(x))),by=list(n=x$n,o=x$o,l=x$l),sum) } return( object ) } ) setGeneric("lineagetree", function(object,pthr=0.01,nmode=FALSE) standardGeneric("lineagetree")) setMethod("lineagetree", signature = "Ltree", definition = function(object,pthr,nmode){ if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( length(object@trproj) == 0 ) stop("run projcells before lineagetree") if ( max(dim(object@prback)) == 0 & ! nmode ) stop("run projback before lineagetree") if ( ! is.numeric(pthr) ) stop( "pthr has to be a non-negative number" ) else if ( pthr < 0 ) stop( "pthr has to be a non-negative number" ) object@par$pthr <- pthr cnl <- object@ldata$cnl pdil <- object@ldata$pdil cn <- object@ldata$cn pdi <- object@ldata$pdi m <- object@ldata$m lp <- object@ldata$lp res <- object@trproj$res rma <- object@trproj$rma prback <- object@prback cm <- as.matrix(dist(cnl))*0 linl <- list() linn <- list() for ( i in 1:length(m) ){ for ( j in i:length(m) ){ linl[[paste(m[i],m[j],sep=".")]] <- c() linn[[paste(m[i],m[j],sep=".")]] <- c() } } sigcell <- c() for ( i in 1:nrow(res) ){ a <- which( m == res$o[i]) if ( sum( lp == m[a] ) == 1 ){ k <- t(cnl)[,a] k <- NA sigcell <- append(sigcell, FALSE) }else{ b <- which(m == res$l[i] ) h <- res$h[i] if ( nmode ){ sigcell <- append(sigcell, FALSE) }else{ f <- prback$o == m[a] & prback$l == m[b] if ( sum(f) > 0 ){ ql <- quantile(prback[f,"h"],pthr,na.rm=TRUE) qh <- quantile(prback[f,"h"],1 - pthr,na.rm=TRUE) }else{ ql <- 0 qh <- 0 } sigcell <- if (is.na(h) ) append(sigcell, NA) else if ( h > qh | h < min(0,ql) ) append(sigcell, TRUE) else append(sigcell, FALSE) } if ( !is.na(res$h[i]) ){ w <- t(pdil)[,i] - t(cnl)[,a] v <- t(cnl)[,b] - t(cnl)[,a] wo <- t(pdi)[,i] - t(cn)[,a] vo <- t(cn)[,b] - t(cn)[,a] df <-( h*sqrt(sum(wo*wo)) )/sqrt(sum(vo*vo))*v k <- df + t(cnl)[,a] cm[a,b] <- cm[a,b] + 1 so <- m[sort(c(a,b))] dfl <- sign(h)*sqrt( sum( df*df ) )/sqrt(sum(v*v)) if ( a > b ) dfl <- 1 - dfl linn[[paste(so[1],so[2],sep=".")]] <- append( linn[[paste(so[1],so[2],sep=".")]], rownames(pdi)[i] ) linl[[paste(so[1],so[2],sep=".")]] <- append( linl[[paste(so[1],so[2],sep=".")]], dfl ) }else{ k <- t(cnl)[,a] for ( j in unique(lp[lp != m[a]]) ){ b <- which(j == m) so <- m[sort(c(a,b))] dfl <- 0 if ( a > b ) dfl <- 1 - dfl linn[[paste(so[1],so[2],sep=".")]] <- append( linn[[paste(so[1],so[2],sep=".")]], rownames(pdi)[i] ) linl[[paste(so[1],so[2],sep=".")]] <- append( linl[[paste(so[1],so[2],sep=".")]], dfl ) } } } lt <- if ( i == 1 ) data.frame(k) else cbind(lt,k) } lt <- t(lt) cm <- as.data.frame(cm) names(cm) <- paste("cl",m,sep=".") rownames(cm) <- paste("cl",m,sep=".") lt <- as.data.frame(lt) rownames(lt) <- rownames(res) object@ltcoord <- as.matrix(lt) object@prtree <- list(n=linn,l=linl) object@cdata$counts <- cm names(sigcell) <- rownames(res) object@sigcell <- sigcell return( object ) } ) setGeneric("comppvalue", function(object,pethr=0.01,nmode=FALSE) standardGeneric("comppvalue")) setMethod("comppvalue", signature = "Ltree", definition = function(object,pethr,nmode){ if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( length(object@prtree) == 0 ) stop("run lineagetree before comppvalue") if ( ! is.numeric(pethr) ) stop( "pethr has to be a non-negative number" ) else if ( pethr < 0 ) stop( "pethr has to be a non-negative number" ) object@par$pethr <- pethr cm <- object@cdata$counts cmpv <- cm*NA cmpvd <- cm*NA cmbr <- cm*NA cmpvn <- cm*NA cmpvnd <- cm*NA cmfr <- cm/apply(cm,1,sum) if ( nmode ){ N <- apply(cm,1,sum) + 1 N0 <- sum(N) - N n0 <- t(matrix(rep(N,length(N)),ncol=length(N))) p <- n0/N0 n <- cm k <- cbind(N,p,n) cmpv <- apply(k,1,function(x){N <- x[1]; p <- x[2:( ncol(cm) + 1 )]; n <- x[( ncol(cm) + 2 ):( 2*ncol(cm) + 1)]; apply(cbind(n,p),1,function(x,N) binom.test(x[1],N,min(1,x[2]),alternative="g")$p.value,N=N)}) cmpvd <- apply(k,1,function(x){N <- x[1]; p <- x[2:( ncol(cm) + 1 )]; n <- x[( ncol(cm) + 2 ):( 2*ncol(cm) + 1)]; apply(cbind(n,p),1,function(x,N) binom.test(x[1],N,min(1,x[2]),alternative="l")$p.value,N=N)}) cmpvn <- cmpv cmpvnd <- cmpvd cmbr <- as.data.frame(n0/N0*N) names(cmbr) <- names(cm) rownames(cmbr) <- rownames(cm) }else{ for ( i in 1:nrow(cm) ){ for ( j in 1:ncol(cm) ){ f <- object@prbacka$o == object@ldata$m[i] & object@prbacka$l == object@ldata$m[j] x <- object@prbacka$count[f] if ( sum(f) < object@par$pdishuf ) x <- append(x,rep(0, object@par$pdishuf - sum(f))) cmbr[i,j] <- if ( sum(f) > 0 ) mean(x) else 0 cmpv[i,j] <- if ( quantile(x,1 - pethr) < cm[i,j] ) 0 else 0.5 cmpvd[i,j] <- if ( quantile(x,pethr) > cm[i,j] ) 0 else 0.5 cmpvn[i,j] <- sum( x >= cm[i,j])/length(x) cmpvnd[i,j] <- sum( x <= cm[i,j])/length(x) } } } diag(cmpv) <- .5 diag(cmpvd) <- .5 diag(cmpvn) <- NA diag(cmpvnd) <- NA object@cdata$counts.br <- cmbr object@cdata$pv.e <- cmpv object@cdata$pv.d <- cmpvd object@cdata$pvn.e <- cmpvn object@cdata$pvn.d <- cmpvnd m <- object@ldata$m linl <- object@prtree$l ls <- as.data.frame(matrix(rep(NA,length(m)**2),ncol=length(m))) names(ls) <- rownames(ls) <- paste("cl",m,sep=".") for ( i in 1:( length(m) - 1 )){ for ( j in (i + 1):length(m) ){ na <- paste(m[i],m[j],sep=".") if ( na %in% names(linl) & min(cmpv[i,j],cmpv[j,i],na.rm=TRUE) < pethr ){ y <- sort(linl[[na]]) nn <- ( 1 - max(y[-1] - y[-length(y)]) ) }else{ nn <- 0 } ls[i,j] <- nn } } object@cdata$linkscore <- ls return(object) } ) setGeneric("plotlinkpv", function(object) standardGeneric("plotlinkpv")) setMethod("plotlinkpv", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotlinkpv") pheatmap(-log2(object@cdata$pvn.e + 1/object@par$pdishuf/2)) } ) setGeneric("plotlinkscore", function(object) standardGeneric("plotlinkscore")) setMethod("plotlinkscore", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotlinkscore") pheatmap(object@cdata$linkscore,cluster_rows=FALSE,cluster_cols=FALSE) } ) setGeneric("plotmapprojections", function(object) standardGeneric("plotmapprojections")) setMethod("plotmapprojections", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmapprojections") cent <- object@sc@fdata[,compmedoids(object@sc@fdata,object@sc@cpart)] dc <- as.data.frame(1 - cor(cent)) names(dc) <- sort(unique(object@sc@cpart)) rownames(dc) <- sort(unique(object@sc@cpart)) trl <- spantree(dc[object@ldata$m,object@ldata$m]) u <- object@ltcoord[,1] v <- object@ltcoord[,2] cnl <- object@ldata$cnl plot(u,v,cex=1.5,col="grey",pch=20,xlab="Dim 1",ylab="Dim 2") for ( i in unique(object@ldata$lp) ){ f <- object@ldata$lp == i; text(u[f],v[f],i,cex=.75,font=4,col=object@sc@fcol[i]) } points(cnl[,1],cnl[,2]) text(cnl[,1],cnl[,2],object@ldata$m,cex=2) for ( i in 1:length(trl$kid) ){ lines(c(cnl[i+1,1],cnl[trl$kid[i],1]),c(cnl[i+1,2],cnl[trl$kid[i],2]),col="black") } } ) setGeneric("plotmap", function(object) standardGeneric("plotmap")) setMethod("plotmap", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmap") cent <- object@sc@fdata[,compmedoids(object@sc@fdata,object@sc@cpart)] dc <- as.data.frame(1 - cor(cent)) names(dc) <- sort(unique(object@sc@cpart)) rownames(dc) <- sort(unique(object@sc@cpart)) trl <- spantree(dc[object@ldata$m,object@ldata$m]) u <- object@ldata$pdil[,1] v <- object@ldata$pdil[,2] cnl <- object@ldata$cnl plot(u,v,cex=1.5,col="grey",pch=20,xlab="Dim 1",ylab="Dim 2") for ( i in unique(object@ldata$lp) ){ f <- object@ldata$lp == i; text(u[f],v[f],i,cex=.75,font=4,col=object@sc@fcol[i]) } points(cnl[,1],cnl[,2]) text(cnl[,1],cnl[,2],object@ldata$m,cex=2) for ( i in 1:length(trl$kid) ){ lines(c(cnl[i+1,1],cnl[trl$kid[i],1]),c(cnl[i+1,2],cnl[trl$kid[i],2]),col="black") } } ) setGeneric("plottree", function(object,showCells=TRUE,nmode=FALSE,scthr=0) standardGeneric("plottree")) setMethod("plottree", signature = "Ltree", definition = function(object,showCells,nmode,scthr){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmap") if ( !is.numeric(nmode) & !is.logical(nmode) ) stop("argument nmode has to be logical (TRUE/FALSE)") if ( !is.numeric(showCells) & !is.logical(showCells) ) stop("argument showCells has to be logical (TRUE/FALSE)") if ( ! is.numeric(scthr) ) stop( "scthr has to be a non-negative number" ) else if ( scthr < 0 | scthr > 1 ) stop( "scthr has to be a number between 0 and 1" ) ramp <- colorRamp(c("darkgreen", "yellow", "brown")) mcol <- rgb( ramp(seq(0, 1, length = 101)), max = 255) co <- object@cdata fc <- (co$counts/( co$counts.br + .5))*(co$pv.e < object@par$pethr) fc <- fc*(fc > t(fc)) + t(fc)*(t(fc) >= fc) fc <- log2(fc + (fc == 0)) k <- -log10(sort(unique(as.vector(t(co$pvn.e))[as.vector(t(co$pv.e))<object@par$pethr])) + 1/object@par$pdishuf) if (length(k) == 1) k <- c(k - k/100,k) mlpv <- -log10(co$pvn.e + 1/object@par$pdishuf) diag(mlpv) <- min(mlpv,na.rm=TRUE) dcc <- t(apply(round(100*(mlpv - min(k))/(max(k) - min(k)),0) + 1,1,function(x){y <- c(); for ( n in x ) y <- append(y,if ( n < 1 ) NA else mcol[n]); y })) cx <- c() cy <- c() va <- c() m <- object@ldata$m for ( i in 1:( length(m) - 1 ) ){ for ( j in ( i + 1 ):length(m) ){ if ( min(co$pv.e[i,j],co$pv.e[j,i],na.rm=TRUE) < object@par$pethr ){ if ( mlpv[i,j] > mlpv[j,i] ){ va <- append(va,dcc[i,j]) }else{ va <- append(va,dcc[j,i]) } cx <- append(cx,i) cy <- append(cy,j) } } } cnl <- object@ldata$cnl u <- object@ltcoord[,1] v <- object@ltcoord[,2] layout( cbind(c(1, 1), c(2, 3)),widths=c(5,1,1),height=c(5,5,1)) par(mar = c(12,5,1,1)) if ( showCells ){ plot(u,v,cex=1.5,col="grey",pch=20,xlab="Dim 1",ylab="Dim 2") if ( !nmode ) points(u[object@sigcell],v[object@sigcell],col="black") }else{ plot(u,v,cex=0,xlab="Dim 1",ylab="Dim 2") } if ( length(va) > 0 ){ f <- order(va,decreasing=TRUE) for ( i in 1:length(va) ){ if ( object@cdata$linkscore[cx[i],cy[i]] > scthr ){ if ( showCells ){ lines(cnl[c(cx[i],cy[i]),1],cnl[c(cx[i],cy[i]),2],col=va[i],lwd=2) }else{ ##nn <- min(10,fc[cx[i],cy[i]]) lines(cnl[c(cx[i],cy[i]),1],cnl[c(cx[i],cy[i]),2],col=va[i],lwd=5*object@cdata$linkscore[cx[i],cy[i]]) } } } } en <- aggregate(object@entropy,list(object@sc@cpart),median) en <- en[en$Group.1 %in% m,] mi <- min(en[,2],na.rm=TRUE) ma <- max(en[,2],na.rm=TRUE) w <- round((en[,2] - mi)/(ma - mi)*99 + 1,0) ramp <- colorRamp(c("red","orange", "pink","purple", "blue")) ColorRamp <- rgb( ramp(seq(0, 1, length = 101)), max = 255) ColorLevels <- seq(mi, ma, length=length(ColorRamp)) if ( mi == ma ){ ColorLevels <- seq(0.99*mi, 1.01*ma, length=length(ColorRamp)) } for ( i in m ){ f <- en[,1] == m points(cnl[f,1],cnl[f,2],cex=5,col=ColorRamp[w[f]],pch=20) } text(cnl[,1],cnl[,2],m,cex=1.25,font=4,col="white") par(mar = c(5, 4, 1, 2)) image(1, ColorLevels, matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1), col=ColorRamp, xlab="",ylab="", xaxt="n") coll <- seq(min(k), max(k), length=length(mcol)) image(1, coll, matrix(data=coll, ncol=length(mcol),nrow=1), col=mcol, xlab="",ylab="", xaxt="n") layout(1) } ) setGeneric("plotdistanceratio", function(object) standardGeneric("plotdistanceratio")) setMethod("plotdistanceratio", signature = "Ltree", definition = function(object){ if ( length(object@ldata) <= 0 ) stop("run projcells before plotdistanceratio") l <- as.matrix(dist(object@ldata$pdi)) z <- (l/object@ldata$ld) hist(log2(z),breaks=100,xlab=" log2 emb. distance/distance",main="") } ) setGeneric("getproj", function(object,i) standardGeneric("getproj")) setMethod("getproj", signature = "Ltree", definition = function(object,i){ if ( length(object@ldata) <= 0 ) stop("run projcells before plotdistanceratio") if ( ! i %in% object@ldata$m ) stop(paste("argument i has to be one of",paste(object@ldata$m,collapse=","))) x <- object@trproj$rma[names(object@ldata$lp)[object@ldata$lp == i],] x <- x[,names(x) != paste("X",i,sep="")] f <- !is.na(x[,1]) x <- x[f,] if ( nrow(x) > 1 ){ y <- x y <- as.data.frame(t(apply(y,1,function(x) (x - mean(x))/sqrt(var(x))))) } names(x) = sub("X","cl.",names(x)) names(y) = sub("X","cl.",names(y)) return(list(pr=x,prz=y)) } ) setGeneric("projenrichment", function(object) standardGeneric("projenrichment")) setMethod("projenrichment", signature = "Ltree", definition = function(object){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotmap") ze <- ( object@cdata$pv.e < object@par$pethr | object@cdata$pv.d < object@par$pethr) * (object@cdata$counts + .1)/( object@cdata$counts.br + .1 ) pheatmap(log2(ze + ( ze == 0 ) ),cluster_rows=FALSE,cluster_cols=FALSE) } ) setGeneric("compscore", function(object,nn=1) standardGeneric("compscore")) setMethod("compscore", signature = "Ltree", definition = function(object,nn){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before compscore") if ( ! is.numeric(nn) ) stop( "nn has to be a non-negative integer number" ) else if ( round(nn) != nn | nn < 0 ) stop( "nn has to be a non-negative integer number" ) x <- object@cdata$counts*(object@cdata$pv.e < object@par$pethr)>0 y <- x | t(x) if ( max(y) > 0 ){ z <- apply(y,1,sum) nl <- list() n <- list() for ( i in 1:nn ){ if ( i == 1 ){ n[[i]] <- as.list(apply(y,1,function(x) grep(TRUE,x))) nl <- data.frame( apply(y,1,sum) ) } if ( i > 1 ){ v <- rep(0,nrow(nl)) n[[i]] <- list() for ( j in 1:length(n[[i-1]]) ){ cl <- n[[i-1]][[j]] if ( length(cl) == 0 ){ n[[i]][[paste("d",j,sep="")]] <- NA v[j] <- 0 }else{ k <- if ( length(cl) > 1 ) apply(y[cl,],2,sum) > 0 else if ( length(cl) == 1 ) y[cl,] n[[i]][[paste("d",j,sep="")]] <- sort(unique(c(cl,grep(TRUE,k)))) v[j] <- length(n[[i]][[paste("d",j,sep="")]]) } } names(n[[i]]) <- names(z) nl <- cbind(nl,v) } } x <- nl[,i] names(x) <- rownames(nl) }else{ x <- rep(0,length(object@ldata$m)) names(x) <- paste("cl",object@ldata$m,sep=".") } v <- aggregate(object@entropy,list(object@sc@cpart),median) v <- v[v$Group.1 %in% object@ldata$m,] w <- as.vector(v[,-1]) names(w) <- paste("cl.",v$Group.1,sep="") w <- w - min(w) return(list(links=x,entropy=w,StemIDscore=x*w)) } ) setGeneric("plotscore", function(object,nn=1) standardGeneric("plotscore")) setMethod("plotscore", signature = "Ltree", definition = function(object,nn){ if ( length(object@cdata) <= 0 ) stop("run comppvalue before plotscore") x <- compscore(object,nn) layout(1:3) barplot(x$links,names.arg=sub("cl\\.","",object@ldata$m),xlab="Cluster",ylab="Number of links",cex.names=1) barplot(x$entropy,names.arg=sub("cl\\.","",object@ldata$m),xlab="Cluster",ylab="Delta-Entropy",cex.names=1) barplot(x$StemIDscore,names.arg=sub("cl\\.","",object@ldata$m),xlab="Cluster",ylab="Number of links * Delta-Entropy",cex.names=1) layout(1) } ) setGeneric("branchcells", function(object,br) standardGeneric("branchcells")) setMethod("branchcells", signature = "Ltree", definition = function(object,br){ if ( length(object@ldata) <= 0 ) stop("run projcells before branchcells") msg <- paste("br needs to be list of length two containing two branches, where each has to be one of", paste(names(object@prtree$n),collapse=",")) if ( !is.list(br) ) stop(msg) else if ( length(br) != 2 ) stop(msg) else if ( ! br[[1]] %in% names(object@prtree$n) | ! br[[2]] %in% names(object@prtree$n) ) stop(msg) n <- list() scl <- object@sc k <- c() cl <- intersect( as.numeric(strsplit(br[[1]],"\\.")[[1]]), as.numeric(strsplit(br[[2]],"\\.")[[1]])) if ( length(cl) == 0 ) stop("the two branches in br need to have one cluster in common.") for ( i in 1:length(br) ){ f <- object@sc@cpart[ object@prtree$n[[br[[i]]]] ] %in% cl if ( sum(f) > 0 ){ n[[i]] <- names(object@sc@cpart[ object@prtree$n[[br[[i]]]] ])[f] k <- append(k, max( scl@cpart ) + 1) scl@cpart[n[[i]]] <- max( scl@cpart ) + 1 }else{ stop(paste("no cells on branch",br[[i]],"fall into clusters",cl)) } } set.seed(111111) scl@fcol <- sample(rainbow(max(scl@cpart))) z <- diffgenes(scl,k[1],k[2]) return( list(n=n,scl=scl,k=k,diffgenes=z) ) } )
set.seed(123) fair_50rolls <- roll(fair_die, times = 50) fair50_sum <- summary(fair_50rolls) fair50_sum #' @export plot.roll <-function(x){ s<-summary(x) barplot((s$freqs)[,3], main = 'Relative Frequencies in a series of 50 rolls', xlab = 'sides of device', ylab = 'relative frequencies', names.arg = c("1", "2", "3","4","5","6") ) } #plot(fair_50rolls) plot.roll(fair_50rolls)
/hw-stat133/roller/R/plot.rolls.R
no_license
zhenjiasun/demo-repo
R
false
false
430
r
set.seed(123) fair_50rolls <- roll(fair_die, times = 50) fair50_sum <- summary(fair_50rolls) fair50_sum #' @export plot.roll <-function(x){ s<-summary(x) barplot((s$freqs)[,3], main = 'Relative Frequencies in a series of 50 rolls', xlab = 'sides of device', ylab = 'relative frequencies', names.arg = c("1", "2", "3","4","5","6") ) } #plot(fair_50rolls) plot.roll(fair_50rolls)
doorbusters.names.in.csv <- c("id", "door buster", "in stock", "is online", "launch date", "has image", "status code", "status", "Has Price", "Price") doorbusters.names <- c("id", "door.buster", "in.stock", "is.online", "launch.date", "has.image", "status.code", "status", "Has.Price", "Price") test.read.doorbuster.csv_read.proper.format <- function() { ############################################# ############## GIVEN #################### ############################################# test.csv <- "temp.csv" #create the test data to write to a csv# row.1 <- c("4", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.2 <- c("5", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") test.data <- as.data.frame(rbind(row.1, row.2)) names(test.data) <- doorbusters.names.in.csv write.csv(test.data, file = test.csv, row.names = FALSE) ############################################# ############### WHEN #################### ############################################# #sut = system under test# sut <- read.doorbuster.csv(csv.name = test.csv) ############################################# ############### THEN #################### ############################################# checkEquals(2, nrow(sut)) # verify the number of rows checkTrue(setequal(row.1, as.character(sut[1,]))) # verify row 1 checkTrue(setequal(row.2, as.character(sut[2,]))) # verify row 2 checkTrue(setequal(doorbusters.names, names(sut))) # verify the column names #cleanup# file.remove(test.csv) rm(test.data) rm(sut) } # test that the read.all.doorbuster.files() function reads both csv files# test.read.all.doorbuster.files_exactly.two <- function() { ############################################# ############## GIVEN #################### ############################################# doorbusters1.csv <- "./tests/test_data/doorbuster1.csv" doorbusters2.csv <- "./tests/test_data/doorbuster2.csv" # CREATE THE TEST DATA # row.1 <- c("4", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.2 <- c("5", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.3 <- c("6", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.4 <- c("7", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") file1.data <- as.data.frame(rbind(row.1, row.2)) file2.data <- as.data.frame(rbind(row.3, row.4)) names(file1.data) <- doorbusters.names.in.csv names(file2.data) <- doorbusters.names.in.csv write.csv(file1.data, file=doorbusters1.csv, row.names=FALSE) write.csv(file2.data, file=doorbusters2.csv, row.names=FALSE) ############################################# ############### WHEN #################### ############################################# sut <- read.all.doorbuster.files("./tests/test_data/") ############################################# ############### THEN #################### ############################################# checkEquals(4, nrow(sut)) #verify the number of rows checkTrue(setequal(row.1, as.character(sut[1,]))) # verify row 1 checkTrue(setequal(row.2, as.character(sut[2,]))) # verify row 2 checkTrue(setequal(row.3, as.character(sut[3,]))) # verify row 3 checkTrue(setequal(row.4, as.character(sut[4,]))) # verify row 4 checkTrue(setequal(doorbusters.names, names(sut))) # verify the column names # CLEANUP # file.remove(doorbusters1.csv) file.remove(doorbusters2.csv) rm(file1.data) rm(file2.data) rm(sut) } # test that the read.all.doorbuster.files() function reads ONLY the two csv files# test.read.all.doorbuster.files_three.files <- function() { ############################################# ############## GIVEN #################### ############################################# doorbusters1.csv <- "./tests/test_data/doorbuster1.csv" doorbusters2.csv <- "./tests/test_data/doorbuster2.csv" doorbusters3.csv <- "./tests/test_data/doorbuster3.csv" # CREATE THE TEST DATA # row.1 <- c("4", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.2 <- c("5", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.3 <- c("6", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.4 <- c("7", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.5 <- c("8", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.6 <- c("9", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") file1.data <- as.data.frame(rbind(row.1, row.2)) file2.data <- as.data.frame(rbind(row.3, row.4)) file3.data <- as.data.frame(rbind(row.5, row.6)) names(file1.data) <- doorbusters.names.in.csv names(file2.data) <- doorbusters.names.in.csv names(file3.data) <- doorbusters.names.in.csv write.csv(file1.data, file=doorbusters1.csv, row.names=FALSE) write.csv(file2.data, file=doorbusters2.csv, row.names=FALSE) write.csv(file3.data, file=doorbusters3.csv, row.names=FALSE) ############################################# ############### WHEN #################### ############################################# sut <- read.all.doorbuster.files("./tests/test_data/") ############################################# ############### THEN #################### ############################################# checkEquals(4, dim(sut)[1]) #verify the number of rows checkTrue(setequal(row.1, as.character(sut[1,]))) # verify row 1 checkTrue(setequal(row.2, as.character(sut[2,]))) # verify row 2 checkTrue(setequal(row.3, as.character(sut[3,]))) # verify row 3 checkTrue(setequal(row.4, as.character(sut[4,]))) # verify row 4 checkTrue(setequal(doorbusters.names, names(sut))) # verify the column names # CLEANUP # file.remove(doorbusters1.csv) file.remove(doorbusters2.csv) file.remove(doorbusters3.csv) rm(file1.data) rm(file2.data) rm(file3.data) rm(sut) }
/tests/doorbusters_tests_data_acquisition_readcsv.R
no_license
donaldsawyer/test-driven-data-wrangling-r
R
false
false
6,038
r
doorbusters.names.in.csv <- c("id", "door buster", "in stock", "is online", "launch date", "has image", "status code", "status", "Has Price", "Price") doorbusters.names <- c("id", "door.buster", "in.stock", "is.online", "launch.date", "has.image", "status.code", "status", "Has.Price", "Price") test.read.doorbuster.csv_read.proper.format <- function() { ############################################# ############## GIVEN #################### ############################################# test.csv <- "temp.csv" #create the test data to write to a csv# row.1 <- c("4", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.2 <- c("5", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") test.data <- as.data.frame(rbind(row.1, row.2)) names(test.data) <- doorbusters.names.in.csv write.csv(test.data, file = test.csv, row.names = FALSE) ############################################# ############### WHEN #################### ############################################# #sut = system under test# sut <- read.doorbuster.csv(csv.name = test.csv) ############################################# ############### THEN #################### ############################################# checkEquals(2, nrow(sut)) # verify the number of rows checkTrue(setequal(row.1, as.character(sut[1,]))) # verify row 1 checkTrue(setequal(row.2, as.character(sut[2,]))) # verify row 2 checkTrue(setequal(doorbusters.names, names(sut))) # verify the column names #cleanup# file.remove(test.csv) rm(test.data) rm(sut) } # test that the read.all.doorbuster.files() function reads both csv files# test.read.all.doorbuster.files_exactly.two <- function() { ############################################# ############## GIVEN #################### ############################################# doorbusters1.csv <- "./tests/test_data/doorbuster1.csv" doorbusters2.csv <- "./tests/test_data/doorbuster2.csv" # CREATE THE TEST DATA # row.1 <- c("4", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.2 <- c("5", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.3 <- c("6", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.4 <- c("7", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") file1.data <- as.data.frame(rbind(row.1, row.2)) file2.data <- as.data.frame(rbind(row.3, row.4)) names(file1.data) <- doorbusters.names.in.csv names(file2.data) <- doorbusters.names.in.csv write.csv(file1.data, file=doorbusters1.csv, row.names=FALSE) write.csv(file2.data, file=doorbusters2.csv, row.names=FALSE) ############################################# ############### WHEN #################### ############################################# sut <- read.all.doorbuster.files("./tests/test_data/") ############################################# ############### THEN #################### ############################################# checkEquals(4, nrow(sut)) #verify the number of rows checkTrue(setequal(row.1, as.character(sut[1,]))) # verify row 1 checkTrue(setequal(row.2, as.character(sut[2,]))) # verify row 2 checkTrue(setequal(row.3, as.character(sut[3,]))) # verify row 3 checkTrue(setequal(row.4, as.character(sut[4,]))) # verify row 4 checkTrue(setequal(doorbusters.names, names(sut))) # verify the column names # CLEANUP # file.remove(doorbusters1.csv) file.remove(doorbusters2.csv) rm(file1.data) rm(file2.data) rm(sut) } # test that the read.all.doorbuster.files() function reads ONLY the two csv files# test.read.all.doorbuster.files_three.files <- function() { ############################################# ############## GIVEN #################### ############################################# doorbusters1.csv <- "./tests/test_data/doorbuster1.csv" doorbusters2.csv <- "./tests/test_data/doorbuster2.csv" doorbusters3.csv <- "./tests/test_data/doorbuster3.csv" # CREATE THE TEST DATA # row.1 <- c("4", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.2 <- c("5", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.3 <- c("6", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.4 <- c("7", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.5 <- c("8", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") row.6 <- c("9", "1", "1", "1", "1/1/2015", "1", "2", "In Progress", "1", "10.00") file1.data <- as.data.frame(rbind(row.1, row.2)) file2.data <- as.data.frame(rbind(row.3, row.4)) file3.data <- as.data.frame(rbind(row.5, row.6)) names(file1.data) <- doorbusters.names.in.csv names(file2.data) <- doorbusters.names.in.csv names(file3.data) <- doorbusters.names.in.csv write.csv(file1.data, file=doorbusters1.csv, row.names=FALSE) write.csv(file2.data, file=doorbusters2.csv, row.names=FALSE) write.csv(file3.data, file=doorbusters3.csv, row.names=FALSE) ############################################# ############### WHEN #################### ############################################# sut <- read.all.doorbuster.files("./tests/test_data/") ############################################# ############### THEN #################### ############################################# checkEquals(4, dim(sut)[1]) #verify the number of rows checkTrue(setequal(row.1, as.character(sut[1,]))) # verify row 1 checkTrue(setequal(row.2, as.character(sut[2,]))) # verify row 2 checkTrue(setequal(row.3, as.character(sut[3,]))) # verify row 3 checkTrue(setequal(row.4, as.character(sut[4,]))) # verify row 4 checkTrue(setequal(doorbusters.names, names(sut))) # verify the column names # CLEANUP # file.remove(doorbusters1.csv) file.remove(doorbusters2.csv) file.remove(doorbusters3.csv) rm(file1.data) rm(file2.data) rm(file3.data) rm(sut) }
getMSS <- function(hgnc, entrezgene, path, src, reconVersion, step) { # entrezgene=gene # path=outdir # reconVersion=2.0 # library("XLConnect") reconVersion=2.0 path="./results" src="./src" if (reconVersion==2.2){ load(paste(src, "Recon_2.2_biomodels.RData", sep="/")) load(paste(src, "recon2chebi_MODEL1603150001.RData", sep="/")) rownames(recon2chebi)=recon2chebi[,1] recon2chebi=recon2chebi[model@met_id,] } else if (reconVersion==2.0){ load(paste(src, "Recon2.RData", sep="/")) model=recon2$modelR204[,,1] recon2chebi=NULL } files = list.files("./results/metabolite_sets_step_0,1,2,3_1.0_filter_1.1/mss_WG_step_0") for (i in 1:length(files)){ load(paste("./results//metabolite_sets_step_0,1,2,3_1.0_filter_1.1/mss_WG_step_0", files[i], sep="/")) if (!is.null(retVal)){ hgnc = unlist(strsplit(files[i], split = ".", fixed = TRUE))[1] rval = retVal retVal= NULL outdir=paste(path, "mss_0", sep="/") step = 0 tmp = findMetabolicEnvironment(hgnc, model, recon2chebi, hgnc, step, reconVersion, src, rval) if (!is.null(tmp)){ retVal=tmp save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } outdir=paste(path, "mss_1", sep="/") step = 1 tmp = findMetabolicEnvironment(hgnc, model, recon2chebi, hgnc, step, reconVersion, src, rval) if (!is.null(tmp)) { retVal=tmp save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } else if (!is.null(retVal)){ save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } outdir=paste(path, "mss_2", sep="/") step = 2 tmp = findMetabolicEnvironment(hgnc, model, recon2chebi, hgnc, step, reconVersion, src, rval) if (!is.null(tmp)) { retVal=tmp save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } else if (!is.null(retVal)){ save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } } } # save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) ############### # mss = list.files(path = "./results/mss_P14_primary") # for (j in 1:length(mss)){ # load(paste("./results/mss_P14_primary", mss[j], sep="/")) # hgnc=strsplit(mss[j], split=".", fixed =TRUE)[[1]][1] # ############### # retVal$mets=retVal$mets[c(1:14),] ########################################################################################### # if (!is.null(retVal$mets)){ # # metsExtend=NULL # # if (is.null(dim(retVal$mets))){ # retVal$mets=t(as.matrix(retVal$mets)) # rownames(retVal$mets)=retVal$mets[,"rxn_id"] # } # # if (dim(retVal$mets)[1]>0){ # extend CoA2CarnitineGlycine # ############################################################################################# # for (i in 1:length(retVal$mets[,"met_long"])){ # message(retVal$mets[i,"met_long"]) # # if (gregexpr(pattern ="coa", retVal$mets[i,"met_short"])[[1]][1]>1) { # # # consumed = rbind(retVal$mets[i,],retVal$mets[i,]) # colnames(consumed)[9]="CheBI_id" # colnames(consumed)[8]="KEGG_id" # colnames(consumed)[10]="PubChem_id" # index_consumed = getMets2ReconID(consumed, model) # # tmp = getPreviousNext(model, index_consumed, produced=TRUE) # # #metsExtend=rbind(metsExtend,tmp$mets[which(tmp$mets[,"left_right"]=="right"),]) # metsExtend=rbind(metsExtend,tmp$mets) # # tmp = getPreviousNext(model, index_consumed, produced=FALSE) # # #metsExtend=rbind(metsExtend,tmp$mets[which(tmp$mets[,"left_right"]=="right"),]) # metsExtend=rbind(metsExtend,tmp$mets) # } # } # # # only keep carnitine compounds # metsExtend = rbind(metsExtend[grep(metsExtend[,"met_long"], pattern = "carnitine", fixed = TRUE),,drop=FALSE], # metsExtend[grep(metsExtend[,"met_long"], pattern = "glycine", fixed = TRUE),,drop=FALSE]) # # metsExtend = rbind(retVal$mets, removeMetsFromSet(metsExtend, model)$result_mets) # # tmp = metsExtend[,"met_long"] # unic = !duplicated(tmp) ## logical vector of unique values # index = seq_along(tmp)[unic] ## indices # retVal$mets = metsExtend[index,] # ############################################################################################# # extend transcription factor # ################################################################################################################# # controlledGenes = findControlsExpressionOf(hgnc) # controlledGenes = unique(controlledGenes) # # if (length(controlledGenes)>0){ # message(paste("Bingo transcription factor found!!!",hgnc)) # # ensembl = useEnsembl(biomart="ensembl", dataset="hsapiens_gene_ensembl") # gene_map_table2 = getBM(attributes=c('hgnc_symbol', 'entrezgene', 'ensembl_gene_id'), # filters = 'hgnc_symbol', values = controlledGenes, mart = ensembl) # # for (k in 1:length(controlledGenes)){ # # if (is.null(retVal$mets) || (dim(retVal$mets)[1]==0)){ # retVal = findMetabolicEnvironment(gene_map_table2$entrezgene[k], model, gene_map_table2$hgnc_symbol[k]) # } else { # tmp = findMetabolicEnvironment(gene_map_table2$entrezgene[k], model, gene_map_table2$hgnc_symbol[k]) # if (!is.null(tmp$mets)){ # retVal$mets = rbind(retVal$mets, tmp$mets) # } # } # } # } # ################################################################################################################# # } # } # if (is.null(retVal$mets)) { # message(paste("Empty set for", hgnc)) # } else { # if (is.null(dim(retVal$mets))) { # retVal$mets=t(as.data.frame(retVal$mets)) # } # if (dim(retVal$mets)[1]==0) { # message(paste("Empty set for", hgnc)) # } else { # save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) # # genExcelFileShort(retVal$mets, paste(outdir, paste(hgnc, "xls", sep="."),sep="/")) # } # } # ######### # } # ######### }
/src_Metabolite_Set_Creation/Supportive/old : unnecessary/getMSS.R
permissive
UMCUGenetics/Crossomics
R
false
false
6,563
r
getMSS <- function(hgnc, entrezgene, path, src, reconVersion, step) { # entrezgene=gene # path=outdir # reconVersion=2.0 # library("XLConnect") reconVersion=2.0 path="./results" src="./src" if (reconVersion==2.2){ load(paste(src, "Recon_2.2_biomodels.RData", sep="/")) load(paste(src, "recon2chebi_MODEL1603150001.RData", sep="/")) rownames(recon2chebi)=recon2chebi[,1] recon2chebi=recon2chebi[model@met_id,] } else if (reconVersion==2.0){ load(paste(src, "Recon2.RData", sep="/")) model=recon2$modelR204[,,1] recon2chebi=NULL } files = list.files("./results/metabolite_sets_step_0,1,2,3_1.0_filter_1.1/mss_WG_step_0") for (i in 1:length(files)){ load(paste("./results//metabolite_sets_step_0,1,2,3_1.0_filter_1.1/mss_WG_step_0", files[i], sep="/")) if (!is.null(retVal)){ hgnc = unlist(strsplit(files[i], split = ".", fixed = TRUE))[1] rval = retVal retVal= NULL outdir=paste(path, "mss_0", sep="/") step = 0 tmp = findMetabolicEnvironment(hgnc, model, recon2chebi, hgnc, step, reconVersion, src, rval) if (!is.null(tmp)){ retVal=tmp save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } outdir=paste(path, "mss_1", sep="/") step = 1 tmp = findMetabolicEnvironment(hgnc, model, recon2chebi, hgnc, step, reconVersion, src, rval) if (!is.null(tmp)) { retVal=tmp save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } else if (!is.null(retVal)){ save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } outdir=paste(path, "mss_2", sep="/") step = 2 tmp = findMetabolicEnvironment(hgnc, model, recon2chebi, hgnc, step, reconVersion, src, rval) if (!is.null(tmp)) { retVal=tmp save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } else if (!is.null(retVal)){ save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) } } } # save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) ############### # mss = list.files(path = "./results/mss_P14_primary") # for (j in 1:length(mss)){ # load(paste("./results/mss_P14_primary", mss[j], sep="/")) # hgnc=strsplit(mss[j], split=".", fixed =TRUE)[[1]][1] # ############### # retVal$mets=retVal$mets[c(1:14),] ########################################################################################### # if (!is.null(retVal$mets)){ # # metsExtend=NULL # # if (is.null(dim(retVal$mets))){ # retVal$mets=t(as.matrix(retVal$mets)) # rownames(retVal$mets)=retVal$mets[,"rxn_id"] # } # # if (dim(retVal$mets)[1]>0){ # extend CoA2CarnitineGlycine # ############################################################################################# # for (i in 1:length(retVal$mets[,"met_long"])){ # message(retVal$mets[i,"met_long"]) # # if (gregexpr(pattern ="coa", retVal$mets[i,"met_short"])[[1]][1]>1) { # # # consumed = rbind(retVal$mets[i,],retVal$mets[i,]) # colnames(consumed)[9]="CheBI_id" # colnames(consumed)[8]="KEGG_id" # colnames(consumed)[10]="PubChem_id" # index_consumed = getMets2ReconID(consumed, model) # # tmp = getPreviousNext(model, index_consumed, produced=TRUE) # # #metsExtend=rbind(metsExtend,tmp$mets[which(tmp$mets[,"left_right"]=="right"),]) # metsExtend=rbind(metsExtend,tmp$mets) # # tmp = getPreviousNext(model, index_consumed, produced=FALSE) # # #metsExtend=rbind(metsExtend,tmp$mets[which(tmp$mets[,"left_right"]=="right"),]) # metsExtend=rbind(metsExtend,tmp$mets) # } # } # # # only keep carnitine compounds # metsExtend = rbind(metsExtend[grep(metsExtend[,"met_long"], pattern = "carnitine", fixed = TRUE),,drop=FALSE], # metsExtend[grep(metsExtend[,"met_long"], pattern = "glycine", fixed = TRUE),,drop=FALSE]) # # metsExtend = rbind(retVal$mets, removeMetsFromSet(metsExtend, model)$result_mets) # # tmp = metsExtend[,"met_long"] # unic = !duplicated(tmp) ## logical vector of unique values # index = seq_along(tmp)[unic] ## indices # retVal$mets = metsExtend[index,] # ############################################################################################# # extend transcription factor # ################################################################################################################# # controlledGenes = findControlsExpressionOf(hgnc) # controlledGenes = unique(controlledGenes) # # if (length(controlledGenes)>0){ # message(paste("Bingo transcription factor found!!!",hgnc)) # # ensembl = useEnsembl(biomart="ensembl", dataset="hsapiens_gene_ensembl") # gene_map_table2 = getBM(attributes=c('hgnc_symbol', 'entrezgene', 'ensembl_gene_id'), # filters = 'hgnc_symbol', values = controlledGenes, mart = ensembl) # # for (k in 1:length(controlledGenes)){ # # if (is.null(retVal$mets) || (dim(retVal$mets)[1]==0)){ # retVal = findMetabolicEnvironment(gene_map_table2$entrezgene[k], model, gene_map_table2$hgnc_symbol[k]) # } else { # tmp = findMetabolicEnvironment(gene_map_table2$entrezgene[k], model, gene_map_table2$hgnc_symbol[k]) # if (!is.null(tmp$mets)){ # retVal$mets = rbind(retVal$mets, tmp$mets) # } # } # } # } # ################################################################################################################# # } # } # if (is.null(retVal$mets)) { # message(paste("Empty set for", hgnc)) # } else { # if (is.null(dim(retVal$mets))) { # retVal$mets=t(as.data.frame(retVal$mets)) # } # if (dim(retVal$mets)[1]==0) { # message(paste("Empty set for", hgnc)) # } else { # save(retVal, file=paste(outdir, paste(hgnc, "RData", sep="."), sep="/")) # # genExcelFileShort(retVal$mets, paste(outdir, paste(hgnc, "xls", sep="."),sep="/")) # } # } # ######### # } # ######### }
#' Creat an htmlwidget that shows differences between files or directories #' #' This function can be used for viewing differences between current test #' results and the expected results #' #' @param old,new Names of the old and new directories to compare. #' Alternatively, they can be a character vectors of specific files to #' compare. #' @param pattern A filter to apply to the old and new directories. #' @param width Width of the htmlwidget. #' @param height Height of the htmlwidget #' #' @export diffviewer_widget <- function(old, new, width = NULL, height = NULL, pattern = NULL) { if (xor(assertthat::is.dir(old), assertthat::is.dir(new))) { stop("`old` and `new` must both be directories, or character vectors of filenames.") } # If `old` or `new` are directories, get a list of filenames from both directories if (assertthat::is.dir(old)) { all_filenames <- sort(unique(c( dir(old, recursive = TRUE, pattern = pattern), dir(new, recursive = TRUE, pattern = pattern) ))) } # TODO: Make sure old and new are the same length. Needed if someone passes # in files directly. # # Also, make it work with file lists in general. get_file_contents <- function(filename) { if (!file.exists(filename)) { return(NULL) } bin_data <- read_raw(filename) # Assume .json and .download files are text if (grepl("\\.json$", filename) || grepl("\\.download$", filename)) { raw_to_utf8(bin_data) } else if (grepl("\\.png$", filename)) { paste0("data:image/png;base64,", jsonlite::base64_enc(bin_data)) } else { "" } } get_both_file_contents <- function(filename) { list( filename = filename, old = get_file_contents(file.path(old, filename)), new = get_file_contents(file.path(new, filename)) ) } diff_data <- lapply(all_filenames, get_both_file_contents) htmlwidgets::createWidget( name = "diffviewer", list( diff_data = diff_data ), sizingPolicy = htmlwidgets::sizingPolicy( defaultWidth = "100%", defaultHeight = "100%", browser.padding = 10, viewer.fill = FALSE ), package = "shinytest" ) } #' Interactive viewer widget for changes in test results #' #' @param appDir Directory of the Shiny application that was tested. #' @param testname Name of test to compare. #' #' @export viewTestDiffWidget <- function(appDir = ".", testname = NULL) { expected <- file.path(appDir, "tests", paste0(testname, "-expected")) current <- file.path(appDir, "tests", paste0(testname, "-current")) diffviewer_widget(expected, current) } #' Interactive viewer for changes in test results #' #' @inheritParams viewTestDiffWidget #' @import shiny #' @export viewTestDiff <- function(appDir = ".", testname = NULL) { valid_testnames <- dir(file.path(appDir, "tests"), pattern = "-(expected|current)$") valid_testnames <- sub("-(expected|current)$", "", valid_testnames) valid_testnames <- unique(valid_testnames) if (is.null(testname) || !(testname %in% valid_testnames)) { stop('"', testname, '" ', 'is not a valid testname for the app. Valid names are: "', paste(valid_testnames, collapse = '", "'), '".' ) } withr::with_options( list( shinytest.app.dir = normalizePath(appDir, mustWork = TRUE), shinytest.test.name = testname ), invisible( shiny::runApp(system.file("diffviewerapp", package = "shinytest")) ) ) }
/R/view-diff.R
permissive
fxcebx/shinytest
R
false
false
3,480
r
#' Creat an htmlwidget that shows differences between files or directories #' #' This function can be used for viewing differences between current test #' results and the expected results #' #' @param old,new Names of the old and new directories to compare. #' Alternatively, they can be a character vectors of specific files to #' compare. #' @param pattern A filter to apply to the old and new directories. #' @param width Width of the htmlwidget. #' @param height Height of the htmlwidget #' #' @export diffviewer_widget <- function(old, new, width = NULL, height = NULL, pattern = NULL) { if (xor(assertthat::is.dir(old), assertthat::is.dir(new))) { stop("`old` and `new` must both be directories, or character vectors of filenames.") } # If `old` or `new` are directories, get a list of filenames from both directories if (assertthat::is.dir(old)) { all_filenames <- sort(unique(c( dir(old, recursive = TRUE, pattern = pattern), dir(new, recursive = TRUE, pattern = pattern) ))) } # TODO: Make sure old and new are the same length. Needed if someone passes # in files directly. # # Also, make it work with file lists in general. get_file_contents <- function(filename) { if (!file.exists(filename)) { return(NULL) } bin_data <- read_raw(filename) # Assume .json and .download files are text if (grepl("\\.json$", filename) || grepl("\\.download$", filename)) { raw_to_utf8(bin_data) } else if (grepl("\\.png$", filename)) { paste0("data:image/png;base64,", jsonlite::base64_enc(bin_data)) } else { "" } } get_both_file_contents <- function(filename) { list( filename = filename, old = get_file_contents(file.path(old, filename)), new = get_file_contents(file.path(new, filename)) ) } diff_data <- lapply(all_filenames, get_both_file_contents) htmlwidgets::createWidget( name = "diffviewer", list( diff_data = diff_data ), sizingPolicy = htmlwidgets::sizingPolicy( defaultWidth = "100%", defaultHeight = "100%", browser.padding = 10, viewer.fill = FALSE ), package = "shinytest" ) } #' Interactive viewer widget for changes in test results #' #' @param appDir Directory of the Shiny application that was tested. #' @param testname Name of test to compare. #' #' @export viewTestDiffWidget <- function(appDir = ".", testname = NULL) { expected <- file.path(appDir, "tests", paste0(testname, "-expected")) current <- file.path(appDir, "tests", paste0(testname, "-current")) diffviewer_widget(expected, current) } #' Interactive viewer for changes in test results #' #' @inheritParams viewTestDiffWidget #' @import shiny #' @export viewTestDiff <- function(appDir = ".", testname = NULL) { valid_testnames <- dir(file.path(appDir, "tests"), pattern = "-(expected|current)$") valid_testnames <- sub("-(expected|current)$", "", valid_testnames) valid_testnames <- unique(valid_testnames) if (is.null(testname) || !(testname %in% valid_testnames)) { stop('"', testname, '" ', 'is not a valid testname for the app. Valid names are: "', paste(valid_testnames, collapse = '", "'), '".' ) } withr::with_options( list( shinytest.app.dir = normalizePath(appDir, mustWork = TRUE), shinytest.test.name = testname ), invisible( shiny::runApp(system.file("diffviewerapp", package = "shinytest")) ) ) }
\name{do_admb} \alias{do_admb} \title{Compile and/or run an ADMB model, collect output} \usage{ do_admb(fn, data, params, bounds = NULL, phase = NULL, re = NULL, data_type = NULL, safe = TRUE, profile = FALSE, profpars = NULL, mcmc = FALSE, mcmc.opts = mcmc.control(), impsamp = FALSE, verbose = FALSE, run.opts = run.control(), objfunname = "f", workdir = getwd(), admb_errors = c("stop", "warn", "ignore"), extra.args) } \arguments{ \item{fn}{(character) base name of a TPL function, located in the working directory} \item{data}{a list of input data variables (order must match TPL file)} \item{params}{a list of starting parameter values (order must match TPL file)} \item{bounds}{named list of 2-element vectors of lower and upper bounds for specified parameters} \item{phase}{named numeric vector of phases (not implemented yet)} \item{re}{a named list of the identities and dimensions of any random effects vectors or matrices used in the TPL file} \item{data_type}{a named vector specifying (optional) data types for parameters, in parname="storage mode" format (e.g. \code{c(x="integer",y="numeric")})} \item{safe}{(logical) compile in safe mode?} \item{profile}{(logical) generate likelihood profiles? (untested!)} \item{profpars}{(character) vector of names of parameters to profile} \item{mcmc}{(logical) run MCMC around best fit?} \item{mcmc.opts}{options for MCMC (see \code{\link{mcmc.control}} for details)} \item{impsamp}{(logical) run importance sampling?} \item{verbose}{(logical) print details} \item{run.opts}{options for ADMB run (see \code{\link{run.control}} for details)} \item{objfunname}{(character) name for objective function in TPL file (only relevant if \code{checkparam} is set to "write")} \item{workdir}{temporary working directory (dat/pin/tpl files will be copied)} \item{admb_errors}{how to treat ADMB errors (in either compilation or run): use at your own risk!} \item{extra.args}{(character) extra argument string to pass to admb} } \value{ An object of class \code{admb}. } \description{ Compile an ADMB model, run it, collect output } \details{ \code{do_admb} will attempt to do everything required to start from the model definition (TPL file) specified by \code{fn}, the data list, and the list of input parameters, compile and run (i.e. minimize the objective function of) the model in AD Model Builder, and read the results back into an object of class \code{admb} in R. If \code{checkparam} or \code{checkdata} are set to "write", it will attempt to construct a DATA section, and construct or (augment an existing) PARAMETER section (which may contain definitions of non-input parameters to be used in the model). It copies the input TPL file to a backup (.bak); on finishing, it restores the original TPL file and leaves the auto-generated TPL file in a file called [fn]_gen.tpl. } \note{ 1. Mixed-case file names are ignored by ADMB; this function makes a temporary copy with the file name translated to lower case. 2. Parameter names containing periods/full stops will not work, because this violates C syntax (currently not checked). 3. There are many, many, implicit restrictions and assumptions: for example, all vectors and matrices are assumed to be indexed starting from 1. } \examples{ \dontrun{ setup_admb() file.copy(system.file("tplfiles","ReedfrogSizepred0.tpl",package="R2admb"),"tadpole.tpl") tadpoledat <- data.frame(TBL = rep(c(9,12,21,25,37),each=3), Kill = c(0,2,1,3,4,5,0,0,0,0,1,0,0,0,0L), nexposed=rep(10,15)) m1 <- do_admb("tadpole", data=c(list(nobs=15),tadpoledat), params=list(c=0.45,d=13,g=1), bounds=list(c=c(0,1),d=c(0,50),g=c(-1,25)), run.opts=run.control(checkparam="write", checkdata="write",clean="all")) unlink("tadpole.tpl") } } \author{ Ben Bolker } \keyword{misc}
/R2admb/man/do_admb.Rd
no_license
jlaake/R2admb
R
false
false
4,132
rd
\name{do_admb} \alias{do_admb} \title{Compile and/or run an ADMB model, collect output} \usage{ do_admb(fn, data, params, bounds = NULL, phase = NULL, re = NULL, data_type = NULL, safe = TRUE, profile = FALSE, profpars = NULL, mcmc = FALSE, mcmc.opts = mcmc.control(), impsamp = FALSE, verbose = FALSE, run.opts = run.control(), objfunname = "f", workdir = getwd(), admb_errors = c("stop", "warn", "ignore"), extra.args) } \arguments{ \item{fn}{(character) base name of a TPL function, located in the working directory} \item{data}{a list of input data variables (order must match TPL file)} \item{params}{a list of starting parameter values (order must match TPL file)} \item{bounds}{named list of 2-element vectors of lower and upper bounds for specified parameters} \item{phase}{named numeric vector of phases (not implemented yet)} \item{re}{a named list of the identities and dimensions of any random effects vectors or matrices used in the TPL file} \item{data_type}{a named vector specifying (optional) data types for parameters, in parname="storage mode" format (e.g. \code{c(x="integer",y="numeric")})} \item{safe}{(logical) compile in safe mode?} \item{profile}{(logical) generate likelihood profiles? (untested!)} \item{profpars}{(character) vector of names of parameters to profile} \item{mcmc}{(logical) run MCMC around best fit?} \item{mcmc.opts}{options for MCMC (see \code{\link{mcmc.control}} for details)} \item{impsamp}{(logical) run importance sampling?} \item{verbose}{(logical) print details} \item{run.opts}{options for ADMB run (see \code{\link{run.control}} for details)} \item{objfunname}{(character) name for objective function in TPL file (only relevant if \code{checkparam} is set to "write")} \item{workdir}{temporary working directory (dat/pin/tpl files will be copied)} \item{admb_errors}{how to treat ADMB errors (in either compilation or run): use at your own risk!} \item{extra.args}{(character) extra argument string to pass to admb} } \value{ An object of class \code{admb}. } \description{ Compile an ADMB model, run it, collect output } \details{ \code{do_admb} will attempt to do everything required to start from the model definition (TPL file) specified by \code{fn}, the data list, and the list of input parameters, compile and run (i.e. minimize the objective function of) the model in AD Model Builder, and read the results back into an object of class \code{admb} in R. If \code{checkparam} or \code{checkdata} are set to "write", it will attempt to construct a DATA section, and construct or (augment an existing) PARAMETER section (which may contain definitions of non-input parameters to be used in the model). It copies the input TPL file to a backup (.bak); on finishing, it restores the original TPL file and leaves the auto-generated TPL file in a file called [fn]_gen.tpl. } \note{ 1. Mixed-case file names are ignored by ADMB; this function makes a temporary copy with the file name translated to lower case. 2. Parameter names containing periods/full stops will not work, because this violates C syntax (currently not checked). 3. There are many, many, implicit restrictions and assumptions: for example, all vectors and matrices are assumed to be indexed starting from 1. } \examples{ \dontrun{ setup_admb() file.copy(system.file("tplfiles","ReedfrogSizepred0.tpl",package="R2admb"),"tadpole.tpl") tadpoledat <- data.frame(TBL = rep(c(9,12,21,25,37),each=3), Kill = c(0,2,1,3,4,5,0,0,0,0,1,0,0,0,0L), nexposed=rep(10,15)) m1 <- do_admb("tadpole", data=c(list(nobs=15),tadpoledat), params=list(c=0.45,d=13,g=1), bounds=list(c=c(0,1),d=c(0,50),g=c(-1,25)), run.opts=run.control(checkparam="write", checkdata="write",clean="all")) unlink("tadpole.tpl") } } \author{ Ben Bolker } \keyword{misc}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ols-breusch-pagan-test.R \name{ols_test_breusch_pagan} \alias{ols_test_breusch_pagan} \alias{ols_bp_test} \title{Breusch pagan test} \usage{ ols_test_breusch_pagan( model, fitted.values = TRUE, rhs = FALSE, multiple = FALSE, p.adj = c("none", "bonferroni", "sidak", "holm"), vars = NA ) } \arguments{ \item{model}{An object of class \code{lm}.} \item{fitted.values}{Logical; if TRUE, use fitted values of regression model.} \item{rhs}{Logical; if TRUE, specifies that tests for heteroskedasticity be performed for the right-hand-side (explanatory) variables of the fitted regression model.} \item{multiple}{Logical; if TRUE, specifies that multiple testing be performed.} \item{p.adj}{Adjustment for p value, the following options are available: bonferroni, holm, sidak and none.} \item{vars}{Variables to be used for heteroskedasticity test.} } \value{ \code{ols_test_breusch_pagan} returns an object of class \code{"ols_test_breusch_pagan"}. An object of class \code{"ols_test_breusch_pagan"} is a list containing the following components: \item{bp}{breusch pagan statistic} \item{p}{p-value of \code{bp}} \item{fv}{fitted values of the regression model} \item{rhs}{names of explanatory variables of fitted regression model} \item{multiple}{logical value indicating if multiple tests should be performed} \item{padj}{adjusted p values} \item{vars}{variables to be used for heteroskedasticity test} \item{resp}{response variable} \item{preds}{predictors} } \description{ Test for constant variance. It assumes that the error terms are normally distributed. } \details{ Breusch Pagan Test was introduced by Trevor Breusch and Adrian Pagan in 1979. It is used to test for heteroskedasticity in a linear regression model. It test whether variance of errors from a regression is dependent on the values of a independent variable. \itemize{ \item Null Hypothesis: Equal/constant variances \item Alternative Hypothesis: Unequal/non-constant variances } Computation \itemize{ \item Fit a regression model \item Regress the squared residuals from the above model on the independent variables \item Compute \eqn{nR^2}. It follows a chi square distribution with p -1 degrees of freedom, where p is the number of independent variables, n is the sample size and \eqn{R^2} is the coefficient of determination from the regression in step 2. } } \section{Deprecated Function}{ \code{ols_bp_test()} has been deprecated. Instead use \code{ols_test_breusch_pagan()}. } \examples{ # model model <- lm(mpg ~ disp + hp + wt + drat, data = mtcars) # use fitted values of the model ols_test_breusch_pagan(model) # use independent variables of the model ols_test_breusch_pagan(model, rhs = TRUE) # use independent variables of the model and perform multiple tests ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE) # bonferroni p value adjustment ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE, p.adj = 'bonferroni') # sidak p value adjustment ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE, p.adj = 'sidak') # holm's p value adjustment ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE, p.adj = 'holm') } \references{ T.S. Breusch & A.R. Pagan (1979), A Simple Test for Heteroscedasticity and Random Coefficient Variation. Econometrica 47, 1287–1294 Cook, R. D.; Weisberg, S. (1983). "Diagnostics for Heteroskedasticity in Regression". Biometrika. 70 (1): 1–10. } \seealso{ Other heteroskedasticity tests: \code{\link{ols_test_bartlett}()}, \code{\link{ols_test_f}()}, \code{\link{ols_test_score}()} } \concept{heteroskedasticity tests}
/man/ols_test_breusch_pagan.Rd
no_license
kaushikmanikonda/olsrr
R
false
true
3,686
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ols-breusch-pagan-test.R \name{ols_test_breusch_pagan} \alias{ols_test_breusch_pagan} \alias{ols_bp_test} \title{Breusch pagan test} \usage{ ols_test_breusch_pagan( model, fitted.values = TRUE, rhs = FALSE, multiple = FALSE, p.adj = c("none", "bonferroni", "sidak", "holm"), vars = NA ) } \arguments{ \item{model}{An object of class \code{lm}.} \item{fitted.values}{Logical; if TRUE, use fitted values of regression model.} \item{rhs}{Logical; if TRUE, specifies that tests for heteroskedasticity be performed for the right-hand-side (explanatory) variables of the fitted regression model.} \item{multiple}{Logical; if TRUE, specifies that multiple testing be performed.} \item{p.adj}{Adjustment for p value, the following options are available: bonferroni, holm, sidak and none.} \item{vars}{Variables to be used for heteroskedasticity test.} } \value{ \code{ols_test_breusch_pagan} returns an object of class \code{"ols_test_breusch_pagan"}. An object of class \code{"ols_test_breusch_pagan"} is a list containing the following components: \item{bp}{breusch pagan statistic} \item{p}{p-value of \code{bp}} \item{fv}{fitted values of the regression model} \item{rhs}{names of explanatory variables of fitted regression model} \item{multiple}{logical value indicating if multiple tests should be performed} \item{padj}{adjusted p values} \item{vars}{variables to be used for heteroskedasticity test} \item{resp}{response variable} \item{preds}{predictors} } \description{ Test for constant variance. It assumes that the error terms are normally distributed. } \details{ Breusch Pagan Test was introduced by Trevor Breusch and Adrian Pagan in 1979. It is used to test for heteroskedasticity in a linear regression model. It test whether variance of errors from a regression is dependent on the values of a independent variable. \itemize{ \item Null Hypothesis: Equal/constant variances \item Alternative Hypothesis: Unequal/non-constant variances } Computation \itemize{ \item Fit a regression model \item Regress the squared residuals from the above model on the independent variables \item Compute \eqn{nR^2}. It follows a chi square distribution with p -1 degrees of freedom, where p is the number of independent variables, n is the sample size and \eqn{R^2} is the coefficient of determination from the regression in step 2. } } \section{Deprecated Function}{ \code{ols_bp_test()} has been deprecated. Instead use \code{ols_test_breusch_pagan()}. } \examples{ # model model <- lm(mpg ~ disp + hp + wt + drat, data = mtcars) # use fitted values of the model ols_test_breusch_pagan(model) # use independent variables of the model ols_test_breusch_pagan(model, rhs = TRUE) # use independent variables of the model and perform multiple tests ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE) # bonferroni p value adjustment ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE, p.adj = 'bonferroni') # sidak p value adjustment ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE, p.adj = 'sidak') # holm's p value adjustment ols_test_breusch_pagan(model, rhs = TRUE, multiple = TRUE, p.adj = 'holm') } \references{ T.S. Breusch & A.R. Pagan (1979), A Simple Test for Heteroscedasticity and Random Coefficient Variation. Econometrica 47, 1287–1294 Cook, R. D.; Weisberg, S. (1983). "Diagnostics for Heteroskedasticity in Regression". Biometrika. 70 (1): 1–10. } \seealso{ Other heteroskedasticity tests: \code{\link{ols_test_bartlett}()}, \code{\link{ols_test_f}()}, \code{\link{ols_test_score}()} } \concept{heteroskedasticity tests}
# Children receiving dental care FYC <- FYC %>% mutate( child_2to17 = (1 < AGELAST & AGELAST < 18), child_dental = ((DVTOT.yy. > 0) & (child_2to17==1))*1, child_dental = recode_factor( child_dental, .default = "Missing", .missing = "Missing", "1" = "One or more dental visits", "0" = "No dental visits in past year"))
/build_hc_tables/code/r/grps/child_dental.R
permissive
RandomCriticalAnalysis/MEPS-summary-tables
R
false
false
367
r
# Children receiving dental care FYC <- FYC %>% mutate( child_2to17 = (1 < AGELAST & AGELAST < 18), child_dental = ((DVTOT.yy. > 0) & (child_2to17==1))*1, child_dental = recode_factor( child_dental, .default = "Missing", .missing = "Missing", "1" = "One or more dental visits", "0" = "No dental visits in past year"))
\alias{gtkIconInfoGetAttachPoints} \name{gtkIconInfoGetAttachPoints} \title{gtkIconInfoGetAttachPoints} \description{Fetches the set of attach points for an icon. An attach point is a location in the icon that can be used as anchor points for attaching emblems or overlays to the icon.} \usage{gtkIconInfoGetAttachPoints(object)} \arguments{\item{\verb{object}}{a \code{\link{GtkIconInfo}}}} \details{Since 2.4} \value{ A list containing the following elements: \item{retval}{[logical] \code{TRUE} if there are any attach points for the icon.} \item{\verb{points}}{(array length=n_points) (out): location to store pointer to a list of points, or \code{NULL} free the list of points with \code{gFree()}. \emph{[ \acronym{allow-none} ]}} \item{\verb{n.points}}{location to store the number of points in \code{points}, or \code{NULL}. \emph{[ \acronym{allow-none} ]}} } \author{Derived by RGtkGen from GTK+ documentation} \keyword{internal}
/RGtk2/man/gtkIconInfoGetAttachPoints.Rd
no_license
lawremi/RGtk2
R
false
false
942
rd
\alias{gtkIconInfoGetAttachPoints} \name{gtkIconInfoGetAttachPoints} \title{gtkIconInfoGetAttachPoints} \description{Fetches the set of attach points for an icon. An attach point is a location in the icon that can be used as anchor points for attaching emblems or overlays to the icon.} \usage{gtkIconInfoGetAttachPoints(object)} \arguments{\item{\verb{object}}{a \code{\link{GtkIconInfo}}}} \details{Since 2.4} \value{ A list containing the following elements: \item{retval}{[logical] \code{TRUE} if there are any attach points for the icon.} \item{\verb{points}}{(array length=n_points) (out): location to store pointer to a list of points, or \code{NULL} free the list of points with \code{gFree()}. \emph{[ \acronym{allow-none} ]}} \item{\verb{n.points}}{location to store the number of points in \code{points}, or \code{NULL}. \emph{[ \acronym{allow-none} ]}} } \author{Derived by RGtkGen from GTK+ documentation} \keyword{internal}
rankall <- function(outcome, num = "best") { ## Read outcome data from csv ## Check that state and outcome are valid ## For each state, find the hospital of the given rank ## Return a data frame with the hospital names and the ## (abbreviated) state name ## If an invalid state value function should throw message “invalid state”. ## If an invalid outcome value is passed throw message “invalid outcome”. ## Variables to use: ## [2] "Hospital.Name" ## [11] "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack" ## [17] "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure" ## [23] "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia" ##Read data df <- read.csv("outcome-of-care-measures.csv", colClasses = "character") ## Check valid outcome if (!validate_outcome(outcome)) stop("invalid outcome") ## Check valid num if (num != "worst" && num!="best" && is.character(num)) stop("invalid rank") ## Check valid num count ## returns NA in case num is lager than hospitals count in a state if (num != "worst" && num!="best") if (!is.numeric(num)) return(NA) ## Select nth hospital ## Call best hostpital using the apropiate column number) outcome_name<-c("ha","hf","pn") #outcome_measure<-c(11,17,23) outcome_measure<-c( "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack", "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure", "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia") names(outcome_measure)<-outcome_name if (outcome=="heart attack") out=nth_hospitals(df,outcome_measure["ha"],num) if (outcome=="heart failure") out=nth_hospitals(df,outcome_measure["hf"],num) if (outcome=="pneumonia") out=nth_hospitals(df,outcome_measure["pn"],num) out } nth_hospitals<-function(df,measure,num) { ## recieves dataframe, ## the column number( measure) to work with ## position to return (num) ## returns hospital name (variable 2) having the nth measure value ## and state abbreviation ##Selects only the state,hospital name and the measure columns df<-df[,c("State","Hospital.Name",measure)] ## adds a column to set up the hospital position df$pos=0 ## dicards NA values sel=!is.na(as.numeric(df[[measure]])) df<-df[sel,] ##Sorts based state, measure and hospital name df<-df[ order(df["State"],as.numeric(df[[measure]]), df["Hospital.Name"]),] ## ranks using State and measure lst<-tapply(as.numeric(df[[measure]]),df$State,function (x) rank(x,ties.method="first")) ##converts list to vector and Copy calculated Rank to DF$pos ##df$pos=data.frame(matrix(unlist(lst),nrow=nrow(df),byrow=T),stringsAsFactors=FALSE) df$pos=as.vector(matrix(unlist(lst),nrow=nrow(df),byrow=T)) ## Gets the max value for each state to handle worst case scenarios lst2<-tapply(as.numeric(df$pos),df$State,function (x) max(x) ) df$Max<-lst2[df[,"State"]] if (num=="best") num<-1 if (num=="worst") ## If worst case, then set pos to Max to retreive worst sel2<-df$pos==df$Max else { ## Selects Hopsitals having less than the pos selected sel3<-df$Max<num ## Set Name to NA df[sel3,"Hospital.Name"]=NA ## For those NA Hospitals, Set pos=num for the max value df[df$pos==df$Max & is.na(df$Hospital.Name),"pos"]=num ##Selects the position of each state sel2<-df$pos==num } #Copy Selected rows to df df<-df[sel2,c("Hospital.Name","State")] ## Set names as asked in excersice names(df)[1]<-"hospital" names(df)[2]<-"state" return(df) } validate_outcome<-function(outcome) { ## takes an outcome name and compare it to the valid list ## if exists then returns 1 otherwise returns 0 valid_outcome<-c("heart attack","heart failure","pneumonia") sum(outcome==valid_outcome) }
/rankall.R
no_license
DataScienceGB/test
R
false
false
3,875
r
rankall <- function(outcome, num = "best") { ## Read outcome data from csv ## Check that state and outcome are valid ## For each state, find the hospital of the given rank ## Return a data frame with the hospital names and the ## (abbreviated) state name ## If an invalid state value function should throw message “invalid state”. ## If an invalid outcome value is passed throw message “invalid outcome”. ## Variables to use: ## [2] "Hospital.Name" ## [11] "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack" ## [17] "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure" ## [23] "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia" ##Read data df <- read.csv("outcome-of-care-measures.csv", colClasses = "character") ## Check valid outcome if (!validate_outcome(outcome)) stop("invalid outcome") ## Check valid num if (num != "worst" && num!="best" && is.character(num)) stop("invalid rank") ## Check valid num count ## returns NA in case num is lager than hospitals count in a state if (num != "worst" && num!="best") if (!is.numeric(num)) return(NA) ## Select nth hospital ## Call best hostpital using the apropiate column number) outcome_name<-c("ha","hf","pn") #outcome_measure<-c(11,17,23) outcome_measure<-c( "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack", "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure", "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia") names(outcome_measure)<-outcome_name if (outcome=="heart attack") out=nth_hospitals(df,outcome_measure["ha"],num) if (outcome=="heart failure") out=nth_hospitals(df,outcome_measure["hf"],num) if (outcome=="pneumonia") out=nth_hospitals(df,outcome_measure["pn"],num) out } nth_hospitals<-function(df,measure,num) { ## recieves dataframe, ## the column number( measure) to work with ## position to return (num) ## returns hospital name (variable 2) having the nth measure value ## and state abbreviation ##Selects only the state,hospital name and the measure columns df<-df[,c("State","Hospital.Name",measure)] ## adds a column to set up the hospital position df$pos=0 ## dicards NA values sel=!is.na(as.numeric(df[[measure]])) df<-df[sel,] ##Sorts based state, measure and hospital name df<-df[ order(df["State"],as.numeric(df[[measure]]), df["Hospital.Name"]),] ## ranks using State and measure lst<-tapply(as.numeric(df[[measure]]),df$State,function (x) rank(x,ties.method="first")) ##converts list to vector and Copy calculated Rank to DF$pos ##df$pos=data.frame(matrix(unlist(lst),nrow=nrow(df),byrow=T),stringsAsFactors=FALSE) df$pos=as.vector(matrix(unlist(lst),nrow=nrow(df),byrow=T)) ## Gets the max value for each state to handle worst case scenarios lst2<-tapply(as.numeric(df$pos),df$State,function (x) max(x) ) df$Max<-lst2[df[,"State"]] if (num=="best") num<-1 if (num=="worst") ## If worst case, then set pos to Max to retreive worst sel2<-df$pos==df$Max else { ## Selects Hopsitals having less than the pos selected sel3<-df$Max<num ## Set Name to NA df[sel3,"Hospital.Name"]=NA ## For those NA Hospitals, Set pos=num for the max value df[df$pos==df$Max & is.na(df$Hospital.Name),"pos"]=num ##Selects the position of each state sel2<-df$pos==num } #Copy Selected rows to df df<-df[sel2,c("Hospital.Name","State")] ## Set names as asked in excersice names(df)[1]<-"hospital" names(df)[2]<-"state" return(df) } validate_outcome<-function(outcome) { ## takes an outcome name and compare it to the valid list ## if exists then returns 1 otherwise returns 0 valid_outcome<-c("heart attack","heart failure","pneumonia") sum(outcome==valid_outcome) }
\name{plot3d.ca} \alias{plot3d.ca} \title{Plotting 3D maps in correspondence analysis} \description{Graphical display of correspondence analysis in three dimensions} \usage{\method{plot3d}{ca}(x, dim = c(1, 2, 3), map = "symmetric", what = c("all", "all"), contrib = c("none", "none"), col = c("#6666FF","#FF6666"), labcol = c("#0000FF", "#FF0000"), pch = c(16, 1, 18, 9), labels = c(2, 2), sf = 0.00001, arrows = c(FALSE, FALSE), axiscol = "#333333", axislcol = "#333333", laboffset = list(x = 0, y = 0.075, z = 0.05), ...) } \arguments{ \item{x}{Simple correspondence analysis object returned by ca} \item{dim}{Numerical vector of length 2 indicating the dimensions to plot} \item{map}{Character string specifying the map type. Allowed options include \cr \kbd{"symmetric"} (default) \cr \kbd{"rowprincipal"} \cr \kbd{"colprincipal"} \cr \kbd{"symbiplot"} \cr \kbd{"rowgab"} \cr \kbd{"colgab"} \cr \kbd{"rowgreen"} \cr \kbd{"colgreen"} } \item{what}{Vector of two character strings specifying the contents of the plot. First entry sets the rows and the second entry the columns. Allowed values are \cr \kbd{"none"} (no points are displayed) \cr \kbd{"active"} (only active points are displayed, default) \cr \kbd{"supplementary"} (only supplementary points are displayed) \cr \kbd{"all"} (all available points) \cr The status (active or supplementary) is set in \code{\link{ca}}.} \item{contrib}{Vector of two character strings specifying if contributions (relative or absolute) should be indicated by different colour intensities. Available options are\cr \kbd{"none"} (contributions are not indicated in the plot).\cr \kbd{"absolute"} (absolute contributions are indicated by colour intensities).\cr \kbd{"relative"} (relative conrributions are indicated by colour intensities).\cr If set to \kbd{"absolute"} or \kbd{"relative"}, points with zero contribution are displayed in white. The higher the contribution of a point, the closer the corresponding colour to the one specified by the \code{col} option.} \item{col}{Vector of length 2 specifying the colours of row and column profiles. Colours can be entered in hexadecimal (e.g. \kbd{"\#FF0000"}), rgb (e.g. \kbd{rgb(1,0,0)}) values or by R-name (e.g. \kbd{"red"}). } \item{labcol}{Vector of length 2 specifying the colours of row and column labels. } \item{pch}{Vector of length 2 giving the type of points to be used for rows and columns.} \item{labels}{Vector of length two specifying if the plot should contain symbols only (\kbd{0}), labels only (\kbd{1}) or both symbols and labels (\kbd{2}). Setting \code{labels} to \kbd{2} results in the symbols being plotted at the coordinates and the labels with an offset.} \item{sf}{A scaling factor for the volume of the 3d primitives.} \item{arrows}{Vector of two logicals specifying if the plot should contain points (FALSE, default) or arrows (TRUE). First value sets the rows and the second value sets the columns.} \item{axiscol}{Colour of the axis line.} \item{axislcol}{Colour of the axis labels.} \item{laboffset}{List with 3 slots specifying the label offset in x, y, and z direction.} \item{...}{Further arguments passed to the rgl functions.} } \seealso{\code{\link{ca}}}
/man/plot3d.ca.rd
no_license
cran/ca
R
false
false
3,601
rd
\name{plot3d.ca} \alias{plot3d.ca} \title{Plotting 3D maps in correspondence analysis} \description{Graphical display of correspondence analysis in three dimensions} \usage{\method{plot3d}{ca}(x, dim = c(1, 2, 3), map = "symmetric", what = c("all", "all"), contrib = c("none", "none"), col = c("#6666FF","#FF6666"), labcol = c("#0000FF", "#FF0000"), pch = c(16, 1, 18, 9), labels = c(2, 2), sf = 0.00001, arrows = c(FALSE, FALSE), axiscol = "#333333", axislcol = "#333333", laboffset = list(x = 0, y = 0.075, z = 0.05), ...) } \arguments{ \item{x}{Simple correspondence analysis object returned by ca} \item{dim}{Numerical vector of length 2 indicating the dimensions to plot} \item{map}{Character string specifying the map type. Allowed options include \cr \kbd{"symmetric"} (default) \cr \kbd{"rowprincipal"} \cr \kbd{"colprincipal"} \cr \kbd{"symbiplot"} \cr \kbd{"rowgab"} \cr \kbd{"colgab"} \cr \kbd{"rowgreen"} \cr \kbd{"colgreen"} } \item{what}{Vector of two character strings specifying the contents of the plot. First entry sets the rows and the second entry the columns. Allowed values are \cr \kbd{"none"} (no points are displayed) \cr \kbd{"active"} (only active points are displayed, default) \cr \kbd{"supplementary"} (only supplementary points are displayed) \cr \kbd{"all"} (all available points) \cr The status (active or supplementary) is set in \code{\link{ca}}.} \item{contrib}{Vector of two character strings specifying if contributions (relative or absolute) should be indicated by different colour intensities. Available options are\cr \kbd{"none"} (contributions are not indicated in the plot).\cr \kbd{"absolute"} (absolute contributions are indicated by colour intensities).\cr \kbd{"relative"} (relative conrributions are indicated by colour intensities).\cr If set to \kbd{"absolute"} or \kbd{"relative"}, points with zero contribution are displayed in white. The higher the contribution of a point, the closer the corresponding colour to the one specified by the \code{col} option.} \item{col}{Vector of length 2 specifying the colours of row and column profiles. Colours can be entered in hexadecimal (e.g. \kbd{"\#FF0000"}), rgb (e.g. \kbd{rgb(1,0,0)}) values or by R-name (e.g. \kbd{"red"}). } \item{labcol}{Vector of length 2 specifying the colours of row and column labels. } \item{pch}{Vector of length 2 giving the type of points to be used for rows and columns.} \item{labels}{Vector of length two specifying if the plot should contain symbols only (\kbd{0}), labels only (\kbd{1}) or both symbols and labels (\kbd{2}). Setting \code{labels} to \kbd{2} results in the symbols being plotted at the coordinates and the labels with an offset.} \item{sf}{A scaling factor for the volume of the 3d primitives.} \item{arrows}{Vector of two logicals specifying if the plot should contain points (FALSE, default) or arrows (TRUE). First value sets the rows and the second value sets the columns.} \item{axiscol}{Colour of the axis line.} \item{axislcol}{Colour of the axis labels.} \item{laboffset}{List with 3 slots specifying the label offset in x, y, and z direction.} \item{...}{Further arguments passed to the rgl functions.} } \seealso{\code{\link{ca}}}
## Taylor Plot for modis reflectance - Figure 6 ########## library(tidyverse) # modisBRDF weights # we are taking modisBRDF and the site lists - maybe left join by site and time, selecting out the kernel - arrgh, this will be a little tricky, but we should be ok. load('mcmc-results/modeled-rSoil-results.Rda') #modeled_rSoil %>% filter(model_id=='dead_soil') %>% # ggplot() + geom_point(aes(x=modeled,y=measured,color=site)) #flux_data %>% ggplot() + geom_point(aes(x=soilC,y=rSoil,color=site)) + facet_grid(.~treatment) taylor_values <- modeled_rSoil %>% group_by(type,model,site,treatment) %>% summarize( sd_meas = 1, sd_model = sd(modeled) / sd(measured), r = cor(modeled,measured), centered_rms = sd((measured-mean(measured))-((modeled-mean(modeled))))/sd(measured), x_coord = sd_model*r, y_coord = sd_model*sin(acos(r)) ) # load up the results from the empirical model load('mcmc-results/empirical-taylor-results.Rda') taylor_values <- rbind(taylor_values,taylor_values_empirical) # normalize the results, see Taylor 2001 # E = E'/sigma_meas # sigma_model = sigma_model/sigma_meas # sigma_meas = 1 t_plot <- taylor_plot() curr_plot <- t_plot + geom_point(data=taylor_values,aes(x=x_coord,y=y_coord,color=model,shape=type),size=2) + facet_grid(site~treatment) + labs(x="",y=expression(italic("\u03C3")[model]),color="Model",shape="Estimate type") + theme_bw() + theme(legend.position = "bottom", axis.text = element_text(size=14), axis.title=element_text(size=28), title=element_text(size=26), legend.text=element_text(size=12), legend.title=element_text(size=14), strip.text.x = element_text(size=12), strip.text.y = element_text(size=12), strip.background = element_rect(colour="white", fill="white")) + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) fileName <- paste0('manuscript-figures/taylor-plot.png') ggsave(fileName,plot=curr_plot,width=6,dpi=600)
/plot-process/taylor-plot.R
no_license
jmzobitz/SoilModeling
R
false
false
2,057
r
## Taylor Plot for modis reflectance - Figure 6 ########## library(tidyverse) # modisBRDF weights # we are taking modisBRDF and the site lists - maybe left join by site and time, selecting out the kernel - arrgh, this will be a little tricky, but we should be ok. load('mcmc-results/modeled-rSoil-results.Rda') #modeled_rSoil %>% filter(model_id=='dead_soil') %>% # ggplot() + geom_point(aes(x=modeled,y=measured,color=site)) #flux_data %>% ggplot() + geom_point(aes(x=soilC,y=rSoil,color=site)) + facet_grid(.~treatment) taylor_values <- modeled_rSoil %>% group_by(type,model,site,treatment) %>% summarize( sd_meas = 1, sd_model = sd(modeled) / sd(measured), r = cor(modeled,measured), centered_rms = sd((measured-mean(measured))-((modeled-mean(modeled))))/sd(measured), x_coord = sd_model*r, y_coord = sd_model*sin(acos(r)) ) # load up the results from the empirical model load('mcmc-results/empirical-taylor-results.Rda') taylor_values <- rbind(taylor_values,taylor_values_empirical) # normalize the results, see Taylor 2001 # E = E'/sigma_meas # sigma_model = sigma_model/sigma_meas # sigma_meas = 1 t_plot <- taylor_plot() curr_plot <- t_plot + geom_point(data=taylor_values,aes(x=x_coord,y=y_coord,color=model,shape=type),size=2) + facet_grid(site~treatment) + labs(x="",y=expression(italic("\u03C3")[model]),color="Model",shape="Estimate type") + theme_bw() + theme(legend.position = "bottom", axis.text = element_text(size=14), axis.title=element_text(size=28), title=element_text(size=26), legend.text=element_text(size=12), legend.title=element_text(size=14), strip.text.x = element_text(size=12), strip.text.y = element_text(size=12), strip.background = element_rect(colour="white", fill="white")) + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) fileName <- paste0('manuscript-figures/taylor-plot.png') ggsave(fileName,plot=curr_plot,width=6,dpi=600)
# 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. #' @include arrow-datum.R # Base class for RecordBatch and Table for S3 method dispatch only. # Does not exist in C++ class hierarchy ArrowTabular <- R6Class("ArrowTabular", inherit = ArrowObject, public = list( ToString = function() ToString_tabular(self), Take = function(i) { if (is.numeric(i)) { i <- as.integer(i) } if (is.integer(i)) { i <- Array$create(i) } assert_that(is.Array(i)) call_function("take", self, i) }, Filter = function(i, keep_na = TRUE) { if (is.logical(i)) { i <- Array$create(i) } assert_that(is.Array(i, "bool")) call_function("filter", self, i, options = list(keep_na = keep_na)) }, SortIndices = function(names, descending = FALSE) { assert_that(is.character(names)) assert_that(length(names) > 0) assert_that(!any(is.na(names))) if (length(descending) == 1L) { descending <- rep_len(descending, length(names)) } assert_that(is.logical(descending)) assert_that(identical(length(names), length(descending))) assert_that(!any(is.na(descending))) call_function( "sort_indices", self, # cpp11 does not support logical vectors so convert to integer options = list(names = names, orders = as.integer(descending)) ) } ) ) #' @export as.data.frame.ArrowTabular <- function(x, row.names = NULL, optional = FALSE, ...) { tryCatch( df <- x$to_data_frame(), error = handle_embedded_nul_error ) if (!is.null(r_metadata <- x$metadata$r)) { df <- apply_arrow_r_metadata(df, .unserialize_arrow_r_metadata(r_metadata)) } df } #' @export `names<-.ArrowTabular` <- function(x, value) x$RenameColumns(value) #' @importFrom methods as #' @export `[.ArrowTabular` <- function(x, i, j, ..., drop = FALSE) { if (nargs() == 2L) { # List-like column extraction (x[i]) return(x[, i]) } if (!missing(j)) { # Selecting columns is cheaper than filtering rows, so do it first. # That way, if we're filtering too, we have fewer arrays to filter/slice/take if (is.character(j)) { j_new <- match(j, names(x)) if (any(is.na(j_new))) { stop("Column not found: ", oxford_paste(j[is.na(j_new)]), call. = FALSE) } j <- j_new } if (is_integerish(j)) { if (any(is.na(j))) { stop("Column indices cannot be NA", call. = FALSE) } if (length(j) && all(j < 0)) { # in R, negative j means "everything but j" j <- setdiff(seq_len(x$num_columns), -1 * j) } x <- x$SelectColumns(as.integer(j) - 1L) } if (drop && ncol(x) == 1L) { x <- x$column(0) } } if (!missing(i)) { x <- filter_rows(x, i, ...) } x } #' @export `[[.ArrowTabular` <- function(x, i, ...) { if (is.character(i)) { x$GetColumnByName(i) } else if (is.numeric(i)) { x$column(i - 1) } else { stop("'i' must be character or numeric, not ", class(i), call. = FALSE) } } #' @export `$.ArrowTabular` <- function(x, name, ...) { assert_that(is.string(name)) if (name %in% ls(x)) { get(name, x) } else { x$GetColumnByName(name) } } #' @export `[[<-.ArrowTabular` <- function(x, i, value) { if (!is.character(i) & !is.numeric(i)) { stop("'i' must be character or numeric, not ", class(i), call. = FALSE) } assert_that(length(i) == 1, !is.na(i)) if (is.null(value)) { if (is.character(i)) { i <- match(i, names(x)) } x <- x$RemoveColumn(i - 1L) } else { if (!is.character(i)) { # get or create a/the column name if (i <= x$num_columns) { i <- names(x)[i] } else { i <- as.character(i) } } # auto-magic recycling on non-ArrowObjects if (!inherits(value, "ArrowObject")) { value <- vctrs::vec_recycle(value, x$num_rows) } # construct the field if (inherits(x, "RecordBatch") && !inherits(value, "Array")) { value <- Array$create(value) } else if (inherits(x, "Table") && !inherits(value, "ChunkedArray")) { value <- ChunkedArray$create(value) } new_field <- field(i, value$type) if (i %in% names(x)) { i <- match(i, names(x)) - 1L x <- x$SetColumn(i, new_field, value) } else { i <- x$num_columns x <- x$AddColumn(i, new_field, value) } } x } #' @export `$<-.ArrowTabular` <- function(x, i, value) { assert_that(is.string(i)) # We need to check if `i` is in names in case it is an active binding (e.g. # `metadata`, in which case we use assign to change the active binding instead # of the column in the table) if (i %in% ls(x)) { assign(i, value, x) } else { x[[i]] <- value } x } #' @export dim.ArrowTabular <- function(x) c(x$num_rows, x$num_columns) #' @export as.list.ArrowTabular <- function(x, ...) as.list(as.data.frame(x, ...)) #' @export row.names.ArrowTabular <- function(x) as.character(seq_len(nrow(x))) #' @export dimnames.ArrowTabular <- function(x) list(row.names(x), names(x)) #' @export head.ArrowTabular <- head.ArrowDatum #' @export tail.ArrowTabular <- tail.ArrowDatum #' @export na.fail.ArrowTabular <- function(object, ...){ for (col in seq_len(object$num_columns)) { if (object$column(col - 1L)$null_count > 0) { stop("missing values in object", call. = FALSE) } } object } #' @export na.omit.ArrowTabular <- function(object, ...){ not_na <- map(object$columns, ~build_array_expression("is_valid", .x)) not_na_agg <- Reduce("&", not_na) object$Filter(eval_array_expression(not_na_agg)) } #' @export na.exclude.ArrowTabular <- na.omit.ArrowTabular ToString_tabular <- function(x, ...) { # Generic to work with both RecordBatch and Table sch <- unlist(strsplit(x$schema$ToString(), "\n")) sch <- sub("(.*): (.*)", "$\\1 <\\2>", sch) dims <- sprintf("%s rows x %s columns", nrow(x), ncol(x)) paste(c(dims, sch), collapse = "\n") }
/r/R/arrow-tabular.R
permissive
abs-tudelft/arrow
R
false
false
6,748
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. #' @include arrow-datum.R # Base class for RecordBatch and Table for S3 method dispatch only. # Does not exist in C++ class hierarchy ArrowTabular <- R6Class("ArrowTabular", inherit = ArrowObject, public = list( ToString = function() ToString_tabular(self), Take = function(i) { if (is.numeric(i)) { i <- as.integer(i) } if (is.integer(i)) { i <- Array$create(i) } assert_that(is.Array(i)) call_function("take", self, i) }, Filter = function(i, keep_na = TRUE) { if (is.logical(i)) { i <- Array$create(i) } assert_that(is.Array(i, "bool")) call_function("filter", self, i, options = list(keep_na = keep_na)) }, SortIndices = function(names, descending = FALSE) { assert_that(is.character(names)) assert_that(length(names) > 0) assert_that(!any(is.na(names))) if (length(descending) == 1L) { descending <- rep_len(descending, length(names)) } assert_that(is.logical(descending)) assert_that(identical(length(names), length(descending))) assert_that(!any(is.na(descending))) call_function( "sort_indices", self, # cpp11 does not support logical vectors so convert to integer options = list(names = names, orders = as.integer(descending)) ) } ) ) #' @export as.data.frame.ArrowTabular <- function(x, row.names = NULL, optional = FALSE, ...) { tryCatch( df <- x$to_data_frame(), error = handle_embedded_nul_error ) if (!is.null(r_metadata <- x$metadata$r)) { df <- apply_arrow_r_metadata(df, .unserialize_arrow_r_metadata(r_metadata)) } df } #' @export `names<-.ArrowTabular` <- function(x, value) x$RenameColumns(value) #' @importFrom methods as #' @export `[.ArrowTabular` <- function(x, i, j, ..., drop = FALSE) { if (nargs() == 2L) { # List-like column extraction (x[i]) return(x[, i]) } if (!missing(j)) { # Selecting columns is cheaper than filtering rows, so do it first. # That way, if we're filtering too, we have fewer arrays to filter/slice/take if (is.character(j)) { j_new <- match(j, names(x)) if (any(is.na(j_new))) { stop("Column not found: ", oxford_paste(j[is.na(j_new)]), call. = FALSE) } j <- j_new } if (is_integerish(j)) { if (any(is.na(j))) { stop("Column indices cannot be NA", call. = FALSE) } if (length(j) && all(j < 0)) { # in R, negative j means "everything but j" j <- setdiff(seq_len(x$num_columns), -1 * j) } x <- x$SelectColumns(as.integer(j) - 1L) } if (drop && ncol(x) == 1L) { x <- x$column(0) } } if (!missing(i)) { x <- filter_rows(x, i, ...) } x } #' @export `[[.ArrowTabular` <- function(x, i, ...) { if (is.character(i)) { x$GetColumnByName(i) } else if (is.numeric(i)) { x$column(i - 1) } else { stop("'i' must be character or numeric, not ", class(i), call. = FALSE) } } #' @export `$.ArrowTabular` <- function(x, name, ...) { assert_that(is.string(name)) if (name %in% ls(x)) { get(name, x) } else { x$GetColumnByName(name) } } #' @export `[[<-.ArrowTabular` <- function(x, i, value) { if (!is.character(i) & !is.numeric(i)) { stop("'i' must be character or numeric, not ", class(i), call. = FALSE) } assert_that(length(i) == 1, !is.na(i)) if (is.null(value)) { if (is.character(i)) { i <- match(i, names(x)) } x <- x$RemoveColumn(i - 1L) } else { if (!is.character(i)) { # get or create a/the column name if (i <= x$num_columns) { i <- names(x)[i] } else { i <- as.character(i) } } # auto-magic recycling on non-ArrowObjects if (!inherits(value, "ArrowObject")) { value <- vctrs::vec_recycle(value, x$num_rows) } # construct the field if (inherits(x, "RecordBatch") && !inherits(value, "Array")) { value <- Array$create(value) } else if (inherits(x, "Table") && !inherits(value, "ChunkedArray")) { value <- ChunkedArray$create(value) } new_field <- field(i, value$type) if (i %in% names(x)) { i <- match(i, names(x)) - 1L x <- x$SetColumn(i, new_field, value) } else { i <- x$num_columns x <- x$AddColumn(i, new_field, value) } } x } #' @export `$<-.ArrowTabular` <- function(x, i, value) { assert_that(is.string(i)) # We need to check if `i` is in names in case it is an active binding (e.g. # `metadata`, in which case we use assign to change the active binding instead # of the column in the table) if (i %in% ls(x)) { assign(i, value, x) } else { x[[i]] <- value } x } #' @export dim.ArrowTabular <- function(x) c(x$num_rows, x$num_columns) #' @export as.list.ArrowTabular <- function(x, ...) as.list(as.data.frame(x, ...)) #' @export row.names.ArrowTabular <- function(x) as.character(seq_len(nrow(x))) #' @export dimnames.ArrowTabular <- function(x) list(row.names(x), names(x)) #' @export head.ArrowTabular <- head.ArrowDatum #' @export tail.ArrowTabular <- tail.ArrowDatum #' @export na.fail.ArrowTabular <- function(object, ...){ for (col in seq_len(object$num_columns)) { if (object$column(col - 1L)$null_count > 0) { stop("missing values in object", call. = FALSE) } } object } #' @export na.omit.ArrowTabular <- function(object, ...){ not_na <- map(object$columns, ~build_array_expression("is_valid", .x)) not_na_agg <- Reduce("&", not_na) object$Filter(eval_array_expression(not_na_agg)) } #' @export na.exclude.ArrowTabular <- na.omit.ArrowTabular ToString_tabular <- function(x, ...) { # Generic to work with both RecordBatch and Table sch <- unlist(strsplit(x$schema$ToString(), "\n")) sch <- sub("(.*): (.*)", "$\\1 <\\2>", sch) dims <- sprintf("%s rows x %s columns", nrow(x), ncol(x)) paste(c(dims, sch), collapse = "\n") }
library(rioja) View(dissimilarity) diss=dist(dissimilarity,method='canberra') #clust=chclust(diss,method = "coniss") #To plot the dendogram using coniss method clust=chclust(diss,method = "conslink") #To plot the dendogram using conslink method plot(clust,hang=-1) #creating the hclust object to implement hierarchial clustering hc = hclust(d = dist(dissimilarity, method = 'canberra'), method = 'ward.D') y_hc = cutree(hc,6) diss=as.matrix(diss) #To convert diss into a data matrix # Visualising the clusters library(cluster) clusplot(diss, y_hc, lines = 0, shade = FALSE, color = TRUE, labels= 1, plotchar = FALSE, span = TRUE, main = paste('Clusters'), )
/HAC Clustering easy 1.R
no_license
yasheel-vyas/Constrained-Hierarchical-Agglomerative-Clustering-GSOC
R
false
false
791
r
library(rioja) View(dissimilarity) diss=dist(dissimilarity,method='canberra') #clust=chclust(diss,method = "coniss") #To plot the dendogram using coniss method clust=chclust(diss,method = "conslink") #To plot the dendogram using conslink method plot(clust,hang=-1) #creating the hclust object to implement hierarchial clustering hc = hclust(d = dist(dissimilarity, method = 'canberra'), method = 'ward.D') y_hc = cutree(hc,6) diss=as.matrix(diss) #To convert diss into a data matrix # Visualising the clusters library(cluster) clusplot(diss, y_hc, lines = 0, shade = FALSE, color = TRUE, labels= 1, plotchar = FALSE, span = TRUE, main = paste('Clusters'), )
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/TestOneMuSmfg.R \name{test1musm} \alias{test1musm} \title{Tests the hypothesis over population mean based on one sample summary statistics by Sv-plot2.} \usage{ test1musm(n=20,xbar=3,s=2,mu0=4.5,alpha=0.05, unkwnsigma=TRUE,sigma=NULL,xlab="x", title="Single mean summary: Hypothesis testing by Sv-plot2", samcol="grey5",popcol="grey45",thrcol="black",...) } \arguments{ \item{n}{sample size, \emph{n=20} by default.} \item{xbar}{sample average, \emph{xbar=3} by default.} \item{s}{sample standard deviation, \emph{s=2} by default.} \item{mu0}{hypothesized population mean, \emph{mu0=4.5} by default.} \item{alpha}{significance level, \emph{alpha=0.05} by default.} \item{unkwnsigma}{population standard deviation is unknown, \emph{TRUE} by default.} \item{sigma}{population standard deviation, \emph{NULL} by default.} \item{xlab}{\eqn{x}-axis label, \eqn{x} by default.} \item{title}{title of the plot, \emph{Single mean: Hypothesis testing by Sv-plot2 by default} by default.} \item{samcol}{sample Sv-plot2 color, \emph{grey5} by default.} \item{popcol}{sample Sv-plot2 color, \emph{grey45} by default.} \item{thrcol}{threshold color, \emph{black}.} \item{...}{other graphical parameters.} } \value{ Decision on testing hypotheses over single population mean by Sv-plot2. } \description{ Decision on hypothesis testing over single mean is made by graphing sample and population Sv-plot2s along with the threshold line. Intersecting Sv-plots on or above the horizontal line concludes the alternative hypothesis. } \examples{ ## For summary data test1musm(n=20,xbar=3,s=2,mu0=4.5,alpha=0.05, unkwnsigma=TRUE,sigma=NULL,xlab="x", title="Single mean summary: Hypothesis testing by Sv-plot2", samcol="grey5",popcol="grey45",thrcol="black") } \references{ Wijesuriya, U. A. (2020). Sv-plots for identifying characteristics of the distribution and testing hypotheses. \emph{Communications in Statistics-Simulation and Computation}, \doi{10.1080/03610918.2020.1851716}. }
/man/test1musm.Rd
no_license
cran/svplots
R
false
true
2,186
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/TestOneMuSmfg.R \name{test1musm} \alias{test1musm} \title{Tests the hypothesis over population mean based on one sample summary statistics by Sv-plot2.} \usage{ test1musm(n=20,xbar=3,s=2,mu0=4.5,alpha=0.05, unkwnsigma=TRUE,sigma=NULL,xlab="x", title="Single mean summary: Hypothesis testing by Sv-plot2", samcol="grey5",popcol="grey45",thrcol="black",...) } \arguments{ \item{n}{sample size, \emph{n=20} by default.} \item{xbar}{sample average, \emph{xbar=3} by default.} \item{s}{sample standard deviation, \emph{s=2} by default.} \item{mu0}{hypothesized population mean, \emph{mu0=4.5} by default.} \item{alpha}{significance level, \emph{alpha=0.05} by default.} \item{unkwnsigma}{population standard deviation is unknown, \emph{TRUE} by default.} \item{sigma}{population standard deviation, \emph{NULL} by default.} \item{xlab}{\eqn{x}-axis label, \eqn{x} by default.} \item{title}{title of the plot, \emph{Single mean: Hypothesis testing by Sv-plot2 by default} by default.} \item{samcol}{sample Sv-plot2 color, \emph{grey5} by default.} \item{popcol}{sample Sv-plot2 color, \emph{grey45} by default.} \item{thrcol}{threshold color, \emph{black}.} \item{...}{other graphical parameters.} } \value{ Decision on testing hypotheses over single population mean by Sv-plot2. } \description{ Decision on hypothesis testing over single mean is made by graphing sample and population Sv-plot2s along with the threshold line. Intersecting Sv-plots on or above the horizontal line concludes the alternative hypothesis. } \examples{ ## For summary data test1musm(n=20,xbar=3,s=2,mu0=4.5,alpha=0.05, unkwnsigma=TRUE,sigma=NULL,xlab="x", title="Single mean summary: Hypothesis testing by Sv-plot2", samcol="grey5",popcol="grey45",thrcol="black") } \references{ Wijesuriya, U. A. (2020). Sv-plots for identifying characteristics of the distribution and testing hypotheses. \emph{Communications in Statistics-Simulation and Computation}, \doi{10.1080/03610918.2020.1851716}. }
get_lncRNA_mRNA_pairs = function(originalCorrMatrix, corrThreshold){ correlation_pairs = which(originalCorrMatrix > corrThreshold, arr.ind = TRUE) lncRNA = rownames(originalCorrMatrix)[correlation_pairs[,1]] mRNA = colnames(originalCorrMatrix)[correlation_pairs[,2]] dataframe = as.data.frame(cbind(correlation_pairs, lncRNA, mRNA)) colnames(dataframe) = c("lncRNA_index", "mRNA_index","lncRNA", "mRNA") dataframe$lncRNA_index = as.numeric(as.character(dataframe$lncRNA_index)) dataframe$mRNA_index = as.numeric(as.character(dataframe$mRNA_index)) # correlation_vector = normal_lncRNA_mRNA_corr_matrix[dataframe$lncRNA_index,dataframe$mRNA_index] dataframe = cbind(dataframe, originalCorrMatrix[which(originalCorrMatrix > corrThreshold)]) colnames(dataframe) = c("lncRNA_index", "mRNA_index","lncRNA", "mRNA", "corr") dataframe = dataframe[order(-dataframe$corr),] return(dataframe) } get_encRNA = function(matrix, miRNA_mRNA_corr, miRNA_lncRNA_corr, lncRNA_mRNA_corr, threshold){ triple = which(matrix > threshold, arr.ind = TRUE) encRNAs = rownames(matrix)[triple[,1]] miRNA = colnames(matrix)[triple[,2]] dataframe = as.data.frame(cbind(triple, encRNAs, miRNA)) colnames(dataframe) = c("encRNA_pair_index", "miRNA_index","encRNA_pair", "miRNA") dataframe$encRNA_pair_index = as.numeric(as.character(dataframe$encRNA_pair_index)) dataframe$miRNA_index = as.numeric(as.character(dataframe$miRNA_index)) dataframe = cbind(dataframe, matrix[which(matrix > threshold)]) colnames(dataframe) = c("encRNA_pair_index", "miRNA_index","encRNA_pair", "miRNA", "sensitivity") dataframe = dataframe[order(-dataframe$sensitivity),] # dataframe$lncRNA = substr(dataframe$encRNA_pair, start = 1, stop = 17) # dataframe$mRNA = substr(dataframe$encRNA_pair, start = 19, stop = nchar(as.character(dataframe$encRNA_pair))) pos = regexpr("-",as.character(dataframe$encRNA_pair)) dataframe$lncRNA = substr(as.character(dataframe$encRNA_pair), start = 1, stop = pos - 1) dataframe$mRNA = substr(as.character(dataframe$encRNA_pair), start = pos + 1, stop = nchar(as.character(dataframe$encRNA_pair))) dataframe$lncRNA_miRNA_corr = rep(NA, nrow(dataframe)) dataframe$mRNA_miRNA_corr = rep(NA, nrow(dataframe)) dataframe$lncRNA_miRNA_corr = sapply(1:nrow(dataframe), function(index){ miRNA_lncRNA_corr[as.character(dataframe$miRNA[index]),as.character(dataframe$lncRNA[index])] }) dataframe$mRNA_miRNA_corr = sapply(1:nrow(dataframe), function(index){ miRNA_mRNA_corr[as.character(dataframe$miRNA[index]),as.character(dataframe$mRNA[index])] }) dataframe$lncRNA_mRNA_corr = sapply(1:nrow(dataframe), function(index){ lncRNA_mRNA_corr[as.character(dataframe$lncRNA[index]),as.character(dataframe$mRNA[index])] }) dataframe$encRNA_triple = paste(dataframe$encRNA_pair, dataframe$miRNA, sep = "-") dataframe$lncRNA_miRNA_pair = paste(dataframe$lncRNA, dataframe$miRNA, sep = "-") dataframe$mRNA_miRNA_pair = paste(dataframe$mRNA, dataframe$miRNA, sep = "-") dataframe = dataframe[,c("lncRNA", "mRNA", "miRNA", "sensitivity", "lncRNA_mRNA_corr", "lncRNA_miRNA_corr", "mRNA_miRNA_corr", "encRNA_pair", "encRNA_triple", "lncRNA_miRNA_pair" , "mRNA_miRNA_pair", "encRNA_pair_index", "miRNA_index")] return(dataframe) } # for each lncRNA ensemble ids, find potential miRNA interaction getMiRNAs = function(miRNA_family = NULL){ if (is.null(miRNA_family)){ print("must provide miRNA_family") break; } part1 = substr(miRNA_family, start = 1, stop = 3) part1 = paste("hsa",tolower(part1),sep = "-") # substring anything after miR till the end, divided by "/" part2 = substr(miRNA_family,start = 5, stop = nchar(miRNA_family)) part2 = unlist(strsplit(x = part2, split = "/")) # foreach element, remove 3p and 5p parts part2 = gsub("-3p","",part2) part2 = gsub("-5p","",part2) # return individual mircRNA, # example: 106abc will be disconstructed into 106a, 106b, 106c part2 = sapply(part2, function(element){ if (grepl("\\D",element)){ digit_part = gsub(pattern = "\\D", replacement = "", x = element) character_parts = gsub(pattern = "\\d", replacement = "", x = element) character_parts = unlist(strsplit(x = character_parts,split = "")) returned_value = paste(digit_part, character_parts,sep = "") }else{ element } }) part2 = unname(unlist(part2)) return(paste(part1,part2,sep="-")) } get_putative_lncRNA_miRNA = function(dataframe){ require(rlist) l = list() #i = 1; apply(dataframe, 1, function(r){ k = getMiRNAs(r[2]) l <<- list.append(l, k) #print(i); i <<- i + 1; }) names(l) = dataframe$gene_id df = reshape2::melt(l) colnames(df) = c("miRNA", "putative_lncRNAs") df$lncRNA_miRNA_pair = paste(df$putative_lncRNAs, df$miRNA, sep = "-") return(df) } get_putative_lncRNA_miRNA_2 = function(dataframe){ require(rlist) l = list() i = 1; apply(dataframe, 1, function(r){ k = getMiRNAs(r[2]) l <<- list.append(l, k) print(i); i <<- i + 1; }) names(l) = dataframe$gene_id df = data.frame( miRNA = unlist(l), putative_lncRNAs = rep(names(l), lapply(l, length)) ) colnames(df) = c("miRNA", "putative_lncRNAs") df$lncRNA_miRNA_pair = paste(df$putative_lncRNAs, df$miRNA, sep = "-") return(df) } get_putative_encRNA_interaction = function(df){ if (!("brca_putative_encRNA" %in% ls())){ load("data_Saved_R_Objects/miRNA_target/brca_putative_encRNA.rda"); gc() } brca_putative_encRNA_subset = brca_putative_encRNA[which(brca_putative_encRNA$miRNA %in% df$miRNA),] brca_putative_encRNA_subset = brca_putative_encRNA_subset[which(brca_putative_encRNA_subset$lncRNA %in% df$lncRNA),] brca_putative_encRNA_subset = brca_putative_encRNA_subset[which(brca_putative_encRNA_subset$mRNA %in% df$mRNA),] brca_putative_encRNA_subset$encRNA_triple = paste(brca_putative_encRNA_subset$lncRNA, brca_putative_encRNA_subset$mRNA, brca_putative_encRNA_subset$miRNA, sep = "-") common_triplets = intersect(df$encRNA_triple, brca_putative_encRNA_subset$encRNA_triple) return(normal_encRNA[which(df$encRNA_triple %in% common_triplets),]) } get_matched_enRNA_sensitivity_with_putative_binding = function(encRNA_sensitivity){ load("mircode_objects.rda") lncRNAs_overlapped = intersect(unique(mircode_lncRNA$gene_id), unique(encRNA_sensitivity$lncRNA)) # subset the encRNA_sensivivity to include only lncRNAs matches lncRNAs in miRcode encRNA_sensitivity_subset1 = encRNA_sensitivity[which(encRNA_sensitivity$lncRNA %in% lncRNAs_overlapped),] # similarly, subset the mircode_lncRNA to include only lncRNAs matches lncRNAs in encRNA_sensivivity mircode_lncRNA_subset1 = mircode_lncRNA[which(mircode_lncRNA$gene_id %in% lncRNAs_overlapped), c("gene_id","microrna")] mircode_lncRNA_subset1 = get_putative_lncRNA_miRNA(mircode_lncRNA_subset1) # divide miRNAs familily into individual miRNAs # now, subset encRNA_sensivivity_subset1 to include only the lncRNA-miRNA pairs which also shows up in mircode_lncRNA_subset1 # length(intersect(unique(encRNA_sensitivity_subset1$lncRNA_miRNA_pair), unique(mircode_lncRNA_subset1$lncRNA_miRNA_pair))) intersected_lncRNA_miRNA_pairs = intersect(unique(encRNA_sensitivity_subset1$lncRNA_miRNA_pair), unique(mircode_lncRNA_subset1$lncRNA_miRNA_pair)) encRNA_sensitivity_subset2 = encRNA_sensitivity_subset1[which(encRNA_sensitivity_subset1$lncRNA_miRNA_pair %in% intersected_lncRNA_miRNA_pairs),] # now, we have already found all lncRNA_miRNA pairs in the sensitivity matrix that are also included in miRcode, thus the duty of miRcode is done now # next, we will be working on starbase. First, find all the intersected miRNAs between starbase and encRNA_sensitivity_subset2 starbase = process_starBase() intersected_miRNAs = intersect(unique(starbase$miRNA), unique(encRNA_sensitivity_subset2$miRNA)) # subset starbase to include only miRNA shown up in encRNA_sensitivity_subset2; # similarly, subset encRNA_sensitivity_subset2 starbase_subset = starbase[which(starbase$miRNA %in% intersected_miRNAs),] encRNA_sensitivity_subset3 = encRNA_sensitivity_subset2[which(encRNA_sensitivity_subset2$miRNA %in% intersected_miRNAs),] # now, find all intersected miRNA_mRNA pairs between encRNA_sensitivity_subset3 and starbase_subset intersected_lncRNA_miRNA_pairs = intersect(unique(encRNA_sensitivity_subset3$mRNA_miRNA_pair), unique(starbase_subset$mRNA_miRNA_pair)) encRNA_sensitivity_subset4 = encRNA_sensitivity_subset2[which(encRNA_sensitivity_subset3$mRNA_miRNA_pair %in% intersected_lncRNA_miRNA_pairs),] return(encRNA_sensitivity_subset4) } process_starBase = function(){ load("starbase_mRNA_miRNA_interactions.rda") processed = starbase_mrna_mirna_interaction colnames(processed)[1:2] = c("miRNA", "putative_mRNA") #dim(processed); View(processed) processed$miRNA = tolower(processed$miRNA) # foreach element, remove 3p and 5p parts processed$miRNA = gsub("-3p","",processed$miRNA) processed$miRNA = gsub("-5p","",processed$miRNA) processed$mRNA_miRNA_pair = paste(processed$putative_mRNA, processed$miRNA, sep = "-") processed = processed[,c("miRNA", "putative_mRNA", "mRNA_miRNA_pair")] processed = unique(processed) return(processed) } get_scca_result = function(x, z, nperms = 100){ require(PMA) perm_out <- CCA.permute(x = x, z = z, typex = "standard", typez = "standard", nperms = nperms) out <- CCA(x = x, z = z, typex = "standard", typez = "standard", penaltyx = perm_out$bestpenaltyx, penaltyz = perm_out$bestpenaltyz, v = perm_out$v.init, K = 1) l = list(perm = perm_out, out = out) return(l) }
/code_correlation_analysis/helper_functions.R
no_license
cwt1/encRNA
R
false
false
10,189
r
get_lncRNA_mRNA_pairs = function(originalCorrMatrix, corrThreshold){ correlation_pairs = which(originalCorrMatrix > corrThreshold, arr.ind = TRUE) lncRNA = rownames(originalCorrMatrix)[correlation_pairs[,1]] mRNA = colnames(originalCorrMatrix)[correlation_pairs[,2]] dataframe = as.data.frame(cbind(correlation_pairs, lncRNA, mRNA)) colnames(dataframe) = c("lncRNA_index", "mRNA_index","lncRNA", "mRNA") dataframe$lncRNA_index = as.numeric(as.character(dataframe$lncRNA_index)) dataframe$mRNA_index = as.numeric(as.character(dataframe$mRNA_index)) # correlation_vector = normal_lncRNA_mRNA_corr_matrix[dataframe$lncRNA_index,dataframe$mRNA_index] dataframe = cbind(dataframe, originalCorrMatrix[which(originalCorrMatrix > corrThreshold)]) colnames(dataframe) = c("lncRNA_index", "mRNA_index","lncRNA", "mRNA", "corr") dataframe = dataframe[order(-dataframe$corr),] return(dataframe) } get_encRNA = function(matrix, miRNA_mRNA_corr, miRNA_lncRNA_corr, lncRNA_mRNA_corr, threshold){ triple = which(matrix > threshold, arr.ind = TRUE) encRNAs = rownames(matrix)[triple[,1]] miRNA = colnames(matrix)[triple[,2]] dataframe = as.data.frame(cbind(triple, encRNAs, miRNA)) colnames(dataframe) = c("encRNA_pair_index", "miRNA_index","encRNA_pair", "miRNA") dataframe$encRNA_pair_index = as.numeric(as.character(dataframe$encRNA_pair_index)) dataframe$miRNA_index = as.numeric(as.character(dataframe$miRNA_index)) dataframe = cbind(dataframe, matrix[which(matrix > threshold)]) colnames(dataframe) = c("encRNA_pair_index", "miRNA_index","encRNA_pair", "miRNA", "sensitivity") dataframe = dataframe[order(-dataframe$sensitivity),] # dataframe$lncRNA = substr(dataframe$encRNA_pair, start = 1, stop = 17) # dataframe$mRNA = substr(dataframe$encRNA_pair, start = 19, stop = nchar(as.character(dataframe$encRNA_pair))) pos = regexpr("-",as.character(dataframe$encRNA_pair)) dataframe$lncRNA = substr(as.character(dataframe$encRNA_pair), start = 1, stop = pos - 1) dataframe$mRNA = substr(as.character(dataframe$encRNA_pair), start = pos + 1, stop = nchar(as.character(dataframe$encRNA_pair))) dataframe$lncRNA_miRNA_corr = rep(NA, nrow(dataframe)) dataframe$mRNA_miRNA_corr = rep(NA, nrow(dataframe)) dataframe$lncRNA_miRNA_corr = sapply(1:nrow(dataframe), function(index){ miRNA_lncRNA_corr[as.character(dataframe$miRNA[index]),as.character(dataframe$lncRNA[index])] }) dataframe$mRNA_miRNA_corr = sapply(1:nrow(dataframe), function(index){ miRNA_mRNA_corr[as.character(dataframe$miRNA[index]),as.character(dataframe$mRNA[index])] }) dataframe$lncRNA_mRNA_corr = sapply(1:nrow(dataframe), function(index){ lncRNA_mRNA_corr[as.character(dataframe$lncRNA[index]),as.character(dataframe$mRNA[index])] }) dataframe$encRNA_triple = paste(dataframe$encRNA_pair, dataframe$miRNA, sep = "-") dataframe$lncRNA_miRNA_pair = paste(dataframe$lncRNA, dataframe$miRNA, sep = "-") dataframe$mRNA_miRNA_pair = paste(dataframe$mRNA, dataframe$miRNA, sep = "-") dataframe = dataframe[,c("lncRNA", "mRNA", "miRNA", "sensitivity", "lncRNA_mRNA_corr", "lncRNA_miRNA_corr", "mRNA_miRNA_corr", "encRNA_pair", "encRNA_triple", "lncRNA_miRNA_pair" , "mRNA_miRNA_pair", "encRNA_pair_index", "miRNA_index")] return(dataframe) } # for each lncRNA ensemble ids, find potential miRNA interaction getMiRNAs = function(miRNA_family = NULL){ if (is.null(miRNA_family)){ print("must provide miRNA_family") break; } part1 = substr(miRNA_family, start = 1, stop = 3) part1 = paste("hsa",tolower(part1),sep = "-") # substring anything after miR till the end, divided by "/" part2 = substr(miRNA_family,start = 5, stop = nchar(miRNA_family)) part2 = unlist(strsplit(x = part2, split = "/")) # foreach element, remove 3p and 5p parts part2 = gsub("-3p","",part2) part2 = gsub("-5p","",part2) # return individual mircRNA, # example: 106abc will be disconstructed into 106a, 106b, 106c part2 = sapply(part2, function(element){ if (grepl("\\D",element)){ digit_part = gsub(pattern = "\\D", replacement = "", x = element) character_parts = gsub(pattern = "\\d", replacement = "", x = element) character_parts = unlist(strsplit(x = character_parts,split = "")) returned_value = paste(digit_part, character_parts,sep = "") }else{ element } }) part2 = unname(unlist(part2)) return(paste(part1,part2,sep="-")) } get_putative_lncRNA_miRNA = function(dataframe){ require(rlist) l = list() #i = 1; apply(dataframe, 1, function(r){ k = getMiRNAs(r[2]) l <<- list.append(l, k) #print(i); i <<- i + 1; }) names(l) = dataframe$gene_id df = reshape2::melt(l) colnames(df) = c("miRNA", "putative_lncRNAs") df$lncRNA_miRNA_pair = paste(df$putative_lncRNAs, df$miRNA, sep = "-") return(df) } get_putative_lncRNA_miRNA_2 = function(dataframe){ require(rlist) l = list() i = 1; apply(dataframe, 1, function(r){ k = getMiRNAs(r[2]) l <<- list.append(l, k) print(i); i <<- i + 1; }) names(l) = dataframe$gene_id df = data.frame( miRNA = unlist(l), putative_lncRNAs = rep(names(l), lapply(l, length)) ) colnames(df) = c("miRNA", "putative_lncRNAs") df$lncRNA_miRNA_pair = paste(df$putative_lncRNAs, df$miRNA, sep = "-") return(df) } get_putative_encRNA_interaction = function(df){ if (!("brca_putative_encRNA" %in% ls())){ load("data_Saved_R_Objects/miRNA_target/brca_putative_encRNA.rda"); gc() } brca_putative_encRNA_subset = brca_putative_encRNA[which(brca_putative_encRNA$miRNA %in% df$miRNA),] brca_putative_encRNA_subset = brca_putative_encRNA_subset[which(brca_putative_encRNA_subset$lncRNA %in% df$lncRNA),] brca_putative_encRNA_subset = brca_putative_encRNA_subset[which(brca_putative_encRNA_subset$mRNA %in% df$mRNA),] brca_putative_encRNA_subset$encRNA_triple = paste(brca_putative_encRNA_subset$lncRNA, brca_putative_encRNA_subset$mRNA, brca_putative_encRNA_subset$miRNA, sep = "-") common_triplets = intersect(df$encRNA_triple, brca_putative_encRNA_subset$encRNA_triple) return(normal_encRNA[which(df$encRNA_triple %in% common_triplets),]) } get_matched_enRNA_sensitivity_with_putative_binding = function(encRNA_sensitivity){ load("mircode_objects.rda") lncRNAs_overlapped = intersect(unique(mircode_lncRNA$gene_id), unique(encRNA_sensitivity$lncRNA)) # subset the encRNA_sensivivity to include only lncRNAs matches lncRNAs in miRcode encRNA_sensitivity_subset1 = encRNA_sensitivity[which(encRNA_sensitivity$lncRNA %in% lncRNAs_overlapped),] # similarly, subset the mircode_lncRNA to include only lncRNAs matches lncRNAs in encRNA_sensivivity mircode_lncRNA_subset1 = mircode_lncRNA[which(mircode_lncRNA$gene_id %in% lncRNAs_overlapped), c("gene_id","microrna")] mircode_lncRNA_subset1 = get_putative_lncRNA_miRNA(mircode_lncRNA_subset1) # divide miRNAs familily into individual miRNAs # now, subset encRNA_sensivivity_subset1 to include only the lncRNA-miRNA pairs which also shows up in mircode_lncRNA_subset1 # length(intersect(unique(encRNA_sensitivity_subset1$lncRNA_miRNA_pair), unique(mircode_lncRNA_subset1$lncRNA_miRNA_pair))) intersected_lncRNA_miRNA_pairs = intersect(unique(encRNA_sensitivity_subset1$lncRNA_miRNA_pair), unique(mircode_lncRNA_subset1$lncRNA_miRNA_pair)) encRNA_sensitivity_subset2 = encRNA_sensitivity_subset1[which(encRNA_sensitivity_subset1$lncRNA_miRNA_pair %in% intersected_lncRNA_miRNA_pairs),] # now, we have already found all lncRNA_miRNA pairs in the sensitivity matrix that are also included in miRcode, thus the duty of miRcode is done now # next, we will be working on starbase. First, find all the intersected miRNAs between starbase and encRNA_sensitivity_subset2 starbase = process_starBase() intersected_miRNAs = intersect(unique(starbase$miRNA), unique(encRNA_sensitivity_subset2$miRNA)) # subset starbase to include only miRNA shown up in encRNA_sensitivity_subset2; # similarly, subset encRNA_sensitivity_subset2 starbase_subset = starbase[which(starbase$miRNA %in% intersected_miRNAs),] encRNA_sensitivity_subset3 = encRNA_sensitivity_subset2[which(encRNA_sensitivity_subset2$miRNA %in% intersected_miRNAs),] # now, find all intersected miRNA_mRNA pairs between encRNA_sensitivity_subset3 and starbase_subset intersected_lncRNA_miRNA_pairs = intersect(unique(encRNA_sensitivity_subset3$mRNA_miRNA_pair), unique(starbase_subset$mRNA_miRNA_pair)) encRNA_sensitivity_subset4 = encRNA_sensitivity_subset2[which(encRNA_sensitivity_subset3$mRNA_miRNA_pair %in% intersected_lncRNA_miRNA_pairs),] return(encRNA_sensitivity_subset4) } process_starBase = function(){ load("starbase_mRNA_miRNA_interactions.rda") processed = starbase_mrna_mirna_interaction colnames(processed)[1:2] = c("miRNA", "putative_mRNA") #dim(processed); View(processed) processed$miRNA = tolower(processed$miRNA) # foreach element, remove 3p and 5p parts processed$miRNA = gsub("-3p","",processed$miRNA) processed$miRNA = gsub("-5p","",processed$miRNA) processed$mRNA_miRNA_pair = paste(processed$putative_mRNA, processed$miRNA, sep = "-") processed = processed[,c("miRNA", "putative_mRNA", "mRNA_miRNA_pair")] processed = unique(processed) return(processed) } get_scca_result = function(x, z, nperms = 100){ require(PMA) perm_out <- CCA.permute(x = x, z = z, typex = "standard", typez = "standard", nperms = nperms) out <- CCA(x = x, z = z, typex = "standard", typez = "standard", penaltyx = perm_out$bestpenaltyx, penaltyz = perm_out$bestpenaltyz, v = perm_out$v.init, K = 1) l = list(perm = perm_out, out = out) return(l) }
#' Script to extract raster data for all sampling localities #' and find the most important features. #' #' This script takes as input a directory of rasters, crops them to the #' sampling extent, finds the raster values at each sample locality, #' and uses MAXENT and ENMeval to determine the most important raster #' layers (i.e. features). #' #' #' Function to load in and crop the raster layers to the sampling extent #' #' This function takes as input a directory of rasters. Only the desired #' rasters should be included in raster.dir. You also will need a #' comma-delimited sample.file that has four columns in a specific order: #' (sampleIDs,populationIDs,latitude,longitude). You can choose if a header #' line is present. The rasters will all be put into a stack and cropped to #' the extent of the sample localities + bb.buffer. #' @param raster.dir Directory of rasters to load and crop #' @param sample.file CSV file with sample information (sampleID,popID,lat,lon) #' @param header Boolean; Does sample.file have a header line? #' @param bb.buffer Integer; Buffer around sample bounding box. #' bb.buffer = bb.buffer * resolution (in arc-seconds) #' @param plotDIR Directory to save plots to #' @return List with cropped rasters and other info #' @export prepare_rasters <- function(raster.dir, sample.file, header = TRUE, bb.buffer = 10, plotDIR = "./plots"){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } dir.create(plotDIR, showWarnings = FALSE) samples <- read.csv(file = sample.file, header = header, stringsAsFactors = FALSE) # Make sure values are numeric. samples[,3] <- as.numeric(as.character(samples[,3])) samples[,4] <- as.numeric(as.character(samples[,4])) # Get dataframe of longitude, latitude. coords <- data.frame(samples[,4], samples[,3]) # Make into factor for bg color assignment later. pops <- base::as.factor(samples[,2]) # Change column names. colnames(coords) <- c("lng", "lat") # Get raster filenames (all in one directory) files <- list.files(path = raster.dir, full.names = T) writeLines("\n\nOrder of raster files: \n") # Order alphanumerically. files <- gtools::mixedsort(files) for (i in 1:length(files)){ writeLines(paste0(i, ": ", files[i])) } # Put the rasters into a RasterStack. envs <- raster::stack(files) writeLines(paste0("\n\nLoaded ", raster::nlayers(envs), " raster layers..")) # Plot first raster in the stack, bio1. #raster::plot(envs[[1]], main=names(envs)[1]) # Get CRS (coordinate reference system) mycrs <- raster::crs(envs[[1]]) # Create spatialpoints object. p <- sp::SpatialPoints(coords = coords, proj4string=mycrs) # Get the bounding box of the points bb <- raster::bbox(p) # Add (bb.buffer * resolution / 2) to sample bounds for background extent. bb.buf <- raster::extent(bb[1]-bb.buffer, bb[3]+bb.buffer, bb[2]-bb.buffer, bb[4]+bb.buffer) # Add bb.buffer * resolution (in arc-seconds) to bb for cropping raster layer. envs.buf <- raster::extent(bb[1]-(bb.buffer/2), bb[3]+(bb.buffer/2), bb[2]-(bb.buffer/2), bb[4]+(bb.buffer/2)) writeLines(paste0("\n\nCropping to samples with buffer of ", (bb.buffer/2), " degrees\n")) # Crop raster extent to sample bounding box + bb.buffer envs.cropped <- raster::crop(envs, envs.buf) writeLines(paste0("\nCropping background layers with buffer of ", bb.buffer, " degrees\n")) # Crop environmental layers to tmatch the study extent. # Used for background data later. envs.backg <- raster::crop(envs, bb.buf) counter <- 1 # Save raster plots with sample points layered on top pdf(file = file.path(plotDIR, "croppedRasterPlots.pdf"), width = 7, height = 7, onefile = T) for (i in 1:raster::nlayers(envs.backg)){ writeLines(paste0("Saving raster plot ", i, " to disk...")) raster::plot(envs.backg[[i]]) dismo::points(coords, pch=21, bg=pops) counter <- counter+1 } dev.off() envList <- list(envs.cropped, envs.backg, coords, p, pops, samples[,1]) rm(envs, p, bb, bb.buf, envs.buf, envs.cropped, envs.backg) gc(verbose = FALSE) return(envList) } #' Function to make partitions from background and foreground rasters. #' #' This function uses the output from prepare_raster() and makes #' background partitions using several methods. #' @param env.list Object output from prepare_rasters() function #' @param number.bg.points Number of background points to generate #' @param bg.raster Raster to use for background points #' @param agg.factor A vector of 1 or 2 numbers for the checkerboard #' methods #' @param plotDIR Directory to save the plots to #' @return Object with background points #' @export partition_raster_bg <- function(env.list, number.bg.points = 10000, bg.raster = 1, plotDIR = "./plots", agg.factor = 2){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } dir.create(plotDIR, showWarnings = FALSE) bg.raster <- as.integer(as.character(bg.raster)) envs.cropped <- env.list[[1]] envs.backg <- env.list[[2]] coords <- env.list[[3]] p <- env.list[[4]] pops <- env.list[[5]] inds <- env.list[[6]] rm(env.list) gc(verbose = FALSE) writeLines(paste0("\n\nGenerating ", number.bg.points, " random points...")) # Randomly sample 10,000 background points from one background extent raster # (only one per cell without replacement). # Note: If the raster has <10,000 pixels, # you'll get a warning and all pixels will be used for background. bg <- dismo::randomPoints(envs.backg[[bg.raster]], n=number.bg.points) bg <- raster::as.data.frame(bg) # Change column names. colnames(coords) <- c("lng", "lat") rm(pops) gc(verbose = FALSE) writeLines("\nSaving background partition plots...") writeLines("\nPerforming block method...") ### Block Method blocks <- ENMeval::get.block(coords, bg) pdf(file = file.path(plotDIR, "bgPartitions_blocks.pdf"), width = 7, height = 7, onefile = TRUE) raster::plot(envs.backg[[bg.raster]], col="gray", main = "Partitions into Training and Test Data", sub="Block Method", xlab = "Longitude", ylab = "Latitude") dismo::points(coords, pch=21, bg=blocks$occ.grp) dev.off() rm(blocks) gc(verbose = FALSE) writeLines("Performing checkerboard1 method...") ### Checkerboard1 Method check1 <- ENMeval::get.checkerboard1(coords, envs.cropped, bg, aggregation.factor = agg.factor) pdf(file = file.path(plotDIR, "bgPartitions_checkerboard1.pdf"), width = 7, height = 7, onefile = TRUE) raster::plot( envs.backg[[bg.raster]], col="gray", main = "Partitions into Training and Test Data (Aggregation Factor=5)", sub="Checkerboard1 Method", xlab = "Longitude", ylab = "Latitude" ) dismo::points(bg, pch=21, bg=check1$occ.grp) dev.off() rm(check1) gc(verbose = FALSE) writeLines("Performing checkerboard2 method...") ### Using the Checkerboard2 method. check2 <- ENMeval::get.checkerboard2(coords, envs.cropped, bg, aggregation.factor = c(agg.factor, agg.factor)) pdf(file = file.path(plotDIR, "bgPartitions_checkerboard2.pdf"), width = 7, height = 7, onefile = TRUE) raster::plot(envs.backg[[bg.raster]], col="gray", main = "Partitions into Training and Test Data", sub="Checkerboard2 Method", xlab = "Longitude", ylab = "Latitude") dismo::points(bg, pch=21, bg=check2$bg.grp) dismo::points(coords, pch=21, bg=check2$occ.grp, col="white", cex=1.5) dev.off() rm(check2) gc(verbose = FALSE) writeLines("\nDone!") return(bg) } #' Function to run ENMeval and MAXENT on the raster layers. #' #' This function takes as input the object output from preparte_rasters() and #' the background partitioning method you would like to use #' (see ENMeval documentation). You can visualize how the partitioning #' methods will look by viewing the PDF output from partition_raster_bg. #' See ?partition_raster_bg for more info. #' @param envs.fg First element of envs.list returned from prepare_raster_bg() #' @param bg Object with background points; generated from partition_raster_bg #' @param coords Data.Frame with (lon,lat). 3rd element of envs.list #' @param partition.method Method used for background point partitioning #' @param parallel If TRUE, ENMeval is run parallelized with np CPU cores #' @param np Number of parallel cores to use if parallel = TRUE #' @param RMvalues Vector of non-negative regularization multiplier values. #' Higher values impose a stronger penalty on model complexity #' @param feature.classes Character vector of feature classes to be used #' @param categoricals Vector indicating which (if any) of the input #' environmental layers are categorical. #' @param agg.factor Aggregation factor(s) for checkerboard #' partitioning method. #' @param algorithm Character vector. Defaults to dismo's maxent.jar #' @return ENMeval object #' @export runENMeval <- function(envs.fg, bg, coords, partition.method, parallel = FALSE, np = 2, RMvalues = seq(0.5, 4, 0.5), feature.classes = c("L", "LQ", "H", "LQH", "LQHP", "LQHPT"), categoricals = NULL, agg.factor = 2, algorithm = "maxent.jar" ){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } if (partition.method == "checkerboard2"){ agg.factor <- c(agg.factor, agg.factor) } if (parallel == TRUE){ eval.par <- ENMeval::ENMevaluate( occ = coords, env = envs.fg, bg.coords = bg, method = partition.method, RMvalues = RMvalues, fc = feature.classes, parallel = parallel, algorithm = algorithm, categoricals = categoricals, aggregation.factor = agg.factor, numCores = np ) } else if (parallel == FALSE){ eval.par <- ENMeval::ENMevaluate( occ = coords, env = envs.fg, bg.coords = bg, method = partition.method, RMvalues = RMvalues, fc = feature.classes, parallel = parallel, algorithm = algorithm, categoricals = categoricals, aggregation.factor = agg.factor ) } else { stop("Parallel must be either TRUE or FALSE") } return(eval.par) } #' Function to summarize ENMeval output #' @param eval.par Object returned from runENMeval #' @param minLat Minimum latitude to plot for predictions #' @param maxLat Maximum latitude to plot for predictions #' @param minLon Minimum longitude to plot for predictions #' @param maxLon Maximum longitude to plot for predictions #' @param examine.predictions Character vector of feature classes to examine #' how complexity affects predictions #' @param RMvalues Vector of non-negative RM values to examine how #' complexity affects predictions #' @param plotDIR Directory to save plots to #' @param niche.overlap Boolean. If TRUE, calculates pairwise niche overlap #' matrix #' @param plot.width Integer. Specify plot widths #' @param plot.height Integer. Specify plot heights #' @param imp.margins Integer vector. Margins of variable importance barplot. #' c(bottom, left, top, right) #' @export summarize_ENMeval <- function(eval.par, minLat = 20, maxLat = 50, minLon = -110, maxLon = -40, examine.predictions = c("L", "LQ", "H", "LQH", "LQHP", "LQHPT"), RMvalues = seq(0.5, 4, 0.5), plotDIR = "./plots", niche.overlap = FALSE, plot.width = 7, plot.height = 7, imp.margins = c(10.0, 4.1, 4.1, 2.1)){ dir.create(plotDIR, showWarnings = FALSE) if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } if (niche.overlap){ # Calculate niche overlap. overlap <- ENMeval::calc.niche.overlap(eval.par@predictions, stat="D") # Write niche overlap to a file. write.csv(x = overlap, file = file.path(plotDIR, "ENMeval_nicheOverlap.csv")) } # Write ENMeval results to file. write.csv(x = eval.par@results, file = file.path(plotDIR, "ENMeval_results.csv")) # Get best model. eval.par@results[which(eval.par@results$delta.AICc==0),] eval.par@results[which(eval.par@results$delta.AICc==0),] bestAICc <- eval.par@results[which(eval.par@results$delta.AICc==0),] # Write to file. write.csv(bestAICc, file = file.path(plotDIR, "ENMeval_bestAICc.csv")) # Save it to file. pdf(file = file.path(plotDIR, "ENMeval_relativeOccurenceRate_bestModel.pdf"), width = plot.width, height = plot.height, onefile = TRUE) raster::plot(eval.par@predictions[[which(eval.par@results$delta.AICc==0)]], main="Relative Occurrence Rate") dev.off() # Look at the model object for our "AICc optimal" model: aic.opt <- eval.par@models[[which(eval.par@results$delta.AICc==0)]] # Write it to file. write.csv(x = aic.opt@results, file = file.path(plotDIR, "ENMeval_maxentModel_aicOptimal.csv")) # Get a data.frame of two variable importance metrics: # percent contribution and permutation importance. varImportance <- ENMeval::var.importance(aic.opt) # Write them to file. write.csv(varImportance, file = file.path(plotDIR, "ENMeval_varImportance.csv")) # The "lambdas" slot shows which variables were included in the model. # If the coefficient is 0, that variable was not included in the model. lambdas <- aic.opt@lambdas write.csv(lambdas, file = file.path(plotDIR, "ENMeval_lambdas.csv")) pdf(file = file.path(plotDIR, "ENMeval_AUC_importancePlots.pdf"), width = plot.width, height = plot.height, onefile = TRUE) ENMeval::eval.plot(eval.par@results) ENMeval::eval.plot(eval.par@results, 'avg.test.AUC', variance ='var.test.AUC') ENMeval::eval.plot(eval.par@results, "avg.diff.AUC", variance="var.diff.AUC") # Plot permutation importance. df <- ENMeval::var.importance(aic.opt) par(mar=imp.margins) raster::barplot(df$permutation.importance, names.arg = df$variable, las = 2, ylab = "Permutation Importance") dev.off() # Let's see how model complexity changes the predictions in our example pdf(file = file.path(plotDIR, "modelPredictions.pdf"), width = plot.width, height = plot.height, onefile = TRUE) for (i in 1:length(examine.predictions)){ for (j in 1:length(RMvalues)){ raster::plot(eval.par@predictions[[paste(examine.predictions[i], RMvalues[j], sep = "_")]], ylim=c(minLat,maxLat), xlim=c(minLon, maxLon), main=paste0(examine.predictions[i], "_", RMvalues[j], " Prediction"), ) } } dev.off() } #' Function to extract raster values at each sample point for raster stack #' @param env.list List object generated from prepare_rasters() #' @return List of data.frames with raster values at each sample locality #' for each raster layer, and list of raster names #' @export extractPointValues <- function(env.list){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } envs.cropped <- env.list[[1]] p <- env.list[[4]] inds <- env.list[[6]] raster.points <- list() writeLines("\nExtracting raster values at sample points") # Extract raster values at each sample point. for (i in 1:raster::nlayers(envs.cropped)){ raster.points[[i]] <- raster::extract(envs.cropped[[i]], p) } writeLines("\nAdding sampleIDs to raster dataframe") # Add sample IDs to point/raster value dataframe. rp.df <- lapply(raster.points, function(x) { cbind.data.frame( inds, raster::coordinates(p), x ) } ) rasterNames <- env.list[[1]]@data@names # Use raster name as x colname for (i in 1:length(rasterNames)){ colnames(rp.df[[i]]) <- c("inds", "lng", "lat", rasterNames[i]) } rm(raster.points) gc(verbose = FALSE) # Get which samples are on NA raster values. test4na <- lapply(rp.df, function(x) x[raster::rowSums(is.na(x)) > 0,]) # If some samples are on NA raster values: Print them and stop with error. allEmpty <- lapply(test4na, function(x) nrow(x) == 0) allEmpty <- unlist(allEmpty) if(!all(allEmpty)){ writeLines("\n\nThe following samples are located on NA raster values:\n") print(test4na) stop("The above samples have NA raster values. Please remove the them.") } rm(test4na) gc(verbose = FALSE) return(rp.df) }
/R/get_important_rasters.R
no_license
tkchafin/ClinePlotR
R
false
false
22,493
r
#' Script to extract raster data for all sampling localities #' and find the most important features. #' #' This script takes as input a directory of rasters, crops them to the #' sampling extent, finds the raster values at each sample locality, #' and uses MAXENT and ENMeval to determine the most important raster #' layers (i.e. features). #' #' #' Function to load in and crop the raster layers to the sampling extent #' #' This function takes as input a directory of rasters. Only the desired #' rasters should be included in raster.dir. You also will need a #' comma-delimited sample.file that has four columns in a specific order: #' (sampleIDs,populationIDs,latitude,longitude). You can choose if a header #' line is present. The rasters will all be put into a stack and cropped to #' the extent of the sample localities + bb.buffer. #' @param raster.dir Directory of rasters to load and crop #' @param sample.file CSV file with sample information (sampleID,popID,lat,lon) #' @param header Boolean; Does sample.file have a header line? #' @param bb.buffer Integer; Buffer around sample bounding box. #' bb.buffer = bb.buffer * resolution (in arc-seconds) #' @param plotDIR Directory to save plots to #' @return List with cropped rasters and other info #' @export prepare_rasters <- function(raster.dir, sample.file, header = TRUE, bb.buffer = 10, plotDIR = "./plots"){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } dir.create(plotDIR, showWarnings = FALSE) samples <- read.csv(file = sample.file, header = header, stringsAsFactors = FALSE) # Make sure values are numeric. samples[,3] <- as.numeric(as.character(samples[,3])) samples[,4] <- as.numeric(as.character(samples[,4])) # Get dataframe of longitude, latitude. coords <- data.frame(samples[,4], samples[,3]) # Make into factor for bg color assignment later. pops <- base::as.factor(samples[,2]) # Change column names. colnames(coords) <- c("lng", "lat") # Get raster filenames (all in one directory) files <- list.files(path = raster.dir, full.names = T) writeLines("\n\nOrder of raster files: \n") # Order alphanumerically. files <- gtools::mixedsort(files) for (i in 1:length(files)){ writeLines(paste0(i, ": ", files[i])) } # Put the rasters into a RasterStack. envs <- raster::stack(files) writeLines(paste0("\n\nLoaded ", raster::nlayers(envs), " raster layers..")) # Plot first raster in the stack, bio1. #raster::plot(envs[[1]], main=names(envs)[1]) # Get CRS (coordinate reference system) mycrs <- raster::crs(envs[[1]]) # Create spatialpoints object. p <- sp::SpatialPoints(coords = coords, proj4string=mycrs) # Get the bounding box of the points bb <- raster::bbox(p) # Add (bb.buffer * resolution / 2) to sample bounds for background extent. bb.buf <- raster::extent(bb[1]-bb.buffer, bb[3]+bb.buffer, bb[2]-bb.buffer, bb[4]+bb.buffer) # Add bb.buffer * resolution (in arc-seconds) to bb for cropping raster layer. envs.buf <- raster::extent(bb[1]-(bb.buffer/2), bb[3]+(bb.buffer/2), bb[2]-(bb.buffer/2), bb[4]+(bb.buffer/2)) writeLines(paste0("\n\nCropping to samples with buffer of ", (bb.buffer/2), " degrees\n")) # Crop raster extent to sample bounding box + bb.buffer envs.cropped <- raster::crop(envs, envs.buf) writeLines(paste0("\nCropping background layers with buffer of ", bb.buffer, " degrees\n")) # Crop environmental layers to tmatch the study extent. # Used for background data later. envs.backg <- raster::crop(envs, bb.buf) counter <- 1 # Save raster plots with sample points layered on top pdf(file = file.path(plotDIR, "croppedRasterPlots.pdf"), width = 7, height = 7, onefile = T) for (i in 1:raster::nlayers(envs.backg)){ writeLines(paste0("Saving raster plot ", i, " to disk...")) raster::plot(envs.backg[[i]]) dismo::points(coords, pch=21, bg=pops) counter <- counter+1 } dev.off() envList <- list(envs.cropped, envs.backg, coords, p, pops, samples[,1]) rm(envs, p, bb, bb.buf, envs.buf, envs.cropped, envs.backg) gc(verbose = FALSE) return(envList) } #' Function to make partitions from background and foreground rasters. #' #' This function uses the output from prepare_raster() and makes #' background partitions using several methods. #' @param env.list Object output from prepare_rasters() function #' @param number.bg.points Number of background points to generate #' @param bg.raster Raster to use for background points #' @param agg.factor A vector of 1 or 2 numbers for the checkerboard #' methods #' @param plotDIR Directory to save the plots to #' @return Object with background points #' @export partition_raster_bg <- function(env.list, number.bg.points = 10000, bg.raster = 1, plotDIR = "./plots", agg.factor = 2){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } dir.create(plotDIR, showWarnings = FALSE) bg.raster <- as.integer(as.character(bg.raster)) envs.cropped <- env.list[[1]] envs.backg <- env.list[[2]] coords <- env.list[[3]] p <- env.list[[4]] pops <- env.list[[5]] inds <- env.list[[6]] rm(env.list) gc(verbose = FALSE) writeLines(paste0("\n\nGenerating ", number.bg.points, " random points...")) # Randomly sample 10,000 background points from one background extent raster # (only one per cell without replacement). # Note: If the raster has <10,000 pixels, # you'll get a warning and all pixels will be used for background. bg <- dismo::randomPoints(envs.backg[[bg.raster]], n=number.bg.points) bg <- raster::as.data.frame(bg) # Change column names. colnames(coords) <- c("lng", "lat") rm(pops) gc(verbose = FALSE) writeLines("\nSaving background partition plots...") writeLines("\nPerforming block method...") ### Block Method blocks <- ENMeval::get.block(coords, bg) pdf(file = file.path(plotDIR, "bgPartitions_blocks.pdf"), width = 7, height = 7, onefile = TRUE) raster::plot(envs.backg[[bg.raster]], col="gray", main = "Partitions into Training and Test Data", sub="Block Method", xlab = "Longitude", ylab = "Latitude") dismo::points(coords, pch=21, bg=blocks$occ.grp) dev.off() rm(blocks) gc(verbose = FALSE) writeLines("Performing checkerboard1 method...") ### Checkerboard1 Method check1 <- ENMeval::get.checkerboard1(coords, envs.cropped, bg, aggregation.factor = agg.factor) pdf(file = file.path(plotDIR, "bgPartitions_checkerboard1.pdf"), width = 7, height = 7, onefile = TRUE) raster::plot( envs.backg[[bg.raster]], col="gray", main = "Partitions into Training and Test Data (Aggregation Factor=5)", sub="Checkerboard1 Method", xlab = "Longitude", ylab = "Latitude" ) dismo::points(bg, pch=21, bg=check1$occ.grp) dev.off() rm(check1) gc(verbose = FALSE) writeLines("Performing checkerboard2 method...") ### Using the Checkerboard2 method. check2 <- ENMeval::get.checkerboard2(coords, envs.cropped, bg, aggregation.factor = c(agg.factor, agg.factor)) pdf(file = file.path(plotDIR, "bgPartitions_checkerboard2.pdf"), width = 7, height = 7, onefile = TRUE) raster::plot(envs.backg[[bg.raster]], col="gray", main = "Partitions into Training and Test Data", sub="Checkerboard2 Method", xlab = "Longitude", ylab = "Latitude") dismo::points(bg, pch=21, bg=check2$bg.grp) dismo::points(coords, pch=21, bg=check2$occ.grp, col="white", cex=1.5) dev.off() rm(check2) gc(verbose = FALSE) writeLines("\nDone!") return(bg) } #' Function to run ENMeval and MAXENT on the raster layers. #' #' This function takes as input the object output from preparte_rasters() and #' the background partitioning method you would like to use #' (see ENMeval documentation). You can visualize how the partitioning #' methods will look by viewing the PDF output from partition_raster_bg. #' See ?partition_raster_bg for more info. #' @param envs.fg First element of envs.list returned from prepare_raster_bg() #' @param bg Object with background points; generated from partition_raster_bg #' @param coords Data.Frame with (lon,lat). 3rd element of envs.list #' @param partition.method Method used for background point partitioning #' @param parallel If TRUE, ENMeval is run parallelized with np CPU cores #' @param np Number of parallel cores to use if parallel = TRUE #' @param RMvalues Vector of non-negative regularization multiplier values. #' Higher values impose a stronger penalty on model complexity #' @param feature.classes Character vector of feature classes to be used #' @param categoricals Vector indicating which (if any) of the input #' environmental layers are categorical. #' @param agg.factor Aggregation factor(s) for checkerboard #' partitioning method. #' @param algorithm Character vector. Defaults to dismo's maxent.jar #' @return ENMeval object #' @export runENMeval <- function(envs.fg, bg, coords, partition.method, parallel = FALSE, np = 2, RMvalues = seq(0.5, 4, 0.5), feature.classes = c("L", "LQ", "H", "LQH", "LQHP", "LQHPT"), categoricals = NULL, agg.factor = 2, algorithm = "maxent.jar" ){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } if (partition.method == "checkerboard2"){ agg.factor <- c(agg.factor, agg.factor) } if (parallel == TRUE){ eval.par <- ENMeval::ENMevaluate( occ = coords, env = envs.fg, bg.coords = bg, method = partition.method, RMvalues = RMvalues, fc = feature.classes, parallel = parallel, algorithm = algorithm, categoricals = categoricals, aggregation.factor = agg.factor, numCores = np ) } else if (parallel == FALSE){ eval.par <- ENMeval::ENMevaluate( occ = coords, env = envs.fg, bg.coords = bg, method = partition.method, RMvalues = RMvalues, fc = feature.classes, parallel = parallel, algorithm = algorithm, categoricals = categoricals, aggregation.factor = agg.factor ) } else { stop("Parallel must be either TRUE or FALSE") } return(eval.par) } #' Function to summarize ENMeval output #' @param eval.par Object returned from runENMeval #' @param minLat Minimum latitude to plot for predictions #' @param maxLat Maximum latitude to plot for predictions #' @param minLon Minimum longitude to plot for predictions #' @param maxLon Maximum longitude to plot for predictions #' @param examine.predictions Character vector of feature classes to examine #' how complexity affects predictions #' @param RMvalues Vector of non-negative RM values to examine how #' complexity affects predictions #' @param plotDIR Directory to save plots to #' @param niche.overlap Boolean. If TRUE, calculates pairwise niche overlap #' matrix #' @param plot.width Integer. Specify plot widths #' @param plot.height Integer. Specify plot heights #' @param imp.margins Integer vector. Margins of variable importance barplot. #' c(bottom, left, top, right) #' @export summarize_ENMeval <- function(eval.par, minLat = 20, maxLat = 50, minLon = -110, maxLon = -40, examine.predictions = c("L", "LQ", "H", "LQH", "LQHP", "LQHPT"), RMvalues = seq(0.5, 4, 0.5), plotDIR = "./plots", niche.overlap = FALSE, plot.width = 7, plot.height = 7, imp.margins = c(10.0, 4.1, 4.1, 2.1)){ dir.create(plotDIR, showWarnings = FALSE) if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } if (niche.overlap){ # Calculate niche overlap. overlap <- ENMeval::calc.niche.overlap(eval.par@predictions, stat="D") # Write niche overlap to a file. write.csv(x = overlap, file = file.path(plotDIR, "ENMeval_nicheOverlap.csv")) } # Write ENMeval results to file. write.csv(x = eval.par@results, file = file.path(plotDIR, "ENMeval_results.csv")) # Get best model. eval.par@results[which(eval.par@results$delta.AICc==0),] eval.par@results[which(eval.par@results$delta.AICc==0),] bestAICc <- eval.par@results[which(eval.par@results$delta.AICc==0),] # Write to file. write.csv(bestAICc, file = file.path(plotDIR, "ENMeval_bestAICc.csv")) # Save it to file. pdf(file = file.path(plotDIR, "ENMeval_relativeOccurenceRate_bestModel.pdf"), width = plot.width, height = plot.height, onefile = TRUE) raster::plot(eval.par@predictions[[which(eval.par@results$delta.AICc==0)]], main="Relative Occurrence Rate") dev.off() # Look at the model object for our "AICc optimal" model: aic.opt <- eval.par@models[[which(eval.par@results$delta.AICc==0)]] # Write it to file. write.csv(x = aic.opt@results, file = file.path(plotDIR, "ENMeval_maxentModel_aicOptimal.csv")) # Get a data.frame of two variable importance metrics: # percent contribution and permutation importance. varImportance <- ENMeval::var.importance(aic.opt) # Write them to file. write.csv(varImportance, file = file.path(plotDIR, "ENMeval_varImportance.csv")) # The "lambdas" slot shows which variables were included in the model. # If the coefficient is 0, that variable was not included in the model. lambdas <- aic.opt@lambdas write.csv(lambdas, file = file.path(plotDIR, "ENMeval_lambdas.csv")) pdf(file = file.path(plotDIR, "ENMeval_AUC_importancePlots.pdf"), width = plot.width, height = plot.height, onefile = TRUE) ENMeval::eval.plot(eval.par@results) ENMeval::eval.plot(eval.par@results, 'avg.test.AUC', variance ='var.test.AUC') ENMeval::eval.plot(eval.par@results, "avg.diff.AUC", variance="var.diff.AUC") # Plot permutation importance. df <- ENMeval::var.importance(aic.opt) par(mar=imp.margins) raster::barplot(df$permutation.importance, names.arg = df$variable, las = 2, ylab = "Permutation Importance") dev.off() # Let's see how model complexity changes the predictions in our example pdf(file = file.path(plotDIR, "modelPredictions.pdf"), width = plot.width, height = plot.height, onefile = TRUE) for (i in 1:length(examine.predictions)){ for (j in 1:length(RMvalues)){ raster::plot(eval.par@predictions[[paste(examine.predictions[i], RMvalues[j], sep = "_")]], ylim=c(minLat,maxLat), xlim=c(minLon, maxLon), main=paste0(examine.predictions[i], "_", RMvalues[j], " Prediction"), ) } } dev.off() } #' Function to extract raster values at each sample point for raster stack #' @param env.list List object generated from prepare_rasters() #' @return List of data.frames with raster values at each sample locality #' for each raster layer, and list of raster names #' @export extractPointValues <- function(env.list){ if (!requireNamespace("raster", quietly = TRUE)){ warning("The raster package must be installed to use this functionality") return(NULL) } if(!requireNamespace("sp", quietly = TRUE)){ warning("The sp package must be installed to use this functionality") return(NULL) } if(!requireNamespace("dismo", quietly = TRUE)){ warning("The dismo package must be installed to use this functionality") return(NULL) } if(!requireNamespace("rJava", quietly = TRUE)){ warning("The rJava package must be installed to use this functionality") return(NULL) } if(!requireNamespace("ENMeval", quietly = TRUE)){ warning("The ENMeval package must be installed to use this functionality") return(NULL) } envs.cropped <- env.list[[1]] p <- env.list[[4]] inds <- env.list[[6]] raster.points <- list() writeLines("\nExtracting raster values at sample points") # Extract raster values at each sample point. for (i in 1:raster::nlayers(envs.cropped)){ raster.points[[i]] <- raster::extract(envs.cropped[[i]], p) } writeLines("\nAdding sampleIDs to raster dataframe") # Add sample IDs to point/raster value dataframe. rp.df <- lapply(raster.points, function(x) { cbind.data.frame( inds, raster::coordinates(p), x ) } ) rasterNames <- env.list[[1]]@data@names # Use raster name as x colname for (i in 1:length(rasterNames)){ colnames(rp.df[[i]]) <- c("inds", "lng", "lat", rasterNames[i]) } rm(raster.points) gc(verbose = FALSE) # Get which samples are on NA raster values. test4na <- lapply(rp.df, function(x) x[raster::rowSums(is.na(x)) > 0,]) # If some samples are on NA raster values: Print them and stop with error. allEmpty <- lapply(test4na, function(x) nrow(x) == 0) allEmpty <- unlist(allEmpty) if(!all(allEmpty)){ writeLines("\n\nThe following samples are located on NA raster values:\n") print(test4na) stop("The above samples have NA raster values. Please remove the them.") } rm(test4na) gc(verbose = FALSE) return(rp.df) }
library(MNM) ### Name: affine.trans ### Title: Function For Affine Data Transformation ### Aliases: affine.trans ### Keywords: multivariate ### ** Examples data(iris) IRIS <- iris[,1:4] colMeans(IRIS) cov(IRIS) IRIS.trans <- affine.trans(IRIS, solve(cov(IRIS)), colMeans(IRIS),TRUE) colMeans(IRIS.trans) cov(IRIS.trans)
/data/genthat_extracted_code/MNM/examples/affine.trans.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
327
r
library(MNM) ### Name: affine.trans ### Title: Function For Affine Data Transformation ### Aliases: affine.trans ### Keywords: multivariate ### ** Examples data(iris) IRIS <- iris[,1:4] colMeans(IRIS) cov(IRIS) IRIS.trans <- affine.trans(IRIS, solve(cov(IRIS)), colMeans(IRIS),TRUE) colMeans(IRIS.trans) cov(IRIS.trans)
library(ggplot2) data = read.csv("../strongscaling.csv") data$Fragments = as.factor(data$Fragments) str(data) ggplot(data, aes(x = Processors, y = Efficiency.S, color = Fragments)) + geom_point(size = 3, aes(shape = Fragments)) + scale_shape_manual(values = c(15,19,17,8)) + geom_line(size = 1) + scale_x_log10(breaks = c(128, 256, 512, 1024, 2048, 4096, 8192, 16384)) + #scale_y_continuous(breaks = c(1, 2, 3, 4, 5)) + xlab("Number of Cores") + ylab("Efficiency") + #ggtitle("") + theme_bw() ggsave("../../strong-efficiency.pdf", last_plot())
/plots/scripts/strong-efficiency.r
no_license
sumitkrpandit/DNASequencing
R
false
false
572
r
library(ggplot2) data = read.csv("../strongscaling.csv") data$Fragments = as.factor(data$Fragments) str(data) ggplot(data, aes(x = Processors, y = Efficiency.S, color = Fragments)) + geom_point(size = 3, aes(shape = Fragments)) + scale_shape_manual(values = c(15,19,17,8)) + geom_line(size = 1) + scale_x_log10(breaks = c(128, 256, 512, 1024, 2048, 4096, 8192, 16384)) + #scale_y_continuous(breaks = c(1, 2, 3, 4, 5)) + xlab("Number of Cores") + ylab("Efficiency") + #ggtitle("") + theme_bw() ggsave("../../strong-efficiency.pdf", last_plot())
##### Global: options ##### Production = T options(scipen = 1000, expressions = 10000) appVersion = "v2.0" appName = "COVID-19 Data Visualization Platform" appLongName = "COVID-19 Data Visualization Platform" lastUpdate = "2020-04-07" loader <- tagList( waiter::spin_loaders(42), br(), h3("Loading data") ) jsToggleFS <- 'shinyjs.toggleFullScreen = function() { var element = document.documentElement, enterFS = element.requestFullscreen || element.msRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen, exitFS = document.exitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen; if (!document.fullscreenElement && !document.msFullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) { enterFS.call(element); } else { exitFS.call(document); } }' source("appFiles/packageLoad.R") source("appFiles/dataLoad.R") source("appFiles/CSS.R", local = TRUE) source("appFiles/dashboardPage.R", local = TRUE) ##### User interface ##### ui <- tagList( # dependencies use_waiter(), useSweetAlert(), useShinyjs(), extendShinyjs(text = jsToggleFS), waiter::waiter_show_on_load(loader, color = "#000"), # shows before anything else ##### CSS and style functions ##### CSS, #CSS.R # Loading message argonDash::argonDashPage( title = appLongName, header = argonDash::argonDashHeader( gradient = T, color = NULL, top_padding = 2, bottom_padding = 0, background_img = "coronavirus.jpg", height = 70, argonRow( argonColumn(width = 8, h4(appLongName, style = 'color:white; text-align:left; vertical-align: middle; font-size:40px;') ), argonColumn( width = 4, h6(HTML(paste0("Creator & Maintainer: <a href='https://www.shubhrampandey.com' target = '_blank'>Shubhram Pandey</a>")), style = 'color:white; text-align: right; font-size:15px; margin-bottom: 0em'), h6(HTML(paste0("<a href='https://www.3ai.in' target = '_blank'> - 3AI Ambassdor</a>")), style = 'color:white;text-align: right;font-size:15px;') ), fixedPanel( div( actionBttn("fullScreen", style = "material-circle", icon = icon("arrows-alt"), size = "xs", color = "warning"), bsPopover("fullScreen", title = NULL, content = "Click to view in full screen", placement = "left", trigger = "hover", options = NULL), onclick = "shinyjs.toggleFullScreen();" ), top = 55, right = 10 ), fixedPanel( div( actionBttn("kofi", style = "material-circle", icon = icon("coffee"), size = "xs", color = "success"), bsPopover("kofi", title = NULL, content = "Buy me a coffee", placement = "left", trigger = "hover", options = NULL), onclick = "window.open('https://ko-fi.com/shubhrampandey', '_blank')" ), top = 55, right = 40 ), fixedPanel( div( actionBttn("userGuide", style = "material-circle", icon = icon("info"), size = "xs", color = "royal"), bsPopover("userGuide", title = NULL, content = "Go to app help page", placement = "left", trigger = "hover", options = NULL), onclick = "window.open('https://sites.google.com/view/covid-19-userguide/home', '_blank')" ), top = 55, right = 70 ), fixedPanel( div( actionBttn("webSite", style = "material-circle", icon = icon("address-card"), size = "xs", color = "primary"), bsPopover("webSite", title = NULL, content = "About developer", placement = "left", trigger = "hover", options = NULL), onclick = "window.open('https://www.shubhrampandey.com', '_blank')" ), top = 55, right = 100 ) ) ), sidebar = NULL, body = argonDashBody( tags$head( tags$meta(name = "viewport", content = "width=1600"),uiOutput("body")), tags$br(), dashboardUI ) ) ) ##### server ##### server <- function(input, output, session) { printLogJs = function(x, ...) { logjs(x) T } # addHandler(printLogJs) if (!Production) options(shiny.error = recover) options(shiny.sanitize.errors = TRUE, width = 160) session$onSessionEnded(function() { stopApp() # q("no") }) source("appFiles/dashboardServer.R", local = TRUE) # Hide the loading message when the rest of the server function has executed waiter_hide() # will hide *on_load waiter } # Run the application shinyApp(ui = ui, server = server)
/app.R
no_license
champasoft/coronaVirus-dataViz
R
false
false
5,380
r
##### Global: options ##### Production = T options(scipen = 1000, expressions = 10000) appVersion = "v2.0" appName = "COVID-19 Data Visualization Platform" appLongName = "COVID-19 Data Visualization Platform" lastUpdate = "2020-04-07" loader <- tagList( waiter::spin_loaders(42), br(), h3("Loading data") ) jsToggleFS <- 'shinyjs.toggleFullScreen = function() { var element = document.documentElement, enterFS = element.requestFullscreen || element.msRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen, exitFS = document.exitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen; if (!document.fullscreenElement && !document.msFullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) { enterFS.call(element); } else { exitFS.call(document); } }' source("appFiles/packageLoad.R") source("appFiles/dataLoad.R") source("appFiles/CSS.R", local = TRUE) source("appFiles/dashboardPage.R", local = TRUE) ##### User interface ##### ui <- tagList( # dependencies use_waiter(), useSweetAlert(), useShinyjs(), extendShinyjs(text = jsToggleFS), waiter::waiter_show_on_load(loader, color = "#000"), # shows before anything else ##### CSS and style functions ##### CSS, #CSS.R # Loading message argonDash::argonDashPage( title = appLongName, header = argonDash::argonDashHeader( gradient = T, color = NULL, top_padding = 2, bottom_padding = 0, background_img = "coronavirus.jpg", height = 70, argonRow( argonColumn(width = 8, h4(appLongName, style = 'color:white; text-align:left; vertical-align: middle; font-size:40px;') ), argonColumn( width = 4, h6(HTML(paste0("Creator & Maintainer: <a href='https://www.shubhrampandey.com' target = '_blank'>Shubhram Pandey</a>")), style = 'color:white; text-align: right; font-size:15px; margin-bottom: 0em'), h6(HTML(paste0("<a href='https://www.3ai.in' target = '_blank'> - 3AI Ambassdor</a>")), style = 'color:white;text-align: right;font-size:15px;') ), fixedPanel( div( actionBttn("fullScreen", style = "material-circle", icon = icon("arrows-alt"), size = "xs", color = "warning"), bsPopover("fullScreen", title = NULL, content = "Click to view in full screen", placement = "left", trigger = "hover", options = NULL), onclick = "shinyjs.toggleFullScreen();" ), top = 55, right = 10 ), fixedPanel( div( actionBttn("kofi", style = "material-circle", icon = icon("coffee"), size = "xs", color = "success"), bsPopover("kofi", title = NULL, content = "Buy me a coffee", placement = "left", trigger = "hover", options = NULL), onclick = "window.open('https://ko-fi.com/shubhrampandey', '_blank')" ), top = 55, right = 40 ), fixedPanel( div( actionBttn("userGuide", style = "material-circle", icon = icon("info"), size = "xs", color = "royal"), bsPopover("userGuide", title = NULL, content = "Go to app help page", placement = "left", trigger = "hover", options = NULL), onclick = "window.open('https://sites.google.com/view/covid-19-userguide/home', '_blank')" ), top = 55, right = 70 ), fixedPanel( div( actionBttn("webSite", style = "material-circle", icon = icon("address-card"), size = "xs", color = "primary"), bsPopover("webSite", title = NULL, content = "About developer", placement = "left", trigger = "hover", options = NULL), onclick = "window.open('https://www.shubhrampandey.com', '_blank')" ), top = 55, right = 100 ) ) ), sidebar = NULL, body = argonDashBody( tags$head( tags$meta(name = "viewport", content = "width=1600"),uiOutput("body")), tags$br(), dashboardUI ) ) ) ##### server ##### server <- function(input, output, session) { printLogJs = function(x, ...) { logjs(x) T } # addHandler(printLogJs) if (!Production) options(shiny.error = recover) options(shiny.sanitize.errors = TRUE, width = 160) session$onSessionEnded(function() { stopApp() # q("no") }) source("appFiles/dashboardServer.R", local = TRUE) # Hide the loading message when the rest of the server function has executed waiter_hide() # will hide *on_load waiter } # Run the application shinyApp(ui = ui, server = server)
make_time_aligner <- function(alignment_variable, ahead, threshold = 500){ days_since_threshold_attained_first_time_aligner <- function(df_use, forecast_date){ stopifnot(alignment_variable %in% unique(df_use %>% pull(variable_name))) df_alignment_variable <- df_use %>% filter(variable_name == alignment_variable) day0 <- df_alignment_variable %>% arrange(geo_value, time_value) %>% group_by(location, geo_value, variable_name) %>% mutate(cumul_value = cumsum(value)) %>% arrange(variable_name, geo_value, time_value) %>% filter(cumul_value >= threshold) %>% group_by(location) %>% summarize(value = min(time_value), .groups = "drop") locations <- df_use %>% pull(location) %>% unique train_dates <- df_use %>% pull(time_value) %>% unique target_dates <- get_target_period(forecast_date, incidence_period = "epiweek", ahead) %$% seq(start, end, by = "days") dates <- unique(c(train_dates, target_dates)) df_align <- expand_grid(location = locations, time_value = dates) %>% left_join(day0, by = "location") %>% mutate(align_date = ifelse(time_value - value >= 0, time_value - value, NA)) %>% select(-value) return(df_align) } }
/forecasters/aardvark/R/time_alignment.R
permissive
mjl2241/covid-19-forecast
R
false
false
1,250
r
make_time_aligner <- function(alignment_variable, ahead, threshold = 500){ days_since_threshold_attained_first_time_aligner <- function(df_use, forecast_date){ stopifnot(alignment_variable %in% unique(df_use %>% pull(variable_name))) df_alignment_variable <- df_use %>% filter(variable_name == alignment_variable) day0 <- df_alignment_variable %>% arrange(geo_value, time_value) %>% group_by(location, geo_value, variable_name) %>% mutate(cumul_value = cumsum(value)) %>% arrange(variable_name, geo_value, time_value) %>% filter(cumul_value >= threshold) %>% group_by(location) %>% summarize(value = min(time_value), .groups = "drop") locations <- df_use %>% pull(location) %>% unique train_dates <- df_use %>% pull(time_value) %>% unique target_dates <- get_target_period(forecast_date, incidence_period = "epiweek", ahead) %$% seq(start, end, by = "days") dates <- unique(c(train_dates, target_dates)) df_align <- expand_grid(location = locations, time_value = dates) %>% left_join(day0, by = "location") %>% mutate(align_date = ifelse(time_value - value >= 0, time_value - value, NA)) %>% select(-value) return(df_align) } }
readType <- function(x) { ret <- list() ret$type <- "character" ret$mode <- NULL ret$labels <- NULL ret$min <- -Inf ret$max <- +Inf if (xmlName(x) == "type") { ## FIXME: why is the seq_along() statement needed?? x <- x[sapply(x[seq_along(x)], xmlName) != "text"][[1]] ret$type <- xmlName(x) if (ret$type == "categorical") { ## mode ret$mode <- xmlAttrs(x)["mode"] ## labels ind <- 1 for (k in 1:xmlSize(x)) { if (xmlName(x[[k]]) != "text") { code <- as.integer(xmlAttrs(x[[k]])["code"]) children <- xmlChildren(x[[k]]) lab <- if (length(children)) children else NULL ret$labels[code] <- if (is.null(lab)) ind else xmlValue(lab[[1]]) ind <- ind + 1 } } } if (ret$type == "numeric") { if (!length(xmlChildren(x))) ret$mode <- "real" else { x <- x[sapply(x[seq_along(x)], xmlName) != "text"][[1]] ret$mode <- xmlName(x) l <- length(xmlChildren(x)) if (ret$mode %in% c("integer", "real") && l) for (i in seq_len(l)) if (xmlName(x[[i]]) != "text") ret[[xmlName(x[[i]])]] <- getDataSDML(x[i]) } } } ret }
/R/readTypeSDML.R
no_license
cran/StatDataML
R
false
false
1,564
r
readType <- function(x) { ret <- list() ret$type <- "character" ret$mode <- NULL ret$labels <- NULL ret$min <- -Inf ret$max <- +Inf if (xmlName(x) == "type") { ## FIXME: why is the seq_along() statement needed?? x <- x[sapply(x[seq_along(x)], xmlName) != "text"][[1]] ret$type <- xmlName(x) if (ret$type == "categorical") { ## mode ret$mode <- xmlAttrs(x)["mode"] ## labels ind <- 1 for (k in 1:xmlSize(x)) { if (xmlName(x[[k]]) != "text") { code <- as.integer(xmlAttrs(x[[k]])["code"]) children <- xmlChildren(x[[k]]) lab <- if (length(children)) children else NULL ret$labels[code] <- if (is.null(lab)) ind else xmlValue(lab[[1]]) ind <- ind + 1 } } } if (ret$type == "numeric") { if (!length(xmlChildren(x))) ret$mode <- "real" else { x <- x[sapply(x[seq_along(x)], xmlName) != "text"][[1]] ret$mode <- xmlName(x) l <- length(xmlChildren(x)) if (ret$mode %in% c("integer", "real") && l) for (i in seq_len(l)) if (xmlName(x[[i]]) != "text") ret[[xmlName(x[[i]])]] <- getDataSDML(x[i]) } } } ret }
source("../R.xtables/fun.R") source("../R.xtables/xtabularAssay.R") source("../R.xtables/xtablesAssay.R") source("../R.xtables/xtableHead.R") source("../R.xtables/xtableLabels.R") source("../R.xtables/xtableLatinSquare.R") source("../R.xtables/xtableTableCS.R") source("../R.xtables/xtableTable.R") source("../R.xtables/xtableModel.R") source("../R.xtables/xtableAnova.R") source("../R.xtables/xtableParameters.R") source("../R.xtables/xtableValidity.R") source("../R.xtables/xtablePotency.R")
/pla/inst/scripts/R/xtables.bak.R
no_license
ingted/R-Examples
R
false
false
494
r
source("../R.xtables/fun.R") source("../R.xtables/xtabularAssay.R") source("../R.xtables/xtablesAssay.R") source("../R.xtables/xtableHead.R") source("../R.xtables/xtableLabels.R") source("../R.xtables/xtableLatinSquare.R") source("../R.xtables/xtableTableCS.R") source("../R.xtables/xtableTable.R") source("../R.xtables/xtableModel.R") source("../R.xtables/xtableAnova.R") source("../R.xtables/xtableParameters.R") source("../R.xtables/xtableValidity.R") source("../R.xtables/xtablePotency.R")
### R code from vignette source 'compareGroups_vignette.rnw' ### Encoding: ISO8859-1 ################################################### ### code chunk number 1: compareGroups_vignette.rnw:106-107 ################################################### library(compareGroups) ################################################### ### code chunk number 2: compareGroups_vignette.rnw:152-153 ################################################### data(predimed) ################################################### ### code chunk number 3: compareGroups_vignette.rnw:160-168 ################################################### dicc<-data.frame( "Name"=I(names(predimed)), "Label"=I(unlist(lapply(predimed,label))), "Codes"=I(unlist(lapply(predimed,function(x) paste(levels(x),collapse="; ")))) ) dicc$Codes<-sub(">=","$\\\\geq$",dicc$Codes) #print(xtable(dicc,align=rep("l",4)),include.rownames=FALSE,size="small",tabular.environment="longtable", sanitize.text.function=function(x) x) print(xtable(dicc,align=rep("l",4)),include.rownames=FALSE,size="small", sanitize.text.function=function(x) x) ################################################### ### code chunk number 4: compareGroups_vignette.rnw:194-196 ################################################### predimed$tmain <- with(predimed, Surv(toevent, event == 'Yes')) label(predimed$tmain) <- "AMI, stroke, or CV Death" ################################################### ### code chunk number 5: compareGroups_vignette.rnw:216-217 ################################################### compareGroups(group ~ . , data=predimed) ################################################### ### code chunk number 6: compareGroups_vignette.rnw:228-229 ################################################### compareGroups(group ~ . -toevent - event, data=predimed) ################################################### ### code chunk number 7: compareGroups_vignette.rnw:236-238 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed) res ################################################### ### code chunk number 8: compareGroups_vignette.rnw:257-259 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, subset = sex=='Female') ################################################### ### code chunk number 9: compareGroups_vignette.rnw:266-267 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 10: compareGroups_vignette.rnw:270-272 ################################################### compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed, selec = list(hormo= sex=="Female", waist = waist>20 )) ################################################### ### code chunk number 11: compareGroups_vignette.rnw:277-278 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 12: compareGroups_vignette.rnw:281-283 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, selec = list(waist= !is.na(hormo)), subset = sex=="Female") ################################################### ### code chunk number 13: compareGroups_vignette.rnw:289-290 ################################################### options(width=80,keep.source=TRUE) ################################################### ### code chunk number 14: compareGroups_vignette.rnw:292-294 ################################################### compareGroups(group ~ age + sex + bmi + bmi + waist + hormo, data=predimed, selec = list(bmi.1=!is.na(hormo))) ################################################### ### code chunk number 15: compareGroups_vignette.rnw:307-308 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 16: compareGroups_vignette.rnw:310-312 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=2)) ################################################### ### code chunk number 17: compareGroups_vignette.rnw:314-315 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 18: compareGroups_vignette.rnw:330-331 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 19: compareGroups_vignette.rnw:333-335 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=NA), alpha= 0.01) ################################################### ### code chunk number 20: compareGroups_vignette.rnw:337-338 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 21: compareGroups_vignette.rnw:347-351 ################################################### cuts<-"lo:55=1; 56:60=2; 61:65=3; 66:70=4; 71:75=5; 76:80=6; 81:hi=7" predimed$age7gr<-car::recode(predimed$age, cuts) compareGroups(group ~ age7gr, data=predimed, method = c(age7gr=NA)) compareGroups(group ~ age7gr, data=predimed, method = c(age7gr=NA), min.dis=8) ################################################### ### code chunk number 22: compareGroups_vignette.rnw:367-368 ################################################### compareGroups(age7gr ~ sex + bmi + waist, data=predimed, max.ylev=7) ################################################### ### code chunk number 23: compareGroups_vignette.rnw:373-374 ################################################### compareGroups(group ~ sex + age7gr, method= (age7gr=3), data=predimed, max.xlev=5) ################################################### ### code chunk number 24: compareGroups_vignette.rnw:392-394 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, include.label= FALSE) ################################################### ### code chunk number 25: compareGroups_vignette.rnw:401-402 ################################################### options(width=80, keep.source=FALSE) ################################################### ### code chunk number 26: compareGroups_vignette.rnw:405-408 ################################################### resu1<-compareGroups(group ~ age + waist, data=predimed, method = c(waist=2)) createTable(resu1) ################################################### ### code chunk number 27: compareGroups_vignette.rnw:415-418 ################################################### resu2<-compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=2), Q1=0.025, Q3=0.975) createTable(resu2) ################################################### ### code chunk number 28: compareGroups_vignette.rnw:425-426 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 29: compareGroups_vignette.rnw:430-431 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 30: compareGroups_vignette.rnw:433-435 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=2), Q1=0, Q3=1) ################################################### ### code chunk number 31: compareGroups_vignette.rnw:437-438 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 32: compareGroups_vignette.rnw:445-449 ################################################### predimed$smk<-predimed$smoke levels(predimed$smk)<- c("Never smoker", "Current or former < 1y", "Never or former >= 1y", "Unknown") label(predimed$smk)<-"Smoking 4 cat." cbind(table(predimed$smk)) ################################################### ### code chunk number 33: compareGroups_vignette.rnw:482-483 ################################################### compareGroups(group ~ age + smk, data=predimed, simplify=FALSE) ################################################### ### code chunk number 34: compareGroups_vignette.rnw:514-517 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, method = c(waist=2), data=predimed) summary(res[c(1, 2, 4)]) ################################################### ### code chunk number 35: compareGroups_vignette.rnw:530-531 ################################################### plot(res[c(1,2)], file="./figures/univar/", type="pdf") ################################################### ### code chunk number 36: compareGroups_vignette.rnw:549-550 ################################################### plot(res[c(1,2)], bivar=TRUE, file="./figures/bivar/") ################################################### ### code chunk number 37: compareGroups_vignette.rnw:574-576 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed) res ################################################### ### code chunk number 38: compareGroups_vignette.rnw:581-582 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 39: compareGroups_vignette.rnw:584-586 ################################################### res<-update(res, . ~. - sex + bmi + toevent, subset = sex=='Female', method = c(waist=2, tovent=2), selec = list(bmi=!is.na(hormo))) ################################################### ### code chunk number 40: compareGroups_vignette.rnw:588-589 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 41: compareGroups_vignette.rnw:591-592 ################################################### res ################################################### ### code chunk number 42: compareGroups_vignette.rnw:606-612 ################################################### library(SNPassoc) data(SNPs) tab <- createTable(compareGroups(casco ~ snp10001 + snp10002 + snp10005 + snp10008 + snp10009, SNPs)) pvals <- getResults(tab, "p.overall") p.adjust(pvals, method = "BH") ################################################### ### code chunk number 43: compareGroups_vignette.rnw:629-631 ################################################### res1<-compareGroups(htn ~ age + sex + bmi + smoke, data=predimed, ref=1) createTable(res1, show.ratio=TRUE) ################################################### ### code chunk number 44: compareGroups_vignette.rnw:637-638 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 45: compareGroups_vignette.rnw:640-643 ################################################### res2<-compareGroups(htn ~ age + sex + bmi + smoke, data=predimed, ref=c(smoke=1, sex=2)) createTable(res2, show.ratio=TRUE) ################################################### ### code chunk number 46: compareGroups_vignette.rnw:648-649 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 47: compareGroups_vignette.rnw:656-659 ################################################### res<-compareGroups(htn ~ age + sex + bmi + hormo + hyperchol, data=predimed, ref.no='NO') createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 48: compareGroups_vignette.rnw:668-670 ################################################### res<-compareGroups(htn ~ age + bmi, data=predimed) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 49: compareGroups_vignette.rnw:675-676 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 50: compareGroups_vignette.rnw:678-681 ################################################### res<-compareGroups(htn ~ age + bmi, data=predimed, fact.ratio= c(age=10, bmi=2)) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 51: compareGroups_vignette.rnw:683-684 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 52: compareGroups_vignette.rnw:693-695 ################################################### res<-compareGroups(htn ~ age + sex + bmi + hyperchol, data=predimed) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 53: compareGroups_vignette.rnw:701-703 ################################################### res<-compareGroups(htn ~ age + sex + bmi + hyperchol, data=predimed, ref.y=2) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 54: compareGroups_vignette.rnw:717-719 ################################################### plot(compareGroups(tmain ~ sex, data=predimed), bivar=TRUE, file="./figures/bivar/") plot(compareGroups(tmain ~ age, data=predimed), bivar=TRUE, file="./figures/bivar/") ################################################### ### code chunk number 55: compareGroups_vignette.rnw:754-755 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 56: compareGroups_vignette.rnw:757-760 ################################################### res<-compareGroups(sex ~ age + tmain, timemax=c(tmain=3), data=predimed) res ################################################### ### code chunk number 57: compareGroups_vignette.rnw:762-763 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 58: compareGroups_vignette.rnw:772-774 ################################################### plot(res[2], file="./figures/univar/") plot(res[2], bivar=TRUE, file="./figures/bivar/") ################################################### ### code chunk number 59: compareGroups_vignette.rnw:799-800 ################################################### options(width=100,keep.source=FALSE) ################################################### ### code chunk number 60: compareGroups_vignette.rnw:803-806 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed, selec = list(hormo=sex=="Female")) restab<-createTable(res) ################################################### ### code chunk number 61: compareGroups_vignette.rnw:811-812 ################################################### print(restab,which.table='descr') ################################################### ### code chunk number 62: compareGroups_vignette.rnw:817-818 ################################################### print(restab,which.table='avail') ################################################### ### code chunk number 63: compareGroups_vignette.rnw:834-835 ################################################### update(restab, hide = c(sex="Male")) ################################################### ### code chunk number 64: compareGroups_vignette.rnw:844-846 ################################################### res<-compareGroups(group ~ age + sex + htn + diab, data=predimed) createTable(res, hide.no='no', hide = c(sex="Male")) ################################################### ### code chunk number 65: compareGroups_vignette.rnw:855-856 ################################################### createTable(res, digits= c(age=2, sex = 3)) ################################################### ### code chunk number 66: compareGroups_vignette.rnw:865-866 ################################################### createTable(res, type=1) ################################################### ### code chunk number 67: compareGroups_vignette.rnw:871-872 ################################################### createTable(res, type=3) ################################################### ### code chunk number 68: compareGroups_vignette.rnw:884-885 ################################################### createTable(res, show.n=TRUE) ################################################### ### code chunk number 69: compareGroups_vignette.rnw:892-893 ################################################### createTable(res, show.descr=FALSE) ################################################### ### code chunk number 70: compareGroups_vignette.rnw:900-901 ################################################### createTable(res, show.all=TRUE) ################################################### ### code chunk number 71: compareGroups_vignette.rnw:907-908 ################################################### createTable(res, show.p.overall=FALSE) ################################################### ### code chunk number 72: compareGroups_vignette.rnw:915-916 ################################################### createTable(res, show.p.trend=TRUE) ################################################### ### code chunk number 73: compareGroups_vignette.rnw:926-927 ################################################### createTable(res, show.p.mul=TRUE) ################################################### ### code chunk number 74: compareGroups_vignette.rnw:933-934 ################################################### createTable(update(res, subset= group!="Control diet"), show.ratio=TRUE) ################################################### ### code chunk number 75: compareGroups_vignette.rnw:939-941 ################################################### createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.ratio=TRUE) ################################################### ### code chunk number 76: compareGroups_vignette.rnw:950-952 ################################################### createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.ratio=TRUE, digits.ratio= 3) ################################################### ### code chunk number 77: compareGroups_vignette.rnw:959-962 ################################################### tab<-createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.all = TRUE) print(tab, header.labels = c("p.overall" = "p-value", "all" = "All")) ################################################### ### code chunk number 78: compareGroups_vignette.rnw:974-977 ################################################### restab1 <- createTable(compareGroups(group ~ age + sex, data=predimed)) restab2 <- createTable(compareGroups(group ~ bmi + smoke, data=predimed)) rbind("Non-modifiable risk factors"=restab1, "Modifiable risk factors"=restab2) ################################################### ### code chunk number 79: compareGroups_vignette.rnw:990-991 ################################################### rbind("Non-modifiable"=restab1,"Modifiable"=restab2)[c(1,4)] ################################################### ### code chunk number 80: compareGroups_vignette.rnw:996-997 ################################################### rbind("Modifiable"=restab1,"Non-modifiable"=restab2)[c(4,3,2,1)] ################################################### ### code chunk number 81: compareGroups_vignette.rnw:1008-1013 ################################################### res<-compareGroups(group ~ age + smoke + bmi + htn , data=predimed) alltab <- createTable(res, show.p.overall = FALSE) femaletab <- createTable(update(res,subset=sex=='Female'), show.p.overall = FALSE) maletab <- createTable(update(res,subset=sex=='Male'), show.p.overall = FALSE) cbind("ALL"=alltab,"FEMALE"=femaletab,"MALE"=maletab) ################################################### ### code chunk number 82: compareGroups_vignette.rnw:1018-1019 ################################################### cbind(alltab,femaletab,maletab,caption=NULL) ################################################### ### code chunk number 83: compareGroups_vignette.rnw:1024-1025 ################################################### cbind(alltab,femaletab,maletab) ################################################### ### code chunk number 84: compareGroups_vignette.rnw:1038-1040 ################################################### print(createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)), which.table='both') ################################################### ### code chunk number 85: compareGroups_vignette.rnw:1043-1045 ################################################### print(createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)), nmax=FALSE) ################################################### ### code chunk number 86: compareGroups_vignette.rnw:1051-1053 ################################################### summary(createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed))) ################################################### ### code chunk number 87: compareGroups_vignette.rnw:1058-1062 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed) restab<-createTable(res, type=1, show.ratio=TRUE ) restab update(restab, show.n=TRUE) ################################################### ### code chunk number 88: compareGroups_vignette.rnw:1068-1069 ################################################### update(restab, x = update(res, subset=c(sex=='Female')), show.n=TRUE) ################################################### ### code chunk number 89: compareGroups_vignette.rnw:1080-1081 ################################################### createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)) ################################################### ### code chunk number 90: compareGroups_vignette.rnw:1083-1084 ################################################### createTable(compareGroups(group ~ age + sex + bmi, data=predimed))[1:2, ] ################################################### ### code chunk number 91: compareGroups_vignette.rnw:1130-1133 ################################################### restab<-createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)) export2latex(restab) ################################################### ### code chunk number 92: compareGroups_vignette.rnw:1170-1172 (eval = FALSE) ################################################### ## ?report # to know more about report function ## ?regicor # info about REGICOR data set ################################################### ### code chunk number 93: compareGroups_vignette.rnw:1187-1191 ################################################### # from a compareGroups object data(regicor) res <- compareGroups(year ~ .-id, regicor) missingTable(res) ################################################### ### code chunk number 94: compareGroups_vignette.rnw:1194-1197 (eval = FALSE) ################################################### ## # or from createTable objects ## restab <- createTable(res, hide.no = 'no') ## missingTable(restab) ################################################### ### code chunk number 95: compareGroups_vignette.rnw:1203-1209 ################################################### # first create time-to-cardiovascular event regicor$tcv<-with(regicor,Surv(tocv,cv=='Yes')) # create the table res <- compareGroups(tcv ~ . -id-tocv-cv-todeath-death, regicor, include.miss = TRUE) restab <- createTable(res, hide.no = 'no') restab ################################################### ### code chunk number 96: compareGroups_vignette.rnw:1226-1228 ################################################### data(SNPs) head(SNPs) ################################################### ### code chunk number 97: compareGroups_vignette.rnw:1233-1235 ################################################### res<-compareSNPs(casco ~ snp10001 + snp10002 + snp10003, data=SNPs) res ################################################### ### code chunk number 98: compareGroups_vignette.rnw:1243-1245 ################################################### res<-compareSNPs(~ snp10001 + snp10002 + snp10003, data=SNPs) res ################################################### ### code chunk number 99: compareGroups_vignette.rnw:1267-1270 ################################################### export2latex(createTable(compareGroups(group ~ age + sex + smoke + bmi + waist + wth + htn + diab + hyperchol + famhist + hormo + p14 + toevent + event, data=predimed), hide.no="No",hide = c(sex="Male"))) ################################################### ### code chunk number 100: compareGroups_vignette.rnw:1332-1337 ################################################### export2latex(createTable(compareGroups(htn ~ age + sex + smoke + bmi + waist + wth + diab + hyperchol + famhist + hormo + p14 + toevent + event, data=predimed), hide.no="No",hide = c(sex="Male"), show.ratio=TRUE, show.descr=FALSE)) ################################################### ### code chunk number 101: compareGroups_vignette.rnw:1350-1352 ################################################### export2latex(createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.ratio=TRUE))
/compareGroups/inst/doc/compareGroups_vignette.R
no_license
ingted/R-Examples
R
false
false
27,321
r
### R code from vignette source 'compareGroups_vignette.rnw' ### Encoding: ISO8859-1 ################################################### ### code chunk number 1: compareGroups_vignette.rnw:106-107 ################################################### library(compareGroups) ################################################### ### code chunk number 2: compareGroups_vignette.rnw:152-153 ################################################### data(predimed) ################################################### ### code chunk number 3: compareGroups_vignette.rnw:160-168 ################################################### dicc<-data.frame( "Name"=I(names(predimed)), "Label"=I(unlist(lapply(predimed,label))), "Codes"=I(unlist(lapply(predimed,function(x) paste(levels(x),collapse="; ")))) ) dicc$Codes<-sub(">=","$\\\\geq$",dicc$Codes) #print(xtable(dicc,align=rep("l",4)),include.rownames=FALSE,size="small",tabular.environment="longtable", sanitize.text.function=function(x) x) print(xtable(dicc,align=rep("l",4)),include.rownames=FALSE,size="small", sanitize.text.function=function(x) x) ################################################### ### code chunk number 4: compareGroups_vignette.rnw:194-196 ################################################### predimed$tmain <- with(predimed, Surv(toevent, event == 'Yes')) label(predimed$tmain) <- "AMI, stroke, or CV Death" ################################################### ### code chunk number 5: compareGroups_vignette.rnw:216-217 ################################################### compareGroups(group ~ . , data=predimed) ################################################### ### code chunk number 6: compareGroups_vignette.rnw:228-229 ################################################### compareGroups(group ~ . -toevent - event, data=predimed) ################################################### ### code chunk number 7: compareGroups_vignette.rnw:236-238 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed) res ################################################### ### code chunk number 8: compareGroups_vignette.rnw:257-259 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, subset = sex=='Female') ################################################### ### code chunk number 9: compareGroups_vignette.rnw:266-267 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 10: compareGroups_vignette.rnw:270-272 ################################################### compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed, selec = list(hormo= sex=="Female", waist = waist>20 )) ################################################### ### code chunk number 11: compareGroups_vignette.rnw:277-278 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 12: compareGroups_vignette.rnw:281-283 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, selec = list(waist= !is.na(hormo)), subset = sex=="Female") ################################################### ### code chunk number 13: compareGroups_vignette.rnw:289-290 ################################################### options(width=80,keep.source=TRUE) ################################################### ### code chunk number 14: compareGroups_vignette.rnw:292-294 ################################################### compareGroups(group ~ age + sex + bmi + bmi + waist + hormo, data=predimed, selec = list(bmi.1=!is.na(hormo))) ################################################### ### code chunk number 15: compareGroups_vignette.rnw:307-308 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 16: compareGroups_vignette.rnw:310-312 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=2)) ################################################### ### code chunk number 17: compareGroups_vignette.rnw:314-315 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 18: compareGroups_vignette.rnw:330-331 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 19: compareGroups_vignette.rnw:333-335 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=NA), alpha= 0.01) ################################################### ### code chunk number 20: compareGroups_vignette.rnw:337-338 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 21: compareGroups_vignette.rnw:347-351 ################################################### cuts<-"lo:55=1; 56:60=2; 61:65=3; 66:70=4; 71:75=5; 76:80=6; 81:hi=7" predimed$age7gr<-car::recode(predimed$age, cuts) compareGroups(group ~ age7gr, data=predimed, method = c(age7gr=NA)) compareGroups(group ~ age7gr, data=predimed, method = c(age7gr=NA), min.dis=8) ################################################### ### code chunk number 22: compareGroups_vignette.rnw:367-368 ################################################### compareGroups(age7gr ~ sex + bmi + waist, data=predimed, max.ylev=7) ################################################### ### code chunk number 23: compareGroups_vignette.rnw:373-374 ################################################### compareGroups(group ~ sex + age7gr, method= (age7gr=3), data=predimed, max.xlev=5) ################################################### ### code chunk number 24: compareGroups_vignette.rnw:392-394 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, include.label= FALSE) ################################################### ### code chunk number 25: compareGroups_vignette.rnw:401-402 ################################################### options(width=80, keep.source=FALSE) ################################################### ### code chunk number 26: compareGroups_vignette.rnw:405-408 ################################################### resu1<-compareGroups(group ~ age + waist, data=predimed, method = c(waist=2)) createTable(resu1) ################################################### ### code chunk number 27: compareGroups_vignette.rnw:415-418 ################################################### resu2<-compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=2), Q1=0.025, Q3=0.975) createTable(resu2) ################################################### ### code chunk number 28: compareGroups_vignette.rnw:425-426 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 29: compareGroups_vignette.rnw:430-431 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 30: compareGroups_vignette.rnw:433-435 ################################################### compareGroups(group ~ age + smoke + waist + hormo, data=predimed, method = c(waist=2), Q1=0, Q3=1) ################################################### ### code chunk number 31: compareGroups_vignette.rnw:437-438 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 32: compareGroups_vignette.rnw:445-449 ################################################### predimed$smk<-predimed$smoke levels(predimed$smk)<- c("Never smoker", "Current or former < 1y", "Never or former >= 1y", "Unknown") label(predimed$smk)<-"Smoking 4 cat." cbind(table(predimed$smk)) ################################################### ### code chunk number 33: compareGroups_vignette.rnw:482-483 ################################################### compareGroups(group ~ age + smk, data=predimed, simplify=FALSE) ################################################### ### code chunk number 34: compareGroups_vignette.rnw:514-517 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, method = c(waist=2), data=predimed) summary(res[c(1, 2, 4)]) ################################################### ### code chunk number 35: compareGroups_vignette.rnw:530-531 ################################################### plot(res[c(1,2)], file="./figures/univar/", type="pdf") ################################################### ### code chunk number 36: compareGroups_vignette.rnw:549-550 ################################################### plot(res[c(1,2)], bivar=TRUE, file="./figures/bivar/") ################################################### ### code chunk number 37: compareGroups_vignette.rnw:574-576 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed) res ################################################### ### code chunk number 38: compareGroups_vignette.rnw:581-582 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 39: compareGroups_vignette.rnw:584-586 ################################################### res<-update(res, . ~. - sex + bmi + toevent, subset = sex=='Female', method = c(waist=2, tovent=2), selec = list(bmi=!is.na(hormo))) ################################################### ### code chunk number 40: compareGroups_vignette.rnw:588-589 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 41: compareGroups_vignette.rnw:591-592 ################################################### res ################################################### ### code chunk number 42: compareGroups_vignette.rnw:606-612 ################################################### library(SNPassoc) data(SNPs) tab <- createTable(compareGroups(casco ~ snp10001 + snp10002 + snp10005 + snp10008 + snp10009, SNPs)) pvals <- getResults(tab, "p.overall") p.adjust(pvals, method = "BH") ################################################### ### code chunk number 43: compareGroups_vignette.rnw:629-631 ################################################### res1<-compareGroups(htn ~ age + sex + bmi + smoke, data=predimed, ref=1) createTable(res1, show.ratio=TRUE) ################################################### ### code chunk number 44: compareGroups_vignette.rnw:637-638 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 45: compareGroups_vignette.rnw:640-643 ################################################### res2<-compareGroups(htn ~ age + sex + bmi + smoke, data=predimed, ref=c(smoke=1, sex=2)) createTable(res2, show.ratio=TRUE) ################################################### ### code chunk number 46: compareGroups_vignette.rnw:648-649 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 47: compareGroups_vignette.rnw:656-659 ################################################### res<-compareGroups(htn ~ age + sex + bmi + hormo + hyperchol, data=predimed, ref.no='NO') createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 48: compareGroups_vignette.rnw:668-670 ################################################### res<-compareGroups(htn ~ age + bmi, data=predimed) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 49: compareGroups_vignette.rnw:675-676 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 50: compareGroups_vignette.rnw:678-681 ################################################### res<-compareGroups(htn ~ age + bmi, data=predimed, fact.ratio= c(age=10, bmi=2)) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 51: compareGroups_vignette.rnw:683-684 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 52: compareGroups_vignette.rnw:693-695 ################################################### res<-compareGroups(htn ~ age + sex + bmi + hyperchol, data=predimed) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 53: compareGroups_vignette.rnw:701-703 ################################################### res<-compareGroups(htn ~ age + sex + bmi + hyperchol, data=predimed, ref.y=2) createTable(res, show.ratio=TRUE) ################################################### ### code chunk number 54: compareGroups_vignette.rnw:717-719 ################################################### plot(compareGroups(tmain ~ sex, data=predimed), bivar=TRUE, file="./figures/bivar/") plot(compareGroups(tmain ~ age, data=predimed), bivar=TRUE, file="./figures/bivar/") ################################################### ### code chunk number 55: compareGroups_vignette.rnw:754-755 ################################################### options(width=80,keep.source=FALSE) ################################################### ### code chunk number 56: compareGroups_vignette.rnw:757-760 ################################################### res<-compareGroups(sex ~ age + tmain, timemax=c(tmain=3), data=predimed) res ################################################### ### code chunk number 57: compareGroups_vignette.rnw:762-763 ################################################### options(width=120,keep.source=FALSE) ################################################### ### code chunk number 58: compareGroups_vignette.rnw:772-774 ################################################### plot(res[2], file="./figures/univar/") plot(res[2], bivar=TRUE, file="./figures/bivar/") ################################################### ### code chunk number 59: compareGroups_vignette.rnw:799-800 ################################################### options(width=100,keep.source=FALSE) ################################################### ### code chunk number 60: compareGroups_vignette.rnw:803-806 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed, selec = list(hormo=sex=="Female")) restab<-createTable(res) ################################################### ### code chunk number 61: compareGroups_vignette.rnw:811-812 ################################################### print(restab,which.table='descr') ################################################### ### code chunk number 62: compareGroups_vignette.rnw:817-818 ################################################### print(restab,which.table='avail') ################################################### ### code chunk number 63: compareGroups_vignette.rnw:834-835 ################################################### update(restab, hide = c(sex="Male")) ################################################### ### code chunk number 64: compareGroups_vignette.rnw:844-846 ################################################### res<-compareGroups(group ~ age + sex + htn + diab, data=predimed) createTable(res, hide.no='no', hide = c(sex="Male")) ################################################### ### code chunk number 65: compareGroups_vignette.rnw:855-856 ################################################### createTable(res, digits= c(age=2, sex = 3)) ################################################### ### code chunk number 66: compareGroups_vignette.rnw:865-866 ################################################### createTable(res, type=1) ################################################### ### code chunk number 67: compareGroups_vignette.rnw:871-872 ################################################### createTable(res, type=3) ################################################### ### code chunk number 68: compareGroups_vignette.rnw:884-885 ################################################### createTable(res, show.n=TRUE) ################################################### ### code chunk number 69: compareGroups_vignette.rnw:892-893 ################################################### createTable(res, show.descr=FALSE) ################################################### ### code chunk number 70: compareGroups_vignette.rnw:900-901 ################################################### createTable(res, show.all=TRUE) ################################################### ### code chunk number 71: compareGroups_vignette.rnw:907-908 ################################################### createTable(res, show.p.overall=FALSE) ################################################### ### code chunk number 72: compareGroups_vignette.rnw:915-916 ################################################### createTable(res, show.p.trend=TRUE) ################################################### ### code chunk number 73: compareGroups_vignette.rnw:926-927 ################################################### createTable(res, show.p.mul=TRUE) ################################################### ### code chunk number 74: compareGroups_vignette.rnw:933-934 ################################################### createTable(update(res, subset= group!="Control diet"), show.ratio=TRUE) ################################################### ### code chunk number 75: compareGroups_vignette.rnw:939-941 ################################################### createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.ratio=TRUE) ################################################### ### code chunk number 76: compareGroups_vignette.rnw:950-952 ################################################### createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.ratio=TRUE, digits.ratio= 3) ################################################### ### code chunk number 77: compareGroups_vignette.rnw:959-962 ################################################### tab<-createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.all = TRUE) print(tab, header.labels = c("p.overall" = "p-value", "all" = "All")) ################################################### ### code chunk number 78: compareGroups_vignette.rnw:974-977 ################################################### restab1 <- createTable(compareGroups(group ~ age + sex, data=predimed)) restab2 <- createTable(compareGroups(group ~ bmi + smoke, data=predimed)) rbind("Non-modifiable risk factors"=restab1, "Modifiable risk factors"=restab2) ################################################### ### code chunk number 79: compareGroups_vignette.rnw:990-991 ################################################### rbind("Non-modifiable"=restab1,"Modifiable"=restab2)[c(1,4)] ################################################### ### code chunk number 80: compareGroups_vignette.rnw:996-997 ################################################### rbind("Modifiable"=restab1,"Non-modifiable"=restab2)[c(4,3,2,1)] ################################################### ### code chunk number 81: compareGroups_vignette.rnw:1008-1013 ################################################### res<-compareGroups(group ~ age + smoke + bmi + htn , data=predimed) alltab <- createTable(res, show.p.overall = FALSE) femaletab <- createTable(update(res,subset=sex=='Female'), show.p.overall = FALSE) maletab <- createTable(update(res,subset=sex=='Male'), show.p.overall = FALSE) cbind("ALL"=alltab,"FEMALE"=femaletab,"MALE"=maletab) ################################################### ### code chunk number 82: compareGroups_vignette.rnw:1018-1019 ################################################### cbind(alltab,femaletab,maletab,caption=NULL) ################################################### ### code chunk number 83: compareGroups_vignette.rnw:1024-1025 ################################################### cbind(alltab,femaletab,maletab) ################################################### ### code chunk number 84: compareGroups_vignette.rnw:1038-1040 ################################################### print(createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)), which.table='both') ################################################### ### code chunk number 85: compareGroups_vignette.rnw:1043-1045 ################################################### print(createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)), nmax=FALSE) ################################################### ### code chunk number 86: compareGroups_vignette.rnw:1051-1053 ################################################### summary(createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed))) ################################################### ### code chunk number 87: compareGroups_vignette.rnw:1058-1062 ################################################### res<-compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed) restab<-createTable(res, type=1, show.ratio=TRUE ) restab update(restab, show.n=TRUE) ################################################### ### code chunk number 88: compareGroups_vignette.rnw:1068-1069 ################################################### update(restab, x = update(res, subset=c(sex=='Female')), show.n=TRUE) ################################################### ### code chunk number 89: compareGroups_vignette.rnw:1080-1081 ################################################### createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)) ################################################### ### code chunk number 90: compareGroups_vignette.rnw:1083-1084 ################################################### createTable(compareGroups(group ~ age + sex + bmi, data=predimed))[1:2, ] ################################################### ### code chunk number 91: compareGroups_vignette.rnw:1130-1133 ################################################### restab<-createTable(compareGroups(group ~ age + sex + smoke + waist + hormo, data=predimed)) export2latex(restab) ################################################### ### code chunk number 92: compareGroups_vignette.rnw:1170-1172 (eval = FALSE) ################################################### ## ?report # to know more about report function ## ?regicor # info about REGICOR data set ################################################### ### code chunk number 93: compareGroups_vignette.rnw:1187-1191 ################################################### # from a compareGroups object data(regicor) res <- compareGroups(year ~ .-id, regicor) missingTable(res) ################################################### ### code chunk number 94: compareGroups_vignette.rnw:1194-1197 (eval = FALSE) ################################################### ## # or from createTable objects ## restab <- createTable(res, hide.no = 'no') ## missingTable(restab) ################################################### ### code chunk number 95: compareGroups_vignette.rnw:1203-1209 ################################################### # first create time-to-cardiovascular event regicor$tcv<-with(regicor,Surv(tocv,cv=='Yes')) # create the table res <- compareGroups(tcv ~ . -id-tocv-cv-todeath-death, regicor, include.miss = TRUE) restab <- createTable(res, hide.no = 'no') restab ################################################### ### code chunk number 96: compareGroups_vignette.rnw:1226-1228 ################################################### data(SNPs) head(SNPs) ################################################### ### code chunk number 97: compareGroups_vignette.rnw:1233-1235 ################################################### res<-compareSNPs(casco ~ snp10001 + snp10002 + snp10003, data=SNPs) res ################################################### ### code chunk number 98: compareGroups_vignette.rnw:1243-1245 ################################################### res<-compareSNPs(~ snp10001 + snp10002 + snp10003, data=SNPs) res ################################################### ### code chunk number 99: compareGroups_vignette.rnw:1267-1270 ################################################### export2latex(createTable(compareGroups(group ~ age + sex + smoke + bmi + waist + wth + htn + diab + hyperchol + famhist + hormo + p14 + toevent + event, data=predimed), hide.no="No",hide = c(sex="Male"))) ################################################### ### code chunk number 100: compareGroups_vignette.rnw:1332-1337 ################################################### export2latex(createTable(compareGroups(htn ~ age + sex + smoke + bmi + waist + wth + diab + hyperchol + famhist + hormo + p14 + toevent + event, data=predimed), hide.no="No",hide = c(sex="Male"), show.ratio=TRUE, show.descr=FALSE)) ################################################### ### code chunk number 101: compareGroups_vignette.rnw:1350-1352 ################################################### export2latex(createTable(compareGroups(tmain ~ group + age + sex, data=predimed), show.ratio=TRUE))
context("classif_neuralnet") test_that("classif_neuralnet", { requirePackagesOrSkip("neuralnet", default.method = "load") set.seed(getOption("mlr.debug.seed")) capture.output({ # neuralnet is not dealing with formula with `.` well nms = names(binaryclass.train) formula_head = as.character(binaryclass.formula)[2] varnames = nms[nms!=formula_head] formula_head = paste('as.numeric(',formula_head,')~') formula_expand = paste(formula_head, paste(varnames, collapse = "+")) formula_expand = as.formula(formula_expand) traindat = binaryclass.train traindat[[binaryclass.target]] = as.numeric(traindat[[binaryclass.target]])-1 m = neuralnet::neuralnet(formula_expand, hidden=7, data=traindat, err.fct="ce", linear.output = FALSE) p = neuralnet::compute(m, covariate = binaryclass.test[,-ncol(binaryclass.test)]) p = as.numeric(as.vector(p[[2]])>0.5) p = factor(p, labels = binaryclass.class.levs) }) set.seed(getOption("mlr.debug.seed")) testSimple("classif.neuralnet", binaryclass.df, binaryclass.target, binaryclass.train.inds, p, parset = list(hidden = 7, err.fct = "ce")) # Neuralnet doesn't have the `predict` method # set.seed(getOption("mlr.debug.seed")) # lrn = makeLearner("classif.neuralnet",hidden=7) # task = makeClassifTask(data = binaryclass.df, target = binaryclass.target) # m2 = try(train(lrn, task, subset = binaryclass.train.inds)) # p2 = predictLearner(.learner=lrn,.model=m2, # .newdata = binaryclass.test[,-ncol(binaryclass.test)]) # expect_equal(p,p2,tol=1e-4) })
/tests/testthat/test_classif_neuralnet.R
no_license
jimhester/mlr
R
false
false
1,606
r
context("classif_neuralnet") test_that("classif_neuralnet", { requirePackagesOrSkip("neuralnet", default.method = "load") set.seed(getOption("mlr.debug.seed")) capture.output({ # neuralnet is not dealing with formula with `.` well nms = names(binaryclass.train) formula_head = as.character(binaryclass.formula)[2] varnames = nms[nms!=formula_head] formula_head = paste('as.numeric(',formula_head,')~') formula_expand = paste(formula_head, paste(varnames, collapse = "+")) formula_expand = as.formula(formula_expand) traindat = binaryclass.train traindat[[binaryclass.target]] = as.numeric(traindat[[binaryclass.target]])-1 m = neuralnet::neuralnet(formula_expand, hidden=7, data=traindat, err.fct="ce", linear.output = FALSE) p = neuralnet::compute(m, covariate = binaryclass.test[,-ncol(binaryclass.test)]) p = as.numeric(as.vector(p[[2]])>0.5) p = factor(p, labels = binaryclass.class.levs) }) set.seed(getOption("mlr.debug.seed")) testSimple("classif.neuralnet", binaryclass.df, binaryclass.target, binaryclass.train.inds, p, parset = list(hidden = 7, err.fct = "ce")) # Neuralnet doesn't have the `predict` method # set.seed(getOption("mlr.debug.seed")) # lrn = makeLearner("classif.neuralnet",hidden=7) # task = makeClassifTask(data = binaryclass.df, target = binaryclass.target) # m2 = try(train(lrn, task, subset = binaryclass.train.inds)) # p2 = predictLearner(.learner=lrn,.model=m2, # .newdata = binaryclass.test[,-ncol(binaryclass.test)]) # expect_equal(p,p2,tol=1e-4) })
library(ggplot2) library(grid) library(RColorBrewer) load('data/wind_year.Rda') wind <- wind.year load("data/bathy.Rdata") load("data/night.Rdata") load("data/red_sea_inside.Rdata") load("data/red_sea_outside.Rdata") x_min <- 31 x_max <- 45 y_min <- 10 y_max <- 31 #----- Axis layer ----# axis_p <-ggplot(wind, aes(x=long, y=lat)) axis_p <- axis_p + coord_cartesian(ylim=c(y_min,y_max),xlim=c(x_min,x_max)) #----- Theme layer -----# theme_p <- theme(axis.line=element_blank(), axis.text.x=element_blank(), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), legend.position="none", panel.background=element_blank(), panel.border=element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), plot.background=element_blank(), plot.margin = unit(c(-.1, -.1, -1, -1), "lines")) # ----- Bathymetry layer ------# bathy_p <-stat_contour(data=bathy_df, aes(x, y, z=topo1), color="black", breaks=c(-30), size=.15) # color="#00BAFFFF", breaks=c(-30), size=.15) #------ Red Sea layer -----# red.sea.outside_p <- geom_polygon(data=red.sea.outside, aes(x=long, y=lat, group=group), colour="#1c5c6b", fill="magenta", size=.5) #------ Wind Layer ------# wind_p <- axis_p + geom_tile(aes(fill = class50), height=0.1) wind_p <- wind_p + scale_fill_manual(values=rev(brewer.pal(7, "RdYlBu")), labels=seq(7)) wind_p <- wind_p + bathy_p + red.sea.outside_p + theme_p ggsave(filename="results/posterfig/wind.png", plot=wind_p, width=568.3, height=826, dpi=300, units="mm") #------ Night Layer ------# night_p <- axis_p + geom_raster(data=night_df, aes(x = x, y = y, fill = nightearth)) night_p <- night_p + scale_fill_gradient(low='black', high='white', trans='log', limits=c(.1,5000), na.value='black') night_p <- night_p + theme_p ggsave(filename="results/posterfig/night.png", plot=night_p, units="mm")
/scripts/posterBackground/do.R
no_license
XResearch/redSeaWind
R
false
false
2,350
r
library(ggplot2) library(grid) library(RColorBrewer) load('data/wind_year.Rda') wind <- wind.year load("data/bathy.Rdata") load("data/night.Rdata") load("data/red_sea_inside.Rdata") load("data/red_sea_outside.Rdata") x_min <- 31 x_max <- 45 y_min <- 10 y_max <- 31 #----- Axis layer ----# axis_p <-ggplot(wind, aes(x=long, y=lat)) axis_p <- axis_p + coord_cartesian(ylim=c(y_min,y_max),xlim=c(x_min,x_max)) #----- Theme layer -----# theme_p <- theme(axis.line=element_blank(), axis.text.x=element_blank(), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), legend.position="none", panel.background=element_blank(), panel.border=element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), plot.background=element_blank(), plot.margin = unit(c(-.1, -.1, -1, -1), "lines")) # ----- Bathymetry layer ------# bathy_p <-stat_contour(data=bathy_df, aes(x, y, z=topo1), color="black", breaks=c(-30), size=.15) # color="#00BAFFFF", breaks=c(-30), size=.15) #------ Red Sea layer -----# red.sea.outside_p <- geom_polygon(data=red.sea.outside, aes(x=long, y=lat, group=group), colour="#1c5c6b", fill="magenta", size=.5) #------ Wind Layer ------# wind_p <- axis_p + geom_tile(aes(fill = class50), height=0.1) wind_p <- wind_p + scale_fill_manual(values=rev(brewer.pal(7, "RdYlBu")), labels=seq(7)) wind_p <- wind_p + bathy_p + red.sea.outside_p + theme_p ggsave(filename="results/posterfig/wind.png", plot=wind_p, width=568.3, height=826, dpi=300, units="mm") #------ Night Layer ------# night_p <- axis_p + geom_raster(data=night_df, aes(x = x, y = y, fill = nightearth)) night_p <- night_p + scale_fill_gradient(low='black', high='white', trans='log', limits=c(.1,5000), na.value='black') night_p <- night_p + theme_p ggsave(filename="results/posterfig/night.png", plot=night_p, units="mm")
library(plyr) library(reshape2) library(ggplot2) library(grid) library(scales) set.seed(420) theme_set(theme_bw()) cbp <- c('#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7') theme_update(axis.text = element_text(size = 32), axis.title = element_text(size = 35), axis.title.y = element_text(hjust = 0.1), legend.text = element_text(size = 25), legend.title = element_text(size = 26), legend.key.size = unit(2, 'cm'), strip.text = element_text(size = 30)) # exponential lam <- 1 k <- 1 durs <- rweibull(1000, k, lam) surv <- exp(-lam * durs^k) haz <- lam * k * durs^(k - 1) survival <- data.frame(durs = durs, surv = surv, haz = haz) gd <- ggplot(survival, aes(x = durs)) gd <- gd + geom_histogram(aes(y = ..density..), fill = 'grey') gd <- gd + stat_function(fun = dweibull, colour = 'blue', size = 3, arg = list(shape = k, scale = lam)) gd <- gd + labs(x = 'Duration', y = 'Density') ggsave(gd, filename = '../doc/figure/dur_exp.png', width = 15, height = 10) gsv <- ggplot(survival, aes(x = durs, y = surv)) gsv <- gsv + geom_line(size = 3) gsv <- gsv + scale_y_continuous(trans = log10_trans()) gsv <- gsv + labs(x = 'Duration', y = 'P(T > t)') ggsave(gsv, filename = '../doc/figure/sur_exp.png', width = 15, height = 10) ghz <- ggplot(survival, aes(x = durs, y = haz)) ghz <- ghz + geom_line(size = 3) ghz <- ghz + scale_y_continuous(trans = log10_trans()) ghz <- ghz + labs(x = 'Duration', y = 'h(t)') ggsave(ghz, filename = '../doc/figure/haz_exp.png', width = 15, height = 10) # dec lam <- 1 k <- 0.5 durs <- rweibull(1000, k, lam) surv <- exp(-lam * durs^k) haz <- lam * k * durs^(k - 1) survival <- data.frame(durs = durs, surv = surv, haz = haz) gdd <- ggplot(survival, aes(x = durs)) gdd <- gdd + geom_histogram(aes(y = ..density..), fill = 'grey') gdd <- gdd + stat_function(fun = dweibull, data = data.frame(ss = seq(0, 50, 0.1)), mapping = aes(x = ss), colour = 'blue', size = 3, arg = list(shape = k, scale = lam)) gdd <- gdd + labs(x = 'Duration', y = 'Density') ggsave(gdd, filename = '../doc/figure/dur_dec.png', width = 15, height = 10) gsvd <- ggplot(survival, aes(x = durs, y = surv)) gsvd <- gsvd + geom_line(size = 3) gsvd <- gsvd + scale_y_continuous(trans = log10_trans()) gsvd <- gsvd + labs(x = 'Duration', y = 'P(T > t)') ggsave(gsvd, filename = '../doc/figure/sur_dec.png', width = 15, height = 10) ghzd <- ggplot(survival, aes(x = durs, y = haz)) ghzd <- ghzd + geom_line(size = 3) ghzd <- ghzd + scale_y_continuous(trans = log10_trans()) ghzd <- ghzd + labs(x = 'Duration', y = 'h(t)') ggsave(ghzd, filename = '../doc/figure/haz_dec.png', width = 15, height = 10) # acc lam <- 1 k <- 1.5 durs <- rweibull(1000, k, lam) surv <- exp(-lam * durs^k) haz <- lam * k * durs^(k - 1) survival <- data.frame(durs = durs, surv = surv, haz = haz) gda <- ggplot(survival, aes(x = durs)) gda <- gda + geom_histogram(aes(y = ..density..), fill = 'grey') gda <- gda + stat_function(fun = dweibull, colour = 'blue', size = 3, arg = list(shape = k, scale = lam)) gda <- gda + labs(x = 'Duration', y = 'Density') ggsave(gda, filename = '../doc/figure/dur_acc.png', width = 15, height = 10) gsva <- ggplot(survival, aes(x = durs, y = surv)) gsva <- gsva + geom_line(size = 3) gsva <- gsva + scale_y_continuous(trans = log10_trans()) gsva <- gsva + labs(x = 'Duration', y = 'P(T > t)') ggsave(gsva, filename = '../doc/figure/sur_acc.png', width = 15, height = 10) ghza <- ggplot(survival, aes(x = durs, y = haz)) ghza <- ghza + geom_line(size = 3) ghza <- ghza + scale_y_continuous(trans = log10_trans()) ghza <- ghza + labs(x = 'Duration', y = 'h(t)') ggsave(ghza, filename = '../doc/figure/haz_acc.png', width = 15, height = 10)
/R/gambler.r
no_license
psmits/survivor
R
false
false
3,933
r
library(plyr) library(reshape2) library(ggplot2) library(grid) library(scales) set.seed(420) theme_set(theme_bw()) cbp <- c('#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7') theme_update(axis.text = element_text(size = 32), axis.title = element_text(size = 35), axis.title.y = element_text(hjust = 0.1), legend.text = element_text(size = 25), legend.title = element_text(size = 26), legend.key.size = unit(2, 'cm'), strip.text = element_text(size = 30)) # exponential lam <- 1 k <- 1 durs <- rweibull(1000, k, lam) surv <- exp(-lam * durs^k) haz <- lam * k * durs^(k - 1) survival <- data.frame(durs = durs, surv = surv, haz = haz) gd <- ggplot(survival, aes(x = durs)) gd <- gd + geom_histogram(aes(y = ..density..), fill = 'grey') gd <- gd + stat_function(fun = dweibull, colour = 'blue', size = 3, arg = list(shape = k, scale = lam)) gd <- gd + labs(x = 'Duration', y = 'Density') ggsave(gd, filename = '../doc/figure/dur_exp.png', width = 15, height = 10) gsv <- ggplot(survival, aes(x = durs, y = surv)) gsv <- gsv + geom_line(size = 3) gsv <- gsv + scale_y_continuous(trans = log10_trans()) gsv <- gsv + labs(x = 'Duration', y = 'P(T > t)') ggsave(gsv, filename = '../doc/figure/sur_exp.png', width = 15, height = 10) ghz <- ggplot(survival, aes(x = durs, y = haz)) ghz <- ghz + geom_line(size = 3) ghz <- ghz + scale_y_continuous(trans = log10_trans()) ghz <- ghz + labs(x = 'Duration', y = 'h(t)') ggsave(ghz, filename = '../doc/figure/haz_exp.png', width = 15, height = 10) # dec lam <- 1 k <- 0.5 durs <- rweibull(1000, k, lam) surv <- exp(-lam * durs^k) haz <- lam * k * durs^(k - 1) survival <- data.frame(durs = durs, surv = surv, haz = haz) gdd <- ggplot(survival, aes(x = durs)) gdd <- gdd + geom_histogram(aes(y = ..density..), fill = 'grey') gdd <- gdd + stat_function(fun = dweibull, data = data.frame(ss = seq(0, 50, 0.1)), mapping = aes(x = ss), colour = 'blue', size = 3, arg = list(shape = k, scale = lam)) gdd <- gdd + labs(x = 'Duration', y = 'Density') ggsave(gdd, filename = '../doc/figure/dur_dec.png', width = 15, height = 10) gsvd <- ggplot(survival, aes(x = durs, y = surv)) gsvd <- gsvd + geom_line(size = 3) gsvd <- gsvd + scale_y_continuous(trans = log10_trans()) gsvd <- gsvd + labs(x = 'Duration', y = 'P(T > t)') ggsave(gsvd, filename = '../doc/figure/sur_dec.png', width = 15, height = 10) ghzd <- ggplot(survival, aes(x = durs, y = haz)) ghzd <- ghzd + geom_line(size = 3) ghzd <- ghzd + scale_y_continuous(trans = log10_trans()) ghzd <- ghzd + labs(x = 'Duration', y = 'h(t)') ggsave(ghzd, filename = '../doc/figure/haz_dec.png', width = 15, height = 10) # acc lam <- 1 k <- 1.5 durs <- rweibull(1000, k, lam) surv <- exp(-lam * durs^k) haz <- lam * k * durs^(k - 1) survival <- data.frame(durs = durs, surv = surv, haz = haz) gda <- ggplot(survival, aes(x = durs)) gda <- gda + geom_histogram(aes(y = ..density..), fill = 'grey') gda <- gda + stat_function(fun = dweibull, colour = 'blue', size = 3, arg = list(shape = k, scale = lam)) gda <- gda + labs(x = 'Duration', y = 'Density') ggsave(gda, filename = '../doc/figure/dur_acc.png', width = 15, height = 10) gsva <- ggplot(survival, aes(x = durs, y = surv)) gsva <- gsva + geom_line(size = 3) gsva <- gsva + scale_y_continuous(trans = log10_trans()) gsva <- gsva + labs(x = 'Duration', y = 'P(T > t)') ggsave(gsva, filename = '../doc/figure/sur_acc.png', width = 15, height = 10) ghza <- ggplot(survival, aes(x = durs, y = haz)) ghza <- ghza + geom_line(size = 3) ghza <- ghza + scale_y_continuous(trans = log10_trans()) ghza <- ghza + labs(x = 'Duration', y = 'h(t)') ggsave(ghza, filename = '../doc/figure/haz_acc.png', width = 15, height = 10)
library(data.table) library(lubridate) library(dplyr) setwd ("H:/Coursera/Exploratory data analysis/exdata-data-household_power_consumption") data<-read.table("H:/Coursera/Exploratory data analysis/exdata-data-household_power_consumption/household_power_consumption.txt" ,header = TRUE, sep = ";", dec = ".",stringsAsFactors=FALSE, na.strings=c("NA", "-", "?")) Subset<-dmy(data$Date)>=ymd("2007-02-01") & dmy(data$Date)<=ymd("2007-02-02") data_subset <- data[Subset,] data_subset2 <- mutate(data_subset, Time =dmy_hms(paste(data_subset$Date, data_subset$Time))) png(width = 480, height = 480, file ="H:/Coursera/Exploratory data analysis/plot4.png") par(mfrow=c(2,2)) plot2<-plot(data_subset2$Time,data_subset2$Global_active_power, xlab= "", ylab= "Global Active Power (kilowatts)", type="n") lines(data_subset2$Time,data_subset2$Global_active_power) plot4<-plot(data_subset2$Time,data_subset2$Voltage, xlab= "datetime", ylab= "Voltage", type="n") lines(data_subset2$Time, data_subset2$Voltage) plot3<-plot(data_subset2$Time, data_subset2$Sub_metering_1, xlab= "", ylab= "Energy sub metering", type="n") lines(data_subset2$Time, data_subset2$Sub_metering_1) lines(data_subset2$Time, data_subset2$Sub_metering_2, col="red") lines(data_subset2$Time, data_subset2$Sub_metering_3, col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty="n", col=c("black", "red", "blue"), lty = c(1,1,1), cex=0.6) plot5<-plot(data_subset2$Time,data_subset2$Global_reactive_power, xlab= "datetime", ylab= "Global_reactive_power", type="n") lines(data_subset2$Time, data_subset2$Global_reactive_power) dev.off()
/plot4.R
no_license
aliciafs/ExData_Plotting1
R
false
false
1,665
r
library(data.table) library(lubridate) library(dplyr) setwd ("H:/Coursera/Exploratory data analysis/exdata-data-household_power_consumption") data<-read.table("H:/Coursera/Exploratory data analysis/exdata-data-household_power_consumption/household_power_consumption.txt" ,header = TRUE, sep = ";", dec = ".",stringsAsFactors=FALSE, na.strings=c("NA", "-", "?")) Subset<-dmy(data$Date)>=ymd("2007-02-01") & dmy(data$Date)<=ymd("2007-02-02") data_subset <- data[Subset,] data_subset2 <- mutate(data_subset, Time =dmy_hms(paste(data_subset$Date, data_subset$Time))) png(width = 480, height = 480, file ="H:/Coursera/Exploratory data analysis/plot4.png") par(mfrow=c(2,2)) plot2<-plot(data_subset2$Time,data_subset2$Global_active_power, xlab= "", ylab= "Global Active Power (kilowatts)", type="n") lines(data_subset2$Time,data_subset2$Global_active_power) plot4<-plot(data_subset2$Time,data_subset2$Voltage, xlab= "datetime", ylab= "Voltage", type="n") lines(data_subset2$Time, data_subset2$Voltage) plot3<-plot(data_subset2$Time, data_subset2$Sub_metering_1, xlab= "", ylab= "Energy sub metering", type="n") lines(data_subset2$Time, data_subset2$Sub_metering_1) lines(data_subset2$Time, data_subset2$Sub_metering_2, col="red") lines(data_subset2$Time, data_subset2$Sub_metering_3, col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty="n", col=c("black", "red", "blue"), lty = c(1,1,1), cex=0.6) plot5<-plot(data_subset2$Time,data_subset2$Global_reactive_power, xlab= "datetime", ylab= "Global_reactive_power", type="n") lines(data_subset2$Time, data_subset2$Global_reactive_power) dev.off()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Hilmo_import_csv.R \name{Hilmo_import_csv} \alias{Hilmo_import_csv} \title{A Hilmo import .csv function} \usage{ Hilmo_import_csv(filename) } \arguments{ \item{filename}{the name of your file you wish to import} } \description{ This function allows you to import csv files in more tidy format and it creates ID column from lahtopaiva and tnro } \examples{ Hilmo_import_csv() } \keyword{csv} \keyword{hilmo} \keyword{import}
/Hilmo/man/Hilmo_import_csv.Rd
no_license
vilponk/hilmoGIT
R
false
true
502
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Hilmo_import_csv.R \name{Hilmo_import_csv} \alias{Hilmo_import_csv} \title{A Hilmo import .csv function} \usage{ Hilmo_import_csv(filename) } \arguments{ \item{filename}{the name of your file you wish to import} } \description{ This function allows you to import csv files in more tidy format and it creates ID column from lahtopaiva and tnro } \examples{ Hilmo_import_csv() } \keyword{csv} \keyword{hilmo} \keyword{import}
loadBands<-function(file = "../../genomic_info/chromosome_bands.csv") { t = read.table(file, sep=",", header=T) b = cbind(t$chromosome, t$band, t$start, t$end) b = b[order(b$chromosome),] return(b) } loadBreakpoints<-function(bpfile, use_sex = FALSE, ignore_subbands = TRUE) { bp = read.table(bpfile, sep="\t", comment="#", header=T) if (nrow(bp) <= 0) { stop("Breakpoint file is empty") } if (ignore_subbands) { ## Ignoring subbands (11.1) and just group them by the major band designation (11) #bp$Breakpoint = sub("\\.[0-9]+", "", bp$Breakpoint) bp$Breakpoint = clearSubbands(bp$Breakpoint) } if (!use_sex) { # Not using sex chromosomes generally, bp = dropSexChr(bp) } return(bp) } ## if I care enough I can make one function for this stuff... loadFragments<-function(file, use_sex = FALSE, ignore_subbands = TRUE) { ## Fragments ## fg = read.table(file, header=T, sep="\t") if (nrow(fg) <= 0) { stop("Fragments file is empty") } fg = fg[order(fg$Chr),] if (!use_sex) { # Not using sex chromosomes generally, fg = dropSexChr(fg) } if (ignore_subbands) { ## Lets ignore subbands (11.1) and just group them by the major band designation (11) fg$Start = clearSubbands(fg$Start) fg$End = clearSubbands(fg$End) } return(fg) } loadChromosomeInfo<-function(chrfile = "../../genomic_info/chromosome_gene_info_2012.txt") { chrinfo = read.table(chrfile, sep="\t", row.names=1, header=T) if (nrow(chrinfo) <= 0) { stop("Failed to load chromosome info file") } # don't need the mtDNA row chrinfo = chrinfo[ -(nrow(chrinfo)), ] for (i in 1:nrow(chrinfo)) { row = chrinfo[i,] # leave pseudogenes out of it chrinfo[i,'Total.Prot.RNA'] = sum(row$Confirmed.proteins, row$Putative.proteins, row$miRNA, row$rRNA, row$snRNA, row$snoRNA, row$Misc.ncRNA) } return(chrinfo) } dropSexChr<-function(df, colname = "Chr") { df = df[ which(df[[colname]]!="X" & df[[colname]]!="Y"),] return(df) } clearSubbands<-function(col) { ## Ignoring subbands (11.1) and just group them by the major band designation (11) col = sub("\\.[0-9]+", "", col) return(col) } sampleCancers<-function(df, colname = "Cancer", cancers) { message(nrow(df)) dfcnc = df[ which(df[[colname]] %in% cancers ) ,] sampled = dfcnc[sample(1:nrow(dfcnc), 500, replace=FALSE),] noncnc = df[which(df[[colname]] %nin% cancers), ] df = rbind(noncnc, sampled) message(nrow(df)) return(df) }
/R/lib/load_files.R
no_license
kavitarege/CancerCytogenetics
R
false
false
2,539
r
loadBands<-function(file = "../../genomic_info/chromosome_bands.csv") { t = read.table(file, sep=",", header=T) b = cbind(t$chromosome, t$band, t$start, t$end) b = b[order(b$chromosome),] return(b) } loadBreakpoints<-function(bpfile, use_sex = FALSE, ignore_subbands = TRUE) { bp = read.table(bpfile, sep="\t", comment="#", header=T) if (nrow(bp) <= 0) { stop("Breakpoint file is empty") } if (ignore_subbands) { ## Ignoring subbands (11.1) and just group them by the major band designation (11) #bp$Breakpoint = sub("\\.[0-9]+", "", bp$Breakpoint) bp$Breakpoint = clearSubbands(bp$Breakpoint) } if (!use_sex) { # Not using sex chromosomes generally, bp = dropSexChr(bp) } return(bp) } ## if I care enough I can make one function for this stuff... loadFragments<-function(file, use_sex = FALSE, ignore_subbands = TRUE) { ## Fragments ## fg = read.table(file, header=T, sep="\t") if (nrow(fg) <= 0) { stop("Fragments file is empty") } fg = fg[order(fg$Chr),] if (!use_sex) { # Not using sex chromosomes generally, fg = dropSexChr(fg) } if (ignore_subbands) { ## Lets ignore subbands (11.1) and just group them by the major band designation (11) fg$Start = clearSubbands(fg$Start) fg$End = clearSubbands(fg$End) } return(fg) } loadChromosomeInfo<-function(chrfile = "../../genomic_info/chromosome_gene_info_2012.txt") { chrinfo = read.table(chrfile, sep="\t", row.names=1, header=T) if (nrow(chrinfo) <= 0) { stop("Failed to load chromosome info file") } # don't need the mtDNA row chrinfo = chrinfo[ -(nrow(chrinfo)), ] for (i in 1:nrow(chrinfo)) { row = chrinfo[i,] # leave pseudogenes out of it chrinfo[i,'Total.Prot.RNA'] = sum(row$Confirmed.proteins, row$Putative.proteins, row$miRNA, row$rRNA, row$snRNA, row$snoRNA, row$Misc.ncRNA) } return(chrinfo) } dropSexChr<-function(df, colname = "Chr") { df = df[ which(df[[colname]]!="X" & df[[colname]]!="Y"),] return(df) } clearSubbands<-function(col) { ## Ignoring subbands (11.1) and just group them by the major band designation (11) col = sub("\\.[0-9]+", "", col) return(col) } sampleCancers<-function(df, colname = "Cancer", cancers) { message(nrow(df)) dfcnc = df[ which(df[[colname]] %in% cancers ) ,] sampled = dfcnc[sample(1:nrow(dfcnc), 500, replace=FALSE),] noncnc = df[which(df[[colname]] %nin% cancers), ] df = rbind(noncnc, sampled) message(nrow(df)) return(df) }
## setwd in UCI HAR DATASET, load dplyr and tidyr libraries ## READ DATASETS FOR TRAIN AND TEST #TRAIN sub_1<- read.delim("./train/subject_train.txt", header = FALSE) act_1<- read.delim("./train/y_train.txt", header = FALSE) set_1 <- read.delim("./train/X_train.txt", header = FALSE) features <- unlist(read.delim("features.txt", header = FALSE)) for(i in 1:7352){ set_1[i,1]<- trimws(set_1[i,1]) set_1[i,1]<- gsub(" ", " ", set_1[i,1]) } set_1 <- separate(set_1, V1, into=features, sep=" ") #TEST sub_2<- read.delim("./test/subject_test.txt", header = FALSE) act_2<- read.delim("./test/y_test.txt", header = FALSE) set_2 <- read.delim("./test/X_test.txt", header = FALSE) for(i in 1:2947){ set_2[i,1]<- trimws(set_2[i,1]) set_2[i,1]<- gsub(" ", " ", set_2[i,1]) } set_2 <- separate(set_2, V1, into=features, sep=" ") ## FIND AND EXTRACT ONLY MEASUREMENTS ON MEAN AND STD c1 <- c(grep("mean\\(\\)$|std\\(\\)$", features)) set_1 <- select(set_1, c1) set_2 <- select(set_2, c1) for(i in 1:18){ set_1[,i] <- as.numeric(set_1[,i]) set_2[,i] <- as.numeric(set_2[,i]) } ## MERGE DATASETS data<-rbind(cbind(sub_1,act_1, set_1),cbind(sub_2, act_2, set_2)) ##LABELING ACTIVITIES data[,2] <- factor(data[,2], levels = c(1,2,3,4,5,6), labels = c("WALKING", "WALKING_UPSTAIRS","WALKING_DOWNSTAIRS", "SITTING", "STANDING", "LAYING")) ##LABELING DATA names(data)[1:2] <- c("subject", "activity") m<- names(data)[3:20] m<- as.data.frame(strsplit(m, " ")) m<- as.vector(gsub("-", "",m[2,])) names(data)[3:20]<-m ##CREATING MEANS data %>% group_by(subject, activity) %>% summarize_at(vars(1:18), list(mean=mean))
/run_analysis.R
no_license
adanclop/tidy-data
R
false
false
1,776
r
## setwd in UCI HAR DATASET, load dplyr and tidyr libraries ## READ DATASETS FOR TRAIN AND TEST #TRAIN sub_1<- read.delim("./train/subject_train.txt", header = FALSE) act_1<- read.delim("./train/y_train.txt", header = FALSE) set_1 <- read.delim("./train/X_train.txt", header = FALSE) features <- unlist(read.delim("features.txt", header = FALSE)) for(i in 1:7352){ set_1[i,1]<- trimws(set_1[i,1]) set_1[i,1]<- gsub(" ", " ", set_1[i,1]) } set_1 <- separate(set_1, V1, into=features, sep=" ") #TEST sub_2<- read.delim("./test/subject_test.txt", header = FALSE) act_2<- read.delim("./test/y_test.txt", header = FALSE) set_2 <- read.delim("./test/X_test.txt", header = FALSE) for(i in 1:2947){ set_2[i,1]<- trimws(set_2[i,1]) set_2[i,1]<- gsub(" ", " ", set_2[i,1]) } set_2 <- separate(set_2, V1, into=features, sep=" ") ## FIND AND EXTRACT ONLY MEASUREMENTS ON MEAN AND STD c1 <- c(grep("mean\\(\\)$|std\\(\\)$", features)) set_1 <- select(set_1, c1) set_2 <- select(set_2, c1) for(i in 1:18){ set_1[,i] <- as.numeric(set_1[,i]) set_2[,i] <- as.numeric(set_2[,i]) } ## MERGE DATASETS data<-rbind(cbind(sub_1,act_1, set_1),cbind(sub_2, act_2, set_2)) ##LABELING ACTIVITIES data[,2] <- factor(data[,2], levels = c(1,2,3,4,5,6), labels = c("WALKING", "WALKING_UPSTAIRS","WALKING_DOWNSTAIRS", "SITTING", "STANDING", "LAYING")) ##LABELING DATA names(data)[1:2] <- c("subject", "activity") m<- names(data)[3:20] m<- as.data.frame(strsplit(m, " ")) m<- as.vector(gsub("-", "",m[2,])) names(data)[3:20]<-m ##CREATING MEANS data %>% group_by(subject, activity) %>% summarize_at(vars(1:18), list(mean=mean))
## This is a pair of functions that cache the inverse of a matrix. ## This function creates a special "matrix" object ## that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { ## set the m to NULL for starters m <- NULL ## create a setter that caches x and m set <- function(y) { x <<- y m <<- NULL } ## create a getter that returns the cached x, ## which is the inverse of a matrix get <- function() x setsolve <- function(solve) m <<- solve ## create a getsolve function that returns the inverse of matrix, # only calculating it if necessary getsolve <- function() m ## return the CacheMatrix object as a list of 4 functions list(set = set, get = get, setsolve = setsolve, getsolve = getsolve) } } ## this function computes the inverse of the special "matrix" returned ##by makeCacheMatrix above. If the inverse has already been ##calculated (and the matrix has not changed), ##then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' #subset list of 4 functions, if the inverse has already been ##calculated, return the cached inverse m <- x$getsolve() if(!is.null(m)) { message("getting cached data") return(m) } #pass matrix to calculation data <- x$get() m <- solve(data, ...) x$setsolve(m) m } ###Test Case: # create cacheable matrix object m<- makeCacheMatrix( ) # initailize with a an easy to inspect matrix m$set( matrix( c(0, 2, 2, 0 ), 2, 2)) # note use of parens to retrive the matrix part of the object m$get() # test the inverse cacher cacheSolve( m ) # should be cached now cacheSolve( m )
/cachematrix.R
no_license
ShuangyuanWei/ProgrammingAssignment2
R
false
false
1,929
r
## This is a pair of functions that cache the inverse of a matrix. ## This function creates a special "matrix" object ## that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { ## set the m to NULL for starters m <- NULL ## create a setter that caches x and m set <- function(y) { x <<- y m <<- NULL } ## create a getter that returns the cached x, ## which is the inverse of a matrix get <- function() x setsolve <- function(solve) m <<- solve ## create a getsolve function that returns the inverse of matrix, # only calculating it if necessary getsolve <- function() m ## return the CacheMatrix object as a list of 4 functions list(set = set, get = get, setsolve = setsolve, getsolve = getsolve) } } ## this function computes the inverse of the special "matrix" returned ##by makeCacheMatrix above. If the inverse has already been ##calculated (and the matrix has not changed), ##then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' #subset list of 4 functions, if the inverse has already been ##calculated, return the cached inverse m <- x$getsolve() if(!is.null(m)) { message("getting cached data") return(m) } #pass matrix to calculation data <- x$get() m <- solve(data, ...) x$setsolve(m) m } ###Test Case: # create cacheable matrix object m<- makeCacheMatrix( ) # initailize with a an easy to inspect matrix m$set( matrix( c(0, 2, 2, 0 ), 2, 2)) # note use of parens to retrive the matrix part of the object m$get() # test the inverse cacher cacheSolve( m ) # should be cached now cacheSolve( m )
################### # Nelly Amenyogbe # HEU Manuscript Analysis: Microbiome data ordination ################### # In this script, we will prepare ordinations (Non-metric multidimensional scaling; NMDS) for HEU and HUU children together, and for each study site separately. We will then perform statistical analyses (PERMANOVA test) to determine the variance explained by HIV exposure on the stool microbiome composition in each study site separately. # Load packages library(phyloseq) library(ggplot2) library(vegan) library(plyr) # load data sample.cols <- read.csv("HEU_manuscript_analysis/Rdata/luminex/heu_pca_colours.csv") physeq <- readRDS("HEU_manuscript_analysis/Rdata/microbiome/gc_heu_phyloseq.rds") # Subset data by site #### cad <- subset_samples(physeq, Site == "Canada") cad <- prune_taxa(taxa_sums(cad) > 0, cad) blg <- subset_samples(physeq, Site == "Belgium") blg <- prune_taxa(taxa_sums(blg) > 0, blg) saf <- subset_samples(physeq, Site == "South Africa") saf <- prune_taxa(taxa_sums(saf) > 0, saf) # Ordination of samples #### # get.nmds.data # Input: ps = phyloseq object # output: data frame friendly for plotting via ggplot2 get.nmds.data <- function(ps){ ord <- ordinate(ps, method = "NMDS", distance = "bray") p <- plot_ordination(physeq, ord) dat <- p$data dat$Exposure <- gsub("Control", "HUU", dat$Exposure) dat$Exposure <- factor(dat$Exposure, levels = c("HUU", "HEU")) dat$site.exposure <- paste(dat$Site, dat$Exposure) return(dat) } # All samples together #### heu.nmds.dat <- get.nmds.data(physeq) # set aesthetics # colour sample.cols$site.heu <- gsub("Control", "HUU", sample.cols$site.heu) cols <- as.character(sample.cols$colour) names(cols) <- sample.cols$site.heu # shape shapes <- sample.cols$shape names(shapes) <- sample.cols$site.heu shapes.f <- c("Canada HEU" = 24, "Canada HUU" = 24, "Belgium HEU" = 21, "Belgium HUU" = 21, "South Africa HEU" = 22, "South Africa HUU" = 22) # this is for shapes where the fill is specified rather than the colour # set factor levels heu.nmds.dat$site.exposure <- factor(heu.nmds.dat$site.exposure, levels = c("Belgium HUU", "Belgium HEU", "Canada HUU", "Canada HEU", "South Africa HUU", "South Africa HEU")) p.heu <- ggplot(heu.nmds.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, color = "black") + theme_classic() + scale_shape_manual("", values = shapes.f) + scale_fill_manual("", values = cols) + theme(axis.text.x = element_text(size = 18, face = "bold"), axis.text.y = element_text(size = 18, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 12), legend.title = element_text(size = 12), legend.position = "bottom") p.heu #ggsave("HEU_manuscript_analysis/figures/microbiome/heu_nmds.pdf", device = "pdf", dpi = 300, width = 6.5, height = 6) # Ordination by Site #### # CAD ord #### cad.dat <- get.nmds.data(cad) cad.p <- ggplot(cad.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, shape = 24) + theme_classic() + scale_shape_manual("", values = shapes[3:4]) + scale_fill_manual("", values = cols[3:4]) + theme(axis.text.x = element_text(size = 14, face = "bold"), axis.text.y = element_text(size = 14, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 16), legend.title = element_text(size = 12), legend.position = "none") cad.p #ggsave("HEU_manuscript_analysis/figures/microbiome/cad_heu_nmds.pdf", device = "pdf", dpi = 300, width = 5, height = 4) # BLG ord #### blg.dat <- get.nmds.data(blg) blg.p <- ggplot(blg.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, shape = 21) + theme_classic() + scale_shape_manual("", values = shapes[1:2]) + scale_fill_manual("", values = cols[1:2]) + theme(axis.text.x = element_text(size = 14, face = "bold"), axis.text.y = element_text(size = 14, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 16), legend.title = element_text(size = 12), legend.position = "none") blg.p #ggsave("HEU_manuscript_analysis/figures/microbiome/blg_heu_nmds.pdf", device = "pdf", dpi = 300, width = 5, height = 4) # SAF ord #### saf.dat <- get.nmds.data(saf) saf.p <- ggplot(saf.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, shape = 22) + theme_classic() + scale_shape_manual("", values = shapes[5:6]) + scale_fill_manual("", values = cols[5:6]) + theme(axis.text.x = element_text(size = 14, face = "bold"), axis.text.y = element_text(size = 14, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 16), legend.title = element_text(size = 12), legend.position = "none") saf.p #ggsave("HEU_manuscript_analysis/figures/microbiome/saf_heu_nmds.pdf", device = "pdf", dpi = 300, width = 5, height = 4) # Adonis Test for Clustering #### # determine the variance explained by HIV exposure for each site separately physeqs <- list(cad, blg, saf) names(physeqs) <- c("cad", "blg", "saf") adonis.tests <- llply(as.list(physeqs), function(i){ df <- data.frame(sample_data(i)) dist <- phyloseq::distance(i, "bray") adonis(dist ~ Exposure, data = df) }) names(adonis.tests) <- names(physeqs) adonis.tests # CAD R2 = 0.03527, p = 0.043 # BLG R2 = 0.03824, p = 0.579 # SAF R2 = 0.0724, p = 0.311 # END ####
/HEU_manuscript_analysis/scripts/microbiome/ms_microbiome_ordination.R
no_license
nelly-amenyogbe/Global_HEU_immune_microbiome
R
false
false
6,167
r
################### # Nelly Amenyogbe # HEU Manuscript Analysis: Microbiome data ordination ################### # In this script, we will prepare ordinations (Non-metric multidimensional scaling; NMDS) for HEU and HUU children together, and for each study site separately. We will then perform statistical analyses (PERMANOVA test) to determine the variance explained by HIV exposure on the stool microbiome composition in each study site separately. # Load packages library(phyloseq) library(ggplot2) library(vegan) library(plyr) # load data sample.cols <- read.csv("HEU_manuscript_analysis/Rdata/luminex/heu_pca_colours.csv") physeq <- readRDS("HEU_manuscript_analysis/Rdata/microbiome/gc_heu_phyloseq.rds") # Subset data by site #### cad <- subset_samples(physeq, Site == "Canada") cad <- prune_taxa(taxa_sums(cad) > 0, cad) blg <- subset_samples(physeq, Site == "Belgium") blg <- prune_taxa(taxa_sums(blg) > 0, blg) saf <- subset_samples(physeq, Site == "South Africa") saf <- prune_taxa(taxa_sums(saf) > 0, saf) # Ordination of samples #### # get.nmds.data # Input: ps = phyloseq object # output: data frame friendly for plotting via ggplot2 get.nmds.data <- function(ps){ ord <- ordinate(ps, method = "NMDS", distance = "bray") p <- plot_ordination(physeq, ord) dat <- p$data dat$Exposure <- gsub("Control", "HUU", dat$Exposure) dat$Exposure <- factor(dat$Exposure, levels = c("HUU", "HEU")) dat$site.exposure <- paste(dat$Site, dat$Exposure) return(dat) } # All samples together #### heu.nmds.dat <- get.nmds.data(physeq) # set aesthetics # colour sample.cols$site.heu <- gsub("Control", "HUU", sample.cols$site.heu) cols <- as.character(sample.cols$colour) names(cols) <- sample.cols$site.heu # shape shapes <- sample.cols$shape names(shapes) <- sample.cols$site.heu shapes.f <- c("Canada HEU" = 24, "Canada HUU" = 24, "Belgium HEU" = 21, "Belgium HUU" = 21, "South Africa HEU" = 22, "South Africa HUU" = 22) # this is for shapes where the fill is specified rather than the colour # set factor levels heu.nmds.dat$site.exposure <- factor(heu.nmds.dat$site.exposure, levels = c("Belgium HUU", "Belgium HEU", "Canada HUU", "Canada HEU", "South Africa HUU", "South Africa HEU")) p.heu <- ggplot(heu.nmds.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, color = "black") + theme_classic() + scale_shape_manual("", values = shapes.f) + scale_fill_manual("", values = cols) + theme(axis.text.x = element_text(size = 18, face = "bold"), axis.text.y = element_text(size = 18, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 12), legend.title = element_text(size = 12), legend.position = "bottom") p.heu #ggsave("HEU_manuscript_analysis/figures/microbiome/heu_nmds.pdf", device = "pdf", dpi = 300, width = 6.5, height = 6) # Ordination by Site #### # CAD ord #### cad.dat <- get.nmds.data(cad) cad.p <- ggplot(cad.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, shape = 24) + theme_classic() + scale_shape_manual("", values = shapes[3:4]) + scale_fill_manual("", values = cols[3:4]) + theme(axis.text.x = element_text(size = 14, face = "bold"), axis.text.y = element_text(size = 14, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 16), legend.title = element_text(size = 12), legend.position = "none") cad.p #ggsave("HEU_manuscript_analysis/figures/microbiome/cad_heu_nmds.pdf", device = "pdf", dpi = 300, width = 5, height = 4) # BLG ord #### blg.dat <- get.nmds.data(blg) blg.p <- ggplot(blg.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, shape = 21) + theme_classic() + scale_shape_manual("", values = shapes[1:2]) + scale_fill_manual("", values = cols[1:2]) + theme(axis.text.x = element_text(size = 14, face = "bold"), axis.text.y = element_text(size = 14, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 16), legend.title = element_text(size = 12), legend.position = "none") blg.p #ggsave("HEU_manuscript_analysis/figures/microbiome/blg_heu_nmds.pdf", device = "pdf", dpi = 300, width = 5, height = 4) # SAF ord #### saf.dat <- get.nmds.data(saf) saf.p <- ggplot(saf.dat, aes(x = NMDS1, y =NMDS2, fill = site.exposure, shape = site.exposure)) + geom_point(alpha = 0.9, size = 4, shape = 22) + theme_classic() + scale_shape_manual("", values = shapes[5:6]) + scale_fill_manual("", values = cols[5:6]) + theme(axis.text.x = element_text(size = 14, face = "bold"), axis.text.y = element_text(size = 14, face = "bold"), axis.title.x = element_text(size = 14, face = "bold"), axis.title.y = element_text(size = 14, face = "bold"), axis.line = element_line(size = 0.8), legend.text = element_text(size = 16), legend.title = element_text(size = 12), legend.position = "none") saf.p #ggsave("HEU_manuscript_analysis/figures/microbiome/saf_heu_nmds.pdf", device = "pdf", dpi = 300, width = 5, height = 4) # Adonis Test for Clustering #### # determine the variance explained by HIV exposure for each site separately physeqs <- list(cad, blg, saf) names(physeqs) <- c("cad", "blg", "saf") adonis.tests <- llply(as.list(physeqs), function(i){ df <- data.frame(sample_data(i)) dist <- phyloseq::distance(i, "bray") adonis(dist ~ Exposure, data = df) }) names(adonis.tests) <- names(physeqs) adonis.tests # CAD R2 = 0.03527, p = 0.043 # BLG R2 = 0.03824, p = 0.579 # SAF R2 = 0.0724, p = 0.311 # END ####
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/catboost.R \name{catboost.save_pool} \alias{catboost.save_pool} \title{Save the dataset} \usage{ catboost.save_pool( data, label = NULL, weight = NULL, baseline = NULL, pool_path = "data.pool", cd_path = "cd.pool" ) } \arguments{ \item{data}{A data.frame with features. The following column types are supported: \itemize{ \item double \item factor. It is assumed that categorical features are given in this type of columns. A standard CatBoost processing procedure is applied to this type of columns: \describe{ \item{1.}{The values are converted to strings.} \item{2.}{The ConvertCatFeatureToFloat function is applied to the resulting string.} } } Default value: Required argument} \item{label}{The label vector.} \item{weight}{The weights of the label vector.} \item{baseline}{Vector of initial (raw) values of the label function for the object. Used in the calculation of final values of trees.} \item{pool_path}{The path to the output file that contains the dataset description.} \item{cd_path}{The path to the output file that contains the column descriptions.} } \value{ Nothing. This method writes a dataset to disk. } \description{ Save the dataset to the CatBoost format. Files with the following data are created: \itemize{ \item Dataset description \item Column descriptions } Use the catboost.load_pool function to read the resulting files. These files can also be used in the \href{https://catboost.ai/docs/concepts/cli-installation.html}{Command-line version} and the \href{https://catboost.ai/docs/concepts/python-installation.html}{Python library}. }
/catboost/R-package/man/catboost.save_pool.Rd
permissive
catboost/catboost
R
false
true
1,832
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/catboost.R \name{catboost.save_pool} \alias{catboost.save_pool} \title{Save the dataset} \usage{ catboost.save_pool( data, label = NULL, weight = NULL, baseline = NULL, pool_path = "data.pool", cd_path = "cd.pool" ) } \arguments{ \item{data}{A data.frame with features. The following column types are supported: \itemize{ \item double \item factor. It is assumed that categorical features are given in this type of columns. A standard CatBoost processing procedure is applied to this type of columns: \describe{ \item{1.}{The values are converted to strings.} \item{2.}{The ConvertCatFeatureToFloat function is applied to the resulting string.} } } Default value: Required argument} \item{label}{The label vector.} \item{weight}{The weights of the label vector.} \item{baseline}{Vector of initial (raw) values of the label function for the object. Used in the calculation of final values of trees.} \item{pool_path}{The path to the output file that contains the dataset description.} \item{cd_path}{The path to the output file that contains the column descriptions.} } \value{ Nothing. This method writes a dataset to disk. } \description{ Save the dataset to the CatBoost format. Files with the following data are created: \itemize{ \item Dataset description \item Column descriptions } Use the catboost.load_pool function to read the resulting files. These files can also be used in the \href{https://catboost.ai/docs/concepts/cli-installation.html}{Command-line version} and the \href{https://catboost.ai/docs/concepts/python-installation.html}{Python library}. }
input <- scan("stdin") cat(input[1]-input[2])
/q1001.r
no_license
taehyunkim2/practice
R
false
false
45
r
input <- scan("stdin") cat(input[1]-input[2])
#' dimsum__identify_double_aa_mutations #' #' Identify and annotate double AA substitutions. #' #' @param input_dt input data.table (required) #' @param singles_dt singles data.table (required) #' @param wt_AAseq WT amino acid sequence (required) #' #' @return data.table with double amino acid variants #' @export #' @import data.table dimsum__identify_double_aa_mutations <- function( input_dt, singles_dt, wt_AAseq ){ #WT AA sequences wt_AAseq_split <- strsplit(wt_AAseq,"")[[1]] ### Identify position and identity of double AA mutations ########################### #Double AA mutants doubles <- input_dt[Nham_aa==2] #Add position, mutant AA, WT AA and mean input count doubles[,Pos1 := which(strsplit(aa_seq,"")[[1]] !=wt_AAseq_split)[1],aa_seq] doubles[,Pos2 := which(strsplit(aa_seq,"")[[1]] !=wt_AAseq_split)[2],aa_seq] doubles[,Mut1 := strsplit(aa_seq,"")[[1]][Pos1],aa_seq] doubles[,Mut2 := strsplit(aa_seq,"")[[1]][Pos2],aa_seq] doubles[,WT_AA1 := wt_AAseq_split[Pos1],aa_seq] doubles[,WT_AA2 := wt_AAseq_split[Pos2],aa_seq] #Mean counts doubles <- merge(doubles,singles_dt[,.(Pos,Mut,s1_mean_count = mean_count)],by.x = c("Pos1","Mut1"),by.y = c("Pos","Mut")) doubles <- merge(doubles,singles_dt[,.(Pos,Mut,s2_mean_count = mean_count)],by.x = c("Pos2","Mut2"),by.y = c("Pos","Mut")) return(doubles) }
/R/dimsum__identify_double_aa_mutations.R
permissive
jschmiedel/DiMSum
R
false
false
1,360
r
#' dimsum__identify_double_aa_mutations #' #' Identify and annotate double AA substitutions. #' #' @param input_dt input data.table (required) #' @param singles_dt singles data.table (required) #' @param wt_AAseq WT amino acid sequence (required) #' #' @return data.table with double amino acid variants #' @export #' @import data.table dimsum__identify_double_aa_mutations <- function( input_dt, singles_dt, wt_AAseq ){ #WT AA sequences wt_AAseq_split <- strsplit(wt_AAseq,"")[[1]] ### Identify position and identity of double AA mutations ########################### #Double AA mutants doubles <- input_dt[Nham_aa==2] #Add position, mutant AA, WT AA and mean input count doubles[,Pos1 := which(strsplit(aa_seq,"")[[1]] !=wt_AAseq_split)[1],aa_seq] doubles[,Pos2 := which(strsplit(aa_seq,"")[[1]] !=wt_AAseq_split)[2],aa_seq] doubles[,Mut1 := strsplit(aa_seq,"")[[1]][Pos1],aa_seq] doubles[,Mut2 := strsplit(aa_seq,"")[[1]][Pos2],aa_seq] doubles[,WT_AA1 := wt_AAseq_split[Pos1],aa_seq] doubles[,WT_AA2 := wt_AAseq_split[Pos2],aa_seq] #Mean counts doubles <- merge(doubles,singles_dt[,.(Pos,Mut,s1_mean_count = mean_count)],by.x = c("Pos1","Mut1"),by.y = c("Pos","Mut")) doubles <- merge(doubles,singles_dt[,.(Pos,Mut,s2_mean_count = mean_count)],by.x = c("Pos2","Mut2"),by.y = c("Pos","Mut")) return(doubles) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/expandFunctions.R \name{coefPlot} \alias{coefPlot} \title{Plots coefficients in an impulse response format} \usage{ coefPlot(xObj, includeIntercept = FALSE, type = "h", main = NULL, ...) } \arguments{ \item{xObj}{Output of a fitting model.} \item{includeIntercept}{Should the 1st coefficient be plotted? Default is FALSE.} \item{type}{Graphics type. Default is "h", which results in an impulse-like plot.} \item{main}{"main" title; default is the relative number of non-zero coefficients, a measure of sparsity.} \item{...}{Optional additional graphical parameters, for instance to set ylim to a fixed value.} } \value{ Invisibly returns TRUE. Used for its graphic side effects only. } \description{ Given a model xObj for which coef(xObj) returns a set of coefficients, plot the coefficients. The plots make it easier to compare which features are large, which are set to zero, and how features change from run to run in a graphical manner. If the fitting process is linear (e.g. lm, glmnet, etc.) and the original features are appropriately ordered lags, this will generate an impulse response. Any coefficients that are \emph{exactly} zero (for instance, set that way by LASSO) will appear as red X's; non-zero points will be black O's. } \details{ If includeIntercept==TRUE, the intercept of the model will be plotted as index 0. Changing the type using \code{type="b"} will result in a parallel coordinate-like plot rather than an impulse-like plot. It is sometimes easier to see the differences in coefficients with type="b" rather than type="h". } \examples{ set.seed(1) nObs <- 100 X <- distMat(nObs,6) A <- cbind(c(1,0,-1,rep(0,3))) # Y will only depend on X[,1] and X[,3] Y <- X \%*\% A + 0.1*rnorm(nObs) lassoObj <- easyLASSO(X,Y) Yhat <- predict(lassoObj,newx=X) yyHatPlot(Y,Yhat) coef( lassoObj ) # Sparse coefficients coefPlot( lassoObj ) coefPlot( lassoObj, includeIntercept=TRUE ) coefPlot( lassoObj, type="b" ) }
/man/coefPlot.Rd
no_license
cran/expandFunctions
R
false
true
2,122
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/expandFunctions.R \name{coefPlot} \alias{coefPlot} \title{Plots coefficients in an impulse response format} \usage{ coefPlot(xObj, includeIntercept = FALSE, type = "h", main = NULL, ...) } \arguments{ \item{xObj}{Output of a fitting model.} \item{includeIntercept}{Should the 1st coefficient be plotted? Default is FALSE.} \item{type}{Graphics type. Default is "h", which results in an impulse-like plot.} \item{main}{"main" title; default is the relative number of non-zero coefficients, a measure of sparsity.} \item{...}{Optional additional graphical parameters, for instance to set ylim to a fixed value.} } \value{ Invisibly returns TRUE. Used for its graphic side effects only. } \description{ Given a model xObj for which coef(xObj) returns a set of coefficients, plot the coefficients. The plots make it easier to compare which features are large, which are set to zero, and how features change from run to run in a graphical manner. If the fitting process is linear (e.g. lm, glmnet, etc.) and the original features are appropriately ordered lags, this will generate an impulse response. Any coefficients that are \emph{exactly} zero (for instance, set that way by LASSO) will appear as red X's; non-zero points will be black O's. } \details{ If includeIntercept==TRUE, the intercept of the model will be plotted as index 0. Changing the type using \code{type="b"} will result in a parallel coordinate-like plot rather than an impulse-like plot. It is sometimes easier to see the differences in coefficients with type="b" rather than type="h". } \examples{ set.seed(1) nObs <- 100 X <- distMat(nObs,6) A <- cbind(c(1,0,-1,rep(0,3))) # Y will only depend on X[,1] and X[,3] Y <- X \%*\% A + 0.1*rnorm(nObs) lassoObj <- easyLASSO(X,Y) Yhat <- predict(lassoObj,newx=X) yyHatPlot(Y,Yhat) coef( lassoObj ) # Sparse coefficients coefPlot( lassoObj ) coefPlot( lassoObj, includeIntercept=TRUE ) coefPlot( lassoObj, type="b" ) }
library(sp) library(ggplot2) segntos <- read.csv(file = "C:/Users/Giuseppe Antonelli/Desktop/tesi/segntos.csv") date <- segntos[,32] date <- as.Date(date, format = '%Y%m%d') date <- na.omit(date) mesi <- format(date, '%m') mesi <- as.numeric(mesi) segnalaz <- table(mesi) barplot(segnalaz, main="Segnalazioni per mese", ylab="segnalazioni", xlab="mesi", names.arg=c("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"), cex.names=1.8)
/extract_mesi_wikiplantbase.R
no_license
interacquas/Optmised-sampling
R
false
false
484
r
library(sp) library(ggplot2) segntos <- read.csv(file = "C:/Users/Giuseppe Antonelli/Desktop/tesi/segntos.csv") date <- segntos[,32] date <- as.Date(date, format = '%Y%m%d') date <- na.omit(date) mesi <- format(date, '%m') mesi <- as.numeric(mesi) segnalaz <- table(mesi) barplot(segnalaz, main="Segnalazioni per mese", ylab="segnalazioni", xlab="mesi", names.arg=c("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"), cex.names=1.8)
################################################### ## 1.3.2017 ## Exploratory Analysis Project 1 - Part 3 of 4 ## UC Irvine Data set: Electric power consumption ## Reproduce a histogram of Global Active Power ## Create plot3.png ## Restrict Dates to: 2007-02-01 and 2007-02-02 ## Note: missing data is coded as ? in dataset ################################################### ## Get data fileloc <- "./exdata_data_household_power_consumption/household_power_consumption.txt" readLines(fileloc,10) ## Note: setting column class to "date" expects a certain ordering "year/month/day" ## however the data is set up as "day/month/year". can use read.zoo to set date format, ## but chose to import as character and convert to date columnClasses <- c("character","character","numeric","numeric","numeric","numeric","numeric", "numeric","numeric") EPCdata <- read.table(fileloc, header = TRUE, sep = ";", na.strings = "?", colClasses = columnClasses) ##Data checks summary(EPCdata) colSums(is.na(EPCdata)) table(EPCdata$Date) ## subset data on dates: 2007-02-01 & 2007-02-02 ## "Date" is still character vector, will convert after subsetting ## current format: "d/m/yyyy" EPC <- EPCdata[EPCdata$Date == "1/2/2007"|EPCdata$Date == "2/2/2007", ] ## add datetime; not necessary for plot 1 but needed for the others EPC$Datetime <- strptime(paste(EPC$Date,EPC$Time, sep =" "),format = "%d/%m/%Y %H:%M:%S") ## Open graphical device: png png(filename = "ExData_Plotting1/plot3.png", width = 480, height = 480) ## Recreate graph with(EPC, plot(Datetime,Sub_metering_1, type = "n", xlab = "", ylab = "Energy sub metering")) with(EPC, points(Datetime, Sub_metering_1, type = "l")) with(EPC, points(Datetime, Sub_metering_2, type = "l", col = "red")) with(EPC, points(Datetime, Sub_metering_3, type = "l", col = "blue")) legend("topright", lty = 1,col = c("black","red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) ## Close graphics device dev.off()
/plot3.R
no_license
Michelle-Stutey-Henderson/ExData_Plotting1
R
false
false
2,004
r
################################################### ## 1.3.2017 ## Exploratory Analysis Project 1 - Part 3 of 4 ## UC Irvine Data set: Electric power consumption ## Reproduce a histogram of Global Active Power ## Create plot3.png ## Restrict Dates to: 2007-02-01 and 2007-02-02 ## Note: missing data is coded as ? in dataset ################################################### ## Get data fileloc <- "./exdata_data_household_power_consumption/household_power_consumption.txt" readLines(fileloc,10) ## Note: setting column class to "date" expects a certain ordering "year/month/day" ## however the data is set up as "day/month/year". can use read.zoo to set date format, ## but chose to import as character and convert to date columnClasses <- c("character","character","numeric","numeric","numeric","numeric","numeric", "numeric","numeric") EPCdata <- read.table(fileloc, header = TRUE, sep = ";", na.strings = "?", colClasses = columnClasses) ##Data checks summary(EPCdata) colSums(is.na(EPCdata)) table(EPCdata$Date) ## subset data on dates: 2007-02-01 & 2007-02-02 ## "Date" is still character vector, will convert after subsetting ## current format: "d/m/yyyy" EPC <- EPCdata[EPCdata$Date == "1/2/2007"|EPCdata$Date == "2/2/2007", ] ## add datetime; not necessary for plot 1 but needed for the others EPC$Datetime <- strptime(paste(EPC$Date,EPC$Time, sep =" "),format = "%d/%m/%Y %H:%M:%S") ## Open graphical device: png png(filename = "ExData_Plotting1/plot3.png", width = 480, height = 480) ## Recreate graph with(EPC, plot(Datetime,Sub_metering_1, type = "n", xlab = "", ylab = "Energy sub metering")) with(EPC, points(Datetime, Sub_metering_1, type = "l")) with(EPC, points(Datetime, Sub_metering_2, type = "l", col = "red")) with(EPC, points(Datetime, Sub_metering_3, type = "l", col = "blue")) legend("topright", lty = 1,col = c("black","red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) ## Close graphics device dev.off()
library(caret) ### Name: as.matrix.confusionMatrix ### Title: Confusion matrix as a table ### Aliases: as.matrix.confusionMatrix as.table.confusionMatrix ### Keywords: utilities ### ** Examples ################### ## 2 class example lvs <- c("normal", "abnormal") truth <- factor(rep(lvs, times = c(86, 258)), levels = rev(lvs)) pred <- factor( c( rep(lvs, times = c(54, 32)), rep(lvs, times = c(27, 231))), levels = rev(lvs)) xtab <- table(pred, truth) results <- confusionMatrix(xtab) as.table(results) as.matrix(results) as.matrix(results, what = "overall") as.matrix(results, what = "classes") ################### ## 3 class example xtab <- confusionMatrix(iris$Species, sample(iris$Species)) as.matrix(xtab)
/data/genthat_extracted_code/caret/examples/as.matrix.confusionMatrix.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
806
r
library(caret) ### Name: as.matrix.confusionMatrix ### Title: Confusion matrix as a table ### Aliases: as.matrix.confusionMatrix as.table.confusionMatrix ### Keywords: utilities ### ** Examples ################### ## 2 class example lvs <- c("normal", "abnormal") truth <- factor(rep(lvs, times = c(86, 258)), levels = rev(lvs)) pred <- factor( c( rep(lvs, times = c(54, 32)), rep(lvs, times = c(27, 231))), levels = rev(lvs)) xtab <- table(pred, truth) results <- confusionMatrix(xtab) as.table(results) as.matrix(results) as.matrix(results, what = "overall") as.matrix(results, what = "classes") ################### ## 3 class example xtab <- confusionMatrix(iris$Species, sample(iris$Species)) as.matrix(xtab)
# Travel-app06 # setup.R library(shiny) library(rsconnect) shinyapps::setAccountInfo(name='tohweizhong', token='DF9614818065B5DAAF22AE7D78C38089', secret='uSZ0rCRf6/gKj2ltBXrGENb4kn0y8Cw2bZaA87zk') deployApp(appName = "Travel-app06", account = "tohweizhong")
/Travel-app06/setup.R
no_license
tohweizhong/Travel-app
R
false
false
315
r
# Travel-app06 # setup.R library(shiny) library(rsconnect) shinyapps::setAccountInfo(name='tohweizhong', token='DF9614818065B5DAAF22AE7D78C38089', secret='uSZ0rCRf6/gKj2ltBXrGENb4kn0y8Cw2bZaA87zk') deployApp(appName = "Travel-app06", account = "tohweizhong")
library(scater) library(stringr) options(stringsAsFactors=FALSE) library(pheatmap) library(gtools) library(ggplot2) source("../utils.R") source("runGSEA_preRank.R") args <- commandArgs() tumor <- args[6] outDir <- file.path("dataset",tumor) if(!dir.exists(outDir) ) dir.create(outDir,recursive=TRUE) pathway_file <- "../Data/KEGG_metabolism.gmt" #1. Loading the data selected_sce <- readRDS(file.path("../1-ReadData/dataset/",tumor,"selected_sce.rds")) selected_nontumor_sce <- selected_sce[,selected_sce$cellType!="Malignant"] selected_nontumor_metabolic_sce <- selected_nontumor_sce[rowData(selected_nontumor_sce)$metabolic,] #========================================================================= celltypes <- unique(selected_nontumor_metabolic_sce$cellType) #2.Tumor cells enrich_data_df <- data.frame(x=NULL,y=NULL,NES=NULL,PVAL=NULL) pc_plotdata <- data.frame(x=numeric(),y=numeric(), sel=character(),types=character()) for (t in celltypes){ t2 <- str_replace(t," ","") each_metabolic_sce <- selected_nontumor_metabolic_sce[,selected_nontumor_metabolic_sce$cellType==t] each_metabolic_tpm <- assay(each_metabolic_sce,"exprs") each_metabolic_tpm <- each_metabolic_tpm[rowSums(each_metabolic_tpm)>0,] x <- each_metabolic_tpm ntop <- nrow(x) rv <- rowVars(x) select <- order(rv, decreasing=TRUE)[seq_len(min(ntop, length(rv)))] pca <- prcomp(t(x[select,])) percentVar <- pca$sdev^2 / sum( pca$sdev^2 ) ###select PCs that explain at least 80% of the variance cum_var <- cumsum(percentVar) select_pcs <- which(cum_var>0.8)[1] ###plot the PCA and explained variances tmp_plotdata <- data.frame(x=1:length(percentVar),y=percentVar, sel=c(rep("y",select_pcs),rep("n",length(percentVar)-select_pcs)), types=rep(t,length(percentVar))) pc_plotdata <- rbind(pc_plotdata,tmp_plotdata) ### pre_rank_matrix <- as.matrix(rowSums(abs(pca$rotation[,1:select_pcs]))) runGSEA_preRank(pre_rank_matrix,pathway_file,t2) #get the result result_dir <- list.files(path="preRankResults",pattern = paste0("^",t2,".GseaPreranked(.*)"),full.names=T) result_file <- list.files(path=result_dir,pattern="gsea_report_for_na_pos_(.*).xls",full.names=T) gsea_result <- read.table(result_file,header = T,sep="\t",row.names=1) gsea_pathways <- str_to_title(rownames(gsea_result)) gsea_pathways <- str_replace(gsea_pathways,"Tca","TCA") gsea_pathways <- str_replace(gsea_pathways,"Gpi","GPI") enrich_data_df <- rbind(enrich_data_df,data.frame(x=t2,y=gsea_pathways,NES=gsea_result$NES,PVAL=gsea_result$NOM.p.val)) } #remove pvalue <0.01 pathways min_pval <- by(enrich_data_df$PVAL, enrich_data_df$y, FUN=min) select_pathways <- names(min_pval)[(min_pval<=0.01)] select_enrich_data_df <- enrich_data_df[enrich_data_df$y%in% select_pathways,] #converto pvalue to -log10 pvals <- select_enrich_data_df$PVAL pvals[pvals<=0] = 1e-10 select_enrich_data_df$PVAL <- -log10(pvals) #sort pathway_pv_sum <- by(select_enrich_data_df$PVAL,select_enrich_data_df$y,FUN=sum) pathway_order <- names(pathway_pv_sum)[order(pathway_pv_sum,decreasing = T)] ###########################top 10 ##check before doing this pathway_order <- pathway_order[1:10] select_enrich_data_df <- select_enrich_data_df[select_enrich_data_df$y %in% pathway_order,] ######################################## select_enrich_data_df$y <- factor(select_enrich_data_df$y,levels = pathway_order) # #buble plot p <- ggplot(select_enrich_data_df, aes(x = x, y = y, size = PVAL, color = NES)) + geom_point(shape=19) + #ggtitle("pathway heterogeneity") + labs(x = NULL, y = NULL, size = "-log10 pvalue", color = "NES") + scale_size(range = c(0, 2.5)) + scale_color_gradient( low = "white", high = "red") + #scale_color_gradient2(low="red",mid="white",high="blue",midpoint = 1) + theme(legend.position = "bottom", legend.direction = "horizontal", legend.box = "horizontal", legend.key.size = unit(0.1, "cm"), legend.text = element_text(colour="black",size=6), axis.line = element_line(size=0.3, colour = "black"), #panel.grid.major = element_line(colour = "#d3d3d3"), #panel.grid.minor = element_blank(), axis.ticks = element_line(colour = "black", size = 0.3), panel.border = element_blank(), panel.background = element_blank(), axis.text.x=element_text(colour="black", size = 6,angle=90,hjust=1,vjust=0.5), axis.text.y=element_text(colour="black", size = 6)) + theme(plot.margin = unit(rep(1,4),"lines")) ggsave(file.path(outDir,"non-malignant_enriched_pathway.pdf"),p,width = 3.6,height=2.5,units="in",device="pdf",useDingbats=FALSE) ##plot variance p <- ggplot(pc_plotdata) + geom_point(aes(x,y,colour=factor(sel)),size=0.5) + scale_color_manual(values=c("gray","#ff4000")) + facet_wrap(~factor(types),scales="free",ncol = 4) + theme_bw() + labs(x="Principal components", y="Explained variance (%)") + theme(legend.position="none",panel.grid.major = element_blank(), panel.grid.minor= element_blank(), axis.line=element_line(size=0.2,colour="black"), axis.ticks = element_line(colour = "black",size=0.2), axis.text.x=element_text(colour="black", size = 6), axis.text.y=element_text(colour="black", size = 6), strip.background = element_rect(fill="white",size=0.2,colour = NULL), strip.text=element_text(size=6)) ggsave(file.path(outDir,"non-malignant_PC_variance_plot.pdf"),p,width = 7.5,height=2.7,units="in",device="pdf",useDingbats=FALSE) unlink("preRankResults",recursive=T) unlink("prerank.rnk") date_string <- Sys.Date() date_split <- strsplit(as.character(date_string),"-")[[1]] unlink(paste0(tolower(month.abb[as.numeric(date_split[2])]),date_split[3]),recursive=T)
/6-PathwayHeterogeneity/intra_non-malignant_heterogeneity.R.R
permissive
zhengtaoxiao/Single-Cell-Metabolic-Landscape
R
false
false
5,818
r
library(scater) library(stringr) options(stringsAsFactors=FALSE) library(pheatmap) library(gtools) library(ggplot2) source("../utils.R") source("runGSEA_preRank.R") args <- commandArgs() tumor <- args[6] outDir <- file.path("dataset",tumor) if(!dir.exists(outDir) ) dir.create(outDir,recursive=TRUE) pathway_file <- "../Data/KEGG_metabolism.gmt" #1. Loading the data selected_sce <- readRDS(file.path("../1-ReadData/dataset/",tumor,"selected_sce.rds")) selected_nontumor_sce <- selected_sce[,selected_sce$cellType!="Malignant"] selected_nontumor_metabolic_sce <- selected_nontumor_sce[rowData(selected_nontumor_sce)$metabolic,] #========================================================================= celltypes <- unique(selected_nontumor_metabolic_sce$cellType) #2.Tumor cells enrich_data_df <- data.frame(x=NULL,y=NULL,NES=NULL,PVAL=NULL) pc_plotdata <- data.frame(x=numeric(),y=numeric(), sel=character(),types=character()) for (t in celltypes){ t2 <- str_replace(t," ","") each_metabolic_sce <- selected_nontumor_metabolic_sce[,selected_nontumor_metabolic_sce$cellType==t] each_metabolic_tpm <- assay(each_metabolic_sce,"exprs") each_metabolic_tpm <- each_metabolic_tpm[rowSums(each_metabolic_tpm)>0,] x <- each_metabolic_tpm ntop <- nrow(x) rv <- rowVars(x) select <- order(rv, decreasing=TRUE)[seq_len(min(ntop, length(rv)))] pca <- prcomp(t(x[select,])) percentVar <- pca$sdev^2 / sum( pca$sdev^2 ) ###select PCs that explain at least 80% of the variance cum_var <- cumsum(percentVar) select_pcs <- which(cum_var>0.8)[1] ###plot the PCA and explained variances tmp_plotdata <- data.frame(x=1:length(percentVar),y=percentVar, sel=c(rep("y",select_pcs),rep("n",length(percentVar)-select_pcs)), types=rep(t,length(percentVar))) pc_plotdata <- rbind(pc_plotdata,tmp_plotdata) ### pre_rank_matrix <- as.matrix(rowSums(abs(pca$rotation[,1:select_pcs]))) runGSEA_preRank(pre_rank_matrix,pathway_file,t2) #get the result result_dir <- list.files(path="preRankResults",pattern = paste0("^",t2,".GseaPreranked(.*)"),full.names=T) result_file <- list.files(path=result_dir,pattern="gsea_report_for_na_pos_(.*).xls",full.names=T) gsea_result <- read.table(result_file,header = T,sep="\t",row.names=1) gsea_pathways <- str_to_title(rownames(gsea_result)) gsea_pathways <- str_replace(gsea_pathways,"Tca","TCA") gsea_pathways <- str_replace(gsea_pathways,"Gpi","GPI") enrich_data_df <- rbind(enrich_data_df,data.frame(x=t2,y=gsea_pathways,NES=gsea_result$NES,PVAL=gsea_result$NOM.p.val)) } #remove pvalue <0.01 pathways min_pval <- by(enrich_data_df$PVAL, enrich_data_df$y, FUN=min) select_pathways <- names(min_pval)[(min_pval<=0.01)] select_enrich_data_df <- enrich_data_df[enrich_data_df$y%in% select_pathways,] #converto pvalue to -log10 pvals <- select_enrich_data_df$PVAL pvals[pvals<=0] = 1e-10 select_enrich_data_df$PVAL <- -log10(pvals) #sort pathway_pv_sum <- by(select_enrich_data_df$PVAL,select_enrich_data_df$y,FUN=sum) pathway_order <- names(pathway_pv_sum)[order(pathway_pv_sum,decreasing = T)] ###########################top 10 ##check before doing this pathway_order <- pathway_order[1:10] select_enrich_data_df <- select_enrich_data_df[select_enrich_data_df$y %in% pathway_order,] ######################################## select_enrich_data_df$y <- factor(select_enrich_data_df$y,levels = pathway_order) # #buble plot p <- ggplot(select_enrich_data_df, aes(x = x, y = y, size = PVAL, color = NES)) + geom_point(shape=19) + #ggtitle("pathway heterogeneity") + labs(x = NULL, y = NULL, size = "-log10 pvalue", color = "NES") + scale_size(range = c(0, 2.5)) + scale_color_gradient( low = "white", high = "red") + #scale_color_gradient2(low="red",mid="white",high="blue",midpoint = 1) + theme(legend.position = "bottom", legend.direction = "horizontal", legend.box = "horizontal", legend.key.size = unit(0.1, "cm"), legend.text = element_text(colour="black",size=6), axis.line = element_line(size=0.3, colour = "black"), #panel.grid.major = element_line(colour = "#d3d3d3"), #panel.grid.minor = element_blank(), axis.ticks = element_line(colour = "black", size = 0.3), panel.border = element_blank(), panel.background = element_blank(), axis.text.x=element_text(colour="black", size = 6,angle=90,hjust=1,vjust=0.5), axis.text.y=element_text(colour="black", size = 6)) + theme(plot.margin = unit(rep(1,4),"lines")) ggsave(file.path(outDir,"non-malignant_enriched_pathway.pdf"),p,width = 3.6,height=2.5,units="in",device="pdf",useDingbats=FALSE) ##plot variance p <- ggplot(pc_plotdata) + geom_point(aes(x,y,colour=factor(sel)),size=0.5) + scale_color_manual(values=c("gray","#ff4000")) + facet_wrap(~factor(types),scales="free",ncol = 4) + theme_bw() + labs(x="Principal components", y="Explained variance (%)") + theme(legend.position="none",panel.grid.major = element_blank(), panel.grid.minor= element_blank(), axis.line=element_line(size=0.2,colour="black"), axis.ticks = element_line(colour = "black",size=0.2), axis.text.x=element_text(colour="black", size = 6), axis.text.y=element_text(colour="black", size = 6), strip.background = element_rect(fill="white",size=0.2,colour = NULL), strip.text=element_text(size=6)) ggsave(file.path(outDir,"non-malignant_PC_variance_plot.pdf"),p,width = 7.5,height=2.7,units="in",device="pdf",useDingbats=FALSE) unlink("preRankResults",recursive=T) unlink("prerank.rnk") date_string <- Sys.Date() date_split <- strsplit(as.character(date_string),"-")[[1]] unlink(paste0(tolower(month.abb[as.numeric(date_split[2])]),date_split[3]),recursive=T)
\encoding{UTF8} \name{granplot} \alias{granplot} \title{ Histogram with a cumulative percentage curve } \description{ This function provides a histogram of the grain-size distribution with a cumulative percentage curve } \usage{ granplot(x, xc = 1, meshmin=1, hist = TRUE, cum = TRUE, main = "", col.cum = "red", col.hist="darkgray", cexname=0.9, cexlab=1.3,decreasing=FALSE) } \arguments{ \item{x}{ A numeric matrix or data frame (see the shape of data(granulo)) } \item{xc}{ A numeric value or a numeric vector to define columns } \item{meshmin}{ Define the size of the smallest meshsize if it is 0 in raw data } \item{hist}{ If TRUE, display a histogram; if FALSE, do not display a histogram (only for only one column) } \item{cum}{ If TRUE, display a cumulative percentage curve; if FALSE do not display a cumulative percentage curve (only for only one column) } \item{main}{ Add a title to the current plot } \item{col.cum}{ Color in which cumulative percentage curve will be drawn } \item{col.hist}{ Color in which histogram will be drawn } \item{cexname}{ A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. } \item{cexlab}{ A numerical value giving the amount by which axis labels should be magnified relative to the default. } \item{decreasing}{ A logical value defining the order increasing or decreasing } } \details{ The obtained graph is the most commonly used by Sedimentologists } \value{ A histogram with a cumulative percentage curve } \author{ Regis K. Gallon (MNHN) \email{reg.gallon@gmail.com}, Jerome Fournier (CNRS) \email{fournier@mnhn.fr} } \seealso{ \code{\link[G2Sd]{grandistrib}} } \examples{ data(granulo) granplot(granulo,xc=1,hist=TRUE,cum=TRUE,main="Grain-size Distribution", col.hist="gray",col.cum="red") granplot(granulo,xc=2:4,main="Grain-size Distribution") }
/man/granplot.Rd
no_license
gallonr/G2Sd
R
false
false
1,893
rd
\encoding{UTF8} \name{granplot} \alias{granplot} \title{ Histogram with a cumulative percentage curve } \description{ This function provides a histogram of the grain-size distribution with a cumulative percentage curve } \usage{ granplot(x, xc = 1, meshmin=1, hist = TRUE, cum = TRUE, main = "", col.cum = "red", col.hist="darkgray", cexname=0.9, cexlab=1.3,decreasing=FALSE) } \arguments{ \item{x}{ A numeric matrix or data frame (see the shape of data(granulo)) } \item{xc}{ A numeric value or a numeric vector to define columns } \item{meshmin}{ Define the size of the smallest meshsize if it is 0 in raw data } \item{hist}{ If TRUE, display a histogram; if FALSE, do not display a histogram (only for only one column) } \item{cum}{ If TRUE, display a cumulative percentage curve; if FALSE do not display a cumulative percentage curve (only for only one column) } \item{main}{ Add a title to the current plot } \item{col.cum}{ Color in which cumulative percentage curve will be drawn } \item{col.hist}{ Color in which histogram will be drawn } \item{cexname}{ A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. } \item{cexlab}{ A numerical value giving the amount by which axis labels should be magnified relative to the default. } \item{decreasing}{ A logical value defining the order increasing or decreasing } } \details{ The obtained graph is the most commonly used by Sedimentologists } \value{ A histogram with a cumulative percentage curve } \author{ Regis K. Gallon (MNHN) \email{reg.gallon@gmail.com}, Jerome Fournier (CNRS) \email{fournier@mnhn.fr} } \seealso{ \code{\link[G2Sd]{grandistrib}} } \examples{ data(granulo) granplot(granulo,xc=1,hist=TRUE,cum=TRUE,main="Grain-size Distribution", col.hist="gray",col.cum="red") granplot(granulo,xc=2:4,main="Grain-size Distribution") }
# Copyright (C) 2016-2017,2019 Iñaki Ucar # # This file is part of simmer. # # simmer is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # simmer is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with simmer. If not, see <http://www.gnu.org/licenses/>. context("resource-preemption") test_that("a lower priority arrival gets rejected before accessing the server", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 0)) %>% add_generator("p1a", t, at(2, 3), priority = 1) %>% add_resource("dummy", 1, 2, preemptive = TRUE) %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(as.character(arrs[!arrs$finished, ]$name), "p0a1") expect_equal(arrs_ordered$end_time, c(30, 3, 12, 22)) }) test_that("tasks are NOT restarted", { t0 <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) t1 <- trajectory() %>% seize("dummy", 2) %>% timeout(10) %>% release("dummy", 2) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t0, at(0, 0), restart = FALSE) %>% add_generator("p1a", t1, at(2, 15), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE) %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(30, 30, 12, 25)) expect_equal(arrs_ordered$activity_time, c(10, 10, 10, 10)) }) test_that("tasks are restarted", { t0 <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) t1 <- trajectory() %>% seize("dummy", 2) %>% timeout(10) %>% release("dummy", 2) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t0, at(0, 0), restart = TRUE) %>% add_generator("p1a", t1, at(2, 15), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE) %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(35, 35, 12, 25)) expect_equal(arrs_ordered$activity_time, c(15, 15, 10, 10)) }) test_that("tasks are preempted in a FIFO basis", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 1), restart = TRUE) %>% add_generator("p1a", t, at(2, 3), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE, preempt_order = "fifo") %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(22, 23, 12, 13)) expect_equal(arrs_ordered$activity_time, c(12, 12, 10, 10)) }) test_that("tasks are preempted in a LIFO basis", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 1), restart = TRUE) %>% add_generator("p1a", t, at(2, 3), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE, preempt_order = "lifo") %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(22, 23, 12, 13)) expect_equal(arrs_ordered$activity_time, c(13, 11, 10, 10)) }) test_that("queue can exceed queue_size by default", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 0)) %>% add_generator("p1a", t, at(1), priority = 1) %>% add_resource("dummy", 1, 1, preemptive = TRUE) %>% run() res <- env %>% get_mon_resources() arr <- env %>% get_mon_arrivals() arr_ordered <- arr[order(arr$name), ] expect_equal(res$time, c(0, 0, 1, 11, 20, 30)) expect_equal(res$server, c(1, 1, 1, 1, 1, 0)) expect_equal(res$queue, c(0, 1, 2, 1, 0, 0)) expect_equal(arr_ordered$end_time, c(20, 30, 11)) expect_equal(arr_ordered$activity_time, c(10, 10, 10)) expect_equal(arr_ordered$finished, c(TRUE, TRUE, TRUE)) }) test_that("queue cannot exceed queue_size with hard limit (preempted rejected)", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 0)) %>% add_generator("p1a", t, at(1), priority = 1) %>% add_resource("dummy", 1, 1, preemptive = TRUE, queue_size_strict = TRUE) %>% run() res <- env %>% get_mon_resources() arr <- env %>% get_mon_arrivals() arr_ordered <- arr[order(arr$name), ] expect_equal(res$time, c(0, 0, 1, 11, 21)) expect_equal(res$server, c(1, 1, 1, 1, 0)) expect_equal(res$queue, c(0, 1, 1, 0, 0)) expect_equal(arr_ordered$end_time, c(1, 21, 11)) expect_equal(arr_ordered$activity_time, c(1, 10, 10)) expect_equal(arr_ordered$finished, c(FALSE, TRUE, TRUE)) }) test_that("queue cannot exceed queue_size with hard limit (preempted to queue)", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy") env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0), priority = 0) %>% add_generator("p1a", t, at(0), priority = 1) %>% add_generator("p2a", t, at(1), priority = 2) %>% add_resource("dummy", 1, 1, preemptive = TRUE, queue_size_strict = TRUE) %>% run() res <- env %>% get_mon_resources() arr <- env %>% get_mon_arrivals() arr_ordered <- arr[order(arr$name), ] expect_equal(res$time, c(0, 0, 1, 11, 20)) expect_equal(res$server, c(1, 1, 1, 1, 0)) expect_equal(res$queue, c(0, 1, 1, 0, 0)) expect_equal(arr_ordered$end_time, c(1, 20, 11)) expect_equal(arr_ordered$activity_time, c(0, 10, 10)) expect_equal(arr_ordered$finished, c(FALSE, TRUE, TRUE)) }) test_that("preemption works in non-saturated multi-server resources", { low_prio <- trajectory() %>% seize("res", 1) %>% timeout(10) %>% release("res", 1) high_prio <- trajectory() %>% seize("res", 7) %>% timeout(10) %>% release("res", 7) env <- simmer(verbose = TRUE) %>% add_resource("res", 10, preemptive = TRUE) %>% add_generator("low_prio", low_prio, at(rep(0, 5))) %>% add_generator("high_prio", high_prio, at(1), priority = 1) %>% run() arr <- get_mon_arrivals(env) expect_equal(arr$start_time, c(0, 0, 0, 1, 0, 0)) expect_equal(arr$end_time, c(10, 10, 10, 11, 19, 19)) expect_equal(arr$activity_time, rep(10, 6)) }) test_that("preemption works properly for a previously stopped arrival", { new_timeout <- trajectory() %>% timeout(1) customer <- trajectory() %>% seize("res") %>% trap("signal", new_timeout) %>% timeout(5) %>% release("res") blocker <- trajectory() %>% send("signal") %>% seize("res") %>% timeout(20) %>% release("res") arr <- simmer(verbose=TRUE) %>% add_resource("res", preemptive=TRUE) %>% add_generator("customer", customer, at(0)) %>% add_generator("blocker", blocker, at(2), priority=10) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, c(2, 0)) expect_equal(arr$end_time, c(22, 23)) expect_equal(arr$activity_time, c(20, 3)) }) test_that("arrivals wait until dequeued from all resources", { lprio <- trajectory() %>% seize("one") %>% # "one" seized seize("two") %>% # enqueued in "two" timeout(10) %>% release_all() hprio <- trajectory() %>% seize("one") %>% # preempts lprio in "one" set_capacity("two", 1) %>% # dequeues lprio in "two" timeout(100) %>% release_all() arr <- simmer(verbose=TRUE) %>% add_resource("one", 1, preemptive=TRUE) %>% add_resource("two", 0) %>% add_generator("lprio", lprio, at(0), priority=0) %>% add_generator("hprio", hprio, at(1), priority=1) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, c(1, 0)) expect_equal(arr$end_time, c(101, 111)) expect_equal(arr$activity_time, c(100, 10)) expect_equal(arr$finished, c(TRUE, TRUE)) }) test_that("rejected arrivals leave all queues", { out <- trajectory() %>% timeout(1) lprio <- trajectory() %>% handle_unfinished(out) %>% seize("one") %>% # "one" seized seize("two") %>% # enqueued in "two" timeout(10) %>% release_all() hprio <- trajectory() %>% seize("one") %>% # preempts and rejects lprio from "one" timeout(100) %>% release_all() arr <- simmer(verbose=TRUE) %>% add_resource("one", 1, 0, preemptive=TRUE, queue_size_strict=TRUE) %>% add_resource("two", 0) %>% add_generator("lprio", lprio, at(0), priority=0) %>% add_generator("hprio", hprio, at(1), priority=1) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, c(0, 1)) expect_equal(arr$end_time, c(2, 101)) expect_equal(arr$activity_time, c(1, 100)) expect_equal(arr$finished, c(TRUE, TRUE)) })
/simmer/tests/testthat/test-simmer-resource-preemption.R
no_license
akhikolla/TestedPackages-NoIssues
R
false
false
9,401
r
# Copyright (C) 2016-2017,2019 Iñaki Ucar # # This file is part of simmer. # # simmer is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # simmer is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with simmer. If not, see <http://www.gnu.org/licenses/>. context("resource-preemption") test_that("a lower priority arrival gets rejected before accessing the server", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 0)) %>% add_generator("p1a", t, at(2, 3), priority = 1) %>% add_resource("dummy", 1, 2, preemptive = TRUE) %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(as.character(arrs[!arrs$finished, ]$name), "p0a1") expect_equal(arrs_ordered$end_time, c(30, 3, 12, 22)) }) test_that("tasks are NOT restarted", { t0 <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) t1 <- trajectory() %>% seize("dummy", 2) %>% timeout(10) %>% release("dummy", 2) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t0, at(0, 0), restart = FALSE) %>% add_generator("p1a", t1, at(2, 15), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE) %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(30, 30, 12, 25)) expect_equal(arrs_ordered$activity_time, c(10, 10, 10, 10)) }) test_that("tasks are restarted", { t0 <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) t1 <- trajectory() %>% seize("dummy", 2) %>% timeout(10) %>% release("dummy", 2) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t0, at(0, 0), restart = TRUE) %>% add_generator("p1a", t1, at(2, 15), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE) %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(35, 35, 12, 25)) expect_equal(arrs_ordered$activity_time, c(15, 15, 10, 10)) }) test_that("tasks are preempted in a FIFO basis", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 1), restart = TRUE) %>% add_generator("p1a", t, at(2, 3), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE, preempt_order = "fifo") %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(22, 23, 12, 13)) expect_equal(arrs_ordered$activity_time, c(12, 12, 10, 10)) }) test_that("tasks are preempted in a LIFO basis", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 1), restart = TRUE) %>% add_generator("p1a", t, at(2, 3), priority = 1) %>% add_resource("dummy", 2, preemptive = TRUE, preempt_order = "lifo") %>% run() arrs <- env %>% get_mon_arrivals() arrs_ordered <- arrs[order(arrs$name), ] expect_equal(arrs_ordered$end_time, c(22, 23, 12, 13)) expect_equal(arrs_ordered$activity_time, c(13, 11, 10, 10)) }) test_that("queue can exceed queue_size by default", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 0)) %>% add_generator("p1a", t, at(1), priority = 1) %>% add_resource("dummy", 1, 1, preemptive = TRUE) %>% run() res <- env %>% get_mon_resources() arr <- env %>% get_mon_arrivals() arr_ordered <- arr[order(arr$name), ] expect_equal(res$time, c(0, 0, 1, 11, 20, 30)) expect_equal(res$server, c(1, 1, 1, 1, 1, 0)) expect_equal(res$queue, c(0, 1, 2, 1, 0, 0)) expect_equal(arr_ordered$end_time, c(20, 30, 11)) expect_equal(arr_ordered$activity_time, c(10, 10, 10)) expect_equal(arr_ordered$finished, c(TRUE, TRUE, TRUE)) }) test_that("queue cannot exceed queue_size with hard limit (preempted rejected)", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy", 1) env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0, 0)) %>% add_generator("p1a", t, at(1), priority = 1) %>% add_resource("dummy", 1, 1, preemptive = TRUE, queue_size_strict = TRUE) %>% run() res <- env %>% get_mon_resources() arr <- env %>% get_mon_arrivals() arr_ordered <- arr[order(arr$name), ] expect_equal(res$time, c(0, 0, 1, 11, 21)) expect_equal(res$server, c(1, 1, 1, 1, 0)) expect_equal(res$queue, c(0, 1, 1, 0, 0)) expect_equal(arr_ordered$end_time, c(1, 21, 11)) expect_equal(arr_ordered$activity_time, c(1, 10, 10)) expect_equal(arr_ordered$finished, c(FALSE, TRUE, TRUE)) }) test_that("queue cannot exceed queue_size with hard limit (preempted to queue)", { t <- trajectory() %>% seize("dummy", 1) %>% timeout(10) %>% release("dummy") env <- simmer(verbose = TRUE) %>% add_generator("p0a", t, at(0), priority = 0) %>% add_generator("p1a", t, at(0), priority = 1) %>% add_generator("p2a", t, at(1), priority = 2) %>% add_resource("dummy", 1, 1, preemptive = TRUE, queue_size_strict = TRUE) %>% run() res <- env %>% get_mon_resources() arr <- env %>% get_mon_arrivals() arr_ordered <- arr[order(arr$name), ] expect_equal(res$time, c(0, 0, 1, 11, 20)) expect_equal(res$server, c(1, 1, 1, 1, 0)) expect_equal(res$queue, c(0, 1, 1, 0, 0)) expect_equal(arr_ordered$end_time, c(1, 20, 11)) expect_equal(arr_ordered$activity_time, c(0, 10, 10)) expect_equal(arr_ordered$finished, c(FALSE, TRUE, TRUE)) }) test_that("preemption works in non-saturated multi-server resources", { low_prio <- trajectory() %>% seize("res", 1) %>% timeout(10) %>% release("res", 1) high_prio <- trajectory() %>% seize("res", 7) %>% timeout(10) %>% release("res", 7) env <- simmer(verbose = TRUE) %>% add_resource("res", 10, preemptive = TRUE) %>% add_generator("low_prio", low_prio, at(rep(0, 5))) %>% add_generator("high_prio", high_prio, at(1), priority = 1) %>% run() arr <- get_mon_arrivals(env) expect_equal(arr$start_time, c(0, 0, 0, 1, 0, 0)) expect_equal(arr$end_time, c(10, 10, 10, 11, 19, 19)) expect_equal(arr$activity_time, rep(10, 6)) }) test_that("preemption works properly for a previously stopped arrival", { new_timeout <- trajectory() %>% timeout(1) customer <- trajectory() %>% seize("res") %>% trap("signal", new_timeout) %>% timeout(5) %>% release("res") blocker <- trajectory() %>% send("signal") %>% seize("res") %>% timeout(20) %>% release("res") arr <- simmer(verbose=TRUE) %>% add_resource("res", preemptive=TRUE) %>% add_generator("customer", customer, at(0)) %>% add_generator("blocker", blocker, at(2), priority=10) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, c(2, 0)) expect_equal(arr$end_time, c(22, 23)) expect_equal(arr$activity_time, c(20, 3)) }) test_that("arrivals wait until dequeued from all resources", { lprio <- trajectory() %>% seize("one") %>% # "one" seized seize("two") %>% # enqueued in "two" timeout(10) %>% release_all() hprio <- trajectory() %>% seize("one") %>% # preempts lprio in "one" set_capacity("two", 1) %>% # dequeues lprio in "two" timeout(100) %>% release_all() arr <- simmer(verbose=TRUE) %>% add_resource("one", 1, preemptive=TRUE) %>% add_resource("two", 0) %>% add_generator("lprio", lprio, at(0), priority=0) %>% add_generator("hprio", hprio, at(1), priority=1) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, c(1, 0)) expect_equal(arr$end_time, c(101, 111)) expect_equal(arr$activity_time, c(100, 10)) expect_equal(arr$finished, c(TRUE, TRUE)) }) test_that("rejected arrivals leave all queues", { out <- trajectory() %>% timeout(1) lprio <- trajectory() %>% handle_unfinished(out) %>% seize("one") %>% # "one" seized seize("two") %>% # enqueued in "two" timeout(10) %>% release_all() hprio <- trajectory() %>% seize("one") %>% # preempts and rejects lprio from "one" timeout(100) %>% release_all() arr <- simmer(verbose=TRUE) %>% add_resource("one", 1, 0, preemptive=TRUE, queue_size_strict=TRUE) %>% add_resource("two", 0) %>% add_generator("lprio", lprio, at(0), priority=0) %>% add_generator("hprio", hprio, at(1), priority=1) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, c(0, 1)) expect_equal(arr$end_time, c(2, 101)) expect_equal(arr$activity_time, c(1, 100)) expect_equal(arr$finished, c(TRUE, TRUE)) })
library(qrcmNP) ### Name: summary.piqr ### Title: Summary After Penalized Quantile Regression Coefficients ### Modeling ### Aliases: summary.piqr ### ** Examples # using simulated data set.seed(1234) n <- 300 x1 <- rexp(n) x2 <- runif(n, 0, 5) x <- cbind(x1,x2) b <- function(p){matrix(cbind(1, qnorm(p), slp(p, 2)), nrow=4, byrow=TRUE)} theta <- matrix(0, nrow=3, ncol=4); theta[, 1] <- 1; theta[1,2] <- 1; theta[2:3,3] <- 2 qy <- function(p, theta, b, x){rowSums(x * t(theta %*% b(p)))} y <- qy(runif(n), theta, b, cbind(1, x)) s <- matrix(1, nrow=3, ncol=4); s[1,3:4] <- 0 obj <- piqr(y ~ x1 + x2, formula.p = ~ I(qnorm(p)) + slp(p, 2), s=s, nlambda=50) best <- gof.piqr(obj, method="AIC", plot=FALSE) best2 <- gof.piqr(obj, method="BIC", plot=FALSE) summary(obj, best$minLambda) summary(obj, best2$minLambda)
/data/genthat_extracted_code/qrcmNP/examples/summary.piqr.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
829
r
library(qrcmNP) ### Name: summary.piqr ### Title: Summary After Penalized Quantile Regression Coefficients ### Modeling ### Aliases: summary.piqr ### ** Examples # using simulated data set.seed(1234) n <- 300 x1 <- rexp(n) x2 <- runif(n, 0, 5) x <- cbind(x1,x2) b <- function(p){matrix(cbind(1, qnorm(p), slp(p, 2)), nrow=4, byrow=TRUE)} theta <- matrix(0, nrow=3, ncol=4); theta[, 1] <- 1; theta[1,2] <- 1; theta[2:3,3] <- 2 qy <- function(p, theta, b, x){rowSums(x * t(theta %*% b(p)))} y <- qy(runif(n), theta, b, cbind(1, x)) s <- matrix(1, nrow=3, ncol=4); s[1,3:4] <- 0 obj <- piqr(y ~ x1 + x2, formula.p = ~ I(qnorm(p)) + slp(p, 2), s=s, nlambda=50) best <- gof.piqr(obj, method="AIC", plot=FALSE) best2 <- gof.piqr(obj, method="BIC", plot=FALSE) summary(obj, best$minLambda) summary(obj, best2$minLambda)
install.packages("caret") install.packages("rpart") install.packages("tree") install.packages("randomForest") install.packages("e1071") install.packages("ggplot2")
/assignment5/setup.r
no_license
reidy-p/datasci_course_materials
R
false
false
164
r
install.packages("caret") install.packages("rpart") install.packages("tree") install.packages("randomForest") install.packages("e1071") install.packages("ggplot2")
#' RM2C2: Scoring, Summarizing #' @name filter_cog_duplicate_records #' @param df class: numeric; original X #' @param group_vars class: vector; factors to group data by #' @param time_var class: vector; variable for time #' @keywords m2c2, cognition #' @import tidyverse #' @examples #' filter_cog_duplicate_records(df) #' @export filter_cog_duplicate_records <- function(df) { return(df %>% distinct()) }
/R/filter_cog_duplicate_records.R
permissive
nelsonroque/surveydolphinr
R
false
false
412
r
#' RM2C2: Scoring, Summarizing #' @name filter_cog_duplicate_records #' @param df class: numeric; original X #' @param group_vars class: vector; factors to group data by #' @param time_var class: vector; variable for time #' @keywords m2c2, cognition #' @import tidyverse #' @examples #' filter_cog_duplicate_records(df) #' @export filter_cog_duplicate_records <- function(df) { return(df %>% distinct()) }
## 8 R로 데이터 읽어오기 ## 8.0.1 주요 내용 install.packages('AER') library('AER') # R 내장 데이터 : data() # 기본적인 방법 : read.table/write.table,load/save # 텍스트로 저장된 화일 읽어오기 # -read.csv # -빅데이터: data.table::fread,readr::read_csv # 엑셀화일: readxl::read_excel # 웹에서 긁어오기: htmltab, readHTMLTable ## 8.1 R 내장 데이터 data(mtcars) head(mtcars, n=3) data("BankWages", package='AER') head(BankWages, n=3) ## 8.2 들어가기 : write.table/read.table, save/load dat <- mtcars head(dat, n=3) class(dat) write.table(dat, file='dat.txt') dat02 <- read.table(file='dat.txt') all.equal(dat, dat02) dat <- mtcars save(dat, file='dat.RData') datBackup <- dat rm(dat) head(dat) # Error in head(dat) : object 'dat' not found load(file='dat.RData') head(dat, n=3) all.equal(dat, datBackup) file.size('dat.txt') file.size('dat.RData') # ubuntu에서는 3835(아마도 데이터가 크지 않아서) vs 1780 object.size(dat) ## 8.3 텍스트로 저장된 데이터 화일 읽기 ## 8.3.1 직접 텍스트 데이터 화일을 작성해 보기 datMsg <- data.frame( name = c("BTS", "트와이스", "케이티 킴"), phone = c('010-4342-5842', '010-5821-4433', '010-5532-4432'), usageLastMonth = c(38000, 58000,31000), message = c('안녕, 날씨 좋다! "가즈아!"라고 말하고 싶다.', '달빛 아래 춤추자! \'너무너무너무\'라고 노래 부를래.', 'Memorable'), price = c(30, 10, NA), stringsAsFactors=FALSE) datMsg ## 8.3.2 확장자 csv write.csv(datMsg, file='dat.csv') datMsg02 <- read.csv(file='dat.csv') all.equal(datMsg, datMsg02) head(datMsg02, 3) datMsg03 <- read.csv(file='dat.csv', row.names=1, stringsAsFactors=FALSE) all.equal(datMsg, datMsg03) ## 8.3.3 텍스트 데이터 화일을 불러읽기 # 1. 텍스트 인코딩 # readr::guess_encoding 을 통해 유추 가능. 하지만 확실치 않음 # # notepad++^3 등의 문서작성 프로그램을 활용하여 인코딩을 확인할 수도 있다. # 특히 UTF-8BOM과 UTF-8의 구분은 readr::guess_encoding()에서는 불가능 하지만 notepad++에서는 가능 # # 2. 전체적인 형식: 아래에서 c(,) 로 묶인 원소 중 하나를 선택해야 한다. # 예) header=TRUE 또는 header = FALSE # # 행이름을 포함하는가? header=c(TRUE,FALSE) # 열이름을 포함하는가? row.names = c(1,NULL) # 열 구분자(delimiter) sep=c('\t',',','') # # 3.데이터를 표기하는 방법 # 주석은 어떻게 구분하는가? comment.char = # 따옴표(quotation mark; 문자열 속에 열 구분자를 포함시켜야 할 경우를 생각해보자): quote= # 소수점 표기 방법(decimal seperator): dec=(나라마다 소수점 표기방법이 다르다.) # # 4.그밖에 # stringsAsFactors = c(TRUE,FALSE) # 파일 불러오는 경우 디렉토리 getwd()를 통해 확인해야함 # dat01 <- read.csv('Seoul_Hangang_Tourist_2009_2013.csv', fileEncoding = 'UTF-8') # dat01 <- read.csv('서울시 한강공원 이용객 현황 (2009_2013년).csv', fileEncoding = 'UTF-8') #dat01 <- read.csv('Seoul_Hangang_Tourist_2009_2013.csv', header = TRUE) dat01 <- read.csv('서울시 한강공원 이용객 현황 (2009_2013년).csv', fileEncoding = 'UTF-8') # windows에서는 에러. ubuntu에서는 정상적으로 읽어들임. dat02 <- read.csv('서울특별시 공공자전거 대여소별 이용정보(월간)_2017_1_12.csv', fileEncoding = 'cp949', quote="'") # unbuntu dat02 <- read.csv('서울특별시 공공자전거 대여소별 이용정보(월간)_2017_1_12.csv', quote="'") # windows에서는 정상 작동. # ubuntu에서는, # Error in make.names(col.names, unique = TRUE) : # invalid multibyte string at '<b4>뿩<c0><cf><c0><da>' dat02 <- read.csv('서울특별시 공공자전거 대여소별 이용정보(월간)_2017_1_12.csv', quote="'", fileEncoding = 'EUC-KR') # ubuntu에서 정상 작동 dat03 <- read.csv('http://www.nber.org/data/population-birthplace-diversity/JoEG_BP_diversity_data.csv') head(dat03, n=3) ## 8.3.5 윈도우에서 인코딩 문제 dat1 <- read.table('UTF-8test.txt', sep=',', fileEncoding = 'UTF-8', stringsAsFactors = FALSE); dat1 dat2 <- readr::read_delim('UTF-8test.txt', delim = ',', col_names = FALSE); dat2 dat3 <- data.table::fread('UTF-8test.txt', sep = ',', header = FALSE, encoding = 'UTF-8'); dat3 dat1 <- read.table('UTF-8test.txt', sep = ',', fileEncoding = 'UTF-8', stringsAsFactors = FALSE) dat1 ## ubuntu에서는 문제 없음 dat2 <- readr::read_delim('UTF-8test.txt', delim = ',', col_names = FALSE) dat2 dat3 <- data.table::fread('UTF-8test.txt', sep = ',', header = FALSE, encoding = 'UTF-8'); dat3 dat1$V1 # ubuntu에서는 정상 작동 dat3$V1 dat3df <- as.data.frame(dat3); dat3tb <- tibble::as_tibble(dat3) print(dat3df) print(dat3df$V1) ## 8.4 EXCEL 화일 읽기 # install.packages("xlsx") # ubuntu> # sudo apt update -y # sudo apt install -y openjdk-8-jdk openjdk-8-jre # sudo R CMD javareconf # *** JAVA_HOME is not a valid path, ignoring # Java interpreter : /usr/bin/java # Java version : 1.8.0_252 # Java home path : /usr/lib/jvm/java-8-openjdk-amd64/jre # Java compiler : /usr/bin/javac # Java headers gen.: /usr/bin/javah # Java archive tool: /usr/bin/jar # trying to compile and link a JNI program # detected JNI cpp flags : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux # detected JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm # gcc -std=gnu99 -I"/usr/share/R/include" -DNDEBUG -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include/linux -fpic -g -O2 -fdebug-prefix-map=/home/jranke/git/r-backports/stretch/r-base-3.6.3=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c conftest.c -o conftest.o # gcc -std=gnu99 -shared -L/usr/lib/R/lib -Wl,-z,relro -o conftest.so conftest.o -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server -ljvm -L/usr/lib/R/lib -lR # # # JAVA_HOME : /usr/lib/jvm/java-8-openjdk-amd64/jre # Java library path: $(JAVA_HOME)/lib/amd64/server # JNI cpp flags : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux # JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm # Updating Java configuration in /usr/lib/R # Done. #install.packages("rJava") #java libs : '-L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm' #checking whether Java run-time works... ./configure: line 3796: /usr/lib/jvm/default-java/jre/bin/java: No such file or directory #no #configure: error: Java interpreter '/usr/lib/jvm/default-java/jre/bin/java' does not work #ERROR: configuration failed for package ‘rJava’ #* removing ‘/home/master/R/x86_64-pc-linux-gnu-library/3.6/rJava’ #Warning in install.packages : # installation of package ‘rJava’ had non-zero exit status # require(rJava) # ubuntu와 windows에서 java 설치 방법??? #Loading required package: rJava #Error: package or namespace load failed for ‘rJava’: # .onLoad failed in loadNamespace() for 'rJava', details: # call: dyn.load(file, DLLpath = DLLpath, ...) #error: unable to load shared object '/home/master/R/x86_64-pc-linux-gnu-library/3.6/rJava/libs/rJava.so': # libjvm.so: cannot open shared object file: No such file or directory # rJava 설치 on ubuntu # https://wikidocs.net/52630 #install.packages('xlsx') ## 8.4 EXCEL 화일 읽기 # readxl::excel_sheets(path= ) # readxl::read_excel(path= , sheet= ) library(readxl) readxl::read_excel('서울시 한강공원 이용객 현황 (2009_2013년).xls', sheet=1) #Error(Ubuntu): # filepath: 서울시 한강공원 이용객 현황 (2009_2013년).xls # libxls error: Unable to open file readxl::read_xlsx('서울시 한강공원 이용객 현황 (2009_2013년).xls', sheet=1) # 8.4.1 library(readxl) rm(list=ls()) fn = "excel_example.xls" vSh <- excel_sheets(fn) #li <- vector(mode="list", length=length(vSh)-1) if ( length(vSh) > 0 ) { for (iSh in 1:(length(vSh))) { vname <- vSh[iSh] if (exists(vname)) { cat('\b\b변수 ', vname, '이(가) 이미 존재합니다.\n') break } assign(vname, read_excel(fn, sheet=vSh[iSh])) } } else { cat('No Sheet!!!\n') } vSh ls() # 8.5 install.packages('foreign') install.packages('haven') # 기본값이 없는 인수에 대한 오류 library(foreign) #read.spss() # SPSS #read.dta() # Stata #read.ssd() # SAS #read.octave() # Octave #read.mtp() # Minitab #read.systat() # Systat library(haven) #read_dta() # Stata #read_por() # SPSS .por #read_sas() # SAS #read_sav() # SPSS .sav, .zsav #read_stata() # Stata #read_xpt() # SAS transport files url = 'http://www.nber.org/data/population-birthplace-diversity/JoEG_BP_diversity_data.dta' # 8.5.1 # 8.5.2 #install.packages('htmltab') library(htmltab) url <- "https://en.wikipedia.org/wiki/List_of_most_common_surnames_in_Europe" surnames <- htmltab(doc = url, which = 13) head(surnames, n=10) #install.packages('XML') #install.packages("RCurl") #install.packages("rlist") library(XML) library(RCurl) library(rlist) url <- "https://en.wikipedia.org/wiki/List_of_most_common_surnames_in_Europe" theurl <- getURL(url, .opts = list(ssl.verifypeer = FALSE) ) # Windows에서 다음과 같은 에러가 발생(ubuntu는 정상작동) # error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version # RCurl은 더 이상 관리되지 않는다고 함. #https://stackoverflow.com/questions/31504983/rcurl-geturl-ssl-error library(curl) con <- curl(url) html <- readLines(con) df <- readHTMLTable(html, header = TRUE, which = 13, stringsAsFactors = FALSE, encoding = "UTF-8") head(df, n=10)
/08_ImportData_seolbin_edited.R
no_license
Sumeun/DSwithRv2
R
false
false
10,210
r
## 8 R로 데이터 읽어오기 ## 8.0.1 주요 내용 install.packages('AER') library('AER') # R 내장 데이터 : data() # 기본적인 방법 : read.table/write.table,load/save # 텍스트로 저장된 화일 읽어오기 # -read.csv # -빅데이터: data.table::fread,readr::read_csv # 엑셀화일: readxl::read_excel # 웹에서 긁어오기: htmltab, readHTMLTable ## 8.1 R 내장 데이터 data(mtcars) head(mtcars, n=3) data("BankWages", package='AER') head(BankWages, n=3) ## 8.2 들어가기 : write.table/read.table, save/load dat <- mtcars head(dat, n=3) class(dat) write.table(dat, file='dat.txt') dat02 <- read.table(file='dat.txt') all.equal(dat, dat02) dat <- mtcars save(dat, file='dat.RData') datBackup <- dat rm(dat) head(dat) # Error in head(dat) : object 'dat' not found load(file='dat.RData') head(dat, n=3) all.equal(dat, datBackup) file.size('dat.txt') file.size('dat.RData') # ubuntu에서는 3835(아마도 데이터가 크지 않아서) vs 1780 object.size(dat) ## 8.3 텍스트로 저장된 데이터 화일 읽기 ## 8.3.1 직접 텍스트 데이터 화일을 작성해 보기 datMsg <- data.frame( name = c("BTS", "트와이스", "케이티 킴"), phone = c('010-4342-5842', '010-5821-4433', '010-5532-4432'), usageLastMonth = c(38000, 58000,31000), message = c('안녕, 날씨 좋다! "가즈아!"라고 말하고 싶다.', '달빛 아래 춤추자! \'너무너무너무\'라고 노래 부를래.', 'Memorable'), price = c(30, 10, NA), stringsAsFactors=FALSE) datMsg ## 8.3.2 확장자 csv write.csv(datMsg, file='dat.csv') datMsg02 <- read.csv(file='dat.csv') all.equal(datMsg, datMsg02) head(datMsg02, 3) datMsg03 <- read.csv(file='dat.csv', row.names=1, stringsAsFactors=FALSE) all.equal(datMsg, datMsg03) ## 8.3.3 텍스트 데이터 화일을 불러읽기 # 1. 텍스트 인코딩 # readr::guess_encoding 을 통해 유추 가능. 하지만 확실치 않음 # # notepad++^3 등의 문서작성 프로그램을 활용하여 인코딩을 확인할 수도 있다. # 특히 UTF-8BOM과 UTF-8의 구분은 readr::guess_encoding()에서는 불가능 하지만 notepad++에서는 가능 # # 2. 전체적인 형식: 아래에서 c(,) 로 묶인 원소 중 하나를 선택해야 한다. # 예) header=TRUE 또는 header = FALSE # # 행이름을 포함하는가? header=c(TRUE,FALSE) # 열이름을 포함하는가? row.names = c(1,NULL) # 열 구분자(delimiter) sep=c('\t',',','') # # 3.데이터를 표기하는 방법 # 주석은 어떻게 구분하는가? comment.char = # 따옴표(quotation mark; 문자열 속에 열 구분자를 포함시켜야 할 경우를 생각해보자): quote= # 소수점 표기 방법(decimal seperator): dec=(나라마다 소수점 표기방법이 다르다.) # # 4.그밖에 # stringsAsFactors = c(TRUE,FALSE) # 파일 불러오는 경우 디렉토리 getwd()를 통해 확인해야함 # dat01 <- read.csv('Seoul_Hangang_Tourist_2009_2013.csv', fileEncoding = 'UTF-8') # dat01 <- read.csv('서울시 한강공원 이용객 현황 (2009_2013년).csv', fileEncoding = 'UTF-8') #dat01 <- read.csv('Seoul_Hangang_Tourist_2009_2013.csv', header = TRUE) dat01 <- read.csv('서울시 한강공원 이용객 현황 (2009_2013년).csv', fileEncoding = 'UTF-8') # windows에서는 에러. ubuntu에서는 정상적으로 읽어들임. dat02 <- read.csv('서울특별시 공공자전거 대여소별 이용정보(월간)_2017_1_12.csv', fileEncoding = 'cp949', quote="'") # unbuntu dat02 <- read.csv('서울특별시 공공자전거 대여소별 이용정보(월간)_2017_1_12.csv', quote="'") # windows에서는 정상 작동. # ubuntu에서는, # Error in make.names(col.names, unique = TRUE) : # invalid multibyte string at '<b4>뿩<c0><cf><c0><da>' dat02 <- read.csv('서울특별시 공공자전거 대여소별 이용정보(월간)_2017_1_12.csv', quote="'", fileEncoding = 'EUC-KR') # ubuntu에서 정상 작동 dat03 <- read.csv('http://www.nber.org/data/population-birthplace-diversity/JoEG_BP_diversity_data.csv') head(dat03, n=3) ## 8.3.5 윈도우에서 인코딩 문제 dat1 <- read.table('UTF-8test.txt', sep=',', fileEncoding = 'UTF-8', stringsAsFactors = FALSE); dat1 dat2 <- readr::read_delim('UTF-8test.txt', delim = ',', col_names = FALSE); dat2 dat3 <- data.table::fread('UTF-8test.txt', sep = ',', header = FALSE, encoding = 'UTF-8'); dat3 dat1 <- read.table('UTF-8test.txt', sep = ',', fileEncoding = 'UTF-8', stringsAsFactors = FALSE) dat1 ## ubuntu에서는 문제 없음 dat2 <- readr::read_delim('UTF-8test.txt', delim = ',', col_names = FALSE) dat2 dat3 <- data.table::fread('UTF-8test.txt', sep = ',', header = FALSE, encoding = 'UTF-8'); dat3 dat1$V1 # ubuntu에서는 정상 작동 dat3$V1 dat3df <- as.data.frame(dat3); dat3tb <- tibble::as_tibble(dat3) print(dat3df) print(dat3df$V1) ## 8.4 EXCEL 화일 읽기 # install.packages("xlsx") # ubuntu> # sudo apt update -y # sudo apt install -y openjdk-8-jdk openjdk-8-jre # sudo R CMD javareconf # *** JAVA_HOME is not a valid path, ignoring # Java interpreter : /usr/bin/java # Java version : 1.8.0_252 # Java home path : /usr/lib/jvm/java-8-openjdk-amd64/jre # Java compiler : /usr/bin/javac # Java headers gen.: /usr/bin/javah # Java archive tool: /usr/bin/jar # trying to compile and link a JNI program # detected JNI cpp flags : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux # detected JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm # gcc -std=gnu99 -I"/usr/share/R/include" -DNDEBUG -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include/linux -fpic -g -O2 -fdebug-prefix-map=/home/jranke/git/r-backports/stretch/r-base-3.6.3=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c conftest.c -o conftest.o # gcc -std=gnu99 -shared -L/usr/lib/R/lib -Wl,-z,relro -o conftest.so conftest.o -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server -ljvm -L/usr/lib/R/lib -lR # # # JAVA_HOME : /usr/lib/jvm/java-8-openjdk-amd64/jre # Java library path: $(JAVA_HOME)/lib/amd64/server # JNI cpp flags : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux # JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm # Updating Java configuration in /usr/lib/R # Done. #install.packages("rJava") #java libs : '-L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm' #checking whether Java run-time works... ./configure: line 3796: /usr/lib/jvm/default-java/jre/bin/java: No such file or directory #no #configure: error: Java interpreter '/usr/lib/jvm/default-java/jre/bin/java' does not work #ERROR: configuration failed for package ‘rJava’ #* removing ‘/home/master/R/x86_64-pc-linux-gnu-library/3.6/rJava’ #Warning in install.packages : # installation of package ‘rJava’ had non-zero exit status # require(rJava) # ubuntu와 windows에서 java 설치 방법??? #Loading required package: rJava #Error: package or namespace load failed for ‘rJava’: # .onLoad failed in loadNamespace() for 'rJava', details: # call: dyn.load(file, DLLpath = DLLpath, ...) #error: unable to load shared object '/home/master/R/x86_64-pc-linux-gnu-library/3.6/rJava/libs/rJava.so': # libjvm.so: cannot open shared object file: No such file or directory # rJava 설치 on ubuntu # https://wikidocs.net/52630 #install.packages('xlsx') ## 8.4 EXCEL 화일 읽기 # readxl::excel_sheets(path= ) # readxl::read_excel(path= , sheet= ) library(readxl) readxl::read_excel('서울시 한강공원 이용객 현황 (2009_2013년).xls', sheet=1) #Error(Ubuntu): # filepath: 서울시 한강공원 이용객 현황 (2009_2013년).xls # libxls error: Unable to open file readxl::read_xlsx('서울시 한강공원 이용객 현황 (2009_2013년).xls', sheet=1) # 8.4.1 library(readxl) rm(list=ls()) fn = "excel_example.xls" vSh <- excel_sheets(fn) #li <- vector(mode="list", length=length(vSh)-1) if ( length(vSh) > 0 ) { for (iSh in 1:(length(vSh))) { vname <- vSh[iSh] if (exists(vname)) { cat('\b\b변수 ', vname, '이(가) 이미 존재합니다.\n') break } assign(vname, read_excel(fn, sheet=vSh[iSh])) } } else { cat('No Sheet!!!\n') } vSh ls() # 8.5 install.packages('foreign') install.packages('haven') # 기본값이 없는 인수에 대한 오류 library(foreign) #read.spss() # SPSS #read.dta() # Stata #read.ssd() # SAS #read.octave() # Octave #read.mtp() # Minitab #read.systat() # Systat library(haven) #read_dta() # Stata #read_por() # SPSS .por #read_sas() # SAS #read_sav() # SPSS .sav, .zsav #read_stata() # Stata #read_xpt() # SAS transport files url = 'http://www.nber.org/data/population-birthplace-diversity/JoEG_BP_diversity_data.dta' # 8.5.1 # 8.5.2 #install.packages('htmltab') library(htmltab) url <- "https://en.wikipedia.org/wiki/List_of_most_common_surnames_in_Europe" surnames <- htmltab(doc = url, which = 13) head(surnames, n=10) #install.packages('XML') #install.packages("RCurl") #install.packages("rlist") library(XML) library(RCurl) library(rlist) url <- "https://en.wikipedia.org/wiki/List_of_most_common_surnames_in_Europe" theurl <- getURL(url, .opts = list(ssl.verifypeer = FALSE) ) # Windows에서 다음과 같은 에러가 발생(ubuntu는 정상작동) # error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version # RCurl은 더 이상 관리되지 않는다고 함. #https://stackoverflow.com/questions/31504983/rcurl-geturl-ssl-error library(curl) con <- curl(url) html <- readLines(con) df <- readHTMLTable(html, header = TRUE, which = 13, stringsAsFactors = FALSE, encoding = "UTF-8") head(df, n=10)
# Plot Of Twitter User Hashtag Count # Original source: http://decisionsandr.blogspot.com/2013/11/using-r-to-find-obamas-most-frequent.html & https://github.com/chrisalbon/code_r/blob/master/twitter.r # Note: This r code will have to be run in two parts since you will have to get a code from the Twitter website and enter it into R manually. # Load twitteR package library(twitteR) # create object of request token URL reqURL <- "https://api.twitter.com/oauth/request_token" # create object of access URL accessURL <- "http://api.twitter.com/oauth/access_token" # create object of authorization URL authURL <- "http://api.twitter.com/oauth/authorize" # create objects with keys (get these from dev.twitter.com) consumerKey <- "XXXXX" consumerSecret <- "XXXXX" # add them to twitcred twitCred <- OAuthFactory$new(consumerKey=consumerKey,consumerSecret=consumerSecret,requestURL=reqURL,accessURL=accessURL,authURL=authURL) # Prepare for the hangshake download.file(url="http://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem") # conduct the handshake, then enter in the number code twitCred$handshake(cainfo="cacert.pem") # ------------- # Enter number from browser into R # ------------- # test to make sure it works registerTwitterOAuth(twitCred) # create object of 3200 tweets in ChrisAlbon's timeline tw <- userTimeline("ChrisAlbon", n = 3200) # create a object that is a data frame of tw tw <- twListToDF(tw) # create an object of the tweet texts vec1 <- tw$text # create an object that extract the hashtags extract.hashes <- function(vec){ hash.pattern = "#[[:alpha:]]+" have.hash = grep(x = vec, pattern = hash.pattern) hash.matches = gregexpr(pattern = hash.pattern, text = vec[have.hash]) extracted.hash = regmatches(x = vec[have.hash], m = hash.matches) df = data.frame(table(tolower(unlist(extracted.hash)))) colnames(df) = c("tag","freq") df = df[order(df$freq,decreasing = TRUE),] return(df) } # create object of 50 of vec1's hashtags dat = head(extract.hashes(vec1),50) # create object the hashtags ordered by frequency dat2 = transform(dat,tag = reorder(tag,freq)) # load the ggplot2 package library(ggplot2) # plot the hashtags by frequency p = ggplot(dat2, aes(x = tag, y = freq)) + geom_bar(fill = "blue") # redo it a bit and add a title p + coord_flip() + labs(title = "Hashtag frequencies in the tweets of ChrisAlbon)
/R/api/twitter.R
no_license
mitchelllisle/code_snippets
R
false
false
2,375
r
# Plot Of Twitter User Hashtag Count # Original source: http://decisionsandr.blogspot.com/2013/11/using-r-to-find-obamas-most-frequent.html & https://github.com/chrisalbon/code_r/blob/master/twitter.r # Note: This r code will have to be run in two parts since you will have to get a code from the Twitter website and enter it into R manually. # Load twitteR package library(twitteR) # create object of request token URL reqURL <- "https://api.twitter.com/oauth/request_token" # create object of access URL accessURL <- "http://api.twitter.com/oauth/access_token" # create object of authorization URL authURL <- "http://api.twitter.com/oauth/authorize" # create objects with keys (get these from dev.twitter.com) consumerKey <- "XXXXX" consumerSecret <- "XXXXX" # add them to twitcred twitCred <- OAuthFactory$new(consumerKey=consumerKey,consumerSecret=consumerSecret,requestURL=reqURL,accessURL=accessURL,authURL=authURL) # Prepare for the hangshake download.file(url="http://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem") # conduct the handshake, then enter in the number code twitCred$handshake(cainfo="cacert.pem") # ------------- # Enter number from browser into R # ------------- # test to make sure it works registerTwitterOAuth(twitCred) # create object of 3200 tweets in ChrisAlbon's timeline tw <- userTimeline("ChrisAlbon", n = 3200) # create a object that is a data frame of tw tw <- twListToDF(tw) # create an object of the tweet texts vec1 <- tw$text # create an object that extract the hashtags extract.hashes <- function(vec){ hash.pattern = "#[[:alpha:]]+" have.hash = grep(x = vec, pattern = hash.pattern) hash.matches = gregexpr(pattern = hash.pattern, text = vec[have.hash]) extracted.hash = regmatches(x = vec[have.hash], m = hash.matches) df = data.frame(table(tolower(unlist(extracted.hash)))) colnames(df) = c("tag","freq") df = df[order(df$freq,decreasing = TRUE),] return(df) } # create object of 50 of vec1's hashtags dat = head(extract.hashes(vec1),50) # create object the hashtags ordered by frequency dat2 = transform(dat,tag = reorder(tag,freq)) # load the ggplot2 package library(ggplot2) # plot the hashtags by frequency p = ggplot(dat2, aes(x = tag, y = freq)) + geom_bar(fill = "blue") # redo it a bit and add a title p + coord_flip() + labs(title = "Hashtag frequencies in the tweets of ChrisAlbon)
# install packages # install.packages("dplyr") # install.packages('hflights') # Load Library library(dplyr) library(hflights) dim(hflights) hflights_df <- tbl_df(hflights) # filter 함수 # 조건에 따라(Month가 1 또는 2) 데이터 행 추출 (subset()함수와 비슷) filter(hflights_df, Month == 1 | Month == 2) filter(hflights_df, Month == 1 , DayofMonth == 1) # arrange 함수 # 지정한 열 기준으로 작은값 부터 큰 값 순으로 데이터 정렬 (역순을 원할 땐, desc() 함께 사용) arrange(hflights_df, ArrDelay, Month, Year) # ArrDelay, Month, Year 순으로 정렬) arrange(hflights_df, desc(Month)) # Month의 큰 값부터 작은 값으로 정렬 # select 함수 # 열을 추출할 때 사용, 복수 열을 추출할 때에는 콤마(,)로 구분하고, 인접한 열은 (:) 연산자로 이용하여 추출 select(hflights_df, Year, Month, DayofMonth) select(hflights_df, -(Year:DayOfWeek)) # Year부터 DayOfWeek를 제외한 나머지 열 추출 # mutate 함수 # 열을 추가할 때 사용(transform() 함수와 비슷) mutate(hflights_df, gain = ArrDelay - DepDelay, gain_per_hour = gain/(AirTime/60)) # mutate 함수에서 생성한 열인 gain을 바로 다음 gain_per_hour에서 바로 사용할 수 있음 # transform 함수에서는 위와 같은 동시활동(계산)을 사용할 수 없음) # summarise 함수 # mean(), sd(), var(), median() 등의 함수를 지정하여 기초 통계량을 구할 수 있음, 결과값은 data.frame형식으로 출력 summarise(hflights_df, delay = mean(DepDelay, na.rm = TRUE)) summarise(hflights_df, plane = n_distinct(TailNum)) # n_distinct 함수는 열(변수)의 유니크 값의 수를 산출 hflights_df %>% group_by(FlightNum, Dest) %>% summarise(n = n()) # n()은 관측값의 갯수를 구해줌(group_by와 함꼐 쓰일 떄 유용함) summarise(hflights_df, first = first(DepTime)) # first() 함수는 해당 열(변수)의 첫번째 값을 산출 summarise(hflights_df, last = last(DepTime)) # last() 함수는 해당 열(변수)의 마지막 행 값을 산출 summarise(hflights_df, data = nth(DepTime, 10)) # nth(x, n) 함수는 원하는 행의 해당 열(변수 : x)의 값을 산출 # group_by 함수 # 지정한 열의 수준(Level)별로 그룹화된 결과를 얻을 수 있음 #아래 코드는 비행편수 20편 이상, 평군 비행거리 2,000마일 이상인 항공사별 평균 연착시간을 계산하여 그림으로 표현 planes <- group_by(hflights_df, TailNum) delay <- summarise(planes, count = n(), dist = mean(Distance, na.rm = TeRUE), delay = mean(ArrDelay, na.rm = TRUE)) delay <- filter(delay, count > 20, dist < 2000) library(ggplot2) ggplot(delay, aes(dist, delay))+geom_point(aes(size = count), alpha = 1/2)+geom_smooth()+scale_size_area() #group_by의 많은 예제는 vignette("introduction", package = 'dplyr') # package 간단히 공부할때는 도움이 많이 될 듯 !! (vignette : 삽화) # chain 함수 : 코드를 줄일 수 있는 획기적인 방법 또한 코드도 직관적으로 이해할 수 있음 # (1) # hflight 데이터를 a1) Year, Month, DayofMonth의 수준별로 그룹화, a2) Year부터 DayofMonth, ArrDelay, DepDelay열을 선택, # a3) 평균 연착시간과 평균 출발 지연시간을 구하고, a4) 평균 연착시간과 평균 출발지연시간이 30분 이상인 데이터를 추출한 # 결과 a1 <- group_by(hflights_df, Year, Month, DayofMonth) a2 <- select(a1, Year:DayofMonth, ArrDelay, DepDelay) a3 <- summarise(a2, arr = mean(ArrDelay, na.rm = TRUE), dep = mean(DepDelay, na.rm = TRUE)) a4 <- filter(a3, arr > 30 | dep > 30) # (2) #위 예제를 " %>% " 를 이용하면 코드가 아래와 같이 단순해짐 hflights_df %>% group_by(Year, Month, DayofMonth) %>% summarise(arr = mean(ArrDelay, na.rm = TRUE), dep = mean(DepDelay, na.rm = TRUE)) %>% filter(arr > 30 | dep > 30) # (3) # 위 예제 3번째 표현식 : 데이터 input 자리에 함수를 이용해 데이터를 자동 입력 filter( summarise( select( group_by(hflights_df, Year, Month, DayofMonth), Year:DayofMonth, ArrDelay, DepDelay ), arr = mean(ArrDelay, na.rm = TRUE), dep = mean(DepDelay, na.rm = TRUE) ), arr > 30 | dep > 30 ) # distinct 함수 #데이터의 유니크한 변수들을 찾아줌 (unique() 함수와 유사함) distinct(hflights_df, Year, DepDelay) # sample_n / sample_frac 함수 sample_n(hflights_df, 10) # 10개의 행을 랜덤해서 추출 sample_frac(hflights_df, 0.01) # 전체 행에서 0.01 (1%) 비율로 데이터(행)를 추출 # 예제 (* 주의 *) # 이 예제의 각 결과들을 보면 처음에 3개의 변수(Year, Month, DayofMonth)를 기준으로 group설정 후, summarise 함수는 # 하나의 수준씩 그룹에서 제외시켜 결과를 산출 # per_month는 DayofMonth의 변수가 제외되어 결과가 산출 # per_year는 Month 변수가 벗겨져(peel off) 결과를 산출 daily <- group_by(hflights_df, Year, Month, DayofMonth) per_day <- summarise(daily, flights = n()) per_month <- summarise(per_day, flights = sum(flights)) per_year <- summarise(per_month, flights = sum(flights))
/dplyr-exercise.R
no_license
sys505moon/R_Study
R
false
false
5,162
r
# install packages # install.packages("dplyr") # install.packages('hflights') # Load Library library(dplyr) library(hflights) dim(hflights) hflights_df <- tbl_df(hflights) # filter 함수 # 조건에 따라(Month가 1 또는 2) 데이터 행 추출 (subset()함수와 비슷) filter(hflights_df, Month == 1 | Month == 2) filter(hflights_df, Month == 1 , DayofMonth == 1) # arrange 함수 # 지정한 열 기준으로 작은값 부터 큰 값 순으로 데이터 정렬 (역순을 원할 땐, desc() 함께 사용) arrange(hflights_df, ArrDelay, Month, Year) # ArrDelay, Month, Year 순으로 정렬) arrange(hflights_df, desc(Month)) # Month의 큰 값부터 작은 값으로 정렬 # select 함수 # 열을 추출할 때 사용, 복수 열을 추출할 때에는 콤마(,)로 구분하고, 인접한 열은 (:) 연산자로 이용하여 추출 select(hflights_df, Year, Month, DayofMonth) select(hflights_df, -(Year:DayOfWeek)) # Year부터 DayOfWeek를 제외한 나머지 열 추출 # mutate 함수 # 열을 추가할 때 사용(transform() 함수와 비슷) mutate(hflights_df, gain = ArrDelay - DepDelay, gain_per_hour = gain/(AirTime/60)) # mutate 함수에서 생성한 열인 gain을 바로 다음 gain_per_hour에서 바로 사용할 수 있음 # transform 함수에서는 위와 같은 동시활동(계산)을 사용할 수 없음) # summarise 함수 # mean(), sd(), var(), median() 등의 함수를 지정하여 기초 통계량을 구할 수 있음, 결과값은 data.frame형식으로 출력 summarise(hflights_df, delay = mean(DepDelay, na.rm = TRUE)) summarise(hflights_df, plane = n_distinct(TailNum)) # n_distinct 함수는 열(변수)의 유니크 값의 수를 산출 hflights_df %>% group_by(FlightNum, Dest) %>% summarise(n = n()) # n()은 관측값의 갯수를 구해줌(group_by와 함꼐 쓰일 떄 유용함) summarise(hflights_df, first = first(DepTime)) # first() 함수는 해당 열(변수)의 첫번째 값을 산출 summarise(hflights_df, last = last(DepTime)) # last() 함수는 해당 열(변수)의 마지막 행 값을 산출 summarise(hflights_df, data = nth(DepTime, 10)) # nth(x, n) 함수는 원하는 행의 해당 열(변수 : x)의 값을 산출 # group_by 함수 # 지정한 열의 수준(Level)별로 그룹화된 결과를 얻을 수 있음 #아래 코드는 비행편수 20편 이상, 평군 비행거리 2,000마일 이상인 항공사별 평균 연착시간을 계산하여 그림으로 표현 planes <- group_by(hflights_df, TailNum) delay <- summarise(planes, count = n(), dist = mean(Distance, na.rm = TeRUE), delay = mean(ArrDelay, na.rm = TRUE)) delay <- filter(delay, count > 20, dist < 2000) library(ggplot2) ggplot(delay, aes(dist, delay))+geom_point(aes(size = count), alpha = 1/2)+geom_smooth()+scale_size_area() #group_by의 많은 예제는 vignette("introduction", package = 'dplyr') # package 간단히 공부할때는 도움이 많이 될 듯 !! (vignette : 삽화) # chain 함수 : 코드를 줄일 수 있는 획기적인 방법 또한 코드도 직관적으로 이해할 수 있음 # (1) # hflight 데이터를 a1) Year, Month, DayofMonth의 수준별로 그룹화, a2) Year부터 DayofMonth, ArrDelay, DepDelay열을 선택, # a3) 평균 연착시간과 평균 출발 지연시간을 구하고, a4) 평균 연착시간과 평균 출발지연시간이 30분 이상인 데이터를 추출한 # 결과 a1 <- group_by(hflights_df, Year, Month, DayofMonth) a2 <- select(a1, Year:DayofMonth, ArrDelay, DepDelay) a3 <- summarise(a2, arr = mean(ArrDelay, na.rm = TRUE), dep = mean(DepDelay, na.rm = TRUE)) a4 <- filter(a3, arr > 30 | dep > 30) # (2) #위 예제를 " %>% " 를 이용하면 코드가 아래와 같이 단순해짐 hflights_df %>% group_by(Year, Month, DayofMonth) %>% summarise(arr = mean(ArrDelay, na.rm = TRUE), dep = mean(DepDelay, na.rm = TRUE)) %>% filter(arr > 30 | dep > 30) # (3) # 위 예제 3번째 표현식 : 데이터 input 자리에 함수를 이용해 데이터를 자동 입력 filter( summarise( select( group_by(hflights_df, Year, Month, DayofMonth), Year:DayofMonth, ArrDelay, DepDelay ), arr = mean(ArrDelay, na.rm = TRUE), dep = mean(DepDelay, na.rm = TRUE) ), arr > 30 | dep > 30 ) # distinct 함수 #데이터의 유니크한 변수들을 찾아줌 (unique() 함수와 유사함) distinct(hflights_df, Year, DepDelay) # sample_n / sample_frac 함수 sample_n(hflights_df, 10) # 10개의 행을 랜덤해서 추출 sample_frac(hflights_df, 0.01) # 전체 행에서 0.01 (1%) 비율로 데이터(행)를 추출 # 예제 (* 주의 *) # 이 예제의 각 결과들을 보면 처음에 3개의 변수(Year, Month, DayofMonth)를 기준으로 group설정 후, summarise 함수는 # 하나의 수준씩 그룹에서 제외시켜 결과를 산출 # per_month는 DayofMonth의 변수가 제외되어 결과가 산출 # per_year는 Month 변수가 벗겨져(peel off) 결과를 산출 daily <- group_by(hflights_df, Year, Month, DayofMonth) per_day <- summarise(daily, flights = n()) per_month <- summarise(per_day, flights = sum(flights)) per_year <- summarise(per_month, flights = sum(flights))
# Analyze bird counts # All rights reserved Read data file into dataframe Run analysis using p-val 0.5 Save table with bold black header Save small figure, thick blue line Save references 1 through 12 WOW I'VE MADE SUCH CHANGES same here!
/script.R
no_license
brad2x/birdsurvey
R
false
false
247
r
# Analyze bird counts # All rights reserved Read data file into dataframe Run analysis using p-val 0.5 Save table with bold black header Save small figure, thick blue line Save references 1 through 12 WOW I'VE MADE SUCH CHANGES same here!
library(hddtools) ### Name: getContent ### Title: Extracts links from ftp page ### Aliases: getContent ### ** Examples ## Not run: ##D # Retrieve mopex daily catalogue ##D url <- "ftp://hydrology.nws.noaa.gov/pub/gcip/mopex/US_Data/Us_438_Daily/" ##D getContent(dirs = url) ## End(Not run)
/data/genthat_extracted_code/hddtools/examples/getContent.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
305
r
library(hddtools) ### Name: getContent ### Title: Extracts links from ftp page ### Aliases: getContent ### ** Examples ## Not run: ##D # Retrieve mopex daily catalogue ##D url <- "ftp://hydrology.nws.noaa.gov/pub/gcip/mopex/US_Data/Us_438_Daily/" ##D getContent(dirs = url) ## End(Not run)
## The function makecache creats a special "matrix". makeCache <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y i <<- NULL } get <- function() x setinverse <- function(inverse) i <<- inverse getinverse <- function() i list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } #The function "cacheSolve" computes the inverse of the special “matrix” returned by makeCacheMatrix above. #If the inverse has already been calculated (and the matrix has not changed), then cacheSolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { i <- x$getinverse() if (!is.null(i)) { message("getting cached data") return(i) } data <- x$get() i <- solve(data, ...) x$setinverse(i) i } #testing a<-matrix(c(1,2,3,4),3,3) b<-makeCache(a) cacheSolve(b)
/asm2.R
no_license
tracyli6/cocowalnut
R
false
false
1,022
r
## The function makecache creats a special "matrix". makeCache <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y i <<- NULL } get <- function() x setinverse <- function(inverse) i <<- inverse getinverse <- function() i list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } #The function "cacheSolve" computes the inverse of the special “matrix” returned by makeCacheMatrix above. #If the inverse has already been calculated (and the matrix has not changed), then cacheSolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { i <- x$getinverse() if (!is.null(i)) { message("getting cached data") return(i) } data <- x$get() i <- solve(data, ...) x$setinverse(i) i } #testing a<-matrix(c(1,2,3,4),3,3) b<-makeCache(a) cacheSolve(b)
#reading and transforming the data df1= read.csv(file="QueryResults1.csv",header=TRUE) df2<- read.csv(file="QueryResults2.csv",header=TRUE) StackOverflow<- rbind(df1,df2) #str(StackOverflow) #names(StackOverflow) nrow(StackOverflow) #replacing NA with 1001 StackOverflow [is.na(StackOverflow)] <- 1001 #removing column that contain text or are unrelated to this question StackOverflowdata<- StackOverflow[,-c(1, 2,3,12,14,15,22,23,25,26,27,28,29,30,31,32,33,34)] #str(StackOverflowdata) nrow(StackOverflowdata) #to check uniqueness of data lapply(StackOverflowdata["RejectionReasonId"], unique) StackOverflowdata$IsSpam= ifelse(StackOverflowdata$RejectionReasonId==101,1,0) #str(StackOverflowdata) #names(StackOverflowdata) StackOverflowdata<- StackOverflowdata[,-c(16)] lapply(StackOverflowdata["IsSpam"], unique) #dividing data for training and testing purpose smp_size<- floor(0.75*nrow(StackOverflowdata)) set.seed(123) train_ind<- sample(seq_len(nrow(StackOverflowdata)), size=smp_size) training_data<- StackOverflowdata[train_ind,] testing_data<- StackOverflowdata[-train_ind,] testing_y<- testing_data$IsSpam nrow(training_data) nrow(testing_data) #str(training_data) #names(training_data) #GLM logistics_model<-glm(IsSpam~.,data=training_data,family="binomial") #to discover better model #step(logistics_model, direction = "forward") logistics_model = glm(IsSpam ~ PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_views + owner_upvotes + owner_downvotes + editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount + has_code +post_views + UserId, family = "binomial", data = training_data) summary(logistics_model) #performing trial modelling #step(logistics_model, direction = "backward") #final regression model logistics_model = glm(formula = IsSpam ~ PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views, family = "binomial", data = training_data) summary(logistics_model) #Bayesian information criterion BIC(logistics_model) logistics_probs<-predict(logistics_model,training_data,type="response") head(logistics_probs) logistics_pred_y=rep(0,length(testing_y)) logistics_pred_y[logistics_probs>0.55]=1 training_y=training_data$IsSpam table(logistics_pred_y,training_y) mean(logistics_pred_y!=training_y,na.rm=TRUE) logistics_probs<- predict(logistics_model,testing_data, type="response") head(logistics_probs) logistics_pred_y=rep(0,length(testing_y)) logistics_pred_y[logistics_probs>0.55]=1 table(logistics_pred_y,testing_y) mean(logistics_pred_y!=testing_y,na.rm=TRUE) #kfold for regression library(boot) MSE_10_Fold_CV=cv.glm(training_data,logistics_model,K=10)$delta[1] MSE_10_Fold_CV MSE_10_Fold_CV=NULL for(i in 1:10){ model=glm(IsSpam~poly(PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views),data=training_data) MSE_10_Fold_CV[i]=cv.glm(training_data,model,K=10)$delta[1] } #summary(model) MSE_10_Fold_CV #ROC logistic regression #install.packagesll.packages("ROCR") library(ROCR) ROCRpred=prediction(logistics_probs,testing_y) ROCRperf=performance(ROCRpred,"tpr","fpr") #plot(ROCRperf) #plot(ROCRperf,colorize=TRUE) #plot(ROCRperf,colorize=TRUE,print.cutoffs.at=seq(0,1,0.05),text.adj=c(-0.2,1.7)) as.numeric(performance(ROCRpred,"auc")@y.values) #Linear Discriminant Analysis library(MASS) lda.model<- lda(IsSpam~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,data=training_data) #lda.model #summary(lda.model) lda_pred<- predict(lda.model,training_data) lda_class<- lda_pred$class table(lda_class,training_data$IsSpam) mean(lda_class!=training_data$IsSpam) lda_pred<- predict(lda.model,testing_data) lda_class<- lda_pred$class table(lda_class,testing_data$IsSpam) mean(lda_class!=testing_data$IsSpam) #Cross Validation LDA library(rpart) library(ipred) ip.lda <- function(object, newdata) predict(object, newdata = newdata)$class errorest(factor(training_data$IsSpam)~ training_data$PostTypeId + training_data$PostScore + training_data$post_length + training_data$owner_reputation + training_data$owner_profile_summary + training_data$owner_upvotes+ training_data$editDurationAfterCreation + training_data$q_num_tags + training_data$AnswerCount + training_data$CommentCount+ training_data$post_views, data=training_data, model=lda, estimator="cv",est.para=control.errorest(k=10), predict=ip.lda)$err #ROC LDA S=lda_pred$posterior[,2] roc.curve=function(s,print=FALSE){ Ps=(S>s)*1 FP=sum((Ps==1)*(testing_data$IsSpam==0))/sum(testing_data$IsSpam==0) TP=sum((Ps==1)*(testing_data$IsSpam==1))/sum(testing_data$IsSpam==1) if(print==TRUE){ print(table(Observed=testing_data$IsSpam,Predicted=Ps)) } vect=c(FP,TP) names(vect)=c("FPR","TPR") return(vect) } threshold=0.53 roc.curve(threshold,print=TRUE) ROC.curve=Vectorize(roc.curve) M.ROC=ROC.curve(seq(0,1,by=.01)) plot(M.ROC[1,],M.ROC[2,],col="blue",lwd=2,type="l",main="ROC for LDA") abline(0,1) #Quadratic Discriminant Analysis qda.model<- qda(IsSpam~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,data=training_data) #qda.model qda_pred=predict(qda.model,training_data) qda_class=qda_pred$class table(qda_class,training_data$IsSpam) mean(qda_class!=training_data$IsSpam) qda_pred1=predict(qda.model,testing_data) qda_class_n=qda_pred1$class table(qda_class_n,testing_data$IsSpam) mean(qda_class_n!=testing_data$IsSpam) #Cross Validation QDA ip.qda <- function(object, newdata) predict(object, newdata = newdata)$class errorest(factor(training_data$IsSpam)~ training_data$PostTypeId + training_data$PostScore + training_data$post_length + training_data$owner_reputation + training_data$owner_profile_summary + training_data$owner_upvotes+ training_data$editDurationAfterCreation + training_data$q_num_tags + training_data$AnswerCount + training_data$CommentCount+ training_data$post_views, data=training_data, model=qda, estimator="cv",est.para=control.errorest(k=10), predict=ip.qda)$err #ROC QDA qda.S=qda_pred1$posterior[,2] roc.curve=function(s,print=FALSE){ Ps=(qda.S>s)*1 FP=sum((Ps==1)*(testing_data$IsSpam==0))/sum(testing_data$IsSpam==0) TP=sum((Ps==1)*(testing_data$IsSpam==1))/sum(testing_data$IsSpam==1) if(print==TRUE){ print(table(Observed=testing_data$IsSpam,Predicted=Ps)) } vect=c(FP,TP) names(vect)=c("FPR","TPR") return(vect) } threshold=0.85 roc.curve(threshold,print=TRUE) ROC.curve=Vectorize(roc.curve) M.ROC=ROC.curve(seq(0,1,by=.01)) plot(M.ROC[1,],M.ROC[2,],col="blue",lwd=2,type="l",main="ROC for LDA") abline(0,1) #k nearest neighbours library(class) #install.packagesll.packages("cars") #library(cars) train.x<- cbind(training_data$PostTypeId + training_data$PostScore + training_data$post_length + training_data$owner_reputation + training_data$owner_profile_summary + training_data$owner_upvotes + training_data$editDurationAfterCreation + training_data$q_num_tags + training_data$AnswerCount + training_data$CommentCount + training_data$post_views) test.x<- cbind(testing_data$PostTypeId + testing_data$PostScore + testing_data$post_length + testing_data$owner_reputation + testing_data$owner_profile_summary + testing_data$owner_upvotes + testing_data$editDurationAfterCreation + testing_data$q_num_tags + testing_data$AnswerCount + testing_data$CommentCount + testing_data$post_views) train1.x=train.x[!duplicated(train.x),drop=FALSE] test1.x=test.x[!duplicated(test.x), drop=FALSE] tt<- training_data$IsSpam[duplicated(train.x)=='FALSE'] head(tt) length(tt) knn.pred<- knn(data.frame(train1.x),data.frame(test1.x),tt,k=1) tt1<- testing_data$IsSpam[duplicated(test.x)=='FALSE'] length(tt1) table(knn.pred,tt1) mean(knn.pred!=tt1) knn.pred<- knn(data.frame(train1.x),data.frame(test1.x),tt,k=2) table(knn.pred,tt1) mean(knn.pred!=tt1) #Classification and Regression Trees #CART Modeling: #install.packagesll.packages("tree") library(tree) tree.training_data=tree(as.factor(IsSpam)~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,training_data) text(tree.training_data,pretty=0) summary(tree.training_data) plot(tree.training_data) text(tree.training_data,pretty=0) lf<- seq(1,nrow(training_data)) tree.training_data=tree(as.factor(IsSpam)~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,training_data,subset=lf) tree.pred=predict(tree.training_data,testing_data,type="class") table(tree.pred,testing_y) mean(tree.pred!=testing_data$IsSpam) #Cross Validation and Pruning for the Classification Tree: cv.training_data=cv.tree(tree.training_data,FUN=prune.misclass) names(cv.training_data) #cv.training_data par(mfrow=c(1,2)) plot(cv.training_data$size,cv.training_data$dev,type="b") plot(cv.training_data$k,cv.training_data$dev,type="b") par(mfrow=c(1,1)) prune.training_data=prune.misclass(tree.training_data,best=5) plot(prune.training_data) text(prune.training_data,pretty=0) tree.pred=predict(prune.training_data,testing_data,type="class") table(tree.pred,testing_y) mean(tree.pred!=testing_data$IsSpam) #ROC for CART: tree.pred=predict(tree.training_data,testing_data,type="vector",prob=TRUE) #tree.pred tree.S=tree.pred[,2] roc.curve=function(s,print=FALSE){ Ps=(tree.S>s)*1 FP=sum((Ps==1)*(testing_data$IsSpam==0))/sum(testing_data$IsSpam==0) TP=sum((Ps==1)*(testing_data$IsSpam==1))/sum(testing_data$IsSpam==1) if(print==TRUE){ print(table(Observed=testing_data$IsSpam,Predicted=Ps)) } vect=c(FP,TP) names(vect)=c("FPR","TPR") return(vect) } threshold=0.55 roc.curve(threshold,print=TRUE) ROC.curve=Vectorize(roc.curve) M.ROC=ROC.curve(seq(0,1,by=.01)) plot(M.ROC[1,],M.ROC[2,],col="blue",lwd=2,type="l",main="ROC for CART") abline(0,1) #Random Forest Modeling: #install.packagesll.packages("randomForest") library(randomForest) bag.training_data=randomForest(as.factor(IsSpam)~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,data=training_data,subset=lf,importance=TRUE) #bag.training_data xyz = predict(bag.training_data, newdata = testing_data) table(testing_y, xyz) mean(xyz!=testing_y) #C5.0 #install.packagesll.packages("C50") library(C50) c50_model <- C5.0(training_data[-16], as.factor(training_data$IsSpam)) c50_model #summary(c50_model) #testing C50 c50_pred <- predict(c50_model, testing_data) #install.packagesll.packages("gmodels") library(gmodels) CrossTable(testing_data$IsSpam, c50_pred, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c('actual default', 'predicted default')) #improving C50 with adaptive boosting c50_boost10 <- C5.0(training_data[-16], as.factor(training_data$IsSpam), trials = 10) c50_boost10 c50_pred10 <- predict(c50_boost10, testing_data) CrossTable(testing_data$IsSpam, c50_pred10, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c('actual default', 'predicted default')) #Dimensional Reduction #install.packages("ISLR") library(ISLR) #fix(StackOverflowdata) #names(StackOverflowdata) dim(StackOverflowdata) sum(is.na(StackOverflowdata$IsSpam)) StackOverflowdata=na.omit(StackOverflowdata) dim(StackOverflowdata) sum(is.na(StackOverflowdata)) #install.packages("pls") library(pls) set.seed(2) pcr.fit=pcr(IsSpam~., data=StackOverflowdata,scale=TRUE,validation="CV") summary(pcr.fit) validationplot(pcr.fit,val.type="MSEP") set.seed(1) pcr.fit=pcr(IsSpam~., data=training_data,scale=TRUE, validation="CV") validationplot(pcr.fit,val.type="MSEP") pcr.pred=predict(pcr.fit,testing_data,ncomp=7) mean((pcr.pred-testing_y)^2) pcr.fit=pcr(IsSpam~.,data=testing_data, scale=TRUE,ncomp=7) mean((pcr.pred-testing_y)^2) summary(pcr.fit) # Partial Least Squares set.seed(1) pls.fit=plsr(IsSpam~., data=StackOverflowdata,scale=TRUE, validation="CV") summary(pls.fit) validationplot(pls.fit,val.type="MSEP") pls.pred=predict(pls.fit,testing_data,ncomp=2) mean((pls.pred-testing_y)^2) pls.fit=plsr(IsSpam~., data=StackOverflowdata,scale=TRUE,ncomp=2) summary(pls.fit) # Subset Selection Methods # Best Subset Selection #install.packages("ISLR") library(ISLR) #sum(is.na(StackOverflow$IsSpam)) lapply(StackOverflowdata["IsSpam"], unique) #Confirms NO NA data #install.packages("leaps") library(leaps) regfit.full=regsubsets(IsSpam~.,StackOverflowdata) summary(regfit.full) regfit.full=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19) reg.summary=summary(regfit.full) names(reg.summary) reg.summary$rsq par(mfrow=c(2,2)) plot(reg.summary$rss,xlab="Number of Variables",ylab="RSS",type="l") plot(reg.summary$adjr2,xlab="Number of Variables",ylab="Adjusted RSq",type="l") which.max(reg.summary$adjr2) points(11,reg.summary$adjr2[11], col="red",cex=2,pch=20) plot(reg.summary$cp,xlab="Number of Variables",ylab="Cp",type='l') which.min(reg.summary$cp) points(10,reg.summary$cp[10],col="red",cex=2,pch=20) which.min(reg.summary$bic) plot(reg.summary$bic,xlab="Number of Variables",ylab="BIC",type='l') points(6,reg.summary$bic[6],col="red",cex=2,pch=20) coef(regfit.full,6) # Forward and Backward Stepwise Selection regfit.fwd=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19,method="forward") summary(regfit.fwd) regfit.bwd=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19,method="backward" ) summary(regfit.bwd) coef(regfit.full,7) coef(regfit.fwd,7) coef(regfit.bwd,7) # Choosing Among Models set.seed(1) train=sample(c(TRUE,FALSE), nrow(StackOverflowdata),rep=TRUE) test=(!train) regfit.best=regsubsets(IsSpam~.,data=StackOverflowdata[train,],nvmax=19) test.mat=model.matrix(IsSpam~.,data=StackOverflowdata[test,]) val.errors=rep(NA,19) for(i in 1:11){ coefi=coef(regfit.best,id=i) pred=test.mat[,names(coefi)]%*%coefi val.errors[i]=mean((StackOverflowdata$IsSpam[test]-pred)^2) } val.errors which.min(val.errors) coef(regfit.best,10) predict.regsubsets=function(object,newdata,id,...){ form=as.formula(object$call[[2]]) mat=model.matrix(form,newdata) coefi=coef(object,id=id) xvars=names(coefi) mat[,xvars]%*%coefi } regfit.best=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19) coef(regfit.best,10) k=10 set.seed(1) folds=sample(1:k,nrow(StackOverflowdata),replace=TRUE) cv.errors=matrix(NA,k,11, dimnames=list(NULL, paste(1:11))) for(j in 1:k){ best.fit=regsubsets(IsSpam~.,data=StackOverflowdata[folds!=j,],nvmax=11) for(i in 1:11){ pred=predict(best.fit,StackOverflowdata[folds==j,],id=i) cv.errors[j,i]=mean( (StackOverflowdata$IsSpam[folds==j]-pred)^2) } } mean.cv.errors=apply(cv.errors,2,mean) mean.cv.errors par(mfrow=c(1,1)) plot(mean.cv.errors,type='b') reg.best=regsubsets(IsSpam~.,data=StackOverflowdata, nvmax=11) coef(reg.best,11) # Ridge Regression and LASSO #install.packages("ISLR") library(ISLR) fix(Hitters) names(Hitters) dim(Hitters) sum(is.na(Hitters$Salary)) Hitters=na.omit(Hitters) dim(Hitters) sum(is.na(Hitters)) #install.packages("glmnet") library(glmnet) #the package invokes inputs and outputs separately unlike lm and glm x=model.matrix(Salary~.,Hitters)[,-1] y=Hitters$Salary # set vector of lambda values to study range from 10^10 to 0.01, total length=100 grid=10^seq(10,-2,length=100) ridge.mod=glmnet(x,y,alpha=0,lambda=grid) dim(coef(ridge.mod)) # let us look at a few results here #first lambda=50 ridge.mod$lambda[50] coef(ridge.mod)[,50] sqrt(sum(coef(ridge.mod)[-1,50]^2)) #next, lambda=60 ridge.mod$lambda[60] coef(ridge.mod)[,60] sqrt(sum(coef(ridge.mod)[-1,60]^2)) #prediction of the coefficients for lambda=50 (play with this) predict(ridge.mod,s=500,type="coefficients")[1:20,] #prepare for training and validation set testing set.seed(1) train=sample(1:nrow(x), nrow(x)/2) test=(-train) y.test=y[test] ridge.mod=glmnet(x[train,],y[train],alpha=0,lambda=grid, thresh=1e-12) ridge.pred=predict(ridge.mod,s=4,newx=x[test,]) #evaluate and compare test MSE and the spread of y.test mean((ridge.pred-y.test)^2) mean((mean(y[train])-y.test)^2) #test wth two other lambdas ridge.pred=predict(ridge.mod,s=1e10,newx=x[test,]) mean((ridge.pred-y.test)^2) ridge.pred=predict(ridge.mod,s=0,newx=x[test,],exact=T) mean((ridge.pred-y.test)^2) # compare with lm # The following two are the same lm(y~x, subset=train) predict(ridge.mod,s=0,exact=T,type="coefficients")[1:20,] #Cross validation to get the best lambda set.seed(1) cv.out=cv.glmnet(x[train,],y[train],alpha=0) plot(cv.out) bestlam=cv.out$lambda.min bestlam #now predict with the best lambda ridge.pred=predict(ridge.mod,s=bestlam,newx=x[test,]) mean((ridge.pred-y.test)^2) out=glmnet(x,y,alpha=0) predict(out,type="coefficients",s=bestlam)[1:20,] # Lasso #only difference in model building is to use aloha=1 lasso.mod=glmnet(x[train,],y[train],alpha=1,lambda=grid) plot(lasso.mod) # use CV to get best lambda set.seed(1) cv.out=cv.glmnet(x[train,],y[train],alpha=1) plot(cv.out) bestlam=cv.out$lambda.min #use best lambda for prediction lasso.pred=predict(lasso.mod,s=bestlam,newx=x[test,]) mean((lasso.pred-y.test)^2) out=glmnet(x,y,alpha=1,lambda=grid) lasso.coef=predict(out,type="coefficients",s=bestlam)[1:20,] lasso.coef lasso.coef[lasso.coef!=0] ``` # Support Vector Classifier set.seed(1) install.packages("e1071") librarIsSpam(e1071) svmfit=svm(IsSpam~., data=training_data, kernel="linear", cost=10,scale=FALSE) plot(svmfit, training_data) #which ones are support vectors svmfit$index summary(svmfit) svmfit=svm(IsSpam~., data=training_data, kernel="linear", cost=0.1,scale=FALSE) plot(svmfit, training_data) svmfit$index #cross validation set.seed(1) tune.out=tune(svm,IsSpam~.,data=training_data,kernel="linear",ranges=list(cost=c(0.001, 0.01, 0.1, 1,5,10,100))) summary(tune.out) bestmod=tune.out$best.model summary(bestmod) ypred=predict(bestmod,testing_data) table(predict=ypred, truth=testing_y) svmfit=svm(IsSpam~., data=training_data, kernel="linear", cost=.01,scale=FALSE) ypred=predict(svmfit,testing_data) table(predict=ypred, truth=testing_y) plot(x, col=(y+5)/2, pch=19) dat=data.frame(x=x,y=as.factor(IsSpam)) svmfit=svm(IsSpam~., data=dat, kernel="linear", cost=1e5) summarIsSpam(svmfit) plot(svmfit, dat) svmfit=svm(IsSpam~., data=dat, kernel="linear", cost=1) summarIsSpam(svmfit) plot(svmfit,dat) set.seed(1) svmfit=svm(IsSpam~., data=training_data, kernel="radial", gamma=1, cost=1) plot(svmfit, training_data) summary(svmfit) svmfit=svm(IsSpam~., data=training_data, kernel="radial",gamma=1,cost=1e5) plot(svmfit,training_data) set.seed(1) tune.out=tune(svm, IsSpam~., data=training_data, kernel="radial", ranges=list(cost=c(0.1,1,10,100,1000),gamma=c(0.5,1,2,3,4))) summary(tune.out) table(true=testing_data, pred=predict(tune.out$best.model,newx=testing_data)) #ROC install.packages("ROCR") library(ROCR) rocplot=function(pred, truth, ...){ predob = prediction(pred, truth) perf = performance(predob, "tpr", "fpr") plot(perf,...)} svmfit.opt=svm(IsSpam~., data=training_data, kernel="radial",gamma=2, cost=1,decision.values=T) fitted=attributes(predict(svmfit.opt,training_data,decision.values=TRUE))$decision.values par(mfrow=c(1,2)) rocplot(fitted,training_data,main="Training Data") svmfit.flex=svm(IsSpam~., data=training_data, kernel="radial",gamma=50, cost=1, decision.values=T) fitted=attributes(predict(svmfit.flex,training_data,decision.values=T))$decision.values rocplot(fitted,training_data,add=T,col="red") fitted=attributes(predict(svmfit.opt,testing_y,decision.values=T))$decision.values rocplot(fitted,testing_y,main="Test Data") fitted=attributes(predict(svmfit.flex,testing_data,decision.values=T))$decision.values rocplot(fitted,testing_y,add=T,col="red")
/R code/Question1 R code.R
no_license
aloksatpathy/EDAStackOverflow
R
false
false
20,858
r
#reading and transforming the data df1= read.csv(file="QueryResults1.csv",header=TRUE) df2<- read.csv(file="QueryResults2.csv",header=TRUE) StackOverflow<- rbind(df1,df2) #str(StackOverflow) #names(StackOverflow) nrow(StackOverflow) #replacing NA with 1001 StackOverflow [is.na(StackOverflow)] <- 1001 #removing column that contain text or are unrelated to this question StackOverflowdata<- StackOverflow[,-c(1, 2,3,12,14,15,22,23,25,26,27,28,29,30,31,32,33,34)] #str(StackOverflowdata) nrow(StackOverflowdata) #to check uniqueness of data lapply(StackOverflowdata["RejectionReasonId"], unique) StackOverflowdata$IsSpam= ifelse(StackOverflowdata$RejectionReasonId==101,1,0) #str(StackOverflowdata) #names(StackOverflowdata) StackOverflowdata<- StackOverflowdata[,-c(16)] lapply(StackOverflowdata["IsSpam"], unique) #dividing data for training and testing purpose smp_size<- floor(0.75*nrow(StackOverflowdata)) set.seed(123) train_ind<- sample(seq_len(nrow(StackOverflowdata)), size=smp_size) training_data<- StackOverflowdata[train_ind,] testing_data<- StackOverflowdata[-train_ind,] testing_y<- testing_data$IsSpam nrow(training_data) nrow(testing_data) #str(training_data) #names(training_data) #GLM logistics_model<-glm(IsSpam~.,data=training_data,family="binomial") #to discover better model #step(logistics_model, direction = "forward") logistics_model = glm(IsSpam ~ PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_views + owner_upvotes + owner_downvotes + editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount + has_code +post_views + UserId, family = "binomial", data = training_data) summary(logistics_model) #performing trial modelling #step(logistics_model, direction = "backward") #final regression model logistics_model = glm(formula = IsSpam ~ PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views, family = "binomial", data = training_data) summary(logistics_model) #Bayesian information criterion BIC(logistics_model) logistics_probs<-predict(logistics_model,training_data,type="response") head(logistics_probs) logistics_pred_y=rep(0,length(testing_y)) logistics_pred_y[logistics_probs>0.55]=1 training_y=training_data$IsSpam table(logistics_pred_y,training_y) mean(logistics_pred_y!=training_y,na.rm=TRUE) logistics_probs<- predict(logistics_model,testing_data, type="response") head(logistics_probs) logistics_pred_y=rep(0,length(testing_y)) logistics_pred_y[logistics_probs>0.55]=1 table(logistics_pred_y,testing_y) mean(logistics_pred_y!=testing_y,na.rm=TRUE) #kfold for regression library(boot) MSE_10_Fold_CV=cv.glm(training_data,logistics_model,K=10)$delta[1] MSE_10_Fold_CV MSE_10_Fold_CV=NULL for(i in 1:10){ model=glm(IsSpam~poly(PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views),data=training_data) MSE_10_Fold_CV[i]=cv.glm(training_data,model,K=10)$delta[1] } #summary(model) MSE_10_Fold_CV #ROC logistic regression #install.packagesll.packages("ROCR") library(ROCR) ROCRpred=prediction(logistics_probs,testing_y) ROCRperf=performance(ROCRpred,"tpr","fpr") #plot(ROCRperf) #plot(ROCRperf,colorize=TRUE) #plot(ROCRperf,colorize=TRUE,print.cutoffs.at=seq(0,1,0.05),text.adj=c(-0.2,1.7)) as.numeric(performance(ROCRpred,"auc")@y.values) #Linear Discriminant Analysis library(MASS) lda.model<- lda(IsSpam~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,data=training_data) #lda.model #summary(lda.model) lda_pred<- predict(lda.model,training_data) lda_class<- lda_pred$class table(lda_class,training_data$IsSpam) mean(lda_class!=training_data$IsSpam) lda_pred<- predict(lda.model,testing_data) lda_class<- lda_pred$class table(lda_class,testing_data$IsSpam) mean(lda_class!=testing_data$IsSpam) #Cross Validation LDA library(rpart) library(ipred) ip.lda <- function(object, newdata) predict(object, newdata = newdata)$class errorest(factor(training_data$IsSpam)~ training_data$PostTypeId + training_data$PostScore + training_data$post_length + training_data$owner_reputation + training_data$owner_profile_summary + training_data$owner_upvotes+ training_data$editDurationAfterCreation + training_data$q_num_tags + training_data$AnswerCount + training_data$CommentCount+ training_data$post_views, data=training_data, model=lda, estimator="cv",est.para=control.errorest(k=10), predict=ip.lda)$err #ROC LDA S=lda_pred$posterior[,2] roc.curve=function(s,print=FALSE){ Ps=(S>s)*1 FP=sum((Ps==1)*(testing_data$IsSpam==0))/sum(testing_data$IsSpam==0) TP=sum((Ps==1)*(testing_data$IsSpam==1))/sum(testing_data$IsSpam==1) if(print==TRUE){ print(table(Observed=testing_data$IsSpam,Predicted=Ps)) } vect=c(FP,TP) names(vect)=c("FPR","TPR") return(vect) } threshold=0.53 roc.curve(threshold,print=TRUE) ROC.curve=Vectorize(roc.curve) M.ROC=ROC.curve(seq(0,1,by=.01)) plot(M.ROC[1,],M.ROC[2,],col="blue",lwd=2,type="l",main="ROC for LDA") abline(0,1) #Quadratic Discriminant Analysis qda.model<- qda(IsSpam~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,data=training_data) #qda.model qda_pred=predict(qda.model,training_data) qda_class=qda_pred$class table(qda_class,training_data$IsSpam) mean(qda_class!=training_data$IsSpam) qda_pred1=predict(qda.model,testing_data) qda_class_n=qda_pred1$class table(qda_class_n,testing_data$IsSpam) mean(qda_class_n!=testing_data$IsSpam) #Cross Validation QDA ip.qda <- function(object, newdata) predict(object, newdata = newdata)$class errorest(factor(training_data$IsSpam)~ training_data$PostTypeId + training_data$PostScore + training_data$post_length + training_data$owner_reputation + training_data$owner_profile_summary + training_data$owner_upvotes+ training_data$editDurationAfterCreation + training_data$q_num_tags + training_data$AnswerCount + training_data$CommentCount+ training_data$post_views, data=training_data, model=qda, estimator="cv",est.para=control.errorest(k=10), predict=ip.qda)$err #ROC QDA qda.S=qda_pred1$posterior[,2] roc.curve=function(s,print=FALSE){ Ps=(qda.S>s)*1 FP=sum((Ps==1)*(testing_data$IsSpam==0))/sum(testing_data$IsSpam==0) TP=sum((Ps==1)*(testing_data$IsSpam==1))/sum(testing_data$IsSpam==1) if(print==TRUE){ print(table(Observed=testing_data$IsSpam,Predicted=Ps)) } vect=c(FP,TP) names(vect)=c("FPR","TPR") return(vect) } threshold=0.85 roc.curve(threshold,print=TRUE) ROC.curve=Vectorize(roc.curve) M.ROC=ROC.curve(seq(0,1,by=.01)) plot(M.ROC[1,],M.ROC[2,],col="blue",lwd=2,type="l",main="ROC for LDA") abline(0,1) #k nearest neighbours library(class) #install.packagesll.packages("cars") #library(cars) train.x<- cbind(training_data$PostTypeId + training_data$PostScore + training_data$post_length + training_data$owner_reputation + training_data$owner_profile_summary + training_data$owner_upvotes + training_data$editDurationAfterCreation + training_data$q_num_tags + training_data$AnswerCount + training_data$CommentCount + training_data$post_views) test.x<- cbind(testing_data$PostTypeId + testing_data$PostScore + testing_data$post_length + testing_data$owner_reputation + testing_data$owner_profile_summary + testing_data$owner_upvotes + testing_data$editDurationAfterCreation + testing_data$q_num_tags + testing_data$AnswerCount + testing_data$CommentCount + testing_data$post_views) train1.x=train.x[!duplicated(train.x),drop=FALSE] test1.x=test.x[!duplicated(test.x), drop=FALSE] tt<- training_data$IsSpam[duplicated(train.x)=='FALSE'] head(tt) length(tt) knn.pred<- knn(data.frame(train1.x),data.frame(test1.x),tt,k=1) tt1<- testing_data$IsSpam[duplicated(test.x)=='FALSE'] length(tt1) table(knn.pred,tt1) mean(knn.pred!=tt1) knn.pred<- knn(data.frame(train1.x),data.frame(test1.x),tt,k=2) table(knn.pred,tt1) mean(knn.pred!=tt1) #Classification and Regression Trees #CART Modeling: #install.packagesll.packages("tree") library(tree) tree.training_data=tree(as.factor(IsSpam)~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,training_data) text(tree.training_data,pretty=0) summary(tree.training_data) plot(tree.training_data) text(tree.training_data,pretty=0) lf<- seq(1,nrow(training_data)) tree.training_data=tree(as.factor(IsSpam)~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,training_data,subset=lf) tree.pred=predict(tree.training_data,testing_data,type="class") table(tree.pred,testing_y) mean(tree.pred!=testing_data$IsSpam) #Cross Validation and Pruning for the Classification Tree: cv.training_data=cv.tree(tree.training_data,FUN=prune.misclass) names(cv.training_data) #cv.training_data par(mfrow=c(1,2)) plot(cv.training_data$size,cv.training_data$dev,type="b") plot(cv.training_data$k,cv.training_data$dev,type="b") par(mfrow=c(1,1)) prune.training_data=prune.misclass(tree.training_data,best=5) plot(prune.training_data) text(prune.training_data,pretty=0) tree.pred=predict(prune.training_data,testing_data,type="class") table(tree.pred,testing_y) mean(tree.pred!=testing_data$IsSpam) #ROC for CART: tree.pred=predict(tree.training_data,testing_data,type="vector",prob=TRUE) #tree.pred tree.S=tree.pred[,2] roc.curve=function(s,print=FALSE){ Ps=(tree.S>s)*1 FP=sum((Ps==1)*(testing_data$IsSpam==0))/sum(testing_data$IsSpam==0) TP=sum((Ps==1)*(testing_data$IsSpam==1))/sum(testing_data$IsSpam==1) if(print==TRUE){ print(table(Observed=testing_data$IsSpam,Predicted=Ps)) } vect=c(FP,TP) names(vect)=c("FPR","TPR") return(vect) } threshold=0.55 roc.curve(threshold,print=TRUE) ROC.curve=Vectorize(roc.curve) M.ROC=ROC.curve(seq(0,1,by=.01)) plot(M.ROC[1,],M.ROC[2,],col="blue",lwd=2,type="l",main="ROC for CART") abline(0,1) #Random Forest Modeling: #install.packagesll.packages("randomForest") library(randomForest) bag.training_data=randomForest(as.factor(IsSpam)~PostTypeId + PostScore + post_length + owner_reputation + owner_profile_summary + owner_upvotes+ editDurationAfterCreation + q_num_tags + AnswerCount + CommentCount+ post_views,data=training_data,subset=lf,importance=TRUE) #bag.training_data xyz = predict(bag.training_data, newdata = testing_data) table(testing_y, xyz) mean(xyz!=testing_y) #C5.0 #install.packagesll.packages("C50") library(C50) c50_model <- C5.0(training_data[-16], as.factor(training_data$IsSpam)) c50_model #summary(c50_model) #testing C50 c50_pred <- predict(c50_model, testing_data) #install.packagesll.packages("gmodels") library(gmodels) CrossTable(testing_data$IsSpam, c50_pred, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c('actual default', 'predicted default')) #improving C50 with adaptive boosting c50_boost10 <- C5.0(training_data[-16], as.factor(training_data$IsSpam), trials = 10) c50_boost10 c50_pred10 <- predict(c50_boost10, testing_data) CrossTable(testing_data$IsSpam, c50_pred10, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c('actual default', 'predicted default')) #Dimensional Reduction #install.packages("ISLR") library(ISLR) #fix(StackOverflowdata) #names(StackOverflowdata) dim(StackOverflowdata) sum(is.na(StackOverflowdata$IsSpam)) StackOverflowdata=na.omit(StackOverflowdata) dim(StackOverflowdata) sum(is.na(StackOverflowdata)) #install.packages("pls") library(pls) set.seed(2) pcr.fit=pcr(IsSpam~., data=StackOverflowdata,scale=TRUE,validation="CV") summary(pcr.fit) validationplot(pcr.fit,val.type="MSEP") set.seed(1) pcr.fit=pcr(IsSpam~., data=training_data,scale=TRUE, validation="CV") validationplot(pcr.fit,val.type="MSEP") pcr.pred=predict(pcr.fit,testing_data,ncomp=7) mean((pcr.pred-testing_y)^2) pcr.fit=pcr(IsSpam~.,data=testing_data, scale=TRUE,ncomp=7) mean((pcr.pred-testing_y)^2) summary(pcr.fit) # Partial Least Squares set.seed(1) pls.fit=plsr(IsSpam~., data=StackOverflowdata,scale=TRUE, validation="CV") summary(pls.fit) validationplot(pls.fit,val.type="MSEP") pls.pred=predict(pls.fit,testing_data,ncomp=2) mean((pls.pred-testing_y)^2) pls.fit=plsr(IsSpam~., data=StackOverflowdata,scale=TRUE,ncomp=2) summary(pls.fit) # Subset Selection Methods # Best Subset Selection #install.packages("ISLR") library(ISLR) #sum(is.na(StackOverflow$IsSpam)) lapply(StackOverflowdata["IsSpam"], unique) #Confirms NO NA data #install.packages("leaps") library(leaps) regfit.full=regsubsets(IsSpam~.,StackOverflowdata) summary(regfit.full) regfit.full=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19) reg.summary=summary(regfit.full) names(reg.summary) reg.summary$rsq par(mfrow=c(2,2)) plot(reg.summary$rss,xlab="Number of Variables",ylab="RSS",type="l") plot(reg.summary$adjr2,xlab="Number of Variables",ylab="Adjusted RSq",type="l") which.max(reg.summary$adjr2) points(11,reg.summary$adjr2[11], col="red",cex=2,pch=20) plot(reg.summary$cp,xlab="Number of Variables",ylab="Cp",type='l') which.min(reg.summary$cp) points(10,reg.summary$cp[10],col="red",cex=2,pch=20) which.min(reg.summary$bic) plot(reg.summary$bic,xlab="Number of Variables",ylab="BIC",type='l') points(6,reg.summary$bic[6],col="red",cex=2,pch=20) coef(regfit.full,6) # Forward and Backward Stepwise Selection regfit.fwd=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19,method="forward") summary(regfit.fwd) regfit.bwd=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19,method="backward" ) summary(regfit.bwd) coef(regfit.full,7) coef(regfit.fwd,7) coef(regfit.bwd,7) # Choosing Among Models set.seed(1) train=sample(c(TRUE,FALSE), nrow(StackOverflowdata),rep=TRUE) test=(!train) regfit.best=regsubsets(IsSpam~.,data=StackOverflowdata[train,],nvmax=19) test.mat=model.matrix(IsSpam~.,data=StackOverflowdata[test,]) val.errors=rep(NA,19) for(i in 1:11){ coefi=coef(regfit.best,id=i) pred=test.mat[,names(coefi)]%*%coefi val.errors[i]=mean((StackOverflowdata$IsSpam[test]-pred)^2) } val.errors which.min(val.errors) coef(regfit.best,10) predict.regsubsets=function(object,newdata,id,...){ form=as.formula(object$call[[2]]) mat=model.matrix(form,newdata) coefi=coef(object,id=id) xvars=names(coefi) mat[,xvars]%*%coefi } regfit.best=regsubsets(IsSpam~.,data=StackOverflowdata,nvmax=19) coef(regfit.best,10) k=10 set.seed(1) folds=sample(1:k,nrow(StackOverflowdata),replace=TRUE) cv.errors=matrix(NA,k,11, dimnames=list(NULL, paste(1:11))) for(j in 1:k){ best.fit=regsubsets(IsSpam~.,data=StackOverflowdata[folds!=j,],nvmax=11) for(i in 1:11){ pred=predict(best.fit,StackOverflowdata[folds==j,],id=i) cv.errors[j,i]=mean( (StackOverflowdata$IsSpam[folds==j]-pred)^2) } } mean.cv.errors=apply(cv.errors,2,mean) mean.cv.errors par(mfrow=c(1,1)) plot(mean.cv.errors,type='b') reg.best=regsubsets(IsSpam~.,data=StackOverflowdata, nvmax=11) coef(reg.best,11) # Ridge Regression and LASSO #install.packages("ISLR") library(ISLR) fix(Hitters) names(Hitters) dim(Hitters) sum(is.na(Hitters$Salary)) Hitters=na.omit(Hitters) dim(Hitters) sum(is.na(Hitters)) #install.packages("glmnet") library(glmnet) #the package invokes inputs and outputs separately unlike lm and glm x=model.matrix(Salary~.,Hitters)[,-1] y=Hitters$Salary # set vector of lambda values to study range from 10^10 to 0.01, total length=100 grid=10^seq(10,-2,length=100) ridge.mod=glmnet(x,y,alpha=0,lambda=grid) dim(coef(ridge.mod)) # let us look at a few results here #first lambda=50 ridge.mod$lambda[50] coef(ridge.mod)[,50] sqrt(sum(coef(ridge.mod)[-1,50]^2)) #next, lambda=60 ridge.mod$lambda[60] coef(ridge.mod)[,60] sqrt(sum(coef(ridge.mod)[-1,60]^2)) #prediction of the coefficients for lambda=50 (play with this) predict(ridge.mod,s=500,type="coefficients")[1:20,] #prepare for training and validation set testing set.seed(1) train=sample(1:nrow(x), nrow(x)/2) test=(-train) y.test=y[test] ridge.mod=glmnet(x[train,],y[train],alpha=0,lambda=grid, thresh=1e-12) ridge.pred=predict(ridge.mod,s=4,newx=x[test,]) #evaluate and compare test MSE and the spread of y.test mean((ridge.pred-y.test)^2) mean((mean(y[train])-y.test)^2) #test wth two other lambdas ridge.pred=predict(ridge.mod,s=1e10,newx=x[test,]) mean((ridge.pred-y.test)^2) ridge.pred=predict(ridge.mod,s=0,newx=x[test,],exact=T) mean((ridge.pred-y.test)^2) # compare with lm # The following two are the same lm(y~x, subset=train) predict(ridge.mod,s=0,exact=T,type="coefficients")[1:20,] #Cross validation to get the best lambda set.seed(1) cv.out=cv.glmnet(x[train,],y[train],alpha=0) plot(cv.out) bestlam=cv.out$lambda.min bestlam #now predict with the best lambda ridge.pred=predict(ridge.mod,s=bestlam,newx=x[test,]) mean((ridge.pred-y.test)^2) out=glmnet(x,y,alpha=0) predict(out,type="coefficients",s=bestlam)[1:20,] # Lasso #only difference in model building is to use aloha=1 lasso.mod=glmnet(x[train,],y[train],alpha=1,lambda=grid) plot(lasso.mod) # use CV to get best lambda set.seed(1) cv.out=cv.glmnet(x[train,],y[train],alpha=1) plot(cv.out) bestlam=cv.out$lambda.min #use best lambda for prediction lasso.pred=predict(lasso.mod,s=bestlam,newx=x[test,]) mean((lasso.pred-y.test)^2) out=glmnet(x,y,alpha=1,lambda=grid) lasso.coef=predict(out,type="coefficients",s=bestlam)[1:20,] lasso.coef lasso.coef[lasso.coef!=0] ``` # Support Vector Classifier set.seed(1) install.packages("e1071") librarIsSpam(e1071) svmfit=svm(IsSpam~., data=training_data, kernel="linear", cost=10,scale=FALSE) plot(svmfit, training_data) #which ones are support vectors svmfit$index summary(svmfit) svmfit=svm(IsSpam~., data=training_data, kernel="linear", cost=0.1,scale=FALSE) plot(svmfit, training_data) svmfit$index #cross validation set.seed(1) tune.out=tune(svm,IsSpam~.,data=training_data,kernel="linear",ranges=list(cost=c(0.001, 0.01, 0.1, 1,5,10,100))) summary(tune.out) bestmod=tune.out$best.model summary(bestmod) ypred=predict(bestmod,testing_data) table(predict=ypred, truth=testing_y) svmfit=svm(IsSpam~., data=training_data, kernel="linear", cost=.01,scale=FALSE) ypred=predict(svmfit,testing_data) table(predict=ypred, truth=testing_y) plot(x, col=(y+5)/2, pch=19) dat=data.frame(x=x,y=as.factor(IsSpam)) svmfit=svm(IsSpam~., data=dat, kernel="linear", cost=1e5) summarIsSpam(svmfit) plot(svmfit, dat) svmfit=svm(IsSpam~., data=dat, kernel="linear", cost=1) summarIsSpam(svmfit) plot(svmfit,dat) set.seed(1) svmfit=svm(IsSpam~., data=training_data, kernel="radial", gamma=1, cost=1) plot(svmfit, training_data) summary(svmfit) svmfit=svm(IsSpam~., data=training_data, kernel="radial",gamma=1,cost=1e5) plot(svmfit,training_data) set.seed(1) tune.out=tune(svm, IsSpam~., data=training_data, kernel="radial", ranges=list(cost=c(0.1,1,10,100,1000),gamma=c(0.5,1,2,3,4))) summary(tune.out) table(true=testing_data, pred=predict(tune.out$best.model,newx=testing_data)) #ROC install.packages("ROCR") library(ROCR) rocplot=function(pred, truth, ...){ predob = prediction(pred, truth) perf = performance(predob, "tpr", "fpr") plot(perf,...)} svmfit.opt=svm(IsSpam~., data=training_data, kernel="radial",gamma=2, cost=1,decision.values=T) fitted=attributes(predict(svmfit.opt,training_data,decision.values=TRUE))$decision.values par(mfrow=c(1,2)) rocplot(fitted,training_data,main="Training Data") svmfit.flex=svm(IsSpam~., data=training_data, kernel="radial",gamma=50, cost=1, decision.values=T) fitted=attributes(predict(svmfit.flex,training_data,decision.values=T))$decision.values rocplot(fitted,training_data,add=T,col="red") fitted=attributes(predict(svmfit.opt,testing_y,decision.values=T))$decision.values rocplot(fitted,testing_y,main="Test Data") fitted=attributes(predict(svmfit.flex,testing_data,decision.values=T))$decision.values rocplot(fitted,testing_y,add=T,col="red")
testlist <- list(A = structure(c(2.257160459728e+205, 9.53818252179844e+295 ), .Dim = 1:2), B = structure(c(2.19477802979261e+294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L))) result <- do.call(multivariance:::match_rows,testlist) str(result)
/multivariance/inst/testfiles/match_rows/AFL_match_rows/match_rows_valgrind_files/1613124293-test.R
no_license
akhikolla/updatedatatype-list3
R
false
false
321
r
testlist <- list(A = structure(c(2.257160459728e+205, 9.53818252179844e+295 ), .Dim = 1:2), B = structure(c(2.19477802979261e+294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L))) result <- do.call(multivariance:::match_rows,testlist) str(result)
install.packages('MASS') library('MASS') View(cpus) set.seed(20) install.packages('neuralnet') library('neuralnet') base <-cpus max_base <- apply(base, 2, max) min_base <- apply(base, 2, min) base_scal <- scale(base, center = min_base, scale = max_base - min_base) index <- sample(1:nrow(base), round(0.80*nrow(base))) train_base <- as.data.frame(base_scal[index,]) test_base <- as.data.frame(base_scal[-index,]) n <- colnames(base) f <- as.formula(paste('chmin~', paste(n[!n %in% 'chmin'], collapse = '+'))) n1 <- neuralnet(f,data = train_base, hidden = c(9, 5, 3), linear.output = F) plot(n1) pr <- compute(n1, test_base[1:8]) print(pr$net.result) pr$net.result <- sapply(pr$net.result, round, digits = 0) test1 <- table(test_base$age, pr$net.result) test1 sum(test1[1,]) sum(test1[2,]) Accuracy1 <- (test1[1,1] + test1[2, 2])/sum(test1) Accuracy1 install.packages('RSNNS') library(RSNNS) set.seed(20) base2 <- cpus[sample(1:nrow(cpus), length(1:nrow(cpus))), 1:ncol(cpus)] base2_Values <- base2[,1] base2_Target <- base2[, 1:3] base2 <- splitForTrainingAndTest(base2_Values, base2_Target, ratio = 0.2) base2 <- normTrainingAndTestSet(base2) model <- mlp(base2$inputsTrain, base2$targetsTrain, size = 5, maxit = 50, inputsTest = base2$inputsTest, targetsTest = base2$targetsTest) test2 <- confusionMatrix(base2$targetsTrain, encodeClassLabels(fitted.values(model), method = "402040", l = 0.5, h = 0.51)) test2 sum(test2[1,]) sum(test2[2,]) Accuracy2 <- (test2[1,1] + test2[2, 2])/sum(test2) Accuracy2 install.packages("kohonen") library('kohonen') set.seed(20) base3 <- base[1:8] base3_1 <- cpus[1:1] table(base3_1) train <- sample(nrow(base3), 151) X_train <- scale(data3[train,]) X_test <- scale(data3[-train,], center = attr(X_train, "scaled:center"), scale = attr(X_train, "scaled:center")) train_base <- list(measurements = X_train, base3_1 = base3_1[train,]) test_base <- list(measurements = X_test, base3_1 = base3_1[-train,]) mygrid <- somgrid(5, 5, 'chmin') som.base3 <- supersom(train_base, grid = mygrid) som.predict <- predict(som.base3, newdata = test_base) test3 <- table(base3_1[-train,], som.predict$predictions$base3_1) sum(test3[1,]) sum(test3[2,]) Accuracy3 <- (test3[1,1] + test3[2, 2])/sum(test3) Accuracy3 Accuracy1 Accuracy2 Accuracy3
/Dmitrieva_E-2041.r
no_license
dmitrieva18/Dmitrieva_KT
R
false
false
2,645
r
install.packages('MASS') library('MASS') View(cpus) set.seed(20) install.packages('neuralnet') library('neuralnet') base <-cpus max_base <- apply(base, 2, max) min_base <- apply(base, 2, min) base_scal <- scale(base, center = min_base, scale = max_base - min_base) index <- sample(1:nrow(base), round(0.80*nrow(base))) train_base <- as.data.frame(base_scal[index,]) test_base <- as.data.frame(base_scal[-index,]) n <- colnames(base) f <- as.formula(paste('chmin~', paste(n[!n %in% 'chmin'], collapse = '+'))) n1 <- neuralnet(f,data = train_base, hidden = c(9, 5, 3), linear.output = F) plot(n1) pr <- compute(n1, test_base[1:8]) print(pr$net.result) pr$net.result <- sapply(pr$net.result, round, digits = 0) test1 <- table(test_base$age, pr$net.result) test1 sum(test1[1,]) sum(test1[2,]) Accuracy1 <- (test1[1,1] + test1[2, 2])/sum(test1) Accuracy1 install.packages('RSNNS') library(RSNNS) set.seed(20) base2 <- cpus[sample(1:nrow(cpus), length(1:nrow(cpus))), 1:ncol(cpus)] base2_Values <- base2[,1] base2_Target <- base2[, 1:3] base2 <- splitForTrainingAndTest(base2_Values, base2_Target, ratio = 0.2) base2 <- normTrainingAndTestSet(base2) model <- mlp(base2$inputsTrain, base2$targetsTrain, size = 5, maxit = 50, inputsTest = base2$inputsTest, targetsTest = base2$targetsTest) test2 <- confusionMatrix(base2$targetsTrain, encodeClassLabels(fitted.values(model), method = "402040", l = 0.5, h = 0.51)) test2 sum(test2[1,]) sum(test2[2,]) Accuracy2 <- (test2[1,1] + test2[2, 2])/sum(test2) Accuracy2 install.packages("kohonen") library('kohonen') set.seed(20) base3 <- base[1:8] base3_1 <- cpus[1:1] table(base3_1) train <- sample(nrow(base3), 151) X_train <- scale(data3[train,]) X_test <- scale(data3[-train,], center = attr(X_train, "scaled:center"), scale = attr(X_train, "scaled:center")) train_base <- list(measurements = X_train, base3_1 = base3_1[train,]) test_base <- list(measurements = X_test, base3_1 = base3_1[-train,]) mygrid <- somgrid(5, 5, 'chmin') som.base3 <- supersom(train_base, grid = mygrid) som.predict <- predict(som.base3, newdata = test_base) test3 <- table(base3_1[-train,], som.predict$predictions$base3_1) sum(test3[1,]) sum(test3[2,]) Accuracy3 <- (test3[1,1] + test3[2, 2])/sum(test3) Accuracy3 Accuracy1 Accuracy2 Accuracy3
################# require(lubridate) # download the data set, if it doesn't already exist in the working directory # (has already been downloaded previously) if(!file.exists("exdata_data_household_power_consumption.zip")) { download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", "exdata_data_household_power_consumption.zip") } if(!dir.exists("exdata_data_household_power_consumption")) { unzip("exdata_data_household_power_consumption.zip", exdir="exdata_data_household_power_consumption") } # read the data set into R, unless it has been read into R already if(!exists("bigTable")) { classes <- c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric") bigTable <- read.table("exdata_data_household_power_consumption/household_power_consumption.txt", sep=";", header=TRUE, na.strings="?", colClasses=classes) } # create the data frame of date subsets, unless it already exists if(!exists("dateSubset")) { # subset data from only dates within the range 2007-02-01 and 2007-02-02 dateSubset <- bigTable[bigTable$Date == "1/2/2007" | bigTable$Date == "2/2/2007", ] # convert the date/time columns into date/time class objects dateSubset$Date <- dmy(dateSubset$Date) timeVector <- strptime(dateSubset$Time, format="%H:%M:%S", tz="UTC") timeVector[dateSubset$Date=="2007-02-01"] <- update(timeVector[dateSubset$Date=="2007-02-01"], years=2007, months=2, days=1) timeVector[dateSubset$Date=="2007-02-02"] <- update(timeVector[dateSubset$Date=="2007-02-02"], years=2007, months=2, days=2) dateSubset$Time <- timeVector row.names(dateSubset) <- NULL } ################# # create the line graph plot 2 png(file="plot2.png", width=480, height=480, bg="transparent") plot(dateSubset$Time, dateSubset$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="") dev.off()
/plot2.R
no_license
Natasha-R/Exploratory-Data-Analysis-Course-Project-1
R
false
false
2,186
r
################# require(lubridate) # download the data set, if it doesn't already exist in the working directory # (has already been downloaded previously) if(!file.exists("exdata_data_household_power_consumption.zip")) { download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", "exdata_data_household_power_consumption.zip") } if(!dir.exists("exdata_data_household_power_consumption")) { unzip("exdata_data_household_power_consumption.zip", exdir="exdata_data_household_power_consumption") } # read the data set into R, unless it has been read into R already if(!exists("bigTable")) { classes <- c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric") bigTable <- read.table("exdata_data_household_power_consumption/household_power_consumption.txt", sep=";", header=TRUE, na.strings="?", colClasses=classes) } # create the data frame of date subsets, unless it already exists if(!exists("dateSubset")) { # subset data from only dates within the range 2007-02-01 and 2007-02-02 dateSubset <- bigTable[bigTable$Date == "1/2/2007" | bigTable$Date == "2/2/2007", ] # convert the date/time columns into date/time class objects dateSubset$Date <- dmy(dateSubset$Date) timeVector <- strptime(dateSubset$Time, format="%H:%M:%S", tz="UTC") timeVector[dateSubset$Date=="2007-02-01"] <- update(timeVector[dateSubset$Date=="2007-02-01"], years=2007, months=2, days=1) timeVector[dateSubset$Date=="2007-02-02"] <- update(timeVector[dateSubset$Date=="2007-02-02"], years=2007, months=2, days=2) dateSubset$Time <- timeVector row.names(dateSubset) <- NULL } ################# # create the line graph plot 2 png(file="plot2.png", width=480, height=480, bg="transparent") plot(dateSubset$Time, dateSubset$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="") dev.off()
## 1. Build the states data.frame---- ## Clear the environment rm(list = ls()) ## set working dir setwd("C:/Users/jayso/OneDrive/Desktop/coviddata") ## call necessary libraries library(dplyr) library(ggplot2) library(purrr) library(stringr) library(data.table) ## Read the Data states <- fread("C:/Users/jayso/OneDrive/Documents/GitHub/covid-19-data/us-states.csv") ## Read the population data statepop <- fread("C:/RWD/countypopbyfips2.csv") ## merge state data with state population states <- left_join(states, statepop, by = "fips", all.x = TRUE) ## Make the date column a format that R can recognize states$date <- as.Date(states$date) ## Add a column for yesterday's cases states$adayago <- sapply(seq_len(nrow(states)), function(ayer) with(states, sum(cases[date == (date[ayer] - 1) & state == state[ayer]]))) ## Add a column for today's new cases states$newcases <- states$cases - states$adayago ## 7 day average of new cases states$sevdayavg <- sapply(seq_len(nrow(states)), function(ayer) with(states, mean(newcases[date >= (date[ayer] - 7) & date <= date[ayer] & state == state[ayer]]))) ## 7 day average 7 days ago states$sevdayavgwkago <- sapply(seq_len(nrow(states)), function(ayer) with(states, sum(sevdayavg[date == (date[ayer] - 7) & state == state[ayer]]))) ## Change in 7 day average since 7 days ago states$sevdayavgchange <- states$sevdayavg - states$sevdayavgwkago ## Add a column for number of cases one week ago states$aweekago <- sapply(seq_len(nrow(states)), function(semana) with(states, sum(cases[date == (date[semana] - 7) & state == state[semana]]))) ## Add a column for this week's new cases states$weeklynew <- states$cases - states$aweekago ## Add a column for cases 3 weeks ago states$weeksago <- sapply(seq_len(nrow(states)), function(act) with(states, sum(cases[date == (date[act] - 21) & state == state[act]]))) ## Add a column for the estimated number of active cases (total - total from 3 weeks ago) states$active <- states$cases - states$weeksago ## Add a column to calculate the active cases per 100,000 people states$activepp <- states$active / states$population * 100000 ## Add a column to calculate the number of recovered cases (total - active - deaths) states$recovered <- states$cases - states$active - states$deaths ## Add a column to calculate the number of recovered cases per 100,000 people states$recoveredpp <- states$recovered / states$population * 100000 ## Add a column to calculate weekly growth as a percent states$weeklygrowth <- states$weeklynew / states$aweekago ## Add a column to calculate weekly growth per 100,000 people states$actgrowthpp <- states$active / states$population *100000 ## Add a column for total cases per 100,000 states$casespp <- states$cases / states$population * 100000 ## turn states into factor states$state <-as.factor(states$state) states$region <- as.factor(states$region) states$division <- as.factor(states$division) ## Turn a data column into a categorical variable states$activeppF <- cut(states$activepp, breaks = quantile(states$activepp)) table(states$activeppF) library(Hmisc) states$activeppF <- cut2(states$activepp, g = 4) table(states$activeppF) ## yesno <- sample(c("yes", "no"), size = 10, replace = TRUE) ## yesnofac <- factor(yesno, levels = c("yes", "no")) ## relevel(yesnofac, ref = "yes") ## as.numeric(yesnofac) library(plyr) ## restData2 <- mutate(restData, zipGroups = cut2(zipCode, g = 4)) ## table(restData2$zipGroups) ##----- ## Load purrr library(purrr) ## Create a 7 day rolling average for new cases states$newcasesavg <- sapply(seq_len(nrow(states)), function(act) with(states, mean(newcases[date <= (date[act] - 7) & state == state[act]], na.rm = TRUE))) ## Group by division div_summ = filter(states, date == as.Date(max(states$date))) div_summ = group_by(div_summ, division) div_summ = summarise(div_summ, sumcases = sum(cases, na.rm = T), sumactive = sum(active, na.rm = T), sumpop = sum(population, na.rm = T), activepp = sum(active, na.rm = T) / sum(population, na.rm = T) * 100000) div_summ2 <- table(today$division, today$activepp) states$state <- as.factor(states$state) states2 <- states %>% group_by(state) %>% select(date, activepp) %>% filter(min_rank(desc(activepp)) <= 1) %>% arrange(state, desc(activepp)) levels(states$state) ## 2. Functions for analyzing and plotting the states data.frame ---- ## Load ggplot2 library(ggplot2) ## Function to plot a state's total and active per 100,000 curves plotpp <- function(st) { # st = the state whose data we wish to plot s1 <- subset(states, state == st) t1 <- deparse(substitute(st)) t2 <- paste(t1, "Per 100k People") ggplot(s1, aes(x = date)) + geom_line(aes(y = activepp), color = "blue", size = 2) + geom_line(aes(y = casespp), color = "black", size = 2) + labs(title = t2, y = "Total / Active", x = "Date") } ## Function to compare 3 states activepp curves plot3active <- function(st1, st2, st3) { # st = the state whose data we wish to plot s1 <- subset(states, state == st1 | state == st2 | state == st3) t1 <- deparse(substitute(st1)) t2 <- deparse(substitute(st2)) t3 <- deparse(substitute(st3)) t4 <- paste("Active per 100K") ggplot(s1, aes(x = date)) + facet_wrap(~state) + geom_line(aes(y = activepp), color = "blue", size = 2) + labs(title = t4, x = "Date") } plot37DA <- function(st1, st2, st3) { # st = the state whose data we wish to plot s1 <- subset(states, state == st1 | state == st2 | state == st3) t1 <- deparse(substitute(st1)) t2 <- deparse(substitute(st2)) t3 <- deparse(substitute(st3)) t4 <- paste("7 Day Avg of New Cases") ggplot(s1, aes(x = date)) + facet_wrap(~state) + geom_line(aes(y = sevdayavg), color = "blue", size = 2) + labs(title = t4, x = "Date") } plotUSA <- function() { ggplot(states, aes(x = date)) + facet_wrap(~division) + geom_line(aes(y = sevdayavg), color = "blue", size = 2) } ENCentral <- states %>% filter(division == "East North Central") ggplot(ENCentral, aes(x = date)) + facet_wrap(. ~ state) + geom_line(aes(y = sevdayavg), color = "darkred", size = 2) ## Filter the latest numbers date1 <- max(states$date) statestoday <- filter(states, states$date == date1) fastestgrowth <- statestoday %>% select(state, weeklygrowthpp) %>% arrange(desc(weeklygrowthpp)) library(ggplot2) ggplot(states2$Oklahoma, aes(x = date)) + geom_line(aes(y = activepp), color = "blue", size = 2) + geom_line(aes(y = casespp), color = "black", size = 2) + geom_line(aes(y = recoveredpp), color = "red", size = 2) ## 3. Load the counties data ---- ## **Don't try and load the counties data and the states data at the same time** # Clear the environment to make some space - this file contains many observations rm(list = ls()) ## set working dir setwd("C:/Users/jayso/OneDrive/Desktop/covid-data") ## call required libraries library(dplyr) library(ggplot2) library(purrr) library(stringr) library(data.table) # Read the counties data counties <- fread("C:/Users/jayso/OneDrive/Documents/GitHub/covid-19-data/us-counties.csv") ## NYC/KC/territory fix counties$fips[counties$county == "New York City"] = 361111 counties$fips[counties$county == "Kansas City"] = 291111 counties$fips[counties$state == "Puerto Rico"] = 7200 counties$fips[counties$state == "Guam"] = 6600 counties$fips[counties$state == "Virgin Islands"] = 7800 counties$fips[counties$state == "Northern Mariana Islands"] = 6900 counties <- counties[counties$county != "Unknown"] ## Read county population values countydemo <- fread("./demobyfips.csv") ## merge county data with county population counties <- left_join(counties, countydemo, by = "fips", all.x = TRUE) ## filter to cities in/around Mississippi counties <- counties[counties$state == "Mississippi"] MScitynames <- countiesMS$csba MScitynames <- unique(MScitynames) MScitynames <- MScitynames[MScitynames != ""] counties <- counties[counties$csba %in% MScitynames] ggplot(counties, aes(x = date)) + geom_line(aes(y = activepp), col = "blue", size = 2) x <- round(runif(1000, 0, 100)) y <- x + rnorm(1000, 0, 30) summary(y) sd(y) range(y) mean(y) qqplot(x, y) plot(ecdf(x)) xy <- sample(x, 200) mean(x) summary(xy) plot(ecdf(xy)) ## Make the date column a format that R will recognize counties$date <- as.Date(counties$date) ## Add a column for yesterday's cases (with timer so I have a benchmark for judging improvements) counties$adayago2 <- for (i in 1:nrow(counties)) sapply(seq_len(nrow(counties)), function(x) with(counties,)) rep(c("a", "b", "c")) num_repeat <- 10 dates <- data.frame(rep( seq(as.Date('2017-01-01'), as.Date('2017-12-31'), by = 'days'), times = num_repeat)) system.time({ counties$adayago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(cases[date == (date[x] - 1) & fips == fips[x]], na.rm = TRUE))) counties$aweekago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(cases[date == (date[x] - 7) & fips == fips[x]], na.rm = TRUE))) counties$thrweekago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(cases[date == (date[x] - 21) & fips == fips[x]], na.rm = TRUE)))}) counties$active <- counties$cases - counties$thrweekago counties$activepp <- counties$active / counties$population * 100000 counties$newcases <- counties$cases - counties$adayago system.time({ counties$svnDAnc <- sapply(seq_len(nrow(counties)), function(x) with(counties, mean(newcases[date >= (date[x] - 7) & date <= date[x] & fips == fips[x]], na.rm = TRUE))) counties$svnDAlast <- sapply(seq_len(nrow(counties)), function(sumx) with(counties, sum(svnDAnc[date == (date[sumx] - 7) & fips == fips[sumx]], na.rm = TRUE)))}) system.time({ counties$actadayago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(active[date == (date[x] - 1) & fips == fips[x]], na.rm = TRUE))) counties$actaweekago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(active[date == (date[x] - 7) & fips == fips[x]], na.rm = TRUE))) counties$actgrowthpp <- (counties$active - counties$actaweekago) / counties$population *100000 }) countiesDT$newcases <- ifelse(countiesDT$cases - countiesDT$adayago < 0, 0, countiesDT$cases - countiesDT$adayago) countiesDT$newcasesW <- ifelse(countiesDT$cases - countiesDT$aweekago < 0, 0, countiesDT$cases - countiesDT$aweekago) countiesDT$active <- ifelse(countiesDT$cases - countiesDT$thrweekago < 0, 0, countiesDT$cases - countiesDT$thrweekago) data.frame(Count = colSums(df[,-1] == 'Y'), # count of "Y"s in each column # sum of Values column where A/B/C is "Y" Sum = sapply(df[,-1], function(x){sum(df$Values[x == 'Y'])})) RI$adayago <- sapply(seq_len(nrow(RI)), function(x) with(RI, sum(cases[date == (date[x] - 1) & fips == fips[x]], na.rm = TRUE))) #### FYI - system.time call - user, 519, system, 109, elapsed 630.33 countiesDT$newcases <- countiesDT$cases - countiesDT$adayago ### A week ago - with system.time call system.time({ countiesDT$aweekago <- sapply(seq_len(nrow(countiesDT)), function(ayer) with(countiesDT, sum(cases[date == (date[ayer] - 7) & fips == fips[ayer]])))}) ## user system elapsed ## 526.89 101.89 631.96 system.time({ TX$aweekago <- sapply(seq_len(nrow(TX)), function(x) with(TX, sum(cases[date == (date[x] - 7) & fips == fips[x]])))}) system.time({ TX$thrwkago <- sapply(seq_len(nrow(TX)), function(x) with(TX, sum(cases[date == (date[x] - 21) & fips == fips[x]])))}) TX$actthrwkago <- sapply(seq_len(nrow(TX)), function(x) with(TX, sum(active[date == (date[x] - 21) & fips == fips[x]]))) system.time({ RI$aweekago <- lapply(seq_len(nrow(RI)), function(ayer) with(RI, sum(cases[date == (date[ayer] - 7) & fips == fips[ayer]], na.rm = TRUE)))}) ## group by city latest <- max(counties$date) basic_summ = filter(counties, date == as.Date(latest)) basic_summ$csba <- as.factor(basic_summ$csba) basic_summ$csa <- as.factor(basic_summ$csa) basic_summ = group_by(basic_summ, csba, csa) basic_summ = summarise(basic_summ, sumcases = sum(cases), sumactive = sum(active), sumpop = sum(population), activepp = sum(active) / sum(population) * 100000) summary(basic_summ) ## group by state state_summ = filter(counties, date == as.Date(latest)) state_summ = group_by(state_summ, state) state_summ = summarise(state_summ, sumcases = sum(cases, na.rm = T), sumactive = sum(active, na.rm = T), sumpop = sum(population, na.rm = T), activepp = sum(active, na.rm = T) / sum(population, na.rm = T) * 100000) state_summ <- state_summ[state_summ$sumpop > 0,] ## group by division div_summ = filter(counties, date == as.Date(latest)) div_summ = group_by(div_summ, division) div_summ = summarise(div_summ, sumcases = sum(cases, na.rm = T), sumactive = sum(active, na.rm = T), sumpop = sum(population, na.rm = T), activepp = sum(active, na.rm = T) / sum(population, na.rm = T) * 100000) ## filter by state pkstate <- function(pk) { stname <- deparse(substitute(pk)) stname2 <- noquote(stname) sta1 <- filter(counties, state == pk) assign(stname2, sta1, env=.GlobalEnv) } getwd() ## Filter the latest numbers date1 <- max(TX$date) countiestoday <- filter(TX, TX$date == date1) fastestgrowth <- countiestoday %>% select(county, activegrowth) %>% arrange(desc(activegrowth)) ## 4. Plot some county stuff ---- plot3county <- function(co1, co2, co3) { # co = the counties whose data we wish to plot s1 <- subset(counties, county == co1 | county == co2 | county == co3) t1 <- deparse(substitute(co1)) t2 <- deparse(substitute(co2)) t3 <- deparse(substitute(co3)) t4 <- paste("Active per 100K") ggplot(s1, aes(x = date)) + facet_wrap(~county) + geom_line(aes(y = activepp), color = "blue", size = 2) + labs(title = t4, x = "Date") } plot3fips <- function(f1, f2, f3) { # co = the counties whose data we wish to plot s1 <- subset(counties, fips == f1 | fips == f2 | fips == f3) t4 <- paste("Active per 100K") ggplot(s1, aes(x = date)) + facet_wrap(~county) + geom_line(aes(y = active), color = "blue", size = 1) + labs(title = t4, x = "Date") } counties <- counties %>% group_by(csba) ggplot(counties, aes(x = date)) + facet_wrap(. ~ csa) + geom_line(aes(y = activepp), color = "orange", size = 1) today <- counties %>% filter(date == "2020-08-23") today$log <- log(today$activepp) meanlog <- mean(today$log) today$sd <- sd(today$activepp) sqrtsd <- sqrt(175.5) today$log2 <- (today$log - meanlog)/sqrtsd boxplot(today$log2) max(counties$date) cutpoints <- quantile(today$activepp, seq(0, 1, length = 10), na.rm = TRUE) today$activecut <- cut(today$activepp, cutpoints) levels(today$activecut) ### 5. Cross validation ------ library(ggplot2) library(ggthemes) library(zoo) library(xts) library(quantmod) library(forecast) library(fpp) library(fpp2) library(tidyverse) library(caret) set.seed(123) CFR5 <- read.csv("./CFR3.csv") train.control <- trainControl(method = "repeatedcv", number = 10, repeats = 3) model <- train(CFR ~., data = CFRdata1, method = "lm", trControl = train.control) print(model) usa$date <- as.Date(usa$date) usa$thrwksago <- sapply(seq_len(nrow(usa)), function(x) with(usa, sum(cases[date == (date[x] - 21)], na.rm = TRUE))) ## DT counties$peaktodate <- sapply(seq_len(nrow(counties)), function(x) with(counties, max(activepp[date <= date[x] & fips == fips[x]], na.rm = TRUE))) countiesDT <- data.table(counties) countiesDT[, peaked := activepp != peaktodate] countiesDT[, actppvstavg := {tmp <- sapply(seq_len(nrow(countiesDT)), function(x) with(countiesDT, mean(activepp[date <= (date[x] - 1) & state == state[x]]))); activepp / tmp}] x <- round(runif(1000, 0, 100)) x quantile(x) data(iris) head(Iris) head(iris) do.call("rbind", tapply(iris$Sepal.Length, iris$Species, quantile)) statesquant <- do.call("rbind", tapply(statestoday$activepp, statestoday$state, quantile))
/script.R
no_license
jaysonleek/coviddata
R
false
false
17,887
r
## 1. Build the states data.frame---- ## Clear the environment rm(list = ls()) ## set working dir setwd("C:/Users/jayso/OneDrive/Desktop/coviddata") ## call necessary libraries library(dplyr) library(ggplot2) library(purrr) library(stringr) library(data.table) ## Read the Data states <- fread("C:/Users/jayso/OneDrive/Documents/GitHub/covid-19-data/us-states.csv") ## Read the population data statepop <- fread("C:/RWD/countypopbyfips2.csv") ## merge state data with state population states <- left_join(states, statepop, by = "fips", all.x = TRUE) ## Make the date column a format that R can recognize states$date <- as.Date(states$date) ## Add a column for yesterday's cases states$adayago <- sapply(seq_len(nrow(states)), function(ayer) with(states, sum(cases[date == (date[ayer] - 1) & state == state[ayer]]))) ## Add a column for today's new cases states$newcases <- states$cases - states$adayago ## 7 day average of new cases states$sevdayavg <- sapply(seq_len(nrow(states)), function(ayer) with(states, mean(newcases[date >= (date[ayer] - 7) & date <= date[ayer] & state == state[ayer]]))) ## 7 day average 7 days ago states$sevdayavgwkago <- sapply(seq_len(nrow(states)), function(ayer) with(states, sum(sevdayavg[date == (date[ayer] - 7) & state == state[ayer]]))) ## Change in 7 day average since 7 days ago states$sevdayavgchange <- states$sevdayavg - states$sevdayavgwkago ## Add a column for number of cases one week ago states$aweekago <- sapply(seq_len(nrow(states)), function(semana) with(states, sum(cases[date == (date[semana] - 7) & state == state[semana]]))) ## Add a column for this week's new cases states$weeklynew <- states$cases - states$aweekago ## Add a column for cases 3 weeks ago states$weeksago <- sapply(seq_len(nrow(states)), function(act) with(states, sum(cases[date == (date[act] - 21) & state == state[act]]))) ## Add a column for the estimated number of active cases (total - total from 3 weeks ago) states$active <- states$cases - states$weeksago ## Add a column to calculate the active cases per 100,000 people states$activepp <- states$active / states$population * 100000 ## Add a column to calculate the number of recovered cases (total - active - deaths) states$recovered <- states$cases - states$active - states$deaths ## Add a column to calculate the number of recovered cases per 100,000 people states$recoveredpp <- states$recovered / states$population * 100000 ## Add a column to calculate weekly growth as a percent states$weeklygrowth <- states$weeklynew / states$aweekago ## Add a column to calculate weekly growth per 100,000 people states$actgrowthpp <- states$active / states$population *100000 ## Add a column for total cases per 100,000 states$casespp <- states$cases / states$population * 100000 ## turn states into factor states$state <-as.factor(states$state) states$region <- as.factor(states$region) states$division <- as.factor(states$division) ## Turn a data column into a categorical variable states$activeppF <- cut(states$activepp, breaks = quantile(states$activepp)) table(states$activeppF) library(Hmisc) states$activeppF <- cut2(states$activepp, g = 4) table(states$activeppF) ## yesno <- sample(c("yes", "no"), size = 10, replace = TRUE) ## yesnofac <- factor(yesno, levels = c("yes", "no")) ## relevel(yesnofac, ref = "yes") ## as.numeric(yesnofac) library(plyr) ## restData2 <- mutate(restData, zipGroups = cut2(zipCode, g = 4)) ## table(restData2$zipGroups) ##----- ## Load purrr library(purrr) ## Create a 7 day rolling average for new cases states$newcasesavg <- sapply(seq_len(nrow(states)), function(act) with(states, mean(newcases[date <= (date[act] - 7) & state == state[act]], na.rm = TRUE))) ## Group by division div_summ = filter(states, date == as.Date(max(states$date))) div_summ = group_by(div_summ, division) div_summ = summarise(div_summ, sumcases = sum(cases, na.rm = T), sumactive = sum(active, na.rm = T), sumpop = sum(population, na.rm = T), activepp = sum(active, na.rm = T) / sum(population, na.rm = T) * 100000) div_summ2 <- table(today$division, today$activepp) states$state <- as.factor(states$state) states2 <- states %>% group_by(state) %>% select(date, activepp) %>% filter(min_rank(desc(activepp)) <= 1) %>% arrange(state, desc(activepp)) levels(states$state) ## 2. Functions for analyzing and plotting the states data.frame ---- ## Load ggplot2 library(ggplot2) ## Function to plot a state's total and active per 100,000 curves plotpp <- function(st) { # st = the state whose data we wish to plot s1 <- subset(states, state == st) t1 <- deparse(substitute(st)) t2 <- paste(t1, "Per 100k People") ggplot(s1, aes(x = date)) + geom_line(aes(y = activepp), color = "blue", size = 2) + geom_line(aes(y = casespp), color = "black", size = 2) + labs(title = t2, y = "Total / Active", x = "Date") } ## Function to compare 3 states activepp curves plot3active <- function(st1, st2, st3) { # st = the state whose data we wish to plot s1 <- subset(states, state == st1 | state == st2 | state == st3) t1 <- deparse(substitute(st1)) t2 <- deparse(substitute(st2)) t3 <- deparse(substitute(st3)) t4 <- paste("Active per 100K") ggplot(s1, aes(x = date)) + facet_wrap(~state) + geom_line(aes(y = activepp), color = "blue", size = 2) + labs(title = t4, x = "Date") } plot37DA <- function(st1, st2, st3) { # st = the state whose data we wish to plot s1 <- subset(states, state == st1 | state == st2 | state == st3) t1 <- deparse(substitute(st1)) t2 <- deparse(substitute(st2)) t3 <- deparse(substitute(st3)) t4 <- paste("7 Day Avg of New Cases") ggplot(s1, aes(x = date)) + facet_wrap(~state) + geom_line(aes(y = sevdayavg), color = "blue", size = 2) + labs(title = t4, x = "Date") } plotUSA <- function() { ggplot(states, aes(x = date)) + facet_wrap(~division) + geom_line(aes(y = sevdayavg), color = "blue", size = 2) } ENCentral <- states %>% filter(division == "East North Central") ggplot(ENCentral, aes(x = date)) + facet_wrap(. ~ state) + geom_line(aes(y = sevdayavg), color = "darkred", size = 2) ## Filter the latest numbers date1 <- max(states$date) statestoday <- filter(states, states$date == date1) fastestgrowth <- statestoday %>% select(state, weeklygrowthpp) %>% arrange(desc(weeklygrowthpp)) library(ggplot2) ggplot(states2$Oklahoma, aes(x = date)) + geom_line(aes(y = activepp), color = "blue", size = 2) + geom_line(aes(y = casespp), color = "black", size = 2) + geom_line(aes(y = recoveredpp), color = "red", size = 2) ## 3. Load the counties data ---- ## **Don't try and load the counties data and the states data at the same time** # Clear the environment to make some space - this file contains many observations rm(list = ls()) ## set working dir setwd("C:/Users/jayso/OneDrive/Desktop/covid-data") ## call required libraries library(dplyr) library(ggplot2) library(purrr) library(stringr) library(data.table) # Read the counties data counties <- fread("C:/Users/jayso/OneDrive/Documents/GitHub/covid-19-data/us-counties.csv") ## NYC/KC/territory fix counties$fips[counties$county == "New York City"] = 361111 counties$fips[counties$county == "Kansas City"] = 291111 counties$fips[counties$state == "Puerto Rico"] = 7200 counties$fips[counties$state == "Guam"] = 6600 counties$fips[counties$state == "Virgin Islands"] = 7800 counties$fips[counties$state == "Northern Mariana Islands"] = 6900 counties <- counties[counties$county != "Unknown"] ## Read county population values countydemo <- fread("./demobyfips.csv") ## merge county data with county population counties <- left_join(counties, countydemo, by = "fips", all.x = TRUE) ## filter to cities in/around Mississippi counties <- counties[counties$state == "Mississippi"] MScitynames <- countiesMS$csba MScitynames <- unique(MScitynames) MScitynames <- MScitynames[MScitynames != ""] counties <- counties[counties$csba %in% MScitynames] ggplot(counties, aes(x = date)) + geom_line(aes(y = activepp), col = "blue", size = 2) x <- round(runif(1000, 0, 100)) y <- x + rnorm(1000, 0, 30) summary(y) sd(y) range(y) mean(y) qqplot(x, y) plot(ecdf(x)) xy <- sample(x, 200) mean(x) summary(xy) plot(ecdf(xy)) ## Make the date column a format that R will recognize counties$date <- as.Date(counties$date) ## Add a column for yesterday's cases (with timer so I have a benchmark for judging improvements) counties$adayago2 <- for (i in 1:nrow(counties)) sapply(seq_len(nrow(counties)), function(x) with(counties,)) rep(c("a", "b", "c")) num_repeat <- 10 dates <- data.frame(rep( seq(as.Date('2017-01-01'), as.Date('2017-12-31'), by = 'days'), times = num_repeat)) system.time({ counties$adayago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(cases[date == (date[x] - 1) & fips == fips[x]], na.rm = TRUE))) counties$aweekago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(cases[date == (date[x] - 7) & fips == fips[x]], na.rm = TRUE))) counties$thrweekago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(cases[date == (date[x] - 21) & fips == fips[x]], na.rm = TRUE)))}) counties$active <- counties$cases - counties$thrweekago counties$activepp <- counties$active / counties$population * 100000 counties$newcases <- counties$cases - counties$adayago system.time({ counties$svnDAnc <- sapply(seq_len(nrow(counties)), function(x) with(counties, mean(newcases[date >= (date[x] - 7) & date <= date[x] & fips == fips[x]], na.rm = TRUE))) counties$svnDAlast <- sapply(seq_len(nrow(counties)), function(sumx) with(counties, sum(svnDAnc[date == (date[sumx] - 7) & fips == fips[sumx]], na.rm = TRUE)))}) system.time({ counties$actadayago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(active[date == (date[x] - 1) & fips == fips[x]], na.rm = TRUE))) counties$actaweekago <- sapply(seq_len(nrow(counties)), function(x) with(counties, sum(active[date == (date[x] - 7) & fips == fips[x]], na.rm = TRUE))) counties$actgrowthpp <- (counties$active - counties$actaweekago) / counties$population *100000 }) countiesDT$newcases <- ifelse(countiesDT$cases - countiesDT$adayago < 0, 0, countiesDT$cases - countiesDT$adayago) countiesDT$newcasesW <- ifelse(countiesDT$cases - countiesDT$aweekago < 0, 0, countiesDT$cases - countiesDT$aweekago) countiesDT$active <- ifelse(countiesDT$cases - countiesDT$thrweekago < 0, 0, countiesDT$cases - countiesDT$thrweekago) data.frame(Count = colSums(df[,-1] == 'Y'), # count of "Y"s in each column # sum of Values column where A/B/C is "Y" Sum = sapply(df[,-1], function(x){sum(df$Values[x == 'Y'])})) RI$adayago <- sapply(seq_len(nrow(RI)), function(x) with(RI, sum(cases[date == (date[x] - 1) & fips == fips[x]], na.rm = TRUE))) #### FYI - system.time call - user, 519, system, 109, elapsed 630.33 countiesDT$newcases <- countiesDT$cases - countiesDT$adayago ### A week ago - with system.time call system.time({ countiesDT$aweekago <- sapply(seq_len(nrow(countiesDT)), function(ayer) with(countiesDT, sum(cases[date == (date[ayer] - 7) & fips == fips[ayer]])))}) ## user system elapsed ## 526.89 101.89 631.96 system.time({ TX$aweekago <- sapply(seq_len(nrow(TX)), function(x) with(TX, sum(cases[date == (date[x] - 7) & fips == fips[x]])))}) system.time({ TX$thrwkago <- sapply(seq_len(nrow(TX)), function(x) with(TX, sum(cases[date == (date[x] - 21) & fips == fips[x]])))}) TX$actthrwkago <- sapply(seq_len(nrow(TX)), function(x) with(TX, sum(active[date == (date[x] - 21) & fips == fips[x]]))) system.time({ RI$aweekago <- lapply(seq_len(nrow(RI)), function(ayer) with(RI, sum(cases[date == (date[ayer] - 7) & fips == fips[ayer]], na.rm = TRUE)))}) ## group by city latest <- max(counties$date) basic_summ = filter(counties, date == as.Date(latest)) basic_summ$csba <- as.factor(basic_summ$csba) basic_summ$csa <- as.factor(basic_summ$csa) basic_summ = group_by(basic_summ, csba, csa) basic_summ = summarise(basic_summ, sumcases = sum(cases), sumactive = sum(active), sumpop = sum(population), activepp = sum(active) / sum(population) * 100000) summary(basic_summ) ## group by state state_summ = filter(counties, date == as.Date(latest)) state_summ = group_by(state_summ, state) state_summ = summarise(state_summ, sumcases = sum(cases, na.rm = T), sumactive = sum(active, na.rm = T), sumpop = sum(population, na.rm = T), activepp = sum(active, na.rm = T) / sum(population, na.rm = T) * 100000) state_summ <- state_summ[state_summ$sumpop > 0,] ## group by division div_summ = filter(counties, date == as.Date(latest)) div_summ = group_by(div_summ, division) div_summ = summarise(div_summ, sumcases = sum(cases, na.rm = T), sumactive = sum(active, na.rm = T), sumpop = sum(population, na.rm = T), activepp = sum(active, na.rm = T) / sum(population, na.rm = T) * 100000) ## filter by state pkstate <- function(pk) { stname <- deparse(substitute(pk)) stname2 <- noquote(stname) sta1 <- filter(counties, state == pk) assign(stname2, sta1, env=.GlobalEnv) } getwd() ## Filter the latest numbers date1 <- max(TX$date) countiestoday <- filter(TX, TX$date == date1) fastestgrowth <- countiestoday %>% select(county, activegrowth) %>% arrange(desc(activegrowth)) ## 4. Plot some county stuff ---- plot3county <- function(co1, co2, co3) { # co = the counties whose data we wish to plot s1 <- subset(counties, county == co1 | county == co2 | county == co3) t1 <- deparse(substitute(co1)) t2 <- deparse(substitute(co2)) t3 <- deparse(substitute(co3)) t4 <- paste("Active per 100K") ggplot(s1, aes(x = date)) + facet_wrap(~county) + geom_line(aes(y = activepp), color = "blue", size = 2) + labs(title = t4, x = "Date") } plot3fips <- function(f1, f2, f3) { # co = the counties whose data we wish to plot s1 <- subset(counties, fips == f1 | fips == f2 | fips == f3) t4 <- paste("Active per 100K") ggplot(s1, aes(x = date)) + facet_wrap(~county) + geom_line(aes(y = active), color = "blue", size = 1) + labs(title = t4, x = "Date") } counties <- counties %>% group_by(csba) ggplot(counties, aes(x = date)) + facet_wrap(. ~ csa) + geom_line(aes(y = activepp), color = "orange", size = 1) today <- counties %>% filter(date == "2020-08-23") today$log <- log(today$activepp) meanlog <- mean(today$log) today$sd <- sd(today$activepp) sqrtsd <- sqrt(175.5) today$log2 <- (today$log - meanlog)/sqrtsd boxplot(today$log2) max(counties$date) cutpoints <- quantile(today$activepp, seq(0, 1, length = 10), na.rm = TRUE) today$activecut <- cut(today$activepp, cutpoints) levels(today$activecut) ### 5. Cross validation ------ library(ggplot2) library(ggthemes) library(zoo) library(xts) library(quantmod) library(forecast) library(fpp) library(fpp2) library(tidyverse) library(caret) set.seed(123) CFR5 <- read.csv("./CFR3.csv") train.control <- trainControl(method = "repeatedcv", number = 10, repeats = 3) model <- train(CFR ~., data = CFRdata1, method = "lm", trControl = train.control) print(model) usa$date <- as.Date(usa$date) usa$thrwksago <- sapply(seq_len(nrow(usa)), function(x) with(usa, sum(cases[date == (date[x] - 21)], na.rm = TRUE))) ## DT counties$peaktodate <- sapply(seq_len(nrow(counties)), function(x) with(counties, max(activepp[date <= date[x] & fips == fips[x]], na.rm = TRUE))) countiesDT <- data.table(counties) countiesDT[, peaked := activepp != peaktodate] countiesDT[, actppvstavg := {tmp <- sapply(seq_len(nrow(countiesDT)), function(x) with(countiesDT, mean(activepp[date <= (date[x] - 1) & state == state[x]]))); activepp / tmp}] x <- round(runif(1000, 0, 100)) x quantile(x) data(iris) head(Iris) head(iris) do.call("rbind", tapply(iris$Sepal.Length, iris$Species, quantile)) statesquant <- do.call("rbind", tapply(statestoday$activepp, statestoday$state, quantile))
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AMOUNTAIN.R \name{networkSimulation} \alias{networkSimulation} \title{Illustration of weighted network simulation} \usage{ networkSimulation(n, k, theta) } \arguments{ \item{n}{number of nodes in the network} \item{k}{number of nodes in the module, n < k} \item{theta}{module node score follow the uniform distribution in range [theta,1]} } \value{ a list containing network adjacency matrix, node score and module membership } \description{ Simulate a single weighted network } \examples{ pp <- networkSimulation(100,20,0.5) moduleid <- pp[[3]] netid <- 1:100 restp<- netid[-moduleid] groupdesign=list(moduleid,restp) names(groupdesign)=c('module','background') \dontrun{library(qgraph) pg<-qgraph(pp[[1]],groups=groupdesign,legend=TRUE)} } \author{ Dong Li, \email{dxl466@cs.bham.ac.uk} } \keyword{simulation}
/man/networkSimulation.Rd
no_license
fairmiracle/AMOUNTAIN
R
false
true
893
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AMOUNTAIN.R \name{networkSimulation} \alias{networkSimulation} \title{Illustration of weighted network simulation} \usage{ networkSimulation(n, k, theta) } \arguments{ \item{n}{number of nodes in the network} \item{k}{number of nodes in the module, n < k} \item{theta}{module node score follow the uniform distribution in range [theta,1]} } \value{ a list containing network adjacency matrix, node score and module membership } \description{ Simulate a single weighted network } \examples{ pp <- networkSimulation(100,20,0.5) moduleid <- pp[[3]] netid <- 1:100 restp<- netid[-moduleid] groupdesign=list(moduleid,restp) names(groupdesign)=c('module','background') \dontrun{library(qgraph) pg<-qgraph(pp[[1]],groups=groupdesign,legend=TRUE)} } \author{ Dong Li, \email{dxl466@cs.bham.ac.uk} } \keyword{simulation}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plausibleValues.R \name{plausibleValues} \alias{plausibleValues} \title{Plausible-Values Imputation of Factor Scores Estimated from a lavaan Model} \usage{ plausibleValues(object, nDraws = 20L, seed = 12345, omit.imps = c("no.conv", "no.se"), ...) } \arguments{ \item{object}{A fitted model of class \code{\linkS4class{lavaan}}, \code{\link[blavaan]{blavaan}}, or \code{\linkS4class{lavaan.mi}}} \item{nDraws}{\code{integer} specifying the number of draws, analogous to the number of imputed data sets. If \code{object} is of class \code{\linkS4class{lavaan.mi}}, this will be the number of draws taken \emph{per imputation}. Ignored if \code{object} is of class \code{\link[blavaan]{blavaan}}, in which case the number of draws is the number of MCMC samples from the posterior.} \item{seed}{\code{integer} passed to \code{\link{set.seed}()}. Ignored if \code{object} is of class \code{\link[blavaan]{blavaan}},} \item{omit.imps}{\code{character} vector specifying criteria for omitting imputations when \code{object} is of class \code{\linkS4class{lavaan.mi}}. Can include any of \code{c("no.conv", "no.se", "no.npd")}.} \item{...}{Optional arguments to pass to \code{\link[lavaan]{lavPredict}}. \code{assemble} will be ignored because multiple groups are always assembled into a single \code{data.frame} per draw. \code{type} will be ignored because it is set internally to \code{type="lv"}.} } \value{ A \code{list} of length \code{nDraws}, each of which is a \code{data.frame} containing plausible values, which can be treated as a \code{list} of imputed data sets to be passed to \code{\link{runMI}} (see \bold{Examples}). If \code{object} is of class \code{\linkS4class{lavaan.mi}}, the \code{list} will be of length \code{nDraws*m}, where \code{m} is the number of imputations. } \description{ Draw plausible values of factor scores estimated from a fitted \code{\link[lavaan]{lavaan}} model, then treat them as multiple imputations of missing data using \code{\link{runMI}}. } \details{ Because latent variables are unobserved, they can be considered as missing data, which can be imputed using Monte Carlo methods. This may be of interest to researchers with sample sizes too small to fit their complex structural models. Fitting a factor model as a first step, \code{\link[lavaan]{lavPredict}} provides factor-score estimates, which can be treated as observed values in a path analysis (Step 2). However, the resulting standard errors and test statistics could not be trusted because the Step-2 analysis would not take into account the uncertainty about the estimated factor scores. Using the asymptotic sampling covariance matrix of the factor scores provided by \code{\link[lavaan]{lavPredict}}, \code{plausibleValues} draws a set of \code{nDraws} imputations from the sampling distribution of each factor score, returning a list of data sets that can be treated like multiple imputations of incomplete data. If the data were already imputed to handle missing data, \code{plausibleValues} also accepts an object of class \code{\linkS4class{lavaan.mi}}, and will draw \code{nDraws} plausible values from each imputation. Step 2 would then take into account uncertainty about both missing values and factor scores. Bayesian methods can also be used to generate factor scores, as available with the \pkg{blavaan} package, in which case plausible values are simply saved parameters from the posterior distribution. See Asparouhov and Muthen (2010) for further technical details and references. Each returned \code{data.frame} includes a \code{case.idx} column that indicates the corresponding rows in the data set to which the model was originally fitted (unless the user requests only Level-2 variables). This can be used to merge the plausible values with the original observed data, but users should note that including any new variables in a Step-2 model might not accurately account for their relationship(s) with factor scores because they were not accounted for in the Step-1 model from which factor scores were estimated. If \code{object} is a multilevel \code{lavaan} model, users can request plausible values for latent variables at particular levels of analysis by setting the \code{\link[lavaan]{lavPredict}} argument \code{level=1} or \code{level=2}. If the \code{level} argument is not passed via \dots, then both levels are returned in a single merged data set per draw. For multilevel models, each returned \code{data.frame} also includes a column indicating to which cluster each row belongs (unless the user requests only Level-2 variables). } \examples{ ## example from ?cfa and ?lavPredict help pages HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' fit1 <- cfa(HS.model, data = HolzingerSwineford1939) fs1 <- plausibleValues(fit1, nDraws = 3, ## lavPredict() can add only the modeled data append.data = TRUE) lapply(fs1, head) ## To merge factor scores to original data.frame (not just modeled data) fs1 <- plausibleValues(fit1, nDraws = 3) idx <- lavInspect(fit1, "case.idx") # row index for each case if (is.list(idx)) idx <- do.call(c, idx) # for multigroup models data(HolzingerSwineford1939) # copy data to workspace HolzingerSwineford1939$case.idx <- idx # add row index as variable ## loop over draws to merge original data with factor scores for (i in seq_along(fs1)) { fs1[[i]] <- merge(fs1[[i]], HolzingerSwineford1939, by = "case.idx") } lapply(fs1, head) ## multiple-group analysis, in 2 steps step1 <- cfa(HS.model, data = HolzingerSwineford1939, group = "school", group.equal = c("loadings","intercepts")) PV.list <- plausibleValues(step1) ## subsequent path analysis path.model <- ' visual ~ c(t1, t2)*textual + c(s1, s2)*speed ' \dontrun{ step2 <- sem.mi(path.model, data = PV.list, group = "school") ## test equivalence of both slopes across groups lavTestWald.mi(step2, constraints = 't1 == t2 ; s1 == s2') } ## multilevel example from ?Demo.twolevel help page model <- ' level: 1 fw =~ y1 + y2 + y3 fw ~ x1 + x2 + x3 level: 2 fb =~ y1 + y2 + y3 fb ~ w1 + w2 ' msem <- sem(model, data = Demo.twolevel, cluster = "cluster") mlPVs <- plausibleValues(msem, nDraws = 3) # both levels by default lapply(mlPVs, head, n = 10) ## only Level 1 mlPV1 <- plausibleValues(msem, nDraws = 3, level = 1) lapply(mlPV1, head) ## only Level 2 mlPV2 <- plausibleValues(msem, nDraws = 3, level = 2) lapply(mlPV2, head) } \references{ Asparouhov, T. & Muthen, B. O. (2010). \emph{Plausible values for latent variables using M}plus. Technical Report. Retrieved from www.statmodel.com/download/Plausible.pdf } \seealso{ \code{\link{runMI}}, \code{\linkS4class{lavaan.mi}} } \author{ Terrence D. Jorgensen (University of Amsterdam; \email{TJorgensen314@gmail.com}) }
/semTools/man/plausibleValues.Rd
no_license
HarmanjitS/semTools
R
false
true
6,979
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plausibleValues.R \name{plausibleValues} \alias{plausibleValues} \title{Plausible-Values Imputation of Factor Scores Estimated from a lavaan Model} \usage{ plausibleValues(object, nDraws = 20L, seed = 12345, omit.imps = c("no.conv", "no.se"), ...) } \arguments{ \item{object}{A fitted model of class \code{\linkS4class{lavaan}}, \code{\link[blavaan]{blavaan}}, or \code{\linkS4class{lavaan.mi}}} \item{nDraws}{\code{integer} specifying the number of draws, analogous to the number of imputed data sets. If \code{object} is of class \code{\linkS4class{lavaan.mi}}, this will be the number of draws taken \emph{per imputation}. Ignored if \code{object} is of class \code{\link[blavaan]{blavaan}}, in which case the number of draws is the number of MCMC samples from the posterior.} \item{seed}{\code{integer} passed to \code{\link{set.seed}()}. Ignored if \code{object} is of class \code{\link[blavaan]{blavaan}},} \item{omit.imps}{\code{character} vector specifying criteria for omitting imputations when \code{object} is of class \code{\linkS4class{lavaan.mi}}. Can include any of \code{c("no.conv", "no.se", "no.npd")}.} \item{...}{Optional arguments to pass to \code{\link[lavaan]{lavPredict}}. \code{assemble} will be ignored because multiple groups are always assembled into a single \code{data.frame} per draw. \code{type} will be ignored because it is set internally to \code{type="lv"}.} } \value{ A \code{list} of length \code{nDraws}, each of which is a \code{data.frame} containing plausible values, which can be treated as a \code{list} of imputed data sets to be passed to \code{\link{runMI}} (see \bold{Examples}). If \code{object} is of class \code{\linkS4class{lavaan.mi}}, the \code{list} will be of length \code{nDraws*m}, where \code{m} is the number of imputations. } \description{ Draw plausible values of factor scores estimated from a fitted \code{\link[lavaan]{lavaan}} model, then treat them as multiple imputations of missing data using \code{\link{runMI}}. } \details{ Because latent variables are unobserved, they can be considered as missing data, which can be imputed using Monte Carlo methods. This may be of interest to researchers with sample sizes too small to fit their complex structural models. Fitting a factor model as a first step, \code{\link[lavaan]{lavPredict}} provides factor-score estimates, which can be treated as observed values in a path analysis (Step 2). However, the resulting standard errors and test statistics could not be trusted because the Step-2 analysis would not take into account the uncertainty about the estimated factor scores. Using the asymptotic sampling covariance matrix of the factor scores provided by \code{\link[lavaan]{lavPredict}}, \code{plausibleValues} draws a set of \code{nDraws} imputations from the sampling distribution of each factor score, returning a list of data sets that can be treated like multiple imputations of incomplete data. If the data were already imputed to handle missing data, \code{plausibleValues} also accepts an object of class \code{\linkS4class{lavaan.mi}}, and will draw \code{nDraws} plausible values from each imputation. Step 2 would then take into account uncertainty about both missing values and factor scores. Bayesian methods can also be used to generate factor scores, as available with the \pkg{blavaan} package, in which case plausible values are simply saved parameters from the posterior distribution. See Asparouhov and Muthen (2010) for further technical details and references. Each returned \code{data.frame} includes a \code{case.idx} column that indicates the corresponding rows in the data set to which the model was originally fitted (unless the user requests only Level-2 variables). This can be used to merge the plausible values with the original observed data, but users should note that including any new variables in a Step-2 model might not accurately account for their relationship(s) with factor scores because they were not accounted for in the Step-1 model from which factor scores were estimated. If \code{object} is a multilevel \code{lavaan} model, users can request plausible values for latent variables at particular levels of analysis by setting the \code{\link[lavaan]{lavPredict}} argument \code{level=1} or \code{level=2}. If the \code{level} argument is not passed via \dots, then both levels are returned in a single merged data set per draw. For multilevel models, each returned \code{data.frame} also includes a column indicating to which cluster each row belongs (unless the user requests only Level-2 variables). } \examples{ ## example from ?cfa and ?lavPredict help pages HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' fit1 <- cfa(HS.model, data = HolzingerSwineford1939) fs1 <- plausibleValues(fit1, nDraws = 3, ## lavPredict() can add only the modeled data append.data = TRUE) lapply(fs1, head) ## To merge factor scores to original data.frame (not just modeled data) fs1 <- plausibleValues(fit1, nDraws = 3) idx <- lavInspect(fit1, "case.idx") # row index for each case if (is.list(idx)) idx <- do.call(c, idx) # for multigroup models data(HolzingerSwineford1939) # copy data to workspace HolzingerSwineford1939$case.idx <- idx # add row index as variable ## loop over draws to merge original data with factor scores for (i in seq_along(fs1)) { fs1[[i]] <- merge(fs1[[i]], HolzingerSwineford1939, by = "case.idx") } lapply(fs1, head) ## multiple-group analysis, in 2 steps step1 <- cfa(HS.model, data = HolzingerSwineford1939, group = "school", group.equal = c("loadings","intercepts")) PV.list <- plausibleValues(step1) ## subsequent path analysis path.model <- ' visual ~ c(t1, t2)*textual + c(s1, s2)*speed ' \dontrun{ step2 <- sem.mi(path.model, data = PV.list, group = "school") ## test equivalence of both slopes across groups lavTestWald.mi(step2, constraints = 't1 == t2 ; s1 == s2') } ## multilevel example from ?Demo.twolevel help page model <- ' level: 1 fw =~ y1 + y2 + y3 fw ~ x1 + x2 + x3 level: 2 fb =~ y1 + y2 + y3 fb ~ w1 + w2 ' msem <- sem(model, data = Demo.twolevel, cluster = "cluster") mlPVs <- plausibleValues(msem, nDraws = 3) # both levels by default lapply(mlPVs, head, n = 10) ## only Level 1 mlPV1 <- plausibleValues(msem, nDraws = 3, level = 1) lapply(mlPV1, head) ## only Level 2 mlPV2 <- plausibleValues(msem, nDraws = 3, level = 2) lapply(mlPV2, head) } \references{ Asparouhov, T. & Muthen, B. O. (2010). \emph{Plausible values for latent variables using M}plus. Technical Report. Retrieved from www.statmodel.com/download/Plausible.pdf } \seealso{ \code{\link{runMI}}, \code{\linkS4class{lavaan.mi}} } \author{ Terrence D. Jorgensen (University of Amsterdam; \email{TJorgensen314@gmail.com}) }
# plot tuning performance library(ggplot2) library(gridExtra) source(file = "helperfunctions.R") load(file = "./data/cv_lists-nnet-tuning.RData") parameters = expand.grid("size" = seq(from = 3, to = 15, by = 2), "decay" = c(0.01, 0.1, 0.5, 0.8, 1)) # extract results from tuning with helperfunction loss = helper.cvlist.tune(cv.list.u) x = 1:length(loss[[1]]) # 3x2 plot for each tau-category df = data.frame(loss[[1]])/10000 blank.x = theme(axis.title.x = element_blank()) caption.b = labs(y = "loss [10.000]") # only y-axis caption = labs(x = "parameter index", # x- and y-axis y = "loss [10.000]") # text inside plot (for tau-category 1) text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 1") # sub-plot for tau-category 1 g1 = ggplot(df, aes(x=x, y=loss[[1]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x # sub-plots for tau-category 2:6 text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 2") g2 = ggplot(df, aes(x=x, y=loss[[2]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 3") g3 = ggplot(df, aes(x=x, y=loss[[3]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 4") g4 = ggplot(df, aes(x=x, y=loss[[4]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 5") g5 = ggplot(df, aes(x=x, y=loss[[5]]/10000)) + geom_point() + caption + text + theme_bw() text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 6") g6 = ggplot(df, aes(x=x, y=loss[[6]]/10000)) + geom_point() + caption + text + theme_bw() # combine plots plot = grid.arrange(g1, g2 , g3, g4, g5, g6, nrow = 3, ncol = 2) # save plot as pdf width = 2 hight = 1 b = 11 ggsave(file="./graphs/plots/nnet_tuning.pdf", plot, width = b*width, height = b*hight, dpi = 150, units = "cm", device='pdf') dev.off() # combine tau-categories # when combining the graphs from previous plot, it is important to # normalize the loss of each category to 1 since the loss depends on # the item_price, as well as the tau-category. # higher tau-category leads naturally to a higher loss su = (df[,1]*(-1))/max(df[,1]*(-1)) # tau-category 1 su = loss[[1]]*(-1)/max(loss[[1]]*(-1)) for (i in 2:6){ su = su + (loss[[i]]*(-1))/max(loss[[i]]*(-1)) } su = su/6 * (-1) # normalize and change sign # to compare shape to previous plots su2 = data.frame(su) # change to data.frame for ggplot() caption = labs(x = "parameter index", y = "normed loss") plot = ggplot(su2, aes(x=x, y=su2)) + geom_point() + caption + theme_bw() width = 1 hight = 1/2 b = 11 ggsave(file="./graphs/plots/nnet-normed_sum.pdf", plot, width = b*width, height = b*hight, dpi = 150, units = "cm", device='pdf') plot dev.off() parameters[which.max(su2[[1]]),] # best settings for nnet df[which.max(su2[[1]]),] # results for best settings
/submission/graphs/nnet_tuning_graph.R
no_license
fractaldust/SPL_DFK
R
false
false
3,666
r
# plot tuning performance library(ggplot2) library(gridExtra) source(file = "helperfunctions.R") load(file = "./data/cv_lists-nnet-tuning.RData") parameters = expand.grid("size" = seq(from = 3, to = 15, by = 2), "decay" = c(0.01, 0.1, 0.5, 0.8, 1)) # extract results from tuning with helperfunction loss = helper.cvlist.tune(cv.list.u) x = 1:length(loss[[1]]) # 3x2 plot for each tau-category df = data.frame(loss[[1]])/10000 blank.x = theme(axis.title.x = element_blank()) caption.b = labs(y = "loss [10.000]") # only y-axis caption = labs(x = "parameter index", # x- and y-axis y = "loss [10.000]") # text inside plot (for tau-category 1) text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 1") # sub-plot for tau-category 1 g1 = ggplot(df, aes(x=x, y=loss[[1]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x # sub-plots for tau-category 2:6 text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 2") g2 = ggplot(df, aes(x=x, y=loss[[2]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 3") g3 = ggplot(df, aes(x=x, y=loss[[3]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 4") g4 = ggplot(df, aes(x=x, y=loss[[4]]/10000)) + geom_point() + caption.b + text + theme_bw() + blank.x text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 5") g5 = ggplot(df, aes(x=x, y=loss[[5]]/10000)) + geom_point() + caption + text + theme_bw() text = annotate(geom = "text", x=Inf, y=-Inf,hjust = 1, vjust = 0, color = "red", size = 4, label = "tau_c = 6") g6 = ggplot(df, aes(x=x, y=loss[[6]]/10000)) + geom_point() + caption + text + theme_bw() # combine plots plot = grid.arrange(g1, g2 , g3, g4, g5, g6, nrow = 3, ncol = 2) # save plot as pdf width = 2 hight = 1 b = 11 ggsave(file="./graphs/plots/nnet_tuning.pdf", plot, width = b*width, height = b*hight, dpi = 150, units = "cm", device='pdf') dev.off() # combine tau-categories # when combining the graphs from previous plot, it is important to # normalize the loss of each category to 1 since the loss depends on # the item_price, as well as the tau-category. # higher tau-category leads naturally to a higher loss su = (df[,1]*(-1))/max(df[,1]*(-1)) # tau-category 1 su = loss[[1]]*(-1)/max(loss[[1]]*(-1)) for (i in 2:6){ su = su + (loss[[i]]*(-1))/max(loss[[i]]*(-1)) } su = su/6 * (-1) # normalize and change sign # to compare shape to previous plots su2 = data.frame(su) # change to data.frame for ggplot() caption = labs(x = "parameter index", y = "normed loss") plot = ggplot(su2, aes(x=x, y=su2)) + geom_point() + caption + theme_bw() width = 1 hight = 1/2 b = 11 ggsave(file="./graphs/plots/nnet-normed_sum.pdf", plot, width = b*width, height = b*hight, dpi = 150, units = "cm", device='pdf') plot dev.off() parameters[which.max(su2[[1]]),] # best settings for nnet df[which.max(su2[[1]]),] # results for best settings
% Generated by roxygen2 (4.1.0): do not edit by hand % Please edit documentation in R/sampling.R \name{betasUnder} \alias{betasUnder} \title{betasUnder} \usage{ betasUnder(y, positive = 1, N = 10, method = "perc") } \arguments{ \item{y}{response variable} \item{positive}{value of the positive (minority) class} \item{N}{number of values of beta to return} \item{method}{method to compute beta: perc or prob} } \value{ values of beta for a give response variable } \description{ Defines the possible levels of undersampling given the class proporiton } \examples{ y <- rep(c(1, 0, 1, 0, 0, 0), 100) betasUnder(y, positive=1, N = 10, method="perc") }
/man/betasUnder.Rd
no_license
dalpozz/warping
R
false
false
654
rd
% Generated by roxygen2 (4.1.0): do not edit by hand % Please edit documentation in R/sampling.R \name{betasUnder} \alias{betasUnder} \title{betasUnder} \usage{ betasUnder(y, positive = 1, N = 10, method = "perc") } \arguments{ \item{y}{response variable} \item{positive}{value of the positive (minority) class} \item{N}{number of values of beta to return} \item{method}{method to compute beta: perc or prob} } \value{ values of beta for a give response variable } \description{ Defines the possible levels of undersampling given the class proporiton } \examples{ y <- rep(c(1, 0, 1, 0, 0, 0), 100) betasUnder(y, positive=1, N = 10, method="perc") }
#### Subsetting #### #### 1. Integers #### # Positive integers behave just like *ij* notation in linear algebra. # Lets work with an example data frame `df` inspired from the Beatles. df <- data.frame(name=c("John","Paul","George","Ringo"), birth=c(1940, 1942, 1943, 1940), insturment=c("guitar", "bass","guitar","drums") ) df # The following gives the element in 2nd row and 3rd column. df[2,3] #### Multiple integers to subset #### # By giving vectors as indices, we can also get multiple rows and columns, giving multiple elements. # The following gives the elements that are in 2nd and 4th rows and the 3rd column. df[c(2,4),3] # The following gives the elements that are in 2nd & 4th rows and 2nd & 3rd columns. df[c(2,4),c(2,3)] # When selecting a series of rows and columns in a sequential manner, `:` becomes very handy. # (Remember: `start:end` gives us a sequence of integers. For example `1:10` gives a vector of integers from 1 to 10.) # Select rows from 1 to 3 and columns from 1 to 2. df[1:3, 1:2] #### Repeating integers #### # repeating input repeats output. df[c(1,1,1,2,2), 1:3] #### Integer `0` #### # As an index, **zero will return nothing** from a dimension. This creates an empty object. df[1:2,0] #### Negative integers #### # Negative integers return **everything but** the elements at the specified locations. # You cannot use both negative and positive integers in the same dimension # Exclude rows 2 to 4 and select columns 2 to 3. df[-c(2:4), 2:3] # Exclude rows 2 to 4 and select columns 2 to 3. df[-c(2:4), 2:3] #### 2. Blank Spaces #### # Blank spaces return **everything** # (i.e., no subsetting occurs on that dimension) vec <- c(6,1,3,6,10,5) vec[] # Return every element on row 1 df[1,] # Return every element on column 2 df[,2] #### 3. Names #### # If your object has names, you can ask for elements or columns back by name. (We talked about this in the first session) names(vec) <- c("a","b","c","d","e","f") vec # Now I can call elements in `vec` by their names vec[c("a","b","d")] # Same applies to columns and column names df[ ,"birth"] df[ ,c("name","birth")] #### 4. Logical #### # You can subset with a logical vector of the **same length as the dimension** you are subsetting. Each element that corresponds to a TRUE will be returned. # The following will return 2nd, 4th and 5th elements in `vec` vec[c(FALSE,TRUE,FALSE,TRUE,TRUE,FALSE)] # The following will return **2nd, 3rd rows** in `df` df[c(FALSE,TRUE,TRUE,FALSE), ] #### Subsetting Lists #### # Subsetting lists can get tricky, since a list can contain objects that has one or more dimensions. lst <- list(c(1,2), TRUE, c("a", "b", "c")) lst # What is the difference? lst[c(1,2)] # outputs a list with 2 objects lst[1] # outputs a list with 1 object lst[[1]] # outputs a vector ### Easiest way to subset data frames and lists: `$` sign # The most common syntax for subsetting lists and data frames: # When we have a names list such as names(lst) <- c("alpha", "beta", "gamma") lst # then we can subset objects with `$` lst$alpha lst$beta lst$gamma # It also works to subset columns of a data frame df$birth #### R Packages #### install.packages(c("ggplot2", "maps", "RColorBrewer")) library("ggplot2") library("maps") library("RColorBrewer") #### Diamonds #### diamonds <- data.frame(diamonds) # first 6 rows diamonds[1:6,] # last 6 rows dim(diamonds) ncol(diamonds) # number of columns #one way nrow(diamonds) # number of rows nrow(diamonds) - 6 diamonds[53934:53940,] # another way diamonds[(nrow(diamonds)-6):nrow(diamonds),] diamonds[-( 1: (nrow(diamonds)-6) ), ] # easiest way to check the first and last 5 rows head(diamonds, 20) tail(diamonds) # view data View(diamonds) # notice: Capital V ## Help pages ## # You can open the help page for any R object (including functions) by typing `?` # followed by the object's name ?diamonds #### Logical tests #### #### Logical comparisons #### # What will these return? 1< 3 1> 3 c(1, 2, 3, 4, 5) > 3 #### %in% #### # What does this do? 1 %in% c(1, 2, 3, 4) 1 %in% c(2, 3, 4) c(3,4,5,6) %in% c(2, 3, 4) #### Boolean operators #### ?Logic x <- 4 # & -- and x > 2 & x < 9 x > 5 & x < 9 x > 5 & x < 2 TRUE & TRUE TRUE & TRUE & TRUE & TRUE TRUE & TRUE & FALSE & TRUE # | -- or TRUE | TRUE TRUE | FALSE FALSE | FALSE x > 2 | x < 9 x > 5 | x < 9 x > 5 | x < 2 # xor -- Is either condition 1 or condition 2 true, but not both? xor(TRUE, TRUE) xor(TRUE, FALSE) xor(FALSE, TRUE) xor(FALSE, FALSE) xor(x > 2, x < 9) xor(x > 5, x < 9) xor(x > 5, x < 2) # ! -- Negation !c(TRUE, TRUE) !c(TRUE, FALSE) !c(FALSE, FALSE) !(x > 2, x < 9) !(x > 5, x < 9) !(x > 5, x < 2) # any -- is any condition true? any(c(TRUE, FALSE, FALSE)) any(c(FALSE, FALSE, FALSE)) any(x > 5, x < 2) any(x > 2, x < 9) # all -- is every condition TRUE? all(c(TRUE, TRUE, TRUE)) all(c(TRUE, FALSE, TRUE)) all(x > 5, x < 2) all(x > 2, x < 9) #### Your turn #### w <- c(-1, 0, 1) x <- c(5, 15) y <- "February" z <- c("Monday", "Tuesday", "Friday") # Is w positive? # Is x greater than 10 and less than 20? Is object y the word February? # Is every value in z a day of the week? ## Answers # Is w positive? w> 0 # Is x greater than 10 and less than 20? 10 < x & x < 20 #Is object y the word February? y == "February" # Is every value in z a day of the week? all(z %in% c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")) # Common mistakes x > 10 & < 20 y = "February" all(z == "Monday" | "Tuesday" | "Wednesday"...) #### Logical subsetting ##### x_zeroes <- diamonds$x == 0 head(x_zeroes) # What will this return? diamonds[x_zeroes, ] #### Saving results #### # Prints to screen diamonds[diamonds$x > 10, ] # Saves to new data frame big <- diamonds[diamonds$x > 10, ] # Overwrites existing data frame. Dangerous! diamonds <- diamonds[diamonds$x < 10,] diamonds <- diamonds[1, 1] diamonds # Uh oh! rm(diamonds) diamonds <- data.frame(diamonds) # Phew! #### NA behavior #### a <- c(1, NA) a == NA is.na(a) b <- c(1, 2, 3, 4, NA) sum(b) sum(b, na.rm = TRUE) #### NA Assignment #### # Before removing outliers qplot(x, y, data = diamonds) ## Let's remove outliers ## ?diamonds # Let's start with x summary(diamonds$x) # there are 0s in x #but x is supposed to be the lenght of the diamond, it can't be 0, a diamond is a 3d object in real life diamonds$x[diamonds$x == 0] # we can assign NA to 0s to let qplot know that these are missing values diamonds$x[diamonds$x == 0] <- NA # now 0s gone from the Min. and we have NA's summary(diamonds$x) # Now let's do y summary(diamonds$y) # we can assign NA to 0s to let qplot know that these are missing values diamonds$y[diamonds$y == 0] <- NA # very big diamonds y_big <- diamonds$y > 20 diamonds$y[y_big] <- NA # outliers are assigned as NA! summary(diamonds$y) # let's look at our plot again qplot(x, y, data = diamonds)
/IntroToRSessions/RIntroductionWorkshop_July2017/Session2/Session2.R
no_license
spiralelucide/R
R
false
false
6,997
r
#### Subsetting #### #### 1. Integers #### # Positive integers behave just like *ij* notation in linear algebra. # Lets work with an example data frame `df` inspired from the Beatles. df <- data.frame(name=c("John","Paul","George","Ringo"), birth=c(1940, 1942, 1943, 1940), insturment=c("guitar", "bass","guitar","drums") ) df # The following gives the element in 2nd row and 3rd column. df[2,3] #### Multiple integers to subset #### # By giving vectors as indices, we can also get multiple rows and columns, giving multiple elements. # The following gives the elements that are in 2nd and 4th rows and the 3rd column. df[c(2,4),3] # The following gives the elements that are in 2nd & 4th rows and 2nd & 3rd columns. df[c(2,4),c(2,3)] # When selecting a series of rows and columns in a sequential manner, `:` becomes very handy. # (Remember: `start:end` gives us a sequence of integers. For example `1:10` gives a vector of integers from 1 to 10.) # Select rows from 1 to 3 and columns from 1 to 2. df[1:3, 1:2] #### Repeating integers #### # repeating input repeats output. df[c(1,1,1,2,2), 1:3] #### Integer `0` #### # As an index, **zero will return nothing** from a dimension. This creates an empty object. df[1:2,0] #### Negative integers #### # Negative integers return **everything but** the elements at the specified locations. # You cannot use both negative and positive integers in the same dimension # Exclude rows 2 to 4 and select columns 2 to 3. df[-c(2:4), 2:3] # Exclude rows 2 to 4 and select columns 2 to 3. df[-c(2:4), 2:3] #### 2. Blank Spaces #### # Blank spaces return **everything** # (i.e., no subsetting occurs on that dimension) vec <- c(6,1,3,6,10,5) vec[] # Return every element on row 1 df[1,] # Return every element on column 2 df[,2] #### 3. Names #### # If your object has names, you can ask for elements or columns back by name. (We talked about this in the first session) names(vec) <- c("a","b","c","d","e","f") vec # Now I can call elements in `vec` by their names vec[c("a","b","d")] # Same applies to columns and column names df[ ,"birth"] df[ ,c("name","birth")] #### 4. Logical #### # You can subset with a logical vector of the **same length as the dimension** you are subsetting. Each element that corresponds to a TRUE will be returned. # The following will return 2nd, 4th and 5th elements in `vec` vec[c(FALSE,TRUE,FALSE,TRUE,TRUE,FALSE)] # The following will return **2nd, 3rd rows** in `df` df[c(FALSE,TRUE,TRUE,FALSE), ] #### Subsetting Lists #### # Subsetting lists can get tricky, since a list can contain objects that has one or more dimensions. lst <- list(c(1,2), TRUE, c("a", "b", "c")) lst # What is the difference? lst[c(1,2)] # outputs a list with 2 objects lst[1] # outputs a list with 1 object lst[[1]] # outputs a vector ### Easiest way to subset data frames and lists: `$` sign # The most common syntax for subsetting lists and data frames: # When we have a names list such as names(lst) <- c("alpha", "beta", "gamma") lst # then we can subset objects with `$` lst$alpha lst$beta lst$gamma # It also works to subset columns of a data frame df$birth #### R Packages #### install.packages(c("ggplot2", "maps", "RColorBrewer")) library("ggplot2") library("maps") library("RColorBrewer") #### Diamonds #### diamonds <- data.frame(diamonds) # first 6 rows diamonds[1:6,] # last 6 rows dim(diamonds) ncol(diamonds) # number of columns #one way nrow(diamonds) # number of rows nrow(diamonds) - 6 diamonds[53934:53940,] # another way diamonds[(nrow(diamonds)-6):nrow(diamonds),] diamonds[-( 1: (nrow(diamonds)-6) ), ] # easiest way to check the first and last 5 rows head(diamonds, 20) tail(diamonds) # view data View(diamonds) # notice: Capital V ## Help pages ## # You can open the help page for any R object (including functions) by typing `?` # followed by the object's name ?diamonds #### Logical tests #### #### Logical comparisons #### # What will these return? 1< 3 1> 3 c(1, 2, 3, 4, 5) > 3 #### %in% #### # What does this do? 1 %in% c(1, 2, 3, 4) 1 %in% c(2, 3, 4) c(3,4,5,6) %in% c(2, 3, 4) #### Boolean operators #### ?Logic x <- 4 # & -- and x > 2 & x < 9 x > 5 & x < 9 x > 5 & x < 2 TRUE & TRUE TRUE & TRUE & TRUE & TRUE TRUE & TRUE & FALSE & TRUE # | -- or TRUE | TRUE TRUE | FALSE FALSE | FALSE x > 2 | x < 9 x > 5 | x < 9 x > 5 | x < 2 # xor -- Is either condition 1 or condition 2 true, but not both? xor(TRUE, TRUE) xor(TRUE, FALSE) xor(FALSE, TRUE) xor(FALSE, FALSE) xor(x > 2, x < 9) xor(x > 5, x < 9) xor(x > 5, x < 2) # ! -- Negation !c(TRUE, TRUE) !c(TRUE, FALSE) !c(FALSE, FALSE) !(x > 2, x < 9) !(x > 5, x < 9) !(x > 5, x < 2) # any -- is any condition true? any(c(TRUE, FALSE, FALSE)) any(c(FALSE, FALSE, FALSE)) any(x > 5, x < 2) any(x > 2, x < 9) # all -- is every condition TRUE? all(c(TRUE, TRUE, TRUE)) all(c(TRUE, FALSE, TRUE)) all(x > 5, x < 2) all(x > 2, x < 9) #### Your turn #### w <- c(-1, 0, 1) x <- c(5, 15) y <- "February" z <- c("Monday", "Tuesday", "Friday") # Is w positive? # Is x greater than 10 and less than 20? Is object y the word February? # Is every value in z a day of the week? ## Answers # Is w positive? w> 0 # Is x greater than 10 and less than 20? 10 < x & x < 20 #Is object y the word February? y == "February" # Is every value in z a day of the week? all(z %in% c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")) # Common mistakes x > 10 & < 20 y = "February" all(z == "Monday" | "Tuesday" | "Wednesday"...) #### Logical subsetting ##### x_zeroes <- diamonds$x == 0 head(x_zeroes) # What will this return? diamonds[x_zeroes, ] #### Saving results #### # Prints to screen diamonds[diamonds$x > 10, ] # Saves to new data frame big <- diamonds[diamonds$x > 10, ] # Overwrites existing data frame. Dangerous! diamonds <- diamonds[diamonds$x < 10,] diamonds <- diamonds[1, 1] diamonds # Uh oh! rm(diamonds) diamonds <- data.frame(diamonds) # Phew! #### NA behavior #### a <- c(1, NA) a == NA is.na(a) b <- c(1, 2, 3, 4, NA) sum(b) sum(b, na.rm = TRUE) #### NA Assignment #### # Before removing outliers qplot(x, y, data = diamonds) ## Let's remove outliers ## ?diamonds # Let's start with x summary(diamonds$x) # there are 0s in x #but x is supposed to be the lenght of the diamond, it can't be 0, a diamond is a 3d object in real life diamonds$x[diamonds$x == 0] # we can assign NA to 0s to let qplot know that these are missing values diamonds$x[diamonds$x == 0] <- NA # now 0s gone from the Min. and we have NA's summary(diamonds$x) # Now let's do y summary(diamonds$y) # we can assign NA to 0s to let qplot know that these are missing values diamonds$y[diamonds$y == 0] <- NA # very big diamonds y_big <- diamonds$y > 20 diamonds$y[y_big] <- NA # outliers are assigned as NA! summary(diamonds$y) # let's look at our plot again qplot(x, y, data = diamonds)
################################################################################ ## ## R package clusrank by Mei-Ling Ting Lee, Jun Yan, and Yujing Jiang ## Copyright (C) 2015 ## ## This file is part of the R package clusrank. ## ## The R package clusrank is free software: you can redistribute it and/or ## modify it under the terms of the GNU General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## The R package clusrank is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with the R package reda. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################ #' The Wilcoxon Signed Rank Test for Clustered Data #' #' Performs one-sample Wilcoxon test on vectors of data using #' large sample. #' #' @note This function is able to deal with data with #' clusterentitical or variable cluster size. When the data #' is unbalanced, adjusted signed rank statistic is used. #' Ties are dropped in the test. #' @examples #' data(crsd) #' cluswilcox.test(z, cluster = id, data = crsd) #' data(crsdUnb) #' cluswilcox.test(z, cluster = id, data = crsdUnb) #' @author Yujing Jiang #' @references #' Bernard Rosner, Robert J. Glynn, Mei-Ling Ting Lee(2006) #' \emph{The Wilcoxon Signed Rank Test for Paired Comparisons of #' Clustered Data.} Biometrics, \bold{62}, 185-192. #' @describeIn cluswilcox.test numeric interface for signed rank test. #' @importFrom stats complete.cases #' @export cluswilcox.test.numeric <- function(x, y = NULL, cluster = NULL, data = parent.frame(), alternative = c("two.sided", "less", "greater"), mu = 0, permutation = FALSE, n.rep = 500, ...) { ## Process the input arguments before feeding them to ## signed rank test . Assign a class (better to ## be S4) to the processed arguments for them to be ## sent to the corresponding functions. ## ## Inputs: ## The same as cluswilcox.test. ## x: numeric vector of data values. Non-finite ## (e.g., infinite or missing) values will be omitted. ## ## ## y: an optional numeric vector of data values: ## as with x non-finite values will be omitted. ## ## ## cluster: an integer vector. Cluster cluster.If not provclustered, ## assume there is no cluster. ## ## data: an optional matrix or data frame ## (or similar: see model.frame) containing the variables. ## By default the variables are taken from environment(formula). ## ## ## alternative: a character string specifying the ## alternative hypothesis, must be one of ## "two.sclustered" (default), "greater" or "less". ## You can specify just the initial letter. ## ## mu: a number specifying an optional parameter ## used to form the null hypothesis. ## ## paired: a logical indicating whether you want a paired test. ## ## permuation: METHOD <- "Wilcoxon signed rank test for clutered data" pars <- as.list(match.call()[-1]) ## If data name existed, take out the x (and y) observations, ## group cluster, cluster cluster, stratum cluster, otherwise, no need to ## take values from a data frame. if(!is.null(pars$data)) { x <- data[, as.character(pars$x)] DNAME <- (pars$x) if(!is.null(pars$y)) { y <- data[, as.character(pars$y)] DNAME <- paste(DNAME, "and", pars$y) } else { y <- NULL } if(!is.null(pars$cluster)) { cluster <- data[, as.character(pars$cluster)] DNAME <- paste0(DNAME, ", cluster: ", pars$cluster) } else { cluster <- NULL } DNAME <- paste0(DNAME, " from ", pars$data) } else { DNAME <- deparse(substitute(x)) if(!is.null(y)) { DNAME <- paste(DNAME, "and", deparse(substitute(y))) } if(!is.null(cluster)) { DNAME <- paste0(DNAME, ", cluster id: ", deparse(substitute(cluster))) } } ## Check and initialize cluster if not given, ## transform it to numeric if given as characters. l.x <- length(x) if( is.null(cluster)) { cluster <- c(1 : l.x) } else { if(!is.numeric(cluster)) { if(!is.character(cluster)) { stop("'cluster' has to be numeric or characters") } if(length(cluster) != l.x) { stop("'cluster' and 'x' must have the same lengths") } uniq.cluster <- unique(cluster) l.uniq.cluster <- length(uniq.cluster) cluster <- as.numeric(recoderFunc(cluster, uniq.cluster, c(1 : l.uniq.cluster))) } } ## Check x. if ( !is.numeric(x)) stop("'x' must be numeric") ## Check data for paired test, paired test ## do not deal with stratified data. if( !is.null(y)) { if (!is.numeric(y)) stop("'y' must be numeric") l.y <- length(y) if( l.y != l.x) { stop("'x' and 'y' must have the same lengths for signed rank test.") } OK <- complete.cases(x, y, cluster) x <- x[OK] - y[OK] - mu cluster <- cluster[OK] finite.x <- is.finite(x) x <- x[finite.x] cluster <- cluster[finite.x] if(length(x) < 1L) { stop("not enough (finite) 'x' observations") } } else { ## If only x is given, it is the difference score. OK <- complete.cases(x, cluster) x <- x[OK] cluster <- cluster[OK] finite.x <- is.finite(x) x <- x[finite.x] - mu cluster <- cluster[finite.x] if(length(x) < 1L) { stop("not enough (finite) 'x' observations") } } alternative <- match.arg(alternative) if(!missing(mu) && ((length(mu) > 1L) || !is.finite(mu))) { stop("'mu' must be a single number") } if(permutation == FALSE) { return(cluswilcox.test.signedrank(x, cluster, alternative, mu, DNAME, METHOD)) } else { METHOD <- paste(METHOD, "using permutation") return(cluswilcox.test.signedrank.permutation(x, cluster, alternative, mu, n.rep, DNAME, METHOD)) } }
/clusrank/R/clusnumeric.R
no_license
ingted/R-Examples
R
false
false
6,530
r
################################################################################ ## ## R package clusrank by Mei-Ling Ting Lee, Jun Yan, and Yujing Jiang ## Copyright (C) 2015 ## ## This file is part of the R package clusrank. ## ## The R package clusrank is free software: you can redistribute it and/or ## modify it under the terms of the GNU General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## The R package clusrank is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with the R package reda. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################ #' The Wilcoxon Signed Rank Test for Clustered Data #' #' Performs one-sample Wilcoxon test on vectors of data using #' large sample. #' #' @note This function is able to deal with data with #' clusterentitical or variable cluster size. When the data #' is unbalanced, adjusted signed rank statistic is used. #' Ties are dropped in the test. #' @examples #' data(crsd) #' cluswilcox.test(z, cluster = id, data = crsd) #' data(crsdUnb) #' cluswilcox.test(z, cluster = id, data = crsdUnb) #' @author Yujing Jiang #' @references #' Bernard Rosner, Robert J. Glynn, Mei-Ling Ting Lee(2006) #' \emph{The Wilcoxon Signed Rank Test for Paired Comparisons of #' Clustered Data.} Biometrics, \bold{62}, 185-192. #' @describeIn cluswilcox.test numeric interface for signed rank test. #' @importFrom stats complete.cases #' @export cluswilcox.test.numeric <- function(x, y = NULL, cluster = NULL, data = parent.frame(), alternative = c("two.sided", "less", "greater"), mu = 0, permutation = FALSE, n.rep = 500, ...) { ## Process the input arguments before feeding them to ## signed rank test . Assign a class (better to ## be S4) to the processed arguments for them to be ## sent to the corresponding functions. ## ## Inputs: ## The same as cluswilcox.test. ## x: numeric vector of data values. Non-finite ## (e.g., infinite or missing) values will be omitted. ## ## ## y: an optional numeric vector of data values: ## as with x non-finite values will be omitted. ## ## ## cluster: an integer vector. Cluster cluster.If not provclustered, ## assume there is no cluster. ## ## data: an optional matrix or data frame ## (or similar: see model.frame) containing the variables. ## By default the variables are taken from environment(formula). ## ## ## alternative: a character string specifying the ## alternative hypothesis, must be one of ## "two.sclustered" (default), "greater" or "less". ## You can specify just the initial letter. ## ## mu: a number specifying an optional parameter ## used to form the null hypothesis. ## ## paired: a logical indicating whether you want a paired test. ## ## permuation: METHOD <- "Wilcoxon signed rank test for clutered data" pars <- as.list(match.call()[-1]) ## If data name existed, take out the x (and y) observations, ## group cluster, cluster cluster, stratum cluster, otherwise, no need to ## take values from a data frame. if(!is.null(pars$data)) { x <- data[, as.character(pars$x)] DNAME <- (pars$x) if(!is.null(pars$y)) { y <- data[, as.character(pars$y)] DNAME <- paste(DNAME, "and", pars$y) } else { y <- NULL } if(!is.null(pars$cluster)) { cluster <- data[, as.character(pars$cluster)] DNAME <- paste0(DNAME, ", cluster: ", pars$cluster) } else { cluster <- NULL } DNAME <- paste0(DNAME, " from ", pars$data) } else { DNAME <- deparse(substitute(x)) if(!is.null(y)) { DNAME <- paste(DNAME, "and", deparse(substitute(y))) } if(!is.null(cluster)) { DNAME <- paste0(DNAME, ", cluster id: ", deparse(substitute(cluster))) } } ## Check and initialize cluster if not given, ## transform it to numeric if given as characters. l.x <- length(x) if( is.null(cluster)) { cluster <- c(1 : l.x) } else { if(!is.numeric(cluster)) { if(!is.character(cluster)) { stop("'cluster' has to be numeric or characters") } if(length(cluster) != l.x) { stop("'cluster' and 'x' must have the same lengths") } uniq.cluster <- unique(cluster) l.uniq.cluster <- length(uniq.cluster) cluster <- as.numeric(recoderFunc(cluster, uniq.cluster, c(1 : l.uniq.cluster))) } } ## Check x. if ( !is.numeric(x)) stop("'x' must be numeric") ## Check data for paired test, paired test ## do not deal with stratified data. if( !is.null(y)) { if (!is.numeric(y)) stop("'y' must be numeric") l.y <- length(y) if( l.y != l.x) { stop("'x' and 'y' must have the same lengths for signed rank test.") } OK <- complete.cases(x, y, cluster) x <- x[OK] - y[OK] - mu cluster <- cluster[OK] finite.x <- is.finite(x) x <- x[finite.x] cluster <- cluster[finite.x] if(length(x) < 1L) { stop("not enough (finite) 'x' observations") } } else { ## If only x is given, it is the difference score. OK <- complete.cases(x, cluster) x <- x[OK] cluster <- cluster[OK] finite.x <- is.finite(x) x <- x[finite.x] - mu cluster <- cluster[finite.x] if(length(x) < 1L) { stop("not enough (finite) 'x' observations") } } alternative <- match.arg(alternative) if(!missing(mu) && ((length(mu) > 1L) || !is.finite(mu))) { stop("'mu' must be a single number") } if(permutation == FALSE) { return(cluswilcox.test.signedrank(x, cluster, alternative, mu, DNAME, METHOD)) } else { METHOD <- paste(METHOD, "using permutation") return(cluswilcox.test.signedrank.permutation(x, cluster, alternative, mu, n.rep, DNAME, METHOD)) } }
library(ggplot2) library(reshape2) library(BEST) ## Read our datasets areas_wide <- read.csv("./results/buffer_areas.csv") symdiffs_wide <- read.csv("./results/buffer_symdiffs.csv") ## Convert to tidy/long format and ft^2 -> km^2 ft2tokm2 <- function(x) x * 9.2903e-8 areas <- melt(areas_wide, value.name="sqft", variable.name="type", id.vars=c("id")) areas$km2 <- ft2tokm2(areas$sqft) symdiffs <- melt(symdiffs_wide, value.name="sqft", variable.name="type", id.vars=c("id")) symdiffs$km2 <- ft2tokm2(symdiffs$sqft) ## Descriptive density plots of areas and symmetric differences area_dens <- ggplot(areas, aes(x=km2, color=type, linetype=type)) + scale_color_brewer(type="qual", palette=2) + geom_density() + theme_bw() ggsave("./results/area_dens.pdf", width=5, height=2.5) symdiff_dens <- ggplot(symdiffs, aes(x=km2)) + geom_density() + theme_bw() ggsave("./results/symdiff_dens.pdf", width=5, height=2.5) ## Statistically compare areas of pg buffers and esri round ended ## buffers using BEST best_areas_pg_esr <- BESTmcmc(y1=ft2tokm2(areas_wide$postgis), y2=ft2tokm2(areas_wide$esri)) ## Power analysis, takes quite a while to run ## bpwr_areas_pg_esr <- BESTpower(best_areas_pg_esr, ## N1=length(areas_wide$postgis), ## N2=length(areas_wide$esri_round), ## ROPEm=c(-0.0314,0.0314), ## maxHDIWm=1.0, nRep=1000) ## Plots from BEST pdf("./results/best_areas_pg_esr_mean.pdf", width=8, height=4) plot(best_areas_pg_esr, "mean") dev.off() pdf("./results/best_areas_pg_esr_sd.pdf", width=8, height=4) plot(best_areas_pg_esr, "sd") dev.off() pdf("./results/best_areas_pg_esr_effect.pdf", width=8, height=4) plot(best_areas_pg_esr, "effect") dev.off() pdf("./results/best_areas_pg_esr_nu.pdf", width=8, height=4) plot(best_areas_pg_esr, "nu") dev.off() pdf("./results/best_areas_pg_esr.pdf", width=8.5, height=11) plotAll(best_areas_pg_esr) dev.off()
/analysis/055-compare-buffers.R
permissive
pschmied/pgismethods
R
false
false
2,024
r
library(ggplot2) library(reshape2) library(BEST) ## Read our datasets areas_wide <- read.csv("./results/buffer_areas.csv") symdiffs_wide <- read.csv("./results/buffer_symdiffs.csv") ## Convert to tidy/long format and ft^2 -> km^2 ft2tokm2 <- function(x) x * 9.2903e-8 areas <- melt(areas_wide, value.name="sqft", variable.name="type", id.vars=c("id")) areas$km2 <- ft2tokm2(areas$sqft) symdiffs <- melt(symdiffs_wide, value.name="sqft", variable.name="type", id.vars=c("id")) symdiffs$km2 <- ft2tokm2(symdiffs$sqft) ## Descriptive density plots of areas and symmetric differences area_dens <- ggplot(areas, aes(x=km2, color=type, linetype=type)) + scale_color_brewer(type="qual", palette=2) + geom_density() + theme_bw() ggsave("./results/area_dens.pdf", width=5, height=2.5) symdiff_dens <- ggplot(symdiffs, aes(x=km2)) + geom_density() + theme_bw() ggsave("./results/symdiff_dens.pdf", width=5, height=2.5) ## Statistically compare areas of pg buffers and esri round ended ## buffers using BEST best_areas_pg_esr <- BESTmcmc(y1=ft2tokm2(areas_wide$postgis), y2=ft2tokm2(areas_wide$esri)) ## Power analysis, takes quite a while to run ## bpwr_areas_pg_esr <- BESTpower(best_areas_pg_esr, ## N1=length(areas_wide$postgis), ## N2=length(areas_wide$esri_round), ## ROPEm=c(-0.0314,0.0314), ## maxHDIWm=1.0, nRep=1000) ## Plots from BEST pdf("./results/best_areas_pg_esr_mean.pdf", width=8, height=4) plot(best_areas_pg_esr, "mean") dev.off() pdf("./results/best_areas_pg_esr_sd.pdf", width=8, height=4) plot(best_areas_pg_esr, "sd") dev.off() pdf("./results/best_areas_pg_esr_effect.pdf", width=8, height=4) plot(best_areas_pg_esr, "effect") dev.off() pdf("./results/best_areas_pg_esr_nu.pdf", width=8, height=4) plot(best_areas_pg_esr, "nu") dev.off() pdf("./results/best_areas_pg_esr.pdf", width=8.5, height=11) plotAll(best_areas_pg_esr) dev.off()
rm(list = ls()); gc() # get args args = commandArgs(TRUE) batch_no = as.double(args[1]) simulations = as.integer(args[2]) library(extdepth) source('/home/trevorh2/assimilation-cfr/code/ks_field_functions.R') source('/home/trevorh2/assimilation-cfr/code/sim_functions.R') # marginal number of points in the field (field is pts x pts) pts = 40 # number of regions to subdivide the fields into regions = 64 # number of time points time_points = 10 # standard flat prior mean prior_mu = matrix(0, pts, pts) post_mu = readRDS("post_mu.rds") prior_mu = as.vector(prior_mu) post_mu = as.vector(post_mu) cat("#### Starting Simulation \n") upper_de = matrix(0, regions*time_points, simulations) upper_bf = matrix(0, regions*time_points, simulations) upper_pw = matrix(0, regions*time_points, simulations) ks_value = matrix(0, regions*time_points, simulations) pval_de = rep(0, simulations) for (i in 1:simulations) { t0 = Sys.time() kst = rep(0, regions*time_points) ksp = matrix(0, regions*time_points, 1000) for (t in 1:time_points) { prior = sim_gp(100, mu = prior_mu, l = 5, pts = pts) post = sim_gp(100, mu = post_mu, l = 5, pts = pts) # split em all prior.split = vapply(1:100, function(x) matsplitter(prior[,,x], 5, 5), FUN.VALUE = array(0, dim = c(5, 5, regions))) post.split = vapply(1:100, function(x) matsplitter(post[,,x], 5, 5), FUN.VALUE = array(0, dim = c(5, 5, regions))) # find the observed kst field kst[1:regions + regions*(t - 1)] = kst.field(prior.split, post.split, 100) ksp[1:regions + regions*(t - 1),] = kst.permute(prior.split, post.split, 1000, 1) } # Bonferroni central regions bf_val = (1-(0.05/(regions*time_points))) # Depth central regions perm.ed = edepth_set(ksp, depth_function = "rank") perm.cr = central_region(ksp, perm.ed) kst.ed = edepth(kst, ksp, depth_function = "rank") # Upper regions upper_bf[,i] = sapply(1:length(kst), function(r) quantile(ksp[r,], bf_val)) upper_pw[,i] = sapply(1:length(kst), function(r) quantile(ksp[r,], 0.95)) upper_de[,i] = perm.cr[[2]] # save ks values ks_value[,i] = kst # save ks p values pval_de[i] = kst.ed cat(paste0("sim ", i, "\t", Sys.time()-t0, "\n")) }
/Archive/code/sim/power_time.R
no_license
trevor-harris/assimilation-cfr
R
false
false
2,309
r
rm(list = ls()); gc() # get args args = commandArgs(TRUE) batch_no = as.double(args[1]) simulations = as.integer(args[2]) library(extdepth) source('/home/trevorh2/assimilation-cfr/code/ks_field_functions.R') source('/home/trevorh2/assimilation-cfr/code/sim_functions.R') # marginal number of points in the field (field is pts x pts) pts = 40 # number of regions to subdivide the fields into regions = 64 # number of time points time_points = 10 # standard flat prior mean prior_mu = matrix(0, pts, pts) post_mu = readRDS("post_mu.rds") prior_mu = as.vector(prior_mu) post_mu = as.vector(post_mu) cat("#### Starting Simulation \n") upper_de = matrix(0, regions*time_points, simulations) upper_bf = matrix(0, regions*time_points, simulations) upper_pw = matrix(0, regions*time_points, simulations) ks_value = matrix(0, regions*time_points, simulations) pval_de = rep(0, simulations) for (i in 1:simulations) { t0 = Sys.time() kst = rep(0, regions*time_points) ksp = matrix(0, regions*time_points, 1000) for (t in 1:time_points) { prior = sim_gp(100, mu = prior_mu, l = 5, pts = pts) post = sim_gp(100, mu = post_mu, l = 5, pts = pts) # split em all prior.split = vapply(1:100, function(x) matsplitter(prior[,,x], 5, 5), FUN.VALUE = array(0, dim = c(5, 5, regions))) post.split = vapply(1:100, function(x) matsplitter(post[,,x], 5, 5), FUN.VALUE = array(0, dim = c(5, 5, regions))) # find the observed kst field kst[1:regions + regions*(t - 1)] = kst.field(prior.split, post.split, 100) ksp[1:regions + regions*(t - 1),] = kst.permute(prior.split, post.split, 1000, 1) } # Bonferroni central regions bf_val = (1-(0.05/(regions*time_points))) # Depth central regions perm.ed = edepth_set(ksp, depth_function = "rank") perm.cr = central_region(ksp, perm.ed) kst.ed = edepth(kst, ksp, depth_function = "rank") # Upper regions upper_bf[,i] = sapply(1:length(kst), function(r) quantile(ksp[r,], bf_val)) upper_pw[,i] = sapply(1:length(kst), function(r) quantile(ksp[r,], 0.95)) upper_de[,i] = perm.cr[[2]] # save ks values ks_value[,i] = kst # save ks p values pval_de[i] = kst.ed cat(paste0("sim ", i, "\t", Sys.time()-t0, "\n")) }
context("AMQP Connection") test_that("rabbitr succesfully stablishes connection with RabbitMQ", { skip_if_no_rabbitmq() conn <- rabbitr() })
/tests/testthat/test_connection.R
no_license
lecardozo/rabbitr
R
false
false
150
r
context("AMQP Connection") test_that("rabbitr succesfully stablishes connection with RabbitMQ", { skip_if_no_rabbitmq() conn <- rabbitr() })
#' Prepare inputs for TMB model. #' #' @param naomi_data Naomi data object #' @param report_likelihood Option to report likelihood in fit object (default true). #' @param anchor_home_district Option to include random effect home district attractiveness to retain residents on ART within home districts (default true). #' #' @return Inputs ready for TMB model #' #' @seealso [select_naomi_data] #' @export prepare_tmb_inputs <- function(naomi_data, report_likelihood = 1L) { stopifnot(is(naomi_data, "naomi_data")) stopifnot(is(naomi_data, "naomi_mf")) ## ANC observation aggregation matrices ## ## TODO: Refactor code to make the function create_artattend_Amat() more generic. ## Should not refer to 'ART' specific; also useful for ANC attendance, ## fertility, etc. create_anc_Amat <- function(anc_obs_dat) { df_attend_anc <- naomi_data$mf_model %>% dplyr::select(reside_area_id = area_id, attend_area_id = area_id, sex, age_group, idx) dat <- dplyr::rename(anc_obs_dat, attend_area_id = area_id) Amat <- create_artattend_Amat( dat, age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_attend_anc, by_residence = FALSE ) Amat } create_survey_Amat <- function(survey_dat) { df_attend_survey <- naomi_data$mf_model %>% dplyr::select(reside_area_id = area_id, attend_area_id = area_id, sex, age_group, idx) survey_dat$attend_area_id <- survey_dat$area_id Amat <- create_artattend_Amat( survey_dat, age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_attend_survey, by_residence = FALSE, by_survey = TRUE ) Amat } A_anc_clients_t2 <- create_anc_Amat(naomi_data$anc_clients_t2_dat) A_anc_prev_t1 <- create_anc_Amat(naomi_data$anc_prev_t1_dat) A_anc_prev_t2 <- create_anc_Amat(naomi_data$anc_prev_t2_dat) A_anc_artcov_t1 <- create_anc_Amat(naomi_data$anc_artcov_t1_dat) A_anc_artcov_t2 <- create_anc_Amat(naomi_data$anc_artcov_t2_dat) A_prev <- create_survey_Amat(naomi_data$prev_dat) A_artcov <- create_survey_Amat(naomi_data$artcov_dat) A_vls <- create_survey_Amat(naomi_data$vls_dat) A_recent <- create_survey_Amat(naomi_data$recent_dat) ## ART attendance aggregation # Default model for ART attending: Anchor home district = add random effect for home district if(naomi_data$model_options$anchor_home_district) { Xgamma <- naomi:::sparse_model_matrix(~0 + attend_area_idf, naomi_data$mf_artattend) } else { Xgamma <- sparse_model_matrix(~0 + attend_area_idf:as.integer(jstar != 1), naomi_data$mf_artattend) } if(naomi_data$artattend_t2) { Xgamma_t2 <- Xgamma } else { Xgamma_t2 <- sparse_model_matrix(~0, naomi_data$mf_artattend) } df_art_attend <- naomi_data$mf_model %>% dplyr::rename(reside_area_id = area_id) %>% dplyr::left_join(naomi_data$mf_artattend, by = "reside_area_id", multiple = "all") %>% dplyr::mutate(attend_idf = forcats::as_factor(attend_idx), idf = forcats::as_factor(idx)) Xart_gamma <- sparse_model_matrix(~0 + attend_idf, df_art_attend) Xart_idx <- sparse_model_matrix(~0 + idf, df_art_attend) A_artattend_t1 <- create_artattend_Amat(artnum_df = dplyr::rename(naomi_data$artnum_t1_dat, attend_area_id = area_id), age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = FALSE) A_artattend_t2 <- create_artattend_Amat(artnum_df = dplyr::rename(naomi_data$artnum_t2_dat, attend_area_id = area_id), age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = FALSE) A_artattend_mf <- create_artattend_Amat(artnum_df = dplyr::select(naomi_data$mf_model, attend_area_id = area_id, sex, age_group, artnum_idx = idx), age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = FALSE) A_art_reside_attend <- naomi_data$mf_artattend %>% dplyr::transmute( reside_area_id, attend_area_id, sex = "both", age_group = "Y000_999" ) %>% create_artattend_Amat(age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = TRUE) ## Construct TMB data and initial parameter vectors df <- naomi_data$mf_model X_15to49 <- Matrix::t(sparse_model_matrix(~-1 + area_idf:age15to49, naomi_data$mf_model)) ## Paediatric prevalence from 15-49 female ratio X_15to49f <- Matrix::t(Matrix::sparse.model.matrix(~0 + area_idf:age15to49:as.integer(sex == "female"), df)) df$bin_paed_rho_model <- 1 - df$bin_rho_model X_paed_rho_ratio <- sparse_model_matrix(~-1 + area_idf:paed_rho_ratio:bin_paed_rho_model, df) paed_rho_ratio_offset <- 0.5 * df$bin_rho_model X_paed_lambda_ratio_t1 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t1, df) X_paed_lambda_ratio_t2 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t2, df) X_paed_lambda_ratio_t3 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t3, df) X_paed_lambda_ratio_t4 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t4, df) X_paed_lambda_ratio_t5 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t5, df) f_rho_a <- if(all(is.na(df$rho_a_fct))) ~0 else ~0 + rho_a_fct f_alpha_a <- if(all(is.na(df$alpha_a_fct))) ~0 else ~0 + alpha_a_fct if (naomi_data$rho_paed_x_term) { f_rho_xa <- ~0 + area_idf } else { f_rho_xa <- ~0 } ## Ratio of paediatric incidence rate to 15-49 female prevalence ## If no sex stratified prevalence data, don't estimate spatial variation in ## sex odds ratio if ( ! all(c("male", "female") %in% naomi_data$prev_dat$sex)) { f_rho_xs <- ~0 } else { f_rho_xs <- ~0 + area_idf } ## If no sex stratified ART coverage data, don't estimate spatial variation in ## sex odds ratio if ( ! all(c("male", "female") %in% naomi_data$artcov_dat$sex) && ! all(c("male", "female") %in% naomi_data$artnum_t1_dat$sex) && ! all(c("male", "female") %in% naomi_data$artnum_t2_dat$sex) ) { f_alpha_xs <- ~0 } else { f_alpha_xs <- ~0 + area_idf } ## If flag **and** has ART by sex data at both times, estimate time x district x ## sex ART odds ratio. if (naomi_data$alpha_xst_term) { if (!all(c("male", "female") %in% naomi_data$artnum_t1_dat$sex) && !all(c("male", "female") %in% naomi_data$artnum_t2_dat$sex)) { stop(paste("Sex-stratified ART data are required at both Time 1 and Time 2", "to estimate district x sex x time interaction for ART coverage")) } f_alpha_xst <- ~0 + area_idf } else { f_alpha_xst <- ~0 } ## If no ART data at both time points, do not fit a change in ART coverage. Use ## logit difference in ART coverage from Spectrum. ## T1 ART data may be either survey or programme ## has_t1_art <- nrow(naomi_data$artcov_dat) > 0 | nrow(naomi_data$artnum_t1_dat) > 0 has_t2_art <- nrow(naomi_data$artnum_t2_dat) > 0 if( !has_t1_art | !has_t2_art ) { f_alpha_t2 <- ~0 f_alpha_xt <- ~0 logit_alpha_t1t2_offset <- naomi_data$mf_model$logit_alpha_t1t2_offset } else { f_alpha_t2 <- ~1 f_alpha_xt <- ~0 + area_idf logit_alpha_t1t2_offset <- numeric(nrow(naomi_data$mf_model)) } ## Paediatric ART coverage random effects artnum_t1_dat <- naomi_data$artnum_t1_dat %>% dplyr::left_join(get_age_groups(), by = "age_group") %>% dplyr::mutate(age_group_end = age_group_start + age_group_span - 1) artnum_t2_dat <- naomi_data$artnum_t2_dat %>% dplyr::left_join(get_age_groups(), by = "age_group") %>% dplyr::mutate(age_group_end = age_group_start + age_group_span - 1) has_t1_paed_art <- any(artnum_t1_dat$age_group_end < 15) has_t2_paed_art <- any(artnum_t2_dat$age_group_end < 15) if(has_t1_paed_art | has_t2_paed_art) { f_alpha_xa <- ~0 + area_idf } else { f_alpha_xa <- ~0 } if(has_t1_paed_art & has_t2_paed_art) { f_alpha_t2 <- ~1 + age_below15 f_alpha_xat <- ~0 + area_idf } else { f_alpha_xat <- ~0 } ## If no recent infection data, do not estimate incidence sex ratio or ## district random effects if(nrow(naomi_data$recent_dat) == 0) { f_lambda <- ~0 f_lambda_x <- ~0 } else { f_lambda <- ~ 1 + female_15plus f_lambda_x <- ~0 + area_idf } dtmb <- list( population_t1 = df$population_t1, population_t2 = df$population_t2, Lproj_hivpop_t1t2 = naomi_data$Lproj_t1t2$Lproj_hivpop, Lproj_incid_t1t2 = naomi_data$Lproj_t1t2$Lproj_incid, Lproj_paed_t1t2 = naomi_data$Lproj_t1t2$Lproj_paed, X_rho = as.matrix(sparse_model_matrix(~female_15plus, df, "bin_rho_model", TRUE)), X_alpha = stats::model.matrix(~female_15plus, df), X_alpha_t2 = stats::model.matrix(f_alpha_t2, df), X_lambda = stats::model.matrix(f_lambda, df), X_asfr = stats::model.matrix(~1, df), X_ancrho = stats::model.matrix(~1, df), X_ancalpha = stats::model.matrix(~1, df), Z_x = sparse_model_matrix(~0 + area_idf, df), Z_rho_x = sparse_model_matrix(~0 + area_idf, df, "bin_rho_model", TRUE), Z_rho_xs = sparse_model_matrix(f_rho_xs, df, "female_15plus", TRUE), Z_rho_a = sparse_model_matrix(f_rho_a, df, "bin_rho_model", TRUE), Z_rho_as = sparse_model_matrix(f_rho_a, df, "female_15plus", TRUE), Z_rho_xa = sparse_model_matrix(f_rho_xa, df, "age_below15"), Z_alpha_x = sparse_model_matrix(~0 + area_idf, df), Z_alpha_xs = sparse_model_matrix(f_alpha_xs, df, "female_15plus", TRUE), Z_alpha_a = sparse_model_matrix(f_alpha_a, df), Z_alpha_as = sparse_model_matrix(f_alpha_a, df, "female_15plus", TRUE), Z_alpha_xt = sparse_model_matrix(f_alpha_xt, df), Z_alpha_xa = sparse_model_matrix(f_alpha_xa, df, "age_below15"), Z_alpha_xat = sparse_model_matrix(f_alpha_xat, df, "age_below15"), Z_alpha_xst = sparse_model_matrix(f_alpha_xst, df, "female_15plus", TRUE), Z_lambda_x = sparse_model_matrix(f_lambda_x, df), ## Z_xa = Matrix::sparse.model.matrix(~0 + area_idf:age_group_idf, df), Z_asfr_x = sparse_model_matrix(~0 + area_idf, df), Z_ancrho_x = sparse_model_matrix(~0 + area_idf, df), Z_ancalpha_x = sparse_model_matrix(~0 + area_idf, df), log_asfr_t1_offset = log(df$asfr_t1), log_asfr_t2_offset = log(df$asfr_t2), log_asfr_t3_offset = log(df$asfr_t3), logit_anc_rho_t1_offset = log(df$frr_plhiv_t1), logit_anc_rho_t2_offset = log(df$frr_plhiv_t2), logit_anc_rho_t3_offset = log(df$frr_plhiv_t3), logit_anc_alpha_t1_offset = log(df$frr_already_art_t1), logit_anc_alpha_t2_offset = log(df$frr_already_art_t2), logit_anc_alpha_t3_offset = log(df$frr_already_art_t3), ## logit_rho_offset = naomi_data$mf_model$logit_rho_offset * naomi_data$mf_model$bin_rho_model, logit_alpha_offset = naomi_data$mf_model$logit_alpha_offset, logit_alpha_t1t2_offset = logit_alpha_t1t2_offset, ## unaware_untreated_prop_t1 = df$spec_unaware_untreated_prop_t1, unaware_untreated_prop_t2 = df$spec_unaware_untreated_prop_t2, unaware_untreated_prop_t3 = df$spec_unaware_untreated_prop_t3, ## Q_x = methods::as(naomi_data$Q, "dgCMatrix"), Q_x_rankdef = ncol(naomi_data$Q) - as.integer(Matrix::rankMatrix(naomi_data$Q)), n_nb = naomi_data$mf_areas$n_neighbors, adj_i = naomi_data$mf_artattend$reside_area_idx - 1L, adj_j = naomi_data$mf_artattend$attend_area_idx - 1L, Xgamma = Xgamma, Xgamma_t2 = Xgamma_t2, log_gamma_offset = naomi_data$mf_artattend$log_gamma_offset, Xart_idx = Xart_idx, Xart_gamma = Xart_gamma, ## omega = naomi_data$omega, OmegaT0 = naomi_data$rita_param$OmegaT0, sigma_OmegaT = naomi_data$rita_param$sigma_OmegaT, betaT0 = naomi_data$rita_param$betaT0, sigma_betaT = naomi_data$rita_param$sigma_betaT, ritaT = naomi_data$rita_param$ritaT, ## logit_nu_mean = naomi_data$logit_nu_mean, logit_nu_sd = naomi_data$logit_nu_sd, ## X_15to49 = X_15to49, log_lambda_t1_offset = naomi_data$mf_model$log_lambda_t1_offset, log_lambda_t2_offset = naomi_data$mf_model$log_lambda_t2_offset, ## X_15to49f = X_15to49f, X_paed_rho_ratio = X_paed_rho_ratio, paed_rho_ratio_offset = paed_rho_ratio_offset, ## X_paed_lambda_ratio_t1 = X_paed_lambda_ratio_t1, X_paed_lambda_ratio_t2 = X_paed_lambda_ratio_t2, X_paed_lambda_ratio_t3 = X_paed_lambda_ratio_t3, X_paed_lambda_ratio_t4 = X_paed_lambda_ratio_t4, X_paed_lambda_ratio_t5 = X_paed_lambda_ratio_t5, ## ## Household survey input data x_prev = naomi_data$prev_dat$x_eff, n_prev = naomi_data$prev_dat$n_eff, A_prev = A_prev, x_artcov = naomi_data$artcov_dat$x_eff, n_artcov = naomi_data$artcov_dat$n_eff, A_artcov = A_artcov, x_vls = naomi_data$vls_dat$x_eff, n_vls = naomi_data$vls_dat$n_eff, A_vls = A_vls, x_recent = naomi_data$recent_dat$x_eff, n_recent = naomi_data$recent_dat$n_eff, A_recent = A_recent, ## ## ANC testing input data x_anc_clients_t2 = naomi_data$anc_clients_t2_dat$anc_clients_x, offset_anc_clients_t2 = naomi_data$anc_clients_t2_dat$anc_clients_pys_offset, A_anc_clients_t2 = A_anc_clients_t2, x_anc_prev_t1 = naomi_data$anc_prev_t1_dat$anc_prev_x, n_anc_prev_t1 = naomi_data$anc_prev_t1_dat$anc_prev_n, A_anc_prev_t1 = A_anc_prev_t1, x_anc_artcov_t1 = naomi_data$anc_artcov_t1_dat$anc_artcov_x, n_anc_artcov_t1 = naomi_data$anc_artcov_t1_dat$anc_artcov_n, A_anc_artcov_t1 = A_anc_artcov_t1, x_anc_prev_t2 = naomi_data$anc_prev_t2_dat$anc_prev_x, n_anc_prev_t2 = naomi_data$anc_prev_t2_dat$anc_prev_n, A_anc_prev_t2 = A_anc_prev_t2, x_anc_artcov_t2 = naomi_data$anc_artcov_t2_dat$anc_artcov_x, n_anc_artcov_t2 = naomi_data$anc_artcov_t2_dat$anc_artcov_n, A_anc_artcov_t2 = A_anc_artcov_t2, ## ## Number on ART input data A_artattend_t1 = A_artattend_t1, x_artnum_t1 = naomi_data$artnum_t1_dat$art_current, A_artattend_t2 = A_artattend_t2, x_artnum_t2 = naomi_data$artnum_t2_dat$art_current, A_artattend_mf = A_artattend_mf, A_art_reside_attend = A_art_reside_attend, ## ## Time 3 projection inputs population_t3 = df$population_t3, Lproj_hivpop_t2t3 = naomi_data$Lproj_t2t3$Lproj_hivpop, Lproj_incid_t2t3 = naomi_data$Lproj_t2t3$Lproj_incid, Lproj_paed_t2t3 = naomi_data$Lproj_t2t3$Lproj_paed, logit_alpha_t2t3_offset = df$logit_alpha_t2t3_offset, log_lambda_t3_offset = df$log_lambda_t3_offset, ## ## Time 4 projection inputs population_t4 = df$population_t4, Lproj_hivpop_t3t4 = naomi_data$Lproj_t3t4$Lproj_hivpop, Lproj_incid_t3t4 = naomi_data$Lproj_t3t4$Lproj_incid, Lproj_paed_t3t4 = naomi_data$Lproj_t3t4$Lproj_paed, logit_alpha_t3t4_offset = df$logit_alpha_t3t4_offset, log_lambda_t4_offset = df$log_lambda_t4_offset, ## ## Time 5 projection inputs population_t5 = df$population_t5, Lproj_hivpop_t4t5 = naomi_data$Lproj_t4t5$Lproj_hivpop, Lproj_incid_t4t5 = naomi_data$Lproj_t4t5$Lproj_incid, Lproj_paed_t4t5 = naomi_data$Lproj_t4t5$Lproj_paed, logit_alpha_t4t5_offset = df$logit_alpha_t4t5_offset, log_lambda_t5_offset = df$log_lambda_t5_offset, ## A_out = naomi_data$A_out, A_anc_out = naomi_data$A_anc_out, calc_outputs = 1L, report_likelihood = report_likelihood ) ptmb <- list( beta_rho = numeric(ncol(dtmb$X_rho)), beta_alpha = numeric(ncol(dtmb$X_alpha)), beta_alpha_t2 = numeric(ncol(dtmb$X_alpha_t2)), beta_lambda = numeric(ncol(dtmb$X_lambda)), beta_asfr = numeric(1), beta_anc_rho = numeric(1), beta_anc_alpha = numeric(1), beta_anc_rho_t2 = numeric(1), beta_anc_alpha_t2 = numeric(1), u_rho_x = numeric(ncol(dtmb$Z_rho_x)), us_rho_x = numeric(ncol(dtmb$Z_rho_x)), u_rho_xs = numeric(ncol(dtmb$Z_rho_xs)), us_rho_xs = numeric(ncol(dtmb$Z_rho_xs)), u_rho_a = numeric(ncol(dtmb$Z_rho_a)), u_rho_as = numeric(ncol(dtmb$Z_rho_as)), u_rho_xa = numeric(ncol(dtmb$Z_rho_xa)), ui_asfr_x = numeric(ncol(dtmb$Z_asfr_x)), ui_anc_rho_x = numeric(ncol(dtmb$Z_ancrho_x)), ui_anc_alpha_x = numeric(ncol(dtmb$Z_ancalpha_x)), ui_anc_rho_xt = numeric(ncol(dtmb$Z_ancrho_x)), ui_anc_alpha_xt = numeric(ncol(dtmb$Z_ancalpha_x)), ## u_alpha_x = numeric(ncol(dtmb$Z_alpha_x)), us_alpha_x = numeric(ncol(dtmb$Z_alpha_x)), u_alpha_xs = numeric(ncol(dtmb$Z_alpha_xs)), us_alpha_xs = numeric(ncol(dtmb$Z_alpha_xs)), u_alpha_a = numeric(ncol(dtmb$Z_alpha_a)), u_alpha_as = numeric(ncol(dtmb$Z_alpha_as)), u_alpha_xt = numeric(ncol(dtmb$Z_alpha_xt)), u_alpha_xa = numeric(ncol(dtmb$Z_alpha_xa)), u_alpha_xat = numeric(ncol(dtmb$Z_alpha_xat)), u_alpha_xst = numeric(ncol(dtmb$Z_alpha_xst)), ## log_sigma_lambda_x = log(1.0), ui_lambda_x = numeric(ncol(dtmb$Z_lambda_x)), ## logit_phi_rho_a = 0, log_sigma_rho_a = log(2.5), logit_phi_rho_as = 2.582, log_sigma_rho_as = log(2.5), logit_phi_rho_x = 0, log_sigma_rho_x = log(2.5), logit_phi_rho_xs = 0, log_sigma_rho_xs = log(2.5), log_sigma_rho_xa = log(0.5), ## logit_phi_alpha_a = 0, log_sigma_alpha_a = log(2.5), logit_phi_alpha_as = 2.582, log_sigma_alpha_as = log(2.5), logit_phi_alpha_x = 0, log_sigma_alpha_x = log(2.5), logit_phi_alpha_xs = 0, log_sigma_alpha_xs = log(2.5), log_sigma_alpha_xt = log(2.5), log_sigma_alpha_xa = log(2.5), log_sigma_alpha_xat = log(2.5), log_sigma_alpha_xst = log(2.5), ## OmegaT_raw = 0, log_betaT = 0, logit_nu_raw = 0, ## log_sigma_asfr_x = log(0.5), log_sigma_ancrho_x = log(2.5), log_sigma_ancalpha_x = log(2.5), log_sigma_ancrho_xt = log(2.5), log_sigma_ancalpha_xt = log(2.5), ## log_or_gamma = numeric(ncol(dtmb$Xgamma)), log_sigma_or_gamma = log(2.5), log_or_gamma_t1t2 = numeric(ncol(dtmb$Xgamma_t2)), log_sigma_or_gamma_t1t2 = log(2.5) ) v <- list(data = dtmb, par_init = ptmb) class(v) <- "naomi_tmb_input" v } sparse_model_matrix <- function(formula, data, binary_interaction = 1, drop_zero_cols = FALSE) { if(is.character(binary_interaction)) binary_interaction <- data[[binary_interaction]] stopifnot(length(binary_interaction) %in% c(1, nrow(data))) mm <- Matrix::sparse.model.matrix(formula, data) mm <- mm * binary_interaction mm <- Matrix::drop0(mm) if(drop_zero_cols) mm <- mm[ , apply(mm, 2, Matrix::nnzero) > 0] mm } make_tmb_obj <- function(data, par, calc_outputs = 1L, inner_verbose = FALSE, progress = NULL) { data$calc_outputs <- as.integer(calc_outputs) obj <- TMB::MakeADFun(data = data, parameters = par, DLL = "naomi", silent = !inner_verbose, random = c("beta_rho", "beta_alpha", "beta_alpha_t2", "beta_lambda", "beta_asfr", "beta_anc_rho", "beta_anc_alpha", "beta_anc_rho_t2", "beta_anc_alpha_t2", "u_rho_x", "us_rho_x", "u_rho_xs", "us_rho_xs", "u_rho_a", "u_rho_as", "u_rho_xa", ## "u_alpha_x", "us_alpha_x", "u_alpha_xs", "us_alpha_xs", "u_alpha_a", "u_alpha_as", "u_alpha_xt", "u_alpha_xa", "u_alpha_xat", "u_alpha_xst", ## "ui_lambda_x", "logit_nu_raw", ## "ui_asfr_x", "ui_anc_rho_x", "ui_anc_alpha_x", "ui_anc_rho_xt", "ui_anc_alpha_xt", ## "log_or_gamma", "log_or_gamma_t1t2")) if (!is.null(progress)) { obj$fn <- report_progress(obj$fn, progress) } obj } report_progress <- function(fun, progress) { fun <- match.fun(fun) function(...) { progress$iterate_fit() fun(...) } } #' Fit TMB model #' #' @param tmb_input Model input data #' @param outer_verbose If TRUE print function and parameters every iteration #' @param inner_verbose If TRUE then disable tracing information from TMB #' @param max_iter maximum number of iterations #' @param progress Progress printer, if null no progress printed #' #' @return Fit model. #' @export fit_tmb <- function(tmb_input, outer_verbose = TRUE, inner_verbose = FALSE, max_iter = 250, progress = NULL ) { stopifnot(inherits(tmb_input, "naomi_tmb_input")) obj <- make_tmb_obj(tmb_input$data, tmb_input$par_init, calc_outputs = 0L, inner_verbose, progress) trace <- if(outer_verbose) 1 else 0 f <- withCallingHandlers( stats::nlminb(obj$par, obj$fn, obj$gr, control = list(trace = trace, iter.max = max_iter)), warning = function(w) { if(grepl("NA/NaN function evaluation", w$message)) invokeRestart("muffleWarning") } ) if(f$convergence != 0) warning(paste("convergence error:", f$message)) if(outer_verbose) message(paste("converged:", f$message)) f$par.fixed <- f$par f$par.full <- obj$env$last.par objout <- make_tmb_obj(tmb_input$data, tmb_input$par_init, calc_outputs = 1L, inner_verbose) f$mode <- objout$report(f$par.full) val <- c(f, obj = list(objout)) class(val) <- "naomi_fit" val } #' Calculate Posterior Mean and Uncertainty Via TMB `sdreport()` #' #' @param naomi_fit Fitted TMB model. #' #' @export report_tmb <- function(naomi_fit) { stopifnot(methods::is(fit, "naomi_fit")) naomi_fit$sdreport <- TMB::sdreport(naomi_fit$obj, naomi_fit$par, getReportCovariance = FALSE, bias.correct = TRUE) naomi_fit } #' Sample TMB fit #' #' @param fit The TMB fit #' @param nsample Number of samples #' @param rng_seed seed passed to set.seed. #' @param random_only Random only #' @param verbose If TRUE prints additional information. #' #' @return Sampled fit. #' @export sample_tmb <- function(fit, nsample = 1000, rng_seed = NULL, random_only = TRUE, verbose = FALSE) { set.seed(rng_seed) stopifnot(methods::is(fit, "naomi_fit")) stopifnot(nsample > 1) to_tape <- TMB:::isNullPointer(fit$obj$env$ADFun$ptr) if (to_tape) fit$obj$retape(FALSE) if(!random_only) { if(verbose) print("Calculating joint precision") hess <- sdreport_joint_precision(fit$obj, fit$par.fixed) if(verbose) print("Inverting precision for joint covariance") cov <- solve(hess) if(verbose) print("Drawing sample") ## TODO: write a version of rmvnorm that uses precision instead of covariance smp <- mvtnorm::rmvnorm(nsample, fit$par.full, cov) } else { r <- fit$obj$env$random par_f <- fit$par.full[-r] par_r <- fit$par.full[r] hess_r <- fit$obj$env$spHess(fit$par.full, random = TRUE) smp_r <- rmvnorm_sparseprec(nsample, par_r, hess_r) smp <- matrix(0, nsample, length(fit$par.full)) smp[ , r] <- smp_r smp[ ,-r] <- matrix(par_f, nsample, length(par_f), byrow = TRUE) colnames(smp)[r] <- colnames(smp_r) colnames(smp)[-r] <- names(par_f) } if(verbose) print("Simulating outputs") sim <- apply(smp, 1, fit$obj$report) r <- fit$obj$report() if(verbose) print("Returning sample") fit$sample <- Map(vapply, list(sim), "[[", lapply(lengths(r), numeric), names(r)) is_vector <- vapply(fit$sample, inherits, logical(1), "numeric") fit$sample[is_vector] <- lapply(fit$sample[is_vector], matrix, nrow = 1) names(fit$sample) <- names(r) fit } rmvnorm_sparseprec <- function( n, mean = rep(0, nrow(prec)), prec = diag(length(mean)) ) { z = matrix(stats::rnorm(n * length(mean)), ncol = n) L_inv = Matrix::Cholesky(prec) v <- mean + Matrix::solve(as(L_inv, "pMatrix"), Matrix::solve(Matrix::t(as(L_inv, "Matrix")), z)) as.matrix(Matrix::t(v)) } create_artattend_Amat <- function(artnum_df, age_groups, sexes, area_aggregation, df_art_attend, by_residence = FALSE, by_survey = FALSE) { ## If by_residence = TRUE, merge by reside_area_id, else aggregate over all ## reside_area_id by_vars <- c("attend_area_id", "sex", "age_group") if (by_residence) { by_vars <- c(by_vars, "reside_area_id") } id_vars <- by_vars if (by_survey) { id_vars <- c(id_vars, "survey_id") } if(!("artnum_idx" %in% colnames(artnum_df))) { artnum_df$artnum_idx <- seq_len(nrow(artnum_df)) } A_artnum <- artnum_df %>% dplyr::select(tidyselect::all_of(id_vars), artnum_idx) %>% dplyr::rename(artdat_age_group = age_group, artdat_sex = sex) %>% dplyr::left_join( get_age_groups() %>% dplyr::transmute( artdat_age_group = age_group, artdat_age_start = age_group_start, artdat_age_end = age_group_start + age_group_span ), by = "artdat_age_group" ) %>% ## Note: this would be much faster with tree data structure for age rather than crossing... tidyr::crossing( get_age_groups() %>% dplyr::filter(age_group %in% age_groups) ) %>% dplyr::filter( artdat_age_start <= age_group_start, age_group_start + age_group_span <= artdat_age_end ) %>% dplyr::left_join( data.frame(artdat_sex = c("male", "female", "both", "both", "both"), sex = c("male", "female", "male", "female", "both"), stringsAsFactors = FALSE) %>% dplyr::filter(sex %in% sexes), by = "artdat_sex", multiple = "all" ) ## Map artattend_area_id to model_area_id A_artnum <- A_artnum %>% dplyr::left_join( area_aggregation, by = c("attend_area_id" = "area_id"), multiple = "all" ) %>% dplyr::mutate(attend_area_id = model_area_id, model_area_id = NULL) ## Check no areas with duplicated reporting art_duplicated_check <- A_artnum %>% dplyr::group_by_at(id_vars) %>% dplyr::summarise(n = dplyr::n(), .groups = "drop") %>% dplyr::filter(n > 1) if (nrow(art_duplicated_check)) { stop(paste("ART or ANC data multiply reported for some age/sex strata in areas:", paste(unique(art_duplicated_check$attend_area_id), collapse = ", "))) } ## Merge to ART attendance data frame df_art_attend <- df_art_attend %>% dplyr::select(tidyselect::all_of(by_vars)) %>% dplyr::mutate( Aidx = dplyr::row_number(), value = 1 ) A_artnum <- dplyr::left_join(A_artnum, df_art_attend, by = by_vars, multiple = "all") A_artnum <- A_artnum %>% { Matrix::spMatrix(nrow(artnum_df), nrow(df_art_attend), .$artnum_idx, .$Aidx, .$value) } A_artnum }
/R/tmb-model.R
permissive
mrc-ide/naomi
R
false
false
29,092
r
#' Prepare inputs for TMB model. #' #' @param naomi_data Naomi data object #' @param report_likelihood Option to report likelihood in fit object (default true). #' @param anchor_home_district Option to include random effect home district attractiveness to retain residents on ART within home districts (default true). #' #' @return Inputs ready for TMB model #' #' @seealso [select_naomi_data] #' @export prepare_tmb_inputs <- function(naomi_data, report_likelihood = 1L) { stopifnot(is(naomi_data, "naomi_data")) stopifnot(is(naomi_data, "naomi_mf")) ## ANC observation aggregation matrices ## ## TODO: Refactor code to make the function create_artattend_Amat() more generic. ## Should not refer to 'ART' specific; also useful for ANC attendance, ## fertility, etc. create_anc_Amat <- function(anc_obs_dat) { df_attend_anc <- naomi_data$mf_model %>% dplyr::select(reside_area_id = area_id, attend_area_id = area_id, sex, age_group, idx) dat <- dplyr::rename(anc_obs_dat, attend_area_id = area_id) Amat <- create_artattend_Amat( dat, age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_attend_anc, by_residence = FALSE ) Amat } create_survey_Amat <- function(survey_dat) { df_attend_survey <- naomi_data$mf_model %>% dplyr::select(reside_area_id = area_id, attend_area_id = area_id, sex, age_group, idx) survey_dat$attend_area_id <- survey_dat$area_id Amat <- create_artattend_Amat( survey_dat, age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_attend_survey, by_residence = FALSE, by_survey = TRUE ) Amat } A_anc_clients_t2 <- create_anc_Amat(naomi_data$anc_clients_t2_dat) A_anc_prev_t1 <- create_anc_Amat(naomi_data$anc_prev_t1_dat) A_anc_prev_t2 <- create_anc_Amat(naomi_data$anc_prev_t2_dat) A_anc_artcov_t1 <- create_anc_Amat(naomi_data$anc_artcov_t1_dat) A_anc_artcov_t2 <- create_anc_Amat(naomi_data$anc_artcov_t2_dat) A_prev <- create_survey_Amat(naomi_data$prev_dat) A_artcov <- create_survey_Amat(naomi_data$artcov_dat) A_vls <- create_survey_Amat(naomi_data$vls_dat) A_recent <- create_survey_Amat(naomi_data$recent_dat) ## ART attendance aggregation # Default model for ART attending: Anchor home district = add random effect for home district if(naomi_data$model_options$anchor_home_district) { Xgamma <- naomi:::sparse_model_matrix(~0 + attend_area_idf, naomi_data$mf_artattend) } else { Xgamma <- sparse_model_matrix(~0 + attend_area_idf:as.integer(jstar != 1), naomi_data$mf_artattend) } if(naomi_data$artattend_t2) { Xgamma_t2 <- Xgamma } else { Xgamma_t2 <- sparse_model_matrix(~0, naomi_data$mf_artattend) } df_art_attend <- naomi_data$mf_model %>% dplyr::rename(reside_area_id = area_id) %>% dplyr::left_join(naomi_data$mf_artattend, by = "reside_area_id", multiple = "all") %>% dplyr::mutate(attend_idf = forcats::as_factor(attend_idx), idf = forcats::as_factor(idx)) Xart_gamma <- sparse_model_matrix(~0 + attend_idf, df_art_attend) Xart_idx <- sparse_model_matrix(~0 + idf, df_art_attend) A_artattend_t1 <- create_artattend_Amat(artnum_df = dplyr::rename(naomi_data$artnum_t1_dat, attend_area_id = area_id), age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = FALSE) A_artattend_t2 <- create_artattend_Amat(artnum_df = dplyr::rename(naomi_data$artnum_t2_dat, attend_area_id = area_id), age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = FALSE) A_artattend_mf <- create_artattend_Amat(artnum_df = dplyr::select(naomi_data$mf_model, attend_area_id = area_id, sex, age_group, artnum_idx = idx), age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = FALSE) A_art_reside_attend <- naomi_data$mf_artattend %>% dplyr::transmute( reside_area_id, attend_area_id, sex = "both", age_group = "Y000_999" ) %>% create_artattend_Amat(age_groups = naomi_data$age_groups, sexes = naomi_data$sexes, area_aggregation = naomi_data$area_aggregation, df_art_attend = df_art_attend, by_residence = TRUE) ## Construct TMB data and initial parameter vectors df <- naomi_data$mf_model X_15to49 <- Matrix::t(sparse_model_matrix(~-1 + area_idf:age15to49, naomi_data$mf_model)) ## Paediatric prevalence from 15-49 female ratio X_15to49f <- Matrix::t(Matrix::sparse.model.matrix(~0 + area_idf:age15to49:as.integer(sex == "female"), df)) df$bin_paed_rho_model <- 1 - df$bin_rho_model X_paed_rho_ratio <- sparse_model_matrix(~-1 + area_idf:paed_rho_ratio:bin_paed_rho_model, df) paed_rho_ratio_offset <- 0.5 * df$bin_rho_model X_paed_lambda_ratio_t1 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t1, df) X_paed_lambda_ratio_t2 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t2, df) X_paed_lambda_ratio_t3 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t3, df) X_paed_lambda_ratio_t4 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t4, df) X_paed_lambda_ratio_t5 <- sparse_model_matrix(~-1 + area_idf:paed_lambda_ratio_t5, df) f_rho_a <- if(all(is.na(df$rho_a_fct))) ~0 else ~0 + rho_a_fct f_alpha_a <- if(all(is.na(df$alpha_a_fct))) ~0 else ~0 + alpha_a_fct if (naomi_data$rho_paed_x_term) { f_rho_xa <- ~0 + area_idf } else { f_rho_xa <- ~0 } ## Ratio of paediatric incidence rate to 15-49 female prevalence ## If no sex stratified prevalence data, don't estimate spatial variation in ## sex odds ratio if ( ! all(c("male", "female") %in% naomi_data$prev_dat$sex)) { f_rho_xs <- ~0 } else { f_rho_xs <- ~0 + area_idf } ## If no sex stratified ART coverage data, don't estimate spatial variation in ## sex odds ratio if ( ! all(c("male", "female") %in% naomi_data$artcov_dat$sex) && ! all(c("male", "female") %in% naomi_data$artnum_t1_dat$sex) && ! all(c("male", "female") %in% naomi_data$artnum_t2_dat$sex) ) { f_alpha_xs <- ~0 } else { f_alpha_xs <- ~0 + area_idf } ## If flag **and** has ART by sex data at both times, estimate time x district x ## sex ART odds ratio. if (naomi_data$alpha_xst_term) { if (!all(c("male", "female") %in% naomi_data$artnum_t1_dat$sex) && !all(c("male", "female") %in% naomi_data$artnum_t2_dat$sex)) { stop(paste("Sex-stratified ART data are required at both Time 1 and Time 2", "to estimate district x sex x time interaction for ART coverage")) } f_alpha_xst <- ~0 + area_idf } else { f_alpha_xst <- ~0 } ## If no ART data at both time points, do not fit a change in ART coverage. Use ## logit difference in ART coverage from Spectrum. ## T1 ART data may be either survey or programme ## has_t1_art <- nrow(naomi_data$artcov_dat) > 0 | nrow(naomi_data$artnum_t1_dat) > 0 has_t2_art <- nrow(naomi_data$artnum_t2_dat) > 0 if( !has_t1_art | !has_t2_art ) { f_alpha_t2 <- ~0 f_alpha_xt <- ~0 logit_alpha_t1t2_offset <- naomi_data$mf_model$logit_alpha_t1t2_offset } else { f_alpha_t2 <- ~1 f_alpha_xt <- ~0 + area_idf logit_alpha_t1t2_offset <- numeric(nrow(naomi_data$mf_model)) } ## Paediatric ART coverage random effects artnum_t1_dat <- naomi_data$artnum_t1_dat %>% dplyr::left_join(get_age_groups(), by = "age_group") %>% dplyr::mutate(age_group_end = age_group_start + age_group_span - 1) artnum_t2_dat <- naomi_data$artnum_t2_dat %>% dplyr::left_join(get_age_groups(), by = "age_group") %>% dplyr::mutate(age_group_end = age_group_start + age_group_span - 1) has_t1_paed_art <- any(artnum_t1_dat$age_group_end < 15) has_t2_paed_art <- any(artnum_t2_dat$age_group_end < 15) if(has_t1_paed_art | has_t2_paed_art) { f_alpha_xa <- ~0 + area_idf } else { f_alpha_xa <- ~0 } if(has_t1_paed_art & has_t2_paed_art) { f_alpha_t2 <- ~1 + age_below15 f_alpha_xat <- ~0 + area_idf } else { f_alpha_xat <- ~0 } ## If no recent infection data, do not estimate incidence sex ratio or ## district random effects if(nrow(naomi_data$recent_dat) == 0) { f_lambda <- ~0 f_lambda_x <- ~0 } else { f_lambda <- ~ 1 + female_15plus f_lambda_x <- ~0 + area_idf } dtmb <- list( population_t1 = df$population_t1, population_t2 = df$population_t2, Lproj_hivpop_t1t2 = naomi_data$Lproj_t1t2$Lproj_hivpop, Lproj_incid_t1t2 = naomi_data$Lproj_t1t2$Lproj_incid, Lproj_paed_t1t2 = naomi_data$Lproj_t1t2$Lproj_paed, X_rho = as.matrix(sparse_model_matrix(~female_15plus, df, "bin_rho_model", TRUE)), X_alpha = stats::model.matrix(~female_15plus, df), X_alpha_t2 = stats::model.matrix(f_alpha_t2, df), X_lambda = stats::model.matrix(f_lambda, df), X_asfr = stats::model.matrix(~1, df), X_ancrho = stats::model.matrix(~1, df), X_ancalpha = stats::model.matrix(~1, df), Z_x = sparse_model_matrix(~0 + area_idf, df), Z_rho_x = sparse_model_matrix(~0 + area_idf, df, "bin_rho_model", TRUE), Z_rho_xs = sparse_model_matrix(f_rho_xs, df, "female_15plus", TRUE), Z_rho_a = sparse_model_matrix(f_rho_a, df, "bin_rho_model", TRUE), Z_rho_as = sparse_model_matrix(f_rho_a, df, "female_15plus", TRUE), Z_rho_xa = sparse_model_matrix(f_rho_xa, df, "age_below15"), Z_alpha_x = sparse_model_matrix(~0 + area_idf, df), Z_alpha_xs = sparse_model_matrix(f_alpha_xs, df, "female_15plus", TRUE), Z_alpha_a = sparse_model_matrix(f_alpha_a, df), Z_alpha_as = sparse_model_matrix(f_alpha_a, df, "female_15plus", TRUE), Z_alpha_xt = sparse_model_matrix(f_alpha_xt, df), Z_alpha_xa = sparse_model_matrix(f_alpha_xa, df, "age_below15"), Z_alpha_xat = sparse_model_matrix(f_alpha_xat, df, "age_below15"), Z_alpha_xst = sparse_model_matrix(f_alpha_xst, df, "female_15plus", TRUE), Z_lambda_x = sparse_model_matrix(f_lambda_x, df), ## Z_xa = Matrix::sparse.model.matrix(~0 + area_idf:age_group_idf, df), Z_asfr_x = sparse_model_matrix(~0 + area_idf, df), Z_ancrho_x = sparse_model_matrix(~0 + area_idf, df), Z_ancalpha_x = sparse_model_matrix(~0 + area_idf, df), log_asfr_t1_offset = log(df$asfr_t1), log_asfr_t2_offset = log(df$asfr_t2), log_asfr_t3_offset = log(df$asfr_t3), logit_anc_rho_t1_offset = log(df$frr_plhiv_t1), logit_anc_rho_t2_offset = log(df$frr_plhiv_t2), logit_anc_rho_t3_offset = log(df$frr_plhiv_t3), logit_anc_alpha_t1_offset = log(df$frr_already_art_t1), logit_anc_alpha_t2_offset = log(df$frr_already_art_t2), logit_anc_alpha_t3_offset = log(df$frr_already_art_t3), ## logit_rho_offset = naomi_data$mf_model$logit_rho_offset * naomi_data$mf_model$bin_rho_model, logit_alpha_offset = naomi_data$mf_model$logit_alpha_offset, logit_alpha_t1t2_offset = logit_alpha_t1t2_offset, ## unaware_untreated_prop_t1 = df$spec_unaware_untreated_prop_t1, unaware_untreated_prop_t2 = df$spec_unaware_untreated_prop_t2, unaware_untreated_prop_t3 = df$spec_unaware_untreated_prop_t3, ## Q_x = methods::as(naomi_data$Q, "dgCMatrix"), Q_x_rankdef = ncol(naomi_data$Q) - as.integer(Matrix::rankMatrix(naomi_data$Q)), n_nb = naomi_data$mf_areas$n_neighbors, adj_i = naomi_data$mf_artattend$reside_area_idx - 1L, adj_j = naomi_data$mf_artattend$attend_area_idx - 1L, Xgamma = Xgamma, Xgamma_t2 = Xgamma_t2, log_gamma_offset = naomi_data$mf_artattend$log_gamma_offset, Xart_idx = Xart_idx, Xart_gamma = Xart_gamma, ## omega = naomi_data$omega, OmegaT0 = naomi_data$rita_param$OmegaT0, sigma_OmegaT = naomi_data$rita_param$sigma_OmegaT, betaT0 = naomi_data$rita_param$betaT0, sigma_betaT = naomi_data$rita_param$sigma_betaT, ritaT = naomi_data$rita_param$ritaT, ## logit_nu_mean = naomi_data$logit_nu_mean, logit_nu_sd = naomi_data$logit_nu_sd, ## X_15to49 = X_15to49, log_lambda_t1_offset = naomi_data$mf_model$log_lambda_t1_offset, log_lambda_t2_offset = naomi_data$mf_model$log_lambda_t2_offset, ## X_15to49f = X_15to49f, X_paed_rho_ratio = X_paed_rho_ratio, paed_rho_ratio_offset = paed_rho_ratio_offset, ## X_paed_lambda_ratio_t1 = X_paed_lambda_ratio_t1, X_paed_lambda_ratio_t2 = X_paed_lambda_ratio_t2, X_paed_lambda_ratio_t3 = X_paed_lambda_ratio_t3, X_paed_lambda_ratio_t4 = X_paed_lambda_ratio_t4, X_paed_lambda_ratio_t5 = X_paed_lambda_ratio_t5, ## ## Household survey input data x_prev = naomi_data$prev_dat$x_eff, n_prev = naomi_data$prev_dat$n_eff, A_prev = A_prev, x_artcov = naomi_data$artcov_dat$x_eff, n_artcov = naomi_data$artcov_dat$n_eff, A_artcov = A_artcov, x_vls = naomi_data$vls_dat$x_eff, n_vls = naomi_data$vls_dat$n_eff, A_vls = A_vls, x_recent = naomi_data$recent_dat$x_eff, n_recent = naomi_data$recent_dat$n_eff, A_recent = A_recent, ## ## ANC testing input data x_anc_clients_t2 = naomi_data$anc_clients_t2_dat$anc_clients_x, offset_anc_clients_t2 = naomi_data$anc_clients_t2_dat$anc_clients_pys_offset, A_anc_clients_t2 = A_anc_clients_t2, x_anc_prev_t1 = naomi_data$anc_prev_t1_dat$anc_prev_x, n_anc_prev_t1 = naomi_data$anc_prev_t1_dat$anc_prev_n, A_anc_prev_t1 = A_anc_prev_t1, x_anc_artcov_t1 = naomi_data$anc_artcov_t1_dat$anc_artcov_x, n_anc_artcov_t1 = naomi_data$anc_artcov_t1_dat$anc_artcov_n, A_anc_artcov_t1 = A_anc_artcov_t1, x_anc_prev_t2 = naomi_data$anc_prev_t2_dat$anc_prev_x, n_anc_prev_t2 = naomi_data$anc_prev_t2_dat$anc_prev_n, A_anc_prev_t2 = A_anc_prev_t2, x_anc_artcov_t2 = naomi_data$anc_artcov_t2_dat$anc_artcov_x, n_anc_artcov_t2 = naomi_data$anc_artcov_t2_dat$anc_artcov_n, A_anc_artcov_t2 = A_anc_artcov_t2, ## ## Number on ART input data A_artattend_t1 = A_artattend_t1, x_artnum_t1 = naomi_data$artnum_t1_dat$art_current, A_artattend_t2 = A_artattend_t2, x_artnum_t2 = naomi_data$artnum_t2_dat$art_current, A_artattend_mf = A_artattend_mf, A_art_reside_attend = A_art_reside_attend, ## ## Time 3 projection inputs population_t3 = df$population_t3, Lproj_hivpop_t2t3 = naomi_data$Lproj_t2t3$Lproj_hivpop, Lproj_incid_t2t3 = naomi_data$Lproj_t2t3$Lproj_incid, Lproj_paed_t2t3 = naomi_data$Lproj_t2t3$Lproj_paed, logit_alpha_t2t3_offset = df$logit_alpha_t2t3_offset, log_lambda_t3_offset = df$log_lambda_t3_offset, ## ## Time 4 projection inputs population_t4 = df$population_t4, Lproj_hivpop_t3t4 = naomi_data$Lproj_t3t4$Lproj_hivpop, Lproj_incid_t3t4 = naomi_data$Lproj_t3t4$Lproj_incid, Lproj_paed_t3t4 = naomi_data$Lproj_t3t4$Lproj_paed, logit_alpha_t3t4_offset = df$logit_alpha_t3t4_offset, log_lambda_t4_offset = df$log_lambda_t4_offset, ## ## Time 5 projection inputs population_t5 = df$population_t5, Lproj_hivpop_t4t5 = naomi_data$Lproj_t4t5$Lproj_hivpop, Lproj_incid_t4t5 = naomi_data$Lproj_t4t5$Lproj_incid, Lproj_paed_t4t5 = naomi_data$Lproj_t4t5$Lproj_paed, logit_alpha_t4t5_offset = df$logit_alpha_t4t5_offset, log_lambda_t5_offset = df$log_lambda_t5_offset, ## A_out = naomi_data$A_out, A_anc_out = naomi_data$A_anc_out, calc_outputs = 1L, report_likelihood = report_likelihood ) ptmb <- list( beta_rho = numeric(ncol(dtmb$X_rho)), beta_alpha = numeric(ncol(dtmb$X_alpha)), beta_alpha_t2 = numeric(ncol(dtmb$X_alpha_t2)), beta_lambda = numeric(ncol(dtmb$X_lambda)), beta_asfr = numeric(1), beta_anc_rho = numeric(1), beta_anc_alpha = numeric(1), beta_anc_rho_t2 = numeric(1), beta_anc_alpha_t2 = numeric(1), u_rho_x = numeric(ncol(dtmb$Z_rho_x)), us_rho_x = numeric(ncol(dtmb$Z_rho_x)), u_rho_xs = numeric(ncol(dtmb$Z_rho_xs)), us_rho_xs = numeric(ncol(dtmb$Z_rho_xs)), u_rho_a = numeric(ncol(dtmb$Z_rho_a)), u_rho_as = numeric(ncol(dtmb$Z_rho_as)), u_rho_xa = numeric(ncol(dtmb$Z_rho_xa)), ui_asfr_x = numeric(ncol(dtmb$Z_asfr_x)), ui_anc_rho_x = numeric(ncol(dtmb$Z_ancrho_x)), ui_anc_alpha_x = numeric(ncol(dtmb$Z_ancalpha_x)), ui_anc_rho_xt = numeric(ncol(dtmb$Z_ancrho_x)), ui_anc_alpha_xt = numeric(ncol(dtmb$Z_ancalpha_x)), ## u_alpha_x = numeric(ncol(dtmb$Z_alpha_x)), us_alpha_x = numeric(ncol(dtmb$Z_alpha_x)), u_alpha_xs = numeric(ncol(dtmb$Z_alpha_xs)), us_alpha_xs = numeric(ncol(dtmb$Z_alpha_xs)), u_alpha_a = numeric(ncol(dtmb$Z_alpha_a)), u_alpha_as = numeric(ncol(dtmb$Z_alpha_as)), u_alpha_xt = numeric(ncol(dtmb$Z_alpha_xt)), u_alpha_xa = numeric(ncol(dtmb$Z_alpha_xa)), u_alpha_xat = numeric(ncol(dtmb$Z_alpha_xat)), u_alpha_xst = numeric(ncol(dtmb$Z_alpha_xst)), ## log_sigma_lambda_x = log(1.0), ui_lambda_x = numeric(ncol(dtmb$Z_lambda_x)), ## logit_phi_rho_a = 0, log_sigma_rho_a = log(2.5), logit_phi_rho_as = 2.582, log_sigma_rho_as = log(2.5), logit_phi_rho_x = 0, log_sigma_rho_x = log(2.5), logit_phi_rho_xs = 0, log_sigma_rho_xs = log(2.5), log_sigma_rho_xa = log(0.5), ## logit_phi_alpha_a = 0, log_sigma_alpha_a = log(2.5), logit_phi_alpha_as = 2.582, log_sigma_alpha_as = log(2.5), logit_phi_alpha_x = 0, log_sigma_alpha_x = log(2.5), logit_phi_alpha_xs = 0, log_sigma_alpha_xs = log(2.5), log_sigma_alpha_xt = log(2.5), log_sigma_alpha_xa = log(2.5), log_sigma_alpha_xat = log(2.5), log_sigma_alpha_xst = log(2.5), ## OmegaT_raw = 0, log_betaT = 0, logit_nu_raw = 0, ## log_sigma_asfr_x = log(0.5), log_sigma_ancrho_x = log(2.5), log_sigma_ancalpha_x = log(2.5), log_sigma_ancrho_xt = log(2.5), log_sigma_ancalpha_xt = log(2.5), ## log_or_gamma = numeric(ncol(dtmb$Xgamma)), log_sigma_or_gamma = log(2.5), log_or_gamma_t1t2 = numeric(ncol(dtmb$Xgamma_t2)), log_sigma_or_gamma_t1t2 = log(2.5) ) v <- list(data = dtmb, par_init = ptmb) class(v) <- "naomi_tmb_input" v } sparse_model_matrix <- function(formula, data, binary_interaction = 1, drop_zero_cols = FALSE) { if(is.character(binary_interaction)) binary_interaction <- data[[binary_interaction]] stopifnot(length(binary_interaction) %in% c(1, nrow(data))) mm <- Matrix::sparse.model.matrix(formula, data) mm <- mm * binary_interaction mm <- Matrix::drop0(mm) if(drop_zero_cols) mm <- mm[ , apply(mm, 2, Matrix::nnzero) > 0] mm } make_tmb_obj <- function(data, par, calc_outputs = 1L, inner_verbose = FALSE, progress = NULL) { data$calc_outputs <- as.integer(calc_outputs) obj <- TMB::MakeADFun(data = data, parameters = par, DLL = "naomi", silent = !inner_verbose, random = c("beta_rho", "beta_alpha", "beta_alpha_t2", "beta_lambda", "beta_asfr", "beta_anc_rho", "beta_anc_alpha", "beta_anc_rho_t2", "beta_anc_alpha_t2", "u_rho_x", "us_rho_x", "u_rho_xs", "us_rho_xs", "u_rho_a", "u_rho_as", "u_rho_xa", ## "u_alpha_x", "us_alpha_x", "u_alpha_xs", "us_alpha_xs", "u_alpha_a", "u_alpha_as", "u_alpha_xt", "u_alpha_xa", "u_alpha_xat", "u_alpha_xst", ## "ui_lambda_x", "logit_nu_raw", ## "ui_asfr_x", "ui_anc_rho_x", "ui_anc_alpha_x", "ui_anc_rho_xt", "ui_anc_alpha_xt", ## "log_or_gamma", "log_or_gamma_t1t2")) if (!is.null(progress)) { obj$fn <- report_progress(obj$fn, progress) } obj } report_progress <- function(fun, progress) { fun <- match.fun(fun) function(...) { progress$iterate_fit() fun(...) } } #' Fit TMB model #' #' @param tmb_input Model input data #' @param outer_verbose If TRUE print function and parameters every iteration #' @param inner_verbose If TRUE then disable tracing information from TMB #' @param max_iter maximum number of iterations #' @param progress Progress printer, if null no progress printed #' #' @return Fit model. #' @export fit_tmb <- function(tmb_input, outer_verbose = TRUE, inner_verbose = FALSE, max_iter = 250, progress = NULL ) { stopifnot(inherits(tmb_input, "naomi_tmb_input")) obj <- make_tmb_obj(tmb_input$data, tmb_input$par_init, calc_outputs = 0L, inner_verbose, progress) trace <- if(outer_verbose) 1 else 0 f <- withCallingHandlers( stats::nlminb(obj$par, obj$fn, obj$gr, control = list(trace = trace, iter.max = max_iter)), warning = function(w) { if(grepl("NA/NaN function evaluation", w$message)) invokeRestart("muffleWarning") } ) if(f$convergence != 0) warning(paste("convergence error:", f$message)) if(outer_verbose) message(paste("converged:", f$message)) f$par.fixed <- f$par f$par.full <- obj$env$last.par objout <- make_tmb_obj(tmb_input$data, tmb_input$par_init, calc_outputs = 1L, inner_verbose) f$mode <- objout$report(f$par.full) val <- c(f, obj = list(objout)) class(val) <- "naomi_fit" val } #' Calculate Posterior Mean and Uncertainty Via TMB `sdreport()` #' #' @param naomi_fit Fitted TMB model. #' #' @export report_tmb <- function(naomi_fit) { stopifnot(methods::is(fit, "naomi_fit")) naomi_fit$sdreport <- TMB::sdreport(naomi_fit$obj, naomi_fit$par, getReportCovariance = FALSE, bias.correct = TRUE) naomi_fit } #' Sample TMB fit #' #' @param fit The TMB fit #' @param nsample Number of samples #' @param rng_seed seed passed to set.seed. #' @param random_only Random only #' @param verbose If TRUE prints additional information. #' #' @return Sampled fit. #' @export sample_tmb <- function(fit, nsample = 1000, rng_seed = NULL, random_only = TRUE, verbose = FALSE) { set.seed(rng_seed) stopifnot(methods::is(fit, "naomi_fit")) stopifnot(nsample > 1) to_tape <- TMB:::isNullPointer(fit$obj$env$ADFun$ptr) if (to_tape) fit$obj$retape(FALSE) if(!random_only) { if(verbose) print("Calculating joint precision") hess <- sdreport_joint_precision(fit$obj, fit$par.fixed) if(verbose) print("Inverting precision for joint covariance") cov <- solve(hess) if(verbose) print("Drawing sample") ## TODO: write a version of rmvnorm that uses precision instead of covariance smp <- mvtnorm::rmvnorm(nsample, fit$par.full, cov) } else { r <- fit$obj$env$random par_f <- fit$par.full[-r] par_r <- fit$par.full[r] hess_r <- fit$obj$env$spHess(fit$par.full, random = TRUE) smp_r <- rmvnorm_sparseprec(nsample, par_r, hess_r) smp <- matrix(0, nsample, length(fit$par.full)) smp[ , r] <- smp_r smp[ ,-r] <- matrix(par_f, nsample, length(par_f), byrow = TRUE) colnames(smp)[r] <- colnames(smp_r) colnames(smp)[-r] <- names(par_f) } if(verbose) print("Simulating outputs") sim <- apply(smp, 1, fit$obj$report) r <- fit$obj$report() if(verbose) print("Returning sample") fit$sample <- Map(vapply, list(sim), "[[", lapply(lengths(r), numeric), names(r)) is_vector <- vapply(fit$sample, inherits, logical(1), "numeric") fit$sample[is_vector] <- lapply(fit$sample[is_vector], matrix, nrow = 1) names(fit$sample) <- names(r) fit } rmvnorm_sparseprec <- function( n, mean = rep(0, nrow(prec)), prec = diag(length(mean)) ) { z = matrix(stats::rnorm(n * length(mean)), ncol = n) L_inv = Matrix::Cholesky(prec) v <- mean + Matrix::solve(as(L_inv, "pMatrix"), Matrix::solve(Matrix::t(as(L_inv, "Matrix")), z)) as.matrix(Matrix::t(v)) } create_artattend_Amat <- function(artnum_df, age_groups, sexes, area_aggregation, df_art_attend, by_residence = FALSE, by_survey = FALSE) { ## If by_residence = TRUE, merge by reside_area_id, else aggregate over all ## reside_area_id by_vars <- c("attend_area_id", "sex", "age_group") if (by_residence) { by_vars <- c(by_vars, "reside_area_id") } id_vars <- by_vars if (by_survey) { id_vars <- c(id_vars, "survey_id") } if(!("artnum_idx" %in% colnames(artnum_df))) { artnum_df$artnum_idx <- seq_len(nrow(artnum_df)) } A_artnum <- artnum_df %>% dplyr::select(tidyselect::all_of(id_vars), artnum_idx) %>% dplyr::rename(artdat_age_group = age_group, artdat_sex = sex) %>% dplyr::left_join( get_age_groups() %>% dplyr::transmute( artdat_age_group = age_group, artdat_age_start = age_group_start, artdat_age_end = age_group_start + age_group_span ), by = "artdat_age_group" ) %>% ## Note: this would be much faster with tree data structure for age rather than crossing... tidyr::crossing( get_age_groups() %>% dplyr::filter(age_group %in% age_groups) ) %>% dplyr::filter( artdat_age_start <= age_group_start, age_group_start + age_group_span <= artdat_age_end ) %>% dplyr::left_join( data.frame(artdat_sex = c("male", "female", "both", "both", "both"), sex = c("male", "female", "male", "female", "both"), stringsAsFactors = FALSE) %>% dplyr::filter(sex %in% sexes), by = "artdat_sex", multiple = "all" ) ## Map artattend_area_id to model_area_id A_artnum <- A_artnum %>% dplyr::left_join( area_aggregation, by = c("attend_area_id" = "area_id"), multiple = "all" ) %>% dplyr::mutate(attend_area_id = model_area_id, model_area_id = NULL) ## Check no areas with duplicated reporting art_duplicated_check <- A_artnum %>% dplyr::group_by_at(id_vars) %>% dplyr::summarise(n = dplyr::n(), .groups = "drop") %>% dplyr::filter(n > 1) if (nrow(art_duplicated_check)) { stop(paste("ART or ANC data multiply reported for some age/sex strata in areas:", paste(unique(art_duplicated_check$attend_area_id), collapse = ", "))) } ## Merge to ART attendance data frame df_art_attend <- df_art_attend %>% dplyr::select(tidyselect::all_of(by_vars)) %>% dplyr::mutate( Aidx = dplyr::row_number(), value = 1 ) A_artnum <- dplyr::left_join(A_artnum, df_art_attend, by = by_vars, multiple = "all") A_artnum <- A_artnum %>% { Matrix::spMatrix(nrow(artnum_df), nrow(df_art_attend), .$artnum_idx, .$Aidx, .$value) } A_artnum }
######################################################## ## Power function, compute the stratified power-realted quantities ## ## Return values: ## TD: number of True Discoveries in each stratum ## FD: number of False Discoveries in each stratum ## power: within strata, proportion of TD out of total DE ## alpha.nomial: cutoff of alpha on raw p-values ## alpha: empirical p-value in each stratum ## alpha.marginal: overall empirical p-value ######################################################## PowerEst = function(fdr, alpha, Zg, Zg2, xgr){ ## p is input nominal p-value or FDR. ## alpha is cutoff of p ## !Zg is indicator for TN, Zg2 is indicators for TP, ## xgr is grouping in covariate ix.D = fdr <= alpha N = sum(ix.D) ## this is the total discovery N.stratified = tapply(ix.D, xgr, sum) ## TD (called DE genes) id.TP = Zg2==1 TD = tapply(fdr[id.TP] <= alpha, xgr[id.TP], sum) TD[is.na(TD)] = 0 ## FD id.TN = Zg==0 FD = tapply(fdr[id.TN] <= alpha, xgr[id.TN], sum) FD[is.na(FD)] = 0 ## type I error alpha = as.vector(FD/table(xgr[id.TN])) alpha.marginal = sum(FD)/sum(id.TN) ## power & precision power=as.vector(TD/table(xgr[id.TP])) power.marginal=sum(TD,na.rm=TRUE)/sum(id.TP) ## FDR FDR = FD / N.stratified FDR.marginal = sum(FD, na.rm=TRUE) / N ## conditional truths (true DE genes) CT = table(xgr[id.TP]) list(CD=TD,FD=FD,TD=CT,alpha.nominal=alpha, alpha=alpha, alpha.marginal=alpha.marginal, power=power, power.marginal=power.marginal, FDR=FDR, FDR.marginal=FDR.marginal) } #' Run DE analysis by using MAST. Here we output two result tables corresponding to two forms of DE genes. #' These parameters include four gene-wise parameters and two cell-wise parameters. #' #' @param DErslt is from the DE analysis by MAST #' @param simData is the corresponding simulated scRNA-seq dataset (SingCellExperiment) #' @param alpha is the cutoff for the fdr which can be modified #' @param delta or the lfc is the cutoff (=0.5) used to determined the high DE genes for Form II #' @param strata can be modified by the user. By default, it is (0, 10], (10, 20], (20, 40], (40, 80], (80, Inf] #' @return a list of metrics for power analysis such as: stratified targeted power and marginal power. #' @export Power_Cont ## Continous case corresponding to the Phase II DE, delta means lfc Power_Cont = function(DErslt, simData, alpha = 0.1, delta = 0.5, strata = c(0,10,2^(1:4)*10,Inf)){ fdrvec = DErslt$cont$fdr lfc = simData$lfc ngenes = nrow(simData$sce) DEid = simData$ix.DE2 Zg = Zg2 = rep(0, ngenes) Zg[DEid] = 1 ix = which(abs(lfc) > delta) Zg2[DEid[ix]] = 1 sce = simData$sce Y = round(assays(sce)[[1]]) # sizeF = colSums(Y) # sizeF = sizeF/median(sizeF) # X.bar = rowMeans(sweep(Y,2,sizeF,FUN="/")) X.bar = rowMeans(Y) ix.keep = which(X.bar>0) xgr = cut(X.bar[ix.keep], strata) # lev = levels(xgr) # ix.keep = ix.keep[!(xgr %in% lev[strata.filtered])] # ## recut # xgr = cut(X.bar[ix.keep], strata[-strata.filtered]) # Interested genes Zg = Zg[ix.keep]; Zg2 = Zg2[ix.keep] fdrvec = fdrvec[ix.keep] pow = PowerEst(fdrvec, alpha, Zg, Zg2, xgr=xgr) return(pow) } #' Run DE analysis by using MAST. Here we output two result tables corresponding to two forms of DE genes. #' These parameters include four gene-wise parameters and two cell-wise parameters. #' #' @param DErslt is from the DE analysis by MAST #' @param simData is the corresponding simulated scRNA-seq dataset (SingCellExperiment) #' @param alpha is the cutoff for the fdr which can be modified #' @param delta or the zero ratio change is the cutoff (=0.1) used to determined the high DE genes for Form II #' @param strata can be modified by the user. By default, it is (0, 0.2], (0.2, 0.4], (0.4, 0.6], (0.6, 0.8], (0.8, 1] #' @return a list of metrics for power analysis such as: stratified targeted power and marginal power. #' @export Power_Disc ## Discreate case corresponding to the Phase I DE, delta means pi.df Power_Disc = function(DErslt, simData, alpha = 0.1, delta = 0.1, strata = seq(0, 1, by = 0.2)){ fdrvec = DErslt$disc$fdr pi.df = simData$pi.df ngenes = nrow(simData$sce) DEid = simData$ix.DE1 Zg = Zg2 = rep(0, ngenes) Zg[DEid] = 1 ix = which(abs(pi.df) > delta) Zg2[DEid[ix]] = 1 sce = simData$sce ntotal = ncol(sce) Y = round(assays(sce)[[1]]) rate0 = rowMeans(Y==0) ix.keep = intersect(which(rate0 < 0.99), which(rate0 > 0.01)) # too small none 0 rate cannot detect xgr = cut(rate0[ix.keep], strata) # lev = levels(xgr) # ix.keep = ix.keep[!(xgr %in% lev[strata.filtered])] # ## recut # xgr = cut(X.bar[ix.keep], strata[-strata.filtered]) # Interested genes Zg = Zg[ix.keep]; Zg2 = Zg2[ix.keep] fdrvec = fdrvec[ix.keep] pow = PowerEst(fdrvec, alpha, Zg, Zg2, xgr=xgr) return(pow) }
/R/estPower.R
no_license
alaminzju/POWSC
R
false
false
5,070
r
######################################################## ## Power function, compute the stratified power-realted quantities ## ## Return values: ## TD: number of True Discoveries in each stratum ## FD: number of False Discoveries in each stratum ## power: within strata, proportion of TD out of total DE ## alpha.nomial: cutoff of alpha on raw p-values ## alpha: empirical p-value in each stratum ## alpha.marginal: overall empirical p-value ######################################################## PowerEst = function(fdr, alpha, Zg, Zg2, xgr){ ## p is input nominal p-value or FDR. ## alpha is cutoff of p ## !Zg is indicator for TN, Zg2 is indicators for TP, ## xgr is grouping in covariate ix.D = fdr <= alpha N = sum(ix.D) ## this is the total discovery N.stratified = tapply(ix.D, xgr, sum) ## TD (called DE genes) id.TP = Zg2==1 TD = tapply(fdr[id.TP] <= alpha, xgr[id.TP], sum) TD[is.na(TD)] = 0 ## FD id.TN = Zg==0 FD = tapply(fdr[id.TN] <= alpha, xgr[id.TN], sum) FD[is.na(FD)] = 0 ## type I error alpha = as.vector(FD/table(xgr[id.TN])) alpha.marginal = sum(FD)/sum(id.TN) ## power & precision power=as.vector(TD/table(xgr[id.TP])) power.marginal=sum(TD,na.rm=TRUE)/sum(id.TP) ## FDR FDR = FD / N.stratified FDR.marginal = sum(FD, na.rm=TRUE) / N ## conditional truths (true DE genes) CT = table(xgr[id.TP]) list(CD=TD,FD=FD,TD=CT,alpha.nominal=alpha, alpha=alpha, alpha.marginal=alpha.marginal, power=power, power.marginal=power.marginal, FDR=FDR, FDR.marginal=FDR.marginal) } #' Run DE analysis by using MAST. Here we output two result tables corresponding to two forms of DE genes. #' These parameters include four gene-wise parameters and two cell-wise parameters. #' #' @param DErslt is from the DE analysis by MAST #' @param simData is the corresponding simulated scRNA-seq dataset (SingCellExperiment) #' @param alpha is the cutoff for the fdr which can be modified #' @param delta or the lfc is the cutoff (=0.5) used to determined the high DE genes for Form II #' @param strata can be modified by the user. By default, it is (0, 10], (10, 20], (20, 40], (40, 80], (80, Inf] #' @return a list of metrics for power analysis such as: stratified targeted power and marginal power. #' @export Power_Cont ## Continous case corresponding to the Phase II DE, delta means lfc Power_Cont = function(DErslt, simData, alpha = 0.1, delta = 0.5, strata = c(0,10,2^(1:4)*10,Inf)){ fdrvec = DErslt$cont$fdr lfc = simData$lfc ngenes = nrow(simData$sce) DEid = simData$ix.DE2 Zg = Zg2 = rep(0, ngenes) Zg[DEid] = 1 ix = which(abs(lfc) > delta) Zg2[DEid[ix]] = 1 sce = simData$sce Y = round(assays(sce)[[1]]) # sizeF = colSums(Y) # sizeF = sizeF/median(sizeF) # X.bar = rowMeans(sweep(Y,2,sizeF,FUN="/")) X.bar = rowMeans(Y) ix.keep = which(X.bar>0) xgr = cut(X.bar[ix.keep], strata) # lev = levels(xgr) # ix.keep = ix.keep[!(xgr %in% lev[strata.filtered])] # ## recut # xgr = cut(X.bar[ix.keep], strata[-strata.filtered]) # Interested genes Zg = Zg[ix.keep]; Zg2 = Zg2[ix.keep] fdrvec = fdrvec[ix.keep] pow = PowerEst(fdrvec, alpha, Zg, Zg2, xgr=xgr) return(pow) } #' Run DE analysis by using MAST. Here we output two result tables corresponding to two forms of DE genes. #' These parameters include four gene-wise parameters and two cell-wise parameters. #' #' @param DErslt is from the DE analysis by MAST #' @param simData is the corresponding simulated scRNA-seq dataset (SingCellExperiment) #' @param alpha is the cutoff for the fdr which can be modified #' @param delta or the zero ratio change is the cutoff (=0.1) used to determined the high DE genes for Form II #' @param strata can be modified by the user. By default, it is (0, 0.2], (0.2, 0.4], (0.4, 0.6], (0.6, 0.8], (0.8, 1] #' @return a list of metrics for power analysis such as: stratified targeted power and marginal power. #' @export Power_Disc ## Discreate case corresponding to the Phase I DE, delta means pi.df Power_Disc = function(DErslt, simData, alpha = 0.1, delta = 0.1, strata = seq(0, 1, by = 0.2)){ fdrvec = DErslt$disc$fdr pi.df = simData$pi.df ngenes = nrow(simData$sce) DEid = simData$ix.DE1 Zg = Zg2 = rep(0, ngenes) Zg[DEid] = 1 ix = which(abs(pi.df) > delta) Zg2[DEid[ix]] = 1 sce = simData$sce ntotal = ncol(sce) Y = round(assays(sce)[[1]]) rate0 = rowMeans(Y==0) ix.keep = intersect(which(rate0 < 0.99), which(rate0 > 0.01)) # too small none 0 rate cannot detect xgr = cut(rate0[ix.keep], strata) # lev = levels(xgr) # ix.keep = ix.keep[!(xgr %in% lev[strata.filtered])] # ## recut # xgr = cut(X.bar[ix.keep], strata[-strata.filtered]) # Interested genes Zg = Zg[ix.keep]; Zg2 = Zg2[ix.keep] fdrvec = fdrvec[ix.keep] pow = PowerEst(fdrvec, alpha, Zg, Zg2, xgr=xgr) return(pow) }
### R programming: Programming assignment 2 - Catching the inverse of a matrix### ## As a way to make the inversion of a matrix more efficient, the next couple of functions ## store the result of this computation directly in the cache for subsequent fast recovery. ## makeCacheMatrix creates a list containing four elements is: the first element sets the ## values of a square invertible matrix, the next one gets these values, the third one sets ## the inverse of the matrix, while the last one stores this inverse matrix. makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y = matrix){ ## The operator <<- assigns y to x, which means x <<- y ## that if this variable is found in the parent m <<- NULL ## environment it will be assigned; otherwise, } ## the assigment takes place in the global environment. get <- function() x setInverse <- function(solve) m <<- solve getInverse <- function() m list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## The cacheSolve function verifies whether the inverse matrix of the matrix created with ## makeCacheMatrix has been calculated, in which case it will return a message indicating ## that is was recovered from the cache along with the value, without the need of doing it ## again. If this is not the case, the function will calculate the inverse with the 'solve' ## function and it will set the value in the cache for further usage. cacheSolve <- function(x, ...) { m <- x$getInverse() if(!is.null(m)){ ## The condition will look if there is already a value. message("Getting cached data") return(m) } data <- x$get() ## Otherwise, it will return a matrix that is the inverse of x. m <- solve(data, ...) x$setInverse(m) m }
/cachematrix.R
no_license
mruizvel/ProgrammingAssignment2
R
false
false
1,797
r
### R programming: Programming assignment 2 - Catching the inverse of a matrix### ## As a way to make the inversion of a matrix more efficient, the next couple of functions ## store the result of this computation directly in the cache for subsequent fast recovery. ## makeCacheMatrix creates a list containing four elements is: the first element sets the ## values of a square invertible matrix, the next one gets these values, the third one sets ## the inverse of the matrix, while the last one stores this inverse matrix. makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y = matrix){ ## The operator <<- assigns y to x, which means x <<- y ## that if this variable is found in the parent m <<- NULL ## environment it will be assigned; otherwise, } ## the assigment takes place in the global environment. get <- function() x setInverse <- function(solve) m <<- solve getInverse <- function() m list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## The cacheSolve function verifies whether the inverse matrix of the matrix created with ## makeCacheMatrix has been calculated, in which case it will return a message indicating ## that is was recovered from the cache along with the value, without the need of doing it ## again. If this is not the case, the function will calculate the inverse with the 'solve' ## function and it will set the value in the cache for further usage. cacheSolve <- function(x, ...) { m <- x$getInverse() if(!is.null(m)){ ## The condition will look if there is already a value. message("Getting cached data") return(m) } data <- x$get() ## Otherwise, it will return a matrix that is the inverse of x. m <- solve(data, ...) x$setInverse(m) m }
#' @name example5 #' @title Example 5: Transformation of treatment levels to improve model fit #' @description #' Mead (1988, p. 323) describes an experiment on spacing effects with turnips, #' which was laid out in three complete blocks. Five different seed rates #' (0.5, 2, 8, 20, 32 lb/acre) were tested in combination with four different row widths #' (4, 8, 16, 32 inches), giving rise to a total of 20 treatments. #' @details #' Transformation of the dependent variable will often stabilize the variance of the observations #' whereas transformation of the regressor variables will often simplify the fitted model. In this #' example, the fit of a regression model based on the original seed rate and row width variables is compared #' with the fit of a regression model based on the log transformed seed rates and log transformed row widths. #' In each case, the model lack-of-fit is examined by assessing the extra variability explained when the #' Density and Spacing treatment factors and their interactions are added to the quadratic regression models. #' All yields are logarithmically transformed to stabilize the variance. #' #' The first analysis fits a quadratic regression model of log yields on the untransformed seed rates and row #' widths (Table 16) while the second analysis fits a quadratic regression model of log yields on the log #' transformed seed rates and log transformed row widths (Table 17). The analysis of variance of the first model #' shows that significant extra variability is explained by the Density and #' Spacing factors and this shows that a quadratic regression model is inadequate for the untransformed regressor #' variables. The analysis of variance of the second model, however, shows no significant extra variability #' explained by the Density and Spacing factors and this shows that the quadratic regression model with the log #' transformed regressor variables gives a good fit to the data and therefore is the preferred model for the #' observed data. #' #' The superiority of the model with the log transformed regressor variables is confirmed by comparing the fit of the #' quadratic regression model for the untransformed regressor variables (Figs 8 and 9) versus the fit of the #' quadratic regression model for the log transformed regressor variables (Figs 10 and 11). #' #' Fig 12a shows diagnostic plots for the fit of a quadratic model with untransformed regressor variables #' while Fig 12b shows corresponding diagnostic plots for the fit of a quadratic model with #' loge transformed regressor variables. Each of the four types of diagnostic plots in the two figures #' shows an improvement in fit for the transformed versus the untransformed regressor variables. #' #' \code{\link[agriTutorial]{agriTutorial}}: return to home page if you want to select a different example \cr #' #' @references #' Mead, R. (1988). The design of experiments. Statistical principles for practical application. #' Cambridge: Cambridge University Press. #' #' Piepho, H. P, and Edmondson. R. N. (2018). A tutorial on the statistical analysis of factorial experiments with qualitative and quantitative #' treatment factor levels. Journal of Agronomy and Crop Science. DOI: 10.1111/jac.12267. #' \href{http://dx.doi.org/10.1111/jac.12267}{View} #' #' @examples #' #' ## ************************************************************************************* #' ## How to run the code #' ## ************************************************************************************* #' #' ## Either type example("example5") to run ALL the examples succesively #' ## or copy and paste examples sucessively, as required #' #' ## ************************************************************************************* #' ## Options and required packages #' ## ************************************************************************************* #' #' options(contrasts = c('contr.treatment', 'contr.poly')) #' require(lattice) #' #' ## ************************************************************************************* #' ## Quadratic regression models with and without transformation of regressor variables #' ## ************************************************************************************* #' #' RowSpacing = poly(turnip$rowspacing, 3, raw = TRUE) #' colnames(RowSpacing) = c("linSpacing", "quadSpacing", "cubSpacing") #' Density = poly(turnip$density, 4, raw = TRUE) #' colnames(Density) = c("linDensity", "quadDensity", "cubDensity", "quartDensity") #' turnip = cbind(turnip, Density, RowSpacing) #' #' ## Log transformed row spacing and density polynomials #' logRowSpacing = poly(log(turnip$rowspacing), 3, raw = TRUE) #' colnames(logRowSpacing) = c("linlogSpacing", "quadlogSpacing", "cublogSpacing") #' logDensity = poly(log(turnip$density), 4, raw = TRUE) #' colnames(logDensity) = c("linlogDensity", "quadlogDensity", "cublogDensity", "quartlogDensity") #' turnip = cbind(turnip, logDensity, logRowSpacing) #' #' ## Table 16 Quadratic response surface for untransformed planting density by row spacing model #' quad.mod = lm(log_yield ~ Replicate + linDensity * linSpacing + quadDensity + quadSpacing + #' Density * Spacing, turnip) #' anova(quad.mod) #' #' ## Table 17 Quadratic response surface for transformed log planting density by log row spacing #' log.quad.mod = lm(log_yield ~ Replicate + linlogDensity * linlogSpacing + #' quadlogDensity + quadlogSpacing + Density * Spacing, turnip) #' anova(log.quad.mod) #' #' ## ************************************************************************************* #' ## Quadratic regression model plots with and without transformations #' ## Averaged over replicate blocks to give mean of block effects #' ## ************************************************************************************* #' #' ## Quadratic response surface for untransformed planting density by row spacing model #' quad.mod = lm(log_yield ~ linDensity * linSpacing + quadDensity + quadSpacing , turnip) #' quad.mod$coefficients #' #' ## Fig 8 Plot of loge yield (lb/plot) versus row width #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' SeedDensity = c(0.5,2,8,20,32)[panel.number()] #' panel.curve(1.1146900855 + 0.0284788787 * x -0.0007748656 * x * x + 0.1564753713 *SeedDensity - #' 0.0033192569 * SeedDensity* SeedDensity -0.0006749985 * x * SeedDensity, #' from = 4, to = 32.0, type = "l", lwd = 2) #' } #' Seed_Rate=factor(turnip$linDensity) #' xyplot(log_yield ~ linSpacing|Seed_Rate, data = turnip, #' scales = list(x = list(at = c(10,20,30), labels = c(10,20,30))), #' main = "Fig 8: loge yield versus row width", #' xlab = " Row Width ", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("0.5", "2", "8", "20", "32")), #' panel = panel.plot) #' #' ## Fig 9 Plot of loge yield (lb/plot) versus seed rate #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' RowWidth = c(4, 8, 16, 32)[panel.number()] #' panel.curve(1.1146900855 + 0.1564753713 * x - 0.0033192569 * x * x + 0.0284788787 * RowWidth - #' 0.0007748656* RowWidth * RowWidth -0.0006749985 * x * RowWidth, #' from = 0.5, to = 32.0, type = "l", lwd = 2) #' } #' Row_Width=factor(turnip$linSpacing) #' xyplot(log_yield ~ linDensity|Row_Width, data = turnip, #' scales = list(x = list(at = c(0,10,20,30), labels = c(0,10,20,30))), #' main = "Fig 9: loge yield versus seed rate", #' xlab = " Seed Rate", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("4", "8", "16", "32")), #' panel = panel.plot) #' #' ## Quadratic response surface for log transformed planting density by log row spacing model #' log.quad.mod = lm(log_yield ~ linlogDensity * linlogSpacing + quadlogDensity + quadlogSpacing, #' turnip) #' log.quad.mod$coefficients #' ## Fig 10 Plot of loge yield (lb/plot) versus log row width #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' LogSeedDensity = c(-0.6931472,0.6931472,2.0794415,2.9957323,3.4657359)[panel.number()] #' panel.curve( 0.18414803 + 1.09137389 * x - 0.20987137 * x * x + 0.94207543 *LogSeedDensity - #' 0.10875560 * LogSeedDensity* LogSeedDensity -0.09440938 * x * LogSeedDensity, #' from = 1.35, to =3.50, type = "l", lwd = 2) #' } #' xyplot(log_yield ~ linlogSpacing|Seed_Rate, data = turnip, #' scales = list(x = list(at = c(1.5,2.0,2.5,3.0,3.5), labels = c(1.5,2.0,2.5,3.0,3.5))), #' main = "Fig 10: loge yield versus loge row width", #' xlab = " Loge Row Width ", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("0.5", "2", "8", "20", "32")), #' panel = panel.plot) #' #' ## Fig 11 Plot of loge yield (lb/plot) versus log seed rate #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' LogRowWidth = c(1.386294, 2.079442, 2.772589,3.465736)[panel.number()] #' panel.curve(0.18414803 + 0.94207543 * x -0.10875560 * x * x + 1.09137389* LogRowWidth - #' 0.20987137* LogRowWidth * LogRowWidth -0.09440938 * x * LogRowWidth, #' from = -0.7 , to = 3.5, type = "l", lwd = 2) #' } #' xyplot(log_yield ~ linlogDensity|Row_Width, data = turnip, #' scales = list(x = list(at = c(0,1,2,3),labels = c(0,1,2,3))), #' main = "Fig 11: loge yield versus loge seed rate", #' xlab = " Loge Seed Rate", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("4", "8", "16", "32")), #' panel = panel.plot) #' #' ## ************************************************************************************* #' ## Quadratic regression model diagnostic plots with and without transformations #' ## ************************************************************************************* #' #' ## graphical plots of untransformed data #' par(mfrow = c(2, 2), oma = c(0, 0, 2, 0)) #' fit.quad.mod = lm(log_yield ~ linDensity * linSpacing + quadDensity + quadSpacing, #' turnip) #' plot(fit.quad.mod, sub.caption = NA) #' title(main = "Fig 12a Diagnostics for untransformed sowing density and row spacing", outer = TRUE) #' #' ## graphical plots of log transformed data #' par(mfrow = c(2, 2), oma = c(0, 0, 2, 0)) #' fit.log.quad.mod = lm(log_yield ~ linlogDensity * linlogSpacing + quadlogDensity + #' quadlogSpacing, turnip) #' plot(fit.log.quad.mod, sub.caption = NA) #' title(main = "Fig 12b Diagnostics for log transformed sowing density and row spacing", outer = TRUE) #' NULL
/R/example5.R
no_license
cran/agriTutorial
R
false
false
10,553
r
#' @name example5 #' @title Example 5: Transformation of treatment levels to improve model fit #' @description #' Mead (1988, p. 323) describes an experiment on spacing effects with turnips, #' which was laid out in three complete blocks. Five different seed rates #' (0.5, 2, 8, 20, 32 lb/acre) were tested in combination with four different row widths #' (4, 8, 16, 32 inches), giving rise to a total of 20 treatments. #' @details #' Transformation of the dependent variable will often stabilize the variance of the observations #' whereas transformation of the regressor variables will often simplify the fitted model. In this #' example, the fit of a regression model based on the original seed rate and row width variables is compared #' with the fit of a regression model based on the log transformed seed rates and log transformed row widths. #' In each case, the model lack-of-fit is examined by assessing the extra variability explained when the #' Density and Spacing treatment factors and their interactions are added to the quadratic regression models. #' All yields are logarithmically transformed to stabilize the variance. #' #' The first analysis fits a quadratic regression model of log yields on the untransformed seed rates and row #' widths (Table 16) while the second analysis fits a quadratic regression model of log yields on the log #' transformed seed rates and log transformed row widths (Table 17). The analysis of variance of the first model #' shows that significant extra variability is explained by the Density and #' Spacing factors and this shows that a quadratic regression model is inadequate for the untransformed regressor #' variables. The analysis of variance of the second model, however, shows no significant extra variability #' explained by the Density and Spacing factors and this shows that the quadratic regression model with the log #' transformed regressor variables gives a good fit to the data and therefore is the preferred model for the #' observed data. #' #' The superiority of the model with the log transformed regressor variables is confirmed by comparing the fit of the #' quadratic regression model for the untransformed regressor variables (Figs 8 and 9) versus the fit of the #' quadratic regression model for the log transformed regressor variables (Figs 10 and 11). #' #' Fig 12a shows diagnostic plots for the fit of a quadratic model with untransformed regressor variables #' while Fig 12b shows corresponding diagnostic plots for the fit of a quadratic model with #' loge transformed regressor variables. Each of the four types of diagnostic plots in the two figures #' shows an improvement in fit for the transformed versus the untransformed regressor variables. #' #' \code{\link[agriTutorial]{agriTutorial}}: return to home page if you want to select a different example \cr #' #' @references #' Mead, R. (1988). The design of experiments. Statistical principles for practical application. #' Cambridge: Cambridge University Press. #' #' Piepho, H. P, and Edmondson. R. N. (2018). A tutorial on the statistical analysis of factorial experiments with qualitative and quantitative #' treatment factor levels. Journal of Agronomy and Crop Science. DOI: 10.1111/jac.12267. #' \href{http://dx.doi.org/10.1111/jac.12267}{View} #' #' @examples #' #' ## ************************************************************************************* #' ## How to run the code #' ## ************************************************************************************* #' #' ## Either type example("example5") to run ALL the examples succesively #' ## or copy and paste examples sucessively, as required #' #' ## ************************************************************************************* #' ## Options and required packages #' ## ************************************************************************************* #' #' options(contrasts = c('contr.treatment', 'contr.poly')) #' require(lattice) #' #' ## ************************************************************************************* #' ## Quadratic regression models with and without transformation of regressor variables #' ## ************************************************************************************* #' #' RowSpacing = poly(turnip$rowspacing, 3, raw = TRUE) #' colnames(RowSpacing) = c("linSpacing", "quadSpacing", "cubSpacing") #' Density = poly(turnip$density, 4, raw = TRUE) #' colnames(Density) = c("linDensity", "quadDensity", "cubDensity", "quartDensity") #' turnip = cbind(turnip, Density, RowSpacing) #' #' ## Log transformed row spacing and density polynomials #' logRowSpacing = poly(log(turnip$rowspacing), 3, raw = TRUE) #' colnames(logRowSpacing) = c("linlogSpacing", "quadlogSpacing", "cublogSpacing") #' logDensity = poly(log(turnip$density), 4, raw = TRUE) #' colnames(logDensity) = c("linlogDensity", "quadlogDensity", "cublogDensity", "quartlogDensity") #' turnip = cbind(turnip, logDensity, logRowSpacing) #' #' ## Table 16 Quadratic response surface for untransformed planting density by row spacing model #' quad.mod = lm(log_yield ~ Replicate + linDensity * linSpacing + quadDensity + quadSpacing + #' Density * Spacing, turnip) #' anova(quad.mod) #' #' ## Table 17 Quadratic response surface for transformed log planting density by log row spacing #' log.quad.mod = lm(log_yield ~ Replicate + linlogDensity * linlogSpacing + #' quadlogDensity + quadlogSpacing + Density * Spacing, turnip) #' anova(log.quad.mod) #' #' ## ************************************************************************************* #' ## Quadratic regression model plots with and without transformations #' ## Averaged over replicate blocks to give mean of block effects #' ## ************************************************************************************* #' #' ## Quadratic response surface for untransformed planting density by row spacing model #' quad.mod = lm(log_yield ~ linDensity * linSpacing + quadDensity + quadSpacing , turnip) #' quad.mod$coefficients #' #' ## Fig 8 Plot of loge yield (lb/plot) versus row width #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' SeedDensity = c(0.5,2,8,20,32)[panel.number()] #' panel.curve(1.1146900855 + 0.0284788787 * x -0.0007748656 * x * x + 0.1564753713 *SeedDensity - #' 0.0033192569 * SeedDensity* SeedDensity -0.0006749985 * x * SeedDensity, #' from = 4, to = 32.0, type = "l", lwd = 2) #' } #' Seed_Rate=factor(turnip$linDensity) #' xyplot(log_yield ~ linSpacing|Seed_Rate, data = turnip, #' scales = list(x = list(at = c(10,20,30), labels = c(10,20,30))), #' main = "Fig 8: loge yield versus row width", #' xlab = " Row Width ", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("0.5", "2", "8", "20", "32")), #' panel = panel.plot) #' #' ## Fig 9 Plot of loge yield (lb/plot) versus seed rate #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' RowWidth = c(4, 8, 16, 32)[panel.number()] #' panel.curve(1.1146900855 + 0.1564753713 * x - 0.0033192569 * x * x + 0.0284788787 * RowWidth - #' 0.0007748656* RowWidth * RowWidth -0.0006749985 * x * RowWidth, #' from = 0.5, to = 32.0, type = "l", lwd = 2) #' } #' Row_Width=factor(turnip$linSpacing) #' xyplot(log_yield ~ linDensity|Row_Width, data = turnip, #' scales = list(x = list(at = c(0,10,20,30), labels = c(0,10,20,30))), #' main = "Fig 9: loge yield versus seed rate", #' xlab = " Seed Rate", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("4", "8", "16", "32")), #' panel = panel.plot) #' #' ## Quadratic response surface for log transformed planting density by log row spacing model #' log.quad.mod = lm(log_yield ~ linlogDensity * linlogSpacing + quadlogDensity + quadlogSpacing, #' turnip) #' log.quad.mod$coefficients #' ## Fig 10 Plot of loge yield (lb/plot) versus log row width #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' LogSeedDensity = c(-0.6931472,0.6931472,2.0794415,2.9957323,3.4657359)[panel.number()] #' panel.curve( 0.18414803 + 1.09137389 * x - 0.20987137 * x * x + 0.94207543 *LogSeedDensity - #' 0.10875560 * LogSeedDensity* LogSeedDensity -0.09440938 * x * LogSeedDensity, #' from = 1.35, to =3.50, type = "l", lwd = 2) #' } #' xyplot(log_yield ~ linlogSpacing|Seed_Rate, data = turnip, #' scales = list(x = list(at = c(1.5,2.0,2.5,3.0,3.5), labels = c(1.5,2.0,2.5,3.0,3.5))), #' main = "Fig 10: loge yield versus loge row width", #' xlab = " Loge Row Width ", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("0.5", "2", "8", "20", "32")), #' panel = panel.plot) #' #' ## Fig 11 Plot of loge yield (lb/plot) versus log seed rate #' panel.plot = function(x, y) { #' panel.xyplot(x, y) # lattice plot shows observed points #' LogRowWidth = c(1.386294, 2.079442, 2.772589,3.465736)[panel.number()] #' panel.curve(0.18414803 + 0.94207543 * x -0.10875560 * x * x + 1.09137389* LogRowWidth - #' 0.20987137* LogRowWidth * LogRowWidth -0.09440938 * x * LogRowWidth, #' from = -0.7 , to = 3.5, type = "l", lwd = 2) #' } #' xyplot(log_yield ~ linlogDensity|Row_Width, data = turnip, #' scales = list(x = list(at = c(0,1,2,3),labels = c(0,1,2,3))), #' main = "Fig 11: loge yield versus loge seed rate", #' xlab = " Loge Seed Rate", ylab = "Loge yield ", #' strip = strip.custom(strip.names = TRUE, #' factor.levels = c("4", "8", "16", "32")), #' panel = panel.plot) #' #' ## ************************************************************************************* #' ## Quadratic regression model diagnostic plots with and without transformations #' ## ************************************************************************************* #' #' ## graphical plots of untransformed data #' par(mfrow = c(2, 2), oma = c(0, 0, 2, 0)) #' fit.quad.mod = lm(log_yield ~ linDensity * linSpacing + quadDensity + quadSpacing, #' turnip) #' plot(fit.quad.mod, sub.caption = NA) #' title(main = "Fig 12a Diagnostics for untransformed sowing density and row spacing", outer = TRUE) #' #' ## graphical plots of log transformed data #' par(mfrow = c(2, 2), oma = c(0, 0, 2, 0)) #' fit.log.quad.mod = lm(log_yield ~ linlogDensity * linlogSpacing + quadlogDensity + #' quadlogSpacing, turnip) #' plot(fit.log.quad.mod, sub.caption = NA) #' title(main = "Fig 12b Diagnostics for log transformed sowing density and row spacing", outer = TRUE) #' NULL
# ############################################################################################################ # ############################################# Dados simulados ############################################## # ############################################################################################################ # carregando dependencias source("dependencies.R",encoding = "UTF-8") # Amostrador de Gibbs para modelo linear bayesiano -------------------------- ############################ # Gerando a amostra ############################ set.seed(22-03-2018) x = c(8, 15, 22, 29, 36) xbarra = mean(x) x = x - xbarra n = 30 t = 5 alpha_c = 20 beta_c = 2 alpha = beta = NULL taualpha = 1/0.2 taubeta = 1/0.2 y = matrix(NA,n,t) tau = 1 e = matrix(rnorm(n*t,0,sqrt(1/tau)),n,t) for(i in 1:n){ alpha[i] = rnorm(1,alpha_c,sqrt(1/taualpha)) beta[i] = rnorm(1,beta_c,sqrt(1/taubeta)) for(j in 1:t){ y[i,j] = alpha[i] + beta[i]*x[j] + e[i,j] }} hist(y) ############################ # Parametros a Priori ############################ m.alpha = 0 V.alpha =1/0.0001 m.beta =0 V.beta =1/0.0001 a.tau =0.001 b.tau =0.001 a.alpha =0.001 b.alpha =0.001 a.beta =0.001 b.beta =0.001 ############################ # Valores da cadeia ############################ nsim = 150000 burnin = nsim/2 #Criando os objetos: cadeia.alpha.i = matrix(NA,nsim,n) cadeia.beta.i = matrix(NA,nsim,n) cadeia.tau.c = matrix(NA,nsim,1) cadeia.alpha.c = matrix(NA,nsim,1) cadeia.beta.c = matrix(NA,nsim,1) cadeia.tau.alpha = matrix(NA,nsim,1) cadeia.tau.beta = matrix(NA,nsim,1) #Chutes iniciais: cadeia.alpha.i[1,] = 0 cadeia.beta.i[1,] = 0 cadeia.tau.c[1,] = 1 cadeia.alpha.c[1,] = 0 cadeia.beta.c[1,] = 0 cadeia.tau.alpha[1,] = 1 cadeia.tau.beta[1,] = 1 # Obs.: Indice da cadeia sera k # ---------------------------------------------------------------------------------- ############################ # Algoritimo da cadeia ############################ # Sementes: set.seed(1) #Criar uma barra de processo e acompanhar o carregamento: pb <- txtProgressBar(min = 0, max = nsim, style = 3);antes = Sys.time() for(k in 2:nsim){ soma = 0 #Cadeia alpha.i e beta.i for(i in 1:n){ dccp.tau.alpha = 1 / ((t*cadeia.tau.c[k-1]) + cadeia.tau.alpha[k-1]) dccp.alpha.c = ( cadeia.tau.c[k-1]*sum( y[i,] - cadeia.beta.i[k-1,i]*x ) + cadeia.tau.alpha[k-1]*cadeia.alpha.c[k-1] ) * dccp.tau.alpha cadeia.alpha.i[k,i] = rnorm(1,dccp.alpha.c,sqrt(dccp.tau.alpha)) dccp.tau.beta = 1 / ((cadeia.tau.c[k-1]*sum(x^2)) + cadeia.tau.beta[k-1]) u = (y[i,]-cadeia.alpha.i[k,i])*x dccp.beta.c = (cadeia.tau.c[k-1]*sum(u) + (cadeia.tau.beta[k-1]*cadeia.beta.c[k-1])) * dccp.tau.beta cadeia.beta.i[k,i] = rnorm(1,dccp.beta.c,sqrt(dccp.tau.beta)) for(j in 1:t){soma = soma + (y[i,j] - cadeia.alpha.i[k,i]-cadeia.beta.i[k,i]*x[j])^2} } # cadeia de tau dccp.a = ((n*t)/2) + a.tau dccp.beta = b.tau + 0.5 * soma cadeia.tau.c[k] = rgamma(1,dccp.a,dccp.beta) #cadeia.tau.c[k] = tau #cadeia de tau.alpha dccp.a.alpha = (n/2) + a.alpha dccp.b.alpha = b.alpha + 0.5 * sum((cadeia.alpha.i[k,]-cadeia.alpha.c[k-1,])^2) cadeia.tau.alpha[k] = rgamma(1,dccp.a.alpha,dccp.b.alpha) #cadeia.tau.alpha[k] = taualpha #cadeia de tau.beta dccp.a.beta = (n/2) + a.beta dccp.b.beta = b.beta + 0.5 * sum((cadeia.beta.i[k,]-cadeia.beta.c[k-1,])^2) cadeia.tau.beta[k] = rgamma(1,dccp.a.beta,dccp.b.beta) #cadeia.tau.beta[k] = taubeta #Cadeia de alpha.c dccp.V.alpha = 1 / (n*cadeia.tau.alpha[k] + 1/V.alpha) dccp.m.alpha = (cadeia.tau.alpha[k] * sum(cadeia.alpha.i[k,]) + m.alpha/V.alpha) * dccp.V.alpha cadeia.alpha.c[k] = rnorm(1,dccp.m.alpha,sqrt(dccp.V.alpha)) #cadeia.alpha.c[k] = alpha_c #Cadeia de beta.c dccp.V.beta = 1 / (n*cadeia.tau.beta[k] + 1/V.beta) dccp.m.beta = (cadeia.tau.beta[k] * sum(cadeia.beta.i[k,]) + m.beta/V.beta) * dccp.V.beta cadeia.beta.c[k] = rnorm(1,dccp.m.beta,sqrt(dccp.V.beta)) #cadeia.beta.c[k] = beta_c # update barra de processo setTxtProgressBar(pb, k) }; close(pb); depois = Sys.time() - antes; depois #Encerrando barra de processo e tempo da cadeia ############################ # Resultados da cadeia ############################ # Juntando resultados: inds = seq(burnin,nsim,50) results <- cbind(cadeia.alpha.c, cadeia.beta.c, cadeia.tau.c, cadeia.tau.alpha, cadeia.tau.beta) %>% as.data.frame() %>% .[inds,] real <- c(alpha_c,beta_c,tau,taualpha,taubeta) name <- c(expression(alpha[c]), expression(beta[c]), expression(tau[c]), expression(tau[alpha]), expression(tau[beta])) # Cadeia png("imagens/cadeia_hierarquica_sim.png",1100,1000) cadeia(results,name,real) dev.off() # Histograma e densidade png("imagens/hist_hierarquica_sim.png",830,610) g1 <- hist_den(results[,1],name = name[1], p = real[1]) g2 <- hist_den(results[,2],name = name[2], p = real[2]) g3 <- hist_den(results[,3],name = name[3], p = real[3]) g4 <- hist_den(results[,4],name = name[4], p = real[4]) g5 <- hist_den(results[,5],name = name[5], p = real[5]) grid.arrange(g1,g2,g3,g4,g5,ncol=1) dev.off() # ACF png("imagens/acf_hierarquica_sim.png",1000,610) FAC(results) dev.off() # Coeficientes: coeficientes <- coeficientes_hierarquico(cadeia.alpha.i[inds,],alpha, cadeia.beta.i[inds,], beta, cadeia.alpha.c, alpha_c, cadeia.beta.c, beta_c, cadeia.tau.c,tau, cadeia.tau.alpha, taualpha, cadeia.tau.beta, taubeta, ncol(results)+60 ) # sumario: sumario <- coeficientes[[1]];sumario # credibilidade: tab <- coeficientes[[2]];tab tab %>% tail(5) %>% .[,c(1,3,4)] %>% cbind(sd = results %>% apply(2,sd) %>% round(4)) %>% xtable() # Com GGPLOT para o texto ------------------------------------------------- ############## # Para alpha # ############## png("imagens/caterplot_a_hierarquica_sim.png",800,600) cbind(alpha=1:30,tab[1:30,])%>% as.data.frame%>% ggplot( aes(x=alpha, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + # geom_line(position=pd) + geom_point(aes(x=alpha,y=`Param. Pop.`),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle xlab("Cadeia de alpha") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[1:30,1]),max(tab[1:30,4])),breaks=seq(min(tab[1:30,1]),max(tab[1:30,4]),0.2)) + # Set tick every 4 theme_bw()+ geom_hline(yintercept = alpha_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() ############## # Para beta # ############## png("imagens/caterplot_b_hierarquica_sim.png",800,600) cbind(beta=31:60,tab[31:60,])%>% as.data.frame%>% ggplot( aes(x=beta, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle geom_point(aes(x=beta,y=`Param. Pop.`),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle # geom_line(position=pd) + xlab("Cadeia de beta") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[31:60,1]),max(tab[31:60,4])),breaks=seq(min(tab[31:60,1]),max(tab[31:60,4]),0.2)) + # Set tick every 4 theme_bw()+ geom_hline(yintercept = beta_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() # ############################################################################################################ # ############################################# Dados reais ############################################## # ############################################################################################################ # Amostrador de Gibbs para modelo linear bayesiano -------------------------- ############################ # Amostra utilizada ############################ rats = read.table("rats.txt",header=T) y=rats x=c(8, 15, 22, 29, 36) xbarra=mean(x) x=x-xbarra n=nrow(y) t=ncol(y) ############################ # Parametros a Priori ############################ m.alpha = 0 V.alpha =1/0.0001 m.beta =0 V.beta =1/0.0001 a.tau =0.001 b.tau =0.001 a.alpha =0.001 b.alpha =0.001 a.beta =0.001 b.beta =0.001 ############################ # Valores da cadeia ############################ nsim = 50000 burnin = nsim/3 #Criando os objetos: cadeia.alpha.i = matrix(NA,nsim,n) cadeia.beta.i = matrix(NA,nsim,n) cadeia.tau.c = matrix(NA,nsim,1) cadeia.alpha.c = matrix(NA,nsim,1) cadeia.beta.c = matrix(NA,nsim,1) cadeia.tau.alpha = matrix(NA,nsim,1) cadeia.tau.beta = matrix(NA,nsim,1) #Chutes iniciais: cadeia.alpha.i[1,] = 0 cadeia.beta.i[1,] = 0 cadeia.tau.c[1,] = 1 cadeia.alpha.c[1,] = 0 cadeia.beta.c[1,] = 0 cadeia.tau.alpha[1,] = 1 cadeia.tau.beta[1,] = 1 # Obs.: Indice da cadeia sera k # ---------------------------------------------------------------------------------- ############################ # Algoritimo da cadeia ############################ # Sementes: set.seed(1) #Criar uma barra de processo e acompanhar o carregamento: pb <- txtProgressBar(min = 0, max = nsim, style = 3);antes = Sys.time() for(k in 2:nsim){ soma = 0 #Cadeia alpha.i e beta.i for(i in 1:n){ dccp.tau.alpha = 1 / ((t*cadeia.tau.c[k-1]) + cadeia.tau.alpha[k-1]) dccp.alpha.c = ( cadeia.tau.c[k-1]*sum( y[i,] - cadeia.beta.i[k-1,i]*x ) + cadeia.tau.alpha[k-1]*cadeia.alpha.c[k-1] ) * dccp.tau.alpha cadeia.alpha.i[k,i] = rnorm(1,dccp.alpha.c,sqrt(dccp.tau.alpha)) dccp.tau.beta = 1 / ((cadeia.tau.c[k-1]*sum(x^2)) + cadeia.tau.beta[k-1]) u = (y[i,]-cadeia.alpha.i[k,i])*x dccp.beta.c = (cadeia.tau.c[k-1]*sum(u) + (cadeia.tau.beta[k-1]*cadeia.beta.c[k-1])) * dccp.tau.beta cadeia.beta.i[k,i] = rnorm(1,dccp.beta.c,sqrt(dccp.tau.beta)) for(j in 1:t){soma = soma + (y[i,j] - cadeia.alpha.i[k,i]-cadeia.beta.i[k,i]*x[j])^2} } # cadeia de tau dccp.a = ((n*t)/2) + a.tau dccp.beta = b.tau + 0.5 * soma cadeia.tau.c[k] = rgamma(1,dccp.a,dccp.beta) #cadeia.tau.c[k] = tau #cadeia de tau.alpha dccp.a.alpha = (n/2) + a.alpha dccp.b.alpha = b.alpha + 0.5 * sum((cadeia.alpha.i[k,]-cadeia.alpha.c[k-1,])^2) cadeia.tau.alpha[k] = rgamma(1,dccp.a.alpha,dccp.b.alpha) #cadeia.tau.alpha[k] = taualpha #cadeia de tau.beta dccp.a.beta = (n/2) + a.beta dccp.b.beta = b.beta + 0.5 * sum((cadeia.beta.i[k,]-cadeia.beta.c[k-1,])^2) cadeia.tau.beta[k] = rgamma(1,dccp.a.beta,dccp.b.beta) #cadeia.tau.beta[k] = taubeta #Cadeia de alpha.c dccp.V.alpha = 1 / (n*cadeia.tau.alpha[k] + 1/V.alpha) dccp.m.alpha = (cadeia.tau.alpha[k] * sum(cadeia.alpha.i[k,]) + m.alpha/V.alpha) * dccp.V.alpha cadeia.alpha.c[k] = rnorm(1,dccp.m.alpha,sqrt(dccp.V.alpha)) #cadeia.alpha.c[k] = alpha_c #Cadeia de beta.c dccp.V.beta = 1 / (n*cadeia.tau.beta[k] + 1/V.beta) dccp.m.beta = (cadeia.tau.beta[k] * sum(cadeia.beta.i[k,]) + m.beta/V.beta) * dccp.V.beta cadeia.beta.c[k] = rnorm(1,dccp.m.beta,sqrt(dccp.V.beta)) #cadeia.beta.c[k] = beta_c # update barra de processo setTxtProgressBar(pb, k) }; close(pb); depois = Sys.time() - antes; depois #Encerrando barra de processo e tempo da cadeia ############################ # Resultados da cadeia ############################ # Juntando resultados: inds = seq(burnin,nsim,50) results <- cbind(cadeia.alpha.c, cadeia.beta.c, cadeia.tau.c, cadeia.tau.alpha, cadeia.tau.beta) %>% as.data.frame() %>% .[inds,] name <- c(expression(alpha[c]), expression(beta[c]), expression(tau[c]), expression(tau[alpha]), expression(tau[beta])) # Cadeia png("imagens/cadeia_hierarquica_rats.png",830,610) cadeia(results,name) dev.off() # Histograma e densidade png("imagens/hist_hierarquica_rats.png",830,610) g1 <- hist_den(results[,1],name = name[1]) g2 <- hist_den(results[,2],name = name[2]) g3 <- hist_den(results[,3],name = name[3]) g4 <- hist_den(results[,4],name = name[4]) g5 <- hist_den(results[,5],name = name[5]) grid.arrange(g1,g2,g3,g4,g5,ncol=1) dev.off() # ACF png("imagens/acf_hierarquica_rats.png",1000,610) FAC(results) dev.off() ################### # continuar aqui ################## # Coeficientes: coeficientes <- coeficientes_hierarquico2(cadeia.alpha.i[inds,], cadeia.beta.i[inds,], cadeia.alpha.c, cadeia.beta.c, cadeia.tau.c, cadeia.tau.alpha, cadeia.tau.beta, ncol(results)+60 ) # sumario: sumario <- coeficientes[[1]];sumario # credibilidade: tab <- coeficientes[[2]];tab tab %>% tail(5) %>% cbind(sd = results %>% apply(2,sd) %>% round(4)) %>% xtable() # Com GGPLOT para o texto ------------------------------------------------- ############## # Para alpha # ############## png("imagens/caterplot_a_hierarquica_rats.png",800,600) cbind(alpha=1:30,tab[1:30,])%>% as.data.frame%>% ggplot( aes(x=alpha, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + # geom_line(position=pd) + geom_point(aes(x=alpha,y=Média),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle xlab("Cadeia de alpha") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[1:30,1]),max(tab[1:30,3]))) + # Set tick every 4 scale_x_continuous(breaks = seq(1,30,1)) + # Set tick every 4 theme_bw() # + # geom_hline(yintercept = alpha_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), # axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() ############## # Para beta # ############## png("imagens/caterplot_b_hierarquica_rats.png",800,600) cbind(beta=1:30,tab[31:60,])%>% as.data.frame%>% ggplot( aes(x=beta, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + # geom_line(position=pd) + geom_point(aes(x=beta,y=Média),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle xlab("Cadeia de beta") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[31:60,1]),max(tab[31:60,3]))) + # Set tick every 4 scale_x_continuous(breaks = seq(1,30,1)) + # Set tick every 4 theme_bw() # + # geom_hline(yintercept = beta_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), # axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() tab
/modelo linear hierarquico bayesiano com dados simulados e rats.R
no_license
gomesfellipe/projeto_modelos_hierarquicos_bayesianos
R
false
false
18,743
r
# ############################################################################################################ # ############################################# Dados simulados ############################################## # ############################################################################################################ # carregando dependencias source("dependencies.R",encoding = "UTF-8") # Amostrador de Gibbs para modelo linear bayesiano -------------------------- ############################ # Gerando a amostra ############################ set.seed(22-03-2018) x = c(8, 15, 22, 29, 36) xbarra = mean(x) x = x - xbarra n = 30 t = 5 alpha_c = 20 beta_c = 2 alpha = beta = NULL taualpha = 1/0.2 taubeta = 1/0.2 y = matrix(NA,n,t) tau = 1 e = matrix(rnorm(n*t,0,sqrt(1/tau)),n,t) for(i in 1:n){ alpha[i] = rnorm(1,alpha_c,sqrt(1/taualpha)) beta[i] = rnorm(1,beta_c,sqrt(1/taubeta)) for(j in 1:t){ y[i,j] = alpha[i] + beta[i]*x[j] + e[i,j] }} hist(y) ############################ # Parametros a Priori ############################ m.alpha = 0 V.alpha =1/0.0001 m.beta =0 V.beta =1/0.0001 a.tau =0.001 b.tau =0.001 a.alpha =0.001 b.alpha =0.001 a.beta =0.001 b.beta =0.001 ############################ # Valores da cadeia ############################ nsim = 150000 burnin = nsim/2 #Criando os objetos: cadeia.alpha.i = matrix(NA,nsim,n) cadeia.beta.i = matrix(NA,nsim,n) cadeia.tau.c = matrix(NA,nsim,1) cadeia.alpha.c = matrix(NA,nsim,1) cadeia.beta.c = matrix(NA,nsim,1) cadeia.tau.alpha = matrix(NA,nsim,1) cadeia.tau.beta = matrix(NA,nsim,1) #Chutes iniciais: cadeia.alpha.i[1,] = 0 cadeia.beta.i[1,] = 0 cadeia.tau.c[1,] = 1 cadeia.alpha.c[1,] = 0 cadeia.beta.c[1,] = 0 cadeia.tau.alpha[1,] = 1 cadeia.tau.beta[1,] = 1 # Obs.: Indice da cadeia sera k # ---------------------------------------------------------------------------------- ############################ # Algoritimo da cadeia ############################ # Sementes: set.seed(1) #Criar uma barra de processo e acompanhar o carregamento: pb <- txtProgressBar(min = 0, max = nsim, style = 3);antes = Sys.time() for(k in 2:nsim){ soma = 0 #Cadeia alpha.i e beta.i for(i in 1:n){ dccp.tau.alpha = 1 / ((t*cadeia.tau.c[k-1]) + cadeia.tau.alpha[k-1]) dccp.alpha.c = ( cadeia.tau.c[k-1]*sum( y[i,] - cadeia.beta.i[k-1,i]*x ) + cadeia.tau.alpha[k-1]*cadeia.alpha.c[k-1] ) * dccp.tau.alpha cadeia.alpha.i[k,i] = rnorm(1,dccp.alpha.c,sqrt(dccp.tau.alpha)) dccp.tau.beta = 1 / ((cadeia.tau.c[k-1]*sum(x^2)) + cadeia.tau.beta[k-1]) u = (y[i,]-cadeia.alpha.i[k,i])*x dccp.beta.c = (cadeia.tau.c[k-1]*sum(u) + (cadeia.tau.beta[k-1]*cadeia.beta.c[k-1])) * dccp.tau.beta cadeia.beta.i[k,i] = rnorm(1,dccp.beta.c,sqrt(dccp.tau.beta)) for(j in 1:t){soma = soma + (y[i,j] - cadeia.alpha.i[k,i]-cadeia.beta.i[k,i]*x[j])^2} } # cadeia de tau dccp.a = ((n*t)/2) + a.tau dccp.beta = b.tau + 0.5 * soma cadeia.tau.c[k] = rgamma(1,dccp.a,dccp.beta) #cadeia.tau.c[k] = tau #cadeia de tau.alpha dccp.a.alpha = (n/2) + a.alpha dccp.b.alpha = b.alpha + 0.5 * sum((cadeia.alpha.i[k,]-cadeia.alpha.c[k-1,])^2) cadeia.tau.alpha[k] = rgamma(1,dccp.a.alpha,dccp.b.alpha) #cadeia.tau.alpha[k] = taualpha #cadeia de tau.beta dccp.a.beta = (n/2) + a.beta dccp.b.beta = b.beta + 0.5 * sum((cadeia.beta.i[k,]-cadeia.beta.c[k-1,])^2) cadeia.tau.beta[k] = rgamma(1,dccp.a.beta,dccp.b.beta) #cadeia.tau.beta[k] = taubeta #Cadeia de alpha.c dccp.V.alpha = 1 / (n*cadeia.tau.alpha[k] + 1/V.alpha) dccp.m.alpha = (cadeia.tau.alpha[k] * sum(cadeia.alpha.i[k,]) + m.alpha/V.alpha) * dccp.V.alpha cadeia.alpha.c[k] = rnorm(1,dccp.m.alpha,sqrt(dccp.V.alpha)) #cadeia.alpha.c[k] = alpha_c #Cadeia de beta.c dccp.V.beta = 1 / (n*cadeia.tau.beta[k] + 1/V.beta) dccp.m.beta = (cadeia.tau.beta[k] * sum(cadeia.beta.i[k,]) + m.beta/V.beta) * dccp.V.beta cadeia.beta.c[k] = rnorm(1,dccp.m.beta,sqrt(dccp.V.beta)) #cadeia.beta.c[k] = beta_c # update barra de processo setTxtProgressBar(pb, k) }; close(pb); depois = Sys.time() - antes; depois #Encerrando barra de processo e tempo da cadeia ############################ # Resultados da cadeia ############################ # Juntando resultados: inds = seq(burnin,nsim,50) results <- cbind(cadeia.alpha.c, cadeia.beta.c, cadeia.tau.c, cadeia.tau.alpha, cadeia.tau.beta) %>% as.data.frame() %>% .[inds,] real <- c(alpha_c,beta_c,tau,taualpha,taubeta) name <- c(expression(alpha[c]), expression(beta[c]), expression(tau[c]), expression(tau[alpha]), expression(tau[beta])) # Cadeia png("imagens/cadeia_hierarquica_sim.png",1100,1000) cadeia(results,name,real) dev.off() # Histograma e densidade png("imagens/hist_hierarquica_sim.png",830,610) g1 <- hist_den(results[,1],name = name[1], p = real[1]) g2 <- hist_den(results[,2],name = name[2], p = real[2]) g3 <- hist_den(results[,3],name = name[3], p = real[3]) g4 <- hist_den(results[,4],name = name[4], p = real[4]) g5 <- hist_den(results[,5],name = name[5], p = real[5]) grid.arrange(g1,g2,g3,g4,g5,ncol=1) dev.off() # ACF png("imagens/acf_hierarquica_sim.png",1000,610) FAC(results) dev.off() # Coeficientes: coeficientes <- coeficientes_hierarquico(cadeia.alpha.i[inds,],alpha, cadeia.beta.i[inds,], beta, cadeia.alpha.c, alpha_c, cadeia.beta.c, beta_c, cadeia.tau.c,tau, cadeia.tau.alpha, taualpha, cadeia.tau.beta, taubeta, ncol(results)+60 ) # sumario: sumario <- coeficientes[[1]];sumario # credibilidade: tab <- coeficientes[[2]];tab tab %>% tail(5) %>% .[,c(1,3,4)] %>% cbind(sd = results %>% apply(2,sd) %>% round(4)) %>% xtable() # Com GGPLOT para o texto ------------------------------------------------- ############## # Para alpha # ############## png("imagens/caterplot_a_hierarquica_sim.png",800,600) cbind(alpha=1:30,tab[1:30,])%>% as.data.frame%>% ggplot( aes(x=alpha, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + # geom_line(position=pd) + geom_point(aes(x=alpha,y=`Param. Pop.`),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle xlab("Cadeia de alpha") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[1:30,1]),max(tab[1:30,4])),breaks=seq(min(tab[1:30,1]),max(tab[1:30,4]),0.2)) + # Set tick every 4 theme_bw()+ geom_hline(yintercept = alpha_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() ############## # Para beta # ############## png("imagens/caterplot_b_hierarquica_sim.png",800,600) cbind(beta=31:60,tab[31:60,])%>% as.data.frame%>% ggplot( aes(x=beta, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle geom_point(aes(x=beta,y=`Param. Pop.`),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle # geom_line(position=pd) + xlab("Cadeia de beta") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[31:60,1]),max(tab[31:60,4])),breaks=seq(min(tab[31:60,1]),max(tab[31:60,4]),0.2)) + # Set tick every 4 theme_bw()+ geom_hline(yintercept = beta_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() # ############################################################################################################ # ############################################# Dados reais ############################################## # ############################################################################################################ # Amostrador de Gibbs para modelo linear bayesiano -------------------------- ############################ # Amostra utilizada ############################ rats = read.table("rats.txt",header=T) y=rats x=c(8, 15, 22, 29, 36) xbarra=mean(x) x=x-xbarra n=nrow(y) t=ncol(y) ############################ # Parametros a Priori ############################ m.alpha = 0 V.alpha =1/0.0001 m.beta =0 V.beta =1/0.0001 a.tau =0.001 b.tau =0.001 a.alpha =0.001 b.alpha =0.001 a.beta =0.001 b.beta =0.001 ############################ # Valores da cadeia ############################ nsim = 50000 burnin = nsim/3 #Criando os objetos: cadeia.alpha.i = matrix(NA,nsim,n) cadeia.beta.i = matrix(NA,nsim,n) cadeia.tau.c = matrix(NA,nsim,1) cadeia.alpha.c = matrix(NA,nsim,1) cadeia.beta.c = matrix(NA,nsim,1) cadeia.tau.alpha = matrix(NA,nsim,1) cadeia.tau.beta = matrix(NA,nsim,1) #Chutes iniciais: cadeia.alpha.i[1,] = 0 cadeia.beta.i[1,] = 0 cadeia.tau.c[1,] = 1 cadeia.alpha.c[1,] = 0 cadeia.beta.c[1,] = 0 cadeia.tau.alpha[1,] = 1 cadeia.tau.beta[1,] = 1 # Obs.: Indice da cadeia sera k # ---------------------------------------------------------------------------------- ############################ # Algoritimo da cadeia ############################ # Sementes: set.seed(1) #Criar uma barra de processo e acompanhar o carregamento: pb <- txtProgressBar(min = 0, max = nsim, style = 3);antes = Sys.time() for(k in 2:nsim){ soma = 0 #Cadeia alpha.i e beta.i for(i in 1:n){ dccp.tau.alpha = 1 / ((t*cadeia.tau.c[k-1]) + cadeia.tau.alpha[k-1]) dccp.alpha.c = ( cadeia.tau.c[k-1]*sum( y[i,] - cadeia.beta.i[k-1,i]*x ) + cadeia.tau.alpha[k-1]*cadeia.alpha.c[k-1] ) * dccp.tau.alpha cadeia.alpha.i[k,i] = rnorm(1,dccp.alpha.c,sqrt(dccp.tau.alpha)) dccp.tau.beta = 1 / ((cadeia.tau.c[k-1]*sum(x^2)) + cadeia.tau.beta[k-1]) u = (y[i,]-cadeia.alpha.i[k,i])*x dccp.beta.c = (cadeia.tau.c[k-1]*sum(u) + (cadeia.tau.beta[k-1]*cadeia.beta.c[k-1])) * dccp.tau.beta cadeia.beta.i[k,i] = rnorm(1,dccp.beta.c,sqrt(dccp.tau.beta)) for(j in 1:t){soma = soma + (y[i,j] - cadeia.alpha.i[k,i]-cadeia.beta.i[k,i]*x[j])^2} } # cadeia de tau dccp.a = ((n*t)/2) + a.tau dccp.beta = b.tau + 0.5 * soma cadeia.tau.c[k] = rgamma(1,dccp.a,dccp.beta) #cadeia.tau.c[k] = tau #cadeia de tau.alpha dccp.a.alpha = (n/2) + a.alpha dccp.b.alpha = b.alpha + 0.5 * sum((cadeia.alpha.i[k,]-cadeia.alpha.c[k-1,])^2) cadeia.tau.alpha[k] = rgamma(1,dccp.a.alpha,dccp.b.alpha) #cadeia.tau.alpha[k] = taualpha #cadeia de tau.beta dccp.a.beta = (n/2) + a.beta dccp.b.beta = b.beta + 0.5 * sum((cadeia.beta.i[k,]-cadeia.beta.c[k-1,])^2) cadeia.tau.beta[k] = rgamma(1,dccp.a.beta,dccp.b.beta) #cadeia.tau.beta[k] = taubeta #Cadeia de alpha.c dccp.V.alpha = 1 / (n*cadeia.tau.alpha[k] + 1/V.alpha) dccp.m.alpha = (cadeia.tau.alpha[k] * sum(cadeia.alpha.i[k,]) + m.alpha/V.alpha) * dccp.V.alpha cadeia.alpha.c[k] = rnorm(1,dccp.m.alpha,sqrt(dccp.V.alpha)) #cadeia.alpha.c[k] = alpha_c #Cadeia de beta.c dccp.V.beta = 1 / (n*cadeia.tau.beta[k] + 1/V.beta) dccp.m.beta = (cadeia.tau.beta[k] * sum(cadeia.beta.i[k,]) + m.beta/V.beta) * dccp.V.beta cadeia.beta.c[k] = rnorm(1,dccp.m.beta,sqrt(dccp.V.beta)) #cadeia.beta.c[k] = beta_c # update barra de processo setTxtProgressBar(pb, k) }; close(pb); depois = Sys.time() - antes; depois #Encerrando barra de processo e tempo da cadeia ############################ # Resultados da cadeia ############################ # Juntando resultados: inds = seq(burnin,nsim,50) results <- cbind(cadeia.alpha.c, cadeia.beta.c, cadeia.tau.c, cadeia.tau.alpha, cadeia.tau.beta) %>% as.data.frame() %>% .[inds,] name <- c(expression(alpha[c]), expression(beta[c]), expression(tau[c]), expression(tau[alpha]), expression(tau[beta])) # Cadeia png("imagens/cadeia_hierarquica_rats.png",830,610) cadeia(results,name) dev.off() # Histograma e densidade png("imagens/hist_hierarquica_rats.png",830,610) g1 <- hist_den(results[,1],name = name[1]) g2 <- hist_den(results[,2],name = name[2]) g3 <- hist_den(results[,3],name = name[3]) g4 <- hist_den(results[,4],name = name[4]) g5 <- hist_den(results[,5],name = name[5]) grid.arrange(g1,g2,g3,g4,g5,ncol=1) dev.off() # ACF png("imagens/acf_hierarquica_rats.png",1000,610) FAC(results) dev.off() ################### # continuar aqui ################## # Coeficientes: coeficientes <- coeficientes_hierarquico2(cadeia.alpha.i[inds,], cadeia.beta.i[inds,], cadeia.alpha.c, cadeia.beta.c, cadeia.tau.c, cadeia.tau.alpha, cadeia.tau.beta, ncol(results)+60 ) # sumario: sumario <- coeficientes[[1]];sumario # credibilidade: tab <- coeficientes[[2]];tab tab %>% tail(5) %>% cbind(sd = results %>% apply(2,sd) %>% round(4)) %>% xtable() # Com GGPLOT para o texto ------------------------------------------------- ############## # Para alpha # ############## png("imagens/caterplot_a_hierarquica_rats.png",800,600) cbind(alpha=1:30,tab[1:30,])%>% as.data.frame%>% ggplot( aes(x=alpha, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + # geom_line(position=pd) + geom_point(aes(x=alpha,y=Média),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle xlab("Cadeia de alpha") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[1:30,1]),max(tab[1:30,3]))) + # Set tick every 4 scale_x_continuous(breaks = seq(1,30,1)) + # Set tick every 4 theme_bw() # + # geom_hline(yintercept = alpha_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), # axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() ############## # Para beta # ############## png("imagens/caterplot_b_hierarquica_rats.png",800,600) cbind(beta=1:30,tab[31:60,])%>% as.data.frame%>% ggplot( aes(x=beta, y=Média)) + #, colour=supp, group=supp <- separar por cadeia? geom_errorbar(aes(ymin=`2.5%`, ymax=`97.5%`), colour="black", width=.1, position=position_dodge(0.1)) + # geom_line(position=pd) + geom_point(aes(x=beta,y=Média),position=position_dodge(0.1), size=2, shape=21, fill="blue") + # 21 is filled circle geom_point(position=position_dodge(0.1), size=3, shape=21, fill="white") + # 21 is filled circle xlab("Cadeia de beta") + ylab("Intervalo de credibilidade") + # scale_colour_hue(name="Supplement type", # Legend label, use darker colors # breaks=c("OJ", "VC"), # labels=c("Orange juice", "Ascorbic acid"), # l=40) + # Use darker colors, lightness=40 ggtitle(" ") + expand_limits(y=0) + # Expand y range scale_y_continuous(limits=c(min(tab[31:60,1]),max(tab[31:60,3]))) + # Set tick every 4 scale_x_continuous(breaks = seq(1,30,1)) + # Set tick every 4 theme_bw() # + # geom_hline(yintercept = beta_c, linetype="dashed", color = "red",size=1.3)+theme(axis.text=element_text(size=12), # axis.title=element_text(size=14,face="bold")) # + # Para incluir legenda # theme(legend.justification=c(1,0), # legend.position=c(1,0)) # Position legend in bottom right dev.off() tab
f <- function(n, x=1) for(i in 1:n) x <- 1/(1+x) g <- function(n, x=1) for(i in 1:n) x <- (1/(1+x)) h <- function(n, x=1) for(i in 1:n) x <- (1+x)^(-1) j <- function(n, x=1) for(i in 1:n) x <- {1/{1+x}} k <- function(n, x=1) for(i in 1:n) x <- 1/{1+x} library(rbenchmark) N <- 1e5 benchmark(f(N,1),g(N,1),h(N,1),j(N,1),k(N,1))[,1:4] library(Rcpp) cppFunction(" double m(int n, double x=1) { for (int i=0; i<n; i++) x = 1 / (1+x); return x; }") benchmark(f(N,1),g(N,1),h(N,1),j(N,1),k(N,1),m(N,1),order="relative")[,1:4]
/uzuerich-2015-06/straightorcurly.R
no_license
eddelbuettel/samplecode
R
false
false
563
r
f <- function(n, x=1) for(i in 1:n) x <- 1/(1+x) g <- function(n, x=1) for(i in 1:n) x <- (1/(1+x)) h <- function(n, x=1) for(i in 1:n) x <- (1+x)^(-1) j <- function(n, x=1) for(i in 1:n) x <- {1/{1+x}} k <- function(n, x=1) for(i in 1:n) x <- 1/{1+x} library(rbenchmark) N <- 1e5 benchmark(f(N,1),g(N,1),h(N,1),j(N,1),k(N,1))[,1:4] library(Rcpp) cppFunction(" double m(int n, double x=1) { for (int i=0; i<n; i++) x = 1 / (1+x); return x; }") benchmark(f(N,1),g(N,1),h(N,1),j(N,1),k(N,1),m(N,1),order="relative")[,1:4]
## This file takes an annotSnpStats object and removes all SNPs that are not in basis library(data.table) # basis reference file ref_af_file<-'/rds/user/ob219/hpc-work/as_basis/support_tab/as_basis_snp_support_feb_2018_w_ms.tab' m_file<-'/home/ob219/git/as_basis/manifest/as_manifest_mar_2018.csv' ## dir where all preprocessed gwas files are. ## we expect variants to be reflected in ref_af_file, have there OR aligned and be defined in the manifest file gwas_data_dir <- '/rds/user/ob219/hpc-work/as_basis/gwas_stats/filter_feb_2018_w_ms/aligned' bsnps <- fread(ref_af_file) bsnps[,c('chr','pos'):=tstrsplit(pid,':')] out.dir <- '/rds/user/ob219/hpc-work/as_basis/JIA_basis_annotSnpStats' jfil <- list.files(path="/home/ob219/rds/rds-cew54-wallace-share/Data/GWAS/JIA-2017-data/",pattern="*.RData",full.names=TRUE) library(annotSnpStats) PF <- function(fn){ G <- get(load(fn)) #chr <- gsub("annotsnpstats-([^.]+)\\.RData","\\1",basename(fn)) sdt <- data.table(snps(G)) keep <- which(paste(sdt$chromosome,sdt$position,sep=':') %in% bsnps$pid) missing <- nrow(bsnps[chr==sdt$chromosome[1]]) - length(keep) if(missing!=0) message(sprintf("Not matching missing %d",missing)) G <- G[,keep] sdt <- data.table(snps(G))[,.(position,a0=allele.1,a1=allele.2,rs_id=ID,chromosome)] samps <- data.table(samples(G)) ## we don't have any control data so cannot compute RAF for them #controls <- which(samps$phenotype==0) sdt[,af.wrt.a2:=col.summary(G)[,"RAF"]] #G <- G[-controls,] snps(G)<-as.data.frame(sdt) alleles(G)<-c('a0','a1') save(G,file=file.path(out.dir,basename(fn))) } for(f in jfil){ message(sprintf("Processing %s",f)) PF(f) }
/R/JIA_IND_MAY/cut_down_annoSnpStats_JIA.R
no_license
ollyburren/as_basis
R
false
false
1,675
r
## This file takes an annotSnpStats object and removes all SNPs that are not in basis library(data.table) # basis reference file ref_af_file<-'/rds/user/ob219/hpc-work/as_basis/support_tab/as_basis_snp_support_feb_2018_w_ms.tab' m_file<-'/home/ob219/git/as_basis/manifest/as_manifest_mar_2018.csv' ## dir where all preprocessed gwas files are. ## we expect variants to be reflected in ref_af_file, have there OR aligned and be defined in the manifest file gwas_data_dir <- '/rds/user/ob219/hpc-work/as_basis/gwas_stats/filter_feb_2018_w_ms/aligned' bsnps <- fread(ref_af_file) bsnps[,c('chr','pos'):=tstrsplit(pid,':')] out.dir <- '/rds/user/ob219/hpc-work/as_basis/JIA_basis_annotSnpStats' jfil <- list.files(path="/home/ob219/rds/rds-cew54-wallace-share/Data/GWAS/JIA-2017-data/",pattern="*.RData",full.names=TRUE) library(annotSnpStats) PF <- function(fn){ G <- get(load(fn)) #chr <- gsub("annotsnpstats-([^.]+)\\.RData","\\1",basename(fn)) sdt <- data.table(snps(G)) keep <- which(paste(sdt$chromosome,sdt$position,sep=':') %in% bsnps$pid) missing <- nrow(bsnps[chr==sdt$chromosome[1]]) - length(keep) if(missing!=0) message(sprintf("Not matching missing %d",missing)) G <- G[,keep] sdt <- data.table(snps(G))[,.(position,a0=allele.1,a1=allele.2,rs_id=ID,chromosome)] samps <- data.table(samples(G)) ## we don't have any control data so cannot compute RAF for them #controls <- which(samps$phenotype==0) sdt[,af.wrt.a2:=col.summary(G)[,"RAF"]] #G <- G[-controls,] snps(G)<-as.data.frame(sdt) alleles(G)<-c('a0','a1') save(G,file=file.path(out.dir,basename(fn))) } for(f in jfil){ message(sprintf("Processing %s",f)) PF(f) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dictionary.functions.R \name{mapHugo} \alias{mapHugo} \title{Convert from hugo gene names to entrez ids} \usage{ mapHugo(hugo.ids) } \arguments{ \item{hugo.ids}{: vector of hugo gene names, requires hugo2entrez to be loaded} } \value{ : vector of entrez ids } \description{ Convert from hugo gene names to entrez ids } \examples{ mapHugo(c("A1CF","PTEN")) } \seealso{ \code{\link[MOMA]{mapEntrez}} }
/man/mapHugo.Rd
no_license
califano-lab/MOMA
R
false
true
478
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dictionary.functions.R \name{mapHugo} \alias{mapHugo} \title{Convert from hugo gene names to entrez ids} \usage{ mapHugo(hugo.ids) } \arguments{ \item{hugo.ids}{: vector of hugo gene names, requires hugo2entrez to be loaded} } \value{ : vector of entrez ids } \description{ Convert from hugo gene names to entrez ids } \examples{ mapHugo(c("A1CF","PTEN")) } \seealso{ \code{\link[MOMA]{mapEntrez}} }
library(readxl) library(dplyr) library(tidyr) #reading BP data CDE <- read_excel("bp-stats-review-2020-all-data.xlsx", sheet = "Carbon Dioxide Emissions", na = "n/a") CDE <- as.data.frame(CDE, stringsAsFactors = False) #fixing few names CDE[111,1] = 'OECD' CDE[113,1] = 'European Union' CDE[2,1] = 'Country' #changing JEDNOSTKA to Country will help us later #first variable without NAs List_of_observations <- na.exclude(CDE[,1]) CDE <- CDE[CDE[,1] %in% List_of_observations,] #creating function which negates %in% '%!in%' = Negate('%in%') #creating two variables to contain names of Organisations and Totals Totals <- c("Total North America","Total S. & Cent. America", "Total Asia Pacific", "Total Europe", "Total CIS", "Total Africa", "Total World") Organizations <- c("of which: OECD" = "OECD", "Non-OECD", "European Union") #deleting totals' rows CDE <- CDE[CDE[,1] %!in% Totals,] #deleting organistions' rows CDE <- CDE[CDE[,1] %!in% Organizations,] #adding column's names colnames(CDE) <- CDE[1,] #deleting comments in the last seven rows and the last one CDE <- head(CDE, -7) #deleting few last columns and first row CDE <- CDE[2:94,1:56] #unPivoting columns CDE2 <- gather(CDE, key = 'Year', value = 'Million tonnes of carbon dioxide', -'Country' )
/Data import and cleaning/Carbon_Dioxide_Emissions.R
no_license
sbrylka/Statistical_Review_of_World_Energy
R
false
false
1,276
r
library(readxl) library(dplyr) library(tidyr) #reading BP data CDE <- read_excel("bp-stats-review-2020-all-data.xlsx", sheet = "Carbon Dioxide Emissions", na = "n/a") CDE <- as.data.frame(CDE, stringsAsFactors = False) #fixing few names CDE[111,1] = 'OECD' CDE[113,1] = 'European Union' CDE[2,1] = 'Country' #changing JEDNOSTKA to Country will help us later #first variable without NAs List_of_observations <- na.exclude(CDE[,1]) CDE <- CDE[CDE[,1] %in% List_of_observations,] #creating function which negates %in% '%!in%' = Negate('%in%') #creating two variables to contain names of Organisations and Totals Totals <- c("Total North America","Total S. & Cent. America", "Total Asia Pacific", "Total Europe", "Total CIS", "Total Africa", "Total World") Organizations <- c("of which: OECD" = "OECD", "Non-OECD", "European Union") #deleting totals' rows CDE <- CDE[CDE[,1] %!in% Totals,] #deleting organistions' rows CDE <- CDE[CDE[,1] %!in% Organizations,] #adding column's names colnames(CDE) <- CDE[1,] #deleting comments in the last seven rows and the last one CDE <- head(CDE, -7) #deleting few last columns and first row CDE <- CDE[2:94,1:56] #unPivoting columns CDE2 <- gather(CDE, key = 'Year', value = 'Million tonnes of carbon dioxide', -'Country' )
suppressPackageStartupMessages(library(okcpuid, quietly=TRUE)) suppressPackageStartupMessages(library(pbdMPI, quietly=TRUE)) if (interactive()) comm.stop("This benchmark may not be run interactively.") suppressPackageStartupMessages(library(pbdDMAT, quietly=TRUE)) init.grid() N <- 4500 bldim <- 64 # comm.set.seed(diff=TRUE) if (length(bldim) == 1) bldim <- rep(bldim, 2) A <- ddmatrix("rnorm", N, N) B <- ddmatrix("rnorm", N, 1) peak <- linpack(A=A, B=B) comm.print(peak) finalize()
/demo/pbdlinpack.r
permissive
shinra-dev/okcpuid
R
false
false
501
r
suppressPackageStartupMessages(library(okcpuid, quietly=TRUE)) suppressPackageStartupMessages(library(pbdMPI, quietly=TRUE)) if (interactive()) comm.stop("This benchmark may not be run interactively.") suppressPackageStartupMessages(library(pbdDMAT, quietly=TRUE)) init.grid() N <- 4500 bldim <- 64 # comm.set.seed(diff=TRUE) if (length(bldim) == 1) bldim <- rep(bldim, 2) A <- ddmatrix("rnorm", N, N) B <- ddmatrix("rnorm", N, 1) peak <- linpack(A=A, B=B) comm.print(peak) finalize()
##' key drawing function ##' ##' ##' @name draw_key ##' @param data A single row data frame containing the scaled aesthetics to display in this key ##' @param params A list of additional parameters supplied to the geom. ##' @param size Width and height of key in mm ##' @return A grid grob NULL ggname <- getFromNamespace("ggname", "ggplot2") ##' @rdname draw_key ##' @importFrom grid rectGrob ##' @importFrom grid pointsGrob ##' @importFrom grid gpar ##' @importFrom scales alpha ##' @export draw_key_image <- function(data, params, size) { kt <- getOption("ggimage.keytype") if (is.null(kt)) { kt <- "point" } if (kt == "point") { keyGrob <- pointsGrob( 0.5, 0.5, pch = 19, gp = gpar ( col = alpha(data$colour, data$alpha), fill = alpha(data$colour, data$alpha), fontsize = 3 * ggplot2::.pt, lwd = 0.94 ) ) } else if (kt == "rect") { keyGrob <- rectGrob(gp = gpar( col = NA, fill = alpha(data$colour, data$alpha) )) } else if (kt == "image") { img <- image_read(system.file("extdata/Rlogo.png", package="ggimage")) grobs <- lapply(seq_along(data$colour), function(i) { img <- color_image(img, data$colour[i], data$alpha[i]) rasterGrob( 0.5, 0.5, image = img, width = 1, height = 1 ) }) class(grobs) <- "gList" keyGrob <- ggname("image_key", gTree(children = grobs)) } return(keyGrob) }
/R/draw_key.R
no_license
cran/ggimage
R
false
false
1,772
r
##' key drawing function ##' ##' ##' @name draw_key ##' @param data A single row data frame containing the scaled aesthetics to display in this key ##' @param params A list of additional parameters supplied to the geom. ##' @param size Width and height of key in mm ##' @return A grid grob NULL ggname <- getFromNamespace("ggname", "ggplot2") ##' @rdname draw_key ##' @importFrom grid rectGrob ##' @importFrom grid pointsGrob ##' @importFrom grid gpar ##' @importFrom scales alpha ##' @export draw_key_image <- function(data, params, size) { kt <- getOption("ggimage.keytype") if (is.null(kt)) { kt <- "point" } if (kt == "point") { keyGrob <- pointsGrob( 0.5, 0.5, pch = 19, gp = gpar ( col = alpha(data$colour, data$alpha), fill = alpha(data$colour, data$alpha), fontsize = 3 * ggplot2::.pt, lwd = 0.94 ) ) } else if (kt == "rect") { keyGrob <- rectGrob(gp = gpar( col = NA, fill = alpha(data$colour, data$alpha) )) } else if (kt == "image") { img <- image_read(system.file("extdata/Rlogo.png", package="ggimage")) grobs <- lapply(seq_along(data$colour), function(i) { img <- color_image(img, data$colour[i], data$alpha[i]) rasterGrob( 0.5, 0.5, image = img, width = 1, height = 1 ) }) class(grobs) <- "gList" keyGrob <- ggname("image_key", gTree(children = grobs)) } return(keyGrob) }
testlist <- list(data = structure(c(4.77773545311322e-299, 0, 0, 0, 0, 0, 0), .Dim = c(1L, 7L)), q = 0) result <- do.call(biwavelet:::rcpp_row_quantile,testlist) str(result)
/biwavelet/inst/testfiles/rcpp_row_quantile/libFuzzer_rcpp_row_quantile/rcpp_row_quantile_valgrind_files/1610555225-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
174
r
testlist <- list(data = structure(c(4.77773545311322e-299, 0, 0, 0, 0, 0, 0), .Dim = c(1L, 7L)), q = 0) result <- do.call(biwavelet:::rcpp_row_quantile,testlist) str(result)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/multilevel_qp.R \name{create_q_vector_multi} \alias{create_q_vector_multi} \title{Create the q vector for an QP that solves min_x 0.5 * x'Px + q'x} \usage{ create_q_vector_multi(Xz, trtz) } \arguments{ \item{Xz}{list of J n x d matrices of covariates split by group} \item{target}{Vector of population means to re-weight to} \item{aux_dim}{Dimension of auxiliary weights} } \value{ q vector } \description{ Create the q vector for an QP that solves min_x 0.5 * x'Px + q'x }
/man/create_q_vector_multi.Rd
no_license
ebenmichael/balancer
R
false
true
554
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/multilevel_qp.R \name{create_q_vector_multi} \alias{create_q_vector_multi} \title{Create the q vector for an QP that solves min_x 0.5 * x'Px + q'x} \usage{ create_q_vector_multi(Xz, trtz) } \arguments{ \item{Xz}{list of J n x d matrices of covariates split by group} \item{target}{Vector of population means to re-weight to} \item{aux_dim}{Dimension of auxiliary weights} } \value{ q vector } \description{ Create the q vector for an QP that solves min_x 0.5 * x'Px + q'x }
packages = c("shiny", "markdown", "shinythemes", "dplyr", "ggplot2", "plotly", "tidyr", "kableExtra", "reshape2", "quantmod", "lubridate", "shinyWidgets", "Hmisc", "fGarch", "parallel", "shinycssloaders", "colourpicker") invisible(lapply(packages, library, character.only = TRUE)) shinythemes::themeSelector() tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ) tagList( tags$head(tags$style(HTML(" .navbar-nav { float: none !important; } .navbar-nav > li:nth-child(4) { float: right; } .fa { font-size: 20px; } "))), navbarPage("Praedicere", theme = shinytheme("darkly"), navbarMenu("Stock Overview", tabPanel("Daily", fluidPage( fluidRow(column(4, align="center", textInput(inputId = "stockSymbol", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "overviewDateRan", label = "Start and End Date:", start = Sys.Date() %m-% months(1), end = Sys.Date())), column(4, align="center", selectInput(inputId = "overviewGraphic", label = "Graph:", choices = c("Candlestick" = "cs", "Time Series" = "ts")))), hr(style = "border-color: #ffffff;"), tags$br(), withSpinner(plotly::plotlyOutput("overviewPlot")), tags$br(), tags$br(), tags$br(), hr(style = "border-color: #ffffff;"), tags$br(), tags$br(), tags$br(), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), withSpinner(DT::dataTableOutput("overviewTable")), tags$br(), tags$br(), tags$br() )), "----", tabPanel("Intraday", fluidPage( fluidRow(align = "center", column(4, align="center", textInput(inputId = "intra.ov.stockSymbol", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "intra.ov.overviewDateRan", label = "Start and End Date:", start = Sys.Date(), end = Sys.Date()), selectInput("intra.ov.intraday.step", label = "Choose Intraday Step:", choices = c("1 min." = "1min", "5 min." = "5min", "15 min." = "15min", "30 min." = "30min", "60 min." = "60min"))), column(4, align="center", selectInput(inputId = "intra.ov.overviewGraphic", label = "Graph:", choices = c("Candlestick" = "cs", "Time Series" = "ts")))), hr(style = "border-color: #ffffff;"), withSpinner(plotly::plotlyOutput("intra.ov.overviewPlot")), hr(style = "border-color: #ffffff;"), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), DT::dataTableOutput("intra.ov.overviewTable") ))), tabPanel("Daily Forecast", fluidPage( fluidRow(column(4, align="center", textInput(inputId = "stockSymbolForecast", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "forecastDateRan", label = "Start and End Date:", start = Sys.Date() %m-% months(1), end = Sys.Date())), column(4, align="center", numericInput(inputId = "numForecast", label = "Number of Forecasts:", value = 1))), fluidRow(column(4, align="center", actionButton(inputId = "forecastButton", label = "Auto GARCH", width = '75%')), column(4, align="center", actionButton(inputId = "model.performance", label = "Model Performance", width = '75%')), column(4, align="center", actionButton(inputId = "man.forecast.button", label = "Manual GARCH", width = '75%'))), hr(style = "border-color: #ffffff;"), withSpinner(plotly::plotlyOutput("forecastPlot")), hr(style = "border-color: #ffffff;"), fluidRow(column(8, offset = 2, align="center", selectInput(inputId = "forecastDisplay.button", label = "Display", choices = c("Actuals and Forecast", "Only Forecast")))), fluidRow(column(4, offset = 4, align="center", downloadButton(outputId = "forecast.download", label = "Download Forecast .csv"))), hr(style = "border-color: #ffffff;"), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), withSpinner(DT::dataTableOutput("forecastTable")), hr(style = "border-color: #ffffff;") )), tabPanel("Intraday Forecast", fluidPage( fluidRow(column(4, align="center", textInput(inputId = "intra.stockSymbolForecast", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "intra.forecastDateRan", label = "Start and End Date:", start = Sys.Date(), end = Sys.Date()), selectInput("intra.intraday.step", label = "Choose Intraday Step:", choices = c("5 min." = "5min", "15 min." = "15min", "30 min." = "30min", "60 min." = "60min"), selected = "5 min.")), column(4, align="center", numericInput(inputId = "intra.numForecast", label = "Number of Forecasts:", value = 1))), fluidRow(column(4, align="center", actionButton(inputId = "intra.forecastButton", label = "Auto GARCH", width = '75%')), column(4, align="center", actionButton(inputId = "intra.model.performance", label = "Model Performance", width = '75%')), column(4, align="center", actionButton(inputId = "intra.man.forecast.button", label = "Manual GARCH", width = '75%'))), hr(style = "border-color: #ffffff;"), withSpinner(plotly::plotlyOutput("intra.forecastPlot")), hr(style = "border-color: #ffffff;"), fluidRow(column(8, offset = 2, align="center", selectInput(inputId = "intra.forecastDisplay.button", label = "Display", choices = c("Actuals and Forecast", "Only Forecast")))), fluidRow(column(4, offset = 4, align="center", downloadButton(outputId = "intra.forecast.download", label = "Download Forecast .csv"))), hr(style = "border-color: #ffffff;"), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), withSpinner(DT::dataTableOutput("intra.forecastTable")), hr(style = "border-color: #ffffff;") )), tabPanel("", icon = icon("cog"), fluidPage()) ))
/Application/OLD/Pres/ui.R
no_license
jordanmwheeler/UNO-MasterProject
R
false
false
9,100
r
packages = c("shiny", "markdown", "shinythemes", "dplyr", "ggplot2", "plotly", "tidyr", "kableExtra", "reshape2", "quantmod", "lubridate", "shinyWidgets", "Hmisc", "fGarch", "parallel", "shinycssloaders", "colourpicker") invisible(lapply(packages, library, character.only = TRUE)) shinythemes::themeSelector() tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ) tagList( tags$head(tags$style(HTML(" .navbar-nav { float: none !important; } .navbar-nav > li:nth-child(4) { float: right; } .fa { font-size: 20px; } "))), navbarPage("Praedicere", theme = shinytheme("darkly"), navbarMenu("Stock Overview", tabPanel("Daily", fluidPage( fluidRow(column(4, align="center", textInput(inputId = "stockSymbol", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "overviewDateRan", label = "Start and End Date:", start = Sys.Date() %m-% months(1), end = Sys.Date())), column(4, align="center", selectInput(inputId = "overviewGraphic", label = "Graph:", choices = c("Candlestick" = "cs", "Time Series" = "ts")))), hr(style = "border-color: #ffffff;"), tags$br(), withSpinner(plotly::plotlyOutput("overviewPlot")), tags$br(), tags$br(), tags$br(), hr(style = "border-color: #ffffff;"), tags$br(), tags$br(), tags$br(), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), withSpinner(DT::dataTableOutput("overviewTable")), tags$br(), tags$br(), tags$br() )), "----", tabPanel("Intraday", fluidPage( fluidRow(align = "center", column(4, align="center", textInput(inputId = "intra.ov.stockSymbol", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "intra.ov.overviewDateRan", label = "Start and End Date:", start = Sys.Date(), end = Sys.Date()), selectInput("intra.ov.intraday.step", label = "Choose Intraday Step:", choices = c("1 min." = "1min", "5 min." = "5min", "15 min." = "15min", "30 min." = "30min", "60 min." = "60min"))), column(4, align="center", selectInput(inputId = "intra.ov.overviewGraphic", label = "Graph:", choices = c("Candlestick" = "cs", "Time Series" = "ts")))), hr(style = "border-color: #ffffff;"), withSpinner(plotly::plotlyOutput("intra.ov.overviewPlot")), hr(style = "border-color: #ffffff;"), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), DT::dataTableOutput("intra.ov.overviewTable") ))), tabPanel("Daily Forecast", fluidPage( fluidRow(column(4, align="center", textInput(inputId = "stockSymbolForecast", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "forecastDateRan", label = "Start and End Date:", start = Sys.Date() %m-% months(1), end = Sys.Date())), column(4, align="center", numericInput(inputId = "numForecast", label = "Number of Forecasts:", value = 1))), fluidRow(column(4, align="center", actionButton(inputId = "forecastButton", label = "Auto GARCH", width = '75%')), column(4, align="center", actionButton(inputId = "model.performance", label = "Model Performance", width = '75%')), column(4, align="center", actionButton(inputId = "man.forecast.button", label = "Manual GARCH", width = '75%'))), hr(style = "border-color: #ffffff;"), withSpinner(plotly::plotlyOutput("forecastPlot")), hr(style = "border-color: #ffffff;"), fluidRow(column(8, offset = 2, align="center", selectInput(inputId = "forecastDisplay.button", label = "Display", choices = c("Actuals and Forecast", "Only Forecast")))), fluidRow(column(4, offset = 4, align="center", downloadButton(outputId = "forecast.download", label = "Download Forecast .csv"))), hr(style = "border-color: #ffffff;"), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), withSpinner(DT::dataTableOutput("forecastTable")), hr(style = "border-color: #ffffff;") )), tabPanel("Intraday Forecast", fluidPage( fluidRow(column(4, align="center", textInput(inputId = "intra.stockSymbolForecast", label = "Stock Symbol:", value = "AAPL")), column(4, align="center", dateRangeInput(inputId = "intra.forecastDateRan", label = "Start and End Date:", start = Sys.Date(), end = Sys.Date()), selectInput("intra.intraday.step", label = "Choose Intraday Step:", choices = c("5 min." = "5min", "15 min." = "15min", "30 min." = "30min", "60 min." = "60min"), selected = "5 min.")), column(4, align="center", numericInput(inputId = "intra.numForecast", label = "Number of Forecasts:", value = 1))), fluidRow(column(4, align="center", actionButton(inputId = "intra.forecastButton", label = "Auto GARCH", width = '75%')), column(4, align="center", actionButton(inputId = "intra.model.performance", label = "Model Performance", width = '75%')), column(4, align="center", actionButton(inputId = "intra.man.forecast.button", label = "Manual GARCH", width = '75%'))), hr(style = "border-color: #ffffff;"), withSpinner(plotly::plotlyOutput("intra.forecastPlot")), hr(style = "border-color: #ffffff;"), fluidRow(column(8, offset = 2, align="center", selectInput(inputId = "intra.forecastDisplay.button", label = "Display", choices = c("Actuals and Forecast", "Only Forecast")))), fluidRow(column(4, offset = 4, align="center", downloadButton(outputId = "intra.forecast.download", label = "Download Forecast .csv"))), hr(style = "border-color: #ffffff;"), tags$style(HTML(".dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate .paginate_button, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled { color: #ffffff !important;}")), withSpinner(DT::dataTableOutput("intra.forecastTable")), hr(style = "border-color: #ffffff;") )), tabPanel("", icon = icon("cog"), fluidPage()) ))
test_that("dat_generate_unrestricted properly generates date in desired format", { schema <- read_schema("schema-date.yml") col_def <- schema$public$tables$patients$columns$birth options <- default_faker_opts faked_col <- dat_generate_unrestricted(2, col_def, schema, options) expect_true(all(!is.na(as.Date(faked_col, format = col_def$format)))) }) test_that("dat_generate_restricted properly generates date in desired range", { schema <- read_schema("schema-date.yml") col_def <- schema$public$tables$patients$columns$treatment options <- default_faker_opts faked_col <- dat_generate_restricted(2, col_def, schema, options) sim_dates <- as.Date(faked_col) min_date <- as.Date(col_def$range[1]) max_date <- as.Date(col_def$range[2]) expect_true(all(min_date <= sim_dates & sim_dates < max_date)) })
/tests/testthat/test-simulate_dat_col.R
no_license
LenaNoel/DataFakeR
R
false
false
830
r
test_that("dat_generate_unrestricted properly generates date in desired format", { schema <- read_schema("schema-date.yml") col_def <- schema$public$tables$patients$columns$birth options <- default_faker_opts faked_col <- dat_generate_unrestricted(2, col_def, schema, options) expect_true(all(!is.na(as.Date(faked_col, format = col_def$format)))) }) test_that("dat_generate_restricted properly generates date in desired range", { schema <- read_schema("schema-date.yml") col_def <- schema$public$tables$patients$columns$treatment options <- default_faker_opts faked_col <- dat_generate_restricted(2, col_def, schema, options) sim_dates <- as.Date(faked_col) min_date <- as.Date(col_def$range[1]) max_date <- as.Date(col_def$range[2]) expect_true(all(min_date <= sim_dates & sim_dates < max_date)) })