content
large_stringlengths
0
6.46M
path
large_stringlengths
3
331
license_type
large_stringclasses
2 values
repo_name
large_stringlengths
5
125
language
large_stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.46M
extension
large_stringclasses
75 values
text
stringlengths
0
6.46M
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/enumerationSetApi.r \name{enumerationSet$update} \alias{enumerationSet$update} \title{Update an enumeration set by replacing items in its definition.} \arguments{ \item{webId}{The ID of the enumeration set to update.} \item{PIEnumerationSet}{A partial enumeration set containing the desired changes.} } \value{ The enumeration set was updated. } \description{ Update an enumeration set by replacing items in its definition. }
/man/enumerationSet-cash-update.Rd
permissive
frbl/PI-Web-API-Client-R
R
false
true
505
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/enumerationSetApi.r \name{enumerationSet$update} \alias{enumerationSet$update} \title{Update an enumeration set by replacing items in its definition.} \arguments{ \item{webId}{The ID of the enumeration set to update.} \item{PIEnumerationSet}{A partial enumeration set containing the desired changes.} } \value{ The enumeration set was updated. } \description{ Update an enumeration set by replacing items in its definition. }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/trav_out_node.R \name{trav_out_node} \alias{trav_out_node} \title{Traverse from one or more selected edges onto adjacent, outward nodes} \usage{ trav_out_node(graph, conditions = NULL, copy_attrs_from = NULL, agg = "sum") } \arguments{ \item{graph}{a graph object of class \code{dgr_graph}.} \item{conditions}{an option to use filtering conditions for the traversal.} \item{copy_attrs_from}{providing an edge attribute name will copy those edge attribute values to the traversed nodes. If the edge attribute already exists, the values will be merged to the traversed nodes; otherwise, a new node attribute will be created.} \item{agg}{if an edge attribute is provided to \code{copy_attrs_from}, then an aggregation function is required since there may be cases where multiple edge attribute values will be passed onto the traversed node(s). To pass only a single value, the following aggregation functions can be used: \code{sum}, \code{min}, \code{max}, \code{mean}, or \code{median}.} } \value{ a graph object of class \code{dgr_graph}. } \description{ From a graph object of class \code{dgr_graph} with an active selection of edges move opposite to the edge direction to connected nodes, replacing the current edge selection with the selection with those nodes traversed to. An optional filter by node attribute can limit the set of nodes traversed to. } \examples{ # Set a seed set.seed(23) # Create a simple graph graph <- create_graph() \%>\% add_n_nodes( 2, type = "a", label = c("asd", "iekd")) \%>\% add_n_nodes( 3, type = "b", label = c("idj", "edl", "ohd")) \%>\% add_edges_w_string( "1->2 1->3 2->4 2->5 3->5", rel = c(NA, "A", "B", "C", "D")) # Create a data frame with node ID values # representing the graph edges (with `from` # and `to` columns), and, a set of numeric values df_edges <- data.frame( from = c(1, 1, 2, 2, 3), to = c(2, 3, 4, 5, 5), values = round(rnorm(5, 5), 2)) # Create a data frame with node ID values # representing the graph nodes (with the `id` # columns), and, a set of numeric values df_nodes <- data.frame( id = 1:5, values = round(rnorm(5, 7), 2)) # Join the data frame to the graph's internal # edge data frame (edf) graph <- graph \%>\% join_edge_attrs(df_edges) \%>\% join_node_attrs(df_nodes) get_node_df(graph) #> id type label values #> 1 1 a asd 8.58 #> 2 2 a iekd 7.22 #> 3 3 b idj 5.95 #> 4 4 b edl 6.71 #> 5 5 b ohd 7.48 get_edge_df(graph) #> id from to rel values #> 1 1 1 2 <NA> 6.00 #> 2 2 1 3 A 6.11 #> 3 3 2 4 B 4.72 #> 4 4 2 5 C 6.02 #> 5 5 3 5 D 5.05 # Perform a simple traversal from the # edge `1`->`3` to the attached node # in the direction of the edge; here, no # conditions are placed on the nodes # traversed to graph \%>\% select_edges(from = 1, to = 3) \%>\% trav_out_node() \%>\% get_selection() #> [1] 1 # Traverse from edges `2`->`5` and # `3`->`5` to the attached node along # the direction of the edge; here, the # traversals lead to different nodes graph \%>\% select_edges(from = 2, to = 5) \%>\% select_edges(from = 3, to = 5) \%>\% trav_out_node() \%>\% get_selection() #> [1] 2 3 # Traverse from the edge `1`->`3` # to the attached node where the edge # is outgoing, this time filtering # numeric values greater than `7.0` for # the `values` node attribute graph \%>\% select_edges(from = 1, to = 3) \%>\% trav_out_node( conditions = "values > 7.0") \%>\% get_selection() #> [1] 1 # Traverse from the edge `1`->`3` # to the attached node where the edge # is outgoing, this time filtering # numeric values less than `7.0` for # the `values` node attribute (the # condition is not met so the original # selection of edge `1`->`3` remains) graph \%>\% select_edges(from = 1, to = 3) \%>\% trav_out_node( conditions = "values < 7.0") \%>\% get_selection() #> [1] 2 # Traverse from the edge `1`->`2` to # the node `2` using multiple conditions # with a single-length vector (here, using # a `|` to create a set of `OR` conditions) graph \%>\% select_edges(from = 1, to = 2) \%>\% trav_out_node( conditions = "grepl('.*d$', label) | values < 6.0") \%>\% get_selection() #> [1] 1 # Create another simple graph to demonstrate # copying of edge attribute values to traversed # nodes graph <- create_graph() \%>\% add_node() \%>\% select_nodes() \%>\% add_n_nodes_ws(2, "from") \%>\% clear_selection() \%>\% select_nodes_by_id(2) \%>\% set_node_attrs_ws("value", 8) \%>\% clear_selection() \%>\% select_edges_by_edge_id(1) \%>\% set_edge_attrs_ws("value", 5) \%>\% clear_selection() \%>\% select_edges_by_edge_id(2) \%>\% set_edge_attrs_ws("value", 5) \%>\% clear_selection() \%>\% select_edges() # Show the graph's internal edge data frame graph \%>\% get_edge_df() #> id from to rel value #> 1 1 1 2 <NA> 5 #> 2 2 1 3 <NA> 5 # Show the graph's internal node data frame graph \%>\% get_node_df() #> id type label value #> 1 1 <NA> <NA> NA #> 2 2 <NA> <NA> 8 #> 3 3 <NA> <NA> NA # Perform a traversal from the edges to # the central node (`1`) while also applying # the edge attribute `value` to the node (in # this case summing the `value` of 5 from # both edges before adding as a node attribute) graph <- graph \%>\% trav_out_node( copy_attrs_from = "value", agg = "sum") # Show the graph's internal node data frame # after this change graph \%>\% get_node_df() #> id type label value #> 1 1 <NA> <NA> 10 #> 2 2 <NA> <NA> 8 #> 3 3 <NA> <NA> NA }
/man/trav_out_node.Rd
no_license
KID4978/DiagrammeR
R
false
true
5,713
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/trav_out_node.R \name{trav_out_node} \alias{trav_out_node} \title{Traverse from one or more selected edges onto adjacent, outward nodes} \usage{ trav_out_node(graph, conditions = NULL, copy_attrs_from = NULL, agg = "sum") } \arguments{ \item{graph}{a graph object of class \code{dgr_graph}.} \item{conditions}{an option to use filtering conditions for the traversal.} \item{copy_attrs_from}{providing an edge attribute name will copy those edge attribute values to the traversed nodes. If the edge attribute already exists, the values will be merged to the traversed nodes; otherwise, a new node attribute will be created.} \item{agg}{if an edge attribute is provided to \code{copy_attrs_from}, then an aggregation function is required since there may be cases where multiple edge attribute values will be passed onto the traversed node(s). To pass only a single value, the following aggregation functions can be used: \code{sum}, \code{min}, \code{max}, \code{mean}, or \code{median}.} } \value{ a graph object of class \code{dgr_graph}. } \description{ From a graph object of class \code{dgr_graph} with an active selection of edges move opposite to the edge direction to connected nodes, replacing the current edge selection with the selection with those nodes traversed to. An optional filter by node attribute can limit the set of nodes traversed to. } \examples{ # Set a seed set.seed(23) # Create a simple graph graph <- create_graph() \%>\% add_n_nodes( 2, type = "a", label = c("asd", "iekd")) \%>\% add_n_nodes( 3, type = "b", label = c("idj", "edl", "ohd")) \%>\% add_edges_w_string( "1->2 1->3 2->4 2->5 3->5", rel = c(NA, "A", "B", "C", "D")) # Create a data frame with node ID values # representing the graph edges (with `from` # and `to` columns), and, a set of numeric values df_edges <- data.frame( from = c(1, 1, 2, 2, 3), to = c(2, 3, 4, 5, 5), values = round(rnorm(5, 5), 2)) # Create a data frame with node ID values # representing the graph nodes (with the `id` # columns), and, a set of numeric values df_nodes <- data.frame( id = 1:5, values = round(rnorm(5, 7), 2)) # Join the data frame to the graph's internal # edge data frame (edf) graph <- graph \%>\% join_edge_attrs(df_edges) \%>\% join_node_attrs(df_nodes) get_node_df(graph) #> id type label values #> 1 1 a asd 8.58 #> 2 2 a iekd 7.22 #> 3 3 b idj 5.95 #> 4 4 b edl 6.71 #> 5 5 b ohd 7.48 get_edge_df(graph) #> id from to rel values #> 1 1 1 2 <NA> 6.00 #> 2 2 1 3 A 6.11 #> 3 3 2 4 B 4.72 #> 4 4 2 5 C 6.02 #> 5 5 3 5 D 5.05 # Perform a simple traversal from the # edge `1`->`3` to the attached node # in the direction of the edge; here, no # conditions are placed on the nodes # traversed to graph \%>\% select_edges(from = 1, to = 3) \%>\% trav_out_node() \%>\% get_selection() #> [1] 1 # Traverse from edges `2`->`5` and # `3`->`5` to the attached node along # the direction of the edge; here, the # traversals lead to different nodes graph \%>\% select_edges(from = 2, to = 5) \%>\% select_edges(from = 3, to = 5) \%>\% trav_out_node() \%>\% get_selection() #> [1] 2 3 # Traverse from the edge `1`->`3` # to the attached node where the edge # is outgoing, this time filtering # numeric values greater than `7.0` for # the `values` node attribute graph \%>\% select_edges(from = 1, to = 3) \%>\% trav_out_node( conditions = "values > 7.0") \%>\% get_selection() #> [1] 1 # Traverse from the edge `1`->`3` # to the attached node where the edge # is outgoing, this time filtering # numeric values less than `7.0` for # the `values` node attribute (the # condition is not met so the original # selection of edge `1`->`3` remains) graph \%>\% select_edges(from = 1, to = 3) \%>\% trav_out_node( conditions = "values < 7.0") \%>\% get_selection() #> [1] 2 # Traverse from the edge `1`->`2` to # the node `2` using multiple conditions # with a single-length vector (here, using # a `|` to create a set of `OR` conditions) graph \%>\% select_edges(from = 1, to = 2) \%>\% trav_out_node( conditions = "grepl('.*d$', label) | values < 6.0") \%>\% get_selection() #> [1] 1 # Create another simple graph to demonstrate # copying of edge attribute values to traversed # nodes graph <- create_graph() \%>\% add_node() \%>\% select_nodes() \%>\% add_n_nodes_ws(2, "from") \%>\% clear_selection() \%>\% select_nodes_by_id(2) \%>\% set_node_attrs_ws("value", 8) \%>\% clear_selection() \%>\% select_edges_by_edge_id(1) \%>\% set_edge_attrs_ws("value", 5) \%>\% clear_selection() \%>\% select_edges_by_edge_id(2) \%>\% set_edge_attrs_ws("value", 5) \%>\% clear_selection() \%>\% select_edges() # Show the graph's internal edge data frame graph \%>\% get_edge_df() #> id from to rel value #> 1 1 1 2 <NA> 5 #> 2 2 1 3 <NA> 5 # Show the graph's internal node data frame graph \%>\% get_node_df() #> id type label value #> 1 1 <NA> <NA> NA #> 2 2 <NA> <NA> 8 #> 3 3 <NA> <NA> NA # Perform a traversal from the edges to # the central node (`1`) while also applying # the edge attribute `value` to the node (in # this case summing the `value` of 5 from # both edges before adding as a node attribute) graph <- graph \%>\% trav_out_node( copy_attrs_from = "value", agg = "sum") # Show the graph's internal node data frame # after this change graph \%>\% get_node_df() #> id type label value #> 1 1 <NA> <NA> 10 #> 2 2 <NA> <NA> 8 #> 3 3 <NA> <NA> NA }
testlist <- list(a = 3538943L, b = -1L, x = c(370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 385822975L, -1L)) result <- do.call(grattan:::anyOutside,testlist) str(result)
/grattan/inst/testfiles/anyOutside/libFuzzer_anyOutside/anyOutside_valgrind_files/1610056513-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
331
r
testlist <- list(a = 3538943L, b = -1L, x = c(370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 370546198L, 385822975L, -1L)) result <- do.call(grattan:::anyOutside,testlist) str(result)
#PCA_hist function generates the PCA plot for all datapoints with density distribution along PC1 #data = dataframe of gene expression, genes in columns #clus = no. of clusters to be generated #seed = initialization seed to be set #pointsize = size of point on PCA plot #V = Loading scores of genes for principal components PCA_hist <- function(data,pointsize = 0.5, V = NULL, title){ require(factoextra) require(ggpubr) data[!is.finite(as.matrix(data))] <- 0 if(is.null(V)){ pca <- FactoMineR::PCA(data, scale = FALSE, graph = F) df <- as.data.frame(pca$ind$coord[,1:2]) }else{ #Determining coordinates for fixed PC1 loading scores (For control network) data <- as.matrix(data) df <- data %*% V df <- as.data.frame(df)[,1:2] } names(df) <- c("PC1", "PC2") df <- as.data.frame(df[complete.cases(df),]) sp <- ggscatter(df, x = "PC1", y = "PC2", color = "#0073C299", size = pointsize)+ border() sp <- sp + rremove("legend") xplot <- ggdensity(df[,1],xlab="PC1", fill = "black")+ ylim(0,0.5) library(cowplot) p <- print(plot_grid(xplot, sp, ncol = 1, align = "hv", rel_widths = c(2, 1), rel_heights = c(1, 2))) title1 <- ggdraw() + draw_label(paste0(title), fontface='bold') print(plot_grid(title1, p, ncol=1, rel_heights=c(0.1, 1)) ) } #To determine V (PC1 loading scores) df <- read.delim("Datasets/KD/Control.txt") pca <- FactoMineR::PCA(df, graph = F, scale.unit = F) V <- pca$svd$V jpeg("Figures/Fig. 7/S8_Control.jpeg", width = 350, height =350) PCA_hist(df, V = V, title = "Control") dev.off() list <- c("NFIC", "AHR", "JUN", "SMAD3", "KLF4", "TBX3", "NR3C1","MITF","FOS", "SMAD4") for (i in list) { df <- read.delim(paste0("Datasets/KD/",i," KD.txt")) jpeg(paste0("Figures/Fig. 7/S8_",i,"_KD.jpeg"), width = 350, height = 350) PCA_hist(df, V = V, title = paste0(i, " KD")) dev.off() }
/Figures/Fig. 7/Code/FigS8_PCA_hist.R
no_license
csbBSSE/Melanoma
R
false
false
2,020
r
#PCA_hist function generates the PCA plot for all datapoints with density distribution along PC1 #data = dataframe of gene expression, genes in columns #clus = no. of clusters to be generated #seed = initialization seed to be set #pointsize = size of point on PCA plot #V = Loading scores of genes for principal components PCA_hist <- function(data,pointsize = 0.5, V = NULL, title){ require(factoextra) require(ggpubr) data[!is.finite(as.matrix(data))] <- 0 if(is.null(V)){ pca <- FactoMineR::PCA(data, scale = FALSE, graph = F) df <- as.data.frame(pca$ind$coord[,1:2]) }else{ #Determining coordinates for fixed PC1 loading scores (For control network) data <- as.matrix(data) df <- data %*% V df <- as.data.frame(df)[,1:2] } names(df) <- c("PC1", "PC2") df <- as.data.frame(df[complete.cases(df),]) sp <- ggscatter(df, x = "PC1", y = "PC2", color = "#0073C299", size = pointsize)+ border() sp <- sp + rremove("legend") xplot <- ggdensity(df[,1],xlab="PC1", fill = "black")+ ylim(0,0.5) library(cowplot) p <- print(plot_grid(xplot, sp, ncol = 1, align = "hv", rel_widths = c(2, 1), rel_heights = c(1, 2))) title1 <- ggdraw() + draw_label(paste0(title), fontface='bold') print(plot_grid(title1, p, ncol=1, rel_heights=c(0.1, 1)) ) } #To determine V (PC1 loading scores) df <- read.delim("Datasets/KD/Control.txt") pca <- FactoMineR::PCA(df, graph = F, scale.unit = F) V <- pca$svd$V jpeg("Figures/Fig. 7/S8_Control.jpeg", width = 350, height =350) PCA_hist(df, V = V, title = "Control") dev.off() list <- c("NFIC", "AHR", "JUN", "SMAD3", "KLF4", "TBX3", "NR3C1","MITF","FOS", "SMAD4") for (i in list) { df <- read.delim(paste0("Datasets/KD/",i," KD.txt")) jpeg(paste0("Figures/Fig. 7/S8_",i,"_KD.jpeg"), width = 350, height = 350) PCA_hist(df, V = V, title = paste0(i, " KD")) dev.off() }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utility_functions.R \name{dense2sparse} \alias{dense2sparse} \title{Converts matrix given in dense format to sparse format data frame.} \usage{ dense2sparse(mtx, add.diagonal = TRUE, name = NULL) } \arguments{ \item{mtx}{matrix in dense format} \item{add.diagonal}{logical, if true an additional column indicating diagonal of each cell will be appended to resulting data frame} \item{name}{character, additional argument, if specified column with name will be appended to resulting data frame} } \value{ data.frame with columns \code{c("i","j","val")} and optionally \code{c("diagonal","name")} columns; every row of resulting dataframe corresponds to cell in given dense matrix with i-th row, j-th column and value val } \description{ This function only keeps non-zero cells. In case given dense matix is symmetric \code{dense2sparse} will return upper triangular part of the matrix (i.e. where rows <= columns) } \examples{ dense2sparse(matrix(1:24, ncol = 3)) dense2sparse(matrix(1:24, ncol = 3), name = "some.matrix") dense2sparse(matrix(1:24, ncol = 3), add.diagonal = FALSE) # symmetric matrix mtx.sym <- matrix(1:25, ncol = 5) mtx.sym <- mtx.sym + t(mtx.sym) dense2sparse(matrix(mtx.sym)) }
/man/dense2sparse.Rd
permissive
rz6/DIADEM
R
false
true
1,279
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utility_functions.R \name{dense2sparse} \alias{dense2sparse} \title{Converts matrix given in dense format to sparse format data frame.} \usage{ dense2sparse(mtx, add.diagonal = TRUE, name = NULL) } \arguments{ \item{mtx}{matrix in dense format} \item{add.diagonal}{logical, if true an additional column indicating diagonal of each cell will be appended to resulting data frame} \item{name}{character, additional argument, if specified column with name will be appended to resulting data frame} } \value{ data.frame with columns \code{c("i","j","val")} and optionally \code{c("diagonal","name")} columns; every row of resulting dataframe corresponds to cell in given dense matrix with i-th row, j-th column and value val } \description{ This function only keeps non-zero cells. In case given dense matix is symmetric \code{dense2sparse} will return upper triangular part of the matrix (i.e. where rows <= columns) } \examples{ dense2sparse(matrix(1:24, ncol = 3)) dense2sparse(matrix(1:24, ncol = 3), name = "some.matrix") dense2sparse(matrix(1:24, ncol = 3), add.diagonal = FALSE) # symmetric matrix mtx.sym <- matrix(1:25, ncol = 5) mtx.sym <- mtx.sym + t(mtx.sym) dense2sparse(matrix(mtx.sym)) }
### run_ssm_standard_filters.R #################################################################### # Run the standard simple somatic filters on MuTect2 output. Output will be separate for SNVs and # indels. ### HISTORY ####################################################################################### # Version Date Developer Comments # 0.01 2017-04-10 rdeborja initial development # 0.02 2017-04-13 rdeborja removed MT from dataframe due to # clip filtering issues ### NOTES ######################################################################################### # ### PREAMBLE ###################################################################################### library('getopt') usage <- function() { usage.text <- '\nUsage: run_ssm_standard_filters.R --path </path/to/directory/containing/files> --sample <sample name> --source <WGS|WXS|CPANEL>\n\n' return(usage.text) } params = matrix( c( 'path', 'p', 1, 'character', 'sample', 's', 1, 'character', 'source', 'c', 1, 'character' ), ncol = 4, byrow = TRUE ) opt = getopt(params) # verify arguments if (is.null(opt$path)) { stop(usage()) } output <- paste(sep='.', paste(sep='_', opt$sample, 'annotated'), 'rda') snv_filtered <- paste(sep='.', paste(sep='_', opt$sample, 'annotated_filtered_snv'), 'rda') indel_filtered <- paste(sep='.', paste(sep='_', opt$sample, 'annotated_filtered_indel'), 'rda') ### LIBRARIES ##################################################################################### library(ShlienLab.Core.SSM) ### FUNCTIONS ##################################################################################### ### GET DATA ###################################################################################### data <- get.mutect2.data(path=opt$path) ### PROCESS DATA ################################################################################## # add additional annotations to the dataframe data <- ShlienLab.Core.SSM::annotate.mutect2.data(data=data) # currently there is a bug in downstream filtering causing a pre-filter step to remove the # mitochondrial DNA from the output data <- data %>% filter(annovar_chr != 'MT') data <- data %>% filter(annovar_chr != 'M') # separately filter the snv and indel data data.snv.filtered <- ShlienLab.Core.SSM::filter_snv(data=data, source='WGS') data.indel.filtered <- ShlienLab.Core.SSM::filter_indel(data=data, source='WGS') # save the dataframes save(data.snv.filtered, file=snv_filtered) save(data.indel.filtered, file=indel_filtered) ### ANALYSIS ###################################################################################### ### PLOTTING ###################################################################################### ### SESSION INFORMATION ########################################################################### sessionInfo()
/exec/run_ssm_standard_filters.R
no_license
rdeborja/ShlienLab.Core.SSM
R
false
false
3,023
r
### run_ssm_standard_filters.R #################################################################### # Run the standard simple somatic filters on MuTect2 output. Output will be separate for SNVs and # indels. ### HISTORY ####################################################################################### # Version Date Developer Comments # 0.01 2017-04-10 rdeborja initial development # 0.02 2017-04-13 rdeborja removed MT from dataframe due to # clip filtering issues ### NOTES ######################################################################################### # ### PREAMBLE ###################################################################################### library('getopt') usage <- function() { usage.text <- '\nUsage: run_ssm_standard_filters.R --path </path/to/directory/containing/files> --sample <sample name> --source <WGS|WXS|CPANEL>\n\n' return(usage.text) } params = matrix( c( 'path', 'p', 1, 'character', 'sample', 's', 1, 'character', 'source', 'c', 1, 'character' ), ncol = 4, byrow = TRUE ) opt = getopt(params) # verify arguments if (is.null(opt$path)) { stop(usage()) } output <- paste(sep='.', paste(sep='_', opt$sample, 'annotated'), 'rda') snv_filtered <- paste(sep='.', paste(sep='_', opt$sample, 'annotated_filtered_snv'), 'rda') indel_filtered <- paste(sep='.', paste(sep='_', opt$sample, 'annotated_filtered_indel'), 'rda') ### LIBRARIES ##################################################################################### library(ShlienLab.Core.SSM) ### FUNCTIONS ##################################################################################### ### GET DATA ###################################################################################### data <- get.mutect2.data(path=opt$path) ### PROCESS DATA ################################################################################## # add additional annotations to the dataframe data <- ShlienLab.Core.SSM::annotate.mutect2.data(data=data) # currently there is a bug in downstream filtering causing a pre-filter step to remove the # mitochondrial DNA from the output data <- data %>% filter(annovar_chr != 'MT') data <- data %>% filter(annovar_chr != 'M') # separately filter the snv and indel data data.snv.filtered <- ShlienLab.Core.SSM::filter_snv(data=data, source='WGS') data.indel.filtered <- ShlienLab.Core.SSM::filter_indel(data=data, source='WGS') # save the dataframes save(data.snv.filtered, file=snv_filtered) save(data.indel.filtered, file=indel_filtered) ### ANALYSIS ###################################################################################### ### PLOTTING ###################################################################################### ### SESSION INFORMATION ########################################################################### sessionInfo()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{print.netrankr_interval} \alias{print.netrankr_interval} \title{Print netrankr_interval object to terminal} \usage{ \method{print}{netrankr_interval}(x, ...) } \arguments{ \item{x}{A netrankr_interval object} \item{...}{additional arguments to print} } \description{ Prints the result of an object obtained from \link{rank_intervals} to terminal } \author{ David Schoch }
/man/print.netrankr_interval.Rd
permissive
schochastics/netrankr
R
false
true
465
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{print.netrankr_interval} \alias{print.netrankr_interval} \title{Print netrankr_interval object to terminal} \usage{ \method{print}{netrankr_interval}(x, ...) } \arguments{ \item{x}{A netrankr_interval object} \item{...}{additional arguments to print} } \description{ Prints the result of an object obtained from \link{rank_intervals} to terminal } \author{ David Schoch }
EBS <- function(object, model=1, block.length=NULL, alpha.boot=0.05, field.sig=0.05, bootR=1000, ntrials=1000, verbose=FALSE) { a <- attributes(object) out <- list() attributes(out) <- a X <- object[[1]] Xhat <- object[[2]] if(!is.array(Xhat)) { if(!is.numeric(model)) { nf <- a$nforecast dn <- a$data.name if(length(dn) == nf + 2) mod.names <- dn[-(1:2)] else mod.names <- dn[-1] model <- (1:nf)[dn == model] if(is.na(model)) stop("datagrabber: invalid model argument.") } Xhat <- Xhat[[model]] } # end of if 'Xhat' is not an array (i.e., if more than one model in object) stmts. X <- t(apply(X, 3, c)) Xhat <- t(apply(Xhat, 3, c)) loc <- a$loc if(!is.null(a$subset)) { id <- a$subset X <- X[,id] Xhat <- Xhat[,id] loc <- loc[id,] } res <- spatbiasFS(X=X, Y=Xhat, loc=a$loc, block.length=block.length, alpha.boot=alpha.boot, field.sig=field.sig, bootR=bootR, ntrials=ntrials, verbose=verbose) out$block.boot.results <- res$block.boot.results out$sig.results <- res$sig.results sig.values <- c(res$field.significance, res$alpha.boot, bootR, ntrials) names(sig.values) <- c("field sig.", "alpha boot", "bootstrap replicates", "number of trials") attr(out, "arguments") <- sig.values attr(out, "which.model") <- model class(out) <- "EBS" return(out) } # end of 'EBS' function. LocSig <- function(Z, numrep=1000, block.length=NULL, bootfun="mean", alpha=0.05, bca=FALSE, ...) { if(bootfun=="mean") bootfun <- function(data) return(colMeans(data, na.rm=TRUE)) else if(is.character(bootfun)) bootfun <- get(bootfun) zdim <- dim(Z) n <- zdim[1] m <- zdim[2] out <- data.frame(Lower = numeric(m), Estimate = numeric(m), Upper = numeric(m)) if(is.null(block.length)) block.length <- floor(sqrt(n)) if(block.length==1) booted <- boot(Z, bootfun, R=numrep, ...) else booted <- tsboot(Z, bootfun, l=block.length, R=numrep, sim="fixed", ...) out$Estimate <- booted$t0 if((block.length==1) & bca) { for(i in 1:m) { tmp <- boot.ci( booted, conf=1-alpha, type="bca", index=i) out$Lower[i] <- tmp$bca[,4] out$Upper[i] <- tmp$bca[,5] } # end of for 'i' loop. } else { if(bca) warning("LocSig: You chose to use the BCa method, but block.length != 1. Using percentile method with circular block bootstrap instead.") for(i in 1:m) { tmp <- boot.ci( booted, conf=1-alpha, type="perc", index=i) out$Lower[i] <- tmp$perc[,4] out$Upper[i] <- tmp$perc[,5] } # end of for 'i' loop. } # end of if else do "BCa" (IID bootstrap only) or percentile confidence limits. class(out) <- "LocSig" return(out) } # end of 'LocSig' function. MCdof <- function(x, ntrials=5000, field.sig=0.05, zfun="rnorm", zfun.args=NULL, which.test=c("t", "Z", "cor.test"), verbose=FALSE, ...) { if(verbose) begin.time <- Sys.time() if(length(which.test)>1) which.test <- "t" xdim <- dim(x) tlen <- xdim[1] B.dof.test <- numeric(ntrials) if(which.test=="cor.test") cortester <- function(x,y,...) return(cor.test(x=x,y=y,...)$p.value) if(verbose) cat("\n", "Looping through ", ntrials, " times to simulate data and take correlations. Enjoy!\n") for(i in 1:ntrials) { if(verbose & (i < 100 | i%%100==0)) cat(i, " ") z <- do.call(zfun, args=c(list(n=tlen), zfun.args)) if(which.test=="cor.test") tmp <- apply(x, 2, cortester, y=z, ...) else { cor.value <- abs(cor(x, z, use = "pairwise.complete.obs")) if(which.test=="t") tmp <- sig.cor.t(cor.value, len=tlen, ...) else if(which.test=="Z") tmp <- sig.cor.Z(cor.value, len=tlen, ...) } B.dof.test[i] <- mean(field.sig > tmp, na.rm = TRUE) } # end of for 'i' loop. if(verbose) print(Sys.time() - begin.time) return(list(MCprops=B.dof.test, minsigcov=quantile(B.dof.test, probs=1-field.sig, na.rm=TRUE))) } # end of 'MCdof' function. sig.cor.t <- function(r, len = 40, ...) { # # A function to determine if a correlation is significantly different from x # # Input - # r - the (unsigned) correlation coefficient # len - the length of the vectors used to generate the correlation (default = 40) # Alpha - the significance level (default = 0.05) # # Output - # palpha.cor - the p-level of the correlation # # v1.0 # KLE 2/3/2009 # Ported to R -- 03/30/2011 # t <- abs(r) * sqrt((len - 2)/(1 - r^2)) palpha.cor <- 1 - pt(t, len - 2) return(palpha.cor) } # end of 'sig.cor.t' function. sig.cor.Z <- function(r, len = 40, H0 = 0) { # # A function to find the significance of a correlation from H0 using Fisher's Z transform. # # Input - # r - the correlation # len - the length of the crrelated vectors # Ho0- the null hypothesis correlation default = 0 # # Output - # palpha.cor - the p-value of the correlation. # # KLE 02/20/2009 # Ported to R -- 03/30/2011 # W <- fisherz(abs(r)) stderr <- 1/sqrt(len - 3) zscore <- (W - H0)/stderr palpha.cor <- 1 - pnorm(zscore) return(palpha.cor) } # end of 'sig.cor.Z' function. fisherz <- function(r) { # # The sampling distribution of Pearson's r is not normally distributed. Fisher # developed a transformation now called "Fisher's z' transformation" that converts # Pearson's r's to the normally distributed variable z'. # # A function to perfoem Fisher's Z transformation on a correlation value, allowing # a t-test for significant correlation. # # Input - # r - the correlation # # Output - # W - the transformed corelation # # v1.0 # KLE 2 Feb 2009 # Ported to R -- 03/30/2011 # W <- 0.5 * (log((1 + r)/(1 - r))) return(W) } plot.LocSig <- function(x, loc=NULL, nx=NULL, ny=NULL, ...){ n <- dim(x)[1] if(is.null(loc)) { if(is.null(nx) | is.null(ny)) stop("plot.LocSig: must specify either loc or both nx and ny") loc <- cbind(rep(1:nx, ny), rep(1:ny, each=nx)) } mean.i <- as.image(x$Estimate, x=loc) thk.i <- as.image((x$Upper - x$Lower), x=loc) output <- list(mean.i = mean.i, thk.i = thk.i) par(mfrow=c(1,2)) image.plot(mean.i, main="Mean of Estimate", ...) image.plot(thk.i, main="CI range of Estimate", ...) invisible(output) } plot.EBS <- function(x, ..., set.pw=FALSE, col, horizontal) { if(missing(col)) col <- c("gray", tim.colors(64)) if(missing(horizontal)) horizontal <- TRUE if(set.pw) par(mfrow=c(1,2), oma=c(0,0,2,0)) else par(oma=c(0,0,2,0)) Zest <- x$block.boot.results$Estimate ZciR <- x$block.boot.results$Upper - x$block.boot.results$Lower a <- attributes(x) loc.byrow <- a$loc.byrow xd <- a$xdim if(is.null(a$subset)) { if(!is.matrix(Zest)) Zest <- matrix(Zest, xd[1], xd[2]) if(!is.matrix(ZciR)) ZciR <- matrix(ZciR, xd[1], xd[2]) } if(a$projection && is.null(a$subset)) { xloc <- matrix(a$loc[,1], xd[1], xd[2], byrow=loc.byrow) yloc <- matrix(a$loc[,2], xd[1], xd[2], byrow=loc.byrow) } if(!is.null(a$subset)) { if(is.logical(a$subset)) Ns <- sum(a$subset, na.rm=TRUE) else Ns <- length(a$subset) Zest <- as.image(Zest, nx=ceiling(Ns/2), ny=ceiling(Ns/2), x=a$loc[a$subset,], na.rm=TRUE) ZciR <- as.image(ZciR, nx=ceiling(Ns/2), ny=ceiling(Ns/2), x=a$loc[a$subset,], na.rm=TRUE) } else if(!a$reg.grid) { Zest <- as.image(Zest, nx=xd[1], ny=xd[2], x=a$loc, na.rm=TRUE) ZciR <- as.image(ZciR, nx=xd[1], ny=xd[2], x=a$loc, na.rm=TRUE) } if(a$map) { ax <- list(x=pretty(round(a$loc[,1], digits=2)), y=pretty(round(a$loc[,2], digits=2))) if(is.null(a$subset)) r <- apply(a$loc, 2, range, finite=TRUE) else r <- apply(a$loc[a$subset,], 2, range, finite=TRUE) map(xlim=r[,1], ylim=r[,2], type="n") axis(1, at=ax$x, labels=ax$x) axis(2, at=ax$y, labels=ax$y) if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, Zest, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(Zest, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else image.plot(Zest, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) map(add=TRUE, lwd=1.5) map(database="state", add=TRUE) map(xlim=r[,1], ylim=r[,2], type="n") axis(1, at=ax$x, labels=ax$x) axis(2, at=ax$y, labels=ax$y) if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, ZciR, add=TRUE, col=col, main="CI Range", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(ZciR, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else image.plot(ZciR, add=TRUE, col=col, main="CI Range", horizontal=horizontal, ...) map(add=TRUE, lwd=1.5) map(database="state", add=TRUE) } else { if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, Zest, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(Zest, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else image.plot(Zest, col=col, main="Mean of Estimate", horizontal=horizontal, ...) if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, ZciR, col=col, main="CI Range", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(ZciR, col=col, main="Mean of Estimate", ...) else image.plot(ZciR, col=col, main="CI Range", horizontal=horizontal, ...) } # end of if else 'map' stmts. if(length(a$data.name) == a$nforecast + 2) { msg <- paste(a$data.name[1], ": ", a$data.name[2], " vs ", a$data.name[a$which.model+2], sep="") } else msg <- paste(a$data.name[2], " vs ", a$data.name[a$which.model+1], sep="") if(a$field.type != "" && a$units != "") msg <- paste(msg, "\n", a$field.type, " (", a$units, ")", sep="") else if(a$field.type != "") msg <- paste(msg, a$field.type, sep="\n") else if(a$units != "") msg <- paste(msg, "\n(", a$units, ")", sep="") mtext(msg, line=0.05, outer=TRUE) invisible() } # end of 'plot.EBS' function. inside <- function(DF) { # # A function to determine if the mean error at a data point is # inside the confidence limits. # # Input # DF - data frame containing mean error values and upper and lower # confidence limits # # Output # logical T if outside, F if inside. # result <- !is.na(CI.fun(DF$Upper - DF$Lower, DF$Estimate)) return(result) } # end of 'inside' function. CI.fun <- function(CI.field, est.field, replacement = NA) { test <- ifelse((0.5 * CI.field < abs(est.field)), est.field, replacement) return(test) } # end of 'CI.fun' function. sig.coverage <- function(DF) { tmp <- inside(DF) out <- sum(tmp,na.rm=TRUE)/(length(tmp[!is.na(tmp)])) - sum(is.na(DF$Estimate)) return(out) } # end of 'sig.coverage' function. is.sig <- function(X, blockboot.results.df, n = 3000, fld.sig = 0.05, verbose=FALSE) { # # Input - # X - matrix of errors at gridpoints. n gridpoints by m days # blockboot.results.df - dataframe of errors and CI at each # gridpoint. # n - number of Monte Carlo trials. # field.sig - significnace alpha for field significance. # # Output - # List # name - Name of the data beig tested # results - The minimum amount of areal coverage needed for # significance at # the given fld.sig # actual - The actual coverage of sigificant gridpoint # results. # issig - Logical variable: T for significant results, F for # non-significant results. # # KLE 01/2005 # # Remove missing rows # sig.results <- MCdof(X, ntrials = n, field.sig = fld.sig, verbose=verbose)$minsigcov actual.coverage <- sig.coverage(blockboot.results.df) sig <- (actual.coverage > sig.results) output <- list(name = as.character(deparse(substitute(X))), required = as.numeric(sig.results), actual = as.numeric( actual.coverage), issig = as.logical(sig)) return(output) } spatbiasFS <- function(X, Y, loc=NULL, block.length=NULL, alpha.boot=0.05, field.sig=0.05, bootR=1000, ntrials=1000, verbose=FALSE) { out <- list() if(!is.null(loc)) { data.name <- c(as.character(substitute(X)),as.character(substitute(Y)),as.character(substitute(loc))) names(data.name) <- c("verification","forecast","locations") } else { data.name <- c(as.character(substitute(X)),as.character(substitute(Y))) names(data.name) <- c("verification","forecast") } out$data.name <- data.name errfield <- Y - X hold <- LocSig(Z=errfield, numrep=bootR, block.length=block.length, alpha=alpha.boot) res <- is.sig(errfield, hold, n=ntrials, fld.sig=field.sig, verbose=verbose) out$block.boot.results <- hold out$sig.results <- res out$field.significance <- field.sig out$alpha.boot <- alpha.boot out$bootR <- bootR out$ntrials <- ntrials class(out) <- "spatbiasFS" return(out) } # end of 'spatbiasFS' function. summary.spatbiasFS <- function(object, ...) { cat("\n") msg <- paste("Results for ", object$data.name[2], " compared against ", object$data.name[1], sep="") print(msg) cat("\n", "\n") cat("Field significance level: ", object$field.significance, "\n") cat("Observed coverage of significant difference: ", object$sig.results$actual, "\n") cat("Required coverage for field significance: ", object$sig.results$required, "\n") invisible() } # end of 'summary.spatbiasFS' function. plot.spatbiasFS <- function(x, ...) { # TO DO: Try to make a better plot (without using as.image). msg <- paste("Mean Error: ", x$data.name[2], " vs ", x$data.name[1], sep="") # X <- get(x$data.name[1]) # Y <- get(x$data.name[2]) if(length(x$data.name)==3) loc <- get(x$data.name[3]) else stop("plot.spatbiasFS: No entry loc. Must supply location information.") est.i <- as.image(x$block.boot.results$Estimate, x=loc) CIrange <- as.image(x$block.boot.results$Upper - x$block.boot.results$Lower, x=loc) par(mfrow=c(1,2)) image.plot(est.i, col=tim.colors(64), axes=FALSE, main=msg) # map(add=TRUE) # map(add=TRUE,database="state") image.plot(CIrange, col=tim.colors(64), axes=FALSE, xlab=paste("Req. Coverage: ", round(x$sig.results$required,digits=2), " vs Obs. coverage: ", round(x$sig.results$actual,digits=2), sep=""), main=paste((1-x$alpha.boot)*100, "% CI range", sep="")) invisible() } # end of 'plot.spatbiasFS' function.
/SpatialVx/R/SigFuns.R
no_license
ingted/R-Examples
R
false
false
14,453
r
EBS <- function(object, model=1, block.length=NULL, alpha.boot=0.05, field.sig=0.05, bootR=1000, ntrials=1000, verbose=FALSE) { a <- attributes(object) out <- list() attributes(out) <- a X <- object[[1]] Xhat <- object[[2]] if(!is.array(Xhat)) { if(!is.numeric(model)) { nf <- a$nforecast dn <- a$data.name if(length(dn) == nf + 2) mod.names <- dn[-(1:2)] else mod.names <- dn[-1] model <- (1:nf)[dn == model] if(is.na(model)) stop("datagrabber: invalid model argument.") } Xhat <- Xhat[[model]] } # end of if 'Xhat' is not an array (i.e., if more than one model in object) stmts. X <- t(apply(X, 3, c)) Xhat <- t(apply(Xhat, 3, c)) loc <- a$loc if(!is.null(a$subset)) { id <- a$subset X <- X[,id] Xhat <- Xhat[,id] loc <- loc[id,] } res <- spatbiasFS(X=X, Y=Xhat, loc=a$loc, block.length=block.length, alpha.boot=alpha.boot, field.sig=field.sig, bootR=bootR, ntrials=ntrials, verbose=verbose) out$block.boot.results <- res$block.boot.results out$sig.results <- res$sig.results sig.values <- c(res$field.significance, res$alpha.boot, bootR, ntrials) names(sig.values) <- c("field sig.", "alpha boot", "bootstrap replicates", "number of trials") attr(out, "arguments") <- sig.values attr(out, "which.model") <- model class(out) <- "EBS" return(out) } # end of 'EBS' function. LocSig <- function(Z, numrep=1000, block.length=NULL, bootfun="mean", alpha=0.05, bca=FALSE, ...) { if(bootfun=="mean") bootfun <- function(data) return(colMeans(data, na.rm=TRUE)) else if(is.character(bootfun)) bootfun <- get(bootfun) zdim <- dim(Z) n <- zdim[1] m <- zdim[2] out <- data.frame(Lower = numeric(m), Estimate = numeric(m), Upper = numeric(m)) if(is.null(block.length)) block.length <- floor(sqrt(n)) if(block.length==1) booted <- boot(Z, bootfun, R=numrep, ...) else booted <- tsboot(Z, bootfun, l=block.length, R=numrep, sim="fixed", ...) out$Estimate <- booted$t0 if((block.length==1) & bca) { for(i in 1:m) { tmp <- boot.ci( booted, conf=1-alpha, type="bca", index=i) out$Lower[i] <- tmp$bca[,4] out$Upper[i] <- tmp$bca[,5] } # end of for 'i' loop. } else { if(bca) warning("LocSig: You chose to use the BCa method, but block.length != 1. Using percentile method with circular block bootstrap instead.") for(i in 1:m) { tmp <- boot.ci( booted, conf=1-alpha, type="perc", index=i) out$Lower[i] <- tmp$perc[,4] out$Upper[i] <- tmp$perc[,5] } # end of for 'i' loop. } # end of if else do "BCa" (IID bootstrap only) or percentile confidence limits. class(out) <- "LocSig" return(out) } # end of 'LocSig' function. MCdof <- function(x, ntrials=5000, field.sig=0.05, zfun="rnorm", zfun.args=NULL, which.test=c("t", "Z", "cor.test"), verbose=FALSE, ...) { if(verbose) begin.time <- Sys.time() if(length(which.test)>1) which.test <- "t" xdim <- dim(x) tlen <- xdim[1] B.dof.test <- numeric(ntrials) if(which.test=="cor.test") cortester <- function(x,y,...) return(cor.test(x=x,y=y,...)$p.value) if(verbose) cat("\n", "Looping through ", ntrials, " times to simulate data and take correlations. Enjoy!\n") for(i in 1:ntrials) { if(verbose & (i < 100 | i%%100==0)) cat(i, " ") z <- do.call(zfun, args=c(list(n=tlen), zfun.args)) if(which.test=="cor.test") tmp <- apply(x, 2, cortester, y=z, ...) else { cor.value <- abs(cor(x, z, use = "pairwise.complete.obs")) if(which.test=="t") tmp <- sig.cor.t(cor.value, len=tlen, ...) else if(which.test=="Z") tmp <- sig.cor.Z(cor.value, len=tlen, ...) } B.dof.test[i] <- mean(field.sig > tmp, na.rm = TRUE) } # end of for 'i' loop. if(verbose) print(Sys.time() - begin.time) return(list(MCprops=B.dof.test, minsigcov=quantile(B.dof.test, probs=1-field.sig, na.rm=TRUE))) } # end of 'MCdof' function. sig.cor.t <- function(r, len = 40, ...) { # # A function to determine if a correlation is significantly different from x # # Input - # r - the (unsigned) correlation coefficient # len - the length of the vectors used to generate the correlation (default = 40) # Alpha - the significance level (default = 0.05) # # Output - # palpha.cor - the p-level of the correlation # # v1.0 # KLE 2/3/2009 # Ported to R -- 03/30/2011 # t <- abs(r) * sqrt((len - 2)/(1 - r^2)) palpha.cor <- 1 - pt(t, len - 2) return(palpha.cor) } # end of 'sig.cor.t' function. sig.cor.Z <- function(r, len = 40, H0 = 0) { # # A function to find the significance of a correlation from H0 using Fisher's Z transform. # # Input - # r - the correlation # len - the length of the crrelated vectors # Ho0- the null hypothesis correlation default = 0 # # Output - # palpha.cor - the p-value of the correlation. # # KLE 02/20/2009 # Ported to R -- 03/30/2011 # W <- fisherz(abs(r)) stderr <- 1/sqrt(len - 3) zscore <- (W - H0)/stderr palpha.cor <- 1 - pnorm(zscore) return(palpha.cor) } # end of 'sig.cor.Z' function. fisherz <- function(r) { # # The sampling distribution of Pearson's r is not normally distributed. Fisher # developed a transformation now called "Fisher's z' transformation" that converts # Pearson's r's to the normally distributed variable z'. # # A function to perfoem Fisher's Z transformation on a correlation value, allowing # a t-test for significant correlation. # # Input - # r - the correlation # # Output - # W - the transformed corelation # # v1.0 # KLE 2 Feb 2009 # Ported to R -- 03/30/2011 # W <- 0.5 * (log((1 + r)/(1 - r))) return(W) } plot.LocSig <- function(x, loc=NULL, nx=NULL, ny=NULL, ...){ n <- dim(x)[1] if(is.null(loc)) { if(is.null(nx) | is.null(ny)) stop("plot.LocSig: must specify either loc or both nx and ny") loc <- cbind(rep(1:nx, ny), rep(1:ny, each=nx)) } mean.i <- as.image(x$Estimate, x=loc) thk.i <- as.image((x$Upper - x$Lower), x=loc) output <- list(mean.i = mean.i, thk.i = thk.i) par(mfrow=c(1,2)) image.plot(mean.i, main="Mean of Estimate", ...) image.plot(thk.i, main="CI range of Estimate", ...) invisible(output) } plot.EBS <- function(x, ..., set.pw=FALSE, col, horizontal) { if(missing(col)) col <- c("gray", tim.colors(64)) if(missing(horizontal)) horizontal <- TRUE if(set.pw) par(mfrow=c(1,2), oma=c(0,0,2,0)) else par(oma=c(0,0,2,0)) Zest <- x$block.boot.results$Estimate ZciR <- x$block.boot.results$Upper - x$block.boot.results$Lower a <- attributes(x) loc.byrow <- a$loc.byrow xd <- a$xdim if(is.null(a$subset)) { if(!is.matrix(Zest)) Zest <- matrix(Zest, xd[1], xd[2]) if(!is.matrix(ZciR)) ZciR <- matrix(ZciR, xd[1], xd[2]) } if(a$projection && is.null(a$subset)) { xloc <- matrix(a$loc[,1], xd[1], xd[2], byrow=loc.byrow) yloc <- matrix(a$loc[,2], xd[1], xd[2], byrow=loc.byrow) } if(!is.null(a$subset)) { if(is.logical(a$subset)) Ns <- sum(a$subset, na.rm=TRUE) else Ns <- length(a$subset) Zest <- as.image(Zest, nx=ceiling(Ns/2), ny=ceiling(Ns/2), x=a$loc[a$subset,], na.rm=TRUE) ZciR <- as.image(ZciR, nx=ceiling(Ns/2), ny=ceiling(Ns/2), x=a$loc[a$subset,], na.rm=TRUE) } else if(!a$reg.grid) { Zest <- as.image(Zest, nx=xd[1], ny=xd[2], x=a$loc, na.rm=TRUE) ZciR <- as.image(ZciR, nx=xd[1], ny=xd[2], x=a$loc, na.rm=TRUE) } if(a$map) { ax <- list(x=pretty(round(a$loc[,1], digits=2)), y=pretty(round(a$loc[,2], digits=2))) if(is.null(a$subset)) r <- apply(a$loc, 2, range, finite=TRUE) else r <- apply(a$loc[a$subset,], 2, range, finite=TRUE) map(xlim=r[,1], ylim=r[,2], type="n") axis(1, at=ax$x, labels=ax$x) axis(2, at=ax$y, labels=ax$y) if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, Zest, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(Zest, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else image.plot(Zest, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) map(add=TRUE, lwd=1.5) map(database="state", add=TRUE) map(xlim=r[,1], ylim=r[,2], type="n") axis(1, at=ax$x, labels=ax$x) axis(2, at=ax$y, labels=ax$y) if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, ZciR, add=TRUE, col=col, main="CI Range", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(ZciR, add=TRUE, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else image.plot(ZciR, add=TRUE, col=col, main="CI Range", horizontal=horizontal, ...) map(add=TRUE, lwd=1.5) map(database="state", add=TRUE) } else { if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, Zest, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(Zest, col=col, main="Mean of Estimate", horizontal=horizontal, ...) else image.plot(Zest, col=col, main="Mean of Estimate", horizontal=horizontal, ...) if(a$projection && a$reg.grid && is.null(a$subset)) image.plot(xloc, yloc, ZciR, col=col, main="CI Range", horizontal=horizontal, ...) else if(a$reg.grid && is.null(a$subset)) image.plot(ZciR, col=col, main="Mean of Estimate", ...) else image.plot(ZciR, col=col, main="CI Range", horizontal=horizontal, ...) } # end of if else 'map' stmts. if(length(a$data.name) == a$nforecast + 2) { msg <- paste(a$data.name[1], ": ", a$data.name[2], " vs ", a$data.name[a$which.model+2], sep="") } else msg <- paste(a$data.name[2], " vs ", a$data.name[a$which.model+1], sep="") if(a$field.type != "" && a$units != "") msg <- paste(msg, "\n", a$field.type, " (", a$units, ")", sep="") else if(a$field.type != "") msg <- paste(msg, a$field.type, sep="\n") else if(a$units != "") msg <- paste(msg, "\n(", a$units, ")", sep="") mtext(msg, line=0.05, outer=TRUE) invisible() } # end of 'plot.EBS' function. inside <- function(DF) { # # A function to determine if the mean error at a data point is # inside the confidence limits. # # Input # DF - data frame containing mean error values and upper and lower # confidence limits # # Output # logical T if outside, F if inside. # result <- !is.na(CI.fun(DF$Upper - DF$Lower, DF$Estimate)) return(result) } # end of 'inside' function. CI.fun <- function(CI.field, est.field, replacement = NA) { test <- ifelse((0.5 * CI.field < abs(est.field)), est.field, replacement) return(test) } # end of 'CI.fun' function. sig.coverage <- function(DF) { tmp <- inside(DF) out <- sum(tmp,na.rm=TRUE)/(length(tmp[!is.na(tmp)])) - sum(is.na(DF$Estimate)) return(out) } # end of 'sig.coverage' function. is.sig <- function(X, blockboot.results.df, n = 3000, fld.sig = 0.05, verbose=FALSE) { # # Input - # X - matrix of errors at gridpoints. n gridpoints by m days # blockboot.results.df - dataframe of errors and CI at each # gridpoint. # n - number of Monte Carlo trials. # field.sig - significnace alpha for field significance. # # Output - # List # name - Name of the data beig tested # results - The minimum amount of areal coverage needed for # significance at # the given fld.sig # actual - The actual coverage of sigificant gridpoint # results. # issig - Logical variable: T for significant results, F for # non-significant results. # # KLE 01/2005 # # Remove missing rows # sig.results <- MCdof(X, ntrials = n, field.sig = fld.sig, verbose=verbose)$minsigcov actual.coverage <- sig.coverage(blockboot.results.df) sig <- (actual.coverage > sig.results) output <- list(name = as.character(deparse(substitute(X))), required = as.numeric(sig.results), actual = as.numeric( actual.coverage), issig = as.logical(sig)) return(output) } spatbiasFS <- function(X, Y, loc=NULL, block.length=NULL, alpha.boot=0.05, field.sig=0.05, bootR=1000, ntrials=1000, verbose=FALSE) { out <- list() if(!is.null(loc)) { data.name <- c(as.character(substitute(X)),as.character(substitute(Y)),as.character(substitute(loc))) names(data.name) <- c("verification","forecast","locations") } else { data.name <- c(as.character(substitute(X)),as.character(substitute(Y))) names(data.name) <- c("verification","forecast") } out$data.name <- data.name errfield <- Y - X hold <- LocSig(Z=errfield, numrep=bootR, block.length=block.length, alpha=alpha.boot) res <- is.sig(errfield, hold, n=ntrials, fld.sig=field.sig, verbose=verbose) out$block.boot.results <- hold out$sig.results <- res out$field.significance <- field.sig out$alpha.boot <- alpha.boot out$bootR <- bootR out$ntrials <- ntrials class(out) <- "spatbiasFS" return(out) } # end of 'spatbiasFS' function. summary.spatbiasFS <- function(object, ...) { cat("\n") msg <- paste("Results for ", object$data.name[2], " compared against ", object$data.name[1], sep="") print(msg) cat("\n", "\n") cat("Field significance level: ", object$field.significance, "\n") cat("Observed coverage of significant difference: ", object$sig.results$actual, "\n") cat("Required coverage for field significance: ", object$sig.results$required, "\n") invisible() } # end of 'summary.spatbiasFS' function. plot.spatbiasFS <- function(x, ...) { # TO DO: Try to make a better plot (without using as.image). msg <- paste("Mean Error: ", x$data.name[2], " vs ", x$data.name[1], sep="") # X <- get(x$data.name[1]) # Y <- get(x$data.name[2]) if(length(x$data.name)==3) loc <- get(x$data.name[3]) else stop("plot.spatbiasFS: No entry loc. Must supply location information.") est.i <- as.image(x$block.boot.results$Estimate, x=loc) CIrange <- as.image(x$block.boot.results$Upper - x$block.boot.results$Lower, x=loc) par(mfrow=c(1,2)) image.plot(est.i, col=tim.colors(64), axes=FALSE, main=msg) # map(add=TRUE) # map(add=TRUE,database="state") image.plot(CIrange, col=tim.colors(64), axes=FALSE, xlab=paste("Req. Coverage: ", round(x$sig.results$required,digits=2), " vs Obs. coverage: ", round(x$sig.results$actual,digits=2), sep=""), main=paste((1-x$alpha.boot)*100, "% CI range", sep="")) invisible() } # end of 'plot.spatbiasFS' function.
/02-Profit/00-3-RviseMain.R
no_license
Ravin515/STN-DE
R
false
false
803
r
% Generated by roxygen2 (4.0.1): do not edit by hand \name{wwz} \alias{wwz} \title{Runs the Wang-Wei-Zhu decomposition} \usage{ wwz(x) } \arguments{ \item{x}{an object of the class decompr} } \value{ the decomposed table } \description{ This function runs the Wang-Wei-Zhu decomposition. } \details{ Adapted from code by Fei Wang. } \author{ Bastiaan Quast } \references{ Wang, Zhi, Shang-Jin Wei, and Kunfu Zhu. Quantifying international production sharing at the bilateral and sector levels. No. w19677. National Bureau of Economic Research, 2013. }
/man/wwz.Rd
no_license
vkummritz/decompr
R
false
false
553
rd
% Generated by roxygen2 (4.0.1): do not edit by hand \name{wwz} \alias{wwz} \title{Runs the Wang-Wei-Zhu decomposition} \usage{ wwz(x) } \arguments{ \item{x}{an object of the class decompr} } \value{ the decomposed table } \description{ This function runs the Wang-Wei-Zhu decomposition. } \details{ Adapted from code by Fei Wang. } \author{ Bastiaan Quast } \references{ Wang, Zhi, Shang-Jin Wei, and Kunfu Zhu. Quantifying international production sharing at the bilateral and sector levels. No. w19677. National Bureau of Economic Research, 2013. }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/check.blocksDS.R \name{check.blocksDS} \alias{check.blocksDS} \title{Name imputation blocks This helper function names any unnamed elements in the \code{blocks} specification. This is a convenience function.} \usage{ check.blocksDS(blocks, data, calltype = "type") } \arguments{ \item{prefix}{A character vector of length 1 with the prefix to be using for naming any unnamed blocks with two or more variables.} } \value{ A named list of character vectors with variables names. } \description{ Name imputation blocks This helper function names any unnamed elements in the \code{blocks} specification. This is a convenience function. } \details{ This function will name any unnamed list elements specified in the optional argument \code{blocks}. Unnamed blocks consisting of just one variable will be named after this variable. Unnamed blocks containing more than one variables will be named by the \code{prefix} argument, padded by an integer sequence stating at 1. } \examples{ blocks <- list(c("hyp", "chl"), AGE = "age", c("bmi", "hyp"), "edu") name.blocks(blocks) }
/man/check.blocksDS.Rd
no_license
paularaissa/dsMice
R
false
true
1,149
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/check.blocksDS.R \name{check.blocksDS} \alias{check.blocksDS} \title{Name imputation blocks This helper function names any unnamed elements in the \code{blocks} specification. This is a convenience function.} \usage{ check.blocksDS(blocks, data, calltype = "type") } \arguments{ \item{prefix}{A character vector of length 1 with the prefix to be using for naming any unnamed blocks with two or more variables.} } \value{ A named list of character vectors with variables names. } \description{ Name imputation blocks This helper function names any unnamed elements in the \code{blocks} specification. This is a convenience function. } \details{ This function will name any unnamed list elements specified in the optional argument \code{blocks}. Unnamed blocks consisting of just one variable will be named after this variable. Unnamed blocks containing more than one variables will be named by the \code{prefix} argument, padded by an integer sequence stating at 1. } \examples{ blocks <- list(c("hyp", "chl"), AGE = "age", c("bmi", "hyp"), "edu") name.blocks(blocks) }
#' Function for creating simple D3 JavaScript force directed network graphs. #' #' \code{simpleNetwork} creates simple D3 JavaScript force directed network #' graphs. #' #' @param Data a data frame object with three columns. The first two are the #' names of the linked units. The third records an edge value. (Currently the #' third column doesn't affect the graph.) #' @param Source character string naming the network source variable in the data #' frame. If \code{Source = NULL} then the first column of the data frame is #' treated as the source. #' @param Target character string naming the network target variable in the data #' frame. If \code{Target = NULL} then the second column of the data frame is #' treated as the target. #' @param height height for the network graph's frame area in pixels (if #' \code{NULL} then height is automatically determined based on context) #' @param width numeric width for the network graph's frame area in pixels (if #' \code{NULL} then width is automatically determined based on context) #' @param linkDistance numeric distance between the links in pixels (actually #' arbitrary relative to the diagram's size). #' @param charge numeric value indicating either the strength of the node #' repulsion (negative value) or attraction (positive value). #' @param fontSize numeric font size in pixels for the node text labels. #' @param fontFamily font family for the node text labels. #' @param linkColour character string specifying the colour you want the link #' lines to be. Multiple formats supported (e.g. hexadecimal). #' @param nodeColour character string specifying the colour you want the node #' circles to be. Multiple formats supported (e.g. hexadecimal). #' @param nodeClickColour character string specifying the colour you want the #' node circles to be when they are clicked. Also changes the colour of the #' text. Multiple formats supported (e.g. hexadecimal). #' @param textColour character string specifying the colour you want the text to #' be before they are clicked. Multiple formats supported (e.g. hexadecimal). #' @param opacity numeric value of the proportion opaque you would like the #' graph elements to be. #' @param zoom logical value to enable (\code{TRUE}) or disable (\code{FALSE}) #' zooming #' #' @examples #' # Fake data #' Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D") #' Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I") #' NetworkData <- data.frame(Source, Target) #' #' # Create graph #' simpleNetwork(NetworkData) #' simpleNetwork(NetworkData, fontFamily = "sans-serif") #' #' @source D3.js was created by Michael Bostock. See \url{http://d3js.org/} and, #' more specifically for directed networks #' \url{https://github.com/mbostock/d3/wiki/Force-Layout} #' #' @export simpleNetwork <- function(Data, Source = NULL, Target = NULL, height = NULL, width = NULL, linkDistance = 50, charge = -200, fontSize = 7, fontFamily = "serif", linkColour = "#666", nodeColour = "#3182bd", nodeClickColour = "#E34A33", textColour = "#3182bd", opacity = 0.6, zoom = F) { # validate input if (!is.data.frame(Data)) stop("data must be a data frame class object.") # If tbl_df convert to plain data.frame Data <- tbl_df_strip(Data) # create links data if (is.null(Source) && is.null(Target)) links <- Data[, 1:2] else if (!is.null(Source) && !is.null(Target)) links <- data.frame(Data[, Source], Data[, Target]) names(links) <- c("source", "target") # Check if data is zero indexed check_zero(links[, 'source'], links[, 'target']) # create options options = list( linkDistance = linkDistance, charge = charge, fontSize = fontSize, fontFamily = fontFamily, linkColour = linkColour, nodeColour = nodeColour, nodeClickColour = nodeClickColour, textColour = textColour, opacity = opacity, zoom = zoom ) # create widget htmlwidgets::createWidget( name = "simpleNetwork", x = list(links = links, options = options), width = width, height = height, htmlwidgets::sizingPolicy(padding = 10, browser.fill = TRUE), package = "networkD3" ) } #' @rdname networkD3-shiny #' @export simpleNetworkOutput <- function(outputId, width = "100%", height = "500px") { shinyWidgetOutput(outputId, "simpleNetwork", width, height, package = "networkD3") } #' @rdname networkD3-shiny #' @export renderSimpleNetwork <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted shinyRenderWidget(expr, simpleNetworkOutput, env, quoted = TRUE) }
/R/simpleNetwork.R
no_license
fbreitwieser/networkD3
R
false
false
5,115
r
#' Function for creating simple D3 JavaScript force directed network graphs. #' #' \code{simpleNetwork} creates simple D3 JavaScript force directed network #' graphs. #' #' @param Data a data frame object with three columns. The first two are the #' names of the linked units. The third records an edge value. (Currently the #' third column doesn't affect the graph.) #' @param Source character string naming the network source variable in the data #' frame. If \code{Source = NULL} then the first column of the data frame is #' treated as the source. #' @param Target character string naming the network target variable in the data #' frame. If \code{Target = NULL} then the second column of the data frame is #' treated as the target. #' @param height height for the network graph's frame area in pixels (if #' \code{NULL} then height is automatically determined based on context) #' @param width numeric width for the network graph's frame area in pixels (if #' \code{NULL} then width is automatically determined based on context) #' @param linkDistance numeric distance between the links in pixels (actually #' arbitrary relative to the diagram's size). #' @param charge numeric value indicating either the strength of the node #' repulsion (negative value) or attraction (positive value). #' @param fontSize numeric font size in pixels for the node text labels. #' @param fontFamily font family for the node text labels. #' @param linkColour character string specifying the colour you want the link #' lines to be. Multiple formats supported (e.g. hexadecimal). #' @param nodeColour character string specifying the colour you want the node #' circles to be. Multiple formats supported (e.g. hexadecimal). #' @param nodeClickColour character string specifying the colour you want the #' node circles to be when they are clicked. Also changes the colour of the #' text. Multiple formats supported (e.g. hexadecimal). #' @param textColour character string specifying the colour you want the text to #' be before they are clicked. Multiple formats supported (e.g. hexadecimal). #' @param opacity numeric value of the proportion opaque you would like the #' graph elements to be. #' @param zoom logical value to enable (\code{TRUE}) or disable (\code{FALSE}) #' zooming #' #' @examples #' # Fake data #' Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D") #' Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I") #' NetworkData <- data.frame(Source, Target) #' #' # Create graph #' simpleNetwork(NetworkData) #' simpleNetwork(NetworkData, fontFamily = "sans-serif") #' #' @source D3.js was created by Michael Bostock. See \url{http://d3js.org/} and, #' more specifically for directed networks #' \url{https://github.com/mbostock/d3/wiki/Force-Layout} #' #' @export simpleNetwork <- function(Data, Source = NULL, Target = NULL, height = NULL, width = NULL, linkDistance = 50, charge = -200, fontSize = 7, fontFamily = "serif", linkColour = "#666", nodeColour = "#3182bd", nodeClickColour = "#E34A33", textColour = "#3182bd", opacity = 0.6, zoom = F) { # validate input if (!is.data.frame(Data)) stop("data must be a data frame class object.") # If tbl_df convert to plain data.frame Data <- tbl_df_strip(Data) # create links data if (is.null(Source) && is.null(Target)) links <- Data[, 1:2] else if (!is.null(Source) && !is.null(Target)) links <- data.frame(Data[, Source], Data[, Target]) names(links) <- c("source", "target") # Check if data is zero indexed check_zero(links[, 'source'], links[, 'target']) # create options options = list( linkDistance = linkDistance, charge = charge, fontSize = fontSize, fontFamily = fontFamily, linkColour = linkColour, nodeColour = nodeColour, nodeClickColour = nodeClickColour, textColour = textColour, opacity = opacity, zoom = zoom ) # create widget htmlwidgets::createWidget( name = "simpleNetwork", x = list(links = links, options = options), width = width, height = height, htmlwidgets::sizingPolicy(padding = 10, browser.fill = TRUE), package = "networkD3" ) } #' @rdname networkD3-shiny #' @export simpleNetworkOutput <- function(outputId, width = "100%", height = "500px") { shinyWidgetOutput(outputId, "simpleNetwork", width, height, package = "networkD3") } #' @rdname networkD3-shiny #' @export renderSimpleNetwork <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted shinyRenderWidget(expr, simpleNetworkOutput, env, quoted = TRUE) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Pr_S_cnd.R \name{Pr_S_cnd} \alias{Pr_S_cnd} \title{Probability of selection event, conditonal on theta} \usage{ Pr_S_cnd(theta, sigma, t) } \arguments{ \item{theta}{the given value of mean of sampling distribution for y} \item{sigma}{standard deviation for y} \item{t}{truncation point} } \description{ Probability of selection event, conditonal on theta }
/man/Pr_S_cnd.Rd
no_license
spencerwoody/saFAB
R
false
true
437
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Pr_S_cnd.R \name{Pr_S_cnd} \alias{Pr_S_cnd} \title{Probability of selection event, conditonal on theta} \usage{ Pr_S_cnd(theta, sigma, t) } \arguments{ \item{theta}{the given value of mean of sampling distribution for y} \item{sigma}{standard deviation for y} \item{t}{truncation point} } \description{ Probability of selection event, conditonal on theta }
if (!file.exists("household_power_consumption.txt")) { URL <- "http://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(URL, destfile="./household_power_consumption.zip") unzip("household_power_consumption.zip") } ## Read in data from only two dates hpc <- subset(read.table("household_power_consumption.txt", header=TRUE, sep=";", colClasses=c(rep('character', 2), rep('numeric', 7)), na.strings="?"), Date=="1/2/2007" | Date=="2/2/2007") ## Load lubridate, format dates and time and create datetime column library(lubridate) hpc$datetime <- dmy_hms(paste(hpc$Date, hpc$Time)) ##Open png device png(file="plot4.png") par(mfrow = c(2,2)) with(hpc, { ##First plot plot(hpc$datetime, hpc$Global_active_power, type="n", xlab="", ylab="Global Active Power") lines(hpc$datetime, hpc$Global_active_power, type="l") ##Second plot plot(hpc$datetime, hpc$Voltage, xlab="datetime", ylab="Voltage", type="n") lines(hpc$datetime, hpc$Voltage, type="l") ##Third plot plot(hpc$datetime, hpc$Sub_metering_1, type="n", xlab="", ylab="Energy sub metering") lines(hpc$datetime, hpc$Sub_metering_1, type="l") lines(hpc$datetime, hpc$Sub_metering_2, type="l", col="red") lines(hpc$datetime, hpc$Sub_metering_3, type="l", col="blue") legend("topright", lty=c(1,1,1), col=c("black", "red", "blue"), legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty="n") ##Forth plot plot(hpc$datetime, hpc$Global_reactive_power, xlab="datetime", ylab="Global_reactive_power", type="n") lines(hpc$datetime, hpc$Global_reactive_power, type="l") }) ##Close png file device dev.off()
/plot4.R
no_license
wavygravy18/ExData_Plotting1
R
false
false
1,643
r
if (!file.exists("household_power_consumption.txt")) { URL <- "http://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(URL, destfile="./household_power_consumption.zip") unzip("household_power_consumption.zip") } ## Read in data from only two dates hpc <- subset(read.table("household_power_consumption.txt", header=TRUE, sep=";", colClasses=c(rep('character', 2), rep('numeric', 7)), na.strings="?"), Date=="1/2/2007" | Date=="2/2/2007") ## Load lubridate, format dates and time and create datetime column library(lubridate) hpc$datetime <- dmy_hms(paste(hpc$Date, hpc$Time)) ##Open png device png(file="plot4.png") par(mfrow = c(2,2)) with(hpc, { ##First plot plot(hpc$datetime, hpc$Global_active_power, type="n", xlab="", ylab="Global Active Power") lines(hpc$datetime, hpc$Global_active_power, type="l") ##Second plot plot(hpc$datetime, hpc$Voltage, xlab="datetime", ylab="Voltage", type="n") lines(hpc$datetime, hpc$Voltage, type="l") ##Third plot plot(hpc$datetime, hpc$Sub_metering_1, type="n", xlab="", ylab="Energy sub metering") lines(hpc$datetime, hpc$Sub_metering_1, type="l") lines(hpc$datetime, hpc$Sub_metering_2, type="l", col="red") lines(hpc$datetime, hpc$Sub_metering_3, type="l", col="blue") legend("topright", lty=c(1,1,1), col=c("black", "red", "blue"), legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty="n") ##Forth plot plot(hpc$datetime, hpc$Global_reactive_power, xlab="datetime", ylab="Global_reactive_power", type="n") lines(hpc$datetime, hpc$Global_reactive_power, type="l") }) ##Close png file device dev.off()
#!/usr/bin/env Rscript library(ggplot2) args <- commandArgs(trailingOnly = TRUE) parse_1d_str_args <- function(str) { return(unlist(strsplit(str,","))) } parse_2d_numeric_args <- function(str) { return(lapply(unlist(strsplit(str,";")),function(s) as.numeric(parse_1d_str_args(s)))) } data <- unlist(parse_2d_numeric_args(args[1])) data_labels <- parse_1d_str_args(args[2]) stats <- parse_1d_str_args(args[3]) stat_colors <- parse_1d_str_args(args[4]) ylabel <- args[5] xlabel <- args[6] output_files <- parse_1d_str_args(args[7]) df <- data.frame( opts = factor(rep(stats,length(data_labels)),levels=stats), numParallel = factor( unlist(lapply(data_labels, function(x) rep(x,length(stats)))), levels=data_labels), data=data) ggplot(data=df, aes(x=numParallel, y=data, fill=opts)) + geom_bar(stat="identity", position=position_dodge(), colour="black") + theme_bw() + theme(legend.title=element_blank(),legend.position="bottom") + xlab(xlabel) + ylab(ylabel) + scale_fill_manual(values=stat_colors) lapply(output_files, function(f) ggsave(f,width=7,height=6))
/nic_of_time/r-scripts/grouped_bars.r
no_license
nic-of-time/nic-of-time
R
false
false
1,094
r
#!/usr/bin/env Rscript library(ggplot2) args <- commandArgs(trailingOnly = TRUE) parse_1d_str_args <- function(str) { return(unlist(strsplit(str,","))) } parse_2d_numeric_args <- function(str) { return(lapply(unlist(strsplit(str,";")),function(s) as.numeric(parse_1d_str_args(s)))) } data <- unlist(parse_2d_numeric_args(args[1])) data_labels <- parse_1d_str_args(args[2]) stats <- parse_1d_str_args(args[3]) stat_colors <- parse_1d_str_args(args[4]) ylabel <- args[5] xlabel <- args[6] output_files <- parse_1d_str_args(args[7]) df <- data.frame( opts = factor(rep(stats,length(data_labels)),levels=stats), numParallel = factor( unlist(lapply(data_labels, function(x) rep(x,length(stats)))), levels=data_labels), data=data) ggplot(data=df, aes(x=numParallel, y=data, fill=opts)) + geom_bar(stat="identity", position=position_dodge(), colour="black") + theme_bw() + theme(legend.title=element_blank(),legend.position="bottom") + xlab(xlabel) + ylab(ylabel) + scale_fill_manual(values=stat_colors) lapply(output_files, function(f) ggsave(f,width=7,height=6))
.onAttach <- function(libname, pkgname){ options(stringsAsFactors = F) library(glmnet) library(plyr) library(dplyr) library(RColorBrewer) library(e1071) library(ggplot2) library(Hmisc) library(randomForest) }
/R/zzz.R
no_license
menghaomiao/ITR.Forest
R
false
false
235
r
.onAttach <- function(libname, pkgname){ options(stringsAsFactors = F) library(glmnet) library(plyr) library(dplyr) library(RColorBrewer) library(e1071) library(ggplot2) library(Hmisc) library(randomForest) }
#' @param pg.where Character length one. If left at the default 'def', the value #' from the settings.r file is read in (parameter \code{gen_plot_pgWhereDefault}). #' For plotting to PDFs provide "pdf", for plotting to graphics device provide #' anything but "pdf". #' @param pg.main Character length one. The additional text on the title of each #' single plot. #' @param pg.sub Character length one. The additional text on the subtitle of #' each single plot. #' @param pg.fns Character length one. The additional text in the filename of #' the pdf.
/man-roxygen/mr_pg_genParams.r
no_license
bpollner/aquap2
R
false
false
558
r
#' @param pg.where Character length one. If left at the default 'def', the value #' from the settings.r file is read in (parameter \code{gen_plot_pgWhereDefault}). #' For plotting to PDFs provide "pdf", for plotting to graphics device provide #' anything but "pdf". #' @param pg.main Character length one. The additional text on the title of each #' single plot. #' @param pg.sub Character length one. The additional text on the subtitle of #' each single plot. #' @param pg.fns Character length one. The additional text in the filename of #' the pdf.
source("load_data.R") plot3 <- function(dt=NULL) { if(is.null(dt)) dt <- load_data() png("plot3.png", width=400, height=400) plot(dt$Time, dt$Sub_metering_1, type="l", col="black", xlab="", ylab="Energy sub metering") lines(dt$Time, dt$Sub_metering_2, col="red") lines(dt$Time, dt$Sub_metering_3, col="blue") legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1) dev.off() }
/plot3.R
no_license
Drj2015/ExData_Plotting1
R
false
false
496
r
source("load_data.R") plot3 <- function(dt=NULL) { if(is.null(dt)) dt <- load_data() png("plot3.png", width=400, height=400) plot(dt$Time, dt$Sub_metering_1, type="l", col="black", xlab="", ylab="Energy sub metering") lines(dt$Time, dt$Sub_metering_2, col="red") lines(dt$Time, dt$Sub_metering_3, col="blue") legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1) dev.off() }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/crossReferenceList.R \name{crossReferenceList} \alias{crossReferenceList} \title{crossReferenceList} \usage{ crossReferenceList(crossReferenceFile, mySubjectClass) } \arguments{ \item{crossReferenceFile}{The filepath of sequence database whose sequences have pdb in text.} \item{mySubjectClass}{A S4 class storing all information from the given sequence database in fasta.} } \value{ A dataframe with column "entry", "crossReference" which stores entry names and their corresponding PDB name } \description{ Create a dataframe storing entries and corresponding cross reference. There might be more than one pdb names for one sequence, the package only pick the last one in given file. } \examples{ # Go to UniPort, download IPR005814 family entry database in text that is reviewed and has # 3D structure (databaseExample.fasta, databaseExample.txt). mySubject <- Biostrings::readAAStringSet("databaseExample.fasta") crossReferenceList("databaseExample.txt", mySubject) }
/man/crossReferenceList.Rd
permissive
MichelleMengzhi/hmtp
R
false
true
1,052
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/crossReferenceList.R \name{crossReferenceList} \alias{crossReferenceList} \title{crossReferenceList} \usage{ crossReferenceList(crossReferenceFile, mySubjectClass) } \arguments{ \item{crossReferenceFile}{The filepath of sequence database whose sequences have pdb in text.} \item{mySubjectClass}{A S4 class storing all information from the given sequence database in fasta.} } \value{ A dataframe with column "entry", "crossReference" which stores entry names and their corresponding PDB name } \description{ Create a dataframe storing entries and corresponding cross reference. There might be more than one pdb names for one sequence, the package only pick the last one in given file. } \examples{ # Go to UniPort, download IPR005814 family entry database in text that is reviewed and has # 3D structure (databaseExample.fasta, databaseExample.txt). mySubject <- Biostrings::readAAStringSet("databaseExample.fasta") crossReferenceList("databaseExample.txt", mySubject) }
#' The application User-Interface #' #' @param request Internal parameter for `{shiny}`. #' DO NOT REMOVE. #' @import shiny #' @import shinydashboard #' @noRd app_ui <- function(request) { tagList( # Leave this function for adding external resources golem_add_external_resources(), # List the first level UI elements here dashboardPage( title = "Etherpad Dashboard", skin = "black", dashboardHeader(title = "OULAD dashboard"), dashboardSidebar( sidebarMenu( menuItem("Overview", tabName = "overview", icon = icon("table")) ) ), dashboardBody( tabItems( tabItem(tabName = "overview", fluidRow( mod_module_presentation_switch_ui("module_presentation_switch_ui_1") ), fluidRow( mod_activity_graph_ui("activity_graph_ui_1") ), fluidRow( mod_general_stats_ui("general_stats_ui_1") ), fluidRow( mod_student_overview_ui("student_overview_ui_1") ) ), tabItem(tabName = "groups") ) ) ) ) } #' Add external Resources to the Application #' #' This function is internally used to add external #' resources inside the Shiny application. #' #' @import shiny #' @importFrom golem add_resource_path activate_js favicon bundle_resources #' @noRd golem_add_external_resources <- function(){ add_resource_path( 'www', app_sys('app/www') ) tags$head( favicon(), bundle_resources( path = app_sys('app/www'), app_title = 'oulad.dashboard' ) # Add here other external resources # for example, you can add shinyalert::useShinyalert() ) }
/image/oulad.dashboard/R/app_ui.R
permissive
jakubkuzilek/LA-Dashboards-course
R
false
false
1,839
r
#' The application User-Interface #' #' @param request Internal parameter for `{shiny}`. #' DO NOT REMOVE. #' @import shiny #' @import shinydashboard #' @noRd app_ui <- function(request) { tagList( # Leave this function for adding external resources golem_add_external_resources(), # List the first level UI elements here dashboardPage( title = "Etherpad Dashboard", skin = "black", dashboardHeader(title = "OULAD dashboard"), dashboardSidebar( sidebarMenu( menuItem("Overview", tabName = "overview", icon = icon("table")) ) ), dashboardBody( tabItems( tabItem(tabName = "overview", fluidRow( mod_module_presentation_switch_ui("module_presentation_switch_ui_1") ), fluidRow( mod_activity_graph_ui("activity_graph_ui_1") ), fluidRow( mod_general_stats_ui("general_stats_ui_1") ), fluidRow( mod_student_overview_ui("student_overview_ui_1") ) ), tabItem(tabName = "groups") ) ) ) ) } #' Add external Resources to the Application #' #' This function is internally used to add external #' resources inside the Shiny application. #' #' @import shiny #' @importFrom golem add_resource_path activate_js favicon bundle_resources #' @noRd golem_add_external_resources <- function(){ add_resource_path( 'www', app_sys('app/www') ) tags$head( favicon(), bundle_resources( path = app_sys('app/www'), app_title = 'oulad.dashboard' ) # Add here other external resources # for example, you can add shinyalert::useShinyalert() ) }
############################################################################### # Create simulation scenarios ############################################################################### path.output_data <- Sys.getenv("path.output_data") this.folder <- "exchangeable" source(file.path(path.output_data, this.folder, "create-scenarios-exch.R")) ############################################################################### # Check which values of rho will result in a positive definite # correlation matrix (for Z_{it}'s) ############################################################################### # Fix other.corr.params and increase rho from 0 to 1 -------------------------- path.code <- Sys.getenv("path.code") source(file.path(path.code,"datagen-utils.R")) input.rand.time <- 2 input.tot.time <- 6 list.check.pd.results <- list() for(curr.rho in seq(from = 0, to = 1, by = 0.05)){ pd <- CheckPositiveDefinite(tot.time = input.tot.time, rand.time = input.rand.time, rho = curr.rho, corr.str = "exch", other.corr.params = curr.rho/2) # If pd==0, then positive definite, else, if pd!=0, then not positive definite list.check.pd.results <- append(list.check.pd.results, list(data.frame(rho = curr.rho, is.pd = 1*(pd==0)))) } check.pd.results <- do.call(rbind, list.check.pd.results) print(check.pd.results) # Clean up environment remove(list = ls()) ############################################################################### # Calculate power for fixed value of means and proportion of zeros within # this.folder while varying total sample size and rho ############################################################################### path.output_data <- Sys.getenv("path.output_data") this.folder <- "exchangeable" for(i in 1:10){ this.scenario <- paste("sim_vary_effect/sim_results_", i, sep="") use.grid <- expand.grid(N = seq(100,550,50), rho = c(0.2, 0.4, 0.6)) dat.all.results <- data.frame(N = rep(NA_real_, nrow(use.grid)), rho = rep(NA_real_, nrow(use.grid)), power.diff.eos.means = rep(NA_real_, nrow(use.grid)), power.diff.AUC = rep(NA_real_, nrow(use.grid)), elapsed.secs = rep(NA_real_, nrow(use.grid))) for(idx in 1:nrow(use.grid)){ path.code <- Sys.getenv("path.code") path.output_data <- Sys.getenv("path.output_data") input.means <- read.csv(file.path(path.output_data, this.folder, this.scenario, "input_means.csv")) input.prop.zeros <- read.csv(file.path(path.output_data, this.folder, this.scenario, "input_prop_zeros.csv")) input.M <- 5000 input.N <- use.grid[idx, "N"] input.rho <- use.grid[idx, "rho"] input.n4 <- NA_real_ input.rand.time <- 2 input.tot.time <- 6 input.cutoff <- 0 input.corr.str <- "exch" input.other.corr.params <- input.rho/2 use.working.corr <- "ar1" start.time <- Sys.time() source(file.path(path.code,"calc-covmat.R")) this.pair <- 2 source(file.path(path.code,"calc-estimated-contrasts.R")) input.alpha <- 0.05 source(file.path(path.code,"calc-estimated-power.R")) end.time <- Sys.time() elapsed.secs <- difftime(time1 = end.time, time2 = start.time, units = "secs") elapsed.secs <- as.numeric(elapsed.secs) dat.all.results[idx,"N"] <- input.N dat.all.results[idx,"rho"] <- input.rho dat.all.results[idx,"power.diff.eos.means"] <- power.diff.eos.means dat.all.results[idx,"power.diff.AUC"] <- power.diff.AUC dat.all.results[idx,"elapsed.secs"] <- elapsed.secs } write.csv(dat.all.results, file = file.path(path.output_data, this.folder, this.scenario, "power.csv"), row.names = FALSE) } # Clean up environment remove(list = ls()) ############################################################################### # Calculate relationship between rho and tau ############################################################################### path.code <- Sys.getenv("path.code") path.output_data <- Sys.getenv("path.output_data") for(i in 1:10){ # Input parameters input.M <- 5000 input.N <- 1000 input.rand.time <- 2 input.tot.time <- 6 input.cutoff <- 0 input.corr.str <- "exch" min.rho <- 0 max.rho <- 0.6 this.folder <- "exchangeable" this.scenario <- paste("sim_vary_effect/sim_results_", i, sep="") # Calculate correspondence between rho and tau source(file.path(path.code,"calc-corr-params-curve.R")) # Save output save(collect.seq.cormat, file = file.path(path.output_data, this.folder, this.scenario, "collect_seq_cormat.RData")) write.csv(collect.correlation.tau, file.path(path.output_data, this.folder, this.scenario, "collect_tau.csv"), row.names = FALSE) } # Clean up environment remove(list = ls())
/output/exchangeable/simulation-study-pipeline-exch.R
permissive
jamieyap/CountSMART
R
false
false
4,969
r
############################################################################### # Create simulation scenarios ############################################################################### path.output_data <- Sys.getenv("path.output_data") this.folder <- "exchangeable" source(file.path(path.output_data, this.folder, "create-scenarios-exch.R")) ############################################################################### # Check which values of rho will result in a positive definite # correlation matrix (for Z_{it}'s) ############################################################################### # Fix other.corr.params and increase rho from 0 to 1 -------------------------- path.code <- Sys.getenv("path.code") source(file.path(path.code,"datagen-utils.R")) input.rand.time <- 2 input.tot.time <- 6 list.check.pd.results <- list() for(curr.rho in seq(from = 0, to = 1, by = 0.05)){ pd <- CheckPositiveDefinite(tot.time = input.tot.time, rand.time = input.rand.time, rho = curr.rho, corr.str = "exch", other.corr.params = curr.rho/2) # If pd==0, then positive definite, else, if pd!=0, then not positive definite list.check.pd.results <- append(list.check.pd.results, list(data.frame(rho = curr.rho, is.pd = 1*(pd==0)))) } check.pd.results <- do.call(rbind, list.check.pd.results) print(check.pd.results) # Clean up environment remove(list = ls()) ############################################################################### # Calculate power for fixed value of means and proportion of zeros within # this.folder while varying total sample size and rho ############################################################################### path.output_data <- Sys.getenv("path.output_data") this.folder <- "exchangeable" for(i in 1:10){ this.scenario <- paste("sim_vary_effect/sim_results_", i, sep="") use.grid <- expand.grid(N = seq(100,550,50), rho = c(0.2, 0.4, 0.6)) dat.all.results <- data.frame(N = rep(NA_real_, nrow(use.grid)), rho = rep(NA_real_, nrow(use.grid)), power.diff.eos.means = rep(NA_real_, nrow(use.grid)), power.diff.AUC = rep(NA_real_, nrow(use.grid)), elapsed.secs = rep(NA_real_, nrow(use.grid))) for(idx in 1:nrow(use.grid)){ path.code <- Sys.getenv("path.code") path.output_data <- Sys.getenv("path.output_data") input.means <- read.csv(file.path(path.output_data, this.folder, this.scenario, "input_means.csv")) input.prop.zeros <- read.csv(file.path(path.output_data, this.folder, this.scenario, "input_prop_zeros.csv")) input.M <- 5000 input.N <- use.grid[idx, "N"] input.rho <- use.grid[idx, "rho"] input.n4 <- NA_real_ input.rand.time <- 2 input.tot.time <- 6 input.cutoff <- 0 input.corr.str <- "exch" input.other.corr.params <- input.rho/2 use.working.corr <- "ar1" start.time <- Sys.time() source(file.path(path.code,"calc-covmat.R")) this.pair <- 2 source(file.path(path.code,"calc-estimated-contrasts.R")) input.alpha <- 0.05 source(file.path(path.code,"calc-estimated-power.R")) end.time <- Sys.time() elapsed.secs <- difftime(time1 = end.time, time2 = start.time, units = "secs") elapsed.secs <- as.numeric(elapsed.secs) dat.all.results[idx,"N"] <- input.N dat.all.results[idx,"rho"] <- input.rho dat.all.results[idx,"power.diff.eos.means"] <- power.diff.eos.means dat.all.results[idx,"power.diff.AUC"] <- power.diff.AUC dat.all.results[idx,"elapsed.secs"] <- elapsed.secs } write.csv(dat.all.results, file = file.path(path.output_data, this.folder, this.scenario, "power.csv"), row.names = FALSE) } # Clean up environment remove(list = ls()) ############################################################################### # Calculate relationship between rho and tau ############################################################################### path.code <- Sys.getenv("path.code") path.output_data <- Sys.getenv("path.output_data") for(i in 1:10){ # Input parameters input.M <- 5000 input.N <- 1000 input.rand.time <- 2 input.tot.time <- 6 input.cutoff <- 0 input.corr.str <- "exch" min.rho <- 0 max.rho <- 0.6 this.folder <- "exchangeable" this.scenario <- paste("sim_vary_effect/sim_results_", i, sep="") # Calculate correspondence between rho and tau source(file.path(path.code,"calc-corr-params-curve.R")) # Save output save(collect.seq.cormat, file = file.path(path.output_data, this.folder, this.scenario, "collect_seq_cormat.RData")) write.csv(collect.correlation.tau, file.path(path.output_data, this.folder, this.scenario, "collect_tau.csv"), row.names = FALSE) } # Clean up environment remove(list = ls())
library(tidyverse) library(glmmML) library(rstan) ## Variance by individual difference d <- read_csv('https://kuboweb.github.io/-kubo/stat/iwanamibook/fig/hbm/data7a.csv') d %>% ggplot(aes(x=y)) + geom_histogram() ##GLM fit.glm <- glm(cbind(y, 8-y)~1, data=d, family=binomial()) summary(fit.glm) 1/(1+exp(-fit.glm$coefficients[1])) ##GLMM fit.glmm <- glmmML(cbind(y, 8-y)~1, data=d, family=binomial(), cluster=id) summary(fit.glmm) 1/(1+exp(-fit.glmm$coefficients[1])) ##Stan d.list <- list( N = nrow(d), y = d$y ) fit.stan <- stan( file = './Chapter10/model2.stan', data = d.list) print(fit.stan) plot(fit.stan) beta <- summary(fit.stan)$summary['beta','mean'] r <- summary(fit.stan)$summary[2:101,'mean'] sigma <- summary(fit.stan)$summary['sigma','mean'] rm(list=ls(all.names=TRUE)) ## Variance by individual difference and by pot difference d <- read_csv('https://kuboweb.github.io/-kubo/stat/iwanamibook/fig/hbm/nested/d1.csv') d$f <- as.numeric(d$f=='T') d$pot <- as.numeric(factor(d$pot)) ##Stan d.list <- list( N = nrow(d), N_pot = length(unique(d$pot)), y = d$y, f = d$f, pot = d$pot ) fit.stan <- stan( file = './Chapter10/model3.stan', data = d.list) print(fit.stan) plot(fit.stan) ## Reference ## https://fisproject.jp/2015/06/glm-stan/ ## https://ito-hi.blog.ss-blog.jp/2012-09-03 ## https://ito-hi.blog.ss-blog.jp/2012-09-04
/Chapter10/Chapter10.R
no_license
kenyam1979/Statistical-modeling-for-data-analysis
R
false
false
1,391
r
library(tidyverse) library(glmmML) library(rstan) ## Variance by individual difference d <- read_csv('https://kuboweb.github.io/-kubo/stat/iwanamibook/fig/hbm/data7a.csv') d %>% ggplot(aes(x=y)) + geom_histogram() ##GLM fit.glm <- glm(cbind(y, 8-y)~1, data=d, family=binomial()) summary(fit.glm) 1/(1+exp(-fit.glm$coefficients[1])) ##GLMM fit.glmm <- glmmML(cbind(y, 8-y)~1, data=d, family=binomial(), cluster=id) summary(fit.glmm) 1/(1+exp(-fit.glmm$coefficients[1])) ##Stan d.list <- list( N = nrow(d), y = d$y ) fit.stan <- stan( file = './Chapter10/model2.stan', data = d.list) print(fit.stan) plot(fit.stan) beta <- summary(fit.stan)$summary['beta','mean'] r <- summary(fit.stan)$summary[2:101,'mean'] sigma <- summary(fit.stan)$summary['sigma','mean'] rm(list=ls(all.names=TRUE)) ## Variance by individual difference and by pot difference d <- read_csv('https://kuboweb.github.io/-kubo/stat/iwanamibook/fig/hbm/nested/d1.csv') d$f <- as.numeric(d$f=='T') d$pot <- as.numeric(factor(d$pot)) ##Stan d.list <- list( N = nrow(d), N_pot = length(unique(d$pot)), y = d$y, f = d$f, pot = d$pot ) fit.stan <- stan( file = './Chapter10/model3.stan', data = d.list) print(fit.stan) plot(fit.stan) ## Reference ## https://fisproject.jp/2015/06/glm-stan/ ## https://ito-hi.blog.ss-blog.jp/2012-09-03 ## https://ito-hi.blog.ss-blog.jp/2012-09-04
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/getARTData.R \name{calcARTCov} \alias{calcARTCov} \title{calcARTCov} \usage{ calcARTCov(dat = getEverART(), Args = setArgs()) } \arguments{ \item{dat}{A dataset from \code{\link{getEverART}}.} \item{Args}{requires Args, see \code{\link{setArgs}}} } \value{ data.frame } \description{ Calculate ART coverage for AHRI data. (This is a very crude measure of ART coverage. More work needed on an appropriate measure.) }
/man/calcARTCov.Rd
no_license
hkim207/ahri-1
R
false
true
495
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/getARTData.R \name{calcARTCov} \alias{calcARTCov} \title{calcARTCov} \usage{ calcARTCov(dat = getEverART(), Args = setArgs()) } \arguments{ \item{dat}{A dataset from \code{\link{getEverART}}.} \item{Args}{requires Args, see \code{\link{setArgs}}} } \value{ data.frame } \description{ Calculate ART coverage for AHRI data. (This is a very crude measure of ART coverage. More work needed on an appropriate measure.) }
import_path = "Import/180216_no_comments_and_pull_requests_per_owner.csv" df1 = read.csv(import_path, header=TRUE, sep=",", stringsAsFactors = TRUE) import_path = "Import/180216_count_commits_per_owner.csv" df2 = read.csv(import_path, header=TRUE, sep=",", stringsAsFactors = TRUE) df1$comment_count_log = log(df1$comment_count) df1$pull_request_count_log = log(df1$pull_request_count) df2$commit_count_log = log(df2$commit_count) r_comment_count <- hist(df1$comment_count_log) r_pull_request_count <- hist(df1$pull_request_count_log) r_commit_count <- hist(df2$commit_count_log) logplot <- function(r, title, xlab){ plot(r$breaks[-1], r$counts, type='l', log = 'y', main = title, xlab = xlab, ylab = "log(frequency)") } logplot(r=r_comment_count, title="log-log plot of no comments to frequency per owner (considers all comments between 2014-01-01 and 2017-07-31)", xlab = "log(count comments per owner)") logplot(r_pull_request_count, title = "log-log plot of no pull_requests to frequency per owner (considers all pull_requtests between 2014-01-01 and 2017-07-31)", xlab = "log(count pull requests per owner)") logplot(r_commit_count, title = "log-log plot of no commits to frequency per owner (considers all commits between 2014-01-01 and 2017-07-31)", xlab = "log(count commits per owner)") quantile(df1$comment_count, prob = c(0.8, 0.9, 0.98, 0.985, 0.99, 0.999)) quantile(df1$pull_request_count, prob = c(0.8, 0.9, 0.98, 0.985, 0.99, 0.999)) quantile(df2$commit_count, prob = c(0.8, 0.9, 0.98, 0.985, 0.99, 0.999)) # hist(df$count) summary(df1) summary(df2) boxplot_sample <- function(data, c_name, sample_factor){ df_sample <- data.frame(na.omit(data[, c_name])) sample_size = round(nrow(df_sample)*sample_factor) df_sample <- df_sample[sample(nrow(df_sample), sample_size), ] boxplot(df_sample, ylab = c_name, sub = paste( "population: ", toString(nrow(data)), "\nsample size: ", toString(sample_size), " (", toString(sample_factor*100),"%)" ), log = "y") } boxplot_sample(df1, "comment_count", 0.002) boxplot_sample(df1, "pull_request_count", 0.002) boxplot_sample(df2, "commit_count", 0.001) df3 = merge(x = df1, y = df2, by = "owner_id", all = TRUE) ############# filters lim_commit_count = 500 lim_pull_request_count = 100 lim_comment_count = 2000 df4 <- select(filter(df3, comment_count >= lim_comment_count), c(owner_id, comment_count, pull_request_count, commit_count)) df5 <- select(filter(df4, (pull_request_count >= lim_pull_request_count | commit_count >= lim_commit_count)), c(owner_id, comment_count, pull_request_count, commit_count)) boxplot(df5[,-1], log='y', ylab = 'count (log-transformed)', main = 'Distribution of the remaining owner data after applying selection criteria', sub = paste( 'remaining number of owners: ', toString(nrow(df5)), '(', toString(round(nrow(df5)/nrow(df3)*100, digits = 2)), '% of original data)', '\ncriteria: ', 'no commits >= ', toString(lim_commit_count), ' OR', ' no pull requests >= ', toString(lim_pull_request_count), 'AND', ' no comments >= ', toString(lim_comment_count)) ) df3_log = data.frame(commit_count = log(df3$commit_count), pull_request_count = log(df3$pull_request_count), comment_count = log(df3$comment_count)) plot(df3_log) r <- hist(na.omit(df3_log$commit_count)) plot(r$breaks[-1], r$counts, type='l', main = "Number of commits to owners on a log scale to frequency", sub = "considers data between 2014-01-01 and 2017-07-31", xlab = "log(count commits per owner)", ylab = "frequency") abline(v=log(lim_commit_count), lty = 2, col = 'blue')
/project_selection/180216_boxplots_comment_and_pullrequest_count.R
no_license
maxthemillion/gitNetAnalyzer
R
false
false
3,997
r
import_path = "Import/180216_no_comments_and_pull_requests_per_owner.csv" df1 = read.csv(import_path, header=TRUE, sep=",", stringsAsFactors = TRUE) import_path = "Import/180216_count_commits_per_owner.csv" df2 = read.csv(import_path, header=TRUE, sep=",", stringsAsFactors = TRUE) df1$comment_count_log = log(df1$comment_count) df1$pull_request_count_log = log(df1$pull_request_count) df2$commit_count_log = log(df2$commit_count) r_comment_count <- hist(df1$comment_count_log) r_pull_request_count <- hist(df1$pull_request_count_log) r_commit_count <- hist(df2$commit_count_log) logplot <- function(r, title, xlab){ plot(r$breaks[-1], r$counts, type='l', log = 'y', main = title, xlab = xlab, ylab = "log(frequency)") } logplot(r=r_comment_count, title="log-log plot of no comments to frequency per owner (considers all comments between 2014-01-01 and 2017-07-31)", xlab = "log(count comments per owner)") logplot(r_pull_request_count, title = "log-log plot of no pull_requests to frequency per owner (considers all pull_requtests between 2014-01-01 and 2017-07-31)", xlab = "log(count pull requests per owner)") logplot(r_commit_count, title = "log-log plot of no commits to frequency per owner (considers all commits between 2014-01-01 and 2017-07-31)", xlab = "log(count commits per owner)") quantile(df1$comment_count, prob = c(0.8, 0.9, 0.98, 0.985, 0.99, 0.999)) quantile(df1$pull_request_count, prob = c(0.8, 0.9, 0.98, 0.985, 0.99, 0.999)) quantile(df2$commit_count, prob = c(0.8, 0.9, 0.98, 0.985, 0.99, 0.999)) # hist(df$count) summary(df1) summary(df2) boxplot_sample <- function(data, c_name, sample_factor){ df_sample <- data.frame(na.omit(data[, c_name])) sample_size = round(nrow(df_sample)*sample_factor) df_sample <- df_sample[sample(nrow(df_sample), sample_size), ] boxplot(df_sample, ylab = c_name, sub = paste( "population: ", toString(nrow(data)), "\nsample size: ", toString(sample_size), " (", toString(sample_factor*100),"%)" ), log = "y") } boxplot_sample(df1, "comment_count", 0.002) boxplot_sample(df1, "pull_request_count", 0.002) boxplot_sample(df2, "commit_count", 0.001) df3 = merge(x = df1, y = df2, by = "owner_id", all = TRUE) ############# filters lim_commit_count = 500 lim_pull_request_count = 100 lim_comment_count = 2000 df4 <- select(filter(df3, comment_count >= lim_comment_count), c(owner_id, comment_count, pull_request_count, commit_count)) df5 <- select(filter(df4, (pull_request_count >= lim_pull_request_count | commit_count >= lim_commit_count)), c(owner_id, comment_count, pull_request_count, commit_count)) boxplot(df5[,-1], log='y', ylab = 'count (log-transformed)', main = 'Distribution of the remaining owner data after applying selection criteria', sub = paste( 'remaining number of owners: ', toString(nrow(df5)), '(', toString(round(nrow(df5)/nrow(df3)*100, digits = 2)), '% of original data)', '\ncriteria: ', 'no commits >= ', toString(lim_commit_count), ' OR', ' no pull requests >= ', toString(lim_pull_request_count), 'AND', ' no comments >= ', toString(lim_comment_count)) ) df3_log = data.frame(commit_count = log(df3$commit_count), pull_request_count = log(df3$pull_request_count), comment_count = log(df3$comment_count)) plot(df3_log) r <- hist(na.omit(df3_log$commit_count)) plot(r$breaks[-1], r$counts, type='l', main = "Number of commits to owners on a log scale to frequency", sub = "considers data between 2014-01-01 and 2017-07-31", xlab = "log(count commits per owner)", ylab = "frequency") abline(v=log(lim_commit_count), lty = 2, col = 'blue')
library(foreign) library(reshape2) library(rgdal) library(maptools) rm(list = ls()) # Set working directory setwd("D:\\Dropbox\\Fishing_effects_model\\to_maedhbh") gear = "all" ## Pelagic trawls: "PTR", Non-pelagic trawls: "NPT", Hook and line: "HAL", Jig: "JIG", Pots/traps: "POT" habFeature = "both" ## Keep "b":biological, "g": geological, or "both" if(habFeature == "both"){ habFeatToKeep = c("G", "B") }else{ habFeatToKeep = toupper(habFeature) } if(gear == "all"){ gearToKeep = c("PTR", "NPT", "HAL", "JIG", "POT") }else{ gearToKeep = toupper(gear) } ### Output file name year.now = substr(Sys.time(), 1,4) month.now = substr(Sys.time(), 6,7) day.now = substr(Sys.time(), 9,10) outFile = paste("disturbProps_deepSteep_", gear, "Gear_",habFeature, "Struct_", year.now, month.now, day.now, sep = "") # Import data grid5k = readOGR(dsn = "Fishing_effects_model.gdb", layer = "Grid5k") grid5k.dat = grid5k@data fe = read.csv("R_input_tables\\aggregated_fishing_effort_fake_data.csv") #fe = subset(fe, YEAR <2016) ## CIA only goes through June of 2015 gt = read.csv("R_input_tables\\GearWidthTable_022316.csv") recovery_table = read.csv("R_input_tables\\Recovery_table_DeepCorals.csv") ### Convert total fishing to contact adjusted fe = merge(fe, gt[,c("GearID", "Gear", "SASI_gear", "adjLow","adjMed", "adjHigh")], by.x = "GEARID", by.y = "GearID", all.x = T) ## Gear mods fe[fe$GEARID %in% 45:53 & fe$YEAR < 2011, ]$adjLow = 1 # Pre 2011 gear change fe[fe$GEARID %in% 45:53 & fe$YEAR < 2011, ]$adjMed = 1 fe[fe$GEARID %in% 45:53 & fe$YEAR < 2011, ]$adjHigh = 1 fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR < 2014, ]$adjLow = 1 # Pre Feb 2014 gear change fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR < 2014, ]$adjMed = 1 fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR < 2014, ]$adjHigh = 1 ## None of these gears in Jan 2014 #fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR == 2014 & fe$MONTH == 1, ]$adjLow = 1 # Pre Feb 2014 gear change #fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR == 2014 & fe$MONTH == 1, ]$adjMed = 1 #fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR == 2014 & fe$MONTH == 1, ]$adjHigh = 1 fe[!(fe$Gear %in% gearToKeep), ]$SUM_Shape_ = 0 # Change area of gears not interested in keeping to zero fe$adjArea = fe$SUM_Shape_ * runif(nrow(fe), min = fe$adjLow, max = fe$adjHigh) ## Random uniform contact adj from min and max ## aggregate fishing adjusted fishing effort fe.agg = aggregate(adjArea ~ Grid5k_ID + YEAR + MONTH + SASI_gear, data = fe, sum) grid_order = sort(unique(fe$Grid5k_ID)) # Sediment sed = read.dbf("R_input_tables\\sediment_v4_deepCorals.dbf") # Create sediment matrix for model. Make sure grid order is same as I_a # and keep only sediment areas sedProps = as.matrix(sed[match(grid_order, sed$Grid5k_ID), c("mudProp","sandProp","grpeProp","cobProp","bouldProp", "deepProp") ]) subst_types = c("Mud", "Sand", "Gran.Peb", "Cobble", "Boulder", "DeepSteep") SASI_gears = c("trawl", "longline", "trap") # Set parameters nYears = length(unique(fe$YEAR)) nSubAnnual = 12 nGrid = length(unique(fe$Grid5k_ID)) nGear = 3 # Number of SASI gears: Trawl, Trap, Longline nSubst = ncol(sedProps) #Number of substrates gear_types = levels(fe$SASI_gear) eg = expand.grid(Grid5k_ID=unique(fe$Grid5k_ID), SASI_gear=unique(fe$SASI_gear)) # create all combos of gear and grid cells m = merge(grid5k.dat, fe.agg, by = "Grid5k_ID") m$prop = m$adjAre/m$Shape_Area m$MONTH = as.numeric(as.character(m$MONTH)) # Populate Fishing effort array F_a = array(NA, dim = c(nYears, nSubAnnual, nGrid, nGear)) #create empty array year.i = 1 # year index counter for(year in min(m$YEAR):max(m$YEAR)){ my = subset(m, YEAR == year) for(month.i in 1:12){ mym = subset(my, MONTH==month.i) mym = merge(x = eg, y = mym, by.x = c("Grid5k_ID","SASI_gear"), by.y = c("Grid5k_ID", "SASI_gear"), all.x=T) mym[is.na(mym$prop),]$prop = 0 mym.x = dcast(Grid5k_ID ~ SASI_gear, data=mym, value.var = "prop", fun.aggregate = function(x) sum(x)) mym.x = mym.x[order(mym.x$Grid5k_ID),] mym.x = mym.x[,c(gear_types)] F_a[year.i, month.i, ,] = as.matrix(mym.x) } year.i = year.i + 1 } # Suceptibility suscept.f = function(){ gear.q = matrix(NA, nrow = nGear, ncol = nSubst) i = 1 for(gear in SASI_gears){ gear.m = read.csv(paste("R_input_tables\\Susceptibilty_table_deepCoral_", gear, ".csv", sep="")) gear.m = subset(gear.m, FeatureClass %in% habFeatToKeep) ## Choose geological or biological features gear.m = gear.m[,subst_types] for(column in 1:ncol(gear.m)){ gear.m[gear.m[,column] %in% 0, column] = runif(sum(gear.m[,column] %in% 0), min = 0, max = 0.1) gear.m[gear.m[,column] %in% 1, column] = runif(sum(gear.m[,column] %in% 1), min = 0.1, max = 0.25) gear.m[gear.m[,column] %in% 2, column] = runif(sum(gear.m[,column] %in% 2), min = 0.25, max = 0.5) gear.m[gear.m[,column] %in% 3, column] = runif(sum(gear.m[,column] %in% 3), min = 0.5, max = 1) } gear.q[i,] = colMeans(gear.m, na.rm=T) i = i + 1 } gear.q.df = data.frame(SASI_gear = SASI_gears, gear.q) names(gear.q.df)[-1] = subst_types q_m = as.matrix(gear.q.df[,subst_types]) return(q_m) } #Fishing impacts (I') I.prime_a = array(NA, dim = c(nYears, nSubAnnual, nGrid, nSubst)) for(y in 1:nYears){ for(m in 1:nSubAnnual){ q_m = suscept.f() # Get new susceptibility table for each month I_m = F_a[y,m,,] %*% q_m I.prime_a[y,m,,] = 1-exp(-I_m) } } # Recovery (rho') recovery_table = recovery_table[,subst_types] tau_m = recovery_table[,subst_types] # Make sure sediments are in correct order recovery.f = function(){ for(column in 1:ncol(tau_m)){ tau_m[recovery_table[,column] %in% 0, column] = runif(sum(tau_m[,column] %in% 0), min = 0, max = 1) tau_m[recovery_table[,column] %in% 1, column] = runif(sum(tau_m[,column] %in% 1), min = 1, max = 2) tau_m[recovery_table[,column] %in% 2, column] = runif(sum(tau_m[,column] %in% 2), min = 2, max = 5) tau_m[recovery_table[,column] %in% 3, column] = runif(sum(tau_m[,column] %in% 3), min = 5, max = 10) tau_m[recovery_table[,column] %in% 4, column] = runif(sum(tau_m[,column] %in% 4), min = 10, max = 50) } tau_v = colMeans(tau_m, na.rm=T) # Average recovery over all habitat features rho_v = 1 / (tau_v * nSubAnnual) # Convert recovery time in years to rates per month return(rho_v) } rho.prime_a = array(NA, dim = c(nYears, nSubAnnual, nGrid, nSubst)) for(y in 1:nYears){ for(m in 1:nSubAnnual){ rho_v = recovery.f() # Get new recovery values for each month for(i in 1:nGrid){ rho.prime_a[y,m,i,] = 1-exp(-rho_v) } } } # Fishing Effects Model function FishingEffectsModel = function(I.prime_a, rho.prime_a, H_prop_0){ model_nYears = dim(I.prime_a)[1] model_nSubAnnual = dim(I.prime_a)[2] model_nGrid = dim(I.prime_a)[3] model_nSubst = dim(I.prime_a)[4] #Make array to hold H H_prop = array(dim = c(model_nYears, model_nSubAnnual, model_nGrid, model_nSubst)) for(y in 1:model_nYears){ for(m in 1:model_nSubAnnual){ if(y == 1 & m == 1){ # First time step use H_prop_0 for t-1 prior_state = H_prop_0 } else if (m == 1){ prior_state = H_prop[y-1,model_nSubAnnual,,] } else{ prior_state = H_prop[y,m-1,,] } H_from_H = (1-I.prime_a[y,m,,])*prior_state # undisturbed remaining undisturbed H_from_h = (1-prior_state) * (rho.prime_a[y,m,,]) # disturbed recovered to undisturbed H_prop[y,m,,] = H_from_H + H_from_h # Total proportion disturbed } } return(H_prop) } # end function ##### Run model with H =burnin initial conditions # Define five year burnin in H_prop_0 = matrix(runif(nGrid*nSubst, 0,1), nrow = nGrid, ncol = nSubst) # First start with random conditions # Cycle through 2003-2005 ten times to create burnin starting conditions for(i in 1:10){ H_burn = FishingEffectsModel(I.prime_a[1:3,,,], rho.prime_a[1:3,,,], H_prop_0) H_prop_0 = H_burn[3,12,,] # extract only the last time step as the new intial condition } ##### Run model H_tot = FishingEffectsModel(I.prime_a, rho.prime_a, H_prop_0) # Calculate undisturbed Areas fished_cells = grid5k.dat[match(grid_order, grid5k.dat$Grid5k_ID), ] undistProps = matrix(NA, ncol = nSubAnnual*nYears, nrow = length(grid_order)) i = 1 for(y in 1:nYears){ for(m in 1:12){ undistProps[,i] = rowSums(H_tot[y,m,,]*sedProps) i = i + 1 } } undistProps = data.frame(Grid5k_ID = grid_order, undistProps) disturbProps = data.frame(Grid5k_ID = undistProps[,1], apply(undistProps[,-1],2, function(x) 1 - x)) ## Write results to a shapefile grid5k@data$orderID = 1:nrow(grid5k@data) grid5k_results = grid5k@data grid5k_results = merge(grid5k_results, disturbProps, by = "Grid5k_ID", all.x = T) months = c("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec") counter = 6 # Start counter at first column that has disturbAreas for(y in 2003:2016){ for(m in 1:12){ names(grid5k_results)[counter] = paste(months[m], y, sep = "") counter = counter + 1 } } dist.out = grid5k dist.out@data = grid5k_results[order(grid5k_results$orderID),] ## Create file name and write it to output writeSpatialShape(dist.out, paste("FE_model_output\\", outFile, ".shp", sep = ""))
/Fishing_effects_model_102716.R
no_license
pipelino93/Fishing_Effects_Model
R
false
false
10,079
r
library(foreign) library(reshape2) library(rgdal) library(maptools) rm(list = ls()) # Set working directory setwd("D:\\Dropbox\\Fishing_effects_model\\to_maedhbh") gear = "all" ## Pelagic trawls: "PTR", Non-pelagic trawls: "NPT", Hook and line: "HAL", Jig: "JIG", Pots/traps: "POT" habFeature = "both" ## Keep "b":biological, "g": geological, or "both" if(habFeature == "both"){ habFeatToKeep = c("G", "B") }else{ habFeatToKeep = toupper(habFeature) } if(gear == "all"){ gearToKeep = c("PTR", "NPT", "HAL", "JIG", "POT") }else{ gearToKeep = toupper(gear) } ### Output file name year.now = substr(Sys.time(), 1,4) month.now = substr(Sys.time(), 6,7) day.now = substr(Sys.time(), 9,10) outFile = paste("disturbProps_deepSteep_", gear, "Gear_",habFeature, "Struct_", year.now, month.now, day.now, sep = "") # Import data grid5k = readOGR(dsn = "Fishing_effects_model.gdb", layer = "Grid5k") grid5k.dat = grid5k@data fe = read.csv("R_input_tables\\aggregated_fishing_effort_fake_data.csv") #fe = subset(fe, YEAR <2016) ## CIA only goes through June of 2015 gt = read.csv("R_input_tables\\GearWidthTable_022316.csv") recovery_table = read.csv("R_input_tables\\Recovery_table_DeepCorals.csv") ### Convert total fishing to contact adjusted fe = merge(fe, gt[,c("GearID", "Gear", "SASI_gear", "adjLow","adjMed", "adjHigh")], by.x = "GEARID", by.y = "GearID", all.x = T) ## Gear mods fe[fe$GEARID %in% 45:53 & fe$YEAR < 2011, ]$adjLow = 1 # Pre 2011 gear change fe[fe$GEARID %in% 45:53 & fe$YEAR < 2011, ]$adjMed = 1 fe[fe$GEARID %in% 45:53 & fe$YEAR < 2011, ]$adjHigh = 1 fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR < 2014, ]$adjLow = 1 # Pre Feb 2014 gear change fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR < 2014, ]$adjMed = 1 fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR < 2014, ]$adjHigh = 1 ## None of these gears in Jan 2014 #fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR == 2014 & fe$MONTH == 1, ]$adjLow = 1 # Pre Feb 2014 gear change #fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR == 2014 & fe$MONTH == 1, ]$adjMed = 1 #fe[fe$GEARID %in% c(6,7,9,10) & fe$YEAR == 2014 & fe$MONTH == 1, ]$adjHigh = 1 fe[!(fe$Gear %in% gearToKeep), ]$SUM_Shape_ = 0 # Change area of gears not interested in keeping to zero fe$adjArea = fe$SUM_Shape_ * runif(nrow(fe), min = fe$adjLow, max = fe$adjHigh) ## Random uniform contact adj from min and max ## aggregate fishing adjusted fishing effort fe.agg = aggregate(adjArea ~ Grid5k_ID + YEAR + MONTH + SASI_gear, data = fe, sum) grid_order = sort(unique(fe$Grid5k_ID)) # Sediment sed = read.dbf("R_input_tables\\sediment_v4_deepCorals.dbf") # Create sediment matrix for model. Make sure grid order is same as I_a # and keep only sediment areas sedProps = as.matrix(sed[match(grid_order, sed$Grid5k_ID), c("mudProp","sandProp","grpeProp","cobProp","bouldProp", "deepProp") ]) subst_types = c("Mud", "Sand", "Gran.Peb", "Cobble", "Boulder", "DeepSteep") SASI_gears = c("trawl", "longline", "trap") # Set parameters nYears = length(unique(fe$YEAR)) nSubAnnual = 12 nGrid = length(unique(fe$Grid5k_ID)) nGear = 3 # Number of SASI gears: Trawl, Trap, Longline nSubst = ncol(sedProps) #Number of substrates gear_types = levels(fe$SASI_gear) eg = expand.grid(Grid5k_ID=unique(fe$Grid5k_ID), SASI_gear=unique(fe$SASI_gear)) # create all combos of gear and grid cells m = merge(grid5k.dat, fe.agg, by = "Grid5k_ID") m$prop = m$adjAre/m$Shape_Area m$MONTH = as.numeric(as.character(m$MONTH)) # Populate Fishing effort array F_a = array(NA, dim = c(nYears, nSubAnnual, nGrid, nGear)) #create empty array year.i = 1 # year index counter for(year in min(m$YEAR):max(m$YEAR)){ my = subset(m, YEAR == year) for(month.i in 1:12){ mym = subset(my, MONTH==month.i) mym = merge(x = eg, y = mym, by.x = c("Grid5k_ID","SASI_gear"), by.y = c("Grid5k_ID", "SASI_gear"), all.x=T) mym[is.na(mym$prop),]$prop = 0 mym.x = dcast(Grid5k_ID ~ SASI_gear, data=mym, value.var = "prop", fun.aggregate = function(x) sum(x)) mym.x = mym.x[order(mym.x$Grid5k_ID),] mym.x = mym.x[,c(gear_types)] F_a[year.i, month.i, ,] = as.matrix(mym.x) } year.i = year.i + 1 } # Suceptibility suscept.f = function(){ gear.q = matrix(NA, nrow = nGear, ncol = nSubst) i = 1 for(gear in SASI_gears){ gear.m = read.csv(paste("R_input_tables\\Susceptibilty_table_deepCoral_", gear, ".csv", sep="")) gear.m = subset(gear.m, FeatureClass %in% habFeatToKeep) ## Choose geological or biological features gear.m = gear.m[,subst_types] for(column in 1:ncol(gear.m)){ gear.m[gear.m[,column] %in% 0, column] = runif(sum(gear.m[,column] %in% 0), min = 0, max = 0.1) gear.m[gear.m[,column] %in% 1, column] = runif(sum(gear.m[,column] %in% 1), min = 0.1, max = 0.25) gear.m[gear.m[,column] %in% 2, column] = runif(sum(gear.m[,column] %in% 2), min = 0.25, max = 0.5) gear.m[gear.m[,column] %in% 3, column] = runif(sum(gear.m[,column] %in% 3), min = 0.5, max = 1) } gear.q[i,] = colMeans(gear.m, na.rm=T) i = i + 1 } gear.q.df = data.frame(SASI_gear = SASI_gears, gear.q) names(gear.q.df)[-1] = subst_types q_m = as.matrix(gear.q.df[,subst_types]) return(q_m) } #Fishing impacts (I') I.prime_a = array(NA, dim = c(nYears, nSubAnnual, nGrid, nSubst)) for(y in 1:nYears){ for(m in 1:nSubAnnual){ q_m = suscept.f() # Get new susceptibility table for each month I_m = F_a[y,m,,] %*% q_m I.prime_a[y,m,,] = 1-exp(-I_m) } } # Recovery (rho') recovery_table = recovery_table[,subst_types] tau_m = recovery_table[,subst_types] # Make sure sediments are in correct order recovery.f = function(){ for(column in 1:ncol(tau_m)){ tau_m[recovery_table[,column] %in% 0, column] = runif(sum(tau_m[,column] %in% 0), min = 0, max = 1) tau_m[recovery_table[,column] %in% 1, column] = runif(sum(tau_m[,column] %in% 1), min = 1, max = 2) tau_m[recovery_table[,column] %in% 2, column] = runif(sum(tau_m[,column] %in% 2), min = 2, max = 5) tau_m[recovery_table[,column] %in% 3, column] = runif(sum(tau_m[,column] %in% 3), min = 5, max = 10) tau_m[recovery_table[,column] %in% 4, column] = runif(sum(tau_m[,column] %in% 4), min = 10, max = 50) } tau_v = colMeans(tau_m, na.rm=T) # Average recovery over all habitat features rho_v = 1 / (tau_v * nSubAnnual) # Convert recovery time in years to rates per month return(rho_v) } rho.prime_a = array(NA, dim = c(nYears, nSubAnnual, nGrid, nSubst)) for(y in 1:nYears){ for(m in 1:nSubAnnual){ rho_v = recovery.f() # Get new recovery values for each month for(i in 1:nGrid){ rho.prime_a[y,m,i,] = 1-exp(-rho_v) } } } # Fishing Effects Model function FishingEffectsModel = function(I.prime_a, rho.prime_a, H_prop_0){ model_nYears = dim(I.prime_a)[1] model_nSubAnnual = dim(I.prime_a)[2] model_nGrid = dim(I.prime_a)[3] model_nSubst = dim(I.prime_a)[4] #Make array to hold H H_prop = array(dim = c(model_nYears, model_nSubAnnual, model_nGrid, model_nSubst)) for(y in 1:model_nYears){ for(m in 1:model_nSubAnnual){ if(y == 1 & m == 1){ # First time step use H_prop_0 for t-1 prior_state = H_prop_0 } else if (m == 1){ prior_state = H_prop[y-1,model_nSubAnnual,,] } else{ prior_state = H_prop[y,m-1,,] } H_from_H = (1-I.prime_a[y,m,,])*prior_state # undisturbed remaining undisturbed H_from_h = (1-prior_state) * (rho.prime_a[y,m,,]) # disturbed recovered to undisturbed H_prop[y,m,,] = H_from_H + H_from_h # Total proportion disturbed } } return(H_prop) } # end function ##### Run model with H =burnin initial conditions # Define five year burnin in H_prop_0 = matrix(runif(nGrid*nSubst, 0,1), nrow = nGrid, ncol = nSubst) # First start with random conditions # Cycle through 2003-2005 ten times to create burnin starting conditions for(i in 1:10){ H_burn = FishingEffectsModel(I.prime_a[1:3,,,], rho.prime_a[1:3,,,], H_prop_0) H_prop_0 = H_burn[3,12,,] # extract only the last time step as the new intial condition } ##### Run model H_tot = FishingEffectsModel(I.prime_a, rho.prime_a, H_prop_0) # Calculate undisturbed Areas fished_cells = grid5k.dat[match(grid_order, grid5k.dat$Grid5k_ID), ] undistProps = matrix(NA, ncol = nSubAnnual*nYears, nrow = length(grid_order)) i = 1 for(y in 1:nYears){ for(m in 1:12){ undistProps[,i] = rowSums(H_tot[y,m,,]*sedProps) i = i + 1 } } undistProps = data.frame(Grid5k_ID = grid_order, undistProps) disturbProps = data.frame(Grid5k_ID = undistProps[,1], apply(undistProps[,-1],2, function(x) 1 - x)) ## Write results to a shapefile grid5k@data$orderID = 1:nrow(grid5k@data) grid5k_results = grid5k@data grid5k_results = merge(grid5k_results, disturbProps, by = "Grid5k_ID", all.x = T) months = c("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec") counter = 6 # Start counter at first column that has disturbAreas for(y in 2003:2016){ for(m in 1:12){ names(grid5k_results)[counter] = paste(months[m], y, sep = "") counter = counter + 1 } } dist.out = grid5k dist.out@data = grid5k_results[order(grid5k_results$orderID),] ## Create file name and write it to output writeSpatialShape(dist.out, paste("FE_model_output\\", outFile, ".shp", sep = ""))
# Normalize a table of ascents into ascent, page and route tables. # Copyright 2019, 2020 Dean Scarff # # 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. # Make sure to source("00-data_prep_functions.R") before sourcing this script. period_length <- 604800 # seconds in 1 week # Read in the ascents table. df_raw <- read.csv( file.path(data_dir, "raw_ascents.csv"), comment.char = "#", colClasses = c( ascentId = "character", route = "factor", climber = "factor", tick = "factor", grade = "integer", timestamp = "integer" ) ) df_clean <- CleanAscents(df_raw) message(SummarizeAscents(df_clean)) dfs <- NormalizeTables(df_clean, period_length) dfs$routes <- mutate(dfs$routes, gamma = TransformGrade(grade)) WriteNormalizedTables(dfs, data_dir)
/01-data_prep.R
permissive
scottwedge/climbing_ratings
R
false
false
1,275
r
# Normalize a table of ascents into ascent, page and route tables. # Copyright 2019, 2020 Dean Scarff # # 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. # Make sure to source("00-data_prep_functions.R") before sourcing this script. period_length <- 604800 # seconds in 1 week # Read in the ascents table. df_raw <- read.csv( file.path(data_dir, "raw_ascents.csv"), comment.char = "#", colClasses = c( ascentId = "character", route = "factor", climber = "factor", tick = "factor", grade = "integer", timestamp = "integer" ) ) df_clean <- CleanAscents(df_raw) message(SummarizeAscents(df_clean)) dfs <- NormalizeTables(df_clean, period_length) dfs$routes <- mutate(dfs$routes, gamma = TransformGrade(grade)) WriteNormalizedTables(dfs, data_dir)
if(!require(gdalUtils)){install.packages("gdalUtils"); library(gdalUtils)} # sostituire library(rgdal) library(raster) library(rgeos) library(spsann) library(sp) library(ICSNP) library(velox) library(spcosa) library(spatstat) library(dplyr) library(tibble) library(tidyr) library(geosphere) library(Rfast) sampleboost <- function(x, ignorance, boundary, nplot, radius, perm, quant){ ndvi.vx <-velox(x) igno.vx <- velox(ignorance) result<-list() distanze<-matrix(ncol=1, nrow = perm) pb <- txtProgressBar(min = 0, max = perm, style = 3) for (i in 1:perm){ punti_random <- spsample(boundary, n=nplot, type='random') sampling_points <- as(punti_random, "data.frame") xy <- sampling_points[,c(1,2)] spdf <- SpatialPointsDataFrame(coords = xy, data = sampling_points, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")) spols <- gBuffer(spgeom=spdf, width=radius, byid=TRUE) estratti <- data.frame(coordinates(spdf), ndvi.vx$extract(sp=spols, fun=median)) names(estratti) <- c("x", "y", "ndvi") estratti$ignorance <- igno.vx$extract(sp=spols, fun=median) result[[i]]<-data.frame(estratti) dataset_points <- cbind(xy, ID = 1:NROW(xy)) pairwise_distances <- distm(dataset_points[,1:2]) distanze[[i]] <- total.dist(pairwise_distances, method = "euclidean", square = FALSE, p = 0) setTxtProgressBar(pb, i) } new_mat<-plyr::ldply(result, data.frame) new_mat$try<-as.factor(rep(1:perm, each= nplot)) agg1<-aggregate(new_mat$ndvi,by=list(new_mat$try),FUN=var) agg_igno<-aggregate(new_mat$ignorance,by=list(new_mat$try),FUN=mean) agg2<-data.frame(agg1,distanze,agg_igno[[2]]) colnames(agg2)<-c('Try','Variance','Mean Dist', 'Mean Ignorance') agg2 <- na.omit(agg2) agg3 <- agg2[agg2$Variance > quantile(agg2$Variance, quant),] ordered_solutions <- agg3[order(agg3[,'Mean Dist'], decreasing = TRUE),] best <- ordered_solutions[order(ordered_solutions[,3], decreasing = TRUE),] Index <- as.numeric(best[1,1]) sol <- subset(new_mat[new_mat$try %in% Index,]) sol2 <- subset(agg2[agg2$Try %in% Index,]) return(list("Full matrix"=new_mat, "Aggregated matrix"=agg2, "Best"= sol, "Variance of sampling points"=sol2[,'Variance'], "Spatial Median of Distance"= sol2[,'Mean Dist'])) ## Plot best solution xy_out1 <- out1$Best[,c(1,2)] out1_points <- SpatialPointsDataFrame(coords = xy_out1, data = out1$Best, proj4string = crs(boundary)) p <- rasterVis::levelplot(x, layers=1, margin = list(FUN = median))+ latticeExtra::layer(sp.points(out1_points, lwd= 0.8, col='darkgray')) p2 <- rasterVis::levelplot(mfi2, layers=1, margin = list(FUN = median))+ latticeExtra::layer(sp.points(out1_points, lwd= 0.8, col='darkgray')) p3 <- ggplot(out1$`Full matrix`, aes(x = ndvi, group = try)) + geom_density(colour = "lightgrey")+ theme(legend.position = "none")+ geom_density(data = out1$Best, aes(x = ndvi, colour = "red")) print(p) print(p2) print(p3) } out1 <- sampleboost(x=ndvi_clip, ignorance = ignorance_map, nplot= 9, radius=0.2, quant = 0.99, perm = 1000, boundary=area_studio) out1 ##### PLOTTO LA SOLUZIONE OUT1, BEST SOLUTION xy_out1 <- out1$Best[,c(1,2)] out1_points <- SpatialPointsDataFrame(coords = xy_out1, data = out1$Best, proj4string = CRS("+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")) plot(ndvi_clip) plot(site, add=TRUE) plot(out1_points, add=TRUE) sp::plot(site) sp::plot(mfi2, add=TRUE) sp::plot(out1_points, add=TRUE) plot(mfi2) plot(mystratification@centroids, add=TRUE, col="red") #### Ordino per valori decrescenti di varianza con il quantile 0.99 ######### out1 <- tent6 out_filter <- na.omit(out1$`Aggregated matrix`) out_new <- out_filter[out_filter$Variance > quantile(out_filter$Variance, quantile_threshold),] ordered_solutions <- out_new[order(out_new[,2], decreasing = TRUE),] ordered_solutions_2 <- ordered_solutions[order(ordered_solutions[,3], decreasing = TRUE),] head(ordered_solutions_2, 10) ######################################################################## ####### Plotto la soluzione scelta ##################################### prova <- out1$`Full matrix`[is.element(out1$`Full matrix`$try, 3313),] xy_prova <- prova[,c(1,2)] prova_points <- SpatialPointsDataFrame(coords = xy_prova, data = prova, proj4string = CRS("+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")) plot(ndvi_clip) #plotRGB(rgb_crop, r= 1, g= 2, b = 3, stretch = "lin") plot(area_studio, add=TRUE) plot(prova_points, add=TRUE, col="black") ############################## REFERENCE_SYSTEM <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" file_export <- spTransform(prova_points, crs(REFERENCE_SYSTEM)) #### salvo il csv ---- rinominare il file write.csv(file_export, "Sampling points_a.csv", row.names = TRUE) saveRDS(out1, file = "Sampling points_a.rds") a <- df %>% column_to_rownames("ID") %>% #make the ID the rownames. dist will use these> NB will not work on a tibble dist() %>% as.matrix() %>% as.data.frame() %>% rownames_to_column(var = "ID.x") %>% #capture the row IDs gather(key = ID.y, value = dist, -ID.x) %>% filter(ID.x < ID.y) %>% as_tibble() a <-as.data.frame(a) distance <- sum(a$dist)
/Sampling code_con buffers.R
no_license
interacquas/Optmised-sampling
R
false
false
5,519
r
if(!require(gdalUtils)){install.packages("gdalUtils"); library(gdalUtils)} # sostituire library(rgdal) library(raster) library(rgeos) library(spsann) library(sp) library(ICSNP) library(velox) library(spcosa) library(spatstat) library(dplyr) library(tibble) library(tidyr) library(geosphere) library(Rfast) sampleboost <- function(x, ignorance, boundary, nplot, radius, perm, quant){ ndvi.vx <-velox(x) igno.vx <- velox(ignorance) result<-list() distanze<-matrix(ncol=1, nrow = perm) pb <- txtProgressBar(min = 0, max = perm, style = 3) for (i in 1:perm){ punti_random <- spsample(boundary, n=nplot, type='random') sampling_points <- as(punti_random, "data.frame") xy <- sampling_points[,c(1,2)] spdf <- SpatialPointsDataFrame(coords = xy, data = sampling_points, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")) spols <- gBuffer(spgeom=spdf, width=radius, byid=TRUE) estratti <- data.frame(coordinates(spdf), ndvi.vx$extract(sp=spols, fun=median)) names(estratti) <- c("x", "y", "ndvi") estratti$ignorance <- igno.vx$extract(sp=spols, fun=median) result[[i]]<-data.frame(estratti) dataset_points <- cbind(xy, ID = 1:NROW(xy)) pairwise_distances <- distm(dataset_points[,1:2]) distanze[[i]] <- total.dist(pairwise_distances, method = "euclidean", square = FALSE, p = 0) setTxtProgressBar(pb, i) } new_mat<-plyr::ldply(result, data.frame) new_mat$try<-as.factor(rep(1:perm, each= nplot)) agg1<-aggregate(new_mat$ndvi,by=list(new_mat$try),FUN=var) agg_igno<-aggregate(new_mat$ignorance,by=list(new_mat$try),FUN=mean) agg2<-data.frame(agg1,distanze,agg_igno[[2]]) colnames(agg2)<-c('Try','Variance','Mean Dist', 'Mean Ignorance') agg2 <- na.omit(agg2) agg3 <- agg2[agg2$Variance > quantile(agg2$Variance, quant),] ordered_solutions <- agg3[order(agg3[,'Mean Dist'], decreasing = TRUE),] best <- ordered_solutions[order(ordered_solutions[,3], decreasing = TRUE),] Index <- as.numeric(best[1,1]) sol <- subset(new_mat[new_mat$try %in% Index,]) sol2 <- subset(agg2[agg2$Try %in% Index,]) return(list("Full matrix"=new_mat, "Aggregated matrix"=agg2, "Best"= sol, "Variance of sampling points"=sol2[,'Variance'], "Spatial Median of Distance"= sol2[,'Mean Dist'])) ## Plot best solution xy_out1 <- out1$Best[,c(1,2)] out1_points <- SpatialPointsDataFrame(coords = xy_out1, data = out1$Best, proj4string = crs(boundary)) p <- rasterVis::levelplot(x, layers=1, margin = list(FUN = median))+ latticeExtra::layer(sp.points(out1_points, lwd= 0.8, col='darkgray')) p2 <- rasterVis::levelplot(mfi2, layers=1, margin = list(FUN = median))+ latticeExtra::layer(sp.points(out1_points, lwd= 0.8, col='darkgray')) p3 <- ggplot(out1$`Full matrix`, aes(x = ndvi, group = try)) + geom_density(colour = "lightgrey")+ theme(legend.position = "none")+ geom_density(data = out1$Best, aes(x = ndvi, colour = "red")) print(p) print(p2) print(p3) } out1 <- sampleboost(x=ndvi_clip, ignorance = ignorance_map, nplot= 9, radius=0.2, quant = 0.99, perm = 1000, boundary=area_studio) out1 ##### PLOTTO LA SOLUZIONE OUT1, BEST SOLUTION xy_out1 <- out1$Best[,c(1,2)] out1_points <- SpatialPointsDataFrame(coords = xy_out1, data = out1$Best, proj4string = CRS("+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")) plot(ndvi_clip) plot(site, add=TRUE) plot(out1_points, add=TRUE) sp::plot(site) sp::plot(mfi2, add=TRUE) sp::plot(out1_points, add=TRUE) plot(mfi2) plot(mystratification@centroids, add=TRUE, col="red") #### Ordino per valori decrescenti di varianza con il quantile 0.99 ######### out1 <- tent6 out_filter <- na.omit(out1$`Aggregated matrix`) out_new <- out_filter[out_filter$Variance > quantile(out_filter$Variance, quantile_threshold),] ordered_solutions <- out_new[order(out_new[,2], decreasing = TRUE),] ordered_solutions_2 <- ordered_solutions[order(ordered_solutions[,3], decreasing = TRUE),] head(ordered_solutions_2, 10) ######################################################################## ####### Plotto la soluzione scelta ##################################### prova <- out1$`Full matrix`[is.element(out1$`Full matrix`$try, 3313),] xy_prova <- prova[,c(1,2)] prova_points <- SpatialPointsDataFrame(coords = xy_prova, data = prova, proj4string = CRS("+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")) plot(ndvi_clip) #plotRGB(rgb_crop, r= 1, g= 2, b = 3, stretch = "lin") plot(area_studio, add=TRUE) plot(prova_points, add=TRUE, col="black") ############################## REFERENCE_SYSTEM <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" file_export <- spTransform(prova_points, crs(REFERENCE_SYSTEM)) #### salvo il csv ---- rinominare il file write.csv(file_export, "Sampling points_a.csv", row.names = TRUE) saveRDS(out1, file = "Sampling points_a.rds") a <- df %>% column_to_rownames("ID") %>% #make the ID the rownames. dist will use these> NB will not work on a tibble dist() %>% as.matrix() %>% as.data.frame() %>% rownames_to_column(var = "ID.x") %>% #capture the row IDs gather(key = ID.y, value = dist, -ID.x) %>% filter(ID.x < ID.y) %>% as_tibble() a <-as.data.frame(a) distance <- sum(a$dist)
# Clear variables and close windows rm(list = ls(all = TRUE)) graphics.off() # Please change working directory setwd('C:/...') data <- read.delim2("SP1997-2005s.txt") time <- (1:length(data[, 1])) dat0 <- data[, 1] - c(mean(data[, 1])) dat0 <- dat0/sd(dat0) timet <- (time - 1078)/250 + 2001 plot(timet[time >= 1075], dat0[time >= 1075], xaxp = c(2001, 2005, 4), xlab = "Time", ylab = "Log-returns", type = "l")
/STF2tvch01/STF2tvch01.R
no_license
QuantLet/STF
R
false
false
417
r
# Clear variables and close windows rm(list = ls(all = TRUE)) graphics.off() # Please change working directory setwd('C:/...') data <- read.delim2("SP1997-2005s.txt") time <- (1:length(data[, 1])) dat0 <- data[, 1] - c(mean(data[, 1])) dat0 <- dat0/sd(dat0) timet <- (time - 1078)/250 + 2001 plot(timet[time >= 1075], dat0[time >= 1075], xaxp = c(2001, 2005, 4), xlab = "Time", ylab = "Log-returns", type = "l")
# sapply() takes the same arguments as lapply but tries to simplify the result # into a vector or matrix. # If this is not possible, it returns the same result as lapply() # This is the structure of temp: > str(temp) List of 7 $ : num [1:5] 3 7 9 6 -1 $ : num [1:5] 6 9 12 13 5 $ : num [1:5] 4 8 3 -1 -3 $ : num [1:5] 1 4 7 2 -2 $ : num [1:5] 5 7 9 4 2 $ : num [1:5] -3 5 8 9 4 $ : num [1:5] 3 6 9 4 1 # Define a function extremes_avg <- function(x) { ( min(x) + max(x) ) / 2 } # Apply extremes_avg() over temp using sapply() > sapply(temp, extremes_avg) [1] 4.0 9.0 2.5 2.5 5.5 3.0 5.0 # Notice that this is the same as: > unlist(lapply(temp, extremes_avg)) [1] 4.0 9.0 2.5 2.5 5.5 3.0 5.0 # In the previous example, we have seen that sapply simplifies the result into a vector. # If the function passed to sapply() returns a vector of length > 1, then a matrix is returned: extremes <- function(x) { c(min = min(x), max = max(x)) } > sapply(temp, extremes) [,1] [,2] [,3] [,4] [,5] [,6] [,7] min -1 5 -3 -2 2 -3 1 max 9 13 8 7 9 9 9 # If sapply cannot simplify the result into a meaningful vector or matrix, then it returs the # same output as lapply: below_zero <- function(x) { return(x[x < 0]) } freezing_s <- sapply(temp, below_zero) # Apply below_zero over temp using lapply(): freezing_l freezing_l <- lapply(temp, below_zero) # Are freezing_s and freezing_l identical? > identical(freezing_s, freezing_l) [1] TRUE # Finally, here is an example demonstrating sapply()'s power: > sapply(list(runif (10), runif (10)), + function(x) c(min = min(x), mean = mean(x), max = max(x))) [,1] [,2] min 0.01998662 0.07075416 mean 0.50691288 0.58029329 max 0.98786178 0.93855891
/R/R_Apply_Family/1.sapply.R
no_license
MrfksIv/R_Python_Tutorials
R
false
false
1,768
r
# sapply() takes the same arguments as lapply but tries to simplify the result # into a vector or matrix. # If this is not possible, it returns the same result as lapply() # This is the structure of temp: > str(temp) List of 7 $ : num [1:5] 3 7 9 6 -1 $ : num [1:5] 6 9 12 13 5 $ : num [1:5] 4 8 3 -1 -3 $ : num [1:5] 1 4 7 2 -2 $ : num [1:5] 5 7 9 4 2 $ : num [1:5] -3 5 8 9 4 $ : num [1:5] 3 6 9 4 1 # Define a function extremes_avg <- function(x) { ( min(x) + max(x) ) / 2 } # Apply extremes_avg() over temp using sapply() > sapply(temp, extremes_avg) [1] 4.0 9.0 2.5 2.5 5.5 3.0 5.0 # Notice that this is the same as: > unlist(lapply(temp, extremes_avg)) [1] 4.0 9.0 2.5 2.5 5.5 3.0 5.0 # In the previous example, we have seen that sapply simplifies the result into a vector. # If the function passed to sapply() returns a vector of length > 1, then a matrix is returned: extremes <- function(x) { c(min = min(x), max = max(x)) } > sapply(temp, extremes) [,1] [,2] [,3] [,4] [,5] [,6] [,7] min -1 5 -3 -2 2 -3 1 max 9 13 8 7 9 9 9 # If sapply cannot simplify the result into a meaningful vector or matrix, then it returs the # same output as lapply: below_zero <- function(x) { return(x[x < 0]) } freezing_s <- sapply(temp, below_zero) # Apply below_zero over temp using lapply(): freezing_l freezing_l <- lapply(temp, below_zero) # Are freezing_s and freezing_l identical? > identical(freezing_s, freezing_l) [1] TRUE # Finally, here is an example demonstrating sapply()'s power: > sapply(list(runif (10), runif (10)), + function(x) c(min = min(x), mean = mean(x), max = max(x))) [,1] [,2] min 0.01998662 0.07075416 mean 0.50691288 0.58029329 max 0.98786178 0.93855891
library(ape) testtree <- read.tree("10136_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="10136_0_unrooted.txt")
/codeml_files/newick_trees_processed/10136_0/rinput.R
no_license
DaniBoo/cyanobacteria_project
R
false
false
137
r
library(ape) testtree <- read.tree("10136_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="10136_0_unrooted.txt")
#***Problem 1*** #$$P1: Question 1$$ AK = .67 LA = .61 NC = .52 #assuming all these events are independent #4 diff ways to win pr_AK_LA_NC = AK*LA*NC pr_AK_LA = AK*LA*(1-NC) pr_AK_NC = AK*(1-LA)*NC pr_LA_NC = (1-AK)*LA*NC answerP1Q1 = pr_AK_LA_NC + pr_AK_LA + pr_AK_NC + pr_LA_NC ##0.649252 margin = .8-answerP1Q1 #$$P1: Question 2$$ ##The betting markets probability is .150748 higher than our answer. ##This is so much higher because the events of the states are ##most likely not independent, but dependent #***Problem 2*** ##This is not enough info for me to make the decision. ##I would need to know the length of the delays because #If Delta's delays were significantly longer than those of United's #the 2% difference would not make up for the greater amount of lost time #***Problem 3*** #$$P3: Section B$$ #$$P3: Section C$$ #$$P3: Section D$$
/HW1.R
no_license
wonathanjong/Stat371-H-W
R
false
false
861
r
#***Problem 1*** #$$P1: Question 1$$ AK = .67 LA = .61 NC = .52 #assuming all these events are independent #4 diff ways to win pr_AK_LA_NC = AK*LA*NC pr_AK_LA = AK*LA*(1-NC) pr_AK_NC = AK*(1-LA)*NC pr_LA_NC = (1-AK)*LA*NC answerP1Q1 = pr_AK_LA_NC + pr_AK_LA + pr_AK_NC + pr_LA_NC ##0.649252 margin = .8-answerP1Q1 #$$P1: Question 2$$ ##The betting markets probability is .150748 higher than our answer. ##This is so much higher because the events of the states are ##most likely not independent, but dependent #***Problem 2*** ##This is not enough info for me to make the decision. ##I would need to know the length of the delays because #If Delta's delays were significantly longer than those of United's #the 2% difference would not make up for the greater amount of lost time #***Problem 3*** #$$P3: Section B$$ #$$P3: Section C$$ #$$P3: Section D$$
# Please do three things to ensure this template is correctly modified: # 1. Rename this file based on the content you are testing using # `test-functionName.R` format so that your can directly call `moduleCoverage` # to calculate module coverage information. # `functionName` is a function's name in your module (e.g., `fireSense_spreadDataPrepEvent1`). # 2. Copy this file to the tests folder (i.e., `C:/Users/Tati/Documents/GitHub/fireSense_spreadDataPrep/tests/testthat`). # 3. Modify the test description based on the content you are testing: test_that("test Event1 and Event2.", { module <- list("fireSense_spreadDataPrep") path <- list(modulePath = "C:/Users/Tati/Documents/GitHub", outputPath = file.path(tempdir(), "outputs")) parameters <- list( #.progress = list(type = "graphical", interval = 1), .globals = list(verbose = FALSE), fireSense_spreadDataPrep = list(.saveInitialTime = NA) ) times <- list(start = 0, end = 1) # If your test function contains `time(sim)`, you can test the function at a # particular simulation time by defining the start time above. object1 <- "object1" # please specify object2 <- "object2" # please specify objects <- list("object1" = object1, "object2" = object2) mySim <- simInit(times = times, params = parameters, modules = module, objects = objects, paths = path) # You may need to set the random seed if your module or its functions use the # random number generator. set.seed(1234) # You have two strategies to test your module: # 1. Test the overall simulation results for the given objects, using the # sample code below: output <- spades(mySim, debug = FALSE) # is output a simList? expect_is(output, "simList") # does output have your module in it expect_true(any(unlist(modules(output)) %in% c(unlist(module)))) # did it simulate to the end? expect_true(time(output) == 1) # 2. Test the functions inside of the module using the sample code below: # To allow the `moduleCoverage` function to calculate unit test coverage # level, it needs access to all functions directly. # Use this approach when using any function within the simList object # (i.e., one version as a direct call, and one with `simList` object prepended). if (exists("fireSense_spreadDataPrepEvent1", envir = .GlobalEnv)) { simOutput <- fireSense_spreadDataPrepEvent1(mySim) } else { simOutput <- myEvent1(mySim) } expectedOutputEvent1Test1 <- " this is test for event 1. " # please define your expection of your output expect_is(class(simOutput$event1Test1), "character") expect_equal(simOutput$event1Test1, expectedOutputEvent1Test1) # or other expect function in testthat package. expect_equal(simOutput$event1Test2, as.numeric(999)) # or other expect function in testthat package. if (exists("fireSense_spreadDataPrepEvent2", envir = .GlobalEnv)) { simOutput <- fireSense_spreadDataPrepEvent2(mySim) } else { simOutput <- myEvent2(mySim) } expectedOutputEvent2Test1 <- " this is test for event 2. " # please define your expection of your output expect_is(class(simOutput$event2Test1), "character") expect_equal(simOutput$event2Test1, expectedOutputEvent2Test1) # or other expect function in testthat package. expect_equal(simOutput$event2Test2, as.numeric(777)) # or other expect function in testthat package. })
/tests/testthat/test-template.R
no_license
tati-micheletti/fireSense_dataPrep
R
false
false
3,482
r
# Please do three things to ensure this template is correctly modified: # 1. Rename this file based on the content you are testing using # `test-functionName.R` format so that your can directly call `moduleCoverage` # to calculate module coverage information. # `functionName` is a function's name in your module (e.g., `fireSense_spreadDataPrepEvent1`). # 2. Copy this file to the tests folder (i.e., `C:/Users/Tati/Documents/GitHub/fireSense_spreadDataPrep/tests/testthat`). # 3. Modify the test description based on the content you are testing: test_that("test Event1 and Event2.", { module <- list("fireSense_spreadDataPrep") path <- list(modulePath = "C:/Users/Tati/Documents/GitHub", outputPath = file.path(tempdir(), "outputs")) parameters <- list( #.progress = list(type = "graphical", interval = 1), .globals = list(verbose = FALSE), fireSense_spreadDataPrep = list(.saveInitialTime = NA) ) times <- list(start = 0, end = 1) # If your test function contains `time(sim)`, you can test the function at a # particular simulation time by defining the start time above. object1 <- "object1" # please specify object2 <- "object2" # please specify objects <- list("object1" = object1, "object2" = object2) mySim <- simInit(times = times, params = parameters, modules = module, objects = objects, paths = path) # You may need to set the random seed if your module or its functions use the # random number generator. set.seed(1234) # You have two strategies to test your module: # 1. Test the overall simulation results for the given objects, using the # sample code below: output <- spades(mySim, debug = FALSE) # is output a simList? expect_is(output, "simList") # does output have your module in it expect_true(any(unlist(modules(output)) %in% c(unlist(module)))) # did it simulate to the end? expect_true(time(output) == 1) # 2. Test the functions inside of the module using the sample code below: # To allow the `moduleCoverage` function to calculate unit test coverage # level, it needs access to all functions directly. # Use this approach when using any function within the simList object # (i.e., one version as a direct call, and one with `simList` object prepended). if (exists("fireSense_spreadDataPrepEvent1", envir = .GlobalEnv)) { simOutput <- fireSense_spreadDataPrepEvent1(mySim) } else { simOutput <- myEvent1(mySim) } expectedOutputEvent1Test1 <- " this is test for event 1. " # please define your expection of your output expect_is(class(simOutput$event1Test1), "character") expect_equal(simOutput$event1Test1, expectedOutputEvent1Test1) # or other expect function in testthat package. expect_equal(simOutput$event1Test2, as.numeric(999)) # or other expect function in testthat package. if (exists("fireSense_spreadDataPrepEvent2", envir = .GlobalEnv)) { simOutput <- fireSense_spreadDataPrepEvent2(mySim) } else { simOutput <- myEvent2(mySim) } expectedOutputEvent2Test1 <- " this is test for event 2. " # please define your expection of your output expect_is(class(simOutput$event2Test1), "character") expect_equal(simOutput$event2Test1, expectedOutputEvent2Test1) # or other expect function in testthat package. expect_equal(simOutput$event2Test2, as.numeric(777)) # or other expect function in testthat package. })
#' @export makeRLearner.classif.lqa = function() { makeRLearnerClassif( cl = "classif.lqa", package = "lqa", par.set = makeParamSet( makeDiscreteLearnerParam(id = "penalty", values = c("adaptive.lasso", "ao", "bridge", "enet", "fused.lasso", "genet", "icb", "lasso", "licb", "oscar", "penalreg", "ridge", "scad", "weighted.fusion")), makeNumericLearnerParam(id = "lambda", lower = 0, requires = quote(penalty %in% c("adaptive.lasso", "ao", "bridge", "genet", "lasso", "oscar", "penalreg", "ridge", "scad"))), makeNumericLearnerParam(id = "gamma", lower = 1 + .Machine$double.eps, requires = quote(penalty %in% c("ao", "bridge", "genet", "weighted.fusion"))), makeNumericLearnerParam(id = "alpha", lower = 0, requires = quote(penalty == "genet")), makeNumericLearnerParam(id = "c", lower = 0, requires = quote(penalty == "oscar")), makeNumericLearnerParam(id = "a", lower = 2 + .Machine$double.eps, requires = quote(penalty == "scad")), makeNumericLearnerParam(id = "lambda1", lower = 0, requires = quote(penalty %in% c("enet", "fused.lasso", "icb", "licb", "weighted.fusion"))), makeNumericLearnerParam(id = "lambda2", lower = 0, requires = quote(penalty %in% c("enet", "fused.lasso", "icb", "licb", "weighted.fusion"))), makeDiscreteLearnerParam(id = "method", default = "lqa.update2", values = c("lqa.update2", "ForwardBoost", "GBlockBoost")), makeNumericLearnerParam(id = "var.eps", default = .Machine$double.eps, lower = 0), makeIntegerLearnerParam(id = "max.steps", lower = 1L, default = 5000L), makeNumericLearnerParam(id = "conv.eps", default = 0.001, lower = 0), makeLogicalLearnerParam(id = "conv.stop", default = TRUE), makeNumericLearnerParam(id = "c1", default = 1e-08, lower = 0), makeIntegerLearnerParam(id = "digits", default = 5L, lower = 1L) ), properties = c("numerics", "prob", "twoclass", "weights"), par.vals = list(penalty = 'lasso', lambda = 0.1), name = "Fitting penalized Generalized Linear Models with the LQA algorithm", short.name = "lqa", note = "`penalty` has been set to *lasso* and `lambda` to 0.1 by default." ) } #' @export trainLearner.classif.lqa = function(.learner, .task, .subset, .weights = NULL, var.eps, max.steps, conv.eps, conv.stop, c1, digits, ...) { ctrl = learnerArgsToControl(lqa::lqa.control, var.eps, max.steps, conv.eps, conv.stop, c1, digits) d = getTaskData(.task, .subset, target.extra = TRUE, recode.target = "01") args = c(list(x = d$data, y = d$target, family = binomial(), control = ctrl), list(...)) rm(d) if (!args$penalty %in% c("adaptive.lasso", "ao", "bridge", "genet", "lasso", "oscar", "penalreg", "ridge", "scad")) { args$lambda = NULL } is.tune.param = names(args) %in% c("lambda", "gamma", "alpha", "c", "a", "lambda1", "lambda2") penfun = getFromNamespace(args$penalty, "lqa") args$penalty = do.call(penfun, list(lambda = unlist(args[is.tune.param]))) args = args[!is.tune.param] if (!is.null(.weights)) args$weights = .weights do.call(lqa::lqa.default, args) } #' @export predictLearner.classif.lqa = function(.learner, .model, .newdata, ...) { p = lqa::predict.lqa(.model$learner.model, new.x = cbind(1, .newdata), ...)$mu.new levs = c(.model$task.desc$negative, .model$task.desc$positive) if (.learner$predict.type == "prob") { p = propVectorToMatrix(p, levs) } else { p = as.factor(ifelse(p > 0.5, levs[2L], levs[1L])) names(p) = NULL } return(p) }
/R/RLearner_classif_lqa.R
no_license
abhik1368/mlr
R
false
false
3,618
r
#' @export makeRLearner.classif.lqa = function() { makeRLearnerClassif( cl = "classif.lqa", package = "lqa", par.set = makeParamSet( makeDiscreteLearnerParam(id = "penalty", values = c("adaptive.lasso", "ao", "bridge", "enet", "fused.lasso", "genet", "icb", "lasso", "licb", "oscar", "penalreg", "ridge", "scad", "weighted.fusion")), makeNumericLearnerParam(id = "lambda", lower = 0, requires = quote(penalty %in% c("adaptive.lasso", "ao", "bridge", "genet", "lasso", "oscar", "penalreg", "ridge", "scad"))), makeNumericLearnerParam(id = "gamma", lower = 1 + .Machine$double.eps, requires = quote(penalty %in% c("ao", "bridge", "genet", "weighted.fusion"))), makeNumericLearnerParam(id = "alpha", lower = 0, requires = quote(penalty == "genet")), makeNumericLearnerParam(id = "c", lower = 0, requires = quote(penalty == "oscar")), makeNumericLearnerParam(id = "a", lower = 2 + .Machine$double.eps, requires = quote(penalty == "scad")), makeNumericLearnerParam(id = "lambda1", lower = 0, requires = quote(penalty %in% c("enet", "fused.lasso", "icb", "licb", "weighted.fusion"))), makeNumericLearnerParam(id = "lambda2", lower = 0, requires = quote(penalty %in% c("enet", "fused.lasso", "icb", "licb", "weighted.fusion"))), makeDiscreteLearnerParam(id = "method", default = "lqa.update2", values = c("lqa.update2", "ForwardBoost", "GBlockBoost")), makeNumericLearnerParam(id = "var.eps", default = .Machine$double.eps, lower = 0), makeIntegerLearnerParam(id = "max.steps", lower = 1L, default = 5000L), makeNumericLearnerParam(id = "conv.eps", default = 0.001, lower = 0), makeLogicalLearnerParam(id = "conv.stop", default = TRUE), makeNumericLearnerParam(id = "c1", default = 1e-08, lower = 0), makeIntegerLearnerParam(id = "digits", default = 5L, lower = 1L) ), properties = c("numerics", "prob", "twoclass", "weights"), par.vals = list(penalty = 'lasso', lambda = 0.1), name = "Fitting penalized Generalized Linear Models with the LQA algorithm", short.name = "lqa", note = "`penalty` has been set to *lasso* and `lambda` to 0.1 by default." ) } #' @export trainLearner.classif.lqa = function(.learner, .task, .subset, .weights = NULL, var.eps, max.steps, conv.eps, conv.stop, c1, digits, ...) { ctrl = learnerArgsToControl(lqa::lqa.control, var.eps, max.steps, conv.eps, conv.stop, c1, digits) d = getTaskData(.task, .subset, target.extra = TRUE, recode.target = "01") args = c(list(x = d$data, y = d$target, family = binomial(), control = ctrl), list(...)) rm(d) if (!args$penalty %in% c("adaptive.lasso", "ao", "bridge", "genet", "lasso", "oscar", "penalreg", "ridge", "scad")) { args$lambda = NULL } is.tune.param = names(args) %in% c("lambda", "gamma", "alpha", "c", "a", "lambda1", "lambda2") penfun = getFromNamespace(args$penalty, "lqa") args$penalty = do.call(penfun, list(lambda = unlist(args[is.tune.param]))) args = args[!is.tune.param] if (!is.null(.weights)) args$weights = .weights do.call(lqa::lqa.default, args) } #' @export predictLearner.classif.lqa = function(.learner, .model, .newdata, ...) { p = lqa::predict.lqa(.model$learner.model, new.x = cbind(1, .newdata), ...)$mu.new levs = c(.model$task.desc$negative, .model$task.desc$positive) if (.learner$predict.type == "prob") { p = propVectorToMatrix(p, levs) } else { p = as.factor(ifelse(p > 0.5, levs[2L], levs[1L])) names(p) = NULL } return(p) }
# Pie2 expenditure=c(600,300,150,100,200) names(expenditure)=c('Housing','Food','Cloths','Entertainment', 'Other') expenditure pie(expenditure) pie(expenditure, labels=as.character(expenditure), main="Monthly Expenditure Breakdown", col=c("red","orange","yellow","blue","green"), border="brown", clockwise=TRUE )
/32-basicGraphs/27c-pie2.R
no_license
DUanalytics/rAnalytics
R
false
false
347
r
# Pie2 expenditure=c(600,300,150,100,200) names(expenditure)=c('Housing','Food','Cloths','Entertainment', 'Other') expenditure pie(expenditure) pie(expenditure, labels=as.character(expenditure), main="Monthly Expenditure Breakdown", col=c("red","orange","yellow","blue","green"), border="brown", clockwise=TRUE )
library(kcde) library(pdtmvn) library(plyr) library(dplyr) library(lubridate) library(doMC) options(error = recover) all_data_sets <- c("ili_national", "dengue_sj") all_prediction_horizons <- seq_len(52) # make predictions at every horizon from 1 to 52 weeks ahead all_max_lags <- 1L # use incidence at times t^* and t^* - 1 to predict incidence after t^* all_max_seasonal_lags <- 0L # not used all_filtering_values <- FALSE # not used all_differencing_values <- FALSE # not used all_seasonality_values <- c(FALSE, TRUE) # specifications without and with periodic kernel all_bw_parameterizations <- c("diagonal", "full") # specifications with diagonal and full bandwidth ## Test values for debugging #all_data_sets <- c("ili_national") #all_prediction_horizons <- 4L #all_max_lags <- 1L #all_filtering_values <- c(FALSE) #all_differencing_values <- c(FALSE) #all_seasonality_values <- c(TRUE) #all_bw_parameterizations <- c("diagonal") num_cores <- 3L registerDoMC(cores = num_cores) for(data_set in all_data_sets) { ## Set path where fit object is stored results_path <- file.path( "/media/evan/data/Reich/infectious-disease-prediction-with-kcde/inst/results", data_set, "estimation-results") if(identical(data_set, "ili_national")) { ## Load data for nationally reported influenza like illness usflu <- read.csv("/media/evan/data/Reich/infectious-disease-prediction-with-kcde/data-raw/usflu.csv") # ## This is how I originally got the data -- have saved it to # ## csv for the purposes of stable access going forward. # library(cdcfluview) # usflu <- get_flu_data("national", "ilinet", years=1997:2014) ## A little cleanup data <- transmute(usflu, region.type = REGION.TYPE, region = REGION, year = YEAR, week = WEEK, weighted_ili = as.numeric(X..WEIGHTED.ILI)) ## Subset data to do prediction using only data up through 2014 data <- data[data$year <= 2014, , drop = FALSE] ## Row indices in data corresponding to times at which we want to make a prediction prediction_time_inds <- which(data$year %in% 2011:2014) ## Add time column. This is used for calculating times to drop in cross-validation data$time <- ymd(paste(data$year, "01", "01", sep = "-")) week(data$time) <- data$week ## Add time_index column. This is used for calculating the periodic kernel. ## Here, this is calculated as the number of days since some origin date (1970-1-1 in this case). ## The origin is arbitrary. data$time_index <- as.integer(data$time - ymd(paste("1970", "01", "01", sep = "-"))) ## Season column: for example, weeks of 2010 up through and including week 30 get season 2009/2010; ## weeks after week 30 get season 2010/2011 data$season <- ifelse( data$week <= 30, paste0(data$year - 1, "/", data$year), paste0(data$year, "/", data$year + 1) ) ## Season week column: week number within season data$season_week <- sapply(seq_len(nrow(data)), function(row_ind) { sum(data$season == data$season[row_ind] & data$time_index <= data$time_index[row_ind]) }) } else if(identical(data_set, "dengue_sj")) { ## Load data for Dengue fever in San Juan data <- read.csv("/media/evan/data/Reich/infectious-disease-prediction-with-kcde/data-raw/San_Juan_Testing_Data.csv") ## Form variable with total cases + 0.5 which can be logged, and its seasonally lagged ratio data$total_cases_plus_0.5 <- data$total_cases + 0.5 ## Row indices in data corresponding to times at which we want to make a prediction prediction_time_inds <- which(data$season %in% paste0(2009:2012, "/", 2010:2013)) ## convert dates data$time <- ymd(data$week_start_date) ## Add time_index column. This is used for calculating the periodic kernel. ## Here, this is calculated as the number of days since some origin date (1970-1-1 in this case). ## The origin is arbitrary. data$time_index <- as.integer(data$time - ymd(paste("1970", "01", "01", sep = "-"))) } data_set_results <- foreach(prediction_horizon=all_prediction_horizons, .packages=c("kcde", "pdtmvn", "plyr", "dplyr", "lubridate"), .combine="rbind") %dopar% { results_row_ind <- 1L ## Allocate data frame to store results for this prediction horizon num_rows <- length(all_max_lags) * length(all_max_seasonal_lags) * length(all_filtering_values) * length(all_differencing_values) * length(all_seasonality_values) * length(all_bw_parameterizations) * length(prediction_time_inds) ph_results <- data.frame(data_set = data_set, prediction_horizon = rep(NA_integer_, num_rows), max_lag = rep(NA_integer_, num_rows), max_seasonal_lag = rep(NA_integer_, num_rows), filtering = rep(NA, num_rows), differencing = rep(NA, num_rows), seasonality = rep(NA, num_rows), bw_parameterization = rep(NA_character_, num_rows), model = "kcde", prediction_time = rep(NA, num_rows), log_score = rep(NA_real_, num_rows), pt_pred = rep(NA_real_, num_rows), AE = rep(NA_real_, num_rows), interval_pred_lb_95 = rep(NA_real_, num_rows), interval_pred_ub_95 = rep(NA_real_, num_rows), interval_pred_lb_50 = rep(NA_real_, num_rows), interval_pred_ub_50 = rep(NA_real_, num_rows), stringsAsFactors = FALSE ) class(ph_results$prediction_time) <- class(data$time) for(max_lag in all_max_lags) { for(max_seasonal_lag in all_max_seasonal_lags) { for(filtering in all_filtering_values) { for(differencing in all_differencing_values) { ## Set prediction target var if(identical(data_set, "ili_national")) { if(differencing) { prediction_target_var <- "weighted_ili_ratio" orig_prediction_target_var <- "weighted_ili" } else { prediction_target_var <- "weighted_ili" } } else if(identical(data_set, "dengue_sj")) { if(differencing) { prediction_target_var <- "total_cases_plus_0.5_ratio" orig_prediction_target_var <- "total_cases_plus_0.5" } else { prediction_target_var <- "total_cases_plus_0.5" } } for(seasonality in all_seasonality_values) { for(bw_parameterization in all_bw_parameterizations) { for(prediction_time_ind in prediction_time_inds) { ## Set values describing case in ph_results ph_results$prediction_horizon[results_row_ind] <- prediction_horizon ph_results$max_lag[results_row_ind] <- max_lag ph_results$max_seasonal_lag[results_row_ind] <- max_seasonal_lag ph_results$filtering[results_row_ind] <- filtering ph_results$differencing[results_row_ind] <- differencing ph_results$seasonality[results_row_ind] <- seasonality ph_results$bw_parameterization[results_row_ind] <- bw_parameterization ph_results$prediction_time[results_row_ind] <- data$time[prediction_time_ind] ## Load kcde_fit object. Estimation was performed previously. case_descriptor <- paste0( data_set, "-prediction_horizon_", prediction_horizon, "-max_lag_", max_lag, "-max_seasonal_lag_", max_seasonal_lag, "-filtering_", filtering, "-differencing_", differencing, "-seasonality_", seasonality, "-bw_parameterization_", bw_parameterization ) kcde_fit_file_path <- file.path(results_path, paste0("kcde_fit-", case_descriptor, ".rds")) kcde_fit <- readRDS(kcde_fit_file_path) ## If Dengue fit, fix a bug in the in_range function for discrete variables ## that was supplied at time of estimation. This function was not used in ## estimation, but is required here. Original definition referenced a function ## that may not be available now. if(identical(data_set, "dengue_sj")) { for(kernel_component_ind in seq_along(kcde_fit$kcde_control$kernel_components)) { kernel_component <- kcde_fit$kcde_control$kernel_components[[kernel_component_ind]] if(!is.null(kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns)) { for(var_ind in seq_along(kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns)) { kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns[[var_ind]]$in_range <- function(x, tolerance = .Machine$double.eps^0.5) { return(sapply(x, function(x_i) { return(isTRUE(all.equal(x_i, kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns[[var_ind]]$discretizer(x_i)))) })) } } kcde_fit$theta_hat[[kernel_component_ind]]$discrete_var_range_fns <- kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns } } } ## fix rkernel_fn for pdtmvn-based kernel functions ## I supplied a buggy version of this in the call to the estimation routine ## that did not ensure that variables were supplied in a consistent order. ## This did not affect estimation as rkernel_fn is not called there ## But it does need to be fixed here. for(kernel_component_ind in seq(from = (as.logical(seasonality) + 1), to = length(kcde_fit$kcde_control$kernel_components))) { kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$rkernel_fn <- function(n, conditioning_obs, center, bw, bw_continuous, conditional_bw_discrete, conditional_center_discrete_offset_multiplier, continuous_vars, discrete_vars, continuous_var_col_inds, discrete_var_col_inds, discrete_var_range_fns, lower, upper, x_names, ...) { if(missing(conditioning_obs) || is.null(conditioning_obs)) { log_conditioning_obs <- NULL } else { log_conditioning_obs <- log(conditioning_obs) } if(missing(bw_continuous)) { bw_continuous <- NULL } if(missing(conditional_bw_discrete)) { conditional_bw_discrete <- NULL } if(missing(conditional_center_discrete_offset_multiplier)) { conditional_center_discrete_offset_multiplier <- NULL } ## center parameter of pdtmvn_kernel is mean of log ## mode of resulting log-normal distribution is ## mode = exp(mu - bw %*% 1) (where 1 is a column vector of 1s) ## therefore mu = log(mode) + bw %*% 1 reduced_x_names <- names(center) inds_x_vars_in_orig_vars <- which(x_names %in% reduced_x_names) x_names_for_call <- x_names[inds_x_vars_in_orig_vars] mean_offset <- apply(bw, 1, sum)[x_names %in% colnames(center)] return(exp(rpdtmvn_kernel(n = n, conditioning_obs = log_conditioning_obs, center = sweep(log(center)[, x_names_for_call, drop = FALSE], 2, mean_offset, `+`), bw = bw, bw_continuous = bw_continuous, conditional_bw_discrete = conditional_bw_discrete, conditional_center_discrete_offset_multiplier = conditional_center_discrete_offset_multiplier, continuous_vars = continuous_vars, discrete_vars = discrete_vars, continuous_var_col_inds = continuous_var_col_inds, discrete_var_col_inds = discrete_var_col_inds, discrete_var_range_fns = discrete_var_range_fns, lower = lower, upper = upper, x_names = x_names)[, reduced_x_names, drop = FALSE])) } } ## Get index of analysis time in data set ## (time from which we predict forward) analysis_time_ind <- prediction_time_ind - prediction_horizon ## Compute log score observed_prediction_target <- data[prediction_time_ind, prediction_target_var, drop = FALSE] colnames(observed_prediction_target) <- paste0(prediction_target_var, "_horizon", prediction_horizon) ph_results$log_score[results_row_ind] <- kcde_predict( kcde_fit = kcde_fit, prediction_data = data[seq_len(analysis_time_ind), , drop = FALSE], leading_rows_to_drop = 0L, trailing_rows_to_drop = 0L, additional_training_rows_to_drop = NULL, prediction_type = "distribution", prediction_test_lead_obs = observed_prediction_target, log = TRUE ) if(differencing) { ph_results$log_score[results_row_ind] <- ph_results$log_score[results_row_ind] - (abs(data[analysis_time_ind - 52, orig_prediction_target_var])) } ## Compute point prediction and interval predictions -- quantiles ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] <- kcde_predict( p = c(0.5, 0.025, 0.975, 0.25, 0.75), n = 100000, kcde_fit = kcde_fit, prediction_data = data[seq_len(analysis_time_ind), , drop = FALSE], leading_rows_to_drop = 0L, trailing_rows_to_drop = 0L, additional_training_rows_to_drop = NULL, prediction_type = "quantile", log = TRUE ) if(differencing) { ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] <- ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] * data[prediction_time_ind - 52, prediction_target_var] } ## Correction by subtracting 0.5 for Dengue data set if(identical(data_set, "dengue_sj")) { ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] <- ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] - 0.5 } ## Compute absolute error of point prediction ph_results$AE[results_row_ind] <- abs(ph_results$pt_pred[results_row_ind] - observed_prediction_target) ## Increment results row results_row_ind <- results_row_ind + 1L } # prediction_time_ind } # bw_parameterization } # seasonality } # differencing } # filtering } # max_seasonal_lag } # max_lag saveRDS(ph_results, file = file.path( "/media/evan/data/Reich/infectious-disease-prediction-with-kcde/inst/results", data_set, "prediction-results", paste0("kcde-predictions-ph_", prediction_horizon, ".rds"))) return(ph_results) } # prediction_horizon -- in foreach/dopar statement ## Save results for the given data set saveRDS(data_set_results, file = file.path( "/media/evan/data/Reich/infectious-disease-prediction-with-kcde/inst/results", data_set, "prediction-results/kcde-predictions.rds")) } # data_set
/inst/code/prediction/kcde-prediction.R
no_license
MartinPDLE/article-disease-pred-with-kcde
R
false
false
23,557
r
library(kcde) library(pdtmvn) library(plyr) library(dplyr) library(lubridate) library(doMC) options(error = recover) all_data_sets <- c("ili_national", "dengue_sj") all_prediction_horizons <- seq_len(52) # make predictions at every horizon from 1 to 52 weeks ahead all_max_lags <- 1L # use incidence at times t^* and t^* - 1 to predict incidence after t^* all_max_seasonal_lags <- 0L # not used all_filtering_values <- FALSE # not used all_differencing_values <- FALSE # not used all_seasonality_values <- c(FALSE, TRUE) # specifications without and with periodic kernel all_bw_parameterizations <- c("diagonal", "full") # specifications with diagonal and full bandwidth ## Test values for debugging #all_data_sets <- c("ili_national") #all_prediction_horizons <- 4L #all_max_lags <- 1L #all_filtering_values <- c(FALSE) #all_differencing_values <- c(FALSE) #all_seasonality_values <- c(TRUE) #all_bw_parameterizations <- c("diagonal") num_cores <- 3L registerDoMC(cores = num_cores) for(data_set in all_data_sets) { ## Set path where fit object is stored results_path <- file.path( "/media/evan/data/Reich/infectious-disease-prediction-with-kcde/inst/results", data_set, "estimation-results") if(identical(data_set, "ili_national")) { ## Load data for nationally reported influenza like illness usflu <- read.csv("/media/evan/data/Reich/infectious-disease-prediction-with-kcde/data-raw/usflu.csv") # ## This is how I originally got the data -- have saved it to # ## csv for the purposes of stable access going forward. # library(cdcfluview) # usflu <- get_flu_data("national", "ilinet", years=1997:2014) ## A little cleanup data <- transmute(usflu, region.type = REGION.TYPE, region = REGION, year = YEAR, week = WEEK, weighted_ili = as.numeric(X..WEIGHTED.ILI)) ## Subset data to do prediction using only data up through 2014 data <- data[data$year <= 2014, , drop = FALSE] ## Row indices in data corresponding to times at which we want to make a prediction prediction_time_inds <- which(data$year %in% 2011:2014) ## Add time column. This is used for calculating times to drop in cross-validation data$time <- ymd(paste(data$year, "01", "01", sep = "-")) week(data$time) <- data$week ## Add time_index column. This is used for calculating the periodic kernel. ## Here, this is calculated as the number of days since some origin date (1970-1-1 in this case). ## The origin is arbitrary. data$time_index <- as.integer(data$time - ymd(paste("1970", "01", "01", sep = "-"))) ## Season column: for example, weeks of 2010 up through and including week 30 get season 2009/2010; ## weeks after week 30 get season 2010/2011 data$season <- ifelse( data$week <= 30, paste0(data$year - 1, "/", data$year), paste0(data$year, "/", data$year + 1) ) ## Season week column: week number within season data$season_week <- sapply(seq_len(nrow(data)), function(row_ind) { sum(data$season == data$season[row_ind] & data$time_index <= data$time_index[row_ind]) }) } else if(identical(data_set, "dengue_sj")) { ## Load data for Dengue fever in San Juan data <- read.csv("/media/evan/data/Reich/infectious-disease-prediction-with-kcde/data-raw/San_Juan_Testing_Data.csv") ## Form variable with total cases + 0.5 which can be logged, and its seasonally lagged ratio data$total_cases_plus_0.5 <- data$total_cases + 0.5 ## Row indices in data corresponding to times at which we want to make a prediction prediction_time_inds <- which(data$season %in% paste0(2009:2012, "/", 2010:2013)) ## convert dates data$time <- ymd(data$week_start_date) ## Add time_index column. This is used for calculating the periodic kernel. ## Here, this is calculated as the number of days since some origin date (1970-1-1 in this case). ## The origin is arbitrary. data$time_index <- as.integer(data$time - ymd(paste("1970", "01", "01", sep = "-"))) } data_set_results <- foreach(prediction_horizon=all_prediction_horizons, .packages=c("kcde", "pdtmvn", "plyr", "dplyr", "lubridate"), .combine="rbind") %dopar% { results_row_ind <- 1L ## Allocate data frame to store results for this prediction horizon num_rows <- length(all_max_lags) * length(all_max_seasonal_lags) * length(all_filtering_values) * length(all_differencing_values) * length(all_seasonality_values) * length(all_bw_parameterizations) * length(prediction_time_inds) ph_results <- data.frame(data_set = data_set, prediction_horizon = rep(NA_integer_, num_rows), max_lag = rep(NA_integer_, num_rows), max_seasonal_lag = rep(NA_integer_, num_rows), filtering = rep(NA, num_rows), differencing = rep(NA, num_rows), seasonality = rep(NA, num_rows), bw_parameterization = rep(NA_character_, num_rows), model = "kcde", prediction_time = rep(NA, num_rows), log_score = rep(NA_real_, num_rows), pt_pred = rep(NA_real_, num_rows), AE = rep(NA_real_, num_rows), interval_pred_lb_95 = rep(NA_real_, num_rows), interval_pred_ub_95 = rep(NA_real_, num_rows), interval_pred_lb_50 = rep(NA_real_, num_rows), interval_pred_ub_50 = rep(NA_real_, num_rows), stringsAsFactors = FALSE ) class(ph_results$prediction_time) <- class(data$time) for(max_lag in all_max_lags) { for(max_seasonal_lag in all_max_seasonal_lags) { for(filtering in all_filtering_values) { for(differencing in all_differencing_values) { ## Set prediction target var if(identical(data_set, "ili_national")) { if(differencing) { prediction_target_var <- "weighted_ili_ratio" orig_prediction_target_var <- "weighted_ili" } else { prediction_target_var <- "weighted_ili" } } else if(identical(data_set, "dengue_sj")) { if(differencing) { prediction_target_var <- "total_cases_plus_0.5_ratio" orig_prediction_target_var <- "total_cases_plus_0.5" } else { prediction_target_var <- "total_cases_plus_0.5" } } for(seasonality in all_seasonality_values) { for(bw_parameterization in all_bw_parameterizations) { for(prediction_time_ind in prediction_time_inds) { ## Set values describing case in ph_results ph_results$prediction_horizon[results_row_ind] <- prediction_horizon ph_results$max_lag[results_row_ind] <- max_lag ph_results$max_seasonal_lag[results_row_ind] <- max_seasonal_lag ph_results$filtering[results_row_ind] <- filtering ph_results$differencing[results_row_ind] <- differencing ph_results$seasonality[results_row_ind] <- seasonality ph_results$bw_parameterization[results_row_ind] <- bw_parameterization ph_results$prediction_time[results_row_ind] <- data$time[prediction_time_ind] ## Load kcde_fit object. Estimation was performed previously. case_descriptor <- paste0( data_set, "-prediction_horizon_", prediction_horizon, "-max_lag_", max_lag, "-max_seasonal_lag_", max_seasonal_lag, "-filtering_", filtering, "-differencing_", differencing, "-seasonality_", seasonality, "-bw_parameterization_", bw_parameterization ) kcde_fit_file_path <- file.path(results_path, paste0("kcde_fit-", case_descriptor, ".rds")) kcde_fit <- readRDS(kcde_fit_file_path) ## If Dengue fit, fix a bug in the in_range function for discrete variables ## that was supplied at time of estimation. This function was not used in ## estimation, but is required here. Original definition referenced a function ## that may not be available now. if(identical(data_set, "dengue_sj")) { for(kernel_component_ind in seq_along(kcde_fit$kcde_control$kernel_components)) { kernel_component <- kcde_fit$kcde_control$kernel_components[[kernel_component_ind]] if(!is.null(kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns)) { for(var_ind in seq_along(kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns)) { kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns[[var_ind]]$in_range <- function(x, tolerance = .Machine$double.eps^0.5) { return(sapply(x, function(x_i) { return(isTRUE(all.equal(x_i, kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns[[var_ind]]$discretizer(x_i)))) })) } } kcde_fit$theta_hat[[kernel_component_ind]]$discrete_var_range_fns <- kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$theta_fixed$discrete_var_range_fns } } } ## fix rkernel_fn for pdtmvn-based kernel functions ## I supplied a buggy version of this in the call to the estimation routine ## that did not ensure that variables were supplied in a consistent order. ## This did not affect estimation as rkernel_fn is not called there ## But it does need to be fixed here. for(kernel_component_ind in seq(from = (as.logical(seasonality) + 1), to = length(kcde_fit$kcde_control$kernel_components))) { kcde_fit$kcde_control$kernel_components[[kernel_component_ind]]$rkernel_fn <- function(n, conditioning_obs, center, bw, bw_continuous, conditional_bw_discrete, conditional_center_discrete_offset_multiplier, continuous_vars, discrete_vars, continuous_var_col_inds, discrete_var_col_inds, discrete_var_range_fns, lower, upper, x_names, ...) { if(missing(conditioning_obs) || is.null(conditioning_obs)) { log_conditioning_obs <- NULL } else { log_conditioning_obs <- log(conditioning_obs) } if(missing(bw_continuous)) { bw_continuous <- NULL } if(missing(conditional_bw_discrete)) { conditional_bw_discrete <- NULL } if(missing(conditional_center_discrete_offset_multiplier)) { conditional_center_discrete_offset_multiplier <- NULL } ## center parameter of pdtmvn_kernel is mean of log ## mode of resulting log-normal distribution is ## mode = exp(mu - bw %*% 1) (where 1 is a column vector of 1s) ## therefore mu = log(mode) + bw %*% 1 reduced_x_names <- names(center) inds_x_vars_in_orig_vars <- which(x_names %in% reduced_x_names) x_names_for_call <- x_names[inds_x_vars_in_orig_vars] mean_offset <- apply(bw, 1, sum)[x_names %in% colnames(center)] return(exp(rpdtmvn_kernel(n = n, conditioning_obs = log_conditioning_obs, center = sweep(log(center)[, x_names_for_call, drop = FALSE], 2, mean_offset, `+`), bw = bw, bw_continuous = bw_continuous, conditional_bw_discrete = conditional_bw_discrete, conditional_center_discrete_offset_multiplier = conditional_center_discrete_offset_multiplier, continuous_vars = continuous_vars, discrete_vars = discrete_vars, continuous_var_col_inds = continuous_var_col_inds, discrete_var_col_inds = discrete_var_col_inds, discrete_var_range_fns = discrete_var_range_fns, lower = lower, upper = upper, x_names = x_names)[, reduced_x_names, drop = FALSE])) } } ## Get index of analysis time in data set ## (time from which we predict forward) analysis_time_ind <- prediction_time_ind - prediction_horizon ## Compute log score observed_prediction_target <- data[prediction_time_ind, prediction_target_var, drop = FALSE] colnames(observed_prediction_target) <- paste0(prediction_target_var, "_horizon", prediction_horizon) ph_results$log_score[results_row_ind] <- kcde_predict( kcde_fit = kcde_fit, prediction_data = data[seq_len(analysis_time_ind), , drop = FALSE], leading_rows_to_drop = 0L, trailing_rows_to_drop = 0L, additional_training_rows_to_drop = NULL, prediction_type = "distribution", prediction_test_lead_obs = observed_prediction_target, log = TRUE ) if(differencing) { ph_results$log_score[results_row_ind] <- ph_results$log_score[results_row_ind] - (abs(data[analysis_time_ind - 52, orig_prediction_target_var])) } ## Compute point prediction and interval predictions -- quantiles ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] <- kcde_predict( p = c(0.5, 0.025, 0.975, 0.25, 0.75), n = 100000, kcde_fit = kcde_fit, prediction_data = data[seq_len(analysis_time_ind), , drop = FALSE], leading_rows_to_drop = 0L, trailing_rows_to_drop = 0L, additional_training_rows_to_drop = NULL, prediction_type = "quantile", log = TRUE ) if(differencing) { ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] <- ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] * data[prediction_time_ind - 52, prediction_target_var] } ## Correction by subtracting 0.5 for Dengue data set if(identical(data_set, "dengue_sj")) { ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] <- ph_results[results_row_ind, c("pt_pred", "interval_pred_lb_95", "interval_pred_ub_95", "interval_pred_lb_50", "interval_pred_ub_50")] - 0.5 } ## Compute absolute error of point prediction ph_results$AE[results_row_ind] <- abs(ph_results$pt_pred[results_row_ind] - observed_prediction_target) ## Increment results row results_row_ind <- results_row_ind + 1L } # prediction_time_ind } # bw_parameterization } # seasonality } # differencing } # filtering } # max_seasonal_lag } # max_lag saveRDS(ph_results, file = file.path( "/media/evan/data/Reich/infectious-disease-prediction-with-kcde/inst/results", data_set, "prediction-results", paste0("kcde-predictions-ph_", prediction_horizon, ".rds"))) return(ph_results) } # prediction_horizon -- in foreach/dopar statement ## Save results for the given data set saveRDS(data_set_results, file = file.path( "/media/evan/data/Reich/infectious-disease-prediction-with-kcde/inst/results", data_set, "prediction-results/kcde-predictions.rds")) } # data_set
data = matrix(c(1,0,0,0,1,0,0,0,0,0, 0,1,0,1,0,1,0,0,1,0, 1,1,0,0,0,0,1,0,0,0, 1,1,1,0,0,0,1,0,0,0, 0,1,1,1,0,0,0,1,0,0, 1,0,1,1,1,0,1,1,1,1, 1,1,0,1,0,1,0,1,1,1, 0,0,0,1,1,0,1,0,1,0, 0,1,1,0,0,0,1,1,0,0, 1,0,0,0,1,1,1,0,0,0), nrow=10, ncol=10); # Imagine the matrix represents presence/absence across a # geographic space. The row and columm index corresponds # to the pixels longitudinal and latitudinal offset. # The goal is to calculate a "clumping" score for the matrix # that is the product over each cell, x, of: # \epsilon + \sum_{i\in N_x} I(i == x) # score(x) = ---------------------------------------- # | N_x | + 2 \epsilon # where: # N_x is the set of cells that neighbor x # | N_x | is the size of this set (3 for corner cells, 5 for # cells on the side, and 8 of other cells). # \epsilon is a positive # (we'll use .1) # I(i == x) is an "indicator" function that is 1 if the cell # x and the cell i have the same value. It is 0 # if the cells differ. # # If \epsilon is 1. The score function can be thought of as # a simple model that states that "probability of a cell being 1 # is the proportion of neighbors who display 1". # As epsilon increases, we nudge the probability of 0 or 1 closer # to 0.5 # # The value for the matrix is the product of this score for each cell epsilon <- 0.1; total.score = 1.0; count_matches <- function(cell, row, ind) { num.matching <- 0; if (row[ind] == cell) { num.matching <- num.matching + 1; } if (ind > 1 && row[ind - 1] == cell) { num.matching <- num.matching + 1; } if (ind < length(row) && row[ind + 1] == cell) { num.matching <- num.matching + 1; } return(num.matching); } for (r in 1 : nrow(data)) { row <- data[r,] top.or.bottom <- r == 1 || r == nrow(data); for (c in 1 : length(row)) { cell <- row[c]; left.or.right <- c == 1 || c == length(row); if (left.or.right) { if (top.or.bottom) { num.neighbors = 3; # corner } else { num.neighbors = 5; # left or right side } } else if (top.or.bottom) { num.neighbors = 5; # top or bottom side } else { num.neighbors = 8; } num.matching <- count_matches(cell, row, c) - 1; if (r > 1) { prev.row <- data[(r - 1),]; m <- count_matches(cell, prev.row, c); num.matching <- num.matching + m; } if (r < nrow(data)) { nr = r + 1; next.row <- data[nr,]; m <- count_matches(cell, next.row, c); num.matching <- num.matching + m; } cell.score <- (epsilon + num.matching)/(2*epsilon + num.neighbors); total.score <- total.score * cell.score; #cat(r, " ", c, " ", cell, " ", num.neighbors, " ", num.matching, "\n"); } } cat('score = ', total.score, "\n");
/flow-control/spatial.R
permissive
mtholder/some-simple-r-examples
R
false
false
3,172
r
data = matrix(c(1,0,0,0,1,0,0,0,0,0, 0,1,0,1,0,1,0,0,1,0, 1,1,0,0,0,0,1,0,0,0, 1,1,1,0,0,0,1,0,0,0, 0,1,1,1,0,0,0,1,0,0, 1,0,1,1,1,0,1,1,1,1, 1,1,0,1,0,1,0,1,1,1, 0,0,0,1,1,0,1,0,1,0, 0,1,1,0,0,0,1,1,0,0, 1,0,0,0,1,1,1,0,0,0), nrow=10, ncol=10); # Imagine the matrix represents presence/absence across a # geographic space. The row and columm index corresponds # to the pixels longitudinal and latitudinal offset. # The goal is to calculate a "clumping" score for the matrix # that is the product over each cell, x, of: # \epsilon + \sum_{i\in N_x} I(i == x) # score(x) = ---------------------------------------- # | N_x | + 2 \epsilon # where: # N_x is the set of cells that neighbor x # | N_x | is the size of this set (3 for corner cells, 5 for # cells on the side, and 8 of other cells). # \epsilon is a positive # (we'll use .1) # I(i == x) is an "indicator" function that is 1 if the cell # x and the cell i have the same value. It is 0 # if the cells differ. # # If \epsilon is 1. The score function can be thought of as # a simple model that states that "probability of a cell being 1 # is the proportion of neighbors who display 1". # As epsilon increases, we nudge the probability of 0 or 1 closer # to 0.5 # # The value for the matrix is the product of this score for each cell epsilon <- 0.1; total.score = 1.0; count_matches <- function(cell, row, ind) { num.matching <- 0; if (row[ind] == cell) { num.matching <- num.matching + 1; } if (ind > 1 && row[ind - 1] == cell) { num.matching <- num.matching + 1; } if (ind < length(row) && row[ind + 1] == cell) { num.matching <- num.matching + 1; } return(num.matching); } for (r in 1 : nrow(data)) { row <- data[r,] top.or.bottom <- r == 1 || r == nrow(data); for (c in 1 : length(row)) { cell <- row[c]; left.or.right <- c == 1 || c == length(row); if (left.or.right) { if (top.or.bottom) { num.neighbors = 3; # corner } else { num.neighbors = 5; # left or right side } } else if (top.or.bottom) { num.neighbors = 5; # top or bottom side } else { num.neighbors = 8; } num.matching <- count_matches(cell, row, c) - 1; if (r > 1) { prev.row <- data[(r - 1),]; m <- count_matches(cell, prev.row, c); num.matching <- num.matching + m; } if (r < nrow(data)) { nr = r + 1; next.row <- data[nr,]; m <- count_matches(cell, next.row, c); num.matching <- num.matching + m; } cell.score <- (epsilon + num.matching)/(2*epsilon + num.neighbors); total.score <- total.score * cell.score; #cat(r, " ", c, " ", cell, " ", num.neighbors, " ", num.matching, "\n"); } } cat('score = ', total.score, "\n");
#' @name kro.ref #' @title LMS Parameters for German reference data (Kromeyer Hauschild, 2001) for height, weight, bmi, and waist circumference, including preterm correction (Voigt) #' @docType data #' @usage kro.ref #' @source Perzentile fuer den Body-mass-Index fuer das Kindes- und Jugendalter unter Heranziehung verschiedener deutscher Stichproben, Monatsschrift Kinderheilkunde August 2001, Volume 149, Issue 8, pp 807-818; Fruehgeborenenkorrektur nach Voigt NULL
/childsds/R/kroref-data.r
no_license
ingted/R-Examples
R
false
false
469
r
#' @name kro.ref #' @title LMS Parameters for German reference data (Kromeyer Hauschild, 2001) for height, weight, bmi, and waist circumference, including preterm correction (Voigt) #' @docType data #' @usage kro.ref #' @source Perzentile fuer den Body-mass-Index fuer das Kindes- und Jugendalter unter Heranziehung verschiedener deutscher Stichproben, Monatsschrift Kinderheilkunde August 2001, Volume 149, Issue 8, pp 807-818; Fruehgeborenenkorrektur nach Voigt NULL
## KAGGLE CONTEST: BNPP DATASET ## MATH 289 FINAL REPORT ## AUTHORS: MITESH GADGIL & sAURABH KULKARNI ## PREDICTIVE MODELLING USING XGBOOST library(xgboost) # Inputting data test <- read.csv("test.csv") train <- read.csv("train.csv") # Replacing missing data with NA train[train ==""] <- NA test[test ==""] <- NA # Storing "target" as a different vector and equalizing test and train data columns y <- train[, 'target'] train <- train[, -2] # the number of NA's in a data point are stored to be used as a feature feature_NA.train <- apply(train,1,function(x)sum(is.na(x))) feature_NA.test <- apply(test,1,function(x)sum(is.na(x))) train[is.na(train)] <- -1 test[is.na(test)] <- -1 # Find factor variables and translate to numeric # store column numbers of factor attributes in f and f.t f <- c() for(i in 1:ncol(train)) { if (is.factor(train[, i])) f <- c(f, i) } f.t <- c() for(i in 1:ncol(test)) { if (is.factor(test[, i])) f.t <- c(f.t, i) } # COnverting the test and training sets into numeric variables ttrain <- rbind(train, test) for (i in f) { ttrain[, i] <- as.numeric(ttrain[, i]) } train <- ttrain[1:nrow(train), ] train <- cbind.data.frame(train,"feature"=feature_NA.train) test <- ttrain[(nrow(train)+1):nrow(ttrain), ] test <- cbind.data.frame(test,"feature"=feature_NA.test) # the function that returns probability vector for test set after training according to #parameters in param0 for number of iterations given in 'iter' doPrediction <- function(y, train, test, param0, iter) { n<- nrow(train) xgtrain <- xgb.DMatrix(as.matrix(train), label = y,missing = NaN) xgval = xgb.DMatrix(as.matrix(test),missing = NaN) watchlist <- list('train' = xgtrain) model = xgb.train( nrounds = iter , params = param0 , data = xgtrain , watchlist = watchlist , print.every.n = 100 , nthread = 8 ) p <- predict(model, xgval) rm(model) gc() p } # Set parameters of the algorithm: eta and max_depth can control overfitting # logloss is the evaluation metric used for evaluation param0 <- list( # general , non specific params - just guessing "objective" = "binary:logistic" , "eval_metric" = "logloss" , "eta" = 0.01 , "subsample" = 0.8 , "colsample_bytree" = 0.8 , "min_child_weight" = 1 , "max_depth" = 10 ) # Preparing submission file submission <- read.table("sample_submission.csv", header=TRUE, sep=',') ensemble <- rep(0, nrow(test)) # change to 1:n to get an ensemble of 'n' trained models for (i in 1:2) { p <- doPrediction(y, train, test, param0, 1200) ensemble <- ensemble + p } submission$PredictedProb <- ensemble/i # writing the submission file write.csv(submission, "submission.csv", row.names=F, quote=F)
/BNP-Paribas-Claims-Management/XgBoost_SSK_MAG.R
no_license
saurabhkulkarni2312/R-Projects
R
false
false
2,713
r
## KAGGLE CONTEST: BNPP DATASET ## MATH 289 FINAL REPORT ## AUTHORS: MITESH GADGIL & sAURABH KULKARNI ## PREDICTIVE MODELLING USING XGBOOST library(xgboost) # Inputting data test <- read.csv("test.csv") train <- read.csv("train.csv") # Replacing missing data with NA train[train ==""] <- NA test[test ==""] <- NA # Storing "target" as a different vector and equalizing test and train data columns y <- train[, 'target'] train <- train[, -2] # the number of NA's in a data point are stored to be used as a feature feature_NA.train <- apply(train,1,function(x)sum(is.na(x))) feature_NA.test <- apply(test,1,function(x)sum(is.na(x))) train[is.na(train)] <- -1 test[is.na(test)] <- -1 # Find factor variables and translate to numeric # store column numbers of factor attributes in f and f.t f <- c() for(i in 1:ncol(train)) { if (is.factor(train[, i])) f <- c(f, i) } f.t <- c() for(i in 1:ncol(test)) { if (is.factor(test[, i])) f.t <- c(f.t, i) } # COnverting the test and training sets into numeric variables ttrain <- rbind(train, test) for (i in f) { ttrain[, i] <- as.numeric(ttrain[, i]) } train <- ttrain[1:nrow(train), ] train <- cbind.data.frame(train,"feature"=feature_NA.train) test <- ttrain[(nrow(train)+1):nrow(ttrain), ] test <- cbind.data.frame(test,"feature"=feature_NA.test) # the function that returns probability vector for test set after training according to #parameters in param0 for number of iterations given in 'iter' doPrediction <- function(y, train, test, param0, iter) { n<- nrow(train) xgtrain <- xgb.DMatrix(as.matrix(train), label = y,missing = NaN) xgval = xgb.DMatrix(as.matrix(test),missing = NaN) watchlist <- list('train' = xgtrain) model = xgb.train( nrounds = iter , params = param0 , data = xgtrain , watchlist = watchlist , print.every.n = 100 , nthread = 8 ) p <- predict(model, xgval) rm(model) gc() p } # Set parameters of the algorithm: eta and max_depth can control overfitting # logloss is the evaluation metric used for evaluation param0 <- list( # general , non specific params - just guessing "objective" = "binary:logistic" , "eval_metric" = "logloss" , "eta" = 0.01 , "subsample" = 0.8 , "colsample_bytree" = 0.8 , "min_child_weight" = 1 , "max_depth" = 10 ) # Preparing submission file submission <- read.table("sample_submission.csv", header=TRUE, sep=',') ensemble <- rep(0, nrow(test)) # change to 1:n to get an ensemble of 'n' trained models for (i in 1:2) { p <- doPrediction(y, train, test, param0, 1200) ensemble <- ensemble + p } submission$PredictedProb <- ensemble/i # writing the submission file write.csv(submission, "submission.csv", row.names=F, quote=F)
\name{add_names.ggplot2} \alias{add_names.ggplot2} \title{Add names to ggplot2 scatter plot points} \usage{ add_names.ggplot2(g, idx, label, ...) } \arguments{ \item{g}{a ggplot2 object} \item{idx}{index of the names to add. If \code{idx} is not specified, \code{\link{identify.ggplot2}} is called.} \item{label}{the name of the variable to be used for the names. If \code{label} is not specified, the indexes \code{idx} are used instead.} \item{...}{additional arguments to \code{\link{geom_text}}} } \value{ The ggplot2 object \code{g} with names added. } \description{ Add names to ggplot2 scatter plot points } \examples{ \donttest{ g=ggplot(data=mtcars,aes(x=wt,y=disp))+ geom_point(aes(color=as.factor(cyl))) add_names.ggplot2(g) } }
/man/add_names.ggplot2.Rd
no_license
kuremon/iggplot2
R
false
false
800
rd
\name{add_names.ggplot2} \alias{add_names.ggplot2} \title{Add names to ggplot2 scatter plot points} \usage{ add_names.ggplot2(g, idx, label, ...) } \arguments{ \item{g}{a ggplot2 object} \item{idx}{index of the names to add. If \code{idx} is not specified, \code{\link{identify.ggplot2}} is called.} \item{label}{the name of the variable to be used for the names. If \code{label} is not specified, the indexes \code{idx} are used instead.} \item{...}{additional arguments to \code{\link{geom_text}}} } \value{ The ggplot2 object \code{g} with names added. } \description{ Add names to ggplot2 scatter plot points } \examples{ \donttest{ g=ggplot(data=mtcars,aes(x=wt,y=disp))+ geom_point(aes(color=as.factor(cyl))) add_names.ggplot2(g) } }
#Challenge_06.1 'Everlasting Love' # Your name is Julie, and you're a brand new freshman at BYU-Idaho # In the last three weeks you've given your number to 32 different boys, but only kissed 8 of them. # But no more of that because you have a boyfriend. His name is Cody and he's the most wonderful man in the world. # You've already had the marriage talk, and you're both positive that you're the most perfect match ever. # Lately though, you've been noticing how cute Kody's roommate, Dylan is. You've written your (soon to be) ex boyfriend pages and pages # Of love letters already and it would be a downright shame to let all that effort go to waste on someone that # Isn't as cute as Dylan. # Challenge: Replace all mentions of Cody in the love letter with Dylan. Don't mess up or else you could be in # A terribly awkward situation! #Bonus: That's not my name # Input Data (data/input_data_06.1.txt): #sample: #Cody, after being your best friend and telling you all my hopes and desires, #I need to tell you what will make me happy. #Your code here: #Answer:
/user_challenges/love_letter_challenge.R
no_license
dylanjm/dss_coding_challenge
R
false
false
1,075
r
#Challenge_06.1 'Everlasting Love' # Your name is Julie, and you're a brand new freshman at BYU-Idaho # In the last three weeks you've given your number to 32 different boys, but only kissed 8 of them. # But no more of that because you have a boyfriend. His name is Cody and he's the most wonderful man in the world. # You've already had the marriage talk, and you're both positive that you're the most perfect match ever. # Lately though, you've been noticing how cute Kody's roommate, Dylan is. You've written your (soon to be) ex boyfriend pages and pages # Of love letters already and it would be a downright shame to let all that effort go to waste on someone that # Isn't as cute as Dylan. # Challenge: Replace all mentions of Cody in the love letter with Dylan. Don't mess up or else you could be in # A terribly awkward situation! #Bonus: That's not my name # Input Data (data/input_data_06.1.txt): #sample: #Cody, after being your best friend and telling you all my hopes and desires, #I need to tell you what will make me happy. #Your code here: #Answer:
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/systat.reader.R \name{systat.reader} \alias{systat.reader} \title{Read a Systat file with a .sys or .syd file extension.} \usage{ systat.reader(data.file, filename, variable.name) } \arguments{ \item{data.file}{The name of the data file to be read.} \item{filename}{The path to the data set to be loaded.} \item{variable.name}{The name to be assigned to in the global environment.} } \value{ No value is returned; this function is called for its side effects. } \description{ This function will load the specified Systat file into memory. } \examples{ library('ProjectTemplate2') \dontrun{systat.reader('example.sys', 'data/example.sys', 'example')} }
/man/systat.reader.Rd
no_license
connectedblue/ProjectTemplate2
R
false
true
733
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/systat.reader.R \name{systat.reader} \alias{systat.reader} \title{Read a Systat file with a .sys or .syd file extension.} \usage{ systat.reader(data.file, filename, variable.name) } \arguments{ \item{data.file}{The name of the data file to be read.} \item{filename}{The path to the data set to be loaded.} \item{variable.name}{The name to be assigned to in the global environment.} } \value{ No value is returned; this function is called for its side effects. } \description{ This function will load the specified Systat file into memory. } \examples{ library('ProjectTemplate2') \dontrun{systat.reader('example.sys', 'data/example.sys', 'example')} }
args = commandArgs(trailingOnly=TRUE) gibbsFile = args[1] sampleNum = args[2] g <- read.table(gibbsFile) g$samples <- rep(1:sampleNum, length(unique(g$V2))) gS <- spread(g, samples, V3) write.csv(gS, "Gibbs1.csv", row.names=FALSE, quote=FALSE)
/PICExample/RearrangeGibbs1.R
permissive
janaobsteter/Genotype_CODES
R
false
false
248
r
args = commandArgs(trailingOnly=TRUE) gibbsFile = args[1] sampleNum = args[2] g <- read.table(gibbsFile) g$samples <- rep(1:sampleNum, length(unique(g$V2))) gS <- spread(g, samples, V3) write.csv(gS, "Gibbs1.csv", row.names=FALSE, quote=FALSE)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sjPlotGroupPropTable.R \name{sjp.gpt} \alias{sjp.gpt} \title{Plot grouped proportional tables} \usage{ sjp.gpt(x, y, groups, geom.colors = "Set1", geom.size = 2.5, shape.fill.color = "#f0f0f0", shapes = c(15, 16, 17, 18, 21, 22, 23, 24, 25, 7, 8, 9, 10, 12), title = NULL, axis.labels = NULL, axis.titles = NULL, legend.title = NULL, legend.labels = NULL, wrap.title = 50, wrap.labels = 15, wrap.legend.title = 20, wrap.legend.labels = 20, axis.lim = NULL, grid.breaks = NULL, show.total = TRUE, annotate.total = TRUE, show.p = TRUE, show.n = TRUE, prnt.plot = TRUE) } \arguments{ \item{x}{categorical variable, where the proportion of each category in \code{x} for the highest category of \code{y} will be printed along the x-axis.} \item{y}{categorical or numeric variable. If not a binary variable, \code{y} will be recoded into a binary variable, dichtomized at the highest category and all remaining categories.} \item{groups}{grouping variable, which will define the y-axis} \item{geom.colors}{user defined color for geoms. See 'Details' in \code{\link{sjp.grpfrq}}.} \item{geom.size}{size resp. width of the geoms (bar width, line thickness or point size, depending on plot type and function). Note that bar and bin widths mostly need smaller values than dot sizes.} \item{shape.fill.color}{optional color vector, fill-color for non-filled shapes} \item{shapes}{numeric vector with shape styles, used to map the different categories of \code{x}.} \item{title}{character vector, used as plot title. Depending on plot type and function, will be set automatically. If \code{title = ""}, no title is printed.} \item{axis.labels}{character vector with labels used as axis labels. Optional argument, since in most cases, axis labels are set automatically.} \item{axis.titles}{character vector of length one or two, defining the title(s) for the x-axis and y-axis.} \item{legend.title}{character vector, used as title for the plot legend.} \item{legend.labels}{character vector with labels for the guide/legend.} \item{wrap.title}{numeric, determines how many chars of the plot title are displayed in one line and when a line break is inserted.} \item{wrap.labels}{numeric, determines how many chars of the value, variable or axis labels are displayed in one line and when a line break is inserted.} \item{wrap.legend.title}{numeric, determines how many chars of the legend's title are displayed in one line and when a line break is inserted.} \item{wrap.legend.labels}{numeric, determines how many chars of the legend labels are displayed in one line and when a line break is inserted.} \item{axis.lim}{numeric vector of length 2, defining the range of the plot axis. Depending on plot type, may effect either x- or y-axis, or both. For multiple plot outputs (e.g., from \code{type = "eff"} or \code{type = "slope"} in \code{\link{sjp.glm}}), \code{axis.lim} may also be a list of vectors of length 2, defining axis limits for each plot (only if non-faceted).} \item{grid.breaks}{numeric; sets the distance between breaks for the axis, i.e. at every \code{grid.breaks}'th position a major grid is being printed.} \item{show.total}{logical, if \code{TRUE}, a total summary line for all aggregated \code{groups} is added.} \item{annotate.total}{logical, if \code{TRUE} and \code{show.total = TRUE}, the total-row in the figure will be highlighted with a slightly shaded background.} \item{show.p}{logical, adds significance levels to values, or value and variable labels.} \item{show.n}{logical, if \code{TRUE}, adds total number of cases for each group or category to the labels.} \item{prnt.plot}{logical, if \code{TRUE} (default), plots the results as graph. Use \code{FALSE} if you don't want to plot any graphs. In either case, the ggplot-object will be returned as value.} } \value{ (Insisibily) returns the ggplot-object with the complete plot (\code{plot}) as well as the data frame that was used for setting up the ggplot-object (\code{df}). } \description{ Plot grouped proportional crosstables, where the proportion of each level of \code{x} for the highest category in \code{y} is plotted, for each subgroup of \code{groups}. } \details{ The p-values are based on \code{\link[stats]{chisq.test}} of \code{x} and \code{y} for each \code{groups}. } \examples{ library(sjmisc) data(efc) # the proportion of dependency levels in female # elderly, for each family carer's relationship # to elderly sjp.gpt(efc$e42dep, efc$e16sex, efc$e15relat) # proportion of educational levels in highest # dependency category of elderly, for different # care levels sjp.gpt(efc$c172code, efc$e42dep, efc$n4pstu) }
/man/sjp.gpt.Rd
no_license
RogerBorras/devel
R
false
true
4,796
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sjPlotGroupPropTable.R \name{sjp.gpt} \alias{sjp.gpt} \title{Plot grouped proportional tables} \usage{ sjp.gpt(x, y, groups, geom.colors = "Set1", geom.size = 2.5, shape.fill.color = "#f0f0f0", shapes = c(15, 16, 17, 18, 21, 22, 23, 24, 25, 7, 8, 9, 10, 12), title = NULL, axis.labels = NULL, axis.titles = NULL, legend.title = NULL, legend.labels = NULL, wrap.title = 50, wrap.labels = 15, wrap.legend.title = 20, wrap.legend.labels = 20, axis.lim = NULL, grid.breaks = NULL, show.total = TRUE, annotate.total = TRUE, show.p = TRUE, show.n = TRUE, prnt.plot = TRUE) } \arguments{ \item{x}{categorical variable, where the proportion of each category in \code{x} for the highest category of \code{y} will be printed along the x-axis.} \item{y}{categorical or numeric variable. If not a binary variable, \code{y} will be recoded into a binary variable, dichtomized at the highest category and all remaining categories.} \item{groups}{grouping variable, which will define the y-axis} \item{geom.colors}{user defined color for geoms. See 'Details' in \code{\link{sjp.grpfrq}}.} \item{geom.size}{size resp. width of the geoms (bar width, line thickness or point size, depending on plot type and function). Note that bar and bin widths mostly need smaller values than dot sizes.} \item{shape.fill.color}{optional color vector, fill-color for non-filled shapes} \item{shapes}{numeric vector with shape styles, used to map the different categories of \code{x}.} \item{title}{character vector, used as plot title. Depending on plot type and function, will be set automatically. If \code{title = ""}, no title is printed.} \item{axis.labels}{character vector with labels used as axis labels. Optional argument, since in most cases, axis labels are set automatically.} \item{axis.titles}{character vector of length one or two, defining the title(s) for the x-axis and y-axis.} \item{legend.title}{character vector, used as title for the plot legend.} \item{legend.labels}{character vector with labels for the guide/legend.} \item{wrap.title}{numeric, determines how many chars of the plot title are displayed in one line and when a line break is inserted.} \item{wrap.labels}{numeric, determines how many chars of the value, variable or axis labels are displayed in one line and when a line break is inserted.} \item{wrap.legend.title}{numeric, determines how many chars of the legend's title are displayed in one line and when a line break is inserted.} \item{wrap.legend.labels}{numeric, determines how many chars of the legend labels are displayed in one line and when a line break is inserted.} \item{axis.lim}{numeric vector of length 2, defining the range of the plot axis. Depending on plot type, may effect either x- or y-axis, or both. For multiple plot outputs (e.g., from \code{type = "eff"} or \code{type = "slope"} in \code{\link{sjp.glm}}), \code{axis.lim} may also be a list of vectors of length 2, defining axis limits for each plot (only if non-faceted).} \item{grid.breaks}{numeric; sets the distance between breaks for the axis, i.e. at every \code{grid.breaks}'th position a major grid is being printed.} \item{show.total}{logical, if \code{TRUE}, a total summary line for all aggregated \code{groups} is added.} \item{annotate.total}{logical, if \code{TRUE} and \code{show.total = TRUE}, the total-row in the figure will be highlighted with a slightly shaded background.} \item{show.p}{logical, adds significance levels to values, or value and variable labels.} \item{show.n}{logical, if \code{TRUE}, adds total number of cases for each group or category to the labels.} \item{prnt.plot}{logical, if \code{TRUE} (default), plots the results as graph. Use \code{FALSE} if you don't want to plot any graphs. In either case, the ggplot-object will be returned as value.} } \value{ (Insisibily) returns the ggplot-object with the complete plot (\code{plot}) as well as the data frame that was used for setting up the ggplot-object (\code{df}). } \description{ Plot grouped proportional crosstables, where the proportion of each level of \code{x} for the highest category in \code{y} is plotted, for each subgroup of \code{groups}. } \details{ The p-values are based on \code{\link[stats]{chisq.test}} of \code{x} and \code{y} for each \code{groups}. } \examples{ library(sjmisc) data(efc) # the proportion of dependency levels in female # elderly, for each family carer's relationship # to elderly sjp.gpt(efc$e42dep, efc$e16sex, efc$e15relat) # proportion of educational levels in highest # dependency category of elderly, for different # care levels sjp.gpt(efc$c172code, efc$e42dep, efc$n4pstu) }
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/DendSer.R \name{DendSer.dendrogram} \alias{DendSer.dendrogram} \title{Tries to run DendSer on a dendrogram} \usage{ DendSer.dendrogram(dend, ser_weight, ...) } \arguments{ \item{dend}{An object of class dendrogram} \item{ser_weight}{Used by cost function to evaluate ordering. For cost=costLS, this is a vector of object weights. Otherwise is a dist or symmetric matrix. passed to DendSer. If it is missing, the cophenetic distance is used instead.} \item{...}{parameters passed to \link[DendSer]{DendSer}} } \value{ Numeric vector giving an optimal dendrogram order } \description{ Implements dendrogram seriation. The function tries to turn the dend into hclust, on which it runs \link[DendSer]{DendSer}. Also, if a distance matrix is missing, it will try to use the \link{cophenetic} distance. } \examples{ \dontrun{ library(DendSer) # already used from within the function hc <- hclust(dist(USArrests[1:4,]), "ave") dend <- as.dendrogram(hc) DendSer.dendrogram(dend) } } \seealso{ \code{\link[DendSer]{DendSer}}, \link{DendSer.dendrogram} , \link{untangle_DendSer}, \link{rotate_DendSer} }
/man/DendSer.dendrogram.Rd
no_license
timelyportfolio/dendextend
R
false
false
1,187
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/DendSer.R \name{DendSer.dendrogram} \alias{DendSer.dendrogram} \title{Tries to run DendSer on a dendrogram} \usage{ DendSer.dendrogram(dend, ser_weight, ...) } \arguments{ \item{dend}{An object of class dendrogram} \item{ser_weight}{Used by cost function to evaluate ordering. For cost=costLS, this is a vector of object weights. Otherwise is a dist or symmetric matrix. passed to DendSer. If it is missing, the cophenetic distance is used instead.} \item{...}{parameters passed to \link[DendSer]{DendSer}} } \value{ Numeric vector giving an optimal dendrogram order } \description{ Implements dendrogram seriation. The function tries to turn the dend into hclust, on which it runs \link[DendSer]{DendSer}. Also, if a distance matrix is missing, it will try to use the \link{cophenetic} distance. } \examples{ \dontrun{ library(DendSer) # already used from within the function hc <- hclust(dist(USArrests[1:4,]), "ave") dend <- as.dendrogram(hc) DendSer.dendrogram(dend) } } \seealso{ \code{\link[DendSer]{DendSer}}, \link{DendSer.dendrogram} , \link{untangle_DendSer}, \link{rotate_DendSer} }
########################################## # Coliphage analysis - 6 beaches # v1 by Jade 11/3/15 # Illness figures for main text ########################################## rm(list=ls()) # -------------------------------------- # load the and pre-preprocess the # analysis dataset # (refer to the base functions script # for details on the pre-processing) # -------------------------------------- beaches13=read.csv("~/Documents/CRG/coliphage/13beaches-data/final/13beaches-analysis.csv") # load base functions source("~/Documents/CRG/coliphage/13beaches-coliphage/src/Analysis/0-base-functions.R") data=preprocess.6beaches(beaches13) # restrict to 6 beaches with coliphage data beach.list=c("Avalon","Doheny","Malibu","Mission Bay", "Fairhope","Goddard") all=data[data$beach %in% beach.list,] # drop individuals with no water quality information all=subset(all,nowq==0) # -------------------------------------- # % swimmers in waters with coliphage # -------------------------------------- sum(table(all$fmc.pres[all$bodycontact=="Yes"])) sum(table(all$fpc.pres[all$bodycontact=="Yes"])) prop.table(table(all$fmc.pres[all$bodycontact=="Yes"])) prop.table(table(all$fpc.pres[all$bodycontact=="Yes"])) # -------------------------------------- # illness rates # -------------------------------------- # illness rates among all enrollees table(all$gici10) prop.table(table(all$gici10)) prop.table(table(all$gici10,all$beach),2) # illness rates among swimmers table(all$gici10[all$bodycontact=="Yes"]) prop.table(table(all$gici10[all$bodycontact=="Yes"])) prop.table(table(all$gici10[all$bodycontact=="Yes"],all$beach[all$bodycontact=="Yes"]),2) # illness rates among non-swimmers table(all$gici10[all$anycontact=="No"]) prop.table(table(all$gici10[all$anycontact=="No"])) prop.table(table(all$gici10[all$anycontact=="No"],all$beach[all$anycontact=="No"]),2) # -------------------------------------- # regression for swimming only # -------------------------------------- swim.reg=glm(gici10~bodycontact+agecat+female+racewhite+gichron+anim_any+gicontactbase+ rawfood+beach,family=poisson(link="log"),data=all) # CIR for swimming exp(swim.reg$coef[["bodycontactYes"]]) exp(swim.reg$coef[["bodycontactYes"]]- qnorm(.975)*summary(swim.reg)$coefficients[2,2]) exp(swim.reg$coef[["bodycontactYes"]]+ qnorm(.975)*summary(swim.reg)$coefficients[2,2]) swimrisk.reg=glm(gici10~bodycontact*risk+agecat+female+racewhite+gichron+anim_any+gicontactbase+ rawfood+beach,family=poisson(link="log"),data=all) # CIR for swimming under high risk exp(swimrisk.reg$coef[["bodycontactYes"]]+ swimrisk.reg$coef[["bodycontactYes:riskHigh"]]) # CIR for swimming under low risk exp(swimrisk.reg$coef[["bodycontactYes"]]) lrtest(swim.reg,swimrisk.reg) save(swim.reg,file="~/Documents/CRG/coliphage/results/rawoutput/regress-10day-swim.Rdata")
/src/Analysis/7-illness-analysis.R
no_license
jadebc/13beaches-coliphage
R
false
false
2,864
r
########################################## # Coliphage analysis - 6 beaches # v1 by Jade 11/3/15 # Illness figures for main text ########################################## rm(list=ls()) # -------------------------------------- # load the and pre-preprocess the # analysis dataset # (refer to the base functions script # for details on the pre-processing) # -------------------------------------- beaches13=read.csv("~/Documents/CRG/coliphage/13beaches-data/final/13beaches-analysis.csv") # load base functions source("~/Documents/CRG/coliphage/13beaches-coliphage/src/Analysis/0-base-functions.R") data=preprocess.6beaches(beaches13) # restrict to 6 beaches with coliphage data beach.list=c("Avalon","Doheny","Malibu","Mission Bay", "Fairhope","Goddard") all=data[data$beach %in% beach.list,] # drop individuals with no water quality information all=subset(all,nowq==0) # -------------------------------------- # % swimmers in waters with coliphage # -------------------------------------- sum(table(all$fmc.pres[all$bodycontact=="Yes"])) sum(table(all$fpc.pres[all$bodycontact=="Yes"])) prop.table(table(all$fmc.pres[all$bodycontact=="Yes"])) prop.table(table(all$fpc.pres[all$bodycontact=="Yes"])) # -------------------------------------- # illness rates # -------------------------------------- # illness rates among all enrollees table(all$gici10) prop.table(table(all$gici10)) prop.table(table(all$gici10,all$beach),2) # illness rates among swimmers table(all$gici10[all$bodycontact=="Yes"]) prop.table(table(all$gici10[all$bodycontact=="Yes"])) prop.table(table(all$gici10[all$bodycontact=="Yes"],all$beach[all$bodycontact=="Yes"]),2) # illness rates among non-swimmers table(all$gici10[all$anycontact=="No"]) prop.table(table(all$gici10[all$anycontact=="No"])) prop.table(table(all$gici10[all$anycontact=="No"],all$beach[all$anycontact=="No"]),2) # -------------------------------------- # regression for swimming only # -------------------------------------- swim.reg=glm(gici10~bodycontact+agecat+female+racewhite+gichron+anim_any+gicontactbase+ rawfood+beach,family=poisson(link="log"),data=all) # CIR for swimming exp(swim.reg$coef[["bodycontactYes"]]) exp(swim.reg$coef[["bodycontactYes"]]- qnorm(.975)*summary(swim.reg)$coefficients[2,2]) exp(swim.reg$coef[["bodycontactYes"]]+ qnorm(.975)*summary(swim.reg)$coefficients[2,2]) swimrisk.reg=glm(gici10~bodycontact*risk+agecat+female+racewhite+gichron+anim_any+gicontactbase+ rawfood+beach,family=poisson(link="log"),data=all) # CIR for swimming under high risk exp(swimrisk.reg$coef[["bodycontactYes"]]+ swimrisk.reg$coef[["bodycontactYes:riskHigh"]]) # CIR for swimming under low risk exp(swimrisk.reg$coef[["bodycontactYes"]]) lrtest(swim.reg,swimrisk.reg) save(swim.reg,file="~/Documents/CRG/coliphage/results/rawoutput/regress-10day-swim.Rdata")
IterEigv <- function(CovM, StartV, m){ v <- matrix(0, nrow = nrow(CovM), ncol = m) v[,1] <- StartV w <- 0 for(i in 2:m){ w <- CovM%*%v[,i-1] v[,i] <- w/(sqrt(sum(w^2))) } return(v) }
/Blatt2/IterEigv.R
no_license
alexanderlange53/DataMining_in_Bioinformatics
R
false
false
201
r
IterEigv <- function(CovM, StartV, m){ v <- matrix(0, nrow = nrow(CovM), ncol = m) v[,1] <- StartV w <- 0 for(i in 2:m){ w <- CovM%*%v[,i-1] v[,i] <- w/(sqrt(sum(w^2))) } return(v) }
depvar.icc <- function(depvar, include.r3=TRUE, stratify="branch.office", treatments=c("credit", "cash", "info")) { rhs <- treatments reg.variables <- c(depvar, "village", "incentive", stratify, rhs) round2.data[, reg.variables] %>% mutate(round=2) %>% { if (include.r3) { bind_rows(., round3.data[, reg.variables] %>% mutate(round=3)) } else { return(.) } } %>% filter(incentive %in% treatments) %>% mutate_each(funs(factor), round) %>% icc(depvar, cluster="village", rhs=rhs, stratify=stratify) } foreach(depvar=c(depvars_T1_08), .combine=bind_rows) %do% { depvar.icc(depvar) %>% t %>% as.data.frame %>% mutate(depvar=depvar) } %>% bind_rows(depvar.icc("migrant", include.r3=FALSE) %>% t %>% as.data.frame %>% mutate(depvar="migrant")) %>% bind_rows(depvar.icc("ngo.help.migrate", stratify=c("branch.office"), include.r3=FALSE) %>% t %>% as.data.frame %>% mutate(depvar="ngo.help.migrate"))
/calc_icc_0809.R
no_license
evidenceaction/seasonal-migration
R
false
false
995
r
depvar.icc <- function(depvar, include.r3=TRUE, stratify="branch.office", treatments=c("credit", "cash", "info")) { rhs <- treatments reg.variables <- c(depvar, "village", "incentive", stratify, rhs) round2.data[, reg.variables] %>% mutate(round=2) %>% { if (include.r3) { bind_rows(., round3.data[, reg.variables] %>% mutate(round=3)) } else { return(.) } } %>% filter(incentive %in% treatments) %>% mutate_each(funs(factor), round) %>% icc(depvar, cluster="village", rhs=rhs, stratify=stratify) } foreach(depvar=c(depvars_T1_08), .combine=bind_rows) %do% { depvar.icc(depvar) %>% t %>% as.data.frame %>% mutate(depvar=depvar) } %>% bind_rows(depvar.icc("migrant", include.r3=FALSE) %>% t %>% as.data.frame %>% mutate(depvar="migrant")) %>% bind_rows(depvar.icc("ngo.help.migrate", stratify=c("branch.office"), include.r3=FALSE) %>% t %>% as.data.frame %>% mutate(depvar="ngo.help.migrate"))
suppressPackageStartupMessages(c( library(shinythemes), library(shiny), library(tm), library(stringr), library(markdown), library(stylo),library(stringi), library(ggplot2), library(magrittr), library(markdown), library(RWeka), library(openNLP), library(wordcloud), library(tm), library(NLP), library(qdap), library(RColorBrewer), library(dplyr))) y <- readRDS(file="./fourgramTable.RData") z <- readRDS(file="./threegramTable.RData") k <- readRDS(file="./twogramTable.RData") prediction_model <- function(x,y,z,k){ t<- tolower(x) t <- removePunctuation(t) t <- removeNumbers(t) t <- str_replace_all(t, "[^[:alnum:]]", " ") m<- paste(tail(unlist(strsplit(t,' ')),3), collapse=" ") u<- paste(tail(unlist(strsplit(t,' ')),2), collapse=" ") v<- paste(tail(unlist(strsplit(t,' ')),1), collapse=" ") if (stri_count_words(x)>2){ if (m %in% y$nminusgram){ i <- y %>% filter(nminusgram==m) %>% .$lastword print(i[1]) } else if (u %in% z$nminusgram){ i <- z %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else if (v %in% k$nminusgram){ i <- k %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else {print('the')} } else if(stri_count_words(x)==2){ if (u %in% z$nminusgram){ i <- z %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else if (v %in% k$nminusgram){ i <- k %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else {print('the')} } else if(stri_count_words(x)==1){ if (v %in% k$nminusgram){ i <- k %>% filter(nminusgram==u) %>% .$lastword print(i[1]) }else {print('the')} } else {print('wrong input')} }
/PredictionFunction.R
no_license
abharga6/word-prediction-capstone
R
false
false
1,727
r
suppressPackageStartupMessages(c( library(shinythemes), library(shiny), library(tm), library(stringr), library(markdown), library(stylo),library(stringi), library(ggplot2), library(magrittr), library(markdown), library(RWeka), library(openNLP), library(wordcloud), library(tm), library(NLP), library(qdap), library(RColorBrewer), library(dplyr))) y <- readRDS(file="./fourgramTable.RData") z <- readRDS(file="./threegramTable.RData") k <- readRDS(file="./twogramTable.RData") prediction_model <- function(x,y,z,k){ t<- tolower(x) t <- removePunctuation(t) t <- removeNumbers(t) t <- str_replace_all(t, "[^[:alnum:]]", " ") m<- paste(tail(unlist(strsplit(t,' ')),3), collapse=" ") u<- paste(tail(unlist(strsplit(t,' ')),2), collapse=" ") v<- paste(tail(unlist(strsplit(t,' ')),1), collapse=" ") if (stri_count_words(x)>2){ if (m %in% y$nminusgram){ i <- y %>% filter(nminusgram==m) %>% .$lastword print(i[1]) } else if (u %in% z$nminusgram){ i <- z %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else if (v %in% k$nminusgram){ i <- k %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else {print('the')} } else if(stri_count_words(x)==2){ if (u %in% z$nminusgram){ i <- z %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else if (v %in% k$nminusgram){ i <- k %>% filter(nminusgram==u) %>% .$lastword print(i[1]) } else {print('the')} } else if(stri_count_words(x)==1){ if (v %in% k$nminusgram){ i <- k %>% filter(nminusgram==u) %>% .$lastword print(i[1]) }else {print('the')} } else {print('wrong input')} }
################################################################################ ################################################################################ # Objective: Geometric approach. # Author: Tiago Tambonis and Marcelo Boareto. # Additional informations: # Date: 08/2017. ################################################################################ ################################################################################ GA<- function(counts.dat, group){ colnames(counts.dat) <- factor(group) condA <- counts.dat[,colnames(counts.dat)==1] condB <- counts.dat[,colnames(counts.dat)==2] f_diff <- data.frame() f_diff_temp = 0 n_diff = 0 for (k in seq(1, dim(counts.dat)[1])){ for (i in seq(1, dim(condA)[2])){ for (j in seq(1, dim(condB)[2])){ f_diff_temp = f_diff_temp + abs(condA[k,i] - condB[k,j]) n_diff = n_diff + 1 } } f_diff = rbind(f_diff, f_diff_temp) f_diff_temp = 0 } n_same = 0 f_same_A = data.frame() f_same_temp = 0 combinations <- combn(1:(dim(condA)[2]), 2) for (k in seq(1, dim(counts.dat)[1])){ for (i in seq(1:dim(combinations)[2])){ f_same_temp = f_same_temp + abs(condA[k,combinations[1,i]] - condA[k,combinations[2,i]]) n_same = n_same + 1 } f_same_A = rbind(f_same_A, f_same_temp) f_same_temp = 0 } f_same_B = data.frame() f_same_temp = 0 combinations <- combn(1:(dim(condB)[2]), 2) for (k in seq(1, dim(counts.dat)[1])){ for (i in seq(1:dim(combinations)[2])){ f_same_temp = f_same_temp + abs(condB[k,combinations[1,i]] - condB[k,combinations[2,i]]) n_same = n_same + 1 } f_same_B = rbind(f_same_B, f_same_temp) f_same_temp = 0 } f_same = f_same_A + f_same_B w = (f_diff/n_diff)**2 - (f_same/n_same)**2 w[w<0] = 0 w = w/sqrt(sum((w**2))) rownames(w) <- rownames(counts.dat) colnames(w) <- "Results" return(w) }
/Codes/Fold-change/Geometric_Approach.R
no_license
tambonis/GA_RNA_Seq
R
false
false
1,957
r
################################################################################ ################################################################################ # Objective: Geometric approach. # Author: Tiago Tambonis and Marcelo Boareto. # Additional informations: # Date: 08/2017. ################################################################################ ################################################################################ GA<- function(counts.dat, group){ colnames(counts.dat) <- factor(group) condA <- counts.dat[,colnames(counts.dat)==1] condB <- counts.dat[,colnames(counts.dat)==2] f_diff <- data.frame() f_diff_temp = 0 n_diff = 0 for (k in seq(1, dim(counts.dat)[1])){ for (i in seq(1, dim(condA)[2])){ for (j in seq(1, dim(condB)[2])){ f_diff_temp = f_diff_temp + abs(condA[k,i] - condB[k,j]) n_diff = n_diff + 1 } } f_diff = rbind(f_diff, f_diff_temp) f_diff_temp = 0 } n_same = 0 f_same_A = data.frame() f_same_temp = 0 combinations <- combn(1:(dim(condA)[2]), 2) for (k in seq(1, dim(counts.dat)[1])){ for (i in seq(1:dim(combinations)[2])){ f_same_temp = f_same_temp + abs(condA[k,combinations[1,i]] - condA[k,combinations[2,i]]) n_same = n_same + 1 } f_same_A = rbind(f_same_A, f_same_temp) f_same_temp = 0 } f_same_B = data.frame() f_same_temp = 0 combinations <- combn(1:(dim(condB)[2]), 2) for (k in seq(1, dim(counts.dat)[1])){ for (i in seq(1:dim(combinations)[2])){ f_same_temp = f_same_temp + abs(condB[k,combinations[1,i]] - condB[k,combinations[2,i]]) n_same = n_same + 1 } f_same_B = rbind(f_same_B, f_same_temp) f_same_temp = 0 } f_same = f_same_A + f_same_B w = (f_diff/n_diff)**2 - (f_same/n_same)**2 w[w<0] = 0 w = w/sqrt(sum((w**2))) rownames(w) <- rownames(counts.dat) colnames(w) <- "Results" return(w) }
# Distance to points - parallelized # H. Achicanoy # Jul - 2013 source(paste(src.dir,"/000.zipWrite.R",sep="")) populationDistance <- function(bdir,spID) { idir <- paste(bdir, "/maxent_modeling", sep="") odir <- paste(bdir, "/samples_calculations", sep="") spOutFolder <- paste(odir,"/",spID, sep="") cat("Loading occurrences \n") occ <- read.csv(paste(bdir, "/occurrence_files/",spID, ".csv", sep="")) xy <- occ[,2:3] cat("Loading mask \n") msk <- raster(paste(bdir, "/masks/mask.asc", sep="")) cat("Distance from points \n") dgrid <- distanceFromPoints(msk, xy) dgrid[which(is.na(msk[]))] <- NA cat("Writing output \n") dumm <- zipWrite(dgrid, spOutFolder, "pop-dist.asc.gz") return(dgrid) } summarizeDistances <- function(bdir) { spList <- list.files(paste(bdir, "/occurrence_files", sep="")) sppC <- 1 for (spp in spList) { spp <- unlist(strsplit(spp, ".", fixed=T))[1] pdir <- paste(bdir,"/samples_calculations/",spp,sep="") #pop=sum(pdir=="pop-dist.asc.gz") if(file.exists(paste(pdir,"/pop-dist.asc.gz",sep=""))){ cat("The file already exists",spp,"\n") }else{ cat("Processing taxon", spp, "\n") if(!file.exists(pdir)){dir.create(pdir)} dg <- populationDistance(bdir, spp)} } return(spList) } ParProcess <- function(bdir, ncpu) { spList <- list.files(paste(bdir, "/occurrence_files", sep=""),pattern=".csv") pDist_wrapper <- function(i) { library(raster) library(rgdal) sp <- spList[i] sp <- unlist(strsplit(sp, ".", fixed=T))[1] cat("\n") cat("...Species", sp, "\n") out <- summarizeDistances(bdir) } library(snowfall) sfInit(parallel=T,cpus=ncpu) sfExport("populationDistance") sfExport("summarizeDistances") sfExport("zipWrite") sfExport("bdir") sfExport("src.dir") sfExport("spList") #run the control function system.time(sfSapply(as.vector(1:length(spList)), pDist_wrapper)) #stop the cluster sfStop() return("Done!") }
/011.distanceToPopulations2.R
no_license
vbern/gap-analysis-maxent
R
false
false
2,008
r
# Distance to points - parallelized # H. Achicanoy # Jul - 2013 source(paste(src.dir,"/000.zipWrite.R",sep="")) populationDistance <- function(bdir,spID) { idir <- paste(bdir, "/maxent_modeling", sep="") odir <- paste(bdir, "/samples_calculations", sep="") spOutFolder <- paste(odir,"/",spID, sep="") cat("Loading occurrences \n") occ <- read.csv(paste(bdir, "/occurrence_files/",spID, ".csv", sep="")) xy <- occ[,2:3] cat("Loading mask \n") msk <- raster(paste(bdir, "/masks/mask.asc", sep="")) cat("Distance from points \n") dgrid <- distanceFromPoints(msk, xy) dgrid[which(is.na(msk[]))] <- NA cat("Writing output \n") dumm <- zipWrite(dgrid, spOutFolder, "pop-dist.asc.gz") return(dgrid) } summarizeDistances <- function(bdir) { spList <- list.files(paste(bdir, "/occurrence_files", sep="")) sppC <- 1 for (spp in spList) { spp <- unlist(strsplit(spp, ".", fixed=T))[1] pdir <- paste(bdir,"/samples_calculations/",spp,sep="") #pop=sum(pdir=="pop-dist.asc.gz") if(file.exists(paste(pdir,"/pop-dist.asc.gz",sep=""))){ cat("The file already exists",spp,"\n") }else{ cat("Processing taxon", spp, "\n") if(!file.exists(pdir)){dir.create(pdir)} dg <- populationDistance(bdir, spp)} } return(spList) } ParProcess <- function(bdir, ncpu) { spList <- list.files(paste(bdir, "/occurrence_files", sep=""),pattern=".csv") pDist_wrapper <- function(i) { library(raster) library(rgdal) sp <- spList[i] sp <- unlist(strsplit(sp, ".", fixed=T))[1] cat("\n") cat("...Species", sp, "\n") out <- summarizeDistances(bdir) } library(snowfall) sfInit(parallel=T,cpus=ncpu) sfExport("populationDistance") sfExport("summarizeDistances") sfExport("zipWrite") sfExport("bdir") sfExport("src.dir") sfExport("spList") #run the control function system.time(sfSapply(as.vector(1:length(spList)), pDist_wrapper)) #stop the cluster sfStop() return("Done!") }
setwd("C:/Users/James/Documents/GitHub/ExData_Plotting1") download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip","rawdata.zip") unzip("rawdata.zip") rawdb <- read.table("household_power_consumption.txt", header = T,sep = ";",na.strings = c("NA","?"), colClasses = c("character","character","numeric", "numeric","numeric","numeric", "numeric","numeric","numeric")) rawdb <- rawdb[rawdb$Date %in% c("1/2/2007","2/2/2007"),] rawdb$DateTime <- paste(rawdb$Date,rawdb$Time) rawdb$DateTime <- strptime(rawdb$DateTime,"%d/%m/%Y %H:%M:%S") db <- rawdb png("plot3.png", width = 480, height = 480) plot(db$DateTime,db$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering") lines(db$DateTime,db$Sub_metering_2,col = "red") lines(db$DateTime,db$Sub_metering_3,col = "blue") legend("topright", lty = c(1,1,1), col = c("black","red","blue"), legend = c("Sub_metering_1", "Sub_metering_2","Sub_metering_3")) dev.off()
/plot3.R
no_license
jferre/ExData_Plotting1
R
false
false
1,099
r
setwd("C:/Users/James/Documents/GitHub/ExData_Plotting1") download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip","rawdata.zip") unzip("rawdata.zip") rawdb <- read.table("household_power_consumption.txt", header = T,sep = ";",na.strings = c("NA","?"), colClasses = c("character","character","numeric", "numeric","numeric","numeric", "numeric","numeric","numeric")) rawdb <- rawdb[rawdb$Date %in% c("1/2/2007","2/2/2007"),] rawdb$DateTime <- paste(rawdb$Date,rawdb$Time) rawdb$DateTime <- strptime(rawdb$DateTime,"%d/%m/%Y %H:%M:%S") db <- rawdb png("plot3.png", width = 480, height = 480) plot(db$DateTime,db$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering") lines(db$DateTime,db$Sub_metering_2,col = "red") lines(db$DateTime,db$Sub_metering_3,col = "blue") legend("topright", lty = c(1,1,1), col = c("black","red","blue"), legend = c("Sub_metering_1", "Sub_metering_2","Sub_metering_3")) dev.off()
#================================================================== # Install packages not already installed in a list #================================================================== rm(list=ls()) list=c("tidyverse","stringr","forcats","ggmap","rvest","tm","SnowballC","dplyr","calibrate","doParallel", "stringi","ggplot2","maps","httr","rsdmx","devtools","plyr","dplyr","ggplot2","caret","elasticnet", "magrittr","broom","glmnet","Hmisc",'knitr',"RSQLite","RANN","lubridate","ggvis","plotly","lars", "ggcorrplot","GGally","ROCR","lattice","car","corrgram","ggcorrplot","parallel","readxl","ggmosaic", "vcd","Amelia","d3heatmap","ResourceSelection","ROCR","plotROC","DT","aod","mice","Hmisc","data.table", "corrplot","gvlma") list_packages <- list new.packages <- list_packages[!(list_packages %in% installed.packages()[,"Package"])] if(length(new.packages)) install.packages(new.packages) R<-suppressWarnings(suppressMessages(sapply(list, require, character.only = TRUE))) setwd("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines") data=data.table::fread("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/Take_home_Stats_test_Data.xlsx") #install.packages("xlsx") require(xlsx) FirstTable <- read.xlsx("Take_home_Stats_test_Data.xlsx", 1 , stringsAsFactors=F) read.xlsx("Take_home_Stats_test_Data.xlsx", sheetName = "Sheet1") read.xlsx2("Take_home_Stats_test_Data.xlsx", sheetName = "Sheet1") #devtools::install_github("hadley/readxl") # development version library(readxl) # read_excel reads both xls and xlsx files uniteddata=read_excel("Take_home_Stats_test_Data.xlsx") # Specify sheet with a number or name #read_excel("my-spreadsheet.xls", sheet = "data") #read_excel("my-spreadsheet.xls", sheet = 2) # If NAs are represented by something other than blank cells, # set the na argument #read_excel("my-spreadsheet.xls", na = "NA") model1=glm(Y~X1+X2,data=uniteddata) broom::tidy(model1) tidyr::gather(uniteddata) head(broom::augment(model1)) broom::glance(model1) #install.packages("plsdepot") library(pls) model2=pls::plsr(Y~X1+X2,data=uniteddata,ncomp=1) summary(model2) biplot(model2) plot(model2, plottype = "biplot") library(plsdepot) model3=plsdepot::plsreg1(uniteddata[,3:4],uniteddata["Y"],comps=1, crosval=TRUE) model3=mvr(Y~X1+X2,data=uniteddata,comps=1, crosval=TRUE) model3$cor.xyt model3$reg.coefs model3$R2 plot(model3) selectNcomp(model3) pls::crossval(model3) pls::coefplot(model3) #load semPLS and datasets #install.packages("BiplotGUI") library(semPLS) data(mobi) data(ECSImobi) #runs PLS SEM ecsi <- sempls(Y=X1+X2, data=uniteddata, E="C") ecsi #calculate percent variation (prcomp(scale(mobi))$sdev^2)/24 #load and open BiPlotGUI library(BiplotGUI) Biplots(uniteddata, PointLabels=NULL) #right click on biplot #select "Predict points closest to cursor positions" #Select Prediction Tab in top-right frame pcr_model <- pcr(Y~., data = uniteddata, scale = TRUE, validation = "CV") summary(pcr_model) # Plot the root mean squared error validationplot(pcr_model) # Plot the cross validation MSE validationplot(pcr_model, val.type="MSEP") # Plot the R2 validationplot(pcr_model, val.type = "R2") predplot(pcr_model) coefplot(pcr_model) # Train-test split # Pricipal Components Analysis # entering raw data and extracting PCs # from the correlation matrix fit <- princomp(uniteddata, cor=TRUE) summary(fit) # print variance accounted for loadings(fit) # pc loadings plot(fit,type="lines") # scree plot fit$scores # the principal components biplot(fit) # Maximum Likelihood Factor Analysis # entering raw data and extracting 3 factors, # with varimax rotation fit <- factanal(uniteddata[,-1], 1, rotation="varimax") print(fit, digits=2, cutoff=.3, sort=TRUE) # plot factor 1 by factor 2 load <- fit$loadings[,1:2] plot(load,type="n") # set up plot text(load,labels=names(uniteddata[,-1]),cex=.7) # add variable names # Varimax Rotated Principal Components # retaining 5 components library(psych) fit <- principal(uniteddata[,-1], nfactors=1, rotate="varimax") fit # print results factanal(uniteddata[,-1],1) y_test <-uniteddata["Y"] index <- createDataPartition(uniteddata$Y,p=0.70, list=FALSE) trainSet <- uniteddata[index,] testSet <- uniteddata[-index,] pcr_model <- pcr(Y~., data = trainSet,scale =TRUE, validation = "CV",ncomp=1) pcr_pred <- predict(pcr_model, testSet, ncomp = 1) mean((pcr_pred - y_test)^2) data.table::melt.data.table(as.data.table(uniteddata)) tidyr::gather(uniteddata) data.table::dcast.data.table() reshape2::melt(uniteddata) uniteddata2=data_frame(No.Trial=c(seq(1:13)),No=c(29,16,17,4,3,9,4,5,1,1,1,3,7) ,Yes=c(198,107,55,38,18,22,7,9,5,3,6,6,12)) m1=reshape2::melt(uniteddata2,id.vars ="No.Trial",variable.name ="Driving.school",value.name ="Frequency") m2= reshape2::dcast(reshape2::melt(uniteddata2,id.vars ="No.Trial"),No.Trial~variable ) hist(m1$Frequency,breaks = "fd") hist(log(m1$Trials),breaks = "fd") l=list(xtabs(~Trials+Driving.school+No.Trial,data=m1)) do.call(chisq.test,xtabs(~No.Trial+Driving.school+Trials,data=m1)) tmp <- expand.grid(letters[1:2], 1:3, c("+", "-")) do.call("paste", c(tmp, sep = "")) by(m1, m1["No.Trial"], function(x) chisq.test) fisher.test(xtabs(No.Trial~Driving.school+Trials, data=m1),workspace = 200000000) chisq.test(xtabs(No.Trial~Driving.school+Frequency, data=m1),simulate.p.value = T)%>%tidy() ggplot(m1, aes(No.Trial,Frequency, group=Driving.school, linetype=Driving.school, shape=Driving.school)) + geom_line() +geom_point() p=ggplot(m1, aes(No.Trial,Frequency, color=Driving.school)) + geom_line() + geom_point()+theme_bw()+xlab("Number of Trials") ggplotly(p) ggsave("p.pdf") p1=ggplot(m1, aes( No.Trial,Frequency, color=Driving.school)) + theme_bw()+ geom_smooth(se = FALSE, method = "loess") ggplotly(p1) ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/p1.pdf") p2=ggplot(m1, aes( No.Trial,Frequency, color=Driving.school)) + theme_bw()+ geom_histogram() ggplotly(p2) ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/p2.pdf") p2=ggplot(m1, aes(No.Trial,Frequency, color=Driving.school)) + geom_line() + theme_bw() ggplotly(p2) model4=glm(log(Frequency)~(No.Trial)+Driving.school+No.Trial*Driving.school,data=m1) summary(model4) m1$Driving.school=if_else(m1$Driving.school=="Yes",1,0) model5=glm(Driving.school~(No.Trial)+log(Frequency)+No.Trial*log(Frequency),data=m1,family="binomial") summary(model5) model6=glm(Driving.school~(No.Trial)+log(Frequency)+No.Trial*log(Frequency),data=m1,family="binomial") summary(model6) str(m1) pq=qplot(log( m1$Frequency), geom="histogram",binwidth = 0.5)+theme_minimal()+xlab("log(Number of Trials)") ggplotly(pq) ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/plott.pdf") qplot((m1$Frequency), geom="histogram",binwidth = 2)+theme_minimal()+xlab("Number of Trials") ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/plot3.pdf") ?tapply
/United.R
no_license
NanaAkwasiAbayieBoateng/United
R
false
false
7,265
r
#================================================================== # Install packages not already installed in a list #================================================================== rm(list=ls()) list=c("tidyverse","stringr","forcats","ggmap","rvest","tm","SnowballC","dplyr","calibrate","doParallel", "stringi","ggplot2","maps","httr","rsdmx","devtools","plyr","dplyr","ggplot2","caret","elasticnet", "magrittr","broom","glmnet","Hmisc",'knitr',"RSQLite","RANN","lubridate","ggvis","plotly","lars", "ggcorrplot","GGally","ROCR","lattice","car","corrgram","ggcorrplot","parallel","readxl","ggmosaic", "vcd","Amelia","d3heatmap","ResourceSelection","ROCR","plotROC","DT","aod","mice","Hmisc","data.table", "corrplot","gvlma") list_packages <- list new.packages <- list_packages[!(list_packages %in% installed.packages()[,"Package"])] if(length(new.packages)) install.packages(new.packages) R<-suppressWarnings(suppressMessages(sapply(list, require, character.only = TRUE))) setwd("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines") data=data.table::fread("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/Take_home_Stats_test_Data.xlsx") #install.packages("xlsx") require(xlsx) FirstTable <- read.xlsx("Take_home_Stats_test_Data.xlsx", 1 , stringsAsFactors=F) read.xlsx("Take_home_Stats_test_Data.xlsx", sheetName = "Sheet1") read.xlsx2("Take_home_Stats_test_Data.xlsx", sheetName = "Sheet1") #devtools::install_github("hadley/readxl") # development version library(readxl) # read_excel reads both xls and xlsx files uniteddata=read_excel("Take_home_Stats_test_Data.xlsx") # Specify sheet with a number or name #read_excel("my-spreadsheet.xls", sheet = "data") #read_excel("my-spreadsheet.xls", sheet = 2) # If NAs are represented by something other than blank cells, # set the na argument #read_excel("my-spreadsheet.xls", na = "NA") model1=glm(Y~X1+X2,data=uniteddata) broom::tidy(model1) tidyr::gather(uniteddata) head(broom::augment(model1)) broom::glance(model1) #install.packages("plsdepot") library(pls) model2=pls::plsr(Y~X1+X2,data=uniteddata,ncomp=1) summary(model2) biplot(model2) plot(model2, plottype = "biplot") library(plsdepot) model3=plsdepot::plsreg1(uniteddata[,3:4],uniteddata["Y"],comps=1, crosval=TRUE) model3=mvr(Y~X1+X2,data=uniteddata,comps=1, crosval=TRUE) model3$cor.xyt model3$reg.coefs model3$R2 plot(model3) selectNcomp(model3) pls::crossval(model3) pls::coefplot(model3) #load semPLS and datasets #install.packages("BiplotGUI") library(semPLS) data(mobi) data(ECSImobi) #runs PLS SEM ecsi <- sempls(Y=X1+X2, data=uniteddata, E="C") ecsi #calculate percent variation (prcomp(scale(mobi))$sdev^2)/24 #load and open BiPlotGUI library(BiplotGUI) Biplots(uniteddata, PointLabels=NULL) #right click on biplot #select "Predict points closest to cursor positions" #Select Prediction Tab in top-right frame pcr_model <- pcr(Y~., data = uniteddata, scale = TRUE, validation = "CV") summary(pcr_model) # Plot the root mean squared error validationplot(pcr_model) # Plot the cross validation MSE validationplot(pcr_model, val.type="MSEP") # Plot the R2 validationplot(pcr_model, val.type = "R2") predplot(pcr_model) coefplot(pcr_model) # Train-test split # Pricipal Components Analysis # entering raw data and extracting PCs # from the correlation matrix fit <- princomp(uniteddata, cor=TRUE) summary(fit) # print variance accounted for loadings(fit) # pc loadings plot(fit,type="lines") # scree plot fit$scores # the principal components biplot(fit) # Maximum Likelihood Factor Analysis # entering raw data and extracting 3 factors, # with varimax rotation fit <- factanal(uniteddata[,-1], 1, rotation="varimax") print(fit, digits=2, cutoff=.3, sort=TRUE) # plot factor 1 by factor 2 load <- fit$loadings[,1:2] plot(load,type="n") # set up plot text(load,labels=names(uniteddata[,-1]),cex=.7) # add variable names # Varimax Rotated Principal Components # retaining 5 components library(psych) fit <- principal(uniteddata[,-1], nfactors=1, rotate="varimax") fit # print results factanal(uniteddata[,-1],1) y_test <-uniteddata["Y"] index <- createDataPartition(uniteddata$Y,p=0.70, list=FALSE) trainSet <- uniteddata[index,] testSet <- uniteddata[-index,] pcr_model <- pcr(Y~., data = trainSet,scale =TRUE, validation = "CV",ncomp=1) pcr_pred <- predict(pcr_model, testSet, ncomp = 1) mean((pcr_pred - y_test)^2) data.table::melt.data.table(as.data.table(uniteddata)) tidyr::gather(uniteddata) data.table::dcast.data.table() reshape2::melt(uniteddata) uniteddata2=data_frame(No.Trial=c(seq(1:13)),No=c(29,16,17,4,3,9,4,5,1,1,1,3,7) ,Yes=c(198,107,55,38,18,22,7,9,5,3,6,6,12)) m1=reshape2::melt(uniteddata2,id.vars ="No.Trial",variable.name ="Driving.school",value.name ="Frequency") m2= reshape2::dcast(reshape2::melt(uniteddata2,id.vars ="No.Trial"),No.Trial~variable ) hist(m1$Frequency,breaks = "fd") hist(log(m1$Trials),breaks = "fd") l=list(xtabs(~Trials+Driving.school+No.Trial,data=m1)) do.call(chisq.test,xtabs(~No.Trial+Driving.school+Trials,data=m1)) tmp <- expand.grid(letters[1:2], 1:3, c("+", "-")) do.call("paste", c(tmp, sep = "")) by(m1, m1["No.Trial"], function(x) chisq.test) fisher.test(xtabs(No.Trial~Driving.school+Trials, data=m1),workspace = 200000000) chisq.test(xtabs(No.Trial~Driving.school+Frequency, data=m1),simulate.p.value = T)%>%tidy() ggplot(m1, aes(No.Trial,Frequency, group=Driving.school, linetype=Driving.school, shape=Driving.school)) + geom_line() +geom_point() p=ggplot(m1, aes(No.Trial,Frequency, color=Driving.school)) + geom_line() + geom_point()+theme_bw()+xlab("Number of Trials") ggplotly(p) ggsave("p.pdf") p1=ggplot(m1, aes( No.Trial,Frequency, color=Driving.school)) + theme_bw()+ geom_smooth(se = FALSE, method = "loess") ggplotly(p1) ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/p1.pdf") p2=ggplot(m1, aes( No.Trial,Frequency, color=Driving.school)) + theme_bw()+ geom_histogram() ggplotly(p2) ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/p2.pdf") p2=ggplot(m1, aes(No.Trial,Frequency, color=Driving.school)) + geom_line() + theme_bw() ggplotly(p2) model4=glm(log(Frequency)~(No.Trial)+Driving.school+No.Trial*Driving.school,data=m1) summary(model4) m1$Driving.school=if_else(m1$Driving.school=="Yes",1,0) model5=glm(Driving.school~(No.Trial)+log(Frequency)+No.Trial*log(Frequency),data=m1,family="binomial") summary(model5) model6=glm(Driving.school~(No.Trial)+log(Frequency)+No.Trial*log(Frequency),data=m1,family="binomial") summary(model6) str(m1) pq=qplot(log( m1$Frequency), geom="histogram",binwidth = 0.5)+theme_minimal()+xlab("log(Number of Trials)") ggplotly(pq) ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/plott.pdf") qplot((m1$Frequency), geom="histogram",binwidth = 2)+theme_minimal()+xlab("Number of Trials") ggsave("/Users/nanaakwasiabayieboateng/Documents/memphisclassesbooks/DataMiningscience/UnitedAirlines/plot3.pdf") ?tapply
\name{dccforecast-methods} \docType{methods} \alias{dccforecast} \alias{dccforecast,ANY-method} \alias{dccforecast,DCCfit-method} \title{function: DCC-GARCH Forecast} \description{ Method for creating a DCC-GARCH forecast object. } \usage{ dccforecast(fit, n.ahead = 1, n.roll = 0, external.forecasts = list(mregfor = NULL, vregfor = NULL), cluster = NULL, ...) } \arguments{ \item{fit}{ A \code{\linkS4class{DCCfit}} object created by calling \code{\link{dccfit}}.} \item{n.ahead}{ The forecast horizon.} \item{n.roll}{ The no. of rolling forecasts to create beyond the first one (see details).} \item{external.forecasts}{ A list with forecasts for the external regressors in the mean and/or variance equations if specified (see details).} \item{cluster}{ A cluster object created by calling \code{makeCluster} from the parallel package. If it is not NULL, then this will be used for parallel estimation (remember to stop the cluster on completion).} \item{...}{.} } \value{ A \code{\linkS4class{DCCforecast}} object containing details of the DCC-GARCH forecast. } \details{ When using \code{n.roll}, it is assumed that \code{\link{dccfit}} was called with argument \sQuote{out.sample} being large enough to cover n-rolling forecasts.\cr When n.roll = 0, all forecasts are based on an unconditional n-ahead forecast routine based on the approximation method described in ENGLE and SHEPPARD (2001) paper (see reference below). If any external regressors are present, then the user must pass in their unconditional forecasts in the \sQuote{external.forecasts} list, as matrices with dimensions equal to n.ahead x n.assets. This assumes that the univariate GARCH specifications share common external regressors (this may change in the future).\cr When n.roll>0 and n.ahead = 1, then this is a pure rolling forecast based on the available out.sample data provided for in the call to the fit routine. It is also assumed that if any external regressors were passed to the fit routine that they contained enough values to cover the out.sample period so that they could be used in this forecast scenario.\cr The case of n.roll > 0 AND n.ahead > 1 is not implemented.\cr } \references{ Engle, R.F. and Sheppard, K. 2001, Theoretical and empirical properties of dynamic conditional correlation multivariate GARCH, \emph{NBER Working Paper}.\cr } \author{Alexios Ghalanos} \keyword{methods}
/fuzzedpackages/rmgarch/man/dccforecast-methods.Rd
no_license
akhikolla/testpackages
R
false
false
2,488
rd
\name{dccforecast-methods} \docType{methods} \alias{dccforecast} \alias{dccforecast,ANY-method} \alias{dccforecast,DCCfit-method} \title{function: DCC-GARCH Forecast} \description{ Method for creating a DCC-GARCH forecast object. } \usage{ dccforecast(fit, n.ahead = 1, n.roll = 0, external.forecasts = list(mregfor = NULL, vregfor = NULL), cluster = NULL, ...) } \arguments{ \item{fit}{ A \code{\linkS4class{DCCfit}} object created by calling \code{\link{dccfit}}.} \item{n.ahead}{ The forecast horizon.} \item{n.roll}{ The no. of rolling forecasts to create beyond the first one (see details).} \item{external.forecasts}{ A list with forecasts for the external regressors in the mean and/or variance equations if specified (see details).} \item{cluster}{ A cluster object created by calling \code{makeCluster} from the parallel package. If it is not NULL, then this will be used for parallel estimation (remember to stop the cluster on completion).} \item{...}{.} } \value{ A \code{\linkS4class{DCCforecast}} object containing details of the DCC-GARCH forecast. } \details{ When using \code{n.roll}, it is assumed that \code{\link{dccfit}} was called with argument \sQuote{out.sample} being large enough to cover n-rolling forecasts.\cr When n.roll = 0, all forecasts are based on an unconditional n-ahead forecast routine based on the approximation method described in ENGLE and SHEPPARD (2001) paper (see reference below). If any external regressors are present, then the user must pass in their unconditional forecasts in the \sQuote{external.forecasts} list, as matrices with dimensions equal to n.ahead x n.assets. This assumes that the univariate GARCH specifications share common external regressors (this may change in the future).\cr When n.roll>0 and n.ahead = 1, then this is a pure rolling forecast based on the available out.sample data provided for in the call to the fit routine. It is also assumed that if any external regressors were passed to the fit routine that they contained enough values to cover the out.sample period so that they could be used in this forecast scenario.\cr The case of n.roll > 0 AND n.ahead > 1 is not implemented.\cr } \references{ Engle, R.F. and Sheppard, K. 2001, Theoretical and empirical properties of dynamic conditional correlation multivariate GARCH, \emph{NBER Working Paper}.\cr } \author{Alexios Ghalanos} \keyword{methods}
## Coursera - Exploratory Data Analysis - Course Project 1 - Plot 4 ## ## Create and Combine 4 different plots in one plot and export and save it as PNG Files ## Download the neccessary data file and save it into a file in the local working directory filename = "exdata_consumption.zip" if (!file.exists(filename)) { retval = download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", destfile = filename) } ## Unzip the file and read the data from the file Epc = read.csv(unz(filename, "household_power_consumption.txt"), header=T, sep=";", stringsAsFactors=F, na.strings="?", colClasses=c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric")) ## Format the date and time and then subset the data to time period 2007-02-01 to 2007-02-02 Epc$timestamp = strptime(paste(Epc$Date, Epc$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") FromDate = strptime("01/02/2007 00:00:00", format="%d/%m/%Y %H:%M:%S", tz="UTC") ToDate = strptime("02/02/2007 23:59:59", format="%d/%m/%Y %H:%M:%S", tz="UTC") Epc = Epc[Epc$timestamp >= FromDate & Epc$timestamp <= ToDate, ] ## Create the plot png(filename="plot4.png", width=480, height=480) # Use par() to combine the 4 plots par(mfcol=c(2,2)) # Create the first plot plot(Epc$timestamp, Epc$Global_active_power, type="l", xlab="", ylab="Global Active Power") # Create the second plot plot(Epc$timestamp, Epc$Sub_metering_1, type="l", xlab="", ylab="Energy sub metering") lines(Epc$timestamp, Epc$Sub_metering_2, col="red") lines(Epc$timestamp, Epc$Sub_metering_3, col="blue") legend("topright", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col=c("black", "red", "blue"), lwd=par("lwd"), bty="n") # Create the third Plot plot(Epc$timestamp, Epc$Voltage, type="l", xlab="datetime", ylab="Voltage") # Create the fourth plot plot(Epc$timestamp, Epc$Global_reactive_power, type="l", xlab="datetime", ylab="Global_reactive_power") dev.off()
/Plot4.R
no_license
Divyaratna/ExData_Plotting1
R
false
false
2,128
r
## Coursera - Exploratory Data Analysis - Course Project 1 - Plot 4 ## ## Create and Combine 4 different plots in one plot and export and save it as PNG Files ## Download the neccessary data file and save it into a file in the local working directory filename = "exdata_consumption.zip" if (!file.exists(filename)) { retval = download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", destfile = filename) } ## Unzip the file and read the data from the file Epc = read.csv(unz(filename, "household_power_consumption.txt"), header=T, sep=";", stringsAsFactors=F, na.strings="?", colClasses=c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric")) ## Format the date and time and then subset the data to time period 2007-02-01 to 2007-02-02 Epc$timestamp = strptime(paste(Epc$Date, Epc$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") FromDate = strptime("01/02/2007 00:00:00", format="%d/%m/%Y %H:%M:%S", tz="UTC") ToDate = strptime("02/02/2007 23:59:59", format="%d/%m/%Y %H:%M:%S", tz="UTC") Epc = Epc[Epc$timestamp >= FromDate & Epc$timestamp <= ToDate, ] ## Create the plot png(filename="plot4.png", width=480, height=480) # Use par() to combine the 4 plots par(mfcol=c(2,2)) # Create the first plot plot(Epc$timestamp, Epc$Global_active_power, type="l", xlab="", ylab="Global Active Power") # Create the second plot plot(Epc$timestamp, Epc$Sub_metering_1, type="l", xlab="", ylab="Energy sub metering") lines(Epc$timestamp, Epc$Sub_metering_2, col="red") lines(Epc$timestamp, Epc$Sub_metering_3, col="blue") legend("topright", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col=c("black", "red", "blue"), lwd=par("lwd"), bty="n") # Create the third Plot plot(Epc$timestamp, Epc$Voltage, type="l", xlab="datetime", ylab="Voltage") # Create the fourth plot plot(Epc$timestamp, Epc$Global_reactive_power, type="l", xlab="datetime", ylab="Global_reactive_power") dev.off()
#' @rdname dgmcm.loglik dgmm.loglik <- function (theta, z, marginal.loglik = FALSE) { if (!is.theta(theta)) stop("theta is not formatted correctly") if (!is.matrix(z)) stop("z is not a matrix") if (ncol(z) != theta$d) stop("Number of colums of z does not equal theta$d") dgmm_loglik(mus = theta$mu, sigmas = theta$sigma, pie = theta$pie, z = z, marginal_loglik = marginal.loglik) } # dgmm.loglik2 <- function (theta, z, marginal.loglik = FALSE) { # TempFuncJoint <- function (k) { # theta$pie[k]* # dmvnormal(z, mu = theta$mu[[k]], sigma = theta$sigma[[k]]) # } # loglik <- log(rowSums(rbind(sapply(1:theta$m, FUN = TempFuncJoint)))) # if (!marginal.loglik) # loglik <- sum(loglik) # return(loglik) # }
/fuzzedpackages/GMCM/R/dgmm.loglik.R
no_license
akhikolla/testpackages
R
false
false
791
r
#' @rdname dgmcm.loglik dgmm.loglik <- function (theta, z, marginal.loglik = FALSE) { if (!is.theta(theta)) stop("theta is not formatted correctly") if (!is.matrix(z)) stop("z is not a matrix") if (ncol(z) != theta$d) stop("Number of colums of z does not equal theta$d") dgmm_loglik(mus = theta$mu, sigmas = theta$sigma, pie = theta$pie, z = z, marginal_loglik = marginal.loglik) } # dgmm.loglik2 <- function (theta, z, marginal.loglik = FALSE) { # TempFuncJoint <- function (k) { # theta$pie[k]* # dmvnormal(z, mu = theta$mu[[k]], sigma = theta$sigma[[k]]) # } # loglik <- log(rowSums(rbind(sapply(1:theta$m, FUN = TempFuncJoint)))) # if (!marginal.loglik) # loglik <- sum(loglik) # return(loglik) # }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bin_helpers.R \name{extractLeadAuthor} \alias{extractLeadAuthor} \title{Title} \usage{ extractLeadAuthor(x) } \arguments{ \item{x}{} } \value{ } \description{ Title }
/man/extractLeadAuthor.Rd
permissive
benjamincrary/CrossRefEDNA
R
false
true
246
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bin_helpers.R \name{extractLeadAuthor} \alias{extractLeadAuthor} \title{Title} \usage{ extractLeadAuthor(x) } \arguments{ \item{x}{} } \value{ } \description{ Title }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/filechoose.R, R/dirchoose.R, R/filesave.R \name{shinyFiles-buttons} \alias{shinyFiles-buttons} \alias{shinyFilesButton} \alias{shinyFilesLink} \alias{shinyDirButton} \alias{shinyDirLink} \alias{shinySaveButton} \alias{shinySaveLink} \title{Create a button to summon a shinyFiles dialog} \usage{ shinyFilesButton( id, label, title, multiple, buttonType = "default", class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) shinyFilesLink( id, label, title, multiple, class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) shinyDirButton( id, label, title, buttonType = "default", class = NULL, icon = NULL, style = NULL, ... ) shinyDirLink(id, label, title, class = NULL, icon = NULL, style = NULL, ...) shinySaveButton( id, label, title, filename = "", filetype, buttonType = "default", class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) shinySaveLink( id, label, title, filename = "", filetype, class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) } \arguments{ \item{id}{The id matching the \code{\link[=shinyFileChoose]{shinyFileChoose()}}} \item{label}{The text that should appear on the button} \item{title}{The heading of the dialog box that appears when the button is pressed} \item{multiple}{A logical indicating whether or not it should be possible to select multiple files} \item{buttonType}{The Bootstrap button markup used to colour the button. Defaults to 'default' for a neutral appearance but can be changed for another look. The value will be pasted with 'btn-' and added as class.} \item{class}{Additional classes added to the button} \item{icon}{An optional \href{http://shiny.rstudio.com/reference/shiny/latest/icon.html}{icon} to appear on the button.} \item{style}{Additional styling added to the button (e.g., "margin-top: 25px;")} \item{viewtype}{View type to use in the file browser. One of "detail" (default), "list", or "icon"} \item{...}{Named attributes to be applied to the button or link (e.g., 'onclick')} \item{filename}{A predefined filename to be filed in. Can be modified by the user during saving.} \item{filetype}{A named list of file extensions. The name of each element gives the name of the filetype and the content of the element the possible extensions e.g. \code{list(picture=c('jpg', 'jpeg'))}. The first extension will be used as default if it is not supplied by the user.} } \value{ This function is called for its side effects } \description{ This function adds the required html markup for the client to access the file system. The end result will be the appearance of a button on the webpage that summons one of the shinyFiles dialog boxes. The last position in the file system is automatically remembered between instances, but not shared between several shinyFiles buttons. For a button to have any functionality it must have a matching observer on the server side. shinyFilesButton() is matched with shinyFileChoose() and shinyDirButton with shinyDirChoose(). The id argument of two matching calls must be the same. See \code{\link[=shinyFiles-observers]{shinyFiles-observers()}} on how to handle client input on the server side. } \details{ \strong{Selecting files} When a user selects one or several files the corresponding input variable is set to a list containing a character vector for each file. The character vectors gives the traversal route from the root to the selected file(s). The reason it does not give a path as a string is that the client has no knowledge of the file system on the server and can therefore not ensure proper formatting. The \code{\link[=parseFilePaths]{parseFilePaths()}} function can be used on the server to format the input variable into a format similar to that returned by \code{\link[shiny:fileInput]{shiny::fileInput()}}. \strong{Selecting folders} When a folder is selected it will also be available in its respective input variable as a list giving the traversal route to the selected folder. To properly format it, feed it into \code{\link[=parseDirPath]{parseDirPath()}} and a string with the full folder path will be returned. \strong{Creating files (saving)} When a new filename is created it will become available in the respective input variable and can be formatted with \code{\link[=parseSavePath]{parseSavePath()}} into a data.frame reminiscent that returned by fileInput. There is no size column and the type is only present if the filetype argument is used in \code{shinySaveButton}. In that case it will be the name of the chosen type (not the extension). \strong{Manual markup} For users wanting to design their html markup manually it is very easy to add a shinyFiles button. The only markup required is: \emph{shinyFilesButton} \verb{<button id="inputId" type="button" class="shinyFiles btn btn-default" data-title="title" data-selecttype="single"|"multiple">label</button>} \emph{shinyDirButton} \verb{<button id="inputId" type="button" class="shinyDirectories btn-default" data-title="title">label</button>} \emph{shinySaveButton} \code{<button id="inputId" type="button" class="shinySave btn-default" data-title="title" data-filetype="[{name: 'type1', ext: ['txt']}, {name: 'type2', ext: ['exe', 'bat']}]">label</button>} where the id tag matches the inputId parameter, the data-title tag matches the title parameter, the data-selecttype is either "single" or "multiple" (the non-logical form of the multiple parameter) and the internal textnode matches the label parameter. The data-filetype tag is a bit more involved as it is a json formatted array of objects with the properties 'name' and 'ext'. 'name' gives the name of the filetype as a string and 'ext' the allowed extensions as an array of strings. The non-exported \code{\link[=formatFiletype]{formatFiletype()}} function can help convert from a named R list into the string representation. In the example above "btn-default" is used as button styling, but this can be changed to any other Bootstrap style. Apart from this the html document should link to a script with the following path 'sF/shinyFiles.js' and a stylesheet with the following path 'sF/styles.css'. The markup is bootstrap compliant so if the bootstrap css is used in the page the look will fit right in. There is nothing that hinders the developer from ignoring bootstrap altogether and designing the visuals themselves. The only caveat being that the glyphs used in the menu buttons are bundled with bootstrap. Use the css ::after pseudoclasses to add alternative content to these buttons. Additional filetype specific icons can be added with css using the following style: \preformatted{ .sF-file .sF-file-icon .yourFileExtension{ content: url(path/to/16x16/pixel/png); } .sF-fileList.sF-icons .sF-file .sF-file-icon .yourFileExtension{ content: url(path/to/32x32/pixel/png); } } If no large version is specified the small version gets upscaled. \strong{Client side events} If the shiny app uses custom Javascript it is possible to react to selections directly from the javascript. Once a selection has been made, the button will fire of the event 'selection' and pass the selection data along with the event. To listen for this event you simple add: \preformatted{ $(button).on('selection', function(event, path) { // Do something with the paths here }) } in the same way a 'cancel' event is fired when a user dismisses a selection box. In that case, no path is passed on. Outside events the current selection is available as an object bound to the button and can be accessed at any time: \preformatted{ // For a shinyFilesButton $(button).data('files') // For a shinyDirButton $(button).data('directory') // For a shinySaveButton $(button).data('file') } } \references{ The file icons used in the file system navigator is taken from FatCows Farm-Fresh Web Icons (\url{http://www.fatcow.com/free-icons}) } \seealso{ Other shinyFiles: \code{\link{shinyFiles-observers}}, \code{\link{shinyFiles-parsers}}, \code{\link{shinyFilesExample}()} } \concept{shinyFiles}
/man/shinyFiles-buttons.Rd
no_license
kacoster/shinyfileslite
R
false
true
8,186
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/filechoose.R, R/dirchoose.R, R/filesave.R \name{shinyFiles-buttons} \alias{shinyFiles-buttons} \alias{shinyFilesButton} \alias{shinyFilesLink} \alias{shinyDirButton} \alias{shinyDirLink} \alias{shinySaveButton} \alias{shinySaveLink} \title{Create a button to summon a shinyFiles dialog} \usage{ shinyFilesButton( id, label, title, multiple, buttonType = "default", class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) shinyFilesLink( id, label, title, multiple, class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) shinyDirButton( id, label, title, buttonType = "default", class = NULL, icon = NULL, style = NULL, ... ) shinyDirLink(id, label, title, class = NULL, icon = NULL, style = NULL, ...) shinySaveButton( id, label, title, filename = "", filetype, buttonType = "default", class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) shinySaveLink( id, label, title, filename = "", filetype, class = NULL, icon = NULL, style = NULL, viewtype = "detail", ... ) } \arguments{ \item{id}{The id matching the \code{\link[=shinyFileChoose]{shinyFileChoose()}}} \item{label}{The text that should appear on the button} \item{title}{The heading of the dialog box that appears when the button is pressed} \item{multiple}{A logical indicating whether or not it should be possible to select multiple files} \item{buttonType}{The Bootstrap button markup used to colour the button. Defaults to 'default' for a neutral appearance but can be changed for another look. The value will be pasted with 'btn-' and added as class.} \item{class}{Additional classes added to the button} \item{icon}{An optional \href{http://shiny.rstudio.com/reference/shiny/latest/icon.html}{icon} to appear on the button.} \item{style}{Additional styling added to the button (e.g., "margin-top: 25px;")} \item{viewtype}{View type to use in the file browser. One of "detail" (default), "list", or "icon"} \item{...}{Named attributes to be applied to the button or link (e.g., 'onclick')} \item{filename}{A predefined filename to be filed in. Can be modified by the user during saving.} \item{filetype}{A named list of file extensions. The name of each element gives the name of the filetype and the content of the element the possible extensions e.g. \code{list(picture=c('jpg', 'jpeg'))}. The first extension will be used as default if it is not supplied by the user.} } \value{ This function is called for its side effects } \description{ This function adds the required html markup for the client to access the file system. The end result will be the appearance of a button on the webpage that summons one of the shinyFiles dialog boxes. The last position in the file system is automatically remembered between instances, but not shared between several shinyFiles buttons. For a button to have any functionality it must have a matching observer on the server side. shinyFilesButton() is matched with shinyFileChoose() and shinyDirButton with shinyDirChoose(). The id argument of two matching calls must be the same. See \code{\link[=shinyFiles-observers]{shinyFiles-observers()}} on how to handle client input on the server side. } \details{ \strong{Selecting files} When a user selects one or several files the corresponding input variable is set to a list containing a character vector for each file. The character vectors gives the traversal route from the root to the selected file(s). The reason it does not give a path as a string is that the client has no knowledge of the file system on the server and can therefore not ensure proper formatting. The \code{\link[=parseFilePaths]{parseFilePaths()}} function can be used on the server to format the input variable into a format similar to that returned by \code{\link[shiny:fileInput]{shiny::fileInput()}}. \strong{Selecting folders} When a folder is selected it will also be available in its respective input variable as a list giving the traversal route to the selected folder. To properly format it, feed it into \code{\link[=parseDirPath]{parseDirPath()}} and a string with the full folder path will be returned. \strong{Creating files (saving)} When a new filename is created it will become available in the respective input variable and can be formatted with \code{\link[=parseSavePath]{parseSavePath()}} into a data.frame reminiscent that returned by fileInput. There is no size column and the type is only present if the filetype argument is used in \code{shinySaveButton}. In that case it will be the name of the chosen type (not the extension). \strong{Manual markup} For users wanting to design their html markup manually it is very easy to add a shinyFiles button. The only markup required is: \emph{shinyFilesButton} \verb{<button id="inputId" type="button" class="shinyFiles btn btn-default" data-title="title" data-selecttype="single"|"multiple">label</button>} \emph{shinyDirButton} \verb{<button id="inputId" type="button" class="shinyDirectories btn-default" data-title="title">label</button>} \emph{shinySaveButton} \code{<button id="inputId" type="button" class="shinySave btn-default" data-title="title" data-filetype="[{name: 'type1', ext: ['txt']}, {name: 'type2', ext: ['exe', 'bat']}]">label</button>} where the id tag matches the inputId parameter, the data-title tag matches the title parameter, the data-selecttype is either "single" or "multiple" (the non-logical form of the multiple parameter) and the internal textnode matches the label parameter. The data-filetype tag is a bit more involved as it is a json formatted array of objects with the properties 'name' and 'ext'. 'name' gives the name of the filetype as a string and 'ext' the allowed extensions as an array of strings. The non-exported \code{\link[=formatFiletype]{formatFiletype()}} function can help convert from a named R list into the string representation. In the example above "btn-default" is used as button styling, but this can be changed to any other Bootstrap style. Apart from this the html document should link to a script with the following path 'sF/shinyFiles.js' and a stylesheet with the following path 'sF/styles.css'. The markup is bootstrap compliant so if the bootstrap css is used in the page the look will fit right in. There is nothing that hinders the developer from ignoring bootstrap altogether and designing the visuals themselves. The only caveat being that the glyphs used in the menu buttons are bundled with bootstrap. Use the css ::after pseudoclasses to add alternative content to these buttons. Additional filetype specific icons can be added with css using the following style: \preformatted{ .sF-file .sF-file-icon .yourFileExtension{ content: url(path/to/16x16/pixel/png); } .sF-fileList.sF-icons .sF-file .sF-file-icon .yourFileExtension{ content: url(path/to/32x32/pixel/png); } } If no large version is specified the small version gets upscaled. \strong{Client side events} If the shiny app uses custom Javascript it is possible to react to selections directly from the javascript. Once a selection has been made, the button will fire of the event 'selection' and pass the selection data along with the event. To listen for this event you simple add: \preformatted{ $(button).on('selection', function(event, path) { // Do something with the paths here }) } in the same way a 'cancel' event is fired when a user dismisses a selection box. In that case, no path is passed on. Outside events the current selection is available as an object bound to the button and can be accessed at any time: \preformatted{ // For a shinyFilesButton $(button).data('files') // For a shinyDirButton $(button).data('directory') // For a shinySaveButton $(button).data('file') } } \references{ The file icons used in the file system navigator is taken from FatCows Farm-Fresh Web Icons (\url{http://www.fatcow.com/free-icons}) } \seealso{ Other shinyFiles: \code{\link{shinyFiles-observers}}, \code{\link{shinyFiles-parsers}}, \code{\link{shinyFilesExample}()} } \concept{shinyFiles}
#load libraries library(dplyr) library(haven) library(patchwork) library(caTools) options(scipen = 999) " Data Download Link: https://hrsdata.isr.umich.edu/data-products/2018-rand-hrs-fat-file Data Codebook: https://hrs.isr.umich.edu/sites/default/files/meta/2018/core/codebook/h18_00.html The raw SAS file was read into R and saved as an RDS file. Read in the file below " dat <- readRDS(file="../h18e1a_SAS/h18e1a.rds") #Data processing mydat <- dat %>% select(QX060_R, QX065_R, QA019, QA099, QA100, QA101, QA113, QB063, QB000,QC001,QC005,QC010, QC018, QC257, QC053, QC271,QC272, QC080,QC117,QC129, QC229, QC150, QD101,QD114,QD115, QJ005M1, QJ612, QJK014, QJ067,QJ547, QJ549, QG059, QH004, QJ179, QJ3568, QJ3570, QJ3478, QN001,QP097,QT011, QT012, QJ3578, QQ317, QQ331,QQ345, QQ357, QQ371,QQ376, QJ2W009_1, QJ2W009_2, QJ2W009_3, QJ2W009_4,QJ2W009_5, QJ2W009_6,QJ2W009_7,QJ2W009_8, QJ2W009_9,QJ2W009_10, #friends QG198, QG097, #housing - mortage QH020,QH016,QH166, QH032, #debts QQ478, QQ519)%>% filter(QJ3578 %in% c(1,3,5)) %>% mutate(retirement = ifelse(QJ3578 %in% c(1,3), "Retired", "Not Retired"), sex = ifelse(QX060_R ==1, "Male","Female"), partner_status = ifelse(QX065_R ==1, "Married", ifelse(QX065_R ==3, "Partnered", ifelse(QX065_R ==6, "Other",NA))), age = QA019, resident_children = QA099, nonresident_children = QA100, children_nonspouse = QA101, children = resident_children + nonresident_children + children_nonspouse, #grandchildren = QA113, #don't think we need this - "COUNT OF CHILD CHILDLAW AND GRANDCHILD" marital_status =ifelse(QB063 ==1, "Married", ifelse(QB063 ==3, "Separated", ifelse(QB063 ==4, "Divorced", ifelse(QB063 ==5, "Widowed", ifelse(QB063 ==6, "Never Married", ifelse(QB063 %in% c(2, 7, 8, 9), "Other",NA)))))), life_satisfaction = ifelse(QB000 ==1, "Completely Satisfied", ifelse(QB000 ==2, "Very Satisfied", ifelse(QB000 ==3, "Somewhat Satisfied", ifelse(QB000 ==4, "Not Very Satisfied", ifelse(QB000 ==5, "Not At All Satisfied", ifelse(QB000 == 8 | QB000 == 9, NA,QB000)))))), health_rate = ifelse(QC001 ==1, "Excellent", ifelse(QC001 ==2, "Very Good", ifelse(QC001 ==3, "Good", ifelse(QC001 ==4, "Fair", ifelse(QC001 ==5, "Poor", ifelse(QC001 == 8 | QC001 == 9, NA,QC001)))))), high_BP = ifelse(QC005 ==1, "Yes", ifelse(QC005 == 4, "No", ifelse(QC005 == 5, "No", ifelse(QC005 == 6, "No", ifelse(QC005 == 8 | QC001 == 9, NA,QC005))))), diabetes = ifelse(QC010 ==1, "Yes", ifelse(QC010 ==4, "No", ifelse(QC010 ==5, "No", ifelse(QC010 ==6, "No", ifelse(QC010 == 8 | QC010 == 9, NA,QC010))))), cancer = ifelse(QC018 == 1, "Yes", ifelse(QC018 ==4, "No", ifelse(QC018 ==5, "No", ifelse(QC018 == 8 | QC018 == 9, NA, QC018)))), heart_attack = ifelse(QC257 == 1, "Yes", ifelse(QC257 ==4, "No", ifelse(QC257 ==5, "No", ifelse(QC257 == 8 | QC257 == 9, NA, QC257)))), depression = ifelse(QC271 == 1, "Yes", ifelse(QC271 ==6, "No", ifelse(QC271 ==4, "No", ifelse(QC271 ==5, "No", ifelse(QC271 == 8 | QC271 == 9, NA, QC271))))), times_fallen = ifelse(QC080 == 99 | QC080 ==98, NA, QC080), alc_days = ifelse(QC129 == 9 | QC129 ==8, NA, QC129), days_in_bed = ifelse(QC229 == 98 | QC229 ==99, NA, QC229), memory = ifelse(QD101 ==1, "Excellent", ifelse(QD101 ==2, "Very Good", ifelse(QD101 ==3, "Good", ifelse(QD101 ==4, "Fair", ifelse(QD101 ==5, "Poor", ifelse(QD101 == 8 | QD101 == 9, NA,QD101)))))), lonely_pw = ifelse(QD114 == 1, "Yes", ifelse(QD114 == 5, "No", ifelse(QD114 == 8 | QD114 == 9, NA, QD114))), enjoy_life_pw = ifelse(QD115 == 1, "Yes", ifelse(QD115 == 5, "No", ifelse(QD115 == 8 | QD115 == 9, NA, QD115))), help_friends_py = ifelse(QG198 == 1, "Yes", ifelse(QG198 ==5, "No", ifelse(QG198 == 8 | QG198 == 9, NA, QG198))), have_friends = ifelse(QG097 == 1, "Yes", ifelse(QG097 ==5, "No", ifelse(QG097 == 8 | QG097 == 9, NA, QG097))), job_status =ifelse(QJ005M1 ==1, "Working Now", ifelse(QJ005M1 ==2, "Unemployed", ifelse(QJ005M1 ==3, "Laid Off", ifelse(QJ005M1 ==4, "Disabled", ifelse(QJ005M1 ==5, "Retired", ifelse(QJ005M1 ==6, "Homemaker", ifelse(QJ005M1 ==7, "Other", ifelse(QJ005M1 == 8,"On Leave", ifelse(QJ005M1 == 98 | QJ005M1 == 99, NA, NA))))))))), weeks_worked_py = ifelse(QJ612 == 98 | QJ612 ==99, NA, QJ612), amount_earn_when_left = ifelse(QJ067 == 9999998 | QJ067 == 9999999, NA, QJ067), difficulty_managing_mny = ifelse(QG059 ==1, "Yes", ifelse(QG059 == 5, "No", ifelse(QG059 == 8 | QG059 == 9 | QG059 == 6 | QG059 == 7, NA,QG059))), own_rent_home = ifelse(QH004 ==1, "Own", ifelse(QH004 ==2, "Rent", ifelse(QH004 ==3, "Lives Rent Free", ifelse(QH004 ==7, "Other", ifelse(QH004 == 8 | QH004 == 9, NA,QH004))))), age_plan_stop_wrk = ifelse(QJ3568 == 96, NA, ifelse(QJ3568 == 98 |QJ3568 == 99, NA,QJ3568)), #age to plan to stop working: if never (95), then we will go to the maximum (95) social_security = ifelse(QJ3478 == 1, "Yes", ifelse(QJ3478 == 5, "No", ifelse(QJ3478 == 8 | QJ3478 == 9, NA, QJ3478))), medicare = ifelse(QN001 == 1, "Yes", ifelse(QN001 == 5, "No", ifelse(QN001 == 8 | QN001 == 9, NA, QN001))), follow_stockmarket = ifelse(QP097 == 1, "Very Closely", ifelse(QP097 == 2, "Somewhat Closely", ifelse(QP097 == 3, "Not At All", ifelse(QP097 == 8 | QP097 == 9, NA, QP097)))), life_insurance = ifelse(QT011 == 1, "Yes", ifelse(QT011 == 5, "No", ifelse(QT011 == 8 | QT011 == 9, NA, QT011))), num_lifeinsur_policies = ifelse(QT012 ==1, "1", ifelse(QT012 ==2, "2", ifelse(QT012 ==3, "3", ifelse(QT012 ==4, "4", ifelse(QT012 ==5, "5 or more", ifelse(QT012 == 8 | QT012 == 9, NA,QT012)))))), stocks_mf = ifelse(QQ317 == 9999998 | QQ317 == 9999999, NA, QQ317), bonds = ifelse(QQ331 == 99999998 | QQ331 == 99999999, NA, QQ331), savings = ifelse(QQ345 == 99999998 | QQ345 == 99999999, NA, QQ345), cds = ifelse(QQ357 == 99999998 | QQ357 == 99999999, NA, QQ357), vehicles = ifelse(QQ371 == 99999998 | QQ371 == 99999999, NA, QQ371), other_savings = ifelse(QQ376 == 99999998 | QQ376 == 99999999, NA, QQ376), pension_1= ifelse(QJ2W009_1 == 99999998 | QJ2W009_1 == 99999999, NA, QJ2W009_1), pension_2= ifelse(QJ2W009_2 == 99999998 | QJ2W009_2 == 99999999, NA, QJ2W009_2), pension_3= ifelse(QJ2W009_3 == 99999998 | QJ2W009_3 == 99999999, NA, QJ2W009_3), pension_4= ifelse(QJ2W009_4 == 99999998 | QJ2W009_4 == 99999999, NA, QJ2W009_4), pension_5= ifelse(QJ2W009_5 == 99999998 | QJ2W009_5 == 99999999, NA, QJ2W009_5), pension_6= ifelse(QJ2W009_6 == 99999998 | QJ2W009_6 == 99999999, NA, QJ2W009_6), pension_7= ifelse(QJ2W009_7 == 99999998 | QJ2W009_7 == 99999999, NA, QJ2W009_7), pension_8= ifelse(QJ2W009_8 == 99999998 | QJ2W009_8 == 99999999, NA, QJ2W009_8), pension_9= ifelse(QJ2W009_9 == 99999998 | QJ2W009_9 == 99999999, NA, QJ2W009_9), pension_10= ifelse(QJ2W009_10 == 99999998 | QJ2W009_10 == 99999999, NA, QJ2W009_10), home_value = ifelse(QH020 == 9999999998 | QH020 == 9999999999, NA, QH020), mobile_home_value = ifelse(QH016 == 99999998 | QH016 == 99999999, NA, QH016), second_home_value = ifelse(QH166 == 9999999998 | QH166 == 9999999999, NA, QH166), mortgage = ifelse(QH032 == 99999998 | QH032 == 99999999, NA, QH032), debts = ifelse(QQ478 == 9999998 | QQ478 == 9999999, NA, QQ478), credit_card_debt = ifelse(QQ519 == 9999998 | QQ519 == 9999999, NA, QQ519)) %>% select(retirement, sex, age, children, marital_status, life_satisfaction, health_rate, high_BP, diabetes, cancer, heart_attack, depression, times_fallen, alc_days, days_in_bed, memory, lonely_pw, enjoy_life_pw, job_status, weeks_worked_py, help_friends_py,have_friends, amount_earn_when_left, difficulty_managing_mny, own_rent_home, age_plan_stop_wrk, social_security, medicare, follow_stockmarket, life_insurance, num_lifeinsur_policies, stocks_mf, bonds, savings, cds, vehicles, other_savings, home_value, mobile_home_value, second_home_value, mortgage, debts, credit_card_debt, pension_1, pension_2,pension_3,pension_4,pension_5, pension_6,pension_7,pension_8,pension_9,pension_10) %>% rowwise() %>% mutate( pension = sum(pension_1, pension_2,pension_3,pension_4,pension_5, pension_6,pension_7,pension_8,pension_9,pension_10, na.rm = TRUE), assets = sum(stocks_mf, bonds, savings, cds, vehicles, other_savings, pension, na.rm = TRUE), housing_assets = sum(home_value, second_home_value,mobile_home_value, -mortgage, na.rm = TRUE), net_assets = assets + housing_assets + pension) %>% ungroup() %>% #we now remove the values that have lots of missingness and are shown to be seen in other variables select(-heart_attack, -amount_earn_when_left, -age_plan_stop_wrk, -times_fallen, -weeks_worked_py, -num_lifeinsur_policies, -alc_days, -job_status) %>% #remove variables that are used to compute the outcome variable select(-c(stocks_mf, bonds, savings, cds, vehicles, other_savings, pension,home_value, second_home_value,mobile_home_value, mortgage, assets, housing_assets,debts, credit_card_debt, pension_1, pension_2,pension_3,pension_4,pension_5, pension_6,pension_7,pension_8,pension_9,pension_10)) %>% data.frame() %>% mutate(net_assets = ifelse(net_assets <0, 0, net_assets)) %>% data.frame() #attribute removal: mydat[] <- lapply(mydat, function(x) { attributes(x) <- NULL; x }) #turn all character variables into factors: mydat[sapply(mydat, is.character)] <- lapply(mydat[sapply(mydat, is.character)], as.factor) ############## Training & Test Split ############## #Note that the data has 16,309 rows #Create a test data set with 20% of these rows (3262 rows) #The test data set must include complete cases. #The remaining data will be imputed set.seed(11+05+21) all_rownum <- nrow(mydat) test_rownums <- ceiling(all_rownum*0.2) #data with complete cases: data_complete <- mydat[complete.cases(mydat), ] #calculate ratio percentage with new rows #math to solve percentage new_p <- 1 - (test_rownums / nrow(data_complete)) new_p <- round(new_p, 1) #find test set sample <- sample.split(data_complete$net_assets, SplitRatio = new_p) #define test data test <- subset(data_complete, sample == FALSE) #define training data by #rbind'ing the rest of the complete cases with "sample == TRUE" pre_train <- rbind(mydat[!complete.cases(mydat), ], subset(data_complete, sample == TRUE))
/scripts/R/processing/proposal_preprocessing.R
no_license
delashu/health_retirement
R
false
false
14,647
r
#load libraries library(dplyr) library(haven) library(patchwork) library(caTools) options(scipen = 999) " Data Download Link: https://hrsdata.isr.umich.edu/data-products/2018-rand-hrs-fat-file Data Codebook: https://hrs.isr.umich.edu/sites/default/files/meta/2018/core/codebook/h18_00.html The raw SAS file was read into R and saved as an RDS file. Read in the file below " dat <- readRDS(file="../h18e1a_SAS/h18e1a.rds") #Data processing mydat <- dat %>% select(QX060_R, QX065_R, QA019, QA099, QA100, QA101, QA113, QB063, QB000,QC001,QC005,QC010, QC018, QC257, QC053, QC271,QC272, QC080,QC117,QC129, QC229, QC150, QD101,QD114,QD115, QJ005M1, QJ612, QJK014, QJ067,QJ547, QJ549, QG059, QH004, QJ179, QJ3568, QJ3570, QJ3478, QN001,QP097,QT011, QT012, QJ3578, QQ317, QQ331,QQ345, QQ357, QQ371,QQ376, QJ2W009_1, QJ2W009_2, QJ2W009_3, QJ2W009_4,QJ2W009_5, QJ2W009_6,QJ2W009_7,QJ2W009_8, QJ2W009_9,QJ2W009_10, #friends QG198, QG097, #housing - mortage QH020,QH016,QH166, QH032, #debts QQ478, QQ519)%>% filter(QJ3578 %in% c(1,3,5)) %>% mutate(retirement = ifelse(QJ3578 %in% c(1,3), "Retired", "Not Retired"), sex = ifelse(QX060_R ==1, "Male","Female"), partner_status = ifelse(QX065_R ==1, "Married", ifelse(QX065_R ==3, "Partnered", ifelse(QX065_R ==6, "Other",NA))), age = QA019, resident_children = QA099, nonresident_children = QA100, children_nonspouse = QA101, children = resident_children + nonresident_children + children_nonspouse, #grandchildren = QA113, #don't think we need this - "COUNT OF CHILD CHILDLAW AND GRANDCHILD" marital_status =ifelse(QB063 ==1, "Married", ifelse(QB063 ==3, "Separated", ifelse(QB063 ==4, "Divorced", ifelse(QB063 ==5, "Widowed", ifelse(QB063 ==6, "Never Married", ifelse(QB063 %in% c(2, 7, 8, 9), "Other",NA)))))), life_satisfaction = ifelse(QB000 ==1, "Completely Satisfied", ifelse(QB000 ==2, "Very Satisfied", ifelse(QB000 ==3, "Somewhat Satisfied", ifelse(QB000 ==4, "Not Very Satisfied", ifelse(QB000 ==5, "Not At All Satisfied", ifelse(QB000 == 8 | QB000 == 9, NA,QB000)))))), health_rate = ifelse(QC001 ==1, "Excellent", ifelse(QC001 ==2, "Very Good", ifelse(QC001 ==3, "Good", ifelse(QC001 ==4, "Fair", ifelse(QC001 ==5, "Poor", ifelse(QC001 == 8 | QC001 == 9, NA,QC001)))))), high_BP = ifelse(QC005 ==1, "Yes", ifelse(QC005 == 4, "No", ifelse(QC005 == 5, "No", ifelse(QC005 == 6, "No", ifelse(QC005 == 8 | QC001 == 9, NA,QC005))))), diabetes = ifelse(QC010 ==1, "Yes", ifelse(QC010 ==4, "No", ifelse(QC010 ==5, "No", ifelse(QC010 ==6, "No", ifelse(QC010 == 8 | QC010 == 9, NA,QC010))))), cancer = ifelse(QC018 == 1, "Yes", ifelse(QC018 ==4, "No", ifelse(QC018 ==5, "No", ifelse(QC018 == 8 | QC018 == 9, NA, QC018)))), heart_attack = ifelse(QC257 == 1, "Yes", ifelse(QC257 ==4, "No", ifelse(QC257 ==5, "No", ifelse(QC257 == 8 | QC257 == 9, NA, QC257)))), depression = ifelse(QC271 == 1, "Yes", ifelse(QC271 ==6, "No", ifelse(QC271 ==4, "No", ifelse(QC271 ==5, "No", ifelse(QC271 == 8 | QC271 == 9, NA, QC271))))), times_fallen = ifelse(QC080 == 99 | QC080 ==98, NA, QC080), alc_days = ifelse(QC129 == 9 | QC129 ==8, NA, QC129), days_in_bed = ifelse(QC229 == 98 | QC229 ==99, NA, QC229), memory = ifelse(QD101 ==1, "Excellent", ifelse(QD101 ==2, "Very Good", ifelse(QD101 ==3, "Good", ifelse(QD101 ==4, "Fair", ifelse(QD101 ==5, "Poor", ifelse(QD101 == 8 | QD101 == 9, NA,QD101)))))), lonely_pw = ifelse(QD114 == 1, "Yes", ifelse(QD114 == 5, "No", ifelse(QD114 == 8 | QD114 == 9, NA, QD114))), enjoy_life_pw = ifelse(QD115 == 1, "Yes", ifelse(QD115 == 5, "No", ifelse(QD115 == 8 | QD115 == 9, NA, QD115))), help_friends_py = ifelse(QG198 == 1, "Yes", ifelse(QG198 ==5, "No", ifelse(QG198 == 8 | QG198 == 9, NA, QG198))), have_friends = ifelse(QG097 == 1, "Yes", ifelse(QG097 ==5, "No", ifelse(QG097 == 8 | QG097 == 9, NA, QG097))), job_status =ifelse(QJ005M1 ==1, "Working Now", ifelse(QJ005M1 ==2, "Unemployed", ifelse(QJ005M1 ==3, "Laid Off", ifelse(QJ005M1 ==4, "Disabled", ifelse(QJ005M1 ==5, "Retired", ifelse(QJ005M1 ==6, "Homemaker", ifelse(QJ005M1 ==7, "Other", ifelse(QJ005M1 == 8,"On Leave", ifelse(QJ005M1 == 98 | QJ005M1 == 99, NA, NA))))))))), weeks_worked_py = ifelse(QJ612 == 98 | QJ612 ==99, NA, QJ612), amount_earn_when_left = ifelse(QJ067 == 9999998 | QJ067 == 9999999, NA, QJ067), difficulty_managing_mny = ifelse(QG059 ==1, "Yes", ifelse(QG059 == 5, "No", ifelse(QG059 == 8 | QG059 == 9 | QG059 == 6 | QG059 == 7, NA,QG059))), own_rent_home = ifelse(QH004 ==1, "Own", ifelse(QH004 ==2, "Rent", ifelse(QH004 ==3, "Lives Rent Free", ifelse(QH004 ==7, "Other", ifelse(QH004 == 8 | QH004 == 9, NA,QH004))))), age_plan_stop_wrk = ifelse(QJ3568 == 96, NA, ifelse(QJ3568 == 98 |QJ3568 == 99, NA,QJ3568)), #age to plan to stop working: if never (95), then we will go to the maximum (95) social_security = ifelse(QJ3478 == 1, "Yes", ifelse(QJ3478 == 5, "No", ifelse(QJ3478 == 8 | QJ3478 == 9, NA, QJ3478))), medicare = ifelse(QN001 == 1, "Yes", ifelse(QN001 == 5, "No", ifelse(QN001 == 8 | QN001 == 9, NA, QN001))), follow_stockmarket = ifelse(QP097 == 1, "Very Closely", ifelse(QP097 == 2, "Somewhat Closely", ifelse(QP097 == 3, "Not At All", ifelse(QP097 == 8 | QP097 == 9, NA, QP097)))), life_insurance = ifelse(QT011 == 1, "Yes", ifelse(QT011 == 5, "No", ifelse(QT011 == 8 | QT011 == 9, NA, QT011))), num_lifeinsur_policies = ifelse(QT012 ==1, "1", ifelse(QT012 ==2, "2", ifelse(QT012 ==3, "3", ifelse(QT012 ==4, "4", ifelse(QT012 ==5, "5 or more", ifelse(QT012 == 8 | QT012 == 9, NA,QT012)))))), stocks_mf = ifelse(QQ317 == 9999998 | QQ317 == 9999999, NA, QQ317), bonds = ifelse(QQ331 == 99999998 | QQ331 == 99999999, NA, QQ331), savings = ifelse(QQ345 == 99999998 | QQ345 == 99999999, NA, QQ345), cds = ifelse(QQ357 == 99999998 | QQ357 == 99999999, NA, QQ357), vehicles = ifelse(QQ371 == 99999998 | QQ371 == 99999999, NA, QQ371), other_savings = ifelse(QQ376 == 99999998 | QQ376 == 99999999, NA, QQ376), pension_1= ifelse(QJ2W009_1 == 99999998 | QJ2W009_1 == 99999999, NA, QJ2W009_1), pension_2= ifelse(QJ2W009_2 == 99999998 | QJ2W009_2 == 99999999, NA, QJ2W009_2), pension_3= ifelse(QJ2W009_3 == 99999998 | QJ2W009_3 == 99999999, NA, QJ2W009_3), pension_4= ifelse(QJ2W009_4 == 99999998 | QJ2W009_4 == 99999999, NA, QJ2W009_4), pension_5= ifelse(QJ2W009_5 == 99999998 | QJ2W009_5 == 99999999, NA, QJ2W009_5), pension_6= ifelse(QJ2W009_6 == 99999998 | QJ2W009_6 == 99999999, NA, QJ2W009_6), pension_7= ifelse(QJ2W009_7 == 99999998 | QJ2W009_7 == 99999999, NA, QJ2W009_7), pension_8= ifelse(QJ2W009_8 == 99999998 | QJ2W009_8 == 99999999, NA, QJ2W009_8), pension_9= ifelse(QJ2W009_9 == 99999998 | QJ2W009_9 == 99999999, NA, QJ2W009_9), pension_10= ifelse(QJ2W009_10 == 99999998 | QJ2W009_10 == 99999999, NA, QJ2W009_10), home_value = ifelse(QH020 == 9999999998 | QH020 == 9999999999, NA, QH020), mobile_home_value = ifelse(QH016 == 99999998 | QH016 == 99999999, NA, QH016), second_home_value = ifelse(QH166 == 9999999998 | QH166 == 9999999999, NA, QH166), mortgage = ifelse(QH032 == 99999998 | QH032 == 99999999, NA, QH032), debts = ifelse(QQ478 == 9999998 | QQ478 == 9999999, NA, QQ478), credit_card_debt = ifelse(QQ519 == 9999998 | QQ519 == 9999999, NA, QQ519)) %>% select(retirement, sex, age, children, marital_status, life_satisfaction, health_rate, high_BP, diabetes, cancer, heart_attack, depression, times_fallen, alc_days, days_in_bed, memory, lonely_pw, enjoy_life_pw, job_status, weeks_worked_py, help_friends_py,have_friends, amount_earn_when_left, difficulty_managing_mny, own_rent_home, age_plan_stop_wrk, social_security, medicare, follow_stockmarket, life_insurance, num_lifeinsur_policies, stocks_mf, bonds, savings, cds, vehicles, other_savings, home_value, mobile_home_value, second_home_value, mortgage, debts, credit_card_debt, pension_1, pension_2,pension_3,pension_4,pension_5, pension_6,pension_7,pension_8,pension_9,pension_10) %>% rowwise() %>% mutate( pension = sum(pension_1, pension_2,pension_3,pension_4,pension_5, pension_6,pension_7,pension_8,pension_9,pension_10, na.rm = TRUE), assets = sum(stocks_mf, bonds, savings, cds, vehicles, other_savings, pension, na.rm = TRUE), housing_assets = sum(home_value, second_home_value,mobile_home_value, -mortgage, na.rm = TRUE), net_assets = assets + housing_assets + pension) %>% ungroup() %>% #we now remove the values that have lots of missingness and are shown to be seen in other variables select(-heart_attack, -amount_earn_when_left, -age_plan_stop_wrk, -times_fallen, -weeks_worked_py, -num_lifeinsur_policies, -alc_days, -job_status) %>% #remove variables that are used to compute the outcome variable select(-c(stocks_mf, bonds, savings, cds, vehicles, other_savings, pension,home_value, second_home_value,mobile_home_value, mortgage, assets, housing_assets,debts, credit_card_debt, pension_1, pension_2,pension_3,pension_4,pension_5, pension_6,pension_7,pension_8,pension_9,pension_10)) %>% data.frame() %>% mutate(net_assets = ifelse(net_assets <0, 0, net_assets)) %>% data.frame() #attribute removal: mydat[] <- lapply(mydat, function(x) { attributes(x) <- NULL; x }) #turn all character variables into factors: mydat[sapply(mydat, is.character)] <- lapply(mydat[sapply(mydat, is.character)], as.factor) ############## Training & Test Split ############## #Note that the data has 16,309 rows #Create a test data set with 20% of these rows (3262 rows) #The test data set must include complete cases. #The remaining data will be imputed set.seed(11+05+21) all_rownum <- nrow(mydat) test_rownums <- ceiling(all_rownum*0.2) #data with complete cases: data_complete <- mydat[complete.cases(mydat), ] #calculate ratio percentage with new rows #math to solve percentage new_p <- 1 - (test_rownums / nrow(data_complete)) new_p <- round(new_p, 1) #find test set sample <- sample.split(data_complete$net_assets, SplitRatio = new_p) #define test data test <- subset(data_complete, sample == FALSE) #define training data by #rbind'ing the rest of the complete cases with "sample == TRUE" pre_train <- rbind(mydat[!complete.cases(mydat), ], subset(data_complete, sample == TRUE))
/SCRIPT_S3R/GUI_tab2.r
no_license
palou26/testgit
R
false
false
5,646
r
#preprocessing data library(lubridate) library(dplyr) d <- read.table("household_power_consumption.txt",header=TRUE,sep=";") cDate <- as.character(d$Date) dDate <- dmy(cDate) d <- d %>% mutate(Date=dDate) ad <- d %>% filter(Date == "2007-02-01" | Date == "2007-02-02") #plot 2 Date <- ad$Date Time <- ad$Time NewTime <- paste(Date,Time) NewTime <- ymd_hms(NewTime) GAP <- as.numeric(ad$Global_active_power) plot(NewTime,GAP,type="l",xlab = "",ylab = "Global Active Power (kilowatts)",yaxt="n") axis(2,at = c(0,1000,2000,3000),labels = c(0,2,4,6)) dev.copy(png,"plot2.png") dev.off()
/plot2.R
no_license
MGitting/plotting-homework
R
false
false
603
r
#preprocessing data library(lubridate) library(dplyr) d <- read.table("household_power_consumption.txt",header=TRUE,sep=";") cDate <- as.character(d$Date) dDate <- dmy(cDate) d <- d %>% mutate(Date=dDate) ad <- d %>% filter(Date == "2007-02-01" | Date == "2007-02-02") #plot 2 Date <- ad$Date Time <- ad$Time NewTime <- paste(Date,Time) NewTime <- ymd_hms(NewTime) GAP <- as.numeric(ad$Global_active_power) plot(NewTime,GAP,type="l",xlab = "",ylab = "Global Active Power (kilowatts)",yaxt="n") axis(2,at = c(0,1000,2000,3000),labels = c(0,2,4,6)) dev.copy(png,"plot2.png") dev.off()
bb_individuals<-function(bb_probabilitydensity=bb, #Output from IndividualBB tracksums=tracksums.out, cellsize=3000){ ## NOTE: ud estimates have been scaled by multiplying each value by cellsize^2 to make prob vol that sums to 1.00 accross pixel space #individuals also may be split across groups (year, season) if the tracks were segmented useing these require(adehabitatHR) require(SDMTools) #grp.meta<-data.matrix(meta[grping.var]) bb<-bb_probabilitydensity burst<-names(bb) tracksums$bbref<-1:nrow(tracksums) # get unique groups (use tracksums b/c these points are contained in polygon - not a tracks will necessarily be represented in a given polygon) (grp.ids<-unique(tracksums$timegrp)) #### initialize lists to house data by desired grouping variable (group.uniq) # list to house uds normalized by track duration bbindis <- vector ("list", length(grp.ids)) #### loop through groups for (h in 1:length(grp.ids)) { grp.id<-grp.ids[h] #tracksums.want<-tracksums[which(tracksums$grp==grp.ids[k]),] tracksums.want<-tracksums%>%dplyr::filter(timegrp==grp.id) # create summary table of # of segments from each track (track.freq<-tracksums.want%>%group_by(uniID)%>% dplyr::summarize(n=n_distinct(seg_id),minbb=min(bbref),maxbb=max(bbref))) # initialize lists to house data for segment based on deploy_id ud.track <- vector("list", nrow(track.freq)) track.days <- vector ("list", nrow(track.freq)) # sum up segments for each track # run through track.freq table summing segments >1 for (j in 1:nrow(track.freq)) { if (track.freq$n[j]==1) { # operation for only one segment in polygon bbIndx<-track.freq$minbb[j] ud.seg<-bb[[bbIndx]] a<- slot(ud.seg,"data") slot(ud.seg,"data")<-a*(cellsize^2) ud.track[[j]]<-ud.seg # get number of track days (in decimal days) track.days[[j]]<-tracksums.want$days[tracksums.want$uniID==track.freq$uniID[j]] #paste(paste("bird:",track.freq$uniID[j], # "segnum:",track.freq$n[j], # "area:",sum(slot(ud.track[[j]],"data")[,1]))) } else { # get multiple segments days.segs<-tracksums.want$days[tracksums.want$uniID==track.freq$uniID[j]] bbIndx.segs<-seq(from=track.freq$minbb[track.freq$uniID==track.freq$uniID[j]], to=track.freq$maxbb[track.freq$uniID==track.freq$uniID[j]]) # list to house each segment ud.segs.new <- vector ("list", length(bbIndx.segs)) for (k in 1:length(bbIndx.segs)) { bbIndx<-bbIndx.segs[k] ud.seg <- bb[[bbIndx]] # weigh each segment it's proportion of total hours tracked within the clipperName (Freiberg 20XX paper) a<- slot(ud.seg,"data")*(days.segs[k]/sum(days.segs)) #slot(ud.seg,"data")<-a ud.segs.new[[k]] <- a } # adds the segments from one bird together into one UD spdf<-Reduce("+",ud.segs.new)*(cellsize^2) sum(spdf) estUDsum<-ud.seg#steal UD formatting from slot(estUDsum,"data")<-spdf ud.track[[j]]<-estUDsum # get number of track days track.days[[j]]<-sum(days.segs)} #print(paste(j,k,sum(slot(ud.track[[j]],"data")))) } names(ud.track)<-track.freq$uniID class(ud.track) <- "estUDm" bbindis[[h]]<-ud.track } names(bbindis)<-grp.ids #class(bbindis)<-"estUD" return(bbindis) }
/R/bb_individuals.R
no_license
raorben/seabird_tracking_atlas
R
false
false
3,615
r
bb_individuals<-function(bb_probabilitydensity=bb, #Output from IndividualBB tracksums=tracksums.out, cellsize=3000){ ## NOTE: ud estimates have been scaled by multiplying each value by cellsize^2 to make prob vol that sums to 1.00 accross pixel space #individuals also may be split across groups (year, season) if the tracks were segmented useing these require(adehabitatHR) require(SDMTools) #grp.meta<-data.matrix(meta[grping.var]) bb<-bb_probabilitydensity burst<-names(bb) tracksums$bbref<-1:nrow(tracksums) # get unique groups (use tracksums b/c these points are contained in polygon - not a tracks will necessarily be represented in a given polygon) (grp.ids<-unique(tracksums$timegrp)) #### initialize lists to house data by desired grouping variable (group.uniq) # list to house uds normalized by track duration bbindis <- vector ("list", length(grp.ids)) #### loop through groups for (h in 1:length(grp.ids)) { grp.id<-grp.ids[h] #tracksums.want<-tracksums[which(tracksums$grp==grp.ids[k]),] tracksums.want<-tracksums%>%dplyr::filter(timegrp==grp.id) # create summary table of # of segments from each track (track.freq<-tracksums.want%>%group_by(uniID)%>% dplyr::summarize(n=n_distinct(seg_id),minbb=min(bbref),maxbb=max(bbref))) # initialize lists to house data for segment based on deploy_id ud.track <- vector("list", nrow(track.freq)) track.days <- vector ("list", nrow(track.freq)) # sum up segments for each track # run through track.freq table summing segments >1 for (j in 1:nrow(track.freq)) { if (track.freq$n[j]==1) { # operation for only one segment in polygon bbIndx<-track.freq$minbb[j] ud.seg<-bb[[bbIndx]] a<- slot(ud.seg,"data") slot(ud.seg,"data")<-a*(cellsize^2) ud.track[[j]]<-ud.seg # get number of track days (in decimal days) track.days[[j]]<-tracksums.want$days[tracksums.want$uniID==track.freq$uniID[j]] #paste(paste("bird:",track.freq$uniID[j], # "segnum:",track.freq$n[j], # "area:",sum(slot(ud.track[[j]],"data")[,1]))) } else { # get multiple segments days.segs<-tracksums.want$days[tracksums.want$uniID==track.freq$uniID[j]] bbIndx.segs<-seq(from=track.freq$minbb[track.freq$uniID==track.freq$uniID[j]], to=track.freq$maxbb[track.freq$uniID==track.freq$uniID[j]]) # list to house each segment ud.segs.new <- vector ("list", length(bbIndx.segs)) for (k in 1:length(bbIndx.segs)) { bbIndx<-bbIndx.segs[k] ud.seg <- bb[[bbIndx]] # weigh each segment it's proportion of total hours tracked within the clipperName (Freiberg 20XX paper) a<- slot(ud.seg,"data")*(days.segs[k]/sum(days.segs)) #slot(ud.seg,"data")<-a ud.segs.new[[k]] <- a } # adds the segments from one bird together into one UD spdf<-Reduce("+",ud.segs.new)*(cellsize^2) sum(spdf) estUDsum<-ud.seg#steal UD formatting from slot(estUDsum,"data")<-spdf ud.track[[j]]<-estUDsum # get number of track days track.days[[j]]<-sum(days.segs)} #print(paste(j,k,sum(slot(ud.track[[j]],"data")))) } names(ud.track)<-track.freq$uniID class(ud.track) <- "estUDm" bbindis[[h]]<-ud.track } names(bbindis)<-grp.ids #class(bbindis)<-"estUD" return(bbindis) }
library(dtwclust) library(dtw) words = list("nula", "jedan", "dva", "tri", "cetiri", "pet", "sest", "sedam", "osam", "devet", "plus", "minus", "puta", "dijeljeno", "jednako") for(word in words){ path = 'C:/Users/Mira/Documents/DIPLOMSKI RAD - ALGORITAM PORAVNANJA VREMENSKIH NIZOVA/speach-recognition/Dataset/Train/' directory = paste(path, word, sep="") files = Sys.glob(file.path(directory, "*.txt")) mfccs = list() i = 1 for(file in files){ data = as.matrix(read.table(file ,header=FALSE,sep=" ")) n = ncol(data) data=t(data) data = na.omit(data) mfccs[[i]] = data i = i + 1 } average = DBA(mfccs) filename = paste(directory, "/", word, "_average1.txt", sep="") print(filename) write.table(t(average), file=filename, row.names=FALSE, col.names=FALSE, sep=" ") }
/speach-recognition/baricenter-averaging.R
no_license
mjukicbraculj/Diplomski-rad
R
false
false
833
r
library(dtwclust) library(dtw) words = list("nula", "jedan", "dva", "tri", "cetiri", "pet", "sest", "sedam", "osam", "devet", "plus", "minus", "puta", "dijeljeno", "jednako") for(word in words){ path = 'C:/Users/Mira/Documents/DIPLOMSKI RAD - ALGORITAM PORAVNANJA VREMENSKIH NIZOVA/speach-recognition/Dataset/Train/' directory = paste(path, word, sep="") files = Sys.glob(file.path(directory, "*.txt")) mfccs = list() i = 1 for(file in files){ data = as.matrix(read.table(file ,header=FALSE,sep=" ")) n = ncol(data) data=t(data) data = na.omit(data) mfccs[[i]] = data i = i + 1 } average = DBA(mfccs) filename = paste(directory, "/", word, "_average1.txt", sep="") print(filename) write.table(t(average), file=filename, row.names=FALSE, col.names=FALSE, sep=" ") }
## First function takes a square matrix and returns a list of functions to both set and get the matrix and inverse ## This list is then used as the input to the next function so the use of <-- to write to write outside the environment is present makeCacheMatrix <- function(x = matrix()) { i<- NULL set<-function(y){ x<<-y #<-- has been used to write to the outside environment i<<-NULL #<-- has been used to write to the outside environment } get <-function() x seti<-function(inverse) i<<-inverse #<-- has been used to write to the outside environment geti<-function() i list(set=set, get=get, seti=seti, geti=geti) } ## Second funtion takes the output of the first as mentioned above and returns the invers of the matrix first entered to the first function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' i<-x$geti() if(!is.null(i)){ message("getting cached data") return(i) } data<-x$get() i<-solve(data) x$seti(i) return(i) }
/cachematrix.R
no_license
CodeManLearner/ProgrammingAssignment2
R
false
false
1,031
r
## First function takes a square matrix and returns a list of functions to both set and get the matrix and inverse ## This list is then used as the input to the next function so the use of <-- to write to write outside the environment is present makeCacheMatrix <- function(x = matrix()) { i<- NULL set<-function(y){ x<<-y #<-- has been used to write to the outside environment i<<-NULL #<-- has been used to write to the outside environment } get <-function() x seti<-function(inverse) i<<-inverse #<-- has been used to write to the outside environment geti<-function() i list(set=set, get=get, seti=seti, geti=geti) } ## Second funtion takes the output of the first as mentioned above and returns the invers of the matrix first entered to the first function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' i<-x$geti() if(!is.null(i)){ message("getting cached data") return(i) } data<-x$get() i<-solve(data) x$seti(i) return(i) }
##Assignment3## ##Q0 firstName<- "JINGNI" lastName <- "LI" print( paste(firstName, lastName ) ) studentID<- "1505021" print(studentID) print("jli239@ucsc.edu") ## Q1 ##loding data library(foreign) df.ex<-read.dta("https://github.com/EconomiCurtis/econ294_2015/raw/master/data/org_example.dta") View(df.ex) ##Q2 ##filter install.packages("dplyr") library(dplyr) df.ex.lastyear2013<- dplyr::filter(df.ex,year == 2013 & month == 12) print(nrow(df.ex.lastyear2013)) july <- sum(with(df.ex,year==2013&month==7)) august <- sum(with(df.ex,year==2013&month==8)) sept <-sum(with(df.ex,year==2013&month==9)) summer2013<-sum(july+august+sept) print(summer2013) ##Q3 install.packages("dplyr") library(foreign) df.ex.3a <-arrange(df.ex, year, month) View(df.ex.3a) ##Q4 df.ex.4a<-select(df.ex,year,age) View(df.ex.4a) df.ex.4b <- select(df.ex, year,month,starts_with("i")) state<-distinct(select(df.ex, state)) View(state) ##Q5 stndz <- function(x){(x - mean(x, na.rm = T)) / sd(x, na.rm = T)} nrmlz <-function(x) {(x-min(x,na.rm = T))/(max(x,na.rm = T)-min(x,na.rm=T))} df.ex.5a <- dplyr::mutate(df.ex, rw.stndz = stndz(rw), rw_nrmlz = nrmlz(rw)) %>% select(rw.stndz, rw_nrmlz) df.ex.5b <- df.ex %>% group_by(year,month) %>% mutate(rw.stndz = stndz(rw), rw_nrmlz = nrmlz(rw),count = n()) %>% select(rw.stndz, rw_nrmlz,count) ##Q6 df.ex.6 <- dplyr::group_by(df.ex,year, month, state) %>% dplyr::summarise( rw.min = min(rw, na.rm = T), rw.1stq = quantile(rw, 0.25, na.rm = T), rw.mean = mean(rw, na.rm = T), rw.median = median(rw, na.rm = T), rw.3rdq = quantile(rw, 0.75, na.rm = T), rw.max = max(rw, na.rm = T), count = n() ) print(nrow(df.ex.6)) View(df.ex.6)
/jingniliAssignment3Creator.R
no_license
JINGNILItina/TINA
R
false
false
1,717
r
##Assignment3## ##Q0 firstName<- "JINGNI" lastName <- "LI" print( paste(firstName, lastName ) ) studentID<- "1505021" print(studentID) print("jli239@ucsc.edu") ## Q1 ##loding data library(foreign) df.ex<-read.dta("https://github.com/EconomiCurtis/econ294_2015/raw/master/data/org_example.dta") View(df.ex) ##Q2 ##filter install.packages("dplyr") library(dplyr) df.ex.lastyear2013<- dplyr::filter(df.ex,year == 2013 & month == 12) print(nrow(df.ex.lastyear2013)) july <- sum(with(df.ex,year==2013&month==7)) august <- sum(with(df.ex,year==2013&month==8)) sept <-sum(with(df.ex,year==2013&month==9)) summer2013<-sum(july+august+sept) print(summer2013) ##Q3 install.packages("dplyr") library(foreign) df.ex.3a <-arrange(df.ex, year, month) View(df.ex.3a) ##Q4 df.ex.4a<-select(df.ex,year,age) View(df.ex.4a) df.ex.4b <- select(df.ex, year,month,starts_with("i")) state<-distinct(select(df.ex, state)) View(state) ##Q5 stndz <- function(x){(x - mean(x, na.rm = T)) / sd(x, na.rm = T)} nrmlz <-function(x) {(x-min(x,na.rm = T))/(max(x,na.rm = T)-min(x,na.rm=T))} df.ex.5a <- dplyr::mutate(df.ex, rw.stndz = stndz(rw), rw_nrmlz = nrmlz(rw)) %>% select(rw.stndz, rw_nrmlz) df.ex.5b <- df.ex %>% group_by(year,month) %>% mutate(rw.stndz = stndz(rw), rw_nrmlz = nrmlz(rw),count = n()) %>% select(rw.stndz, rw_nrmlz,count) ##Q6 df.ex.6 <- dplyr::group_by(df.ex,year, month, state) %>% dplyr::summarise( rw.min = min(rw, na.rm = T), rw.1stq = quantile(rw, 0.25, na.rm = T), rw.mean = mean(rw, na.rm = T), rw.median = median(rw, na.rm = T), rw.3rdq = quantile(rw, 0.75, na.rm = T), rw.max = max(rw, na.rm = T), count = n() ) print(nrow(df.ex.6)) View(df.ex.6)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/extract-prm.R \name{extract_prm} \alias{extract_prm} \alias{extract_prm_cohort} \title{Extract values for Atlantis parameters from the biological parameter file.} \usage{ extract_prm(prm_biol, variables, ignore_duplicates = FALSE) extract_prm_cohort(prm_biol, variables) } \arguments{ \item{prm_biol}{Character string giving the connection to the biological parameterfile. The filename usually contains \code{biol_fishing} and does end in \code{.prm}.} \item{variables}{Character string giving the flag to search for. This should be a combination of the parameter name and the group-Code.} \item{ignore_duplicates}{TRUE to just return first value in case of duplicates, FALSE for error} } \value{ numeric vector. } \description{ Extract values for Atlantis parameters from the biological parameter file. } \examples{ d <- system.file("extdata", "setas-model-new-trunk", package = "atlantistools") prm_biol <- file.path(d, "VMPA_setas_biol_fishing_Trunk.prm") # You can pass a single variable extract_prm(prm_biol, variables = "KWRR_FVS") # Or multiple variables extract_prm(prm_biol, variables = paste("KWRR", c("FVS", "FPS"), sep = "_")) # Use extract_prm_cohort do extract data for age specific parameters. # They are usually stored in the next line following the parameter tag. extract_prm_cohort(prm_biol, variables = "C_FVS") extract_prm_cohort(prm_biol, variables = paste("C", c("FVS", "FPS"), sep = "_")) }
/man/extract_prm.Rd
no_license
cbracis/atlantistools
R
false
true
1,498
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/extract-prm.R \name{extract_prm} \alias{extract_prm} \alias{extract_prm_cohort} \title{Extract values for Atlantis parameters from the biological parameter file.} \usage{ extract_prm(prm_biol, variables, ignore_duplicates = FALSE) extract_prm_cohort(prm_biol, variables) } \arguments{ \item{prm_biol}{Character string giving the connection to the biological parameterfile. The filename usually contains \code{biol_fishing} and does end in \code{.prm}.} \item{variables}{Character string giving the flag to search for. This should be a combination of the parameter name and the group-Code.} \item{ignore_duplicates}{TRUE to just return first value in case of duplicates, FALSE for error} } \value{ numeric vector. } \description{ Extract values for Atlantis parameters from the biological parameter file. } \examples{ d <- system.file("extdata", "setas-model-new-trunk", package = "atlantistools") prm_biol <- file.path(d, "VMPA_setas_biol_fishing_Trunk.prm") # You can pass a single variable extract_prm(prm_biol, variables = "KWRR_FVS") # Or multiple variables extract_prm(prm_biol, variables = paste("KWRR", c("FVS", "FPS"), sep = "_")) # Use extract_prm_cohort do extract data for age specific parameters. # They are usually stored in the next line following the parameter tag. extract_prm_cohort(prm_biol, variables = "C_FVS") extract_prm_cohort(prm_biol, variables = paste("C", c("FVS", "FPS"), sep = "_")) }
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/metab.kalman.R \name{metab.kalman} \alias{metab.kalman} \title{Metabolism calculated from parameters estimated using a Kalman filter} \usage{ metab.kalman(do.obs, do.sat, k.gas, z.mix, irr, wtr, ...) } \arguments{ \item{do.obs}{Vector of dissovled oxygen concentration observations, \eqn{mg O[2] L^{-1}}{mg O2 / L}} \item{do.sat}{Vector of dissolved oxygen saturation values based on water temperature. Calculate using \link{o2.at.sat}} \item{k.gas}{Vector of kGAS values calculated from any of the gas flux models (e.g., \link{k.cole}) and converted to kGAS using \link{k600.2.kGAS}} \item{z.mix}{Vector of mixed-layer depths in meters. To calculate, see \link{ts.meta.depths}} \item{irr}{Vector of photosynthetically active radiation in \eqn{\mu mol\ m^{-2} s^{-1}}{micro mols / m^2 / s}} \item{wtr}{Vector of water temperatures in \eqn{^{\circ}C}{degrees C}. Used in scaling respiration with temperature} \item{...}{additional arguments; currently "datetime" is the only recognized argument passed through \code{...}} } \value{ A data.frame with columns corresponding to components of metabolism \describe{ \item{GPP}{numeric estimate of Gross Primary Production, \eqn{mg O_2 L^{-1} d^{-1}}{mg O2 / L / d}} \item{R}{numeric estimate of Respiration, \eqn{mg O_2 L^{-1} d^{-1}}{mg O2 / L / d}} \item{NEP}{numeric estimate of Net Ecosystem production, \eqn{mg O_2 L^{-1} d^{-1}}{mg O2 / L / d}} } Use \link{attributes} to access more model output: \item{smoothDO}{smoothed time series of oxygen concentration (\eqn{mg O[2] L^{-1}}{mg O2 / L}), from Kalman smoother} \item{params}{parameters estimated by the Kalman filter (\eqn{c_1, c_2, Q, H}{c1, c2, Q, H})} } \description{ A state space model accounting for process and observation error, with the maximum likelihood of parameteres estimated using a Kalman filter. Also provides a smoothed time series of oxygen concentration. } \details{ The model has four parameters, \eqn{c_1, c_2, Q, H}{c1, c2, Q, H}, and consists of equations involving the prediction of upcoming state conditional on information of the previous state (\eqn{a_{t|t-1}}{a[t|t-1]}, \eqn{P_{t|t-1}}{P[t|t-1]}), as well as updates of those predictions that are conditional upon information of the current state (\eqn{a_{t|t}}{a[t|t]}, \eqn{P_{t|t}}{P[t|t]}). \eqn{a} is the \deqn{v=k.gas/z.mix}{v=k.gas/z.mix} \deqn{a_t = c_1*irr_{t-1} + c_2*log_e(wtr_{t-1}) + v_{t-1}*do.sat_{t-1}}{a[t] = c1*irr[t-1] + c2*log(wtr[t-1]) + v[t-1]*do.sat[t-1]} \deqn{\beta = e^{-v}}{beta = exp(-v)} \deqn{do.obs_t = a_t/v_{t-1} + -e^{-v_{t-1}}*a_t/v_{t-1} + \beta_{t-1}*\do.obs_{t-1} + \epsilon_t}{do.obs[t] = a[t]/v[t-1] + -exp(-v[t-1])*a[t]/v[t-1] + beta[t-1]*do.obs[t-1] + epsilon[t]} The above model is used during model fitting, but if gas flux is not integrated between time steps, those equations simplify to the following: \deqn{F_{t-1} = k.gas_{t-1}*(do.sat_{t-1} - do.obs_{t-1})/z.mix_{t-1}}{F[t-1] = k.gas[t-1]*(do.sat[t-1] - do.obs[t-1])/z.mix[t-1]} \deqn{do.obs_t=do.obs_{t-1}+c_1*irr_{t-1}+c_2*log_e(wtr_{t-1}) + F_{t-1} + \epsilon_t}{do.obs[t] = do.obs[t-1] + c1*irr[t-1] + c2*log(wtr[t-1]) + F[t-1] + epsilon[t]} The parameters are fit using maximum likelihood, and the optimization (minimization of the negative log likelihood function) is performed by \code{optim} using default settings. GPP is then calculated as \code{mean(c1*irr, na.rm=TRUE)*freq}, where \code{freq} is the number of observations per day, as estimated from the typical size between time steps. Thus, generally \code{freq==length(do.obs)}. Similarly, R is calculated as \code{mean(c2*log(wtr), na.rm=TRUE)*freq}. NEP is the sum of GPP and R. } \note{ If observation error is substantial, consider applying a Kalman filter to the water temperature time series by supplying \code{wtr} as the output from \link{temp.kalman} } \examples{ library(rLakeAnalyzer) doobs <- load.ts(system.file('extdata', 'sparkling.doobs', package="LakeMetabolizer")) wtr <- load.ts(system.file('extdata', 'sparkling.wtr', package="LakeMetabolizer")) wnd <- load.ts(system.file('extdata', 'sparkling.wnd', package="LakeMetabolizer")) irr <- load.ts(system.file('extdata', 'sparkling.par', package="LakeMetabolizer")) #Subset a day Sys.setenv(TZ='GMT') mod.date <- as.POSIXct('2009-07-08', 'GMT') doobs <- doobs[trunc(doobs$datetime, 'day') == mod.date, ] wtr <- wtr[trunc(wtr$datetime, 'day') == mod.date, ] wnd <- wnd[trunc(wnd$datetime, 'day') == mod.date, ] irr <- irr[trunc(irr$datetime, 'day') == mod.date, ] k600 <- k.cole.base(wnd[,2]) k.gas <- k600.2.kGAS.base(k600, wtr[,3], 'O2') do.sat <- o2.at.sat.base(wtr[,3], altitude=300) metab.kalman(irr=irr[,2], z.mix=rep(1, length(k.gas)), do.sat=do.sat, wtr=wtr[,2], k.gas=k.gas, do.obs=doobs[,2]) } \author{ Ryan Batt, Luke A. Winslow } \references{ Batt, Ryan D. and Stephen R. Carpenter. 2012. \emph{Free-water lake metabolism: addressing noisy time series with a Kalman filter}. Limnology and Oceanography: Methods 10: 20-30. doi: 10.4319/lom.2012.10.20 } \seealso{ \link{temp.kalman}, \link{watts.in}, \link{metab}, \link{metab.bookkeep}, \link{metab.ols}, \link{metab.mle}, \link{metab.bayesian} }
/man/metab.kalman.Rd
no_license
aappling-usgs/LakeMetabolizer
R
false
false
5,366
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/metab.kalman.R \name{metab.kalman} \alias{metab.kalman} \title{Metabolism calculated from parameters estimated using a Kalman filter} \usage{ metab.kalman(do.obs, do.sat, k.gas, z.mix, irr, wtr, ...) } \arguments{ \item{do.obs}{Vector of dissovled oxygen concentration observations, \eqn{mg O[2] L^{-1}}{mg O2 / L}} \item{do.sat}{Vector of dissolved oxygen saturation values based on water temperature. Calculate using \link{o2.at.sat}} \item{k.gas}{Vector of kGAS values calculated from any of the gas flux models (e.g., \link{k.cole}) and converted to kGAS using \link{k600.2.kGAS}} \item{z.mix}{Vector of mixed-layer depths in meters. To calculate, see \link{ts.meta.depths}} \item{irr}{Vector of photosynthetically active radiation in \eqn{\mu mol\ m^{-2} s^{-1}}{micro mols / m^2 / s}} \item{wtr}{Vector of water temperatures in \eqn{^{\circ}C}{degrees C}. Used in scaling respiration with temperature} \item{...}{additional arguments; currently "datetime" is the only recognized argument passed through \code{...}} } \value{ A data.frame with columns corresponding to components of metabolism \describe{ \item{GPP}{numeric estimate of Gross Primary Production, \eqn{mg O_2 L^{-1} d^{-1}}{mg O2 / L / d}} \item{R}{numeric estimate of Respiration, \eqn{mg O_2 L^{-1} d^{-1}}{mg O2 / L / d}} \item{NEP}{numeric estimate of Net Ecosystem production, \eqn{mg O_2 L^{-1} d^{-1}}{mg O2 / L / d}} } Use \link{attributes} to access more model output: \item{smoothDO}{smoothed time series of oxygen concentration (\eqn{mg O[2] L^{-1}}{mg O2 / L}), from Kalman smoother} \item{params}{parameters estimated by the Kalman filter (\eqn{c_1, c_2, Q, H}{c1, c2, Q, H})} } \description{ A state space model accounting for process and observation error, with the maximum likelihood of parameteres estimated using a Kalman filter. Also provides a smoothed time series of oxygen concentration. } \details{ The model has four parameters, \eqn{c_1, c_2, Q, H}{c1, c2, Q, H}, and consists of equations involving the prediction of upcoming state conditional on information of the previous state (\eqn{a_{t|t-1}}{a[t|t-1]}, \eqn{P_{t|t-1}}{P[t|t-1]}), as well as updates of those predictions that are conditional upon information of the current state (\eqn{a_{t|t}}{a[t|t]}, \eqn{P_{t|t}}{P[t|t]}). \eqn{a} is the \deqn{v=k.gas/z.mix}{v=k.gas/z.mix} \deqn{a_t = c_1*irr_{t-1} + c_2*log_e(wtr_{t-1}) + v_{t-1}*do.sat_{t-1}}{a[t] = c1*irr[t-1] + c2*log(wtr[t-1]) + v[t-1]*do.sat[t-1]} \deqn{\beta = e^{-v}}{beta = exp(-v)} \deqn{do.obs_t = a_t/v_{t-1} + -e^{-v_{t-1}}*a_t/v_{t-1} + \beta_{t-1}*\do.obs_{t-1} + \epsilon_t}{do.obs[t] = a[t]/v[t-1] + -exp(-v[t-1])*a[t]/v[t-1] + beta[t-1]*do.obs[t-1] + epsilon[t]} The above model is used during model fitting, but if gas flux is not integrated between time steps, those equations simplify to the following: \deqn{F_{t-1} = k.gas_{t-1}*(do.sat_{t-1} - do.obs_{t-1})/z.mix_{t-1}}{F[t-1] = k.gas[t-1]*(do.sat[t-1] - do.obs[t-1])/z.mix[t-1]} \deqn{do.obs_t=do.obs_{t-1}+c_1*irr_{t-1}+c_2*log_e(wtr_{t-1}) + F_{t-1} + \epsilon_t}{do.obs[t] = do.obs[t-1] + c1*irr[t-1] + c2*log(wtr[t-1]) + F[t-1] + epsilon[t]} The parameters are fit using maximum likelihood, and the optimization (minimization of the negative log likelihood function) is performed by \code{optim} using default settings. GPP is then calculated as \code{mean(c1*irr, na.rm=TRUE)*freq}, where \code{freq} is the number of observations per day, as estimated from the typical size between time steps. Thus, generally \code{freq==length(do.obs)}. Similarly, R is calculated as \code{mean(c2*log(wtr), na.rm=TRUE)*freq}. NEP is the sum of GPP and R. } \note{ If observation error is substantial, consider applying a Kalman filter to the water temperature time series by supplying \code{wtr} as the output from \link{temp.kalman} } \examples{ library(rLakeAnalyzer) doobs <- load.ts(system.file('extdata', 'sparkling.doobs', package="LakeMetabolizer")) wtr <- load.ts(system.file('extdata', 'sparkling.wtr', package="LakeMetabolizer")) wnd <- load.ts(system.file('extdata', 'sparkling.wnd', package="LakeMetabolizer")) irr <- load.ts(system.file('extdata', 'sparkling.par', package="LakeMetabolizer")) #Subset a day Sys.setenv(TZ='GMT') mod.date <- as.POSIXct('2009-07-08', 'GMT') doobs <- doobs[trunc(doobs$datetime, 'day') == mod.date, ] wtr <- wtr[trunc(wtr$datetime, 'day') == mod.date, ] wnd <- wnd[trunc(wnd$datetime, 'day') == mod.date, ] irr <- irr[trunc(irr$datetime, 'day') == mod.date, ] k600 <- k.cole.base(wnd[,2]) k.gas <- k600.2.kGAS.base(k600, wtr[,3], 'O2') do.sat <- o2.at.sat.base(wtr[,3], altitude=300) metab.kalman(irr=irr[,2], z.mix=rep(1, length(k.gas)), do.sat=do.sat, wtr=wtr[,2], k.gas=k.gas, do.obs=doobs[,2]) } \author{ Ryan Batt, Luke A. Winslow } \references{ Batt, Ryan D. and Stephen R. Carpenter. 2012. \emph{Free-water lake metabolism: addressing noisy time series with a Kalman filter}. Limnology and Oceanography: Methods 10: 20-30. doi: 10.4319/lom.2012.10.20 } \seealso{ \link{temp.kalman}, \link{watts.in}, \link{metab}, \link{metab.bookkeep}, \link{metab.ols}, \link{metab.mle}, \link{metab.bayesian} }
hybrid.pc.backend = function(x, cluster = NULL, whitelist, blacklist, test, alpha, B, max.sx = ncol(x), complete, debug = FALSE) { nodes = names(x) mb = smartSapply(cluster, as.list(nodes), hybrid.pc.heuristic, data = x, nodes = nodes, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, debug = debug) names(mb) = nodes # make up a set of believable Markov blankets, using all the nodes within # distance 2 from the target node (which is a superset). for (node in nodes) mb[[node]]$mb = fake.markov.blanket(mb, node) # check neighbourhood sets for consistency. mb = bn.recovery(mb, nodes = nodes, debug = debug) return(mb) }#HYBRID.PC.BACKEND hybrid.pc.heuristic = function(x, data, nodes, alpha, B, whitelist, blacklist, test, max.sx = ncol(data), complete, debug = FALSE) { # identify the parents-and-children superset. pvalues = hybrid.pc.de.pcs(x = x, data = data, nodes = nodes, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, complete = complete, debug = debug) pc.superset = names(pvalues) # if the superset contains zero or just one nodes, there is nothing else to do # (the superset is not super, it is the right set). if (length(pc.superset) < 2) return(list(nbr = pc.superset, mb = NULL)) # identify the spouses superset (some spouses may already be in the # parents-and-children superset). sp.superset = hybrid.pc.de.sps(x = x, data = data, nodes = nodes, pc.superset = pc.superset, dsep.set = attr(pvalues, "dsep.set"), alpha = alpha, B = B, test = test, max.sx = max.sx, complete = complete, debug = debug) # if there are just two nodes in the parents-and-children set and no spouse, # the superset is necessarily the same as the set.. if ((length(pc.superset) == 2) && (length(sp.superset) == 0)) return(list(nbr = pc.superset, mb = pc.superset)) # the two nodes with the smallest p-values would be examined again using the # same low-order tests as before, so just include them. start = names(sort(pvalues))[1:min(length(pvalues), 2)] # identify the real parents and children from the supersets. pc = hybrid.pc.nbr.search(x, data = data, nodes = c(x, pc.superset, sp.superset), alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, start = start, debug = debug) # one more scan to identify possible false negatives. for (node in setdiff(pc.superset, pc)) { fn = hybrid.pc.nbr.search(node, data = data, nodes = c(x, pc.superset, sp.superset), alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, start = start, debug = debug, looking.for = x) # add the nodes which appear to be neighbours. if (x %in% fn) { pc = c(pc, node) mb = c(mb, node) if (debug) cat(" @", node, "added to the parents and children. (HPC's OR)\n") }#THEN }#FOR return(list(nbr = pc, mb = c(pc.superset, sp.superset))) }#HYBRID.PC.HEURISTIC hybrid.pc.nbr.search = function(x, data, nodes, alpha, B, whitelist, blacklist, test, max.sx = ncol(data), complete, debug = FALSE, start = start, looking.for = NULL) { mb = ia.fdr.markov.blanket(x, data = data, nodes = nodes, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, start = start, test = test, max.sx = max.sx, complete = complete, debug = debug) # if the node is not in the markov blanket it cannot be a neighbour either. if (!is.null(looking.for) && (looking.for %!in% mb)) return(NULL) pc = hybrid.pc.filter(x, pc.superset = mb, sp.superset = NULL, data = data, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, debug = debug) return(pc) }#HYBRID.PC.NBR.SEARCH hybrid.pc.de.pcs = function(x, data, nodes, alpha, B, whitelist, blacklist, test, complete, debug = FALSE) { whitelisted = nodes[sapply(nodes, function(y) { is.whitelisted(whitelist, c(x, y), either = TRUE) })] blacklisted = nodes[sapply(nodes, function(y) { is.blacklisted(blacklist, c(x, y), both = TRUE) })] if (debug) { cat("----------------------------------------------------------------\n") cat("* learning the parents and children superset of", x, ".\n") }#THEN if (debug) cat(" * nodes to be tested for inclusion: '", nodes[nodes %!in% x], "'.\n") # all nodes are candidates initially, except for those whose status is already # determined (from whitelist and blacklist). to.check = setdiff(nodes, c(x, whitelisted, blacklisted)) # exclude nodes that are marginally independent from the target. association = indep.test(to.check, x, sx = character(0), data = data, test = test, B = B, alpha = alpha, complete = complete) to.keep = names(association[association <= alpha]) to.drop = names(association[association > alpha]) pvalues = association[to.keep] if (debug) { cat(" * checking nodes for association.\n") if (length(to.keep) > 0) { cat(" * nodes that are still candidates for inclusion.\n") sapply(to.keep, function(x) { cat(" >", x, "has p-value", association[x], ".\n")}) }#THEN if (length(to.drop) > 0) { cat(" * nodes that will be disregarded from now on.\n") sapply(to.drop, function(x) { cat(" >", x, "has p-value", association[x], ".\n")}) }#THEN }#THEN # sort the candidates in order of increasing association, so that nodes with # weak associations are checked for exclusion first. pvalues = sort(pvalues, decreasing = TRUE) to.check = names(pvalues) fixed = whitelisted if (debug) cat(" * nodes to be tested for exclusion: '", to.check, "'.\n") pvalues = structure(c(rep(0, length(fixed)), pvalues), names = c(fixed, names(pvalues))) dsep.set = list() # if there is only a single node left to check, it would be conditional on # the empty set which would just repeat an earlier test; nothing left to do. if (length(to.check) == 1) return(structure(pvalues, dsep.set = dsep.set)) # exlcude nodes that are independent given a single conditioning node. for (node in to.check) { # sort the candidates in order of decreasing association, so that nodes with # strong associations are checked first. to.check.against = setdiff(names(sort(pvalues, decreasing = FALSE)), node) if (length(to.check.against) == 0) next a = allsubs.test(x = x, y = node, sx = to.check.against, min = 1, max = 1, data = data, test = test, alpha = alpha, B = B, complete = complete, debug = debug) if (a["p.value"] > alpha) { pvalues = pvalues[names(pvalues) != node] dsep.set[[node]] = attr(a, "dsep.set") }#THEN else { pvalues[node] = max(pvalues[node], a["max.p.value"]) }#ELSE }#FOR return(structure(pvalues, dsep.set = dsep.set)) }#HYBRID.PC.DE.PCS hybrid.pc.de.sps = function(x, data, nodes, pc.superset, dsep.set, alpha, B, test, max.sx, complete, debug = FALSE) { spouses.superset = character(0) if (debug) { cat("----------------------------------------------------------------\n") cat("* learning the spouses superset of", x, ".\n") cat(" * nodes still to be tested for inclusion:", nodes[nodes %!in% c(x, pc.superset)], "\n") }#THEN for (cpc in pc.superset) { pvalues = numeric(0) # forward selection. for (y in setdiff(nodes, c(x, pc.superset))) { # if the candidate node d-separates the current node from a node that is # not in the superset, it is potentially in the markov blanket and thus a # potential spouse. if (cpc %in% dsep.set[[y]]) next # skip tests whose conditioning sets are too large (assuming independence # means not adding the node to the superset). if (length(c(dsep.set[[y]], cpc)) > max.sx) next if (debug) cat(" > checking node", y, "for inclusion.\n") a = indep.test(x = x, y = y, sx = c(dsep.set[[y]], cpc), data = data, test = test, B = B, alpha = alpha, complete = complete) if (debug) cat(" > node", x, "is", ifelse(a > alpha, "independent from", "dependent on"), y, "given", c(dsep.set[[y]], cpc), " ( p-value:", a, ").\n") if (a <= alpha) { pvalues[y] = a if (debug) cat(" @ node", y, "added to the spouses superset.\n") }#THEN }#FOR # sort the candidates in order of increasing association, so that nodes with # weak associations are checked for exclusion first. pvalues = sort(pvalues, decreasing = TRUE) # backward selection, to remove false positives. for (y in names(pvalues)) { sx = setdiff(names(pvalues), y) if (length(sx) == 0) next if (debug) cat(" > checking node", y, "for removal.\n") a = allsubs.test(x = x, y = y, sx = sx, fixed = cpc, data = data, test = test, B = B, alpha = alpha, complete = complete, min = 1, max = 1, debug = debug) if (a["p.value"] > alpha) { pvalues = pvalues[names(pvalues) != y] if (debug) cat(" @ node", y, "removed from the spouses superset.\n") }#THEN }#FOR spouses.superset = union(spouses.superset, names(pvalues)) }#FOR return(spouses.superset) }#HYBRID.PC.DE.SPS hybrid.pc.filter = function(x, pc.superset, sp.superset, data, alpha, B = B, whitelist, blacklist, test, max.sx, complete, debug = FALSE) { nodes = names(data) mb.superset = c(pc.superset, sp.superset) whitelisted = nodes[sapply(nodes, function(y) { is.whitelisted(whitelist, c(x, y), either = TRUE) })] blacklisted = nodes[sapply(nodes, function(y) { is.blacklisted(blacklist, c(x, y), both = TRUE) })] if (debug) { cat("----------------------------------------------------------------\n") cat("* filtering parents and children of", x, ".\n") cat(" * blacklisted nodes: '", blacklisted, "'\n") cat(" * whitelisted nodes: '", whitelisted, "'\n") cat(" * starting with neighbourhood superset: '", pc.superset, "'\n") cat(" * with spouses superset: '", sp.superset, "'\n") }#THEN # make sure blacklisted nodes are not included, and add whitelisted nodes. pc.superset = union(setdiff(pc.superset, blacklisted), whitelisted) mb.superset = union(mb.superset, whitelisted) # if the markov blanket is empty, the neighbourhood is empty as well. if (length(mb.superset) == 0) return(character(0)) nbr = function(node) { a = allsubs.test(x = x, y = node, sx = setdiff(mb.superset, node), data = data, test = test, B = B, alpha = alpha, max = max.sx, complete = complete, debug = debug) return(as.logical(a["p.value"] < alpha)) }#NBR # do not even try to remove whitelisted nodes. pc = names(which(sapply(setdiff(pc.superset, whitelisted), nbr))) # make sure whitelisted nodes are always included. pc = unique(c(pc, whitelisted)) return(pc) }#HYBRID.PC.FILTER
/R/hybrid-pc.R
no_license
cran/bnlearn
R
false
false
11,462
r
hybrid.pc.backend = function(x, cluster = NULL, whitelist, blacklist, test, alpha, B, max.sx = ncol(x), complete, debug = FALSE) { nodes = names(x) mb = smartSapply(cluster, as.list(nodes), hybrid.pc.heuristic, data = x, nodes = nodes, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, debug = debug) names(mb) = nodes # make up a set of believable Markov blankets, using all the nodes within # distance 2 from the target node (which is a superset). for (node in nodes) mb[[node]]$mb = fake.markov.blanket(mb, node) # check neighbourhood sets for consistency. mb = bn.recovery(mb, nodes = nodes, debug = debug) return(mb) }#HYBRID.PC.BACKEND hybrid.pc.heuristic = function(x, data, nodes, alpha, B, whitelist, blacklist, test, max.sx = ncol(data), complete, debug = FALSE) { # identify the parents-and-children superset. pvalues = hybrid.pc.de.pcs(x = x, data = data, nodes = nodes, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, complete = complete, debug = debug) pc.superset = names(pvalues) # if the superset contains zero or just one nodes, there is nothing else to do # (the superset is not super, it is the right set). if (length(pc.superset) < 2) return(list(nbr = pc.superset, mb = NULL)) # identify the spouses superset (some spouses may already be in the # parents-and-children superset). sp.superset = hybrid.pc.de.sps(x = x, data = data, nodes = nodes, pc.superset = pc.superset, dsep.set = attr(pvalues, "dsep.set"), alpha = alpha, B = B, test = test, max.sx = max.sx, complete = complete, debug = debug) # if there are just two nodes in the parents-and-children set and no spouse, # the superset is necessarily the same as the set.. if ((length(pc.superset) == 2) && (length(sp.superset) == 0)) return(list(nbr = pc.superset, mb = pc.superset)) # the two nodes with the smallest p-values would be examined again using the # same low-order tests as before, so just include them. start = names(sort(pvalues))[1:min(length(pvalues), 2)] # identify the real parents and children from the supersets. pc = hybrid.pc.nbr.search(x, data = data, nodes = c(x, pc.superset, sp.superset), alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, start = start, debug = debug) # one more scan to identify possible false negatives. for (node in setdiff(pc.superset, pc)) { fn = hybrid.pc.nbr.search(node, data = data, nodes = c(x, pc.superset, sp.superset), alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, start = start, debug = debug, looking.for = x) # add the nodes which appear to be neighbours. if (x %in% fn) { pc = c(pc, node) mb = c(mb, node) if (debug) cat(" @", node, "added to the parents and children. (HPC's OR)\n") }#THEN }#FOR return(list(nbr = pc, mb = c(pc.superset, sp.superset))) }#HYBRID.PC.HEURISTIC hybrid.pc.nbr.search = function(x, data, nodes, alpha, B, whitelist, blacklist, test, max.sx = ncol(data), complete, debug = FALSE, start = start, looking.for = NULL) { mb = ia.fdr.markov.blanket(x, data = data, nodes = nodes, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, start = start, test = test, max.sx = max.sx, complete = complete, debug = debug) # if the node is not in the markov blanket it cannot be a neighbour either. if (!is.null(looking.for) && (looking.for %!in% mb)) return(NULL) pc = hybrid.pc.filter(x, pc.superset = mb, sp.superset = NULL, data = data, alpha = alpha, B = B, whitelist = whitelist, blacklist = blacklist, test = test, max.sx = max.sx, complete = complete, debug = debug) return(pc) }#HYBRID.PC.NBR.SEARCH hybrid.pc.de.pcs = function(x, data, nodes, alpha, B, whitelist, blacklist, test, complete, debug = FALSE) { whitelisted = nodes[sapply(nodes, function(y) { is.whitelisted(whitelist, c(x, y), either = TRUE) })] blacklisted = nodes[sapply(nodes, function(y) { is.blacklisted(blacklist, c(x, y), both = TRUE) })] if (debug) { cat("----------------------------------------------------------------\n") cat("* learning the parents and children superset of", x, ".\n") }#THEN if (debug) cat(" * nodes to be tested for inclusion: '", nodes[nodes %!in% x], "'.\n") # all nodes are candidates initially, except for those whose status is already # determined (from whitelist and blacklist). to.check = setdiff(nodes, c(x, whitelisted, blacklisted)) # exclude nodes that are marginally independent from the target. association = indep.test(to.check, x, sx = character(0), data = data, test = test, B = B, alpha = alpha, complete = complete) to.keep = names(association[association <= alpha]) to.drop = names(association[association > alpha]) pvalues = association[to.keep] if (debug) { cat(" * checking nodes for association.\n") if (length(to.keep) > 0) { cat(" * nodes that are still candidates for inclusion.\n") sapply(to.keep, function(x) { cat(" >", x, "has p-value", association[x], ".\n")}) }#THEN if (length(to.drop) > 0) { cat(" * nodes that will be disregarded from now on.\n") sapply(to.drop, function(x) { cat(" >", x, "has p-value", association[x], ".\n")}) }#THEN }#THEN # sort the candidates in order of increasing association, so that nodes with # weak associations are checked for exclusion first. pvalues = sort(pvalues, decreasing = TRUE) to.check = names(pvalues) fixed = whitelisted if (debug) cat(" * nodes to be tested for exclusion: '", to.check, "'.\n") pvalues = structure(c(rep(0, length(fixed)), pvalues), names = c(fixed, names(pvalues))) dsep.set = list() # if there is only a single node left to check, it would be conditional on # the empty set which would just repeat an earlier test; nothing left to do. if (length(to.check) == 1) return(structure(pvalues, dsep.set = dsep.set)) # exlcude nodes that are independent given a single conditioning node. for (node in to.check) { # sort the candidates in order of decreasing association, so that nodes with # strong associations are checked first. to.check.against = setdiff(names(sort(pvalues, decreasing = FALSE)), node) if (length(to.check.against) == 0) next a = allsubs.test(x = x, y = node, sx = to.check.against, min = 1, max = 1, data = data, test = test, alpha = alpha, B = B, complete = complete, debug = debug) if (a["p.value"] > alpha) { pvalues = pvalues[names(pvalues) != node] dsep.set[[node]] = attr(a, "dsep.set") }#THEN else { pvalues[node] = max(pvalues[node], a["max.p.value"]) }#ELSE }#FOR return(structure(pvalues, dsep.set = dsep.set)) }#HYBRID.PC.DE.PCS hybrid.pc.de.sps = function(x, data, nodes, pc.superset, dsep.set, alpha, B, test, max.sx, complete, debug = FALSE) { spouses.superset = character(0) if (debug) { cat("----------------------------------------------------------------\n") cat("* learning the spouses superset of", x, ".\n") cat(" * nodes still to be tested for inclusion:", nodes[nodes %!in% c(x, pc.superset)], "\n") }#THEN for (cpc in pc.superset) { pvalues = numeric(0) # forward selection. for (y in setdiff(nodes, c(x, pc.superset))) { # if the candidate node d-separates the current node from a node that is # not in the superset, it is potentially in the markov blanket and thus a # potential spouse. if (cpc %in% dsep.set[[y]]) next # skip tests whose conditioning sets are too large (assuming independence # means not adding the node to the superset). if (length(c(dsep.set[[y]], cpc)) > max.sx) next if (debug) cat(" > checking node", y, "for inclusion.\n") a = indep.test(x = x, y = y, sx = c(dsep.set[[y]], cpc), data = data, test = test, B = B, alpha = alpha, complete = complete) if (debug) cat(" > node", x, "is", ifelse(a > alpha, "independent from", "dependent on"), y, "given", c(dsep.set[[y]], cpc), " ( p-value:", a, ").\n") if (a <= alpha) { pvalues[y] = a if (debug) cat(" @ node", y, "added to the spouses superset.\n") }#THEN }#FOR # sort the candidates in order of increasing association, so that nodes with # weak associations are checked for exclusion first. pvalues = sort(pvalues, decreasing = TRUE) # backward selection, to remove false positives. for (y in names(pvalues)) { sx = setdiff(names(pvalues), y) if (length(sx) == 0) next if (debug) cat(" > checking node", y, "for removal.\n") a = allsubs.test(x = x, y = y, sx = sx, fixed = cpc, data = data, test = test, B = B, alpha = alpha, complete = complete, min = 1, max = 1, debug = debug) if (a["p.value"] > alpha) { pvalues = pvalues[names(pvalues) != y] if (debug) cat(" @ node", y, "removed from the spouses superset.\n") }#THEN }#FOR spouses.superset = union(spouses.superset, names(pvalues)) }#FOR return(spouses.superset) }#HYBRID.PC.DE.SPS hybrid.pc.filter = function(x, pc.superset, sp.superset, data, alpha, B = B, whitelist, blacklist, test, max.sx, complete, debug = FALSE) { nodes = names(data) mb.superset = c(pc.superset, sp.superset) whitelisted = nodes[sapply(nodes, function(y) { is.whitelisted(whitelist, c(x, y), either = TRUE) })] blacklisted = nodes[sapply(nodes, function(y) { is.blacklisted(blacklist, c(x, y), both = TRUE) })] if (debug) { cat("----------------------------------------------------------------\n") cat("* filtering parents and children of", x, ".\n") cat(" * blacklisted nodes: '", blacklisted, "'\n") cat(" * whitelisted nodes: '", whitelisted, "'\n") cat(" * starting with neighbourhood superset: '", pc.superset, "'\n") cat(" * with spouses superset: '", sp.superset, "'\n") }#THEN # make sure blacklisted nodes are not included, and add whitelisted nodes. pc.superset = union(setdiff(pc.superset, blacklisted), whitelisted) mb.superset = union(mb.superset, whitelisted) # if the markov blanket is empty, the neighbourhood is empty as well. if (length(mb.superset) == 0) return(character(0)) nbr = function(node) { a = allsubs.test(x = x, y = node, sx = setdiff(mb.superset, node), data = data, test = test, B = B, alpha = alpha, max = max.sx, complete = complete, debug = debug) return(as.logical(a["p.value"] < alpha)) }#NBR # do not even try to remove whitelisted nodes. pc = names(which(sapply(setdiff(pc.superset, whitelisted), nbr))) # make sure whitelisted nodes are always included. pc = unique(c(pc, whitelisted)) return(pc) }#HYBRID.PC.FILTER
# Various objects have attributes that are worth preserving. This does that. modify_object <- function(object, new_object) { x_attr <- attributes(object) x_class <- class(object) attrs <- names(x_attr) attrs <- attrs[!(attrs %in% c("class", "names", "dim", "dimnames", "row.names"))] for(obj in attrs) { attr(new_object, obj) <- x_attr[[obj]] } class(new_object) <- x_class new_object }
/R/modify_object.R
no_license
byandell/intermediate
R
false
false
410
r
# Various objects have attributes that are worth preserving. This does that. modify_object <- function(object, new_object) { x_attr <- attributes(object) x_class <- class(object) attrs <- names(x_attr) attrs <- attrs[!(attrs %in% c("class", "names", "dim", "dimnames", "row.names"))] for(obj in attrs) { attr(new_object, obj) <- x_attr[[obj]] } class(new_object) <- x_class new_object }
library(limma) library(stats) library(VennDiagram) library(gtools) library(ggplot2) setwd('/group/stranger-lab/immvar/meta') load('/group/stranger-lab/immvar_rep/mappings/annot.Robj') cd4.meta <- read.table(file='cd4_meta1.txt', header=T) cd14.meta <- read.table(file='cd14_meta1.txt', header=T) cd4_gene_counts <- table(annots[as.character(cd4.meta$MarkerName),"chr"]) cd14_gene_counts <- table(annots[as.character(cd14.meta$MarkerName),"chr"]) cd4.meta$Q.value <- p.adjust(cd4.meta$P.value, method="BH") cd4.meta <- cd4.meta[order(cd4.meta$Q.value),] cd14.meta$Q.value <- p.adjust(cd14.meta$P.value, method="BH") cd14.meta <- cd14.meta[order(cd14.meta$Q.value),] meta_sig_cd4_bh <- cd4.meta[cd4.meta$Q.value<=0.05, ] meta_sig_cd4_bh <- meta_sig_cd4_bh[order(meta_sig_cd4_bh$P.value),] rownames(meta_sig_cd4_bh) <- as.character(meta_sig_cd4_bh$MarkerName) cd4_meta_percent <- table(annots[rownames(meta_sig_cd4_bh), "chr"]) / cd4_gene_counts cd4_gene_pers <- data.frame(chr_name=names(cd4_meta_percent), per = as.numeric(cd4_meta_percent)) g <- ggplot(cd4_gene_pers, aes(x=chr_name, y=per)) pdf(file='/group/stranger-lab/czysz/cd4.meta.locs.pdf') g + geom_bar(stat="identity") dev.off() meta_sig_cd14_bh <- cd14.meta[cd14.meta$Q.value<=0.05, ] meta_sig_cd14_bh <- meta_sig_cd14_bh[order(meta_sig_cd14_bh$P.value),] rownames(meta_sig_cd14_bh) <- as.character(meta_sig_cd14_bh$MarkerName) cd14_meta_percent <- table(annots[rownames(meta_sig_cd14_bh), "chr"]) / cd14_gene_counts cd14_gene_pers <- data.frame(chr=mixedorder(names(cd14_meta_percent)), chr_name = names(cd14_meta_percent), per = as.numeric(cd14_meta_percent)) setwd('/group/stranger-lab/immvar_data') cd14.fits<-list() cd4.fits<-list() for ( pop in c('Caucasian', 'African-American', 'Asian')) { for ( cell in c('CD14', 'CD4') ) { if (cell=='CD14') { load(paste('fit',pop, cell, 'Robj', sep='.')) eb.fit$Q.value <- p.adjust(eb.fit$p.value, method='fdr') cd14.fits[[pop]]<-data.frame(eb.fit) } else { load(paste('fit',pop, cell, 'Robj', sep='.')) eb.fit$Q.value <- p.adjust(eb.fit$p.value, method='fdr') cd4.fits[[pop]]<-data.frame(eb.fit) } } } # CD14 Venn Diagram cd14.venn <- list(cau=rownames(subset(cd14.fits[[1]], Q.value<0.05)), afr=rownames(subset(cd14.fits[[2]], Q.value<0.05)), asn=rownames(subset(cd14.fits[[3]], Q.value<0.05))) cd14.shared <- intersect(cd14.venn[[1]], intersect(cd14.venn[[2]], cd14.venn[[3]])) print(table(annots[cd14.shared, "chr"])) venn.diagram(cd14.venn, filename='/group/stranger-lab/czysz/cd14_separate_venn.tiff', fontfamily="Helvetica", main.fontfamily="Helvetica", cat.fontfamily="Helvetica", sub.fontfamily="Helvetica", fill=topo.colors(3), main="CD14 - Separate VennDiagram", sub.cex=1.5, width=10, height=10, units="in") # CD4 cd4.venn <- list(cau=rownames(subset(cd4.fits[[1]], Q.value<0.05)), afr=rownames(subset(cd4.fits[[2]], Q.value<0.05)), asn=rownames(subset(cd4.fits[[3]], Q.value<0.05))) cd4.shared <- intersect(cd4.venn[[1]], intersect(cd4.venn[[2]], cd4.venn[[3]])) print(table(annots[cd4.shared, "chr"])) venn.diagram(cd4.venn, filename='/group/stranger-lab/czysz/cd4_separate_venn.tiff', fontfamily="Helvetica", main.fontfamily="Helvetica", cat.fontfamily="Helvetica", sub.fontfamily="Helvetica", fill=topo.colors(3), main="CD4 - Separate VennDiagram", sub.cex=1.5, width=10, height=10, units="in")
/meta/analyze_sep_meta.R
permissive
cczysz/immvar
R
false
false
3,376
r
library(limma) library(stats) library(VennDiagram) library(gtools) library(ggplot2) setwd('/group/stranger-lab/immvar/meta') load('/group/stranger-lab/immvar_rep/mappings/annot.Robj') cd4.meta <- read.table(file='cd4_meta1.txt', header=T) cd14.meta <- read.table(file='cd14_meta1.txt', header=T) cd4_gene_counts <- table(annots[as.character(cd4.meta$MarkerName),"chr"]) cd14_gene_counts <- table(annots[as.character(cd14.meta$MarkerName),"chr"]) cd4.meta$Q.value <- p.adjust(cd4.meta$P.value, method="BH") cd4.meta <- cd4.meta[order(cd4.meta$Q.value),] cd14.meta$Q.value <- p.adjust(cd14.meta$P.value, method="BH") cd14.meta <- cd14.meta[order(cd14.meta$Q.value),] meta_sig_cd4_bh <- cd4.meta[cd4.meta$Q.value<=0.05, ] meta_sig_cd4_bh <- meta_sig_cd4_bh[order(meta_sig_cd4_bh$P.value),] rownames(meta_sig_cd4_bh) <- as.character(meta_sig_cd4_bh$MarkerName) cd4_meta_percent <- table(annots[rownames(meta_sig_cd4_bh), "chr"]) / cd4_gene_counts cd4_gene_pers <- data.frame(chr_name=names(cd4_meta_percent), per = as.numeric(cd4_meta_percent)) g <- ggplot(cd4_gene_pers, aes(x=chr_name, y=per)) pdf(file='/group/stranger-lab/czysz/cd4.meta.locs.pdf') g + geom_bar(stat="identity") dev.off() meta_sig_cd14_bh <- cd14.meta[cd14.meta$Q.value<=0.05, ] meta_sig_cd14_bh <- meta_sig_cd14_bh[order(meta_sig_cd14_bh$P.value),] rownames(meta_sig_cd14_bh) <- as.character(meta_sig_cd14_bh$MarkerName) cd14_meta_percent <- table(annots[rownames(meta_sig_cd14_bh), "chr"]) / cd14_gene_counts cd14_gene_pers <- data.frame(chr=mixedorder(names(cd14_meta_percent)), chr_name = names(cd14_meta_percent), per = as.numeric(cd14_meta_percent)) setwd('/group/stranger-lab/immvar_data') cd14.fits<-list() cd4.fits<-list() for ( pop in c('Caucasian', 'African-American', 'Asian')) { for ( cell in c('CD14', 'CD4') ) { if (cell=='CD14') { load(paste('fit',pop, cell, 'Robj', sep='.')) eb.fit$Q.value <- p.adjust(eb.fit$p.value, method='fdr') cd14.fits[[pop]]<-data.frame(eb.fit) } else { load(paste('fit',pop, cell, 'Robj', sep='.')) eb.fit$Q.value <- p.adjust(eb.fit$p.value, method='fdr') cd4.fits[[pop]]<-data.frame(eb.fit) } } } # CD14 Venn Diagram cd14.venn <- list(cau=rownames(subset(cd14.fits[[1]], Q.value<0.05)), afr=rownames(subset(cd14.fits[[2]], Q.value<0.05)), asn=rownames(subset(cd14.fits[[3]], Q.value<0.05))) cd14.shared <- intersect(cd14.venn[[1]], intersect(cd14.venn[[2]], cd14.venn[[3]])) print(table(annots[cd14.shared, "chr"])) venn.diagram(cd14.venn, filename='/group/stranger-lab/czysz/cd14_separate_venn.tiff', fontfamily="Helvetica", main.fontfamily="Helvetica", cat.fontfamily="Helvetica", sub.fontfamily="Helvetica", fill=topo.colors(3), main="CD14 - Separate VennDiagram", sub.cex=1.5, width=10, height=10, units="in") # CD4 cd4.venn <- list(cau=rownames(subset(cd4.fits[[1]], Q.value<0.05)), afr=rownames(subset(cd4.fits[[2]], Q.value<0.05)), asn=rownames(subset(cd4.fits[[3]], Q.value<0.05))) cd4.shared <- intersect(cd4.venn[[1]], intersect(cd4.venn[[2]], cd4.venn[[3]])) print(table(annots[cd4.shared, "chr"])) venn.diagram(cd4.venn, filename='/group/stranger-lab/czysz/cd4_separate_venn.tiff', fontfamily="Helvetica", main.fontfamily="Helvetica", cat.fontfamily="Helvetica", sub.fontfamily="Helvetica", fill=topo.colors(3), main="CD4 - Separate VennDiagram", sub.cex=1.5, width=10, height=10, units="in")
# Read the BPRS data BPRS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/BPRS.txt", sep =" ", header = T) # Look at the (column) names of BPRS names(BPRS) # Look at the structure of BPRS str(BPRS) # Print out summaries of the variables summary(BPRS) # The data BPRS is available # Access the packages dplyr and tidyr library(dplyr) library(tidyr) # Factor treatment & subject BPRS$treatment <- factor(BPRS$treatment) BPRS$subject <- factor(BPRS$subject) # Convert to long form BPRSL <- BPRS %>% gather(key = weeks, value = bprs, -treatment, -subject) # Extract the week number BPRSL <- BPRSL %>% mutate(week = as.integer(substr(weeks,5,5))) # Take a glimpse at the BPRSL data glimpse(BPRSL) #Access the package ggplot2 library(ggplot2) # Draw the plot ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) + geom_line() + scale_linetype_manual(values = rep(1:10, times=4)) + facet_grid(. ~ treatment, labeller = label_both) + theme(legend.position = "none") + scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs))) # dplyr, tidyr and ggplot2 packages and BPRSL are available # Standardise the variable bprs BPRSL <- BPRSL %>% group_by(week) %>% mutate(stdbprs = (bprs - mean(bprs))/sd(bprs) ) %>% ungroup() # Glimpse the data glimpse(BPRSL) # Plot again with the standardised bprs ggplot(BPRSL, aes(x = week, y = stdbprs, linetype = subject)) + geom_line() + scale_linetype_manual(values = rep(1:10, times=4)) + facet_grid(. ~ treatment, labeller = label_both) + scale_y_continuous(name = "standardized bprs") # dplyr, tidyr & ggplot2 packages and BPRSL are available # Number of weeks, baseline (week 0) included n <- BPRSL$week %>% unique() %>% length() # Summary data with mean and standard error of bprs by treatment and week BPRSS <- BPRSL %>% group_by(treatment, week) %>% summarise( mean = mean(bprs), se = sd(bprs)/sqrt(n) ) %>% ungroup() # Glimpse the data glimpse(BPRSS) # A very nice picture! i think going to be useful. # Plot the mean profiles ggplot(BPRSS, aes(x = week, y = mean, linetype = treatment, shape = treatment)) + geom_line() + scale_linetype_manual(values = c(1,2)) + geom_point(size=3) + scale_shape_manual(values = c(1,2)) + geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) + theme(legend.position = c(0.8,0.8)) + scale_y_continuous(name = "mean(bprs) +/- se(bprs)") # dplyr, tidyr & ggplot2 packages and BPRSL are available # Create a summary data by treatment and subject with mean as the summary variable (ignoring baseline week 0). BPRSL8S <- BPRSL %>% filter(week > 0) %>% group_by(treatment, subject) %>% summarise( mean=mean(bprs) ) %>% ungroup() # Glimpse the data glimpse(BPRSL8S) # Draw a boxplot of the mean versus treatment ggplot(BPRSL8S, aes(x = treatment, y = mean)) + geom_boxplot() + stat_summary(fun.y = "mean", geom = "point", shape=23, size=4, fill = "white") + scale_y_continuous(name = "mean(bprs), weeks 1-8") # Create a new data by filtering the outlier and adjust the ggplot code the draw the plot again with the new data BPRSL8S1 <- BPRSL8S %>% filter(mean < 65) # dplyr, tidyr & ggplot2 packages and BPRSL8S & BPRSL8S1 data are available # Perform a two-sample t-test t.test(mean ~ treatment, data = BPRSL8S1, var.equal = TRUE) # Add the baseline from the original data as a new variable to the summary data BPRSL8S2 <- BPRSL8S %>% mutate(baseline = BPRS$week0) # Fit the linear model with the mean as the response fit <- lm(mean ~ baseline + treatment, data = BPRSL8S2) summary(fit) # Compute the analysis of variance table for the fitted model with anova() # this shows about the same as summary(fit) anova(fit) ######################################################## # read the RATS data RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", header = TRUE, sep = '\t') # Factor variables ID and Group RATS$ID <- factor(RATS$ID) RATS$Group <- factor(RATS$Group) # Glimpse the data glimpse(RATS) # dplyr, tidyr and RATS are available # Convert data to long form str(RATS) RATSL <- RATS %>% gather(key = WD, value = Weight, -ID, -Group) %>% mutate(Time = as.integer(substr(WD,3,4))) # Glimpse the data glimpse(RATSL) # dplyr, tidyr and RATSL are available # Check the dimensions of the data dim(RATSL) # Plot the RATSL data ggplot(RATSL, aes(x = Time, y = Weight, group = ID)) + geom_line() # dplyr, tidyr, RATS and RATSL are available # create a regression model RATS_reg RATS_reg <- lm(Weight ~ Time + Group, data = RATSL) # print out a summary of the model summary(RATS_reg) # dplyr, tidyr, RATS and RATSL are available # access library lme4 library(lme4) # Create a random intercept model RATS_ref <- lmer(Weight ~ Time + Group + (1 | ID), data = RATSL, REML = FALSE) # Print the summary of the model # dplyr, tidyr, lme4, ggplot2, RATS and RATSL are available # create a random intercept and random slope model RATS_ref1 <- lmer(Weight ~ Time + Group + (Time | ID), data = RATSL, REML = FALSE) # print a summary of the model summary(RATS_ref1) # perform an ANOVA test on the two models anova(RATS_ref1, RATS_ref) # dplyr, tidyr, lme4, ggplot2, RATS and RATSL are available # create a random intercept and random slope model with the interaction RATS_ref2 <- lmer(Weight ~ Group + Time + (Time|ID) +Time*Group, REML= FALSE, data= RATSL) # print a summary of the model summary(RATS_ref2) # perform an ANOVA test on the two models anova(RATS_ref2, RATS_ref1) # draw the plot of RATSL with the observed Weight values ggplot(RATSL, aes(x = Time, y = Weight, group = ID)) + geom_line(aes(linetype = Group)) + scale_x_continuous(name = "Time (days)", breaks = seq(0, 60, 20)) + scale_y_continuous(name = "Observed weight (grams)") + theme(legend.position = "top") # Create a vector of the fitted values Fitted <- fitted(RATS_ref2) help(fitted) # Create a new column fitted to RATSL RATSL <- RATSL %>% mutate(Fitted) # draw the plot of RATSL with the Fitted values of weight ggplot(RATSL, aes(x = Time, y = Fitted, group = ID)) + geom_line(aes(linetype = Group)) + scale_x_continuous(name = "Time (days)", breaks = seq(0, 60, 20)) + scale_y_continuous(name = "Fitted weight (grams)") + theme(legend.position = "top")
/week6_Datacamp_lmm.R
no_license
atiitu/IODS-project
R
false
false
6,363
r
# Read the BPRS data BPRS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/BPRS.txt", sep =" ", header = T) # Look at the (column) names of BPRS names(BPRS) # Look at the structure of BPRS str(BPRS) # Print out summaries of the variables summary(BPRS) # The data BPRS is available # Access the packages dplyr and tidyr library(dplyr) library(tidyr) # Factor treatment & subject BPRS$treatment <- factor(BPRS$treatment) BPRS$subject <- factor(BPRS$subject) # Convert to long form BPRSL <- BPRS %>% gather(key = weeks, value = bprs, -treatment, -subject) # Extract the week number BPRSL <- BPRSL %>% mutate(week = as.integer(substr(weeks,5,5))) # Take a glimpse at the BPRSL data glimpse(BPRSL) #Access the package ggplot2 library(ggplot2) # Draw the plot ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) + geom_line() + scale_linetype_manual(values = rep(1:10, times=4)) + facet_grid(. ~ treatment, labeller = label_both) + theme(legend.position = "none") + scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs))) # dplyr, tidyr and ggplot2 packages and BPRSL are available # Standardise the variable bprs BPRSL <- BPRSL %>% group_by(week) %>% mutate(stdbprs = (bprs - mean(bprs))/sd(bprs) ) %>% ungroup() # Glimpse the data glimpse(BPRSL) # Plot again with the standardised bprs ggplot(BPRSL, aes(x = week, y = stdbprs, linetype = subject)) + geom_line() + scale_linetype_manual(values = rep(1:10, times=4)) + facet_grid(. ~ treatment, labeller = label_both) + scale_y_continuous(name = "standardized bprs") # dplyr, tidyr & ggplot2 packages and BPRSL are available # Number of weeks, baseline (week 0) included n <- BPRSL$week %>% unique() %>% length() # Summary data with mean and standard error of bprs by treatment and week BPRSS <- BPRSL %>% group_by(treatment, week) %>% summarise( mean = mean(bprs), se = sd(bprs)/sqrt(n) ) %>% ungroup() # Glimpse the data glimpse(BPRSS) # A very nice picture! i think going to be useful. # Plot the mean profiles ggplot(BPRSS, aes(x = week, y = mean, linetype = treatment, shape = treatment)) + geom_line() + scale_linetype_manual(values = c(1,2)) + geom_point(size=3) + scale_shape_manual(values = c(1,2)) + geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) + theme(legend.position = c(0.8,0.8)) + scale_y_continuous(name = "mean(bprs) +/- se(bprs)") # dplyr, tidyr & ggplot2 packages and BPRSL are available # Create a summary data by treatment and subject with mean as the summary variable (ignoring baseline week 0). BPRSL8S <- BPRSL %>% filter(week > 0) %>% group_by(treatment, subject) %>% summarise( mean=mean(bprs) ) %>% ungroup() # Glimpse the data glimpse(BPRSL8S) # Draw a boxplot of the mean versus treatment ggplot(BPRSL8S, aes(x = treatment, y = mean)) + geom_boxplot() + stat_summary(fun.y = "mean", geom = "point", shape=23, size=4, fill = "white") + scale_y_continuous(name = "mean(bprs), weeks 1-8") # Create a new data by filtering the outlier and adjust the ggplot code the draw the plot again with the new data BPRSL8S1 <- BPRSL8S %>% filter(mean < 65) # dplyr, tidyr & ggplot2 packages and BPRSL8S & BPRSL8S1 data are available # Perform a two-sample t-test t.test(mean ~ treatment, data = BPRSL8S1, var.equal = TRUE) # Add the baseline from the original data as a new variable to the summary data BPRSL8S2 <- BPRSL8S %>% mutate(baseline = BPRS$week0) # Fit the linear model with the mean as the response fit <- lm(mean ~ baseline + treatment, data = BPRSL8S2) summary(fit) # Compute the analysis of variance table for the fitted model with anova() # this shows about the same as summary(fit) anova(fit) ######################################################## # read the RATS data RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", header = TRUE, sep = '\t') # Factor variables ID and Group RATS$ID <- factor(RATS$ID) RATS$Group <- factor(RATS$Group) # Glimpse the data glimpse(RATS) # dplyr, tidyr and RATS are available # Convert data to long form str(RATS) RATSL <- RATS %>% gather(key = WD, value = Weight, -ID, -Group) %>% mutate(Time = as.integer(substr(WD,3,4))) # Glimpse the data glimpse(RATSL) # dplyr, tidyr and RATSL are available # Check the dimensions of the data dim(RATSL) # Plot the RATSL data ggplot(RATSL, aes(x = Time, y = Weight, group = ID)) + geom_line() # dplyr, tidyr, RATS and RATSL are available # create a regression model RATS_reg RATS_reg <- lm(Weight ~ Time + Group, data = RATSL) # print out a summary of the model summary(RATS_reg) # dplyr, tidyr, RATS and RATSL are available # access library lme4 library(lme4) # Create a random intercept model RATS_ref <- lmer(Weight ~ Time + Group + (1 | ID), data = RATSL, REML = FALSE) # Print the summary of the model # dplyr, tidyr, lme4, ggplot2, RATS and RATSL are available # create a random intercept and random slope model RATS_ref1 <- lmer(Weight ~ Time + Group + (Time | ID), data = RATSL, REML = FALSE) # print a summary of the model summary(RATS_ref1) # perform an ANOVA test on the two models anova(RATS_ref1, RATS_ref) # dplyr, tidyr, lme4, ggplot2, RATS and RATSL are available # create a random intercept and random slope model with the interaction RATS_ref2 <- lmer(Weight ~ Group + Time + (Time|ID) +Time*Group, REML= FALSE, data= RATSL) # print a summary of the model summary(RATS_ref2) # perform an ANOVA test on the two models anova(RATS_ref2, RATS_ref1) # draw the plot of RATSL with the observed Weight values ggplot(RATSL, aes(x = Time, y = Weight, group = ID)) + geom_line(aes(linetype = Group)) + scale_x_continuous(name = "Time (days)", breaks = seq(0, 60, 20)) + scale_y_continuous(name = "Observed weight (grams)") + theme(legend.position = "top") # Create a vector of the fitted values Fitted <- fitted(RATS_ref2) help(fitted) # Create a new column fitted to RATSL RATSL <- RATSL %>% mutate(Fitted) # draw the plot of RATSL with the Fitted values of weight ggplot(RATSL, aes(x = Time, y = Fitted, group = ID)) + geom_line(aes(linetype = Group)) + scale_x_continuous(name = "Time (days)", breaks = seq(0, 60, 20)) + scale_y_continuous(name = "Fitted weight (grams)") + theme(legend.position = "top")
#' --- #' title: test Fox forces data #' --- library("tidyverse") library("stringr") library("assertthat") fox_forces <- read_csv("data/fox_forces.csv") %>% mutate(start_date = as.Date(start_date), end_date = as.Date(end_date)) # Check validity of IDs assert_that(length(unique(fox_forces$battle_id)) == nrow(fox_forces)) assert_that(all(str_detect(fox_forces$battle_id, "[UC]\\d+[A-Z]?"))) # belligerents BELLIGERENTS <- c("US", "Confederate") assert_that(all(!is.na(fox_forces$belligerent))) assert_that(all(fox_forces$belligerent %in% BELLIGERENTS)) # states STATES <- c("AR", "DC", "FL", "GA", "KY", "LA", "MD", "MO", "MS", "NC", "PA", "SC", "TN", "VA", "WV") assert_that(all(!is.na(fox_forces$state))) assert_that(all(fox_forces$state %in% STATES)) # battle names assert_that(all(!is.na(fox_forces$battle_name))) assert_that(is.character(fox_forces$battle_name)) # dates MIN_DATE <- as.Date("1861-04-10") MAX_DATE <- as.Date("1865-04-17") MAX_DURATION <- 119 assert_that(all(!is.na(fox_forces$start_date))) assert_that(all(!is.na(fox_forces$end_date))) assert_that(!nrow(filter(fox_forces, start_date < MIN_DATE))) # assert_that(!nrow(filter(fox_forces, end_date > MAX_DATE))) assert_that(!nrow(filter(fox_forces, end_date < start_date))) # longest entry is 119 days (Atlanta Campaign) assert_that(!nrow(filter(fox_forces, as.integer(end_date - start_date) <= UQ(MAX_DURATION)))) # killed MAX_KILLED <- 4423 assert_that(min(fox_forces$killed, nr.rm = TRUE) >= 0) assert_that(max(fox_forces$killed, na.rm = TRUE) <= MAX_KILLED) # wounded # Number wounded is so large because of the Atlanta Campaign MAX_WOUNDED <- 22822 assert_that(min(fox_forces$wounded, nr.rm = TRUE) >= 0) assert_that(max(fox_forces$wounded, na.rm = TRUE) <= MAX_WOUNDED) # killed MAX_MISSING <- 13829 assert_that(min(fox_forces$missing, na.rm = TRUE) >= 0) assert_that(max(fox_forces$missing, na.rm = TRUE) <= MAX_MISSING) # total casualties MAX_CASUALTIES <- 31687 assert_that(min(fox_forces$casualties, nr.rm = TRUE) >= 0) assert_that(max(fox_forces$casualties, na.rm = TRUE) <= MAX_CASUALTIES)
/tests/test_fox_forces.R
permissive
jrnold/acw_battle_data
R
false
false
2,167
r
#' --- #' title: test Fox forces data #' --- library("tidyverse") library("stringr") library("assertthat") fox_forces <- read_csv("data/fox_forces.csv") %>% mutate(start_date = as.Date(start_date), end_date = as.Date(end_date)) # Check validity of IDs assert_that(length(unique(fox_forces$battle_id)) == nrow(fox_forces)) assert_that(all(str_detect(fox_forces$battle_id, "[UC]\\d+[A-Z]?"))) # belligerents BELLIGERENTS <- c("US", "Confederate") assert_that(all(!is.na(fox_forces$belligerent))) assert_that(all(fox_forces$belligerent %in% BELLIGERENTS)) # states STATES <- c("AR", "DC", "FL", "GA", "KY", "LA", "MD", "MO", "MS", "NC", "PA", "SC", "TN", "VA", "WV") assert_that(all(!is.na(fox_forces$state))) assert_that(all(fox_forces$state %in% STATES)) # battle names assert_that(all(!is.na(fox_forces$battle_name))) assert_that(is.character(fox_forces$battle_name)) # dates MIN_DATE <- as.Date("1861-04-10") MAX_DATE <- as.Date("1865-04-17") MAX_DURATION <- 119 assert_that(all(!is.na(fox_forces$start_date))) assert_that(all(!is.na(fox_forces$end_date))) assert_that(!nrow(filter(fox_forces, start_date < MIN_DATE))) # assert_that(!nrow(filter(fox_forces, end_date > MAX_DATE))) assert_that(!nrow(filter(fox_forces, end_date < start_date))) # longest entry is 119 days (Atlanta Campaign) assert_that(!nrow(filter(fox_forces, as.integer(end_date - start_date) <= UQ(MAX_DURATION)))) # killed MAX_KILLED <- 4423 assert_that(min(fox_forces$killed, nr.rm = TRUE) >= 0) assert_that(max(fox_forces$killed, na.rm = TRUE) <= MAX_KILLED) # wounded # Number wounded is so large because of the Atlanta Campaign MAX_WOUNDED <- 22822 assert_that(min(fox_forces$wounded, nr.rm = TRUE) >= 0) assert_that(max(fox_forces$wounded, na.rm = TRUE) <= MAX_WOUNDED) # killed MAX_MISSING <- 13829 assert_that(min(fox_forces$missing, na.rm = TRUE) >= 0) assert_that(max(fox_forces$missing, na.rm = TRUE) <= MAX_MISSING) # total casualties MAX_CASUALTIES <- 31687 assert_that(min(fox_forces$casualties, nr.rm = TRUE) >= 0) assert_that(max(fox_forces$casualties, na.rm = TRUE) <= MAX_CASUALTIES)
testlist <- list(bytes1 = c(892679477L, 3487029L, 838860799L, -1L, -8585216L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), pmutation = 0) result <- do.call(mcga:::ByteCodeMutation,testlist) str(result)
/mcga/inst/testfiles/ByteCodeMutation/libFuzzer_ByteCodeMutation/ByteCodeMutation_valgrind_files/1612802295-test.R
no_license
akhikolla/updatedatatype-list3
R
false
false
328
r
testlist <- list(bytes1 = c(892679477L, 3487029L, 838860799L, -1L, -8585216L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), pmutation = 0) result <- do.call(mcga:::ByteCodeMutation,testlist) str(result)
## This R script takes the household power consumption data that you have, ## plots a histogram of the global active power in kilowatts for Feb 01 and 02 2007, ## and saves this histogram to a PNG file. ## reads household power consumption to a csv file power <- read.csv("household_power_consumption.txt", sep=";") ## converts Date column to the right format power$Date <- as.Date(power$Date, format="%d/%m/%Y") ## subsets the rows for which the date is 2007-02-01 or 2007-02-02 powersub <- power[(power$Date == "2007-02-01" | power$Date == "2007-02-02"), ] ## Turns the column Global_active_power into numeric powersub$Global_active_power <- as.numeric(powersub$Global_active_power) ## initiates dplyr library library(dplyr) ## creates a new column called Global_active_power_kilowatts that is the global active power in kilowatts (divided by 1000) powersub <- mutate(powersub, Global_active_power_kilowatts = Global_active_power/1000) ## draws the histogram for you and saves it to a PNG file called plot1.png png("plot1.png") hist(powersub$Global_active_power_kilowatts, xlab="Global Active Power (kilowatts)", main="Global Active Power", col = "red") dev.off()
/plot1.R
no_license
gracechua/ExData_Plotting1
R
false
false
1,182
r
## This R script takes the household power consumption data that you have, ## plots a histogram of the global active power in kilowatts for Feb 01 and 02 2007, ## and saves this histogram to a PNG file. ## reads household power consumption to a csv file power <- read.csv("household_power_consumption.txt", sep=";") ## converts Date column to the right format power$Date <- as.Date(power$Date, format="%d/%m/%Y") ## subsets the rows for which the date is 2007-02-01 or 2007-02-02 powersub <- power[(power$Date == "2007-02-01" | power$Date == "2007-02-02"), ] ## Turns the column Global_active_power into numeric powersub$Global_active_power <- as.numeric(powersub$Global_active_power) ## initiates dplyr library library(dplyr) ## creates a new column called Global_active_power_kilowatts that is the global active power in kilowatts (divided by 1000) powersub <- mutate(powersub, Global_active_power_kilowatts = Global_active_power/1000) ## draws the histogram for you and saves it to a PNG file called plot1.png png("plot1.png") hist(powersub$Global_active_power_kilowatts, xlab="Global Active Power (kilowatts)", main="Global Active Power", col = "red") dev.off()
#' Standardise the column headers in the Summary Statistics files #' #' Use a reference data table of common column header names (stored in sumstatsColHeaders.rda) convert them to a standard set, i.e. chromosome --> CHR #' #' This function does not check that all the required column headers are present #' #' The amended header is written directly back into the file #' #' @param path Filepath for the summary statistics file #' #' @return The amended column headers (also the column headers will be written directly into the summary statistics file) #' #' @examples #' col_headers = standardise.sumstats.column.headers("~/Downloads/202040.assoc.tsv") #' #' @export standardise.sumstats.column.headers.linux <- function(path){ # Check the sumstats file exists if(!file.exists(path)){stop("Path to GWAS sumstats is not valid")} # Read in the first line of the file only con <- file(path,"r") ; first_line <- readLines(con,n=1) ; close(con) column_headers = strsplit(first_line,"\t")[[1]] # Show to the user what the header is print("First line of summary statistics file: ") print(first_line) print(column_headers) # Amend the column headers based on a data table of commonly used names data(sumstatsColHeaders) column_headers = toupper(column_headers) for(headerI in 1:dim(sumstatsColHeaders)[1]){ un = sumstatsColHeaders[headerI,1] cr = sumstatsColHeaders[headerI,2] #print(un) if(un %in% column_headers & (!cr %in% column_headers)){column_headers=gsub(sprintf("^%s$",un),cr,column_headers)} #if(tolower(un) %in% column_headers){column_headers=gsub(sprintf("^%s$",tolower(un)),cr,column_headers)} } new_first_line = paste(column_headers,collapse = "\t") # Write the new column headers to file sed_command = sprintf("sed -i.bak '1s/%s/%s/' %s",first_line,new_first_line,path) system2("/bin/bash", args = c("-c", shQuote(sed_command))) system(sprintf("rm %s.bak", path)) #column_headers = strsplit(column_headers," ")[[1]] return(column_headers) }
/R/standardise.sumstats.column.headers.linux.r
no_license
rbutleriii/MAGMA_Celltyping
R
false
false
2,125
r
#' Standardise the column headers in the Summary Statistics files #' #' Use a reference data table of common column header names (stored in sumstatsColHeaders.rda) convert them to a standard set, i.e. chromosome --> CHR #' #' This function does not check that all the required column headers are present #' #' The amended header is written directly back into the file #' #' @param path Filepath for the summary statistics file #' #' @return The amended column headers (also the column headers will be written directly into the summary statistics file) #' #' @examples #' col_headers = standardise.sumstats.column.headers("~/Downloads/202040.assoc.tsv") #' #' @export standardise.sumstats.column.headers.linux <- function(path){ # Check the sumstats file exists if(!file.exists(path)){stop("Path to GWAS sumstats is not valid")} # Read in the first line of the file only con <- file(path,"r") ; first_line <- readLines(con,n=1) ; close(con) column_headers = strsplit(first_line,"\t")[[1]] # Show to the user what the header is print("First line of summary statistics file: ") print(first_line) print(column_headers) # Amend the column headers based on a data table of commonly used names data(sumstatsColHeaders) column_headers = toupper(column_headers) for(headerI in 1:dim(sumstatsColHeaders)[1]){ un = sumstatsColHeaders[headerI,1] cr = sumstatsColHeaders[headerI,2] #print(un) if(un %in% column_headers & (!cr %in% column_headers)){column_headers=gsub(sprintf("^%s$",un),cr,column_headers)} #if(tolower(un) %in% column_headers){column_headers=gsub(sprintf("^%s$",tolower(un)),cr,column_headers)} } new_first_line = paste(column_headers,collapse = "\t") # Write the new column headers to file sed_command = sprintf("sed -i.bak '1s/%s/%s/' %s",first_line,new_first_line,path) system2("/bin/bash", args = c("-c", shQuote(sed_command))) system(sprintf("rm %s.bak", path)) #column_headers = strsplit(column_headers," ")[[1]] return(column_headers) }
#Question 6: Compare emissions from motor vehicle sources in Baltimore City #with emissions from motor vehicle sources in Los Angeles County, California #(\color{red}{\verb|fips == "06037"|}fips=="06037"). #Which city has seen greater changes over time in motor vehicle emissions? #Unzip the dataset unzip(zipfile = "./data/exdata_data_NEI_data.zip", exdir = "./data") library(ggplot2) #Reading data NEI <- readRDS("./data/summarySCC_PM25.rds") SCC <- readRDS("./data/Source_Classification_Code.rds") #subsetting Los Angeles and Baltimore data LA <- subset(NEI, fips == "06037") Baltimore <- subset(NEI, fips=="24510") # subsetting SCC with vehicle values vehicle <- grepl("vehicle", SCC$SCC.Level.Two, ignore.case=TRUE) subsetSCC <- SCC[vehicle, ] # merging Baltimore and LA data with SCC vehicles data_Balt <- merge(Baltimore, subsetSCC, by="SCC") data_LA <- merge(LA, subsetSCC, by="SCC") #adding city variable data_Balt$city <- make.names("Baltimore City") data_LA$city <- make.names("Los Angeles County") #merging Baltimore and Los Angeles data data_merged <- rbind(data_Balt, data_LA) # summing emission data per year by city data_LA_Balt<-aggregate(Emissions ~ year + city, data_merged, sum) # plotting png("plot6.png", width=560, height=480) g <- ggplot(data_LA_Balt, aes(year, Emissions, color = city)) g + geom_line() + xlab("Year") + ylab(expression("Total PM"[2.5]*" Emissions")) + ggtitle("Total Emissions from motor sources in Baltimore,MD and Los Angeles, CA") dev.off()
/Course 4- Exploratory Data Analysis/Week 4/Assignment/plot6.R
no_license
shovitraj/DataScienceSpecialization-JHU
R
false
false
1,526
r
#Question 6: Compare emissions from motor vehicle sources in Baltimore City #with emissions from motor vehicle sources in Los Angeles County, California #(\color{red}{\verb|fips == "06037"|}fips=="06037"). #Which city has seen greater changes over time in motor vehicle emissions? #Unzip the dataset unzip(zipfile = "./data/exdata_data_NEI_data.zip", exdir = "./data") library(ggplot2) #Reading data NEI <- readRDS("./data/summarySCC_PM25.rds") SCC <- readRDS("./data/Source_Classification_Code.rds") #subsetting Los Angeles and Baltimore data LA <- subset(NEI, fips == "06037") Baltimore <- subset(NEI, fips=="24510") # subsetting SCC with vehicle values vehicle <- grepl("vehicle", SCC$SCC.Level.Two, ignore.case=TRUE) subsetSCC <- SCC[vehicle, ] # merging Baltimore and LA data with SCC vehicles data_Balt <- merge(Baltimore, subsetSCC, by="SCC") data_LA <- merge(LA, subsetSCC, by="SCC") #adding city variable data_Balt$city <- make.names("Baltimore City") data_LA$city <- make.names("Los Angeles County") #merging Baltimore and Los Angeles data data_merged <- rbind(data_Balt, data_LA) # summing emission data per year by city data_LA_Balt<-aggregate(Emissions ~ year + city, data_merged, sum) # plotting png("plot6.png", width=560, height=480) g <- ggplot(data_LA_Balt, aes(year, Emissions, color = city)) g + geom_line() + xlab("Year") + ylab(expression("Total PM"[2.5]*" Emissions")) + ggtitle("Total Emissions from motor sources in Baltimore,MD and Los Angeles, CA") dev.off()
# My library(shiny) shinyUI(fluidPage( titlePanel("StockComp"), sidebarLayout( sidebarPanel( helpText("Select two stocks and a time frame to compare. Information will be collected from yahoo finance."), textInput("symb1", "1st Stock Symbol", "GOOG"), textInput("symb2", "2nd Stock Symbol", "AAPL"), dateRangeInput("dates", "Date range", start = "2012-01-01", end = as.character(Sys.Date())), actionButton("get", "Compare Stocks"), br(), br(), checkboxInput("log", "Plot y axis on log scale", value = FALSE) ), mainPanel( plotOutput("plot"), plotOutput("plot2") ) ) ))
/ui.R
no_license
EricHPei/MyApp
R
false
false
730
r
# My library(shiny) shinyUI(fluidPage( titlePanel("StockComp"), sidebarLayout( sidebarPanel( helpText("Select two stocks and a time frame to compare. Information will be collected from yahoo finance."), textInput("symb1", "1st Stock Symbol", "GOOG"), textInput("symb2", "2nd Stock Symbol", "AAPL"), dateRangeInput("dates", "Date range", start = "2012-01-01", end = as.character(Sys.Date())), actionButton("get", "Compare Stocks"), br(), br(), checkboxInput("log", "Plot y axis on log scale", value = FALSE) ), mainPanel( plotOutput("plot"), plotOutput("plot2") ) ) ))
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JieZ_2017.R \name{JieZ_2017} \alias{JieZ_2017} \alias{JieZ_2017.genefamilies_relab.stool} \alias{JieZ_2017.marker_abundance.stool} \alias{JieZ_2017.marker_presence.stool} \alias{JieZ_2017.metaphlan_bugs_list.stool} \alias{JieZ_2017.pathabundance_relab.stool} \alias{JieZ_2017.pathcoverage.stool} \title{Data from the JieZ_2017 study} \description{ Data from the JieZ_2017 study } \section{Datasets}{ \subsection{JieZ_2017.genefamilies_relab.stool}{ An ExpressionSet with 385 samples and 1,976,093 features specific to the stool body site } \subsection{JieZ_2017.marker_abundance.stool}{ An ExpressionSet with 385 samples and 158,072 features specific to the stool body site } \subsection{JieZ_2017.marker_presence.stool}{ An ExpressionSet with 385 samples and 145,642 features specific to the stool body site } \subsection{JieZ_2017.metaphlan_bugs_list.stool}{ An ExpressionSet with 385 samples and 1,666 features specific to the stool body site } \subsection{JieZ_2017.pathabundance_relab.stool}{ An ExpressionSet with 385 samples and 13,222 features specific to the stool body site } \subsection{JieZ_2017.pathcoverage.stool}{ An ExpressionSet with 385 samples and 13,222 features specific to the stool body site } } \section{Source}{ \subsection{Title}{ The gut microbiome in atherosclerotic cardiovascular disease. } \subsection{Author}{ Jie Z, Xia H, Zhong SL, Feng Q, Li S, Liang S, Zhong H, Liu Z, Gao Y, Zhao H, Zhang D, Su Z, Fang Z, Lan Z, Li J, Xiao L, Li J, Li R, Li X, Li F, Ren H, Huang Y, Peng Y, Li G, Wen B, Dong B, Chen JY, Geng QS, Zhang ZW, Yang H, Wang J, Wang J, Zhang X, Madsen L, Brix S, Ning G, Xu X, Liu X, Hou Y, Jia H, He K, Kristiansen K } \subsection{Lab}{ [1] BGI-Shenzhen, Shenzhen, 518083, China., [2] China National Genebank, Shenzhen, 518120, China., [3] Shenzhen Key Laboratory of Human Commensal Microorganisms and Health Research, BGI-Shenzhen, Shenzhen, 518083, China., [4] Guangdong Provincial Key Laboratory of Coronary Heart Disease Prevention, Guangdong Cardiovascular Institute, Guangzhou, 510080, China., [5] Medical Research Center of Guangdong General Hospital, Guangdong Academy of Medical Sciences, Guangzhou, 510080, China., [6] Shenzhen Engineering Laboratory of Detection and Intervention of Human Intestinal Microbiome, Shenzhen, 518083, China., [7] Department of Biology, Laboratory of Genomics and Molecular Biomedicine, University of Copenhagen, Universitetsparken 13, 2100, Copenhagen, Denmark., [8] Department of Human Microbiome, School of Stomatology, Shandong University, Shandong Provincial Key Laboratory of Oral Tissue Regeneration, Jinan, 250012, China., [9] BGI Education Center, University of Chinese Academy of Sciences, Shenzhen, 518083, China., [10] School of Bioscience and Biotechnology, South China University of Technology, Guangzhou, 510006, China., [11] Beijing Key Laboratory for Precision Medicine of Chronic Heart Failure, Chinese PLA General Hospital, Beijing, 100853, China., [12] Center for Genome Sciences &amp; Systems Biology, Washington University School of Medicine, St. Louis, MO, 63110, USA., [13] James D. Watson Institute of Genome Sciences, Hangzhou, 310000, China., [14] Macau University of Science and Technology, Macau, 999078, China., [15] iCarbonX, Shenzhen, 518053, China., [16] Department of Rheumatology and Clinical Immunology, Peking Union Medical College Hospital, Chinese Academy of Medical Sciences and Peking Union Medical College, Beijing, 100730, China., [17] National Institute of Nutrition and Seafood Research, (NIFES), Postboks 2029, Nordnes, N-5817, Bergen, Norway., [18] Department of Biotechnology and Biomedicine, Technical University of Denmark (DTU), 2800, Kongens Lyngby, Denmark., [19] Department of Endocrinology and Metabolism, State Key Laboratory of Medical Genomes, National Clinical Research Center for Metabolic Diseases, Shanghai Clinical Center for Endocrine and Metabolic Diseases, Shanghai Institute of Endocrine and Metabolic Diseases, Ruijin Hospital, Shanghai Jiao Tong University School of Medicine, Shanghai, 200025, China., [20] BGI-Shenzhen, Shenzhen, 518083, China. jiahuijue@genomics.cn., [21] China National Genebank, Shenzhen, 518120, China. jiahuijue@genomics.cn., [22] Shenzhen Key Laboratory of Human Commensal Microorganisms and Health Research, BGI-Shenzhen, Shenzhen, 518083, China. jiahuijue@genomics.cn., [23] Macau University of Science and Technology, Macau, 999078, China. jiahuijue@genomics.cn., [24] Beijing Key Laboratory for Precision Medicine of Chronic Heart Failure, Chinese PLA General Hospital, Beijing, 100853, China. hekl301@aliyun.com., [25] BGI-Shenzhen, Shenzhen, 518083, China. kk@bio.ku.dk., [26] China National Genebank, Shenzhen, 518120, China. kk@bio.ku.dk., [27] Department of Biology, Laboratory of Genomics and Molecular Biomedicine, University of Copenhagen, Universitetsparken 13, 2100, Copenhagen, Denmark. kk@bio.ku.dk. } \subsection{PMID}{ 29018189 } } \examples{ JieZ_2017.metaphlan_bugs_list.stool() }
/man/JieZ_2017.Rd
permissive
vjcitn/curatedMetagenomicData
R
false
true
5,109
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JieZ_2017.R \name{JieZ_2017} \alias{JieZ_2017} \alias{JieZ_2017.genefamilies_relab.stool} \alias{JieZ_2017.marker_abundance.stool} \alias{JieZ_2017.marker_presence.stool} \alias{JieZ_2017.metaphlan_bugs_list.stool} \alias{JieZ_2017.pathabundance_relab.stool} \alias{JieZ_2017.pathcoverage.stool} \title{Data from the JieZ_2017 study} \description{ Data from the JieZ_2017 study } \section{Datasets}{ \subsection{JieZ_2017.genefamilies_relab.stool}{ An ExpressionSet with 385 samples and 1,976,093 features specific to the stool body site } \subsection{JieZ_2017.marker_abundance.stool}{ An ExpressionSet with 385 samples and 158,072 features specific to the stool body site } \subsection{JieZ_2017.marker_presence.stool}{ An ExpressionSet with 385 samples and 145,642 features specific to the stool body site } \subsection{JieZ_2017.metaphlan_bugs_list.stool}{ An ExpressionSet with 385 samples and 1,666 features specific to the stool body site } \subsection{JieZ_2017.pathabundance_relab.stool}{ An ExpressionSet with 385 samples and 13,222 features specific to the stool body site } \subsection{JieZ_2017.pathcoverage.stool}{ An ExpressionSet with 385 samples and 13,222 features specific to the stool body site } } \section{Source}{ \subsection{Title}{ The gut microbiome in atherosclerotic cardiovascular disease. } \subsection{Author}{ Jie Z, Xia H, Zhong SL, Feng Q, Li S, Liang S, Zhong H, Liu Z, Gao Y, Zhao H, Zhang D, Su Z, Fang Z, Lan Z, Li J, Xiao L, Li J, Li R, Li X, Li F, Ren H, Huang Y, Peng Y, Li G, Wen B, Dong B, Chen JY, Geng QS, Zhang ZW, Yang H, Wang J, Wang J, Zhang X, Madsen L, Brix S, Ning G, Xu X, Liu X, Hou Y, Jia H, He K, Kristiansen K } \subsection{Lab}{ [1] BGI-Shenzhen, Shenzhen, 518083, China., [2] China National Genebank, Shenzhen, 518120, China., [3] Shenzhen Key Laboratory of Human Commensal Microorganisms and Health Research, BGI-Shenzhen, Shenzhen, 518083, China., [4] Guangdong Provincial Key Laboratory of Coronary Heart Disease Prevention, Guangdong Cardiovascular Institute, Guangzhou, 510080, China., [5] Medical Research Center of Guangdong General Hospital, Guangdong Academy of Medical Sciences, Guangzhou, 510080, China., [6] Shenzhen Engineering Laboratory of Detection and Intervention of Human Intestinal Microbiome, Shenzhen, 518083, China., [7] Department of Biology, Laboratory of Genomics and Molecular Biomedicine, University of Copenhagen, Universitetsparken 13, 2100, Copenhagen, Denmark., [8] Department of Human Microbiome, School of Stomatology, Shandong University, Shandong Provincial Key Laboratory of Oral Tissue Regeneration, Jinan, 250012, China., [9] BGI Education Center, University of Chinese Academy of Sciences, Shenzhen, 518083, China., [10] School of Bioscience and Biotechnology, South China University of Technology, Guangzhou, 510006, China., [11] Beijing Key Laboratory for Precision Medicine of Chronic Heart Failure, Chinese PLA General Hospital, Beijing, 100853, China., [12] Center for Genome Sciences &amp; Systems Biology, Washington University School of Medicine, St. Louis, MO, 63110, USA., [13] James D. Watson Institute of Genome Sciences, Hangzhou, 310000, China., [14] Macau University of Science and Technology, Macau, 999078, China., [15] iCarbonX, Shenzhen, 518053, China., [16] Department of Rheumatology and Clinical Immunology, Peking Union Medical College Hospital, Chinese Academy of Medical Sciences and Peking Union Medical College, Beijing, 100730, China., [17] National Institute of Nutrition and Seafood Research, (NIFES), Postboks 2029, Nordnes, N-5817, Bergen, Norway., [18] Department of Biotechnology and Biomedicine, Technical University of Denmark (DTU), 2800, Kongens Lyngby, Denmark., [19] Department of Endocrinology and Metabolism, State Key Laboratory of Medical Genomes, National Clinical Research Center for Metabolic Diseases, Shanghai Clinical Center for Endocrine and Metabolic Diseases, Shanghai Institute of Endocrine and Metabolic Diseases, Ruijin Hospital, Shanghai Jiao Tong University School of Medicine, Shanghai, 200025, China., [20] BGI-Shenzhen, Shenzhen, 518083, China. jiahuijue@genomics.cn., [21] China National Genebank, Shenzhen, 518120, China. jiahuijue@genomics.cn., [22] Shenzhen Key Laboratory of Human Commensal Microorganisms and Health Research, BGI-Shenzhen, Shenzhen, 518083, China. jiahuijue@genomics.cn., [23] Macau University of Science and Technology, Macau, 999078, China. jiahuijue@genomics.cn., [24] Beijing Key Laboratory for Precision Medicine of Chronic Heart Failure, Chinese PLA General Hospital, Beijing, 100853, China. hekl301@aliyun.com., [25] BGI-Shenzhen, Shenzhen, 518083, China. kk@bio.ku.dk., [26] China National Genebank, Shenzhen, 518120, China. kk@bio.ku.dk., [27] Department of Biology, Laboratory of Genomics and Molecular Biomedicine, University of Copenhagen, Universitetsparken 13, 2100, Copenhagen, Denmark. kk@bio.ku.dk. } \subsection{PMID}{ 29018189 } } \examples{ JieZ_2017.metaphlan_bugs_list.stool() }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/wasserstein.R \name{wasserstein} \alias{wasserstein} \title{wasserstein} \usage{ wasserstein(p, q, cost_matrix, epsilon, niterations) } \value{ a list with "distances", "transportmatrix", "u" and "v" } \description{ Compute regularized Wasserstein distance between two empirical distributions, p and q, specified as vector of probabilities summing to one. The third argument is the cost matrix, i.e. a matrix of pair-wise distances, the fourth argument is the regularization parameter, e.g. 0.05*median(cost_matrix), and the last argument is the number of Sinkhorn iterations to perform, e.g. 100. Important references are - Cuturi, M. (2013). Sinkhorn distances: Lightspeed computation of optimal transport. In Advances in Neural Information Processing Systems (NIPS), pages 2292-2300. - Cuturi, M. and Doucet, A. (2014). Fast computation of Wasserstein barycenters. In Proceedings of the 31st International Conference on Machine Learning (ICML), pages 685-693. }
/man/wasserstein.Rd
no_license
ramcqueary/winference
R
false
true
1,045
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/wasserstein.R \name{wasserstein} \alias{wasserstein} \title{wasserstein} \usage{ wasserstein(p, q, cost_matrix, epsilon, niterations) } \value{ a list with "distances", "transportmatrix", "u" and "v" } \description{ Compute regularized Wasserstein distance between two empirical distributions, p and q, specified as vector of probabilities summing to one. The third argument is the cost matrix, i.e. a matrix of pair-wise distances, the fourth argument is the regularization parameter, e.g. 0.05*median(cost_matrix), and the last argument is the number of Sinkhorn iterations to perform, e.g. 100. Important references are - Cuturi, M. (2013). Sinkhorn distances: Lightspeed computation of optimal transport. In Advances in Neural Information Processing Systems (NIPS), pages 2292-2300. - Cuturi, M. and Doucet, A. (2014). Fast computation of Wasserstein barycenters. In Proceedings of the 31st International Conference on Machine Learning (ICML), pages 685-693. }
#Autor: Suárez Pérez Juan Pablo #Funciónn Principal del programa main <- function() { cat("Bienvenido\n") cat("Calculadora de ahorro por viajes compartidos...\n\n") #Registro de viajes. viajes <- registrar_viajes() #Impresión del los viajes realizados. print(viajes) View(viajes) #Resultado por viajes: costo del viaje, costo por persona y ahorrado. resultados_viajes <- obtener_resultados(viajes) print(resultados_viajes) View(resultados_viajes) #Obtención de resultados diarios. calcular_resultados(resultados_viajes) #Resultados del día: costo diario, costo diario por persona y ahorrado diario. generar_graficos(viajes, resultados_viajes) } registrar_viajes <- function() { respuesta <- "Si" bandera = TRUE cat("Es necesario que ingreses los siguientes datos:\n") cat("1. Kilometros conducidos\n") cat("2. Costo por litro de gasolina\n") cat("3. Kilometros por litro\n") cat("4. Peaje\n") cat("5. Cuotas por estacionamiento\n") cat("6. Número de integrantes por viaje\n\n") #Obtención del primer carácter de la respuesta. respuesta <- substr(respuesta, start = 1, stop = 1) while (respuesta == 'S' || respuesta == 's') { #Ingreso de los resultados del usuario. #Se realizan algunas validaciones de los datos de entrada. cat("1. ¿Cuántos kilometros recorriste?") km_recorridos <- as.numeric(readLines(n = 1)) if (is.na(km_recorridos)) km_recorridos = 0 cat("2. Ingresa el precio por litro de gasolina") costo_lt_gas <- as.numeric(readLines(n = 1)) #Promedio del costo de gasolina. if (is.na(costo_lt_gas)) costo_lt_gas = 20 cat("3. ¿Cuántos kilometros por litro de gasolina?") km_lt <- as.numeric(readLines(n = 1)) #Promedio de km por litro de gasolina. if (is.na(km_lt)) km_lt = 12 cat("4. ¿Cuánto gastaste en peajes?") peaje_recorrido <- as.numeric(readLines(n = 1)) if (is.na(peaje_recorrido)) peaje_recorrido = 0 cat("5. ¿Cuánto gastaste en estacionamiento?") cuota_estacionamiento <- as.numeric(readLines(n = 1)) if (is.na(cuota_estacionamiento)) cuota_estacionamiento = 0 cat("6. ¿Cuántas personas viajaron contigo? (incluyendote)") integrantes <- as.numeric(readLines(n = 1)) if (is.na(integrantes)) integrantes = 1 cat("\n") if (bandera == TRUE) { #Creación de la matriz llamada viajes. viajes <- matrix(c(km_recorridos, costo_lt_gas, km_lt, peaje_recorrido, cuota_estacionamiento, integrantes), ncol = 6, byrow = T) colnames(viajes) <- c("km_recorridos", "costo_lt_gas", "km_lt", "peaje_recorrido", "cuota_estacionamiento", "integrantes") bandera = FALSE } else { #Actualización de la matriz llamda viajes. viajes <- rbind(viajes, c(km_recorridos, costo_lt_gas, km_lt, peaje_recorrido, cuota_estacionamiento, integrantes)) } cat("¿Quieres realizar más viajes?") respuesta <- readLines(n = 1) cat("\n") respuesta <- substr(respuesta, start = 1, stop = 1) } #Retorno de la matriz viajes. return(viajes) } obtener_resultados <- function(viajes) { bandera = TRUE #Obtención de las dimensiones del viaje. dim_viajes <- dim(viajes) cat("\n") for (i in 1:dim_viajes[1]) { #Obtención de los resultados obtenidos por viajes. litros_necesarios <- viajes[i, "km_recorridos"] / viajes[i, "km_lt"] costo_total_gasolina <- litros_necesarios * viajes[i, "costo_lt_gas"] costo_total <- costo_total_gasolina + viajes[i, "peaje_recorrido"] + viajes[i, "cuota_estacionamiento"] costo_persona <- costo_total / viajes[i, "integrantes"] ahorrado <- costo_total - costo_persona #Impresión de los resultados obtenidos por viajes. cat("Resultados obtenidos del viaje ", i, "...\n") cat("Litros necesarios para tu viaje: ", litros_necesarios, "\n") cat("Costo total de la gasolina: $", costo_total_gasolina, "\n") cat("El costo total del viaje es de: $", costo_total, "\n") cat("El costo por persona: $", costo_persona, "\n") cat("Te ahorraste: $", ahorrado, "\n\n") if (bandera == TRUE) { #Creación de la matriz con los resultados. resultados_viajes <- matrix(c(costo_total, costo_persona, ahorrado), ncol = 3, byrow = TRUE) colnames(resultados_viajes) <- c("costo_total", "costo_persona", "ahorrado") bandera = FALSE } else { #Actualización de la matriz con los resultados. resultados_viajes <- rbind(resultados_viajes, c(costo_total, costo_persona, ahorrado)) } } #Retorno del la matriz de resultados. return(resultados_viajes) } calcular_resultados <- function(resultados_viajes) { #Resultados finales. res_diarios <- colSums(resultados_viajes) cat("\n") cat("Costo total diario: $", res_diarios[1], "\n") cat("Costo por persona diario: $", res_diarios[2], "\n") cat("Ahorrado diario: $", res_diarios[3], "\n") } generar_graficos <- function(viajes, resultados_viajes) { #Generación de gráfico. plot(x = viajes[, "integrantes"], y = resultados_viajes[, "ahorrado"], main = "Ahorrado por integrantes", xlab = "Integrantes", ylab = "Ahorrado") } main()
/calculadora_viajes.R
no_license
breko151/Calculadora_Viajes
R
false
false
5,489
r
#Autor: Suárez Pérez Juan Pablo #Funciónn Principal del programa main <- function() { cat("Bienvenido\n") cat("Calculadora de ahorro por viajes compartidos...\n\n") #Registro de viajes. viajes <- registrar_viajes() #Impresión del los viajes realizados. print(viajes) View(viajes) #Resultado por viajes: costo del viaje, costo por persona y ahorrado. resultados_viajes <- obtener_resultados(viajes) print(resultados_viajes) View(resultados_viajes) #Obtención de resultados diarios. calcular_resultados(resultados_viajes) #Resultados del día: costo diario, costo diario por persona y ahorrado diario. generar_graficos(viajes, resultados_viajes) } registrar_viajes <- function() { respuesta <- "Si" bandera = TRUE cat("Es necesario que ingreses los siguientes datos:\n") cat("1. Kilometros conducidos\n") cat("2. Costo por litro de gasolina\n") cat("3. Kilometros por litro\n") cat("4. Peaje\n") cat("5. Cuotas por estacionamiento\n") cat("6. Número de integrantes por viaje\n\n") #Obtención del primer carácter de la respuesta. respuesta <- substr(respuesta, start = 1, stop = 1) while (respuesta == 'S' || respuesta == 's') { #Ingreso de los resultados del usuario. #Se realizan algunas validaciones de los datos de entrada. cat("1. ¿Cuántos kilometros recorriste?") km_recorridos <- as.numeric(readLines(n = 1)) if (is.na(km_recorridos)) km_recorridos = 0 cat("2. Ingresa el precio por litro de gasolina") costo_lt_gas <- as.numeric(readLines(n = 1)) #Promedio del costo de gasolina. if (is.na(costo_lt_gas)) costo_lt_gas = 20 cat("3. ¿Cuántos kilometros por litro de gasolina?") km_lt <- as.numeric(readLines(n = 1)) #Promedio de km por litro de gasolina. if (is.na(km_lt)) km_lt = 12 cat("4. ¿Cuánto gastaste en peajes?") peaje_recorrido <- as.numeric(readLines(n = 1)) if (is.na(peaje_recorrido)) peaje_recorrido = 0 cat("5. ¿Cuánto gastaste en estacionamiento?") cuota_estacionamiento <- as.numeric(readLines(n = 1)) if (is.na(cuota_estacionamiento)) cuota_estacionamiento = 0 cat("6. ¿Cuántas personas viajaron contigo? (incluyendote)") integrantes <- as.numeric(readLines(n = 1)) if (is.na(integrantes)) integrantes = 1 cat("\n") if (bandera == TRUE) { #Creación de la matriz llamada viajes. viajes <- matrix(c(km_recorridos, costo_lt_gas, km_lt, peaje_recorrido, cuota_estacionamiento, integrantes), ncol = 6, byrow = T) colnames(viajes) <- c("km_recorridos", "costo_lt_gas", "km_lt", "peaje_recorrido", "cuota_estacionamiento", "integrantes") bandera = FALSE } else { #Actualización de la matriz llamda viajes. viajes <- rbind(viajes, c(km_recorridos, costo_lt_gas, km_lt, peaje_recorrido, cuota_estacionamiento, integrantes)) } cat("¿Quieres realizar más viajes?") respuesta <- readLines(n = 1) cat("\n") respuesta <- substr(respuesta, start = 1, stop = 1) } #Retorno de la matriz viajes. return(viajes) } obtener_resultados <- function(viajes) { bandera = TRUE #Obtención de las dimensiones del viaje. dim_viajes <- dim(viajes) cat("\n") for (i in 1:dim_viajes[1]) { #Obtención de los resultados obtenidos por viajes. litros_necesarios <- viajes[i, "km_recorridos"] / viajes[i, "km_lt"] costo_total_gasolina <- litros_necesarios * viajes[i, "costo_lt_gas"] costo_total <- costo_total_gasolina + viajes[i, "peaje_recorrido"] + viajes[i, "cuota_estacionamiento"] costo_persona <- costo_total / viajes[i, "integrantes"] ahorrado <- costo_total - costo_persona #Impresión de los resultados obtenidos por viajes. cat("Resultados obtenidos del viaje ", i, "...\n") cat("Litros necesarios para tu viaje: ", litros_necesarios, "\n") cat("Costo total de la gasolina: $", costo_total_gasolina, "\n") cat("El costo total del viaje es de: $", costo_total, "\n") cat("El costo por persona: $", costo_persona, "\n") cat("Te ahorraste: $", ahorrado, "\n\n") if (bandera == TRUE) { #Creación de la matriz con los resultados. resultados_viajes <- matrix(c(costo_total, costo_persona, ahorrado), ncol = 3, byrow = TRUE) colnames(resultados_viajes) <- c("costo_total", "costo_persona", "ahorrado") bandera = FALSE } else { #Actualización de la matriz con los resultados. resultados_viajes <- rbind(resultados_viajes, c(costo_total, costo_persona, ahorrado)) } } #Retorno del la matriz de resultados. return(resultados_viajes) } calcular_resultados <- function(resultados_viajes) { #Resultados finales. res_diarios <- colSums(resultados_viajes) cat("\n") cat("Costo total diario: $", res_diarios[1], "\n") cat("Costo por persona diario: $", res_diarios[2], "\n") cat("Ahorrado diario: $", res_diarios[3], "\n") } generar_graficos <- function(viajes, resultados_viajes) { #Generación de gráfico. plot(x = viajes[, "integrantes"], y = resultados_viajes[, "ahorrado"], main = "Ahorrado por integrantes", xlab = "Integrantes", ylab = "Ahorrado") } main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # ProjectName: Bluebook 2021-Universe # Purpose: Price # programmer: Zhe Liu # Date: 2021-03-12 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ##---- Price ---- ## origin price price.origin <- raw.total %>% group_by(packid, quarter, province, city) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price = sales / units) %>% select(-sales, -units) ## mean price by city year price.city <- raw.total %>% group_by(packid, year, province, city) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_city = sales / units) %>% select(-sales, -units) ## mean price by province quarter price.province <- raw.total %>% group_by(packid, quarter, province) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_prov = sales / units) %>% select(-sales, -units) ## mean price by province year price.year <- raw.total %>% group_by(packid, year, province) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_year = sales / units) %>% select(-sales, -units) ## mean price by pack quarter price.pack <- raw.total %>% group_by(packid, quarter) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_pack = sales / units) %>% select(-sales, -units) ## mean price by pack year price.pack.year <- raw.total %>% group_by(packid, year) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_pack_year = sales / units) %>% select(-sales, -units) ##---- Result ---- proj.price <- proj.nation %>% left_join(price.origin, by = c('province', 'city', 'quarter', 'packid')) %>% left_join(price.city, by = c('province', 'city', 'year', 'packid')) %>% left_join(price.province, by = c('province', 'quarter', 'packid')) %>% left_join(price.year, by = c('province', 'year', 'packid')) %>% left_join(price.pack, by = c('quarter', 'packid')) %>% left_join(price.pack.year, by = c('year', 'packid')) %>% mutate(price = if_else(is.na(price), price_city, price), price = if_else(is.na(price), price_prov, price), price = if_else(is.na(price), price_year, price), price = if_else(is.na(price), price_pack, price), price = if_else(is.na(price), price_pack_year, price)) %>% mutate(units = sales / price) %>% filter(units > 0, sales > 0) %>% select(year, quarter, date, province, city, market, atc4, molecule, packid, units, sales) write_feather(proj.price, '03_Outputs/Universe/05_Bluebook_2020_Universe_Projection_Price.feather')
/04_Codes/Universe/05_Price.R
no_license
Zaphiroth/Bluebook_2021
R
false
false
3,112
r
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # ProjectName: Bluebook 2021-Universe # Purpose: Price # programmer: Zhe Liu # Date: 2021-03-12 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ##---- Price ---- ## origin price price.origin <- raw.total %>% group_by(packid, quarter, province, city) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price = sales / units) %>% select(-sales, -units) ## mean price by city year price.city <- raw.total %>% group_by(packid, year, province, city) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_city = sales / units) %>% select(-sales, -units) ## mean price by province quarter price.province <- raw.total %>% group_by(packid, quarter, province) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_prov = sales / units) %>% select(-sales, -units) ## mean price by province year price.year <- raw.total %>% group_by(packid, year, province) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_year = sales / units) %>% select(-sales, -units) ## mean price by pack quarter price.pack <- raw.total %>% group_by(packid, quarter) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_pack = sales / units) %>% select(-sales, -units) ## mean price by pack year price.pack.year <- raw.total %>% group_by(packid, year) %>% summarise(sales = sum(sales, na.rm = TRUE), units = sum(units, na.rm = TRUE)) %>% ungroup() %>% mutate(price_pack_year = sales / units) %>% select(-sales, -units) ##---- Result ---- proj.price <- proj.nation %>% left_join(price.origin, by = c('province', 'city', 'quarter', 'packid')) %>% left_join(price.city, by = c('province', 'city', 'year', 'packid')) %>% left_join(price.province, by = c('province', 'quarter', 'packid')) %>% left_join(price.year, by = c('province', 'year', 'packid')) %>% left_join(price.pack, by = c('quarter', 'packid')) %>% left_join(price.pack.year, by = c('year', 'packid')) %>% mutate(price = if_else(is.na(price), price_city, price), price = if_else(is.na(price), price_prov, price), price = if_else(is.na(price), price_year, price), price = if_else(is.na(price), price_pack, price), price = if_else(is.na(price), price_pack_year, price)) %>% mutate(units = sales / price) %>% filter(units > 0, sales > 0) %>% select(year, quarter, date, province, city, market, atc4, molecule, packid, units, sales) write_feather(proj.price, '03_Outputs/Universe/05_Bluebook_2020_Universe_Projection_Price.feather')
##### we evaluate health outcome from various potential intervetions in this script # setwd("~/Desktop/Spring 2020/coronavirus/codes") setwd("~/Dropbox/codes") rm(list = ls()) library(lubridate) require("sfsmisc") require("deSolve") library(matrixStats) ###### source wuhan model and other city model source('wuhan_simulation_policy_by_age.R') source('other_city_simulation_policy_by_age.R') # load('m_calib_res.rda') load('m_calib_res_revision.rda') load('model_inputs.rda') ################ Intervention 1: change quarantine start time ##### we assume massive social distancing start on the same date of city-quarantine id = 1 milestone = as.Date("03/31/20", "%m/%d/%y") # delta_t_range = -30:30 start = -30 incre = 2 end = 30 delta_t_range = seq(start, end, by = incre) ### debug # delta_t_range = 25:30 nage = length(f_cq) CI_and_mean = 3 date = structure(rep(NA_real_, length(delta_t_range)), class="Date") cum_exportion = array(0, c(length(delta_t_range), CI_and_mean)) cum_infected = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH cum_death = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH disease_burden = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH economy_loss = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH # THS_effectiveness = array(0, c(length(delta_t_range), 3, CI_and_mean)) # only for CQ, BJ, SH screening_cost = array(0, c(length(delta_t_range), 3, CI_and_mean)) SD_end_dates = structure(rep(NA_real_, length(nage)), class="Date") n_sample = 1000 temp_disease_burden = matrix(0, 4, n_sample) temp_cum_infected = matrix(0, 4, n_sample) temp_cum_death = matrix(0, 4, n_sample) temp_economy_loss = matrix(0, 4, n_sample) temp_screening_cost = matrix(0, 3, n_sample) # sample_param_indexes = which.min(abs(runif(n_sample) - m_calib_res[,"c_posterior_prob"])) t_init = Sys.time() for (delta_t in delta_t_range){ # delta_t_ind = delta_t - delta_t_range[1] + 1 delta_t_ind = as.integer(as.character((delta_t - start)/incre)) + 1 cat( "delta_t is ", delta_t, "\n") base_line_quarantine_startdate = as.Date("01/23/20", "%m/%d/%y") for (ind in 1:n_sample){ # if (ind %% 50 == 0){ # cat('ind is ', ind, "\n") # } # param_ind = which.min(abs(runif(1) - m_calib_res[,"c_posterior_prob"])) param_ind = ind symptomatic_ratio = as.numeric(m_calib_res[param_ind, 1:3]) mu_1 = as.numeric(m_calib_res[param_ind, 4:6]) beta = as.numeric(m_calib_res[param_ind, 7]) # ratio = ratio_range[beta_ind] quarantine_start = base_line_quarantine_startdate + delta_t quarantine_end = simulation_end ### we assume social_distancing start as the same time as social_distancing_start = quarantine_start SD_end_dates[1] = as.Date("03/31/20", "%m/%d/%y") SD_end_dates[2] = as.Date("03/31/20", "%m/%d/%y") SD_end_dates[3] = as.Date("03/31/20", "%m/%d/%y") # social_distancing_end = delta_t + base_line_social_distancing_end time_knot_vec = list('simulation_start' = simulation_start,'simulation_end' = simulation_end, 'chunyun_start' = chunyun_start, 'chunyun_end' = chunyun_end, 'quarantine_start' = quarantine_start, 'quarantine_end' = quarantine_end, 'social_distancing_start' = social_distancing_start, 'SD_end_dates' = SD_end_dates) mu = mu_1 * 2 WH_output <- wuhan_simulation(N_wh, time, beta, z_0, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, symptomatic_ratio) # ratio = ratio_range[2] #### for other cities exported = WH_output$exported ths_efficiency = 1 ths_window = 14 ths_start = quarantine_start ###ths: travel history screening ths_end = quarantine_end ### ths: travel history screening # social_distancing_start = as.Date("01/23/20", "%m/%d/%y") social_distancing_start = ths_start # social_distancing_end = quarantine_end SD_end_dates[1] = as.Date("03/31/20", "%m/%d/%y") SD_end_dates[2] = as.Date("02/29/20", "%m/%d/%y") SD_end_dates[3] = as.Date("03/31/20", "%m/%d/%y") time_knot_vec = list('simulation_start' = simulation_start,'simulation_end' = simulation_end, 'chunyun_start' = chunyun_start, 'chunyun_end' = chunyun_end, 'ths_start' = ths_start, 'ths_end' = ths_end, 'social_distancing_start' = social_distancing_start, 'SD_end_dates' = SD_end_dates) mu = mu_1/7 * 2 CQ_output <- other_city_simulation(N_cq, f_cq, time, beta, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, exported, exportion_perc_cq, ths_efficiency, ths_window, symptomatic_ratio) BJ_output <- other_city_simulation(N_bj, f_bj, time, beta, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, exported, exportion_perc_bj, ths_efficiency, ths_window, symptomatic_ratio) SH_output <- other_city_simulation(N_sh, f_sh, time, beta, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, exported, exportion_perc_sh, ths_efficiency, ths_window, symptomatic_ratio) diff_t = as.integer(milestone - simulation_start) temp_disease_burden[1, ind] = sum((WH_output$IS[diff_t + 1, ] + WH_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (WH_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_disease_burden[2, ind] = sum((CQ_output$IS[diff_t + 1, ] + CQ_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (CQ_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_disease_burden[3, ind] = sum((BJ_output$IS[diff_t + 1, ] + BJ_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (BJ_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_disease_burden[4, ind] = sum((SH_output$IS[diff_t + 1, ] + SH_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (SH_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_cum_infected[1, ind] = sum(WH_output$incidence[1:diff_t + 1])/WH_output$N_t[diff_t + 1] * 10000 temp_cum_infected[2, ind] = sum(CQ_output$incidence[1:diff_t + 1])/CQ_output$N_t[diff_t + 1] * 10000 temp_cum_infected[3, ind] = sum(BJ_output$incidence[1:diff_t + 1])/BJ_output$N_t[diff_t + 1] * 10000 temp_cum_infected[4, ind] = sum(SH_output$incidence[1:diff_t + 1])/SH_output$N_t[diff_t + 1] * 10000 temp_cum_death[1, ind] = WH_output$D[diff_t + 1 - time_to_death[1], 1] + WH_output$D[diff_t + 1 - time_to_death[2], 2] + WH_output$D[diff_t + 1 - time_to_death[3], 3] temp_cum_death[2, ind] = CQ_output$D[diff_t + 1 - time_to_death[1], 1] + CQ_output$D[diff_t + 1 - time_to_death[2], 2] + CQ_output$D[diff_t + 1 - time_to_death[3], 3] temp_cum_death[3, ind] = BJ_output$D[diff_t + 1 - time_to_death[1], 1] + BJ_output$D[diff_t + 1 - time_to_death[2], 2] + BJ_output$D[diff_t + 1 - time_to_death[3], 3] temp_cum_death[4, ind] = SH_output$D[diff_t + 1 - time_to_death[1], 1] + SH_output$D[diff_t + 1 - time_to_death[2], 2] + SH_output$D[diff_t + 1 - time_to_death[3], 3] temp_screening_cost[1, ind] = CQ_output$screening_counts * 16.438/1e+06 temp_screening_cost[2, ind] = BJ_output$screening_counts * 16.438/1e+06 temp_screening_cost[3, ind] = SH_output$screening_counts * 16.438/1e+06 temp_economy_loss[, ind] = temp_economy_loss[ ,ind] + GDP_loss_matrix[1,] * (milestone - quarantine_start + 1) + GDP_loss_matrix[2, ] * (SD_end_dates[2] - social_distancing_start + 1) + temp_disease_burden[ ,ind] + c(0, temp_screening_cost[ ,ind]) temp_economy_loss[ , ind] = round(temp_economy_loss[ ,ind]/1000,2) } # cum_exportion[delta_t_ind, beta_ind] = sum(WH_output$exported[1:diff_t + 1,,]) disease_burden[delta_t_ind, ,] = rowQuantiles(temp_disease_burden, probs = c(0.025, 0.5, 0.975)) cum_infected[delta_t_ind, ,] = rowQuantiles(temp_cum_infected, probs = c(0.025, 0.5, 0.975)) cum_death[delta_t_ind, ,] = rowQuantiles(temp_cum_death, probs = c(0.025, 0.5, 0.975)) screening_cost[delta_t_ind, ,] = rowQuantiles(temp_screening_cost, probs = c(0.025, 0.5, 0.975)) economy_loss[delta_t_ind, ,] = rowQuantiles(temp_economy_loss, probs = c(0.025, 0.5, 0.975)) ### change meadian to mean disease_burden[delta_t_ind, ,2] = rowMeans(temp_disease_burden) cum_infected[delta_t_ind, ,2] = rowMeans(temp_cum_infected) cum_death[delta_t_ind, ,2] = rowMeans(temp_cum_death) screening_cost[delta_t_ind, ,2] = rowMeans(temp_screening_cost) economy_loss[delta_t_ind, ,2] = rowMeans(temp_economy_loss) date[delta_t_ind] = base_line_quarantine_startdate + delta_t # date[delta_t_ind, 1] = as.Date(base_line_quarantine_startdate + delta_t) } comp_time = Sys.time() - t_init comp_time save(economy_loss, disease_burden, cum_infected, cum_death, date, delta_t_range, screening_cost, file = "vary_start_date_all_doubled_mortality.rda")
/simulation_by_policy/vary_start_date_all_doubled_moratlity.R
no_license
Anthony-zh-Zhang/COVID_19_model
R
false
false
9,199
r
##### we evaluate health outcome from various potential intervetions in this script # setwd("~/Desktop/Spring 2020/coronavirus/codes") setwd("~/Dropbox/codes") rm(list = ls()) library(lubridate) require("sfsmisc") require("deSolve") library(matrixStats) ###### source wuhan model and other city model source('wuhan_simulation_policy_by_age.R') source('other_city_simulation_policy_by_age.R') # load('m_calib_res.rda') load('m_calib_res_revision.rda') load('model_inputs.rda') ################ Intervention 1: change quarantine start time ##### we assume massive social distancing start on the same date of city-quarantine id = 1 milestone = as.Date("03/31/20", "%m/%d/%y") # delta_t_range = -30:30 start = -30 incre = 2 end = 30 delta_t_range = seq(start, end, by = incre) ### debug # delta_t_range = 25:30 nage = length(f_cq) CI_and_mean = 3 date = structure(rep(NA_real_, length(delta_t_range)), class="Date") cum_exportion = array(0, c(length(delta_t_range), CI_and_mean)) cum_infected = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH cum_death = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH disease_burden = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH economy_loss = array(0, c(length(delta_t_range), 4, CI_and_mean)) # 4 cities: Wuhan, CQ, BJ, SH # THS_effectiveness = array(0, c(length(delta_t_range), 3, CI_and_mean)) # only for CQ, BJ, SH screening_cost = array(0, c(length(delta_t_range), 3, CI_and_mean)) SD_end_dates = structure(rep(NA_real_, length(nage)), class="Date") n_sample = 1000 temp_disease_burden = matrix(0, 4, n_sample) temp_cum_infected = matrix(0, 4, n_sample) temp_cum_death = matrix(0, 4, n_sample) temp_economy_loss = matrix(0, 4, n_sample) temp_screening_cost = matrix(0, 3, n_sample) # sample_param_indexes = which.min(abs(runif(n_sample) - m_calib_res[,"c_posterior_prob"])) t_init = Sys.time() for (delta_t in delta_t_range){ # delta_t_ind = delta_t - delta_t_range[1] + 1 delta_t_ind = as.integer(as.character((delta_t - start)/incre)) + 1 cat( "delta_t is ", delta_t, "\n") base_line_quarantine_startdate = as.Date("01/23/20", "%m/%d/%y") for (ind in 1:n_sample){ # if (ind %% 50 == 0){ # cat('ind is ', ind, "\n") # } # param_ind = which.min(abs(runif(1) - m_calib_res[,"c_posterior_prob"])) param_ind = ind symptomatic_ratio = as.numeric(m_calib_res[param_ind, 1:3]) mu_1 = as.numeric(m_calib_res[param_ind, 4:6]) beta = as.numeric(m_calib_res[param_ind, 7]) # ratio = ratio_range[beta_ind] quarantine_start = base_line_quarantine_startdate + delta_t quarantine_end = simulation_end ### we assume social_distancing start as the same time as social_distancing_start = quarantine_start SD_end_dates[1] = as.Date("03/31/20", "%m/%d/%y") SD_end_dates[2] = as.Date("03/31/20", "%m/%d/%y") SD_end_dates[3] = as.Date("03/31/20", "%m/%d/%y") # social_distancing_end = delta_t + base_line_social_distancing_end time_knot_vec = list('simulation_start' = simulation_start,'simulation_end' = simulation_end, 'chunyun_start' = chunyun_start, 'chunyun_end' = chunyun_end, 'quarantine_start' = quarantine_start, 'quarantine_end' = quarantine_end, 'social_distancing_start' = social_distancing_start, 'SD_end_dates' = SD_end_dates) mu = mu_1 * 2 WH_output <- wuhan_simulation(N_wh, time, beta, z_0, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, symptomatic_ratio) # ratio = ratio_range[2] #### for other cities exported = WH_output$exported ths_efficiency = 1 ths_window = 14 ths_start = quarantine_start ###ths: travel history screening ths_end = quarantine_end ### ths: travel history screening # social_distancing_start = as.Date("01/23/20", "%m/%d/%y") social_distancing_start = ths_start # social_distancing_end = quarantine_end SD_end_dates[1] = as.Date("03/31/20", "%m/%d/%y") SD_end_dates[2] = as.Date("02/29/20", "%m/%d/%y") SD_end_dates[3] = as.Date("03/31/20", "%m/%d/%y") time_knot_vec = list('simulation_start' = simulation_start,'simulation_end' = simulation_end, 'chunyun_start' = chunyun_start, 'chunyun_end' = chunyun_end, 'ths_start' = ths_start, 'ths_end' = ths_end, 'social_distancing_start' = social_distancing_start, 'SD_end_dates' = SD_end_dates) mu = mu_1/7 * 2 CQ_output <- other_city_simulation(N_cq, f_cq, time, beta, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, exported, exportion_perc_cq, ths_efficiency, ths_window, symptomatic_ratio) BJ_output <- other_city_simulation(N_bj, f_bj, time, beta, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, exported, exportion_perc_bj, ths_efficiency, ths_window, symptomatic_ratio) SH_output <- other_city_simulation(N_sh, f_sh, time, beta, D_E, D_I, time_knot_vec, E_I_beta_ratio, contact_mat, contact_ratio, mu, exported, exportion_perc_sh, ths_efficiency, ths_window, symptomatic_ratio) diff_t = as.integer(milestone - simulation_start) temp_disease_burden[1, ind] = sum((WH_output$IS[diff_t + 1, ] + WH_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (WH_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_disease_burden[2, ind] = sum((CQ_output$IS[diff_t + 1, ] + CQ_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (CQ_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_disease_burden[3, ind] = sum((BJ_output$IS[diff_t + 1, ] + BJ_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (BJ_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_disease_burden[4, ind] = sum((SH_output$IS[diff_t + 1, ] + SH_output$RS[diff_t + 1, ]) * ratio * (cost_treatment + cost_survived) + (SH_output$D[diff_t + 1, ]) * cost_death) /1e+06 temp_cum_infected[1, ind] = sum(WH_output$incidence[1:diff_t + 1])/WH_output$N_t[diff_t + 1] * 10000 temp_cum_infected[2, ind] = sum(CQ_output$incidence[1:diff_t + 1])/CQ_output$N_t[diff_t + 1] * 10000 temp_cum_infected[3, ind] = sum(BJ_output$incidence[1:diff_t + 1])/BJ_output$N_t[diff_t + 1] * 10000 temp_cum_infected[4, ind] = sum(SH_output$incidence[1:diff_t + 1])/SH_output$N_t[diff_t + 1] * 10000 temp_cum_death[1, ind] = WH_output$D[diff_t + 1 - time_to_death[1], 1] + WH_output$D[diff_t + 1 - time_to_death[2], 2] + WH_output$D[diff_t + 1 - time_to_death[3], 3] temp_cum_death[2, ind] = CQ_output$D[diff_t + 1 - time_to_death[1], 1] + CQ_output$D[diff_t + 1 - time_to_death[2], 2] + CQ_output$D[diff_t + 1 - time_to_death[3], 3] temp_cum_death[3, ind] = BJ_output$D[diff_t + 1 - time_to_death[1], 1] + BJ_output$D[diff_t + 1 - time_to_death[2], 2] + BJ_output$D[diff_t + 1 - time_to_death[3], 3] temp_cum_death[4, ind] = SH_output$D[diff_t + 1 - time_to_death[1], 1] + SH_output$D[diff_t + 1 - time_to_death[2], 2] + SH_output$D[diff_t + 1 - time_to_death[3], 3] temp_screening_cost[1, ind] = CQ_output$screening_counts * 16.438/1e+06 temp_screening_cost[2, ind] = BJ_output$screening_counts * 16.438/1e+06 temp_screening_cost[3, ind] = SH_output$screening_counts * 16.438/1e+06 temp_economy_loss[, ind] = temp_economy_loss[ ,ind] + GDP_loss_matrix[1,] * (milestone - quarantine_start + 1) + GDP_loss_matrix[2, ] * (SD_end_dates[2] - social_distancing_start + 1) + temp_disease_burden[ ,ind] + c(0, temp_screening_cost[ ,ind]) temp_economy_loss[ , ind] = round(temp_economy_loss[ ,ind]/1000,2) } # cum_exportion[delta_t_ind, beta_ind] = sum(WH_output$exported[1:diff_t + 1,,]) disease_burden[delta_t_ind, ,] = rowQuantiles(temp_disease_burden, probs = c(0.025, 0.5, 0.975)) cum_infected[delta_t_ind, ,] = rowQuantiles(temp_cum_infected, probs = c(0.025, 0.5, 0.975)) cum_death[delta_t_ind, ,] = rowQuantiles(temp_cum_death, probs = c(0.025, 0.5, 0.975)) screening_cost[delta_t_ind, ,] = rowQuantiles(temp_screening_cost, probs = c(0.025, 0.5, 0.975)) economy_loss[delta_t_ind, ,] = rowQuantiles(temp_economy_loss, probs = c(0.025, 0.5, 0.975)) ### change meadian to mean disease_burden[delta_t_ind, ,2] = rowMeans(temp_disease_burden) cum_infected[delta_t_ind, ,2] = rowMeans(temp_cum_infected) cum_death[delta_t_ind, ,2] = rowMeans(temp_cum_death) screening_cost[delta_t_ind, ,2] = rowMeans(temp_screening_cost) economy_loss[delta_t_ind, ,2] = rowMeans(temp_economy_loss) date[delta_t_ind] = base_line_quarantine_startdate + delta_t # date[delta_t_ind, 1] = as.Date(base_line_quarantine_startdate + delta_t) } comp_time = Sys.time() - t_init comp_time save(economy_loss, disease_burden, cum_infected, cum_death, date, delta_t_range, screening_cost, file = "vary_start_date_all_doubled_mortality.rda")
% Generated by roxygen2 (4.0.1): do not edit by hand \name{geom_widerect} \alias{geom_widerect} \title{ggplot2 geom with ymin and ymax aesthetics that covers the entire x range, useful for clickSelects background elements.} \usage{ geom_widerect(mapping = NULL, data = NULL, stat = "identity", position = "identity", ...) } \arguments{ \item{mapping}{aesthetic mapping} \item{data}{data set} \item{stat}{statistic mapping, defaults to identity} \item{position}{position mapping, defaults to identity} \item{...}{other arguments} } \value{ ggplot2 layer } \description{ ggplot2 geom with ymin and ymax aesthetics that covers the entire x range, useful for clickSelects background elements. } \examples{ \dontrun{ source(system.file("examples/WorldBank.R", package = "animint")) } }
/man/geom_widerect.Rd
no_license
cesine/animint
R
false
false
802
rd
% Generated by roxygen2 (4.0.1): do not edit by hand \name{geom_widerect} \alias{geom_widerect} \title{ggplot2 geom with ymin and ymax aesthetics that covers the entire x range, useful for clickSelects background elements.} \usage{ geom_widerect(mapping = NULL, data = NULL, stat = "identity", position = "identity", ...) } \arguments{ \item{mapping}{aesthetic mapping} \item{data}{data set} \item{stat}{statistic mapping, defaults to identity} \item{position}{position mapping, defaults to identity} \item{...}{other arguments} } \value{ ggplot2 layer } \description{ ggplot2 geom with ymin and ymax aesthetics that covers the entire x range, useful for clickSelects background elements. } \examples{ \dontrun{ source(system.file("examples/WorldBank.R", package = "animint")) } }
unemp = scan('unemp_nz_quarterly_1986Q1-2019Q2.txt') unemp = ts(unemp, frequency = 4, start = 1986) diff1 = diff(unemp) Box.test(diff1, lag = 20)
/092019TA/p43a.R
no_license
ding05/time_series
R
false
false
148
r
unemp = scan('unemp_nz_quarterly_1986Q1-2019Q2.txt') unemp = ts(unemp, frequency = 4, start = 1986) diff1 = diff(unemp) Box.test(diff1, lag = 20)
## Exploratory Data Analyis Project 1 ## source: graph2.r ## result: graph2.png ## file is being kept in the .\data directory setwd("C:\Users\x\devel\DataScience\ExploratoryDataAnalysis\ExData_Plotting1") ## Read in the data from the csv file, header values are true powdf <- read.csv("data\\household_power_consumption.txt", header=T, sep=";", stringsAsFactors=F, na.strings="?", colClasses=c("character","character","numeric","numeric","numeric","numeric","numeric","numeric","numeric")) ## convert the start/end date first then compare ## in the next statement to get subset of data we are interested in. sdttm <- strptime("01/02/2007 00:00:00", format="%d/%m/%Y %H:%M:%S", tz="UTC") edttm <- strptime("03/02/2007 00:00:00", format="%d/%m/%Y %H:%M:%S", tz="UTC") powdfsubset <- powdf[strptime(paste(powdf$Date, powdf$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") >= sdttm & strptime(paste(powdf$Date, powdf$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") <= edttm,] powdfsubset$dttm <- strptime(paste(powdfsubset$Date, powdfsubset$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") ## Initialize PNG device png(filename="graph2.png", width=500, height=500) ## create histogram plot(powdfsubset$dttm,powdfsubset$Global_active_power, xlab="", ylab="Global Active Power (kilowatts)") ## turn off the PNG device ... dev.off
/graph2.r
no_license
aeamaea/ExData_Plotting1
R
false
false
1,319
r
## Exploratory Data Analyis Project 1 ## source: graph2.r ## result: graph2.png ## file is being kept in the .\data directory setwd("C:\Users\x\devel\DataScience\ExploratoryDataAnalysis\ExData_Plotting1") ## Read in the data from the csv file, header values are true powdf <- read.csv("data\\household_power_consumption.txt", header=T, sep=";", stringsAsFactors=F, na.strings="?", colClasses=c("character","character","numeric","numeric","numeric","numeric","numeric","numeric","numeric")) ## convert the start/end date first then compare ## in the next statement to get subset of data we are interested in. sdttm <- strptime("01/02/2007 00:00:00", format="%d/%m/%Y %H:%M:%S", tz="UTC") edttm <- strptime("03/02/2007 00:00:00", format="%d/%m/%Y %H:%M:%S", tz="UTC") powdfsubset <- powdf[strptime(paste(powdf$Date, powdf$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") >= sdttm & strptime(paste(powdf$Date, powdf$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") <= edttm,] powdfsubset$dttm <- strptime(paste(powdfsubset$Date, powdfsubset$Time),format="%d/%m/%Y %H:%M:%S", tz="UTC") ## Initialize PNG device png(filename="graph2.png", width=500, height=500) ## create histogram plot(powdfsubset$dttm,powdfsubset$Global_active_power, xlab="", ylab="Global Active Power (kilowatts)") ## turn off the PNG device ... dev.off
temp <- tempfile() Url <- "https://d396qusza40orc.cloudfront.net/exdata/data/household_power_consumption.zip" download.file(Url, temp) data <- read.table(unz(temp, "household_power_consumption.txt"), sep = ";", na.strings = "?", nrows = 2880, skip = 66637)house unlink(temp) names(data) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3") data[,3:9] <- sapply(data[,3:9], as.numeric) library(lubridate) data[,1] <- dmy(data[,1]) datetime <- as.POSIXct(paste(data$Date, as.character(data$Time))) data <- cbind(data, datetime) png(file="plot2.png", width = 480, height = 480, unit = "px", bg = "white") plot(data$datetime, data$Global_active_power, type = "l", xlab ="", ylab = "Global Active Power (kilowatts)") mtext("Plot 2", side = 10, adj = 0, line = 16, at = 2, outer = TRUE) dev.off()
/plot2.R
no_license
panyvino/ExData_Plotting1
R
false
false
915
r
temp <- tempfile() Url <- "https://d396qusza40orc.cloudfront.net/exdata/data/household_power_consumption.zip" download.file(Url, temp) data <- read.table(unz(temp, "household_power_consumption.txt"), sep = ";", na.strings = "?", nrows = 2880, skip = 66637)house unlink(temp) names(data) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3") data[,3:9] <- sapply(data[,3:9], as.numeric) library(lubridate) data[,1] <- dmy(data[,1]) datetime <- as.POSIXct(paste(data$Date, as.character(data$Time))) data <- cbind(data, datetime) png(file="plot2.png", width = 480, height = 480, unit = "px", bg = "white") plot(data$datetime, data$Global_active_power, type = "l", xlab ="", ylab = "Global Active Power (kilowatts)") mtext("Plot 2", side = 10, adj = 0, line = 16, at = 2, outer = TRUE) dev.off()
# Cria um modelo preditivo usando randomForest # Este código foi criado para executar tanto no Azure, quanto no RStudio. # Para executar no Azure, altere o valor da variavel Azure para TRUE. # Se o valor for FALSE, o codigo será executado no RStudio # Obs: Caso tenha problemas com a acentuação, consulte este link: # https://support.rstudio.com/hc/en-us/articles/200532197-Character-Encoding # Configurando o diretório de trabalho # Coloque entre aspas o diretório de trabalho que você está usando no seu computador # Não use diretórios com espaço no nome # setwd("C:/FCD/BigDataRAzure/Cap14/Projeto") # getwd() # Função para tratar as datas set.asPOSIXct <- function(inFrame) { dteday <- as.POSIXct( as.integer(inFrame$dteday), origin = "1970-01-01") as.POSIXct(strptime( paste(as.character(dteday), " ", as.character(inFrame$hr), ":00:00", sep = ""), "%Y-%m-%d %H:%M:%S")) } char.toPOSIXct <- function(inFrame) { as.POSIXct(strptime( paste(inFrame$dteday, " ", as.character(inFrame$hr), ":00:00", sep = ""), "%Y-%m-%d %H:%M:%S")) } # Variável que controla a execução do script Azure <- FALSE if(Azure){ dataset$dteday <- set.asPOSIXct(dataset) }else{ bikes <- bikes } require(randomForest) model <- randomForest(cnt ~ xformWorkHr + dteday + temp + hum, data = bikes, # altere o nome do objeto data para "dataset" de estiver trabalhando no Azure ML ntree = 40, nodesize = 5) print(model)
/pt_02_regressao/Projeto/06-CreateModel.R
no_license
ralsouza/azure_machine_learning
R
false
false
1,656
r
# Cria um modelo preditivo usando randomForest # Este código foi criado para executar tanto no Azure, quanto no RStudio. # Para executar no Azure, altere o valor da variavel Azure para TRUE. # Se o valor for FALSE, o codigo será executado no RStudio # Obs: Caso tenha problemas com a acentuação, consulte este link: # https://support.rstudio.com/hc/en-us/articles/200532197-Character-Encoding # Configurando o diretório de trabalho # Coloque entre aspas o diretório de trabalho que você está usando no seu computador # Não use diretórios com espaço no nome # setwd("C:/FCD/BigDataRAzure/Cap14/Projeto") # getwd() # Função para tratar as datas set.asPOSIXct <- function(inFrame) { dteday <- as.POSIXct( as.integer(inFrame$dteday), origin = "1970-01-01") as.POSIXct(strptime( paste(as.character(dteday), " ", as.character(inFrame$hr), ":00:00", sep = ""), "%Y-%m-%d %H:%M:%S")) } char.toPOSIXct <- function(inFrame) { as.POSIXct(strptime( paste(inFrame$dteday, " ", as.character(inFrame$hr), ":00:00", sep = ""), "%Y-%m-%d %H:%M:%S")) } # Variável que controla a execução do script Azure <- FALSE if(Azure){ dataset$dteday <- set.asPOSIXct(dataset) }else{ bikes <- bikes } require(randomForest) model <- randomForest(cnt ~ xformWorkHr + dteday + temp + hum, data = bikes, # altere o nome do objeto data para "dataset" de estiver trabalhando no Azure ML ntree = 40, nodesize = 5) print(model)
\name{poolSeq-package} \alias{poolSeq-package} \alias{poolSeq} \docType{package} \title{ Analyze Pool-seq Data } \description{ The \code{poolSeq} package provides a variety of functions to simulate and analyze Pool-seq data, including estimation of the effective population size, selection coefficients and dominance parameters. } \details{ } \author{ \packageAuthor{poolSeq} Maintainer: \packageMaintainer{poolSeq} } \references{ Waples R. S.: A generalized approach for estimating effective population size from temporal changes in allele frequency, \emph{Genetics} \bold{1989}, 121, 379–391. Agresti A.: Categorical data analysis (second edition). \emph{New York: Wiley} \bold{2002} Jorde P. E. and Ryman N.: Unbiased estimator for genetic drift and effective population size, \emph{Genetics} \bold{2007}, 177 927–935. Frick K., Munk, A. and Sieling, H.: Multiscale Change-Point Inference, \emph{Journal of the Royal Statistical Society: Series B} \bold{2014}, 76, 495-580. Futschik A., Hotz T., Munk A. and Sieling H.: Multiresolution DNA partitioning: statistical evidence for segments, \emph{Bioinformatics} \bold{2014}, 30, 2255-2262. Jónás A., Taus T., Kosiol C., Schlötterer C. & Futschik A.: Estimating effective population size from temporal allele frequency changes in experimental evolution, manuscript in preparation. } \keyword{ package } \seealso{ \code{\link{wf.traj}}, \code{\link{sample.alleles}}, \code{\link{estimateNe}}, \code{\link{cmh.test}}, \code{\link{chi.sq.test}} and \code{\link{read.sync}}. } \examples{ }
/man/poolSeq-package.Rd
permissive
ThomasTaus/poolSeq
R
false
false
1,552
rd
\name{poolSeq-package} \alias{poolSeq-package} \alias{poolSeq} \docType{package} \title{ Analyze Pool-seq Data } \description{ The \code{poolSeq} package provides a variety of functions to simulate and analyze Pool-seq data, including estimation of the effective population size, selection coefficients and dominance parameters. } \details{ } \author{ \packageAuthor{poolSeq} Maintainer: \packageMaintainer{poolSeq} } \references{ Waples R. S.: A generalized approach for estimating effective population size from temporal changes in allele frequency, \emph{Genetics} \bold{1989}, 121, 379–391. Agresti A.: Categorical data analysis (second edition). \emph{New York: Wiley} \bold{2002} Jorde P. E. and Ryman N.: Unbiased estimator for genetic drift and effective population size, \emph{Genetics} \bold{2007}, 177 927–935. Frick K., Munk, A. and Sieling, H.: Multiscale Change-Point Inference, \emph{Journal of the Royal Statistical Society: Series B} \bold{2014}, 76, 495-580. Futschik A., Hotz T., Munk A. and Sieling H.: Multiresolution DNA partitioning: statistical evidence for segments, \emph{Bioinformatics} \bold{2014}, 30, 2255-2262. Jónás A., Taus T., Kosiol C., Schlötterer C. & Futschik A.: Estimating effective population size from temporal allele frequency changes in experimental evolution, manuscript in preparation. } \keyword{ package } \seealso{ \code{\link{wf.traj}}, \code{\link{sample.alleles}}, \code{\link{estimateNe}}, \code{\link{cmh.test}}, \code{\link{chi.sq.test}} and \code{\link{read.sync}}. } \examples{ }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/xtabs.R \name{collect_and_normalize_xtab} \alias{collect_and_normalize_xtab} \title{Collect data and normalize result} \usage{ collect_and_normalize_xtab(connection, disconnect = FALSE) } \arguments{ \item{connection}{SQlite connection} \item{disconnect}{Optional parameter to determine if the SQlite connection should be closed, `FALSE` by default.} } \value{ A tibble with the data in long form } \description{ Collect data and normalize result }
/man/collect_and_normalize_xtab.Rd
permissive
mountainMath/statcanXtabs
R
false
true
528
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/xtabs.R \name{collect_and_normalize_xtab} \alias{collect_and_normalize_xtab} \title{Collect data and normalize result} \usage{ collect_and_normalize_xtab(connection, disconnect = FALSE) } \arguments{ \item{connection}{SQlite connection} \item{disconnect}{Optional parameter to determine if the SQlite connection should be closed, `FALSE` by default.} } \value{ A tibble with the data in long form } \description{ Collect data and normalize result }
remove(list= ls()) options(stringsAsFactors = FALSE) options(scipen = 999) setwd("/Users/francisco06121988/Desktop/coursera_files/applied_time_series/") library(astsa);library(tidyverse) # Johnson & Johnson quarterly earnings ------------------------------------ plot(JohnsonJohnson, main = "Johnson & Johnson earnings per share", col ="red", lwd = 2, ylab = "Earnings per share") # Log return of Johnson & Johnson ----------------------------------------- jj_log_return <- diff(log(JohnsonJohnson)) jj_log_return_mean_0 <- jj_log_return - mean(jj_log_return) # Obtain time plot, ACF, and PACF ----------------------------------------- par(mfrow = c(3,1)) plot(jj_log_return_mean_0, main = "Mean 0 log returns of Johnson & Johnson shares", col = "blue", lwd = 2, ylab = "Log returns") acf(jj_log_return_mean_0, main = "ACF") pacf(jj_log_return_mean_0, main = "PACF") # Obtain the r vector ----------------------------------------------------- r <- acf(jj_log_return_mean_0, main = "ACF", plot = FALSE)$acf[2:5] # Obtain matrix R --------------------------------------------------------- R <- matrix(1,4,4) for(i in 1:4){ for(j in 1:4){ if(i!=j) R[i,j]=r[abs(i-j)] } } # Solve for sigma hat ----------------------------------------------------- phi_hat <- solve(R) %*% r # Obtain the estimate of the variance of residuals ------------------------ c_0 <- acf(jj_log_return_mean_0, type = "covariance",plot = FALSE)$acf[1] sigma_sq_hat <- c_0*(1 - sum(phi_hat*r)) sigma_sq_hat # Obtain the constant in the model ---------------------------------------- phi_0_hat <- mean(jj_log_return)*(1 - sum(phi_hat)) ##Normal mean coefficient phi_0_hat # Predictions from the model ---------------------------------------------- ##predicting diff log par(mfrow = c(1,1)) predictions <- vector(length = length(jj_log_return_mean_0), mode = "numeric") predictions <- vector(length = 83, mode = "numeric") for(i in 5:length(jj_log_return_mean_0)){ predictions[i] <- phi_0_hat + phi_hat[1]*jj_log_return[i-1] + phi_hat[2]*jj_log_return[i-2] + phi_hat[3]*jj_log_return[i-3] + phi_hat[4]*jj_log_return[i-4] } remove(i) tibble( time = 1:80, earnings = jj_log_return[4:83], predictions = predictions[4:83] )%>% gather(type, value, - time) %>% ggplot(aes(x = time, y = value, color = str_to_title(type))) + geom_line() + hrbrthemes::theme_ipsum_rc() + theme( legend.position = "bottom" ) + guides(color = guide_legend(title = "Series",title.position = "top", title.hjust = 0.5, label.position = "bottom")) + labs(x = "Time", y = "Log difference of earnings") # Back to original scale -------------------------------------------------- same_scale <- vector(length = 83, mode = "numeric") for(i in 5:length(predictions)){ same_scale[i] <- exp(predictions[i]) + JohnsonJohnson[i-1] } tibble( time = 1:83, earnings = JohnsonJohnson[2:84], predictions = same_scale[2:84] ) %>% gather( measure, value, -time ) %>% ggplot(aes(x = time, y = value, color = str_to_title(measure))) + geom_line() + hrbrthemes::theme_ipsum_rc() + theme( legend.position = "bottom" ) + guides(color = guide_legend(title = "Series",title.position = "top", title.hjust = 0.5, label.position = "bottom")) + labs(x = "Time", y = "Earnings")
/applied_time_series/Week 4 - Johnson & Johnson Earnings.R
no_license
ssh352/coursera_files
R
false
false
3,487
r
remove(list= ls()) options(stringsAsFactors = FALSE) options(scipen = 999) setwd("/Users/francisco06121988/Desktop/coursera_files/applied_time_series/") library(astsa);library(tidyverse) # Johnson & Johnson quarterly earnings ------------------------------------ plot(JohnsonJohnson, main = "Johnson & Johnson earnings per share", col ="red", lwd = 2, ylab = "Earnings per share") # Log return of Johnson & Johnson ----------------------------------------- jj_log_return <- diff(log(JohnsonJohnson)) jj_log_return_mean_0 <- jj_log_return - mean(jj_log_return) # Obtain time plot, ACF, and PACF ----------------------------------------- par(mfrow = c(3,1)) plot(jj_log_return_mean_0, main = "Mean 0 log returns of Johnson & Johnson shares", col = "blue", lwd = 2, ylab = "Log returns") acf(jj_log_return_mean_0, main = "ACF") pacf(jj_log_return_mean_0, main = "PACF") # Obtain the r vector ----------------------------------------------------- r <- acf(jj_log_return_mean_0, main = "ACF", plot = FALSE)$acf[2:5] # Obtain matrix R --------------------------------------------------------- R <- matrix(1,4,4) for(i in 1:4){ for(j in 1:4){ if(i!=j) R[i,j]=r[abs(i-j)] } } # Solve for sigma hat ----------------------------------------------------- phi_hat <- solve(R) %*% r # Obtain the estimate of the variance of residuals ------------------------ c_0 <- acf(jj_log_return_mean_0, type = "covariance",plot = FALSE)$acf[1] sigma_sq_hat <- c_0*(1 - sum(phi_hat*r)) sigma_sq_hat # Obtain the constant in the model ---------------------------------------- phi_0_hat <- mean(jj_log_return)*(1 - sum(phi_hat)) ##Normal mean coefficient phi_0_hat # Predictions from the model ---------------------------------------------- ##predicting diff log par(mfrow = c(1,1)) predictions <- vector(length = length(jj_log_return_mean_0), mode = "numeric") predictions <- vector(length = 83, mode = "numeric") for(i in 5:length(jj_log_return_mean_0)){ predictions[i] <- phi_0_hat + phi_hat[1]*jj_log_return[i-1] + phi_hat[2]*jj_log_return[i-2] + phi_hat[3]*jj_log_return[i-3] + phi_hat[4]*jj_log_return[i-4] } remove(i) tibble( time = 1:80, earnings = jj_log_return[4:83], predictions = predictions[4:83] )%>% gather(type, value, - time) %>% ggplot(aes(x = time, y = value, color = str_to_title(type))) + geom_line() + hrbrthemes::theme_ipsum_rc() + theme( legend.position = "bottom" ) + guides(color = guide_legend(title = "Series",title.position = "top", title.hjust = 0.5, label.position = "bottom")) + labs(x = "Time", y = "Log difference of earnings") # Back to original scale -------------------------------------------------- same_scale <- vector(length = 83, mode = "numeric") for(i in 5:length(predictions)){ same_scale[i] <- exp(predictions[i]) + JohnsonJohnson[i-1] } tibble( time = 1:83, earnings = JohnsonJohnson[2:84], predictions = same_scale[2:84] ) %>% gather( measure, value, -time ) %>% ggplot(aes(x = time, y = value, color = str_to_title(measure))) + geom_line() + hrbrthemes::theme_ipsum_rc() + theme( legend.position = "bottom" ) + guides(color = guide_legend(title = "Series",title.position = "top", title.hjust = 0.5, label.position = "bottom")) + labs(x = "Time", y = "Earnings")
#The 3-factor model (can follow the 3-factor notebook for more details) library(stats) library(psych) library(polycor) library(lavaan) ####### NOTES 1 THE CORRELATION MATRIX ############################ #read in the coded undergraduate response data and take the items (questions) of interest all_student_data <- read.csv('path_to_your_data_here.csv') #student_data <- all_student_data[,c(6,7,9,15,16,17,19,21,23,24)] student_data <- all_student_data[,c(6,7,15,16,17,19,21,23,24)] #Q8 dropped for KMO test #make sure the incoming data is interpreted as ordinal, not as interval - you can check that without this line, hetcor produces Pearson correlations student_data_cat <- sapply(student_data, as.factor) #apply the hetcor function which produces the polychoric correlation matrix and associated information #check for 0 cell values in contingency tables corr_info = hetcor(student_data_cat) PCM <- corr_info$cor #the correlation matrix PCM_type <- corr_info$type #the type of correlation computed for each pair - all should be polychoric PCM_assumption_test <- corr_info$tests #the p-value for each test of bivariate normality (uses pearson, want < .1) #Assessing correlation matrix as input to FA # eyeball correlations, want some but not too large # check Bartlett's test of sphericity - tests the null hypothesis that PCM is an identity matrix (reject with small p) BToS_pvalue <- cortest.bartlett(PCM, n = 82)$p.value #n is the number of samples # check for multicolinearity and singularity by checking the determinant detMtest = det(PCM) # check eigenvalues - should all be positive and not too close to zero (smoothing) eigsPCM = eigen(PCM, only.values = TRUE)$values # Kaiser-Meyer-Olkin (KMO) test of sampling adequacy KMO_summary <- KMO(PCM) ########## NOTES 2 EFA ################## ######### PART 2.1 DETERMINING NUMBER OF FACTORS TO RETAIN ####### #take a look at the eigenvalues of the correlation matrix and plot them #run the parallel analysis - which also will show you the scree plot and eigs greater than 1 fa.parallel(PCM, n.obs = 82, fm="pa", fa ="both") #note: this analysis runs 1-factor PA for many randomly simulated corr matices, it's not unusual that some warnings will be produced ######## PART 2.2 RUNNING FACTOR ANALYSIS ####### fa_3 <- fa(r = PCM, nfactors = 3, fm = "uls", rotate = "promax") ######## PART 3 CFA ######## ### 3-factor model ### #define the model model_3 <- 'F3_A =~ Q3_6 + Q3_14 + Q3_15 + Q3_18 + Q3_23 F3_B =~ Q3_5 + Q3_22 + Q3_23 F3_C =~ Q3_5 + Q3_16 + Q3_20' #we fit our model providing the entire dataset #ordinal data must be labelled as ordered; doing so will use the WLSMV estimator for (robust) test statistics fit_3 <- cfa(model_3, data = student_data, ordered = c("Q3_5","Q3_6", "Q3_14", "Q3_15", "Q3_16", "Q3_18", "Q3_20","Q3_22", "Q3_23")) #look at some output #summary(fit_1, fit.measures=TRUE) sanity_3 <- standardizedSolution(fit_3) #compare factor loadings and uniquenesses to EFA soln (double check output is sensible) #check the modifaction indices mi <- modindices(fit_3) #print(mi) ####### PART 4: RELIABILITY ########## # check ordinal alpha for the item measure, and each factor #entire survey (since we use a polychoric corr matrix, we don't have to do anything except call alpha on the correct matrix) overall_alpha <- alpha(PCM, check.keys=TRUE) #find the sub-correlation matrices associated with each factor corr_FA <- hetcor(sapply(all_student_data[,c(7,15,16,19,24)],as.factor))$cor corr_FB <- hetcor(sapply(all_student_data[,c(6,23,24)],as.factor))$cor corr_FC <- hetcor(sapply(all_student_data[,c(6,17,21)],as.factor))$cor #check their alphas alpha_A <- alpha(corr_FA) alpha_B <- alpha(corr_FB) alpha_C <- alpha(corr_FC)
/3FactorScript.R
no_license
hillary-dawkins/ValidationNotes
R
false
false
3,845
r
#The 3-factor model (can follow the 3-factor notebook for more details) library(stats) library(psych) library(polycor) library(lavaan) ####### NOTES 1 THE CORRELATION MATRIX ############################ #read in the coded undergraduate response data and take the items (questions) of interest all_student_data <- read.csv('path_to_your_data_here.csv') #student_data <- all_student_data[,c(6,7,9,15,16,17,19,21,23,24)] student_data <- all_student_data[,c(6,7,15,16,17,19,21,23,24)] #Q8 dropped for KMO test #make sure the incoming data is interpreted as ordinal, not as interval - you can check that without this line, hetcor produces Pearson correlations student_data_cat <- sapply(student_data, as.factor) #apply the hetcor function which produces the polychoric correlation matrix and associated information #check for 0 cell values in contingency tables corr_info = hetcor(student_data_cat) PCM <- corr_info$cor #the correlation matrix PCM_type <- corr_info$type #the type of correlation computed for each pair - all should be polychoric PCM_assumption_test <- corr_info$tests #the p-value for each test of bivariate normality (uses pearson, want < .1) #Assessing correlation matrix as input to FA # eyeball correlations, want some but not too large # check Bartlett's test of sphericity - tests the null hypothesis that PCM is an identity matrix (reject with small p) BToS_pvalue <- cortest.bartlett(PCM, n = 82)$p.value #n is the number of samples # check for multicolinearity and singularity by checking the determinant detMtest = det(PCM) # check eigenvalues - should all be positive and not too close to zero (smoothing) eigsPCM = eigen(PCM, only.values = TRUE)$values # Kaiser-Meyer-Olkin (KMO) test of sampling adequacy KMO_summary <- KMO(PCM) ########## NOTES 2 EFA ################## ######### PART 2.1 DETERMINING NUMBER OF FACTORS TO RETAIN ####### #take a look at the eigenvalues of the correlation matrix and plot them #run the parallel analysis - which also will show you the scree plot and eigs greater than 1 fa.parallel(PCM, n.obs = 82, fm="pa", fa ="both") #note: this analysis runs 1-factor PA for many randomly simulated corr matices, it's not unusual that some warnings will be produced ######## PART 2.2 RUNNING FACTOR ANALYSIS ####### fa_3 <- fa(r = PCM, nfactors = 3, fm = "uls", rotate = "promax") ######## PART 3 CFA ######## ### 3-factor model ### #define the model model_3 <- 'F3_A =~ Q3_6 + Q3_14 + Q3_15 + Q3_18 + Q3_23 F3_B =~ Q3_5 + Q3_22 + Q3_23 F3_C =~ Q3_5 + Q3_16 + Q3_20' #we fit our model providing the entire dataset #ordinal data must be labelled as ordered; doing so will use the WLSMV estimator for (robust) test statistics fit_3 <- cfa(model_3, data = student_data, ordered = c("Q3_5","Q3_6", "Q3_14", "Q3_15", "Q3_16", "Q3_18", "Q3_20","Q3_22", "Q3_23")) #look at some output #summary(fit_1, fit.measures=TRUE) sanity_3 <- standardizedSolution(fit_3) #compare factor loadings and uniquenesses to EFA soln (double check output is sensible) #check the modifaction indices mi <- modindices(fit_3) #print(mi) ####### PART 4: RELIABILITY ########## # check ordinal alpha for the item measure, and each factor #entire survey (since we use a polychoric corr matrix, we don't have to do anything except call alpha on the correct matrix) overall_alpha <- alpha(PCM, check.keys=TRUE) #find the sub-correlation matrices associated with each factor corr_FA <- hetcor(sapply(all_student_data[,c(7,15,16,19,24)],as.factor))$cor corr_FB <- hetcor(sapply(all_student_data[,c(6,23,24)],as.factor))$cor corr_FC <- hetcor(sapply(all_student_data[,c(6,17,21)],as.factor))$cor #check their alphas alpha_A <- alpha(corr_FA) alpha_B <- alpha(corr_FB) alpha_C <- alpha(corr_FC)
# https://stanford.edu/~wpmarble/webscraping_tutorial/webscraping_tutorial.pdf ## Webscraping tutorial # Will Marble - August 2016 # This code goes along with the tutorial found at # http://stanford.edu/~wpmarble/webscraping_tutorial/webscraping_tutorial.pdf ## Before going through this tutorial, you should download google chrome ## and the SelectorGadget chrome extension (http://selectorgadget.com/) ## Then run the following code to make sure you have all the required packages: rm(list=ls()) pkgs = c("rvest", "magrittr", "httr", "stringr", "ggplot2", "rjson") for (pkg in pkgs){ if (!require(pkg, character.only = T)){ install.packages(pkg) library(pkg) } } # simple example ---------------------------------------------------------- ## Read my example html with read_html() silly_webpage = read_html("http://stanford.edu/~wpmarble/webscraping_tutorial/html/silly_webpage.html") # get paragraphs (css selector "p") my_paragraphs = html_nodes(silly_webpage, "p") my_paragraphs # get elements with class "thisOne" -- use a period to denote class thisOne_elements = html_nodes(silly_webpage, ".thisOne") thisOne_elements # get elements with id "myDivID" -- use a hashtag to denote id myDivID_elements = html_nodes(silly_webpage, "#myDivID") myDivID_elements # extract text from myDivID_elements myDivID_text = html_text(myDivID_elements) myDivID_text # extract links from myDivID_elements. first i extract all the "a" nodes (as in a href="website.com") # and then extract the "href" attribute from those nodes myDivID_link = html_nodes(myDivID_elements, "a") %>% html_attr("href") myDivID_link # harder example ---------------------------------------------------------- # STEP 1, OUTSIDE OF R # Open that webpage on Chrome and search for the relevant set of ballot measures # (in this case, everything from 2016). Then download the page source. # I did this and saved it to my website. # STEP 2 # Use rvest to read the html file measures = read_html("http://stanford.edu/~wpmarble/webscraping_tutorial/html/ballot_measures_2016.html") # STEP 3 # Select the nodes I want -- I can use the | character to return both types of # Xpath selectors I want selector = '//*[contains(concat( " ", @class, " " ), concat( " ", "divRepeaterResults", " " ))]|//*[contains(concat( " ", @class, " " ), concat( " ", "h2Headers", " " ))]' my_nodes = measures %>% html_nodes(xpath=selector) # let's look at what we got my_nodes[1:9] # the first 6 nodes don't have information I want, so get rid of them my_nodes = my_nodes[-c(1:6)] ## work thru one entry first ## # randomly chose 128 as an example to work thru thetext = html_text(my_nodes[[128]]) # get rid of all those extra spaces thetext = gsub(pattern = "[ ]+", replacement = " ", thetext) # let's split up the string using the "\r\n \r\n" identifier plus the one field that's # not separated by two line breaks -- topic areas thetext = strsplit(thetext, split= "\r\n \r\n|\r\n Topic")[[1]] thetext # get rid of the \r\n, extra whitespace, and empty entries thetext = gsub(pattern="\\r|\\n", replacement="", thetext) %>% str_trim thetext = thetext[thetext != ""] thetext # finally extract results title = thetext[1] election = thetext[grepl(pattern = "^Election", thetext)] %>% gsub("Election:", "", x = .) %>% str_trim type = thetext[grepl(pattern = "^Type", thetext)] %>% gsub("Type:", "", x = .) %>% str_trim status = thetext[grepl(pattern = "^Status", thetext)] %>% gsub("Status:", "", x = .) %>% str_trim topic_areas = thetext[grepl(pattern = "^Area:|Areas:", thetext)] %>% gsub("Area:|Areas:", "", x = .) %>% str_trim # summary is a little trickier to get because the actual summary comes # the entry after the one that says "Summary: Click for Summary" summary_index = grep(pattern="^Summary", thetext) + 1 summary = thetext[summary_index] # we're done! print the results: for (x in c("title", "election", "type", "status", "summary", "topic_areas")){ cat(x,": ", get(x), "\n") } ## Now loop thru all our nodes ## # create state / info indicator vector state_or_info = my_nodes %>% html_attr("class") state_or_info = ifelse(state_or_info == "h2Headers", "state", "info") # set up data frame to store results results_df = data.frame(state = rep(NA_character_, length(my_nodes)), title = NA_character_, election = NA_character_, type = NA_character_, status = NA_character_, topic_areas = NA, summary = NA_character_, stringsAsFactors = F) state = NA_character_ # this variable will keep track of what state we're in # loop through all the nodes for (i in 1:length(my_nodes)){ # first see if the node tells us what state we're in; if so, update # the state variable if (state_or_info[i] == "state") { state = html_text(my_nodes[[i]]) } # if it doesn't say what state we're in, apply the parsing code from above else { results_df$state[i] = state # fill in state # parse text like above thetext = html_text(my_nodes[[i]]) thetext = gsub(pattern = "[ ]+", replacement = " ", thetext) thetext = strsplit(thetext, split= "\r\n \r\n|\r\n Topic")[[1]] thetext = gsub(pattern="\\r|\\n", replacement="", thetext) %>% str_trim thetext = thetext[thetext != ""] results_df$title[i] = thetext[1] results_df$election[i] = thetext[grepl(pattern = "^Election", thetext)] %>% gsub("Election:", "", x = .) %>% str_trim results_df$type[i] = thetext[grepl(pattern = "^Type", thetext)] %>% gsub("Type:", "", x = .) %>% str_trim results_df$status[i] = thetext[grepl(pattern = "^Status", thetext)] %>% gsub("Status:", "", x = .) %>% str_trim results_df$topic_areas[i] = thetext[grepl(pattern = "^Area:|Areas:", thetext)] %>% gsub("Area:|Areas:", "", x = .) %>% str_trim summary_index = grep(pattern="^Summary", thetext) + 1 results_df$summary[i] = thetext[summary_index] } } results_df = results_df[!is.na(results_df$state),] # let's have a look at a bit of the final product (some variables omitted for space) head(results_df) View(results_df) # Briefly on API's -------------------------------------------------------- list_of_shows = c("breaking bad", "mad men", "game of thrones", "homeland", "house of cards", "true detective", "orange is the new black", "the americans", "mr robot", "boardwalk empire", "the good wife", "dexter", "lost", "true blood", "house", "big love", "downton abbey", "damages", "boston legal", "grey's anatomy", "the sopranos", "heroes", "better call saul") show_db = data.frame(title = list_of_shows, year = NA, genre = NA, plot = NA, country = NA, awards = NA, metascore = NA, imdbrating = NA, imdbvotes = NA, imdbid = NA, totalseasons = NA) # construct the url for each show by pasting the name of the show after # the API base, and encoding using URLencode(). for (show in list_of_shows){ show_url = paste0("http://omdbapi.com/?&t=", URLencode(show, reserved = T)) show_info = read_html(show_url) %>% html_text %>% fromJSON show_db$year[show_db$title==show] = show_info$Year show_db$genre[show_db$title==show] = show_info$Genre show_db$plot[show_db$title==show] = show_info$Plot show_db$country[show_db$title==show] = show_info$Country show_db$awards[show_db$title==show] = show_info$Awards show_db$metascore[show_db$title==show] = show_info$Metascore show_db$imdbrating[show_db$title==show] = show_info$imdbRating show_db$imdbvotes[show_db$title==show] = show_info$imdbVotes show_db$imdbid[show_db$title==show] = show_info$imdbID show_db$totalseasons[show_db$title==show] = show_info$totalSeasons } show_db[1:5, c(1:3, 8)] # make a plot show_db = show_db[order(show_db$imdbrating),] show_db$title = factor(show_db$title, levels = show_db$title) ggplot(show_db, aes(x = title, y = as.numeric(imdbrating))) + geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=65, hjust=1)) + scale_y_continuous(breaks = seq(0, 10, 1)) + coord_cartesian(ylim = c(0, 10)) + labs(x = NULL, y = "IMDb rating")
/webscaping1/webscraping_example.R
no_license
106035007/Text-Mining
R
false
false
8,361
r
# https://stanford.edu/~wpmarble/webscraping_tutorial/webscraping_tutorial.pdf ## Webscraping tutorial # Will Marble - August 2016 # This code goes along with the tutorial found at # http://stanford.edu/~wpmarble/webscraping_tutorial/webscraping_tutorial.pdf ## Before going through this tutorial, you should download google chrome ## and the SelectorGadget chrome extension (http://selectorgadget.com/) ## Then run the following code to make sure you have all the required packages: rm(list=ls()) pkgs = c("rvest", "magrittr", "httr", "stringr", "ggplot2", "rjson") for (pkg in pkgs){ if (!require(pkg, character.only = T)){ install.packages(pkg) library(pkg) } } # simple example ---------------------------------------------------------- ## Read my example html with read_html() silly_webpage = read_html("http://stanford.edu/~wpmarble/webscraping_tutorial/html/silly_webpage.html") # get paragraphs (css selector "p") my_paragraphs = html_nodes(silly_webpage, "p") my_paragraphs # get elements with class "thisOne" -- use a period to denote class thisOne_elements = html_nodes(silly_webpage, ".thisOne") thisOne_elements # get elements with id "myDivID" -- use a hashtag to denote id myDivID_elements = html_nodes(silly_webpage, "#myDivID") myDivID_elements # extract text from myDivID_elements myDivID_text = html_text(myDivID_elements) myDivID_text # extract links from myDivID_elements. first i extract all the "a" nodes (as in a href="website.com") # and then extract the "href" attribute from those nodes myDivID_link = html_nodes(myDivID_elements, "a") %>% html_attr("href") myDivID_link # harder example ---------------------------------------------------------- # STEP 1, OUTSIDE OF R # Open that webpage on Chrome and search for the relevant set of ballot measures # (in this case, everything from 2016). Then download the page source. # I did this and saved it to my website. # STEP 2 # Use rvest to read the html file measures = read_html("http://stanford.edu/~wpmarble/webscraping_tutorial/html/ballot_measures_2016.html") # STEP 3 # Select the nodes I want -- I can use the | character to return both types of # Xpath selectors I want selector = '//*[contains(concat( " ", @class, " " ), concat( " ", "divRepeaterResults", " " ))]|//*[contains(concat( " ", @class, " " ), concat( " ", "h2Headers", " " ))]' my_nodes = measures %>% html_nodes(xpath=selector) # let's look at what we got my_nodes[1:9] # the first 6 nodes don't have information I want, so get rid of them my_nodes = my_nodes[-c(1:6)] ## work thru one entry first ## # randomly chose 128 as an example to work thru thetext = html_text(my_nodes[[128]]) # get rid of all those extra spaces thetext = gsub(pattern = "[ ]+", replacement = " ", thetext) # let's split up the string using the "\r\n \r\n" identifier plus the one field that's # not separated by two line breaks -- topic areas thetext = strsplit(thetext, split= "\r\n \r\n|\r\n Topic")[[1]] thetext # get rid of the \r\n, extra whitespace, and empty entries thetext = gsub(pattern="\\r|\\n", replacement="", thetext) %>% str_trim thetext = thetext[thetext != ""] thetext # finally extract results title = thetext[1] election = thetext[grepl(pattern = "^Election", thetext)] %>% gsub("Election:", "", x = .) %>% str_trim type = thetext[grepl(pattern = "^Type", thetext)] %>% gsub("Type:", "", x = .) %>% str_trim status = thetext[grepl(pattern = "^Status", thetext)] %>% gsub("Status:", "", x = .) %>% str_trim topic_areas = thetext[grepl(pattern = "^Area:|Areas:", thetext)] %>% gsub("Area:|Areas:", "", x = .) %>% str_trim # summary is a little trickier to get because the actual summary comes # the entry after the one that says "Summary: Click for Summary" summary_index = grep(pattern="^Summary", thetext) + 1 summary = thetext[summary_index] # we're done! print the results: for (x in c("title", "election", "type", "status", "summary", "topic_areas")){ cat(x,": ", get(x), "\n") } ## Now loop thru all our nodes ## # create state / info indicator vector state_or_info = my_nodes %>% html_attr("class") state_or_info = ifelse(state_or_info == "h2Headers", "state", "info") # set up data frame to store results results_df = data.frame(state = rep(NA_character_, length(my_nodes)), title = NA_character_, election = NA_character_, type = NA_character_, status = NA_character_, topic_areas = NA, summary = NA_character_, stringsAsFactors = F) state = NA_character_ # this variable will keep track of what state we're in # loop through all the nodes for (i in 1:length(my_nodes)){ # first see if the node tells us what state we're in; if so, update # the state variable if (state_or_info[i] == "state") { state = html_text(my_nodes[[i]]) } # if it doesn't say what state we're in, apply the parsing code from above else { results_df$state[i] = state # fill in state # parse text like above thetext = html_text(my_nodes[[i]]) thetext = gsub(pattern = "[ ]+", replacement = " ", thetext) thetext = strsplit(thetext, split= "\r\n \r\n|\r\n Topic")[[1]] thetext = gsub(pattern="\\r|\\n", replacement="", thetext) %>% str_trim thetext = thetext[thetext != ""] results_df$title[i] = thetext[1] results_df$election[i] = thetext[grepl(pattern = "^Election", thetext)] %>% gsub("Election:", "", x = .) %>% str_trim results_df$type[i] = thetext[grepl(pattern = "^Type", thetext)] %>% gsub("Type:", "", x = .) %>% str_trim results_df$status[i] = thetext[grepl(pattern = "^Status", thetext)] %>% gsub("Status:", "", x = .) %>% str_trim results_df$topic_areas[i] = thetext[grepl(pattern = "^Area:|Areas:", thetext)] %>% gsub("Area:|Areas:", "", x = .) %>% str_trim summary_index = grep(pattern="^Summary", thetext) + 1 results_df$summary[i] = thetext[summary_index] } } results_df = results_df[!is.na(results_df$state),] # let's have a look at a bit of the final product (some variables omitted for space) head(results_df) View(results_df) # Briefly on API's -------------------------------------------------------- list_of_shows = c("breaking bad", "mad men", "game of thrones", "homeland", "house of cards", "true detective", "orange is the new black", "the americans", "mr robot", "boardwalk empire", "the good wife", "dexter", "lost", "true blood", "house", "big love", "downton abbey", "damages", "boston legal", "grey's anatomy", "the sopranos", "heroes", "better call saul") show_db = data.frame(title = list_of_shows, year = NA, genre = NA, plot = NA, country = NA, awards = NA, metascore = NA, imdbrating = NA, imdbvotes = NA, imdbid = NA, totalseasons = NA) # construct the url for each show by pasting the name of the show after # the API base, and encoding using URLencode(). for (show in list_of_shows){ show_url = paste0("http://omdbapi.com/?&t=", URLencode(show, reserved = T)) show_info = read_html(show_url) %>% html_text %>% fromJSON show_db$year[show_db$title==show] = show_info$Year show_db$genre[show_db$title==show] = show_info$Genre show_db$plot[show_db$title==show] = show_info$Plot show_db$country[show_db$title==show] = show_info$Country show_db$awards[show_db$title==show] = show_info$Awards show_db$metascore[show_db$title==show] = show_info$Metascore show_db$imdbrating[show_db$title==show] = show_info$imdbRating show_db$imdbvotes[show_db$title==show] = show_info$imdbVotes show_db$imdbid[show_db$title==show] = show_info$imdbID show_db$totalseasons[show_db$title==show] = show_info$totalSeasons } show_db[1:5, c(1:3, 8)] # make a plot show_db = show_db[order(show_db$imdbrating),] show_db$title = factor(show_db$title, levels = show_db$title) ggplot(show_db, aes(x = title, y = as.numeric(imdbrating))) + geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=65, hjust=1)) + scale_y_continuous(breaks = seq(0, 10, 1)) + coord_cartesian(ylim = c(0, 10)) + labs(x = NULL, y = "IMDb rating")
library(dplyr) library(reshape2) # ------------------------------------------------------------------------------ # solution to problem 2 # This problem focuses on Baltimore City, Maryland. We want to determine if the # total emissions from PM2.5 has decreased in Baltimore during the period of # this study. Problem2 <- function(to.png = TRUE) { # read in the data files if (!exists('NEI')) NEI <- readRDS("summarySCC_PM25.rds") if (!exists('SCC')) SCC <- readRDS("Source_Classification_Code.rds") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Group the data frame by the year and city grouped.nei <- filter(NEI, fips == '24510') %>% group_by(year) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # open the png plot device if (to.png) png('plot2.png', width = 720, height = 720) # plot the sum of the emissions by the year # this is done implicitly because the data is grouped by year. Therefore, the # summarise function returns a data frame with two columns whcih can directly # be plotted summary <- summarise(grouped.nei, emissions = sum(Emissions)/1e3) plot(summary, xlab = 'Year', ylab = 'Total emmisions [thousands of tons]', main = expression(paste('Total emissions of PM'[2.5], ' by year in Baltimore City, MD')), ylim = c(0.0, 5.3), pch = 20) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # perform linear fit to data linear.model <- lm(emissions ~ year, summary) abline(linear.model, lwd = 2) # compute the confidence interval smoother <- data.frame(year = seq(min(summary$year), max(summary$year), 0.1)) conf.interval <- predict(linear.model, newdata=smoother, interval="confidence") # conf.interval <- predict(linear.model, interval="confidence") matlines(smoother[, 'year'], conf.interval[, c('lwr', 'upr')], col='blue', lty=2) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # extract the slope and R^2 value from the fit slope <- summary(linear.model)[['coefficients']]['year', 'Estimate'] slope.uncert <- summary(linear.model)[['coefficients']]['year', 'Std. Error'] adj.r.squared <- summary(linear.model)[['adj.r.squared']] p.value <- summary(linear.model)$coef[2,4] # create labels and draw them to the plot slope.label <- bquote(Slope == .(format(slope, digits = 2)) %+-% .(format(slope.uncert, digits = 2))) adj.r.sq.label <- bquote(Adj.~italic(R)^2 == .(format(adj.r.squared, digits = 2))) p.value.label <- bquote(italic(p) == .(format(p.value, digits = 2))) x.pos <- 2005.5 y.pos <- 5.1 y.spacing <- 0.40 text(x.pos, y.pos, slope.label , adj = c(0,0)); y.pos <- y.pos - y.spacing text(x.pos, y.pos, adj.r.sq.label, adj = c(0,0)); y.pos <- y.pos - y.spacing text(x.pos, y.pos, p.value.label , adj = c(0,0)); y.pos <- y.pos - y.spacing # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (to.png) dev.off() } Problem2()
/ExploratoryDataAnalysis/Project2/Problem2.R
no_license
bdjackson/CourseraDataScience
R
false
false
3,258
r
library(dplyr) library(reshape2) # ------------------------------------------------------------------------------ # solution to problem 2 # This problem focuses on Baltimore City, Maryland. We want to determine if the # total emissions from PM2.5 has decreased in Baltimore during the period of # this study. Problem2 <- function(to.png = TRUE) { # read in the data files if (!exists('NEI')) NEI <- readRDS("summarySCC_PM25.rds") if (!exists('SCC')) SCC <- readRDS("Source_Classification_Code.rds") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Group the data frame by the year and city grouped.nei <- filter(NEI, fips == '24510') %>% group_by(year) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # open the png plot device if (to.png) png('plot2.png', width = 720, height = 720) # plot the sum of the emissions by the year # this is done implicitly because the data is grouped by year. Therefore, the # summarise function returns a data frame with two columns whcih can directly # be plotted summary <- summarise(grouped.nei, emissions = sum(Emissions)/1e3) plot(summary, xlab = 'Year', ylab = 'Total emmisions [thousands of tons]', main = expression(paste('Total emissions of PM'[2.5], ' by year in Baltimore City, MD')), ylim = c(0.0, 5.3), pch = 20) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # perform linear fit to data linear.model <- lm(emissions ~ year, summary) abline(linear.model, lwd = 2) # compute the confidence interval smoother <- data.frame(year = seq(min(summary$year), max(summary$year), 0.1)) conf.interval <- predict(linear.model, newdata=smoother, interval="confidence") # conf.interval <- predict(linear.model, interval="confidence") matlines(smoother[, 'year'], conf.interval[, c('lwr', 'upr')], col='blue', lty=2) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # extract the slope and R^2 value from the fit slope <- summary(linear.model)[['coefficients']]['year', 'Estimate'] slope.uncert <- summary(linear.model)[['coefficients']]['year', 'Std. Error'] adj.r.squared <- summary(linear.model)[['adj.r.squared']] p.value <- summary(linear.model)$coef[2,4] # create labels and draw them to the plot slope.label <- bquote(Slope == .(format(slope, digits = 2)) %+-% .(format(slope.uncert, digits = 2))) adj.r.sq.label <- bquote(Adj.~italic(R)^2 == .(format(adj.r.squared, digits = 2))) p.value.label <- bquote(italic(p) == .(format(p.value, digits = 2))) x.pos <- 2005.5 y.pos <- 5.1 y.spacing <- 0.40 text(x.pos, y.pos, slope.label , adj = c(0,0)); y.pos <- y.pos - y.spacing text(x.pos, y.pos, adj.r.sq.label, adj = c(0,0)); y.pos <- y.pos - y.spacing text(x.pos, y.pos, p.value.label , adj = c(0,0)); y.pos <- y.pos - y.spacing # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (to.png) dev.off() } Problem2()
library("depmixS4") library(parallel) library(plyr) getwd() setwd("\Users\kali\Documents") data <- read.table("Dataset3.txt",header = TRUE, sep = ",") data$day <- as.POSIXlt(data$Date,format = "%d/%m/%Y")$wday #Q2 sundayNights <- data[data$day == 0 & strptime(data$Time,"%H:%M:%S") >= strptime("21:00:00","%H:%M:%S") & strptime(data$Time,"%H:%M:%S") < strptime("24:00:00","%H:%M:%S"),] sundayNights <- sundayNights[order(as.Date(sundayNights$Date, format = "%d/%m/%Y"), strptime(sundayNights$Time,"%H:%M:%S")),] GAP_GRP_cor <- cor(sundayNights$Global_active_power, sundayNights$Global_reactive_power, method = "pearson") GAP_Vol_cor <- cor(sundayNights$Global_active_power, sundayNights$Voltage, method = "pearson") GAP_GI_cor <- cor(sundayNights$Global_active_power, sundayNights$Global_intensity, method = "pearson") Nmin <- 2 Nmax <- 20 Nstates <- Nmin:Nmax BIC <- vector("list", Nmax - Nmin + 1) ct <- count(sundayNights, "Date") ct <- ct[order(as.Date(ct$Date, format = "%d/%m/%Y")),] set.seed(2) for (n in Nstates) { mod <- depmix(response = Global_active_power ~ 1, data = sundayNights, nstates = n, ntimes = ct$freq) fm <- fit(mod) BIC[[n-Nmin+1]] <- BIC(fm) } plot(Nstates, BIC, ty="b")
/CMPT318/CMPT 318 R workspace/Assignment2Final/Group_15_Assignment_2_Q2.R
no_license
alik604/Classes
R
false
false
1,237
r
library("depmixS4") library(parallel) library(plyr) getwd() setwd("\Users\kali\Documents") data <- read.table("Dataset3.txt",header = TRUE, sep = ",") data$day <- as.POSIXlt(data$Date,format = "%d/%m/%Y")$wday #Q2 sundayNights <- data[data$day == 0 & strptime(data$Time,"%H:%M:%S") >= strptime("21:00:00","%H:%M:%S") & strptime(data$Time,"%H:%M:%S") < strptime("24:00:00","%H:%M:%S"),] sundayNights <- sundayNights[order(as.Date(sundayNights$Date, format = "%d/%m/%Y"), strptime(sundayNights$Time,"%H:%M:%S")),] GAP_GRP_cor <- cor(sundayNights$Global_active_power, sundayNights$Global_reactive_power, method = "pearson") GAP_Vol_cor <- cor(sundayNights$Global_active_power, sundayNights$Voltage, method = "pearson") GAP_GI_cor <- cor(sundayNights$Global_active_power, sundayNights$Global_intensity, method = "pearson") Nmin <- 2 Nmax <- 20 Nstates <- Nmin:Nmax BIC <- vector("list", Nmax - Nmin + 1) ct <- count(sundayNights, "Date") ct <- ct[order(as.Date(ct$Date, format = "%d/%m/%Y")),] set.seed(2) for (n in Nstates) { mod <- depmix(response = Global_active_power ~ 1, data = sundayNights, nstates = n, ntimes = ct$freq) fm <- fit(mod) BIC[[n-Nmin+1]] <- BIC(fm) } plot(Nstates, BIC, ty="b")
# # # # # # # Analysing the data set provided by Hilary Kennedy # Jordi F. Pagès # 20-03-2019 # University of Barcelona # # # # # # # # # # # # # # # # # # # # # # # # # # # # Loading the data clean and corrected # # # # # # # # # # # # # # # # # # # # # # source("01_DataImport&Corrections_CarbonReview.R") library(gridExtra) library(patchwork) # library(cowplot) # # # # # # # # # # # # # # # # # # # # # # Data visualisation of Carbon stocks ---- # # # # # # # # # # # # # # # # # # # # # # HISTOGRAM OF CSTOCKS ---- # Histogram for 0-20 cstocks %>% ggplot() + geom_histogram(aes(Stock_0_20cm), binwidth = 10, fill = "#9FDA3AFF") + xlab("Carbon stock 0-20 cm") + theme_bw() # ggsave("Figs/Cstocks_histogram_0_20cm.pdf") # Histogram for 20-50 cstocks %>% ggplot() + geom_histogram(aes(Stock_20_50cm), binwidth = 10, fill = "#9FDA3AFF") + xlab("Carbon stock 20-50 cm") + theme_bw() # ggsave("Figs/Cstocks_histogram_20_50cm.pdf") # Histograms all together in the same plot (for that we need to gather (tidy) the data set) cstocks_tidy <- cstocks %>% select(-Stock_20_50cm_estimate) %>% gather(key = depth, value = cstocks, Stock_0_20cm:Stock_20_50cm) cstocks_tidy %>% filter(depth != "Stock_0_50cm") %>% ggplot() + geom_histogram(aes(cstocks, fill = depth, colour = depth), alpha = 0.5) + theme_bw() # ggsave("Figs/Cstocks_histogram_allDepths_same_plot.pdf") # BARPLOT PER SPECIES (COUNT) ---- cstocks %>% mutate(Species = factor(Species) %>% fct_infreq() %>% fct_rev()) %>% filter(Meadow_type == "monospecific") %>% group_by(Species) %>% summarise(n = n()) %>% ggplot() + geom_bar(aes(x = Species, y = n), stat = "identity") + geom_text(aes(x = Species, y = n, label = str_c("(", n, ")")), nudge_y = 6, size = 3) + ylab("count") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.y = element_text(face = "italic")) # ggsave("Figs/CoreCount_by_Species.pdf") # BARPLOT PER SPECIES PERCENT ---- cstocks %>% mutate(Species = factor(Species) %>% fct_infreq() %>% fct_rev()) %>% filter(Meadow_type == "monospecific") %>% group_by(Species) %>% summarise(n = n()) %>% mutate(percent = 100*(n/sum(n))) %>% ggplot() + geom_bar(aes(x = Species, y = percent), stat = "identity") + geom_text(aes(x = Species, y = percent, label = str_c(round(percent), "%")), nudge_y = 1, size = 3) + ylab("%") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.y = element_text(face = "italic")) # ggsave("Figs/CoreCountPercent_by_Species.pdf") # BARPLOT PER COUNTRY ---- cstocks %>% mutate(Country = factor(Country) %>% fct_infreq() %>% fct_rev()) %>% filter(!is.na(Country)) %>% group_by(Country) %>% summarise(n = n()) %>% ggplot() + geom_bar(aes(x = Country, y = n), stat = "identity") + geom_text(aes(x = Country, y = n, label = str_c("(", n, ")")), nudge_y = 15, size = 3) + ylab("count") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # ggsave("Figs/CountryCount.pdf") # BARPLOT PER COUNTRY PERCENT ---- cstocks %>% mutate(Country = factor(Country) %>% fct_infreq() %>% fct_rev()) %>% filter(!is.na(Country)) %>% group_by(Country) %>% summarise(n = n()) %>% mutate(percent = 100*(n/sum(n))) %>% ggplot() + geom_bar(aes(x = Country, y = percent), stat = "identity") + geom_text(aes(x = Country, y = percent, label = str_c(round(percent), "%")), nudge_y = 3, size = 3) + ylab("%") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # ggsave("Figs/CountryPercent.pdf") # MAP OF CORES BY COUNTRY ---- cstocksCountry <- cstocks %>% group_by(Country) %>% filter(!is.na(Country)) %>% summarise(n = n()) unique(cstocksCountry$Country) map.world <- map_data('world') unique(map.world$region) # Checking potential join mismatches cstocksCountry %>% anti_join(map.world, by = c('Country' = 'region')) %>% print(n = Inf) # Ok, no mismatches. Useful to see what will not be joined. In this case, nothing. Everything will be joined. # So we can proceed with the left_join map.cstocks <- left_join(map.world, cstocksCountry, by = c('region' = 'Country')) # Map of number of cores per country ggplot(map.cstocks, aes(x = long, y = lat, group = group )) + geom_polygon(aes(fill = n)) + # scale_fill_gradientn(colours = brewer.pal(5, "YlOrRd"), trans = "log10", na.value = "#d0d0d0") + # scale_fill_gradientn(colours = rev(c("#9FDA3AFF", "#4AC16DFF", "#1FA187FF", "#277F8EFF", "#365C8DFF", # "#46337EFF")), trans = "log10", na.value = "#d0d0d0") + # scale_fill_gradientn(colours = brewer.pal(5, "Blues"), trans = "log10") + # theme_minimal() labs(fill = '', x = NULL, y = NULL) + theme(text = element_text(color = '#EEEEEE'), axis.ticks = element_blank(), axis.text = element_blank(), panel.grid = element_blank(), panel.background = element_rect(fill = '#787878'), plot.background = element_rect(fill = '#787878'), legend.position = c(.18,.36) , legend.background = element_blank(), legend.key = element_blank()) # ggsave(filename = "Figs/CountryMap.pdf") # MAPPING INDIVIDUAL CORES WITH GGMAP ---- # From https://lucidmanager.org/geocoding-with-ggmap/ library(ggmap) # Now, to use Google API you have to be registered (include a credit card) and get an API key. See below. api <- readLines("google.api") # Text file with the API key register_google(key = api) getOption("ggmap") has_google_key() # To check we don't exceed the day_limit that Google imposes (2500) geocodeQueryCheck() #### Successful trial with https://blog.dominodatalab.com/geographic-visualization-with-rs-ggmaps/ # We get the lat lon coordinates in a df Df_coord <- cstocks %>% select(Latitude, Longitude) %>% group_by(Latitude, Longitude) %>% summarise(Samples = n()) # We build a world map from google Map <- ggmap(ggmap = get_googlemap(center = c(lon = 10, lat = 0), zoom = 1, style = c(feature="all",element="labels",visibility="off"), maptype = "roadmap", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Map # We plot the frequency of samples per coordinate combination as 'bubbles' Map + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude, size = Samples), col="#365C8DFF", alpha=0.4) + scale_size(range = range(sqrt(Df_coord$Samples))) + scale_y_continuous(limits = c(-70,70)) + theme_bw() # ggsave("Figs/CoreMapBubbles.pdf") # Just plotting the points Map + geom_jitter(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col= "#0063ad", alpha=0.2, width = 1, height = 1) + scale_y_continuous(limits = c(-55,70), breaks = c(-50, -25, 25, 50, 75)) + theme_bw() + xlab("Longitude (º)") + ylab("Latitude (º)") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), text = element_text(size = 12)) ggsave("Figs/Final_Figures_March2021/GlobalCoreMapPointsNEW_sized.png", width = 180, height = 110, units = "mm", dpi = 350) # MAPPING INDIVIDUAL CORES IN GGMAP ZOOMING IN EACH REGION ---- # Europe MapEurope <- ggmap(ggmap = get_googlemap(center = c(lon = 10, lat = 50), zoom = 4, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Europe <- MapEurope + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + scale_y_continuous(limits = c(35,60)) + scale_x_continuous(limits = c(-10,30)) + theme_bw() # N.America MapAmerica <- ggmap(ggmap = get_googlemap(center = c(lon = -100, lat = 40), zoom = 3, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_America <- MapAmerica + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(15,50)) + # scale_x_continuous(limits = c(-125,-65)) + theme_bw() # Brasil MapBrasil <- ggmap(ggmap = get_googlemap(center = c(lon = -50, lat = -20), zoom = 4, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Brasil <- MapBrasil + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # Arabia MapArabia <- ggmap(ggmap = get_googlemap(center = c(lon = 45, lat = 25), zoom = 5, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Arabia <- MapArabia + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # Australia MapAustralia <- ggmap(ggmap = get_googlemap(center = c(lon = 133, lat = -28), zoom = 4, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Australia <- MapAustralia + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # Asia MapAsia <- ggmap(ggmap = get_googlemap(center = c(lon = 120, lat = 25), zoom = 3, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Asia <- MapAsia + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # General map # zooms <- grid.arrange(Cstocks_America, # Cstocks_Europe, # Cstocks_Asia, # Cstocks_Brasil, # Cstocks_Arabia, # Cstocks_Australia, # nrow = 2, top = "") patchwork <- Cstocks_America + Cstocks_Europe + Cstocks_Asia + Cstocks_Brasil + Cstocks_Arabia + Cstocks_Australia + plot_annotation(tag_levels = 'A') patchwork & xlab("Longitude") & ylab("Latitude") # ggsave("Figs/Core_coordinates_MapZoom_Points.pdf") # CSTOCKS PER SPECIES FACET PLOT ---- source('reorder_within_function.R') cstocks_tidy <- cstocks %>% select(-Stock_20_50cm_estimate) %>% gather(key = depth, value = cstocks, Stock_0_20cm:Stock_20_50cm) # ggplot(iris_gathered, aes(reorder_within(Species, value, metric), value)) + #' geom_boxplot() + #' scale_x_reordered() + #' facet_wrap(~ metric, scales = "free_x") ### WORKING ON THIS!!! NOW HAVE TO REORDER cstocks_tidy %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = Species, y = cstocks), fill = "#9FDA3AFF") + scale_y_reordered() + coord_flip() + xlab("Species") + ylab("Carbon stock") + facet_grid(~depth, scales = "free_x") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_facet_depths.pdf", width = 12, height = 6) # CSTOCKS PER SPECIES grid.arrange PLOT ---- p1 <- cstocks %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_20cm, FUN = median), y = Stock_0_20cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 0-20 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) p2 <- cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_20_50cm, FUN = median), y = Stock_20_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("") + ylab("Carbon stock 20-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) p3 <- cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_50cm, FUN = median), y = Stock_0_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("") + ylab("Carbon stock 0-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) ml <- grid.arrange(p1, p2, p3, widths = c(2,2,2), nrow = 1, top = "") # ggsave("Figs/Cstocks_by_Species_grid.arrange_depths.pdf", plot = ml, width = 12, height = 6) # CSTOCKS PER SPECIES ---- # Boxplots cstocks 0-20 cm cstocks %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_20cm, FUN = median), y = Stock_0_20cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 0-20 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_0_20cm.pdf") # Boxplots cstocks 0-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_50cm, FUN = median), y = Stock_0_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 0-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_0_50cm.pdf") # Boxplots cstocks 20-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_20_50cm, FUN = median), y = Stock_20_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 20-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_20_50cm.pdf") # CSTOCKS PER GENUS ---- # Boxplots cstocks 0-20 cm cstocks %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = reorder(Genus, Stock_0_20cm, FUN = median), y = Stock_0_20cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Genus") + ylab("Carbon stock 0-20 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Genus_0_20cm.pdf") # Boxplots cstocks 0-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Genus, Stock_0_50cm, FUN = median), y = Stock_0_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Genus") + ylab("Carbon stock 0-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Genus_0_50cm.pdf") # Boxplots cstocks 20-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Genus, Stock_20_50cm, FUN = median), y = Stock_20_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Genus") + ylab("Carbon stock 20-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Genus_20_50cm.pdf") # CSTOCKS PER MEADOW TYPE ---- # Boxplots cstocks 0-20 cm cstocks %>% ggplot() + geom_boxplot(aes(x = Meadow_type, y = Stock_0_20cm), fill = "#9FDA3AFF") + xlab("Meadow type") + ylab("Carbon stock 0-20 cm") + coord_flip() + theme_bw() # ggsave("Figs/Cstocks_meadowtype_0_20cm.pdf") # Boxplots cstocks 0-50 cm cstocks %>% ggplot() + geom_boxplot(aes(x = Meadow_type, y = Stock_0_50cm), fill = "#9FDA3AFF") + xlab("Meadow type") + ylab("Carbon stock 0-50 cm") + coord_flip() + theme_bw() # ggsave("Figs/Cstocks_meadowtype_0_50cm.pdf") # Boxplots cstocks 20-50 cm cstocks %>% ggplot() + geom_boxplot(aes(x = Meadow_type, y = Stock_20_50cm), fill = "#9FDA3AFF") + xlab("Meadow type") + ylab("Carbon stock 20-50 cm") + coord_flip() + theme_bw() # ggsave("Figs/Cstocks_meadowtype_20_50cm.pdf") # DELTA13C PER SPECIES ---- # Boxplots delta13C 0-20 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(d13C_0_20cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, d13C_0_20cm, FUN = median), y = d13C_0_20cm), fill = "#1FA187FF") + coord_flip() + xlab("Species") + ylab(bquote(delta*"13C 0-20 cm")) + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/delta13C_by_Species_0_20cm.pdf") # Boxplots delta13C 0-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(d13C_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, d13C_0_50cm, FUN = median), y = d13C_0_50cm), fill = "#1FA187FF") + coord_flip() + xlab("Species") + ylab(bquote(delta*"13C 0-50 cm")) + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/delta13C_by_Species_0_50cm.pdf") # Boxplots delta13C 20-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(d13C_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, d13C_20_50cm, FUN = median), y = d13C_20_50cm), fill = "#1FA187FF") + coord_flip() + xlab("Species") + ylab(bquote(delta*"13C 20-50 cm")) + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/delta13C_by_Species_20_50cm.pdf") # # # # # # # # # # # # # # # # # # # # # # Data visualisation of Plant traits ---- # # # # # # # # # # # # # # # # # # # # # # ABOVEGROUND BIOMASS PER SPECIES ---- # Dotplots mean aboveground biomass cstocks_traits %>% filter(!is.na(Mean_aboveground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Mean_aboveground_biomass, FUN = mean), y = Mean_aboveground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Mean_aboveground_biomass, FUN = mean), ymin=Mean_aboveground_biomass-SE_Mean_aboveground_biomass, ymax=Mean_aboveground_biomass+SE_Mean_aboveground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Mean_aboveground_biomass, FUN = mean), y = Mean_aboveground_biomass+SE_Mean_aboveground_biomass, label = str_c("n = ", N_Mean_aboveground_biomass)), nudge_y = 50, size = 3) + coord_flip() + xlab("Species") + ylab("Mean aboveground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MeanAbovegroundB_by_Species_.pdf") # Dotplots max aboveground biomass cstocks_traits %>% filter(!is.na(Max_aboveground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Max_aboveground_biomass, FUN = mean), y = Max_aboveground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Max_aboveground_biomass, FUN = mean), ymin=Max_aboveground_biomass-SE_Max_aboveground_biomass, ymax=Max_aboveground_biomass+SE_Max_aboveground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Max_aboveground_biomass, FUN = mean), y = Max_aboveground_biomass+SE_Max_aboveground_biomass, label = str_c("n = ", N_Max_aboveground_biomass)), nudge_y = 100, size = 3) + coord_flip() + xlab("Species") + ylab("Max aboveground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MaxAbovegroundB_by_Species_.pdf") # BELOWGROUND BIOMASS PER SPECIES ---- # Dotplots max aboveground biomass cstocks_traits %>% filter(!is.na(Mean_belowground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Mean_belowground_biomass, FUN = mean), y = Mean_belowground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Mean_belowground_biomass, FUN = mean), ymin=Mean_belowground_biomass-SE_Mean_belowground_biomass, ymax=Mean_belowground_biomass+SE_Mean_belowground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Mean_belowground_biomass, FUN = mean), y = Mean_belowground_biomass+SE_Mean_belowground_biomass, label = str_c("n = ", N_Mean_belowground_biomass)), nudge_y = 150, size = 3) + coord_flip() + xlab("Species") + ylab("Mean belowground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MeanBelowgroundB_by_Species_.pdf") # Dotplots mean aboveground biomass cstocks_traits %>% filter(!is.na(Max_belowground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Max_belowground_biomass, FUN = mean), y = Max_belowground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Max_belowground_biomass, FUN = mean), ymin=Max_belowground_biomass-SE_Max_belowground_biomass, ymax=Max_belowground_biomass+SE_Max_belowground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Max_belowground_biomass, FUN = mean), y = Max_belowground_biomass, label = str_c("n = ", N_Max_belowground_biomass)), nudge_y = 550, size = 3) + coord_flip() + xlab("Species") + ylab("Max belowground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MaxBelowgroundB_by_Species_.pdf") # ROOT:SHOOT RATIO PER SPECIES ---- cstocks_traits %>% filter(!is.na(Root_shoot_ratio)) %>% ggplot() + geom_point(aes(x = reorder(Species, Root_shoot_ratio, FUN = mean), y = Root_shoot_ratio), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Root_shoot_ratio, FUN = mean), ymin=Root_shoot_ratio-SE_Root_shoot_ratio, ymax=Root_shoot_ratio+SE_Root_shoot_ratio), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Root_shoot_ratio, FUN = mean), y = Root_shoot_ratio+SE_Root_shoot_ratio, label = str_c("n = ", N_Max_belowground_biomass)), nudge_y = 1, size = 3) + coord_flip() + xlab("Species") + ylab("Root:Shoot ratio") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/RootShootRatio_by_Species_.pdf") #########################
/02_ExploratoryDataVis_CarbonReview.R
no_license
jordipages-repo/seagrass_Cstocks_pub
R
false
false
24,494
r
# # # # # # # Analysing the data set provided by Hilary Kennedy # Jordi F. Pagès # 20-03-2019 # University of Barcelona # # # # # # # # # # # # # # # # # # # # # # # # # # # # Loading the data clean and corrected # # # # # # # # # # # # # # # # # # # # # # source("01_DataImport&Corrections_CarbonReview.R") library(gridExtra) library(patchwork) # library(cowplot) # # # # # # # # # # # # # # # # # # # # # # Data visualisation of Carbon stocks ---- # # # # # # # # # # # # # # # # # # # # # # HISTOGRAM OF CSTOCKS ---- # Histogram for 0-20 cstocks %>% ggplot() + geom_histogram(aes(Stock_0_20cm), binwidth = 10, fill = "#9FDA3AFF") + xlab("Carbon stock 0-20 cm") + theme_bw() # ggsave("Figs/Cstocks_histogram_0_20cm.pdf") # Histogram for 20-50 cstocks %>% ggplot() + geom_histogram(aes(Stock_20_50cm), binwidth = 10, fill = "#9FDA3AFF") + xlab("Carbon stock 20-50 cm") + theme_bw() # ggsave("Figs/Cstocks_histogram_20_50cm.pdf") # Histograms all together in the same plot (for that we need to gather (tidy) the data set) cstocks_tidy <- cstocks %>% select(-Stock_20_50cm_estimate) %>% gather(key = depth, value = cstocks, Stock_0_20cm:Stock_20_50cm) cstocks_tidy %>% filter(depth != "Stock_0_50cm") %>% ggplot() + geom_histogram(aes(cstocks, fill = depth, colour = depth), alpha = 0.5) + theme_bw() # ggsave("Figs/Cstocks_histogram_allDepths_same_plot.pdf") # BARPLOT PER SPECIES (COUNT) ---- cstocks %>% mutate(Species = factor(Species) %>% fct_infreq() %>% fct_rev()) %>% filter(Meadow_type == "monospecific") %>% group_by(Species) %>% summarise(n = n()) %>% ggplot() + geom_bar(aes(x = Species, y = n), stat = "identity") + geom_text(aes(x = Species, y = n, label = str_c("(", n, ")")), nudge_y = 6, size = 3) + ylab("count") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.y = element_text(face = "italic")) # ggsave("Figs/CoreCount_by_Species.pdf") # BARPLOT PER SPECIES PERCENT ---- cstocks %>% mutate(Species = factor(Species) %>% fct_infreq() %>% fct_rev()) %>% filter(Meadow_type == "monospecific") %>% group_by(Species) %>% summarise(n = n()) %>% mutate(percent = 100*(n/sum(n))) %>% ggplot() + geom_bar(aes(x = Species, y = percent), stat = "identity") + geom_text(aes(x = Species, y = percent, label = str_c(round(percent), "%")), nudge_y = 1, size = 3) + ylab("%") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.y = element_text(face = "italic")) # ggsave("Figs/CoreCountPercent_by_Species.pdf") # BARPLOT PER COUNTRY ---- cstocks %>% mutate(Country = factor(Country) %>% fct_infreq() %>% fct_rev()) %>% filter(!is.na(Country)) %>% group_by(Country) %>% summarise(n = n()) %>% ggplot() + geom_bar(aes(x = Country, y = n), stat = "identity") + geom_text(aes(x = Country, y = n, label = str_c("(", n, ")")), nudge_y = 15, size = 3) + ylab("count") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # ggsave("Figs/CountryCount.pdf") # BARPLOT PER COUNTRY PERCENT ---- cstocks %>% mutate(Country = factor(Country) %>% fct_infreq() %>% fct_rev()) %>% filter(!is.na(Country)) %>% group_by(Country) %>% summarise(n = n()) %>% mutate(percent = 100*(n/sum(n))) %>% ggplot() + geom_bar(aes(x = Country, y = percent), stat = "identity") + geom_text(aes(x = Country, y = percent, label = str_c(round(percent), "%")), nudge_y = 3, size = 3) + ylab("%") + coord_flip() + theme_bw() + theme(legend.title = element_blank(), legend.spacing.x = unit(0.2, 'cm'), legend.text.align = 0, text = element_text(size=14), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # ggsave("Figs/CountryPercent.pdf") # MAP OF CORES BY COUNTRY ---- cstocksCountry <- cstocks %>% group_by(Country) %>% filter(!is.na(Country)) %>% summarise(n = n()) unique(cstocksCountry$Country) map.world <- map_data('world') unique(map.world$region) # Checking potential join mismatches cstocksCountry %>% anti_join(map.world, by = c('Country' = 'region')) %>% print(n = Inf) # Ok, no mismatches. Useful to see what will not be joined. In this case, nothing. Everything will be joined. # So we can proceed with the left_join map.cstocks <- left_join(map.world, cstocksCountry, by = c('region' = 'Country')) # Map of number of cores per country ggplot(map.cstocks, aes(x = long, y = lat, group = group )) + geom_polygon(aes(fill = n)) + # scale_fill_gradientn(colours = brewer.pal(5, "YlOrRd"), trans = "log10", na.value = "#d0d0d0") + # scale_fill_gradientn(colours = rev(c("#9FDA3AFF", "#4AC16DFF", "#1FA187FF", "#277F8EFF", "#365C8DFF", # "#46337EFF")), trans = "log10", na.value = "#d0d0d0") + # scale_fill_gradientn(colours = brewer.pal(5, "Blues"), trans = "log10") + # theme_minimal() labs(fill = '', x = NULL, y = NULL) + theme(text = element_text(color = '#EEEEEE'), axis.ticks = element_blank(), axis.text = element_blank(), panel.grid = element_blank(), panel.background = element_rect(fill = '#787878'), plot.background = element_rect(fill = '#787878'), legend.position = c(.18,.36) , legend.background = element_blank(), legend.key = element_blank()) # ggsave(filename = "Figs/CountryMap.pdf") # MAPPING INDIVIDUAL CORES WITH GGMAP ---- # From https://lucidmanager.org/geocoding-with-ggmap/ library(ggmap) # Now, to use Google API you have to be registered (include a credit card) and get an API key. See below. api <- readLines("google.api") # Text file with the API key register_google(key = api) getOption("ggmap") has_google_key() # To check we don't exceed the day_limit that Google imposes (2500) geocodeQueryCheck() #### Successful trial with https://blog.dominodatalab.com/geographic-visualization-with-rs-ggmaps/ # We get the lat lon coordinates in a df Df_coord <- cstocks %>% select(Latitude, Longitude) %>% group_by(Latitude, Longitude) %>% summarise(Samples = n()) # We build a world map from google Map <- ggmap(ggmap = get_googlemap(center = c(lon = 10, lat = 0), zoom = 1, style = c(feature="all",element="labels",visibility="off"), maptype = "roadmap", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Map # We plot the frequency of samples per coordinate combination as 'bubbles' Map + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude, size = Samples), col="#365C8DFF", alpha=0.4) + scale_size(range = range(sqrt(Df_coord$Samples))) + scale_y_continuous(limits = c(-70,70)) + theme_bw() # ggsave("Figs/CoreMapBubbles.pdf") # Just plotting the points Map + geom_jitter(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col= "#0063ad", alpha=0.2, width = 1, height = 1) + scale_y_continuous(limits = c(-55,70), breaks = c(-50, -25, 25, 50, 75)) + theme_bw() + xlab("Longitude (º)") + ylab("Latitude (º)") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), text = element_text(size = 12)) ggsave("Figs/Final_Figures_March2021/GlobalCoreMapPointsNEW_sized.png", width = 180, height = 110, units = "mm", dpi = 350) # MAPPING INDIVIDUAL CORES IN GGMAP ZOOMING IN EACH REGION ---- # Europe MapEurope <- ggmap(ggmap = get_googlemap(center = c(lon = 10, lat = 50), zoom = 4, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Europe <- MapEurope + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + scale_y_continuous(limits = c(35,60)) + scale_x_continuous(limits = c(-10,30)) + theme_bw() # N.America MapAmerica <- ggmap(ggmap = get_googlemap(center = c(lon = -100, lat = 40), zoom = 3, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_America <- MapAmerica + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(15,50)) + # scale_x_continuous(limits = c(-125,-65)) + theme_bw() # Brasil MapBrasil <- ggmap(ggmap = get_googlemap(center = c(lon = -50, lat = -20), zoom = 4, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Brasil <- MapBrasil + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # Arabia MapArabia <- ggmap(ggmap = get_googlemap(center = c(lon = 45, lat = 25), zoom = 5, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Arabia <- MapArabia + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # Australia MapAustralia <- ggmap(ggmap = get_googlemap(center = c(lon = 133, lat = -28), zoom = 4, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Australia <- MapAustralia + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # Asia MapAsia <- ggmap(ggmap = get_googlemap(center = c(lon = 120, lat = 25), zoom = 3, maptype = "terrain", size = c(512, 512), scale = 2, color = "bw"), extent = "panel") Cstocks_Asia <- MapAsia + geom_point(data=Df_coord, mapping = aes(x=Longitude, y=Latitude), col="#0063ad", size = 2, alpha = 0.4) + # scale_y_continuous(limits = c(-30, -5)) + # scale_x_continuous(limits = c(-70,-30)) + theme_bw() # General map # zooms <- grid.arrange(Cstocks_America, # Cstocks_Europe, # Cstocks_Asia, # Cstocks_Brasil, # Cstocks_Arabia, # Cstocks_Australia, # nrow = 2, top = "") patchwork <- Cstocks_America + Cstocks_Europe + Cstocks_Asia + Cstocks_Brasil + Cstocks_Arabia + Cstocks_Australia + plot_annotation(tag_levels = 'A') patchwork & xlab("Longitude") & ylab("Latitude") # ggsave("Figs/Core_coordinates_MapZoom_Points.pdf") # CSTOCKS PER SPECIES FACET PLOT ---- source('reorder_within_function.R') cstocks_tidy <- cstocks %>% select(-Stock_20_50cm_estimate) %>% gather(key = depth, value = cstocks, Stock_0_20cm:Stock_20_50cm) # ggplot(iris_gathered, aes(reorder_within(Species, value, metric), value)) + #' geom_boxplot() + #' scale_x_reordered() + #' facet_wrap(~ metric, scales = "free_x") ### WORKING ON THIS!!! NOW HAVE TO REORDER cstocks_tidy %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = Species, y = cstocks), fill = "#9FDA3AFF") + scale_y_reordered() + coord_flip() + xlab("Species") + ylab("Carbon stock") + facet_grid(~depth, scales = "free_x") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_facet_depths.pdf", width = 12, height = 6) # CSTOCKS PER SPECIES grid.arrange PLOT ---- p1 <- cstocks %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_20cm, FUN = median), y = Stock_0_20cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 0-20 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) p2 <- cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_20_50cm, FUN = median), y = Stock_20_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("") + ylab("Carbon stock 20-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) p3 <- cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_50cm, FUN = median), y = Stock_0_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("") + ylab("Carbon stock 0-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) ml <- grid.arrange(p1, p2, p3, widths = c(2,2,2), nrow = 1, top = "") # ggsave("Figs/Cstocks_by_Species_grid.arrange_depths.pdf", plot = ml, width = 12, height = 6) # CSTOCKS PER SPECIES ---- # Boxplots cstocks 0-20 cm cstocks %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_20cm, FUN = median), y = Stock_0_20cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 0-20 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_0_20cm.pdf") # Boxplots cstocks 0-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_0_50cm, FUN = median), y = Stock_0_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 0-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_0_50cm.pdf") # Boxplots cstocks 20-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, Stock_20_50cm, FUN = median), y = Stock_20_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Species") + ylab("Carbon stock 20-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Species_20_50cm.pdf") # CSTOCKS PER GENUS ---- # Boxplots cstocks 0-20 cm cstocks %>% filter(Meadow_type == "monospecific") %>% ggplot() + geom_boxplot(aes(x = reorder(Genus, Stock_0_20cm, FUN = median), y = Stock_0_20cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Genus") + ylab("Carbon stock 0-20 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Genus_0_20cm.pdf") # Boxplots cstocks 0-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Genus, Stock_0_50cm, FUN = median), y = Stock_0_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Genus") + ylab("Carbon stock 0-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Genus_0_50cm.pdf") # Boxplots cstocks 20-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(Stock_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Genus, Stock_20_50cm, FUN = median), y = Stock_20_50cm), fill = "#9FDA3AFF") + coord_flip() + xlab("Genus") + ylab("Carbon stock 20-50 cm") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/Cstocks_by_Genus_20_50cm.pdf") # CSTOCKS PER MEADOW TYPE ---- # Boxplots cstocks 0-20 cm cstocks %>% ggplot() + geom_boxplot(aes(x = Meadow_type, y = Stock_0_20cm), fill = "#9FDA3AFF") + xlab("Meadow type") + ylab("Carbon stock 0-20 cm") + coord_flip() + theme_bw() # ggsave("Figs/Cstocks_meadowtype_0_20cm.pdf") # Boxplots cstocks 0-50 cm cstocks %>% ggplot() + geom_boxplot(aes(x = Meadow_type, y = Stock_0_50cm), fill = "#9FDA3AFF") + xlab("Meadow type") + ylab("Carbon stock 0-50 cm") + coord_flip() + theme_bw() # ggsave("Figs/Cstocks_meadowtype_0_50cm.pdf") # Boxplots cstocks 20-50 cm cstocks %>% ggplot() + geom_boxplot(aes(x = Meadow_type, y = Stock_20_50cm), fill = "#9FDA3AFF") + xlab("Meadow type") + ylab("Carbon stock 20-50 cm") + coord_flip() + theme_bw() # ggsave("Figs/Cstocks_meadowtype_20_50cm.pdf") # DELTA13C PER SPECIES ---- # Boxplots delta13C 0-20 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(d13C_0_20cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, d13C_0_20cm, FUN = median), y = d13C_0_20cm), fill = "#1FA187FF") + coord_flip() + xlab("Species") + ylab(bquote(delta*"13C 0-20 cm")) + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/delta13C_by_Species_0_20cm.pdf") # Boxplots delta13C 0-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(d13C_0_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, d13C_0_50cm, FUN = median), y = d13C_0_50cm), fill = "#1FA187FF") + coord_flip() + xlab("Species") + ylab(bquote(delta*"13C 0-50 cm")) + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/delta13C_by_Species_0_50cm.pdf") # Boxplots delta13C 20-50 cm cstocks %>% filter(Meadow_type == "monospecific") %>% filter(!is.na(d13C_20_50cm)) %>% ggplot() + geom_boxplot(aes(x = reorder(Species, d13C_20_50cm, FUN = median), y = d13C_20_50cm), fill = "#1FA187FF") + coord_flip() + xlab("Species") + ylab(bquote(delta*"13C 20-50 cm")) + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/delta13C_by_Species_20_50cm.pdf") # # # # # # # # # # # # # # # # # # # # # # Data visualisation of Plant traits ---- # # # # # # # # # # # # # # # # # # # # # # ABOVEGROUND BIOMASS PER SPECIES ---- # Dotplots mean aboveground biomass cstocks_traits %>% filter(!is.na(Mean_aboveground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Mean_aboveground_biomass, FUN = mean), y = Mean_aboveground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Mean_aboveground_biomass, FUN = mean), ymin=Mean_aboveground_biomass-SE_Mean_aboveground_biomass, ymax=Mean_aboveground_biomass+SE_Mean_aboveground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Mean_aboveground_biomass, FUN = mean), y = Mean_aboveground_biomass+SE_Mean_aboveground_biomass, label = str_c("n = ", N_Mean_aboveground_biomass)), nudge_y = 50, size = 3) + coord_flip() + xlab("Species") + ylab("Mean aboveground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MeanAbovegroundB_by_Species_.pdf") # Dotplots max aboveground biomass cstocks_traits %>% filter(!is.na(Max_aboveground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Max_aboveground_biomass, FUN = mean), y = Max_aboveground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Max_aboveground_biomass, FUN = mean), ymin=Max_aboveground_biomass-SE_Max_aboveground_biomass, ymax=Max_aboveground_biomass+SE_Max_aboveground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Max_aboveground_biomass, FUN = mean), y = Max_aboveground_biomass+SE_Max_aboveground_biomass, label = str_c("n = ", N_Max_aboveground_biomass)), nudge_y = 100, size = 3) + coord_flip() + xlab("Species") + ylab("Max aboveground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MaxAbovegroundB_by_Species_.pdf") # BELOWGROUND BIOMASS PER SPECIES ---- # Dotplots max aboveground biomass cstocks_traits %>% filter(!is.na(Mean_belowground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Mean_belowground_biomass, FUN = mean), y = Mean_belowground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Mean_belowground_biomass, FUN = mean), ymin=Mean_belowground_biomass-SE_Mean_belowground_biomass, ymax=Mean_belowground_biomass+SE_Mean_belowground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Mean_belowground_biomass, FUN = mean), y = Mean_belowground_biomass+SE_Mean_belowground_biomass, label = str_c("n = ", N_Mean_belowground_biomass)), nudge_y = 150, size = 3) + coord_flip() + xlab("Species") + ylab("Mean belowground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MeanBelowgroundB_by_Species_.pdf") # Dotplots mean aboveground biomass cstocks_traits %>% filter(!is.na(Max_belowground_biomass)) %>% ggplot() + geom_point(aes(x = reorder(Species, Max_belowground_biomass, FUN = mean), y = Max_belowground_biomass), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Max_belowground_biomass, FUN = mean), ymin=Max_belowground_biomass-SE_Max_belowground_biomass, ymax=Max_belowground_biomass+SE_Max_belowground_biomass), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Max_belowground_biomass, FUN = mean), y = Max_belowground_biomass, label = str_c("n = ", N_Max_belowground_biomass)), nudge_y = 550, size = 3) + coord_flip() + xlab("Species") + ylab("Max belowground biomass") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/MaxBelowgroundB_by_Species_.pdf") # ROOT:SHOOT RATIO PER SPECIES ---- cstocks_traits %>% filter(!is.na(Root_shoot_ratio)) %>% ggplot() + geom_point(aes(x = reorder(Species, Root_shoot_ratio, FUN = mean), y = Root_shoot_ratio), fill = "#1FA187FF") + geom_errorbar(aes(x = reorder(Species, Root_shoot_ratio, FUN = mean), ymin=Root_shoot_ratio-SE_Root_shoot_ratio, ymax=Root_shoot_ratio+SE_Root_shoot_ratio), width=.2, position=position_dodge(.9)) + geom_text(aes(x = reorder(Species, Root_shoot_ratio, FUN = mean), y = Root_shoot_ratio+SE_Root_shoot_ratio, label = str_c("n = ", N_Max_belowground_biomass)), nudge_y = 1, size = 3) + coord_flip() + xlab("Species") + ylab("Root:Shoot ratio") + theme_bw() + theme(axis.text.y = element_text(face = "italic")) # ggsave("Figs/RootShootRatio_by_Species_.pdf") #########################
mtcars km1 = kmeans(mtcars, centers = 3) #cluster into 3 groups km1$centers km1 = kmeans(mtcars[,c('mpg','wt')], centers = 3) km1$centers df=mtcars[c('mpg','wt')] df df2=scale(df) df2
/clusterexercise.R
no_license
samiksha04/analytics1
R
false
false
184
r
mtcars km1 = kmeans(mtcars, centers = 3) #cluster into 3 groups km1$centers km1 = kmeans(mtcars[,c('mpg','wt')], centers = 3) km1$centers df=mtcars[c('mpg','wt')] df df2=scale(df) df2
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/amm.replace.r \name{amm.replacemp} \alias{amm.replacemp} \title{Replace pattern in column by match} \usage{ amm.replacemp(ds, ds.list, ds.string, ds.replace) } \arguments{ \item{ds}{data.table: data set} \item{ds.list}{character vector of columns name needed to convert} \item{ds.string}{character: value to replace} \item{ds.replace}{character: replacing character} } \value{ Character vector of column names } \description{ Replace pattern in column by matching. Replaces only pattern, not the whole value } \seealso{ amm.match, amm.gbetween }
/man/amm.replacemp.Rd
no_license
ameshkoff/amfeat
R
false
true
628
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/amm.replace.r \name{amm.replacemp} \alias{amm.replacemp} \title{Replace pattern in column by match} \usage{ amm.replacemp(ds, ds.list, ds.string, ds.replace) } \arguments{ \item{ds}{data.table: data set} \item{ds.list}{character vector of columns name needed to convert} \item{ds.string}{character: value to replace} \item{ds.replace}{character: replacing character} } \value{ Character vector of column names } \description{ Replace pattern in column by matching. Replaces only pattern, not the whole value } \seealso{ amm.match, amm.gbetween }
#' @template dbispec-sub-wip #' @format NULL #' @importFrom withr with_output_sink #' @section Connection: #' \subsection{Stress tests}{ spec_stress_connection <- list( #' Open 50 simultaneous connections simultaneous_connections = function(ctx) { cons <- list() on.exit(try_silent(lapply(cons, dbDisconnect)), add = TRUE) for (i in seq_len(50L)) { cons <- c(cons, connect(ctx)) } inherit_from_connection <- vapply(cons, is, class2 = "DBIConnection", logical(1)) expect_true(all(inherit_from_connection)) }, #' Open and close 50 connections stress_connections = function(ctx) { for (i in seq_len(50L)) { con <- connect(ctx) expect_s4_class(con, "DBIConnection") expect_error(dbDisconnect(con), NA) } }, #' } NULL )
/R/spec-stress-connection.R
no_license
wlattner/DBItest
R
false
false
796
r
#' @template dbispec-sub-wip #' @format NULL #' @importFrom withr with_output_sink #' @section Connection: #' \subsection{Stress tests}{ spec_stress_connection <- list( #' Open 50 simultaneous connections simultaneous_connections = function(ctx) { cons <- list() on.exit(try_silent(lapply(cons, dbDisconnect)), add = TRUE) for (i in seq_len(50L)) { cons <- c(cons, connect(ctx)) } inherit_from_connection <- vapply(cons, is, class2 = "DBIConnection", logical(1)) expect_true(all(inherit_from_connection)) }, #' Open and close 50 connections stress_connections = function(ctx) { for (i in seq_len(50L)) { con <- connect(ctx) expect_s4_class(con, "DBIConnection") expect_error(dbDisconnect(con), NA) } }, #' } NULL )
# 2016-06-23 # Jake Yeung rm(list=ls()) setwd("/home/yeung/projects/tissue-specificity") library(dplyr) library(ggplot2) library(hash) source("scripts/functions/ListFunctions.R") source("scripts/functions/LiverKidneyFunctions.R") source("scripts/functions/PlotGeneAcrossTissues.R") source("scripts/functions/NcondsFunctions.R") source("scripts/functions/SvdFunctions.R") source("scripts/functions/GetClockGenes.R") source("scripts/functions/BiomartFunctions.R") # load("Robjs/liver_kidney_atger_nestle/fits.long.multimethod.filtbest.Robj", v=T) load("Robjs/liver_kidney_atger_nestle/fits.long.multimethod.filtbest.staggeredtimepts.bugfixed.Robj", v=T) load("Robjs/liver_kidney_atger_nestle/dat.long.liverkidneyWTKO.bugfixed.Robj", v=T) dat.orig <- dat.long dat.long <- CollapseTissueGeno(dat.long) dat.long <- StaggeredTimepointsLivKid(dat.long) # dat.long <- SameTimepointsLivKid(dat.long) # filter NA changes dat.long <- subset(dat.long, !is.na(gene)) # Filter to common genes -------------------------------------------------- genes.keep <- unique(as.character(fits.long.filt$gene)) dat.long <- subset(dat.long, gene %in% genes.keep) # Project to Frequency ---------------------------------------------------- omega <- 2 * pi / 24 dat.freq <- dat.long %>% group_by(gene, tissue) %>% do(ProjectToFrequency2(., omega, add.tissue=TRUE)) s <- SvdOnComplex(dat.freq, value.var = "exprs.transformed") for (i in seq(1)){ eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) } # All periods ------------------------------------------------------------- periods <- rep(48, 6) / seq(1, 6) # 48/1, 48/2 ... 48/12 loadfile <- "Robjs/liver_kidney_atger_nestle/dat.complex.all_T.Robj" if (file.exists(loadfile)){ load(loadfile) } else { library(parallel) dat.complexes <- mclapply(periods, function(period, dat.long){ omega <- 2 * pi / period dat.tmp <- dat.long %>% group_by(gene, tissue) %>% do(ProjectToFrequency2(., omega, add.tissue=TRUE)) dat.tmp$period <- period return(dat.tmp) }, dat.long = dat.long, mc.cores = length(periods)) dat.complex.all_T <- do.call(rbind, dat.complexes) outfcomp <- "Robjs/liver_kidney_atger_nestle/dat.complex.all_T.bugfixed.Robj" if (!file.exists(outfcomp)) save(dat.complex.all_T, file = outfcomp) rm(dat.complexes) } outffreq <- "Robjs/liver_kidney_atger_nestle/dat.freq.bugfixed.Robj" if (!file.exists(outffreq)) save(dat.freq, file = outffreq) # By clusters ------------------------------------------------------------- jmeth <- "zf" jmeth <- "g=4001" jmeth <- "g=1001" jmeth <- "BIC" i <- 1 genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129,Kidney_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = 30, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = 30, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129,Liver_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129;Liver_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_SV129,Kidney_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_SV129;Kidney_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 10, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_BmalKO"))$gene) # # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 30, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) genes.tw <- as.character(subset(fits.long.filt, method ==jmeth & model %in% c("Liver_SV129;Kidney_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = length(genes.tw) - 1, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # Count by temporal variance ---------------------------------------------- fits.g <- subset(fits.long.filt, gene %in% genes.keep & !method %in% c("zf")) fits.g$g <- sapply(fits.g$method, function(m){ g = tryCatch({ g <- as.numeric(strsplit(m, "=")[[1]][[2]]) }, error = function(e) { g <- m }) return(g) }) by.noise <- TRUE if (!by.noise){ # for 24hr variance dat.freq.tvar <- subset(dat.freq) %>% group_by(gene) %>% summarize(tvar = sum(Mod(exprs.transformed * 2) ^ 2)) temp.var <- hash(as.character(dat.freq.tvar$gene), dat.freq.tvar$tvar) jylab <- "24h Spectral Power" } else { # for 16 and 9.6 hour variance noise.components <- periods[which(24 %% periods != 0)] dat.freq.tvar <- subset(dat.complex.all_T, period %in% noise.components) %>% group_by(gene) %>% summarize(tvar = sum(Mod(exprs.transformed * 2) ^ 2)) temp.var <- hash(as.character(dat.freq.tvar$gene), dat.freq.tvar$tvar) jylab <- paste0(paste(noise.components, collapse=","), "Spectral Power") } fits.g$tvar <- sapply(as.character(fits.g$gene), function(g){ tvar <- temp.var[[g]] if (is.null(tvar)){ return(0) } else { return(tvar) } }) fits.count <- fits.g %>% group_by(g, model) %>% summarize(n.genes = length(model), tvar = sum(tvar)) tvar.flat <- hash(as.character(subset(fits.count, model == "")$g), subset(fits.count, model == "")$tvar) fits.count$tvar.flat <- sapply(as.character(fits.count$g), function(g) tvar.flat[[g]]) cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#0072B2", "#D55E00", "#CC79A7", "#F0E442", "#009E73") jmodels <- c("Liver_SV129", "Kidney_SV129", "Liver_SV129,Kidney_SV129", "Liver_SV129;Kidney_SV129", "") jmodels <- c("Liver_SV129", "Kidney_SV129", "Liver_SV129,Kidney_SV129", "Liver_SV129;Kidney_SV129") bic.var <- subset(fits.count, g == "BIC" & model %in% jmodels) ggplot(subset(fits.count, model %in% jmodels & g != "BIC"), aes(x = as.numeric(g), y = tvar, colour = model, group = model)) + geom_point(size = 3) + geom_line() + xlim(0, 5001) + theme_bw() + theme(aspect.ratio=1, panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_manual(values=cbPalette) + ylab(jylab) + xlab("g (larger g favors simpler models)") + geom_hline(yintercept=bic.var$tvar[[1]], colour=cbPalette[[1]], linetype = "dotted") + geom_hline(yintercept=bic.var$tvar[[2]], colour=cbPalette[[2]], linetype = "dotted") + geom_hline(yintercept=bic.var$tvar[[3]], colour=cbPalette[[3]], linetype = "dotted") + geom_hline(yintercept=bic.var$tvar[[4]], colour=cbPalette[[4]], linetype = "dotted") + geom_vline(xintercept = 1000) bic.n.genes <- subset(fits.count, g == "BIC" & model %in% jmodels) ggplot(subset(fits.count, model %in% jmodels & g != "BIC"), aes(x = as.numeric(g), y = n.genes, colour = model, group = model)) + geom_point(size = 3) + geom_line() + xlim(0, 5001) + theme_bw() + theme(aspect.ratio=1, panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_manual(values=cbPalette) + ylab("# genes") + xlab("g (larger g favors simpler models)") + geom_hline(yintercept=bic.var$n.genes[[1]], colour=cbPalette[[1]], linetype = "dotted") + geom_hline(yintercept=bic.var$n.genes[[2]], colour=cbPalette[[2]], linetype = "dotted") + geom_hline(yintercept=bic.var$n.genes[[3]], colour=cbPalette[[3]], linetype = "dotted") + geom_hline(yintercept=bic.var$n.genes[[4]], colour=cbPalette[[4]], linetype = "dotted") + geom_vline(xintercept = 1000)
/scripts/liver_kidney_WTKO/nconds_downstream.analysis.R
no_license
jakeyeung/Yeung_et_al_2018_TissueSpecificity
R
false
false
10,497
r
# 2016-06-23 # Jake Yeung rm(list=ls()) setwd("/home/yeung/projects/tissue-specificity") library(dplyr) library(ggplot2) library(hash) source("scripts/functions/ListFunctions.R") source("scripts/functions/LiverKidneyFunctions.R") source("scripts/functions/PlotGeneAcrossTissues.R") source("scripts/functions/NcondsFunctions.R") source("scripts/functions/SvdFunctions.R") source("scripts/functions/GetClockGenes.R") source("scripts/functions/BiomartFunctions.R") # load("Robjs/liver_kidney_atger_nestle/fits.long.multimethod.filtbest.Robj", v=T) load("Robjs/liver_kidney_atger_nestle/fits.long.multimethod.filtbest.staggeredtimepts.bugfixed.Robj", v=T) load("Robjs/liver_kidney_atger_nestle/dat.long.liverkidneyWTKO.bugfixed.Robj", v=T) dat.orig <- dat.long dat.long <- CollapseTissueGeno(dat.long) dat.long <- StaggeredTimepointsLivKid(dat.long) # dat.long <- SameTimepointsLivKid(dat.long) # filter NA changes dat.long <- subset(dat.long, !is.na(gene)) # Filter to common genes -------------------------------------------------- genes.keep <- unique(as.character(fits.long.filt$gene)) dat.long <- subset(dat.long, gene %in% genes.keep) # Project to Frequency ---------------------------------------------------- omega <- 2 * pi / 24 dat.freq <- dat.long %>% group_by(gene, tissue) %>% do(ProjectToFrequency2(., omega, add.tissue=TRUE)) s <- SvdOnComplex(dat.freq, value.var = "exprs.transformed") for (i in seq(1)){ eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) } # All periods ------------------------------------------------------------- periods <- rep(48, 6) / seq(1, 6) # 48/1, 48/2 ... 48/12 loadfile <- "Robjs/liver_kidney_atger_nestle/dat.complex.all_T.Robj" if (file.exists(loadfile)){ load(loadfile) } else { library(parallel) dat.complexes <- mclapply(periods, function(period, dat.long){ omega <- 2 * pi / period dat.tmp <- dat.long %>% group_by(gene, tissue) %>% do(ProjectToFrequency2(., omega, add.tissue=TRUE)) dat.tmp$period <- period return(dat.tmp) }, dat.long = dat.long, mc.cores = length(periods)) dat.complex.all_T <- do.call(rbind, dat.complexes) outfcomp <- "Robjs/liver_kidney_atger_nestle/dat.complex.all_T.bugfixed.Robj" if (!file.exists(outfcomp)) save(dat.complex.all_T, file = outfcomp) rm(dat.complexes) } outffreq <- "Robjs/liver_kidney_atger_nestle/dat.freq.bugfixed.Robj" if (!file.exists(outffreq)) save(dat.freq, file = outffreq) # By clusters ------------------------------------------------------------- jmeth <- "zf" jmeth <- "g=4001" jmeth <- "g=1001" jmeth <- "BIC" i <- 1 genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129,Kidney_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = 30, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = 30, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129,Liver_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Liver_SV129;Liver_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_SV129,Kidney_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 15, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_SV129;Kidney_BmalKO"))$gene) # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 10, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # genes.tw <- as.character(subset(fits.long.filt, method == jmeth & model %in% c("Kidney_BmalKO"))$gene) # # s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") # eigens <- GetEigens(s, period = 24, comp = i, label.n = 30, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) # jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) # multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) genes.tw <- as.character(subset(fits.long.filt, method ==jmeth & model %in% c("Liver_SV129;Kidney_SV129"))$gene) s <- SvdOnComplex(subset(dat.freq, gene %in% genes.tw), value.var = "exprs.transformed") eigens <- GetEigens(s, period = 24, comp = i, label.n = length(genes.tw) - 1, eigenval = TRUE, adj.mag = TRUE, constant.amp = 4, peak.to.trough = TRUE) jlayout <- matrix(c(1, 2), 1, 2, byrow = TRUE) multiplot(eigens$u.plot, eigens$v.plot, layout = jlayout) # Count by temporal variance ---------------------------------------------- fits.g <- subset(fits.long.filt, gene %in% genes.keep & !method %in% c("zf")) fits.g$g <- sapply(fits.g$method, function(m){ g = tryCatch({ g <- as.numeric(strsplit(m, "=")[[1]][[2]]) }, error = function(e) { g <- m }) return(g) }) by.noise <- TRUE if (!by.noise){ # for 24hr variance dat.freq.tvar <- subset(dat.freq) %>% group_by(gene) %>% summarize(tvar = sum(Mod(exprs.transformed * 2) ^ 2)) temp.var <- hash(as.character(dat.freq.tvar$gene), dat.freq.tvar$tvar) jylab <- "24h Spectral Power" } else { # for 16 and 9.6 hour variance noise.components <- periods[which(24 %% periods != 0)] dat.freq.tvar <- subset(dat.complex.all_T, period %in% noise.components) %>% group_by(gene) %>% summarize(tvar = sum(Mod(exprs.transformed * 2) ^ 2)) temp.var <- hash(as.character(dat.freq.tvar$gene), dat.freq.tvar$tvar) jylab <- paste0(paste(noise.components, collapse=","), "Spectral Power") } fits.g$tvar <- sapply(as.character(fits.g$gene), function(g){ tvar <- temp.var[[g]] if (is.null(tvar)){ return(0) } else { return(tvar) } }) fits.count <- fits.g %>% group_by(g, model) %>% summarize(n.genes = length(model), tvar = sum(tvar)) tvar.flat <- hash(as.character(subset(fits.count, model == "")$g), subset(fits.count, model == "")$tvar) fits.count$tvar.flat <- sapply(as.character(fits.count$g), function(g) tvar.flat[[g]]) cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#0072B2", "#D55E00", "#CC79A7", "#F0E442", "#009E73") jmodels <- c("Liver_SV129", "Kidney_SV129", "Liver_SV129,Kidney_SV129", "Liver_SV129;Kidney_SV129", "") jmodels <- c("Liver_SV129", "Kidney_SV129", "Liver_SV129,Kidney_SV129", "Liver_SV129;Kidney_SV129") bic.var <- subset(fits.count, g == "BIC" & model %in% jmodels) ggplot(subset(fits.count, model %in% jmodels & g != "BIC"), aes(x = as.numeric(g), y = tvar, colour = model, group = model)) + geom_point(size = 3) + geom_line() + xlim(0, 5001) + theme_bw() + theme(aspect.ratio=1, panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_manual(values=cbPalette) + ylab(jylab) + xlab("g (larger g favors simpler models)") + geom_hline(yintercept=bic.var$tvar[[1]], colour=cbPalette[[1]], linetype = "dotted") + geom_hline(yintercept=bic.var$tvar[[2]], colour=cbPalette[[2]], linetype = "dotted") + geom_hline(yintercept=bic.var$tvar[[3]], colour=cbPalette[[3]], linetype = "dotted") + geom_hline(yintercept=bic.var$tvar[[4]], colour=cbPalette[[4]], linetype = "dotted") + geom_vline(xintercept = 1000) bic.n.genes <- subset(fits.count, g == "BIC" & model %in% jmodels) ggplot(subset(fits.count, model %in% jmodels & g != "BIC"), aes(x = as.numeric(g), y = n.genes, colour = model, group = model)) + geom_point(size = 3) + geom_line() + xlim(0, 5001) + theme_bw() + theme(aspect.ratio=1, panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_manual(values=cbPalette) + ylab("# genes") + xlab("g (larger g favors simpler models)") + geom_hline(yintercept=bic.var$n.genes[[1]], colour=cbPalette[[1]], linetype = "dotted") + geom_hline(yintercept=bic.var$n.genes[[2]], colour=cbPalette[[2]], linetype = "dotted") + geom_hline(yintercept=bic.var$n.genes[[3]], colour=cbPalette[[3]], linetype = "dotted") + geom_hline(yintercept=bic.var$n.genes[[4]], colour=cbPalette[[4]], linetype = "dotted") + geom_vline(xintercept = 1000)
#============================================================= #====================== MAIN FUNCTION ======================== #============================================================= plotEcoCompanyGoods <- function(df_economy, output_dir, one_plot) { name = "Company_goods_plot" #------------------------------------------------------------- #-------------------- DATA MANIPULATION ---------------------- #------------------------------------------------------------- print(paste(name, " performing data manipulation", sep="")) # CONTACTS PER GATHERING POINT PER APP USAGE SCENARIO ---------------------------- #group_by(tick) %>% summarise(total = mean(count_people_with_not_is_young_and_is_in_poverty)) # Add days converted from ticks #df_economy$day <- dmfConvertTicksToDay(df_economy$tick) # df_people_captial <- df_economy %>% select(tick, run_number, Scenario, # workers = workers_average_amount_of_goods, # retired = retirees_average_amount_of_goods, # students = students_average_amount_of_goods) df_essential_shop_goods <- df_economy %>% select(tick, run_number, Scenario, goods = essential_shop_amount_of_goods_in_stock, ) df_essential_shop_mean_std <- df_economy %>% group_by(tick, Scenario) %>% summarise(tick, Scenario, mean = mean(essential_shop_amount_of_goods_in_stock) ,std = sd(essential_shop_amount_of_goods_in_stock) ) df_non_essential_shop_goods <- df_economy %>% select(tick, run_number, Scenario, goods = non_essential_shop_amount_of_goods_in_stock, ) df_non_essential_shop_mean_std <- df_economy %>% group_by(tick, Scenario) %>% summarise(tick, Scenario, mean = mean(non_essential_shop_amount_of_goods_in_stock) ,std = sd(non_essential_shop_amount_of_goods_in_stock) ) df_workplace_goods <- df_economy %>% select(tick, run_number, Scenario, goods = workplace_amount_of_goods_in_stock, ) df_workplace_mean_std <- df_economy %>% group_by(tick, Scenario) %>% summarise(tick, Scenario, mean = mean(workplace_amount_of_goods_in_stock) ,std = sd(workplace_amount_of_goods_in_stock) ) #seg_people_calpital <- gather(df_mean_std, variable, measurement, mean, std) # ----- convert to days df_essential_shop_mean_std_day <- df_essential_shop_mean_std df_essential_shop_mean_std_day$day <- dmfConvertTicksToDay(df_essential_shop_mean_std_day$tick) df_essential_shop_mean_std_day <- df_essential_shop_mean_std_day %>% group_by(day, Scenario) %>% summarise( day, Scenario, mean = mean(mean), std = mean(std)) df_non_essential_shop_mean_std_day <- df_non_essential_shop_mean_std df_non_essential_shop_mean_std_day$day <- dmfConvertTicksToDay(df_non_essential_shop_mean_std_day$tick) df_non_essential_shop_mean_std_day <- df_non_essential_shop_mean_std_day %>% group_by(day, Scenario) %>% summarise( day, Scenario, mean = mean(mean), std = mean(std)) df_workplace_mean_std_day <- df_workplace_mean_std df_workplace_mean_std_day$day <- dmfConvertTicksToDay(df_workplace_mean_std_day$tick) df_workplace_mean_std_day <- df_workplace_mean_std_day %>% group_by(day, Scenario) %>% summarise( day, Scenario, mean = mean(mean), std = mean(std)) print(paste(name, " writing CSV", sep="")) write.csv(df_essential_shop_mean_std, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_non_essential_shop_mean_std, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_workplace_mean_std, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_essential_shop_mean_std_day, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_non_essential_shop_mean_std_day, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_workplace_mean_std_day, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) #------------------------------------------------------------- #------------------------- Plotting -------------------------- #------------------------------------------------------------- #seg_people_calpital <- gather(df_people_captial, variable, measurement, workers, retired) print(paste(name, " making plots", sep="")) dmfPdfOpen(output_dir, "eco_essential_shop_goods") print(plot_ggplot(df_essential_shop_mean_std, "essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_essential_shop_goods_smooth") print(plot_ggplot_smooth(df_essential_shop_mean_std, "essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_non_essential_shop_goods") print(plot_ggplot(df_non_essential_shop_mean_std, "non-essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_non_essential_shop_goods_smooth") print(plot_ggplot_smooth(df_non_essential_shop_mean_std, "non-essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_workplace_goods") print(plot_ggplot(df_workplace_mean_std, "workplace", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_workplace_smooth_goodd") print(plot_ggplot_smooth(df_workplace_mean_std, "workplace", "tick")) dmfPdfClose() # --- days dmfPdfOpen(output_dir, "eco_essential_shop_goods_smooth_day") print(plot_ggplot_smooth(df_essential_shop_mean_std_day, "essential shop", "day")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_non_essential_shop_goods_smooth_day") print(plot_ggplot_smooth(df_non_essential_shop_mean_std_day, "non-essential shop", "day")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_workplace_capital_goods_day") print(plot_ggplot_smooth(df_workplace_mean_std_day, "workplace", "day")) dmfPdfClose() } #============================================================= #=================== PLOTTING FUNCTIONS ====================== #============================================================= plot_ggplot <- function(data_to_plot, type_of_people, timeframe) { timeframe <- sym(timeframe) data_to_plot %>% ggplot(aes(x = !!timeframe, y = mean)) + geom_line(size=1,alpha=0.8,aes(color=Scenario, group = Scenario)) + #geom_errorbar(aes(ymin = mean - std, ymax = mean + std, # color=Scenario, group = Scenario)) + #continues_colour_brewer(palette = "Spectral", name="Infected") + xlab(paste(toupper(substring(timeframe, 1,1)), substring(timeframe, 2), "s", sep = "")) + ylab("Goods") + labs(title=paste("Average", type_of_people, "goods in stock", sep = " "), subtitle=paste("Average goods in stock at", type_of_people, sep = " "), caption="Agent-based Social Simulation of Corona Crisis (ASSOCC)") + scale_color_manual(values = gl_plot_colours) + gl_plot_guides + gl_plot_theme } plot_ggplot_smooth <- function(data_to_plot, type_of_people, timeframe) { timeframe <- sym(timeframe) data_to_plot %>% ggplot(aes(x = !!timeframe, y = mean)) + gl_plot_smooth + geom_ribbon(aes(ymin = mean - std, ymax = mean + std, color= Scenario), alpha=0.025) + #scale_colour_brewer(palette = "Spectral", name="Infected") + xlab(paste(toupper(substring(timeframe, 1,1)), substring(timeframe, 2), "s", sep = "")) + ylab("Goods") + labs(title=paste("Average", type_of_people, "goods in stock", sep = " "), subtitle=paste("Average goods in stock at", type_of_people, "(smoothed + uncertainty (std. dev.))", sep = " "), caption="Agent-based Social Simulation of Corona Crisis (ASSOCC)") + scale_color_manual(values = gl_plot_colours) + gl_plot_guides + gl_plot_theme }
/processing/scenarios/R_ASSOCC_Economy/1.0_company_goods_plot.R
no_license
SergeStinckwich/COVID-sim
R
false
false
8,367
r
#============================================================= #====================== MAIN FUNCTION ======================== #============================================================= plotEcoCompanyGoods <- function(df_economy, output_dir, one_plot) { name = "Company_goods_plot" #------------------------------------------------------------- #-------------------- DATA MANIPULATION ---------------------- #------------------------------------------------------------- print(paste(name, " performing data manipulation", sep="")) # CONTACTS PER GATHERING POINT PER APP USAGE SCENARIO ---------------------------- #group_by(tick) %>% summarise(total = mean(count_people_with_not_is_young_and_is_in_poverty)) # Add days converted from ticks #df_economy$day <- dmfConvertTicksToDay(df_economy$tick) # df_people_captial <- df_economy %>% select(tick, run_number, Scenario, # workers = workers_average_amount_of_goods, # retired = retirees_average_amount_of_goods, # students = students_average_amount_of_goods) df_essential_shop_goods <- df_economy %>% select(tick, run_number, Scenario, goods = essential_shop_amount_of_goods_in_stock, ) df_essential_shop_mean_std <- df_economy %>% group_by(tick, Scenario) %>% summarise(tick, Scenario, mean = mean(essential_shop_amount_of_goods_in_stock) ,std = sd(essential_shop_amount_of_goods_in_stock) ) df_non_essential_shop_goods <- df_economy %>% select(tick, run_number, Scenario, goods = non_essential_shop_amount_of_goods_in_stock, ) df_non_essential_shop_mean_std <- df_economy %>% group_by(tick, Scenario) %>% summarise(tick, Scenario, mean = mean(non_essential_shop_amount_of_goods_in_stock) ,std = sd(non_essential_shop_amount_of_goods_in_stock) ) df_workplace_goods <- df_economy %>% select(tick, run_number, Scenario, goods = workplace_amount_of_goods_in_stock, ) df_workplace_mean_std <- df_economy %>% group_by(tick, Scenario) %>% summarise(tick, Scenario, mean = mean(workplace_amount_of_goods_in_stock) ,std = sd(workplace_amount_of_goods_in_stock) ) #seg_people_calpital <- gather(df_mean_std, variable, measurement, mean, std) # ----- convert to days df_essential_shop_mean_std_day <- df_essential_shop_mean_std df_essential_shop_mean_std_day$day <- dmfConvertTicksToDay(df_essential_shop_mean_std_day$tick) df_essential_shop_mean_std_day <- df_essential_shop_mean_std_day %>% group_by(day, Scenario) %>% summarise( day, Scenario, mean = mean(mean), std = mean(std)) df_non_essential_shop_mean_std_day <- df_non_essential_shop_mean_std df_non_essential_shop_mean_std_day$day <- dmfConvertTicksToDay(df_non_essential_shop_mean_std_day$tick) df_non_essential_shop_mean_std_day <- df_non_essential_shop_mean_std_day %>% group_by(day, Scenario) %>% summarise( day, Scenario, mean = mean(mean), std = mean(std)) df_workplace_mean_std_day <- df_workplace_mean_std df_workplace_mean_std_day$day <- dmfConvertTicksToDay(df_workplace_mean_std_day$tick) df_workplace_mean_std_day <- df_workplace_mean_std_day %>% group_by(day, Scenario) %>% summarise( day, Scenario, mean = mean(mean), std = mean(std)) print(paste(name, " writing CSV", sep="")) write.csv(df_essential_shop_mean_std, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_non_essential_shop_mean_std, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_workplace_mean_std, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_essential_shop_mean_std_day, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_non_essential_shop_mean_std_day, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) write.csv(df_workplace_mean_std_day, file=paste(output_dir, "/plot_data_", name, ".csv", sep="")) #------------------------------------------------------------- #------------------------- Plotting -------------------------- #------------------------------------------------------------- #seg_people_calpital <- gather(df_people_captial, variable, measurement, workers, retired) print(paste(name, " making plots", sep="")) dmfPdfOpen(output_dir, "eco_essential_shop_goods") print(plot_ggplot(df_essential_shop_mean_std, "essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_essential_shop_goods_smooth") print(plot_ggplot_smooth(df_essential_shop_mean_std, "essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_non_essential_shop_goods") print(plot_ggplot(df_non_essential_shop_mean_std, "non-essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_non_essential_shop_goods_smooth") print(plot_ggplot_smooth(df_non_essential_shop_mean_std, "non-essential shop", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_workplace_goods") print(plot_ggplot(df_workplace_mean_std, "workplace", "tick")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_workplace_smooth_goodd") print(plot_ggplot_smooth(df_workplace_mean_std, "workplace", "tick")) dmfPdfClose() # --- days dmfPdfOpen(output_dir, "eco_essential_shop_goods_smooth_day") print(plot_ggplot_smooth(df_essential_shop_mean_std_day, "essential shop", "day")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_non_essential_shop_goods_smooth_day") print(plot_ggplot_smooth(df_non_essential_shop_mean_std_day, "non-essential shop", "day")) dmfPdfClose() dmfPdfOpen(output_dir, "eco_workplace_capital_goods_day") print(plot_ggplot_smooth(df_workplace_mean_std_day, "workplace", "day")) dmfPdfClose() } #============================================================= #=================== PLOTTING FUNCTIONS ====================== #============================================================= plot_ggplot <- function(data_to_plot, type_of_people, timeframe) { timeframe <- sym(timeframe) data_to_plot %>% ggplot(aes(x = !!timeframe, y = mean)) + geom_line(size=1,alpha=0.8,aes(color=Scenario, group = Scenario)) + #geom_errorbar(aes(ymin = mean - std, ymax = mean + std, # color=Scenario, group = Scenario)) + #continues_colour_brewer(palette = "Spectral", name="Infected") + xlab(paste(toupper(substring(timeframe, 1,1)), substring(timeframe, 2), "s", sep = "")) + ylab("Goods") + labs(title=paste("Average", type_of_people, "goods in stock", sep = " "), subtitle=paste("Average goods in stock at", type_of_people, sep = " "), caption="Agent-based Social Simulation of Corona Crisis (ASSOCC)") + scale_color_manual(values = gl_plot_colours) + gl_plot_guides + gl_plot_theme } plot_ggplot_smooth <- function(data_to_plot, type_of_people, timeframe) { timeframe <- sym(timeframe) data_to_plot %>% ggplot(aes(x = !!timeframe, y = mean)) + gl_plot_smooth + geom_ribbon(aes(ymin = mean - std, ymax = mean + std, color= Scenario), alpha=0.025) + #scale_colour_brewer(palette = "Spectral", name="Infected") + xlab(paste(toupper(substring(timeframe, 1,1)), substring(timeframe, 2), "s", sep = "")) + ylab("Goods") + labs(title=paste("Average", type_of_people, "goods in stock", sep = " "), subtitle=paste("Average goods in stock at", type_of_people, "(smoothed + uncertainty (std. dev.))", sep = " "), caption="Agent-based Social Simulation of Corona Crisis (ASSOCC)") + scale_color_manual(values = gl_plot_colours) + gl_plot_guides + gl_plot_theme }
testlist <- list(Beta = 0, CVLinf = 0, FM = 3.19900290824811e-83, L50 = 0, L95 = 0, LenBins = numeric(0), LenMids = numeric(0), Linf = 0, MK = 0, Ml = numeric(0), Prob = structure(0, .Dim = c(1L, 1L)), SL50 = 1.64050245440024e-303, SL95 = 1.05376013623562e-264, nage = 847783982L, nlen = 1735852032L, rLens = numeric(0)) result <- do.call(DLMtool::LBSPRgen,testlist) str(result)
/DLMtool/inst/testfiles/LBSPRgen/AFL_LBSPRgen/LBSPRgen_valgrind_files/1615830404-test.R
no_license
akhikolla/updatedatatype-list2
R
false
false
398
r
testlist <- list(Beta = 0, CVLinf = 0, FM = 3.19900290824811e-83, L50 = 0, L95 = 0, LenBins = numeric(0), LenMids = numeric(0), Linf = 0, MK = 0, Ml = numeric(0), Prob = structure(0, .Dim = c(1L, 1L)), SL50 = 1.64050245440024e-303, SL95 = 1.05376013623562e-264, nage = 847783982L, nlen = 1735852032L, rLens = numeric(0)) result <- do.call(DLMtool::LBSPRgen,testlist) str(result)