blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
327
content_id
stringlengths
40
40
detected_licenses
listlengths
0
91
license_type
stringclasses
2 values
repo_name
stringlengths
5
134
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
46 values
visit_date
timestamp[us]date
2016-08-02 22:44:29
2023-09-06 08:39:28
revision_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
committer_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
github_id
int64
19.4k
671M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
14 values
gha_event_created_at
timestamp[us]date
2012-06-21 16:39:19
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-06-28 13:19:12
gha_language
stringclasses
60 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
9.18M
extension
stringclasses
20 values
filename
stringlengths
1
141
content
stringlengths
7
9.18M
066ee8a3941c60fa6c8b5f90a5a701c4287b3f8b
b6c263edf819e3cda7264f964bcbbe3a857fd140
/R/loc_est_bw.R
4ed3aaa5900f9ff7c0b1abc4fdb21e0196b9ff5c
[]
no_license
cran/npbr
d2da3bfa7c43c255e70651b031de24be85a5d4cf
fb273a2137bc9dbd3efe0ce35aa2c6c2fd6fc638
refs/heads/master
2023-04-10T12:02:30.030340
2023-03-22T08:00:05
2023-03-22T08:00:05
17,697,969
1
0
null
null
null
null
UTF-8
R
false
false
3,183
r
loc_est_bw.R
loc_est_bw <- function(xtab, ytab, x, hini, B = 5, method = "u", fix.seed = FALSE, control = list("tm_limit" = 700)){ # verification stopifnot(length(xtab)==length(ytab)) # initialiasation h_loc_min <- max(diff(sort(xtab))) h_loc_max <- (max(xtab)-min(xtab))/2 h_loc_range <- seq(h_loc_min, h_loc_max, length = 30) BIterN <- B # number of bootstrap iteration ghat <- loc_est(xtab, ytab, x, hini, method = method, control = control) # a pilot estimator gpil <- length(ghat) # a second pilot estimator h1 <- 1.5*hini # internal function ckernel <- function(x, bandwidth){ as.numeric((x/bandwidth<=0.5) & (x/bandwidth>=-0.5))*bandwidth^{-1} } for(i in 1:length(x)){ gpil[i] <- sum(ghat*ckernel(x[i]-x, h1), na.rm = T)*unique(diff(x))[1]/(sum(ckernel(x[i]-x, h1), na.rm = T)*unique(diff(x))[1]) # smoothing } #################################### # STEA (a) in Hall and Park (2004) # #################################### rm_ind <- c() for (i in 1:length(xtab)){ if(ytab[i]>gpil[which.min( abs(xtab[i]-x))]){ rm_ind <- c(rm_ind, i) } } # L_1 xtab_r <- xtab[-rm_ind] ytab_r <- ytab[-rm_ind] #################################### # STEA (b) in Hall and Park (2004) # #################################### # L xtab_e <- xtab_r ytab_e <- ytab_r for(i in 1:length(xtab_r)){ ytab_e <- c(ytab_e, 2*gpil[which.min(abs(xtab_r[i]-x))]-ytab_r[i]) xtab_e <- c(xtab_e, xtab_r[i]) } ###################################### # STEA (c,d) in Hall and Park (2004) # ###################################### m <- as.matrix(dist(cbind(xtab_e, ytab_e))) sortm <- apply(m, 2, sort) k <- 10 DZ <- sortm[k+1,] MSE <- rep(0, length(h_loc_range)) count <- rep(0, length(h_loc_range)) for(iterB in 1:BIterN){ cat("Bootstrap Sample #", iterB, "\n") if(fix.seed) set.seed(iterB) NZ <- rpois(length(xtab_e), 1) bxtab <- c() bytab <- c() for (i in 1:length(xtab_e)){ if(NZ[i]>0){ if(fix.seed) set.seed(i) R <- runif(NZ[i], 0, DZ[i]) if(fix.seed) set.seed(i+1) theta <- runif(NZ[i], 0, 2*pi) bxtab <- c(bxtab, xtab_e[i] + R*cos(theta)) bytab <- c(bytab, ytab_e[i] + R*sin(theta)) } } rm_ind_b <- c() for(i in 1:length(bxtab)){ if(bytab[i]>gpil[which.min(abs(bxtab[i]-x))]){ rm_ind_b <- c(rm_ind_b, i) } } bxtab_r <- bxtab[-rm_ind_b] bytab_r <- bytab[-rm_ind_b] h_chk_min <- max(diff(sort(bxtab_r))) if(h_chk_min < max(h_loc_range)){ count <- count + as.numeric(h_loc_range>=h_chk_min) xb <- x[(x>=min(bxtab_r)) & (x<=max(bxtab_r))] gpilb <- gpil[(x>=min(bxtab_r)) & (x<=max(bxtab_r))] for(hi in min(which(h_loc_range>=h_chk_min)):length(h_loc_range)){ est <- loc_est(bxtab_r, bytab_r, xb, h = h_loc_range[hi], method = method, control = control) MSE[hi] <- MSE[hi] + mean((est-gpilb)^2, na.rm = T) } } } h_loc_range_r <- h_loc_range[count>0] hbopt <- h_loc_range_r[which.min(MSE[count>0]*(1/count[count>0]))] return(hbopt) }
6b4ca402b5a648eada95f0da1c38841626b48f7c
7ea08d762a5cfad1ff672199b1431ac9e9449a3f
/blog-2023/Blog-4-submissions/charchit/ozone-map.R
1ad86591c9640549639cd55cdd34ef1bc09185f1
[]
no_license
Stat585-at-ISU/Stat585-at-ISU.github.io
54a0d08c274522914aabd2d74e71259d5253b326
33d38ef0d67047d83fa8b7a216598e162a5f2400
refs/heads/main
2023-07-06T14:48:30.349444
2023-06-26T20:24:22
2023-06-26T20:24:22
78,376,998
3
3
null
2017-04-17T04:23:52
2017-01-08T23:18:27
HTML
UTF-8
R
false
false
1,277
r
ozone-map.R
library("ggplot2") library("maps") outlines <- as.data.frame(map("world",xlim=-c(113.8, 56.2), ylim=c(-21.2, 36.2), plot=FALSE)[c("x","y")]) map <- c( geom_path(aes(x=x, y=y, fill=NULL, group=NULL, order=NULL, size=NULL), data = outlines, colour = alpha("grey20", 0.2)), scale_x_continuous("", limits = c(-114.8, -55.2), breaks=c(-110, -85, -60)), scale_y_continuous("", limits = c(-22.2, 37.2)) ) ozm <- melt(ozone) fac <- laply(ozm, is.factor) ozm[fac] <- llply(ozm[fac], function(x) as.numeric(as.character(x))) small_mult <- function(df) { res <- 2 # lat and long measured every 2.5, but need a gap rexpo <- transform(df, rozone = rescaler(value, type="range") - 0.5, rtime = rescaler(time %% 12, type="range") - 0.5, year = time %/% 12 ) ggplot(rexpo, aes(x = long + res * rtime, y = lat + res * rozone)) + map } make_stars <- function(data, time, value) { data[, c(time, value)] <- lapply(data[, c(time, value)], function(x) { x <- as.numeric(x) (x - min(x)) / diff(range(x)) }) ddply(data, .(lat, long), function(df) { df$x <- df[, value] * cos(df[, time] * 2 * pi + pi / 2) df$y <- df[, value] * sin(df[, time] * 2 * pi + pi / 2) df[order(df[, time]), ] }) } # df <- stars(owide[, 1:2], owide[, -(1:2)])
9463d8e1a5ac4f18cfe3118a7fcd605bf0836fe5
cbfa01cb81d4aa3684655ed93b7e179819057083
/tests/testthat.R
d011b841a13e6a774e2ec3e108abff37a90a99f4
[ "MIT" ]
permissive
dirkschumacher/lazyseq
b1d00d3603ae845acd495788304af66d8ad30fb1
00bde2c17f21a8708c9d6a98666435f7c1f871e1
refs/heads/main
2023-02-26T14:15:19.264720
2021-02-02T20:42:39
2021-02-02T20:42:39
335,417,878
2
0
null
null
null
null
UTF-8
R
false
false
58
r
testthat.R
library(testthat) library(lazyseq) test_check("lazyseq")
b5b5f98a971832d5368ecc6b4fc83f5b5b267675
b798dcec9242b0656453186201aa2411f65fe28d
/man/createProfileMatrix.Rd
fd6601f481f257f686c254e98c00cac48ec4e8b5
[]
no_license
frosinastojanovska/Bioinformatics
481367484796e04fc89ae2675644652355d88729
65620c37026336f816d4d981addfc92b15a2d488
refs/heads/master
2021-01-17T08:42:15.789577
2017-03-24T20:08:31
2017-03-24T20:08:31
83,944,435
1
0
null
null
null
null
UTF-8
R
false
true
537
rd
createProfileMatrix.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/createProfileMatrix.R \name{createProfileMatrix} \alias{createProfileMatrix} \title{Creates profile matrix for given aligment matrix.} \usage{ createProfileMatrix(aligmentMatrix) } \arguments{ \item{aligmentMatrix}{A matrix indicating the aligment matrix.} } \value{ Profile matrix } \description{ Creates profile matrix for given aligment matrix. } \examples{ createProfileMatrix(matrix(c("A","C","A","C","A","C","U","A","A","C","U","A"), nrow=4, ncol=3)) }
6cf98ade83431b0e5e5e728adfabcde688d9d20d
24975c66d61805ffd50147890b9fc34769f18324
/Notes_scripts_bank/ex3_binomial-uniform_multiple_control_JAGS.R
43d5bfd580af59871877c1d8ad62400cf2a66aff
[]
no_license
npetraco/MATFOS705
53081de4e38a1aae8e0d67bf093a1bcd6b9f0258
dc54407b7b13ebf8315282cbaf0c9b742212884d
refs/heads/master
2023-05-28T03:08:46.839815
2023-05-16T14:47:15
2023-05-16T14:47:15
121,066,670
0
0
null
null
null
null
UTF-8
R
false
false
1,352
r
ex3_binomial-uniform_multiple_control_JAGS.R
library(bayesutils) # Data n <- rep(50, 5) participant.errs <- c(0, 0, 20, 0, 1) s <- participant.errs dat <- list( "N" = length(n), "s" = s, "n" = n, "a_hyp" = 0, "b_hyp" = 1 ) inits <- function (){ list(ppi=runif(length(n))) } #Run the model: fit <- jags(data=dat, inits=inits, parameters.to.save = c("ppi","mean.ppi"), #n.iter=10, n.iter=20000, n.burnin = 500, n.thin = 10, n.chains=4, model.file = system.file("jags/binomial-uniform_multiple.bug.R", package = "bayesutils")) fit # Examine chains trace and autocorrelation: #params.chains <- extract.params(fit, by.chainQ = T) #mcmc_trace(params.chains, regex_pars = c("ppi")) #autocorrelation.plots(params.chains, pars = c("ppi")) # Examine posterior params.mat <- extract.params(fit, as.matrixQ = T) mcmc_areas(params.mat, regex_pars = c("ppi"), prob = 0.95) dim(params.mat) colnames(params.mat) ppi <- params.mat[,2:6] mean.ppi <- params.mat[,1] parameter.intervals(ppi[,1], prob=0.95, plotQ = F) parameter.intervals(ppi[,2], prob=0.95, plotQ = F) parameter.intervals(ppi[,3], prob=0.95, plotQ = F) parameter.intervals(ppi[,4], prob=0.95, plotQ = F) parameter.intervals(ppi[,5], prob=0.95, plotQ = F) parameter.intervals(mean.ppi, prob=0.95, plotQ = F)
57da56bac26b30b5c61af0cfa6ff79342b64cb42
24d5d85c21f8843f7c9c61e00222522fde104e7d
/percentlabelv2.R
8322c2d37624286fabf594b137a392d3b152fb0b
[]
no_license
cassierole/ms_percentlabel
deab302aee17274f2cfd407aae2e7429609a13ca
25cd2408668979e56f4765e3897cc3b381823a46
refs/heads/master
2021-01-10T13:30:26.909309
2016-04-11T23:19:49
2016-04-11T23:19:49
52,817,206
0
0
null
null
null
null
UTF-8
R
false
false
3,023
r
percentlabelv2.R
# This function accepts as argument a csv file (ex."file.csv") containing raw quantitative # mass spec data and produces a file in the working directory containing the percentage of # C13-labeled phospholipid for each individual species. # Experiments carried out on Acinetobacter baumannii fed 2-C13 acetate percentlabelv2 <- function(datafile){ dat <- read.csv(datafile, check.names = FALSE) #import raw mass spec data frame <- data.frame() #create an empty data frame for binding cname <-names(dat) #store the column names from mass spec data in vector cnames for (i in 1:(nrow(dat))){ name <- dat[i,grep("name",cname,ignore.case=TRUE)] #calculate the percentage labeled for each species and save as variables dioPG <- getvalues(i,"795","773",dat,cname) paloPG <- getvalues(i,"768","747",dat,cname) dipPG <- getvalues(i,"739","719",dat,cname) dioPE <- getvalues(i,"764","742",dat,cname) paloPE <- getvalues(i,"737","716",dat,cname) dipPE <- getvalues(i,"708","688",dat,cname) card <- getvalues(i,"711","701",dat,cname) #create a new data frame containing percentages, then bind this to existing data frame newframe <- data.frame("Sample_Name"=name,"PG C18:1/18:1"=dioPG,"PG C18:1/16:0"=paloPG,"PG C16:0/16:0"=dipPG,"PE C18:1/18:1"=dioPE,"PE C18:1/16:0"=paloPE,"PE C16:0/16:0"=dipPE,"Cardiolipin"=card, check.names=FALSE) frame <- rbind(frame,newframe) } #creates a file in working directory containing percentages: filename <- paste("percent_labeled",datafile,sep="_") write.csv(frame,file=filename) print("Calculation Complete") #frame } #a function to calculate percentages calcper <- function(lab, unlab){ perlab <- 100 * lab / (lab + unlab) } #getvalues accepts as arguments row of database, m/z of parent ions for labeled and unlabeled, and database #returns percentage of labeled species out of total for that species. getvalues <-function(row,label,unlabel,data,cnames){ #store as a vectors the column positions of labeled and unlabeled species loclab <- grep(label, cnames, ignore.case=TRUE) locunl <- grep(unlabel, cnames, ignore.case=TRUE) vallab <- NA valunl <- NA #If there is more than one transition corresponding to a given parent ion, sum the quantitation values if ((length(loclab)>0)&&(length(locunl)>0)){ for (i in 1:length(loclab)){ vallab <- sum(vallab, data[row,loclab[i]],na.rm=TRUE) } for (i in 1:length(locunl)){ valunl <- sum(valunl, data[row,locunl[i]],na.rm=TRUE) } } calcper(vallab,valunl) }
ac065990bb0a476637a982b3d38e77c84571e1fc
799f724f939763c26c4c94497b8632bad380e8f3
/man/as.tokens.Rd
c1ad9479f2599038451fba137887d45206cbc3fd
[]
no_license
chmue/quanteda
89133a7196b1617f599e5bba57fe1f6e59b5c579
aed5cce6778150be790b66c031ac8a40431ec712
refs/heads/master
2020-12-01T02:59:48.346832
2017-11-22T18:35:37
2017-11-22T18:35:37
50,363,453
2
0
null
2016-01-25T16:18:50
2016-01-25T16:18:50
null
UTF-8
R
false
true
3,635
rd
as.tokens.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tokens.R \name{as.tokens} \alias{as.tokens} \alias{as.tokens.list} \alias{as.tokens.spacyr_parsed} \alias{as.list.tokens} \alias{unlist.tokens} \alias{as.character.tokens} \alias{is.tokens} \alias{+.tokens} \alias{c.tokens} \title{coercion, checking, and combining functions for tokens objects} \usage{ as.tokens(x, concatenator = "_", ...) \method{as.tokens}{list}(x, concatenator = "_", ...) \method{as.tokens}{spacyr_parsed}(x, concatenator = "/", include_pos = c("none", "pos", "tag"), use_lemma = FALSE, ...) \method{as.list}{tokens}(x, ...) \method{unlist}{tokens}(x, recursive = FALSE, use.names = TRUE) \method{as.character}{tokens}(x, use.names = FALSE, ...) is.tokens(x) \method{+}{tokens}(t1, t2) \method{c}{tokens}(...) } \arguments{ \item{x}{object to be coerced or checked} \item{concatenator}{character between multi-word expressions, default is the underscore character. See Details.} \item{...}{additional arguments used by specific methods. For \link{c.tokens}, these are the \link{tokens} objects to be concatenated.} \item{include_pos}{character; whether and which part-of-speech tag to use: \code{"none"} do not use any part of speech indicator, \code{"pos"} use the \code{pos} variable, \code{"tag"} use the \code{tag} variable. The POS will be added to the token after \code{"concatenator"}.} \item{use_lemma}{logical; if \code{TRUE}, use the lemma rather than the raw token} \item{recursive}{a required argument for \link{unlist} but inapplicable to \link{tokens} objects} \item{use.names}{logical; preserve names if \code{TRUE}. For \code{as.character} and \code{unlist} only.} \item{t1}{tokens one to be added} \item{t2}{tokens two to be added} } \value{ \code{as.tokens} returns a quanteda \link{tokens} object. \code{as.list} returns a simple list of characters from a \link{tokens} object. \code{unlist} returns a simple vector of characters from a \link{tokens} object. \code{as.character} returns a character vector from a \link{tokens} object. \code{is.tokens} returns \code{TRUE} if the object is of class tokens, \code{FALSE} otherwise. \code{c(...)} and \code{+} return a tokens object whose documents have been added as a single sequence of documents. } \description{ Coercion functions to and from \link{tokens} objects, checks for whether an object is a \link{tokens} object, and functions to combine \link{tokens} objects. } \details{ The \code{concatenator} is used to automatically generate dictionary values for multi-word expressions in \code{\link{tokens_lookup}} and \code{\link{dfm_lookup}}. The underscore character is commonly used to join elements of multi-word expressions (e.g. "piece_of_cake", "New_York"), but other characters (e.g. whitespace " " or a hyphen "-") can also be used. In those cases, users have to tell the system what is the concatenator in your tokens so that the conversion knows to treat this character as the inter-word delimiter, when reading in the elements that will become the tokens. } \examples{ # create tokens object from list of characters with custom concatenator dict <- dictionary(list(country = "United States", sea = c("Atlantic Ocean", "Pacific Ocean"))) lis <- list(c("The", "United-States", "has", "the", "Atlantic-Ocean", "and", "the", "Pacific-Ocean", ".")) toks <- as.tokens(lis, concatenator = "-") tokens_lookup(toks, dict) # combining tokens toks1 <- tokens(c(doc1 = "a b c d e", doc2 = "f g h")) toks2 <- tokens(c(doc3 = "1 2 3")) toks1 + toks2 c(toks1, toks2) }
c4e710346981ed9c21da1c4701381fdd96659e9d
f97f007dc8fab3d266fa9426f1dc612ba23754e7
/man/high_value_terms.Rd
221a9c828c2be02401b00a5f0723d75f088d3375
[]
no_license
anpatton/overdoseR
6e5c7b8f66d9664ee455379ab23392918d138530
e84e15a027b18fff9530950aaef23fcc350e2455
refs/heads/master
2022-11-16T11:09:32.289312
2020-07-07T16:38:51
2020-07-07T16:38:51
276,998,525
2
0
null
null
null
null
UTF-8
R
false
true
686
rd
high_value_terms.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{high_value_terms} \alias{high_value_terms} \title{High Value Terms} \format{ A data frame with 189 rows and 4 variables: \describe{ \item{token}{actual string of high value term} \item{freqYES}{Frequency of term in development set for opioid related events} \item{freqNO}{Frequency of term in development set for non-opioid related events} \item{type}{word, bigram, or trigram} } } \usage{ high_value_terms } \description{ Dataset containing the raw words, bigrams, and trigrams that were determined to be statistically significant in prior research. } \keyword{datasets}
8b037e9259022527bcc68a473bceedb6f854b9c6
7f3d289e75c1faf4a44d50621d969dc70658259b
/2-StackFiles.R
e7dddddc2ec26fee5809d6330040f4c48275d23c
[]
no_license
alessiobocco/IFPRI_Ethiopia_Drought_2016
89ccaf8bbbdbe9cee57925ed4e41c8bded0f99f5
5f08c729c1e567adc9c629162d10b90e7ec09470
refs/heads/master
2020-05-27T21:09:39.770253
2017-02-01T14:25:57
2017-02-01T14:25:57
83,603,162
1
0
null
2017-03-01T21:23:58
2017-03-01T21:23:58
null
UTF-8
R
false
false
14,948
r
2-StackFiles.R
# This script takes outputs from DownloadMODISFTP_Rcurl.R and stacks them # Run the following in bash before starting R if [ -e $HOME/.Renviron ]; then cp $HOME/.Renviron $HOME/.Renviron.bkp; fi if [ ! -d $HOME/.Rtmp ] ; then mkdir $HOME/.Rtmp; fi echo "TMP='$HOME/.Rtmp'" > $HOME/.Renviron module load proj.4/4.8.0 module load gdal/gcc/1.11 module load R module load gcc/4.9.0 R rm(list=ls()) #source('R:\\Mann Research\\IFPRI_Ethiopia_Drought_2016\\IFPRI_Ethiopia_Drought_Code\\ModisDownload.R') source('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/IFPRI_Ethiopia_Drought_2016/SummaryFunctions.R') library(RCurl) library(raster) library(MODISTools) library(rgdal) library(sp) library(maptools) #library(rts) library(gdalUtils) library(foreach) library(doParallel) library(compiler) library(ggplot2) #cl <- makeCluster(32) #registerDoParallel(cl) # Compile Functions --------------------------------------------------------------- functions_in = lsf.str() lapply(1:length(functions_in), function(x){cmpfun(get(functions_in[[x]]))}) # byte code compile all functions http://adv-r.had.co.nz/Profil$ # Set up parameters ------------------------------------------------------- # give path to Modis Reproduction Tool MRT = 'H:/Projects/MRT/bin' # get list of all available modis products #GetProducts() # Product Filters products = c('MYD13Q1') #EVI c('MYD13Q1','MOD13Q1') , land cover = 'MCD12Q1' for 250m and landcover ='MCD12Q2' location = c(9.145000, 40.489673) # Lat Lon of a location of interest within your tiles listed above #India c(-31.467934,-57.101319) # tiles = c('h21v07','h22v07','h21v08','h22v08') # India example c('h13v12') dates = c('2011-01-01','2016-03-30') # example c('year-month-day',year-month-day') c('2002-07-04','2016-02-02') ftp = 'ftp://ladsweb.nascom.nasa.gov/allData/6/' # allData/6/ for evi, /51/ for landcover # allData/51/ for landcover DOESn't WORK jUST PULL FROM FTP strptime(gsub("^.*A([0-9]+).*$", "\\1",GetDates(location[1], location[2],products[1])),'%Y%j') # get list of all available dates for products[1] # out_dir = 'R:\\Mann_Research\\IFPRI_Ethiopia_Drought_2016\\Data\\VegetationIndex' # setwd(out_dir) # Stack Raw data ----------------------------------------------------- registerDoParallel(5) setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/VegetationIndex/') # folder where EVI .tifs are # create data stack for each variable and tile foreach(product = c('composite_day_of_the_year', 'EVI','NDVI','pixel_reliability')) %dopar% { for( tile_2_process in tiles){ # Set up data print('stacking') flist = list.files(".",glob2rx(paste('*',tile_2_process,'.250m_16_days_',product,'.tif$',sep='')), full.names = TRUE) flist_dates = gsub("^.*_([0-9]{7})_.*$", "\\1",flist,perl = T) # Strip dates flist = flist[order(flist_dates)] # file list in order flist_dates = flist_dates[order(flist_dates)] # file_dates list in order # stack data and save stacked = stack(flist) names(stacked) = flist_dates # assign projection crs(stacked) ='+proj=sinu +a=6371007.181 +b=6371007.181 +units=m' # save assign(paste(product,'stack',tile_2_process,sep='_'),stacked) dir.create(file.path('../Data Stacks/Raw Stacks/'), showWarnings=F,recursive=T) # create stack directory if doesnt exist save( list=paste(product,'stack',tile_2_process,sep='_') , file = paste('../Data Stacks/Raw Stacks/',product,'_stack_',tile_2_process,'.RData',sep='') ) }} # Limit stacks to common dates ------------------------------------------- setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/') # load data stacks from both directories stack_types_2_load =c('composite_day_of_the_year','EVI','NDVI','pixel_reliability') dir1 = list.files('./Data Stacks/Raw Stacks/','.RData',full.names=T) lapply(dir1, load,.GlobalEnv) # limit stacks to common elements for(product in stack_types_2_load ){ for( tile in tiles){ # find dates that exist in all datasets for current tile all_dates = lapply(paste(stack_types_2_load,'stack',tile,sep='_'),function(x){names(get(x))}) # restrict to common dates common_dates = Reduce(intersect, all_dates) # subset stacks for common dates assign(paste(product,'_stack_',tile,sep=''),subset( get(paste(product,'_stack_',tile,sep='')), common_dates, drop=F) ) print('raster depth all equal') print( all.equal(common_dates,names(get(paste(product,'_stack_',tile,sep='')))) ) print(dim(get(paste(product,'_stack_',tile,sep='')))[3]) }} # stack smoother ----------------------------------------------------- # this stack is used for land cover classification only (bc classifier can't have NA values) rm(list=ls()[grep('stack',ls())]) # running into memory issues clear stacks load one by one setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/Raw Stacks/') # don't load smoothed... # load data stacks from both directories dir1 = list.files('.','.RData',full.names=T) lapply(dir1, load,.GlobalEnv) for( i in ls(pattern = "NDVI_stack*")){ print('##############################################################') dir.create(file.path(getwd(), i), showWarnings = FALSE) print(paste('Starting processing of:',i)) stack_in = get(i) stack_name = i dates = as.numeric(gsub("^.*X([0-9]{7}).*$", "\\1",names(stack_in),perl = T)) # Strip dates pred_dates = dates spline_spar=0.4 # 0.4 for RF workers = 20 out_dir = '/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/Smoothed/' stack_smoother(stack_in,dates,pred_dates,spline_spar,workers,stack_name,out_dir) } for( i in ls(pattern = "EVI_stack*")){ print('##############################################################') dir.create(file.path(getwd(), i), showWarnings = FALSE) print(paste('Starting processing of:',i)) stack_in = get(i) stack_name = i dates = as.numeric(gsub("^.*X([0-9]{7}).*$", "\\1",names(stack_in),perl = T)) # Strip dates pred_dates = dates spline_spar=0.4 # 0.4 for RF workers = 20 out_dir = '/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/Smoothed/' stack_smoother(stack_in,dates,pred_dates,spline_spar,workers,stack_name,out_dir) } # Restack Smoothed Files ---------------------------------------------------- setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/Smoothed/Tifs/') # folder where EVI .tifs are # create data stack for each variable and tile # load data stacks from both directories dir1 = list.files('.','.RData',full.names=T) lapply(dir1, load,.GlobalEnv) foreach(product = c('NDVI','EVI')) %do% { for( tile_2_process in tiles){ print(paste('processing',product,tile_2_process,sep=' ')) # Set up data flist = list.files(".",glob2rx(paste(product,'_',tile_2_process,'*','.tif$',sep='')), full.names = TRUE) flist_dates = gsub("^.*_X([0-9]{7}).*$", "\\1",flist,perl = T) # Strip dates flist = flist[order(flist_dates)] # file list in order flist_dates = flist_dates[order(flist_dates)] # file_dates list in order # stack data and save stacked = stack(flist) names(stacked) = flist_dates assign(paste(product,'stack',tile_2_process,'smooth',sep='_'),stacked) save( list=paste(product,'stack',tile_2_process,'smooth',sep='_') , file = paste('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/Smoothed/', product,'_stack_',tile_2_process,'_smooth','.RData',sep='') ) }} # Remove low quality,CLEAN, & assign projection FROM RAW, THEN STACK ------------------------------------------------ # load data in previous section and run common dates rm(list=ls()[grep('stack',ls())]) # running into memory issues clear stacks load one by one setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/Raw Stacks/') # don't load smoothed... # load data stacks from both directories dir1 = list.files('.','.RData',full.names=T) lapply(dir1, load,.GlobalEnv) # set up directories and names setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data//Data Stacks') reliability_prefix = 'pixel_reliability' dir.create(file.path('./WO Clouds/Tifs'), showWarnings=F,recursive=T) dir.create(file.path('./WO Clouds Clean/tifs'), showWarnings=F,recursive=T) dir.create(file.path('/lustre/groups/manngroup/WO Clouds Clean/Tifs'), showWarnings=F,recursive=T) # folder on high speed ssd drive registerDoParallel(25) # setup a dataframe with valid ranges and scale factors valid = data.frame(stack='NDVI', fill= -3000,validL=-2000,validU=10000, scale=0.0001,stringsAsFactors=F) valid = rbind(valid,c('EVI',-3000,-2000,10000,0.0001)) valid for(product in c('EVI','NDVI')){ #'EVI','NDVI' for( tile in tiles){ print(paste('Working on',product,tile)) # load quality flag reliability_stackvalues = get(paste(reliability_prefix,'_stack_',tile,sep='')) # remove clouds from produt data_stackvalues = get(paste(product,'_stack_',tile,sep='')) valid_values = valid[grep(product,valid$stack),] ScaleClean = function(x,y){ x[x==as.numeric(valid_values$fill)]=NA x[x < as.numeric(valid_values$validL)]=NA x[x > as.numeric(valid_values$validU)]=NA #x = x * as.numeric(valid_values$scale) x[ y<0 | y>1 ] = NA # remove very low quality x} # process and write to lustre foreach(i=(1:dim(data_stackvalues)[3]), .inorder=F) %dopar% { print(i) data_stackvalues[[i]] = ScaleClean(data_stackvalues[[i]],reliability_stackvalues[[i]]) writeRaster(data_stackvalues[[i]],paste('/lustre/groups/manngroup/WO Clouds Clean/Tifs/',product,'_',tile, '_',names(data_stackvalues[[i]]),'.tif',sep=''),overwrite=T) } # Copy files back from lustre and delete lustre flist = list.files("/lustre/groups/manngroup/WO Clouds Clean/Tifs/", glob2rx(paste(product,'_',tile,'*','.tif$',sep='')),full.names = T) fname = list.files("/lustre/groups/manngroup/WO Clouds Clean/Tifs/", glob2rx(paste(product,'_',tile,'*','.tif$',sep='')),full.names = F) file.copy(from=flist, to=paste("./WO Clouds Clean/tifs",fname,sep='/'), overwrite = T, recursive = F, copy.mode = T) file.remove(flist) # Restack outputs print(paste('Restacking',product,tile,sep=' ')) # Set up data flist = list.files("./WO Clouds Clean/tifs/",glob2rx(paste(product,'_',tile,'*','.tif$',sep='')),full.names = T) flist_dates = gsub("^.*_X([0-9]{7}).*$", "\\1",flist,perl = T) # Strip dates flist = flist[order(flist_dates)] # file list in order flist_dates = flist_dates[order(flist_dates)] # file_dates list in order # stack data and save stacked = stack(flist) names(stacked) = flist_dates assign(paste(product,'stack',tile,'wo_clouds_clean',sep='_'),stacked) save( list=paste(product,'stack',tile,'wo_clouds_clean',sep='_') , file = paste('./WO Clouds Clean/',product,'_stack_', tile,'_wo_clouds_clean','.RData',sep='') ) }} # Limit to crop signal ---------------------------------------------------- # Class Codes: # 1 agforest 2 arid 3 dryag 4 forest 5 semiarid 6 shrub 7 water 8 wetag 9 wetforest # load data in previous section and run common dates rm(list=ls()[grep('stack',ls())]) # running into memory issues clear stacks load one by one setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data/Data Stacks/WO Clouds Clean/') # don't load smoothed... dir.create(file.path('../WO Clouds Clean LC/tifs/'), showWarnings=F,recursive=T) # create dir for tifs dir.create(file.path('/lustre/groups/manngroup/WO Clouds Clean LC/Tifs'), showWarnings=F,recursive=T) # folder on high speed # load data stacks from both directories dir1 = list.files('.','.RData',full.names=T) lapply(dir1, load,.GlobalEnv) # set up directories and names setwd('/groups/manngroup/IFPRI_Ethiopia_Dought_2016/Data//Data Stacks') landcover_prefix = 'smooth_lc_svm_mn.tif' landcover_path = '../LandUseClassifications/' registerDoParallel(25) for(product in c('EVI','NDVI')){ #'EVI','NDVI' for( tile in tiles){ print(paste('Working on',product,tile)) # load quality flag lc_stackvalues = raster(paste(landcover_path,'NDVI','_stack_',tile,'_',landcover_prefix,sep='')) # remove clouds from produt data_stackvalues = get(paste(product,'_stack_',tile,'_wo_clouds_clean',sep='')) foreach(i=(1:dim(data_stackvalues)[3]), .inorder=F) %dopar% { print(i) data_stackvalues[[i]][lc_stackvalues[[i]]==2|lc_stackvalues[[i]]==7| lc_stackvalues[[i]]==9]=NA writeRaster(data_stackvalues[[i]],paste('/lustre/groups/manngroup/WO Clouds Clean LC/Tifs/' ,product,'_',tile,'_',names(data_stackvalues[[i]]), '_Clean_LC','.tif',sep=''),overwrite=T) } # Copy files back from lustre and delete lustre flist = list.files("/lustre/groups/manngroup/WO Clouds Clean LC/Tifs/", glob2rx(paste(product,'_',tile,'*','.tif$',sep='')),full.names = T) fname = list.files("/lustre/groups/manngroup/WO Clouds Clean LC/Tifs/", glob2rx(paste(product,'_',tile,'*','.tif$',sep='')),full.names = F) file.copy(from=flist, to=paste("./WO Clouds Clean LC/tifs",fname,sep='/'), overwrite = T, recursive = F, copy.mode = T) file.remove(flist) print(paste('Restacking',product,tile,sep=' ')) # Set up data flist = list.files("./WO Clouds Clean LC/tifs/",glob2rx(paste(product,'_',tile,'*','.tif$',sep='')),full.names = T) flist_dates = gsub("^.*_X([0-9]{7}).*$", "\\1",flist,perl = T) # Strip dates flist = flist[order(flist_dates)] # file list in order flist_dates = flist_dates[order(flist_dates)] # file_dates list in order # stack data and save stacked = stack(flist) names(stacked) = flist_dates assign(paste(product,'stack',tile,'WO_Clouds_Clean_LC',sep='_'),stacked) save( list=paste(product,'stack',tile,'WO_Clouds_Clean_LC',sep='_') , file = paste('./WO_Clouds_Clean_LC/',product,'_stack_', tile,'_WO_Clouds_Clean_LC','.RData',sep='') ) }}
faa1d0ae0f21926af9977941fa71f7a0658f2d76
77109777ecf9aa8b467b7225589daecd9f309148
/Projeto2.R
e741f0e766ca95947928273632630c5c6c22b153
[]
no_license
edufrigini/prevendo_estoque
5bf889d44cb1e60438433e9853d75c26e4f835cf
bf6477529175c58edac3f1a9bae6efc8b1443161
refs/heads/master
2020-05-25T00:00:19.835408
2019-05-19T20:46:54
2019-05-19T20:46:54
187,526,262
0
0
null
null
null
null
UTF-8
R
false
false
7,906
r
Projeto2.R
# DSA - DATA SCIENCE ACADEMY # FORMACAO CIENTISTA DE DADOS # LIGUAGEM R COM AZURE MACHINE LEARNING # # PROJETO 2, Prevendo Demanda de Estoque com Base em Vendas # ALUNO: EDUARDO FRIGINI DE JESUS # # Goal: Maximize sales and minimize returns of bakery goods # Data fields # Semana — Week number (From Thursday to Wednesday) # Agencia_ID — Sales Depot ID # Canal_ID — Sales Channel ID # Ruta_SAK — Route ID (Several routes = Sales Depot) # Cliente_ID — Client ID # NombreCliente — Client name # Producto_ID — Product ID # NombreProducto — Product Name # Venta_uni_hoy — Sales unit this week (integer) # Venta_hoy — Sales this week (unit: pesos) # Dev_uni_proxima — Returns unit next week (integer) # Dev_proxima — Returns next week (unit: pesos) # Demanda_uni_equil — Adjusted Demand (integer) (This is the target you will predict) setwd("C:/FCD/BigDataRAzure/Projeto2") getwd() install.packages("gmodels") install.packages("psych") install.packages("rmarkdown") library(rmarkdown) # carregando as bibliotecas, se nao estiver instalada, instalar install.packages("nome do pacote") library(data.table) # para usar a fread library("gmodels") # para usar o CrossTable library(psych) # para usar o pairs.panels library(lattice) # graficos de correlacao require(ggplot2) library(randomForest) library(DMwR) library(dplyr) library(tidyr) library("ROCR") library(caret) library(lattice) library(corrplot) library(corrgram) ## Carregando os dados na memoria # Usando o arquivo train.csv para treinar o modelo para producao dados_originais <- fread("train.csv", sep = ",", header = TRUE, stringsAsFactors = TRUE) dados <- dados_originais[sample(1:nrow(dados_originais), 1000, replace = F)] head(dados) str(dados) View(dados) ## Tratando os dados ## Convertendo as variáveis para o tipo fator (categórica) to.factors <- function(df, variables){ for (variable in variables){ df[[variable]] <- as.factor(df[[variable]]) } return(df) } # Variáveis do tipo fator # nao converti as outras pq eram mts categorias e a floresta randomica nao processa mts categorias colunas_F <- c("Semana", "Canal_ID") dados <- to.factors(df = dados, variables = colunas_F) # corrigir caso hajam dados NA dados <- na.omit(dados) str(dados) head(dados) ## Analise exploratoria dos dados summary(dados$Demanda_uni_equil) # Min. 1st Qu. Median Mean 3rd Qu. Max. # 0.000 2.000 3.000 7.018 6.000 230.000 mean(dados$Demanda_uni_equil) # 7.018 median(dados$Demanda_uni_equil) # 3 quantile(dados$Demanda_uni_equil) # 0% 25% 50% 75% 100% # 0 2 3 6 230 quantile(dados$Demanda_uni_equil, probs = c(0.01, 0.95)) # 1% = 0.00 e 95% = 23.05 quantile(dados$Demanda_uni_equil, seq(from = 0, to = 1, by = 0.10)) IQR(dados$Demanda_uni_equil) # diferenca entre Q3 e Q1 = 4 range(dados$Demanda_uni_equil) # 230 diff(range(dados$Demanda_uni_equil)) sd(dados$Demanda_uni_equil) # 13.74 var(dados$Demanda_uni_equil) # 188.9666 # A variavel alvo esta com muitos outlyers, dai vou restringir ao valores menores que 0.95 quartil quartil_90 <- quantile(dados$Demanda_uni_equil, probs = 0.90) class(quartil_90) quartil_90[[1]] dados_sem_ouliers <- dados[Demanda_uni_equil<=quartil_90[[1]],] plot(dados_sem_ouliers$Demanda_uni_equil) sd(dados_sem_ouliers$Demanda_uni_equil) # 4.35 var(dados_sem_ouliers$Demanda_uni_equil) # 19 ## OS DADOS DO TARGET NAO SEGUEM UMA DISTRIBUICAO NORMAL ## Explorando os dados graficamente plot(dados_sem_ouliers$Semana) hist(dados_sem_ouliers$Ruta_SAK) plot(dados_sem_ouliers$Demanda_uni_equil) # target e esta com outliers hist(dados_sem_ouliers$Demanda_uni_equil) # dados concentrados no zero boxplot(dados_sem_ouliers$Demanda_uni_equil) plot(dados_sem_ouliers$Agencia_ID) plot(dados_sem_ouliers$Canal_ID) # Predominancia do canal 1 # Explorando os dados # variaveis numericas cols <- c("Venta_uni_hoy", "Venta_hoy", "Dev_uni_proxima", "Dev_proxima", "Demanda_uni_equil") cor(dados[, cols, with=FALSE]) pairs.panels(dados[, cols, with=FALSE]) # Correlacao forte com Venta_Roy e Venta_Uni_Roy #### OBSERVACOES #### Venta_uni_hoy e Venta_hoy sao colineares #### Dev_uni_proxima e Dev Proxima sao colineares ###################################################################### ## Apenas para confirmar a correlacao com Venta_hoy e Venta_uni_hoy ## ###################################################################### # Vetor com os métodos de correlação metodos <- c("pearson", "spearman") # Aplicando os métodos de correlação com a função cor() cors <- lapply(metodos, function(method) (cor(dados[, cols, with=FALSE], method = method))) head(cors) # Preparando o plot plot.cors <- function(x, labs){ diag(x) <- 0.0 plot( levelplot(x, main = paste("Plot de Correlação usando Método", labs), scales = list(x = list(rot = 90), cex = 1.0)) ) } # Mapa de Correlação Map(plot.cors, cors, metodos) ######################################################### ## Sem necessidade desse grafico, apenas para confirmar ######################################################### str(dados_sem_ouliers) # Demanda x potenciais variáveis preditoras labels <- list("Boxplots - Demanda por Semana", "Boxplots - Demanda por Agencia", "Boxplots - Demanda por Canal", "Boxplots - Demanda por Rota", "Boxplots - Demanda Cliente") xAxis <- list("Semana", "Agencia_ID", "Canal_ID", "Ruta_SAK", "Cliente_ID") # Função para criar os boxplots plot.boxes <- function(X, label){ ggplot(dados, aes_string(x = X, y = "Demanda_uni_equil", group = X)) + geom_boxplot( ) + ggtitle(label) + theme(text = element_text(size = 18)) } Map(plot.boxes, xAxis, labels) str(dados_sem_ouliers) # Avalidando a importância de todas as variaveis modelo <- randomForest(Demanda_uni_equil ~ . , data = dados_sem_ouliers, ntree = 100, nodesize = 10, importance = TRUE) # Plotando as variáveis por grau de importância varImpPlot(modelo) # Correlacao forte com Venta_Roy e Venta_Uni_Roy #### OBSERVACOES #### Venta_uni_hoy e Venta_hoy sao colineares #### Dev_uni_proxima e Dev_Proxima sao colineares # Removendo variáveis colineares modelo <- randomForest(Demanda_uni_equil ~ . - Venta_hoy - Dev_proxima, data = dados_sem_ouliers, ntree = 100, nodesize = 10, importance = TRUE) varImpPlot(modelo) modelo$importance # Gravando o resultado df_saida <- dados_sem_ouliers[, c("Demanda_uni_equil", (modelo$importance))] df_saida # Removendo as variaveis menos importantes ou colineares dados_ok <- dados_sem_ouliers dados_ok$Dev_proxima <- NULL dados_ok$Venta_hoy <- NULL dados_ok$Cliente_ID <- NULL dados_ok$Agencia_ID <- NULL str(dados_ok) # Gerando dados de treino e de teste sample <- sample.int(n = nrow(dados_ok), size = floor(.7*nrow(dados_sem_ouliers)), replace = F) treino <- dados_ok[sample, ] teste <- dados_ok[-sample, ] # Verificando o numero de linhas nrow(treino) nrow(teste) # Treinando o modelo linear (usando os dados de treino) modelo_lm <- lm(Demanda_uni_equil ~ ., data = treino) modelo_lm # Prevendo demanda de produtos previsao1 <- predict(modelo_lm) View(previsao1) plot(treino$Demanda_uni_equil, previsao1) previsao2 <- predict(modelo_lm, teste) View(previsao2) plot(teste$Demanda_uni_equil, previsao2) # Avaliando a Performance do Modelo summary(modelo_lm) # Adjusted R-squared: 0.9923
67225c32124b38f49e03a442d7fbfd4a6dc3ffd1
b29688e753d4ae51662783aa23198292369f72b8
/R/methMatrixManipulation.R
19c52129b9cafe8a21438d1ad50d0174c9085490
[]
no_license
jsemple19/methMatrix
0de45df9e5d6c9911d4e1a0356f25e618c55f993
9af39085680235b9f380347b52fcc322ade51c0e
refs/heads/master
2022-08-27T16:32:14.539253
2022-08-16T11:56:03
2022-08-16T11:56:03
165,834,604
0
0
null
null
null
null
UTF-8
R
false
false
36,963
r
methMatrixManipulation.R
############ functions for working with methylation matrix lists ################## # the methylation matrices for individual genes by TSS have the following structure: # a list (by sample) of lists of matrices (by TSS) # e.g # [1] sample1 # [1] TSS1 matrix of reads x Cpositions # [2] TSS2 matrix of reads x Cpositions # [2] sample2 # [1] TSS1 matrix of reads x Cpositions # [2] TSS2 matrix of reads x Cpositions # # the matrices contain METHYLATION values: 0 = not methylated, 1 = methylated. # to avoid confusion, keep them this way and only convert to dSMF (1-methylation) for plotting # or correlations #' Convert C position numbering from genomic to relative coordinates #' #' @param mat A methylation matrix #' @param regionGR A genomicRanges object of the region relative to which the new coordinates are caclulated #' @param invert A logical variable to indicate if the region should be inverted (e.g. if it is on the negative strand). Default: FALSE #' @return A methylation matrix in which the column names have been changed from absolute genomic positions to relative #' positions within the genomicRange regionGR #' @export getRelativeCoord<-function(mat,regionGR,invert=F){ # converts matrix from absolute genome coordinates to # relative coordinates within a genomic Range pos<-as.numeric(colnames(mat)) regionStart<-GenomicRanges::start(regionGR) regionEnd<-GenomicRanges::end(regionGR) if (invert==F) { newPos<-pos-regionStart colnames(mat)<-as.character(newPos) } else { newPos<-regionEnd-pos colnames(mat)<-newPos mat<-mat[,order(as.numeric(colnames(mat))),drop=F] colnames(mat)<-as.character(colnames(mat)) } return(mat) } #' Change the anchor coordinate #' #' @param mat A methylation matrix #' @param anchorCoord The coordinate which will be set as the 0 position for relative coordinates #' (default=0) #' @return A methylation matrix in which the column names have been changed to indicate relative position #' with reference to the anchor coordinate. e.g. a 500bp matrix centered around the TSS can have its column #' names changed from 0 to 500 range to -250 to 250 range by setting anchorCoord=250. #' @export changeAnchorCoord<-function(mat,anchorCoord=0) { # changes the 0 coordinate position (anchorCoord) of # a matrix. e.g. sets position 250 to 0 in a 500 region around TSS # to get +-250 bp around TSS pos<-as.numeric(colnames(mat)) newPos<-pos-anchorCoord colnames(mat)<-as.character(newPos) return(mat) } #' Get full matrix of all positions in a window even if no C #' #' In order to compare different promoters, we need to create a padded #' matrix with NAs in positions in between Cs. #' #' @param matList A table of paths to matrices which have the same columns #' @param regionType A name for the type of region the matrices desribe #' @param winSize The size (in bp) of the window containing the matrices #' @param workDir The path to working directory #' @return A table of file paths to padded methylation matrices #' @export getFullMatrices<-function(matList,regionType,winSize=500, workDir=".") { currentSample<-regionGR<-NULL naRows<-is.na(matList$filename) matList<-matList[!naRows,] makeDirs(workDir,paste0("/rds/paddedMats_",regionType)) matrixLog<-matList[,c("filename","sample","region")] matrixLog$filename<-NA for (i in 1:nrow(matList)) { mat<-readRDS(matList$filename[i]) # create a matrix with winSize columns and one row per seq read Cpos<-colnames(mat) withinRange<- -winSize/2<=as.numeric(Cpos) & winSize/2>=as.numeric(Cpos) fullMat<-matrix(data=NaN,nrow=dim(mat)[1],ncol=winSize) colnames(fullMat)<-c(seq(-winSize/2,-1),seq(1,winSize/2)) fullMat[,Cpos[withinRange]]<-mat[,withinRange] matName<-paste0(workDir,"/rds/paddedMats_",regionType,"/",currentSample,"_",regionGR$ID,".rds") saveRDS(fullMat,file=matName) matrixLog[i,"filename"]<-matName } #utils::write.csv(matrixLog,paste0(workDir,"/csv/MatrixLog_paddedMats_",regionType,".csv"), quote=F, row.names=F) return(matrixLog) } #' Convert C position numbering from genomic to relative coordinates for a list of matrices #' #' @param matList A table of paths to methylation matrices with names that match the regionGRs object #' @param regionGRs A genomicRanges object of the regions relative to which the new coordinates are caclulated with a metadata column called "ID" containing names that match the methylation matrices in matList #' @param regionType A collective name for this list of regions (e.g TSS or amplicons). It will be used in naming the output directories. #' @param anchorCoord The coordinate which will be set as the 0 position for relative #' coordinates (default=0) #' @param workDir path to working directory #' @return A list of methylation matrices that have been converted from abslute genomic coordinates #' to relativepositions within the genomicRanges regionGRs. regionGRs on the negative strand will be flipped to be #' in the forward orientation. #' @export getRelativeCoordMats<-function(matList, regionGRs, regionType, anchorCoord=0,workDir=".") { naRows<-is.na(matList$filename) matList<-matList[!naRows,] makeDirs(workDir,paste0("/rds/relCoord_",regionType)) matrixLog<-matList[,c("filename","sample","region")] matrixLog$filename<-NA matrixLog$reads<-NA matrixLog$motifs<-NA for (i in 1:nrow(matList)) { print(matList[i,c("sample","region")]) mat<-readRDS(matList$filename[i]) if(sum(dim(mat)==c(0,0))<1) { regionID<-matList$region[i] regionGR<-regionGRs[regionGRs$ID==regionID] newMat<-getRelativeCoord(mat, regionGR, invert=ifelse(GenomicRanges::strand(regionGR)=="+",F,T)) newMat<-changeAnchorCoord(mat=newMat,anchorCoord=anchorCoord) } else { newMat<-mat } matName<-paste0(workDir,"/rds/relCoord_",regionType,"/",matList$sample[i],"_",regionGR$ID,".rds") saveRDS(newMat,file=matName) matrixLog[i,"filename"]<-matName matrixLog[i,"reads"]<-dim(newMat)[1] matrixLog[i,"motifs"]<-dim(newMat)[2] } if (! dir.exists(paste0(workDir,"/csv/"))) { dir.create(paste0(workDir,"/csv/")) } utils::write.csv(matrixLog,paste0(workDir,"/csv/MatrixLog_relCoord_",regionType,".csv"), quote=F, row.names=F) return(matrixLog) } #' Calculate methylation frequency at each position for metagene plots #' #' @param matList A table of filepaths of methylation matrices with names that match the regionsGRs object #' @param regionGRs A genomicRanges object of the regions for which aggregate methylation frequency #' will be calculated. the object must contain a metadata column called "ID" containing names that #' match the methylation matrices in matList #' @param minReads The minimal number of reads a matrix must have in order to be used (default=50) #' @return A long form dataframe with four columns: "position" is the C position within the genomic Ranges, #' "methFreq" is the frequency of methylation at that position, "ID" is the name of the region, "chr" #' is the chromosome on which that region is present. #' @export getMetaMethFreq<-function(matList,regionGRs,minReads=50) { naRows<-is.na(matList$filename) matList<-matList[!naRows,] first=TRUE for (i in 1:nrow(matList)) { mat<-readRDS(matList$filename[i]) if (dim(mat)[1]>minReads) { vecSummary<-colMeans(mat,na.rm=T) df<-data.frame("position"=names(vecSummary),"methFreq"=vecSummary,stringsAsFactors=F) df$ID<-matList$region[i] df$chr<-as.character(GenomicRanges::seqnames(regionGRs)[match(matList$region[i],regionGRs$ID)]) if (first==TRUE){ methFreqDF<-df first=FALSE } else { methFreqDF<-rbind(methFreqDF,df) } } } return(methFreqDF) } #' Single molecule plot of a methylation matrix #' #' @param mat A methylation matrix #' @param regionName The name of the region the matrix is taken from should match on of the IDs in regionGRs #' @param regionGRs A genomicRanges object which includes the region which the mat matrix provides the data for. #' The object must contain a metadata column called "ID" containing names that match the methylation #' matrices in mat #' @param featureGRs A genomicRanges object denoting features to be plotted such as the TSS #' @param myXlab A label for the x axis (default is "CpG/GpC position") #' @param featureLabel A label for a feature you want to plot, such as the position of the TSS #' (default="TSS) #' @param drawArrow Boolean: should the feature be drawn as an arrow or just a line? (default=TRUE) #' @param title A title for the plot (default will be the name of the region, the chr and strand on which #' the region is present) #' @param baseFontSize The base font for the plotting theme (default=12 works well for 4x plots per A4 page) #' @param maxNAfraction Maximual fraction of CpG/GpC positions that can be undefined (default=0.2) #' @param segmentSize Length of colour segment denoting methylation site #' @param colourChoice A list of colours for colour pallette. Must include #' values for "low", "mid", "high" and "bg" (background) and "lines". #' @param colourScaleMidpoint Numerical value for middle of colour scale. Useful for Nanopore data where a particular threshold other than 0.5 is used to distinguish methylated from non-methylated sites. (default=0.5). #' @param doClustering Boolean value to determine if reads should be clustered with heirarchical clustering before plotting (default=T). #' @return A ggplot2 plot object #' @export plotSingleMolecules<-function(mat,regionName, regionGRs, featureGRs=NULL, myXlab="CpG/GpC position", featureLabel="TSS", drawArrow=TRUE, title=NULL, baseFontSize=12, maxNAfraction=0.2, segmentSize=3, colourChoice=list(low="blue", mid="white", high="red", bg="white", lines="black"), colourScaleMidpoint=0.5, doClustering=T) { position<-methylation<-molecules<-NULL ### single molecule plot. mat is matrix containing methylation values at different postions # (columns) in individual reads (rows). regionName is the ID of the amplicon or genomic # region being plotted. regionGRs is a genomicRanges object containing the region being # plotted. one of its mcols must have a name "ID" in which the same ID as in regionName # appears. featureGRs is genomic ranges object for plotting location of some feature in # the region, such as the TSS. myXlab is the X axis label. featureLabel is the label for # the type of feature that will be plotted underneath the feature tooManyNAs<-rowMeans(is.na(mat))>maxNAfraction mat<-mat[!tooManyNAs,] if (!is.null(dim(mat)) & any(dim(mat)[1]>10)) { regionGR<-regionGRs[match(regionName,regionGRs$ID)] if (length(featureGRs)>0) { featGR<-featureGRs[match(regionName,featureGRs$ID)] } na.matrix<-is.na(mat) mat[na.matrix]<- -1 # try to perform heirarchical clustering hc <- try( stats::hclust(stats::dist(apply(mat,2,as.numeric))), silent = TRUE) mat[na.matrix]<-NA if (class(hc) == "try-error" | !doClustering ) { df<-as.data.frame(mat,stringsAsFactors=F) print("hclust not performed. Matrix dim: ") print(dim(mat)) } else { df<-as.data.frame(mat[hc$order,], stringsAsFactors=F) } reads<-row.names(df) d<-tidyr::gather(df,key=position,value=methylation) d$molecules<-seq_along(reads) #d$methylation<-as.character(d$methylation) d$position<-as.numeric(d$position) if (is.null(title)) { strandInfo<-ifelse(GenomicRanges::strand(featGR)!= GenomicRanges::strand(regionGR), paste0("reg: ", GenomicRanges::strand(regionGR), "ve, ",featureLabel,": ", GenomicRanges::strand(featGR),"ve strand"), paste0(GenomicRanges::strand(regionGR),"ve strand")) title=paste0(regionName, ": ", GenomicRanges::seqnames(regionGR), " ", strandInfo) } scaleFactor<-(GenomicRanges::width(regionGR)/500) p<-ggplot2::ggplot(d,ggplot2::aes(x=position,y=molecules)) + ggplot2::geom_tile(ggplot2::aes(width=segmentSize*scaleFactor, fill=methylation), alpha=0.8) + ggplot2::scale_fill_gradient2(low=colourChoice$low, mid=colourChoice$mid, high=colourChoice$high, midpoint=colourScaleMidpoint, na.value=colourChoice$bg, breaks=c(0,1), labels=c("protected","accessible"), limits=c(0,1), name="dSMF\n\n") + #ggplot2::scale_fill_manual(values=c("0"="black","1"="grey80"),na.translate=F,na.value="white", labels=c("protected","accessible"),name="dSMF") + ggplot2::theme_light(base_size=baseFontSize) + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), panel.background=ggplot2::element_rect(fill=colourChoice$bg), plot.title = ggplot2::element_text(face = "bold",hjust = 0.5), legend.position="bottom", legend.key.height = ggplot2::unit(0.2, "cm"), legend.key.width=ggplot2::unit(0.5,"cm")) + ggplot2::ggtitle(title) + ggplot2::xlab(myXlab) + ggplot2::ylab("Single molecules") + ggplot2::xlim(GenomicRanges::start(regionGR), GenomicRanges::end(regionGR)+10) if(!is.null(featureGRs)) { p<-p+ggplot2::geom_linerange(ggplot2::aes( x=GenomicRanges::start(featGR), y=NULL, ymin=0, ymax=length(reads)+max(3,0.04*length(reads))), col=colourChoice$lines) + ggplot2::annotate(geom="text", x=GenomicRanges::start(featGR), y=-max(2,0.03*length(reads)), label=featureLabel,color=colourChoice$lines) if (drawArrow==TRUE) { p<-p+ggplot2::annotate("segment", x = GenomicRanges::start(featGR), xend = GenomicRanges::start(featGR)+ 20*scaleFactor*ifelse(GenomicRanges::strand(featGR)=="-", -1,1), y = length(reads)+max(3,0.04*length(reads)), yend =length(reads)+max(3,0.04*length(reads)), colour = colourChoice$lines, arrow=ggplot2::arrow(length = ggplot2::unit(0.3,"cm")), size=0.7) } } } else { p<-NULL } return(p) } #' Single molecule plot of a methylation matrix with average methylation frequency #' #' @param mat A methylation matrix #' @param regionName The name of the region the matrix is taken from should match on of the IDs in regionGRs #' @param regionGRs A genomicRanges object which includes the region which the mat matrix provides the data for. #' The object must contain a metadata column called "ID" containing names that match the methylation #' matrices in mat #' @param featureGRs A genomicRanges object denoting features to be plotted such as the TSS #' @param myXlab A label for the x axis (default is "CpG/GpC position") #' @param featureLabel A label for a feature you want to plot, such as the position of the TSS #' (default="TSS) #' @param drawArrow Boolean: should the feature be drawn as an arrow or just a line? (default=TRUE) #' @param title A title for the plot (default will be the name of the region, the chr and strand on which #' the region is present) #' @param baseFontSize The base font for the plotting theme (default=11 works well for 4x plots per A4 page) #' @param maxNAfraction Maximual fraction of CpG/GpC positions that can be undefined (default=0.2) #' @param segmentSize Length of colour segment denoting methylation site #' @param colourChoice A list of colours for colour pallette. Must include #' values for "low", "mid", "high" and "bg" (background) and "lines". #' @param colourScaleMidpoint Numerical value for middle of colour scale. Useful for Nanopore data where a particular threshold other than 0.5 is used to distinguish methylated from non-methylated sites. (default=0.5). #' @param doClustering Boolean value to determine if reads should be clustered with heirarchical clustering before plotting (default=T). #' @return A ggplot2 plot object #' @export plotSingleMoleculesWithAvr<-function(mat, regionName, regionGRs, featureGRs, myXlab="CpG/GpC position", featureLabel="TSS", drawArrow=TRUE, title=NULL, baseFontSize=11, maxNAfraction=0.2, segmentSize=3, colourChoice=list(low="blue", mid="white", high="red", bg="white", lines="grey80"), colourScaleMidpoint=0.5, doClustering=T) { dSMF<-molecules<-position<-methylation<-NULL # remove reads with more than maxNAfraction positions with NAs tooManyNAs<-rowMeans(is.na(mat))>maxNAfraction mat<-mat[!tooManyNAs,] if(!is.null(dim(mat)) & any(dim(mat)[1]>10)) { regionGR<-regionGRs[match(regionName,regionGRs$ID)] if (length(featureGRs)>0) { featGR<-featureGRs[match(regionName,featureGRs$ID)] } na.matrix<-is.na(mat) mat[na.matrix]<--1 # try to perform heirarchical clustering hc <- try( stats::hclust(stats::dist(apply(mat,2,as.numeric))), silent = TRUE) mat[na.matrix]<-NA if (class(hc) == "try-error" | !doClustering ) { df<-as.data.frame(mat,stringsAsFactors=F) print("hclust not performed. Matrix dim: ") print(dim(mat)) } else { df<-as.data.frame(mat[hc$order,],stringsAsFactors=F) } reads<-row.names(df) d<-tidyr::gather(df,key=position,value=methylation) d$molecules<-seq_along(reads) #d$methylation<-as.character(d$methylation) d$position<-as.numeric(d$position) if (is.null(title)) { strandInfo<-ifelse(GenomicRanges::strand(featGR)!=GenomicRanges::strand(regionGR), paste0("reg: ",GenomicRanges::strand(regionGR),"ve, ", featureLabel,": ",GenomicRanges::strand(featGR),"ve strand"), paste0(GenomicRanges::strand(regionGR),"ve strand")) title=paste0(regionName, ": ",GenomicRanges::seqnames(regionGR)," ",strandInfo) } scaleFactor<-(GenomicRanges::width(regionGR)/500) dAvr<-data.frame(position=as.numeric(colnames(df)), dSMF=1-colSums(df>=colourScaleMidpoint, na.rm=T)/length(reads)) # average plot p1<-ggplot2::ggplot(dAvr,ggplot2::aes(x=position,y=dSMF,group=1)) + ggplot2::geom_point(size=1/scaleFactor)+ ggplot2::geom_line(size=1,show.legend=F) + ggplot2::guides(fill=FALSE, color=FALSE) + ggplot2::theme_light(base_size=baseFontSize) + ggplot2::ylab("Mean dSMF") + ggplot2::theme(axis.title.x = ggplot2::element_blank(), axis.text.x = ggplot2::element_blank(), plot.background = ggplot2::element_rect(colour="white")) + ggplot2::ylim(0,1) + ggplot2::xlim(GenomicRanges::start(regionGR),GenomicRanges::end(regionGR)+20) if (!is.null(featureGRs)) { # plot feature if present p1<-p1 + ggplot2::geom_linerange(ggplot2::aes(x=GenomicRanges::start(featGR), y=NULL, ymin=0, ymax=1), col=colourChoice$lines,size=0.7) if (drawArrow==TRUE) { p1<-p1+ggplot2::annotate("segment", x = GenomicRanges::start(featGR), xend = GenomicRanges::start(featGR)+ 20*scaleFactor*ifelse(GenomicRanges::strand(featGR)=="-",-1,1), y = 1, yend = 1, colour = colourChoice$lines, size=0.7, arrow=ggplot2::arrow(length = ggplot2::unit(0.2, "cm"))) } } #single molecule plot p2<-ggplot2::ggplot(d,ggplot2::aes(x=position,y=molecules)) + ggplot2::geom_tile(ggplot2::aes(width=segmentSize*scaleFactor,fill=methylation),alpha=0.8) + ggplot2::scale_fill_gradient2(low=colourChoice$low, mid=colourChoice$mid, high=colourChoice$high, midpoint=colourScaleMidpoint, na.value=colourChoice$bg, breaks=c(0,1), labels=c("protected","accessible"), limits=c(0,1), name="dSMF\n\n") + ggplot2::theme_light(base_size=baseFontSize) + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), panel.background=ggplot2::element_rect(fill=colourChoice$bg), plot.title = ggplot2::element_blank(), legend.position="bottom", legend.key.height = ggplot2::unit(0.2, "cm"), legend.key.width=ggplot2::unit(0.5,"cm")) + ggplot2::xlab(myXlab) + ggplot2::ylab("Single molecules") + ggplot2::xlim(GenomicRanges::start(regionGR),GenomicRanges::end(regionGR)+20) if (length(featureGRs)>0) { # plot feature if present p2<-p2+ggplot2::geom_linerange(ggplot2::aes(x=GenomicRanges::start(featGR), y=NULL, ymin=0, ymax=length(reads)+max(3,0.04*length(reads))), col=colourChoice$lines) + ggplot2::annotate(geom="text", x=GenomicRanges::start(featGR), y=-max(2,0.03*length(reads)), label=featureLabel, color=colourChoice$lines) if (drawArrow==TRUE) { p2<-p2+ggplot2::annotate("segment", x = GenomicRanges::start(featGR), xend = GenomicRanges::start(featGR)+ 20*scaleFactor*ifelse(GenomicRanges::strand(featGR)=="-",-1,1), y = length(reads)+max(3,0.04*length(reads)), yend =length(reads)+max(3,0.04*length(reads)), colour = colourChoice$lines, size=0.7, arrow=ggplot2::arrow(length = ggplot2::unit(0.3, "cm"))) } } figure<-ggpubr::ggarrange(p1, p2, heights = c(0.5, 2), ncol = 1, nrow = 2, align = "v") figure<-ggpubr::annotate_figure(figure, top = ggpubr::text_grob(title, face = "bold")) } else { figure=NULL } return(figure) } #' Plot a list of list of single molecule matrices #' #' This function takes a list (by sample) of a list (by genomic region) of #' methylation matrices and produces single molecule plots for each amplicon with #' four samples per page. #' #' @param allSampleMats A list (by sample) of lists (by regions) of methylation matrices #' @param samples A list of samples to plot (same as sample names in allSampleMats) #' @param regionGRs A genomic regions object with all regions for which matrices should be extracted (same as in allSampleMats). The metadata columns must contain a column called "ID" with a unique ID for each region. #' @param featureGRs A genomic regions object for features (such as TSS) to be plotted. Feature must be identified with the same ID as the regionGRs #' @param regionType A collective name for this list of regions (e.g TSS or amplicons). It will be used in naming the output directories #' @param featureLabel A string with a label for the feature to be added to the plot (default="TSS") #' @param maxNAfraction Maximual fraction of CpG/GpC positions that can be undefined (default=0.2) #' @param withAvr Boolean value: should single molecule plots be plotted together with the average profile (default=FALSE) #' @param includeInFileName String to be included at the end of the plot file name, e.g. experiment name (default="") #' @param drawArrow Boolean: should the feature be drawn as an arrow or just a line? (default=TRUE) #' @param workDir Path to working directory #' @return Plots are written to plots directory #' @export plotAllMatrices<-function(allSampleMats, samples, regionGRs, featureGRs, regionType, featureLabel="TSS", maxNAfraction=0.2,withAvr=FALSE, includeInFileName="", drawArrow=TRUE, workDir=".") { # convert any factor variables to character f <- sapply(allSampleMats, is.factor) allSampleMats[f] <- lapply(allSampleMats[f], as.character) # remove any regions with no matrix naRows<-is.na(allSampleMats$filename) allSampleMats<-allSampleMats[!naRows,] # get list of all regions in the object allAmp2plot<-unique(allSampleMats$region) # plot single molecule matrices on their own for (i in allAmp2plot) { if (withAvr==TRUE) { makeDirs(workDir,paste0("plots/singleMoleculePlotsAvr_",regionType)) } else { makeDirs(workDir,paste0("plots/singleMoleculePlots_",regionType)) } plotList=list() print(paste0("plotting ", i)) currentRegion<-allSampleMats[allSampleMats$region==i,] for (j in seq_along(currentRegion$sample)) { mat<-readRDS(allSampleMats[allSampleMats$region==i & allSampleMats$sample==currentRegion$sample[j],"filename"]) maxReads=10000 if (!is.null(dim(mat))) { if (dim(mat)[1]>maxReads) { # if matrix contains more than 10000 reads, do a random subsample set.seed(1) chooseRows<-sample(1:dim(mat)[1],maxReads) mat<-mat[chooseRows,] } if (withAvr==TRUE) { p<-plotSingleMoleculesWithAvr(mat=mat, regionName=i, regionGRs=regionGRs, featureGRs=featureGRs, myXlab="CpG/GpC position", featureLabel=featureLabel, drawArrow=drawArrow, title=currentRegion$sample[j], baseFontSize=11, maxNAfraction=maxNAfraction) } else { p<-plotSingleMolecules(mat=mat, regionName=i, regionGRs=regionGRs, featureGRs=featureGRs, myXlab="CpG/GpC position", featureLabel=featureLabel, drawArrow=drawArrow, title=currentRegion$sample[j], baseFontSize=12, maxNAfraction=maxNAfraction) } if (!is.null(p)) { plotList[[currentRegion$sample[j]]]<-p } } } if (length(plotList)>0) { numPages=ceiling(length(plotList)/4) for (page in 1:numPages) { regionGR<-regionGRs[match(i,regionGRs$ID)] featGR<-featureGRs[match(i,featureGRs$ID)] chr<-GenomicRanges::seqnames(regionGR) strandInfo<-ifelse(GenomicRanges::strand(featGR)!=GenomicRanges::strand(regionGR), paste0("reg: ",GenomicRanges::strand(regionGR),"ve, ", featureLabel,": ",GenomicRanges::strand(featGR), "ve strand"), paste0(GenomicRanges::strand(regionGR),"ve strand")) title<-paste0(i, ": ",chr," ",strandInfo) spacer<-ifelse(length(includeInFileName)>0,"_","") toPlot<-c(1:4)+4*(page-1) #get plots for this page toPlot<-toPlot[toPlot<=length(plotList)] #make sure only valid plot numbers used mp<-gridExtra::marrangeGrob(grobs=plotList[toPlot],nrow=2,ncol=2,top=title) if (withAvr==TRUE) { ggplot2::ggsave(paste0(workDir,"/plots/singleMoleculePlotsAvr_", regionType, "/", chr,"_",i,spacer,includeInFileName,"_",page,".png"), plot=mp, device="png", width=20, height=29, units="cm") } else { ggplot2::ggsave(paste0(workDir,"/plots/singleMoleculePlots_",regionType, "/",chr,"_",i, spacer, includeInFileName,"_",page,".png"), plot=mp, device="png", width=29, height=20, units="cm") } } } } } #' Convert Genomic Ranges to relative cooridnates #' #' Convert a normal genomic ranges to one where the start and end are relative to some #' anchor point - either the middle or the start of the genomic ranges (e.g. -250 to 250, or #' 0 to 500). The original start end and strand are stored in the metadata. #' @param grs A GenomicRanges object to be converted to relative coordinates #' @param winSize The size of the window you wish to create #' @param anchorPoint One of "middle" or "start": the position from which numbering starts #' @return A GenomicRanges object with relative coordinate numbering #' @export convertGRtoRelCoord<-function(grs,winSize,anchorPoint="middle") { grsRelCoord<-grs GenomicRanges::mcols(grsRelCoord)$gnmStart<-GenomicRanges::start(grs) GenomicRanges::mcols(grsRelCoord)$gnmEnd<-GenomicRanges::end(grs) GenomicRanges::mcols(grsRelCoord)$gnmStrand<-GenomicRanges::strand(grs) grsRelCoord<-GenomicRanges::resize(grsRelCoord,width=winSize,fix="center") GenomicRanges::strand(grsRelCoord)<-"*" if (anchorPoint=="middle") { GenomicRanges::start(grsRelCoord)<- -winSize/2 GenomicRanges::end(grsRelCoord)<- winSize/2 } else if (anchorPoint=="start") { GenomicRanges::start(grsRelCoord)<- 1 GenomicRanges::end(grsRelCoord)<- winSize } else { print("anchorPoint must be one of 'middle' or 'start'") } return(grsRelCoord) } #' Convert relative cooridnates to absolute genomic position #' #' Convert genomic ranges where the start and end are #' relative to some anchor point - either the middle or the start of #' the genomic ranges (e.g. -250 to 250, or 0 to 500) to a normal Genomic #' Ranges with absolute genomic positions. #' @param grsRelCoord A GenomicRanges object with one or more relative #' coordinate ranges to be converted to absolute genomic positions. #' @param regionGR A GenomicRanges object for the whole region to which the #' grsRelCoord are relative to. #' @param anchorPoint One of "middle" or "start": the position from which numbering starts #' @return A GenomicRanges object with absolute genomic position #' @export convertRelCoordtoGR<-function(grsRelCoord,regionGR,anchorPoint="middle") { winSize<-NULL grs<-grsRelCoord #grsRelCoord<-GenomicRanges::resize(grsRelCoord,width=winSize,fix="center") GenomicRanges::strand(grs)<-GenomicRanges::strand(regionGR) if (anchorPoint=="middle") { GenomicRanges::start(grs)<- GenomicRanges::start(regionGR) + winSize/2 + GenomicRanges::start(grsRelCoord) GenomicRanges::end(grs)<- GenomicRanges::start(regionGR) + winSize/2 + GenomicRanges::end(grsRelCoord) } else if (anchorPoint=="start") { GenomicRanges::start(grs)<- GenomicRanges::start(regionGR) - 1 + GenomicRanges::start(grsRelCoord) GenomicRanges::end(grs)<- GenomicRanges::start(regionGR) + GenomicRanges::end(grsRelCoord) } else { print("anchorPoint must be one of 'middle' or 'start'") } return(grs) } #' get average methylation frequency from all matrices #' #' In order to do a metagene plot from matrices, the average methylation frequency from all #' matrices with more reads than minReads is collected into a data frame #' @param relCoordMats A table of paths to methylation matrices which have been converted to relative coordinates #' @param samples A list of samples to plot (same as sample names in relCoordMats) #' @param regionGRs A genomic regions object with all regions for which matrices should be extracted (same as in relCoordMats). The metadata columns must contain a column called "ID" with a unique ID for each region. #' @param minReads The minimal number of reads required in a matrix for average frequency to be calculated. #' @return Data frame with average methylation at relative coordinates extracted from all matrices for all samples #' @export getAllSampleMetaMethFreq<-function(relCoordMats,samples,regionGRs,minReads=10) { naRows<-is.na(relCoordMats$filename) relCoordMats<-relCoordMats[!naRows,] first<-TRUE for (i in seq_along(samples)) { idx<-relCoordMats$sample==samples[i] metaMethFreqDF<-getMetaMethFreq(matList=relCoordMats[idx,], regionGRs=regionGRs, minReads=minReads) print(samples[i]) metaMethFreqDF$sample<-samples[i] if(first==TRUE) { allSampleMetaMethFreqDF<-metaMethFreqDF first<-FALSE } else { allSampleMetaMethFreqDF<-rbind(allSampleMetaMethFreqDF,metaMethFreqDF) } } # convert position from factor to numeric allSampleMetaMethFreqDF$position<-as.numeric(as.character(allSampleMetaMethFreqDF$position)) return(allSampleMetaMethFreqDF) } #' Plot metagene by sample #' #' Plots metagene methylation frequency from dataframe extracted from matrices. #' @param metageneDF ata frame with average methylation at relative coordinates extracted from all matrices for all samples #' @param maxPoints The maximum number of points to plot per sample. To avoid large files with too much overplotting, the defualt limit is set to 10000. Larger dataframes will be randomly sub-sampled #' @return A ggplot2 plot object #' @export plotDSMFmetageneDF<-function(metageneDF,maxPoints=10000) { position<-methFreq<-NULL # subsample if too many points if (nrow(metageneDF)>maxPoints) { set.seed(1) idx<-sample(1:nrow(metageneDF),maxPoints) } else { idx<-1:nrow(metageneDF) } p1<-ggplot2::ggplot(metageneDF[idx,],ggplot2::aes(x=position,y=1-methFreq)) + ggplot2::theme_light(base_size=16) + ggplot2::ylim(0,1) + ggplot2::xlab("Position relative to TSS") + ggplot2::ylab("dSMF (1-%methylation)") + ggplot2::geom_linerange(ggplot2::aes(x=0, y=NULL, ymin=0, ymax=1),color="steelblue",size=1) + ggplot2::geom_point(alpha=0.1) + ggplot2::geom_smooth(colour="red",fill="red") + ggplot2::facet_wrap(~sample) p2<-ggplot2::ggplot(metageneDF,ggplot2::aes(x=position,y=1-methFreq,colour=sample)) + ggplot2::theme_light(base_size=16) + ggplot2::ylim(0,1) + ggplot2::xlab("Position relative to TSS") + ggplot2::ylab("dSMF (1-%methylation)") + ggplot2::geom_linerange(ggplot2::aes(x=0, y=NULL, ymin=0, ymax=1),color="steelblue",size=1) + ggplot2::geom_smooth(se=FALSE) ml <- gridExtra::marrangeGrob(list(p1,p2), nrow=1, ncol=1) return(ml) } #' Merge tables listing methylation matrices for different samples #' #' Uses file naming convention of MatrixLog_regionType_sampleName.csv to #' merge tables of methylation matrices that were processed separately for #' each sample. The function will merge all the samples listed in samples and #' then will also delete the original split files #' @param path Path to working directory in which csv subdirectory exists. #' @param regionType A collective name for this list of regions (e.g TSS or amplicons). It is used in naming the files #' @param samples A list of sample names to merge (used in the name of the file) #' @param deleteSplitFiles Logical value to determine if individual sample files #' should be deleted (defualt=F). #' @return Table of merged samples #' @export mergeSampleMats<-function(path, regionType, samples, deleteSplitFiles=F) { allSampleMats<-NULL for(s in 1:length(samples)){ if(!file.exists(paste0(path,"/csv/MatrixLog_", regionType, "_", samples[s], ".csv"))){ cat(paste0("File ",path,"/csv/MatrixLog_", regionType, "_", samples[s], ".csv"," not found"),sep="\n") next() } temp<-utils::read.csv(paste0(path,"/csv/MatrixLog_", regionType, "_", samples[s], ".csv"),header=T, stringsAsFactors=F) if(is.null(allSampleMats)) { allSampleMats<-temp } else { allSampleMats<-rbind(allSampleMats,temp) } } utils::write.csv(allSampleMats,paste0(path, "/csv/MatrixLog_", regionType,".csv"), quote=F, row.names=F) # delete split files if(deleteSplitFiles){ for(s in 1:length(samples)){ file.remove(paste0(path, "/csv/MatrixLog_", regionType, "_",samples[s], ".csv")) file.remove(paste0(path, "/csv/MatrixLog_", regionType, "_", samples[s], "_log.csv")) } } return(allSampleMats) }
2231a4293ef5cfcaa22324f4bdd0b958043a5ce8
fc214123e9c4caca64b4a063e67df94584277771
/0_GraphEffects.R
180d3e44b60b4bc742e1229d91a1e993f1de5e8a
[]
no_license
alexanderm10/canopy_class_climate
e6ecc886ba668be3ef969af2227365c3f76d3971
ebc780ec0cda97492beb9c531b933ca95cadce42
refs/heads/master
2021-05-09T20:09:12.334030
2020-11-04T20:05:55
2020-11-04T20:05:55
118,674,596
0
1
null
null
null
null
UTF-8
R
false
false
16,979
r
0_GraphEffects.R
# Making functions so that all models can get graphed using the same parameters cbbPalette <- c("#009E73", "#e79f00", "#9ad0f3", "#0072B2", "#D55E00") # plotting the size effect; standard dimensions = 8 tall, 5 wide plot.size <- function(dat.plot){ ggplot(data=dat.plot[dat.plot$Effect=="dbh.recon",]) + # ggtitle("Null Model") + facet_grid(Species~.) + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100)) + geom_hline(yintercept=100, linetype="dashed") + scale_x_continuous(expand=c(0,0)) + # coord_cartesian(ylim=c(0, 1750)) + labs(x = expression(bold(paste("DBH (cm)"))), y = expression(bold(paste("Relativized BAI (%)"))))+ theme(axis.line=element_line(color="black"), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.border=element_blank(), panel.background=element_rect(fill=NA, color="black"), axis.text.x=element_text(angle=0, color="black", size=10), axis.text.y=element_text(angle=0, color="black", size=10), strip.text=element_text(face="bold", size=12), axis.line.x = element_line(color="black", size = 0.5), axis.line.y = element_line(color="black", size = 0.5), legend.position="top", legend.key.size = unit(0.75, "cm"), legend.text = element_text(size=10), legend.key = element_rect(fill = "white")) + #guides(color=guide_legend(nrow=1),)+ theme(axis.title.x = element_text(size=12, face="bold"), axis.title.y= element_text(size=12, face="bold"))+ theme(panel.spacing.x = unit(0.5,"lines"), panel.spacing.y = unit(0.5,"lines")) } plot.year <- function(dat.plot){ ggplot(data=dat.plot[dat.plot$Effect=="Year",]) + # ggtitle("Null Model") + facet_wrap(~PlotID, scales="free_y") + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100, fill=Species), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100, color=Species)) + geom_hline(yintercept=100, linetype="dashed") + scale_x_continuous(expand=c(0,0)) + coord_cartesian(ylim=c(0,300)) + # coord_cartesian(ylim=c(0, 1750)) + labs(x = expression(bold(paste("Year"))), y = expression(bold(paste("Relativized BAI (%)")))) + theme(axis.line=element_line(color="black"), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.border=element_blank(), panel.background=element_rect(fill=NA, color="black"), axis.text.x=element_text(angle=-45, hjust=0, color="black", size=10), axis.text.y=element_text(angle=0, color="black", size=10), strip.text=element_text(face="bold", size=10), axis.line.x = element_line(color="black", size = 0.5), axis.line.y = element_line(color="black", size = 0.5), legend.position="top", legend.key.size = unit(0.75, "cm"), legend.text = element_text(size=10), legend.key = element_rect(fill = "white")) + #guides(color=guide_legend(nrow=1),)+ theme(axis.title.x = element_text(size=12, face="bold"), axis.title.y= element_text(size=12, face="bold"))+ theme(panel.spacing.x = unit(0.5,"lines"), panel.spacing.y = unit(0.5,"lines"), plot.margin=unit(c(0.5, 2, 0.5, 0.5), "lines")) } # --------------------------------------------- # The big one: 3-panel climate effects # --------------------------------------------- plot.climate <- function(dat.plot, canopy=F, species=F, ...){ plot.base <- ggplot(data=dat.plot[dat.plot$Effect%in%c("tmean", "precip", "vpd.max"),]) + # facet_grid(.~Effect) + coord_cartesian(ylim=c(50, 200)) + geom_hline(yintercept=100, linetype="dashed") + scale_y_continuous(limits=c(min(dat.plot$lwr.bai[dat.plot$Effect %in% c("tmean", "precip", "vpd.max")]*100, na.rm=T), max(dat.plot$upr.bai[dat.plot$Effect %in% c("tmean", "precip", "vpd.max")]*100, na.rm=T))) + theme(axis.line=element_line(color="black"), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.border=element_blank(), panel.background=element_rect(fill=NA, color="black"), axis.ticks.length = unit(-0.5, "lines"), axis.text.x = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), axis.text.y = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), strip.text=element_text(face="bold", size=18), axis.line.x = element_line(color="black", size = 0.5), axis.line.y = element_line(color="black", size = 0.5), legend.position="top", # legend.key.size = unit(0.75, "cm"), legend.text = element_text(size=12), legend.key = element_rect(fill = "white")) + #guides(color=guide_legend(nrow=1),)+ theme(axis.title.x = element_text(size=12, face="bold"), axis.title.y= element_text(size=12, face="bold")) + theme(panel.spacing.x = unit(0.5,"lines"), panel.spacing.y = unit(0.5,"lines"), strip.text.x = element_blank(), plot.background = element_rect(fill=NA, color=NA)) if(species){ plot.base <- plot.base + facet_grid(Species ~ Effect) } else { plot.base <- plot.base + facet_grid(.~Effect) } if(canopy){ plot.base <- plot.base + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100, fill=Canopy.Class), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100, color=Canopy.Class)) + scale_fill_manual(values=c("#E69F00","#009E73", "#0072B2"))+ scale_color_manual(values=c("#E69F00","#009E73", "#0072B2")) + theme(legend.title = element_blank()) } else { plot.base <- plot.base + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100)) } plot.tmean <- plot.base %+% subset(dat.plot, Effect=="tmean") + labs(x = expression(bold(paste("Temperature ("^"o", "C)"))), y = expression(bold(paste("Relativized BAI (%)")))) + guides(fill=F, color=F) + theme(strip.text.y = element_blank(), axis.text.x = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), axis.title.x = element_text(margin=unit(c(0,0,0,0), "lines"), color="black", size=12), plot.margin = unit(c(3.75,0.5, 0.5, 1), "lines")) if(canopy){ plot.precip <- plot.base %+% subset(dat.plot, Effect=="precip") + labs(x = expression(bold(paste("Precipitation (mm)"))), y = element_blank()) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), strip.text.y = element_blank(), plot.margin = unit(c(1,0.5, 0.5, 0.5), "lines")) } else { plot.precip <- plot.base %+% subset(dat.plot, Effect=="precip") + labs(x = expression(bold(paste("Precipitation (mm)"))), y = element_blank()) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), strip.text.y = element_blank(), plot.margin = unit(c(3.75,0.5, 0.5, 0.5), "lines")) } plot.vpd <- plot.base %+% subset(dat.plot, Effect=="vpd.max") + labs(x = expression(bold(paste("VPD (kPa)"))), y = element_blank()) + guides(fill=F, color=F) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), plot.margin = unit(c(3.75,1, 0.5, 0.5), "lines")) cowplot::plot_grid(plot.tmean, plot.precip, plot.vpd, nrow=1, rel_widths = c(1.5, 1, 1.25)) } plot.climate.site <- function(dat.plot, canopy=T, species=F, ...){ if(species) stop("We're using the function that plots sites. Can't do both species & site!") plot.base <- ggplot(data=dat.plot[dat.plot$Effect%in%c("tmean", "precip", "vpd.max"),]) + facet_grid(Site.Code~Effect) + geom_hline(yintercept=100, linetype="dashed") + scale_y_continuous(limits=c(min(dat.plot$lwr.bai[dat.plot$Effect %in% c("tmean", "precip", "vpd.max")]*100, na.rm=T), max(dat.plot$upr.bai[dat.plot$Effect %in% c("tmean", "precip", "vpd.max")]*100, na.rm=T))) + coord_cartesian(ylim=c(50, 200)) + theme(axis.line=element_line(color="black"), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.border=element_blank(), panel.background=element_rect(fill=NA, color="black"), axis.ticks.length = unit(-0.5, "lines"), axis.text.x = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), axis.text.y = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), strip.text=element_text(face="bold", size=18), axis.line.x = element_line(color="black", size = 0.5), axis.line.y = element_line(color="black", size = 0.5), legend.position="top", # legend.key.size = unit(0.75, "cm"), legend.text = element_text(size=12), legend.key = element_rect(fill = "white")) + #guides(color=guide_legend(nrow=1),)+ theme(axis.title.x = element_text(size=12, face="bold"), axis.title.y= element_text(size=12, face="bold")) + theme(panel.spacing.x = unit(0.5,"lines"), panel.spacing.y = unit(0.5,"lines"), strip.text.x = element_blank(), plot.background = element_rect(fill=NA, color=NA)) if(canopy){ plot.base <- plot.base + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100, fill=Canopy.Class), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100, color=Canopy.Class)) + scale_fill_manual(values=c("#E69F00","#009E73", "#0072B2"))+ scale_color_manual(values=c("#E69F00","#009E73", "#0072B2")) + theme(legend.title = element_blank()) } else { plot.base <- plot.base + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100)) } plot.tmean <- plot.base %+% subset(dat.plot, Effect=="tmean") + labs(x = expression(bold(paste("Temperature ("^"o", "C)"))), y = expression(bold(paste("Relativized BAI (%) (%)")))) + guides(fill=F, color=F) + theme(strip.text.y = element_blank(), axis.text.x = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), axis.title.x = element_text(margin=unit(c(0,0,0,0), "lines"), color="black", size=12), plot.margin = unit(c(3.75,0.5, 0.5, 1), "lines")) if(canopy){ plot.precip <- plot.base %+% subset(dat.plot, Effect=="precip") + labs(x = expression(bold(paste("Precipitation (mm)"))), y = element_blank()) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), strip.text.y = element_blank(), plot.margin = unit(c(1,0.5, 0.5, 0.5), "lines")) } else { plot.precip <- plot.base %+% subset(dat.plot, Effect=="precip") + labs(x = expression(bold(paste("Precipitation (mm)"))), y = element_blank()) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), strip.text.y = element_blank(), plot.margin = unit(c(3.75,0.5, 0.5, 0.5), "lines")) } plot.vpd <- plot.base %+% subset(dat.plot, Effect=="vpd.max") + labs(x = expression(bold(paste("VPD (kPa)"))), y = element_blank()) + guides(fill=F, color=F) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), plot.margin = unit(c(3.75,1, 0.5, 0.5), "lines")) cowplot::plot_grid(plot.tmean, plot.precip, plot.vpd, nrow=1, rel_widths = c(1.5, 1, 1.25)) } # --------------------------------------------- # --------------------------------------------- # The big one: 3-panel climate effects for leave-one-out analysis # --------------------------------------------- plot.climate.sites <- function(dat.plot, canopy=F, species=NULL, panel="sites", ...){ if(!canopy) panel="sites" if(is.null(species)) species <- unique(dat.plot$Species) plot.base <- ggplot(data=dat.plot[dat.plot$Species %in% species & dat.plot$Effect%in%c("tmean", "precip", "vpd.max"),]) + # facet_grid(.~Effect) + coord_cartesian(ylim=c(50, 200)) + geom_hline(yintercept=100, linetype="dashed") + scale_y_continuous(limits=c(min(dat.plot$lwr.bai[dat.plot$Effect %in% c("tmean", "precip", "vpd.max")]*100, na.rm=T), max(dat.plot$upr.bai[dat.plot$Effect %in% c("tmean", "precip", "vpd.max")]*100, na.rm=T))) + theme(axis.line=element_line(color="black"), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.border=element_blank(), panel.background=element_rect(fill=NA, color="black"), axis.ticks.length = unit(-0.5, "lines"), axis.text.x = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), axis.text.y = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), strip.text=element_text(face="bold", size=18), axis.line.x = element_line(color="black", size = 0.5), axis.line.y = element_line(color="black", size = 0.5), legend.position="top", # legend.key.size = unit(0.75, "cm"), legend.text = element_text(size=12), legend.key = element_rect(fill = "white")) + #guides(color=guide_legend(nrow=1),)+ theme(axis.title.x = element_text(size=12, face="bold"), axis.title.y= element_text(size=12, face="bold")) + theme(panel.spacing.x = unit(0.5,"lines"), panel.spacing.y = unit(0.5,"lines"), strip.text.x = element_blank(), plot.background = element_rect(fill=NA, color=NA)) if(panel=="sites"){ if(!canopy){ plot.base <- plot.base + facet_grid(Species ~ Effect) } else { plot.base <- plot.base + facet_grid(Canopy.Class ~ Effect) } plot.base <- plot.base + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100, fill=Site), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100, color=Site)) + scale_fill_manual(name="SiteOut", values=c("HO"="#792427FF", "GB"="#633D43FF", "RH"="#4E565FFF", "GE"="#36727EFF", "PS"="#438990FF", "NR"="#739B96FF", "HF"="#A2AC9CFF", "LF"="#D1BDA2FF"))+ scale_color_manual(name="SiteOut", values=c("HO"="#792427FF", "GB"="#633D43FF", "RH"="#4E565FFF", "GE"="#36727EFF", "PS"="#438990FF", "NR"="#739B96FF", "HF"="#A2AC9CFF", "LF"="#D1BDA2FF"))+ theme(legend.title = element_blank()) } else { # Panel shows comparisons of canopy classes plot.base <- plot.base + facet_grid(Site ~ Effect) + geom_ribbon(aes(x=x, ymin=lwr.bai*100, ymax=upr.bai*100, fill=Canopy.Class), alpha=0.5) + geom_line(aes(x=x, y=mean.bai*100, color=Canopy.Class)) + scale_fill_manual(values=c(Overstory="#E69F00","Middle"="#009E73", "Understory"="#0072B2"))+ scale_color_manual(values=c(Overstory="#E69F00","Middle"="#009E73", "Understory"="#0072B2")) + theme(legend.title = element_blank()) } # End sites-based panels or not # test <- subset(dat.plot, Effect=="tmean", Species==species) plot.tmean <- plot.base %+% dat.plot[dat.plot$Effect=="tmean" & dat.plot$Species==species, ] + labs(x = expression(bold(paste("Temperature ("^"o", "C)"))), y = expression(bold(paste("Relativized BAI (%)")))) + guides(fill=F, color=F) + theme(strip.text.y = element_blank(), axis.text.x = element_text(margin=unit(c(1,1,1,1), "lines"), color="black", size=10), axis.title.x = element_text(margin=unit(c(0,0,0,0), "lines"), color="black", size=12), plot.margin = unit(c(4.75,0.5, 0.5, 1), "lines")) plot.precip <- plot.base %+% dat.plot[dat.plot$Effect=="precip" & dat.plot$Species==species, ] + labs(x = expression(bold(paste("Precipitation (mm)"))), y = element_blank()) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), strip.text.y = element_blank()) if(!panel=="sites"){ plot.precip <- plot.precip + theme(plot.margin = unit(c(2,0.5, 0.5, 0.5), "lines")) } else { plot.precip <- plot.precip + theme(plot.margin = unit(c(0.8,0.5, 0.5, 0.5), "lines")) } # End setting margins based on color level plot.vpd <- plot.base %+% dat.plot[dat.plot$Effect=="vpd.max" & dat.plot$Species==species, ] + labs(x = expression(bold(paste("VPD (kPa)"))), y = element_blank()) + guides(fill=F, color=F) + theme(axis.text.y=element_blank(), axis.ticks.y=element_line(unit(-0.5, units="lines")), plot.margin = unit(c(4.75,1, 0.5, 0.5), "lines")) cowplot::plot_grid(plot.tmean, plot.precip, plot.vpd, nrow=1, rel_widths = c(1.5, 1, 1.25)) } # End function # ---------------------------------------------
5f075ed8daf8b88d2a27da3d3b5c18c2531882b4
06c93d110bc8441b6fafba6e2df030224e87cb2b
/man/create_course_assigment.Rd
333d36c826eff3b853c9b0beaaccd1e1178a09a6
[]
no_license
wsphd/rcanvas
57162905a0d860b80ac0cc548cab259a72a8fd6e
ad8929935f410d196a9891a07f537e4b6c8d3ab2
refs/heads/master
2020-03-25T05:49:58.661865
2018-08-03T20:04:54
2018-08-03T20:04:54
143,467,846
0
0
null
2018-08-03T19:51:25
2018-08-03T19:51:25
null
UTF-8
R
false
true
6,207
rd
create_course_assigment.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/uploads.R \name{create_course_assigment} \alias{create_course_assigment} \title{Create a course assignment} \usage{ create_course_assigment(course_id, name, position = NULL, submission_types = NULL, allowed_extensions = NULL, turnitin_enabled = NULL, vericite_enabled = NULL, turnitin_settings = NULL, integration_data = NULL, integration_id = NULL, peer_reviews = NULL, automatic_peer_reviews = NULL, notify_of_update = NULL, group_category_id = NULL, grade_group_students_individually = NULL, external_tool_tag_attributes = NULL, points_possible = NULL, grading_type = NULL, due_at = NULL, lock_at = NULL, unlock_at = NULL, description = NULL, assignment_group_id = NULL, muted = NULL, assignment_overrides = NULL, only_visible_to_overrides = NULL, published = NULL, grading_standard_id = NULL, omit_from_final_grade = NULL, quiz_lti = NULL) } \arguments{ \item{course_id}{a valid course id} \item{name}{the assignment name (only parameter required)} \item{position}{integer - The position of this assignment in the group when displaying assignment lists.} \item{submission_types}{string - List of supported submission types for the assignment. Unless the assignment is allowing online submissions, the array should only have one element. Options: online_quiz, none, on_paper, discussion_topic, external_tool, online_upload, online_text_entry, online_url, media_recording} \item{allowed_extensions}{Allowed extensions if submission_types includes “online_upload”. E.g. "docx", "png".} \item{turnitin_enabled}{boolean - Only applies when the Turnitin plugin is enabled for a course and the submission_types array includes “online_upload”. Toggles Turnitin submissions for the assignment. Will be ignored if Turnitin is not available for the course.} \item{vericite_enabled}{boolean - Only applies when the VeriCite plugin is enabled for a course and the submission_types array includes “online_upload”. Toggles VeriCite submissions for the assignment. Will be ignored if VeriCite is not available for the course.} \item{turnitin_settings}{string - Settings to send along to turnitin. See Assignment object definition for format.} \item{integration_data}{string - Data used for SIS integrations. Requires admin-level token with the “Manage SIS” permission. JSON string required.} \item{integration_id}{string - Unique ID from third party integrations} \item{peer_reviews}{boolean - If submission_types does not include external_tool,discussion_topic, online_quiz, or on_paper, determines whether or not peer reviews will be turned on for the assignment.} \item{automatic_peer_reviews}{boolean - Whether peer reviews will be assigned automatically by Canvas or if teachers must manually assign peer reviews. Does not apply if peer reviews are not enabled.} \item{notify_of_update}{boolean - If true, Canvas will send a notification to students in the class notifying them that the content has changed.} \item{group_category_id}{integer - If present, the assignment will become a group assignment assigned to the group.} \item{grade_group_students_individually}{boolean - If this is a group assignment, teachers have the options to grade students individually. If false, Canvas will apply the assignment's score to each member of the group. If true, the teacher can manually assign scores to each member of the group.} \item{external_tool_tag_attributes}{string - Hash of external tool parameters if submission_types is external_tool. See Assignment object definition for format.} \item{points_possible}{number - The maximum points possible on the assignment.} \item{grading_type}{string - The strategy used for grading the assignment. The assignment defaults to “points” if this field is omitted. Options: pass_fail, percent, letter_grade, gpa_scale, points} \item{due_at}{datetime - The day/time the assignment is due. Must be between the lock dates if there are lock dates. Accepts times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z.} \item{lock_at}{datetime - The day/time the assignment is locked after. Must be after the due date if there is a due date. Accepts times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z.} \item{unlock_at}{datetime - The day/time the assignment is unlocked. Must be before the due date if there is a due date. Accepts times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z.} \item{description}{string - The assignment's description, supports HTML.} \item{assignment_group_id}{number - The assignment group id to put the assignment in. Defaults to the top assignment group in the course.} \item{muted}{boolean - Whether this assignment is muted. A muted assignment does not send change notifications and hides grades from students. Defaults to false.} \item{assignment_overrides}{List of overrides for the assignment.} \item{only_visible_to_overrides}{boolean - Whether this assignment is only visible to overrides (Only useful if 'differentiated assignments' account setting is on)} \item{published}{boolean - Whether this assignment is published. (Only useful if 'draft state' account setting is on) Unpublished assignments are not visible to students.} \item{grading_standard_id}{integer - The grading standard id to set for the course. If no value is provided for this argument the current grading_standard will be un-set from this course. This will update the grading_type for the course to letter_grade' unless it is already 'gpa_scale'.} \item{omit_from_final_grade}{boolean - Whether this assignment is counted towards a student's final grade.} \item{quiz_lti}{boolean - Whether this assignment should use the Quizzes 2 LTI tool. Sets the submission type to 'external_tool' and configures the external tool attributes to use the Quizzes 2 LTI tool configured for this course. Has no effect if no Quizzes 2 LTI tool is configured.} } \description{ Create a course assignment } \examples{ create_course_assignment(course_id = 432432, name = "Challenging Assignment") create_course_assignment(course_id = 3432432, name = "R Packages, Review", peer_reviews = TRUE, points_possible = 100, omit_from_final_grade = TRUE) }
467a5cb825e22f212b5a78ea30c33d81750a7033
1f6d79658ce351eafa3bf83cf38949d82b58de2f
/man/diffnet_check_attr_class.Rd
036294892729f14b1260efbf1df6e3d7e2f102ad
[ "MIT" ]
permissive
USCCANA/netdiffuseR
3dd061f8b9951f7bdc5ec69cded73144f6a63cf7
7c5c9a7d4a8120491bfd44d6e307bdb5b66c18ae
refs/heads/master
2023-09-01T08:26:19.951911
2023-08-30T15:44:09
2023-08-30T15:44:09
28,208,077
85
23
NOASSERTION
2020-03-14T00:54:59
2014-12-19T00:44:59
R
UTF-8
R
false
true
728
rd
diffnet_check_attr_class.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/diffnet-indexing.r \name{diffnet_check_attr_class} \alias{diffnet_check_attr_class} \title{Infer whether \code{value} is dynamic or static.} \usage{ diffnet_check_attr_class(value, meta) } \arguments{ \item{value}{Either a matrix, data frame or a list. Attribute values.} \item{meta}{A list. A diffnet object's meta data.} } \value{ The value object either as a data frame (if static) or as a list of data frames (if dynamic). If \code{value} does not follows the permitted types of \code{\link{diffnet_index}}, then returns with error. } \description{ Intended for internal use only, this function is used in \code{\link{diffnet_index}} methods. }
42e69cb0f2aed966673789ba384d84b1758e4571
e8577e571531992fa56a9173a19c55529716502b
/tests/testthat/test-golem.R
7a39a39b69320843a697c95583a75bd0ae150bfe
[ "MIT" ]
permissive
DivadNojnarg/packer
bcd2c3a13da1308761fcef6cc124aeabfc478b2b
332e01964835bf4cdf3d5dfc1eb0f2c43d3db107
refs/heads/master
2023-08-29T14:59:35.402851
2021-10-17T12:27:30
2021-10-17T12:27:30
416,646,602
0
0
null
null
null
null
UTF-8
R
false
false
2,166
r
test-golem.R
source("../fns.R") skip_on_cran() test_that("Golem Bare", { # keep working directory wd <- getwd() # test bare pkg <- create_tmp_golem() setwd(pkg) on.exit({ setwd(wd) delete_tmp_package(pkg) }) expect_output(scaffold_golem(edit = FALSE)) expect_error(scaffold_golem(edit = FALSE)) expect_message(bundle_dev()) expect_message(add_plugin_html(use_pug = TRUE)) expect_message(add_plugin_prettier()) expect_message(add_plugin_eslint()) expect_message(add_plugin_jsdoc(FALSE)) add_jsdoc_tutorial("xxx", FALSE) expect_message(add_plugin_workbox()) }) test_that("Golem CDN", { # keep working directory wd <- getwd() # test react pkg <- create_tmp_golem() setwd(pkg) expect_output(scaffold_golem(react = TRUE, edit = FALSE)) expect_message(bundle()) expect_message(use_loader_mocha(FALSE)) setwd(wd) delete_tmp_package(pkg) # test vue pkg <- create_tmp_golem() setwd(pkg) expect_output(scaffold_golem(vue = TRUE, edit = FALSE)) expect_message(bundle()) expect_message(add_plugin_clean()) setwd(wd) delete_tmp_package(pkg) }) test_that("Golem no CDN", { # keep working directory wd <- getwd() # test react pkg <- create_tmp_golem() setwd(pkg) expect_output(scaffold_golem(react = TRUE, use_cdn = FALSE, edit = FALSE)) expect_message(bundle()) expect_message(npm_console()) expect_message(npm_run("production")) setwd(wd) delete_tmp_package(pkg) # test vue pkg <- create_tmp_golem() setwd(pkg) expect_output(scaffold_golem(vue = TRUE, use_cdn = FALSE, edit = FALSE)) expect_message(bundle()) setwd(wd) delete_tmp_package(pkg) # test framework7 pkg <- create_tmp_golem() setwd(pkg) expect_output(scaffold_golem(framework7 = TRUE, edit = FALSE)) expect_message(bundle()) setwd(wd) delete_tmp_package(pkg) }) test_that("Golem F7", { # keep working directory wd <- getwd() # test bare pkg <- create_tmp_golem() setwd(pkg) on.exit({ setwd(wd) delete_tmp_package(pkg) }) expect_output(scaffold_golem(framework7 = TRUE, edit = FALSE)) expect_error(scaffold_golem(edit = FALSE)) expect_message(bundle_dev()) })
affa1b8754127a55c4d0e31899f70c5a9c75cae2
1ea6b75a27e313ec0a0386e28352f390a6915677
/Examples/4_DefaultCreditCard.r
1740766c57eed3f983e319e08ecaa2da37014a40
[]
no_license
NQuinn27/NCIY4_R_Labs
7cb160943d64868282e9df9e7ad6fd75f3d560bf
ce9f062b5bc9ed022fc59344ed9beaa4ddd9c2ff
refs/heads/master
2021-01-11T02:19:03.436797
2016-10-15T09:46:10
2016-10-15T09:46:10
70,979,428
0
0
null
null
null
null
UTF-8
R
false
false
2,660
r
4_DefaultCreditCard.r
install.packages(c("e1071", "C50", "ggplot2", "hexbin","descr", "caret", "e1071")) library(e1071) library(hexbin) library(ggplot2) library(caret) library(descr) library(C50) setwd("Developer/NCI/Data Application Design") # First remove first row (i.e., X1, X2 etc.) and export the data as .csv from Excel data <- read.csv("default of credit card clients.csv", stringsAsFactors=F) data <- data[-1] str(data) View(data) summary(data) #tranform the #SEX column from numeric to a Factor (vector with associated labels) data$SEX <- factor(data$SEX, levels=c(1, 2), labels=c("M", "F")) summary(data) table(data$EDUCATION, useNA='ifany') table(data$MARRIAGE, useNA='ifany') data$EDUCATION <- factor(data$EDUCATION, levels=c(0, 1, 2, 3, 4, 5, 6), labels=c(NA, "GS", "UNI", "HS", "O1", "O2", "O3")) data$MARRIAGE <- factor(data$MARRIAGE, levels=c(0, 1, 2, 3), labels=c(NA, "M", "S", "O")) data$default.payment.next.month <- factor(data$default.payment.next.month, levels=c(0, 1), labels=c("N", "Y")) str(data) summary(data) # Descriptive statistics and plots mean(data$LIMIT_BAL) summary(data$LIMIT_BAL) median(data$LIMIT_BAL) sd(data$LIMIT_BAL) IQR(data$LIMIT_BAL) mad(data$LIMIT_BAL) boxplot(data$LIMIT_BAL) hist(data$LIMIT_BAL, freq=F) lines(density(data$LIMIT_BAL), lwd=3, col="blue") ggplot(data, aes(x=LIMIT_BAL, y=AGE)) + stat_binhex(colour="white") + theme_bw() + scale_fill_gradient(low="white", high="blue") + labs(x="Limit Balance", y="Age") ggplot(data, aes(x=LIMIT_BAL, y=AGE)) + stat_binhex(colour="white") + theme_bw() + scale_fill_gradient(low="white", high="blue") + labs(x="Limit Balance", y="Age") + facet_wrap("EDUCATION") CrossTable(data$EDUCATION, data$default.payment.next.month, prop.c=F, prop.t=F, prop.chisq=F) boxplot(LIMIT_BAL ~ EDUCATION, data=data) ggplot(data=data, aes(EDUCATION, LIMIT_BAL)) + geom_violin(fill="lightblue") + geom_boxplot( alpha=.2) # Randomise data data_rand <- data[order(runif(10000)), ] summary(data$LIMIT_BAL) summary(data_rand$LIMIT_BAL) # Create test and train subsets train <- data_rand[1:9000, ] test <- data_rand[9001:10000, ] prop.table(table(train$default.payment.next.month)) prop.table(table(test$default.payment.next.month)) # Train the classifier (i.e., decusion tree) credit_model <- C5.0(train[-24], train$default.payment.next.month) credit_model summary(credit_model) #Evaluate the model credit_pred <- predict(credit_model, test) CrossTable(test$default.payment.next.month, credit_pred,prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c('actual default', 'predicted default')) confusionMatrix(credit_pred, test$default.payment.next.month, positive = "Y")
a6e3d1820e9f78af549205514fe4336d2d17661d
f898801224c1f17ba62089b28f3f69c7c525e766
/binomial/man/bin_probability.Rd
b149aac2493a72bde00e98ddac62ae3ae437c2cc
[]
no_license
stat133-sp19/hw-stat133-nadia1212
44079944e7b5ab9dffdddbbb3fb82033d2de79a9
57ba3ab524660f9d3e8162f1b53a6d030eac6dd6
refs/heads/master
2020-04-28T12:33:00.104710
2019-05-03T19:14:44
2019-05-03T19:14:44
175,279,474
0
0
null
null
null
null
UTF-8
R
false
true
447
rd
bin_probability.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/functions.R \name{bin_probability} \alias{bin_probability} \title{bin_probability} \usage{ bin_probability(success, trials, prob) } \arguments{ \item{success}{number of success} \item{trials}{number of trials} \item{prob}{probability of success} } \value{ number of combinations } \description{ finds number of combinations in which k success can occur in n trials }
dfa4f2bc4f44c54fec8d7db3de36d71c672e0c72
72d9009d19e92b721d5cc0e8f8045e1145921130
/spass/inst/testfiles/mlFirstHExp/libFuzzer_mlFirstHExp/libfuzzer_logs/1609981123-inps.R
8a1d6fcad90d0447c14a8fc2ea60b5c6155bd97f
[]
no_license
akhikolla/TestedPackages-NoIssues
be46c49c0836b3f0cf60e247087089868adf7a62
eb8d498cc132def615c090941bc172e17fdce267
refs/heads/master
2023-03-01T09:10:17.227119
2021-01-25T19:44:44
2021-01-25T19:44:44
332,027,727
1
0
null
null
null
null
UTF-8
R
false
false
109
r
1609981123-inps.R
list(kf = 0, tp = 0L, type = 0L, y = numeric(0)) testlist <- list(kf = 0, tp = 0L, type = 0L, y = numeric(0))
3c66d0a8d5998ca3f88b983fa45d685f9fcc5974
8849921ce5655845b566e5f740fba1a399432fe6
/R/CUSUM.R
0602c64cba83915bbb70637a23497a89b38b1940
[]
no_license
cran/spcadjust
3ad36af53c3eb6c0541f81656445177f3ea67b78
de5d69322dcb921c7755154e30e5cbd659730f80
refs/heads/master
2021-01-22T23:53:18.673892
2016-09-29T11:37:35
2016-09-29T11:37:35
17,699,983
2
0
null
null
null
null
UTF-8
R
false
false
5,440
r
CUSUM.R
######################## ## Basic CUSUM Charts ## ######################## #' @include main.R model.R CUSUMlib.R NULL #' CUSUM Charts #' #' Class extending SPCChart with a basic CUSUM charts implementation. #' #' The only slot this class contains is the data model. This data #' model should already incorporate the negative mean for in-control #' updates that is typical for CUSUM charts. #' #' Let \eqn{U_t, t=1,2,\dots} be the updates from the data model. Then #' the CUSUM chart is given by \eqn{S_0=0} and #' \deqn{S_t=max(S_{t-1}+U_t,0)} #' #' @examples #' X <- rnorm(1000) #' chart <- new("SPCCUSUM",model=SPCModelNormal(Delta=1)) #' \dontrun{ #' SPCproperty(data=X,nrep=10,chart=chart, #' property="calARL",params=list(target=100)) #' SPCproperty(data=X,nrep=10,chart=chart, #' property="calhitprob",params=list(target=0.05,nsteps=1e3)) #' SPCproperty(data=X,nrep=10,chart=chart, #' property="ARL",params=list(threshold=3)) #' } #' SPCproperty(data=X,nrep=10,chart=chart, #' property="hitprob",params=list(threshold=3,nsteps=1e3)) #' #increase the number of repetitions nrep for real applications. #' #' @export setClass("SPCCUSUM",contains="SPCchart") #' @describeIn runchart Generic function for running CUSUM #' charts. Relies on \code{\link{updates}} being implemented for the #' chart. #' @export setMethod("runchart", signature="SPCCUSUM", function(chart,newdata,xi){ R <- cumsum(chart@model$updates(xi=xi, data=newdata)) R - cummin(R) }) #' @describeIn getq Implements the properties \code{ARL}, #' \code{calARL}, \code{hitprob} and \code{calhitprob}. #' #' @export setMethod("getq", signature="SPCCUSUM",function(chart,property,params){ if (is.null(params[["gridpoints"]])) params$gridpoints=75; if (grepl("cal",property)&&is.null(params$target)) stop("Argument params contains no element target (needed for calibration).") if (grepl("hitprob",property)){ if (is.null(params$nsteps)) stop("Argument params does not contain an element nsteps (needed for hitting probabilities).") else if (params$nsteps<1|round(params$nsteps)!=params$nsteps) stop("nsteps has to be a positive integer.") } if (is.element(property,c("ARL","hitprob"))){ if (is.null(params$threshold)) stop("Argument params does not contain an element threshold.") else if (params$threshold<0) stop("Negative threshold.") } switch(property, "calARL"= list(q= function(P,xi) log(calibrateARL_Markovapprox(pobs=getcdfupdates(chart,xi=xi, P=P), ARL=params$target, gridpoints=params$gridpoints)), trafo=function(x) exp(x), lowerconf=TRUE, format=function(res) paste("A threshold of ", format(res,digits=4), " gives an in-control ARL of at least ", params$target, ".", sep="",collapse="") ), "ARL"= list(q= function(P,xi){ as.double(log(ARL_CUSUM_Markovapprox(c=params$threshold,pobs=getcdfupdates(chart,xi=xi, P=P),gridpoints=params$gridpoints))) }, trafo=function(x) exp(x), lowerconf=FALSE, format=function(res) paste("A threshold of ", params$threshold, " gives an in-control ARL of at least ", format(res,digits=4), ".", sep="",collapse="") ), "hitprob"= list(q=function(P,xi){ res <- hitprob_CUSUM_Markovapprox(c=params$threshold,pobs=getcdfupdates(chart,xi=xi, P=P),n=params$nsteps,gridpoints=params$gridpoints); as.double(log(res/(1-res))) }, trafo=function(x) exp(x)/(1+exp(x)), lowerconf=TRUE, format=function(res) paste("A threshold of ", params$threshold, " gives an in-control false alarm probability of at most ", format(res,digits=4), " within ",params$nsteps," steps.", sep="",collapse="") ), "calhitprob"= list(q=function(P,xi) log(calibratehitprob_Markovapprox(pobs=getcdfupdates(chart,xi=xi, P=P), hprob=params$target, n=params$nsteps, gridpoints=params$gridpoints)), trafo=function(x) exp(x), lowerconf=TRUE, format=function(res) paste("A threshold of ", format(res,digits=4), " gives an in-control false alarm probability of at most ", params$target, " within ",params$nsteps, " steps.", sep="",collapse="") ), stop(paste("Property",property,"not implemented.")) ) })
6d435a409f3ef5bcabef5dd4a40b2aca3ce00406
04eb50424b3fa3e24fff24fbcab6c7b7fcb22f65
/scripts/merge_1000.R
7d0991d1ef4f4a572f6f926481694db71d5396fc
[]
no_license
jonathanperrie/bigham_climber_dump
070992955761d26e33009e71a6b420f3c611c33f
46884c0c975fb2782f7e70af7751873c1c2071d9
refs/heads/main
2023-06-21T14:33:00.647978
2021-07-29T17:24:49
2021-07-29T17:24:49
389,523,877
0
0
null
null
null
null
UTF-8
R
false
false
1,955
r
merge_1000.R
library(VariantAnnotation) setwd("~/Bigham/v2/") data <- read.table("igsr_samples.tsv",sep="\t",header=T) x <- scan("intersect_set.txt", what="", sep="\n") setwd("~/Bigham/v2/1000") geno1000_list<-read.table("affy_samples.20141118.panel",sep="\t",header=T) matches_2 <- data[data$Sample.name %in% geno1000_list$sample,] matches_2 <- matches_2[matches_2$Superpopulation.name=="European Ancestry",] write.csv(matches_2[c("Sample.name","Sex","Population.code")],"1000geno_meta.csv",quote=F,row.names=FALSE) genoSum <- function(x) { suppressWarnings(sum(as.integer(strsplit(x,"/")[[1]]))) } genoSumOneRow <- function(y){ sapply(y,genoSum) } idx<- 1 param <- ScanVcfParam(fixed="ALT", geno=c("GT")) tab <- TabixFile("ALL.wgs.nhgri_coriell_affy_6.20140825.genotypes_has_ped.vcf.gz", yieldSize=25000) open(tab) # first pass to append column names vcf_yield <- readVcf(tab, param=param) tmp<-geno(vcf_yield[rownames(vcf_yield) %in% x,colnames(vcf_yield) %in% matches_2$Sample.name])$GT geno_int <- matrix(nrow=dim(tmp)[1],ncol=dim(tmp)[2]) rownames(geno_int)<-rownames(tmp) colnames(geno_int)<-colnames(tmp) for (i in seq(dim(tmp)[1])){ geno_int[i,] <- sapply(tmp[i,],genoSumOneRow) } write.table(geno_int,"1000Genomes_intersect.tsv",sep="\t",quote=F,col.names=NA,row.names=TRUE,append=FALSE) print(idx) idx <- idx+1 # additional passes to not append column names while (nrow(vcf_yield <- readVcf(tab, param=param))){ tmp<-geno(vcf_yield[rownames(vcf_yield) %in% x,colnames(vcf_yield) %in% matches_2$Sample.name])$GT geno_int <- matrix(nrow=dim(tmp)[1],ncol=dim(tmp)[2]) rownames(geno_int)<-rownames(tmp) colnames(geno_int)<-colnames(tmp) for (i in seq(dim(tmp)[1])){ geno_int[i,] <- sapply(tmp[i,],genoSumOneRow) } write.table(geno_int,"1000Genomes_intersect.tsv",sep="\t",quote=F,col.names=FALSE,row.names=TRUE,append=TRUE) print(idx) idx <- idx+1 } close(tab)
50e959bf19c7434a6dadfc261542068458af2b32
9ec240c392225a6b9408a1636c7dc6b7d720fd79
/packrat/src/backports/backports/man/file.size.Rd
0a5914342e5f922492c72c18f7979a62a068119f
[]
no_license
wjhopper/PBS-R-Manual
6f7709c8eadc9e4f7a163f1790d0bf8d86baa5bf
1a2a7bd15a448652acd79f71e9619e36c57fbe7b
refs/heads/master
2020-05-30T17:47:46.346001
2019-07-01T15:53:23
2019-07-01T15:53:23
189,883,322
0
1
null
null
null
null
UTF-8
R
false
true
795
rd
file.size.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/file.mode.R, R/file.mtime.R, R/file.size.R \name{file.mode} \alias{file.mode} \alias{file.mtime} \alias{file.size} \title{Backports of wrappers around \code{file.info} for R < 3.2.0} \usage{ file.mode(...) file.mtime(...) file.size(...) } \description{ See the original description in \code{base::file.size}. } \examples{ # get functions from namespace instead of possibly getting # implementations shipped with recent R versions: bp_file.size = getFromNamespace("file.size", "backports") bp_file.mode = getFromNamespace("file.size", "backports") bp_file.mtime = getFromNamespace("file.size", "backports") fn = file.path(R.home(), "COPYING") bp_file.size(fn) bp_file.mode(fn) bp_file.size(fn) } \keyword{internal}
9139adf60c030d3435badf6065649dfe0cc263b7
79aa103b7b35ae807444be74805e42ed4e57acc5
/R/ggscatter.R
ecd70c1d37ca72f981baa5fe34adf14dd4bbd870
[ "MIT" ]
permissive
UBC-MDS/ggexpress
47ac0252e35ae6f7ee0cc52743bd303b45219d09
76e9692c62054a71534d8da1c98f03c424e3a4cc
refs/heads/master
2021-01-15T06:03:34.739464
2020-03-26T22:45:36
2020-03-26T22:45:36
242,897,067
2
1
NOASSERTION
2020-03-26T22:45:38
2020-02-25T03:06:09
R
UTF-8
R
false
false
1,872
r
ggscatter.R
library(dplyr) library(ggplot2) #' Create a scatterplot and calculate correlation values for two numerical variables #' #' Creates a ggplot scatterplot object containing two numerical variables. Arguments in the #' function will control whether correlational values and log transformations are calculated for the input data. #' #' @param df Dataframe to plot #' @param xval x-var Column name used as the x-axis variable #' @param yval y-var Column name used as the y-axis variable #' @param x_transform Determines whether the x-axis undergoes a natural log transformation #' @param y_transform Determines whether the y-axis undergoes a natural log transformation #' #' @return ggplot Object #' @export #' #' @examples #' scatter_express(iris, Sepal.Width, Sepal.Length) scatter_express <- function(df, xval = NA, yval = NA, x_transform = FALSE, y_transform = FALSE){ corr_df <- dplyr::select(df, {{xval}}, {{yval}}) if (is.numeric(corr_df[[1]]) == FALSE) stop("Your x-variable must be numeric") if (is.numeric(corr_df[[2]]) == FALSE) stop("Your y-variable must be numeric") corr_val <- round(stats::cor(corr_df[[1]], corr_df[[2]]), 2) scatter <- ggplot2::ggplot(corr_df, ggplot2::aes(x = {{xval}}, y = {{yval}})) + ggplot2::geom_point(color = "blue") if (x_transform == TRUE) { scatter <- scatter + ggplot2::scale_x_continuous(trans = "log2") } if (y_transform == TRUE) { scatter <- scatter + ggplot2::scale_y_continuous(trans = "log2") } scatter <- scatter + ggplot2::labs(title = paste(rlang::get_expr(scatter$mapping$x), " vs ", rlang::get_expr(scatter$mapping$y), "(Pearson Correlation: ", corr_val, ")")) scatter }
74cdbc5eec50d85ca2197607cafb639dead4b79f
d11fadd13f28e7223c37a8395661cc650159c817
/R/urbn_geofacet.R
7d895f16d4526fdae40acf784efe2f54c15d263c
[]
no_license
scoultersdcoe/urbnthemes
4f5a7dd3a76bc68a1b2709fc866e737503a49062
8d88a618c8bf50a4c8c4a80eef3bfd5f5f4e9200
refs/heads/master
2023-08-01T02:59:26.110414
2021-09-03T20:58:11
2021-09-03T20:58:11
null
0
0
null
null
null
null
UTF-8
R
false
false
284
r
urbn_geofacet.R
#' Urban Institute geofacet template #' #' @format Data frame with columns #' \describe{ #' \item{row}{Row in geofacet} #' \item{col}{Column in geofacet} #' \item{state_abbv}{State abbreviation} #' \item{state_name}{State name} #' } "urbn_geofacet" #' @importFrom tibble tibble NULL
5f8d01ae57a3d97ee718f3c859ea198761d04b46
95f82fae345c99b0ac48f7080306617d8af109da
/run_analysis.R
f9f3a464ea2681b8df13035dcd6acdec40e8c837
[]
no_license
PavelMAA/Getting-and-Cleaning-Data-Course-Project
681ac6a7e06a68081f5a05012bbfdbb4ebf10a26
a965fcf2ee7b4b69b420fc4e7090f47760ba20e3
refs/heads/master
2023-06-28T02:00:42.938567
2021-08-06T00:58:28
2021-08-06T00:58:28
393,202,736
0
0
null
null
null
null
UTF-8
R
false
false
2,974
r
run_analysis.R
rm(list = ls()) ##install library install.packages("reshape2") install.packages("dplyr") library(reshape2) library(dplyr) ## define directory setwd("C:/Coursera/GettingData") #Get data(data> UCI HAR Dataset) if(!file.exists("./data")){dir.create("./data")} fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(fileUrl,destfile="./data/Dataset.zip",method="curl") #unzip data in the folder (data> UCI HAR Dataset) unzip(zipfile="./data/Dataset.zip",exdir="./data") #define the path p_rf <- file.path("./data" , "UCI HAR Dataset") f<-list.files(p_rf, recursive=TRUE) f #Read the data from the files dActivityTest <- read.table(file.path(p_rf, "test" , "Y_test.txt" ),header = FALSE) dActivityTrain <- read.table(file.path(p_rf, "train", "Y_train.txt"),header = FALSE) dSubjectTrain <- read.table(file.path(p_rf, "train", "subject_train.txt"),header = FALSE) dSubjectTest <- read.table(file.path(p_rf, "test" , "subject_test.txt"),header = FALSE) dFeaturesTest <- read.table(file.path(p_rf, "test" , "X_test.txt" ),header = FALSE) dFeaturesTrain <- read.table(file.path(p_rf, "train", "X_train.txt"),header = FALSE) ##Check the properties of the variable str(dActivityTest) str(dActivityTrain) str(dSubjectTest) str(dSubjectTrain) str(dFeaturesTest) str(dFeaturesTrain) #Merges the training and the test sets to create one data set dSubject <- rbind(dSubjectTrain, dSubjectTest) dActivity<- rbind(dActivityTrain, dActivityTest) dFeatures<- rbind(dFeaturesTrain, dFeaturesTest) # Tidy the variable name names(dSubject)<-c("subject") names(dActivity)<- c("activity") # read the feature.txt dFeaturesNames <- read.table(file.path(p_rf, "features.txt"),head=FALSE) names(dFeatures)<- dFeaturesNames$V2 # Merge the data set dCombine <- cbind(dSubject, dActivity) D <- cbind(dFeatures, dCombine) # Calculate the mean and standard deviation subdFeaturesNames<-dFeaturesNames$V2[grep("mean\\(\\)|std\\(\\)", dFeaturesNames$V2)] # Add the "subject", "activity" with the subdFeaturesNames selectedNames<-c(as.character(subdFeaturesNames), "subject", "activity" ) # Create again data set base on the selectedNames D<-subset(D,select=selectedNames) str(D) #Uses descriptive activity names to name of the activities in the data set activityLabels <- read.table(file.path(p_rf, "activity_labels.txt"),header = FALSE) head(D$activity,30) #Appropriately labels the data set with descriptive variable names names(D)<-gsub("^t", "time", names(D)) names(D)<-gsub("^f", "frequency", names(D)) names(D)<-gsub("Acc", "Accelerometer", names(D)) names(D)<-gsub("Gyro", "Gyroscope", names(D)) names(D)<-gsub("Mag", "Magnitude", names(D)) names(D)<-gsub("BodyBody", "Body", names(D)) names(D) #Creates a second,independent tidy data set and it output library(plyr); D2<-aggregate(. ~subject + activity, D, mean) D2<-D2[order(D2$subject,D2$activity),] write.table(D2, file = "tidydataset.txt",row.name=FALSE)
441abfb264f145b9b801ab942b3c3de5f2183669
f53c62df2e61aa215870b40ce90265bf97705960
/RNA_FISH/AC16_Tp53_Results.R
87667bd8ee5e3c168aa519f5f95d7b676ccd7404
[ "MIT" ]
permissive
hjf34/Cold
058b3ac970a20ef7902909d3d910261a784b6dbc
32c70926e4646e8db62f0e6752efe73dc8a19bc1
refs/heads/master
2023-02-23T03:06:37.524385
2021-01-19T15:32:03
2021-01-19T15:32:03
272,039,850
1
0
null
null
null
null
UTF-8
R
false
false
3,911
r
AC16_Tp53_Results.R
setwd("/path/to/Results.csv/directory/") lf = list.files() lf1 = lf[grep("Results.csv", lf)] filenamestem = as.vector(sapply(lf1, function(n) strsplit(n, ".dv")[[1]][1])) Nr1d1NuclearDots = rep(NA, length(lf1)) Nr1d1CytoplasmicDots = rep(NA, length(lf1)) NuclearArea = rep(NA, length(lf1)) WholeCellArea = rep(NA, length(lf1)) for(a1 in 1:length(lf1)){ csv1 = read.csv((lf1[a1]), stringsAsFactors = F) NuclearArea[a1] = csv1$Area[1] WholeCellArea[a1] = csv1$Area[2] Nr1d1NuclearDots[a1] = csv1$Count[3] Nr1d1CytoplasmicDots[a1] = csv1$Count[4] } condition_repeat = as.vector(sapply(lf1, function(n) strsplit(n, "_Poor")[[1]][1])) condition = as.vector(sapply(lf1, function(n) strsplit(n, "_Rep")[[1]][1])) df = data.frame(condition_repeat, condition, Nr1d1NuclearDots,Nr1d1CytoplasmicDots,NuclearArea,WholeCellArea) df$CytoplasmicArea = df$WholeCellArea - df$NuclearArea df$cba = df$Nr1d1CytoplasmicDots/df$CytoplasmicArea df$nba = df$Nr1d1NuclearDots/df$NuclearArea df1 = df row.names(df1) = filenamestem colnames(df1)[c(8,9)] = c("DotsPerCyt","DotsPerNuc") repsimaged = data.frame(images=c(table(df1$condition_repeat))) write.csv(repsimaged, file="AC16_Tp53_RepsImaged.csv") write.csv(df1, file="AC16_Tp53_Dots_Per_Image.csv") ########################################################################## ########################################################################## dba = df[,c("condition","cba","nba")] dba$condition = as.vector(dba$condition) dba1 = dba dba1$condition1 = factor(dba1$condition, levels=names(table(dba1$condition))[c(3,1,2)]) ########################################################################### ########PER IMAGE PLOT AND STATS mx1 = aggregate(dba1[,2:3], by=list(dba1$condition1), function(n) mean(n)) sx1 = aggregate(dba1[,2:3], by=list(dba1$condition1), function(n) sd(n)/sqrt(length(n))) m1 = mx1[,3]; m2 = mx1[,2] sem1 = sx1[,3]; sem2 = sx1[,2] ################################# ################################# barplotter = function(means,sems,colours){ mx = means smx = sems par(mar = c(1,5,1,1)) mp = barplot(mx, cex.axis=1.5,col=colours, ylim = c(0,1.2*max(mx+smx, na.rm=T)),xaxt="n", las=1, main = "", ylab = "") subseg1 = as.numeric(mx) -as.numeric(smx) subseg2 = as.numeric(mx) +as.numeric(smx) subseg1[subseg1 < 0] = 0 segments(mp, subseg1, mp, subseg2, lwd=2) segments(mp-0.2, subseg1, mp+0.2, subseg1, lwd=2) segments(mp-0.2, subseg2, mp+0.2, subseg2, lwd=2) box(lwd = 2) } colours1 = c("gold","dodgerblue3","purple") #########################NUCLEAR png("AC16_Tp53NucPerImageMeanSEM.png", height = 3, width = 2.5, units = "in", res = 600) barplotter(m1,sem1,colours1) dev.off() #########################CYTOPLASMIC png("AC16_Tp53CytPerImageMeanSEM.png", height = 3, width = 2.5, units = "in", res = 600) barplotter(m2,sem2,colours1) dev.off() ########################################################################### ########################################################################### ########################################################################### summary(aov(cba~condition1, data=dba1)) cTHSD = TukeyHSD(aov(cba~condition1, data=dba1))$condition1 summary(aov(nba~condition1, data=dba1)) nTHSD = TukeyHSD(aov(nba~condition1, data=dba1))$condition1 aovdata = rbind(data.frame(summary(aov(nba~condition1, data=dba1))[[1]]),data.frame(summary(aov(cba~condition1, data=dba1))[[1]])) row.names(aovdata) = c("Nuc_Condition","Nuc_Residuals","Cyt_Condition","Cyt_Residuals") THSD = rbind(nTHSD,cTHSD) row.names(THSD) = c(paste("Nuc_",row.names(THSD)[1:3], sep=""),paste("Cyt_",row.names(THSD)[4:6], sep="")) write.csv(THSD, file="AC16_Tp53_TukeyHSDdata.csv") write.csv(aovdata, file="AC16_Tp53_ANOVAdata.csv") ############################################################################# #############################################################################
44b23c880aa8e07ec657d656bc673732b05d359c
58ec8c9b97ea1bd69aed7d55c994f026aad420a2
/man/myLinearRegression.Rd
9ad23a596fc9d193f55a1314881351bfa4377c23
[]
no_license
msalmon7/myLinearRegressionPackage
6a888f366a806a30809e86e9549b39d9dee53cdc
de07ff8619f8b9483515380a022df738b9c43da6
refs/heads/master
2022-06-12T07:36:05.779333
2020-05-01T15:39:08
2020-05-01T15:39:08
260,494,542
0
0
null
null
null
null
UTF-8
R
false
true
1,716
rd
myLinearRegression.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/myLinearRegression.R \name{myLinearRegression} \alias{myLinearRegression} \title{Perform linear regression and create scatterplots of each pair of covariates.} \usage{ myLinearRegression(y = myData[, 1], x = myData[, 2:4], sub = c(1:20)) } \arguments{ \item{y}{A vector of outcomes.} \item{x}{A matrix of covariates.} \item{sub}{A list of subjects (i.e. a set of integers corresponding to rows in x)} } \value{ The coefficients and p-values of a linear regression performed on \code{y} subject to \code{x} and a scatterplot matrix of each pair of covariates. } \description{ This function takes inputs of a vector as the dependent variable, a matrix as a set of independent variables, and a list of subjects from these sets to perform linear regression. The function outputs the coefficients and p-values from the regression as well as a scatterplot matrix barring that there are more than 5 covariates, in which case a warning is given. } \examples{ # You can reference the data any way you would like. For example, the # data set myData is running a linear regression of column "Y" and columns # "X1", "X2", and "X3." This data set has 100 rows, but we're using the sub # function to specify that we only want to look at the first 30. myLinearRegression(y = myData[, "Y"], x = myData[ ,c("X1", "X2", "X3")], sub = c(1:30)) # Similarly, you can create your own vector to perform linear regression with. # If 5 or more columns are selected as covariates, as is the case here, the # function will not output any scatterplots. This only looks at rows 5 through 20. myLinearRegression(y = c(1:50), x = myData[ ,2:6], sub = c(5:20)) }
621cb6f6284d288722ea7ba040069c127d0a5f22
10af39cbdd712d0bd786232d41089b71005788aa
/data_raw/results_exp_ols_mc.mvn_ci.R
6f0099a4c0792962599f3c4d218eb4dd738c63f1
[ "MIT" ]
permissive
jeksterslabds/jeksterslabRmedsimple
1f914691b75c44f14ea6701bdbec776908997da5
4a14bc41892bfa670ebc56f691262475986d48fb
refs/heads/master
2022-12-30T23:59:12.475315
2020-10-16T05:48:55
2020-10-16T05:48:55
287,948,188
0
0
null
null
null
null
UTF-8
R
false
false
1,123
r
results_exp_ols_mc.mvn_ci.R
#' --- #' title: "Data: Simple Mediation Model - Exponential X lambda = 1 - Complete Data - Monte Carlo Method Confidence Intervals with Ordinary Least Squares Parameter Estimates and Standard Errors" #' author: "Ivan Jacob Agaloos Pesigan" #' date: "`r Sys.Date()`" #' output: #' rmarkdown::html_vignette: #' toc: true #' vignette: > #' %\VignetteIndexEntry{Data: Simple Mediation Model - Exponential X lambda = 1 - Complete Data - Monte Carlo Method Confidence Intervals with Ordinary Least Squares Parameter Estimates and Standard Errors} #' %\VignetteEngine{knitr::rmarkdown} #' %\VignetteEncoding{UTF-8} #' --- #' #+ data results_exp_ols_mc.mvn_ci <- readRDS("summary_medsimple_exp_ols_mc.mvn_pcci.Rds") # subset # results_exp_ols_mc.mvn_ci <- results_exp_ols_mc.mvn_ci[which(results_exp_ols_mc.mvn_ci$taskid < 145 | results_exp_ols_mc.mvn_ci$taskid > 153), ] # results_exp_ols_mc.mvn_ci <- results_exp_ols_mc.mvn_ci[which(results_exp_ols_mc.mvn_ci$n > 20), ] head(results_exp_ols_mc.mvn_ci) str(results_exp_ols_mc.mvn_ci) #' #+ usedata usethis::use_data( results_exp_ols_mc.mvn_ci, overwrite = TRUE )
49be68b4186cc4bf35bf4254668cd9f1872b2a94
7d5d8492c2d88b88bdc57e3c32db038a7e7e7924
/PhD/0007-crop-modelling/scripts/cmip5/06.bc_rain-functions.R
5d07755a84e26bc7b9652dddcd94f375b24e3cb3
[]
no_license
CIAT-DAPA/dapa-climate-change
80ab6318d660a010efcd4ad942664c57431c8cce
2480332e9d61a862fe5aeacf6f82ef0a1febe8d4
refs/heads/master
2023-08-17T04:14:49.626909
2023-08-15T00:39:58
2023-08-15T00:39:58
39,960,256
15
17
null
null
null
null
UTF-8
R
false
false
13,291
r
06.bc_rain-functions.R
#Julian Ramirez-Villegas #UoL / CIAT / CCAFS #Oct 2012 #final wrap wrap_bc_wthmkr <- function(k) { source(paste(src.dir,"/0007-crop-modelling/scripts/cmip5/06.bc_rain-functions.R",sep="")) lmts <- bc_rain_wrapper(k) # bias correct the data ctrf <- make_bc_wth_wrapper(k) # generate the wth files } #make bias corrected weather files for GLAM runs make_bc_wth_wrapper <- function(i) { library(raster) #source functions of interest source(paste(src.dir,"/0006-weather-data/scripts/GHCND-GSOD-functions.R",sep="")) source(paste(src.dir,"/0008-CMIP5/scripts/CMIP5-functions.R",sep="")) source(paste(src.dir,"/0007-crop-modelling/scripts/cmip5/06.bc_rain-functions.R",sep="")) source(paste(src.dir,"/0007-crop-modelling/scripts/cmip5/01.make_wth-functions.R",sep="")) source(paste(src.dir,"/0007-crop-modelling/scripts/glam/glam-make_wth.R",sep="")) sce <- paste(all_proc$GCM[i]) gcm <- unlist(strsplit(sce,"_ENS_",fixed=T))[1] ens <- unlist(strsplit(sce,"_ENS_",fixed=T))[2] loc <- all_proc$LOC[i] #635 thisLeap <- paste(gcmChars$has_leap[which(gcmChars$GCM == gcm)][1]) #directories where the uncorrected data is inDir_his <- paste(hisDir,"/",gcm,"/",ens,sep="") #folder with raw gridded data inDir_rcp <- paste(rcpDir,"/",gcm,"/",ens,sep="") #folder with raw gridded data #directories where the bias corrected data is oDir_his_bc <- paste(bcDir_his,"/",gcm,"/",ens,sep="") #folder with bc gridded data oDir_rcp_bc <- paste(bcDir_rcp,"/",gcm,"/",ens,sep="") #folder with bc gridded data #directories where check files are checkDir <- paste(wthDirBc_his,"/_process",sep="") if (!file.exists(checkDir)) {dir.create(checkDir)} checkFil_his <- paste(checkDir,"/",sce,"_loc-",loc,".proc",sep="") #historical period if (!file.exists(checkFil_his)) { #copy all other data from the uncorrected output, and then remove it for (cvn in c("rsds","tasmax","tasmin")) { codir <- paste(oDir_his_bc,"/",cvn,sep="") if (!file.exists(codir)) {dir.create(codir)} ff <- file.copy(from=paste(inDir_his,"/",cvn,"/cell-",loc,".csv",sep=""),to=codir) } #create the daily data files for historical outfol_his <- write_cmip5_loc(all_locs=cells,gridcell=loc,scen=sce, year_i=1966,year_f=1993,wleap=thisLeap, out_wth_dir=wthDirBc_his,fut_wth_dir=oDir_his_bc, sow_date_dir=sowDir) #remove extra files for (cvn in c("rsds","tasmax","tasmin")) { codir <- paste(oDir_his_bc,"/",cvn,sep="") ff <- file.remove(from=paste(codir,"/cell-",loc,".csv",sep=""),to=codir) #system(paste("rm -rf ",codir,sep="")) } ff <- file(checkFil_his,"w") cat("Processed on",date(),"\n",file=ff) close(ff) } #directories where check files are checkDir <- paste(wthDirBc_rcp,"/_process",sep="") if (!file.exists(checkDir)) {dir.create(checkDir)} checkFil_rcp <- paste(checkDir,"/",sce,"_loc-",loc,".proc",sep="") if (!file.exists(checkFil_rcp)) { #copy all other data from the uncorrected output, and then remove it for (cvn in c("rsds","tasmax","tasmin")) { codir <- paste(oDir_rcp_bc,"/",cvn,sep="") if (!file.exists(codir)) {dir.create(codir)} ff <- file.copy(from=paste(inDir_rcp,"/",cvn,"/cell-",loc,".csv",sep=""),to=codir) } outfol_rcp <- write_cmip5_loc(all_locs=cells,gridcell=loc,scen=sce, year_i=2021,year_f=2049,wleap=thisLeap, out_wth_dir=wthDirBc_rcp,fut_wth_dir=oDir_rcp_bc, sow_date_dir=sowDir) #remove extra files for (cvn in c("rsds","tasmax","tasmin")) { codir <- paste(oDir_rcp_bc,"/",cvn,sep="") ff <- file.remove(from=paste(codir,"/cell-",loc,".csv",sep=""),to=codir) #system(paste("rm -rf ",codir,sep="")) } ff <- file(checkFil_rcp,"w") cat("Processed on",date(),"\n",file=ff) close(ff) } return(list(HIS=checkFil_his,RCP=checkFil_rcp)) } #bias correction wrapper function bc_rain_wrapper <- function(i) { library(raster) #source functions of interest source(paste(src.dir,"/0006-weather-data/scripts/GHCND-GSOD-functions.R",sep="")) source(paste(src.dir,"/0008-CMIP5/scripts/CMIP5-functions.R",sep="")) source(paste(src.dir,"/0007-crop-modelling/scripts/cmip5/06.bc_rain-functions.R",sep="")) source(paste(src.dir,"/0007-crop-modelling/scripts/cmip5/01.make_wth-functions.R",sep="")) source(paste(src.dir,"/0007-crop-modelling/scripts/glam/glam-make_wth.R",sep="")) sce <- paste(all_proc$GCM[i]) gcm <- unlist(strsplit(sce,"_ENS_",fixed=T))[1] ens <- unlist(strsplit(sce,"_ENS_",fixed=T))[2] loc <- all_proc$LOC[i] #635 thisLeap <- paste(gcmChars$has_leap[which(gcmChars$GCM == gcm)][1]) cat("processing",sce," / and loc = ",loc,"\n") #specific gcm directories oDir_his <- paste(bcDir_his,"/",gcm,"/",ens,"/",vn_gcm,sep="") oDir_rcp <- paste(bcDir_rcp,"/",gcm,"/",ens,"/",vn_gcm,sep="") if (!file.exists(oDir_his)) {dir.create(oDir_his,recursive=T)} if (!file.exists(oDir_rcp)) {dir.create(oDir_rcp,recursive=T)} ############################################################################# # bias correcting the GCM output precipitation ############################################################################# if (!file.exists(paste(oDir_his,"/fit_cell-",loc,".csv",sep=""))) { #read in observed and gcm data obs_data <- read.csv(paste(obsDir,"/",vn,"/cell-",loc,".csv",sep="")) his_data <- read.csv(paste(hisDir,"/",gcm,"/",ens,"/",vn_gcm,"/cell-",loc,".csv",sep="")) rcp_data <- read.csv(paste(rcpDir,"/",gcm,"/",ens,"/",vn_gcm,"/cell-",loc,".csv",sep="")) #separate months into individual series obs_list <- mk_mth_list(obs_data,"createDateGrid",dg_args=NA,yi_h,yf_h) his_list <- mk_mth_list(his_data,"createDateGridCMIP5",dg_args=thisLeap,yi_h,yf_h) rcp_list <- mk_mth_list(rcp_data,"createDateGridCMIP5",dg_args=thisLeap,yi_f,yf_f) #calculate loci metrics loci_mets <- loci_cal(obs_list,his_list,wdt_obs=1,iter_step=1e-4) #calculate bias corrected data based on historical data his_list <- loci_correct(his_list,loci_mets) #putting all the series together again into a matrix his_data_bc <- remake_daily(his_list,his_data,thisLeap,yi_h,yf_h) #here bias correct the future climates and plot the pdfs together rcp_list <- loci_correct(rcp_list,loci_mets) rcp_data_bc <- remake_daily(rcp_list,rcp_data,thisLeap,yi_f,yf_f) #here write the data write.csv(his_data_bc,paste(oDir_his,"/cell-",loc,".csv",sep=""),quote=T,row.names=F) write.csv(rcp_data_bc,paste(oDir_rcp,"/cell-",loc,".csv",sep=""),quote=T,row.names=F) write.csv(loci_mets,paste(oDir_his,"/fit_cell-",loc,".csv",sep=""),quote=T,row.names=F) } else { loci_mets <- read.csv(paste(oDir_his,"/fit_cell-",loc,".csv",sep="")) } return(loci_mets) } #calculate total rainfall and number of rainy days for the whole time series calc_metrics <- function(all_data,dg_fun="createDateGrid",dg_args=NA,yi,yf) { cat("calculating rainfall and rain days\n") odat_all <- data.frame() for (yr in yi:yf) { yr_data <- as.numeric(all_data[which(all_data$YEAR == yr),2:ncol(all_data)]) if (!is.na(dg_args)) { dg <- do.call(dg_fun,list(yr,dg_args)) } else { dg <- do.call(dg_fun,list(yr)) } dg$MTH <- as.numeric(substr(dg$MTH.DAY,2,3)) dg$VALUE <- yr_data[1:nrow(dg)] pr <- as.numeric(by(dg$VALUE,dg$MTH,FUN=sum)) rd <- as.numeric(by(dg$VALUE,dg$MTH,FUN=function(x) {length(which(x>=1))})) pr_jja <- sum(pr[6:8]) rd_jja <- sum(rd[6:8]) pr_ann <- sum(pr) rd_ann <- sum(rd) odat <- data.frame(YEAR=yr,MTH=c(1:12,"JJA","ANN"),PR=c(pr,pr_jja,pr_ann),RD=c(rd,rd_jja,rd_ann)) odat_all <- rbind(odat_all,odat) } return(odat_all) } #re construct a daily data.frame using a dummy one and the corrected data remake_daily <- function(his_list,bc_data,wleap,yi,yf) { cat("remaking daily data.frame\n") bc_data[,2:ncol(bc_data)] <- NA for (mth in 1:12) { #cat("calculating month",mth,"\n") #looping through years out_df <- data.frame() for (yr in yi:yf) { dg <- createDateGridCMIP5(yr,wleap) dg$MTH <- as.numeric(substr(dg$MTH.DAY,2,3)) jdi <- min(dg$JD[which(dg$MTH == mth)])+1 #+1 to account that 1st column is year jdf <- max(dg$JD[which(dg$MTH == mth)])+1 data_yr <- his_list[[paste("MTH.",mth,sep="")]] data_yr <- data_yr$VALUE_BC[which(data_yr$YEAR==yr)] bc_data[which(bc_data$YEAR==yr),jdi:jdf] <- data_yr } } return(bc_data) } #correct a given time series based on pre-fitted parameters loci_correct <- function(his_data,loci_mets) { cat("correcting the data\n") #now apply the correction to the time series for (mth in 1:12) { s <- loci_mets$S[which(loci_mets$MTH==mth)] wdt_obs <- loci_mets$WDT_OBS[which(loci_mets$MTH==mth)] wdt_mod <- loci_mets$WDT_MOD[which(loci_mets$MTH==mth)] nwd_obs <- loci_mets$NWD_OBS[which(loci_mets$MTH==mth)] his_data[[paste("MTH.",mth,sep="")]]$VALUE_BC <- sapply(his_data[[paste("MTH.",mth,sep="")]]$VALUE,FUN=function(x) {y<-max(c(0,s*(x-wdt_mod)+wdt_obs));if (nwd_obs == 0) {y<-0}; return(y)}) } return(his_data) } #calibrate loci for all momths loci_cal <- function(obs_list,his_list,wdt_obs=1,iter_step=0.0001) { cat("calculating loci metrics\n") out_mets <- data.frame() for (mth in 1:12) { ts_obs <- obs_list[[paste("MTH.",mth,sep="")]] ts_mod <- his_list[[paste("MTH.",mth,sep="")]] mth_mx <- loci_cal_mth(ts_obs,ts_mod,wdt_obs=wdt_obs,iter_step=iter_step) mth_mx <- cbind(MTH=mth,mth_mx) out_mets <- rbind(out_mets,mth_mx) } return(out_mets) } #calibrate loci for a month loci_cal_mth <- function(ts_obs,ts_mod,wdt_obs=1,iter_step=0.0001) { #calculate number of wet days and average rain in wet days wdays_obs <- which(ts_obs$VALUE>=wdt_obs) nwd_obs <- length(wdays_obs) if (nwd_obs==0) { wet_obs <- 0 } else { wet_obs <- mean(ts_obs$VALUE[wdays_obs],na.rm=T) } #find wet-day threshold for GCM wdt_mod <- find_wdt(ts_mod$VALUE,nwd_obs,iter_step=iter_step) wdays_mod <- which(ts_mod$VALUE>=wdt_mod) nwd_mod <- length(wdays_mod) if (nwd_mod==0) { wet_mod <- 0 } else { wet_mod <- mean(ts_mod$VALUE[wdays_mod],na.rm=T) } #calculate s correction factor s <- (wet_obs-wdt_obs)/(wet_mod-wdt_mod) #put everything into a matrix out_mx <- data.frame(WDT_OBS=wdt_obs,NWD_OBS=nwd_obs,WET_OBS=wet_obs, WDT_MOD=wdt_mod,NWD_MOD=nwd_mod,WET_MOD=wet_mod,S=s) return(out_mx) } #find the GCM wet-day threshold that matches the observed ones find_wdt <- function(values,nwd_obs,iter_step=1e-4) { nwd_mod <- length(values)+1 #initialise wdt_mod <- iter_step*-1 #initialise if (length(which(values>=0)) < nwd_obs) { wdt_mod <- 0 } else { nwitr <- 0 while (nwd_mod > nwd_obs) { wdt_mod <- wdt_mod+iter_step nwd_mod <- length(which(values>=wdt_mod)) nxt_nwd <- length(which(values>=(wdt_mod+iter_step))) #if the next value exceeds the value i'm looking for if (nxt_nwd < nwd_obs) { new_istep <- iter_step niter <- 0 #until a value of iter_step is found so that it does not exceed #the value i'm looking for while (nxt_nwd < nwd_obs) { new_istep <- new_istep*0.1 nxt_nwd <- length(which(values>=(wdt_mod+new_istep))) niter <- niter+1 #if (niter == 100) {nxt_nwd <- nwd_obs} } iter_step <- new_istep } nwitr <- nwitr+1 #truncation if (nwitr==100000) {nwd_mod <- nwd_obs} } } return(wdt_mod) } #### make a monthly list from the yearly matrices mk_mth_list <- function(all_data,dg_fun="createDateGrid",dg_args=NA,yi,yf) { cat("making monthly list\n") out_all <- list() for (mth in 1:12) { #cat("calculating month",mth,"\n") #looping through years out_df <- data.frame() for (yr in yi:yf) { if (!is.na(dg_args)) { dg <- do.call(dg_fun,list(yr,dg_args)) } else { dg <- do.call(dg_fun,list(yr)) } #get days of interest (julian days of month mth) dg$MTH <- as.numeric(substr(dg$MTH.DAY,2,3)) jdi <- min(dg$JD[which(dg$MTH == mth)])+1 #+1 to account that 1st column is year jdf <- max(dg$JD[which(dg$MTH == mth)])+1 #get the data from the matrix data_yr <- all_data[which(all_data$YEAR==yr),] data_yr <- as.numeric(data_yr[,jdi:jdf]) tmp_df <- data.frame(YEAR=yr,VALUE=data_yr) out_df <- rbind(out_df,tmp_df) } out_all[[paste("MTH.",mth,sep="")]] <- out_df } return(out_all) }
6d2a5deb4e11cad50cf670d0ba58a0623088554a
09b581d3c65d6c9687684aa5e538e3b650f130d2
/Cross-validation.R
77257f341da16f357b6ca3d518d576c2eaf55abf
[]
no_license
seth127/statToolkit
a9fe2886341eb609def4cf9497fdcb4413a9f3d0
e220cd3d760cadd6bce663e92eb72f5fa9a82625
refs/heads/master
2021-01-11T04:40:10.916944
2016-10-26T04:36:00
2016-10-26T04:36:00
71,141,777
0
0
null
null
null
null
UTF-8
R
false
false
8,273
r
Cross-validation.R
setwd("~/Documents/DSI/notes/2-STAT-6021/team assignments") train <- read.csv("teamassign05train.csv", header=T, stringsAsFactors = F) ## cross validate with the lm function cv.lm <- function(vars, train, k=5) { ## vars should be a character vector of variable names/combinations # the function to do the cross-validation theCV <- function(var, train, k, seed) { # create formula form = paste('y ~', var) #make column for preds train$preds <- numeric(nrow(train)) #randomize the indexes nums <- sample(row.names(train), nrow(train)) #split the indexes into k groups nv <- split(nums, cut(seq_along(nums), k, labels = FALSE)) #subset the training data into k folds trainlist <- list() for (i in 1:k) { trainlist[[i]] <- train[nv[[i]], ] } #trainlist #run on each fold for (i in 1:k) { ftrainlist <- trainlist[-i] ftrain <- ftrainlist[[1]] for (j in 2:length(ftrainlist)) { ftrain <- rbind(ftrain, ftrainlist[[j]]) } mod <- lm(as.formula(paste(form,' - preds')), data = ftrain) ### the model trainlist[[i]]$preds <- predict(mod, newdata = trainlist[[i]]) } #reassemble cvdata <- ftrainlist[[1]] for (j in 2:length(trainlist)) { cvdata <- rbind(cvdata, trainlist[[j]]) } # cross-validated test set MSE ###degfree <- nrow(cvdata) - ncol(subset(cvdata, select = -c(y, preds))) ##just use n? MSE <- sum((cvdata$y-cvdata$preds)^2) / nrow(cvdata) ##training set stats m <- lm(as.formula(paste(form,' - preds')), data = train) # adjusted R-squared aR2 <- summary(m)$adj.r.squared # p-value from F-stat lmp <- function (modelobject) { if (class(modelobject) != "lm") stop("Not an object of class 'lm' ") f <- summary(modelobject)$fstatistic p <- pf(f[1],f[2],f[3],lower.tail=F) attributes(p) <- NULL return(p) } p <- lmp(m) list(form, MSE, aR2, p) } # # now call that function on all the variable combinations dfM <- sapply(vars, theCV, train=train, k=k, simplify = 'array', USE.NAMES = F) df <- data.frame(formula = unlist(dfM[1,]), MSE = unlist(dfM[2,]), adj.R2 = unlist(dfM[3,]), p.value = unlist(dfM[4,]), stringsAsFactors = F) df } cv.lm('x7', train) plus <- cv.lm(c('x7', 'x5', 'x3+x5'), train) ### FORWARD SUBSET SELECTION FSS <- function(train, k) { #### the y variable MUST be called "y" # master vector of variables varsMaster <- names(train)[!grepl("y", names(train))] # cross validation on single variables df <- cv.lm(varsMaster, train, k) # create a master df to store all levels dfMaster <- df # pick the best one winner <- df[df$MSE==min(df$MSE), 1] varsWinner <- gsub(" ", "", gsub("y ~ ", "", winner)) # subset out remaining vars varsRemain <- varsMaster[!(varsMaster %in% unlist(strsplit(varsWinner, "+", fixed = T)))] # paste remaining vars onto winners to create new combinations newVars <- paste(varsWinner, varsRemain, sep="+") # # loop over all combinations, picking the best one each level while(length(varsRemain) > 0) { # run cross-validation with new variable combinations df <- cv.lm(newVars, train, k) # store new level stats in master df dfMaster <- rbind(dfMaster, df) # pick best one from new level winner <- df[df$MSE==min(df$MSE), 1] varsWinner <- gsub(" ", "", gsub("y ~ ", "", winner)) print(paste("varsWinner", varsWinner, df[df$MSE==min(df$MSE), 2])) ##### # subset out remaining vars varsRemain <- varsMaster[!(varsMaster %in% unlist(strsplit(varsWinner, "+", fixed = T)))] #print(paste("varsRemain", paste(varsRemain, collapse = ", "))) ### # paste remaining vars onto winners to create new combinations newVars <- paste(varsWinner, varsRemain, sep="+") } # output print(paste("optimal model:", dfMaster[dfMaster$MSE == min(dfMaster$MSE), 1])) list(dfMaster[dfMaster$MSE == min(dfMaster$MSE), 1], ## the optimal formula dfMaster[dfMaster$MSE == min(dfMaster$MSE), ], ## the optimal formula plus stats for it dfMaster) ## stats for all of the options tested } w <- FSS(train, 5) w[[1]] w[[2]] # if you want to look choose by adj.R2 instead, just look at w[[3]] and pick the lowest adj.R2 ### BACKWARD SUBSET SELECTION BSS <- function(train, k) { #### the y variable MUST be called "y" # master vector of variables varsMaster <- names(train)[!grepl("y", names(train))] # cross validation on all variables together varsAll <- paste(varsMaster, collapse = "+") df <- cv.lm(varsAll, train, k) # create a master df to store all levels dfMaster <- df # pick the best one winner <- varsAll varsWinner <- gsub(" ", "", gsub("y ~ ", "", winner)) # subset out remaining vars varsRemain <- unlist(strsplit(varsWinner, "+", fixed = T)) # paste remaining vars onto winners to create new combinations newVars <- character() for (i in 1:length(varsRemain)) { newVars[i] <- paste(varsRemain[-i], collapse = "+") } # # loop over all combinations, picking the best one each level while(length(newVars) > 1) { # run cross-validation with new variable combinations df <- cv.lm(newVars, train, k) # store new level stats in master df dfMaster <- rbind(dfMaster, df) # pick best one from new level winner <- df[df$MSE==min(df$MSE), 1] varsWinner <- gsub(" ", "", gsub("y ~ ", "", winner)) print(paste("varsWinner", varsWinner, df[df$MSE==min(df$MSE), 2])) ### # make options for next level varsRemain <- unlist(strsplit(varsWinner, "+", fixed = T)) newVars <- character() for (i in 1:length(varsRemain)) { newVars[i] <- paste(varsRemain[-i], collapse = "+") } } # output print(paste("optimal model:", dfMaster[dfMaster$MSE == min(dfMaster$MSE), 1])) list(dfMaster[dfMaster$MSE == min(dfMaster$MSE), 1], ## the optimal formula dfMaster[dfMaster$MSE == min(dfMaster$MSE), ], ## the optimal formula plus stats for it dfMaster) ## stats for all of the options tested } bw <- BSS(train, 5) bw[[1]] bw[[2]] # if you want to look choose by adj.R2 instead, just look at bw[[3]] and pick the lowest adj.R2 ##### OTHER MODELS CROSS VALIDATION ## cross validated RANDOM FOREST cv.rf <- function(train, k=5, returnDF=F) { #make column for preds train$preds <- factor(x=rep(levels(train$y)[1], nrow(train)), levels = levels(train$y)) #randomize the indexes nums <- sample(row.names(train), nrow(train)) #split the indexes into k groups nv <- split(nums, cut(seq_along(nums), k, labels = FALSE)) #subset the training data into k folds trainlist <- list() for (i in 1:k) { trainlist[[i]] <- train[nv[[i]], ] } #trainlist #run on each fold for (i in 1:k) { ftrainlist <- trainlist[-i] ftrain <- ftrainlist[[1]] for (j in 2:length(ftrainlist)) { ftrain <- rbind(ftrain, ftrainlist[[j]]) } ############# THE MODEL ####################### #mod <- lm(as.formula(paste(form,' - preds')), data = ftrain) ### the model mod <- randomForest(y ~ .-preds, data=ftrain, importance=TRUE,proximity=FALSE) ### the model ############################################### trainlist[[i]]$preds <- predict(mod, newdata = trainlist[[i]]) print(paste("finished fold", i)) } #reassemble cvdata <- ftrainlist[[1]] for (j in 2:length(trainlist)) { cvdata <- rbind(cvdata, trainlist[[j]]) } # return stats ##raw accuracy ra <- nrow(cvdata[cvdata$y == cvdata$preds,]) / nrow(cvdata) print(paste("Raw Accuracy:", ra)) ##balanced error rate ###http://spokenlanguageprocessing.blogspot.com/2011/12/evaluating-multi-class-classification.html nk <- length(levels(train$y)) recall <- numeric(nk) for (i in 1:nk) { ck <- levels(train$y)[i] recall[i] <- nrow(cvdata[cvdata$y==ck & cvdata$preds==ck,]) / nrow(cvdata[cvdata$y==ck,]) } BER <- 1 - (sum(recall)/nk) print(paste("Balanced Error Rate:", BER)) # return actual predictions cvdata <- cvdata[order(as.numeric(row.names(cvdata))), ] if(returnDF == T) { return(cvdata[,c('y', 'preds')]) } else { return() } } predDF <- cv.rf(moddf, returnDF = T)
76353d72611753e502853ff241975c07be5c40ad
85df0b56b85eb23536cd7f95160b816884148238
/bnlearn.R
8731c0b2162e3edfe5ce0eba5f35b745b676ae7a
[]
no_license
dgod1028/Bayesian-Network
5167c7c48256446af39f3e86d15446c1820bddc7
46da7afa9175af0321a82f06dbe470b2b432a142
refs/heads/master
2021-01-10T11:58:38.012575
2016-04-08T05:52:37
2016-04-08T05:52:37
54,442,688
0
0
null
null
null
null
UTF-8
R
false
false
1,819
r
bnlearn.R
## install.packages("bnlearn") ## 関連文献 http://arxiv.org/pdf/0908.3817.pdf library(bnlearn) library(Ecdat) data(Fair) head(Fair) data <- Fair[,c(-2,-3,-9,-7)] data[] <- lapply(data,as.factor) colnames(data) <- c("性別","子供","宗教","教育","幸福") bn.gs <- gs(data) bn.gs bn.hc <- hc(data,score ="aic") bn.hc par(mfrow = c(1,2)) plot(bn.gs, main = "Constraint-based algorithms") plot(bn.hc, main = "Hill-Climbing",highlight = "幸福") score <- score(bn.hc,data,type="aic") score fitted <- bn.fit(bn.hc,data,method="bayes") ### method = bayes or mle (Coef <- coefficients(fitted)) Coef Coef$幸福 #### Black list banlist <- data.frame(from=c("性別","子供"),to=c("子供","性別")) banlist bn.hc2 <- hc(data,score="aic",blacklist = banlist) bn.hc2 score2 <- score(bn.hc2,data,type="aic") par(mfrow = c(1,1)) plot(bn.hc2, main = paste("Bayesian Network"," (Score: ",round(score2,digits=2),")",sep=""),,highlight = "幸福") fitted2 <- bn.fit(bn.hc2,data,method="bayes") ### method = bayes or mle (Coef2 <- coefficients(fitted2)) Coef2 Coef2$幸福 Coef2$教育 Coef2$宗教 Coef2$教育 ##### #### 作業中 #---絵に上書き XMax <- max(axTicks(1)) YMax <- max(axTicks(2)) par(mfrow = c(1,1)) plot(bn.hc, main = "Hill-Climbing",highlight = "幸福") #切片 text(XMax*0.05, YMax*0.7, round(Coef$性別, digits=2), adj=0) text(XMax*0.85, YMax*0.6, round(Coef$SBP, digits=2), adj=0) text(XMax*0.35, YMax*0.9, round(Coef$FBS, digits=2), adj=0) text(XMax*0.35, YMax*0.05, round(Coef$BMI[1], digits=2), adj=0) #回帰係数 text(XMax*0.3, YMax*0.3, round(Coef$BMI[2], digits=3), adj=0) text(XMax*0.65, YMax*0.3, round(Coef$BMI[3], digits=3), adj=0) text(XMax*0.45, YMax*0.5, round(Coef$BMI[4], digits=3), adj=0) ## [1] "性別" "子供" "宗教" "教育" "幸福"
0baf50d068a94b514b364113d45941efb6debeb9
bb789bd6b0649fae85c747710354122fd8ff7e25
/man/summary.pmlr.Rd
846a7cc219ab2298662057035554ca7df9777c4a
[]
no_license
jshinb/pmlr
8efb9cf4e213f117db51ee4152747d9503408403
d000cc72192113356a84dd0ff501dae5fa98320f
refs/heads/master
2016-08-10T14:19:18.869369
2016-02-20T00:12:23
2016-02-20T00:12:23
49,685,089
0
0
null
null
null
null
UTF-8
R
false
true
1,376
rd
summary.pmlr.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/summary.pmlr.R \name{summary.pmlr} \alias{summary.pmlr} \title{Summarizing Penalized Multinomial Logistic Model Fits} \usage{ \method{summary}{pmlr}(object, ...) } \arguments{ \item{object}{an object of class \code{"pmlr"}, a result of a call to \code{\link{pmlr}}.} \item{...}{further arguments passed to or from other methods} } \value{ \code{summary.pmlr} returns an object of class \code{"summary.pmlr"}, a list with components \item{call}{the matched call of the \code{object}} \item{method}{which method was used for hypothesis testing and computation of confidence intervals} \item{coef}{an array containing the coefficient estimates, standard errors, and test statistics and their p-values asssociated with the chosen method for the p parameters for the J categories} \item{joint.test}{an array contatining the test statistics and p-values from constrained hypothesis tests under all betas = 0, all betas are equal, and betas are proportional.} \item{test.all0.vs.constraint}{Returned only if joint hypothesis testing was done: An array containing likelihood ratio test statistics and p-values testing all \eqn{H_0}: betas=0 vs. other constraints (\eqn{H_C}), which can be 'all betas are equal' or 'betas are proportion'.} } \description{ This function is for class \code{pmlr} object. }
665e33bf4046de16fa0ff58b2c6f7ddc6002c1ab
fecb973f3ed39663ddeafeacac4b4e272c53f6fc
/R/mhealth.validate.R
53cce8389666033fbd64e3e84da8ec70fefe47f8
[ "MIT" ]
permissive
qutang/mHealthR
79c173db45ea34b67566fbdd38fddc133b2e8621
4b3fef1fa24249a1c3c09d9721cd1148ae5c98a4
refs/heads/master
2018-12-09T04:44:39.771468
2018-09-11T20:09:01
2018-09-11T20:09:01
70,870,269
2
0
null
null
null
null
UTF-8
R
false
false
7,621
r
mhealth.validate.R
#' @name mhealth.validate #' @title Validate filename or dataframe against mhealth specification #' @param group_cols numeric or character vector specify columns to be validated as group variable. Only feasible for dataframe validation. Default is NULL, meaning there is no group columns in the dataframe. #' @import stringr #' @export mhealth.validate = function(file_or_df, file_type, group_cols = NULL) { if (is.character(file_or_df) & length(file_or_df) == 1) { valid = .validate.filename(file_or_df, file_type) } else if (is.data.frame(file_or_df)) { # validate dataframe valid = .validate.dataframe(file_or_df, file_type, group_cols) } else{ valid = FALSE message( sprintf( fmt = "\n Input is not feasible for validation, input class is: %s, but should be filename string or dataframe", class(file_or_df) ) ) } return(valid) } .validate.filename = function(filename, filetype) { # validate number of sections tokens = stringr::str_split(filename, "\\.", simplify = TRUE) if (length(tokens) != 5 && length(tokens) != 6) { valid = FALSE message( sprintf( "\n The number of sections separated by '.' is not correct: %s There should be 'name', 'ID', 'timestamp', 'filetype', 'extension', 'opt-extension' sections.", filename ) ) return(valid) } # validate name section valid = stringr::str_detect(tokens[1], pattern = mhealth$pattern$filename$NAME) if (!valid) { message( sprintf( "\n Invalid name section: %s, name section should only contain alphabets, numbers and '-'", tokens[1] ) ) } # validate ID section v_id = stringr::str_detect(tokens[2], pattern = mhealth$pattern$filename$ID) valid = valid & v_id if (!v_id) { message( sprintf( "\n Invalid id section: %s, id section should only contain uppercase alphabets, numbers and '-'", tokens[2] ) ) } # validate timestamp ts = stringr::str_extract(filename, pattern = mhealth$pattern$filename$TIMESTAMP) valid = valid & .validate.timestamp(ts, format = mhealth$format$filename$TIMESTAMP) # validate timezone v_tz = stringr::str_detect(tokens[3], pattern = mhealth$pattern$filename$TIMEZONE) valid = valid & v_tz tz = stringr::str_extract(tokens[3], pattern = mhealth$pattern$filename$TIMEZONE) if (!v_tz) { message(sprintf( "\n Invalid time zone format: %s, time zone should be like: [M/P]HHmm", tz )) } # validate filetype v_filetype = tokens[4] == filetype valid = valid & v_filetype if (!v_filetype) { message( sprintf( "\n Invalid file type section: %s, file types should be %s", tokens[4], filetype ) ) } # validate extension v_ext = tokens[5] == mhealth$pattern$filename$EXTENSION valid = valid & v_ext if (!v_ext) { message( sprintf( "\n Invalid extension: %s, extension should be '%s'", tokens[5], mhealth$pattern$filename$EXTENSION ) ) } # validate optional extension if (length(tokens) == 6) { v_optext = tokens[6] == mhealth$pattern$filename$OPT_EXTENSION valid = valid & v_optext if (!v_optext) { message( sprintf( "\n Invalid optional extension: %s, optional extension can only be '%s'", tokens[6], mhealth$pattern$filename$OPT_EXTENSION ) ) } } # # validate overall pattern # Use this simple method to valid as a whole pattern, but this way we can't get the insightful information where the pattern breaks # valid = valid & stringr::str_detect(filename, mhealth$pattern$filename$FILENAME) # if (!valid) { # message( # sprintf( # "\n # File name does not match mhealth convention: %s, # As an example: %s", # filename, # mhealth$example$filename[filetype] # ) # ) # } return(valid) } .validate.dataframe = function(df, filetype, group_cols) { required_cols = c(1) cols = colnames(df) ncols = ncol(df) if(filetype == mhealth$filetype$annotation){ required_cols = 1:4 }else if(filetype == mhealth$filetype$feature){ required_cols = 1:3 } # validate number of columns if (filetype == mhealth$filetype$sensor || filetype == mhealth$filetype$event) { valid = ncols >= 2 if (!valid) { message( sprintf( "\n The dataframe should have at least two columns for %s, it only has: %d", filetype, ncols ) ) return(valid) } } if (filetype == mhealth$filetype$annotation || filetype == mhealth$filetype$feature) { valid = ncols >= 4 if (!valid) { message( sprintf( "\n The dataframe should have at least fhour columns for %s, it only has: %d", filetype, ncols ) ) return(valid) } } # validate column style for (i in 1:ncols) { valid = valid & .validate.columnstyle(cols, i) } # validate first column to be date valid = .validate.columndate(df, 1) # validate first column header valid = valid & .validate.columnheader(cols, 1, mhealth$column$TIMESTAMP, filetype) # validate start and stop time column header for annotation and feature files if (filetype == mhealth$filetype$feature || filetype == mhealth$filetype$annotation) { valid = valid & .validate.columnheader(cols, 2, mhealth$column$START_TIME, filetype) valid = valid & .validate.columnheader(cols, 3, mhealth$column$STOP_TIME, filetype) # validate second and third column to be date for annotation and feature file valid = valid & .validate.columndate(df, 2) valid = valid & .validate.columndate(df, 3) } # validate the annotation name for annotation file if(filetype == mhealth$filetype$annotation){ valid = valid & .validate.columnheader(cols, 4, mhealth$column$ANNOTATION_NAME, filetype) valid = valid & .validate.columntype(df, 4, "character") } # convert group cols to numeric vector if(is.character(group_cols)){ group_cols = sapply(group_cols, function(x){which(x == names(df))}, simplify = TRUE) }else if(is.numeric(group_cols)){ }else{ message(sprintf( "\n group columns are not valid vector: %s So it will be ignored", class(group_cols) )) group_cols = NULL } # validate group columns to be numeric or character if(!is.null(group_cols)){ group_cols = setdiff(group_cols, required_cols) result = sapply(group_cols, function(x){ if(x > ncol(df) || x < 1){ message(sprintf( "\n group column index %d does not exist", x )) return(FALSE) } if(!is.character(df[1,x]) && !is.numeric(df[1,x]) && !is.integer(df[1,x])){ message(sprintf( "\n group column %s is not in the correct format: %s", names(df)[x], class(df[1, x]) )) return(FALSE) } return(TRUE) }) valid = valid & all(result) } # validate numerical values for sensor type file if (filetype == mhealth$filetype$sensor) { validate_cols = 2:ncols if(!is.null(group_cols)){ validate_cols = setdiff(2:ncols, group_cols) } for (i in validate_cols) { valid = valid & .validate.columntype(df, i, "numeric") } } return(valid) }
af4a6ca8503482c042057826e8357c41876676a5
176deb3e42481c7db657cd945e2b53ad0dab66ca
/man/seg.Rd
ae4d2e4a51e74c2814c88ae688293f1c9a3336d7
[ "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
katakagi/rloadest_test
a23d4ba635eadf00cebf5f9934217b3c5e16e0fd
74694ab65c7b62929961c45fdfa7eabf790869ef
refs/heads/master
2023-07-28T20:15:56.696712
2021-10-09T01:46:54
2021-10-09T01:46:54
null
0
0
null
null
null
null
UTF-8
R
false
true
567
rd
seg.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/seg.R \name{seg} \alias{seg} \title{Load Model} \usage{ seg(x, N) } \arguments{ \item{x}{the data to segment. Missing values are permitted and result corresponing in missing values in output.} \item{N}{the number of breaks in the segmented model.} } \value{ The data in \code{x} with attributes to build the segmented model. } \description{ Support function for building a segmented rating curve load model. Required in the formula in \code{segLoadReg} to define the segmented model. }
3e9b9ba36a41b00a8da687c2364d59bb41652cf2
4ba00ffc6623cdfc2d61f7b5e13918a889ee2472
/R/rbindfill-spdf.R
6448ed906db6aa61d41ed4adda8a728ff2e42398
[]
no_license
fdetsch/StackExchange
acfe10041443c351a0336e38d62c72b0072ad90f
52dbd089da4fb9a59fcc3b40ebfcc2d129133b3e
refs/heads/main
2022-09-10T04:06:42.964264
2022-09-06T07:36:44
2022-09-06T07:36:44
99,312,967
0
0
null
null
null
null
UTF-8
R
false
false
1,092
r
rbindfill-spdf.R
### Answer to 'How to use rbind with SPDFs when the number of columns of arguments do not match?' ----- ### (available online: https://gis.stackexchange.com/questions/267284/how-to-use-rbind-with-spdfs-when-the-number-of-columns-of-arguments-do-not-match/267355#267355) library(raster) France_map <- getData(name = "GADM", country = "FRA", level = 0, path = "D:/Data/GADM") Germany_map <- getData(name = "GADM", country = "DEU", level = 1, path = "D:/Data/GADM") Belgium_map <- getData(name = "GADM", country = "BEL", level = 2, path = "D:/Data/GADM") ## two-step approach df = plyr::rbind.fill(France_map@data, Germany_map@data, Belgium_map@data) spdf = SpatialPolygonsDataFrame(bind(as(France_map, "SpatialPolygons") , as(Germany_map, "SpatialPolygons") , as(Belgium_map, "SpatialPolygons")) , data = df) ## all-in-one out1 = bind(France_map, Germany_map, Belgium_map) countries = list(France_map, Germany_map, Belgium_map) out2 = do.call(bind, countries) identical(out1, out2)
f0c57c6658d5effb36425ca452561d4c5bd8b404
d4edb03b1bf3b0a0fbc58208b6437fda4dbd3d6f
/inst/simulation_and_plotting_scripts/compare-methods_auRC-auPRC(discrete).R
749954556350da61ee528df407411960562edcb9
[ "MIT" ]
permissive
insilico/npdr
245df976150f06ed32203354819711dfe60f211b
1aa134b6e82b700460e4b6392ef60ae2f80dfcfc
refs/heads/master
2023-06-23T20:24:58.581892
2023-06-10T00:53:23
2023-06-10T00:53:23
163,314,265
10
5
NOASSERTION
2021-09-21T18:15:34
2018-12-27T16:16:52
R
UTF-8
R
false
false
14,556
r
compare-methods_auRC-auPRC(discrete).R
# compute auRC and auPRC for NPDR, Relief, and Random Forest from 30 replicated data sets # Discrete (SNP) Data library(npdr) library(CORElearn) library(randomForest) library(reshape2) library(ggplot2) library(PRROC) show.plots = T # probalby want F for num.iter > 1 iterations save.files = F # T for subsequent auPRC etc plots run.pairs = T # compute all pairwise interaction stats and graph, # probalby want F for num.iter > 1 iterations num.iter <- 1 # just run one simulation #num.iter <- 30 # 30 replicate simulations will take several minutes if (save.files){ cat("Results files for ",num.iter, " replicate simulation(s) will be saved in ", getwd(),".", sep="") } # sim.type (options) # # "mainEffect": simple main effects # "mainEffect_Erdos-Renyi": main effects with added correlation from Erdos-Renyi network # "mainEffect_Scalefree": main effects with added correlation from Scale-free network # "interactionErdos": interaction effects from Erdos-Renyi network # "interactionScalefree": interaction effects from Scale-free network # "mixed": main effects and interaction effects # mix.type (options) # # "main-interactionErdos": main effects and interaction effects from Erdos-Renyi network # "main-interactionScalefree": main effects and interaction effects from Scale-free network # data.type (options) # # "continuous": random normal data N(0,1) (e.g., gene expression data) # "discrete": random binomial data B(n=2,prob) (e.g., GWAS data) num.samples <- 100 num.variables <- 100 main.bias <- 0.5 pct.mixed <- .5 # percent of effects that are main effects, must also use sim.type = "mixed" pct.imbalance <- .5 # 0.25 => 75% case - 25% ctrl mix.type <- "main-interactionErdos" pct.signals <- 0.1 nbias <- round(pct.signals*num.variables) sim.type <- "interactionErdos" # "mixed" for mixed main and interactions data.type <- "discrete" # or "continuous" for standard normal data auRC.npdr.multisurf <- numeric() auRC.npdr.fixedk <- numeric() auRC.relief <- numeric() auRC.RF <- numeric() auPRC.vec.npdr.multisurf <- numeric() auPRC.vec.npdr.fixedk <- numeric() auPRC.vec.relief <- numeric() auPRC.vec.RF <- numeric() set.seed(1989) for(iter in 1:num.iter){ cat("Iteration: ",iter,"\n") dataset <- createSimulation2(num.samples=num.samples, num.variables=num.variables, pct.imbalance=pct.imbalance, pct.signals=pct.signals, main.bias=main.bias, interaction.bias=1, # 1/0 is max/min effect size hi.cor=0.8, lo.cor=0.1, mix.type=mix.type, label="class", sim.type=sim.type, pct.mixed=pct.mixed, pct.train=0.5, pct.holdout=0.5, pct.validation=0, plot.graph=FALSE, verbose=TRUE, use.Rcpp=FALSE, prob.connected=0.3, out.degree=(num.variables-2), data.type=data.type) dats <- rbind(dataset$train, dataset$holdout, dataset$validation) dats <- dats[order(dats[,ncol(dats)]),] if (run.pairs){ # only use this to explore one dataset # pairwise interaction p-values or beta's if you want from inbixGAIN.R output.type <- "Pvals" intPairs.mat <- getInteractionEffects("class", dats, regressionFamily = "binomial", numCovariates = 0, writeBetas = FALSE, excludeMainEffects = FALSE, interactOutput = output.type, # "Pvals", Betas", "stdBetas" transformMethod = "", numCores = 1, verbose = F) colnames(intPairs.mat) <- colnames(dats)[1:(ncol(dats)-1)] rownames(intPairs.mat) <- colnames(dats)[1:(ncol(dats)-1)] intPairs.Betas <- getInteractionEffects("class", dats, regressionFamily = "binomial", numCovariates = 0, writeBetas = FALSE, excludeMainEffects = FALSE, interactOutput = "Betas", # "Pvals", Betas", "stdBetas" transformMethod = "", numCores = 1, verbose = F) colnames(intPairs.stdBetas) <- colnames(dats)[1:(ncol(dats)-1)] rownames(intPairs.stdBetas) <- colnames(dats)[1:(ncol(dats)-1)] want.to.adjust.p <- TRUE if (output.type=="Pvals" & want.to.adjust.p){ # adjust p values p.raw <- intPairs.mat[lower.tri(intPairs.mat, diag=FALSE)] p.adj <- p.adjust(p.raw,method="fdr") intPairs.mat[lower.tri(intPairs.mat, diag=FALSE)] <- p.adj intPairs.mat <- intPairs.mat + t(intPairs.mat) } threshold <- .05 rm.nodes <- numeric() A <- intPairs.mat row <- 1 for (var in rownames(intPairs.mat)){ A[row,] <- 0 # make all A values 0 unless significant if (output.type=="Pvals"){ signif.pairs.idx <- which(intPairs.mat[row,]>0 & intPairs.mat[row,]<threshold) } else{ # matrix of betas signif.pairs.idx <- which(intPairs.mat[row,]>threshold) } if (any(signif.pairs.idx)){ cat(var,": ", colnames(intPairs.mat)[signif.pairs.idx],"\n") cat("pval.adj: ", intPairs.mat[row,signif.pairs.idx],"\n") cat("beta: ", intPairs.Betas[row,signif.pairs.idx],"\n") A[row,signif.pairs.idx] <- 1 } else{ # collect rows with no significant interactions for removal rm.nodes <- c(rm.nodes,row) } row <- row + 1 } A <- A[-rm.nodes,-rm.nodes] # remove nodes with no connections # plot graph g <- igraph::graph.adjacency(A) # shape V(g)$shape <- "circle" V(g)$shape[grep("intvar",names(V(g)))] <- "rectangle" # color V(g)$color <- "gray" V(g)$color[grep("intvar",names(V(g)))] <- "lightblue" #igraph::V(g)$size <- scaleAB(degrees, 10, 20) #png(paste(filePrefix, "_ba_network.png", sep = ""), width = 1024, height = 768) plot(g, layout = igraph::layout.fruchterman.reingold, edge.arrow.mode = 0) #vertex.size=(strwidth(V(g)$names) + strwidth("oo")) * 100, #vertex.size2=strheight("I") * 100) } # npdr - multisurf npdr.results1 <- npdr("class", dats, regression.type="binomial", attr.diff.type="allele-sharing", #nbd.method="relieff", nbd.method="multisurf", nbd.metric = "manhattan", msurf.sd.frac=.5, k=0, neighbor.sampling="none", separate.hitmiss.nbds=F, dopar.nn = T, dopar.reg=T, padj.method="bonferroni", verbose=T) df1 <- data.frame(att=npdr.results1$att, beta=npdr.results1$beta.Z.att, pval=npdr.results1$pval.adj) functional.vars <- dataset$signal.names npdr.positives1 <- npdr.results1 %>% filter(pval.adj<.05) %>% pull(att) npdr.positives1 npdr.results1[1:10,] df1 <- na.omit(df1) idx.func <- which(c(as.character(df1[,"att"]) %in% functional.vars)) func.betas1 <- df1[idx.func,"beta"] neg.betas1 <- df1[-idx.func,"beta"] pr.npdr1 <- PRROC::pr.curve(scores.class0 = func.betas1, scores.class1 = neg.betas1, curve = T) if (show.plots){plot(pr.npdr1)} npdr.detect.stats1 <- detectionStats(functional.vars, npdr.positives1) # npdr - fixed k npdr.results2 <- npdr("class", dats, regression.type="binomial", attr.diff.type="allele-sharing", nbd.method="relieff", #nbd.method="multisurf", nbd.metric = "manhattan", msurf.sd.frac=.5, k=0, neighbor.sampling="none", separate.hitmiss.nbds=T, dopar.nn = T, dopar.reg=T, padj.method="bonferroni", verbose=T) npdr.positives2 <- npdr.results2 %>% filter(pval.adj<.05) %>% pull(att) df2 <- data.frame(att=npdr.results2$att, beta=npdr.results2$beta.Z.att, pval=npdr.results2$pval.adj) df2 <- na.omit(df2) idx.func <- which(c(as.character(df2[,"att"]) %in% functional.vars)) func.betas2 <- df2[idx.func,"beta"] neg.betas2 <- df2[-idx.func,"beta"] pr.npdr2 <- PRROC::pr.curve(scores.class0 = func.betas2, scores.class1 = neg.betas2, curve = T) if (show.plots){plot(pr.npdr2)} npdr.detect.stats2 <- detectionStats(functional.vars, npdr.positives2) #### Random Forest ranfor.fit <- randomForest(as.factor(class) ~ ., data = dats) rf.importance <- importance(ranfor.fit) rf.sorted<-sort(rf.importance, decreasing=T, index.return=T) rf.df <-data.frame(att=rownames(rf.importance)[rf.sorted$ix],rf.scores=rf.sorted$x) rf.df[1:10,] idx.func <- which(c(as.character(rf.df$att) %in% functional.vars)) func.scores.rf <- rf.df[idx.func,"rf.scores"] neg.scores.rf <- rf.df[-idx.func,"rf.scores"] pr.rf <- PRROC::pr.curve(scores.class0 = func.scores.rf, scores.class1 = neg.scores.rf, curve = T) if (show.plots){plot(pr.rf)} ##### Regular Relief relief <- CORElearn::attrEval(as.factor(class) ~ ., data = dats, estimator = "ReliefFequalK", costMatrix = NULL, outputNumericSplits=FALSE, kNearestEqual = floor(knnSURF(nrow(dats),.5)/2)) # fn from npdr relief.order <- order(relief, decreasing = T) relief.df <- data.frame(att=names(relief)[relief.order], rrelief=relief[relief.order]) idx.func <- which(c(as.character(relief.df$att) %in% functional.vars)) func.scores.relief <- relief.df[idx.func,"rrelief"] neg.scores.relief <- relief.df[-idx.func,"rrelief"] pr.relief <- PRROC::pr.curve(scores.class0 = func.scores.relief, scores.class1 = neg.scores.relief, curve = T) if (show.plots){plot(pr.relief)} pcts <- seq(0,1,.05) rf.detected <- sapply(pcts,function(p){rfDetected(rf.df,functional.vars,p)}) relief.detected <- sapply(pcts,function(p){reliefDetected(relief.df,functional.vars,p)}) npdr.detected.multisurf <- sapply(pcts,function(p){npdrDetected(npdr.results1,functional.vars,p)}) npdr.detected.fixedk <- sapply(pcts,function(p){npdrDetected(npdr.results2,functional.vars,p)}) if (show.plots){ # plot recall curves (RC) for several methods df <- data.frame(pcts=pcts, NPDR.MultiSURF=npdr.detected.multisurf, NPDR.Fixed.k=npdr.detected.fixedk, Relief=relief.detected, RForest=rf.detected) melt.df <- melt(data = df, measure.vars = c("NPDR.MultiSURF", "NPDR.Fixed.k", "Relief","RForest")) gg <- ggplot(melt.df, aes(x=pcts, y=value, group=variable)) + geom_line(aes(linetype=variable)) + geom_point(aes(shape=variable, color=variable), size=2) + scale_color_manual(values = c("#FC4E07", "brown", "#E7B800", "#228B22")) + xlab("Percent Selected") + ylab("Percent Correct") + ggtitle("Power to Detect Functional Variables") + theme(plot.title = element_text(hjust = 0.5)) + theme_bw() print(gg) # plot precision-recall curves (PRC) for several methods method.vec <- c(rep('NPDR.MultiSURF',length=nrow(pr.npdr1$curve)), rep('NPDR.Fixed.k',length=nrow(pr.npdr2$curve)), rep('Relief',length=nrow(pr.relief$curve)), rep('RForest',length=nrow(pr.rf$curve))) df <- data.frame(recall=c(pr.npdr1$curve[,1],pr.npdr2$curve[,1],pr.relief$curve[,1],pr.rf$curve[,1]), precision=c(pr.npdr1$curve[,2],pr.npdr2$curve[,2],pr.relief$curve[,2],pr.rf$curve[,2]), method=method.vec) gg <- ggplot(df, aes(x=recall, y=precision, group=method)) + geom_line(aes(linetype=method)) + geom_point(aes(shape=method, color=method), size=2) + scale_color_manual(values= c("#FC4E07", "brown", "#E7B800", "#228B22")) + xlab("Recall") + ylab("Precision") + ggtitle("Precision-Recall Curves: Comparison of Methods") + theme(plot.title = element_text(hjust=0.5)) + theme_bw() print(gg) } # auRC: area under the recall curve for several methods auRC.RF[iter] <- sum(rf.detected)/length(rf.detected) auRC.npdr.multisurf[iter] <- sum(npdr.detected.multisurf)/length(npdr.detected.multisurf) auRC.npdr.fixedk[iter] <- sum(npdr.detected.fixedk)/length(npdr.detected.fixedk) auRC.relief[iter] <- sum(relief.detected)/length(relief.detected) # auPRC: area under the precision-recall curve for several methods auPRC.vec.npdr.multisurf[iter] <- pr.npdr1$auc.integral auPRC.vec.npdr.fixedk[iter] <- pr.npdr2$auc.integral auPRC.vec.relief[iter] <- pr.relief$auc.integral auPRC.vec.RF[iter] <- pr.rf$auc.integral } if (save.files){ # save results df.save <- data.frame(cbind(iter=seq(1,30,by=1), auRC.RForest=auRC.RF, auRC.NPDR.MultiSURF=auRC.npdr.multisurf, auRC.NPDR.Fixed.k=auRC.npdr.fixedk, auRC.Relief=auRC.relief, auPRC.RForest=auPRC.vec.RF, auPRC.NPDR.MultiSURF=auPRC.vec.npdr.multisurf, auPRC.NPDR.Fixed.k=auPRC.vec.npdr.fixedk, auPRC.Relief=auPRC.vec.relief)) df.save <- apply(df.save,2,as.numeric) #setwd("C:/Users/bdawk/Documents/KNN_project_output") will need to change to desired directory file <- paste("auRC-auPRC_iterates_methods-comparison_",data.type,"-",sim.type,".csv",sep="") write.csv(df.save,file,row.names=F) }
711d25eca26fc012f7ba6995d5ffb63627896e21
3758b9c36518ec91a374660bc94745a2a615f675
/cmd/testsite/golden/load/test-library-4.0/fansi/tests/unitizer/_pre/funs.R
cff2b418d0422cd12a78c60f08533a4777a52597
[]
no_license
metrumresearchgroup/pkgr
ac35bce7c4ae384daba0d6738fd52ef7b3ba16e8
27c581cb81b353769b88ea742e9649fbcc1b533d
refs/heads/develop
2023-06-08T20:07:04.191824
2023-06-06T14:00:06
2023-06-06T14:00:06
150,817,179
33
5
null
2023-08-30T14:06:50
2018-09-29T02:45:53
R
UTF-8
R
false
false
240
r
funs.R
## Helpers to extract the condition message only due to instability in ## C level error/warning in displaying the call or not tce <- function(x) tryCatch(x, error=conditionMessage) tcw <- function(x) tryCatch(x, warning=conditionMessage)
6f13a5979d7a7955926728bf01ebb12ff8f9e063
472eb2a35e6e58adddaf24dbd0b9aebf6aa61ad8
/02_nova_codificacao.R
02676227f26dad5ef6bf644f2ddb3cb50af46f48
[]
no_license
neylsoncrepalde/midia-e-esfera-publica
99c04ce9c2074aedd12a4a56408beb908ed7f9d7
d08072cd592415b5e4f5f02c0d3ffacf426da86d
refs/heads/master
2021-09-15T07:03:49.802502
2018-05-28T07:23:23
2018-05-28T07:23:23
103,695,628
0
0
null
null
null
null
UTF-8
R
false
false
4,350
r
02_nova_codificacao.R
############################## # Mídia e Esfera Pública # Rousiley, Gabriella Hauber # Script: Neylson Crepalde ############################## setwd('~/Documentos/Rousiley') list.files() library(xlsx) dados = read.xlsx("Nova_codificacao.xlsx",1) View(dados) nomes = names(dados) nomes nomes2 = gsub("X", "", nomes) nomes2 names(dados) = nomes2 ########################################### library(reshape2) library(dplyr) dados$ocasiao = ifelse(dados$PH == 1, "Public Hearing", "Meeting") names(dados) emocoes = dados %>% select(1:6) argumentos = dados %>% select(c(1, 14:37)) objetos = dados %>% select(c(1, 7:13)) names(argumentos) emocoes_molten = melt(emocoes, id=1) names(emocoes_molten)[2] = "emocao" emocoes_molten = emocoes_molten %>% filter(value==1) %>% select(-value) argumentos_molten = melt(argumentos, id=1) names(argumentos_molten)[2] = "argumento" argumentos_molten = argumentos_molten %>% filter(value==1) %>% select(-value) objetos_molten = melt(objetos, id=1) names(objetos_molten)[2] = "objeto" objetos_molten = objetos_molten %>% filter(value==1) %>% select(-value) molten = full_join(emocoes_molten, argumentos_molten, by='Argumentos') emo_obj = full_join(emocoes_molten, objetos_molten, by="Argumentos") obj_ocasiao = full_join(emo_obj, dados[c(1,40)], by="Argumentos") molten_ocasiao = full_join(molten, dados[c(1,40)], by="Argumentos") head(molten) head(emo_obj) head(molten_ocasiao) # CRUZA EMOÇÕES E ARGUMENTOS molten$argumento = factor(molten$argumento, levels = c('1C','2C','3C','4C','5C','6C', '7C','8C','9C','10C','11C','12C', '1F','2F','3F','4F','5F','6F', '7F','8F','9F','10F','11F','12F')) table(molten$emocao, molten$argumento) xtable::xtable(table(molten$emocao, molten$argumento)) # testa fisher.test(table(molten$emocao, molten$argumento), simulate.p.value = T, B=5000) chisq.test(table(molten$emocao, molten$argumento)) # PREPARANDO indexc = grep("C", molten$argumento) indexf = grep("F", molten$argumento) molten$argumento = as.character(molten$argumento) molten$posicionamento[indexc] = "Contra" molten$posicionamento[indexf] = "A Favor" contra = molten[indexc,] afavor = molten[indexf,] head(contra) head(afavor) # CRUZA EMOÇÕES E TIPO DE ARGUMENTO table(molten$posicionamento, molten$emocao) xtable::xtable(table(molten$posicionamento, molten$emocao)) chisq.test(table(molten$posicionamento, molten$emocao)) fisher.test(table(molten$posicionamento, molten$emocao)) # CRUZA EMOÇÕES E ARGUMENTOS contra$argumento = factor(contra$argumento, levels = c('1C','2C','3C','4C','5C','6C', '7C','8C','9C','10C','11C','12C')) #levels(contra$argumento) = c('1C','2C','3C','4C','5C','6C', # '7C','8C','9C','10C','11C','12C') table(contra$emocao, contra$argumento) xtable::xtable(table(contra$emocao, contra$argumento)) chisq.test(table(contra$emocao, contra$argumento)) fisher.test(table(contra$emocao, contra$argumento), simulate.p.value = T, B=5000) afavor$argumento = factor(afavor$argumento, levels = c('1F','2F','3F','4F','5F','6F', '7F','8F','9F','10F','11F','12F')) xtable::xtable(table(afavor$emocao, afavor$argumento)) table(afavor$emocao, afavor$argumento) fisher.test(table(afavor$emocao, afavor$argumento), simulate.p.value = T, B=5000) # CRUZA EMOÇÕES E OBJETOS table(emo_obj$emocao, emo_obj$objeto) xtable::xtable(table(emo_obj$emocao, emo_obj$objeto)) fisher.test(table(emo_obj$emocao, emo_obj$objeto), simulate.p.value = T, B=5000) # CRUZA EMOÇÕES E OCASIAO table(molten_ocasiao$ocasiao, molten_ocasiao$emocao) chisq.test(table(molten_ocasiao$ocasiao, molten_ocasiao$emocao)) # CRUZA POSICIONAMENTO E OCASIAO table(molten_ocasiao$posicionamento, molten_ocasiao$ocasiao) chisq.test(table(molten_ocasiao$posicionamento, molten_ocasiao$ocasiao)) # CRUZA OBJETOS E OCASIÃO table(obj_ocasiao$ocasiao, obj_ocasiao$objeto) xtable::xtable(table(obj_ocasiao$objeto, obj_ocasiao$ocasiao)) chisq.test(table(obj_ocasiao$ocasiao, obj_ocasiao$objeto)) fisher.test(table(obj_ocasiao$ocasiao, obj_ocasiao$objeto), simulate.p.value = T, B=5000) ######################################
60fa77a12c131eab107a8be989aab79fefefafd5
31698075d1580c6dc455adde3b30b636f0c87e70
/man/get_pdp_predictions.Rd
5c97d7bdfedc404424db58ff7d2d9c629bf75e4c
[]
no_license
erblast/easyalluvial
11d10267e31ed44400f99c2e8d5df982ec90f468
df22644596db1eaa8e66f05e66b343de338d0d1f
refs/heads/master
2022-07-29T20:10:19.912023
2022-07-09T07:06:21
2022-07-09T07:06:21
149,339,634
101
10
null
2022-07-09T07:06:22
2018-09-18T19:13:25
R
UTF-8
R
false
true
3,757
rd
get_pdp_predictions.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/alluvial_model_response.R \name{get_pdp_predictions} \alias{get_pdp_predictions} \title{get predictions compatible with the partial dependence plotting method} \usage{ get_pdp_predictions( df, imp, m, degree = 4, bins = 5, .f_predict = predict, parallel = FALSE ) } \arguments{ \item{df}{dataframe, training data} \item{imp}{dataframe, with not more then two columns one of them numeric containing importance measures and one character or factor column containing corresponding variable names as found in training data.} \item{m}{model object} \item{degree}{integer, number of top important variables to select. For plotting more than 4 will result in two many flows and the alluvial plot will not be very readable, Default: 4} \item{bins}{integer, number of bins for numeric variables, increasing this number might result in too many flows, Default: 5} \item{.f_predict}{corresponding model predict() function. Needs to accept `m` as the first parameter and use the `newdata` parameter. Supply a wrapper for predict functions with x-y syntax. For parallel processing the predict method of object classes will not always get imported correctly to the worker environment. We can pass the correct predict method via this parameter for example randomForest:::predict.randomForest. Note that a lot of modeling packages do not export the predict method explicitly and it can only be found using :::.} \item{parallel}{logical, turn on parallel processing. Default: FALSE} } \value{ vector, predictions } \description{ Alluvial plots are capable of displaying higher dimensional data on a plane, thus lend themselves to plot the response of a statistical model to changes in the input data across multiple dimensions. The practical limit here is 4 dimensions while conventional partial dependence plots are limited to 2 dimensions. Briefly the 4 variables with the highest feature importance for a given model are selected and 5 values spread over the variable range are selected for each. Then a grid of all possible combinations is created. All none-plotted variables are set to the values found in the first row of the training data set. Using this artificial data space model predictions are being generated. This process is then repeated for each row in the training data set and the overall model response is averaged in the end. Each of the possible combinations is plotted as a flow which is coloured by the bin corresponding to the average model response generated by that particular combination. } \details{ For more on partial dependency plots see [https://christophm.github.io/interpretable-ml-book/pdp.html]. } \section{Parallel Processing}{ We are using `furrr` and the `future` package to paralelize some of the computational steps for calculating the predictions. It is up to the user to register a compatible backend (see \link[future]{plan}). } \examples{ df = mtcars2[, ! names(mtcars2) \%in\% 'ids' ] m = randomForest::randomForest( disp ~ ., df) imp = m$importance pred = get_pdp_predictions(df, imp , m , degree = 3 , bins = 5) # parallel processing -------------------------- \dontrun{ future::plan("multisession") # note that we have to pass the predict method via .f_predict otherwise # it will not be available in the worker's environment. pred = get_pdp_predictions(df, imp , m , degree = 3 , bins = 5, , parallel = TRUE , .f_predict = randomForest:::predict.randomForest) } }
4ba924dd9ed1e2bcd7e365f02cc8153f51670cf7
2f7eb4978331ab3585a57347f19a6a4323460191
/R/get_icc.R
962110b9cb99abc1f46465c797dd8e83c90308a0
[ "MIT" ]
permissive
ernestguevarra/sampsizer
09ee112e7f9dc84cabab619167ceda4df0761a3e
801108c9c131b895465f3f328f04f642721953bd
refs/heads/master
2020-03-27T06:14:05.216847
2019-09-07T05:08:50
2019-09-07T05:08:50
146,090,847
0
0
null
null
null
null
UTF-8
R
false
false
1,039
r
get_icc.R
################################################################################ # #' #' Function to calculate the intracluster correlation coefficient of an #' indicator collected from random cluster survey (RCS). This is a wrapper of #' the \code{deff()} function in the \code{Hmisc} package. #' #' @param x variable to calculate ICC from #' @param cluster variable identifying the clusters or groupings of the variable #' #' @return A vector with named elements n (total number of non-missing observations), #' \code{clusters} (number of clusters after deleting missing data), #' \code{rho} (intra-cluster correlation), and \code{deff} (design effect). #' #' @examples #' x <- sample(1:2, size = 25, replace = TRUE) #' cluster <- c(rep(1, 5), rep(2, 5), rep(3, 5), rep(4, 5), rep(5, 5)) #' get_icc(x = x, cluster = cluster) #' #' @export #' # ################################################################################ get_icc <- function(x, cluster) { icc <- Hmisc::deff(y = x, cluster = cluster) return(icc) }
5d12096453c1c4d5ab8e2d156204435b6ba68949
5397b2f52030662f0e55f23f82e45faa165b8346
/R/j_get_meta.R
46c4c6392256e31d80e03c8d8bee3fd907a42d22
[ "MIT" ]
permissive
data-science-made-easy/james-old
8569dcc8ce74c68bcbb81106127da4b903103fcd
201cc8e527123a62a00d27cd45d365c463fc1411
refs/heads/master
2023-01-12T21:16:23.231628
2020-11-19T13:46:17
2020-11-19T13:46:17
null
0
0
null
null
null
null
UTF-8
R
false
false
86
r
j_get_meta.R
#' @export j_get_meta j_get_meta <- function(index) { j_get(index, what = "meta") }
342508343a5374389c1d68fa1d7e81b659cf13f1
4ff46765a3b93d40632c9c94d154b8b23e638fdd
/cba/machine-learning/codes/batch.R
37e7016c0f1aed3c613eae8a4f274ad976cb6556
[]
no_license
harakonan/research-public
e5bedaa225aba44d1da624e9816434abe05529ac
5ea6a58e8603a08130095ad028c92ca791cbed3f
refs/heads/master
2023-06-28T04:27:35.057728
2023-06-08T11:47:55
2023-06-08T11:47:55
129,033,826
1
1
null
null
null
null
UTF-8
R
false
false
5,323
r
batch.R
# Batch file for data cleaning and analysis # Do not forget to change set_env depending on the environment # set_env <- "test" set_env <- "main" # Path to working directories if (set_env == "test"){ source("~/Workspace/research-private/cba/machine-learning/codes/pathtowd/pathtowd_test.R") } else if (set_env == "main"){ source("/mnt/d/userdata/k.hara/codes/pathtowd/pathtowd_main.R") } # track_r: Function that execute and track R script source(paste0(pathtotools, "track_r.R")) # Package loading library(data.table) library(zoo) library(dplyr) library(Hmisc) library(ggplot2) library(epiR) library(pROC) library(mnlogit) library(splitstackshape) library(doParallel) library(mltools) library(glmnet) library(gam) library(ranger) library(xgboost) library(nnet) library(mda) library(fastknn) library(LiblineaR) library(gridExtra) # cba_data_cleaning.R if (set_env == "test"){ claim_startmon <- 201404 claim_endmon <- 201603 hs_startday <- 20140401 hs_endday <- 20160331 agepoint <- 201603 track_r(pathtomain, "cba_data_cleaning_test.R", pathtolog, "cba_data_cleaning.log") } else if (set_env == "main"){ claim_startmon <- 201604 claim_endmon <- 201803 hs_startday <- 20160401 hs_endday <- 20180331 agepoint <- 201803 track_r(pathtomain, "cba_data_cleaning.R", pathtolog, "cba_data_cleaning.log") } # cba_data_man_stat.R if (set_env == "test"){ fyclaim <- 2015 } else if (set_env == "main"){ fyclaim <- 2017 } track_r(pathtomain, "cba_data_man_stat.R", pathtolog, "cba_data_man_stat.log") # cba_data_man_conv.R if (set_env == "test"){ fyclaim <- 2015 } else if (set_env == "main"){ fyclaim <- 2017 } track_r(pathtomain, "cba_data_man_conv.R", pathtolog, "cba_data_man_conv.log") # Caution!: samples and labels will be refreshed if executed # cba_sampling_refresh.R sample_ratio <- NULL target_disease <- "ht" track_r(pathtomain, "cba_sampling_refresh.R", pathtolog, paste0("cba_sampling_refresh_", target_disease, ".log")) sample_ratio <- NULL target_disease <- "dm" track_r(pathtomain, "cba_sampling_refresh.R", pathtolog, paste0("cba_sampling_refresh_", target_disease, ".log")) sample_ratio <- NULL target_disease <- "dl" track_r(pathtomain, "cba_sampling_refresh.R", pathtolog, paste0("cba_sampling_refresh_", target_disease, ".log")) # samples for testing cba_statlearn_analysis.R sample_ratio <- 0.05 target_disease <- "ht" track_r(pathtomain, "cba_sampling_refresh.R", pathtolog, paste0("cba_sampling_refresh_", target_disease, "_sample.log")) sample_ratio <- 0.15 target_disease <- "dm" track_r(pathtomain, "cba_sampling_refresh.R", pathtolog, paste0("cba_sampling_refresh_", target_disease, "_sample.log")) sample_ratio <- 0.05 target_disease <- "dl" track_r(pathtomain, "cba_sampling_refresh.R", pathtolog, paste0("cba_sampling_refresh_", target_disease, "_sample.log")) # # cba_sampling_preserve.R # sample_ratio <- NULL # target_disease <- "ht" # track_r(pathtomain, "cba_sampling_preserve.R", pathtolog, paste0("cba_sampling_preserve_", target_disease, ".log")) # sample_ratio <- NULL # target_disease <- "dm" # track_r(pathtomain, "cba_sampling_preserve.R", pathtolog, paste0("cba_sampling_preserve_", target_disease, ".log")) # sample_ratio <- NULL # target_disease <- "dl" # track_r(pathtomain, "cba_sampling_preserve.R", pathtolog, paste0("cba_sampling_preserve_", target_disease, ".log")) # samples for testing cba_statlearn_analysis.R # sample_ratio <- 0.05 # target_disease <- "ht" # track_r(pathtomain, "cba_sampling_preserve.R", pathtolog, paste0("cba_sampling_preserve_", target_disease, "_sample.log")) # sample_ratio <- 0.15 # target_disease <- "ht" # track_r(pathtomain, "cba_sampling_preserve.R", pathtolog, paste0("cba_sampling_preserve_", target_disease, "_sample.log")) # sample_ratio <- 0.05 # target_disease <- "dl" # track_r(pathtomain, "cba_sampling_preserve.R", pathtolog, paste0("cba_sampling_preserve_", target_disease, "_sample.log")) # cba_summary.R if (set_env == "test"){ fyclaim <- 2015 } else if (set_env == "main"){ fyclaim <- 2017 } track_r(pathtomain, "cba_summary.R", pathtolog, paste0("cba_summary", ".log")) # cba_conventional_analysis.R target_disease <- "ht" track_r(pathtomain, "cba_conventional_analysis.R", pathtolog, paste0("cba_conventional_analysis_", target_disease, ".log")) target_disease <- "dm" track_r(pathtomain, "cba_conventional_analysis.R", pathtolog, paste0("cba_conventional_analysis_", target_disease, ".log")) target_disease <- "dl" track_r(pathtomain, "cba_conventional_analysis.R", pathtolog, paste0("cba_conventional_analysis_", target_disease, ".log")) # cba_statlearn_analysis.R # change full_data after test target_disease <- "ht" # full_data <- TRUE full_data <- FALSE track_r(pathtomain, "cba_statlearn_analysis.R", pathtolog, paste0("cba_statlearn_analysis_", target_disease, ".log")) target_disease <- "dm" # full_data <- TRUE full_data <- FALSE track_r(pathtomain, "cba_statlearn_analysis.R", pathtolog, paste0("cba_statlearn_analysis_", target_disease, ".log")) target_disease <- "dl" # full_data <- TRUE full_data <- FALSE track_r(pathtomain, "cba_statlearn_analysis.R", pathtolog, paste0("cba_statlearn_analysis_", target_disease, ".log"))
9fcc4793e8a7fdb8e83911aaf5c655161344402a
ac0a2b0c0dcbe8ea08d0baa42b66a38b2ffe6e37
/mean_substitution_rate_by_pango.R
8f2e6a84b30345c6d9836b849e4659e460632f4f
[ "CC0-1.0" ]
permissive
cednotsed/ditto
3957e0fcb11ec505570bf7c6862a99c1916bb507
8a27ec1a06c2363ae36a6674457f3e7e2e1b9c9a
refs/heads/main
2023-04-17T18:43:09.591358
2022-05-08T03:50:28
2022-05-08T03:50:28
430,035,274
1
0
CC0-1.0
2022-05-08T03:50:30
2021-11-20T07:13:17
R
UTF-8
R
false
false
12,373
r
mean_substitution_rate_by_pango.R
rm(list = ls()) setwd("../Desktop/git_repos/ditto/") require(tidyverse) require(data.table) require(ape) require(ggplot2) require(see) require(foreach) prefixes <- list.files("results/human_animal_subsets/V5/dating_out/") ant_df <- read.csv("data/metadata/netherlands_humans_anthroponoses.txt", header = F) prefixes <- prefixes[!grepl("deer|all_|USA|.png", prefixes)] human_background <- "V5" cluster_meta <- fread("results/cluster_annotation/deer_mink_parsed_clusters.csv") %>% select(accession_id, cluster) morsels <- foreach (prefix = prefixes) %do% { country_name <- str_split(prefix, "\\.")[[1]][2] time_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/timetree.nexus")) div_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/divergence_tree.nexus")) meta <- fread(str_glue("data/metadata/human_animal_subsets/{human_background}/{prefix}.csv")) %>% select(-cluster) %>% filter(accession_id %in% time_tree$tip.label) %>% left_join(cluster_meta) # Divide time tree by divergence tree rate_tree <- div_tree rate_tree$edge.length <- rate_tree$edge.length / time_tree$edge.length # Drop anthroponotic tips rate_tree <- drop.tip(rate_tree, ant_df$V1) n <- length(rate_tree$tip.label) rate_df <- tibble(accession_id = rate_tree$tip.label, terminal_rate = rate_tree$edge.length[sapply(1:n, function(x,y) which(y == x), y = rate_tree$edge[,2])]) rate_df %>% left_join(meta) %>% add_column(country = country_name) %>% select(host, terminal_rate, cluster, country, pango_lineage) } plot_df <- bind_rows(morsels) plot_df %>% group_by(host, pango_lineage) %>% summarise(n = n()) %>% right_join(plot_df, by = c("host", "pango_lineage")) %>% ggplot(aes(x = host, y = log(terminal_rate, base = 10), fill = host)) + facet_grid(rows = vars(pango_lineage), scales = "free", space = "free") + theme_bw() + geom_point(color = "darkgrey", position = position_jitter(width = 0.08), size = 0.5, alpha = 0.8) + geom_boxplot(position = position_nudge(x = -0.2, y = 0), width = 0.2, outlier.shape = NA, alpha = 0.3) + geom_violinhalf(position = position_nudge(x = 0.2, y = 0), alpha = 1) + geom_text(aes(x = host, y = -1.5, label = paste0("n = ", n))) + coord_flip() + labs(y = "lg(subst. rate)", x = "Host") + theme(legend.position = "none") # ggsave(str_glue("results/human_animal_subsets/{human_background}/dating_out/mutations_rates_terminal.png"), # width = 7, # height = 5) # Plot by cluster plot_df %>% group_by(cluster) %>% summarise(n = n()) %>% right_join(plot_df, by = c("cluster")) %>% filter(host == "Neovison vison") %>% ggplot(aes(x = cluster, y = log(terminal_rate, base = 10), fill = cluster)) + facet_grid(rows = vars(country), scales = "free", space = "free") + theme_bw() + geom_point(color = "darkgrey", position = position_jitter(width = 0.08), size = 0.5, alpha = 0.8) + geom_boxplot(position = position_nudge(x = -0.2, y = 0), width = 0.2, outlier.shape = NA, alpha = 0.3) + geom_violinhalf(position = position_nudge(x = 0.2, y = 0), alpha = 1) + geom_text(aes(x = cluster, y = -1.5, label = paste0("n = ", n))) + coord_flip() + labs(y = "lg(subst. rate)", x = "Host") + theme(legend.position = "none") ggsave(str_glue("results/human_animal_subsets/{human_background}/dating_out/mutations_rates_terminal_by_cluster.png"), width = 7, height = 5) #### ALL branches ################### morsels2 <- foreach (prefix = prefixes) %do% { country_name <- str_split(prefix, "\\.")[[1]][2] time_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/timetree.nexus")) div_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/divergence_tree.nexus")) cluster_meta <- fread("results/cluster_annotation/deer_mink_parsed_clusters.csv") %>% select(accession_id, cluster) meta <- fread(str_glue("data/metadata/human_animal_subsets/{human_background}/{prefix}.csv")) %>% filter(accession_id %in% time_tree$tip.label) %>% left_join(cluster_meta) human <- meta %>% filter(host == "Human") animal <- meta %>% filter(host == "Neovison vison") # Divide time tree by divergence tree rate_tree <- div_tree rate_tree$edge.length <- rate_tree$edge.length / time_tree$edge.length # Drop anthroponotic tips rate_tree <- drop.tip(rate_tree, ant_df$V1) # Drop host tips animal_tree <- drop.tip(rate_tree, human$accession_id) human_tree <- drop.tip(rate_tree, animal$accession_id) tibble(rate = animal_tree$edge.length, host = "Neovison vison") %>% bind_rows(tibble(rate = human_tree$edge.length, host = "Human")) %>% add_column(country = country_name) %>% select(host, country, rate) } plot_df2 <- bind_rows(morsels2) plot_df2 %>% group_by(host, country) %>% summarise(n = n()) %>% right_join(plot_df2, by = c("host", "country")) %>% ggplot(aes(x = host, y = log(rate, base = 10), fill = host)) + facet_grid(rows = vars(country), scales = "free", space = "free") + theme_bw() + geom_point(color = "darkgrey", position = position_jitter(width = 0.08), size = 0.5, alpha = 0.8) + geom_boxplot(position = position_nudge(x = -0.2, y = 0), width = 0.2, outlier.shape = NA, alpha = 0.3) + geom_violinhalf(position = position_nudge(x = 0.2, y = 0), alpha = 1) + geom_text(aes(x = host, y = -1.5, label = paste0("n = ", n))) + coord_flip() + labs(y = "lg(subst. rate)", x = "Host") + theme(legend.position = "none") ggsave(str_glue("results/human_animal_subsets/{human_background}/dating_out/mutations_rates_internal.png"), width = 7, height = 5) #### Specific mutations ##### morsels3 <- foreach (prefix = prefixes) %do% { country_name <- str_split(prefix, "\\.")[[1]][2] time_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/timetree.nexus")) div_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/divergence_tree.nexus")) cluster_meta <- fread("results/cluster_annotation/deer_mink_parsed_clusters.csv") %>% select(accession_id, cluster) meta <- fread(str_glue("data/metadata/human_animal_subsets/{human_background}/{prefix}.csv")) %>% filter(accession_id %in% time_tree$tip.label) %>% select(-cluster) %>% left_join(cluster_meta) # Divide time tree by divergence tree rate_tree <- div_tree rate_tree$edge.length <- rate_tree$edge.length / time_tree$edge.length # Drop anthroponotic tips rate_tree <- drop.tip(rate_tree, ant_df$V1) n <- length(rate_tree$tip.label) rate_df <- tibble(accession_id = rate_tree$tip.label, terminal_rate = rate_tree$edge.length[sapply(1:n, function(x,y) which(y == x), y = rate_tree$edge[,2])]) rate_df %>% left_join(meta) %>% add_column(country = country_name) %>% select(host, terminal_rate, cluster, country) } plot_df3 <- bind_rows(morsels3) %>% filter(host == "Neovison vison") plot_df3 %>% group_by(cluster) %>% summarise(n = n()) %>% right_join(plot_df3, by = "cluster") %>% ggplot(aes(x = cluster, y = log(terminal_rate, base = 10), fill = cluster)) + theme_bw() + geom_point(color = "darkgrey", position = position_jitter(width = 0.08), size = 0.5, alpha = 0.8) + geom_boxplot(position = position_nudge(x = -0.2, y = 0), width = 0.2, outlier.shape = NA, alpha = 0.3) + geom_violinhalf(position = position_nudge(x = 0.2, y = 0), alpha = 1) + geom_text(aes(x = cluster, y = -1.5, label = paste0("n = ", n))) + coord_flip() + labs(y = "lg(subst. rate)", x = "Cluster") + theme(legend.position = "none") ggsave(str_glue("results/human_animal_subsets/{human_background}/dating_out/mutations_rates_terminal.png"), width = 7, height = 5) ##### Compute by mutation ##### mut_df <- fread("results/mink_homoplasy_alele_frequency_V5.csv") %>% filter(mutation_annot %in% c("G37E", "Y486L", "N501T", "T229I", "L219V", "Y453F")) # Load trees prefix <- "all_mink.n1487.unambiguous.dedup" time_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/timetree.nexus")) div_tree <- read.nexus(str_glue("results/human_animal_subsets/{human_background}/dating_out/{prefix}/divergence_tree.nexus")) meta <- fread(str_glue("data/metadata/human_animal_subsets/{human_background}/{prefix}.csv")) %>% filter(accession_id %in% time_tree$tip.label) aln_prefix <- gsub(".unambiguous", ".audacity_only.v8_masked.unambiguous", prefix) aln <- read.dna(str_glue("data/alignments/human_animal_subsets/{human_background}/{aln_prefix}.fasta"), format = "fasta", as.matrix = T) morsels <- foreach (i = seq(nrow(mut_df))) %do% { row <- mut_df[i, ] # Get allele by position aln_df <- tibble(accession_id = rownames(aln), allele = toupper(as.vector(as.character(aln[, row$nucleotide_pos])))) # Divide time tree by divergence tree rate_tree <- div_tree rate_tree$edge.length <- rate_tree$edge.length / time_tree$edge.length # Drop anthroponotic tips rate_tree <- drop.tip(rate_tree, ant_df$V1) n <- length(rate_tree$tip.label) with_df <- tibble(accession_id = rate_tree$tip.label, terminal_rate = rate_tree$edge.length[sapply(1:n, function(x,y) which(y == x), y = rate_tree$edge[,2])]) %>% left_join(aln_df) %>% filter(allele == row$var_nuc) %>% add_column(mutation = row$mutation_annot, mutation_present = "Present") without_df <- tibble(accession_id = rate_tree$tip.label, terminal_rate = rate_tree$edge.length[sapply(1:n, function(x,y) which(y == x), y = rate_tree$edge[,2])]) %>% left_join(aln_df) %>% filter(allele != row$var_nuc) %>% add_column(mutation = row$mutation_annot, mutation_present = "Absent") with_df %>% bind_rows(without_df) } bind_rows(morsels) %>% mutate(log_rate = log(terminal_rate, base = 10)) %>% ggplot(aes(x = as.factor(mutation), y = log_rate, fill = mutation_present)) + geom_violinhalf(position = position_dodge(width = 1), alpha = 1) + geom_point(position = position_jitterdodge(dodge.width = 1, jitter.width = 0.07), size = 0.5, alpha = 0.3, color = "black") + geom_boxplot(position = position_dodge2(width = 1), width = 0.2, outlier.shape = NA, alpha = 1) ggpubr::ggarrange(plotlist = mut_plots) pos_1 <- position_jitterdodge( jitter.width = 0.25, jitter.height = 0, dodge.width = 0.9 ) bind_rows(morsels) %>% ggplot(aes(x = mutation, y = terminal_rate, color = mutation_present)) + # geom_jitter(alpha = 0.4, position = pos_1) + stat_summary(position = position_dodge(width = 0.5), fun.y = "mean", geom = "point", size = 3) + stat_summary(position = position_dodge(width = 0.5), fun.data = "mean_cl_normal", geom = "errorbar", width = 0.05, lwd = 1, fun.args = list(conf.int = 0.95)) + labs(y = "Subst. rate", x = "Mutation", color = "") ggsave(str_glue("results/human_animal_subsets/{human_background}/dating_out/mutations_rates_terminal_by_mutation.png"), width = 7, height = 5)
2907d4a548e7eed2a183281696420f5cebbb6704
50131539a2e92a690f43aea65b0c8ff10b90bbc0
/R/theme_coffee.R
7733fec4e244824f1792cbf47f85028c6cc88808
[ "MIT" ]
permissive
RMHogervorst/coffeegeeks
904bc083fec2fc19e16151020795f19c33648698
23deb87e58029c6d345a5f1aa0e0ec07e96b86ca
refs/heads/master
2021-01-16T19:46:37.509578
2017-09-16T14:56:04
2017-09-16T14:56:04
100,188,183
1
1
null
2017-09-12T17:41:59
2017-08-13T16:01:48
CSS
UTF-8
R
false
false
2,344
r
theme_coffee.R
theme_coffee <- function(base_size=12, base_family="sans"){ ggplot2::theme(rect = element_rect(colour = "black", fill = "white"), line = element_line(colour = "black"), text = element_text(colour = "black"), plot.title = element_text(face = "bold", # 16 pt, bold, align left size = rel(1.33), hjust = 0), panel.background = element_rect(fill = NA, colour = NA), panel.border = element_rect(fill = NA, colour = NA), # 12 pt axis.title = element_text(face = "italic"), # 12 pt axis.text = element_text(), axis.line = element_line(colour = "black"), axis.ticks = element_blank(), panel.grid.major = element_line(colour = "#CCCCCC"), panel.grid.minor = element_blank(), legend.background = element_rect(colour = NA), legend.key = element_rect(colour = NA), legend.position = "right", legend.direction = "vertical") } #' A set of coffee colors #' #' @rdname coffeetheme #' @export #' @inheritParams ggplot2::scale_colour_hue coffee_pal <- function(){ function(n){ colors <- get_cols_data_frame()$hex_code[11:44] colors[seq_len(n)] } } #' @rdname coffeetheme #' @export scale_colour_coffee <- function(...){ discrete_scale("color", "coffeecolors", coffee_pal(), ...) } #' @rdname coffeetheme #' @export scale_color_coffee <- scale_colour_coffee #' @rdname coffeetheme #' @export scale_fill_coffee <- function(...){ discrete_scale("fill", "coffeecolors", coffee_pal(), ...) } #' @rdname coffeetheme #' @inheritParams ggplot2::scale_colour_hue #' @export scale_gradient_coffee <- function(..., space = "Lab", na.value = "grey50", guide = "colourbar"){ scale_color_gradient(..., low = coffee_cols(cream), high = coffee_cols(espresso), space = space, na.value = na.value, guide = guide) }
a3b3a40f870cbb34eded25f2b6edc0d190a243e0
770b14ae44e4991d444f0a0b1af124396bf2960f
/pkg/man/memisc-deprecated.Rd
c781641bbc0811b5941a701f27834785bd8ca0b0
[]
no_license
melff/memisc
db5e2d685e44f3e2f2fa3d50e0986c1131a1448c
b5b03f75e6fe311911a552041ff5c573bb3515df
refs/heads/master
2023-07-24T19:44:10.092063
2023-07-07T23:09:11
2023-07-07T23:09:11
29,761,100
40
10
null
2022-08-19T19:19:13
2015-01-24T01:21:55
R
UTF-8
R
false
false
1,615
rd
memisc-deprecated.Rd
\name{memisc-deprecated} \alias{memisc-deprecated} \alias{fapply} \alias{fapply.default} \title{Deprecated Functions in Package \pkg{memisc}} \description{ These functions are provided for compatibility with older versions of \pkg{memisc} only, and may be defunct as soon as the next release. } \usage{ fapply(formula,data,\dots) # calls UseMethod("fapply",data) \method{fapply}{default}(formula, data, subset=NULL, names=NULL, addFreq=TRUE,\dots) } \arguments{ \item{formula}{a formula. The right hand side includes one or more grouping variables separated by '+'. These may be factors, numeric, or character vectors. The left hand side may be empty, a numerical variable, a factor, or an expression. See details below.} \item{data}{an environment or data frame or an object coercable into a data frame.} \item{subset}{an optional vector specifying a subset of observations to be used.} \item{names}{an optional character vector giving names to the result(s) yielded by the expression on the left hand side of \code{formula}. This argument may be redundant if the left hand side results in is a named vector. (See the example below.)} \item{addFreq}{a logical value. If TRUE and \code{data} is a table or a data frame with a variable named "Freq", a call to \code{table}, \code{\link{Table}}, \code{\link{percent}}, or \code{\link{nvalid}} is supplied by an additional argument \code{Freq} and a call to \code{table} is translated into a call to \code{Table}. } \item{\dots}{further arguments, passed to methods or ignored.} }
a64bc677622f253be64e2a4663447c5f9c2fbb99
32ca51d8fb4de3e520b4aa49b545acefed74c3b2
/binder/install.R
303d08bd98f60deda45709203c155a7beaac6011
[]
no_license
cannin/repo2docker-test
639211141beda5979a56536aaf653c1ea9eca445
1e7671acfbbfaa6855bdc19ec8a2f6de96306b2a
refs/heads/master
2020-05-18T09:33:28.996626
2019-08-05T17:54:24
2019-08-05T17:54:24
184,327,815
0
0
null
null
null
null
UTF-8
R
false
false
191
r
install.R
install.packages("devtools") install.packages("rJava") #source("https://gist.githubusercontent.com/cannin/6b8c68e7db19c4902459/raw/installPackages.R") #installPackages("r-requirements.txt")
23590832b02d5139b5f6749c34fdb49d1afbc9d2
7f9d20b9e57be5dad4feeabf3e7f5fc6448c04e5
/WB_Data_Africa.R
bfe2b7a7c39f611a2792e5368938aaa08493c651
[]
no_license
monmon1994/TB_COVID19_Africa
3de5e9d03cdea9c3c459be7271d9f7e814ac7220
2c4d01c2d211b9ed0cef4ac36c49580e785d23be
refs/heads/master
2022-07-20T22:12:59.814109
2020-05-13T08:48:22
2020-05-13T08:48:22
263,574,765
0
0
null
null
null
null
UTF-8
R
false
false
6,767
r
WB_Data_Africa.R
# COVID Data and World Bank Data for Africa library(wbstats) library(tidyverse) library(tidycovid19) library(scales) library(ggrepel) # World Bank Data # Load the data from the stats wb_africa <- wb(country = c("DZA", "AGO", "BEN", "BWA", "BFA", "BDI", "CV", "CMR", "CAF", "TCD", "COM", "COD", "COG", "CIV", "DJI", "EGY", "ERI", "SWZ", "ETH", "GAB", "GMB", "GHA", "GIN", "GNB", "KEN", "LSO", "LBR", "LBY", "MDG", "MWI", "MLI", "MRT", "MUS", "MAR", "MOZ", "NAM", "NER", "NGA", "RWA", "STP", "SEN", "SYC", "SLE", "SOM", "ZAF", "SSD", "SDN", "TZA", "TGO", "TUN", "UGA", "ZMB", "ZWE"), indicator = c("SH.MED.PHYS.ZS", "SH.XPD.CHEX.GD.ZS", "SH.XPD.OOPC.CH.ZS", "SH.STA.DIAB.ZS", "SH.PRV.SMOK", "SH.DYN.NCOM.ZS", "SH.STA.BASS.ZS", "SP.POP.65UP.TO.ZS", "NY.GDP.MKTP.CD", "EN.POP.DNST", "SH.MED.BEDS.ZS", "SH.STA.HYGN.ZS", "NY.GDP.PCAP.CD"), startdate = 2015, enddate = 2018, POSIXct = T, return_wide = T, removeNA = T) ## COVID DATA AFRICA df <- download_jhu_csse_covid19_data(silent = T, cached = T) df <- df[['country']] df_africa <- df %>% filter(iso3c %in% c("DZA", "AGO", "BEN", "BWA", "BFA", "BDI", "CV", "CMR", "CAF", "TCD", "COM", "COD", "COG", "CIV", "DJI", "EGY", "ERI", "SWZ", "ETH", "GAB", "GMB", "GHA", "GIN", "GNB", "KEN", "LSO", "LBR", "LBY", "MDG", "MWI", "MLI", "MRT", "MUS", "MAR", "MOZ", "NAM", "NER", "NGA", "RWA", "STP", "SEN", "SYC", "SLE", "SOM", "ZAF", "SSD", "SDN", "TZA", "TGO", "TUN", "UGA", "ZMB", "ZWE")) %>% group_by(country) %>% mutate( total_confirmed = max(confirmed), total_deaths = max(deaths) ) %>% select(country, total_confirmed, total_deaths, iso3c) %>% distinct() %>% ungroup() %>% arrange(-total_deaths) merged <- merge(wb_africa, df_africa, by = "iso3c") # merge the df's save(merged, file = "data/merged.RData") ########### plots pal <- wesanderson::wes_palette("BottleRocket2", n = 51, type = "continuous") # AGE 65 above merged %>% filter(date == 2018) %>% ggplot() + geom_point(aes(x = SP.POP.65UP.TO.ZS, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + geom_label_repel(aes(x = SP.POP.65UP.TO.ZS, y = total_confirmed, label = country.x)) + guides(fill=FALSE) + xlab("Population ages 65 and above (% of total)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # SMOKING SH.PRV.SMOK ggplot(merged) + geom_point(aes(x = SH.PRV.SMOK, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + geom_label_repel(aes(x = SH.PRV.SMOK, y = total_confirmed, label = country.x)) + guides(fill=FALSE) + xlab("Smoking prevalence, total, ages 15+") + ylab("COVID-19 Confirmed Cases") + theme_classic() # Physicians per 1,000 SH.MED.PHYS.ZS ggplot(merged) + geom_point(aes(x = SH.MED.PHYS.ZS, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + geom_label_repel(aes(x = SH.MED.PHYS.ZS, y = total_confirmed, label = country.x)) + guides(fill=FALSE) + xlab("Physicians (1,000 per people)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # Non-communicable diseases SH.DTH.NCOM.ZS ggplot(merged) + geom_point(aes(x = SH.DYN.NCOM.ZS, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + geom_label_repel(aes(x = SH.DYN.NCOM.ZS, y = total_confirmed, label = country.x)) + guides(fill=FALSE) + xlab("Mortality from CVD, cancer, diabetes or CRD between exact ages 30 and 70 (%)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # SH.STA.DIAB.ZS no data # SH.STA.HYGN.ZS basic hygiene services merged %>% filter(date == 2017) %>% ggplot() + geom_point(aes(x = SH.STA.HYGN.ZS, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + guides(fill=FALSE, size = F) + gghighlight::gghighlight(use_direct_label = T) + xlab("People with basic handwashing facilities including soap and water (% of population)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # NY.GDP.MKTP.CD merged %>% filter(date == 2018) %>% ggplot() + geom_point(aes(x = NY.GDP.MKTP.CD, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + scale_x_log10() + guides(fill=FALSE, size = F) + gghighlight::gghighlight(use_direct_label = T) + xlab("GDP (current USD)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # NY.GDP.PCAP.CD GDP per capita merged %>% filter(date == 2018) %>% ggplot() + geom_point(aes(x = NY.GDP.PCAP.CD, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + scale_x_log10() + guides(fill=FALSE, size = F) + gghighlight::gghighlight(use_direct_label = T) + xlab("GDP (current USD)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # Health expenditure "SH.XPD.CHEX.GD.ZS" merged %>% filter(date == 2017) %>% ggplot() + geom_point(aes(x = SH.XPD.CHEX.GD.ZS, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + guides(fill=FALSE, size = F) + gghighlight::gghighlight(use_direct_label = T) + xlab("Current health expenditure (% of GDP)") + ylab("COVID-19 Confirmed Cases") + theme_classic() # SH.XPD.OOPC.CH.ZS "Out-of-pocket expenditure (% of current health expenditure)" merged %>% filter(date == 2017) %>% ggplot() + geom_point(aes(x = SH.XPD.OOPC.CH.ZS, y = total_confirmed, colour = country.x, size = 3), show.legend = FALSE) + scale_fill_gradientn(colours = pal) + scale_y_log10() + guides(fill=FALSE, size = F) + gghighlight::gghighlight(use_direct_label = T) + xlab("Out-of-pocket expenditure (% of current health expenditure)") + ylab("COVID-19 Confirmed Cases") + theme_classic()
5bb7c25110290707bcbd78341103071b8449100a
0e6f03600e49c8a9f6bfe1c4e0ed2fb423d9690d
/Real_study/r/1_lacpd_wadi.R
aad41b3144521915e53bcfa547bc74ae9e2ad778
[]
no_license
mmontesinosanmartin/LACPD_Article
bd1688dea09d993dcd859b01741a9c3449d28ee5
b8acd76eae1ea704c21cf8c9306dc34403e4f071
refs/heads/master
2023-02-16T04:15:10.784437
2021-01-12T17:48:11
2021-01-12T17:48:11
259,288,942
0
1
null
null
null
null
UTF-8
R
false
false
2,680
r
1_lacpd_wadi.R
############################################################################### # R CODE: Locally adaptive change point detection ############################################################################### # Moradi, M., Montesino-SanMartin, M., Ugarte, M.D., Militino, A.F. # Public University of Navarre # License: Availability of material under # [CC-BY-SA](https://creativecommons.org/licenses/by-sa/2.0/). ############################################################################### # PACKAGE ############################################################################### # devtools package # library(devtools) # install from github # install_github("mmontesinosanmartin/LACPD_Article/LACPD") # load library(LACPD) ############################################################################### # DATA PATHS ############################################################################### # inputs root.git <- "https://raw.githubusercontent.com/mmontesinosanmartin/changepoint_article/" root.dir <- "master/Real_study/data" files <- c("field1_7.RData", "field2_21.RData", "field3_29.RData") n.files <- length(files) # output directory (select your own) out.dir <- "./" ############################################################################### # ANALYSIS ############################################################################### # Paramters # windows this.k <- "02:10" # iterations this.m <- 100 # adjusting method this.adj <- "BY" # Check running times t.strt <- Sys.time() # Run: for each file for(i in 1:n.files){ # load the dataset f.i <- file.path(root.git, root.dir, paste0(files[i])) load(url(f.i)) # result resl <- list() # for each pixel for (j in 1:nrow(this.data)) { # the time-series for this pixel x <- this.data[j,] # print message (every 10% completed) p <- round(j/nrow(this.data)*100) if (p %% 10 == 0 & p > 0) print(paste0(p, "%")) # run the analysis resl[[j]] <- lacpd_mk(x = x, k = eval(parse(text=this.k)), m = this.m, adjust = TRUE, method = this.adj, history = TRUE) } # save output suffix <- paste(gsub(":","",this.k), this.m, this.adj, sep = "_") out.file <- paste0(gsub(".RData","",basename(f.i)),"_",suffix, ".RData") out.path <- file.path(out.dir,out.file) save(sample.roi, # study region sample.val, # NDVI RasterBrick this.data, # NDVI data matrix resl, # All results file = out.path) } # Total running time Sys.time() - t.strt # Time difference of 1.734562 hours
0b5fcd5e86a49b416e21482e56be05a22beecd1e
2970a3fe4634b1f8fb24243730b8becce4b5da42
/week_1/5_friday/Phylacine/commands.r
cf867f8bf0490e9bef76d4e80bbfa95f400f5335
[ "MIT" ]
permissive
chase-lab/biodiv-patterns-course
21b38d5b99e3a90cc18e020c2fb74db9a5a8966b
8212e9fabb2db9187c510e6e15ce8e94e83f960e
refs/heads/master
2022-04-05T06:07:53.110753
2020-02-21T16:11:04
2020-02-21T16:11:04
235,298,888
2
1
null
null
null
null
UTF-8
R
false
false
467
r
commands.r
library(rgdal) library(sp) library(raster) # ------------------------------------------------------------------------------ sh <- readOGR(dsn= "Shapefile", layer = "land_boundary") rs <- raster("Environment/Elevation.tif") plot(rs) plot(sh, add=T) # projections BEHRMANN <- CRS("+proj=cea +lon_0=0 +lat_ts=30 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0") WGS84 <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
17b8ef6f3dcae7519cebb932a446dd011848db4a
0accbe1994d882fdeb49cad9398519cfb4e40a15
/r_scripts/170220_pol2_profiles_meta_meta.R
1a3219ce6cc7ffb18f3588d907aa5547ab544545
[ "MIT" ]
permissive
linlabbcm/RASMC_Phenotypic_Switching
026da5f96dc0aef3705eb0218fd7d2d3990f025e
0636cf9154bae385c998e1a44c360f726e09ea56
refs/heads/master
2020-03-22T01:05:36.876041
2018-06-30T23:43:42
2018-06-30T23:43:42
null
0
0
null
null
null
null
UTF-8
R
false
false
8,457
r
170220_pol2_profiles_meta_meta.R
pol2_0_TSS = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TSS_ALL_-3000_+0\\RN6_TSS_ALL_-3000_+0_RASMC_POL2_UNSTIM_NEW.gff',header=TRUE) pol2_0_TXN = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TXN_ALL_-0_+0\\RN6_TXN_ALL_-0_+0_RASMC_POL2_UNSTIM_NEW.gff',header=TRUE) pol2_0_TTR = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TTR_ALL_-0_+3000\\RN6_TTR_ALL_-0_+3000_RASMC_POL2_UNSTIM_NEW.gff',header=TRUE) pol2_2_TSS = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TSS_ALL_-3000_+0\\RN6_TSS_ALL_-3000_+0_RASMC_POL2_PDGF_2H_NEW.gff',header=TRUE) pol2_2_TXN = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TXN_ALL_-0_+0\\RN6_TXN_ALL_-0_+0_RASMC_POL2_PDGF_2H_NEW.gff',header=TRUE) pol2_2_TTR = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TTR_ALL_-0_+3000\\RN6_TTR_ALL_-0_+3000_RASMC_POL2_PDGF_2H_NEW.gff',header=TRUE) pol2_24_TSS = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TSS_ALL_-3000_+0\\RN6_TSS_ALL_-3000_+0_RASMC_POL2_PDGF_24H_NEW.gff',header=TRUE) pol2_24_TXN = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TXN_ALL_-0_+0\\RN6_TXN_ALL_-0_+0_RASMC_POL2_PDGF_24H_NEW.gff',header=TRUE) pol2_24_TTR = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TTR_ALL_-0_+3000\\RN6_TTR_ALL_-0_+3000_RASMC_POL2_PDGF_24H_NEW.gff',header=TRUE) pol2_2J_TSS = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TSS_ALL_-3000_+0\\RN6_TSS_ALL_-3000_+0_RASMC_POL2_PDGF_2H_JQ1_NEW.gff',header=TRUE) pol2_2J_TXN = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TXN_ALL_-0_+0\\RN6_TXN_ALL_-0_+0_RASMC_POL2_PDGF_2H_JQ1_NEW.gff',header=TRUE) pol2_2J_TTR = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TTR_ALL_-0_+3000\\RN6_TTR_ALL_-0_+3000_RASMC_POL2_PDGF_2H_JQ1_NEW.gff',header=TRUE) pol2_24J_TSS = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TSS_ALL_-3000_+0\\RN6_TSS_ALL_-3000_+0_RASMC_POL2_PDGF_24H_JQ1_NEW.gff',header=TRUE) pol2_24J_TXN = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TXN_ALL_-0_+0\\RN6_TXN_ALL_-0_+0_RASMC_POL2_PDGF_24H_JQ1_NEW.gff',header=TRUE) pol2_24J_TTR = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\mappedFolder\\RN6_TTR_ALL_-0_+3000\\RN6_TTR_ALL_-0_+3000_RASMC_POL2_PDGF_24H_JQ1_NEW.gff',header=TRUE) active_genes = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\activeListTable.txt', header = FALSE) orderTable = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\170206_waterfall_genes_log2_24_v_0_ordered_BRD4_H3k_RNA_0_2_24_and_log2.txt',header = TRUE) up_24=which(orderTable[,12]>=1) down_24 = which(orderTable[,12]<=-1) orderTable2 = read.delim('C:\\Users\\rhirsch\\Documents\\rasmc_docs\\170206_waterfall_genes_log2_2_v_0_ordered_BRD4_H3k_RNA_0_2_24_and_log2.txt',header = TRUE) up_2=which(orderTable2[,10]>=1) down_2 = which(orderTable2[,10]<=-1) pol2_0 = cbind(pol2_0_TSS[,3:62],pol2_0_TXN[,3:202],pol2_0_TTR[,3:62]) rownames(pol2_0) = pol2_0_TTR[,1] pol2_2 = cbind(pol2_2_TSS[,3:62], pol2_2_TXN[,3:202],pol2_2_TTR[,3:62]) rownames(pol2_2) = rownames(pol2_0) pol2_24 = cbind(pol2_24_TSS[,3:62],pol2_24_TXN[,3:202],pol2_24_TTR[,3:62]) rownames(pol2_24) = pol2_0_TTR[,1] pol2_2J = cbind(pol2_2J_TSS[,3:62], pol2_2J_TXN[,3:202],pol2_2J_TTR[,3:62]) rownames(pol2_2J) = rownames(pol2_0) pol2_24J = cbind(pol2_24J_TSS[,3:62], pol2_24J_TXN[,3:202],pol2_24J_TTR[,3:62]) rownames(pol2_24J) = rownames(pol2_0) ########################################### ############Active Genes Metas############# ########################################### active0 = c() for(i in 1:length(active_genes[,1])){ row = which(as.character(rownames(pol2_0))==as.character(active_genes[i,1])) active0=c(active0,row) } pol2_0_meta = apply(pol2_0[active0,],2,mean,na.rm=TRUE) pol2_2_meta = apply(pol2_2[active0,],2,mean,na.rm=TRUE) pol2_24_meta = apply(pol2_24[active0,],2,mean,na.rm=TRUE) pol2_2J_meta = apply(pol2_2J[active0,],2,mean,na.rm=TRUE) pol2_24J_meta = apply(pol2_24J[active0,],2,mean,na.rm=TRUE) pdf(file='C:\\Users\\rhirsch\\Documents\\rasmc_figures_1-3\\170222_rasmc_active_pol2_0v2_meta.pdf',width = 10,height = 8) plot(1:320, pol2_0_meta,type='l',col='red',ylim =c(0,2.5),xaxt='n',xlab='',ylab='rpm/bp',main='active genes 0H (red) vs. 2H (black)') lines(1:320, pol2_2_meta,type='l',col='black') axis(1,c(0,60,260,320),c('-3kb','TSS','END','+3kb')) dev.off() pdf(file='C:\\Users\\rhirsch\\Documents\\rasmc_figures_1-3\\170222_rasmc_active_pol2_0v24_meta.pdf',width = 10,height = 8) plot(1:320, pol2_0_meta,type='l',col='red',ylim =c(0,2.5),xaxt='n',xlab='',ylab='rpm/bp',main='active genes 0H (red) vs. 24H (black)') lines(1:320, pol2_24_meta,type='l',col='black') axis(1,c(0,60,260,320),c('-3kb','TSS','END','+3kb')) dev.off() pdf(file='C:\\Users\\rhirsch\\Documents\\rasmc_figures_1-3\\170222_rasmc_active_pol2_2v2J_meta.pdf',width = 10,height = 8) plot(1:320, pol2_2_meta,type='l',col='red',ylim =c(0,2.5),xaxt='n',xlab='',ylab='rpm/bp',main='active genes 2H (red) vs. 2H+JQ1 (black)') lines(1:320, pol2_2J_meta,type='l',col='black') axis(1,c(0,60,260,320),c('-3kb','TSS','END','+3kb')) dev.off() pdf(file='C:\\Users\\rhirsch\\Documents\\rasmc_figures_1-3\\170222_rasmc_active_pol2_24v24J_meta.pdf',width = 10,height = 8) plot(1:320, pol2_24_meta,type='l',col='red',ylim =c(0,5),xaxt='n',xlab='',ylab='rpm/bp',main='active genes 24H (red) vs. 24H+JQ1 (black)') lines(1:320, pol2_24J_meta,type='l',col='black') axis(1,c(0,60,260,320),c('-3kb','TSS','END','+3kb')) dev.off() ########################################### ############Gained/Lost Genes Metas 24H#### ########################################### lost_genes=c() for(i in 1:1000){ row = which(as.character(active_genes[,2]) == as.character(orderTable[i,1])) lost_genes = c(lost_genes,row) } gained_genes = c() for(i in 7726:8725){ row = which(as.character(active_genes[,2])==as.character(orderTable[i,1])) gained_genes = c(gained_genes,row) } pol2_rows_up = c() for(i in 1:length(gained_genes)){ row = which(rownames(pol2_0)==active_genes[i,1]) pol2_rows_up = c(pol2_rows_up,row) } pol2_rows_down = c() for(i in 1:length(lost_genes)){ row = which(rownames(pol2_0) == active_genes[i,1]) pol2_rows_down = c(pol2_rows_down,row) } pol2_24_meta_up = apply(pol2_24[pol2_rows_up,],2,mean,na.rm=TRUE) print(pol2_24_meta_up[1:5]) print(pol2_24_meta_up[150:155]) print(pol2_24_meta_up[315:320]) pol2_24_meta_down = apply(pol2_24[pol2_rows_down,],2,mean,na.rm=TRUE) print(pol2_24_meta_down[1:5]) print(pol2_24_meta_down[150:155]) print(pol2_24_meta_down[315:320]) pdf(file='C:\\Users\\rhirsch\\Documents\\rasmc_figures_1-3\\170222_rasmc_gained_vs_lost_24H_meta_750.pdf',width = 10,height = 8) plot(1:320, pol2_24_meta_up,type='l',col='red',ylim =c(0,2.5),xaxt='n',xlab='',ylab='rpm/bp',main='lost genes 24H (black) vs. gained genes 24H (red)') lines(1:320, pol2_24_meta_down,type='l',col='black') axis(1,c(0,60,260,320),c('-3kb','TSS','END','+3kb')) dev.off() ########################################### ############Gained/Lost Genes Metas 2H##### ########################################### table2_genes = as.character(rownames(orderTable2)) lost_genes2=c() for(i in 1:500){ row = which(as.character(active_genes[,2]) == table2_genes[i]) lost_genes2 = c(lost_genes2,row) } gained_genes2 = c() for(i in 7726:8725){ row = which(as.character(active_genes[,2])== table2_genes[i]) gained_genes2 = c(gained_genes2,row) } pol2_rows_up2 = c() for(i in 1:length(gained_genes2)){ row = which(rownames(pol2_0)==active_genes[i,1]) pol2_rows_up2 = c(pol2_rows_up2,row) } pol2_rows_down2 = c() for(i in 1:length(lost_genes2)){ row = which(rownames(pol2_0) == active_genes[i,1]) pol2_rows_down2 = c(pol2_rows_down2,row) } pol2_2_meta_up = apply(pol2_2[pol2_rows_up2,],2,mean,na.rm=TRUE) pol2_2_meta_down = apply(pol2_2[pol2_rows_down2,],2,mean,na.rm=TRUE) pdf(file='C:\\Users\\rhirsch\\Documents\\rasmc_figures_1-3\\170222_rasmc_gained_vs_lost_2H_meta.pdf',width = 10,height = 8) plot(1:320, pol2_2_meta_up,type='l',col='red',ylim =c(0,2.5),xaxt='n',xlab='',ylab='rpm/bp',main='lost genes 2H (black) vs. gained genes 2H (red)') lines(1:320, pol2_2_meta_down,type='l',col='black') axis(1,c(0,60,260,320),c('-3kb','TSS','END','+3kb')) dev.off()
37ea4ccc462b754f2191118194d7cffb4b481bd4
0fd0fb1ada1b966357fe55bfab6540fc7358b62a
/man/count_consonants.Rd
4ca4dda86f3b6c74710c323dcbf4ba7e610b72f2
[ "MIT" ]
permissive
nelsonroque/ruf
f1f8598964ade0085ad9ecc77b92b99a4c544a4a
dbf86c97ce5ad03e417cd379c47a410c4dbd0566
refs/heads/master
2021-06-26T18:31:48.057608
2021-02-28T14:04:12
2021-02-28T14:04:12
206,207,103
0
0
null
null
null
null
UTF-8
R
false
true
285
rd
count_consonants.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/count_consonants.R \name{count_consonants} \alias{count_consonants} \title{ruf} \usage{ count_consonants(str) } \arguments{ \item{str}{class: string} } \description{ ruf } \examples{ count_consonants(str) }
bdfa3f1d3ba92174c9c8200bb1a59c53aa6f4581
3c8ba871dfa3dc3673c2fbd0e4838c35e09caf2a
/댓글 크롤링.R
d032fb9b2c911276c7bed9d3b2898129a2c097b2
[]
no_license
JinsaGalbi/webtoon-recommend-system
bc580fb61f61802254cf9836eae9a0e7707edf52
9983935d1ec26f5723e3859f6c933b08d0886b81
refs/heads/master
2022-12-15T03:02:37.297373
2020-09-08T04:56:15
2020-09-08T04:56:15
293,414,785
0
0
null
null
null
null
UTF-8
R
false
false
7,027
r
댓글 크롤링.R
## 댓글 크롤링 setwd('c:/Users/USER/Desktop/주제분석/웹툰크롤링') comment_url <- read.csv('comment_url.csv') library(rvest);library(tidyverse);library(magrittr) library(RSelenium) rD <- rsDriver(port = 4445L,browser = 'chrome',chromever = '78.0.3904.70') remDr <- rD[["client"]] # comment_final <- data.frame(nickname=NULL,id=NULL,recommend=NULL,unrecommend=NULL,text=NULL,i=NULL) for(i in 127:length(comment_url$url)){ nickname <- c();id <- c();recommend <- c();unrecommend <- c();date <- c();text <- c() remDr$navigate(paste0('http://comic.naver.com',comment_url$url[i])) webElem <- remDr$findElements(using = 'xpath',value = '//*[@id="cbox_module"]/div/div[4]/div[1]/div/ul/li[2]/a') #전체댓글 표시하기 remDr$mouseMoveToLocation(webElement = webElem[[1]]) #마우스 이동 remDr$click() #버튼 클릭 Sys.sleep(0.2) frontPage <- remDr$getPageSource() #페이지 전체 소스 가져오기 nickname_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_nick') %>% html_text() %>% trimws() id_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_id') %>% html_text() %>% trimws() recommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_recomm') %>% html_text() %>% trimws() unrecommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_unrecomm') %>% html_text() %>% trimws() date_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_date') %>% html_text() %>% trimws() text_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_text_wrap') %>% html_text() %>% trimws() nickname <- c(nickname, nickname_temp) id <- c(id, id_temp) recommend <- c(recommend, recommend_temp) unrecommend <- c(unrecommend, unrecommend_temp) date <- c(date, date_temp) text <- c(text, text_temp) # 여기까지 첫페이지 page_flag <- read_html(frontPage[[1]]) %>% html_nodes(css='.u_cbox_next') %>% html_attr('href') %>% first() if(is.na(page_flag)){ # 댓글에 다음페이지가 없는 경우 = 페이지가 1~10까지만 있는 경우 for(j in c(1,3:10)){ webElem <- remDr$findElements(using = 'xpath',value = paste0('//*[@id="cbox_module"]/div/div[7]/div/a[',j,']')) remDr$mouseMoveToLocation(webElement = webElem[[1]]) remDr$click() #버튼 클릭 Sys.sleep(0.2) frontPage <- remDr$getPageSource() #페이지 전체 소스 가져오기 nickname_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_nick') %>% html_text() %>% trimws() id_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_id') %>% html_text() %>% trimws() recommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_recomm') %>% html_text() %>% trimws() unrecommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_unrecomm') %>% html_text() %>% trimws() date_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_date') %>% html_text() %>% trimws() text_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_text_wrap') %>% html_text() %>% trimws() nickname <- c(nickname, nickname_temp) id <- c(id, id_temp) recommend <- c(recommend, recommend_temp) unrecommend <- c(unrecommend, unrecommend_temp) date <- c(date, date_temp) text <- c(text, text_temp) # 여기까지 2~11페이지 } }else{ # 댓글에 다음페이지가 있는 경우 = 페이지가 11장 이상 for(k in c(1,3:11)){ webElem <- remDr$findElements(using = 'xpath',value = paste0('//*[@id="cbox_module"]/div/div[7]/div/a[',k,']')) remDr$mouseMoveToLocation(webElement = webElem[[1]]) remDr$click() #버튼 클릭 Sys.sleep(0.2) frontPage <- remDr$getPageSource() #페이지 전체 소스 가져오기 nickname_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_nick') %>% html_text() %>% trimws() id_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_id') %>% html_text() %>% trimws() recommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_recomm') %>% html_text() %>% trimws() unrecommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_unrecomm') %>% html_text() %>% trimws() date_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_date') %>% html_text() %>% trimws() text_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_text_wrap') %>% html_text() %>% trimws() nickname <- c(nickname, nickname_temp) id <- c(id, id_temp) recommend <- c(recommend, recommend_temp) unrecommend <- c(unrecommend, unrecommend_temp) date <- c(date, date_temp) text <- c(text, text_temp) # 여기까지 2~11페이지 } for(l in rep(3:12,10000)){ webElem <- remDr$findElements(using = 'xpath',value = paste0('//*[@id="cbox_module"]/div/div[7]/div/a[',l,']')) if(length(webElem)>=1){ remDr$mouseMoveToLocation(webElement = webElem[[1]]) remDr$click() #버튼 클릭 Sys.sleep(0.2) frontPage <- remDr$getPageSource() #페이지 전체 소스 가져오기 nickname_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_nick') %>% html_text() %>% trimws() id_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_id') %>% html_text() %>% trimws() recommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_recomm') %>% html_text() %>% trimws() unrecommend_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_cnt_unrecomm') %>% html_text() %>% trimws() date_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_date') %>% html_text() %>% trimws() text_temp <- read_html(frontPage[[1]]) %>% html_nodes('.u_cbox_text_wrap') %>% html_text() %>% trimws() nickname <- c(nickname, nickname_temp) id <- c(id, id_temp) recommend <- c(recommend, recommend_temp) unrecommend <- c(unrecommend, unrecommend_temp) date <- c(date, date_temp) text <- c(text, text_temp) }else{break}} } instant <- data.frame(i=i,title=rep(comment_url$title[i],length(id)),nickname=nickname,id=id,text=text) %>% filter(text!='클린봇이 이용자 보호를 위해 숨긴 댓글입니다.') %>% bind_cols(data.frame(recommend=recommend,unrecommend=unrecommend)) comment_final %<>% bind_rows(instant) } # write.csv(comment_final,'comment1.csv', row.names = F) # write.csv(comment_final,'comment2.csv', row.names = F) # write.csv(comment_final,'comment3.csv', row.names = F) # write.csv(comment_final,'comment4.csv', row.names = F) # write.csv(comment_final,'comment5.csv', row.names = F) # write.csv(comment_final,'comment6.csv', row.names = F) # write.csv(comment_final,'comment7.csv', row.names = F) # write.csv(comment_final,'comment8.csv', row.names = F) # write.csv(comment_final,'comment9.csv', row.names = F)
f463c9693a65af962d8d8bba38aa927377cde04a
474c866367bda19aa16c88961e34dde81a17786f
/housing-market/new-home-sales/new-home-sales.R
c2ced9c14db2a14738d5b9ae464dfb4dbc0af4f1
[]
no_license
davidallen02/economic-market-commentary
fefde0a6e46a5f92eac8dfe9969d004769a34f2e
2eef6f4d7fbbff1db39c3323bb7246f6263dff3d
refs/heads/master
2023-06-08T10:36:40.946661
2021-06-22T21:04:09
2021-06-22T21:04:09
281,976,227
0
0
null
null
null
null
UTF-8
R
false
false
1,320
r
new-home-sales.R
library(magrittr) lay <- pamngr::set_layout(11) title <- pamngr::set_title("New Home Sales") new_home_sales <- pamngr::run_and_load("new-home-sales", "new-home-sales") + ggplot2::theme(legend.position = "none", plot.caption = ggplot2::element_blank()) northeast <- pamngr::run_and_load("new-home-sales", "new-home-sales-northeast") + ggplot2::theme(plot.caption = ggplot2::element_blank()) midwest <- pamngr::run_and_load("new-home-sales", "new-home-sales-midwest") + ggplot2::theme(plot.caption = ggplot2::element_blank()) south <- pamngr::run_and_load("new-home-sales", "new-home-sales-south") + ggplot2::theme(plot.caption = ggplot2::element_blank()) west <- pamngr::run_and_load("new-home-sales", "new-home-sales-west") + ggplot2::theme(plot.caption = ggplot2::element_blank()) foo <- gridExtra::grid.arrange(grobs = list(title, new_home_sales, northeast, midwest, south, west), layout_matrix = lay) ggplot2::ggsave("./housing-market/new-home-sales/new-home-sales.png", plot = foo, width = 10, height = 6.75, units = "in")
2528244c1ab6f5a52508444bafeab1cf52eeada3
2d12c1d9fff0c57acc87fb1fcbd9d189854c3d79
/programs/ggplottrain.R
7427ba1d880cf60c2d7ff4663c157c2283d67d28
[ "MIT" ]
permissive
lfthwjx/DataAnalytics
8cbab6bf7006d46f6e8ab34bbc86d7907d9ed177
68aaf7a936a5a7599e2e2039f6fe26b0a90c14e9
refs/heads/master
2021-01-13T12:35:18.255673
2016-11-01T21:52:37
2016-11-01T21:52:37
72,579,217
0
0
null
null
null
null
UTF-8
R
false
false
585
r
ggplottrain.R
library(ggplot2) data("diamonds") p <- ggplot(data = diamonds, mapping = aes(x = carat, y = price, color = cut)) summary(p) p p + layer(geom = "point", stat = "identity", position = "identity") #p + geom_point() p <- ggplot(data = diamonds, mapping = aes(x = carat)) summary(p) p p2 <- p + layer(geom = "bar",stat = "bin") summary(p2) p<-ggplot(data=mpg,mapping = aes(x=cty,y=hwy)) p+geom_point() summary(p) summary(p+geom_point()) p<-ggplot(data=mpg,aes(x=cty,y=hwy),colours = factor(mpg$year)) p+geom_point() p+geom_point()+stat_smooth() factor(mpg$year)
2588cb153675ee6087016b010a4cfa5fb084ffe1
49e30ad80df564f40b163938f0fd1c00658ff1da
/Fig_1B/limma_main_Fig1B.R
22fcba4ca58f78a26bcfa550642040b240d5dec5
[]
no_license
wasimaftab/IMS_Shotgun
ca583f16aa72198ef4ce174c69de7196d528cbc3
32bb13f21df969d9562b966f1e44ff9436d3e159
refs/heads/master
2021-08-18T02:48:43.082139
2020-12-27T11:46:04
2020-12-27T11:46:04
237,218,411
1
0
null
null
null
null
UTF-8
R
false
false
9,580
r
limma_main_Fig1B.R
################################################################################ ## This code is to reproduce the data and image of Figure 1B ## Since the missing values are imputed randomly (from normal distribution), ## One can notice minute changes in numbers associated with fold change and p-values ## across multiple runs of the code. However, the major patterns in the data do not change. ## Author: Wasim Aftab ################################################################################ cat('\014') rm(list = ls()) ## Installing Bioconductor packages if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") list.of.packages <- c("limma", "qvalue") new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])] if(length(new.packages)) BiocManager::install(new.packages) ## Installing CRAN packages list.of.packages <- c("dplyr", "stringr", "MASS", "matlab", "plotly", "htmlwidgets", "rstudioapi", "webshot", "matrixStats") new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])] if(length(new.packages)) install.packages(new.packages) if (is.null(webshot:::find_phantom())){ webshot::install_phantomjs() } library(dplyr) library(stringr) library(MASS) library(matlab) library(plotly) library(limma) library(qvalue) library(htmlwidgets) library(rstudioapi) ##Chdir to source dir path <- rstudioapi::getActiveDocumentContext()$path Encoding(path) <- "UTF-8" setwd(dirname(path)) cur_dir <- getwd() source("limma_helper_functions_Fig1B.R") ##Load the proteingroups file myFilePath <- "proteinGroups_180416.txt" proteingroups <- as.data.frame(read.table(myFilePath, header = TRUE, sep = "\t")) ###Kill the code if proteingroups does not contain crap columns####################################### temp <- select( proteingroups, matches("(Reverse|Potential.contaminant|Only.identified.by.site)") ) if (!nrow(temp) * ncol(temp)) { stop("File error, It does not contain crap...enter another file with crap") } ###################################################################################################### ##Display data to faciliate choice of treatment and control temp <- select(proteingroups, matches("(ibaq|lfq)")) print(names(temp)) # #remove "+" identifeid rows from proteingroups################################################## idx <- NULL # temp <- as.matrix(select(proteingroups, matches("(Only.identified.by.site|Reverse|Potential.contaminant)"))) temp <- select(proteingroups, matches("(Only.identified.by.site|Reverse|Potential.contaminant)")) for (i in 1:ncol(temp)){ index <- which(unlist(!is.na(match(temp[,i], "+")))) idx <- union(idx, index) } proteingroups <- proteingroups[-idx, ] # removing indexed rows # ################################################################################################ # #Extrat Uniprot and gene symbols Uniprot <- character(length = nrow(proteingroups)) Symbol <- character(length = nrow(proteingroups)) ProteinNames <- proteingroups$Protein.names for (i in 1:nrow(proteingroups)) { temp <- as.character(proteingroups$Fasta.headers[i]) splits <- unlist(strsplit(temp, '\\|')) Uniprot[i] <- splits[2] splits <- unlist(str_match(splits[3], "GN=(.*?) PE=")) Symbol[i] <- splits[2] } #Extract required data for Limma treatment <- readline('Enter treatment name(case insensitive) as it appeared in the iBAQ/LFQ column= ') control <- readline('Enter control name(case insensitive) as it appeared in the iBAQ/LFQ column= ') ibaq <- readinteger_binary('Enter 1 for iBAQ or 0 for LFQ= ') if (ibaq) { temp <- select(proteingroups, matches(paste('^.*', "ibaq", '.*$', sep = ''))) treatment_reps <- data_sanity_check(temp, 'treatment', treatment) control_reps <- select(temp, matches(control)) control_reps <- data_sanity_check(temp, 'control', control) data <- cbind(treatment_reps, control_reps, select(proteingroups, matches("^id$")), Uniprot, Symbol, ProteinNames) } else { temp <- select(proteingroups, matches(paste('^.*', "lfq", '.*$', sep = ''))) treatment_reps <- select(temp, matches(treatment)) treatment_reps <- data_sanity_check(temp, 'treatment', treatment) control_reps <- select(temp, matches(control)) control_reps <- data_sanity_check(temp, 'control', control) data <- cbind(treatment_reps, control_reps, select(proteingroups, matches("^id$")), Uniprot, Symbol, ProteinNames) } print(names(data)) rep_treats <- readinteger("Enter the number of treatment replicates=") rep_conts <- readinteger("Enter the number of control replicates=") FC_Cutoff <- readfloat("Enter the fold change cut off=") ## Find out Blank rows, i.e. proteins with all zeros in treatment and in control, see followig example # iBAQ.Mrpl40_1 iBAQ.Mrpl40_2 iBAQ.Mrpl40_3 iBAQ.Kgd4_1 iBAQ.Kgd4_2 iBAQ.Kgd4_3 id Uniprot Symbol #------------------------------------------------------------------------------------------------- # 0 0 0 0 0 0 84 Q02888 INA17 temp <- as.matrix(rowSums(apply(data[, 1:(rep_treats + rep_conts)], 2, as.numeric))) idx <- which(temp == 0) if (length(idx)) { data <- data[-idx,] # removing blank rows } # ## Find out outliers, i.e. proteins with all zeros in treatment and all/some values in control, see followig example # ## Uniprot Symbol treat_1 treat_2 treat_3 contrl_1 contrl_2 contrl_3 # ##----------------------------------------------------------------------------------- # ## P25554 SGF29 0 0 0 2810900 0 0 # temp <- as.matrix(rowSums(data[,1:rep_treats])) temp <- as.matrix(rowSums(apply(data[, 1:rep_treats], 2, as.numeric))) idx <- which(temp == 0) if (length(idx)) { outliers <- data[idx,] filename_outliers <- "Exclusive_proteins_WT" # paste("Outliers_treatment_", treatment, "_", control, sep = "") data <- data[-idx, ] # removing indexed rows } # ## Find out outliers, i.e. proteins with all zeros in control and all/some values in treatment, see followig example # iBAQ.Mrpl40_1 iBAQ.Mrpl40_2 iBAQ.Mrpl40_3 iBAQ.Kgd4_1 iBAQ.Kgd4_2 iBAQ.Kgd4_3 id Uniprot Symbol ##----------------------------------------------------------------------------------------------------- # 662810 505600 559130 0 0 0 79 P38845 CRP1 # temp <- # as.matrix(rowSums(data[, (rep_treats + 1):(rep_conts + rep_treats)])) temp <- as.matrix(rowSums(apply(data[, (rep_treats + 1):(rep_conts + rep_treats)], 2, as.numeric))) idx <- which(temp == 0) if (length(idx)) { outliers_control <- data[idx,] filename_outliers_control <- "Exclusive_proteins_AROM" # paste("Outliers_control_", treatment, "_", control, sep = "") data <- data[-idx, ] # removing indexed rows } #Impute data data_limma <- log2(as.matrix(data[c(1:(rep_treats + rep_conts))])) data_limma[is.infinite(data_limma)] <- NA nan_idx <- which(is.na(data_limma)) fit <- fitdistr(c(na.exclude(data_limma)), "normal") mu <- as.double(fit$estimate[1]) sigma <- as.double(fit$estimate[2]) sigma_cutoff <- 6 new_width_cutoff <- 0.3 downshift <- 1.8 width <- sigma_cutoff * sigma new_width <- width * new_width_cutoff new_sigma <- new_width / sigma_cutoff new_mean <- mu - downshift * sigma imputed_vals_my = rnorm(length(nan_idx), new_mean, new_sigma) data_limma[nan_idx] <- imputed_vals_my ##Limma main code design <- model.matrix( ~ factor(c(rep(2, rep_treats), rep(1, rep_conts)))) colnames(design) <- c("Intercept", "Diff") res.eb <- eb.fit(data_limma, design, data$Symbol) Sig_FC_idx <- union(which(res.eb$logFC < (-FC_Cutoff)), which(res.eb$logFC > FC_Cutoff)) Sig_Pval_mod_idx <- which(res.eb$p.mod < 0.05) Sig_Pval_ord_idx <- which(res.eb$p.ord < 0.05) Sig_mod_idx <- intersect(Sig_FC_idx, Sig_Pval_mod_idx) Sig_ord_idx <- intersect(Sig_FC_idx, Sig_Pval_ord_idx) categ_Ord <- rep(c("Not Significant"), times = length(data$Symbol)) categ_Mod <- categ_Ord categ_Mod[Sig_mod_idx] <- "Significant" categ_Ord[Sig_ord_idx] <- "Significant" dat <- cbind( res.eb, categ_Ord, categ_Mod, NegLogPvalMod = (-log10(res.eb$p.mod)), NegLogPvalOrd = (-log10(res.eb$p.ord)) ) dat <- select(dat, -matches("^gene$")) # dat <- select(dat, -matches("^Uniprot$")) ##Save the data file final_data <- cbind(data$Uniprot, data$ProteinNames, data$Symbol, data[,1:(rep_treats+rep_conts)], dat) colnames(final_data)[1] <- c("Uniprot") colnames(final_data)[2] <- c("ProteinNames") colnames(final_data)[3] <- c("Symbol") filename_final_data <- readline('Enter a filename for final data= ') ##Create plotly object and save plot as html filename_mod <- readline('Enter a filename for limma plot= ') # filename_ord <- # readline('Enter a filename for ordinary t-test plot= ') # display_plotly_figs(final_data, FC_Cutoff, filename_mod, filename_ord) display_plotly_figs(final_data, FC_Cutoff, filename_mod) ## Write final data write.table( final_data, paste(filename_final_data, '.tsv', sep = ''), sep = '\t', row.names = FALSE, col.names = TRUE ) ## Write outliers in treatment write.table( outliers, paste(filename_outliers, '.tsv', sep = ''), sep = '\t', row.names = FALSE, col.names = TRUE ) ## Write outliers in control write.table( outliers_control, paste(filename_outliers_control, '.tsv', sep = ''), sep = '\t', row.names = FALSE, col.names = TRUE ) setwd(cur_dir)
f9764567b463f5354b76ef002822db1fba0361e3
afa997ac0246d2ede8e3fde18dc3ae780fa16d2f
/8kyu/litres.r
5876ad0a46bca7e20fc663e7ef83f7baabc57e12
[]
no_license
supvolume/codewars_solution_in_R
20fc2332afd5b33fd3e15ba716a1e54af955e761
1c3912e6b7c60ced07a9879405fad43ada5ba24a
refs/heads/master
2021-11-27T16:58:02.949777
2021-11-26T08:48:05
2021-11-26T08:48:05
169,952,519
1
0
null
null
null
null
UTF-8
R
false
false
99
r
litres.r
# solution for Keep Hydrated! challenge litres <- function(time) { return(as.integer(time*0.5)) }
d58f1f833c12d8b6a5a0f0b0473bce3d289ce808
ab38fcf1040a66038f81e2963d3ab96cc513a4df
/man/lpnet.Rd
22628f8581c3cd958e40fc6db696c306d5473c33
[]
no_license
yukimayuli-gmz/lpnet
a1d271864508886939ede89dac3d73d1d9d3a1f1
5cbb3af788c1a742e4448450efca1e1344d81f20
refs/heads/main
2023-04-19T04:50:32.524818
2022-02-17T18:20:03
2022-02-17T18:20:03
343,287,614
1
0
null
null
null
null
UTF-8
R
false
true
2,529
rd
lpnet.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lpnet.R \name{lpnet} \alias{lpnet} \title{Consruct a circular network based on a tree by Linear Programming} \usage{ lpnet( M, tree.method = "unj", lp.package = "Rglpk", lp.type = "B", filename = "lpnet.nex", taxaname = NULL ) } \arguments{ \item{M}{the distance matrix for construct tree and network (the matrix should fit the triangle inequality and the diagonal should be 0).} \item{tree.method}{method for construct the original tree for lp, default is \code{unj}, for unweighted ntighbor joining tree; \code{nj} for neighbor joining tree; \code{nnet} for symmetry nnet tree; \code{nnetns} for no symmetry nnet tree; \code{BioNJ} for BioNJ tree.} \item{lp.package}{which package will used for Linear Programming, default is \code{Rglpk}, for a free R package; \code{gurobi} for the gurobi package.} \item{lp.type}{a character vector indicating the types of the objective variables. default is \code{B} for binary; \code{I} for intrger; \code{C} for continuous; \code{NULL}, for ordinary.} \item{filename}{a character will be the naxus file's name, default is \code{lpnet.nex}.} \item{taxaname}{a character set of names for taxa, ordering is consist with original distance matrix \code{M}.} } \value{ The LSfit value. } \description{ Construct a planner network which has a circular ordering for a distance matrix, and write a nexus file for SplitsTree4. First construct a tree for the distance matrix.Then use Linear Programming(lp) to change the circular ordering. The ordering have the biggest sum of quartets for all taxa is the lp net ordering. Then use Non-negative least squares(nnls) to calculate weights of splits which are consist with the lp net ordering. Finally, return a LSfit which is the least squares fit between the pairwise distances in the graph and the pairwise distances in the matrix. And write a nexus file with taxa block and splits block for SplitsTree4 to see the circular network. } \examples{ ### From Huson and Bryant (2006, Fig 4): x <- c(14.06, 17.24, 20.5, 23.37, 17.43, 19.18, 18.48, 9.8, 13.06, 15.93, 15.65, 17.4, 16.7, 6.74, 16.87, 16.59, 18.34, 17.64, 17.57, 17.29, 19.04, 18.34, 17.6, 19.35, 21.21, 9.51, 11.37, 13.12) M <- matrix(0, 8, 8) M[row(M) > col(M)] <- x M <- M + t(M) taxaname <- c("A", "B", "C", "D", "E", "F", "G", "H") lpnet(M, tree.method = "nj", lp.package = "Rglpk", lp.type = "B", filename = "example.nex", taxaname = taxaname) }
21838bc23052db1f85d945de07e536f808b1a525
f256fd8f31ea589cae179c155f44b7e4f8de744a
/R/check_collinearity.R
163bfcc3d401005f4a9d0d19c7e9a87840471383
[]
no_license
cran/performance
9578b76fd8981e5896d25d036cb8439e8b01c24a
c44285dff9936445c56ec8b83feb7ff9cae3fa81
refs/heads/master
2023-06-08T08:42:02.230184
2023-06-02T10:30:02
2023-06-02T10:30:02
183,289,241
0
0
null
null
null
null
UTF-8
R
false
false
21,547
r
check_collinearity.R
#' @title Check for multicollinearity of model terms #' @name check_collinearity #' #' @description #' #' `check_collinearity()` checks regression models for #' multicollinearity by calculating the variance inflation factor (VIF). #' `multicollinearity()` is an alias for `check_collinearity()`. #' `check_concurvity()` is a wrapper around `mgcv::concurvity()`, and can be #' considered as a collinearity check for smooth terms in GAMs. Confidence #' intervals for VIF and tolerance are based on Marcoulides et al. #' (2019, Appendix B). #' #' @param x A model object (that should at least respond to `vcov()`, #' and if possible, also to `model.matrix()` - however, it also should #' work without `model.matrix()`). #' @param component For models with zero-inflation component, multicollinearity #' can be checked for the conditional model (count component, #' `component = "conditional"` or `component = "count"`), #' zero-inflation component (`component = "zero_inflated"` or #' `component = "zi"`) or both components (`component = "all"`). #' Following model-classes are currently supported: `hurdle`, #' `zeroinfl`, `zerocount`, `MixMod` and `glmmTMB`. #' @param ci Confidence Interval (CI) level for VIF and tolerance values. #' @param verbose Toggle off warnings or messages. #' @param ... Currently not used. #' #' @return A data frame with information about name of the model term, the #' variance inflation factor and associated confidence intervals, the factor #' by which the standard error is increased due to possible correlation #' with other terms, and tolerance values (including confidence intervals), #' where `tolerance = 1/vif`. #' #' @section Multicollinearity: #' Multicollinearity should not be confused with a raw strong correlation #' between predictors. What matters is the association between one or more #' predictor variables, *conditional on the other variables in the #' model*. In a nutshell, multicollinearity means that once you know the #' effect of one predictor, the value of knowing the other predictor is rather #' low. Thus, one of the predictors doesn't help much in terms of better #' understanding the model or predicting the outcome. As a consequence, if #' multicollinearity is a problem, the model seems to suggest that the #' predictors in question don't seems to be reliably associated with the #' outcome (low estimates, high standard errors), although these predictors #' actually are strongly associated with the outcome, i.e. indeed might have #' strong effect (_McElreath 2020, chapter 6.1_). #' #' Multicollinearity might arise when a third, unobserved variable has a causal #' effect on each of the two predictors that are associated with the outcome. #' In such cases, the actual relationship that matters would be the association #' between the unobserved variable and the outcome. #' #' Remember: "Pairwise correlations are not the problem. It is the conditional #' associations - not correlations - that matter." (_McElreath 2020, p. 169_) #' #' @section Interpretation of the Variance Inflation Factor: #' The variance inflation factor is a measure to analyze the magnitude of #' multicollinearity of model terms. A VIF less than 5 indicates a low #' correlation of that predictor with other predictors. A value between 5 and #' 10 indicates a moderate correlation, while VIF values larger than 10 are a #' sign for high, not tolerable correlation of model predictors (_James et al. #' 2013_). The *Increased SE* column in the output indicates how much larger #' the standard error is due to the association with other predictors #' conditional on the remaining variables in the model. Note that these #' thresholds, although commonly used, are also criticized for being too high. #' _Zuur et al. (2010)_ suggest using lower values, e.g. a VIF of 3 or larger #' may already no longer be considered as "low". #' #' @section Multicollinearity and Interaction Terms: #' If interaction terms are included in a model, high VIF values are expected. #' This portion of multicollinearity among the component terms of an #' interaction is also called "inessential ill-conditioning", which leads to #' inflated VIF values that are typically seen for models with interaction #' terms _(Francoeur 2013)_. #' #' @section Concurvity for Smooth Terms in Generalized Additive Models: #' `check_concurvity()` is a wrapper around `mgcv::concurvity()`, and can be #' considered as a collinearity check for smooth terms in GAMs."Concurvity #' occurs when some smooth term in a model could be approximated by one or more #' of the other smooth terms in the model." (see `?mgcv::concurvity`). #' `check_concurvity()` returns a column named _VIF_, which is the "worst" #' measure. While `mgcv::concurvity()` range between 0 and 1, the _VIF_ value #' is `1 / (1 - worst)`, to make interpretation comparable to classical VIF #' values, i.e. `1` indicates no problems, while higher values indicate #' increasing lack of identifiability. The _VIF proportion_ column equals the #' "estimate" column from `mgcv::concurvity()`, ranging from 0 (no problem) to #' 1 (total lack of identifiability). #' #' @references #' #' - Francoeur, R. B. (2013). Could Sequential Residual Centering Resolve #' Low Sensitivity in Moderated Regression? Simulations and Cancer Symptom #' Clusters. Open Journal of Statistics, 03(06), 24-44. #' #' - James, G., Witten, D., Hastie, T., and Tibshirani, R. (eds.). (2013). #' An introduction to statistical learning: with applications in R. New York: #' Springer. #' #' - Marcoulides, K. M., and Raykov, T. (2019). Evaluation of Variance #' Inflation Factors in Regression Models Using Latent Variable Modeling #' Methods. Educational and Psychological Measurement, 79(5), 874–882. #' #' - McElreath, R. (2020). Statistical rethinking: A Bayesian course with #' examples in R and Stan. 2nd edition. Chapman and Hall/CRC. #' #' - Vanhove, J. (2019). Collinearity isn't a disease that needs curing. #' [webpage](https://janhove.github.io/analysis/2019/09/11/collinearity) #' #' - Zuur AF, Ieno EN, Elphick CS. A protocol for data exploration to avoid #' common statistical problems: Data exploration. Methods in Ecology and #' Evolution (2010) 1:3–14. #' #' @family functions to check model assumptions and and assess model quality #' #' @note The code to compute the confidence intervals for the VIF and tolerance #' values was adapted from the Appendix B from the Marcoulides et al. paper. #' Thus, credits go to these authors the original algorithm. There is also #' a [`plot()`-method](https://easystats.github.io/see/articles/performance.html) #' implemented in the \href{https://easystats.github.io/see/}{\pkg{see}-package}. #' #' @examples #' m <- lm(mpg ~ wt + cyl + gear + disp, data = mtcars) #' check_collinearity(m) #' #' @examplesIf require("see") #' # plot results #' x <- check_collinearity(m) #' plot(x) #' @export check_collinearity <- function(x, ...) { UseMethod("check_collinearity") } #' @rdname check_collinearity #' @export multicollinearity <- check_collinearity # default ------------------------------ #' @rdname check_collinearity #' @export check_collinearity.default <- function(x, ci = 0.95, verbose = TRUE, ...) { # check for valid input .is_model_valid(x) .check_collinearity(x, component = "conditional", ci = ci, verbose = verbose) } # methods ------------------------------------------- #' @export print.check_collinearity <- function(x, ...) { insight::print_color("# Check for Multicollinearity\n", "blue") if ("Component" %in% colnames(x)) { comp <- split(x, x$Component) for (i in seq_along(comp)) { cat(paste0("\n* ", comp[[i]]$Component[1], " component:\n")) .print_collinearity(datawizard::data_remove(comp[[i]], "Component")) } } else { .print_collinearity(x) } invisible(x) } #' @export plot.check_collinearity <- function(x, ...) { insight::check_if_installed("see", "to plot collinearity-check") NextMethod() } .print_collinearity <- function(x) { vifs <- x$VIF low_vif <- which(vifs < 5) mid_vif <- which(vifs >= 5 & vifs < 10) high_vif <- which(vifs >= 10) all_vifs <- insight::compact_list(list(low_vif, mid_vif, high_vif)) # if we have no CIs, remove those columns x <- datawizard::remove_empty_columns(x) # format table for each "ViF" group - this ensures that CIs are properly formatted x <- insight::format_table(x) x <- datawizard::data_rename( x, pattern = "SE_factor", replacement = "Increased SE", verbose = FALSE ) if (length(low_vif)) { cat("\n") insight::print_color("Low Correlation\n\n", "green") print.data.frame(x[low_vif, ], row.names = FALSE) } if (length(mid_vif)) { cat("\n") insight::print_color("Moderate Correlation\n\n", "yellow") print.data.frame(x[mid_vif, ], row.names = FALSE) } if (length(high_vif)) { cat("\n") insight::print_color("High Correlation\n\n", "red") print.data.frame(x[high_vif, ], row.names = FALSE) } } # other classes ---------------------------------- #' @export check_collinearity.afex_aov <- function(x, verbose = TRUE, ...) { if (length(attr(x, "within")) == 0L) { return(check_collinearity(x$lm, verbose = verbose, ...)) } f <- insight::find_formula(x)[[1]] f <- Reduce(paste, deparse(f)) f <- sub("\\+\\s*Error\\(.*\\)$", "", f) f <- stats::as.formula(f) d <- insight::get_data(x, verbose = FALSE) is_num <- vapply(d, is.numeric, logical(1)) d[is_num] <- sapply(d[is_num], datawizard::center, simplify = TRUE) is_fac <- !is_num contrs <- lapply(is_fac, function(...) stats::contr.sum)[is_fac] if (verbose) { insight::format_alert( "All predictors have been centered (factors with `contr.sum()`, numerics with `scale()`)." ) } check_collinearity(suppressWarnings(stats::lm( formula = f, data = d, contrasts = contrs ))) } #' @export check_collinearity.BFBayesFactor <- function(x, verbose = TRUE, ...) { if (!insight::is_model(x)) { insight::format_error("Collinearity only applicable to regression models.") } f <- insight::find_formula(x)[[1]] d <- insight::get_data(x, verbose = FALSE) check_collinearity(stats::lm(f, d)) } # mfx models ------------------------------- #' @export check_collinearity.logitor <- function(x, ci = 0.95, verbose = TRUE, ...) { .check_collinearity(x$fit, component = "conditional", ci = ci, verbose = verbose) } #' @export check_collinearity.logitmfx <- check_collinearity.logitor #' @export check_collinearity.probitmfx <- check_collinearity.logitor #' @export check_collinearity.poissonirr <- check_collinearity.logitor #' @export check_collinearity.poissonmfx <- check_collinearity.logitor #' @export check_collinearity.negbinirr <- check_collinearity.logitor #' @export check_collinearity.negbinmfx <- check_collinearity.logitor #' @export check_collinearity.betaor <- check_collinearity.logitor #' @export check_collinearity.betamfx <- check_collinearity.logitor # zi-models ------------------------------------- #' @rdname check_collinearity #' @export check_collinearity.glmmTMB <- function(x, component = c("all", "conditional", "count", "zi", "zero_inflated"), ci = 0.95, verbose = TRUE, ...) { component <- match.arg(component) .check_collinearity_zi_model(x, component, ci = ci, verbose = verbose) } #' @export check_collinearity.MixMod <- function(x, component = c("all", "conditional", "count", "zi", "zero_inflated"), ci = 0.95, verbose = TRUE, ...) { component <- match.arg(component) .check_collinearity_zi_model(x, component, ci = ci, verbose = verbose) } #' @export check_collinearity.hurdle <- function(x, component = c("all", "conditional", "count", "zi", "zero_inflated"), ci = 0.95, verbose = verbose, ...) { component <- match.arg(component) .check_collinearity_zi_model(x, component, ci = ci, verbose = verbose) } #' @export check_collinearity.zeroinfl <- function(x, component = c("all", "conditional", "count", "zi", "zero_inflated"), ci = 0.95, verbose = verbose, ...) { component <- match.arg(component) .check_collinearity_zi_model(x, component, ci = ci, verbose = verbose) } #' @export check_collinearity.zerocount <- function(x, component = c("all", "conditional", "count", "zi", "zero_inflated"), ci = 0.95, verbose = verbose, ...) { component <- match.arg(component) .check_collinearity_zi_model(x, component, ci = ci, verbose = verbose) } # utilities --------------------------------- .check_collinearity_zi_model <- function(x, component, ci = 0.95, verbose = TRUE) { if (component == "count") component <- "conditional" if (component == "zi") component <- "zero_inflated" mi <- insight::model_info(x, verbose = FALSE) if (!mi$is_zero_inflated) component <- "conditional" if (component == "all") { cond <- .check_collinearity(x, "conditional", ci = ci, verbose = verbose) zi <- .check_collinearity(x, "zero_inflated", ci = ci, verbose = FALSE) if (is.null(cond) && is.null(zi)) { return(NULL) } if (is.null(cond)) { zi$Component <- "zero inflated" return(zi) } if (is.null(zi)) { cond$Component <- "conditional" return(cond) } # retrieve data for plotting dat_cond <- attr(cond, "data") dat_zi <- attr(zi, "data") ci_cond <- attr(cond, "CI") ci_zi <- attr(zi, "CI") # add component cond$Component <- "conditional" zi$Component <- "zero inflated" dat_cond$Component <- "conditional" dat_zi$Component <- "zero inflated" ci_cond$Component <- "conditional" ci_zi$Component <- "zero inflated" # create final data dat <- rbind(cond, zi) attr(dat, "data") <- rbind(dat_cond, dat_zi) attr(dat, "CI") <- rbind(ci_cond, ci_zi) dat } else { .check_collinearity(x, component, ci = ci, verbose = verbose) } } .check_collinearity <- function(x, component, ci = 0.95, verbose = TRUE) { v <- insight::get_varcov(x, component = component, verbose = FALSE) assign <- .term_assignments(x, component, verbose = verbose) # any assignment found? if (is.null(assign) || all(is.na(assign))) { if (verbose) { insight::format_alert( sprintf("Could not extract model terms for the %s component of the model.", component) ) } return(NULL) } # we have rank-deficiency here. remove NA columns from assignment if (isTRUE(attributes(v)$rank_deficient) && !is.null(attributes(v)$na_columns_index)) { assign <- assign[-attributes(v)$na_columns_index] if (isTRUE(verbose)) { insight::format_alert( "Model matrix is rank deficient. VIFs may not be sensible." ) } } # check for missing intercept if (insight::has_intercept(x)) { v <- v[-1, -1] assign <- assign[-1] } else { if (isTRUE(verbose)) { insight::format_alert("Model has no intercept. VIFs may not be sensible.") } } f <- insight::find_formula(x) if (inherits(x, "mixor")) { terms <- labels(x$terms) } else { terms <- labels(stats::terms(f[[component]])) } if ("instruments" %in% names(f)) { terms <- unique(c(terms, labels(stats::terms(f[["instruments"]])))) } n.terms <- length(terms) if (n.terms < 2) { if (isTRUE(verbose)) { insight::format_alert( sprintf("Not enough model terms in the %s part of the model to check for multicollinearity.", component) ) } return(NULL) } R <- stats::cov2cor(v) detR <- det(R) result <- vector("numeric") na_terms <- vector("numeric") for (term in 1:n.terms) { subs <- which(assign == term) if (length(subs)) { result <- c( result, det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs])) / detR ) } else { na_terms <- c(na_terms, term) } } # any terms to remove, due to rank deficiency? if (length(na_terms)) { terms <- terms[-na_terms] } # check for interactions, VIF might be inflated... if (!is.null(insight::find_interactions(x)) && any(result > 10) && isTRUE(verbose)) { insight::format_alert( "Model has interaction terms. VIFs might be inflated.", "You may check multicollinearity among predictors of a model without interaction terms." ) } # CIs, see Appendix B 10.1177/0013164418817803 r <- 1 - (1 / result) n <- insight::n_obs(x) p <- insight::n_parameters(x) # check if CIs are requested if (!is.null(ci) && !is.na(ci) && is.numeric(ci)) { ci_lvl <- (1 + ci) / 2 logis_r <- stats::qlogis(r) # see Raykov & Marcoulides (2011, ch. 7) for details. se <- sqrt((1 - r^2)^2 * (n - p - 1)^2 / ((n^2 - 1) * (n + 3))) se_log <- se / (r * (1 - r)) ci_log_lo <- logis_r - stats::qnorm(ci_lvl) * se_log ci_log_up <- logis_r + stats::qnorm(ci_lvl) * se_log ci_lo <- stats::plogis(ci_log_lo) ci_up <- stats::plogis(ci_log_up) } else { ci_lo <- ci_up <- NA } out <- insight::text_remove_backticks( data.frame( Term = terms, VIF = result, VIF_CI_low = 1 / (1 - ci_lo), VIF_CI_high = 1 / (1 - ci_up), SE_factor = sqrt(result), Tolerance = 1 / result, Tolerance_CI_low = 1 - ci_up, Tolerance_CI_high = 1 - ci_lo, stringsAsFactors = FALSE ), column = "Term" ) attr(out, "ci") <- ci attr(out, "data") <- insight::text_remove_backticks( data.frame( Term = terms, VIF = result, SE_factor = sqrt(result), stringsAsFactors = FALSE ), column = "Term" ) attr(out, "CI") <- data.frame( VIF_CI_low = 1 / (1 - ci_lo), VIF_CI_high = 1 / (1 - ci_up), Tolerance_CI_low = 1 - ci_up, Tolerance_CI_high = 1 - ci_lo, stringsAsFactors = FALSE ) class(out) <- c("check_collinearity", "see_check_collinearity", "data.frame") out } .term_assignments <- function(x, component, verbose = TRUE) { tryCatch( { if (inherits(x, c("hurdle", "zeroinfl", "zerocount"))) { assign <- switch(component, conditional = attr(insight::get_modelmatrix(x, model = "count"), "assign"), zero_inflated = attr(insight::get_modelmatrix(x, model = "zero"), "assign") ) } else if (inherits(x, "glmmTMB")) { assign <- switch(component, conditional = attr(insight::get_modelmatrix(x), "assign"), zero_inflated = .zi_term_assignment(x, component, verbose = verbose) ) } else if (inherits(x, "MixMod")) { assign <- switch(component, conditional = attr(insight::get_modelmatrix(x, type = "fixed"), "assign"), zero_inflated = attr(insight::get_modelmatrix(x, type = "zi_fixed"), "assign") ) } else { assign <- attr(insight::get_modelmatrix(x), "assign") } if (is.null(assign)) { assign <- .find_term_assignment(x, component, verbose = verbose) } assign }, error = function(e) { .find_term_assignment(x, component, verbose = verbose) } ) } .find_term_assignment <- function(x, component, verbose = TRUE) { pred <- insight::find_predictors(x)[[component]] if (is.null(pred)) { return(NULL) } dat <- insight::get_data(x, verbose = FALSE)[, pred, drop = FALSE] parms <- unlist(lapply(seq_along(pred), function(i) { p <- pred[i] if (is.factor(dat[[p]])) { ps <- paste0(p, levels(dat[[p]])) names(ps)[seq_along(ps)] <- i ps } else { names(p) <- i p } })) if (insight::is_gam_model(x)) { model_params <- as.vector(unlist(insight::find_parameters(x)[c(component, "smooth_terms")])) } else { model_params <- insight::find_parameters(x)[[component]] } as.numeric(names(parms)[match( insight::clean_names(model_params), parms )]) } .zi_term_assignment <- function(x, component = "zero_inflated", verbose = TRUE) { tryCatch( { rhs <- insight::find_formula(x)[[component]] d <- insight::get_data(x, verbose = FALSE) attr(insight::get_modelmatrix(rhs, data = d), "assign") }, error = function(e) { NULL } ) }
f016d45af91e02c9c900332fe90a551519a3522a
5db2dac679963587ac50ad850ea3a2ccb508465a
/phd-scripts/R/zeta_plot.R
575804f6dcd92b8239de7789259cd8f1a01b7996
[ "MIT" ]
permissive
softloud/simeta
be88fe336eeee9610086823adce839493781c0ef
2a7e979077c57812a7d29c3e23e8c00080e1cb03
refs/heads/master
2023-04-16T23:27:16.936986
2023-03-25T11:49:23
2023-03-25T11:49:23
200,359,586
2
2
NOASSERTION
2020-01-28T09:55:16
2019-08-03T09:56:12
HTML
UTF-8
R
false
false
1,525
r
zeta_plot.R
#' plot the distribution of the proportion allocated to the intervention group #' #' @family vis_tools #' @family reporting Functions and tools for reporting simulation results. #' #' @export zeta_plot <- function(mu, epsilon) { # check numeric args neet::assert_neet(mu, "numeric") neet::assert_neet(epsilon, "numeric") # check args are [0,1] assertthat::assert_that( mu > 0 & mu < 1, msg = "mu must be a value from [0,1].") assertthat::assert_that( epsilon > 0 & epsilon < 1, msg = "epsilon must be a value from [0,1].") # calculate parameters par <- beta_par(mu, epsilon) # return plot of beta distribution with parameters tibble(x = c(0, 1)) %>% ggplot(aes(x = x)) + geom_rect(xmin = mu - epsilon, xmax = mu + epsilon, ymin = 0, ymax = Inf, alpha = 0.2) + geom_vline(xintercept = mu, linetype = "dashed", alpha = 0.8) + stat_function(fun = dbeta, linetype = "dotted", args = list(shape1 = par$alpha, shape2 = par$beta)) + labs(title = str_wrap("Distribution of expected proportion of intervention cohort" ), x = TeX("$\\zeta$"), y = NULL, caption = str_wrap(paste0( "We assume a beta distribution with expected centre ", mu, " and 90% of values falling within ", epsilon, "; i.e, within the interval [", mu - epsilon, ",", mu + epsilon, "]"), width = 70)) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) }
f9ca07dcd19963980785a8e19f5ac735565975cd
5e67544bd977d277ea24050d1aafa1c9bed9cf86
/2-analysis/old/adoption.R
574966b90e8e35102c8ab9efc418e202775850ff
[]
no_license
balachia/Currency
8d08a1c11a6472e7b019c641afb64ad90c7e1b7b
ff46e4b042eb176cb7787ba524c52d21303cd5ce
refs/heads/master
2021-01-17T04:46:31.851629
2016-07-14T22:45:06
2016-07-14T22:45:06
15,240,711
0
0
null
null
null
null
UTF-8
R
false
false
8,994
r
adoption.R
# let's run an adoption model viz coxph # What do we need to do here? # Create a data set containing events by user/currency # split spells on ... # every day with observed friend or self returns? library(rms) library(survival) library(data.table) library(ffbase) library(reshape2) library(texreg) library(parallel) rm(list=ls()) qcuts <- function(x, qs) { cut(x, unique(quantile(x, qs, na.rm=TRUE)), labels=FALSE, include.lowest=TRUE) } collapse.to.spells <- function(dt, t.var, grp.vars, sort.vars, coll.vars) { dt.out <- data.table(dt) dt.out <- dt[do.call(order, dt[,c(grp.vars,sort.vars), with=FALSE])] dt.out[, nspell := FALSE] lapply(coll.vars, function (x) { dt.out[, nspell := nspell | (get(x) != c(NA, get(x)[1:(.N-1)])),by=grp.vars] 0 }) dt.out[is.na(nspell), nspell := TRUE] dt.out[,spellid := cumsum(nspell)] dt.out[, start := min(get(t.var)) - 1, by=spellid] dt.out[, stop := max(get(t.var)), by=spellid] # print(dt.out) # return(dt.out) dt.out <- dt.out[ dt.out[,.I[.N], by=spellid][,V1]] dt.out } poor.cem <- function(dt, keys, snames=NULL, qnames=NULL, bkeys=keys) { kdt <- dt[,c(keys,snames),with=FALSE] setkeyv(dt,keys) setkeyv(kdt,keys) print(kdt) # print(names(dt)) cat('making quantiles\n') lapply(qnames, function (x) { cat('processing ',x,'\n') kdt[,paste0(x,'_q') := qcuts(dt[,get(x)], seq(0,1,0.1))] NULL }) allnames <- c(snames, paste0(qnames,'_q')) cat('making groups\n') kdt[,grp := .GRP, by=allnames] ngrps <- kdt[,max(grp)] cat('# Groups:', ngrps, '\n') cat('balance statistics\n') cat('# observations\n') dat <- kdt[,.N,by=grp][,N] print(summary(dat)) print(quantile(dat,seq(0,1,0.1), na.rm=TRUE)) cat('\n') for(key in bkeys) { cat(key,':\n') # dat <- kdt[,dim(.SD[,.N,by=key])[1],by=grp][,V1] dat <- kdt[,length(unique(get(key))),by=grp][,V1] # try a parallel version... # dats <- mclapply(split(1:ngrps, factor(1:ngrps %% (64 * 2))), # mc.cores=64, mc.preschedule=FALSE, # function (subgrps) { # sub.dat <- kdt[grp %in% subgrps, length(unique(key)), by=grp][,V1] # sub.dat # }) # dat <- rbindlist(dats) # print(dats) # print(dat) print(summary(dat)) print(quantile(dat,seq(0,1,0.1), na.rm=TRUE)) cat('# == 1 ::', sum(dat==1), '(', sum(dat==1) / length(dat), '%)\n') cat('\n') } kdt[,c(keys,'grp'), with=FALSE] } if (grepl('.*stanford\\.edu',Sys.info()[['nodename']])) { DATA.DIR <- '/archive/gsb/vashevko/forex/' OUT.DIR <- '~/2YP/writing/' } else { DATA.DIR <- '~/Data/forex/' OUT.DIR <- '~/Dropbox/forex Project/writing/' } setwd(DATA.DIR) # load in data aus <- readRDS('./Rds/active-user-quantiles.Rds') dt <- readRDS('./Rds/day.stats-0-1samp.Rds') fpt <- readRDS('./Rds/forexposition.Rds') ffdfns <- load.ffdf('./ffdb/sbc') ffd <- ffdfns$ffd # put days in fpt stuff fpt[,openday := floor((opendate / 86400000.0) + 0.125)] fpt[,cp := paste0(currency1,currency2)] # get currency use frequency cps <- fpt[, list(cpN=.N), by=cp] cps <- cps[order(-cps$cpN)] cps[,rank:=.I] # merge in currency frequency # why? setkey(cps,cp) setkey(fpt,cp) fpt <- merge(fpt,cps,all.x=TRUE) uids <- aus[Npd_q %in% 2:5 & med_ob_q %in% 2:5 & dpnlpd_q %in% 2:5 & netdep_q %in% 2:5,user_id] # reduce users under consideration c.dt <- dt[user_id %in% uids] # pull out all adoption events g.min.day <- 1199145600000 / 86400000 all.adopt.es <- fpt[,list(adopt = min(openday)), by=list(user_id,cp)] # throw out each user's first day of currency # all.adopt.es <- all.adopt.es[order(user_id,adopt)] all.adopt.es[, valid := adopt > min(adopt), by=user_id] all.adopt.es <- all.adopt.es[(valid)] all.adopt.es <- all.adopt.es[adopt > g.min.day] all.adopt.es[,valid := NULL] # can we pull in the whole sbc database? only need results of single day... idx.1d <- ffwhich(ffd,gap==1) sbc.1d <- as.data.table(as.data.frame(ffd[idx.1d,])) print(object.size(sbc.1d), units='auto') # create time since last trade c.dt <- c.dt[order(user_id,day)] c.dt[, bopen := as.integer(opened_today > 0)] c.dt[, cumopen := cumsum(bopen) - bopen, by=user_id] c.dt[, dlapse := 1:.N, by=list(user_id,cumopen)] #c.dt[, dlapse := as.factor(dlapse)] c.dt[, c('imputed','bopen','cumopen') := NULL] # we should insert user's own stats here... sbc.1d <- sbc.1d[, c('gap','imputed','dpnl_sum','dpnl_mean','dpnl_pos','dpnl_neg') := NULL] sbc.e1d <- sbc.1d[type == 'ego'] sbc.a1d <- sbc.1d[type == 'alter'] # make 10 day lag for ego # make 14 day lag for alters sbc.a14 <- rbindlist(lapply(0:13, function (x) { res <- data.table(sbc.a1d) res[, src := day] res[, day := day + x] res })) sbc.e2 <- rbindlist(lapply(0:1, function (x) { res <- data.table(sbc.e1d) res[, src := day] res[, day := day + x] res })) sbc.e10 <- rbindlist(lapply(2:9, function (x) { res <- data.table(sbc.e1d) res[, src := day] res[, day := day + x] res })) # now collapse the fuckers sbc.a14 <- sbc.a14[, list(ntotal.alt = sum(ntotal), npos.alt = sum(npos), nneg.alt = sum(nneg) ), by=list(user_id, cp, day)] sbc.e2 <- sbc.e2[, list(ntotal.e2 = sum(ntotal), npos.e2 = sum(npos), nneg.e2 = sum(nneg) ), by=list(user_id, day)] sbc.e10 <- sbc.e10[, list(ntotal.e10 = sum(ntotal), npos.e10 = sum(npos), nneg.e10 = sum(nneg) ), by=list(user_id, day)] # sort the bastard setkey(sbc.a14, user_id, day) setkey(sbc.e2, user_id, day) setkey(sbc.e10, user_id, day) setkey(c.dt,user_id, day) c.dt <- merge(c.dt, sbc.e2, all.x=TRUE) c.dt <- merge(c.dt, sbc.e10, all.x=TRUE) c.dt[is.na(ntotal.e2), c('ntotal.e2', 'npos.e2', 'nneg.e2') := 0] c.dt[is.na(ntotal.e10), c('ntotal.e10', 'npos.e10', 'nneg.e10') := 0] # set up the users/currencies under observation cp.set <- all.adopt.es[,unique(cp)] # cp.set <- cp.set[1:4] # cp.set <- c('EURUSD','USDCZK') # cp.set <- cps[(rank - 1) %% 10 == 0, cp] # what do we need in the spell split? res <- mclapply(cp.set, mc.cores=60, mc.preschedule=FALSE, function (ccp) { print(ccp) # adopt.es <- fpt[cp == ccp, list(adopt=min(openday)), by=user_id] adopt.es <- all.adopt.es[cp == ccp] cp.rank <- cps[cp==ccp, rank] setkey(adopt.es,user_id) cp.dt <- merge(c.dt, adopt.es, all.x=TRUE) cp.dt <- cp.dt[is.na(adopt) | day <= adopt] cp.dt[, badopt := ifelse(day==adopt,1,0)] cp.dt[is.na(badopt), badopt := 0] cp.dt[, cp := ccp] cp.dt[, adopt := NULL] setkey(cp.dt, user_id, day) cp.dt <- merge(cp.dt, sbc.a14[cp == ccp, !'cp', with=FALSE], all.x=TRUE) cp.dt[is.na(ntotal.alt), c('ntotal.alt', 'npos.alt', 'nneg.alt') := 0] cp.dt[,rank := cp.rank] # cp.dt }) if(!file.exists('dta/adopts-m10.dta')) { cat('writing to stata\n') library(foreign) all.adopts <- rbindlist(res) print(object.size(all.adopts), units='auto') print(dim(all.adopts)) cat('starting write\n') write.dta(all.adopts, 'dta/adopts-m10.dta') cat('done with write\n') } # put day groups back in res <- lapply(res, function(x) { x[, dgrp := cumsum(opened_today>0) - (opened_today>0), by=user_id] x }) res2 <- mclapply(res, mc.cores=60, mc.preschedule=FALSE, function (cdt) { colldt <- collapse.to.spells(cdt, 'dlapse', c('user_id','cp'), 'day', coll.vars=c('ntotal.e2','ntotal.e10','ntotal.alt','dgrp')) colldt }) # saveRDS(res2, 'Rds/adopt.events.m10.Rds') saveRDS(res2, 'Rds/adopt.events.Rds') stop() stop() lapply(res, function (cpdt) { print(m.res <- clogit(badopt ~ ntotal.alt + strata(dlapse), data=cpdt)) 0 }) stop() stopifnot(FALSE) # assign user group aus <- aus[user_id %in% uids] aus[,ugrp := .GRP, by=list(nfriends_q,naccts_q,med_ob_q,netdep_q,Npd_q,dpnlpd_q)] # aus[,ugrp := .GRP, by=list(nfriends_q,naccts_q,med_ob_q,Npd_q,dpnlpd_q)] aus[,ugrpN := .N, by=ugrp] summary(aus[,.N,by=ugrp]) quantile(aus[,.N,by=ugrp][,N], seq(0,1,0.1)) # drop single user groups # uids <- aus[ugrpN > 1, user_id] uids <- aus[,user_id] # pull out user-restricted observations c.dt <- dt[user_id %in% uids] c.fpt <- fpt[user_id %in% uids] # preprocess c.dt stuff c.dt[,bopen:=as.integer(opened_today>0)] # merge in user statistics setkey(c.dt,user_id) setkey(aus,user_id) c.dt <- merge(c.dt,aus)
4fd2c388a19e7e3a237edacd3c7114b175d47838
1f10c23dcc48836a6f731a5dd3a1ba1279efd343
/R_scripts/3_fit_models.R
b3fa668dcf28667726fd47226066597dd9797aae
[ "CC-BY-2.0" ]
permissive
LeanaGooriah/ISAR_analysis
fcab2596754ca3ba7a75b7499ec749effaf94b2c
2827a402db297464ace5c29222f7bf735bcc007c
refs/heads/master
2021-07-15T02:44:43.837907
2020-05-31T22:24:44
2020-05-31T22:24:44
147,322,370
6
1
null
null
null
null
UTF-8
R
false
false
692
r
3_fit_models.R
library(tidyr) library(purrr) library(dplyr) library(broom) dat1 <- read.csv("ISAR_DATA/diversity_indices/allstudies_allscales_allindices.csv", stringsAsFactors = F) names(dat1) by_index <- dat1 %>% group_by(Study, Scale, index) %>% nest() by_index2 <- by_index %>% mutate(model = map(data, ~ lm(log(value) ~ log(Area), data = .)), Intercept = map_dbl(model, ~coef(.x)[1]), Slope = map_dbl(model, ~coef(.x)[2]), glance = map(model, glance) ) %>% unnest(glance) names(by_index2) by_index2a <- by_index2 %>% select(Study:r.squared, -model, -data, p.value) write.csv(by_index2a, "ISAR_DATA/results/Table_2.csv", row.names = FALSE)
7dc5a5425d33c2fd427c9d304f72075f9e33c339
4d2c711b308db9eeefd2faf1f13d4c5db3ab70b1
/plot1.R
b0e4ca019c5a70ec1fa13f01068e731cabd3b833
[]
no_license
kimhale/ExData_Plotting1
1ad185478180f4b969fb7093d92616ac2d9fcf48
53014e056de9524bc888444ff2368a9d9d271aa1
refs/heads/master
2020-03-23T02:11:07.152949
2018-07-14T22:41:53
2018-07-14T22:41:53
140,961,037
0
0
null
null
null
null
UTF-8
R
false
false
1,480
r
plot1.R
# Set working directory setwd("/Users/kimberlyhale/Documents/Coursera/DataScienceCert/C4_EDA/ExData_Plotting1") # Load packages library(data.table) # Download file if data doesn't exist if (!file.exists("data/household_power_consumption.txt")){ dir.create("data") fileURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(fileURL, destfile = "data/HouseholdPower.zip", method = "curl") #Unzip file zipF<- "data/HouseholdPower.zip" outDir<-"data" unzip(zipF,exdir=outDir) } # Read data into datatable dt <- fread("data/household_power_consumption.txt", na.strings = "?") # Check that data is as expected head(dt) summary(dt) # Turn Date into Date class and filter to just Feb 01-02 2007 dt$Date <- as.Date(dt$Date, format = "%d/%m/%Y") dt <- dt[(dt$Date >= as.Date("2007-02-01") & dt$Date <= as.Date("2007-02-02")), ] # Turn Date/Time into Date/Time instead of character dt$DateTime <- paste(dt$Date, dt$Time, sep = " ") dt$DateTime <- as.POSIXct(dt$DateTime, format = "%Y-%m-%d %H:%M:%S") # Check that data is as expected dt$DateTime[2] - dt$DateTime[1] head(dt$DateTime) # Create a histogram, change title, color, x-axis title # Save it to a PNG file, width of 480 pixels and height of 480 pixels, named plot1.png png(filename = 'plot1.png', width = 480, height = 480) hist(dt$Global_active_power, col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)") dev.off()
3dd29b0e9348838f15d725dff2952d512be0a7cb
7e1d6c1822045ee656a6a41c063631760466add3
/man/appendVerticalTab.Rd
113dd66ba17e586cb312a4e3dc34c7214f741149
[ "MIT" ]
permissive
jcheng5/shinyWidgets
c784a3c9e4da76c0c7f23e8362fe647044beb6d2
f17f91f6c2e38ee8d7c6be6484ccb474ebef6417
refs/heads/master
2020-04-29T18:20:46.195001
2019-03-18T16:10:00
2019-03-18T16:56:59
176,321,196
3
0
NOASSERTION
2019-03-18T15:59:35
2019-03-18T15:59:35
null
UTF-8
R
false
true
1,350
rd
appendVerticalTab.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/vertical-tab.R \name{appendVerticalTab} \alias{appendVerticalTab} \alias{removeVerticalTab} \alias{reorderVerticalTabs} \title{Mutate Vertical Tabset Panel} \usage{ appendVerticalTab(inputId, tab, session = shiny::getDefaultReactiveDomain()) removeVerticalTab(inputId, index, session = shiny::getDefaultReactiveDomain()) reorderVerticalTabs(inputId, newOrder, session = shiny::getDefaultReactiveDomain()) } \arguments{ \item{inputId}{The id of the \code{verticalTabsetPanel} object.} \item{tab}{The verticalTab to append.} \item{session}{The \code{session} object passed to function given to \code{shinyServer.}} \item{index}{The index of the the tab to remove.} \item{newOrder}{The new index order.} } \description{ Mutate Vertical Tabset Panel } \examples{ if (interactive()) { library(shiny) library(shinyWidgets) ui <- fluidPage( verticalTabsetPanel( verticalTabPanel("blaa","foo"), verticalTabPanel("yarp","bar"), id="hippi" ) ) server <- function(input, output, session) { appendVerticalTab("hippi", verticalTabPanel("bipi","long")) removeVerticalTab("hippi", 1) appendVerticalTab("hippi", verticalTabPanel("howdy","fair")) reorderVerticalTabs("hippi", c(3,2,1)) } # Run the application shinyApp(ui = ui, server = server) } }
f88419bd06c98c170a02b78d9937aff2a86fcd8d
83d7c5a5d018752961787e7ddaee30e005ab36aa
/man/bbx_pad.Rd
fab8f72bc6f95f6a186b0037aae8412c55bc4df3
[ "MIT" ]
permissive
dmi3kno/bbx
09f9997463987144b0c3a541ae96215598a96405
c805c50bc1ebbab04c035b80e4c5f835979d6f91
refs/heads/master
2022-06-22T03:44:02.044482
2020-05-07T08:22:31
2020-05-07T08:22:31
261,409,960
2
0
null
null
null
null
UTF-8
R
false
true
1,028
rd
bbx_pad.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/transform.R \name{bbx_pad_width} \alias{bbx_pad_width} \alias{bbx_pad_height} \title{Functions for padding bbx These functions can "pad" (increase size of) bbx} \usage{ bbx_pad_width(bbx, n = 1, word = NULL, side = "both") bbx_pad_height(bbx, n = 1, word = NULL, side = "both") } \arguments{ \item{bbx}{character vector of bounding boxes to pad} \item{n}{integer number of pixels to add. If a `word` is provided, `n` is interpreted as number of characters.} \item{word}{optional character vector of words contained in bbxes} \item{side}{"left", "right" (for `bbx_pad_width()`), "up", "down" (for `bbx_pad_height()`) or "both" which side to pad} } \value{ a vector of validated bbxes } \description{ Functions for padding bbx These functions can "pad" (increase size of) bbx } \examples{ bbx_pad_width("5 5 10 20", word="There") bbx_pad_width("5 5 10 20", 1) bbx_pad_height("5 5 10 20", word="There/nbe/ndragons") bbx_pad_height("5 5 10 20", 1) }
9a362c140c0f61805bf401a7c3c87046f4f53bd8
c9a0e70c007ab6f1f6495dbaef44258e18959f17
/climate_comp_plots_AGUV_GUV_IVT_AGU2020poster.R
a7eff26545bf9cc74904cd038cc65112062b70eb
[ "MIT" ]
permissive
LizCarter492/MW_P_STG
e51e10ef872222fbc644f6ca88836e48dd13cb8c
06701a69c29201eb717638baecd4ec1c0e25e88c
refs/heads/main
2023-03-06T18:34:00.191059
2021-02-20T01:11:07
2021-02-20T01:11:07
340,173,894
0
0
null
null
null
null
UTF-8
R
false
false
19,232
r
climate_comp_plots_AGUV_GUV_IVT_AGU2020poster.R
library(lubridate) library(ncdf4) library(fields) library(maps) library(maptools) library(raster) library(data.table) library(RColorBrewer) library(viridis) library(colorRamps) #setwd("D:/DELL_PHD/Box Sync/AFRI_Aexam/R scripts") source("filled.contour3.R") source("filled.legend.R") in_path<-("D:/DELL_PHD/E/NASH_subseasonal_prediction/") out_path<-("H:/MW_seasonal_warm_season_precip_forecast/") ###################################################### #Variable names:###################################### #gu: geostrophic u wind component #gv: geostrophic v wind component #agu: ageostrophic u wind component #agv: ageostrophic v wind component #p: precipitation #mdf: moisture flux divergence #ivt: integrated vapor transport #q: specific humidity #o: omega (surface lifting index) #z: geopotential height #h: sensible heat flux # #ltm prefix indicates long-term monthly mean ####################################################### ####################################################### #(u,v); (gu, gv); (agu, agv): load total, gesotrophic, and ageostrophic wind#### gUV<-nc_open(paste(in_path,"geos_uv_1000_600mB.nc", sep="")) gu<-ncvar_get(gUV, varid="u_g") gv<-ncvar_get(gUV, varid="v_g") nc_close(gUV) unc<-nc_open(paste(in_path,"uwnd.mon.mean.nc", sep="")) u<-ncvar_get(unc, varid="uwnd") u<-u[,,1:5,] nc_close(unc) vnc<-nc_open(paste(in_path,"vwnd.mon.mean.nc", sep="")) v<-ncvar_get(vnc, varid="vwnd") v<-v[,,1:5,] nc_close(vnc) agu<-u-gu agu<-apply(agu[,,1:4,1:840], c(1,2,4), mean) agv<-v-gv agv<-apply(agv[,,1:4,1:840], c(1,2,4), mean) gu<-apply(gu[,,1:4,1:840], c(1,2,4), mean) gv<-apply(gv[,,1:4,1:840], c(1,2,4), mean) u<-apply(u[,,1:4,1:840], c(1,2,4), mean) v<-apply(v[,,1:4,1:840], c(1,2,4), mean) ltmagu<-ltmagv<-ltmgu<-ltmgv<-ltmu<-ltmv<- array(NA, dim=c(dim(agu)[1:2],12)) mthi<-rep(1:12, length(1948:2017)) yeari<-rep(1948:2017, each=12) for(j in 1:12){ ltmagu[,,j]<-apply(agu[,,which(mthi==j)],c(1,2), mean) ltmagv[,,j]<-apply(agv[,,which(mthi==j)],c(1,2), mean) ltmgu[,,j]<-apply(gu[,,which(mthi==j)],c(1,2), mean) ltmgv[,,j]<-apply(gv[,,which(mthi==j)],c(1,2), mean) ltmu[,,j]<-apply(u[,,which(mthi==j)],c(1,2), mean) ltmv[,,j]<-apply(v[,,which(mthi==j)],c(1,2), mean) } #(P): load GPCC precipitation#### setwd(in_path) P.nc<-nc_open("precip.comb.v2018to2016-v6monitorafter.total.nc") plat<-ncvar_get(P.nc, "lat") plon<-ncvar_get(P.nc, "lon") ptime<-ncvar_get(P.nc, "time") ptime<-as.POSIXct("1800-01-01 00:00")+as.difftime(ptime,units="days") ptime<-as.Date(ptime, origin=as.Date("1800-01-01 00:00:0.0")) p<-ncvar_get(P.nc, "precip") p<-p[,,which(year(ptime)>=1948 & year(ptime)<2018)] nc_close(P.nc) #(z): load geopotential height##### setwd(in_path) Z.nc<-nc_open("hgt.mon.mean.nc") lat<-ncvar_get(Z.nc, "lat") lon<-ncvar_get(Z.nc, "lon") lev<-ncvar_get(Z.nc, "level") z<-ncvar_get(Z.nc, "hgt") time<-ncvar_get(Z.nc, "time") time<-as.POSIXct("1800-01-01 00:00")+as.difftime(time,units="hours") time<-as.Date(time, origin=as.Date("1800-01-01 00:00:0.0")) z<-z[,,,year(time)<2018] nc_close(Z.nc) ltmz<-array(NA, dim=c(dim(z)[1:3],12)) mthi<-rep(1:12, length(1948:2017)) yeari<-rep(1948:2017, each=12) for(j in 1:12){ ltmz[,,,j]<-apply(z[,,,which(mthi==j)],c(1,2,3), mean) } #(MFD): load moisture flux divergence#### MFD<-array(NA, dim=c(144, 73, 12*length(1948:2018))) mthi<-rep(1:12, length(1948:2017)) yeari<-rep(1948:2017, each=12) setwd(paste(in_path,"NCAR_NCEP_Daily_moisture_budget/", sep="")) for(g in (1948:2018)){ mfd.nc <- nc_open(paste("MFD_daily_", g, ".nc", sep="")) time<-ncvar_get(mfd.nc, varid="time") time<-as.POSIXct("1800-01-01 00:00")+as.difftime(time,units="hours") time<-as.Date(time, origin=as.Date("1800-01-01 00:00:0.0")) mfd<-ncvar_get(mfd.nc, "Div_UQVQ") nc_close(mfd.nc) mth<-month(time) for(j in 1:12){ MFD[,,which(mthi==j & yeari==g)]<-apply(mfd[,,mth==j], c(1,2), mean) } remove(mfd) } ltmMFD<-array(NA, dim=c(dim(MFD)[1:2],12)) for(j in 1:12){ ltmMFD[,,j]<-apply(MFD[,,which(mthi==j)],c(1,2), mean) } #(UQ, VQ, IVT): load integrated vapor transport#### UQ<-VQ<-IVT<-array(NA, dim=c(144, 73, 12*length(1948:2017))) mthi<-rep(1:12, length(1948:2017)) yeari<-rep(1948:2017, each=12) setwd(paste(in_path,"NCAR_NCEP_Daily_moisture_budget/", sep="")) for(g in (1948:2017)){ VINT.nc <- nc_open(paste("VINT_daily_", g, ".nc", sep="")) time<-ncvar_get(VINT.nc, varid="time") time<-as.POSIXct("1800-01-01 00:00")+as.difftime(time,units="hours") time<-as.Date(time, origin=as.Date("1800-01-01 00:00:0.0")) uq<-ncvar_get(VINT.nc, "UQ") vq<-ncvar_get(VINT.nc, "VQ") nc_close(VINT.nc) mth<-month(time) for(j in 1:12){ UQ[,,which(mthi==j & yeari==g)]<-apply(uq[,,mth==j], c(1,2), mean) VQ[,,which(mthi==j & yeari==g)]<-apply(vq[,,mth==j], c(1,2), mean) } remove(uq); remove(vq); remove(time); remove(mth) } IVT<-sqrt(UQ^2 + VQ^2) ltmUQ<-ltmVQ<-ltmIVT<-array(NA, dim=c(dim(MFD)[1:2],12)) for(j in 1:12){ ltmUQ[,,j]<-apply(UQ[,,which(mthi==j)],c(1,2), mean) ltmVQ[,,j]<-apply(VQ[,,which(mthi==j)],c(1,2), mean) ltmIVT[,,j]<-apply(IVT[,,which(mthi==j)],c(1,2), mean) } #(q): load specific humidity#### setwd(in_path) Q.nc<-nc_open("shum.mon.mean.nc") lat<-ncvar_get(Q.nc, "lat") lon<-ncvar_get(Q.nc, "lon") q<-ncvar_get(Q.nc, "shum") time<-ncvar_get(Q.nc, "time") time<-as.POSIXct("1800-01-01 00:00")+as.difftime(time,units="hours") time<-as.Date(time, origin=as.Date("1800-01-01 00:00:0.0")) q<-apply(q[,,1:4,year(time)<2018], c(1,2,4), mean) ltmq<-array(NA, dim=c(dim(q)[1:2],12)) for(j in 1:12){ ltmq[,,j]<-apply(q[,,which(mthi==j)],c(1,2), mean) } #(o): load omega#### setwd(in_path) O.nc<-nc_open("omega.mon.mean.nc") lat<-ncvar_get(O.nc, "lat") lon<-ncvar_get(O.nc, "lon") o<-ncvar_get(O.nc, "omega") time<-ncvar_get(O.nc, "time") time<-as.POSIXct("1800-01-01 00:00")+as.difftime(time,units="hours") time<-as.Date(time, origin=as.Date("1800-01-01 00:00:0.0")) o<-apply(o[,,1:4,year(time)<2018], c(1,2,4), mean) ltmo<-array(NA, dim=c(dim(o)[1:2],12)) for(j in 1:12){ ltmo[,,j]<-apply(o[,,which(mthi==j)],c(1,2), mean) } # ##################################################################################### #set map graphical parameters#### #map dimensions lat.min <- 10#min(lat) lat.max <- 75#max(lat) lon.min <- -132#min(lon-360) lon.max <- max(lon-360) lat.min.ar <- lat.min+1 lat.max.ar <- lat.max-1 lon.min.ar <- lon.min+1 lon.max.ar <- lon.max-1 lat_final <- rev(lat) lon_final <- lon - 360 keep1 <- which(lon_final>=lon.min & lon_final<=lon.max) keep2 <- which(lat_final>=lat.min & lat_final<=lat.max) lon_all <- rep(lon_final,length(lat_final)) lat_all <- sort(rep(lat_final,length(lon_final))) month_name<-format(ISOdate(2004,1:12,1),"%B") mth<-rep(1:12, length(1948:2017)) yr<-rep(1948:2017, each=12) #image size hgt<-500 wdt<-1600 p_c_df<-rbind(c(1),c(2),c(3), c(4), c(5), c(6), c(7), c(8), c(9), c(10), c(11), c(12)) lat.min <- 10#min(lat) lat.max <- 75#max(lat) lon.min <- -132#min(lon-360) lon.max <- max(lon-360) lat.min.ar <- lat.min+1 lat.max.ar <- lat.max-1 lon.min.ar <- lon.min+1 lon.max.ar <- lon.max-1 lat_final <- rev(lat) lon_final <- lon - 360 keep1 <- which(lon_final>=lon.min & lon_final<=lon.max) keep2 <- which(lat_final>=lat.min & lat_final<=lat.max) lon_all <- rep(lon_final,length(lat_final)) lat_all <- sort(rep(lat_final,length(lon_final))) month_name<-format(ISOdate(2004,1:12,1),"%B") mth<-rep(1:12, length(1948:2017)) yr<-rep(1948:2017, each=12) #image size hgt<-1500 #4 # wdt<-3200 #12.8 for(m in 1:12){ m_c<-p_c_df[m,] #mfd ltmUQ_sub<-apply(ltmUQ[,,m_c],c(1,2),mean) ltmUQ_sub<-t(ltmUQ_sub) ltmUQ_sub<-ltmUQ_sub[seq(dim(ltmUQ_sub)[1],1),] ltmVQ_sub<-apply(ltmVQ[,,m_c],c(1,2),mean) ltmVQ_sub<-t(ltmVQ_sub) ltmVQ_sub<-ltmVQ_sub[seq(dim(ltmVQ_sub)[1],1),] ltmmfd_sub<-apply(ltmMFD[,,m_c], c(1,2), mean)*30 ltmmfd_sub<-t(ltmmfd_sub) ltmmfd_sub<-ltmmfd_sub[seq(dim(ltmmfd_sub)[1],1),] #geo ltmz850_sub<-apply(ltmz[,,3,m_c],c(1,2),mean) ltmz850_sub<-t(ltmz850_sub) ltmz850_sub<-ltmz850_sub[seq(dim(ltmz850_sub)[1],1),] gu_sub<-apply(gu[,,which(mth %in% (m_c))],c(1,2), mean) gu_sub<-t(gu_sub) gu_sub<-gu_sub[seq(dim(gu_sub)[1],1),] gv_sub<-apply(gv[,,which(mth %in% (m_c))],c(1,2), mean) gv_sub<-t(gv_sub) gv_sub<-gv_sub[seq(dim(gv_sub)[1],1),] #ageo ltmo_sub<-apply(o[,,which (mth %in% m_c)], c(1,2), mean) ltmo_sub<-t(ltmo_sub) ltmo_sub<-ltmo_sub[seq(dim(ltmo_sub)[1],1),] agu_sub<-apply(agu[,,which(mth %in% (m_c))],c(1,2), mean) agu_sub<-t(agu_sub) agu_sub<-agu_sub[seq(dim(agu_sub)[1],1),] agv_sub<-apply(agv[,,which(mth %in% (m_c))],c(1,2), mean) agv_sub<-t(agv_sub) agv_sub<-agv_sub[seq(dim(agv_sub)[1],1),] png(paste("H:/Research/MW_ClimateChange/images/climatological maps/", month_name[m_c[1]],"_", month_name[m_c[2]],"climatologyREVISED.png",sep=""), res=300, #pointsize=15, type="cairo", width=wdt, height=hgt, ) par(mfrow=c(1,2)) #geo uua<-as.vector(t(gu_sub)) vva<-as.vector(t(gv_sub)) uu<-uua vv<-vva speed <- sqrt(uu*uu+ vv*vv) speeda <- sqrt(uua*uua + vva*vva) uv <-which(speed>speeda & (1:length(uu))%in%seq(2,length(uu),by=4)) uvall<-which(speed<=speeda & (1:length(uu))%in%seq(2,length(uu),by=4)) mylevel<-c(1200, seq(1400, 1600, by=5), 1700) mycol<-topo.colors(length(mylevel)+1) mnm<-c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")[m] filled.contour3(lon_final,lat_final,t(ltmz850_sub), xlim=c(lon.min,lon.max), ylim=c(lat.min,lat.max), level=mylevel, col=mycol, #frame.plot=FALSE, main=title(mnm,cex.main=3), plot.axes={ axis(1, labels=FALSE, tick=FALSE); axis(2, labels=FALSE, tick=FALSE); if(m %in% 4:9){ arrow.plot(a1=lon_all[uv],a2=lat_all[uv],u=uua[uv],v=vva[uv],arrow.ex=0.5,length=0.06,xpd=FALSE, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="gray40"); arrow.plot(a1=lon_all[uvall],a2=lat_all[uvall],u=uua[uvall],v=vva[uvall],arrow.ex=0.5,length=0.06,xpd=FALSE, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="gray40"); }else{ arrow.plot(a1=lon_all[uv],a2=lat_all[uv],u=uua[uv],v=vva[uv],arrow.ex=0.5,length=0.06,xpd=FALSE, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="gray40"); arrow.plot(a1=lon_all[uvall],a2=lat_all[uvall],u=uua[uvall],v=vva[uvall],arrow.ex=0.5,length=0.06,xpd=FALSE, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="gray40"); } if(m_c[1]<5){ contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1480, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1420, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1540, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub),lwd=1,lty=1, levels=c(1440,1500,1520,1540, 1560), xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max),add=TRUE); }else if(m_c[1]<6) { contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1480, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1420, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1540, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1500, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1440, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub),lwd=1,lty=1, levels=c(1440,1500,1520,1540, 1560), xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max),add=TRUE); }else{ contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1480, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1420, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1540, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1510, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1460, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub), levels=1560, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=4,lty=1, add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmz850_sub),lwd=1,lty=1, levels=c(1440,1500,1520,1540), xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), add=TRUE); } map("world",add=T, lwd=3); } ) # #ageo # uua<-as.vector(t(agu_sub)) # vva<-as.vector(t(agv_sub)) # uu<-uua # uua[uu>quantile(uu, 0.99, na.rm=T)]<-NA#quantile(uu, 0.95, na.rm=T) # #uua[uu<quantile(uu, 0.01, na.rm=T)]<-NA#quantile(uu, 0.05, na.rm=T) # vv<-vva # vva[vva>quantile(vv, 0.99, na.rm=T)]<-NA#quantile(vva, 0.95, na.rm=T) # #vva[vv<quantile(vv, 0.05, na.rm=T)]<-NA#quantile(vv, 0.05, na.rm=T) # #uua<-ifelse(uua>=0, sqrt(abs(uua)), -1*sqrt(abs(uua))) # #vva<-ifelse(vva>=0, sqrt(abs(vva)), -1*sqrt(abs(vva))) # speed <- sqrt(uua*uua+ vva*vva) # speeda <- sqrt(uua*uua + vva*vva) # uv <-which(speed>speeda & (1:length(uu))%in%seq(1,length(uu),by=2)) # uvall<-which(speed<=speeda & (1:length(uu))%in%seq(1,length(uu),by=2)) # # mylevel<-c(-0.2, seq(-0.02, 0.02, by=0.001), 0.5) # mycol<-cm.colors(length(mylevel)+1) # # filled.contour3(lon_final,lat_final,t(ltmo_sub), # xlim=c(lon.min,lon.max), # ylim=c(lat.min,lat.max), # level=mylevel, # col=mycol, # main=title(mnm,cex.main=3), # plot.axes={ # axis(1, labels=FALSE, tick=FALSE); # axis(2, labels=FALSE, tick=FALSE); # arrow.plot(a1=lon_all[uv],a2=lat_all[uv],u=uua[uv],v=vva[uv],arrow.ex=0.5,length=0.06,xpd=FALSE, # xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="gray40"); # arrow.plot(a1=lon_all[uvall],a2=lat_all[uvall],u=uua[uvall],v=vva[uvall],arrow.ex=0.5,length=0.06,xpd=FALSE, # xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="gray40"); # contour(x=lon_final, y=lat_final, z=t(ltmo_sub), levels=c(0.008), # xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=2,lty=1, col="black",add=TRUE); # contour(x=lon_final, y=lat_final, z=t(ltmo_sub), levels= c(-0.008),lty=2, # xlim=c(lon.min,lon.max),ylim=c(lat.min+5,lat.max), lwd=2, col="black",add=TRUE); # # map("world",add=T, lwd=3); # } # # ) #mfd library(colorRamps) mylevel<-c(-7, seq(-3, 3, by=0.1), 10) mycol<-rev(matlab.like(length(mylevel)+1)) uua<-as.vector(t(ltmUQ_sub)) vva<-as.vector(t(ltmVQ_sub)) #uua<-ifelse(uua>=0, sqrt(abs(uua)), -1*sqrt(abs(uua))) #vva<-ifelse(vva>=0, sqrt(abs(vva)), -1*sqrt(abs(vva))) uvall<-which((1:length(uua))%in%seq(1,length(uua),by=3)) filled.contour3(lon_final,lat_final,t(ltmmfd_sub), xlim=c(lon.min,lon.max), ylim=c(lat.min,lat.max), level=mylevel, col=mycol, #frame.plot=FALSE, key.title=title(main=paste(j, k, sep=" "),cex=2), plot.axes={ axis(1, labels=FALSE, tick=FALSE); axis(2, labels=FALSE, tick=FALSE); arrow.plot(a1=lon_all[uvall],a2=lat_all[uvall],u=uua[uvall],v=vva[uvall],arrow.ex=0.4,length=0.06,xpd=FALSE, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="grey40"); contour(x=lon_final, y=lat_final, z=t(ltmmfd_sub), levels= c(-1.5),lty=2, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="black",add=TRUE); contour(x=lon_final, y=lat_final, z=t(ltmmfd_sub), levels= c(1.5),lty=1, xlim=c(lon.min,lon.max),ylim=c(lat.min,lat.max), lwd=3, col="black",add=TRUE); map("world",add=T, lwd=3); } ) dev.off() }
fdd28f2ca586a74ae6acf749263d5fe263120948
b75b290b2dd161e4c850858ecf7abee486bdede8
/man/calc_cgp.Rd
7589849018715d0f17fccd34f387a42f88fc3405
[]
no_license
rabare/mapvizieR
7d7bffb8691f6045e678d822f9e461e748038cd3
1a344ec1376ee41e85dcda0407f8bc63cfb95a82
refs/heads/master
2020-12-25T16:14:33.669385
2015-07-14T21:24:27
2015-07-14T21:24:27
null
0
0
null
null
null
null
UTF-8
R
false
false
930
rd
calc_cgp.Rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/cgp_prep.R \name{calc_cgp} \alias{calc_cgp} \title{calc_cgp} \usage{ calc_cgp(measurementscale, grade, growth_window, baseline_avg_rit = NA, ending_avg_rit = NA, sch_growth_study = sch_growth_norms_2012, calc_for = c(1:99)) } \arguments{ \item{measurementscale}{MAP subject} \item{grade}{baseline/starting grad for the group of students} \item{growth_window}{desired growth window for targets (fall/spring, spring/spring, fall/fall)} \item{baseline_avg_rit}{the baseline mean rit for the group of students} \item{ending_avg_rit}{the baseline mean rit for the group of students} \item{sch_growth_study}{a school growth study to use. default is sch_growth_norms_2012} \item{calc_for}{vector of cgp targets to calculate for.} } \value{ a named list - targets, and results } \description{ calculates both cgp targets and cgp results. }
6c7f8064efec1b49029180adb0f75d1594ae282d
2171f3867747a89929b1ad396afb855b09896309
/man/yan_2013.Rd
832f7396b51bb9b54906ccc61faac0d2f994aa83
[ "MIT" ]
permissive
aelhossiny/rDeepMAPS
4c1a0a0bcdad4bf6240984b9a47da55250c1fa8e
ec6b742f9f42dc4f1a40a392ddfe8d3610ab9e63
refs/heads/master
2023-06-09T20:02:19.866887
2021-07-07T02:56:57
2021-07-07T02:56:57
null
0
0
null
null
null
null
UTF-8
R
false
true
504
rd
yan_2013.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{yan_2013} \alias{yan_2013} \title{Data of yan_2013} \format{ A list with expression matrix and metadata: $meta: \describe{ \item{$expr}{a data frame with 20214 genes (rows) amd 90 cells (columns)} \item{$meta$Cluster}{fct cell type} } } \source{ \url{https://www.nature.com/articles/nsmb.2660} } \usage{ yan_2013 } \description{ Yan 2013: Human embryo, 7 cell types, 90 cells } \keyword{datasets}
215ba762b7cc4a8e6ab9bc81badb0841c5fe9406
b54ab392f5b31b6d665521d7f32d9b77ccae8728
/aprioritestingCosmetics.R
9f428d5a243942c07d466365d65feb820d52063c
[]
no_license
snehavishwanatha/Apriori_on_Cosmetics_Dataset
59cd97bdf5600e5a52b479faf165b7adbf5a88b9
dd145ddc4e5c1487fdbc368d31ab864df4d0652c
refs/heads/master
2020-05-15T21:45:01.909665
2019-04-23T07:12:51
2019-04-23T07:12:51
182,508,244
0
0
null
null
null
null
UTF-8
R
false
false
3,272
r
aprioritestingCosmetics.R
library(arules) library(arulesViz) library(RColorBrewer) f=file.choose() f1=read.csv(f) #summarizing data data<-f1 #data=na.omit(f1) head(data,n=10) str(data) summary(data) #inspecting rules rules<-apriori(data,parameter=list(supp=0.5,conf=0.8,target="rules")) rules.sorted <-sort(rules, by="confidence") rules <- rules.sorted[!is.redundant(rules)] summary(rules) inspect(rules) #item frequency histogram rules<-apriori(data,parameter=list(supp=0.5,conf=0.8,target="rules")) itemFrequencyPlot(items(rules),topN=13,col=brewer.pal(8,'Pastel2'), main='Relative Item Frequency Plot',type="relative",ylab="Item Frequency (Relative)") #graphical understanding plot(rules[1:25],method = "graph",cex=0.7,main="Graphical representation for 25 rules") #reporting the client in layman terms sink("cosmeticsreport.txt") suppyes=vector() supportyes=vector() suppno=vector() supportno=vector() for(q in 1:ncol(data)) { suppyes[q]=0 suppno[q]=0 } #suppyes #suppno for(i in 1:ncol(data)) { for(j in 1:nrow(data)) { if(data[j,i]=="No") suppno[i]=suppno[i]+1 if(data[j,i]=="Yes") suppyes[i]=suppyes[i]+1 } supportyes[i]=suppyes[i]/nrow(data) supportno[i]=suppno[i]/nrow(data) if(supportyes[i]>0.5) print(paste("Probability of the product ",colnames(data[i])," being purchased is ",supportyes[i]*100,"%")) } #suppno #supportno #suppyes #supportyes op=vector() sop=vector() for(l in 1:ncol(data[,-1])) { s=l+1 for(k in s:ncol(data)) { if(l!=k) { for(opq in 1:4) op[opq]=0 for(j in 1:nrow(data)) { if(data[j,l]=="No"&&data[j,k]=="No") { op[1]=op[1]+1 } else if(data[j,l]=="Yes"&&data[j,k]=="No") { op[2]=op[2]+1 } else if(data[j,l]=="No"&&data[j,k]=="Yes") { op[3]=op[3]+1 } else op[4]=op[4]+1 } sop=op for(b in 1:4) { if(op[b]!=0) op[b]=op[b]/nrow(data) } if(sop[4]!=0&&op[4]>0.5&&suppyes[l]!=0) { sop[4]=sop[4]/suppyes[l] print(paste(" The probability that purchase of ",colnames(data[l])," influences the purchase of ",colnames(data[k])," when placed on the same aisle is")) print(paste(sop[4]*100,"%")) } } } } op=vector() sop=vector() for(l in ncol(data[,-1]):2) { s=l-1 for(k in s:ncol(data)) { if(l!=k) { for(opq in 1:4) op[opq]=0 for(j in 1:nrow(data)) { if(data[j,l]=="No"&&data[j,k]=="No") { op[1]=op[1]+1 } else if(data[j,l]=="Yes"&&data[j,k]=="No") { op[2]=op[2]+1 } else if(data[j,l]=="No"&&data[j,k]=="Yes") { op[3]=op[3]+1 } else op[4]=op[4]+1 } sop=op for(b in 1:4) { if(op[b]!=0) op[b]=op[b]/nrow(data) } if(sop[4]!=0&&op[4]>0.6&&suppyes[l]!=0) { sop[4]=sop[4]/suppyes[l] print(paste(" The probability that purcahse of ",colnames(data[l])," influences the purchase of ",colnames(data[k])," when placed on the same aisle is")) print(paste(sop[4]*100," %")) } } } } sink()
eef2d94954c515dd5df756cec2f12b4c4fd722dc
8c07cac2a097b87ab88301826126271165bdd261
/november/data/nadieh/Step 1 - Get the top 100 Fantasy authors from Amazon.R
8bfe38970bd69a1b6fde013c0a10793e220212aa
[]
no_license
Minotaur-zx/datasketches-gh-pages
d53dc7e7d3afac9e0a279eb95cb44463c69950f1
b63dcef736d67a52da69d70092f5eb25be4e8fb5
refs/heads/master
2022-12-31T08:06:05.991245
2020-10-23T05:35:06
2020-10-23T05:35:06
306,538,550
0
0
null
null
null
null
UTF-8
R
false
false
1,093
r
Step 1 - Get the top 100 Fantasy authors from Amazon.R
#Get the top 100 fantasy authors from Amazon #Taken on November 7th, 2016 at 13:24 Amsterdam time #Web scraper explanation #https://blog.rstudio.org/2014/11/24/rvest-easy-web-scraping-with-r/ library(rvest) library(stringr) library(tidyr) #https://www.amazon.com/author-rank/Fantasy/books/16190/ref=kar_mr_pg_1?_encoding=UTF8&pg=1 #https://www.amazon.com/author-rank/Fantasy/books/16190/ref=kar_mr_pg_1?_encoding=UTF8&pg=2 numPages <- 10 authorList <- NULL for(i in 1:numPages) { url <- paste('https://www.amazon.com/author-rank/Fantasy/books/16190/ref=kar_mr_pg_1?_encoding=UTF8&pg=',i,sep="") webpage <- read_html(url) #Get the names of the authors #Used http://selectorgadget.com/ to figure out how to grab a hold of the author's name authorListPage <- webpage %>% html_nodes(".kar_authorName") %>% html_text() authorList <- append(authorList, authorListPage) }#for i #save the list authorListDF <- data.frame(rank = 1:length(authorList), author = authorList, stringsAsFactors = F) write.csv(authorListDF, file="top100FantasyAuthorsAmazon.csv", row.names = F)
26abe9f81a64e8c4bcd8f7696660a6d584701f9f
a8b27b2a52ed577253ecc30b969ee8f4d5b0dca3
/man/opchar_admissable.Rd
629134e020523462c65f0786d20e6582a9d67964
[]
no_license
mjg211/singlearm
51d2a0c3141ef4861a0156e0b29d57c23815100b
ad0c23a7780b902b1d5028915b8948d208999ba6
refs/heads/master
2021-06-03T14:25:29.390692
2021-05-04T14:57:48
2021-05-04T14:57:48
133,361,647
0
1
null
null
null
null
UTF-8
R
false
true
2,486
rd
opchar_admissable.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/opchar_admissable.R \name{opchar_admissable} \alias{opchar_admissable} \title{Determine the operating characteristics of admissable group sequential single-arm trial designs for a single binary endpoint} \usage{ opchar_admissable(des, k, pi, summary = F) } \arguments{ \item{des}{An object of class \code{"sa_des_admissable"}, as returned by \code{des_admissable()}.} \item{k}{Calculations are performed conditional on the trial stopping in one of the stages listed in vector \code{k}. Thus, \code{k} should be a vector of integers, with elements between one and the maximal number of possible stages in the supplied designs. If left unspecified, it will internally default to all possible stages.} \item{pi}{A vector of response probabilities to evaluate operating characteristics at. This will internally default to be the \ifelse{html}{\out{<i>&pi;</i><sub>0</sub>}}{\deqn{\pi_0}} and \ifelse{html}{\out{<i>&pi;</i><sub>1</sub>}}{\deqn{\pi_1}} from the supplied designs if it is left unspecified.} \item{summary}{A logical variable indicating whether a summary of the unction's progress should be printed to the console.} } \value{ A list of class \code{"sa_opchar_admissable"} containing the following elements \itemize{ \item A tibble in the slot \code{$opchar} summarising the operating characteristics of the supplied designs. \item Each of the input variables as specified, subject to internal modification. } } \description{ \code{opchar_admissable()} supports the evaluation of the operating characteristics of admissable group sequential single-arm clinical trial designs for a single binary primary endpoint, determined using \code{des_admissable()}. } \details{ For each value of \ifelse{html}{\out{<i>pi</i>}}{\eqn{\pi}} in the supplied vector \ifelse{html}{\out{<b><i>pi</i></b>}}{\eqn{\bold{\pi}}}, \code{opchar_admissable()} evaluates the power, ESS, and other key characteristics, of each of the supplied designs. Calculations are performed conditional on the trial stopping in one of the stages specified using the input (vector) \code{k}. } \examples{ # Find the admissable two-stage design for the default parameters des <- des_admissable() # Determine operating characteristics for a range of response probabilities opchar <- opchar_admissable(des, pi = seq(0, 1, 0.01)) } \seealso{ \code{\link{des_admissable}}, and their associated \code{plot} family of functions. }
cc14e1cf8319f8a967c45ffb049e2f54c126321b
4c671b09b63895596debc68f8a1eee4de7507356
/1_Names_Load Data Functions.R
17f53331e930c06952424ca882fb3f2133a35ce9
[]
no_license
ryantimpe/Kerasaurs
80782e631f4a5df29895348bc840da9c9ebdfdfa
c289e61ce2d2da7bdee437ffd7cd622681e581c5
refs/heads/master
2021-05-03T23:22:23.042740
2018-12-13T21:51:51
2018-12-13T21:51:51
120,399,442
8
0
null
null
null
null
UTF-8
R
false
false
1,703
r
1_Names_Load Data Functions.R
#this file loads the packages and creates the functions that will be used in the model require(readr) require(stringr) require(dplyr) require(purrr) require(tokenizers) require(keras) # This function loads the raw text of the _saurs get_saurs <- function() { readRDS("data/list_of_extinct_reptiles.RDS") %>% str_replace_all("[^[:alnum:] ]", "") %>% # remove any special characters tolower } add_stop <- function(saurs, symbol="+") { str_c(saurs, symbol) } # make a note for the end of a _saur name # We want to predict each of the n character on the _saur name. Have to split one # data point into n data points (where n is the number of characters on the plate). # So _saur ABC would become data points "A", "AB", and "ABC" split_into_subs <- function(saurs){ saurs %>% tokenize_characters(lowercase=FALSE) %>% map(function(saur) map(1:length(saur),function(i) saur[1:i])) %>% flatten() } # make each data point the same number of characters by # adding a padding symbol * to the font fill_data <- function(saur_characters, max_length = 20){ saur_characters %>% map(function(s){ if (max_length+1 > length(s)) { fill <- rep("*", max_length+1 - length(s)) c(fill, s) } else { s } }) } # convert the data into vectors that can be used by keras vectorize <- function(data,characters, max_length){ x <- array(0, dim = c(length(data), max_length, length(characters))) y <- array(0, dim = c(length(data), length(characters))) for(i in 1:length(data)){ for(j in 1:(max_length)){ x[i,j,which(characters==data[[i]][j])] <- 1 } y[i,which(characters==data[[i]][max_length+1])] <- 1 } list(y=y,x=x) }
83bbbbd00c095f9d751b7f0e90199a1583281456
5e968d1fa5ae2f0b3f15693561d61571a0b27a77
/R Code/Producemobile Time Series Analysis/producemobile_tsa.r
c9087445dccea46c37fb7e7718ba6db32ad373e7
[]
no_license
adityagi1/everybody-eats-summer-2020
a4dadce45728122f046c926bbdfcbb96b85f2e5c
fbd17660736eae447a447bbb594bd1dea19e8da9
refs/heads/master
2022-12-28T22:06:29.840546
2020-10-20T02:50:39
2020-10-20T02:50:39
305,567,747
0
0
null
null
null
null
UTF-8
R
false
false
4,331
r
producemobile_tsa.r
library(tidyverse) library(readxl) library(lubridate) library(imputeTS) pm = read_excel("../../Data/ProduceMobile/Producemobile_historical_data_clean.xlsx", sheet = "Sheet1") #rename column names names(pm) = c("date", "in_out", "amt_food_received","num_guests_signed_in", "num_individuals_served", "truck_arrival_time","num_volunteers", "leftover_pickup","num_boxes_pickup", "num_boxes_waste","note") #form food received time series (has missing values) amt_food_rec.ts = ts(pm$amt_food_received, frequency = 12) plot(amt_food_rec.ts) #form num individuals served time series (has missing values) num_ind.ts = ts(pm$num_individuals_served, frequency = 12) plot(num_ind.ts) #form the num volunteers time series (has missing values) num_volunteers.ts = ts(pm$num_volunteers, frequency = 12) plot(num_volunteers.ts) #num_ind, amt_food_rec, num_volunteers have na's that will need to be imputed num_ind.ts.imp = na_seadec(num_ind.ts, algorithm = "interpolation") plot(num_ind.ts.imp) ggplot_na_imputations(num_ind.ts, num_ind.ts.imp) #amount food received amt_food_rec.ts.imp = na_seadec(amt_food_rec.ts, algorithm = "interpolation") plot(amt_food_rec.ts.imp) ggplot_na_imputations(amt_food_rec.ts, amt_food_rec.ts.imp) #num_volunteers num_volunteers.ts.imp = na_seadec(num_volunteers.ts, algorithm = "interpolation") ggplot_na_imputations(num_volunteers.ts, num_volunteers.ts.imp) #####Autocorrelation plots to check seasonality #use smoothed data (using ma) as a preliminary estimate of the trend num_ind.ts.ma = ma(num_ind.ts.imp, order = 12, centre = TRUE) amt_food.ts.ma = ma(amt_food_rec.ts.imp, order = 12, centre = TRUE) num_volunteers.ts.ma = ma(num_volunteers.ts.imp, order = 12, centre = TRUE) #now compute the autocorr function of the de-trended data acf(na_remove(num_ind.ts.imp - num_ind.ts.ma)) acf(na_remove(amt_food_rec.ts.imp - amt_food.ts.ma)) acf(na_remove(num_volunteers.ts.imp - num_volunteers.ts.ma)) #there are strong auto-correlations (nearing 0.4-0.5), #indicating seasonality is present ######Time Series Decomposition num_ind.decomp = decompose(num_ind.ts.imp, type = "additive") num_volunteers.decomp = decompose(num_volunteers.ts.imp, type = "additive") amt_food_rec.decomp = decompose(amt_food_rec.ts.imp, type = "additive") #visualize decompositions plot(num_ind.decomp)#, main = "Num. Individuals Decomposition") plot(num_volunteers.decomp) #main = "Num. Volunteers Attending Decomposition") plot(amt_food_rec.decomp)# main = "Amount food received Decomposition") #there are strong seasonal and trend components, therefore it makes sense #to use a holt-winters model ######MODELLING num_ind.hw.mod = HoltWinters(num_ind.ts.imp, seasonal = "additive") amt_food_rec.hw.mod = HoltWinters(amt_food_rec.ts.imp, seasonal = "additive") num_volunteers.hw.mod = HoltWinters(num_volunteers.ts.imp, seasonal = "additive") # let's look at summaries for the model num_ind.hw.mod amt_food_rec.hw.mod num_volunteers.hw.mod #####INTERPRETATIONS #a very strong trend detected because beta = 0 for all three time series ##interpretations for seasonality ###NUM_IND_SERVED #fewer individuals are served during: #- Jan #- Feb #- April #- october #- december #more individuals are served during: #- march #- may #- september #- november ### AMT_FOOD_RECEIVED #lesser food is received during #- february #- april #- june #- october #- december #more food is received during: #january, #march, #may, #july, #september, #november #more volunteers tend to come in: #january #february #march #april #september #november #less volunteers tend to come in: #may #june #july #august #october #december ######PREDICTIONS num_ind.hw.pred = predict(num_ind.hw.mod, n.ahead = 6, prediction.interval = TRUE) amt_food_rec.hw.pred = predict(amt_food_rec.hw.mod, n.ahead = 6, prediction.interval = TRUE) num_volunteers.hw.pred = predict(num_volunteers.hw.mod, n.ahead = 6, prediction.interval = TRUE) ##plot predictions plot(num_ind.hw.mod, num_ind.hw.pred, type = 'b', main = "Forecasted Num. Individuals Arriving Till December 2020") plot(amt_food_rec.hw.mod, amt_food_rec.hw.pred, type = 'b', main = "Forecasted Amt. Food Arriving Till December 2020") plot(num_volunteers.hw.mod, num_volunteers.hw.pred, type = 'b', main = "Forecasted Num. Volunteers Till December 2020")
c01b07e4222a9a434cffcda6fe0dab792bd5099a
7188afce97d4674ec52fe33aeaf27b38e0889ac0
/plot2.R
fd59ad7864091381ec92e4c4f10f2163e9ef9280
[]
no_license
joski/ExData_Plotting1
b7aaa92f0faa94bd343e0e7bf239595a9cd49f9d
a0392e468ac403d04d8727b08f57dacdb5b1bedd
refs/heads/master
2020-03-07T05:28:33.147234
2018-03-29T18:24:57
2018-03-29T18:24:57
null
0
0
null
null
null
null
UTF-8
R
false
false
243
r
plot2.R
source("load_data.R") data<-load_data() png("plot2.png", width=400, height=400) with(data,plot(Time,Global_active_power, type="l", xlab = "", ylab = "Global Active Power (kilowatts)")) dev.off()
fae3732706ea29acd8534118f8ff641aba989bb2
d175a3870bbe9086724b614aaf681eda6002fa83
/server.R
a2a9e45db6ee1a729cdb7417ed1666669ff4e60c
[]
no_license
MFKiani/ShinyAppCode
22bec721bdf85a026a050e4388627de5ade785ef
652981e69fc5cb35dffec5c555e96620c58c1c5e
refs/heads/master
2021-01-10T17:00:19.093394
2015-05-23T18:31:37
2015-05-23T18:31:37
36,120,606
0
0
null
null
null
null
UTF-8
R
false
false
1,229
r
server.R
library(shiny) # We tweak the "am" field to have nicer factor labels. Since this doesn't # rely on any user inputs we can do this once at startup and then use the # value throughout the lifetime of the application # Define server logic required to plot various variables against mpg shinyServer(function(input, output) { # Compute the forumla text in a reactive expression since it is # shared by the output$caption and output$mpgPlot expressions formulaText <- reactive({ paste("Normal distributions with mean", input$mean1, "and standard deviation", input$sd1, "(in red) and mean",input$mean2, "and standard deviation", input$sd2, "(in blue)") }) # Return the formula text for printing as a caption output$caption1 <- renderText({ formulaText() }) # Generate a plot of the requested variable against mpg and only # include outliers if requested output$normalPlot1 <- renderPlot({ x=seq(-10,10,length=200) y1=dnorm(x,mean=input$mean1,sd=input$sd1) plot(x,y1,type="l",lwd=2,col="red") par(new = TRUE) y2=dnorm(x,mean=input$mean2,sd=input$sd2) plot(x,y2,type="l",lwd=2,col="blue") }) })
6622733770139bc3c00ca3772d78cc176b5e736b
985015b0c5399a82a1c874e1d68406aeb8042c72
/dockerfiles/haloplex-qc/CoveragePlots.R
006e36bb92d74a3ed93949795cb5af36c90c5a51
[]
no_license
genome/cle-myeloseq
f27f48c8e2fc868ac6a0ee3178c0f180be0871dc
fedd71f8daed318f3e4794e398797d038c002350
refs/heads/master
2021-10-10T00:53:51.361753
2021-10-08T16:34:19
2021-10-08T16:34:19
180,651,790
1
2
null
2021-05-04T19:04:01
2019-04-10T19:40:08
Perl
UTF-8
R
false
false
2,966
r
CoveragePlots.R
require(scales) sample.name <- commandArgs(T)[1] pdf(height=8.5,width=11,file=paste0(sample.name,".coverage_qc.pdf")) layout(matrix(c(1,1,2:5),nrow=3,byrow = T),heights = c(.2,1,1)) op <- par(mar=c(2,2,2,2)) plot.new() text(0,.5,labels = sample.name,cex=2,font=2,xpd=T,pos=4) par(op) cov <- read.table(paste0(sample.name,".coverage.txt"),stringsAsFactors = F) cov$V5 <- gsub("_.+","",cov$V5) genes <- levels(factor(cov$V5)) gene.chunks <- split(genes, ceiling(seq_along(genes)/10)) invisible(lapply(gene.chunks, function(g){ x <- subset(cov,cov$V5 %in% g) stats <- cbind(aggregate(x$V4 ~ x$V5,FUN = length), aggregate(x$V4 ~ x$V5,FUN = mean), aggregate(x$V4 ~ x$V5,FUN = median), aggregate(x$V4 ~ x$V5,FUN = function(X){ length(which(X<50)) }))[,c(1,2,4,6,8)] rownames(stats) <- stats[,1] apply(stats[,1:5],1,function(X){ cat(c("COVERAGE",X,"\n"),sep="\t"); }) op <- par(mar=c(4.5,4,4.5,2)) boxplot(log2(x$V4+1) ~ x$V5,las=2,axes=F,col="light gray") axis(1,at=1:nrow(stats),labels=rownames(stats),las=2) yAx <- c(0,1,20,50,100,500,seq(1000,max(x$V4,1000),by=1000)) axis(2,at=log2(yAx+1),labels = yAx) mtext("Coverage depth (by position)",side=2,line=2.5) box() abline(h=log2(c(20,50)+1),lty=2,lwd=3,col="red") mtext(c("Mean",round(stats[,3],0)),at=c(-.25,1:nrow(stats)),line=2.75,cex=.8) mtext(c("Median",round(stats[,4],0)),at=c(-.25,1:nrow(stats)),line=1.5,cex=.8) mtext(c("<50x",round(stats[,5],0)),at=c(-.25,1:nrow(stats)),line=0.25,cex=.8) invisible(par(op)) })) invisible(dev.off()) invisible(require(scales)) pdf(height=11,width=8.5,file=paste0(sample.name,".gc_length_qc.pdf")) layout(matrix(1:3,nrow=3,byrow = T),heights = c(.2,1,1)) op <- par(mar=c(2,2,2,2)) plot.new() text(0,.5,labels = sample.name,cex=2,font=2,xpd=T,pos=4) par(op) x <- read.table(paste0(sample.name,".amplicon_counts.txt"),stringsAsFactors = F) op <- par(mar=c(4,4,2,1),cex=1.25) plot(x$V3-x$V2,log2(x$V5),pch=16,cex=.4,col=alpha("black",.5),xlab="Amplicon length",ylab="Read counts (log2)") length.loess <- loess.smooth(x$V3-x$V2,log2(x$V5)) lines(length.loess,col="blue",lwd=3) abline(h=log2(50),col="red",lwd=3,lty=3) abline(h=log2(20),col="red",lwd=3,lty=3) cat(paste0(c("LENGTHFITX\t",paste0(length.loess$x,collapse=",")))) cat("\n") cat(paste0(c("LENGTHFITY\t",paste0(length.loess$y,collapse=",")))) cat("\n") plot(x$V6*100,log2(x$V5),pch=16,cex=.4,col=alpha("black",.5),xlab="Amplicon GC%",ylab="Read counts (log2)") gc.loess <- loess.smooth(x$V6*100,log2(x$V5)) lines(gc.loess,col="blue",lwd=3) abline(h=log2(50),col="red",lwd=3,lty=3) abline(h=log2(20),col="red",lwd=3,lty=3) cat(paste0(c("GCFITX\t",paste0(gc.loess$x,collapse=",")))) cat("\n") cat(paste0(c("GCFITY\t",paste0(gc.loess$y,collapse=",")))) cat("\n") par(op) invisible(dev.off())
1eadbb12f1feb597ecc4417e001eef1e1fb63f42
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/hawkes/examples/simulateHawkes.Rd.R
eda387c2ed25579725f6550cfc8ef0fa8e42b585
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
457
r
simulateHawkes.Rd.R
library(hawkes) ### Name: simulateHawkes ### Title: Hawkes process simulation Function ### Aliases: simulateHawkes ### ** Examples #One dimensional Hawkes process lambda0<-0.2 alpha<-0.5 beta<-0.7 horizon<-3600#one hour h<-simulateHawkes(lambda0,alpha,beta,horizon) #Multivariate Hawkes process lambda0<-c(0.2,0.2) alpha<-matrix(c(0.5,0,0,0.5),byrow=TRUE,nrow=2) beta<-c(0.7,0.7) horizon<-3600#one hour h<-simulateHawkes(lambda0,alpha,beta,horizon)
41fe9f7b6f7180e00a09a589546b81344b98e8c6
20c506f33d3bfe2322d9be7a894d64bd6a179fff
/R code
3a8e10a2c2c3e308682852e15fbf60fd4a6ded9a
[]
no_license
johnukfr/IDaSRP
ccdb75eab5bd7a42b63b2fd6a7f998d68599bbce
329bbd0260bcc62dacf5614ee7abcd642c189c9e
refs/heads/master
2020-07-04T18:04:08.063693
2020-05-15T13:57:21
2020-05-15T13:57:21
202,365,845
0
0
null
null
null
null
UTF-8
R
false
false
201,845
R code
#!/usr/bin/Rscript # sink("IDaSRP_077.3.txt", type = c("output", "message")) #####--------------------------------------------------------------------------- ##### R code for Disertation 'Information Demand and Stock Return Predictability' ##### University of Essex ##### Written by: Jonathan Legrand #####--------------------------------------------------------------------------- print("R code Version 77 for Disertation 'Information Demand and Stock Return Predictability': University of Essex: Written by: Jonathan Legrand. Written to be ran on Univeristy ceres.essex.ac.uk") ####--------------------------------------------------------------------------- #### Code preperation (clear memory, prepare libraries) ####--------------------------------------------------------------------------- print("Code preperation (clear memory, prepare libraries)") # remove all objects in the memory rm(list = ls()) # # Install pakages/libraries/dependancies needed # install.packages(c("readxl", "xts", "fpp", "astsa", "tidyverse", "dplyr", "rugarch", "Metrics", "e1071", "forecast", "R.utils", "aTSA", "R.utils", "EnvStats", "ggplot2", "plotly", "tsoutliers") # Import Libraries library(readxl) # The library 'astsa' is used for Econometric Modelling. See more at: #https://www.rdocumentation.org/packages/astsa/versions/1.6/ library(astsa) # The library 'rugarch' is used for GARCH Modelling. See more at: # https://stats.stackexchange.com/questions/93815/fit-a-garch-1-1-model-with-covariates-in-r # https://cran.r-project.org/web/packages/rugarch/rugarch.pdf # https://rdrr.io/rforge/rugarch/man/ugarchspec-methods.html library(rugarch) library(tidyverse) library(dplyr) library(xts) # The library 'Metrics' allows for the calculation of RMSE library(Metrics) # The library 'e1071' allows for the calculation of skewness library(e1071) # The library 'aTSA' allows for the calculation of the ADF test library(aTSA) library(forecast) # R.utils is needed for timeout functions library(R.utils) # EnvStats is needed to plot pdf's library(EnvStats) # plotly will allow us to plot 3d graphs library(plotly) Sys.setenv("plotly_username"="johnukfr") # Sys.setenv("plotly_api_key"=) library(ggplot2) theme_set(theme_minimal()) # tsoutliers allows us to perform jarque-bera tests library(tsoutliers) ####--------------------------------------------------------------------------- #### Set Datasets ####--------------------------------------------------------------------------- print('Set Datasets') ###--------------------------------------------------------------------------- ### SPX (i.e.: the S&P 500) ###--------------------------------------------------------------------------- SPX_Dates_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/1-Month_Treasury_Rate/1-Month_Treasury_Constant_Maturity_Rate_FRED_id_DGS1MO_2004.01.01_to_2019.03.13.xlsx", sheet = "Without_FRED_or_O-M_Holidays", range = "A2:A3794", col_names = "SPX_Dates") SPX_Dates = as.Date(SPX_Dates_df$SPX_Dates,"%Y-%m-%d", tz="Europe/London") # Setup Dates for subsets: SPX_Dates_df_m1 = slice(SPX_Dates_df, 2:3793) SPX_Datesm1 = as.Date(SPX_Dates_df_m1$SPX_Dates,"%Y-%m-%d", tz="Europe/London") SPX_Dates_df_m2 = slice(SPX_Dates_df, 3:3793) SPX_Datesm2 = as.Date(SPX_Dates_df_m2$SPX_Dates,"%Y-%m-%d", tz="Europe/London") # For a list of available time zones see: # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones # # One can see the list of dates with the comand # fix(SPX_Dates) DGS1MO_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/1-Month_Treasury_Rate/1-Month_Treasury_Constant_Maturity_Rate_FRED_id_DGS1MO_2004.01.01_to_2019.03.13.xlsx", sheet = "Without_FRED_or_O-M_Holidays", range = "B2:B3794", col_names = "DGS1MO") DGS1MO_df_dates = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/1-Month_Treasury_Rate/1-Month_Treasury_Constant_Maturity_Rate_FRED_id_DGS1MO_2004.01.01_to_2019.03.13.xlsx", sheet = "Without_FRED_or_O-M_Holidays", range = "A2:A3794", col_names = "DGS1MO_Dates") DGS1MO_df_dates = as.Date(DGS1MO_df_dates$DGS1MO_Dates,"%Y-%m-%d", tz="Europe/London") DGS1MO = as.matrix(DGS1MO_df) DTB3_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/3-Month_Treasury_Bill/Daily_3-Month_Treasury_Bill_FRED_id_TB3MS_2004.01.01_to_2019.03.13.xlsx", sheet = "Without_FRED_or_O-M_Holidays", range = "B2:B3794", col_names = "TB3MS") DTB3 = as.matrix(DTB3_df) DDGS10_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/10-Year_Treasury_Rate/10-Year_Treasury_Constant_Maturity_Rate_FRED_id_DGS10_2004.01.01_to_2019.03.13.xlsx", sheet = "Without_FRED_or_O-M_Holidays", range = "B2:B3794", col_names = "DGS10") DDGS10 = as.matrix(DDGS10_df) SPX_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/Realised Volatility/5min_realised_volatility_from_Oxford-Man.xlsx", sheet = "SPX2004-2019.03.1WithoutFREDHol", range = 'T2:T3794', col_names = "SPX") SPX = as.matrix(SPX_df) SPX_RVar_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/Realised Volatility/5min_realised_volatility_from_Oxford-Man.xlsx", sheet = "SPX2004-2019.03.1WithoutFREDHol", range = "I2:I3794", col_names = "SPX_RVar") # Note that the Ox-Man institute provides real VARIANCE as per # https://realized.oxford-man.ox.ac.uk/documentation/estimators SPX_RV_df = (SPX_RVar_df^0.5) SPX_RV = as.matrix(SPX_RV_df) colnames(SPX_RV) = c('SPX_RV') SPX_RV_zoo=zoo(SPX_RV, as.Date(SPX_Dates)) ###--------------------------------------------------------------------------- ### FTSE ###--------------------------------------------------------------------------- print("Importing FTSE data") FTSE_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/Realised Volatility/5min_realised_volatility_from_Oxford-Man.xlsx", sheet = "FTSE2001-2019.06.21", range = 'U2:U4910', col_names = "FTSE") FTSE_matrix = as.matrix(FTSE_df) FTSE_Dates = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/Realised Volatility/5min_realised_volatility_from_Oxford-Man.xlsx", sheet = "FTSE2001-2019.06.21", range = 'A2:A4910', col_names = "FTSE Dates") FTSE_Dates_matrix = as.matrix(FTSE_Dates) FTSE_zoo = as.zoo(FTSE_matrix, as.Date(FTSE_Dates_matrix)) # # Band of England (BoE) r_f (risk free bond daily rate of return) # Zero coupon nominal curves as defined by the BoE: : The spot interest rate or zero coupon yield is the rate at which an individual cash flow on some future date is discounted to determine its present value. By definition it is the yield to maturity of a zero coupon bond and can be considered as an average of single period rates to that maturity. Conventional dated stocks with a significant amount in issue and having more than three months to maturity, plus General Collateral repo rates (at the short end) are used to estimate these yields; index-linked stocks, irredeemable stocks, double dated stocks, stocks with embedded options, variable and floating stocks are all excluded. # Data gathered from http://www.bankofengland.co.uk/boeapps/iadb/index.asp?Travel=NIxIRx&levels=1&XNotes=Y&C=2C6&C=RN&C=DR6&G0Xtop.x=57&G0Xtop.y=9&XNotes2=Y&Nodes=X4051X4052X4053X4054X4066X4067X4068X38263&SectionRequired=I&HideNums=-1&ExtraInfo=true#BM # https://www.bankofengland.co.uk/statistics/details/further-details-about-yields-data # Note that: The prices of conventional gilts are quoted in terms of £100 nominal. As per: https://www.dmo.gov.uk/responsibilities/gilt-market/about-gilts/ print("Importing BoE data") BoE5YR_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/BoE_5_Year_Gilt/British_ Government_Securities_Yield_5_year_Nominal_Zero_Coupon.xlsx", sheet = "British_ Government_Securities_", range = 'A5:B3937', col_names = c("BoE 5Y Yield Dates", "BoE 5Y Yield")) BoE5YR_matrix = as.matrix(BoE5YR_df) BoE5YR_zoo = zoo(BoE5YR_matrix[1:3933,2], as.Date(BoE5YR_matrix[1:3933,1])) SVIFTSE_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/SVI/FTSE 100 World/SVI_from_2004.01.01_to_2019.03.13_normalised_by_2016.06.24_all_days.xlsx", sheet = "Sheet1", range = "A2:B5552", col_names = c("SVIFTSE_dates", "SVIFTSE")) SVIFTSE_zoo = zoo(SVIFTSE_df[1:5551,2], as.Date(as.matrix(SVIFTSE_df[1:5551,1]))) SVIFTSE = as.matrix(SVIFTSE_zoo) RVarFTSE_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/Realised Volatility/5min_realised_volatility_from_Oxford-Man.xlsx", sheet = "FTSE2001-2019.06.21", range = 'J2:J4910', col_names = "FTSE") # Note that the Ox-Man institute provides realised VARIANCE as per # https://realized.oxford-man.ox.ac.uk/documentation/estimators RVFTSE_df = (RVarFTSE_df^0.5) RVFTSE_zoo = zoo(RVFTSE_df, as.Date(FTSE_Dates_matrix)) ####--------------------------------------------------------------------------- #### Derive variables ####--------------------------------------------------------------------------- print("Derive variables") ###--------------------------------------------------------------------------- ### SPX ###--------------------------------------------------------------------------- # Several points have to be made about the FRED's data at this point: # # 1st: # The 1-, 2-, and 3-month rates are equivalent to the 30-, 60-, # and 90-day dates respectively, reported on the Board's Commercial Paper Web # page (www.federalreserve.gov/releases/cp/). This is as per the FRED's own # website (https://fred.stlouisfed.org/series/DGS1MO#0)'s referance # (https://www.federalreserve.gov/releases/h15/current/h15.pdf). # Figures are annualized using a 360-day year or bank interest as per # https://www.federalreserve.gov/releases/h15/. # We are using FRED's Constant Maturity Rate (CMR) data, more info on that: # https://www.investopedia.com/terms/c/constantmaturity.asp # https://www.investopedia.com/terms/c/cmtindex.asp # https://fred.stlouisfed.org/release/tables?rid=18&eid=289&snid=316 # # 2nd: From there, # we workout bellow the unit return from holding a one-month Treasury bill over # the period from t-1 to t by calculating its differrance in daily price # where: Daily price = (((CMR/100)+1)^(-(1/12)))*1000 # US_1MO_r_f=((((((DGS1MO/100)+1)^(-1/12))*1000)- ((((lag(DGS1MO)/100)+1)^(-1/12))*1000))/ ((((lag(DGS1MO)/100)+1)^(-(1/12)))*1000)) US_1MO_r_f_zoo = zoo(US_1MO_r_f, as.Date(DGS1MO_df_dates)) # Construct the returns variable, R_t (and its laged value, R_tm1) # Note things here: # # 1st: that due to the diferancing nessesary to calculate 'R', # the first value is empty. The comand: # as.matrix(((INDEX_df-lag.xts(data.matrix(INDEX_df)))/INDEX_df)-APPROPRIATE_r_f) # Where INDEX is SPX or FTSE and APPROPRIATE_r_f is # US_1MO_r_f or BoE_5Y_r_f displays this well. # # 2nd: In order for the correct 'R' values to be associated with the correct # dates, the element 'R' has to be changed into a 'zoo' element. # This will allow future models to have data points with correct date lables. # A vecor element is left however, # for libraries and functions that do not support them. # SPX_R_matrix = as.matrix(((SPX_df-lag.xts(data.matrix(SPX_df))) /lag.xts(data.matrix(SPX_df))) -US_1MO_r_f)[2:length(SPX)] SPX_R_zoo = zoo(SPX_R_matrix,as.Date(SPX_Datesm1)) ##--------------------------------------------------------------------------- ## SVI1 ##--------------------------------------------------------------------------- # The SVI Excel file tends to have empty values at its end. # The 'slice' function bellow will remove them. SPX_SVI_df = slice(read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/SVI/SVI_from_2004.01.01_to_2019.03.13_normalised_by_2018.02.06_Only_Trading_Days.xlsx", sheet = "SVI_Without_O-M_Holidays", range = "A1:B3802", col_names = c("Dates", "SPX_SVI")), 1:length(SPX_Dates)) SPX_SVI = as.matrix(SPX_SVI_df$SPX_SVI) # Convert the data frame 'SPX_SVI_df' into a matrix SPX_SVI_zoo = zoo(SPX_SVI, as.Date(SPX_SVI_df$Dates,"%Y-%m-%d", tz="Europe/London")) # Construct Google's Search Vecrot Index (SVI). SPX_dSVI = as.matrix(SPX_SVI - lag.xts(data.matrix(SPX_SVI)))[2:length(SPX_SVI)] colnames(SPX_dSVI) = c('SPX_dSVI') SPX_dSVI_zoo = zoo(SPX_dSVI, as.Date(Dates[1:3792])) ##--------------------------------------------------------------------------- ## SVI2 ##--------------------------------------------------------------------------- SPX_SVI2_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/SVI/2/SVI_from_2004.01.01_to_2019.03.13_normalised_by_2018.02.06_all_days.xlsx", sheet = "Sheet1", range = "A2:B5552", col_names = c("SVI2_dates", "SPX_SVI2")) SPX_SVI2_zoo = zoo(SPX_SVI2_df[1:5551,2], as.Date(as.matrix(SPX_SVI2_df[1:5551,1]))) SPX_SVI2 = as.matrix(SPX_SVI2_zoo) SPX_dSVI2_zoo = zoo(SPX_SVI2 - lag.xts(data.matrix(SPX_SVI2)), as.Date(as.matrix(SPX_SVI2_df[1:5551,1]))) SPX_dSVI2_zoo = SPX_dSVI2_zoo - (SPX_R_zoo*0) colnames(SPX_dSVI2_zoo) = c('SPX_dSVI2') ##--------------------------------------------------------------------------- ## SVI CVP ##--------------------------------------------------------------------------- SPX_SVICPV_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/SVI/CPV/SVI_from_2004.01.01_to_2017.03.15_normalised_by_2018.02.06 _CPV_days.xlsx", sheet = "Sheet1", range = "A2:B4824", col_names = c("SPX_SVICPV_dates", "SPX_SVICPV")) SPX_SVICPV_zoo = zoo(SPX_SVICPV_df[1:4823,2], as.Date(as.matrix(SPX_SVICPV_df[1:4823,1]))) SPX_SVICPV = as.matrix(SPX_SVICPV_zoo) SPX_dSVICPV_all_days_zoo=zoo(SPX_SVICPV-lag.xts(data.matrix(SPX_SVICPV)), as.Date(as.matrix(SPX_SVICPV_df[1:4823,1]))) SPX_dSVICPV = SPX_dSVICPV_all_days_zoo - (SPX_R_zoo*0) colnames(SPX_dSVICPV) = c('SPX_dSVICPV') ##--------------------------------------------------------------------------- ## SVI CVP US ##--------------------------------------------------------------------------- SPX_SVICPVUS_df = read_excel("C:/Users/johnukfr/OneDrive/UoE/Disertation/Data/SVI/CPV_US/SVI_from_2004.01.01_to_2017.03.15_normalised_by_2016.11.09_all_days.xlsx", sheet = "Sheet1", range = "A2:B4824", col_names = c("SPX_SVICPV_dates", "SPX_SVICPV")) SPX_SVICPVUS_zoo = zoo(SPX_SVICPVUS_df[1:4823,2], as.Date(as.matrix(SPX_SVICPVUS_df[1:4823,1]))) SPX_SVICPVUS_matrix = as.matrix(SPX_SVICPVUS_zoo) SPX_dSVICPVUS_all_days_zoo=zoo(SPX_SVICPVUS_matrix-lag.xts(SPX_SVICPVUS_matrix), as.Date(as.matrix(SPX_SVICPVUS_df[1:4823,1]))) SPX_dSVICPVUS_R = SPX_dSVICPVUS_all_days_zoo-(SPX_R_zoo*0) colnames(SPX_dSVICPVUS_R) = c('SPX_dSVICPVUS_R') SPX_dSVICPVUS_Rm1 = lag(SPX_dSVICPVUS_all_days_zoo) - (SPX_R_zoo*0) colnames(SPX_dSVICPVUS_R) = c('SPX_dSVICPVUS_Rm1') #--------------------------------------------------------------------------- # # SVI CPV MA #--------------------------------------------------------------------------- # the dSVI data is quite noisy, so we use a Moving Average to smooth it out # SPX_MAdSVICPV_all_days_zoo=zoo(movavg(SPX_dSVICPV_all_days_zoo, M,type="s"), # as.Date(as.matrix(SPX_SVICPV_df[1:4823,1]))) # SPX_MAdSVICPV_all_days_zoo=zoo(SPX_dSVICPV_all_days_zoo, as.Date(as.matrix(SPX_SVICPV_df[1:4823,1]))) # SPX_MAdSVICPV = na.omit(SPX_MAdSVICPV_all_days_zoo) - (SPX_R_zoo*0) # Deppending on the M chosen, the sample sie differs since we loose M starting # datapoints; so to insure we get comparable data throughout, we will only start # R and MAdSVI on 2004-01-07: # SPX_R_Sample_zoo = SPX_R_zoo[3:length(SPX_R_zoo)] # SPX_R_Sample_zoo = SPX_R_Sample_zoo - (SPX_MAdSVICPV*0) # SPX_MAdSVICPV = SPX_MAdSVICPV - (SPX_R_Sample_zoo*0) # SPX_dSVICPV = SPX_MAdSVICPV - (SPX_R_Sample_zoo*0) # SPX_Sample_Dates = as.Date(zoo::index(SPX_MAdSVICPV)) # Note that when usinf MAdSVI, the sample would start M days after 2004-01-01; # the maximum we will allow M to be will be 6, such that it starts on # 2004-01-07 and ends on 2017-03-15. # Its last in-GARCH-training-sample value is 2004-12-31 and is its 245th value. # Its first out-of-GARCH-training-sample value is 2005-01-03 and is its 246th value. ###--------------------------------------------------------------------------- ### FTSE (including SVIFTSE) ###--------------------------------------------------------------------------- BoE_r_f=((((((as.numeric(BoE5YR_zoo)/100)+1)^(-5))*100)- ((((lag(as.numeric(BoE5YR_zoo))/100)+1)^(-5))*100))/ ((((lag(as.numeric(BoE5YR_zoo))/100)+1)^(-5)*100))) BoE_r_f_zoo = zoo(BoE_r_f[2:length(BoE_r_f)], as.Date(BoE5YR_matrix[2:length(BoE_r_f),1])) BoE_p_f=((((as.numeric(BoE5YR_zoo)/100)+1)^(-5))*100) cumulative_BoE_r_f = matrix(,nrow=length(BoE_r_f_zoo)) for (i in c(1:length(cumulative_BoE_r_f))) {cumulative_BoE_r_f[i] = prod((1+BoE_r_f)[1:i], na.rm=TRUE)} FTSE_R_zoo = zoo(na.exclude(as.matrix((FTSE_df-lag.xts(data.matrix(FTSE_df))) /lag.xts(data.matrix(FTSE_df)))), as.Date(FTSE_Dates_matrix[2:4909])) - BoE_r_f_zoo FTSE_R_matrix = as.matrix(FTSE_R_zoo) # # Construct Google's Search Vecrot Index (SVI). dSVIFTSE=matrix(data.matrix(data.matrix(SVIFTSE)- lag.xts(data.matrix(SVIFTSE)))[2:length(SVIFTSE)]) colnames(dSVIFTSE) = c('dSVIFTSE') dSVIFTSE_zoo = zoo(dSVIFTSE, as.Date(as.matrix(SVIFTSE_df[2:5551,1]))) dSVIFTSE_zoo = dSVIFTSE_zoo - (FTSE_R_zoo*0) colnames(dSVIFTSE_zoo) = c('dSVIFTSE') dSVIFTSE=matrix(dSVIFTSE_zoo) Dates = as.Date(rownames(as.matrix(dSVIFTSE_zoo))) ####--------------------------------------------------------------------------- #### Descriptive Statistics of variables ####--------------------------------------------------------------------------- print("Descriptive Statistics of variables") ###--------------------------------------------------------------------------- ### FTSE ###--------------------------------------------------------------------------- # FTSE excess return print("plot of FTSE Excess Returns") epdfPlot(as.numeric(FTSE_R_zoo), main = "", xlab="") pdfPlot(param.list = list(mean=0, sd=sd(FTSE_R_matrix)), add = TRUE, pdf.col = "red") pdfPlot(add = TRUE, pdf.col = "blue") legend("topright", legend = c("EPDF plot of Excess FTSE Returns", "N[0,Var(Excess FTSE Returns)]", "N(0,1)"), col = c("black", "red", "blue"), lwd = 2 * par("cex")) title("PDF Plots") print("Mean of FTSE_R_zoo") mean(FTSE_R_zoo) print("Standard Deviation of FTSE_R_zoo") sd(FTSE_R_zoo) print("Median of FTSE_R_zoo") median(FTSE_R_zoo) print("Skewness of FTSE_R_zoo") skewness(as.numeric(FTSE_R_zoo)) print("Kurtosis of FTSE_R_zoo") kurtosis(as.numeric(FTSE_R_zoo)) print("AutoCorrelation Function of FTSE_R_zoo") acf(matrix(FTSE_R_zoo), lag.max = 1, plot = FALSE) # FTSE's SVI print("Mean of SVIFTSE_zoo") mean(SVIFTSE_zoo) # Note that that's the same as 'mean(SPX_dSVI_zoo)'; after much study on the matter, it seems as though this mean and other statistics are correct, which only highlights how different seperate SVI draws can be. print("Standard Deviation of SVIFTSE_zoo") sd(SVIFTSE_zoo) print("Median of SVIFTSE_zoo") median(SVIFTSE_zoo) print("Skewness of SVIFTSE_zoo") skewness(as.numeric(SVIFTSE_zoo)) print("Kurtosis of SVIFTSE_zoo") kurtosis(as.numeric(SVIFTSE_zoo)) print("AutoCorrelation Function of SVIFTSE_zoo") acf(as.numeric(SVIFTSE_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SVIFTSE_zoo") adf.test(matrix(SVIFTSE_zoo), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(SVIFTSE_zoo, xlab='Date', ylab='SVICPVUSSPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SVIFTSE_zoo") PP.test(SVIFTSE_zoo) print("KPSS Test of SVIFTSE_zoo") kpss.test(matrix(SVIFTSE_zoo)) # FTSE's dSVI print("Mean of dSVIFTSE") mean(dSVIFTSE_zoo) print("Standard Deviation of dSVIFTSE") sd(dSVIFTSE_zoo) print("Median of dSVIFTSE") median(dSVIFTSE_zoo) print("Skewness of dSVIFTSE") skewness(as.numeric(dSVIFTSE_zoo)) print("Kurtosis of dSVIFTSE") kurtosis(as.numeric(dSVIFTSE_zoo)) print("AutoCorrelation Function of dSVIFTSE") acf(matrix(dSVIFTSE_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of dSVIFTSE") adf.test(matrix(dSVIFTSE_zoo), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(dSVIFTSE_zoo, xlab='Date', ylab='dSVIFTSE', col='black', main='dSVIFTSE', type='l') print("PP Test of dSVIFTSE") PP.test(dSVIFTSE_zoo) print("KPSS Test of dSVIFTSE") kpss.test(matrix(dSVIFTSE_zoo)) plot(SVIFTSE_zoo, xlab='Date', ylab='SVIFTSE', col='blue', # main='Google Search Vector Index (SVI) for the FTSE index over time', type='l') # FTSE's Realised Volatility print("Mean of RVFTSE") mean(RVFTSE_zoo) print("Standard Deviation of RVFTSE") sd(RVFTSE_zoo) print("Median of RVFTSE") median(RVFTSE_zoo) print("Skewness of RVFTSE") skewness(as.numeric(RVFTSE_zoo)) print("Kurtosis of RVFTSE") kurtosis(as.numeric(RVFTSE_zoo)) print("AutoCorrelation Function of RVFTSE") acf(as.numeric(RVFTSE_zoo), lag.max = 1, plot = FALSE) # FTSE's BoE_r_f print("Mean of BoE_r_f") mean(BoE_r_f_zoo) print("Standard Deviation of BoE_r_f") sd(BoE_r_f_zoo) print("Median of BoE_r_f") median(BoE_r_f_zoo) print("Skewness of BoE_r_f") skewness(as.numeric(BoE_r_f_zoo)) print("Kurtosis of BoE_r_f") kurtosis(as.numeric(BoE_r_f_zoo)) print("AutoCorrelation Function of BoE_r_f") acf(as.numeric(BoE_r_f_zoo), lag.max = 1, plot = FALSE) # Descriptive Plot plot(SVIFTSE_zoo, xlab='Date', ylab='SVIFTSE', col='blue', main='Google Search Vector Index (SVI) for the FTSE index over time', type='l') ###--------------------------------------------------------------------------- ### SPX ###--------------------------------------------------------------------------- # SPX excess return print("plot of SPX Excess Returns") epdfPlot(as.numeric(SPX_R_zoo), main = "", xlab="") lines(density(FTSE_R_matrix),col="orange", lwd = 2 * par("cex")) pdfPlot(param.list = list(mean=0, sd=sd(FTSE_R_matrix)), add = TRUE, pdf.col = "red") pdfPlot(param.list = list(mean=0, sd=sd(SPX_R_zoo)), add = TRUE, pdf.col = "green") pdfPlot(add = TRUE, pdf.col = "blue") legend("topright", legend = c("EPDF plot of Excess SPX Returns", "EPDF plot of Excess FTSE Returns", "N[0,Var(Excess FTSE Returns)]", "N[0,Var(Excess SPX Returns)]", "N(0,1)"), col = c("black", "orange", "red","green", "blue"), lwd = 2 * par("cex")) # title("PDF Plots") print("Mean of SPX_R_zoo") mean(SPX_R_zoo) print("Standard Deviation of SPX_R_zoo") sd(SPX_R_zoo) print("Median of SPX_R_zoo") median(SPX_R_zoo) print("Skewness of SPX_R_zoo") skewness(as.numeric(SPX_R_zoo)) print("Kurtosis of SPX_R_zoo") kurtosis(as.numeric(SPX_R_zoo)) print("AutoCorrelation Function of SPX_R_zoo") acf(matrix(SPX_R_zoo), lag.max = 1, plot = FALSE) # SPX's Realised Volatility print("Mean of SPX_RV") mean(SPX_RV_zoo) print("Standard Deviation of SPX_RV") sd(SPX_RV_zoo) print("Median of SPX_RV") median(SPX_RV_zoo) print("Skewness of SPX_RV") skewness(as.numeric(SPX_RV_zoo)) print("Kurtosis of SPX_RV") kurtosis(as.numeric(SPX_RV_zoo)) print("AutoCorrelation Function of SPX_RV") acf(as.numeric(SPX_RV_zoo), lag.max = 1, plot = FALSE) # SPX's r_f print("Mean of US_1MO_r_f") mean(US_1MO_r_f[2:length(US_1MO_r_f)]) print("Standard Deviation of US_1MO_r_f") sd(US_1MO_r_f[2:length(US_1MO_r_f)]) print("Median of US_1MO_r_f") median(US_1MO_r_f[2:length(US_1MO_r_f)]) print("Skewness of US_1MO_r_f") skewness(as.numeric(US_1MO_r_f[2:length(US_1MO_r_f)])) print("Kurtosis of US_1MO_r_f") kurtosis(as.numeric(US_1MO_r_f[2:length(US_1MO_r_f)])) print("AutoCorrelation Function of US_1MO_r_f") acf(as.numeric(US_1MO_r_f[2:length(US_1MO_r_f)]), lag.max = 1, plot = FALSE) # SPX's SVI1 print("Mean of SPX_SVI_zoo") mean(SPX_SVI_zoo) # Note that that's the same as 'mean(SPX_dSVI_zoo)'; after much study on the matter, it seems as though this mean and other statistics are correct, which only highlights how different seperate SVI draws can be. print("Standard Deviation of SPX_SVI_zoo") sd(SPX_SVI_zoo) print("Median of SPX_SVI_zoo") median(SPX_SVI_zoo) print("Skewness of SPX_SVI_zoo") skewness(as.numeric(SPX_SVI_zoo)) print("Kurtosis of SPX_SVI_zoo") kurtosis(as.numeric(SPX_SVI_zoo)) print("AutoCorrelation Function of SPX_SVI_zoo") acf(as.numeric(SPX_SVI_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_SVI_zoo") adf.test(matrix(SPX_SVI_zoo), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(SPX_SVI_zoo, xlab='Date', ylab='SVI1SPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_SVI_zoo") PP.test(SPX_SVI_zoo) print("KPSS Test of SPX_SVI_zoo_zoo") kpss.test(matrix(SPX_SVI_zoo)) # SPX's dSVI1 print("Mean of SPX_dSVI") mean(SPX_dSVI_zoo) # Note that that's the same as 'mean(SPX_dSVI_zoo)'; after much study on the matter, it seems as though this mean and other statistics are correct, which only highlights how different seperate SVI draws can be. print("Standard Deviation of SPX_dSVI") sd(SPX_dSVI) print("Median of SPX_dSVI") median(SPX_dSVI) print("Skewness of SPX_dSVI") skewness(as.numeric(SPX_dSVI)) print("Kurtosis of SPX_dSVI") kurtosis(as.numeric(SPX_dSVI)) print("AutoCorrelation Function of SPX_dSVI") acf(as.numeric(SPX_dSVI), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_dSVI") adf.test(matrix(SPX_dSVI), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(SPX_dSVI_zoo, xlab='Date', ylab='dSVI1SPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_dSVI") PP.test(SPX_dSVI) print("KPSS Test of SPX_dSVI_zoo") kpss.test(matrix(SPX_dSVI_zoo)) # SPX's SVI2 print("Mean of SPX_SVI2_zoo") mean(SPX_SVI2_zoo) # Note that that's the same as 'mean(SPX_dSVI_zoo)'; after much study on the matter, it seems as though this mean and other statistics are correct, which only highlights how different seperate SVI draws can be. print("Standard Deviation of SPX_SVI2_zoo") sd(SPX_SVI2_zoo) print("Median of SPX_SVI2_zoo") median(SPX_SVI2_zoo) print("Skewness of SPX_SVI2_zoo") skewness(as.numeric(SPX_SVI2_zoo)) print("Kurtosis of SPX_SVI2_zoo") kurtosis(as.numeric(SPX_SVI2_zoo)) print("AutoCorrelation Function of SPX_SVI2_zoo") acf(as.numeric(SPX_SVI2_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_SVI2_zoo") adf.test(matrix(SPX_SVI2_zoo), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(SPX_SVI2_zoo, xlab='Date', ylab='SVI2SPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_SVI2_zoo") PP.test(SPX_SVI2_zoo) print("KPSS Test of SPX_SVI2_zoo") kpss.test(matrix(SPX_SVI2_zoo)) # SPX's SPX_dSVI2_zoo print("Mean of SPX_dSVI2") mean(SPX_dSVI2_zoo) print("Standard Deviation of SPX_dSVI2") sd(SPX_dSVI2_zoo) print("Median of SPX_dSVI2") median(SPX_dSVI2_zoo) print("Skewness of SPX_dSVI2") skewness(as.numeric(SPX_dSVI2_zoo)) print("Kurtosis of SPX_dSVI2") kurtosis(as.numeric(SPX_dSVI2_zoo)) print("AutoCorrelation Function of SPX_dSVI2") acf(as.numeric(SPX_dSVI2_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_dSVI2_zoo") adf.test(matrix(SPX_dSVI2_zoo), nlag = NULL, output = TRUE) plot(SPX_dSVI2_zoo, xlab='Date', ylab='dSVI2SPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_dSVI2_zoo") PP.test(SPX_dSVI2_zoo) print("KPSS Test of SPX_dSVI2_zoo") kpss.test(matrix(SPX_dSVI2_zoo)) # SPX's SVICPV print("Mean of SPX_SVICPV_zoo") mean(SPX_SVICPV_zoo) # Note that that's the same as 'mean(SPX_dSVI_zoo)'; after much study on the matter, it seems as though this mean and other statistics are correct, which only highlights how different seperate SVI draws can be. print("Standard Deviation of SPX_SVICPV_zoo") sd(SPX_SVICPV_zoo) print("Median of SPX_SVICPV_zoo") median(SPX_SVICPV_zoo) print("Skewness of SPX_SVICPV_zoo") skewness(as.numeric(SPX_SVICPV_zoo)) print("Kurtosis of SPX_SVICPV_zoo") kurtosis(as.numeric(SPX_SVICPV_zoo)) print("AutoCorrelation Function of SPX_SVICPV_zoo") acf(as.numeric(SPX_SVICPV_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_SVICPV_zoo") adf.test(matrix(SPX_SVICPV_zoo), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(SPX_SVICPV_zoo, xlab='Date', ylab='SVICPVSPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_SVICPV_zoo") PP.test(SPX_SVICPV_zoo) print("KPSS Test of SPX_SVICPV_zoo") kpss.test(matrix(SPX_SVICPV_zoo)) # SPX's SPX_dSVICPV print("Mean of SPX_SVICPV") mean(SPX_dSVICPV) print("Standard Deviation of SPX_SVICPV") sd(SPX_dSVICPV) print("Median of SPX_SVICPV") median(SPX_dSVICPV) print("Skewness of SPX_SVICPV") skewness(as.numeric(SPX_dSVICPV)) print("Kurtosis of SPX_SVICPV") kurtosis(as.numeric(SPX_dSVICPV)) print("AutoCorrelation Function of SPX_SVICPV") acf(as.numeric(SPX_dSVICPV), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_dSVICPV") adf.test(matrix(SPX_dSVICPV), nlag = NULL, output = TRUE) plot(SPX_dSVICPV, xlab='Date', ylab='dSVICPVSPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_dSVICPV") PP.test(SPX_dSVICPV) print("KPSS Test of SPX_dSVICPV") kpss.test(matrix(SPX_dSVICPV)) # SPX's SVICPVUS print("Mean of SPX_SVICPVUS_zoo") mean(SPX_SVICPVUS_zoo) # Note that that's the same as 'mean(SPX_dSVI_zoo)'; after much study on the matter, it seems as though this mean and other statistics are correct, which only highlights how different seperate SVI draws can be. print("Standard Deviation of SPX_SVICPVUS_zoo") sd(SPX_SVICPVUS_zoo) print("Median of SPX_SVICPVUS_zoo") median(SPX_SVICPVUS_zoo) print("Skewness of SPX_SVICPVUS_zoo") skewness(as.numeric(SPX_SVICPVUS_zoo)) print("Kurtosis of SPX_SVICPVUS_zoo") kurtosis(as.numeric(SPX_SVICPVUS_zoo)) print("AutoCorrelation Function of SPX_SVICPVUS_zoo") acf(as.numeric(SPX_SVICPVUS_zoo), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_SVICPVUS_zoo") adf.test(matrix(SPX_SVICPVUS_zoo), nlag = NULL, output = TRUE) # Our ADF test here should show that we reject the Null Hypothesis (low p-value) # in preference for the alternative of stationarity. One can see that dSVIFTSE_zoo # is stationary by ploting it with: plot(SPX_SVICPVUS_zoo, xlab='Date', ylab='SVICPVUSSPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_SVICPVUS_zoo") PP.test(SPX_SVICPVUS_zoo) print("KPSS Test of SPX_SVICPVUS_zoo") kpss.test(matrix(SPX_SVICPVUS_zoo)) # SPX's SPX_dSVICPVUS_all_days_zoo print("Mean of SPX_dSVICPVUS_R") mean(SPX_dSVICPVUS_R) print("Standard Deviation of SPX_dSVICPVUS_R") sd(SPX_dSVICPVUS_R) print("Median of SPX_dSVICPVUS_R") median(SPX_dSVICPVUS_R) print("Skewness of SPX_dSVICPVUS_R") skewness(as.numeric(SPX_dSVICPVUS_R)) print("Kurtosis of SPX_dSVICPVUS_R") kurtosis(as.numeric(SPX_dSVICPVUS_R)) print("AutoCorrelation Function of SPX_dSVICPVUS_R") acf(as.numeric(SPX_dSVICPVUS_R), lag.max = 1, plot = FALSE) print("Augmented Dickey-Fuller Test of SPX_dSVICPVUS_R") adf.test(matrix(SPX_dSVICPVUS_R), nlag = NULL, output = TRUE) plot(SPX_dSVICPVUS_R, xlab='Date', ylab='dSVICPVUSSPX', col='black', type='l', # main='dSVIFTSE' ) print("PP Test of SPX_dSVICPVUS_R") PP.test(SPX_dSVICPVUS_R) print("KPSS Test of SPX_dSVICPVUS_R") kpss.test(matrix(SPX_dSVICPVUS_R)) # Descriptive Plot plot(SPX_SVI_zoo, xlab='Date', ylab='SVISPX1', col='blue', type='l', # main='Google Search Vector Index 1 (SVI 1) for the SPX index over time' ) plot(SPX_SVI2_zoo, xlab='Date', ylab='SVISPX2', col='blue', # main='Google Search Vector Index 2 (SVI 2) for the SPX index over time', type='l' ) plot(SPX_SVICPV_zoo, xlab='Date', ylab='SVISPXCPV', col='blue', # main='Google Search Vector Index CPV (SVI-CPV) for the SPX index over time', type='l' ) plot(SPX_SVICPVUS_zoo, xlab='Date', ylab='SVICPVUS', col='blue', # main='Google Search Vector Index CPV-US (SVI-CPV-US) for the SPX index over time', type='l' ) ####--------------------------------------------------------------------------- #### FTSE GARCH models: create, train/fit them and create forecasts ####--------------------------------------------------------------------------- # Set parameters roll = length(dSVIFTSE_zoo)-252 # This will also be the number of out-of-sample predictions. N.B.: the 253rd # value of FTSE_R_zoo corresponds to 2005-01-04, the 1st trading day # out-of-sample, the first value after 252. # Define functions to make our code easier to read GARCH_model_spec = function(mod, exreg) {ugarchspec(variance.model = list(model=mod, garchOrder = c(1, 1), external.regressors = exreg), mean.model=list(armaOrder = c(1, 0), include.mean = TRUE, external.regressors = exreg), distribution.model = "norm")} GARCH_model_forecast = function(mod) {ugarchforecast(mod, n.ahead = 1, n.roll = 0, data = NULL, out.sample = 0)} ###---------------------------------------------------------------------------- ### In-sample AR(1)-GARCH(1,1) Model ###--------------------------------------------------------------------------- in_sample_GARCH11 = GARCH_model_spec(mod="sGARCH", exreg= NULL) in_sample_GARCH11fit = ugarchfit(data = FTSE_R_matrix[1:(251+1)], spec=in_sample_GARCH11) ###---------------------------------------------------------------------------- ### Create the AR(1)-GARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- # Non-linear Variance Models are created using the 'rugarch' package for # adequacy; then create one-step-ahead forecasts, taking into account new # data every step and re-estimating GARCH variables/cofactors. GARCH11_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GARCH11_mu_hat) = c('GARCH11_mu_hat') GARCH11_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GARCH11_sigma_hat) = c('GARCH11_sigma_hat') for (i in c(1:roll)) {GARCH11 = GARCH_model_spec(mod="sGARCH", exreg= NULL) try(withTimeout({(GARCH11fit = ugarchfit(data = FTSE_R_matrix[1:(251+i)], spec=GARCH11))} , timeout = 3),silent = TRUE) try((GARCH11fitforecast = GARCH_model_forecast(mod = GARCH11fit)) ,silent = TRUE # suppressWarnings(expr) ) try((GARCH11_mu_hat[i]=GARCH11fitforecast@forecast[["seriesFor"]]) ,silent = TRUE) try((GARCH11_sigma_hat[i]=GARCH11fitforecast@forecast[["sigmaFor"]]) ,silent = TRUE) rm(GARCH11) rm(GARCH11fit) rm(GARCH11fitforecast) } # fitted(GARCH11fitforecast) RV_no_GARCH11_sigma_hat_na_dated = as.matrix(RVFTSE_zoo -(na.omit(GARCH11_sigma_hat*0))) # This above is just a neat trick that returns strictly the RV (Realised # Volatility) values corresponding to the dates for which GARCH11_sigma_hat # values are not NA without any new functions or packages. # Forecast Error, Mean and S.D.: GARCH11forecasterror = (na.omit(GARCH11_sigma_hat) -RV_no_GARCH11_sigma_hat_na_dated) colnames(GARCH11forecasterror) = c("GARCH11forecasterror") # plot(zoo(GARCH11forecasterror, as.Date(row.names(GARCH11forecasterror))) # , type='l', ylab='GARCH11forecasterror', xlab='Date') print("Mean of GARCH11forecasterror") mean(GARCH11forecasterror) print("Standard Deviation GARCH11forecasterror") sd(GARCH11forecasterror) # RMSE of the sigma (standard deviations) of the forecast: print("RMSE of the sigma (standard deviations) of the forecast from the GARCH11 model") rmse(RV_no_GARCH11_sigma_hat_na_dated, (na.omit(GARCH11_sigma_hat))) # Note that this is the same as the bellow: # sqrt(mean((RV[(252+1):(length(FTSE_R_matrix)+1)] - # as.matrix((GARCH11fitforecast@forecast[["sigmaFor"]]))[1:roll]) # ^2)) ###---------------------------------------------------------------------------- ### In-sample AR(1)-GARCH(1,1)-SVI Model ###---------------------------------------------------------------------------- in_sample_GARCH11SVI = GARCH_model_spec(mod = "sGARCH", exreg = as.matrix(dSVIFTSE[1:(251+1)])) in_sample_GARCH11SVIfit = ugarchfit(data = FTSE_R_matrix[1:(251+1)], spec=in_sample_GARCH11SVI) ###---------------------------------------------------------------------------- ### Create the AR(1)-GARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- GARCH11SVI_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GARCH11SVI_mu_hat) = c('GARCH11SVI_mu_hat') GARCH11SVI_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GARCH11SVI_sigma_hat) = c('GARCH11SVI_sigma_hat') for (i in c(1:roll)){ GARCH11SVI = GARCH_model_spec(mod= "sGARCH", exreg = as.matrix(dSVIFTSE[1:(251+i)])) try(withTimeout({(GARCH11SVIfit = ugarchfit(data = FTSE_R_matrix[1:(251+i)], spec=GARCH11SVI))}, timeout = 3),silent = TRUE) try((GARCH11SVIfitforecast = GARCH_model_forecast(mod = GARCH11SVIfit)),silent = TRUE) try((GARCH11SVI_mu_hat[i]=GARCH11SVIfitforecast@forecast[["seriesFor"]]), silent = TRUE) try((GARCH11SVI_sigma_hat[i]=GARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(GARCH11SVI) rm(GARCH11SVIfit) rm(GARCH11SVIfitforecast) } # fitted(GARCH11SVIfitforecast) RV_no_GARCH11SVI_sigma_hat_na_dated = as.matrix(RVFTSE_zoo -(na.omit(GARCH11SVI_sigma_hat*0))) # Forecast Error, Mean and S.D.: GARCH11SVIforecasterror = (na.omit(GARCH11SVI_sigma_hat) -RV_no_GARCH11SVI_sigma_hat_na_dated) colnames(GARCH11SVIforecasterror) = c("GARCH11SVIforecasterror") print("Mean of GARCH11SVIforecasterror") mean(GARCH11SVIforecasterror) print("Standard Deviation GARCH11SVIforecasterror") sd(GARCH11SVIforecasterror) # RMSE of the sigma (standard deviations) of the forecast: print("RMSE of the sigma (standard deviations) of the forecast from the GARCH11-SVI model") rmse(RV_no_GARCH11SVI_sigma_hat_na_dated, (na.omit(GARCH11SVI_sigma_hat))) ###---------------------------------------------------------------------------- ### In-sample AR(1)-GJRGARCH(1,1) Model ###---------------------------------------------------------------------------- in_sample_GJRGARCH11 = GARCH_model_spec("gjrGARCH", exreg= NULL) in_sample_GJRGARCH11fit = ugarchfit(data = FTSE_R_matrix[1:(251+1)], spec=in_sample_GJRGARCH11) ###---------------------------------------------------------------------------- ### Create the AR(1)-GJRGARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- GJRGARCH11_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GJRGARCH11_mu_hat) = c('GJRGARCH11_mu_hat') GJRGARCH11_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GJRGARCH11_sigma_hat) = c('GJRGARCH11_sigma_hat') for (i in c(1:roll)) {GJRGARCH11 = GARCH_model_spec(mod = "gjrGARCH", exreg = NULL) try(withTimeout({(GJRGARCH11fit = ugarchfit(data = FTSE_R_matrix[1:(251+i)], spec=GJRGARCH11))} , timeout = 3),silent = TRUE) try((GJRGARCH11fitforecast = GARCH_model_forecast(mod = GJRGARCH11fit)),silent = TRUE) try((GJRGARCH11_mu_hat[i]=GJRGARCH11fitforecast@forecast[["seriesFor"]]), silent = TRUE) try((GJRGARCH11_sigma_hat[i]=GJRGARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(GJRGARCH11) rm(GJRGARCH11fit) rm(GJRGARCH11fitforecast) } RV_no_GJRGARCH11_sigma_hat_na_dated = as.matrix(RVFTSE_zoo -(na.omit(GJRGARCH11_sigma_hat*0))) # Forecast Error, Mean and S.D.: GJRGARCH11forecasterror = (na.omit(GJRGARCH11_sigma_hat) -RV_no_GJRGARCH11_sigma_hat_na_dated) colnames(GJRGARCH11forecasterror) = c("GJRGARCH11forecasterror") print("Mean of GJRGARCH11forecasterror") mean(GJRGARCH11forecasterror) print("Standard Deviation GJRGARCH11forecasterror") sd(GJRGARCH11forecasterror) # RMSE of the sigma (standard deviations) of the forecast: print("RMSE of the sigma (standard deviations) of the forecast from the GJRGARCH11 model") rmse(RV_no_GJRGARCH11_sigma_hat_na_dated, (na.omit(GJRGARCH11_sigma_hat))) ###---------------------------------------------------------------------------- ### In-sample AR(1)-GJRGARCH(1,1)-SVI Model ###---------------------------------------------------------------------------- in_sample_GJRGARCH11SVI = GARCH_model_spec("gjrGARCH", as.matrix(dSVIFTSE[1:(251+1)])) in_sample_GJRGARCH11SVIfit = ugarchfit(data = FTSE_R_matrix[1:(251+1)], spec=in_sample_GJRGARCH11SVI) ###---------------------------------------------------------------------------- ### Create the AR(1)-GJRGARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- GJRGARCH11SVI_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GJRGARCH11SVI_mu_hat) = c('GJRGARCH11SVI_mu_hat') GJRGARCH11SVI_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(GJRGARCH11SVI_sigma_hat) = c('GJRGARCH11SVI_sigma_hat') for (i in c(1:roll)) {GJRGARCH11SVI = GARCH_model_spec(mod = "gjrGARCH", exreg=as.matrix(dSVIFTSE[1:(251+i)])) try(withTimeout({(GJRGARCH11SVIfit = ugarchfit(data = FTSE_R_matrix[1:(251+i)], spec=GJRGARCH11SVI))} , timeout = 3),silent = TRUE) try((GJRGARCH11SVIfitforecast = GARCH_model_forecast(mod = GJRGARCH11SVIfit)) ,silent = TRUE) try((GJRGARCH11SVI_mu_hat[i]=GJRGARCH11SVIfitforecast@forecast[["seriesFor"]]), silent = TRUE) try((GJRGARCH11SVI_sigma_hat[i]=GJRGARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(GJRGARCH11SVI) rm(GJRGARCH11SVIfit) rm(GJRGARCH11SVIfitforecast) } RV_no_GJRGARCH11SVI_sigma_hat_na_dated = as.matrix(RVFTSE_zoo -(na.omit(GJRGARCH11SVI_sigma_hat*0))) # Forecast Error, Mean and S.D.: GJRGARCH11SVIforecasterror = (na.omit(GJRGARCH11SVI_sigma_hat) -RV_no_GJRGARCH11SVI_sigma_hat_na_dated) colnames(GJRGARCH11SVIforecasterror) = c("GJRGARCH11SVIforecasterror") print("Mean of GJRGARCH11SVIforecasterror") mean(GJRGARCH11SVIforecasterror) print("Standard Deviation GJRGARCH11SVIforecasterror") sd(GJRGARCH11SVIforecasterror) # RMSE of the sigma (standard deviations) of the forecast: print("RMSE of the sigma (standard deviations) of the forecast from the GJRGARCH11SVI model") rmse(RV_no_GJRGARCH11SVI_sigma_hat_na_dated, (na.omit(GJRGARCH11SVI_sigma_hat))) ###---------------------------------------------------------------------------- ### In-sample AR(1)-EGARCH(1,1) Model ###---------------------------------------------------------------------------- in_sample_EGARCH11 = GARCH_model_spec(mod="eGARCH", exreg= NULL) in_sample_EGARCH11fit = ugarchfit(data = FTSE_R_matrix[1:(251+1)], spec=in_sample_EGARCH11) ###---------------------------------------------------------------------------- ### Create the AR(1)-EGARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- EGARCH11_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(EGARCH11_mu_hat) = c('EGARCH11_mu_hat') EGARCH11_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(EGARCH11_sigma_hat) = c('EGARCH11_sigma_hat') for (i in c(1:roll)) {EGARCH11 = GARCH_model_spec(mod = "eGARCH", exreg = NULL) try(withTimeout({(EGARCH11fit = ugarchfit(data = FTSE_R_matrix[1:(251+i)], spec=EGARCH11))} , timeout = 3),silent = TRUE) try((EGARCH11fitforecast = GARCH_model_forecast(mod = EGARCH11fit)),silent = TRUE) try((EGARCH11_mu_hat[i]=EGARCH11fitforecast@forecast[["seriesFor"]]), silent = TRUE) try((EGARCH11_sigma_hat[i]=EGARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(EGARCH11) rm(EGARCH11fit) rm(EGARCH11fitforecast) } RV_no_EGARCH11_sigma_hat_na_dated = as.matrix(RVFTSE_zoo -(na.omit(EGARCH11_sigma_hat*0))) # Forecast Error, Mean and S.D.: EGARCH11forecasterror = (na.omit(EGARCH11_sigma_hat)-RV_no_EGARCH11_sigma_hat_na_dated) colnames(EGARCH11forecasterror) = c("EGARCH11forecasterror") print("Mean of EGARCH11forecasterror") mean(EGARCH11forecasterror) print("Standard Deviation EGARCH11forecasterror") sd(EGARCH11forecasterror) # RMSE of the sigma (standard deviations) of the forecast: print("RMSE of the sigma (standard deviations) of the forecast from the EGARCH11 model") rmse(RV_no_EGARCH11_sigma_hat_na_dated, (na.omit(EGARCH11_sigma_hat))) ###---------------------------------------------------------------------------- ### In-sample AR(1)-EGARCH(1,1)-SVI Model ###---------------------------------------------------------------------------- in_sample_EGARCH11SVI = GARCH_model_spec(mod = "eGARCH", exreg = as.matrix(dSVIFTSE[1:(251+1)])) in_sample_EGARCH11SVIfit = ugarchfit(data = FTSE_R_matrix[1:(251+1)], spec=in_sample_EGARCH11SVI) ###---------------------------------------------------------------------------- ### Create the AR(1)-EGARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- EGARCH11SVI_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(EGARCH11SVI_mu_hat) = c('EGARCH11SVI_mu_hat') EGARCH11SVI_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(Dates[(252+1):(252+roll)])) colnames(EGARCH11SVI_sigma_hat) = c('EGARCH11SVI_sigma_hat') for (i in c(1:roll)) {EGARCH11SVI = GARCH_model_spec(mod = "eGARCH", exreg = as.matrix(dSVIFTSE[1:(251+i)])) try(withTimeout({(EGARCH11SVIfit = ugarchfit(data = FTSE_R_matrix[1:(251+i)], spec=EGARCH11SVI))} , timeout = 3),silent = TRUE) try((EGARCH11SVIfitforecast = GARCH_model_forecast(mod = EGARCH11SVIfit)), silent = TRUE) try((EGARCH11SVI_mu_hat[i]=EGARCH11SVIfitforecast@forecast[["seriesFor"]]), silent = TRUE) try((EGARCH11SVI_sigma_hat[i]=EGARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(EGARCH11SVI) rm(EGARCH11SVIfit) rm(EGARCH11SVIfitforecast) } # fitted(EGARCH11SVIfitforecast) RV_no_EGARCH11SVI_sigma_hat_na_dated = as.matrix(RVFTSE_zoo -(na.omit(EGARCH11SVI_sigma_hat*0))) # Forecast Error, Mean and S.D.: EGARCH11SVIforecasterror = (na.omit(EGARCH11SVI_sigma_hat)-RV_no_EGARCH11SVI_sigma_hat_na_dated) colnames(EGARCH11SVIforecasterror) = c("EGARCH11SVIforecasterror") print("Mean of EGARCH11SVIforecasterror") mean(EGARCH11SVIforecasterror) print("Standard Deviation EGARCH11SVIforecasterror") sd(EGARCH11SVIforecasterror) # RMSE of the sigma (standard deviations) of the forecast: print("RMSE of the sigma (standard deviations) of the forecast from the EGARCH11-SVI model") rmse(RV_no_EGARCH11SVI_sigma_hat_na_dated, (na.omit(EGARCH11SVI_sigma_hat))) ###--------------------------------------------------------------------------- ### s.d. forecase D-M tests ###--------------------------------------------------------------------------- print("This function implements the modified test proposed by Harvey, Leybourne and Newbold (1997). The null hypothesis is that the two methods have the same forecast accuracy. For alternative=less, the alternative hypothesis is that method 2 is less accurate than method 1. For alternative=greater, the alternative hypothesis is that method 2 is more accurate than method 1. For alternative=two.sided, the alternative hypothesis is that method 1 and method 2 have different levels of accuracy.") print("Diebold and Mariano test GARCH11 with and without SVI") GARCH11forecasterror_dm = GARCH11forecasterror - (GARCH11SVIforecasterror*0) GARCH11SVIforecasterror_dm = GARCH11SVIforecasterror - (GARCH11forecasterror*0) dm.test(matrix(GARCH11forecasterror_dm), matrix(GARCH11SVIforecasterror_dm), alternative = "less") print("Diebold and Mariano test GJRGARCH11 with and without SVI") GJRGARCH11forecasterror_dm = GJRGARCH11forecasterror - (GJRGARCH11SVIforecasterror*0) GJRGARCH11SVIforecasterror_dm = GJRGARCH11SVIforecasterror - (GJRGARCH11forecasterror*0) dm.test(matrix(GJRGARCH11forecasterror_dm), matrix(GJRGARCH11SVIforecasterror_dm), alternative = "less") print("Diebold and Mariano test EGARCH11 with and without SVI") EGARCH11forecasterror_dm = EGARCH11forecasterror - (EGARCH11SVIforecasterror*0) EGARCH11SVIforecasterror_dm = EGARCH11SVIforecasterror - (EGARCH11forecasterror*0) dm.test(matrix(EGARCH11forecasterror_dm), matrix(EGARCH11SVIforecasterror_dm), alternative = "less") ####--------------------------------------------------------------------------- #### FTSE estimates of the probability of a positive return ####--------------------------------------------------------------------------- ###---------------------------------------------------------------------------- ### C&D, Naive ###---------------------------------------------------------------------------- ##----------------------------------------------------------------------------- ## Naive-Model and its forecast error statistics ##----------------------------------------------------------------------------- # Naive-Model's Indicator function according to the GARCH11 Model: Naive_I = ifelse(FTSE_R_matrix>0 , 1 , 0) # Naive Model: Naive=(1:(length(FTSE_R_matrix))) for(t in c(1:(length(FTSE_R_matrix)))) {Naive[t] = (1/t) * sum(FTSE_R_matrix[1:t])} # Note that the naive model provides the probability of aa positive return in # the next time period and therefore spams from 2004-01-06 to 2019-03-13. Naive_zoo = zoo(Naive, as.Date(rownames(as.matrix(FTSE_R_zoo)))) ##----------------------------------------------------------------------------- ## C&D's GARCH models with and without SVI ## (Model independent variables' construction) ##----------------------------------------------------------------------------- # mean of return up to time 'k' R_mu=(1:length(FTSE_R_matrix)) for (i in c(1:length(FTSE_R_matrix))){R_mu[i]=mean(FTSE_R_matrix[1:i])} # standard deviation of return up to time 'k'. # Note that its 1st value is NA since there is no standard deviation for a # constant (according to R). R_sigma=(1:length(FTSE_R_matrix)) for (i in c(1:length(FTSE_R_matrix))){R_sigma[i]=sd(FTSE_R_matrix[1:i])} R_sigma[1]=0 # Since the variance of a constant is 0. #------------------------------------------------------------------------------ # GARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GARCH11 Model: GARCH11_CandD_I = matrix(, nrow=roll, ncol=roll) GARCH11_CandD_I_k= matrix(, nrow=roll, ncol=roll) GARCH11_CandD_I_t = matrix( - (GARCH11_mu_hat/GARCH11_sigma_hat)) for(t in c(1:roll)) {for (k in c(1:t)) {GARCH11_CandD_I_k[k,t] = ifelse(((FTSE_R_matrix[252+k]-GARCH11_mu_hat[k])/GARCH11_sigma_hat[k]) <=GARCH11_CandD_I_t[t+1], 1,0) # Note that we have some missing values due to the model not always managing # to converge to estimates of sigma and mu; since we need the t+1 model # estimates to compute its CandD_I_k, we also loose its t'th value for # each model's missing value. # We also los the last value (the roll'th value) for the same reason. GARCH11_CandD_I[k,t] = ifelse((is.na(GARCH11_CandD_I_k[k,t])), NA, (sum(GARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GARCH11 Model: GARCH11_CandD=(1:(roll-1)) for(i in c(1:(roll-1))) {GARCH11_CandD[i] = 1 - ((GARCH11_CandD_I[i,i])/ length(na.omit(GARCH11_CandD_I[1:i,i])))} GARCH11_CandD_zoo = zoo(GARCH11_CandD, as.Date(Dates[(253+1):(253+(roll-1))])) # This zoo object has missing values. GARCH11_CandD_zoo_no_nas=zoo(na.omit(GARCH11_CandD_zoo)) # rm(GARCH11_CandD_I_t) # Cleaning datasets # rm(GARCH11_CandD_I_k) # rm(GARCH11_CandD_I) #------------------------------------------------------------------------------ # GARCH11-SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GARCH11SVI Model: GARCH11SVI_CandD_I = matrix(, nrow=roll, ncol=roll) GARCH11SVI_CandD_I_k= matrix(, nrow=roll, ncol=roll) GARCH11SVI_CandD_I_t = matrix( - (GARCH11SVI_mu_hat/GARCH11SVI_sigma_hat)) for(t in c(1:roll)) {for (k in c(1:t)) {GARCH11SVI_CandD_I_k[k,t] = ifelse(((FTSE_R_matrix[252+k]-GARCH11SVI_mu_hat[k])/GARCH11SVI_sigma_hat[k]) <=GARCH11SVI_CandD_I_t[t+1], 1,0) GARCH11SVI_CandD_I[k,t] = ifelse( (is.na(GARCH11SVI_CandD_I_k[k,t])), NA, (sum(GARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GARCH11SVI Model: GARCH11SVI_CandD=(1:(roll-1)) for(i in c(1:(roll-1))) {GARCH11SVI_CandD[i] = 1 - ((GARCH11SVI_CandD_I[i,i])/ length(na.omit(GARCH11SVI_CandD_I[1:i,i])))} GARCH11SVI_CandD_zoo = zoo(GARCH11SVI_CandD, as.Date(Dates[(253+1):(253+(roll-1))])) # This zoo object has missing values. GARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(GARCH11SVI_CandD_zoo)) # rm(GARCH11SVI_CandD_I_t) # Cleaning datasets # rm(GARCH11SVI_CandD_I_k) # rm(GARCH11SVI_CandD_I) #------------------------------------------------------------------------------ # GJRGARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GJRGARCH11 Model: GJRGARCH11_CandD_I = matrix(, nrow=roll, ncol=roll) GJRGARCH11_CandD_I_k= matrix(, nrow=roll, ncol=roll) GJRGARCH11_CandD_I_t = matrix( - (GJRGARCH11_mu_hat/GJRGARCH11_sigma_hat)) for(t in c(1:roll)) {for (k in c(1:t)) {GJRGARCH11_CandD_I_k[k,t] = ifelse(((FTSE_R_matrix[252+k]-GJRGARCH11_mu_hat[k])/GJRGARCH11_sigma_hat[k]) <=GJRGARCH11_CandD_I_t[t+1], 1,0) # Note that we have some missing values due to the model not always managing # to converge to estimates of sigma and mu; since we need the t+1 model # estimates to compute its CandD_I_k, we also loose its t'th value for # each model's missing value. # We also los the last value (the roll'th value) for the same reason. GJRGARCH11_CandD_I[k,t] = ifelse( (is.na(GJRGARCH11_CandD_I_k[k,t])), NA, (sum(GJRGARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GJRGARCH11 Model: GJRGARCH11_CandD=(1:(roll-1)) for(i in c(1:(roll-1))) {GJRGARCH11_CandD[i] = 1 - ((GJRGARCH11_CandD_I[i,i])/ length(na.omit(GJRGARCH11_CandD_I[1:i,i])))} GJRGARCH11_CandD_zoo = zoo(GJRGARCH11_CandD, as.Date(Dates[(253+1):(253+(roll-1))])) # This zoo object has missing values. GJRGARCH11_CandD_zoo_no_nas=zoo(na.omit(GJRGARCH11_CandD_zoo)) # rm(GJRGARCH11_CandD_I_t) # Cleaning datasets # rm(GJRGARCH11_CandD_I_k) # rm(GJRGARCH11_CandD_I) #------------------------------------------------------------------------------ # GJRGARCH11-SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GJRGARCH11-SVI Model: GJRGARCH11SVI_CandD_I = matrix(, nrow=roll, ncol=roll) GJRGARCH11SVI_CandD_I_k = matrix(, nrow=roll, ncol=roll) GJRGARCH11SVI_CandD_I_t = matrix( - (GJRGARCH11SVI_mu_hat/GJRGARCH11SVI_sigma_hat)) for(t in c(1:roll)) {for (k in c(1:t)) {GJRGARCH11SVI_CandD_I_k[k,t] = ifelse(((FTSE_R_matrix[252+k]-GJRGARCH11SVI_mu_hat[k])/GJRGARCH11SVI_sigma_hat[k]) <=GJRGARCH11SVI_CandD_I_t[t+1], 1,0) GJRGARCH11SVI_CandD_I[k,t] = ifelse( (is.na(GJRGARCH11SVI_CandD_I_k[k,t])), NA, (sum(GJRGARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GJRGARCH11-SVI Model: GJRGARCH11SVI_CandD=(1:(roll-1)) for(i in c(1:(roll-1))) {GJRGARCH11SVI_CandD[i] = 1 - ((GJRGARCH11SVI_CandD_I[i,i])/ length(na.omit(GJRGARCH11SVI_CandD_I[1:i,i])))} GJRGARCH11SVI_CandD_zoo = zoo(GJRGARCH11SVI_CandD, as.Date(Dates[(253+1):(253+(roll-1))])) # This zoo object has missing values. GJRGARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(GJRGARCH11SVI_CandD_zoo)) # rm(GJRGARCH11SVI_CandD_I_t) # Cleaning datasets # rm(GJRGARCH11SVI_CandD_I_k) # rm(GJRGARCH11SVI_CandD_I) #------------------------------------------------------------------------------ # EGARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the EGARCH11 Model: EGARCH11_CandD_I = matrix(, nrow=roll, ncol=roll) EGARCH11_CandD_I_k= matrix(, nrow=roll, ncol=roll) EGARCH11_CandD_I_t = matrix( - (EGARCH11_mu_hat/EGARCH11_sigma_hat)) for(t in c(1:roll)) {for (k in c(1:t)) {EGARCH11_CandD_I_k[k,t] = ifelse(((FTSE_R_matrix[252+k]-EGARCH11_mu_hat[k])/EGARCH11_sigma_hat[k]) <=EGARCH11_CandD_I_t[t+1], 1,0) EGARCH11_CandD_I[k,t] = ifelse( (is.na(EGARCH11_CandD_I_k[k,t])), NA, (sum(EGARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the EGARCH11 Model: EGARCH11_CandD=(1:(roll-1)) for(i in c(1:(roll-1))) {EGARCH11_CandD[i] = 1 - ((EGARCH11_CandD_I[i,i])/ length(na.omit(EGARCH11_CandD_I[1:i,i])))} EGARCH11_CandD_zoo = zoo(EGARCH11_CandD, as.Date(Dates[(253+1):(253+(roll-1))])) # This zoo object has missing values. EGARCH11_CandD_zoo_no_nas=zoo(na.omit(EGARCH11_CandD_zoo)) # rm(EGARCH11_CandD_I_t) # Cleaning datasets # rm(EGARCH11_CandD_I_k) # rm(EGARCH11_CandD_I) #------------------------------------------------------------------------------ # EGARCH11-SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the EGARCH11-SVI Model: EGARCH11SVI_CandD_I = matrix(, nrow=roll, ncol=roll) EGARCH11SVI_CandD_I_k= matrix(, nrow=roll, ncol=roll) EGARCH11SVI_CandD_I_t = matrix( - (EGARCH11SVI_mu_hat/EGARCH11SVI_sigma_hat)) for(t in c(1:roll)) {for (k in c(1:t)) {EGARCH11SVI_CandD_I_k[k,t] = ifelse(((FTSE_R_matrix[252+k]-EGARCH11SVI_mu_hat[k])/EGARCH11SVI_sigma_hat[k]) <=EGARCH11SVI_CandD_I_t[t+1], 1,0) EGARCH11SVI_CandD_I[k,t] = ifelse( (is.na(EGARCH11SVI_CandD_I_k[k,t])), NA, (sum(EGARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the EGARCH11-SVI Model: EGARCH11SVI_CandD=(1:(roll-1)) for(i in c(1:(roll-1))) {EGARCH11SVI_CandD[i] = 1 - ((EGARCH11SVI_CandD_I[i,i])/ length(na.omit(EGARCH11SVI_CandD_I[1:i,i])))} EGARCH11SVI_CandD_zoo = zoo(EGARCH11SVI_CandD, as.Date(Dates[(253+1):(253+(roll-1))])) # This zoo object has missing values. EGARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(EGARCH11SVI_CandD_zoo)) # rm(EGARCH11SVI_CandD_I_t) # Cleaning datasets # rm(EGARCH11SVI_CandD_I_k) # rm(EGARCH11SVI_CandD_I) ##----------------------------------------------------------------------------- ## compare the predictive performance of each model ## (forecast error mean, sd, Brier Scores and Diebold&Mariano statistics) ##----------------------------------------------------------------------------- # # mean of the probabilistic forecast errors derived from each model Observed_pi= ifelse(FTSE_R_matrix>0,1,0) Observed_pi_zoo = zoo(Observed_pi, as.Date(Dates)) Naive_pi_error = Naive_zoo - Observed_pi_zoo GARCH11_pi_error = GARCH11_CandD_zoo_no_nas - Observed_pi_zoo GARCH11SVI_pi_error = GARCH11SVI_CandD_zoo_no_nas - Observed_pi_zoo GJRGARCH11_pi_error = GJRGARCH11_CandD_zoo_no_nas - Observed_pi_zoo GJRGARCH11SVI_pi_error = GJRGARCH11SVI_CandD_zoo_no_nas - Observed_pi_zoo EGARCH11_pi_error = EGARCH11_CandD_zoo_no_nas - Observed_pi_zoo EGARCH11SVI_pi_error = EGARCH11SVI_CandD_zoo_no_nas - Observed_pi_zoo mean(Naive_pi_error) sd(Naive_pi_error) mean(GARCH11_pi_error) sd(GARCH11_pi_error) mean(GARCH11SVI_pi_error) sd(GARCH11SVI_pi_error) mean(GJRGARCH11_pi_error) sd(GJRGARCH11_pi_error) mean(GJRGARCH11SVI_pi_error) sd(GJRGARCH11SVI_pi_error) mean(EGARCH11_pi_error) sd(EGARCH11_pi_error) mean(EGARCH11SVI_pi_error) sd(EGARCH11SVI_pi_error) # # Brier scores of the probabilistic forecast errors derived from each model Naive_pi_error_Brier_score = (1/length(Naive_pi_error))*sum(Naive_pi_error^2) show(Naive_pi_error_Brier_score) GARCH11_pi_error_Brier_score = (1/length(GARCH11_pi_error))*sum(GARCH11_pi_error^2) show(GARCH11_pi_error_Brier_score) GARCH11SVI_pi_error_Brier_score = (1/length(GARCH11SVI_pi_error))*sum(GARCH11SVI_pi_error^2) show(GARCH11SVI_pi_error_Brier_score) GJRGARCH11_pi_error_Brier_score = (1/length(GJRGARCH11_pi_error))*sum(GJRGARCH11_pi_error^2) show(GJRGARCH11_pi_error_Brier_score) GJRGARCH11SVI_pi_error_Brier_score = (1/length(GJRGARCH11SVI_pi_error))*sum(GJRGARCH11SVI_pi_error^2) show(GJRGARCH11SVI_pi_error_Brier_score) EGARCH11_pi_error_Brier_score = (1/length(EGARCH11_pi_error))*sum(EGARCH11_pi_error^2) show(EGARCH11_pi_error_Brier_score) EGARCH11SVI_pi_error_Brier_score = (1/length(EGARCH11SVI_pi_error))*sum(EGARCH11SVI_pi_error^2) show(EGARCH11SVI_pi_error_Brier_score) # # Diebold&Mariano statistics # Here the alternative hypothesis is that method 2 is more accurate than # method 1; remember that a small p-value indicates strong evidence against # the Null Hypothesis. GARCH11_pi_error_dm = GARCH11_pi_error - (GARCH11SVI_pi_error*0) GARCH11SVI_pi_error_dm = GARCH11SVI_pi_error - (GARCH11_pi_error*0) dm.test(matrix(GARCH11_pi_error_dm), matrix(GARCH11SVI_pi_error_dm), alternative = "less") GJRGARCH11_pi_error_dm = GJRGARCH11_pi_error - (GJRGARCH11SVI_pi_error*0) GJRGARCH11SVI_pi_error_dm = GJRGARCH11SVI_pi_error - (GJRGARCH11_pi_error*0) dm.test(matrix(GJRGARCH11_pi_error_dm), matrix(GJRGARCH11SVI_pi_error_dm), alternative = c("greater")) EGARCH11_pi_error_dm = EGARCH11_pi_error - (EGARCH11SVI_pi_error*0) EGARCH11SVI_pi_error_dm = EGARCH11SVI_pi_error - (EGARCH11_pi_error*0) dm.test(matrix(EGARCH11_pi_error_dm), matrix(EGARCH11SVI_pi_error_dm), alternative = c("greater")) ####---------------------------------------------------------------------------- #### FTSE Financial significance ####---------------------------------------------------------------------------- # As per Chronopoulos et. al (2018): Investor with a utility function for wealth w is defined as U(w) where U = function(w) {-exp((-3) * w)} # where A is the investor's degree of risk aversion. # in Goetzmann et al. (2007), Della Corte et al. (2010), and Andriosopoulos et al. (2014), we assume that the risk aversion coefficient to be 3. # indicator of the realised direction of the return on the S&P 500 index y_d = ifelse(FTSE_R_zoo>0,1,0) # Set the probability threashold at which to invest in the index in our 2d graphs: p = 0.5 ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework using the Naive model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_Naive = ifelse(Naive_zoo>p,1,0) y_d_Naive = y_d - (Naive_zoo*0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_Naive),1))==1 , 1, 0) R_Active_Naive_p = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_Naive*0))+(BoE_r_f_zoo-(y_hat_d_Naive*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_Naive*0))))[2:length(y_hat_d_Naive)] # note that the trick '(FTSE_R_zoo-(y_hat_d_Naive*0))' returns only the R values # corresponding to dates present in y_hat_d_Naive, which are the ones # in omega (omega couldn't be used because it's not a zoo object) R_Active_Naive_p_cumulated = matrix(,nrow=length(R_Active_Naive_p)) for (i in c(1:length(R_Active_Naive_p))) {R_Active_Naive_p_cumulated[i] = prod((1+R_Active_Naive_p)[1:i])} # plot(R_Active_Naive_p_cumulated, type='l') R_cumulated = matrix(,nrow=length(R_Active_Naive_p)) for (i in c(1:length(R_Active_Naive_p))) {R_cumulated[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_Naive_p*0))))[1:i])} # plot(R_cumulated, type='l') plot(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), type="l",col="black", xlab='Date', ylab='FTSE index and Naive index cumulated') lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="green") ###---------------------------------------------------------------------------- ### Granger and Pesaran (2000)'s framework using the GARCH11 model ###---------------------------------------------------------------------------- ##---------------------------------------------------------------------------- ## FTSE 3D graph Low Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath sequance = seq(from = 0, to = 1, by = 0.05) R_Active_GARCH11_p = matrix(, nrow=3575, ncol=length(sequance)) R_Active_GARCH11_p_cumulated = matrix(, nrow=3575, ncol=length(sequance)) R_cumulated = matrix(, nrow=3575, ncol=length(sequance)) y_d_GARCH11 = y_d - (GARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(length(sequance)-1) # corresponding directional forecast and realised direction y_hat_d_GARCH11 = ifelse(GARCH11_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GARCH11),1))==1 , 1, 0) R_Active_GARCH11_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GARCH11*0))+(BoE_r_f_zoo-(y_hat_d_GARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GARCH11*0))))[2:length(y_hat_d_GARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GARCH11*0))' returns only the R values corresponding to dates present in y_hat_d_GARCH11, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GARCH11_p[,P_number] = R_Active_GARCH11_p_col_zoo for (i in c(1:length(R_Active_GARCH11_p[,P_number]))) {R_Active_GARCH11_p_cumulated[i,P_number] = prod((1+R_Active_GARCH11_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GARCH11_p_col_zoo*0)))[1:i])} } GARCH11_CandD_3D_LowRes = (plot_ly(z=R_Active_GARCH11_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GARCH11 models", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GARCH11_CandD_3D, filename = "GARCH11_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 3D graph High Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath BY = 0.0125 FROM = 0.45 sequance = seq(from = FROM, to = 0.6, by = BY) R_Active_GARCH11_p = matrix(, nrow=3575, ncol=length(sequance)) R_Active_GARCH11_p_cumulated = matrix(, nrow=3575, ncol=length(sequance)) R_cumulated = matrix(, nrow=3575, ncol=length(sequance)) y_d_GARCH11 = y_d - (GARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(1/BY) - FROM/BY # corresponding directional forecast and realised direction y_hat_d_GARCH11 = ifelse(GARCH11_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GARCH11),1))==1 , 1, 0) R_Active_GARCH11_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GARCH11*0))+ (BoE_r_f_zoo-(y_hat_d_GARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GARCH11*0))))[2:length(y_hat_d_GARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GARCH11*0))' returns only the R values corresponding to dates present in y_hat_d_GARCH11, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GARCH11_p[,P_number] = R_Active_GARCH11_p_col_zoo for (i in c(1:length(R_Active_GARCH11_p[,P_number]))) {R_Active_GARCH11_p_cumulated[i,P_number] = prod((1+R_Active_GARCH11_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GARCH11_p_col_zoo*0)))[1:i])} } GARCH11_CandD_3D_HighRes = (plot_ly(z=R_Active_GARCH11_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GARCH11 models where 0.45<=P<=0.6", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GARCH11_CandD_3D, filename = "GARCH11_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 2D graph (p=0.49 seems best at increments of 0.0005 p increpemnts) ##---------------------------------------------------------------------------- p = 0.49 # corresponding directional forecast and realised direction y_hat_d_GARCH11_2d = ifelse(GARCH11_CandD_zoo_no_nas>p,1,0) y_d_GARCH11_2d = y_d - (GARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11-'s. # let the portfolio weight attributed to the stock market index be omega_2d = ifelse( (lead(as.matrix(y_hat_d_GARCH11_2d),1))==1 , 1, 0) R_Active_GARCH11_p_2d = ((lag(omega_2d,1) * (FTSE_R_zoo-(y_hat_d_GARCH11_2d*0)) + (1-lag(omega_2d,1)) * (BoE_r_f_zoo-(y_hat_d_GARCH11_2d*0))))[2:length(y_hat_d_GARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GARCH11_2d*0))' returns only the R values # corresponding to dates present in y_hat_d_GARCH11_2d, which are the ones # in omega (omega_2d couldn't be used because it's not a zoo object) R_Active_GARCH11_p_cumulated_2d = matrix(,nrow=length(R_Active_GARCH11_p_2d)) for (i in c(1:length(R_Active_GARCH11_p_2d))) {R_Active_GARCH11_p_cumulated_2d[i] = prod((1+R_Active_GARCH11_p_2d)[1:i])} # plot(R_Active_GARCH11_p_cumulated_2d, type='l') R_cumulated_2d = matrix(,nrow=length(R_Active_GARCH11_p_2d)) for (i in c(1:length(R_Active_GARCH11_p_2d))) {R_cumulated_2d[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_GARCH11_p_2d*0))))[1:i])} # plot(R_cumulated_2d, type='l') plot(zoo(R_cumulated_2d, as.Date(zoo::index(y_hat_d_GARCH11_2d[2:length(y_hat_d_GARCH11_2d)]))), type="l",col="black", xlab='Date', #ylim=c(0.5,1.2), ylab=p) lines(zoo(R_Active_GARCH11_p_cumulated_2d, as.Date(zoo::index(y_hat_d_GARCH11_2d[2:length(y_hat_d_GARCH11_2d)]))), col="red") lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="green") ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework using the GARCH11-SVI model (p=0.4935 seems best) ###---------------------------------------------------------------------------- p=0.4935 # corresponding directional forecast and realised direction y_hat_d_GARCH11SVI = ifelse(GARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_GARCH11SVI = y_d - (GARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has # values on dates corresponding to GARCH11-SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GARCH11SVI),1))==1 , 1, 0) R_Active_GARCH11SVI_p = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GARCH11SVI*0))+(BoE_r_f_zoo-(y_hat_d_GARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GARCH11SVI*0))))[2:length(y_hat_d_GARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GARCH11SVI*0))' returns only the R values # corresponding to dates present in y_hat_d_GARCH11SVI, which are the ones # in omega (omega couldn't be used because it's not a zoo object) R_Active_GARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_GARCH11SVI_p)) for (i in c(1:length(R_Active_GARCH11SVI_p))) {R_Active_GARCH11SVI_p_cumulated[i] = prod((1+R_Active_GARCH11SVI_p)[1:i])} # plot(R_Active_GARCH11SVI_p_cumulated, type='l') R_cumulated = matrix(,nrow=length(R_Active_GARCH11SVI_p)) for (i in c(1:length(R_Active_GARCH11SVI_p))) {R_cumulated[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_GARCH11SVI_p*0))))[1:i])} # plot(R_cumulated, type='l') plot(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_GARCH11SVI[2:length(y_hat_d_GARCH11SVI)]))), type="l",col="black", xlab='Date', ylim=c(0.67,2), main=p, ylab='FTSE index and GARCH11SVI index cumulated') lines(zoo(R_Active_GARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_GARCH11SVI[2:length(y_hat_d_GARCH11SVI)]))), col="green") ##---------------------------------------------------------------------------- ## 3D graph Low Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath sequance = seq(from = 0, to = 1, by = 0.05) R_Active_GARCH11SVI_p = matrix(, nrow=3567, ncol=length(sequance)) R_Active_GARCH11SVI_p_cumulated = matrix(, nrow=3567, ncol=length(sequance)) R_cumulated = matrix(, nrow=3567, ncol=length(sequance)) y_d_GARCH11SVI = y_d - (GARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11SVI's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(length(sequance)-1) # corresponding directional forecast and realised direction y_hat_d_GARCH11SVI = ifelse(GARCH11SVI_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GARCH11SVI),1))==1 , 1, 0) R_Active_GARCH11SVI_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GARCH11SVI*0))+(BoE_r_f_zoo-(y_hat_d_GARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GARCH11SVI*0))))[2:length(y_hat_d_GARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GARCH11SVI*0))' returns only the R values corresponding to dates present in y_hat_d_GARCH11SVI, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GARCH11SVI_p[,P_number] = R_Active_GARCH11SVI_p_col_zoo for (i in c(1:length(R_Active_GARCH11SVI_p[,P_number]))) {R_Active_GARCH11SVI_p_cumulated[i,P_number] = prod((1+R_Active_GARCH11SVI_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GARCH11SVI_p_col_zoo*0)))[1:i])} } GARCH11SVI_CandD_3D_LowRes = (plot_ly(z=R_Active_GARCH11SVI_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GARCH11SVI models", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GARCH11SVI_CandD_3D, filename = "GARCH11SVI_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 3D graph High Resolution (suggests P =0.45) ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath BY = 0.0125 FROM = 0.4 sequance = seq(from = FROM, to = 0.55, by = BY) R_Active_GARCH11SVI_p = matrix(, nrow=3567, ncol=length(sequance)) R_Active_GARCH11SVI_p_cumulated = matrix(, nrow=3567, ncol=length(sequance)) R_cumulated = matrix(, nrow=3567, ncol=length(sequance)) y_d_GARCH11SVI = y_d - (GARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11SVI's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(1/BY) - FROM/BY # corresponding directional forecast and realised direction y_hat_d_GARCH11SVI = ifelse(GARCH11SVI_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GARCH11SVI),1))==1 , 1, 0) R_Active_GARCH11SVI_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GARCH11SVI*0))+ (BoE_r_f_zoo-(y_hat_d_GARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GARCH11SVI*0))))[2:length(y_hat_d_GARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GARCH11SVI*0))' returns only the R values corresponding to dates present in y_hat_d_GARCH11SVI, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GARCH11SVI_p[,P_number] = R_Active_GARCH11SVI_p_col_zoo for (i in c(1:length(R_Active_GARCH11SVI_p[,P_number]))) {R_Active_GARCH11SVI_p_cumulated[i,P_number] = prod((1+R_Active_GARCH11SVI_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GARCH11SVI_p_col_zoo*0)))[1:i])} } GARCH11SVI_CandD_3D_HighRes = (plot_ly(z=R_Active_GARCH11SVI_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GARCH11SVI models where 0.4<=P<=0.55", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GARCH11SVI_CandD_3D, filename = "GARCH11SVI_CandD_3D-public-graph") ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework using the GJRGARCH11 model (p=0.505 seems best) ###---------------------------------------------------------------------------- p = 0.505 # corresponding directional forecast and realised direction y_hat_d_GJRGARCH11 = ifelse(GJRGARCH11_CandD_zoo_no_nas>p,1,0) y_d_GJRGARCH11 = y_d - (GJRGARCH11_CandD_zoo_no_nas*0) # This y_d only has # values on dates corresponding to GJRGARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GJRGARCH11),1))==1 , 1, 0) R_Active_GJRGARCH11_p = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GJRGARCH11*0))+(BoE_r_f_zoo-(y_hat_d_GJRGARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GJRGARCH11*0))))[2:length(y_hat_d_GJRGARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GJRGARCH11*0))' returns only the R values # corresponding to dates present in y_hat_d_GARCH11, which are the ones # in omega (omega couldn't be used because it's not a zoo object) R_Active_GJRGARCH11_p_cumulated = matrix(,nrow=length(R_Active_GJRGARCH11_p)) for (i in c(1:length(R_Active_GJRGARCH11_p))) {R_Active_GJRGARCH11_p_cumulated[i] = prod((1+R_Active_GJRGARCH11_p)[1:i])} # plot(R_Active_GJRGARCH11_p_cumulated, type='l') R_cumulated = matrix(,nrow=length(R_Active_GJRGARCH11_p)) for (i in c(1:length(R_Active_GJRGARCH11_p))) {R_cumulated[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_GJRGARCH11_p*0))))[1:i])} # plot(R_cumulated, type='l') plot(zoo(R_Active_GJRGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_GJRGARCH11[2:length(y_hat_d_GJRGARCH11)]))), type="l",col="red", xlab='Date', main=p, ylab='FTSE index and GJRGARCH11 index cumulated') lines(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_GJRGARCH11[2:length(y_hat_d_GJRGARCH11)]))), col="black") lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="green") ##---------------------------------------------------------------------------- ## 3D graph Low Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath sequance = seq(from = 0, to = 1, by = 0.05) R_Active_GJRGARCH11_p = matrix(, nrow=3585, ncol=length(sequance)) R_Active_GJRGARCH11_p_cumulated = matrix(, nrow=3585, ncol=length(sequance)) R_cumulated = matrix(, nrow=3585, ncol=length(sequance)) y_d_GJRGARCH11 = y_d - (GJRGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(length(sequance)-1) # corresponding directional forecast and realised direction y_hat_d_GJRGARCH11 = ifelse(GJRGARCH11_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GJRGARCH11),1))==1 , 1, 0) R_Active_GJRGARCH11_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GJRGARCH11*0))+(BoE_r_f_zoo-(y_hat_d_GJRGARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GJRGARCH11*0))))[2:length(y_hat_d_GJRGARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GJRGARCH11*0))' returns only the R values corresponding to dates present in y_hat_d_GJRGARCH11, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GJRGARCH11_p[,P_number] = R_Active_GJRGARCH11_p_col_zoo for (i in c(1:length(R_Active_GJRGARCH11_p[,P_number]))) {R_Active_GJRGARCH11_p_cumulated[i,P_number] = prod((1+R_Active_GJRGARCH11_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GJRGARCH11_p_col_zoo*0)))[1:i])} } GJRGARCH11_CandD_3D_LowRes = (plot_ly(z=R_Active_GJRGARCH11_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GJRGARCH11 models", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GJRGARCH11_CandD_3D, filename = "GJRGARCH11_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 3D graph High Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath BY = 0.0125 FROM = 0.45 sequance = seq(from = FROM, to = 0.6, by = BY) R_Active_GJRGARCH11_p = matrix(, nrow=3585, ncol=length(sequance)) R_Active_GJRGARCH11_p_cumulated = matrix(, nrow=3585, ncol=length(sequance)) R_cumulated = matrix(, nrow=3585, ncol=length(sequance)) y_d_GJRGARCH11 = y_d - (GJRGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(1/BY) - FROM/BY # corresponding directional forecast and realised direction y_hat_d_GJRGARCH11 = ifelse(GJRGARCH11_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GJRGARCH11),1))==1 , 1, 0) R_Active_GJRGARCH11_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GJRGARCH11*0))+ (BoE_r_f_zoo-(y_hat_d_GJRGARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GJRGARCH11*0))))[2:length(y_hat_d_GJRGARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GJRGARCH11*0))' returns only the R values corresponding to dates present in y_hat_d_GJRGARCH11, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GJRGARCH11_p[,P_number] = R_Active_GJRGARCH11_p_col_zoo for (i in c(1:length(R_Active_GJRGARCH11_p[,P_number]))) {R_Active_GJRGARCH11_p_cumulated[i,P_number] = prod((1+R_Active_GJRGARCH11_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GJRGARCH11_p_col_zoo*0)))[1:i])} } GJRGARCH11_CandD_3D_HighRes = (plot_ly(z=R_Active_GJRGARCH11_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GJRGARCH11 models where 0.45<=P<=0.6", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GJRGARCH11_CandD_3D, filename = "GJRGARCH11_CandD_3D-public-graph") ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework using the GJRGARCH11SVI model (p=0.506 seems best) ###---------------------------------------------------------------------------- p = 0.506 # corresponding directional forecast and realised direction y_hat_d_GJRGARCH11SVI = ifelse(GJRGARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_GJRGARCH11SVI = y_d - (GJRGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has # values on dates corresponding to GJRGARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GJRGARCH11SVI),1))==1 , 1, 0) R_Active_GJRGARCH11SVI_p = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GJRGARCH11SVI*0))+(BoE_r_f_zoo-(y_hat_d_GJRGARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GJRGARCH11SVI*0))))[2:length(y_hat_d_GJRGARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GJRGARCH11SVI*0))' returns only the R values # corresponding to dates present in y_hat_d_GARCH11, which are the ones # in omega (omega couldn't be used because it's not a zoo object) R_Active_GJRGARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_GJRGARCH11SVI_p)) for (i in c(1:length(R_Active_GJRGARCH11SVI_p))) {R_Active_GJRGARCH11SVI_p_cumulated[i] = prod((1+R_Active_GJRGARCH11SVI_p)[1:i])} # plot(R_Active_GJRGARCH11SVI_p_cumulated, type='l') R_cumulated = matrix(,nrow=length(R_Active_GJRGARCH11SVI_p)) for (i in c(1:length(R_Active_GJRGARCH11SVI_p))) {R_cumulated[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_GJRGARCH11SVI_p*0))))[1:i])} # plot(R_cumulated, type='l') plot(zoo(R_Active_GJRGARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_GJRGARCH11SVI[2:length(y_hat_d_GJRGARCH11SVI)]))), type="l",col="red", xlab='Date', main = p, ylab='FTSE index and GJRGARCH11SVI index cumulated') lines(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_GJRGARCH11SVI[2:length(y_hat_d_GJRGARCH11SVI)]))), col="black") lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="green") ##---------------------------------------------------------------------------- ## 3D graph Low Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath sequance = seq(from = 0, to = 1, by = 0.05) R_Active_GJRGARCH11SVI_p = matrix(, nrow=3567, ncol=length(sequance)) R_Active_GJRGARCH11SVI_p_cumulated = matrix(, nrow=3567, ncol=length(sequance)) R_cumulated = matrix(, nrow=3567, ncol=length(sequance)) y_d_GJRGARCH11SVI = y_d - (GJRGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11SVI's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(length(sequance)-1) # corresponding directional forecast and realised direction y_hat_d_GJRGARCH11SVI = ifelse(GJRGARCH11SVI_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GJRGARCH11SVI),1))==1 , 1, 0) R_Active_GJRGARCH11SVI_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GJRGARCH11SVI*0))+(BoE_r_f_zoo-(y_hat_d_GJRGARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GJRGARCH11SVI*0))))[2:length(y_hat_d_GJRGARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GJRGARCH11SVI*0))' returns only the R values corresponding to dates present in y_hat_d_GJRGARCH11SVI, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GJRGARCH11SVI_p[,P_number] = R_Active_GJRGARCH11SVI_p_col_zoo for (i in c(1:length(R_Active_GJRGARCH11SVI_p[,P_number]))) {R_Active_GJRGARCH11SVI_p_cumulated[i,P_number] = prod((1+R_Active_GJRGARCH11SVI_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GJRGARCH11SVI_p_col_zoo*0)))[1:i])} } GJRGARCH11SVI_CandD_3D_LowRes = (plot_ly(z=R_Active_GJRGARCH11SVI_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GJRGARCH11SVI models", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GJRGARCH11SVI_CandD_3D, filename = "GJRGARCH11SVI_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 3D graph High Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath BY = 0.0125 FROM = 0.45 sequance = seq(from = FROM, to = 0.6, by = BY) R_Active_GJRGARCH11SVI_p = matrix(, nrow=3567, ncol=length(sequance)) R_Active_GJRGARCH11SVI_p_cumulated = matrix(, nrow=3567, ncol=length(sequance)) R_cumulated = matrix(, nrow=3567, ncol=length(sequance)) y_d_GJRGARCH11SVI = y_d - (GJRGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11SVI's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(1/BY) - FROM/BY # corresponding directional forecast and realised direction y_hat_d_GJRGARCH11SVI = ifelse(GJRGARCH11SVI_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_GJRGARCH11SVI),1))==1 , 1, 0) R_Active_GJRGARCH11SVI_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_GJRGARCH11SVI*0))+ (BoE_r_f_zoo-(y_hat_d_GJRGARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_GJRGARCH11SVI*0))))[2:length(y_hat_d_GJRGARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_GJRGARCH11SVI*0))' returns only the R values corresponding to dates present in y_hat_d_GJRGARCH11SVI, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_GJRGARCH11SVI_p[,P_number] = R_Active_GJRGARCH11SVI_p_col_zoo for (i in c(1:length(R_Active_GJRGARCH11SVI_p[,P_number]))) {R_Active_GJRGARCH11SVI_p_cumulated[i,P_number] = prod((1+R_Active_GJRGARCH11SVI_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_GJRGARCH11SVI_p_col_zoo*0)))[1:i])} } GJRGARCH11SVI_CandD_3D_HighRes = (plot_ly(z=R_Active_GJRGARCH11SVI_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using GJRGARCH11SVI models where 0.45<=P<=0.6", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(GJRGARCH11SVI_CandD_3D, filename = "GJRGARCH11SVI_CandD_3D-public-graph") ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework using the EGARCH11 model (p=0.499 seems best) ###---------------------------------------------------------------------------- p=0.499 # corresponding directional forecast and realised direction y_hat_d_EGARCH11 = ifelse(EGARCH11_CandD_zoo_no_nas>p,1,0) y_d_EGARCH11 = y_d - (EGARCH11_CandD_zoo_no_nas*0) # This y_d only has # values on dates corresponding to EGARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_EGARCH11),1))==1 , 1, 0) R_Active_EGARCH11_p = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_EGARCH11*0))+(BoE_r_f_zoo-(y_hat_d_EGARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_EGARCH11*0))))[2:length(y_hat_d_EGARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_EGARCH11*0))' returns only the R values # corresponding to dates present in y_hat_d_EGARCH11, which are the ones # in omega (omega couldn't be used because it's not a zoo object) R_Active_EGARCH11_p_cumulated = matrix(,nrow=length(R_Active_EGARCH11_p)) for (i in c(1:length(R_Active_EGARCH11_p))) {R_Active_EGARCH11_p_cumulated[i] = prod((1+R_Active_EGARCH11_p)[1:i])} # plot(R_Active_EGARCH11_p_cumulated, type='l') R_cumulated = matrix(,nrow=length(R_Active_EGARCH11_p)) for (i in c(1:length(R_Active_EGARCH11_p))) {R_cumulated[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_EGARCH11_p*0))))[1:i])} # plot(R_cumulated, type='l') plot(zoo(R_Active_EGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_EGARCH11[2:length(y_hat_d_EGARCH11)]))), type="l",col="red", xlab='Date', main = p, ylab='FTSE index and EGARCH11 index cumulated') lines(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_EGARCH11[2:length(y_hat_d_EGARCH11)]))), col="black") lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="green") ##---------------------------------------------------------------------------- ## 3D graph Low Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath sequance = seq(from = 0, to = 1, by = 0.05) R_Active_EGARCH11_p = matrix(, nrow=3585, ncol=length(sequance)) R_Active_EGARCH11_p_cumulated = matrix(, nrow=3585, ncol=length(sequance)) R_cumulated = matrix(, nrow=3585, ncol=length(sequance)) y_d_EGARCH11 = y_d - (EGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(length(sequance)-1) # corresponding directional forecast and realised direction y_hat_d_EGARCH11 = ifelse(EGARCH11_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_EGARCH11),1))==1 , 1, 0) R_Active_EGARCH11_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_EGARCH11*0))+(BoE_r_f_zoo-(y_hat_d_EGARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_EGARCH11*0))))[2:length(y_hat_d_EGARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_EGARCH11*0))' returns only the R values corresponding to dates present in y_hat_d_EGARCH11, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_EGARCH11_p[,P_number] = R_Active_EGARCH11_p_col_zoo for (i in c(1:length(R_Active_EGARCH11_p[,P_number]))) {R_Active_EGARCH11_p_cumulated[i,P_number] = prod((1+R_Active_EGARCH11_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_EGARCH11_p_col_zoo*0)))[1:i])} } EGARCH11_CandD_3D_LowRes = (plot_ly(z=R_Active_EGARCH11_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using EGARCH11 models", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(EGARCH11_CandD_3D, filename = "EGARCH11_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 3D graph High Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath BY = 0.0125 FROM = 0.45 sequance = seq(from = FROM, to = 0.6, by = BY) R_Active_EGARCH11_p = matrix(, nrow=3585, ncol=length(sequance)) R_Active_EGARCH11_p_cumulated = matrix(, nrow=3585, ncol=length(sequance)) R_cumulated = matrix(, nrow=3585, ncol=length(sequance)) y_d_EGARCH11 = y_d - (EGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(1/BY) - FROM/BY # corresponding directional forecast and realised direction y_hat_d_EGARCH11 = ifelse(EGARCH11_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_EGARCH11),1))==1 , 1, 0) R_Active_EGARCH11_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_EGARCH11*0))+ (BoE_r_f_zoo-(y_hat_d_EGARCH11*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_EGARCH11*0))))[2:length(y_hat_d_EGARCH11)] # note that the trick '(FTSE_R_zoo-(y_hat_d_EGARCH11*0))' returns only the R values corresponding to dates present in y_hat_d_EGARCH11, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_EGARCH11_p[,P_number] = R_Active_EGARCH11_p_col_zoo for (i in c(1:length(R_Active_EGARCH11_p[,P_number]))) {R_Active_EGARCH11_p_cumulated[i,P_number] = prod((1+R_Active_EGARCH11_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_EGARCH11_p_col_zoo*0)))[1:i])} } EGARCH11_CandD_3D_HighRes = (plot_ly(z=R_Active_EGARCH11_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using an EGARCH11 model where 0.45<=P<=0.6", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(EGARCH11_CandD_3D, filename = "EGARCH11_CandD_3D-public-graph") ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework using the EGARCH11-SVI model (p=0.46 seems best) ###---------------------------------------------------------------------------- p=0.46 # corresponding directional forecast and realised direction y_hat_d_EGARCH11SVI = ifelse(EGARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_EGARCH11SVI = y_d - (EGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has # values on dates corresponding to EGARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_EGARCH11SVI),1))==1 , 1, 0) R_Active_p = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_EGARCH11SVI*0))+ (BoE_r_f_zoo-(y_hat_d_EGARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_EGARCH11SVI*0))))[2:length(y_hat_d_EGARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_EGARCH11SVI*0))' returns only the R values # corresponding to dates present in y_hat_d_EGARCH11SVI, which are the ones # in omega (omega couldn't be used because it's not a zoo object) R_Active_p_cumulated = matrix(,nrow=length(R_Active_p)) for (i in c(1:length(R_Active_p))) {R_Active_p_cumulated[i] = prod((1+R_Active_p)[1:i])} # plot(R_Active_p_cumulated, type='l') R_cumulated = matrix(,nrow=length(R_Active_p)) for (i in c(1:length(R_Active_p))) {R_cumulated[i] = prod((1+(FTSE_R_zoo+(BoE_r_f_zoo - (R_Active_p*0))))[1:i])} # plot(R_cumulated, type='l') plot(zoo(R_Active_p_cumulated, as.Date(zoo::index(y_hat_d_EGARCH11SVI[2:length(y_hat_d_EGARCH11SVI)]))), type="l",col="red", xlab='Date', main = p, ylab='FTSE index and EGARCH11SVI index cumulated') lines(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_EGARCH11SVI[2:length(y_hat_d_EGARCH11SVI)]))), col="black") lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="green") ##---------------------------------------------------------------------------- ## 3D graph Low Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath sequance = seq(from = 0, to = 1, by = 0.05) R_Active_EGARCH11SVI_p = matrix(, nrow=3565, ncol=length(sequance)) R_Active_EGARCH11SVI_p_cumulated = matrix(, nrow=3565, ncol=length(sequance)) R_cumulated = matrix(, nrow=3565, ncol=length(sequance)) y_d_EGARCH11SVI = y_d - (EGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11SVI's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(length(sequance)-1) # corresponding directional forecast and realised direction y_hat_d_EGARCH11SVI = ifelse(EGARCH11SVI_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_EGARCH11SVI),1))==1 , 1, 0) R_Active_EGARCH11SVI_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_EGARCH11SVI*0))+(BoE_r_f_zoo-(y_hat_d_EGARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_EGARCH11SVI*0))))[2:length(y_hat_d_EGARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_EGARCH11SVI*0))' returns only the R values corresponding to dates present in y_hat_d_EGARCH11SVI, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_EGARCH11SVI_p[,P_number] = R_Active_EGARCH11SVI_p_col_zoo for (i in c(1:length(R_Active_EGARCH11SVI_p[,P_number]))) {R_Active_EGARCH11SVI_p_cumulated[i,P_number] = prod((1+R_Active_EGARCH11SVI_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_EGARCH11SVI_p_col_zoo*0)))[1:i])} } EGARCH11SVI_CandD_3D_LowRes = (plot_ly(z=R_Active_EGARCH11SVI_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using EGARCH11SVI models", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(EGARCH11SVI_CandD_3D, filename = "EGARCH11SVI_CandD_3D-public-graph") ##---------------------------------------------------------------------------- ## 3D graph High Resolution ##---------------------------------------------------------------------------- # Set the probability above which we would like our investing algorythm to invest in our 3d grath BY = 0.0125 FROM = 0.45 sequance = seq(from = FROM, to = 0.6, by = BY) R_Active_EGARCH11SVI_p = matrix(, nrow=3565, ncol=length(sequance)) R_Active_EGARCH11SVI_p_cumulated = matrix(, nrow=3565, ncol=length(sequance)) R_cumulated = matrix(, nrow=3565, ncol=length(sequance)) y_d_EGARCH11SVI = y_d - (EGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11SVI's. # Set eh probability above which we would like our investing algorythm to invest for(P in sequance) {P_number = 1 + P*(1/BY) - FROM/BY # corresponding directional forecast and realised direction y_hat_d_EGARCH11SVI = ifelse(EGARCH11SVI_CandD_zoo_no_nas>P,1,0) # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_EGARCH11SVI),1))==1 , 1, 0) R_Active_EGARCH11SVI_p_col_zoo = ((lag(omega,1) * ((FTSE_R_zoo-(y_hat_d_EGARCH11SVI*0))+ (BoE_r_f_zoo-(y_hat_d_EGARCH11SVI*0))) + (1-lag(omega,1)) * (BoE_r_f_zoo-(y_hat_d_EGARCH11SVI*0))))[2:length(y_hat_d_EGARCH11SVI)] # note that the trick '(FTSE_R_zoo-(y_hat_d_EGARCH11SVI*0))' returns only the R values corresponding to dates present in y_hat_d_EGARCH11SVI, which are the ones in omega (omega couldn't be used because it's not a zoo object) R_Active_EGARCH11SVI_p[,P_number] = R_Active_EGARCH11SVI_p_col_zoo for (i in c(1:length(R_Active_EGARCH11SVI_p[,P_number]))) {R_Active_EGARCH11SVI_p_cumulated[i,P_number] = prod((1+R_Active_EGARCH11SVI_p[,P_number])[1:i]) R_cumulated[i,P_number] = prod((1+(FTSE_R_zoo-(R_Active_EGARCH11SVI_p_col_zoo*0)))[1:i])} } EGARCH11SVI_CandD_3D_HighRes = (plot_ly(z=R_Active_EGARCH11SVI_p_cumulated, type="scatter3d") %>% layout( title = "Portfolio Investing £1 as per the Active C&D Model Using EGARCH11SVI models where 0.45<=P<=0.6", scene = list( xaxis = list(title = "Investment Threashold"), yaxis = list(title = "Date"), zaxis = list(title = "Portfolio Return") )) %>% add_surface()) # chart_link = api_create(EGARCH11SVI_CandD_3D, filename = "EGARCH11SVI_CandD_3D-public-graph") ###---------------------------------------------------------------------------- ### FTSE Granger and Pesaran (2000)'s framework 2d Graphs put together ###---------------------------------------------------------------------------- # Plot all 2d polts plot(zoo(R_Active_GARCH11_p_cumulated_2d, as.Date(zoo::index(y_hat_d_GARCH11_2d[2:length(y_hat_d_GARCH11_2d)]))), cex.axis=1, type="l",col="red", xlab='Date', ylim=c(0.67,2.05), ylab='£') lines(zoo(R_cumulated_2d, as.Date(zoo::index(y_hat_d_GARCH11_2d[2:length(y_hat_d_GARCH11_2d)]))), col="black") lines(zoo(R_Active_GARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_GARCH11SVI[2:length(y_hat_d_GARCH11SVI)]))), col="orange") lines(zoo(R_Active_GJRGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_GJRGARCH11[2:length(y_hat_d_GJRGARCH11)]))), col="blue") lines(zoo(R_Active_GJRGARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_GJRGARCH11SVI[2:length(y_hat_d_GJRGARCH11SVI)]))), col="magenta") lines(zoo(R_Active_EGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_EGARCH11[2:length(y_hat_d_EGARCH11)]))), col="green") lines(zoo(R_Active_p_cumulated, as.Date(zoo::index(y_hat_d_EGARCH11SVI[2:length(y_hat_d_EGARCH11SVI)]))), col="purple") lines(zoo(R_Active_Naive_p_cumulated, as.Date(zoo::index(y_hat_d_Naive[2:length(y_hat_d_Naive)]))), col="bisque4") legend(lty=1, cex=1, "topleft", col=c("black", "bisque4", "red", "orange", "blue", "magenta", "green", "purple"), legend=c("Buy and hold", "Naïve", "GARCH for psi=0.4900", "GARCH-SVI for psi=0.4935", "GJRGARCH for psi=0.5050", "GJRGARCH-SVI for psi=0.5060", "EGARCH for psi=0.4990", "EGARCH-SVI for psi=0.4600")) ####--------------------------------------------------------------------------- #### SPX1 GARCH models: create, train/fit them and create forecasts ####--------------------------------------------------------------------------- # Set parameters SPX1_roll = length(SPX_dSVI_zoo)-247 # This will also be the number of out-of-sample predictions. N.B.: the 248th # value of R corresponds to 2005-01-03, the 1st trading day out-of-sample, # the first value after 247. ###---------------------------------------------------------------------------- ### SPX1 In-sample SPX1_AR(1)-GARCH(1,1) Model ###--------------------------------------------------------------------------- SPX1_in_sample_GARCH11 = GARCH_model_spec(mod="sGARCH", exreg= NULL) SPX1_in_sample_GARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPX1_in_sample_GARCH11) ###---------------------------------------------------------------------------- ### Create the SPX1_AR(1)-GARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- SPX1_GARCH11_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(SPX1_GARCH11_mu_hat) = c('SPX1_GARCH11_mu_hat') SPX1_GARCH11_sigma_hat_test = zoo(matrix(, nrow=roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(GARCH11_sigma_hat) = c('GARCH11_sigma_hat') for (i in c(1:SPX1_roll)) {SPX1_GARCH11 = GARCH_model_spec(mod="sGARCH", exreg=NULL) try(withTimeout({(SPX1_GARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPX1_GARCH11))}, timeout = 5),silent = TRUE) # the 247th value of R is 2004-12-31. try((SPX1_GARCH11fitforecast = GARCH_model_forecast(mod=SPX1_GARCH11fit)), silent = TRUE) # suppressWarnings(expr) try((SPX1_GARCH11_mu_hat[i]=SPX1_GARCH11fitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPX1_GARCH11_sigma_hat[i]=SPX1_GARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPX1_GARCH11) rm(SPX1_GARCH11fit) rm(SPX1_GARCH11fitforecast) } # fitted(GARCH11fitforecast) SPX_RV_no_SPX1_GARCH11_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPX1_roll)], as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])) -(na.omit(zoo((SPX1_GARCH11_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])))))) # This above is just a neat trick that returns strictly the RV values corresponding to the dates for which GARCH11_sigma_hat values are not NA without any new functions or packages. # Forecast Error, Mean and S.D.: SPX1_GARCH11forecasterror = (na.omit(SPX1_GARCH11_sigma_hat) -SPX_RV_no_SPX1_GARCH11_sigma_hat_na_dated) colnames(SPX1_GARCH11forecasterror) = c("SPX1_GARCH11forecasterror") # plot(zoo(GARCH11forecasterror, as.Date(row.names(GARCH11forecasterror))), type='l', ylab='GARCH11forecasterror', xlab='Date') mean(SPX1_GARCH11forecasterror) sd(SPX1_GARCH11forecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPX1_GARCH11_sigma_hat_na_dated, (na.omit(SPX1_GARCH11_sigma_hat))) ###---------------------------------------------------------------------------- ### SPX1 In-sample SPX1_AR(1)-GARCH(1,1)-SVI Model ###--------------------------------------------------------------------------- SPX1_in_sample_GARCH11SVI = GARCH_model_spec(mod="sGARCH", exreg= as.matrix(SPX_dSVI_zoo[1:(246+1)])) SPX1_in_sample_GARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPX1_in_sample_GARCH11SVI) ###---------------------------------------------------------------------------- ### Create the SPX1_AR(1)-GARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- SPX1_GARCH11SVI_mu_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(SPX1_GARCH11SVI_mu_hat) = c('SPX1_GARCH11_mu_hat') SPX1_GARCH11SVI_sigma_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(GARCH11_sigma_hat) = c('GARCH11_sigma_hat') for (i in c(1:SPX1_roll)) {SPX1_GARCH11SVI = GARCH_model_spec(mod="sGARCH", exreg=as.matrix(SPX_dSVI_zoo[1:(246+i)])) try(withTimeout({(SPX1_GARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPX1_GARCH11SVI))}, timeout = 5),silent = TRUE) try((SPX1_GARCH11SVIfitforecast = GARCH_model_forecast(mod=SPX1_GARCH11SVIfit)), silent = TRUE) try((SPX1_GARCH11SVI_mu_hat[i]=SPX1_GARCH11SVIfitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPX1_GARCH11SVI_sigma_hat[i]=SPX1_GARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPX1_GARCH11SVI) rm(SPX1_GARCH11SVIfit) rm(SPX1_GARCH11SVIfitforecast) } # fitted(GARCH11SVIfitforecast) SPX_RV_no_SPX1_GARCH11SVI_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPX1_roll)], as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])) -(na.omit(zoo((SPX1_GARCH11SVI_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])))))) # Forecast Error, Mean and S.D.: SPX1_GARCH11SVIforecasterror = (na.omit(SPX1_GARCH11SVI_sigma_hat) -SPX_RV_no_SPX1_GARCH11SVI_sigma_hat_na_dated) colnames(SPX1_GARCH11SVIforecasterror) = c("SPX1_GARCH11SVIforecasterror") # plot(zoo(GARCH11SVIforecasterror, as.Date(row.names(GARCH11SVIforecasterror))), type='l', ylab='GARCH11SVIforecasterror', xlab='Date') mean(SPX1_GARCH11SVIforecasterror) sd(SPX1_GARCH11SVIforecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPX1_GARCH11SVI_sigma_hat_na_dated, (na.omit(SPX1_GARCH11SVI_sigma_hat))) # Note that this is the same as the bellow: # sqrt(mean((RV[(249+1):(length(R_vector)+1)] - as.matrix((GARCH11SVIfitforecast@forecast[["sigmaFor"]]))[1:SPX1_roll])^2)) ###---------------------------------------------------------------------------- ### SPX1 In-sample SPX1_AR(1)-GJRGARCH(1,1) Model ###--------------------------------------------------------------------------- SPX1_in_sample_GJRGARCH11 = GARCH_model_spec(mod="gjrGARCH", exreg= NULL) SPX1_in_sample_GJRGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPX1_in_sample_GJRGARCH11) ###---------------------------------------------------------------------------- ### Create the SPX1_AR(1)-GJRGARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- SPX1_GJRGARCH11_mu_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(SPX1_GJRGARCH11_mu_hat) = c('SPX1_GJRGARCH11_mu_hat') SPX1_GJRGARCH11_sigma_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(GJRGARCH11_sigma_hat) = c('GJRGARCH11_sigma_hat') for (i in c(1:SPX1_roll)) {SPX1_GJRGARCH11 = GARCH_model_spec(mod="gjrGARCH", exreg=NULL) try(withTimeout({(SPX1_GJRGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPX1_GJRGARCH11))}, timeout = 5),silent = TRUE) # the 247th value of R is 2004-12-31. try((SPX1_GJRGARCH11fitforecast = GARCH_model_forecast(mod=SPX1_GJRGARCH11fit)), silent = TRUE) # suppressWarnings(expr) try((SPX1_GJRGARCH11_mu_hat[i]=SPX1_GJRGARCH11fitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPX1_GJRGARCH11_sigma_hat[i]=SPX1_GJRGARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPX1_GJRGARCH11) rm(SPX1_GJRGARCH11fit) rm(SPX1_GJRGARCH11fitforecast) } # fitted(GJRGARCH11fitforecast) SPX_RV_no_SPX1_GJRGARCH11_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPX1_roll)], as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])) -(na.omit(zoo((SPX1_GJRGARCH11_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])))))) # Forecast Error, Mean and S.D.: SPX1_GJRGARCH11forecasterror = (na.omit(SPX1_GJRGARCH11_sigma_hat) -SPX_RV_no_SPX1_GJRGARCH11_sigma_hat_na_dated) colnames(SPX1_GJRGARCH11forecasterror) = c("SPX1_GJRGARCH11forecasterror") # plot(zoo(GJRGARCH11forecasterror, as.Date(row.names(GJRGARCH11forecasterror))), type='l', ylab='GJRGARCH11forecasterror', xlab='Date') mean(SPX1_GJRGARCH11forecasterror) sd(SPX1_GJRGARCH11forecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPX1_GJRGARCH11_sigma_hat_na_dated, (na.omit(SPX1_GJRGARCH11_sigma_hat))) ###---------------------------------------------------------------------------- ### SPX1 In-sample SPX1_AR(1)-GJRGARCH(1,1)-SVI Model ###--------------------------------------------------------------------------- SPX1_in_sample_GJRGARCH11SVI = GARCH_model_spec(mod="gjrGARCH", exreg= as.matrix(SPX_dSVI_zoo[1:(246+1)])) SPX1_in_sample_GJRGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPX1_in_sample_GJRGARCH11SVI) ###---------------------------------------------------------------------------- ### Create the SPX1_AR(1)-GJRGARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- SPX1_GJRGARCH11SVI_mu_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(SPX1_GJRGARCH11SVI_mu_hat) = c('SPX1_GJRGARCH11_mu_hat') SPX1_GJRGARCH11SVI_sigma_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(GJRGARCH11_sigma_hat) = c('GJRGARCH11_sigma_hat') for (i in c(1:SPX1_roll)) {SPX1_GJRGARCH11SVI = GARCH_model_spec(mod="gjrGARCH", exreg=as.matrix(SPX_dSVI_zoo[1:(246+i)])) try(withTimeout({(SPX1_GJRGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPX1_GJRGARCH11SVI))}, timeout = 5),silent = TRUE) try((SPX1_GJRGARCH11SVIfitforecast = GARCH_model_forecast(mod=SPX1_GJRGARCH11SVIfit)), silent = TRUE) try((SPX1_GJRGARCH11SVI_mu_hat[i]=SPX1_GJRGARCH11SVIfitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPX1_GJRGARCH11SVI_sigma_hat[i]=SPX1_GJRGARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPX1_GJRGARCH11SVI) rm(SPX1_GJRGARCH11SVIfit) rm(SPX1_GJRGARCH11SVIfitforecast) } # fitted(GJRGARCH11SVIfitforecast) SPX_RV_no_SPX1_GJRGARCH11SVI_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPX1_roll)], as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])) -(na.omit(zoo((SPX1_GJRGARCH11SVI_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])))))) # Forecast Error, Mean and S.D.: SPX1_GJRGARCH11SVIforecasterror = (na.omit(SPX1_GJRGARCH11SVI_sigma_hat) -SPX_RV_no_SPX1_GJRGARCH11SVI_sigma_hat_na_dated) colnames(SPX1_GJRGARCH11SVIforecasterror) = c("SPX1_GJRGARCH11SVIforecasterror") # plot(zoo(GJRGARCH11SVIforecasterror, as.Date(row.names(GJRGARCH11SVIforecasterror))), type='l', ylab='GJRGARCH11SVIforecasterror', xlab='Date') mean(SPX1_GJRGARCH11SVIforecasterror) sd(SPX1_GJRGARCH11SVIforecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPX1_GJRGARCH11SVI_sigma_hat_na_dated, (na.omit(SPX1_GJRGARCH11SVI_sigma_hat))) ###---------------------------------------------------------------------------- ### SPX1 In-sample SPX1_AR(1)-EGARCH(1,1) Model ###--------------------------------------------------------------------------- SPX1_in_sample_EGARCH11 = GARCH_model_spec(mod="eGARCH", exreg= NULL) SPX1_in_sample_EGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPX1_in_sample_EGARCH11) ###---------------------------------------------------------------------------- ### Create the SPX1_AR(1)-EGARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- SPX1_EGARCH11_mu_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(SPX1_EGARCH11_mu_hat) = c('SPX1_EGARCH11_mu_hat') SPX1_EGARCH11_sigma_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(EGARCH11_sigma_hat) = c('EGARCH11_sigma_hat') for (i in c(1:SPX1_roll)) {SPX1_EGARCH11 = GARCH_model_spec(mod="eGARCH", exreg=NULL) try(withTimeout({(SPX1_EGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPX1_EGARCH11))}, timeout = 5),silent = TRUE) # the 247th value of R is 2004-12-31. try((SPX1_EGARCH11fitforecast = GARCH_model_forecast(mod=SPX1_EGARCH11fit)), silent = TRUE) # suppressWarnings(expr) try((SPX1_EGARCH11_mu_hat[i]=SPX1_EGARCH11fitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPX1_EGARCH11_sigma_hat[i]=SPX1_EGARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPX1_EGARCH11) rm(SPX1_EGARCH11fit) rm(SPX1_EGARCH11fitforecast) } # fitted(EGARCH11fitforecast) SPX_RV_no_SPX1_EGARCH11_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPX1_roll)], as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])) -(na.omit(zoo((SPX1_EGARCH11_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])))))) # Forecast Error, Mean and S.D.: SPX1_EGARCH11forecasterror = (na.omit(SPX1_EGARCH11_sigma_hat) -SPX_RV_no_SPX1_EGARCH11_sigma_hat_na_dated) colnames(SPX1_EGARCH11forecasterror) = c("SPX1_EGARCH11forecasterror") # plot(zoo(EGARCH11forecasterror, as.Date(row.names(EGARCH11forecasterror))), type='l', ylab='EGARCH11forecasterror', xlab='Date') mean(SPX1_EGARCH11forecasterror) sd(SPX1_EGARCH11forecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPX1_EGARCH11_sigma_hat_na_dated, (na.omit(SPX1_EGARCH11_sigma_hat))) ###---------------------------------------------------------------------------- ### SPX1 In-sample SPX1_AR(1)-EGARCH(1,1)-SVI Model ###--------------------------------------------------------------------------- SPX1_in_sample_EGARCH11SVI = GARCH_model_spec(mod="eGARCH", exreg= as.matrix(SPX_dSVI_zoo[1:(246+1)])) SPX1_in_sample_EGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPX1_in_sample_EGARCH11SVI) ###---------------------------------------------------------------------------- ### Create the SPX1_AR(1)-EGARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- SPX1_EGARCH11SVI_mu_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(SPX1_EGARCH11SVI_mu_hat) = c('SPX1_EGARCH11SVI_mu_hat') SPX1_EGARCH11SVI_sigma_hat = zoo(matrix(, nrow=SPX1_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPX1_roll)])) colnames(EGARCH11SVI_sigma_hat) = c('EGARCH11SVI_sigma_hat') for (i in c(1:SPX1_roll)) {SPX1_EGARCH11SVI = GARCH_model_spec(mod="eGARCH", exreg=as.matrix(SPX_dSVI_zoo[1:(246+i)])) try(withTimeout({(SPX1_EGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPX1_EGARCH11SVI))}, timeout = 5),silent = TRUE) try((SPX1_EGARCH11SVIfitforecast = GARCH_model_forecast(mod=SPX1_EGARCH11SVIfit)), silent = TRUE) try((SPX1_EGARCH11SVI_mu_hat[i]=SPX1_EGARCH11SVIfitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPX1_EGARCH11SVI_sigma_hat[i]=SPX1_EGARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPX1_EGARCH11SVI) rm(SPX1_EGARCH11SVIfit) rm(SPX1_EGARCH11SVIfitforecast) } SPX_RV_no_SPX1_EGARCH11SVI_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPX1_roll)], as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])) -(na.omit(zoo((SPX1_EGARCH11SVI_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPX1_roll)])))))) # Forecast Error, Mean and S.D.: SPX1_EGARCH11SVIforecasterror = (na.omit(SPX1_EGARCH11SVI_sigma_hat) -SPX_RV_no_SPX1_EGARCH11SVI_sigma_hat_na_dated) colnames(SPX1_EGARCH11SVIforecasterror) = c("SPX1_EGARCH11SVIforecasterror") # plot(zoo(EGARCH11SVIforecasterror, as.Date(row.names(EGARCH11SVIforecasterror))), type='l', ylab='EGARCH11SVIforecasterror', xlab='Date') mean(SPX1_EGARCH11SVIforecasterror) sd(SPX1_EGARCH11SVIforecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPX1_EGARCH11SVI_sigma_hat_na_dated, (na.omit(SPX1_EGARCH11SVI_sigma_hat))) ###--------------------------------------------------------------------------- ### s.d. forecase D-M tests ###--------------------------------------------------------------------------- print("This function implements the modified test proposed by Harvey, Leybourne and Newbold (1997). The null hypothesis is that the two methods have the same forecast accuracy. For alternative=less, the alternative hypothesis is that method 2 is less accurate than method 1. For alternative=greater, the alternative hypothesis is that method 2 is more accurate than method 1. For alternative=two.sided, the alternative hypothesis is that method 1 and method 2 have different levels of accuracy.") print("Diebold and Mariano test SPX1_GARCH11 with and without SVI") SPX1_GARCH11forecasterror_dm = SPX1_GARCH11forecasterror - (SPX1_GARCH11SVIforecasterror*0) SPX1_GARCH11SVIforecasterror_dm = SPX1_GARCH11SVIforecasterror - (SPX1_GARCH11forecasterror*0) SPX1_DM_Test_GARCH = dm.test(matrix(SPX1_GARCH11forecasterror_dm), matrix(SPX1_GARCH11SVIforecasterror_dm), alternative = "less") print("Diebold and Mariano test SPX1_GJRGARCH11 with and without SVI") SPX1_GJRGARCH11forecasterror_dm = SPX1_GJRGARCH11forecasterror - (SPX1_GJRGARCH11SVIforecasterror*0) SPX1_GJRGARCH11SVIforecasterror_dm = SPX1_GJRGARCH11SVIforecasterror - (SPX1_GJRGARCH11forecasterror*0) SPX1_DM_Test_GJRARCH = dm.test(matrix(SPX1_GJRGARCH11forecasterror_dm), matrix(SPX1_GJRGARCH11SVIforecasterror_dm), alternative = "less") print("Diebold and Mariano test SPX1_EGARCH11 with and without SVI") SPX1_EGARCH11forecasterror_dm = SPX1_EGARCH11forecasterror - (SPX1_EGARCH11SVIforecasterror*0) SPX1_EGARCH11SVIforecasterror_dm = SPX1_EGARCH11SVIforecasterror - (SPX1_EGARCH11forecasterror*0) SPX1_DM_Test_EGARCH = dm.test(matrix(SPX1_EGARCH11forecasterror_dm), matrix(SPX1_EGARCH11SVIforecasterror_dm), alternative = "less") ####--------------------------------------------------------------------------- #### SPX1 estimates of the probability of a positive return ####--------------------------------------------------------------------------- ###---------------------------------------------------------------------------- ### SPX1 C&D, Naive ###---------------------------------------------------------------------------- ##----------------------------------------------------------------------------- ## Naive-Model and its forecast error statistics ##----------------------------------------------------------------------------- # Naive-Model's Indicator function according to the GARCH11 Model: SPX_Naive_I = ifelse(SPX_R_matrix>0 , 1 , 0) # Naive Model: SPX_Naive=(1:(length(SPX_R_matrix))) for(t in c(1:(length(SPX_R_matrix)))) {SPX_Naive[t] = (1/t) * sum(SPX_R_matrix[1:t])} # Note that the naive model provides the probability of aa positive return in # the next time period and therefore spams from 2004-01-06 to 2019-03-13. Naive_zoo = zoo(SPX_Naive, as.Date(rownames(as.matrix(SPX_R_zoo)))) ##----------------------------------------------------------------------------- ## SPX1 C&D's GARCH models with and without SVI ## (Model independent variables' construction) ##----------------------------------------------------------------------------- # mean of return up to time 'k' SPX_R_mu=(1:length(SPX_R_matrix)) for (i in c(1:length(SPX_R_matrix))){SPX_R_mu[i]=mean(SPX_R_matrix[1:i])} # standard deviation of return up to time 'k'. # Note that its 1st value is NA since there is no standard deviation for a constant (according to R). SPX_R_sigma=(1:length(SPX_R_matrix)) for (i in c(1:length(SPX_R_matrix))){R_sigma[i]=sd(SPX_R_matrix[1:i])} SPX_R_sigma[1]=0 # Since the variance of a constant is 0. #------------------------------------------------------------------------------ # SPX1 GARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GARCH11 Model: SPX1_GARCH11_CandD_I = matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GARCH11_CandD_I_k= matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GARCH11_CandD_I_t = matrix( - (SPX1_GARCH11_mu_hat/SPX1_GARCH11_sigma_hat)) for(t in c(1:SPX1_roll)) {for (k in c(1:t)) {SPX1_GARCH11_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPX1_GARCH11_mu_hat[k])/SPX1_GARCH11_sigma_hat[k]) <=SPX1_GARCH11_CandD_I_t[t+1], 1,0) # This will also be the number of out-of-sample predictions. N.B.: the 248th value of SPX_R_zoo corresponds to 2005-01-03, the 1st trading day out-of-sample, the first value after 252. # Note that we have some missing values due to the model not always managing # to converge to estimates of sigma and mu; since we need the t+1 model # estimates to compute its CandD_I_k, we also loose its t'th value for # each model's missing value. # We also los the last value (the SPX1_roll'th value) for the same reason. SPX1_GARCH11_CandD_I[k,t] = ifelse((is.na(SPX1_GARCH11_CandD_I_k[k,t])), NA, (sum(SPX1_GARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GARCH11 Model: SPX1_GARCH11_CandD=(1:(SPX1_roll-1)) for(i in c(1:(SPX1_roll-1))) {SPX1_GARCH11_CandD[i] = 1 - ((SPX1_GARCH11_CandD_I[i,i])/ length(na.omit(SPX1_GARCH11_CandD_I[1:i,i])))} SPX1_GARCH11_CandD_zoo = zoo(SPX1_GARCH11_CandD, as.Date(SPX_Dates[(248+1):(248+(SPX1_roll-1))])) # This zoo object has missing values. SPX1_GARCH11_CandD_zoo_no_nas=zoo(na.omit(SPX1_GARCH11_CandD_zoo)) # rm(SPX1_GARCH11_CandD_I_t) # Cleaning datasets # rm(SPX1_GARCH11_CandD_I_k) # rm(SPX1_GARCH11_CandD_I) #------------------------------------------------------------------------------ # SPX1 GARCH11SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GARCH11SVI Model: SPX1_GARCH11SVI_CandD_I = matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GARCH11SVI_CandD_I_k= matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GARCH11SVI_CandD_I_t = matrix( - (SPX1_GARCH11SVI_mu_hat/SPX1_GARCH11SVI_sigma_hat)) for(t in c(1:SPX1_roll)) {for (k in c(1:t)) {SPX1_GARCH11SVI_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPX1_GARCH11SVI_mu_hat[k])/SPX1_GARCH11SVI_sigma_hat[k]) <=SPX1_GARCH11SVI_CandD_I_t[t+1], 1,0) SPX1_GARCH11SVI_CandD_I[k,t] = ifelse((is.na(SPX1_GARCH11SVI_CandD_I_k[k,t])), NA, (sum(SPX1_GARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GARCH11SVI Model: SPX1_GARCH11SVI_CandD=(1:(SPX1_roll-1)) for(i in c(1:(SPX1_roll-1))) {SPX1_GARCH11SVI_CandD[i] = 1 - ((SPX1_GARCH11SVI_CandD_I[i,i])/ length(na.omit(SPX1_GARCH11SVI_CandD_I[1:i,i])))} SPX1_GARCH11SVI_CandD_zoo = zoo(SPX1_GARCH11SVI_CandD, as.Date(SPX_Dates[(248+1):(248+(SPX1_roll-1))])) # This zoo object has missing values. SPX1_GARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(SPX1_GARCH11SVI_CandD_zoo)) # rm(SPX1_GARCH11SVI_CandD_I_t) # Cleaning datasets # rm(SPX1_GARCH11SVI_CandD_I_k) # rm(SPX1_GARCH11SVI_CandD_I) #------------------------------------------------------------------------------ # SPX1 GJRGARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GJRGARCH11 Model: SPX1_GJRGARCH11_CandD_I = matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GJRGARCH11_CandD_I_k= matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GJRGARCH11_CandD_I_t = matrix( - (SPX1_GJRGARCH11_mu_hat/SPX1_GJRGARCH11_sigma_hat)) for(t in c(1:SPX1_roll)) {for (k in c(1:t)) {SPX1_GJRGARCH11_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPX1_GJRGARCH11_mu_hat[k])/SPX1_GJRGARCH11_sigma_hat[k]) <=SPX1_GJRGARCH11_CandD_I_t[t+1], 1,0) # This will also be the number of out-of-sample predictions. N.B.: the 248th value of SPX_R_zoo corresponds to 2005-01-03, the 1st trading day out-of-sample, the first value after 252. # Note that we have some missing values due to the model not always managing # to converge to estimates of sigma and mu; since we need the t+1 model # estimates to compute its CandD_I_k, we also loose its t'th value for # each model's missing value. # We also los the last value (the SPX1_roll'th value) for the same reason. SPX1_GJRGARCH11_CandD_I[k,t] = ifelse((is.na(SPX1_GJRGARCH11_CandD_I_k[k,t])), NA, (sum(SPX1_GJRGARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GJRGARCH11 Model: SPX1_GJRGARCH11_CandD=(1:(SPX1_roll-1)) for(i in c(1:(SPX1_roll-1))) {SPX1_GJRGARCH11_CandD[i] = 1 - ((SPX1_GJRGARCH11_CandD_I[i,i])/ length(na.omit(SPX1_GJRGARCH11_CandD_I[1:i,i])))} SPX1_GJRGARCH11_CandD_zoo = zoo(SPX1_GJRGARCH11_CandD, as.Date(SPX_Dates[(248+1):(248+(SPX1_roll-1))])) # This zoo object has missing values. SPX1_GJRGARCH11_CandD_zoo_no_nas=zoo(na.omit(SPX1_GJRGARCH11_CandD_zoo)) # rm(SPX1_GJRGARCH11_CandD_I_t) # Cleaning datasets # rm(SPX1_GJRGARCH11_CandD_I_k) # rm(SPX1_GJRGARCH11_CandD_I) #------------------------------------------------------------------------------ # SPX1 GJRGARCH11SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GJRGARCH11SVI Model: SPX1_GJRGARCH11SVI_CandD_I = matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GJRGARCH11SVI_CandD_I_k= matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_GJRGARCH11SVI_CandD_I_t = matrix( - (SPX1_GJRGARCH11SVI_mu_hat/SPX1_GJRGARCH11SVI_sigma_hat)) for(t in c(1:SPX1_roll)) {for (k in c(1:t)) {SPX1_GJRGARCH11SVI_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPX1_GJRGARCH11SVI_mu_hat[k])/SPX1_GJRGARCH11SVI_sigma_hat[k]) <=SPX1_GJRGARCH11SVI_CandD_I_t[t+1], 1,0) SPX1_GJRGARCH11SVI_CandD_I[k,t] = ifelse((is.na(SPX1_GJRGARCH11SVI_CandD_I_k[k,t])), NA, (sum(SPX1_GJRGARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GJRGARCH11SVI Model: SPX1_GJRGARCH11SVI_CandD=(1:(SPX1_roll-1)) for(i in c(1:(SPX1_roll-1))) {SPX1_GJRGARCH11SVI_CandD[i] = 1 - ((SPX1_GJRGARCH11SVI_CandD_I[i,i])/ length(na.omit(SPX1_GJRGARCH11SVI_CandD_I[1:i,i])))} SPX1_GJRGARCH11SVI_CandD_zoo = zoo(SPX1_GJRGARCH11SVI_CandD, as.Date(SPX_Dates[(248+1):(248+(SPX1_roll-1))])) # This zoo object has missing values. SPX1_GJRGARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(SPX1_GJRGARCH11SVI_CandD_zoo)) # rm(SPX1_GJRGARCH11SVI_CandD_I_t) # Cleaning datasets # rm(SPX1_GJRGARCH11SVI_CandD_I_k) # rm(SPX1_GJRGARCH11SVI_CandD_I) #------------------------------------------------------------------------------ # SPX1 EGARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the EGARCH11 Model: SPX1_EGARCH11_CandD_I = matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_EGARCH11_CandD_I_k= matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_EGARCH11_CandD_I_t = matrix( - (SPX1_EGARCH11_mu_hat/SPX1_EGARCH11_sigma_hat)) for(t in c(1:SPX1_roll)) {for (k in c(1:t)) {SPX1_EGARCH11_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPX1_EGARCH11_mu_hat[k])/SPX1_EGARCH11_sigma_hat[k]) <=SPX1_EGARCH11_CandD_I_t[t+1], 1,0) # This will also be the number of out-of-sample predictions. N.B.: the 248th value of SPX_R_zoo corresponds to 2005-01-03, the 1st trading day out-of-sample, the first value after 252. # Note that we have some missing values due to the model not always managing # to converge to estimates of sigma and mu; since we need the t+1 model # estimates to compute its CandD_I_k, we also loose its t'th value for # each model's missing value. # We also los the last value (the SPX1_roll'th value) for the same reason. SPX1_EGARCH11_CandD_I[k,t] = ifelse((is.na(SPX1_EGARCH11_CandD_I_k[k,t])), NA, (sum(SPX1_EGARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the EGARCH11 Model: SPX1_EGARCH11_CandD=(1:(SPX1_roll-1)) for(i in c(1:(SPX1_roll-1))) {SPX1_EGARCH11_CandD[i] = 1 - ((SPX1_EGARCH11_CandD_I[i,i])/ length(na.omit(SPX1_EGARCH11_CandD_I[1:i,i])))} SPX1_EGARCH11_CandD_zoo = zoo(SPX1_EGARCH11_CandD, as.Date(SPX_Dates[(248+1):(248+(SPX1_roll-1))])) # This zoo object has missing values. SPX1_EGARCH11_CandD_zoo_no_nas=zoo(na.omit(SPX1_EGARCH11_CandD_zoo)) # rm(SPX1_EGARCH11_CandD_I_t) # Cleaning datasets # rm(SPX1_EGARCH11_CandD_I_k) # rm(SPX1_EGARCH11_CandD_I) #------------------------------------------------------------------------------ # SPX1 EGARCH11SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the EGARCH11SVI Model: SPX1_EGARCH11SVI_CandD_I = matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_EGARCH11SVI_CandD_I_k= matrix(, nrow=SPX1_roll, ncol=SPX1_roll) SPX1_EGARCH11SVI_CandD_I_t = matrix( - (SPX1_EGARCH11SVI_mu_hat/SPX1_EGARCH11SVI_sigma_hat)) for(t in c(1:SPX1_roll)) {for (k in c(1:t)) {SPX1_EGARCH11SVI_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPX1_EGARCH11SVI_mu_hat[k])/SPX1_EGARCH11SVI_sigma_hat[k]) <=SPX1_EGARCH11SVI_CandD_I_t[t+1], 1,0) SPX1_EGARCH11SVI_CandD_I[k,t] = ifelse((is.na(SPX1_EGARCH11SVI_CandD_I_k[k,t])), NA, (sum(SPX1_EGARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the EGARCH11SVI Model: SPX1_EGARCH11SVI_CandD=(1:(SPX1_roll-1)) for(i in c(1:(SPX1_roll-1))) {SPX1_EGARCH11SVI_CandD[i] = 1 - ((SPX1_EGARCH11SVI_CandD_I[i,i])/ length(na.omit(SPX1_EGARCH11SVI_CandD_I[1:i,i])))} SPX1_EGARCH11SVI_CandD_zoo = zoo(SPX1_EGARCH11SVI_CandD, as.Date(SPX_Dates[(248+1):(248+(SPX1_roll-1))])) # This zoo object has missing values. SPX1_EGARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(SPX1_EGARCH11SVI_CandD_zoo)) # rm(SPX1_EGARCH11SVI_CandD_I_t) # Cleaning datasets # rm(SPX1_EGARCH11SVI_CandD_I_k) # rm(SPX1_EGARCH11SVI_CandD_I) ##----------------------------------------------------------------------------- ## SPX1 compare the predictive performance of each model ## (forecast error mean, sd, Brier Scores and Diebold&Mariano statistics) ##----------------------------------------------------------------------------- # # mean of the probabilistic forecast errors derived from each model SPX1_Observed_pi= ifelse(SPX_R_matrix>0,1,0) SPX1_Observed_pi_zoo = zoo(SPX1_Observed_pi, as.Date(SPX_Dates)) SPX1_Naive_pi_error = SPX1_Naive_zoo - SPX1_Observed_pi_zoo SPX1_GARCH11_pi_error = SPX1_GARCH11_CandD_zoo_no_nas - SPX1_Observed_pi_zoo SPX1_GARCH11SVI_pi_error = SPX1_GARCH11SVI_CandD_zoo_no_nas - SPX1_Observed_pi_zoo SPX1_GJRGARCH11_pi_error = SPX1_GJRGARCH11_CandD_zoo_no_nas - SPX1_Observed_pi_zoo SPX1_GJRGARCH11SVI_pi_error = SPX1_GJRGARCH11SVI_CandD_zoo_no_nas - SPX1_Observed_pi_zoo SPX1_EGARCH11_pi_error = SPX1_EGARCH11_CandD_zoo_no_nas - SPX1_Observed_pi_zoo SPX1_EGARCH11SVI_pi_error = SPX1_EGARCH11SVI_CandD_zoo_no_nas - SPX1_Observed_pi_zoo mean(SPX1_Naive_pi_error) sd(SPX1_Naive_pi_error) mean(SPX1_GARCH11_pi_error) sd(SPX1_GARCH11_pi_error) mean(SPX1_GARCH11SVI_pi_error) sd(SPX1_GARCH11SVI_pi_error) mean(SPX1_GJRGARCH11_pi_error) sd(SPX1_GJRGARCH11_pi_error) mean(SPX1_GJRGARCH11SVI_pi_error) sd(SPX1_GJRGARCH11SVI_pi_error) mean(SPX1_EGARCH11_pi_error) sd(SPX1_EGARCH11_pi_error) mean(SPX1_EGARCH11SVI_pi_error) sd(SPX1_EGARCH11SVI_pi_error) # # SPX1_Brier scores of the probabilistic forecast errors derived from each model SPX1_Naive_pi_error_Brier_score = (1/length(SPX1_Naive_pi_error))*sum(SPX1_Naive_pi_error^2) show(SPX1_Naive_pi_error_Brier_score) SPX1_GARCH11_pi_error_Brier_score = (1/length(SPX1_GARCH11_pi_error))*sum(SPX1_GARCH11_pi_error^2) show(SPX1_GARCH11_pi_error_Brier_score) SPX1_GARCH11SVI_pi_error_Brier_score = (1/length(SPX1_GARCH11SVI_pi_error))*sum(SPX1_GARCH11SVI_pi_error^2) show(SPX1_GARCH11SVI_pi_error_Brier_score) SPX1_GJRGARCH11_pi_error_Brier_score = (1/length(SPX1_GJRGARCH11_pi_error))*sum(SPX1_GJRGARCH11_pi_error^2) show(SPX1_GJRGARCH11_pi_error_Brier_score) SPX1_GJRGARCH11SVI_pi_error_Brier_score = (1/length(SPX1_GJRGARCH11SVI_pi_error))*sum(SPX1_GJRGARCH11SVI_pi_error^2) show(SPX1_GJRGARCH11SVI_pi_error_Brier_score) SPX1_EGARCH11_pi_error_Brier_score = (1/length(SPX1_EGARCH11_pi_error))*sum(SPX1_EGARCH11_pi_error^2) show(SPX1_EGARCH11_pi_error_Brier_score) SPX1_EGARCH11SVI_pi_error_Brier_score = (1/length(SPX1_EGARCH11SVI_pi_error))*sum(SPX1_EGARCH11SVI_pi_error^2) show(SPX1_EGARCH11SVI_pi_error_Brier_score) # # SPX1_Diebold&Mariano statistics # Here the alternative hypothesis is that method 2 is more accurate than method 1; remember that a small p-value indicates strong evidence against the Null Hypothesis. SPX1_GARCH11_pi_error_dm = SPX1_GARCH11_pi_error - (SPX1_GARCH11SVI_pi_error*0) SPX1_GARCH11SVI_pi_error_dm = SPX1_GARCH11SVI_pi_error - (SPX1_GARCH11_pi_error*0) SPX1_GARCH11_dm_test = dm.test(matrix(SPX1_GARCH11_pi_error_dm), matrix(SPX1_GARCH11SVI_pi_error_dm), alternative = "greater") SPX1_GJRGARCH11_pi_error_dm = SPX1_GJRGARCH11_pi_error - (SPX1_GJRGARCH11SVI_pi_error*0) SPX1_GJRGARCH11SVI_pi_error_dm = SPX1_GJRGARCH11SVI_pi_error - (SPX1_GJRGARCH11_pi_error*0) SPX1_GJRGARCH11_dm_test = dm.test(matrix(SPX1_GJRGARCH11_pi_error_dm), matrix(SPX1_GJRGARCH11SVI_pi_error_dm), alternative = c("greater")) SPX1_EGARCH11_pi_error_dm = SPX1_EGARCH11_pi_error - (SPX1_EGARCH11SVI_pi_error*0) SPX1_EGARCH11SVI_pi_error_dm = SPX1_EGARCH11SVI_pi_error - (SPX1_EGARCH11_pi_error*0) SPX1_EGARCH11_dm_test = dm.test(matrix(SPX1_EGARCH11_pi_error_dm), matrix(SPX1_EGARCH11SVI_pi_error_dm), alternative = c("greater")) ####---------------------------------------------------------------------------- #### SPX1's Financial significance ####---------------------------------------------------------------------------- # indicator of the realised direction of the return on the S&P 500 index y_d = ifelse(SPX_R_zoo>0,1,0) # Set the probability threashold at which to invest in the index in our 2d graphs: for (p in c(0.49, 0.495, 0.5, 0.505, 0.51)){ ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework using the GARCH11 model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPX1_GARCH11 = ifelse(SPX1_GARCH11_CandD_zoo_no_nas>p,1,0) y_d_SPX1_GARCH11 = y_d - (SPX1_GARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPX1_GARCH11),1))==1 , 1, 0) R_Active_SPX1_GARCH11_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPX1_GARCH11*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPX1_GARCH11*0))))[2:length(y_hat_d_SPX1_GARCH11)] R_Active_SPX1_GARCH11_p_cumulated = matrix(,nrow=length(R_Active_SPX1_GARCH11_p)) for (i in c(1:length(R_Active_SPX1_GARCH11_p))) {R_Active_SPX1_GARCH11_p_cumulated[i] = prod((1+R_Active_SPX1_GARCH11_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPX1_GARCH11_p)) for (i in c(1:length(R_Active_SPX1_GARCH11_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPX1_GARCH11_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework using the GARCH11-SVI model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPX1_GARCH11SVI = ifelse(SPX1_GARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_SPX1_GARCH11SVI = y_d - (SPX1_GARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPX1_GARCH11SVI),1))==1 , 1, 0) R_Active_SPX1_GARCH11SVI_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPX1_GARCH11SVI*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPX1_GARCH11SVI*0))))[2:length(y_hat_d_SPX1_GARCH11SVI)] R_Active_SPX1_GARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_SPX1_GARCH11SVI_p)) for (i in c(1:length(R_Active_SPX1_GARCH11SVI_p))) {R_Active_SPX1_GARCH11SVI_p_cumulated[i] = prod((1+R_Active_SPX1_GARCH11SVI_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPX1_GARCH11SVI_p)) for (i in c(1:length(R_Active_SPX1_GARCH11SVI_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPX1_GARCH11SVI_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework using the GJRGARCH11 model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPX1_GJRGARCH11 = ifelse(SPX1_GJRGARCH11_CandD_zoo_no_nas>p,1,0) y_d_SPX1_GJRGARCH11 = y_d - (SPX1_GJRGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPX1_GJRGARCH11),1))==1 , 1, 0) R_Active_SPX1_GJRGARCH11_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPX1_GJRGARCH11*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPX1_GJRGARCH11*0))))[2:length(y_hat_d_SPX1_GJRGARCH11)] R_Active_SPX1_GJRGARCH11_p_cumulated = matrix(,nrow=length(R_Active_SPX1_GJRGARCH11_p)) for (i in c(1:length(R_Active_SPX1_GJRGARCH11_p))) {R_Active_SPX1_GJRGARCH11_p_cumulated[i] = prod((1+R_Active_SPX1_GJRGARCH11_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPX1_GJRGARCH11_p)) for (i in c(1:length(R_Active_SPX1_GJRGARCH11_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPX1_GJRGARCH11_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework using the GJRGARCH11-SVI model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPX1_GJRGARCH11SVI = ifelse(SPX1_GJRGARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_SPX1_GJRGARCH11SVI = y_d - (SPX1_GJRGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPX1_GJRGARCH11SVI),1))==1 , 1, 0) R_Active_SPX1_GJRGARCH11SVI_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPX1_GJRGARCH11SVI*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPX1_GJRGARCH11SVI*0))))[2:length(y_hat_d_SPX1_GJRGARCH11SVI)] R_Active_SPX1_GJRGARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_SPX1_GJRGARCH11SVI_p)) for (i in c(1:length(R_Active_SPX1_GJRGARCH11SVI_p))) {R_Active_SPX1_GJRGARCH11SVI_p_cumulated[i] = prod((1+R_Active_SPX1_GJRGARCH11SVI_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPX1_GJRGARCH11SVI_p)) for (i in c(1:length(R_Active_SPX1_GJRGARCH11SVI_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPX1_GJRGARCH11SVI_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework using the EGARCH11 model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPX1_EGARCH11 = ifelse(SPX1_EGARCH11_CandD_zoo_no_nas>p,1,0) y_d_SPX1_EGARCH11 = y_d - (SPX1_EGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPX1_EGARCH11),1))==1 , 1, 0) R_Active_SPX1_EGARCH11_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPX1_EGARCH11*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPX1_EGARCH11*0))))[2:length(y_hat_d_SPX1_EGARCH11)] R_Active_SPX1_EGARCH11_p_cumulated = matrix(,nrow=length(R_Active_SPX1_EGARCH11_p)) for (i in c(1:length(R_Active_SPX1_EGARCH11_p))) {R_Active_SPX1_EGARCH11_p_cumulated[i] = prod((1+R_Active_SPX1_EGARCH11_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPX1_EGARCH11_p)) for (i in c(1:length(R_Active_SPX1_EGARCH11_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPX1_EGARCH11_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework using the EGARCH11-SVI model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPX1_EGARCH11SVI = ifelse(SPX1_EGARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_SPX1_EGARCH11SVI = y_d - (SPX1_EGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPX1_EGARCH11SVI),1))==1 , 1, 0) R_Active_SPX1_EGARCH11SVI_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPX1_EGARCH11SVI*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPX1_EGARCH11SVI*0))))[2:length(y_hat_d_SPX1_EGARCH11SVI)] R_Active_SPX1_EGARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_SPX1_EGARCH11SVI_p)) for (i in c(1:length(R_Active_SPX1_EGARCH11SVI_p))) {R_Active_SPX1_EGARCH11SVI_p_cumulated[i] = prod((1+R_Active_SPX1_EGARCH11SVI_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPX1_EGARCH11SVI_p)) for (i in c(1:length(R_Active_SPX1_EGARCH11SVI_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPX1_EGARCH11SVI_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPX1 Granger and Pesaran (2000)'s framework 2d Graphs put together ###---------------------------------------------------------------------------- # Plot all 2d polts plot(zoo(R_Active_SPX1_GARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_SPX1_GARCH11[2:length(y_hat_d_SPX1_GARCH11)]))), cex.axis=1, type="l",col="red", xlab='Date', ylim=c(0,3), ylab='SPX1 strategy gain ($)', main=str_c("SPX1 Strategy for psi ", p)) lines(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_SPX1_GARCH11[2:length(y_hat_d_SPX1_GARCH11)]))), col="black") lines(zoo(R_Active_SPX1_GARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_SPX1_GARCH11SVI[2:length(y_hat_d_SPX1_GARCH11SVI)]))), col="orange") lines(zoo(R_Active_SPX1_GJRGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_SPX1_GJRGARCH11[2:length(y_hat_d_SPX1_GJRGARCH11)]))), col="blue") lines(zoo(R_Active_SPX1_GJRGARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_SPX1_GJRGARCH11SVI[2:length(y_hat_d_SPX1_GJRGARCH11SVI)]))), col="magenta") lines(zoo(R_Active_SPX1_EGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_SPX1_EGARCH11[2:length(y_hat_d_SPX1_EGARCH11)]))), col="green") lines(zoo(R_Active_SPX1_EGARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_SPX1_EGARCH11SVI[2:length(y_hat_d_SPX1_EGARCH11SVI)]))), col="purple") legend(lty=1, cex=1, "topleft", col=c("black", "red", "orange", "blue", "magenta", "green", "purple"), legend=c("Buy and hold", "GARCH", "GARCH-SVI", "GJRGARCH", "GJRGARCH-SVI", "EGARCH", "EGARCH-SVI")) } ####--------------------------------------------------------------------------- #### SPXCPV GARCH models: create, train/fit them and create forecasts ####--------------------------------------------------------------------------- # Set parameters SPXCPV_roll = length(SPX_dSVICPV)-247 # This will also be the number of out-of-sample predictions. N.B.: the 248th # value of R corresponds to 2005-01-03, the 1st trading day out-of-sample, # the first value after 247. ###---------------------------------------------------------------------------- ### SPXCPV In-sample SPXCPV_AR(1)-GARCH(1,1) Model ###--------------------------------------------------------------------------- SPXCPV_in_sample_GARCH11 = GARCH_model_spec(mod="sGARCH", exreg= NULL) SPXCPV_in_sample_GARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPXCPV_in_sample_GARCH11) ###---------------------------------------------------------------------------- ### Create the SPXCPV_AR(1)-GARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- SPXCPV_GARCH11_mu_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_GARCH11_mu_hat) = c('SPXCPV_GARCH11_mu_hat') SPXCPV_GARCH11_sigma_hat = zoo(matrix(, nrow=roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_GARCH11_sigma_hat) = c('SPXCPV_GARCH11_sigma_hat') for (i in c(1:SPXCPV_roll)) {SPXCPV_GARCH11 = GARCH_model_spec(mod="sGARCH", exreg=NULL) try(withTimeout({(SPXCPV_GARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPXCPV_GARCH11))}, timeout = 5),silent = TRUE) # the 247th value of R is 2004-12-31. try((SPXCPV_GARCH11fitforecast = GARCH_model_forecast(mod=SPXCPV_GARCH11fit)), silent = TRUE) # suppressWarnings(expr) try((SPXCPV_GARCH11_mu_hat[i]=SPXCPV_GARCH11fitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPXCPV_GARCH11_sigma_hat[i]=SPXCPV_GARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPXCPV_GARCH11) rm(SPXCPV_GARCH11fit) rm(SPXCPV_GARCH11fitforecast) } SPX_RV_no_SPXCPV_GARCH11_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPXCPV_roll)], as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])) -(na.omit(zoo((SPXCPV_GARCH11_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])))))) # Forecast Error, Mean and S.D.: SPXCPV_GARCH11forecasterror = (na.omit(SPXCPV_GARCH11_sigma_hat) -SPX_RV_no_SPXCPV_GARCH11_sigma_hat_na_dated) colnames(SPXCPV_GARCH11forecasterror) = c("SPXCPV_GARCH11forecasterror") mean(SPXCPV_GARCH11forecasterror) sd(SPXCPV_GARCH11forecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPXCPV_GARCH11_sigma_hat_na_dated, (na.omit(SPXCPV_GARCH11_sigma_hat))) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.1_SPX_CPV_GARCH11.RData") ###---------------------------------------------------------------------------- ### SPXCPV In-sample SPXCPV_AR(1)-GARCH(1,1)-SVI Model ###--------------------------------------------------------------------------- SPXCPV_in_sample_GARCH11SVI = GARCH_model_spec(mod="sGARCH", exreg= as.matrix(SPX_dSVICPV[1:(246+1)])) SPXCPV_in_sample_GARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPXCPV_in_sample_GARCH11SVI) ###---------------------------------------------------------------------------- ### Create the SPXCPV_AR(1)-GARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- SPXCPV_GARCH11SVI_mu_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_GARCH11SVI_mu_hat) = c('SPXCPV_GARCH11_mu_hat') SPXCPV_GARCH11SVI_sigma_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(GARCH11_sigma_hat) = c('GARCH11_sigma_hat') for (i in c(1:SPXCPV_roll)) {SPXCPV_GARCH11SVI = GARCH_model_spec(mod="sGARCH", exreg=as.matrix(SPX_dSVICPV[1:(246+i)])) try(withTimeout({(SPXCPV_GARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPXCPV_GARCH11SVI))}, timeout = 5),silent = TRUE) try((SPXCPV_GARCH11SVIfitforecast = GARCH_model_forecast(mod=SPXCPV_GARCH11SVIfit)), silent = TRUE) try((SPXCPV_GARCH11SVI_mu_hat[i]=SPXCPV_GARCH11SVIfitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPXCPV_GARCH11SVI_sigma_hat[i]=SPXCPV_GARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPXCPV_GARCH11SVI) rm(SPXCPV_GARCH11SVIfit) rm(SPXCPV_GARCH11SVIfitforecast) } # fitted(GARCH11SVIfitforecast) SPX_RV_no_SPXCPV_GARCH11SVI_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPXCPV_roll)], as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])) -(na.omit(zoo((SPXCPV_GARCH11SVI_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])))))) # Forecast Error, Mean and S.D.: SPXCPV_GARCH11SVIforecasterror = (na.omit(SPXCPV_GARCH11SVI_sigma_hat) -SPX_RV_no_SPXCPV_GARCH11SVI_sigma_hat_na_dated) colnames(SPXCPV_GARCH11SVIforecasterror) = c("SPXCPV_GARCH11SVIforecasterror") # plot(zoo(GARCH11SVIforecasterror, as.Date(row.names(GARCH11SVIforecasterror))), type='l', ylab='GARCH11SVIforecasterror', xlab='Date') mean(SPXCPV_GARCH11SVIforecasterror) sd(SPXCPV_GARCH11SVIforecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPXCPV_GARCH11SVI_sigma_hat_na_dated, (na.omit(SPXCPV_GARCH11SVI_sigma_hat))) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.2_SPX_CPV_GARCH11SVI.RData") ###---------------------------------------------------------------------------- ### SPXCPV In-sample SPXCPV_AR(1)-GJRGARCH(1,1) Model ###--------------------------------------------------------------------------- SPXCPV_in_sample_GJRGARCH11 = GARCH_model_spec(mod="gjrGARCH", exreg= NULL) SPXCPV_in_sample_GJRGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPXCPV_in_sample_GJRGARCH11) ###---------------------------------------------------------------------------- ### Create the SPXCPV_AR(1)-GJRGARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- SPXCPV_GJRGARCH11_mu_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_GJRGARCH11_mu_hat) = c('SPXCPV_GJRGARCH11_mu_hat') SPXCPV_GJRGARCH11_sigma_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(GJRGARCH11_sigma_hat) = c('GJRGARCH11_sigma_hat') for (i in c(1:SPXCPV_roll)) {SPXCPV_GJRGARCH11 = GARCH_model_spec(mod="gjrGARCH", exreg=NULL) try(withTimeout({(SPXCPV_GJRGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPXCPV_GJRGARCH11))}, timeout = 5),silent = TRUE) # the 247th value of R is 2004-12-31. try((SPXCPV_GJRGARCH11fitforecast = GARCH_model_forecast(mod=SPXCPV_GJRGARCH11fit)), silent = TRUE) # suppressWarnings(expr) try((SPXCPV_GJRGARCH11_mu_hat[i]=SPXCPV_GJRGARCH11fitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPXCPV_GJRGARCH11_sigma_hat[i]=SPXCPV_GJRGARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPXCPV_GJRGARCH11) rm(SPXCPV_GJRGARCH11fit) rm(SPXCPV_GJRGARCH11fitforecast) } # fitted(GJRGARCH11fitforecast) SPX_RV_no_SPXCPV_GJRGARCH11_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPXCPV_roll)], as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])) -(na.omit(zoo((SPXCPV_GJRGARCH11_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])))))) # Forecast Error, Mean and S.D.: SPXCPV_GJRGARCH11forecasterror = (na.omit(SPXCPV_GJRGARCH11_sigma_hat) -SPX_RV_no_SPXCPV_GJRGARCH11_sigma_hat_na_dated) colnames(SPXCPV_GJRGARCH11forecasterror) = c("SPXCPV_GJRGARCH11forecasterror") # plot(zoo(GJRGARCH11forecasterror, as.Date(row.names(GJRGARCH11forecasterror))), type='l', ylab='GJRGARCH11forecasterror', xlab='Date') mean(SPXCPV_GJRGARCH11forecasterror) sd(SPXCPV_GJRGARCH11forecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPXCPV_GJRGARCH11_sigma_hat_na_dated, (na.omit(SPXCPV_GJRGARCH11_sigma_hat))) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.3_SPX_CPV_GJRGARCH11.RData") ###---------------------------------------------------------------------------- ### SPXCPV In-sample SPXCPV_AR(1)-GJRGARCH(1,1)-SVI Model ###--------------------------------------------------------------------------- SPXCPV_in_sample_GJRGARCH11SVI = GARCH_model_spec(mod="gjrGARCH", exreg= as.matrix(SPX_dSVICPV[1:(246+1)])) SPXCPV_in_sample_GJRGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPXCPV_in_sample_GJRGARCH11SVI) ###---------------------------------------------------------------------------- ### Create the SPXCPV_AR(1)-GJRGARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- SPXCPV_GJRGARCH11SVI_mu_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_GJRGARCH11SVI_mu_hat) = c('SPXCPV_GJRGARCH11_mu_hat') SPXCPV_GJRGARCH11SVI_sigma_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(GJRGARCH11_sigma_hat) = c('GJRGARCH11_sigma_hat') for (i in c(1:SPXCPV_roll)) {SPXCPV_GJRGARCH11SVI = GARCH_model_spec(mod="gjrGARCH", exreg=as.matrix(SPX_dSVICPV[1:(246+i)])) try(withTimeout({(SPXCPV_GJRGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPXCPV_GJRGARCH11SVI))}, timeout = 5),silent = TRUE) try((SPXCPV_GJRGARCH11SVIfitforecast = GARCH_model_forecast(mod=SPXCPV_GJRGARCH11SVIfit)), silent = TRUE) try((SPXCPV_GJRGARCH11SVI_mu_hat[i]=SPXCPV_GJRGARCH11SVIfitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPXCPV_GJRGARCH11SVI_sigma_hat[i]=SPXCPV_GJRGARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPXCPV_GJRGARCH11SVI) rm(SPXCPV_GJRGARCH11SVIfit) rm(SPXCPV_GJRGARCH11SVIfitforecast) } SPX_RV_no_SPXCPV_GJRGARCH11SVI_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPXCPV_roll)], as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])) -(na.omit(zoo((SPXCPV_GJRGARCH11SVI_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])))))) # Forecast Error, Mean and S.D.: SPXCPV_GJRGARCH11SVIforecasterror = (na.omit(SPXCPV_GJRGARCH11SVI_sigma_hat) -SPX_RV_no_SPXCPV_GJRGARCH11SVI_sigma_hat_na_dated) colnames(SPXCPV_GJRGARCH11SVIforecasterror) = c("SPXCPV_GJRGARCH11SVIforecasterror") # plot(zoo(GJRGARCH11SVIforecasterror, as.Date(row.names(GJRGARCH11SVIforecasterror))), type='l', ylab='GJRGARCH11SVIforecasterror', xlab='Date') mean(SPXCPV_GJRGARCH11SVIforecasterror) sd(SPXCPV_GJRGARCH11SVIforecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPXCPV_GJRGARCH11SVI_sigma_hat_na_dated, (na.omit(SPXCPV_GJRGARCH11SVI_sigma_hat))) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.4_SPX_CPV_GJRGARCH11SVI.RData") ###---------------------------------------------------------------------------- ### SPXCPV In-sample SPXCPV_AR(1)-EGARCH(1,1) Model ###--------------------------------------------------------------------------- SPXCPV_in_sample_EGARCH11 = GARCH_model_spec(mod="eGARCH", exreg= NULL) SPXCPV_in_sample_EGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPXCPV_in_sample_EGARCH11) ###---------------------------------------------------------------------------- ### Create the SPXCPV_AR(1)-EGARCH(1,1) Model and forecasts ###---------------------------------------------------------------------------- SPXCPV_EGARCH11_mu_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_EGARCH11_mu_hat) = c('SPXCPV_EGARCH11_mu_hat') SPXCPV_EGARCH11_sigma_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(EGARCH11_sigma_hat) = c('EGARCH11_sigma_hat') for (i in c(1:SPXCPV_roll)) {SPXCPV_EGARCH11 = GARCH_model_spec(mod="eGARCH", exreg=NULL) try(withTimeout({(SPXCPV_EGARCH11fit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPXCPV_EGARCH11))}, timeout = 5),silent = TRUE) # the 247th value of R is 2004-12-31. try((SPXCPV_EGARCH11fitforecast = GARCH_model_forecast(mod=SPXCPV_EGARCH11fit)), silent = TRUE) # suppressWarnings(expr) try((SPXCPV_EGARCH11_mu_hat[i]=SPXCPV_EGARCH11fitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPXCPV_EGARCH11_sigma_hat[i]=SPXCPV_EGARCH11fitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPXCPV_EGARCH11) rm(SPXCPV_EGARCH11fit) rm(SPXCPV_EGARCH11fitforecast) } # fitted(EGARCH11fitforecast) SPX_RV_no_SPXCPV_EGARCH11_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPXCPV_roll)], as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])) -(na.omit(zoo((SPXCPV_EGARCH11_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])))))) # Forecast Error, Mean and S.D.: SPXCPV_EGARCH11forecasterror = (na.omit(SPXCPV_EGARCH11_sigma_hat) -SPX_RV_no_SPXCPV_EGARCH11_sigma_hat_na_dated) colnames(SPXCPV_EGARCH11forecasterror) = c("SPXCPV_EGARCH11forecasterror") # plot(zoo(EGARCH11forecasterror, as.Date(row.names(EGARCH11forecasterror))), type='l', ylab='EGARCH11forecasterror', xlab='Date') mean(SPXCPV_EGARCH11forecasterror) sd(SPXCPV_EGARCH11forecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPXCPV_EGARCH11_sigma_hat_na_dated, (na.omit(SPXCPV_EGARCH11_sigma_hat))) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.5_SPX_CPV_EGARCH11.RData") ###---------------------------------------------------------------------------- ### SPXCPV In-sample SPXCPV_AR(1)-EGARCH(1,1)-SVI Model ###--------------------------------------------------------------------------- SPXCPV_in_sample_EGARCH11SVI = GARCH_model_spec(mod="eGARCH", exreg= as.matrix(SPX_dSVICPV[1:(246+1)])) SPXCPV_in_sample_EGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+1)], spec=SPXCPV_in_sample_EGARCH11SVI) ###---------------------------------------------------------------------------- ### Create the SPXCPV_AR(1)-EGARCH(1,1)-SVI Model and forecasts ###---------------------------------------------------------------------------- SPXCPV_EGARCH11SVI_mu_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(SPXCPV_EGARCH11SVI_mu_hat) = c('SPXCPV_EGARCH11SVI_mu_hat') SPXCPV_EGARCH11SVI_sigma_hat = zoo(matrix(, nrow=SPXCPV_roll, ncol=1), as.Date(SPX_Datesm1[(247+1):(247+SPXCPV_roll)])) colnames(EGARCH11SVI_sigma_hat) = c('EGARCH11SVI_sigma_hat') for (i in c(1:SPXCPV_roll)) {SPXCPV_EGARCH11SVI = GARCH_model_spec(mod="eGARCH", exreg=as.matrix(SPX_dSVICPV[1:(246+i)])) try(withTimeout({(SPXCPV_EGARCH11SVIfit = ugarchfit(data = SPX_R_matrix[1:(246+i)], spec=SPXCPV_EGARCH11SVI))}, timeout = 5),silent = TRUE) try((SPXCPV_EGARCH11SVIfitforecast = GARCH_model_forecast(mod=SPXCPV_EGARCH11SVIfit)), silent = TRUE) try((SPXCPV_EGARCH11SVI_mu_hat[i]=SPXCPV_EGARCH11SVIfitforecast@forecast[["seriesFor"]]),silent = TRUE) try((SPXCPV_EGARCH11SVI_sigma_hat[i]=SPXCPV_EGARCH11SVIfitforecast@forecast[["sigmaFor"]]), silent = TRUE) rm(SPXCPV_EGARCH11SVI) rm(SPXCPV_EGARCH11SVIfit) rm(SPXCPV_EGARCH11SVIfitforecast) } SPXCPV_EGARCH11SVI_sigma_hat[2874] = NA # This is due to a bad conversion specifically for EGARCH11SVI at i=2874. SPX_RV_no_SPXCPV_EGARCH11SVI_sigma_hat_na_dated = as.matrix( (zoo(SPX_RV[(248+1):(248+SPXCPV_roll)], as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])) -(na.omit(zoo((SPXCPV_EGARCH11SVI_sigma_hat*0), as.Date(SPX_Dates[(248+1):(248+SPXCPV_roll)])))))) # Forecast Error, Mean and S.D.: SPXCPV_EGARCH11SVIforecasterror = (na.omit(SPXCPV_EGARCH11SVI_sigma_hat) -SPX_RV_no_SPXCPV_EGARCH11SVI_sigma_hat_na_dated) colnames(SPXCPV_EGARCH11SVIforecasterror) = c("SPXCPV_EGARCH11SVIforecasterror") # plot(zoo(EGARCH11SVIforecasterror, as.Date(row.names(EGARCH11SVIforecasterror))), type='l', ylab='EGARCH11SVIforecasterror', xlab='Date') mean(SPXCPV_EGARCH11SVIforecasterror) sd(SPXCPV_EGARCH11SVIforecasterror) # RMSE of the sigme (standard deviations) of the forecast: rmse(SPX_RV_no_SPXCPV_EGARCH11SVI_sigma_hat_na_dated, (na.omit(SPXCPV_EGARCH11SVI_sigma_hat))) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.6_SPX_CPV_EGARCH11SVI.RData") ###--------------------------------------------------------------------------- ### s.d. forecase D-M tests ###--------------------------------------------------------------------------- print("This function implements the modified test proposed by Harvey, Leybourne and Newbold (1997). The null hypothesis is that the two methods have the same forecast accuracy. For alternative=less, the alternative hypothesis is that method 2 is less accurate than method 1. For alternative=greater, the alternative hypothesis is that method 2 is more accurate than method 1. For alternative=two.sided, the alternative hypothesis is that method 1 and method 2 have different levels of accuracy.") print("Diebold and Mariano test SPXCPV_GARCH11 with and without SVI") SPXCPV_GARCH11forecasterror_dm = SPXCPV_GARCH11forecasterror - (SPXCPV_GARCH11SVIforecasterror*0) SPXCPV_GARCH11SVIforecasterror_dm = SPXCPV_GARCH11SVIforecasterror - (SPXCPV_GARCH11forecasterror*0) SPXCPV_DM_Test_GARCH = dm.test(matrix(SPXCPV_GARCH11forecasterror_dm), matrix(SPXCPV_GARCH11SVIforecasterror_dm), alternative = "less") print("Diebold and Mariano test SPXCPV_GJRGARCH11 with and without SVI") SPXCPV_GJRGARCH11forecasterror_dm = SPXCPV_GJRGARCH11forecasterror - (SPXCPV_GJRGARCH11SVIforecasterror*0) SPXCPV_GJRGARCH11SVIforecasterror_dm = SPXCPV_GJRGARCH11SVIforecasterror - (SPXCPV_GJRGARCH11forecasterror*0) SPXCPV_DM_Test_GJRARCH = dm.test(matrix(SPXCPV_GJRGARCH11forecasterror_dm), matrix(SPXCPV_GJRGARCH11SVIforecasterror_dm), alternative = "less") print("Diebold and Mariano test SPXCPV_EGARCH11 with and without SVI") SPXCPV_EGARCH11forecasterror_dm = SPXCPV_EGARCH11forecasterror - (SPXCPV_EGARCH11SVIforecasterror*0) SPXCPV_EGARCH11SVIforecasterror_dm = SPXCPV_EGARCH11SVIforecasterror - (SPXCPV_EGARCH11forecasterror*0) SPXCPV_DM_Test_EGARCH = dm.test(matrix(SPXCPV_EGARCH11forecasterror_dm), matrix(SPXCPV_EGARCH11SVIforecasterror_dm), alternative = "less") save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.7_SPX_CPV_DM.RData") ####--------------------------------------------------------------------------- #### SPXCPV estimates of the probability of a positive return ####--------------------------------------------------------------------------- ###---------------------------------------------------------------------------- ### C&D, Naive ###---------------------------------------------------------------------------- #------------------------------------------------------------------------------ # SPXCPV GARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GARCH11 Model: SPXCPV_GARCH11_CandD_I = matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GARCH11_CandD_I_k= matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GARCH11_CandD_I_t = matrix( - (SPXCPV_GARCH11_mu_hat/SPXCPV_GARCH11_sigma_hat)) for(t in c(1:SPXCPV_roll)) {for (k in c(1:t)) {SPXCPV_GARCH11_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPXCPV_GARCH11_mu_hat[k])/SPXCPV_GARCH11_sigma_hat[k]) <=SPXCPV_GARCH11_CandD_I_t[t+1], 1,0) SPXCPV_GARCH11_CandD_I[k,t] = ifelse((is.na(SPXCPV_GARCH11_CandD_I_k[k,t])), NA, (sum(SPXCPV_GARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GARCH11 Model: SPXCPV_GARCH11_CandD=(1:(SPXCPV_roll-1)) for(i in c(1:(SPXCPV_roll-1))) {SPXCPV_GARCH11_CandD[i] = 1 - ((SPXCPV_GARCH11_CandD_I[i,i])/ length(na.omit(SPXCPV_GARCH11_CandD_I[1:i,i])))} SPXCPV_GARCH11_CandD_zoo = zoo(SPXCPV_GARCH11_CandD, as.Date(SPX_Dates[(248+1):(248+(SPXCPV_roll-1))])) # This zoo object has missing values. SPXCPV_GARCH11_CandD_zoo_no_nas=zoo(na.omit(SPXCPV_GARCH11_CandD_zoo)) # rm(SPXCPV_GARCH11_CandD_I_t) # Cleaning datasets # rm(SPXCPV_GARCH11_CandD_I_k) # rm(SPXCPV_GARCH11_CandD_I) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.8_SPX_CPV_GARCH11_CandD.RData") #------------------------------------------------------------------------------ # SPXCPV GARCH11SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GARCH11SVI Model: SPXCPV_GARCH11SVI_CandD_I = matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GARCH11SVI_CandD_I_k= matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GARCH11SVI_CandD_I_t = matrix( - (SPXCPV_GARCH11SVI_mu_hat/SPXCPV_GARCH11SVI_sigma_hat)) for(t in c(1:SPXCPV_roll)) {for (k in c(1:t)) {SPXCPV_GARCH11SVI_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPXCPV_GARCH11SVI_mu_hat[k])/SPXCPV_GARCH11SVI_sigma_hat[k]) <=SPXCPV_GARCH11SVI_CandD_I_t[t+1], 1,0) SPXCPV_GARCH11SVI_CandD_I[k,t] = ifelse((is.na(SPXCPV_GARCH11SVI_CandD_I_k[k,t])), NA, (sum(SPXCPV_GARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GARCH11SVI Model: SPXCPV_GARCH11SVI_CandD=(1:(SPXCPV_roll-1)) for(i in c(1:(SPXCPV_roll-1))) {SPXCPV_GARCH11SVI_CandD[i] = 1 - ((SPXCPV_GARCH11SVI_CandD_I[i,i])/ length(na.omit(SPXCPV_GARCH11SVI_CandD_I[1:i,i])))} SPXCPV_GARCH11SVI_CandD_zoo = zoo(SPXCPV_GARCH11SVI_CandD, as.Date(SPX_Dates[(248+1):(248+(SPXCPV_roll-1))])) # This zoo object has missing values. SPXCPV_GARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(SPXCPV_GARCH11SVI_CandD_zoo)) # rm(SPXCPV_GARCH11SVI_CandD_I_t) # Cleaning datasets # rm(SPXCPV_GARCH11SVI_CandD_I_k) # rm(SPXCPV_GARCH11SVI_CandD_I) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.9_SPX_CPV_GARCH11SVI_CandD.RData") #------------------------------------------------------------------------------ # SPXCPV GJRGARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GJRGARCH11 Model: SPXCPV_GJRGARCH11_CandD_I = matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GJRGARCH11_CandD_I_k= matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GJRGARCH11_CandD_I_t = matrix( - (SPXCPV_GJRGARCH11_mu_hat/SPXCPV_GJRGARCH11_sigma_hat)) for(t in c(1:SPXCPV_roll)) {for (k in c(1:t)) {SPXCPV_GJRGARCH11_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPXCPV_GJRGARCH11_mu_hat[k])/SPXCPV_GJRGARCH11_sigma_hat[k]) <=SPXCPV_GJRGARCH11_CandD_I_t[t+1], 1,0) # This will also be the number of out-of-sample predictions. N.B.: the 248th value of SPX_R_zoo corresponds to 2005-01-03, the 1st trading day out-of-sample, the first value after 252. # Note that we have some missing values due to the model not always managing # to converge to estimates of sigma and mu; since we need the t+1 model # estimates to compute its CandD_I_k, we also loose its t'th value for # each model's missing value. # We also los the last value (the SPXCPV_roll'th value) for the same reason. SPXCPV_GJRGARCH11_CandD_I[k,t] = ifelse((is.na(SPXCPV_GJRGARCH11_CandD_I_k[k,t])), NA, (sum(SPXCPV_GJRGARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GJRGARCH11 Model: SPXCPV_GJRGARCH11_CandD=(1:(SPXCPV_roll-1)) for(i in c(1:(SPXCPV_roll-1))) {SPXCPV_GJRGARCH11_CandD[i] = 1 - ((SPXCPV_GJRGARCH11_CandD_I[i,i])/ length(na.omit(SPXCPV_GJRGARCH11_CandD_I[1:i,i])))} SPXCPV_GJRGARCH11_CandD_zoo = zoo(SPXCPV_GJRGARCH11_CandD, as.Date(SPX_Dates[(248+1):(248+(SPXCPV_roll-1))])) # This zoo object has missing values. SPXCPV_GJRGARCH11_CandD_zoo_no_nas=zoo(na.omit(SPXCPV_GJRGARCH11_CandD_zoo)) # rm(SPXCPV_GJRGARCH11_CandD_I_t) # Cleaning datasets # rm(SPXCPV_GJRGARCH11_CandD_I_k) # rm(SPXCPV_GJRGARCH11_CandD_I) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.10_SPX_CPV_GJRGARCH11_CandD.RData") #------------------------------------------------------------------------------ # SPXCPV GJRGARCH11SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the GJRGARCH11SVI Model: SPXCPV_GJRGARCH11SVI_CandD_I = matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GJRGARCH11SVI_CandD_I_k= matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_GJRGARCH11SVI_CandD_I_t = matrix( - (SPXCPV_GJRGARCH11SVI_mu_hat/SPXCPV_GJRGARCH11SVI_sigma_hat)) for(t in c(1:SPXCPV_roll)) {for (k in c(1:t)) {SPXCPV_GJRGARCH11SVI_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPXCPV_GJRGARCH11SVI_mu_hat[k])/SPXCPV_GJRGARCH11SVI_sigma_hat[k]) <=SPXCPV_GJRGARCH11SVI_CandD_I_t[t+1], 1,0) SPXCPV_GJRGARCH11SVI_CandD_I[k,t] = ifelse((is.na(SPXCPV_GJRGARCH11SVI_CandD_I_k[k,t])), NA, (sum(SPXCPV_GJRGARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the GJRGARCH11SVI Model: SPXCPV_GJRGARCH11SVI_CandD=(1:(SPXCPV_roll-1)) for(i in c(1:(SPXCPV_roll-1))) {SPXCPV_GJRGARCH11SVI_CandD[i] = 1 - ((SPXCPV_GJRGARCH11SVI_CandD_I[i,i])/ length(na.omit(SPXCPV_GJRGARCH11SVI_CandD_I[1:i,i])))} SPXCPV_GJRGARCH11SVI_CandD_zoo = zoo(SPXCPV_GJRGARCH11SVI_CandD, as.Date(SPX_Dates[(248+1):(248+(SPXCPV_roll-1))])) # This zoo object has missing values. SPXCPV_GJRGARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(SPXCPV_GJRGARCH11SVI_CandD_zoo)) # rm(SPXCPV_GJRGARCH11SVI_CandD_I_t) # Cleaning datasets # rm(SPXCPV_GJRGARCH11SVI_CandD_I_k) # rm(SPXCPV_GJRGARCH11SVI_CandD_I) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.11_SPX_CPV_GJRGARCH11SVI_CandD.RData") #------------------------------------------------------------------------------ # SPXCPV EGARCH11's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the EGARCH11 Model: SPXCPV_EGARCH11_CandD_I = matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_EGARCH11_CandD_I_k= matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_EGARCH11_CandD_I_t = matrix( - (SPXCPV_EGARCH11_mu_hat/SPXCPV_EGARCH11_sigma_hat)) for(t in c(1:SPXCPV_roll)) {for (k in c(1:t)) {SPXCPV_EGARCH11_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPXCPV_EGARCH11_mu_hat[k])/SPXCPV_EGARCH11_sigma_hat[k]) <=SPXCPV_EGARCH11_CandD_I_t[t+1], 1,0) SPXCPV_EGARCH11_CandD_I[k,t] = ifelse((is.na(SPXCPV_EGARCH11_CandD_I_k[k,t])), NA, (sum(SPXCPV_EGARCH11_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the EGARCH11 Model: SPXCPV_EGARCH11_CandD=(1:(SPXCPV_roll-1)) for(i in c(1:(SPXCPV_roll-1))) {SPXCPV_EGARCH11_CandD[i] = 1 - ((SPXCPV_EGARCH11_CandD_I[i,i])/ length(na.omit(SPXCPV_EGARCH11_CandD_I[1:i,i])))} SPXCPV_EGARCH11_CandD_zoo = zoo(SPXCPV_EGARCH11_CandD, as.Date(SPX_Dates[(248+1):(248+(SPXCPV_roll-1))])) # This zoo object has missing values. SPXCPV_EGARCH11_CandD_zoo_no_nas=zoo(na.omit(SPXCPV_EGARCH11_CandD_zoo)) # rm(SPXCPV_EGARCH11_CandD_I_t) # Cleaning datasets # rm(SPXCPV_EGARCH11_CandD_I_k) # rm(SPXCPV_EGARCH11_CandD_I) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.12_SPX_CPV_EGARCH11_CandD.RData") #------------------------------------------------------------------------------ # SPXCPV EGARCH11SVI's C&D Model #------------------------------------------------------------------------------ # # Create our variables: # C&D's Indicator function according to the EGARCH11SVI Model: SPXCPV_EGARCH11SVI_CandD_I = matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_EGARCH11SVI_CandD_I_k= matrix(, nrow=SPXCPV_roll, ncol=SPXCPV_roll) SPXCPV_EGARCH11SVI_CandD_I_t = matrix( - (SPXCPV_EGARCH11SVI_mu_hat/SPXCPV_EGARCH11SVI_sigma_hat)) for(t in c(1:SPXCPV_roll)) {for (k in c(1:t)) {SPXCPV_EGARCH11SVI_CandD_I_k[k,t] = ifelse(((SPX_R_matrix[247+k]-SPXCPV_EGARCH11SVI_mu_hat[k])/SPXCPV_EGARCH11SVI_sigma_hat[k]) <=SPXCPV_EGARCH11SVI_CandD_I_t[t+1], 1,0) SPXCPV_EGARCH11SVI_CandD_I[k,t] = ifelse((is.na(SPXCPV_EGARCH11SVI_CandD_I_k[k,t])), NA, (sum(SPXCPV_EGARCH11SVI_CandD_I_k[1:k,t], na.rm = TRUE)))}} # C&D's model according to the EGARCH11SVI Model: SPXCPV_EGARCH11SVI_CandD=(1:(SPXCPV_roll-1)) for(i in c(1:(SPXCPV_roll-1))) {SPXCPV_EGARCH11SVI_CandD[i] = 1 - ((SPXCPV_EGARCH11SVI_CandD_I[i,i])/ length(na.omit(SPXCPV_EGARCH11SVI_CandD_I[1:i,i])))} SPXCPV_EGARCH11SVI_CandD_zoo = zoo(SPXCPV_EGARCH11SVI_CandD, as.Date(SPX_Dates[(248+1):(248+(SPXCPV_roll-1))])) # This zoo object has missing values. SPXCPV_EGARCH11SVI_CandD_zoo_no_nas=zoo(na.omit(SPXCPV_EGARCH11SVI_CandD_zoo)) # rm(SPXCPV_EGARCH11SVI_CandD_I_t) # Cleaning datasets # rm(SPXCPV_EGARCH11SVI_CandD_I_k) # rm(SPXCPV_EGARCH11SVI_CandD_I) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.13_SPX_CPV_EGARCH11SVI_CandD.RData") ##----------------------------------------------------------------------------- ## compare the predictive performance of each model using SPXCPV data ## (forecast error mean, sd, Brier Scores and Diebold&Mariano statistics) ##----------------------------------------------------------------------------- # # mean of the probabilistic forecast errors derived from each model SPXCPV_Observed_pi= ifelse(SPX_R_matrix>0,1,0) SPXCPV_Observed_pi_zoo = zoo(SPXCPV_Observed_pi, as.Date(SPX_Dates)) SPXCPV_GARCH11_pi_error = SPXCPV_GARCH11_CandD_zoo_no_nas - SPXCPV_Observed_pi_zoo SPXCPV_GARCH11SVI_pi_error = SPXCPV_GARCH11SVI_CandD_zoo_no_nas - SPXCPV_Observed_pi_zoo SPXCPV_GJRGARCH11_pi_error = SPXCPV_GJRGARCH11_CandD_zoo_no_nas - SPXCPV_Observed_pi_zoo SPXCPV_GJRGARCH11SVI_pi_error = SPXCPV_GJRGARCH11SVI_CandD_zoo_no_nas - SPXCPV_Observed_pi_zoo SPXCPV_EGARCH11_pi_error = SPXCPV_EGARCH11_CandD_zoo_no_nas - SPXCPV_Observed_pi_zoo SPXCPV_EGARCH11SVI_pi_error = SPXCPV_EGARCH11SVI_CandD_zoo_no_nas - SPXCPV_Observed_pi_zoo mean(SPXCPV_GARCH11_pi_error) sd(SPXCPV_GARCH11_pi_error) mean(SPXCPV_GARCH11SVI_pi_error) sd(SPXCPV_GARCH11SVI_pi_error) mean(SPXCPV_GJRGARCH11_pi_error) sd(SPXCPV_GJRGARCH11_pi_error) mean(SPXCPV_GJRGARCH11SVI_pi_error) sd(SPXCPV_GJRGARCH11SVI_pi_error) mean(SPXCPV_EGARCH11_pi_error) sd(SPXCPV_EGARCH11_pi_error) mean(SPXCPV_EGARCH11SVI_pi_error) sd(SPXCPV_EGARCH11SVI_pi_error) # # SPXCPV_Brier scores of the probabilistic forecast errors derived from each model SPXCPV_GARCH11_pi_error_Brier_score = (1/length(SPXCPV_GARCH11_pi_error))*sum(SPXCPV_GARCH11_pi_error^2) show(SPXCPV_GARCH11_pi_error_Brier_score) SPXCPV_GARCH11SVI_pi_error_Brier_score = (1/length(SPXCPV_GARCH11SVI_pi_error))*sum(SPXCPV_GARCH11SVI_pi_error^2) show(SPXCPV_GARCH11SVI_pi_error_Brier_score) SPXCPV_GJRGARCH11_pi_error_Brier_score = (1/length(SPXCPV_GJRGARCH11_pi_error))*sum(SPXCPV_GJRGARCH11_pi_error^2) show(SPXCPV_GJRGARCH11_pi_error_Brier_score) SPXCPV_GJRGARCH11SVI_pi_error_Brier_score = (1/length(SPXCPV_GJRGARCH11SVI_pi_error))*sum(SPXCPV_GJRGARCH11SVI_pi_error^2) show(SPXCPV_GJRGARCH11SVI_pi_error_Brier_score) SPXCPV_EGARCH11_pi_error_Brier_score = (1/length(SPXCPV_EGARCH11_pi_error))*sum(SPXCPV_EGARCH11_pi_error^2) show(SPXCPV_EGARCH11_pi_error_Brier_score) SPXCPV_EGARCH11SVI_pi_error_Brier_score = (1/length(SPXCPV_EGARCH11SVI_pi_error))*sum(SPXCPV_EGARCH11SVI_pi_error^2) show(SPXCPV_EGARCH11SVI_pi_error_Brier_score) # # SPXCPV_Diebold&Mariano statistics # Here the alternative hypothesis is that method 2 is more accurate than method 1; remember that a small p-value indicates strong evidence against the Null Hypothesis. SPXCPV_GARCH11_pi_error_dm = SPXCPV_GARCH11_pi_error - (SPXCPV_GARCH11SVI_pi_error*0) SPXCPV_GARCH11SVI_pi_error_dm = SPXCPV_GARCH11SVI_pi_error - (SPXCPV_GARCH11_pi_error*0) SPXCPV_GARCH11_dm_test = dm.test(matrix(SPXCPV_GARCH11_pi_error_dm), matrix(SPXCPV_GARCH11SVI_pi_error_dm), alternative = "greater") SPXCPV_GJRGARCH11_pi_error_dm = SPXCPV_GJRGARCH11_pi_error - (SPXCPV_GJRGARCH11SVI_pi_error*0) SPXCPV_GJRGARCH11SVI_pi_error_dm = SPXCPV_GJRGARCH11SVI_pi_error - (SPXCPV_GJRGARCH11_pi_error*0) SPXCPV_GJRGARCH11_dm_test = dm.test(matrix(SPXCPV_GJRGARCH11_pi_error_dm), matrix(SPXCPV_GJRGARCH11SVI_pi_error_dm), alternative = c("greater")) SPXCPV_EGARCH11_pi_error_dm = SPXCPV_EGARCH11_pi_error - (SPXCPV_EGARCH11SVI_pi_error*0) SPXCPV_EGARCH11SVI_pi_error_dm = SPXCPV_EGARCH11SVI_pi_error - (SPXCPV_EGARCH11_pi_error*0) SPXCPV_EGARCH11_dm_test = dm.test(matrix(SPXCPV_EGARCH11_pi_error_dm), matrix(SPXCPV_EGARCH11SVI_pi_error_dm), alternative = c("greater")) save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.14_SPX_CPV_pi_DM.RData") ####---------------------------------------------------------------------------- #### SPXCPV's Financial significance ####---------------------------------------------------------------------------- # indicator of the realised direction of the return on the S&P 500 index y_d = ifelse(SPX_R_zoo>0,1,0) # Set the probability threashold at which to invest in the index in our 2d graphs: for (p in c(0.49, 0.495, 0.5, 0.505, 0.51)){ ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework using the GARCH11 model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPXCPV_GARCH11 = ifelse(SPXCPV_GARCH11_CandD_zoo_no_nas>p,1,0) y_d_SPXCPV_GARCH11 = y_d - (SPXCPV_GARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPXCPV_GARCH11),1))==1 , 1, 0) R_Active_SPXCPV_GARCH11_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPXCPV_GARCH11*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPXCPV_GARCH11*0))))[2:length(y_hat_d_SPXCPV_GARCH11)] R_Active_SPXCPV_GARCH11_p_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GARCH11_p)) for (i in c(1:length(R_Active_SPXCPV_GARCH11_p))) {R_Active_SPXCPV_GARCH11_p_cumulated[i] = prod((1+R_Active_SPXCPV_GARCH11_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GARCH11_p)) for (i in c(1:length(R_Active_SPXCPV_GARCH11_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPXCPV_GARCH11_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework using the GARCH11-SVI model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPXCPV_GARCH11SVI = ifelse(SPXCPV_GARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_SPXCPV_GARCH11SVI = y_d - (SPXCPV_GARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPXCPV_GARCH11SVI),1))==1 , 1, 0) R_Active_SPXCPV_GARCH11SVI_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPXCPV_GARCH11SVI*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPXCPV_GARCH11SVI*0))))[2:length(y_hat_d_SPXCPV_GARCH11SVI)] R_Active_SPXCPV_GARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GARCH11SVI_p)) for (i in c(1:length(R_Active_SPXCPV_GARCH11SVI_p))) {R_Active_SPXCPV_GARCH11SVI_p_cumulated[i] = prod((1+R_Active_SPXCPV_GARCH11SVI_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GARCH11SVI_p)) for (i in c(1:length(R_Active_SPXCPV_GARCH11SVI_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPXCPV_GARCH11SVI_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework using the GJRGARCH11 model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPXCPV_GJRGARCH11 = ifelse(SPXCPV_GJRGARCH11_CandD_zoo_no_nas>p,1,0) y_d_SPXCPV_GJRGARCH11 = y_d - (SPXCPV_GJRGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPXCPV_GJRGARCH11),1))==1 , 1, 0) R_Active_SPXCPV_GJRGARCH11_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPXCPV_GJRGARCH11*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPXCPV_GJRGARCH11*0))))[2:length(y_hat_d_SPXCPV_GJRGARCH11)] R_Active_SPXCPV_GJRGARCH11_p_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GJRGARCH11_p)) for (i in c(1:length(R_Active_SPXCPV_GJRGARCH11_p))) {R_Active_SPXCPV_GJRGARCH11_p_cumulated[i] = prod((1+R_Active_SPXCPV_GJRGARCH11_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GJRGARCH11_p)) for (i in c(1:length(R_Active_SPXCPV_GJRGARCH11_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPXCPV_GJRGARCH11_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework using the GJRGARCH11-SVI model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPXCPV_GJRGARCH11SVI = ifelse(SPXCPV_GJRGARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_SPXCPV_GJRGARCH11SVI = y_d - (SPXCPV_GJRGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to GJRGARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPXCPV_GJRGARCH11SVI),1))==1 , 1, 0) R_Active_SPXCPV_GJRGARCH11SVI_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPXCPV_GJRGARCH11SVI*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPXCPV_GJRGARCH11SVI*0))))[2:length(y_hat_d_SPXCPV_GJRGARCH11SVI)] R_Active_SPXCPV_GJRGARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GJRGARCH11SVI_p)) for (i in c(1:length(R_Active_SPXCPV_GJRGARCH11SVI_p))) {R_Active_SPXCPV_GJRGARCH11SVI_p_cumulated[i] = prod((1+R_Active_SPXCPV_GJRGARCH11SVI_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPXCPV_GJRGARCH11SVI_p)) for (i in c(1:length(R_Active_SPXCPV_GJRGARCH11SVI_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPXCPV_GJRGARCH11SVI_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework using the EGARCH11 model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPXCPV_EGARCH11 = ifelse(SPXCPV_EGARCH11_CandD_zoo_no_nas>p,1,0) y_d_SPXCPV_EGARCH11 = y_d - (SPXCPV_EGARCH11_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPXCPV_EGARCH11),1))==1 , 1, 0) R_Active_SPXCPV_EGARCH11_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPXCPV_EGARCH11*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPXCPV_EGARCH11*0))))[2:length(y_hat_d_SPXCPV_EGARCH11)] R_Active_SPXCPV_EGARCH11_p_cumulated = matrix(,nrow=length(R_Active_SPXCPV_EGARCH11_p)) for (i in c(1:length(R_Active_SPXCPV_EGARCH11_p))) {R_Active_SPXCPV_EGARCH11_p_cumulated[i] = prod((1+R_Active_SPXCPV_EGARCH11_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPXCPV_EGARCH11_p)) for (i in c(1:length(R_Active_SPXCPV_EGARCH11_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPXCPV_EGARCH11_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework using the EGARCH11-SVI model ###---------------------------------------------------------------------------- # corresponding directional forecast and realised direction y_hat_d_SPXCPV_EGARCH11SVI = ifelse(SPXCPV_EGARCH11SVI_CandD_zoo_no_nas>p,1,0) y_d_SPXCPV_EGARCH11SVI = y_d - (SPXCPV_EGARCH11SVI_CandD_zoo_no_nas*0) # This y_d only has values on dates corresponding to EGARCH11SVI's. # let the portfolio weight attributed to the stock market index be omega = ifelse( (lead(as.matrix(y_hat_d_SPXCPV_EGARCH11SVI),1))==1 , 1, 0) R_Active_SPXCPV_EGARCH11SVI_p = ((lag(omega,1) * (SPX_R_zoo-(y_hat_d_SPXCPV_EGARCH11SVI*0)) + (1-lag(omega,1)) * (US_1MO_r_f_zoo-(y_hat_d_SPXCPV_EGARCH11SVI*0))))[2:length(y_hat_d_SPXCPV_EGARCH11SVI)] R_Active_SPXCPV_EGARCH11SVI_p_cumulated = matrix(,nrow=length(R_Active_SPXCPV_EGARCH11SVI_p)) for (i in c(1:length(R_Active_SPXCPV_EGARCH11SVI_p))) {R_Active_SPXCPV_EGARCH11SVI_p_cumulated[i] = prod((1+R_Active_SPXCPV_EGARCH11SVI_p)[1:i])} R_cumulated = matrix(,nrow=length(R_Active_SPXCPV_EGARCH11SVI_p)) for (i in c(1:length(R_Active_SPXCPV_EGARCH11SVI_p))) {R_cumulated[i] = prod((1+(SPX_R_zoo+(US_1MO_r_f_zoo - (R_Active_SPXCPV_EGARCH11SVI_p*0))))[1:i])} ###---------------------------------------------------------------------------- ### SPXCPV Granger and Pesaran (2000)'s framework 2d Graphs put together ###---------------------------------------------------------------------------- # Plot all 2d polts plot(zoo(R_Active_SPXCPV_GARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_GARCH11[2:length(y_hat_d_SPXCPV_GARCH11)]))), cex.axis=1, type="l",col="red", xlab='Date', ylim=c(0,3), ylab='SPXCPV strategy gain ($)', main=str_c("SPXCPV Strategy for psi ", p)) lines(zoo(R_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_GARCH11[2:length(y_hat_d_SPXCPV_GARCH11)]))), col="black") lines(zoo(R_Active_SPXCPV_GARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_GARCH11SVI[2:length(y_hat_d_SPXCPV_GARCH11SVI)]))), col="orange") lines(zoo(R_Active_SPXCPV_GJRGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_GJRGARCH11[2:length(y_hat_d_SPXCPV_GJRGARCH11)]))), col="blue") lines(zoo(R_Active_SPXCPV_GJRGARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_GJRGARCH11SVI[2:length(y_hat_d_SPXCPV_GJRGARCH11SVI)]))), col="magenta") lines(zoo(R_Active_SPXCPV_EGARCH11_p_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_EGARCH11[2:length(y_hat_d_SPXCPV_EGARCH11)]))), col="green") lines(zoo(R_Active_SPXCPV_EGARCH11SVI_p_cumulated, as.Date(zoo::index(y_hat_d_SPXCPV_EGARCH11SVI[2:length(y_hat_d_SPXCPV_EGARCH11SVI)]))), col="purple") legend(lty=1, cex=1, "topleft", col=c("black", "red", "orange", "blue", "magenta", "green", "purple"), legend=c("Buy and hold", "GARCH", "GARCH-SVI", "GJRGARCH", "GJRGARCH-SVI", "EGARCH", "EGARCH-SVI")) } save.image("C:/Users/johnukfr/OneDrive/UoE/Disertation/Maths/IDaSRP_077.4.15_SPX_CPV_Finance.RData") # sink() ####--------------------------------------------------------------------------- #### End??????????????????? ####--------------------------------------------------------------------------- # # # historical averages of positive index returns of up to time # # t are used to predict the Rising Return: # R_R_m = mean(Observed_pi_zoo * R) # # # historical averages of negative index returns of up to time # # t are used to predict the Falling Return: # # # # xi = (1- tau_m) * (1 - tau_f) # # w = ifelse(y_hat_d_EGARCH11SVI == 1, # ifelse(y_d == 1, (R_Active_p), (0)), # ifelse(y_d == 1, (0), (0))) # # # # u = function(y_hat_d, y_d) # { # ifelse(y_hat_d = 1, R_Active_p_sumed, )
b4f6013695118af9d13122f2cc3d6c72adf49ab7
d5eef5ca98115b14d13345c3e104fe4d9448b721
/man/print.SDMfit.Rd
6cfe153b07a41dc16c9f27755da43401b32d11ed
[]
no_license
giopogg/webSDM
b6e3e40fc0ee82f87b2cee3a4c2167555fc3e19a
9b011d1dcb58b9e2874f841af4874db752c73fff
refs/heads/main
2023-04-19T02:10:10.368235
2023-03-15T07:23:58
2023-03-15T07:23:58
359,931,820
5
1
null
2023-03-14T09:38:33
2021-04-20T19:39:24
R
UTF-8
R
false
true
884
rd
print.SDMfit.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/print.SDMfit.R \name{print.SDMfit} \alias{print.SDMfit} \title{Prints a SDMfit object} \usage{ \method{print}{SDMfit}(x, ...) } \arguments{ \item{x}{A SDMfit object, typically obtained with trophicSDM() and available in the field $model of a trophicSDMfit object} \item{...}{additional arguments} } \value{ Prints a summary of the local SDM } \description{ Prints a SDMfit object } \examples{ data(Y, X, G) # define abiotic part of the model env.formula = "~ X_1 + X_2" # Run the model with bottom-up control using stan_glm as fitting method and no penalisation # (set iter = 1000 to obtain reliable results) m = trophicSDM(Y, X, G, env.formula, family = binomial(link = "logit"), penal = NULL, mode = "prey", method = "stan_glm") m$model$Y1 } \author{ Giovanni Poggiato }
15f687e7462a61df6dd3a85ee05cbbbcce4955dc
e10ccafdbc900072e638285141eab217f241ae2f
/man/GeomTimeLineLabel.Rd
a0c80ab32c8d9d2f587fce7b01c4775a6e0dfb26
[]
no_license
pvisser82/earthquakedata
04e545d00a022e4b1fc794c67552b7782e2e1571
e04ab6d870acc5f4307a5fc8c8388b196c740d7f
refs/heads/master
2021-05-06T05:28:06.046277
2018-01-02T09:51:34
2018-01-02T09:51:34
115,095,231
0
0
null
null
null
null
UTF-8
R
false
true
617
rd
GeomTimeLineLabel.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/timeline.R \docType{data} \name{GeomTimeLineLabel} \alias{GeomTimeLineLabel} \title{GeomTimeLineLabel proto} \format{An object of class \code{GeomTimeLineLabel} (inherits from \code{Geom}, \code{ggproto}) of length 6.} \usage{ GeomTimeLineLabel } \description{ This geom is responsible for drawing the labels on the timeline. The number of labels are set using the n_max parameter. The function will retrieve the n_max number of highest magnitudes using the setup_data function and add the label to those earthquakes. } \keyword{datasets}
1bc9ff81d4270477ae3f7a898c6b9cb1201ce8d8
be232f39144fcd136ce0ba20549124e50d1f495a
/1-Exploratory_Data_Analysis.R
5ca54fc23c1b24da8260b4c538f0555d33585d7f
[]
no_license
davidsalazarv95/Resolve_test
f86311e406014e310ba298acc126ce6a424c9176
9cb31e331aab7d89b26df084c8b8ddfca1e44fba
refs/heads/master
2021-07-22T23:11:46.095043
2017-11-01T21:10:11
2017-11-01T21:10:11
109,029,268
0
0
null
null
null
null
UTF-8
R
false
false
2,459
r
1-Exploratory_Data_Analysis.R
################ Univariado Valor ################ library(tidyverse) library(corrplot) library(hrbrthemes) library(corrr) library(viridis) library(gridExtra) library(grid) histograma_valor <- function(datos, binwidth = 50) { medidas_centrales <- datos %>% select(valor) %>% summarise(mediana = median(valor), media = mean(valor)) datos %>% ggplot(aes(x = valor)) + geom_histogram(binwidth = binwidth, fill = "blue4", alpha = 0.5, color = "black") + theme_ipsum_rc() + scale_x_continuous(labels = scales::dollar_format(suffix = "", prefix = "$")) + geom_vline(xintercept = medidas_centrales[['mediana']], linetype = 4, show.legend = TRUE) + labs(y = "Conteo", title = "Histograma de valor de inmueble", subtitle = paste0("Cada barra representa intervalos de ", binwidth ,". Mediana como línea: ", "$",round(medidas_centrales[['mediana']], 1))) } ################ Location ################ ubicación <- function(datos) { datos %>% ggplot(aes(x = coordx, y = coordy, color = valor, size = valor)) + geom_point() + scale_color_viridis() + theme_ipsum_rc() } ################ Variación conjunta ################ matriz_correlaciones <- function(datos) { datos <- datos %>% select(-index) %>% mutate(rio = as.numeric(rio)) corrplot(cor(datos), order = "hclust", tl.col = "black") } big_three <- function(datos, num = 3) { datos <- datos %>% select(-index) %>% mutate(rio = as.numeric(rio)) correlate(datos) %>% stretch() %>% filter(x == "valor") %>% arrange(desc(abs(r))) %>% head(num) %>% select(y, r) %>% rename(Variable = y, Correlación = r) } scatterplots <- function(datos) { g1 <- datos %>% ggplot(aes(x = pobreza, y = valor)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE) + theme_ipsum_rc() + labs(title = "Valor vs. Pobreza") g2 <- datos %>% ggplot(aes(x = cuartos, y = valor)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE) + theme_ipsum_rc() + labs(title = "Valor vs. # de Cuartos") g3 <- datos %>% ggplot(aes(x = tasaeducativa, y = valor)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm") + theme_ipsum_rc() + labs(title = "Valor vs. # profesores por alumno") grid.arrange(g1, g2, g3, ncol = 2, widths = c(1.3, 1.5)) }
66488a4355c805221849ff67597c3bda2834700f
e6f4e3afd16a7ee5c7a8fb61f7ed697ce88ef4c4
/Pro3/R_p3/Subsampling_final_example.R
9ed5c50e625af4ca62d0632c0697f24044eba1bb
[]
no_license
xl0418/Code
01b58d05f7fae1a5fcfec15894ce0ed8c833fd1a
75235b913730714d538d6d822a99297da54d3841
refs/heads/master
2021-06-03T21:10:31.578731
2020-11-17T07:50:48
2020-11-17T07:50:48
136,896,128
0
0
null
null
null
null
UTF-8
R
false
false
17,707
r
Subsampling_final_example.R
library(DDD) library(ggplot2) library(ggridges) library(ggthemes) library(viridis) library("RColorBrewer") library(grid) library(gridExtra) library(ggtree) library(ape) source(paste0(getwd(),'/g_legend.R')) # source('E:/Code/Pro3/R_p3/barplot3d.R', echo=TRUE) source('E:/Code/Pro3/R_p3/multi3dbar.R', echo=TRUE) moviedir = 'E:/Googlebox/Research/Project3/replicate_sim_9sces_results/' dir = 'E:/Googlebox/Research/Project3/replicate_sim_9sces/' dir.result = 'E:/Googlebox/Research/Project3/replicate_sim_9sces_results/' sce.short = c('H','M','L') scenario = NULL sce.short.comb.vec = NULL for(i.letter in sce.short){ for(j.letter in sce.short){ sce.folder = paste0('sce',i.letter,j.letter) scenario = c(scenario,sce.folder) sce.short.comb = paste0(i.letter,j.letter) sce.short.comb.vec = c(sce.short.comb.vec,sce.short.comb) } } interleave <- function(x,y){ lx <- length(x) ly <- length(y) n <- max(lx,ly) as.vector(rbind(rep(x, length.out=n), rep(y, length.out=n))) } x_label_fontsize = 12 y_label_fontsize = 12 mu_title_fontsize = 16 mig_title_fontsize = 16 x_title_fontsize = 16 y_title_fontsize = 16 dispersal_title <- rep(c('high dispersal', 'intermediate dispersal', 'low dispersal'), each = 3) interaction_title <- rep(c('high interaction distance', 'intermediate interaction distance', 'low interaction distance'), 3) psi_title <- c('0', '0.5', '1', '0.25', '0.75') phi_title <- c('0', '-2', '-4', '-6', '-8', 0) subsampling_scale_vec <- rep(c(50,250), 2) count1 = 1 p = list() # AWMIPD mode pdmode = 'exp' a = 100 rep.sample = 18 plot.combination = rbind(c(1, 3, 3), c(1, 3, 3), c(6, 3, 4), c(6, 3, 4)) # rbind(c(1, 3, 3), # c(1, 4, 4), # c(8, 3, 2)) col_labels = NULL for(plot.comb in c(1:nrow(plot.combination))){ i_n = plot.combination[plot.comb,1] i = plot.combination[plot.comb,2] j = plot.combination[plot.comb,3] subsampling_scale <- subsampling_scale_vec[plot.comb] comb = paste0(i,j) scefolder = scenario[i_n] letter.comb = sce.short.comb.vec[i_n] sce = scenario[i_n] print(paste0('i_n = ',i_n,'; comb = ', comb)) multitreefile <- paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/','multitreen',letter.comb,comb,'.tre') replicate_trees <- read.tree(multitreefile) single.tree_example <- replicate_trees[[rep.sample]] rname_example = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'M',i,j,'rep',rep.sample,'.csv') L.table_example = read.csv(rname_example,header = FALSE) global.matrix_example = as.matrix(L.table_example) # sub area grid sub_local_matrix_example <- global.matrix_example[(167-subsampling_scale/2):(167+subsampling_scale/2), (167-subsampling_scale/2):(167+subsampling_scale/2)] species_number_example <- unique(as.vector(sub_local_matrix_example))+1 species_label_example <- paste0('t', species_number_example) # sub tree subtree_example <- keep.tip(single.tree_example, species_label_example) p[[count1]] <- ggtree(subtree_example,layout = "circular") #+xlim(0,age) count1 = count1+1 # plot SAR print('Plotting SAR...') species.area = NULL comb = paste0(i,j) for(local.scale in c(1:19,seq(20,subsampling_scale,10))){ mean.data = NULL print(paste0('i_n = ',i_n,'...','i = ', i, '; j = ',j,'; area = ',local.scale)) for(rep_sar in c(1:100)){ ns.vec=NULL rname = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'M',i,j,'rep',rep_sar,'.csv') L.table = read.csv(rname,header = FALSE) global.matrix = as.matrix(L.table) sub_local_matrix <- global.matrix[(167-subsampling_scale/2):(167+subsampling_scale/2), (167-subsampling_scale/2):(167+subsampling_scale/2)] # calculate abundances in the sub grid species_number <- unique(as.vector(sub_local_matrix)) submatrix.vec = c(0:(subsampling_scale %/% local.scale - 1))*local.scale+1 for(row.num in submatrix.vec){ local.grid = sub_local_matrix[row.num:(row.num+local.scale-1),row.num:(row.num+local.scale-1)] local.richness = length(unique(as.vector(as.matrix(local.grid)))) ns.vec = c(ns.vec, local.richness) } mean.data = c(mean.data,mean(ns.vec)) } quantile1 = quantile(mean.data) species.area = rbind(species.area,c(quantile1,i,j,i_n,local.scale)) } colnames(species.area) = c('0','25','50','75','100','i','j','i_n','area') species.area.df <- as.data.frame(species.area) area = species.area.df$area df_lineage_sar = rbind(c(rep(1,5),i,j,i_n,1),species.area.df) df_lineage_sar$`0` = log(df_lineage_sar$`0`) df_lineage_sar$`25` = log(df_lineage_sar$`25`) df_lineage_sar$`50` = log(df_lineage_sar$`50`) df_lineage_sar$`75` = log(df_lineage_sar$`75`) df_lineage_sar$`100` = log(df_lineage_sar$`100`) df_lineage_sar$area = log(df_lineage_sar$area) df_min_max_sar = data.frame(id = "min_max", value = 1, x = c(df_lineage_sar$area,rev(df_lineage_sar$area)), y = c(df_lineage_sar$'0',rev(df_lineage_sar$'100'))) df_0025_sar = data.frame(id = "0025", value = 2, x = c(df_lineage_sar$area,rev(df_lineage_sar$area)), y = c(df_lineage_sar$'25',rev(df_lineage_sar$'75'))) df_mean_sar = data.frame(id = 'mean',y = df_lineage_sar$`50`,x = df_lineage_sar$area) df_lineage_all_sar = rbind(df_min_max_sar,df_0025_sar) p[[count1]] <- ggplot(df_mean_sar, aes(x = x, y = y)) + theme(legend.position="none", panel.border = element_blank(), panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.background = element_blank(), axis.line.x = element_line(color="black"),axis.line.y = element_line(color="black") ,plot.margin=unit(c(0,0,0,0),"cm"))+ geom_polygon(data = df_min_max_sar, aes( group = id),fill = "gray70", alpha = 0.8)+ geom_polygon(data = df_0025_sar, aes( group = id),fill = "gray27", alpha = 0.8)+ geom_line()+ coord_cartesian(xlim=c(log(1),log(subsampling_scale)),ylim=c(0,log(1000))) + scale_y_continuous(name = "No. of species",breaks = log(c(1,10,100)),labels = c('1','10','100'))+ scale_x_continuous(name = "Area",breaks = log(c(1,10,100)),labels = c('1','10','100'))+ theme(axis.text.y=element_text(angle=90,size = y_label_fontsize), axis.text.x=element_text(size = x_label_fontsize)) count1 = count1+1 # SAD print("Plotting SAD...") x.breaks = seq(0,17,1) abund <- NULL for(rep_sar in c(1:100)){ ns.vec=NULL rname = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'M',i,j,'rep',rep_sar,'.csv') L.table = read.csv(rname,header = FALSE) global.matrix = as.matrix(L.table) sub_local_matrix <- global.matrix[(167-subsampling_scale/2):(167+subsampling_scale/2), (167-subsampling_scale/2):(167+subsampling_scale/2)] # calculate abundances in the sub grid species_number <- unique(as.vector(sub_local_matrix)) Rs <- NULL for (spe in species_number) { Rs <- c(Rs, length(which(as.vector(sub_local_matrix) == spe))) } log.Rs = log2(Rs) freq = hist(as.numeric(log.Rs),plot=FALSE,breaks = x.breaks) counts = freq$counts abund = rbind(abund, counts) } mean.sim = apply(abund,MARGIN=2,FUN=mean) sd.sim = sqrt(apply(abund,MARGIN=2,FUN=var)) col.quan = length(mean.sim) if(col.quan<length(x.breaks)){ mean.sim <- c(mean.sim,matrix(0,1,length(x.breaks)-col.quan)) sd.sim <- c(sd.sim,matrix(0,1,length(x.breaks)-col.quan)) } abund.df = cbind(mean.sim,sd.sim,c(1:length(x.breaks))) colnames(abund.df) <- c('mean','sd','species') abund.df <- as.data.frame(abund.df) my_labs <- interleave(seq(1,length(x.breaks),2), "") my_labs = my_labs[1:18] p[[count1]] <- ggplot(abund.df) + geom_bar( aes(x=species, y=mean),width = 0.6, stat="identity", fill="red", alpha=0.7) + geom_errorbar( aes(x=species, ymin=mean-sd, ymax=mean+sd), width=0.4, colour="blue", alpha=0.7, size=1.3)+ geom_line(aes(species, mean),size=0.8,color="blue")+ #theme_gdocs()+ #scale_color_calc()+ scale_x_continuous(name="Abundance (log2)", breaks=seq(1,length(x.breaks),1),labels = my_labs) + scale_y_continuous(name="Frequency",breaks=seq(0,60,20))+ theme(axis.text.x = element_text(angle = 90,vjust = 0.5),panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), strip.background = element_blank(),strip.text.x = element_text(size = 12, colour = "black"), strip.text.y = element_text(size = 12, colour = "black")) count1 = count1+1 # AWMIPD print('Plotting AWMIPD...') # rname = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'M',comb,'rep',rep.sample,'.csv') # L.table = read.csv(rname,header = FALSE) Dname_example = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'D',comb,'rep',rep.sample,'.csv') D.table_example = read.csv(Dname_example,header = FALSE) Rname_example = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'R',comb,'rep',rep.sample,'.csv') R.table_example = read.csv(Rname_example,header = FALSE) R.table_example <- R.table_example[species_number_example] # global.matrix = as.matrix(L.table) D.matrix_example = as.matrix(D.table_example) * 2 / 10^7 D.matrix_example = D.matrix_example[species_number_example,species_number_example] # phylogenetic distance if (pdmode == 'inv') { ID = 1 / D.matrix_example diag(ID) = 1 AD.matrix = sweep(ID, MARGIN = 2, as.matrix(as.numeric(R.table_example)), `*`) } else if (pdmode == 'exp') { ID = exp(- a * D.matrix_example) AD.matrix = sweep(ID, MARGIN = 2, as.matrix(as.numeric(R.table_example)), `*`) } total.dvalues = rowSums(AD.matrix) * as.matrix( as.numeric(R.table_example)) D.normalized = total.dvalues/sum(total.dvalues) D.normalized = (D.normalized-min(D.normalized))/(max(D.normalized)-min(D.normalized)) local.x = c(1:subsampling_scale) local.y = c(1:subsampling_scale) distribution.data = expand.grid(X=local.x,Y=local.y) distribution.data$Z = sub_local_matrix_example[cbind(distribution.data$X,distribution.data$Y)] distribution.data$D = D.normalized[match((distribution.data$Z+1), species_number_example) ] p[[count1]] <- ggplot(distribution.data, aes(X, Y, fill= D)) + geom_tile()+ theme(legend.position = '',axis.text = element_blank(),axis.ticks = element_blank(), panel.background = element_blank())+ xlab("")+ylab("") + scale_fill_gradient2(low="#648FFF",mid = '#DDCC77', high="#882255",midpoint=0.5) count1 = count1+1 # LTT plot print("Plotting LTT...") subtrees <- list() tree_index <- 1 for (rep.ltt in c(1:100)) { single.tree <- replicate_trees[[rep.ltt]] rname = paste0(dir,scefolder,'/results/1e+07/spatialpara1e+07',letter.comb,comb,'/',letter.comb,'M',i,j,'rep',rep.ltt,'.csv') M.table = read.csv(rname,header = FALSE) global.matrix = as.matrix(M.table) if (length(single.tree$tip.label) == length(unique(as.vector(global.matrix)))) { # sub area grid sub_local_matrix <- global.matrix[(167-subsampling_scale/2):(167+subsampling_scale/2), (167-subsampling_scale/2):(167+subsampling_scale/2)] species_number <- unique(as.vector(sub_local_matrix))+1 species_label <- paste0('t', species_number) # sub tree subtree <- keep.tip(single.tree, species_label) subtrees[[tree_index]] <- subtree tree_index <- tree_index+1 } else { print('Inconsistent diversity...') } } class(subtrees) <- "multiPhylo" trees <- subtrees age = 10000000 data = NULL for (tree_i in 1:length(trees)) { tes = trees[[tree_i]] brts= -unname(sort(branching.times(tes),decreasing = T)) data0 = cbind(tree_i,brts,c(2:(length(brts)+1))) if(max(brts)<0) data0 = rbind(data0,c(tree_i,0,data0[nrow(data0),3])) data = rbind(data, data0) } time = data[order(data[,2]),2] timeu = unique(time) data_lineage = timeu for(tree_i in 1:length(trees)){ tes = trees[[tree_i]] brts= -unname(sort(branching.times(tes),decreasing = T)) M1 = match(brts,timeu) M1[1] = 1 M11 = diff(M1) M13 = length(timeu)-max(M1)+1 M12 = c(M11,M13) N1 = rep(2:(length(brts)+1),M12) data_lineage = cbind(data_lineage,N1) } x = data_lineage[,1] z = data_lineage[,2:length(trees)+1] data_average_z <- apply(z, 1, median) data_q0.025_z <- apply(z, 1 , quantile, 0.025) data_q0.25_z <- apply(z, 1, quantile, 0.25) data_q0.75_z <- apply(z, 1, quantile, 0.75) data_q0.975_z <- apply(z, 1, quantile, 0.975) data_lower_z <- apply(z,1,min) data_upper_z <- apply(z,1,max) lineage_stat = cbind(x,log(data_average_z),log(data_q0.025_z),log(data_q0.25_z),log(data_q0.75_z),log(data_q0.975_z),log(data_lower_z),log(data_upper_z)) colnames(lineage_stat) = c("time", "median","0.025","0.25","0.75","0.975","min","max") time = min(lineage_stat[,1]) df_lineage = data.frame(lineage_stat) df_min_max = data.frame(id = "min_max", value = 1, x = c(df_lineage$time,rev(df_lineage$time)), y = c(df_lineage$min,rev(df_lineage$max))) df_0025 = data.frame(id = "0025", value = 2, x = c(df_lineage$time,rev(df_lineage$time)), y = c(df_lineage$X0.025,rev(df_lineage$X0.975))) df_025 = data.frame(id = "025", value = 3, x = c(df_lineage$time,rev(df_lineage$time)), y = c(df_lineage$X0.25,rev(df_lineage$X0.75))) df_lineage_all = rbind(df_min_max,df_025,df_0025) p[[count1]] <- ggplot(df_min_max, aes(x = x, y = y)) + theme(legend.position="none", panel.border = element_blank(), panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.background = element_blank(), axis.line.x = element_line(color="black"),axis.line.y = element_line(color="black") ,plot.margin=unit(c(0,0,0,0),"cm"))+ geom_polygon(data = df_min_max, aes( group = id),fill = "gray80", alpha = 0.8)+ geom_polygon(data = df_0025, aes( group = id),fill = "gray50", alpha = 0.8)+ geom_polygon(data = df_025, aes( group = id), fill = "gray27", alpha = 0.8)+ coord_cartesian(xlim=c(-age,0),ylim=c(log(2),log(600))) + scale_y_continuous(name="No. of species",breaks = c(log(2),log(10),log(50),log(400)),labels = c(2,10,50,400))+ scale_x_continuous(name="Time",breaks = -rev(seq(0,1e7,1e7/5)),labels = c('10','8','6','4','2','0'))+ theme(axis.text.y=element_text(angle=90,size = y_label_fontsize),axis.text.x=element_text(size = x_label_fontsize)) count1 = count1+1 col_labels <- c(col_labels, paste0('SPJC ', dispersal_title[i_n], ' &\n', interaction_title[i_n], '\n', 'scale = ',subsampling_scale)) } m = matrix(1:20,ncol = 4) row_labels = c('Tree', 'SAR','SAD','SPD','LTT') phi1 <- textGrob(row_labels[1], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) phi2 <- textGrob(row_labels[2], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) phi3 <- textGrob(row_labels[3], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) phi4 <- textGrob(row_labels[4], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) phi5 <- textGrob(row_labels[5], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi11 <- textGrob(col_labels[1], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi12 <- textGrob(col_labels[2], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi13 <- textGrob(col_labels[3], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi14 <- textGrob(col_labels[4], gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi21 <- textGrob(bquote(psi == .(psi_title[plot.combination[1, 2]]) ~ phi == 10^.(phi_title[plot.combination[1, 3]])), gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi22 <- textGrob(bquote(psi == .(psi_title[plot.combination[2, 2]]) ~ phi == 10^.(phi_title[plot.combination[2, 3]])), gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi23 <- textGrob(bquote(psi == .(psi_title[plot.combination[3, 2]]) ~ phi == 10^.(phi_title[plot.combination[3, 3]])), gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) psi24 <- textGrob(bquote(psi == .(psi_title[plot.combination[4, 2]]) ~ phi == 10^.(phi_title[plot.combination[4, 3]])), gp=gpar(fontsize=mu_title_fontsize, fontface=3L)) row_titles <- arrangeGrob(phi1,phi2,phi3,phi4,phi5,ncol = 1) column_titles1 <- arrangeGrob(psi11,psi12,psi13,psi14, ncol = 4) column_titles2 <- arrangeGrob(psi21,psi22,psi23,psi24,ncol = 4) # label = textGrob("Number of lineages",gp=gpar(fontsize=y_title_fontsize), rot = 90) g_ltt4 = arrangeGrob(grobs = p, layout_matrix = m) g_ltt5 = textGrob("area", gp=gpar(fontsize=x_title_fontsize),rot = 0) g_ltt1 = textGrob("") g_a = textGrob("(a)") g_b = textGrob("(b)") ltt.sce <- grid.arrange(column_titles1,g_ltt1, column_titles2,g_ltt1, g_ltt4,row_titles,ncol = 2,widths = c(24,1),heights = c(2,1,25)) dir_save <- 'E:/Googlebox/Research/Project3/replicate_sim_9sces_results/' savefilename <- paste0(dir_save,'mixing_example_subscale_a100.png') ggsave(savefilename,ltt.sce,width = 20,height = 15)
7ea35b0a1016904316bebadfef3fd5cbd1eef18c
54833a5f2af934ba192600b0c2550f0ce2e4d97f
/in-action/apis/analysis.R
2cd34a49d3c53e55a5e61f04e57846f28789cd56
[ "MIT" ]
permissive
HOXOMInc/programming-skills-for-data-science
2e47fb2a445e71bcfe3d7acc2a881fda217e4a2e
5aa1e954434674789c5df9518f8f137c3b91358b
refs/heads/main
2023-06-27T02:03:13.023455
2021-07-25T05:00:55
2021-07-25T05:00:55
319,144,846
2
4
null
2021-01-17T07:56:40
2020-12-06T22:28:03
null
UTF-8
R
false
false
2,300
r
analysis.R
# APIs in Action: シアトルのキューバレストラン # 必要なパッケージをロードする library(httr) library(jsonlite) library(dplyr) library(ggrepel) # ggmapの開発中のバージョンをインストール・ロードする library(devtools) # GitHubからパッケージをインストールする devtools::install_github("dkahle/ggmap", ref = "tidyup") library(ggmap) # Google API Keyを登録する # https://developers.google.com/maps/documentation/geocoding/get-api-key register_google(key="YOUR_GOOGLE_KEY") # Yelp APIキーを"api_key.R"からロードする source("api_key.R") # ロードすることで`yelp_key`変数が使えるようになる # Yelp Fusion API's Business Searchエンドポイントの検索クエリを作成する base_uri <- "https://api.yelp.com/v3" endpoint <- "/businesses/search" search_uri <- paste0(base_uri, endpoint) # クエリ変数を代入する query_params <- list( term = "restaurant", categories = "cuban", location = "Seattle, WA", sort_by = "rating", radius = 8000 # ドキュメントに記載あるようにradiusの単位はメートルとなっている ) # APIキーとクエリ変数を用いてGETリクエストを作成する response <- GET( search_uri, query = query_params, add_headers(Authorization = paste("bearer", yelp_key)) ) # リクエストの結果をパースする response_text <- content(response, type = "text") response_data <- fromJSON(response_text) # `response_data`変数の内容を調査する names(response_data) # [1] "businesses" "total" "region" # flatten()を用いて`response_data$businesses`をデータフレームに変換する restaurants <- flatten(response_data$businesses) # データフレームに必要な列を追加する restaurants <- restaurants %>% mutate(rank = row_number()) %>% # 行数をランクとする mutate(name_and_rank = paste0(rank, ". ", name)) # 地図のベースとなるレイヤーを作成する(シアトルのGoogle Maps画像) base_map <- ggmap( get_map( location = c(-122.3321, 47.6062), zoom = 11, source = "google") ) # 地図にラベルを付与する base_map + geom_label_repel( data = restaurants, aes(x = coordinates.longitude, y = coordinates.latitude, label = name_and_rank) )
603b4e282ca403212d04bd1f9473358524542273
63e1231faa30a4cea6dd9f25e87c2372383aa2f4
/man/L2A.Rd
d8b36f47d29d7c36320ae8a050356a14ec4ac7b2
[]
no_license
cran/MSEtool
35e4f802f1078412d5ebc2efc3149c46fc6d13a5
6b060d381adf2007becf5605bc295cca62f26770
refs/heads/master
2023-08-03T06:51:58.080968
2023-07-19T22:10:23
2023-07-20T01:47:18
145,912,213
1
0
null
null
null
null
UTF-8
R
false
true
661
rd
L2A.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Misc_Exported.R \name{L2A} \alias{L2A} \title{Length to age conversion} \usage{ L2A(t0c, Linfc, Kc, Len, maxage, ploty = F) } \arguments{ \item{t0c}{Theoretical age at length zero} \item{Linfc}{Maximum length} \item{Kc}{Maximum growth rate} \item{Len}{Length} \item{maxage}{Maximum age} \item{ploty}{Should a plot be included} } \value{ An age (vector of ages, matrix of ages) corresponding with Len } \description{ Simple deterministic length to age conversion given inverse von Bertalanffy growth. } \author{ T. Carruthers } \keyword{internal}
4f678fec2c41c02a12223a5edc4836843ffa880c
15f26ad8f0fef7e64ab39a39fcfcf501ae15c5f1
/man/zipf_race.Rd
5340181924bedcc822f0696f7fff4eda1ab04098
[]
no_license
seqva/RcappeR
56120272f9b39287e579134346e268800fd78bf6
e84bdf0b386898fc4b88850cb298efaa442cdca0
refs/heads/master
2020-07-02T15:13:55.485347
2016-02-26T00:02:30
2016-02-26T00:02:30
null
0
0
null
null
null
null
UTF-8
R
false
true
1,437
rd
zipf_race.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/zipf_race.R \name{zipf_race} \alias{zipf_race} \title{Handicap a race using one race} \source{ Article by Simon Rowlands explaining use of Zipf's Law: \url{https://betting.betfair.com/horse-racing/bloggers/simon-rowlands/simon-rowlands-on-handicapping-060710.html} } \usage{ zipf_race(race, btn_var, race_2, rating = NULL) } \arguments{ \item{race}{dataframe of race to handicap} \item{btn_var}{name of variable which contains the margins between the horses} \item{race_2}{dataframe of a race to be used to handicap \strong{race}} \item{rating}{name of ratings variable (if applicable) in \strong{race_2}} } \description{ Assess the performance of a winner (ie handicap) of a race using race standardisation; which uses the performances of runners in a different, but similar, race for this assessment. It is called by \link{zipf_hcp} and \link{zipf_init}. } \details{ The method of race standardisation used was first explained by Simon Rowlands and uses Zipfs Law. The difference at the weights, from the race to be handicapped, is applied to the second race, creating a vector of possible ratings the victor could have achieved. This is where Zipfs Law plays its part, as depending on the finishing position, different weights are assigned to each of the ratings in the vector, placing more significance on horses towards the front of the field. }
3fc057d66e362395b0c16524e5dd5b34ef1fa2ee
eec115235405a54b642d3286863dcca14786c9e8
/experiments/experiment_variance_pvalue_plotter.R
62f1cd1ef596df03b50c504aea082e213e20eb55
[]
no_license
linnykos/selectiveModel
5f5c95f84c006dc8bd83fdc2032ea251a9f4d3e6
75e42567a9a4fe1daf4d80a54cc15e47e549f60d
refs/heads/master
2023-01-21T18:24:22.665232
2020-12-01T16:45:43
2020-12-01T16:45:43
110,089,332
0
0
null
null
null
null
UTF-8
R
false
false
550
r
experiment_variance_pvalue_plotter.R
png("../figures/pvalue_stability.png", heigh = 2000, width = 2500, units = "px", res = 300) par(mfrow = c(2,2)) hist(res_vec_known_0, breaks = seq(0, 1, length.out = 50), col = "gray", xlab = "P-value", main = "Delta = 0 (Null), Known sigma") hist(res_vec_unknown_0, breaks = seq(0, 1, length.out = 50), col = "gray", xlab = "P-value", main = "Delta = 0 (Null), Unknown sigma") hist(res_vec_known_signal, breaks = seq(0, 1, length.out = 50), col = "gray", xlab = "P-value", main = "Delta = 1 (Signal), Known sigma") graphics.off()
ea6a9546894cf4023fe51412c984a1663c14c325
2a6dc4ea444f5522291923ef172865314c4bc9e8
/R/sgdWt_convexLinCom.R
f01dace307c7cc895353b5db58bb578fc93a64f7
[]
no_license
benkeser/onlinesl
e482e8606268a546011d6bc01019bb5e51c30ad3
acf1935523cf5bdf4c0408f55f7930e74bc7f384
refs/heads/master
2020-12-26T04:27:31.876193
2016-09-22T15:41:39
2016-09-22T15:41:39
66,727,503
3
1
null
null
null
null
UTF-8
R
false
false
1,228
r
sgdWt_convexLinCom.R
#' Perform first order stochastic gradient descent update of super learner #' weights #' #' This function performs a single step of gradient descent on the weight #' vector for the super learner weights and projects the resulting vector onto #' the L1-simplex via the internal function .projToL1Simp. The function returns #' the updated weight vector. #' #' @param Y The outcome at iteration t #' @param slFit.t A named list with a component named alpha.t that contains the #' 1-column matrix of current estimate of the super learner weights #' @param p.t The predictions from the various online algorithms at time t #' @param tplus1 The iteration of the online algorithm #' @param stepSize The size of the step to take in the direction of the #' gradient. If \code{stepSize=NULL} (default) the function uses #' \code{1/tplus1}. #' #' @return alpha A matrix of updated weights. #' #' @export sgdWt_convexLinCom <- function(Y,slFit.t,p.t,tplus1,stepSize=NULL){ if(is.null(stepSize)){ stepSize <- 1/tplus1 } grad <- - t(p.t) %*% (Y - p.t%*%slFit.t$alpha) cwt <- slFit.t$alpha - stepSize * grad wt.tplus1 <- onlinesl:::.projToL1Simp(cwt) list(alpha=wt.tplus1) }
bebc5f4c8b628eb1df2a6ed9317a3a70edfb8f75
d966e9fe4e0e667b20cad92c1cd21a55ccf401a9
/R/TitanicAnalysis01_lowlevel.R
7153869eccee011ae6bffcff697c456e0f92c140
[]
no_license
darsa881r/titanic
0efbb92d408958de5860e431206319403e87e71a
f519ab108bf7eede6c9f5126cc33d5228062ae4b
refs/heads/master
2022-11-26T17:03:12.945916
2020-08-10T20:52:28
2020-08-10T20:52:28
286,527,686
0
0
null
null
null
null
UTF-8
R
false
false
30,361
r
TitanicAnalysis01_lowlevel.R
# Loading default Libraries library("ggplot2") library("datasets") library("graphics") library("grDevices") library("methods") library("stats") library("utils") # Loading data train <- read.csv("/Users/sabbirhassan/Dropbox/ML_stuff/titanic/train.csv", header = TRUE) test <- read.csv("/Users/sabbirhassan/Dropbox/ML_stuff/titanic/test.csv", header = TRUE) #train <- read.csv("D:\\Dropbox\\ML_stuff\\titanic\\train.csv", header = TRUE) #test <- read.csv("D:\\Dropbox\\ML_stuff\\titanic\\test.csv", header = TRUE) # Adding Survived empty valued column in test set test.survived <- data.frame(Survived = rep("None",nrow(test)),test[,]) # Combining the two data sets data.combined <- rbind(train, test.survived) #look at the datatypes str(data.combined) # Pclass seems like int but actually its an factor (or categorical) data # Survived also seems char type but its supposed to be a factortype data.combined$Pclass <- as.factor(data.combined$Pclass) data.combined$Survived <- as.factor(data.combined$Survived) # Take a look at survival frequencies table(data.combined$Survived) table(data.combined$Pclass) # But instead of tabular representation we visualize for more insight train$Pclass <- as.factor(train$Pclass) train$Survived <- as.factor(train$Survived) test$Pclass <- as.factor(test$Pclass) ggplot(train, aes(x = Pclass, fill = factor(Survived))) + geom_bar(width = 0.5) + xlab("Pclass") + ylab("Total Count") + labs(fill = "Survived") # This shows the society class does play a role in survival head(as.character((train$Name))) length(unique(as.character(data.combined$Name))) # Lets find the duplicate names dup.names <- as.character(data.combined[which(duplicated(as.character(data.combined$Name))), "Name"]) # Now lets pullout this name and check their records data.combined[which(data.combined$Name %in% dup.names),] # So we can decide they are different people # Now we see Miss , Mr, Mrs are inside the Names, So lets extract them out library(stringr) misses <- data.combined[which(str_detect(data.combined$Name, "Miss.")),] summary(misses) mrs <- data.combined[which(str_detect(data.combined$Name, "Mrs.")),] males <- data.combined[which(train$Sex == "male"),] # Do something New with function # extract title using a function extractTitle <- function(Name) { name <- as.character(Name) if (length(grep("Miss.", name))>0) { return ("Miss.") } else if (length(grep("Master.", name))>0) { return("Master.") } else if (length(grep("Mrs.", name))>0) { return("Mrs.") } else if (length(grep("Mr.", name))>0) { return("Mr.") } else { return("Other") } } titles <- NULL for (i in 1:nrow(data.combined)) { titles <- c(titles, extractTitle(data.combined[i,"Name"])) } data.combined$title <- as.factor(titles) ggplot(data.combined[1:891,], aes(x = title, fill= factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass) + ggtitle("Pclass") + xlab("Title") + ylab("total count")+ labs(fill = "Survived") # look at sex table(data.combined$Sex) ggplot(data.combined[1:891,], aes(x = Sex, fill= factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass) + ggtitle("Pclass") + xlab("Sex") + ylab("Total Count")+ labs(fill = "Survived") # look at Age summary(data.combined$Age) summary(data.combined[1:891,"Age"]) # we see a lot of missing values; so how to deal with them? # what are the imputation methods? Gradient boosting trees: xgboost, lightgbm ??? ggplot(data.combined[1:891,], aes(x = Age, fill= factor(Survived))) + geom_bar(width = 10) + facet_wrap(~Sex+Pclass) + ggtitle("Pclass") + xlab("Age") + ylab("Total Count") + labs(fill = "Survived") # validate that master is a good proxy of male choldren boys <- data.combined[which(data.combined$title == "Master."),] summary(boys$Age) girls <- data.combined[which(data.combined$title == "Miss."),] summary(girls$Age) adultmales <- data.combined[which(data.combined$title == "Mr."),] summary(adultmales$Age) adultfemales <- data.combined[which(data.combined$title == "Mrs."),] summary(adultfemales$Age) ggplot(misses[misses$Survived != "None",], aes(x = Age, fill= factor(Survived))) + geom_bar(width = 5) + facet_wrap(~Pclass) + ggtitle("Pclass") + xlab("Age") + ylab("Total Count") labs(fill = "Survived") # looking closer into female misses misses.alone <- misses[which(misses$SibSp == 0 & misses$Parch == 0),] summary(misses.alone$Age) length(which(misses.alone$Age <= 14.5)) # this insight is helpful for feature engineering # look look into Sibsp variable summary(data.combined$SibSp) # can we treat this as a categorical variable? as its #finite value, and make a dropdown list to select or sth. length(unique(data.combined$SibSp)) # only 7, so we can turn it into factors ggplot(data.combined[1:891,], aes(x = SibSp, fill= factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title) + ggtitle("Pclass, title") + xlab("SibSp") + ylab("Total Count") + ylim(0,300) + labs(fill = "Survived") ggplot(data.combined[1:891,], aes(x = as.factor(Parch), fill= as.factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title) + ggtitle("Pclass, title") + xlab("Parch") + ylab("Total Count") + ylim(0,300) + labs(fill = "Survived") #Create a family size feature temp.SibSp <- c(train$SibSp, test$SibSp) temp.Parch <- c(train$Parch, test$Parch) data.combined$family <- as.factor(temp.Parch+temp.SibSp+1) #Now lets look into this new feature ggplot(data.combined[1:891,], aes(x = as.factor(family), fill= as.factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title) + ggtitle("Pclass, title") + xlab("Family Size") + ylab("Total Count") + ylim(0,300) + labs(fill = "Survived") # Looking into tickets and fares str(data.combined$Ticket) data.combined$Ticket <- as.character(data.combined$Ticket) # lets start looking at just the frst character for each Ticket.first.char <- ifelse(data.combined$Ticket == ""," ", substr(data.combined$Ticket,1,1)) unique(Ticket.first.char) #we can make it a factor data.combined$Ticket.first.char <- as.factor(Ticket.first.char) ggplot(data.combined[1:891,], aes(x = as.factor(Ticket.first.char), fill= as.factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title) + ggtitle("Pclass, title") + xlab("Ticket First Char") + ylab("Total Count") + ylim(0,200) + labs(fill = "Survived") ggplot(data.combined[1:891,], aes(x = as.factor(Ticket.first.char), fill= as.factor(Survived))) + geom_bar(width = 0.5) + #facet_wrap(~Pclass + title) + #ggtitle("Pclass, title") + xlab("Ticket First Char") + ylab("Total Count") + ylim(0,200) + labs(fill = "Survived") # there probably very strng correlation betn class and fare price. it's obvious, but lets take a look at it str(data.combined$Fare) summary(data.combined$Fare) length(unique(data.combined$Fare)) ggplot(data.combined[1:891,], aes(x = Fare, fill= as.factor(Survived))) + geom_bar(width = 5, position = "stack") + #facet_wrap(~Pclass + title) + ggtitle("Fare Distribution") + xlab("Fare") + ylab("Total Count") + ylim(0,50) + labs(fill = "Survived") #probably fare doesnt affet much? #analysis in caboin variable str(data.combined$Cabin) length(unique(as.character(data.combined$Cabin))) # random forest is looking to be useful here, but default factor levels RF can use is 32 summary(data.combined$Cabin) # seems that some blank maybe there data.combined$Cabin[1:100] #replace empty cabin with U data.combined$Cabin <- as.character(data.combined$Cabin) data.combined[(as.character(data.combined$Cabin) == ""),"Cabin"] <-"U" #from cabin names we can see that the frst char might be importatn Cabin.first.char <- substr(data.combined$Cabin,1,1) str(Cabin.first.char) unique(Cabin.first.char) #we can make it a factor data.combined$Cabin.first.char <- as.factor(Cabin.first.char) ggplot(data.combined[1:891,], aes(x = as.factor(Cabin.first.char), fill= as.factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title) + ggtitle("Pclass, title") + xlab("Cabin First Char") + ylab("Total Count") + ylim(0,700) + labs(fill = "Survived") ggplot(data.combined[1:891,], aes(x = as.factor(Cabin.first.char), fill= as.factor(Survived))) + geom_bar(width = 0.5) + #facet_wrap(~Pclass + title) + #ggtitle("Pclass, title") + xlab("Cabin First Char") + ylab("Total Count") + ylim(0,700) + labs(fill = "Survived") #seemes like strong correlationwit Pclass, so no new info, not thathelpful !! # what about ppl with multiple cabins data.combined$Cabin.multiple <- as.factor(ifelse(str_detect(data.combined$Cabin, " "),"Y","N")) ggplot(data.combined[1:891,], aes(x = as.factor(Cabin.multiple), fill= as.factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title) + ggtitle("Pclass, title") + xlab("Cabin multiple") + ylab("Total Count") + ylim(0,200) + labs(fill = "Survived") #seems not that important , even though RF algorithm will tell us later # checking Embraked column ggplot(data.combined[1:891,], aes(x = as.factor(Embarked), fill= as.factor(Survived))) + geom_bar(width = 0.5) + facet_wrap(~Pclass + title, nrow = 3, ncol = 5) + ggtitle("Pclass, title") + xlab("Embarked") + ylab("Total Count") + ylim(0,100) + labs(fill = "Survived") # So exploratory analysis tells us that some variables asre important and some can be replaced by our #derived features, but what evidence can we use to rule a column out? #Now how we can get the idea of feature importance? some models do it implicitly : RF #sometimes we need to do PCA to know importance. #Lets Do Random forest and then upgrade to Xgboost later . (also show that Logistic is not good) #what about neural network for categorical data #install.packages("randomForest") library(randomForest) #tarin a random forest with default parameters #lets check all the vars # rf.train.1 <- data.combined[1:891,c("Pclass","Sex","SibSp","Parch","Fare","Embarked","title","family","Ticket.first.char","Cabin.first.char","Cabin.multiple")] #taking just two important cols that we think # #we drop Age due to missing values # rf.label <- as.factor(train$Survived) # # set.seed(1) #seting seed to verify a random run # rf.1 <- randomForest(x=rf.train.1, y=rf.label, importance = TRUE, ntree = 1000) # # rf.1 #just this output gives some info esp the confusion matrix and oob (out of the bag) # importance(rf.1) #getting importance values # varImpPlot(rf.1) #taking the frst 4 variables rf.train.2 <- data.combined[1:891,c("title","family","Ticket.first.char","Cabin.first.char")] #taking just two important cols that we think #we drop Age due to missing values rf.label <- as.factor(train$Survived) set.seed(1) #seting seed to verify a random run rf.2 <- randomForest(x=rf.train.2, y=rf.label, importance = TRUE, ntree = 1000) rf.2 #just this output gives some info esp the confusion matrix and oob (out of the bag) importance(rf.2) #getting importance values varImpPlot(rf.2) #Making predictions # Ommiting NA and predicting test.submit.df <- data.combined[892:1309, c("title","family","Ticket.first.char","Cabin.first.char")] rf.2.pred <- predict(rf.2, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.2.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190205_1.csv", row.names = FALSE) #installed.packages(caret) library(caret) # good for Crossvalidation process; but its really expensive in terms of computaitons #install.packages(doSNOW) library(doSNOW) # default cross validation settings is 10-fold cross validation repeated 10 times is standard # caret works parallely and uses cores of the PC. #doSNOW works on both MAc and Windows using parallelizinf the work for caret # so we need 10 * 10 = 100 fols that are random. # # # set.seed(5) # cv.10.folds <- createMultiFolds(rf.label, k = 10, times = 10) #creates bunch of indexes # # #check stratification , caret can do it for you. # #its usefull for small amount of imbalancing # # table(rf.label) # 342/549 # # table(rf.label[cv.10.folds[[32]]]) # 308/494 # # #seems like the ratio is okay # library("e1071") # cntrl.1 <- trainControl(method = "repeatedcv", number = 10, repeats = 10, # index = cv.10.folds) # # setting up doSNOW package for multi-core training; doMC only works on Linux # cl <- makeCluster(4, type = "SOCK") # registerDoSNOW(cl) # # set.seed(10) # rf.2.cv.1 <- train(x = rf.train.2, y = rf.label, method = "rf", tuneLength = 3, # ntree = 1000, trControl = cntrl.1) # # #Shut down cluster # stopCluster(cl) # # #checkout results # # rf.2.cv.1 # # #maybe 10 folds overfit... what happens if we do 5 fold? # set.seed(15) # cv.5.folds <- createMultiFolds(rf.label, k = 5, times = 10) #creates bunch of indexes # # #check stratification , caret can do it for you. # #its usefull for small amount of imbalancing # # # cntrl.2 <- trainControl(method = "repeatedcv", number = 10, repeats = 10, # index = cv.5.folds) # # setting up doSNOW package for multi-core training; doMC only works on Linux # cl <- makeCluster(4, type = "SOCK") # registerDoSNOW(cl) # # set.seed(20) # rf.2.cv.2 <- train(x = rf.train.2, y = rf.label, method = "rf", tuneLength = 3, # ntree = 1000, trControl = cntrl.2) # # #Shut down cluster # stopCluster(cl) # # #checkout results # # rf.2.cv.2 # set.seed(25) cv.3.folds <- createMultiFolds(rf.label, k = 3, times = 10) #creates bunch of indexes #check stratification , caret can do it for you. #its usefull for small amount of imbalancing cntrl.3 <- trainControl(method = "repeatedcv", number = 10, repeats = 10, index = cv.3.folds) # setting up doSNOW package for multi-core training; doMC only works on Linux cl <- makeCluster(4, type = "SOCK") registerDoSNOW(cl) set.seed(30) rf.2.cv.3 <- train(x = rf.train.2, y = rf.label, method = "rf", tuneLength = 3, ntree = 64, trControl = cntrl.3) #also reducing the trees #Shut down cluster stopCluster(cl) #checkout results rf.2.cv.3 #so this 3-fold maybe more generalized and better. test.submit.df <- data.combined[892:1309, c("title","family","Ticket.first.char","Cabin.first.char")] rf.2.cv.3.pred <- predict(rf.2.cv.3, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.2.cv.3.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190205_2.csv", row.names = FALSE) # a small improvement in Kaggle 0.6 % # the link has a basic tutorial using caret # https://www.analyticsvidhya.com/blog/2016/12/practical-guide-to-implement-machine-learning-with-caret-package-in-r-with-practice-problem/ # Let's look into the details of a decision tree to understand # install.packages("rpart") # install.packages("rpart.plot") # library("rpart") # library("rpart.plot") # LEts update the titles and look at it more closely # Parse out last name and title data.combined[1:25, "Name"] name.splits <- str_split(data.combined$Name, ",") name.splits[1] last.names <- sapply(name.splits, "[", 1) # paralell and vectorize applies a function on all elements last.names[1:10] # "[" is the indexing element # Add last names to dataframe in case we find it useful later data.combined$last.name <- last.names # Now for titles name.splits <- str_split(sapply(name.splits, "[", 2), " ") titles <- sapply(name.splits, "[", 2) unique(titles) # What's up with a title of 'the'? data.combined[which(titles == "the"),] # Re-map titles to be more exact titles[titles %in% c("Dona.", "the")] <- "Lady." titles[titles %in% c("Ms.", "Mlle.")] <- "Miss." titles[titles == "Mme."] <- "Mrs." titles[titles %in% c("Jonkheer.", "Don.")] <- "Sir." titles[titles %in% c("Col.", "Capt.", "Major.")] <- "Officer" table(titles) # Make title a factor data.combined$New.title <- as.factor(titles) # Visualize new version of title ggplot(data.combined[1:891,], aes(x = New.title, fill = Survived)) + geom_bar() + facet_wrap(~ Pclass) + ggtitle("Surival Rates for new.title by pclass") # Collapse titles based on visual analysis indexes <- which(data.combined$New.title == "Lady.") data.combined$New.title[indexes] <- "Mrs." indexes <- which(data.combined$New.title == "Dr." | data.combined$New.title == "Rev." | data.combined$New.title == "Sir." | data.combined$New.title == "Officer") data.combined$New.title[indexes] <- "Mr." # Visualize ggplot(data.combined[1:891,], aes(x = New.title, fill = Survived)) + geom_bar() + facet_wrap(~ Pclass) + ggtitle("Surival Rates for Collapsed new.title by pclass") # Grab features features <- c("Pclass", "New.title","family","Ticket.first.char","Cabin.first.char") # Dive in on 1st class Mr." indexes.first.mr <- which(data.combined$New.title == "Mr." & data.combined$Pclass == "1") first.mr.df <- data.combined[indexes.first.mr, ] summary(first.mr.df) # One female? so this Dr is a woman first.mr.df[first.mr.df$Sex == "female",] # Update new.title feature indexes <- which(data.combined$New.title == "Mr." & data.combined$Sex == "female") data.combined$New.title[indexes] <- "Mrs." # Any other gender slip ups? length(which(data.combined$Sex == "female" & (data.combined$New.title == "Master." | data.combined$New.title == "Mr."))) # Refresh data frame indexes.first.mr <- which(data.combined$New.title == "Mr." & data.combined$Pclass == "1") first.mr.df <- data.combined[indexes.first.mr, ] # Let's look at surviving 1st class "Mr." summary(first.mr.df[first.mr.df$Ssurvived == "1",]) View(first.mr.df[first.mr.df$Survived == "1",]) # Take a look at some of the high fares # Visualize survival rates for 1st class "Mr." by fare ggplot(first.mr.df, aes(x = Fare, fill = Survived)) + geom_density(alpha = 0.5) + ggtitle("1st Class 'Mr.' Survival Rates by fare") # Engineer features based on all the passengers with the same ticket # getting per person avg fare. instead of whole pclass fare ticket.party.size <- rep(0, nrow(data.combined)) avg.fare <- rep(0.0, nrow(data.combined)) tickets <- unique(data.combined$Ticket) for (i in 1:length(tickets)) { current.ticket <- tickets[i] party.indexes <- which(data.combined$Ticket == current.ticket) current.avg.fare <- data.combined[party.indexes[1], "Fare"] / length(party.indexes) for (k in 1:length(party.indexes)) { ticket.party.size[party.indexes[k]] <- length(party.indexes) avg.fare[party.indexes[k]] <- current.avg.fare } } data.combined$ticket.party.size <- ticket.party.size data.combined$avg.fare <- avg.fare # Refresh 1st class "Mr." dataframe first.mr.df <- data.combined[indexes.first.mr, ] summary(first.mr.df) # Visualize new features ggplot(first.mr.df[first.mr.df$Survived != "None",], aes(x = ticket.party.size, fill = Survived)) + geom_density(alpha = 0.5) + ggtitle("Survival Rates 1st Class 'Mr.' by ticket.party.size") ggplot(first.mr.df[first.mr.df$Survived != "None",], aes(x = avg.fare, fill = Survived)) + geom_density(alpha = 0.5) + ggtitle("Survival Rates 1st Class 'Mr.' by avg.fare") # Hypothesis - ticket.party.size is highly correlated with avg.fare summary(data.combined$avg.fare) # One missing value, take a look data.combined[is.na(data.combined$avg.fare), ] # Get records for similar passengers and summarize avg.fares indexes <- with(data.combined, which(Pclass == "3" & title == "Mr." & family == 1 & Ticket != "3701")) similar.na.passengers <- data.combined[indexes,] summary(similar.na.passengers$avg.fare) # Use median since close to mean and a little higher than mean data.combined[is.na(avg.fare), "avg.fare"] <- 7.840 #summary(similar.na.passengers$Age) will give you NA in age. and its a lot. #it requires a lot of imputation. so we ignore it now # normalizing data is very important to esp for models like support vector machine and others # Leverage caret's preProcess function to normalize data using z-score preproc.data.combined <- data.combined[, c("ticket.party.size", "avg.fare")] preProc <- preProcess(preproc.data.combined, method = c("center", "scale")) postproc.data.combined <- predict(preProc, preproc.data.combined) # Hypothesis refuted for all data; seesm like uncorrelated so we can use these as features cor(postproc.data.combined$ticket.party.size, postproc.data.combined$avg.fare) # How about for just 1st class all-up? indexes <- which(data.combined$Pclass == "1") cor(postproc.data.combined$ticket.party.size[indexes], postproc.data.combined$avg.fare[indexes]) # Hypothesis refuted again # OK, let's see if our feature engineering has made any difference #including previous plus the new and checking the importance features <- c("Pclass", "New.title","family","Ticket.first.char","Cabin.first.char", "ticket.party.size", "avg.fare") rf.train.3 <- data.combined[1:891, features] rf.label <- as.factor(train$Survived) set.seed(40) #seting seed to verify a random run rf.3 <- randomForest(x=rf.train.3, y=rf.label, importance = TRUE, ntree = 1000) rf.3 #just this output gives some info esp the confusion matrix and oob (out of the bag) importance(rf.3) #getting importance values varImpPlot(rf.3) test.submit.df <- data.combined[892:1309, features] rf.3.pred <- predict(rf.3, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.3.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190207_03.csv", row.names = FALSE) #lets reduce the features and check features <- c("Pclass", "New.title","family","ticket.party.size", "avg.fare") rf.train.4 <- data.combined[1:891, features] rf.label <- as.factor(train$Survived) set.seed(45) #seting seed to verify a random run rf.4 <- randomForest(x=rf.train.4, y=rf.label, importance = TRUE, ntree = 1000) rf.4 #just this output gives some info esp the confusion matrix and oob (out of the bag) importance(rf.4) #getting importance values varImpPlot(rf.4) test.submit.df <- data.combined[892:1309, features] rf.4.pred <- predict(rf.4, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.4.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190207_04.csv", row.names = FALSE) #seems like the less features inceased the test scores #Lets try crossvalidation 3 fold and try set.seed(50) cv.3.folds <- createMultiFolds(rf.label, k = 3, times = 10) #creates bunch of indexes cntrl.3 <- trainControl(method = "repeatedcv", number = 10, repeats = 10, index = cv.3.folds) # setting up doSNOW package for multi-core training; doMC only works on Linux cl <- makeCluster(4, type = "SOCK") registerDoSNOW(cl) set.seed(55) rf.5.cv.3 <- train(x = rf.train.4, y = rf.label, method = "rf", tuneLength = 3, ntree = 64, trControl = cntrl.3) #also reducing the trees #Shut down cluster stopCluster(cl) #checkout results rf.5.cv.3 #so this 3-fold maybe more generalized and better. test.submit.df <- data.combined[892:1309, features] rf.5.cv.3.pred <- predict(rf.5.cv.3, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.5.cv.3.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190207_05.csv", row.names = FALSE) #some how CV 3 fold doesnt work well. rather just RF is working well #lets see by CV 10 set.seed(60) cv.10.folds <- createMultiFolds(rf.label, k = 10, times = 10) #creates bunch of indexes #check stratification , caret can do it for you. #its usefull for small amount of imbalancing cntrl.10 <- trainControl(method = "repeatedcv", number = 10, repeats = 10, index = cv.10.folds) # setting up doSNOW package for multi-core training; doMC only works on Linux cl <- makeCluster(4, type = "SOCK") registerDoSNOW(cl) set.seed(65) rf.5.cv.10 <- train(x = rf.train.4, y = rf.label, method = "rf", tuneLength = 3, ntree = 64, trControl = cntrl.10) #also reducing the trees #Shut down cluster stopCluster(cl) #checkout results rf.5.cv.10 test.submit.df <- data.combined[892:1309, features] rf.5.cv.10.pred <- predict(rf.5.cv.10, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.5.cv.10.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190207_06.csv", row.names = FALSE) #using random forest package instead of package features <- c("Pclass", "New.title", "ticket.party.size", "avg.fare") rf.train.temp <- data.combined[1:891, features] set.seed(1234) rf.temp <- randomForest(x = rf.train.temp, y = rf.label, ntree = 1000) rf.temp test.submit.df <- data.combined[892:1309, features] # Make predictions rf.preds <- predict(rf.temp, test.submit.df) table(rf.preds) # Write out a CSV file for submission to Kaggle submit.df <- data.frame(PassengerId = rep(892:1309), Survived = rf.preds) write.csv(submit.df, file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190207_07.csv", row.names = FALSE) # feature analysis very important # First, let's explore our collection of features using mutual information to # gain some additional insight. Our intuition is that the plot of our tree # should align well to the definition of mutual information. #install.packages("infotheo") #using mutual information / entropy for feature selection : use stanford link library(infotheo) mutinformation(rf.label, data.combined$Pclass[1:891]) mutinformation(rf.label, data.combined$Sex[1:891]) mutinformation(rf.label, data.combined$SibSp[1:891]) mutinformation(rf.label, data.combined$Parch[1:891]) mutinformation(rf.label, discretize(data.combined$Fare[1:891])) mutinformation(rf.label, data.combined$Embarked[1:891]) mutinformation(rf.label, data.combined$title[1:891]) mutinformation(rf.label, data.combined$family[1:891]) mutinformation(rf.label, data.combined$Ticket.first.char[1:891]) #mutinformation(rf.label, data.combined$Age[1:891]) mutinformation(rf.label, data.combined$New.title[1:891]) mutinformation(rf.label, data.combined$ticket.party.size[1:891]) mutinformation(rf.label, discretize(data.combined$avg.fare[1:891])) # OK, now let's leverage the tsne algorithm to create a 2-D representation of our data # suitable for visualization starting with folks our model gets right very often - folks # with titles other than 'Mr." #install.packages("Rtsne") # Also keep dimension reduction in mind. not really needed in trees, but other algorithms might need it. # PCA, ICA can generate the correspoonding reduced important features. library #dimensionality reduction library most.correct <- data.combined[data.combined$New.title != "Mr.",] indexes <- which(most.correct$Survived != "None") # NOTE - Bug fix for original version. Rtsne needs a seed to ensure consistent # output between runs. set.seed(984357) tsne.1 <- Rtsne(most.correct[, features], check_duplicates = FALSE) ggplot(NULL, aes(x = tsne.1$Y[indexes, 1], y = tsne.1$Y[indexes, 2], color = most.correct$Survived[indexes])) + geom_point() + labs(color = "Survived") + ggtitle("tsne 2D Visualization of Features for new.title Other than 'Mr.'") # To get a baseline, let's use conditional mutual information on the tsne X and # Y features for females and boys in 1st and 2nd class. The intuition here is that # the combination of these features should be higher than any individual feature # we looked at above. condinformation(most.correct$Survived[indexes], discretize(tsne.1$Y[indexes,])) # As one more comparison, we can leverage conditional mutual information using # the top two features used in our tree plot - new.title and pclass condinformation(rf.label, data.combined[1:891, c("New.title", "Pclass")]) # OK, now let's take a look at adult males since our model has the biggest # potential upside for improving (i.e., the tree predicts incorrectly for 86 # adult males). Let's visualize with tsne. misters <- data.combined[data.combined$New.title == "Mr.",] indexes <- which(misters$Survived != "None") set.seed(98437) tsne.2 <- Rtsne(misters[, features], check_duplicates = FALSE) ggplot(NULL, aes(x = tsne.2$Y[indexes, 1], y = tsne.2$Y[indexes, 2], color = misters$Survived[indexes])) + geom_point() + labs(color = "Survived") + ggtitle("tsne 2D Visualization of Features for new.title of 'Mr.'") # very poor for males misters # Now conditional mutual information for tsne features for adult males condinformation(misters$Survived[indexes], discretize(tsne.2$Y[indexes,])) # # Idea - How about creating tsne featues for all of the training data and # using them in our model? set.seed(987) tsne.3 <- Rtsne(data.combined[, features], check_duplicates = FALSE) ggplot(NULL, aes(x = tsne.3$Y[1:891, 1], y = tsne.3$Y[1:891, 2], color = data.combined$Survived[1:891])) + geom_point() + labs(color = "Survived") + ggtitle("tsne 2D Visualization of Features for all Training Data") # Now conditional mutual information for tsne features for all training condinformation(data.combined$Survived[1:891], discretize(tsne.3$Y[1:891,])) # Add the tsne features to our data frame for use in model building data.combined$tsne.x <- tsne.3$Y[,1] data.combined$tsne.y <- tsne.3$Y[,2] # ----------------------------- # # we did visualization in training only but we use tsne for both train and test features <- c("Pclass", "New.title","family","ticket.party.size", "avg.fare","tsne.x","tsne.y") rf.train.7 <- data.combined[1:891, features] rf.label <- as.factor(train$Survived) set.seed(450) #seting seed to verify a random run rf.7 <- randomForest(x=rf.train.7, y=rf.label, importance = TRUE, ntree = 1000) rf.7 #just this output gives some info esp the confusion matrix and oob (out of the bag) importance(rf.7) #getting importance values varImpPlot(rf.7) test.submit.df <- data.combined[892:1309, features] rf.7.pred <- predict(rf.7, test.submit.df) submit.df <- data.frame(PassengerID = rep(892:1309),Survived = rf.7.pred) write.csv(submit.df,file = "/Users/sabbirhassan/Dropbox/ML_stuff/titanic/RF_SUB_20190207_08.csv", row.names = FALSE)
af508b56e662505139cb4fb1e644d181fc2827d6
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/pvsR/examples/CandidateBio.getAddlBio.Rd.R
07197f4146c46d8fc42ce7babb9d1f7db4003692
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
569
r
CandidateBio.getAddlBio.Rd.R
library(pvsR) ### Name: CandidateBio.getAddlBio ### Title: Get a candidate's additional biographical information ### Aliases: CandidateBio.getAddlBio ### ** Examples # First, make sure your personal PVS API key is saved as character string in the pvs.key variable: ## Not run: pvs.key <- "yourkey" # get additional biographical data on Barack Obama ## Not run: obama <- CandidateBio.getAddlBio(9490) ## Not run: obama # get additional biographical data on Barack Obama and Mitt Romney ## Not run: onr <- CandidateBio.getAddlBio(list(9490,21942)) ## Not run: onr
96f35caf5fe5aef409fde95604fc8d7aa484b630
bb9140e05d2b493422d65084bc9df4fb6ae88ba9
/R/R_cookbook/data_structures/factor_example.R
d5ef13aeccd8ecbe771712427ffbb0d25e3d0e37
[]
no_license
8589/codes
080e40d6ac6e9043e53ea3ce1f6ce7dc86bb767f
fd879e36b6d10e5688cc855cd631bd82cbdf6cac
refs/heads/master
2022-01-07T02:31:11.599448
2018-11-05T23:12:41
2018-11-05T23:12:41
null
0
0
null
null
null
null
UTF-8
R
false
false
68
r
factor_example.R
f <- factor(c("Win","Win","Lose","Tie","Win","Lose")) print(f) wday
fbecfa8cdb8c24b2c4d79dd2c2439d6f93ffa635
0a906cf8b1b7da2aea87de958e3662870df49727
/distr6/inst/testfiles/C_EmpiricalMVPdf/libFuzzer_C_EmpiricalMVPdf/C_EmpiricalMVPdf_valgrind_files/1610036757-test.R
9dfed72e18972c277e4bfadc27f585d7957ce119
[]
no_license
akhikolla/updated-only-Issues
a85c887f0e1aae8a8dc358717d55b21678d04660
7d74489dfc7ddfec3955ae7891f15e920cad2e0c
refs/heads/master
2023-04-13T08:22:15.699449
2021-04-21T16:25:35
2021-04-21T16:25:35
360,232,775
0
0
null
null
null
null
UTF-8
R
false
false
330
r
1610036757-test.R
testlist <- list(data = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 1L)), x = structure(c(1.82391755146545e-183, 1.82391755146545e-183, 8.0988077346472e-179, 5.4674514851239e-304, 4.88059051526537e-312, 0, 8.48798316386109e-314), .Dim = c(7L, 1L))) result <- do.call(distr6:::C_EmpiricalMVPdf,testlist) str(result)
5b7ba371257b5b0f2a2965eb0b04362cbf50a895
32a77ca7d4f4acbc71e8d4c1cdb5fadb9e2a0eef
/zarzar_hw06.R
3add4fc355bdc8f4bfed9c4b886264d564040d89
[]
no_license
ChrisZarzar/quantitative_methods
dd2673d839b03206f2ce978f6b1d1c16a16713f0
17a4e867c38e32646adbd767b912a5a4be33f848
refs/heads/master
2020-04-05T09:35:28.117681
2018-11-08T20:36:52
2018-11-08T20:36:52
156,753,903
0
0
null
null
null
null
UTF-8
R
false
false
2,112
r
zarzar_hw06.R
#a) #I am going to plot the PDF quantiles <- seq(0,5, by =0.01) pdf.exp <- dexp(quantiles, rate=(1/2)) plot(quantiles, pdf.exp, type='l', main = "PDF: Beta = 2") #I am going to plot the CDF quantiles <- seq(0,5, by =0.01) cdf.exp <- pexp(quantiles, rate=(1/2)) plot(quantiles, cdf.exp, type ='l', main = "CDF: Beta = 2") #b) # I need to generate a random exponential dataset with 1500 values at a rate of 3.5 set.seed(35) exp.dist <- rexp(1500, rate=(1/3.5)) exp.dist hist(exp.dist) #c) #Now I need to sort the data using the sort() function. sort.exp.dist <- sort(exp.dist) #Calculate the probability between the 1st and 750th datapoints (pexp(sort.exp.dist[750],rate=(1/3.5))) - (pexp(sort.exp.dist[1],rate=(1/3.5))) #probability between the 1st to 750th column #OUTPUT: 0.4768198 #Calculate the probability 50th and 350th datapoints (pexp(sort.exp.dist[350],rate=(1/3.5))) - (pexp(sort.exp.dist[50],rate=(1/3.5))) ##probability betwee 50th and 350th. You have to subtract the probability from the 1st to the 50th to geth the probability for just tha region between #OUTPUT: 0.1828813 #Calculate the probability 1000th and 1250th datapoints (pexp(sort.exp.dist[1250],rate=(1/3.5))) - (pexp(sort.exp.dist[1000],rate=(1/3.5))) #probability betwee 1000th and 1250th. You have to subtract the probability from the 1st to the 1000th to geth the probability for just tha region between #OUTPUT: 0.183537 #Determine the probability of getting a random value greater than the maximum in the dataset 1-(pexp(sort.exp.dist[1500],rate=(1/3.5))) #OUTPUT: 0.0005217617 #d) #Determining the quantile values for the 0.025 and 0.975 probabilities. #Determine, using ifelse stamtements, what percentage of your random number data fall outside of this range #What percent should it be? low.limit <- qexp(0.025,rate=(1/3.5)) low.limit #OUTPUT: 0.08861233 upper.limit <- qexp(0.975, rate=(1/3.5)) upper.limit #OUTPUT: 12.91108 low.out.prob <- sum(ifelse(sort.exp.dist<low.limit,1,0))/1500 up.out.prob <- sum(ifelse(sort.exp.dist>upper.limit,1,0))/1500 low.out.prob #OUTPUT: 0.02533333 up.out.prob #OUTPUT:0.02933333
3cd36d7534bbe2b2de1d4e7e3c05e3c1fc0f586c
9b5483c96399f5accf4ee2f8758899f7b41cb5cf
/man/clusterability.Rd
e6c650723f4668b8ff2cfb3f78cfc070dd061c04
[]
no_license
cran/clusterability
a7f070fa7b8ddcdd0a9e67b230435c7b3a3ef7d8
57a774c8c63c7920b0af55a62db0ea5daa707c85
refs/heads/master
2020-12-21T21:46:43.838786
2020-03-04T10:40:07
2020-03-04T10:40:07
236,572,725
0
0
null
null
null
null
UTF-8
R
false
true
4,247
rd
clusterability.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/clusterability.R \docType{package} \name{clusterability} \alias{clusterability} \alias{clusterability-package} \title{clusterability: a package to perform tests of clusterability} \description{ The \code{\link{clusterabilitytest}} function can test for clusterability of a dataset, and the \code{\link[=print.clusterability]{print}} function to display output in the console. Below we include code to use with the provided example datasets. Please see the \code{clusterabilitytest} function for documentation on available parameters. } \examples{ \donttest{ # Normals1 data(normals1) normals1 <- normals1[,-3] norm1_dippca <- clusterabilitytest(normals1, "dip") norm1_dipdist <- clusterabilitytest(normals1, "dip", distance_standardize = "NONE", reduction = "distance") norm1_silvpca <- clusterabilitytest(normals1, "silverman", s_setseed = 123) norm1_silvdist <- clusterabilitytest(normals1, "silverman", distance_standardize = "NONE", reduction = "distance", s_setseed = 123) print(norm1_dippca) print(norm1_dipdist) print(norm1_silvpca) print(norm1_silvdist) # Normals2 data(normals2) normals2 <- normals2[,-3] norm2_dippca <- clusterabilitytest(normals2, "dip") norm2_dipdist <- clusterabilitytest(normals2, "dip", reduction = "distance", distance_standardize = "NONE") norm2_silvpca <- clusterabilitytest(normals2, "silverman", s_setseed = 123) norm2_silvdist <- clusterabilitytest(normals2, "silverman", reduction = "distance", distance_standardize = "NONE", s_setseed = 123) print(norm2_dippca) print(norm2_dipdist) print(norm2_silvpca) print(norm2_silvdist) # Normals3 data(normals3) normals3 <- normals3[,-3] norm3_dippca <- clusterabilitytest(normals3, "dip") norm3_dipdist <- clusterabilitytest(normals3, "dip", reduction = "distance", distance_standardize = "NONE") norm3_silvpca <- clusterabilitytest(normals3, "silverman", s_setseed = 123) norm3_silvdist <- clusterabilitytest(normals3, "silverman", reduction = "distance", distance_standardize = "NONE", s_setseed = 123) print(norm3_dippca) print(norm3_dipdist) print(norm3_silvpca) print(norm3_silvdist) # Normals4 data(normals4) normals4 <- normals4[,-4] norm4_dippca <- clusterabilitytest(normals4, "dip") norm4_dipdist <- clusterabilitytest(normals4, "dip", reduction = "distance", distance_standardize = "NONE") norm4_silvpca <- clusterabilitytest(normals4, "silverman", s_setseed = 123) norm4_silvdist <- clusterabilitytest(normals4, "silverman", reduction = "distance", distance_standardize = "NONE", s_setseed = 123) print(norm4_dippca) print(norm4_dipdist) print(norm4_silvpca) print(norm4_silvdist) # Normals5 data(normals5) normals5 <- normals5[,-4] norm5_dippca <- clusterabilitytest(normals5, "dip") norm5_dipdist <- clusterabilitytest(normals5, "dip", reduction = "distance", distance_standardize = "NONE") norm5_silvpca <- clusterabilitytest(normals5, "silverman", s_setseed = 123) norm5_silvdist <- clusterabilitytest(normals5, "silverman", reduction = "distance", distance_standardize = "NONE", s_setseed = 123) print(norm5_dippca) print(norm5_dipdist) print(norm5_silvpca) print(norm5_silvdist) # iris data(iris) newiris <- iris[,c(1:4)] iris_dippca <- clusterabilitytest(newiris, "dip") iris_dipdist <- clusterabilitytest(newiris, "dip", reduction = "distance", distance_standardize = "NONE") iris_silvpca <- clusterabilitytest(newiris, "silverman", s_setseed = 123) iris_silvdist <- clusterabilitytest(newiris, "silverman", reduction = "distance", distance_standardize = "NONE", s_setseed = 123) print(iris_dippca) print(iris_dipdist) print(iris_silvpca) print(iris_silvdist)} # cars data(cars) cars_dippca <- clusterabilitytest(cars, "dip") cars_dipdist <- clusterabilitytest(cars, "dip", reduction = "distance", distance_standardize = "NONE") cars_silvpca <- clusterabilitytest(cars, "silverman", s_setseed = 123) cars_silvdist <- clusterabilitytest(cars, "silverman", reduction = "distance", distance_standardize = "NONE", s_setseed = 123) print(cars_dippca) print(cars_dipdist) print(cars_silvpca) print(cars_silvdist) }
aad51b1e6f1515aa0c3af3013e39afaa3acd0035
8e8fe47449384105bd58ef569aa509a834494501
/Goodies/man/PHS.bxp.Rd
4dbb5628637719c0d7892326dc0661fcaffc85f7
[]
no_license
Kuvelkar/TEST
761d20692383052559081f67abd50293512e875c
d06f8c49dfcff128f98ca79f6477c1b1c15a6b11
refs/heads/master
2021-01-10T16:48:09.896028
2016-02-03T08:53:29
2016-02-03T08:53:29
50,986,445
0
0
null
null
null
null
UTF-8
R
false
false
3,564
rd
PHS.bxp.Rd
\name{PHS.bxp} \alias{PHS.bxp} \title{Draw Box Plots from Summaries} \description{Draw box plots based on the given summaries in z. It is usually called from within bowplot.} \usage{PHS.bxp(z, notch = FALSE, width = NULL, varwidth = FALSE, outline = TRUE, notch.frac = 0.5, log = "", border = par("fg"), pars = NULL, frame.plot = axes, horizontal = FALSE, add = FALSE, at = NULL, show.names = NULL, medlwd = 5, confint = FALSE, confcol = 2, boxwex = 0.5, staplewex = 1, ...)} \arguments{ \item{z}{a list containing data summaries to be used in constructing the plots. These are usually the result of a call to boxplot, but can be generated in any fashion.} \item{notch}{logical if notch is TRUE, a notch is drawn in each side of the boxes. If the notches of two plots do not overlap then the medians are significantly different at the 5 percent level.} \item{width}{a vector giving the relative widths of the boxes making up the plot.} \item{varwidth}{logical if varwidth is TRUE, the boxes are drawn with widths proportional to the square-roots of the number of observations in the groups.} \item{outline}{logical if outline is not true, the outliers are not drawn.} \item{notch.frac}{numeric in (0,1). When notch = TRUE, the fraction of the box width that the notches should use.} \item{log}{character, indicating if any axis should be drawn in logarithmic scale.} \item{border}{character or numeric (vector), the color of the box borders. Is recycled for multiple boxes. Is used as default for the boxcol, medcol, whiskcol, staplecol, and outcol options (see below).} \item{pars}{graphical parameters.} \item{frame.plot}{logical, indicating if a ?frame? (box) should be drawn; defaults to TRUE, unless axes = FALSE is specified.} \item{horizontal}{logical indicating if the boxplots should be horizontal; default FALSE means vertical boxes.} \item{add}{logical, if true add boxplot to current plot.} \item{at}{numeric vector giving the locations where the boxplots should be drawn, particularly when add = TRUE; defaults to 1:n where n is the number of boxes.} \item{show.names}{set to TRUE or FALSE to override the defaults on whether an x-axis label is printed for each group.} \item{medlwd}{median line width. Setting this parameter implicitly sets the medline parameter to TRUE. The special value, NA, is used to indicate the current line width ( par("lwd")). The default is 5, but the "old" and "att" styles set the it to 5. } \item{confint}{confidence interval logical flag. If TRUE, use z$conf to display confidence intervals. How the confidence intervals are shown is determined by the confnotch, confcol, confangle and confdensity parameters.} \item{confcol}{confidence interval color. If supplied, confidence intervals will be filled with the indicated color. The default is 2, but the "old" and "att" styles set it to -1 (no filling). } \item{boxwex}{box width expansion. The width of the boxes, along with the width of the staples (whisker end caps) and outliers (if drawn as lines), are proportional to this parameter. The default is 0.5, but the "att" and "old" styles set this to 1.} \item{staplewex}{staple width expansion. Proportional to the box width. The default is 1, but the "old" style sets the default to 0.125.} \item{\dots}{other arguments.} } \details{} \value{An invisible vector, actually identical to the at argument, with the coordinates ("x" if horizontal is false, "y" otherwise) of box centers, useful for adding to the plot.} \author{IAZI} \examples{}
365192ce355be889b2dcd0dfada7c68ea3c785fb
187337b1f53c771c1537f2dc3b5c6dde99519b02
/man/eclat.Rd
a58da3317845800ae850374aacfd3619b497725f
[]
no_license
lgallindo/arules
8da9dabe54a7351afa3e7bec12c0c11bbc9de741
887184cd80068e04531b0c13bc231ecbd1afddfb
refs/heads/master
2023-07-24T02:56:14.691724
2018-01-10T19:08:50
2018-01-10T19:08:50
117,311,210
0
0
null
2018-02-17T08:13:46
2018-01-13T03:38:40
C
UTF-8
R
false
false
2,612
rd
eclat.Rd
\name{eclat} \alias{eclat} \title{Mining Associations with Eclat} \description{ Mine frequent itemsets with the Eclat algorithm. This algorithm uses simple intersection operations for equivalence class clustering along with bottom-up lattice traversal. } \usage{ eclat(data, parameter = NULL, control = NULL) } \arguments{ \item{data}{object of class \code{\linkS4class{transactions}} or any data structure which can be coerced into \code{\linkS4class{transactions}} (e.g., binary \code{matrix}, \code{data.frame}).} \item{parameter}{object of class \code{\linkS4class{ECparameter}} or named list (default values are: support 0.1 and maxlen 5)} \item{control}{object of class \code{\linkS4class{ECcontrol}} or named list for algorithmic controls.} } \details{ Calls the C implementation of the Eclat algorithm by Christian Borgelt for mining frequent itemsets. Note for control parameter \code{tidLists=TRUE}: Since storing transaction ID lists is very memory intensive, creating transaction ID lists only works for minimum support values which create a relatively small number of itemsets. See also \code{\link{supportingTransactions}}. \code{\link{ruleInduction}} can be used to generate rules from the found itemsets. A weighted version of ECLAT is available as function \code{\link{weclat}}. This version can be used to perform weighted association rule mining (WARM). } \value{ Returns an object of class \code{\linkS4class{itemsets}}. } \references{ Mohammed J. Zaki, Srinivasan Parthasarathy, Mitsunori Ogihara, and Wei Li. (1997) \emph{New algorithms for fast discovery of association rules}. Technical Report 651, Computer Science Department, University of Rochester, Rochester, NY 14627. Christian Borgelt (2003) Efficient Implementations of Apriori and Eclat. \emph{Workshop of Frequent Item Set Mining Implementations} (FIMI 2003, Melbourne, FL, USA). ECLAT Implementation: \url{http://www.borgelt.net/eclat.html} } \seealso{ \code{\link{ECparameter-class}}, \code{\link{ECcontrol-class}}, \code{\link{transactions-class}}, \code{\link{itemsets-class}}, \code{\link{weclat}}, \code{\link{apriori}}, \code{\link{ruleInduction}}, \code{\link{supportingTransactions}} } \author{Michael Hahsler and Bettina Gruen} \examples{ data("Adult") ## Mine itemsets with minimum support of 0.1 and 5 or less items itemsets <- eclat(Adult, parameter = list(supp = 0.1, maxlen = 5)) itemsets ## Create rules from the itemsets rules <- ruleInduction(itemsets, Adult, confidence = .9) rules } \keyword{models}
f7d4c936c395e5cc69130c02bde5f88053d3cb9c
570f57c6d5355d2064d123e4452094090f16d5b9
/Assignment 2 code.R
08b00730becf8df9ff892a2e766ec5dda8cf5a4a
[]
no_license
R-pidit/R-projects
7227aa6d5f45d841e53289f7a41eb9daed1491d2
6ac3f271fed69ce54b135b4b554a37085099ffee
refs/heads/master
2021-01-22T14:55:51.562359
2017-09-07T11:09:20
2017-09-07T11:09:20
102,372,084
5
0
null
null
null
null
UTF-8
R
false
false
4,475
r
Assignment 2 code.R
install.packages("titanic") install.packages("rpart.plot") install.packages("randomForest") install.packages("DAAG") library(titanic) library(rpart.plot) library(gmodels) library(Hmisc) library(pROC) library(ResourceSelection) library(car) library(caret) library(dplyr) library(InformationValue) library(rpart) library(randomForest) library("DAAG") cat("\014") # Clearing the screen getwd() setwd("C:\\Users\\Subha\\Documents\\R_Data") #This working directory is the folder where all the bank data is stored rm(list = ls()) titanic_data<-read.csv('train.csv') titanic_train= titanic_data[c("Pclass" ,"Sex" ,"Age" ,"SibSp", "Parch","Survived")] #titanic test titanic_test <-read.csv('test-3.csv') # number of survived vs number of dead CrossTable(titanic_train$Survived) View(titanic_train) # replacing NA in age column by it's mean titanic_train$Age[is.na(titanic_train$Age)]= mean(titanic_train$Age[!is.na(titanic_train$Age)]) summary(titanic_train) #splitting titanic train into 70,30 set.seed(1234) # for reproducibility titanic_train$rand <- runif(nrow(titanic_train)) titanic_train_start <- titanic_train[titanic_train$rand <= 0.7,] titanic_test_start <- titanic_train[titanic_train$rand > 0.7,] View(titanic_train_start) ########## Model building ########## full.model.titanic.mean <- glm(formula = Survived ~ Pclass+Sex+Age+SibSp+Parch,data = titanic_train_start,family = binomial) #family = binomial implies that it is logistic regression summary(full.model.titanic.mean) #removing insignificant variables titanic_train_start$Parch<-NULL full.model.titanic.mean <- glm(formula = Survived ~ Pclass+Sex+Age+SibSp, data=titanic_train_start, family = binomial) #family = binomial implies that the type of regression is logistic summary(full.model.titanic.mean) #All variables significant #Testing performance on Train set titanic_train_start$prob = predict(full.model.titanic.mean, type=c("response")) titanic_train_start$Survived.pred = ifelse(titanic_train_start$prob>=.5,'pred_yes','pred_no') table(titanic_train_start$Survived.pred,titanic_train_start$Survived) #Testing performance on test set nrow(titanic_test) titanic_test_start$prob = predict(full.model.titanic.mean, newdata=titanic_test_start, type=c("response")) titanic_test_start$Survived.pred = ifelse(titanic_test_start$prob>=.5,'pred_yes','pred_no') table(titanic_test_start$Survived.pred,titanic_test_start$Survived) ########## END - Model with mean included instead of NA ######### ### Testing for Jack n Rose's survival ### df.jackrose <- read.csv('Book1.csv') df.jackrose$prob = predict(full.model.titanic.mean, newdata=df.jackrose, type=c("response")) df.jackrose$Survived.pred = ifelse(df.jackrose$prob>=.5,'pred_yes','pred_no') head(df.jackrose) # Jack dies, Rose survives ### END - Testing on Jack n Rose ### ## START K-fold cross validation ## # Defining the K Fold CV function here Kfold_func <- function(dataset,formula,family,k) { object <- glm(formula=formula, data=dataset, family = family) CVbinary(object, nfolds= k, print.details=TRUE) } #Defining the function to calculate Mean Squared Error here MeanSquareError_func <- function(dataset,formula) { LM_Object <- lm(formula=formula, data=dataset) LM_Object_sum <-summary(LM_Object) MSE <- mean(LM_Object_sum$residuals^2) print("Mean squared error") print(MSE) } #Performing KFold CV on Training set by calling the KFOLD CV function here Kfoldobj <- Kfold_func(titanic_train_start,Survived ~ Pclass + Sex + SibSp + Age,binomial,10) #Calling the Mean Squared Error function on the training set here MSE_Train <-MeanSquareError_func(titanic_train_start,Survived ~ Pclass + Sex + SibSp + Age) #confusion matrix on training set table(titanic_train_start$Survived,round(Kfoldobj$cvhat)) print("Estimate of Accuracy") print(Kfoldobj$acc.cv) #Performing KFold CV on test set by calling the KFOLD CV function here Kfoldobj.test <- Kfold_func(titanic_test_start,Survived ~ Pclass + Sex + SibSp + Age,binomial,10) #Calling the Mean Squared Error function on the test set here MSE_Test <-MeanSquareError_func(titanic_test_start,Survived ~ Pclass + Sex + SibSp + Age) #Confusion matrix on test set table(titanic_test_start$Survived,round(Kfoldobj.test$cvhat)) print("Estimate of Accuracy") print(Kfoldobj.test$acc.cv) ## END K-FOLD CROSS VALIDATION ##
ece440a44978c2ff0932d186df772f1bd402e513
8bde36c00a458f1d3b3c81eea824c56bc72b26e2
/approximate_UMVUE.R
cf57a4d4fd65278e0e72e433d3927c47406a6cea
[]
no_license
snigdhagit/Bayesian-selective-inference
ea186c866700510cf5206977e936e6224dbc5dd2
a4e436aef0636c6acc6385e75f40109ead722d21
refs/heads/master
2021-07-08T07:45:00.242158
2017-10-02T08:47:00
2017-10-02T08:47:00
105,512,054
1
2
null
null
null
null
UTF-8
R
false
false
544
r
approximate_UMVUE.R
#computes approximate UMVUE under additive Gaussian randomization with variance tau^2 (in the univariate case) UMVUE.compute<-function(y, sigma, tau) { objective<-function(z,alpha) { (((-alpha*z))+((z^2/2)+log(1+(1/z)))) } objective1<-function(z,alpha) { (((-alpha*z)/tau)+((z^2/2)+log(1+(1/z)))) } approx1<-function(alpha1) { opt<-nlm(objective1,p=1,alpha=alpha1,hessian=TRUE) return(opt$estimate) } UMVUE.approx<-(y*(1+((sigma^2)/(tau^2))))-(((sigma^2)/(tau))*approx1(y)) return(UMVUE.approx) }
f3a5851977bbf960cc10042ff7fcd3375fd35624
bccaf9ca75d67fef6bec733e784c582149a32ed1
/plagiat/R/jclu2bup.f.R
89e1438d0b95b2f91986de64fd67d7cdb98df4c2
[]
no_license
brooksambrose/pack-dev
9cd89c134bcc80711d67db33c789d916ebcafac2
af1308111a36753bff9dc00aa3739ac88094f967
refs/heads/master
2023-05-10T17:22:37.820713
2023-05-01T18:42:08
2023-05-01T18:42:08
43,087,209
0
1
null
null
null
null
UTF-8
R
false
false
1,050
r
jclu2bup.f.R
#' JSTOR Clustering 2 Bimodal Unimodal Projection Illustration #' #' @param jclu #' @param s #' #' @return #' @export #' @import igraph magrittr data.table #' #' @examples jclu2bup.f<-function(jclu,s=300){ par(mar=c(0,0,1,0)) bs<-igraph::as_edgelist(jclu$b) %>% data.table %>% setnames(ec('j,l')) %>% .[sample(1:.N,s)] %>% as.matrix %>% graph_from_edgelist V(bs)$type<-grepl('^[A-Z]',V(bs)$name) bs$name<-'journal-label' args<-function(x) list(x=x,main=graph_attr(x, 'name'),label.family='serif',vertex.label=NA,vertex.size=4,edge.arrow.size=0,vertex.color=V(x)$type+1,vertex.frame.color=NA,edge.color=if(E(x)$weight %>% is.null) gray(.2) else sapply(E(x)$weight,function(y) gray(level=1-(y/max(E(x)$weight))))) ms<-bipartite_projection(bs,remove.type = F) ms$proj1$name<-'journal' ms$proj2$name<-'label' docx<-'docx'%in%knitr::opts_knit$get("rmarkdown.pandoc.to") if(docx) par(mfrow=c(1,3)) do.call(plot,args(bs)) do.call(plot,args(ms$proj1)) do.call(plot,args(ms$proj2)) if(docx) par(mfrow=c(1,1)) c(list(b=bs),ms) }
7a8a8347270b7c5bfd44f40a1de964a87bab6a5f
bb767f6a07340c0c313c79587ea6c96ce5e17f33
/R/data.r
da1aa212d98a75fe535d3ca11d467ba2b7815e10
[]
no_license
psychobas/corpustools
82694086aa0b3d861e38624a5cf17a53ce61e23e
e9c1ac2011234a62b2fc2c7b46ab01dd9159e4ac
refs/heads/master
2023-05-04T01:35:30.735603
2021-05-25T10:41:30
2021-05-25T10:41:30
null
0
0
null
null
null
null
UTF-8
R
false
false
808
r
data.r
#' State of the Union addresses #' #' @docType data #' @usage data(sotu_texts) #' @format data.frame 'sotu_texts' ##save(sotu_texts, file='data/sotu_texts.rda', compression_level = 9) #' coreNLP example sentences #' #' @docType data #' @usage data(corenlp_tokens) #' @format data.frame 'corenlp_tokens' #' A tCorpus with a small sample of sotu paragraphs parsed with udpipe #' #' @docType data #' @usage data(tc_sotu_udpipe) #' @format data.frame 'tc_sotu_udpipe' ## run if tc methods have been updated ## tc_sotu_udpipe = refresh_tcorpus(tc_sotu_udpipe) ## save(tc_sotu_udpipe, file='data/tc_sotu_udpipe.rda', compression_level = 9) #' Basic stopword lists #' #' @docType data #' @usage data(stopwords_list) #' @format A named list, with names matching the languages used by SnowballC "stopwords_list"
d165b85aafed9b2a16ca2e7d132720bc7eca0e02
eff4f65785cdd0f198245b46876720ee4cf40bba
/Intro to R II.R
fb055ab99c6c1967bde355baa1e7f89b8fa3be7e
[]
no_license
PRATIKSHIRBHATE/r_training
afc84e0f5a24ded8c4cbb00c8499bd5eb1605e14
d11dbe97ac602eaca0c37c1285dcdd4cfe623f47
refs/heads/master
2020-09-25T15:53:36.079049
2019-12-05T11:13:50
2019-12-05T11:13:50
226,038,433
0
0
null
null
null
null
UTF-8
R
false
false
7,153
r
Intro to R II.R
## Introduction to R - Part II ## This file contains all of the same code that is contained in the Markdown ## version of the guide. This document serves to demonstrate how a regular R ## script looks and how to run code in this format. # Loading the packages and data as shown on the previous guide # "Introduction to R". packages.to.load <- c("plyr", "dplyr" ,"DT", "ggplot2", "plotly", "RODBC") invisible(lapply(packages.to.load, library, character.only=TRUE)) load("C:/Users/shregmi/Documents/Current Projects/R Training/Example Datasets/Auto.rda") write.csv(Auto, file="Autodata.csv") auto.data <- read.csv(file ="C:/Users/shregmi/Documents/Current Projects/R Training/Autodata.csv" , header = TRUE) #Manipulating Data # This section will cover a couple ways to shape data into something that is # easy to work with. ##Using the $ operator #For very simple filters and selection of certain columns from a data frame, you # can use the $ operator. Here, we take one column from our auto.data data frame # and assign it to a new object. You can use the class() function to see what # kind of object it is. JustMPG <- matrix(auto.data$mpg) class(JustMPG) # We can also pull multiple columns pretty easily. MPGandWeight <- data.frame(auto.data$mpg, auto.data$weight) head(MPGandWeight) ##dplyr # The package dplyr is a heavily used library for data cleaning and preparation # (one of R's main strong suits). Here is a little cheat sheet covering some # dplyr and tidyr features: # https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf # The official dplyr documentation can also be found here: # https://cran.r-project.org/web/packages/dplyr/dplyr.pdf #There are 5 main functions or "verbs" used in dplyr: Select, Filter, Mutate, # Arrange, and Summarize. Many of these align with the main SQL commands: # Select, Where, Group By, etc... ###Select # Let's take a subset of columns from the auto.data dataset. auto.subset <- select(auto.data, name, mpg, cylinders, weight) head(auto.subset) # We can also specify which columns to exclude using the "-" operator. auto.subset2 <- select(auto.data, -horsepower, -year) head(auto.subset2) ###Filter # After selecting your data of interest, you can pass filters in the same way as # you would a "where" clause in SQL. only.4cyl <- filter(auto.subset, cylinders==4) head(only.4cyl) # You can add multiple arguments to the filter function. multi.filter <- filter(auto.subset, cylinders %in% c(4,6), weight<3000) head(multi.filter) # We can filter strings as well. filter.name <- filter(auto.subset, cylinders==4, weight<2000, grepl("toyota|volkswagen", name)) head(filter.name) ###Mutate # Using mutate, we can create new columns. Additionally, we can chain the # previous "verbs" together using the "%>%" operator (called pipe operator). # Note that the dplyr package must be loaded in order to use this operator. add.col <- auto.data %>% select(name, mpg, cylinders, weight) %>% filter(weight>1800) %>% mutate(weightpercyl <- weight/cylinders) head(add.col) ###Arrange # This is equivalent to an "order by" statement in SQL. Here, we sort the # previous output by "weightpercyl" in descending order using the "-" operator. add.col.sorted <- auto.data %>% select(name, mpg, cylinders, weight) %>% filter(weight>1800) %>% mutate(weightpercyl = weight/cylinders) %>% arrange(-weightpercyl) head(add.col.sorted) ###Summarize summarized.auto <- auto.data %>% select(name, mpg, cylinders, weight) %>% filter(weight>1800) %>% mutate(weightpercyl = weight/cylinders) %>% summarise(avg_mpg = mean(mpg), min_weight = min(weight), median_weightpercyl = median(weightpercyl)) summarized.auto # We can pass a group_by() clause as well. summarized.auto2 <- auto.data %>% select(name, mpg, cylinders, weight) %>% filter(weight>1800) %>% mutate(weightpercyl = weight/cylinders) %>% group_by(cylinders) %>% summarise(avg_mpg = mean(mpg), avg_weight = mean(weight), avg_weightpercyl = mean(weightpercyl)) summarized.auto2 #Visualization # This section will cover a few useful packages and methods for visualization in # an R Markdown document. ##Displaying Tables in R Markdown # When using print() or head() functions to show the contents of a data frame, # the output looks very ugly. There are a huge number of packages that are # specifically for displaying tables in an aesthetically pleasing way. The "DT" # or Data Tables package is one of them. datatable(auto.data) # This is the default way to display a data frame with this package with no # arguments provided except for the object that is to be shown. # There are a huge number of arguments you can add to make your reports look # nicer and to add functionality. BONUS: You'll also write the smallest piece of # JavaScript code in this as well. datatable(auto.data, extensions = 'Buttons', options = list( dom = 'Bfrtip', buttons= c('copy', 'excel'), pageLength = 5, initComplete = JS(" function(settings, json) { $(this.api().table().header()).css({ 'background-color': '#232D69', 'color': '#fff' }); }") ), rownames = FALSE) ##Charts with Plotly # Cheat sheet for plotly: # https://images.plot.ly/plotly-documentation/images/r_cheat_sheet.pdf. # Another great resource: https://plot.ly/r/ plot <- plot_ly(x = auto.data$weight, type="histogram") plot # In plotly, you can add multiple sets of traces or bars to the same plot with # the use of pipe operators. You can also name each of the traces/bars so that # the result is clear. plot2 <- plot_ly(data =auto.data, alpha = 0.5) %>% #adjusting color transparency add_histogram(x = auto.data$weight[auto.data$origin == 1], name="American") %>% add_histogram(x = auto.data$weight[auto.data$origin == 2], name="European") %>% add_histogram(x = auto.data$weight[auto.data$origin == 3], name="Japanese") %>% layout(barmode = "overlay") plot2 # Here is an example of a scatterplot generated by plotly. This has many more # features and much more functionality than the plot we first generated with the # R Base plot() function. auto.data$OriginName[which(auto.data$origin == 1)] = "American" auto.data$OriginName[which(auto.data$origin == 2)] = "European" auto.data$OriginName[which(auto.data$origin == 3)] = "Japanese" plot3 <- plot_ly(data = auto.data ,x = ~weight ,y = ~mpg ,color = ~OriginName ,type ="scatter" ,mode="markers" ,text= ~paste("Car name: ", name ,"</br> Year: ", year ,"</br> Cylinders: ", cylinders)) plot3 ##Charts with ggplot2 #Cheat sheet for ggplot2: https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf
38ac95555fe279ef8ae6c775d78ed81c1f14e47d
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/HelpersMG/examples/modeled.hist.Rd.R
271dde27ceb26963b9b570054bf6ba2ea8b265bf
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
615
r
modeled.hist.Rd.R
library(HelpersMG) ### Name: modeled.hist ### Title: Return the theoretical value for the histogram bar ### Aliases: modeled.hist ### ** Examples ## Not run: ##D n <- rnorm(100, mean=10, sd=2) ##D breaks <- 0:20 ##D hist(n, breaks=breaks) ##D ##D s <- modeled.hist(breaks=breaks, FUN=pnorm, mean=10, sd=2, sum=100) ##D ##D points(s$x, s$y, pch=19) ##D lines(s$x, s$y) ##D ##D n <- rlnorm(100, meanlog=2, sdlog=0.4) ##D b <- hist(n, ylim=c(0, 70)) ##D ##D s <- modeled.hist(breaks=b$breaks, FUN=plnorm, meanlog=2, sdlog=0.4, sum=100) ##D ##D points(s$x, s$y, pch=19) ##D lines(s$x, s$y) ## End(Not run)
dcc6d38fe84ec6562e1230189687a50a97624fa0
ef424746a3ea4ed6e167f03d359b39da48a0fc21
/man/colLuminosity_utility.Rd
a6badc261d6881eba0e7c11abd380faa9f24fb26
[]
no_license
smitdave/MASH
397a1f501c664089ea297b8841f2cea1611797e4
b5787a1fe963b7c2005de23a3e52ef981485f84c
refs/heads/master
2021-01-18T18:08:25.424086
2017-08-17T00:18:52
2017-08-17T00:18:52
86,845,212
0
3
null
2017-08-17T00:18:52
2017-03-31T17:42:46
R
UTF-8
R
false
true
671
rd
colLuminosity_utility.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/MICRO-Landscape-Utilities.R \name{colLuminosity_utility} \alias{colLuminosity_utility} \title{Brighten or Darken Colors} \usage{ colLuminosity_utility(color, factor, bright, alpha = NULL) } \arguments{ \item{color}{vector of hcl colors} \item{factor}{factor to brighten or darken colors} \item{bright}{logical variable to brighten or darken} \item{alpha}{opacity} } \value{ a vector of colors in hex format } \description{ With input of hcl colors (hex code), brighten or darken by a factor } \examples{ colLuminosity_utility(color=MASH::ggCol_utility(n=5), factor = 1.15, bright = TRUE) }