blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
327
content_id
stringlengths
40
40
detected_licenses
listlengths
0
91
license_type
stringclasses
2 values
repo_name
stringlengths
5
134
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
46 values
visit_date
timestamp[us]date
2016-08-02 22:44:29
2023-09-06 08:39:28
revision_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
committer_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
github_id
int64
19.4k
671M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
14 values
gha_event_created_at
timestamp[us]date
2012-06-21 16:39:19
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-06-28 13:19:12
gha_language
stringclasses
60 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
9.18M
extension
stringclasses
20 values
filename
stringlengths
1
141
content
stringlengths
7
9.18M
daf003d2cb1865698a0251fa0779f0ae8e63f788
584025b690582ab9ac588c77ebc5e746e95816f8
/man/include.Rd
c12f4207091e043bb6a2f8129af3bc9802fa15a4
[]
no_license
rstudio/htmltools
27b459793e6c7dfb12bcd196e72378072d85e92a
251526c9886ca9ab5460c7bd4d73c0d61e2b40b8
refs/heads/main
2023-08-17T23:16:13.900249
2023-08-14T19:49:04
2023-08-14T19:49:04
18,398,793
210
82
null
2023-09-08T14:34:59
2014-04-03T10:11:03
R
UTF-8
R
false
true
1,326
rd
include.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tags.R \name{include} \alias{include} \alias{includeHTML} \alias{includeText} \alias{includeMarkdown} \alias{includeCSS} \alias{includeScript} \title{Include Content From a File} \usage{ includeHTML(path) includeText(path) includeMarkdown(path) includeCSS(path, ...) includeScript(path, ...) } \arguments{ \item{path}{The path of the file to be included. It is highly recommended to use a relative path (the base path being the Shiny application directory), not an absolute path.} \item{...}{Any additional attributes to be applied to the generated tag.} } \description{ Load HTML, text, or rendered Markdown from a file and turn into HTML. } \details{ These functions provide a convenient way to include an extensive amount of HTML, textual, Markdown, CSS, or JavaScript content, rather than using a large literal R string. } \note{ \code{includeText} escapes its contents, but does no other processing. This means that hard breaks and multiple spaces will be rendered as they usually are in HTML: as a single space character. If you are looking for preformatted text, wrap the call with \code{\link[=pre]{pre()}}, or consider using \code{includeMarkdown} instead. The \code{includeMarkdown} function requires the \code{markdown} package. }
63a7553f56d85ce836f7943764849a17bcf8e3cc
c73553a8936ec72cbbfbcc5e88cabbc946ce32a6
/R/generics.R
af6f47d82032e5abc5ca4e98d8103d2ba5fce6c0
[ "MIT" ]
permissive
stephaneghozzi/trendbreaker
b0f9a1475f56bd7f14fb10573c5fe2b807c508e5
5002f7f12dc90c079f4391eb88be4166916403c5
refs/heads/master
2022-10-22T02:47:22.895042
2020-06-17T09:17:19
2020-06-17T09:17:19
275,192,241
1
0
NOASSERTION
2020-06-26T15:47:17
2020-06-26T15:47:16
null
UTF-8
R
false
false
1,561
r
generics.R
#' S3 generics for trendbreaker #' #' These are generic functions used by the *trendbreaker* package, mostly used for #' accessing content of various objects. See `?trendbreaker-accessors` for methods #' relating to `trendbreaker` objects, and `trendbreaker_model-accessors` for methods #' relating to `trendbreaker_model` objects. #' #' @seealso [trendbreaker-accessors](trendbreaker-accessors), #' [trendbreaker_model-accessors](trendbreaker_model-accessors) #' #' @param x the object to access information from #' #' @param ... further arguments used in methods #' #' @param data a `data.frame` to be used as training set for the model #' #' @rdname trendbreaker-generics #' @aliases trendbreaker-generics #' @export get_model <- function (x, ...) { UseMethod("get_model", x) } #' @export #' @rdname trendbreaker-generics get_k <- function (x, ...) { UseMethod("get_k", x) } #' @export #' @rdname trendbreaker-generics get_results <- function (x, ...) { UseMethod("get_results", x) } #' @export #' @rdname trendbreaker-generics get_outliers <- function (x, ...) { UseMethod("get_outliers", x) } #' @export #' @rdname trendbreaker-generics get_formula <- function (x, ...) { UseMethod("get_formula", x) } #' @export #' @rdname trendbreaker-generics get_response <- function (x, ...) { UseMethod("get_response", x) } #' @export #' @rdname trendbreaker-generics get_family <- function (x, ...) { UseMethod("get_family", x) } #' @export #' @rdname trendbreaker-generics train <- function (x, data, ...) { UseMethod("train", x) }
0d93bf530a8f0f1daeb7190d335bf2a58609a515
b4fa675971a21aa98021a1ff2c3f831ad89834e7
/RMGWebScraping.R
6d6cc528de0e460676e0883d766bfa12b8c00a42
[]
no_license
bslakman/representing-chemical-data
4b9f59f3fc136e0f6cd152706827acd2076417c5
6f015fb5f93724ad767de32bafde93a0ad3cad29
refs/heads/master
2021-01-24T10:49:29.491673
2016-10-05T21:28:48
2016-10-05T21:28:48
70,100,006
0
0
null
null
null
null
UTF-8
R
false
false
11,070
r
RMGWebScraping.R
# Belinda Slakman # DSCS 6020 Term Project - Web Scraping # This file will scrape the RMG website at http://rmg.coe.neu.edu for chemical data. # Load required packages library('RCurl') library('XML') # This function scrapes thermodynamic data from the RMG database according to sourceType (either 'libraries' or 'groups') # and name (of the library or group). ScrapeRMGThermo <- function(sourceType, name){ # form the URL by joining the rmg thermo database website with the source type and source name url <- paste0("http://rmg.coe.neu.edu/database/thermo/", sourceType, "/", name) webpage <- getURL(url, followlocation=TRUE) # convert the page into a line-by-line format tc <- textConnection(webpage) webpage <- readLines(tc) close(tc) # get webpage in tree format pagetree_parent <- htmlTreeParse(webpage, useInternalNodes = TRUE) # Figure out how many species there are lastSpecLabel <- unlist(xpathApply(pagetree_parent,"//*/div[@id='contents']/table[@class='thermoData']/tr[position()=last()]/td[1]/a", xmlValue)) lastSpecSplit <- strsplit(lastSpecLabel, ". ") numSpecies <- as.numeric(lastSpecSplit[[1]][1]) # create empty vectors label <- rep(NA, numSpecies) adj_list <- rep(NA, numSpecies) Hf <- rep(NA, numSpecies) Sf <- rep(NA, numSpecies) Cp_300 <- rep(NA, numSpecies) Cp_1000 <- rep(NA, numSpecies) for(index in 1:numSpecies){ # create specific URL for species url_specific <- paste0(url, "/", index) # Make sure it exists if (!url.exists(url_specific)) {next} webpage <- getURL(url_specific, followlocation=TRUE) # convert the page into a line-by-line format tc <- textConnection(webpage) webpage <- readLines(tc) close(tc) # get webpage in tree format pagetree <- htmlTreeParse(webpage, useInternalNodes = TRUE) # get the label for the molecule, and add just its name to the list whole_label <- unlist(xpathApply(pagetree,"//*/h1",xmlValue)) split_label <- strsplit(whole_label, ". ", fixed=TRUE) label[index] <- split_label[[1]][[2]] # get the "alt" attribute of the molecule's image, which corresponds to its adjacency list adj_list_attr <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/p/img/@alt")) adj_list[index] <- adj_list_attr[[1]] # Check the thermo format. We'll only process if Group additivity number_label <- paste0(index, ". ", label[index]) thermo_type <- unlist(xpathApply(pagetree_parent, paste0("//*/table[@class='thermoData']/tr[td[a='", number_label, "']]/td[3]"), xmlValue)) if (!thermo_type=='Group additivity') {next} # get enthalpy of formation, entropy of formation, and heat capcity at 300K and 1000K Hf_value <- unlist(xpathApply(pagetree, "//*/table[@class='thermoEntryData']/tr[1]/td[@class='value']/span", xmlValue)) Hf_processing <- strsplit(Hf_value, " ") Hf[index] <- paste0(Hf_processing[[1]][[1]], " ", Hf_processing[[1]][[4]]) Sf_value <- unlist(xpathApply(pagetree, "//*/table[@class='thermoEntryData']/tr[2]/td[@class='value']/span", xmlValue)) Sf_processing <- strsplit(Sf_value, " ") Sf[index] <- paste0(Sf_processing[[1]][[1]], " ", Sf_processing[[1]][[4]]) Cp_300_value <- unlist(xpathApply(pagetree, "//*/table[@class='thermoEntryData']/tr[3]/td[@class='value']/span", xmlValue)) Cp_300_processing <- strsplit(Cp_300_value, " ") Cp_300[index] <- paste0(Cp_300_processing[[1]][[1]], " ", Cp_300_processing[[1]][[4]]) Cp_1000_value <- unlist(xpathApply(pagetree, "//*/table[@class='thermoEntryData']/tr[8]/td[@class='value']/span", xmlValue)) Cp_1000_processing <- strsplit(Cp_1000_value, " ") Cp_1000[index] <- paste0(Hf_processing[[1]][[1]], " ", Cp_1000_processing[[1]][[4]]) } # Create data frame of these 10 species thermo <- data.frame(label, adj_list, Hf, Sf, Cp_300, Cp_1000, stringsAsFactors = FALSE) thermo <- thermo[complete.cases(thermo[,1]),] return(thermo) } ScrapeRMGKineticsFromLibrary <- function(libraryName){ # form the URL by joining the rmg kinetics library website with the library name url <- paste0("http://rmg.coe.neu.edu/database/kinetics/libraries/", libraryName) webpage <- getURL(url, followlocation=TRUE) # convert the page into a line-by-line format tc <- textConnection(webpage) webpage <- readLines(tc) close(tc) # get webpage in tree format pagetree_parent <- htmlTreeParse(webpage, useInternalNodes = TRUE) # Figure out how many species there are lastSpecLabel <- unlist(xpathApply(pagetree_parent,"//*/div[@id='contents']/table[@class='kineticsData']/tr[position()=last()]/td[1]/a", xmlValue)) lastSpecSplit <- strsplit(lastSpecLabel, ". ") numSpecies <- as.numeric(lastSpecSplit[[1]][1]) # create empty vectors for reactants and kinetics data reactant_1 <- rep(NA, numSpecies) reactant_2 <- rep(NA, numSpecies) reactant_3 <- rep(NA, numSpecies) product_1 <- rep(NA, numSpecies) product_2 <- rep(NA, numSpecies) product_3 <- rep(NA, numSpecies) A <- rep(NA, numSpecies) n <- rep(NA, numSpecies) E_A <- rep(NA, numSpecies) for(index in 1:numSpecies){ # create specific URL for reaction url_specific <- paste0(url, "/", index) if (!url.exists(url_specific)) {next} webpage <- getURL(url_specific, followlocation=TRUE) # convert the page into a line-by-line format tc <- textConnection(webpage) webpage <- readLines(tc) close(tc) # get webpage in tree format pagetree <- htmlTreeParse(webpage, useInternalNodes = TRUE) reactants <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='reaction']/tr/td[1]/a/img/@alt")) reactant_1[index] <- reactants[[1]] if(length(reactants) > 1) {reactant_2[index] <- reactants[[2]]} if(length(reactants) > 2) {reactant_3[index] <- reactants[[3]]} products <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='reaction']/tr/td[3]/a/img/@alt")) product_1[index] <- products[[1]] if(length(products) > 1) {product_2[index] <- products[[2]]} if(length(products) > 2) {product_3[index] <- products[[3]]} # Check the kinetics format. We'll only process if Arrhenius number_label <- paste0(index, ". ") kinetics_type <- unlist(xpathApply(pagetree_parent, paste0("//*/table[@class='kineticsData']/tr[td[a='", number_label, "']]/td[5]"), xmlValue)) if (!kinetics_type=='Arrhenius') {next} kinetics <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/div[@class='math']", xmlValue)) kinetics_split1 <- strsplit(kinetics, "= ") if(length(kinetics_split1[[1]]) < 2) {next} kinetics_split2 <- strsplit(kinetics_split1[[1]][[2]], "T") A[index] <- kinetics_split2[[1]][[1]] if(length(kinetics_split2[[1]]) < 2) {next} kinetics_split3 <- strsplit(kinetics_split2[[1]][[2]], " ") if(length(kinetics_split3[[1]]) < 9) {next} n[index] <- kinetics_split3[[1]][[2]] E_A[index] <- kinetics_split3[[1]][[9]] } kinetics <- data.frame(reactant_1, reactant_2, reactant_3, product_1, product_2, product_3, A, n, E_A, stringsAsFactors = FALSE) kinetics <- kinetics[complete.cases(kinetics[,1]),] return(kinetics) } ScrapeRMGSolvation <- function(){ url <- "http://rmg.mit.edu/database/solvation/libraries/solute" webpage <- getURL(url, followlocation=TRUE) # convert the page into a line-by-line format tc <- textConnection(webpage) webpage <- readLines(tc) close(tc) # get webpage in tree format pagetree_parent <- htmlTreeParse(webpage, useInternalNodes = TRUE) # Figure out how many species there are lastSpecLabel <- unlist(xpathApply(pagetree_parent,"//*/div[@id='contents']/table[@class='solvationData']/tr[position()=last()]/td[1]/a", xmlValue)) lastSpecSplit <- strsplit(lastSpecLabel, ". ") numSpecies <- as.numeric(lastSpecSplit[[1]][1]) # create empty lists for 10 solutes label <- rep(NA, numSpecies) adj_list <- rep(NA, numSpecies) S <- rep(NA, numSpecies) B <- rep(NA, numSpecies) E <- rep(NA, numSpecies) L <- rep(NA, numSpecies) A <- rep(NA, numSpecies) V <- rep(NA, numSpecies) for(index in 1:numSpecies){ url_solvation <- paste0("http://rmg.mit.edu/database/solvation/libraries/solute/", index) if (!url.exists(url_solvation)) {next} webpage <- getURL(url_solvation, followlocation=TRUE) # convert the page into a line-by-line format tc <- textConnection(webpage) webpage <- readLines(tc) close(tc) # get webpage in tree format pagetree <- htmlTreeParse(webpage, useInternalNodes = TRUE) # get the label for the molecule, and add just its name to the list whole_label <- unlist(xpathApply(pagetree,"//*/h1",xmlValue)) split_label <- strsplit(whole_label, ". ", fixed=TRUE) label[index] <- split_label[[1]][[2]] # get the "alt" attribute of the molecule's image, which corresponds to its adjacency list adj_list_attr <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/p/a/img/@alt")) adj_list[index] <- adj_list_attr[[1]] # Retrieve solvation data S_full <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='solvationEntryData']/table[@class='solvationEntryData']/tr[1]/td[@class='value']/span"), xmlValue) splitS <- strsplit(xmlValue(S_full[[1]]), " ") S[index] <- splitS[[1]][1] B_full <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='solvationEntryData']/table[@class='solvationEntryData']/tr[2]/td[@class='value']/span"), xmlValue) splitB <- strsplit(xmlValue(B_full[[1]]), " ") B[index] <- splitB[[1]][1] E_full <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='solvationEntryData']/table[@class='solvationEntryData']/tr[3]/td[@class='value']/span"), xmlValue) splitE <- strsplit(xmlValue(E_full[[1]]), " ") E[index] <- splitE[[1]][1] L_full <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='solvationEntryData']/table[@class='solvationEntryData']/tr[4]/td[@class='value']/span"), xmlValue) splitL <- strsplit(xmlValue(L_full[[1]]), " ") L[index] <- splitL[[1]][1] A_full <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='solvationEntryData']/table[@class='solvationEntryData']/tr[5]/td[@class='value']/span"), xmlValue) splitA <- strsplit(xmlValue(A_full[[1]]), " ") A[index] <- splitA[[1]][1] V_full <- unlist(xpathApply(pagetree,"//*/div[@id='contents']/table[@class='solvationEntryData']/table[@class='solvationEntryData']/tr[6]/td[@class='value']/span"), xmlValue) splitV <- strsplit(xmlValue(V_full[[1]]), " ") V[index] <- splitV[[1]][1] } solvation <- data.frame(label, adj_list, S, B, E, L, A, V, stringsAsFactors = FALSE) solvation <- solvation[complete.cases(solvation[,1]),] return(solvation) } #prim_thermo <- ScrapeRMGThermo('libraries', 'primaryThermoLibrary') #Glarborg_C3_kinetics <- ScrapeRMGKineticsFromLibrary('Glarborg/C3') #solvation <- ScrapeRMGSolvation()
571faec5aa89adbdce04f30bc8d68e2ad1d4924a
e94b06a65f3f5ad73bcf869606fd3178f6a18919
/Scripts/Trait_differences.R
0f2f7d02f735dda8693173dbb54a6f6098683ad8
[]
no_license
phil-martin-research/Invas_ES
da0a79e9b17498ba26761a393ad177d1399939cd
4bf3fc0838428e62ab697aec4480d7b5ec9a8553
refs/heads/master
2021-10-28T14:40:02.868814
2016-08-11T12:59:56
2016-08-11T12:59:56
null
0
0
null
null
null
null
UTF-8
R
false
false
1,707
r
Trait_differences.R
#script to sort out trait data and check for inconsistencies library(ggplot2) #load in data Species_traits<-read.csv("Data/Species_resolved_traits.csv") Species_traits$Median_height<-ifelse(!is.na(Species_traits$Single_height),Species_traits$Single_height,(Species_traits$Upper_height+Species_traits$Lower_height)/2) write.csv(Species_traits,"Data/Species_traits_median.csv") head(Species_traits) ggplot(Species_traits,aes(y= Trait_db_height,x=Upper_height))+geom_point()+geom_abline()+geom_smooth(method="lm") ggplot(Species_traits,aes(y= Trait_db_height,x=Lower_height))+geom_point()+geom_abline()+geom_smooth(method="lm") ggplot(Species_traits,aes(y= Trait_db_height,x=Median_height))+geom_point()+geom_abline()+geom_smooth(method="lm") #look at how close height values derived from internet are to trait databases #first calculated as a percentage sqrt(mean(((Species_traits$Trait_db_height-Species_traits$Upper_height)/Species_traits$Trait_db_height)^2,na.rm = T))-1 sqrt(mean(((Species_traits$Trait_db_height-Species_traits$Lower_height)/Species_traits$Trait_db_height)^2,na.rm = T))-1 sqrt(mean(((Species_traits$Trait_db_height-Species_traits$Median_height)/Species_traits$Trait_db_height)^2,na.rm = T))-1 #then in metres sqrt(mean(((Species_traits$Trait_db_height-Species_traits$Upper_height))^2,na.rm = T)) sqrt(mean(((Species_traits$Trait_db_height-Species_traits$Lower_height))^2,na.rm = T)) sqrt(mean(((Species_traits$Trait_db_height-Species_traits$Median_height))^2,na.rm = T)) #plot how this varies by height plot(Species_traits$Trait_db_height,Species_traits$Median_height-Species_traits$Trait_db_height) M1<-lm(Trait_db_height~Median_height,data=Species_traits) summary(M1)
bb64aad82960ba9f92a9b516160ccca465ccf28c
b21d84bf18b039f4832157d6071e07f036c9d6cf
/man/GenerateReport.Rd
eec98828b11b901ac6975cdb4b8fde76188457f8
[]
no_license
apxr/analyzer
d0ff7682b1a5fc9ad5ae1bf8b0546d052c2bcba0
6dd8de796323ed9b40288c50f7080a9044301f59
refs/heads/master
2023-01-30T09:57:47.253439
2020-12-14T23:16:48
2020-12-14T23:16:48
260,771,475
1
0
null
null
null
null
UTF-8
R
false
true
2,102
rd
GenerateReport.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/GenerateReport.R \name{GenerateReport} \alias{GenerateReport} \title{Generate the report} \usage{ GenerateReport( dtpath, catVars, yvar = NULL, model = "linReg", title = "Report", output_format = "html_document", output_dir = NULL, normality_test_method = "ks", interactive.plots = FALSE, include.vars = NULL ) } \arguments{ \item{dtpath}{dataset path} \item{catVars}{vector of categorical variables names} \item{yvar}{y variable name if present else \code{NULL}} \item{model}{type of model - \code{linReg} for linear regression \code{binClass} for binary classification and \code{multiClass} for multiclass classification} \item{title}{Title of the generated report} \item{output_format}{output report format. \code{'html_documennt'} for html file or \code{pdf_document} for pdf file output. OR \code{c("html_document", "pdf_document")} for both.} \item{output_dir}{Directory where the output files needs to be stored.} \item{normality_test_method}{method for normality test for a variable. Values can be \code{shapiro} for Shapiro-Wilk test or \code{'anderson'} for 'Anderson-Darling' test of normality or \code{ks} for 'Kolmogorov-Smirnov'} \item{interactive.plots}{for interactive variable exploration} \item{include.vars}{include only these variables from the full data} } \value{ creates a rmarkdown and html/pdf file. Invisibly returns \code{TRUE} on successful run and \code{FALSE} in case of error } \description{ \code{GenerateReport} generates the markdown report in one command } \details{ This function creates a rmarkdown report which can be converted to html or pdf format file. } \examples{ # Assigning the temporary folder in Documnets/temp fodler GenerateReport(dtpath = "mtcars.csv", catVars = c("cyl", "vs", "am", "gear"), yvar = "vs", model = "binClass", output_format = NULL, title = "Report", output_dir = NULL, # pass the output directory interactive.plots = FALSE) }
76e7bea9736caf9f08cabf76d76ff9f374044230
d10d46c626637e7f467da67010734f22554c7911
/R/01.2-dados_setores_censitarios.R
b9edc11d60b3e6780f63c9d6d976bab73a348e71
[]
no_license
r-akemii/acesso_oport
6e08c945312784c1ed8ba7637e8223a2c2e93817
2bb7dd307be0ddb9ac09523b873f01bd3eceed7a
refs/heads/master
2020-12-13T10:45:26.764169
2020-01-16T16:11:03
2020-01-16T16:11:03
null
0
0
null
null
null
null
UTF-8
R
false
false
2,929
r
01.2-dados_setores_censitarios.R
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###### 0.1.2 Seleciona e agrega microdados dos setores censitarios # carregar bibliotecas source('./R/fun/setup.R') # # Cria data.frame com municipios do projeto # munis_df <- data.frame( code_muni= c(2304400, 3550308, 3304557, 4106902, 4314902, 3106200, 2211001), # abrev_muni=c('for', 'sao', 'rio', 'cur', 'por', 'bel', 'ter'), # name_muni=c('Fortaleza', 'Sao Paulo', 'Rio de Janeiro', 'Curitiba', 'Porto Alegre', 'Belo Horizonte', 'Teresina')) ### 1. Carrega micro dados dos setores censitarios -------------------------------------------------- ## Leitura dos dados setores1 <- data.table::fread("../data-raw/setores_censitarios/dados_censo2010A.csv", select= c('Cod_UF', 'Cod_municipio', 'Cod_setor', 'DomRend_V003', 'Dom2_V002', 'Pess3_V002', 'Pess3_V003', 'Pess3_V004', 'Pess3_V005', 'Pess3_V006')) names(setores1) # Raca/cor # Pess3_V002 # Pessoas Residentes e cor ou raça - branca # Pess3_V003 # Pessoas Residentes e cor ou raça - preta # Pess3_V004 # Pessoas Residentes e cor ou raça - amarela # Pess3_V005 # Pessoas Residentes e cor ou raça - parda # Pess3_V006 # Pessoas Residentes e cor ou raça - indígena # filtra apenas municipio do projeto setores1 <- setores1[Cod_municipio %in% munis_df$code_muni,] ## Renomeia variaveis # Renda 6.19 - variavel escolhida: V003 = Total do rendimento nominal mensal dos domicílios particulares permanentes setores_renda <- setores1 %>% dplyr::select(cod_uf = Cod_UF, cod_muni = Cod_municipio, cod_setor = Cod_setor, renda_total = DomRend_V003, moradores_total = Dom2_V002, cor_branca=Pess3_V002, cor_preta=Pess3_V003, cor_amarela=Pess3_V004, cor_parda=Pess3_V005, cor_indigena=Pess3_V006) # Criar variavel de renda domicilias per capita de cada setor censitario setDT(setores_renda)[, renda_per_capta := renda_total / moradores_total] setores_renda[, cod_setor := as.character(cod_setor)] ### 2. Merge dos dados de renda com shapes dos setores censitarios -------------------------------------------------- # funcao para fazer merge dos dados e salve arquivos na pata 'data' merge_renda_setores <- function(sigla){ # sigla <- "for" # status message message('Woking on city ', sigla, '\n') # codigo do municipios code_muni <- subset(munis_df, abrev_muni==sigla )$code_muni # subset dados dos setores dados <- subset(setores_renda, cod_muni == code_muni) # leitura do shape dos setores sf <- readr::read_rds( paste0("../data-raw/setores_censitarios/", sigla,"/setores_", sigla,".rds") ) # merge sf2 <- dplyr::left_join(sf, dados, c('code_tract'='cod_setor')) # salvar readr::write_rds(sf2, paste0("../data/setores_agregados/setores_agregados_", sigla,".rds")) } # aplicar funcao purrr::walk(munis_df$abrev_muni, merge_renda_setores)
64f11195806733984d9bccea8844acafc2e2bc34
388e04f6e256c7ad21d5119b7ca56a92b576013c
/R_Programming/rankall.R
8ecf8198c812368235b0c0ab166deb8f4c653e7c
[]
no_license
dinoamaral/DataScienceCousera
9f7a9b21683d5b8f69c4575881862c13b92f35c2
9acbf12a7be8cc1e8c4915e6548a999b556586f0
refs/heads/master
2016-09-11T02:28:58.487472
2015-09-13T17:05:11
2015-09-13T17:05:11
38,140,963
0
0
null
null
null
null
UTF-8
R
false
false
1,642
r
rankall.R
setwd("~/GitHub/DataScienceCousera/R_Programming") hosp_finder <- function(state_sub, col, num) { outcome_sub <- as.numeric(state_sub[, col]) len <- dim(state_sub[!is.na(outcome_sub), ])[1] if (num == "best"){ rank <- state_sub[, 2][order(outcome_sub, state_sub[, 2])[1]] } else if (num == "worst"){ rank <- state_sub[, 2][order(outcome_sub, state_sub[, 2])[len]] } else if (num > len){ rank <- NA } else { rank <- state_sub[, 2][order(outcome_sub, state_sub[, 2])[num]] } return(rank) } rankall <- function(outcome, num = "best") { ## Read outcome data measures <- read.csv("./data/outcome-of-care-measures.csv", colClasses="character") # Create a vector with valid diseases valid_outcomes <- c("heart attack", "heart failure", "pneumonia") state_target <- sort(unique(measures$State)) state_len <- length(state_target) hosp <- rep("", length(state_target)) ## Check that state and outcome are valid valid_outcome <- c("heart attack", "heart failure", "pneumonia") if (!outcome %in% valid_outcome){ stop("Invalid outcome") } else { for (i in 1:state_len){ # serach for each state state_sub <- measures[measures[,7]==state_target[i], ] if(outcome == "heart attack") { hosp[i] <- hosp_finder(state_sub, 11, num) } else if (outcome == "heart failure") { hosp[i] <- hosp_finder(state_sub, 17, num) } else { hosp[i] <- hosp_finder(state_sub, 23, num) } } } #create data frame with the hospital names and the abrevisted state name data_final <- data.frame(hospital=hosp, state=state_target) return(data_final) }
08bbe9670b5ddb38d99e65badec4c79fa0fd72df
9818307f3706a47345e0dec83675adcc681d736c
/Rscript/nls.R
fdc9441a8cbdaa29dd36a29ac730f9b741aa3d10
[ "MIT" ]
permissive
msk940609/rmsp
b63b854a12a057e0a0aa93b65d97a29032757676
19bd2a16d7b2bbb2b5ddabeece1c84a28b7ec298
refs/heads/main
2023-07-14T12:31:29.459897
2021-08-30T16:15:44
2021-08-30T16:15:44
396,658,333
1
0
null
null
null
null
UTF-8
R
false
false
5,344
r
nls.R
library(devtools) library(tidyverse) library(knitr) library(shiny) library(data.table) library(ggplot2) sp1=fread("Datafile/ex_spectrum1.csv") sp2=fread("Datafile/ex_spectrum2.csv") sp1 ggplot()+ geom_point(data=sp1, aes(`Raman shift`, Intensity), col="red") #geom_line(data=sp1, aes(`Raman shift`, Intensity), col="red")+ #geom_point(data=sp2, aes(`Raman shift`, Intensity), col="blue") #geom_line(data=sp1, aes(`Raman shift`, Intensity), col="red") library(broom) library(plotly) ##final================= source("myfunc.R") # for the Pruby() function Lor <- function(x, x0=0, FWHM=1){ 2/(pi*FWHM)/( 1 + ((x-x0)/(FWHM/2))^2 ) } flist <- list.files(path="Data", pattern = "rubis") # Load all data files and do the fits in a single pipe flow data <- tibble(name = flist) %>% mutate(data = map(name, ~read_table2(file = file.path("Data", .), col_names = c("w", "Int"))), fit = map(data, ~ nls(data = ., Int ~ y0 + A1*Lor(w,x1,FWHM1) + A2*Lor(w,x2,FWHM2), start=list(y0 = 0.01, x1 = .$w[which.max(.$Int)] - 2, x2 = .$w[which.max(.$Int)] - 30, FWHM1 = 10, FWHM2 = 10, A1 = max(.$Int)*10, A2 = max(.$Int)*10))), tidied = map(fit, tidy), augmented = map(fit, augment), P = map_dbl(tidied, ~round(Pruby(.$estimate[.$term=='x1']),2)) ) %>% separate(name, c("sample","run", NA), convert=TRUE) %>% relocate(P, .after = run) data ###final end================= ### prac https://lmi.cnrs.fr/r/fitting.html#linear-fitting-with-lm===== x <- seq(-5,7,.1) y <- dnorm(x, sd = .5) + dnorm(x, mean=2, sd = 1) + runif(length(x))/10 - 0.05 df <- tibble(x=x, y=y) ggplot(data=df, aes(x,y))+ geom_point()+ ggtitle("Some fake data we want to fit with 2 Gaussians") myfunc <- function(x, y0, x0, A, B) { y0 + dnorm(x, sd=A) + dnorm(x, mean=x0, sd=B) } ##y0: start point ##x:peak position1, considered peoak located at x=0 ##A:gaussian standard distribution (sd) at peak 1 ##x0:peak poisition2 at xo ##B:gaussian standard distribution (sd) at peak 2 # Fit the data using a user function fit_nls <- nls(data=df, y ~ myfunc(x, y0, x0, A, B), start=list(y0=0, x0=1.5, A=.2, B=.2) # provide starting point ) summary(fit_nls) coef(fit_nls) plot(x, y, pch=16) lines(x, predict(fit_nls), col="red", lwd=2) P1 <- ggplot(data=df, aes(x,y))+ ggtitle("Retrieving the fit performed beforehand")+ geom_point(size=2, alpha=.5) + geom_line(aes(y=predict(fit_nls)), color="red", size=1) P2 <- ggplot(data=df, aes(x,y))+ ggtitle("Doing the fit directly withing ggplot2")+ geom_point(size=2, alpha=.5) + geom_smooth(method = "nls", method.args = list(formula = y ~ myfunc(x, y0, x0, A, B), start=list(y0=0, x0=1.5, A=.2, B=.2) ), data = df, se = FALSE, color="red") P1 P2 fit_constr <- nls(data = df, y ~ myfunc(x, y0, x0, A, B), start = list(y0=0, x0=5, A=.2, B=.2), upper = list(y0=Inf, x0=Inf, A=.4, B=1), lower = list(y0=-Inf, x0=4, A=-Inf, B=-Inf), algorithm = "port" ) ##forced linear regression peak located at x=0 & x=5 # Plotting the resulting function in blue ggplot(data=df, aes(x,y))+ ggtitle("Beware of bad constraints!")+ geom_point(size=2, alpha=.5) + geom_line(aes(y = predict(fit_constr)), color="royalblue", size=1) ##** nls can't affordable with large sd install.packages("minpack.lm") library(minpack.lm) fit_nlsLM <- nlsLM(data = df, y ~ myfunc(x, y0, x0, A, B), start = list(y0=0, x0=5, A=1, B=1) ) summary(fit_nls) ###prac=== library(broom) library(tidyverse) library(ggplot2) theme_set(theme_bw()) # Create fake data a <- seq(-10,10,.1) centers <- c(-2*pi,pi,pi/6) widths <- runif(3, min=0.5, max=1) amp <- runif(3, min=2, max=10) noise <- .3*runif(length(a))-.15 d <- tibble(x=rep(a,3), y=c(amp[1]*dnorm(a,mean=centers[1],sd=widths[1]) + sample(noise), amp[2]*dnorm(a,mean=centers[2],sd=widths[2]) + sample(noise), amp[3]*dnorm(a,mean=centers[3],sd=widths[3]) + sample(noise)), T=rep(1:3, each=length(a)) ) d # Plot the data d %>% ggplot(aes(x=x, y=y, color=factor(T))) + geom_line() d_fitted <- d %>% nest(data = -T) %>% mutate(fit = purrr::map(data, ~ nls(data = ., y ~ y0 + A*dnorm(x, mean=x0, sd=FW), start=list(A = max(.$y), y0 = .01, x0 = .$x[which.max(.$y)], FW = .7) )), tidied = purrr::map(fit, tidy), augmented = purrr::map(fit, augment) ) d_fitted d_fitted %>% unnest(augmented) d_fitted %>% unnest(augmented) %>% ggplot(aes(x=x, color=factor(T)))+ geom_point(aes(y=y), alpha=0.5, size=3) + geom_line(aes(y=.fitted))
97ede1d5f28fad143e73e8062bd3b803923a208b
44c1963ad10663bc6511c9cd6c6d977cc8bb7656
/Plotting Test Heuristics.R
88fcb70ec2d73283e28ab914539b984cd5d4e40a
[]
no_license
Tomlowbridge07/Local-Observations-Generic-Attack-Time-Distributions
912084c726c8b76cece1c013ffbe70ee464961ce
774683a7b7c20315ee11f48bb5836a5c79eb62c7
refs/heads/master
2020-03-22T03:34:19.854980
2018-10-08T13:42:40
2018-10-08T13:42:40
139,439,361
0
0
null
null
null
null
UTF-8
R
false
false
5,791
r
Plotting Test Heuristics.R
source("Testing Heuristics.R") library(ggplot2) library(reshape) library(tikzDevice) #This R file contains functions which take in the Test Matrix and return values #Test Matrices come in the order MinError,BestHeuristics,AdjMatrix,AttackTimes,Capacity,Lambda,Costs,Whole Errors #This function returns the matrix of errors for one scenario DecodeTestMatrixErrors<-function(ScenarioNumber,TestMatrix) { print(TestMatrix) print(TestMatrix[ScenarioNumber,8]) return(TestMatrix[ScenarioNumber,8][[1]]) } #This function just returns the vector of errors for a scenario DecodeTestVectorErrors<-function(ScenarioNumber,TestMatrix) { Matrix=DecodeTestMatrixErrors(ScenarioNumber,TestMatrix) return(Matrix[,4]) } #This function collects the test matrix error data for all heuristics per row DecodeErrorDataPerHeuristic<-function(TestMatrix) { #First we form a matrix of errors rows=heuristicnumber,col=scenarionumber NumberOfScenarios=nrow(TestMatrix) NumberOfHeuristics=length(DecodeTestVectorErrors(1,TestMatrix)) MatrixOfErrors=matrix(0,nrow=NumberOfHeuristics,ncol=NumberOfScenarios) for(ScenarioNumber in 1:NumberOfScenarios) { VectorOfErrors=DecodeTestVectorErrors(ScenarioNumber,TestMatrix) MatrixOfErrors[,ScenarioNumber]=VectorOfErrors } return(MatrixOfErrors) } #This function takes a heuristic vector and categorizes it CategorizeHeuristicErrorData<-function(HeuristicErrors,NumberOfCategories,MaxErrorCategory) { #Work out categories #Note we use the number of categories+1 to allow for the maximum category to be picked CategoryBoundaries=seq(0,MaxErrorCategory,length.out = NumberOfCategories+1) MidPointOfCategories=((CategoryBoundaries[2]-CategoryBoundaries[1])/2) + CategoryBoundaries NumberInEachCategory=vector(length=NumberOfCategories+1) #Now find out how many are in each category for(CategoryNum in 1:(NumberOfCategories+1)) { #Set upper and lower bounds if(CategoryNum==0) { LowerBound=-1 } else { LowerBound=CategoryBoundaries[CategoryNum] } if(CategoryNum==(NumberOfCategories+1)) { UpperBound=Inf } else { UpperBound=CategoryBoundaries[CategoryNum+1] } NumberInEachCategory[CategoryNum]=length(HeuristicErrors[HeuristicErrors>LowerBound & HeuristicErrors<=UpperBound]) } return(list(CategoryMidPoints=MidPointOfCategories,NumberInEachCategory=NumberInEachCategory)) } #Plot a single heuristic PlotHeuristicErrorData<-function(HeuristicErrors,NumberOfCategories,MaxErrorCategory) { #We run the categorize to get the data to plot Categorized=CategorizeHeuristicErrorData(HeuristicErrors,NumberOfCategories,MaxErrorCategory) XCoordinates=Categorized$CategoryMidPoints YCoordinates=Categorized$NumberInEachCategory DataFrame=data.frame(XCoordinates,YCoordinates) Plot<-ggplot(DataFrame,show.legend='True') + geom_point(aes(x = XCoordinates, y = YCoordinates)) + geom_line(aes(x = XCoordinates, y = YCoordinates)) print(Plot) return(Plot) } #Plot a group of heuristics #Note the heuristic erros should be provided in a matrix of rows for each heuristic PlotMultipleHeuristicErrorData<-function(HeuristicErrors,NumberOfCategories,MaxErrorCategory,HeuristicNames=NULL,SaveTexImage=F,FileName=NULL,Size=c(3,2)) { #First we look at how many graphs we are going to plot NumHeuristics=nrow(HeuristicErrors) XCoordinates=matrix(0,ncol=length(CategorizeHeuristicErrorData(HeuristicErrors[1,],NumberOfCategories,MaxErrorCategory)$NumberInEachCategory),nrow=NumHeuristics) YCoordinates=matrix(0,ncol=length(CategorizeHeuristicErrorData(HeuristicErrors[1,],NumberOfCategories,MaxErrorCategory)$NumberInEachCategory),nrow=NumHeuristics) #Now categorize the data for(i in 1:NumHeuristics) { if(i==1) { #Initialize Categorized=CategorizeHeuristicErrorData(HeuristicErrors[i,],NumberOfCategories,MaxErrorCategory) YCoordinates=matrix(0,ncol=length(Categorized$NumberInEachCategory),nrow=NumHeuristics) XCoordinates=Categorized$CategoryMidPoints YCoordinates[i,]=Categorized$NumberInEachCategory YCoordinates[i,]=YCoordinates[i,]/sum(YCoordinates[i,]) Ydataframecol<-data.frame(YCoordinates[i,]) if(is.null(HeuristicNames)) { names(Ydataframecol)=paste("YCoordinates",toString(i)) } else { names(Ydataframecol)=toString(HeuristicNames[i]) } XYCoordinates=data.frame(XCoordinates) XYCoordinates<-cbind(XYCoordinates,Ydataframecol) } else { Categorized=CategorizeHeuristicErrorData(HeuristicErrors[i,],NumberOfCategories,MaxErrorCategory) YCoordinates[i,]=Categorized$NumberInEachCategory YCoordinates[i,]=YCoordinates[i,]/sum(YCoordinates[i,]) Ydataframecol<-data.frame(YCoordinates[i,]) if(is.null(HeuristicNames)) { names(Ydataframecol)=paste("YCoordinates",toString(i)) } else { names(Ydataframecol)=toString(HeuristicNames[i]) } XYCoordinates<-cbind(XYCoordinates,Ydataframecol) } print(XYCoordinates) } #Now we plot the data DataFrame<-XYCoordinates print(DataFrame) MeltedDataFrame<-melt(DataFrame,id="XCoordinates") print(MeltedDataFrame) if(SaveTexImage) { tikz(file=paste("/local/pmxtol/Dropbox/",toString(FileName),".tex",sep=""),width=Size[1],height=Size[2]) } Plot<-ggplot(MeltedDataFrame,aes(x=XCoordinates,y=value,color=variable),show.legend='True') + #geom_point()+ geom_line() +xlab("Percentage Error")+ylab("Frequency Density") + labs(color="Heuristic Type") if(SaveTexImage) { print(Plot) dev.off() } print(Plot) return(Plot) }
0ca158ba017eff5a7426d3a6600d5a3bd85a8203
34de2b3ef4a2478fc6a03ea3b5990dd267d20d2d
/R/rprograms/file/fileread/fileread1/fileRead.r
d05f1383dba73a2fc193173dd6dbf64e149a6b16
[ "MIT" ]
permissive
bhishanpdl/Programming
d4310f86e1d9ac35483191526710caa25b5f138e
9654c253c598405a22cc96dfa1497406c0bd0990
refs/heads/master
2020-03-26T06:19:01.588451
2019-08-21T18:09:59
2019-08-21T18:09:59
69,140,073
0
1
null
null
null
null
UTF-8
R
false
false
366
r
fileRead.r
#!/usr/bin/env Rscript # Author : Bhishan Poudel # Date : Feb 11, 2016 # Program : # ref: http://www.r-tutor.com/r-introduction/data-frame/data-import # Setting working directory this.dir <- dirname(parent.frame(2)$ofile) setwd(this.dir) # reading csv file cat("\n") fileReadcsv <- "data.csv" mydata = read.csv(fileReadcsv) # read csv file print(mydata)
9cf46c62edc47a0b3647b16cf8d246f009736bdc
ba43d630f29f969fdeb0794019bbdf05fa0e9890
/R/gumbel_r.R
c66091e0f07e0e3b2e7a6f8e3257f9d69bf2abaf
[]
no_license
LuchTiarna/PsyFuns
8faaa174c88ee64e631c716dec19c73b298352ac
35b5104e82a0293fb214bfee69be336904c13499
refs/heads/master
2020-06-14T11:17:39.769489
2019-07-07T17:04:48
2019-07-07T17:04:48
194,991,237
1
0
null
null
null
null
UTF-8
R
false
false
862
r
gumbel_r.R
#'@name gumbel_r #'@rdname gumbel_r #' #'@title Gumbel_r #'@description #'Right gumbel function is a sigmoid type function. #'\cr #'It's CDF formula is: exp(- exp(-x)) #'\cr #'It's PDF formula is: y = exp(- exp(-x) - x) #' #'@param x Vector of x parametres #'@return Vector of result vaues #'@rdname gumbel_r gumbel_r <- function(x) { UseMethod("gumbel_r") } #'@rdname gumbel_r gumbel_r.orig <- function(x) { UseMethod("gumbel_r.orig") } #'@rdname gumbel_r gumbel_r.inverse <- function(x) { UseMethod("gumbel_r.inverse") } #'@rdname gumbel_r gumbel_r.orig.cdf <- function(x) { return(exp(- exp(-x))) } #'@rdname gumbel_r gumbel_r.orig.pdf <- function(x) { return(exp(- exp(-x) - x)) } #'@rdname gumbel_r gumbel_r.inverse.cdf <- function(x) { return(-log(-log(x))) } #'@rdname gumbel_r gumbel_r.inverse.pdf <- function(x) { return(-1/(x*log(x))) }
bd5e60029bd8c5da8ed2b5e9f76398c67397417b
24bc03ae395f42bd16386d7c0c6dfafb2c360487
/R/ji.ds.class.R
fae16affd7e8f55711894d532e06f2c4164ac075
[]
no_license
datashield/ji.dev.cl
25307208dcbfb5213d3ca27aaaa7e3866f94a15d
93c378cb4191621897dc509338ca99dd73249e66
refs/heads/master
2020-05-04T04:25:33.072519
2013-12-02T09:44:49
2013-12-02T09:44:49
null
0
0
null
null
null
null
UTF-8
R
false
false
1,361
r
ji.ds.class.R
#' #' @title Retrieves the class of an object #' @description this function is similar to R function \code{class} #' @param datasources a list of opal object(s) obtained after login in to opal servers; #' these objects hold also the data assign to R, as \code{dataframe}, from opal datasources. #' @param x an R object #' @return class of x #' @author Gaye, A. (amadou.gaye@bristol.ac.uk) and Isaeva, J. (julia.isaeva@fhi.no) #' @export #' @examples { #' #' # load that contains the login details #' data(logindata) #' #' # login #' opals <- datashield.login(logins=logindata,assign=TRUE) #' #' # Example 1: Get the class of the whole dataset #' ji.ds.class(datasources=opals, x=quote(D)) #' #' # Example 2: Get the class of the variable PM_BMI_CONTINUOUS #' ji.ds.class(datasources=opals, x=quote(D$LAB_TSC)) #' } #' ji.ds.class = function(datasources=NULL, x=NULL) { if(is.null(datasources)){ message("\n\n ALERT!\n") message(" No valid opal object(s) provided.\n") message(" Make sure you are logged in to valid opal server(s).\n") stop(" End of process!\n\n", call.=FALSE) } if(is.null(x)){ message("\n\n ALERT!\n") message(" Please provide a valid object\n") stop(" End of process!\n\n", call.=FALSE) } cally <- call('class', x ) classes <- datashield.aggregate(datasources, cally) return(classes) }
28bfde191590cf8c2e88e72f6c93641223f16639
82a04ac219608d776f5fc6f89325e1d99fe6c04e
/5.7 Exercise.R
c98d2f575416bb0b830f69bcf8f6436e4e084f2c
[ "MIT" ]
permissive
PacktPublishing/Programming-for-Statistics-and-Data-Science
ba3ee85580430769b9a81184505a71e50527f162
08cb273ca132658a92f3ccd3e66349d495174d97
refs/heads/master
2023-02-09T01:42:05.078048
2023-01-30T09:34:51
2023-01-30T09:34:51
185,159,458
11
16
null
null
null
null
UTF-8
R
false
false
680
r
5.7 Exercise.R
# Create a 5x5 matrix with the rnorm() function, and a 5x5 matrix with runif(). Create each in a single line of code (Hint: nest the operations) # For the two matrices, get the following information; for the first four, save the new values as columns in their corresponding matrixes: #Column averages #Row averages #Column sums #Row sums #Minimum and maximum value in the matrix #Minimum and maximum value for the 3rd column in each matrix #The means and standard deviations for each matrix (compare the two values; if interested in the mathematics side of things, recreate the matrices a couple of times, and compare the results; can you explain what is happening?)
05441f3c6de5f6fe2a19592c2c2600dc1fb4812d
183caf378df099da122f65ea9b75002b1e12b774
/projFocus/ceRNA/DESeq.r
17184ddef5401dcd5ede8962c969ffd2ffa1bab4
[]
no_license
cwt1/scripts-1
f58e476ddb2c83e0480856a95a95a644ad3c001c
061d6592aa6ab11c93363fcb40305a57db05e3f2
refs/heads/master
2021-05-28T01:31:30.896133
2014-08-25T19:02:37
2014-08-25T19:02:37
null
0
0
null
null
null
null
UTF-8
R
false
false
2,496
r
DESeq.r
#!/usr/bin/Rscript #J.HE #input: #output: #TODO: # args <- commandArgs(TRUE) # if (is.null(args)){ # print("Please provide parameters") # exit # }else{ # print(args) # } # library(EBSeq) library(DESeq) rootd <- "/ifs/scratch/c2b2/ac_lab/jh3283/projFocus/ceRNA/result/exp" setwd(rootd) # load raw expression matrix and prepare a matrix # infile <- args[1] infile <- "/ifs/scratch/c2b2/ac_lab/jh3283/projFocus/ceRNA/data/rnaSeq2/brca_rnaSeq2_rsem_raw_1.mat" designfile <- "/ifs/scratch/c2b2/ac_lab/jh3283/projFocus/ceRNA/data/rnaSeq2/input_EBseqR_ColDesign.txt" datacolDesign <- read.table(designfile, sep= "\t") # table(datacolDesign[,4]) replace = function(df,old,new){ dfnew <- apply(df,c(1,2),function(x){ pattern <- paste("^",old,"$",sep="") gsub(pattern,new,gsub(" ","",x),perl=T) }) return(dfnew) } # take tumor and normal sample datacolDesign <- datacolDesign[which(datacolDesign[,4]=="1" | datacolDesign[,4]=="11"),] datacolDesign <- replace(datacolDesign,1,"tumor") datacolDesign <- replace(datacolDesign,11,"normal") datacolDesign[,1] <- sapply(datacolDesign[,1],function(x){gsub("-",".",x)}) dataMat <- read.table(infile,sep="\t",header=T) row.names(dataMat) <- dataMat[,1] dataMat <- dataMat[,-1] designCol <- datacolDesign[,4] names(designCol) <- datacolDesign[,1] designCond <- na.omit(designCol[colnames(dataMat)]) dataMat <- dataMat[,names(designCond)] # prepare the Design libDesign <- rep("paired-end",ncol(dataMat)) dataMatDesign = data.frame(row.names = colnames(dataMat), condition = designCond, libType = libDesign ) condition <- factor( designCond ) # normalization DESeq dataMat <- apply(dataMat,c(1,2),round) cds = newCountDataSet( dataMat, condition ) cds = estimateSizeFactors( cds ) sizeFactors( cds ) topleft( counts( cds, normalized=TRUE ) ) cds = estimateDispersions( cds ) str( fitInfo(cds) ) save(cds, file=paste(rootd,"/DESeq_run1_cds.rda",sep="")) head( fData(cds) ) res = nbinomTest( cds, "tumor", "normal" ) save(res, file=paste(rootd,"/DESeq_run1_res.rda",sep="")) head(res) pdf(paste(rootd,"/DESeq_run1.pdf",sep="")) plotDispEsts( cds ) plotMA(res) hist(res$pval, breaks=100, col="skyblue", border="slateblue", main="") dev.off() # resSig = res[ res$padj < 0.1, ] # head( resSig[ order(resSig$pval), ] ) # head( resSig[ order( resSig$foldChange, -resSig$baseMean ), ] ) write.csv( res, file=paste(rootd,"/DESeq_run1_DEG_result.csv",sep="")) # source("http://bioconductor.org/biocLite.R") # biocLite("genefilter")
4fac5ef395e8be29bde39352b8668c121a75fa38
eef7754e99418c7c040e2bc18e95b3263d542426
/man/sca.Rd
c950375b467a04a6a091924d5b23b84d1a009cb6
[]
no_license
cran/cabootcrs
e63b5ce9d86b5f2b973c19b8a250095f81f81c55
a5e3efc3f1e555b547a9b0ffb266052bee11a770
refs/heads/master
2022-03-06T06:23:19.926820
2022-03-02T22:00:02
2022-03-02T22:00:02
17,694,910
0
0
null
null
null
null
UTF-8
R
false
true
1,170
rd
sca.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sca.R \name{sca} \alias{sca} \title{Performs standard Correspondence Analysis calculations} \usage{ sca(X, catype = "sca", mcatype = NULL, p = 2, needtrans = FALSE) } \arguments{ \item{X}{A data matrix with rows >= cols} \item{catype}{Can be "sca" for simple CA or "mca" for multiple CA} \item{mcatype}{If catype="mca" then this can be "Burt", "Indicator" or "doubled" depending on the analysis required.\cr This affects the number of meaningful singular values, as does p below} \item{p}{Number of variables, only needed if catype="mca"} \item{needtrans}{TRUE if rows < columns so need to transpose in the routine} } \value{ An object of class \code{\linkS4class{cabasicresults}} } \description{ \code{sca} returns all the basic results from a CA of a matrix with rows >= cols, in an object of class \code{\linkS4class{cabasicresults}} } \details{ This is only intended for internal use by the \code{\link{cabootcrs}} function. } \examples{ results <- sca(as.matrix(DreamData)) } \seealso{ \code{\link{cabootcrs-package}}, \code{\link{cabootcrs}}, \code{\linkS4class{cabasicresults}} }
6667026891e2c8305c1891bd94c8e4063aa8ebfe
8f6565e5310613a58bffb390591dbada2d4d00f7
/scripts/Second_run.R
a41fae3b7d257983400c1c24777fc7161a10e63a
[]
no_license
AugustT/whats_flying_tonight
2aa0ee6e85ea87449b2347b877bbe2640437c3d7
afda2a00ca4df9a4152725812ec65657c1aeac68
refs/heads/master
2021-01-18T05:11:10.861463
2018-11-16T14:38:43
2018-11-16T14:38:43
45,030,483
0
1
null
2015-10-27T09:33:47
2015-10-27T09:33:47
null
UTF-8
R
false
false
8,317
r
Second_run.R
## Gather new data, create phenologies and hectad count data ## rm(list = ls()) # This file should be re-runable. You shouldn't have to change anything in this # file, just update the sql queries in the NMRS folder so that they include the # year range of interest. Note the info in the app will also need to be # updated ################## # Get Count Data # ################## # Setup DB connection library(RODBC) if(exists("channel") == FALSE) channel = odbcConnect("BRC", uid = "tomaug", pwd = "DoHitDedKu") # Run an sql query to gather the hectad data files get_all_query <- paste(readLines('data/NMRS/NMRS summary sp agg 2017.sql'), collapse = ' ') all_data <- sqlQuery(channel = channel, query = get_all_query) # save the data write.table(all_data, file = 'data/NMRS/NMRS_summary_data.csv', row.names = FALSE, sep = ',') # Write a species summary for MB species_table <- unique(all_data[, c('CONCEPT', 'NAME', 'RANK')]) # Add to this the species other data load('data/UKMoths/speciesData_newNames.rdata') speciesDataRaw <- speciesDataRaw[, c('CONCEPT', 'new_englishname', 'NAME_ENGLISH', 'BINOMIAL')] names(speciesDataRaw) <- c('CONCEPT', 'english_name', 'old_englishname', 'old_binomial') species_table_plus <- merge(x = species_table, y = speciesDataRaw, by.x = 'CONCEPT', by.y = 'CONCEPT', all = T) write.csv(x = species_table, file = 'data/NMRS/species_extracted.csv', row.names = FALSE) write.csv(x = species_table_plus, file = 'data/NMRS/species_extracted_translation.csv', row.names = FALSE) rm(list = c('all_data')) ##################### # Cut up count data # ##################### recData <- read.table('data/NMRS/NMRS_summary_data.csv', stringsAsFactors = FALSE, header = TRUE, sep = ',') n <- length(sort(unique(recData$SQ_10))) # parallelise library(snowfall) sfInit(cpus = 3, parallel = TRUE) sfExport('n', 'recData') # This dataset needs to be cut up into small chunks for loading on the go sfClusterApplyLB(sort(unique(recData$SQ_10)), fun = function(hec){ cat(grep(paste('^',hec, sep = ''), sort(unique(recData$SQ_10))), 'of', n, hec, '\n') temp_dat <- recData[recData$SQ_10 == hec, c('CONCEPT','DAYNO','N_RECS')] save(temp_dat, file = paste('data/hectad_counts/', hec, '.rdata', sep = '')) rm(list = c('temp_dat')) }) sfStop() ################################################## # Create phenology plots and add missing species # ################################################## # Get the data rm(list = ls()) library(RODBC) if(exists("channel") == FALSE) channel = odbcConnect("BRC", uid = "tomaug", pwd = "DoHitDedKu") get_weeks_query <- paste(readLines('data/NMRS/NMRS sp week counts 2017.sql'), collapse = ' ') all_weeks_data <- sqlQuery(channel = channel, query = get_weeks_query) # save the data write.table(all_weeks_data, file = 'data/NMRS/NMRS_weeks_counts.csv', row.names = FALSE, sep = ',') rm(list = c('all_weeks_data')) speciesData <- read.csv('data/NMRS/NMRS_weeks_counts.csv', stringsAsFactors = FALSE) library(ggplot2) library(RColorBrewer) library(grid) load(file = 'data/UKMoths/speciesData_newNames2017.rdata') # reset phenology columns speciesDataRaw$phenosmall <- NA speciesDataRaw$phenobig <- NA for(n in seq_along(unique(speciesData$CONCEPT))){ i <- unique(speciesData$CONCEPT)[n] cat(i, '... ') if(!i %in% speciesDataRaw$new_concept){ new_name_data <- sqlQuery(channel = channel, query = paste0( "select * from brc.taxa_taxon_register where concept = '", i, "' AND valid = 'V'")) temp <- speciesDataRaw[1,] temp[,] <- NA temp[,c('NAME', 'BINOMIAL', 'new_binomial')] <- as.character(new_name_data$BINOMIAL) temp[,c('NAME_ENGLISH', 'new_englishname')] <- as.character(new_name_data$NAME_ENGLISH) temp[,c('CONCEPT','new_concept')] <- as.character(i) temp$URL <- 'http://ukmoths.org.uk' temp$changed <- 'new' temp$VALID <- 'V' cat(' * NEW * ') speciesDataRaw <- rbind(speciesDataRaw, temp) } sp_name <- speciesDataRaw[speciesDataRaw$new_concept == i & !is.na(speciesDataRaw$new_concept), ] latinName <- as.character(sp_name$new_binomial) commonName <- as.character(sp_name$new_englishname) valid <- as.character(sp_name$VALID) cat(valid, latinName, commonName) #n_recs is number of distinct site date records tempDat <- speciesData[speciesData$CONCEPT == i, ] if(nrow(tempDat) != 53){ tempDat <- rbind(tempDat[,c('CONCEPT', 'WEEKNO', 'N_RECS')], data.frame(CONCEPT = i, WEEKNO = c(1:53)[!c(1:53) %in% tempDat$WEEKNO], N_RECS = 0)) } # Create a custom colour pallette for the calendar plots myPalette <- colorRampPalette(brewer.pal(9, 'YlOrBr')) small_filename <- paste('phenology/', valid, gsub(' ', '_', gsub('/', '_', latinName)), '.png', sep = '') speciesDataRaw[speciesDataRaw$new_concept == i & !is.na(speciesDataRaw$new_concept), 'phenosmall'] <- small_filename png(filename = small_filename, width = 235, height = 60, bg = "transparent") p <- ggplot(tempDat, aes(x = WEEKNO, y = CONCEPT, fill = N_RECS)) + geom_tile() + scale_fill_gradientn(colours = myPalette(50)) + scale_x_continuous(expand = c(0, 0), breaks = seq(52/12, 52, 52/12) - (52/12)/2, labels = c('J','F','M','A','M','J','J','A','S','O','N','D')) + scale_y_discrete(expand = c(0, 0)) + # geom_vline(xintercept = c(thisWeek - 0.5, thisWeek + 0.5)) + ylab('') + xlab('') + # geom_hline(yintercept = c(1.5, 2.5), colour = 'white') + theme_bw() + theme(text = element_text(size = 12), legend.position = "none", plot.background = element_rect(fill = "transparent", colour = NA), plot.margin = unit(c(0.1,0.1,-0.3,-0.8), "cm"), axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.ticks.x = element_blank()) plot(p) dev.off() big_filename <- paste('phenology/', valid, gsub(' ', '_', gsub('/', '_', latinName)), '_big.png', sep = '') speciesDataRaw[speciesDataRaw$new_concept == i & !is.na(speciesDataRaw$new_concept), 'phenobig'] <- big_filename png(filename = big_filename, width = 600, height = 120, bg = "transparent") p <- ggplot(tempDat, aes(x = WEEKNO, y = CONCEPT, fill = N_RECS)) + geom_tile() + scale_fill_gradientn(colours = myPalette(50)) + scale_x_continuous(expand = c(0, 0), breaks = seq(52/12, 52, 52/12) - (52/12)/2, labels = c('Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec')) + scale_y_discrete(expand = c(0, 0)) + # geom_vline(xintercept = c(thisWeek - 0.5, thisWeek + 0.5)) + # geom_hline(yintercept = c(1.5, 2.5), colour = 'white') + theme_bw() + ylab('') + xlab('') + theme(text = element_text(size = 12), legend.position = "none", axis.text.y = element_blank(), plot.background = element_rect(fill = "transparent", colour = NA), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) plot(p) dev.off() cat(' ... done', '\n') } # Save out the new species names table # unique(speciesData$CONCEPT[!speciesData$CONCEPT %in% speciesDataRaw$new_concept]) # x <- speciesDataRaw[!speciesDataRaw$new_concept %in% unique(speciesData$CONCEPT),] save(speciesDataRaw, file = 'data/UKMoths/speciesData_newNames2017.rdata')
f1bf450ddfb4231064e203d06c44ac404dab4cfb
dd4f8da164a0c50e503cad009e2128bf4eb2a7ed
/project1.R
e706e9f2e2554790486accf057e8ee83cb0581c0
[]
no_license
ootmon1/linear-regression
5f7574855a3341b6db231f7e21454004931ce843
277fc9df1fbbeac72c2bcd174ec1ad9226afe628
refs/heads/master
2020-11-25T23:53:36.884438
2019-12-18T18:13:51
2019-12-18T18:13:51
228,895,968
0
0
null
null
null
null
UTF-8
R
false
false
1,396
r
project1.R
# Program: Project 1 # Author: John Dixon # Date: 17 Feb. 2019 # Description: Linear regression using the Boston data set. # get Boston data frame from MASS library library(MASS) df <- Boston[] # explore the Boston data set str(df) # show structure of df summary(df) # show stats for each column sapply(df, function(x) sum(is.na(x) == TRUE)) # count NAs in each column head(df, n = 10) # show first 10 rows # visualize the data set pairs(df) # show correlation between columns # plot rm and medv on scatterplot plot(df$rm, df$medv, main = "Median Home Value vs Avg. Number of Rooms", xlab = "Avg. Number of Rooms", ylab = "Median Home Value (in $1000s)") # separate data into train/test train <- df[c(1:400),] test <- df[c(401:506),] # train linear regression model and record start/end time start_time <- proc.time() lm1 <- lm(medv ~ rm, data = train) end_time <- proc.time() # calculate elapsed time for linear regression algorithm lr_time <- (end_time[3] - start_time[3]) # print model coefficients summary(lm1) # predict test values pred <- predict(lm1, newdata = test) # evaluate test predictions corr <- cor(pred, test$medv) mse <- mean((pred - test$medv)^2) rmse <- sqrt(mse) # print results print(paste("Elapsed time for linear regression:", lr_time, "seconds")) print(paste("Correlation:", corr)) print(paste("MSE:", mse)) print(paste("RMSE:", rmse))
5ddadcc384f9e9acfe20955ab8277057f73744fc
9386a55c2b8b01d0f0f2190221c9ea27521c3c71
/wind.event.predictor/clustertest.R
1a60dfbbcc302a9bfaf77ae1692e445be9dde78e
[]
no_license
lisaoshita/apcd.r
0fd50db5a7fbd030eb3e3cc4052bc3ce8bc476e3
abae94cf88516e25d66958d2f5d404825d4d9002
refs/heads/master
2021-07-10T12:30:46.424243
2018-12-06T01:19:37
2018-12-06T01:19:37
129,440,838
0
0
null
null
null
null
UTF-8
R
false
false
2,331
r
clustertest.R
library(dplyr) library(sp) # functions to convert polar coordinates to cartesian: make.x <- function(ws, wd){ ws*cos((90-wd)*pi/180) } make.y <- function(ws, wd){ ws*sin((90-wd)*pi/180) } s1.training <- training %>% select(date, year, wd.s1, ws.s1, pm10.cdf) colnames(s1.training) <- c("date", "year", "wd", "ws", "pm10") s1.clust <- polarCluster(s1.training, pollutant = "pm10", x = "ws", wd = "wd", n.clusters = 2) # get cluster of high PM and create cartersian coordinates: s1.clust$data %>% filter(cluster == 2) %>% mutate(x = make.x(ws, wd)) %>% mutate(y = make.y(ws, wd)) -> s1.range # check (looks reasoable): summary(s1.range) plot(s1.range$x, s1.range$y, #compare with print(s1.clust) ylim = c(-15, 15), xlim = c(-15, 15), asp = 1, pch = 16, cex = 0.5) # get convex hull chull.index <- chull(s1.range$x, s1.range$y) chull.index <- c(chull.index, chull.index[1]) s1.range.chull <- s1.range[chull.index, c("x", "y")] # check --> looks good! lines(s1.range.chull$x, s1.range.chull$y, col = "red") # add to current plot # function to see if a point falls in the s1 range: wind.in.range <- function(ws, wd, range){ # assumes range is a two column df with "x" and "y" # assumes ws and wd in usual format, # so must convert to cartesian coords. # define these functions again, in case they are not # in environment: make.x <- function(ws, wd){ ws*cos((90-wd)*pi/180) } make.y <- function(ws, wd){ ws*sin((90-wd)*pi/180) } xs <- make.x(ws, wd) ys <- make.y(ws, wd) # test if in range res <- point.in.polygon(xs, ys, range$x, range$y) # return 0 if outside, 1 if inside or on edge, NA if ws or wd is missing res <- ifelse(res == 0, 0, 1) # see ?point.in.polygon res[is.na(ws) | is.na(wd)] <- NA # preserve NA's return(res) } ## test function: does it 'predict' if ws/wd pair is in high PM10 cluster? preds <- wind.in.range(s1.clust$data$ws, s1.clust$data$wd, s1.range.chull) table(s1.clust$data$cluster, preds) # hmmm... 52 observation from cluster 1 are predicted to be in cluster 2 s1.clust$data[preds == 1 & s1.clust$data$cluster == 1, ] # these all appear to be on the edge, so OK if predicted to be in cluster 2
faf80660eff4c6365bc12089846a7d93e8c85162
48dbeff0b9b2fd9336ee33e0a33771bdd4ca5ea2
/Script.R
25503aa2644fa96079bde735e4cd85f5474915d9
[]
no_license
julianarturoc/Reproducible-Research
1714cd444015de76d0b7b5d4a6de8ce8e7f5b886
7c57f9c99d96522b1b0ed6295c8f5647ab630c77
refs/heads/master
2022-08-01T08:17:51.387729
2020-05-31T04:29:47
2020-05-31T04:29:47
268,208,223
0
0
null
null
null
null
UTF-8
R
false
false
2,476
r
Script.R
## ------------------------------------------------------------------------ # 0. loading libraries library(ggplot2) library(dplyr) library(lubridate) ## ------------------------------------------------------------------------ # 1. Reading Data unzip(zipfile="activity.zip") data<-read.csv(file="activity.csv", header=TRUE, sep=",") head(data) # 2. Graph steps per day t_steps <- tapply(data$steps, data$date, FUN=sum, na.rm=TRUE) qplot(t_steps, binwidth=1000, xlab="Total number of steps taken per day") mean(t_steps, na.rm=TRUE) median(t_steps, na.rm=TRUE) ## ------------------------------------------------------------------------ # 3. Graph average steps taken averages <- aggregate(x=list(steps=data$steps), by=list(interval=data$interval), FUN=mean, na.rm=TRUE) ggplot(data=averages, aes(x=interval, y=steps)) + geom_line() + xlab("interval [every 5 minutes]") + ylab("Number of steps taken [average]") ## ------------------------------------------------------------------------ # Calculating metrics for filling values averages[which.max(averages$steps),] missing <- is.na(data$steps) table(missing) ## ------------------------------------------------------------------------ # Replace each missing value with the mean calculated above fill <- function(steps, interval) { filled <- NA if (!is.na(steps)) filled <- c(steps) else filled <- (averages[averages$interval==interval, "steps"]) return(filled) } completed.data <- data completed.data$steps <- mapply(fill, completed.data$steps, completed.data$interval) t_steps <- tapply(completed.data$steps, completed.data$date, FUN=sum) qplot(t_steps, binwidth=1000, xlab="total number of steps taken each day") mean(t_steps) median(t_steps) ## ------------------------------------------------------------------------ # checking the day completed.data$date<-as.Date(completed.data$date) completed.data<-mutate(completed.data, weekdayType=0) completed.data$weekdayType <- ifelse(weekdays(completed.data$date) %in% c("sabado", "domingo"), "weekend", "weekday") ## ------------------------------------------------------------------------ day <- weekdays(completed.data$date) averages <- aggregate(steps ~ interval + day, data=completed.data, mean) ggplot(averages, aes(interval, steps)) + geom_line() + facet_grid(day ~ .) + xlab("5-minute interval") + ylab("steps (Q)")
0059365c6c6071e96f73d8a0af79d1973540ff4e
f681257722365f95a24cfbe26310345b50a4a4f6
/R/lcvp_group_search.R
f08b7748ccbadad0ee3bc1af57e0428720e45d1c
[ "MIT" ]
permissive
idiv-biodiversity/lcvplants
ac3008d1a0ec7a19211e670905a7056442082724
4521372afff25f0f8e7f43a2f825277dc6a1c5d4
refs/heads/master
2023-05-23T22:01:33.748106
2022-11-07T14:48:18
2022-11-07T14:48:18
215,979,088
14
4
NOASSERTION
2021-09-14T16:56:14
2019-10-18T08:37:16
R
UTF-8
R
false
false
8,323
r
lcvp_group_search.R
#' Search plants by taxa or author names in the Leipzig Catalogue of Plants (LCVP) #' #' Search all plant taxa names listed in the "Leipzig #' Catalogue of Vascular Plants" (LCVP) by order, family, #' genus or author. #' #' @param group_names A character vector specifying the taxa or author names. #' This includes names of orders, families, genus or authors. Only valid #' characters are allowed (see \code{\link[base:validEnc]{validEnc}}). #' #' @param search_by A character indicating whether to search by "Order", #' "Family", "Genus" or "Author". #' #'@param max_distance It represents the maximum string distance allowed for a #' match when comparing the submitted name with the closest name matches in the #' LCVP. The distance used is a generalized Levenshtein distance that indicates #' the total number of insertions, deletions, and substitutions allowed to #' match the two names. It can be expressed as an integer or as the fraction of #' the binomial name. For example, a name with length 10, and a max_distance = #' 0.1, allow only one change (insertion, deletion, or substitution). A #' max_distance = 2, allows two changes. #' #' @param bind_result If TRUE the function will return one data.frame (default). #' If False, the function will return a list of separate data.frames for #' each input group. #' #' @param status A character vector indicating what taxa status should be #' included in the results: "accepted", "synonym", "unresolved", "external". #' #' The "unresolved" rank means that the status of the plant name could be #' either valid or synonym, but the information available does not allow #' a definitive decision. "external" is an extra rank that lists names #' outside the scope of this publication but useful to keep on this #' updated list. #' #' @details #' #' The algorithm will look for all the plant taxa names listed in the "Leipzig #' Catalogue of Vascular Plants" (LCVP) based on a user-specified list of #' orders, families, genus, or authors names. If no match is found, it will try #' to find the closest name given the maximum distance defined in `max_distance`. #' If more than one name is fuzzy matched, only the first will be returned. #' #' @return #' A data.frame or a list of data.frames (if \code{bind_result = FALSE}) #' with the following columns for all species of the matched groups: #' #' \describe{#' \item{global.Id}{The fixed species id of the input taxon in the #' Leipzig Catalogue of Vascular Plants (LCVP).} #' \item{Input.Genus}{A #' character vector. The input genus of the corresponding vascular plant #' species name listed in LCVP.} #' \item{Input.Epitheton}{A character vector. #' The input epitheton of the corresponding vascular plant species name listed #' in LCVP.} #' \item{Rank}{A character vector. The taxonomic rank ("species", #' subspecies: "subsp.", variety: "var.", subvariety: "subvar.", "forma", or #' subforma: "subf.") of the corresponding vascular plant species name listed #' in LCVP.} #' \item{Input.Subspecies.Epitheton}{A character vector. If the #' indicated rank is below species, the subspecies epitheton input of the #' corresponding vascular plant species name listed in LCVP. If the rank is #' "species", the input is "nil".} #' \item{Input.Authors}{A character vector. #' The taxonomic authority input of the corresponding vascular plant species #' name listed in LCVP.} #' \item{Status}{A character vector. description if a #' taxon is classified as ‘valid’, ‘synonym’, ‘unresolved’, ‘external’ or #' ‘blanks’. The ‘unresolved’ rank means that the status of the plant name #' could be either valid or synonym, but the information available does not #' allow a definitive decision. ‘External’ in an extra rank which lists names #' outside the scope of this publication but useful to keep on this updated #' list. ‘Blanks’ means that the respective name exists in bibliography but it #' is neither clear where it came from valid, synonym or unresolved. (see the #' main text Freiberg et al. for more details)} #' \item{globalId.of.Output.Taxon}{The fixed species id of the output taxon #' in LCVP.} #' \item{Output.Taxon}{A character vector. The list of the accepted #' plant taxa names according to the LCVP.} #' \item{Family}{A character vector. #' The corresponding family name of the Input.Taxon, staying empty if the #' Status is unresolved.} #' \item{Order}{A character vector. The corresponding #' order name of the Input.Taxon, staying empty if the Status is unresolved.} #' \item{Literature}{A character vector. The bibliography used.} #' \item{Comments}{A character vector. Further taxonomic comments.}} #' #' See \code{\link[LCVP:tab_lcvp]{LCVP:tab_lcvp}} for more details. #' #' If no match is found for all searched names the function will #' return NULL and a warning message. #' #' @author #' Bruno Vilela & Alexander Ziska #' #' @seealso #' \code{\link[lcvplants:lcvp_search]{lcvp_search}}, #' \code{\link[lcvplants:lcvp_fuzzy_search]{lcvp_fuzzy_search}}. #' #' @references #' Freiberg, M., Winter, M., Gentile, A. et al. LCVP, The Leipzig #' catalogue of vascular plants, a new taxonomic reference list for all known #' vascular plants. Sci Data 7, 416 (2020). #' https://doi.org/10.1038/s41597-020-00702-z #' #' @keywords R-package nomenclature taxonomy vascular plants #' #' @examples #' # Ensure that LCVP package is available before running the example. #' # If it is not, see the `lcvplants` package vignette for details #' # on installing the required data package. #' if (requireNamespace("LCVP", quietly = TRUE)) { # Do not run this #' #' # Search by Genus #' lcvp_group_search(c("AA", "Adansonia"), search_by = "Genus") #' #' # Search by Author and keep only accepted names #' lcvp_group_search("Schltr.", search_by = "Author", status = "accepted") #' #' } #'@export lcvp_group_search <- function(group_names, search_by, max_distance = 0.2, bind_result = TRUE, status = c("accepted", "synonym", "unresolved", "external")) { hasData() # Check if LCVP is installed # Check names if (is.factor(group_names)) { group_names <- as.character(group_names) } .names_check(group_names, "group_names") .search_by_check(search_by) .check_status(status) # Fix entry names group_names <- .names_standardize(group_names) # Get position in the table based on group if (search_by == "Genus") { ref_names <- LCVP::tab_position$Genus } if (search_by == "Family") { ref_names <- names(LCVP::lcvp_family) } if (search_by == "Order") { ref_names <- names(LCVP::lcvp_order) } if (search_by == "Author") { # not ready yet ref_names <- names(LCVP::lcvp_authors) } # Get the position list pos_group <- .lcvp_group(group_names, ref_names, max_distance) if (all(is.na(pos_group))) { return(NULL) } else { # Get position list based on the group used if (search_by == "Genus") { pos_list <- .genus_search_multiple(pos_group) } if (search_by == "Family") { pos_list <- LCVP::lcvp_family[pos_group] } if (search_by == "Order") { pos_list <- LCVP::lcvp_order[pos_group] } if (search_by == "Author") { # not ready yet pos_list <- LCVP::lcvp_authors[pos_group] } # Return the actual data.frames result <- list() for (i in seq_along(pos_list)) { result[[i]] <- LCVP::tab_lcvp[pos_list[[i]],] rownames(result[[i]]) <- NULL if (!all(c("accepted", "synonym", "unresolved", "external") %in% status)) { result[[i]] <- result[[i]][result[[i]]$Status %in% status, , drop = FALSE] } } # Bind the results or not if (bind_result) { result <- do.call(rbind, result) if (nrow(result) == 0) { return(NULL) } } else { names(result) <- ref_names[pos_group] } return(result) } }
f0ff6569afe2760c90d3f932ea8b8d26a9cc9601
a189183555031f077a0b52ac55176c808b272e9d
/GIS_4.R
221a9fd653846aa71fac91d9008f358b071963d6
[]
no_license
TomoyaOzawa-DA/GIS
030d427c13e1009178d3c92f21273fa78811469a
07321e584d43859d9d40a647bcfad5d728bbaa8c
refs/heads/main
2023-01-06T21:49:55.093138
2020-10-30T12:22:52
2020-10-30T12:22:52
308,618,531
0
0
null
null
null
null
UTF-8
R
false
false
2,762
r
GIS_4.R
########################################### ### 【地理情報講座#3】Rでの距離計算入門 ### ########################################### ### 1. 2つの店舗間の距離計算 # geosphereというライブラリ install.packages("geosphere") library("geosphere") # distGeoというコマンドで距離計算ができる。単位はm。()内で距離を測りたい2組の緯度経度を指定します。 # 他にもコマンドがありますが、distGEOが一番正確みたいです。 # gas_naha[1, c("longitude", "latitude")]は1行目の"longitude", "latitude"という列に含まれている値を示している。 distGeo(gas_naha[1, c("longitude", "latitude")], gas_naha[2, c("longitude", "latitude")]) # Imapというライブラリでも出来るみたいです。 install.packages("Imap") library(Imap) # gdistというコマンドで距離計算ができる。単位は指定可能 gdist(lon.1 = gas_naha[1, "longitude"], lon.2 =gas_naha[2, "longitude"] , lat.1 = gas_naha[1, "latitude"], lat.2 = gas_naha[2, "latitude"], units = "m") # ちなみに、どっちでも値は等しいです。個人的にはgeosphereの方が書きやすいです。Imapは距離の指定ができるのが嬉しいですね。 ### 2. 複数の店舗間の距離を一気に計算する ### ## 2.1. 1行目の店舗との距離を各店舗に対して算出 for (i in 1:48){ gas_naha[i,"1" ] <- distGeo(gas_naha[1, c("longitude", "latitude")], gas_naha[i, c("longitude", "latitude")]) } ## 2.2.全店舗に対して同じことをやってみます。これぞ自動化。 # エラーが出たので、店舗名をFactorから文字列にしています。 gas_naha$store <- as.character(gas_naha$store) # i行目の店舗との距離を各店舗j(1~48行目)に対して測っている。 for (i in 1:48){ for (j in 1:48){ colname <- gas_naha[i, "store"] gas_naha[j,colname ] <- distGeo(gas_naha[i, c("longitude", "latitude")], gas_naha[j, c("longitude", "latitude")]) } } ## 2.3. 競合店舗の数を集計する for (i in 1:48){ for (j in 1:48){ colname <- gas_naha[i, "store"] gas_naha[j,colname ] <- distGeo(gas_naha[i, c("longitude", "latitude")], gas_naha[j, c("longitude", "latitude")]) gas_naha[j,colname ] <- ifelse(gas_naha[j,colname ] <= 2000, 1, 0) } } for (i in 1:48){ gas_naha[i, "compe"] <- sum(gas_naha[i, 10:57]) -1 } ### 3. 競合の店舗数と価格の関係を分析する ## 3.1. 価格データを結合してデータを整える gas_compe <- gas_naha[, c(1, 58)] price <- read.csv("price.csv") gas_compe <- merge(gas_compe, price, by = 'store') gas_compe <- na.omit(gas_compe) ## 3.2. 回帰分析で検証 out <- lm(data = gas_compe, Price ~ compe) summary(out)
ea7e51bded805246f312f3aabd80c8d966172de9
d5d9f5fb71e07db529cc6c50d50e18577ed6ab20
/scripts/cleaning/wm_math.R
09b0d0878fabf3b4aea235a2be9be4ab4046babc
[]
no_license
laurafdeza/Dissertation
c0ab736cf96227ce49d5833b42587d572deea262
6cd94b2e32d0863eb342fe4ce1ddc49e12672beb
refs/heads/master
2022-04-28T16:47:38.986331
2022-03-09T16:39:05
2022-03-09T16:39:05
251,065,189
0
4
null
2021-03-26T00:08:38
2020-03-29T15:27:13
HTML
UTF-8
R
false
false
3,686
r
wm_math.R
# Working memory # Scores for working memory are not homogeneous—the highest mean score is for the EN, then MA, and then ES # (My hypothesis is that the lower scores are due to the need to remember gender and concepts rather than just the word) # So, since anticipation is closely linked to processing speed, which is another component of working memory, # we are going to use other OSpan measures to ensure that populations are homogeneous. # Namely, we are going to use processing speed in match while ignoring storage (which is the score we tested first). # Load packages library(data.table) library(tidyverse) library(lmerTest) # Load visuospatial WM data and bind them into one dataframe csv_files <- list.files (path = "./data/corsi", pattern = "*.csv", full.names = T) corsi_speed <- as_tibble (rbindlist (lapply (csv_files, fread))) # Select correct trials, rename participants' IDs and participant column corsi_speed <- corsi_speed %>% filter(., correct == 1) %>% rename(., participant = subject_id) corsi_speed$participant <- str_replace(corsi_speed$participant, "ae", "aes") corsi_speed$participant <- str_replace(corsi_speed$participant, "ie", "ies") corsi_speed$participant <- str_replace(corsi_speed$participant, "am", "ams") corsi_speed$participant <- str_replace(corsi_speed$participant, "im", "ims") corsi_speed$participant <- str_replace(corsi_speed$participant, "mo", "mon") # Find random effects for each participant corsi_glm <- lmer(time ~ level + (1 | participant), data = corsi_speed) corsi_ranef <- ranef(corsi_glm) %>% as_tibble() corsi_sel <- corsi_ranef %>% select(., grp, condval, condsd) %>% rename(., participant = grp, corsi_rt = condval, corsi_sd = condsd) ### Repeat process for verbal WM # Load data csv_files <- list.files (path = "./data/ospan", pattern = "*.csv", full.names = T) ospan_speed <- as_tibble (rbindlist (lapply (csv_files, fread))) # Select correct trials, rename participants' IDs ospan_speed <- ospan_speed %>% filter(., correct_resp == 1) ospan_speed$subject_id <- str_replace(ospan_speed$subject_id, "ae", "aes") ospan_speed$subject_id <- str_replace(ospan_speed$subject_id, "ie", "ies") ospan_speed$subject_id <- str_replace(ospan_speed$subject_id, "am", "ams") ospan_speed$subject_id <- str_replace(ospan_speed$subject_id, "im", "ims") ospan_speed$subject_id <- str_replace(ospan_speed$subject_id, "mo", "mon") # Calculate random effects for each participant ospan_glm <- lmer(rt_formula ~ seq_length + (1 | subject_id), data = ospan_speed) ospan_ranef <- ranef(ospan_glm) %>% as_tibble() ospan_sel <- ospan_ranef %>% select(., grp, condval, condsd) %>% rename(., participant = grp, ospan_rt = condval, ospan_sd = condsd) ### merge dataframes and save resulting one as a .csv for analysis wm_speed <- merge(corsi_sel, ospan_sel, by="participant") write.csv(wm_speed,'./data/clean/wm_processing_speed.csv', row.names = F) # # Load all data and bind them into one dataframe (model: https://iamkbpark.com) # csv_files <- list.files (path = "./data/wm", # pattern = "*.csv", # full.names = T) # # wm_ENES <- as_tibble (rbindlist (lapply (csv_files, fread))) # # # Mean of RT for each participant # wm_RT <- wm_ENES %>% # filter(., subj_form_resp == correct_resp) %>% # group_by(., subject_id) %>% # summarize(., mean_rt = mean(rt_formula)) %>% # write.csv(., "./data/clean/wm_EN_ES.csv")
467575501c988c1a86c177d01bf9c8c1ba63d509
c15b64c651fac5e9e6cd41044d8c9766620e55ce
/Statistical Summaries.R
b5b046221cc8ae933c823120a50f6a454dfec140
[]
no_license
kunal09/R_programming
ac846c36e98445b045d8eef2d292ed4ee2433cb2
5a6d9f0e104bd3370657951f8508f7570a71f1ab
refs/heads/master
2021-08-23T23:05:03.119763
2017-12-07T00:58:39
2017-12-07T00:58:39
113,111,109
0
0
null
null
null
null
UTF-8
R
false
false
417
r
Statistical Summaries.R
#Statistical Summaries mydata <- read.table("http://www.sthda.com/upload/boxplot_format.txt",stringsAsFactors = FALSE) mydata #provides a statstical summary of the data summary(mydata$V2) #how many times some value has occured table(mydata$V3) #returns the min value of a function min(mydata$V2) range(mydata$V2) median(mydata$V3) sd(mydata$V2) #will return unique values unique(mydata$V3) length(unique(mydata$V3))
2fec8f48c0e6416725f022ec71550091cfc78c65
7b0c33ec54d5b05d81b10de246a8fb8c23fc0c1d
/dectree.R
c9844e68a3e84341e7eb111046bcc7a7e217ee62
[]
no_license
nirave/nfl-red-wine-supervised-learning
1f9855119f9e422cfe7f8b5cc374a70b9d4458ed
db6c35e0f149b33af3863192118f9ab1314bfc4f
refs/heads/master
2021-01-25T01:03:13.239211
2017-06-18T23:22:13
2017-06-18T23:22:13
null
0
0
null
null
null
null
UTF-8
R
false
false
650
r
dectree.R
library(RWeka) modeldecisiontree_cv<-function(training, cat, dataType, learnType) { train_control <- trainControl(method="repeatedcv", number=10, repeats=3) param_grid <- expand.grid(C = c(0.01, 0.05, .1,.2,.3,.4)) trained<-train(as.formula(paste(cat, " ~.")), data=training, trControl=train_control, tuneGrid = param_grid, method="J48") plot_cross(trained$results[1], trained$results[2], dataType, learnType, "c") return (trained) } modeldecisiontree<-function(training, cat, dataType, learnType) { return(J48(as.formula(paste(cat, " ~.")), data = training, control = Weka_control(M=2,U=FALSE))) }
7527845e5f0efa963409242b9168bbfe85bd4419
29666f9152da5d06e208a248add2393d2130180c
/man/safe_month_min.Rd
986fc4b3f147a5b5215e8949dac5aa47fe6fd36e
[]
no_license
Nicktz/fmxdat
147433ce18ec493fdf3431e4fe40e05fc8e4a253
ec52cdcc65d3431edce67a0ff65b5258a5184bd7
refs/heads/master
2023-08-18T14:03:45.452330
2023-08-08T07:27:38
2023-08-08T07:27:38
205,252,472
0
1
null
null
null
null
UTF-8
R
false
true
1,022
rd
safe_month_min.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/safe_month_min.R \name{safe_month_min} \alias{safe_month_min} \title{safe_month_min} \usage{ safe_month_min(datesel, N = 6) } \arguments{ \item{Ra}{N months back} } \value{ N months back } \description{ Safely goes back N months for monthly data. This is an improved version of using filter(date >= last(date) %-% months(6)) - c.f. below: library(tidyverse);library(lubridate) df <- data.frame(date = rmsfuns::dateconverter(StartDate = lubridate::ymd(20200831), EndDate = lubridate::ymd(20210228), Transform = 'calendarEOM')) df %>% filter(date > last(date) %m-% months(6)) Note that this gives 7 months, not 6. Instead, use: df %>% filter(date >= safe_month_min(last(date), N = 6)) } \examples{ library(tidyverse);library(lubridate) df <- data.frame(date = rmsfuns::dateconverter(StartDate = lubridate::ymd(20200131), EndDate = lubridate::ymd(20210228), Transform = 'calendarEOM')) df \%>\% filter(date >= safe_month_min(last(date), N = 6)) }
8d5bb3849756d6fd7dd986f6cad4f94e6e452588
8c84ea2e7e9c74c085ac1c04d3af2f2818264e97
/scripts/ch11.R
a52f685b6a2a043f3d96a18146218cd98bc8a8c1
[]
no_license
liao961120/rethinking_code
250351fc54e61dd81e8e23bacf9c1e4a4a35b346
5b4d07eb7a71c5735825066c564dec11b399f6aa
refs/heads/main
2023-06-01T13:03:19.506478
2021-06-20T05:16:14
2021-06-20T05:16:14
335,544,180
0
2
null
null
null
null
UTF-8
R
false
false
16,157
r
ch11.R
#+ Setup remotes::install_github('rmcelreath/rethinking', upgrade=F) library(rethinking) #' ## R code 11.1 #+ R code 11.1 library(rethinking) data(chimpanzees) d <- chimpanzees #' ## R code 11.2 #+ R code 11.2 d$treatment <- 1 + d$prosoc_left + 2*d$condition #' ## R code 11.3 #+ R code 11.3 xtabs( ~ treatment + prosoc_left + condition , d ) #' ## R code 11.4 #+ R code 11.4 m11.1 <- quap( alist( pulled_left ~ dbinom( 1 , p ) , logit(p) <- a , a ~ dnorm( 0 , 10 ) ) , data=d ) #' ## R code 11.5 #+ R code 11.5 set.seed(1999) prior <- extract.prior( m11.1 , n=1e4 ) #' ## R code 11.6 #+ R code 11.6 p <- inv_logit( prior$a ) dens( p , adj=0.1 ) #' ## R code 11.7 #+ R code 11.7 m11.2 <- quap( alist( pulled_left ~ dbinom( 1 , p ) , logit(p) <- a + b[treatment] , a ~ dnorm( 0 , 1.5 ), b[treatment] ~ dnorm( 0 , 10 ) ) , data=d ) set.seed(1999) prior <- extract.prior( m11.2 , n=1e4 ) p <- sapply( 1:4 , function(k) inv_logit( prior$a + prior$b[,k] ) ) #' ## R code 11.8 #+ R code 11.8 dens( abs( p[,1] - p[,2] ) , adj=0.1 ) #' ## R code 11.9 #+ R code 11.9 m11.3 <- quap( alist( pulled_left ~ dbinom( 1 , p ) , logit(p) <- a + b[treatment] , a ~ dnorm( 0 , 1.5 ), b[treatment] ~ dnorm( 0 , 0.5 ) ) , data=d ) set.seed(1999) prior <- extract.prior( m11.3 , n=1e4 ) p <- sapply( 1:4 , function(k) inv_logit( prior$a + prior$b[,k] ) ) mean( abs( p[,1] - p[,2] ) ) #' ## R code 11.10 #+ R code 11.10 # trimmed data list dat_list <- list( pulled_left = d$pulled_left, actor = d$actor, treatment = as.integer(d$treatment) ) #' ## R code 11.11 #+ R code 11.11 m11.4 <- ulam( alist( pulled_left ~ dbinom( 1 , p ) , logit(p) <- a[actor] + b[treatment] , a[actor] ~ dnorm( 0 , 1.5 ), b[treatment] ~ dnorm( 0 , 0.5 ) ) , data=dat_list , chains=4 , log_lik=TRUE ) precis( m11.4 , depth=2 ) #' ## R code 11.12 #+ R code 11.12 post <- extract.samples(m11.4) p_left <- inv_logit( post$a ) plot( precis( as.data.frame(p_left) ) , xlim=c(0,1) ) #' ## R code 11.13 #+ R code 11.13 labs <- c("R/N","L/N","R/P","L/P") plot( precis( m11.4 , depth=2 , pars="b" ) , labels=labs ) #' ## R code 11.14 #+ R code 11.14 diffs <- list( db13 = post$b[,1] - post$b[,3], db24 = post$b[,2] - post$b[,4] ) plot( precis(diffs) ) #' ## R code 11.15 #+ R code 11.15 pl <- by( d$pulled_left , list( d$actor , d$treatment ) , mean ) pl[1,] #' ## R code 11.16 #+ R code 11.16 plot( NULL , xlim=c(1,28) , ylim=c(0,1) , xlab="" , ylab="proportion left lever" , xaxt="n" , yaxt="n" ) axis( 2 , at=c(0,0.5,1) , labels=c(0,0.5,1) ) abline( h=0.5 , lty=2 ) for ( j in 1:7 ) abline( v=(j-1)*4+4.5 , lwd=0.5 ) for ( j in 1:7 ) text( (j-1)*4+2.5 , 1.1 , concat("actor ",j) , xpd=TRUE ) for ( j in (1:7)[-2] ) { lines( (j-1)*4+c(1,3) , pl[j,c(1,3)] , lwd=2 , col=rangi2 ) lines( (j-1)*4+c(2,4) , pl[j,c(2,4)] , lwd=2 , col=rangi2 ) } points( 1:28 , t(pl) , pch=16 , col="white" , cex=1.7 ) points( 1:28 , t(pl) , pch=c(1,1,16,16) , col=rangi2 , lwd=2 ) yoff <- 0.01 text( 1 , pl[1,1]-yoff , "R/N" , pos=1 , cex=0.8 ) text( 2 , pl[1,2]+yoff , "L/N" , pos=3 , cex=0.8 ) text( 3 , pl[1,3]-yoff , "R/P" , pos=1 , cex=0.8 ) text( 4 , pl[1,4]+yoff , "L/P" , pos=3 , cex=0.8 ) mtext( "observed proportions\n" ) #' ## R code 11.17 #+ R code 11.17 dat <- list( actor=rep(1:7,each=4) , treatment=rep(1:4,times=7) ) p_post <- link( m11.4 , data=dat ) p_mu <- apply( p_post , 2 , mean ) p_ci <- apply( p_post , 2 , PI ) #' ## R code 11.18 #+ R code 11.18 d$side <- d$prosoc_left + 1 # right 1, left 2 d$cond <- d$condition + 1 # no partner 1, partner 2 #' ## R code 11.19 #+ R code 11.19 dat_list2 <- list( pulled_left = d$pulled_left, actor = d$actor, side = d$side, cond = d$cond ) m11.5 <- ulam( alist( pulled_left ~ dbinom( 1 , p ) , logit(p) <- a[actor] + bs[side] + bc[cond] , a[actor] ~ dnorm( 0 , 1.5 ), bs[side] ~ dnorm( 0 , 0.5 ), bc[cond] ~ dnorm( 0 , 0.5 ) ) , data=dat_list2 , chains=4 , log_lik=TRUE ) #' ## R code 11.20 #+ R code 11.20 compare( m11.5 , m11.4 , func=PSIS ) #' ## R code 11.21 #+ R code 11.21 post <- extract.samples( m11.4 , clean=FALSE ) str(post) #' ## R code 11.22 #+ R code 11.22 m11.4_stan_code <- stancode(m11.4) m11.4_stan <- stan( model_code=m11.4_stan_code , data=dat_list , chains=4 ) compare( m11.4_stan , m11.4 ) #' ## R code 11.23 #+ R code 11.23 post <- extract.samples(m11.4) mean( exp(post$b[,4]-post$b[,2]) ) #' ## R code 11.24 #+ R code 11.24 data(chimpanzees) d <- chimpanzees d$treatment <- 1 + d$prosoc_left + 2*d$condition d$side <- d$prosoc_left + 1 # right 1, left 2 d$cond <- d$condition + 1 # no partner 1, partner 2 d_aggregated <- aggregate( d$pulled_left , list( treatment=d$treatment , actor=d$actor , side=d$side , cond=d$cond ) , sum ) colnames(d_aggregated)[5] <- "left_pulls" #' ## R code 11.25 #+ R code 11.25 dat <- with( d_aggregated , list( left_pulls = left_pulls, treatment = treatment, actor = actor, side = side, cond = cond ) ) m11.6 <- ulam( alist( left_pulls ~ dbinom( 18 , p ) , logit(p) <- a[actor] + b[treatment] , a[actor] ~ dnorm( 0 , 1.5 ) , b[treatment] ~ dnorm( 0 , 0.5 ) ) , data=dat , chains=4 , log_lik=TRUE ) #' ## R code 11.26 #+ R code 11.26 compare( m11.6 , m11.4 , func=PSIS ) #' ## R code 11.27 #+ R code 11.27 # deviance of aggregated 6-in-9 -2*dbinom(6,9,0.2,log=TRUE) # deviance of dis-aggregated -2*sum(dbern(c(1,1,1,1,1,1,0,0,0),0.2,log=TRUE)) #' ## R code 11.28 #+ R code 11.28 library(rethinking) data(UCBadmit) d <- UCBadmit #' ## R code 11.29 #+ R code 11.29 dat_list <- list( admit = d$admit, applications = d$applications, gid = ifelse( d$applicant.gender=="male" , 1 , 2 ) ) m11.7 <- ulam( alist( admit ~ dbinom( applications , p ) , logit(p) <- a[gid] , a[gid] ~ dnorm( 0 , 1.5 ) ) , data=dat_list , chains=4 ) precis( m11.7 , depth=2 ) #' ## R code 11.30 #+ R code 11.30 post <- extract.samples(m11.7) diff_a <- post$a[,1] - post$a[,2] diff_p <- inv_logit(post$a[,1]) - inv_logit(post$a[,2]) precis( list( diff_a=diff_a , diff_p=diff_p ) ) #' ## R code 11.31 #+ R code 11.31 postcheck( m11.7 ) # draw lines connecting points from same dept for ( i in 1:6 ) { x <- 1 + 2*(i-1) y1 <- d$admit[x]/d$applications[x] y2 <- d$admit[x+1]/d$applications[x+1] lines( c(x,x+1) , c(y1,y2) , col=rangi2 , lwd=2 ) text( x+0.5 , (y1+y2)/2 + 0.05 , d$dept[x] , cex=0.8 , col=rangi2 ) } #' ## R code 11.32 #+ R code 11.32 dat_list$dept_id <- rep(1:6,each=2) m11.8 <- ulam( alist( admit ~ dbinom( applications , p ) , logit(p) <- a[gid] + delta[dept_id] , a[gid] ~ dnorm( 0 , 1.5 ) , delta[dept_id] ~ dnorm( 0 , 1.5 ) ) , data=dat_list , chains=4 , iter=4000 ) precis( m11.8 , depth=2 ) #' ## R code 11.33 #+ R code 11.33 post <- extract.samples(m11.8) diff_a <- post$a[,1] - post$a[,2] diff_p <- inv_logit(post$a[,1]) - inv_logit(post$a[,2]) precis( list( diff_a=diff_a , diff_p=diff_p ) ) #' ## R code 11.34 #+ R code 11.34 pg <- with( dat_list , sapply( 1:6 , function(k) applications[dept_id==k]/sum(applications[dept_id==k]) ) ) rownames(pg) <- c("male","female") colnames(pg) <- unique(d$dept) round( pg , 2 ) #' ## R code 11.35 #+ R code 11.35 y <- rbinom(1e5,1000,1/1000) c( mean(y) , var(y) ) #' ## R code 11.36 #+ R code 11.36 library(rethinking) data(Kline) d <- Kline d #' ## R code 11.37 #+ R code 11.37 d$P <- scale( log(d$population) ) d$contact_id <- ifelse( d$contact=="high" , 2 , 1 ) #' ## R code 11.38 #+ R code 11.38 curve( dlnorm( x , 0 , 10 ) , from=0 , to=100 , n=200 ) #' ## R code 11.39 #+ R code 11.39 a <- rnorm(1e4,0,10) lambda <- exp(a) mean( lambda ) #' ## R code 11.40 #+ R code 11.40 curve( dlnorm( x , 3 , 0.5 ) , from=0 , to=100 , n=200 ) #' ## R code 11.41 #+ R code 11.41 N <- 100 a <- rnorm( N , 3 , 0.5 ) b <- rnorm( N , 0 , 10 ) plot( NULL , xlim=c(-2,2) , ylim=c(0,100) ) for ( i in 1:N ) curve( exp( a[i] + b[i]*x ) , add=TRUE , col=grau() ) #' ## R code 11.42 #+ R code 11.42 set.seed(10) N <- 100 a <- rnorm( N , 3 , 0.5 ) b <- rnorm( N , 0 , 0.2 ) plot( NULL , xlim=c(-2,2) , ylim=c(0,100) ) for ( i in 1:N ) curve( exp( a[i] + b[i]*x ) , add=TRUE , col=grau() ) #' ## R code 11.43 #+ R code 11.43 x_seq <- seq( from=log(100) , to=log(200000) , length.out=100 ) lambda <- sapply( x_seq , function(x) exp( a + b*x ) ) plot( NULL , xlim=range(x_seq) , ylim=c(0,500) , xlab="log population" , ylab="total tools" ) for ( i in 1:N ) lines( x_seq , lambda[i,] , col=grau() , lwd=1.5 ) #' ## R code 11.44 #+ R code 11.44 plot( NULL , xlim=range(exp(x_seq)) , ylim=c(0,500) , xlab="population" , ylab="total tools" ) for ( i in 1:N ) lines( exp(x_seq) , lambda[i,] , col=grau() , lwd=1.5 ) #' ## R code 11.45 #+ R code 11.45 dat <- list( T = d$total_tools , P = d$P , cid = d$contact_id ) # intercept only m11.9 <- ulam( alist( T ~ dpois( lambda ), log(lambda) <- a, a ~ dnorm( 3 , 0.5 ) ), data=dat , chains=4 , log_lik=TRUE ) # interaction model m11.10 <- ulam( alist( T ~ dpois( lambda ), log(lambda) <- a[cid] + b[cid]*P, a[cid] ~ dnorm( 3 , 0.5 ), b[cid] ~ dnorm( 0 , 0.2 ) ), data=dat , chains=4 , log_lik=TRUE ) #' ## R code 11.46 #+ R code 11.46 compare( m11.9 , m11.10 , func=PSIS ) #' ## R code 11.47 #+ R code 11.47 k <- PSIS( m11.10 , pointwise=TRUE )$k plot( dat$P , dat$T , xlab="log population (std)" , ylab="total tools" , col=rangi2 , pch=ifelse( dat$cid==1 , 1 , 16 ) , lwd=2 , ylim=c(0,75) , cex=1+normalize(k) ) # set up the horizontal axis values to compute predictions at ns <- 100 P_seq <- seq( from=-1.4 , to=3 , length.out=ns ) # predictions for cid=1 (low contact) lambda <- link( m11.10 , data=data.frame( P=P_seq , cid=1 ) ) lmu <- apply( lambda , 2 , mean ) lci <- apply( lambda , 2 , PI ) lines( P_seq , lmu , lty=2 , lwd=1.5 ) shade( lci , P_seq , xpd=TRUE ) # predictions for cid=2 (high contact) lambda <- link( m11.10 , data=data.frame( P=P_seq , cid=2 ) ) lmu <- apply( lambda , 2 , mean ) lci <- apply( lambda , 2 , PI ) lines( P_seq , lmu , lty=1 , lwd=1.5 ) shade( lci , P_seq , xpd=TRUE ) #' ## R code 11.48 #+ R code 11.48 plot( d$population , d$total_tools , xlab="population" , ylab="total tools" , col=rangi2 , pch=ifelse( dat$cid==1 , 1 , 16 ) , lwd=2 , ylim=c(0,75) , cex=1+normalize(k) ) ns <- 100 P_seq <- seq( from=-5 , to=3 , length.out=ns ) # 1.53 is sd of log(population) # 9 is mean of log(population) pop_seq <- exp( P_seq*1.53 + 9 ) lambda <- link( m11.10 , data=data.frame( P=P_seq , cid=1 ) ) lmu <- apply( lambda , 2 , mean ) lci <- apply( lambda , 2 , PI ) lines( pop_seq , lmu , lty=2 , lwd=1.5 ) shade( lci , pop_seq , xpd=TRUE ) lambda <- link( m11.10 , data=data.frame( P=P_seq , cid=2 ) ) lmu <- apply( lambda , 2 , mean ) lci <- apply( lambda , 2 , PI ) lines( pop_seq , lmu , lty=1 , lwd=1.5 ) shade( lci , pop_seq , xpd=TRUE ) #' ## R code 11.49 #+ R code 11.49 dat2 <- list( T=d$total_tools, P=d$population, cid=d$contact_id ) m11.11 <- ulam( alist( T ~ dpois( lambda ), lambda <- exp(a[cid])*P^b[cid]/g, a[cid] ~ dnorm(1,1), b[cid] ~ dexp(1), g ~ dexp(1) ), data=dat2 , chains=4 , log_lik=TRUE ) #' ## R code 11.50 #+ R code 11.50 num_days <- 30 y <- rpois( num_days , 1.5 ) #' ## R code 11.51 #+ R code 11.51 num_weeks <- 4 y_new <- rpois( num_weeks , 0.5*7 ) #' ## R code 11.52 #+ R code 11.52 y_all <- c( y , y_new ) exposure <- c( rep(1,30) , rep(7,4) ) monastery <- c( rep(0,30) , rep(1,4) ) d <- data.frame( y=y_all , days=exposure , monastery=monastery ) #' ## R code 11.53 #+ R code 11.53 # compute the offset d$log_days <- log( d$days ) # fit the model m11.12 <- quap( alist( y ~ dpois( lambda ), log(lambda) <- log_days + a + b*monastery, a ~ dnorm( 0 , 1 ), b ~ dnorm( 0 , 1 ) ), data=d ) #' ## R code 11.54 #+ R code 11.54 post <- extract.samples( m11.12 ) lambda_old <- exp( post$a ) lambda_new <- exp( post$a + post$b ) precis( data.frame( lambda_old , lambda_new ) ) #' ## R code 11.55 #+ R code 11.55 # simulate career choices among 500 individuals N <- 500 # number of individuals income <- c(1,2,5) # expected income of each career score <- 0.5*income # scores for each career, based on income # next line converts scores to probabilities p <- softmax(score[1],score[2],score[3]) # now simulate choice # outcome career holds event type values, not counts career <- rep(NA,N) # empty vector of choices for each individual # sample chosen career for each individual set.seed(34302) for ( i in 1:N ) career[i] <- sample( 1:3 , size=1 , prob=p ) #' ## R code 11.56 #+ R code 11.56 code_m11.13 <- " data{ int N; // number of individuals int K; // number of possible careers int career[N]; // outcome vector[K] career_income; } parameters{ vector[K-1] a; // intercepts real<lower=0> b; // association of income with choice } model{ vector[K] p; vector[K] s; a ~ normal( 0 , 1 ); b ~ normal( 0 , 0.5 ); s[1] = a[1] + b*career_income[1]; s[2] = a[2] + b*career_income[2]; s[3] = 0; // pivot p = softmax( s ); career ~ categorical( p ); } " #' ## R code 11.57 #+ R code 11.57 dat_list <- list( N=N , K=3 , career=career , career_income=income ) m11.13 <- stan( model_code=code_m11.13 , data=dat_list , chains=4 ) precis( m11.13 , 2 ) #' ## R code 11.58 #+ R code 11.58 post <- extract.samples( m11.13 ) # set up logit scores s1 <- with( post , a[,1] + b*income[1] ) s2_orig <- with( post , a[,2] + b*income[2] ) s2_new <- with( post , a[,2] + b*income[2]*2 ) # compute probabilities for original and counterfactual p_orig <- sapply( 1:length(post$b) , function(i) softmax( c(s1[i],s2_orig[i],0) ) ) p_new <- sapply( 1:length(post$b) , function(i) softmax( c(s1[i],s2_new[i],0) ) ) # summarize p_diff <- p_new[2,] - p_orig[2,] precis( p_diff ) #' ## R code 11.59 #+ R code 11.59 N <- 500 # simulate family incomes for each individual family_income <- runif(N) # assign a unique coefficient for each type of event b <- c(-2,0,2) career <- rep(NA,N) # empty vector of choices for each individual for ( i in 1:N ) { score <- 0.5*(1:3) + b*family_income[i] p <- softmax(score[1],score[2],score[3]) career[i] <- sample( 1:3 , size=1 , prob=p ) } code_m11.14 <- " data{ int N; // number of observations int K; // number of outcome values int career[N]; // outcome real family_income[N]; } parameters{ vector[K-1] a; // intercepts vector[K-1] b; // coefficients on family income } model{ vector[K] p; vector[K] s; a ~ normal(0,1.5); b ~ normal(0,1); for ( i in 1:N ) { for ( j in 1:(K-1) ) s[j] = a[j] + b[j]*family_income[i]; s[K] = 0; // the pivot p = softmax( s ); career[i] ~ categorical( p ); } } " dat_list <- list( N=N , K=3 , career=career , family_income=family_income ) m11.14 <- stan( model_code=code_m11.14 , data=dat_list , chains=4 ) precis( m11.14 , 2 ) #' ## R code 11.60 #+ R code 11.60 library(rethinking) data(UCBadmit) d <- UCBadmit #' ## R code 11.61 #+ R code 11.61 # binomial model of overall admission probability m_binom <- quap( alist( admit ~ dbinom(applications,p), logit(p) <- a, a ~ dnorm( 0 , 1.5 ) ), data=d ) # Poisson model of overall admission rate and rejection rate # 'reject' is a reserved word in Stan, cannot use as variable name dat <- list( admit=d$admit , rej=d$reject ) m_pois <- ulam( alist( admit ~ dpois(lambda1), rej ~ dpois(lambda2), log(lambda1) <- a1, log(lambda2) <- a2, c(a1,a2) ~ dnorm(0,1.5) ), data=dat , chains=3 , cores=3 ) #' ## R code 11.62 #+ R code 11.62 inv_logit(coef(m_binom)) #' ## R code 11.63 #+ R code 11.63 k <- coef(m_pois) a1 <- k['a1']; a2 <- k['a2'] exp(a1)/(exp(a1)+exp(a2))
1b0abf0959dc72cdd79906d448a9bd637dbe456e
e63df753a1819766d0b40dbf035ebaaa2c0d1526
/man/sort.predictions.frame.Rd
1e6a8840440e0547df8c24c99627fb40371fd830
[]
no_license
cran/asremlPlus
cf74d404854a1f2b37e5acefe7fae86132b01a3e
7a5b7b2124a5b736fc49b99f91eba4b6a41b5fb3
refs/heads/master
2023-08-31T16:36:03.614939
2023-08-24T07:30:12
2023-08-24T09:31:08
36,970,354
1
0
null
null
null
null
UTF-8
R
false
false
9,930
rd
sort.predictions.frame.Rd
\name{sort.predictions.frame} \alias{sort.predictions.frame} \title{Sorts a \code{\link{predictions.frame}} according to the predicted values associated with a factor.} \description{Sorts the rows of a \code{\link{predictions.frame}} according to the predicted values in the \code{predictions.frame}. These predicted values are generally obtained using \code{predict.asreml} by specifying a \code{classify} term comprised of one or more variables. Generally, the values associated with one variable are sorted in parallel within each combination of values of the other variables. When there is more than one variable in the \code{classify} term, the sorting is controlled using one or more of \code{sortFactor}, \code{sortParallelToCombo} and \code{sortOrder}. If there is only one variable in the \code{classify} then the \code{\link{predictions.frame}} is sorted according to the order of the complete set of predictions.} \usage{\method{sort}{predictions.frame}(x, decreasing = FALSE, classify, sortFactor = NULL, sortParallelToCombo = NULL, sortNestingFactor = NULL, sortOrder = NULL, ...)} \arguments{ \item{x}{A \code{\link{predictions.frame}}.} \item{decreasing}{A \code{\link{logical}} passed to \code{order} that detemines whether the order is for increasing or decreasing magnitude of the predicted values.} \item{classify}{A \code{\link{character}} string giving the variables that define the margins of the multiway table that was predicted. Multiway tables are specified by forming an interaction type term from the classifying variables, that is, separating the variable names with the \code{:} operator.} \item{sortFactor}{A \code{\link{character}} containing the name of the \code{factor} that indexes the set of predicted values that determines the sorting of the components. If there is only one variable in the \code{classify} term then \code{sortFactor} can be \code{NULL} and the order is defined by the complete set of predicted values. If there is more than one variable in the \code{classify} term then \code{sortFactor} must be set. In this case the \code{sortFactor} is sorted in the same order within each combination of the values of the \code{sortParallelToCombo} variables: the \code{classify} variables, excluding the \code{sortFactor}. There should be only one predicted value for each unique value of \code{sortFactor} within each set defined by a combination of the values of the \code{classify} variables, excluding the \code{sortFactor} \code{factor}. The order to use is determined by either \code{sortParallelToCombo} or \code{sortOrder}.} \item{sortParallelToCombo}{A \code{\link{list}} that specifies a combination of the values of the \code{factor}s and \code{numeric}s, excluding \code{sortFactor}, that are in \code{classify}. Each of the components of the supplied \code{\link{list}} is named for a \code{classify} variable and specifies a single value for it. The combination of this set of values will be used to define a subset of the predicted values whose order will define the order of \code{sortFactor}. Each of the other combinations of the values of the \code{factor}s and \code{numeric}s will be sorted in parallel. If \code{sortParallelToCombo} is \code{NULL} then the first value of each \code{classify} variable, except for the \code{sortFactor} \code{factor}, in the \code{predictions} component is used to define \code{sortParallelToCombo}. If there is only one variable in the \code{classify} then \code{sortParallelToCombo} is ignored.} \item{sortNestingFactor}{A \code{\link{character}} containing the name of the \code{factor} that defines groups of the \code{sortFactor} within which the predicted values are to be ordered. If there is only one variable in the \code{classify} then \code{sortNestingFactor} is ignored.} \item{sortOrder}{A \code{\link{character}} vector whose length is the same as the number of levels for \code{sortFactor} in the \code{predictions.frame}. It specifies the desired order of the levels in the reordered the \code{\link{predictions.frame}}. The argument \code{sortParallelToCombo} is ignored. The following creates a \code{sortOrder} vector \code{levs} for factor \code{f} based on the values in \code{x}: \code{levs <- levels(f)[order(x)]}.} \item{\dots}{further arguments passed to or from other methods. Not used at present.} } \value{The sorted \code{\link{predictions.frame}}. Also, the \code{sortFactor} and \code{sortOrder} attributes are set.} \details{The basic technique is to change the order of the levels of the \code{sortFactor} within the \code{predictions.frame} so that they are ordered for a subset of predicted values, one for each levels of the \code{sortFactor}. When the \code{classify} term consists of more than one variable then a subset of one combination of the values of variables other than the \code{sortFactor}, the \code{sortParallelToCombo} combination, must be chosen for determining the order of the \code{sortFactor} levels. Then the sorting of the rows (and columns) will be in parallel within each combination of the values of \code{sortParallelToCombo} variables: the \code{classify} term, excluding the \code{sortFactor}.} \author{Chris Brien} \seealso{\code{\link{as.predictions.frame}}, \code{\link{print.predictions.frame}}, \code{\link{sort.alldiffs}}, \cr \code{\link{predictPlus.asreml}}, \code{\link{predictPresent.asreml}}} \examples{ ##Halve WaterRunoff data to reduce time to execute data(WaterRunoff.dat) tmp <- subset(WaterRunoff.dat, Date == "05-18") ##Use asreml to get predictions and associated statistics \dontrun{ #Analyse pH m1.asr <- asreml(fixed = pH ~ Benches + (Sources * (Type + Species)), random = ~ Benches:MainPlots, keep.order=TRUE, data= tmp) current.asrt <- as.asrtests(m1.asr, NULL, NULL) current.asrt <- as.asrtests(m1.asr) current.asrt <- rmboundary(current.asrt) m1.asr <- current.asrt$asreml.obj #Get predictions and associated statistics TS.diffs <- predictPlus.asreml(classify = "Sources:Type", asreml.obj = m1.asr, tables = "none", wald.tab = current.asrt$wald.tab, present = c("Type","Species","Sources")) #Use sort.predictions.frame and save order for use with other response variables TS.preds <- TS.diffs$predictions TS.preds.sort <- sort(TS.preds, sortFactor = "Sources", sortParallelToCombo = list(Type = "Control")) sort.order <- attr(TS.preds.sort, which = "sortOrder") #Analyse Turbidity m2.asr <- asreml(fixed = Turbidity ~ Benches + (Sources * (Type + Species)), random = ~ Benches:MainPlots, keep.order=TRUE, data= tmp) current.asrt <- as.asrtests(m2.asr) #Use pH sort.order to sort Turbidity alldiffs object TS.diffs2 <- predictPlus(m2.asr, classify = "Sources:Type", pairwise = FALSE, error.intervals = "Stand", tables = "none", present = c("Type","Species","Sources")) TS.preds2 <- TS.diffs2$predictions TS.preds2.sort <- sort(TS.preds, sortFactor = "Sources", sortOder = sort.order) } ## Use lmeTest and emmmeans to get predictions and associated statistics if (requireNamespace("lmerTest", quietly = TRUE) & requireNamespace("emmeans", quietly = TRUE)) { #Analyse pH m1.lmer <- lmerTest::lmer(pH ~ Benches + (Sources * (Type + Species)) + (1|Benches:MainPlots), data=na.omit(tmp)) TS.emm <- emmeans::emmeans(m1.lmer, specs = ~ Sources:Type) TS.preds <- summary(TS.emm) den.df <- min(TS.preds$df, na.rm = TRUE) ## Modify TS.preds to be compatible with a predictions.frame TS.preds <- as.predictions.frame(TS.preds, predictions = "emmean", se = "SE", interval.type = "CI", interval.names = c("lower.CL", "upper.CL")) #Use sort.predictions.frame and save order for use with other response variables TS.preds.sort <- sort(TS.preds, classify = "Sources:Type", sortFactor = "Sources", sortParallelToCombo = list(Type = "Control")) sort.order <- attr(TS.preds.sort, which = "sortOrder") #Analyse Turbidity m2.lmer <- lmerTest::lmer(Turbidity ~ Benches + (Sources * (Type + Species)) + (1|Benches:MainPlots), data=na.omit(tmp)) TS.emm <- emmeans::emmeans(m2.lmer, specs = ~ Sources:Type) TS.preds <- summary(TS.emm) den.df <- min(TS.preds$df, na.rm = TRUE) ## Modify TS.preds to be compatible with a predictions.frame TS.preds <- as.predictions.frame(TS.preds, predictions = "emmean", se = "SE", interval.type = "CI", interval.names = c("lower.CL", "upper.CL")) } } \keyword{asreml}
68f5d6a14bdf1707f4458025b1f41906ddb1c6fd
4843d2c1c8bc436d4ddc660cb4f9a90d33713382
/ARD/Castle_Farm/Rhizosphere/full_analysis.R
a268f4b03c71f0e0cc471923abe13d132b98e422
[]
no_license
harrisonlab/Metabarcoding_projects
530ec0fed4d4ad45cbb47d600f2a8be1182da1fd
ac0590843eda264502802ec7c614a1c7d75728f9
refs/heads/master
2022-03-19T15:11:29.620885
2022-02-24T10:14:17
2022-02-24T10:14:17
41,956,604
1
1
null
null
null
null
UTF-8
R
false
false
61,247
r
full_analysis.R
#=============================================================================== # Load libraries #=============================================================================== library(DESeq2) library(BiocParallel) library(data.table) library(plyr) library(dplyr) library(ggplot2) library(devtools) library(Biostrings) library(vegan) library(lmPerm) library(phyloseq) library(ape) register(MulticoreParam(12)) load_all("~/pipelines/metabarcoding/scripts/myfunctions") environment(plot_ordination) <- environment(ordinate) <- environment(plot_richness) <- environment(phyloseq::ordinate) #assignInNamespace("plot_ordination",value=plot_ordination,ns="phyloseq") #=============================================================================== # Load data #=============================================================================== # load otu count table countData <- read.table("BAC.otus_table.txt",header=T,sep="\t",row.names=1, comment.char = "") # load sample metadata colData <- read.table("colData",header=T,sep="\t",row.names=1) # load taxonomy data taxData <- read.table("BAC.taxa",header=F,sep=",",row.names=1) # reorder columns taxData<-taxData[,c(1,3,5,7,9,11,13,2,4,6,8,10,12,14)] # add best "rank" at 0.65 confidence and tidy-up the table taxData<-phyloTaxaTidy(taxData,0.65) # get unifrac dist phylipData <- fread.phylip("BAC.phy") njtree <- nj(as.dist(phylipData)) # save data into a list ubiom_BAC <- list( countData=countData, colData=colData, taxData=taxData, phylipData=phylipData, njtree=njtree, RHB="BAC" ) # Fungi all in one call ubiom_FUN <- list( countData=read.table("FUN.otus_table.txt",header=T,sep="\t",row.names=1,comment.char = ""), colData=read.table("colData",header=T,sep="\t",row.names=1), taxData=phyloTaxaTidy(read.table("FUN.taxa",header=F,sep=",",row.names=1)[,c(1,3,5,7,9,11,13,2,4,6,8,10,12,14)],0.65), phylipData=fread.phylip("FUN.phy"), RHB="FUN" ) ubiom_FUN$njtree <- nj(as.dist(ubiom_FUN$phylipData)) # Oomycetes ubiom_OO <- list( countData=read.table("OO.otus_table.txt",header=T,sep="\t",row.names=1,comment.char = ""), colData=read.table("colData2",header=T,sep="\t",row.names=1), taxData=phyloTaxaTidy(read.table("OO.taxa",header=F,sep=",",row.names=1)[,c(1,3,5,7,9,11,13,2,4,6,8,10,12,14)],0.65), phylipData=fread.phylip("OO.phy"), RHB="OO" ) ubiom_OO$njtree <- nj(as.dist(ubiom_OO$phylipData)) rownames(ubiom_OO$colData) <- paste0("X",gsub("_","\\.",ubiom_OO$colData$name),"_",sub("D.*","",rownames(ubiom_OO$colData))) rownames(ubiom_OO$colData) <- sub("XG","G",rownames(ubiom_OO$colData)) # Nematodes ubiom_NEM <- list( countData=read.table("NEM.otus_table.txt",header=T,sep="\t",row.names=1,comment.char = ""), colData=read.table("colData2",header=T,sep="\t",row.names=1), taxData=phyloTaxaTidy(read.table("NEM.taxa",header=F,sep=",",row.names=1)[,c(1,3,5,7,9,11,13,2,4,6,8,10,12,14)],0.65), phylipData=fread.phylip("NEM.phy"), RHB="NEM" ) ubiom_NEM$njtree <- nj(as.dist(ubiom_NEM$phylipData)) rownames(ubiom_NEM$colData) <- paste0("X",gsub("_","\\.",ubiom_NEM$colData$name),"_",sub("D.*","",rownames(ubiom_NEM$colData))) rownames(ubiom_NEM$colData) <- sub("XG","G",rownames(ubiom_NEM$colData)) #=============================================================================== # Combine species #=============================================================================== #### combine species at 0.95 (default) confidence (if they are species) # Fungi invisible(mapply(assign, names(ubiom_FUN), ubiom_FUN, MoreArgs=list(envir = globalenv()))) combinedTaxa <- combineTaxa("FUN.taxa") countData <- combCounts(combinedTaxa,countData) taxData <- combTaxa(combinedTaxa,taxData) ubiom_FUN$countData <- countData ubiom_FUN$taxData <- taxData # Nematodes # oomycetes #=============================================================================== # ****FUNGI**** #=============================================================================== invisible(mapply(assign, names(ubiom_FUN), ubiom_FUN, MoreArgs=list(envir = globalenv()))) #=============================================================================== # Create DEseq objects #=============================================================================== # ensure colData rows and countData columns have the same order colData <- colData[names(countData),] # remove low count and control samples myfilter <- (colSums(countData)>=1000) & colData$Condition!="C" # remove Pair of any sample with a low count exclude<-which(!myfilter) myfilter <- myfilter&sapply(colData$Pair,function(x) length(which(x==colData$Pair[-exclude]))>1) # apply filter colData <- droplevels(colData[myfilter,]) countData <- countData[,myfilter] # simple Deseq design design<-~1 #create DES object # colnames(countData) <- row.names(colData) dds<-DESeqDataSetFromMatrix(countData,colData,design) #=============================================================================== # **Normalised** #=============================================================================== sizeFactors(dds) <-sizeFactors(estimateSizeFactors(dds)) #=============================================================================== # Alpha diversity analysis #=============================================================================== # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"Alpha.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"),limits=c(0,1000,"Chao1"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"ALPHA_stats.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"OTU_counts.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"PCA.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"PCA_loc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) ggsave(paste(RHB,"PCA_Original.pdf",sep="_"),plotOrd(d,colData,design="Condition",continuous=F,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) g <- plotOrd(d,colData,design="Condition",continuous=F,axes=c(1,3),plot="Label",labelSize=2.5,cbPalette=T,label="Pair",legend="bottom") g$layers[[1]] <- NULL g <- g + geom_point(size = 0, stroke = 0) # OR geom_point(shape = "") + g <- g + geom_label(show.legend = FALSE,size=2.5) g <- g + guides(colour = guide_legend(override.aes = list(size = 5, shape = c(utf8ToInt("H"), utf8ToInt("S"))))) g <- g + scale_colour_manual(name = "Condition", breaks = c("H","S"), labels = c("",""),values=c("#000000", "#E69F00")) ggsave(paste(RHB,"PCA_NEW_1vs3.pdf",sep="_"),g) g_fun_fig4 <- plotOrd(d,colData,design="Condition",facet="Pair",axes=c(1,2),alpha=0.75,pointSize=2,cbPalette=T,legend="bottom") + geom_line(aes(group=facet),alpha=0.1,linetype=3,colour="#000000") g2 <- g_fun_fig4 + ggtitle("B")+ theme_classic_thin(base_size=12)%+replace% theme(plot.title = element_text(hjust = -0.1,size=14),legend.position="bottom") ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"PCA_without_paired_var.pdf",sep="_"),plotOrd(d,colData,design="Condition",continuous=F,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"PCA_ANOVA.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"Unifrac_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"PERMANOVA_unifrac.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"BRAY_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top7phyla = names(sort(phylum.sum, TRUE))[1:7] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top7phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) # calculate ordination Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") # plot with plot_ordination theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"NMDS_taxa_by_Condition.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) dev.off() # theme_set(theme_classic_thin()) # plot_ordination(myphylo, ordu, type="samples", shape="Condition", color="Location",continuous=T) # PCoA # ordu = ordinate(myphylo, "PCoA", "unifrac", weighted=TRUE) # d <-t(data.frame(t(ordu$vectors)*ordu$values$Relative_eig)) # plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PCoA1",ylabel="PCoA2") #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[ rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"diff.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[ res.merge[padj<=0.05]$OTU],paste0(RHB,".sig.fa")) #============================================================================== # **qPCR** #=============================================================================== dds<-DESeqDataSetFromMatrix(countData,colData,design) # Correction from aboslute quantification sizeFactors(dds) <- colData$funq # Correction from aboslute quantification v2 # sizeFactors(dds) <- sizeFactors(dds)/colData$funq #=============================================================================== # Alpha diversity analysis #=============================================================================== # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"qPCR_Alpha.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"qPCR_ALPHA_stats.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"qPCR_OTU_counts.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"qPCR_PCA.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"qPCR_PCA_loc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2,ylims=c(-2,4))) ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"qPCR_PCA_deloc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"qPCR_PCA_ANOVA.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"qPCR_Unifrac_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"qPCR_PERMANOVA_unifrac.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"qPC_BRAY_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top7phyla = names(sort(phylum.sum, TRUE))[1:7] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top7phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"qPCR_NMDS_taxa_by_Condition.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum",ylims=c(-0.8,1.2),xlims=c(-0.8,1.2))+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum",ylims=c(-0.8,1.2),xlims=c(-0.8,1.2))+ facet_wrap(~phylum, 3) dev.off() #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[ rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"qPCR_diff.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[ res.merge[ padj<=0.05]$OTU],paste0(RHB,".qPCR_sig.fa")) #=============================================================================== # ****BACTERIA**** #=============================================================================== invisible(mapply(assign, names(ubiom_BAC), ubiom_BAC, MoreArgs=list(envir = globalenv()))) #=============================================================================== # Create DEseq objects #=============================================================================== # ensure colData rows and countData columns have the same order colData <- colData[names(countData),] # remove low count and control samples myfilter <- (colSums(countData)>=1000) & colData$Condition!="C" # remove Pair of any sample with a low count exclude<-which(!myfilter) myfilter <- myfilter&sapply(colData$Pair,function(x) length(which(x==colData$Pair[-exclude]))>1) # apply filter colData <- droplevels(colData[myfilter,]) countData <- countData[,myfilter] # simple Deseq design design<-~1 #create DES object # colnames(countData) <- row.names(colData) dds<-DESeqDataSetFromMatrix(countData,colData,design) #=============================================================================== # ****Normalised**** #=============================================================================== sizeFactors(dds) <-sizeFactors(estimateSizeFactors(dds)) #=============================================================================== # Alpha diversity analysis #=============================================================================== # plot alpha diversity - plot_alpha will convert normalised abundances to integer values # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"Alpha.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"),limits=c(0,2000,"Chao1"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"ALPHA_stats.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ ### read accumulation filter # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"OTU_counts.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"PCA.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"PCA_loc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) g_bac_fig4 <- plotOrd(d,colData,design="Condition",facet="Pair",axes=c(1,3),ylims=c(-2,4),alpha=0.75,pointSize=2,cbPalette=T,legend="none") + geom_line(aes(group=facet),alpha=0.1,linetype=3,colour="#000000") g1 <- g_bac_fig4 + ggtitle("A")+ theme_classic_thin(base_size=12)%+replace% theme(plot.title = element_text(hjust = -0.07,size=14),legend.position="none") g <- plotOrd(d,colData,shape="Condition",design="Pair",continuous=T,axes=c(1,3),ylims=c(-2,4),alpha=0.75,pointSize=2) + + scale_colour_gradient(guide=F,low="red",high="yellow") ggsave("NEW_Figure_4.pdf",grid.arrange(g1,g2,nrow=2),width=7,height=8) ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"PCA_deloc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"PCA_ANOVA.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"Unifrac_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"PERMANOVA_unifrac.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"BRAY_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top12phyla = names(sort(phylum.sum, TRUE))[1:12] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top12phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) # calculate ordination Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") # plot with plot_ordination theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"NMDS_taxa_by_Condition.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) dev.off() #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"diff.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[res.merge[padj<=0.05]$OTU],paste0(RHB,".sig.fa")) #============================================================================== # ****qPCR**** #=============================================================================== dds<-DESeqDataSetFromMatrix(countData,colData,design) # Correction from aboslute quantification sizeFactors(dds) <- colData$bacq # Correction from aboslute quantification v2 # sizeFactors(dds) <- sizeFactors(dds)/colData$bacq #=============================================================================== # Alpha diversity analysis #=============================================================================== # plot alpha diversity - plot_alpha will convert normalised abundances to integer values # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"qPCR_Alpha.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"),limits=c(0,2000,"Chao1"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"qPCR_ALPHA_stats.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"qPCR_OTU_counts.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"qPCR_PCA.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"qPCR_PCA_loc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"qPCR_PCA_deloc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"qPCR_PCA_ANOVA.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"qPCR_Unifrac_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"qPCR_BRAY_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"qPCR_PERMANOVA_unifrac.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top12phyla = names(sort(phylum.sum, TRUE))[1:12] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top12phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"qPCR_NMDS_taxa_by_Condition.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum",ylims=c(-0.8,1.2),xlims=c(-0.8,1.2))+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum",ylims=c(-0.8,1.2),xlims=c(-0.8,1.2))+ facet_wrap(~phylum, 3) dev.off() #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"qPCR_diff.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[res.merge[padj<=0.05]$OTU],paste0(RHB,".qPCR_sig.fa")) #=============================================================================== # ****OOMYCETES**** #=============================================================================== invisible(mapply(assign, names(ubiom_OO), ubiom_OO, MoreArgs=list(envir = globalenv()))) #=============================================================================== # Create DEseq objects #=============================================================================== # ensure colData rows and countData columns have the same order colData <- colData[names(countData),] # remove low count and control samples myfilter <- (colSums(countData)>=1000) & colData$Condition!="C" # remove Pair of any sample with a low count exclude<-which(!myfilter) myfilter <- myfilter&sapply(colData$Pair,function(x) length(which(x==colData$Pair[-exclude]))>1) # apply filter colData <- droplevels(colData[myfilter,]) countData <- countData[,myfilter] # simple Deseq design design<-~1 #create DES object # colnames(countData) <- row.names(colData) dds<-DESeqDataSetFromMatrix(countData,colData,design) # calculate size factors sizeFactors(dds) <-sizeFactors(estimateSizeFactors(dds)) ### filter to remove OTUs which are unlikely part of the correct kingdom (best to do this before Alpha diversity analysis) myfilter <- row.names(countData[row.names(countData) %in% row.names(taxData[(taxData$kingdom=="SAR"|as.numeric(taxData$k_conf)<=0.5),]),]) dds <- dds[myfilter,] #=============================================================================== # Alpha diversity analysis #=============================================================================== # plot alpha diversity - plot_alpha will convert normalised abundances to integer values # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"Alpha.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"ALPHA_stats.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"OTU_counts.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"PCA.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"PCA_loc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"PCA_deloc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"PCA_ANOVA.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"Unifrac_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"PERMANOVA_unifrac.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"BRAY_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top7phyla = names(sort(phylum.sum, TRUE))[1:7] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top7phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) # calculate ordination Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") # plot with plot_ordination theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"NMDS_taxa_by_Condition.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) dev.off() #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"diff.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[res.merge[padj<=0.05]$OTU],paste0(RHB,".sig.fa")) #============================================================================== # **qPCR** #=============================================================================== dds<-DESeqDataSetFromMatrix(countData,colData,design) # Correction from aboslute quantification of fungal ITS sizeFactors(dds) <- sizeFactors(estimateSizeFactors(dds))/left_join(colData,ubiom_FUN$colData)$funq sizeFactors(dds) <- left_join(colData,ubiom_FUN$colData)$funq ### filter to remove OTUs which are unlikely part of the correct kingdom (best to do this before Alpha diversity analysis) myfilter <- row.names(countData[row.names(countData) %in% row.names(taxData[(taxData$kingdom=="SAR"|as.numeric(taxData$k_conf)<=0.5),]),]) dds <- dds[myfilter,] #=============================================================================== # Alpha diversity analysis #=============================================================================== # plot alpha diversity - plot_alpha will convert normalised abundances to integer values # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"Alpha_qPCR.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"ALPHA_stats_qPCR.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"OTU_counts_qPCR.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"PCA_qPCR.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"PCA_loc_qPCR.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"PCA_deloc_qPCR.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"PCA_ANOVA_qPCR.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"Unifrac_NMDS_qPCR.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"PERMANOVA_unifrac_qPCR.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"BRAY_NMDS_qPCR.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top7phyla = names(sort(phylum.sum, TRUE))[1:7] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top7phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) # calculate ordination Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") # plot with plot_ordination theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"NMDS_taxa_by_Condition_qPCR.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) dev.off() #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"diff_qPCR.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[res.merge[padj<=0.05]$OTU],paste0(RHB,".sig_qPCR.fa")) #=============================================================================== # ****NEMATODE**** #=============================================================================== invisible(mapply(assign, names(ubiom_NEM), ubiom_NEM, MoreArgs=list(envir = globalenv()))) #=============================================================================== # Create DEseq objects #=============================================================================== # ensure colData rows and countData columns have the same order colData <- colData[names(countData),] # remove low count and control samples myfilter <- (colSums(countData)>=1000) & colData$Condition!="C" # remove Pair of any sample with a low count exclude<-which(!myfilter) myfilter <- myfilter&sapply(colData$Pair,function(x) length(which(x==colData$Pair[-exclude]))>1) # apply filter colData <- droplevels(colData[myfilter,]) countData <- countData[,myfilter] # simple Deseq design design<-~1 #create DES object # colnames(countData) <- row.names(colData) dds<-DESeqDataSetFromMatrix(countData,colData,design) # calculate size factors sizeFactors(dds) <-sizeFactors(estimateSizeFactors(dds)) ### filter to remove OTUs which are unlikely part of the correct kingdom (best to do this before Alpha diversity analysis) myfilter <- row.names(taxData[as.number(taxData$c_conf)>0.9 & as.number(taxData$o_conf)>0.9,]) dds <- dds[rownames(dds)%in%myfilter,] #=============================================================================== # Alpha diversity analysis #=============================================================================== # plot alpha diversity - plot_alpha will convert normalised abundances to integer values # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) ggsave(paste(RHB,"Alpha.pdf",sep="_"),plot_alpha(counts(dds,normalize=T),colData,design="Condition",colour="Condition",cbPalette=T,legend="hidden",measures=c("Chao1", "Shannon", "Simpson","Observed"))) ### permutation based anova on diversity index ranks ### # get the diversity index data all_alpha_ord <- plot_alpha(counts(dds,normalize=T),colData,design="Condition",returnData=T) # add column names as row to metadata (or use tribble) colData$samples <- rownames(colData) # join diversity indices and metadata all_alpha_ord <- as.data.table(inner_join(all_alpha_ord,colData,by=c("Samples"="samples"))) # perform anova for each index colData$Pair<-as.factor(colData$Pair) sink(paste(RHB,"ALPHA_stats.txt",sep="_")) setkey(all_alpha_ord,S.chao1) print("Chao1") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.chao1))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,shannon) print("Shannon") summary(aovp(as.numeric(as.factor(all_alpha_ord$shannon))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,simpson) print("simpson") summary(aovp(as.numeric(as.factor(all_alpha_ord$simpson))~Pair+Condition,all_alpha_ord)) setkey(all_alpha_ord,S.ACE) print("ACE") summary(aovp(as.numeric(as.factor(all_alpha_ord$S.ACE))~Pair+Condition,all_alpha_ord)) sink() #=============================================================================== # Filter data #============================================================================ ### read accumulation filter # plot cummulative reads (will also produce a data table "dtt" in the global environment) ggsave(paste(RHB,"OTU_counts.pdf",sep="_"),plotCummulativeReads(counts(dds,normalize=T))) dds <- dds[rowSums(counts(dds, normalize=T))>4,] #=============================================================================== # Beta diversity PCA/NMDS #=============================================================================== ### PCA ### # perform PC decomposition of DES object mypca <- des_to_pca(dds) # to get pca plot axis into the same scale create a dataframe of PC scores multiplied by their variance d <-t(data.frame(t(mypca$x)*mypca$percentVar)) # Add spatial information as a numeric and plot colData$Location<-as.number(colData$Pair) # plot the PCA pdf(paste(RHB,"PCA.pdf",sep="_")) plotOrd(d,colData,design="Condition",xlabel="PC1",ylabel="PC2") plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2") dev.off() ggsave(paste(RHB,"PCA_loc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2",alpha=0.75,pointSize=2)) ### remove spatial information (this uses the factor "Pair" not the numeric "Location") and plot pc.res <- resid(aov(mypca$x~colData$Pair,colData)) d <- t(data.frame(t(pc.res*mypca$percentVar))) ggsave(paste(RHB,"PCA_deloc.pdf",sep="_"),plotOrd(d,colData,shape="Condition",design="Location",continuous=T,xlabel="PC1",ylabel="PC2")) # ANOVA sink(paste(RHB,"PCA_ANOVA.txt",sep="_")) print("ANOVA") lapply(seq(1:3),function(x) summary(aov(mypca$x[,x]~Pair+Condition,colData(dds)))) print("PERMANOVA") lapply(seq(1:3),function(x) summary(aovp(mypca$x[,x]~Pair+Condition,colData(dds)))) sink() # Sum of variances in PC scores sum_squares <- t(apply(mypca$x,2,function(x) t(summary(aov(x~Pair+Condition,colData(dds)))[[1]][2])) ) colnames(sum_squares) <- c("Pair","Condition","residual") x<-t(apply(sum_squares,1,prop.table)) perVar <- x * mypca$percentVar colSums(perVar) colSums(perVar)/sum(colSums(perVar))*100 ### NMDS ### # phyloseq has functions (using Vegan) for making NMDS plots myphylo <- ubiom_to_phylo(list(counts(dds,normalize=T),taxData,colData)) # add tree to phyloseq object phy_tree(myphylo) <- njtree # calculate NMDS ordination using weighted unifrac scores ordu = ordinate(myphylo, "NMDS", "unifrac", weighted=TRUE) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"Unifrac_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # permanova of unifrac distance sink(paste(RHB,"PERMANOVA_unifrac.txt",sep="_")) adonis(distance(myphylo,"unifrac",weighted=T)~Pair+Condition,colData(dds),parallel=12,permutations=9999) sink() # calculate NMDS ordination with bray-curtis distance matrix ordu = ordinate(myphylo, "NMDS", "bray",stratmax=50) # plot with plotOrd (or use plot_ordination) ggsave(paste(RHB,"BRAY_NMDS.pdf",sep="_"),plotOrd(ordu$points,colData,shape="Condition",design="Location",continuous=T,xlabel="NMDS1",ylabel="NMDS2",alpha=0.75,pointSize=2)) # phyla plots - keep top 7 phyla only phylum.sum = tapply(taxa_sums(myphylo), tax_table(myphylo)[, "phylum"], sum, na.rm=TRUE) top7phyla = names(sort(phylum.sum, TRUE))[1:7] myphylo_slim = prune_taxa((tax_table(myphylo)[, "phylum"] %in% top7phyla), myphylo) # split phylo into H and S H <- prune_samples(colData$Condition=="H",myphylo_slim) S <- prune_samples(colData$Condition=="S",myphylo_slim) # calculate ordination Hord <- ordinate(H, "NMDS", "bray") Sord <- ordinate(S, "NMDS", "bray") # plot with plot_ordination theme_set(theme_facet_blank(angle=0,vjust=0,hjust=0.5)) pdf(paste(RHB,"NMDS_taxa_by_Condition.pdf",sep="_")) plot_ordination(H, Hord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) plot_ordination(S, Sord, type="taxa", color="phylum")+ facet_wrap(~phylum, 3) dev.off() #=============================================================================== # differential analysis #=============================================================================== # filter for low counts - this can affect the FD probability and DESeq2 does apply its own filtering for genes/otus with no power # but, no point keeping OTUs with 0 count dds<-dds[rowSums(counts(dds,normalize=T))>0,] # p value for FDR cutoff alpha <- 0.1 # the full model full_design <- ~Pair + Condition # add full model to dds object design(dds) <- full_design # calculate fit dds <- DESeq(dds,parallel=T) # calculate results for default contrast (S vs H) res <- results(dds,alpha=alpha,parallel=T) # merge results with taxonomy data res.merge <- data.table(inner_join(data.table(OTU=rownames(res),as.data.frame(res)),data.table(OTU=rownames(taxData),taxData))) write.table(res.merge, paste(RHB,"diff.txt",sep="_"),quote=F,sep="\t",na="",row.names=F) # output sig fasta writeXStringSet(readDNAStringSet(paste0(RHB,".otus.fa"))[res.merge[padj<=0.05]$OTU],paste0(RHB,".sig.fa"))
162b8375e5a5b2fd72795ed754369b93c99aaaca
a175d771d8fbe234ca1ca55f8ca7bf13aa8d847e
/Linear regression on Housing Price dataset.R
d812181ebf94116d360f5e312c924cc196d0780b
[]
no_license
HarshadaPatil19/Linear-Regression
0633aebe2e33d3ac087cbce3870c2883a0c5e7ae
c2d6430e3d5eb67ff530e04519d9b5cb11fa88bc
refs/heads/main
2023-03-25T15:21:05.620903
2021-03-13T19:00:07
2021-03-13T19:00:07
347,454,123
0
0
null
null
null
null
UTF-8
R
false
false
13,234
r
Linear regression on Housing Price dataset.R
# library(ggplot2) library(ggthemes) library(scales) library(dplyr) library(gridExtra) library(corrplot) library(GGally) library(e1071) library(DAAG) # Read Data File data = read.csv("C:/Users/harsh/Downloads/Property_Price_Train.csv", na.strings=c("","NA")) data # Data dim dim(data) # structure of the data str(data) # Summary summary(data) # Data View View(data) # Remove ID variable containing unique values data <- data[-1] data # Detecting NA values colSums(is.na(data)) # Missing value analysis Missing_index <- data %>% is.na() %>% colSums() * 100 Missing_index <- sort(round(Missing_index[Missing_index > 0], 2), decreasing = TRUE) Missing_index View(Missing_index) # % of NA's in dataframe sum(is.na(data))/prod(dim(data)) * 100 # % of NA's contains as rows nrow(data[!complete.cases(data),]) / nrow(data) * 100 # Segregating numeric and factor data data.numeric <- data[sapply(data, is.numeric)] data.numeric data.factor <- data[sapply(data, is.factor)] data.factor dim(data.numeric) dim(data.factor) # Numerical data analysis for cleaning str(data.numeric) summary(data.numeric) # Need to convert datatype from numeic to factor # 1. Overall_Material # 2. House_Condition # 3. Construction_Year # 4. Remodel_Year # 5. Kitchen_Above_Grade # 6. Rooms_Above_Grade # 7. Fireplaces # 8. Garage_Size # 9. Garage_Built_Year # 10. Month_Sold # 11. Year_Sold # 12. "Underground_Full_Bathroom", # 13. "Underground_Half_Bathroom", # 14. "Full_Bathroom_Above_Grade", # 15. "Half_Bathroom_Above_Grade", # 16. "Bedroom_Above_Grade", data$Overall_Material <- as.factor(data$Overall_Material) data$House_Condition <- as.factor(data$House_Condition) data$Construction_Year <- as.factor(data$Construction_Year) data$Remodel_Year <- as.factor(data$Remodel_Year) data$Kitchen_Above_Grade <- as.factor(data$Kitchen_Above_Grade) data$Rooms_Above_Grade <- as.factor(data$Rooms_Above_Grade) data$Fireplaces <- as.factor(data$Fireplaces) data$Garage_Size <- as.factor(data$Garage_Size) data$Garage_Built_Year <- as.factor(data$Garage_Built_Year) data$Month_Sold <- as.factor(data$Month_Sold) data$Year_Sold <- as.factor(data$Year_Sold) data$Underground_Full_Bathroom <- as.factor(data$Underground_Full_Bathroom) data$Underground_Half_Bathroom <- as.factor(data$Underground_Half_Bathroom) data$Full_Bathroom_Above_Grade <- as.factor(data$Full_Bathroom_Above_Grade) data$Half_Bathroom_Above_Grade <- as.factor(data$Half_Bathroom_Above_Grade) data$Bedroom_Above_Grade <- as.factor(data$Bedroom_Above_Grade) ## Again data segregation data.numeric <- data[sapply(data, is.numeric)] data.numeric dim(data.numeric) data.factor <- data[sapply(data, is.factor)] data.factor dim(data.factor) # Factor data analysis for cleaning str(data.factor) summary(data.factor) # Remove the highly biassed variables "Road_Type" and "Utility_Type" data <- data[(!colnames(data) %in% c("Utility_Type","Road_Type"))] dim(data) # Again data segregation data.numeric <- data[sapply(data, is.numeric)] data.numeric dim(data.numeric) data.factor <- data[sapply(data, is.factor)] data.factor dim(data.factor) # Checking NA values in target variable any(is.na(data$Sale_Price)) #Imputation with mean for(i in seq(data.numeric)) { data.numeric[i]<- ifelse(is.na(data.numeric[,i]), median(data.numeric[,i], na.rm = T), data.numeric[,i]) } colSums(is.na(data.numeric)) # Imputation with mode # Mode function #mode function getmode <- function(x) { x <- x[!is.na(x)] uniqv <- unique(x) uniqv[which.max(tabulate(match(x, uniqv)))] } #imputation with mode for(i in seq(data.factor)) data.factor[,i][is.na(data.factor[,i])] <- getmode(data.factor[,i]) colSums(is.na(data)) str(data.factor) summary(data.factor) # Analysing histogram of each numeric values numplot <- function(column, data) { ggplot(data, aes_string(x=column)) + geaom_histogram(aes(y=..density..), fill = "grey", color = "black") + geaom_density(fill = 'blue', alpha=0.2) + xlab(column) } np <- lapply(colnames(data.numeric), numplot, df=data.numeric) np do.call("grid.arrange", np) # Check with skewness data.skewed <- apply(data.numeric, c(2), skewness) data.skewed drops <- data.numeric[c("Lot_Size", "Brick_Veneer_Area", "BsmtFinSF2", "Second_Floor_Area", "LowQualFinSF", "Three_Season_Lobby_Area", "Screen_Lobby_Area", "Pool_Area", "Miscellaneous_Value")] drops np_1 <- lapply(colnames(drops), numplot, data=drops);np_1 do.call("grid.arrange", np_1) #Outlier out_std_check = function(x){ m=mean(x) s=sd(x) lc=m-3*s #lower cut-off uc=m+3*s n=list( val=sum(x>uc | x<lc), lc=lc, uc=uc) return(n) } np <- apply(data.numeric, c(2), out_std_check) np out_std_fix = function(x){ m=mean(x) s=sd(x) lc=m-3*s #lower cut-off uc=m+3*s out_value <- which(x > uc | x < lc) x[out_value] <- m return(x) } data.numeric <- apply(data.numeric, c(2), out_std_fix) data.numeric <- as.data.frame(data.numeric) View(data.numeric) np <- lapply(colnames(data.numeric), numplot, data=data.numeric) do.call("grid.arrange", np) apply(data.numeric, c(2), skewness) corrplot::corrplot(cor(data.numeric)) corrplot.mixed(cor(data.numeric), lower.col = "black", number.cex = .7) colnames(data.numeric) data.numeric <- data.numeric[!colnames(data.numeric) %in% c("Garage_Area","W_Deck_Area","Open_Lobby_Area","Enclosed_Lobby_Area")] #Now factor analysis #bar plot for categorical varibale etc. factplot <- function(column, df) { ggplot(df, aes_string(x=column))+ geom_bar(fill = "blue", color = "black", alpha= 0.2)+ xlab(column) } #calling all bar plot fp <- lapply(colnames(data.factor), factplot, df=data.factor) fp do.call("grid.arrange", fp) drps <- c("Land_Outline", "Property_Slope", "Condition1","Condition2" ,"House_Type", "Roof_Quality","Heating_Type" , "BsmtFinType2","Functional_Rate", "Kitchen_Above_Grade", "Garage_Quality","Garage_Condition") data.factor <- data.factor[!colnames(data.factor) %in% drps] factors <- c("Construction_Year", "Remodel_Year","Neighborhood","Garage_Built_Year", "Month_Sold") data.dummies <- data.factor[!colnames(data.factor) %in% factors] data.dummies #Significance ananlysis annova <- function(x) { y <- data.numeric$Sale_Price q <- list(summary(aov(y~x))) return(q) } y <- data.numeric$Sale_Price q <- (summary(aov(y~data.factor$Sale_Condition))) q signify <- apply(data.factor, c(2),annova) signify #dealing with year factor. #these will need transformation like life of house by substraction built & remodled year #for now just converting them into numeric data.factor$Construction_Year <- as.numeric(data.factor$Construction_Year) data.factor$Remodel_Year <- as.numeric(data.factor$Remodel_Year) data.factor$Garage_Built_Year <- as.numeric(data.factor$Garage_Built_Year) data.factor$Garage_Finish_Year <- as.numeric(data.factor$Garage_Finish_Year) data.factor$Month_Sold <- as.numeric(data.factor$Month_Sold) data.factor$Year_Sold <- as.numeric(data.factor$Year_Sold) library(dummies) data.factor <- dummy.data.frame(data.factor) data.factor # dim(data.dummies) # dim(aq) # data.factor <- data.factor[colnames(data.factor) %in% factors] # data.factor <- cbind(data.factor, aq) # data<- cbind(data.numeric, data.factor) data str(data) dim(data) colnames(data) ### Model 1 #sampling set.seed(10) s=sample(1:nrow(data),0.70*nrow(data)) train=data[s,] test=data[-s,] dim(train) dim(test) colnames(test1) test1 <- test[!colnames(test) %in% "Sale_Price"] #Applying lm model model <- lm(Sale_Price~., data=train) summary(model) pred <- predict(model, test1) View(pred) results <- cbind(pred,test$Sale_Price) colnames(results) <- c('pred','real') results <- as.data.frame(results) View(results) # Grab residuals res <- residuals(model) res <- as.data.frame(res) head(res) ggplot(res,aes(res)) + geom_histogram(fill='blue',alpha=0.5) plot(model) #Stepwise modeling #stepwise sleection: nullModel<- lm(Sale_Price ~ 1, train) #summary(nullModel) fullmodel <- lm(Sale_Price~.,data = (train)) #summary(fullmodel) fit <- step(nullModel, scope=list(lower=nullModel, upper=fullmodel), direction="both") #revel the model fit model <- lm(formula = Sale_Price ~ Grade_Living_Area + Construction_Year + Total_Basement_Area + Overall_Material8 + Overall_Material7 + BsmtFinSF1 + Fireplaces0 + House_Condition7 + Overall_Material9 + Kitchen_QualityGd + Overall_Material6 + Zoning_ClassRMD + Sale_ConditionNormal + NeighborhoodTimber + NeighborhoodSomerst + Building_Class160 + House_Condition2 + Exterior_ConditionEx + Garage_Size0 + House_Condition8 + Rooms_Above_Grade12 + NeighborhoodCrawfor + NeighborhoodBrkSide + House_Condition6 + House_Condition9 + House_Condition5 + NeighborhoodNridgHt + Sale_TypeConLI + Rooms_Above_Grade11 + Full_Bathroom_Above_Grade3 + Property_ShapeIR3 + Underground_Full_Bathroom0 + Building_Class75 + Garage_Size4 + NeighborhoodBrDale + Exterior_MaterialGd + Exposure_LevelAv + NeighborhoodClearCr + Garage_Size1 + NeighborhoodNoRidge + Rooms_Above_Grade9 + Foundation_TypeW + Exposure_LevelNo + Zoning_ClassCommer + NeighborhoodIDOTRR + Bedroom_Above_Grade0 + Exterior1stStone + Lot_ConfigurationC + Rooms_Above_Grade5 + Bedroom_Above_Grade1 + Exterior1stHdBoard + Exterior2ndVinylSd + Bedroom_Above_Grade8 + Building_Class90 + Underground_Full_Bathroom1 + Overall_Material10 + Garage_Size2 + `Exterior2ndWd Shng` + BsmtFinType1GLQ + Basement_HeightEx + NeighborhoodBlmngtn + GarageAttchd + House_Design2.5Unf + Exterior1stBrkComm, data = train) summary(model) plot(model) # # x <- factor(c("A","B","A","C","D","E","A","E","C")) # x # library(car) # x <- recode(x, "c('A', 'B')='A+B';c('D', 'E') = 'D+E'") # x ### Model 2 #sampling set.seed(20) s=sample(1:nrow(data),0.70*nrow(data)) train=data[s,] test=data[-s,] dim(train) dim(test) colnames(test1) test1 <- test[!colnames(test) %in% "Sale_Price"] #Applying lm model model <- lm(Sale_Price~., data=train) summary(model) pred <- predict(model, test1) View(pred) results <- cbind(pred,test$Sale_Price) colnames(results) <- c('pred','real') results <- as.data.frame(results) View(results) # Grab residuals res <- residuals(model) res <- as.data.frame(res) head(res) ggplot(res,aes(res)) + geom_histogram(fill='blue',alpha=0.5) plot(model) #Stepwise modeling #stepwise sleection: nullModel<- lm(Sale_Price ~ 1, train) summary(nullModel) fullmodel <- lm(Sale_Price~.,data = (train)) summary(fullmodel) fit <- step(nullModel, scope=list(lower=nullModel, upper=fullmodel), direction="both") #revel the model fit model <- lm(formula = Sale_Price ~ Grade_Living_Area + Construction_Year + Total_Basement_Area + Overall_Material8 + Overall_Material7 + BsmtFinSF1 + Fireplaces0 + House_Condition7 + Overall_Material9 + Kitchen_QualityGd + Overall_Material6 + Zoning_ClassRMD + Sale_ConditionNormal + NeighborhoodTimber + NeighborhoodSomerst + Building_Class160 + House_Condition2 + Exterior_ConditionEx + Garage_Size0 + House_Condition8 + Rooms_Above_Grade12 + NeighborhoodCrawfor + NeighborhoodBrkSide + House_Condition6 + House_Condition9 + House_Condition5 + NeighborhoodNridgHt + Sale_TypeConLI + Rooms_Above_Grade11 + Full_Bathroom_Above_Grade3 + Property_ShapeIR3 + Underground_Full_Bathroom0 + Building_Class75 + Garage_Size4 + NeighborhoodBrDale + Exterior_MaterialGd + Exposure_LevelAv + NeighborhoodClearCr + Garage_Size1 + NeighborhoodNoRidge + Rooms_Above_Grade9 + Foundation_TypeW + Exposure_LevelNo + Zoning_ClassCommer + NeighborhoodIDOTRR + Bedroom_Above_Grade0 + Exterior1stStone + Lot_ConfigurationC + Rooms_Above_Grade5 + Bedroom_Above_Grade1 + Exterior1stHdBoard + Exterior2ndVinylSd + Bedroom_Above_Grade8 + Building_Class90 + Underground_Full_Bathroom1 + Overall_Material10 + Garage_Size2 + `Exterior2ndWd Shng` + BsmtFinType1GLQ + Basement_HeightEx + NeighborhoodBlmngtn + GarageAttchd + House_Design2.5Unf + Exterior1stBrkComm, data = train) summary(model) plot(model)
3ca9693d9201e2105c67fadad71cf4d05e795ce6
502d84d512114b0fff16811e50941ca9e99e82d9
/tests/testthat/test-02_grow_leaves.R
c43713f21042acaa1b7607884552ffe4366e1bea
[]
no_license
empalmer/leafart
49e270c8c1ac78df4635e9ca792d93d1f3b04dc3
5cd139cb40ddf0df4df6802232bcd5dd2be02f7c
refs/heads/main
2023-02-08T01:43:22.308199
2021-01-04T20:40:25
2021-01-04T20:40:25
326,800,945
2
0
null
null
null
null
UTF-8
R
false
false
615
r
test-02_grow_leaves.R
test_that("Number of layers correct", { param <- get_params(n_leaves = 1, n_layer = 3, scale = c(.8,.9), angle = c(-30,10,20), split = 3) expect_length(grow_leaf(param), param$n_layer +1) }) test_that("number of branches correct",{ param <- get_params(n_layer = 3,split = 3) leaf <- grow_leaf(param) expect_equal(map_dbl(leaf,nrow),rep(param$split)^(0:param$n_layer)) param <- get_params(n_layer = 6,split = 5) leaf <- grow_leaf(param) expect_equal(map_dbl(leaf,nrow),rep(param$split)^(0:param$n_layer)) })
f50b9ad87562b0dbcc88f0b463555b333360e0c2
08048efe5325fe4930e3c9fe9694a95a02b10c0f
/R/zakup_zwierzecia.R
9ad9f032ac6f2d5a169f3ff8025a95b3603826a2
[]
no_license
nkneblewska/SuperFarmerRCNK
0412245e48a93f43885bbc6fc44062bf249776a2
be69ebe194f2811c98415a4c591d3a2d6d752a7e
refs/heads/master
2020-06-19T15:57:29.529074
2016-11-27T16:03:26
2016-11-27T16:03:26
null
0
0
null
null
null
null
UTF-8
R
false
false
357
r
zakup_zwierzecia.R
zakup_zwierzecia <- function(stan_gracza, stan_stada, zwierzak) { wartosci_zwierzat <- c(R = 1, S = 6, P = 12, C = 36, H = 72, SD = 6, BD = 36) if (sum(stan_gracza[1:5]*wartosci_zwierzat[1:5]) >= wartosci_zwierzat[zwierzak]) { return (kup_zwierze_yolo(zwierzak, stan_gracza, stan_stada)) } else { return (cbind(stan_gracza, stan_stada)) } }
e931a873842e17231f86df927dbac2b2a22ee50b
2bec5a52ce1fb3266e72f8fbeb5226b025584a16
/Opt5PL/man/sMultiple.Rd
03c6336b29246b814bdee6a6e5b379901db72b0b
[]
no_license
akhikolla/InformationHouse
4e45b11df18dee47519e917fcf0a869a77661fce
c0daab1e3f2827fd08aa5c31127fadae3f001948
refs/heads/master
2023-02-12T19:00:20.752555
2020-12-31T20:59:23
2020-12-31T20:59:23
325,589,503
9
2
null
null
null
null
UTF-8
R
false
false
231
rd
sMultiple.Rd
\name{sMultiple} \alias{sMultiple} \title{Multiply a constant to a matrix} \usage{ sMultiple(s, M) } \arguments{ \item{s}{Numeric} \item{M}{A numeric matrix} } \description{ Multiply a constant to a matrix: s*M. }
dd0d63121a3eba8061033d8ded44316dc9f68d0d
4dcd968ca1104a67e366179474240a2c5c9b9f0e
/R/tp_Bayes.R
03b9f55e05642f5ef1a389de491a31a8047e21f9
[]
no_license
ThomasDavenel/TP_ACI
27edb80623c4d58a9ac219d640c0f0921a2ab824
d3efd5007c2d6f73074e80465d447f806bb8e7e2
refs/heads/main
2023-03-18T17:25:27.572962
2021-03-07T15:34:12
2021-03-07T15:34:12
337,032,440
0
0
null
null
null
null
UTF-8
R
false
false
4,033
r
tp_Bayes.R
# ---------- Chargement des packages nécéssaires library(e1071) source("fonctions_utiles.R") # ---------- Chargement des données ex1 = read.table("./data/data_exam.txt", header = T) ex1$Reussite = as.factor(ex1$Reussite) str(ex1) table(ex1$Reussite) # ---------- Separation Apprentissage/Test nall = nrow(ex1) #total number of rows in data ntrain = floor(0.7 * nall) # number of examples (rows) for train: 70% (vous pouvez changer en fonction des besoins) ntest = nall - ntrain # number of examples for test: le reste set.seed(20) # choix d'une graine pour le tirage aléatoire index = sample(nall) # permutation aléatoire des nombres 1, 2, 3 , ... nall ex1_app = ex1[index[1:ntrain],] # création du jeu d'apprentissage ex1_test = ex1[index[(ntrain+1):(ntrain+ntest)],] # création du jeu de test table(ex1_app$Reussite) table(ex1_test$Reussite) # ----- Visualisation des données apprentissage et validation #Affichage des données d apprentissage plot(ex1_app[which(ex1_app$Reussite==0),1:2], col = "red", xlim = c(0,105), ylim = c(0,105)) points(ex1_app[which(ex1_app$Reussite==1),1:2], col = "blue") # Affichage des données de test (avec un triangle , pch = 2) points(ex1_test[which(ex1_test$Reussite==1),1:2], col = "blue", pch = 2) points(ex1_test[which(ex1_test$Reussite==0),1:2], col = "red", pch = 2) # ---------- Construction du classifieur Bayesien Naif # Pour le bayesien naif, il n y a pas de paramètres à ajuster donc on apprend le modèle sur # l'ensemble d'apprentissage uniquement (pas d'ensemble de validation) bayes = naiveBayes(Reussite~., data = ex1_app) # Vous pouvez voir les probabilites a priori, ainsi que les paramètres des gaussiennes estimées en tapant le nom du modèle : print(bayes$apriori) print(bayes$tables) # ou print(bayes) # A-priori probabilities: # Y # 0 1 # 0.3882353 0.6117647 # Conditional probabilities: # moyenne et ecart-type sachant Y dans les 2 colonnes des matrices données à l'écran # Note1 = x1 # Y [,1] [,2] # 0 53.07455 17.69572 -> moyenne [,1] et ecart-type [,2] de x1|C1 # 1 73.91385 14.68127 -> moyenne et ecart-type de x1|C2 # Note2 = x2 # Y [,1] [,2] # 0 53.12424 15.36159 # 1 74.77731 16.17977 #### Visualisation des vraisemblances # Affichage des densites de probabilités pour la variable x1=Note1 note1_c1=as.numeric(unlist(ex1_app[ex1_app$Reussite==0,][1])) #conversion to numeric for density plot note1_c2=as.numeric(unlist(ex1_app[ex1_app$Reussite==1,][1])) # Pour la classe 0 plot(density(note1_c1),lty=2,col="red", xlab="Note 1", main="Density estimation for Note1") # estimation par KDE points(note1_c1, y= rep(0.00,length(note1_c1)),col="red") # affichage des points de l'ensemble d'apprentissage curve(dnorm(x, bayes$tables$Note1[1,1], bayes$tables$Note1[1,2]), add=TRUE, col="red") # gaussienne estimée par MV # Idem pour la classe 1 lines(density(note1_c2),lty=2,col="blue") points(note1_c2, y= rep(0.00,length(note1_c2)),col="blue") curve(dnorm(x, bayes$tables$Note1[2,1], bayes$tables$Note1[2,2]), add=TRUE, col="blue") legend("topright", c("KDE class 0", "gaussian class 0","KDE class 1", "gaussian class 1"), col = c("red","red","blue","blue"), lty=c(2,1,2,1), cex=0.5) # ---------- Prediction avec Bayes ###### Question 1: Calculer la classe du premier exemple de l'ensemble de test. Donnez les valeurs numériques calculées. # Aide: # - dnorm(x, mean = ??, sd = ??) calcul la densité de proba au point x # d'une distribution gaussienne de moyenne 'mean' et d'ecart-type 'sd' # - bayes$tables$Note1[1,1] et bayes$tables$Note1[1,2] pour accéder aux paramètres appris # La fonction predict marche avec Bayes # Vous pouvez prédire la classe de tous les individus de l'ensemble de test d'un coup: predict(bayes, ex1_test) # ---------- Affichage de la frontière de décision # idem tree dessiner_frontiere_tree(ex1_app, ex1_test, bayes, 0,105,0,105,c("red", "blue")) ###### Question 2: Estimez l'erreur de généralisation faite par bayes sur ces données.
03678cf781d7187df1e614702115f5156decf3f7
16502827f4c63a4dbb1a52517d777740b4253dcf
/R/taxa_summary.R
28f1da2828681dc6ce8abedb9114027f06c84205
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
microsud/microbiomeutilities
62a3dd12fa5396dff29a17f8f7612d25251e0269
046a9f928f35fc2a02dd6cfb9175a0c7ddf65c4b
refs/heads/master
2022-12-06T14:44:11.259855
2022-11-23T08:07:05
2022-11-23T08:07:05
104,251,264
32
8
NOASSERTION
2021-04-14T09:31:29
2017-09-20T18:10:49
R
UTF-8
R
false
false
2,094
r
taxa_summary.R
#' @title Give taxa summary at specified taxonomic level #' @description Data frame with mean, max, median standard deviation of relative abundance. #' @param x \code{\link{phyloseq-class}} object #' @param level Taxonomic level for which summary is required #' @return returns a data frame with relative abundance summary. #' @import utils #' @export #' @author Contact: Sudarshan A. Shetty \email{sudarshanshetty9@@gmail.com} #' @examples #' \dontrun{ #' # Example data #' library(microbiomeutilities) #' data("zackular2014") #' p0 <- zackular2014 #' p0.rel <- microbiome::transform(p0, "compositional") #' tx.sum1 <- taxa_summary(p0, "Phylum") #' #' tx.sum2 <- taxa_summary(p0.rel, "Phylum") #' } #' #' @keywords utilities taxa_summary <- function(x, level) { pobj <- taxdf <- pobj.ag <- otudf <- outputdf <- NULL pobj <- x # taxdf <- as.data.frame(pobj@tax_table) taxdf <- tax_table(pobj) %>% as("matrix") %>% as.data.frame() taxdf$OTU <- rownames(tax_table(pobj)) tax_table(pobj) <- tax_table(as.matrix(taxdf, quote = FALSE)) pobj.ag <- microbiome::aggregate_taxa(pobj, level) com <- all(sample_sums(pobj.ag) == 1) if (com == TRUE) { message("Data provided is compositional \n will use values directly") otudf2 <- as.data.frame(abundances(pobj.ag)) rownames(otudf2) <- tax_table(pobj.ag)[, level] } else { message("Data provided is not compositional \n will first transform") otudf2 <- as.data.frame(abundances(pobj.ag, "compositional")) rownames(otudf2) <- tax_table(pobj.ag)[, level] } output <- NULL for (j in 1:nrow(otudf2)) { x2 <- as.numeric(otudf2[j, ]) mx.rel <- max(x2, na.rm = TRUE) mean.rel <- mean(x2, na.rm = TRUE) med.rel <- median(x2, na.rm = TRUE) Std.dev <- sd(x2, na.rm = TRUE) output <- rbind(output, c(row.names(otudf2)[j], mx.rel, mean.rel, med.rel, Std.dev)) } outputdf <- as.data.frame(output) colnames(outputdf) <- c("Taxa", "Max.Rel.Ab", "Mean.Rel.Ab", "Median.Rel.Ab", "Std.dev") return(outputdf) }
7447db084a331dd5f279d53c296f7e889e465417
eb41c31ea2ec86dd0638aee11754a78c82260c4f
/attemp1.R
98e2c2cd390a2c2e95bf0197c77a7cc1caec23c8
[]
no_license
SimSid2312/DataMiningClassifiers
4f2c9db4ffa2a6dd1ad08fb14a8bd93af467374e
699913b6198ae50a835e22db4f2cec8f94f3cd1f
refs/heads/master
2020-04-07T18:49:23.889432
2018-12-30T07:32:07
2018-12-30T07:32:07
158,625,036
0
0
null
null
null
null
UTF-8
R
false
false
492
r
attemp1.R
#read the dataset dataset=read.csv('data.csv',as.is = TRUE) dataset<- iris #splitting the dataset - 60% will be training data and 40 % will be test data training_rowCount= (nrow(dataset)*0.6) test_rowCount=nrow(dataset)-training_rowCount training_dataset= dataset[1:training_rowCount,] test_dataset=tail(dataset,n=test_rowCount) source("D:/data mining/tutPoint/naive_bayes.R") results_training <- My_NaiveBayes(training_dataset) results_test <- My_NaiveBayes(test_dataset)
adfeb35912f5bc73c8acefe2b5a8063298260aab
278057fd9b095a2805639d1c5f2cb7afdd33a44f
/man/read.pipe.Rd
fa2a7e09257b084d6ba82be976d32f530512085e
[]
no_license
tlcaputi/tlcPack
6301c14540d02c35f05d163f6600d96b2c4fac67
d8d42ce3e3a807ec0e12bd20549fd1e3ac1861d4
refs/heads/master
2020-03-24T11:23:48.352052
2020-03-23T22:47:13
2020-03-23T22:47:13
142,684,188
0
0
null
null
null
null
UTF-8
R
false
true
452
rd
read.pipe.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/testingFunctions.R, R/trackProjectFunctions.r \name{read.pipe} \alias{read.pipe} \title{Read Pipe Delimited Files} \usage{ read.pipe(filename, ...) read.pipe(filename, ...) } \arguments{ \item{filename}{filename for pipe-delimited file} } \description{ This function creates a table of summary statistics. } \examples{ read.pipe(filename) } \keyword{pipe} \keyword{read}
0e3993b89f8a57a76c101f1626dc4e0abcb4e519
7e0f4777f4e06b0ac72b90422ac0d9c765767755
/projects/josm-shf/pif-ab-popsize.R
95aea614037c74c5164dca4a8342596b5bcbcda7
[]
no_license
psolymos/abmianalytics
edd6a040082260f85afbf4fc25c4f2726b369392
9e801c2c564be155124109b4888d29c80bd1340d
refs/heads/master
2023-01-30T05:00:32.776882
2023-01-21T05:36:23
2023-01-21T05:36:23
34,713,422
0
7
null
2017-01-20T19:07:59
2015-04-28T06:39:37
R
UTF-8
R
false
false
45,374
r
pif-ab-popsize.R
library(mefa4) ROOT <- "d:/abmi/AB_data_v2016" e <- new.env() #load(file.path(ROOT, "data", "data-full-withrevisit.Rdata"), envir=e) load(file.path(ROOT, "out", "birds", "data", "data-wrsi.Rdata"), envir=e) TAX <- droplevels(e$TAX) TAX$Fn <- droplevels(TAX$English_Name) levels(TAX$Fn) <- nameAlnum(levels(TAX$Fn), capitalize="mixed", collapse="") rm(e) e <- new.env() load(file.path(ROOT, "out", "birds", "data", "data-josmshf.Rdata"), envir=e) xn <- e$DAT mods <- e$mods OFF <- e$OFF yy <- e$YY BB <- e$BB rm(e) fln <- list.files(file.path(ROOT, "out", "birds", "results", "josmshf")) fln <- sub("birds_abmi-josmshf_", "", fln) fln <- sub(".Rdata", "", fln) SPP <- fln tax <- droplevels(TAX[SPP,]) tv0 <- read.csv("~/repos/abmianalytics/lookup/lookup-veg-hf-age.csv") tv0$Sector2 <- factor(ifelse(is.na(tv0$Sector), "NATIVE", as.character(tv0$Sector)), c("NATIVE", "Agriculture", "Energy", "Forestry", "Misc", "RuralUrban", "Transportation")) tv0$HAB <- paste0(tv0$Type, ifelse(tv0$AGE %in% c("5", "6", "7", "8", "9"), "O", "")) tv0$HAB[tv0$Combined %in% c("RoadTrailVegetated", "RoadVegetatedVerge", "RailVegetatedVerge")] <- "Verges" #tv0[tv0$HAB=="SoftLin",c("Combined", "HAB")] if (FALSE) { source("~/Dropbox/courses/st-johns-2017/R/diagnostics-functions.R") xn$counts <- as.numeric(yy[,"ALFL"]) xn$counts01 <- ifelse(xn$counts>0, 1, 0) plot(counts ~ wtAge + pAspen + ClosedCanopy + pWater + X + Y + xPET + xAHM + Succ_KM + Alien_KM, xn, B=0) siplot(counts01 ~ wtAge + pAspen + ClosedCanopy + pWater + X + Y + xPET + xAHM + Succ_KM + Alien_KM, xn, B=0) } ## --- calculating total pop size based on predictions --- STAGE <- list(veg = 7) # hab=5, hab+clim=6, hab+clim+shf=7 OUTDIR1 <- paste0("e:/peter/josm/2017/stage", STAGE$veg, "/pred1") OUTDIRB <- paste0("e:/peter/josm/2017/stage", STAGE$veg, "/predB") load(file.path(ROOT, "out", "kgrid", "kgrid_table.Rdata")) #source("~/repos/bragging/R/glm_skeleton.R") #source("~/repos/abmianalytics/R/results_functions.R") #source("~/repos/bamanalytics/R/makingsense_functions.R") source("~/repos/abmianalytics/R/maps_functions.R") regs <- levels(kgrid$LUFxNSR) kgrid$useN <- !(kgrid$NRNAME %in% c("Grassland", "Parkland") | kgrid$NSRNAME == "Dry Mixedwood") kgrid$useN[kgrid$NSRNAME == "Dry Mixedwood" & kgrid$POINT_Y > 56.7] <- TRUE kgrid$useS <- kgrid$NRNAME == "Grassland" kgrid$useBCR6 <- kgrid$BCRCODE == " 6-BOREAL_TAIGA_PLAINS" AREA_ha <- (1-kgrid$pWater) * kgrid$Area_km2 * 100 #AREA_ha <- kgrid$Area_km2 * 100 AREA_ha <- AREA_ha[kgrid$useBCR6] names(AREA_ha) <- rownames(kgrid)[kgrid$useBCR6] PREDS <- matrix(0, sum(kgrid$useBCR6), length(SPP)) rownames(PREDS) <- rownames(kgrid)[kgrid$useBCR6] colnames(PREDS) <- SPP PREDS0 <- PREDS for (spp in SPP) { cat(spp, "--------------------------------------\n");flush.console() fl <- list.files(file.path(OUTDIR1, spp)) ssRegs <- gsub("\\.Rdata", "", fl) pxNcr <- NULL #pxNrf <- NULL for (i in ssRegs) { cat(spp, i, "\n");flush.console() load(file.path(OUTDIR1, spp, paste0(i, ".Rdata"))) rownames(pxNcr1) <- rownames(pxNrf1) <- names(Cells) pxNcr <- rbind(pxNcr, pxNcr1) #pxNrf <- rbind(pxNrf, pxNrf1) } PREDS[,spp] <- pxNcr[rownames(PREDS),] #PREDS0[,spp] <- pxNrf[rownames(PREDS0),] } N <- colSums(PREDS*AREA_ha) / 10^6 save(AREA_ha, N, PREDS, file=file.path(OUTDIR1, "predictions.Rdata")) ## making pretty maps library(sp) library(rgeos) library(raster) library(cure4insect) opar <- set_options(path = "w:/reports") load_common_data() stopifnot(all(rownames(KT)==rownames(kgrid))) KT <- cure4insect:::.c4if$KT rt <- cure4insect:::.read_raster_template() #INSIDE <- KT$reg_nr!="Grassland" & coordinates(cure4insect:::.c4if$XY)[,2] > 50 INSIDE <- kgrid$useBCR6 r0 <- cure4insect:::.make_raster(ifelse(INSIDE, 1, 0), KT, rt) v <- values(r0) values(r0)[!is.na(v) & v==0] <- NA cf <- function(n) rev(viridis::viridis(2*n)[(1+n):(n*2)]) pdf(file.path(ROOT, "out", "birds", "josmshf", "BCR6-maps.pdf"), onefile=TRUE, width=6, height=9) for (spp in SPP) { cat(spp, "--------------------------------------\n");flush.console() fl <- list.files(file.path(OUTDIR1, spp)) ssRegs <- gsub("\\.Rdata", "", fl) pxNcr <- NULL #pxNrf <- NULL for (i in ssRegs) { cat(spp, i, "\n");flush.console() load(file.path(OUTDIR1, spp, paste0(i, ".Rdata"))) rownames(pxNcr1) <- rownames(pxNrf1) <- names(Cells) pxNcr <- rbind(pxNcr, pxNcr1) #pxNrf <- rbind(pxNrf, pxNrf1) } PREDS <- pxNcr[rownames(KT[INSIDE,]),] PREDS <- PREDS[match(rownames(KT), names(PREDS))] PREDS[is.na(PREDS)] <- 0 r1 <- .make_raster(PREDS, KT, rt) r1 <- mask(r1, r0) plot(rt, col="darkgrey", axes=FALSE, box=FALSE, legend=FALSE, main=spp) #plot(r1, col=cf(100), axes=FALSE, box=FALSE, main=spp) plot(r1, col=cf(100), add=TRUE) } dev.off() ## getting habitat stuf fl <- list.files(file.path(OUTDIR1, SPP[1])) ssRegs <- gsub("\\.Rdata", "", fl) Aveg <- NULL for (i in ssRegs) { load(file.path(ROOT, "out", "transitions", paste0(i, ".Rdata"))) tmp <- trVeg[rownames(trVeg) %in% names(AREA_ha),] tmp <- (1-kgrid[rownames(tmp), "pWater"]) * tmp Aveg <- rbind(Aveg, colSums(tmp)) } rownames(Aveg) <- ssRegs Aveg <- Aveg / 10^4 ch2veg <- t(sapply(strsplit(colnames(trVeg), "->"), function(z) if (length(z)==1) z[c(1,1)] else z[1:2])) ch2veg <- data.frame(ch2veg) colnames(ch2veg) <- c("rf","cr") rownames(ch2veg) <- colnames(Aveg) ch2veg$isHF <- ch2veg$cr %in% c("BorrowpitsDugoutsSumps", "Canals", "CCConif0", "CCConif1", "CCConif2", "CCConif3", "CCConif4", "CCConifR", "CCDecid0", "CCDecid1", "CCDecid2", "CCDecid3", "CCDecid4", "CCDecidR", "CCMixwood0", "CCMixwood1", "CCMixwood2", "CCMixwood3", "CCMixwood4", "CCMixwoodR", "CCPine0", "CCPine1", "CCPine2", "CCPine3", "CCPine4", "CCPineR", "CultivationCropPastureBareground", "HighDensityLivestockOperation", "IndustrialSiteRural", "MineSite", "MunicipalWaterSewage", "OtherDisturbedVegetation", "PeatMine", "Pipeline", "RailHardSurface", "RailVegetatedVerge", "Reservoirs", "RoadHardSurface", "RoadTrailVegetated", "RoadVegetatedVerge", "RuralResidentialIndustrial", "SeismicLine", "TransmissionLine", "Urban", "WellSite", "WindGenerationFacility") ch2veg$HAB <- tv0$HAB[match(ch2veg$cr, tv0$Combined)] ch2veg$HAB[is.na(ch2veg$HAB)] <- "Swamp" ch2veg$HAB0 <- tv0$HAB[match(ch2veg$rf, tv0$Combined)] ch2veg$HAB0[is.na(ch2veg$HAB0)] <- "Swamp" AvegH <- groupSums(Aveg, 2, ch2veg$HAB) sum(colSums(AvegH))/100 sum(AREA_ha)/100 ch2veg$Area_ha <- colSums(Aveg) Nhab <- list() for (spp in SPP) { cat(spp, "--------------------------------------\n");flush.console() # fl <- list.files(file.path(OUTDIR1, spp)) # ssRegs <- gsub("\\.Rdata", "", fl) hbNcr <- 0 for (i in ssRegs) { cat(spp, i, "\n");flush.console() aa <- AvegH[i,] ee <- new.env() load(file.path(OUTDIR1, spp, paste0(i, ".Rdata")), envir=ee) e <- new.env() load(file.path(OUTDIRB, spp, paste0(i, ".Rdata")), envir=e) if (FALSE) { sum(aa) sum(AREA_ha[names(e$Cells)]) str(ee$pxNcr1) str(e$pxNcrB) sum(ee$pxNcr1[,1], na.rm=TRUE) sum(e$pxNcrB[,1], na.rm=TRUE) str(ee$hbNcr1) str(e$hbNcrB) sum(ee$hbNcr1[,1], na.rm=TRUE) sum(e$hbNcrB[,1], na.rm=TRUE) sum(ee$pxNcr1[,1]*AREA_ha[names(ee$Cells)], na.rm=TRUE) sum(e$pxNcrB[,1]*AREA_ha[names(e$Cells)], na.rm=TRUE) sum(ee$hbNcr1[,1]*Aveg[i,], na.rm=TRUE) sum(e$hbNcrB[,1]*Aveg[i,], na.rm=TRUE) } tmp <- e$hbNcrB tmp[is.na(tmp)] <- 0 tmp <- groupSums(tmp*Aveg[i,], 1, ch2veg$HAB) hbNcr <- hbNcr + tmp } Nhab[[spp]] <- hbNcr } save(AvegH, Nhab, file=file.path(OUTDIRB, "predictions_HAB.Rdata")) ## getting CIs for Stage 7 ssRegs <- gsub("\\.Rdata", "", list.files(file.path(OUTDIR1, SPP[1]))) PREDSCI <- array(0, c(length(ssRegs), length(SPP), 100)) dimnames(PREDSCI) <- list(ssRegs, SPP, NULL) #PREDSCI0 <- PREDSCI ## do not need to subtract water: it was not accounted for in predictions #AA <- (1-kgrid$pWater) * kgrid$Area_km2 * 100 AA <- kgrid$Area_km2 * 100 names(AA) <- rownames(kgrid) for (i in ssRegs) { cat(i, "--------------------------------------\n");flush.console() for (spp in SPP) { cat(i, spp, "\n");flush.console() e <- new.env() load(file.path(OUTDIRB, spp, paste0(i, ".Rdata")), envir=e) pxNcr <- e$pxNcrB #pxNrf <- e$pxNrfB rownames(pxNcr) <- names(e$Cells) #rownames(pxNrf) <- names(e$Cells) PREDSCI[i,spp,] <- colSums(pxNcr*AA[names(e$Cells)]) #PREDSCI0[i,spp,] <- colSums(pxNrf*AA[names(e$Cells)]) } } save(PREDSCI, file=file.path(OUTDIRB, "predictionsCI.Rdata")) ## looking at results e <- new.env() load("e:/peter/josm/2017/stage5/pred1/predictions.Rdata", envir=e) N5 <- e$N e <- new.env() load("e:/peter/josm/2017/stage6/pred1/predictions.Rdata", envir=e) N6 <- e$N e <- new.env() load("e:/peter/josm/2017/stage7/pred1/predictions.Rdata", envir=e) N7 <- e$N rm(e) NN <- data.frame(N5=N5, N6=N6, N7=N7) NN$spp <- rownames(NN) write.csv(NN, row.names=FALSE, file="~/Dropbox/bam/PIF-AB/results/PopSize567.csv") summary(NN) pairs(NN[NN$N5 < 20 & NN$N6 < 20 & NN$N7 < 20,]) ## --- evaluating AUC based on external data --- pr_fun_for_gof <- function(est, X, off=0) { if (is.null(dim(est))) { mu0 <- drop(X %*% est) exp(mu0 + off) } else { mu0 <- apply(est, 1, function(z) X %*% z) rowMeans(exp(mu0 + off)) } } simple_roc <- function(labels, scores){ labels <- labels[order(scores, decreasing=TRUE)] data.frame(TPR=cumsum(labels)/sum(labels), FPR=cumsum(!labels)/sum(!labels), labels) } simple_auc <- function(ROC) { ROC$inv_spec <- 1-ROC$FPR dx <- diff(ROC$inv_spec) sum(dx * ROC$TPR[-1]) / sum(dx) } ## out-of-sample set bunique <- unique(BB) INTERNAL <- 1:nrow(xn) %in% bunique ss <- which(INTERNAL) ss1 <- which(!INTERNAL) bid <- xn$bootid levels(bid) <- sapply(strsplit(levels(bid), "\\."), "[[", 1) up <- function() { source("~/repos/bragging/R/glm_skeleton.R") source("~/repos/abmianalytics/R/results_functions.R") source("~/repos/bamanalytics/R/makingsense_functions.R") # source("~/repos/abmianalytics/R/wrsi_functions.R") # source("~/repos/abmianalytics/R/results_functions1.R") # source("~/repos/abmianalytics/R/results_functions2.R") invisible(NULL) } up() Terms <- getTerms(mods, "list") Xn <- model.matrix(getTerms(mods, "formula"), xn) colnames(Xn) <- fixNames(colnames(Xn)) #spp <- "OVEN" res_AUC <- list() for (spp in fln) { cat(spp, "\n");flush.console() y1sp <- yy[,spp] y10sp <- ifelse(y1sp > 0, 1, 0) off1sp <- OFF[,spp] resn <- loadSPP(file.path(ROOT, "out", "birds", "results", "josmshf", paste0("birds_abmi-josmshf_", spp, ".Rdata"))) est0 <- getEst(resn, stage=0, na.out=FALSE, Xn) est5 <- getEst(resn, stage=5, na.out=FALSE, Xn) est6 <- getEst(resn, stage=6, na.out=FALSE, Xn) est7 <- getEst(resn, stage=7, na.out=FALSE, Xn) j <- 1:nrow(est7) pr0o <- pr_fun_for_gof(est0[j,], Xn[ss1,], off=off1sp[ss1]) pr5o <- pr_fun_for_gof(est5[j,], Xn[ss1,], off=off1sp[ss1]) pr6o <- pr_fun_for_gof(est6[j,], Xn[ss1,], off=off1sp[ss1]) pr7o <- pr_fun_for_gof(est7[j,], Xn[ss1,], off=off1sp[ss1]) pr0i <- pr_fun_for_gof(est0[j,], Xn[ss,], off=off1sp[ss]) pr5i <- pr_fun_for_gof(est5[j,], Xn[ss,], off=off1sp[ss]) pr6i <- pr_fun_for_gof(est6[j,], Xn[ss,], off=off1sp[ss]) pr7i <- pr_fun_for_gof(est7[j,], Xn[ss,], off=off1sp[ss]) auc0o <- simple_auc(simple_roc(y10sp[ss1], pr0o)) auc5o <- simple_auc(simple_roc(y10sp[ss1], pr5o)) auc6o <- simple_auc(simple_roc(y10sp[ss1], pr6o)) auc7o <- simple_auc(simple_roc(y10sp[ss1], pr7o)) auc0i <- simple_auc(simple_roc(y10sp[ss], pr0i)) auc5i <- simple_auc(simple_roc(y10sp[ss], pr5i)) auc6i <- simple_auc(simple_roc(y10sp[ss], pr6i)) auc7i <- simple_auc(simple_roc(y10sp[ss], pr7i)) res_AUC[[spp]] <- c( auc0o=auc0o, auc5o=auc5o, auc6o=auc6o, auc7o=auc7o, auc0i=auc0i, auc5i=auc5i, auc6i=auc6i, auc7i=auc7i) } AUC <- data.frame(do.call(rbind, res_AUC)) AUC$k5 <- (AUC$auc5i-AUC$auc0i) / (1-AUC$auc0i) AUC$k6 <- (AUC$auc6i-AUC$auc0i) / (1-AUC$auc0i) AUC$k7 <- (AUC$auc7i-AUC$auc0i) / (1-AUC$auc0i) AUC$spp <- rownames(AUC) write.csv(AUC, row.names=FALSE, file="~/Dropbox/bam/PIF-AB/results/AUC.csv") write.csv(NN, row.names=FALSE, file="~/Dropbox/bam/PIF-AB/results/PopSize567.csv") ## road effects pr_fun_for_road <- function(est, X0, X1) { lam1 <- exp(apply(est, 1, function(z) X1 %*% z)) Lam1 <- unname(colMeans(lam1)) lam0 <- exp(apply(est, 1, function(z) X0 %*% z)) Lam0 <- unname(colMeans(lam0)) out <- rbind(Lam1, Lam0, Ratio=Lam1 / Lam0) cbind(mean=rowMeans(out), t(apply(out, 1, quantile, c(0.5, 0.025, 0.975)))) } roadside_bias <- list() xn$BCR6 Xn_onroad <- Xn_offroad <- Xn[Xn[,"ROAD01"] == 1,] Xn_offroad[,c("ROAD01","habCl:ROAD01")] <- 0 for (spp in SPP) { cat(spp, "\n");flush.console() resn <- loadSPP(file.path(ROOT, "out", "birds", "results", "josmshf", paste0("birds_abmi-josmshf_", spp, ".Rdata"))) est7 <- getEst(resn, stage=7, na.out=FALSE, Xn) roadside_bias[[spp]] <- pr_fun_for_road(est7, X0=Xn_offroad, X1=Xn_onroad) } #rsb <- data.frame(do.call(rbind, roadside_bias)) #rsb$spp <- SPP #write.csv(rsb, row.names=FALSE, file="~/Dropbox/bam/PIF-AB/results/roadside_bias.csv") #save(roadside_bias, file=file.path(ROOT, "josmshf", "roadside_bias.Rdata")) ## not conclusive: but habCl effect pulls the contrast to more neutral for forest species roadside_coef <- list() for (spp in SPP) { cat(spp, "\n");flush.console() resn <- loadSPP(file.path(ROOT, "out", "birds", "results", "josmshf", paste0("birds_abmi-josmshf_", spp, ".Rdata"))) est7 <- getEst(resn, stage=7, na.out=FALSE, Xn) roadside_coef[[spp]] <- est7[,c("ROAD01","habCl:ROAD01")] } rcf <- t(exp(sapply(roadside_coef, function(z) c(RdOp=mean(z[,1]), RdCl=mean(rowSums(z)))))) boxplot(rcf,ylim=c(0,10)) abline(h=1,col=2) hist(rcf[,2]/rcf[,1]) ## roadside avoidance index rai_data <- data.frame(HAB=xn$hab1ec, ROAD=xn$ROAD01) rai_pred <- matrix(0, nrow(Xn), nrow(tax)) rownames(rai_pred) <- rownames(rai_data) <- rownames(xn) colnames(rai_pred) <- SPP for (spp in SPP) { cat(spp, "\n");flush.console() resn <- loadSPP(file.path(ROOT, "out", "birds", "results", "josmshf", paste0("birds_abmi-josmshf_", spp, ".Rdata"))) est7 <- getEst(resn, stage=7, na.out=FALSE, Xn) rai_pred[,spp] <- pr_fun_for_gof(est7, Xn, off=0) } save(roadside_bias, rai_pred, rai_data, file="e:/peter/josm/2017/roadside_avoidance.Rdata") ## --- unifying the bits and pieces --- source("~/repos/bamanalytics/R/makingsense_functions.R") ## PIF table pif <- read.csv("~/GoogleWork/bam/PIF-AB/popBCR-6AB_v2_22-May-2013.csv") mefa4::compare_sets(tax$English_Name, pif$Common_Name) setdiff(tax$English_Name, pif$Common_Name) pif <- pif[match(tax$English_Name, pif$Common_Name),] rownames(pif) <- rownames(tax) AUC <- read.csv("~/GoogleWork/bam/PIF-AB/results/AUC.csv") rownames(AUC) <- AUC$spp AUC$spp <- NULL AUC <- AUC[rownames(tax),] if (FALSE) { NN <- read.csv("~/GoogleWork/bam/PIF-AB/results/PopSize567.csv") rownames(NN) <- NN$spp NN$spp <- NULL NN <- NN[rownames(tax),] load("e:/peter/josm/2017/stage7/predB/predictionsCI.Rdata") rm(PREDSCI0) PREDSCI <- PREDSCI[,rownames(tax),] / 10^6 N7B <- apply(PREDSCI, 2, colSums) N7CI <- t(apply(N7B, 2, quantile, c(0.5, 0.025, 0.975))) N7mean <- colMeans(N7B) } #load("e:/peter/AB_data_v2016/out/birds/data/mean-qpad-estimates.Rdata") #qpad_vals <- qpad_vals[rownames(tax),] ## roadside_bias, rai_pred, rai_data #load("e:/peter/josm/2017/roadside_avoidance.Rdata") #rsb <- t(sapply(roadside_bias, function(z) z[,1])) ## AvegH, Nhab load("e:/peter/josm/2017/stage7/predB/predictions_HAB.Rdata") ## bootstrap averaged pop size estimate b_fun <- function(h) { N7tb <- c(Mean=mean(colSums(h) / 10^6), quantile(colSums(h) / 10^6, c(0.5, 0.025, 0.975))) N7hb <- t(apply(h, 1, function(z) c(Mean=mean(z / 10^6), quantile(z / 10^6, c(0.5, 0.025, 0.975))))) N7b <- rbind(N7hb, TOTAL=N7tb) N7b } NestAll <- lapply(Nhab, b_fun) NestTot <- t(sapply(NestAll, function(z) z["TOTAL",])) library(mefa4) library(rgdal) library(rgeos) library(sp) library(gstat) library(raster) #library(viridis) load(file.path("e:/peter/AB_data_v2016", "out", "kgrid", "kgrid_table.Rdata")) r <- raster(file.path("~/Dropbox/courses/st-johns-2017", "data", "ABrasters", "dem.asc")) slope <- terrain(r, opt="slope") aspect <- terrain(r, opt="aspect") hill <- hillShade(slope, aspect, 40, 270) od <- setwd("e:/peter/AB_data_v2017/data/raw/xy/bcr/") BCR <- readOGR(".", "BCR_Terrestrial_master") # rgdal BCR <- spTransform(BCR, proj4string(r)) BCR <- gSimplify(BCR, tol=500, topologyPreserve=TRUE) setwd(od) od <- setwd("~/Dropbox/courses/st-johns-2017/data/NatRegAB") AB <- readOGR(".", "Natural_Regions_Subregions_of_Alberta") # rgdal AB <- spTransform(AB, proj4string(r)) AB <- gUnaryUnion(AB, rep(1, nrow(AB))) # province AB <- gSimplify(AB, tol=500, topologyPreserve=TRUE) setwd(od) BCR2AB <- gIntersection(AB, BCR, byid=TRUE) For <- c("Decid", "Mixwood", "Pine", "Conif", "BSpr", "Larch") xn$HAB <- paste0(xn$hab1, ifelse(xn$hab1 %in% For & xn$wtAge*200 >= 80, "O", "")) compare_sets(colnames(AvegH), xn$HAB) setdiff(colnames(AvegH), xn$HAB) xnss <- nonDuplicated(xn, SS, TRUE) xy <- xnss coordinates(xy) <- ~ POINT_X + POINT_Y proj4string(xy) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") xy <- spTransform(xy, proj4string(r)) xy2BCR <- over(xy, BCR) tmp <- xnss[!is.na(xy2BCR) & xy2BCR==24,] tmp <- tmp[!(tmp$PCODE != "BBSAB" & tmp$ROAD01 > 0),] tab <- table(tmp$HAB, tmp$ROAD01) xypt <- xn coordinates(xypt) <- ~ POINT_X + POINT_Y proj4string(xypt) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") xypt <- spTransform(xypt, proj4string(r)) xypt2BCR <- over(xypt, BCR) tabpt <- table(xn$HAB) #Ahab <- tab[,"0"] / sum(tab[,"0"]) Ahab <- colSums(AvegH[,rownames(tab)]) / sum(AvegH[,rownames(tab)]) Whab <- tab[,"1"] / sum(tab[,"1"]) AWhab <- data.frame(Ahab, Whab) NAM <- names(Ahab) h_fun <- function(h) { NN <- h[NAM, "50%"] * 10^6 # back to individuals DD <- NN / colSums(AvegH)[NAM] # density: males / ha sum(DD * Whab) / sum(DD * Ahab) } H <- sapply(NestAll, h_fun) d_fun <- function(h) { NN <- h[NAM, "50%"] * 10^6 # back to individuals DD <- NN / colSums(AvegH)[NAM] # density: males / ha DD } ## forest classes NAM_for <- c("BSpr", "BSprO", "Conif", "ConifO", "Decid", "DecidO", "Larch", "LarchO", "Mixwood", "MixwoodO", "Pine", "PineO") pref_fun <- function(h) { NN <- h[NAM, "50%"] * 10^6 # back to individuals NN_for <- h[NAM[NAM %in% NAM_for], "50%"] * 10^6 # back to individuals sum(NN_for) / sum(NN) } pref <- sapply(NestAll, pref_fun) quantile(pref,seq(0,1,0.25)) ## roadside count effect within BCR 6 source("~/repos/abmianalytics/R/results_functions.R") pr_fun_for_road <- function(est, X0, X1) { lam1 <- exp(apply(est, 1, function(z) X1 %*% z)) Lam1 <- unname(colMeans(lam1)) lam0 <- exp(apply(est, 1, function(z) X0 %*% z)) Lam0 <- unname(colMeans(lam0)) out <- rbind(Lam1, Lam0, Ratio=Lam1 / Lam0) cbind(mean=rowMeans(out), t(apply(out, 1, quantile, c(0.5, 0.025, 0.975)))) } roadside_bias <- list() tmp <- xn[!is.na(xypt2BCR) & xypt2BCR==24,] tmp <- tmp[tmp$PCODE == "BBSAB",] Xn_offroad <- model.matrix(getTerms(mods, "formula"), tmp) colnames(Xn_offroad) <- fixNames(colnames(Xn_offroad)) Xn_onroad <- Xn_offroad Xn_offroad[,c("ROAD01","habCl:ROAD01")] <- 0 for (spp in SPP) { cat(spp, "\n");flush.console() resn <- loadSPP(file.path(ROOT, "out", "birds", "results", "josmshf", paste0("birds_abmi-josmshf_", spp, ".Rdata"))) est7 <- getEst(resn, stage=7, na.out=FALSE, Xn_offroad) roadside_bias[[spp]] <- pr_fun_for_road(est7, X0=Xn_offroad, X1=Xn_onroad) } rsb <- t(sapply(roadside_bias, function(z) z[,1])) ## offsets load("e:/peter/AB_data_v2016/out/birds/data/data-offset-covars.Rdata") tmp <- xn[!is.na(xypt2BCR) & xypt2BCR==24,] offdat <- offdat[rownames(offdat) %in% rownames(tmp),] Xp <- cbind("(Intercept)"=1, as.matrix(offdat[,c("TSSR","JDAY","TSSR2","JDAY2")])) Xq <- cbind("(Intercept)"=1, TREE=offdat$TREE, LCC2OpenWet=ifelse(offdat$LCC2=="OpenWet", 1, 0), LCC4Conif=ifelse(offdat$LCC4=="Conif", 1, 0), LCC4Open=ifelse(offdat$LCC4=="Open", 1, 0), LCC4Wet=ifelse(offdat$LCC4=="Wet", 1, 0)) library(QPAD) load_BAM_QPAD(3) getBAMversion() meanphi <- meantau <- meanphi0 <- meantau0 <- structure(rep(NA, length(SPP)), names=SPP) for (spp in SPP) { cf0 <- exp(unlist(coefBAMspecies(spp, 0, 0))) mi <- bestmodelBAMspecies(spp, type="BIC", model.sra=0:8) cat(spp, unlist(mi), "\n");flush.console() cfi <- coefBAMspecies(spp, mi$sra, mi$edr) Xp2 <- Xp[,names(cfi$sra),drop=FALSE] OKp <- rowSums(is.na(Xp2)) == 0 Xq2 <- Xq[,names(cfi$edr),drop=FALSE] OKq <- rowSums(is.na(Xq2)) == 0 phi1 <- exp(drop(Xp2[OKp,,drop=FALSE] %*% cfi$sra)) tau1 <- exp(drop(Xq2[OKq,,drop=FALSE] %*% cfi$edr)) meanphi[spp] <- mean(phi1) meantau[spp] <- mean(tau1) meanphi0[spp] <- cf0[1] meantau0[spp] <- cf0[2] } qpad_vals <- data.frame(Species=SPP, phi0=meanphi0, tau0=meantau0, phi=meanphi, tau=meantau) ## taxonomy etc --- pop <- tax[,c("Species_ID", "English_Name", "Scientific_Name", "Spp")] ## LH stuff library(lhreg) data(lhreg_data) compare_sets(lhreg_data$spp, rownames(pop)) setdiff(rownames(pop), lhreg_data$spp) pop <- data.frame(pop, lhreg_data[match(rownames(pop), lhreg_data$spp), c("Mig", "Mig2", "Hab2", "Hab3", "Hab4")]) ## pop size estimates --- #pop$Npix <- NestTot[,"Mean"] # M males #pop$Npix <- NestTot[,"50%"] #pop$NpixLo <- NestTot[,"2.5%"] #pop$NpixHi <- NestTot[,"97.5%"] #pop$Npif <- (pif$Population_Estimate_unrounded / pif$Pair_Adjust) / 10^6 # M males pop$Npix <- NestTot[,"50%"] * pif$Pair_Adjust # M inds pop$NpixLo <- NestTot[,"2.5%"] * pif$Pair_Adjust pop$NpixHi <- NestTot[,"97.5%"] * pif$Pair_Adjust pop$Npif <- pif$Population_Estimate_unrounded / 10^6 # M inds ## roadside related metrics pop$Y1 <- rsb[,"Lam1"] pop$Y0 <- rsb[,"Lam0"] ## Tadj and EDR/MDD --- pop$TimeAdj <- pif$Time_Adjust #pop$p3 <- 1-exp(-3 * qpad_vals$phi0) pop$p3 <- 1-exp(-3 * qpad_vals$phi) pop$MDD <- pif$Detection_Distance_m #pop$EDR <- qpad_vals$tau0 * 100 pop$EDR <- qpad_vals$tau * 100 ## QAQC --- pop$AUCin <- AUC$auc7i pop$AUCout <- AUC$auc7o pop$k7 <- AUC$k7 pop$DataQ <- pif$Data_Quality_Rating pop$BbsVar <- pif$BBS_Variance_Rating pop$SpSamp <- pif$Species_Sample_Rating pop$H <- H ## Deltas --- pop$DeltaObs <- log(pop$Npix / pop$Npif) pop$DeltaR <- log(pop$Y0/pop$Y1) pop$DeltaT <- log((1/pop$p3)/pop$TimeAdj) pop$DeltaA <- log((1/pop$EDR^2) / (1/pop$MDD^2)) pop$DeltaH <- log(1/H) # we take inverse because H=1 is the PIF setup pop$DeltaExp <- pop$DeltaR + pop$DeltaT + pop$DeltaA + pop$DeltaH pop$epsilon <- pop$DeltaObs - pop$DeltaExp ## subset --- pop <- droplevels(pop[rowSums(is.na(pop))==0,]) #pop <- droplevels(pop[!is.na(pop$Npif),]) pop <- pop[sort(rownames(pop)),] Dall <- data.frame(Ahab=100*Ahab, Whab=100*Whab, sapply(NestAll, d_fun)[,rownames(pop)]) write.csv(pop, row.names=FALSE, file="~/GoogleWork/bam/PIF-AB/draft2/Table1-estimates.csv") write.csv(Dall, file="~/GoogleWork/bam/PIF-AB/draft2/Table3-densities.csv") write.csv(cbind(Dall[,1:2], n=tabpt), file="~/GoogleWork/bam/PIF-AB/draft2/Table2-habitats.csv") ## --- making the figures --- ## maps pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig1-maps.pdf", width=12, height=9) op <- par(mfrow=c(1,2), mar=c(1,1,1,1)) plot(BCR2AB, col=c(NA, "grey", rep(NA, 11)), border=NA, main="Roadside surveys") plot(AB, col=NA, border=1,add=TRUE) plot(xy[xy@data$ROAD01 == 1,], add=TRUE, pch=19, col=1, cex=0.25) plot(BCR2AB, col=c(NA, "grey", rep(NA, 11)), border=NA, main="Off-road surveys") plot(AB, col=NA, border=1,add=TRUE) plot(xy[xy@data$ROAD01 == 0,], add=TRUE, pch=19, col=1, cex=0.25) par(op) dev.off() xylonlat <- spTransform(xy, CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")) plot(density(coordinates(xylonlat)[,2]), type="n") lines(density(coordinates(xylonlat)[xylonlat@data$PCODE!="BBSAB",2]), col=2) lines(density(coordinates(xylonlat)[xylonlat@data$PCODE=="BBSAB",2]), col=4) library(MASS) library(KernSmooth) dots_box_plot <- function(mat, lines=FALSE, method="box", ...) { set.seed(1) rnd <- runif(nrow(mat), -0.05, 0.05) boxplot(mat, range=0, border="white",...) if (lines) for (i in 2:ncol(mat)) segments(x0=i+rnd-1, x1=i+rnd, y0=mat[,i-1], y1=mat[,i], col="lightgrey") for (i in 1:ncol(mat)) points(i+rnd, mat[,i], pch=19, col="#00000080") if (method == "box") { #boxplot(mat, range=0, add=TRUE, col="#ff000020", names=NA) boxplot(mat, range=0, add=TRUE, col="#00000020", names=NA) } else { v <- 0.2 for (i in 1:ncol(mat)) { xx <- sort(mat[,i]) st <- boxplot.stats(xx) s <- st$stats if (method == "kde") d <- bkde(xx) # uses Normal kernel if (method == "fft") d <- density(xx) # uses FFT if (method == "hist") { h <- hist(xx, plot=FALSE) xv <- rep(h$breaks, each=2) yv <- c(0, rep(h$density, each=2), 0) } else { xv <- d$x yv <- d$y jj <- xv >= min(xx) & xv <= max(xx) xv <- xv[jj] yv <- yv[jj] } yv <- 0.4 * yv / max(yv) polygon(c(-yv, rev(yv))+i, c(xv, rev(xv)), col="#00000020", border="#40404080") polygon(c(-v,-v,v,v)+i, s[c(2,4,4,2)], col="#40404080", border=NA) lines(c(-v,v)+i, s[c(3,3)], lwd=2, col="#00000020") } } invisible(NULL) } pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig2-popsize-old.pdf", width=8, height=8) op <- par(mfrow=c(2,2), las=1, mar=c(4,4,1,2)) dots_box_plot(pop[,c("Npif", "Npix")], lines=TRUE, ylab="Population Size (M singing inds.)", names=c("PIF", "PIX")) dots_box_plot(log(pop[,c("Npif", "Npix")]), lines=TRUE, ylab="log Population Size (M singing inds.)", names=c("PIF", "PIX")) plot(pop[,c("Npif", "Npix")], xlab=expression(N[PIF]), ylab=expression(N[PIX]), pch=19, col="#00000080", xlim=c(0, max(pop[,c("Npif", "Npix")])), ylim=c(0, max(pop[,c("Npif", "Npix")]))) abline(0,1) plot(log(pop[,c("Npif", "Npix")]), xlab=expression(log(N[PIF])), ylab=expression(log(N[PIX])), pch=19, col="#00000080", xlim=range(log(pop[,c("Npif", "Npix")])), ylim=range(log(pop[,c("Npif", "Npix")]))) abline(0,1) par(op) dev.off() pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig2-popsize.pdf", width=7, height=7) op <- par(mfrow=c(1,1), las=1, mar=c(4,4,1,2)) pch <- 19 # ifelse(pop$Npif %[]% list(pop$NpixLo, pop$NpixHi), 21, 19) plot(pop[,c("Npif", "Npix")], xlab=expression(N[PIF]), ylab=expression(N[PIX]), type="n", pch=pch, col="#00000080", xlim=c(0, max(pop[,c("Npif", "Npix")])), ylim=c(0, max(pop[,c("Npif", "Npix")]))) abline(0,1, lty=2) Min <- 3*2 Siz <- 18*2 di <- sqrt(pop[,"Npif"]^2+pop[,"Npix"]^2) > Min pp <- pop[pop[,"Npif"] < Min & pop[,"Npix"] < Min, c("Npif", "Npix")] ppp <- pop[pop[,"Npif"] < Min & pop[,"Npix"] < Min, ] pch2 <- 19 # ifelse(ppp$Npif %[]% list(ppp$NpixLo, ppp$NpixHi), 21, 19) di2 <- sqrt(pp[,"Npif"]^2+pp[,"Npix"]^2) > 1 pp <- pp*Siz/Min pp[,1] <- pp[,1] + (60-Siz) lines(c(0,60-Siz), c(0, 0), col="grey") lines(c(0,60-Siz), c(Min, Siz), col="grey") rect(0, 0, Min, Min) rect(60-Siz, 0, 60-Siz+Min*Siz/Min, Min*Siz/Min, col="white") lines(c(60-Siz, 60), c(0, Siz), col=1, lty=2) points(pp, pch=pch2, col="#00000080") points(pop[,c("Npif", "Npix")], pch=pch, col="#00000080") text(pop[,"Npif"]+1.2*2, pop[,"Npix"]+0, labels=ifelse(di, rownames(pop), ""), cex=0.5) text(pp[,"Npif"]+1.2*2, pp[,"Npix"]+0, labels=ifelse(di2, rownames(pp), ""), cex=0.5) segments(x0=c(60-Siz+c(0, 1, 2, 3)*Siz/3), y0=rep(Siz, 4), y1=rep(Siz, 4)+0.5) text(c(60-Siz+c(0, 1, 2, 3)*Siz/3), rep(Siz, 4)+1, 0:3) dev.off() pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig3-poprank.pdf", width=7, height=7) op <- par(mfrow=c(1,1), las=1, mar=c(4,4,1,2)) rnk <- cbind(rank(pop$Npif), rank(pop$Npix)) #rnk <- 100 * rnk / max(rnk) plot(rnk, #xlab="PIF rank quantile (%)", ylab="PIX rank quantile (%)", xlab=expression(N[PIF]~rank), ylab=expression(N[PIX]~rank), #xlim=c(0,100), ylim=c(0,100), type="n", axes=FALSE) abline(0,1, lty=2) text(rnk, labels=rownames(pop), cex=0.8) axis(1, c(1, 20, 40, 60, 80, 95), c(1, 20, 40, 60, 80, 95)) axis(2, c(1, 20, 40, 60, 80, 95), c(1, 20, 40, 60, 80, 95)) box() #abline(h=c(24,48,72),v=c(24,48,72)) par(op) dev.off() pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig4-components.pdf", width=10, height=7) op <- par(las=1) #mat <- pop[,c("DeltaObs", "DeltaExp", "DeltaR", "DeltaT", "DeltaA", "DeltaH")] #colnames(mat) <- c("OBS", "EXP", "R", "T", "A", "H") mat <- pop[,c("DeltaObs", "DeltaExp", "DeltaT", "DeltaA", "DeltaR", "DeltaH")] colnames(mat) <- c("OBS", "EXP", "T", "A", "R", "H") par(las=1) dots_box_plot(mat, ylab="Log Ratio", method="kde") abline(h=0, col=1, lwd=1,lty=2) off <- 0.2 i <- 1 z <- mat[order(mat[,i], decreasing=TRUE),] text(i+off, head(z[,i], 1), cex=0.8, rownames(z)[1]) text(i+off, tail(z[,i], 2), cex=0.8, rownames(z)[(nrow(z)-1):nrow(z)]) i <- 2 z <- mat[order(mat[,i], decreasing=TRUE),] text(i+off, head(z[,i], 1), cex=0.8, rownames(z)[1]) text(i+off, tail(z[,i], 1), cex=0.8, rownames(z)[nrow(z)]) i <- 5 z <- mat[order(mat[,i], decreasing=TRUE),] text(i+off, head(z[,i], 2), cex=0.8, rownames(z)[1:2]) text(i+off, tail(z[,i], 3), cex=0.8, rownames(z)[(nrow(z)-2):nrow(z)]) i <- 4 z <- mat[order(mat[,i], decreasing=TRUE),] text(i+off, head(z[,i], 1), cex=0.8, rownames(z)[1]) text(i+off, tail(z[,i], 1), cex=0.8, rownames(z)[nrow(z)]) i <- 6 z <- mat[order(mat[,i], decreasing=TRUE),] text(i+off, head(z[,i], 1), cex=0.8, rownames(z)[1]) #text(i+off, tail(z[,i], 1), cex=0.8, rownames(z)[nrow(z)]) for (i in 1:6) { zz1 <- format(mean(mat[,i]), trim = TRUE, scientific = FALSE, digits = 2) zz2 <- format(sd(mat[,i]), trim = TRUE, scientific = FALSE, digits = 2) mtext(paste("Mean =", zz1), side=1,at=i,line=3, cex=0.8) mtext(paste("SD =", zz2), side=1,at=i,line=4, cex=0.8) } par(op) dev.off() mod <- lm(DeltaObs ~ DeltaR + DeltaT + DeltaA + DeltaH, pop) an <- anova(mod) an$Percent <- 100 * an[["Sum Sq"]] / sum(an[["Sum Sq"]]) an <- an[c("Df", "Sum Sq", "Percent", "Mean Sq", "F value", "Pr(>F)")] an summary(mod) summary(mod)$sigma^2 zval <- c(coef(summary(mod))[,1] - c(0, 1, 1, 1, 1))/coef(summary(mod))[,2] round(cbind(coef(summary(mod))[,1:2], ph=2 * pnorm(-abs(zval))), 3) round(an$Percent,1) mod2 <- step(lm(DeltaObs ~ (DeltaR + DeltaT + DeltaA + DeltaH)^2, pop), trace=0) summary(mod2) an2 <- anova(mod2) an2$Percent <- 100 * an2[["Sum Sq"]] / sum(an2[["Sum Sq"]]) an2 <- an2[c("Df", "Sum Sq", "Percent", "Mean Sq", "F value", "Pr(>F)")] an2 ## looking at shared variation vpfun <- function (x, cutoff = 0, digits = 1, Xnames, showNote=FALSE, ...) { x <- x$part vals <- x$indfract[, 3] is.na(vals) <- vals < cutoff if (cutoff >= 0) vals <- round(vals, digits + 1) labs <- format(vals, digits = digits, nsmall = digits + 1) labs <- gsub("NA", "", labs) showvarparts(x$nsets, labs, Xnames=Xnames, ...) if (any(is.na(vals)) && showNote) mtext(paste("Values <", cutoff, " not shown", sep = ""), 1) invisible() } prt <- vegan::varpart(Y=pop$DeltaObs, ~DeltaR, ~DeltaT, ~DeltaA, ~DeltaH, data=pop) pdf("~/GoogleWork/bam/PIF-AB/draft3/FigX-varpart.pdf", width=6, height=6) vpfun(prt, cutoff = 0, digits = 2, Xnames=c("R", "T", "A", "H")) dev.off() ## road avoidance and ordination library(vegan) DD <- as.matrix(t(Dall[,-(1:2)])) NN <- t(t(DD) * Dall$Ahab) NN <- t(NN / rowSums(NN)) Cex <- pop$DeltaObs names(Cex) <- rownames(pop) br <- c(-Inf, -2, -1, -0.1, 0.1, 1, 2, Inf) #c00 <- c('#d7191c','#fdae61','#ffffbf','#abdda4','#2b83ba') c00 <- c('#d7191c','darkgrey','#2b83ba') #c00 <- c("red", "darkgrey", "blue") Col0 <- colorRampPalette(c00)(7) Col <- Col0[cut(Cex, br)] names(Col) <- names(Cex) o <- cca(NN) round(100*eigenvals(o)/sum(eigenvals(o)), 1) round(cumsum(100*eigenvals(o)/sum(eigenvals(o))), 1) pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig6-ordination3.pdf", width=9, height=9) op <- par(las=1) plot(0, type="n", xlim=c(-0.8,1.2), ylim=c(-1,1), xlab="Axis 1", ylab="Axis 2") s2 <- scores(o)$sites s2 <- s2 / max(abs(s2)) for (i in 1:nrow(s2)) arrows(x0=0,y0=0,x1=s2[i,1],y1=s2[i,2], angle=20, length = 0.1, col="darkgrey") text(s2*1.05, labels=rownames(NN),cex=1,col=1) abline(h=0,v=0,lty=2) s1 <- scores(o)$species s1 <- s1 / max(abs(s1)) text(s1[names(Col),]*0.8, labels=colnames(NN),cex=0.75, col=Col) #text(s1[names(Col),]*0.8, labels=colnames(NN),cex=0.75, col=4) for (ii in 1:200) lines(c(0.85, 0.9), rep(seq(-0.55, -0.95, len=200)[ii], 2), col=colorRampPalette(c00)(200)[ii]) text(c(1,1,1)+0.1, c(-0.6, -0.75, -0.9), c(expression(N[PIX] < N[PIF]),expression(N[PIX] == N[PIF]),expression(N[PIX] > N[PIF]))) par(op) dev.off() pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig6-report.pdf", width=8, height=8) op <- par(las=1) Colg <- colorRampPalette(c("red","yellow"))(7)[cut(Cex, br)] names(Colg) <- names(Cex) plot(0, type="n", xlim=c(-0.8,1.2), ylim=c(-1,1), xlab="", ylab="") s1 <- scores(o)$species s1 <- s1 / max(abs(s1)) points(s1[names(Colg),]*0.8, cex=2, col=Colg, pch=19) points(s1[names(Colg),]*0.8, cex=2, col="orange") s2 <- scores(o)$sites s2 <- s2 / max(abs(s2)) for (i in 1:nrow(s2)) arrows(x0=0,y0=0,x1=s2[i,1],y1=s2[i,2], angle=20, length = 0.1, col="darkgrey") text(s2*1.05, labels=rownames(NN),cex=1,col=1) abline(h=0,v=0,lty=2) #text(s1[names(Col),]*0.8, labels=colnames(NN),cex=0.75, col=4) for (ii in 1:200) lines(c(0.85, 0.9), rep(seq(-0.55, -0.95, len=200)[ii], 2), col=colorRampPalette(c("red","yellow"))(200)[ii]) text(c(1,1,1)+0.1, c(-0.6, -0.75, -0.9), c(expression(N[PIX] < N[PIF]),expression(N[PIX] == N[PIF]),expression(N[PIX] > N[PIF]))) par(op) dev.off() pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig6-ordination-all.pdf", width=9, height=9, onefile=TRUE) for (ii in c("DeltaObs", "DeltaExp", "DeltaR", "DeltaT", "DeltaA", "DeltaH")) { Cex <- pop[[ii]] names(Cex) <- rownames(pop) br <- c(-Inf, -2, -1, -0.1, 0.1, 1, 2, Inf) #c00 <- c('#d7191c','#fdae61','#ffffbf','#abdda4','#2b83ba') c00 <- c('#d7191c','darkgrey','#2b83ba') #c00 <- c("red", "darkgrey", "blue") Col0 <- colorRampPalette(c00)(7) Col <- Col0[cut(Cex, br)] names(Col) <- names(Cex) op <- par(las=1) plot(0, type="n", xlim=c(-0.8,1.2), ylim=c(-1,1), xlab="Axis 1", ylab="Axis 2", main=ii) s2 <- scores(o)$sites s2 <- s2 / max(abs(s2)) for (i in 1:nrow(s2)) arrows(x0=0,y0=0,x1=s2[i,1],y1=s2[i,2], angle=20, length = 0.1, col="darkgrey") text(s2*1.05, labels=rownames(NN),cex=1,col=1) abline(h=0,v=0,lty=2) s1 <- scores(o)$species s1 <- s1 / max(abs(s1)) text(s1[names(Col),]*0.8, labels=colnames(NN),cex=0.75, col=Col) for (ii in 1:200) lines(c(0.85, 0.9), rep(seq(-0.55, -0.95, len=200)[ii], 2), col=colorRampPalette(c00)(200)[ii]) text(c(1,1,1)+0.1, c(-0.6, -0.75, -0.9), c(expression(N[PIX] < N[PIF]),expression(N[PIX] == N[PIF]),expression(N[PIX] > N[PIF]))) par(op) } dev.off() ## roadside count/habitat bias figure library(intrval) rd_over <- sapply(roadside_bias[rownames(pop)], function(z) z[1,3:4] %[o]% z[2,3:4]) rd_roadhigher <- sapply(roadside_bias[rownames(pop)], function(z) z[1,3:4] %[<o]% z[2,3:4]) rd_sign <- ifelse(rd_roadhigher, 1, -1) rd_sign[rd_over] <- 0 table(rd_over, rd_roadhigher) table(rd_sign) plot(pop$DeltaR, pop$DeltaH, col=rd_sign+2) abline(h=0, v=0) Cex <- pop$DeltaObs names(Cex) <- rownames(pop) br <- c(-Inf, -2, -1, -0.1, 0.1, 1, 2, Inf) #c00 <- c('#d7191c','#fdae61','#ffffbf','#abdda4','#2b83ba') c00 <- c('#d7191c','darkgrey','#2b83ba') #c00 <- c("red", "darkgrey", "blue") Col0 <- colorRampPalette(c00)(7) Col <- Col0[cut(Cex, br)] names(Col) <- names(Cex) pdf("~/GoogleWork/bam/PIF-AB/draft3/Fig5-count-habitat.pdf", width=7, height=7) op <- par(las=1) cx <- 1 # pop$EDR/100 topl <- pop[,c("DeltaR", "DeltaH")] plot(topl, xlab="R", ylab="H", pch=c(19, 21, 19)[rd_sign+2], cex=cx, col=Col) abline(h=0,v=0,lty=2) #points(topl, cex=cx, pch=21) text(topl[,1], topl[,2]-0.06, labels=ifelse(pop$DeltaR %][% c(-1.5, 0.9), rownames(topl), ""), cex=0.6) for (ii in 1:200) lines(c(1.7, 1.9), rep(seq(-0.55, -0.95, len=200)[ii], 2), col=colorRampPalette(c00)(200)[ii]) text(c(2.5,2.5,2.5)+0.1, c(-0.6, -0.75, -0.9), c(expression(N[PIX] < N[PIF]),expression(N[PIX] == N[PIF]),expression(N[PIX] > N[PIF]))) dev.off() ## ranking pdf("~/GoogleWork/bam/PIF-AB/draft2/Fig2-popsize.pdf", width=7, height=7) op <- par(mfrow=c(1,1), las=1, mar=c(4,4,1,2)) plot(rank(pop$Npif), rank(pop$Npix), xlab="PIF rank", ylab="PIX rank", type="n", pch=19, col="#00000080", ylim=c(0, nrow(pop)), xlim=c(0, nrow(pop))) abline(0,1, lty=2) text(rank(pop$Npif), rank(pop$Npix), labels=rownames(pop), cex=0.4) par(op) dev.off() ## results numbers summary(exp(pop$DeltaObs)) table(pop$Npif < pop$NpixLo) table(pop$Npif > pop$NpixHi) table(pop$Npif %[]% list(pop$NpixLo, pop$NpixHi)) # AMCR AMGO AMRO BARS BBMA BRBL CCSP EAPH EUST HOSP HOWR SAVS SOSP VESP rownames(pop)[pop$Npif > pop$NpixHi] # BANS BAOR CLSW EAKI GRCA LCSP MODO NESP RWBL TRESVEER YHBL rownames(pop)[pop$Npif %[]% list(pop$NpixLo, pop$NpixHi)] # --- plot(Ahab, Whab, type="n", ylim=c(0,max(AWhab)), xlim=c(0,max(AWhab))) abline(0,1) text(Ahab, Whab, names(Ahab), cex=0.7) summary(round(rowSums(mat[,-(1:2)]) - mat[,1], 12)) summary(round(mat[,2]+mat[,"epsilon"] - mat[,1], 12)) mod <- lm(DeltaObs ~ DeltaR + DeltaT + DeltaA + DeltaH, pop) an <- anova(mod) an$Percent <- 100 * an[["Sum Sq"]] / sum(an[["Sum Sq"]]) an <- an[c("Df", "Sum Sq", "Percent", "Mean Sq", "F value", "Pr(>F)")] summary(mod) an cf <- coef(mod) mat2 <- t(t(model.matrix(mod)) * cf) mat2 <- cbind(Obs=pop$DeltaObs, mat2[,-1], eps=pop$DeltaObs-rowSums(mat2)) par(mfrow=c(2,1)) dots_box_plot(mat2) abline(h=0, col=2, lwd=2) dots_box_plot(mat) abline(h=0, col=2, lwd=2) par(las=1) mat2 <- pop[,c("Npif", "Npix")] colnames(mat2) <- c("PIF", "'Pixel'") dots_box_plot(mat2, col="grey", "Population Size (M singing inds.)") library(intrval) table(OVER <- pop$Npif %[]% pop[,c("NpixLo", "NpixHi")]) rownames(pop)[OVER] #v <- tanh(pop$RAI * 0.5) #v <- plogis(pop$RAI)*2-1 #v <- pop$RAI Cex <- pop$DeltaObs names(Cex) <- rownames(pop) br <- c(-Inf, -2, -1, -0.1, 0.1, 1, 2, Inf) Col <- colorRampPalette(c("red", "black", "blue"))(7)[cut(Cex, br)] names(Col) <- rownames(pop) with(pop, plot(log(H), DeltaObs-DeltaExp, type="n", #xlim=c(-0.4, 0.4), ylim=c(-10,10), ylab=expression(Delta[OBS]-Delta[EXP]), xlab=expression(-Delta[H]))) abline(h=0, v=0, col=1, lwd=1, lty=2) abline(lm(I(DeltaObs-DeltaExp) ~ I(log(H)), pop), col=1) with(pop, text(log(H), DeltaObs-DeltaExp, rownames(pop), cex=0.8, col=Col)) legend("topright", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) with(pop, plot(DeltaObs-log(H), DeltaExp, type="n", #xlim=c(-0.4, 0.4), ylim=c(-10,10), ylab=expression(Delta[OBS]-Delta[H]), xlab=expression(Delta[R]+Delta[T]+Delta[A]+epsilon))) abline(h=0, v=0, col=1, lwd=1, lty=2) abline(0, 1) with(pop, text(DeltaObs-log(H), DeltaExp, rownames(pop), cex=0.8, col=Col)) legend("bottomright", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) with(pop, plot(DeltaObs, log(H))) with(pop, plot(epsilon, log(H))) with(pop, plot(PropRd, log(DeltaRes), type="n", ylab=expression(log(Delta[Res])), xlab="Road Avoidance Index")) abline(h=0, v=0, col=1, lwd=1, lty=2) abline(lm(log(DeltaRes) ~ PropRd, pop), col=1) with(pop, text(PropRd, log(DeltaRes), rownames(pop), cex=0.8, col=Col)) legend("topleft", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) o <- cca(rai) plot(0,type="n", xlim=c(-1,1), ylim=c(-1,1)) s1 <- scores(o)$species s1 <- s1 / max(abs(s1)) text(s1[names(Col),], labels=colnames(rai),cex=0.75, col=Col) s2 <- scores(o)$sites s2 <- s2 / max(abs(s2)) text(s2, labels=rownames(rai),cex=1,col=3) points(s1[1,,drop=F],pch=3,col=4,cex=5) abline(h=0,v=0,lty=2) legend("topleft", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) plot(Ahab, Whab, type="n", ylim=c(0,max(AWhab)), xlim=c(0,max(AWhab))) abline(0,1) text(Ahab, Whab, names(Ahab), cex=0.7) op <- par(mar=c(1,1,1,1)) plot(hill, col=grey(0:100/100), legend=FALSE, bty="n", box=FALSE, axes=FALSE) plot(r, legend=FALSE, col=topo.colors(50, alpha=0.35)[26:50], add=TRUE) plot(BCR2AB, col=c("#00000060", NA, rep("#00000060", 11)), add=TRUE) plot(xy[xy@data$PCODE!="BBSAB" & !(!is.na(xy2BCR) & xy2BCR==24),], add=TRUE, pch=19, col="white", cex=0.5) plot(xy[xy@data$PCODE=="BBSAB" & !(!is.na(xy2BCR) & xy2BCR==24),], add=TRUE, pch=19, col="lightblue", cex=0.5) plot(xy[xy@data$PCODE!="BBSAB" & !is.na(xy2BCR) & xy2BCR==24,], add=TRUE, pch=19, cex=0.5) plot(xy[xy@data$PCODE=="BBSAB" & !is.na(xy2BCR) & xy2BCR==24,], add=TRUE, pch=19, col=4, cex=0.5) legend("bottomleft", title="Surveys", pch=c(19, 19, 19, 21), bty="n", col=c("blue", "lightblue", "black", "black"), legend=c("BBS in BCR 6", "BBS outside", "Off road in BCR 6", "Off road outside")) par(op) tab0 <- table(xy@data$HAB) ii1 <- xy@data$PCODE=="BBSAB" & !is.na(xy2BCR) & xy2BCR==24 tab1 <- table(xy@data$HAB, ii1) summary(xnss$POINT_Y[ii1 & xnss$POINT_Y < 58]) # 56.51 latitude ii2 <- xnss$POINT_Y < 56.51 tab2 <- table(xy@data$HAB, ii2) df <- data.frame(tab0/sum(tab0), w1=tab1[,"TRUE"]/sum(tab1[,"TRUE"]), w2=tab2[,"TRUE"]/sum(tab2[,"TRUE"])) all(NAM==rownames(df)) tmp <- t(as.matrix(df[,-1])) rownames(tmp)[1] <- "a" tmp <- tmp[,order(tmp[1,])] par(las=1, mar=c(5,6,2,2)) barplot(100*tmp[1:2,], beside=TRUE, horiz=TRUE, xlab="% representation", legend.text=TRUE) h_fun <- function(h, a, w) { NN <- h[NAM, "50%"] * 10^6 # back to individuals DD <- NN / colSums(AvegH)[NAM] # density: males / ha sum(DD * w) / sum(DD * a) } H1 <- sapply(NestAll, h_fun, a=df$Freq, w=df$w1) H2 <- sapply(NestAll, h_fun, a=df$Freq, w=df$w2) H3 <- sapply(NestAll, h_fun, a=df$Freq, w=df$w1*df$w2/sum(df$w1*df$w2)) names(H1) <- names(H2) <- names(H3) <- names(NestAll) par(mfrow=c(2,2)) plot(H1,H2) plot(log(H1[rownames(pop)]), pop$epsilon) plot(log(H2[rownames(pop)]), pop$epsilon) plot(log(H3[rownames(pop)]), pop$epsilon) cor(cbind(pop$epsilon, H1[rownames(pop)], H2[rownames(pop)], H3[rownames(pop)])) par(mfrow=c(1,3)) logH <- log(H1[rownames(pop)]) with(pop, plot(logH, epsilon, type="n", #xlim=c(-0.4, 0.4), ylim=c(-10,10), ylab=expression(Delta[RES]), xlab=expression(Delta[H]))) abline(h=0, v=0, col=1, lwd=1, lty=2) abline(lm(epsilon ~ logH, pop), col=1) with(pop, text(logH, epsilon, rownames(pop), cex=0.8, col=Col)) legend("topleft", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) logH <- log(H2[rownames(pop)]) with(pop, plot(logH, epsilon, type="n", #xlim=c(-0.4, 0.4), ylim=c(-10,10), ylab=expression(Delta[RES]), xlab=expression(Delta[H]))) abline(h=0, v=0, col=1, lwd=1, lty=2) abline(lm(epsilon ~ logH, pop), col=1) with(pop, text(logH, epsilon, rownames(pop), cex=0.8, col=Col)) legend("topleft", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) logH <- log(H3[rownames(pop)]) with(pop, plot(logH, epsilon, type="n", #xlim=c(-0.4, 0.4), ylim=c(-10,10), ylab=expression(Delta[RES]), xlab=expression(Delta[H]))) abline(h=0, v=0, col=1, lwd=1, lty=2) abline(lm(epsilon ~ logH, pop), col=1) with(pop, text(logH, epsilon, rownames(pop), cex=0.8, col=Col)) legend("topleft", bty="n", fill=c(4,2), border=NA, legend=c("QPAD > PIF", "QPAD < PIF")) par(mfrow=c(1,3)) plot(pop$Npix, pop$Npif, ylim=c(0,7));abline(0,1) plot(pop$Npix, pop$Npif/H1[rownames(pop)], ylim=c(0,7));abline(0,1) plot(pop$Npix, pop$Npif/H2[rownames(pop)], ylim=c(0,7));abline(0,1) plot(log(pop$Npix/pop$Npif), log(H1[rownames(pop)]));abline(h=0,v=0) plot(pop$epsilon, log(H1[rownames(pop)]));abline(h=0,v=0) plot(pop$epsilon+log(H1[rownames(pop)]), log(H1[rownames(pop)]));abline(h=0,v=0) pop$DeltaH <- log(H1[rownames(pop)]) pop$Res1 <- pop$DeltaObs - pop$DeltaT pop$Res2 <- pop$DeltaObs - pop$DeltaT - pop$DeltaA pop$Res3 <- pop$DeltaObs - pop$DeltaT - pop$DeltaA - pop$DeltaR pop$Res4 <- pop$DeltaObs - pop$DeltaT - pop$DeltaA - pop$DeltaR - pop$DeltaH par(mfrow=c(2,1)) mat <- pop[,c("DeltaObs", "DeltaR", "DeltaT", "DeltaA", "DeltaH", "epsilon")] dots_box_plot(mat, col="grey", ylab=expression(Delta)) abline(h=0, col=2, lwd=2) mat <- pop[,c("DeltaObs", "Res1", "Res2", "Res3", "Res4")] dots_box_plot(mat, col="grey", ylab=expression(Delta)) abline(h=0, col=2, lwd=2) yyy <- as.matrix(t(groupMeans(yy, 1, xn$ROAD01))) r2 <- yyy[,"0"]/yyy[,"1"] r2 <- r2[rownames(pop)] plot(r2, exp(pop$DeltaR))
abe355e2694387f6c8bc77ac044ca6312da70aaf
32b18b6d88a47691a6a8d4275268b2c197e90b99
/run_analysis.R
ceb5f412c0c6aeeeffddf48ee5a618ab0230dc79
[]
no_license
BBeise/GettingCleansingData
039e04eee578a2fe53b6089974a3c8b233cb55f2
d09b4cf049212e41d947d09d18443df49bedadfe
refs/heads/master
2020-05-18T12:35:03.204294
2015-03-22T23:25:00
2015-03-22T23:25:00
32,700,516
0
0
null
null
null
null
UTF-8
R
false
false
3,009
r
run_analysis.R
# preliminary stuff library(dplyr) library(tidyr) # read in the datasets activity_labels <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/activity_labels.txt", quote="\"") subject_test <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/test/subject_test.txt", quote="\"") subject_train <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/train/subject_train.txt", quote="\"") features <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/features.txt", quote="\"") y_test <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/test/y_test.txt", quote="\"") y_train <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/train/y_train.txt", quote="\"") X_train <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/train/X_train.txt", quote="\"") X_test <- read.table("~/Google Drive/Training/Data Science/Getting Cleansing Data/Class Project/UCI HAR Dataset/test/X_test.txt", quote="\"") # Step 1 from Project Instruction - Merge the test and training datasets # SubStep 1.1 - creating a Test/Train identifier to the subject tables subj_test_in<-data.frame(subject_test) subj_test_in$group<-"TEST" subj_train_in<-data.frame(subject_train) subj_train_in$group<-"TRAIN" # SubStep 1.2 - rowbinding the test/train subject files to the subject_files # for each row - output: a_subject a_subject<-data.frame(rbind(subj_test_in,subj_train_in)) # SubStep 1.3 - rowbinding and labelling the test/train activity files - output: b_activity b_activity<-data.frame(rbind(y_test,y_train)) colnames(b_activity)<-c("actcode") # SubStep 1.4 - rowbinding the test and training data files and applying colnames - output: c_data c_data<-data.frame(rbind(X_test,X_train)) names.cdata<-t(features) colnames(c_data)<-names.cdata[2,] # SubStep 1.5 - colbinding the subject file to the activity file to the data file - output: comb_raw comb_raw<-cbind(a_subject,b_activity,c_data) # Step 2 - Extract the measurements on the mean and standard deviation for each measurement # SubStep 2.1 - identify the variables of interest and subset on that list variables <- grep("std|mean|Mean",features[,2],value=TRUE) comb_sub1<-comb_raw[,1:3] comb_sub2<-comb_raw[,variables] comb_dat<-cbind(comb_sub1,comb_sub2) # Step 3 - apply activity name through merge names(activity_labels)<-c("actcode","ACTIVITY") mergefile<-merge(activity_labels,comb_dat,by.x="actcode",by.y="actcode",all=TRUE) # Step 4 - label data set with appropriate variable names colnames(mergefile)[3] <- "SUBJID" # Step 5 - create tidy data set of average of each variable for each activity and each subject ############# unable to complete step 5 by submission date
9adaa066e4024d2e441af2a2920383a5b1c92967
c539d183c64dfd4206676803a38e2b1b87022e3f
/qrsvm/man/predict.qrsvm.Rd
f2a2af2d02eb4ccac3eff78743f10a1d98971068
[]
no_license
wothad/qrsvm
c26a97c0702842daa922b8b5da6a2aeaa6cd6b3a
3606547b79116895f0f64a266723c9e0e058312e
refs/heads/master
2021-01-20T12:41:41.771990
2017-05-05T16:22:28
2017-05-05T16:22:28
90,394,299
1
0
null
null
null
null
UTF-8
R
false
true
469
rd
predict.qrsvm.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/predict.qrsvm.R \name{predict.qrsvm} \alias{predict.qrsvm} \title{Predict ann Object oc class "qrsvm"} \usage{ predict.qrsvm(model, newdata) } \arguments{ \item{model}{An object of class "qrsvm"} \item{newdata}{The predictors of the predictable data in an n X m Matrix} } \value{ A numeric vector of predicted values } \description{ Predict ann Object oc class "qrsvm" }
8bb567f4a58d89494ef09622d913cec6bc56c436
d0c44734ab7c3ea3a1a14e2769f175c8dfd60302
/run_analysis.R
d80497230a8cfba496d9f2d4ce63194009009c9d
[]
no_license
rakeshds/runanalysis
fd1e1f5f6ee490b8573b1b37389e020d1a145716
a1bf7a16615ef45f9c530fe8007102e8b51d6419
refs/heads/master
2021-01-01T04:45:08.652049
2016-04-28T08:52:27
2016-04-28T08:52:27
56,919,566
0
0
null
null
null
null
UTF-8
R
false
false
1,331
r
run_analysis.R
##load package library(resahpe2) library(dplyr) ##downlaoding of data url<-"https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" f<-file.path(getwd(),"gdpf.zip") download.file(url,f) ##data make up actname<-read.table("./UCIHARDataset/activity_labels.txt") name_feature<-read.table("./UCIHARDataset/features.txt") name_feature[,2] <- as.character(name_feature[,2]) extract_feature<-grep(".*mean.*|.*std.*",name_feature[,2]) extract_feature.names<-name_feature[extract_feature,2] ##training train_x<- read.table("./UCIHARDataset/train/X_train.txt")[extract_feature] train_y<-read.table("./UCIHARDataset/train/y_train.txt") train_sub<-read.table("./UCIHARDataset/train/subject_train.txt") train<-cbind(train_x,train_y,train_sub) ##testing test_x<- read.table("./UCIHARDataset/test/X_test.txt")[extract_feature] test_y<-read.table("./UCIHARDataset/test/y_test.txt") test_sub<-read.table("./UCIHARDataset/test/subject_test.txt") test<-cbind(test_x,test_y,test_sub) ##merge data merge_data<-rbind(test,train) colnames(merge_data)<-c(extract_feature.names,"activity","subject") ##tidy data average.df <- aggregate(x=merge_data, by=list(act=merge_data$activity, subj=merge_data$subject), FUN=mean) write.table(average.df, './UCIHARDataset/average.txt', row.names = F)
6179e0deaac1df8aeb181afc3e6f2d87a6fec575
24acd216a8755a84e072cc10401f0e495461af26
/EDAcasestudy.R
12f285359fbd34f84269378b42f773bdeb2fadb1
[]
no_license
PrudviBilakanti/Exploratory-Data-Analysis-on-Lending-Club-data
2a72c78bc046d51a7ac8fafa2fa4ff1d71f1a94b
ef0dfb50a39041344d325872fdcad12b86de917d
refs/heads/master
2020-04-09T19:39:45.250801
2018-12-05T16:51:44
2018-12-05T16:51:44
160,549,799
0
0
null
null
null
null
UTF-8
R
false
false
31,852
r
EDAcasestudy.R
library(dplyr) library(tidyr) library(stringr) library(ggplot2) #install ggcorrplot you dont have any such package install.packages("ggcorrplot") library(ggcorrplot) #set working directory df <- read.csv('loan.csv',stringsAsFactors = F,na.strings=c(""," ","NA","n/a","N/A")) # Lets subset the data for the output variable loan_status with value Charged off or Fully paid. df <- subset(df,df$loan_status == 'Charged Off' | df$loan_status == 'Fully Paid') # Lets do some cleaning. # Lets clean columsn with Zero variance df <- df[sapply(df, function(x) n_distinct(x,na.rm = T) > 1)] # Lets get rid of columns which doesnt provide any insights about why user defaults # Below Coumns doesnt have any values that differentiate between Charged off and Fully paid loans or these columns represent values after declaring a loan as charged off # out_prncp,out_prncp_inv,next_pymnt_d,recoveries df <- df[,!(names(df) %in% c('out_prncp','out_prncp_inv','next_pymnt_d','recoveries','id','member_id','url','desc','title','mths_since_last_record','mths_since_last_delinq'))] # Bucket funded_amount into buckets min(df$funded_amnt) max(df$funded_amnt) summary(df$revol_bal) df$funded_amnt_range[between(df$funded_amnt,0,10000)] <- 'Low_fund' df$funded_amnt_range[between(df$funded_amnt,10001,20000)] <- 'Medium_fund' df$funded_amnt_range[df$funded_amnt > 20000] <- 'High_fund' summary(df) # Bucket funded_amount into buckets min(df$funded_amnt_inv) max(df$funded_amnt_inv) df$funded_amnt_inv_range[between(df$funded_amnt_inv,0,10000)] <- 'Low_inv_fund' df$funded_amnt_inv_range[between(df$funded_amnt_inv,10001,20000)] <- 'Medium_inv_fund' df$funded_amnt_inv_range[df$funded_amnt_inv > 20000] <- 'High_inv_fund' # Remove 'months' from term df$term <- gsub(" months","",df$term) # Lets format int_rate column so that we can bucket into segments for further analysis. df$int_rate <- gsub("%","",df$int_rate) df$int_rate <- as.double(df$int_rate) max(df$int_rate) min(df$int_rate) df$int_rate_category[between(df$int_rate,0,10)] <- 'Low_interest' df$int_rate_category[between(df$int_rate,11,20)] <- 'Medium_interest' df$int_rate_category[df$int_rate > 20] <- 'High_interest' # Lets also bucket installment into buckets summary(df$installment) df$installment_category[between(df$installment,0,450)] <- 'Low_installment' df$installment_category[between(df$installment,451,900)] <- 'Medium_installment' df$installment_category[df$installment > 900] <- 'High_intallment' # bucket dti into low medium and high df$dti_category[between(df$dti,0,10)] <- 'Low_dti' df$dti_category[between(df$dti,11,20)] <- 'Medium_dti' df$dti_category[df$dti > 20] <- 'High_dti' # Format the revolving credit utilization revol_util. remove % from the value df$revol_util <- gsub("%","",df$revol_util) df$revol_util <- as.double(df$revol_util) #Lets also bucket the revol_util summary(df$revol_util) df$rev_util_rate[between(df$revol_util,0,25)] <- 'Low_revol_credit' df$rev_util_rate[between(df$revol_util,26,50)] <- 'Average_revol_credit' df$rev_util_rate[between(df$revol_util,51,75)] <- 'above_avg_revol_credit' df$rev_util_rate[between(df$revol_util,76,100)] <- 'High_revol_credit' # extracting the years (so the 0-1 year exp will be represented as 1, 10 or 10+ as 10) df$emp_length <- str_extract(df$emp_length, pattern = '[0-9]+') # round funded amount by investors to match it with other rows df$funded_amnt_inv <- round(df$funded_amnt_inv,0) df$annual_inc <- round(df$annual_inc,0) df$issue_d <- as.Date(paste('1-',df$issue_d,sep = ''),format ='%d-%b-%y') df$issued_month <- as.numeric(format(df$issue_d, "%m")) df$earliest_cr_line <- as.Date(paste('1-',df$earliest_cr_line,sep = ''),format ='%d-%b-%y') df$last_pymnt_d <-as.Date(paste('1-',df$last_pymnt_d,sep = ''),format ='%d-%b-%y') df$issue_year <- format(df$issue_d,"%Y") #sub-grade has number and alphabet associated so we can split to get better insights #subgrade spitting split_sub_grade <- function(x){ return(unlist(str_split(x,''))[2]) } df$sub_grade_no <- as.numeric(unlist(lapply(df$sub_grade, split_sub_grade))) #filling na revo_util with mean df$revol_util[is.na(df$revol_util)] <- 48.7 # Delete title column. ########################################################## UNI VARIATE ANALYSIS ########################################################### #Funded amout by investor distribution ggplot(df,aes(x=funded_amnt_inv,fill=loan_status))+ geom_histogram(bins = 50)+ggtitle('Funded amount by Investor Distribution') #we can see that we have some outliers in distribution mean(df$funded_amnt_inv) ggplot(df, aes(x="",y=funded_amnt_inv))+ geom_boxplot()+ggtitle('Funded amount by Investor Boxplot') #We can identify outliers in boxplot easily summary(df$funded_amnt_inv) #catogery distribution of term ggplot(df,aes(x=term,fill=term))+ geom_bar()+ geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('Terms distribution') # Plotting Interest rate distribution ggplot(df, aes(x=int_rate))+ geom_histogram(binwidth = 5)+ggtitle('Interest rate Distribution') # We can see that interest rate is around 10,15 have high count #Installment Distribution ggplot(df, aes(x=installment))+ geom_histogram(binwidth = 100)+ggtitle('Installment Distribution') #Understanding outliers using boxplot ggplot(df, aes(x="",y=installment))+ geom_boxplot()+ggtitle('Installment Boxplot') #central tendency are affected due to outliers here summary(df$installment) # Analyse Grade catogery using bar plot ggplot(df,aes(x=grade,fill=grade))+ geom_bar()+ geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('grade distribution') #Sub Grade ggplot(df,aes(x=sub_grade_no,fill=factor(sub_grade_no)))+ geom_bar()+ geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('sub_grade_no distribution') # emp df$emp_title <- tolower(df$emp_title) df$emp_title <- gsub("^\\s+|\\s+$", "", df$emp_title) #exp length ggplot(df,aes(x=emp_length,fill=loan_status))+ geom_bar()+theme(axis.text.x = element_text(angle = 90, hjust = 1))+ ggtitle('Employee Experience Bar plot') table(df$home_ownership) # MORTGAGE NONE OTHER OWN RENT # 17659 3 98 3058 18899 ### ggplot(df,aes(x=home_ownership,fill=home_ownership))+ geom_bar()+ geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('Home Ownership Bar plot') # 14 of all egments are defaulted # annual income box plot and histogram #since values are very large log transformation would give better insight ggplot(df,aes(x="",y=annual_inc))+ geom_boxplot()+ coord_trans(y = "log10")+ggtitle('Log Transformed annual income boxplot') ggplot(df,aes(x=annual_inc))+ geom_histogram(bins = 30)+ggtitle('Annual income Histogram') summary(df$annual_inc) #Outliers are affecting central tendency in this feature # Verification Status ggplot(df, aes(x=verification_status,fill=verification_status))+ geom_bar()+ geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('Verification Status Bar plot') #There are high people with not verified as status around 43 # loan status ggplot(df, aes(x=loan_status,fill=loan_status))+ geom_bar()+geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('Loan Status Bar plot') #Here we can see that bank can have losses due to 14.6% of individuals tend to default # Charged Off Current Fully Paid # 0.14167737 0.02870307 0.82961956 # Purpose ggplot(df, aes(x=purpose,fill=purpose))+ geom_bar()+ geom_text(aes(label=paste(round((..count..)/sum(..count..)*100,1),'%'),vjust=-0.3),stat="count")+ ggtitle('Purpose Bar plot')+ theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) # majority people opted loan to consolidate debts(46%), credit card (12%), #home improvements(7.4), major purchase(5.5%) and small bussiness(4.6%) #zip code commented plot for zip as its hard to infer #ggplot(df,aes(x=zip_code,fill=loan_status))+ # geom_bar() # addr_state ggplot(df,aes(x=addr_state,fill=addr_state))+ geom_bar()+ theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) sort(table(df$addr_state),decreasing = T) #These are the top 5 states. most of the loans are from California region # CA NY FL TX NJ # 7099 3812 2866 2727 1850 # dti ggplot(df, aes(x=dti))+ geom_histogram(bins = 50)+ggtitle('DTI Distribution') #we can see a sudden drop in count around 28 ggplot(df, aes(x='',y=dti))+geom_boxplot() # delinq_2yrs ggplot(df,aes(x=factor(delinq_2yrs),fill=factor(delinq_2yrs)))+ geom_bar() sort(table(df$delinq_2yrs),decreasing = T) # Majority of the poeple were not delin1 in last 2 years # Pending formatting on Date column table(df$issue_d) ggplot(df,aes(x=issue_d))+geom_bar()+ggtitle('Issue date histogram') #inq_last_6mths table(df$inq_last_6mths,df$loan_status) ggplot(df, aes(x=inq_last_6mths))+ geom_bar()+ggtitle('inq_last_6mths Distribution') # people with less inq in last 6 months are more #mths_since_last_delinq #ggplot(df,aes(x=mths_since_last_delinq,fill=loan_status))+ # geom_bar() # mths_since_last_delinq dosent seem to effect loan status directly #droped column due to high number of na #mths_since_last_record #ggplot(df,aes(x=mths_since_last_record,fill=loan_status))+ # geom_bar() #we can drop this column as it contains more number of na and is not directly affecting loan status # open_acc Distribution ggplot(df, aes(x=(open_acc),fill=loan_status))+ geom_histogram(bins = 50) # Most of the poeple have credit lines between 2 and 15 #pub_rec ggplot(df,aes(x=factor(pub_rec)))+ geom_bar()+ggtitle('Number of derogatory public records distribution') # Majority of the people had zero derogatory public records # revol_bal ggplot(df, aes(x="",y=revol_bal))+ geom_boxplot()+coord_trans(x = "log")+ggtitle('Transformed annual income boxplot') #we can see many outliers lets plot distribution plot ggplot(df,aes(x=revol_bal))+ geom_histogram(binwidth = 10000) # Most of the poeple had the revol balance between 0 and 25000 # revol_util distribution ggplot(df, aes(x="",y=revol_util))+ geom_boxplot() summary(df$revol_util) # Most of the people utilised 50 % of their revlving credit #after loking at summary and distribution we can impute na values with mean # Total credit lines in borrowers accoun ggplot(df,aes(x=total_acc))+ geom_histogram(bins = 10)+ggtitle('total_acc distribution') # There are more number of people with credit line between 10 to 40 # Outstanding Principle# #ggplot(df, aes(x=out_prncp))+ # geom_histogram()# # This is expected as most of the users have cleared their loans, there will be zero pending principle amount #we can remove feature # Outstanding principle for the amount funded by investors# #ggplot(df,aes(x=out_prncp_inv))+ # geom_histogram() # Same trend with the amount that is funded by investors. #total_pymnt ggplot(df,aes(x=total_pymnt,fill=loan_status))+ geom_histogram(bins = 50) #total payment distribution and its effect on loan status ggplot(df,aes(x=total_pymnt,fill=loan_status))+ geom_histogram(bins = 50)+ggtitle('Total payment and loan status Distribution') ##################### Continues variables Analysis ####### ggplot(df, aes(x=dti, fill = factor(loan_status))) + geom_histogram(aes(y=..density..),bins = 30, position="identity", alpha=0.5,fill="white", color="black")+ geom_density(alpha=0.6) + labs(title = "DTI vs Status", x = "DTI", y = "Status") ggplot(df, aes(x=loan_amnt, fill = factor(loan_status))) + geom_histogram(aes(y=..density..), bins = 30,position="identity", alpha=0.5)+ geom_density(alpha=0.6) + labs(title = "Loan Amount vs Status", x = "Loan Amount", y = "Status") ######################################## BI variate Analysis and Multi Variate analysis ######################################################### #plotting term vs loanstatus ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status') #multi variate on term and loan status ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs grade')+facet_grid(.~grade ) ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs Employee experience')+facet_grid(.~emp_length ) #for 10 year experience 60 month has high default rate ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs verification_status')+facet_grid(.~verification_status ) ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs purpose')+facet_grid(.~purpose ) #debt consolidation has high amount of loan default in both terms ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs home_ownership')+facet_grid(.~home_ownership ) ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs dti_category')+facet_grid(.~dti_category ) ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs installment_category')+facet_grid(.~installment_category ) #low installments has high defaulters ggplot(df,aes(x=term,fill=loan_status))+geom_bar()+ggtitle('Term vs Loan status vs sub_grade_no')+facet_grid(.~sub_grade_no ) #plot home ownership vs loanstatus ggplot(df,aes(x=home_ownership,fill=loan_status))+ggtitle('Home Ownership vs Loan Status')+geom_bar() #mortgage and rent has high amount of defaulters ggplot(df,aes(x=home_ownership,fill=loan_status))+geom_bar()+facet_grid(.~grade)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=home_ownership,fill=loan_status))+ggtitle('Home Ownership vs Loan Status Vs Experiance')+geom_bar()+facet_grid(.~emp_length)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=home_ownership,fill=loan_status))+geom_bar()+facet_grid(.~purpose)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #mortgage,rent purpose has high default in debt consolidation ggplot(df,aes(x=home_ownership,fill=loan_status))+geom_bar()+facet_grid(.~dti_category)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=home_ownership,fill=loan_status))+geom_bar()+ggtitle('Home Ownership vs Loan Status vs installment catogery')+facet_grid(.~installment_category)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #low installment and rent mortage are showing significant pattern ggplot(df,aes(x=home_ownership,fill=loan_status))+geom_bar()+facet_grid(.~sub_grade_no)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #plot emp_length vs loan status and multi varient plots ggplot(df,aes(x=emp_length,fill=loan_status))+geom_bar() ggplot(df,aes(x=emp_length,fill=loan_status))+geom_bar()+facet_grid(.~grade)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=emp_length,fill=loan_status))+geom_bar()+facet_grid(.~emp_length)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #mortgage,rent purpose has high default in debt consolidation ggplot(df,aes(x=emp_length,fill=loan_status))+geom_bar()+facet_grid(.~dti_category)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=emp_length,fill=loan_status))+geom_bar()+facet_grid(.~installment_category)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #low installment and rent mortage are showing significant pattern ggplot(df,aes(x=emp_length,fill=loan_status))+geom_bar()+facet_grid(.~sub_grade_no)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #plot grade vs loan status ggplot(df,aes(x=loan_status,fill=loan_status))+geom_bar()+facet_grid(.~grade)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #grade B,C,D has high amount of defaulters ggplot(df,aes(x=grade,fill=loan_status))+geom_bar()+facet_grid(.~verification_status)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=grade,fill=loan_status))+geom_bar()+facet_grid(.~emp_length)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=grade,fill=loan_status))+geom_bar()+facet_grid(.~dti_category)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=grade,fill=loan_status))+geom_bar()+facet_grid(.~df$home_ownership)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=grade,fill=loan_status))+geom_bar()+facet_grid(.~installment_category)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=grade,fill=loan_status))+geom_bar()+facet_grid(.~sub_grade_no)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #multi variate on term and loan status ggplot(df,aes(x=purpose,fill=loan_status))+geom_bar()+facet_grid(.~grade )+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=purpose,fill=loan_status))+geom_bar()+facet_grid(.~verification_status )+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=purpose,fill=loan_status))+geom_bar()+facet_grid(.~dti_category )+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #medium dti has high rate of defaulters ggplot(df,aes(x=purpose,fill=loan_status))+geom_bar()+facet_grid(.~installment_category )+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #low installments has high defaults ggplot(df,aes(x=purpose,fill=loan_status))+geom_bar()+facet_grid(.~sub_grade_no )+theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplot(df,aes(x=loan_status,fill=loan_status))+geom_bar()+facet_grid(.~installment_category )+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #low installments has high fully paid and high defaulters ggplot(df,aes(x=loan_amnt,y=purpose , col=factor(loan_status)))+geom_point()+geom_jitter() #we can see that debt considolation and small bussiness have good amount of defaulterss ggplot(df,aes(x=loan_amnt,y=purpose , col=loan_status))+geom_point()+ggtitle('Purpose vs Loan Status vs Loan amount vs Installment catogery')+geom_jitter()+facet_grid(.~installment_category ) #medium and low installments with dc and sb has high defaulters ggplot(df,aes(x=loan_amnt,y=purpose , col=loan_status))+geom_point()+geom_jitter()+facet_grid(.~dti_category ) #lets look address ggplot(df,aes(x=addr_state,fill=loan_status))+geom_bar()+ggtitle('Address vs loan Status') #CA and NY has high amount of # ggplot(df,aes(factor(issued_month),fill=loan_status))+ geom_bar(position = 'fill') ggplot(df,aes(x=purpose,fill=loan_status))+ geom_bar(position = 'fill') #small business reltively high defaulters ggplot(df,aes(x=grade,fill=loan_status))+ geom_bar(position = 'fill') #as grade increases charged off increases ggplot(df,aes(x=sub_grade,fill=loan_status))+ geom_bar(position = 'fill') #f5 has highest amount of defaulters ggplot(df,aes(x=home_ownership,fill=loan_status))+ geom_bar(position = 'fill') #none seems to haveno defaulters whihc is good from banks as then can confidently provide loans ggplot(df,aes(x=zip_code,fill=loan_status))+ geom_bar(position = 'fill') ############################################# scatter plot for continues variables##### ## Loan amount - by grade and loan status Grade_total <- df %>% select(grade,loan_status,loan_amnt) %>% group_by(grade,loan_status) %>% summarise(loan_amnt = sum(loan_amnt)) ggplot(Grade_total, aes(x = grade, y = loan_amnt, col = factor(loan_status))) + geom_point(aes(size=loan_amnt)) + labs(title = "Loan amount distribution among loan status and Grade", x = "grade", y = "Amount") ### loan amount by purpose and loan status purpose_total <- df %>% select(purpose,loan_status,loan_amnt) %>% group_by(purpose,loan_status) %>% summarise(loan_amnt = sum(loan_amnt)) ggplot(purpose_total, aes(x = purpose, y = loan_amnt, col = factor(loan_status))) + geom_point(aes(size=loan_amnt)) + theme(axis.text.x = element_text(angle = 90, hjust = 1))+ labs(title = "Loan amount distribution among loan status and purpose", x = "purpose", y = "Amount") ########################################################################## select_if(df, is.numeric) -> df_numeric #correlation plot ggcorrplot(round(cor(df_numeric,use = 'pairwise.complete.obs'),2), hc.order = TRUE, type = "lower", lab = TRUE, lab_size = 3, method="circle", colors = c("tomato2", "white", "springgreen3"), title="Correlogram of variables", ggtheme=theme_bw)+ theme(plot.title = element_text(hjust = 0.5)) # Funded Amount buckets df %>% group_by(funded_amnt_range,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = paste0(round(100 * cnt/sum(cnt), 0), "%")) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=funded_amnt_range,y=percent,fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Defaulters ratio by the funded amount range', x='Funded amount range', y='Percent', fill="Loan_Status")+ geom_text(aes(y=(percent),label=(percent)),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # funded amount by investor df %>% group_by(funded_amnt_inv_range,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = paste0(round(100 * cnt/sum(cnt), 0), "%")) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=funded_amnt_inv_range,y=percent,fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Defaulters ratio by the investors funded amount range', x='Funded amount by investors range', y='Percent', fill="Loan_Status")+ geom_text(aes(y=(percent),label=(percent)),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # As the funded amount and funded amount by investors are nearly the same we clearly see that poeple # with high amount of loans tend to default. # Term and loan status df %>% group_by(term,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = paste0(round(100 * cnt/sum(cnt), 0), "%")) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=term,y=percent,fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by loan term period', x='Term', y='Percent', fill="Loan_Status")+ geom_text(aes(y=(percent),label=(percent)),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # *** Loans with higher term (60 month) tend to default more when compared to 36 months term. # Int rate bucket df %>% filter(int_rate_category != 'NA') %>% group_by(int_rate_category,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=int_rate_category,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by loan term period', x='Term', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # We can see that people with High interest rinterest rates default more # installment_category df %>% filter(installment_category != 'NA') %>% group_by(installment_category,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=installment_category,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by loan installment category', x='installment category', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # Even here we can see that people with high installment tend to default more. # Grade df %>% group_by(grade,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=grade,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by Grade', x='Grade', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # From the plot it is evident that the loan defaulters are high in the groups D to G df %>% filter(emp_length != 'NA') %>% group_by(emp_length,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = paste0(round(100 * cnt/sum(cnt), 0), "%")) %>% ungroup() %>% as.data.frame() df %>% filter(emp_length != 'NA') %>% group_by(emp_length,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=as.factor(emp_length),y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by Employent Length', x='Employment Length', y='Percent', fill="Loan_Status")+ geom_text(aes(label=(percent)),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # The default ration is common across all the employment length. # Home ownership df %>% filter(home_ownership != 'NONE') %>% group_by(home_ownership,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=home_ownership,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by home ownership status', x='Home Ownership', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # Home ownership Rent and Mortgage to contribute to defaulters ratio. # Verification Status df %>% filter(verification_status != 'NA') %>% group_by(verification_status,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=verification_status,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by LC verification of income source and others', x='verification Status', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # In contrast to the general belief, loan defaults are higher in verfied pool. # Purpose df %>% filter(purpose != 'NA') %>% group_by(purpose,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=purpose,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by purpose of the Loans', x='Purpose of the Loan', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # People who took loans to setup small business tend to default ( 27% ) more, # Debit to Income ratio df %>% filter(dti_category != 'NA') %>% group_by(dti_category,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=dti_category,y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by Debit to income ration', x='Debit to income ratio', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # People with high Debt to income ratio tend to default more, 17% of the people defaulted from the higher dt bucket. # delinq_2yrs df %>% filter(delinq_2yrs != 'NA') %>% group_by(delinq_2yrs,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=factor(delinq_2yrs),y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by delinq in last 2yrs', x='Number of Delinq in last 2 years', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) # We have less data with high delinq rate ni last 2 years. So we cannot firmly say that Defaulters ratio is high for the people who were delinq in last 2 years. #inq_last_6mths df %>% filter(inq_last_6mths != 'NA') %>% group_by(inq_last_6mths,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% ggplot(.,aes(x=factor(inq_last_6mths),y=as.numeric(as.character(percent)),fill=loan_status))+ geom_bar(stat = 'identity')+ labs(title='Default ratio by number of inquiries in last 6 months', x='Number of inquiries in last 6 months', y='Percent', fill="Loan_Status")+ geom_text(aes(label=paste(percent,'%')),hjust = 0.5,vjust=1,size=3, position = position_stack(vjust = .5))+ theme(plot.title = element_text(hjust = 0.5)) df %>% filter(inq_last_6mths != 'NA') %>% group_by(inq_last_6mths,loan_status) %>% summarise(cnt = n()) %>% mutate(percent = round(100 * cnt/sum(cnt), 0)) %>% ungroup() %>% as.data.frame() %>% filter(loan_status == 'Charged Off') %>% ggplot(.,aes(x=inq_last_6mths,y=percent,col=loan_status))+ geom_point()+ geom_smooth(method = 'loess') # The Defaulters ratio is slightly high with high number of inquiries. ##################################END of EDA#############################
479302d49ea0b98c679ae071a77907a47283176d
d73a21c656c4b75f0e26ae376209077e739df76c
/public/blog/maps/map_functions.R
acff05ab4680af2631471ce5a4271aaa0525c888
[ "MIT" ]
permissive
hsowards/hayleysowards
af45a572c844b0a153cb6ab87d1f3cac7190ae03
34b62defd6b0260f464c15284d97433941ac66e9
refs/heads/master
2021-07-15T06:08:22.705628
2021-02-01T05:31:08
2021-02-01T05:31:08
232,381,620
0
0
null
null
null
null
UTF-8
R
false
false
781
r
map_functions.R
library(tidyverse) library(osmdata) get_streets <- function(city) { getbb(paste0(city, " United States")) %>% opq() %>% add_osm_feature(key = "highway", value = c("motorway", "primary", "secondary", "tertiary")) %>% osmdata_sf() } get_small_streets <- function(city) { getbb(paste0(city, " United States")) %>% opq() %>% add_osm_feature(key = "highway", value = c("residential", "living_street", "unclassified", "service", "footway")) %>% osmdata_sf() } get_river <- function(city){ getbb(paste0(city, " United States"))%>% opq()%>% add_osm_feature(key = "waterway", value = "river") %>% osmdata_sf() }
43239af51bdfd1482109d1b0ca1cfd65fab7765d
0d5fdf5238436ab70990eb931ca5d9356536882c
/selftrain_gradativo_epoca/treinamento.R
4d4a268a8a4234dd889616ead2a0a015a78591c3
[]
no_license
karlianev/projeto_karliane
632360ae3a86a2c49a9d9d3e0d80777d11e6ed09
38a5a729707425300113d21372f8ca070075cd4c
refs/heads/master
2021-06-30T10:47:01.838081
2021-01-12T21:50:06
2021-01-12T21:50:06
94,321,582
1
4
null
2017-08-02T12:53:09
2017-06-14T11:01:50
R
UTF-8
R
false
false
1,329
r
treinamento.R
#chamando a funcao selfTrain adaptada print("Iniciando Treinamento") #naive if(k==1){ if (t==1){ nbST_gra<- funcSelfTrainGradativo(as.formula(paste(classe,'~', '.')), base_treino_self_training,learner("naiveBayes", list()),'func',0.9,100,1,TRUE,grad) }else if (t==2){ nbST_gra<- funcSelfTrainGradativo(as.formula(paste(classe,'~', '.')), base_treino_self_training,learner("naiveBayes", list()),'func',0.95,100,1,TRUE,grad) } matriz_confusao_gra<-table(predict(nbST_gra, base_teste), base_teste$class) } if(k==2){ if (t==1){ ST_gra <- funcSelfTrainGradativo(as.formula(paste(classe,'~', '.')), base_treino_self_training,learner('rpartXse',list(se=0.5)),'f',0.9,100,1,TRUE,grad) }else if (t==2){ ST_gra <- funcSelfTrainGradativo(as.formula(paste(classe,'~', '.')), base_treino_self_training,learner('rpartXse',list(se=0.5)),'f',0.95,100,1,TRUE,grad) } matriz_confusao_gra=table(predict(ST_gra,base_teste,type='class'),base_teste$class) } n <- length(base_teste$class) acc_gra<-((sum(diag(matriz_confusao_gra)) / n) * 100) acc_g_gra <- c(acc_g_gra, acc_gra) grad_g_acc<-c(grad_g_acc,grad) bd <- c(bd, bd_nome) tx <- c(tx, taxa) cat("\n Acerto global original (%) =", acc_gra) cat('FIM') #, '\t base de dados ', i, '\n', 'total rotulados: ', total_rotulados, '\n')
4cec405f0f9f7b9e8bb6f9e3f594c138f4ca8caa
26151b679705ae098e79fab6c98ca68c093a4f09
/Classification_Techniques/ADiscriminante_Practica_8.R
f11dd60b5c47b1a8438b63bfcc6bb4d188e63e54
[]
no_license
octadelsueldo/Master_DS_CUNEF
2808e5f5fbf564c7c3fdf209d699056ecd75a8af
354f9d4e43cbcf9d47edd85cfcb5010b417a8b3a
refs/heads/main
2023-08-21T22:54:16.712139
2021-10-06T22:33:32
2021-10-06T22:33:32
414,352,378
0
0
null
null
null
null
WINDOWS-1250
R
false
false
2,866
r
ADiscriminante_Practica_8.R
#---------------------------------------------------------------------- # MDS - Tecnicas de Clasificacion # Modelos de AD para Datos del MC. Modelos LDA - QDA # Práctica 8 #---------------------------------------------------------------------- rm(list=ls()) datos<-read.table("Cotizaciones2020.txt",header=T) names(datos) attach(datos) head(datos) #---------------------------------------------------------------------- # Calculo de los Rendimientos #---------------------------------------------------------------------- n <- dim(datos)[1] n RIBEX <- IBEX[2:n]/IBEX[1:n-1] - 1 RSAN <- SAN.MC[2:n] / SAN.MC[1:n-1] - 1 RBBVA <- BBVA.MC[2:n] / BBVA.MC[1:n-1] - 1 RREP <- REP.MC[2:n] / REP.MC[1:n-1] - 1 RITX <- ITX.MC[2:n] / ITX.MC[1:n-1] - 1 RTL5 <- TL5.MC[2:n] / TL5.MC[1:n-1] - 1 #---------------------------------------------------------------------- # Variable RSAN en cuatro categorias #---------------------------------------------------------------------- summary(RSAN) RSANBIN <- cut(RSAN, breaks=c(-Inf, -0.015468,-0.003004, 0.011675, Inf), labels=c("lo", "med", "high", "vhigh")) table(RSANBIN) datos1<-cbind(RSANBIN, RSAN, RIBEX, RBBVA, RREP, RITX, RTL5) datos1<-as.data.frame(datos1) summary(datos1) #---------------------------------------------------------------------- # Analisis discriminante lineal #---------------------------------------------------------------------- library(MASS) sant.lda <- lda(RSANBIN ~ RIBEX+RBBVA, data=datos1) sant.lda plot(sant.lda, pch=16) #Probabilidades a priori sant.lda$prior #Probabilidades a posteriori predict(sant.lda)$posterior # Matriz de confusion predicted.lda <- predict(sant.lda, data = datos1) tabla1<-table(RSANBIN, predicted.lda$class, dnn = c("Grupo real","Grupo Pronosticado")) tabla1 # Precision del modelo sum(diag(tabla1))/sum(tabla1) # Precision de 0.66 # Graficos de Particion library(klaR) partimat(datos1[,c(3,4)],RSANBIN,data=datos1,method="lda",main="Partition Plots") #---------------------------------------------------------------------- # Analisis discriminante cuadratico #---------------------------------------------------------------------- library(MASS) sant.qda <- qda(RSANBIN ~ RIBEX+RBBVA, data=datos1) sant.qda # Comprobar la hipotesis para el QDA library(biotools) boxM(datos1[,c(3,4)],RSANBIN) #Probabilidades a priori sant.qda$prior #Probabilidades a posteriori predict(sant.qda)$posterior # Matriz de confusion predicted.qda <- predict(sant.qda, data = datos1) tabla2<-table(RSANBIN, predicted.qda$class, dnn = c("Grupo real","Grupo Pronosticado")) tabla2 # Precision del modelo sum(diag(tabla2))/sum(tabla2) # 0.67 # Graficos de Particion library(klaR) partimat(datos1[,c(3,4)],RSANBIN,data=datos1,method="qda",main="Partition Plots")
a2fcf2bd936baf0899d916d529df0eb45a11f677
a2099edf0795624d588faae2095f6104944977ab
/inst/shiny/read_delim_dygraph/ui.R
404c9c28518ae9fb9a6a1c18363eaf4aa0511196
[]
no_license
ijlyttle/shinychord
00343338bb7e0fdf33ee703201bc89ecf82e4726
71c6abd6b05d012f1fb54a227f6ca24adb760911
refs/heads/master
2020-05-17T03:58:11.967469
2016-01-29T23:52:00
2016-01-29T23:52:00
40,910,215
14
2
null
2016-01-29T23:52:00
2015-08-17T16:27:03
HTML
UTF-8
R
false
false
421
r
ui.R
library("shiny") library("shinyBS") library("shinyjs") library("shinychord") shinyUI( fluidPage( useShinyjs(), sidebarLayout( sidebarPanel( h4("CSV"), chord_tbl_csv$ui_controller, h4("Dygraph"), chord_dygraph$ui_controller ), mainPanel( h3("CSV"), chord_tbl_csv$ui_view, h3("Dygraph"), chord_dygraph$ui_view ) ) ) )
9f999e63e6491832acaa2af16e1224bc16ee8d47
14f57999626b31adc1d5c68dde59ee9b7428580c
/scripts/safecracker_40.R
a53e2e8523efc5d27bf641aea04a7a8af4c2f4cf
[]
no_license
rocalabern/r-safecracker_40_puzzle
2dcd2cab4fe2a6106b22185c9669b7bd43c20f1b
fc8884340cb71f120c29fde8a42893dc1fb32116
refs/heads/main
2023-07-18T21:45:27.552870
2021-09-19T08:07:36
2021-09-19T08:07:36
407,860,541
0
0
null
null
null
null
UTF-8
R
false
false
411
r
safecracker_40.R
# runApp ---- library(shiny) runApp() # Test local ---- rm(list=ls()) library(plotly) source('tools/load_tools.R', encoding = "utf8") load_tools('tools') c_angles <- c(-9, -4, 4, 0) # solution c_angles <- c(0, 0, 0, 0) c_totals <- calc_totals(c_Layers, c_angles) fig <- plotly_puzzle(c_Layers, c_angles, c_totals) # fig <- fig %>% layout(height = 800, width = 800) fig c_angles c_totals
aee8250a8ca2a1025474aa1a118120c941024af8
d17100a3f8887e627fb33eebd2feac71dbbf5f02
/anomalous_subsequence.R
99f509d73b7b3fa2f334417ebdd642df329ea696
[]
no_license
jeffung/coursework-cypersecurity
28da95476c2cd94cc139def3caf7a1a58cabe5f7
336844efc06022de223ccc3f52232766b845a9b1
refs/heads/master
2020-03-28T21:55:34.250107
2017-08-03T23:29:03
2017-08-03T23:29:03
149,192,504
0
0
null
null
null
null
UTF-8
R
false
false
1,228
r
anomalous_subsequence.R
sampleSize <- 1000 subsequenceSize <- 100 randIndex <- sample(1400616:length(train$Global_active_power), sampleSize) lLikelihood <- as.data.frame(cbind(c(1:1000), c(1:1000), c(1:1000), c(1:1000))) interval <- as.data.frame(cbind(c(1:2), c(1:2), c(1:2), c(1:2))) LLmean <- c(1:4) for (i in 1:1000) { if (randIndex[i] < (length(train$Global_active_power) - sampleSize + 1)) { start <- randIndex[i] end <- start + sampleSize } else { end <- randIndex[i] start <- end - sampleSize } subSeq1 <- data.frame(train$Global_active_power[start:(start + 450)]) colnames(subSeq1) <- c("global_active_power") subSeq2 <- data.frame(train$Global_active_power[(start + 550):end]) colnames(subSeq2) <- c("global_active_power") tmp <- formatMhsmm(data.frame(rbind(subSeq1, subSeq2))) yhat1 <- predict(hmm_8, tmp) lLikelihood[i, 1] <- yhat1$loglik yhat2 <- predict(hmm_10, tmp) lLikelihood[i, 2] <- yhat2$loglik yhat3 <- predict(hmm_12, tmp) lLikelihood[i, 3] <- yhat3$loglik yhat4 <- predict(hmm_14, tmp) lLikelihood[i, 4] <- yhat4$loglik } for (i in 1:4) { interval[1,i] <- max(lLikelihood[, i]) interval[2,i] <- min(lLikelihood[, i]) LLmean[i] <- mean(lLikelihood[, i]) } interval LLmean
f3494cad00e6f1ed3612dd17d84a0556bb23bc77
0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb
/cran/paws.networking/man/cloudfront_list_invalidations.Rd
67561caa9d03c7c4deeff20bfd657da610faef12
[ "Apache-2.0" ]
permissive
paws-r/paws
196d42a2b9aca0e551a51ea5e6f34daca739591b
a689da2aee079391e100060524f6b973130f4e40
refs/heads/main
2023-08-18T00:33:48.538539
2023-08-09T09:31:24
2023-08-09T09:31:24
154,419,943
293
45
NOASSERTION
2023-09-14T15:31:32
2018-10-24T01:28:47
R
UTF-8
R
false
true
1,139
rd
cloudfront_list_invalidations.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cloudfront_operations.R \name{cloudfront_list_invalidations} \alias{cloudfront_list_invalidations} \title{Lists invalidation batches} \usage{ cloudfront_list_invalidations(DistributionId, Marker = NULL, MaxItems = NULL) } \arguments{ \item{DistributionId}{[required] The distribution's ID.} \item{Marker}{Use this parameter when paginating results to indicate where to begin in your list of invalidation batches. Because the results are returned in decreasing order from most recent to oldest, the most recent results are on the first page, the second page will contain earlier results, and so on. To get the next page of results, set \code{Marker} to the value of the \code{NextMarker} from the current page's response. This value is the same as the ID of the last invalidation batch on that page.} \item{MaxItems}{The maximum number of invalidation batches that you want in the response body.} } \description{ Lists invalidation batches. See \url{https://www.paws-r-sdk.com/docs/cloudfront_list_invalidations/} for full documentation. } \keyword{internal}
8e5fadd67721404ec4d6732f60884fc6d38cd123
c3eba48b456943d39f0ff66ef9288159ef4ce4ab
/milestone_1.r
c897c140340d1eda2d52c2b9edf527b7f2b4cee5
[]
no_license
MakotoAsami/INST737
fcd93414e27e412c99d37fe1569f8a89ef80da11
45bf28510267e59762ab30473956d45a05dd3bde
refs/heads/master
2021-04-04T19:21:49.346693
2020-03-19T11:45:37
2020-03-19T11:45:37
248,480,863
0
0
null
null
null
null
UTF-8
R
false
false
3,348
r
milestone_1.r
# load csv file to data frame bank <- read.csv("Databank_1.csv", stringsAsFactors=FALSE) # delete eccessive rows bank <- bank[-(4921:4925),] # create new data frame for 2012 data with 1 row per country bank2012 <- data.frame(Country.Name=c("Afghanistan"),Country.Code=c("AFG"),NY.GDP.MKTP.KD.ZG=c(0), NY.GDP.MKTP.CD=c(0),NY.GDP.PCAP.CD=c(0),NY.GNP.PCAP.CD=c(0),NE.EXP.GNFS.ZS=c(0),BN.KLT.DINV.CD=c(0), NY.GNP.PCAP.PP.CD=c(0),SI.POV.GINI=c(0),FP.CPI.TOTL.ZG=c(0),NY.GDP.DEFL.KD.ZG=c(0),IT.NET.USER.P2=c(0), NE.IMP.GNFS.ZS=c(0),SP.DYN.LE00.IN=c(0),SE.ADT.LITR.ZS=c(0),SL.UEM.TOTL.ZS=c(0),SI.POV.NAHC=c(0), NV.AGR.TOTL.ZS=c(0),EN.ATM.CO2E.PC=c(0),GC.DOD.TOTL.GD.ZS=c(0),SP.POP.TOTL=c(0),stringsAsFactors=FALSE) # transfer data from original dataset to new format using for loop for(i in 1:nrow(bank)) { # when country code matches, copy 2012 data to applicable column if(bank[i,4] %in% bank2012[,2]) { bank2012[bank2012[,1]==bank[i,3],c(bank[i,2])] <- bank[i,c("X2012")] # when country code doesn't match, add a row for the country and copy 2012 data to applicable column } else { newRow <- data.frame(Country.Name=bank[i,3],Country.Code=bank[i,4],NY.GDP.MKTP.KD.ZG=c(0), NY.GDP.MKTP.CD=c(0),NY.GDP.PCAP.CD=c(0),NY.GNP.PCAP.CD=c(0),NE.EXP.GNFS.ZS=c(0), BN.KLT.DINV.CD=c(0),NY.GNP.PCAP.PP.CD=c(0),SI.POV.GINI=c(0),FP.CPI.TOTL.ZG=c(0), NY.GDP.DEFL.KD.ZG=c(0),IT.NET.USER.P2=c(0),NE.IMP.GNFS.ZS=c(0),SP.DYN.LE00.IN=c(0), SE.ADT.LITR.ZS=c(0),SL.UEM.TOTL.ZS=c(0),SI.POV.NAHC=c(0),NV.AGR.TOTL.ZS=c(0),EN.ATM.CO2E.PC=c(0), GC.DOD.TOTL.GD.ZS=c(0),SP.POP.TOTL=c(0),stringsAsFactors=FALSE) bank2012 <- rbind(bank2012,newRow) bank2012[bank2012[,1]==bank[i,3],c(bank[i,2])] <- bank[i,c("X2012")] } } # convert chr type to numeric type bank2012$NY.GDP.MKTP.KD.ZG <- as.numeric(bank2012$NY.GDP.MKTP.KD.ZG) bank2012$NY.GDP.MKTP.CD <- as.numeric(bank2012$NY.GDP.MKTP.CD) bank2012$NY.GDP.PCAP.CD <- as.numeric(bank2012$NY.GDP.PCAP.CD) bank2012$NY.GNP.PCAP.CD <- as.numeric(bank2012$NY.GNP.PCAP.CD) bank2012$NE.EXP.GNFS.ZS <- as.numeric(bank2012$NE.EXP.GNFS.ZS) bank2012$BN.KLT.DINV.CD <- as.numeric(bank2012$BN.KLT.DINV.CD) bank2012$NY.GNP.PCAP.PP.CD <- as.numeric(bank2012$NY.GNP.PCAP.PP.CD) bank2012$SI.POV.GINI <- as.numeric(bank2012$SI.POV.GINI) bank2012$FP.CPI.TOTL.ZG <- as.numeric(bank2012$FP.CPI.TOTL.ZG) bank2012$NY.GDP.DEFL.KD.ZG <- as.numeric(bank2012$NY.GDP.DEFL.KD.ZG) bank2012$IT.NET.USER.P2 <- as.numeric(bank2012$IT.NET.USER.P2) bank2012$NE.IMP.GNFS.ZS <- as.numeric(bank2012$NE.IMP.GNFS.ZS) bank2012$SP.DYN.LE00.IN <- as.numeric(bank2012$SP.DYN.LE00.IN) bank2012$SE.ADT.LITR.ZS <- as.numeric(bank2012$SE.ADT.LITR.ZS) bank2012$SL.UEM.TOTL.ZS <- as.numeric(bank2012$SL.UEM.TOTL.ZS) bank2012$SI.POV.NAHC <- as.numeric(bank2012$SI.POV.NAHC) bank2012$NV.AGR.TOTL.ZS <- as.numeric(bank2012$NV.AGR.TOTL.ZS) bank2012$EN.ATM.CO2E.PC <- as.numeric(bank2012$EN.ATM.CO2E.PC) bank2012$GC.DOD.TOTL.GD.ZS <- as.numeric(bank2012$GC.DOD.TOTL.GD.ZS) bank2012$SP.POP.TOTL <- as.numeric(bank2012$SP.POP.TOTL) # delete rows for aggregated data bank2012 <- bank2012[-(215:246),] # install ggplots package install.packages("ggplot2") library(ggplot2) # plot each country's population and GDP ggplot(data=bank2012,aes(x=SP.POP.TOTL,y=NY.GDP.MKTP.CD))+geom_point(size=3)
bfc6f47f02c9850f429a2b74a6352af214e27ebb
24c417f8bbfff92fec2d7025816348d0fec31ae1
/geneinteraction/mergesum.r
74757aaf7b0116d2d6d481006d9983a90272351b
[]
no_license
Wenxue-PKU/script
3532d2d3a56b5a31c0d841fdeed274e3c149b89b
4d85c218b70422f034a9c4367fa01274f0206d73
refs/heads/master
2022-03-26T07:02:52.857563
2020-01-07T03:20:15
2020-01-07T03:20:15
null
0
0
null
null
null
null
UTF-8
R
false
false
1,075
r
mergesum.r
#!/usr/bin/R # 2018-9-7 # this is used to sum the interaction, only for these data command=matrix(c("Input","i",1,"character", "Output","o",1,"character", "help","h",0,"logical"),byrow=T,ncol=4) args=getopt::getopt(command) if (!is.null(args$help) || is.null(args$Input) || is.null(args$Output)) { cat(paste(getopt::getopt(command, usage = T), "\n")) q() } #suppressMessages(datatest <- readr::read_tsv(args$Input,col_names = c("ID1","ID2","interaction","chr1","chr2"))) #sum(datatest$interaction) suppressMessages(library(dplyr)) uniqw <- read.table(args$Input) colnames(uniqw) <- c("ID1","ID2","NUM") uniqw <- mutate(uniqw, ID3=paste0(ID1,ID2)) total <- summarise(group_by(uniqw,ID3),sum(NUM)) uniquniq <- select(uniqw, ID1,ID2,ID3) uniquniq <- unique(uniquniq) mergeuniq <- merge(y = total, x = uniquniq,by.x = "ID3",by.y = "ID3") colnames(mergeuniq) <- c("ID3","ID1","ID2","NUM") mergeuniq <- select(mergeuniq, ID1,ID2,NUM) write.table(mergeuniq,args$Output,col.names = F, row.names = F,quote = F)
29f29cd298ab0209d6397ccd1ccdf4e9ed76e5f8
dfbdc3b9ef4942f7dd8822c0a67c2da933e009f9
/man/unByteCode.Rd
576c5f60ed02e3a0edd5114ed0c4491bdac364d2
[]
no_license
r-gregmisc/gtools
50453e16f6887cd878a6f10fd1acfba6a1f5ab01
bdabe5340501e3b73f63aaa26ab5c1fa9475066f
refs/heads/master
2023-05-11T11:00:16.825040
2023-05-06T19:01:07
2023-05-06T19:01:07
245,282,085
18
6
null
2023-08-19T17:16:53
2020-03-05T22:40:00
R
UTF-8
R
false
true
2,708
rd
unByteCode.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/unByteCode.R \name{unByteCode} \alias{unByteCode} \alias{unByteCodeAssign} \alias{assignEdgewise} \title{Convert a byte-code function to an interpreted-code function} \usage{ unByteCode(fun) assignEdgewise(name, env, value) unByteCodeAssign(fun) } \arguments{ \item{fun}{function to be modified} \item{name}{object name} \item{env}{namespace} \item{value}{new function body} } \value{ All three functions return a copy of the modified function or assigned value. } \description{ The purpose of these functions is to allow a byte coded function to be converted back into a fully interpreted function as a \emph{temporary} work around for issues in byte-code interpretation. } \details{ \code{unByteCode} returns a copy of the function that is directly interpreted from text rather than from byte-code. \code{assignEdgewise} makes an assignment into a locked environment. \code{unByteCodeAssign} changes the specified function \emph{in its source environment} to be directly interpreted from text rather than from byte-code. The latter two functions no longer work out of the box because \code{assignEdgewise} (which \code{unByteCodeAssign} uses) makes use of an unsafe \code{unlockBinding} call, but running \code{assignEdgewise()} will } \note{ These functions are not intended as a permanent solution to issues with byte-code compilation or interpretation. Any such issues should be promptly reported to the R maintainers via the R Bug Tracking System at \url{https://bugs.r-project.org} and via the R-devel mailing list \url{https://stat.ethz.ch/mailman/listinfo/r-devel}. } \examples{ data(badDend) dist2 <- function(x) as.dist(1 - cor(t(x), method = "pearson")) hclust1 <- function(x) hclust(x, method = "single") distance <- dist2(badDend) cluster <- hclust1(distance) dend <- as.dendrogram(cluster) \dontrun{ ## In R 2.3.0 and earlier crashes with a node stack overflow error plot(dend) ## Error in xy.coords(x, y, recycle = TRUE) : node stack overflow } ## convert stats:::plotNode from byte-code to interpreted-code ## (no longer available unless assignEdgewise is defined by the user) ## unByteCodeAssign(stats:::plotNode) ## illustrated in https://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots # increase recursion limit options("expressions" = 5e4) # now the function does not crash plot(dend) } \references{ These functions were inspired as a work-around to R bug \url{https://bugs.r-project.org/show_bug.cgi?id=15215}. } \seealso{ \code{\link[compiler]{disassemble}}, \code{\link{assign}} } \author{ Gregory R. Warnes \email{greg@warnes.net} } \keyword{programming} \keyword{utilites}
47e3f4148a611698977547c9a7ec9735aad8b24d
efd0d6bec42aa38c1e62b6eecd5b1f4234581ec2
/man/apeff_bife.Rd
b4f92de5b8cdabb09ee98d050b2c0e513b71c24d
[]
no_license
jlegewie/bife
5bdabfd799f8075ea1f55f60002d3d427d45c2c5
2206789a3a8bc157fbd7c8d10aca6243d626dc1d
refs/heads/master
2020-04-06T16:52:13.632534
2018-11-15T02:03:50
2018-11-15T02:03:50
157,637,657
0
0
null
2018-11-15T02:01:55
2018-11-15T02:01:55
null
UTF-8
R
false
true
4,059
rd
apeff_bife.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/apeff_bife.R \name{apeff_bife} \alias{apeff_bife} \title{Average Partial Effects for Binary Choice Models with Fixed Effects} \usage{ apeff_bife(mod, discrete = NULL, bias_corr = "ana", iter_demeaning = 100, tol_demeaning = 1e-05, iter_offset = 1000, tol_offset = 1e-05) } \arguments{ \item{mod}{an object of class \code{bife}.} \item{discrete}{a description of the variables that are discrete regressors. For \code{apeff_bife} this has to be a character string naming the discrete regressors. Default is \code{NULL} (no discrete regressor(s)).} \item{bias_corr}{an optional string that specifies the type of the bias correction: semi or analytical. The value should be any of the values \code{"semi"} or \code{"ana"}. Default is \code{"ana"} (analytical bias-correction). Details are given under \code{Details}.} \item{iter_demeaning}{an optional integer value that specifies the maximum number of iterations of the demeaning algorithm. Default is \code{100}. Details are given under \code{Details}.} \item{tol_demeaning}{an optional number that specifies the tolerance level of the demeaning algorithm. Default is \code{1e-5}. Details are given under \code{Details}.} \item{iter_offset}{an optional integer value that specifies the maximum number of iterations of the offset algorithm for the computation of bias-adjusted fixed effects. Default is \code{1000}. Details are given under \code{Details}.} \item{tol_offset}{an optional number that specifies the tolerance level of the offset algorithm for the computation of bias-adjusted fixed effects. Default is \code{1e-5}. Details are given under \code{Details}.} } \value{ An object of \code{apeff_bife} returns a named matrix with at least a first column "apeff" containing the uncorrected average partial effects of the structural variables. An optional second column "apeff_corrected" is returned containing the corrected average partial effects of the structural variables. } \description{ \code{apeff_bife} is a function used to compute average partial effects for fixed effects binary choice models. It is able to compute bias-corrected average partial effects derived by Newey and Hahn (2004) to account for the incidental parameters bias. } \details{ The semi bias-corrected average partial effects are computed as usual partial effects with the bias-adjusted fixed effects and the bias-corrected structural parameters. The analytical bias-corrected average partial effects follow Newey and Hahn (2004). For further details consult the description of \code{bife}. \strong{Note:} Bias-corrected partial effects can be only returned if the object \code{mod} returns bias-corrected coefficients, i.e. if a bias-correction has been used in the previous \code{bife} command. } \examples{ library("bife") # Load 'psid' dataset dataset <- psid head(dataset) # Fixed effects logit model w/o bias-correction mod_no <- bife(LFP ~ AGE + I(INCH / 1000) + KID1 + KID2 + KID3 | ID, data = dataset, bias_corr = "no") # Compute uncorrected average partial effects for mod_no # Note: bias_corr does not affect the result apeff_bife(mod_no, discrete = c("KID1", "KID2", "KID3")) # Fixed effects logit model with analytical bias-correction mod_ana <- bife(LFP ~ AGE + I(INCH / 1000) + KID1 + KID2 + KID3 | ID, data = dataset) # Compute semi-corrected average partial effects for mod_ana apeff_bife(mod_ana, discrete = c("KID1", "KID2", "KID3"), bias_corr = "semi") # Compute analytical bias-corrected average partial effects # for mod_ana apeff_bife(mod_ana, discrete = c("KID1", "KID2", "KID3")) } \references{ Hahn, J., and W. Newey (2004). "Jackknife and analytical bias reduction for nonlinear panel models." Econometrica 72(4), 1295-1319. Stammann, A., F. Heiss, and D. McFadden (2016). "Estimating Fixed Effects Logit Models with Large Panel Data". Working paper. } \seealso{ \code{\link{bife}} } \author{ Amrei Stammann, Daniel Czarnowske, Florian Heiss, Daniel McFadden }
7aff9b861139fb8d4f7f7dcdd937b02e7158b77c
ca577d7c18719c05bed95bd510d13bdd0c7c13d0
/script(7).R
5cb0592f922314572f60a87ded276d99ec141095
[]
no_license
fredyulie123/R-programming-
eb2b163480510a11626215647b6e3d2c0258a0ed
44c564869f91b13217527c23f030399dc7b71707
refs/heads/main
2023-03-27T10:22:53.510694
2021-03-30T05:06:08
2021-03-30T05:06:08
352,876,241
0
0
null
null
null
null
UTF-8
R
false
false
3,432
r
script(7).R
######################################### ####### R Statistical Programming ####### #### Lesson 10: Model Validation ##### ######################################### # Install and load the caret package install.packages("caret") install.packages("e1071") library(e1071) library(caret) library(ggplot2) library(lattice) # Bring the sonar dataset into our environment library(mlbench) data("Sonar") ?Sonar # We'll take a subset of these sonar columns Sonar <- Sonar[, c(1:20, 61)] library(Metrics) library(tidyverse) #### Building a Basic GLM ## # We can use caret's create data partition to split our data into a # training and test set data.split <- createDataPartition(Sonar$Class, p = .75, list = F) # Index Sonar by data.split to get a training and testing set training <- Sonar[data.split, ] testing <- Sonar[-data.split, ] view(training) # Use glm to try and predict class sonar.glm1 <- glm(Class ~ ., data = training, family = "binomial") summary(sonar.glm1) # Get the predicted probabilities and classes glm1.prob.train <- predict(sonar.glm1, type = "response") glm1.prob.test <- predict(sonar.glm1, newdata = testing, type = "response") glm1.class.train <- ifelse(glm1.prob.train >= .5, "R", "M") glm1.class.test <- ifelse(glm1.prob.test >= .5, "R", "M") #find accuracy of model accuracy(actual = training$Class, predicted = glm1.class.train) accuracy(actual = testing$Class, predicted = glm1.class.test) #### Using Caret for Model Building #### # Use train to develop a model and specify what method you want to use set.seed(1234) sonar.glm.cv <- train(Class ~ ., data = training, method = "glm", family = "binomial", trControl = trainControl(method = "repeatedcv", repeats = 5, number = 3, savePredictions = T)) sonar.glm.cv$results sonar.glm.cv ## train original data set.seed(1234) sonar.cv <- train(Class ~ ., data = Sonar, method = "glm", family = "binomial", trControl = trainControl(method = "repeatedcv", repeats = 5, number = 3, p=.75, savePredictions = T)) sonar.cv$results # By calling resample, we can see how caret performed on each held out fold sonar.glm.cv$resample # We can even plot the accuracy distribution ggplot(data = sonar.glm.cv$resample, aes(x = Accuracy)) + geom_density(alpha = .2, fill="red") # If we needed to get a non-caret object, we can extract the final model sonar.glm2 <- sonar.glm.cv$finalModel summary(sonar.glm2) # We can try different validation methods by specifying them in # the control parameter set.seed(123) sonar.glm.cv2 <- train(Class ~ ., data = training, method = "glm", family = "binomial", trControl=trainControl(method = "boot", number = 5, savePredictions = T)) sonar.glm.cv2 sonar.glm.cv2$resample # Calling predict on the caret output brings back class predictions class.predictions <- predict(sonar.glm.cv, newdata = testing) # We can create confusion matrices with the caret package confusionMatrix(data = class.predictions, reference = testing$Class, positive = "R")
35f631473b76aafd0f33fc865ac960ec2f9b19be
9984fa5e343a7810ae8da2ee3933d1acce9a9657
/twitter_profiles_DB_prep/prepSeveralFiles.R
dea5b6b16874becb0a005f8aef600347770afb91
[]
no_license
kennyjoseph/twitter_matching
4757e7cff241d90167888ce24625be36015b5a93
9fe3a2b970e0ff2f559261f89d29b3202db25920
refs/heads/master
2022-01-05T15:45:19.643082
2019-07-11T20:28:54
2019-07-11T20:28:54
84,259,451
1
0
null
null
null
null
UTF-8
R
false
false
6,799
r
prepSeveralFiles.R
source("cleanProfilesIndexNames.R") # Code in this file: makes calls to preprocessProfileTextFileParallel() from cleanProfilesIndexNames.R. Many times. # See the very bottom for live / best version, which calls runOnManyFiles(). runOnManyFiles = function(inDir, inFiles, outDir) { fullInFiles = file.path(inDir, inFiles) outFs = vector(mode="character", length=length(inFiles)) outFDs = vector(mode="character", length=length(inFiles)) # do a little loop as the easiest way to fill in outFs and outFDs messageFiles = vector(mode="character", length=length(inFiles)) fileCnt = 0 for (filePiece in inFiles) { fileCnt = fileCnt + 1 f2 = filePiece substr(f2, start=nchar(f2) - 2, stop=nchar(f2)) = "csv" outF = file.path(outDir, f2) outFs[fileCnt] = outF substr(f2, start=nchar(f2) - 2, stop=nchar(f2)) = "out" messageF = file.path(outDir, f2) messageFiles[fileCnt] = messageF substr(f2, start=nchar(f2) - 13, stop=nchar(f2)) = "foreign.csv.gz" outFD = file.path(outDir, f2) outFDs[fileCnt] = outFD } print("Created list of args, about to initialize the cluster") initSnowfall() print("About to make the big call! Check *.out files in output directory to see stdout from each run") files = cbind(fullInFiles, outFs, outFDs, messageFiles) #sfClusterApplyLB(files, 1, function(x) safeClusterDoOneFile(x[1], x[2], x[3])) <-- wrong b/c it doesn't do margins, only single vector arg sfApply(files, 1, function(x) capture.output(safeClusterDoOneFile(x[1], x[2], x[3]), file=x[4])) print("finished running!!") sfStop() } initSnowfall = function() { require(snowfall) sfInit(parallel=TRUE,cpus=10) # components for making isDefinitelyForeign work: sfLibrary(stringi) sfExport("onlyForeignAlphabet", "isDefinitelyForeign", "isDefinitelyForeignVectorized") sfExport("USTimeZoneStrings") # components for making putThemTogether work: sfExport("putThemTogether", "getWordsFromTwitterHandle", "splitHandleNative", "getWordsFromTwitterName", "getWordsFromTwitterNameForHandleMatching", "processNameText", "getHandleChunksUsingNameWords", "assembleAlignment", "getContinguousChunksFromDataStructure", "getMatchedChunksFromDataStructure", "itemizeAvailableChunks") # the big function itself sfLibrary(data.table) sfExport("preprocessProfileTextFileParallel", "safeClusterDoOneFile") # helpers I didn't export before sfExport("makeDate", "fixGPS") } safeClusterDoOneFile = function(inFile, outF, outFD) { print(paste("At", Sys.time(), "starting to work on inFile", inFile, ", with outF=", outF, "and outFD=", outFD)) # todo: surround by try/catch result = tryCatch( { preprocessProfileTextFileParallel(inFile, outF, outFileForDroppedForeign=outFD, appendToOutputFiles=F, compressOutput=F, chunkSize=-1, pruneMoreForeign=T, timeProfiling=T, inParallel=F) # while testing/debugging #chunkSize=1000, stopAfterChunk=1, pruneMoreForeign=T, timeProfiling=T, inParallel=F) print(paste("Finished successfully with inFile", inFile)) }, error = function(err) { print(paste("Died on inFile", inFile, "with the following error:")) print(err) } ) } # Example usage / small tests if (F) { inFile = "/home/kjoseph/profile_study/collection_1_22/100_user_info.txt" inFile = "/home/lfriedl/100_noNul-head.txt" # or a small one outF = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data/100_prep.csv" outFD = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data/100_foreign.csv.gz" preprocessProfileTextFileParallel(inFile, outF, outFileForDroppedForeign=outFD, appendToOutputFiles=F, compressOutput=F, chunkSize=5000, pruneMoreForeign=T, timeProfiling=T, inParallel=F, stopAfterChunk=4, needCleanInfile=F) # or outF = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data/100_prepPar.csv" outFD = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data/100_foreignPar.csv.gz" preprocessProfileTextFileParallel(inFile, outF, outFileForDroppedForeign=outFD, appendToOutputFiles=F, compressOutput=F, chunkSize=5000, pruneMoreForeign=T, timeProfiling=T, inParallel=T, stopAfterChunk=4, needCleanInfile=F) # can also experiment with useFread=F flag, but there's no reason to ever use it # test on a whole file inFile = "/home/lfriedl/100_noNul.txt" outF = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data/100_bigPrep.2.csv" outFD = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data/100_bigForeign.2.csv.gz" preprocessProfileTextFileParallel(inFile, outF, outFileForDroppedForeign=outFD, appendToOutputFiles=F, compressOutput=F, chunkSize=-1, pruneMoreForeign=T, timeProfiling=T, inParallel=T, needCleanInfile=F) } # One way to run everything: 1 file at a time, parallelized. This turns out not to be the fast way. if (F) { # actual processing of everything in a directory inDir = "/home/kjoseph/profile_study/collection_20170306" outDir = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data_collection_20170306" fileList = list.files(path=inDir, pattern="_user_info.txt", no..=T) fileCnt = 0 startAtFile = 23 for (filePiece in fileList) { fileCnt = fileCnt + 1 if (fileCnt < startAtFile) { next } inFile = file.path(inDir, filePiece) f2 = filePiece substr(f2, start=nchar(f2) - 2, stop=nchar(f2)) = "csv" outF = file.path(outDir, f2) substr(f2, start=nchar(f2) - 13, stop=nchar(f2)) = "foreign.csv.gz" outFD = file.path(outDir, f2) print(paste("At", Sys.time(), "starting to work on file", fileCnt, ":", filePiece)) preprocessProfileTextFileParallel(inFile, outF, outFileForDroppedForeign=outFD, appendToOutputFiles=F, compressOutput=F, chunkSize=-1, pruneMoreForeign=T, timeProfiling=T, inParallel=T) gc() } print("finished!!!") } # notes: # -error on file 10 : 108_user_info.txt. during putThemTogether, got "Character conversion: Unmappable input sequence / Invalid character. (U_INVALID_CHAR_FOUND)" # -ditto, file 14: 111_user_info.txt # -ditto, file 22 : 119_user_info.txt # -ditto, file 23 : 11_user_info.txt # -ditto, file 27 : 123_user_info.txt if (F) { # a new way to run things inDir = "/home/kjoseph/profile_study/collection_20170306" outDir = "/home/lfriedl/twitter_matching/twitter_profiles_DB_prep/data_collection_20170306" fileList = list.files(path=inDir, pattern="_user_info.txt", no..=T) infiles = rev(sort(fileList)) # start at the bottom, so as not to conflict with other version # we put the first 100 of the reversed list on achtung04. # on achtung03, send the broken ones from before: 14, 22, 23, and 27; then the rest through #130. (100 + 130 = total number of input files) infiles = infiles[1:130] infiles = infiles[c(14, 22, 23, 27:130)] runOnManyFiles(inDir, infiles, outDir) }
1ba3c9bf0c51b4ce31ab40cba123f9669fece645
a5b8244731689344004c67af107b1a531f7e9e2f
/src/07_dashboard_aggs/00_player_ratings.R
d5caa61302228d9ab2d8e1f4943a2bc51e41721b
[]
no_license
jvenzor23/DefensiveCoverageNet
4efcb0f36d6806c71a1750fa9b58ba63c55e3929
85eef09aeede123aa32cb8ad3a8075cd7b7f3e43
refs/heads/master
2023-02-13T22:14:23.396421
2021-01-07T22:52:32
2021-01-07T22:52:32
317,361,746
4
0
null
null
null
null
UTF-8
R
false
false
21,265
r
00_player_ratings.R
# Clean workspace rm(list=ls()) # Setting Working Directory setwd("~/Desktop/CoverageNet/inputs/") # Calling Necessary Libraries library(tidyverse) library(dplyr) library(ggplot2) library(lubridate) library(reticulate) library(gganimate) library(magick) library(fitdistrplus) library(skewt) library(sn) library(broom) library(dplyr) # Reading in The Data ----------------------------------------------------- man_ratings = read.csv("~/Desktop/CoverageNet/src/04_evaluate_players/outputs/overall_player_skills_summary.csv") zone_ratings = read.csv("~/Desktop/CoverageNet/src/05_evaluate_players_zone/outputs/overall_player_skills_summary.csv") sos_ratings = read.csv("~/Desktop/CoverageNet/src/06_evaluate_receivers/outputs/overall_player_sos_skills_summary.csv") player_info = read.csv("~/Desktop/CoverageNet/src/00_data_wrangle/helper_tables/dashboard_player_info.csv") %>% dplyr::select(nflId, displayName, team, games, plays, position) %>% rename(pass_snaps = plays, Pos = position, G = games, `Pass Snaps` = plays) %>% mutate(Player = paste0(displayName, " (", team, ")")) %>% dplyr::select(nflId, Player, G, `Pass Snaps`, Pos) man_zone_classification = rbind( read.csv("~/Desktop/CoverageNet/src/01_identify_man_coverage/outputs/all_positions_pass_attempts_man_zone_classes.csv") %>% dplyr::select(gameId, playId, nflId, zone_probability), read.csv("~/Desktop/CoverageNet/src/01_identify_man_coverage/outputs/all_positions_sacks_man_zone_classes.csv") %>% dplyr::select(gameId, playId, nflId, zone_probability) ) %>% arrange(gameId, playId, nflId) %>% distinct(gameId, playId, nflId, .keep_all = TRUE) man_coverage = read.csv("~/Desktop/CoverageNet/src/01_identify_man_coverage/outputs/man_defense_off_coverage_assignments_all_lbs.csv") zone_coverage = man_zone_classification %>% anti_join(man_coverage, by = c("gameId", "playId", "nflId" = "nflId_def")) man_zone_perc = man_coverage %>% distinct(gameId, playId, nflId_def) %>% group_by(nflId_def) %>% summarize(man_plays = n()) %>% full_join(zone_coverage %>% rename(nflId_def = nflId) %>% distinct(gameId, playId, nflId_def) %>% group_by(nflId_def) %>% summarize(zone_plays = n())) man_zone_perc[is.na(man_zone_perc)] = 0 man_zone_perc = man_zone_perc %>% mutate(`%Man` = man_plays/(zone_plays + man_plays)) %>% dplyr::select(nflId_def, `%Man`) # Overall Aggregation --------------------------------------------- overall_table = man_ratings %>% dplyr::select(nflId_def, eps_man_coverage, routes, accurate_targets, completions_allowed, PB, ball_hawk_pbus, INT, ball_hawk_ints, T, FF, penalties_count, penalties_eps) %>% rename(man_routes = routes, man_accurate_targets = accurate_targets, man_completions_allowed = completions_allowed, man_T = T, man_INTs = INT, man_ball_hawk_ints = ball_hawk_ints, man_PB = PB, man_ball_hawk_pbus = ball_hawk_pbus, man_FF = FF, man_penalties = penalties_count, man_penalties_eps = penalties_eps, `Man EPS` = eps_man_coverage) %>% dplyr::select(nflId_def, `Man EPS`, starts_with("man")) %>% full_join(zone_ratings %>% dplyr::select(nflId_def, eps_zone_coverage, zone_covers, accurate_targets, completions_allowed, PB, ball_hawk_pbus, INT, ball_hawk_ints, T, FF, penalties_count, penalties_eps) %>% rename(zone_accurate_targets = accurate_targets, zone_completions_allowed = completions_allowed, zone_INTs = INT, zone_ball_hawk_ints = ball_hawk_ints, zone_PB = PB, zone_ball_hawk_pbus = ball_hawk_pbus, zone_T = T, zone_FF = FF, zone_penalties = penalties_count, zone_penalties_eps = penalties_eps, `Zone EPS` = eps_zone_coverage) %>% dplyr::select(nflId_def, `Zone EPS`, starts_with("zone"))) %>% full_join(sos_ratings %>% dplyr::select(nflId_def, eps_tot_sos_adj, eps_zone_sos_adj, eps_man_sos_adj) %>% rename(`SOS EPS` = eps_tot_sos_adj, `SOS Man EPS` = eps_man_sos_adj, `SOS Zone EPS` = eps_zone_sos_adj)) overall_table[is.na(overall_table)] = 0 overall_table = overall_table %>% inner_join(player_info %>% rename(nflId_def = nflId)) %>% mutate(EPS = `Man EPS` + `Zone EPS`, `EPS Per Game` = EPS/G, `EPS Per Snap` = EPS/`Pass Snaps`, `SOS EPS Per Game` = `SOS EPS`/G, `SOS EPS Per Snap` = `SOS EPS`/`Pass Snaps`, `EPS Penalties` = man_penalties_eps + zone_penalties_eps, Covers = man_routes + zone_covers, `Accurate TAR` = man_accurate_targets + zone_accurate_targets, C = man_completions_allowed + zone_completions_allowed, INT = man_INTs + zone_INTs, `Ball Hawk INT` = man_ball_hawk_ints + zone_ball_hawk_ints, PB = man_PB + zone_PB, `Ball Hawk PB` = man_ball_hawk_pbus + zone_ball_hawk_pbus, T = man_T + zone_T, FF = man_FF + zone_FF, Penalties = man_penalties + zone_penalties, `Targeted C%` = replace_na(C/`Accurate TAR`, 0), `Hands on Ball % of Targets` = replace_na((INT + PB)/`Accurate TAR`, 0), `Hands on Ball % of Plays` = replace_na((INT + `Ball Hawk INT` + PB + `Ball Hawk PB`)/`Pass Snaps`, 0)) %>% inner_join(man_zone_perc) %>% dplyr::select(nflId_def, Pos, Player, G, `Pass Snaps`, `%Man`, EPS, `Man EPS`, `Zone EPS`, `EPS Per Game`, `EPS Per Snap`, `SOS EPS`, `SOS Man EPS`, `SOS Zone EPS`, `SOS EPS Per Game`, `SOS EPS Per Snap`, Covers, `Accurate TAR`, C, `Targeted C%`, INT, `Ball Hawk INT`, PB, `Ball Hawk PB`, `Hands on Ball % of Targets`, `Hands on Ball % of Plays`, T, FF, Penalties) %>% arrange(desc(EPS)) %>% # dplyr::mutate_if(is.numeric, round, digits=4) %>% # mutate(`%Man` = scales::percent(`%Man`, accuracy = .1), # `Targeted C%` = scales::percent(`Targeted C%`, accuracy = .1), # `Hands on Ball % of Targets` = scales::percent(`Hands on Ball % of Targets`, accuracy = .1), # `Hands on Ball % of Plays` = scales::percent(`Hands on Ball % of Plays`, accuracy = .1)) %>% dplyr::mutate_if(is.numeric, round, digits=2) write.csv(overall_table, "~/Desktop/CoverageNet/src/07_dashboard_aggs/outputs/player_ratings/player_ratings_overall.csv", row.names = FALSE) # Man/Overall Aggregation -------------------------------------------------- man_overall_table = man_ratings %>% dplyr::select(nflId_def, eps_man_coverage, eps_tracking, eps_closing, eps_ball_skills, eps_tackling, eps_int_returns, eps_ball_hawk, routes, accurate_targets, completions_allowed, PB, ball_hawk_pbus, INT, ball_hawk_ints, T, FF, penalties_count, penalties_eps, man_tracking_win_rate) %>% rename(man_routes = routes, man_accurate_targets = accurate_targets, man_completions_allowed = completions_allowed, man_T = T, man_INTs = INT, man_ball_hawk_ints = ball_hawk_ints, man_PB = PB, man_ball_hawk_pbus = ball_hawk_pbus, man_FF = FF, man_penalties = penalties_count, man_penalties_eps = penalties_eps, `Man EPS` = eps_man_coverage, `Man EPS Tracking` = eps_tracking, `Man EPS Closing` = eps_closing, `Man EPS Ball Skills` = eps_ball_skills, `Man EPS Tackling` = eps_tackling, `Man EPS Ball Hawk` = eps_ball_hawk, `Man EPS INT Returns` = eps_int_returns, `Man Tracking Win Rate` = man_tracking_win_rate) %>% dplyr::select(nflId_def, `Man EPS`, starts_with("man")) %>% full_join(sos_ratings %>% rename(`SOS Man EPS` = eps_man_sos_adj, `SOS Man EPS Tracking` = eps_man_tracking_sos_adj, `SOS Man EPS Closing` = eps_man_closing_sos_adj, `SOS Man EPS Ball Skills` = eps_man_ball_skills_sos_adj, `SOS Man EPS Tackling` = eps_man_tackling_sos_adj)) man_overall_table[is.na(man_overall_table)] = 0 man_overall_table = man_overall_table %>% inner_join(player_info %>% rename(nflId_def = nflId)) %>% mutate(`EPS Penalties` = man_penalties_eps, Covers = man_routes, `Man EPS Per Game` = `Man EPS`/G, `Man EPS Per Cover` = `Man EPS`/Covers, `SOS Man EPS Per Game` = `SOS Man EPS`/G, `SOS Man EPS Per Cover` = `SOS Man EPS`/Covers, `Accurate TAR` = man_accurate_targets, C = man_completions_allowed, INT = man_INTs, `Ball Hawk INT` = man_ball_hawk_ints, PB = man_PB, `Ball Hawk PB` = man_ball_hawk_pbus, T = man_T, FF = man_FF, Penalties = man_penalties, `Targeted C%` = replace_na(C/`Accurate TAR`, 0), `Hands on Ball % of Targets` = replace_na((INT + PB)/`Accurate TAR`, 0), `Hands on Ball % of Plays` = replace_na((INT + `Ball Hawk INT` + PB + `Ball Hawk PB`)/`Covers`, 0)) %>% inner_join(man_zone_perc) %>% dplyr::select(nflId_def, Pos, Player, G, `Pass Snaps`, `%Man`, `Man EPS`,`Man EPS Per Game`, `Man EPS Per Cover`, `Man EPS Tracking`, `Man EPS Closing`, `Man EPS Ball Skills`, `Man EPS Tackling`, `Man EPS Ball Hawk`, `Man EPS INT Returns`, `SOS Man EPS`,`SOS Man EPS Per Game`,`SOS Man EPS Per Cover`, `SOS Man EPS Tracking`, `SOS Man EPS Closing`, `SOS Man EPS Ball Skills`, `SOS Man EPS Tackling`, Covers, `Accurate TAR`, C, `Targeted C%`, INT, `Ball Hawk INT`, PB, `Ball Hawk PB`, `Hands on Ball % of Targets`, `Hands on Ball % of Plays`, T, FF, Penalties, `Man Tracking Win Rate`) %>% arrange(desc(`Man EPS`)) %>% # dplyr::mutate_if(is.numeric, round, digits=4) %>% # mutate(`%Man` = scales::percent(`%Man`, accuracy = .1), # `Targeted C%` = scales::percent(`Targeted C%`, accuracy = .1), # `Hands on Ball % of Targets` = scales::percent(`Hands on Ball % of Targets`, accuracy = .1), # `Hands on Ball % of Plays` = scales::percent(`Hands on Ball % of Plays`, accuracy = .1), # `Man Tracking Win Rate` = scales::percent(`Man Tracking Win Rate`, accuracy = .1)) %>% dplyr::mutate_if(is.numeric, round, digits=2) write.csv(man_overall_table, "~/Desktop/CoverageNet/src/07_dashboard_aggs/outputs/player_ratings/player_ratings_man.csv", row.names = FALSE) # Zone Overall Table ------------------------------------------------------ zone_overall_table = zone_ratings %>% dplyr::select(nflId_def, eps_zone_coverage, eps_closing, eps_ball_skills, eps_tackling, eps_int_returns, eps_ball_hawk, zone_covers, accurate_targets, completions_allowed, PB, ball_hawk_pbus, INT, ball_hawk_ints, T, FF, penalties_count, penalties_eps) %>% rename(zone_covers = zone_covers, zone_accurate_targets = accurate_targets, zone_completions_allowed = completions_allowed, zone_T = T, zone_INTs = INT, zone_ball_hawk_ints = ball_hawk_ints, zone_PB = PB, zone_ball_hawk_pbus = ball_hawk_pbus, zone_FF = FF, zone_penalties = penalties_count, zone_penalties_eps = penalties_eps, `Zone EPS` = eps_zone_coverage, `Zone EPS Closing` = eps_closing, `Zone EPS Ball Skills` = eps_ball_skills, `Zone EPS Tackling` = eps_tackling, `Zone EPS Ball Hawk` = eps_ball_hawk, `Zone EPS INT Returns` = eps_int_returns) %>% dplyr::select(nflId_def, `Zone EPS`, starts_with("zone")) %>% full_join(sos_ratings %>% rename(`SOS Zone EPS` = eps_zone_sos_adj, `SOS Zone EPS Closing` = eps_zone_closing_sos_adj, `SOS Zone EPS Ball Skills` = eps_zone_ball_skills_sos_adj, `SOS Zone EPS Tackling` = eps_zone_tackling_sos_adj)) zone_overall_table[is.na(zone_overall_table)] = 0 zone_overall_table = zone_overall_table %>% inner_join(player_info %>% rename(nflId_def = nflId)) %>% mutate(`EPS Penalties` = zone_penalties_eps, Covers = zone_covers, `Zone EPS Per Game` = `Zone EPS`/G, `Zone EPS Per Cover` = `Zone EPS`/Covers, `SOS Zone EPS Per Game` = `SOS Zone EPS`/G, `SOS Zone EPS Per Cover` = `SOS Zone EPS`/Covers, `Accurate TAR` = zone_accurate_targets, C = zone_completions_allowed, INT = zone_INTs, `Ball Hawk INT` = zone_ball_hawk_ints, PB = zone_PB, `Ball Hawk PB` = zone_ball_hawk_pbus, T = zone_T, FF = zone_FF, Penalties = zone_penalties, `Targeted C%` = replace_na(C/`Accurate TAR`, 0), `Hands on Ball % of Targets` = replace_na((INT + PB)/`Accurate TAR`, 0), `Hands on Ball % of Plays` = replace_na((INT + `Ball Hawk INT` + PB + `Ball Hawk PB`)/`Covers`, 0)) %>% inner_join(man_zone_perc) %>% mutate(`%Zone` = 1 - `%Man`) %>% dplyr::select(nflId_def, Pos, Player, G, `Pass Snaps`, `%Zone`, `Zone EPS`, `Zone EPS Per Game`, `Zone EPS Per Cover`, `Zone EPS Closing`, `Zone EPS Ball Skills`, `Zone EPS Tackling`, `Zone EPS Ball Hawk`, `Zone EPS INT Returns`, `SOS Zone EPS`, `SOS Zone EPS Per Game`,`SOS Zone EPS Per Cover`, `SOS Zone EPS Closing`, `SOS Zone EPS Ball Skills`, `SOS Zone EPS Tackling`, Covers, `Accurate TAR`, C, `Targeted C%`,, INT, `Ball Hawk INT`, PB, `Ball Hawk PB`, `Hands on Ball % of Targets`, `Hands on Ball % of Plays`, T, FF, Penalties) %>% arrange(desc(`Zone EPS`)) %>% # dplyr::mutate_if(is.numeric, round, digits=4) %>% # mutate(`%Zone` = scales::percent(`%Zone`, accuracy = .1), # `Targeted C%` = scales::percent(`Targeted C%`, accuracy = .1), # `Hands on Ball % of Targets` = scales::percent(`Hands on Ball % of Targets`, accuracy = .1), # `Hands on Ball % of Plays` = scales::percent(`Hands on Ball % of Plays`, accuracy = .1)) %>% dplyr::mutate_if(is.numeric, round, digits=2) write.csv(zone_overall_table, "~/Desktop/CoverageNet/src/07_dashboard_aggs/outputs/player_ratings/player_ratings_zone.csv", row.names = FALSE) # by route route_man_ratings = read.csv("~/Desktop/CoverageNet/src/04_evaluate_players/outputs/overall_player_skills_summary_by_route.csv") route_zone_ratings = read.csv("~/Desktop/CoverageNet/src/05_evaluate_players_zone/outputs/overall_player_skills_summary_by_route.csv") route_overall_table = route_man_ratings %>% dplyr::select(nflId_def, route, eps_man_coverage, routes, accurate_targets, completions_allowed, PB, INT, T, FF) %>% rename(man_routes = routes, man_accurate_targets = accurate_targets, man_completions_allowed = completions_allowed, man_T = T, man_INTs = INT, man_PB = PB, man_FF = FF, `Man EPS` = eps_man_coverage) %>% dplyr::select(nflId_def, route, `Man EPS`, starts_with("man")) %>% full_join(route_zone_ratings %>% dplyr::select(nflId_def, route, eps_zone_coverage, zone_covers, accurate_targets, completions_allowed, PB, INT, T, FF) %>% rename(zone_accurate_targets = accurate_targets, zone_completions_allowed = completions_allowed, zone_INTs = INT, zone_PB = PB, zone_T = T, zone_FF = FF, `Zone EPS` = eps_zone_coverage) %>% dplyr::select(nflId_def, route, `Zone EPS`, starts_with("zone"))) route_overall_table[is.na(route_overall_table)] = 0 route_overall_table = route_overall_table %>% mutate(EPS = `Man EPS` + `Zone EPS`, Covers = man_routes + zone_covers, `Accurate TAR` = man_accurate_targets + zone_accurate_targets, C = man_completions_allowed + zone_completions_allowed, INT = man_INTs + zone_INTs, PB = man_PB + zone_PB, T = man_T + zone_T, FF = man_FF + zone_FF) %>% inner_join(player_info %>% rename(nflId_def = nflId)) %>% inner_join(man_zone_perc) %>% dplyr::select(nflId_def, Pos, Player, G, `Pass Snaps`, route, `%Man`, EPS, `Man EPS`, `Zone EPS`, Covers, `Accurate TAR`, C, INT, PB, T, FF) %>% arrange(desc(EPS)) %>% dplyr::mutate_if(is.numeric, round, digits=2) write.csv(route_overall_table, "~/Desktop/CoverageNet/src/07_dashboard_aggs/outputs/player_ratings/player_ratings_route_overall.csv", row.names = FALSE) # Man/Overall Aggregation -------------------------------------------------- route_man_overall_table = route_man_ratings %>% dplyr::select(nflId_def, route, eps_man_coverage, eps_tracking, eps_closing, eps_ball_skills, eps_tackling, routes, accurate_targets, completions_allowed, PB, INT, T, FF) %>% rename(man_routes = routes, man_accurate_targets = accurate_targets, man_completions_allowed = completions_allowed, man_T = T, man_INTs = INT, man_PB = PB, man_FF = FF, `Man EPS` = eps_man_coverage, `Man EPS Tracking` = eps_tracking, `Man EPS Closing` = eps_closing, `Man EPS Ball Skills` = eps_ball_skills, `Man EPS Tackling` = eps_tackling) %>% dplyr::select(nflId_def, route, `Man EPS`, starts_with("man")) route_man_overall_table[is.na(route_man_overall_table)] = 0 route_man_overall_table = route_man_overall_table %>% mutate(Covers = man_routes, `Accurate TAR` = man_accurate_targets, C = man_completions_allowed, INT = man_INTs, PB = man_PB, T = man_T, FF = man_FF) %>% inner_join(player_info %>% rename(nflId_def = nflId)) %>% inner_join(man_zone_perc) %>% dplyr::select(nflId_def, Pos, Player, G, `Pass Snaps`, `%Man`,route, `Man EPS`,`Man EPS Tracking`, `Man EPS Closing`, `Man EPS Ball Skills`, `Man EPS Tackling`, Covers, `Accurate TAR`, C, INT, PB, T, FF) %>% arrange(desc(`Man EPS`)) %>% dplyr::mutate_if(is.numeric, round, digits=2) write.csv(route_man_overall_table, "~/Desktop/CoverageNet/src/07_dashboard_aggs/outputs/player_ratings/player_ratings_route_man.csv", row.names = FALSE) # Zone Overall Table ------------------------------------------------------ route_zone_overall_table = route_zone_ratings %>% dplyr::select(nflId_def, route, eps_zone_coverage, eps_closing, eps_ball_skills, eps_tackling, zone_covers, accurate_targets, completions_allowed, PB, INT, T, FF) %>% rename(zone_covers = zone_covers, zone_accurate_targets = accurate_targets, zone_completions_allowed = completions_allowed, zone_T = T, zone_INTs = INT, zone_PB = PB, zone_FF = FF, `Zone EPS` = eps_zone_coverage, `Zone EPS Closing` = eps_closing, `Zone EPS Ball Skills` = eps_ball_skills, `Zone EPS Tackling` = eps_tackling) %>% dplyr::select(nflId_def, route, `Zone EPS`, starts_with("zone")) route_zone_overall_table[is.na(route_zone_overall_table)] = 0 route_zone_overall_table = route_zone_overall_table %>% mutate(Covers = zone_covers, `Accurate TAR` = zone_accurate_targets, C = zone_completions_allowed, INT = zone_INTs, PB = zone_PB, T = zone_T, FF = zone_FF) %>% inner_join(player_info %>% rename(nflId_def = nflId)) %>% inner_join(man_zone_perc) %>% mutate(`%Zone` = 1 - `%Man`) %>% dplyr::select(nflId_def, Pos, Player, G, `Pass Snaps`, `%Zone`, route, `Zone EPS`, `Zone EPS Closing`, `Zone EPS Ball Skills`, `Zone EPS Tackling`, Covers, `Accurate TAR`, C, INT, PB, T, FF) %>% arrange(desc(`Zone EPS`)) %>% dplyr::mutate_if(is.numeric, round, digits=2) write.csv(route_zone_overall_table, "~/Desktop/CoverageNet/src/07_dashboard_aggs/outputs/player_ratings/player_ratings_route_zone.csv", row.names = FALSE)
2e5b3cb3341bcf7b2a2d6030fcd45ad5c8982f15
02e3ab7b73e3a57f0e63849b4ab6cc9f62f3ebc1
/tests/oprobit2.R
ed23861cfee9214d3cd3463da2b5507a8dd6cf60
[]
no_license
zeligdev/ZeligOrdinal
6f0317768b923052d70adf542c773667a4aa8a18
b4348d6bc413faab0402f42811f62ff8e8615896
refs/heads/master
2016-09-06T17:58:53.002123
2011-12-12T20:16:52
2011-12-12T20:16:52
null
0
0
null
null
null
null
UTF-8
R
false
false
393
r
oprobit2.R
# library(ZeligOrdinal) data(sanction) sanction$ncost <- factor(sanction$ncost, ordered = TRUE, levels = c("net gain", "little effect", "modest loss", "major loss")) z.out2 <- zelig(ncost ~ mil + coop, model = "oprobit", data = sanction) x.out2 <- setx(z.out2, fn = NULL) s.out2 <- sim(z.out2, x = x.out2) summary(z.out2) plot(s.out2)
6da5956dec35a8d4b1882a505d1b502c90f8e8fe
29585dff702209dd446c0ab52ceea046c58e384e
/ssh.utils/R/mkdir.R
ba00a45b6197db653f6672a164d2db6ad07e80df
[]
no_license
ingted/R-Examples
825440ce468ce608c4d73e2af4c0a0213b81c0fe
d0917dbaf698cb8bc0789db0c3ab07453016eab9
refs/heads/master
2020-04-14T12:29:22.336088
2016-07-21T14:01:14
2016-07-21T14:01:14
null
0
0
null
null
null
null
UTF-8
R
false
false
2,481
r
mkdir.R
#------------------------------------------------------------------------------- # # Package ssh.utils # # Implementation. # # Sergei Izrailev, 2011-2014 #------------------------------------------------------------------------------- # Copyright 2011-2014 Collective, Inc. # # 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. #------------------------------------------------------------------------------- #' Creates a remote directory with the specified group ownership and permissions. #' #' If the directory already exists, attempts to set the group ownership to the #' \code{user.group}. The allowed group permissions are one of #' \code{c("g+rwx", "g+rx", "go-w", "go-rwx")}, or \code{"-"}. The value #' \code{"-"} means "don't change permissions". #' @param path Directory path. If using \code{remote}, this should be a full path or #' a path relative to the user's home directory. #' @param user.group The user group. If NULL, the default group is used. #' @param remote Remote machine specification for ssh, in format such as \code{user@@server} that does not #' require interactive password entry. For local execution, pass an empty string "" (default). #' @param permissions The group permissions on the directory. Default is 'rwx'. #' @rdname mkdir.remote #' @note This may not work on Windows. # COMPATIBILITY WARNING: WINDOWS mkdir.remote <- function(path, user.group = NULL, remote = "", permissions = c("g+rwx", "g+rx", "go-w", "go-rwx", "-")) { permissions <- match.arg(permissions) if (!file.exists.remote(path, remote = remote)) { run.remote(paste("mkdir -p", path), remote = remote) } if (!is.null(user.group)) { run.remote(paste("chgrp -R", user.group, path), remote = remote) } if (permissions != "-") { run.remote(paste("chmod ", permissions, " ", path, sep = ""), remote = remote) } } #-------------------------------------------------------------------------------
a18c2672cb66eff89cf1e184962aa2b75e45f5b4
9548b1f23cad26a5a5c68cd9b67d45b8280c7040
/man/survival.Rd
0ef3f37c2464ba1780a356b848e09f7582c5afb3
[]
no_license
socale/frailtypack
1e802fe02f735df54655d361512ddef163ec2dd9
fc55e2f58b8f0c972405ae3049e0a21f5d2074fb
refs/heads/master
2021-08-11T02:56:31.967342
2021-06-10T10:06:54
2021-06-10T10:06:54
156,885,473
5
16
null
2020-03-31T13:35:48
2018-11-09T16:03:01
Fortran
UTF-8
R
false
true
698
rd
survival.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/survival.R \name{survival} \alias{survival} \title{Survival function} \usage{ survival(t, ObjFrailty) } \arguments{ \item{t}{time for survival function.} \item{ObjFrailty}{an object from the frailtypack fit.} } \value{ return the value of survival function in t. } \description{ Let t be a continuous variable, we determine the value of the survival function to t after run fit. } \examples{ \dontrun{ #-- a fit Shared data(readmission) fit.shared <- frailtyPenal(Surv(time,event)~dukes+cluster(id)+ strata(sex),n.knots=10,kappa=c(10000,10000),data=readmission) #-- calling survival survival(20,fit.shared) } }
773d4d363704e5727071ebffdc2641d11e2efa97
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/adpss/man/adaptive_analysis_norm_global.Rd
cc3f32aeccf9f0038b1ec5d784ae1cb7f1cd09c7
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
true
3,043
rd
adaptive_analysis_norm_global.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/work_test_norm_global.R \name{adaptive_analysis_norm_global} \alias{adaptive_analysis_norm_global} \title{Analyze data according to a globally efficient adaptive design.} \usage{ adaptive_analysis_norm_global(initial_test = 0, times = 0, stats = 0, costs = 0, final_analysis = TRUE, estimate = TRUE, ci_coef = 0.95, tol_est = 1e-08, input_check = TRUE) } \arguments{ \item{initial_test}{Designate the initial working test generated by \code{work_test_norm_global} function.} \item{times}{The sequence of times (sample size or information level) at which analyses were conducted.} \item{stats}{The sequence of test statistics.} \item{costs}{The sequence of loss required to construct working tests. Specification is optional. Partial specification is allowed, in which non-specification may be represented by \code{0}.} \item{final_analysis}{If \code{TRUE}, the result input will be regarded as complete (no more data will be obtained) and the significance level will be exhausted. If \code{FALSE}, the current analysis will be regarded as an interim analysis and the significance level will be preserved.} \item{estimate}{If \code{TRUE}, p-value, median unbiased estimator and upper and lower confidence limits will be calculated.} \item{ci_coef}{The confidence coefficient. Default is 0.95.} \item{tol_est}{The precision of the calculated results.} \item{input_check}{Indicate whether or not the arguments input by user contain invalid values.} } \value{ It returns whether or not the result was statistically significant, a p-value and an exact confidence limits. } \description{ \code{adaptive_analysis_norm_global} performs an globally efficient adaptive test, a Frequentist adaptive test with the specified significance level with full flexibility. Normality with known variance is assumed for the test statistic (more accurately, the test statistic is assumed to follow Brownian motion.) Null hypothesis is fixed at 0 without loss of generality. Exact p-value, median unbiased estimate and confidence limits proposed by Gao et al. (2013) can also be calculated. For detailed illustration, see \code{vignette("adpss_ex")}. } \examples{ # Construct an initial working test # Note: cost_type_1_err will be automatically calculated when 0 is specified. init_work_test <- work_test_norm_global(min_effect_size = -log(0.65), cost_type_1_err=1683.458) # Sample size calculation sample_size_norm_global( initial_test = init_work_test, effect_size = 11.11 / 20.02, # needs not be MLE time = 20.02, target_power = 0.75, sample_size = TRUE ) } \references{ Kashiwabara, K., Matsuyama, Y. An efficient adaptive design approximating fixed sample size designs. In preparation. Gao, P., Liu, L., Mehta, C. (2013) Exact inference for adaptive group sequential designs. Stat Med 32: 3991-4005. } \seealso{ \code{\link{work_test_norm_global}} and \code{\link{sample_size_norm_global}}. }
e2dce9d131ed7e512734d18563b84e0eee8ac752
c5a08892d45ce23f54771eafe379ed843363f27e
/man/octashift.Rd
f9fe4f5f5676d9f9f78872670cd44e7b874bcaec
[]
no_license
cran/StratigrapheR
9a995ea399e97a449bb94a5c8bb239935b108da0
aff0937f9ee8d0976fc67a46768b32379cf0274b
refs/heads/master
2023-07-26T21:02:30.211546
2023-07-05T23:14:06
2023-07-05T23:14:06
163,700,147
0
0
null
null
null
null
UTF-8
R
false
true
1,326
rd
octashift.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/octashift.R \name{octashift} \alias{octashift} \title{Shifts the order of polygon points} \usage{ octashift(x, y, i, pos, clockwise = NA) } \arguments{ \item{x, y}{the coordinates of the polygons} \item{i}{the identification of the polygons if there are multiple ones} \item{pos}{an integer from 1 to 8 identifying a points, based on the formalism of the \code{\link{octapos}} function} \item{clockwise}{whether to have the points in the polygon be ordered clockwise (T), counterclockwise (F). If NA (which is the default), this will not be addressed} } \value{ a data frame with $x, $y and $i of the polygons as columns } \description{ Shifts the order of polygon points based on octagon-like reference } \examples{ xy <- c(-3,-4,-3,0,-1,-2,-1,0,1,2,1,3,4,5,4,3) dt <- c(1,1.5,2,1,1,1.5,2,2,1,1.5,2,1,1,1.5,2,2) id <- c(rep("B1",3), rep("B2",5), rep("B3",3), rep("B4",5)) out <- octashift(xy, dt, id, pos = 3, clockwise = TRUE) par(mfrow = c(2,1)) plot.new() plot.window(xlim = range(xy) + c(-1, 1), ylim = range(dt) + 0.5 * c(-1, 1)) axis(1) axis(2) multilines(i = id, x = xy, y = dt) plot.new() plot.window(xlim = range(xy) + c(-1, 1), ylim = range(dt) + 0.5 * c(-1, 1)) axis(1) axis(2) multilines(i = out$i, x = out$x, y = out$y) }
eeed3063df995ce81312f2bf3bff2e46290d660d
10c2dbb072e022a11a61f3a86d7f327cae85aa6e
/man/lookup_symbol.Rd
1572b4802c0149acb6c12d61bf8481e4331d3c4b
[]
no_license
dwinter/rensembl
3dda8f10637de87d1663b4a4771baddc2322c8f4
2225df9968dfb1ad8bc3c9c6d1cc8c950cd65453
refs/heads/master
2020-05-30T05:44:51.784053
2016-10-25T21:20:21
2016-10-25T21:22:56
29,898,025
2
3
null
2015-10-12T18:13:29
2015-01-27T04:55:32
R
UTF-8
R
false
true
1,224
rd
lookup_symbol.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/info.r \name{lookup_symbol} \alias{lookup_symbol} \title{Retrieve information about a sequence via gene symbol and species} \usage{ lookup_symbol(symbol, expand = FALSE, species = "homo_sapiens", format = "full", return_format = "json") } \arguments{ \item{symbol}{character, gene symbol(s) from which to retreive information.} \item{species}{character, species from which to retreieve information. See \code{info_species} for a list of avaliable species. Defaults to homo_sapiens} \item{format, }{character, type of record to return either 'full' or 'condensed'} \item{return_format, }{character method by which record is returned. Defaults to \code{json}} \item{symbol}{logical, if \code{TRUE} return information about transcripts/proteins associated with these record. Defaults to \code{FALSE}} } \description{ Retrieve information about a sequence via gene symbol and species } \examples{ human_brca <- lookup_symbol("BRCA2") chimp_brca <- lookup_symbol("BRCA2", species="ptro") chimp_brca_expanded <- lookup_symbol("BRCA2", species="ptro", expand=TRUE) } \references{ \url{lhttp://rest.ensembl.org/documentation/info/symbol_lookup} }
dce67268fd5e8b667f3a87a035143c97a5f7c268
81a2fa3228451179b12779bb0149398cbfc8e9b1
/man/firstOfRepeated.Rd
812db8335f7248743fd4e64895e69d86aeec1777
[]
no_license
cran/wrMisc
c91af4f8d93ad081acef04877fb7558d7de3ffa2
22edd90bd9c2e320e7c2302460266a81d1961e31
refs/heads/master
2023-08-16T21:47:39.481176
2023-08-10T18:00:02
2023-08-10T19:30:33
236,959,523
0
0
null
null
null
null
UTF-8
R
false
true
1,614
rd
firstOfRepeated.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/firstOfRepeated.R \name{firstOfRepeated} \alias{firstOfRepeated} \title{Find first of repeated elements} \usage{ firstOfRepeated(x, silent = FALSE, debug = FALSE, callFrom = NULL) } \arguments{ \item{x}{(charcter or numeric) main input} \item{silent}{(logical) suppress messages} \item{debug}{(logical) display additional messages for debugging} \item{callFrom}{(character) allow easier tracking of message(s) produced} } \value{ list with indices: $indRepeated, $indUniq, $indRedund } \description{ This function works similar to \code{unique}, but provides additional information about which elements of original input \code{'x'} are repeatd by providing indexes realtoe to the input. \code{firstOfRepeated} makes list with 3 elements : $indRepeated.. index for first of repeated 'x', $indUniq.. index of all unique + first of repeated, $indRedund.. index of all redundant entries, ie non-unique (wo 1st). Used for reducing data to non-redundant status, however, for large numeric input the function nonAmbiguousNum() may perform better/faster. NAs won't be considered (NAs do not appear in reported index of results), see also firstOfRepLines() . } \examples{ x <- c(letters[c(3,2:4,8,NA,3:1,NA,5:4)]); names(x) <- 100+(1:length(x)) firstOfRepeated(x) x[firstOfRepeated(x)$indUniq] # only unique with names } \seealso{ \code{\link[base]{duplicated}}, \code{\link{nonAmbiguousNum}}, \code{\link{firstOfRepLines}} gives less detail in output (lines/elements/indexes of omitted not directly accessible) and works fsster }
a78420cc40013b9790ca3774633b404066473f2f
447332bec1373c67f98fff08313d85e89f3c8944
/usefullcode.R
7408ffd975667a4bc727d6ef2157552aa1f18c87
[]
no_license
bitterbalpiraat/random_bear_trajectories
8a254d64529448bc86f8002c56d2034f5f523a88
ee82d3d28c5beb2877b6de14fbd5dfaf4d9ef5c0
refs/heads/master
2021-01-17T10:15:17.921784
2016-03-04T14:20:15
2016-03-04T14:20:15
53,140,136
1
0
null
2016-03-04T14:17:56
2016-03-04T14:17:56
null
UTF-8
R
false
false
3,549
r
usefullcode.R
mypoints <- SpatialPointsDataFrame(cbind(Koski2007$Locale_E, Koski2007$Locale_N), data =Koski2007, proj4string=CRS("+init=epsg:2400")) mypoints@data$tspannum<- as.numeric(mypoints@data$tspan) mypoints<-mypoints[1:10,] # 74:150 bij V<-2000 #tinterval <- 3 mypoints<-SpatialPointsDataFrame(mypoints@coords,as.data.frame(mypoints@data$tspannum)) names(mypoints)<-'tspannum' V<-5000 tinterval <- 2 allpoints<-mypoints[length(mypoints),] xy<-c() time<-c() tvector<- sample(seq(1:(tinterval-1))) plot(mypoints,col='blue',xlim=c(bbox(mypoints)[1][1]-(V/3),bbox(mypoints)[,2][1]+(V/3)),axes=T, ylim=c(bbox(mypoints)[2][1]-(V/3),bbox(mypoints)[,2][2]+(V/3)),xlab='X (meters)', ylab= 'Y (meters)', main='Random trajectory between known points') for(j in seq(1:(length(mypoints)-1))){ startpoint<-mypoints[j,] endpoint<- mypoints[j+1,] newpoints<-mypoints[j,] npoint<-startpoint last_t<-0 t<-(mypoints[j+1,]@data$tspannum-mypoints[j,]@data$tspannum)/tinterval for(i in tvector){ if (i<last_t) { endpoint<-npoint } if (i>last_t) { startpoint<-npoint } buffer1<-gBuffer(startpoint,width=(V*(t*i)),quadsegs=7) buffer2<-gBuffer(endpoint,width=(V*(t*(tinterval-i))),quadsegs=7) plot(buffer1,add=T) plot(buffer2,add=T,border='red') PpA<-gIntersection(buffer1,buffer2) plot(PpA,add=T,col='green') npoint<-spsample(PpA,1,type = 'random') npoint<-SpatialPointsDataFrame(npoint,data=as.data.frame(mypoints@data$tspannum[j]+(i*t))) names(npoint)<-'tspannum' newpoints<-spRbind(newpoints,npoint) last_t<-i } xy<-rbind(xy,newpoints@coords) time <- c(time,newpoints@data$tspannum) } allpoints<-SpatialPointsDataFrame(xy[order(time),],data=as.data.frame(c(time[order(time)]))) names(allpoints)<- 'tspannum' allpoints<-spRbind(allpoints,mypoints[length(mypoints),]) plot(allpoints,add=T,col='blue',pch='*') lines(allpoints@coords) plot(mypoints,add=T,col='red') ## spplot spplot(mypoints,zcol='tspannum',colorkey = list( right = list( # see ?levelplot in package trellis, argument colorkey: fun = draw.colorkey, args = list( key = list( at = seq(0, max(mypoints@data$tspannum), 10), # colour breaks col = bpy.colors(length(seq(0, max(mypoints@data$tspannum), 10))), # colours labels = list( at = c(0, median(seq(0, max(mypoints@data$tspannum), 10)),740), labels = c("0 hour", "370 hour", "740 hour") ) ) ) ) )) #### original function V<-100 tinterval <- 16 allpoints<-mypoints[length(mypoints),] xy<-c() time<-c() for(j in seq(1:(length(mypoints)-1))){ npoint<-mypoints[j,] newpoints<-mypoints[j,] plot(mypoints,col='blue') t<-(mypoints[j+1,]@data$tspannum-mypoints[j,]@data$tspannum)/tinterval m=1 for(i in seq(tinterval,2,-1)){ buffer1<-gBuffer(npoint,width=(V*t),quadsegs=7) buffer2<-gBuffer(mypoints[j+1,],width=(V*t)*i,quadsegs=7) PpA<-gIntersection(buffer1,buffer2) npoint<-spsample(PpA,1,type = 'random') npoint<-SpatialPointsDataFrame(npoint,data=as.data.frame(mypoints@data$tspannum[j]+m*(t))) names(npoint)<-'tspannum' newpoints<-spRbind(newpoints,npoint) m <- m+1 } xy<-rbind(xy,newpoints@coords) time <- c(time,newpoints@data$tspannum) } allpoints<-SpatialPointsDataFrame(xy,data=as.data.frame(c(time))) names(allpoints)<- 'tspannum' allpoints<-spRbind(allpoints,mypoints[length(mypoints),]) plot(allpoints) lines(allpoints@coords) plot(mypoints,add=T,col='red')
a7a24610205721eb019fc82b11dc14d73df75979
c2c3cec8f61b1cca97326dea30d70f7912c37987
/man/dot-mergeAndReturn.Rd
a92fdf305d44a86c1815330767bccf681d0ceb41
[]
no_license
malnirav/hiAnnotator
549747d5c601349a2bf732e28b3d7462e9e1f7c2
9f52365c3e8f396fba947eca377a2c5b5fe87f47
refs/heads/master
2021-07-29T19:14:19.164306
2021-07-27T20:27:19
2021-07-27T20:27:19
3,418,947
3
3
null
null
null
null
UTF-8
R
false
true
543
rd
dot-mergeAndReturn.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hiAnnotator.R \name{.mergeAndReturn} \alias{.mergeAndReturn} \title{Merge results back to the query object and perform additional post processing steps.} \usage{ .mergeAndReturn() } \description{ This function merges all the calculation results back to the query object. Additionally, if any flags were set, the function does the necessary checks and processing to format the return object as required. Evaluation of this function happens in the parent function. }
f32c6e9ed3c0b1d6f0946b8343fe48bee738cecf
d96c0d0c39d1e96fa98154e1206c136ccef7686f
/code/09-write_fns.R
eeaa806c248945895aa48c7a342c97eb25031e08
[]
no_license
HelenaLC/simulation-comparison
d94df6f9a68e46f974d6342a81c75066aad7e1d7
f89e6650f8acae1c32b8fe27d644ec7c7be63051
refs/heads/master
2023-04-17T22:06:50.698560
2022-08-10T09:32:28
2022-08-10T09:32:28
344,418,980
7
3
null
null
null
null
UTF-8
R
false
false
103
r
09-write_fns.R
pat <- paste0("^", wcs$pat) fns <- list.files("outs", pat, full.names = TRUE) writeLines(fns, args$txt)
70cd3888c6e7c7affc0c601ff6e693796d349758
580587aeff946a705babe263bb1d52a059a6614b
/_scripts/MFA_RTBcrops.R
a1209109acecc929f03800dfad53b35346ec2296
[]
no_license
CIAT-DAPA/gfsf_project
cdb1b8716624f4cb59f7781800e62b134d4914c0
49c525a9e30368358b18400681a0160dc97dae7f
refs/heads/master
2021-01-12T12:45:42.612328
2019-06-19T17:08:58
2019-06-19T17:08:58
69,292,875
0
1
null
null
null
null
ISO-8859-2
R
false
false
30,509
r
MFA_RTBcrops.R
#MFA RTB ### PCA for RTB crops ### Carlos Eduardo Gonzalez R. ### RTB Analysis g=gc;rm(list = ls()) # librerias------------ suppressMessages(library(reshape)) suppressMessages(library(ggplot2)) suppressMessages(library(plyr)) suppressMessages(library(grid)) suppressMessages(library(gridExtra)) suppressMessages(library(dplyr)) suppressMessages(library(tidyverse)) suppressMessages(library(modelr)) suppressMessages(library(purrr)) suppressMessages(library(broom)) suppressMessages(library(tidyr)) suppressMessages(library(corrplot)) suppressMessages(library(FactoMineR)) suppressMessages(library(factoextra)) suppressMessages(library(cluster)) suppressMessages(library(RCurl)) suppressMessages(library(ggthemes)) suppressMessages(library(tidyquant)) suppressMessages(library(devtools)) suppressMessages(library(mvoutlier)) suppressMessages(library(R.utils)) # if(!require(devtools)) install.packages("devtools") # devtools::install_github("kassambara/factoextra") # abbreviate("percentage") options(warn = -1); options(scipen = 999) options(digits=3) ############################################################# BIG Regions #################################################################### rdsFiles<-c("//dapadfs/workspace_cluster_6/Socioeconomia/GF_and_SF/USAIDForGFSF/RTB_files/") # Big Regions[ r<- c("EAP", "EUR","FSU", "LAC", "MEN", "NAM", "SAS", "SSA") s<- c("SSP2-HGEM-HiYld2","SSP2-HGEM-RegYld2","SSP2-HGEM-HiNARS2", "SSP2-HGEM-MMEFF2","SSP2-HGEM2") # Parametro 2 All Countries. r2<- c("EAP", "EUR","FSU", "LAC", "MEN", "NAM", "SAS", "SSA", "Africa","Americas","DVD", "DVG","WLD") r3<- c("Africa","Americas", "Asia","Europe", "Oceania") r4<- c("Australia and New Zealand","Caribbean","Central America", "Central Asia","Eastern Africa","Eastern Asia","Eastern Europe","Melanesia", "Middle Africa","Northern Africa","Northern America","Northern Europe","South America","South-Eastern Asia","Southern Africa","Southern Asia", "Southern Europe","Western Africa","Western Asia", "Western Europe", "Western and Central Asia") r5<- c("MENg","EAPg") rall<- c(r2,r3,r4, r5) jrtb<- c("jbana","jcass", "jpota", "jswpt","jyams","jorat") t<- c(2010, 2030,2050) # Vector con los cultivos para RTB incluyendo Bananas rtb<- c("R&T-Potato","R&T-Sweet Potato","R&T-Yams","R&T-Other Roots","R&T-Cassava","F&V-Banana") cfiles<-list.files(path = rdsFiles, pattern = "Blue.rds|dataagg.rds|datatotal.rds|precios.rds|TradeFood.rds",full.names = T) cfiles<- lapply(cfiles, readRDS) cdata<-cfiles # primer grupo de variables------------ for(i in 1:length(cdata)){ cdata[[i]]$Scenarios<- gsub("'",'',cdata[[i]]$Scenarios) cdata[[i]]$Commodity<- gsub("'", '',cdata[[i]]$Commodity) cdata[[i]]$Regions<- gsub("'", '',cdata[[i]]$Regions) cdata[[i]]$Year<- gsub("'",'',cdata[[i]]$Year) cdata[[i]]$Scenarios<- as.character( cdata[[i]]$Scenarios) cdata[[i]]$Commodity<- as.character( cdata[[i]]$Commodity) cdata[[i]]$Regions<- as.character( cdata[[i]]$Regions) cdata[[i]]<- filter(cdata[[i]], Scenarios %in% s) cdata[[i]]<- filter(cdata[[i]], !Regions %in% rall) cdata[[i]]<- filter(cdata[[i]], Commodity %in% rtb) cdata[[i]]<- cdata[[i]]%>% spread(Year, Val) cdata[[i]]$change<- ((cdata[[i]]$`2050`-cdata[[i]]$`2010`)/cdata[[i]]$`2010`)*100 cdata[[i]]<- cdata[[i]][,c("Scenarios", "Commodity", "Regions", "parameter", "change" )] cdata[[i]]<- cdata[[i]]%>% spread(Scenarios, change) colnames(cdata[[i]])<- c("Commodity", "Regions","parameter", "HIGH+NARS","HIGH","RMM", "REGION", "REF" ) print(i) } crbind<- do.call(rbind, cdata) # Por sistema -------- jfiles<-list.files(path = rdsFiles, pattern = "datasys.rds|green.rds",full.names = T) #|shock.rds|ipr.rds jfiles<- lapply(jfiles, readRDS) jdata<-jfiles countries <- read.csv(file = paste(rdsFiles,"IPRsLabelsRegions.csv", sep=""), header = T) colnames(countries)<- c("Regions", "IMPACT.Name") #i=3 for(i in 1:length(jdata)){ jdata[[i]]$Scenarios<- gsub("'",'',jdata[[i]]$Scenarios) jdata[[i]]$Commodity<- gsub("'", '',jdata[[i]]$Commodity) jdata[[i]]$Regions<- gsub("'", '',jdata[[i]]$Regions) jdata[[i]]$Year<- gsub("'",'',jdata[[i]]$Year) jdata[[i]]$Sys<- gsub("'",'',jdata[[i]]$Sys) jdata[[i]]$parameter<- gsub("'",'',jdata[[i]]$parameter) jdata[[i]]<- filter(jdata[[i]], Scenarios %in% s) jdata[[i]]<- filter(jdata[[i]], !Regions %in% rall) jdata[[i]]<- filter(jdata[[i]], Commodity %in% rtb) jdata[[i]]<- jdata[[i]][,c("Scenarios", "Commodity","Regions","parameter", "Sys", "Year","Val") ] jdata[[i]]<- jdata[[i]]%>% spread(Year, Val) jdata[[i]]$change<- ((jdata[[i]]$`2050`-jdata[[i]]$`2010`)/jdata[[i]]$`2010`)*100 jdata[[i]]<- jdata[[i]][,c("Scenarios", "Commodity", "Regions", "parameter","Sys", "change" )] jdata[[i]]<- jdata[[i]]%>% spread(Scenarios, change) colnames(jdata[[i]])<- c("Commodity", "Regions","parameter","Sys", "HIGH+NARS","HIGH","RMM", "REGION", "REF" ) print(i) } jrbind<- do.call(rbind, jdata) # Economic Variables1-------------- efiles<-list.files(path = rdsFiles, pattern = "EcoFood.rds",full.names = T) efiles<- lapply(efiles, readRDS) erbind<- do.call(rbind, efiles) #ajuste y corregir asuntos de texto erbind$Scenarios<- gsub("'",'',erbind$Scenarios) erbind$Regions<- gsub("'", '',erbind$Regions) erbind$Year<- gsub("'",'',erbind$Year) erbind$Scenarios<- as.character( erbind$Scenarios) erbind$Regions<- as.character(erbind$Regions) erbind<- filter(erbind, Scenarios %in% s) %>% filter(., !Regions %in% rall) %>% spread(Year, Val) erbind$change<- ((erbind$`2050`-erbind$`2010`)/erbind$`2010`)*100 erbind<- erbind[,c("Scenarios","Regions","parameter","change")] erbind<- erbind %>% spread(Scenarios, change) colnames(erbind)<- c("Regions","parameter","HIGH+NARS","HIGH","RMM", "REGION", "REF") # Economic Variables2-------------- efiles2<-list.files(path = rdsFiles, pattern = "EcoFood2.rds",full.names = T) efiles2<- lapply(efiles2, readRDS) erbind2<- do.call(rbind, efiles2) #ajuste y corregir asuntos de texto erbind2$Scenarios<- gsub("'",'',erbind2$Scenarios) erbind2$Regions<- gsub("'", '',erbind2$Regions) erbind2$Year<- gsub("'",'',erbind2$Year) erbind2$Scenarios<- as.character( erbind2$Scenarios) erbind2$Regions<- as.character(erbind2$Regions) erbind2<- erbind2 %>% filter(Scenarios %in% s) %>% filter(., !Regions %in% rall) %>% spread(Year, Val) erbind2$change<- ((log10(erbind2$`2050`)- log10(erbind2$`2010`))/(2050-2010)) erbind2<- erbind2[,c("Scenarios","Regions","parameter","change")] erbind2<- erbind2 %>% spread(Scenarios, change) colnames(erbind2)<- c("Regions","parameter","HIGH+NARS","HIGH","RMM", "REGION", "REF") #Economic variables3------------- efiles3<-list.files(path = rdsFiles, pattern = "EcoFood3.rds",full.names = T) efiles3<- lapply(efiles3, readRDS) erbind3<- do.call(rbind, efiles3) #ajuste y corregir asuntos de texto erbind3$Scenarios<- gsub("'",'',erbind3$Scenarios) erbind3$Regions<- gsub("'", '',erbind3$Regions) erbind3$Year<- gsub("'",'',erbind3$Year) erbind3$Scenarios<- as.character( erbind3$Scenarios) erbind3$Regions<- as.character(erbind3$Regions) erbind3<- erbind3 %>% filter(Scenarios %in% s) %>% filter(., !Regions %in% rall) %>% spread(Year, Val) erbind3$change<- (erbind3$`2050`- erbind3$`2010`) erbind3<- erbind3[,c("Scenarios","Regions","parameter","change")] erbind3<- erbind3 %>% spread(Scenarios, change) colnames(erbind3)<- c("Regions","parameter","HIGH+NARS","HIGH","RMM", "REGION", "REF") ############################### Tratamiento y construccion de grupos de variables ###################### #detection and deleted of NA crbind[is.na(crbind)]<- 0 erbind[is.na(erbind)]<- 0 jrbind[is.na(jrbind)]<- 0 erbind2[is.na(erbind2)]<- 0 erbind3[is.na(erbind3)]<- 0 crbind<- crbind %>% gather(Sce, change, 4:8) erbind<- erbind %>% gather(Sce, change, 3:7) erbind2<- erbind2 %>% gather(Sce, change, 3:7) erbind3<- erbind3 %>% gather(Sce, change, 3:7) jrbind<- jrbind %>% gather(Sce, change, 5:9) ###################################### Tratamiento de datos economicos ################################# #economic1 ad_erbind<- erbind %>% split(erbind$Sce) efiles<- list() for(i in 1:length(ad_erbind)){ efiles[[i]] <- ad_erbind[[i]] %>% spread(parameter, change) %>% gather(Variable, Summary, -(Regions:Sce)) %>% unite(Temp, Sce, Variable)%>% spread(Temp, Summary) } #economic2 ad_erbind2<- erbind2 %>% split(erbind2$Sce) efiles2<- list() for(i in 1:length(ad_erbind2)){ efiles2[[i]] <- ad_erbind2[[i]] %>% spread(parameter, change) %>% gather(Variable, Summary, -(Regions:Sce)) %>% unite(Temp, Sce, Variable)%>% spread(Temp, Summary) } #economic3 ad_erbind3<- erbind3 %>% split(erbind3$Sce) efiles3<- list() for(i in 1:length(ad_erbind3)){ efiles3[[i]] <- ad_erbind3[[i]] %>% spread(parameter, change) %>% gather(Variable, Summary, -(Regions:Sce)) %>% unite(Temp, Sce, Variable)%>% spread(Temp, Summary) } ######################################## Irrigacion ################################################### ad_jrbind<- jrbind %>% split(jrbind$Sce) jfiles<- list() #i=1 for(i in 1:length(ad_jrbind)){ jfiles[[i]] <- ad_jrbind[[i]] %>% spread(parameter, change) %>% gather(Variable, Summary, -(Commodity:Sce)) %>% unite(Temp, Sys, Variable)%>% spread(Temp, Summary) %>% gather(Variable, Summary, -(Commodity:Sce))%>% unite(Temp, Sce, Variable)%>% spread(Temp, Summary) } ######################################### Analisis PCA ################################################# ad_crbind<- crbind %>% split(crbind$Sce) cfiles<- list() usaid<- c("HIGH","HIGH+NARS","REF","REGION","RMM") c=1 s=1 for(s in 1:length(ad_crbind)){ cfiles[[s]]<- ad_crbind[[s]] %>% spread(parameter, change) ##### By Sce cfiles[[s]] <- cfiles[[s]] %>% gather(Variable, Summary, -(Commodity:Sce)) %>% unite(Temp, Sce, Variable)%>% spread(Temp, Summary) dfjoin<- left_join(cfiles[[s]],efiles[[s]], by=("Regions")) dfjoin<- left_join(dfjoin,efiles2[[s]], by=("Regions")) dfjoin<- left_join(dfjoin,efiles3[[s]], by=("Regions")) dfjoin<- left_join(dfjoin, jfiles[[s]], by=c("Commodity","Regions")) ##### By crops ad_crops<- dfjoin %>% split(dfjoin$Commodity) lapply(1:length(ad_crops), function(c){ crop<- unique(as.character(ad_crops[[c]]$Commodity)) sce<- usaid[s] zones<- unique(ad_crops[[c]]$Regions) # Creating directories wk_dir <- "//dapadfs/workspace_cluster_6/Socioeconomia/GF_and_SF/USAIDForGFSF/RTB_files/RTBAnalysis" if(!dir.exists(paths = paste(wk_dir, "/",crop, sep = ""))){ dir.create(path = paste(wk_dir, "/", crop, sep = "")) } # Creando data frame dff<- ad_crops[[c]] dff<- dff[grep(pattern ="MEN|SSA|SAS|LAC|EAP" ,x = dff$Regions, ignore.case = T),] #eliminando variables con baja correlación dff<- dff[,-c(5,6,7,8,10,11,12,17,19,21)] dbox<- dff dbox$Sce<- usaid[s] write.csv(x = dbox, file = paste(wk_dir, "/", crop,"_", usaid[s],"_boxplot.csv", sep = "")) # # boxplot boxplot(dff[,3:ncol(dff)], horizontal = T) # Deleting columns with SD = 0 rownames(dff) <- dff$Regions dff$Regions <- dff$Commodity <- NULL ##Calcular porcentaje de datos faltantes por variable miss <- apply(X=dff, MARGIN = 2, FUN = function(x){ y <- sum(is.na(x))/nrow(dff); return(y*100) }) dff <- dff[,names(which(miss <= 30))] dff[is.na(dff)]<- 0 dff <- Filter(function(x) sd(x) != 0, dff) #detection outluiers, multivariado mahal<- mahalanobis(dff,colMeans(dff, na.rm = TRUE),cov(dff), use="pairwise.complete.obs") cuotoff<- qchisq(0.999, ncol(dff)) summary(mahal < cuotoff) # identificar outliners outMvar<- dff[mahal>cuotoff,] if(nrow(outMvar)>1){ outMvar<- as.data.frame(outMvar) outMvar$sce<- sce outMvar$crop<- crop outMvar$Regions<- row.names(outMvar) row.names(outMvar)<- NULL outMvar<- outMvar %>% gather(Var, Val, 1:(ncol(outMvar)-3)) outMvar$Var<- gsub("HIGH_", '',outMvar$Var) outMvar$Var<- gsub("REF_", '',outMvar$Var) outMvar$Var<- gsub("REGION_", '',outMvar$Var) outMvar$Var<- gsub("RMM_", '',outMvar$Var) outMvar$Var<- gsub("RMM_", '',outMvar$Var) outMvar$Var<- gsub("[[:punct:]]", '',outMvar$Var) outMvar$Var<- gsub("HIGHNARS",'', outMvar$Var) outMvar$Regions<- gsub("LAC-", '',outMvar$Regions) outMvar$Regions<- gsub("FSU-", '',outMvar$Regions) outMvar$Regions<- gsub("SSA-", '',outMvar$Regions) outMvar$Regions<- gsub("MEN-", '',outMvar$Regions) outMvar$Regions<- gsub("SAS-", '',outMvar$Regions) outMvar$Regions<- gsub("EAP-", '',outMvar$Regions) write.csv(x = outMvar, file = paste(wk_dir, "/", crop,"_",sce,"_OutlierMV.csv", sep = "") ) }else{cat("no pasa nada de nada")} dff<- dff[mahal< cuotoff,] write.csv(x = dff, file = paste(wk_dir, "/", crop,"/",sce,"dataGenesis.csv", sep = "") ) # Correlation matrix if(!file.exists(paste(wk_dir, "/", crop,"/",sce,"_corrMatrix.png", sep = ""))){ M<- cor(dff) png(file = paste(wk_dir, "/", crop,"/",sce,"_corrMatrix.png", sep = ""), height = 8, width = 8, units = "in", res = 300) corrplot.mixed(M) dev.off() } # Principal Component Analysis res.pca <- FactoMineR::PCA(dff, graph = F,scale.unit = T) #quanti.sup =8, ind.sup =12 if(!file.exists(paste(wk_dir, "/", crop,"/",sce,"_eigenValuesPCA.png", sep = ""))){ gg <- fviz_eig(res.pca, addlabels = TRUE, hjust = -0.3) + theme_bw() # Visualize eigenvalues/variances ggsave(filename = paste(wk_dir, "/", crop,"/",sce,"_eigenValuesPCA.png", sep = ""), plot = gg, width = 8, height = 8, units = "in") } if(!file.exists(paste(wk_dir, "/", crop,"/",sce,"_varQuality.png", sep = ""))){ png(paste(wk_dir, "/", crop, "/",sce,"_varQuality.png", sep = ""), height = 8, width = 16, units = "in", res = 300) par(mfrow = c(1, 3)) corrplot(res.pca$var$cos2[,1:2], is.corr = FALSE, title = "Representation quality", mar = c(1, 0, 1, 0)) # Representation quality of each variable corrplot(res.pca$var$contrib[,1:2], is.corr = FALSE, title = "Contribution", mar = c(1, 0, 1, 0)) # Contribution of each variable to dimension corrplot(res.pca$var$cor[,1:2], method = "ellipse", is.corr = TRUE, title = "Correlation", mar = c(1, 0, 1, 0)) # Correlation of each variable to dimension dev.off() } # Hierarchical Clustering on Principle Components res.hcpc <- FactoMineR::HCPC(res.pca, nb.clust = -1, graph = F) if(!file.exists(paste(wk_dir, "/", crop, "/",sce,"_biplotPCA.png", sep = ""))){ gg <- fviz_pca_biplot(res.pca, label = "var", habillage = res.hcpc$data.clust$clust, addEllipses = TRUE, ellipse.level = 0.95) + theme_bw() # Biplot of individuals and variables. Only variables are labelled (var, ind) ggsave(filename = paste(wk_dir, "/", crop, "/",sce,"_biplotPCA.png", sep = ""), plot = gg, width = 8, height = 8, units = "in") } # Getting coordinates by cluster coordClust<- res.hcpc$call$X coordClust$Regions<- rownames(coordClust) rownames(coordClust)<- NULL coordClust$sce<- sce coordClust$crop<- crop coordClust<- coordClust[,c("Regions","sce","crop","Dim.1","Dim.2","clust")] interClus<- coordClust %>% split(coordClust$clust) lapply(1: length(interClus), function(i){ d<- interClus[[i]] write.csv(x = d,paste(wk_dir, "/",crop,"_",sce,"Inter_clusT",i,".csv" ,sep = "")) }) # Getting countries farthest disFar<- res.hcpc$desc.ind$dist disClos<- (res.hcpc$desc.ind$para) #cluster grafico1 png(paste(wk_dir, "/", crop, "/",sce,"_1ClusterPLOTPCA.png", sep = "")) plot(res.hcpc, choice = "3D.map", angle=60) dev.off() #Cluster grafico2 gg1 <- fviz_cluster(res.hcpc,ellipse.alpha = 0.1,main = paste("Scenario: ",sce, " ","crop: ",crop, sep = "" )) #labelsize = T, ggtheme = theme_minimal() ggsave(filename = paste(wk_dir, "/", crop, "/",sce,"_2ClusterPLOTPCA.png", sep = ""), plot = gg1, width = 8, height = 8, units = "in") #dendrogram gg1<- fviz_dend(res.hcpc,main = paste("Scenario: ",sce, " ","crop: ",crop, sep = "" ),horiz = T ,cex = 0.5, color_labels_by_k = FALSE, rect = TRUE) ggsave(filename = paste(wk_dir, "/", crop, "/",sce,"_DendogramPCA.png", sep = ""), plot = gg1, width = 10, height = 8, units = "in") # Individuals factor map if(!file.exists(paste(wk_dir, "/", crop, "/",sce,"_IndividualsFactorPCA.png", sep = ""))){ gg <- fviz_pca_ind(res.pca, habillage = res.hcpc$data.clust$clust, addEllipses = TRUE, ellipse.level = 0.95) + theme_bw() # Biplot of individuals and variables. Only variables are labelled (var, ind) ggsave(filename = paste(wk_dir, "/", crop, "/",sce,"_IndividualsFactorPCA.png", sep = ""), plot = gg, width = 8, height = 8, units = "in") } #deteccion de datos por cluster desClus<- res.hcpc$desc.var$quanti for(i in 1:length(desClus)){ if(!is.null(desClus[[i]])){ cfilesClust<- as.data.frame(desClus[[i]]) cfilesClust$Var<- rownames(cfilesClust) rownames(cfilesClust) <- NULL cfilesClust$cv <- cfilesClust$`sd in category`/cfilesClust$`Mean in category` cfilesClust$crop<- crop cfilesClust$clust<- i cfilesClust$Sce<- sce write.csv(x =cfilesClust, file = paste(wk_dir, "/", crop,"/",sce, "cluster_",i,"_desCluster.csv", sep = "")) }else{} } # Contribution individual indcontri<- data.frame(res.pca$ind$contrib) indcontri$Sce<- sce indcontri$crop<- crop indcontri$Regions<- rownames(indcontri) rownames(indcontri) <- NULL indcontri<- indcontri[,c("Sce","crop","Regions","Dim.1","Dim.2","Dim.3","Dim.4","Dim.5")] write.csv(x =indcontri, file = paste(wk_dir, "/", crop,"/",sce,"_IndContribution.csv", sep = "")) # Contribution variable indcontriVar<- data.frame(res.pca$var$contrib) indcontriVar$Sce<- sce indcontriVar$crop<- crop indcontriVar$var<- rownames(indcontriVar) rownames(indcontriVar) <- NULL indcontriVar<- indcontriVar[,c("Sce","crop","var","Dim.1","Dim.2","Dim.3","Dim.4","Dim.5")] write.csv(x =indcontriVar, file = paste(wk_dir, "/", crop,"/",sce,"_VarContribution.csv", sep = "")) # Index based on PCA script <- getURL("https://raw.githubusercontent.com/haachicanoy/r_scripts/master/calculate_index_by_pca.R", ssl.verifypeer = FALSE); eval(parse(text = script)); rm(script) #cluster df_cluster <- res.hcpc$data.clust dataCluster<- res.hcpc$data.clust dataCluster$Sce<- sce dataCluster$crop<- crop dataCluster$Regions<- rownames(dataCluster) rownames(dataCluster) <- NULL dataCluster<- dataCluster[,c("crop","Regions","Sce","clust")] write.csv(x =dataCluster, file = paste(wk_dir, "/", crop,"/",sce,"_DataCluster.csv", sep = "")) cat(paste(crop, " done\n", sep = "")) }) cat(paste("terminos el escenario ", s, " cool it's done\n", sep = "")) } ############################# Analisis de cluster ############# wk_dir <- "//dapadfs/workspace_cluster_6/Socioeconomia/GF_and_SF/USAIDForGFSF/RTB_files/RTBAnalysis" for(i in 1:length(rtb)){ c_clus<- list.files(path =paste(wk_dir,"/",rtb[i],sep = ""), pattern = "DataCluster.csv", full.names = T) c_clus<- lapply(c_clus, read.csv) rr<- do.call(rbind, c_clus) rr$X<- NULL write.csv(x = rr, file = paste(wk_dir, "/", rtb[i],"/","sumCluster.csv", sep = "")) write.csv(x = rr, file = paste(wk_dir, "/", rtb[i],"_sumCluster.csv", sep = "")) png(filename = paste(wk_dir,"/",rtb[i],"_HeatMapCluster",".png",sep=""), width = 10, height = 10, units = 'in', res = 100) gg<- ggplot(rr, aes(Sce, Regions)) + geom_tile(aes(fill = as.factor(clust)), colour = "white") + scale_fill_brewer(palette = "Set1")+ labs(x=NULL, y=NULL, title=paste( "Clustering of\n ", rtb[i], " by scenarios",sep = ""))+ coord_equal()+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ theme_grey() + labs(x = "",y = "")+ theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 12))+ theme(axis.text.y = element_text(hjust = 1, size = 12))+ theme(strip.text.x = element_text(size = 12, face = "bold.italic"))+ theme(strip.text=element_text(size=8))+ theme(strip.text.y = element_text(angle = 0,size = 12))+ guides(fill=guide_legend(title="Cluster")) plot(gg) dev.off() print(i) } ############################################ total subregions c_clus<- list.files(path =wk_dir, pattern = "_sumCluster", full.names = T) c_clus<- lapply(c_clus, read.csv) rrsubregions<- do.call(rbind, c_clus) rrsubregions$X<- NULL write.csv(x = rrsubregions, file = paste(wk_dir, "/","subregionsTotalCluster.csv", sep = "")) #correr rrsubregions$Regions<- gsub("LAC-", '',rrsubregions$Regions) rrsubregions$Regions<- gsub("FSU-", '',rrsubregions$Regions) rrsubregions$Regions<- gsub("SSA-", '',rrsubregions$Regions) rrsubregions$Regions<- gsub("MEN-", '',rrsubregions$Regions) rrsubregions$Regions<- gsub("SAS-", '',rrsubregions$Regions) rrsubregions$Regions<- gsub("EAP-", '',rrsubregions$Regions) rrsubregions$Sce <- factor(rrsubregions$Sce, levels = c("REF","HIGH","HIGH+NARS","REGION","RMM")) png(filename = paste(wk_dir,"/","HeatMapClustersuper",".png",sep=""), width = 12, height =16 , units = 'in', res = 100) gg<- ggplot(rrsubregions, aes(Sce, Regions)) + geom_tile(aes(fill = as.factor(clust)), colour = "white") + scale_fill_brewer(palette = "Set1")+ facet_grid(~crop,scales = "free")+ labs(x=NULL, y=NULL, title=paste( "RTB crops clustering of\n ", " by scenarios",sep = ""))+ coord_equal()+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ theme_grey() + labs(x = "",y = "")+ theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 10))+ theme(axis.text.y = element_text(hjust = 1, size = 9))+ theme(strip.text.x = element_text(size = 9, face = "bold.italic"))+ theme(strip.text=element_text(size=8))+ theme(strip.text.y = element_text(angle = 0,size = 9))+ guides(fill=guide_legend(title="Cluster")) plot(gg) dev.off() ########################################### groups by cluster for(i in 1:6){ c_clusG<- list.files(path =paste(wk_dir,"/",rtb[i],sep = ""), pattern = "desCluster.csv", full.names = T) c_clusG<- lapply(c_clusG, read.csv) rrG<- do.call(rbind, c_clusG) rrG$X<- NULL rrG$v.test<- NULL rrG<- rrG[,c("crop","clust", "Sce" ,"Var","Mean.in.category", "Overall.mean", "sd.in.category","Overall.sd","p.value", "cv")] rrG$crop<- as.character(rrG$crop) rrG$Var<- as.character(rrG$Var) write.csv(x = rrG, file = paste(wk_dir, "/", rtb[i],"_sum_AllClustReport.csv", sep = "")) print(i) } c_clusG<- list.files(path =wk_dir, pattern = "_sum_AllClustReport.csv", full.names = T) c_clusG<- lapply(c_clusG, read.csv) rrG<- do.call(rbind, c_clusG) rrG$X<- NULL rrG$Var<- gsub("HIGH_", '',rrG$Var) rrG$Var<- gsub("REF_", '',rrG$Var) rrG$Var<- gsub("REGION_", '',rrG$Var) rrG$Var<- gsub("RMM_", '',rrG$Var) rrG$Var<- gsub("RMM_", '',rrG$Var) rrG$Var<- gsub("[[:punct:]]", '',rrG$Var) rrG$Var<- gsub("HIGHNARS",'', rrG$Var) write.csv(x = rrG, file = paste(wk_dir, "/","TotalCluster.csv", sep = "")) ########################## additional analysis ######################## #tabla con cluster y paises que corresponde a cada cluster c_distri<- list.files(path =wk_dir, pattern = "boxplot", full.names = T) c_distri<- lapply(c_distri, read.csv) for(c in 1:length(c_distri)){ # d<- c_distri[[c]] c_distri[[c]]$X<- NULL c_distri[[c]]<- c_distri[[c]] %>% gather(Var, change, 3:(ncol(c_distri[[c]])-1)) c_distri[[c]]$Var<- gsub("HIGH_", '',c_distri[[c]]$Var) c_distri[[c]]$Var<- gsub("REF_", '',c_distri[[c]]$Var) c_distri[[c]]$Var<- gsub("REGION_", '',c_distri[[c]]$Var) c_distri[[c]]$Var<- gsub("RMM_", '',c_distri[[c]]$Var) c_distri[[c]]$Var<- gsub("[[:punct:]]", '',c_distri[[c]]$Var) c_distri[[c]]$Var<- gsub("HIGHNARS",'', c_distri[[c]]$Var) c_distri[[c]]$Regions<- gsub("LAC-", '',c_distri[[c]]$Regions) c_distri[[c]]$Regions<- gsub("FSU-", '',c_distri[[c]]$Regions) c_distri[[c]]$Regions<- gsub("SSA-", '',c_distri[[c]]$Regions) c_distri[[c]]$Regions<- gsub("MEN-", '',c_distri[[c]]$Regions) c_distri[[c]]$Regions<- gsub("SAS-", '',c_distri[[c]]$Regions) c_distri[[c]]$Regions<- gsub("EAP-", '',c_distri[[c]]$Regions) print(c) } ccc<- do.call(rbind, c_distri) colnames(ccc)[1]<- "crop" testC<- left_join(ccc, rrsubregions, by=c("crop", "Regions", "Sce")) testXX<- left_join(rrG, testC, by=c("crop", "Sce", "Var","clust")) testXX<- testXX[,c("crop","clust", "Sce","Var", "Regions","change" )] cultivation<- unique(testXX$crop) grupos<- unique(testXX$clust) testXX$Sce <- factor(testXX$Sce, levels = c("REF","HIGH","HIGH+NARS","REGION","RMM")) for(c in 1:length(cultivation)){ cfiles<- testXX %>% filter(crop==cultivation[c]) png(filename = paste(wk_dir,"/",cultivation[c],"_BloxPlot",".png",sep=""), width = 12, height =16 , units = 'in', res = 100) gg<- ggplot(cfiles, aes(y=change, x=droplevels(Sce),fill=Var)) + geom_boxplot() + facet_grid(clust~Var, scales = "free")+ labs(x=NULL, y=NULL, title=paste(cultivation[c]," cluster boxplot\n ", " by scenarios",sep = ""))+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ theme_grey() + labs(x = "",y = "")+ theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 10))+ theme(axis.text.y = element_text(hjust = 1, size = 9))+ theme(strip.text.x = element_text(size = 9, face = "bold.italic"))+ theme(strip.text=element_text(size=8))+ theme(strip.text.y = element_text(angle = 0,size = 9)) plot(gg) dev.off() print(i) } ### Paises con valores extremos coutfiles<- list.files(path = wk_dir,pattern = "OutlierMV", full.names = T) coutfiles<- lapply(coutfiles, read.csv, header=T) coutfiles<- do.call(rbind, coutfiles) coutfiles$X<- NULL coutfiles<- coutfiles[,c("Regions","crop","sce", "Var", "Val")] coutfiles<- coutfiles %>% spread (sce, Val) write.csv(x = coutfiles,file = paste(wk_dir,"/","CountriesAtypical.csv", sep = "")) ### intersection across scenarios it<- list.files(path = wk_dir,pattern = "Inter_clusT", full.names = T) it<- lapply(it, read.csv) it<- do.call(rbind, it) it$X<- NULL crosInter<- it%>% split(it$crop) # c=1 intentM<- lapply(1:length(crosInter), function(c){ df<- crosInter[[c]] crop<- droplevels(unique(df$crop)) df<- df[,c("Regions","sce","crop", "clust")] cfcrops<- df %>% split(df$sce) a<- left_join(cfcrops[[1]],cfcrops[[2]],by = c("Regions", "crop")) b<- left_join(a,cfcrops[[3]],by = c("Regions", "crop")) c<- left_join(b,cfcrops[[4]],by = c("Regions", "crop")) d<- left_join(c,cfcrops[[5]],by = c("Regions", "crop")) d$inter <- apply(d[,c(4,6,8,10,12)], 1, function(x)( all(x==1) || all(x==2) || all(x==3) || all(x==4) )) d$inter<- ifelse(d$inter=="TRUE",1,0) # d<- d[,c("Regions","crop", "inter")] rateStab<- d %>% group_by(inter) %>% summarise(n = n()) write.csv(rateStab, paste(wk_dir,"/" ,crop,"_consisting.csv", sep = "")) cat(paste("Cultivation: ", crop, " is complete\n", sep = "")) })
ec3e2b142f67fb4392952f29efd6630c9fa70d7d
7a602fb8fd4df2cac0002d0522f3ffa8c23a3e05
/data_prep/scheduler.R
9ca925ccc43b3f3e0cdead7bb351c06731ec4f1e
[]
no_license
mkaranja/btract1
7f7add53cb6b7341b869c18a252d9de091706139
a582692bc5fb6e5b667c48ce014c49bf820042f1
refs/heads/main
2023-04-30T16:54:02.498744
2021-05-14T23:10:01
2021-05-14T23:10:01
367,032,252
0
0
null
null
null
null
UTF-8
R
false
false
6,038
r
scheduler.R
#source("data_prep/cleantable.R", local = T) dt <- cleantable()%>% arrange(Date = as.Date(Date, "%d-%m-%Y")) df <- dt[!duplicated(dt[,1:4]),] df <- df[!duplicated(df$Accession),] %>% setDT() df <- df[Activity != "Flowering"][,-c(5:6)] # days elapsed df$`Days Elapsed` <- Sys.Date()-df$Date # mean number of days between activities dff <- banana %>% dplyr::left_join( repeatpollination() ) colnames(dff) <- gsub("_"," ", names(dff)) dff$`Days to Maturity` <- lubridate::date(dff$`Bunch Harvest Date`) - lubridate::date(dff$`First Pollination Date`) dff$`Days in ripening shed` <- lubridate::date(dff$`Seed Extraction Date`) - lubridate::date(dff$`Bunch Harvest Date`) dff$`Days to Germination` <- lubridate::date(dff$`Germination Date`) - lubridate::date(dff$`Embryo Rescue Date`) dff$`Days to Embryo Rescue` <- lubridate::date(dff$`Embryo Rescue Date`) - lubridate::date(dff$`Seed Extraction Date`) dff$`Days to Repeat Pollination` <- as.Date(dff$`Repeat Pollination Date`, "1970-01-01") - as.Date(dff$`First Pollination Date`, "1970-01-01") mean_days_to_repeatpollination <- mean(as.integer(na.omit(dff$`Days to Repeat Pollination`))) %>% floor() # to repeat mean_days_to_maturity <- mean(as.integer(na.omit(dff$`Days to Maturity`))) %>% floor() # to harvest mean_days_in_ripening <- mean(as.integer(na.omit(dff$`Days in ripening shed`))) %>% floor() # to extraction mean_days_to_embryo_rescue <- mean(as.integer(na.omit(dff$`Days to Embryo Rescue`))) %>% floor() # to rescue mean_days_to_germination <- mean(as.integer(na.omit(dff$`Days to Germination`))) %>% floor() # to germination df$status <- ifelse(df$Activity=='First pollination' & df$`Days Elapsed` > (mean_days_to_repeatpollination+5), "Overdue", ifelse(df$Activity=='First pollination' & df$`Days Elapsed` >= mean_days_to_repeatpollination-5 & df$`Days Elapsed` <= mean_days_to_repeatpollination+5, "Ready", ifelse(df$Activity=='First pollination' & df$`Days Elapsed` >= mean_days_to_repeatpollination-10 & df$`Days Elapsed` <= mean_days_to_repeatpollination-5, "Approaching", ifelse(df$Activity=='First pollination' & df$`Days Elapsed` < mean_days_to_repeatpollination-10, "Wait", ifelse(df$Activity=='Repeat pollination' & df$`Days Elapsed` > (mean_days_to_maturity+10),"Overdue", ifelse(df$Activity=='Repeat pollination' & df$`Days Elapsed` <= mean_days_to_maturity-10 & df$`Days Elapsed` >= mean_days_to_maturity+10, "Ready", ifelse(df$Activity=='Repeat pollination' & df$`Days Elapsed` >= mean_days_to_maturity-30 & df$`Days Elapsed` <= mean_days_to_maturity-10, "Approaching", ifelse(df$Activity=='Repeat pollination' & df$`Days Elapsed` < mean_days_to_maturity-30, "Wait", # harvested ifelse(df$Activity=='Harvested bunches' & df$`Days Elapsed` > mean_days_in_ripening+3,"Overdue", ifelse(df$Activity=='Harvested bunches' & df$`Days Elapsed` >= mean_days_in_ripening-3 & df$`Days Elapsed` <= mean_days_in_ripening+3, "Ready", ifelse(df$Activity=='Harvested bunches' & df$`Days Elapsed` >= mean_days_in_ripening-5 & df$`Days Elapsed` <= mean_days_in_ripening-3, "Approaching", ifelse(df$Activity=='Harvested bunches' & df$`Days Elapsed` < mean_days_in_ripening-5, "Wait", # Seed extraction ifelse(df$Activity=='Seed extraction' & df$`Total Seeds` > 0 & df$`Days Elapsed` > (mean_days_to_embryo_rescue+3), "Overdue", ifelse(df$Activity=='Seed extraction' & df$`Total Seeds` > 0 & df$`Days Elapsed` >= mean_days_to_embryo_rescue-2 & df$`Days Elapsed` <= mean_days_to_embryo_rescue+3, "Ready", ifelse(df$Activity=='Seed extraction' & df$`Total Seeds` > 0 & df$`Days Elapsed` >= 3 & df$`Days Elapsed` <= mean_days_to_embryo_rescue-3, "Approaching", ifelse(df$Activity=='Seed extraction' & df$`Total Seeds` > 0 & df$`Days Elapsed` < 3, "Wait", # EMbryo rescue ifelse(df$Activity=='Embryo Rescue' & df$`Number of Embryo Rescued` >0 & df$`Days Elapsed` > 56, "Overdue", ifelse(df$Activity=='Embryo Rescue' & df$`Number of Embryo Rescued` >0 & df$`Days Elapsed` >= 50 & df$`Days Elapsed` <= 56, "Ready", ifelse(df$Activity=='Embryo Rescue' & df$`Number of Embryo Rescued` >0 & df$`Days Elapsed` >= 45 & df$`Days Elapsed` <= 49, "Approaching", ifelse(df$Activity=='Embryo Rescue' & df$`Number of Embryo Rescued` >0 & df$`Days Elapsed` < 45, "Wait",NA )))))))))))))))))))) schedulerdata = df[!is.na(df$status),] schedulerdata = schedulerdata[status !='Wait'] schedulerdata$NextActivity = ifelse(schedulerdata$Activity=="First pollination","Repeat pollination", ifelse(schedulerdata$Activity=="Repeat pollination","Bunch Harvesting", ifelse(schedulerdata$Activity=="Harvested bunches","Seed Extraction", ifelse(schedulerdata$Activity=="Seed extraction","Embryo Rescue", ifelse(schedulerdata$Activity=="Embryo Rescue","Germination",''))))) #schedulerdata <- schedulerdata[,c("Location", "Accession","CurrentActivity","Days Elapsed", "status", "NextActivity")]
4a25abc42d38269d03cbe8d437a73c6579af2205
e278fbe0caf74403a865b6e2daffa680517d9886
/tests/testthat/test-search_sorting.R
0aca0db6b686bfab7005ec0e04a4fac062b2d298
[]
no_license
amandaJayanetti/RXapian
cb129fd9527e582a7e897da878e8523260fa40c2
6595c3ab26f4efb55050b6e44b645eb715a10218
refs/heads/master
2021-01-20T17:58:22.156647
2018-03-21T07:01:35
2018-03-21T07:01:35
59,979,615
8
1
null
2016-08-18T17:23:29
2016-05-30T04:08:03
C++
UTF-8
R
false
false
1,819
r
test-search_sorting.R
context("Sorting Search Results") test_that("Search results are sorted as expected", { # preparing arguments for xapian_index() id<-c(1, 2, 3) name<-c("State of Montana", "State of Iowa", "State of Texas") motto<-c("Oro y Plata (Spanish: Gold and Silver)", "Our liberties we prize and our rights we will maintain.", "Equality Before the Law") description<-c("This geographical fact is reflected in the state's name, derived from the Spanish word montaña (mountain).", "It is located in the Midwestern United States and Great Lakes Region.", "The name was applied by the Spanish to the Caddo themselves") admitted<-c(1889, 1959, 1845) data<-data.frame(id, name, motto, description, admitted) db<- tempfile(pattern="RXapian-") id<-c(0) vs1<-list(slot=c(1),serialise=TRUE,name="admitted") valueS<-list(vs1) indexFields<-list(list(name="name",prefix="S"), list(name="description",prefix="XD"), list(name="motto",prefix="XM")) xapian_index(dbpath = db, dataFrame = data, idColumn = id, indexFields = indexFields, valueSlots = valueS, stemmer = "en") # preparing arguments for xapian_search() enq<-list(sortby="value_then_relevance",valueNo=1,reverse_sort_order=FALSE) preF<-list(list(name="name", prefix="S"), list(name="description", prefix="XD")) query<-list(queryString="spanish", stemmer="en", prefix.fields=preF) result<-xapian_search(db, enq, query) # comparing results expect_equal(name[3],as.character(result$b[1])) expect_equal(name[1],as.character(result$b[2])) })
83c399e6c21314b836bed1cfeb6ab312707b1ccc
838a6ac041e68dbe497016af0762e7c19994dce8
/CompData/best.R
40560d35b71c3b0d4fb28a7c8fe989112e066eeb
[]
no_license
htx1219/R
e844243cf9a794ec04440b3b260c9fb07196a4f6
475a68d66387532058d885bcc0606fc1db9e8be1
refs/heads/master
2021-01-19T14:11:10.195519
2013-02-05T01:12:41
2013-02-05T01:12:41
null
0
0
null
null
null
null
UTF-8
R
false
false
815
r
best.R
best<-function(state, outcome){ k<-read.csv("outcome-of-care-measures.csv", colClasses="character") k[,11]<-as.numeric(k[,11]) k[,17]<-as.numeric(k[,17]) k[,23]<-as.numeric(k[,23]) if(!state %in% dimnames(table(k$State))[[1]]){ stop("invalid state") } if(!outcome %in% c("heart failure", "heart attack", "pneumonia")){ stop("invalid outcome") } if(outcome == "heart attack"){ k2<-k[k$State == state,] w<-k2$Hospital.Name[which(k2[,11] == min(k2[,11], na.rm=T))] w<-sort(w) return(w[1]) } if(outcome == "heart failure"){ k2<-k[k$State == state,] w<-k2$Hospital.Name[which(k2[,17] == min(k2[,17], na.rm=T))] w<-sort(w) return(w[1]) } if(outcome == "pneumonia"){ k2<-k[k$State == state,] w<-k2$Hospital.Name[which(k2[,23] == min(k2[,23], na.rm=T))] w<-sort(w) return(w[1]) } }
1b75520cc0d9591c71ba2b6125494bbbcf44b0b9
c7906993c18bef9eeefccf183a3b6563af9f5500
/Lab12/WINFREY_Lab12.R
86f9620e3de17e85450fe3c31de59a4daba52f33
[]
no_license
clairecwinfrey/CompBioLabsAndHomework
2fbfa091f050f98bfd2df1bb3ccf3b1ab7de7d87
67f76cea4406702e58984c1e2ab3ce96e2239772
refs/heads/master
2023-04-12T10:53:41.256988
2021-05-01T10:34:44
2021-05-01T10:34:44
334,553,486
0
0
null
null
null
null
UTF-8
R
false
false
4,809
r
WINFREY_Lab12.R
# Script for Lab #12 # Claire Winfrey # April 2, 2021 # (also worked on in class April 5th and 7th) # Working with some data from the Colorado Department of Public Health # and Environment (CDPHE) on COVID-19 in Colorado. # Changed so that it works on my computer #setwd("~/Desktop/Spring_2021/Comp_Bio/CompBio_sandbox/CompBio_on_git/Datasets/COVID-19/CDPHE_Data/CDPHE_Data_Portal/") stateStatsData <- read.csv("DailyStateStats2/CDPHE_COVID19_Daily_State_Statistics_2_2021-04-02.csv", stringsAsFactors = F) library("tidyverse") library("dplyr") #################################################### ## Explore the data #################################################### names(stateStatsData) str(stateStatsData) summary(stateStatsData) unique(stateStatsData$Name) unique(stateStatsData$Desc_) table(stateStatsData$Name) View(stateStatsData) ############################################# # Part 1: (Finish) Getting the data into shape ############################################# # (going off of what we did together in class): # 1. subset the data so that we only keep the rows where the text in the column (variable) named "Name" is "Colorado" ColoradoData <- filter(stateStatsData, Name == "Colorado") # 2. subset to keep (select) only the columns "Date", "Cases", and "Deaths" substateStats <-ColoradoData %>% select("Date", "Cases", "Deaths") # 3. change the data in the "Date" column to be actual dates rather than a character substateStats$Date <- strptime(substateStats$Date, format = "%m/%d/%Y", tz = "") ## my group in class ## # 4. sort the data so that the rows are in order by date from earliest to latest require("lubridate") substateStats <- substateStats %>% arrange(Date) # 5. subset the data so that we only have dates prior to May 15th, 2020 substateStats$Date <- as.POSIXlt(substateStats$Date, format = "%m/%d/%Y", tz = "") dt <- as.Date("2020-05-15") dt <- as.POSIXlt("2020-05-15") #get dates in right format for ggplot later? index <- which(as.Date(substateStats$Date) < dt) COearlyCovid <- substateStats[index , ] View(COearlyCovid) #looks as expected! # or using lubridate # require("lubridate") # datesTimes <- parse_date_time(x = substateStatsArr$Date, orders = c("mdy")) # Now do it all in a pipeline with pipes (Sam's example from class) ColoradoData <- stateStatsData %>% filter(Name == "Colorado") %>% #this removed 5 rowd select(Date, Cases, Deaths) %>% mutate(Date = strptime(Date, format = "%m/%d/%Y", tz = "")) %>% #Could not specify stateStatsData$Date becasue then it would go back to the beginning! arrange(Date) %>% filter( Date < as.Date("2020-05-15")) View(ColoradoData) #################################################### # Part 2: Make plots in R using the data from Part 1 #################################################### # Plot 1: Cases on y axis, Date on x ggplot(data = ColoradoData, mapping = aes(x=Date, y=Cases)) + geom_point() + geom_line() # Get error "Error: Invalid input: time_trans works with objects of class POSIXct only" # I'll try a few ways to get around this: myPlot <- ggplot(data = ColoradoData, mapping = aes(x=as.Date(Date), y=Cases)) + geom_line() + xlab("Date") # This above looks like the example in the Lab12 document on GitHub, # (except that my data shows twice as many cases by May 15th!) ######### # Plot #2: Date on x-axis, Deaths on y-axis: myPlot2 <- ggplot(data = ColoradoData, mapping = aes(x=as.Date(Date), y=Deaths)) + geom_line() + xlab("Date") # Huh, again the shape of my line in the date is quite different than the example # that we were asked to replicate, but it looks correct based on viewing the ColoradoData # data frame. #################################################### # Part 3: Write a function for adding doubling times #################################################### addDoublingTimeRefLines <- function( myPlot, doublingTimeVec, timeVar, ObsData, startFrom ) { # myPlot is the starting plot, where time or dates are on the x- axis and observations of something are on the y axis. # doublingTimeVec is vector which # timeVar is the time or date data you are working with, e.g. ColoradoData$Date # ObsData is the observational data you are working with, e.g. ColoradoData$Cases from above # Instead of having "startFrom", I make the starting time as below with "timeZero" require("ggplot2") timeZero <- min(timeVar) # I think that for the code below, I wouldn't have to specify the data, because it would work # off of whatever the starting plot "myPlot" had as data... RefLine1 <- 2^ #the power that 2 is to should reflect myNewPlot <- myPlot + geom_line(mapping = aes(x = timeVar - timeZero, y = RefLine1), color = "maroon", linetype = "dashed" ) ) return( myNewPlot ) }
a68aa377f0e4f88be0f2a7b4d046d9603dee98e2
fdc7245741d314f963d42c185845168046f9cf98
/R/BinStat.R
c8d17d5504e41946641e9b5f0d4b65bb6ef998cd
[]
no_license
kkeenan02/MsatAllele
c08db0e279b05a9d5cd966741ec04b6a46bdf458
0379a16db5b4a968b27e989302edb03e86e986d9
refs/heads/master
2020-05-17T17:50:35.658051
2014-10-02T13:33:56
2014-10-02T13:33:56
24,057,348
4
1
null
null
null
null
UTF-8
R
false
false
891
r
BinStat.R
BinStat<-function(DataBase,loci){ o<-order(DataBase[DataBase[,1]==loci,3]) Frag<-DataBase[DataBase[,1]==loci,3] Frag<-Frag[o] Bin<-1:length(Frag) i<-1 repeat{ Bin[i]<-get.allele(DataBase,loci,Frag[i]) i<-i+1 if(i>length(Frag))break} Bins <-levels(as.factor(Bin)) N <-tapply(Bin,as.factor(Bin),length) Min <-tapply(Frag,as.factor(Bin),min) Max <-tapply(Frag,as.factor(Bin),max) Range <-Max-Min Sd <-round(tapply(Frag,as.factor(Bin),sd),digits=3) MEAN <-round(tapply(Frag,as.factor(Bin),mean),digits=2) MEDIAN<-round(tapply(Frag,as.factor(Bin),median),digits=2) Binstats<-data.frame( Bins =Bins , N =N , Min =Min , Max =Max , Range =Range, Sd =Sd , MEAN =MEAN , MEDIAN=MEDIAN) Binstats }
965fa1d130762d545eca288ebb8e741c58f42ad1
c855f7b5003c49ee0bdb2c5405226c3d27a81d1d
/man/get_germplasm_data.Rd
d47d7904c2adcc5d06fc85e6f036d30b893a8f5d
[]
no_license
khaled-alshamaa/QBMS
971bd3f29d62f6f516c7652d7556b8241ef0477e
021abe36f76b3aae3a9ac0e2b9e2f63b7fb270ac
refs/heads/master
2021-07-18T11:48:09.806213
2020-08-09T09:49:28
2020-08-09T09:49:28
198,709,256
1
1
null
null
null
null
UTF-8
R
false
true
1,192
rd
get_germplasm_data.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qbms.R \name{get_germplasm_data} \alias{get_germplasm_data} \title{Get the observations data of a given germplasm name} \usage{ get_germplasm_data(germplasm_name) } \arguments{ \item{germplasm_name}{the name of the germplasm} } \value{ a data frame of the germplasm observations data aggregate from all trials } \description{ This function will retrieve the observations data of the current active study as configured in the internal state object using `set_study()` function. } \examples{ # config your BMS connection set_qbms_config(server = "bms.icarda.org", port = 18443, protocol = "https://") # login using your BMS account (interactive mode) # you can pass BMS username and password as parameters (batch mode) login_bms() set_crop("Tutorial1") # select a breeding program by name set_program("Training Breeding Program") # retrive observations data of a given germplasm aggregated from all trials germplasm_observations <- get_germplasm_data("FLIP10-3C") } \seealso{ \code{\link{login_bms}}, \code{\link{set_crop}}, \code{\link{set_program}} } \author{ Khaled Al-Shamaa, \email{k.el-shamaa@cgiar.org} }
7d1984bc84acbfddb82c33a6f0a63a76b3b16a19
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/alphashape3d/examples/components_ashape3d.Rd.R
d7e1603373c98535ed0d5f3676a8676ca658c8bf
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
767
r
components_ashape3d.Rd.R
library(alphashape3d) ### Name: components_ashape3d ### Title: Connected subsets computation ### Aliases: components_ashape3d ### ** Examples T1 <- rtorus(1000, 0.5, 2) T2 <- rtorus(1000, 0.5, 2, ct = c(2, 0, 0), rotx = pi/2) x <- rbind(T1, T2) alpha <- c(0.25, 2) ashape3d.obj <- ashape3d(x, alpha = alpha) plot(ashape3d.obj, indexAlpha = "all") # Connected components of the alpha-shape for both values of alpha comp <- components_ashape3d(ashape3d.obj, indexAlpha = "all") class(comp) # Number of components and points in each component for alpha=0.25 table(comp[[1]]) # Number of components and points in each component for alpha=2 table(comp[[2]]) # Plot the connected components for alpha=0.25 plot(ashape3d.obj, byComponents = TRUE, indexAlpha = 1)
6e916788abf74d992018f2119b41d2d5c7528f11
9752a371fb29d70be9b4fc7efb7baab3d763c50f
/man/sub-sub-plan-method.Rd
cc36fd1eb537746e593838eaa648dc9a845ea3d9
[]
no_license
cran/plan
5ba2e21c768c322f689a57e1cc287a9a88df0c1e
88a1dd89fcfa562da2f98f88dd9f91e56ada0d4c
refs/heads/master
2023-08-31T07:46:12.007363
2023-08-19T11:10:02
2023-08-19T12:41:36
17,698,551
0
0
null
null
null
null
UTF-8
R
false
true
519
rd
sub-sub-plan-method.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AllClass.R \name{[[,plan-method} \alias{[[,plan-method} \title{Extract Something From a plan Object} \usage{ \S4method{[[}{plan}(x, i, j, ...) } \arguments{ \item{x}{A \linkS4class{plan} object.} \item{i}{The item to extract.} \item{j}{Optional additional information on the \code{i} item.} \item{...}{Optional additional information (ignored).} } \description{ Extract something from a plan object, avoiding using the "slot" notation. }
a8db74305c09d151262204d0bf98b03184b157d0
44e97a4f153fede9ad36444426382599a0b5ad34
/man/visualize_terms.Rd
0a2a12ce1c71b4f250831741d0fa655fec2772f9
[ "MIT" ]
permissive
egeulgen/pathfindR
3f58046ad48ecb7698c604bc9959e7a70d49b53a
857f4b70566ea3a0413c015fd9580c15137a1615
refs/heads/master
2023-08-22T15:13:58.185804
2023-08-22T12:57:44
2023-08-22T12:57:44
115,432,311
149
28
NOASSERTION
2023-08-27T15:21:31
2017-12-26T15:11:22
R
UTF-8
R
false
true
2,358
rd
visualize_terms.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/visualization.R \name{visualize_terms} \alias{visualize_terms} \title{Create Diagrams for Enriched Terms} \usage{ visualize_terms( result_df, input_processed = NULL, hsa_KEGG = TRUE, pin_name_path = "Biogrid", ... ) } \arguments{ \item{result_df}{Data frame of enrichment results. Must-have columns for KEGG human pathway diagrams (\code{hsa_kegg = TRUE}) are: "ID" and "Term_Description". Must-have columns for the rest are: "Term_Description", "Up_regulated" and "Down_regulated"} \item{input_processed}{input data processed via \code{\link{input_processing}}, not necessary when \code{hsa_KEGG = FALSE}} \item{hsa_KEGG}{boolean to indicate whether human KEGG gene sets were used for enrichment analysis or not (default = \code{TRUE})} \item{pin_name_path}{Name of the chosen PIN or absolute/path/to/PIN.sif. If PIN name, must be one of c("Biogrid", "STRING", "GeneMania", "IntAct", "KEGG", "mmu_STRING"). If path/to/PIN.sif, the file must comply with the PIN specifications. (Default = "Biogrid")} \item{...}{additional arguments for \code{\link{visualize_hsa_KEGG}} (used when \code{hsa_kegg = TRUE}) or \code{\link{visualize_term_interactions}} (used when \code{hsa_kegg = FALSE})} } \value{ Depending on the argument \code{hsa_KEGG}, creates visualization of interactions of genes involved in the list of enriched terms in \code{result_df} and saves them in the folder "term_visualizations" under the current working directory. } \description{ Create Diagrams for Enriched Terms } \details{ For \code{hsa_KEGG = TRUE}, KEGG human pathway diagrams are created, affected nodes colored by up/down regulation status. For other gene sets, interactions of affected genes are determined (via a shortest-path algorithm) and are visualized (colored by change status) using igraph. } \examples{ \dontrun{ visualize_terms(result_df, input_processed) visualize_terms(result_df, hsa_KEGG = FALSE, pin_name_path = "IntAct") } } \seealso{ See \code{\link{visualize_hsa_KEGG}} for the visualization function of human KEGG diagrams. See \code{\link{visualize_term_interactions}} for the visualization function that generates diagrams showing the interactions of input genes in the PIN. See \code{\link{run_pathfindR}} for the wrapper function of the pathfindR workflow. }
ae08a37cadacee79b1a961231751ecbc7e1bde2b
3dafbf5ca0374492ee3a0d16dec014cdb6b814fe
/group_map/comparison.do.group_map.R
057aecb5efb53e4b92879cac3d5a0f64f752f170
[]
no_license
razielar/Tidyverse-examples
1174225d4c13db4922c31c8bb56bc87e1efac3c8
e1dbf5e4a970011ab90cf8bc16a777541a836e99
refs/heads/master
2023-08-26T01:06:58.736992
2021-11-03T20:09:49
2021-11-03T20:09:49
232,620,563
1
0
null
2021-08-04T09:09:01
2020-01-08T17:32:39
R
UTF-8
R
false
false
1,174
r
comparison.do.group_map.R
### Comparison between do and group_map ### April 10th 2020 ### Libraries: library(tidyverse) library(magrittr) library(lubridate) library(scales) #dollar_format library(reshape2) options(stringsAsFactors = F) setwd('/home/razielar/Documents/SIRIS/SIRIS_internal_dashboard/') ######### 1) Input: proj_income <- readRDS("Data//proj_income.RDS") ######### 2) Using do: projects_second <- proj_income %>% mutate(amount_month= round(Income/round_project_length, digits=2)) %>% mutate(new_end_date=start_date+months(round_project_length)) %>% select(project, new_status, start_date, new_end_date, round_project_length, Income, amount_month) %>% group_by(project, new_status, start_date, new_end_date, round_project_length, Income) %>% do( data.frame( amount_month= rep(.$amount_month, .$round_project_length) ) ) %>% arrange(start_date, project) %>% ungroup %>% group_by(project) %>% mutate(start_date=start_date+months( row_number()-1 ) ) %>% mutate(new_end_date=start_date+months(1)) %>% ungroup ######### 3) Using group_map:
170ae084ce038b9ea8c8dad233fcd6b3926ccc13
29585dff702209dd446c0ab52ceea046c58e384e
/FisherEM/R/sfem.R
52587e7aaf6f95f24b892bcdab48eab7f20a9657
[]
no_license
ingted/R-Examples
825440ce468ce608c4d73e2af4c0a0213b81c0fe
d0917dbaf698cb8bc0789db0c3ab07453016eab9
refs/heads/master
2020-04-14T12:29:22.336088
2016-07-21T14:01:14
2016-07-21T14:01:14
null
0
0
null
null
null
null
UTF-8
R
false
false
1,531
r
sfem.R
sfem <- function(Y,K=2:6,model='AkjB',method='reg',crit='icl',maxit=50,eps=1e-6,init='kmeans',nstart=25,Tinit=c(),kernel='',disp=F,l1=0.1,l2=0,nbit=2){ call = match.call() if (max(l1)>1 || min(l1)<0 || max(l2)>1 || min(l2)<0) stop("Parameters l1 and l2 must be within [0,1]\n",call.=FALSE) else{ bic = aic = icl = c() RES = list() try(res0 <- fem(Y,K,init=init,nstart=nstart,maxit=maxit,eps=eps,Tinit=Tinit,model=model,kernel=kernel,method='reg',crit=crit)) for (i in 1:length(l1)){ try(RES[[i]] <- fem.sparse(Y,res0$K,model=res0$model,maxit=15,eps=eps,Tinit=res0$P,l1=l1[i],l2=l2,nbit=nbit)) try(bic[i] <- RES[[i]]$bic) try(aic[i] <- RES[[i]]$aic) try(icl[i] <- RES[[i]]$icl) #try(fish[i] <- RES[[i]]$fish) } if (crit=='bic'){ id_max = which.max(bic); crit_max = RES[[id_max]]$bic} if (crit=='aic'){ id_max = which.max(aic); crit_max = RES[[id_max]]$aic} if (crit=='icl'){ id_max = which.max(icl); crit_max = RES[[id_max]]$icl} #if (crit=='fisher'){ id_max = which.max(diff(fish)); crit_max = RES[[id_max]]$fish} res = RES[[id_max]] res$call = res0$call res$plot = res0$plot res$plot$l1 = list(aic=aic,bic=bic,icl=icl,l1=l1) res$call = call res$crit = crit res$l1 = l1[id_max] res$l2 = l2 if (disp){ if (length(l1)>1) cat('The best sparse model is with lambda =',l1[id_max],'(',crit,'=',crit_max,')\n') else cat('The sparse model has a lambda =',l1[id_max],'(',crit,'=',crit_max,')\n')} } class(res)='fem' res }
877babad9da9ab66819c3d89f2e771271fbc1b33
06afced918b4cb9fcce7b227b994d8442c83713d
/redesBayesianas/S2/0_distribuciones_de_probabilidad_con_R.R
c7ab72d258dfbbab25101d93af22686ab9a0845b
[]
no_license
BigDataFred/MasterComputationalEnginerring
20040278446b088d47e8e043266ed856d7f2a658
b383a1feaaa0e7ff39411ca1683595a5febee0c2
refs/heads/master
2020-04-20T16:52:08.864432
2020-01-28T21:45:55
2020-01-28T21:45:55
168,971,382
1
0
null
null
null
null
UTF-8
R
false
false
3,545
r
0_distribuciones_de_probabilidad_con_R.R
## ----plot_normal_density,prompt=TRUE,message=FALSE,fig.path="./figures/",fig.keep='last',fig.show='hide',tidy=FALSE---- #Generamos los puntos en los que evaluar (entre -5 y 5) x<-seq(-5,5,0.01) #Obtenemos los valores de las 3 densidades densidad1<-dnorm(x,mean=0, sd=0.5) densidad2<-dnorm(x,mean=0,sd=1) densidad3<-dnorm(x,mean=2,sd=1) #Las representamos gráficamente plot(x,densidad1,type="l",main="Ejemplo de tres densidades Gausianas", xlab="X", ylab="Densidad") lines(x,densidad2,col=2) lines(x,densidad3,col=3) ## ----plot_lognormal_cummulative,prompt=TRUE,message=FALSE,fig.path="./figures/",fig.keep='last',fig.show='hide',tidy=FALSE---- #Obtenemos los valores de las 3 densidades #Generamos los puntos en los que evaluar (entre -5 y 5) x<-seq(0,100,0.1) cdf1<-plnorm(x,meanlog=0, sdlog=1) cdf2<-plnorm(x,meanlog=0,sdlog=2) cdf3<-plnorm(x,meanlog=3,sdlog=1) #Las representamos gráficamente library(ggplot2) df<-rbind(data.frame(X=x,Y=cdf1,Distribucion="CDF #1"), data.frame(X=x,Y=cdf2,Distribucion="CDF #2"), data.frame(X=x,Y=cdf3,Distribucion="CDF #3")) ggplot(df,aes(x=X, y=Y, col=Distribucion)) + geom_line(size=1.1) + labs(x="X", y="CDF") ## ----integral,prompt=TRUE,message=FALSE,tidy=FALSE----------------------- #Para poder hacer la integral hay que definir la función a integrar f<-function (x){ dchisq(x,df=5) } #Hecho esto la integral será ... integrate(f = f,lower = 4, upper = 6) ## ----sampling,prompt=TRUE,message=FALSE,tidy=FALSE----------------------- muestra<-rbeta(250,1,10) ## ----qteorico,prompt=TRUE,message=FALSE,tidy=FALSE----------------------- #Definimos los cuantiles a usar p<-seq(0.1,0.9,0.1) #Obtenemos los valores teóricos cuantiles_teoricos<-qbeta(p,1,10) ## ----qmuestral,prompt=TRUE,message=FALSE,tidy=FALSE---------------------- #Creamos una función para obtener los cuantiles muestrales qmuestral<-function(p, muestra){ muestra_ordenada<-sort(muestra) posiciones<-p*length(muestra) muestra_ordenada[posiciones] } cuantiles_muestrales<-qmuestral(p,muestra) ## ----qqplot,prompt=TRUE,message=FALSE,fig.path="./figures/",fig.keep='last',fig.show='hide',tidy=FALSE---- plot(cuantiles_muestrales, cuantiles_teoricos, main="Gráfico cuantil-cuantil", xlab="Cuantil muestral", ylab="Cuantil del modelo", pch=19, col=3) lines(c(0,1),c(0,1)) ## ----qqplot_normal,prompt=TRUE,message=FALSE,fig.path="./figures/",fig.keep='last',fig.show='hide',tidy=FALSE---- cuantiles_normal<-qnorm(p,mean(muestra),sd(muestra)) plot(cuantiles_muestrales, cuantiles_normal, main="Gráfico cuantil-cuantil", xlab="Cuantil muestral", ylab="Cuantil del modelo", pch=19, col=3) lines(c(0,1),c(0,1)) ## ----verosimilitud,prompt=TRUE,message=FALSE,tidy=FALSE------------------ #Creamos la muestra sample<-rpois(1000,5) #Determinamos la probabilidad asociada a cada valor muestreado probabilidades<-dpois(sample,5) #La probabilidad la computamos como el producto prod(probabilidades) ## ----loglikelihood,prompt=TRUE,message=FALSE,tidy=FALSE------------------ #El logaritmo del producto de probabilidades es la suma de los logaritmos sum(log(probabilidades)) ## ----logveros_plot,prompt=TRUE,message=FALSE,fig.path="./figures/",fig.keep='last',fig.show='hide',tidy=FALSE---- f<-function(lambda){ sum(log(dpois(sample,lambda))) } lambdas<-seq(1,10,0.1) logveros<-sapply(lambdas, FUN = f) df<-data.frame(Lambda=lambdas, Logverosimilitud=logveros) ggplot(df,aes(x=Lambda, y=Logverosimilitud)) + geom_line(size=1.1) + labs(x=expression(lambda))
c22e84a77cb1b25cb9310c040da43d1deb132d14
60437c90873385bdf7256e2b3dc1b7a6e60e2228
/Scripts/ejercicio_practico.R
6cd012ace13fac7f6d9733ab6fb73ed7b7306d67
[]
no_license
FredysMD/Modeling-and-Simulation
6c725422b0a8e3c7fcca27c0d9865d43f63c345c
3419803157acd517e9ec7ac031254329d7af4700
refs/heads/master
2023-01-12T01:10:39.481052
2020-11-20T17:05:43
2020-11-20T17:05:43
294,872,153
1
0
null
2020-10-09T18:01:07
2020-09-12T04:48:19
R
ISO-8859-1
R
false
false
1,102
r
ejercicio_practico.R
moda <- function(dato){ fa <- data.frame(table(dato)) moda <- fa[which.max(fa$Freq), 1] } zona1<-rbind(194, 199, 191, 202, 215, 214, 197, 204, 199, 202, 230, 193, 194, 209) zona2<-rbind(158, 161, 143, 174, 220, 156, 156, 156, 198, 161, 188, 139, 147, 116) datos <- data.frame("zona1"= zona1, "zona2" = zona2) #---------------------------------- (summary(datos)) paste("moda de zona 1: ",moda(datos$zona1),sep="") paste("varianza de zona 1: ",var(datos$zona1),sep="") paste("varianza de zona 2: ",var(datos$zona2),sep="") #---------------------------------- #---------------------------------- zona1 <- datos$zona1 zona2 <- datos$zona2 hist(zona1,main = "Histograma de zona 1", xlab = "número de colonia/ 1000mm agua", ylab = "Frecuencia") hist(zona2,main = "Histograma de zona 2", xlab = "número de colonia/ 1000mm agua", ylab = "Frecuencia") #---------------------------------- #---------------------------------- boxplot(x = datos, main = "Niveles de colonias de bacterias", col = c("orange3", "yellow3", "green3", "grey")) #----------------------------------
18a9d5163e5743103e67c35ceb949314227d7212
25eed88db72bc6161c4725a210e13bce63cfe95a
/R/cdtStnCoords_Procs.R
59eba9192276cf496a17e04e0d09b569db67c179
[]
no_license
heureux1985/CDT
68fcfb02636cb9473b09bb2be918afd3880dde52
876c5f527628527b6d3923b59c710469c1db2dd2
refs/heads/master
2020-04-25T16:13:30.020982
2019-02-01T06:49:02
2019-02-01T06:49:02
null
0
0
null
null
null
null
UTF-8
R
false
false
11,079
r
cdtStnCoords_Procs.R
StnChkCoordsProcs <- function(GeneralParameters){ if(!dir.exists(GeneralParameters$output)){ Insert.Messages.Out(paste(GeneralParameters$output, "did not find"), format = TRUE) return(NULL) } if(GeneralParameters$data.type == "cdtcoords") { don0 <- getStnOpenData(GeneralParameters$infile) if(is.null(don0)) return(NULL) nom.col <- names(don0) don.disp <- don0 coords <- list(id = as.character(don0[, 1]), lon = as.numeric(don0[, 3]), lat = as.numeric(don0[, 4])) } if(GeneralParameters$data.type == "cdtstation") { don0 <- getStnOpenData(GeneralParameters$infile) if(is.null(don0)) return(NULL) don <- splitCDTData0(don0) if(is.null(don)) return(NULL) don <- don[c('id', 'lon', 'lat', 'elv')] nom.col <- c("ID", "Longitude", "Latitude", "Elevation") if(is.null(don$elv)){ don <- don[c('id', 'lon', 'lat')] nom.col <- nom.col[1:3] } don.disp <- as.data.frame(don) names(don.disp) <- nom.col coords <- don[c('id', 'lon', 'lat')] rm(don) } ############ outdir <- file.path(GeneralParameters$output, "CHECK.COORDS_data") dir.create(outdir, showWarnings = FALSE, recursive = TRUE) fileout <- file.path(outdir, paste0('Checked_Coords_', GeneralParameters$infile)) don.info <- getStnOpenDataInfo(GeneralParameters$infile) sep <- don.info[[3]]$sepr if(sep == "") sep <- " " write.table(don0, file = fileout, sep = sep, na = don.info[[3]]$miss.val, col.names = don.info[[3]]$header, row.names = FALSE, quote = FALSE) rm(don0) ############ if(GeneralParameters$shpfile == "") { Insert.Messages.Out("No ESRI shapefile found", format = TRUE) Insert.Messages.Out("The stations outside the boundaries will not be checked", format = TRUE) shpd <- NULL }else{ shpd <- getShpOpenData(GeneralParameters$shpfile) if(is.null(shpd)){ Insert.Messages.Out(paste('Unable to open', GeneralParameters$shpfile, 'or it is not an ESRI shapefile'), format = TRUE) Insert.Messages.Out("The stations outside the boundaries will not be checked", format = TRUE) shpd <- NULL }else{ shpd <- as(shpd[[2]], "SpatialPolygons") shpd <- gUnaryUnion(shpd) shpd <- gSimplify(shpd, tol = 0.05, topologyPreserve = TRUE) shpd <- gBuffer(shpd, width = GeneralParameters$buffer/111) } } ############ output <- list(params = GeneralParameters, info = don.info, id = coords$id) coords <- as.data.frame(coords) coords$id <- as.character(coords$id) don.disp$LonX <- coords$lon don.disp$LatX <- coords$lat don.disp$StatusX <- rep("blue", length(coords$lon)) don.table <- NULL ############ ## Missing coords imiss <- is.na(coords$lon) | is.na(coords$lat) if(any(imiss)){ don.table$miss <- data.frame(State = 'Missing Coordinates', don.disp[imiss, , drop = FALSE]) don.disp <- don.disp[!imiss, , drop = FALSE] coords <- coords[!imiss, , drop = FALSE] } ## Wrong coords iwrong <- coords$lon < -180 | coords$lon > 360 | coords$lat < -90 | coords$lat > 90 if(any(iwrong)){ don.table$wrong <- data.frame(State = 'Invalid Coordinates', don.disp[iwrong, , drop = FALSE]) don.disp <- don.disp[!iwrong, , drop = FALSE] coords <- coords[!iwrong, , drop = FALSE] } ## Duplicated ID iddup <- duplicated(coords$id) | duplicated(coords$id, fromLast = TRUE) if(any(iddup)){ don.table$iddup <- data.frame(State = 'Duplicate ID', don.disp[iddup, , drop = FALSE]) don.table$iddup <- don.table$iddup[order(coords$id[iddup]), , drop = FALSE] don.disp$StatusX[iddup] <- "orange" } ## Duplicated coordinates crddup <- duplicated(coords[, c('lon', 'lat'), drop = FALSE]) | duplicated(coords[, c('lon', 'lat'), drop = FALSE], fromLast = TRUE) if(any(crddup)){ don.table$crddup <- data.frame(State = 'Duplicate Coordinates', don.disp[crddup, , drop = FALSE]) don.table$crddup <- don.table$crddup[order(paste0(coords$lon[crddup], coords$lat[crddup])), , drop = FALSE] don.disp$StatusX[crddup] <- "orange" } ## Coordinates outside boundaries if(!is.null(shpd)){ spcoords <- coords coordinates(spcoords) <- ~lon+lat iout <- is.na(over(spcoords, geometry(shpd))) if(any(iout)){ don.table$out <- data.frame(State = 'Coordinates Outside', don.disp[iout, , drop = FALSE]) don.table$out <- don.table$out[order(coords$id[iout]), , drop = FALSE] don.disp$StatusX[iout] <- "red" } rm(spcoords, shpd) } ############ if(!is.null(don.table)){ don.table <- do.call(rbind, don.table) don.table <- don.table[, !names(don.table) %in% c('LonX', 'LatX', 'StatusX'), drop = FALSE] rownames(don.table) <- NULL } output$coords <- coords ############ file.index <- file.path(outdir, 'CoordinatesCheck.rds') dataOUT <- file.path(outdir, 'CDTDATASET') dir.create(dataOUT, showWarnings = FALSE, recursive = TRUE) file.table.csv <- file.path(outdir, 'Stations_to_Check.csv') file.table.rds <- file.path(dataOUT, 'Table.rds') file.display <- file.path(dataOUT, 'Display.rds') saveRDS(output, file.index) saveRDS(don.disp, file.display) saveRDS(don.table, file.table.rds) if(!is.null(don.table)) writeFiles(don.table, file.table.csv, col.names = TRUE) ############ .cdtData$EnvData$output <- output .cdtData$EnvData$PathData <- outdir .cdtData$EnvData$Table.Disp <- don.table .cdtData$EnvData$Maps.Disp <- don.disp return(0) } ########################################################################## StnChkCoordsDataStn <- function(GeneralParameters){ if(GeneralParameters$data.type == "cdtcoords") { don0 <- getStnOpenData(GeneralParameters$infile) if(is.null(don0)) return(NULL) nom.col <- names(don0) don.orig <- don0 coords <- list(id = as.character(don0[, 1]), lon = as.numeric(don0[, 3]), lat = as.numeric(don0[, 4])) } if(GeneralParameters$data.type == "cdtstation") { don0 <- getStnOpenData(GeneralParameters$infile) if(is.null(don0)) return(NULL) don <- splitCDTData0(don0) if(is.null(don)) return(NULL) don <- don[c('id', 'lon', 'lat', 'elv')] nom.col <- c("ID", "Longitude", "Latitude", "Elevation") if(is.null(don$elv)){ don <- don[c('id', 'lon', 'lat')] nom.col <- nom.col[1:3] } don.orig <- as.data.frame(don) names(don.orig) <- nom.col coords <- don[c('id', 'lon', 'lat')] rm(don) } ############ rm(don0) coords <- as.data.frame(coords) don.orig$LonX <- coords$lon don.orig$LatX <- coords$lat don.orig$StatusX <- rep("blue", length(coords$lon)) ############ ## Missing coords imiss <- is.na(coords$lon) | is.na(coords$lat) if(any(imiss)){ don.orig <- don.orig[!imiss, , drop = FALSE] coords <- coords[!imiss, , drop = FALSE] } ## Wrong coords iwrong <- coords$lon < -180 | coords$lon > 360 | coords$lat < -90 | coords$lat > 90 if(any(iwrong)){ don.orig <- don.orig[!iwrong, , drop = FALSE] coords <- coords[!iwrong, , drop = FALSE] } .cdtData$EnvData$output$coords <- coords .cdtData$EnvData$Maps.Disp <- don.orig return(0) } ########################################################################## StnChkCoordsCorrect <- function(){ if(is.null(.cdtData$EnvData$Table.Disp0)){ Insert.Messages.Out("No stations to be corrected") return(NULL) } idx0 <- as.character(.cdtData$EnvData$Table.Disp0$ID) fileTable <- file.path(.cdtData$EnvData$PathData, "CDTDATASET/Table.rds") Table.Disp <- readRDS(fileTable) if(!is.null(Table.Disp)){ idx <- as.character(Table.Disp$ID) id.del0 <- idx0[!idx0 %in% idx] change <- Table.Disp[, -1, drop = FALSE] change <- as.matrix(change) .cdtData$EnvData$Table.Disp <- Table.Disp }else{ id.del0 <- idx0 change <- matrix(NA, 0, 3) .cdtData$EnvData$Table.Disp <- NULL } ###### info <- .cdtData$EnvData$output$info fileout <- file.path(.cdtData$EnvData$PathData, paste0('Checked_Coords_', .cdtData$EnvData$output$params$infile)) don0 <- read.table(fileout, header = info[[3]]$header, sep = info[[3]]$sepr, na.strings = info[[3]]$miss.val, stringsAsFactors = FALSE, colClasses = "character") filemap <- file.path(.cdtData$EnvData$PathData, 'CDTDATASET', 'Display.rds') map.disp <- readRDS(filemap) nom1 <- names(map.disp) nom1 <- which(!nom1 %in% c('LonX', 'LatX', 'StatusX')) ###### if(.cdtData$EnvData$output$params$data.type == "cdtcoords"){ if(nrow(change) > 0){ ix <- match(idx, .cdtData$EnvData$output$id) don0[ix, ] <- change pos.lon <- 3 pos.lat <- 4 } if(length(id.del0)){ ix1 <- match(id.del0, .cdtData$EnvData$output$id) don0 <- don0[-ix1, , drop = FALSE] } } if(.cdtData$EnvData$output$params$data.type == "cdtstation"){ if(nrow(change) > 0){ ix <- match(idx, .cdtData$EnvData$output$id) don0[1:ncol(change), ix + 1] <- t(change) pos.lon <- 2 pos.lat <- 3 } if(length(id.del0)){ ix1 <- match(id.del0, .cdtData$EnvData$output$id) don0 <- don0[, -(ix1 + 1), drop = FALSE] } } if(length(id.del0)){ .cdtData$EnvData$output$id <- .cdtData$EnvData$output$id[-ix1] .cdtData$EnvData$Table.Disp0 <- .cdtData$EnvData$Table.Disp0[!idx0 %in% id.del0, , drop = FALSE] if(nrow(.cdtData$EnvData$Table.Disp0) == 0) .cdtData$EnvData$Table.Disp0 <- NULL } ###### idx1 <- .cdtData$EnvData$output$coords$id id.del1 <- if(length(id.del0)) idx1[idx1 %in% id.del0] else NULL if(nrow(change) > 0){ ix0 <- match(idx, idx1) ina <- is.na(ix0) if(any(ina)){ ix0 <- ix0[!ina] change0 <- change[!ina, , drop = FALSE] change1 <- change[ina, , drop = FALSE] idx2 <- idx[ina] }else change0 <- change .cdtData$EnvData$output$coords$id[ix0] <- as.character(change0[, 1]) .cdtData$EnvData$output$coords$lon[ix0] <- as.numeric(change0[, pos.lon]) .cdtData$EnvData$output$coords$lat[ix0] <- as.numeric(change0[, pos.lat]) map.disp[ix0, nom1] <- change0 map.disp$LonX[ix0] <- as.numeric(change0[, pos.lon]) map.disp$LatX[ix0] <- as.numeric(change0[, pos.lat]) .cdtData$EnvData$Maps.Disp[ix0, nom1] <- change0 .cdtData$EnvData$Maps.Disp$LonX[ix0] <- as.numeric(change0[, pos.lon]) .cdtData$EnvData$Maps.Disp$LatX[ix0] <- as.numeric(change0[, pos.lat]) if(any(ina)){ idx1 <- c(idx1, idx2) tmp <- data.frame(id = as.character(change1[, 1]), lon = as.numeric(change1[, pos.lon]), lat = as.numeric(change1[, pos.lat]), stringsAsFactors = FALSE) .cdtData$EnvData$output$coords <- rbind(.cdtData$EnvData$output$coords, tmp) tmp1 <- data.frame(change1, LonX = as.numeric(change1[, pos.lon]), LatX = as.numeric(change1[, pos.lat]), StatusX = "red", stringsAsFactors = FALSE) map.disp <- rbind(map.disp, tmp1) .cdtData$EnvData$Maps.Disp <- rbind(.cdtData$EnvData$Maps.Disp, tmp1) } } if(length(id.del1)){ ix <- match(id.del1, idx1) .cdtData$EnvData$output$coords <- .cdtData$EnvData$output$coords[-ix, , drop = FALSE] map.disp <- map.disp[-ix, , drop = FALSE] .cdtData$EnvData$Maps.Disp <- .cdtData$EnvData$Maps.Disp[-ix, , drop = FALSE] } ###### sep <- info[[3]]$sepr if(sep == "") sep <- " " write.table(don0, file = fileout, sep = sep, na = info[[3]]$miss.val, col.names = info[[3]]$header, row.names = FALSE, quote = FALSE) saveRDS(map.disp, filemap) return(0) }
ef4cee9279be51d7e7ee82a2642e5e9200eb62b4
f38bace9fc1f70068f2119362b4184e3d7122078
/R/plot_top_pictures.R
b2b96f0bc84c1ec9f2a3a9b98411a1ef6212e51d
[]
no_license
thies/paper-uk-vintages
9aafa11a558be8330cd9c69e5272b3cb432d322c
d31a7930725728efbb367d28d36502d205e58783
refs/heads/master
2021-06-24T17:34:10.390676
2020-11-14T12:57:46
2020-11-14T12:57:46
163,590,256
5
0
null
null
null
null
UTF-8
R
false
false
1,592
r
plot_top_pictures.R
# Table with pictures of estimate vintages plot_top_pictures <- function( regsam=NA, n=10, labels_short=NA, figpath = "/home/thies/db/Cambridge/data/images/cambridge/", img.width="50px"){ library(xtable) options(xtable.sanitize.text.function=identity) # load data if( is.na(regsam) ){ require(RCurl) remote.file <- "https://www.dropbox.com/s/he3hfquk8claaa1/regsamples.csv?dl=1" tmp.file <- tempfile() download.file(remote.file, tmp.file) regsam <- read.csv(tmp.file) file.remove(tmp.file) } if( is.na(labels_short) ){ labels_short <- c("Georg.","Early Vic.","Late V./Edw.","Interwar","Postwar","Contemp.","Revival") } eras <- unique(regsam$era) eras <- eras[grepl("^[a-z]", eras)] eras <- eras[ order(eras) ] names(labels_short) <- eras files <- list.files( figpath ) files <- files[grepl(".jpg", files)] tab <- matrix("", n , length(eras)) colnames(tab) <- eras for(e in eras){ tmp <- unique( subset(regsam, era == e, select=c("TOID","max","era"))) tmp <- tmp[rev(order(tmp$max)),] for(i in 1:n){ tab[i, e ] <- files[ grepl( as.character( tmp$TOID[i] ), files )] tab[ i, e] <- paste("\\includegraphics[width=",img.width,"]{", figpath ,tab[i,e],"}", sep="") } } colnames(tab) <- paste("\\emph{",labels_short,"}", sep="") xtab <- xtable( tab, booktabs=TRUE, comment=FALSE, row.names=FALSE) print(xtab, comment=FALSE, include.rownames=FALSE, floating=FALSE) } #plot_top_pictures(regsam=regsample)
219d5a5f640042c892494c39dd08281a75632a19
f8936f07724b6d7179e4bb7705f81d1008377420
/man/flag_dead_fish.Rd
cfe594952d0240fd325702028c60fbb0c61765e0
[]
no_license
jBernardADFG/telprep
5c86cc7f247dc0f126095d958387c55cba423dca
8495cad097b2cc87b97f3339e46e1fed84761c65
refs/heads/master
2021-04-05T11:52:47.124274
2020-07-24T18:20:40
2020-07-24T18:20:40
248,377,136
0
0
null
null
null
null
UTF-8
R
false
true
902
rd
flag_dead_fish.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flagDeadFish.R \name{flag_dead_fish} \alias{flag_dead_fish} \title{Uses movement information to determine the living status of fish.} \usage{ flag_dead_fish(best_detects, dist_thresh = 10) } \arguments{ \item{dist_thresh}{See description.} } \value{ Returns a data.frame where $MortFlag=T if a fish has been flagged as dead. } \description{ An ad hoc algorithm is used to determine the living status of fish. Basically, if a fish moves less than dist_thresh km for all consecutive detection periods following the detection, the fish will be flagged as dead. Euclidean distance is currently used. To determine the survival status of fish using a statistical approach that incorporates mortality sensor information use \code{\link{hmm_survival}}. } \examples{ flagged_fish <- flag_dead_fish(best_detects) head(flagged_fish) }
43df11290b62bb4821212071f31bc3bb024bb50d
8d28b939007e0887f3a1af5b54a24c68dd3d4204
/R/familyAR1TS.R
6620b24a77412669f1291da814e2abd63e86288c
[]
no_license
cran/VGAMextra
897c59ab2b532b0aa1d4011130db79f5c95eb443
ac7e3df54136fd4c9e49b754f6747a11d7c3b122
refs/heads/master
2021-06-06T03:52:23.167971
2021-05-24T03:10:07
2021-05-24T03:10:07
138,900,855
0
0
null
null
null
null
UTF-8
R
false
false
23,368
r
familyAR1TS.R
########################################################################## # These functions are # Copyright (C) 2014-2020 V. Miranda & T. Yee # Auckland University of Technology & University of Auckland # All rights reserved. ### Exact EIms for the AR1 model. # Here, theta = c(m*, serrors^2, theta) AR1EIM.G2 <- function(y, drift, sdError, AR1coeff, var.arg = TRUE, order = 1, nodrift = FALSE) { y <- cbind(y); nn <- nrow(y) RMat <- diag(c(sdError^2)) dRMat <- cbind( if(!nodrift) matrix(0, nrow = nn, ncol = 1) else NULL, if (var.arg) matrix(1, nrow = nn, ncol = 1) else 2 * sdError, matrix(0, nrow = nn, ncol = 1)) dmt0 <- matrix(1, nrow = nn, ncol = 1) dmt <- cbind(if (!nodrift) dmt0 else NULL, rep_len(0, nn), c(1 / (1 - AR1coeff[1])^2, y[-nn])) M <- 3 # For AR1 try.comb <- combVGAMextra(1:M, nodrift = nodrift) finMat <- apply(try.comb, 1, function(x) { kl <- x invRMat <- solve(RMat) dRdthel <- diag(dRMat[, kl[1]]) dRdthek <- diag(dRMat[, kl[2]]) term.1 <- (0.5) * invRMat %*% dRdthel %*% invRMat %*% dRdthek term.2 <- diag(dmt[, kl[1]]) %*% invRMat %*% diag(dmt[, kl[2]]) diag(term.1 + term.2) }) finMat[ , ncol(finMat)] <- (0.995) * finMat[ , ncol(finMat)] finMat } ### Density fo the AR1 model. dARff() may also work. dAR1extra <- function(x, drift = 0, # Stationarity is the default var.error = 1, ARcoef1 = 0.0, type.likelihood = c("exact", "conditional"), log = FALSE) { type.likelihood <- match.arg(type.likelihood, c("exact", "conditional"))[1] is.vector.x <- is.vector(x) x <- as.matrix(x) drift <- as.matrix(drift) var.error <- as.matrix(var.error) ARcoef1 <- as.matrix(ARcoef1) LLL <- max(nrow(x), nrow(drift), nrow(var.error), nrow(ARcoef1)) UUU <- max(ncol(x), ncol(drift), ncol(var.error), ncol(ARcoef1)) x <- matrix(x, LLL, UUU) drift <- matrix(drift, LLL, UUU) var.error <- matrix(var.error, LLL, UUU) rho <- matrix(ARcoef1, LLL, UUU) if (any(abs(rho) > 1)) warning("Values of argument 'ARcoef1' are greater ", "than 1 in absolute value") if (!is.logical(log.arg <- log) || length(log) != 1) stop("Bad input for argument 'log'.") rm(log) ans <- matrix(0.0, LLL, UUU) var.noise <- var.error / (1 - rho^2) ans[ 1, ] <- dnorm(x = x[1, ], mean = drift[ 1, ] / (1 - rho[1, ]), sd = sqrt(var.noise[1, ]), log = log.arg) ans[-1, ] <- dnorm(x = x[-1, ], mean = drift[-1, ] + rho[-1, ] * x[-nrow(x), ], sd = sqrt(var.error[-1, ]), log = log.arg) if (type.likelihood == "conditional") ans[1, ] <- NA if (is.vector.x) as.vector(ans) else ans } if (FALSE) AR1extra.control <- function(epsilon = 1e-6, maxit = 30, stepsize = 1,...){ list(epsilon = epsilon, maxit = maxit, stepsize = stepsize, ...) } ## Family function AR1extra() to fit order-1 Autoregressive models AR1extra <- function(zero = c(if (var.arg) "var" else "sd", "rho"), type.EIM = c("exact", "approximate")[1], var.arg = TRUE, nodrift = FALSE, ldrift = "identitylink", lsd = "loglink", lvar = "loglink", lrho = "rhobitlink", idrift = NULL, isd = NULL, ivar = NULL, irho = NULL, print.EIM = FALSE) { if (length(isd) && !is.Numeric(isd, positive = TRUE)) stop("Bad input for argument 'isd'") if (length(ivar) && !is.Numeric(ivar, positive = TRUE)) stop("Bad input for argument 'ivar'") if (length(irho) && (!is.Numeric(irho) || any(abs(irho) > 1.0))) stop("Bad input for argument 'irho'") type.EIM <- match.arg(type.EIM, c("exact", "approximate"))[1] poratM <- (type.EIM == "exact") imethod = 1 if (!is.logical(nodrift) || length(nodrift) != 1) stop("Argument 'nodrift' must be a single logical") if (!is.logical(var.arg) || length(var.arg) != 1) stop("Argument 'var.arg' must be a single logical") if (!is.logical(print.EIM)) stop("Invalid 'print.EIM'.") type.likelihood <- "exact" ismn <- idrift lsmn <- as.list(substitute(ldrift)) esmn <- link2list(lsmn) lsmn <- attr(esmn, "function.name") lsdv <- as.list(substitute(lsd)) esdv <- link2list(lsdv) lsdv <- attr(esdv, "function.name") lvar <- as.list(substitute(lvar)) evar <- link2list(lvar) lvar <- attr(evar, "function.name") lrho <- as.list(substitute(lrho)) erho <- link2list(lrho) lrho <- attr(erho, "function.name") n.sc <- if (var.arg) "var" else "sd" l.sc <- if (var.arg) lvar else lsdv e.sc <- if (var.arg) evar else esdv new("vglmff", blurb = c(ifelse(nodrift, "Two", "Three"), "-parameter autoregressive process of order-1\n\n", "Links: ", if (nodrift) "" else paste(namesof("drift", lsmn, earg = esmn), ", ", sep = ""), namesof(n.sc , l.sc, earg = e.sc), ", ", namesof("rho", lrho, earg = erho), "\n", "Model: Y_t = drift + rho * Y_{t-1} + error_{t},", "\n", " where 'error_{2:n}' ~ N(0, sigma^2) ", "independently", if (nodrift) ", and drift = 0" else "", "\n", "Mean: drift / (1 - rho)", "\n", "Correlation: rho = ARcoef1", "\n", "Variance: sd^2 / (1 - rho^2)"), constraints = eval(substitute(expression({ M1 <- 3 - .nodrift dotzero <- .zero constraints <- cm.zero.VGAM(constraints, x = x, zero = .zero , M = M, predictors.names = parameter.names, M1 = M1) }), list( .zero = zero, .nodrift = nodrift ))), infos = eval(substitute(function(...) { list(M1 = 3 - .nodrift , Q1 = 1, expected = TRUE, multipleResponse = TRUE, type.likelihood = .type.likelihood , ldrift = if ( .nodrift ) NULL else .lsmn , edrift = if ( .nodrift ) NULL else .esmn , lvar = .lvar , lsd = .lsdv , evar = .evar , esd = .esdv , lrho = .lrho , erho = .erho , zero = .zero ) }, list( .lsmn = lsmn, .lvar = lvar, .lsdv = lsdv, .lrho = lrho, .esmn = esmn, .evar = evar, .esdv = esdv, .erho = erho, .type.likelihood = type.likelihood, .nodrift = nodrift, .zero = zero))), initialize = eval(substitute(expression({ extra$M1 <- M1 <- 3 - .nodrift check <- w.y.check(w = w, y = y, Is.positive.y = FALSE, ncol.w.max = Inf, ncol.y.max = Inf, out.wy = TRUE, colsyperw = 1, maximize = TRUE) w <- check$w y <- check$y if ( .type.likelihood == "conditional") { w[1, ] <- 1.0e-6 } else { w[1, ] <- 1.0e-6 } NOS <- ncoly <- ncol(y) n <- nrow(y) M <- M1 * NOS extra$y <- y extra$print.EIM <- FALSE var.names <- param.names("var", NOS) sdv.names <- param.names("sd", NOS) smn.names <- if ( .nodrift ) NULL else param.names("drift", NOS) rho.names <- param.names("rho", NOS) parameter.names <- c(smn.names, if ( .var.arg ) var.names else sdv.names, rho.names) parameter.names <- parameter.names[interleave.VGAM(M, M1 = M1)] predictors.names <- c(if ( .nodrift ) NULL else namesof(smn.names, .lsmn , earg = .esmn , tag = FALSE), if ( .var.arg ) namesof(var.names, .lvar , earg = .evar , tag = FALSE) else namesof(sdv.names, .lsdv , earg = .esdv , tag = FALSE), namesof(rho.names, .lrho , earg = .erho , tag = FALSE)) predictors.names <- predictors.names[interleave.VGAM(M, M1 = M1)] if (!length(etastart)) { init.smn <- matrix( if (length( .ismn )) .ismn else 0, nrow = n, ncol = NOS, byrow = TRUE) init.rho <- matrix(if (length( .irho )) .irho else 0.1, n, NOS, byrow = TRUE) init.sdv <- matrix(if (length( .isdv )) .isdv else 1.0, n, NOS, byrow = TRUE) init.var <- matrix(if (length( .ivar )) .ivar else 1.0, n, NOS, byrow = TRUE) for (jay in 1:NOS) { mycor <- cov(y[-1, jay], y[-n, jay]) / apply(y[, jay, drop = FALSE], 2, var) init.smn[ , jay] <- mean(y[, jay]) * (1 - mycor) if (!length( .irho )) init.rho[, jay] <- sign(mycor) * min(0.95, abs(mycor)) if (!length( .ivar )) init.var[, jay] <- var(y[, jay]) * (1 - mycor^2) if (!length( .isdv )) init.sdv[, jay] <- sqrt(init.var[, jay]) } # for etastart <- cbind(if ( .nodrift ) NULL else theta2eta(init.smn, .lsmn , earg = .esmn ), if ( .var.arg ) theta2eta(init.var, .lvar , earg = .evar ) else theta2eta(init.sdv, .lsdv , earg = .esdv ), theta2eta(init.rho, .lrho , earg = .erho )) etastart <- etastart[, interleave.VGAM(M, M1 = M1), drop = FALSE] } }), list( .lsmn = lsmn, .lrho = lrho, .lsdv = lsdv, .lvar = lvar, .esmn = esmn, .erho = erho, .esdv = esdv, .evar = evar, .ismn = ismn, .irho = irho, .isdv = isd , .ivar = ivar, .type.likelihood = type.likelihood, .var.arg = var.arg, .nodrift = nodrift ))), linkinv = eval(substitute(function(eta, extra = NULL) { n <- nrow(eta) M1 <- 3 - .nodrift NOS <- ncol(eta)/M1 ar.smn <- if ( .nodrift ) 0 else eta2theta(eta[, M1*(1:NOS) - 2, drop = FALSE], .lsmn , earg = .esmn ) ar.rho <- eta2theta(eta[, M1*(1:NOS) , drop = FALSE], .lrho , earg = .erho ) y.lag <- matrix(0, nrow = n, ncol = NOS) y.lag[-1, ] <- extra$y[-n, ] ar.smn + ar.rho * y.lag }, list ( .lsmn = lsmn, .lrho = lrho , .lsdv = lsdv, .lvar = lvar , .var.arg = var.arg, .type.likelihood = type.likelihood, .esmn = esmn, .erho = erho , .esdv = esdv, .evar = evar , .nodrift = nodrift ))), last = eval(substitute(expression({ if (any(abs(ar.rho) > 1)) warning("Regularity conditions are violated at the final", "IRLS iteration, since 'abs(rho) > 1") M1 <- extra$M1 temp.names <- parameter.names temp.names <- temp.names[interleave.VGAM(M1 * ncoly, M1 = M1)] misc$link <- rep( .lrho , length = M1 * ncoly) misc$earg <- vector("list", M1 * ncoly) names(misc$link) <- names(misc$earg) <- temp.names for (ii in 1:ncoly) { if ( !( .nodrift )) misc$link[ M1*ii-2 ] <- .lsmn misc$link[ M1*ii-1 ] <- if ( .var.arg ) .lvar else .lsdv misc$link[ M1*ii ] <- .lrho if ( !( .nodrift )) misc$earg[[M1*ii-2]] <- .esmn misc$earg[[M1*ii-1]] <- if ( .var.arg ) .evar else .esdv misc$earg[[M1*ii ]] <- .erho } #if (( .poratM ) && any(flag.1) ) # warning("\nExact EIM approach currently implemented for", # " AR(1) processes \n with stationary noise. Shifting", # " to the 'approximate' EIM approach.") misc$M1 <- M1 misc$var.arg <- .var.arg misc$expected <- TRUE misc$nodrift <- .nodrift misc$poratM <- .poratM misc$print.EIM <- FALSE misc$type.likelihood <- .type.likelihood misc$multipleResponses <- TRUE }), list( .lsmn = lsmn, .lrho = lrho, .lsdv = lsdv, .lvar = lvar, .esmn = esmn, .erho = erho, .esdv = esdv, .evar = evar, .irho = irho, .isdv = isd , .ivar = ivar, .nodrift = nodrift, .poratM = poratM, .var.arg = var.arg, .type.likelihood = type.likelihood ))), loglikelihood = eval(substitute( function(mu, y, w, residuals= FALSE, eta, extra = NULL, summation = TRUE) { M1 <- 3 - .nodrift NOS <- ncol(eta)/M1 if ( .var.arg ) { ar.var <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lvar , earg = .evar ) ar.sdv <- sqrt(ar.var) } else { ar.sdv <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lsdv , earg = .esdv ) ar.var <- ar.sdv^2 } ar.smn <- if ( .nodrift ) 0 else eta2theta(eta[, M1*(1:NOS) - 2, drop = FALSE], .lsmn , earg = .esmn ) ar.rho <- eta2theta(eta[, M1*(1:NOS) , drop = FALSE], .lrho , earg = .erho ) if (residuals) { stop("Loglikelihood not implemented yet to handle", "residuals.") } else { loglik.terms <- c(w) * dAR1extra(x = y, drift = ar.smn , var.error = ar.var, type.likelihood = .type.likelihood , ARcoef1 = ar.rho, log = TRUE) loglik.terms <- as.matrix(loglik.terms) if (summation) { sum(if ( .type.likelihood == "exact") loglik.terms else loglik.terms[-1, ] ) } else { loglik.terms } } }, list( .lsmn = lsmn, .lrho = lrho , .lsdv = lsdv, .lvar = lvar , .var.arg = var.arg, .type.likelihood = type.likelihood, .nodrift = nodrift, .esmn = esmn, .erho = erho , .esdv = esdv, .evar = evar ))), vfamily = c("AR1"), validparams = eval(substitute(function(eta, y, extra = NULL) { M1 <- 3 - .nodrift n <- nrow(eta) NOS <- ncol(eta)/M1 ncoly <- ncol(as.matrix(y)) if ( .var.arg ) { ar.var <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lvar , earg = .evar ) ar.sdv <- sqrt(ar.var) } else { ar.sdv <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lsdv , earg = .esdv ) ar.var <- ar.sdv^2 } ar.smn <- if ( .nodrift ) matrix(0, n, NOS) else eta2theta(eta[, M1*(1:NOS) - 2, drop = FALSE], .lsmn , earg = .esmn ) ar.rho <- eta2theta(eta[, M1*(1:NOS) , drop = FALSE], .lrho , earg = .erho ) okay1 <- all(is.finite(ar.sdv)) && all(0 < ar.sdv) && all(is.finite(ar.smn)) && all(is.finite(ar.rho)) okay1 }, list( .lsmn = lsmn, .lrho = lrho , .lsdv = lsdv, .lvar = lvar , .var.arg = var.arg, .type.likelihood = type.likelihood, .nodrift = nodrift, .esmn = esmn, .erho = erho , .esdv = esdv, .evar = evar ))), simslot = eval(substitute(function(object, nsim) { pwts <- if (length(pwts <- object@prior.weights) > 0) pwts else weights(object, type = "prior") if (any(pwts != 1)) warning("ignoring prior weights") eta <- predict(object) fva <- fitted(object) M1 <- 3 - .nodrift NOS <- ncol(eta)/M1 if ( .var.arg ) { ar.var <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lvar , earg = .evar ) ar.sdv <- sqrt(ar.var) } else { ar.sdv <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lsdv , earg = .esdv ) ar.var <- ar.sdv^2 } ar.smn <- if ( .nodrift ) matrix(0, n, NOS) else eta2theta(eta[, M1*(1:NOS) - 2, drop = FALSE], .lsmn , earg = .esmn ) ar.rho <- eta2theta(eta[, M1*(1:NOS) , drop = FALSE], .lrho , earg = .erho ) ans <- array(0, c(nrow(eta), NOS, nsim)) for (jay in 1:NOS) { ans[1, jay, ] <- ar.smn[1, jay] + rnorm(nsim, sd = sqrt(ar.var[1, jay])) for (ii in 2:nrow(eta)) ans[ii, jay, ] <- ar.smn[ii, jay] + ar.rho[ii, jay] * ans[ii-1, jay, ] + rnorm(nsim, sd = sqrt(ar.var[ii, jay])) } ans <- matrix(c(ans), c(nrow(eta) * NOS, nsim)) ans }, list( .lsmn = lsmn, .lrho = lrho , .lsdv = lsdv, .lvar = lvar , .var.arg = var.arg, .nodrift = nodrift, .esmn = esmn, .erho = erho , .esdv = esdv, .evar = evar ))), deriv = eval(substitute(expression({ M1 <- 3 - .nodrift NOS <- ncol(eta)/M1 ncoly <- ncol(as.matrix(y)) if ( .var.arg ) { ar.var <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lvar , earg = .evar ) ar.sdv <- sqrt(ar.var) } else { ar.sdv <- eta2theta(eta[, M1*(1:NOS) - 1, drop = FALSE], .lsdv , earg = .esdv ) ar.var <- ar.sdv^2 } ar.smn <- if ( .nodrift ) matrix(0, n, NOS) else eta2theta(eta[, M1*(1:NOS) - 2, drop = FALSE], .lsmn , earg = .esmn ) ar.rho <- eta2theta(eta[, M1*(1:NOS) , drop = FALSE], .lrho , earg = .erho ) if (any(abs(ar.rho) < 1e-2)) warning("Estimated values of 'rho' are too close to zero.") y.lags <- apply(y, 2, function(x) WN.lags(y = cbind(x), lags = 1)) y.means <- y - (ar.smn + ar.rho * y.lags) dl.dsmn <- y.means / ar.var if ( .var.arg ) { dl.dvarSD <- y.means^2 / ( 2 * ar.var^2) - 1 / (2 * ar.var) } else { dl.dvarSD <- y.means^2 / ar.sdv^3 - 1 / ar.sdv } dl.drho <- y.means * y.lags / ar.var dsmn.deta <- dtheta.deta(ar.smn, .lsmn , earg = .esmn ) drho.deta <- dtheta.deta(ar.rho, .lrho , earg = .erho ) if ( .var.arg ) { dvarSD.deta <- dtheta.deta(ar.var, .lvar , earg = .evar ) } else { dvarSD.deta <- dtheta.deta(ar.sdv, .lsdv , earg = .esdv ) } myderiv <- c(w) * cbind(if ( .nodrift ) NULL else dl.dsmn * dsmn.deta, dl.dvarSD * dvarSD.deta, dl.drho * drho.deta) myderiv <- myderiv[, interleave.VGAM(M, M1 = M1)] myderiv }), list( .lsmn = lsmn, .lrho = lrho, .lsdv = lsdv, .lvar = lvar, .esmn = esmn, .erho = erho, .esdv = esdv, .evar = evar, .nodrift = nodrift , .var.arg = var.arg, .type.likelihood = type.likelihood ))), weight = eval(substitute(expression({ helpPor <- .poratM ### The EXACT EIMs M.fin <- if ( .nodrift ) M1 + (M1 - 1) else M1 + (M1 - 1) + (M1 - 2) pre.wz <- array(NA_real_, dim = c(n, M.fin , NOS)) for (jj in 1:NOS) { pre.wz[, , jj] <- AR1EIM.G2(y = y[, jj, drop = FALSE], drift = ar.smn[, jj, drop = FALSE], sdError = ar.sdv[, jj, drop = FALSE], AR1coeff = ar.rho[, jj, drop = FALSE], order = 1, nodrift = .nodrift , var.arg = .var.arg ) } if ( !(.nodrift) ) { dTHE.dETA <- cbind(dsmn.deta^2, dvarSD.deta^2, drho.deta^2, matrix(0, nrow = n, ncol = NOS), matrix(0, nrow = n, ncol = NOS), dsmn.deta * drho.deta) } else { dTHE.dETA <- cbind(dvarSD.deta^2, drho.deta^2, matrix(0, nrow = n, ncol = NOS)) } wzExact <- arwzTS(wz = pre.wz, w = w, M1 = M1, dTHE.dETA = dTHE.dETA) if ( .print.EIM ) wzPrint1 <- arwzTS(wz = pre.wz, w = w, M1 = M1, dTHE.dETA = dTHE.dETA, print.EIM = TRUE) ### Approximate EIMs pre.wz <- matrix(0, nrow = n, ncol = ifelse( .nodrift, 2 * M - 1, 3 * M - 3)) gamma0 <- ar.var / (1 - ar.rho^2) ned2l.dsmn <- 1 / ar.var ned2l.dvarSD <- if ( .var.arg ) 1 / (2 * ar.var^2) else 2 / ar.var ned2l.drho <- gamma0 / ar.var if (!( .nodrift )) pre.wz[, M1*(1:NOS) - 2] <- ned2l.dsmn * dsmn.deta^2 pre.wz[, M1*(1:NOS) - 1] <- ned2l.dvarSD * dvarSD.deta^2 pre.wz[, M1*(1:NOS) ] <- ned2l.drho * drho.deta^2 wzApp <- w.wz.merge(w = w, wz = pre.wz, n = n, M = ncol(pre.wz), ndepy = NOS) wz <- if (helpPor) wzExact else wzApp if ( .print.EIM ) { wzEx1 <- matrix(NA_real_, nrow = n, ncol = NOS) wzEx2 <- matrix(NA_real_, nrow = n, ncol = NOS) wzApp <- wzApp[, 1:M, drop = FALSE] wzApp <- array(wzApp, dim = c(n, M / NOS, NOS)) for (jj in 1:NOS) { wzEx1[, jj] <- if (NOS == 1) rowSums(wzPrint1) else rowSums(wzPrint1[, , jj, drop = FALSE]) wzEx2[, jj] <- rowSums(wzApp[, , jj, drop = FALSE]) } print.Mat <- cbind(wzEx1, wzEx2) colnames(print.Mat) <- c(paste("Exact", 1:NOS), paste("Approximate", 1:NOS)) rownames(print.Mat) <- paste("", 1:n) print(head(print.Mat)) } else { rm(wzExact, wzApp) } wz }), list( .var.arg = var.arg, .type.likelihood = type.likelihood, .nodrift = nodrift, .poratM = poratM, .print.EIM = print.EIM ))) ) }
f0e21d7ec0bc367df25d6e92655524b840093d80
57399b29b38f1d72bca228495f4da6d3dab0b0ae
/output/cluster/cluster_error.R
1c6d1f59fb6138831bc3492ce924df1822689280
[]
no_license
zpb4/ms_project1
db1b25f6c09c0b3e7a627c8585168d42a85fc30c
4ebaad0da991a3e4fc0febbb546fc04d486a00b0
refs/heads/master
2020-06-22T19:01:52.968077
2019-08-01T16:56:38
2019-08-01T16:56:38
197,782,135
0
0
null
null
null
null
UTF-8
R
false
false
1,055
r
cluster_error.R
##ERROR for Clusters rf_model<-'ncep_rf2' rf_type<-'mean' #'cf' or 'mean' obs<-'gpcc' kmns<-4 fdays<-15 lat<-19:22 #box is [19:22,18:20] lon<-18:20 obs_tp<-readRDS(paste('data/prcp/',obs,'_tp_wc_1984_2019.rds',sep="")) rf_tp<-readRDS(paste('data/prcp/',rf_model,'_tp_',rf_type,'_6_mask.rds',sep="")) clus_idx<-readRDS(paste('output/cluster/',rf_model,'_',obs,'_cluster_idx_',rf_type,'_man.rds',sep="")) ev_index<-readRDS(paste('output/index/',obs,'_ev_index_1_full.rds',sep="")) box_error<-array(NA, c(kmns,fdays)) for(i in 1:15){ for(k in 1:4){ forc<-rf_tp[lat,lon,i+1,(ev_index[which(clus_idx[,i]==k)]-i+1)] forc_mn<-apply(forc,3,function(x){mean(x,na.rm=T)}) ob<-obs_tp[lat,lon,ev_index[which(clus_idx[,i]==k)]] obs_mn<-apply(ob,3,function(x){mean(x,na.rm=T)}) err<-mean((forc_mn-obs_mn)/obs_mn) * 100 box_error[k,i]<-err } } saveRDS(box_error,paste('output/cluster/',rf_model,'_',obs,'_box_error_',rf_type,'.rds',sep="")) rm(list=ls()) ######################################END#####################################
b30cb950cfc7485d3209b6654428cbfb6812b28e
61dea145f59499bf141b22462fd67d2bc8dad134
/R/barlab_order.R
562c7fe1caa5c67f8b084e6107169511cb643dd1
[]
no_license
econDS/DEAR
9c88b69b2c7a1f8439aacd6139ebf0a23a389f8a
a2353380f90674de7c1c242b234097edd9432f8b
refs/heads/master
2022-03-27T14:05:04.896964
2022-02-17T02:08:13
2022-02-17T02:08:13
157,736,564
0
0
null
null
null
null
UTF-8
R
false
false
2,792
r
barlab_order.R
#' barplot with label and sorted frequency #' #' create barplot with label on top and sorted the categories by frequency #' from highest to lowest. #' #' @param x a categorical variable. #' @param percent a logical for display labels as percentage. #' @param title a title of plot #' @param unlimit a logical for setting plot more than 10 categories #' #' @return #' @export #' #' @examples #' a <- c("A", "A", "B", "B", "B", "C") #' barlab_order(a) #' barlab_order(a, percent = TRUE) barlab_order <- function(x, percent=FALSE, title=deparse(substitute(x)), unlimit=FALSE, decimal=0) { freq <- as.matrix(table(x)) ind <- order(freq, decreasing = TRUE) lbl <- attr(freq, "dimnames")[[1]][ind] num_cat <- length(freq) max_char_10 <- max(nchar(lbl[1:min(num_cat, 10)])) rot_angle <- 90 if (max_char_10 > 43.352*num_cat^(-1.134)) { rot_angle <- 65 } if(unlimit){ p <- barplot(freq[ind], names.arg="", col=rainbow(10), yaxt="n", ylim=c(0, max(freq)*1.2), main=title, ylab='count') # x axis label text(p[,1], -3, srt=rot_angle, adj=1, xpd=TRUE, labels=lbl[1:10], cex=1) # data label text(p, freq[ind]*1.05, label=freq[ind], pos=3, cex=0.8, srt=rot_angle, adj=-1) # y axis label aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3]) axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2) } else { if(num_cat >= 10){ cat("There is", num_cat, "categories. Only first top 10th would plot.\n Percent plot also not be available.") op <- par(mar=c(min(max_char_10,25)*0.5,4,4,2)) p <- barplot(freq[ind][1:10], names.arg = "", col=rainbow(10), las=2, ylim=c(0, max(freq)*1.11), main=title, ylab='count') text(p[,1], -3, srt = rot_angle, adj= 1, xpd = TRUE, labels = lbl[1:10] , cex=1.2) text(p, freq[ind][1:10], label = freq[ind][1:10], pos = 3, cex = 0.8) rm(op) } else { if(percent){ pct <- round(table(x)*100/sum(table(x)), decimal) pct_lb <- paste(pct,"%",sep="") p <- barplot(pct[ind], names.arg = lbl, main=title, col=rainbow(10), ylim=c(0, max(pct)*1.199), ylab='percent') text(p, pct[ind], label = pct_lb[ind], pos = 3, cex = 0.8) } else { p <- barplot(freq[ind], names.arg = lbl, main=title, yaxt="n", col=rainbow(10), ylim=c(0, max(freq)*1.2), ylab='count') text(p, freq[ind], label = freq[ind], pos = 3, cex = 0.8) # y axis label aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3]) axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2) } } } }
026576a68bcaee535b5cb19abe6ee57ee68d4939
69ddcaa08f6f0e1837bdc215fe54f2df45909bb0
/ui.R
9c98536e9a2164360ac943481e731a1e140243a1
[]
no_license
ats2/DataProducts
ba64a5ba5fae0ca7f5067ee8fee17a50728a7bf3
528562b632295c6c7c2e391a2ef842a302ed580b
refs/heads/master
2021-01-10T13:57:24.085092
2015-10-23T02:23:21
2015-10-23T02:23:21
44,737,833
0
0
null
null
null
null
UTF-8
R
false
false
734
r
ui.R
shinyUI( fluidPage( # Application title titlePanel("Newsletter Subscriptions"), sidebarLayout( # Sidebar with a slider and selection inputs sidebarPanel( selectInput("selection", "Choose a brand:", choices = brands), checkboxInput("trend", "Show Trend Line"), numericInput('forecast', 'Add Forecast Weeks (0 to 8)', 0, min = 0, max = 8, step = 1), sliderInput("date","Date Range:", min=min(data$WK_DATE),max=max(data$WK_DATE),value=c(min(data$WK_DATE),max(data$WK_DATE))) ), # Show trend mainPanel( #plotOutput("plot") tabsetPanel( tabPanel("App",plotOutput("plot")), tabPanel("Documentation",includeMarkdown("Documentation.md")) ) ) ) ))
470a92bc450f9c7fb701392752acd99b967b163c
67c2a90c7edfac3cfd891cb332c45e71cf4a6ad1
/R/cdm_penalty_values_tlp.R
6198be8b531e03625d7ba0fc733cf00cb5d94546
[]
no_license
alexanderrobitzsch/CDM
48316397029327f213967dd6370a709dd1bd2e0a
7fde48c9fe331b020ad9c7d8b0ec776acbff6a52
refs/heads/master
2022-09-28T18:09:22.491208
2022-08-26T11:36:31
2022-08-26T11:36:31
95,295,826
21
11
null
2019-06-19T09:40:01
2017-06-24T12:19:45
R
UTF-8
R
false
false
177
r
cdm_penalty_values_tlp.R
## File Name: cdm_penalty_values_tlp.R ## File Version: 0.04 cdm_penalty_values_tlp <- function(x, tau ) { y <- abs(x) / tau y <- ifelse( y > 1, 1, y ) return(y) }
46e0a45998192bc6ca786ce9b84ca4ebbd107221
0d7e791ea12733367b56cf6338e137accd3cf9fe
/meta17network/man/set_dirs.Rd
b3e29d38d414f83640c5ee20822550280d7e08cd
[]
no_license
aminorberg/meta17network-pkg
aefb010f8eb7a711049695bc30b01bee71e24050
34526c168603cf7d6b45ad59b9cec15d7c10d993
refs/heads/master
2023-04-18T00:08:35.833429
2023-02-05T11:23:50
2023-02-05T11:23:50
282,894,553
0
0
null
null
null
null
UTF-8
R
false
true
580
rd
set_dirs.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/set_dirs.r \name{set_dirs} \alias{set_dirs} \title{Defining directories} \usage{ set_dirs(working_dir, fit_fold = "fits") } \arguments{ \item{working_dir}{Full path to the working directory, under which everything else will be created.} \item{fit_fold}{Folder where the model fits will be saved (defaults to "fits")} } \value{ List of directories needed for the modelling pipeline, automatically created as subdirectories under the working_dir } \description{ Defining directories/paths to be used }
2145a9483ce7d5ef55703ca21e79bbb6d7900eeb
434104ea9a2d952caf418189c413eaae20b90e41
/man/chroma_random.Rd
a0a0301f42be15b99c78cb8763a38a4703cd758b
[]
no_license
R-forks-to-learn/colorscale
281f855240224e5fcf89b6f4edac2d4ca00b028e
8a6426d3aa2887b2e69aabcf70b7cb1cfe9a488a
refs/heads/master
2022-04-14T14:16:18.823725
2020-04-16T15:11:35
2020-04-16T15:11:35
null
0
0
null
null
null
null
UTF-8
R
false
true
414
rd
chroma_random.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/chroma-utils.R \name{chroma_random} \alias{chroma_random} \title{Random colors} \usage{ chroma_random(n = 1L) } \arguments{ \item{n}{Number of colors desired.} } \value{ A vector of hexadecimal string(s). } \description{ Creates a random color by generating a random hexadecimal string. } \examples{ chroma_random() chroma_random(10) }
089a0762c33b0825eac3fd0a398c412ffc1b54aa
a9a713bd5993bd5d18dcb73f51f477a4d56e2a21
/entry/markups/r-files/visits_area_special.R
753de5fdaa90d753d0c6b497d585b45a7987bc38
[]
no_license
d-sedov/location-configurations
95865f1fc07fda6f3a52922f2654837887af7c08
4f476d4c385c0cba435e78984f56b8ec46c6a957
refs/heads/master
2022-12-20T00:28:56.985992
2020-10-14T12:42:18
2020-10-14T12:42:18
304,011,398
0
0
null
null
null
null
UTF-8
R
false
false
9,200
r
visits_area_special.R
############################################################################### # # FILE: visits_area_special.R # # BY: Dmitry Sedov # # DATE: Sun May 10 2020 # # DESC: This code contains the code to estimate the extra visits from an # an increase in area specifically for a large CBSA # (in order to parallelize). # # IN: # 0. CBSA - the identifier of the urban area. # 1. Rho - the disutility of distance. # 2. c_a - the coefficient on the area. # 3. remainder - the remainder of row number division by 100 # to select a subset ofrestaurants. # ############################################################################### ################################ Libraries #################################### suppressPackageStartupMessages(library(readr)) suppressPackageStartupMessages(library(dplyr)) suppressPackageStartupMessages(library(ggplot2)) suppressPackageStartupMessages(library(gsubfn)) suppressPackageStartupMessages(library(data.table)) suppressPackageStartupMessages(library(stargazer)) ############################################################################### ################################ Constants #################################### days = 31 input_folder = '/home/quser/project_dir/urban/data/output/spatial-demand/main_demand' population_folder = '/home/quser/project_dir/urban/data/output/descriptive' output_folder = '/home/quser/project_dir/urban/data/output/entry/markups' ############################################################################### ################################# Functions ################################### PrepareData <- function(cbsa) { # Function to import and prepare single-CBSA dataset for estimation of extra # visits from extra area. # # IN: # cbsa - string with the cbsa number # OUT: # pairs, deltas # Set the cbsa folder name cbsa_folder_name <- paste0('cbsa', cbsa) # Import the cbg-restaurant pairs pairs_file_name <- paste0('pairs', cbsa, '.csv') pairs_file_path <- file.path(input_folder, cbsa_folder_name, pairs_file_name) pairs <- read_csv(pairs_file_path, col_types = cols(cbg = col_character())) # Import the deltas deltas_file_name <- paste0('deltas_optimized', cbsa, '.csv') deltas_file_path <- file.path(input_folder, cbsa_folder_name, deltas_file_name) suppressMessages(deltas <- read_csv(deltas_file_path)) # Import the total population count population_file_name <- 'cbg_population.csv' population_file_path <- file.path(population_folder, population_file_name) suppressMessages(population <- read_csv(population_file_path, col_types = cols(home_cbg = col_character()))) # Clean the pairs data pairs <- pairs %>% rename(home_cbg = cbg) %>% select(-r_cbsa) if ('cbg_cbsa_x' %in% colnames(pairs)) { pairs <- pairs %>% rename(cbg_cbsa = cbg_cbsa_x) %>% select(-cbg_cbsa_y) } pairs <- pairs %>% mutate(distance_km = distance / 1000) %>% mutate(distance_km_2 = distance_km ^ 2) pairs <- pairs %>% filter(!is.na(number_devices_residing)) pairs <- pairs %>% left_join(population) # Conversion to data tables pairs <- as.data.table(pairs) deltas <- as.data.table(deltas) setkey(pairs, sname_place_id) setkey(deltas, sname_place_id) # Conversion to data tables and set the variables in the outer scope value <- list(pairs = pairs, deltas = deltas) return(value) } visits_if_area_increased <- function(sg_id, area_coef) { # Function to compute the number of visits for a given restaurant with # an increase area. # IN: # 1. sg_id - restaurant identifier. # 2. area_coef - the coefficient on the area. # OUT: # 1. vector: c(sg_id, counterfactual_visits) # # Copy the pairs - deltas joined dataframe pairs_deltas <- copy(pairs_deltas_iteration) pairs_deltas[.(sg_id), delta := delta + area_coef] pairs_deltas[, `:=`( choice_utility = exp(delta + rho1 * distance_km + rho2 * distance_km_2) ) ] pairs_deltas[, `:=`( total_utility = 1 + sum(choice_utility)), by = .(home_cbg) ] pairs_deltas[, choices_made := total_pop * days * (choice_utility / total_utility) ] pairs_deltas <- pairs_deltas[, .(predicted_choices = sum(choices_made)), by = .(sname_place_id)] value <- pairs_deltas[sname_place_id == sg_id, predicted_choices] no_change <- visits[sname_place_id == sg_id, visits] marginal_visits <- value - no_change # Save summary of the results one_line <- paste(sg_id, as.character(no_change), as.character(value), as.character(marginal_visits), sep = ',') write(one_line, file = online_results_file_path, append = TRUE) return(list(sname_place_id = sg_id, altered_visits = value)) } ############################################################################### ################################## Main code ################################## args <- commandArgs(trailingOnly = TRUE) cbsa <- as.character(args[1]) rho1 <- as.numeric(args[2]) rho2 <- 0 c_a <- as.numeric(args[3]) remainder <- as.numeric(args[4]) cbsa_folder_name <- paste0('cbsa', cbsa) cat('cbsa: ', cbsa, 'remainder: ', remainder, '\n') # Create directory if it doesn't exist yet # dir.create(file.path(output_folder, cbsa_folder_name), showWarnings = FALSE) # dir.create(file.path(output_folder, cbsa_folder_name, 'parts'), showWarnings = FALSE) # Set 'online-results' path online_results_file_name <- paste0('online_visits_altered', cbsa, '_remainder', as.character(remainder), '.csv') online_results_file_path <- file.path(output_folder, cbsa_folder_name, 'parts', online_results_file_name) # Prepare data list[pairs, deltas] <- PrepareData(cbsa) # Compute the predicted number of visits pairs_deltas_main <- merge(pairs, deltas, by = 'sname_place_id', all.x = T) pairs_deltas_main[, `:=`( choice_utility = exp(delta + rho1 * distance_km + rho2 * distance_km_2) ) ] pairs_deltas_main[, `:=`( total_utility = 1 + sum(choice_utility)), by = .(home_cbg) ] pairs_deltas_main[, choices_made := total_pop * days * (choice_utility / total_utility) ] visits <- pairs_deltas_main[, .(visits = sum(choices_made)), by = .(sname_place_id)] # Join pairs and deltas for iteration over sname id, changing area pairs_deltas_iteration <- merge(pairs, deltas, by = 'sname_place_id', all.x = T) # Import the already-computed sname_place_ids: already_completed_file_path <- file.path(output_folder, paste0('cbsa', cbsa), paste0('online_visits_altered', cbsa, '.csv')) already_completed <- read_csv(already_completed_file_path, col_names = FALSE) already_completed <- already_completed %>% rename(sname_place_id = X1) not_completed <- deltas %>% anti_join(already_completed) %>% arrange(sname_place_id) %>% mutate(id = row_number()) %>% filter((id %% 100) == remainder) # Compute visits when extra area unit is added / subtracted altered_visits_p1 <- lapply(not_completed$sname_place_id, function(x) {visits_if_area_increased(x, c_a)}) # altered_visits_m1 <- lapply(deltas$sname_place_id, # function(x) {visits_if_area_increased(x, -c_a)}) # Convert the list to dataframe altered_visits_p1 <- rbindlist(lapply(altered_visits_p1, as.data.frame, stringsAsFactors = FALSE)) # altered_visits_m1 <- rbindlist(lapply(altered_visits_m1, as.data.frame, stringsAsFactors = FALSE)) # Rename columns altered_visits_p1 <- altered_visits_p1 %>% rename(visits_p1 = altered_visits) # altered_visits_m1 <- altered_visits_m1 %>% rename(visits_m1 = altered_visits) visits <- altered_visits_p1 %>% left_join(visits) # %>% left_join(altered_visits_m1) visits <- visits %>% mutate(diff_p1 = visits_p1 - visits) # %>% mutate(diff_m1 = visits - visits_m1) # Export the altered visits visits_altered_file_name <- paste0('all_visits_altered', cbsa, '_remainder', as.character(remainder), '.csv') visits_altered_file_path <- file.path(output_folder, cbsa_folder_name, 'parts', visits_altered_file_name) write_csv(visits, visits_altered_file_path) ###############################################################################
a0ddc799ef57680f8e15dde06b77b9f36b7c7034
688185e8e8df9b6e3c4a31fc2d43064f460665f1
/man/plafit.Rd
09d2bc6c2c64bfe13ab9b870668d04f75f654c6c
[]
no_license
IPS-LMU/emuR
4b084971c56e4fed9032e40999eeeacfeb4896e8
eb703f23c8295c76952aa786d149c67a7b2df9b2
refs/heads/master
2023-06-09T03:51:37.328416
2023-05-26T11:17:13
2023-05-26T11:17:13
21,941,175
17
22
null
2023-05-29T12:35:55
2014-07-17T12:32:58
R
UTF-8
R
false
true
1,702
rd
plafit.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plafit.R \name{plafit} \alias{plafit} \title{Calculate the coefficients of a parabola} \usage{ plafit(wav, fit = FALSE, n = 101) } \arguments{ \item{wav}{a vector or single column matrix of numeric values to which the 2nd order polynomial is to be fitted.} \item{fit}{if FALSE, return the coefficients of the polynomial; if TRUE, the values of the polynomial are returned to the same length as the vector wav.} \item{n}{in fitting the polynomial, linear time normalisation is first applied to the input vector wav to 101 points. The polynomial is fitted under the assumption that these points extend linearly in time between t = -1 and t = 1 with t = 0 occurring at the temporal midpoint.} } \value{ The function returns the coefficients of c0, c1, c2 in the parabola y = c0 + c1t + c2t\eqn{\mbox{\textasciicircum}}{^}2 where t extends between -1 and 1. The function can also be used to derive the values of the parabola as a function of time from the coefficients. } \description{ Fit a second ordered polynomial to a vector of values } \details{ The function fits a parabola (2nd order polynomial) following the method of van Bergem, Speech Communication, 14, 1994, 143-162. The algorithm fixes the parabola at the onset, midpoint, and offset of the vector i.e. such htat the fitted parabola and original vector have the same values at these points. } \examples{ # fit a polynomial to a segment of fundamental frequency data plafit(vowlax.fund[1,]$data) # return the fitted values of the polynomial plafit(vowlax.fund[1,]$data, fit=TRUE) } \seealso{ \code{\link{dct}} } \author{ Jonathan Harrington } \keyword{math}
7bab8cb6845dfc10de79683229d2c5320f06e5b9
20d793950af5e0c63f2a55eabbd1987d2fac517f
/man/howell.Rd
2285465fb6e850baf5cf5edc21d77a063affbb91
[]
no_license
RemkoDuursma/lgrdata
d708ad4af6dc586aa7ffbdc4ccf9bbb551da23bf
40f47e6588c056dfc9c909951e718ce4775bda3e
refs/heads/master
2020-04-18T15:36:00.468086
2019-06-19T09:45:57
2019-06-19T09:45:57
167,615,274
0
0
null
null
null
null
UTF-8
R
false
true
823
rd
howell.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/zzz.R \docType{data} \name{howell} \alias{howell} \title{Howell height, age and weight data} \format{A data frame with 783 rows and 4 variables: \describe{ \item{\code{sex}}{factor male or female} \item{\code{age}}{double Age (years) } \item{\code{weight}}{double Body weight (kg)} \item{\code{height}}{double Total height (cm)} }} \source{ <https://tspace.library.utoronto.ca/handle/1807/17996>, subsetted for non-missing data and one outlier removed. } \usage{ howell } \description{ These data were also used by McElreath (2016, "Statistical Rethinking", CRC Press). Data include measurements of height, age and weight on Khosan people. } \examples{ data(howell) with(howell, plot(age, height, pch=19, col=sex)) } \keyword{datasets}
e669445adbe1db377accf4f43574147996b69e15
1d7683d7394100ff40ffca9a906987f553058e46
/MCM/美赛/PRESS分析.R
705ee765f2585d1d7975a0f3ca9f6cf665f5d8fc
[]
no_license
lvksh/2018MCM
49353b5c5b3e0e222fcdb4042a508e1e51d857fd
a3a73e62f3032cc60d455025742ea0a7958da0bd
refs/heads/master
2020-07-25T12:29:09.134851
2019-09-13T15:24:54
2019-09-13T15:24:54
208,289,750
2
0
null
null
null
null
UTF-8
R
false
false
4,946
r
PRESS分析.R
# 灵敏度分析 # load data_2 & analysi ##### ProblemCData_CRTCB <- read_excel("ProblemCData_CRTCB.xlsx") Y <- filter(ProblemCData_CRTCB, MSN == 'TPOPP' | # population MSN == 'TETCB' | # total energy consumption MSN == 'CRTCB') # renewable + nuclear total consumption X <- filter(ProblemCData_CRTCB, # consumption for energies and sectors # NG MSN == 'NNACB' | # NG tran MSN == 'NNCCB' | # NG comercial MSN == 'NNICB' | # NG industry MSN == 'NNRCB' | # NG residential # petro MSN == 'PAACB' | MSN == 'PACCB' | MSN == 'PAICB' | MSN == 'PARCB' | # expen # NG MSN == 'NGACV' | MSN == 'NGCCV' | MSN == 'NGICV' | MSN == 'NGRCV' | # petro MSN == 'PAACV' | MSN == 'PACCV' | MSN == 'PAICV' | MSN == 'PARCV' ) Y <- filter(Y,Year >= 1970) X <- filter(X,Year >= 1970) Y_distinct <- function(statecode) { YY <- sapply(1:n_distinct(Y$MSN),function(e){ temp <- filter(eval(parse(text = paste0("Y_",statecode))),MSN == unique(Y$MSN)[e]) temp <- temp[,'Data'] temp }) YY } X_distinct <- function(statecode) { XX <- sapply(1:n_distinct(X$MSN),function(e){ temp <- filter(eval(parse(text = paste0("X_",statecode))),MSN == unique(X$MSN)[e]) temp <- temp[,'Data'] temp }) XX } for (statecode in c("AZ","CA","NM","TX")) { eval(parse(text = paste0('X_',statecode,' <- filter(X,StateCode == ',paste0('"',statecode,'"'),')'))) eval(parse(text = paste0('Y_',statecode,' <- filter(Y,StateCode == ',paste0('"',statecode,'"'),')'))) } for (statecode in c("AZ","CA","NM","TX")) { eval(parse(text = paste0('X_',statecode,'_name <- X_distinct(',paste0('"',statecode,'"'),')'))) eval(parse(text = paste0('Y_',statecode,'_name <- Y_distinct(',paste0('"',statecode,'"'),')'))) } for (statecode in c("AZ","CA","NM","TX")) { eval(parse(text = paste0('X_',statecode,'_name <- data.frame(X_',statecode,'_name)'))) eval(parse(text = paste0('Y_',statecode,'_name <- data.frame(Y_',statecode,'_name)'))) } for (statecode in c("AZ","CA","NM","TX")) { eval(parse(text = paste0('colnames(X_',statecode,'_name) <- unique(X$MSN)'))) eval(parse(text = paste0('colnames(Y_',statecode,'_name) <- unique(Y$MSN)'))) } # for (statecode in c("AZ","CA","NM","TX")) { # eval(parse(text = paste0('write.table(X_',statecode,'_name',",'","X_",statecode,'_modelbuilding.csv',"',",'sep="',",","\")"))) # eval(parse(text = paste0('write.table(Y_',statecode,'_name',",'","Y_",statecode,'_modelbuilding.csv',"',",'sep="',",","\")"))) # } ##### # AZ # Y1 : PRESS : 27527580451 SSE : 24208194049 # Y2 : PRESS : 225347199092 SSE: 195387643205 Y <- Y_AZ_name[,-2] X <- X_AZ_name Y1 <- Y[,1] Y2 <- Y[,2] X9 <- X[,9] X16 <- X[,16] X13 <- X[,13] p <- numeric(40) for (i in 1:40){ mod <- lm(Y1[-i]~X9[-i]+X16[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X9[i]+co[3]*X16[i] p[i] <- Y1[i]-Yh } sum(p^2) p <- numeric(40) for (i in 1:40){ mod <- lm(Y2[-i]~X9[-i]+X13[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X9[i]+co[3]*X13[i] p[i] <- Y2[i]-Yh } sum(p^2) # CA # Y1 : PRESS : 9.78881890542e+11 SSE : 8.94406597838e+11 # Y2 : PRESS : 5.15478e+11 SSE: 9.1466691981e+10 Y <- Y_CA_name[,-2] X <- X_CA_name Y1 <- Y[,1] Y2 <- Y[,2] X9 <- X[,9] # JKTCB X3 <- X[,3] p <- numeric(40) for (i in 1:40){ mod <- lm(Y1[-i]~X9[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X9[i] p[i] <- Y1[i]-Yh } sum(p^2) p <- numeric(40) for (i in 1:40){ mod <- lm(Y2[-i]~JKTCB[-i]+X3[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*JKTCB[i]+co[3]*X3[i] p[i] <- Y2[i]-Yh } sum(p^2) # NM # Y1 : PRESS : 61755441738 SSE : 56942150649 # Y2 : PRESS : 480666650 SSE: 388610135 Y <- Y_NM_name[,-2] X <- X_NM_name Y1 <- Y[,1] Y2 <- Y[,2] X9 <- X[,9] X10 <- X[,10] X16 <- X[,16] p <- numeric(40) for (i in 1:40){ mod <- lm(Y1[-i]~X9[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X9[i] p[i] <- Y1[i]-Yh } sum(p^2) p <- numeric(40) for (i in 1:40){ mod <- lm(Y2[-i]~X10[-i]+X16[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X10[i]+co[3]*X16[i] p[i] <- Y2[i]-Yh } sum(p^2) # TX # Y1 : PRESS : 2.250407e+14 SSE : 2.906097e+12 # Y2 : PRESS : 724282174263 SSE: 616417874230 Y <- Y_TX_name[,-2] X <- X_TX_name Y1 <- Y[,1] Y2 <- Y[,2] X9 <- X[,9] X4 <- X[,4] X3 <- X[,3] X13 <- X[,13] p <- numeric(40) for (i in 1:40){ mod <- lm(Y1[-i]~X4[-i]+X9[-i]+X13[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X4[i]+co[3]*X9[-i]+co[4]*X13[i] p[i] <- Y1[i]-Yh } sum(p^2) p <- numeric(40) for (i in 1:40){ mod <- lm(Y2[-i]~X4[-i]+X3[-i]) co <- mod$coefficients Yh <- co[1]*1+co[2]*X4[i]+co[3]*X3[i] p[i] <- Y2[i]-Yh } sum(p^2)
e4d683d6ee5688088295e194267c819df70b9fb8
1a6bd47467a151a6c59dac7948df7a6bf1d7694a
/Coherence.R
51d15b4ba0a3f0544000172697038eb08956e6fd
[]
no_license
gopalam/R_Matlab_Scripts
1c5f64fe4e279044ff5dd37fe6845de609b60a30
b1ecd55008bb7a7d485a5609968b75e1b01ab5f3
refs/heads/main
2023-07-22T13:40:20.623552
2021-09-11T20:06:25
2021-09-11T20:06:25
405,449,726
0
0
null
null
null
null
UTF-8
R
false
false
2,212
r
Coherence.R
Coherence <- function(signal1,signal2,Dt) { # input signal1 , signal1, vectors to analyze for coherence. # Dt, sampling interval (in time units of time, e.g 15 min sampling interval, Dt=1/96.) #Frequency-dependent coherence on a pair of variables # Dt= sampling interval in units of days # coherence can be determined for pairs of tims series variables # output= coherence (c) and frequency (f) vectors # # written as described in Menke, W., and J. Menke (2009), Environmental Data Analysis with # MATLAB, 288 pp., Elsevier, New York. N=length(signal1); # round off to even number of points N=floor(N/2)*2; signal1=signal1[1:N]; signal2=signal2[1:N]; N=2*floor(N/2); Nf = N/2+1; fny = 1/(2*Dt); Df = fny/(N/2); f1 = Df f2=0:(Nf-1); f=f1*f2; # bandwidth factors lowside = 0.75; highside =1.25; # initialize matrix C = matrix( 0 ,nrow=Nf, ncol=1) # compute cross spectral density and power spectral density # no need to normalize, since all normalizations cancel u = fft( signal1[1:N] ); # fft v = fft( signal2[1:N] ); # fft u = u[1:Nf]; # delete negative frequencies v = v[1:Nf]; usv = Conj(u) * v; # cross spectral density of u and v usu = Conj(u) * u; # power spectral density of u vsv = Conj(v) * v; # power spectral density of v # average over band usva=matrix( 0 ,nrow=Nf, ncol=1) usua=matrix( 0 ,nrow=Nf, ncol=1) vsva=matrix( 0 ,nrow=Nf, ncol=1) for (i in 1:Nf) { fi = Df*(i-1); # center frequency flow = lowside*fi; fhigh = highside*fi; ilow = floor(flow/Df)+1; ihigh = floor(fhigh/Df)+1; if (ilow < 1){ ilow=1; } else { if (ilow > Nf) { ilow=Nf; } } if (ihigh < 1) { ihigh=1; } else { if (ihigh > Nf) { ihigh=Nf; } } # integral over frequency range usva = mean( usv[ilow:ihigh] ); usua = mean( usu[ilow:ihigh] ); vsva = mean( vsv[ilow:ihigh] ); C[i] = (Conj(usva)*usva) / (usua * vsva) ; C=Re(C); } Ch=cbind(f,C) return(Ch) }
9097eb3ea8521d3a70bc9b5112a7b756bbd25697
61836adc436f52ad22dc9546c4fc435c1d581234
/cachematrix.R
ac7001db2a3954cff9006c8bf26da7d8e165f46a
[]
no_license
sonkrishna/ProgrammingAssignment2
e806c637f7158295e08d9a760c1db93bcaa99189
28944627867098abf01ca4369c335840d1683e21
refs/heads/master
2020-12-29T18:52:31.021546
2014-10-26T12:35:24
2014-10-26T12:35:24
null
0
0
null
null
null
null
UTF-8
R
false
false
1,899
r
cachematrix.R
## This file has 2 functions. ## makeCacheMatrix - creates a wrapper around a matrix, #helps cache matrix inverse ## cacheSolve - Computes matrix inversion if not already computed before. #stores inverted matrix in its environment, that can be retrieved when needed #next time ## This function, #1. Takes in a matrix (invertible). #2. If not given when called, matrix can be set by set function exposed #3. set, get, setInverse, getInverse functions are returned #4. get function gives the matrix stored in this environment #5. setInverse function stores inverse of matrix into im #6. getInverse returns inverse of the matrix stored in im. makeCacheMatrix <- function(x = matrix()) { im <- NULL set <- function(mat) { x <<- mat im <<- NULL } get <- function() x setInverse <- function(inv) im <<- inv getInverse <- function() im list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## This function, #1. Takes output of makeCacheMatrix as input #2. Return of makeCacheMatrix is its environment (im and x), #list(set, get, setInverse, getInverse) #3. Sees if the input has inverse computed, else reads matix, #computes inverse, and stores back in environment #4. Returns inverse of matrix cacheSolve <- function(x, ...) { mi <- x$getInverse() if(!is.null(mi)) { message("Getting inverse") return(mi) } data <- x$get() mi <- solve(data, ...) x$setInverse(mi) mi } ## Usage, #1. m <- matrix(c(1, 0, 5, 2, 1, 6, 3, 4, 0), 3, 3) #Makes matrix #2. setwd("D:/Krishna/Personal/Tutorial/Data Science JHU/R/Assignments #/02/code/ProgrammingAssignment2/") #Sets working directory for codefile #3. source("cachematrix.R") #Loads makeCacheMatrix, cacheSolve into memory #4. auxMatrix <- makeCacheMatrix(m) # creates cache matrix functions #5. cacheSolve(auxMatrix) #computes n stores inverse
6aa38a4ca594644ff0e8d629c0b5d66a415dc38f
55663fab76aba92730ab3b91e12b079e7d8b3466
/EB.R
d5aba94692475e656206b3e5b9b28af1ab068bbc
[]
no_license
BimoUnderWater/Image-Processing
97fec43f038997499172ccdd7dbf05c5db075733
c48065d938d7f708a915c74250b53c6046c92f8f
refs/heads/main
2023-03-06T19:38:16.549330
2021-02-22T14:37:44
2021-02-22T14:37:44
null
0
0
null
null
null
null
SHIFT_JIS
R
false
false
10,712
r
EB.R
########################################################## # 魚解析用スクリプト   2021/01/09 山中改良 # 魚解析用スクリプト   2019/04/18 山中作成  # マガン解析用スクリプト 2018/03/15 横山作成を基に作成 # できること:画像解析,暗さを指定して処理の自動停止,結果をcsv形式で自動保存, #         解析日の自動入力,画像・マスク・結果の保存先フォルダの指定,グラフ作成,総個体数の表示  # 画像解析手法:差分→マスク処理→2値化→オブジェクトサイズ分類→ラベリング #  # :オプション機能.使用したいときに#を消去する. #  ## :処理過程の説明 #  ### :入力が必要な部分 # 使用するためにはEBImageパッケージのインストールが必要 ########################################################## ## 処理時間の計測開始 ts<-proc.time() ## EBImage(画像処理パッケージ)の起動 library(EBImage) library(tcltk) ## 撮影情報の入力 place <- "izunuma" ### 撮影場所を入力 time <- " 04:11" ### 撮影開始時刻を入力 today <- Sys.Date() ##今日(解析を実施した日)の日付を表示 todayc <- format(today, "%Y-%m-%d") #todayc <- "2018-07-27" ### 撮影日と解析日が異なる場合は手入力 now <- Sys.time() ##解析時時刻取得 todayc <- format(now, "-%Y%m%d-%H%M%S") ##解析時時刻文字列 todayc ## 解析に使用するパラメータを設定 th <- 0.1 ### 2値化閾値を入力 ob <- 2000  ### オブジェクトサイズを入力 stop <- 0.43  ### 解析を停止する暗さ(輝度値)を入力(izunuma171116は0.19) erth <- 3 dith <- 81 ## マスク画像を保存した作業ディレクトリ(ファイルパス)の設定 ## 解析に使用する画像を保存した作業ディレクトリ(ファイルパス)の設定 file.dir <- "C:/test/1029"  ### " "に指定したいフォルダの1つ前までのパスを入力しておく.パスは/で区切ること.撮影日と解析日が異なる場合は下行で手入力する #file.dir <- "result0.10-1.csv"  ### " "にフォルダのパスを入力する.パスは/で区切ること ## 解析結果と処理時間のファイルを出力したい作業ディレクトリ(ファイルパス)の設定 result.dir <- "C:/result" ### " "にフォルダのパスを入力する.パスは/で区切ること ## 解析結果の出力ファイル名を指定する result.name <- paste0("result", todayc,th,ob,stop,erth,dith, ".csv")  ### 撮影日と解析日が異なる場合は下行で手入力する #result.name <- "result0.10-1.csv"  ### " "に結果のファイル名を入力.拡張子はcsvにする ## グラフの出力ファイル名を指定する #graph.name <- paste0("graph", todayc, ".pdf")  ### 撮影日と解析日が異なる場合は下行で手入力する #graph.name <- "graph.10-1.csv"  ### " "にグラフのファイル名を入力.拡張子はjpgにする ## 処理時間の出力ファイル名を指定する #time.name <- paste0("time", todayc, ".csv")  ### 撮影日と解析日が異なる場合は下行で手入力する #time.name <- "time0.10-1.csv"  ### ""に処理時間のファイル名を入力.拡張子はcsvにする ## 解析準備 ## マスク画像を保存した作業ディレクトリ(ファイルパス)を指定 #setwd(mask.dir) ## マスク画像の読み込み #mask <- readImage(mask.file) ## 処理する画像を保存した作業ディレクトリ(ファイルパス)を指定 setwd(file.dir) ## ディレクトリ内のファイル一覧を作成 files <- list.files() files ## 「JPG」拡張子を持つファイルをリストアップ JPG.files <- grep("\\.jpg$", files) JPG.files ## 処理結果を行列として定義 result <- matrix(",", nrow = length(JPG.files), ncol = 8) ## 総個体数nを定義 n <- 0 n1 <- (length(JPG.files)/3) pb <- txtProgressBar(min=1, max=n1, style=3) ## 以下,画像処理ディレクトリ内の画像の枚数分の処理を繰り返す for (i in 1:(length(JPG.files)/3)) { ## 画像解析 ## 解析に使用する画像を読み込む.img2を解析対象の画像とし,前後の画像を使用 img1 <- readImage(files[JPG.files[3*i-2]]) img2 <- readImage(files[JPG.files[3*i-1]]) img3 <- readImage(files[JPG.files[3*i]]) #display(img2)  ## 解析対象の画像を表示 #img1 <- img1*mask ##水面に反射している場合オンに #img2 <- img2*mask #img3 <- img3*mask ## RGBのうちRのみを抽出 imgb1 <- channel(img1,"red") imgb2 <- channel(img2,"red") imgb3 <- channel(img3,"red") #display(imgb2)  ## B画像の表示 #writeImage(imgb2,"imgb2.jpg")  ## B画像の保存 ## 全ての輝度値の平均を算出 mean <- mean(imgb2[,]) ## 画像が明るくなりすぎたら解析を停止 if(mean >= stop) { ## 全ての輝度値の中央値を算出 #median1 <- median(imgb1[,]) #median2 <- median(imgb2[,]) #median3 <- median(imgb3[,]) #median <- abs(median1-median2) ##全部で動かす #if(0.005 <= median) {th <- (median*4)+0.01} ##明るさが変わったら止める #if(median <= 0.001) { ## 背景差分 ## 前後の写真との差分により背景及び雲を除去する.雲は数秒で動き難い. ## img2を減ずるのはの画像を白の値にするため. ## 前後平均画像との背景差分 imgd <- imgb1-imgb2 imgd3 <- imgb3-imgb2 imgd2 <- abs(imgd) imgd4 <- abs(imgd3) ## 単純2値化 #hist(imgm) ## 輝度のヒストグラムの表示 ### ヒストグラムグラム等により閾値を設定.小さい値ほど残りやすく,大きい値ほど消えやすい imgt <- imgd2 >th imgt3 <- imgd4 >th #display(imgt) ## 2値化画像の表示 #writeImage(imgt,"imgt.jpg") ## 2値化画像の 保存 kern <- makeBrush(erth, shape="disc")## フィルタの作成 imge1<-erode(imgt,kern)## 明るい部分を減らす imge3<-erode(imgt3,kern)## 明るい部分を減らす kern2 <- makeBrush(dith, shape="disc")## フィルタの作成 imgm1<-dilate(imge1,kern2)## 明るい部分を増やす imgm3<-dilate(imge3,kern2)## 明るい部分を増やす imgm<-fillHull(imgm1) ##穴の開いた魚を無くす imgm2<-fillHull(imgm3) ##穴の開いた魚を無くす #display(imgd) ## 差分画像の表示 #writeImage(imgd,"imgd.jpg")  ## 差分画像の保存 ## マスク処理 ## 画像にマスクをかける #imgm <- imgm*mask  ## 差分画像とマスク範囲が重なる部分(=魚(ノイズを含む))のみを残す #display(imgm)  ## マスク画像の表示 #writeImage(imgm,"imgm.jpg")  ## マスク画像の保存 ## ノイズ除去 ## オブジェクトサイズ処理によるノイズ除去 ## オブジェクトのサイズをリストアップ imgt <- bwlabel(imgm) imgt3 <- bwlabel(imgm2) sizelist <- computeFeatures.shape(imgt)[,1] sizelist3 <- computeFeatures.shape(imgt3)[,1] ## 対象が多すぎると時間がかかる.閾値とのバランス #hist(sizelist) ## オブジェクトサイズのヒストグラムを表示 ## オブジェクトサイズがより小さい対象をノイズとして除去 ## 除去するオブジェクトサイズを設定.ヒストグラムと実際の魚のオブジェクトサイズから判断(600m→2.2px,1km→1.2px) objn <- which(sizelist >= ob) ## 設定したサイズ以上のオブジェクトを魚として抽出 objn3 <- which(sizelist3 >= ob) a <- 1:length(sizelist) a3 <- 1:length(sizelist3) if(length(objn) == 0){ b <- a }else{ b <- a[-objn] } if(length(objn3) == 0){ b3 <- a3 }else{ b3 <- a3[-objn3] } imgn <- rmObjects(imgt, b)  ## 小さいオブジェクト(=ノイズ)を消去 imgn3 <- rmObjects(imgt3, b3)  ## 小さいオブジェクト(=ノイズ)を消去 #display(imgn) ## ノイズ除去画像の表示 #s <- as.character(i) #s1 <- paste("imgn",s,".jpg", sep="") #writeImage(imgn,s1) ##ラベリング(オブジェクトに通し番号をつける) imgl <- bwlabel(imgn) imgl3 <- bwlabel(imgn3) #}else{imgl <- 0} }else{ imgl <- 0 imgl3 <- 0 } ## カウント結果 ## 処理結果にファイル名,カウント数,輝度値の平均を入れる. result[3*i-2,1] <- 3*i-2  ### グラフの横軸に使用する.撮影間隔に従い式を入力する result[3*i-2,3] <- files[JPG.files[3*i-2]] ##写真のファイル名 result[3*i-2,5] <- max(imgl) ## ラベリングの最大値(=オブジェクトの個数) result[3*i-2,7] <- mean ## 輝度値の平均 result[3*i-1,1] <- 3*i-1  ### グラフの横軸に使用する.撮影間隔に従い式を入力する result[3*i-1,3] <- files[JPG.files[3*i-1]] ##写真のファイル名 result[3*i-1,5] <- max(imgl3) ## ラベリングの最大値(=オブジェクトの個数) result[3*i-1,7] <- mean ## 輝度値の平均 result[3*i,1] <- 3*i  ### グラフの横軸に使用する.撮影間隔に従い式を入力する result[3*i,3] <- files[JPG.files[3*i]] ##写真のファイル名 result[3*i,5] <- 0 ## ラベリングの最大値(=オブジェクトの個数) result[3*i,7] <- 0 ## 輝度値の平均 setTxtProgressBar(pb, i) ## 処理結果を出力保存 setwd(result.dir) write(t(result), file=result.name, ncolumns=8) ## 処理結果のグラフを作成・出力保存 #x <- result[,1] #y <- result[,5] #n <- n+max(imgl) ### 軸の最大・最小、ラベル名、プロットの色や形等を任意で指定する #plot(x, y, type = "n", ylim=c(0,80), xlab = "photo [枚]", ylab = "fish count [匹]") #points(x, y , col = "red", pch = 16) #lines(x, y, col = "red") ## グラフに撮影情報を表示 #date <- paste0(todayc, time) #n.picture <- paste0("Number of pictures: ", length(JPG.files)) #n.fish <- paste0("Total count of fishes: ", n) #mtext(place,side=3,line=3,adj=0,cex=1) #mtext(date,side=3,line=2,adj=0,cex=1) #mtext(n.picture,side=3,line=1,adj=0,cex=1) #mtext(n.fish,side=3,line=0,adj=0,cex=1) #dev.copy(device=pdf, file=graph.name, family="Japan1GothicBBB") #dev.off() ## 処理時間の計測終了 te <- proc.time()-ts ## 処理時間=終了時間-開始時間 ## 処理時間を出力保存 #write(te, file=time.name) ## 次の解析のため,作業ディレクトリを画像が保存されたフォルダに戻す setwd(file.dir) } result te
65f7e9c54ce4dcb74e5b82fa6b7999cd14b82d71
a113344ac3a2bd80b0528079183ce6c43e4b65de
/man/dot-get_H.Rd
65f5cb12237a66d085d0c0778a15cb96d70e5798
[ "MIT" ]
permissive
cdmuir/tealeaves
2ae939d9a2f2560f2b5af38c1bdbae9ae053b119
f4495e2403107d7b549165ac5f8c3a48bbac086a
refs/heads/master
2022-08-11T23:27:56.357289
2022-07-20T02:31:39
2022-07-20T02:31:39
156,582,831
7
1
null
null
null
null
UTF-8
R
false
true
1,648
rd
dot-get_H.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tleaves.R \name{.get_H} \alias{.get_H} \title{H: sensible heat flux density (W / m^2)} \usage{ .get_H(T_leaf, pars, unitless) } \arguments{ \item{T_leaf}{Leaf temperature in Kelvin} \item{pars}{Concatenated parameters (\code{leaf_par}, \code{enviro_par}, and \code{constants})} \item{unitless}{Logical. Should function use parameters with \code{units}? The function is faster when FALSE, but input must be in correct units or else results will be incorrect without any warning.} } \value{ Value in W / m\eqn{^2} of class \code{units} } \description{ H: sensible heat flux density (W / m^2) } \details{ \deqn{H = P_\mathrm{a} c_p g_\mathrm{h} (T_\mathrm{leaf} - T_\mathrm{air})}{H = P_a c_p g_h * (T_leaf - T_air)} \tabular{lllll}{ \emph{Symbol} \tab \emph{R} \tab \emph{Description} \tab \emph{Units} \tab \emph{Default}\cr \eqn{c_p} \tab \code{c_p} \tab heat capacity of air \tab J / (g K) \tab 1.01\cr \eqn{g_\mathrm{h}}{g_h} \tab \code{g_h} \tab boundary layer conductance to heat \tab m / s \tab \link[=.get_gh]{calculated}\cr \eqn{P_\mathrm{a}}{P_a} \tab \code{P_a} \tab density of dry air \tab g / m^3 \tab \link[=.get_Pa]{calculated}\cr \eqn{T_\mathrm{air}}{T_air} \tab \code{T_air} \tab air temperature \tab K \tab 298.15\cr \eqn{T_\mathrm{leaf}}{T_leaf} \tab \code{T_leaf} \tab leaf temperature \tab K \tab input } } \examples{ library(tealeaves) cs <- make_constants() ep <- make_enviropar() lp <- make_leafpar() T_leaf <- set_units(298.15, K) tealeaves:::.get_H(T_leaf, c(cs, ep, lp), FALSE) } \seealso{ \code{\link{.get_gh}}, \code{\link{.get_Pa}} }
62891260bee7e1b59f5fd1881c36e3c215b25884
6cc899d63c4bab1e667cc0f1c1e6286fbb8596fc
/man/dunn_index.Rd
e089c236cd5d413931b126f5d3dfe646ed7f25dd
[]
no_license
mobius-eng/ravcutils
1b26a513b8b6eecb4d71ed26f775d462c1870287
7e3138c0b8ac1df8799bde50b391de2205f98d92
refs/heads/master
2023-08-13T11:32:27.675698
2021-10-13T10:48:09
2021-10-13T10:48:09
373,436,701
0
0
null
null
null
null
UTF-8
R
false
true
587
rd
dunn_index.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ravcutils.R \name{dunn_index} \alias{dunn_index} \title{Dunn index to select cluster numbers} \usage{ dunn_index(data, classification, centroids, stdev) } \arguments{ \item{data}{matrix of observations} \item{classification}{vector of classiffication labels for each observation} \item{centroids}{Matrix whose each row is the centroid of a cluster} \item{stdev}{vector of standard deviations for each variable} } \description{ Optimal selection is done for the number of clusters that maximize the index }
26d905c831600213e5c1790bb189eaab74227c2f
ef8bf01e222787092e3c62dadf19c573558b68b5
/man/TF_EAE_LAND_OCCUPTN_1991.Rd
efa2ec3f2d240749b161175a909116d287eebd1b
[ "CC-BY-2.0" ]
permissive
weRbelgium/BelgiumStatistics
fdd8998e52ae43bf1564a61cba6a676edacd8dd4
37758b79164412322db35e9bb172d0ea5f3b192b
refs/heads/master
2021-01-21T05:59:22.308770
2015-11-19T22:59:05
2015-11-19T22:59:05
44,752,835
17
2
null
null
null
null
UTF-8
R
false
false
651
rd
TF_EAE_LAND_OCCUPTN_1991.Rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/datasets.R \docType{data} \name{TF_EAE_LAND_OCCUPTN_1991} \alias{TF_EAE_LAND_OCCUPTN_1991} \title{TF_EAE_LAND_OCCUPTN_1991} \description{ leefmilieu: TF_EAE_LAND_OCCUPTN_1991. More information about this data can be found in the inst/docs folder and at \url{http://statbel.fgov.be/nl/statistieken/opendata/datasets/leefmilieu} } \examples{ \dontrun{ data(TF_EAE_LAND_OCCUPTN_1991) str(TF_EAE_LAND_OCCUPTN_1991) } } \references{ \url{http://statbel.fgov.be/nl/statistieken/opendata/home}, \url{http://statbel.fgov.be/nl/statistieken/opendata/datasets/leefmilieu} }
9b03d9f8e06a7b42b959725a4f2ee1894a4ba66a
10955e82b2b8e760bb5aed755dcc4555a6ee7ae4
/R/script_ProATPsyn.R
3be946eb45e933aef12939667f8975708f09ff8e
[]
no_license
wangjs/BioCycTU
b0dbd7aa94b4c8a92af45779946fed5664ebf1f0
d278b20f301ef30267f8b47495b6b21e0df4b08b
refs/heads/master
2021-05-06T10:32:04.256753
2014-06-03T19:22:13
2014-06-03T19:22:13
null
0
0
null
null
null
null
UTF-8
R
false
false
11,894
r
script_ProATPsyn.R
#! /usr/bin/Rscript --vanilla ## subunit KOID ## beta K02112 ## alpha K02111 ## gamma K02115 ## delta K02113 ## epsilon K02114 ## c K02110 ## a K02108 ## b K02109 CutSeq <- function(cutSeq){ # USE: cut a vector based on the 'cutSeq'. This function is used to cut "full" seq. It means the sum of 'cutSeq' should be equal to the length of vector, which is used to cut. # INPUT: 'cutSeq' a sequence used to cut the vector. # OUTPUT: the index matrix # remove 0, because we cannot cut a sequence by the internal of 0. cutSeq <- cutSeq[cutSeq != 0] vecCutseq <- length(cutSeq) if (vecCutseq == 1) { headCut <- 1 endCut <- cutSeq } else { # loopCutSeq is the circle of vecCutseq loopCutSeq <- list() for(i in 1:vecCutseq) { loopCutSeq[[i]] <- cutSeq[1:i] } loopSumCutSeq <- sapply(loopCutSeq, sum) # the head and tail sequence headCut <- c(1,loopSumCutSeq[1:(vecCutseq-1)]+1) endCut <- loopSumCutSeq } cutMat <- matrix(c(headCut, endCut), 2, byrow=TRUE) return(cutMat) } CutSeqEqu <- function(vecLen, equNum){ # USE: to cut a vector with equal internal. # INPUT: 'vecLen' the length of vector used to cut. 'equNum' the equal internal # OUTPUT: the index matrix. if (equNum > vecLen){ # the internal is bigger than the length of vecLen. So we use the full vecLen. cutMat <- matrix(c(1, vecLen)) } else { timeNum <- vecLen %/% equNum remainer <- vecLen %% equNum cutSeq <- c(rep(equNum, timeNum), remainer) cutMat <- CutSeq(cutSeq) } return(cutMat) } # load KEGG and BioCyc database load('biocycSpe.RData') load('bioKEGGSpe.RData') load('KEGGCycAPI.RData') library(foreach) library(doMC) library(XML) registerDoMC(4) # the common species commSpe <- merge(biocycSpe, bioKEGGSpe, by.x = 'TaxonomyID', by.y = 'TaxonomyID', sort = FALSE) commProSpe <- commSpe[grepl('Prokaryotes', commSpe[, 8]), ] # remove duplicate BioCyc speID according to KEGG speID commKEGGVec <- commProSpe[duplicated(commProSpe[, 6]), 6] commKEGGMat <- commProSpe[commProSpe[, 6] %in% commKEGGVec, ] delRowName <- c('553', '839', '1057', '1056', '1066', '1346', '1267', '1481', '1480', '1482', '1582', '1648', '1645', '1647', '1723', '1681', '1666', '1902', '2107', '1918', '2299', '2473') commProSpe <- commProSpe[!(rownames(commProSpe) %in% delRowName), ] # some species names changed commProSpe[commProSpe[, 2] %in% 'BANT198094-WGS', 2] <- 'ANTHRA' ## # **select species used in phylogenetic profiling** ## phyloProSpe <- read.csv('wholeListFile.csv', row.names = 1) ## commProSpe <- commProSpe[commProSpe[, 6] %in% phyloProSpe[, 2], ] # get KO list KOVec <- c('K02111', 'K02112', 'K02115', 'K02113', 'K02114', 'K02110', 'K02108', 'K02109') names(KOVec) <- c('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'c', 'a', 'b') KOList <- vector('list', 8) names(KOList) <- paste(names(KOVec), 'KO', sep = '') for (i in 1:8) { KOMat <- getKEGGKO(KOVec[i]) KOMat <- KOMat[KOMat[, 1] %in% commProSpe[, 6], ] KOList[[i]] <- KOMat } # whole species vector wholeSpe = vector() for (i in 1:8) { wholeSpe = union(wholeSpe, KOList[[i]][, 1]) } # merge ATPKO <- vector('list', length(wholeSpe)) names(ATPKO) <- wholeSpe for (i in 1:length(wholeSpe)) { eachSpe <- lapply(KOList, function(x) { eachSpeKO <- x[x[, 1] %in% wholeSpe[i], ,drop = FALSE] # some species may lack certain subuints speKONum <- nrow(eachSpeKO) if (speKONum == 0) { uniKO <- NA } else { uniKO <- eachSpeKO[, 2] } return(unname(uniKO)) }) ATPKO[[i]] <- unlist(eachSpe) } # transfer KEGG ID to BioCyc ID # BioCyc speID uniSpe <- commProSpe[commProSpe[, 6] %in% wholeSpe, ] uniSpe <- uniSpe[order(as.character(uniSpe[, 6])), ] uniSpe <- uniSpe[rank(wholeSpe), ] ATPKOKEGGSpe <- names(ATPKO) names(ATPKO) <- as.character(uniSpe[, 2]) tmp1 <- ATPKO # some may contain ''', like 'atpF'', and could not be identified by R ramote server for (i in 1:length(ATPKO)) { print(paste('It is running ', i, '.', sep = '')) x <- ATPKO[[i]] KEGGIDVec <- paste(ATPKOKEGGSpe[i], x, sep = ':') KEGGIDVec <- paste(KEGGIDVec, collapse='+') KEGGsymTable <- webTable(paste('http://rest.kegg.jp/list/', KEGGIDVec, sep = ''), n = 2) KEGGsym <- KEGGsymTable[, 2] KEGGsym <- sapply(strsplit(KEGGsym, split = ';', fixed = TRUE), '[', 1) y <- character(length = length(x)) y[which(is.na(x))] <- NA y[which(!is.na(x))] <- KEGGsym hasSym <- which(!grepl(' ', y)) x[hasSym] <- y[hasSym] ATPKO[[i]] <- x } identical(sapply(tmp1, length), sapply(ATPKO, length)) identical(sapply(tmp1, is.na), sapply(tmp1, is.na)) # sperate ATPKO hasDot <- sapply(ATPKO, function(x) { hasDotEach <- grepl('\'', x) if (sum(hasDotEach) > 0){ return(TRUE) } else { return(FALSE) } }) save(ATPKO, ATPKOKEGGSpe, file = 'ATPKO.RData') # ========================== script ======================= ATPKODot <- ATPKO[hasDot] ATPKOKEGGSpeDOT <- ATPKOKEGGSpe[hasDot] save(ATPKODot, ATPKOKEGGSpeDOT, file = 'ATPKODOT.RData') ATPKO <- ATPKO[!hasDot] ATPKOKEGGSpe <-ATPKOKEGGSpe[!hasDot] save(ATPKO, ATPKOKEGGSpe, file = 'ATPKONODOT.RData') # ========================================================= # BioCyc geneID. Cut the whole length with internal 4 cutMat <- CutSeqEqu(length(ATPKODot), 4) for (j in 1:ncol(cutMat)) { ATPKOCycPart <- foreach (i = cutMat[1, j]:cutMat[2, j]) %dopar% { # may have NA print(paste('It is running ', i, ' with the name of ', names(ATPKODot)[i], '.', sep = '')) iniVal <- ATPKODot[[i]] iniVal[!is.na(iniVal)] <- sapply(iniVal[!is.na(iniVal)], KEGGID2CycID, speKEGGID = ATPKOKEGGSpeDOT[i], speCycID = names(ATPKODot)[i]) return(iniVal) } names(ATPKOCycPart) <- names(ATPKODot)[cutMat[1, j]:cutMat[2, j]] save(ATPKOCycPart, file = paste('ATPKOCycPartDOT', cutMat[1, j], '_', cutMat[2, j], '.RData', sep = '')) Sys.sleep(30) } # BioCyc geneID. Cut the whole length with internal 4 cutMat <- CutSeqEqu(length(ATPKO), 4) for (j in 1:ncol(cutMat)) { ATPKOCycPart <- foreach (i = cutMat[1, j]:cutMat[2, j]) %dopar% { # may have NA print(paste('It is running ', i, ' with the name of ', names(ATPKO)[i], '.', sep = '')) iniVal <- ATPKO[[i]] iniVal[!is.na(iniVal)] <- sapply(iniVal[!is.na(iniVal)], KEGGID2CycID, speKEGGID = ATPKOKEGGSpe[i], speCycID = names(ATPKO)[i]) return(iniVal) } names(ATPKOCycPart) <- names(ATPKO)[cutMat[1, j]:cutMat[2, j]] save(ATPKOCycPart, file = paste('ATPKOCycNODOTPart', cutMat[1, j], '_', cutMat[2, j], '.RData', sep = '')) Sys.sleep(60) } list2list <- function(lsInput){ # not support NA ## $alphaKO ## [1] "TU0-6636" "TU0-6635" "TU00243" ## $betaKO ## [1] "TU0-6636" "TU0-6635" "TU00243" ## $gammaKO ## [1] "TU0-6636" "TU0-6635" "TU00243" ## $detaKO ## [1] "TU0-6636" "TU0-6635" "TU00243" ## $epsilonKO ## [1] "TU0-42328" "TU0-6636" "TU0-6635" "TU00243" ## $cKO ## [1] "TU0-6636" "TU0-6635" "TU00243" ## $aKO ## [1] "TU0-6636" "TU0-6635" "TU00243" ## $bKO ## [1] "TU0-6636" "TU0-6635" "TU00243" uniEle <- unique(unlist(lsInput)) uniList <- vector('list', length(uniEle)) names(uniList) <- uniEle for (i in 1:length(uniEle)) { uniList[[i]] <- names(lsInput)[sapply(lsInput, function(x){uniEle[i] %in% x})] } return(uniList) } # transcription unit ATPTU <- vector('list', length(ATPKO)) names(ATPTU) <- names(ATPKO) for (i in 1:length(ATPKO)) { # get TU name eachTU <- lapply(ATPKO[[i]], function(x) { if (is.na(x)) { TU <- NA } else { eachGeneInfo <- getCycTUfGene(x, speID = names(ATPKO)[i]) TU <- eachGeneInfo if (is.null(TU)) { TU <- NA } else {} } return(TU) }) # range the list # select non NA hasNA <- sapply(eachTU, function(x) { if (sum(is.na(x)) > 0) { return(TRUE) } else { return(FALSE) } }) TUnona <- eachTU[which(!hasNA)] TUList <- list2list(TUnona) # select NA TUna <- eachTU[which(hasNA)] if (length(TUna) != 0) { TUList$noTU <- names(TUna) } else {} ATPTU[[i]] <- TUList } save(ATPTU, file = 'ATPCycPhyloTU.RData') #################### process the repeat data ################ load('wholeTUList.RData') delNum <- 284 nonDelNum <- which(!((1:length(wholeTUList)) %in% delNum)) wholeTUList <- wholeTUList[nonDelNum] duNames <- names(wholeTUList)[which(duplicated(names(wholeTUList)))] which(names(wholeTUList) %in% duNames) wholeTUList[which(names(wholeTUList) %in% duNames)] load('ATPKOCyc.RData') delNum <- c(1240, 1293, 1428, 1857) nonDelNum <- which(!((1:length(ATPKOCyc)) %in% delNum)) ATPKOCyc <- ATPKOCyc[nonDelNum] duNames <- names(ATPKOCyc)[which(duplicated(names(ATPKOCyc)))] which(names(ATPKOCyc) %in% duNames) ATPKOCyc[which(names(ATPKOCyc) %in% duNames)] ############## calculate the loss/repeat ATP ############ ATPSubMat <- matrix(ncol = 8, nrow = length(ATPKO)) colnames(ATPSubMat) <- names(KOVec) rownames(ATPSubMat) <- names(ATPKO) for (i in 1:length(ATPKO)) { subGene <- ATPKO[[i]] subName <- names(subGene) ATPsubName <- names(KOVec) subNamePat <- paste('^', ATPsubName, 'KO', sep = '') subNum <- integer(8) for (j in 1:8) { sub <- subGene[grep(subNamePat[j], subName)] if (sum(is.na(sub)) > 0) { num <- 0 } else { num <- length(sub) } subNum[j] <- num } ATPSubMat[i, ] <- subNum } write.csv(ATPSubMat, 'ATPSubMat.csv') ATPSubMat2 <- apply(ATPSubMat, 1:2, function(x) { if (x > 0) { x <- 1 } else { x <- 0 } return(x) }) require(pheatmap) subComplexCol <- data.frame(Subunit = factor(c(rep(1, 5), rep(2, 3)), labels = c('F1', 'Fo'))) rownames(subComplexCol) <- names(KOVec) pheatmap(as.matrix(dist(t(ATPSubMat), diag = TRUE, upper = TRUE)), annotation = subComplexCol, clustering_method = "average", cellwidth = 15, cellheight = 12) ########################## test code ######################## ## test2 <- ATPKO[1:2] ## for (i in 1:length(test2)){ ## may have NA ## iniVal <- test2[[i]] ## iniVal[!is.na(iniVal)] <- names(KEGGID2CycID(iniVal[!is.na(iniVal)], names(test2)[i], n = 4)) ## test2[[i]] <- iniVal ## } ## test1 <- vector('list', 3) ## names(test1) <- c('ECOLI', 'RRUB269796', 'MTUB1304279-WGS') ## ecoKO <- c('EG10098', 'EG10101', 'EG10104', 'EG10105', 'EG10100', 'EG10102', 'EG10099', 'EG10103') ## names(ecoKO) <- names(ATPKO$ECOLI) ## rruKO <- c('GCN1-1247', 'GCN1-1249', 'GCN1-1248', 'GCN1-1246', 'GCN1-1250', 'GCN1-3300', 'GCN1-3301', 'GCN1-3298', 'GCN1-3299') ## names(rruKO) <- names(ATPKO$RRUB269796) ## mtuhKO <- c(NA, NA, 'GSRF-1250', NA, 'GSRF-1251', 'GSRF-1247', 'GSRF-1246', 'GSRF-1248') ## names(mtuhKO) <- names(ATPKO$`MTUB1304279-WGS`) ## test1[[1]] <- ecoKO ## test1[[2]] <- rruKO ## test1[[3]] <- mtuhKO ## eachTU <- lapply(test1[[2]], function(x) { ## if (is.na(x)) { ## TU <- NA ## } else { ## eachGeneInfo <- getCycTUfGene(x, speID = 'RRUB269796') ## TU <- eachGeneInfo ## if (is.null(TU)) { ## TU <- NA ## } else {} ## } ## return(TU) ## }) ## ATPTU <- vector('list', length(test1)) ## names(ATPTU) <- names(test1) ## for (i in 1:length(test1)) { ## get TU name ## eachTU <- lapply(test1[[i]], function(x) { ## if (is.na(x)) { ## TU <- NA ## } else { ## eachGeneInfo <- getCycTUfGene(x, speID = names(test1)[i]) ## TU <- eachGeneInfo ## if (is.null(TU)) { ## TU <- NA ## } else {} ## } ## return(TU) ## }) ## range the list ## select non NA ## hasNA <- sapply(eachTU, function(x) { ## if (sum(is.na(x)) > 0) { ## return(TRUE) ## } else { ## return(FALSE) ## } ## }) ## TUnona <- eachTU[which(!hasNA)] ## TUList <- list2list(TUnona) ## select NA ## TUna <- eachTU[which(hasNA)] ## if (length(TUna) != 0) { ## TUList$noTU <- names(TUna) ## } else {} ## ATPTU[[i]] <- TUList ## }