content
large_stringlengths
0
6.46M
path
large_stringlengths
3
331
license_type
large_stringclasses
2 values
repo_name
large_stringlengths
5
125
language
large_stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.46M
extension
large_stringclasses
75 values
text
stringlengths
0
6.46M
# library(yaml) l <- yaml.load_file("tree1.yaml") library(data.tree) jl <- as.Node(l) #Plotting library(igraph) library(ape) jl$Revert() jlp <- as.phylo(jl) library(igraph) G <- graph.tree(n=13,children=2) # let's print it using a tree-specific layout # (N.B. you must specify the root node) co <- layout.reingold.tilford(G, params=list(root=1)) plot(G, layout=co) acme <- Node$new("Acme Inc.") accounting <- acme$AddChild("Accounting") software <- accounting$AddChild("New Software") standards <- accounting$AddChild("New Accounting Standards") research <- acme$AddChild("Research") newProductLine <- research$AddChild("New Product Line") newLabs <- research$AddChild("New Labs") it <- acme$AddChild("IT") outsource <- it$AddChild("Outsource") agile <- it$AddChild("Go agile") goToR <- it$AddChild("Switch to R") print(acme) ti <- Node$new("Topic indicators") do <- ti$AddChild("dobj") va <- do$AddChild("Verb=hankkia/etsiä/etc") fp <- va$AddChild("First person") fp$AddChild("Asumisen järjestin itselleni jo Suomesta käsin. ") fp$AddChild("Asunnon hankin yksityiseltä vuokranantajalta, ja se oli valmiina saapuessani. ") va$AddChild("third person / passive") do$AddChild("other") do <- ti$AddChild("nmod") fp <- do$AddChild("First person") fp$AddChild("Kuljin rautatieasemalta metrolla yliopiston asuntolalle, missä... ") ot <- do$AddChild("Other") lc <- ot$AddChild("Locative cases") ela <- lc$AddChild("Elative") ela$AddChild("Asunnosta muodostui kriittisin osa koko vaihtoa. ") ila <- lc$AddChild("Illative") ila$AddChild("Suurin osa Pietarin vaihtareista majoittuu samaan asuntolaan, ") ine <- lc$AddChild("Inessive") ine$AddChild("Meidän lisäksi samassa asunnossa asui italialainen tyttö, jonka kanssa jaoimme vessan, suihkun ja jääkaapin. ") ot <- do$AddChild("Asunnon suhteen / kanssa") ot$AddChild("Minulla kävi tuuri asunnon kanssa, sillä eräs tuttuni omistaa asunnon Berliinissä. ") do <- ti$AddChild("") print(ti) collapsibleTree(ti, fontSize=20, height=900, width=1200, linkLength=200) collapsibleTreeNetwork(ti, fontSize=20, height=900, width=1200, linkLength=200) simpleNetwork(tiNetwork[-3], fontSize = 15) tiNetwork <- ToDataFrameNetwork(ti, "name") acmeNetwork <- ToDataFrameNetwork(acme, "name") other: Rekistöröityminen paikalliseksi asukkaaksi sujui helposti, accounting <- acme$AddChild("Accounting") software <- accounting$AddChild("New Software") standards <- accounting$AddChild("New Accounting Standards") research <- acme$AddChild("Research") newProductLine <- research$AddChild("New Product Line") newLabs <- research$AddChild("New Labs") it <- acme$AddChild("IT") outsource <- it$AddChild("Outsource") agile <- it$AddChild("Go agile") goToR <- it$AddChild("Switch to R")
/teksti/shiny_tree.R
no_license
hrmJ/matkakertomukset
R
false
false
3,051
r
# library(yaml) l <- yaml.load_file("tree1.yaml") library(data.tree) jl <- as.Node(l) #Plotting library(igraph) library(ape) jl$Revert() jlp <- as.phylo(jl) library(igraph) G <- graph.tree(n=13,children=2) # let's print it using a tree-specific layout # (N.B. you must specify the root node) co <- layout.reingold.tilford(G, params=list(root=1)) plot(G, layout=co) acme <- Node$new("Acme Inc.") accounting <- acme$AddChild("Accounting") software <- accounting$AddChild("New Software") standards <- accounting$AddChild("New Accounting Standards") research <- acme$AddChild("Research") newProductLine <- research$AddChild("New Product Line") newLabs <- research$AddChild("New Labs") it <- acme$AddChild("IT") outsource <- it$AddChild("Outsource") agile <- it$AddChild("Go agile") goToR <- it$AddChild("Switch to R") print(acme) ti <- Node$new("Topic indicators") do <- ti$AddChild("dobj") va <- do$AddChild("Verb=hankkia/etsiä/etc") fp <- va$AddChild("First person") fp$AddChild("Asumisen järjestin itselleni jo Suomesta käsin. ") fp$AddChild("Asunnon hankin yksityiseltä vuokranantajalta, ja se oli valmiina saapuessani. ") va$AddChild("third person / passive") do$AddChild("other") do <- ti$AddChild("nmod") fp <- do$AddChild("First person") fp$AddChild("Kuljin rautatieasemalta metrolla yliopiston asuntolalle, missä... ") ot <- do$AddChild("Other") lc <- ot$AddChild("Locative cases") ela <- lc$AddChild("Elative") ela$AddChild("Asunnosta muodostui kriittisin osa koko vaihtoa. ") ila <- lc$AddChild("Illative") ila$AddChild("Suurin osa Pietarin vaihtareista majoittuu samaan asuntolaan, ") ine <- lc$AddChild("Inessive") ine$AddChild("Meidän lisäksi samassa asunnossa asui italialainen tyttö, jonka kanssa jaoimme vessan, suihkun ja jääkaapin. ") ot <- do$AddChild("Asunnon suhteen / kanssa") ot$AddChild("Minulla kävi tuuri asunnon kanssa, sillä eräs tuttuni omistaa asunnon Berliinissä. ") do <- ti$AddChild("") print(ti) collapsibleTree(ti, fontSize=20, height=900, width=1200, linkLength=200) collapsibleTreeNetwork(ti, fontSize=20, height=900, width=1200, linkLength=200) simpleNetwork(tiNetwork[-3], fontSize = 15) tiNetwork <- ToDataFrameNetwork(ti, "name") acmeNetwork <- ToDataFrameNetwork(acme, "name") other: Rekistöröityminen paikalliseksi asukkaaksi sujui helposti, accounting <- acme$AddChild("Accounting") software <- accounting$AddChild("New Software") standards <- accounting$AddChild("New Accounting Standards") research <- acme$AddChild("Research") newProductLine <- research$AddChild("New Product Line") newLabs <- research$AddChild("New Labs") it <- acme$AddChild("IT") outsource <- it$AddChild("Outsource") agile <- it$AddChild("Go agile") goToR <- it$AddChild("Switch to R")
#' Retrieval functions for USGS data #' #' \tabular{ll}{ #' Package: \tab USGSwsDataRetrieval\cr #' Type: \tab Package\cr #' Version: \tab 0.0.0\cr #' Date: \tab 2014-07-03\cr #' License: \tab Unlimited for this package, dependencies have more restrictive licensing.\cr #' Copyright: \tab This software is in the public domain because it contains materials #' that originally came from the United States Geological Survey, an agency of #' the United States Department of Interior. For more information, see the #' official USGS copyright policy at #' http://www.usgs.gov/visual-id/credit_usgs.html#copyright\cr #' LazyLoad: \tab yes\cr #' } #' #' Collection of functions to help retrieve USGS data from either web services or user provided data files. #' #' @name USGSwsDataRetrieval-package #' @import RCurl XML reshape2 #' @docType package #' @author David Lorenz \email{lorenz@@usgs.gov}, Laura De Cicco \email{ldecicco@@usgs.gov} #' @keywords data, retrieval NULL #' List of USGS parameter codes #' #' Complete list of USGS parameter codes as of September 25, 2013. #' #' @name parameterCdFile #' @docType data #' @keywords USGS parameterCd NULL
/R/USGSwsDataRetrieval.R
permissive
wcdamsch/USGSwsDataRetrieval
R
false
false
1,150
r
#' Retrieval functions for USGS data #' #' \tabular{ll}{ #' Package: \tab USGSwsDataRetrieval\cr #' Type: \tab Package\cr #' Version: \tab 0.0.0\cr #' Date: \tab 2014-07-03\cr #' License: \tab Unlimited for this package, dependencies have more restrictive licensing.\cr #' Copyright: \tab This software is in the public domain because it contains materials #' that originally came from the United States Geological Survey, an agency of #' the United States Department of Interior. For more information, see the #' official USGS copyright policy at #' http://www.usgs.gov/visual-id/credit_usgs.html#copyright\cr #' LazyLoad: \tab yes\cr #' } #' #' Collection of functions to help retrieve USGS data from either web services or user provided data files. #' #' @name USGSwsDataRetrieval-package #' @import RCurl XML reshape2 #' @docType package #' @author David Lorenz \email{lorenz@@usgs.gov}, Laura De Cicco \email{ldecicco@@usgs.gov} #' @keywords data, retrieval NULL #' List of USGS parameter codes #' #' Complete list of USGS parameter codes as of September 25, 2013. #' #' @name parameterCdFile #' @docType data #' @keywords USGS parameterCd NULL
rm(list=ls()) subtype <- "~/GDAN/fpkm-uq/TCGA-BRCA/BRCA_subtype.txt" geneannot_file <- "~/GDAN/scripts/geneannot.rds" outdir <- "~/GDAN//fpkm-uq/TCGA-BRCA/output/" active_file_rds <- paste(outdir,"active.rds",sep="") legacy_file_rds <- paste(outdir,"legacy.rds",sep="") merged_file_rds <- paste(outdir,"merged_active_legacy.rds",sep="") functions_file <- "~/GDAN/scripts/rsem_fpkm_functions.R" cancer_var <- "BRCA" subtype_var <- "Expression_subtype" data.full <- readRDS(file=merged_file_rds) data.ge <- subset(data.full,! row.names(data.full) %in% c("dataset",subtype_var,"entrezgene")) dataset <- data.full["dataset",] data_df1 <- rbind(data.ge,cl=dataset) dim(data_df1) source(functions_file) analysis(data_df1,"BRCA\n",outdir) #subtype analysis pat <- "-\\d\\d\\w-\\d\\d\\w-\\w\\w\\w\\w-\\d\\d$" actdf <- readRDS(file=active_file_rds) actdf <- add_subtype_row(actdf,subtype,subtype_var,"Barcode",pat) rownames(actdf) <- gsub("\\.\\d+","",rownames(actdf), perl=TRUE) actdf <- rbind(actdf,dataset=rep(38,dim(actdf)[2])) legacy <- readRDS(file=legacy_file_rds) en2hg <- readRDS(file=geneannot_file) legacy$hgnc <- gsub("\\|\\d+$","",rownames(legacy),perl=TRUE) legacy$entrezgene <- gsub("^[\\w\\-]+\\|","",rownames(legacy),perl=TRUE) legacy <- legacy[!duplicated(legacy$entrezgene),] legacy <- merge(legacy,en2hg,by.x='entrezgene',by.y='entrezgene') legacy <- legacy[!duplicated(legacy$ensembl_gene_id),] rownames(legacy) <- legacy$ensembl_gene_id legacy <- rbind(legacy,dataset=rep(19,dim(legacy)[2])) legacy <- add_subtype_row(legacy,subtype,subtype_var,"Barcode",pat) mergeddf <- merge(legacy,actdf,by="row.names") rownames(mergeddf) <- mergeddf$Row.names dim(mergeddf) mergeddf$Row.names <- NULL mergeddf$hgnc <- NULL mergeddf$ensembl_gene_id <- NULL mergeddf$entrezgene <- NULL fileout=paste(outdir,"merged_with_subtype.rds",sep="") saveRDS(mergeddf,file=fileout) m <- readRDS(file=paste(outdir,"merged_with_subtype.rds",sep="")) plotname <- paste(cancer_var,subtype_var) class_analysis(m,"dataset",subtype_var,plotname,outdir,cancer_var)
/tcga_brca_2.R
no_license
joelsparker1/gdan_rna_qc
R
false
false
2,140
r
rm(list=ls()) subtype <- "~/GDAN/fpkm-uq/TCGA-BRCA/BRCA_subtype.txt" geneannot_file <- "~/GDAN/scripts/geneannot.rds" outdir <- "~/GDAN//fpkm-uq/TCGA-BRCA/output/" active_file_rds <- paste(outdir,"active.rds",sep="") legacy_file_rds <- paste(outdir,"legacy.rds",sep="") merged_file_rds <- paste(outdir,"merged_active_legacy.rds",sep="") functions_file <- "~/GDAN/scripts/rsem_fpkm_functions.R" cancer_var <- "BRCA" subtype_var <- "Expression_subtype" data.full <- readRDS(file=merged_file_rds) data.ge <- subset(data.full,! row.names(data.full) %in% c("dataset",subtype_var,"entrezgene")) dataset <- data.full["dataset",] data_df1 <- rbind(data.ge,cl=dataset) dim(data_df1) source(functions_file) analysis(data_df1,"BRCA\n",outdir) #subtype analysis pat <- "-\\d\\d\\w-\\d\\d\\w-\\w\\w\\w\\w-\\d\\d$" actdf <- readRDS(file=active_file_rds) actdf <- add_subtype_row(actdf,subtype,subtype_var,"Barcode",pat) rownames(actdf) <- gsub("\\.\\d+","",rownames(actdf), perl=TRUE) actdf <- rbind(actdf,dataset=rep(38,dim(actdf)[2])) legacy <- readRDS(file=legacy_file_rds) en2hg <- readRDS(file=geneannot_file) legacy$hgnc <- gsub("\\|\\d+$","",rownames(legacy),perl=TRUE) legacy$entrezgene <- gsub("^[\\w\\-]+\\|","",rownames(legacy),perl=TRUE) legacy <- legacy[!duplicated(legacy$entrezgene),] legacy <- merge(legacy,en2hg,by.x='entrezgene',by.y='entrezgene') legacy <- legacy[!duplicated(legacy$ensembl_gene_id),] rownames(legacy) <- legacy$ensembl_gene_id legacy <- rbind(legacy,dataset=rep(19,dim(legacy)[2])) legacy <- add_subtype_row(legacy,subtype,subtype_var,"Barcode",pat) mergeddf <- merge(legacy,actdf,by="row.names") rownames(mergeddf) <- mergeddf$Row.names dim(mergeddf) mergeddf$Row.names <- NULL mergeddf$hgnc <- NULL mergeddf$ensembl_gene_id <- NULL mergeddf$entrezgene <- NULL fileout=paste(outdir,"merged_with_subtype.rds",sep="") saveRDS(mergeddf,file=fileout) m <- readRDS(file=paste(outdir,"merged_with_subtype.rds",sep="")) plotname <- paste(cancer_var,subtype_var) class_analysis(m,"dataset",subtype_var,plotname,outdir,cancer_var)
\alias{gtkRecentInfoGetDescription} \name{gtkRecentInfoGetDescription} \title{gtkRecentInfoGetDescription} \description{Gets the (short) description of the resource.} \usage{gtkRecentInfoGetDescription(object)} \arguments{\item{\code{object}}{[\code{\link{GtkRecentInfo}}] a \code{\link{GtkRecentInfo}}}} \details{ Since 2.10} \value{[character] the description of the resource.} \author{Derived by RGtkGen from GTK+ documentation} \keyword{internal}
/man/gtkRecentInfoGetDescription.Rd
no_license
cran/RGtk2.10
R
false
false
455
rd
\alias{gtkRecentInfoGetDescription} \name{gtkRecentInfoGetDescription} \title{gtkRecentInfoGetDescription} \description{Gets the (short) description of the resource.} \usage{gtkRecentInfoGetDescription(object)} \arguments{\item{\code{object}}{[\code{\link{GtkRecentInfo}}] a \code{\link{GtkRecentInfo}}}} \details{ Since 2.10} \value{[character] the description of the resource.} \author{Derived by RGtkGen from GTK+ documentation} \keyword{internal}
#' Dupla Sena lottery game probability #' #' Does the ticket have 50 tens, in which the bettor can? dial from 6 to 15 numbers, #' consists of extracting 6 different numbers, you can win by hitting 3, 4, 5 or #' 6 numbers, with a differential, the player has two chances to win. #' #' To choose 6 numbers, the bet is simple, where it offers the lowest odds #' win: combination of 50 numbers taken from 6 to 6 = 50!/6!44! = 15890700 #' However, as there are two draws, the player has two chances out of approximately 16 million. #' 2/15890700 = 1/7945350, to win any of the SENAS, the player has approximately 1 chance in 8 million. #' #'x is the amount of numbers bet #' #'y is the amount number of hits #' #' @param x number #' @param y number #' #' @return number #' @export #' #' @examples ProbDSena(15,5) ProbDSena = function(x,y){ prob = (choose(x,y)*choose(50-x,6-y)*2)/choose(50,6) if(y>6){ prob = 0 message("The maximum number of correct answers is six") } else if(y<=2){ stop("There is no such probability of hits in Dupla Sena") } else if(y==3) message("Happy birthday. you hit the Terno!") if(y==4) message("Happy birthday. you hit the Quadra!") if(y==5) message("Happy birthday. you hit the Quina!") if(y==6) message("Happy birthday. You are champion of the Dupla Sena!") return(prob) }
/R/ProbDSena.R
permissive
farias741/Lotto
R
false
false
1,361
r
#' Dupla Sena lottery game probability #' #' Does the ticket have 50 tens, in which the bettor can? dial from 6 to 15 numbers, #' consists of extracting 6 different numbers, you can win by hitting 3, 4, 5 or #' 6 numbers, with a differential, the player has two chances to win. #' #' To choose 6 numbers, the bet is simple, where it offers the lowest odds #' win: combination of 50 numbers taken from 6 to 6 = 50!/6!44! = 15890700 #' However, as there are two draws, the player has two chances out of approximately 16 million. #' 2/15890700 = 1/7945350, to win any of the SENAS, the player has approximately 1 chance in 8 million. #' #'x is the amount of numbers bet #' #'y is the amount number of hits #' #' @param x number #' @param y number #' #' @return number #' @export #' #' @examples ProbDSena(15,5) ProbDSena = function(x,y){ prob = (choose(x,y)*choose(50-x,6-y)*2)/choose(50,6) if(y>6){ prob = 0 message("The maximum number of correct answers is six") } else if(y<=2){ stop("There is no such probability of hits in Dupla Sena") } else if(y==3) message("Happy birthday. you hit the Terno!") if(y==4) message("Happy birthday. you hit the Quadra!") if(y==5) message("Happy birthday. you hit the Quina!") if(y==6) message("Happy birthday. You are champion of the Dupla Sena!") return(prob) }
# connectivity with macrobond, try around when you get a chance # https://help.macrobond.com/add-ins/the-macrobond-api-for-r/
/Macrobond.R
no_license
mustang115/Rsetup
R
false
false
126
r
# connectivity with macrobond, try around when you get a chance # https://help.macrobond.com/add-ins/the-macrobond-api-for-r/
# setup temp folders --------------------------- temp_folder <- tempdir() dir2 <- file.path(temp_folder, "tmp2") dir3 <- file.path(temp_folder, "tmp3") setup({ dir.create(dir2) dir.create(dir3) }) teardown({ unlink(dir2, recursive = TRUE) unlink(dir3, recursive = TRUE) }) p1 <- ".." rr <- sample(1:29, 4) # get 4 random nodes message('\n4 random nodes are: ',paste(rr, collapse = " ")) r2u <- zoo::as.yearmon(c('1950-01','1954-12')) # check errors ------------------- test_that("Upfront errors post correctly", { expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = 'doesNotExist', startYear = 2017, endYear = 2021, recordToUse = r2u ), paste0(file.path("doesNotExist"), " folder does not exist.", "\n", "Create the directory before calling crssi_create_dnf_files()") ) expect_error( crssi_create_dnf_files( "CoRiverNF.txt", oFolder = 'doesNotExist', startYear = 2017, endYear = 2021, recordToUse = r2u ), paste0("CoRiverNF.txt does not appear to be valid.\n", "It should be either an Excel (xlsx) file or 'CoRiverNF'"), fixed = TRUE ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = c("1906-01", "1997-12") ), "recordToUse must be class 'yearmon'." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-01", "1997-12", "1999-12")) ), "recordToUse should only contain two entries, or be 'NA'." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-2", "1997-12")) ), "The first entry to recordToUse should be January of some year." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-1", "1997-11")) ), "The second entry to recordToUse should be December of some year." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1905-1", "1997-12")) ), "Years in recordToUse should not be before 1906." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-1", "1905-12")) ), "Years in recordToUse should not be before 1906." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1988-1", "1980-12")) ), "The second entry in recordToUse should be after the first entry." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1988-1", "2100-12")) ), paste( "The end year in `recordToUse` must be <=", as.integer(format(tail(zoo::index(CoRiverNF::monthlyInt), 1), "%Y")) ) ) }) # check the two different fucntions create data ------- # because we are using pre- 1971 data, we do not need to regenerate the data # in the provided trace folders each time the natural flow are updated test_that('can create files',{ expect_message( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = r2u ) ) expect_warning(expect_message( crssi_create_dnf_files( "../NaturalFlows_Sample.xlsx", oFolder = dir3, startYear = 2017, endYear = 2021, recordToUse = r2u ) )) }) # check that all files in the three directories are the same ------------- dirs <- list.dirs(dir2, recursive = FALSE, full.names = FALSE) test_that("all files are the same", { for(curDir in dirs){ allFiles <- list.files(file.path(dir2, curDir)) for(ff in allFiles){ #message(curDir, "/", ff) expect_identical( scan(file.path(dir2, curDir, ff), what = "character", quiet = TRUE), scan(file.path(dir3, curDir, ff), what = "character", quiet = TRUE), info = paste(curDir, ff) ) } } }) allFiles <- c(nf_file_names(), "MWD_ICS.SacWYType", "MeadFloodControlData.hydrologyIncrement", "HydrologyParameters.TraceNumber", "HydrologyParameters.SupplyScenario") test_that("all files exist", { expect_setequal(allFiles, list.files(file.path(dir2, "trace1"))) expect_setequal(allFiles, list.files(file.path(dir2, "trace3"))) }) test_that('files created from "CoRiverNF" are the same as from Excel', { expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[1]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace1', nf_file_names()[rr[1]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace5',nf_file_names()[rr[1]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace5', nf_file_names()[rr[1]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace2',nf_file_names()[rr[2]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace2', nf_file_names()[rr[2]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace3',nf_file_names()[rr[3]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace3', nf_file_names()[rr[3]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace4',nf_file_names()[rr[4]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace4', nf_file_names()[rr[4]]), skip = 1 )) ) }) test_that('ism files match each other as expected', { expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[1]]), skip = 1 ))[13:24], as.matrix(read.csv( file.path(p1,'trace2', nf_file_names()[rr[1]]), skip = 1 ))[1:12] ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[2]]), skip = 1 ))[49:60], as.matrix(read.csv( file.path(p1,'trace5', nf_file_names()[rr[2]]), skip = 1 ))[1:12] ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[2]]), skip = 1 ))[1:12], as.matrix(read.csv( file.path(p1,'trace4', nf_file_names()[rr[2]]), skip = 1 ))[25:36] ) }) # internal format excel function ------------------- test_that("Excel formatting works", { expect_warning(expect_s3_class( tmp <- CRSSIO:::read_and_format_nf_excel("../NaturalFlows_Sample.xlsx"), c("xts", "zoo") )) expect_equal(ncol(tmp), 29) expect_equal(nrow(tmp) %% 12, 0) expect_equal(zoo::index(tmp)[1], zoo::as.yearmon("Jan 1906")) expect_equal(format(tail(zoo::index(tmp),1), "%b"), "Dec") })
/tests/testthat/test-nfFileCreation.R
no_license
rabutler-usbr/CRSSIO
R
false
false
7,342
r
# setup temp folders --------------------------- temp_folder <- tempdir() dir2 <- file.path(temp_folder, "tmp2") dir3 <- file.path(temp_folder, "tmp3") setup({ dir.create(dir2) dir.create(dir3) }) teardown({ unlink(dir2, recursive = TRUE) unlink(dir3, recursive = TRUE) }) p1 <- ".." rr <- sample(1:29, 4) # get 4 random nodes message('\n4 random nodes are: ',paste(rr, collapse = " ")) r2u <- zoo::as.yearmon(c('1950-01','1954-12')) # check errors ------------------- test_that("Upfront errors post correctly", { expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = 'doesNotExist', startYear = 2017, endYear = 2021, recordToUse = r2u ), paste0(file.path("doesNotExist"), " folder does not exist.", "\n", "Create the directory before calling crssi_create_dnf_files()") ) expect_error( crssi_create_dnf_files( "CoRiverNF.txt", oFolder = 'doesNotExist', startYear = 2017, endYear = 2021, recordToUse = r2u ), paste0("CoRiverNF.txt does not appear to be valid.\n", "It should be either an Excel (xlsx) file or 'CoRiverNF'"), fixed = TRUE ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = c("1906-01", "1997-12") ), "recordToUse must be class 'yearmon'." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-01", "1997-12", "1999-12")) ), "recordToUse should only contain two entries, or be 'NA'." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-2", "1997-12")) ), "The first entry to recordToUse should be January of some year." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-1", "1997-11")) ), "The second entry to recordToUse should be December of some year." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1905-1", "1997-12")) ), "Years in recordToUse should not be before 1906." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1906-1", "1905-12")) ), "Years in recordToUse should not be before 1906." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1988-1", "1980-12")) ), "The second entry in recordToUse should be after the first entry." ) expect_error( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = zoo::as.yearmon(c("1988-1", "2100-12")) ), paste( "The end year in `recordToUse` must be <=", as.integer(format(tail(zoo::index(CoRiverNF::monthlyInt), 1), "%Y")) ) ) }) # check the two different fucntions create data ------- # because we are using pre- 1971 data, we do not need to regenerate the data # in the provided trace folders each time the natural flow are updated test_that('can create files',{ expect_message( crssi_create_dnf_files( 'CoRiverNF', oFolder = dir2, startYear = 2017, endYear = 2021, recordToUse = r2u ) ) expect_warning(expect_message( crssi_create_dnf_files( "../NaturalFlows_Sample.xlsx", oFolder = dir3, startYear = 2017, endYear = 2021, recordToUse = r2u ) )) }) # check that all files in the three directories are the same ------------- dirs <- list.dirs(dir2, recursive = FALSE, full.names = FALSE) test_that("all files are the same", { for(curDir in dirs){ allFiles <- list.files(file.path(dir2, curDir)) for(ff in allFiles){ #message(curDir, "/", ff) expect_identical( scan(file.path(dir2, curDir, ff), what = "character", quiet = TRUE), scan(file.path(dir3, curDir, ff), what = "character", quiet = TRUE), info = paste(curDir, ff) ) } } }) allFiles <- c(nf_file_names(), "MWD_ICS.SacWYType", "MeadFloodControlData.hydrologyIncrement", "HydrologyParameters.TraceNumber", "HydrologyParameters.SupplyScenario") test_that("all files exist", { expect_setequal(allFiles, list.files(file.path(dir2, "trace1"))) expect_setequal(allFiles, list.files(file.path(dir2, "trace3"))) }) test_that('files created from "CoRiverNF" are the same as from Excel', { expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[1]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace1', nf_file_names()[rr[1]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace5',nf_file_names()[rr[1]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace5', nf_file_names()[rr[1]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace2',nf_file_names()[rr[2]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace2', nf_file_names()[rr[2]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace3',nf_file_names()[rr[3]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace3', nf_file_names()[rr[3]]), skip = 1 )) ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace4',nf_file_names()[rr[4]]), skip = 1 )), as.matrix(read.csv( file.path(p1,'trace4', nf_file_names()[rr[4]]), skip = 1 )) ) }) test_that('ism files match each other as expected', { expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[1]]), skip = 1 ))[13:24], as.matrix(read.csv( file.path(p1,'trace2', nf_file_names()[rr[1]]), skip = 1 ))[1:12] ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[2]]), skip = 1 ))[49:60], as.matrix(read.csv( file.path(p1,'trace5', nf_file_names()[rr[2]]), skip = 1 ))[1:12] ) expect_equal( as.matrix(read.csv( file.path(dir2, 'trace1',nf_file_names()[rr[2]]), skip = 1 ))[1:12], as.matrix(read.csv( file.path(p1,'trace4', nf_file_names()[rr[2]]), skip = 1 ))[25:36] ) }) # internal format excel function ------------------- test_that("Excel formatting works", { expect_warning(expect_s3_class( tmp <- CRSSIO:::read_and_format_nf_excel("../NaturalFlows_Sample.xlsx"), c("xts", "zoo") )) expect_equal(ncol(tmp), 29) expect_equal(nrow(tmp) %% 12, 0) expect_equal(zoo::index(tmp)[1], zoo::as.yearmon("Jan 1906")) expect_equal(format(tail(zoo::index(tmp),1), "%b"), "Dec") })
# Hello, world! # # This is an example function named 'hello' # which prints 'Hello, world!'. # # You can learn more about package authoring with RStudio at: # # http://r-pkgs.had.co.nz/ # # Some useful keyboard shortcuts for package authoring: # # Build and Reload Package: 'Ctrl + Shift + B' # Check Package: 'Ctrl + Shift + E' # Test Package: 'Ctrl + Shift + T' #
/R/hello.R
no_license
jimmywle/tsoutlier
R
false
false
401
r
# Hello, world! # # This is an example function named 'hello' # which prints 'Hello, world!'. # # You can learn more about package authoring with RStudio at: # # http://r-pkgs.had.co.nz/ # # Some useful keyboard shortcuts for package authoring: # # Build and Reload Package: 'Ctrl + Shift + B' # Check Package: 'Ctrl + Shift + E' # Test Package: 'Ctrl + Shift + T' #
\name{midint} \alias{midint} \title{ Calculation of the middle of time interval } \description{ Calculates the middle of observing time interval for a given visual meteor dataset. } \usage{ midint(data) } \arguments{ \item{data}{ data frame consisting of visual meteor data (rate or magnitude data). } } \value{ \code{midint} returns the middle of observing time interval, in \code{"\%Y-\%m-\%d \%H:\%M:\%S"} format, UTC timezone (object of \code{POSIXct} class). } \author{ Kristina Veljkovic } \note{ Argument \code{data} has to consist of the columns named "Start.Date" and "End.Date". These dates should be given in \code{"\%Y-\%m-\%d \%H:\%M:\%S"} format (UTC timezone). } \seealso{ \code{\link{solar.long}} } \examples{ ## calculate middle of time interval for rate and magnitude data, year 2015 midint(rate2015) midint(magn2015) }
/man/midint.Rd
no_license
cran/MetFns
R
false
false
885
rd
\name{midint} \alias{midint} \title{ Calculation of the middle of time interval } \description{ Calculates the middle of observing time interval for a given visual meteor dataset. } \usage{ midint(data) } \arguments{ \item{data}{ data frame consisting of visual meteor data (rate or magnitude data). } } \value{ \code{midint} returns the middle of observing time interval, in \code{"\%Y-\%m-\%d \%H:\%M:\%S"} format, UTC timezone (object of \code{POSIXct} class). } \author{ Kristina Veljkovic } \note{ Argument \code{data} has to consist of the columns named "Start.Date" and "End.Date". These dates should be given in \code{"\%Y-\%m-\%d \%H:\%M:\%S"} format (UTC timezone). } \seealso{ \code{\link{solar.long}} } \examples{ ## calculate middle of time interval for rate and magnitude data, year 2015 midint(rate2015) midint(magn2015) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Misc_Exported.R \name{setup} \alias{setup} \title{Setup parallel processing} \usage{ setup(cpus = parallel::detectCores() * 0.5, ...) } \arguments{ \item{cpus}{number of CPUs} \item{...}{other arguments passed to 'snowfall::sfInit'} } \description{ Sets up parallel processing using the snowfall package } \examples{ \dontrun{ setup() # set-up half the available processors setup(6) # set-up 6 processors } }
/man/setup.Rd
no_license
DLMtool/DLMtool
R
false
true
488
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Misc_Exported.R \name{setup} \alias{setup} \title{Setup parallel processing} \usage{ setup(cpus = parallel::detectCores() * 0.5, ...) } \arguments{ \item{cpus}{number of CPUs} \item{...}{other arguments passed to 'snowfall::sfInit'} } \description{ Sets up parallel processing using the snowfall package } \examples{ \dontrun{ setup() # set-up half the available processors setup(6) # set-up 6 processors } }
#' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @rdname random_search #' @param IOHproblem An IOHproblem object #' #' @export #' @examples #' \donttest{ #' benchmark_algorithm(IOH_random_search, data.dir = NULL) #' } IOH_random_search <- function(IOHproblem, budget = NULL) { if (IOHproblem$suite == "PBO") random_search_PB(IOHproblem$dimension, IOHproblem$obj_func, IOHproblem$target_hit, budget) else random_search(IOHproblem$dimension, IOHproblem$obj_func, IOHproblem$target_hit, budget, IOHproblem$lbound, IOHproblem$ubound, IOHproblem$maximization) } #' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @param IOHproblem An IOHproblem object #' #' @rdname random_local_search #' @export #' @examples #' \donttest{ #' benchmark_algorithm(IOH_random_local_search, data.dir = NULL) #' } IOH_random_local_search <- function(IOHproblem, budget = NULL) { random_local_search(IOHproblem$dimension, IOHproblem$obj_func, IOHproblem$target_hit, budget) } #' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @param IOHproblem An IOHproblem object #' #' @rdname self_adaptive_GA #' @export #' @examples #' \donttest{ #' one_comma_two_EA <- function(IOHproblem) { IOH_self_adaptive_GA(IOHproblem, lambda_=2) } #' #' benchmark_algorithm(one_comma_two_EA, params.track = "Mutation rate", #' algorithm.name = "one_comma_two_EA", data.dir = NULL, #' algorithm.info = "Using one_comma_two_EA with specific parameter" ) #' } IOH_self_adaptive_GA <- function(IOHproblem, lambda_ = 1, budget = NULL) { self_adaptive_GA(IOHproblem$dimension, IOHproblem$obj_func, target_hit = IOHproblem$target_hit, budget = budget, lambda_ = lambda_, set_parameters = IOHproblem$set_parameters) } #' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @param IOHproblem An IOHproblem object #' #' @rdname two_rate_GA #' @export #' @examples #' \donttest{ #' bechmark_algorithm(IOH_two_rate_GA) #' } IOH_two_rate_GA <- function(IOHproblem, lambda_ = 1, budget = NULL) { two_rate_GA(IOHproblem$dimension, IOHproblem$obj_func, budget = budget, lambda_ = lambda_, set_parameters = IOHproblem$set_parameters, target_hit = IOHproblem$target_hit) } #' Random Search #' #' Random walk in \eqn{{0, 1}^d} space; Maximization #' #' @rdname random_search #' @export random_search_PB <- function(dim, obj_func, target_hit = function(){ FALSE }, budget = NULL) { if (is.null(budget)) budget <- 10 * dim fopt <- -Inf xopt <- NULL while (budget > 0 && !target_hit()) { x <- sample(c(0, 1), dim, TRUE) f <- obj_func(x) budget <- budget - 1 if (f > fopt) { xopt <- x fopt <- f } } list(xopt = xopt, fopt = fopt) } #' Random Search #' #' Random walk in continuous space; #' #' @param dim Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param budget Integer, maximal allowable number of function evaluations #' @param lbound Lower bound of search space. Either single number or vector of size `dim` #' @param ubound Upper bound of search space. Either single number or vector of size `dim` #' @param maximize Whether to perform maximization or minimization. #' The function assumes minimization, achieved by inverting the obj_func when `maximize` is FALSE #' @export random_search <- function(dim, obj_func, target_hit = function(){ FALSE }, budget = NULL, lbound = -1, ubound = 1, maximize = T) { if (is.null(budget)) budget <- 10 * dim if (maximize) { #Assume mimimization in the remainder of this function obj_func_transformed <- function(x) {return(-1*obj_func(x))} } else{ obj_func_transformed <- obj_func } fopt <- Inf xopt <- NULL while (budget > 0 && !target_hit()) { x <- runif(dim, lbound, ubound) f <- obj_func_transformed(x) budget <- budget - 1 if (f < fopt) { xopt <- x fopt <- f } } list(xopt = xopt, fopt = fopt) } #' Random Local Search (RLS) Algorithm #' #' The simplest stochastic optimization algorithm for discrete problems. A randomly #' chosen position in the solution vector is perturbated in each iteration. Only #' improvements are accepted after perturbation. #' #' #' @param dimension Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param budget integer, maximal allowable number of function evaluations #' #' @export random_local_search <- function(dimension, obj_func, target_hit = function(){ FALSE }, budget = NULL) { if (is.null(budget)) budget <- 10*dimension starting_point <- sample(c(0, 1), dimension, TRUE) fopt <- obj_func(starting_point) xopt <- starting_point iter <- 1 while (iter < budget && !target_hit() ) { candidate <- xopt switch_idx <- sample(1:dimension, 1) candidate[switch_idx] <- 1 - candidate[switch_idx] fval <- obj_func(candidate) if (fval >= fopt) { fopt <- fval xopt <- candidate } iter <- iter + 1 } list(xopt = xopt, fopt = fopt) } #' Mutation operator for 1+lambda EA #' #' #' @param ind The individual to mutate #' @param mutation_rate The mutation rate #' @noRd mutate <- function(ind, mutation_rate){ dim <- length(ind) mutations <- seq(0, 0, length.out = dim) while (sum(mutations) == 0) { mutations <- sample(c(0, 1), dim, prob = c(1 - mutation_rate, mutation_rate), replace = TRUE) } as.integer( xor(ind, mutations) ) } #' One-Comma-Lambda Self-Adapative Genetic Algorithm #' #' A genetic algorithm that controls the mutation rate (strength) using the so-called #' self-adaptation mechanism: the mutation rate is firstly perturbated and then the #' resulting value is taken to mutate Lambda solution vector. The best solution is #' selected along with its mutation rate. #' #' @param lambda_ The size of the offspring #' @param budget How many times the objective function can be evaluated #' @param dimension Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param set_parameters Function to call to store the value of the registered parameters #' #' @export self_adaptive_GA <- function(dimension, obj_func, lambda_ = 10, budget = NULL, set_parameters = NULL, target_hit = function(){ FALSE }) { obj_func <- obj_func if (is.null(budget)) budget <- 10 * dimension r <- 1.0 / dimension if (is.function(set_parameters)) set_parameters(r) x <- sample(c(0, 1), dimension, TRUE) xopt <- x fopt <- fx <- obj_func(x) budget <- budget - 1 tau <- 0.22 while (budget > 0 && !target_hit()) { lambda_ <- min(lambda_, budget) #ensure budget is not exceeded x_ <- tcrossprod(rep(1, lambda_), x) r_ <- (1.0 / (1 + (1 - r) / r * exp(tau * rnorm(lambda_)))) %*% t(rep(1, dimension)) idx <- matrix(runif(lambda_ * dimension), lambda_, dimension) < r_ x_[idx] <- 1 - x_[idx] if (is.function(set_parameters)) set_parameters(r) f <- obj_func(x_) budget <- budget - lambda_ selected <- which(min(f) == f)[[1]] x <- x_[selected, ] r <- r_[selected, 1] if (f[selected] > fopt) { fopt <- f[selected] xopt <- x } } list(xopt = xopt, fopt = fopt) } #' One-Comma-Lambda Genetic Algorithm with 2-rate self-adaptive mutation rate #' #' A genetic algorithm that controls the mutation rate (strength) using the so-called #' 2-rate self-adaptation mechanism: the mutation rate is based on a parameter r. For #' each generation, half offspring are generated by mutation rate 2r/dim, and half by #' r/2dim. r that the best offspring has been created with will be inherited by #' probability 3/4, the other by 1/4. #' #' @param lambda_ The size of the offspring #' @param budget How many times the objective function can be evaluated #' @param dimension Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param set_parameters Function to call to store the value of the registered parameters #' #' @export two_rate_GA <- function(dimension, obj_func, target_hit = function() { FALSE }, lambda_ = 2, budget = NULL, set_parameters = NULL){ if (is.null(budget)) budget <- 100*dimension parent <- sample(c(0, 1), dimension, TRUE) best <- parent r <- 2.0 fopt <- obj_func(parent) budget <- budget - 1 if (is.function(set_parameters)) set_parameters(r) while (budget > 0 && !target_hit()) { selected_r <- r; selected_obj <- -Inf for (i in 1:lambda_) { offspring <- parent if (i <= lambda_/2) { mutation_rate = r / 2.0 / dimension; } else{ mutation_rate = 2.0 * r / dimension; } offspring <- mutate(offspring, mutation_rate) v <- obj_func(offspring) if (v >= fopt) { fopt <- v best <- offspring } if (v >= selected_obj) { selected_obj = v selected_r = mutation_rate * dimension; } budget <- budget - 1 if (budget == 0 ) break } parent <- best if (runif(1) > 0.5) { r = selected_r } else{ if (runif(1) > 0.5) { r = r / 2.0 } else{ r = 2.0 * r } } if (r < 2.0) r = 2.0 if (r > dimension / 4.0) r = dimension / 4.0 if (is.function(set_parameters)) set_parameters(r) } list(xopt = best, fopt = fopt) }
/build/R/R/Algorithms.R
permissive
nojhan/IOHexperimenter
R
false
false
9,877
r
#' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @rdname random_search #' @param IOHproblem An IOHproblem object #' #' @export #' @examples #' \donttest{ #' benchmark_algorithm(IOH_random_search, data.dir = NULL) #' } IOH_random_search <- function(IOHproblem, budget = NULL) { if (IOHproblem$suite == "PBO") random_search_PB(IOHproblem$dimension, IOHproblem$obj_func, IOHproblem$target_hit, budget) else random_search(IOHproblem$dimension, IOHproblem$obj_func, IOHproblem$target_hit, budget, IOHproblem$lbound, IOHproblem$ubound, IOHproblem$maximization) } #' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @param IOHproblem An IOHproblem object #' #' @rdname random_local_search #' @export #' @examples #' \donttest{ #' benchmark_algorithm(IOH_random_local_search, data.dir = NULL) #' } IOH_random_local_search <- function(IOHproblem, budget = NULL) { random_local_search(IOHproblem$dimension, IOHproblem$obj_func, IOHproblem$target_hit, budget) } #' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @param IOHproblem An IOHproblem object #' #' @rdname self_adaptive_GA #' @export #' @examples #' \donttest{ #' one_comma_two_EA <- function(IOHproblem) { IOH_self_adaptive_GA(IOHproblem, lambda_=2) } #' #' benchmark_algorithm(one_comma_two_EA, params.track = "Mutation rate", #' algorithm.name = "one_comma_two_EA", data.dir = NULL, #' algorithm.info = "Using one_comma_two_EA with specific parameter" ) #' } IOH_self_adaptive_GA <- function(IOHproblem, lambda_ = 1, budget = NULL) { self_adaptive_GA(IOHproblem$dimension, IOHproblem$obj_func, target_hit = IOHproblem$target_hit, budget = budget, lambda_ = lambda_, set_parameters = IOHproblem$set_parameters) } #' IOHexperimenter-based wrapper #' #' For easier use with the IOHexperimenter #' #' @param IOHproblem An IOHproblem object #' #' @rdname two_rate_GA #' @export #' @examples #' \donttest{ #' bechmark_algorithm(IOH_two_rate_GA) #' } IOH_two_rate_GA <- function(IOHproblem, lambda_ = 1, budget = NULL) { two_rate_GA(IOHproblem$dimension, IOHproblem$obj_func, budget = budget, lambda_ = lambda_, set_parameters = IOHproblem$set_parameters, target_hit = IOHproblem$target_hit) } #' Random Search #' #' Random walk in \eqn{{0, 1}^d} space; Maximization #' #' @rdname random_search #' @export random_search_PB <- function(dim, obj_func, target_hit = function(){ FALSE }, budget = NULL) { if (is.null(budget)) budget <- 10 * dim fopt <- -Inf xopt <- NULL while (budget > 0 && !target_hit()) { x <- sample(c(0, 1), dim, TRUE) f <- obj_func(x) budget <- budget - 1 if (f > fopt) { xopt <- x fopt <- f } } list(xopt = xopt, fopt = fopt) } #' Random Search #' #' Random walk in continuous space; #' #' @param dim Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param budget Integer, maximal allowable number of function evaluations #' @param lbound Lower bound of search space. Either single number or vector of size `dim` #' @param ubound Upper bound of search space. Either single number or vector of size `dim` #' @param maximize Whether to perform maximization or minimization. #' The function assumes minimization, achieved by inverting the obj_func when `maximize` is FALSE #' @export random_search <- function(dim, obj_func, target_hit = function(){ FALSE }, budget = NULL, lbound = -1, ubound = 1, maximize = T) { if (is.null(budget)) budget <- 10 * dim if (maximize) { #Assume mimimization in the remainder of this function obj_func_transformed <- function(x) {return(-1*obj_func(x))} } else{ obj_func_transformed <- obj_func } fopt <- Inf xopt <- NULL while (budget > 0 && !target_hit()) { x <- runif(dim, lbound, ubound) f <- obj_func_transformed(x) budget <- budget - 1 if (f < fopt) { xopt <- x fopt <- f } } list(xopt = xopt, fopt = fopt) } #' Random Local Search (RLS) Algorithm #' #' The simplest stochastic optimization algorithm for discrete problems. A randomly #' chosen position in the solution vector is perturbated in each iteration. Only #' improvements are accepted after perturbation. #' #' #' @param dimension Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param budget integer, maximal allowable number of function evaluations #' #' @export random_local_search <- function(dimension, obj_func, target_hit = function(){ FALSE }, budget = NULL) { if (is.null(budget)) budget <- 10*dimension starting_point <- sample(c(0, 1), dimension, TRUE) fopt <- obj_func(starting_point) xopt <- starting_point iter <- 1 while (iter < budget && !target_hit() ) { candidate <- xopt switch_idx <- sample(1:dimension, 1) candidate[switch_idx] <- 1 - candidate[switch_idx] fval <- obj_func(candidate) if (fval >= fopt) { fopt <- fval xopt <- candidate } iter <- iter + 1 } list(xopt = xopt, fopt = fopt) } #' Mutation operator for 1+lambda EA #' #' #' @param ind The individual to mutate #' @param mutation_rate The mutation rate #' @noRd mutate <- function(ind, mutation_rate){ dim <- length(ind) mutations <- seq(0, 0, length.out = dim) while (sum(mutations) == 0) { mutations <- sample(c(0, 1), dim, prob = c(1 - mutation_rate, mutation_rate), replace = TRUE) } as.integer( xor(ind, mutations) ) } #' One-Comma-Lambda Self-Adapative Genetic Algorithm #' #' A genetic algorithm that controls the mutation rate (strength) using the so-called #' self-adaptation mechanism: the mutation rate is firstly perturbated and then the #' resulting value is taken to mutate Lambda solution vector. The best solution is #' selected along with its mutation rate. #' #' @param lambda_ The size of the offspring #' @param budget How many times the objective function can be evaluated #' @param dimension Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param set_parameters Function to call to store the value of the registered parameters #' #' @export self_adaptive_GA <- function(dimension, obj_func, lambda_ = 10, budget = NULL, set_parameters = NULL, target_hit = function(){ FALSE }) { obj_func <- obj_func if (is.null(budget)) budget <- 10 * dimension r <- 1.0 / dimension if (is.function(set_parameters)) set_parameters(r) x <- sample(c(0, 1), dimension, TRUE) xopt <- x fopt <- fx <- obj_func(x) budget <- budget - 1 tau <- 0.22 while (budget > 0 && !target_hit()) { lambda_ <- min(lambda_, budget) #ensure budget is not exceeded x_ <- tcrossprod(rep(1, lambda_), x) r_ <- (1.0 / (1 + (1 - r) / r * exp(tau * rnorm(lambda_)))) %*% t(rep(1, dimension)) idx <- matrix(runif(lambda_ * dimension), lambda_, dimension) < r_ x_[idx] <- 1 - x_[idx] if (is.function(set_parameters)) set_parameters(r) f <- obj_func(x_) budget <- budget - lambda_ selected <- which(min(f) == f)[[1]] x <- x_[selected, ] r <- r_[selected, 1] if (f[selected] > fopt) { fopt <- f[selected] xopt <- x } } list(xopt = xopt, fopt = fopt) } #' One-Comma-Lambda Genetic Algorithm with 2-rate self-adaptive mutation rate #' #' A genetic algorithm that controls the mutation rate (strength) using the so-called #' 2-rate self-adaptation mechanism: the mutation rate is based on a parameter r. For #' each generation, half offspring are generated by mutation rate 2r/dim, and half by #' r/2dim. r that the best offspring has been created with will be inherited by #' probability 3/4, the other by 1/4. #' #' @param lambda_ The size of the offspring #' @param budget How many times the objective function can be evaluated #' @param dimension Dimension of search space #' @param obj_func The evaluation function #' @param target_hit Optional, function which enables early stopping if a target value is reached #' @param set_parameters Function to call to store the value of the registered parameters #' #' @export two_rate_GA <- function(dimension, obj_func, target_hit = function() { FALSE }, lambda_ = 2, budget = NULL, set_parameters = NULL){ if (is.null(budget)) budget <- 100*dimension parent <- sample(c(0, 1), dimension, TRUE) best <- parent r <- 2.0 fopt <- obj_func(parent) budget <- budget - 1 if (is.function(set_parameters)) set_parameters(r) while (budget > 0 && !target_hit()) { selected_r <- r; selected_obj <- -Inf for (i in 1:lambda_) { offspring <- parent if (i <= lambda_/2) { mutation_rate = r / 2.0 / dimension; } else{ mutation_rate = 2.0 * r / dimension; } offspring <- mutate(offspring, mutation_rate) v <- obj_func(offspring) if (v >= fopt) { fopt <- v best <- offspring } if (v >= selected_obj) { selected_obj = v selected_r = mutation_rate * dimension; } budget <- budget - 1 if (budget == 0 ) break } parent <- best if (runif(1) > 0.5) { r = selected_r } else{ if (runif(1) > 0.5) { r = r / 2.0 } else{ r = 2.0 * r } } if (r < 2.0) r = 2.0 if (r > dimension / 4.0) r = dimension / 4.0 if (is.function(set_parameters)) set_parameters(r) } list(xopt = best, fopt = fopt) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/gh3.R \name{gh_gists_get} \alias{gh_gists_get} \title{List the authenticated user's gists or if called anonymously, this will} \usage{ gh_gists_get(...) } \arguments{ \item{...}{Additional parameters to pass to \code{\link[gh]{gh}}. See details.} } \description{ return all public gists. } \details{ Additional parameters that can be passed: \describe{ \item{type}{ It takes values in: all, public, private, forks, sources, member. The default is: all} \item{Accept}{Is used to set specified media type. } } }
/man/gh_gists_get.Rd
permissive
ramnathv/gh3
R
false
true
589
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/gh3.R \name{gh_gists_get} \alias{gh_gists_get} \title{List the authenticated user's gists or if called anonymously, this will} \usage{ gh_gists_get(...) } \arguments{ \item{...}{Additional parameters to pass to \code{\link[gh]{gh}}. See details.} } \description{ return all public gists. } \details{ Additional parameters that can be passed: \describe{ \item{type}{ It takes values in: all, public, private, forks, sources, member. The default is: all} \item{Accept}{Is used to set specified media type. } } }
if(!exists("NEI")){ NEI <- readRDS("C:\\Users\\winchesters\\Desktop\\coursera\\exploratory\\summarySCC_PM25.rds") } if(!exists("SCC")){ SCC <- readRDS("C:\\Users\\winchesters\\Desktop\\coursera\\exploratory\\Source_Classification_Code.rds") } TotalEmissionPerYear <- aggregate(Emissions ~ year, NEI,sum) png("Plot1.png") barplot(height = TotalEmissionPerYear$Emissions, names.arg = TotalEmissionPerYear$year, xlab = "years", ylab = expression("Total PM[2.5] multiply by emission"), main = expression("PM[2.5] in different years")) dev.off()
/Plot1.R
no_license
sahil411/Exploratory_analysis2
R
false
false
599
r
if(!exists("NEI")){ NEI <- readRDS("C:\\Users\\winchesters\\Desktop\\coursera\\exploratory\\summarySCC_PM25.rds") } if(!exists("SCC")){ SCC <- readRDS("C:\\Users\\winchesters\\Desktop\\coursera\\exploratory\\Source_Classification_Code.rds") } TotalEmissionPerYear <- aggregate(Emissions ~ year, NEI,sum) png("Plot1.png") barplot(height = TotalEmissionPerYear$Emissions, names.arg = TotalEmissionPerYear$year, xlab = "years", ylab = expression("Total PM[2.5] multiply by emission"), main = expression("PM[2.5] in different years")) dev.off()
#' Simulation of Synthetic Populations for Survey Data #' Considering Auxiliary Information #' #' The production of synthetic datasets has been proposed as a #' statistical disclosure control solution to generate public use #' files out of protected data, and as a tool to #' create ``augmented datasets'' to serve as input for #' micro-simulation models. #' Synthetic data have become an important instrument #' for \emph{ex-ante} assessments of policies' impact. #' The performance and acceptability of such a tool relies #' heavily on the quality of the synthetic populations, #' i.e., on the statistical similarity between the synthetic #' and the true population of interest. #' #' Multiple approaches and tools have been developed to #' generate synthetic data. These approaches can be #' categorized into three main groups: #' synthetic reconstruction, combinatorial optimization, #' and model-based generation. #' #' The package: #' \pkg{simPop} is a user-friendly R-package based on a modular object-oriented concept. #' It provides a highly optimized S4 class implementation #' of various methods, including calibration by iterative #' proportional fitting and simulated annealing, and #' modeling or data fusion by logistic regression. #' #' The following applications further shows the methods and package: #' We firstly demonstrated the use of \pkg{simPop} by creating #' a synthetic population of Austria based on the #' European Statistics of Income and Living Conditions (Alfons et al., 2011) #' including the evaluation of the quality of the generated population. #' In this contribution, the mathematical details of functions \code{simStructure}, \code{simCategorical}, #' \code{simContinuous} and \code{simComponents} are given in detail. #' The disclosure risk of this synthetic population has been evaluated in (Templ and Alfons, 2012) using large-scale simulation studies. #' #' Employer-employee data were created in Templ and Filzmoser (2014) whereby #' the structure of companies and employees are considered. #' #' Finally, the R package \pkg{simPop} is presented in full detail #' in Templ et al. (2017). In this paper - the main reference to this work - #' all functions and the S4 class #' structure of the package are described in detail. For beginners, this paper might be #' the starting point to learn about the methods and package. #' #' #' \tabular{ll}{ Package: \tab simPop\cr Type: \tab Package\cr Version: \tab #' 1.0.0\cr Date: \tab 20017-08-07\cr License: \tab GPL (>= 2) \cr } #' #' @name simPop-package #' @aliases simPop-package simPop #' @docType package #' @author Bernhard Meindl, Matthias Templ, Andreas Alfons, Alexander Kowarik, #' #' Maintainer: Matthias Templ <matthias.templ@@gmail.com> #' @references #' M. Templ, B. Meindl, A. Kowarik, A. Alfons, O. Dupriez (2017) Simulation of Synthetic Populations for Survey Data Considering Auxiliary #' Information. \emph{Journal of Statistical Survey}, \strong{79} (10), 1--38. \doi{10.18637/jss.v079.i10} #' #' A. Alfons, M. Templ (2011) Simulation of close-to-reality population data for household surveys with application to EU-SILC. \emph{Statistical Methods & Applications}, \strong{20} (3), 383--407. doi: 10.1007/s10260-011-0163-2 #' #' M. Templ, P. Filzmoser (2014) Simulation and quality of a synthetic close-to-reality employer-employee population. #' Journal of Applied Statistics, \strong{41} (5), 1053--1072. \doi{10.1080/02664763.2013.859237} #' #' M. Templ, A. Alfons (2012) Disclosure Risk of Synthetic Population Data #' with Application in the Case of EU-SILC. In J Domingo-Ferrer, E Magkos (eds.), #' \emph{Privacy in Statistical Databases}, \strong{6344} of Lecture Notes in Computer Science, 174--186. Springer Verlag, Heidelberg. \doi{10.1007/978-3-642-15838-4_16} #' #' @keywords package #' @examples #' #' ## we use synthetic eusilcS survey sample data #' ## included in the package to simulate a population #' #' ## create the structure #' data(eusilcS) #' \donttest{ #' ## approx. 20 seconds computation time #' inp <- specifyInput(data=eusilcS, hhid="db030", hhsize="hsize", strata="db040", weight="db090") #' ## in the following, nr_cpus are selected automatically #' simPop <- simStructure(data=inp, method="direct", basicHHvars=c("age", "rb090")) #' simPop <- simCategorical(simPop, additional=c("pl030", "pb220a"), method="multinom", nr_cpus=1) #' simPop #' class(simPop) #' regModel = ~rb090+hsize+pl030+pb220a #' #' ## multinomial model with random draws #' eusilcM <- simContinuous(simPop, additional="netIncome", #' regModel = regModel, #' upper=200000, equidist=FALSE, nr_cpus=1) #' class(eusilcM) #' } #' #' ## this is already a basic synthetic population, but #' ## many other functions in the package might now #' ## be used for fine-tuning, adding further variables, #' ## evaluating the quality, adding finer geographical details, #' ## using different methods, calibrating surveys or populations, etc. #' ## -- see Templ et al. (2017) for more details. #' NULL
/R/simPop-package.R
no_license
statistikat/simPop
R
false
false
5,083
r
#' Simulation of Synthetic Populations for Survey Data #' Considering Auxiliary Information #' #' The production of synthetic datasets has been proposed as a #' statistical disclosure control solution to generate public use #' files out of protected data, and as a tool to #' create ``augmented datasets'' to serve as input for #' micro-simulation models. #' Synthetic data have become an important instrument #' for \emph{ex-ante} assessments of policies' impact. #' The performance and acceptability of such a tool relies #' heavily on the quality of the synthetic populations, #' i.e., on the statistical similarity between the synthetic #' and the true population of interest. #' #' Multiple approaches and tools have been developed to #' generate synthetic data. These approaches can be #' categorized into three main groups: #' synthetic reconstruction, combinatorial optimization, #' and model-based generation. #' #' The package: #' \pkg{simPop} is a user-friendly R-package based on a modular object-oriented concept. #' It provides a highly optimized S4 class implementation #' of various methods, including calibration by iterative #' proportional fitting and simulated annealing, and #' modeling or data fusion by logistic regression. #' #' The following applications further shows the methods and package: #' We firstly demonstrated the use of \pkg{simPop} by creating #' a synthetic population of Austria based on the #' European Statistics of Income and Living Conditions (Alfons et al., 2011) #' including the evaluation of the quality of the generated population. #' In this contribution, the mathematical details of functions \code{simStructure}, \code{simCategorical}, #' \code{simContinuous} and \code{simComponents} are given in detail. #' The disclosure risk of this synthetic population has been evaluated in (Templ and Alfons, 2012) using large-scale simulation studies. #' #' Employer-employee data were created in Templ and Filzmoser (2014) whereby #' the structure of companies and employees are considered. #' #' Finally, the R package \pkg{simPop} is presented in full detail #' in Templ et al. (2017). In this paper - the main reference to this work - #' all functions and the S4 class #' structure of the package are described in detail. For beginners, this paper might be #' the starting point to learn about the methods and package. #' #' #' \tabular{ll}{ Package: \tab simPop\cr Type: \tab Package\cr Version: \tab #' 1.0.0\cr Date: \tab 20017-08-07\cr License: \tab GPL (>= 2) \cr } #' #' @name simPop-package #' @aliases simPop-package simPop #' @docType package #' @author Bernhard Meindl, Matthias Templ, Andreas Alfons, Alexander Kowarik, #' #' Maintainer: Matthias Templ <matthias.templ@@gmail.com> #' @references #' M. Templ, B. Meindl, A. Kowarik, A. Alfons, O. Dupriez (2017) Simulation of Synthetic Populations for Survey Data Considering Auxiliary #' Information. \emph{Journal of Statistical Survey}, \strong{79} (10), 1--38. \doi{10.18637/jss.v079.i10} #' #' A. Alfons, M. Templ (2011) Simulation of close-to-reality population data for household surveys with application to EU-SILC. \emph{Statistical Methods & Applications}, \strong{20} (3), 383--407. doi: 10.1007/s10260-011-0163-2 #' #' M. Templ, P. Filzmoser (2014) Simulation and quality of a synthetic close-to-reality employer-employee population. #' Journal of Applied Statistics, \strong{41} (5), 1053--1072. \doi{10.1080/02664763.2013.859237} #' #' M. Templ, A. Alfons (2012) Disclosure Risk of Synthetic Population Data #' with Application in the Case of EU-SILC. In J Domingo-Ferrer, E Magkos (eds.), #' \emph{Privacy in Statistical Databases}, \strong{6344} of Lecture Notes in Computer Science, 174--186. Springer Verlag, Heidelberg. \doi{10.1007/978-3-642-15838-4_16} #' #' @keywords package #' @examples #' #' ## we use synthetic eusilcS survey sample data #' ## included in the package to simulate a population #' #' ## create the structure #' data(eusilcS) #' \donttest{ #' ## approx. 20 seconds computation time #' inp <- specifyInput(data=eusilcS, hhid="db030", hhsize="hsize", strata="db040", weight="db090") #' ## in the following, nr_cpus are selected automatically #' simPop <- simStructure(data=inp, method="direct", basicHHvars=c("age", "rb090")) #' simPop <- simCategorical(simPop, additional=c("pl030", "pb220a"), method="multinom", nr_cpus=1) #' simPop #' class(simPop) #' regModel = ~rb090+hsize+pl030+pb220a #' #' ## multinomial model with random draws #' eusilcM <- simContinuous(simPop, additional="netIncome", #' regModel = regModel, #' upper=200000, equidist=FALSE, nr_cpus=1) #' class(eusilcM) #' } #' #' ## this is already a basic synthetic population, but #' ## many other functions in the package might now #' ## be used for fine-tuning, adding further variables, #' ## evaluating the quality, adding finer geographical details, #' ## using different methods, calibrating surveys or populations, etc. #' ## -- see Templ et al. (2017) for more details. #' NULL
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ggthemes_data.R \docType{data} \name{ggthemes_data} \alias{ggthemes_data} \title{Palette and theme data} \format{A \code{list} object.} \usage{ ggthemes_data } \description{ The \code{ggthemes} environment contains various values used in themes and palettes. This is undocumented and subject to change. } \keyword{datasets}
/man/ggthemes_data.Rd
no_license
d2squared/ggthemes
R
false
true
402
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ggthemes_data.R \docType{data} \name{ggthemes_data} \alias{ggthemes_data} \title{Palette and theme data} \format{A \code{list} object.} \usage{ ggthemes_data } \description{ The \code{ggthemes} environment contains various values used in themes and palettes. This is undocumented and subject to change. } \keyword{datasets}
file <- file('./household_power_consumption.txt') data <- read.table(text = grep("^[1,2]/2/2007",readLines(file),value=TRUE), sep = ';', col.names = c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), na.strings = '?') data$Date <- as.Date(data$Date, format = '%d/%m/%Y') data$DateTime <- as.POSIXct(paste(data$Date, data$Time)) if(!file.exists('figures')) dir.create('figures') png(filename = './figures/plot4.png', width = 480, height = 480, units='px') par(mfrow = c(2, 2)) plot(data$DateTime, data$Global_active_power, xlab = '', ylab = 'Global Active Power (kilowatt)', type = 'l') plot(data$DateTime, data$Voltage, xlab = 'datetime', ylab = 'Voltage', type = 'l') plot(data$DateTime, data$Sub_metering_1, xlab = '', ylab = 'Energy sub metering', type = 'l') lines(data$DateTime, data$Sub_metering_2, col = 'red') lines(data$DateTime, data$Sub_metering_3, col = 'blue') legend('topright', col = c('black', 'red', 'blue'), legend = c('Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3'), lwd = 1) plot(data$DateTime, data$Global_reactive_power, xlab = 'datetime', ylab = 'Global_reactive_power', type = 'l') dev.off()
/plot4.R
no_license
pam-wichit/ExData_Plotting1
R
false
false
1,224
r
file <- file('./household_power_consumption.txt') data <- read.table(text = grep("^[1,2]/2/2007",readLines(file),value=TRUE), sep = ';', col.names = c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), na.strings = '?') data$Date <- as.Date(data$Date, format = '%d/%m/%Y') data$DateTime <- as.POSIXct(paste(data$Date, data$Time)) if(!file.exists('figures')) dir.create('figures') png(filename = './figures/plot4.png', width = 480, height = 480, units='px') par(mfrow = c(2, 2)) plot(data$DateTime, data$Global_active_power, xlab = '', ylab = 'Global Active Power (kilowatt)', type = 'l') plot(data$DateTime, data$Voltage, xlab = 'datetime', ylab = 'Voltage', type = 'l') plot(data$DateTime, data$Sub_metering_1, xlab = '', ylab = 'Energy sub metering', type = 'l') lines(data$DateTime, data$Sub_metering_2, col = 'red') lines(data$DateTime, data$Sub_metering_3, col = 'blue') legend('topright', col = c('black', 'red', 'blue'), legend = c('Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3'), lwd = 1) plot(data$DateTime, data$Global_reactive_power, xlab = 'datetime', ylab = 'Global_reactive_power', type = 'l') dev.off()
#please change the address before excution! Thank You:) data <- read.csv("G:/subjects/statistics and probabilities/HW4/movie_metadata.csv") correctData <- function(data){ data <- na.omit(data) color <- vector("numeric") # assign 1 for colory and assign 0 for black and white to make the comparison possible!:) for(i in 1 : nrow(data)){ if(data[i , "color"] == "Color"){ color <- c(color , 1) } else{ color <- c(color , 0) } } data <- data.frame(color , data$budget, data$num_critic_for_reviews,data$duration,data$director_facebook_likes, data$actor_1_facebook_likes, data$num_voted_users, data$cast_total_facebook_likes, data$num_user_for_reviews,data$imdb_score,data$movie_facebook_likes) return(data) } data <- correctData(data) #part-1 covFinder <- function(data){ covMatrix <- matrix(c(0), nrow = 11, ncol = 11) for(i in 1:11){ for(j in 1:11){ covMatrix[i,j] = cov(data[,i],data[,j]) } } colnames(covMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") rownames(covMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") write.csv(covMatrix, "G:/subjects/statistics and probabilities/HW4/cov_mat.csv") return(covMatrix) } covMatrix <- covFinder(data) View(covMatrix) #part-2 #It can be seen that some features have a the same or opposite mean monotoy with film's success but in this way that if they have # positive/negetive Cov then they have the same/oppsite monotony but because it involves the mean amount , makes it hard to compare # effects of the fatures in success rate so to standardize this comparison (adjusting the scales) and easily comparing factors it's better to use correlations # which is done below: corFinder <- function(data){ corMatrix <- matrix(c(0), nrow = 11, ncol = 11) for(i in 1:11){ for(j in 1:11){ corMatrix[i,j] = cor(data[,i],data[,j]) } } colnames(corMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") rownames(corMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") write.csv(corMatrix, "G:/subjects/statistics and probabilities/HW4/cor_mat.csv") return(corMatrix) } corMatrix <- corFinder(data) View(corMatrix) #as it can be seen in the corMatrix : if we declare success with imdb score then these factors are the most improtant respectively as # can be seen in the corMatrix: #num voted users , duration , num critic for reviews , num user for reviews , movie facebook likes , director facebook likes # cast total facebook likes , actor 1 facebook likes , budget , color # it's clear that actor 1 & budget don;t have so effects! #part-3 names <- c("color" , "budget", "num_critic_for_reviews", "duration", "director_facebook_likes", "actor_1_facebook_likes", "num _voted_users", "cast_total_facebook_likes", "num_user_for_reviews","imdb_score", "movie_facebook_likes") for(i in 1:10){ for(j in (i+1):11){ plot(covMatrix[,i], covMatrix[,j],xlab = names[i], ylab = names[j]) } } names <- c("color" , "budget", "num_critic_for_reviews", "duration", "director_facebook_likes", "actor_1_facebook_likes", "num _voted_users", "cast_total_facebook_likes", "num_user_for_reviews","imdb_score", "movie_facebook_likes") for(i in 1:10){ for(j in (i+1):11){ plot(corMatrix[,i], corMatrix[,j],xlab = names[i], ylab = names[j]) } }
/Assignments/Assignment4/Practical Solution/IMDB.R
no_license
Ashkan-Soleymani98/ProbabilityStatistics---Fall2017-2018
R
false
false
4,061
r
#please change the address before excution! Thank You:) data <- read.csv("G:/subjects/statistics and probabilities/HW4/movie_metadata.csv") correctData <- function(data){ data <- na.omit(data) color <- vector("numeric") # assign 1 for colory and assign 0 for black and white to make the comparison possible!:) for(i in 1 : nrow(data)){ if(data[i , "color"] == "Color"){ color <- c(color , 1) } else{ color <- c(color , 0) } } data <- data.frame(color , data$budget, data$num_critic_for_reviews,data$duration,data$director_facebook_likes, data$actor_1_facebook_likes, data$num_voted_users, data$cast_total_facebook_likes, data$num_user_for_reviews,data$imdb_score,data$movie_facebook_likes) return(data) } data <- correctData(data) #part-1 covFinder <- function(data){ covMatrix <- matrix(c(0), nrow = 11, ncol = 11) for(i in 1:11){ for(j in 1:11){ covMatrix[i,j] = cov(data[,i],data[,j]) } } colnames(covMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") rownames(covMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") write.csv(covMatrix, "G:/subjects/statistics and probabilities/HW4/cov_mat.csv") return(covMatrix) } covMatrix <- covFinder(data) View(covMatrix) #part-2 #It can be seen that some features have a the same or opposite mean monotoy with film's success but in this way that if they have # positive/negetive Cov then they have the same/oppsite monotony but because it involves the mean amount , makes it hard to compare # effects of the fatures in success rate so to standardize this comparison (adjusting the scales) and easily comparing factors it's better to use correlations # which is done below: corFinder <- function(data){ corMatrix <- matrix(c(0), nrow = 11, ncol = 11) for(i in 1:11){ for(j in 1:11){ corMatrix[i,j] = cor(data[,i],data[,j]) } } colnames(corMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") rownames(corMatrix) <- c("color" , "budget", "num critic for reviews", "duration", "director facebook likes", "actor 1 facebook likes", "num voted users", "cast total facebook likes", "num user for reviews","imdb score", "movie facebook likes") write.csv(corMatrix, "G:/subjects/statistics and probabilities/HW4/cor_mat.csv") return(corMatrix) } corMatrix <- corFinder(data) View(corMatrix) #as it can be seen in the corMatrix : if we declare success with imdb score then these factors are the most improtant respectively as # can be seen in the corMatrix: #num voted users , duration , num critic for reviews , num user for reviews , movie facebook likes , director facebook likes # cast total facebook likes , actor 1 facebook likes , budget , color # it's clear that actor 1 & budget don;t have so effects! #part-3 names <- c("color" , "budget", "num_critic_for_reviews", "duration", "director_facebook_likes", "actor_1_facebook_likes", "num _voted_users", "cast_total_facebook_likes", "num_user_for_reviews","imdb_score", "movie_facebook_likes") for(i in 1:10){ for(j in (i+1):11){ plot(covMatrix[,i], covMatrix[,j],xlab = names[i], ylab = names[j]) } } names <- c("color" , "budget", "num_critic_for_reviews", "duration", "director_facebook_likes", "actor_1_facebook_likes", "num _voted_users", "cast_total_facebook_likes", "num_user_for_reviews","imdb_score", "movie_facebook_likes") for(i in 1:10){ for(j in (i+1):11){ plot(corMatrix[,i], corMatrix[,j],xlab = names[i], ylab = names[j]) } }
library(ape) testtree <- read.tree("2999_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="2999_0_unrooted.txt")
/codeml_files/newick_trees_processed/2999_0/rinput.R
no_license
DaniBoo/cyanobacteria_project
R
false
false
135
r
library(ape) testtree <- read.tree("2999_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="2999_0_unrooted.txt")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fun.list.rw.R \name{make.robust} \alias{make.robust} \title{Add a vague componenet to mixture model to make robust} \usage{ make.robust(object, weight) } \arguments{ \item{object}{mixture.prior to update} \item{weight}{weight of vague component in updated model} } \value{ A \code{mixture.prior} object with updated weights and parameters } \description{ Add a vague componenet to mixture model to make robust }
/StudyPrior/man/make.robust.Rd
no_license
igrave/StudyPrior
R
false
true
491
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fun.list.rw.R \name{make.robust} \alias{make.robust} \title{Add a vague componenet to mixture model to make robust} \usage{ make.robust(object, weight) } \arguments{ \item{object}{mixture.prior to update} \item{weight}{weight of vague component in updated model} } \value{ A \code{mixture.prior} object with updated weights and parameters } \description{ Add a vague componenet to mixture model to make robust }
# Required data ---------------------------------------------------------------------------------------------------------------------- data("dataHigherMoments") # Formula transformations ------------------------------------------------------------------------------------------------------------ context("Correctness - higherMomentsIV - Formula transformations") # Data sorting ----------------------------------------------------------------------------------------------------------------------- context("Correctness - higherMomentsIV - Data sorting") test_that("Differently sorted data produces same results", { data.altered <- dataHigherMoments data.altered[sample(nrow(data.altered), nrow(data.altered), replace = FALSE), ] expect_silent(res.orig <- higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data=dataHigherMoments, verbose=FALSE)) expect_silent(res.diff.sorted <- higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data=data.altered, verbose=FALSE)) expect_equal(coef(res.orig), coef(res.diff.sorted)) expect_equal(coef(summary(res.orig)), coef(summary(res.diff.sorted))) }) # Predict ---------------------------------------------------------------------------------------------------------------------------- context("Correctness - higherMomentsIV - Predict") test_that("No newdata results in fitted values", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1), fitted(higher.1)) expect_silent(higher.2 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2) + IIV(iiv=yp) + IIV(iiv=g,g=x3,X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.2), fitted(higher.2)) }) test_that("Same prediction data as for fitting results in fitted values", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), fitted(higher.1)) expect_silent(higher.2 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2) + IIV(iiv=yp) + IIV(iiv=g,g=x3,X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.2, newdata=dataHigherMoments), fitted(higher.2)) }) test_that("Same results as ivreg with useless iiv dummies", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), AER:::predict.ivreg(higher.1, newdata = cbind(dataHigherMoments,IIV.isgp.gisx2.regisX1=-11))) expect_silent(higher.2 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2) + IIV(iiv=yp) + IIV(iiv=g,g=x3,X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.2, newdata=dataHigherMoments), AER:::predict.ivreg(higher.2, newdata = cbind(dataHigherMoments,IIV.isy2=1.23, IIV.isyp=2.34, IIV.isg.gisx3.regisX1=3.45))) }) test_that("Correct structure of predictions", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_silent(pred.1 <- predict(higher.1, dataHigherMoments)) expect_true(is.numeric(pred.1)) expect_true(length(pred.1) == nrow(dataHigherMoments)) expect_true(all(names(pred.1) == names(fitted(higher.1)))) expect_true(all(names(pred.1) == rownames(dataHigherMoments))) }) test_that("Correct when using transformations in the formula", { # transformation in regressor expect_silent(higher.1 <- higherMomentsIV(y~I((X1+1)/2)+X2+P|P|IIV(iiv=gp, g=x2, I((X1+1)/2)), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), fitted(higher.1)) # transformation in endogenous expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+I((P+14)/3)|I((P+14)/3)|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), fitted(higher.1)) }) # ** iiv built correctly
/tests/testthat/test-correctness_highermoments.R
no_license
mmeierer/REndo
R
false
false
4,104
r
# Required data ---------------------------------------------------------------------------------------------------------------------- data("dataHigherMoments") # Formula transformations ------------------------------------------------------------------------------------------------------------ context("Correctness - higherMomentsIV - Formula transformations") # Data sorting ----------------------------------------------------------------------------------------------------------------------- context("Correctness - higherMomentsIV - Data sorting") test_that("Differently sorted data produces same results", { data.altered <- dataHigherMoments data.altered[sample(nrow(data.altered), nrow(data.altered), replace = FALSE), ] expect_silent(res.orig <- higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data=dataHigherMoments, verbose=FALSE)) expect_silent(res.diff.sorted <- higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data=data.altered, verbose=FALSE)) expect_equal(coef(res.orig), coef(res.diff.sorted)) expect_equal(coef(summary(res.orig)), coef(summary(res.diff.sorted))) }) # Predict ---------------------------------------------------------------------------------------------------------------------------- context("Correctness - higherMomentsIV - Predict") test_that("No newdata results in fitted values", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1), fitted(higher.1)) expect_silent(higher.2 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2) + IIV(iiv=yp) + IIV(iiv=g,g=x3,X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.2), fitted(higher.2)) }) test_that("Same prediction data as for fitting results in fitted values", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), fitted(higher.1)) expect_silent(higher.2 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2) + IIV(iiv=yp) + IIV(iiv=g,g=x3,X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.2, newdata=dataHigherMoments), fitted(higher.2)) }) test_that("Same results as ivreg with useless iiv dummies", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), AER:::predict.ivreg(higher.1, newdata = cbind(dataHigherMoments,IIV.isgp.gisx2.regisX1=-11))) expect_silent(higher.2 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2) + IIV(iiv=yp) + IIV(iiv=g,g=x3,X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.2, newdata=dataHigherMoments), AER:::predict.ivreg(higher.2, newdata = cbind(dataHigherMoments,IIV.isy2=1.23, IIV.isyp=2.34, IIV.isg.gisx3.regisX1=3.45))) }) test_that("Correct structure of predictions", { expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_silent(pred.1 <- predict(higher.1, dataHigherMoments)) expect_true(is.numeric(pred.1)) expect_true(length(pred.1) == nrow(dataHigherMoments)) expect_true(all(names(pred.1) == names(fitted(higher.1)))) expect_true(all(names(pred.1) == rownames(dataHigherMoments))) }) test_that("Correct when using transformations in the formula", { # transformation in regressor expect_silent(higher.1 <- higherMomentsIV(y~I((X1+1)/2)+X2+P|P|IIV(iiv=gp, g=x2, I((X1+1)/2)), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), fitted(higher.1)) # transformation in endogenous expect_silent(higher.1 <- higherMomentsIV(y~X1+X2+I((P+14)/3)|I((P+14)/3)|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments, verbose=FALSE)) expect_equal(predict(higher.1, newdata=dataHigherMoments), fitted(higher.1)) }) # ** iiv built correctly
M = cor(mtcars) (order.AOE = corrMatOrder(M, order = 'AOE')) (order.FPC = corrMatOrder(M, order = 'FPC')) (order.hc = corrMatOrder(M, order = 'hclust')) (order.hc2 = corrMatOrder(M, order = 'hclust', hclust.method = 'ward.D')) M.AOE = M[order.AOE,order.AOE] M.FPC = M[order.FPC,order.FPC] M.hc = M[order.hc, order.hc] M.hc2 = M[order.hc2,order.hc2] par(ask = TRUE) corrplot(M) corrplot(M.AOE) corrplot(M.FPC) corrplot(M.hc) corrplot(M.hc) corrRect.hclust(corr = M.hc, k = 2) corrplot(M.hc) corrRect.hclust(corr = M.hc, k = 3) corrplot(M.hc2) corrRect.hclust(M.hc2, k = 2, method = 'ward.D')
/vignettes/example-corrMatOrder.R
permissive
ZhangYet/corrplot
R
false
false
600
r
M = cor(mtcars) (order.AOE = corrMatOrder(M, order = 'AOE')) (order.FPC = corrMatOrder(M, order = 'FPC')) (order.hc = corrMatOrder(M, order = 'hclust')) (order.hc2 = corrMatOrder(M, order = 'hclust', hclust.method = 'ward.D')) M.AOE = M[order.AOE,order.AOE] M.FPC = M[order.FPC,order.FPC] M.hc = M[order.hc, order.hc] M.hc2 = M[order.hc2,order.hc2] par(ask = TRUE) corrplot(M) corrplot(M.AOE) corrplot(M.FPC) corrplot(M.hc) corrplot(M.hc) corrRect.hclust(corr = M.hc, k = 2) corrplot(M.hc) corrRect.hclust(corr = M.hc, k = 3) corrplot(M.hc2) corrRect.hclust(M.hc2, k = 2, method = 'ward.D')
# # test filtering via factors # setwd(normalizePath(dirname(R.utils::commandArgs(asValues=TRUE)$"f"))) source('../h2o-runit.R') factorfilter <- function(conn){ Log.info('uploading ddply testing dataset') df.h <- h2o.importFile(conn, normalizePath(locate('smalldata/jira/pub-180.csv'))) Log.info('printing from h2o') Log.info( head(df.h) ) Log.info('subsetting via factor') df.h.1 <- df.h[ df.h$colgroup == 'a', ] expect_that( dim(df.h.1), equals(c(3,4) )) df.h.2 <- df.h[ df.h[,2] == "group2", ] expect_that( dim(df.h.2), equals(c(2, 4) )) df.h.3 <- df.h[ df.h[,2] == 'group1' & df.h$colgroup == 'c', ] expect_that( dim(df.h.3), equals( c(1,4) )) Log.info('localizing') df.1 <- as.data.frame(df.h.1) df.2 <- as.data.frame(df.h.2) df.3 <- as.data.frame(df.h.3) Log.info('testing') expect_that( dim(df.1), equals(c(3, 4) )) checkTrue( unique( df.1[,1] ) == 'a' && unique(df.1[,2]) == 'group1') checkTrue(all( df.1[,3] == c(1,2,1) )) checkTrue(all( df.1[,4] == c(2,3,2) )) expect_that( dim(df.2), equals(c(2, 4) )) expect_that( unique( df.2[,1] ), equals(factor('c'))) expect_that(unique(df.2[,2]), equals(factor('group2'))) checkTrue(all( df.2[,3] == c(5,5) )) checkTrue(all( df.2[,4] == c(6,6) )) expect_that( dim(df.3), equals( c(1, 4) )) expect_that( df.3[1,1], equals( factor('c'))) expect_that(df.3[1,2], equals(factor('group1' ))) expect_that( df.3[1,3], equals(5 )) expect_that( df.3[1,4], equals(6 )) testEnd() } if(F){ # R code that does the same as above data <- read.csv(locate('smalldata/jira/pub-180.csv'), header=T) data[ data$colgroup == 'a', ] data[ data[,2] == 'group2', ] data[ data[,2] == 'group1' & data$colgroup == 'c', ] } doTest('factor filtering', factorfilter)
/h2o-r/tests/testdir_jira/runit_pub_168_dfpredicates.R
permissive
mrgloom/h2o-3
R
false
false
1,780
r
# # test filtering via factors # setwd(normalizePath(dirname(R.utils::commandArgs(asValues=TRUE)$"f"))) source('../h2o-runit.R') factorfilter <- function(conn){ Log.info('uploading ddply testing dataset') df.h <- h2o.importFile(conn, normalizePath(locate('smalldata/jira/pub-180.csv'))) Log.info('printing from h2o') Log.info( head(df.h) ) Log.info('subsetting via factor') df.h.1 <- df.h[ df.h$colgroup == 'a', ] expect_that( dim(df.h.1), equals(c(3,4) )) df.h.2 <- df.h[ df.h[,2] == "group2", ] expect_that( dim(df.h.2), equals(c(2, 4) )) df.h.3 <- df.h[ df.h[,2] == 'group1' & df.h$colgroup == 'c', ] expect_that( dim(df.h.3), equals( c(1,4) )) Log.info('localizing') df.1 <- as.data.frame(df.h.1) df.2 <- as.data.frame(df.h.2) df.3 <- as.data.frame(df.h.3) Log.info('testing') expect_that( dim(df.1), equals(c(3, 4) )) checkTrue( unique( df.1[,1] ) == 'a' && unique(df.1[,2]) == 'group1') checkTrue(all( df.1[,3] == c(1,2,1) )) checkTrue(all( df.1[,4] == c(2,3,2) )) expect_that( dim(df.2), equals(c(2, 4) )) expect_that( unique( df.2[,1] ), equals(factor('c'))) expect_that(unique(df.2[,2]), equals(factor('group2'))) checkTrue(all( df.2[,3] == c(5,5) )) checkTrue(all( df.2[,4] == c(6,6) )) expect_that( dim(df.3), equals( c(1, 4) )) expect_that( df.3[1,1], equals( factor('c'))) expect_that(df.3[1,2], equals(factor('group1' ))) expect_that( df.3[1,3], equals(5 )) expect_that( df.3[1,4], equals(6 )) testEnd() } if(F){ # R code that does the same as above data <- read.csv(locate('smalldata/jira/pub-180.csv'), header=T) data[ data$colgroup == 'a', ] data[ data[,2] == 'group2', ] data[ data[,2] == 'group1' & data$colgroup == 'c', ] } doTest('factor filtering', factorfilter)
library(ape) testtree <- read.tree("3924_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="3924_0_unrooted.txt")
/codeml_files/newick_trees_processed/3924_0/rinput.R
no_license
DaniBoo/cyanobacteria_project
R
false
false
135
r
library(ape) testtree <- read.tree("3924_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="3924_0_unrooted.txt")
#A script to calculate similarity scores for gene expression library(proxy) setwd('Documents/public-datasets/TCGA/expressionData/Expression-Genes/UNC__AgilentG4502A_07_1/') source('~/Documents/Rscripts/120518-initialize.R') geneMatrix = read.delim('~/Documents/public-datasets/TCGA/expressionData/Expression-Genes/UNC__AgilentG4502A_07_1/120814-CREBexpressionMatrixSorted.txt') row.names(geneMatrix) = geneMatrix$genes geneMatrix = geneMatrix[,2:92] #Get the summary stats for the matrix stats = summary(geneMatrix) #In excel get the upper and lower quartiles and put into a vector for the CREB signature. Order alphabetically sig = read.delim('120813-CREBsignatureSorted.txt', header=FALSE) signature = as.matrix(sig$V2) row.names(signature) = sig$V1 #generate the distance matrix. Make sure that the order of genes in the expression matrix and signature are the same! distanceMatrix = function(geneExpressionMatrix, GeneSignature) { index = 1 distanceMatrix = geneExpressionMatrix[,,] while (index <= length(geneExpressionMatrix)) { distanceMatrix[,index] = dist(geneExpressionMatrix[,index], GeneSignature, by_rows=FALSE, pairwise=TRUE) #distance measure index = index + 1 } return (distanceMatrix) } similarityMatrix = function(geneExpressionMatrix, GeneSignature) { index = 1 distanceMatrix = geneExpressionMatrix[,,] while (index <= length(geneExpressionMatrix)) { distanceMatrix[,index] = simil(geneExpressionMatrix[,index], GeneSignature, pairwise=TRUE, by_rows=FALSE) #similarity measure index = index + 1 } return (distanceMatrix) } #Obtain the column sum and mean for the distance matrix meanDistance = colMeans(distanceMatrix) sumDistance = colSums(distanceMatrix) hist(sumDistance, xlim=c(10, 40), breaks='Scott', freq=T, xlab='Sum distance from CREB signature', ylab='Frequency', main='TCGA Agilent 1 sample similarity to 38 gene CREB signature', col='blue') distanceSummary = summary(sumDistance) #bind the survival data to the colSum similarity data survival = read.delim('~/Documents/public-datasets/TCGA/clinicalData/120731-survivalDataStructered.txt') sur = survival[,c(4,5)] distPaitents = colnames(distanceMatrix) sur1 = sur[distPaitents,]
/PhD/120813-GeneExpressionSignature.R
no_license
dvbrown/Rscripts
R
false
false
2,203
r
#A script to calculate similarity scores for gene expression library(proxy) setwd('Documents/public-datasets/TCGA/expressionData/Expression-Genes/UNC__AgilentG4502A_07_1/') source('~/Documents/Rscripts/120518-initialize.R') geneMatrix = read.delim('~/Documents/public-datasets/TCGA/expressionData/Expression-Genes/UNC__AgilentG4502A_07_1/120814-CREBexpressionMatrixSorted.txt') row.names(geneMatrix) = geneMatrix$genes geneMatrix = geneMatrix[,2:92] #Get the summary stats for the matrix stats = summary(geneMatrix) #In excel get the upper and lower quartiles and put into a vector for the CREB signature. Order alphabetically sig = read.delim('120813-CREBsignatureSorted.txt', header=FALSE) signature = as.matrix(sig$V2) row.names(signature) = sig$V1 #generate the distance matrix. Make sure that the order of genes in the expression matrix and signature are the same! distanceMatrix = function(geneExpressionMatrix, GeneSignature) { index = 1 distanceMatrix = geneExpressionMatrix[,,] while (index <= length(geneExpressionMatrix)) { distanceMatrix[,index] = dist(geneExpressionMatrix[,index], GeneSignature, by_rows=FALSE, pairwise=TRUE) #distance measure index = index + 1 } return (distanceMatrix) } similarityMatrix = function(geneExpressionMatrix, GeneSignature) { index = 1 distanceMatrix = geneExpressionMatrix[,,] while (index <= length(geneExpressionMatrix)) { distanceMatrix[,index] = simil(geneExpressionMatrix[,index], GeneSignature, pairwise=TRUE, by_rows=FALSE) #similarity measure index = index + 1 } return (distanceMatrix) } #Obtain the column sum and mean for the distance matrix meanDistance = colMeans(distanceMatrix) sumDistance = colSums(distanceMatrix) hist(sumDistance, xlim=c(10, 40), breaks='Scott', freq=T, xlab='Sum distance from CREB signature', ylab='Frequency', main='TCGA Agilent 1 sample similarity to 38 gene CREB signature', col='blue') distanceSummary = summary(sumDistance) #bind the survival data to the colSum similarity data survival = read.delim('~/Documents/public-datasets/TCGA/clinicalData/120731-survivalDataStructered.txt') sur = survival[,c(4,5)] distPaitents = colnames(distanceMatrix) sur1 = sur[distPaitents,]
rm(list=ls()) library(MASS) library(far) # remotes::install_github("isglobal-brge/mgcca") library(curatedTCGAData) library(TCGAutils) # Libraries needed by mgcca package library(MultiAssayExperiment) library(RSpectra) library(impute) # Benchmark library(microbenchmark) library(mgcca) fsim <- function(n, p, q, prop.miss, ncomp, ncomp.true, sigma.noise, difer){ # n <- 100 # p <- 5 # q <- 5 # prop.miss <- 0.1 # ncomp <- 2 # sigma.noise <- 0.001 # ncomp.true <- 2 # difer <- 1 # n = number of individuals # p = number of variables in X matrix # q = number of variables in Y matrix # prop.miss= proportion of missing values # ncomp = number of correlation functions # sigma.noise = sigma of noise added to Xi. # ncomp.true = number of true canonical variables. # ... = arguments passed to mgcc function (currently ignored) if (p>n | q>n) stop("number of individuals must be larger than the number of variables") if (n%%2!=0) stop("n must be pair") # simulate data (as in "Generalized canonical correlation analysis of matrices with missing rows: A simulation study" paper) # note: we add noise to X1 instead of Y, if noise is added to Ytrue as specified in paper var(Xi) is not singular!!! Ysim <- matrix(rnorm(n*ncomp.true), n, ncomp.true) # simulate from a standard normal variables group <- rep(1:2, each=n/2) names(group) <- 1:n Ysim[group==1,] <- Ysim[group==1,]+difer/2 Ysim[group==2,] <- Ysim[group==2,]-difer/2 # plot(Ysim, col=rep(1:2, each=n/2)) Ytrue <- Ysim pval.true <- anova(manova(Ytrue ~ group))[2,6] b1 <- matrix(runif(ncomp.true*p,-1,1), ncomp.true, p) X1 <- Ytrue%*%b1 + matrix(rnorm(n*p, 0, sigma.noise), n, p) # add noise to X1 instead of Y!!! b2 <- matrix(runif(ncomp.true*q,-1,1), ncomp.true, q) X2 <- Ytrue%*%b2 + matrix(rnorm(n*q, 0, sigma.noise), n, q) # add noise to X2 instead of Y!!! rownames(X1) <- rownames(X2) <- 1:n X<-Xori <- list(X1,X2) ####### introduce individuals missings at random n<- nrow(X[[1]]) Xmiss <- Xori k <- length(Xmiss) which.miss.prev <- integer() for (i in 1:k){ Xi <- X[[i]] n <- nrow(Xi) p <- ncol(Xi) which.miss.i <- sample(1:n,round(prop.miss*n)) which.miss.i <- which.miss.i[!which.miss.i%in%which.miss.prev] if (length(which.miss.i)>0) Xi[which.miss.i,] <- NA Xmiss[[i]] <- Xi which.miss.prev <- which.miss.i } ## average imputation Ximp <- lapply(Xmiss, function(Xi){ apply(Xi,2, function(xx){ m <- mean(xx,na.rm=TRUE) ifelse(is.na(xx), m , xx) }) }) #### fit mgcc to different methods ## gold (all cases) resultAll <- mgcca(Xori, nfac = ncomp, scores=TRUE) #plot(resultAll$Y, col=rep(1:2, each=n/2)) pval.all <- anova(manova(resultAll$Y ~ group))[2,6] ## average imputation resultImp <- mgcca(Ximp, nfac = ncomp, scores=TRUE) pval.imp <- anova(manova(resultImp$Y ~ group))[2,6] ## complete cases common <- Reduce(intersect,lapply(lapply(Xmiss, na.omit),rownames)) Xcommon <- lapply(Xmiss, function(xi) xi[common,,drop=FALSE]) resultCommon <- mgcca(Xcommon, nfac = ncomp, scores=TRUE) #cat("n common=", nrow(Xcommon[[1]]),"\n") # number of individuals with complete data pval.common <- anova(manova(resultCommon$Y ~ group[common]))[2,6] ## mcca Xr <- lapply(Xmiss, na.omit) resultMGCCA <- mgcca(Xr, nfac = ncomp, scores=TRUE) pval.mgcca <- anova(manova(resultMGCCA$Y ~ group))[2,6] c(pval.true, pval.all, pval.imp, pval.common, pval.mgcca) } #replicate(4,fsim(n=500, p=50, q=50, prop.miss=0.2, ncomp=2, ncomp.true=2, sigma.noise=0.2, difer=0.5)) ## fixed parameters n <- 500 ncomp <- 2 ncomp.true <- 2 nsim <- 100 vars <- 50 sigma.noise <- 0.2 nsim <- 1000 ## variable parameters esc <- expand.grid(difer=c(0, 0.25, 0.5), prop.miss=c(0.1,0.2,0.3)) res <- list() set.seed(123456) for (i in 1:nrow(esc)){ cat("----Escenari",i,"\n-difer=",esc$difer[i],"\n-prop.miss=",esc$prop.miss[i],"\n\n") iter <- 0 res[[i]] <- replicate(nsim,{ iter <<- iter+1 if (iter%%10==0) cat("iteration",iter,"\n") res <- try(fsim(n, p=vars, q=vars, prop.miss=esc$prop.miss[i], ncomp, ncomp.true, sigma.noise=sigma.noise, difer=esc$difer[i]), silent=TRUE) if (inherits(res, "try-error")) return(c(NA,NA,NA)) else return(res) }) cat("\n\n\n") } save(res, file="sim2res.rda")
/simulations/case2/simulate2.R
permissive
isglobal-brge/paperGCCA
R
false
false
4,361
r
rm(list=ls()) library(MASS) library(far) # remotes::install_github("isglobal-brge/mgcca") library(curatedTCGAData) library(TCGAutils) # Libraries needed by mgcca package library(MultiAssayExperiment) library(RSpectra) library(impute) # Benchmark library(microbenchmark) library(mgcca) fsim <- function(n, p, q, prop.miss, ncomp, ncomp.true, sigma.noise, difer){ # n <- 100 # p <- 5 # q <- 5 # prop.miss <- 0.1 # ncomp <- 2 # sigma.noise <- 0.001 # ncomp.true <- 2 # difer <- 1 # n = number of individuals # p = number of variables in X matrix # q = number of variables in Y matrix # prop.miss= proportion of missing values # ncomp = number of correlation functions # sigma.noise = sigma of noise added to Xi. # ncomp.true = number of true canonical variables. # ... = arguments passed to mgcc function (currently ignored) if (p>n | q>n) stop("number of individuals must be larger than the number of variables") if (n%%2!=0) stop("n must be pair") # simulate data (as in "Generalized canonical correlation analysis of matrices with missing rows: A simulation study" paper) # note: we add noise to X1 instead of Y, if noise is added to Ytrue as specified in paper var(Xi) is not singular!!! Ysim <- matrix(rnorm(n*ncomp.true), n, ncomp.true) # simulate from a standard normal variables group <- rep(1:2, each=n/2) names(group) <- 1:n Ysim[group==1,] <- Ysim[group==1,]+difer/2 Ysim[group==2,] <- Ysim[group==2,]-difer/2 # plot(Ysim, col=rep(1:2, each=n/2)) Ytrue <- Ysim pval.true <- anova(manova(Ytrue ~ group))[2,6] b1 <- matrix(runif(ncomp.true*p,-1,1), ncomp.true, p) X1 <- Ytrue%*%b1 + matrix(rnorm(n*p, 0, sigma.noise), n, p) # add noise to X1 instead of Y!!! b2 <- matrix(runif(ncomp.true*q,-1,1), ncomp.true, q) X2 <- Ytrue%*%b2 + matrix(rnorm(n*q, 0, sigma.noise), n, q) # add noise to X2 instead of Y!!! rownames(X1) <- rownames(X2) <- 1:n X<-Xori <- list(X1,X2) ####### introduce individuals missings at random n<- nrow(X[[1]]) Xmiss <- Xori k <- length(Xmiss) which.miss.prev <- integer() for (i in 1:k){ Xi <- X[[i]] n <- nrow(Xi) p <- ncol(Xi) which.miss.i <- sample(1:n,round(prop.miss*n)) which.miss.i <- which.miss.i[!which.miss.i%in%which.miss.prev] if (length(which.miss.i)>0) Xi[which.miss.i,] <- NA Xmiss[[i]] <- Xi which.miss.prev <- which.miss.i } ## average imputation Ximp <- lapply(Xmiss, function(Xi){ apply(Xi,2, function(xx){ m <- mean(xx,na.rm=TRUE) ifelse(is.na(xx), m , xx) }) }) #### fit mgcc to different methods ## gold (all cases) resultAll <- mgcca(Xori, nfac = ncomp, scores=TRUE) #plot(resultAll$Y, col=rep(1:2, each=n/2)) pval.all <- anova(manova(resultAll$Y ~ group))[2,6] ## average imputation resultImp <- mgcca(Ximp, nfac = ncomp, scores=TRUE) pval.imp <- anova(manova(resultImp$Y ~ group))[2,6] ## complete cases common <- Reduce(intersect,lapply(lapply(Xmiss, na.omit),rownames)) Xcommon <- lapply(Xmiss, function(xi) xi[common,,drop=FALSE]) resultCommon <- mgcca(Xcommon, nfac = ncomp, scores=TRUE) #cat("n common=", nrow(Xcommon[[1]]),"\n") # number of individuals with complete data pval.common <- anova(manova(resultCommon$Y ~ group[common]))[2,6] ## mcca Xr <- lapply(Xmiss, na.omit) resultMGCCA <- mgcca(Xr, nfac = ncomp, scores=TRUE) pval.mgcca <- anova(manova(resultMGCCA$Y ~ group))[2,6] c(pval.true, pval.all, pval.imp, pval.common, pval.mgcca) } #replicate(4,fsim(n=500, p=50, q=50, prop.miss=0.2, ncomp=2, ncomp.true=2, sigma.noise=0.2, difer=0.5)) ## fixed parameters n <- 500 ncomp <- 2 ncomp.true <- 2 nsim <- 100 vars <- 50 sigma.noise <- 0.2 nsim <- 1000 ## variable parameters esc <- expand.grid(difer=c(0, 0.25, 0.5), prop.miss=c(0.1,0.2,0.3)) res <- list() set.seed(123456) for (i in 1:nrow(esc)){ cat("----Escenari",i,"\n-difer=",esc$difer[i],"\n-prop.miss=",esc$prop.miss[i],"\n\n") iter <- 0 res[[i]] <- replicate(nsim,{ iter <<- iter+1 if (iter%%10==0) cat("iteration",iter,"\n") res <- try(fsim(n, p=vars, q=vars, prop.miss=esc$prop.miss[i], ncomp, ncomp.true, sigma.noise=sigma.noise, difer=esc$difer[i]), silent=TRUE) if (inherits(res, "try-error")) return(c(NA,NA,NA)) else return(res) }) cat("\n\n\n") } save(res, file="sim2res.rda")
if(getRversion() >= "3.1.0") { utils::globalVariables( c( '.', 'loc_lat', 'loc_lng', 'stop_id', 'stop_lat', 'stop_lon', 'stop_name', 'trip_id' ) ) }
/R/globals.R
no_license
r-transit/transitfeedr
R
false
false
208
r
if(getRversion() >= "3.1.0") { utils::globalVariables( c( '.', 'loc_lat', 'loc_lng', 'stop_id', 'stop_lat', 'stop_lon', 'stop_name', 'trip_id' ) ) }
library(dplyr) library(ggplot2) #to set outputs in english Sys.setlocale("LC_ALL", "en_US") #reading in temp file temp <- tempfile() download.file("https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip", temp) data <- read.csv(unz(temp, "activity.csv"), stringsAsFactors = F) data$date <- as.Date(data$date) daily_steps <- data %>% group_by(date) %>% summarise(total_daily_steps = sum(steps)) #What is mean total number of steps taken per day? #histogram ggplot(daily_steps, aes(x = total_daily_steps)) + geom_histogram() #mean and median of steps each day mean(daily_steps$total_daily_steps, na.rm = T) median(daily_steps$total_daily_steps, na.rm = T) #What is the average daily activity pattern? #mean steps by interval + time series mean_per_interval <- data %>% group_by(interval) %>% summarise(mean = mean(steps, na.rm = T)) ggplot(mean_per_interval, aes(x = interval, y = mean)) + geom_line() #interval wth mean highest number of steps mean_per_interval %>% filter(mean == max(mean)) ###Imputing missing values #total number os NAs summary(data) #filling missing values no_missing <- transform(data, steps = ifelse(is.na(steps), )) data2 <- data x <- data.frame(0,0,0,0) for(i in 1:nrow(data2)) { if(is.na(data2[i,1] == T)) { x <- left_join(data2[i,], mean_per_interval, by = 'interval') data2[i,1] <- x[,4] } } #histogram of data2 - with no missing daily_steps2 <- data2 %>% group_by(date) %>% summarise(total_daily_steps = sum(steps)) #histogram ggplot(daily_steps2, aes(x = total_daily_steps)) + geom_histogram() #mean and median of steps each day mean(daily_steps2$total_daily_steps, na.rm = T) median(daily_steps2$total_daily_steps, na.rm = T) #we can see that the mean and median values have no changed for #the overall data set, but now we have a more complete dataset mean(data$steps, na.rm = T) mean(data2$steps) ###Are there differences in activity patterns between weekdays and weekends? data2 <- data2 %>% mutate(weekday = weekdays(date), day_of_week = ifelse(weekday == "Saturday" | weekday == "Sunday", "weekend", "weekday")) data2$day_of_week <- as.factor(data2$day_of_week) mean_per_interval2 <- data2 %>% group_by(interval, day_of_week) %>% summarise(mean = mean(steps, na.rm = T)) ##panel plot ggplot(mean_per_interval2, aes(x = interval, y = mean)) + geom_line() + facet_grid( day_of_week ~ .)
/PA1_script.R
no_license
andreluna15/reproducible_research
R
false
false
2,395
r
library(dplyr) library(ggplot2) #to set outputs in english Sys.setlocale("LC_ALL", "en_US") #reading in temp file temp <- tempfile() download.file("https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip", temp) data <- read.csv(unz(temp, "activity.csv"), stringsAsFactors = F) data$date <- as.Date(data$date) daily_steps <- data %>% group_by(date) %>% summarise(total_daily_steps = sum(steps)) #What is mean total number of steps taken per day? #histogram ggplot(daily_steps, aes(x = total_daily_steps)) + geom_histogram() #mean and median of steps each day mean(daily_steps$total_daily_steps, na.rm = T) median(daily_steps$total_daily_steps, na.rm = T) #What is the average daily activity pattern? #mean steps by interval + time series mean_per_interval <- data %>% group_by(interval) %>% summarise(mean = mean(steps, na.rm = T)) ggplot(mean_per_interval, aes(x = interval, y = mean)) + geom_line() #interval wth mean highest number of steps mean_per_interval %>% filter(mean == max(mean)) ###Imputing missing values #total number os NAs summary(data) #filling missing values no_missing <- transform(data, steps = ifelse(is.na(steps), )) data2 <- data x <- data.frame(0,0,0,0) for(i in 1:nrow(data2)) { if(is.na(data2[i,1] == T)) { x <- left_join(data2[i,], mean_per_interval, by = 'interval') data2[i,1] <- x[,4] } } #histogram of data2 - with no missing daily_steps2 <- data2 %>% group_by(date) %>% summarise(total_daily_steps = sum(steps)) #histogram ggplot(daily_steps2, aes(x = total_daily_steps)) + geom_histogram() #mean and median of steps each day mean(daily_steps2$total_daily_steps, na.rm = T) median(daily_steps2$total_daily_steps, na.rm = T) #we can see that the mean and median values have no changed for #the overall data set, but now we have a more complete dataset mean(data$steps, na.rm = T) mean(data2$steps) ###Are there differences in activity patterns between weekdays and weekends? data2 <- data2 %>% mutate(weekday = weekdays(date), day_of_week = ifelse(weekday == "Saturday" | weekday == "Sunday", "weekend", "weekday")) data2$day_of_week <- as.factor(data2$day_of_week) mean_per_interval2 <- data2 %>% group_by(interval, day_of_week) %>% summarise(mean = mean(steps, na.rm = T)) ##panel plot ggplot(mean_per_interval2, aes(x = interval, y = mean)) + geom_line() + facet_grid( day_of_week ~ .)
#' Plot the biotracer data with one biplot for each combination of 2 biotracers #' #' @inheritParams plot_data #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_biotracer_data <- function(biotracer_data, save=FALSE, save_path){ # If the biotracer data contains 3 elements called d13C, d15N and d125I, then we will plot 3 figures, # because there are 3 ways to choose an unordered subset of 2 elements from a fixed set of 3 elements: # d13C vs. d15N, # d13C vs. d125I and # d15N vs. d125I. # # With the following code, we select all the possible combinations without repetition: nb_biotracers <- ncol(biotracer_data) - 1 if(nb_biotracers==1){ figure <- ggplot(biotracer_data, aes(x = biotracer_data$group, y=get(names(biotracer_data)[2]), colour = biotracer_data$group)) + ggtitle("Isotopic measurements") + geom_point(data=biotracer_data, aes(x = biotracer_data$group, y=get(names(biotracer_data)[2]), colour = biotracer_data$group), position=position_jitter(width=.2,height=.1), show.legend=T) + guides(colour = guide_legend()) + theme_bw() + #xlab(names(biotracer_data)[element1 + 1]) + ylab(names(biotracer_data)[element1 + 1]) + theme(panel.grid.major = element_line(colour = "grey"), panel.grid.minor = element_blank(), axis.title = element_text(size = 15), axis.text.y = element_text(size = 12), axis.text.x = element_text(margin = margin(3, 0, 0, 0), size = 12, angle=45, hjust=1), plot.title = element_text(hjust = 0.5), legend.position="none") print(figure) if (save == TRUE){ save_path <- ifelse(!missing(save_path), save_path, getwd()) ggsave(paste0(save_path, "/figure_biotracer_", colnames(biotracer_data)[element1], ".png"), height = 4.4, width = 8) } }else{ for (element1 in 1:nb_biotracers){ for (element2 in 1:nb_biotracers){ if (element2 > element1){ figure <- ggplot(data=biotracer_data, aes(x = biotracer_data[, element1 + 1], y = biotracer_data[, element2 + 1], colour = biotracer_data$group)) + ggtitle("Isotopic measurements") + xlab(names(biotracer_data)[element1 + 1]) + ylab(names(biotracer_data)[element2 + 1]) + geom_point(size = 3, na.rm = TRUE) + guides(colour = guide_legend()) + theme_bw() + theme(panel.grid.major = element_line(colour = "grey"), panel.grid.minor = element_blank(), axis.title = element_text(size = 15), axis.text.y = element_text(size = 12), axis.text.x = element_text(margin = margin(3, 0, 0, 0), size = 12), plot.title = element_text(hjust = 0.5)) print(figure) if (save == TRUE){ save_path <- ifelse(!missing(save_path), save_path, getwd()) ggsave(paste0(save_path, "/figure_biotracer_", colnames(biotracer_data)[element1+1], "_", colnames(biotracer_data)[element2+1], ".png"), height = 4.4, width = 8) } } } } } } #' Plot any matrix data with a raster plot #' #' @param matrix the matrix ready to be plotted #' @param title the title to put (depends on the variable) #' @inheritParams plot_data #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_matrix <- function(matrix, title, save = FALSE, save_path){ matrix <- as.data.frame(matrix) df <- data.frame(rep(colnames(matrix), each = nrow(matrix)), rep(rownames(matrix), nrow(matrix)), unlist(matrix)) colnames(df) <- c("pred", "prey", "value") df$value <- round(df$value, 2) df$pred <- as.factor(df$pred) df$prey <- rev(as.factor(df$prey)) figure <- ggplot(df, aes_string(x = "pred", y = "prey", fill = "value")) + geom_raster() + theme_bw() + #scale_x_continuous(labels = colnames(matrix)), breaks = seq(1, ncol(matrix))) + scale_y_discrete(labels = rev(rownames(matrix)), limits=rev) + scale_fill_gradient(low = "white", high = "blue3", limit = c(0, 1)) + ggtitle(title) + ylab("Preys") + xlab("Predators") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.title = element_text(size = 15), axis.text.x = element_text(size = 12, angle = 45, vjust = 1, hjust = 1), axis.text.y = element_text(size = 12, angle = 45, vjust = 1, hjust = 0), legend.title = element_blank(), plot.title = element_text(hjust = 0.5)) if (ncol(matrix) < 15){ figure <- figure + geom_text(data = df[!is.na(df$value), ], aes_string(label = "value")) } print(figure) if (save == TRUE){ save_path <- ifelse(!missing(save_path), save_path, getwd()) ggsave(paste0(save_path, "figure_", gsub(" ", "_", title), ".png"), height = 4.4, width = 8) } } #' Plot the input data #' #' @description This function is used to plot the input biotracer and/or the stomach content data. #' You can use the function with only one parameter to plot only one kind of data. #' #' The figure(s) can be saved as PNG using: \code{save = TRUE}, and the directory path to which #' the figures are saved can be precised with: \code{save_path = "."}. #' #' If only the stomach content data is entered, there will be a single raster plot containing the proportions #' of occurences in the stomachs. #' #' For the biotracer data, there will be as many plots as the number of #' combinations of elements. For example if only two isotopes are entered, there will be a single biplot #' plotted. If three elements are entered (element A, B and C), three biplots will be shown : A vs. B, #' B vs. C and A vs. C. #' #' @inheritParams preprocess_data #' @inheritParams plot_prior #' #' @examples #' #' example_biotracer_data <- read.csv(system.file("extdata", "example_biotracer_data.csv", #' package = "EcoDiet")) #' plot_data(biotracer_data = example_biotracer_data) #' #' example_stomach_data <- read.csv(system.file("extdata", "example_stomach_data.csv", #' package = "EcoDiet")) #' #' plot_data(biotracer_data = example_biotracer_data, #' stomach_data = example_stomach_data) #' #' #' @seealso \code{\link{plot_prior}} to plot the prior means or probability distribution(s), #' \code{\link{plot_results}} to plot the posterior means or probability distribution(s) #' #' @export plot_data <- function(biotracer_data = NULL, stomach_data = NULL, save = FALSE, save_path = "."){ if (!is.null(stomach_data)){ # Clean the stomach data similarly as in the preprocess_data function except for the commented parts if (!colnames(stomach_data)[1] %in% rownames(stomach_data)){ row.names(stomach_data) <- stomach_data[, 1] stomach_data[, 1] <- NULL } # Divide the number of stomachs by the total number of full stomachs to obtain proportions stomach_data[] <- sapply(stomach_data, function(X) X/X[nrow(stomach_data)]) # Remove the NA caused by division by zero for the trophic groups at the base of the ecosystem stomach_data[is.na(stomach_data)] <- 0 stomach_data <- stomach_data[-nrow(stomach_data), ] stomach_data <- stomach_data[, order(colnames(stomach_data))] stomach_data <- stomach_data[order(rownames(stomach_data)), ] stomach_data[stomach_data == 0] <- NA plot_matrix(stomach_data, title = "Proportion of occurences in stomachs", save, save_path) } if (!is.null(biotracer_data)){ plot_biotracer_data(biotracer_data, save, save_path) } } #' Plot the prior probability distribution(s) for a given variable, a given predator and its given preys #' #' @inheritParams plot_prior #' @param title the title to put (depends on the variable and the predator to plot) #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_prior_distribution <- function(data, literature_configuration, pred, prey, variable, title, save, save_path){ # Check that the entered predator is correct pred_index <- which(colnames(data$o) == pred) if (length(pred_index) == 0){ stop("You entered a wrong predator name in the `pred` argument.\n", "Please check and ensure to pick one of the following: \"", paste(colnames(data$o), collapse = "\", \""), "\".\n") } if (data$nb_prey[pred_index] == 0){ stop("The predator you have chosen (\"", pred, "\") has no prey.") } # Check that the entered prey(s) is/are correct if (is.null(prey)){ prey_index <- data$list_prey[pred_index, ] prey_index <- prey_index[!is.na(prey_index)] prey <- colnames(data$o)[prey_index] } else { prey_index <- which(colnames(data$o) %in% prey) if (length(prey) != length(prey_index)){ stop("Please check the values entered in `prey` argument.\n", "The following names don't correspond to any trophic groups: \n", "\".\n But the prey names are actually: \"", paste(prey[which(!prey%in%colnames(data$o))], collapse = "\", \""), "\".\n") } if (!all(prey_index %in% data$list_prey[pred_index, ])){ stop("You have entered at least one prey that is not eaten by the predator \"", pred ,"\".\n", " Here are the preys you have entered: \"", paste(prey, collapse = "\", \""), "\".\n And here are the predator's preys: \"", paste(colnames(data$o)[data$list_prey[pred_index, 1:data$nb_prey[pred_index]]], collapse = "\", \""), "\".\n Please rename your prey input to be consistent.") } } # Construct the corresponding data frame x <- seq(0, 1, length = 512) df_to_plot <- data.frame(Prey = c(), x = c(), Density = c(), type=c()) df_to_plot_cond <- data.frame(Prey = c(), x = c(), Density = c(), type=c()) if (variable == "PI"){ if (literature_configuration) { scalar <- ((length(which(!is.na(data$list_prey[pred_index, ]))) - 1) / (data$CV[pred_index]^2))-1 scalar <- ifelse(length(which(!is.na(data$list_prey[pred_index, ]))) == 1, 1, scalar) df_cond_allprey <- sapply(data$alpha_lit[, pred_index], function(x){stats::rgamma(1000000,x*scalar)}) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) X/rowSums(df_cond_allprey)) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) stats::density(X, from=0, to=1)$y) }else{ vecprey <- rep(0,ncol(data$list_prey)) vecprey[prey_index] <- 1 df_cond_allprey <- sapply(vecprey, function(x){stats::rgamma(1000000,x)}) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) X/rowSums(df_cond_allprey)) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) stats::density(X, from=0, to=1)$y) } } for (each_prey in prey){ prey_idx <- which(rownames(data$o) == each_prey) if (prey_idx %in% data$list_prey[pred_index, ]){ if (variable == "PI"){ if (literature_configuration) { Density <- stats::dbeta(x, data$alpha_lit[prey_idx, pred_index] * scalar, (colSums(data$alpha_lit)[pred_index] - data$alpha_lit[prey_idx, pred_index]) * scalar) df_to_plot_cond <- rbind(df_to_plot_cond, data.frame(Prey = rep(each_prey, 512), x = x, Density = df_cond_allprey[, prey_idx], type=" conditional")) } else { Density <- stats::dbeta(x, 1, data$nb_prey[pred_index] - 1) } df_to_plot <- rbind(df_to_plot, data.frame(Prey = rep(each_prey, 512), x = x, Density = Density, type="marginal")) } else if (variable == "eta"){ if (literature_configuration) { Density <- stats::dbeta(x, data$eta_hyperparam_1[prey_idx, pred_index], data$eta_hyperparam_2[prey_idx, pred_index]) } else { Density <- stats::dbeta(x, 1, 1) } df_to_plot <- rbind(df_to_plot, data.frame(Prey = rep(each_prey, 512), x = x, Density = Density, type="marginal")) } } } if (variable == "PI" & literature_configuration==T){ df_to_plot <- rbind(df_to_plot, df_to_plot_cond) } # Plot the figure figure <- ggplot(df_to_plot, aes_string(x = "x", y = "Density", colour = "Prey", linetype = "Prey")) + geom_line(size = 1.25) + ggtitle(paste(title, "\nfor the", pred, "predator")) + xlim(0, 1) + theme_bw() + theme(axis.title.x = element_blank(), plot.title = element_text(hjust = 0.5)) + facet_wrap(~type, scales="free_y") print(figure) if (save == TRUE){ ggsave(paste0("figure_", gsub(" ", "_", title), "_for_the_", pred, "_predator", format(Sys.time(),'_%Y-%m-%d_%H-%M-%S'), ".png"), height = 4.4, width = 6.2, path = save_path) } } #' Plot the prior means or probability distribution(s) #' #' @description This function plots the prior means or probability distribution(s) for one or the two #' variable(s) of interest : the trophic link probabilities ("eta") and/or the diet proportions ("PI"). #' #' The figure(s) can be saved as PNG using: \code{save = TRUE}, and the directory path to which #' the figures are saved can be precised with: \code{save_path = "."}. #' #' If no "pred" nor "prey" parameter is entered, the plot will be a raster plot with the mean priors for #' all the trophic groups. #' #' If one predator name is entered as "pred", the probability distribution(s) will be plotted for all its #' prey(s) by default. Some specific prey(s) name(s) can also be entered because if a predator has #' 22 preys, plotting them all will make the plot hard to read. So you can specify the one or many prey(s) #' of interest and only display their corresponding probability distribution(s). #' #' The "variable" parameter can be specified if one wants to plot the priors for only one variable #' ("PI" or "eta"). #' #' @param data the preprocessed data list output by the preprocess_data() function #' @param pred the predator name for which we want to plot the probability densities #' @param prey the prey(s) name(s) for which we want to plot the probability densities #' @param variable the variable(s) for which we want to plot the probability densities. By default #' we will plot the two variables of interest: eta and PI. #' @param save A boolean describing whether the figure should be saved as PNG. #' By default the figures are not saved. #' @param save_path A string describing the path to which the figures should be saved. #' By default the figures are saved in a temporary directory. #' @inheritParams preprocess_data #' #' @examples #' #' realistic_biotracer_data <- read.csv(system.file("extdata", "realistic_biotracer_data.csv", #' package = "EcoDiet")) #' realistic_stomach_data <- read.csv(system.file("extdata", "realistic_stomach_data.csv", #' package = "EcoDiet")) #' #' data <- preprocess_data(biotracer_data = realistic_biotracer_data, #' trophic_discrimination_factor = c(0.8, 3.4), #' literature_configuration = FALSE, #' stomach_data = realistic_stomach_data) #' #' plot_prior(data, literature_configuration = FALSE) #' plot_prior(data, literature_configuration = FALSE, pred = "Cod") #' plot_prior(data, literature_configuration = FALSE, pred = "Cod", #' prey = c("Crabs", "Shrimps"), variable = "eta") #' #' @seealso \code{\link{plot_results}} to plot the posterior means or probability distribution(s), #' \code{\link{plot_data}} to plot the input data #' #' @export plot_prior <- function(data, literature_configuration, pred = NULL, prey = NULL, variable = c("eta", "PI"), save = FALSE, save_path = "."){ if (!all(variable %in% c("eta", "PI"))){ stop("This function has only be designed to plot the priors of PI or eta.") } for (var in variable){ if (is.null(pred) & is.null(prey)){ title <- switch(var, PI = "Mean of the prior diet proportions", eta = "Mean of the prior trophic link probabilities") mean_prior <- matrix(NA, ncol = data$nb_group, nrow = data$nb_group) colnames(mean_prior) <- rownames(mean_prior) <- colnames(data$o) for (i in data$list_pred){ for (k in data$list_prey[i, 1:data$nb_prey[i]]){ if (var == "eta"){ if (literature_configuration){ mean_prior[k, i] <- (data$eta_hyperparam_1[k, i]/ (data$eta_hyperparam_1[k, i] + data$eta_hyperparam_2[k, i])) } else { mean_prior[k, i] <- 1/2 } } else if (var == "PI"){ if (literature_configuration){ mean_prior[k, i] <- data$alpha_lit[k, i]/colSums(data$alpha_lit)[i] } else { mean_prior[k, i] <- 1/data$nb_prey[i] } } } } plot_matrix(mean_prior, title, save, save_path) } else { title <- switch(var, PI = "Marginal and Conditional prior distribution of the diet proportions", eta = "Marginal prior distribution of the trophic link probabilities") plot_prior_distribution(data, literature_configuration, pred, prey, variable = var, title, save, save_path) } } } #' Extract the means of the posterior distribution for a specific variable (PI or eta) #' in a matrix format (with the predators in the columns, and the preys in the rows) #' #' @inheritParams plot_results #' @param mcmc_output A matrix generated in plot_results containing the MCMC samples #' #' @keywords internal #' @noRd extract_mean <- function(mcmc_output, data, variable = "PI"){ # keep only the means for the relevant variable raw_means <- colMeans(mcmc_output) raw_means <- raw_means[startsWith(names(raw_means), variable)] # prepare an empty matrix with the correct format matrix_mean <- matrix(NA, data$nb_group, data$nb_group) colnames(matrix_mean) <- rownames(matrix_mean) <- colnames(data$o) for (i in seq_along(raw_means)){ # extract the indices that are between the brackets: "PI[2, 4]" -> "2,4" correct_indices <- regmatches(names(raw_means)[i], regexec("\\[(.*?)\\]", names(raw_means)[i]))[[1]][2] # re-format the indices: "2,4" -> c(2L, 4L) correct_indices <- as.integer(strsplit(correct_indices, ",")[[1]]) # use the indices to fill the matrix with the correct format matrix_mean[correct_indices[1], correct_indices[2]] <- raw_means[i] } return(matrix_mean) } #' Plot the posterior probability density(ies) for a given variable and predator #' #' @inheritParams plot_results #' @param mcmc_output A matrix generated in plot_results containing the MCMC samples #' @param title the title to put (depends on the variable and the predator to plot) #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_posterior_distribution <- function(mcmc_output, data, pred, prey, variable, title, save = FALSE, save_path){ # Check that the entered predator is correct pred_index <- which(colnames(data$o) == pred) if (length(pred_index) == 0){ stop("You did not put a correct predator name in the `pred` argument.\n", " You entered the name \"", pred,"\", while the predator names are actually: \"", paste(colnames(data$o), collapse = "\", \""), "\".\n", " Please use one of the above names in the `pred` argument.") } if (data$nb_prey[pred_index] == 0){ stop("The predator you have chosen (\"", pred, "\") has no prey and thus cannot be plotted.") } # Check that the entered prey(s) is/are correct if (!is.null(prey)){ prey_index <- which(colnames(data$o) %in% prey) if (length(prey) != length(prey_index)){ stop("You used an incorrect prey name in the `prey` argument.\n", " You have entered the names: \"", paste(prey, collapse = "\", \""), "\".\n But the prey names are actually: \"", paste(colnames(data$o), collapse = "\", \""), "\".\n", " Please put correct names in the `prey` argument.") } if (!all(prey_index %in% data$list_prey[pred_index, ])){ stop("You have entered at least one prey that is not eaten by the predator \"", pred ,"\".\n", " Here are the preys you have entered: \"", paste(prey, collapse = "\", \""), "\".\n And here are the predator's preys: \"", paste(colnames(data$o)[data$list_prey[pred_index, 1:data$nb_prey[pred_index]]], collapse = "\", \""), "\".\n Please rename your prey input to be consistent.") } } # Keep only the variable of interest (all the "PI" or all the "eta") mcmc_output <- mcmc_output[, startsWith(colnames(mcmc_output), variable)] # Create a lookup table between the model output's names and the prey's and predator's indices: # names prey pred # 1 PI[2,1] 2 1 # 2 PI[3,1] 3 1 # 3 PI[3,2] 3 2 lookup <- sapply(colnames(mcmc_output), function(X) regmatches(X, regexec("\\[(.*?)\\]", X))[[1]][2]) prey_idx <- sapply(lookup, function(X) strsplit(X, split=',')[[1]][[1]]) pred_idx <- sapply(lookup, function(X) strsplit(X, split=',')[[1]][[2]]) lookup_table <- data.frame(names = colnames(mcmc_output), prey = as.integer(prey_idx), pred = as.integer(pred_idx), stringsAsFactors = FALSE) # Prepare a data frame with the values for one predator's preys if (is.null(prey)){ variables_to_extract <- lookup_table[lookup_table$pred == pred_index, ]$names prey <- colnames(data$o)[lookup_table[lookup_table$pred == pred_index, ]$prey] } else { variables_to_extract <- lookup_table[(lookup_table$pred == pred_index & lookup_table$prey %in% prey_index & lookup_table$prey %in% data$list_prey[pred_index, ]), ]$names } values_to_extract <- mcmc_output[, variables_to_extract] df_to_plot <- data.frame(Prey = rep(prey, each = dim(mcmc_output)[1]), variable_to_plot = c(values_to_extract)) # Trick to scale the plot and not have a warning from the CRAN check: variable_to_plot <- NULL ..scaled.. <- NULL Prey <- NULL # Plot these values to represent the approximated probability densities figure <- ggplot(df_to_plot) + geom_density(aes(x = variable_to_plot, y = ..scaled.., fill = Prey), alpha = .3, adjust = 1/2, na.rm = TRUE) + geom_density(aes(x = variable_to_plot, y = ..scaled.., color = Prey), size = 1.25, adjust = 1/2, na.rm = TRUE) + ggtitle(paste(title, "\nfor the", colnames(data$o)[pred_index], "predator")) + ylab("Density") + scale_shape_manual(values = c(seq(1:10))) + guides(colour = guide_legend(byrow = 1, ncol = 1), shape = guide_legend(byrow = 1, ncol = 1)) + xlim(0, 1) + theme_bw() + theme(axis.title.x = element_blank(), plot.title = element_text(hjust = 0.5)) print(figure) if (save == TRUE){ ggsave(paste0("figure_", gsub(" ", "_", title), "_for_the_", colnames(data$o)[pred_index], "_predator", format(Sys.time(),'_%Y-%m-%d_%H-%M-%S'), ".png"), height = 4.4, width = 6.2, path = save_path) } } #' Plot the posterior means or probability distribution(s) #' #' @description This function plots the posterior means or probability distribution(s) for one #' or the two variable(s) of interest : the trophic link probabilities ("eta") and/or #' the diet proportions ("PI"). #' #' The figure(s) can be saved as PNG using: \code{save = TRUE}, and the directory path to which #' the figures are saved can be precised with: \code{save_path = "."}. #' #' If no "pred" nor "prey" parameter is entered, the plot will be a raster plot with the mean priors for #' all the trophic groups. #' #' If one predator name is entered as "pred", the probability distribution(s) will be plotted for all its #' prey(s) by default. Some specific prey(s) name(s) can also be entered because if a predator has #' 22 preys, plotting them all will make the plot hard to read. So you can specify the one or many prey(s) #' of interest and only display their corresponding probability distribution(s). #' #' The "variable" parameter can be specified if one wants to plot the priors for only one variable #' ("PI" or "eta"). #' #' @param jags_output the mcmc.list object output by the run_model() function #' @inheritParams plot_prior #' #' @examples #' #' \donttest{ #' realistic_biotracer_data <- read.csv(system.file("extdata", "realistic_biotracer_data.csv", #' package = "EcoDiet")) #' realistic_stomach_data <- read.csv(system.file("extdata", "realistic_stomach_data.csv", #' package = "EcoDiet")) #' #' data <- preprocess_data(biotracer_data = realistic_biotracer_data, #' trophic_discrimination_factor = c(0.8, 3.4), #' literature_configuration = FALSE, #' stomach_data = realistic_stomach_data) #' #' write_model(literature_configuration = FALSE) #' #' mcmc_output <- run_model("EcoDiet_model.txt", data, run_param="test") #' #' plot_results(mcmc_output, data) #' plot_results(mcmc_output, data, pred = "Crabs") #' plot_results(mcmc_output, data, pred = "Crabs", #' variable = "PI", prey = c("Bivalves", "Shrimps")) #' #' } #' #' @seealso \code{\link{plot_prior}} to plot the prior means or probability distribution(s), #' \code{\link{plot_data}} to plot the input data #' #' @export plot_results <- function(jags_output, data, pred = NULL, prey = NULL, variable = c("eta", "PI"), save = FALSE, save_path = "."){ if (!all(variable %in% c("eta", "PI"))){ stop("This function can only print a figure for the PI or eta variable.\n", " But you have entered this variable name: \"", variable, "\".\n", " Please use rather `variable = \"PI\"` or `variable = \"eta\"` for this function.") } mcmc_output <- as.matrix(jags_output$samples) for (var in variable){ if (is.null(pred) & is.null(prey)){ title <- switch(var, PI = "Mean of the posterior diet proportions", eta = "Mean of the posterior trophic link probabilities") mean <- extract_mean(mcmc_output, data, variable = var) plot_matrix(mean, title, save, save_path) } else { title <- switch(var, PI = "Marginal posterior distribution of the diet proportions", eta = "Marginal posterior distribution of the trophic link probabilities") plot_posterior_distribution(mcmc_output, data, pred, prey, variable = var, title, save, save_path) } } }
/R/plot.R
no_license
cran/EcoDiet
R
false
false
28,694
r
#' Plot the biotracer data with one biplot for each combination of 2 biotracers #' #' @inheritParams plot_data #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_biotracer_data <- function(biotracer_data, save=FALSE, save_path){ # If the biotracer data contains 3 elements called d13C, d15N and d125I, then we will plot 3 figures, # because there are 3 ways to choose an unordered subset of 2 elements from a fixed set of 3 elements: # d13C vs. d15N, # d13C vs. d125I and # d15N vs. d125I. # # With the following code, we select all the possible combinations without repetition: nb_biotracers <- ncol(biotracer_data) - 1 if(nb_biotracers==1){ figure <- ggplot(biotracer_data, aes(x = biotracer_data$group, y=get(names(biotracer_data)[2]), colour = biotracer_data$group)) + ggtitle("Isotopic measurements") + geom_point(data=biotracer_data, aes(x = biotracer_data$group, y=get(names(biotracer_data)[2]), colour = biotracer_data$group), position=position_jitter(width=.2,height=.1), show.legend=T) + guides(colour = guide_legend()) + theme_bw() + #xlab(names(biotracer_data)[element1 + 1]) + ylab(names(biotracer_data)[element1 + 1]) + theme(panel.grid.major = element_line(colour = "grey"), panel.grid.minor = element_blank(), axis.title = element_text(size = 15), axis.text.y = element_text(size = 12), axis.text.x = element_text(margin = margin(3, 0, 0, 0), size = 12, angle=45, hjust=1), plot.title = element_text(hjust = 0.5), legend.position="none") print(figure) if (save == TRUE){ save_path <- ifelse(!missing(save_path), save_path, getwd()) ggsave(paste0(save_path, "/figure_biotracer_", colnames(biotracer_data)[element1], ".png"), height = 4.4, width = 8) } }else{ for (element1 in 1:nb_biotracers){ for (element2 in 1:nb_biotracers){ if (element2 > element1){ figure <- ggplot(data=biotracer_data, aes(x = biotracer_data[, element1 + 1], y = biotracer_data[, element2 + 1], colour = biotracer_data$group)) + ggtitle("Isotopic measurements") + xlab(names(biotracer_data)[element1 + 1]) + ylab(names(biotracer_data)[element2 + 1]) + geom_point(size = 3, na.rm = TRUE) + guides(colour = guide_legend()) + theme_bw() + theme(panel.grid.major = element_line(colour = "grey"), panel.grid.minor = element_blank(), axis.title = element_text(size = 15), axis.text.y = element_text(size = 12), axis.text.x = element_text(margin = margin(3, 0, 0, 0), size = 12), plot.title = element_text(hjust = 0.5)) print(figure) if (save == TRUE){ save_path <- ifelse(!missing(save_path), save_path, getwd()) ggsave(paste0(save_path, "/figure_biotracer_", colnames(biotracer_data)[element1+1], "_", colnames(biotracer_data)[element2+1], ".png"), height = 4.4, width = 8) } } } } } } #' Plot any matrix data with a raster plot #' #' @param matrix the matrix ready to be plotted #' @param title the title to put (depends on the variable) #' @inheritParams plot_data #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_matrix <- function(matrix, title, save = FALSE, save_path){ matrix <- as.data.frame(matrix) df <- data.frame(rep(colnames(matrix), each = nrow(matrix)), rep(rownames(matrix), nrow(matrix)), unlist(matrix)) colnames(df) <- c("pred", "prey", "value") df$value <- round(df$value, 2) df$pred <- as.factor(df$pred) df$prey <- rev(as.factor(df$prey)) figure <- ggplot(df, aes_string(x = "pred", y = "prey", fill = "value")) + geom_raster() + theme_bw() + #scale_x_continuous(labels = colnames(matrix)), breaks = seq(1, ncol(matrix))) + scale_y_discrete(labels = rev(rownames(matrix)), limits=rev) + scale_fill_gradient(low = "white", high = "blue3", limit = c(0, 1)) + ggtitle(title) + ylab("Preys") + xlab("Predators") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.title = element_text(size = 15), axis.text.x = element_text(size = 12, angle = 45, vjust = 1, hjust = 1), axis.text.y = element_text(size = 12, angle = 45, vjust = 1, hjust = 0), legend.title = element_blank(), plot.title = element_text(hjust = 0.5)) if (ncol(matrix) < 15){ figure <- figure + geom_text(data = df[!is.na(df$value), ], aes_string(label = "value")) } print(figure) if (save == TRUE){ save_path <- ifelse(!missing(save_path), save_path, getwd()) ggsave(paste0(save_path, "figure_", gsub(" ", "_", title), ".png"), height = 4.4, width = 8) } } #' Plot the input data #' #' @description This function is used to plot the input biotracer and/or the stomach content data. #' You can use the function with only one parameter to plot only one kind of data. #' #' The figure(s) can be saved as PNG using: \code{save = TRUE}, and the directory path to which #' the figures are saved can be precised with: \code{save_path = "."}. #' #' If only the stomach content data is entered, there will be a single raster plot containing the proportions #' of occurences in the stomachs. #' #' For the biotracer data, there will be as many plots as the number of #' combinations of elements. For example if only two isotopes are entered, there will be a single biplot #' plotted. If three elements are entered (element A, B and C), three biplots will be shown : A vs. B, #' B vs. C and A vs. C. #' #' @inheritParams preprocess_data #' @inheritParams plot_prior #' #' @examples #' #' example_biotracer_data <- read.csv(system.file("extdata", "example_biotracer_data.csv", #' package = "EcoDiet")) #' plot_data(biotracer_data = example_biotracer_data) #' #' example_stomach_data <- read.csv(system.file("extdata", "example_stomach_data.csv", #' package = "EcoDiet")) #' #' plot_data(biotracer_data = example_biotracer_data, #' stomach_data = example_stomach_data) #' #' #' @seealso \code{\link{plot_prior}} to plot the prior means or probability distribution(s), #' \code{\link{plot_results}} to plot the posterior means or probability distribution(s) #' #' @export plot_data <- function(biotracer_data = NULL, stomach_data = NULL, save = FALSE, save_path = "."){ if (!is.null(stomach_data)){ # Clean the stomach data similarly as in the preprocess_data function except for the commented parts if (!colnames(stomach_data)[1] %in% rownames(stomach_data)){ row.names(stomach_data) <- stomach_data[, 1] stomach_data[, 1] <- NULL } # Divide the number of stomachs by the total number of full stomachs to obtain proportions stomach_data[] <- sapply(stomach_data, function(X) X/X[nrow(stomach_data)]) # Remove the NA caused by division by zero for the trophic groups at the base of the ecosystem stomach_data[is.na(stomach_data)] <- 0 stomach_data <- stomach_data[-nrow(stomach_data), ] stomach_data <- stomach_data[, order(colnames(stomach_data))] stomach_data <- stomach_data[order(rownames(stomach_data)), ] stomach_data[stomach_data == 0] <- NA plot_matrix(stomach_data, title = "Proportion of occurences in stomachs", save, save_path) } if (!is.null(biotracer_data)){ plot_biotracer_data(biotracer_data, save, save_path) } } #' Plot the prior probability distribution(s) for a given variable, a given predator and its given preys #' #' @inheritParams plot_prior #' @param title the title to put (depends on the variable and the predator to plot) #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_prior_distribution <- function(data, literature_configuration, pred, prey, variable, title, save, save_path){ # Check that the entered predator is correct pred_index <- which(colnames(data$o) == pred) if (length(pred_index) == 0){ stop("You entered a wrong predator name in the `pred` argument.\n", "Please check and ensure to pick one of the following: \"", paste(colnames(data$o), collapse = "\", \""), "\".\n") } if (data$nb_prey[pred_index] == 0){ stop("The predator you have chosen (\"", pred, "\") has no prey.") } # Check that the entered prey(s) is/are correct if (is.null(prey)){ prey_index <- data$list_prey[pred_index, ] prey_index <- prey_index[!is.na(prey_index)] prey <- colnames(data$o)[prey_index] } else { prey_index <- which(colnames(data$o) %in% prey) if (length(prey) != length(prey_index)){ stop("Please check the values entered in `prey` argument.\n", "The following names don't correspond to any trophic groups: \n", "\".\n But the prey names are actually: \"", paste(prey[which(!prey%in%colnames(data$o))], collapse = "\", \""), "\".\n") } if (!all(prey_index %in% data$list_prey[pred_index, ])){ stop("You have entered at least one prey that is not eaten by the predator \"", pred ,"\".\n", " Here are the preys you have entered: \"", paste(prey, collapse = "\", \""), "\".\n And here are the predator's preys: \"", paste(colnames(data$o)[data$list_prey[pred_index, 1:data$nb_prey[pred_index]]], collapse = "\", \""), "\".\n Please rename your prey input to be consistent.") } } # Construct the corresponding data frame x <- seq(0, 1, length = 512) df_to_plot <- data.frame(Prey = c(), x = c(), Density = c(), type=c()) df_to_plot_cond <- data.frame(Prey = c(), x = c(), Density = c(), type=c()) if (variable == "PI"){ if (literature_configuration) { scalar <- ((length(which(!is.na(data$list_prey[pred_index, ]))) - 1) / (data$CV[pred_index]^2))-1 scalar <- ifelse(length(which(!is.na(data$list_prey[pred_index, ]))) == 1, 1, scalar) df_cond_allprey <- sapply(data$alpha_lit[, pred_index], function(x){stats::rgamma(1000000,x*scalar)}) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) X/rowSums(df_cond_allprey)) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) stats::density(X, from=0, to=1)$y) }else{ vecprey <- rep(0,ncol(data$list_prey)) vecprey[prey_index] <- 1 df_cond_allprey <- sapply(vecprey, function(x){stats::rgamma(1000000,x)}) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) X/rowSums(df_cond_allprey)) df_cond_allprey <- apply(df_cond_allprey, 2, function(X) stats::density(X, from=0, to=1)$y) } } for (each_prey in prey){ prey_idx <- which(rownames(data$o) == each_prey) if (prey_idx %in% data$list_prey[pred_index, ]){ if (variable == "PI"){ if (literature_configuration) { Density <- stats::dbeta(x, data$alpha_lit[prey_idx, pred_index] * scalar, (colSums(data$alpha_lit)[pred_index] - data$alpha_lit[prey_idx, pred_index]) * scalar) df_to_plot_cond <- rbind(df_to_plot_cond, data.frame(Prey = rep(each_prey, 512), x = x, Density = df_cond_allprey[, prey_idx], type=" conditional")) } else { Density <- stats::dbeta(x, 1, data$nb_prey[pred_index] - 1) } df_to_plot <- rbind(df_to_plot, data.frame(Prey = rep(each_prey, 512), x = x, Density = Density, type="marginal")) } else if (variable == "eta"){ if (literature_configuration) { Density <- stats::dbeta(x, data$eta_hyperparam_1[prey_idx, pred_index], data$eta_hyperparam_2[prey_idx, pred_index]) } else { Density <- stats::dbeta(x, 1, 1) } df_to_plot <- rbind(df_to_plot, data.frame(Prey = rep(each_prey, 512), x = x, Density = Density, type="marginal")) } } } if (variable == "PI" & literature_configuration==T){ df_to_plot <- rbind(df_to_plot, df_to_plot_cond) } # Plot the figure figure <- ggplot(df_to_plot, aes_string(x = "x", y = "Density", colour = "Prey", linetype = "Prey")) + geom_line(size = 1.25) + ggtitle(paste(title, "\nfor the", pred, "predator")) + xlim(0, 1) + theme_bw() + theme(axis.title.x = element_blank(), plot.title = element_text(hjust = 0.5)) + facet_wrap(~type, scales="free_y") print(figure) if (save == TRUE){ ggsave(paste0("figure_", gsub(" ", "_", title), "_for_the_", pred, "_predator", format(Sys.time(),'_%Y-%m-%d_%H-%M-%S'), ".png"), height = 4.4, width = 6.2, path = save_path) } } #' Plot the prior means or probability distribution(s) #' #' @description This function plots the prior means or probability distribution(s) for one or the two #' variable(s) of interest : the trophic link probabilities ("eta") and/or the diet proportions ("PI"). #' #' The figure(s) can be saved as PNG using: \code{save = TRUE}, and the directory path to which #' the figures are saved can be precised with: \code{save_path = "."}. #' #' If no "pred" nor "prey" parameter is entered, the plot will be a raster plot with the mean priors for #' all the trophic groups. #' #' If one predator name is entered as "pred", the probability distribution(s) will be plotted for all its #' prey(s) by default. Some specific prey(s) name(s) can also be entered because if a predator has #' 22 preys, plotting them all will make the plot hard to read. So you can specify the one or many prey(s) #' of interest and only display their corresponding probability distribution(s). #' #' The "variable" parameter can be specified if one wants to plot the priors for only one variable #' ("PI" or "eta"). #' #' @param data the preprocessed data list output by the preprocess_data() function #' @param pred the predator name for which we want to plot the probability densities #' @param prey the prey(s) name(s) for which we want to plot the probability densities #' @param variable the variable(s) for which we want to plot the probability densities. By default #' we will plot the two variables of interest: eta and PI. #' @param save A boolean describing whether the figure should be saved as PNG. #' By default the figures are not saved. #' @param save_path A string describing the path to which the figures should be saved. #' By default the figures are saved in a temporary directory. #' @inheritParams preprocess_data #' #' @examples #' #' realistic_biotracer_data <- read.csv(system.file("extdata", "realistic_biotracer_data.csv", #' package = "EcoDiet")) #' realistic_stomach_data <- read.csv(system.file("extdata", "realistic_stomach_data.csv", #' package = "EcoDiet")) #' #' data <- preprocess_data(biotracer_data = realistic_biotracer_data, #' trophic_discrimination_factor = c(0.8, 3.4), #' literature_configuration = FALSE, #' stomach_data = realistic_stomach_data) #' #' plot_prior(data, literature_configuration = FALSE) #' plot_prior(data, literature_configuration = FALSE, pred = "Cod") #' plot_prior(data, literature_configuration = FALSE, pred = "Cod", #' prey = c("Crabs", "Shrimps"), variable = "eta") #' #' @seealso \code{\link{plot_results}} to plot the posterior means or probability distribution(s), #' \code{\link{plot_data}} to plot the input data #' #' @export plot_prior <- function(data, literature_configuration, pred = NULL, prey = NULL, variable = c("eta", "PI"), save = FALSE, save_path = "."){ if (!all(variable %in% c("eta", "PI"))){ stop("This function has only be designed to plot the priors of PI or eta.") } for (var in variable){ if (is.null(pred) & is.null(prey)){ title <- switch(var, PI = "Mean of the prior diet proportions", eta = "Mean of the prior trophic link probabilities") mean_prior <- matrix(NA, ncol = data$nb_group, nrow = data$nb_group) colnames(mean_prior) <- rownames(mean_prior) <- colnames(data$o) for (i in data$list_pred){ for (k in data$list_prey[i, 1:data$nb_prey[i]]){ if (var == "eta"){ if (literature_configuration){ mean_prior[k, i] <- (data$eta_hyperparam_1[k, i]/ (data$eta_hyperparam_1[k, i] + data$eta_hyperparam_2[k, i])) } else { mean_prior[k, i] <- 1/2 } } else if (var == "PI"){ if (literature_configuration){ mean_prior[k, i] <- data$alpha_lit[k, i]/colSums(data$alpha_lit)[i] } else { mean_prior[k, i] <- 1/data$nb_prey[i] } } } } plot_matrix(mean_prior, title, save, save_path) } else { title <- switch(var, PI = "Marginal and Conditional prior distribution of the diet proportions", eta = "Marginal prior distribution of the trophic link probabilities") plot_prior_distribution(data, literature_configuration, pred, prey, variable = var, title, save, save_path) } } } #' Extract the means of the posterior distribution for a specific variable (PI or eta) #' in a matrix format (with the predators in the columns, and the preys in the rows) #' #' @inheritParams plot_results #' @param mcmc_output A matrix generated in plot_results containing the MCMC samples #' #' @keywords internal #' @noRd extract_mean <- function(mcmc_output, data, variable = "PI"){ # keep only the means for the relevant variable raw_means <- colMeans(mcmc_output) raw_means <- raw_means[startsWith(names(raw_means), variable)] # prepare an empty matrix with the correct format matrix_mean <- matrix(NA, data$nb_group, data$nb_group) colnames(matrix_mean) <- rownames(matrix_mean) <- colnames(data$o) for (i in seq_along(raw_means)){ # extract the indices that are between the brackets: "PI[2, 4]" -> "2,4" correct_indices <- regmatches(names(raw_means)[i], regexec("\\[(.*?)\\]", names(raw_means)[i]))[[1]][2] # re-format the indices: "2,4" -> c(2L, 4L) correct_indices <- as.integer(strsplit(correct_indices, ",")[[1]]) # use the indices to fill the matrix with the correct format matrix_mean[correct_indices[1], correct_indices[2]] <- raw_means[i] } return(matrix_mean) } #' Plot the posterior probability density(ies) for a given variable and predator #' #' @inheritParams plot_results #' @param mcmc_output A matrix generated in plot_results containing the MCMC samples #' @param title the title to put (depends on the variable and the predator to plot) #' #' @import ggplot2 #' #' @keywords internal #' @noRd plot_posterior_distribution <- function(mcmc_output, data, pred, prey, variable, title, save = FALSE, save_path){ # Check that the entered predator is correct pred_index <- which(colnames(data$o) == pred) if (length(pred_index) == 0){ stop("You did not put a correct predator name in the `pred` argument.\n", " You entered the name \"", pred,"\", while the predator names are actually: \"", paste(colnames(data$o), collapse = "\", \""), "\".\n", " Please use one of the above names in the `pred` argument.") } if (data$nb_prey[pred_index] == 0){ stop("The predator you have chosen (\"", pred, "\") has no prey and thus cannot be plotted.") } # Check that the entered prey(s) is/are correct if (!is.null(prey)){ prey_index <- which(colnames(data$o) %in% prey) if (length(prey) != length(prey_index)){ stop("You used an incorrect prey name in the `prey` argument.\n", " You have entered the names: \"", paste(prey, collapse = "\", \""), "\".\n But the prey names are actually: \"", paste(colnames(data$o), collapse = "\", \""), "\".\n", " Please put correct names in the `prey` argument.") } if (!all(prey_index %in% data$list_prey[pred_index, ])){ stop("You have entered at least one prey that is not eaten by the predator \"", pred ,"\".\n", " Here are the preys you have entered: \"", paste(prey, collapse = "\", \""), "\".\n And here are the predator's preys: \"", paste(colnames(data$o)[data$list_prey[pred_index, 1:data$nb_prey[pred_index]]], collapse = "\", \""), "\".\n Please rename your prey input to be consistent.") } } # Keep only the variable of interest (all the "PI" or all the "eta") mcmc_output <- mcmc_output[, startsWith(colnames(mcmc_output), variable)] # Create a lookup table between the model output's names and the prey's and predator's indices: # names prey pred # 1 PI[2,1] 2 1 # 2 PI[3,1] 3 1 # 3 PI[3,2] 3 2 lookup <- sapply(colnames(mcmc_output), function(X) regmatches(X, regexec("\\[(.*?)\\]", X))[[1]][2]) prey_idx <- sapply(lookup, function(X) strsplit(X, split=',')[[1]][[1]]) pred_idx <- sapply(lookup, function(X) strsplit(X, split=',')[[1]][[2]]) lookup_table <- data.frame(names = colnames(mcmc_output), prey = as.integer(prey_idx), pred = as.integer(pred_idx), stringsAsFactors = FALSE) # Prepare a data frame with the values for one predator's preys if (is.null(prey)){ variables_to_extract <- lookup_table[lookup_table$pred == pred_index, ]$names prey <- colnames(data$o)[lookup_table[lookup_table$pred == pred_index, ]$prey] } else { variables_to_extract <- lookup_table[(lookup_table$pred == pred_index & lookup_table$prey %in% prey_index & lookup_table$prey %in% data$list_prey[pred_index, ]), ]$names } values_to_extract <- mcmc_output[, variables_to_extract] df_to_plot <- data.frame(Prey = rep(prey, each = dim(mcmc_output)[1]), variable_to_plot = c(values_to_extract)) # Trick to scale the plot and not have a warning from the CRAN check: variable_to_plot <- NULL ..scaled.. <- NULL Prey <- NULL # Plot these values to represent the approximated probability densities figure <- ggplot(df_to_plot) + geom_density(aes(x = variable_to_plot, y = ..scaled.., fill = Prey), alpha = .3, adjust = 1/2, na.rm = TRUE) + geom_density(aes(x = variable_to_plot, y = ..scaled.., color = Prey), size = 1.25, adjust = 1/2, na.rm = TRUE) + ggtitle(paste(title, "\nfor the", colnames(data$o)[pred_index], "predator")) + ylab("Density") + scale_shape_manual(values = c(seq(1:10))) + guides(colour = guide_legend(byrow = 1, ncol = 1), shape = guide_legend(byrow = 1, ncol = 1)) + xlim(0, 1) + theme_bw() + theme(axis.title.x = element_blank(), plot.title = element_text(hjust = 0.5)) print(figure) if (save == TRUE){ ggsave(paste0("figure_", gsub(" ", "_", title), "_for_the_", colnames(data$o)[pred_index], "_predator", format(Sys.time(),'_%Y-%m-%d_%H-%M-%S'), ".png"), height = 4.4, width = 6.2, path = save_path) } } #' Plot the posterior means or probability distribution(s) #' #' @description This function plots the posterior means or probability distribution(s) for one #' or the two variable(s) of interest : the trophic link probabilities ("eta") and/or #' the diet proportions ("PI"). #' #' The figure(s) can be saved as PNG using: \code{save = TRUE}, and the directory path to which #' the figures are saved can be precised with: \code{save_path = "."}. #' #' If no "pred" nor "prey" parameter is entered, the plot will be a raster plot with the mean priors for #' all the trophic groups. #' #' If one predator name is entered as "pred", the probability distribution(s) will be plotted for all its #' prey(s) by default. Some specific prey(s) name(s) can also be entered because if a predator has #' 22 preys, plotting them all will make the plot hard to read. So you can specify the one or many prey(s) #' of interest and only display their corresponding probability distribution(s). #' #' The "variable" parameter can be specified if one wants to plot the priors for only one variable #' ("PI" or "eta"). #' #' @param jags_output the mcmc.list object output by the run_model() function #' @inheritParams plot_prior #' #' @examples #' #' \donttest{ #' realistic_biotracer_data <- read.csv(system.file("extdata", "realistic_biotracer_data.csv", #' package = "EcoDiet")) #' realistic_stomach_data <- read.csv(system.file("extdata", "realistic_stomach_data.csv", #' package = "EcoDiet")) #' #' data <- preprocess_data(biotracer_data = realistic_biotracer_data, #' trophic_discrimination_factor = c(0.8, 3.4), #' literature_configuration = FALSE, #' stomach_data = realistic_stomach_data) #' #' write_model(literature_configuration = FALSE) #' #' mcmc_output <- run_model("EcoDiet_model.txt", data, run_param="test") #' #' plot_results(mcmc_output, data) #' plot_results(mcmc_output, data, pred = "Crabs") #' plot_results(mcmc_output, data, pred = "Crabs", #' variable = "PI", prey = c("Bivalves", "Shrimps")) #' #' } #' #' @seealso \code{\link{plot_prior}} to plot the prior means or probability distribution(s), #' \code{\link{plot_data}} to plot the input data #' #' @export plot_results <- function(jags_output, data, pred = NULL, prey = NULL, variable = c("eta", "PI"), save = FALSE, save_path = "."){ if (!all(variable %in% c("eta", "PI"))){ stop("This function can only print a figure for the PI or eta variable.\n", " But you have entered this variable name: \"", variable, "\".\n", " Please use rather `variable = \"PI\"` or `variable = \"eta\"` for this function.") } mcmc_output <- as.matrix(jags_output$samples) for (var in variable){ if (is.null(pred) & is.null(prey)){ title <- switch(var, PI = "Mean of the posterior diet proportions", eta = "Mean of the posterior trophic link probabilities") mean <- extract_mean(mcmc_output, data, variable = var) plot_matrix(mean, title, save, save_path) } else { title <- switch(var, PI = "Marginal posterior distribution of the diet proportions", eta = "Marginal posterior distribution of the trophic link probabilities") plot_posterior_distribution(mcmc_output, data, pred, prey, variable = var, title, save, save_path) } } }
#week4 finalExcersie #Jorge Balderas #You should create one R script called run_analysis.R that does the following. #Merges the training and the test sets to create one data set. #Extracts only the measurements on the mean and standard deviation for each measurement. #Uses descriptive activity names to name the activities in the data set #Appropriately labels the data set with descriptive variable names. #From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. ---- library(data.table) library(dplyr) -- setwd("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test") setwd("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train") #Cols&Names and Activity Labels features <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/features.txt")[,2] activity_labels <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/activity_labels.txt")[,2] # TEST x_test <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test/X_test.txt") y_test <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test/y_test.txt") subject_test <-read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test/subject_test.txt") # TRAIN x_train <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train/X_train.txt") y_train <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train/y_train.txt") subject_train <-read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train/subject_train.txt") # mean & Std names (x_test) = features names (x_train) = features extract_features <- grepl("mean|std", features) x_test1= x_test[,extract_features] x_train1 = x_train[,extract_features] # Labels y_test[,2] = activity_labels[y_test[,1]] y_train[,2] = activity_labels[y_train[,1]] names(y_test) = c("Activity_ID", "Activity_Label") names(y_train) = c("Activity_ID", "Activity_Label") names(subject_test) = "subject" names(subject_train) = "subject" ### Data test_data <- cbind(subject_test, y_test, x_test1) train_data <- cbind(subject_train, y_train, x_train1) finaldata = rbind(test_data, train_data) dim(finaldata) finaldataavg <- aggregate(.~finaldata$Activity_Label, finaldata, mean) write.table(finaldataavg, "tidy.txt", row.name = FALSE) dim(finaldataavg)
/run_analysis.R
no_license
Jgbalderasa/Getting-and-Cleaning-Data-Course-Project
R
false
false
2,784
r
#week4 finalExcersie #Jorge Balderas #You should create one R script called run_analysis.R that does the following. #Merges the training and the test sets to create one data set. #Extracts only the measurements on the mean and standard deviation for each measurement. #Uses descriptive activity names to name the activities in the data set #Appropriately labels the data set with descriptive variable names. #From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. ---- library(data.table) library(dplyr) -- setwd("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test") setwd("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train") #Cols&Names and Activity Labels features <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/features.txt")[,2] activity_labels <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/activity_labels.txt")[,2] # TEST x_test <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test/X_test.txt") y_test <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test/y_test.txt") subject_test <-read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/test/subject_test.txt") # TRAIN x_train <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train/X_train.txt") y_train <- read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train/y_train.txt") subject_train <-read.table("C:/Users/jorge.balderas.ayala/Documents/R/data/Getting and Cleaning Data/UCI HAR Dataset/train/subject_train.txt") # mean & Std names (x_test) = features names (x_train) = features extract_features <- grepl("mean|std", features) x_test1= x_test[,extract_features] x_train1 = x_train[,extract_features] # Labels y_test[,2] = activity_labels[y_test[,1]] y_train[,2] = activity_labels[y_train[,1]] names(y_test) = c("Activity_ID", "Activity_Label") names(y_train) = c("Activity_ID", "Activity_Label") names(subject_test) = "subject" names(subject_train) = "subject" ### Data test_data <- cbind(subject_test, y_test, x_test1) train_data <- cbind(subject_train, y_train, x_train1) finaldata = rbind(test_data, train_data) dim(finaldata) finaldataavg <- aggregate(.~finaldata$Activity_Label, finaldata, mean) write.table(finaldataavg, "tidy.txt", row.name = FALSE) dim(finaldataavg)
#' Dependency Summary (Console Output) #' #' This function gives a summary of the dependency structure of a given package #' and points out opportunities to eliminate depdendencies completely. The default #' assumption is that there is an R package in the current working #' directory and that the dependencies to be analyzed are given in the DESCRIPTION #' file. Use the parameters ‘githublink’ and/or 'pkg' to alter the package/s #' to be analyzed. #' @param githublink A link to a github repository of an R package. #' @param pkg Character vector of CRAN package name/s you want to see the #' dependencies of. In the case that githublink is also set, the github package #' is considered as the root package and the packages provided #' by the pkg parameter are considered to be first level packages, e.g. on #' the same level as the packages in the DESCRIPTION file of the github package. #' This is to help answer the question "How would the dependency structure change #' if the package on github would also depend on a few more packages (provided by #' the pkg parameter)?". #' @param includebasepkgs Whether to include base packages in the analysis. #' @export #' @examples #' dstr(githublink = "tidyverse/ggplot2", #' pkg = c("astro", "celestial"), includebasepkgs = TRUE) dstr <- function(githublink = NULL, pkg = NULL, includebasepkgs = F){ writeLines("Loading...\n") data <- dstr_data(githublink, pkg, c("root", "unique2", "all", "list"), includebasepkgs = includebasepkgs) uniquelist <- data[[2]] allpkg <- data[[3]] dlist <- data[[4]] if(is.null(githublink) & !is.null(pkg)){ writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF { ", paste0(pkg, collapse = ", ")," } ---")) } else if(is.null(pkg) & !is.null(githublink)){ writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF '", data[[1]],"' ---")) } else if(!is.null(pkg) & !is.null(githublink)){ writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF '", data[[1]], " + { ",paste0(pkg, collapse = ", ")," }' ---")) } else { writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF '", data[[1]],"' ---")) } if(!includebasepkgs){ writeLines("Base packages are ignored in this analysis.") } writeLines("\n") if(is.null(pkg)){ writeLines(paste0("First Level Dependencies (Packages Found In The DESCRIPTION File) (", length(data[[2]]),")")) } else if (!is.null(githublink)){ # both githublink and pkg are set writeLines(paste0("First Level Dependencies (Packages Found In The DESCRIPTION File)", "\n+ Input Packages From The 'pkg' Parameter (", length(data[[2]])," In Total)")) } else { # only pkg is set # writeLines(paste0("Input Packages From The 'pkg' Parameter (", # length(data[[2]]),")")) writeLines(paste0("First Level Dependencies (Packages Found In The DESCRIPTION File/s", "\nOf The Specified Package/s In The 'pkg' Parameter) (", length(data[[2]]),")")) } paragraphsep___ <- paste0(rep("-", 80), collapse = "") writeLines(paragraphsep___) #writeLines(paste(names(data[[2]]), collapse = ", ")) print(names(data[[2]])) writeLines("\n") writeLines(paste("All", length(data[[3]]), "Eventually Loaded Packages (Dependencies Of Dependencies Of...)")) writeLines(paragraphsep___) print(data[[3]]) writeLines("\n") writeLines("Opportunities To Reduce Dependencies (Iterating Through All First Level Dependencies)") writeLines(paragraphsep___) # Sort the list so that packages with most dependencies are first in list uniquelist <- uniquelist[names(sort(sapply(uniquelist, length), decreasing = T))] for (j in 1:length(uniquelist)){ if(length(uniquelist[[j]]) > 1){ writeLines(paste0("If you remove '", names(uniquelist)[j], "' you will remove the following ", length(uniquelist[[j]]), " packages completely:")) print(uniquelist[[j]]) } else if (length(uniquelist[[j]]) == 1){ writeLines(paste0("If you remove '", names(uniquelist)[j], "' you will remove the following ", length(uniquelist[[j]]), " package completely:")) print(uniquelist[[j]]) } else { sought <- names(uniquelist)[j] soughtinlist <- sapply(dlist, function(x) sought %in% x) loaders <- names(soughtinlist)[soughtinlist] writeLines(paste0("If you remove '", names(uniquelist)[j],"' you will remove 0 other packages and also not '", names(uniquelist)[j], "' istelf because it is a deeper level dependency from the following first level dependencies:")) print(loaders) } writeLines("\n") } writeLines("Shared Dependencies / Hard To Remove") writeLines(paragraphsep___) shareddeps <- list() for(i in 1:length(allpkg)){ soughtinlist <- sapply(dlist, function(y) allpkg[i] %in% y) loaders <- names(soughtinlist)[soughtinlist] if(length(loaders) > 1){ shareddeps[[length(shareddeps)+1]] <- loaders names(shareddeps)[length(shareddeps)] <- allpkg[i] } } if(length(shareddeps) > 0){ # Sort the list so that packages with most dependencies are first in list shareddeps <- shareddeps[names(sort(sapply(shareddeps, length), decreasing = T))] unique_loaders <- unique(shareddeps) #sapply(shareddeps, function(x){all(x == y)}) collapsed_loaded <- lapply(unique_loaders, function(y) names(shareddeps)[sapply(shareddeps, function(x){identical(x, y)})]) for(i in 1:length(unique_loaders)){ #writeLines(paste0("The packages '", paste(collapsed_loaded[[i]], collapse = ", "), # "' are loaded by your (",length(unique_loaders[[i]]) ,") first level packages '", # paste(unique_loaders[[i]], collapse = ", ", "'"))) writeLines(paste0(length(unique_loaders[[i]]), " first level packages ('", paste0(unique_loaders[[i]], collapse = ", ", "'"), ") depend on the following packages:")) print(collapsed_loaded[[i]]) writeLines("\n") } } else { writeLines("You don't have shared dependencies, e.g. none of the ulimatively loaded packages is loaded because of two or more first level packages.") } }
/R/dstr.R
no_license
iagomosqueira/dstr
R
false
false
6,688
r
#' Dependency Summary (Console Output) #' #' This function gives a summary of the dependency structure of a given package #' and points out opportunities to eliminate depdendencies completely. The default #' assumption is that there is an R package in the current working #' directory and that the dependencies to be analyzed are given in the DESCRIPTION #' file. Use the parameters ‘githublink’ and/or 'pkg' to alter the package/s #' to be analyzed. #' @param githublink A link to a github repository of an R package. #' @param pkg Character vector of CRAN package name/s you want to see the #' dependencies of. In the case that githublink is also set, the github package #' is considered as the root package and the packages provided #' by the pkg parameter are considered to be first level packages, e.g. on #' the same level as the packages in the DESCRIPTION file of the github package. #' This is to help answer the question "How would the dependency structure change #' if the package on github would also depend on a few more packages (provided by #' the pkg parameter)?". #' @param includebasepkgs Whether to include base packages in the analysis. #' @export #' @examples #' dstr(githublink = "tidyverse/ggplot2", #' pkg = c("astro", "celestial"), includebasepkgs = TRUE) dstr <- function(githublink = NULL, pkg = NULL, includebasepkgs = F){ writeLines("Loading...\n") data <- dstr_data(githublink, pkg, c("root", "unique2", "all", "list"), includebasepkgs = includebasepkgs) uniquelist <- data[[2]] allpkg <- data[[3]] dlist <- data[[4]] if(is.null(githublink) & !is.null(pkg)){ writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF { ", paste0(pkg, collapse = ", ")," } ---")) } else if(is.null(pkg) & !is.null(githublink)){ writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF '", data[[1]],"' ---")) } else if(!is.null(pkg) & !is.null(githublink)){ writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF '", data[[1]], " + { ",paste0(pkg, collapse = ", ")," }' ---")) } else { writeLines(paste0("--- [dstr] DEPENDENCY STRUCTURE ANALYSIS OF '", data[[1]],"' ---")) } if(!includebasepkgs){ writeLines("Base packages are ignored in this analysis.") } writeLines("\n") if(is.null(pkg)){ writeLines(paste0("First Level Dependencies (Packages Found In The DESCRIPTION File) (", length(data[[2]]),")")) } else if (!is.null(githublink)){ # both githublink and pkg are set writeLines(paste0("First Level Dependencies (Packages Found In The DESCRIPTION File)", "\n+ Input Packages From The 'pkg' Parameter (", length(data[[2]])," In Total)")) } else { # only pkg is set # writeLines(paste0("Input Packages From The 'pkg' Parameter (", # length(data[[2]]),")")) writeLines(paste0("First Level Dependencies (Packages Found In The DESCRIPTION File/s", "\nOf The Specified Package/s In The 'pkg' Parameter) (", length(data[[2]]),")")) } paragraphsep___ <- paste0(rep("-", 80), collapse = "") writeLines(paragraphsep___) #writeLines(paste(names(data[[2]]), collapse = ", ")) print(names(data[[2]])) writeLines("\n") writeLines(paste("All", length(data[[3]]), "Eventually Loaded Packages (Dependencies Of Dependencies Of...)")) writeLines(paragraphsep___) print(data[[3]]) writeLines("\n") writeLines("Opportunities To Reduce Dependencies (Iterating Through All First Level Dependencies)") writeLines(paragraphsep___) # Sort the list so that packages with most dependencies are first in list uniquelist <- uniquelist[names(sort(sapply(uniquelist, length), decreasing = T))] for (j in 1:length(uniquelist)){ if(length(uniquelist[[j]]) > 1){ writeLines(paste0("If you remove '", names(uniquelist)[j], "' you will remove the following ", length(uniquelist[[j]]), " packages completely:")) print(uniquelist[[j]]) } else if (length(uniquelist[[j]]) == 1){ writeLines(paste0("If you remove '", names(uniquelist)[j], "' you will remove the following ", length(uniquelist[[j]]), " package completely:")) print(uniquelist[[j]]) } else { sought <- names(uniquelist)[j] soughtinlist <- sapply(dlist, function(x) sought %in% x) loaders <- names(soughtinlist)[soughtinlist] writeLines(paste0("If you remove '", names(uniquelist)[j],"' you will remove 0 other packages and also not '", names(uniquelist)[j], "' istelf because it is a deeper level dependency from the following first level dependencies:")) print(loaders) } writeLines("\n") } writeLines("Shared Dependencies / Hard To Remove") writeLines(paragraphsep___) shareddeps <- list() for(i in 1:length(allpkg)){ soughtinlist <- sapply(dlist, function(y) allpkg[i] %in% y) loaders <- names(soughtinlist)[soughtinlist] if(length(loaders) > 1){ shareddeps[[length(shareddeps)+1]] <- loaders names(shareddeps)[length(shareddeps)] <- allpkg[i] } } if(length(shareddeps) > 0){ # Sort the list so that packages with most dependencies are first in list shareddeps <- shareddeps[names(sort(sapply(shareddeps, length), decreasing = T))] unique_loaders <- unique(shareddeps) #sapply(shareddeps, function(x){all(x == y)}) collapsed_loaded <- lapply(unique_loaders, function(y) names(shareddeps)[sapply(shareddeps, function(x){identical(x, y)})]) for(i in 1:length(unique_loaders)){ #writeLines(paste0("The packages '", paste(collapsed_loaded[[i]], collapse = ", "), # "' are loaded by your (",length(unique_loaders[[i]]) ,") first level packages '", # paste(unique_loaders[[i]], collapse = ", ", "'"))) writeLines(paste0(length(unique_loaders[[i]]), " first level packages ('", paste0(unique_loaders[[i]], collapse = ", ", "'"), ") depend on the following packages:")) print(collapsed_loaded[[i]]) writeLines("\n") } } else { writeLines("You don't have shared dependencies, e.g. none of the ulimatively loaded packages is loaded because of two or more first level packages.") } }
# This module create investment return series. gen_returns <- function( sim_paramlist_ = sim_paramlist, Global_paramlist_ = Global_paramlist, returnScenarios_ = returnScenarios ){ ## Unquote for development # sim_paramlist_ = sim_paramlist # Global_paramlist_ = Global_paramlist # returnScenarios_ = returnScenarios assign_parmsList(Global_paramlist_, envir = environment()) assign_parmsList(sim_paramlist_, envir = environment()) ## Constant return distributions defined by mean and sd if(return_type == "simple"){ set.seed(sim_paramlist$seed) i.r <- matrix(rnorm(nyear*nsim, ir.mean, ir.sd), nyear, nsim) i.r <- cbind(rep(ir.mean - ir.sd^2/2, nyear), i.r) # add deterministic returns colnames(i.r) <- 0:nsim } ## Time varying return distributions defined by scenarios if (return_type == "internal"){ # return_scenario <- "RS1" # nsim = 5 returnScenarios_local <- returnScenarios_ %>% filter(scenario == return_scenario) set.seed(sim_paramlist_$seed) i.r <- cbind( with(returnScenarios_local, create_returns(return_det, 0, period)), # add deterministic returns replicate(nsim, with(returnScenarios_local, create_returns(r.mean, r.sd, period))) ) colnames(i.r) <- 0:nsim } ## T i.r <- cbind(rep(i, nyear), i.r) # add constant return that equals discount rate for checking model consistency i.shock <- i.r[, 2] i.shock[3:6] <- c(-0.24, 0.12, 0.12, 0.12) i.r <- cbind(i.shock, i.r) colnames(i.r) <- c(-2:nsim) return(i.r) } #gen_returns()[,2]
/model/simulation/model_sim_invReturns.R
no_license
yimengyin16/model_SJ
R
false
false
1,634
r
# This module create investment return series. gen_returns <- function( sim_paramlist_ = sim_paramlist, Global_paramlist_ = Global_paramlist, returnScenarios_ = returnScenarios ){ ## Unquote for development # sim_paramlist_ = sim_paramlist # Global_paramlist_ = Global_paramlist # returnScenarios_ = returnScenarios assign_parmsList(Global_paramlist_, envir = environment()) assign_parmsList(sim_paramlist_, envir = environment()) ## Constant return distributions defined by mean and sd if(return_type == "simple"){ set.seed(sim_paramlist$seed) i.r <- matrix(rnorm(nyear*nsim, ir.mean, ir.sd), nyear, nsim) i.r <- cbind(rep(ir.mean - ir.sd^2/2, nyear), i.r) # add deterministic returns colnames(i.r) <- 0:nsim } ## Time varying return distributions defined by scenarios if (return_type == "internal"){ # return_scenario <- "RS1" # nsim = 5 returnScenarios_local <- returnScenarios_ %>% filter(scenario == return_scenario) set.seed(sim_paramlist_$seed) i.r <- cbind( with(returnScenarios_local, create_returns(return_det, 0, period)), # add deterministic returns replicate(nsim, with(returnScenarios_local, create_returns(r.mean, r.sd, period))) ) colnames(i.r) <- 0:nsim } ## T i.r <- cbind(rep(i, nyear), i.r) # add constant return that equals discount rate for checking model consistency i.shock <- i.r[, 2] i.shock[3:6] <- c(-0.24, 0.12, 0.12, 0.12) i.r <- cbind(i.shock, i.r) colnames(i.r) <- c(-2:nsim) return(i.r) } #gen_returns()[,2]
############################################################## # seperate and total variance # ############################################################## variance<-function(){ varmat<-matrix(0,10,6) colnames(varmat)<-c("variance1-200","variance201-400", "variance401-600","variance601-800", "variance801-1000","intergratedVariance") for (i in 1:10) { #variance of sections varmat[i,1]<-round(var(dataList[[i]][c(1,200),"Close"]),digits = 3) varmat[i,2]<-round(var(dataList[[i]][c(201,400),"Close"]),digits = 3) varmat[i,3]<-round(var(dataList[[i]][c(401,600),"Close"]),digits = 3) varmat[i,4]<-round(var(dataList[[i]][c(601,800),"Close"]),digits = 3) varmat[i,5]<-round(var(dataList[[i]][c(801,1000),"Close"]),digits = 3) #integrated variance varmat[i,6]<-round(var(dataList[[i]][,"Close"]),digits = 3) } plot.zoo(varmat,xlab = c(1,10),ylab = c("1-200","201-400","401-600", "601-800","801-1000")) return(varmat) }
/variance.R
no_license
TANKERS888/COMP396
R
false
false
1,037
r
############################################################## # seperate and total variance # ############################################################## variance<-function(){ varmat<-matrix(0,10,6) colnames(varmat)<-c("variance1-200","variance201-400", "variance401-600","variance601-800", "variance801-1000","intergratedVariance") for (i in 1:10) { #variance of sections varmat[i,1]<-round(var(dataList[[i]][c(1,200),"Close"]),digits = 3) varmat[i,2]<-round(var(dataList[[i]][c(201,400),"Close"]),digits = 3) varmat[i,3]<-round(var(dataList[[i]][c(401,600),"Close"]),digits = 3) varmat[i,4]<-round(var(dataList[[i]][c(601,800),"Close"]),digits = 3) varmat[i,5]<-round(var(dataList[[i]][c(801,1000),"Close"]),digits = 3) #integrated variance varmat[i,6]<-round(var(dataList[[i]][,"Close"]),digits = 3) } plot.zoo(varmat,xlab = c(1,10),ylab = c("1-200","201-400","401-600", "601-800","801-1000")) return(varmat) }
unzipFile <- "household_power_consumption.txt" downloadFile <- "household_power_consumption.zip" downloadLink <- "https://d396qusza40orc.cloudfront.net/exdata/data/household_power_consumption.zip" plot3 <- function(){ ## Check if dataset file has already been unzipped if(!file.exists(unzipFile)){ ## Check if file has already been downloaded if (!file.exists(downloadFile)){ ## File not downloaded, hence download file download.file(downloadLink, downloadFile) } else { ## File already downloaded } ## now Unzip file and extract dataset unzip(downloadFile) } else { ## Dataset file exist already } t <- read.table("household_power_consumption.txt", header=TRUE, sep=";", na.strings = "?", colClasses = c('character','character','numeric','numeric','numeric','numeric','numeric','numeric','numeric')) ## Format date to Type Date t$Date <- as.Date(t$Date, "%d/%m/%Y") ## Filter data set from Feb. 1, 2007 to Feb. 2, 2007 t <- subset(t,Date >= as.Date("2007-2-1") & Date <= as.Date("2007-2-2")) ## Remove incomplete observation t <- t[complete.cases(t),] ## Combine Date and Time column dateTime <- paste(t$Date, t$Time) ## Name the vector dateTime <- setNames(dateTime, "DateTime") ## Remove Date and Time column t <- t[ ,!(names(t) %in% c("Date","Time"))] ## Add DateTime column t <- cbind(dateTime, t) ## Format dateTime Column t$dateTime <- as.POSIXct(dateTime) with(t, { plot(Sub_metering_1~dateTime, type="l", ylab="Global Active Power (kilowatts)", xlab="") lines(Sub_metering_2~dateTime,col='Red') lines(Sub_metering_3~dateTime,col='Blue') }) legend("topright", col=c("black", "red", "blue"), lwd=c(1,1,1), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) ## Saving to file dev.copy(png, file="plot3.png", height=480, width=480) dev.off() }
/plot3.R
no_license
Vichar-Dev/ExData_Plotting1
R
false
false
1,951
r
unzipFile <- "household_power_consumption.txt" downloadFile <- "household_power_consumption.zip" downloadLink <- "https://d396qusza40orc.cloudfront.net/exdata/data/household_power_consumption.zip" plot3 <- function(){ ## Check if dataset file has already been unzipped if(!file.exists(unzipFile)){ ## Check if file has already been downloaded if (!file.exists(downloadFile)){ ## File not downloaded, hence download file download.file(downloadLink, downloadFile) } else { ## File already downloaded } ## now Unzip file and extract dataset unzip(downloadFile) } else { ## Dataset file exist already } t <- read.table("household_power_consumption.txt", header=TRUE, sep=";", na.strings = "?", colClasses = c('character','character','numeric','numeric','numeric','numeric','numeric','numeric','numeric')) ## Format date to Type Date t$Date <- as.Date(t$Date, "%d/%m/%Y") ## Filter data set from Feb. 1, 2007 to Feb. 2, 2007 t <- subset(t,Date >= as.Date("2007-2-1") & Date <= as.Date("2007-2-2")) ## Remove incomplete observation t <- t[complete.cases(t),] ## Combine Date and Time column dateTime <- paste(t$Date, t$Time) ## Name the vector dateTime <- setNames(dateTime, "DateTime") ## Remove Date and Time column t <- t[ ,!(names(t) %in% c("Date","Time"))] ## Add DateTime column t <- cbind(dateTime, t) ## Format dateTime Column t$dateTime <- as.POSIXct(dateTime) with(t, { plot(Sub_metering_1~dateTime, type="l", ylab="Global Active Power (kilowatts)", xlab="") lines(Sub_metering_2~dateTime,col='Red') lines(Sub_metering_3~dateTime,col='Blue') }) legend("topright", col=c("black", "red", "blue"), lwd=c(1,1,1), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) ## Saving to file dev.copy(png, file="plot3.png", height=480, width=480) dev.off() }
\name{founder.event} \alias{founder.event} \title{Simulation of a founder event} \usage{ founder.event(p0=0.5,Ne=1000,Nf=10,ttime=100,etime=50,show="p") } \arguments{ \item{p0}{Starting frequency for the A allele.} \item{Ne}{Effective population size at the start of the simulation and after the founding event.} \item{Nf}{Size of the founding population.} \item{ttime}{Total time of the simulation.} \item{etime}{Time for the founding event.} \item{show}{Two different options for plotting. \code{"p"} shows the frequency of the A allele through time; \code{"var"} shows the genetic variation in the population, calculated as p*(1-p). The default is \code{show="p"}.} } \description{ This function simulates genetic drift with a founding event at time \code{etime}. } \value{ The function creates one of two different plots, depending on the value of \code{show}. } \author{Liam Revell \email{liam.revell@umb.edu}} \seealso{ \code{\link{genetic.drift}} } \examples{ founder.event() founder.event(show="variation") } \keyword{population genetics} \keyword{drift}
/man/founder.event.Rd
no_license
jmallon/PopGen
R
false
false
1,076
rd
\name{founder.event} \alias{founder.event} \title{Simulation of a founder event} \usage{ founder.event(p0=0.5,Ne=1000,Nf=10,ttime=100,etime=50,show="p") } \arguments{ \item{p0}{Starting frequency for the A allele.} \item{Ne}{Effective population size at the start of the simulation and after the founding event.} \item{Nf}{Size of the founding population.} \item{ttime}{Total time of the simulation.} \item{etime}{Time for the founding event.} \item{show}{Two different options for plotting. \code{"p"} shows the frequency of the A allele through time; \code{"var"} shows the genetic variation in the population, calculated as p*(1-p). The default is \code{show="p"}.} } \description{ This function simulates genetic drift with a founding event at time \code{etime}. } \value{ The function creates one of two different plots, depending on the value of \code{show}. } \author{Liam Revell \email{liam.revell@umb.edu}} \seealso{ \code{\link{genetic.drift}} } \examples{ founder.event() founder.event(show="variation") } \keyword{population genetics} \keyword{drift}
Geocode_Combined<-function(tidy_tracks,stormvalue,cname){ tryCatch ( { CountryMap = ggmap(get_googlemap(center=as.numeric(geocode(cname)), scale=2, zoom=4), extent="normal") }, warning = function(w) { message("Failure to fetch geo-location. Try again ") message(w) return(NULL) }, error = function(e) { message("error Failure to fetch geo-location. Try again ") message(e) return(NULL) } ) finalgeom = CountryMap tidy_tracks1 <- subset(tidy_tracks,storm_id_unique == stormvalue & ne > 0 & nw > 0 & se > 0 & sw > 0) KATRINA2005f = tidy_tracks1 filter1 = unique(KATRINA2005f$latitude) track_list1<- vector("list", length(filter1)) code1<- vector("list", nrow(KATRINA2005f)) filter1 = unique(KATRINA2005f$latitude) for (k in 1: length(filter1)) { tidy_tracks2 <- subset(KATRINA2005f, latitude == filter1[k]) tidy_tracks2<- tidy_tracks2 %>% mutate(ne = ne*1852*1,se = se*1852*1, sw = sw*1852*1, nw = nw*1852*1 ) l_points_1 = setNames(data.frame(matrix(ncol = 9, nrow = 0)), c("longitude", "latitude","stormid","wind_speed","ne","se","sw","nw")) x_tracks = tidy_tracks2 for (i in 1:nrow(x_tracks)) { ne_tracks <- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 1:90,d = x_tracks[i,]$ne)) ne_tracks$latitude <- x_tracks[i,]$latitude ne_tracks$longitude <- x_tracks[i,]$longitude ne_tracks$stormid <- x_tracks[i,]$storm_id_unique ne_tracks$wind_speed<- x_tracks[i,]$wind_speed ne_tracks$ne = x_tracks[i,]$ne ne_tracks$se = x_tracks[i,]$se ne_tracks$sw = x_tracks[i,]$sw ne_tracks$nw = x_tracks[i,]$nw nw_tracks<- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 271:360,d = x_tracks[i,]$nw)) nw_tracks$latitude <- x_tracks[i,]$latitude nw_tracks$longitude <- x_tracks[i,]$longitude nw_tracks$stormid <- x_tracks[i,]$storm_id_unique nw_tracks$wind_speed<-x_tracks[i,]$wind_speed nw_tracks$ne = x_tracks[i,]$ne nw_tracks$se = x_tracks[i,]$se nw_tracks$sw = x_tracks[i,]$sw nw_tracks$nw = x_tracks[i,]$nw se_tracks <- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 91:180,d = x_tracks[i,]$se)) se_tracks$latitude <- x_tracks[i,]$latitude se_tracks$longitude <- x_tracks[i,]$longitude se_tracks$stormid <- x_tracks[i,]$storm_id_unique se_tracks$wind_speed<-x_tracks[i,]$wind_speed se_tracks$ne = x_tracks[i,]$ne se_tracks$se = x_tracks[i,]$se se_tracks$sw = x_tracks[i,]$sw se_tracks$nw = x_tracks[i,]$nw sw_tracks <- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 181:270,d = x_tracks[i,]$sw)) sw_tracks$latitude <- x_tracks[i,]$latitude sw_tracks$longitude <- x_tracks[i,]$longitude sw_tracks$stormid <- x_tracks[i,]$storm_id_unique sw_tracks$wind_speed<-x_tracks[i,]$wind_speed sw_tracks$ne = x_tracks[i,]$ne sw_tracks$se = x_tracks[i,]$se sw_tracks$sw = x_tracks[i,]$sw sw_tracks$nw = x_tracks[i,]$nw l_points <- dplyr::bind_rows(list(ne_tracks,se_tracks,sw_tracks,nw_tracks)) l_points_1 = dplyr::bind_rows(list(l_points,l_points_1)) } track_list1[[k]] = l_points_1 } for (k in 1:length(track_list1)){ track_list1[[k]]$wind_speed = as.factor(track_list1[[k]]$wind_speed) } for (k in 1:length(track_list1)){ finalgeom= finalgeom + geom_hurricane(data = track_list1[[k]], aes(x = lon, y = lat, ne = ne, se = se, nw = nw,sw = sw, fill = wind_speed, color = wind_speed)) + scale_color_manual(name = "Wind speed (kts)", values = c("red", "orange", "yellow")) + scale_fill_manual(name = "Wind speed (kts)", values = c("red", "orange", "yellow"))} return(finalgeom) }
/R/geocode - clubbed.R
no_license
vanita1/Hurricane1
R
false
false
3,944
r
Geocode_Combined<-function(tidy_tracks,stormvalue,cname){ tryCatch ( { CountryMap = ggmap(get_googlemap(center=as.numeric(geocode(cname)), scale=2, zoom=4), extent="normal") }, warning = function(w) { message("Failure to fetch geo-location. Try again ") message(w) return(NULL) }, error = function(e) { message("error Failure to fetch geo-location. Try again ") message(e) return(NULL) } ) finalgeom = CountryMap tidy_tracks1 <- subset(tidy_tracks,storm_id_unique == stormvalue & ne > 0 & nw > 0 & se > 0 & sw > 0) KATRINA2005f = tidy_tracks1 filter1 = unique(KATRINA2005f$latitude) track_list1<- vector("list", length(filter1)) code1<- vector("list", nrow(KATRINA2005f)) filter1 = unique(KATRINA2005f$latitude) for (k in 1: length(filter1)) { tidy_tracks2 <- subset(KATRINA2005f, latitude == filter1[k]) tidy_tracks2<- tidy_tracks2 %>% mutate(ne = ne*1852*1,se = se*1852*1, sw = sw*1852*1, nw = nw*1852*1 ) l_points_1 = setNames(data.frame(matrix(ncol = 9, nrow = 0)), c("longitude", "latitude","stormid","wind_speed","ne","se","sw","nw")) x_tracks = tidy_tracks2 for (i in 1:nrow(x_tracks)) { ne_tracks <- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 1:90,d = x_tracks[i,]$ne)) ne_tracks$latitude <- x_tracks[i,]$latitude ne_tracks$longitude <- x_tracks[i,]$longitude ne_tracks$stormid <- x_tracks[i,]$storm_id_unique ne_tracks$wind_speed<- x_tracks[i,]$wind_speed ne_tracks$ne = x_tracks[i,]$ne ne_tracks$se = x_tracks[i,]$se ne_tracks$sw = x_tracks[i,]$sw ne_tracks$nw = x_tracks[i,]$nw nw_tracks<- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 271:360,d = x_tracks[i,]$nw)) nw_tracks$latitude <- x_tracks[i,]$latitude nw_tracks$longitude <- x_tracks[i,]$longitude nw_tracks$stormid <- x_tracks[i,]$storm_id_unique nw_tracks$wind_speed<-x_tracks[i,]$wind_speed nw_tracks$ne = x_tracks[i,]$ne nw_tracks$se = x_tracks[i,]$se nw_tracks$sw = x_tracks[i,]$sw nw_tracks$nw = x_tracks[i,]$nw se_tracks <- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 91:180,d = x_tracks[i,]$se)) se_tracks$latitude <- x_tracks[i,]$latitude se_tracks$longitude <- x_tracks[i,]$longitude se_tracks$stormid <- x_tracks[i,]$storm_id_unique se_tracks$wind_speed<-x_tracks[i,]$wind_speed se_tracks$ne = x_tracks[i,]$ne se_tracks$se = x_tracks[i,]$se se_tracks$sw = x_tracks[i,]$sw se_tracks$nw = x_tracks[i,]$nw sw_tracks <- base::data.frame(geosphere::destPoint(p = c(x_tracks[i,]$longitude,x_tracks[i,]$latitude),b = 181:270,d = x_tracks[i,]$sw)) sw_tracks$latitude <- x_tracks[i,]$latitude sw_tracks$longitude <- x_tracks[i,]$longitude sw_tracks$stormid <- x_tracks[i,]$storm_id_unique sw_tracks$wind_speed<-x_tracks[i,]$wind_speed sw_tracks$ne = x_tracks[i,]$ne sw_tracks$se = x_tracks[i,]$se sw_tracks$sw = x_tracks[i,]$sw sw_tracks$nw = x_tracks[i,]$nw l_points <- dplyr::bind_rows(list(ne_tracks,se_tracks,sw_tracks,nw_tracks)) l_points_1 = dplyr::bind_rows(list(l_points,l_points_1)) } track_list1[[k]] = l_points_1 } for (k in 1:length(track_list1)){ track_list1[[k]]$wind_speed = as.factor(track_list1[[k]]$wind_speed) } for (k in 1:length(track_list1)){ finalgeom= finalgeom + geom_hurricane(data = track_list1[[k]], aes(x = lon, y = lat, ne = ne, se = se, nw = nw,sw = sw, fill = wind_speed, color = wind_speed)) + scale_color_manual(name = "Wind speed (kts)", values = c("red", "orange", "yellow")) + scale_fill_manual(name = "Wind speed (kts)", values = c("red", "orange", "yellow"))} return(finalgeom) }
weld_bmillion <- function(filename){ lines <- readLines(filename) lines <- gsub("([0-9]) ([bm]illion)", "\\1~\\2", lines) writeLines(lines, filename) }
/R/weld_bmillion.R
permissive
grattaninstitute/Cost-overruns-report
R
false
false
159
r
weld_bmillion <- function(filename){ lines <- readLines(filename) lines <- gsub("([0-9]) ([bm]illion)", "\\1~\\2", lines) writeLines(lines, filename) }
#install and load plotrix-package / neccessary to use pyramid.plot install.packages("plotrix") library("plotrix") #function to calculate relative frequencies in % table for variable k with l different characteristics frequency = function(k, l){ if (missing(k)) stop("No data passed to the function. Variable k has to be defined.") if (missing(l)) stop("No data passed to the function. Variable l has to be defined.") 100*sweep(table(k,l), 2, colSums(table(k,l)), "/") } #function to build population pyramid and store it as pdf buildpopulation = function(k, l, popname){ if (missing(popname)) stop('No data passed to the function. Variable popname has to be defined. Please define a plot name such as "populationpyramid.pdf". Use quotation marks, at the beginning and the end of the plot name.') pop = frequency(k, l) pdf(popname) pyramid.plot(pop[,1], pop[,2], labels = rownames(pop), gap = 2, lxcol = "blue", rxcol = "red") dev.off() } #subsample with employees covered by the union contract (with FC or SC) datFCSC = dat[ which(SCTariffDummy == 1 | FCTariffDummy == 1),] #subsample with employees which ar not covered by the union contract (no FC & no SC) datNoFCSC = dat[ which(SCTariffDummy == 0 & FCTariffDummy == 0),] #population pyramid on the whole dataset buildpopulation(dat$ef41, dat$ef10, "population_all.pdf") #population pyramid of employees covered by the union contract buildpopulation(datFCSC$ef41, datFCSC$ef10, "populationFCSC.pdf") #population pyramid of employees not covered by the union contract buildpopulation(datNoFCSC$ef41, datNoFCSC$ef10, "population-noFCSC.pdf") #calculate arithmetic mean mean(dat$ef41, na.rm = TRUE) #all population mean(datFCSC$ef41, na.rm = TRUE) #subsample with union covered workers mean(datNoFCSC$ef41, na.rm = TRUE) #subsample with workers without a union contract #calculate median median(dat$ef41, na.rm = TRUE) #all population median(datFCSC$ef41, na.rm = TRUE) #subsample with union covered workers median(datNoFCSC$ef41, na.rm = TRUE) #subsample with workers without a union contract #function to simultaneously generate a boxplot and save it in the seperate pdf-file buildboxplot = function (v, w , boxname, z){ if (missing(v)) stop("No data passed to the function. Variable v has to be defined.") if (missing(w)) stop("No data passed to the function. Variable w has to be defined.") if (missing(z)) stop("No data passed to the function. Variable z has to be defined. z is a vector which should contain labels for the characteristics of the variable w. The number of the characteristics of w must equal the number of elements in z.") if (missing(boxname)) stop('No data passed to the function.boxname has to be defined such as "graph.pdf".') if (is.numeric(v)!= TRUE) stop("Numeric data needed. k has to be a numeric variable.") pdf(boxname, width = 11, height = 7) boxplot(v~w, range=2.5, width=NULL, notch=FALSE,varwidth=FALSE, names = z, boxwex=0.8, outline=FALSE, staplewex=0.5, horizontal=FALSE, border="black", col="#94d639", add=FALSE, at=NULL) abline(h = median(v, na.rm = TRUE), col="red", lwd = 1.5) dev.off() } #define a vector with label names for gender and education genderLAB = c("male", "female") educLAB = c("Educ A", "Educ B", "Educ C", "Educ D", "Educ E", "Educ F", "Educ G") #boxplot ln(wage)~gender of all employees buildboxplot(dat$lnWage, dat$ef10, "boxplot_lnwage_gen.pdf", genderLAB) #boxplot ln(wage)~education of all employees buildboxplot(dat$lnWage, dat$ef16u2, "boxplot_lnwage_educ.pdf", educLAB) #boxplot ln(wage)~education of employees which are covered by an union contract buildboxplot(datFCSC$lnWage, datFCSC$ef16u2, "boxploteducFCSC.pdf", educLAB) #boxplot ln(wage)~education of employees which are not covered by an union contract buildboxplot(datNoFCSC$lnWage, datNoFCSC$ef16u2, "boxploteduc-NoFCSC.pdf", educLAB) #calculate median of the variable ln(wage) median(dat$lnWage, na.rm = TRUE) median(datFCSC$lnWage, na.rm = TRUE) median(datNoFCSC$lnWage, na.rm = TRUE)
/SPLFreqPlot/SPLFreqPlot.R
no_license
maxr91/SPLUnionWageEffects
R
false
false
4,179
r
#install and load plotrix-package / neccessary to use pyramid.plot install.packages("plotrix") library("plotrix") #function to calculate relative frequencies in % table for variable k with l different characteristics frequency = function(k, l){ if (missing(k)) stop("No data passed to the function. Variable k has to be defined.") if (missing(l)) stop("No data passed to the function. Variable l has to be defined.") 100*sweep(table(k,l), 2, colSums(table(k,l)), "/") } #function to build population pyramid and store it as pdf buildpopulation = function(k, l, popname){ if (missing(popname)) stop('No data passed to the function. Variable popname has to be defined. Please define a plot name such as "populationpyramid.pdf". Use quotation marks, at the beginning and the end of the plot name.') pop = frequency(k, l) pdf(popname) pyramid.plot(pop[,1], pop[,2], labels = rownames(pop), gap = 2, lxcol = "blue", rxcol = "red") dev.off() } #subsample with employees covered by the union contract (with FC or SC) datFCSC = dat[ which(SCTariffDummy == 1 | FCTariffDummy == 1),] #subsample with employees which ar not covered by the union contract (no FC & no SC) datNoFCSC = dat[ which(SCTariffDummy == 0 & FCTariffDummy == 0),] #population pyramid on the whole dataset buildpopulation(dat$ef41, dat$ef10, "population_all.pdf") #population pyramid of employees covered by the union contract buildpopulation(datFCSC$ef41, datFCSC$ef10, "populationFCSC.pdf") #population pyramid of employees not covered by the union contract buildpopulation(datNoFCSC$ef41, datNoFCSC$ef10, "population-noFCSC.pdf") #calculate arithmetic mean mean(dat$ef41, na.rm = TRUE) #all population mean(datFCSC$ef41, na.rm = TRUE) #subsample with union covered workers mean(datNoFCSC$ef41, na.rm = TRUE) #subsample with workers without a union contract #calculate median median(dat$ef41, na.rm = TRUE) #all population median(datFCSC$ef41, na.rm = TRUE) #subsample with union covered workers median(datNoFCSC$ef41, na.rm = TRUE) #subsample with workers without a union contract #function to simultaneously generate a boxplot and save it in the seperate pdf-file buildboxplot = function (v, w , boxname, z){ if (missing(v)) stop("No data passed to the function. Variable v has to be defined.") if (missing(w)) stop("No data passed to the function. Variable w has to be defined.") if (missing(z)) stop("No data passed to the function. Variable z has to be defined. z is a vector which should contain labels for the characteristics of the variable w. The number of the characteristics of w must equal the number of elements in z.") if (missing(boxname)) stop('No data passed to the function.boxname has to be defined such as "graph.pdf".') if (is.numeric(v)!= TRUE) stop("Numeric data needed. k has to be a numeric variable.") pdf(boxname, width = 11, height = 7) boxplot(v~w, range=2.5, width=NULL, notch=FALSE,varwidth=FALSE, names = z, boxwex=0.8, outline=FALSE, staplewex=0.5, horizontal=FALSE, border="black", col="#94d639", add=FALSE, at=NULL) abline(h = median(v, na.rm = TRUE), col="red", lwd = 1.5) dev.off() } #define a vector with label names for gender and education genderLAB = c("male", "female") educLAB = c("Educ A", "Educ B", "Educ C", "Educ D", "Educ E", "Educ F", "Educ G") #boxplot ln(wage)~gender of all employees buildboxplot(dat$lnWage, dat$ef10, "boxplot_lnwage_gen.pdf", genderLAB) #boxplot ln(wage)~education of all employees buildboxplot(dat$lnWage, dat$ef16u2, "boxplot_lnwage_educ.pdf", educLAB) #boxplot ln(wage)~education of employees which are covered by an union contract buildboxplot(datFCSC$lnWage, datFCSC$ef16u2, "boxploteducFCSC.pdf", educLAB) #boxplot ln(wage)~education of employees which are not covered by an union contract buildboxplot(datNoFCSC$lnWage, datNoFCSC$ef16u2, "boxploteduc-NoFCSC.pdf", educLAB) #calculate median of the variable ln(wage) median(dat$lnWage, na.rm = TRUE) median(datFCSC$lnWage, na.rm = TRUE) median(datNoFCSC$lnWage, na.rm = TRUE)
## ---------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi <csardi.gabor@gmail.com> ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ---------------------------------------------------------------------- ################################################################### # Convert graphs to human readable forms ################################################################### .get.attr.codes <- function(object) { ga <- va <- ea <- "" gal <- graph_attr_names(object) if (length(gal) != 0) { ga <- paste(sep="", gal, " (g/", .Call("R_igraph_get_attr_mode", object, 2L, PACKAGE="igraph"), ")") } val <- vertex_attr_names(object) if (length(val) != 0) { va <- paste(sep="", val, " (v/", .Call("R_igraph_get_attr_mode", object, 3L, PACKAGE="igraph"), ")") } eal <- edge_attr_names(object) if (length(eal) != 0) { ea <- paste(sep="", edge_attr_names(object), " (e/", .Call("R_igraph_get_attr_mode", object, 4L, PACKAGE="igraph"), ")") } c(ga, va, ea) } .print.header <- function(object) { if (!is_igraph(object)) { stop("Not a graph object") } title <- paste(sep="", "IGRAPH ", c("U","D")[is_directed(object)+1], c("-","N")[is_named(object)+1], c("-","W")[is_weighted(object)+1], c("-","B")[is_bipartite(object)+1], " ", vcount(object), " ", ecount(object), " -- ") w <- getOption("width") if (nchar(title) < w && "name" %in% graph_attr_names(object)) { title <- substring(paste(sep="", title, as.character(object$name)[1]), 1, w-1) } cat(title, "\n", sep="") atxt <- .get.attr.codes(object) atxt <- paste(atxt[atxt!=""], collapse=", ") if (atxt != "") { atxt <- strwrap(paste(sep="", "+ attr: ", atxt), prefix = "| ", initial = "") cat(atxt, sep="\n") } 1 + if (length(atxt) == 1 && atxt == "") 0 else length(atxt) } indent_print <- printr$indent_print .print.graph.attributes <- function(x, full, max.lines) { list <- graph_attr_names(x) if (length(list)!=0) { cat("+ graph attributes:\n") out <- capture.output({ lapply(list, function(n) { cat(sep="", "+ ", n, ":\n") indent_print(graph_attr(x, n), .indent = " ") }) invisible(NULL) }) indent_print(out, sep = "\n", .indent = "| ", .printer = cat) length(out) + 1 } else { 0 } } ## IGRAPH U--- 10 10 -- Ring graph ## + attr: name (g/c), mutual (g/l), circular (g/l) ## + graph attributes: ## | + name: ## | [1] "Ring graph" ## | + mutual: ## | [1] FALSE ## | + circular= ## | [1] TRUE ## | + layout = ## | [,1] [,2] ## | [1,] 0.000000 0.000000e+00 ## | [2,] 1.000000 0.000000e+00 ## | [3,] 0.809017 5.877853e-01 ## | [4,] 0.309017 9.510565e-01 ## | [5,] -0.309017 9.510565e-01 ## | [6,] -0.809017 5.877853e-01 ## | [7,] -1.000000 1.224647e-16 ## | [8,] -0.809017 -5.877853e-01 ## | [9,] -0.309017 -9.510565e-01 ## | [10,] 0.309017 -9.510565e-01 ## | [11,] 0.809017 -5.877853e-01 ## + edges: ## [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10 .print.vertex.attributes <- function(x, full, max.lines) { pf <- function(x) .print.vertex.attributes.old(x, full, max.lines) if (length(vertex_attr_names(x))) cat("+ vertex attributes:\n") indent_print(x, .indent = "| ", .printer = pf) } .print.vertex.attributes.old <- function(x, full, max.lines) { vc <- vcount(x) list <- vertex_attr_names(x) if (length(list) != 0) { mp <- getOption("max.print") options(max.print=1000000000) if (vc <= mp) { omitted.vertices <- 0 ind <- as.numeric(V(x)) } else { omitted.vertices <- vc-mp ind <- seq(length=mp) } if (vc==0 || all(sapply(list, function(v) is.numeric(vertex_attr(x, v)) || is.character(vertex_attr(x, v)) || is.logical(vertex_attr(x, v))))) { ## create a table tab <- data.frame(v=paste(sep="", "[", ind, "]"), row.names="v") for (i in list) { tab[i] <- vertex_attr(x, i, ind) } print(tab) } else { for (i in ind) { cat(sep="", "[[", i, "]]\n") lapply(list, function(n) { cat(sep="", "[[", i, "]][[", n, "]]\n") print(vertex_attr(x, n, i))}) } } options(max.print=mp) if (omitted.vertices != 0) { cat(paste('[ reached getOption("max.print") -- omitted', omitted.vertices, "vertices ]\n\n")) } } } .print.edges.edgelist <- function(x, edges = E(x), names) { ec <- length(edges) list <- edge_attr_names(x) list <- list[list!="name"] arrow <- ifelse(is_directed(x), "->", "--") if (is_named(x)) { cat("+ edges (vertex names) and their attributes:\n") } else { cat("+ edges and their attributes:\n") } if (names && ! "name" %in% vertex_attr_names(x)) { names <- FALSE } if (names && "name" %in% vertex_attr_names(x) && !is.numeric(vertex_attr(x, "name")) && !is.character(vertex_attr(x, "name")) && !is.logical(vertex_attr(x, "name"))) { warning("Can't print vertex names, complex `name' vertex attribute") names <- FALSE } mp <- getOption("max.print") if (mp >= ec) { omitted.edges <- 0 el <- ends(x, edges, names=names) } else { omitted.edges <- ec-mp el <- ends(x, ends[seq_len(mp)]) if (names) { el[] <- V(x)$name[el] } } ename <- if ("name" %in% edge_attr_names(x)) { paste(sep="", "'", E(x)$name, "'") } else { seq(length=nrow(el)) } if (ec==0 || all(sapply(list, function(v) is.numeric(edge_attr(x, v)) | is.character(edge_attr(x,v)) | is.logical(edge_attr(x, v))))) { ## create a table tab <- data.frame(row.names=paste(sep="", "[", ename, "]")) if (is.numeric(el)) { w <- nchar(max(el)) } else { w <- max(nchar(el)) } tab["edge"] <- paste(sep="", format(el[,1], width=w), arrow, format(el[,2], width=w)) for (i in list) { tab[i] <- edge_attr(x, i) } print(tab) } else { i <- 1 apply(el, 1, function(v) { cat(sep="", "[", ename[i], "] ", v[1], " ", arrow, " ", v[2]); lapply(list, function(n) { cat(sep="", "\n[[", i, "]][[", n, "]]\n") print(edge_attr(x, n, i))}) cat("\n") i <<- i+1 }) } if (omitted.edges != 0) { cat(paste('[ reached getOption("max.print") -- omitted', omitted.edges, 'edges ]\n\n')) } } #' @include printr.R head_print <- printr$head_print printer_callback <- printr$printer_callback .print.edges.compressed <- function(x, edges = E(x), names, num = FALSE, max.lines = igraph_opt("auto.print.lines")) { len <- length(edges) title <- "+" %+% (if (num) " " %+% chr(len) %+% "/" %+% (if (is.null(x)) "?" else chr(gsize(x))) else "") %+% (if (len == 1) " edge" else " edges") %+% (if (is.null(x)) ", unknown graph" else "") %+% (if (is.null(attr(edges, "vnames"))) "" else " (vertex names)") %+% ":\n" cat(title) if (!is.null(attr(edges, "single")) && attr(edges, "single") && !is.null(x)) { ## Double bracket ea <- edge_attr(x) if (all(sapply(ea, is.atomic))) { etail <- tail_of(x, edges) ehead <- head_of(x, edges) df <- data.frame( stringsAsFactors = FALSE, tail = as_ids(etail), head = as_ids(ehead), tid = as.vector(etail), hid = as.vector(ehead) ) if (length(ea)) { ea <- do_call(data.frame, .args = ea, stringsAsFactors = FALSE) df <- cbind(df, ea[as.vector(edges), , drop = FALSE]) } print(df) } else { print(lapply(ea, "[", as.vector(edges))) } } else if (is.null(max.lines)) { .print.edges.compressed.all(x, edges, names) } else { .print.edges.compressed.limit(x, edges, names, max.lines) } } .print.edges.compressed.all <- function(x, edges, names) { arrow <- c("--", "->")[is_directed(x)+1] if (!is.null(x)) { el <- ends(x, edges, names=names) pr <- paste(sep="", format(el[,1]), arrow, format(el[,2])) print(pr, quote=FALSE) } else { if (!is.null(attr(edges, "vnames"))) { print(as.vector(attr(edges, "vnames")), quote = FALSE) } else if (!is.null(names(edges))) { print(names(edges), quote = FALSE) } else { print(as.vector(edges)) } } } .print.edges.compressed.limit <- function(x, edges, names, max.lines) { if (!is.null(x)) { arrow <- c("--", "->")[is_directed(x)+1] can_max <- NA el <- NA fun <- function(q, no) { if (q == "length") { length(edges) } else if (q == "min_width") { 5 } else if (q == "width") { el <<- ends(x, edges[seq_len(no)], names = names) cummax(nchar(el[,1])) + nchar(arrow) + cummax(nchar(el[,2])) + 1 } else if (q == "print") { el <<- el[seq_len(no), , drop = FALSE] out <- paste(sep="", format(el[,1]), arrow, format(el[,2])) capture.output(print(out, quote = FALSE)) } else if (q == "max") { can_max <<- no } else if (q == "done") { if (no["tried_items"] < length(edges) || no["printed_lines"] < no["tried_lines"]) { cat("+ ... omitted several edges\n") } } } fun <- printer_callback(fun) head_print(fun, max_lines = max.lines) } else { if (!is.null(attr(edges, "vnames"))) { head_print(as.vector(attr(edges, "vnames")), quote = FALSE) } else if (!is.null(names(edges))) { head_print(names(edges), quote = FALSE) } else { head_print(as.vector(edges)) } } } .print.edges.adjlist <- function(x) { ## TODO: getOption("max.print") cat("+ edges:\n") vc <- vcount(x) arrow <- c(" -- ", " -> ")[is_directed(x)+1] al <- as_adj_list(x, mode="out") w <- nchar(max(which(degree(x, mode="in") != 0))) mpl <- trunc((getOption("width")-nchar(arrow)-nchar(vc)) / (w+1)) if (any(sapply(al, length) > mpl)) { ## Wrapping needed mw <- nchar(vcount(x)) sm <- paste(collapse="", rep(" ", mw+4)) alstr <- lapply(seq_along(al), function(x) { len <- length(al[[x]]) fac <- rep(1:(len/mpl+1), each=mpl, length=len) nei <- tapply(format(al[[x]], width=mw), fac, paste, collapse=" ") mark <- paste(sep="", format(x, width=mw), arrow) mark <- c(mark, rep(sm, max(0, length(nei)-1))) paste(sep="", mark, nei) }) cat(unlist(alstr), sep="\n") } else { alstr <- sapply(al, function(x) { paste(format(x, width=w), collapse=" ") }) mark <- paste(sep="", format(seq_len(vc)), arrow) alstr <- paste(sep="", mark, alstr) maxw <- max(nchar(alstr)) sep <- " " ncol <- trunc((getOption("width")-1+nchar(sep)) / (maxw+nchar(sep))) if (ncol > 1) { alstr <- format(alstr, width=maxw, justify="left") fac <- rep(1:(vc/ncol+1), each=ncol, length=vc) alstr <- tapply(alstr, fac, paste, collapse=sep) } cat(alstr, sep="\n") } } .print.edges.adjlist.named <- function(x, edges = E(x)) { ## TODO getOption("max.print") cat("+ edges (vertex names):\n") arrow <- c(" -- ", " -> ")[is_directed(x)+1] vn <- V(x)$name al <- as_adj_list(x, mode="out") alstr <- sapply(al, function(x) { paste(collapse=", ", vn[x]) }) alstr <- paste(sep="", format(vn), arrow, alstr) alstr <- strwrap(alstr, exdent=max(nchar(vn))+nchar(arrow)) cat(alstr, sep="\n") } #' @method str igraph #' @export str.igraph <- function(object, ...) { print.igraph(object, full=TRUE, ...) } #' Print graphs to the terminal #' #' These functions attempt to print a graph to the terminal in a human readable #' form. #' #' \code{summary.igraph} prints the number of vertices, edges and whether the #' graph is directed. #' #' \code{str.igraph} prints the same information, and also lists the edges, and #' optionally graph, vertex and/or edge attributes. #' #' \code{print.igraph} behaves either as \code{summary.igraph} or #' \code{str.igraph} depending on the \code{full} argument. See also the #' \sQuote{print.full} igraph option and \code{\link{igraph_opt}}. #' #' The graph summary printed by \code{summary.igraph} (and \code{print.igraph} #' and \code{str.igraph}) consists one or more lines. The first line contains #' the basic properties of the graph, and the rest contains its attributes. #' Here is an example, a small star graph with weighed directed edges and named #' vertices: \preformatted{ IGRAPH DNW- 10 9 -- In-star #' + attr: name (g/c), mode (g/c), center (g/n), name (v/c), #' weight (e/n) } #' The first line always #' starts with \code{IGRAPH}, showing you that the object is an igraph graph. #' Then a four letter long code string is printed. The first letter #' distinguishes between directed (\sQuote{\code{D}}) and undirected #' (\sQuote{\code{U}}) graphs. The second letter is \sQuote{\code{N}} for named #' graphs, i.e. graphs with the \code{name} vertex attribute set. The third #' letter is \sQuote{\code{W}} for weighted graphs, i.e. graphs with the #' \code{weight} edge attribute set. The fourth letter is \sQuote{\code{B}} for #' bipartite graphs, i.e. for graphs with the \code{type} vertex attribute set. #' #' Then, after two dashes, the name of the graph is printed, if it has one, #' i.e. if the \code{name} graph attribute is set. #' #' From the second line, the attributes of the graph are listed, separated by a #' comma. After the attribute names, the kind of the attribute -- graph #' (\sQuote{\code{g}}), vertex (\sQuote{\code{v}}) or edge (\sQuote{\code{e}}) #' -- is denoted, and the type of the attribute as well, character #' (\sQuote{\code{c}}), numeric (\sQuote{\code{n}}), logical #' (\sQuote{\code{l}}), or other (\sQuote{\code{x}}). #' #' As of igraph 0.4 \code{str.igraph} and \code{print.igraph} use the #' \code{max.print} option, see \code{\link[base]{options}} for details. #' #' @aliases print.igraph str.igraph summary.igraph #' @param x The graph to print. #' @param full Logical scalar, whether to print the graph structure itself as #' well. #' @param graph.attributes Logical constant, whether to print graph attributes. #' @param vertex.attributes Logical constant, whether to print vertex #' attributes. #' @param edge.attributes Logical constant, whether to print edge attributes. #' @param names Logical constant, whether to print symbolic vertex names (ie. #' the \code{name} vertex attribute) or vertex ids. #' @param max.lines The maximum number of lines to use. The rest of the #' output will be truncated. #' @param object The graph of which the summary will be printed. #' @param \dots Additional agruments. #' @return All these functions return the graph invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @method print igraph #' @export #' @export print.igraph #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g #' summary(g) #' print.igraph <- function(x, full=igraph_opt("print.full"), graph.attributes=igraph_opt("print.graph.attributes"), vertex.attributes=igraph_opt("print.vertex.attributes"), edge.attributes=igraph_opt("print.edge.attributes"), names=TRUE, max.lines = igraph_opt("auto.print.lines"), ...) { if (!is_igraph(x)) { stop("Not a graph object") } head_lines <- .print.header(x) if (is.logical(full) && full) { if (graph.attributes) { head_lines <- head_lines + .print.graph.attributes(x, full, max.lines) } if (vertex.attributes) { head_lines <- head_lines + .print.vertex.attributes(x, full, max.lines) } if (ecount(x)==0) { ## Do nothing } else if (edge.attributes && length(edge_attr_names(x)) != 0 ) { .print.edges.edgelist(x, names = names) } else if (median(degree(x, mode="out")) < 3) { .print.edges.compressed(x, names = names, max.lines = NULL) } else if (is_named(x)) { .print.edges.adjlist.named(x) } else { .print.edges.adjlist(x) } } else if (full == "auto") { .print.edges.compressed(x, names = names, max.lines = max.lines - head_lines) } invisible(x) } #' @rdname print.igraph #' @method summary igraph #' @export summary.igraph <- function(object, ...) { .print.header(object) invisible(object) } " #################################################################### ## Various designs for printing graphs ## Summary IGRAPH UNW- 5 5 -- A ring Attr: name (g/c), name (v/c), weight (e/n) IGRAPH D-W- 100 200 -- Gnm random graph ## Printing, edge list IGRAPH-UNW--V5-E5----------------------------------------- A ring - + attributes: name (g), name (v), weight (e). + edges: edge weight [1]' a--b 1 [2]' b--c 2 [3]' c--d -1 [4]' d--e 0.5 [5]' a--e 1 ## Compressed edge list IGRAPH UNW- 5 10 -- A ring + attributes: name (g/c), name (v/n), weight (e/n) + edges: [1]' 1--2 2--3 3--4 4--5 1--5 2--5 5--1 [8]' 1--4 4--2 1--3 ## This is good if vertices are named IGRAPH UNW- 10 18 -- Krackhardt kite + attributes: name (g/c), name (v/c), weight (e/n) + edges: Andre -- [1] Beverly, Carol, Diane, Fernando Beverly -- [1] Andre, Diane, Ed, Garth Carol -- [1] Andre, Diane, Fernando Diane -- [1] Andre, Beverly, Carol, Diane, Ed -- [6] Garth Ed -- [1] Beverly, Diane, Garth Fernando -- [1] Andre, Carol, Diane, Garth Garth -- [1] Beverly, Diane, Ed, Fernando Heather -- [1] Fernando, Garth Ike -- [1] Heather, Jane Jane -- [1] Ike IGRAPH UNW- 10 18 -- Krackhardt kite + attributes: name (g/c), name (v/c), weight (e/n) + edges: Andre -- Beverly, Carol, Diane, Fernando Beverly -- Andre, Diane, Ed, Garth Carol -- Andre, Diane, Fernando Diane -- Andre, Beverly, Carol, Diane, Ed, Garth Ed -- Beverly, Diane, Garth Fernando -- Andre, Carol, Diane, Garth Garth -- Beverly, Diane, Ed, Fernando Heather -- Fernando, Garth Ike -- Heather, Jane Jane -- Ike ## This is the good one if vertices are not named IGRAPH U--- 100 200 -- Gnm random graph + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... ## Alternative designs, summary IGRAPH-UNW--V5-E5,---------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) IGRAPH. |V|=5, |E|=5, undirected, named, weighted. Attributes: name (g/c), name (v/c), weight (e/n) IGRAPH: 'A ring' Graph attributes: |V|=5, |E|=5, undirected, name. Vertex attributes: name. Edge attributes: weight. ## Alternative designs, printing IGRAPH-UNW--V5-E5----------------------------------------- A ring - '- attributes: name (g), name (v), weight (e). ' edge weight [1] 'a' -- 'b' 1 [2] 'b' -- 'c' 2 [3] 'c' -- 'd' -1 [4] 'd' -- 'e' 0.5 [5] 'a' -- 'e' 1 IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - |- attributes: name (g), name (v), weight (e). |- edges: [1] 'a'--'b' 'b'--'c' 'c'--'d' 'd'--'e' 'a'--'e' 'b'-'e' [7] 'e'--'a' 'a'--'d' 'd'--'b' 'a'--'c' IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g), name (v), weight (e). + vertices: | name | [1] a | [2] b | [3] c | [4] d | [5] e + edges: [1] 'a'--'b' 'b'--'c' 'c'--'d' 'd'--'e' 'a'--'e' 'b'-'e' [7] 'e'--'a' 'a'--'d' 'd'--'b' 'a'--'c' IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + graph attributes: name + vertex attributes: name + edge attributes: weight + vertices: | name |1] a |2] b |3] c |4] d |5] e + edges: |1] a--b b--c c--d d--e a--e b-e |7] e--a a--d d--b a--c IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + graph attributes: name (c) + vertex attributes: name (c) + edge attributes: weight (n) + edges: [1] a--b b--c c--d d--e a--e b-e [7] e--a a--d d--b a--c IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ 1] a--b b--c c--d d--e a--e b--e e--a a--d d--b [10] a--c IGRAPH-DNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/n), weight (e/n) + edges: [1]' 1->2 2->3 3->4 4->5 1->5 2->5 5->1 [8]' 1->4 4->2 1->3 IGRAPH-UNW--V-5-E-20-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ 1] a-b b-c c-d d-e a-e b-e e-a a-d d-b a-c [11] a-b b-c c-d d-e a-e b-e e-a a-d d-b a-c IGRAPH-UNW--V-8-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [a] b c e f h [b] a c e [c] a b d [d] a b c h [e] a b d [f] a [g] [h] a d IGRAPH-UNW--V-10-E-18------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [a] a--{b,c,e,f,h} b--{a,c,e} c--{a,b,d} d--{a,b,c,h} [e] e--{a,b,d} f--{a} g--{} h--{a,d} IGRAPH-UNW--V10-E18------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly Carol Diane Fernando [ Beverly][1] Andre Diane Ed Garth [ Carol][1] Andre Diane Fernando [ Diane][1] Andre Beverly Carol Diane Ed [ Diane][6] Garth [ Ed][1] Beverly Diane Garth [Fernando][1] Andre Carol Diane Garth [ Garth][1] Beverly Diane Ed Fernando [ Heather][1] Fernando Garth [ Ike][1] Heather Jane [ Jane][1] Ike IGRAPH-UNW--V10-E18-------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly/1 Carol/3 Diane/3 Fernando/1 [ Beverly][1] Andre/1 Diane/1 Ed/2 Garth/2 [ Carol][1] Andre/2 Diane/2 Fernando/1 [ Diane][1] Andre/5 Beverly/1 Carol/0.4 Diane/2 [ Diane][5] Ed/1.5 Garth/2.5 [ Ed][1] Beverly/-1 Diane/1.5 Garth/2 [Fernando][1] Andre/1 Carol/2 Diane/1 Garth/1 [ Garth][1] Beverly/2 Diane/3 Ed/1 Fernando/-1 [ Heather][1] Fernando/3 Garth/1 [ Ike][1] Heather/1 Jane/-1 [ Jane][1] Ike/-2 IGRAPH-UNW--V10-E18-------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly (1) Carol (3) Diane (3) Fernando (1) [ Beverly][1] Andre (1) Diane (1) Ed (2) Garth (2) [ Carol][1] Andre (2) Diane (2) Fernando (1) [ Diane][1] Andre (5) Beverly (1) Carol (0.5) Diane (2) [ Diane][5] Ed (1.5) Garth (2.5) [ Ed][1] Beverly (-1) Diane (1.5) Garth (2) [Fernando][1] Andre (1) Carol (2) Diane (1) Garth (1) [ Garth][1] Beverly (2) Diane (3) Ed (1) Fernando (-1) [ Heather][1] Fernando (3) Garth (1) [ Ike][1] Heather (1) Jane (-1) [ Jane][1] Ike (-2) IGRAPH UNW- V10 E18 -- Krackhardt kite + attr: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly (1) Carol (3) Diane (3) Fernando (1) [ Beverly][1] Andre (1) Diane (1) Ed (2) Garth (2) [ Carol][1] Andre (2) Diane (2) Fernando (1) [ Diane][1] Andre (5) Beverly (1) Carol (0.5) Diane (2) [ Diane][5] Ed (1.5) Garth (2.5) [ Ed][1] Beverly (-1) Diane (1.5) Garth (2) [Fernando][1] Andre (1) Carol (2) Diane (1) Garth (1) [ Garth][1] Beverly (2) Diane (3) Ed (1) Fernando (-1) [ Heather][1] Fernando (3) Garth (1) [ Ike][1] Heather (1) Jane (-1) [ Jane][1] Ike (-2) IGRAPH-U----V100-E200----------------------------Gnm random graph-- + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... IGRAPH-U----100-200------------------------------Gnm random graph-- + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... "
/R/print.R
no_license
Ruchika8/Dgraph
R
false
false
25,526
r
## ---------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi <csardi.gabor@gmail.com> ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ---------------------------------------------------------------------- ################################################################### # Convert graphs to human readable forms ################################################################### .get.attr.codes <- function(object) { ga <- va <- ea <- "" gal <- graph_attr_names(object) if (length(gal) != 0) { ga <- paste(sep="", gal, " (g/", .Call("R_igraph_get_attr_mode", object, 2L, PACKAGE="igraph"), ")") } val <- vertex_attr_names(object) if (length(val) != 0) { va <- paste(sep="", val, " (v/", .Call("R_igraph_get_attr_mode", object, 3L, PACKAGE="igraph"), ")") } eal <- edge_attr_names(object) if (length(eal) != 0) { ea <- paste(sep="", edge_attr_names(object), " (e/", .Call("R_igraph_get_attr_mode", object, 4L, PACKAGE="igraph"), ")") } c(ga, va, ea) } .print.header <- function(object) { if (!is_igraph(object)) { stop("Not a graph object") } title <- paste(sep="", "IGRAPH ", c("U","D")[is_directed(object)+1], c("-","N")[is_named(object)+1], c("-","W")[is_weighted(object)+1], c("-","B")[is_bipartite(object)+1], " ", vcount(object), " ", ecount(object), " -- ") w <- getOption("width") if (nchar(title) < w && "name" %in% graph_attr_names(object)) { title <- substring(paste(sep="", title, as.character(object$name)[1]), 1, w-1) } cat(title, "\n", sep="") atxt <- .get.attr.codes(object) atxt <- paste(atxt[atxt!=""], collapse=", ") if (atxt != "") { atxt <- strwrap(paste(sep="", "+ attr: ", atxt), prefix = "| ", initial = "") cat(atxt, sep="\n") } 1 + if (length(atxt) == 1 && atxt == "") 0 else length(atxt) } indent_print <- printr$indent_print .print.graph.attributes <- function(x, full, max.lines) { list <- graph_attr_names(x) if (length(list)!=0) { cat("+ graph attributes:\n") out <- capture.output({ lapply(list, function(n) { cat(sep="", "+ ", n, ":\n") indent_print(graph_attr(x, n), .indent = " ") }) invisible(NULL) }) indent_print(out, sep = "\n", .indent = "| ", .printer = cat) length(out) + 1 } else { 0 } } ## IGRAPH U--- 10 10 -- Ring graph ## + attr: name (g/c), mutual (g/l), circular (g/l) ## + graph attributes: ## | + name: ## | [1] "Ring graph" ## | + mutual: ## | [1] FALSE ## | + circular= ## | [1] TRUE ## | + layout = ## | [,1] [,2] ## | [1,] 0.000000 0.000000e+00 ## | [2,] 1.000000 0.000000e+00 ## | [3,] 0.809017 5.877853e-01 ## | [4,] 0.309017 9.510565e-01 ## | [5,] -0.309017 9.510565e-01 ## | [6,] -0.809017 5.877853e-01 ## | [7,] -1.000000 1.224647e-16 ## | [8,] -0.809017 -5.877853e-01 ## | [9,] -0.309017 -9.510565e-01 ## | [10,] 0.309017 -9.510565e-01 ## | [11,] 0.809017 -5.877853e-01 ## + edges: ## [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10 .print.vertex.attributes <- function(x, full, max.lines) { pf <- function(x) .print.vertex.attributes.old(x, full, max.lines) if (length(vertex_attr_names(x))) cat("+ vertex attributes:\n") indent_print(x, .indent = "| ", .printer = pf) } .print.vertex.attributes.old <- function(x, full, max.lines) { vc <- vcount(x) list <- vertex_attr_names(x) if (length(list) != 0) { mp <- getOption("max.print") options(max.print=1000000000) if (vc <= mp) { omitted.vertices <- 0 ind <- as.numeric(V(x)) } else { omitted.vertices <- vc-mp ind <- seq(length=mp) } if (vc==0 || all(sapply(list, function(v) is.numeric(vertex_attr(x, v)) || is.character(vertex_attr(x, v)) || is.logical(vertex_attr(x, v))))) { ## create a table tab <- data.frame(v=paste(sep="", "[", ind, "]"), row.names="v") for (i in list) { tab[i] <- vertex_attr(x, i, ind) } print(tab) } else { for (i in ind) { cat(sep="", "[[", i, "]]\n") lapply(list, function(n) { cat(sep="", "[[", i, "]][[", n, "]]\n") print(vertex_attr(x, n, i))}) } } options(max.print=mp) if (omitted.vertices != 0) { cat(paste('[ reached getOption("max.print") -- omitted', omitted.vertices, "vertices ]\n\n")) } } } .print.edges.edgelist <- function(x, edges = E(x), names) { ec <- length(edges) list <- edge_attr_names(x) list <- list[list!="name"] arrow <- ifelse(is_directed(x), "->", "--") if (is_named(x)) { cat("+ edges (vertex names) and their attributes:\n") } else { cat("+ edges and their attributes:\n") } if (names && ! "name" %in% vertex_attr_names(x)) { names <- FALSE } if (names && "name" %in% vertex_attr_names(x) && !is.numeric(vertex_attr(x, "name")) && !is.character(vertex_attr(x, "name")) && !is.logical(vertex_attr(x, "name"))) { warning("Can't print vertex names, complex `name' vertex attribute") names <- FALSE } mp <- getOption("max.print") if (mp >= ec) { omitted.edges <- 0 el <- ends(x, edges, names=names) } else { omitted.edges <- ec-mp el <- ends(x, ends[seq_len(mp)]) if (names) { el[] <- V(x)$name[el] } } ename <- if ("name" %in% edge_attr_names(x)) { paste(sep="", "'", E(x)$name, "'") } else { seq(length=nrow(el)) } if (ec==0 || all(sapply(list, function(v) is.numeric(edge_attr(x, v)) | is.character(edge_attr(x,v)) | is.logical(edge_attr(x, v))))) { ## create a table tab <- data.frame(row.names=paste(sep="", "[", ename, "]")) if (is.numeric(el)) { w <- nchar(max(el)) } else { w <- max(nchar(el)) } tab["edge"] <- paste(sep="", format(el[,1], width=w), arrow, format(el[,2], width=w)) for (i in list) { tab[i] <- edge_attr(x, i) } print(tab) } else { i <- 1 apply(el, 1, function(v) { cat(sep="", "[", ename[i], "] ", v[1], " ", arrow, " ", v[2]); lapply(list, function(n) { cat(sep="", "\n[[", i, "]][[", n, "]]\n") print(edge_attr(x, n, i))}) cat("\n") i <<- i+1 }) } if (omitted.edges != 0) { cat(paste('[ reached getOption("max.print") -- omitted', omitted.edges, 'edges ]\n\n')) } } #' @include printr.R head_print <- printr$head_print printer_callback <- printr$printer_callback .print.edges.compressed <- function(x, edges = E(x), names, num = FALSE, max.lines = igraph_opt("auto.print.lines")) { len <- length(edges) title <- "+" %+% (if (num) " " %+% chr(len) %+% "/" %+% (if (is.null(x)) "?" else chr(gsize(x))) else "") %+% (if (len == 1) " edge" else " edges") %+% (if (is.null(x)) ", unknown graph" else "") %+% (if (is.null(attr(edges, "vnames"))) "" else " (vertex names)") %+% ":\n" cat(title) if (!is.null(attr(edges, "single")) && attr(edges, "single") && !is.null(x)) { ## Double bracket ea <- edge_attr(x) if (all(sapply(ea, is.atomic))) { etail <- tail_of(x, edges) ehead <- head_of(x, edges) df <- data.frame( stringsAsFactors = FALSE, tail = as_ids(etail), head = as_ids(ehead), tid = as.vector(etail), hid = as.vector(ehead) ) if (length(ea)) { ea <- do_call(data.frame, .args = ea, stringsAsFactors = FALSE) df <- cbind(df, ea[as.vector(edges), , drop = FALSE]) } print(df) } else { print(lapply(ea, "[", as.vector(edges))) } } else if (is.null(max.lines)) { .print.edges.compressed.all(x, edges, names) } else { .print.edges.compressed.limit(x, edges, names, max.lines) } } .print.edges.compressed.all <- function(x, edges, names) { arrow <- c("--", "->")[is_directed(x)+1] if (!is.null(x)) { el <- ends(x, edges, names=names) pr <- paste(sep="", format(el[,1]), arrow, format(el[,2])) print(pr, quote=FALSE) } else { if (!is.null(attr(edges, "vnames"))) { print(as.vector(attr(edges, "vnames")), quote = FALSE) } else if (!is.null(names(edges))) { print(names(edges), quote = FALSE) } else { print(as.vector(edges)) } } } .print.edges.compressed.limit <- function(x, edges, names, max.lines) { if (!is.null(x)) { arrow <- c("--", "->")[is_directed(x)+1] can_max <- NA el <- NA fun <- function(q, no) { if (q == "length") { length(edges) } else if (q == "min_width") { 5 } else if (q == "width") { el <<- ends(x, edges[seq_len(no)], names = names) cummax(nchar(el[,1])) + nchar(arrow) + cummax(nchar(el[,2])) + 1 } else if (q == "print") { el <<- el[seq_len(no), , drop = FALSE] out <- paste(sep="", format(el[,1]), arrow, format(el[,2])) capture.output(print(out, quote = FALSE)) } else if (q == "max") { can_max <<- no } else if (q == "done") { if (no["tried_items"] < length(edges) || no["printed_lines"] < no["tried_lines"]) { cat("+ ... omitted several edges\n") } } } fun <- printer_callback(fun) head_print(fun, max_lines = max.lines) } else { if (!is.null(attr(edges, "vnames"))) { head_print(as.vector(attr(edges, "vnames")), quote = FALSE) } else if (!is.null(names(edges))) { head_print(names(edges), quote = FALSE) } else { head_print(as.vector(edges)) } } } .print.edges.adjlist <- function(x) { ## TODO: getOption("max.print") cat("+ edges:\n") vc <- vcount(x) arrow <- c(" -- ", " -> ")[is_directed(x)+1] al <- as_adj_list(x, mode="out") w <- nchar(max(which(degree(x, mode="in") != 0))) mpl <- trunc((getOption("width")-nchar(arrow)-nchar(vc)) / (w+1)) if (any(sapply(al, length) > mpl)) { ## Wrapping needed mw <- nchar(vcount(x)) sm <- paste(collapse="", rep(" ", mw+4)) alstr <- lapply(seq_along(al), function(x) { len <- length(al[[x]]) fac <- rep(1:(len/mpl+1), each=mpl, length=len) nei <- tapply(format(al[[x]], width=mw), fac, paste, collapse=" ") mark <- paste(sep="", format(x, width=mw), arrow) mark <- c(mark, rep(sm, max(0, length(nei)-1))) paste(sep="", mark, nei) }) cat(unlist(alstr), sep="\n") } else { alstr <- sapply(al, function(x) { paste(format(x, width=w), collapse=" ") }) mark <- paste(sep="", format(seq_len(vc)), arrow) alstr <- paste(sep="", mark, alstr) maxw <- max(nchar(alstr)) sep <- " " ncol <- trunc((getOption("width")-1+nchar(sep)) / (maxw+nchar(sep))) if (ncol > 1) { alstr <- format(alstr, width=maxw, justify="left") fac <- rep(1:(vc/ncol+1), each=ncol, length=vc) alstr <- tapply(alstr, fac, paste, collapse=sep) } cat(alstr, sep="\n") } } .print.edges.adjlist.named <- function(x, edges = E(x)) { ## TODO getOption("max.print") cat("+ edges (vertex names):\n") arrow <- c(" -- ", " -> ")[is_directed(x)+1] vn <- V(x)$name al <- as_adj_list(x, mode="out") alstr <- sapply(al, function(x) { paste(collapse=", ", vn[x]) }) alstr <- paste(sep="", format(vn), arrow, alstr) alstr <- strwrap(alstr, exdent=max(nchar(vn))+nchar(arrow)) cat(alstr, sep="\n") } #' @method str igraph #' @export str.igraph <- function(object, ...) { print.igraph(object, full=TRUE, ...) } #' Print graphs to the terminal #' #' These functions attempt to print a graph to the terminal in a human readable #' form. #' #' \code{summary.igraph} prints the number of vertices, edges and whether the #' graph is directed. #' #' \code{str.igraph} prints the same information, and also lists the edges, and #' optionally graph, vertex and/or edge attributes. #' #' \code{print.igraph} behaves either as \code{summary.igraph} or #' \code{str.igraph} depending on the \code{full} argument. See also the #' \sQuote{print.full} igraph option and \code{\link{igraph_opt}}. #' #' The graph summary printed by \code{summary.igraph} (and \code{print.igraph} #' and \code{str.igraph}) consists one or more lines. The first line contains #' the basic properties of the graph, and the rest contains its attributes. #' Here is an example, a small star graph with weighed directed edges and named #' vertices: \preformatted{ IGRAPH DNW- 10 9 -- In-star #' + attr: name (g/c), mode (g/c), center (g/n), name (v/c), #' weight (e/n) } #' The first line always #' starts with \code{IGRAPH}, showing you that the object is an igraph graph. #' Then a four letter long code string is printed. The first letter #' distinguishes between directed (\sQuote{\code{D}}) and undirected #' (\sQuote{\code{U}}) graphs. The second letter is \sQuote{\code{N}} for named #' graphs, i.e. graphs with the \code{name} vertex attribute set. The third #' letter is \sQuote{\code{W}} for weighted graphs, i.e. graphs with the #' \code{weight} edge attribute set. The fourth letter is \sQuote{\code{B}} for #' bipartite graphs, i.e. for graphs with the \code{type} vertex attribute set. #' #' Then, after two dashes, the name of the graph is printed, if it has one, #' i.e. if the \code{name} graph attribute is set. #' #' From the second line, the attributes of the graph are listed, separated by a #' comma. After the attribute names, the kind of the attribute -- graph #' (\sQuote{\code{g}}), vertex (\sQuote{\code{v}}) or edge (\sQuote{\code{e}}) #' -- is denoted, and the type of the attribute as well, character #' (\sQuote{\code{c}}), numeric (\sQuote{\code{n}}), logical #' (\sQuote{\code{l}}), or other (\sQuote{\code{x}}). #' #' As of igraph 0.4 \code{str.igraph} and \code{print.igraph} use the #' \code{max.print} option, see \code{\link[base]{options}} for details. #' #' @aliases print.igraph str.igraph summary.igraph #' @param x The graph to print. #' @param full Logical scalar, whether to print the graph structure itself as #' well. #' @param graph.attributes Logical constant, whether to print graph attributes. #' @param vertex.attributes Logical constant, whether to print vertex #' attributes. #' @param edge.attributes Logical constant, whether to print edge attributes. #' @param names Logical constant, whether to print symbolic vertex names (ie. #' the \code{name} vertex attribute) or vertex ids. #' @param max.lines The maximum number of lines to use. The rest of the #' output will be truncated. #' @param object The graph of which the summary will be printed. #' @param \dots Additional agruments. #' @return All these functions return the graph invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @method print igraph #' @export #' @export print.igraph #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g #' summary(g) #' print.igraph <- function(x, full=igraph_opt("print.full"), graph.attributes=igraph_opt("print.graph.attributes"), vertex.attributes=igraph_opt("print.vertex.attributes"), edge.attributes=igraph_opt("print.edge.attributes"), names=TRUE, max.lines = igraph_opt("auto.print.lines"), ...) { if (!is_igraph(x)) { stop("Not a graph object") } head_lines <- .print.header(x) if (is.logical(full) && full) { if (graph.attributes) { head_lines <- head_lines + .print.graph.attributes(x, full, max.lines) } if (vertex.attributes) { head_lines <- head_lines + .print.vertex.attributes(x, full, max.lines) } if (ecount(x)==0) { ## Do nothing } else if (edge.attributes && length(edge_attr_names(x)) != 0 ) { .print.edges.edgelist(x, names = names) } else if (median(degree(x, mode="out")) < 3) { .print.edges.compressed(x, names = names, max.lines = NULL) } else if (is_named(x)) { .print.edges.adjlist.named(x) } else { .print.edges.adjlist(x) } } else if (full == "auto") { .print.edges.compressed(x, names = names, max.lines = max.lines - head_lines) } invisible(x) } #' @rdname print.igraph #' @method summary igraph #' @export summary.igraph <- function(object, ...) { .print.header(object) invisible(object) } " #################################################################### ## Various designs for printing graphs ## Summary IGRAPH UNW- 5 5 -- A ring Attr: name (g/c), name (v/c), weight (e/n) IGRAPH D-W- 100 200 -- Gnm random graph ## Printing, edge list IGRAPH-UNW--V5-E5----------------------------------------- A ring - + attributes: name (g), name (v), weight (e). + edges: edge weight [1]' a--b 1 [2]' b--c 2 [3]' c--d -1 [4]' d--e 0.5 [5]' a--e 1 ## Compressed edge list IGRAPH UNW- 5 10 -- A ring + attributes: name (g/c), name (v/n), weight (e/n) + edges: [1]' 1--2 2--3 3--4 4--5 1--5 2--5 5--1 [8]' 1--4 4--2 1--3 ## This is good if vertices are named IGRAPH UNW- 10 18 -- Krackhardt kite + attributes: name (g/c), name (v/c), weight (e/n) + edges: Andre -- [1] Beverly, Carol, Diane, Fernando Beverly -- [1] Andre, Diane, Ed, Garth Carol -- [1] Andre, Diane, Fernando Diane -- [1] Andre, Beverly, Carol, Diane, Ed -- [6] Garth Ed -- [1] Beverly, Diane, Garth Fernando -- [1] Andre, Carol, Diane, Garth Garth -- [1] Beverly, Diane, Ed, Fernando Heather -- [1] Fernando, Garth Ike -- [1] Heather, Jane Jane -- [1] Ike IGRAPH UNW- 10 18 -- Krackhardt kite + attributes: name (g/c), name (v/c), weight (e/n) + edges: Andre -- Beverly, Carol, Diane, Fernando Beverly -- Andre, Diane, Ed, Garth Carol -- Andre, Diane, Fernando Diane -- Andre, Beverly, Carol, Diane, Ed, Garth Ed -- Beverly, Diane, Garth Fernando -- Andre, Carol, Diane, Garth Garth -- Beverly, Diane, Ed, Fernando Heather -- Fernando, Garth Ike -- Heather, Jane Jane -- Ike ## This is the good one if vertices are not named IGRAPH U--- 100 200 -- Gnm random graph + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... ## Alternative designs, summary IGRAPH-UNW--V5-E5,---------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) IGRAPH. |V|=5, |E|=5, undirected, named, weighted. Attributes: name (g/c), name (v/c), weight (e/n) IGRAPH: 'A ring' Graph attributes: |V|=5, |E|=5, undirected, name. Vertex attributes: name. Edge attributes: weight. ## Alternative designs, printing IGRAPH-UNW--V5-E5----------------------------------------- A ring - '- attributes: name (g), name (v), weight (e). ' edge weight [1] 'a' -- 'b' 1 [2] 'b' -- 'c' 2 [3] 'c' -- 'd' -1 [4] 'd' -- 'e' 0.5 [5] 'a' -- 'e' 1 IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - |- attributes: name (g), name (v), weight (e). |- edges: [1] 'a'--'b' 'b'--'c' 'c'--'d' 'd'--'e' 'a'--'e' 'b'-'e' [7] 'e'--'a' 'a'--'d' 'd'--'b' 'a'--'c' IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g), name (v), weight (e). + vertices: | name | [1] a | [2] b | [3] c | [4] d | [5] e + edges: [1] 'a'--'b' 'b'--'c' 'c'--'d' 'd'--'e' 'a'--'e' 'b'-'e' [7] 'e'--'a' 'a'--'d' 'd'--'b' 'a'--'c' IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + graph attributes: name + vertex attributes: name + edge attributes: weight + vertices: | name |1] a |2] b |3] c |4] d |5] e + edges: |1] a--b b--c c--d d--e a--e b-e |7] e--a a--d d--b a--c IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + graph attributes: name (c) + vertex attributes: name (c) + edge attributes: weight (n) + edges: [1] a--b b--c c--d d--e a--e b-e [7] e--a a--d d--b a--c IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ 1] a--b b--c c--d d--e a--e b--e e--a a--d d--b [10] a--c IGRAPH-DNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/n), weight (e/n) + edges: [1]' 1->2 2->3 3->4 4->5 1->5 2->5 5->1 [8]' 1->4 4->2 1->3 IGRAPH-UNW--V-5-E-20-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ 1] a-b b-c c-d d-e a-e b-e e-a a-d d-b a-c [11] a-b b-c c-d d-e a-e b-e e-a a-d d-b a-c IGRAPH-UNW--V-8-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [a] b c e f h [b] a c e [c] a b d [d] a b c h [e] a b d [f] a [g] [h] a d IGRAPH-UNW--V-10-E-18------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [a] a--{b,c,e,f,h} b--{a,c,e} c--{a,b,d} d--{a,b,c,h} [e] e--{a,b,d} f--{a} g--{} h--{a,d} IGRAPH-UNW--V10-E18------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly Carol Diane Fernando [ Beverly][1] Andre Diane Ed Garth [ Carol][1] Andre Diane Fernando [ Diane][1] Andre Beverly Carol Diane Ed [ Diane][6] Garth [ Ed][1] Beverly Diane Garth [Fernando][1] Andre Carol Diane Garth [ Garth][1] Beverly Diane Ed Fernando [ Heather][1] Fernando Garth [ Ike][1] Heather Jane [ Jane][1] Ike IGRAPH-UNW--V10-E18-------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly/1 Carol/3 Diane/3 Fernando/1 [ Beverly][1] Andre/1 Diane/1 Ed/2 Garth/2 [ Carol][1] Andre/2 Diane/2 Fernando/1 [ Diane][1] Andre/5 Beverly/1 Carol/0.4 Diane/2 [ Diane][5] Ed/1.5 Garth/2.5 [ Ed][1] Beverly/-1 Diane/1.5 Garth/2 [Fernando][1] Andre/1 Carol/2 Diane/1 Garth/1 [ Garth][1] Beverly/2 Diane/3 Ed/1 Fernando/-1 [ Heather][1] Fernando/3 Garth/1 [ Ike][1] Heather/1 Jane/-1 [ Jane][1] Ike/-2 IGRAPH-UNW--V10-E18-------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly (1) Carol (3) Diane (3) Fernando (1) [ Beverly][1] Andre (1) Diane (1) Ed (2) Garth (2) [ Carol][1] Andre (2) Diane (2) Fernando (1) [ Diane][1] Andre (5) Beverly (1) Carol (0.5) Diane (2) [ Diane][5] Ed (1.5) Garth (2.5) [ Ed][1] Beverly (-1) Diane (1.5) Garth (2) [Fernando][1] Andre (1) Carol (2) Diane (1) Garth (1) [ Garth][1] Beverly (2) Diane (3) Ed (1) Fernando (-1) [ Heather][1] Fernando (3) Garth (1) [ Ike][1] Heather (1) Jane (-1) [ Jane][1] Ike (-2) IGRAPH UNW- V10 E18 -- Krackhardt kite + attr: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly (1) Carol (3) Diane (3) Fernando (1) [ Beverly][1] Andre (1) Diane (1) Ed (2) Garth (2) [ Carol][1] Andre (2) Diane (2) Fernando (1) [ Diane][1] Andre (5) Beverly (1) Carol (0.5) Diane (2) [ Diane][5] Ed (1.5) Garth (2.5) [ Ed][1] Beverly (-1) Diane (1.5) Garth (2) [Fernando][1] Andre (1) Carol (2) Diane (1) Garth (1) [ Garth][1] Beverly (2) Diane (3) Ed (1) Fernando (-1) [ Heather][1] Fernando (3) Garth (1) [ Ike][1] Heather (1) Jane (-1) [ Jane][1] Ike (-2) IGRAPH-U----V100-E200----------------------------Gnm random graph-- + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... IGRAPH-U----100-200------------------------------Gnm random graph-- + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... "
rfiles <- list.files(path = "../data/classify/results", pattern = "HNG_res", full.names = T) wfiles <- list.files(path = "../data/classify/welcalc", pattern = "subdat", full.names = T) resdat <- list() for (i in 1:length(rfiles)) { print(rfiles[i]) print(wfiles[i]) load(rfiles[i]) load(wfiles[i]) resdat[[i]] <- cbind(HNG.res, HNG.wel) } HNG <- do.call(rbind, resdat) save(HNG, file = "../data/classify/merged/HNG.Rda") rm(HNG, resdat) rfiles <- list.files(path = "../data/classify/results", pattern = "HO_res", full.names = T) wfiles <- list.files(path = "../data/classify/welcalc", pattern = "subdat", full.names = T) resdat <- list() for (i in 1:length(rfiles)) { print(rfiles[i]) print(wfiles[i]) load(rfiles[i]) load(wfiles[i]) resdat[[i]] <- cbind(HO.res, HO.wel) } HO <- do.call(rbind, resdat) save(HO, file = "../data/classify/merged/HO.Rda") rm(HO, resdat)
/append/mergeres.R
no_license
bamonroe/code-ch4
R
false
false
882
r
rfiles <- list.files(path = "../data/classify/results", pattern = "HNG_res", full.names = T) wfiles <- list.files(path = "../data/classify/welcalc", pattern = "subdat", full.names = T) resdat <- list() for (i in 1:length(rfiles)) { print(rfiles[i]) print(wfiles[i]) load(rfiles[i]) load(wfiles[i]) resdat[[i]] <- cbind(HNG.res, HNG.wel) } HNG <- do.call(rbind, resdat) save(HNG, file = "../data/classify/merged/HNG.Rda") rm(HNG, resdat) rfiles <- list.files(path = "../data/classify/results", pattern = "HO_res", full.names = T) wfiles <- list.files(path = "../data/classify/welcalc", pattern = "subdat", full.names = T) resdat <- list() for (i in 1:length(rfiles)) { print(rfiles[i]) print(wfiles[i]) load(rfiles[i]) load(wfiles[i]) resdat[[i]] <- cbind(HO.res, HO.wel) } HO <- do.call(rbind, resdat) save(HO, file = "../data/classify/merged/HO.Rda") rm(HO, resdat)
# Name: Nithin S Nair #Last updated: June 19, 2019 #--------------------------------------------------------------------------------------------------------------# #RELATIVE WORKING DIRECTORY setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) ## IMPORTING REQUIRED PACKAGES #Packages will be installed if not available in the device packages <- c("dplyr","tidyverse","tidyr","DT","shiny","ggplot2","ggmap") packages_new <- packages[!(packages %in% installed.packages()[,"Package"])] if(length(packages_new)) install.packages(packages_new) library(dplyr) library(tidyverse) library(tidyr) library(DT) library(shiny) library(ggplot2) library(ggmap) # Reading Data collision.df <- read.csv("traffic-collision-data-from-2010-to-present.csv", stringsAsFactors = F) ## Extracting Latitudes and Longitudes from Location collision.df <- tidyr::separate(data=collision.df, col=Location, into=c("Latitude", "Longitude"), sep=",", remove=FALSE) collision.df$Latitude <- stringr::str_replace_all(collision.df$Latitude, "\\{'latitude': '", "") collision.df$Latitude <- stringr::str_replace_all(collision.df$Latitude, "'", "") collision.df$Longitude <- stringr::str_replace_all(collision.df$Longitude, " 'longitude': '", "") collision.df$Longitude <- stringr::str_replace_all(collision.df$Longitude, "'", "") collision.df$Latitude <- as.numeric(collision.df$Latitude) collision.df$Longitude <- as.numeric(collision.df$Longitude) ## Extracting Month and Year from Date Occurred collision.df <- tidyr::separate(data=collision.df, col=Date.Occurred, into=c("Year","Month"), sep="-", remove=FALSE) collision.df$Year <- as.numeric(collision.df$Year) collision.df$Month <- as.numeric(collision.df$Month) ## Filtering Values of Year 2018 collision.df <- collision.df %>% filter(Year == 2018) # Extract Hour of the Accident collision.df$Hour <- as.numeric(collision.df$Time.Occurred)%/%100 #--------------------------------------------------------------------------------------------------------------# # Define UI for application ui <- fluidPage( # App title titlePanel("Vehicle Collisions in Los Angeles"), # Sidebar layout with input and output definitions sidebarLayout( # Sidebar panel for inputs sidebarPanel( sliderInput(inputId="Mon",label = "Month of the Year (Select 0 to see for the whole year)",value = 0,min = 0,max = 12) ), # Outputs mainPanel( tabsetPanel(type = "tabs",id = "tabselected", tabPanel("Bar Chart", value=1, plotOutput(outputId = "BarPlot", height=500),textOutput(outputId = "frequency")), tabPanel("Location of Collisions in Map",value=2, plotOutput(outputId = "maplocation", height=500)), tabPanel("Heat Map", value=3, plotOutput(outputId = "Heatmap", height=500)) ) ) ) ) # Define Server server <- function(input, output) { # Create Barplot output$BarPlot <- renderPlot({ filtered.df <- collision.df if (input$Mon >=1) { filtered.df <- filtered.df %>%filter(filtered.df$Month == input$Mon) } ggplot(data=filtered.df, aes(x=filtered.df$Hour)) + geom_bar(aes(y = (..count..))) + theme_minimal()+xlab("Hour of the Day")+ylab("Frequency")+ ggtitle("Frequency of Collisions by the Time of the Day") }) # Create text output stating the top frequency output$frequency <- renderText({ filtered.df <- collision.df if (input$Mon >=1) { filtered.df <- filtered.df %>%filter(filtered.df$Month == input$Mon) } histo <- hist(filtered.df$Hour, breaks=24, freq=TRUE) Bin <- histo$breaks[which.max(histo$counts)] #Top <- max(histo$counts) Top <- round(max(histo$counts)*100/length(filtered.df$Hour),2) paste0("The highest number of collisions occur in the hour ",Bin+1," and its Percentage Frequency is ", Top) }) # Rendering Map filtered2.df <- collision.df%>%filter(Latitude!=0, Longitude!=0) output$maplocation <- renderPlot({ if (input$Mon >=1) { filtered2.df <- filtered2.df %>%filter(filtered2.df$Month == input$Mon) } maploc<- qmplot(Longitude, Latitude, data=filtered2.df, geom = "blank", zoom = 11, maptype = "terrain", darken = .5)+ ggtitle("Map Locations of Collisions") maploc+geom_point(aes(Longitude,Latitude),data = filtered2.df, size =0.1, color ="red") }) # Rendering Heatmap output$Heatmap <- renderPlot({ filtered.df <- collision.df if (input$Mon >=1) { filtered.df <- filtered.df %>%filter(filtered.df$Month == input$Mon) } ggplot(filtered.df, aes(x = filtered.df$Area.Name, y = filtered.df$Hour))+ geom_bin2d()+ scale_fill_gradient(low="white", high="red")+ ggtitle("Heatmap of Locations of Collisions") + labs(x="Area Name of Collision",y="Hour of the day") }) } # Creating a Shiny app object shinyApp(ui = ui, server = server) #--------------------------------------------------------------------------------------------------------------#
/Traffic-Collision-Incidents-in-LA-R-Shiny-app.R
no_license
NithinNair/Traffic-Collision-Incidents-in-LA-R-Shiny-app-
R
false
false
5,421
r
# Name: Nithin S Nair #Last updated: June 19, 2019 #--------------------------------------------------------------------------------------------------------------# #RELATIVE WORKING DIRECTORY setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) ## IMPORTING REQUIRED PACKAGES #Packages will be installed if not available in the device packages <- c("dplyr","tidyverse","tidyr","DT","shiny","ggplot2","ggmap") packages_new <- packages[!(packages %in% installed.packages()[,"Package"])] if(length(packages_new)) install.packages(packages_new) library(dplyr) library(tidyverse) library(tidyr) library(DT) library(shiny) library(ggplot2) library(ggmap) # Reading Data collision.df <- read.csv("traffic-collision-data-from-2010-to-present.csv", stringsAsFactors = F) ## Extracting Latitudes and Longitudes from Location collision.df <- tidyr::separate(data=collision.df, col=Location, into=c("Latitude", "Longitude"), sep=",", remove=FALSE) collision.df$Latitude <- stringr::str_replace_all(collision.df$Latitude, "\\{'latitude': '", "") collision.df$Latitude <- stringr::str_replace_all(collision.df$Latitude, "'", "") collision.df$Longitude <- stringr::str_replace_all(collision.df$Longitude, " 'longitude': '", "") collision.df$Longitude <- stringr::str_replace_all(collision.df$Longitude, "'", "") collision.df$Latitude <- as.numeric(collision.df$Latitude) collision.df$Longitude <- as.numeric(collision.df$Longitude) ## Extracting Month and Year from Date Occurred collision.df <- tidyr::separate(data=collision.df, col=Date.Occurred, into=c("Year","Month"), sep="-", remove=FALSE) collision.df$Year <- as.numeric(collision.df$Year) collision.df$Month <- as.numeric(collision.df$Month) ## Filtering Values of Year 2018 collision.df <- collision.df %>% filter(Year == 2018) # Extract Hour of the Accident collision.df$Hour <- as.numeric(collision.df$Time.Occurred)%/%100 #--------------------------------------------------------------------------------------------------------------# # Define UI for application ui <- fluidPage( # App title titlePanel("Vehicle Collisions in Los Angeles"), # Sidebar layout with input and output definitions sidebarLayout( # Sidebar panel for inputs sidebarPanel( sliderInput(inputId="Mon",label = "Month of the Year (Select 0 to see for the whole year)",value = 0,min = 0,max = 12) ), # Outputs mainPanel( tabsetPanel(type = "tabs",id = "tabselected", tabPanel("Bar Chart", value=1, plotOutput(outputId = "BarPlot", height=500),textOutput(outputId = "frequency")), tabPanel("Location of Collisions in Map",value=2, plotOutput(outputId = "maplocation", height=500)), tabPanel("Heat Map", value=3, plotOutput(outputId = "Heatmap", height=500)) ) ) ) ) # Define Server server <- function(input, output) { # Create Barplot output$BarPlot <- renderPlot({ filtered.df <- collision.df if (input$Mon >=1) { filtered.df <- filtered.df %>%filter(filtered.df$Month == input$Mon) } ggplot(data=filtered.df, aes(x=filtered.df$Hour)) + geom_bar(aes(y = (..count..))) + theme_minimal()+xlab("Hour of the Day")+ylab("Frequency")+ ggtitle("Frequency of Collisions by the Time of the Day") }) # Create text output stating the top frequency output$frequency <- renderText({ filtered.df <- collision.df if (input$Mon >=1) { filtered.df <- filtered.df %>%filter(filtered.df$Month == input$Mon) } histo <- hist(filtered.df$Hour, breaks=24, freq=TRUE) Bin <- histo$breaks[which.max(histo$counts)] #Top <- max(histo$counts) Top <- round(max(histo$counts)*100/length(filtered.df$Hour),2) paste0("The highest number of collisions occur in the hour ",Bin+1," and its Percentage Frequency is ", Top) }) # Rendering Map filtered2.df <- collision.df%>%filter(Latitude!=0, Longitude!=0) output$maplocation <- renderPlot({ if (input$Mon >=1) { filtered2.df <- filtered2.df %>%filter(filtered2.df$Month == input$Mon) } maploc<- qmplot(Longitude, Latitude, data=filtered2.df, geom = "blank", zoom = 11, maptype = "terrain", darken = .5)+ ggtitle("Map Locations of Collisions") maploc+geom_point(aes(Longitude,Latitude),data = filtered2.df, size =0.1, color ="red") }) # Rendering Heatmap output$Heatmap <- renderPlot({ filtered.df <- collision.df if (input$Mon >=1) { filtered.df <- filtered.df %>%filter(filtered.df$Month == input$Mon) } ggplot(filtered.df, aes(x = filtered.df$Area.Name, y = filtered.df$Hour))+ geom_bin2d()+ scale_fill_gradient(low="white", high="red")+ ggtitle("Heatmap of Locations of Collisions") + labs(x="Area Name of Collision",y="Hour of the day") }) } # Creating a Shiny app object shinyApp(ui = ui, server = server) #--------------------------------------------------------------------------------------------------------------#
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/execute_order.R \name{tn_place_order} \alias{tn_place_order} \title{Place an order (testnet)} \usage{ tn_place_order( symbol = NULL, side = NULL, orderQty = NULL, price = NULL, displayQty = NULL, stopPx = NULL, clOrdID = NULL, pegOffsetValue = NULL, pegPriceType = NULL, ordType = NULL, timeInForce = NULL, execInst = NULL, text = NULL ) } \arguments{ \item{symbol}{string. Instrument symbol. e.g. 'XBTUSD'.} \item{side}{string. Order side. Valid options: Buy, Sell. Defaults to 'Buy' unless \code{orderQty}is negative.} \item{orderQty}{double. Order quantity in units of the instrument (i.e. contracts).} \item{price}{double. Optional limit price for 'Limit', 'StopLimit', and 'LimitIfTouched' orders.} \item{displayQty}{double. Optional quantity to display in the book. Use 0 for a fully hidden order.} \item{stopPx}{double. Optional trigger price for 'Stop', 'StopLimit', 'MarketIfTouched', and 'LimitIfTouched' orders. Use a price below the current price for stop-sell orders and buy-if-touched orders. Use \code{execInst} of 'MarkPrice' or 'LastPrice' to define the current price used for triggering.} \item{clOrdID}{string. Optional Client Order ID. This clOrdID will come back on the order and any related executions.} \item{pegOffsetValue}{string. Optional trailing offset from the current price for 'Stop', 'StopLimit', ' MarketIfTouched', and 'LimitIfTouched' orders; use a negative offset for stop-sell orders and buy-if-touched orders. Optional offset from the peg price for 'Pegged' orders.} \item{pegPriceType}{string. Optional peg price type. Valid options: LastPeg, MidPricePeg, MarketPeg, PrimaryPeg, TrailingStopPeg.} \item{ordType}{string. Order type. Valid options: Market, Limit, Stop, StopLimit, MarketIfTouched, LimitIfTouched, Pegged. Defaults to 'Limit' when \code{price} is specified. Defaults to 'Stop' when \code{stopPx} is specified. Defaults to 'StopLimit' when \code{price} and \code{stopPx} are specified.} \item{timeInForce}{string. Time in force. Valid options: Day, GoodTillCancel, ImmediateOrCancel, FillOrKill. Defaults to 'GoodTillCancel' for 'Limit', 'StopLimit', and 'LimitIfTouched' orders.} \item{execInst}{string. Optional execution instructions. Valid options: ParticipateDoNotInitiate, AllOrNone, MarkPrice, IndexPrice, LastPrice, Close, ReduceOnly, Fixed. 'AllOrNone' instruction requires \code{displayQty} to be 0. 'MarkPrice', 'IndexPrice' or 'LastPrice' instruction valid for 'Stop', 'StopLimit', 'MarketIfTouched', and 'LimitIfTouched' orders.} \item{text}{string. Optional order annotation. e.g. 'Take profit'.} } \value{ Returns a \code{tibble} containing information about the trade that has been placed. See \url{https://testnet.bitmex.com/api/explorer/#!/Order/Order_new} for more details. } \description{ Place an order using the Bitmex testnet API. Requires testnet API key. } \examples{ \dontrun{ # place limit order to Buy at specific price tn_place_order(symbol = "XBTUSD", price = 6000, orderQty = 10) } }
/man/tn_place_order.Rd
permissive
hfshr/bitmexr
R
false
true
3,084
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/execute_order.R \name{tn_place_order} \alias{tn_place_order} \title{Place an order (testnet)} \usage{ tn_place_order( symbol = NULL, side = NULL, orderQty = NULL, price = NULL, displayQty = NULL, stopPx = NULL, clOrdID = NULL, pegOffsetValue = NULL, pegPriceType = NULL, ordType = NULL, timeInForce = NULL, execInst = NULL, text = NULL ) } \arguments{ \item{symbol}{string. Instrument symbol. e.g. 'XBTUSD'.} \item{side}{string. Order side. Valid options: Buy, Sell. Defaults to 'Buy' unless \code{orderQty}is negative.} \item{orderQty}{double. Order quantity in units of the instrument (i.e. contracts).} \item{price}{double. Optional limit price for 'Limit', 'StopLimit', and 'LimitIfTouched' orders.} \item{displayQty}{double. Optional quantity to display in the book. Use 0 for a fully hidden order.} \item{stopPx}{double. Optional trigger price for 'Stop', 'StopLimit', 'MarketIfTouched', and 'LimitIfTouched' orders. Use a price below the current price for stop-sell orders and buy-if-touched orders. Use \code{execInst} of 'MarkPrice' or 'LastPrice' to define the current price used for triggering.} \item{clOrdID}{string. Optional Client Order ID. This clOrdID will come back on the order and any related executions.} \item{pegOffsetValue}{string. Optional trailing offset from the current price for 'Stop', 'StopLimit', ' MarketIfTouched', and 'LimitIfTouched' orders; use a negative offset for stop-sell orders and buy-if-touched orders. Optional offset from the peg price for 'Pegged' orders.} \item{pegPriceType}{string. Optional peg price type. Valid options: LastPeg, MidPricePeg, MarketPeg, PrimaryPeg, TrailingStopPeg.} \item{ordType}{string. Order type. Valid options: Market, Limit, Stop, StopLimit, MarketIfTouched, LimitIfTouched, Pegged. Defaults to 'Limit' when \code{price} is specified. Defaults to 'Stop' when \code{stopPx} is specified. Defaults to 'StopLimit' when \code{price} and \code{stopPx} are specified.} \item{timeInForce}{string. Time in force. Valid options: Day, GoodTillCancel, ImmediateOrCancel, FillOrKill. Defaults to 'GoodTillCancel' for 'Limit', 'StopLimit', and 'LimitIfTouched' orders.} \item{execInst}{string. Optional execution instructions. Valid options: ParticipateDoNotInitiate, AllOrNone, MarkPrice, IndexPrice, LastPrice, Close, ReduceOnly, Fixed. 'AllOrNone' instruction requires \code{displayQty} to be 0. 'MarkPrice', 'IndexPrice' or 'LastPrice' instruction valid for 'Stop', 'StopLimit', 'MarketIfTouched', and 'LimitIfTouched' orders.} \item{text}{string. Optional order annotation. e.g. 'Take profit'.} } \value{ Returns a \code{tibble} containing information about the trade that has been placed. See \url{https://testnet.bitmex.com/api/explorer/#!/Order/Order_new} for more details. } \description{ Place an order using the Bitmex testnet API. Requires testnet API key. } \examples{ \dontrun{ # place limit order to Buy at specific price tn_place_order(symbol = "XBTUSD", price = 6000, orderQty = 10) } }
rm() #options(shiny.autoreload = TRUE) #options(shiny.maxRequestSize=2000*1024^2) library(shiny) library(shinyBS) library(shinyjs) #library(STRINGdb) library(ggplot2) library(tidyverse) library(data.table) library(MSstatsTMT) library(knitr) library(readxl) if (FALSE) require("V8") #library(MSnbase) ##################################### # Global functions # radioTooltip <- function(id, choice, title, placement = "bottom", trigger = "hover", options = NULL){ options = shinyBS:::buildTooltipOrPopoverOptionsList(title, placement, trigger, options) options = paste0("{'", paste(names(options), options, sep = "': '", collapse = "', '"), "'}") bsTag <- shiny::tags$script(shiny::HTML(paste0(" $(document).ready(function() { setTimeout(function() { $('input', $('#", id, "')).each(function(){ if(this.getAttribute('value') == '", choice, "') { opts = $.extend(", options, ", {html: true}); $(this.parentElement).tooltip('destroy'); $(this.parentElement).tooltip(opts); } }) }, 500) }); "))) htmltools::attachDependencies(bsTag, shinyBS:::shinyBSDep) } # shinyjs.disableTab = function() { # vartabs = $('tablist').find('li:not(.active) a'); # tabs.bind('click.tab', function(e) { # e.preventDefault(); # return false; # }); # tabs.addClass('disabled'); # } # # shinyjs.enableTab = function(param) { # vartabs = $('tablist').find('li:not(.active):nth-child(' + param + ') a'); # tab.unbind('click.tab'); # tab.removeClass('disabled'); # } #################################### source("panels/home-ui.R", local = T) source("panels/loadpage-ui.R", local = T) source("panels/qc-ui.R", local = T) source("panels/pq-ui.R", local = T) source("panels/statmodel-ui.R", local = T) source("panels/expdes-ui.R", local = T) #source("panels/analysis-ui.R", local = T) #source("panels/clust-ui.R", local = T) source("panels/report-ui.R", local = T) source("panels/help-ui.R", local = T) ######################################################################### jsCode = ' shinyjs.init = function() { $(document).keypress(function(e) { alert("Key pressed: " + e.which); }); alert("fooo"); console.log("initttttt"); $("#tablist li a").addClass("disabled"); $(".nav").on("click", ".disabled", function (e) { e.preventDefault(); return false; }); } shinyjs.enableTab = function(value) { $("#tablist li a[data-value=" + value + "]").removeClass("disabled"); } ' if(!exists('currentTab') || is.null(currentTab)){ currentTab <- "Homepage" } css <- " .disabled { background: #eee !important; cursor: default !important; color: black !important; } " ui <- navbarPage( title = "MSstats-Shiny", id = "tablist", selected = currentTab, tags$head( tags$style(HTML(" .shiny-output-error-validation { color: red; } ")) ), useShinyjs(), extendShinyjs(text = jsCode,functions = c("init","enableTab")), tags$style(css), tabPanel("Homepage", icon = icon("home"), home), tabPanel("Upload data",value = "Uploaddata", icon = icon("send"), loadpage), tabPanel("Data processing",value = "DataProcessing", icon = icon("gears"), qc), tabPanel("Protein quantification", value = "PQ",icon = icon("calculator"), pq), tabPanel("Statistical model", value = "StatsModel", icon = icon("magic"), statmodel), tabPanel("Future experiments", value = "Future", icon = icon("flask"), expdes), tabPanel("Download logfile", icon = icon("download"), report), tabPanel("Help", icon = icon("ambulance"), help), inverse = T, collapsible = T, windowTitle = "Shiny-MSstats" ) shinyUI(ui)
/ui.R
no_license
dhavalmohandas/ShinyMSstats
R
false
false
4,221
r
rm() #options(shiny.autoreload = TRUE) #options(shiny.maxRequestSize=2000*1024^2) library(shiny) library(shinyBS) library(shinyjs) #library(STRINGdb) library(ggplot2) library(tidyverse) library(data.table) library(MSstatsTMT) library(knitr) library(readxl) if (FALSE) require("V8") #library(MSnbase) ##################################### # Global functions # radioTooltip <- function(id, choice, title, placement = "bottom", trigger = "hover", options = NULL){ options = shinyBS:::buildTooltipOrPopoverOptionsList(title, placement, trigger, options) options = paste0("{'", paste(names(options), options, sep = "': '", collapse = "', '"), "'}") bsTag <- shiny::tags$script(shiny::HTML(paste0(" $(document).ready(function() { setTimeout(function() { $('input', $('#", id, "')).each(function(){ if(this.getAttribute('value') == '", choice, "') { opts = $.extend(", options, ", {html: true}); $(this.parentElement).tooltip('destroy'); $(this.parentElement).tooltip(opts); } }) }, 500) }); "))) htmltools::attachDependencies(bsTag, shinyBS:::shinyBSDep) } # shinyjs.disableTab = function() { # vartabs = $('tablist').find('li:not(.active) a'); # tabs.bind('click.tab', function(e) { # e.preventDefault(); # return false; # }); # tabs.addClass('disabled'); # } # # shinyjs.enableTab = function(param) { # vartabs = $('tablist').find('li:not(.active):nth-child(' + param + ') a'); # tab.unbind('click.tab'); # tab.removeClass('disabled'); # } #################################### source("panels/home-ui.R", local = T) source("panels/loadpage-ui.R", local = T) source("panels/qc-ui.R", local = T) source("panels/pq-ui.R", local = T) source("panels/statmodel-ui.R", local = T) source("panels/expdes-ui.R", local = T) #source("panels/analysis-ui.R", local = T) #source("panels/clust-ui.R", local = T) source("panels/report-ui.R", local = T) source("panels/help-ui.R", local = T) ######################################################################### jsCode = ' shinyjs.init = function() { $(document).keypress(function(e) { alert("Key pressed: " + e.which); }); alert("fooo"); console.log("initttttt"); $("#tablist li a").addClass("disabled"); $(".nav").on("click", ".disabled", function (e) { e.preventDefault(); return false; }); } shinyjs.enableTab = function(value) { $("#tablist li a[data-value=" + value + "]").removeClass("disabled"); } ' if(!exists('currentTab') || is.null(currentTab)){ currentTab <- "Homepage" } css <- " .disabled { background: #eee !important; cursor: default !important; color: black !important; } " ui <- navbarPage( title = "MSstats-Shiny", id = "tablist", selected = currentTab, tags$head( tags$style(HTML(" .shiny-output-error-validation { color: red; } ")) ), useShinyjs(), extendShinyjs(text = jsCode,functions = c("init","enableTab")), tags$style(css), tabPanel("Homepage", icon = icon("home"), home), tabPanel("Upload data",value = "Uploaddata", icon = icon("send"), loadpage), tabPanel("Data processing",value = "DataProcessing", icon = icon("gears"), qc), tabPanel("Protein quantification", value = "PQ",icon = icon("calculator"), pq), tabPanel("Statistical model", value = "StatsModel", icon = icon("magic"), statmodel), tabPanel("Future experiments", value = "Future", icon = icon("flask"), expdes), tabPanel("Download logfile", icon = icon("download"), report), tabPanel("Help", icon = icon("ambulance"), help), inverse = T, collapsible = T, windowTitle = "Shiny-MSstats" ) shinyUI(ui)
if (!exists("hpc")) source("load-dataset.R") png(filename = "figure/plot1.png", bg = "transparent") hist(hpc$Global_active_power, main = "Global Active Power", xlab = "Global Active Power (kilowatts)", col = "red") dev.off()
/plot1.R
no_license
sunsure/ExData_Plotting1
R
false
false
245
r
if (!exists("hpc")) source("load-dataset.R") png(filename = "figure/plot1.png", bg = "transparent") hist(hpc$Global_active_power, main = "Global Active Power", xlab = "Global Active Power (kilowatts)", col = "red") dev.off()
# ============================================================ # Similarity measures for sparse matrices. # ============================================================ #' Calculates correlations between columns of two sparse matrices. #' #' @param X (dgCMatrix) #' @param Y (dgCMatrix) #' @returns Matrix of correlations. cal_cor <- function(X, Y){ availX <- X!=0 availY <- Y!=0 # TODO: to optimize further X<- t(as(t(X) - colMeans(X), "dgCMatrix")) Y<- t(as(t(Y) - colMeans(Y), "dgCMatrix")) R <- crossprod(X,Y) N <- crossprod(X^2, availY) M <- crossprod(availX, Y^2) cor <- R cor@x <- cor@x/((N@x^0.5) * (M@x^0.5)) cor } #' Calculates cosine between columns of two sparse matrices. #' #' @param X (dgCMatrix) #' @param Y (dgCMatrix) #' @returns Matrix of cosine measures. cal_cos <- function(X, Y){ ones <- rep(1,nrow(X)) means <- drop(crossprod(X^2, ones)) ^ 0.5 diagonal <- Diagonal( x = means^-1 ) X <- X %*% diagonal ones <- rep(1,nrow(Y)) means <- drop(crossprod(Y^2, ones)) ^ 0.5 diagonal <- Diagonal( x = means^-1 ) Y <- Y %*% diagonal crossprod(X, Y) }
/R/similarity_measures.R
no_license
Sandy4321/collaboratory
R
false
false
1,126
r
# ============================================================ # Similarity measures for sparse matrices. # ============================================================ #' Calculates correlations between columns of two sparse matrices. #' #' @param X (dgCMatrix) #' @param Y (dgCMatrix) #' @returns Matrix of correlations. cal_cor <- function(X, Y){ availX <- X!=0 availY <- Y!=0 # TODO: to optimize further X<- t(as(t(X) - colMeans(X), "dgCMatrix")) Y<- t(as(t(Y) - colMeans(Y), "dgCMatrix")) R <- crossprod(X,Y) N <- crossprod(X^2, availY) M <- crossprod(availX, Y^2) cor <- R cor@x <- cor@x/((N@x^0.5) * (M@x^0.5)) cor } #' Calculates cosine between columns of two sparse matrices. #' #' @param X (dgCMatrix) #' @param Y (dgCMatrix) #' @returns Matrix of cosine measures. cal_cos <- function(X, Y){ ones <- rep(1,nrow(X)) means <- drop(crossprod(X^2, ones)) ^ 0.5 diagonal <- Diagonal( x = means^-1 ) X <- X %*% diagonal ones <- rep(1,nrow(Y)) means <- drop(crossprod(Y^2, ones)) ^ 0.5 diagonal <- Diagonal( x = means^-1 ) Y <- Y %*% diagonal crossprod(X, Y) }
library(raster) #library(dplyr) #library(lubridate) library(rwrfhydro) library(rgdal) library(tmap) library(parallel) ############################################################### ################# Parametry do ustawienia ##################### ############################################################### args = commandArgs(trailingOnly=TRUE) print(args[1]) print(args[2]) #args <- c(20190526,1) start_wrf <- as.Date(paste0(args[1]), format="%Y%m%d") dzien <- as.numeric(as.character(args[2])) # tutaj chodzi o dzien wyprzedzenia wzgledem startu prognozy (np. +1, +2) patt <- as.character(start_wrf+dzien) #print() #patt<- "2019-05-20" pathway <- paste0("/media/wh/dysk12/wrfout/", format(start_wrf, "%Y%m%d") ,"/wrfprd") day <- dir(path=pathway , pattern = patt,full.names = T) day <- day[grep(pattern = "00$", x = day)] # bez geotiffow if(length(day[grep(pattern = "d03", x = day)])>0) day <- day[grep(pattern = "d03", x = day)] # i tylko domena 03 day <- as.list(day) # warstwy GIS: load(file = "data/gisy.Rdata") # wojewodztwa <- readOGR("data/POL_adm1.shp") # pol <- readOGR("data/POL_adm0.shp") # rzeki <- readOGR("data/rzekiPL.shp") # jeziora <- readOGR("data/jeziora.shp") # proj4 <- "+proj=lcc +lat_1=49.826000213623 +lat_2=49.826000213623 +lat_0=51.8421516418457 +lon_0=16.2469997406006 +x_0=0 +y_0=0 +a=6370000 +b=6370000 +units=m +no_defs" # wojewodztwa <- spTransform(wojewodztwa,proj4) # pol <- spTransform(pol, proj4) # jeziora <- spTransform(jeziora, proj4) # rzeki <- spTransform(rzeki, proj4) # centroidy <- gCentroid(wojewodztwa,byid=TRUE) ########################################################################## # liczymy srednia z poszczegolnych warstw: tempfil<-dir(path=pathway, pattern = "T2", full.names = T) if(length(tempfil[grep(pattern = patt, x = tempfil)])>24) tempfil <- tempfil[grep(pattern = paste0("d03_",patt), x = tempfil)] # i tylko domena 03 tempfil<- stack(tempfil[grepl(pattern=patt, tempfil)]) meantemp<- calc(tempfil,min)-0.5 #beginCluster(4) #meantemp <- clusterR(tempfil, calc, args=list(mean, na.rm=T)) #endCluster() # Creating figure #color scale tempcolores<- c("#f6c39f","#e3ac89","#cb9881","#b58575","#9c716e","#865c62","#704754", "#57344a","#3f1f3f","#240d2b","#260225","#2e0331","#370938","#420a40", "#431243","#481046","#571658","#5e185e","#5f1b60","#671e67","#6d2069", "#853a85","#964299","#9a559d","#a665a3","#ae74a9","#b485b3","#ba93b9", "#c6a5c5","#cbb4cb","#d3c1d2","#c3cad5","#b6b7c6","#9ca4b9","#8992b0", "#5e689b","#5e699d","#48528f","#374182","#1d2e77","#0b1761","#162e74", "#234080","#37578c","#456f9a","#5a88ab","#78b2c4","#9fdbdc","#b1f0ee", "#83c9a7","#72c29a","#67b78c","#69ba8f","#61b080","#56a573","#4c9d64", "#3a9152","#368a45","#2a7f39","#2b7234","#1d681c","#29741a","#44851e", "#578c25","#759c2b","#84a935","#afbf3c","#d8d952","#d4d755","#efe362", "#e9d04f","#e1b845","#d9a53f","#c68f3d","#cc8c38","#c27b31","#ba6323", "#b74d22","#ac4e28","#9f2715","#7b1b11","#80110c","#741105","#6f0d07", "#630c06","#5a0c0c","#540904","#4b0504","#400401","#3f0101","#2d0708", "#442321","#583e3a","#6f5652","#866e6a","#9c8982","#b2a59c","#c8bcb1", "#c9bdb1","#ddd5c9","#f5efe3","#f4efe3") temperatura_map<- function(input="inp", output="outp"){ obj1<- mask(input-273.15, pol) centroidy$column <- sprintf(round(as.vector(raster::extract(obj1, centroidy)),1),fmt = '%#.1f') breaks <-round(seq(-32, 31, length.out = length(tempcolores)),1) range_min <- floor(quantile(obj1, p=0.01)) range_max <- ceiling(max(maxValue(obj1))) ind <- which(breaks> range_min & breaks < range_max) breaks2 <- round(breaks[ind],1) tempcolores2 <- tempcolores[ind[-length(ind)]] tm_shape(obj1) + tm_raster(title= paste0("Minimalna dobowa temperatura powietrza [°C] \n", patt , " (00-23 UTC)"), interval.closure = "left",legend.hist = T, palette = tempcolores2, breaks=breaks2, legend.is.portrait = FALSE, interpolate = FALSE) + #Border tm_shape(pol) + tm_polygons(alpha = 0.001, lwd=1.5) + #Border of counties tm_shape(wojewodztwa)+ tm_polygons(alpha = 0.01, lwd=0.7)+ #Rivers tm_shape(rzeki)+ tm_lines(col="#2669d6", lwd=1.1) + #Lakes tm_shape(jeziora)+ tm_polygons(col="#2669d6") + #Title of the figure tm_layout( aes.palette = "div", sepia.intensity = 0.2, legend.just = "right", title.color = "blue", compass.type = "arrow", title.bg.color = "white", title.bg.alpha = 0.5, title.size = 45, #title.position = c(0.02,0.06), legend.outside = T, legend.outside.position = "bottom", legend.width = 5, legend.hist.width = 0.9, legend.hist.height = 0.6, legend.title.size = 0.90, legend.text.size = 0.5, #legend.position = c("right","bottom"), legend.bg.color = "#FFFFFF60", legend.height = 0.9, legend.frame.lwd = 0.2, legend.frame = F, legend.bg.alpha = 1, space.color="grey90", legend.format = list(text.separator = " ", format = formatC("f")))+ #Lon/Lat tm_grid(projection = "longlat", x = 10:30, y=40:60, labels.col = "black", col = "gray",lwd = 0.5, labels.size = 0.4, labels.inside.frame = T) + #Mean values of counties tm_shape(centroidy)+ tm_text("column", size = 0.6) + #Compass tm_compass(size = 1, fontsize = 0.7, position = c(0.04,0.9), color.light = "grey90") + # scale bar tm_scale_bar(width = 0.12,size = 0.35,breaks = c(0,50,100,150), position = c("left","bottom")) + # windhydro credits tm_credits("(c) Wind-Hydro 2019", position = c("left", "bottom"), size = 0.35, bg.color = "white") } www_path <- gsub(x = pathway, pattern = "wrfprd","www") dir.create(www_path) p <- temperatura_map(input=meantemp) # ciecie w inner margins: dol, lewa, gora, prawa tmap_save(p + tm_layout(inner.margins = c(-0.1, -0.06, -0.1, -0.1)), filename = paste0(www_path, "/t2m_min_",patt,".png"), width=1000, height=1300) writeRaster(meantemp-273.15, filename = paste0(www_path,"/t2m_min_",patt,".tif"),overwrite=TRUE)
/R/temperatura_min.R
no_license
bczernecki/drought
R
false
false
6,455
r
library(raster) #library(dplyr) #library(lubridate) library(rwrfhydro) library(rgdal) library(tmap) library(parallel) ############################################################### ################# Parametry do ustawienia ##################### ############################################################### args = commandArgs(trailingOnly=TRUE) print(args[1]) print(args[2]) #args <- c(20190526,1) start_wrf <- as.Date(paste0(args[1]), format="%Y%m%d") dzien <- as.numeric(as.character(args[2])) # tutaj chodzi o dzien wyprzedzenia wzgledem startu prognozy (np. +1, +2) patt <- as.character(start_wrf+dzien) #print() #patt<- "2019-05-20" pathway <- paste0("/media/wh/dysk12/wrfout/", format(start_wrf, "%Y%m%d") ,"/wrfprd") day <- dir(path=pathway , pattern = patt,full.names = T) day <- day[grep(pattern = "00$", x = day)] # bez geotiffow if(length(day[grep(pattern = "d03", x = day)])>0) day <- day[grep(pattern = "d03", x = day)] # i tylko domena 03 day <- as.list(day) # warstwy GIS: load(file = "data/gisy.Rdata") # wojewodztwa <- readOGR("data/POL_adm1.shp") # pol <- readOGR("data/POL_adm0.shp") # rzeki <- readOGR("data/rzekiPL.shp") # jeziora <- readOGR("data/jeziora.shp") # proj4 <- "+proj=lcc +lat_1=49.826000213623 +lat_2=49.826000213623 +lat_0=51.8421516418457 +lon_0=16.2469997406006 +x_0=0 +y_0=0 +a=6370000 +b=6370000 +units=m +no_defs" # wojewodztwa <- spTransform(wojewodztwa,proj4) # pol <- spTransform(pol, proj4) # jeziora <- spTransform(jeziora, proj4) # rzeki <- spTransform(rzeki, proj4) # centroidy <- gCentroid(wojewodztwa,byid=TRUE) ########################################################################## # liczymy srednia z poszczegolnych warstw: tempfil<-dir(path=pathway, pattern = "T2", full.names = T) if(length(tempfil[grep(pattern = patt, x = tempfil)])>24) tempfil <- tempfil[grep(pattern = paste0("d03_",patt), x = tempfil)] # i tylko domena 03 tempfil<- stack(tempfil[grepl(pattern=patt, tempfil)]) meantemp<- calc(tempfil,min)-0.5 #beginCluster(4) #meantemp <- clusterR(tempfil, calc, args=list(mean, na.rm=T)) #endCluster() # Creating figure #color scale tempcolores<- c("#f6c39f","#e3ac89","#cb9881","#b58575","#9c716e","#865c62","#704754", "#57344a","#3f1f3f","#240d2b","#260225","#2e0331","#370938","#420a40", "#431243","#481046","#571658","#5e185e","#5f1b60","#671e67","#6d2069", "#853a85","#964299","#9a559d","#a665a3","#ae74a9","#b485b3","#ba93b9", "#c6a5c5","#cbb4cb","#d3c1d2","#c3cad5","#b6b7c6","#9ca4b9","#8992b0", "#5e689b","#5e699d","#48528f","#374182","#1d2e77","#0b1761","#162e74", "#234080","#37578c","#456f9a","#5a88ab","#78b2c4","#9fdbdc","#b1f0ee", "#83c9a7","#72c29a","#67b78c","#69ba8f","#61b080","#56a573","#4c9d64", "#3a9152","#368a45","#2a7f39","#2b7234","#1d681c","#29741a","#44851e", "#578c25","#759c2b","#84a935","#afbf3c","#d8d952","#d4d755","#efe362", "#e9d04f","#e1b845","#d9a53f","#c68f3d","#cc8c38","#c27b31","#ba6323", "#b74d22","#ac4e28","#9f2715","#7b1b11","#80110c","#741105","#6f0d07", "#630c06","#5a0c0c","#540904","#4b0504","#400401","#3f0101","#2d0708", "#442321","#583e3a","#6f5652","#866e6a","#9c8982","#b2a59c","#c8bcb1", "#c9bdb1","#ddd5c9","#f5efe3","#f4efe3") temperatura_map<- function(input="inp", output="outp"){ obj1<- mask(input-273.15, pol) centroidy$column <- sprintf(round(as.vector(raster::extract(obj1, centroidy)),1),fmt = '%#.1f') breaks <-round(seq(-32, 31, length.out = length(tempcolores)),1) range_min <- floor(quantile(obj1, p=0.01)) range_max <- ceiling(max(maxValue(obj1))) ind <- which(breaks> range_min & breaks < range_max) breaks2 <- round(breaks[ind],1) tempcolores2 <- tempcolores[ind[-length(ind)]] tm_shape(obj1) + tm_raster(title= paste0("Minimalna dobowa temperatura powietrza [°C] \n", patt , " (00-23 UTC)"), interval.closure = "left",legend.hist = T, palette = tempcolores2, breaks=breaks2, legend.is.portrait = FALSE, interpolate = FALSE) + #Border tm_shape(pol) + tm_polygons(alpha = 0.001, lwd=1.5) + #Border of counties tm_shape(wojewodztwa)+ tm_polygons(alpha = 0.01, lwd=0.7)+ #Rivers tm_shape(rzeki)+ tm_lines(col="#2669d6", lwd=1.1) + #Lakes tm_shape(jeziora)+ tm_polygons(col="#2669d6") + #Title of the figure tm_layout( aes.palette = "div", sepia.intensity = 0.2, legend.just = "right", title.color = "blue", compass.type = "arrow", title.bg.color = "white", title.bg.alpha = 0.5, title.size = 45, #title.position = c(0.02,0.06), legend.outside = T, legend.outside.position = "bottom", legend.width = 5, legend.hist.width = 0.9, legend.hist.height = 0.6, legend.title.size = 0.90, legend.text.size = 0.5, #legend.position = c("right","bottom"), legend.bg.color = "#FFFFFF60", legend.height = 0.9, legend.frame.lwd = 0.2, legend.frame = F, legend.bg.alpha = 1, space.color="grey90", legend.format = list(text.separator = " ", format = formatC("f")))+ #Lon/Lat tm_grid(projection = "longlat", x = 10:30, y=40:60, labels.col = "black", col = "gray",lwd = 0.5, labels.size = 0.4, labels.inside.frame = T) + #Mean values of counties tm_shape(centroidy)+ tm_text("column", size = 0.6) + #Compass tm_compass(size = 1, fontsize = 0.7, position = c(0.04,0.9), color.light = "grey90") + # scale bar tm_scale_bar(width = 0.12,size = 0.35,breaks = c(0,50,100,150), position = c("left","bottom")) + # windhydro credits tm_credits("(c) Wind-Hydro 2019", position = c("left", "bottom"), size = 0.35, bg.color = "white") } www_path <- gsub(x = pathway, pattern = "wrfprd","www") dir.create(www_path) p <- temperatura_map(input=meantemp) # ciecie w inner margins: dol, lewa, gora, prawa tmap_save(p + tm_layout(inner.margins = c(-0.1, -0.06, -0.1, -0.1)), filename = paste0(www_path, "/t2m_min_",patt,".png"), width=1000, height=1300) writeRaster(meantemp-273.15, filename = paste0(www_path,"/t2m_min_",patt,".tif"),overwrite=TRUE)
#You should create one R script called run_analysis.R that does the following. #---Merges the training and the test sets to create one data set. #---Extracts only the measurements on the mean and standard deviation for each measurement. #---Uses descriptive activity names to name the activities in the data set #---Appropriately labels the data set with descriptive variable names. #---From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. #the code runs assuming we are in the UCI HAR Dataset unzipped folder require("data.table") require("reshape2") ################ 1. Merges the training and the test sets to create one data set ############## # Load: data column names features <- read.table("features.txt",stringsAsFactors=F) #reading features features<-features$V2 #working with the labels alone, excluding indexes from the table x_test <- read.table("./test/X_test.txt",stringsAsFactors=F) #reading test set colnames(x_test)<-features #labeling data with descriptive variable names y_test <- read.table("./test/y_test.txt",stringsAsFactors=F) #reading test labels subject_test <- read.table("./test/subject_test.txt",stringsAsFactors=F) x_test$subject<-subject_test[,1] #getting the ids for the subjects in the test data set x_test$activity = y_test[,1] #getting the ids for the activities in the training data set x_train<-read.table("./train/X_train.txt",stringsAsFactors=F) #reading training set colnames(x_train)<-features #labeling data with descriptive variable names y_train<-read.table("./train/y_train.txt") #reading training labels subject_train<-read.table("./train/subject_train.txt",stringsAsFactors=F) x_train$subject<-subject_train[,1] #getting the ids for the subjects in the test data set x_train$activity = y_train[,1] #getting the ids for the subjects in the test data set merged<-rbind(x_train,x_test) #merginf training and test data, binding by row ################ 2. Get mean and standard deviation columns ######### sd.mean.features<-subset(features, (grepl("std|mean",features)==TRUE)) #extracting features containing only the mean and standard deviation extracted<-merged[,sd.mean.features] #extracting from the main dataset the columns corresponding #to mean and standard deviation only extracted$subject<-merged$subject #add subject from main data frame, excluded above extracted$activity<-merged$activity # add activity from main data frame excluded above ############# 3 Uses descriptive activity names to name the activities in the data set ###### activity_labels <- read.table("activity_labels.txt",stringsAsFactors=F) #reading activity labels activity_labels<-activity_labels$V2 #working with the labels alone, excluding indexes from the table activity_labels<-as.factor(activity_labels) # converting column to factor extracted$activity<-as.factor(extracted$activity) #converting column to factor extracted$activity_label = factor(extracted$activity, levels=c(1,2,3,4,5,6), labels=activity_labels) # applying corresponding labels to the activity ids #using factor(); each id c(1,2,3,4,5,6) corresponds to a single activity ############# 4 Appropriately labels the data set with descriptive variable names. ###### ### achievied at step 1: by assigning the column names with the second column from the features table ######### 5 From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. id_labels = c("subject", "activity", "activity_label") # creating a labels vector with the measures labels = setdiff(colnames(extracted), id_labels) #extracting columns corresponding to variables, excluding the list above melted = melt(extracted, id = id_labels, measure.vars = labels) #re-arranging dataframe - measures, variables and values # Generating the tidy dataset with the average of each variable for each activity and each subject # The dataset is aggregated by the casting formula and applying the mean function to the re-arranged dataset using melt() tidy_data = dcast(melted, subject + activity_label ~ variable, mean) write.table(tidy_data,"tidy_data.txt",sep="\t",row.names=F,col.names=T,quote=F)
/run_analysis.R
no_license
andratolbus/CleaningData
R
false
false
4,476
r
#You should create one R script called run_analysis.R that does the following. #---Merges the training and the test sets to create one data set. #---Extracts only the measurements on the mean and standard deviation for each measurement. #---Uses descriptive activity names to name the activities in the data set #---Appropriately labels the data set with descriptive variable names. #---From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. #the code runs assuming we are in the UCI HAR Dataset unzipped folder require("data.table") require("reshape2") ################ 1. Merges the training and the test sets to create one data set ############## # Load: data column names features <- read.table("features.txt",stringsAsFactors=F) #reading features features<-features$V2 #working with the labels alone, excluding indexes from the table x_test <- read.table("./test/X_test.txt",stringsAsFactors=F) #reading test set colnames(x_test)<-features #labeling data with descriptive variable names y_test <- read.table("./test/y_test.txt",stringsAsFactors=F) #reading test labels subject_test <- read.table("./test/subject_test.txt",stringsAsFactors=F) x_test$subject<-subject_test[,1] #getting the ids for the subjects in the test data set x_test$activity = y_test[,1] #getting the ids for the activities in the training data set x_train<-read.table("./train/X_train.txt",stringsAsFactors=F) #reading training set colnames(x_train)<-features #labeling data with descriptive variable names y_train<-read.table("./train/y_train.txt") #reading training labels subject_train<-read.table("./train/subject_train.txt",stringsAsFactors=F) x_train$subject<-subject_train[,1] #getting the ids for the subjects in the test data set x_train$activity = y_train[,1] #getting the ids for the subjects in the test data set merged<-rbind(x_train,x_test) #merginf training and test data, binding by row ################ 2. Get mean and standard deviation columns ######### sd.mean.features<-subset(features, (grepl("std|mean",features)==TRUE)) #extracting features containing only the mean and standard deviation extracted<-merged[,sd.mean.features] #extracting from the main dataset the columns corresponding #to mean and standard deviation only extracted$subject<-merged$subject #add subject from main data frame, excluded above extracted$activity<-merged$activity # add activity from main data frame excluded above ############# 3 Uses descriptive activity names to name the activities in the data set ###### activity_labels <- read.table("activity_labels.txt",stringsAsFactors=F) #reading activity labels activity_labels<-activity_labels$V2 #working with the labels alone, excluding indexes from the table activity_labels<-as.factor(activity_labels) # converting column to factor extracted$activity<-as.factor(extracted$activity) #converting column to factor extracted$activity_label = factor(extracted$activity, levels=c(1,2,3,4,5,6), labels=activity_labels) # applying corresponding labels to the activity ids #using factor(); each id c(1,2,3,4,5,6) corresponds to a single activity ############# 4 Appropriately labels the data set with descriptive variable names. ###### ### achievied at step 1: by assigning the column names with the second column from the features table ######### 5 From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. id_labels = c("subject", "activity", "activity_label") # creating a labels vector with the measures labels = setdiff(colnames(extracted), id_labels) #extracting columns corresponding to variables, excluding the list above melted = melt(extracted, id = id_labels, measure.vars = labels) #re-arranging dataframe - measures, variables and values # Generating the tidy dataset with the average of each variable for each activity and each subject # The dataset is aggregated by the casting formula and applying the mean function to the re-arranged dataset using melt() tidy_data = dcast(melted, subject + activity_label ~ variable, mean) write.table(tidy_data,"tidy_data.txt",sep="\t",row.names=F,col.names=T,quote=F)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/counts.R \name{sens} \alias{sens} \title{Sensitivity} \usage{ sens(thres, y, y.hat) } \arguments{ \item{thres}{thershold where to split. Must be in range of \code{y.hat}} \item{y}{status yes=1, no=0 or dead=1, alive=0} \item{y.hat}{numeric. risk between 0 and 1} } \description{ Sensitivity }
/man/sens.Rd
no_license
guhjy/Atools
R
false
true
391
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/counts.R \name{sens} \alias{sens} \title{Sensitivity} \usage{ sens(thres, y, y.hat) } \arguments{ \item{thres}{thershold where to split. Must be in range of \code{y.hat}} \item{y}{status yes=1, no=0 or dead=1, alive=0} \item{y.hat}{numeric. risk between 0 and 1} } \description{ Sensitivity }
###########################################################################/** # @RdocFunction withRepos # # @title "Evaluate an R expression with repositories set temporarily" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{expr}{The R expression to be evaluated.} # \item{repos}{A @character @vector of repositories to use.} # \item{...}{Additional arguments passed to @see "useRepos".} # \item{substitute}{If @TRUE, argument \code{expr} is # \code{\link[base]{substitute}()}:ed, otherwise not.} # \item{envir}{The @environment in which the expression should be evaluated.} # } # # \value{ # Returns the results of the expression evaluated. # } # # @author # # \examples{\dontrun{ # # Install from BioC related repositories only # withRepos(install.packages("edgeR"), repos="[[BioC]]") # # # Install from CRAN or BioC related repositories only # withRepos(install.packages("edgeR"), repos=c("CRAN", "[[BioC]]")) # # # Install from mainstream repositories only (same as previous) # withRepos(install.packages("edgeR"), repos="[[mainstream]]") # # # Install from R-Forge and mainstream repositories only # withRepos(install.packages("R.utils"), repos="[[R-Forge]]") # # # Update only CRAN packages # withRepos(update.packages(ask=FALSE), repos="[[CRAN]]") # # # Update only Bioconductor packages # withRepos(update.packages(ask=FALSE), repos="[[BioC]]") # }} # # \seealso{ # Internally, @see "base::eval" is used to evaluate the expression. # See also @see "base::options" and @see "utils::install.packages". # } # # @keyword IO # @keyword programming #*/########################################################################### withRepos <- function(expr, repos="[[mainstream]]", ..., substitute=TRUE, envir=parent.frame()) { # Argument 'expr': if (substitute) expr <- substitute(expr) # Argument 'envir': if (!is.environment(envir)) throw("Argument 'envir' is not a list: ", class(envir)[1L]) # Parse and set repositories temporarily prev <- useRepos(repos, ...) on.exit(useRepos(prev)) # Evaluate expression eval(expr, envir = envir, enclos = baseenv()) } # withOptions()
/R/withRepos.R
no_license
HenrikBengtsson/R.utils
R
false
false
2,173
r
###########################################################################/** # @RdocFunction withRepos # # @title "Evaluate an R expression with repositories set temporarily" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{expr}{The R expression to be evaluated.} # \item{repos}{A @character @vector of repositories to use.} # \item{...}{Additional arguments passed to @see "useRepos".} # \item{substitute}{If @TRUE, argument \code{expr} is # \code{\link[base]{substitute}()}:ed, otherwise not.} # \item{envir}{The @environment in which the expression should be evaluated.} # } # # \value{ # Returns the results of the expression evaluated. # } # # @author # # \examples{\dontrun{ # # Install from BioC related repositories only # withRepos(install.packages("edgeR"), repos="[[BioC]]") # # # Install from CRAN or BioC related repositories only # withRepos(install.packages("edgeR"), repos=c("CRAN", "[[BioC]]")) # # # Install from mainstream repositories only (same as previous) # withRepos(install.packages("edgeR"), repos="[[mainstream]]") # # # Install from R-Forge and mainstream repositories only # withRepos(install.packages("R.utils"), repos="[[R-Forge]]") # # # Update only CRAN packages # withRepos(update.packages(ask=FALSE), repos="[[CRAN]]") # # # Update only Bioconductor packages # withRepos(update.packages(ask=FALSE), repos="[[BioC]]") # }} # # \seealso{ # Internally, @see "base::eval" is used to evaluate the expression. # See also @see "base::options" and @see "utils::install.packages". # } # # @keyword IO # @keyword programming #*/########################################################################### withRepos <- function(expr, repos="[[mainstream]]", ..., substitute=TRUE, envir=parent.frame()) { # Argument 'expr': if (substitute) expr <- substitute(expr) # Argument 'envir': if (!is.environment(envir)) throw("Argument 'envir' is not a list: ", class(envir)[1L]) # Parse and set repositories temporarily prev <- useRepos(repos, ...) on.exit(useRepos(prev)) # Evaluate expression eval(expr, envir = envir, enclos = baseenv()) } # withOptions()
dataFile <- "./data/household_power_consumption.txt" data <- read.table(dataFile, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") subSetData <- data[data$Date %in% c("1/2/2007","2/2/2007") ,] #str(subSetData) datetime <- strptime(paste(subSetData$Date, subSetData$Time, sep=" "), "%d/%m/%Y %H:%M:%S") globalActivePower <- as.numeric(subSetData$Global_active_power) subMetering1 <- as.numeric(subSetData$Sub_metering_1) subMetering2 <- as.numeric(subSetData$Sub_metering_2) subMetering3 <- as.numeric(subSetData$Sub_metering_3) png("plot3.png", width=480, height=480) plot(datetime, subMetering1, type="l", ylab="Energy Submetering", xlab="") lines(datetime, subMetering2, type="l", col="red") lines(datetime, subMetering3, type="l", col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1, lwd=2.5, col=c("black", "red", "blue")) dev.off()
/Plot3.R
no_license
GWdata/Exploratory-Course-Project1
R
false
false
908
r
dataFile <- "./data/household_power_consumption.txt" data <- read.table(dataFile, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") subSetData <- data[data$Date %in% c("1/2/2007","2/2/2007") ,] #str(subSetData) datetime <- strptime(paste(subSetData$Date, subSetData$Time, sep=" "), "%d/%m/%Y %H:%M:%S") globalActivePower <- as.numeric(subSetData$Global_active_power) subMetering1 <- as.numeric(subSetData$Sub_metering_1) subMetering2 <- as.numeric(subSetData$Sub_metering_2) subMetering3 <- as.numeric(subSetData$Sub_metering_3) png("plot3.png", width=480, height=480) plot(datetime, subMetering1, type="l", ylab="Energy Submetering", xlab="") lines(datetime, subMetering2, type="l", col="red") lines(datetime, subMetering3, type="l", col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1, lwd=2.5, col=c("black", "red", "blue")) dev.off()
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. context("dbCreateTableAs and sqlCreateTableAs") source("utilities.R") test_that("sqlCreateTableAs works", { conn <- setup_live_connection() test_table_name <- "test_sqlcreatetableas" expect_equal( sqlCreateTableAs( conn, test_table_name, sql = "SELECT * FROM iris" ), DBI::SQL( paste0( "CREATE TABLE ", dbQuoteIdentifier(conn, test_table_name), "\n", "AS\n", "SELECT * FROM iris" ) ) ) expect_equal( sqlCreateTableAs( conn, test_table_name, sql = "SELECT * FROM iris", with = "WITH (format = 'ORC')" ), DBI::SQL( paste0( "CREATE TABLE ", dbQuoteIdentifier(conn, test_table_name), "\n", "WITH (format = 'ORC')\n", "AS\n", "SELECT * FROM iris" ) ) ) }) test_equal_tables <- function(conn, test_table_name, test_origin_table) { expect_equal( dbListFields(conn, test_table_name), dbListFields(conn, test_origin_table) ) expect_equal( get_nrow(conn, test_table_name), get_nrow(conn, test_origin_table) ) } test_that("dbCreateTableAS works with live database", { conn <- setup_live_connection() test_table_name <- "test_createtableas" test_origin_table <- "iris" test_statement <- paste0("SELECT * FROM ", test_origin_table) if (dbExistsTable(conn, test_table_name)) { dbRemoveTable(conn, test_table_name) } expect_false(dbExistsTable(conn, test_table_name)) expect_true(dbCreateTableAs(conn, test_table_name, test_statement)) expect_true(dbExistsTable(conn, test_table_name)) test_equal_tables(conn, test_table_name, test_origin_table) expect_error( dbCreateTableAs(conn, test_table_name, test_statement), "The table .* exists but overwrite is set to FALSE" ) expect_message( res <- dbCreateTableAs( conn, test_table_name, test_statement, overwrite = TRUE ), "is overwritten" ) expect_true(res) expect_true(dbExistsTable(conn, test_table_name)) test_equal_tables(conn, test_table_name, test_origin_table) })
/tests/testthat/test-dbCreateTableAs.R
permissive
prestodb/RPresto
R
false
false
2,264
r
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. context("dbCreateTableAs and sqlCreateTableAs") source("utilities.R") test_that("sqlCreateTableAs works", { conn <- setup_live_connection() test_table_name <- "test_sqlcreatetableas" expect_equal( sqlCreateTableAs( conn, test_table_name, sql = "SELECT * FROM iris" ), DBI::SQL( paste0( "CREATE TABLE ", dbQuoteIdentifier(conn, test_table_name), "\n", "AS\n", "SELECT * FROM iris" ) ) ) expect_equal( sqlCreateTableAs( conn, test_table_name, sql = "SELECT * FROM iris", with = "WITH (format = 'ORC')" ), DBI::SQL( paste0( "CREATE TABLE ", dbQuoteIdentifier(conn, test_table_name), "\n", "WITH (format = 'ORC')\n", "AS\n", "SELECT * FROM iris" ) ) ) }) test_equal_tables <- function(conn, test_table_name, test_origin_table) { expect_equal( dbListFields(conn, test_table_name), dbListFields(conn, test_origin_table) ) expect_equal( get_nrow(conn, test_table_name), get_nrow(conn, test_origin_table) ) } test_that("dbCreateTableAS works with live database", { conn <- setup_live_connection() test_table_name <- "test_createtableas" test_origin_table <- "iris" test_statement <- paste0("SELECT * FROM ", test_origin_table) if (dbExistsTable(conn, test_table_name)) { dbRemoveTable(conn, test_table_name) } expect_false(dbExistsTable(conn, test_table_name)) expect_true(dbCreateTableAs(conn, test_table_name, test_statement)) expect_true(dbExistsTable(conn, test_table_name)) test_equal_tables(conn, test_table_name, test_origin_table) expect_error( dbCreateTableAs(conn, test_table_name, test_statement), "The table .* exists but overwrite is set to FALSE" ) expect_message( res <- dbCreateTableAs( conn, test_table_name, test_statement, overwrite = TRUE ), "is overwritten" ) expect_true(res) expect_true(dbExistsTable(conn, test_table_name)) test_equal_tables(conn, test_table_name, test_origin_table) })
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/helpers.R \name{round_up_nice} \alias{round_up_nice} \title{Round up to nearest 'nice' number source: https://stackoverflow.com/a/6463946} \usage{ round_up_nice(x, nice = c(1, 2, 4, 5, 6, 8, 10)) } \arguments{ \item{x}{Number to round up} \item{nice}{Vector of 'nice' numbers (no need to change this)} } \description{ Round up to nearest 'nice' number source: https://stackoverflow.com/a/6463946 }
/man/round_up_nice.Rd
permissive
matthewgthomas/brclib
R
false
true
477
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/helpers.R \name{round_up_nice} \alias{round_up_nice} \title{Round up to nearest 'nice' number source: https://stackoverflow.com/a/6463946} \usage{ round_up_nice(x, nice = c(1, 2, 4, 5, 6, 8, 10)) } \arguments{ \item{x}{Number to round up} \item{nice}{Vector of 'nice' numbers (no need to change this)} } \description{ Round up to nearest 'nice' number source: https://stackoverflow.com/a/6463946 }
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/providers.R \name{provider} \alias{provider} \title{Create a new provider.} \usage{ provider(tile_f, attr_tile, attr_data = osm_license) } \arguments{ \item{tile_f}{A tile function has inputs x, y and z and returns a url.} \item{attr_title,attr_data}{Attribution information for rendered tiles and underlying data.} } \description{ A provider wrappers a tile function with attribution details. } \keyword{internal}
/man/provider.Rd
no_license
junior128/rastermap
R
false
false
503
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/providers.R \name{provider} \alias{provider} \title{Create a new provider.} \usage{ provider(tile_f, attr_tile, attr_data = osm_license) } \arguments{ \item{tile_f}{A tile function has inputs x, y and z and returns a url.} \item{attr_title,attr_data}{Attribution information for rendered tiles and underlying data.} } \description{ A provider wrappers a tile function with attribution details. } \keyword{internal}
# # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) options(shiny.maxRequestSize=100*1024^2) # Define server logic required to draw a histogram shinyServer( function(input, output) { data <- reactive({ file1 <- input$file if(is.null(file1)) { return()} #read.table(file=file1$datapath, sep=input$sep, header=input$header, stringAsFactors=input$stringAsFactors) read.table(file=file1$datapath, sep=input$sep, header=input$header) }) output$filedf <- renderTable ({ if(is.null(data())) { return () } input$file }) output$sum <- renderTable({ if(is.null(data())) {return ()} summary(data()) }) output$table <- renderTable({ if(is.null(data())) { return ()} head(data()) }) output$tb <- renderUI({ if(is.null(data())) { return () } else tabsetPanel( tabPanel("About file", tableOutput("filedf")), tabPanel("Data", tableOutput("table")), tabPanel("Summary", tableOutput("sum")) ) }) } )
/server.R
no_license
gnetsanet/scViz
R
false
false
1,452
r
# # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) options(shiny.maxRequestSize=100*1024^2) # Define server logic required to draw a histogram shinyServer( function(input, output) { data <- reactive({ file1 <- input$file if(is.null(file1)) { return()} #read.table(file=file1$datapath, sep=input$sep, header=input$header, stringAsFactors=input$stringAsFactors) read.table(file=file1$datapath, sep=input$sep, header=input$header) }) output$filedf <- renderTable ({ if(is.null(data())) { return () } input$file }) output$sum <- renderTable({ if(is.null(data())) {return ()} summary(data()) }) output$table <- renderTable({ if(is.null(data())) { return ()} head(data()) }) output$tb <- renderUI({ if(is.null(data())) { return () } else tabsetPanel( tabPanel("About file", tableOutput("filedf")), tabPanel("Data", tableOutput("table")), tabPanel("Summary", tableOutput("sum")) ) }) } )
#' @title Bayesian VAR #' @author Nikolas Kuschnig, Lukas Vashold #' @description Bayesian VAR with Hyperpriors #' #' @param data #' @param lags Number of lags to include. #' @param nsave Number of MCMC-draws to store. #' @param nburn Number of MCMC-draws to discard #' @param irf Boolean determining whether to compute impulse responses. #' @param horizon Integer stating the horizon of the impulse responses. #' @param sign_res Numeric matrix of sign restrictions. #' @param mn_prior placeholder #' @param soc_prior placeholder #' @param sur_prior placeholder #' @param scale_hess Number or numerical vector scaling the hessian matrix. #' #' @return Returns a list with stored draws of beta, sigma, the impulse responses, #' as well as all draws of parameters and log-likelihood. #' @export #' bvar <- function(data, lags, nsave = 5000, nburn = 1000, irf = TRUE, horizon = 20, sign_res = NULL, # pred_density = FALSE, mn_prior = TRUE, soc_prior = TRUE, sur_prior = TRUE, scale_hess = c(0.1, 0.03, 0.03)) { # Robustness Checks ------------------------------------------------------- if(nsave < 0 || nburn < 0 || !is.numeric(nsave) || !is.numeric(nburn)) { stop("Iterations were not specified properly.") } # Preparation ------------------------------------------------------------- Y <- as.matrix(data) X <- lag_data(Y, lags) Y <- Y[(lags + 1):nrow(Y), ] X <- X[(lags + 1):nrow(X), ] X <- cbind(1, X) K <- ncol(X) M <- ncol(Y) N <- nrow(Y) # OLS beta_ols <- solve(crossprod(X)) %*% crossprod(X, Y) sse_ols <- crossprod(Y - X %*% beta_ols) sigma_ols <- sigma <- sse_ols / (N - K) # Hyperpriors ------------------------------------------------------------- n_priors <- mn_prior + soc_prior + sur_prior # Prior parameters Y0 <- colMeans(Y[1:lags, ]) par_min <- list("lambda" = 0.0001, "miu" = 0.0001, "theta" = 0.0001) par_max <- list("lambda" = 5, "miu" = 50, "theta" = 50) par_modes <- list("lambda" = 0.2, "miu" = 1, "theta" = 1) par_sd <- list("lambda" = 0.4, "miu" = 1, "theta" = 1) mn_alpha <- 2 # Coefficients of the hyperpriors prior_coef <- list("lambda" = gamma_coef(par_modes$lambda, par_sd$lambda), "miu" = gamma_coef(par_modes$miu, par_sd$miu), "theta" = gamma_coef(par_modes$theta, par_sd$theta)) # Inverse Hessian and Jacobian for drawing proposals H <- diag(n_priors) * scale_hess exp_modes <- exp(c(par_modes$lambda, par_modes$miu, par_modes$theta)) J <- exp_modes / (1 + exp_modes) ^ 2 J[1] <- J[1] * (par_max$lambda - par_min$lambda) J[2] <- J[2] * (par_max$miu - par_min$miu) J[3] <- J[3] * (par_max$theta - par_min$theta) J <- diag(J) HH <- J %*% H %*% t(J) mn_mean <- matrix(0, K, M) mn_mean[2:(M + 1), ] <- diag(M) mn_sd <- apply(Y, 2, function(x) { sqrt(arima(x, order = c(lags, 0, 0))$sigma2) }) mn_var <- 1e06 post_mode <- c("lambda" = par_modes$lambda, "miu" = par_modes$miu, "theta" = par_modes$theta) # Initial Values ---------------------------------------------------------- par_draw <- bounded_rnorm(post_mode, diag(HH), bounds = list("min" = par_min, "max" = par_max)) logML_draw <- logML(Y, X, lags, Y_row = N, Y_col = M, par = list("lambda" = par_draw[1], "miu" = par_draw[2], "theta" = par_draw[3], "alpha" = mn_alpha, "psi" = mn_sd), mn_mean, mn_sd, mn_var, Y0, prior_coef) # Storage par_store <- matrix(NA, nsave + nburn, length(post_mode)) ml_store <- vector("numeric", nsave + nburn) beta_store <- array(NA, c(nsave, K, M)) sigma_store <- array(NA, c(nsave, M, M)) accepted <- 0 if(irf) {irf_store <- array(NA, c(nsave, M, M, horizon))} if(!is.null(sign_res)) {sign_res <- as.vector(sign_res)} # if(pred_density) {y_store <- matrix(NA, nrow = nsave, M)} # Loop -------------------------------------------------------------------- for(i in (1 - nburn):nsave) { # Metropolis-Hastings par_temp <- bounded_rnorm(par_draw, diag(HH), bounds = list("min" = par_min, "max" = par_max)) logML_temp <- logML(Y, X, lags, Y_row = N, Y_col = M, par = list("lambda" = par_temp[1], "miu" = par_temp[2], "theta" = par_temp[3], "alpha" = mn_alpha, "psi" = mn_sd), mn_mean, mn_sd, mn_var, Y0, prior_coef) if(runif(1) < exp(logML_temp$logML - logML_draw$logML)) { logML_draw <- logML_temp par_draw <- par_temp accepted <- accepted + 1 } else { logML_draw <- logML(Y, X, lags, Y_row = N, Y_col = M, par = list("lambda" = par_draw[1], "miu" = par_draw[2], "theta" = par_draw[3], "alpha" = mn_alpha, "psi" = mn_sd), mn_mean, mn_sd, mn_var, Y0, prior_coef) } # Storage par_store[i + nburn, ] <- par_draw ml_store[i + nburn] <- logML_draw$logML if(i > 0) { beta_store[i, , ] <- logML_draw$beta_draw sigma_store[i, , ] <- logML_draw$sigma_draw # Impulse Responses if(irf) { # Companion matrix beta_comp <- matrix(0, K - 1, K - 1) beta_comp[1:M, ] <- t(logML_draw$beta_draw[2:K, ]) if(lags > 1) { beta_comp[(M + 1):(K - 1), 1:(K - 1 - M)] <- diag(M * (lags - 1)) } # Identification if(!is.null(sign_res)) { restrictions <- FALSE counter <- 0 while(!restrictions) { counter <- counter + 1 R_tilde <- matrix(rnorm(M^2, 0, 1), M, M) qr_object <- qr(R_tilde) R <- qr.Q(qr_object) R <- R %*% diag((diag(R) > 0) - (diag(R) < 0)) shock <- t(chol(logML_draw$sigma_draw)) %*% R shock_vec <- as.vector(shock) shock_vec[which(shock_vec < 0)] <- -1 shock_vec[which(shock_vec > 0)] <- 1 if(all(shock_vec == sign_res)) {restrictions <- TRUE} if(counter > 2500) { stop("No matrix fitting the sign-restrictions found.") } } } else { shock <- t(chol(logML_draw$sigma_draw)) } # Compute irf_draw <- array(0, c(M * lags, M * lags, horizon)) irf_draw[1:M, 1:M, 1] <- shock for(j in 2:horizon) { irf_draw[, , j] <- irf_draw[, , j - 1] %*% t(beta_comp) } irf_store[i, , , ] <- irf_draw[1:M, 1:M, ] } # if(pred_density) { # X_new <- c(1,Y[N,],X[N,2:(M*(lags-1)+1)]) # y_store[i,] <- X_new%*%logML_draw$beta_draw+t(t(chol(logML_draw$sigma_draw))%*%rnorm(M)) # } } } # Outputs ----------------------------------------------------------------- acc_rate <- accepted / (nburn + nsave) if(irf) { out <- list("beta" = beta_store, "sigma" = sigma_store, "parameters" = par_store, "log_ml" = ml_store, "acceptance" = acc_rate, "irf" = irf_store) } else { out <- list("beta" = beta_store, "sigma" = sigma_store, "parameters" = par_store, "log_ml" = ml_store, "acceptance" = acc_rate) } return(out) }
/exercise_4/exercise_4_var.R
permissive
lnsongxf/econ_exercises
R
false
false
7,717
r
#' @title Bayesian VAR #' @author Nikolas Kuschnig, Lukas Vashold #' @description Bayesian VAR with Hyperpriors #' #' @param data #' @param lags Number of lags to include. #' @param nsave Number of MCMC-draws to store. #' @param nburn Number of MCMC-draws to discard #' @param irf Boolean determining whether to compute impulse responses. #' @param horizon Integer stating the horizon of the impulse responses. #' @param sign_res Numeric matrix of sign restrictions. #' @param mn_prior placeholder #' @param soc_prior placeholder #' @param sur_prior placeholder #' @param scale_hess Number or numerical vector scaling the hessian matrix. #' #' @return Returns a list with stored draws of beta, sigma, the impulse responses, #' as well as all draws of parameters and log-likelihood. #' @export #' bvar <- function(data, lags, nsave = 5000, nburn = 1000, irf = TRUE, horizon = 20, sign_res = NULL, # pred_density = FALSE, mn_prior = TRUE, soc_prior = TRUE, sur_prior = TRUE, scale_hess = c(0.1, 0.03, 0.03)) { # Robustness Checks ------------------------------------------------------- if(nsave < 0 || nburn < 0 || !is.numeric(nsave) || !is.numeric(nburn)) { stop("Iterations were not specified properly.") } # Preparation ------------------------------------------------------------- Y <- as.matrix(data) X <- lag_data(Y, lags) Y <- Y[(lags + 1):nrow(Y), ] X <- X[(lags + 1):nrow(X), ] X <- cbind(1, X) K <- ncol(X) M <- ncol(Y) N <- nrow(Y) # OLS beta_ols <- solve(crossprod(X)) %*% crossprod(X, Y) sse_ols <- crossprod(Y - X %*% beta_ols) sigma_ols <- sigma <- sse_ols / (N - K) # Hyperpriors ------------------------------------------------------------- n_priors <- mn_prior + soc_prior + sur_prior # Prior parameters Y0 <- colMeans(Y[1:lags, ]) par_min <- list("lambda" = 0.0001, "miu" = 0.0001, "theta" = 0.0001) par_max <- list("lambda" = 5, "miu" = 50, "theta" = 50) par_modes <- list("lambda" = 0.2, "miu" = 1, "theta" = 1) par_sd <- list("lambda" = 0.4, "miu" = 1, "theta" = 1) mn_alpha <- 2 # Coefficients of the hyperpriors prior_coef <- list("lambda" = gamma_coef(par_modes$lambda, par_sd$lambda), "miu" = gamma_coef(par_modes$miu, par_sd$miu), "theta" = gamma_coef(par_modes$theta, par_sd$theta)) # Inverse Hessian and Jacobian for drawing proposals H <- diag(n_priors) * scale_hess exp_modes <- exp(c(par_modes$lambda, par_modes$miu, par_modes$theta)) J <- exp_modes / (1 + exp_modes) ^ 2 J[1] <- J[1] * (par_max$lambda - par_min$lambda) J[2] <- J[2] * (par_max$miu - par_min$miu) J[3] <- J[3] * (par_max$theta - par_min$theta) J <- diag(J) HH <- J %*% H %*% t(J) mn_mean <- matrix(0, K, M) mn_mean[2:(M + 1), ] <- diag(M) mn_sd <- apply(Y, 2, function(x) { sqrt(arima(x, order = c(lags, 0, 0))$sigma2) }) mn_var <- 1e06 post_mode <- c("lambda" = par_modes$lambda, "miu" = par_modes$miu, "theta" = par_modes$theta) # Initial Values ---------------------------------------------------------- par_draw <- bounded_rnorm(post_mode, diag(HH), bounds = list("min" = par_min, "max" = par_max)) logML_draw <- logML(Y, X, lags, Y_row = N, Y_col = M, par = list("lambda" = par_draw[1], "miu" = par_draw[2], "theta" = par_draw[3], "alpha" = mn_alpha, "psi" = mn_sd), mn_mean, mn_sd, mn_var, Y0, prior_coef) # Storage par_store <- matrix(NA, nsave + nburn, length(post_mode)) ml_store <- vector("numeric", nsave + nburn) beta_store <- array(NA, c(nsave, K, M)) sigma_store <- array(NA, c(nsave, M, M)) accepted <- 0 if(irf) {irf_store <- array(NA, c(nsave, M, M, horizon))} if(!is.null(sign_res)) {sign_res <- as.vector(sign_res)} # if(pred_density) {y_store <- matrix(NA, nrow = nsave, M)} # Loop -------------------------------------------------------------------- for(i in (1 - nburn):nsave) { # Metropolis-Hastings par_temp <- bounded_rnorm(par_draw, diag(HH), bounds = list("min" = par_min, "max" = par_max)) logML_temp <- logML(Y, X, lags, Y_row = N, Y_col = M, par = list("lambda" = par_temp[1], "miu" = par_temp[2], "theta" = par_temp[3], "alpha" = mn_alpha, "psi" = mn_sd), mn_mean, mn_sd, mn_var, Y0, prior_coef) if(runif(1) < exp(logML_temp$logML - logML_draw$logML)) { logML_draw <- logML_temp par_draw <- par_temp accepted <- accepted + 1 } else { logML_draw <- logML(Y, X, lags, Y_row = N, Y_col = M, par = list("lambda" = par_draw[1], "miu" = par_draw[2], "theta" = par_draw[3], "alpha" = mn_alpha, "psi" = mn_sd), mn_mean, mn_sd, mn_var, Y0, prior_coef) } # Storage par_store[i + nburn, ] <- par_draw ml_store[i + nburn] <- logML_draw$logML if(i > 0) { beta_store[i, , ] <- logML_draw$beta_draw sigma_store[i, , ] <- logML_draw$sigma_draw # Impulse Responses if(irf) { # Companion matrix beta_comp <- matrix(0, K - 1, K - 1) beta_comp[1:M, ] <- t(logML_draw$beta_draw[2:K, ]) if(lags > 1) { beta_comp[(M + 1):(K - 1), 1:(K - 1 - M)] <- diag(M * (lags - 1)) } # Identification if(!is.null(sign_res)) { restrictions <- FALSE counter <- 0 while(!restrictions) { counter <- counter + 1 R_tilde <- matrix(rnorm(M^2, 0, 1), M, M) qr_object <- qr(R_tilde) R <- qr.Q(qr_object) R <- R %*% diag((diag(R) > 0) - (diag(R) < 0)) shock <- t(chol(logML_draw$sigma_draw)) %*% R shock_vec <- as.vector(shock) shock_vec[which(shock_vec < 0)] <- -1 shock_vec[which(shock_vec > 0)] <- 1 if(all(shock_vec == sign_res)) {restrictions <- TRUE} if(counter > 2500) { stop("No matrix fitting the sign-restrictions found.") } } } else { shock <- t(chol(logML_draw$sigma_draw)) } # Compute irf_draw <- array(0, c(M * lags, M * lags, horizon)) irf_draw[1:M, 1:M, 1] <- shock for(j in 2:horizon) { irf_draw[, , j] <- irf_draw[, , j - 1] %*% t(beta_comp) } irf_store[i, , , ] <- irf_draw[1:M, 1:M, ] } # if(pred_density) { # X_new <- c(1,Y[N,],X[N,2:(M*(lags-1)+1)]) # y_store[i,] <- X_new%*%logML_draw$beta_draw+t(t(chol(logML_draw$sigma_draw))%*%rnorm(M)) # } } } # Outputs ----------------------------------------------------------------- acc_rate <- accepted / (nburn + nsave) if(irf) { out <- list("beta" = beta_store, "sigma" = sigma_store, "parameters" = par_store, "log_ml" = ml_store, "acceptance" = acc_rate, "irf" = irf_store) } else { out <- list("beta" = beta_store, "sigma" = sigma_store, "parameters" = par_store, "log_ml" = ml_store, "acceptance" = acc_rate) } return(out) }
#' Load in data from 10x experiment #' #' Creates a full or sparse matrix from a sparse data matrix provided by 10X #' genomics. #' #' @param data_dir Directory containing the matrix.mtx, genes.tsv, and barcodes.tsv #' files provided by 10x. A vector or named vector can be given in order to load #' several data directories. If a named vector is given, the cell barcode names #' will be prefixed with the name. #' @param min_total_cell_counts integer(1) threshold such that cells (barcodes) #' with total counts below the threshold are filtered out #' @param min_mean_gene_counts numeric(1) threshold such that genes with mean #' counts below the threshold are filtered out. #' @param ... passed arguments #' #' @details This function was developed from the \code{Read10X} function from #' the \code{Seurat} package. #' #' @return If \code{expand} is TRUE, returns an SCESet object with counts data #' and log2(cpm + offset) as expression data; else returns a sparse matrix with #' rows and columns labeled. #' #' @importFrom Matrix readMM #' @rdname read10xResults #' @aliases read10xResults read10XResults #' @export #' @examples #' \dontrun{ #' sce10x <- read10Xxesults("path/to/data/directory") #' count_matrix_10x <- read10xResults("path/to/data/directory", expand = FALSE) #' } read10xResults <- function(data_dir, min_total_cell_counts = NULL, min_mean_gene_counts = NULL) { nsets <- length(data_dir) full_data <- vector("list", nsets) gene_info_list <- vector("list", nsets) cell_info_list <- vector("list", nsets) for (i in seq_len(nsets)) { run <- data_dir[i] barcode.loc <- file.path(run, "barcodes.tsv") gene.loc <- file.path(run, "genes.tsv") matrix.loc <- file.path(run, "matrix.mtx") ## read sparse count matrix data_mat <- Matrix::readMM(matrix.loc) ## define filters if (!is.null(min_total_cell_counts)) { keep_barcode <- (Matrix::colSums(data_mat) >= min_total_cell_counts) data_mat <- data_mat[, keep_barcode] } cell.names <- utils::read.table(barcode.loc, header = FALSE, colClasses = "character")[[1]] dataset <- i if (!is.null(names(data_dir))) { dataset <- names(data_dir)[i] } full_data[[i]] <- data_mat gene_info_list[[i]] <- utils::read.table(gene.loc, header = FALSE, colClasses = "character") cell_info_list[[i]] <- DataFrame(dataset = dataset, barcode = cell.names) } # Checking gene uniqueness. if (nsets > 1 && length(unique(gene_info_list)) != 1L) { stop("gene information differs between runs") } gene_info <- gene_info_list[[1]] colnames(gene_info) <- c("id", "symbol") rownames(gene_info) <- gene_info$id # Forming the full data matrix. full_data <- do.call(cbind, full_data) rownames(full_data) <- gene_info$id # Applying some filtering if requested. if (!is.null(min_mean_gene_counts)) { keep_gene <- (Matrix::rowSums(data_mat) >= min_mean_gene_counts) full_data <- full_data[keep_gene,] gene_info <- gene_info[keep_gene,] } # Adding the cell data. cell_info <- do.call(rbind, cell_info_list) SingleCellExperiment(list(counts = full_data), rowData = gene_info, colData = cell_info) } #' @rdname read10xResults #' @export read10XResults <- function(...) { read10xResults(...) }
/R/10ximport-wrapper.R
permissive
Jun-Lizst/archive-scater
R
false
false
3,611
r
#' Load in data from 10x experiment #' #' Creates a full or sparse matrix from a sparse data matrix provided by 10X #' genomics. #' #' @param data_dir Directory containing the matrix.mtx, genes.tsv, and barcodes.tsv #' files provided by 10x. A vector or named vector can be given in order to load #' several data directories. If a named vector is given, the cell barcode names #' will be prefixed with the name. #' @param min_total_cell_counts integer(1) threshold such that cells (barcodes) #' with total counts below the threshold are filtered out #' @param min_mean_gene_counts numeric(1) threshold such that genes with mean #' counts below the threshold are filtered out. #' @param ... passed arguments #' #' @details This function was developed from the \code{Read10X} function from #' the \code{Seurat} package. #' #' @return If \code{expand} is TRUE, returns an SCESet object with counts data #' and log2(cpm + offset) as expression data; else returns a sparse matrix with #' rows and columns labeled. #' #' @importFrom Matrix readMM #' @rdname read10xResults #' @aliases read10xResults read10XResults #' @export #' @examples #' \dontrun{ #' sce10x <- read10Xxesults("path/to/data/directory") #' count_matrix_10x <- read10xResults("path/to/data/directory", expand = FALSE) #' } read10xResults <- function(data_dir, min_total_cell_counts = NULL, min_mean_gene_counts = NULL) { nsets <- length(data_dir) full_data <- vector("list", nsets) gene_info_list <- vector("list", nsets) cell_info_list <- vector("list", nsets) for (i in seq_len(nsets)) { run <- data_dir[i] barcode.loc <- file.path(run, "barcodes.tsv") gene.loc <- file.path(run, "genes.tsv") matrix.loc <- file.path(run, "matrix.mtx") ## read sparse count matrix data_mat <- Matrix::readMM(matrix.loc) ## define filters if (!is.null(min_total_cell_counts)) { keep_barcode <- (Matrix::colSums(data_mat) >= min_total_cell_counts) data_mat <- data_mat[, keep_barcode] } cell.names <- utils::read.table(barcode.loc, header = FALSE, colClasses = "character")[[1]] dataset <- i if (!is.null(names(data_dir))) { dataset <- names(data_dir)[i] } full_data[[i]] <- data_mat gene_info_list[[i]] <- utils::read.table(gene.loc, header = FALSE, colClasses = "character") cell_info_list[[i]] <- DataFrame(dataset = dataset, barcode = cell.names) } # Checking gene uniqueness. if (nsets > 1 && length(unique(gene_info_list)) != 1L) { stop("gene information differs between runs") } gene_info <- gene_info_list[[1]] colnames(gene_info) <- c("id", "symbol") rownames(gene_info) <- gene_info$id # Forming the full data matrix. full_data <- do.call(cbind, full_data) rownames(full_data) <- gene_info$id # Applying some filtering if requested. if (!is.null(min_mean_gene_counts)) { keep_gene <- (Matrix::rowSums(data_mat) >= min_mean_gene_counts) full_data <- full_data[keep_gene,] gene_info <- gene_info[keep_gene,] } # Adding the cell data. cell_info <- do.call(rbind, cell_info_list) SingleCellExperiment(list(counts = full_data), rowData = gene_info, colData = cell_info) } #' @rdname read10xResults #' @export read10XResults <- function(...) { read10xResults(...) }
library(pirate) ### Name: gem_test ### Title: Implement Fitted GEM criterior on a Data Set ### Aliases: gem_test gem_test_sample gem_test_simsample ### ** Examples #constructing the covariance matrix co <- matrix(0.2, 10, 10) diag(co) <- 1 dataEx <- data_generator1(d = 0.3, R2 = 0.5, v2 = 1, n = 300, co = co, beta1 = rep(1,10),inter = c(0,0)) #fit the GEM dat <- dataEx[[1]] model_nu <- gem_fit(dat = dat, method = "nu") #calculate the population average benefit in the data sample gem_test_sample(dat,model_nu[[2]]) #calculate the population average benefit when outcome under both treatment conditions #is known, usually in a simulated sample bigData <- data_generator3(n = 1000,co = co,bet =dataEx[[2]], inter = c(0,0)) gem_test_simsample(bigData[[1]],bigData[[2]],bigData[[3]],model_nu[[2]])
/data/genthat_extracted_code/pirate/examples/gem_test.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
835
r
library(pirate) ### Name: gem_test ### Title: Implement Fitted GEM criterior on a Data Set ### Aliases: gem_test gem_test_sample gem_test_simsample ### ** Examples #constructing the covariance matrix co <- matrix(0.2, 10, 10) diag(co) <- 1 dataEx <- data_generator1(d = 0.3, R2 = 0.5, v2 = 1, n = 300, co = co, beta1 = rep(1,10),inter = c(0,0)) #fit the GEM dat <- dataEx[[1]] model_nu <- gem_fit(dat = dat, method = "nu") #calculate the population average benefit in the data sample gem_test_sample(dat,model_nu[[2]]) #calculate the population average benefit when outcome under both treatment conditions #is known, usually in a simulated sample bigData <- data_generator3(n = 1000,co = co,bet =dataEx[[2]], inter = c(0,0)) gem_test_simsample(bigData[[1]],bigData[[2]],bigData[[3]],model_nu[[2]])
atom_nom <- function(residuetype, atom, mode){ delta <- -1 natom <- "" switch(mode, full = switch(residuetype, ALA = switch(atom, HB1 = {natom = "QB" delta=1}, HB2 = {natom = "QB" delta=1}, HB3 = {natom = "QB" delta=1}, QB = c()), ARG = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c(), HH11 = c(), HH12 = c(), QH1 = c(), HH21 = c(), HH22 = c(), QH2 = c()), ASN = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD21 = c(), HD22 = c(), QD2 = c()), ASP = switch(atom, HB2 = c(), HB3 = c(), QB = c()), CYS = switch(atom, HB2 = c(), HB3 = c(), HG = c(), QB = c()), CYSS = switch(atom, HB2 = c(), HB3 = c(), QB = c()), GLN = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HE21 = c(), HE22 = c(), QE2 = c()), GLU = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c()), GLY = switch(atom, HA2 = c(), HA3 = c(), QA = c()), HIS = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HD2 = c(), HE1 = c()), ILE = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG12 = c(), HG13 = c(), QG1 = c(), HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c()), LEU = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG = c(), HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c(), HD21 = {natom = "QD2" delta=1}, HD22 = {natom = "QD2" delta=1}, HD23 = {natom = "QD2" delta=1}, QD2 = c(), QQD = c()), LYS = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c(), HE2 = c(), HE3 = c(), QE = c(), HZ1 = {natom = "QZ" delta=1}, HZ2 = {natom = "QZ" delta=1}, HZ3 = {natom = "QZ" delta=1}, QZ = c()), MET = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HE1 = {natom = "QE" delta=1}, HE2 = {natom = "QE" delta=1}, HE3 = {natom = "QE" delta=1}, QE = c()), PHE = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HD2 = c(), QD = c(), HB2 = c(), HB3 = c(), QB = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HZ = c()), PRO = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c()), SER = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG = c()), THR = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG1 = c()), TRP = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HE1 = c(), HE3 = c(), HZ2 = c(), HZ3 = c(), HH2 = c()), TYR = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HD2 = c(), QD = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HH = c()), VAL = switch(atom, HB = c(), HG11 = {natom = "QG1" delta=1}, HG12 = {natom = "QG1" delta=1}, HG13 = {natom = "QG1" delta=1}, QG1 = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), QQG = c())), homitted = switch(residuetype, ALA = switch(atom, HB1 = {natom = "CB" delta=1}, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = c()), ARG = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HD2 = {natom = "CD" delta=1}, HD3 = {natom = "CD" delta=1}, QD = {natom = "CD" delta=1}, HH11 = c(), HH12 = c(), QH1 = c(), HH21 = c(), HH22 = c(), QH2 = c()), ASN = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD21 = c(), HD22 = c(), QD2 = c()), ASP = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}), CYS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, HG = {natom = "SG" delta=1}, QB = {natom = "CB" delta=1}), CYSS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}), GLN = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HE21 = c(), HE22 = c(), QE2 = c()), GLU = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}), GLY = switch(atom, HA2 = c(), HA3 = c(), QA = c()), HIS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HD2 = c(), HE1 = c()), ILE = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG12 = {natom = "CG1" delta=1}, HG13 = {natom = "CG1" delta=1}, QG1 = {natom = "CG1" delta=1}, HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c()), LEU = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG = c(), HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c(), HD21 = {natom = "QD2" delta=1}, HD22 = {natom = "QD2" delta=1}, HD23 = {natom = "QD2" delta=1}, QD2 = c(), QQD = c()), LYS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HD2 = {natom = "CD" delta=1}, HD3 = {natom = "CD" delta=1}, QD = {natom = "CD" delta=1}, HE2 = {natom = "CE" delta=1}, HE3 = {natom = "CE" delta=1}, QE = {natom = "CE" delta=1}, HZ1 = {natom = "QZ" delta=1}, HZ2 = {natom = "QZ" delta=1}, HZ3 = {natom = "QZ" delta=1}, QZ = c()), MET = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HE1 = {natom = "QE" delta=1}, HE2 = {natom = "QE" delta=1}, HE3 = {natom = "QE" delta=1}, QE = c()), PHE = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HD2 = c(), QD = c(), HB2 = c(), HB3 = c(), QB = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HZ = c()), PRO = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c()), SER = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG = {natom = "OG" delta=1}), THR = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG1 = {natom = "OG1" delta=1}), TRP = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HE1 = c(), HE3 = c(), HZ2 = c(), HZ3 = c(), HH2 = c()), TYR = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HD2 = c(), QD = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HH = {natom = "OH" delta=1}), VAL = switch(atom, HB = c(), HG11 = {natom = "QG1" delta=1}, HG12 = {natom = "QG1" delta=1}, HG13 = {natom = "QG1" delta=1}, QG1 = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), QQG = c())), xplor = switch(residuetype, ALA = switch(atom, HB1 = c(), HB2 = c(), HB3 = c(), QB = c()), ARG = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HD2 = c(), HD1 = {natom="HD3" delta=-1}, QD = c(), HH11 = c(), HH12 = c(), QH1 = c(), HH21 = c(), HH22 = c(), QH2 = c()), ASN = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD21 = c(), HD22 = c(), QD2 = c()), ASP = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c()), CYS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, HG = c(), QB = c()), CYSS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c()), GLN = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HE21 = c(), HE22 = c(), QE2 = c()), GLU = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c()), GLY = switch(atom, HA2 = c(), HA1 = {natom="HA3" delta=-1}, QA = c()), HIS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HD2 = c(), HE1 = c()), ILE = switch(atom, HB = c(), HG21 = c(), HG22 = c(), HG23 = c(), QG2 = c(), HG12 = c(), HG11 = {natom="HG13" delta=-1}, QG1 = c(), HD11 = c(), HD12 = c(), HD13 = c(), QD1 = c()), LEU = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG = c(), HD11 = c(), HD12 = c(), HD13 = c(), QD1 = c(), HD21 = c(), HD22 = c(), HD23 = c(), QD2 = c(), QQD = c()), LYS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HD2 = c(), HD1 = {natom="HD3" delta=-1}, QD = c(), HE2 = c(), HE1 = {natom="HE3" delta=-1}, QE = c(), HZ1 = c(), HZ2 = c(), HZ3 = c(), QZ = c()), MET = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HE1 = c(), HE2 = c(), HE3 = c(), QE = c()), PHE = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HD2 = c(), QD = c(), HB2 = c(), HB3 = c(), QB = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HZ = c()), PRO = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HD2 = c(), HD1 = {natom="HD3" delta=-1}, QD = c()), SER = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG = c()), THR = switch(atom, HB = c(), HG21 = c(), HG22 = c(), HG23 = c(), QG2 = c(), HG1 = c()), TRP = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HE1 = c(), HE3 = c(), HZ2 = c(), HZ3 = c(), HH2 = c()), TYR = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HD2 = c(), QD = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HH = c()), VAL = switch(atom, HB = c(), HG11 = c(), HG12 = c(), HG13 = c(), QG1 = c(), HG21 = c(), HG22 = c(), HG23 = c(), QG2 = c(), QQG = c()))) return(list(natom=natom, delta=delta)) }
/R/atom_nom.R
no_license
AdamRahman/sprosr
R
false
false
38,766
r
atom_nom <- function(residuetype, atom, mode){ delta <- -1 natom <- "" switch(mode, full = switch(residuetype, ALA = switch(atom, HB1 = {natom = "QB" delta=1}, HB2 = {natom = "QB" delta=1}, HB3 = {natom = "QB" delta=1}, QB = c()), ARG = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c(), HH11 = c(), HH12 = c(), QH1 = c(), HH21 = c(), HH22 = c(), QH2 = c()), ASN = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD21 = c(), HD22 = c(), QD2 = c()), ASP = switch(atom, HB2 = c(), HB3 = c(), QB = c()), CYS = switch(atom, HB2 = c(), HB3 = c(), HG = c(), QB = c()), CYSS = switch(atom, HB2 = c(), HB3 = c(), QB = c()), GLN = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HE21 = c(), HE22 = c(), QE2 = c()), GLU = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c()), GLY = switch(atom, HA2 = c(), HA3 = c(), QA = c()), HIS = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HD2 = c(), HE1 = c()), ILE = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG12 = c(), HG13 = c(), QG1 = c(), HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c()), LEU = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG = c(), HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c(), HD21 = {natom = "QD2" delta=1}, HD22 = {natom = "QD2" delta=1}, HD23 = {natom = "QD2" delta=1}, QD2 = c(), QQD = c()), LYS = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c(), HE2 = c(), HE3 = c(), QE = c(), HZ1 = {natom = "QZ" delta=1}, HZ2 = {natom = "QZ" delta=1}, HZ3 = {natom = "QZ" delta=1}, QZ = c()), MET = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HE1 = {natom = "QE" delta=1}, HE2 = {natom = "QE" delta=1}, HE3 = {natom = "QE" delta=1}, QE = c()), PHE = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HD2 = c(), QD = c(), HB2 = c(), HB3 = c(), QB = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HZ = c()), PRO = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c()), SER = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG = c()), THR = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG1 = c()), TRP = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HE1 = c(), HE3 = c(), HZ2 = c(), HZ3 = c(), HH2 = c()), TYR = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HD1 = c(), HD2 = c(), QD = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HH = c()), VAL = switch(atom, HB = c(), HG11 = {natom = "QG1" delta=1}, HG12 = {natom = "QG1" delta=1}, HG13 = {natom = "QG1" delta=1}, QG1 = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), QQG = c())), homitted = switch(residuetype, ALA = switch(atom, HB1 = {natom = "CB" delta=1}, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = c()), ARG = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HD2 = {natom = "CD" delta=1}, HD3 = {natom = "CD" delta=1}, QD = {natom = "CD" delta=1}, HH11 = c(), HH12 = c(), QH1 = c(), HH21 = c(), HH22 = c(), QH2 = c()), ASN = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD21 = c(), HD22 = c(), QD2 = c()), ASP = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}), CYS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, HG = {natom = "SG" delta=1}, QB = {natom = "CB" delta=1}), CYSS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}), GLN = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HE21 = c(), HE22 = c(), QE2 = c()), GLU = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}), GLY = switch(atom, HA2 = c(), HA3 = c(), QA = c()), HIS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HD2 = c(), HE1 = c()), ILE = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG12 = {natom = "CG1" delta=1}, HG13 = {natom = "CG1" delta=1}, QG1 = {natom = "CG1" delta=1}, HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c()), LEU = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG = c(), HD11 = {natom = "QD1" delta=1}, HD12 = {natom = "QD1" delta=1}, HD13 = {natom = "QD1" delta=1}, QD1 = c(), HD21 = {natom = "QD2" delta=1}, HD22 = {natom = "QD2" delta=1}, HD23 = {natom = "QD2" delta=1}, QD2 = c(), QQD = c()), LYS = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HD2 = {natom = "CD" delta=1}, HD3 = {natom = "CD" delta=1}, QD = {natom = "CD" delta=1}, HE2 = {natom = "CE" delta=1}, HE3 = {natom = "CE" delta=1}, QE = {natom = "CE" delta=1}, HZ1 = {natom = "QZ" delta=1}, HZ2 = {natom = "QZ" delta=1}, HZ3 = {natom = "QZ" delta=1}, QZ = c()), MET = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG2 = {natom = "CG" delta=1}, HG3 = {natom = "CG" delta=1}, QG = {natom = "CG" delta=1}, HE1 = {natom = "QE" delta=1}, HE2 = {natom = "QE" delta=1}, HE3 = {natom = "QE" delta=1}, QE = c()), PHE = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HD2 = c(), QD = c(), HB2 = c(), HB3 = c(), QB = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HZ = c()), PRO = switch(atom, HB2 = c(), HB3 = c(), QB = c(), HG2 = c(), HG3 = c(), QG = c(), HD2 = c(), HD3 = c(), QD = c()), SER = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HG = {natom = "OG" delta=1}), THR = switch(atom, HB = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), HG1 = {natom = "OG1" delta=1}), TRP = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HE1 = c(), HE3 = c(), HZ2 = c(), HZ3 = c(), HH2 = c()), TYR = switch(atom, HB2 = {natom = "CB" delta=1}, HB3 = {natom = "CB" delta=1}, QB = {natom = "CB" delta=1}, HD1 = c(), HD2 = c(), QD = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HH = {natom = "OH" delta=1}), VAL = switch(atom, HB = c(), HG11 = {natom = "QG1" delta=1}, HG12 = {natom = "QG1" delta=1}, HG13 = {natom = "QG1" delta=1}, QG1 = c(), HG21 = {natom = "QG2" delta=1}, HG22 = {natom = "QG2" delta=1}, HG23 = {natom = "QG2" delta=1}, QG2 = c(), QQG = c())), xplor = switch(residuetype, ALA = switch(atom, HB1 = c(), HB2 = c(), HB3 = c(), QB = c()), ARG = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HD2 = c(), HD1 = {natom="HD3" delta=-1}, QD = c(), HH11 = c(), HH12 = c(), QH1 = c(), HH21 = c(), HH22 = c(), QH2 = c()), ASN = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD21 = c(), HD22 = c(), QD2 = c()), ASP = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c()), CYS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, HG = c(), QB = c()), CYSS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c()), GLN = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HE21 = c(), HE22 = c(), QE2 = c()), GLU = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c()), GLY = switch(atom, HA2 = c(), HA1 = {natom="HA3" delta=-1}, QA = c()), HIS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HD2 = c(), HE1 = c()), ILE = switch(atom, HB = c(), HG21 = c(), HG22 = c(), HG23 = c(), QG2 = c(), HG12 = c(), HG11 = {natom="HG13" delta=-1}, QG1 = c(), HD11 = c(), HD12 = c(), HD13 = c(), QD1 = c()), LEU = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG = c(), HD11 = c(), HD12 = c(), HD13 = c(), QD1 = c(), HD21 = c(), HD22 = c(), HD23 = c(), QD2 = c(), QQD = c()), LYS = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HD2 = c(), HD1 = {natom="HD3" delta=-1}, QD = c(), HE2 = c(), HE1 = {natom="HE3" delta=-1}, QE = c(), HZ1 = c(), HZ2 = c(), HZ3 = c(), QZ = c()), MET = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HE1 = c(), HE2 = c(), HE3 = c(), QE = c()), PHE = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HD2 = c(), QD = c(), HB2 = c(), HB3 = c(), QB = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HZ = c()), PRO = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG2 = c(), HG1 = {natom="HG3" delta=-1}, QG = c(), HD2 = c(), HD1 = {natom="HD3" delta=-1}, QD = c()), SER = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HG = c()), THR = switch(atom, HB = c(), HG21 = c(), HG22 = c(), HG23 = c(), QG2 = c(), HG1 = c()), TRP = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HE1 = c(), HE3 = c(), HZ2 = c(), HZ3 = c(), HH2 = c()), TYR = switch(atom, HB2 = c(), HB1 = {natom="HB3" delta=-1}, QB = c(), HD1 = c(), HD2 = c(), QD = c(), HE1 = c(), HE2 = c(), QE = c(), QR = c(), HH = c()), VAL = switch(atom, HB = c(), HG11 = c(), HG12 = c(), HG13 = c(), QG1 = c(), HG21 = c(), HG22 = c(), HG23 = c(), QG2 = c(), QQG = c()))) return(list(natom=natom, delta=delta)) }
# THIS FUNCTION CALCULATES CLIMATIC WATER DEFICIT USING EITHER MONTHLY ANNUAL DATA oR MEAN MONTHLY DATA # DATA INPUT: site (i.e. a unique id for a given location), slope (degrees), latitude (decimal degrees), folded aspect (degrees), ppt, tmean, soilawc (in cm.; default is 200 cm), month, and year (if using annual data only; default is null)) ####note: you input each variable as a vector, but they need to all line up correctly and be the same length, except for soil awc (that way if you don't have soil awc data for each site, you can specify a specific value, such as soilawc = 300) # PACKAGES THAT MUST BE INSTALLED BEFORE RUNNING THE SCRIPT: data.table and geosphere # EXAMPLE SCRIPTS: ###cwd_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,year=data$year,type="annual") ###cwd_normal_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,type="normal") #example script with soil awc specified as one number across all sites: ### cwd_normal_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,soilawc=300,type="normal") #example script where I have unique soil awc data for each site: ### cwd_normal_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,soilawc=data$soilawc,type="normal") cwd_function <- function(site,slope,latitude,foldedaspect,ppt,tmean,month,soilawc=200,year=NULL,type=c('normal','annual')) { # Packages require(data.table) require(geosphere) #R SCRIPT if (type =="annual"){ data<-as.data.table(cbind(as.character(site),slope,latitude,foldedaspect,ppt,tmean,month,year))[,soilawc:=soilawc] colnames(data)<-c("site","slope","latitude","foldedaspect","ppt","tmean","month","year","soilawc")} if (type =="normal"){ data<-as.data.table(cbind(site,slope,latitude,foldedaspect,ppt,tmean,month))[,soilawc:=soilawc] colnames(data)<-c("site","slope","latitude","foldedaspect","ppt","tmean","month","soilawc") } data$site<-as.character(data$site) data$slope<-as.numeric(as.character(data$slope)) data$latitude<-as.numeric(as.character(data$latitude)) data$foldedaspect<-as.numeric(as.character(data$foldedaspect)) data$ppt<-as.numeric(as.character(data$ppt)) data$tmean<-as.numeric(as.character(data$tmean)) data$month<-as.numeric(as.character(data$month)) ### for 30 year normal data only, we'll create iterations so that way the water storage can carry over from one year to the next if (type == "normal"){year<-c(rep(1,length(data$site)),rep(2,length(data$site)),rep(3,length(data$site)),rep(4,length(data$site)),rep(5,length(data$site)),rep(6,length(data$site)),rep(7,length(data$site)),rep(8,length(data$site)),rep(9,length(data$site)),rep(10,length(data$site))) data<-rbind(data,data,data,data,data,data,data,data,data,data)} data$year<-as.numeric(as.character(year)) # calculate daylength daylength<-vector() datasite<-data[,.(latitude=mean(latitude)),by=.(site)] for (i in 1:length(datasite$latitude)){ dl<-daylength(datasite$latitude[i],1:365) day<- tapply(dl, rep(1:12, c(31,28,31,30,31,30,31,31,30,31,30,31)), mean) site <- as.vector(rep(datasite$site[i],length(day))) month<-as.vector(c(1,2,3,4,5,6,7,8,9,10,11,12)) join<-cbind(site,month,day) daylength<-rbind(daylength,join) } daylength<-as.data.frame(daylength) daylength$site<-as.character(daylength$site) daylength$month<-as.numeric(as.character(daylength$month)) daylength$day<-as.numeric(as.character(daylength$day)) data<-merge(data,daylength,by=c("site","month")) ##########data$year<-year # calculate all other variables data[,fm:=ifelse(tmean<0,0,ifelse(tmean>=6,1,tmean*0.166666666))] data[,rainm:=fm*ppt] data[,snowm:=(1-fm)*ppt] data<-setorder(data,site,year,month) sites<-unique(data$site) mergedata<-vector() for (i in 1:length(sites)){ packm<-vector() sitedat<-setorder(data,site,year,month)[site==sites[i],] for (j in 1:length(sitedat$site)){ packmsite<-ifelse(j>1,(((1-sitedat$fm[j])^2)*sitedat$ppt[j])+((1-sitedat$fm[j])*packm[j-1]),(((1-sitedat$fm[j])^2)*sitedat$ppt[j])) packm<-c(packm,packmsite) site<-as.character(sitedat$site) year<-as.numeric(as.character(sitedat$year)) month<-as.numeric(as.character(sitedat$month)) } mergedat<-cbind(site,year,month,packm) mergedata<-rbind(mergedata,mergedat) } mergedt<-as.data.table(mergedata) mergedt$year<-as.numeric(as.character(mergedt$year)) mergedt$month<-as.numeric(as.character(mergedt$month)) mergedt$site<-as.character(mergedt$site) data<-merge(data,mergedt,by=c("site","year","month")) data$packm<-as.numeric(as.character(data$packm)) data[,meltm:=fm*snowm*data.table::shift(packm,1L,type="lag",fill=0)] data[,wm:=rainm+meltm] data[month==1 | month==3 |month==5|month==7|month==8|month==10|month==12,days:=31] data[month==4 | month==6 |month==9|month==11,days:=30] data[month==2,days:=28] data[,ea:=exp(((17.3*tmean)/(tmean+273.2)))*0.611] # convert slope, folded aspect, and latitude to radians data[,sloprad:=slope*0.0174532925] data[,afrad:=foldedaspect*0.0174532925] data[,latrad:=latitude*0.0174532925] #calculate heat load data[,heatload:=0.339+0.808*(cos(latrad)*cos(sloprad))-0.196*(sin(latrad)*sin(sloprad))-0.482*(cos(afrad)*sin(sloprad))] data[,petm:=ifelse(tmean<0,0,((((ea*tmean)/(tmean+273.3))*day*days*29.8)*heatload/10))] mergedata<-vector() for (i in 1:length(sites)){ soilm<-vector() sitedat<-setorder(data,site,year,month)[site==sites[i],] for (j in 1:length(sitedat$site)){ soilmsite<-ifelse(j>1,ifelse((sitedat$wm[j]-sitedat$petm[j]+soilm[j-1])<=0,0,ifelse((sitedat$wm[j]-sitedat$petm[j]+soilm[j-1])<sitedat$soilawc[j],(sitedat$wm[j]-sitedat$petm[j]+soilm[j-1]),sitedat$soilawc[j])),ifelse((sitedat$wm[j]-sitedat$petm[j])<=0,0,ifelse((sitedat$wm[j]-sitedat$petm[j])<sitedat$soilawc[j],(sitedat$wm[j]-sitedat$petm[j]),sitedat$soilawc[j]))) soilm<-c(soilm,soilmsite) site<-as.character(sitedat$site) year<-as.numeric(as.character(sitedat$year)) month<-as.numeric(as.character(sitedat$month)) } mergedat<-cbind(site,year,month,soilm) mergedata<-rbind(mergedata,mergedat) } mergedt<-as.data.table(mergedata) mergedt$year<-as.numeric(as.character(mergedt$year)) mergedt$month<-as.numeric(as.character(mergedt$month)) mergedt$site<-as.character(mergedt$site) data<-merge(data,mergedt,by=c("site","year","month")) data$soilm<-as.numeric(as.character(data$soilm)) data[,soilm1:=data.table::shift(soilm,1L,type="lag",fill=0)] data[,deltsoil:=(soilm1*(1-(exp(-1*(petm-wm)/soilawc))))] data[,deltsoilwm:=ifelse(deltsoil>0,wm+deltsoil,wm)] data[,aet:=ifelse(deltsoilwm<petm,deltsoilwm,petm)] data[,cwd:=petm-aet] ##### for 800 m normal data then we subset to get just the last simulation if (type == "normal"){data<-data[year==10,]} return(data)}
/resources/calculations/cwd_function.R
no_license
rahuezo/gdp_temperature_project
R
false
false
7,009
r
# THIS FUNCTION CALCULATES CLIMATIC WATER DEFICIT USING EITHER MONTHLY ANNUAL DATA oR MEAN MONTHLY DATA # DATA INPUT: site (i.e. a unique id for a given location), slope (degrees), latitude (decimal degrees), folded aspect (degrees), ppt, tmean, soilawc (in cm.; default is 200 cm), month, and year (if using annual data only; default is null)) ####note: you input each variable as a vector, but they need to all line up correctly and be the same length, except for soil awc (that way if you don't have soil awc data for each site, you can specify a specific value, such as soilawc = 300) # PACKAGES THAT MUST BE INSTALLED BEFORE RUNNING THE SCRIPT: data.table and geosphere # EXAMPLE SCRIPTS: ###cwd_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,year=data$year,type="annual") ###cwd_normal_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,type="normal") #example script with soil awc specified as one number across all sites: ### cwd_normal_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,soilawc=300,type="normal") #example script where I have unique soil awc data for each site: ### cwd_normal_data<-cwd_function(site=data$site,slope=data$slope,latitude=data$latitude,foldedaspect=data$foldedaspect,ppt=data$ppt,tmean=data$tmean,month=data$month,soilawc=data$soilawc,type="normal") cwd_function <- function(site,slope,latitude,foldedaspect,ppt,tmean,month,soilawc=200,year=NULL,type=c('normal','annual')) { # Packages require(data.table) require(geosphere) #R SCRIPT if (type =="annual"){ data<-as.data.table(cbind(as.character(site),slope,latitude,foldedaspect,ppt,tmean,month,year))[,soilawc:=soilawc] colnames(data)<-c("site","slope","latitude","foldedaspect","ppt","tmean","month","year","soilawc")} if (type =="normal"){ data<-as.data.table(cbind(site,slope,latitude,foldedaspect,ppt,tmean,month))[,soilawc:=soilawc] colnames(data)<-c("site","slope","latitude","foldedaspect","ppt","tmean","month","soilawc") } data$site<-as.character(data$site) data$slope<-as.numeric(as.character(data$slope)) data$latitude<-as.numeric(as.character(data$latitude)) data$foldedaspect<-as.numeric(as.character(data$foldedaspect)) data$ppt<-as.numeric(as.character(data$ppt)) data$tmean<-as.numeric(as.character(data$tmean)) data$month<-as.numeric(as.character(data$month)) ### for 30 year normal data only, we'll create iterations so that way the water storage can carry over from one year to the next if (type == "normal"){year<-c(rep(1,length(data$site)),rep(2,length(data$site)),rep(3,length(data$site)),rep(4,length(data$site)),rep(5,length(data$site)),rep(6,length(data$site)),rep(7,length(data$site)),rep(8,length(data$site)),rep(9,length(data$site)),rep(10,length(data$site))) data<-rbind(data,data,data,data,data,data,data,data,data,data)} data$year<-as.numeric(as.character(year)) # calculate daylength daylength<-vector() datasite<-data[,.(latitude=mean(latitude)),by=.(site)] for (i in 1:length(datasite$latitude)){ dl<-daylength(datasite$latitude[i],1:365) day<- tapply(dl, rep(1:12, c(31,28,31,30,31,30,31,31,30,31,30,31)), mean) site <- as.vector(rep(datasite$site[i],length(day))) month<-as.vector(c(1,2,3,4,5,6,7,8,9,10,11,12)) join<-cbind(site,month,day) daylength<-rbind(daylength,join) } daylength<-as.data.frame(daylength) daylength$site<-as.character(daylength$site) daylength$month<-as.numeric(as.character(daylength$month)) daylength$day<-as.numeric(as.character(daylength$day)) data<-merge(data,daylength,by=c("site","month")) ##########data$year<-year # calculate all other variables data[,fm:=ifelse(tmean<0,0,ifelse(tmean>=6,1,tmean*0.166666666))] data[,rainm:=fm*ppt] data[,snowm:=(1-fm)*ppt] data<-setorder(data,site,year,month) sites<-unique(data$site) mergedata<-vector() for (i in 1:length(sites)){ packm<-vector() sitedat<-setorder(data,site,year,month)[site==sites[i],] for (j in 1:length(sitedat$site)){ packmsite<-ifelse(j>1,(((1-sitedat$fm[j])^2)*sitedat$ppt[j])+((1-sitedat$fm[j])*packm[j-1]),(((1-sitedat$fm[j])^2)*sitedat$ppt[j])) packm<-c(packm,packmsite) site<-as.character(sitedat$site) year<-as.numeric(as.character(sitedat$year)) month<-as.numeric(as.character(sitedat$month)) } mergedat<-cbind(site,year,month,packm) mergedata<-rbind(mergedata,mergedat) } mergedt<-as.data.table(mergedata) mergedt$year<-as.numeric(as.character(mergedt$year)) mergedt$month<-as.numeric(as.character(mergedt$month)) mergedt$site<-as.character(mergedt$site) data<-merge(data,mergedt,by=c("site","year","month")) data$packm<-as.numeric(as.character(data$packm)) data[,meltm:=fm*snowm*data.table::shift(packm,1L,type="lag",fill=0)] data[,wm:=rainm+meltm] data[month==1 | month==3 |month==5|month==7|month==8|month==10|month==12,days:=31] data[month==4 | month==6 |month==9|month==11,days:=30] data[month==2,days:=28] data[,ea:=exp(((17.3*tmean)/(tmean+273.2)))*0.611] # convert slope, folded aspect, and latitude to radians data[,sloprad:=slope*0.0174532925] data[,afrad:=foldedaspect*0.0174532925] data[,latrad:=latitude*0.0174532925] #calculate heat load data[,heatload:=0.339+0.808*(cos(latrad)*cos(sloprad))-0.196*(sin(latrad)*sin(sloprad))-0.482*(cos(afrad)*sin(sloprad))] data[,petm:=ifelse(tmean<0,0,((((ea*tmean)/(tmean+273.3))*day*days*29.8)*heatload/10))] mergedata<-vector() for (i in 1:length(sites)){ soilm<-vector() sitedat<-setorder(data,site,year,month)[site==sites[i],] for (j in 1:length(sitedat$site)){ soilmsite<-ifelse(j>1,ifelse((sitedat$wm[j]-sitedat$petm[j]+soilm[j-1])<=0,0,ifelse((sitedat$wm[j]-sitedat$petm[j]+soilm[j-1])<sitedat$soilawc[j],(sitedat$wm[j]-sitedat$petm[j]+soilm[j-1]),sitedat$soilawc[j])),ifelse((sitedat$wm[j]-sitedat$petm[j])<=0,0,ifelse((sitedat$wm[j]-sitedat$petm[j])<sitedat$soilawc[j],(sitedat$wm[j]-sitedat$petm[j]),sitedat$soilawc[j]))) soilm<-c(soilm,soilmsite) site<-as.character(sitedat$site) year<-as.numeric(as.character(sitedat$year)) month<-as.numeric(as.character(sitedat$month)) } mergedat<-cbind(site,year,month,soilm) mergedata<-rbind(mergedata,mergedat) } mergedt<-as.data.table(mergedata) mergedt$year<-as.numeric(as.character(mergedt$year)) mergedt$month<-as.numeric(as.character(mergedt$month)) mergedt$site<-as.character(mergedt$site) data<-merge(data,mergedt,by=c("site","year","month")) data$soilm<-as.numeric(as.character(data$soilm)) data[,soilm1:=data.table::shift(soilm,1L,type="lag",fill=0)] data[,deltsoil:=(soilm1*(1-(exp(-1*(petm-wm)/soilawc))))] data[,deltsoilwm:=ifelse(deltsoil>0,wm+deltsoil,wm)] data[,aet:=ifelse(deltsoilwm<petm,deltsoilwm,petm)] data[,cwd:=petm-aet] ##### for 800 m normal data then we subset to get just the last simulation if (type == "normal"){data<-data[year==10,]} return(data)}
testlist <- list(x = c(2.58981145684914e-307, 4.94065645841247e-324, 0, 5.92314661134617e-304, 0, 0, 3.21687814903302e+181, 1.81250437761959e-207, 7.48552777617268e+247, 5.77636796151408e-275, NaN, -9.40591696517169e+24, 1.00496080260073e+180, -7.99990688549151e-280, 1.53047510903779e-314, 0, 0, -5.15273907786594e-36, -6.95715257111252e+306, NaN, -1.65652687672654e-181, NaN, -1.06817373190923e+297, 3.53369545915248e+72, 7.21902962651992e-304, 5.50339608387342e-310, 0, 1.390671161567e-308, -4.73574659118105e+305, NaN, 5.0453059431966e+182, 3.91135427752315e-274, -1.34765550943377e+28, 9.11136727638145e-311, -6.67113314602392e+306, -5.82852024984172e+303, 8.85449539944218e-159, 2.14327978499502e-312, 128978.107570072, 1.59875023337884e-112, 8.98637298518713e-243, 1.6690200483343e-308, -7.98824203857711e-280, 9.11136590428902e-311, -6.67113314602392e+306, 4.8212389505418e+279, 1.62597454369523e-260, 2.13959396519322e+181, NaN, 5.2404436192131e+279, 9.94246486511075e-297, -1.34747548880033e+28, 2.33251002275375e-308, -4.19987381709656e-140, 7.20834935387592e-304, 8.85470246026103e-159, 5.48679624958878e-310, -1.27856197940926e+306, -5.15273908894671e-36, -7.72134029854232e-84, 7.15597569347109e-251, 2.42061551367857e+35, 2.41751947069162e+35, -4.19983489031012e-140), y = c(NaN, -8.15391703403251e-280, 1.00496080260072e+180, 8.02122686268216e-312, -4.16709697076072e+304, NaN, 3.53369545917587e+72, -6.671133146024e+306, 7.20834927233968e-304, -4.80964726313466e+306, -1.50540387407455e+85, -3.82914315864077e+305, -1.10534589198562e-176, NaN, -5.83693282055951e+294, 4.18006618602297e-297, 5.0758839169449e-116, 2.58981098488467e-307, 6.05156985652021e+34, 1.06096233928348e+37, NaN, 3.54164535367902e-317, 9.94246486511075e-297, 5.48671568880241e-310, -1.06812920585108e+297, -1.06812920585333e+297, -4.4610881607846e-140, 7.29112201950355e-304, -1.34763370135724e+28, -1.34765550943381e+28, -1.34765550943381e+28, -1.34765550943381e+28, -1.34765550943381e+28, -1.34765550943381e+28, -5.48684606877171e+303, 1.61363344975071e+184, -4.72620764279479e-85, -3.3131898344407e+304, 9.74576447753728e-113, 5.07588390157017e-116, 5.09911232106546e+182, 5.77636807742164e-275, NaN, 4.77830972673675e-299, 9.34609791357e-307, NaN, -3.07918242955014e+296, 4.18006618602297e-297, 1.26707338641151e-279, -2.94449594723056e+47, -2.94449594579902e+47, NaN, NaN, 3.53369910561397e+72, 3.13151305916514e-294, 1.52973827771342e-308, 1.3953860590809e-258, 5.48663231790394e-310, 2.31663158087643e+77, -1.49960546094526e+126, 0)) result <- do.call(blorr:::blr_pairs_cpp,testlist) str(result)
/blorr/inst/testfiles/blr_pairs_cpp/libFuzzer_blr_pairs_cpp/blr_pairs_cpp_valgrind_files/1609956838-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
2,626
r
testlist <- list(x = c(2.58981145684914e-307, 4.94065645841247e-324, 0, 5.92314661134617e-304, 0, 0, 3.21687814903302e+181, 1.81250437761959e-207, 7.48552777617268e+247, 5.77636796151408e-275, NaN, -9.40591696517169e+24, 1.00496080260073e+180, -7.99990688549151e-280, 1.53047510903779e-314, 0, 0, -5.15273907786594e-36, -6.95715257111252e+306, NaN, -1.65652687672654e-181, NaN, -1.06817373190923e+297, 3.53369545915248e+72, 7.21902962651992e-304, 5.50339608387342e-310, 0, 1.390671161567e-308, -4.73574659118105e+305, NaN, 5.0453059431966e+182, 3.91135427752315e-274, -1.34765550943377e+28, 9.11136727638145e-311, -6.67113314602392e+306, -5.82852024984172e+303, 8.85449539944218e-159, 2.14327978499502e-312, 128978.107570072, 1.59875023337884e-112, 8.98637298518713e-243, 1.6690200483343e-308, -7.98824203857711e-280, 9.11136590428902e-311, -6.67113314602392e+306, 4.8212389505418e+279, 1.62597454369523e-260, 2.13959396519322e+181, NaN, 5.2404436192131e+279, 9.94246486511075e-297, -1.34747548880033e+28, 2.33251002275375e-308, -4.19987381709656e-140, 7.20834935387592e-304, 8.85470246026103e-159, 5.48679624958878e-310, -1.27856197940926e+306, -5.15273908894671e-36, -7.72134029854232e-84, 7.15597569347109e-251, 2.42061551367857e+35, 2.41751947069162e+35, -4.19983489031012e-140), y = c(NaN, -8.15391703403251e-280, 1.00496080260072e+180, 8.02122686268216e-312, -4.16709697076072e+304, NaN, 3.53369545917587e+72, -6.671133146024e+306, 7.20834927233968e-304, -4.80964726313466e+306, -1.50540387407455e+85, -3.82914315864077e+305, -1.10534589198562e-176, NaN, -5.83693282055951e+294, 4.18006618602297e-297, 5.0758839169449e-116, 2.58981098488467e-307, 6.05156985652021e+34, 1.06096233928348e+37, NaN, 3.54164535367902e-317, 9.94246486511075e-297, 5.48671568880241e-310, -1.06812920585108e+297, -1.06812920585333e+297, -4.4610881607846e-140, 7.29112201950355e-304, -1.34763370135724e+28, -1.34765550943381e+28, -1.34765550943381e+28, -1.34765550943381e+28, -1.34765550943381e+28, -1.34765550943381e+28, -5.48684606877171e+303, 1.61363344975071e+184, -4.72620764279479e-85, -3.3131898344407e+304, 9.74576447753728e-113, 5.07588390157017e-116, 5.09911232106546e+182, 5.77636807742164e-275, NaN, 4.77830972673675e-299, 9.34609791357e-307, NaN, -3.07918242955014e+296, 4.18006618602297e-297, 1.26707338641151e-279, -2.94449594723056e+47, -2.94449594579902e+47, NaN, NaN, 3.53369910561397e+72, 3.13151305916514e-294, 1.52973827771342e-308, 1.3953860590809e-258, 5.48663231790394e-310, 2.31663158087643e+77, -1.49960546094526e+126, 0)) result <- do.call(blorr:::blr_pairs_cpp,testlist) str(result)
Nginx provisioning
/Deploy/roles/nginx/readme.rd
no_license
lion-u/Mentorship_program
R
false
false
18
rd
Nginx provisioning
#Q1 Linear Regression Error sigma=0.1 d=8 N=10 ExpectedEin = sigma^2 *(1-(d+1)/N) ExpectedEin #0.001 N=25 sigma^2 *(1-(d+1)/N) #0.0064 N=100 sigma^2 *(1-(d+1)/N) #0.0091 N=500 #0.00982 #Q2 NonLinear Transforms #Q3 #number of parameters + 1 #Q4 Gradient Descent #use chain rule #https://www.khanacademy.org/math/multivariable-calculus/partial_derivatives_topic/partial_derivatives/v/partial-derivatives-2 #Q5 surfaceErrorFunction <- function(u,v) { (u * exp(v) - 2 * v * exp(-u)) ^ 2 } PDEu <- function(u,v) { 2*(exp(v) + 2 * v * exp(-u)) * (u * exp(v) - 2 * v * exp(-u)) } PDEv <- function(u, v) { 2*(exp(v) * u - 2*v*exp(-u)) * (exp(v) * u - 2 * exp(-u)) } learningRate <- 0.1 tolerance <- 10.0 ^ -14 u=1.0 v=1.0 step <- 0 surfaceError <- surfaceErrorFunction(u,v) surfaceError while(surfaceError > tolerance) { uDescent <- PDEu(u,v) vDescent <- PDEv(u,v) u <- u - uDescent * learningRate v <- v - vDescent * learningRate surfaceError <- surfaceErrorFunction(u,v) surfaceError step <- step + 1 step } step #10 #q6 # u #[1] 0.04473629 #> v #[1] 0.02395871 #Q7 u=1.0 v=1.0 step <- 0 maxSteps <- 15 while(step <= maxSteps) { uDescent <- PDEu(u,v) vDescent <- PDEv(u,v) u <- u - uDescent * learningRate uDescent <- PDEu(u,v) vDescent <- PDEv(u,v) v <- v - vDescent * learningRate step <- step + 1 step } surfaceError <- surfaceErrorFunction(u,v) surfaceError # 0.1326554 #8. logistic regression fTargetFunction <- function(trainingPoint, targetLineSlope,targetLineCoeff){ predictedYValue <- (targetLineSlope * trainingPoint$x) + targetLineCoeff if(trainingPoint$y > predictedYValue ) { trainingPointOrientation = 1 #above line } else { trainingPointOrientation = -1 #below line } trainingPointOrientation } crossEntropyFn <- function(trainingPoint, result, weights) { error <- log(1 + exp(-result * tcrossprod(as.matrix(trainingPoint), as.matrix(weights)))) return(error) } gradient <- function( point, result, weights){ num = -(result * point) den = 1 + (exp(result * tcrossprod(as.matrix(point), as.matrix(weights)))) return (num/den) } train <- function(trainingSet, weights, targetLineSlope, targetLineCoeff){ targetVector <- numeric() for (i in 1:nrow(trainingSet)) { trainingPoint <- trainingSet [i,] targetValue <- fTargetFunction(trainingPoint,targetLineSlope, targetLineCoeff); targetVector <- c(targetVector, targetValue); } learningRate = 0.01 previousWeights = data.frame(-1,-1,-1) step = 0 displacement = 1 threshold = 0.01 while (displacement >= threshold) { sampleSet = sample(1:nrow(trainingSet)) for (i in 1:length(sampleSet)) { feature = trainingSet[i,] result = targetVector[i] descent = gradient(feature, result,weights) weights = weights - learningRate * descent } displacement = norm(as.matrix(previousWeights) - as.matrix(weights)) previousWeights = weights step = step + 1 #print( paste("Disp", displacement)) } print(paste("Wts", weights, "step", step)) return(weights) } avgCrossEntropy <- 0.0 trainingPoints <- 100 testingPoints <- 1000 maxIteration=10 iterationCount = 1 while (iterationCount <= maxIteration) { #Generate targetLine targetLine <- data.frame(runif(2,-1,1),runif(2,-1,1)) names(targetLine ) <- c('x','y') fit <- lm(targetLine$y~targetLine$x) targetLineSlope <- fit$coefficients[2] targetLineCoeff <- fit$coefficients[1] #Initialize weights to 0 weights <- data.frame(0,0,0) names(weights) <- c("w0","w1","w2") trainingSet <- data.frame(1,runif(trainingPoints, -1, 1),runif(trainingPoints, -1, 1)) names(trainingSet) <- c('c','x','y') weights <- train(trainingSet, weights, targetLineSlope, targetLineCoeff) testingSet <- data.frame(1,runif(testingPoints, -1, 1),runif(testingPoints, -1, 1)) names(testingSet) <- c('c','x','y') crossEntropy <- 0 for (i in 1:nrow(testingSet)) { testingPoint <- testingSet [i,] result <- fTargetFunction(testingPoint,targetLineSlope, targetLineCoeff); crossEntropyVal <- crossEntropyFn(testingPoint,result, weights); #print(crossEntropyVal); crossEntropy = crossEntropy + crossEntropyVal } print(paste("CrossEntropy Error Avg",crossEntropy/nrow(testingSet))) avgCrossEntropy <- avgCrossEntropy + (crossEntropy/nrow(testingSet)) iterationCount = iterationCount +1 } print(paste("CrossEntropy Error Avg Mult Iterations",avgCrossEntropy/maxIteration)) #q8. # 0.11 #q9 #353 #q1. c #q2 #q3. c #q4. e #q5. d #q6. e #q7. a #q8. d #q9. b x a #q10
/Assignment5/AssignWk5_V1.R
no_license
dxrodri/Caltech_ML
R
false
false
4,573
r
#Q1 Linear Regression Error sigma=0.1 d=8 N=10 ExpectedEin = sigma^2 *(1-(d+1)/N) ExpectedEin #0.001 N=25 sigma^2 *(1-(d+1)/N) #0.0064 N=100 sigma^2 *(1-(d+1)/N) #0.0091 N=500 #0.00982 #Q2 NonLinear Transforms #Q3 #number of parameters + 1 #Q4 Gradient Descent #use chain rule #https://www.khanacademy.org/math/multivariable-calculus/partial_derivatives_topic/partial_derivatives/v/partial-derivatives-2 #Q5 surfaceErrorFunction <- function(u,v) { (u * exp(v) - 2 * v * exp(-u)) ^ 2 } PDEu <- function(u,v) { 2*(exp(v) + 2 * v * exp(-u)) * (u * exp(v) - 2 * v * exp(-u)) } PDEv <- function(u, v) { 2*(exp(v) * u - 2*v*exp(-u)) * (exp(v) * u - 2 * exp(-u)) } learningRate <- 0.1 tolerance <- 10.0 ^ -14 u=1.0 v=1.0 step <- 0 surfaceError <- surfaceErrorFunction(u,v) surfaceError while(surfaceError > tolerance) { uDescent <- PDEu(u,v) vDescent <- PDEv(u,v) u <- u - uDescent * learningRate v <- v - vDescent * learningRate surfaceError <- surfaceErrorFunction(u,v) surfaceError step <- step + 1 step } step #10 #q6 # u #[1] 0.04473629 #> v #[1] 0.02395871 #Q7 u=1.0 v=1.0 step <- 0 maxSteps <- 15 while(step <= maxSteps) { uDescent <- PDEu(u,v) vDescent <- PDEv(u,v) u <- u - uDescent * learningRate uDescent <- PDEu(u,v) vDescent <- PDEv(u,v) v <- v - vDescent * learningRate step <- step + 1 step } surfaceError <- surfaceErrorFunction(u,v) surfaceError # 0.1326554 #8. logistic regression fTargetFunction <- function(trainingPoint, targetLineSlope,targetLineCoeff){ predictedYValue <- (targetLineSlope * trainingPoint$x) + targetLineCoeff if(trainingPoint$y > predictedYValue ) { trainingPointOrientation = 1 #above line } else { trainingPointOrientation = -1 #below line } trainingPointOrientation } crossEntropyFn <- function(trainingPoint, result, weights) { error <- log(1 + exp(-result * tcrossprod(as.matrix(trainingPoint), as.matrix(weights)))) return(error) } gradient <- function( point, result, weights){ num = -(result * point) den = 1 + (exp(result * tcrossprod(as.matrix(point), as.matrix(weights)))) return (num/den) } train <- function(trainingSet, weights, targetLineSlope, targetLineCoeff){ targetVector <- numeric() for (i in 1:nrow(trainingSet)) { trainingPoint <- trainingSet [i,] targetValue <- fTargetFunction(trainingPoint,targetLineSlope, targetLineCoeff); targetVector <- c(targetVector, targetValue); } learningRate = 0.01 previousWeights = data.frame(-1,-1,-1) step = 0 displacement = 1 threshold = 0.01 while (displacement >= threshold) { sampleSet = sample(1:nrow(trainingSet)) for (i in 1:length(sampleSet)) { feature = trainingSet[i,] result = targetVector[i] descent = gradient(feature, result,weights) weights = weights - learningRate * descent } displacement = norm(as.matrix(previousWeights) - as.matrix(weights)) previousWeights = weights step = step + 1 #print( paste("Disp", displacement)) } print(paste("Wts", weights, "step", step)) return(weights) } avgCrossEntropy <- 0.0 trainingPoints <- 100 testingPoints <- 1000 maxIteration=10 iterationCount = 1 while (iterationCount <= maxIteration) { #Generate targetLine targetLine <- data.frame(runif(2,-1,1),runif(2,-1,1)) names(targetLine ) <- c('x','y') fit <- lm(targetLine$y~targetLine$x) targetLineSlope <- fit$coefficients[2] targetLineCoeff <- fit$coefficients[1] #Initialize weights to 0 weights <- data.frame(0,0,0) names(weights) <- c("w0","w1","w2") trainingSet <- data.frame(1,runif(trainingPoints, -1, 1),runif(trainingPoints, -1, 1)) names(trainingSet) <- c('c','x','y') weights <- train(trainingSet, weights, targetLineSlope, targetLineCoeff) testingSet <- data.frame(1,runif(testingPoints, -1, 1),runif(testingPoints, -1, 1)) names(testingSet) <- c('c','x','y') crossEntropy <- 0 for (i in 1:nrow(testingSet)) { testingPoint <- testingSet [i,] result <- fTargetFunction(testingPoint,targetLineSlope, targetLineCoeff); crossEntropyVal <- crossEntropyFn(testingPoint,result, weights); #print(crossEntropyVal); crossEntropy = crossEntropy + crossEntropyVal } print(paste("CrossEntropy Error Avg",crossEntropy/nrow(testingSet))) avgCrossEntropy <- avgCrossEntropy + (crossEntropy/nrow(testingSet)) iterationCount = iterationCount +1 } print(paste("CrossEntropy Error Avg Mult Iterations",avgCrossEntropy/maxIteration)) #q8. # 0.11 #q9 #353 #q1. c #q2 #q3. c #q4. e #q5. d #q6. e #q7. a #q8. d #q9. b x a #q10
# Script to update model hyperparameters and check convergence #source("check_conv.R") # First need script to update sigma2 and nu kappa.nu <- 5 lambda.nu <- 5/kappa.nu kappa.sigma2 <- 5 lambda.sigma2 <- 0.05/kappa.sigma2 inv.chisq.like <- function(par,tau2.vec){ nu <- par[1] sigma2 <- par[2] N.tau2 <- length(tau2.vec) no.data.term <- (nu/2)*log(nu/2) - lgamma(nu/2) + (nu/2)*log(sigma2) log.like <- N.tau2*no.data.term - (nu/2 + 1)*sum(log(tau2.vec)) - (nu*sigma2/2)*sum(1/tau2.vec) return(log.like) } nu.log.prior <- function(nu,kappa,lambda){ log.prior <- (kappa-1)*log(nu) - (nu/lambda) #log.prior <- -log(nu) return(log.prior) } sigma2.log.prior <- function(sigma2,kappa,lambda){ log.prior <- (kappa-1)*log(sigma2) - (sigma2/lambda) #log.prior <- -log(sigma2) return(log.prior) } inv.chisq.post <- function(par,tau2.vec,kappa.nu,lambda.nu, kappa.sigma2,lambda.sigma2){ # Optimize in log space par <- exp(par) log.post <- inv.chisq.like(par=par,tau2.vec=tau2.vec) + nu.log.prior(nu=par[1],kappa=kappa.nu,lambda=lambda.nu) + sigma2.log.prior(sigma2=par[2],kappa=kappa.sigma2,lambda=lambda.sigma2) return(log.post) } joint.inv.chisq.optim <- function(tau2.vec,kappa.nu,lambda.nu, kappa.sigma2,lambda.sigma2){ # Initialize parameters sigma2 <- sigma2.update(tau2.vec=tau2.vec) nu <- initialize.nu(tau2.vec=tau2.vec,sigma2=sigma2) # Optimize in log space par <- log(c(nu,sigma2)) # Get optimium of joint posterior par.out <- optim(par=par,fn=inv.chisq.post, tau2.vec=tau2.vec, kappa.nu=kappa.nu,lambda.nu=lambda.nu, kappa.sigma2=kappa.sigma2, lambda.sigma2=lambda.sigma2, control=list(fnscale=-1))$par # Go back to constrained space par.out <- exp(par.out) names(par.out) <- c("nu","sigma2") return(par.out) } ############################### nu.profile.log.post <- function(nu,sigma2,tau2.vec,kappa,lambda){ log.post <- inv.chisq.like(c(nu,sigma2),tau2.vec) + nu.log.prior(nu,kappa,lambda) return(log.post) } sigma2.profile.log.post <- function(nu,sigma2,tau2.vec,kappa,lambda){ log.post <- inv.chisq.like(c(nu,sigma2),tau2.vec) + sigma2.log.prior(sigma2,kappa,lambda) return(log.post) } nu.optimize <- function(tau2.vec,sigma2,kappa=NULL,lambda=NULL,prior=TRUE){ if(prior){ nu.new <- optimize(f=nu.profile.log.post,interval=c(0,1000),maximum=TRUE, tau2.vec=tau2.vec,sigma2=sigma2,kappa=kappa,lambda=lambda) } else { nu.new <- optimize(f=inv.chisq.like,interval=c(0,1000),maximum=TRUE, tau2.vec=tau2.vec,sigma2=sigma2)} return(nu.new) } sigma2.optimize <- function(tau2.vec,nu,kappa,lambda){ # Initialize parameter sigma2 <- sigma2.update(tau2.vec=tau2.vec) sigma2.new <- optimize(f=sigma2.profile.log.post,interval=c(0,1000),maximum=TRUE, tau2.vec=tau2.vec,nu=nu,kappa=kappa.sigma2,lambda=lambda.sigma2) return(sigma2.new) } # sigma2 update is analytic sigma2.update <- function(tau2.vec){ N.tau2 <- length(tau2.vec) sigma2.new <- N.tau2/sum(1/tau2.vec) return(sigma2.new) } # Get derivates of profile likelihood of nu nu.fd <- function(nu,tau2.vec,sigma2,kappa,lambda){ N.tau2 <- length(tau2.vec) fd <- N.tau2*log(nu/2) - N.tau2*digamma(nu/2) + N.tau2*log(sigma2) - sum(log(tau2.vec)) + (kappa-1)/nu - 1/lambda return(fd) } nu.sd <- function(nu,tau2.vec,sigma2,kappa,lambda){ N.tau2 <- length(tau2.vec) sd <- N.tau2/nu - (N.tau2/2)*trigamma(nu/2) - (kappa-1)/nu^2 return(sd) } # One Newton-Raphson update for nu nu.update <- function(nu,tau2.vec,sigma2,kappa,lambda,log.param=TRUE){ fd <- nu.fd(nu=nu,tau2.vec=tau2.vec,sigma2=sigma2, kappa=kappa,lambda=lambda) sd <- nu.sd(nu=nu,tau2.vec=tau2.vec,sigma2=sigma2, kappa=kappa,lambda=lambda) if(log.param){ # Transform nu to log-nu log.nu <- log(nu) # Need chain rule fd.log <- fd*nu sd.log <- nu*(nu*sd + fd) nu.log.new <- log.nu - (fd.log/sd.log) nu.new <- exp(nu.log.new) } else {nu.new <- nu - (fd/sd)} return(nu.new) } # Function to initialize nu with moment estimator initialize.nu <- function(tau2.vec,sigma2){ mean.tau2 <- mean(tau2.vec) nu.start <- 2*mean.tau2/(mean.tau2-sigma2) # Make sure have reasonable first guess #default.value <- sqrt(.Machine$double.eps) default.value <- 1 nu.start <- max(nu.start,default.value) return(nu.start) } # Newton-Raphson function for nu nu.newton.raphson <- function(tau2.vec,sigma2,kappa,lambda, reltol=1e-8,iter.max=100, verbose=FALSE){ nu <- initialize.nu(tau2.vec,sigma2) nu.vec <- nu for(i in 1:iter.max){ print(nu) nu.old <- nu nu <- nu.update(nu=nu,tau2.vec=tau2.vec,sigma2=sigma2, kappa=kappa,lambda=lambda) nu.vec <- c(nu.vec,nu) conv <- check.conv(old.param.vec=nu.old,new.param.vec=nu, reltol=reltol) if(conv){break} } if(verbose){ if(i < iter.max){print(paste("Newton-Raphson for nu converged in",i,"iterations")) } else {print(paste("Newton-Raphson for nu failed to converge in", iter.max,"iterations"))} ts.plot(nu.vec) } #print(nu.vec) return(nu) } # Overall function to update hyperparamters update.hparam <- function(current.param.list,reltol=1e-6, kappa.nu,lambda.nu,kappa.sigma2, lambda.sigma2){ # Grab relevant parameters out of list mu.corpus.vec <- current.param.list$mu.corpus.vec tau2.vec <- as.vector(current.param.list$tau2.param.vecs) print(summary(tau2.vec)) psi.old <- current.param.list$psi gamma.old <- current.param.list$gamma sigma2.old <- current.param.list$sigma2 nu.old <- current.param.list$nu # Update hparams #psi.new <- mean(mu.corpus.vec) #gamma.new <- sd(mu.corpus.vec) psi.new <- log(0.05) gamma.new <- 0.1 n.tau2 <- length(tau2.vec) nu.new <- mean(log(tau2.vec)) ## nu.new <- -1 sigma2.new <- var(log(tau2.vec))*((n.tau2-1)/n.tau2) ## sigma2.new <- 2 ## sigma2.new <- 1 ## nu.new <- nu.old ## sigma2.new <- sigma2.optimize(tau2.vec=tau2.vec,nu=nu.new,kappa=kappa.sigma2, ## lambda=lambda.sigma2)$maximum ## par.inv.chisq.new <- joint.inv.chisq.optim(tau2.vec=tau2.vec, ## kappa.nu=kappa.nu, ## lambda.nu=lambda.nu, ## kappa.sigma2=kappa.sigma2, ## lambda.sigma2=lambda.sigma2) ## nu.new <- par.inv.chisq.new["nu"] ## sigma2.new <- par.inv.chisq.new["sigma2"] ## sigma2.new <- sigma2.update(tau2.vec=tau2.vec) ## print(sigma2.new) ## sigma2.new <- 0.05 ## nu.new <- nu.optimize(tau2.vec=tau2.vec,sigma2=sigma2.new, ## kappa=kappa,lambda=lambda)$maximum ## nu.new <- 500 ## print(nu.new) ## nu.new <- nu.newton.raphson(tau2.vec=tau2.vec,sigma2=sigma2.new, ## kappa=kappa,lambda=lambda) # Put new hparams in current.param.list current.param.list$psi <- psi.new current.param.list$gamma <- gamma.new current.param.list$sigma2 <- sigma2.new current.param.list$nu <- nu.new # Check global convergence of hyperparameters global.conv <- check.conv(old.param.vec=c(psi.old,gamma.old,sigma2.old,nu.old), new.param.vec=c(psi.new,gamma.new,sigma2.new,nu.new), reltol=1e-6) hparam.outlist <- list(current.param.list=current.param.list, global.conv=global.conv) return(hparam.outlist) }
/mmm_fit_code/mmm_fit_functions/hparam_update_OLD.R
no_license
jbischof/HPC_model
R
false
false
7,857
r
# Script to update model hyperparameters and check convergence #source("check_conv.R") # First need script to update sigma2 and nu kappa.nu <- 5 lambda.nu <- 5/kappa.nu kappa.sigma2 <- 5 lambda.sigma2 <- 0.05/kappa.sigma2 inv.chisq.like <- function(par,tau2.vec){ nu <- par[1] sigma2 <- par[2] N.tau2 <- length(tau2.vec) no.data.term <- (nu/2)*log(nu/2) - lgamma(nu/2) + (nu/2)*log(sigma2) log.like <- N.tau2*no.data.term - (nu/2 + 1)*sum(log(tau2.vec)) - (nu*sigma2/2)*sum(1/tau2.vec) return(log.like) } nu.log.prior <- function(nu,kappa,lambda){ log.prior <- (kappa-1)*log(nu) - (nu/lambda) #log.prior <- -log(nu) return(log.prior) } sigma2.log.prior <- function(sigma2,kappa,lambda){ log.prior <- (kappa-1)*log(sigma2) - (sigma2/lambda) #log.prior <- -log(sigma2) return(log.prior) } inv.chisq.post <- function(par,tau2.vec,kappa.nu,lambda.nu, kappa.sigma2,lambda.sigma2){ # Optimize in log space par <- exp(par) log.post <- inv.chisq.like(par=par,tau2.vec=tau2.vec) + nu.log.prior(nu=par[1],kappa=kappa.nu,lambda=lambda.nu) + sigma2.log.prior(sigma2=par[2],kappa=kappa.sigma2,lambda=lambda.sigma2) return(log.post) } joint.inv.chisq.optim <- function(tau2.vec,kappa.nu,lambda.nu, kappa.sigma2,lambda.sigma2){ # Initialize parameters sigma2 <- sigma2.update(tau2.vec=tau2.vec) nu <- initialize.nu(tau2.vec=tau2.vec,sigma2=sigma2) # Optimize in log space par <- log(c(nu,sigma2)) # Get optimium of joint posterior par.out <- optim(par=par,fn=inv.chisq.post, tau2.vec=tau2.vec, kappa.nu=kappa.nu,lambda.nu=lambda.nu, kappa.sigma2=kappa.sigma2, lambda.sigma2=lambda.sigma2, control=list(fnscale=-1))$par # Go back to constrained space par.out <- exp(par.out) names(par.out) <- c("nu","sigma2") return(par.out) } ############################### nu.profile.log.post <- function(nu,sigma2,tau2.vec,kappa,lambda){ log.post <- inv.chisq.like(c(nu,sigma2),tau2.vec) + nu.log.prior(nu,kappa,lambda) return(log.post) } sigma2.profile.log.post <- function(nu,sigma2,tau2.vec,kappa,lambda){ log.post <- inv.chisq.like(c(nu,sigma2),tau2.vec) + sigma2.log.prior(sigma2,kappa,lambda) return(log.post) } nu.optimize <- function(tau2.vec,sigma2,kappa=NULL,lambda=NULL,prior=TRUE){ if(prior){ nu.new <- optimize(f=nu.profile.log.post,interval=c(0,1000),maximum=TRUE, tau2.vec=tau2.vec,sigma2=sigma2,kappa=kappa,lambda=lambda) } else { nu.new <- optimize(f=inv.chisq.like,interval=c(0,1000),maximum=TRUE, tau2.vec=tau2.vec,sigma2=sigma2)} return(nu.new) } sigma2.optimize <- function(tau2.vec,nu,kappa,lambda){ # Initialize parameter sigma2 <- sigma2.update(tau2.vec=tau2.vec) sigma2.new <- optimize(f=sigma2.profile.log.post,interval=c(0,1000),maximum=TRUE, tau2.vec=tau2.vec,nu=nu,kappa=kappa.sigma2,lambda=lambda.sigma2) return(sigma2.new) } # sigma2 update is analytic sigma2.update <- function(tau2.vec){ N.tau2 <- length(tau2.vec) sigma2.new <- N.tau2/sum(1/tau2.vec) return(sigma2.new) } # Get derivates of profile likelihood of nu nu.fd <- function(nu,tau2.vec,sigma2,kappa,lambda){ N.tau2 <- length(tau2.vec) fd <- N.tau2*log(nu/2) - N.tau2*digamma(nu/2) + N.tau2*log(sigma2) - sum(log(tau2.vec)) + (kappa-1)/nu - 1/lambda return(fd) } nu.sd <- function(nu,tau2.vec,sigma2,kappa,lambda){ N.tau2 <- length(tau2.vec) sd <- N.tau2/nu - (N.tau2/2)*trigamma(nu/2) - (kappa-1)/nu^2 return(sd) } # One Newton-Raphson update for nu nu.update <- function(nu,tau2.vec,sigma2,kappa,lambda,log.param=TRUE){ fd <- nu.fd(nu=nu,tau2.vec=tau2.vec,sigma2=sigma2, kappa=kappa,lambda=lambda) sd <- nu.sd(nu=nu,tau2.vec=tau2.vec,sigma2=sigma2, kappa=kappa,lambda=lambda) if(log.param){ # Transform nu to log-nu log.nu <- log(nu) # Need chain rule fd.log <- fd*nu sd.log <- nu*(nu*sd + fd) nu.log.new <- log.nu - (fd.log/sd.log) nu.new <- exp(nu.log.new) } else {nu.new <- nu - (fd/sd)} return(nu.new) } # Function to initialize nu with moment estimator initialize.nu <- function(tau2.vec,sigma2){ mean.tau2 <- mean(tau2.vec) nu.start <- 2*mean.tau2/(mean.tau2-sigma2) # Make sure have reasonable first guess #default.value <- sqrt(.Machine$double.eps) default.value <- 1 nu.start <- max(nu.start,default.value) return(nu.start) } # Newton-Raphson function for nu nu.newton.raphson <- function(tau2.vec,sigma2,kappa,lambda, reltol=1e-8,iter.max=100, verbose=FALSE){ nu <- initialize.nu(tau2.vec,sigma2) nu.vec <- nu for(i in 1:iter.max){ print(nu) nu.old <- nu nu <- nu.update(nu=nu,tau2.vec=tau2.vec,sigma2=sigma2, kappa=kappa,lambda=lambda) nu.vec <- c(nu.vec,nu) conv <- check.conv(old.param.vec=nu.old,new.param.vec=nu, reltol=reltol) if(conv){break} } if(verbose){ if(i < iter.max){print(paste("Newton-Raphson for nu converged in",i,"iterations")) } else {print(paste("Newton-Raphson for nu failed to converge in", iter.max,"iterations"))} ts.plot(nu.vec) } #print(nu.vec) return(nu) } # Overall function to update hyperparamters update.hparam <- function(current.param.list,reltol=1e-6, kappa.nu,lambda.nu,kappa.sigma2, lambda.sigma2){ # Grab relevant parameters out of list mu.corpus.vec <- current.param.list$mu.corpus.vec tau2.vec <- as.vector(current.param.list$tau2.param.vecs) print(summary(tau2.vec)) psi.old <- current.param.list$psi gamma.old <- current.param.list$gamma sigma2.old <- current.param.list$sigma2 nu.old <- current.param.list$nu # Update hparams #psi.new <- mean(mu.corpus.vec) #gamma.new <- sd(mu.corpus.vec) psi.new <- log(0.05) gamma.new <- 0.1 n.tau2 <- length(tau2.vec) nu.new <- mean(log(tau2.vec)) ## nu.new <- -1 sigma2.new <- var(log(tau2.vec))*((n.tau2-1)/n.tau2) ## sigma2.new <- 2 ## sigma2.new <- 1 ## nu.new <- nu.old ## sigma2.new <- sigma2.optimize(tau2.vec=tau2.vec,nu=nu.new,kappa=kappa.sigma2, ## lambda=lambda.sigma2)$maximum ## par.inv.chisq.new <- joint.inv.chisq.optim(tau2.vec=tau2.vec, ## kappa.nu=kappa.nu, ## lambda.nu=lambda.nu, ## kappa.sigma2=kappa.sigma2, ## lambda.sigma2=lambda.sigma2) ## nu.new <- par.inv.chisq.new["nu"] ## sigma2.new <- par.inv.chisq.new["sigma2"] ## sigma2.new <- sigma2.update(tau2.vec=tau2.vec) ## print(sigma2.new) ## sigma2.new <- 0.05 ## nu.new <- nu.optimize(tau2.vec=tau2.vec,sigma2=sigma2.new, ## kappa=kappa,lambda=lambda)$maximum ## nu.new <- 500 ## print(nu.new) ## nu.new <- nu.newton.raphson(tau2.vec=tau2.vec,sigma2=sigma2.new, ## kappa=kappa,lambda=lambda) # Put new hparams in current.param.list current.param.list$psi <- psi.new current.param.list$gamma <- gamma.new current.param.list$sigma2 <- sigma2.new current.param.list$nu <- nu.new # Check global convergence of hyperparameters global.conv <- check.conv(old.param.vec=c(psi.old,gamma.old,sigma2.old,nu.old), new.param.vec=c(psi.new,gamma.new,sigma2.new,nu.new), reltol=1e-6) hparam.outlist <- list(current.param.list=current.param.list, global.conv=global.conv) return(hparam.outlist) }
infoprobs <- function (betas, z) { cpr <- cprobs(betas, z) ipr <- iprobs(betas, z) sum.cprs <- lapply(cpr, function (x) { nr <- nrow(x) t((1 - rbind(x[1, ], x[-nr, ] + x[-1, ]))^2) }) betas. <- sapply(betas, function (x) x[length(x)]) for (i in 1:length(betas)) sum.cprs[[i]] <- betas.[i]^2 * ipr[[i]] * sum.cprs[[i]] do.call(cbind, lapply(sum.cprs, rowSums)) }
/R/infoprobs.R
no_license
cran/ltm
R
false
false
427
r
infoprobs <- function (betas, z) { cpr <- cprobs(betas, z) ipr <- iprobs(betas, z) sum.cprs <- lapply(cpr, function (x) { nr <- nrow(x) t((1 - rbind(x[1, ], x[-nr, ] + x[-1, ]))^2) }) betas. <- sapply(betas, function (x) x[length(x)]) for (i in 1:length(betas)) sum.cprs[[i]] <- betas.[i]^2 * ipr[[i]] * sum.cprs[[i]] do.call(cbind, lapply(sum.cprs, rowSums)) }
library("deSolve") growth = function(t, y, params) { with(as.list(c(params,y)), { ## function values zigma = P+FF+K+V f = (zigma/80)*(637.27 - 0.305*density)/12/7 # [density] = 1/(dm^2), (zigma/80) er et gæt for hver meget mere større larver spiser g = 0.125 * P # "gæt", sørger for maks 46% proteinindhold kCombustC = 0.08473955701/0.5 h = kCombustC/2*K #kCombust = -0.3485+0.033054*temp #For temp 10-30 grader. Ellers død? kCombust = kCombustC/2*K fCombust = 0.05298229217*FF radius = (zigma/(10*pi))^(1/3) # approx radius (as if cylinder of water 5x as long as the diameter) j = (0.22 * pi * radius^2) * # surface area 1440 * # minutes/day 0.89750342 * (V/zigma - H) * # humidity difference, diffusion boundary assumed linear, replaces (1-H) in eq (temp + 273.15)^(-1.4) * sqrt(vAir) * Pwater(temp) lumenSize = 0.15*zigma ppl = Pl/lumenSize fpl = Fl/lumenSize kpl = Kl/lumenSize pa = Dp * Pl/lumenSize fa = Df * Fl/lumenSize ka = Dk * Kl/lumenSize # / lumenSize [mg] ## derivatives dPx = ppl*f dFx = fpl*f dKx = kpl*f dP = pa-g dUx = 0.5*g dF = fa + h - fCombust dK = ka - h - kCombust #dV = 0.5*g + kCombust + fCombust - j dV = 0.5*g + (0.02108 * zigma) - j # (kCombust + fCombust) = 0.021808 uden skelnen, desværre dVx = j dPl = pp*f - ppl*f - pa dFl = fp*f - fpl*f - fa dKl = kp*f - kpl*f - ka #print(j) return(list(c(dPx, dFx, dKx, dUx, dVx, dP, dF, dK, dV, dPl, dFl, dKl, f, pa+fa+ka), c(f = f, pa = pa, fa = fa, ka = ka, zigma = zigma, kCombust = kCombust, fCombust = fCombust, j = j, pp = 100*P/zigma, kp = 100*K/zigma, fp = 100*FF/zigma, vp = 100*V/zigma, ppt = 100*P/(P+K+FF), kpt = 100*K/(P+K+FF), fpt = 100*FF/(P+K+FF), urp = Ux/(Px+Fx+Kx+Ux), growthrate=dK+dF+dK))) }) } Pwater = function(temp) { # Antoine ligningen 10^( 2.124903 # for at omregne til Pascal + 8.07131 # A - ( 1730.63/ # B (233.426 # C + temp) # [temp] = °C ) ) } params = c( temp = 28, density = 50, H = 0.65, pressure = 101325, # Pa vAir = 0.15, # m/s Dp = 100, # gæt Df = 100, # gæt Dk = 100, # (0.015umol/min)/(3 mol/L) * 1 kg/L omregnet til mg/d pp = 0.33, fp = 0.06, kp = 0.61 ) initials = c( Px = 0, Fx = 0, Kx = 0, Ux = 0, Vx = 0, P = 2, FF = 3, K = 5, V = 5, Pl = 0.2, Fl = 0.3, Kl = 0.5, FoodConsumed = 0, FoodDigested = 0 ) sols = ode(initials,c(1:84),growth,params) plot(sols) print(sols[84,]) # Scatterplot mi <- as.vector(c(0,10,0,101325/2,0.001,1,1,1,0,0,0),"numeric") ma <- as.vector(c(100,100,1,101325*2,10,100,100,100,1,1,1),"numeric") attribute.names = c('temp','density','H','pressure','vAir','Dp','Df','Dk','pp','fp','kp') N.iter <- 500 P.end <- vector("numeric",length = N.iter) FF.end <- vector("numeric",N.iter) K.end <- vector("numeric",N.iter) param.list = matrix(data = NA,nrow = length(params),ncol = N.iter) #parms = matrix(data = NA,nrow = length(params),ncol = N.iter) parms = vector("numeric", length = length(params)) GSA.res = matrix(data = NA,nrow = length(params),ncol = N.iter) #output = matrix(data = NA,nrow = length(params),ncol = N.iter) #j = 1 #loop param set.seed(3) for (j in 1:length(params)){ param.list[j,] = runif(N.iter,min=mi[j],max=ma[j]) } for ( i in 1:N.iter){ # simulate the epidemic parms = param.list[,i] names(parms)<-attribute.names output <- ode(initials,times = c(1:84), growth, parms) # antal syge på samme tid P.end[i] <- output[84,'ppt'] # t.max FF.end[i] <- output[84,'fpt'] # totale antal syge K.end[i] <- output[84,'kpt'] } GSA.res <- data.frame(id=1:N.iter,P.end,FF.end,K.end) names(GSA.res) <- c("id","P end","F end", "K end") pairs(GSA.res) # Andre metoder følger... library(ggplot2) library(reshape2) #head(GSA.res) #GSA.res[1] <- as.factor(P.max) nyGSA = melt(GSA.res,id.vars=c("id")) nyGSA$variable <- as.factor(nyGSA$variable) ggplot(nyGSA, aes(x=variable,y=value)) + geom_violin(trim=T, fill='pink', color="darkred")+ geom_boxplot(width=0.1) + theme_minimal() + ggtitle("Violinplot")+xlab("Slut næringsindhold")+ylab("Værdier")
/globalsensitivitet.R
no_license
Dynamisk-Modellering-AEMMS/melorme-fagprojekt
R
false
false
4,249
r
library("deSolve") growth = function(t, y, params) { with(as.list(c(params,y)), { ## function values zigma = P+FF+K+V f = (zigma/80)*(637.27 - 0.305*density)/12/7 # [density] = 1/(dm^2), (zigma/80) er et gæt for hver meget mere større larver spiser g = 0.125 * P # "gæt", sørger for maks 46% proteinindhold kCombustC = 0.08473955701/0.5 h = kCombustC/2*K #kCombust = -0.3485+0.033054*temp #For temp 10-30 grader. Ellers død? kCombust = kCombustC/2*K fCombust = 0.05298229217*FF radius = (zigma/(10*pi))^(1/3) # approx radius (as if cylinder of water 5x as long as the diameter) j = (0.22 * pi * radius^2) * # surface area 1440 * # minutes/day 0.89750342 * (V/zigma - H) * # humidity difference, diffusion boundary assumed linear, replaces (1-H) in eq (temp + 273.15)^(-1.4) * sqrt(vAir) * Pwater(temp) lumenSize = 0.15*zigma ppl = Pl/lumenSize fpl = Fl/lumenSize kpl = Kl/lumenSize pa = Dp * Pl/lumenSize fa = Df * Fl/lumenSize ka = Dk * Kl/lumenSize # / lumenSize [mg] ## derivatives dPx = ppl*f dFx = fpl*f dKx = kpl*f dP = pa-g dUx = 0.5*g dF = fa + h - fCombust dK = ka - h - kCombust #dV = 0.5*g + kCombust + fCombust - j dV = 0.5*g + (0.02108 * zigma) - j # (kCombust + fCombust) = 0.021808 uden skelnen, desværre dVx = j dPl = pp*f - ppl*f - pa dFl = fp*f - fpl*f - fa dKl = kp*f - kpl*f - ka #print(j) return(list(c(dPx, dFx, dKx, dUx, dVx, dP, dF, dK, dV, dPl, dFl, dKl, f, pa+fa+ka), c(f = f, pa = pa, fa = fa, ka = ka, zigma = zigma, kCombust = kCombust, fCombust = fCombust, j = j, pp = 100*P/zigma, kp = 100*K/zigma, fp = 100*FF/zigma, vp = 100*V/zigma, ppt = 100*P/(P+K+FF), kpt = 100*K/(P+K+FF), fpt = 100*FF/(P+K+FF), urp = Ux/(Px+Fx+Kx+Ux), growthrate=dK+dF+dK))) }) } Pwater = function(temp) { # Antoine ligningen 10^( 2.124903 # for at omregne til Pascal + 8.07131 # A - ( 1730.63/ # B (233.426 # C + temp) # [temp] = °C ) ) } params = c( temp = 28, density = 50, H = 0.65, pressure = 101325, # Pa vAir = 0.15, # m/s Dp = 100, # gæt Df = 100, # gæt Dk = 100, # (0.015umol/min)/(3 mol/L) * 1 kg/L omregnet til mg/d pp = 0.33, fp = 0.06, kp = 0.61 ) initials = c( Px = 0, Fx = 0, Kx = 0, Ux = 0, Vx = 0, P = 2, FF = 3, K = 5, V = 5, Pl = 0.2, Fl = 0.3, Kl = 0.5, FoodConsumed = 0, FoodDigested = 0 ) sols = ode(initials,c(1:84),growth,params) plot(sols) print(sols[84,]) # Scatterplot mi <- as.vector(c(0,10,0,101325/2,0.001,1,1,1,0,0,0),"numeric") ma <- as.vector(c(100,100,1,101325*2,10,100,100,100,1,1,1),"numeric") attribute.names = c('temp','density','H','pressure','vAir','Dp','Df','Dk','pp','fp','kp') N.iter <- 500 P.end <- vector("numeric",length = N.iter) FF.end <- vector("numeric",N.iter) K.end <- vector("numeric",N.iter) param.list = matrix(data = NA,nrow = length(params),ncol = N.iter) #parms = matrix(data = NA,nrow = length(params),ncol = N.iter) parms = vector("numeric", length = length(params)) GSA.res = matrix(data = NA,nrow = length(params),ncol = N.iter) #output = matrix(data = NA,nrow = length(params),ncol = N.iter) #j = 1 #loop param set.seed(3) for (j in 1:length(params)){ param.list[j,] = runif(N.iter,min=mi[j],max=ma[j]) } for ( i in 1:N.iter){ # simulate the epidemic parms = param.list[,i] names(parms)<-attribute.names output <- ode(initials,times = c(1:84), growth, parms) # antal syge på samme tid P.end[i] <- output[84,'ppt'] # t.max FF.end[i] <- output[84,'fpt'] # totale antal syge K.end[i] <- output[84,'kpt'] } GSA.res <- data.frame(id=1:N.iter,P.end,FF.end,K.end) names(GSA.res) <- c("id","P end","F end", "K end") pairs(GSA.res) # Andre metoder følger... library(ggplot2) library(reshape2) #head(GSA.res) #GSA.res[1] <- as.factor(P.max) nyGSA = melt(GSA.res,id.vars=c("id")) nyGSA$variable <- as.factor(nyGSA$variable) ggplot(nyGSA, aes(x=variable,y=value)) + geom_violin(trim=T, fill='pink', color="darkred")+ geom_boxplot(width=0.1) + theme_minimal() + ggtitle("Violinplot")+xlab("Slut næringsindhold")+ylab("Værdier")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ani-compression-profile.R \docType{class} \name{anisotropyprofile_summary-class} \alias{anisotropyprofile_summary-class} \title{Summary of Anisotropy profile} \description{ Information about the anisotropy-profile. }
/man/anisotropyprofile_summary-class.Rd
no_license
antiphon/Kdirectional
R
false
true
295
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ani-compression-profile.R \docType{class} \name{anisotropyprofile_summary-class} \alias{anisotropyprofile_summary-class} \title{Summary of Anisotropy profile} \description{ Information about the anisotropy-profile. }
\name{see.citations} \alias{see.citations} \title{see.citations} \description{ Extract author information from a saved search. } \usage{ see.citations(search = NULL, results = NULL, index = 'article.titles', ...) } \arguments{ \item{search}{a string or regular expression which identifies paper(s) to open in search results} \item{results}{saved search results from a search.pubmed( ) call} \item{index}{results column to search in saved search results} \item{...}{optional arguments passed to rcrossref::cr_cn} } \value{ tibble } \examples{ ## save search #saved.search <- search.pubmed(term = 'baby') ##see citations from article with 'Postnatal' title #see.citations('Postnatal', results = saved.search) ## see citations from article with "Children's" in abstract #see.citations("Children's", results = saved.search, index = 'article.abstracts') ## see citations from article with "Children's" in abstract in text format #see.citations("Children's", results = saved.search, index = 'article.abstracts', format = 'text') }
/man/see.citations.Rd
no_license
ShawnBrad/SearchPubmed
R
false
false
1,029
rd
\name{see.citations} \alias{see.citations} \title{see.citations} \description{ Extract author information from a saved search. } \usage{ see.citations(search = NULL, results = NULL, index = 'article.titles', ...) } \arguments{ \item{search}{a string or regular expression which identifies paper(s) to open in search results} \item{results}{saved search results from a search.pubmed( ) call} \item{index}{results column to search in saved search results} \item{...}{optional arguments passed to rcrossref::cr_cn} } \value{ tibble } \examples{ ## save search #saved.search <- search.pubmed(term = 'baby') ##see citations from article with 'Postnatal' title #see.citations('Postnatal', results = saved.search) ## see citations from article with "Children's" in abstract #see.citations("Children's", results = saved.search, index = 'article.abstracts') ## see citations from article with "Children's" in abstract in text format #see.citations("Children's", results = saved.search, index = 'article.abstracts', format = 'text') }
setwd("C:/Users/dusti/Box Sync/Personal Computer/Quantitative Biodiversity/Group Project/GroupProject") rm(list=ls()) library(vegan) library(psych) library(ggplot2) library(forcats) library(dplyr) library(corrplot) # SPECIES RICHNESS CODE, WITHOUT FORAGING GUILDS data.without.guilds <- read.csv("hf085-01-bird.csv", header = TRUE) data.num <- data.without.guilds[ ,3:51] S.obs <- function(x = ""){ rowSums(x > 0) * 1 } obs.rich <- S.obs(data.num) obs.rich S.chao2 <- function(site = "", SbyS = ""){ SbyS = as.data.frame(SbyS) x = SbyS[site, ] SbyS.pa <- (SbyS > 0) * 1 Q1 = sum(colSums(SbyS.pa) == 1) Q2 = sum(colSums(SbyS.pa) == 2) S.chao2 = S.obs(x) + (Q1^2)/(2*Q2) return(S.chao2) } S.chao2 est.rich <- S.chao2(1:40, data.num) est.rich # FORAGING GUILDS CODE, MEAN ABUNDANCE Guilds <- read.csv("ForagingGuildsDataFile.csv") str(Guilds) summary(Guilds) sem <- function(x){ sd(na.omit(x))/sqrt(length(na.omit(x))) } #Compute means for omnivores and insectivores in the different mortality classes Omnivores.Mean <- tapply(Guilds$Omn_16, Guilds$mortality.class, mean) Omnivores.Mean Insectivores.Mean <- tapply(Guilds$Ins_29, Guilds$mortality.class, mean) Insectivores.Mean #Compute standard errors for those means Omnivores.SE <- tapply(Guilds$Omn_16, Guilds$mortality.class, sem) Omnivores.SE Insectivores.SE <- tapply(Guilds$Ins_29, Guilds$mortality.class, sem) Insectivores.SE #Omnivore bar plot OmnivorePlot <- barplot(Omnivores.Mean, ylim = c(0, round(1.5*max(Omnivores.Mean), digits = 0)), pch = 15, cex = 1.25, las = 1, cex.lab = 1.4, cex.axis = 1.25, xlab = "mortality class", ylab = "mean site abundance", names.arg = c("low", "medium", "high A", "high B")) arrows(x0 = OmnivorePlot, y0 = Omnivores.Mean, y1 = Omnivores.Mean - Omnivores.SE, angle = 90, length = 0.1, lwd = 1) arrows(x0 = OmnivorePlot, y0 = Omnivores.Mean , y1 = Omnivores.Mean + Omnivores.SE, angle = 90, length = 0.1, lwd = 1) #Insectivore bar plot InsectivorePlot <- barplot(Insectivores.Mean, ylim = c(0, round(1.5*max(Insectivores.Mean), digits = 0)), pch = 15, cex = 1.25, las = 1, cex.lab = 1.4, cex.axis = 1.25, xlab = "mortality class", ylab = "mean site abundance", names.arg = c("low", "medium", "high A", "high B")) arrows(x0 = InsectivorePlot, y0 = Insectivores.Mean, y1 = Insectivores.Mean - Insectivores.SE, angle = 90, length = 0.1, lwd = 1) arrows(x0 = InsectivorePlot, y0 = Insectivores.Mean , y1 = Insectivores.Mean + Insectivores.SE, angle = 90, length = 0.1, lwd = 1) #Get omnivore and insectivore bars on same plot #Load excel file with means and S.E.s for both guilds at each mortality class ClusteredBar <- read.csv("GuildsClusteredBar.csv", header = TRUE) ClusteredBar str(ClusteredBar) #Reorder x axis ClusteredBar$Mortality <- fct_relevel(ClusteredBar$Mortality, "Low", "Medium", "High-B", "High-A") ggplot(ClusteredBar, aes(x=Mortality, y = Mean, fill = Guild)) + geom_bar(position=position_dodge(), stat ="identity", colour = 'black') + geom_errorbar(aes(ymin=Mean-S.E., ymax=Mean+S.E.), width = .2, position = position_dodge(.9)) + ggtitle("Bird Abundance") #Run Omnivore Anova OmnivoreAnova <- aov(Guilds$Omn_16~Guilds$mortality.class, data = Guilds) OmnivoreAnova summary(OmnivoreAnova) TukeyHSD(OmnivoreAnova) #Run Insectivore ANOVA InsectivoreAnova <- aov(Guilds$Ins_29~Guilds$mortality.class, data = Guilds) summary(InsectivoreAnova) TukeyHSD(InsectivoreAnova)
/GuildsData.R
no_license
dubrewer92/GroupProject
R
false
false
3,634
r
setwd("C:/Users/dusti/Box Sync/Personal Computer/Quantitative Biodiversity/Group Project/GroupProject") rm(list=ls()) library(vegan) library(psych) library(ggplot2) library(forcats) library(dplyr) library(corrplot) # SPECIES RICHNESS CODE, WITHOUT FORAGING GUILDS data.without.guilds <- read.csv("hf085-01-bird.csv", header = TRUE) data.num <- data.without.guilds[ ,3:51] S.obs <- function(x = ""){ rowSums(x > 0) * 1 } obs.rich <- S.obs(data.num) obs.rich S.chao2 <- function(site = "", SbyS = ""){ SbyS = as.data.frame(SbyS) x = SbyS[site, ] SbyS.pa <- (SbyS > 0) * 1 Q1 = sum(colSums(SbyS.pa) == 1) Q2 = sum(colSums(SbyS.pa) == 2) S.chao2 = S.obs(x) + (Q1^2)/(2*Q2) return(S.chao2) } S.chao2 est.rich <- S.chao2(1:40, data.num) est.rich # FORAGING GUILDS CODE, MEAN ABUNDANCE Guilds <- read.csv("ForagingGuildsDataFile.csv") str(Guilds) summary(Guilds) sem <- function(x){ sd(na.omit(x))/sqrt(length(na.omit(x))) } #Compute means for omnivores and insectivores in the different mortality classes Omnivores.Mean <- tapply(Guilds$Omn_16, Guilds$mortality.class, mean) Omnivores.Mean Insectivores.Mean <- tapply(Guilds$Ins_29, Guilds$mortality.class, mean) Insectivores.Mean #Compute standard errors for those means Omnivores.SE <- tapply(Guilds$Omn_16, Guilds$mortality.class, sem) Omnivores.SE Insectivores.SE <- tapply(Guilds$Ins_29, Guilds$mortality.class, sem) Insectivores.SE #Omnivore bar plot OmnivorePlot <- barplot(Omnivores.Mean, ylim = c(0, round(1.5*max(Omnivores.Mean), digits = 0)), pch = 15, cex = 1.25, las = 1, cex.lab = 1.4, cex.axis = 1.25, xlab = "mortality class", ylab = "mean site abundance", names.arg = c("low", "medium", "high A", "high B")) arrows(x0 = OmnivorePlot, y0 = Omnivores.Mean, y1 = Omnivores.Mean - Omnivores.SE, angle = 90, length = 0.1, lwd = 1) arrows(x0 = OmnivorePlot, y0 = Omnivores.Mean , y1 = Omnivores.Mean + Omnivores.SE, angle = 90, length = 0.1, lwd = 1) #Insectivore bar plot InsectivorePlot <- barplot(Insectivores.Mean, ylim = c(0, round(1.5*max(Insectivores.Mean), digits = 0)), pch = 15, cex = 1.25, las = 1, cex.lab = 1.4, cex.axis = 1.25, xlab = "mortality class", ylab = "mean site abundance", names.arg = c("low", "medium", "high A", "high B")) arrows(x0 = InsectivorePlot, y0 = Insectivores.Mean, y1 = Insectivores.Mean - Insectivores.SE, angle = 90, length = 0.1, lwd = 1) arrows(x0 = InsectivorePlot, y0 = Insectivores.Mean , y1 = Insectivores.Mean + Insectivores.SE, angle = 90, length = 0.1, lwd = 1) #Get omnivore and insectivore bars on same plot #Load excel file with means and S.E.s for both guilds at each mortality class ClusteredBar <- read.csv("GuildsClusteredBar.csv", header = TRUE) ClusteredBar str(ClusteredBar) #Reorder x axis ClusteredBar$Mortality <- fct_relevel(ClusteredBar$Mortality, "Low", "Medium", "High-B", "High-A") ggplot(ClusteredBar, aes(x=Mortality, y = Mean, fill = Guild)) + geom_bar(position=position_dodge(), stat ="identity", colour = 'black') + geom_errorbar(aes(ymin=Mean-S.E., ymax=Mean+S.E.), width = .2, position = position_dodge(.9)) + ggtitle("Bird Abundance") #Run Omnivore Anova OmnivoreAnova <- aov(Guilds$Omn_16~Guilds$mortality.class, data = Guilds) OmnivoreAnova summary(OmnivoreAnova) TukeyHSD(OmnivoreAnova) #Run Insectivore ANOVA InsectivoreAnova <- aov(Guilds$Ins_29~Guilds$mortality.class, data = Guilds) summary(InsectivoreAnova) TukeyHSD(InsectivoreAnova)
#' Inverse logit #' #' Return inverse logit of values. `-Inf` or `Inf` return logits of 0 or 1, respectively. #' #' @md #' @param x Values on logit scale #' #' @export #' inv_logit = function (x) { p = 1/(1 + exp(-x)) p[is.infinite(p)] = 1 p }
/R/inv_logit.R
no_license
hinkelman/YoloBypassSBM
R
false
false
264
r
#' Inverse logit #' #' Return inverse logit of values. `-Inf` or `Inf` return logits of 0 or 1, respectively. #' #' @md #' @param x Values on logit scale #' #' @export #' inv_logit = function (x) { p = 1/(1 + exp(-x)) p[is.infinite(p)] = 1 p }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mwu.R \name{mwu} \alias{mwu} \title{Mann-Whitney-U-Test} \usage{ mwu(x, grp, distribution = "asymptotic", weight.by = NULL) } \arguments{ \item{x}{Numeric vector or variable.} \item{grp}{Grouping variable indicating the groups that should be used for comparison.} \item{distribution}{Indicates how the null distribution of the test statistic should be computed. May be one of \code{"exact"}, \code{"approximate"} or \code{"asymptotic"} (default). See \code{\link[coin]{wilcox_test}} for details.} \item{weight.by}{Vector of weights that will be applied to weight all observations. Must be a vector of same length as the input vector. Default is \code{NULL}, so no weights are used.} } \value{ (Invisibly) returns a data frame with U, p and Z-values for each group-comparison as well as effect-size r; additionally, group-labels and groups' n's are also included. } \description{ This function performs a Mann-Whitney-U-Test (or Wilcoxon rank sum test, see \code{\link{wilcox.test}} and \code{\link[coin]{wilcox_test}}) for \code{x}, for each group indicated by \code{grp}. If \code{grp} has more than two categories, a comparison between each combination of two groups is performed. \cr \cr The function reports U, p and Z-values as well as effect size r and group-rank-means. } \note{ This function calls the \code{\link[coin]{wilcox_test}} with formula. If \code{grp} has more than two groups, additionally a Kruskal-Wallis-Test (see \code{\link{kruskal.test}}) is performed. \cr \cr Interpretation of effect sizes, as a rule-of-thumb: \itemize{ \item small effect >= 0.1 \item medium effect >= 0.3 \item large effect >= 0.5 } } \examples{ data(efc) # Mann-Whitney-U-Tests for elder's age by elder's dependency. mwu(efc$e17age, efc$e42dep) }
/man/mwu.Rd
no_license
stefanfritsch/sjstats
R
false
true
1,998
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mwu.R \name{mwu} \alias{mwu} \title{Mann-Whitney-U-Test} \usage{ mwu(x, grp, distribution = "asymptotic", weight.by = NULL) } \arguments{ \item{x}{Numeric vector or variable.} \item{grp}{Grouping variable indicating the groups that should be used for comparison.} \item{distribution}{Indicates how the null distribution of the test statistic should be computed. May be one of \code{"exact"}, \code{"approximate"} or \code{"asymptotic"} (default). See \code{\link[coin]{wilcox_test}} for details.} \item{weight.by}{Vector of weights that will be applied to weight all observations. Must be a vector of same length as the input vector. Default is \code{NULL}, so no weights are used.} } \value{ (Invisibly) returns a data frame with U, p and Z-values for each group-comparison as well as effect-size r; additionally, group-labels and groups' n's are also included. } \description{ This function performs a Mann-Whitney-U-Test (or Wilcoxon rank sum test, see \code{\link{wilcox.test}} and \code{\link[coin]{wilcox_test}}) for \code{x}, for each group indicated by \code{grp}. If \code{grp} has more than two categories, a comparison between each combination of two groups is performed. \cr \cr The function reports U, p and Z-values as well as effect size r and group-rank-means. } \note{ This function calls the \code{\link[coin]{wilcox_test}} with formula. If \code{grp} has more than two groups, additionally a Kruskal-Wallis-Test (see \code{\link{kruskal.test}}) is performed. \cr \cr Interpretation of effect sizes, as a rule-of-thumb: \itemize{ \item small effect >= 0.1 \item medium effect >= 0.3 \item large effect >= 0.5 } } \examples{ data(efc) # Mann-Whitney-U-Tests for elder's age by elder's dependency. mwu(efc$e17age, efc$e42dep) }
print.dspat=function(x,...) ################################################################################## # Prints relevant parts of a dspat object # # Jeff Laake # 9 April 2008 ################################################################################## { cat("\nStudy area: ") print(x$study.area) cat("\nLines: ") print(x$lines.psp) cat("\nObservations: ") print(x$model$Q$data) cat("\nFitted model: ") print(x$model) return(NULL) } summary.dspat=function(object,...) ################################################################################## # Summarizes ppm model fit # # Jeff Laake # 9 April 2008 ################################################################################## { summary(object$model) } coef.dspat=function(object,...) ################################################################################## # Extracts coefficients and separates into intensity and detection parameters # # Jeff Laake # 9 April 2008 ################################################################################## { coeff=coef(object$model) detection=grep("distance",names(coeff)) if(length(detection)!=0) return(list(intensity=coeff[-detection],detection=coeff[detection])) else return(list(intensity=coeff,detection=NULL)) } vcov.dspat=function(object,...) ################################################################################## # Extracts variance-covariance matrix for coefficients of fitted model # # Jeff Laake # 9 April 2008 ################################################################################## { return(vcov.ppm(object$model,gamaction="silent")) } AIC.dspat=function(object,...,k) ################################################################################## # Extracts AIC for fitted model # # Jeff Laake # 9 April 2008 ################################################################################## { if(missing(k)) k=2 return(-2*object$model$maxlogpl+k*length(coef(object$model))) } im.clipped=function(x,window) ################################################################################## # Fills an image with values x into a clipped non-rectangular window and # returns an image (class im). An im must be rectagular, so this function # creates a rectangular image using the bounding box for window with a 0 value # and then fills in the values (x) that are in window. # # Arguments: # x -a vector of image values in order defined by spatstat with # y increasing fastest and then x increasing (see rev_val) # # window - a polygonal window of class owin # # Value: an image with NA outside window and image values in window of the # image # # # # Jeff Laake # 20 April 2008 ################################################################################## { x.im=as.im(0,W=window) x.im[window]=x return(x.im) } rev_val=function(x,y,val) ################################################################################## # Reverses order of vector val such that it matches order needed for # an image with y increasing within x increasing. If val aleady in that # order it will remain unchanged. # # Arguments: # x - x coordinates # y - y coordinates # val - values at x,y # # Value: reordered vector of values # # Jeff Laake # 20 April 2008 ################################################################################## { X=cbind(x,y,val) return(X[order(x,y),3]) } Ops.psp=function(e1,e2) ################################################################################## # Allows syntax of x==y or x!=y where x and y are 2 psp objects. # Tests whether 2 line segment objects are = or != # # Arguments: e1,e2 - psp objects # Value: TRUE or FALSE # # Jeff Laake # 14 April 2008 ################################################################################## { ok <- switch(.Generic, "==" = , "!=" = TRUE, FALSE) if (!ok) { warning(.Generic, " not meaningful for psp") return(rep.int(NA, max(length(e1), if (!missing(e2)) length(e2)))) } if(!class(e1)[1]=="psp" | !class(e2)[1]=="psp") stop("\nOne or more arguments is not of class psp") x.end=endpoints.psp(e1) y.end=endpoints.psp(e2) if(.Generic == "==") return(x.end$n==y.end$n & all(x.end$x==y.end$x) & all(x.end$y==y.end$y) ) else return(!(x.end$n==y.end$n & all(x.end$x==y.end$x) & all(x.end$y==y.end$y)) ) } owin.gpc.poly=function(window) ################################################################################## # Converts an owin class composed of a single polygon to a gpc.poly # # Arguments: window - an owin class # # Value : gpc.poly from first polygon in owin # # Jeff Laake # 18 April 2008 ################################################################################## { if(is.null(window$bdry)) return(as(cbind(c(window$xrange,rev(window$xrange)), c(rep(window$yrange[1],2),rep(window$yrange[2],2))), "gpc.poly")) else return(as(cbind(window$bdry[[1]]$x,window$bdry[[1]]$y),"gpc.poly")) }
/DSpat/R/internal.R
no_license
jlaake/DSpat
R
false
false
5,207
r
print.dspat=function(x,...) ################################################################################## # Prints relevant parts of a dspat object # # Jeff Laake # 9 April 2008 ################################################################################## { cat("\nStudy area: ") print(x$study.area) cat("\nLines: ") print(x$lines.psp) cat("\nObservations: ") print(x$model$Q$data) cat("\nFitted model: ") print(x$model) return(NULL) } summary.dspat=function(object,...) ################################################################################## # Summarizes ppm model fit # # Jeff Laake # 9 April 2008 ################################################################################## { summary(object$model) } coef.dspat=function(object,...) ################################################################################## # Extracts coefficients and separates into intensity and detection parameters # # Jeff Laake # 9 April 2008 ################################################################################## { coeff=coef(object$model) detection=grep("distance",names(coeff)) if(length(detection)!=0) return(list(intensity=coeff[-detection],detection=coeff[detection])) else return(list(intensity=coeff,detection=NULL)) } vcov.dspat=function(object,...) ################################################################################## # Extracts variance-covariance matrix for coefficients of fitted model # # Jeff Laake # 9 April 2008 ################################################################################## { return(vcov.ppm(object$model,gamaction="silent")) } AIC.dspat=function(object,...,k) ################################################################################## # Extracts AIC for fitted model # # Jeff Laake # 9 April 2008 ################################################################################## { if(missing(k)) k=2 return(-2*object$model$maxlogpl+k*length(coef(object$model))) } im.clipped=function(x,window) ################################################################################## # Fills an image with values x into a clipped non-rectangular window and # returns an image (class im). An im must be rectagular, so this function # creates a rectangular image using the bounding box for window with a 0 value # and then fills in the values (x) that are in window. # # Arguments: # x -a vector of image values in order defined by spatstat with # y increasing fastest and then x increasing (see rev_val) # # window - a polygonal window of class owin # # Value: an image with NA outside window and image values in window of the # image # # # # Jeff Laake # 20 April 2008 ################################################################################## { x.im=as.im(0,W=window) x.im[window]=x return(x.im) } rev_val=function(x,y,val) ################################################################################## # Reverses order of vector val such that it matches order needed for # an image with y increasing within x increasing. If val aleady in that # order it will remain unchanged. # # Arguments: # x - x coordinates # y - y coordinates # val - values at x,y # # Value: reordered vector of values # # Jeff Laake # 20 April 2008 ################################################################################## { X=cbind(x,y,val) return(X[order(x,y),3]) } Ops.psp=function(e1,e2) ################################################################################## # Allows syntax of x==y or x!=y where x and y are 2 psp objects. # Tests whether 2 line segment objects are = or != # # Arguments: e1,e2 - psp objects # Value: TRUE or FALSE # # Jeff Laake # 14 April 2008 ################################################################################## { ok <- switch(.Generic, "==" = , "!=" = TRUE, FALSE) if (!ok) { warning(.Generic, " not meaningful for psp") return(rep.int(NA, max(length(e1), if (!missing(e2)) length(e2)))) } if(!class(e1)[1]=="psp" | !class(e2)[1]=="psp") stop("\nOne or more arguments is not of class psp") x.end=endpoints.psp(e1) y.end=endpoints.psp(e2) if(.Generic == "==") return(x.end$n==y.end$n & all(x.end$x==y.end$x) & all(x.end$y==y.end$y) ) else return(!(x.end$n==y.end$n & all(x.end$x==y.end$x) & all(x.end$y==y.end$y)) ) } owin.gpc.poly=function(window) ################################################################################## # Converts an owin class composed of a single polygon to a gpc.poly # # Arguments: window - an owin class # # Value : gpc.poly from first polygon in owin # # Jeff Laake # 18 April 2008 ################################################################################## { if(is.null(window$bdry)) return(as(cbind(c(window$xrange,rev(window$xrange)), c(rep(window$yrange[1],2),rep(window$yrange[2],2))), "gpc.poly")) else return(as(cbind(window$bdry[[1]]$x,window$bdry[[1]]$y),"gpc.poly")) }
testlist <- list(ExpressionSet = structure(c(3.10503529560174e+231, 1.23181983389617e+58, 1.52478221747831e+245, 6.36967296041789e+178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L)), Phylostratum = numeric(0)) result <- do.call(myTAI:::cpp_TAI,testlist) str(result)
/myTAI/inst/testfiles/cpp_TAI/AFL_cpp_TAI/cpp_TAI_valgrind_files/1615762279-test.R
no_license
akhikolla/updatedatatype-list3
R
false
false
334
r
testlist <- list(ExpressionSet = structure(c(3.10503529560174e+231, 1.23181983389617e+58, 1.52478221747831e+245, 6.36967296041789e+178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L)), Phylostratum = numeric(0)) result <- do.call(myTAI:::cpp_TAI,testlist) str(result)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/maps.R \name{agg_station_map} \alias{agg_station_map} \title{Aggregate scores by station} \usage{ agg_station_map(map.me, pct_sum, spatial, taxon.rank, todays.date) } \description{ Aggregate scores by station }
/man/agg_station_map.Rd
no_license
zsmith27/CHESSIE
R
false
true
289
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/maps.R \name{agg_station_map} \alias{agg_station_map} \title{Aggregate scores by station} \usage{ agg_station_map(map.me, pct_sum, spatial, taxon.rank, todays.date) } \description{ Aggregate scores by station }
## this script won't download the data file for you ## download and extract the zip file to ./data directory in you working directory ## data url: https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip ## this script assume you have household_power_consumption.txt in ./data directory ## tidy data library(dplyr) data <- read.csv("./data/household_power_consumption.txt", stringsAsFactors=F, sep = ";") data <- filter(data, Date=="1/2/2007" | Date=="2/2/2007") data[,3] <- as.numeric(data[,3]) data[,4] <- as.numeric(data[,4]) data[,5] <- as.numeric(data[,5]) data[,6] <- as.numeric(data[,6]) data[,7] <- as.numeric(data[,7]) data[,8] <- as.numeric(data[,8]) data$TD <- strptime(paste(data$Date, data$Time, sep=","), format="%d/%m/%Y, %H:%M:%S") ## plot line par(mfrow = c(1,1),oma=c(0,1,0,0)) plot(data$TD,data$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="", cex.lab=0.8, cex.axis=0.8) ## output to png file dev.copy(png, file="plot2.png") dev.off()
/coursera-exploratory data analysis/project 1/plot2.R
no_license
adamantoi/datasciencecoursera
R
false
false
1,049
r
## this script won't download the data file for you ## download and extract the zip file to ./data directory in you working directory ## data url: https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip ## this script assume you have household_power_consumption.txt in ./data directory ## tidy data library(dplyr) data <- read.csv("./data/household_power_consumption.txt", stringsAsFactors=F, sep = ";") data <- filter(data, Date=="1/2/2007" | Date=="2/2/2007") data[,3] <- as.numeric(data[,3]) data[,4] <- as.numeric(data[,4]) data[,5] <- as.numeric(data[,5]) data[,6] <- as.numeric(data[,6]) data[,7] <- as.numeric(data[,7]) data[,8] <- as.numeric(data[,8]) data$TD <- strptime(paste(data$Date, data$Time, sep=","), format="%d/%m/%Y, %H:%M:%S") ## plot line par(mfrow = c(1,1),oma=c(0,1,0,0)) plot(data$TD,data$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="", cex.lab=0.8, cex.axis=0.8) ## output to png file dev.copy(png, file="plot2.png") dev.off()
suppressMessages(library(cacheSweave)) infile <- system.file("example", "simpleRR.Rnw", package = "cacheSweave") setCacheDir("cache") Sweave(infile, driver = cacheSweaveDriver) ls() ## Check to see that objects were properly cached ## Database should contain 'airquality' and 'fit' dname <- dir("cache", full.names = TRUE) suppressMessages(library(stashR)) db <- new("localDB", dir = dname[2], name = "cacheDB") dbList(db)
/tests/reg-tests.R
no_license
mclements/cachesweave
R
false
false
430
r
suppressMessages(library(cacheSweave)) infile <- system.file("example", "simpleRR.Rnw", package = "cacheSweave") setCacheDir("cache") Sweave(infile, driver = cacheSweaveDriver) ls() ## Check to see that objects were properly cached ## Database should contain 'airquality' and 'fit' dname <- dir("cache", full.names = TRUE) suppressMessages(library(stashR)) db <- new("localDB", dir = dname[2], name = "cacheDB") dbList(db)
CETTActionsParser <- R6::R6Class( "CETTActionsParser", inherit = AbstractParser, private = list( parse_record = function() { cett_type <- strsplit(private$tibble_name, "_")[[1]][1] drugs <- xmlChildren(pkg_env$root) pb <- progress_bar$new(total = xmlSize(drugs)) actions_tbl <- map_df(drugs, ~ private$actions_rec(., cett_type, pb)) %>% unique() if (nrow(actions_tbl) > 0) { colnames(actions_tbl) <- c("action", "parent_id") } return(actions_tbl) }, actions_rec = function(rec, cett_type, pb) { pb$tick() return(map_df(xmlChildren(rec[[cett_type]]), ~ drug_sub_df(., "actions", id = "id"))) } ) ) #' Carriers/ Enzymes/ Targets/ Transporters Actions parsers #' #' Collection of related actions #' #' @return a tibble with 2 variables: #' \describe{ #' \item{action}{describe related action} #' \item{\emph{parent_id}}{carrier/ target/ enzyme/ transporter id} #' } #' @keywords internal #' @name cett_actions_doc NULL #' @rdname cett_actions_doc carriers_actions <- function() { CETTActionsParser$new( "carriers_actions" )$parse() } #' @rdname cett_actions_doc enzymes_actions <- function() { CETTActionsParser$new( "enzymes_actions" )$parse() } #' @rdname cett_actions_doc targets_actions <- function() { CETTActionsParser$new( "targets_actions" )$parse() } #' @rdname cett_actions_doc transporters_actions <- function() { CETTActionsParser$new( "transporters_actions" )$parse() }
/R/cett_actions_parsers.R
no_license
cran/dbparser
R
false
false
1,644
r
CETTActionsParser <- R6::R6Class( "CETTActionsParser", inherit = AbstractParser, private = list( parse_record = function() { cett_type <- strsplit(private$tibble_name, "_")[[1]][1] drugs <- xmlChildren(pkg_env$root) pb <- progress_bar$new(total = xmlSize(drugs)) actions_tbl <- map_df(drugs, ~ private$actions_rec(., cett_type, pb)) %>% unique() if (nrow(actions_tbl) > 0) { colnames(actions_tbl) <- c("action", "parent_id") } return(actions_tbl) }, actions_rec = function(rec, cett_type, pb) { pb$tick() return(map_df(xmlChildren(rec[[cett_type]]), ~ drug_sub_df(., "actions", id = "id"))) } ) ) #' Carriers/ Enzymes/ Targets/ Transporters Actions parsers #' #' Collection of related actions #' #' @return a tibble with 2 variables: #' \describe{ #' \item{action}{describe related action} #' \item{\emph{parent_id}}{carrier/ target/ enzyme/ transporter id} #' } #' @keywords internal #' @name cett_actions_doc NULL #' @rdname cett_actions_doc carriers_actions <- function() { CETTActionsParser$new( "carriers_actions" )$parse() } #' @rdname cett_actions_doc enzymes_actions <- function() { CETTActionsParser$new( "enzymes_actions" )$parse() } #' @rdname cett_actions_doc targets_actions <- function() { CETTActionsParser$new( "targets_actions" )$parse() } #' @rdname cett_actions_doc transporters_actions <- function() { CETTActionsParser$new( "transporters_actions" )$parse() }
TEAM_NAME="jakl" VERSION="R version 3.6.0 (2019-04-26)" load_data <- function(path){ # Loads the data using base R. # data <- read.csv(path, stringsAsFactors = T) data } computer_use_001 <- function(data){ # Computer use is defined using 'comp_week' and 'comp_wend' # IMPORTS # DEFINE COMPUTER USE # Assign average numeric values for each of the categories # reorder the levels of comp_week and comp_wend data$comp_week <- factor(data$comp_week,levels(data$comp_week)[c(4,3,1,2)]) data$comp_wend <- factor(data$comp_wend,levels(data$comp_wend)[c(4,3,1,2)]) # keep these names for plotting later #iv.levels <- levels(data$comp_week) data } depression_001 <- function(data){ # This function defines depression using 'prim_diag' and # 'secd_diag', values 10-12 and also 4 'mixed anxiety and depression' #IMPORTS: #PARAMETERS: #DEFINE DEPRESSION: data$anydepdiag <- 0 data$anydepdiag[data$prim_diag==4 | data$prim_diag==10 | data$prim_diag==11 | data$prim_diag==12 ] <- 1 data$anydepdiag[data$secd_diag==4 | data$secd_diag==10 | data$secd_diag==11 | data$secd_diag==12 ] <- 1 data } transformation_001 <- function(data){ # This selects some variables to use in final model # IMPORTS # PARAMETERS VARIABLES_TO_USE <- c('anydepdiag', 'comp_week', 'comp_wend') # select data data <- select(data, VARIABLES_TO_USE) data } specify_model <- function(data){ # Logistic regression to predict anydepdiag from computer use on weekdays and at weekends # follows examples at https://stats.idre.ucla.edu/r/dae/logit-regression/ # uses package aod # IMPORTS library(aod) library(tidyverse) # logistic regression model model <- glm(data=data, anydepdiag ~ comp_week + comp_wend, family="binomial") summary(model) confint(model) # confidence intervals on co-efficients estimates based on the profiled log-likelihood function # log odds ratio s.e. and lower/upper bounds for CI lor <- model$coefficients[2:7] lse <- summary(model)$coefficients[2:7,2] llb <- lor - 2*lse lub <- lor + 2*lse # exponentiate or <- exp(lor) ci <- exp(c(llb, lub)) # the results # Note: DIC not necessary (not Bayes/Hierarchical model) # data must be returned as part of a list because R can't return multiple objects results <- list('aic' = model$aic, 'or_1' = exp(model$coefficients[2:7]), 'p_1' = summary(model)$coefficients[2:7,4], 'ci_1' = ci, 'mod' = model, 'data' = data) results } output <- function(results){ # make some visible output so we can see what the model has done # IMPORTS library(tidyverse) library(pander) # send reportables to console message(paste("AIC=",results$aic)) message(results$or_1 %>% pandoc.table(caption="Odds Ratios")) message(results$p_1 %>% pandoc.table(caption="Probabilities")) message(results$ci_1 %>% pandoc.table(caption="Confidence Intervals")) } #### lines to run functions data <- load_data(path = 'https://raw.githubusercontent.com/knedza/JAKL/master/maps-synthetic-data-v1.1.csv') data <- computer_use_001(data) data <- depression_001(data) data <- transformation_001(data) results <- specify_model(data) output(results)
/JAKLinFunctions.R
no_license
knedza/JAKL
R
false
false
3,518
r
TEAM_NAME="jakl" VERSION="R version 3.6.0 (2019-04-26)" load_data <- function(path){ # Loads the data using base R. # data <- read.csv(path, stringsAsFactors = T) data } computer_use_001 <- function(data){ # Computer use is defined using 'comp_week' and 'comp_wend' # IMPORTS # DEFINE COMPUTER USE # Assign average numeric values for each of the categories # reorder the levels of comp_week and comp_wend data$comp_week <- factor(data$comp_week,levels(data$comp_week)[c(4,3,1,2)]) data$comp_wend <- factor(data$comp_wend,levels(data$comp_wend)[c(4,3,1,2)]) # keep these names for plotting later #iv.levels <- levels(data$comp_week) data } depression_001 <- function(data){ # This function defines depression using 'prim_diag' and # 'secd_diag', values 10-12 and also 4 'mixed anxiety and depression' #IMPORTS: #PARAMETERS: #DEFINE DEPRESSION: data$anydepdiag <- 0 data$anydepdiag[data$prim_diag==4 | data$prim_diag==10 | data$prim_diag==11 | data$prim_diag==12 ] <- 1 data$anydepdiag[data$secd_diag==4 | data$secd_diag==10 | data$secd_diag==11 | data$secd_diag==12 ] <- 1 data } transformation_001 <- function(data){ # This selects some variables to use in final model # IMPORTS # PARAMETERS VARIABLES_TO_USE <- c('anydepdiag', 'comp_week', 'comp_wend') # select data data <- select(data, VARIABLES_TO_USE) data } specify_model <- function(data){ # Logistic regression to predict anydepdiag from computer use on weekdays and at weekends # follows examples at https://stats.idre.ucla.edu/r/dae/logit-regression/ # uses package aod # IMPORTS library(aod) library(tidyverse) # logistic regression model model <- glm(data=data, anydepdiag ~ comp_week + comp_wend, family="binomial") summary(model) confint(model) # confidence intervals on co-efficients estimates based on the profiled log-likelihood function # log odds ratio s.e. and lower/upper bounds for CI lor <- model$coefficients[2:7] lse <- summary(model)$coefficients[2:7,2] llb <- lor - 2*lse lub <- lor + 2*lse # exponentiate or <- exp(lor) ci <- exp(c(llb, lub)) # the results # Note: DIC not necessary (not Bayes/Hierarchical model) # data must be returned as part of a list because R can't return multiple objects results <- list('aic' = model$aic, 'or_1' = exp(model$coefficients[2:7]), 'p_1' = summary(model)$coefficients[2:7,4], 'ci_1' = ci, 'mod' = model, 'data' = data) results } output <- function(results){ # make some visible output so we can see what the model has done # IMPORTS library(tidyverse) library(pander) # send reportables to console message(paste("AIC=",results$aic)) message(results$or_1 %>% pandoc.table(caption="Odds Ratios")) message(results$p_1 %>% pandoc.table(caption="Probabilities")) message(results$ci_1 %>% pandoc.table(caption="Confidence Intervals")) } #### lines to run functions data <- load_data(path = 'https://raw.githubusercontent.com/knedza/JAKL/master/maps-synthetic-data-v1.1.csv') data <- computer_use_001(data) data <- depression_001(data) data <- transformation_001(data) results <- specify_model(data) output(results)
library(ggplot2) library(ez) library(Hmisc) library(reshape2) library(psychReport) library(lsr) library(bayestestR) library(BayesFactor) library(TOSTER) #### clear environment rm(list = ls()) #### load data # on Inspiron 13 setwd("C:/Users/wuxiu/Documents/PhD@UBC/Lab/2ndYear/AnticipatoryPursuit/AnticipatoryPursuitMotionPerception/analysis/R") source("pairwise.t.test.with.t.and.df.R") plotFolder <- ("C:/Users/wuxiu/Documents/PhD@UBC/Lab/2ndYear/AnticipatoryPursuit/AnticipatoryPursuitMotionPerception/results/manuscript/figures/rawPlots/") ### modify these parameters to plot different conditions # dataFileName <- "timeBinPSE_exp1.csv" dataFileName <- "PSE_exp1vs3.csv" # pdfFileName <- "timeBinPSE_exp1.pdf" pdfInteractionFileName <- "PSE_exp1vs3_interaction.pdf" # pdfFileNameD <- "slopeDiff_exp1vs3.pdf" # for plotting textSize <- 25 axisLineWidth <- 0.5 dotSize <- 3 # slope ylimLow <- 10 ylimHigh <- 50 # PSE ylimLow <- -0.15 ylimHigh <- 0.15 # # ASP # ylimLow <- -1 # ylimHigh <- 5 # # # ASP gain # # ylimLow <- -0.1 # # ylimHigh <- 0.4 # # clp gain in context trials # ylimLow <- 0 # ylimHigh <- 1 data <- read.csv(dataFileName) subAll <- unique(data["sub"]) subTotalN <- dim(subAll)[1] # dataD <- read.csv(dataDFileName) # data <- data[data.exp==3] # # exclude bad fitting... # data <- subset(data[which(data$sub!=8),]) ## compare two experiments # PSE anova sub <- data["sub"] exp <- data["exp"] # timeBin <- data["timeBin"] prob <- data["prob"] measure <- data["PSE"] dataAnova <- data.frame(sub, prob, exp, measure) dataAnova$prob <- as.factor(dataAnova$prob) dataAnova$sub <- as.factor(dataAnova$sub) dataAnova$exp <- as.factor(dataAnova$exp) # dataAnova$timeBin <- as.factor(dataAnova$timeBin) colnames(dataAnova)[4] <- "measure" # dataAnova <- aggregate(perceptualErrorMean ~ sub * rotationSpeed * exp, # data = dataTemp, FUN = "mean") anovaData <- ezANOVA(dataAnova, dv = .(measure), wid = .(sub), within = .(prob, exp), type = 3, return_aov = TRUE, detailed = TRUE) # print(anovaData) aovEffectSize(anovaData, 'pes') # Equivalence test for the differences of PSE between experiments dataE <- data.frame(matrix(ncol=3,nrow=dim(subAll)[1], dimnames=list(NULL, c("sub", "exp1", "exp2")))) for (subN in 1:subTotalN) { data150 <- dataAnova[which(sub==subAll[subN, 1] & exp==1 & prob==50), ]$measure data190 <- dataAnova[which(sub==subAll[subN, 1] & exp==1 & prob==90), ]$measure data250 <- dataAnova[which(sub==subAll[subN, 1] & exp!=1 & prob==50), ]$measure data290 <- dataAnova[which(sub==subAll[subN, 1] & exp!=1 & prob==90), ]$measure dataE["sub"][subN, 1] <- subN dataE["exp1"][subN, 1] <- data190-data150 dataE["exp2"][subN, 1] <- data290-data250 } show(dataE) dataTOSTpaired(data = dataE, pairs = list((c(i1="exp1",i2="exp2"))), low_eqbound = -0.36, high_eqbound = 0.36, eqbound_type = "d", alpha = 0.05, desc = TRUE, plots = TRUE) # # compute Bayes Factor inclusion... # bf <- anovaBF(measure ~ prob + timeBin + prob*timeBin + sub, data = dataAnova, # whichRandom="sub") # bayesfactor_inclusion(bf, match_models = TRUE) # p <- ggplot(dataAnova, aes(x = prob, y = measure, color = exp)) + # stat_summary(aes(y = measure), fun.y = mean, geom = "point", shape = 95, size = 15) + # stat_summary(fun.data = 'mean_sdl', # fun.args = list(mult = 1.96/sqrt(subTotalN)), # geom = 'errorbar', width = .1) + # # geom = 'smooth', se = 'TRUE') + # # stat_summary(aes(y = measure), fun.data = mean_se, geom = "errorbar", width = 0.1) + # geom_point(aes(x = prob, y = measure), size = dotSize, shape = 1) + # # geom_segment(aes_all(c('x', 'y', 'xend', 'yend')), data = data.frame(x = c(50, 40), xend = c(90, 40), y = c(-0.1, -0.1), yend = c(-0.1, 0.15)), size = axisLineWidth) + # scale_y_continuous(name = "Anticipatory pursuit velocity (°/s)") + #, limits = c(-0.1, 0.55), expand = c(0, 0)) + # # scale_y_continuous(name = "PSE") + # scale_x_discrete(name = "Probability of rightward motion", breaks=c("50", "90")) + # # scale_x_discrete(name = "Probability of rightward motion", breaks=c(50, 70, 90)) + # # scale_colour_discrete(name = "After reversal\ndirection", labels = c("CCW", "CW")) + # theme(axis.text=element_text(colour="black"), # axis.ticks=element_line(colour="black", size = axisLineWidth), # panel.grid.major = element_blank(), # panel.grid.minor = element_blank(), # panel.border = element_blank(), # panel.background = element_blank(), # text = element_text(size = textSize, colour = "black"), # legend.background = element_rect(fill="transparent"), # legend.key = element_rect(colour = "transparent", fill = "white")) # # facet_wrap(~exp) # print(p) # ggsave(paste(plotFolder, pdfFileName, sep = "")) # ## t-test of the simple main effect of probability in the control experiment # dataD <- dataAnova[dataAnova$exp==3,] # # show(dataD) # res <- pairwise.t.test.with.t.and.df(x = dataD$measure, g = dataD$prob, paired = TRUE, p.adj="none") # show(res) # [[3]] = p value table, un adjusted # res[[5]] # t-value # res[[6]] # dfs # res[[3]] # p.adjust(res[[3]], method = "bonferroni", n = 4) # cohensd <- cohensD(subset(dataD, prob==50)$measure, subset(dataD, prob==90)$measure, method = 'paired') # show(cohensd) ## interaction plot dataPlot <- data.frame(sub, prob, exp, measure) colnames(dataPlot)[4] <- "measure" dataPlot$sub <- as.factor(dataPlot$sub) # dataPlot$prob <- as.factor(dataPlot$prob) # is.numeric(dataPlot$timeBin) dataPlot$exp <- as.factor(dataPlot$exp) # dataPlot <- aggregate(measure ~ exp+prob, data = dataPlot, FUN = "mean") # show(dataPlot) # # for time bin plots # p <- ggplot(dataPlot, aes(x = timeBin, y = measure, color = prob)) + # stat_summary(fun.y = mean, geom = "point", shape = 95, size = 17.5) + # stat_summary(fun.y = mean, geom = "line", width = 1) + # stat_summary(fun.data = 'mean_sdl', fun.args = list(mult = 1.96/sqrt(subTotalN)), geom = 'errorbar', width = 1.5, size = 1) + # scale_x_continuous(name = "time bin of trials", breaks=c(1, 2), limits = c(0.5, 2.5), expand = c(0, 0)) + p <- ggplot(dataPlot, aes(x = prob, y = measure, color = exp)) + stat_summary(fun.y = mean, geom = "point", shape = 95, size = 17.5) + stat_summary(fun.y = mean, geom = "line", width = 1) + stat_summary(fun.data = 'mean_sdl', fun.args = list(mult = 1.96/sqrt(subTotalN)), geom = 'errorbar', width = 1.5, size = 1) + stat_summary(aes(y = measure), fun.data = mean_se, geom = "errorbar", width = 0.1) + # geom_point(aes(x = prob, y = measure), size = dotSize, shape = 1) + geom_segment(aes_all(c('x', 'y', 'xend', 'yend')), data = data.frame(x = c(50, 45), y = c(ylimLow, ylimLow), xend = c(90, 45), yend = c(ylimLow, ylimHigh)), size = axisLineWidth, inherit.aes = FALSE) + # scale_y_continuous(name = "Anticipatory pursuit velocity (°/s)", breaks = seq(ylimLow, ylimHigh, 1), expand = c(0, 0)) + # scale_y_continuous(name = "Anticipatory pursuit velocity gain", breaks = seq(ylimLow, ylimHigh, 0.1), expand = c(0, 0)) + # coord_cartesian(ylim=c(ylimLow, ylimHigh)) + scale_y_continuous(name = "PSE", limits = c(ylimLow, ylimHigh), breaks = c(ylimLow, 0, ylimHigh), expand = c(0, 0)) + scale_x_continuous(name = "Probability of rightward motion", breaks=c(50, 90), limits = c(45, 95), expand = c(0, 0)) + # scale_x_discrete(name = "Probability of rightward motion", breaks=c("50", "90")) + # scale_colour_discrete(name = "After reversal\ndirection", labels = c("CCW", "CW")) + theme(axis.text=element_text(colour="black"), axis.ticks=element_line(colour="black", size = axisLineWidth), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank(), text = element_text(size = textSize, colour = "black"), legend.background = element_rect(fill="transparent"), legend.key = element_rect(colour = "transparent", fill = "white")) # facet_wrap(~exp) print(p) ggsave(paste(plotFolder, pdfInteractionFileName, sep = "")) # ## t-test of the difference # sub <- dataD["sub"] # exp <- dataD["exp"] # measure <- dataD["slopeDiff"] # dataDtemp <- data.frame(sub, exp, measure) # dataDtemp$sub <- as.factor(dataDtemp$sub) # dataDtemp$exp <- as.factor(dataDtemp$exp) # colnames(dataDtemp)[3] <- "measure" # # dataDttest <- aggregate(measure ~ exp, data = dataDtemp, FUN = "mean") # # res <- pairwise.t.test.with.t.and.df(x = dataDtemp$measure, g = dataDtemp$exp, paired = TRUE, p.adj="none") # # show(res) # [[3]] = p value table, un adjusted # # res[[5]] # t-value # # res[[6]] # dfs # # res[[3]] # # p.adjust(res[[3]], method = "bonferroni", n = 3) # # # bias in PSE # # ylimLow <- -0.05 # # ylimHigh <- 0.2 # # # bias in ASP # # ylimLow <- 0 # # ylimHigh <- 3 # # bias in slope # ylimLow <- -40 # ylimHigh <- 30 # p <- ggplot(dataDtemp, aes(x = exp, y = measure)) + # stat_summary(aes(y = measure), fun.y = mean, geom = "point", shape = 95, size = 15) + # stat_summary(fun.data = 'mean_sdl', # fun.args = list(mult = 1.96/sqrt(subTotalN)), # geom = 'linerange', size = 1) + # geom_line(aes(x = exp, y = measure, group = sub), size = 0.5, linetype = "dashed") + # geom_point(aes(x = exp, y = measure), size = dotSize, shape = 1) + # geom_segment(aes_all(c('x', 'y', 'xend', 'yend')), data = data.frame(x = c(0), y = c(ylimLow), xend = c(0), yend = c(ylimHigh)), size = axisLineWidth) + # # scale_y_continuous(name = "Bias of PSE") + #, limits = c(0, 0.15), expand = c(0, 0.01)) + # scale_y_continuous(name = "Bias of slope") + #, limits = c(0, 0.15), expand = c(0, 0.01)) + # # scale_y_continuous(name = "Bias of anticipatory pursuit velocity(deg/s)") + #, limits = c(0, 0.15), expand = c(0, 0.01)) + # scale_x_discrete(name = "Experiment", limits = c("1", "3"), labels = c("1" = "Exp1", "3" = "Exp3")) + # # scale_x_discrete(name = "Experiment", limits = c("1", "2"), labels = c("1" = "Exp1", "2" = "Exp2")) + # theme(axis.text=element_text(colour="black"), # axis.ticks=element_line(colour="black", size = axisLineWidth), # panel.grid.major = element_blank(), # panel.grid.minor = element_blank(), # panel.border = element_blank(), # panel.background = element_blank(), # text = element_text(size = textSize, colour = "black"), # legend.background = element_rect(fill="transparent"), # legend.key = element_rect(colour = "transparent", fill = "white")) # # facet_wrap(~prob) # print(p) # ggsave(paste(plotFolder, pdfFileNameD, sep = ""))
/analysis/R/twowayANOVAs&plots.R
no_license
CaptainS5/AnticipatoryPursuit-MotionPerception
R
false
false
11,178
r
library(ggplot2) library(ez) library(Hmisc) library(reshape2) library(psychReport) library(lsr) library(bayestestR) library(BayesFactor) library(TOSTER) #### clear environment rm(list = ls()) #### load data # on Inspiron 13 setwd("C:/Users/wuxiu/Documents/PhD@UBC/Lab/2ndYear/AnticipatoryPursuit/AnticipatoryPursuitMotionPerception/analysis/R") source("pairwise.t.test.with.t.and.df.R") plotFolder <- ("C:/Users/wuxiu/Documents/PhD@UBC/Lab/2ndYear/AnticipatoryPursuit/AnticipatoryPursuitMotionPerception/results/manuscript/figures/rawPlots/") ### modify these parameters to plot different conditions # dataFileName <- "timeBinPSE_exp1.csv" dataFileName <- "PSE_exp1vs3.csv" # pdfFileName <- "timeBinPSE_exp1.pdf" pdfInteractionFileName <- "PSE_exp1vs3_interaction.pdf" # pdfFileNameD <- "slopeDiff_exp1vs3.pdf" # for plotting textSize <- 25 axisLineWidth <- 0.5 dotSize <- 3 # slope ylimLow <- 10 ylimHigh <- 50 # PSE ylimLow <- -0.15 ylimHigh <- 0.15 # # ASP # ylimLow <- -1 # ylimHigh <- 5 # # # ASP gain # # ylimLow <- -0.1 # # ylimHigh <- 0.4 # # clp gain in context trials # ylimLow <- 0 # ylimHigh <- 1 data <- read.csv(dataFileName) subAll <- unique(data["sub"]) subTotalN <- dim(subAll)[1] # dataD <- read.csv(dataDFileName) # data <- data[data.exp==3] # # exclude bad fitting... # data <- subset(data[which(data$sub!=8),]) ## compare two experiments # PSE anova sub <- data["sub"] exp <- data["exp"] # timeBin <- data["timeBin"] prob <- data["prob"] measure <- data["PSE"] dataAnova <- data.frame(sub, prob, exp, measure) dataAnova$prob <- as.factor(dataAnova$prob) dataAnova$sub <- as.factor(dataAnova$sub) dataAnova$exp <- as.factor(dataAnova$exp) # dataAnova$timeBin <- as.factor(dataAnova$timeBin) colnames(dataAnova)[4] <- "measure" # dataAnova <- aggregate(perceptualErrorMean ~ sub * rotationSpeed * exp, # data = dataTemp, FUN = "mean") anovaData <- ezANOVA(dataAnova, dv = .(measure), wid = .(sub), within = .(prob, exp), type = 3, return_aov = TRUE, detailed = TRUE) # print(anovaData) aovEffectSize(anovaData, 'pes') # Equivalence test for the differences of PSE between experiments dataE <- data.frame(matrix(ncol=3,nrow=dim(subAll)[1], dimnames=list(NULL, c("sub", "exp1", "exp2")))) for (subN in 1:subTotalN) { data150 <- dataAnova[which(sub==subAll[subN, 1] & exp==1 & prob==50), ]$measure data190 <- dataAnova[which(sub==subAll[subN, 1] & exp==1 & prob==90), ]$measure data250 <- dataAnova[which(sub==subAll[subN, 1] & exp!=1 & prob==50), ]$measure data290 <- dataAnova[which(sub==subAll[subN, 1] & exp!=1 & prob==90), ]$measure dataE["sub"][subN, 1] <- subN dataE["exp1"][subN, 1] <- data190-data150 dataE["exp2"][subN, 1] <- data290-data250 } show(dataE) dataTOSTpaired(data = dataE, pairs = list((c(i1="exp1",i2="exp2"))), low_eqbound = -0.36, high_eqbound = 0.36, eqbound_type = "d", alpha = 0.05, desc = TRUE, plots = TRUE) # # compute Bayes Factor inclusion... # bf <- anovaBF(measure ~ prob + timeBin + prob*timeBin + sub, data = dataAnova, # whichRandom="sub") # bayesfactor_inclusion(bf, match_models = TRUE) # p <- ggplot(dataAnova, aes(x = prob, y = measure, color = exp)) + # stat_summary(aes(y = measure), fun.y = mean, geom = "point", shape = 95, size = 15) + # stat_summary(fun.data = 'mean_sdl', # fun.args = list(mult = 1.96/sqrt(subTotalN)), # geom = 'errorbar', width = .1) + # # geom = 'smooth', se = 'TRUE') + # # stat_summary(aes(y = measure), fun.data = mean_se, geom = "errorbar", width = 0.1) + # geom_point(aes(x = prob, y = measure), size = dotSize, shape = 1) + # # geom_segment(aes_all(c('x', 'y', 'xend', 'yend')), data = data.frame(x = c(50, 40), xend = c(90, 40), y = c(-0.1, -0.1), yend = c(-0.1, 0.15)), size = axisLineWidth) + # scale_y_continuous(name = "Anticipatory pursuit velocity (°/s)") + #, limits = c(-0.1, 0.55), expand = c(0, 0)) + # # scale_y_continuous(name = "PSE") + # scale_x_discrete(name = "Probability of rightward motion", breaks=c("50", "90")) + # # scale_x_discrete(name = "Probability of rightward motion", breaks=c(50, 70, 90)) + # # scale_colour_discrete(name = "After reversal\ndirection", labels = c("CCW", "CW")) + # theme(axis.text=element_text(colour="black"), # axis.ticks=element_line(colour="black", size = axisLineWidth), # panel.grid.major = element_blank(), # panel.grid.minor = element_blank(), # panel.border = element_blank(), # panel.background = element_blank(), # text = element_text(size = textSize, colour = "black"), # legend.background = element_rect(fill="transparent"), # legend.key = element_rect(colour = "transparent", fill = "white")) # # facet_wrap(~exp) # print(p) # ggsave(paste(plotFolder, pdfFileName, sep = "")) # ## t-test of the simple main effect of probability in the control experiment # dataD <- dataAnova[dataAnova$exp==3,] # # show(dataD) # res <- pairwise.t.test.with.t.and.df(x = dataD$measure, g = dataD$prob, paired = TRUE, p.adj="none") # show(res) # [[3]] = p value table, un adjusted # res[[5]] # t-value # res[[6]] # dfs # res[[3]] # p.adjust(res[[3]], method = "bonferroni", n = 4) # cohensd <- cohensD(subset(dataD, prob==50)$measure, subset(dataD, prob==90)$measure, method = 'paired') # show(cohensd) ## interaction plot dataPlot <- data.frame(sub, prob, exp, measure) colnames(dataPlot)[4] <- "measure" dataPlot$sub <- as.factor(dataPlot$sub) # dataPlot$prob <- as.factor(dataPlot$prob) # is.numeric(dataPlot$timeBin) dataPlot$exp <- as.factor(dataPlot$exp) # dataPlot <- aggregate(measure ~ exp+prob, data = dataPlot, FUN = "mean") # show(dataPlot) # # for time bin plots # p <- ggplot(dataPlot, aes(x = timeBin, y = measure, color = prob)) + # stat_summary(fun.y = mean, geom = "point", shape = 95, size = 17.5) + # stat_summary(fun.y = mean, geom = "line", width = 1) + # stat_summary(fun.data = 'mean_sdl', fun.args = list(mult = 1.96/sqrt(subTotalN)), geom = 'errorbar', width = 1.5, size = 1) + # scale_x_continuous(name = "time bin of trials", breaks=c(1, 2), limits = c(0.5, 2.5), expand = c(0, 0)) + p <- ggplot(dataPlot, aes(x = prob, y = measure, color = exp)) + stat_summary(fun.y = mean, geom = "point", shape = 95, size = 17.5) + stat_summary(fun.y = mean, geom = "line", width = 1) + stat_summary(fun.data = 'mean_sdl', fun.args = list(mult = 1.96/sqrt(subTotalN)), geom = 'errorbar', width = 1.5, size = 1) + stat_summary(aes(y = measure), fun.data = mean_se, geom = "errorbar", width = 0.1) + # geom_point(aes(x = prob, y = measure), size = dotSize, shape = 1) + geom_segment(aes_all(c('x', 'y', 'xend', 'yend')), data = data.frame(x = c(50, 45), y = c(ylimLow, ylimLow), xend = c(90, 45), yend = c(ylimLow, ylimHigh)), size = axisLineWidth, inherit.aes = FALSE) + # scale_y_continuous(name = "Anticipatory pursuit velocity (°/s)", breaks = seq(ylimLow, ylimHigh, 1), expand = c(0, 0)) + # scale_y_continuous(name = "Anticipatory pursuit velocity gain", breaks = seq(ylimLow, ylimHigh, 0.1), expand = c(0, 0)) + # coord_cartesian(ylim=c(ylimLow, ylimHigh)) + scale_y_continuous(name = "PSE", limits = c(ylimLow, ylimHigh), breaks = c(ylimLow, 0, ylimHigh), expand = c(0, 0)) + scale_x_continuous(name = "Probability of rightward motion", breaks=c(50, 90), limits = c(45, 95), expand = c(0, 0)) + # scale_x_discrete(name = "Probability of rightward motion", breaks=c("50", "90")) + # scale_colour_discrete(name = "After reversal\ndirection", labels = c("CCW", "CW")) + theme(axis.text=element_text(colour="black"), axis.ticks=element_line(colour="black", size = axisLineWidth), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank(), text = element_text(size = textSize, colour = "black"), legend.background = element_rect(fill="transparent"), legend.key = element_rect(colour = "transparent", fill = "white")) # facet_wrap(~exp) print(p) ggsave(paste(plotFolder, pdfInteractionFileName, sep = "")) # ## t-test of the difference # sub <- dataD["sub"] # exp <- dataD["exp"] # measure <- dataD["slopeDiff"] # dataDtemp <- data.frame(sub, exp, measure) # dataDtemp$sub <- as.factor(dataDtemp$sub) # dataDtemp$exp <- as.factor(dataDtemp$exp) # colnames(dataDtemp)[3] <- "measure" # # dataDttest <- aggregate(measure ~ exp, data = dataDtemp, FUN = "mean") # # res <- pairwise.t.test.with.t.and.df(x = dataDtemp$measure, g = dataDtemp$exp, paired = TRUE, p.adj="none") # # show(res) # [[3]] = p value table, un adjusted # # res[[5]] # t-value # # res[[6]] # dfs # # res[[3]] # # p.adjust(res[[3]], method = "bonferroni", n = 3) # # # bias in PSE # # ylimLow <- -0.05 # # ylimHigh <- 0.2 # # # bias in ASP # # ylimLow <- 0 # # ylimHigh <- 3 # # bias in slope # ylimLow <- -40 # ylimHigh <- 30 # p <- ggplot(dataDtemp, aes(x = exp, y = measure)) + # stat_summary(aes(y = measure), fun.y = mean, geom = "point", shape = 95, size = 15) + # stat_summary(fun.data = 'mean_sdl', # fun.args = list(mult = 1.96/sqrt(subTotalN)), # geom = 'linerange', size = 1) + # geom_line(aes(x = exp, y = measure, group = sub), size = 0.5, linetype = "dashed") + # geom_point(aes(x = exp, y = measure), size = dotSize, shape = 1) + # geom_segment(aes_all(c('x', 'y', 'xend', 'yend')), data = data.frame(x = c(0), y = c(ylimLow), xend = c(0), yend = c(ylimHigh)), size = axisLineWidth) + # # scale_y_continuous(name = "Bias of PSE") + #, limits = c(0, 0.15), expand = c(0, 0.01)) + # scale_y_continuous(name = "Bias of slope") + #, limits = c(0, 0.15), expand = c(0, 0.01)) + # # scale_y_continuous(name = "Bias of anticipatory pursuit velocity(deg/s)") + #, limits = c(0, 0.15), expand = c(0, 0.01)) + # scale_x_discrete(name = "Experiment", limits = c("1", "3"), labels = c("1" = "Exp1", "3" = "Exp3")) + # # scale_x_discrete(name = "Experiment", limits = c("1", "2"), labels = c("1" = "Exp1", "2" = "Exp2")) + # theme(axis.text=element_text(colour="black"), # axis.ticks=element_line(colour="black", size = axisLineWidth), # panel.grid.major = element_blank(), # panel.grid.minor = element_blank(), # panel.border = element_blank(), # panel.background = element_blank(), # text = element_text(size = textSize, colour = "black"), # legend.background = element_rect(fill="transparent"), # legend.key = element_rect(colour = "transparent", fill = "white")) # # facet_wrap(~prob) # print(p) # ggsave(paste(plotFolder, pdfFileNameD, sep = ""))
tabPanel( title = tagList( icon("globe-asia"), i18n$t("感染状況マップ") ), fluidRow( column( width = 5, tags$div( fluidRow( column( width = 6, switchInput( inputId = "switchMapVersion", value = T, onLabel = i18n$t("シンプル"), onStatus = "danger", offStatus = "danger", offLabel = i18n$t("詳細"), label = i18n$t("表示モード"), inline = T, size = "small", width = "300px", labelWidth = "200px", handleWidth = "100px" ), ), column( width = 6, tags$span( dropdownButton( tags$h4(i18n$t("表示設定")), materialSwitch( inputId = "showPopupOnMap", label = i18n$t("日次増加数のポップアップ"), status = "danger", value = T ), materialSwitch( inputId = "replyMapLoop", label = i18n$t("ループ再生"), status = "danger", value = T ), dateRangeInput( inputId = "mapDateRange", label = i18n$t("表示日付"), start = byDate$date[nrow(byDate) - 15], end = byDate$date[nrow(byDate)], min = byDate$date[1], max = byDate$date[nrow(byDate)], separator = " ~ ", language = "ja" ), sliderInput( inputId = "mapFrameSpeed", label = i18n$t("再生速度(秒/日)"), min = 0.5, max = 3, step = 0.1, value = 0.8 ), circle = F, inline = T, status = "danger", icon = icon("gear"), size = "sm", width = "300px", tooltip = tooltipOptions(title = i18n$t("表示設定"), placement = "top") ), style = "float:right;" ) ), ), style = "margin-top:10px;" ), uiOutput("comfirmedMapWrapper") %>% withSpinner(proxy.height = "550px"), # TODO もし全部の都道府県に感染者報告がある場合、こちらのバーを再検討する progressBar( id = "activePatients", value = TOTAL_JAPAN - DEATH_JAPAN - 40 - sum(mhlwSummary[日付 == max(日付)]$退院者), total = TOTAL_JAPAN - DEATH_JAPAN - 40, title = tagList( icon("procedures"), i18n$t("現在患者数") ), striped = T, status = "danger", display_pct = T ), bsTooltip( id = "activePatients", placement = "top", title = i18n$t("分母には死亡者、チャーター便で帰国したクルーズ船の乗客40名は含まれていません。") ), tagList(icon("shield-alt"), tags$b(i18n$t("感染者報告なし"))), uiOutput("saveArea"), ), column( width = 7, boxPad( fluidRow( column( width = 9, radioGroupButtons( inputId = "switchTableVersion", label = NULL, justified = T, choiceNames = c( paste(icon("procedures"), i18n$t("感染")), paste(icon("vials"), i18n$t("検査")), paste(icon("hospital"), i18n$t("回復・死亡")) ), choiceValues = c("confirmed", "test", "discharged"), status = "danger" ) ), column( width = 3, tags$span( awesomeCheckbox( inputId = "tableShowSetting", label = i18n$t("グルーピング表示"), status = "danger", value = T ), style = "float:right;" ) ) ), uiOutput("summaryTable") %>% withSpinner() ) ) ) )
/03_Components/Main/ConfirmedMap.ui.R
permissive
peppy/2019-ncov-japan
R
false
false
4,329
r
tabPanel( title = tagList( icon("globe-asia"), i18n$t("感染状況マップ") ), fluidRow( column( width = 5, tags$div( fluidRow( column( width = 6, switchInput( inputId = "switchMapVersion", value = T, onLabel = i18n$t("シンプル"), onStatus = "danger", offStatus = "danger", offLabel = i18n$t("詳細"), label = i18n$t("表示モード"), inline = T, size = "small", width = "300px", labelWidth = "200px", handleWidth = "100px" ), ), column( width = 6, tags$span( dropdownButton( tags$h4(i18n$t("表示設定")), materialSwitch( inputId = "showPopupOnMap", label = i18n$t("日次増加数のポップアップ"), status = "danger", value = T ), materialSwitch( inputId = "replyMapLoop", label = i18n$t("ループ再生"), status = "danger", value = T ), dateRangeInput( inputId = "mapDateRange", label = i18n$t("表示日付"), start = byDate$date[nrow(byDate) - 15], end = byDate$date[nrow(byDate)], min = byDate$date[1], max = byDate$date[nrow(byDate)], separator = " ~ ", language = "ja" ), sliderInput( inputId = "mapFrameSpeed", label = i18n$t("再生速度(秒/日)"), min = 0.5, max = 3, step = 0.1, value = 0.8 ), circle = F, inline = T, status = "danger", icon = icon("gear"), size = "sm", width = "300px", tooltip = tooltipOptions(title = i18n$t("表示設定"), placement = "top") ), style = "float:right;" ) ), ), style = "margin-top:10px;" ), uiOutput("comfirmedMapWrapper") %>% withSpinner(proxy.height = "550px"), # TODO もし全部の都道府県に感染者報告がある場合、こちらのバーを再検討する progressBar( id = "activePatients", value = TOTAL_JAPAN - DEATH_JAPAN - 40 - sum(mhlwSummary[日付 == max(日付)]$退院者), total = TOTAL_JAPAN - DEATH_JAPAN - 40, title = tagList( icon("procedures"), i18n$t("現在患者数") ), striped = T, status = "danger", display_pct = T ), bsTooltip( id = "activePatients", placement = "top", title = i18n$t("分母には死亡者、チャーター便で帰国したクルーズ船の乗客40名は含まれていません。") ), tagList(icon("shield-alt"), tags$b(i18n$t("感染者報告なし"))), uiOutput("saveArea"), ), column( width = 7, boxPad( fluidRow( column( width = 9, radioGroupButtons( inputId = "switchTableVersion", label = NULL, justified = T, choiceNames = c( paste(icon("procedures"), i18n$t("感染")), paste(icon("vials"), i18n$t("検査")), paste(icon("hospital"), i18n$t("回復・死亡")) ), choiceValues = c("confirmed", "test", "discharged"), status = "danger" ) ), column( width = 3, tags$span( awesomeCheckbox( inputId = "tableShowSetting", label = i18n$t("グルーピング表示"), status = "danger", value = T ), style = "float:right;" ) ) ), uiOutput("summaryTable") %>% withSpinner() ) ) ) )
fileile <- "household_power_consumption.txt" data <- read.table(file, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") subdata <- data[data$Date %in% c("1/2/2007","2/2/2007") ,] plot1 <- as.numeric(subdata$Global_active_power) png("plot1.png", width=480, height=480) hist(plot1, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)")
/plot1.r
no_license
mikeauld74/ExData_Plotting1
R
false
false
370
r
fileile <- "household_power_consumption.txt" data <- read.table(file, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") subdata <- data[data$Date %in% c("1/2/2007","2/2/2007") ,] plot1 <- as.numeric(subdata$Global_active_power) png("plot1.png", width=480, height=480) hist(plot1, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)")
#Load Source File #-the source file is a .RData file where all the functions and codes are preloaded place<-getwd() source("/home/tcrnerc/Scratch/models/incubator/SpatialModel.R") #load ABM load("/home/tcrnerc/Scratch/models/incubator/sweep1.RData") #load sweep setwd(place)#Load Source File #This allows the definition of arguments (this allows the definition of the random seeds as an input argument) Args<-as.numeric(commandArgs(TRUE)) NewArgs=c(45,7282,7941,7971,8681,8714,9435,9436); Args=NewArgs[Args] set.seed(Args) number.sim.per.job = 3 #Subset sweep for current run thissweep<-as.data.frame(paramsweep[((Args-1)*number.sim.per.job+1):(Args*number.sim.per.job),]) resultMean<-numeric() #place holder for containing results resultMedian<-numeric() #place holder for containing results #Simulation loop for (x in 1:number.sim.per.job) { print(x) result<-sim(mat=matrixGenerator(randomPoints(1000),k=thissweep$k[x]), z=thissweep$z[x],mu=thissweep$mu[x],sigma=thissweep$sigma[x], timeSteps=1000,verbose=TRUE,mode="model") resultMean[x]=result[1] resultMedian[x]=result[2] } #When the computation is done, create the name of the RData as the name of the calling code... thissweep$Mean=resultMean thissweep$Median=resultMedian name<-paste("./res",Args,".csv",sep="") write.csv(thissweep,file=name)
/submitLegion/completeRuns/submit_model1ext.R
no_license
ercrema/culturalincubators
R
false
false
1,340
r
#Load Source File #-the source file is a .RData file where all the functions and codes are preloaded place<-getwd() source("/home/tcrnerc/Scratch/models/incubator/SpatialModel.R") #load ABM load("/home/tcrnerc/Scratch/models/incubator/sweep1.RData") #load sweep setwd(place)#Load Source File #This allows the definition of arguments (this allows the definition of the random seeds as an input argument) Args<-as.numeric(commandArgs(TRUE)) NewArgs=c(45,7282,7941,7971,8681,8714,9435,9436); Args=NewArgs[Args] set.seed(Args) number.sim.per.job = 3 #Subset sweep for current run thissweep<-as.data.frame(paramsweep[((Args-1)*number.sim.per.job+1):(Args*number.sim.per.job),]) resultMean<-numeric() #place holder for containing results resultMedian<-numeric() #place holder for containing results #Simulation loop for (x in 1:number.sim.per.job) { print(x) result<-sim(mat=matrixGenerator(randomPoints(1000),k=thissweep$k[x]), z=thissweep$z[x],mu=thissweep$mu[x],sigma=thissweep$sigma[x], timeSteps=1000,verbose=TRUE,mode="model") resultMean[x]=result[1] resultMedian[x]=result[2] } #When the computation is done, create the name of the RData as the name of the calling code... thissweep$Mean=resultMean thissweep$Median=resultMedian name<-paste("./res",Args,".csv",sep="") write.csv(thissweep,file=name)
#' @param infile Path to the input file #' @param header T (Default) or F #' @return A matrix of the infile #' @export load_ped <- function(infile, header = TRUE){ ## read file as a matrix ## in.dt <- data.table::fread(infile, header = header) ## conduct checks ## #- check column names nameVec = c('IID', 'sample', 'FID', 'family', 'PID', 'father', 'DID', 'MID', 'mother', 'mom', 'sex', 'gender', 'phenotype', 'phen', 'pheno' ,'trait') nameVec = toupper(nameVec) colnames(in.dt) = toupper(colnames(in.dt)) if(!any(colnames(in.dt) %in% nameVec)) stop(name.rules()) colnames(in.dt)[which(colnames(in.dt) %in% c("IID", "SAMPLE"))] <- 'IID' colnames(in.dt)[which(colnames(in.dt) %in% c("FID", 'FAMILY'))] <- 'FID' colnames(in.dt)[which(colnames(in.dt) %in% c("PID", "FATHER", 'DID', 'PID'))] <- 'PID' colnames(in.dt)[which(colnames(in.dt) %in% c("MID", "MOTHER", "MOM"))] <- 'MID' colnames(in.dt)[which(colnames(in.dt) %in% c("SEX", "GENDER"))] <- 'SEX' colnames(in.dt)[which(colnames(in.dt) %in% c("PHENOTYPE", "PHEN", "PHENO", "TRAIT"))] <- 'PHEN' #- check for duplicated column names if (length(unique(colnames(in.dt))) < length(colnames(in.dt))) stop(col.duplicated()) #- check if there's duplicated IDs if (length(unique(paste0(in.dt$IID,'-', in.dt$FID))) < length(paste0(in.dt$IID, '-', in.dt$FID))) stop(id.duplicatd()) ## functions ## name.rules <- function(){ writeLines("Column names should be as listed (not case-sensitive): Sample can be 'IID', 'sample' Family can be 'FID', 'family' Father can be 'PID', 'dad', 'DID', 'father' Mother can be 'MID', 'mother', 'mom' Sex can be 'sex', 'gender' Phenotype can be 'phenotype', 'phen','pheno' , 'trait'" ) } value.rules <- function(){ writeLines("Columns can contain the following values (not case-sensitive): Males as 'M', 'male', 1 Females as 'F', 'female', 2 Unknown as NA, -9, 'unk'") } col.duplicated <- function(){ writeLines('Your table has duplicated column names') } id.duplicated <- function(){ writeLines('You have multiple samples within a family with the same ID') } in.dt }
/R/load_ped.R
no_license
kopalgarg/gwas-vis
R
false
false
2,361
r
#' @param infile Path to the input file #' @param header T (Default) or F #' @return A matrix of the infile #' @export load_ped <- function(infile, header = TRUE){ ## read file as a matrix ## in.dt <- data.table::fread(infile, header = header) ## conduct checks ## #- check column names nameVec = c('IID', 'sample', 'FID', 'family', 'PID', 'father', 'DID', 'MID', 'mother', 'mom', 'sex', 'gender', 'phenotype', 'phen', 'pheno' ,'trait') nameVec = toupper(nameVec) colnames(in.dt) = toupper(colnames(in.dt)) if(!any(colnames(in.dt) %in% nameVec)) stop(name.rules()) colnames(in.dt)[which(colnames(in.dt) %in% c("IID", "SAMPLE"))] <- 'IID' colnames(in.dt)[which(colnames(in.dt) %in% c("FID", 'FAMILY'))] <- 'FID' colnames(in.dt)[which(colnames(in.dt) %in% c("PID", "FATHER", 'DID', 'PID'))] <- 'PID' colnames(in.dt)[which(colnames(in.dt) %in% c("MID", "MOTHER", "MOM"))] <- 'MID' colnames(in.dt)[which(colnames(in.dt) %in% c("SEX", "GENDER"))] <- 'SEX' colnames(in.dt)[which(colnames(in.dt) %in% c("PHENOTYPE", "PHEN", "PHENO", "TRAIT"))] <- 'PHEN' #- check for duplicated column names if (length(unique(colnames(in.dt))) < length(colnames(in.dt))) stop(col.duplicated()) #- check if there's duplicated IDs if (length(unique(paste0(in.dt$IID,'-', in.dt$FID))) < length(paste0(in.dt$IID, '-', in.dt$FID))) stop(id.duplicatd()) ## functions ## name.rules <- function(){ writeLines("Column names should be as listed (not case-sensitive): Sample can be 'IID', 'sample' Family can be 'FID', 'family' Father can be 'PID', 'dad', 'DID', 'father' Mother can be 'MID', 'mother', 'mom' Sex can be 'sex', 'gender' Phenotype can be 'phenotype', 'phen','pheno' , 'trait'" ) } value.rules <- function(){ writeLines("Columns can contain the following values (not case-sensitive): Males as 'M', 'male', 1 Females as 'F', 'female', 2 Unknown as NA, -9, 'unk'") } col.duplicated <- function(){ writeLines('Your table has duplicated column names') } id.duplicated <- function(){ writeLines('You have multiple samples within a family with the same ID') } in.dt }
\name{grasp.cormat} \alias{grasp.cormat} \title{GRASP-R correlations map and matrix} \description{Calculates correlation between PVs and plots a matrix of correlation} \usage{grasp.cormat(gr.Yi, cols, thin = 1)} \arguments{ \item{gr.Yi}{Selected responses to be used in the form of a vector with column numbers} \item{cols}{Selected predictors to be used in the form of a vector with column numbers} \item{thin}{Leave 1} } \details{ This function calculates correlation between PVs and plots a matrix of correlation. It is a visual check. Too highly correlated PVs have to be eliminated manually, after checking. } \author{ Fabien Fivaz \email{fabien.fivaz@bluewin.ch}. Ported to R from GRASP \url{http://www.cscf.ch/grasp/} for S-Plus written by A. Lehmann, J.R. Leathwich and J. McC Overton. Look at \url{http://www.cscf.ch/grasp} for details and update. } \seealso{ \code{\link{grasp.histo}}, \code{\link{grasp.datamap}}, \code{\link{grasp.RvsP}} and \code{\link{grasp.corlim}} } \keyword{models} \keyword{smooth} \keyword{regression} \keyword{plot}
/man/grasp.cormat.Rd
no_license
cran/grasper
R
false
false
1,087
rd
\name{grasp.cormat} \alias{grasp.cormat} \title{GRASP-R correlations map and matrix} \description{Calculates correlation between PVs and plots a matrix of correlation} \usage{grasp.cormat(gr.Yi, cols, thin = 1)} \arguments{ \item{gr.Yi}{Selected responses to be used in the form of a vector with column numbers} \item{cols}{Selected predictors to be used in the form of a vector with column numbers} \item{thin}{Leave 1} } \details{ This function calculates correlation between PVs and plots a matrix of correlation. It is a visual check. Too highly correlated PVs have to be eliminated manually, after checking. } \author{ Fabien Fivaz \email{fabien.fivaz@bluewin.ch}. Ported to R from GRASP \url{http://www.cscf.ch/grasp/} for S-Plus written by A. Lehmann, J.R. Leathwich and J. McC Overton. Look at \url{http://www.cscf.ch/grasp} for details and update. } \seealso{ \code{\link{grasp.histo}}, \code{\link{grasp.datamap}}, \code{\link{grasp.RvsP}} and \code{\link{grasp.corlim}} } \keyword{models} \keyword{smooth} \keyword{regression} \keyword{plot}
source("shared.R") rankall <- function(outcome, num = "best") { ranked <- rankedByState(outcome = outcome) ## For each state, find the hospital of the given rank ## Return a data frame with the hospital names and the ## (abbreviated) state name byState <- split(ranked, ranked$state) if (num == "best") idx <- 1 else if (num == "worst") idx <- nrow(byState[[1]]) else idx <- num result <- data.frame(byState[[1]][idx,]) for(i in 2:length(byState)) { if (num == "worst") idx <- nrow(byState[[i]]) state <- byState[[i]][idx,] if (!is.na(state$state)) { result <- rbind(result, state) } } allStates <- levels(byState[[1]]$state) resultStates <- result$state naStates <- setdiff(allStates, resultStates) for(nas in naStates) { r <- data.frame(name=NA, state=nas, score=NaN) result <- rbind(result, r) } result[with(result, order(state, name, na.last = TRUE)),][,c(1,2)] }
/rankall.R
no_license
paulCrsr/RProgrammingAssignment3
R
false
false
1,192
r
source("shared.R") rankall <- function(outcome, num = "best") { ranked <- rankedByState(outcome = outcome) ## For each state, find the hospital of the given rank ## Return a data frame with the hospital names and the ## (abbreviated) state name byState <- split(ranked, ranked$state) if (num == "best") idx <- 1 else if (num == "worst") idx <- nrow(byState[[1]]) else idx <- num result <- data.frame(byState[[1]][idx,]) for(i in 2:length(byState)) { if (num == "worst") idx <- nrow(byState[[i]]) state <- byState[[i]][idx,] if (!is.na(state$state)) { result <- rbind(result, state) } } allStates <- levels(byState[[1]]$state) resultStates <- result$state naStates <- setdiff(allStates, resultStates) for(nas in naStates) { r <- data.frame(name=NA, state=nas, score=NaN) result <- rbind(result, r) } result[with(result, order(state, name, na.last = TRUE)),][,c(1,2)] }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/functions_other.R \name{getRhat} \alias{getRhat} \title{Get rhat} \usage{ getRhat(stan_fit, parameters) } \arguments{ \item{stan_fit}{Output of stan} \item{parameters}{Parameter names to extract} } \description{ Get rhat }
/man/getRhat.Rd
no_license
wjoycezhao/hddmRstan
R
false
true
302
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/functions_other.R \name{getRhat} \alias{getRhat} \title{Get rhat} \usage{ getRhat(stan_fit, parameters) } \arguments{ \item{stan_fit}{Output of stan} \item{parameters}{Parameter names to extract} } \description{ Get rhat }
# # vim:set ff=unix expandtab ts=2 sw=2: ################################################################# writeGenericFunctionRdFiles <- function(path,docs,nsi){ gens<-nsi[["gens_defined_by_package"]] funNamesToDocument <-names(gens) #funNamesToDocument <-names(nsi[["documentableMeths"]]) # note that ls will not find S4 methods for generic functions # these are treated elsewhere list0 <- fixPackageFileNames(funNamesToDocument) names(list0) <- funNamesToDocument sapply( funNamesToDocument, function(item) { docs_i<-docs[[item]] if (!is.null(docs_i)){ fn <- file.path(path, paste(list0[[item]],".Rd",sep="")) #fff<-getGeneric(item,where=e) fff<-gens[[item]] fdo=genericFunctionDocObject(name=item,l=docs_i,functionObject=fff) write_Rd_file(fdo,fn) }else{ # there are two possibilities warning(sprintf("## mm ## No documentation found for item:%s.",item)) } } ) }
/pkg/R/deprecated/writeGenericFunctionRdFiles.R
no_license
mamueller/linkeddocs
R
false
false
995
r
# # vim:set ff=unix expandtab ts=2 sw=2: ################################################################# writeGenericFunctionRdFiles <- function(path,docs,nsi){ gens<-nsi[["gens_defined_by_package"]] funNamesToDocument <-names(gens) #funNamesToDocument <-names(nsi[["documentableMeths"]]) # note that ls will not find S4 methods for generic functions # these are treated elsewhere list0 <- fixPackageFileNames(funNamesToDocument) names(list0) <- funNamesToDocument sapply( funNamesToDocument, function(item) { docs_i<-docs[[item]] if (!is.null(docs_i)){ fn <- file.path(path, paste(list0[[item]],".Rd",sep="")) #fff<-getGeneric(item,where=e) fff<-gens[[item]] fdo=genericFunctionDocObject(name=item,l=docs_i,functionObject=fff) write_Rd_file(fdo,fn) }else{ # there are two possibilities warning(sprintf("## mm ## No documentation found for item:%s.",item)) } } ) }
setwd("D:/FAIMS/20180822_DI2A/") ############### PEPTIDE LEVEL FDRs ## 3 dalton isolation, 60k OT resolution mso60k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR ## 3 dalton isolation, 15k OT resolution mso15k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR ## p8 dalton isolation, 60k OT resolution mso60kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_60k.txt") ## < 1% FDR ## p8 dalton isolation, 15k OT resolution mso15kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_15k.txt") ## < 1% FDR #### 30k resolution ## 3 mz isolation mso30k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR ## 0.8 mz isolation mso30kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_30k.txt") ## < 1% FDR #### 50k resolution ## 3 mz isolation mso50k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR ## 0.8 mz isolation mso50kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_50k.txt") ## < 1% FDR ### PRECURSOR TOLERANCES # 60k, 3mz iso mso60k3i_1p20f<-peplvlfdr(msplitresults="mso1p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_1p5p20f<-peplvlfdr(msplitresults="mso1p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_2p20f<-peplvlfdr(msplitresults="mso2p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_2p5p20f<-peplvlfdr(msplitresults="mso2p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3.50f<-peplvlfdr(msplitresults="mso3p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_420f<-peplvlfdr(msplitresults="mso4p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_4.5p20f<-peplvlfdr(msplitresults="mso4p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_5p20f<-peplvlfdr(msplitresults="mso5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i<-peplvlfdr(msplitresults="mso7p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i<-peplvlfdr(msplitresults="mso5p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR # 60k, 0.8 mz iso mso60k<-peplvlfdr(msplitresults="mso1p2p20f_DIA2_OT_60k.txt") ## < 1% FDR mso60k<-peplvlfdr(msplitresults="mso1p6p20f_DIA2_OT_60k.txt") ## < 1% FDR mso60k<-peplvlfdr(msplitresults="mso2p4p20f_DIA2_OT_60k.txt") ## < 1% FDR # 50k, 3mz iso mso50k3i<-peplvlfdr(msplitresults="mso3p5_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso0p0_20f_DIA2_OT_50k_3i1o_1.txt") ## 5.0 typo mso50k3i<-peplvlfdr(msplitresults="mso6p5_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR # repeat 3 more mso50k3i<-peplvlfdr(msplitresults="mso5p5p_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso6p0p_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso7p0p_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso4p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso4p5p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso5p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso5p5p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso6p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR ######################################################33 #############3 NO FAIMS ############################################################# mso15k3mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_3p_20f_noFAIMS_OT_15k_3i1o_1.txt") ## < 1% FDR mso30k3mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_3p_20f_noFAIMS_OT_30k_3i1o_1.txt") mso15kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_15k_p8ip4o_1.txt") ## < 1% FDR mso30kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_30k_p8ip4o_1.txt") ## < 1% FDR mso50kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_50k_p8ip4o_1.txt") ## < 1% FDR mso60kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_60k_p8ip4o_1.txt") ## < 1% FDR mso60kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180822_DI2A/mso0p8p_500f_DIA2_ITp8_30m_p1f.txt") msoitp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180822_DI2A/mso0p8p_500f_DIA2_ITp8.txt")
/explore_searchparams_DI2A.R
no_license
jgmeyerucsd/pRoteomics
R
false
false
7,554
r
setwd("D:/FAIMS/20180822_DI2A/") ############### PEPTIDE LEVEL FDRs ## 3 dalton isolation, 60k OT resolution mso60k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR ## 3 dalton isolation, 15k OT resolution mso15k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR mso15k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_15k_3i1o_1.txt") ## < 1% FDR ## p8 dalton isolation, 60k OT resolution mso60kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_60k.txt") ## < 1% FDR mso60kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_60k.txt") ## < 1% FDR ## p8 dalton isolation, 15k OT resolution mso15kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_15k.txt") ## < 1% FDR mso15kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_15k.txt") ## < 1% FDR #### 30k resolution ## 3 mz isolation mso30k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR mso30k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_30k_3i1o_1.txt") ## < 1% FDR ## 0.8 mz isolation mso30kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_30k.txt") ## < 1% FDR mso30kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_30k.txt") ## < 1% FDR #### 50k resolution ## 3 mz isolation mso50k3i_3p10f<-peplvlfdr(msplitresults="mso3p10f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p20f<-peplvlfdr(msplitresults="mso3p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p30f<-peplvlfdr(msplitresults="mso3p30f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p40f<-peplvlfdr(msplitresults="mso3p40f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p50f<-peplvlfdr(msplitresults="mso3p50f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i_3p60f<-peplvlfdr(msplitresults="mso3p60f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR ## 0.8 mz isolation mso50kp8i_p8p10f<-peplvlfdr(msplitresults="msop8p10f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p20f<-peplvlfdr(msplitresults="msop8p20f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p30f<-peplvlfdr(msplitresults="msop8p30f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p40f<-peplvlfdr(msplitresults="msop8p40f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p50f<-peplvlfdr(msplitresults="msop8p50f_DIA2_OT_50k.txt") ## < 1% FDR mso50kp8i_p8p60f<-peplvlfdr(msplitresults="msop8p60f_DIA2_OT_50k.txt") ## < 1% FDR ### PRECURSOR TOLERANCES # 60k, 3mz iso mso60k3i_1p20f<-peplvlfdr(msplitresults="mso1p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_1p5p20f<-peplvlfdr(msplitresults="mso1p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_2p20f<-peplvlfdr(msplitresults="mso2p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_2p5p20f<-peplvlfdr(msplitresults="mso2p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_3.50f<-peplvlfdr(msplitresults="mso3p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_420f<-peplvlfdr(msplitresults="mso4p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_4.5p20f<-peplvlfdr(msplitresults="mso4p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i_5p20f<-peplvlfdr(msplitresults="mso5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i<-peplvlfdr(msplitresults="mso7p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR mso60k3i<-peplvlfdr(msplitresults="mso5p5p20f_DIA2_OT_60k_3i1o_1.txt") ## < 1% FDR # 60k, 0.8 mz iso mso60k<-peplvlfdr(msplitresults="mso1p2p20f_DIA2_OT_60k.txt") ## < 1% FDR mso60k<-peplvlfdr(msplitresults="mso1p6p20f_DIA2_OT_60k.txt") ## < 1% FDR mso60k<-peplvlfdr(msplitresults="mso2p4p20f_DIA2_OT_60k.txt") ## < 1% FDR # 50k, 3mz iso mso50k3i<-peplvlfdr(msplitresults="mso3p5_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso0p0_20f_DIA2_OT_50k_3i1o_1.txt") ## 5.0 typo mso50k3i<-peplvlfdr(msplitresults="mso6p5_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR # repeat 3 more mso50k3i<-peplvlfdr(msplitresults="mso5p5p_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso6p0p_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso7p0p_20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso4p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso4p5p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso5p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso5p5p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR mso50k3i<-peplvlfdr(msplitresults="mso6p20f_DIA2_OT_50k_3i1o_1.txt") ## < 1% FDR ######################################################33 #############3 NO FAIMS ############################################################# mso15k3mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_3p_20f_noFAIMS_OT_15k_3i1o_1.txt") ## < 1% FDR mso30k3mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_3p_20f_noFAIMS_OT_30k_3i1o_1.txt") mso15kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_15k_p8ip4o_1.txt") ## < 1% FDR mso30kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_30k_p8ip4o_1.txt") ## < 1% FDR mso50kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_50k_p8ip4o_1.txt") ## < 1% FDR mso60kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180823_noFAIMS/mso_0p8p_20f_noFAIMS_OT_60k_p8ip4o_1.txt") ## < 1% FDR mso60kp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180822_DI2A/mso0p8p_500f_DIA2_ITp8_30m_p1f.txt") msoitp8mz<-peplvlfdr(msplitresults="D:/FAIMS/20180822_DI2A/mso0p8p_500f_DIA2_ITp8.txt")
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Script to auto-generate BigQuery schema and clean the data for BigQuery import. library(reshape) library(plyr) library(dplyr) library(testthat) dataDir <- './' #---------------------------------------------------------------------------- # Load Demographic Data demo <- read.csv(file.path(dataDir, 'PGPParticipantSurvey-20140506220023.csv'), stringsAsFactors=FALSE, na.strings=c('NA', 'N/A', 'No response', 'null', '')) expect_equal(nrow(demo), 2627) expect_equal(ncol(demo), 52) # Substitute whitespace and punctuation for underscores colnames(demo) <- gsub('\\W+', '_', colnames(demo)) # Trim trailing underscores colnames(demo) <- gsub('_+$', '', colnames(demo)) # PGP participants have filled out the surveys multiple times expect_less_than(length(unique(demo$Participant)), nrow(demo)) # Drop a few columns drops <- c('Do_not_touch', 'Do_you_have_a_severe_genetic_disease_or_rare_genetic_trait_If_so_you_can_add_a_description_for_your_public_profile', 'Disease_trait_Documentation_description') demo <- demo[,!(names(demo) %in% drops)] # Convert Timestamp column to dates demo$Timestamp <- strptime(as.character(demo$Timestamp), '%m/%d/%Y %H:%M:%S') demo$Timestamp <- as.POSIXct(demo$Timestamp) # Filter, keeping only most recent survey per participant recentDemo <- demo %.% group_by(Participant) %.% arrange(desc(Timestamp)) %.% filter(row_number(Participant) == 1) expect_equal(length(unique(demo$Participant)), nrow(recentDemo)) # Spot check the data expect_equal(recentDemo[recentDemo$Participant == 'huD554DB',]$Timestamp, as.POSIXct('2014-02-07 12:20:52 PST')) #---------------------------------------------------------------------------- # Load Phenotypic Trait Data files <- c( 'PGPTrait&DiseaseSurvey2012-Blood-20140506220045.csv', 'PGPTrait&DiseaseSurvey2012-Cancers-20140506220037.csv', 'PGPTrait&DiseaseSurvey2012-CirculatorySystem-20140506220056.csv', 'PGPTrait&DiseaseSurvey2012-CongenitalTraitsAndAnomalies-20140506220117.csv', 'PGPTrait&DiseaseSurvey2012-DigestiveSystem-20140506220103.csv', 'PGPTrait&DiseaseSurvey2012-Endocrine,Metabolic,Nutritional,AndImmunity-20140506220041.csv', 'PGPTrait&DiseaseSurvey2012-GenitourinarySystems-20140506220107.csv', 'PGPTrait&DiseaseSurvey2012-MusculoskeletalSystemAndConnectiveTissue-20140506220114.csv', 'PGPTrait&DiseaseSurvey2012-NervousSystem-20140506220048.csv', 'PGPTrait&DiseaseSurvey2012-RespiratorySystem-20140506220059.csv', 'PGPTrait&DiseaseSurvey2012-SkinAndSubcutaneousTissue-20140506220111.csv', 'PGPTrait&DiseaseSurvey2012-VisionAndHearing-20140506220052.csv' ) traits <- lapply(files, function(file) { data <- read.csv(file.path(dataDir, file), stringsAsFactors=FALSE, na.strings=c('NA', 'N/A', 'No response', 'null', '')) print(paste('file:', file, 'nrow:', nrow(data), 'ncol:', ncol(data))) expect_equal(ncol(data), 5) # This column name differs between the surveys but its the same data. Update # the column name so that we can join all this data together. if('Have.you.ever.been.diagnosed.with.one.of.the.following.conditions.' == colnames(data)[4]) { colnames(data)[4] <- 'Have.you.ever.been.diagnosed.with.any.of.the.following.conditions.' } expect_equal(colnames(data), c('Participant', 'Timestamp', 'Do.not.touch.', 'Have.you.ever.been.diagnosed.with.any.of.the.following.conditions.', 'Other.condition.not.listed.here.')) # PGP participants have filled out the surveys multiple times expect_less_than(length(unique(data$Participant)), nrow(data)) data }) trait <- do.call(rbind, traits) expect_equal(ncol(trait), 5) expect_equal(nrow(trait), sum(unlist(lapply(traits, nrow)))) # Convert Timestamp column to dates trait$Timestamp <- strptime(as.character(trait$Timestamp), '%m/%d/%Y %H:%M:%S') trait$Timestamp <- as.POSIXct(trait$Timestamp) trait <- arrange(trait, desc(Timestamp)) # Reshape the trait data such that conditions are individual columns. longTrait <- ddply(trait, .(Participant), function(data) { conditions <- unlist(strsplit(c(as.character(data$Have.you.ever.been.diagnosed.with.any.of.the.following.conditions.)), ',')) # Trim leading and trailing whitespace and punctuation conditions <- gsub('^\\W+', '', conditions) conditions <- gsub('\\W+$', '', conditions) # Substitute whitespace and punctuation for underscores conditions <- gsub('\\W+', '_', conditions) data.frame(Participant = rep(unique(data$Participant), length(conditions)), Timestamp = rep(unique(data$Timestamp), length(conditions)), conditions = conditions) }) longTrait <- cbind(longTrait, has=rep(TRUE, nrow(longTrait))) wideTrait <- reshape(longTrait, idvar = 'Participant', timevar='conditions', v.names='has', direction = 'wide') expect_equal(length(unique(wideTrait$Participant)), nrow(wideTrait)) # Substitute whitespace and punctuation for underscores colnames(wideTrait) <- gsub('\\W$', '', colnames(wideTrait)) colnames(wideTrait) <- gsub('\\W+', '_', colnames(wideTrait)) # Spot check our data to verify that it was reshaped correctly. expect_true(wideTrait[wideTrait$Participant=='hu005023', 'has_Dental_cavities']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Gastroesophageal_reflux_disease_GERD'])) expect_true(wideTrait[wideTrait$Participant=='hu005023', 'has_Impacted_tooth']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Skin_tags'])) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Hair_loss_includes_female_and_male_pattern_baldness'])) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Acne'])) expect_true(wideTrait[wideTrait$Participant=='hu005023', 'has_Allergic_contact_dermatitis']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Dental_cavities']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Gastroesophageal_reflux_disease_GERD']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Impacted_tooth']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu627574', 'has_Skin_tags'])) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Hair_loss_includes_female_and_male_pattern_baldness']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Acne']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu627574', 'has_Allergic_contact_dermatitis'])) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Dental_cavities']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Gastroesophageal_reflux_disease_GERD'])) expect_true(is.na(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Impacted_tooth'])) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Skin_tags']) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Hair_loss_includes_female_and_male_pattern_baldness']) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Acne']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Allergic_contact_dermatitis'])) #---------------------------------------------------------------------------- # Some participants only filled out trait surveys, others only filled out the # participant survey expect_false(setequal(recentDemo$Participant, intersect(wideTrait$Participant, recentDemo$Participant))) expect_false(setequal(wideTrait$Participant, intersect(wideTrait$Participant, recentDemo$Participant))) # JOIN it all together, dropping the Timestamp columns pheno <- join(recentDemo[,-2], wideTrait[,-2], type='full') expect_equal(nrow(pheno), length(union(wideTrait$Participant, recentDemo$Participant))) # Generate BQ Schema cols <- colnames(pheno) bool_ints <- c(0, 1, NA) schema <- c() for (i in 1:length(cols)) { type <- 'STRING' if ('logical' == class(pheno[, i])) { type <- 'BOOLEAN' } else if ('numeric' == class(pheno[, i])) { type <- 'FLOAT' } else if ('integer' == class(pheno[, i])) { if (setequal(bool_ints, union(bool_ints, pheno[, i]))) { type <- 'BOOLEAN' } else { type <- 'INTEGER' } } schema <- append(schema, paste(cols[i], type, sep=":", collapse=",")) } print(paste(schema, collapse=',')) # Write out file to load into BigQuery write.table(pheno, file.path(dataDir, 'pgp-phenotypes.tsv'), row.names=FALSE, sep='\t', na='')
/pgp/provenance/phenotype-prep.R
permissive
deflaux/bigquery-examples
R
false
false
9,276
r
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Script to auto-generate BigQuery schema and clean the data for BigQuery import. library(reshape) library(plyr) library(dplyr) library(testthat) dataDir <- './' #---------------------------------------------------------------------------- # Load Demographic Data demo <- read.csv(file.path(dataDir, 'PGPParticipantSurvey-20140506220023.csv'), stringsAsFactors=FALSE, na.strings=c('NA', 'N/A', 'No response', 'null', '')) expect_equal(nrow(demo), 2627) expect_equal(ncol(demo), 52) # Substitute whitespace and punctuation for underscores colnames(demo) <- gsub('\\W+', '_', colnames(demo)) # Trim trailing underscores colnames(demo) <- gsub('_+$', '', colnames(demo)) # PGP participants have filled out the surveys multiple times expect_less_than(length(unique(demo$Participant)), nrow(demo)) # Drop a few columns drops <- c('Do_not_touch', 'Do_you_have_a_severe_genetic_disease_or_rare_genetic_trait_If_so_you_can_add_a_description_for_your_public_profile', 'Disease_trait_Documentation_description') demo <- demo[,!(names(demo) %in% drops)] # Convert Timestamp column to dates demo$Timestamp <- strptime(as.character(demo$Timestamp), '%m/%d/%Y %H:%M:%S') demo$Timestamp <- as.POSIXct(demo$Timestamp) # Filter, keeping only most recent survey per participant recentDemo <- demo %.% group_by(Participant) %.% arrange(desc(Timestamp)) %.% filter(row_number(Participant) == 1) expect_equal(length(unique(demo$Participant)), nrow(recentDemo)) # Spot check the data expect_equal(recentDemo[recentDemo$Participant == 'huD554DB',]$Timestamp, as.POSIXct('2014-02-07 12:20:52 PST')) #---------------------------------------------------------------------------- # Load Phenotypic Trait Data files <- c( 'PGPTrait&DiseaseSurvey2012-Blood-20140506220045.csv', 'PGPTrait&DiseaseSurvey2012-Cancers-20140506220037.csv', 'PGPTrait&DiseaseSurvey2012-CirculatorySystem-20140506220056.csv', 'PGPTrait&DiseaseSurvey2012-CongenitalTraitsAndAnomalies-20140506220117.csv', 'PGPTrait&DiseaseSurvey2012-DigestiveSystem-20140506220103.csv', 'PGPTrait&DiseaseSurvey2012-Endocrine,Metabolic,Nutritional,AndImmunity-20140506220041.csv', 'PGPTrait&DiseaseSurvey2012-GenitourinarySystems-20140506220107.csv', 'PGPTrait&DiseaseSurvey2012-MusculoskeletalSystemAndConnectiveTissue-20140506220114.csv', 'PGPTrait&DiseaseSurvey2012-NervousSystem-20140506220048.csv', 'PGPTrait&DiseaseSurvey2012-RespiratorySystem-20140506220059.csv', 'PGPTrait&DiseaseSurvey2012-SkinAndSubcutaneousTissue-20140506220111.csv', 'PGPTrait&DiseaseSurvey2012-VisionAndHearing-20140506220052.csv' ) traits <- lapply(files, function(file) { data <- read.csv(file.path(dataDir, file), stringsAsFactors=FALSE, na.strings=c('NA', 'N/A', 'No response', 'null', '')) print(paste('file:', file, 'nrow:', nrow(data), 'ncol:', ncol(data))) expect_equal(ncol(data), 5) # This column name differs between the surveys but its the same data. Update # the column name so that we can join all this data together. if('Have.you.ever.been.diagnosed.with.one.of.the.following.conditions.' == colnames(data)[4]) { colnames(data)[4] <- 'Have.you.ever.been.diagnosed.with.any.of.the.following.conditions.' } expect_equal(colnames(data), c('Participant', 'Timestamp', 'Do.not.touch.', 'Have.you.ever.been.diagnosed.with.any.of.the.following.conditions.', 'Other.condition.not.listed.here.')) # PGP participants have filled out the surveys multiple times expect_less_than(length(unique(data$Participant)), nrow(data)) data }) trait <- do.call(rbind, traits) expect_equal(ncol(trait), 5) expect_equal(nrow(trait), sum(unlist(lapply(traits, nrow)))) # Convert Timestamp column to dates trait$Timestamp <- strptime(as.character(trait$Timestamp), '%m/%d/%Y %H:%M:%S') trait$Timestamp <- as.POSIXct(trait$Timestamp) trait <- arrange(trait, desc(Timestamp)) # Reshape the trait data such that conditions are individual columns. longTrait <- ddply(trait, .(Participant), function(data) { conditions <- unlist(strsplit(c(as.character(data$Have.you.ever.been.diagnosed.with.any.of.the.following.conditions.)), ',')) # Trim leading and trailing whitespace and punctuation conditions <- gsub('^\\W+', '', conditions) conditions <- gsub('\\W+$', '', conditions) # Substitute whitespace and punctuation for underscores conditions <- gsub('\\W+', '_', conditions) data.frame(Participant = rep(unique(data$Participant), length(conditions)), Timestamp = rep(unique(data$Timestamp), length(conditions)), conditions = conditions) }) longTrait <- cbind(longTrait, has=rep(TRUE, nrow(longTrait))) wideTrait <- reshape(longTrait, idvar = 'Participant', timevar='conditions', v.names='has', direction = 'wide') expect_equal(length(unique(wideTrait$Participant)), nrow(wideTrait)) # Substitute whitespace and punctuation for underscores colnames(wideTrait) <- gsub('\\W$', '', colnames(wideTrait)) colnames(wideTrait) <- gsub('\\W+', '_', colnames(wideTrait)) # Spot check our data to verify that it was reshaped correctly. expect_true(wideTrait[wideTrait$Participant=='hu005023', 'has_Dental_cavities']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Gastroesophageal_reflux_disease_GERD'])) expect_true(wideTrait[wideTrait$Participant=='hu005023', 'has_Impacted_tooth']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Skin_tags'])) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Hair_loss_includes_female_and_male_pattern_baldness'])) expect_true(is.na(wideTrait[wideTrait$Participant=='hu005023', 'has_Acne'])) expect_true(wideTrait[wideTrait$Participant=='hu005023', 'has_Allergic_contact_dermatitis']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Dental_cavities']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Gastroesophageal_reflux_disease_GERD']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Impacted_tooth']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu627574', 'has_Skin_tags'])) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Hair_loss_includes_female_and_male_pattern_baldness']) expect_true(wideTrait[wideTrait$Participant=='hu627574', 'has_Acne']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu627574', 'has_Allergic_contact_dermatitis'])) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Dental_cavities']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Gastroesophageal_reflux_disease_GERD'])) expect_true(is.na(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Impacted_tooth'])) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Skin_tags']) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Hair_loss_includes_female_and_male_pattern_baldness']) expect_true(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Acne']) expect_true(is.na(wideTrait[wideTrait$Participant=='hu8E2A35', 'has_Allergic_contact_dermatitis'])) #---------------------------------------------------------------------------- # Some participants only filled out trait surveys, others only filled out the # participant survey expect_false(setequal(recentDemo$Participant, intersect(wideTrait$Participant, recentDemo$Participant))) expect_false(setequal(wideTrait$Participant, intersect(wideTrait$Participant, recentDemo$Participant))) # JOIN it all together, dropping the Timestamp columns pheno <- join(recentDemo[,-2], wideTrait[,-2], type='full') expect_equal(nrow(pheno), length(union(wideTrait$Participant, recentDemo$Participant))) # Generate BQ Schema cols <- colnames(pheno) bool_ints <- c(0, 1, NA) schema <- c() for (i in 1:length(cols)) { type <- 'STRING' if ('logical' == class(pheno[, i])) { type <- 'BOOLEAN' } else if ('numeric' == class(pheno[, i])) { type <- 'FLOAT' } else if ('integer' == class(pheno[, i])) { if (setequal(bool_ints, union(bool_ints, pheno[, i]))) { type <- 'BOOLEAN' } else { type <- 'INTEGER' } } schema <- append(schema, paste(cols[i], type, sep=":", collapse=",")) } print(paste(schema, collapse=',')) # Write out file to load into BigQuery write.table(pheno, file.path(dataDir, 'pgp-phenotypes.tsv'), row.names=FALSE, sep='\t', na='')
#Answer 2 NEI2<-NEI[NEI$fips=="24510",] ans2<-sapply(split(NEI2, NEI2$year),function(k) sum(k$Emissions)) png('plot2a.png', width=480, height=480) barplot(ans2, xlab="years", ylab="PM2.5 Emission", main="Total PM2.5 Emission across years for Baltimore City ") dev.off()
/plot2.R
no_license
adityatare/Exploratory-Data-Analysis2
R
false
false
278
r
#Answer 2 NEI2<-NEI[NEI$fips=="24510",] ans2<-sapply(split(NEI2, NEI2$year),function(k) sum(k$Emissions)) png('plot2a.png', width=480, height=480) barplot(ans2, xlab="years", ylab="PM2.5 Emission", main="Total PM2.5 Emission across years for Baltimore City ") dev.off()
## these functions will cache the inverse of a matrix by 1) storing the ## value of the inverse and 2) calculates the inverse of the matrix using the first function ## this function creates a special matrix object and stores 1) the matrix ad 2) the inverse of the matrix makeCacheMatrix <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y i <<- NULL } get <- function() x setInverse <- function(inverse) i <<- inverse getInverse <- function() i list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## this function calculates the inverse using the above function - first it checks to see ## if the mean has already been calculated and if not completes the calculation cacheSolve <- function(x, ...) { i <- x$getInverse() if(!is.null(i)) { message("getting cached data") return(i) } data <- x$get() i <- solve(data, ...) x$setInverse(i) i ## return a matrix that is the inverse of x }
/cachematrix.R
no_license
jmoss13148/ProgrammingAssignment2
R
false
false
1,019
r
## these functions will cache the inverse of a matrix by 1) storing the ## value of the inverse and 2) calculates the inverse of the matrix using the first function ## this function creates a special matrix object and stores 1) the matrix ad 2) the inverse of the matrix makeCacheMatrix <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y i <<- NULL } get <- function() x setInverse <- function(inverse) i <<- inverse getInverse <- function() i list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## this function calculates the inverse using the above function - first it checks to see ## if the mean has already been calculated and if not completes the calculation cacheSolve <- function(x, ...) { i <- x$getInverse() if(!is.null(i)) { message("getting cached data") return(i) } data <- x$get() i <- solve(data, ...) x$setInverse(i) i ## return a matrix that is the inverse of x }
\name{circos.genomicDensity} \alias{circos.genomicDensity} \title{ Calculate and add genomic density track } \description{ Calculate and add genomic density track } \usage{ circos.genomicDensity( data, ylim.force = FALSE, window.size = NULL, overlap = TRUE, col = ifelse(area, "grey", "black"), lwd = par("lwd"), lty = par("lty"), type = "l", area = TRUE, area.baseline = NULL, baseline = 0, border = NA, ...) } \arguments{ \item{data}{A bed-file-like data frame or a list of data frames } \item{ylim.force}{Whether to force upper bound of \code{ylim} to be 1. } \item{window.size}{Pass to \code{\link{genomicDensity}} } \item{overlap}{Pass to \code{\link{genomicDensity}} } \item{col}{Colors. It should be length of one. If \code{data} is a list of data frames, the length of \code{col} can also be the length of the list. } \item{lwd}{Width of lines } \item{lty}{Style of lines } \item{type}{Type of lines, see \code{\link{circos.lines}} } \item{area}{See \code{\link{circos.lines}} } \item{area.baseline}{Deprecated, use \code{baseline} instead. } \item{baseline}{See \code{\link{circos.lines}} } \item{border}{See \code{\link{circos.lines}} } \item{...}{Pass to \code{\link{circos.trackPlotRegion}} } } \details{ This function is a high-level graphical function, and it will create a new track. } \seealso{ \url{https://jokergoo.github.io/circlize_book/book/high-level-genomic-functions.html#genomic-density-and-rainfall-plot} } \examples{ load(system.file(package = "circlize", "extdata", "DMR.RData")) # rainfall circos.initializeWithIdeogram(plotType = c("axis", "labels")) bed_list = list(DMR_hyper, DMR_hypo) circos.genomicRainfall(bed_list, pch = 16, cex = 0.4, col = c("#FF000080", "#0000FF80")) circos.genomicDensity(bed_list[[1]], col = c("#FF000080"), track.height = 0.1) circos.genomicDensity(bed_list[[2]], col = c("#0000FF80"), track.height = 0.1) circos.clear() }
/man/circos.genomicDensity.Rd
permissive
Amz965/circlize
R
false
false
1,970
rd
\name{circos.genomicDensity} \alias{circos.genomicDensity} \title{ Calculate and add genomic density track } \description{ Calculate and add genomic density track } \usage{ circos.genomicDensity( data, ylim.force = FALSE, window.size = NULL, overlap = TRUE, col = ifelse(area, "grey", "black"), lwd = par("lwd"), lty = par("lty"), type = "l", area = TRUE, area.baseline = NULL, baseline = 0, border = NA, ...) } \arguments{ \item{data}{A bed-file-like data frame or a list of data frames } \item{ylim.force}{Whether to force upper bound of \code{ylim} to be 1. } \item{window.size}{Pass to \code{\link{genomicDensity}} } \item{overlap}{Pass to \code{\link{genomicDensity}} } \item{col}{Colors. It should be length of one. If \code{data} is a list of data frames, the length of \code{col} can also be the length of the list. } \item{lwd}{Width of lines } \item{lty}{Style of lines } \item{type}{Type of lines, see \code{\link{circos.lines}} } \item{area}{See \code{\link{circos.lines}} } \item{area.baseline}{Deprecated, use \code{baseline} instead. } \item{baseline}{See \code{\link{circos.lines}} } \item{border}{See \code{\link{circos.lines}} } \item{...}{Pass to \code{\link{circos.trackPlotRegion}} } } \details{ This function is a high-level graphical function, and it will create a new track. } \seealso{ \url{https://jokergoo.github.io/circlize_book/book/high-level-genomic-functions.html#genomic-density-and-rainfall-plot} } \examples{ load(system.file(package = "circlize", "extdata", "DMR.RData")) # rainfall circos.initializeWithIdeogram(plotType = c("axis", "labels")) bed_list = list(DMR_hyper, DMR_hypo) circos.genomicRainfall(bed_list, pch = 16, cex = 0.4, col = c("#FF000080", "#0000FF80")) circos.genomicDensity(bed_list[[1]], col = c("#FF000080"), track.height = 0.1) circos.genomicDensity(bed_list[[2]], col = c("#0000FF80"), track.height = 0.1) circos.clear() }
`rclust` <- function(dist, clusters = 2, runs = 1000, counter = FALSE) { if (runs == 1) return(relational.clustering(dist, clusters)) else { rc2return <- NULL rc2 <- sum(dist) for (i in 1:runs) { npart <- relational.clustering(dist, clusters) if (i%%10==0 && counter==TRUE) print(paste('Calculating run number ',i,sep='')) if (length(npart) == 1) { next(i) } nd <- as.matrix(dist) n<-dim(nd)[1] nd[upper.tri(nd, diag = TRUE)] <- 0 outer <- NULL inner <- NULL inout <- matrix(0,n,n) for (i in 1:(n-1)) { for (j in (i+1):n) { if (npart[i] != npart[j]) inout[j,i] <- 1 } } sumin <- sum(nd[which(inout==0)]) sumn<-sum(1:(n-1)) np <- sumin/(sumn-sum(inout)) if (np < rc2) { rc2return <- npart rc2 <- np } } } return(rc2return) }
/fossil/R/rclust.R
no_license
ingted/R-Examples
R
false
false
907
r
`rclust` <- function(dist, clusters = 2, runs = 1000, counter = FALSE) { if (runs == 1) return(relational.clustering(dist, clusters)) else { rc2return <- NULL rc2 <- sum(dist) for (i in 1:runs) { npart <- relational.clustering(dist, clusters) if (i%%10==0 && counter==TRUE) print(paste('Calculating run number ',i,sep='')) if (length(npart) == 1) { next(i) } nd <- as.matrix(dist) n<-dim(nd)[1] nd[upper.tri(nd, diag = TRUE)] <- 0 outer <- NULL inner <- NULL inout <- matrix(0,n,n) for (i in 1:(n-1)) { for (j in (i+1):n) { if (npart[i] != npart[j]) inout[j,i] <- 1 } } sumin <- sum(nd[which(inout==0)]) sumn<-sum(1:(n-1)) np <- sumin/(sumn-sum(inout)) if (np < rc2) { rc2return <- npart rc2 <- np } } } return(rc2return) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_theme.R \name{plot_theme} \alias{plot_theme} \title{Plot Theme} \usage{ plot_theme(fontFamily = "Purisa", titleFont = 26) } \arguments{ \item{fontFamily}{A character string that defines the font family to be used for the axis / title / legend etc.} } \description{ Holds the theme for the plots to be used in the README }
/man/plot_theme.Rd
no_license
O1sims/FootballStats
R
false
true
406
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_theme.R \name{plot_theme} \alias{plot_theme} \title{Plot Theme} \usage{ plot_theme(fontFamily = "Purisa", titleFont = 26) } \arguments{ \item{fontFamily}{A character string that defines the font family to be used for the axis / title / legend etc.} } \description{ Holds the theme for the plots to be used in the README }
options(repos = c(cran = 'https://cran.rstudio.com')) ## local library for project-specific packages dir.create('.Rlib', showWarnings = FALSE, recursive = TRUE) .libPaths(new = '.Rlib') print("working in power-analyses repo")
/.Rprofile
no_license
jburos/power-analyses
R
false
false
226
rprofile
options(repos = c(cran = 'https://cran.rstudio.com')) ## local library for project-specific packages dir.create('.Rlib', showWarnings = FALSE, recursive = TRUE) .libPaths(new = '.Rlib') print("working in power-analyses repo")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Rsamplers.R \name{mvtnormSelectionProbs} \alias{mvtnormSelectionProbs} \title{A function for computing the probability of positive/negative selections} \usage{ mvtnormSelectionProbs(y, mu, sigma, threshold, selected = NULL) } \arguments{ \item{y}{the observed normal vector, or an initial sample point that satisfies the selection event} \item{mu}{the mean vector of the (untruncated) normal vector} \item{sigma}{the covariance of the (untruncated) normal vector} \item{threshold}{a vector of size length(y), the selection threshold} \item{selected}{which coordinates were selected? if NULL function will attempt to figure it out on its own but my fail if there are both observations that are larger than \code{threshold} and observations that are smaller than \code{-threshold}.} } \description{ This function uses the mvtnorm package to compute the probability of positive and negative selection events of selective ROI problems. The selection event is assumed to be, {selected > threshold} or {selected < -threshold} (with coordinates which were not selected not satisfying the selection event) }
/man/mvtnormSelectionProbs.Rd
no_license
ammeir2/selectiveROI
R
false
true
1,182
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Rsamplers.R \name{mvtnormSelectionProbs} \alias{mvtnormSelectionProbs} \title{A function for computing the probability of positive/negative selections} \usage{ mvtnormSelectionProbs(y, mu, sigma, threshold, selected = NULL) } \arguments{ \item{y}{the observed normal vector, or an initial sample point that satisfies the selection event} \item{mu}{the mean vector of the (untruncated) normal vector} \item{sigma}{the covariance of the (untruncated) normal vector} \item{threshold}{a vector of size length(y), the selection threshold} \item{selected}{which coordinates were selected? if NULL function will attempt to figure it out on its own but my fail if there are both observations that are larger than \code{threshold} and observations that are smaller than \code{-threshold}.} } \description{ This function uses the mvtnorm package to compute the probability of positive and negative selection events of selective ROI problems. The selection event is assumed to be, {selected > threshold} or {selected < -threshold} (with coordinates which were not selected not satisfying the selection event) }
\name{metaSub.character} \alias{as.filename} \alias{as.filename.character} \alias{metaSub.filename} \alias{metaSub.character} \alias{metaSub} \title{Create Replicate Text files with Systematic Substitutions} \description{ \code{metaSub} is generic. A method is defined for character; a convenience wrapper is provided for passing names of text files to be read and then resampled. \code{metaSub} collapses a character vector to one line of text. The vector is replicated as many times as there are elements in \code{names}, with flexible substitution of text fragments. If \code{out} is supplied, the replicates are saved as text files identified with \code{names} and a \code{suffix}. \code{metaSub.filename} will process multiple filenames, if \code{x} is as long as \code{names}. } \usage{ \method{as.filename}{character}(x, ...) \method{metaSub}{filename}(x, names, pattern=NULL, replacement=NULL, ...) \method{metaSub}{character}( x, names, pattern = NULL, replacement = NULL, out = NULL, suffix = '.txt', fixed = TRUE, ... ) } \arguments{ \item{x}{scalar character, or (second form) filename(s). Multi-element character will be collapsed to one element, with newline as the separator.} \item{names}{a list of (unique) names for resulting output elements. A vector of names will be coerced to character and to list.} \item{pattern}{a character vector of text fragments to replace, optionally encoded as regular expressions (\code{fixed==FALSE}, See \code{?gsub}, \code{?regex}). Can also be a list. See details.} \item{replacement}{A character vector of substitutions for patterns. The wildcard \sQuote{*} is available to represent the corresponding value of \code{names}. Can also be a list with as many elements as \code{pattern} (see details). Expressions are supported (see details).} \item{out}{(path and) directory in which to write the resulting control streams} \item{suffix}{file extension for filenames, if \code{out} is supplied} \item{fixed}{passed to \code{gsub}: use \code{FALSE} if \code{pattern} contains regular expressions. Scalar, or same length as \code{pattern}.} \item{\dots}{extra arguments, available to expressions or passed to \code{gsub}} } \details{ Typical usages are \preformatted{ metaSub(x, names, ...) metaSub(as.filename(x), names, ...) } Replacement is performed by \code{gsub}, so an element of \code{pattern} will be replaced everywhere it occurs in a line. if \code{pattern} or \code{replacement} is a list, each element should be of length one, or as long as \code{names}. In the latter case, substitutions can be specific on a per-name basis. The wild card \sQuote{*} is still available. It is necessary that \code{pattern} and \code{replacement} be of the same length, but it is not necessary that their corresponding elements have equal lengths. Thus, one can specify name-specific replacements for a single pattern, or a single replacement for name-specific patterns. An expression can be specified for \code{replacement} itself, or one of its pattern-wise elements, or one of the name-wise elements of a pattern-wise element. Expressions are evaluated in an environment containing \dQuote{name} (same meaning as \sQuote{*} above) and all other \dots arguments. This is useful if extra arguments have a dimension indexed, at least loosely, by \code{names}. The evaluated expression is treated as character, and wildcard substitution is attempted. Use \code{\*} for a literal asterisk: in R: \code{\\\\*}. NOTE: be very careful not to have trailing commas in your lists! An error results that is very hard to track. e.g. \code{c(a,b,c,)}. } \value{ an invisible named character vector. If \code{out} is supplied, elements are written as files with corresponding names. } \references{\url{http://mifuns.googlecode.com}} \author{Tim Bergsma} \seealso{ \itemize{ \item \code{\link{gsub}} \item \code{\link{regex}} } } \examples{ data(ctl) dir() e <- metaSub( ctl, names=1:3, pattern=c( 'PROBLEM 8', 'data8.csv', '8.MSF' ), replacement=c( 'PROBLEM *', '*.csv', '*.MSF' ), out='.', suffix='.ctl' ) t <- metaSub( ctl, names=c('test1','test2'), pattern=c('PROBLEM 8','data8.csv','METH=0'), replacement=c('PROBLEM *','*.csv','METH=1'), ) t <- metaSub( ctl, names=c('test1','test2'), pattern=c( 'PROBLEM 8', 'data8.csv', 'METH=0' ), replacement=list( 'PROBLEM *', '*.csv', c('METH=1','METH=2') ), out='.', suffix='.ctl' ) #just a file copy... metaSub(as.filename('1.ctl'),names='4',out='.',suffix='.ctl') #using a (nonsense) replacement expression... options <- data.frame(var=c(8,9),alt=c(10,11)) a <- metaSub( ctl, names=rownames(options), pattern='9999', replacement=expression( options$var[rownames(options)==name] ), options=options ) cat(a[[2]]) #replacement expression in a 'mixed' list... b <- metaSub( ctl, names=rownames(options), pattern=list( 'PRINT=2', '9999' ), replacement=list( 'PRINT=3', expression(options$var[rownames(options)==name]) ), options=options ) cat(b[[2]]) #replacement expressions on a per-name basis d <- metaSub( ctl, names=rownames(options), pattern='9999', replacement=list( #so that replacement is as long as pattern list( #with different options for each 'name' expression(options$var[rownames(options)==name]), expression(options$alt[rownames(options)==name]) ) ), options=options ) cat(d[[2]]) } \keyword{manip}
/man/metaSub.character.Rd
no_license
cran/MIfuns
R
false
false
5,532
rd
\name{metaSub.character} \alias{as.filename} \alias{as.filename.character} \alias{metaSub.filename} \alias{metaSub.character} \alias{metaSub} \title{Create Replicate Text files with Systematic Substitutions} \description{ \code{metaSub} is generic. A method is defined for character; a convenience wrapper is provided for passing names of text files to be read and then resampled. \code{metaSub} collapses a character vector to one line of text. The vector is replicated as many times as there are elements in \code{names}, with flexible substitution of text fragments. If \code{out} is supplied, the replicates are saved as text files identified with \code{names} and a \code{suffix}. \code{metaSub.filename} will process multiple filenames, if \code{x} is as long as \code{names}. } \usage{ \method{as.filename}{character}(x, ...) \method{metaSub}{filename}(x, names, pattern=NULL, replacement=NULL, ...) \method{metaSub}{character}( x, names, pattern = NULL, replacement = NULL, out = NULL, suffix = '.txt', fixed = TRUE, ... ) } \arguments{ \item{x}{scalar character, or (second form) filename(s). Multi-element character will be collapsed to one element, with newline as the separator.} \item{names}{a list of (unique) names for resulting output elements. A vector of names will be coerced to character and to list.} \item{pattern}{a character vector of text fragments to replace, optionally encoded as regular expressions (\code{fixed==FALSE}, See \code{?gsub}, \code{?regex}). Can also be a list. See details.} \item{replacement}{A character vector of substitutions for patterns. The wildcard \sQuote{*} is available to represent the corresponding value of \code{names}. Can also be a list with as many elements as \code{pattern} (see details). Expressions are supported (see details).} \item{out}{(path and) directory in which to write the resulting control streams} \item{suffix}{file extension for filenames, if \code{out} is supplied} \item{fixed}{passed to \code{gsub}: use \code{FALSE} if \code{pattern} contains regular expressions. Scalar, or same length as \code{pattern}.} \item{\dots}{extra arguments, available to expressions or passed to \code{gsub}} } \details{ Typical usages are \preformatted{ metaSub(x, names, ...) metaSub(as.filename(x), names, ...) } Replacement is performed by \code{gsub}, so an element of \code{pattern} will be replaced everywhere it occurs in a line. if \code{pattern} or \code{replacement} is a list, each element should be of length one, or as long as \code{names}. In the latter case, substitutions can be specific on a per-name basis. The wild card \sQuote{*} is still available. It is necessary that \code{pattern} and \code{replacement} be of the same length, but it is not necessary that their corresponding elements have equal lengths. Thus, one can specify name-specific replacements for a single pattern, or a single replacement for name-specific patterns. An expression can be specified for \code{replacement} itself, or one of its pattern-wise elements, or one of the name-wise elements of a pattern-wise element. Expressions are evaluated in an environment containing \dQuote{name} (same meaning as \sQuote{*} above) and all other \dots arguments. This is useful if extra arguments have a dimension indexed, at least loosely, by \code{names}. The evaluated expression is treated as character, and wildcard substitution is attempted. Use \code{\*} for a literal asterisk: in R: \code{\\\\*}. NOTE: be very careful not to have trailing commas in your lists! An error results that is very hard to track. e.g. \code{c(a,b,c,)}. } \value{ an invisible named character vector. If \code{out} is supplied, elements are written as files with corresponding names. } \references{\url{http://mifuns.googlecode.com}} \author{Tim Bergsma} \seealso{ \itemize{ \item \code{\link{gsub}} \item \code{\link{regex}} } } \examples{ data(ctl) dir() e <- metaSub( ctl, names=1:3, pattern=c( 'PROBLEM 8', 'data8.csv', '8.MSF' ), replacement=c( 'PROBLEM *', '*.csv', '*.MSF' ), out='.', suffix='.ctl' ) t <- metaSub( ctl, names=c('test1','test2'), pattern=c('PROBLEM 8','data8.csv','METH=0'), replacement=c('PROBLEM *','*.csv','METH=1'), ) t <- metaSub( ctl, names=c('test1','test2'), pattern=c( 'PROBLEM 8', 'data8.csv', 'METH=0' ), replacement=list( 'PROBLEM *', '*.csv', c('METH=1','METH=2') ), out='.', suffix='.ctl' ) #just a file copy... metaSub(as.filename('1.ctl'),names='4',out='.',suffix='.ctl') #using a (nonsense) replacement expression... options <- data.frame(var=c(8,9),alt=c(10,11)) a <- metaSub( ctl, names=rownames(options), pattern='9999', replacement=expression( options$var[rownames(options)==name] ), options=options ) cat(a[[2]]) #replacement expression in a 'mixed' list... b <- metaSub( ctl, names=rownames(options), pattern=list( 'PRINT=2', '9999' ), replacement=list( 'PRINT=3', expression(options$var[rownames(options)==name]) ), options=options ) cat(b[[2]]) #replacement expressions on a per-name basis d <- metaSub( ctl, names=rownames(options), pattern='9999', replacement=list( #so that replacement is as long as pattern list( #with different options for each 'name' expression(options$var[rownames(options)==name]), expression(options$alt[rownames(options)==name]) ) ), options=options ) cat(d[[2]]) } \keyword{manip}
dataSetsPath <- "C:\\Users\\samarths\\Desktop\\newdata\\" require(e1071) svm.models <- list() parentTestSet <- read.csv(paste(dataSetsPath, "test_FS.csv", sep=''), header = TRUE) parentTrainingSet <- read.csv(paste(dataSetsPath, "train_FS.csv", sep=''), header=TRUE) parentTrainingSet <- parentTrainingSet[,-1] mergedSet <- rbind(parentTrainingSet, parentTestSet) # PCA on merged set. pca <- prcomp(mergedSet, scale = TRUE) # Find 95% threshold of cumulative variance proportion of the principal components. thresh <- max(which(cumsum(pca$sdev^2 / sum(pca$sdev^2)) <= 0.95)) # for each digit for (i in 0:9) { print(i) trainingSet <- read.csv(paste(dataSetsPath, "Train_FS_scaled\\", "trainFS-digit", i, ".csv", sep=''), header=TRUE) # Apply PCA to training set. train.pca <- predict(pca, trainingSet[,-ncol(trainingSet)]) # Train SVM model. model <- svm(train.pca[,1:thresh], as.factor(trainingSet[,ncol(trainingSet)]), probability = TRUE) # Add the SVM model to the list of models, one per digit. svm.models[[length(svm.models)+1]] <- model } testSet <- read.csv(paste(dataSetsPath, "test_FS.csv", sep=''), header = TRUE) # apply PCA to test set test.pca <- predict(pca, testSet) predictions <- matrix(nrow = nrow(testSet), ncol=0) # for each digit for (i in 0:9) { print(i) # Predictions from SVM for this digit. prediction <- predict(svm.models[[i+1]], test.pca[,1:thresh], probability = TRUE) # Store predicted probability for this digit. predictions <- cbind(predictions, attr(prediction, "probabilities")[,"1"]) } require(MASS) write.matrix(predictions, paste(dataSetsPath, "probabilities.csv", sep=''), sep=',')
/pca_merged_plus_svm/pcasvm.R
no_license
geramirez/digit-recognizer
R
false
false
1,665
r
dataSetsPath <- "C:\\Users\\samarths\\Desktop\\newdata\\" require(e1071) svm.models <- list() parentTestSet <- read.csv(paste(dataSetsPath, "test_FS.csv", sep=''), header = TRUE) parentTrainingSet <- read.csv(paste(dataSetsPath, "train_FS.csv", sep=''), header=TRUE) parentTrainingSet <- parentTrainingSet[,-1] mergedSet <- rbind(parentTrainingSet, parentTestSet) # PCA on merged set. pca <- prcomp(mergedSet, scale = TRUE) # Find 95% threshold of cumulative variance proportion of the principal components. thresh <- max(which(cumsum(pca$sdev^2 / sum(pca$sdev^2)) <= 0.95)) # for each digit for (i in 0:9) { print(i) trainingSet <- read.csv(paste(dataSetsPath, "Train_FS_scaled\\", "trainFS-digit", i, ".csv", sep=''), header=TRUE) # Apply PCA to training set. train.pca <- predict(pca, trainingSet[,-ncol(trainingSet)]) # Train SVM model. model <- svm(train.pca[,1:thresh], as.factor(trainingSet[,ncol(trainingSet)]), probability = TRUE) # Add the SVM model to the list of models, one per digit. svm.models[[length(svm.models)+1]] <- model } testSet <- read.csv(paste(dataSetsPath, "test_FS.csv", sep=''), header = TRUE) # apply PCA to test set test.pca <- predict(pca, testSet) predictions <- matrix(nrow = nrow(testSet), ncol=0) # for each digit for (i in 0:9) { print(i) # Predictions from SVM for this digit. prediction <- predict(svm.models[[i+1]], test.pca[,1:thresh], probability = TRUE) # Store predicted probability for this digit. predictions <- cbind(predictions, attr(prediction, "probabilities")[,"1"]) } require(MASS) write.matrix(predictions, paste(dataSetsPath, "probabilities.csv", sep=''), sep=',')
# TODO: Add comment # # Author: Ruth ############################################################################### mytheme <-theme_bw(base_size=10) + theme(plot.title = element_text(vjust=2), plot.margin=unit(c(0.08, 0.08, 0.0, 0.08),"cm"), axis.title.y = element_text(vjust=0.50), axis.line = element_line(colour = "grey6", linetype=1, size = 0.3), panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(strip.background = element_rect(fill = 'white')) colorList <- c("orangered2", "dodgerblue1") png("RuthSync/Thesis/Presentation/1_FeedingVsCond.png", width = 1000, height = 800, units = "px", res = 200) ggplot(subset(BoxComboMorn, IndFeed != "NA"), aes(x = residCond, y = IndFeedNum, color = Treatment, linecolor = Treatment)) + ylab("Individual fed?") + geom_point(aes(shape = Treatment), size = 1, position = position_jitter(width = 0.00, height = 0.03)) + stat_smooth(aes(color = Treatment), method="glm", method.args = list(family = "binomial"), se=FALSE, size = 1) + mytheme + xlab("Individual Condition") + scale_shape_manual(values = c(16, 18), name = "Prey Size") + scale_color_manual(values = colorList, name = "Prey Size") dev.off()
/EcuRCode/BoxTrials/ThesisPresentation/BoxTrialsGraphs.R
no_license
ruthubc/ruthubc
R
false
false
1,284
r
# TODO: Add comment # # Author: Ruth ############################################################################### mytheme <-theme_bw(base_size=10) + theme(plot.title = element_text(vjust=2), plot.margin=unit(c(0.08, 0.08, 0.0, 0.08),"cm"), axis.title.y = element_text(vjust=0.50), axis.line = element_line(colour = "grey6", linetype=1, size = 0.3), panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(strip.background = element_rect(fill = 'white')) colorList <- c("orangered2", "dodgerblue1") png("RuthSync/Thesis/Presentation/1_FeedingVsCond.png", width = 1000, height = 800, units = "px", res = 200) ggplot(subset(BoxComboMorn, IndFeed != "NA"), aes(x = residCond, y = IndFeedNum, color = Treatment, linecolor = Treatment)) + ylab("Individual fed?") + geom_point(aes(shape = Treatment), size = 1, position = position_jitter(width = 0.00, height = 0.03)) + stat_smooth(aes(color = Treatment), method="glm", method.args = list(family = "binomial"), se=FALSE, size = 1) + mytheme + xlab("Individual Condition") + scale_shape_manual(values = c(16, 18), name = "Prey Size") + scale_color_manual(values = colorList, name = "Prey Size") dev.off()
#' Number of dimensions. #' Number of dimensions of an array or vector #' #' @param x array #' @keywords internal dims <- function(x) length(amv_dim(x)) #' Dimensions. #' Consistent dimensions for vectors, matrices and arrays. #' #' @param x array, matrix or vector #' @keywords internal amv_dim <- function(x) if (is.vector(x)) length(x) else dim(x) #' Dimension names. #' Consistent dimnames for vectors, matrices and arrays. #' #' Unlike \code{\link{dimnames}} no part of the output will ever be #' null. If a component of dimnames is omitted, \code{amv_dimnames} #' will return an integer sequence of the appropriate length. #' #' @param x array, matrix or vector #' @keywords internal #' @export amv_dimnames <- function(x) { d <- if (is.vector(x)) list(names(x)) else dimnames(x) if (is.null(d)) d <- rep(list(NULL), dims(x)) null_names <- which(unlist(llply(d, is.null))) d[null_names] <- llply(null_names, function(i) seq.int(amv_dim(x)[i])) # if (is.null(names(d))) names(d) <- paste("X", 1:length(d), sep="") d } #' Reduce dimensions. #' Remove extraneous dimensions #' #' @param x array #' @keywords internal reduce_dim <- function(x) { do.call("[", c(list(x), lapply(dim(x), function(x) if (x==1) 1 else TRUE), drop=TRUE)) }
/R/dimensions.r
no_license
froh/plyr
R
false
false
1,273
r
#' Number of dimensions. #' Number of dimensions of an array or vector #' #' @param x array #' @keywords internal dims <- function(x) length(amv_dim(x)) #' Dimensions. #' Consistent dimensions for vectors, matrices and arrays. #' #' @param x array, matrix or vector #' @keywords internal amv_dim <- function(x) if (is.vector(x)) length(x) else dim(x) #' Dimension names. #' Consistent dimnames for vectors, matrices and arrays. #' #' Unlike \code{\link{dimnames}} no part of the output will ever be #' null. If a component of dimnames is omitted, \code{amv_dimnames} #' will return an integer sequence of the appropriate length. #' #' @param x array, matrix or vector #' @keywords internal #' @export amv_dimnames <- function(x) { d <- if (is.vector(x)) list(names(x)) else dimnames(x) if (is.null(d)) d <- rep(list(NULL), dims(x)) null_names <- which(unlist(llply(d, is.null))) d[null_names] <- llply(null_names, function(i) seq.int(amv_dim(x)[i])) # if (is.null(names(d))) names(d) <- paste("X", 1:length(d), sep="") d } #' Reduce dimensions. #' Remove extraneous dimensions #' #' @param x array #' @keywords internal reduce_dim <- function(x) { do.call("[", c(list(x), lapply(dim(x), function(x) if (x==1) 1 else TRUE), drop=TRUE)) }
library(lubridate) library(plyr) library(dplyr) rawattendance<-read.csv("attendance2018.csv") cleanattendance <- rawattendance %>% filter(Attendance.Location.Name=="Seymour Dual Language Academy")%>% mutate(Day=1)%>% mutate(Pres=ifelse(Attendance.Desc=="Present",1,0))%>% mutate(Abs=ifelse(Pres==0,1,0))%>% mutate(StudentName=paste(Student.Last.Nm,Student.First.Nm,sep=", "))%>% group_by(Student.Id,StudentName,Rptg.Race.Ethnicity.Desc,Has.Iep,Male) %>% summarise(TotalEnrolled=sum(Day),DaysPresent=sum(Pres),DaysAbsent=sum(Abs))%>% mutate(AttendancePercentage=DaysPresent/TotalEnrolled)%>% mutate(AttendancePercentage=(paste(round((AttendancePercentage)*100,digits=1),"%",sep="")))%>% rename(Race=Rptg.Race.Ethnicity.Desc,Gender=Male,IEP=Has.Iep)%>% select(Student.Id,StudentName,Race,Gender,IEP,TotalEnrolled,DaysPresent,AttendancePercentage) Demo<-rawattendance %>% filter(Attendance.Location.Name=="Seymour Dual Language Academy")%>% select(Student.Id,Student.Last.Nm,Student.First.Nm,Male,Rptg.Race.Ethnicity.Desc,Has.Iep)%>% mutate(StudentName=paste(Student.Last.Nm,Student.First.Nm,sep=",")) rawattendance$Percent<-as.numeric(rawattendance$'Period.Absence..'>.5) rawattendance$daycount = 1 rawattendance$Month<-month(rawattendance$cal_date) rawattendance$Month<-month.abb[rawattendance$Month] YTDdays<-as.data.frame(aggregate(daycount ~ STUDENT_ID, data=rawattendance, FUN=sum)) YTDabsent<-as.data.frame(aggregate(Absent ~ STUDENT_ID, data=rawattendance, FUN=sum)) YTD<-merge(YTDdays,YTDabsent,by="STUDENT_ID",all=TRUE) YTD$YTDAtt<-((YTD$daycount-YTD$Absent)/(YTD$daycount)) YTD$YTDAtt <- paste(round((YTD$YTDAtt)*100,digits=1),"%",sep="") YTD<-YTD[,c("STUDENT_ID","YTDAtt")] totaldays<-as.data.frame(aggregate(daycount ~ STUDENT_ID + Month, data=rawattendance, FUN=sum)) totalabsent<-as.data.frame(aggregate(Absent ~ STUDENT_ID + Month, data=rawattendance, FUN=sum)) together<-merge(totaldays,totalabsent, by=c("STUDENT_ID","Month"),all=TRUE) together$Percentage<-((together$daycount-together$Absent)/(together$daycount)) together$Percentage <- paste(round((together$Percentage)*100,digits=1),"%",sep="") together<-together[,c("STUDENT_ID","Month","Percentage")] togetherfinal<-reshape(together, idvar="STUDENT_ID", timevar="Month", direction="wide") togetherfinal<-rename(togetherfinal,DecAtt=Percentage.Dec, FebAtt=Percentage.Feb, JanAtt=Percentage.Jan, NovAtt=Percentage.Nov, OctAtt=Percentage.Oct, SepAtt=Percentage.Sep, MarAtt=Percentage.Mar, AprAtt=Percentage.Apr, MayAtt=Percentage.May, JuneAtt=Percentage.Jun) togetherfinal<-merge(togetherfinal,YTD,by="STUDENT_ID",all=TRUE) rawattendance<-togetherfinal[,c("STUDENT_ID","YTDAtt","SepAtt","OctAtt","NovAtt","DecAtt","JanAtt","FebAtt","MarAtt","AprAtt","MayAtt","JuneAtt")] ### STAR DATA #STAR Data #load all files FSM<-read.csv("Fall16SM_cleaned.csv") FSR<-read.csv("Fall16SR_cleaned.csv") FSEL<-read.csv("Fall16SEL_cleaned.csv") WSM<-read.csv("WinterSM_cleaned.csv") WSR<-read.csv("WinterSR_cleaned.csv") WSEL<-read.csv("WinterSEL_cleaned.csv") #cleaning STAR information FSEL<-FSEL[c("F16EL_StudentLocalID","F16EL_LiteracyClassification")] FSM<-FSM[c("F16Math_StudentLocalID","F16Math_GradeEquivalent")] FSR<-FSR[c("F16Read_StudentLocalID","F16Read_GradeEquivalent")] WSM<-WSM[c("Win16Math_StudentLocalID","Win16Math_GradeEquivalent")] WSR<-WSR[c("Win16Read_StudentLocalID","Win16Read_GradeEquivalent")] WSEL<-WSEL[c("Win16EL_StudentLocalID","Win16EL_LiteracyClassification")] #change column names colnames(FSM)[which(names(FSM)=="F16Math_GradeEquivalent")]<-"Fall Math" colnames(FSM)[which(names(FSM)=="F16Math_StudentLocalID")]<-"STUDENT_ID" colnames(FSR)[which(names(FSR)=="F16Read_GradeEquivalent")]<-"Fall Reading" colnames(FSR)[which(names(FSR)=="F16Read_StudentLocalID")]<-"STUDENT_ID" colnames(FSEL)[which(names(FSEL)=="F16EL_StudentLocalID")]<-"STUDENT_ID" colnames(FSEL)[which(names(FSEL)=="F16EL_LiteracyClassification")]<-"Fall EL" colnames(WSM)[which(names(WSM)=="Win16Math_GradeEquivalent")]<-"Winter Math" colnames(WSM)[which(names(WSM)=="Win16Math_StudentLocalID")]<-"STUDENT_ID" colnames(WSR)[which(names(WSR)=="Win16Read_GradeEquivalent")]<-"Winter Reading" colnames(WSR)[which(names(WSR)=="Win16Read_StudentLocalID")]<-"STUDENT_ID" colnames(WSEL)[which(names(WSEL)=="Win16EL_LiteracyClassification")]<-"Winter EL" colnames(WSEL)[which(names(WSEL)=="Win16EL_StudentLocalID")]<-"STUDENT_ID" #merging StarbyMP<-merge(FSM,FSR,by="STUDENT_ID", all=TRUE) StarbyMP<-merge(StarbyMP,FSEL,by="STUDENT_ID",all=TRUE) StarbyMP<-merge(StarbyMP,WSM,by="STUDENT_ID",all=TRUE) StarbyMP<-merge(StarbyMP,WSR,by="STUDENT_ID",all=TRUE) StarbyMP<-merge(StarbyMP,WSEL,by="STUDENT_ID",all=TRUE) #### #getting columns from enrollment enroll1<-read.csv("enrollmentallyears.csv",strip.white = TRUE) enroll1<-rename(enroll1,SchoolCode=EnrollmentSchoolID) enroll1<-filter(enroll1,SCHOOL_YEAR=="2017") enroll1$Active<-ifelse(enroll1$WITHDRAWAL_CODE=="",1,0) enroll<-filter(enroll1,Active=="1") ##student names Demo<-read.csv("Demographics.csv") Demo<-select(Demo,STUDENT_ID,LastName,FirstName) #merging all four final1<-merge(enroll,rawattendance,by="STUDENT_ID",all=TRUE) final<-merge(final1,togetherfinal,by="STUDENT_ID",all=TRUE) final<-merge(final,Demo,by="STUDENT_ID",all=TRUE) #cleanup Report<-subset(final1,EnrollmentSchoolName=="Seymour Dual Language Academy") Report<-Report[,c("STUDENT_ID","LastName","FirstName","IEP","Gender","Grade","ELL","Ethnicity","YTDAtt","SepAtt","OctAtt","NovAtt","DecAtt","JanAtt","FebAtt","MarAtt","AprAtt","MayAtt","JuneAtt")] Report<-sapply(Report, as.character) Report[is.na(Report)]<-" " write.csv(cleanattendance,"C:/Users/drobil66/Desktop/RFiles/R Reports/SeymourAttendance2018.csv")
/Seymour Request.R
no_license
djrobillard/SCSD
R
false
false
6,096
r
library(lubridate) library(plyr) library(dplyr) rawattendance<-read.csv("attendance2018.csv") cleanattendance <- rawattendance %>% filter(Attendance.Location.Name=="Seymour Dual Language Academy")%>% mutate(Day=1)%>% mutate(Pres=ifelse(Attendance.Desc=="Present",1,0))%>% mutate(Abs=ifelse(Pres==0,1,0))%>% mutate(StudentName=paste(Student.Last.Nm,Student.First.Nm,sep=", "))%>% group_by(Student.Id,StudentName,Rptg.Race.Ethnicity.Desc,Has.Iep,Male) %>% summarise(TotalEnrolled=sum(Day),DaysPresent=sum(Pres),DaysAbsent=sum(Abs))%>% mutate(AttendancePercentage=DaysPresent/TotalEnrolled)%>% mutate(AttendancePercentage=(paste(round((AttendancePercentage)*100,digits=1),"%",sep="")))%>% rename(Race=Rptg.Race.Ethnicity.Desc,Gender=Male,IEP=Has.Iep)%>% select(Student.Id,StudentName,Race,Gender,IEP,TotalEnrolled,DaysPresent,AttendancePercentage) Demo<-rawattendance %>% filter(Attendance.Location.Name=="Seymour Dual Language Academy")%>% select(Student.Id,Student.Last.Nm,Student.First.Nm,Male,Rptg.Race.Ethnicity.Desc,Has.Iep)%>% mutate(StudentName=paste(Student.Last.Nm,Student.First.Nm,sep=",")) rawattendance$Percent<-as.numeric(rawattendance$'Period.Absence..'>.5) rawattendance$daycount = 1 rawattendance$Month<-month(rawattendance$cal_date) rawattendance$Month<-month.abb[rawattendance$Month] YTDdays<-as.data.frame(aggregate(daycount ~ STUDENT_ID, data=rawattendance, FUN=sum)) YTDabsent<-as.data.frame(aggregate(Absent ~ STUDENT_ID, data=rawattendance, FUN=sum)) YTD<-merge(YTDdays,YTDabsent,by="STUDENT_ID",all=TRUE) YTD$YTDAtt<-((YTD$daycount-YTD$Absent)/(YTD$daycount)) YTD$YTDAtt <- paste(round((YTD$YTDAtt)*100,digits=1),"%",sep="") YTD<-YTD[,c("STUDENT_ID","YTDAtt")] totaldays<-as.data.frame(aggregate(daycount ~ STUDENT_ID + Month, data=rawattendance, FUN=sum)) totalabsent<-as.data.frame(aggregate(Absent ~ STUDENT_ID + Month, data=rawattendance, FUN=sum)) together<-merge(totaldays,totalabsent, by=c("STUDENT_ID","Month"),all=TRUE) together$Percentage<-((together$daycount-together$Absent)/(together$daycount)) together$Percentage <- paste(round((together$Percentage)*100,digits=1),"%",sep="") together<-together[,c("STUDENT_ID","Month","Percentage")] togetherfinal<-reshape(together, idvar="STUDENT_ID", timevar="Month", direction="wide") togetherfinal<-rename(togetherfinal,DecAtt=Percentage.Dec, FebAtt=Percentage.Feb, JanAtt=Percentage.Jan, NovAtt=Percentage.Nov, OctAtt=Percentage.Oct, SepAtt=Percentage.Sep, MarAtt=Percentage.Mar, AprAtt=Percentage.Apr, MayAtt=Percentage.May, JuneAtt=Percentage.Jun) togetherfinal<-merge(togetherfinal,YTD,by="STUDENT_ID",all=TRUE) rawattendance<-togetherfinal[,c("STUDENT_ID","YTDAtt","SepAtt","OctAtt","NovAtt","DecAtt","JanAtt","FebAtt","MarAtt","AprAtt","MayAtt","JuneAtt")] ### STAR DATA #STAR Data #load all files FSM<-read.csv("Fall16SM_cleaned.csv") FSR<-read.csv("Fall16SR_cleaned.csv") FSEL<-read.csv("Fall16SEL_cleaned.csv") WSM<-read.csv("WinterSM_cleaned.csv") WSR<-read.csv("WinterSR_cleaned.csv") WSEL<-read.csv("WinterSEL_cleaned.csv") #cleaning STAR information FSEL<-FSEL[c("F16EL_StudentLocalID","F16EL_LiteracyClassification")] FSM<-FSM[c("F16Math_StudentLocalID","F16Math_GradeEquivalent")] FSR<-FSR[c("F16Read_StudentLocalID","F16Read_GradeEquivalent")] WSM<-WSM[c("Win16Math_StudentLocalID","Win16Math_GradeEquivalent")] WSR<-WSR[c("Win16Read_StudentLocalID","Win16Read_GradeEquivalent")] WSEL<-WSEL[c("Win16EL_StudentLocalID","Win16EL_LiteracyClassification")] #change column names colnames(FSM)[which(names(FSM)=="F16Math_GradeEquivalent")]<-"Fall Math" colnames(FSM)[which(names(FSM)=="F16Math_StudentLocalID")]<-"STUDENT_ID" colnames(FSR)[which(names(FSR)=="F16Read_GradeEquivalent")]<-"Fall Reading" colnames(FSR)[which(names(FSR)=="F16Read_StudentLocalID")]<-"STUDENT_ID" colnames(FSEL)[which(names(FSEL)=="F16EL_StudentLocalID")]<-"STUDENT_ID" colnames(FSEL)[which(names(FSEL)=="F16EL_LiteracyClassification")]<-"Fall EL" colnames(WSM)[which(names(WSM)=="Win16Math_GradeEquivalent")]<-"Winter Math" colnames(WSM)[which(names(WSM)=="Win16Math_StudentLocalID")]<-"STUDENT_ID" colnames(WSR)[which(names(WSR)=="Win16Read_GradeEquivalent")]<-"Winter Reading" colnames(WSR)[which(names(WSR)=="Win16Read_StudentLocalID")]<-"STUDENT_ID" colnames(WSEL)[which(names(WSEL)=="Win16EL_LiteracyClassification")]<-"Winter EL" colnames(WSEL)[which(names(WSEL)=="Win16EL_StudentLocalID")]<-"STUDENT_ID" #merging StarbyMP<-merge(FSM,FSR,by="STUDENT_ID", all=TRUE) StarbyMP<-merge(StarbyMP,FSEL,by="STUDENT_ID",all=TRUE) StarbyMP<-merge(StarbyMP,WSM,by="STUDENT_ID",all=TRUE) StarbyMP<-merge(StarbyMP,WSR,by="STUDENT_ID",all=TRUE) StarbyMP<-merge(StarbyMP,WSEL,by="STUDENT_ID",all=TRUE) #### #getting columns from enrollment enroll1<-read.csv("enrollmentallyears.csv",strip.white = TRUE) enroll1<-rename(enroll1,SchoolCode=EnrollmentSchoolID) enroll1<-filter(enroll1,SCHOOL_YEAR=="2017") enroll1$Active<-ifelse(enroll1$WITHDRAWAL_CODE=="",1,0) enroll<-filter(enroll1,Active=="1") ##student names Demo<-read.csv("Demographics.csv") Demo<-select(Demo,STUDENT_ID,LastName,FirstName) #merging all four final1<-merge(enroll,rawattendance,by="STUDENT_ID",all=TRUE) final<-merge(final1,togetherfinal,by="STUDENT_ID",all=TRUE) final<-merge(final,Demo,by="STUDENT_ID",all=TRUE) #cleanup Report<-subset(final1,EnrollmentSchoolName=="Seymour Dual Language Academy") Report<-Report[,c("STUDENT_ID","LastName","FirstName","IEP","Gender","Grade","ELL","Ethnicity","YTDAtt","SepAtt","OctAtt","NovAtt","DecAtt","JanAtt","FebAtt","MarAtt","AprAtt","MayAtt","JuneAtt")] Report<-sapply(Report, as.character) Report[is.na(Report)]<-" " write.csv(cleanattendance,"C:/Users/drobil66/Desktop/RFiles/R Reports/SeymourAttendance2018.csv")
library(shiny) library(poppr) library(phangorn) library(ape) library(igraph) ##################################################### # IMPORTANT: ALl the functions written before line 68 refer to functions loaded by R # before shiny is deployed and executes the custom functions. These functions are definitions of' # global functions and variables. Make sure to add these kinds of functions here. For more information # refer ro the shiny manual. #################################################### ########### MICROBE-ID customization ############ # Here's where you add your database file (Comma Separated Object). Make sure # that the database is in the same folder than this file (server.R) df <- read.table("Ramorum_ssr.csv", header = TRUE, sep = "\t") ################################## df.m <- as.matrix(df) ########### MICROBE-ID customization ############ # Change these values to the repeat lenghts and names of your SSR markers. ssr <- c(PrMS6 = 3, PRMS9c3 = 2, PrMS39a = 2, PrMS45 = 4, KI18 = 2, KI64 = 2, ILVOPrMS131 = 2 ) ################################## # Functions to create elements to plot ## 1. Distance Tree plot.tree <- function (tree, type = input$tree, ...){ ARGS <- c("nj", "upgma") type <- match.arg(type, ARGS) barlen <- min(median(tree$edge.length), 0.1) if (barlen < 0.1) barlen <- 0.01 plot.phylo(tree, cex = 0.8, font = 2, adj = 0, xpd = TRUE, label.offset = 0.0125, ...) nodelabels(tree$node.label, adj = c(1.3, -0.5), frame = "n", cex = 0.8, font = 3, xpd = TRUE) if (type == "nj") { add.scale.bar(lwd = 5, length = barlen) tree <- ladderize(tree) } else { axisPhylo(3) } } ## 2. Minimum spanning network plot.minspan <- function(gen, mst, gadj=3, inds = "none", ...){ plot_poppr_msn(gen, mst, gadj=gadj, vertex.label.color = "firebrick", inds = inds, vertex.label.font = 2, vertex.label.dist = 0.5, nodelab = 100, quantiles = FALSE) } ########### MICROBE-ID customization ############ # From this line on, every one of the functions is going to be used by shiny in a reactive way. All modifications # of processes and outputs for the User interface file (in this case, the www/index.html) are found here. # # INPUT FROM index.html: All variables that start with index$... # OUTPUT TO index.html: All variables that start with output$... # # To determine which variable communicates with whic <div> in the index.html file, search for the line with the # class=shiny*.(e.g. The input$table variable is gonna be filled with info from the <div class="shiny-bound-input" id="table">. # # For more information refer to the shiny manual shinyServer(function(input, output) { #Data input and manipulation data.genoid <- reactive({ if (gsub("\\s", "", input$table) == ""){ return(NULL) } else { input_table <- read.table(text = input$table, stringsAsFactors = FALSE) colnames(input_table) <- colnames(df.m) input_data.genoid <- input_table[[1]] df.m <- rbind(df.m, input_table, deparse.level = 0) df.m <- as.data.frame(df.m) gen <- df2genind(df.m[, -c(1, 2)], ploid = 2, sep = "/", pop = df.m[, 2], ind.names = df.m[, 1]) #Adding colors to the tip values according to the clonal lineage gen$other$tipcolor <- pop(gen) gen$other$input_data.genoid <- input_data.genoid ngroups <- length(levels(gen$other$tipcolor)) ########### MICROBE-ID customization ############ # Change these colors to represent the groups defined in your data.genoid set. # defined_groups <- c("blue", "darkcyan", "darkolivegreen", "darkgoldenrod","red") # # Change heat.colors to whatever color palette you want to represent # submitted data.genoid. # input_colors <- heat.colors(ngroups - length(defined_groups)) # ################################## levels(gen$other$tipcolor) <- c(defined_groups, input_colors) gen$other$tipcolor <- as.character(gen$other$tipcolor) return(gen) } }) # Setting a random seed for the current session from the user interface (<input type = "number" name = "seed" id = "seed" value = "9449" min = "0" />) seed <- reactive({ return(input$seed) }) # Greyscale slider settings from the user interface (<input id="integer" type="slider" name="integer" value="3" class="jslider" data-from="0" data-to="50" data-step="1" data-skin="plastic" data-round="FALSE" data-locale="us" data-format="#,##0.#####" data-smooth="FALSE"/>) slider <- reactive({ slider.a <- (input$integer) return(slider.a) }) # Processing the results. The functions here create the figures to be displayed by the user interface. # Bootstrap of a distance tree out of the data boottree <- reactive({ # Running the tree, setting a cutoff of 50 and saving it into a variable to # be plotted (tree) if (input$boot > 1000){ return(1000L) } else if (input$boot < 10){ return(10L) } set.seed(seed()) tree <- try(bruvo.boot(data.genoid(), replen = ssr, sample = input$boot, tree = input$tree, cutoff = 50), silent = TRUE) # This is a catch to avoid having missing data within the distance matrix. if ("try-error" %in% class(tree)){ for (i in sample(100)){ tree <- try(bruvo.boot(data.genoid(), replen = ssr, sample = input$boot, tree = input$tree, cutoff = 50), silent = TRUE) if (!"try-error" %in% class(tree)){ print(paste0("Success: ", i)) break } print(paste0("Failed: ", i)) } } tree$tip.label <- paste(tree$tip.label, as.character(pop(data.genoid()))) if (input$tree=="nj"){ tree <- phangorn::midpoint(ladderize(tree)) } return(tree) }) #Minimum spanning network creation msnet <- reactive ({ msn.plot <- bruvo.msn(data.genoid(), replen = ssr) V(msn.plot$graph)$size <- 3 return(msn.plot) }) ############ MICROBE-ID customization ############ # The following lines of code communicate with the user interface to # plot the outputs from the processes in the server script. ## Distance Tree (<div id="distPlotTree" class="span6 shiny-plot-output">) output$distPlotTree <- renderPlot({ if (is.null(data.genoid())){ plot.new() rect(0, 1, 1, 0.8, col = "indianred2", border = 'transparent' ) + text(x = 0.5, y = 0.9, "No SSR data has been input.", cex = 1.6, col = "white") } else if (is.integer(boottree())){ msg <- ifelse(boottree() > 10L, "\nless than or equal to 1000", "greater than 10") msg <- paste("The number of bootstrap replicates should be", msg) plot.new() rect(0, 1, 1, 0.8, col = "indianred2", border = 'transparent' ) + text(x = 0.5, y = 0.9, msg, cex = 1.6, col = "white") } else { plot.tree(boottree(), type=input$tree, tip.col=as.character(unlist(data.genoid()$other$tipcolor))) } }) ##Minimum Spanning Network (<div id="MinSpanTree" class="shiny-plot-output") output$MinSpanTree <- renderPlot({ if (is.null(data.genoid())){ plot.new() rect(0, 1, 1, 0.8, col = "indianred2", border = 'transparent' ) + text(x = 0.5, y = 0.9, "No SSR data has been input.", cex = 1.6, col = "white") } else { set.seed(seed()) plot.minspan(data.genoid(), msnet(), gadj=slider(), inds = data.genoid()$other$input_data.genoid) } }) ############ MICROBE-ID customization ############ # The following lines of code communicate with the user interface to # download the outputs from the processes in the server script. ## Distance tree in .tre format (<a id="downloadData" class="btn btn-primary shiny-download-link">") output$downloadData <- downloadHandler( filename = function() { paste0(input$tree, '.tre') }, content = function(file) { write.tree(boottree(), file) }) ## Distance tree in PDF format (<a id="downloadPdf" class="btn btn-info shiny-download-link">) output$downloadPdf <- downloadHandler( filename = function() { paste0(input$tree, '.pdf') }, content = function(file) { pdf(file, width=11, height=8.5) plot.tree(boottree(), type=input$tree, tip.col=as.character(unlist(data.genoid()$other$tipcolor))) dev.off() }) ## Minimum spanning network in PDF format (<a id="downloadPdfMst" class="btn btn-info shiny-download-link">) output$downloadPdfMst <- downloadHandler( filename = function() { paste0("min_span_net", '.pdf')} , content = function(file) { pdf(file, width=11, height=8.5) set.seed(seed()) plot.minspan( data.genoid(), msnet(), gadj=slider(), inds = data.genoid()$other$input_data.genoid) dev.off() } ) #EOF })
/shiny-server/www/genoid_ramorum/server.R
no_license
grunwaldlab/phytophthora_id
R
false
false
8,942
r
library(shiny) library(poppr) library(phangorn) library(ape) library(igraph) ##################################################### # IMPORTANT: ALl the functions written before line 68 refer to functions loaded by R # before shiny is deployed and executes the custom functions. These functions are definitions of' # global functions and variables. Make sure to add these kinds of functions here. For more information # refer ro the shiny manual. #################################################### ########### MICROBE-ID customization ############ # Here's where you add your database file (Comma Separated Object). Make sure # that the database is in the same folder than this file (server.R) df <- read.table("Ramorum_ssr.csv", header = TRUE, sep = "\t") ################################## df.m <- as.matrix(df) ########### MICROBE-ID customization ############ # Change these values to the repeat lenghts and names of your SSR markers. ssr <- c(PrMS6 = 3, PRMS9c3 = 2, PrMS39a = 2, PrMS45 = 4, KI18 = 2, KI64 = 2, ILVOPrMS131 = 2 ) ################################## # Functions to create elements to plot ## 1. Distance Tree plot.tree <- function (tree, type = input$tree, ...){ ARGS <- c("nj", "upgma") type <- match.arg(type, ARGS) barlen <- min(median(tree$edge.length), 0.1) if (barlen < 0.1) barlen <- 0.01 plot.phylo(tree, cex = 0.8, font = 2, adj = 0, xpd = TRUE, label.offset = 0.0125, ...) nodelabels(tree$node.label, adj = c(1.3, -0.5), frame = "n", cex = 0.8, font = 3, xpd = TRUE) if (type == "nj") { add.scale.bar(lwd = 5, length = barlen) tree <- ladderize(tree) } else { axisPhylo(3) } } ## 2. Minimum spanning network plot.minspan <- function(gen, mst, gadj=3, inds = "none", ...){ plot_poppr_msn(gen, mst, gadj=gadj, vertex.label.color = "firebrick", inds = inds, vertex.label.font = 2, vertex.label.dist = 0.5, nodelab = 100, quantiles = FALSE) } ########### MICROBE-ID customization ############ # From this line on, every one of the functions is going to be used by shiny in a reactive way. All modifications # of processes and outputs for the User interface file (in this case, the www/index.html) are found here. # # INPUT FROM index.html: All variables that start with index$... # OUTPUT TO index.html: All variables that start with output$... # # To determine which variable communicates with whic <div> in the index.html file, search for the line with the # class=shiny*.(e.g. The input$table variable is gonna be filled with info from the <div class="shiny-bound-input" id="table">. # # For more information refer to the shiny manual shinyServer(function(input, output) { #Data input and manipulation data.genoid <- reactive({ if (gsub("\\s", "", input$table) == ""){ return(NULL) } else { input_table <- read.table(text = input$table, stringsAsFactors = FALSE) colnames(input_table) <- colnames(df.m) input_data.genoid <- input_table[[1]] df.m <- rbind(df.m, input_table, deparse.level = 0) df.m <- as.data.frame(df.m) gen <- df2genind(df.m[, -c(1, 2)], ploid = 2, sep = "/", pop = df.m[, 2], ind.names = df.m[, 1]) #Adding colors to the tip values according to the clonal lineage gen$other$tipcolor <- pop(gen) gen$other$input_data.genoid <- input_data.genoid ngroups <- length(levels(gen$other$tipcolor)) ########### MICROBE-ID customization ############ # Change these colors to represent the groups defined in your data.genoid set. # defined_groups <- c("blue", "darkcyan", "darkolivegreen", "darkgoldenrod","red") # # Change heat.colors to whatever color palette you want to represent # submitted data.genoid. # input_colors <- heat.colors(ngroups - length(defined_groups)) # ################################## levels(gen$other$tipcolor) <- c(defined_groups, input_colors) gen$other$tipcolor <- as.character(gen$other$tipcolor) return(gen) } }) # Setting a random seed for the current session from the user interface (<input type = "number" name = "seed" id = "seed" value = "9449" min = "0" />) seed <- reactive({ return(input$seed) }) # Greyscale slider settings from the user interface (<input id="integer" type="slider" name="integer" value="3" class="jslider" data-from="0" data-to="50" data-step="1" data-skin="plastic" data-round="FALSE" data-locale="us" data-format="#,##0.#####" data-smooth="FALSE"/>) slider <- reactive({ slider.a <- (input$integer) return(slider.a) }) # Processing the results. The functions here create the figures to be displayed by the user interface. # Bootstrap of a distance tree out of the data boottree <- reactive({ # Running the tree, setting a cutoff of 50 and saving it into a variable to # be plotted (tree) if (input$boot > 1000){ return(1000L) } else if (input$boot < 10){ return(10L) } set.seed(seed()) tree <- try(bruvo.boot(data.genoid(), replen = ssr, sample = input$boot, tree = input$tree, cutoff = 50), silent = TRUE) # This is a catch to avoid having missing data within the distance matrix. if ("try-error" %in% class(tree)){ for (i in sample(100)){ tree <- try(bruvo.boot(data.genoid(), replen = ssr, sample = input$boot, tree = input$tree, cutoff = 50), silent = TRUE) if (!"try-error" %in% class(tree)){ print(paste0("Success: ", i)) break } print(paste0("Failed: ", i)) } } tree$tip.label <- paste(tree$tip.label, as.character(pop(data.genoid()))) if (input$tree=="nj"){ tree <- phangorn::midpoint(ladderize(tree)) } return(tree) }) #Minimum spanning network creation msnet <- reactive ({ msn.plot <- bruvo.msn(data.genoid(), replen = ssr) V(msn.plot$graph)$size <- 3 return(msn.plot) }) ############ MICROBE-ID customization ############ # The following lines of code communicate with the user interface to # plot the outputs from the processes in the server script. ## Distance Tree (<div id="distPlotTree" class="span6 shiny-plot-output">) output$distPlotTree <- renderPlot({ if (is.null(data.genoid())){ plot.new() rect(0, 1, 1, 0.8, col = "indianred2", border = 'transparent' ) + text(x = 0.5, y = 0.9, "No SSR data has been input.", cex = 1.6, col = "white") } else if (is.integer(boottree())){ msg <- ifelse(boottree() > 10L, "\nless than or equal to 1000", "greater than 10") msg <- paste("The number of bootstrap replicates should be", msg) plot.new() rect(0, 1, 1, 0.8, col = "indianred2", border = 'transparent' ) + text(x = 0.5, y = 0.9, msg, cex = 1.6, col = "white") } else { plot.tree(boottree(), type=input$tree, tip.col=as.character(unlist(data.genoid()$other$tipcolor))) } }) ##Minimum Spanning Network (<div id="MinSpanTree" class="shiny-plot-output") output$MinSpanTree <- renderPlot({ if (is.null(data.genoid())){ plot.new() rect(0, 1, 1, 0.8, col = "indianred2", border = 'transparent' ) + text(x = 0.5, y = 0.9, "No SSR data has been input.", cex = 1.6, col = "white") } else { set.seed(seed()) plot.minspan(data.genoid(), msnet(), gadj=slider(), inds = data.genoid()$other$input_data.genoid) } }) ############ MICROBE-ID customization ############ # The following lines of code communicate with the user interface to # download the outputs from the processes in the server script. ## Distance tree in .tre format (<a id="downloadData" class="btn btn-primary shiny-download-link">") output$downloadData <- downloadHandler( filename = function() { paste0(input$tree, '.tre') }, content = function(file) { write.tree(boottree(), file) }) ## Distance tree in PDF format (<a id="downloadPdf" class="btn btn-info shiny-download-link">) output$downloadPdf <- downloadHandler( filename = function() { paste0(input$tree, '.pdf') }, content = function(file) { pdf(file, width=11, height=8.5) plot.tree(boottree(), type=input$tree, tip.col=as.character(unlist(data.genoid()$other$tipcolor))) dev.off() }) ## Minimum spanning network in PDF format (<a id="downloadPdfMst" class="btn btn-info shiny-download-link">) output$downloadPdfMst <- downloadHandler( filename = function() { paste0("min_span_net", '.pdf')} , content = function(file) { pdf(file, width=11, height=8.5) set.seed(seed()) plot.minspan( data.genoid(), msnet(), gadj=slider(), inds = data.genoid()$other$input_data.genoid) dev.off() } ) #EOF })