blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
327
content_id
stringlengths
40
40
detected_licenses
listlengths
0
91
license_type
stringclasses
2 values
repo_name
stringlengths
5
134
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
46 values
visit_date
timestamp[us]date
2016-08-02 22:44:29
2023-09-06 08:39:28
revision_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
committer_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
github_id
int64
19.4k
671M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
14 values
gha_event_created_at
timestamp[us]date
2012-06-21 16:39:19
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-06-28 13:19:12
gha_language
stringclasses
60 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
9.18M
extension
stringclasses
20 values
filename
stringlengths
1
141
content
stringlengths
7
9.18M
78386948bfffa6181d642904648c750af5816f65
9710c61f0387afbd3bdbd2c93db5f681649b08e5
/ui.R
7fdc234a6b1cbdebecd47f52ae153c9136c180d6
[]
no_license
TMBish/HHTL
530b9bd9dae6ddc64f0911b870682b87447e3873
92b4b9e1074bdb61e80eec340cd5fc1bdca89d0f
refs/heads/master
2021-03-30T17:56:37.230344
2018-10-06T07:34:43
2018-10-06T07:34:43
104,702,993
0
0
null
null
null
null
UTF-8
R
false
false
1,839
r
ui.R
shinyUI( semanticPage( title = "Hannah's History Timeline", useShinyjs(), useSweetAlert(), extendShinyjs(text = jsCode), # Add custom css styles includeCSS(file.path('www', 'custom-style.css')), div(class="app-header", h1(class = "ui header", ": HANNAH'S HISTORY TIMELINE :") ), br(), # Sweet Alert #receiveSweetAlert(messageId = "event_success"), # Main page after load # hidden( div(id = "app-body", class="ui grid", hidden( div(class="one wide column", id = "dropdown-div", dropdownButton( tags$h3("Add a Historical Event"), hr(), textInput("title", label = "Event Name", value = ""), textInput("image_link", label = "Photo of Event (url)", value = ""), dateRangeInput("event_dates", label = "Period"), textAreaInput("description", label = "Add a Decription:", value = "", height = 150), textInput("new_code", "Enter code word:"), actionButton("upload_event", "Add Event", icon = icon("upload")), circle = TRUE, icon = icon("plus"), width = "300px", tooltip = tooltipOptions(title = "Click to see inputs !") ) ) ), div(class="fifteen wide column", div(class = "ui horizontal divider", icon("globe"), "The History Of Everything") ) ), br(), timevisOutput("timeline"), br() # ) ) )
238e3d5f0d1faed2d9fb05a85efe2ee00fb0d76f
e0ad7ef4247279fad496c3c23891457c5fa0bbe1
/analysis/09_combined_analysis.R
d85af28873cdf5657b6c39d66679682c19c51767
[]
no_license
wiscstatman/immunostat-prostate
8c34672d5f3266566f7a46d028360279934e6c67
bdf6db6257ad6c6770a8fdb163067244a0f6e43b
refs/heads/master
2022-12-23T20:53:57.428843
2020-10-06T04:42:01
2020-10-06T04:42:01
283,579,630
1
1
null
null
null
null
UTF-8
R
false
false
80,557
r
09_combined_analysis.R
library(xlsx) library(allez) library(gridExtra) library(ggplot2) library(matrixStats) # rowMedians library(lme4) # linear mixed effects model library(lmerTest) library(fdrtool) library(heatmap3) library(tidyverse) # make sure you have the latest tidyverse ! ####################################################################################### # Some Common Variables and Functions # ####################################################################################### # specified color and shape scheme pal <- c("navy", "cornflowerblue", "turquoise1", "orchid1", "darkorange1", "firebrick1") names(pal) <- c("normal", "new_dx", "nmCSPC", "mCSPC", "nmCRPC", "mCRPC") shp <- c(8, 15, 16, 3, 17, 18) names(shp) <- names(pal) # function to plot PCA loadings PCload.func <- function(cols, shapes, U, D, x, y, pca.vec, title){ Z <- U %*% diag(D) plot(Z[,x], Z[,y], col = cols, pch = shapes, main = title, las = 1, xlab = paste0("PC",x," (", round(pca.vec[x]*100, 1) ,"% variance explained)"), ylab = paste0("PC",y," (", round(pca.vec[y]*100, 1) ,"% variance explained)") ) } # function to count peptides at different FDR thresholds count.func <- function(pval.vec, thresh.vec){ counter <- NULL for (i in thresh.vec ){ counter <- c(counter, length(pval.vec[pval.vec <= i])) } countab <- rbind(c("FDR threshold", thresh.vec), c("Peptide counts", counter)) return(countab) } # typical step in ANOVA anova_func <- function(anova_pval, xlab){ # control FDR anova_BH <- p.adjust(anova_pval, method = "BH") anova_qval <- fdrtool(anova_pval, statistic = "pvalue", verbose = F, plot = F)$qval anova_qval_eta0 <- unname(fdrtool(anova_pval, statistic = "pvalue", verbose = F, plot = F)$param[,"eta0"]) # plot histogram of p-values all_peptide_hist <- hist(anova_pval, breaks = 70, freq = F, xlab = xlab, las = 1, main = paste0("p-values distribution for ", length(anova_pval), " peptides")) polygon_ind <- which(all_peptide_hist$density >= anova_qval_eta0) for (i in polygon_ind){ polygon( x = c(all_peptide_hist$breaks[i], all_peptide_hist$breaks[i+1], all_peptide_hist$breaks[i+1], all_peptide_hist$breaks[i]), y = c(all_peptide_hist$density[i], all_peptide_hist$density[i], anova_qval_eta0, anova_qval_eta0), col = "red") } text(x=0.65,y=4, labels = paste( "estimated proportion of \nnon-null peptides =", round( 100*(1 - anova_qval_eta0),2 ),"%" )) return(list(anova_BH = anova_BH, anova_qval = anova_qval, anova_qval_eta0 = anova_qval_eta0)) } # post-process allez table for kable output get_alleztable.func <- function(allez_go_input){ allez.tab <- allezTable(allez_go_input, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T) allez.tab$set.size <- paste(allez.tab$in.set, allez.tab$set.size, sep = "/") allez.tab <- allez.tab %>% dplyr::select(-c(in.set, genes)) %>% mutate(in.genes = str_replace_all(in.genes, ";", "; ")) return(allez.tab) } load("09_Cancer_Stage_Effects.RData") load("09_LMER_results.RData") load("09_allez_results.RData") raw_data_median <- read_csv("raw_data_median.csv") raw_data_median_proj2 <- read_csv("raw_data_median_proj2.csv") ####################################################################################### # Data Processing # ####################################################################################### array_id_key = read_csv("sample_key_project1.csv") %>% janitor::clean_names() %>% rename(stage = condition, array_id = "file_name") %>% mutate(id = str_replace_all(id, " ", ""), id = str_to_lower(id), id = str_replace_all(id, "/", ""), stage = as_factor(stage), stage = fct_recode(stage, "normal" = "Normal_male_controls", "new_dx" = "Newly_diagnosed", "nmCSPC" = "PSA-recurrent_nonMet", "mCSPC" = "Met", "nmCRPC" = "Castration-resistent_nonMet", "mCRPC" = "Castration-resistent_Met", "binding_buffer" = "Binding buffer alone")) # drop binding buffer length(array_id_key$stage[array_id_key$stage=="binding_buffer"]) # 1 binding_buffer array_id_key <- array_id_key[!(array_id_key$stage=="binding_buffer"),] array_id_key$stage <- factor(array_id_key$stage) # remove binding_buffer level # remove patients whose rep == 1 patient_key = array_id_key %>% group_by(id, stage) %>% summarize(n = n()) %>% ungroup() %>% filter(n >= 2) %>% select(-n) array_id_key = array_id_key %>% filter(id %in% patient_key$id) # check patient counts (NOT distinct patients) array_id_key %>% group_by(id, stage) %>% summarize() %>% group_by(stage) %>% tally() # there are patients who were measured at two different stages # To ensure unique patients, remove the following ids ids_to_remove = c("adt181", "adt223", "pdv008", "pap123", "pap067", "adt143") # drop patients' earlier records array_id_key = array_id_key %>% filter(!(id %in% ids_to_remove)) patient_key = array_id_key %>% group_by(id, stage) %>% tally() %>% select(-n) patient_key$stage <- relevel(patient_key$stage, ref = "normal") # check patient counts (distinct patients) array_id_key %>% group_by(id, stage) %>% summarize() %>% group_by(stage) %>% tally() #----------------------------------------------------------------------------------------------- # get raw_data_complete.csv and compute median # raw_data = read_csv("raw_data_complete.csv") # # sum(as.numeric(raw_data$X == raw_data$COL_NUM)) == nrow(raw_data) # X = COL_NUM # sum(as.numeric(raw_data$Y == raw_data$ROW_NUM)) == nrow(raw_data) # Y = ROW_NUM # sum(as.numeric(raw_data$MATCH_INDEX == raw_data$FEATURE_ID)) == nrow(raw_data) # MATCH_INDEX = FEATURE_ID # unique(raw_data$DESIGN_NOTE) # only NA # unique(raw_data$SELECTION_CRITERIA) # only NA # unique(raw_data$MISMATCH) # only 0 # unique(raw_data$PROBE_CLASS) # only NA # # we can drop X, Y, MATCH_INDEX, DESIGN_NOTE, SELECTION_CRITERIA, MISMATCH, PROBE_CLASS # # raw_data = raw_data %>% # select(PROBE_DESIGN_ID:Y, any_of(array_id_key$array_id)) %>% # drop patients with records at different stages # select( -c(X, Y, MATCH_INDEX, DESIGN_NOTE, SELECTION_CRITERIA, MISMATCH, PROBE_CLASS) ) # drop unhelpful columns # # colnames(raw_data)[1:15] # check # # # take log2 transformation # raw_data <- raw_data %>% # mutate_at(vars(matches(".dat")), log2) # # # # make sure array_id_key align with raw_data_complete # array_iii <- match( colnames( raw_data %>% select(contains(".dat")) ), array_id_key$array_id ) # array_id_key <- array_id_key[array_iii , ] # sum(as.numeric( colnames( raw_data %>% select(contains(".dat")) ) == array_id_key$array_id )) == nrow(array_id_key) # # # # compute median # raw_data_median <- t( apply( select(raw_data, contains(".dat")), 1, function(x) { # tapply(x, array_id_key$id, FUN=median) # } ) ) # raw_data_median <- bind_cols( select(raw_data, -contains(".dat")), as.data.frame(raw_data_median) ) # # colnames(raw_data_median)[1:15] # check # # write.table(raw_data_median, file = "raw_data_median.csv", sep = ",", row.names = F) #----------------------------------------------------------------------------------------------- # read calls data # read aggregated calls data calls = read_csv("aggregated_calls_full_nmcspc.csv") length(unique(calls$probe_sequence)) == nrow(calls) # probe_sequence NOT unique # probe_sequence NOT unique # need to generate unique PROBE_ID # PROBE_ID in raw_data_complete.csv is paste0(SEQ_ID, ";", POSITION) calls$PROBE_ID = paste0(calls$seq_id, ";", calls$position) calls <- calls %>% select(container:position, PROBE_ID, everything()) # rearrange columns # keep only patients that appear in patient_sample_key calls <- calls %>% select(container:PROBE_ID, any_of(patient_key$id)) # check dimensions of calls match dimensions of raw_data_median (nrow(calls) == nrow(raw_data_median)) & (ncol(calls %>% select(any_of(patient_key$id))) == ncol(raw_data_median %>% select(any_of(patient_key$id)))) ncol(calls %>% select(any_of(patient_key$id))) == nrow(patient_key) # check if PROBE_ID (& patient_id) in calls appear in PROBE_ID (& patient_id) in raw_data_median sum(as.numeric( calls$PROBE_ID %in% raw_data_median$PROBE_ID )) == nrow(calls) sum(as.numeric( colnames( calls %>% select(any_of(patient_key$id)) ) %in% colnames( raw_data_median %>% select(any_of(patient_key$id)) ) )) == nrow(patient_key) # get calls_long for later calls_long <- calls %>% select(PROBE_ID, any_of(array_id_key$id)) # remove peptides that have zero calls in ALL subjects calls <- calls[ apply( calls %>% select(any_of(patient_key$id)) , 1, function(x){ !all(x==0) } ) , ] # in the end, how many peptides with at least one call among all patients nrow(calls) #---------------------------------------------------------------------------------------------- # get median_long median_long2 <- raw_data_median %>% select(PROBE_ID, any_of(array_id_key$id)) dim(median_long2) == dim(calls_long) # check # rearrange rows and columns to match calls_long & median_long calls_long <- calls_long[, match(colnames(median_long2), colnames(calls_long))] calls_long <- calls_long[ match(median_long2$PROBE_ID, calls_long$PROBE_ID) , ] sum(as.numeric( colnames( calls_long ) == colnames( median_long2 ) )) == nrow(patient_key) + 1 # check sum(as.numeric( calls_long$PROBE_ID == median_long2$PROBE_ID )) == nrow(median_long2) # check # pivot_longer median_long2 <- median_long2 %>% select(-PROBE_ID) %>% pivot_longer(cols = everything(), names_to = "id", values_to = "fluorescence") calls_long <- calls_long %>% select(-PROBE_ID) %>% pivot_longer(cols = everything(), names_to = "id", values_to = "calls") # check median_long2 & calls_long nrow(median_long2) == nrow(raw_data_median) * nrow(patient_key) head(median_long2) nrow(calls_long) == nrow(calls) * nrow(patient_key) head(calls_long) dim(median_long2) == dim(median_long2) sum(as.numeric(median_long2$id == calls_long$id)) == nrow(raw_data_median) * nrow(patient_key) # plot fluorescence of calls vs no-calls calls_fl_df <- data.frame( calls = factor(calls_long$calls), fluorescence = median_long2$fluorescence ) janitor::tabyl(calls_fl_df$calls) %>% janitor::adorn_pct_formatting() %>% rename(calls = "calls_fl_df$calls", patient_peptide_counts = n) ggplot(calls_fl_df, aes(x = calls, y = fluorescence, fill = calls)) + geom_boxplot(outlier.shape = ".") + labs(title = "Boxplots of Fluorescence Levels per Peptide per Patient", x = "Calls per peptide per patient", y = "Median (across replicates) Fluorescence Levels on log2 scale") + theme(panel.background = element_rect(fill = "grey90"), panel.grid.major = element_line(color = "white"), panel.grid.minor = element_line(color = "white"), plot.title = element_text(hjust = 0.5)) # free up memory rm(median_long2, calls_fl_df, calls_long); gc() ####################################################################################### # Check normalization of fluorescence data # ####################################################################################### median_long <- raw_data_median %>% select(any_of(array_id_key$id)) %>% pivot_longer(cols = everything(), names_to = "id", values_to = "fluorescence") # check nrow(median_long) == nrow(raw_data_median) * nrow(patient_key) head(median_long) # set fill color median_long$stage <- patient_key$stage[ match(median_long$id, patient_key$id) ] # sort order of patients in boxplot median_long$id <- factor(median_long$id, levels = c( patient_key$id[patient_key$stage == "normal"], patient_key$id[patient_key$stage == "new_dx"], patient_key$id[patient_key$stage == "nmCSPC"], patient_key$id[patient_key$stage == "nmCRPC"], patient_key$id[patient_key$stage == "mCRPC"] )) ggplot(median_long, aes(x = id, y = fluorescence, fill = stage)) + geom_boxplot(outlier.shape = ".") + scale_fill_manual(name = "Stage", values = pal) + labs(title = "Boxplots of Peptide Fluorescence Levels for All Patients", x = "Patient ID", y = "Median Fluorescence Levels on log2 scale") + theme(panel.background = element_rect(fill = "grey90"), panel.grid.major = element_line(color = "white"), panel.grid.minor = element_line(color = "white"), axis.text.x = element_text(angle = 90, hjust = 1, size = 4.5), legend.position = "bottom", plot.title = element_text(hjust = 0.5)) ####################################################################################### # Evaluate Reproducibility of Replicates via Linear Mixed Effects Model # ####################################################################################### # ncol_raw <- ncol(raw_data) # nrep <- nrow(array_id_key) # # # initiate # lmer_result <- matrix(NA, nrow = nrow(raw_data), ncol = 4) # colnames(lmer_result) <- c("variance_id", "variance_residual", "lrstat", "singularity") # # # check array_id_key align with raw_data_complete # sum(as.numeric( colnames( raw_data[,(ncol_raw - nrep + 1) : ncol_raw] ) == array_id_key$array_id )) == nrow(array_id_key) # # # for(i in 1:nrow(raw_data)){ # y <- as.numeric(raw_data[i, (ncol_raw - nrep + 1) : ncol_raw]) # fit1 <- lmer(y ~ stage + (1|id), data = array_id_key) # fit2 <- lmer(y ~ 1 + (1|id), data = array_id_key) # lmer_result[i,] <- c( # as.data.frame(VarCorr(fit1))$'vcov', # as.numeric(-2*(logLik(fit2, REML=T) - logLik(fit1, REML=T))), # ( isSingular(fit1) | isSingular(fit2) ) # ) # print(i) # } # check how many singular fits sum(as.numeric(lmer_result[,'singularity'])) max(as.numeric(lmer_result[,'variance_id'][ lmer_result[,'singularity']==T ])) min(as.numeric(lmer_result[,'variance_residual'] )) # get estimated proportion of variances lmer_var_ratio <- lmer_result[,'variance_id'] / ( lmer_result[,'variance_id'] + lmer_result[,'variance_residual'] ) hist(lmer_var_ratio, breaks = 100, xlab = "estimated proportion of variances", main = "Histogram of peptide-level proportion of random-effect variance to total variance") ####################################################################################### # TEST -- Logistic Regression # ####################################################################################### # ncol_calls <- ncol(calls) # n <- nrow(patient_key) # # # make sure patients' stages align with calls # calls_iii <- match( colnames( calls[,(ncol_calls - n + 1): ncol_calls] ), patient_key$id ) # calls_stages <- (patient_key$stage)[calls_iii] # sum(as.numeric( colnames( calls[,(ncol_calls - n + 1): ncol_calls] ) == (patient_key$id)[calls_iii] )) == nrow(patient_key) # # # initiate # logreg_pval <- rep(NA, nrow(calls)) # names(logreg_pval) <- calls$PROBE_ID # # # compute deviance test p-values # for(i in 1:nrow(calls)){ # y <- as.numeric( calls[i, (ncol_calls - n + 1): ncol_calls] ) # fit1 <- glm(y ~ calls_stages, family = binomial(link = "logit")) # logreg_pval[i] <- 1 - pchisq( fit1$null.deviance - fit1$deviance, df = (fit1$df.null - fit1$df.residual) ) # print(i) # } # control FDR logreg_BH <- p.adjust(logreg_pval, method = "BH") logreg_qval <- fdrtool(logreg_pval, statistic = "pvalue", verbose = F, plot = F)$qval logreg_qval_eta0 <- unname(fdrtool(logreg_pval, statistic = "pvalue", verbose = F, plot = F)$param[,"eta0"]) # plot histogram of p-values hist(logreg_pval, breaks = 50, freq = T, main = "Logistic Regression Deviance Test p-values", xlab = "p-values ") # peptide counts at various FDR thresholds count.func(logreg_BH, seq(0.01, 0.05, by = 0.01)) count.func(logreg_qval, seq(0.01, 0.05, by = 0.01)) # Calls are conservative # Logistic regression based on number of calls yield (almost) no signal even before FDR control ####################################################################################### # Another Tests -- one-way ANOVA & Kruskal-Wallis Test # ####################################################################################### ncol_median <- ncol(raw_data_median) n <- nrow(patient_key) # make sure patients' stages align with raw_data_median median_iii <- match( colnames(raw_data_median[, (ncol_median - n + 1) : ncol_median]), patient_key$id ) median_stage <- patient_key$stage[median_iii] median_stage <- factor(median_stage) sum(as.numeric( colnames(raw_data_median[, (ncol_median - n + 1) : ncol_median]) == patient_key$id[median_iii] )) == nrow(patient_key) #--------------------------------------------------------------------------------------- # initiate ANOVA # all_anova_pval <- rep(NA, nrow(raw_data_median)) # names(all_anova_pval) <- raw_data_median$PROBE_ID # all_anova_mse <- rep(NA, nrow(raw_data_median)) # names(all_anova_mse) <- raw_data_median$PROBE_ID # compute one-way anova p-values # for(i in 1:nrow(raw_data_median)){ # fit1 <- lm( as.numeric(raw_data_median[i, (ncol_median - n + 1) : ncol_median]) ~ median_stage ) # all_anova_pval[i] <- unname( unlist(summary(aov(fit1)))["Pr(>F)1"] ) # all_anova_mse[i] <- deviance(fit1)/df.residual(fit1) # print(i) # } # get p-values histogram and FDR all_anova <- anova_func(all_anova_pval, "one-way ANOVA p-values") # peptide counts at various FDR thresholds count.func(all_anova$anova_BH, seq(0.01, 0.1, by = 0.01)) count.func(all_anova$anova_qval, seq(0.01, 0.1, by = 0.01)) #--------------------------------------------------------------------------------------- # some peptides may violate ANOVA assumption par(mar=c(3.1, 5.1, 2.1, 2.1), mgp=c(2, 0.8, 0)) graphics::boxplot(as.numeric( raw_data_median %>% filter(PROBE_ID == "1324_KIAA1430_57587;185") %>% select(any_of(array_id_key$id)) ) ~ median_stage, varwidth = T, horizontal = T, las = 1, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = "Peptide ID: 1324_KIAA1430_57587;185", xlab = "log2(fluorescence)", ylab = "") par(mar=c(3.1, 5.1, 2.1, 2.1), mgp=c(2, 0.8, 0)) graphics::boxplot(as.numeric( raw_data_median %>% filter(PROBE_ID == "459_CLTC_1213;1421") %>% select(any_of(array_id_key$id)) ) ~ median_stage, varwidth = T, horizontal = T, las= 1, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = "Peptide ID: 459_CLTC_1213;1421", xlab = "log2(fluorescence)", ylab = "") dev.off() #--------------------------------------------------------------------------------------- # now do kruskal-wallis tests # initiate kruskal-wallis(KW) # all_kw_pval <- rep(NA, nrow(raw_data_median)) # names(all_kw_pval) <- raw_data_median$PROBE_ID # # for(i in 1:nrow(raw_data_median)){ # all_kw_pval[i] <- kruskal.test( as.numeric(raw_data_median[i, (ncol_median - n + 1) : ncol_median]) ~ median_stage )$'p.value' # print(i) # } # get p-values histogram and FDR all_kw <- anova_func(all_kw_pval, "Kruskal-Wallis p-values") # peptide counts at various FDR thresholds count.func(all_kw$anova_BH, seq(0.01, 0.1, by = 0.01)) # signif for both ANOVA & Kruskal-Wallis length(which(all_kw$anova_BH <= .05 & all_anova$anova_BH <= .05)) #--------------------------------------------------------------------------------------- # compare kruskal-wallis pval vs ANOVA pval plot(x = all_anova_pval, y = all_kw_pval, pch = ".", xlab = "ANOVA p-values", ylab = "Kruskal-Wallis p-values") lines(x = all_anova_pval[all_anova$anova_BH <= .05], y = all_kw_pval[all_anova$anova_BH <= .05], type = "p", pch = 20, col = "red") lines(x = all_anova_pval[all_kw$anova_BH <= .05], y = all_kw_pval[all_kw$anova_BH <= .05], type = "p", pch = 20, col = "blue") lines(x = all_anova_pval[all_anova$anova_BH <= .05 & all_kw$anova_BH <= .05], y = all_kw_pval[all_anova$anova_BH <= .05 & all_kw$anova_BH <= .05], type = "p", pch = 20, col = "green") # check boxplot of peptide with very signif ANOVA pval but not kruskal-wallis pval ANOVA_but_not_KW <- raw_data_median %>% filter(all_anova_pval <.001 & all_kw_pval >.2) %>% select(PROBE_ID, any_of(array_id_key$id)) %>% as.matrix() ANOVA_but_not_KW_iii <- match( colnames(ANOVA_but_not_KW[, -1]), patient_key$id ) ANOVA_but_not_KW_stage <- patient_key$stage[ANOVA_but_not_KW_iii] ANOVA_but_not_KW_stage <- factor(ANOVA_but_not_KW_stage) sum(as.numeric( colnames(ANOVA_but_not_KW[, -1]) == patient_key$id[ANOVA_but_not_KW_iii] )) == nrow(patient_key) par(mfrow=c(3,1)) par(mar=c(5.1, 6.1, 4.1, 2.1)) graphics::boxplot(as.numeric(ANOVA_but_not_KW[1,-1])~ANOVA_but_not_KW_stage, varwidth = T, horizontal = T,las= 2, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = ANOVA_but_not_KW[1,"PROBE_ID"], xlab = "log2(fluorescence)", ylab = "") graphics::boxplot(as.numeric(ANOVA_but_not_KW[2,-1])~ANOVA_but_not_KW_stage, varwidth = T, horizontal = T,las= 2, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = ANOVA_but_not_KW[2,"PROBE_ID"], xlab = "log2(fluorescence)", ylab = "") graphics::boxplot(as.numeric(ANOVA_but_not_KW[3,-1])~ANOVA_but_not_KW_stage, varwidth = T, horizontal = T,las= 2, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = ANOVA_but_not_KW[3,"PROBE_ID"], xlab = "log2(fluorescence)", ylab = "") # check boxplot of peptide with very signif kruskal-wallis pval but not ANOVA pval KW_but_not_ANOVA <- raw_data_median %>% filter(all_anova_pval > .7 & all_kw_pval < .001) %>% select(PROBE_ID, any_of(array_id_key$id)) %>% as.matrix() KW_but_not_ANOVA_iii <- match( colnames(KW_but_not_ANOVA[, -1]), patient_key$id ) KW_but_not_ANOVA_stage <- patient_key$stage[KW_but_not_ANOVA_iii] KW_but_not_ANOVA_stage <- factor(KW_but_not_ANOVA_stage) sum(as.numeric( colnames(KW_but_not_ANOVA[, -1]) == patient_key$id[KW_but_not_ANOVA_iii] )) == nrow(patient_key) par(mfrow=c(3,1)) par(mar=c(5.1, 6.1, 4.1, 2.1)) graphics::boxplot(as.numeric(KW_but_not_ANOVA[1,-1])~KW_but_not_ANOVA_stage, varwidth = T, horizontal = T,las= 2, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = KW_but_not_ANOVA[1,"PROBE_ID"], xlab = "log2(fluorescence)", ylab = "") graphics::boxplot(as.numeric(KW_but_not_ANOVA[2,-1])~KW_but_not_ANOVA_stage, varwidth = T, horizontal = T,las= 2, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = KW_but_not_ANOVA[2,"PROBE_ID"], xlab = "log2(fluorescence)", ylab = "") graphics::boxplot(as.numeric(KW_but_not_ANOVA[3,-1])~KW_but_not_ANOVA_stage, varwidth = T, horizontal = T,las= 2, col = c("navy", "cornflowerblue", "turquoise1","darkorange1", "firebrick1"), main = KW_but_not_ANOVA[3,"PROBE_ID"], xlab = "log2(fluorescence)", ylab = "") #--------------------------------------------------------------------------------------- # PCA after Kruskal-Wallis anova_dat <- raw_data_median %>% select(PROBE_ID, any_of(patient_key$id)) %>% mutate(anova_BH = all_kw$anova_BH[raw_data_median$PROBE_ID]) %>% filter(anova_BH <= BH_FDR_cutoff) %>% select(-anova_BH) anova_dat_demean <- sweep(as.matrix(anova_dat %>% select(-PROBE_ID)), 1, rowMeans(as.matrix(anova_dat %>% select(-PROBE_ID))), "-") # centering by row # make sure stage aligns with anova_dat_demean visual_iii <- match( colnames(anova_dat_demean) , patient_key$id ) visual_stage <- patient_key$stage[visual_iii] # colors and shapes for the visualization techniques cols = pal[ match(visual_stage, names(pal)) ] shapes = shp[ match(visual_stage, names(shp)) ] # svd sv.dat <- sweep(t(anova_dat_demean), 2, colMeans(t(anova_dat_demean)), "-") # centering sv <- svd(sv.dat) V <- sv$v D <- sv$d U <- sv$u # variance explained pca.var <- D^2/sum(D^2) pca.cumvar <- cumsum(pca.var) # plot PCA par(mfrow = c(1,2), pty = "s", mar = c(2.2,2.3,1.5,0.45), mgp = c(1.6,0.4,0), cex.axis = 0.84, cex.lab = 0.84, cex.main = 0.84, tcl = -0.4) PCload.func(cols, shapes, U, D, 1, 2, pca.var, title = "PC2 vs PC1") # PC loadings (PC2 vs PC1) legend('topright', pch = shp, col = pal, cex = 0.5, c("normal", "new_dx", "nmCSPC", "mCSPC", "nmCRPC", "mCRPC") ) PCload.func(cols, shapes, U, D, 3, 2, pca.var, title = "PC2 vs PC3") # PC loadings (PC2 vs PC3) dev.off() ####################################################################################### # Pairwise Comparisons # ####################################################################################### # we want the following contrasts: # consecutive-group comparison: mCRPC-nmCRPC, nmCRPC-nmCSPS,nmCSPC-new_dx, new_dx-normal # normal vs canceer # mCRPC vs the others # first make sure stage aligns with raw_data_median sum(as.numeric(colnames(raw_data_median %>% select(-(PROBE_DESIGN_ID:DESIGN_ID))) == patient_key$id)) == nrow(patient_key) # set BH-FDR cutoff BH_FDR_cutoff <- .05 # get group medians group_median.func <- function(group, BH_filter){ raw_data_median %>% select(-(PROBE_DESIGN_ID:DESIGN_ID)) %>% select(which(patient_key$stage %in% group)) %>% # filter(all_anova$anova_BH <= BH_filter) %>% filter(all_kw$anova_BH <= BH_filter) %>% as.matrix() %>% matrixStats::rowMedians() } mCRPC_median <- group_median.func("mCRPC", BH_FDR_cutoff) nmCRPC_median <- group_median.func("nmCRPC", BH_FDR_cutoff) nmCSPC_median <- group_median.func("nmCSPC", BH_FDR_cutoff) newdx_median <- group_median.func("new_dx", BH_FDR_cutoff) normal_median <- group_median.func("normal", BH_FDR_cutoff) cancer_median <- group_median.func(c("new_dx", "nmCSPC", "nmCRPC", "mCRPC"), BH_FDR_cutoff) NOT_mCRPC_median <- group_median.func(c("normal", "new_dx", "nmCSPC", "nmCRPC"), BH_FDR_cutoff) # might need group means? # group_means.func <- function(group, BH_filter){ # raw_data_median %>% # select(-(PROBE_DESIGN_ID:DESIGN_ID)) %>% # select(which(patient_key$stage %in% group)) %>% # # filter(all_anova$anova_BH <= BH_filter) %>% # filter(all_kw$anova_BH <= BH_filter) %>% # rowMeans() # } #---------------------------------------------------------------------------------------------- # wilcoxon rank-sum tests # median_subset <- raw_data_median %>% # filter(all_kw$anova_BH <= BH_FDR_cutoff) %>% # change KW BH threshold here! # select(-(PROBE_DESIGN_ID:DESIGN_ID)) %>% # as.matrix() # # # initiate wilcox-pval # mCRPC_nmCRPC_wilcox_pval <- rep(NA, nrow(median_subset)) # nmCRPC_nmCSPC_wilcox_pval <- rep(NA, nrow(median_subset)) # nmCSPC_newdx_wilcox_pval <- rep(NA, nrow(median_subset)) # newdx_normal_wilcox_pval <- rep(NA, nrow(median_subset)) # cancer_normal_wilcox_pval <- rep(NA, nrow(median_subset)) # mCRPC_others_wilcox_pval <- rep(NA, nrow(median_subset)) # # # get wilcox pval (2-sided) # for(i in 1: nrow(median_subset)){ # mCRPC_nmCRPC_wilcox_pval[i] <- wilcox.test( # x = as.numeric(median_subset[i, patient_key$stage == "mCRPC"]), # y = as.numeric(median_subset[i, patient_key$stage == "nmCRPC"]), # alternative = "two.sided", exact = T # )$'p.value' # nmCRPC_nmCSPC_wilcox_pval[i] <- wilcox.test( # x = as.numeric(median_subset[i, patient_key$stage == "nmCRPC"]), # y = as.numeric(median_subset[i, patient_key$stage == "nmCSPC"]), # alternative = "two.sided", exact = T # )$'p.value' # nmCSPC_newdx_wilcox_pval[i] <- wilcox.test( # x = as.numeric(median_subset[i, patient_key$stage == "nmCSPC"]), # y = as.numeric(median_subset[i, patient_key$stage == "new_dx"]), # alternative = "two.sided", exact = T # )$'p.value' # newdx_normal_wilcox_pval[i] <- wilcox.test( # x = as.numeric(median_subset[i, patient_key$stage == "new_dx"]), # y = as.numeric(median_subset[i, patient_key$stage == "normal"]), # alternative = "two.sided", exact = T # )$'p.value' # cancer_normal_wilcox_pval[i] <- wilcox.test( # x = as.numeric(median_subset[i, patient_key$stage %in% c("new_dx", "nmCSPC", "nmCRPC", "mCRPC")]), # y = as.numeric(median_subset[i, patient_key$stage == "normal"]), # alternative = "two.sided", exact = T # )$'p.value' # mCRPC_others_wilcox_pval[i] <- wilcox.test( # x = as.numeric(median_subset[i, patient_key$stage == "mCRPC"]), # y = as.numeric(median_subset[i, patient_key$stage %in% c("normal", "new_dx", "nmCSPC", "nmCRPC")]), # alternative = "two.sided", exact = T # )$'p.value' # print(i) # } # #---------------------------------------------------------------------------------------------- # get the kruskal-wallis 5% BH FDR peptide counts kw_FDR5prct <- length(all_kw$anova_BH[all_kw$anova_BH <= .05]) # pval histograms wilcox_pval_df <- data.frame( group_pair = c( rep("mCRPC vs nmCRPC", kw_FDR5prct), rep("nmCRPC vs nmCSPC", kw_FDR5prct), rep("nmCSPC vs new_dx", kw_FDR5prct), rep("new_dx vs normal", kw_FDR5prct), rep("cancer vs normal", kw_FDR5prct), rep("mCRPC vs others", kw_FDR5prct) ), p_values = c( mCRPC_nmCRPC_wilcox_pval, nmCRPC_nmCSPC_wilcox_pval, nmCSPC_newdx_wilcox_pval, newdx_normal_wilcox_pval, cancer_normal_wilcox_pval, mCRPC_others_wilcox_pval ) ) wilcox_pval_df$group_pair <- factor(wilcox_pval_df$group_pair, levels = c( "cancer vs normal", "mCRPC vs others", "mCRPC vs nmCRPC", "nmCRPC vs nmCSPC", "nmCSPC vs new_dx", "new_dx vs normal" )) ggplot(wilcox_pval_df, aes(x = p_values)) + geom_histogram(aes(y=..density..), bins = 50) + facet_wrap(. ~ group_pair, ncol=2) + labs(x = "Wilcoxon p-values", title = paste0("Density Histograms of the ", kw_FDR5prct, " Wilcoxon p-values")) + theme(plot.title = element_text(hjust = 0.5)) #---------------------------------------------------------------------------------------------- # get BH-corrected pval (restricted to signif peptides from Kruskal-Wallis) mCRPC_nmCRPC_wilcox_BH <- p.adjust(mCRPC_nmCRPC_wilcox_pval, method = "BH") nmCRPC_nmCSPC_wilcox_BH <- p.adjust(nmCRPC_nmCSPC_wilcox_pval, method = "BH") nmCSPC_newdx_wilcox_BH <- p.adjust(nmCSPC_newdx_wilcox_pval, method = "BH") newdx_normal_wilcox_BH <- p.adjust(newdx_normal_wilcox_pval, method = "BH") cancer_normal_wilcox_BH <- p.adjust(cancer_normal_wilcox_pval, method = "BH") mCRPC_others_wilcox_BH <- p.adjust(mCRPC_others_wilcox_pval, method = "BH") wilcox_peptide_counts_df <- data.frame( pairwise_comparison = c( "cancer vs normal", "mCRPC vs others", "mCRPC vs nmCRPC", "nmCRPC vs nmCSPC", "nmCSPC vs new_dx", "new_dx vs normal" ), peptide_counts = c( length(which(abs(cancer_median - normal_median) > 1 & cancer_normal_wilcox_BH <= BH_FDR_cutoff)), length(which(abs(mCRPC_median - NOT_mCRPC_median) > 1 & mCRPC_others_wilcox_BH <= BH_FDR_cutoff)), length(which(abs(mCRPC_median - nmCRPC_median) > 1 & mCRPC_nmCRPC_wilcox_BH <= BH_FDR_cutoff)), length(which(abs(nmCRPC_median - nmCSPC_median) > 1 & nmCRPC_nmCSPC_wilcox_BH <= BH_FDR_cutoff)), length(which(abs(nmCSPC_median - newdx_median) > 1 & nmCSPC_newdx_wilcox_BH <= BH_FDR_cutoff)), length(which(abs(newdx_median - normal_median) > 1 & newdx_normal_wilcox_BH<= BH_FDR_cutoff)) ) ) #---------------------------------------------------------------------------------------------- # volcano plots of contrasts # make sure contrast_diff and contrast_pval and contrast_BH of same length !! contrast_volcano_plot.func <- function(contrast_diff, contrast_pval, contrast_BH, test_type, measure, contrast_title, xlim = c(-7,6), ylim = c(0,8)){ signif_counts = length(which(abs(contrast_diff) > 1 & contrast_BH <= BH_FDR_cutoff)) horizontal_pval = max(contrast_pval[contrast_BH<= BH_FDR_cutoff]) plot(x = contrast_diff, y = -log10(contrast_pval), pch = 20, xlim = xlim, ylim = ylim, las = 1, xlab = paste0("difference of ", measure, " log2(fluorescence)"), ylab = paste0("-log10(contrast ",test_type, " p-values)"), main = paste0("Volcano plot of contrast: ", contrast_title)) text(x = 4, y = 7, paste0(signif_counts, " signif peptides")) lines(x = contrast_diff[ contrast_BH <= BH_FDR_cutoff & abs(contrast_diff) >= 1 ], y = -log10(contrast_pval[ contrast_BH <= BH_FDR_cutoff & abs(contrast_diff) >= 1]), type = "p", pch = 20, col = "red") abline(v = 1, col = "blue", lty = 2, lwd = 2) abline(v = -1, col = "blue", lty = 2, lwd = 2) abline(h = -log10(horizontal_pval), col = "blue", lty = 2, lwd = 2) } # png("09_contrast_volcano_plots(KW_wilcox_diffmedian_cutoff).png", width = 1024, height = 1024) par(mfrow = c(3,2)) # cancer vs normal contrast_volcano_plot.func(cancer_median - normal_median, cancer_normal_wilcox_pval, cancer_normal_wilcox_BH, "Wilcoxon", "median", "cancer vs normal") # mCRPC vs others contrast_volcano_plot.func(mCRPC_median - NOT_mCRPC_median, mCRPC_others_wilcox_pval, mCRPC_others_wilcox_BH, "Wilcoxon", "median", "mCRPC vs others" ) # mCRPC vs nmCRPC contrast_volcano_plot.func(mCRPC_median - nmCRPC_median, mCRPC_nmCRPC_wilcox_pval, mCRPC_nmCRPC_wilcox_BH, "Wilcoxon", "median", "mCRPC vs nmCRPC") # nmCRPC vs nmCSPC contrast_volcano_plot.func(nmCRPC_median - nmCSPC_median, nmCRPC_nmCSPC_wilcox_pval, nmCRPC_nmCSPC_wilcox_BH, "Wilcoxon", "median", "nmCRPC vs nmCSPC") # nmCSPC vs new_dx contrast_volcano_plot.func(nmCSPC_median - newdx_median, nmCSPC_newdx_wilcox_pval, nmCSPC_newdx_wilcox_BH, "Wilcoxon", "median", "nmCSPC vs new_dx") # new_dx vs normal contrast_volcano_plot.func(newdx_median - normal_median, newdx_normal_wilcox_pval, newdx_normal_wilcox_BH, "Wilcoxon", "median", "new_dx vs normal") dev.off() ####################################################################################### # Visualization # ####################################################################################### # replot subset of ANOVA residual heatmap based on effect-size threshold from post-hoc analysis posthoc_signif_crit <- ( abs(mCRPC_median - nmCRPC_median) > 1 & mCRPC_nmCRPC_wilcox_BH <= BH_FDR_cutoff ) | ( abs(nmCRPC_median - nmCSPC_median) > 1 & nmCRPC_nmCSPC_wilcox_BH <= BH_FDR_cutoff ) | ( abs(nmCSPC_median - newdx_median) > 1 & nmCSPC_newdx_wilcox_BH <= BH_FDR_cutoff ) | ( abs(newdx_median - normal_median) > 1 & newdx_normal_wilcox_BH<= BH_FDR_cutoff ) | ( abs(cancer_median - normal_median) > 1 & cancer_normal_wilcox_BH <= BH_FDR_cutoff ) | ( abs(mCRPC_median - NOT_mCRPC_median) > 1 & mCRPC_others_wilcox_BH <= BH_FDR_cutoff ) # check length(posthoc_signif_crit) sum(as.numeric(posthoc_signif_crit)) secondary_cutoff_counts <- sum(as.numeric(posthoc_signif_crit)) anova_dat <- raw_data_median %>% select(PROBE_ID, any_of(patient_key$id)) %>% # mutate(anova_BH = all_anova$anova_BH[raw_data_median$PROBE_ID]) %>% mutate(anova_BH = all_kw$anova_BH[raw_data_median$PROBE_ID]) %>% filter(anova_BH <= BH_FDR_cutoff) %>% select(-anova_BH) %>% filter(posthoc_signif_crit) anova_dat_demean <- sweep(as.matrix(anova_dat %>% select(-PROBE_ID)), 1, rowMeans(as.matrix(anova_dat %>% select(-PROBE_ID))), "-") # centering by row # check dim(anova_dat_demean) # make sure stage aligns with anova_dat_demean visual_iii <- match( colnames(anova_dat_demean) , patient_key$id ) visual_stage <- patient_key$stage[visual_iii] #-------------------------------------------------------------------------------------------- # heatmap # colors and shapes for the visualization techniques cols = pal[ match(visual_stage, names(pal)) ] # cls <- colorRampPalette(c("navy", "honeydew", "firebrick3", "brown"))(n = 1024) # cls <- colorRampPalette(c("navy", "honeydew", "sienna1", "firebrick3", "brown"))(n = 1024) cls <- colorRampPalette(c("navy", "honeydew", "firebrick1"))(n = 1024) get_column_order.func <- function(stages){ heat_map <- heatmap3(anova_dat_demean[,visual_stage == stages],col = cls, labRow = "", scale = "none", showColDendro = F, showRowDendro = F) return( colnames(anova_dat_demean[,visual_stage == stages])[heat_map$colInd] ) } normal_id_order <- get_column_order.func("normal") newdx_id_order <- get_column_order.func("new_dx") nmCSPC_id_order <- get_column_order.func("nmCSPC") nmCRPC_id_order <- get_column_order.func("nmCRPC") mCRPC_id_order <- get_column_order.func("mCRPC") id_order <- match( c(normal_id_order, newdx_id_order, nmCSPC_id_order, nmCRPC_id_order, mCRPC_id_order), colnames(anova_dat_demean) ) # winsorize quantile(as.numeric(anova_dat_demean), probs = c(.01, .05, .1, .15, .2, .25, .3, .7, .75, .8, .85, .9, .95)) # check ecdf(as.numeric(anova_dat_demean))(c(-3.5, -2.6, -2, 2, 2.6, 3.5)) # check anova_dat_demean_winsorize <- t( apply(anova_dat_demean, 1, function(x){ x[x < -2] = -2 x[x > 2] = 2 return(x) }) ) # png("09_residual_heatmap(KW_wilcox_diffmedian_cutoff).png", width = 1024, height = 1024) heatmap3(anova_dat_demean_winsorize[,id_order], col = cls, # specify colors ColSideColors = cols[id_order], # specify patient color code Colv = NA, scale = "none", # no scaling by row labCol = visual_stage[id_order], # specify patient ColSideLabs = "stages", labRow = "", xlab = "Patients", legendfun=function() showLegend(col = c("navy", "cornflowerblue", "turquoise1", "darkorange1", "firebrick1"), legend = c("normal", "new_dx", "nmCSPC", "nmCRPC", "mCRPC"), cex = 1.2, lwd = 5 ) ) dev.off() #-------------------------------------------------------------------------------------------- # PCA # colors and shapes for the visualization techniques cols = pal[ match(visual_stage, names(pal)) ] shapes = shp[ match(visual_stage, names(shp)) ] # svd sv.dat <- sweep(t(anova_dat_demean), 2, colMeans(t(anova_dat_demean)), "-") # centering sv <- svd(sv.dat) V <- sv$v D <- sv$d U <- sv$u # variance explained pca.var <- D^2/sum(D^2) pca.cumvar <- cumsum(pca.var) # plot PCA par(mfrow = c(1,2), pty = "s", mar = c(2.2,2.3,1.5,0.45), mgp = c(1.6,0.4,0), cex.axis = 0.84, cex.lab = 0.84, cex.main = 0.84, tcl = -0.4) PCload.func(cols, shapes, U, D, 1, 2, pca.var, title = "PC2 vs PC1") # PC loadings (PC2 vs PC1) legend('topright', pch = shp, col = pal, cex = 0.5, c("normal", "new_dx", "nmCSPC", "mCSPC", "nmCRPC", "mCRPC") ) PCload.func(cols, shapes, U, D, 3, 2, pca.var, title = "PC2 vs PC3") # PC loadings (PC2 vs PC3) dev.off() ####################################################################################### # Gene Set Analyses After Kruskal-Wallis & Wilcoxon Tests # ####################################################################################### # read uniprot_gene csv uniprot_gene <- read_csv("uniprot_data_entrez.csv", col_types = cols_only( seq_id = col_character(), uniprot_id = col_character(), gene_symbol = col_character(), entrez_gene_id_pete = col_double(), gene_names = col_character(), protein_names = col_character() )) %>% filter(!(is.na(seq_id)) & !(is.na(entrez_gene_id_pete))) %>% select(seq_id, uniprot_id, gene_symbol, entrez_gene_id_pete, gene_names, protein_names) # check if seq_id & entrez_id unique uniprot_gene <- uniprot_gene[!(is.na(uniprot_gene$entrez_gene_id_pete)),] # just in case length(unique(uniprot_gene$seq_id)) == length(uniprot_gene$seq_id) # yes! unique! length(unique(uniprot_gene$entrez_gene_id_pete)) == length(uniprot_gene$entrez_gene_id_pete) # NOT unique # which seq_id has repeated gene_symbol genesymb_repeat <- as.data.frame( uniprot_gene[ uniprot_gene$entrez_gene_id_pete %in% (uniprot_gene %>% group_by(entrez_gene_id_pete) %>% tally() %>% filter(n > 1) %>% pull(entrez_gene_id_pete)) , ] ) entrez_id_repeat <- as.character( unique(genesymb_repeat$entrez_gene_id_pete) ) # # check if these seq_id make the Kruskal-Wallis 5% BH FDR cutoff ? # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff] # yes...fine... # # check if these seq_id make at least one of the secondary cutoffs ? # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][posthoc_signif_crit] # yes...fine # # check each contrast one by one # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][( abs(mCRPC_median - nmCRPC_median) > 1 & mCRPC_nmCRPC_wilcox_BH <= BH_FDR_cutoff ) ] # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][( abs(nmCRPC_median - nmCSPC_median) > 1 & nmCRPC_nmCSPC_wilcox_BH <= BH_FDR_cutoff ) ] # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][( abs(nmCSPC_median - newdx_median) > 1 & nmCSPC_newdx_wilcox_BH <= BH_FDR_cutoff ) ] # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][( abs(newdx_median - normal_median) > 1 & newdx_normal_wilcox_BH<= BH_FDR_cutoff ) ] # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][( abs(cancer_median - normal_median) > 1 & cancer_normal_wilcox_BH <= BH_FDR_cutoff ) ] # genesymb_repeat$seq_id %in% raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][( abs(mCRPC_median - NOT_mCRPC_median) > 1 & mCRPC_others_wilcox_BH <= BH_FDR_cutoff )] # DECISION: treat them as repeats in the microarray # protein deemed signif if either one of the repeated seq_id makes the cutoff get_SeqID.func <- function(diff, BH){ signif_seq_id <- unique( raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][abs(diff) > 1 & BH <= BH_FDR_cutoff] ) seq_id_ok <- as.numeric(uniprot_gene$seq_id %in% signif_seq_id) names(seq_id_ok) <- uniprot_gene$entrez_gene_id_pete seq_id_ok2 <- seq_id_ok[!(names(seq_id_ok) %in% entrez_id_repeat)] seq_id_ok2 <- c(seq_id_ok2, sapply( entrez_id_repeat, function(x){max(seq_id_ok[which(names(seq_id_ok) == x)])} ) ) } cancer_normal_SeqID <- get_SeqID.func(cancer_median - normal_median, cancer_normal_wilcox_BH) mCRPC_others_SeqID <- get_SeqID.func(mCRPC_median - NOT_mCRPC_median, mCRPC_others_wilcox_BH) mCRPC_nmCRPC_SeqID <- get_SeqID.func(mCRPC_median - nmCRPC_median, mCRPC_nmCRPC_wilcox_BH) nmCRPC_nmCSPC_SeqID <- get_SeqID.func(nmCRPC_median - nmCSPC_median, nmCRPC_nmCSPC_wilcox_BH) nmCSPC_newdx_SeqID <- get_SeqID.func(nmCSPC_median - newdx_median, nmCSPC_newdx_wilcox_BH) newdx_normal_SeqID <- get_SeqID.func(newdx_median - normal_median, newdx_normal_wilcox_BH) # gene-set analysis via allez! cancer_normal_allez.go <- allez(cancer_normal_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") mCRPC_others_allez.go <- allez(mCRPC_others_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") mCRPC_nmCRPC_allez.go <- allez(mCRPC_nmCRPC_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") nmCRPC_nmCSPC_allez.go <- allez(nmCRPC_nmCSPC_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") nmCSPC_newdx_allez.go <- allez(nmCSPC_newdx_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") newdx_normal_allez.go <- allez(newdx_normal_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") #--------------------------------------------------------------------------------------------------- # get allez results nom.alpha <- 0.05 max_gene_in_set <- 300 # Extract a table of top-ranked functional sets from allez output # Display an image of gene scores by functional sets # cancel vs normal allezTable(cancer_normal_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(cancer_normal_allez.go) allezPlot(cancer_normal_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) # mCRPC vs others allezTable(mCRPC_others_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(mCRPC_others_allez.go) allezPlot(mCRPC_others_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) # mCRPC vs nmCRPC allezTable(mCRPC_nmCRPC_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(mCRPC_nmCRPC_allez.go) allezPlot(mCRPC_nmCRPC_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) # nmCRPC vs nmCSPC allezTable(nmCRPC_nmCSPC_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(nmCRPC_nmCSPC_allez.go) allezPlot(nmCRPC_nmCSPC_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) # nmCSPC vs new_dx allezTable(nmCSPC_newdx_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(nmCSPC_newdx_allez.go) allezPlot(nmCSPC_newdx_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) # new_dx vs normal allezTable(newdx_normal_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(newdx_normal_allez.go) allezPlot(newdx_normal_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) ####################################################################################### # Data Processing -- part II # ####################################################################################### pal_proj2 <- c("turquoise1", "cornflowerblue","navy", "orchid1", "darkorange1", "firebrick1") names(pal_proj2) <- c("ADT_time:0", "ADT_time:3", "ADT_time:6", "PAP_time:0", "PAP_time:3", "PAP_time:6") array_id_key_proj2 = read_tsv("sample_key_project2.txt") %>% janitor::clean_names() %>% rename(treatment = condition, array_id = "file_name") %>% mutate(id = tolower(id)) sample_key_proj2 = array_id_key_proj2 %>% group_by(id, time) %>% summarize(n = n()) %>% ungroup() %>% filter(n>=2) # check table(sample_key_proj2$n) ## all patients associated with 3 replicates for each of the 3 time points # remove patients with no replicates array_id_key_proj2 = array_id_key_proj2 %>% filter(id %in% sample_key_proj2$id) # make sure sample_key_proj2 align with raw_data_median_proj2 sample_key_proj2 <- sample_key_proj2 %>% select(-n) %>% arrange(time, id) sample_key_proj2 <- sample_key_proj2 %>% left_join(array_id_key_proj2 %>% select(id, treatment) %>% distinct()) # check sum(as.numeric( colnames(raw_data_median_proj2 %>% select(-(PROBE_DESIGN_ID:DESIGN_ID))) == paste( paste0("id:", sample_key_proj2$id), paste0("time:", sample_key_proj2$time), sep = "_" ) )) == ncol(raw_data_median_proj2 %>% select(-(PROBE_DESIGN_ID:DESIGN_ID))) #---------------------------------------------------------------------------------------- # read fluorescence data # raw_data = read_csv("raw_data_complete.csv") # # raw_data = raw_data %>% # select(PROBE_DESIGN_ID:Y, any_of(array_id_key_proj2$array_id)) %>% # drop patients with records at different stages # select( -c(X, Y, MATCH_INDEX, DESIGN_NOTE, SELECTION_CRITERIA, MISMATCH, PROBE_CLASS) ) # drop unhelpful columns # # # check # colnames(raw_data)[1:15] # # # take log2 transformation # raw_data <- raw_data %>% # mutate_at(vars(matches("dat")), log2) # # # check any NA's # raw_data %>% # select_if(function(x) any(is.na(x))) # # # make sure array_id_key_proj2 align with raw_data_complete # array_iii <- match( colnames( raw_data %>% select(contains("dat")) ), array_id_key_proj2$array_id ) # array_id_key_proj2 <- array_id_key_proj2[array_iii , ] # sum(as.numeric( colnames( raw_data %>% select(contains("dat")) ) # == array_id_key_proj2$array_id )) == nrow(array_id_key_proj2) # # # # compute median # raw_data_median_proj2 <- t( apply( select(raw_data, contains("dat")), 1, function(x) { # as.vector( tapply( as.numeric(x), list(array_id_key_proj2$id, array_id_key_proj2$time), FUN=median) ) # } ) ) # raw_data_median_proj2 <- bind_cols( select(raw_data, -contains("dat")), as.data.frame(raw_data_median_proj2) ) # # colnames(raw_data_median_proj2)[1:15] # check # # # want to rename column # example_row <- tapply( as.numeric(select(raw_data, contains("dat"))[1,]), # list(array_id_key_proj2$id, array_id_key_proj2$time), FUN=median) %>% # as.data.frame() %>% # rownames_to_column("id") %>% # pivot_longer(-id, names_to = "time", values_to = "fluorescence") %>% # arrange(time, id) # sum(as.numeric( example_row$fluorescence == select(raw_data_median_proj2, contains("V"))[1,] )) == nrow(example_row) # example_row$column_name <- paste( paste0("id:", example_row$id), paste0("time:", example_row$time), sep = "_" ) # raw_data_median_proj2 <- raw_data_median_proj2 %>% rename_at(vars(contains("V")), ~ example_row$column_name) # # colnames(raw_data_median_proj2)[11:130] <- example_row$column_name # # # make sure sample_key_proj2 align with raw_data_median_proj2 # sample_key_proj2 <- sample_key_proj2 %>% # select(-n) %>% # arrange(time, id) # sum(as.numeric(sample_key_proj2$id == example_row$id)) == nrow(sample_key_proj2) # check # sum(as.numeric(sample_key_proj2$time == example_row$time)) == nrow(sample_key_proj2) # check # sample_key_proj2 <- sample_key_proj2 %>% # left_join(array_id_key_proj2 %>% select(id, treatment) %>% distinct()) # # write.table(raw_data_median_proj2, file = "raw_data_median_proj2.csv", sep = ",", row.names = F) ####################################################################################### # Check Fluorescence Normalization # ####################################################################################### median_long_proj2 <- raw_data_median_proj2 %>% select(contains("id:")) %>% pivot_longer(cols = everything(), names_to = "id_time", values_to = "fluorescence") # check nrow(median_long_proj2) == nrow(raw_data_median_proj2) * nrow(sample_key_proj2) head(median_long_proj2) # set fill color median_long_proj2$treat_time <- rep( paste(sample_key_proj2$treatment, sample_key_proj2$time, sep = "_"), 177604) median_long_proj2 <- median_long_proj2 %>% mutate(treat_time = as_factor(treat_time), treat_time = fct_recode(treat_time, "ADT_time:0" = "ADT_0", "ADT_time:3" = "ADT_3", "ADT_time:6" = "ADT_6", "PAP_time:0" = "Vaccine_0", "PAP_time:3" = "Vaccine_3", "PAP_time:6" = "Vaccine_6")) # sort order of patients in boxplot median_long_proj2$id_time <- factor(median_long_proj2$id_time, levels = c( unique(median_long_proj2$id_time[median_long_proj2$treat_time == "ADT_time:0"]), unique(median_long_proj2$id_time[median_long_proj2$treat_time == "ADT_time:3"]), unique(median_long_proj2$id_time[median_long_proj2$treat_time == "ADT_time:6"]), unique(median_long_proj2$id_time[median_long_proj2$treat_time == "PAP_time:0"]), unique(median_long_proj2$id_time[median_long_proj2$treat_time == "PAP_time:3"]), unique(median_long_proj2$id_time[median_long_proj2$treat_time == "PAP_time:6"]) )) ggplot(median_long_proj2, aes(x = id_time, y = fluorescence, fill = treat_time)) + geom_boxplot(outlier.shape = ".") + scale_fill_manual(name = "treatment_time", values = pal_proj2[levels(median_long_proj2$treat_time)]) + labs(title = "Boxplots of Peptide Fluorescence Levels for Patients at 3 time points", x = "Patient_Time", y = "Median log2 Fluorescence Levels") + theme(panel.background = element_rect(fill = "grey90"), panel.grid.major = element_line(color = "white"), panel.grid.minor = element_line(color = "white"), axis.text.x = element_text(angle = 90, hjust = 1, size = 4.3), legend.position = "bottom", plot.title = element_text(hjust = 0.5)) ####################################################################################### # Linear Mixed Model to Assess Time Effect (REML = TRUE) # # Separate Models for PAP and ADT Groups # ####################################################################################### ncol_med_proj2 <- ncol(raw_data_median_proj2) n_med_proj2 <- nrow(sample_key_proj2) # initiate PAP_resid_fit0 <- matrix(NA, nrow = nrow(raw_data_median_proj2), ncol = nrow(sample_key_proj2%>%filter(treatment == "Vaccine"))) ADT_resid_fit0 <- matrix(NA, nrow = nrow(raw_data_median_proj2), ncol = nrow(sample_key_proj2%>%filter(treatment == "ADT"))) PAP_result <- matrix(NA, nrow = nrow(raw_data_median_proj2), ncol = 8) ADT_result <- matrix(NA, nrow = nrow(raw_data_median_proj2), ncol = 8) colnames(PAP_resid_fit0) <- colnames(raw_data_median_proj2 %>% select(contains("id:pap"))) # colnames(PAP_resid_fit0) <- colnames(raw_data_median_proj2[,(ncol_med_proj2 - n_med_proj2 + 1) : ncol_med_proj2])[sample_key_proj2$treatment == "Vaccine"] colnames(ADT_resid_fit0) <- colnames(raw_data_median_proj2 %>% select(contains("id:adt"))) # colnames(ADT_resid_fit0) <- colnames(raw_data_median_proj2[,(ncol_med_proj2 - n_med_proj2 + 1) : ncol_med_proj2])[sample_key_proj2$treatment == "ADT"] colnames(PAP_result) <- paste0("PAP_", c( "time_effect", "time_tstat", "KR_df", "KR_Ftest_pval", "Satterthwaite_df", "Satterthwaite_Ftest_pval", "zval_1sided_KR", "zval_1sided_Satterthwaite" )) colnames(ADT_result) <- paste0("ADT_", c( "time_effect", "time_tstat", "KR_df", "KR_Ftest_pval", "Satterthwaite_df", "Satterthwaite_Ftest_pval", "zval_1sided_KR", "zval_1sided_Satterthwaite" )) Test_Time.func <- function(y, treat_type){ resp <- y[sample_key_proj2$treatment == treat_type] fit1 <- lmer(resp ~ time + (1 + time | id), REML = T, data = sample_key_proj2[sample_key_proj2$treatment == treat_type,]) fit0 <- lmer(resp ~ 1 + (1 + time | id), REML = T, data = sample_key_proj2[sample_key_proj2$treatment == treat_type,]) resid_fit0 <- unname(round(resid(fit0),4)) effect_tstat <- coef(summary(fit1))['time',c('Estimate', 't value')] KR_df_pval <- contest(fit1, c(0,1), ddf = "Kenward-Roger")[c('DenDF', 'Pr(>F)')] Satterthwaite_df_pval <- contest(fit1, c(0,1))[c('DenDF', 'Pr(>F)')] zval_1sided_KR <- qnorm(pt( as.numeric(effect_tstat['t value']), df = as.numeric(KR_df_pval['DenDF']) , lower.tail = T )) zval_1sided_Satterthwaite <- qnorm(pt( as.numeric(effect_tstat['t value']), df = as.numeric(Satterthwaite_df_pval['DenDF']) , lower.tail = T )) result <- c( as.numeric(effect_tstat), as.numeric(KR_df_pval), as.numeric(Satterthwaite_df_pval), zval_1sided_KR, zval_1sided_Satterthwaite ) return( list( resid_fit0 = resid_fit0, result = result ) ) } for(i in 1:nrow(raw_data_median_proj2)){ y <- as.numeric(raw_data_median_proj2[i, (ncol_med_proj2 - n_med_proj2 + 1) : ncol_med_proj2]) PAP_test <- Test_Time.func(y, "Vaccine") ADT_test <- Test_Time.func(y, "ADT") PAP_resid_fit0[i,] <- PAP_test$resid_fit0 PAP_result[i,] <- PAP_test$result ADT_resid_fit0[i,] <- ADT_test$resid_fit0 ADT_result[i,] <- ADT_test$result if(i %% 100 == 0){ print(i) } } # save(PAP_resid_fit0, ADT_resid_fit0, PAP_result, ADT_result, # file = "08_LMER_results.RData") PAP_Satterth_Ftest_pval <- PAP_result[,"PAP_Satterthwaite_Ftest_pval"] PAP_KR_Ftest_pval <- PAP_result[,"PAP_KR_Ftest_pval"] ADT_Satterth_Ftest_pval <- ADT_result[,"ADT_Satterthwaite_Ftest_pval"] ADT_KR_Ftest_pval <- ADT_result[,"ADT_KR_Ftest_pval"] PAP_Ftest_KR_BH <- p.adjust(PAP_KR_Ftest_pval, method="BH") PAP_Ftest_Satterthwaite_BH <- p.adjust(PAP_Satterth_Ftest_pval, method="BH") ADT_Ftest_KR_BH <- p.adjust(ADT_KR_Ftest_pval,method="BH") ADT_Ftest_Satterthwaite_BH <- p.adjust(ADT_Satterth_Ftest_pval,method="BH") #--------------------------------------------------------------------------------------------- # F-test p-values based on KR adjustments more conservative than Satterthwaite par(mfrow=c(1,2)) plot(PAP_Satterth_Ftest_pval[PAP_Satterth_Ftest_pval <= .2 & PAP_KR_Ftest_pval <= .2], PAP_KR_Ftest_pval[PAP_Satterth_Ftest_pval <= .2 & PAP_KR_Ftest_pval <= .2], pch = ".", xlim = c(0,.2), ylim = c(0,.2), las = 1, main = "Time Fixed Effect p-values \nfor PAP patients", xlab = "Satterthwaite F-test p-values", ylab = "Kenward-Roger (KR) F-test p-values") abline(a=0, b=1, col = "red", lty=2, lwd = 2) plot(ADT_Satterth_Ftest_pval[ADT_Satterth_Ftest_pval <= .2 & ADT_KR_Ftest_pval <= .2], ADT_KR_Ftest_pval[ADT_Satterth_Ftest_pval <= .2 & ADT_KR_Ftest_pval <= .2], pch = ".", xlim = c(0,.2), ylim = c(0,.2), las = 1, main = "Time Fixed Effect p-values \nfor ADT patients", xlab = "Satterthwaite F-test p-values", ylab = "Kenward-Roger (KR) F-test p-values") abline(a=0, b=1, col = "red", lty=2, lwd = 2) dev.off() count.func(PAP_Ftest_KR_BH, seq(.01,.05,by=.01)) count.func(PAP_Ftest_Satterthwaite_BH, seq(.01,.05,by=.01)) count.func(ADT_Ftest_KR_BH, seq(.63,.7,by=.01)) count.func(ADT_Ftest_Satterthwaite_BH, seq(.63,.7,by=.01)) # check sum(as.numeric( raw_data_median_proj2$PROBE_ID[PAP_Ftest_KR_BH <= .01] %in% raw_data_median_proj2$PROBE_ID[PAP_Ftest_Satterthwaite_BH <= .01] )) # tabulate Ftest_pval_counts <- data.frame( BH_FDR_thresholds = seq(.01, .05, by = .01), Peptide_counts_KR = count.func(PAP_Ftest_KR_BH, seq(.01,.05,by=.01))[2,2:6], Peptide_counts_Satterthwaite = count.func(PAP_Ftest_Satterthwaite_BH, seq(.01,.05,by=.01))[2,2:6] ) #--------------------------------------------------------------------------------------------- #p-value density histograms KR_Ftest_pval_df <- data.frame( treatment = c( rep("PAP", 177604*2), rep("ADT", 177604*2) ), method = rep( rep( c("Satterthwaite", "Kenward-Roger"), each = 177604 ), 2) , p_values = c( PAP_Satterth_Ftest_pval, PAP_KR_Ftest_pval, ADT_Satterth_Ftest_pval, ADT_KR_Ftest_pval ) ) ggplot(KR_Ftest_pval_df, aes(x = p_values, fill = method)) + geom_histogram(aes(y=..density..), bins = 100, position = "identity", alpha = .4) + facet_grid(. ~ treatment) + labs(x = "F-test p-values", title = paste0("Density Histograms of F-test p-values")) + theme(plot.title = element_text(hjust = 0.5), legend.position = "bottom") ####################################################################################### # Visualization # ####################################################################################### BH_FDR_cutoff_proj2 <- .05 signif_crit_proj2 <- (PAP_Ftest_KR_BH <= BH_FDR_cutoff_proj2) & (PAP_Ftest_Satterthwaite_BH <= BH_FDR_cutoff_proj2) & (PAP_result[,"PAP_time_effect"] > .3333) sum(as.numeric(signif_crit_proj2)) proj2_signif_count <- sum(as.numeric(signif_crit_proj2)) #--------------------------------------------------------------------------------------------- # volcano plots proj2_volcano_plot.func <- function(time_effect, pval, BH, title){ plot(x = time_effect, y = -log10(pval), pch = ".", las = 1, ylim = c(0,9), xlim = c(-.4, .9), xlab = "coefficient of time fixed effect", ylab = "-log10(KR F-test p-values)", main = title) lines(x = time_effect[ BH <= .01 & time_effect >= .3333 ], y = -log10(pval[ BH <= .01 & time_effect >= .3333]), type = "p", pch = ".", col = "red") } par(mfrow=c(1,2)) proj2_volcano_plot.func(PAP_result[,"PAP_time_effect"], PAP_result[,"PAP_KR_Ftest_pval"], PAP_Ftest_KR_BH, "PAP's volcano plot") abline(v = .3333, lty = 2, lwd = 1.5, col = "blue") proj2_volcano_plot.func(ADT_result[,"ADT_time_effect"], ADT_result[,"ADT_KR_Ftest_pval"], ADT_Ftest_KR_BH, "ADT's volcano plot") #--------------------------------------------------------------------------------------------- # heatmap proj2_resid <- PAP_resid_fit0[signif_crit_proj2,] dim(proj2_resid) # check proj2_resid_time <- sample_key_proj2$time[sample_key_proj2$treatment=="Vaccine"] # specify color scheme cls <- colorRampPalette(c("navy", "honeydew", "firebrick1"))(n = 1024) proj2_heatmap_pal <- c("lightgoldenrod1", "darkorange1", "brown") names(proj2_heatmap_pal) <- c(0,3,6) cols <- proj2_heatmap_pal[ match(proj2_resid_time, names(proj2_heatmap_pal)) ] # winsorize quantile(as.numeric(proj2_resid), probs = c(.01, .05, .1, .15, .2, .25, .3, .7, .75, .8, .85, .9, .95)) # check ecdf(as.numeric(proj2_resid))(c(-1.7, -1.4, 1.4, 1.7)) # check proj2_resid_winsorize <- t( apply(proj2_resid, 1, function(x){ x[x < -1.7] = -1.7 x[x > 1.7] = 1.7 return(x) }) ) # get column order of time 6 proj2_get_column_order.func <- function(resid_mat, Time){ heat_map <- heatmap3(resid_mat[,proj2_resid_time == Time],col = cls, labRow = "", scale = "none", showColDendro = F, showRowDendro = F) return( colnames(resid_mat[,proj2_resid_time == Time])[heat_map$colInd] ) } time6_order <- proj2_get_column_order.func(proj2_resid_winsorize,6) time0_order <- gsub("time:6", "time:0", time6_order) time3_order <- gsub("time:6", "time:3", time6_order) time_order <- match( c(time0_order, time3_order, time6_order), colnames(proj2_resid) ) heatmap3(proj2_resid_winsorize[,time_order], col = cls, # specify colors ColSideColors = cols[time_order], # specify time color code Colv = NA, scale = "none", # no scaling by row labCol = colnames(proj2_resid)[time_order], # specify patient_time ColSideLabs = "Time", labRow = "", xlab = "Patient_Time", legendfun=function() showLegend(col = proj2_heatmap_pal, legend = c("Time 0", "Time 3", "Time 6"), cex = 1.2, lwd = 5 ) ) #-------------------------------------------------------------------------------------------- # longitudinal boxplots # get pap_df from Write to Excel code chunks proj2_signif_boxplot_df <- raw_data_median_proj2 %>% select(PROBE_ID, contains("id:")) %>% filter( PROBE_ID %in% pap_df$PROBE_ID[1:6] ) proj2_signif_boxplot.func <- function(signif_mat, draw){ signif_mat2 <- signif_mat[,-1] signif_df <- data.frame( treatment = factor( toupper( substr(colnames(signif_mat2), 4,6) ) ), time = factor( str_sub( colnames(signif_mat2), -1,-1 ) ), fluorescence = as.numeric(signif_mat2[draw,]) ) ggplot(signif_df, aes(x = time, y = fluorescence, fill = treatment)) + geom_boxplot(width = 0.5, position=position_dodge2(width = 0.5)) + labs(title = paste0("Boxplots of Fluorescence Levels for \nPeptide: ", signif_mat$PROBE_ID[draw]), x = "Time", y = "log2 Median Fluorescence") + scale_fill_manual(values=c("#F8766D", "#00BFC4")) + ylim(c(2,13.2)) + theme(panel.background = element_rect(fill = "grey90"), panel.grid.major = element_line(color = "white"), panel.grid.minor = element_line(color = "white"), # legend.position = "bottom", plot.title = element_text(hjust = 0.5)) } grid.arrange( proj2_signif_boxplot.func(proj2_signif_boxplot_df,1), proj2_signif_boxplot.func(proj2_signif_boxplot_df,2), proj2_signif_boxplot.func(proj2_signif_boxplot_df,3), proj2_signif_boxplot.func(proj2_signif_boxplot_df,4), proj2_signif_boxplot.func(proj2_signif_boxplot_df,5), proj2_signif_boxplot.func(proj2_signif_boxplot_df,6), ncol = 2 ) ####################################################################################### # Gene Set Analyses After LMER # ####################################################################################### proj2_get_SeqID.func <- function(coeff, BH){ signif_seq_id <- unique( raw_data_median_proj2$SEQ_ID[coeff > .3333 & BH <= BH_FDR_cutoff_proj2] ) seq_id_ok <- as.numeric(uniprot_gene$seq_id %in% signif_seq_id) names(seq_id_ok) <- uniprot_gene$entrez_gene_id_pete seq_id_ok2 <- seq_id_ok[!(names(seq_id_ok) %in% entrez_id_repeat)] seq_id_ok2 <- c(seq_id_ok2, sapply( entrez_id_repeat, function(x){max(seq_id_ok[which(names(seq_id_ok) == x)])} ) ) } # deploy allez PAP_SeqID <- proj2_get_SeqID.func(PAP_result[,"PAP_time_effect"], pmin(PAP_Ftest_KR_BH,PAP_Ftest_Satterthwaite_BH)) PAP_allez.go <- allez(PAP_SeqID, lib = "org.Hs.eg", idtype = "ENTREZID", sets = "GO") # get allez result nom.alpha <- 0.05 max_gene_in_set <- 300 allezTable(PAP_allez.go, symbol = T, nominal.alpha = nom.alpha, n.upp = max_gene_in_set, in.set = T)[,c(1:5,7)] get_alleztable.func(PAP_allez.go) allezPlot(PAP_allez.go, nominal.alpha = nom.alpha, n.upp = max_gene_in_set) ####################################################################################### # Boxplot of interesting peptides # ####################################################################################### # first make sure stage aligns with raw_data_median sum(as.numeric(colnames(raw_data_median %>% select(-(PROBE_DESIGN_ID:DESIGN_ID))) == patient_key$id)) == nrow(patient_key) contrast_df.func <- function(contrast_BH, contrast_diff){ df <- data.frame( PROBE_ID = raw_data_median$PROBE_ID[all_kw$anova_BH <= BH_FDR_cutoff][contrast_BH <= BH_FDR_cutoff], SEQ_ID = raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][contrast_BH <= BH_FDR_cutoff], Effect_size = contrast_diff[contrast_BH <= BH_FDR_cutoff], KW_BH_FDR = all_kw$anova_BH[all_kw$anova_BH <= BH_FDR_cutoff][contrast_BH <= BH_FDR_cutoff] ) df <- df %>% filter(abs(Effect_size)>1) %>% arrange(desc(Effect_size)) %>% remove_rownames() %>% mutate(Effect_size = round(Effect_size, 4), KW_BH_FDR = round(KW_BH_FDR, 4)) return(df) } # based on wilcox test mCRPC_others_df <- contrast_df.func(mCRPC_others_wilcox_BH, mCRPC_median - NOT_mCRPC_median) cancer_normal_df <- contrast_df.func(cancer_normal_wilcox_BH, cancer_median - normal_median) mCRPC_nmCRPC_df <- contrast_df.func(mCRPC_nmCRPC_wilcox_BH, mCRPC_median - nmCRPC_median) nmCRPC_nmCSPC_df <- contrast_df.func(nmCRPC_nmCSPC_wilcox_BH, nmCRPC_median - nmCSPC_median) nmCSPC_newdx_df <- contrast_df.func(nmCSPC_newdx_wilcox_BH, nmCSPC_median - newdx_median) newdx_normal_df <- contrast_df.func(newdx_normal_wilcox_BH, newdx_median - normal_median) boxplot_func <- function(ref_df, grp1, grp2, draw, rename_grp1, rename_grp2, col = c("red", "blue")){ mat <- raw_data_median %>% filter(PROBE_ID %in% ref_df$PROBE_ID) mat <- mat[match(ref_df$PROBE_ID, mat$PROBE_ID), ] %>% select(-(PROBE_DESIGN_ID:DESIGN_ID)) %>% select(which(patient_key$stage %in% c(grp1, grp2))) %>% as.matrix() row.names(mat) <- ref_df$PROBE_ID mat_stage <- as.character(patient_key$stage[patient_key$stage %in% c(grp1, grp2)]) if (length(grp1) > 1){ mat_stage[mat_stage %in% grp1] = rename_grp1 } if (length(grp2) > 1){ mat_stage[mat_stage %in% grp2] = rename_grp2 } mat_stage = factor(mat_stage) par(mar = c(4.1, 5.5, 2.8, 1),cex = 0.84) graphics::boxplot( as.numeric(mat[draw,]) ~ mat_stage, varwidth = T, col=col, horizontal=TRUE, las=1, xlab = "log2(fluorescence)", ylab = "groups", main= paste(row.names(mat)[draw]) ) } png("09_1a_Cancer_higher_than_Normal.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=1) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=2) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=3) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=4) dev.off() png("09_1b_Normal_higher_than_Cancer.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=nrow(cancer_normal_df)) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=nrow(cancer_normal_df)-1) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=nrow(cancer_normal_df)-2) boxplot_func(ref_df=cancer_normal_df,grp1=c("new_dx","nmCSPC","nmCRPC","mCRPC"),grp2="normal",rename_grp1="cancer",draw=nrow(cancer_normal_df)-3) dev.off() png("09_2a_mCRPC_higher_than_others.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=1) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=2) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=3) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=4) dev.off() png("09_2b_others_higher_than_mCRPC.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=nrow(mCRPC_others_df)) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=nrow(mCRPC_others_df)-1) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=nrow(mCRPC_others_df)-2) boxplot_func(ref_df=mCRPC_others_df,grp1="mCRPC",grp2=c("new_dx","nmCSPC","nmCRPC","normal"),rename_grp2="others",draw=nrow(mCRPC_others_df)-3) dev.off() png("09_3a_Newdx_higher_than_Normal.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = 1) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = 2) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = 3) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = 4) dev.off() png("09_3b_Normal_higher_than_Newdx.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = nrow(newdx_normal_df)) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = nrow(newdx_normal_df)-1) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = nrow(newdx_normal_df)-2) boxplot_func(ref_df=newdx_normal_df,grp1="new_dx",grp2="normal",draw = nrow(newdx_normal_df)-3) dev.off() png("09_4a_nmCSPC_higher_than_Newdx.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = 1) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = 2) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = 3) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = 4) dev.off() png("09_4b_Newdx_higher_than_nmCSPC.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = nrow(nmCSPC_newdx_df)) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = nrow(nmCSPC_newdx_df)-1) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = nrow(nmCSPC_newdx_df)-2) boxplot_func(ref_df=nmCSPC_newdx_df,grp1="nmCSPC",grp2="new_dx",draw = nrow(nmCSPC_newdx_df)-3) dev.off() png("09_5a_nmCRPC_higher_than_nmCSPC.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=1) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=2) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=3) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=4) dev.off() png("09_5b_nmCSPC_higher_than_nmCRPC.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=nrow(nmCRPC_nmCSPC_df)) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=nrow(nmCRPC_nmCSPC_df)-1) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=nrow(nmCRPC_nmCSPC_df)-2) boxplot_func(ref_df=nmCRPC_nmCSPC_df,grp1="nmCRPC",grp2="nmCSPC",draw=nrow(nmCRPC_nmCSPC_df)-3) dev.off() png("09_6a_mCRPC_higher_than_nmCRPC.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=1) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=2) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=3) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=4) dev.off() png("09_6b_nmCRPC_higher_than_mCRPC.png", height = 1024, width = 512) par(mfrow=c(4,1)) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=nrow(mCRPC_nmCRPC_df)) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=nrow(mCRPC_nmCRPC_df)-1) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=nrow(mCRPC_nmCRPC_df)-2) boxplot_func(ref_df=mCRPC_nmCRPC_df,grp1="mCRPC",grp2="nmCRPC",draw=nrow(mCRPC_nmCRPC_df)-3) dev.off() ####################################################################################### # Write to Excel and Save Results # ####################################################################################### anova_df <- data.frame( PROBE_ID = raw_data_median$PROBE_ID[all_kw$anova_BH <= BH_FDR_cutoff], SEQ_ID = raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff], KW_BH_FDR = all_kw$anova_BH[all_kw$anova_BH <= BH_FDR_cutoff] ) anova_df <- anova_df %>% remove_rownames() %>% mutate( KW_BH_FDR = round(KW_BH_FDR, 4) ) contrast_df.func <- function(contrast_BH, contrast_diff){ df <- data.frame( PROBE_ID = raw_data_median$PROBE_ID[all_kw$anova_BH <= BH_FDR_cutoff][contrast_BH <= BH_FDR_cutoff], SEQ_ID = raw_data_median$SEQ_ID[all_kw$anova_BH <= BH_FDR_cutoff][contrast_BH <= BH_FDR_cutoff], Effect_size = contrast_diff[contrast_BH <= BH_FDR_cutoff], KW_BH_FDR = all_kw$anova_BH[all_kw$anova_BH <= BH_FDR_cutoff][contrast_BH <= BH_FDR_cutoff], contrast_BH_FDR = contrast_BH[contrast_BH <= BH_FDR_cutoff] ) df <- df %>% filter(abs(Effect_size)>1) %>% arrange(desc(Effect_size)) %>% remove_rownames() %>% mutate(Effect_size = round(Effect_size, 4), KW_BH_FDR = round(KW_BH_FDR, 4), contrast_BH_FDR = round(contrast_BH_FDR, 4) ) return(df) } # based on wilcox test cancer_normal_df <- contrast_df.func(cancer_normal_wilcox_BH, cancer_median - normal_median) mCRPC_others_df <- contrast_df.func(mCRPC_others_wilcox_BH, mCRPC_median - NOT_mCRPC_median) mCRPC_nmCRPC_df <- contrast_df.func(mCRPC_nmCRPC_wilcox_BH, mCRPC_median - nmCRPC_median) nmCRPC_nmCSPC_df <- contrast_df.func(nmCRPC_nmCSPC_wilcox_BH, nmCRPC_median - nmCSPC_median) nmCSPC_newdx_df <- contrast_df.func(nmCSPC_newdx_wilcox_BH, nmCSPC_median - newdx_median) newdx_normal_df <- contrast_df.func(newdx_normal_wilcox_BH, newdx_median - normal_median) summary_page_df <- data.frame( contrasts = c("cancer vs normal", "mCRPC vs others", "mCRPC vs nmCRPC", "nmCRPC vs nmCSPC", "nmCSPC vs new_dx", "new_dx vs normal"), total_peptide_counts = c( nrow(cancer_normal_df), nrow(mCRPC_others_df), nrow(mCRPC_nmCRPC_df), nrow(nmCRPC_nmCSPC_df), nrow(nmCSPC_newdx_df), nrow(newdx_normal_df) ), peptides_with_positive_effect_size = c(cancer_normal_df %>% filter(Effect_size > 0) %>% nrow(), mCRPC_others_df %>% filter(Effect_size > 0) %>% nrow(), mCRPC_nmCRPC_df %>% filter(Effect_size > 0) %>% nrow(), nmCRPC_nmCSPC_df %>% filter(Effect_size > 0) %>% nrow(), nmCSPC_newdx_df %>% filter(Effect_size > 0) %>% nrow(), newdx_normal_df %>% filter(Effect_size > 0) %>% nrow()) ) summary_page_df <- summary_page_df %>% mutate(peptides_with_negative_effect_size = total_peptide_counts - peptides_with_positive_effect_size) # longitudinal pap_df <- data.frame( PROBE_ID = raw_data_median_proj2$PROBE_ID[signif_crit_proj2], SEQ_ID = raw_data_median_proj2$SEQ_ID[signif_crit_proj2], Time_Effect = PAP_result[,"PAP_time_effect"][signif_crit_proj2], KR_BH = PAP_Ftest_KR_BH[signif_crit_proj2], Satterth_BH = PAP_Ftest_Satterthwaite_BH[signif_crit_proj2] ) %>% mutate(BH_FDR = pmin(KR_BH, Satterth_BH), BH_FDR = round(BH_FDR, 8), Time_Effect = round(Time_Effect, 4)) %>% select(PROBE_ID, SEQ_ID, BH_FDR, Time_Effect) %>% arrange(desc(Time_Effect)) wb = createWorkbook() sheet = createSheet(wb, "Contrast Summaries") addDataFrame(summary_page_df, sheet=sheet, row.names=FALSE, startRow = 2, startColumn = 2) sheet = createSheet(wb, "Kruskal-Wallis") addDataFrame(anova_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "cancer vs normal") addDataFrame(cancer_normal_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "mCRPC vs others") addDataFrame(mCRPC_others_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "mCRPC vs nmCRPC") addDataFrame(mCRPC_nmCRPC_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "nmCRPC vs nmCSPC") addDataFrame(nmCRPC_nmCSPC_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "nmCSPC vs newdx") addDataFrame(nmCSPC_newdx_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "newdx vs normal") addDataFrame(newdx_normal_df, sheet=sheet, row.names=FALSE) sheet = createSheet(wb, "PAP_Longitudinal") addDataFrame(pap_df, sheet=sheet, row.names=FALSE) saveWorkbook(wb, "09_Significant_Peptides.xlsx") #---------------------------------------------------------------------------------------------- # save results # save(logreg_pval, # lmer_result, # all_anova_pval, # all_kw_pval, # all_anova_mse, # file = "09_Cancer_Stage_Effects.RData") # save(cancer_normal_allez.go, # mCRPC_others_allez.go, # mCRPC_nmCRPC_allez.go, # nmCRPC_nmCSPC_allez.go, # nmCSPC_newdx_allez.go, # newdx_normal_allez.go, # PAP_allez.go, # file = "09_allez_results.RData" # )
36e48b8850de472cfcb95ae115eda07edc4d7607
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/palettesForR/examples/showPalette.Rd.R
c2b0c688d170c5cd30c383e1b69c2c7471bf6fb4
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
170
r
showPalette.Rd.R
library(palettesForR) ### Name: showPalette ### Title: Show a palette. ### Aliases: showPalette ### ** Examples data(Caramel_gpl) showPalette(myPal = Caramel_gpl)
97eb5d96ae287c300c6690b02226653452d85783
b821cea9ea90e31bfe72c8ed718a68a5e4e2dd6d
/Random Forest.R
39002562729503a6db575260ca454edad3d96b5a
[]
no_license
christyChenYa/GoogleSearchQueries
942db1d5ad47c377e33dd8456172f81db2f0c682
c29ce211b0c2a51fdc2e5ad3536c9003947d7c2b
refs/heads/master
2020-04-12T05:49:16.738076
2019-01-11T00:32:31
2019-01-11T00:32:31
162,332,809
0
0
null
null
null
null
UTF-8
R
false
false
3,541
r
Random Forest.R
library(randomForest) getwd() setwd("/Users/Christy/Desktop/Data Mining ") training<-read.csv("training.csv") test=read.csv("test.csv") training<-data.table(training) test<-data.table(test) ######################### check data ################################################ head(training,n = 20) str(training) ######################### Generate new features ###################################### training<-training[,url_per_query:= .N,by='query_id'] training<-training[,url_median:=as.integer(median(url_id)),by='query_id'] training<-training[,url_distance:=log(1+abs(url_id-url_median))] training<-training[,url_appearance:= .N,by='url_id'] training[,c('sig1_rk','sig2_rk','sig3_rk','sig4_rk','sig5_rk','sig6_rk','sig7_rk','sig8_rk'):= list(rank(sig1),rank(sig2),rank(sig3),rank(sig4),rank(sig5),rank(sig6),rank(sig7),rank(sig8)),by='query_id'] training[,c('sig1_mean','sig2_mean','sig3_mean','sig4_mean','sig5_mean','sig6_mean','sig7_mean','sig8_mean'):= list(mean(sig1),mean(sig2),mean(sig3),mean(sig4),mean(sig5),mean(sig6),mean(sig7),mean(sig8)),by='query_id'] training[,c('sig1_max','sig2_max','sig3_max','sig4_max','sig5_max','sig6_max','sig7_max','sig8_max'):= list(max(sig1),max(sig2),max(sig3),max(sig4),max(sig5),max(sig6),max(sig7),max(sig8)),by='query_id'] ######################### prepare for learning ###################################### train_feature<-training[,c(3:12,14:41)] train_target<-training[,13] ############################# test #################################################### head(test,n = 20) str(test) #relevance = c(1:dim(test)[1]) #test$relevance = relevance test<-test[,url_per_query:= .N,by='query_id'] test<-test[,url_median:=as.integer(median(url_id)),by='query_id'] test<-test[,url_distance:=log(1+abs(url_id-url_median))] test<-test[,url_appearance:= .N,by='url_id'] test[,c('sig1_rk','sig2_rk','sig3_rk','sig4_rk','sig5_rk','sig6_rk','sig7_rk','sig8_rk'):= list(rank(sig1),rank(sig2),rank(sig3),rank(sig4),rank(sig5),rank(sig6),rank(sig7),rank(sig8)),by='query_id'] test[,c('sig1_mean','sig2_mean','sig3_mean','sig4_mean','sig5_mean','sig6_mean','sig7_mean','sig8_mean'):= list(mean(sig1),mean(sig2),mean(sig3),mean(sig4),mean(sig5),mean(sig6),mean(sig7),mean(sig8)),by='query_id'] test[,c('sig1_max','sig2_max','sig3_max','sig4_max','sig5_max','sig6_max','sig7_max','sig8_max'):= list(max(sig1),max(sig2),max(sig3),max(sig4),max(sig5),max(sig6),max(sig7),max(sig8)),by='query_id'] ######################### prepare for learning ###################################### #test_target=test[,13] test_feature<-test[,c(3:40)] ############################# RF ####################################################### library(randomForest) training$relevance<-factor(training$relevance) set.seed(1) rf.train1 = randomForest(relevance~., data=training, mtry=6,ntree=1000, importance=TRUE) rf.pred = predict(rf.train1,newdata = test, type = "class") summary(rf.pred) rf.predf=ifelse(rf.pred==1,1,0) write.table(rf.pred,"output1000.txt",sep="\n", row.names = FALSE, quote = FALSE, col.names = FALSE) ############################### Analysis ################################################## training.size <- dim(training)[1] test = sample(1:training.size,training.size/10) train=-test training.test = training[test,] training.train = training[-test,] importance(rf.train1) print(rf.train1) varImpPlot (rf.train1) x=table(rf.predf,training.test$relevance) x error_rate = (x[1,2]+x[2,1])/dim(training.test)[1] error_rate
6f4e0bd4bf23de439e025c3b540d9985349df16b
549ed4f668cb5dd1d9bc8aa40ff4c128fc5158f9
/run_analysis.R
842797a0ec3193385816568d9fb153d69d65f5c5
[]
no_license
michaelgiessing/GetNClean
08984e9235b188c0390f1967065dbb3850d9895b
aca5e6b0ba0b4e72174d9cf8f760fac83d1cc686
refs/heads/master
2021-01-20T09:36:52.900357
2017-03-04T14:44:47
2017-03-04T14:44:47
83,924,321
0
0
null
null
null
null
UTF-8
R
false
false
3,801
r
run_analysis.R
## Create one R script called run_analysis.R that does the following: ## 1. Merges the training and the test sets to create one data set. ## 2. Extracts only the measurements on the mean and standard deviation for each measurement. ## 3. Uses descriptive activity names to name the activities in the data set ## 4. Appropriately labels the data set with descriptive activity names. ## 5. Creates a second, independent tidy data set with the average of each variable for each activity and each subject. library(dplyr) library(magrittr) #setwd('C:/Users/michael.giessing/Box Sync/Michael Giessing/Courses/Coursera/GetNCleanData/Project') #Download and unzip #download.file('https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip','FUCI_HAR_Dataset.zip') unzip('FUCI_HAR_Dataset.zip') #Load activity labels activity_labels <- read.table('./UCI HAR Dataset/activity_labels.txt') names(activity_labels) = c("ActivityID", "ActivityDSC") # Load: data column names and make filtered list with mean or std in the name features <- read.table("./UCI HAR Dataset/features.txt")[,2] goodfeatures <- grepl("mean|std",features) ##Loading Test Data #Read in test data subject_test <- read.table('./UCI HAR Dataset/test/subject_test.txt') X_test <- read.table('./UCI HAR Dataset/test/X_test.txt') Y_test <- read.table('./UCI HAR Dataset/test/Y_test.txt') #Name the variables in X_test and subject_test names(X_test) <- features names(subject_test) <- "SubjectID" #Get the features that have mean or std in the name X_test <- X_test[,goodfeatures] #Join activity labels on to y_test names(Y_test) = "ActivityID" Y_test <- inner_join(Y_test,activity_labels) #Bind it all together test_data <- cbind(subject_test,Y_test,X_test) ##Loading Train Data #Read in Train data subject_train <- read.table('./UCI HAR Dataset/train/subject_train.txt') X_train <- read.table('./UCI HAR Dataset/train/X_train.txt') Y_train <- read.table('./UCI HAR Dataset/train/Y_train.txt') #Name the variables in X_train and subject_train names(X_train) <- features names(subject_train) <- "SubjectID" #Get the features that have mean or std in the name X_train <- X_train[,goodfeatures] #Join activity labels on to y_train names(Y_train) = "ActivityID" Y_train <- inner_join(Y_train,activity_labels) #Bind it all together train_data <- cbind(subject_train,Y_train,X_train) # Merge test and train data data = rbind(test_data, train_data) #Create functions for name substitution timefort <- function (x){ timefort <- sub("^t","Time",x) } frequencyforf <- function (x){ frequencyforf <- sub("^f","Freqency",x) } AccelerationforAcc <- function (x){ AccelerationforAcc <- gsub("Acc","Acceleration",x) } GyroscopeforGyro <- function (x){ AccelerationforAcc <- gsub("Gyro","Gyroscop",x) } MagnitudeforMag <- function (x){ AccelerationforAcc <- gsub("Mag","Magnitude",x) } StandardDeviationforstd <- function (x){ standardDeviationforstd <- gsub("std","StandardDeviation",x) } FrequencyforFreq <- function (x){ FrequencyforFreq <- gsub("Freq","Frequency",x) } Meanformean <- function (x){ Meanformean <- gsub("mean()","Mean",x) } RemoveChar <- function (x){ y<- gsub("\\(\\)","",x) RemoveChar <- gsub("-","",y) } #Fix variable names x<- names(data) x<-sapply(x,timefort) x<-sapply(x,FrequencyforFreq) x<-sapply(x,frequencyforf) x<-sapply(x,AccelerationforAcc) x<-sapply(x,GyroscopeforGyro) x<-sapply(x,MagnitudeforMag) x<-sapply(x,StandardDeviationforstd) x<-sapply(x,Meanformean) x<-sapply(x,RemoveChar) names(data)<-x #Get mean for each variable for each group #Result Stared in SummaryTBL SummaryTBL <- data %>% select(-ActivityID) %>% group_by(ActivityDSC, SubjectID) %>% summarize_all(mean) write.table(SummaryTBL, file = "./independent_tidy_data.txt", row.name = FALSE)
a858a76c172db06978a87c49cbfdbf76b50288d3
9c1772919e81b898b2476e1cd7a998089d8aa103
/myfunc/omega.coef.R
b103536a3dc8494d5d167b14e76a71d1cff2921a
[]
no_license
KeitaSugiyama/menhera
6ec2eb0ae7593fe4327475159e3fde9350efae81
51dba45f78b29eaa447e9002aecaf6806d5e8908
refs/heads/master
2020-04-05T06:29:41.554699
2018-11-08T02:49:07
2018-11-08T02:49:07
156,640,232
0
0
null
null
null
null
UTF-8
R
false
false
442
r
omega.coef.R
#Ω係数を計算する(1因子でも多因子でも計算可能) #引数 # x: 生データ行列(受検者×項目) # nfactors: 因子数 #戻り値 # Ω係数 #(独自性に観測変数の分散をかけて、誤差分散を求める) # 関数faを使用 # omega.coef<-function(x,nfactors=1,fm="ml",...){ 1 - ( sum(fa(x,nfactors=nfactors,fm=fm,...)$uniquenesses*diag(var(x))) / sum(var(x)) ) }
0b83829a6a9d30fe960e9e263f363505859e296b
2aeb930b3ff3079be7694c77f5926838a874370b
/FWI_extract_mod_samples.R
54dc6b0fc91c7285c3af2f7e83ffc82bd48bcc1c
[]
no_license
sm-potter/AK_CA_Combustion
ea5363689c5d37dee90e6c7f5fb58830a8730872
f265b8110d8ae4ead8e80aadcd1e57d468b21d9c
refs/heads/master
2021-02-09T04:31:09.134580
2020-03-23T19:21:33
2020-03-23T19:21:33
244,239,547
0
0
null
null
null
null
UTF-8
R
false
false
5,007
r
FWI_extract_mod_samples.R
# rm(list=ls()) library(tidyverse) library(rgdal) library(raster) library(sf) library(lubridate) # rm(list=ls()) #---------------------------------extract fwi information for the modis samples pts <- read_sf("/mnt/data1/boreal/spotter/combustion/burned_area/scaling/modis_pixels/predictors/DOB.shp") # pts <- pts %>% mutate(Date = as.character(lubridate::as_date(Date))) extract_fwi <- function(pts, raster_path, variables, t1, t2){ #a final dataframe to return the results final_df <- list() #get the unique burn_dates all_dates <- unique(pts$Date) #loop through the unique dates for (bd in all_dates){ print (as.character(lubridate::as_date(bd))) for (var in variables){ #an if else statement for the variable prefix prefix <- ifelse(var %in% c( 'MERRA2_t', 'MERRA2_rh', 'MERRA2_wdSpd', 'MERRA2_snowDepth', 'VPD'), "Wx.MERRA2.Daily.Default.", "FWI.MERRA2.Daily.Default.") #an empty raster stack to get the means of the time steps for_mean <- stack() for (date in (seq(bd - t1, bd+t2, 1))){ date <- as.character(lubridate::as_date(date)) year <- substr(date, 1, 4) month <- substr(date, 6, 7) day <- substr(date, 9, 10) # #the first time step raster in_raster <- raster(file.path(raster_path,var, year, paste0(prefix, year, month, sprintf("%02d", as.numeric(day)), '.tif'))) #append each to "for_mean" for_mean <- stack(for_mean, in_raster) } #get the mean mean_ras <- stackApply(for_mean, indices = rep(1, nlayers(for_mean)), fun = "mean", na.rm = T) sub_frame <- st_as_sf(pts) %>% dplyr::filter(Date == bd) #extract the pts extract <- as_tibble(raster::extract(mean_ras, sub_frame, df = T, method = 'simple')) names(extract) <- c('ID', 'value') extract <- extract %>% distinct(id, .keep_all = TRUE) extract$Variable <- var extract$ID2 <- sub_frame$ID2 extract$Burn_Date <- as.character(lubridate::as_date(bd)) extract <- extract %>% dplyr::select(ID2, Variable, Burn_Date, value) #append the file to "final_df" final_df[[length(final_df) + 1]] <- extract } } return (spread(bind_rows(final_df), key = Variable, value = value)) } variables <- c('MERRA2_DC','MERRA2_DMC','MERRA2_FFMC','MERRA2_ISI','MERRA2_BUI','MERRA2_FWI','MERRA2_DSR', 'MERRA2_t', 'MERRA2_rh', 'MERRA2_wdSpd', 'MERRA2_snowDepth', 'VPD') all_extracted <- extract_fwi(as(pts, 'Spatial'), "/mnt/data1/boreal/raw/GFWED/v2.5", variables, 0, 0) # df <- bind_rows(final_df) # df <- df %>% group_by(ID2, Burn_Date) %>% mutate(idn = row_number()) %>% spread(Variable, value) %>% summarize_all(mean, na.rm = T) %>% drop_na() %>% ungroup() # df <- df %>% dplyr::select(-idn) out <- "/mnt/data1/boreal/spotter/combustion/burned_area/scaling/modis_pixels/predictors" dir.create(out, recursive = T) write_csv(all_extracted, file.path(out, 'FWI.csv')) # write_csv(df, file.path(out, 'FWI.csv')) #------------------------------------get landsat FWI by merging into modis # out <- "/mnt/data1/boreal/spotter/combustion/burned_area/scaling/landsat_pixels/predictors" # dir.create(out, recursive = T) # # mod_fwi <- read_csv("/mnt/data1/boreal/spotter/combustion/burned_area/scaling/modis_pixels/predictors/FWI.csv") # # #read in the landsat pixels - ID2 here is from MODIS pixels burn year and running row id # shape <- read_sf("/mnt/data1/boreal/spotter/combustion/burned_area/scaling/landsat_pixels/all_years.shp") # # shape <- as_tibble(data.frame(shape)) %>% dplyr::select(-geometry) # # #attach the DOB from MODIS to all landsat which overlay - join on ID2 # land_fwi <- left_join(as_tibble(shape), as_tibble(mod_fwi), by = 'ID2') # # write_csv(land_fwi, file.path(out, 'FWI.csv')) # df2 <- read_csv('/Users/spotter/Documents/combustion/intro_files/text_files/Combustion_SynthesisData_05042018_XJW.csv') # df2 <- df2 %>% dplyr::select(-DMC.y, -BUI.y, -Relative.humidity, -Wind.speed, -FFMC.y, -FWI.y, -DC.y, -ISI.y, -DSR, -Temperature) # names(df) <- c("id", "Burn_Date", 'BUI.y', 'DC.y', 'DMC.y', 'DSR', 'FFMC.y', 'FWI.y', 'ISI.y', 'Relative.humidity', 'snowDepth', 'Temperature', 'Wind.speed', 'VPD') # # df <- df %>% dplyr::select(-snowDepth, -Burn_Date) # # df <- left_join(df, df2, on = id) # # df2 <- read_csv('/Users/spotter/Documents/combustion/intro_files/text_files/Combustion_SynthesisData_05042018_XJW.csv') # # df2 <- df2 %>% filter(!id %in% unique(df$id)) # df2 <- df2 %>% mutate(VPD = -999) %>% na_if(-999) # df <- df[names(df2)] # # df <- bind_rows(df, df2) # # df2 <- read_csv('/Users/spotter/Documents/combustion/intro_files/text_files/Combustion_SynthesisData_05042018_XJW.csv') # # # df <- df %>% ungroup() %>% mutate(id = as.factor(id, levels = list(unique(df2$id)))) # write_csv(df, '/Users/spotter/Documents/combustion/intro_files/text_files/Combustion_Data_051019_DOB_SMP.csv')
72cacb8de55e29ec8604fd9dbc310cd851761198
ef52ade6d4a97cd15416c40869583f05cdef8350
/R/ggdotchart.R
78a92314edcf7771d01ab735b6e8a2aa56bed317
[]
no_license
inventionate/ggpubr
9f9c6d55614cd662104e6a4377703f111c758559
b03d7d219342748b388503f87e6aaa8557f3718b
refs/heads/master
2020-05-24T05:56:01.594632
2017-03-13T07:26:54
2017-03-13T07:26:54
null
0
0
null
null
null
null
UTF-8
R
false
false
4,964
r
ggdotchart.R
#' @include utilities.R ggpar.R stat_chull.R stat_conf_ellipse.R NULL #' Cleveland's Dot Plots #' @description Draw a Cleveland dot plot. #' @inheritParams ggpar #' @param data a data frame #' @param x x variable for drawing. #' @param color,size points color and size. #' @param shape point shape. See \code{\link{show_point_shapes}}. #' @param label the name of the column containing point labels. #' @param group an optional column name indicating how the elements of x are #' grouped. #' @param sorting a character vector for sorting into ascending or descending #' order. Allowed values are one of "descending" and "ascending". Partial #' match are allowed (e.g. sorting = "desc" or "asc"). Default is #' "descending". #' @param ... other arguments to be passed to \code{\link[ggplot2]{geom_point}} #' and \code{\link{ggpar}}. #' @details The plot can be easily customized using the function ggpar(). Read #' ?ggpar for changing: \itemize{ \item main title and axis labels: main, #' xlab, ylab \item axis limits: xlim, ylim (e.g.: ylim = c(0, 30)) \item axis #' scales: xscale, yscale (e.g.: yscale = "log2") \item color palettes: #' palette = "Dark2" or palette = c("gray", "blue", "red") \item legend title, #' labels and position: legend = "right" \item plot orientation : orientation #' = c("vertical", "horizontal", "reverse") } #' @seealso \code{\link{ggpar}} #' @examples #' # Load data #' data("mtcars") #' df <- mtcars #' df$cyl <- as.factor(df$cyl) #' df$name <- rownames(df) #' head(df[, c("wt", "mpg", "cyl")], 3) #' #' # Basic plot #' ggdotchart(df, x = "mpg", label = "name" ) #' #' # Change colors by group cyl #' ggdotchart(df, x = "mpg", label = "name", #' group = "cyl", color = "cyl", #' palette = c('#999999','#E69F00','#56B4E9') ) #' #' # Use brewer palette #' ggdotchart(df, x = "mpg", label = "name", #' group = "cyl", color = "cyl", palette = "Dark2" ) #' #' # Change the orientation #' # Sort in ascending order #' ggdotchart(df, x = "mpg", label = "name", #' group = "cyl", color = "cyl", #' palette = c("#00AFBB", "#E7B800", "#FC4E07"), #' orientation = "horizontal", sorting = "ascending" ) #' #' #' @export ggdotchart <- function(data, x, label, group = NULL, color = "black", palette = NULL, shape = 19, size = NULL, sorting = c("descending", "ascending"), orientation = c("vertical", "horizontal"), ggtheme = theme_bw(), ...) { sorting <- match.arg(sorting) orientation <- match.arg(orientation) decreasing <- ifelse(sorting == "descending", FALSE, TRUE) if(is.null(group)){ if (sorting == "descending") data <- data[order(data[, x]), , drop = FALSE] else data <- data[order(-data[, x]), , drop = FALSE] data[, label] <- factor(data[, label], levels = as.vector(data[, label])) } else{ decreasing <- ifelse(orientation == "vertical", TRUE, FALSE) if (sorting == "descending") data <- data[order(data[, group], -data[, x], decreasing = decreasing), , drop = FALSE] else data <- data[order(data[, group], data[, x], decreasing = decreasing), , drop = FALSE] data[, label] <- factor(data[, label], levels = as.vector(data[, label])) } if(orientation == "vertical") p <- ggplot(data, aes_string(x = x, y =label)) else p <- ggplot(data, aes_string(x = label, y =x)) p <- p + .geom_exec(geom_point, data = data, shape = shape, color = color, size = size) p <- ggpar(p, palette = palette, ggtheme = ggtheme, ...) # theme if(orientation == "vertical") p <- .theme_vertical(p, data[, label]) else p <- .theme_horizontal(p, data[, label]) p } # Helper functions # +++++++++++++++++++++++++ .theme_vertical <- function(p, label){ p <- p + theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(colour = "grey70", linetype = "dashed"), axis.title.y = element_blank(), axis.ticks.y = element_blank())+labs_pubr() # y axis text colors # +++++++++++++++++++++++++++ g <- ggplot2::ggplot_build(p) cols <- unlist(g$data[[1]]["colour"]) names(cols) <- as.vector(label) # Give every color an appropriate name p <- p + theme(axis.text.y = ggplot2::element_text(colour = cols)) p } .theme_horizontal <- function(p, label){ p <- p + theme(panel.grid.major.x = element_line(colour = "grey70", linetype = "dashed"), panel.grid.major.y = element_blank(), axis.title.x = element_blank(), axis.ticks.x = element_blank())+ labs_pubr() # x axis text colors # +++++++++++++++++++++++++++ g <- ggplot2::ggplot_build(p) cols <- unlist(g$data[[1]]["colour"]) names(cols) <- as.vector(label) # Give every color an appropriate name p <- p + theme(axis.text.x = ggplot2::element_text(colour = cols, angle = 90, hjust = 1)) p }
b0d320b0926089241e69cd6a34bd3786d5016e23
f45a2fb54815b95f44e414cd9b99980e44a9770a
/Normal GLM Assignment.R
27c62598e713e4c94744d9aa1aefa846f96b1079
[]
no_license
kali237/assignments
e3d797f824db3624cef38824a0cf1c95e18ea15c
de898cfed9b1b3053e04d8f83a8fe12eb7160388
refs/heads/master
2020-04-05T19:52:58.603439
2018-11-12T05:47:01
2018-11-12T05:47:01
157,154,872
0
0
null
null
null
null
UTF-8
R
false
false
7,156
r
Normal GLM Assignment.R
#Normal GLM assignment library(carData) library(car) #setwd(dir="C:\\Users\\kwickens\\Documents\\Regression and Non Parametric\\Normal GLM") setwd(dir = "C:\\Users\\Kali\\Documents\\7880 Assingments\\Assignment 2 - Normal GLM") load("Normal_GLM.Rdata") ############### functions ############### lik=function(beta1,beta2,y,X1,X2){ #y consists of n observations #X1 is an n-by-p1 matrix, with p1 covariates for each subject #X2 is an n-by-p2 matrix, with p2 covariates for each subject #beta1 is a vector of length p1 OR a m-by-p1 matrix #beta2 is a vector of length p2 OR a m-by-p2 matrix if (is.matrix(beta1)){ beta1=t(beta1) beta2=t(beta2) } L=t(y)%*%X1%*%beta1 - t(y^2)%*%X2%*%beta2/2 if (is.matrix(beta1)){ L=L - 0.5*colSums((X1%*%beta1)^2/(X2%*%beta2))+0.5*colSums(log(X2%*%beta2)) L=t(L) colnames(L)="Log-likelihood" } else { L=L - 0.5*sum((X1%*%beta1)^2/(X2%*%beta2))+0.5*sum(log(X2%*%beta2)) L=L[1,1] } return(L-0.5*log(2*pi)*dim(X1)[1]) #returns a vector with m values of the likelihood } Dlik=function(beta1,beta2,y,X1,X2){ #y consists of n observations #X1 is an n-by-p1 matrix, with p1 covariates for each subject #X2 is an n-by-p2 matrix, with p2 covariates for each subject #beta1 is a vector of length p1 OR a m-by-p1 matrix #beta2 is a vector of length p2 OR a m-by-p2 matrix if (is.matrix(beta1)){ m=dim(beta1)[1] L=t(t(rep(1,m)))%*%c(t(y)%*%X1, - t(y^2)%*%X2/2) L=L - cbind(t((X1%*%t(beta1))/(X2%*%t(beta2)))%*%X1, -0.5*t((X1%*%t(beta1))^2/(X2%*%t(beta2))^2)%*%X2 -0.5*t(1/(X2%*%t(beta2)))%*%X2) } else { L=c(t(y)%*%X1, - t(y^2)%*%X2/2) L=L - c(t((X1%*%beta1)/(X2%*%beta2))%*%X1, -0.5*t((X1%*%beta1)^2/(X2%*%beta2)^2)%*%X2 -0.5*t(1/(X2%*%beta2))%*%X2) } if (is.matrix(beta1)) { colnames(L)=c(colnames(beta1),colnames(beta2)) rownames(L)=rownames(beta1)} else { names(L)=c(names(beta1),names(beta2)) } return(L) #returns m-by-(p1+p2) matrix with the m gradient vectors } D2lik=function(beta1,beta2,y,X1,X2){ #y consists of n observations #X1 is an n-by-p1 matrix, with p1 covariates for each subject #X2 is an n-by-p2 matrix, with p2 covariates for each subject #beta1 is a vector of length p1 (only one parameter!) #beta2 is a vector of length p2 (only one parameter!) p1=length(beta1) p2=length(beta2) eta1=X1%*%beta1 eta2=X2%*%beta2 L=matrix(0,p1+p2,p1+p2) for (m in 1:(p1+p2)){ for(n in 1:(p1+p2)){ if (m<=p1 & n<=p1){ L[m,n]=-sum(X1[,m]*X1[,n]/eta2) } if (m<=p1 & n>p1){ L[m,n]=sum(eta1*X1[,m]*X2[,n-p1]/eta2^2) } if (m>p1 & n<=p1){ L[m,n]=sum(eta1*X2[,m-p1]*X1[,n]/eta2^2) } if (m>p1 & n>p1){ L[m,n]=-sum(X2[,m-p1]*X2[,n-p1]*(eta1^2/eta2^3 + 0.5/eta2^2)) } } } #colnames(L)=c(names(beta1),names(beta2)) #rownames(L)=c(names(beta1),names(beta2)) return(L) #returns (p1+p2)-by-(p1+p2) second derivative matrix } ######################################### #a) x_2 = x**2 fit = lm(y ~ x + x_2) #yes, very significant summary(fit) #just for fun fit0 = lm(y~x) summary(fit0) SSres = sum(fit$res^2) SSresH0 = sum(fit0$res^2) f = (SSresH0 - SSres)/SSres * (47/1) pvalue = 1-pf(f,1,47) #plot the residuals plot(fit) plot(x=x, y = fit$res, ylab = "residuals", xlab = NULL) plot(x=x_2, y = fit$res, ylab = "residuals", xlab = NULL) qqplot(fit$residuals) #b) fit model is a submodel assuming equivariance #for the \eta_{i1} this is basically scaling the fitted values from the first model and scaling by the variance. Because we are assuming equivariance, we just divide this all by the variance (or the standard error squared) #for \eta_{i2} we do not want the value of the variance to change based on the data, therefore we want \beta_{21} and \beta_{22} to be 0, and just scale the intercept by the variance sqrt(SSres/47) #residual standard error, \sigma^hat sig2_hat = SSres/47 #estimate for the variance beta1 = fit$coefficients/sig2_hat beta2 = c(1/sig2_hat,0,0) X_1 = model.matrix(fit) X_2 = model.matrix(fit) lik(beta1,beta2,y,X_1,X_2) Dlik(beta1,beta2,y,X_1,X_2) #the first three are 0 because we already found in model a. the last 3 are not, thus we are not at the minimum (MLE), and thus our assumption of equivariance is wrong #c) stupid optimization shit #use the beta1 and beta2 and the lik functions l = lik(beta1,beta2,y,X_1,X_2) Dl = Dlik(beta1,beta2,y,X_1,X_2) D2l = D2lik(beta1,beta2,y,X_1,X_2) D2l_inv = -solve(D2l) h = D2l_inv%*%Dl b = c(beta1,beta2) #stuff from Nick D2l=function(b) {D2lik(b[1:3],b[4:6],y,model.matrix(fit),model.matrix(fit))} Dl=function(b) {Dlik(b[1:3],b[4:6],y,model.matrix(fit),model.matrix(fit))} l=function(b) {lik(b[1:3],b[4:6],y,model.matrix(fit),model.matrix(fit))} h_m=function(b){-solve(D2l(b))%*%Dl(b)} opt = optim(b,l,Dl,control= list(fnscale = -1)) summary(opt) n_beta = opt$par n_beta1 = n_beta[1:3] n_beta2 = n_beta[4:6] lik(n_beta1,n_beta2,y,X_1,X_2) #cool, give -40.25 eta1_1 = X_1%*%n_beta1 eta2_1 = X_1%*%n_beta2 #Newton-Raphson! This now works. It produces a better minimum than 'optim' h=h_m(b) del=1 while(del>10^-35){ # 10^-35 is around 100 times the size of single-precision 'machine zero.' #In reality this will be satisfied when l(b) and l(b+h) agree to ~16 digits, #which will happen much much sooner. while(is.nan(l(b+h))||l(b+h)<l(b)){ h = h/2 } del = l(b+h)-l(b) b = b+h h = h_m(b) b } #Load 'b' with the \beta coefficients #simulate; y = N(\eta1/\eta2, 1/\eta2) lik(b[1:3],b[4:6],y,X_1,X_2) #gives -38.13 eta1 = model.matrix(fit)%*%b[1:3] #\eta_{1,i} = X_i*\beta_1 eta2 = model.matrix(fit)%*%b[4:6] #\eta_{2,i} = X_i*\beta_2 #plots plots plots!! #Plot of 'y' values, fitted values from the GLM, and fitted values from the linear model #Black is the 'y' values, red is the linear model and green is the GLM plot(y) points(fit$fitted.values,col="red") points(eta1/eta2, col="blue") #Residual plots #Residuals from the GLM plot(y - eta1/eta2) points(sqrt(1/eta2),pch="-", col = "red") points(-sqrt(1/eta2),pch="-", col = "red") #Residuals from the linear model plot(fit$residuals) points(sqrt(sig2_hat)*replicate(50,1),pch="-", col = "red") points(sqrt(sig2_hat)*replicate(50,-1),pch="-", col = "red") #It looks good, since there are lots of points within the +/- 1 stdev bars... #But actually there are TOO MANY points within the bars! We should only have ~70% between the bars! #~30% of the points SHOULD be outside the bars, but only 7 of 50 (14%) points are outside the bars. #d) test the quadratic terms for both \eta_1 and \eta_2. Then test which model is better GLM or standard linear model eta1_fit = lm(eta1 ~ x + x_2) summary(eta1_fit) b_h0 = c(b[1:2],0) eta1_fit0 = lm(eta1 ~ x) summary(eta1_fit0) eta2_fit = lm(eta2 ~ x + x_2) summary(eta2_fit) #N(m,s) = m + \sqrt(s)N(0,1) n = rnorm(50) sim = eta1/eta2 + sqrt(1/eta2)*n
70639e02a4ac143c7d820f237728230a7267b944
b7e09d76858c0e98aa32302fc70bb0eebf3ee24d
/R/fars_functions.R
73231b3b560c7f18ea80881cbabc3756af5c3863
[]
no_license
barnabe/building_an_r_package
df98f7015a4ee40ff7277a877e646b384c485d57
365afe3d3dbfa80bfd3387afcfd6b8c1648a9265
refs/heads/master
2021-01-11T15:04:18.341394
2017-01-31T14:14:00
2017-01-31T14:14:00
80,290,435
0
0
null
null
null
null
UTF-8
R
false
false
5,788
r
fars_functions.R
utils::globalVariables(c("STATE", "MONTH","year")) #' Read source data file #' #' @details This function looks for a CSV file called \code{filename} and checks whether it exists or not, #' if found it loads the data using \code{readr::read.csv} and converts it to a dyplr dataframe using \code{dyplr::tbl_df}. #' If no data file with that name exists, the funtion returns an error. #' #' @param filename a string and, optionally a path, representing a CSV file name #' #' @import dplyr #' #' @importFrom readr read_csv #' #' @return a dataframe #' #' @examples #' \dontrun{ #' fars_read("accident_2013.csv")} #' #' @export fars_read <- function(filename) { if(!file.exists(filename)) stop("file '", filename, "' does not exist") data <- suppressMessages({ readr::read_csv(filename, progress = FALSE) }) dplyr::tbl_df(data) } #' Standard data file name #' #' @details This function returns a standard name for a given year for the source zip files #' from the US National Highway Traffic Safety Administration's Fatality Analysis Reporting System #' #' @param year an integer year value (YYYY) #' #' @return a string representing a standard file name for a given year #' #' @examples #' \dontrun{ #' make_filename("accident_%d.csv.bz2", 2013) #' Creates a standard file name for the 2017 dataset #' } #' #' @export make_filename <- function(year) { year <- as.integer(year) sprintf("inst/ext_data/accident_%d.csv.bz2", year) } #' Data date range #' #' This function returns the month and year of the data in a range of annual data files #' #' @details This function iterates over a range of year values and uses the \code{\link{fars_read}} and \code{\link{make_filename}} #' to find and report the content of the MONTH and YEAR columns in each data file. The data files have to be in the same working directory. #' #' @param years a vector of integer year values (YYYY) #' #' @inheritParams fars_read #' #' @inheritParams make_filename #' #' @import dplyr #' #' @import magrittr #' #' @return A tipple of the MONTH and YEAR values for each data file in the \code{years} range #' #' @examples #' \dontrun{ #' fars_read_years(c(2013:2015)) #' } #' #' @export fars_read_years <- function(years) { lapply(years, function(year) { file <- make_filename(year) tryCatch({ dat <- fars_read(file) dplyr::mutate(dat, year = year) %>% dplyr::select(MONTH, year) }, error = function(e) { warning("invalid year: ", year) return(NULL) }) }) } #' Summary statistics #' #' This function provides summary monthly statistics for each year in a range #' #' @details This function uses the output from \code{\link{fars_read_years}} #' to generate summary accident statistics by \code{YEAR} and \code{MONTH}. #' #' @inheritParams fars_read_years #' #' @return table of summary statistics #' #' @import dplyr #' #' @importFrom tidyr spread #' #' @importFrom utils installed.packages #' #' @examples #' \dontrun{ #' fars_summarize_years(c(2013:2015)) #' } #' #' @export fars_summarize_years <- function(years) { dat_list <- fars_read_years(years) dplyr::bind_rows(dat_list) %>% dplyr::group_by(year, MONTH) %>% dplyr::summarize(n = n()) %>% tidyr::spread(year, n) } #' Map Accidents #' #' This function maps accidents in individual U.S. State in a given year #' #' @details For a given year value, this function read the relevant data file #' using the \code{\link{make_filename}} and \code{\link{fars_read}} functions. #' It checks that the stae exists and that any accidents were reported that year in that state. #' The function also removes erroneous longotude and lattitudes entries in the raw data #' (\code{longitude>900} and \code{lattitude>90}) and uses the \code{\link{map}} package to #' draw the relevant map and the \code{\link{graphics}} package to plot dots. #' #' @param state.num the unique identification of a U.S. state #' @param year relevant data year #' @inheritParams fars_read #' @inheritParams make_filname #' #' @import maps #' @import dplyr #' @importFrom graphics points #' #' @return a long/lat plot of reported accidents in the U.S. state and year of choice against a state boundary map #' #' @examples #' \dontrun{ #' fars_map_state("12","2013") #' } #' #' @export fars_map_state <- function(state.num, year) { filename <- make_filename(year) data <- fars_read(filename) state.num <- as.integer(state.num) if(!(state.num %in% unique(data$STATE))) stop("invalid STATE number: ", state.num) data.sub <- dplyr::filter(data, STATE == state.num) if(nrow(data.sub) == 0L) { message("no accidents to plot") return(invisible(NULL)) } is.na(data.sub$LONGITUD) <- data.sub$LONGITUD > 900 is.na(data.sub$LATITUDE) <- data.sub$LATITUDE > 90 with(data.sub, { maps::map("state", ylim = range(LATITUDE, na.rm = TRUE), xlim = range(LONGITUD, na.rm = TRUE)) graphics::points(LONGITUD, LATITUDE, pch = 46) }) } #' Testing #' #' This function runs the tests in the tests/ directory. it has not argument #' #' @importFrom testthat test_that test_dir expect_is #' #' @return test results from the testthat package #' #' @examples #' \dontrun{ #' testing() #' } #' #' @export testing<- function(){ #create test output test_output=fars_summarize_years(c(2013:2015)) #run test files in tests/ directory testthat::test_dir("tests/testthat") }
e7fd0f4e4f2607cd0cbd386d87f5cf4f1a0628a0
2cb2bc953975540de8dfe3aee256fb3daa852bfb
/00misc/tyama_codeiq119-codeiq167.R
33abe88d6859e7311f416b8b41735effe84a822f
[]
no_license
cielavenir/codeiq_solutions
db0c2001f9a837716aee1effbd92071e4033d7e0
750a22c937db0a5d94bfa5b6ee5ae7f1a2c06d57
refs/heads/master
2023-04-27T14:20:09.251817
2023-04-17T03:22:57
2023-04-17T03:22:57
19,687,315
2
4
null
null
null
null
UTF-8
R
false
false
441
r
tyama_codeiq119-codeiq167.R
#!/usr/bin/Rscript #cf: http://d.hatena.ne.jp/isseing333/20121224/1356279424 #問1 t=read.table('DataScience_ML1.csv',header=T,sep=',') l=lm(y~x1+x2,t) #問2 #(1) pdf("167_1.pdf") plot(t) dev.off() #(2) cat(summary(l)$adj.r.squared) cat("\n") #(3) pdf("167_2.pdf") plot(l$fitted,l$resid) dev.off() #(4) pdf("167_3.pdf") plot(l$fitted,l$y) dev.off() #pdftk 167_1.pdf 167_2.pdf 167_3.pdf cat output 167.pdf #rm -f 167_1.pdf 167_2.pdf 167_3.pdf
58a301e40bb514c2593028f253e63586ec0593cd
b8be9f57f05c5e279ff38ff1d0bb7efeb26b4308
/R/leak_detection_MEU.R
922e160640b22d30859749256036b25420cff15e
[]
no_license
Ozeidi/water
aa96f8e451b008f0224da000e8e389a6df492273
9aa62d17b217d00346fac920e2d02c66798c2786
refs/heads/master
2020-06-17T08:02:26.012796
2019-07-08T16:36:39
2019-07-08T16:36:39
195,854,634
0
0
null
null
null
null
UTF-8
R
false
false
6,293
r
leak_detection_MEU.R
library(xts) library(tidyverse) library(dplyr) leak_detection_MEU <- function(timeseries, model_params = NA, id = NA){ # if timseries sent is a single xts if (class(timeseries) %in% c("xts", "zoo")){ if(is.na(id))id <- gsub("-|:|\\s","",paste0(Sys.time())) # wrap the outcome in a list to avoid redundent checks going forward res <- list(id0 = leak_detection_MEU_single(timeseries, id, model_params)) return (res) } # if timeseries is a list of xts else if (class(timeseries) == 'list'){ res <- list() if(!is.na(model_params)){ if (length(timeseries) != length(model_params))stop("The model_params must be a list of the same length as timeseries list") id = names(timeseries) for (i in 1:length(timeseries)){ res[[i]] <- leak_detection_MEU_single(timeseries[[i]], id[i], model_params[[i]]) } } else{ id = names(timeseries) for (i in 1:length(timeseries)){ res[[i]] <- leak_detection_MEU_single(timeseries[[i]], id[i]) } } return(res) } } leak_detection_MEU_single <- function(xts_object, id = NA, model_params = NA){ # if model_params are sent, use it to detect the leak flags directly if(!is.na(model_params))return(learn_and_predict(contract_ts = xts_object, model_params = model_params)) # otherwise, look on disk for previously saved models for this id else if (!is.na(id)){ model_params = tryCatch({ readRDS(paste0("MEU_models/",id,".rds")) }, error = function(e) { print("No saved Model Params") return (NA) }) } if(!is.na(model_params))print("Model Params Loaded from Disk") # proceed with main function call return (learn_and_predict(contract_ts = xts_object, id = id, model_params = model_params)) } learn_and_predict <- function(contract_ts, id = NA, model_params = NA, leak_start = NA, leak_end = NA, z_crit = 1.95, leak_threshold = 0.8, daily_threshold = 0.5, skip_leak = TRUE){ # extract hourly markers and use them to calculate hourly usage ep <- endpoints(contract_ts, on = "hours") usagePerhour_all <- period.apply(contract_ts, INDEX = ep ,FUN = sum, na.rm = T) # if model_params are sent, use it and skip the training phase if(!is.na(model_params))model_params_df <- model_params # otherwise, proceed with training else { print("Training model") model_params_df <- data.frame(mean = numeric(0) , sd = numeric(0), n = numeric(0), meu = numeric(0)) mon_idx <- 0:11 # define months and hour notation (as per xts) hr_idx <- 0:23 # remove hourly usage data during the leak if(skip_leak)usagePerhour <- usagePerhour_all else{ leak_idx <- usagePerhour_all[paste0(leak_start,"/",leak_end), which.i = T] usagePerhour <- usagePerhour_all[-leak_idx] } # loop on each month and each hour to calculate the average hourly usage once for weekdays and another for weekends # the notation of the obtained dictionary is as follows: "Month.Wkday/Wkend.Hour" # f.ex "0.0.13" is the entry for month of Jan (0), Wkday (0), 1P.m. (13) # and "5.1.23" is the entry for month of "june (5), wkend (1), 11P.M. (23) for (mon in mon_idx){ for(hr in hr_idx){ # mark the weekday index for a specific hour and a specific month wkday_idx <- which(.indexhour(usagePerhour) == hr & .indexmon(usagePerhour) == mon & .indexwday(usagePerhour) !=0 & .indexwday(usagePerhour) !=6) # calculate mean, sd, number of observations and Maximum Expected Usage for a specific hour and a specific month MEAN <- mean(usagePerhour[wkday_idx], na.rm = T) SD <- sd(usagePerhour[wkday_idx], na.rm = T) n <- n <- sum(!is.na(usagePerhour[wkday_idx])) MEU <- MEAN + z_crit * SD / sqrt(n) model_params_df[paste0(mon,".",0,".",hr),] <- c(MEAN,SD,n,MEU) # do the same as above for weekend index wkend_idx <- which(.indexhour(usagePerhour) == hr & .indexmon(usagePerhour) == mon & (.indexwday(usagePerhour) ==0 | .indexwday(usagePerhour) ==6)) MEAN <- mean(usagePerhour[wkend_idx], na.rm = T) SD <- sd(usagePerhour[wkend_idx], na.rm = T) n <- sum(!is.na(usagePerhour[wkend_idx])) MEU <- MEAN + z_crit * SD / sqrt(n) model_params_df[paste0(mon,".",1,".",hr),] <- c(MEAN,SD,n,MEU) } } if(!is.na(id))tryCatch({dir.create("MEU_models", showWarnings = FALSE) saveRDS(model_params_df, paste0("MEU_models/",id,".rds")) }, error = function(e)print("Couldn't Write Model to Disk")) } # Using the learned dictionary to loop on all the contract and identify potential leak intervals m <- month(index(usagePerhour_all))-1 w <- ifelse(weekdays(index(usagePerhour_all)) %in% c("Saturday","Sunday"),1,0) h <- hour(index(usagePerhour_all)) # lookup the maximum estimated usage (MEU) corresponding to each hour in the original ts values <- as.vector(sapply(paste0(m,".",w,".",h), FUN = function(x)return(model_params_df[x,"meu"]))) meu_xts <- xts(values, order.by = index(usagePerhour_all)) # concatenate the actual usage to the MEU, convert to dataframe and create a flag column comp_xts <- data.frame(coredata(usagePerhour_all),coredata(meu_xts)) names(comp_xts) <- c("usage", "meu") df <- comp_xts %>% mutate(flag = ifelse(usage > meu, TRUE,FALSE)) flag_xts <- xts(df$flag, order.by = index(usagePerhour_all)) # define an aux function to check if a certain day should be marked as a leak (depending on leak_threshold and daily_threshold) isLeak <- function(x){ if(sum(is.na(coredata(x))) == length(coredata(x))) return (NaN) if(mean(x, na.rm = T) > leak_threshold & sum(is.na(coredata(x))) < 24*daily_threshold)return(TRUE) else return(FALSE) } # apply the aux function on our flag_xts to obtain the leak_xts leak_xts <- period.apply(flag_xts, endpoints(flag_xts, on = "days"), FUN = isLeak) leak_flag <- data.frame(Date = as.Date(index(leak_xts)), leak_flag = coredata(leak_xts)) %>% filter(leak_flag == TRUE) return (list(leak_xts = leak_xts, leak_flag = leak_flag, model_params = model_params_df)) }
99254bacb8f1134cfa0300916bae6d702e4bfaa0
a83d1e348011b202c22d411e861a7e400072131f
/man/SymKL.z.Rd
a7826a089b2c8a76d4cf291ce0157d57650e5eda
[]
no_license
cran/EntropyEstimation
b240598b4256edbeb4c03c19c852f231f264e309
de5307012cf0dbdbd63c2c08aab1748896fa46ac
refs/heads/master
2020-04-08T06:53:52.893493
2015-01-04T00:00:00
2015-01-04T00:00:00
18,805,115
0
1
null
null
null
null
UTF-8
R
false
false
809
rd
SymKL.z.Rd
\name{SymKL.z} \alias{SymKL.z} \title{SymKL.z} \description{ Returns the Z estimator of Symetrized Kullback-Leibler Divergence, which has exponentialy decaying bias. See Zhang and Grabchak (2014b) for details.} \usage{ SymKL.z(x, y) } \arguments{ \item{x}{ Vector of counts from first distribution. Must be integer valued. Each entry represents the number of observations of a distinct letter.} \item{y}{ Vector of counts from second distribution. Must be integer valued. Each entry represents the number of observations of a distinct letter.} } \references{ Z. Zhang and M. Grabchak (2014b). Nonparametric Estimation of Kullback-Leibler Divergence. Neural Computation, DOI 10.1162/NECO_a_00646. } \author{Lijuan Cao and Michael Grabchak} \examples{ x = c(1,3,7,4,8) y = c(2,5,1,3,6) SymKL.z(x,y) }
7b8476a1c34435e92b75229b92d6b88f33eb38bc
1e9a88114a1ec903a55f925f3344ae38065009a1
/03_Analysis/fesibility_analysis.R
4af68cd5575b6da8c5bb06c4750ac0cc20f59675
[]
no_license
GauravKBaruah/Individual_variation_and_tipping_points
f5bf9bb5d7a8a7febb595a92f88efc5615eb13af
3ac128e7316eeac8b8aa7d196c479ef3fd0b38ce
refs/heads/main
2023-07-29T05:04:19.024213
2021-09-09T03:40:06
2021-09-09T03:40:06
391,273,878
0
0
null
null
null
null
UTF-8
R
false
false
7,040
r
fesibility_analysis.R
#code for Ecology Letters paper: #" The impact of individual variation on abrupt collapses in mutualistic networks" 2021. Gaurav Baruah #email: gbaruahecoevo@gmail.com rm(list=ls()) source('~/02_functions_tipping_point.R', echo=F)#converting mutualism matrix to ones and zeros require(deSolve) ## for integrating ordinary differential equations require(tidyverse) ## for efficient data manipulation & plotting require(cowplot) ## for arranging plots in a grid library(dplyr) library(readr) library(beepr) require(ggplot2) require(reshape2) require(flux) require(akima) library(directlabels) library(gridExtra) library(grid) library(igraph) library(bipartite) #five mutualistic networks :60, 34, 8 #nestedness: 0.635, 0.246, 0 newfiles <-c("plant_pollinator/M_PL_046.csv", "plant_pollinator/M_PL_061_33.csv", "plant_pollinator/M_PL_061_18.csv") mydir = 'plant_pollinator' myfiles = list.files(path=mydir, pattern="*.csv", full.names=TRUE) #myfiles<-myfile #myfiles<-myfiles[1:101] fact<- expand.grid(`Strength_mutualism`=seq(0,7.5,0.4), `web` =newfiles, `interaction_type`= "trade_off", `noise`="none", `individual.variation` = c("high","low"), `range_competition` = c(50,70,100,200,500, 700,1000,2000,5000,7000,10000), `random_seed`=4327+(1:30)*100) %>% as_tibble %>% mutate(feasibility = 0, richness = 0) model.t<-list() for(r in 1:nrow(fact)){ #print(r) # extracting the interaction matrix g<-adj.mat(myfiles[which(myfiles == fact$web[r])]) #network web names # g<-g[-1,-1] Aspecies<- dim(g)[2] # no of animal species Plantspecies<- dim(g)[1] # no of plant species degree.animals<-degree.plants<-numeric() #degree of plants and anichmals for(i in 1:Plantspecies){ degree.plants[i]<-sum(g[i,])} # degree of plants for(j in 1:Aspecies){ degree.animals[j]<-sum(g[,j]) # degree of animals } ##control loop for selecting whether variation is high or low if(fact$individual.variation[r] == "low"){ sig <-runif((Aspecies+Plantspecies),0.0001,0.001)}else if(fact$individual.variation[r] == "high"){ sig <-runif((Aspecies+Plantspecies),0.05,0.5)} #heritability used in the model h2<-runif((Aspecies+Plantspecies),0.4,0.4) ## vector of species trait standard deviations N <- runif( (Aspecies+Plantspecies) , 1,1) ## initial species densities nainit<- N[1:Aspecies] npinit<-N[(Aspecies+1): (Aspecies+Plantspecies)] #vector of mean phenotypic values sampled from a uniform distribution muinit <-runif((Aspecies+Plantspecies), -1,1) mainit<-muinit[1:Aspecies] mpinit<-muinit[(Aspecies+1): (Aspecies+Plantspecies)] #matrix of coefficients for competition Amatrix<-mat.comp_feasibility(g,strength=fact$range_competition[r])$Amatrix Pmatrix<-mat.comp_feasibility(g,strength=fact$range_competition[r])$Pmatrix gamma=0.5 mut.strength<-fact$Strength_mutualism[r] nestedness<-nestedness_NODF(g) C<-Connectance(g) web.name<-myfiles[r] #growth rates of species ba<-runif(Aspecies, -0.05,-0.05) bp<-runif(Plantspecies,-0.05,-0.05) dganimals<-degree.animals dgplants<-degree.plants ic <-c(nainit, npinit, mainit,mpinit) params <- list(time=time,matrix=g,sig=sig,Amatrix=Amatrix, Pmatrix=Pmatrix,w=gamma, mut.strength=mut.strength,m=muinit,C=C,nestedness=nestedness, web.name=web.name,h2=h2, ba=ba,bp=bp,dganimals=dganimals, dgplants=dgplants,interaction_type=fact$interaction_type[r], noise=fact$noise[r]) start.time = 3000 model.t<-lapply(1, Mcommunity,time=start.time,state=ic, pars=params) abvector<-c(model.t[[1]]$Plants[3000,],model.t[[1]]$Animals[3000,]) percent_survived<-length(which(abvector > 0.001))/length(abvector) fact$feasibility[r] <- percent_survived fact$richness[r] <- length(which(abvector>1e-3)) print(r) } #save(fact, file="Feasibility_data.RData") # plot and aanalyis for the feasibility data #load("Feasibility_data.RData") for(i in 1:nrow(fact)){ g<-adj.mat(myfiles[which(myfiles == fact$web[i])]) #network web names #g<-g[-1,-1] fact$network.size[i]<- nrow(g)+ncol(g) fact$nesdtedness[i]<- nestedness_NODF(g) fact$connectance[i]<-Connectance(g) } #web1 a1<-fact %>% filter(individual.variation == "low", web == "plant_pollinator/M_PL_046.csv") %>% group_by(range_competition,Strength_mutualism,interaction_type) %>% summarise(mean_feasibility = mean(feasibility, na.rm = TRUE)) plot1<-feasibility_plot(a1) plot1 a2<-fact %>% filter(individual.variation == "high", web == "plant_pollinator/M_PL_046.csv") %>% group_by(range_competition,Strength_mutualism) %>% summarise(mean_feasibility = mean(feasibility, na.rm = TRUE)) plot2<-feasibility_plot(a2) plot2 # web2 a5<-fact %>% filter(individual.variation == "low") %>% group_by(range_competition,Strength_mutualism) %>% summarise(mean_feasibility = mean(feasibility, na.rm = TRUE)) plot5<-feasibility_plot(a5) plot5 a6<-fact %>% filter(individual.variation == "high") %>% group_by(range_competition,Strength_mutualism) %>% summarise(mean_feasibility = mean(feasibility, na.rm = TRUE)) plot6<-feasibility_plot(a6) plot6 #web3 a3<-fact %>% filter(individual.variation == "low", web == "plant_pollinator/M_PL_061_18.csv") %>% group_by(range_competition,Strength_mutualism) %>% summarise(mean_feasibility = mean(feasibility, na.rm = TRUE)) plot3<-feasibility_plot(a3) plot3 a4<-fact %>% filter(individual.variation == "high", web == "plant_pollinator/M_PL_061_18.csv") %>% group_by(range_competition,Strength_mutualism) %>% summarise(mean_feasibility = mean(feasibility, na.rm = TRUE)) plot4<-feasibility_plot(a4) plot4 net1<-adj.mat("plant_pollinator/M_PL_046.csv") net3<-adj.mat("plant_pollinator/M_PL_061_33.csv") net2<-adj.mat("plant_pollinator/M_PL_061_18.csv") par(mfrow=(c(3,1))) web1<-plotweb(net1, method="normal",ybig=0.1, y.width.low = 0.1, col.interaction="wheat4", bor.col.interaction="white", arrow="no", col.high="lightblue", col.low="tomato",labsize=0.1) web2<-plotweb(net2, method="normal",ybig=0.1, y.width.low = 0.1, col.interaction="wheat4", bor.col.interaction="white", arrow="no", col.high="lightblue", col.low="tomato",labsize=0.1) web3<-plotweb(net3, method="normal",ybig=0.1, y.width.low = 0.1, col.interaction="wheat4", bor.col.interaction="white", arrow="no", col.high="lightblue", col.low="tomato",labsize=0.1) grid_arrange_shared_legend(plot1,plot2, plot3,plot4, plot5,plot6, nrow=3,ncol=2)
30134f0c4cc94e4901c72cc64aa70fec0d1d83c2
0b72c2e836e7ba8590dd9cfd3f8dd67798c5eedc
/dev/gene.set/MapBiosystems.r
5b042f80c9c2639623b306565a0439d294d99843
[]
no_license
leipzig/rchive
1fdc5b2b56009e93778556c5b11442f3dbece42c
8814456b218137eafe57bfb19adda19c0d0d625b
refs/heads/master
2020-12-24T12:06:15.051730
2015-08-06T11:59:08
2015-08-06T11:59:08
40,312,197
2
0
null
2015-08-06T15:24:31
2015-08-06T15:24:31
null
UTF-8
R
false
false
10,554
r
MapBiosystems.r
### Functions that process BioSystems annotation info and map BioSystems IDs to other IDs ########################################################################################################################## ########################################################################################################################## # Map gene, protein, etc. to biosystems Map2Biosystems<-function(bsid, species=c('human'='9606'), to=c('gene', 'protein', 'compound', 'substance', 'pubmed'), by.source=TRUE, from=c('r', 'gz', 'url'), path=paste(Sys.getenv("RCHIVE_HOME"), 'data/gene.set/public/biosystems', sep='/')) { #bsid Full annotation table of Biosystems downloaded from NCBI website #species One or multiple species to do the mapping; the value is the NCBI Taxonomy ID and the name is the prefix of output files #to Type(s) of entities the Biosystems will be mapped to #by.source Split mapping results by sources of Biosystems if TRUE, such as GO and KEGG #from Source of input data, from previously save R object, downloaded .gz file, or original URL #path Path to the output input files. <path>/r is for all the R objects and <path>/src is for downloaded .gz file if (!file.exists(path)) dir.create(path); if (!file.exists(paste(path, 'r', sep='/'))) dir.create(paste(path, 'r', sep='/')); # all possible input sources r<-paste(path, '/r/biosystem2', to, '_fulltable.rds', sep=''); fnm<-c("biosystems_gene_all.gz", "biosystems_protein.gz", "biosystems_pccompound.gz", "biosystems_pcsubstance.gz", "biosystems_pubmed.gz") gz<-paste(path, '/src/', fnm, sep=''); url<-paste("ftp://ftp.ncbi.nih.gov/pub/biosystems/CURRENT", fnm, sep='/'); cnm<-c('Gene', 'Protein', 'Compound', 'Substance', 'PubMed'); names(r)<-names(gz)<-names(url)<-names(cnm)<-c('gene', 'protein', 'compound', 'substance', 'pubmed'); to<-to[to %in% names(r)]; if (length(to) == 0) to<-'gene'; r<-r[to]; gz<-gz[to]; url<-url[to]; cnm<-cnm[to]; # Load full mapping data frm<-tolower(from)[1]; ttl<-lapply(to, function(nm) { if (frm=='r' & file.exists(r[nm])) { print(r[nm]); readRDS(r[nm]); } else { if (frm!='gz' | !file.exists(gz[nm])) download.file(url[nm], gz[nm]); # Download data from source print(gz[nm]); mp<-read.table(gz[nm], sep='\t', stringsAsFactors=FALSE); colnames(mp)<-c('BioSystem_ID', paste(cnm[nm], 'ID', sep='_'), 'Score'); mp[[1]]<-as.character(mp[[1]]); mp[[2]]<-as.character(mp[[2]]); saveRDS(mp, file=paste(path, '/r/', 'biosystem2', nm, '_fulltable.rds', sep='')); saveRDS(split(mp[[2]], mp[[1]]), file=paste(path, '/r/', 'biosystem2', nm, '_list.rds', sep='')); mp; } }); names(ttl)<-to; sp<-species[species %in% bsid$Taxonomy]; if (is.null(names(sp))) names(sp)<-sp else names(sp)[names(sp)=='']<-sp[names(sp)=='']; fn<-lapply(names(sp), function(nm) sapply(names(ttl), function(tp) { cat('Mapping', tp, 'of', nm, '\n'); bs<-bsid[bsid$Taxonomy==sp[nm], ]; t1<-ttl[[tp]]; t1<-t1[t1[[1]] %in% rownames(bs), ]; mp<-split(t1[[2]], t1[[1]]); if (!by.source) saveRDS(mp, file=paste(path, '/r/biosystem2', tp, '_', nm, '.rds', sep='')) else { mp0<-split(mp, bsid[names(mp), 1]); sapply(names(mp0), function(sc) saveRDS(mp0[[sc]], file=paste(path, '/r/biosystem2', tp, '_', nm, '_', gsub(' ', '-', sc), '.rds', sep=''))) } })); } ########################################################################################################################## ########################################################################################################################## # Download and parse general Biosystems annotation information ParseBiosystemsGeneral<-function(species=c('human'='9606'), ver="ftp://ftp.ncbi.nih.gov/pub/biosystems/CURRENT", download.new=FALSE, path=paste(Sys.getenv("RCHIVE_HOME"), 'data/gene.set/public/biosystems', sep='/')) { # species Named character vector of NCBI taxanomy ID; the name will be used as prefix of output file # ver The version of BioSystems to download # download.new Whether to re-download source files # path Path to output files if (!file.exists(path)) dir.create(path, recursive=TRUE); if(!file.exists(paste(path, 'r', sep='/'))) dir.create(paste(path, 'r', sep='/')); if(!file.exists(paste(path, 'src', sep='/'))) dir.create(paste(path, 'src', sep='/')); sp<-names(species); names(sp)<-species; #################################################################################################################### # Source file names fn<-c("biosystems_biosystems_conserved.gz", "biosystems_biosystems_linked.gz", "biosystems_biosystems_similar.gz", "biosystems_biosystems_specific.gz", "biosystems_biosystems_sub.gz", "biosystems_biosystems_super.gz", "biosystems_cdd_specific.gz", "biosystems_gene.gz", "biosystems_gene_all.gz", "biosystems_pccompound.gz", "biosystems_pcsubstance.gz", "biosystems_protein.gz", "biosystems_pubmed.gz", "biosystems_taxonomy.gz", "bsid2info.gz"); # Download source files if (download.new) download.file('ftp://ftp.ncbi.nih.gov/pub/biosystems/README.txt', paste(path, '/src/README.txt', sep='')); # original README file fn0<-paste(ver, fn, sep='/'); # source files fn1<-paste(path, 'src', fn, sep='/'); # local files dnld<-lapply(1:length(fn), function(i) if (download.new | !file.exists(fn1[i])) download.file(fn0[i], fn1[i])); ##################### ### Start parsing ### ##################### ########################################################################################### # Meta table of bio-systems, row names are the unique BioSystems IDs lines<-scan(fn1[grep('bsid2info.gz$', fn1)][1], what='', sep='\n', flush=TRUE); split<-strsplit(lines, '\t', useBytes=TRUE); bsid<-t(sapply(split, function(s) s[1:8])); rownames(bsid)<-bsid[,1]; bsid[is.na(bsid)]<-''; bsid<-data.frame(bsid[, -1], stringsAsFactors=FALSE); names(bsid)<-c('Source', 'Accession', 'Name', 'Type', 'Scope', 'Taxonomy', 'Description'); saveRDS(bsid, file=paste(path, 'r', 'biosystem_all.rds', sep='/')); # biosystems by source cls<-split(bsid[, -1], bsid[, 1]); sapply(names(cls), function(nm) saveRDS(cls[[nm]], file=paste(path, '/r/biosystem_', gsub(' ', '-', nm), '.rds', sep=''))); saveRDS(cls, file=paste(path, 'r', 'biosystem_by_source.rds', sep='/')); # Save subset of source-species of selected species (human, mouse, rat, ...) tbl<-xtabs(~bsid$Source + bsid$Taxonomy); tbl<-tbl[, colnames(tbl) %in% names(sp), drop=FALSE]; tbl<-tbl[rowSums(tbl)>0, , drop=FALSE]; sapply(1:nrow(tbl), function(i) sapply(1:ncol(tbl), function(j) { fn<-paste(path, '/r/biosystem_', sp[colnames(tbl)[j]], '_', gsub(' ', '-', rownames(tbl)[i]), '.rds', sep=''); tb<-bsid[bsid$Source == rownames(tbl)[i] & bsid$Taxonomy == colnames(tbl)[j], -c(1, 6), drop=FALSE]; #file.remove(fn); if (nrow(tb) > 0) saveRDS(tb, file=fn); }))->nll; # map organism specific biosystems to corresponding conserved biosystems cons2spec<-read.table(fn1[grep("biosystems_biosystems_conserved.gz$", fn1)][1], sep='\t', stringsAsFactors=FALSE); saveRDS(split(as.character(cons2spec[,1]), cons2spec[,2]), file=paste(path, 'r', 'biosystem_conserved2specific.rds', sep='/')); saveRDS(split(as.character(cons2spec[,2]), cons2spec[,1]), file=paste(path, 'r', 'biosystem_specific2conserved.rds', sep='/')); cons<-bsid[bsid$Scope=='conserved biosystem', , drop=FALSE]; cons.id<-split(rownames(cons), cons$Source); ########################################################################################### # Full tables of Biosystems to other ID mapping spec2taxo<-read.table(fn1[grep("biosystems_taxonomy.gz$", fn1)][1], sep='\t', stringsAsFactors=FALSE); id<-as.character(spec2taxo[[1]]); cons<-as.character(cons2spec[[2]]); names(cons)<-cons2spec[[1]]; spec<-data.frame(Organism=as.character(spec2taxo[[2]]), Conserved=cons[id], Score=spec2taxo[[3]], row.names=id, stringsAsFactors=FALSE); spec[is.na(spec)]<-''; saveRDS(spec, file=paste(path, 'r', 'biosystem_organism_specific.rds', sep='/')); tp<-c('gene_all', 'protein', 'pubmed', 'pccompound', 'pcsubstance'); mp.fn<-sapply(tp, function(tp) fn1[grep(tp, fn1)][1]); bs2oth<-lapply(mp.fn, function(fn) read.table(fn, sep='\t', stringsAsFactors=FALSE)); cnm<-c('Gene', 'Protein', 'PubMed', 'Compound', 'Substance'); for (i in 1:length(bs2oth)) { colnames(bs2oth[[i]])<-c('BioSystem_ID', paste(cnm[i], 'ID', sep='_'), 'Score'); bs2oth[[i]][[1]]<-as.character(bs2oth[[i]][[1]]); bs2oth[[i]][[2]]<-as.character(bs2oth[[i]][[2]]); mp<-split(bs2oth[[i]][[2]], bs2oth[[i]][[1]]) saveRDS(bs2oth[[i]], file=paste(path, '/r/', 'biosystem2', tolower(cnm)[i], '_fulltable.rds', sep='')); saveRDS(mp, file=paste(path, '/r/', 'biosystem2', tolower(cnm)[i], '_list.rds', sep='')); sapply(names(cons.id), function(sc) { mp<-mp[names(mp) %in% cons.id[[sc]]]; saveRDS(mp, file=paste(path, '/r/', 'biosystem2', tolower(cnm)[i], '_conserved_', sc, '.rds', sep='')) }) } ########################################################################################### # Save Log # existing full taxonomy table if (download.new) { if (file.exists(paste(path, 'r', 'biosystem_all.rds', sep='/'))) { bsid0<-readRDS(paste(path, 'r', 'biosystem_all.rds', sep='/')); log.old<-list(id=rownames(bsid0), acc=unique(bsid0$Accession), type=unique(bsid0$Type), src=unique(bsid0$Source), taxonomy.old=unique(bsid0$Taxonomy)); } else { log.old<-list(id=c(), acc=c(), type=c(), src=c(), taxonomy=c()) } log.new<-list(id=rownames(bsid), acc=unique(bsid$Accession), type=unique(bsid$Type), src=unique(bsid$Source), taxonomy.old=unique(bsid$Taxonomy)); names(log.old)<-names(log.new)<-c('ID', 'Accession', 'Type', 'Source', 'Taxonomy'); # updates up<-list( N = sapply(log.new, length), Added = lapply(1:5, function(i) setdiff(log.new[[i]], log.old[[i]])), Removed = lapply(1:5, function(i) setdiff(log.old[[i]], log.new[[i]])) ) # update logs log<-readRDS(paste(path, 'log.rds', sep='/')); log<-c(log, list(up)); names(log)[length(log)]<-as.character(Sys.Date()); saveRDS(log, file=paste(path, 'log.rds', sep='/')); } }
90df3440aff6eaa0332efe8a0ef57e88f0695cbb
cc7bd76a7bfc0d65246ea92ac962b2ec665c200c
/R/irf.varshrinkest.R
0b0b2050cd9488f539c2529d42fa481f7783b172
[]
no_license
Allisterh/VARshrink
a8d309cac5b251b1674ea534b8b4894b29e1874e
404b4cb254e546137df927ea93afcbb8fe6482c2
refs/heads/master
2022-04-07T03:46:51.261116
2020-03-09T16:47:57
2020-03-09T16:47:57
null
0
0
null
null
null
null
UTF-8
R
false
false
3,177
r
irf.varshrinkest.R
#' Impulse response function #' #' Computes the impulse response coefficients of a VAR(p) #' (or transformed VECM to VAR(p)) for n.ahead steps. #' This is a modification of vars::irf() for the class "varshrinkest". #' #' @param x Object of class 'varshrinkest'; #' generated by \code{VARshrink()} #' @param impulse A character vector of the impulses, #' default is all variables. #' @param response A character vector of the responses, #' default is all variables. #' @param n.ahead Integer specifying the steps. #' @param ortho Logical, if TRUE (the default) the #' orthogonalised impulse response coefficients are #' computed (only for objects of class 'varshrinkest'). #' @param cumulative Logical, if TRUE the cumulated impulse #' response coefficients are computed. The default value #' is false. #' @param boot Logical, if TRUE (the default) bootstrapped #' error bands for the imuplse response coefficients are #' computed. #' @param ci Numeric, the confidence interval for the #' bootstrapped errors bands. #' @param runs An integer, specifying the runs for the #' bootstrap. #' @param seed An integer, specifying the seed for the #' rng of the bootstrap. #' @param ... Currently not used. #' @seealso \code{\link[vars]{irf}} #' @export irf.varshrinkest <- function (x, impulse = NULL, response = NULL, n.ahead = 10, ortho = TRUE, cumulative = FALSE, boot = TRUE, ci = 0.95, runs = 100, seed = NULL, ...) { if (!inherits(x, "varest")) { stop("\nPlease provide an object inheriting class 'varest'.\n") } y.names <- names(x$varresult) if (is.null(impulse)) { impulse <- y.names } else { impulse <- as.vector(as.character(impulse)) if (any(!(impulse %in% y.names))) { stop("\nPlease provide variables names in impulse\nthat are in the set of endogenous variables.\n") } impulse <- subset(y.names, subset = y.names %in% impulse) } if (is.null(response)) { response <- y.names } else { response <- as.vector(as.character(response)) if (any(!(response %in% y.names))) { stop("\nPlease provide variables names in response\nthat are in the set of endogenous variables.\n") } response <- subset(y.names, subset = y.names %in% response) } irs <- h_irf(x = x, impulse = impulse, response = response, y.names = y.names, n.ahead = n.ahead, ortho = ortho, cumulative = cumulative) Lower <- NULL Upper <- NULL if (boot) { ci <- as.numeric(ci) if ((ci <= 0) | (ci >= 1)) { stop("\nPlease provide a number between 0 and 1 for the confidence interval.\n") } ci <- 1 - ci BOOT <- h_boot(x = x, n.ahead = n.ahead, runs = runs, ortho = ortho, cumulative = cumulative, impulse = impulse, response = response, ci = ci, seed = seed, y.names = y.names) Lower <- BOOT$Lower Upper <- BOOT$Upper } result <- list(irf = irs, Lower = Lower, Upper = Upper, response = response, impulse = impulse, ortho = ortho, cumulative = cumulative, runs = runs, ci = ci, boot = boot, model = class(x)) class(result) <- c("varshirf", "varirf") return(result) }
9010e01dc444b37e537ae8aa1956eb1f1a6af45c
b0f1f080bb508c682e7f4d9f1b4ff793939af5d6
/R/to.long.R
dd2b4467dfe45aeeb786c7f439387c5db3329bf0
[]
no_license
CaoMengqi/sgmm
fd4989c60533d3b18df46e9d4334390f0f19b332
a3285a9a818a0dd16e6e5ea075cc42268943f9ee
refs/heads/master
2022-01-22T07:37:42.450967
2019-08-23T13:14:09
2019-08-23T13:14:09
null
0
0
null
null
null
null
UTF-8
R
false
false
2,330
r
to.long.R
#' A Wide to Long Data Set Function #' #' This function helps you convert a wide time-series data set (with one row for each patient and multiple columns for each different time points), to a long time-series data set (with t rows for each patient where t=number of time poitns). #' @param data enter data set containing month values. #' @param id_column enter the column containing patient IDs (str) #' @param time_columns enter the time-varying outcome variable columns #' @param date_columns enter the time-indicating month-formatted columns (str) #' @keywords lcmm #' @export #' @examples #' to.long() to.long <- function(data, id_column, time_columns, date_columns) { # reformat id col to factor factored_ids <- as.factor(as.character(data[, which(colnames(data) == toString(id_column))])) # these are the IDs in order ordered_id_levels <- as.numeric(as.character(factored_ids)) # we don't want to use the actual date columns, but instead the month columns # corresponding to the date columns. that is what is happening here: names_list <- c("m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8", "m9", "m10", "m11", "m12", "m13", "m14", "m15", "m16", "m17", "m18", "m19", "m20", "m21", "m22", "m23", "m24", "m25", "m26", "m27", "m28", "m29", "m30", "m31", "m32", "m33", "m34", "m35", "m36", "m37", "m38", "m39", "m40", "m41", "m42", "m43", "m44", "m45", "m46", "m47", "m48", "m49", "m50") month_columns <- names_list[1:length(date_columns)] # new_empty df new_df <- data.frame() # looping # for each id... for(i in 1:length(ordered_id_levels)) { # for each time point... for(col in 1:length(time_columns)) { # stack times times <- t(cbind(data[i, time_columns[col]])) # stack dates months <- t(cbind(data[i, month_columns[col]])) # it is important to use this object, and not to recall the user-inserted data again ids <- ordered_id_levels[i] mybind <- as.data.frame(cbind(ids, times, months)) # append a df new_df <- bind_rows(new_df, mybind) } } # renaming cols colnames(new_df) <- c('id', 'outcomes', 'months') print("colnames are (i) 'id', (ii) 'outcomes', and (iii) 'months'") # end return(new_df) }
e4e121eff6deaffcaa6797e89516d51e25688d68
86bcacc47430c92c6d9a08c57babd0a5ca020541
/StatisticalComputing/HW3/mix.R
79a90ceab859dc5119b53a6d4c898e16c1edb0d2
[]
no_license
xohyun/University
b5dc7ac522415f59080c2d54982a672c258a437e
ec5eb3dfab953140b6b61e650d8e9ec65188486d
refs/heads/master
2023-02-19T03:59:54.882670
2021-01-22T15:06:34
2021-01-22T15:06:34
331,948,930
0
0
null
null
null
null
UTF-8
R
false
false
642
r
mix.R
n <- 30 m <- 100000 mse <- matrix(0, 1, 3) colnames(mse) <-c("sample mean", "sample median", "the 1st trimmed mean") calculate_mse <- function(n, m) { tmean <- numeric(m) x_mean <- numeric(m) x_median <- numeric(m) for (i in 1:m) { sigma <- sample(c(1,10), size = n, replace = TRUE, prob = c(0.9, 0.1)) x <- sort(rnorm(n, 0 , sigma)) tmean[i] <- sum(x[2:(n-1)])/(n-2) x_mean[i] <- mean(x) x_median[i] <- median(x) } mse.tmean <- mean(tmean^2) mse.mean <- mean(x_mean^2) mse.median <- mean(x_median^2) return (c(mse.mean, mse.median, mse.tmean)) } mse[1, 1:3] <- calculate_mse(n = n, m = m) print(mse)
97bd1c3ce9a258f5f586c206f3eb67950ff96229
802683d96a176be260f8de0ff1332a382a5f90c5
/man/attachContext.Rd
80c679ff4de28d93cca5952a38ee152244e05fdd
[]
no_license
dami82/mutSignatures_dev
a14fbbc7ac32a288b784e6d77517ea8268d72704
7065d66ed896c1684f945c004524df148122cc71
refs/heads/master
2021-04-15T03:57:15.490229
2018-09-24T17:37:50
2018-09-24T17:37:50
126,903,439
0
0
null
null
null
null
UTF-8
R
false
false
554
rd
attachContext.Rd
\name{attachContext} \alias{attachContext} \title{ Attach Context } \description{ Attach Context } \usage{ attachContext(mutData, BSGenomeDb, chr_colName = "chr", start_colName = "start_position", end_colName = "end_position", nucl_contextN = 3, context_colName = "context") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{mutData}{ data } \item{BSGenomeDb}{ data } \item{chr_colName}{ data } \item{start_colName}{ data } \item{end_colName}{ data } \item{nucl_contextN}{ data } \item{context_colName}{ data } }
eb4c6eb01da5d1af1cab0d628d05025da9915f6e
7f2cf6dbcc98b1e50aaa4d3c82bbd0291affceaf
/man/simc.model.Rd
fb45175225a5e85ab6e1e7c4f39bab78f900bd1a
[ "Apache-2.0" ]
permissive
guhjy/RsimCity
25d9ebf226cf413f2c4228bb295a1c8647a56d4f
d21488ffaf019830cfbbf2b2558b1b2584add394
refs/heads/master
2020-03-27T04:27:53.572645
2014-02-04T18:46:08
2014-02-04T18:46:08
null
0
0
null
null
null
null
UTF-8
R
false
false
9,611
rd
simc.model.Rd
\name{simc.model} \title{Define a set of linear models} \alias{simCity.model} \concept{ simCity model } \description{ Specify a data generating model for simCity simulations } \usage{ simc.model(file="",exdist=NULL,excov=NULL) \cr simc.model(file="",exdist=NULL,excov=NULL) x~1;edist=rnorm(0,1) y~x;edist=rbinom(10,.5); apply=fun() # } \arguments{ \item{file}{The (quoted) file from which to read the date generating model specification, including the path to the file if it is not in the current directory. If "" (the default), then the specification is read from the standard input stream, and is terminated by a blank line or \code{#}.} \item{exdist}{multivariate distribution of the exogenous variables. If NULL \code{\link{rmnorm}} is used. It can be any function which accept N as first argument, mean and excov as second and third argument} \item{excov}{covariance matrix for the exogenous variables. It must have names corresponding to the exogenous variable names (see details). If there are exogenous variables and no \code{excov} is provided, an identity matrix is the default } \item{fun}{any function which accepts a variable as argument (see details)} } \details{ The data generating model can be specified in a text file or in standard input stream should specify an equation per line. Each line features (if not default applies), separated by semicolumns, an \code{equation}, \code{edist=} a function to generate random residuals, \code{apply=} a list of functions to be applied to the generated variable, \code{options=} a list of options to fine-tune the variable. An example of line can be: \cr \code{y~x+z;edit=rnorm(0,1);apply=scale(),exp();options=beta} \cr \itemize{ \item{\code{equations}:}{ a formula declaring the linear model. Formula should be specified in a way that can be coerce to \code{\link{as.formula}}. For instance \code{y~x+z}. No coefficients should be specified, as they will be specified later during the data generating process (so they can be varied for each run). Constant terms (intercepts) can be specified adding \code{1} as in \code{y~1+x}. Coefficients (possibly \code{1}) should be provided in the experiment if an intercept is declared. Any artimetics should be passed using \code{\link{I}} function or \code{.()} notation. For instance: \code{y~x+I(x^2)+z+I(x*z)} or \code{y~x+.(x^2)+z+.(x*z)} (these two are equivalent). At the moment (version < \code{1.0}), the "\code{:}" notation for interactions is not allowed (use \code{I(x*x)} instead). See examples for further details } \item{\code{edist}:} {a function name to be used to generate the residuals of the linear model. The function should accept as its first argument the sample size (N) and can have any argument as one need. For instance, to generate and endogenous variable accordingly to the model \code{y~x} with standardized residuals one would write \code{edist=rnorm(0,1) } (cf. \code{\link{rnorm}}). Binomial residuals can be specified with \code{edist=rbinom(size,prob)} (cf. \code{\link{rbinom}}). If the parameters of the distribution should be changed during the simulation experiment, reference functions can be used (see examples). Any function can be used as long as it accept N as first argument. If no distribution is specified, \code{edist=rnorm(0,1) } is the default. Note that the distribution function is evaluated in the environment of the data.frame being produced, thus it may have variables as arguments (cf \code{\link[simcity]{categorial}} and "Examples") } \item{\code{apply}:} {a list of function names separated by comma to be applied to the generated endogenous variable. The function should be writen as \code{func(arg1,arg2)} but it must accept the endogenous variable as its first argument. For instance, to standardize the endogenous variable after it is created, one can use \code{\link{scale}} writing \code{apply=scale()}. To center the variable to its mean one can write \code{apply=scale(scale=FALSE)} which implicitly assumes that the function usage is \code{scale(x,scale=FALSE)}. Note that the function in \code{apply} is evaluated in the environment of the data.frame being produced, thus it may have variables as arguments (cf \code{\link[simcity]{categorial}} and "Examples")} \item{\code{options}:} {a comma separeted list of options to fine-tune the data generating process for the corresponding endogenous variable. Available options are: \itemize{ \item{\code{beta}:}{coefficients that will be passed to the simulation should be intended as betas (standardized coefficients). The endogenous variable is constructed using calculated coefficients such that the simple \code{beta} linking the endogenous and the exogenous variable correspond to the passed coefficient. Note that the resulting betas would correspond to the coefficients passed to the simulation only if the exogenous variables are uncorrelated.} \item{\code{trans}:}{the line is intended as a mere \code{trans}formation of the exogenous variable. In practice, when \code{options=trans} is specified, not random residuals are added to the endogenous variable. This options is usefull when complex transformations are needed which are not suitable for using \code{apply}. Choosing to specify a new line for a transformation (with \code{options=trans}) or using the argument \code{apply} is a matter of taste and convenience, particularly as regard how the coefficients apply to the formulas in generating the data. For instance in this model \code{y1} and \code{y2} are structurally identical:\cr\cr \code{ simc.model(file="") \cr y~exp(x); options=trans \cr y~x;apply=exp() \cr # \cr } however, when the simulation is run and the coefficients are passed to the model, for model in line one the coefficient \code{c} result in \code{y~c*exp(x)}, whereas in line two it results in \code{y~exp(c*x)} } } } } } \value{ An object of class \code{\link[simCity]{simCity.model}} which contains (if not default applies): \itemize{ \item{\code{equations}:}{ an object containing, for each equation specified in the model: \itemize{ \item{\code{equation}:} {the equation specified for one linear model} \item{\code{edist}:} {the function producing the residual distribution of the corresponding linear model. } \item{\code{options}:} {a list of options passed to the model } \item{\code{apply}:} {a list of functions to apply on the generated endogenous variable } } } \item{\code{endogenous}:} {a list of endogenous variables name (as.character)} \item{\code{exogenous}:} {a list of exogenous variables name (as.character)} } The object can be passed to to generate one sample, to to set up a complete experiment } \seealso{ \code{\link[stats]{lm}} } \examples{ ### define a simple model with two variables normally distributed, x standardized. simc.model() x~1;edist=rnorm(0,1) y~x # ### define a simple model with two variables normally distributed, both standardized. model<-simc.model() x~1;edist=rnorm(0,1) y~x;apply=scale() # print(model) ### define a model with two uncorrelated and standardized exogenous variables a endogenous variable with binomial residuals. model<-simc.model() y~x+z;edist=rbinom(100,.5) # ### define a model with two correlated exogenous variables with different variances and a endogenous variable with binomial residuals. covs<-matrix(c(2,.3,.3,4),ncol=2) colnames(covs)<-rownames(covs)<-c("x","z") model<-simc.model(excov=covs) y~x+z;edist=rbinom(100, .5) # ### define a model with two standardized correlated exogenous variables endogenous variable with binomial residuals and exponential relations with the exogenous variable. covs<-matrix(c(1,.3,.3,1),ncol=2) colnames(covs)<-rownames(covs)<-c("x","z") model<-simc.model(excov=covs) y~x+z;rbinom(100,.5);apply=exp() # ### define a model with two exogenous variables and an interaction on the endogenous. Coefficients will be passed as standardized coefficients model<-simc.model() y~x+z+I(x*z);rbinom(100,.5);options=beta # ### define a series of polinomial models model<-simc.model() y~x+I(x^2)+I(x^3) z~x+I(exp(log(x)*1/2))+I(exp(log(x)*1/3))+I(exp(log(x)*1/4)) # ### define a mediational model with non standardized residual model<-simc.model() m~x; edist=rnorm(5,10) y~m+x, edist=rnorm(2, 10) # ### define a structural factorial model with two correlated latent factors and 3 observed variables for each factor with etherogenous distribution of residuals. covs<-matrix(c(1,.2,.2,1),ncol=2) colnames(covs)<-rownames(covs)<-c("xi","eta") model<-simc.model(excov=covs) x1~xi x2~xi; binom(10,.5) x2~xi; uniform(0,1) x3~eta; rnorm(0,1) x4~eta; binom(10,.5) x5~eta; uniform(0,1 ) # ### use of reference functions: define a model with a latent variable, a continuous measure and two dichotomized versions of it with different cut-offs mysplit<-function(x,p) { x<-x>quantile(x,p) as.numeric(x) } model<-simc.model() x~csi; rnorm 0 1 d1~x; apply=mysplit(.5) d2~x, apply=mysplit(.7) # ### use of reference functions: define a model with a latent variable, two continuous measures with different percentace of missing values mymissing<-function(x,p) { x[p<runif(length(x),0,1)]<-NA as.numeric(x) } model<-simc.model() x~csi, rnorm 0 1 d1~x, apply=mymissing(.05) d2~x, apply=mymissing(.15) # } \keyword{models}
b52445cf712a5429434fa6418d1a104b9173c482
e17c6aec7115cb53939b784a87f5909be5fff032
/GISS temperature anomaly.R
397d5ad8611caafcf95a5ed7e582b8894eba85dc
[]
no_license
fawnshao/rexamples
801ca734159a46ac67ed03b578001529563d3142
8e61d423237da5cb409f032dd896903fe8ac68c4
refs/heads/master
2021-01-18T05:46:15.505501
2013-06-11T01:26:21
2013-06-11T01:26:21
null
0
0
null
null
null
null
UTF-8
R
false
false
5,190
r
GISS temperature anomaly.R
####################################################################################### ## R Script to read NASA GISS monthly global (land & SST) temperatue anomnaly file # ## Summarize recent trends and generate plot # ## D Kelly O'Day, http://processtrends.com & http://chartgraphs.wordpress.com # ## GISS monthly data import script develodped by http://LearnR.wordpress.com # ####################################################################################### ## Setup & Download from web rm(list=ls()); options(digits=8) script <- "GISS_Trend_by_decade.R" library(ggplot2) par(oma=c(2,1,1,1)) ; par(mar=c(2,4,3,1)); par(xaxs="i"); par(yaxs="i") par(ps=9); par(las=1) ################################## Download and process GISS Data File ############### url <- c("http://data.giss.nasa.gov/gistemp/tabledata/GLB.Ts+dSST.txt") file <- c("GLB.Ts+dSST.txt") download.file(url, file) ## Cleanup File #The first 8 rows and the last 12 rows of the textfile contain instructions # Find out the number of rows in a file, and exclude the last 12 rows <- length(readLines(file)) - 12 # Read file as char vector, one line per row, Exclude first 7 rows lines <- readLines(file, n=rows)[9:rows] #Data Manipulation, R vector with 143 lines. ### Use regexp to replace all the occurences of **** with NA lines2 <- gsub("\\*{3,5}", " NA", lines, perl=TRUE) #Convert the character vector to a dataframe df <- read.table( textConnection(lines2), header=TRUE, colClasses = "character") closeAllConnections() # We are only interested in the montly data in first 13 columns df <- df[,1:13] # Convert all variables (columns) to numeric format df <- colwise(as.numeric) (df) #head(df, 12) # Remove rows where Year=NA from the dataframe df <- df [!is.na(df$Year),] # Convert from wide format to long format dfm <- melt(df, id.var="Year", variable_name="Month") mo_num <- unclass(dfm$Month) mo_frac <- as.numeric(( unclass(dfm$Month)-0.5)/12) #mo_frac yr_frac <- dfm$Year + mo_frac #yr_frac temp_anom <- dfm$value/100 dfm <- data.frame(dfm, mo_num, yr_frac, temp_anom) dfm <- dfm[order(dfm$yr_frac), ] dfm <- dfm[!is.na(dfm$temp),] ## Find last report month and last value last <- nrow(dfm) last_yr <- dfm$Year[last] last_mo <- dfm$Month[last] last_temp <- dfm$temp[last] out <- paste("Latest GISS report: " , last_mo, " - ", last_yr, "; Global land & Sea Temp - Anomaly - ", last_temp) out ############################################################################################## ## Produce plot and prepare regressions plot(temp_anom~ yr_frac, data = dfm, type = "l", col = "darkgrey", xlab = "", ylab = "GISS Temperature Anomaly - C", xlim = c(1880, 2020), ylim = c(-1,1), axes = F, pty="m", main = "GISS Temperature Anomaly \nwith Trend Rates By Decade") axis(1, col="grey") axis(2, col = "grey") grid(col = "lightgrey", lty=1) # overall trend flm <- lm(dfm$temp_anom ~ dfm$yr_fr ) x_min <- min(dfm$yr_frac) x_max <- max(dfm$yr_frac) y_min <- dfm$temp_anom[1] y_max <- dfm$temp_anom[nrow(dfm)] a_flm <- coef(flm)[1] b_flm <- coef(flm)[2] x_vals <- c(x_min, x_max) y_vals <- c(a_flm +b_flm*x_min, a_flm + b_flm*x_max) lines(x_vals, y_vals, col = 139) overall_rate <- signif(b_flm*100,3) overall_note_1 <- "Overall Trend - oC/C" rect(1882, 0.8, 1920, .96, density = NULL, col = "white", border = "white") text(1884, 0.92, adj = 0, overall_note_1, col = 139, cex=0.9) text(1892, 0.85, adj=0, overall_rate,col = 139, cex=0.9) ## Calculate monthly regressions n <- 200-188 v_i <- as.numeric(n) v_a <- as.numeric(n) v_b <- as.numeric(n) rect(1910, -0.94, 1980, -0.8, density = NULL, col = "white", border = "white") text(1940, -0.89, "Decade Trend Rate -oC per Century", font=3) for (d in 1:13){ i = 1870+ d *10 v_i[d] <- i sub <- subset(dfm, dfm$yr_frac>=i) sub <- subset(sub, sub$yr_frac < i+10) dlm <- lm(sub$temp_anom ~ sub$yr_frac, data = sub) #to set indvidual a & b factors for each decade a <- coef(dlm)[1] v_a[d] <- a b <- coef(dlm)[2] v_b[d] <- b x_vals <- c(i, i+9.99) y_vals <- c(a+b*i, a+b*(i+9.99)) ## color code decade trend rate based on <> 0 if (v_b[d] < 0) {dec_col = "darkblue"} if (v_b[d] >= 0) {dec_col = "red"} lines(x_vals, y_vals, col = dec_col) text(i+1, -0.95, signif(b*100, 2), adj = 0, cex=0.8, col = dec_col) } ## generate dat frame of regression results df_regr <- data.frame(v_i, v_a, v_b) names(df_regr) <- c("Decade", "a Coef", "b Coef") df_regr ## Margin Text my_date <- format(Sys.time(), "%m/%d/%y") mtext(script, side = 1, line = .5, cex=0.8, outer = T, adj = 0) mtext(my_date, side = 1, line =.5, cex = 0.8, outer = T, adj = 1)## Add script name to each plot mtext("D Kelly O'Day", side = 1, line =.5, cex = 0.8, outer = T, adj = 0.7)## Add script name to each plot data_note <- paste("Land & Sea Stations \n Baseline 1950-1980") rect(1939, 0.75, 1961, 0.9, density = NULL, col = "white", border = "white") text(1950, 0.85, data_note, cex = 0.8)
b85807e14ef852fe0227b6bea4d58a0ea394d011
d2088d962b87482688cfe98c0c73fe978bc38c5f
/src/function_load_gene_list_data_individual_gene_plots.R
bab5f57fcfb0c067a77263dce689f97a16e681bb
[]
no_license
pascaltimshel/temporal-brain-expression-scz
e7360890243de5df04cd3e3a71cd522315a67ed0
8a5bed33d1c3b689cbba18e0a6ec54c5eb05f2e8
refs/heads/master
2021-06-29T18:47:25.020356
2017-09-15T08:33:49
2017-09-15T08:33:49
26,609,253
2
1
null
null
null
null
UTF-8
R
false
false
3,699
r
function_load_gene_list_data_individual_gene_plots.R
############################# FUNCTIONS ################################# ######### Adding x-tickmarks for stage do_stage_converter <- function (p) { stage_converter <- c("s1"="Embryonic", "s2a"="Early prenatal", "s2b"="Early prenatal", "s3a"="Early mid-prenatal", "s3b"="Early mid-prenatal", "s4"="Late mid-prenatal", "s5"="Late prenatal", "s6"="Early infancy", "s7"="Late infancy", "s8"="Early childhood", "s9"="Late childhood", "s10"="Adolescence", "s11"="Adulthood") p <- p + scale_x_discrete(name="", labels = stage_converter) + theme(axis.text.x = element_text(angle = 35, hjust = 1, size=rel(1.15))) return(p) } ############################# READING GENE LISTs ################################# path.datafiles <- '/Users/pascaltimshel/p_scz/brainspan/gene_lists' ###### Read into a list of files - PATTERN VERSION - read ALL .txt files in directory: #files <- list.files(path = path.datafiles, pattern = "*.txt", full.names = TRUE) #full path #names(files) <- list.files(path = path.datafiles, pattern = "*.txt") # filename #cat(names(files), sep="\n") ###### Read SPECIFIC FILES: filenames2read <- c("gene_prioritization.txt") #filenames2read <- c(filenames2read, "gene_associated.txt", "gene_nearest.txt") #filenames2read <- c(filenames2read, "gene_psd_human.txt", "gene_psd_mouse.txt") #filenames2read <- c(filenames2read, "gilman_nn_2012_cluster1.ens", "gilman_nn_2012_cluster1a.ens", "gilman_nn_2012_cluster1b.ens", "gilman_nn_2012_cluster2.ens") #filenames2read <- c(filenames2read, "gulsuner_S3A_damaging_cases.ens") files <- as.list(paste(path.datafiles, filenames2read, sep="/")) names(files) <- filenames2read files list_of_data <- llply(files, read.csv)#row.names = 1 --> NO!, stringsAsFactors = FALSE names(list_of_data) extract_genes_from_molten_df <- function(df_gene_list) { print("done") df <- subset(df.expression_matrix.clean.melt, ensembl_gene_id %in% df_gene_list[,1]) } df.gene_list <- ldply(list_of_data, extract_genes_from_molten_df, .id="gene_list") ## Converting .id=gene_list to factor df.gene_list$gene_list <- as.factor(df.gene_list$gene_list) str(df.gene_list) levels(df.gene_list$gene_list) ###################################### PROCESSING GENE lists ################################ ###### Mean per stage/structure ######## df.summary <- ddply(df.gene_list, c("stage", "structure_acronym", "gene_list"), summarise, mean = median(value, na.rm=TRUE), sd = sd(value, na.rm=TRUE)) ## plyr magic for renaming factor level levels(df.summary$gene_list) df.summary$gene_list <- revalue(df.summary$gene_list, c("gene_associated.txt"="Associated Genes", "gene_nearest.txt"="Nearest Genes", "gene_prioritization.txt"="Prioritized Genes", "gene_psd_human.txt"="Post Synaptic Genes (Human)", "gene_psd_mouse.txt"="Post Synaptic Genes (Mouse)")) levels(df.summary$gene_list) ###### Mean per stage - FINAL ########## df.summary.sem <- ddply(df.summary, c("stage","gene_list"), summarise, mean1 = mean(mean, na.rm=TRUE), sd1 = sd(mean, na.rm=TRUE)) ###################################### Calculating overall mean ################################ ### *** Runtime ~ 10 s *** df.all.sem <- ddply(ddply(df.expression_matrix.clean.melt, .(stage, structure_acronym), summarise, mean=median(value, na.rm=TRUE)), .(stage), summarise, mean1=mean(mean, na.rm=TRUE), sd1=sd(mean, na.rm=TRUE))
f0f7a6446437a2f2485a08ff234d38dd48a670aa
941bcfc6469da42eec98fd10ad1f3da4236ec697
/R/track_bearing.R
c0216bdf419298ecfbc2a12cd123daf53f04e98e
[]
no_license
cran/traipse
29c3fd65e98f65049da98b1d878512bfdd93940f
01635fd40512f2144e1ce712e0f5912143214e49
refs/heads/master
2022-10-22T02:59:19.828085
2022-10-10T06:40:02
2022-10-10T06:40:02
236,953,410
0
0
null
null
null
null
UTF-8
R
false
false
1,047
r
track_bearing.R
#' Track bearing #' #' Calculate sequential bearing on longitude, latitude input vectors. The unit of bearing is degrees. #' #' By convention the last value is set to `NA` missing value, because the bearing #' applies to the segment extending from the current location. #' #' To use this on multiple track ids, use a grouped data frame with tidyverse code like #' `data %>% group_by(id) %>% mutate(turn = track_bearing(lon, lat))`. #' #' Absolute bearing is relative to North (0), and proceeds clockwise positive and anti-clockwise #' negative `N = 0, E = 90, S = +/-180, W = -90`. #' #' The last value will be `NA` as the bearing is relative to the first point of each segment. #' @param x longitude #' @param y latitude #' @return a numeric vector of absolute bearing in degrees, see Details #' @export #' @examples #' track_bearing(trips0$x, trips0$y)[1:10] track_bearing <- function(x, y) { xy <- cbind(x, y) n <- nrow(xy) c(geosphere::bearing(xy[-nrow(xy), , drop = FALSE], xy[-1L, , drop = FALSE]), NA_real_) }
87179534c10e810d8baf9eb74ccbdb33d3b3f466
03259c6f6d5814362d967eadd415835b55446fd4
/xcms_code.R
cacc91ba2fd32d13198919a4d93e3e09689298f4
[]
no_license
alenzhao/BatchEffects
82663af89e74539a52cd1e7c67cb4471158a78f3
6542bf1139ccd55b654e0bb31eef9f324f9e57df
refs/heads/master
2021-01-11T16:02:12.502695
2015-10-01T04:34:11
2015-10-01T04:34:11
null
0
0
null
null
null
null
UTF-8
R
false
false
434
r
xcms_code.R
num_cores<-8; # The number of CPUs available, be aware of memory issue library(xcms) set1<-xcmsSet(nSlaves=44,method='centWave',ppm=30,peakwidth=c(5,60), prefilter=c(0,0),snthresh=6) set2 <- group(set1,bw=5,mzwid=0.015,minsamp=1,minfrac=0) set3 <- retcor(set2,method="obiwarp",plottype="none") set4 <- group(set3,bw=5,mzwid=0.015,minsamp=1,minfrac=0) set5 <- fillPeaks(set4) peaklist<-peakTable(set5,filebase="algae_blanks")
4283bee2ef52ec37c693b92264b7adea3ab7a085
df2efbcc44a1d8046cbab35021f47b208a391c41
/scripts/imp_packages_to_install.R
b5a00277a6c85648553ea0a5410db0f83a1ac073
[]
no_license
csngh/machine-learning-cyber-sec
eea96bf0c4e3bca25f2021fee69bf99fc33fd191
b82ac267631f34fd57946afec025f4435ad7f5c5
refs/heads/master
2020-04-16T22:07:55.946370
2019-01-19T13:15:27
2019-01-19T13:15:27
165,954,251
0
0
null
null
null
null
UTF-8
R
false
false
216
r
imp_packages_to_install.R
#Run the below code to install all essential packages install.packages("pacman") pacman::p_load(char = c( "caTools", "caret", "mlbench", "randomForest", "arules", "arulesViz", "ggplot2", "plotly", ))
3f06b47da093c6d1dcd7ccd46ed6d664c1772cf7
e25af04a06ef87eb9fc0c3c8a580b8ca4e663c9b
/man/r_unif.Rd
568f90b18d1e291cb0ef45f2e4ce9a2fa297093b
[]
no_license
cran/sphunif
c049569cf09115bb9d4a47333b85c5b7522e7fd8
4dafb9d08e3ac8843e8e961defcf11abe2efa534
refs/heads/master
2023-07-16T01:12:47.852866
2021-09-02T06:40:02
2021-09-02T06:40:02
402,474,585
0
0
null
null
null
null
UTF-8
R
false
true
1,343
rd
r_unif.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R \name{r_unif} \alias{r_unif} \alias{r_unif_cir} \alias{r_unif_sph} \title{Sample uniformly distributed circular and spherical data} \usage{ r_unif_cir(n, M = 1L, sorted = FALSE) r_unif_sph(n, p, M = 1L) } \arguments{ \item{n}{sample size.} \item{M}{number of samples of size \code{n}. Defaults to \code{1}.} \item{sorted}{return each circular sample sorted? Defaults to \code{FALSE}.} \item{p}{integer giving the dimension of the ambient space \eqn{R^p} that contains \eqn{S^{p-1}}.} } \value{ \itemize{ \item \code{r_unif_cir}: a \bold{matrix} of size \code{c(n, M)} with \code{M} random samples of size \code{n} of uniformly-generated circular data on \eqn{[0, 2\pi)}. \item \code{r_unif_sph}: an \bold{array} of size \code{c(n, p, M)} with \code{M} random samples of size \code{n} of uniformly-generated directions on \eqn{S^{p-1}}. } } \description{ Simulation of the uniform distribution on \eqn{[0, 2\pi)} and \eqn{S^{p-1}:=\{{\bf x}\in R^p:||{\bf x}||=1\}}{ S^{p-1}:=\{x\in R^p:||x||=1\}}, \eqn{p\ge 2}. } \examples{ # A sample on [0, 2*pi) n <- 5 r_unif_cir(n = n) # A sample on S^1 p <- 2 samp <- r_unif_sph(n = n, p = p) samp rowSums(samp^2) # A sample on S^2 p <- 3 samp <- r_unif_sph(n = n, p = p) samp rowSums(samp^2) }
0d2b1c16528a963d7ffc88d55a1a7aaa48b9c640
a68ddef61b62475e2cb9c9a81f7ddf3b819d4db9
/SFEI_chl/modelBuilding/addCovariateSpatialMod.R
fe49d8dfb491dd9d17d8249e2576f549b3d87b89
[]
no_license
sastoudt/DS421_summerProject
8f21d04c94a8ae97c6a6b70d0af31f50c9fdcd0c
69996a5662db3564fb44a79a3f55ee0514b30824
refs/heads/master
2020-05-22T03:59:54.549579
2019-12-20T20:53:01
2019-12-20T20:53:01
60,031,870
1
2
null
2016-06-02T23:21:52
2016-05-30T18:48:18
R
UTF-8
R
false
false
3,236
r
addCovariateSpatialMod.R
## spatial models with bam setwd("~/Desktop/sfei") require(mgcv) load("perStation.Rda") names(perStation[[1]]) wholeSeries<-c(1, 2, 5, 7, 11, 13, 15, 16, 17, 18, 21, 22, 23, 29, 40) allData<- do.call("rbind", perStation[wholeSeries]) names(allData) class(allData$Station) ## Need to make a factor ctrl <- list(nthreads=4) system.time(gamP<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station))+ti(date_dec,bs="tp",by=as.factor(Station))+ti(pheo,bs="tp"),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP) ## 30 seconds system.time(gamP<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station))+ti(date_dec,bs="tp",by=as.factor(Station))+ti(pheo,bs="tp",k=10),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP) system.time(gamP<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station))+ti(date_dec,bs="tp",by=as.factor(Station))+ti(pheo,bs="tp",k=20),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP) ## warning system.time(gamP<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station))+ti(date_dec,bs="tp",by=as.factor(Station))+ti(pheo,bs="tp",k=15),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP) ## warning system.time(gamP<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station))+ti(date_dec,bs="tp",by=as.factor(Station),k=10)+ti(pheo,bs="tp",k=10),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP) system.time(gamP<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station),k=10)+ti(date_dec,bs="tp",by=as.factor(Station),k=10)+ti(pheo,bs="tp",k=10),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP) ## Just under a minute spatialMod3Pheo=gamP save(spatialMod3Pheo,file="spatialMod3Pheo.RData") ## pheo helps make this look pretty decent without getting too big ## pheo by station system.time(gamP2<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station))+ti(date_dec,bs="tp",by=as.factor(Station))+ti(pheo,bs="tp",by=as.factor(Station)),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP2) ## stopped after 5 minutes ## try tn system.time(gamP3<-bam(chl~as.factor(Station)+ti(doy,bs="cc",by=as.factor(Station),k=10)+ti(date_dec,bs="tp",by=as.factor(Station),k=10)+ti(tn,bs="tp",k=10),data=allData,family=gaussian(link="log"),control=ctrl)) gam.check(gamP3) ## under 2 minutes spatialMod3Tn=gamP3 save(spatialMod3Tn,file="spatialMod3Tn.RData") ## require(dplyr) pheoUse=na.omit(allData[,c("Station","chl","pheo","doy","date_dec")]) pheoPred=predict(gamP,pheoUse,type="response") pheoUse$resid=(pheoUse$chl-pheoPred)^2 byStation<-group_by(pheoUse,Station) rmsePerStation<-summarise(byStation,stp1=sum(resid),count=n()) rmsePheo=sqrt(as.vector(rmsePerStation$stp1)/rmsePerStation$count) tnUse=na.omit(allData[,c("Station","chl","tn","doy","date_dec")]) tnPred=predict(gamP3,tnUse,type="response") tnUse$resid=(tnUse$chl-tnPred)^2 byStation<-group_by(tnUse,Station) rmsePerStation<-summarise(byStation,stp1=sum(resid),count=n()) rmseTn=sqrt(as.vector(rmsePerStation$stp1)/rmsePerStation$count) cbind(rmsePheo,rmseTn) cbind(rmsePheo, rmseTn, testMerge3$rmse3) ## from comparingSpatialModelsMaps
f4c4b869a0c8de3f360691b884f7dff9ea92c1e3
09da2ae43b503129139904784ed901eca961258f
/plot4.R
336a95f28a6f9c7de259d73defd14b9fad416f28
[]
no_license
sanori/ExData_Plotting1
451e2970e7e907ff86f479d47c3d86f797412c6a
f850a037f1c91574e584a69eda3cb4f771b425a8
refs/heads/master
2020-12-25T17:38:11.898809
2015-03-08T20:15:10
2015-03-08T20:15:10
31,612,724
0
0
null
2015-03-03T17:57:04
2015-03-03T17:57:04
null
UTF-8
R
false
false
1,163
r
plot4.R
# Draw all the trends x <- read.table("household_power_consumption.txt", sep=";", header=TRUE, skip=66636, nrows=2*24*60) names(x) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3") x$datetime <- strptime(paste(x$Date, x$Time), format="%d/%m/%Y %H:%M:%S", tz="EST") Sys.setlocale("LC_TIME", "C") # Remove localization of weekday names png(filename = "plot4.png", width= 480, height = 480, bg=NA) par(mfrow = c(2, 2)) with(x, { plot(datetime, Global_active_power, type = "l", xlab = "", ylab = "Global Active Power") plot(datetime, Voltage, type = "l") plot(datetime, Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering") lines(datetime, Sub_metering_2, col = "red") lines(datetime, Sub_metering_3, col = "blue") legend("topright", lty = c(1,1,1), col=c("black", "red", "blue"), bty="n", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) plot(datetime, Global_reactive_power, type = "l") }) dev.off()
aaab2b6b7131d5c566d782cb3d18ff90242971c2
16d914ffe72e4efbc65a851ba3e755650a618adc
/analysis_scripts_frontiers/Statistics/stats/pairwise.t.test.with.t.and.df.R
26e2b29d2ceb9e65d0b599c35d7a498d0249432e
[ "MIT" ]
permissive
lkorczowski/rASRMatlab
cc38a9607f9666cca08be693d0161b4f9e515a8b
594a57bba587ed3149f11db063c9414fabd92569
refs/heads/master
2020-09-14T00:04:17.048642
2020-01-20T10:51:56
2020-01-20T10:51:56
222,947,393
0
0
NOASSERTION
2019-11-20T13:46:46
2019-11-20T13:46:46
null
UTF-8
R
false
false
3,761
r
pairwise.t.test.with.t.and.df.R
pairwise.t.test.with.t.and.df <- function (x, g, p.adjust.method = p.adjust.methods, pool.sd = !paired, paired = FALSE, alternative = c("two.sided", "less", "greater"), ...) { if (paired & pool.sd) stop("pooling of SD is incompatible with paired tests") DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(g))) g <- factor(g) p.adjust.method <- match.arg(p.adjust.method) alternative <- match.arg(alternative) if (pool.sd) { METHOD <- "t tests with pooled SD" xbar <- tapply(x, g, mean, na.rm = TRUE) s <- tapply(x, g, sd, na.rm = TRUE) n <- tapply(!is.na(x), g, sum) degf <- n - 1 total.degf <- sum(degf) pooled.sd <- sqrt(sum(s^2 * degf)/total.degf) compare.levels <- function(i, j) { dif <- xbar[i] - xbar[j] se.dif <- pooled.sd * sqrt(1/n[i] + 1/n[j]) t.val <- dif/se.dif if (alternative == "two.sided") 2 * pt(-abs(t.val), total.degf) else pt(t.val, total.degf, lower.tail = (alternative == "less")) } compare.levels.t <- function(i, j) { dif <- xbar[i] - xbar[j] se.dif <- pooled.sd * sqrt(1/n[i] + 1/n[j]) t.val = dif/se.dif t.val } } else { METHOD <- if (paired) "paired t tests" else "t tests with non-pooled SD" compare.levels <- function(i, j) { xi <- x[as.integer(g) == i] xj <- x[as.integer(g) == j] t.test(xi, xj, paired = paired, alternative = alternative, ...)$p.value } compare.levels.t <- function(i, j) { xi <- x[as.integer(g) == i] xj <- x[as.integer(g) == j] t.test(xi, xj, paired = paired, alternative = alternative, ...)$statistic } compare.levels.df <- function(i, j) { xi <- x[as.integer(g) == i] xj <- x[as.integer(g) == j] t.test(xi, xj, paired = paired, alternative = alternative, ...)$parameter } } PVAL <- pairwise.table(compare.levels, levels(g), p.adjust.method) TVAL <- pairwise.table.t(compare.levels.t, levels(g), p.adjust.method) if (pool.sd) DF <- total.degf else DF <- pairwise.table.t(compare.levels.df, levels(g), p.adjust.method) ans <- list(method = METHOD, data.name = DNAME, p.value = PVAL, p.adjust.method = p.adjust.method, t.value = TVAL, dfs = DF) class(ans) <- "pairwise.htest" ans } pairwise.table.t <- function (compare.levels.t, level.names, p.adjust.method) { ix <- setNames(seq_along(level.names), level.names) pp <- outer(ix[-1L], ix[-length(ix)], function(ivec, jvec) sapply(seq_along(ivec), function(k) { i <- ivec[k] j <- jvec[k] if (i > j) compare.levels.t(i, j) else NA })) pp[lower.tri(pp, TRUE)] <- pp[lower.tri(pp, TRUE)] pp }
37c53b5e6dec7abe93529b65eb662d68b9cf5229
085bb668985c3302bd1f6c6a43cb50c49bf582c4
/Data Matcher/temp.R
38e57b29f69ff5683ee00a07e869a030058b002a
[]
no_license
zmyao88/Nigeria_Codes
00cf9eac7403522a1f80945bb7676ac481447736
bddb363eb4a66ffdc68787764a48d94fe786aee9
refs/heads/master
2016-09-06T14:38:31.442986
2013-06-13T16:23:33
2013-06-13T16:23:33
null
0
0
null
null
null
null
UTF-8
R
false
false
1,238
r
temp.R
l <- letters set.seed(1) x1 <- l[sample(1:26, 81877, replace=T)] x2 <- l[sample(1:26, 81877, replace=T)] x3 <- l[sample(1:26, 81877, replace=T)] x4 <- l[sample(1:26, 81877, replace=T)] x5 <- l[sample(1:26, 81877, replace=T)] facility_list$random_id <- paste0(x1, x2, x3, x4, x5) t2 <- arrange(facility_list, lga_id, end) t2 <- ddply(t2, .(t2[,"lga_id"]), transform, tmp2 = paste0("A", as.character(1:length(tmp)))) id_generate <- function(df, lga_col = "lga_id", submit_end_col = "end", header = "F") { l <- letters set.seed(1) x1 <- l[sample(1:26, dim(df)[1], replace=T)] x2 <- l[sample(1:26, dim(df)[1], replace=T)] x3 <- l[sample(1:26, dim(df)[1], replace=T)] x4 <- l[sample(1:26, dim(df)[1], replace=T)] x5 <- l[sample(1:26, dim(df)[1], replace=T)] df <- arrange(df, df[, lga_col], df[, submit_end_col]) df <- ddply(df, .(df[,lga_col]), transform, seq_id = paste0(header, as.character(1:length(df[,lga_col])))) df$random_id <- paste0(x1, x2, x3, x4, x5) return(df) } t <- ddply(facility_list, .(lga_id), summarise, unique_short_id = length(unique(tmp)), n_fac = length(tmp)) which(t$unique_short_id != t$n_fac)
53a59754a23ab1c66d7e1473dbaeca4e81941298
609e12295b740d904c45896444e71c7c40215c8e
/R/assignRefugiaFromAbundanceRaster.r
01e30746a5224d3f9a24932d7c4530ed8e88dcdc
[]
no_license
stranda/holoSimCell
a7f68cec17f0c9f599b94fb08344819de40ecd2e
f1570c73345c1369ed3bf3aad01a404c1c5ab3a2
refs/heads/master
2023-08-20T09:08:13.503681
2023-07-20T19:09:41
2023-07-20T19:09:41
189,275,434
1
2
null
2021-03-19T19:32:01
2019-05-29T18:08:16
R
UTF-8
R
false
false
12,969
r
assignRefugiaFromAbundanceRaster.r
#' Rescale carrying capacity rasters and assign refugia #' #' This function takes an "abundance" raster (i.e., from an ENM or from a pollen surface) and identifies refugia and starting (relative) abundances for each refugium. It rescales this to the extent and resolution of a "simulation" raster which typically has coarser spatial resolution than the abundance raster. It then generates a vector of cell IDs that correspond to refugia cells and calculates the average relative abundance across refugial cells. #' #' @param abund Abundance raster. #' @param sim Simulation raster. #' @param threshold Numeric. Value at which to threshold the abundance raster. Values that fall above this threshold will be assumed to represent a refuge and values below will be assumed to be outside (i.e., zero abundance). #' #' @details #' This function rescales abundances obtained from the abundance raster to a new spatial resolution and extent used for demographic simulations. Since the demographic simulation raster often has cells that are larger than the cells in the abundance raster, it cannot faithfully retain abundances or even all unique refugia identified in the abundance raster. The procedure first thresholds the abundance raster using a user-defined value above which it is assumed a cell was inside a refuge and below which it was assumed to be outside any refuge (zero abundance). A unique "abundId" raster is then created by assigning a unique integer number for each block of contiguous cells (using Moore neighborhood adjacency). This raster is then resampled to the resolution used by the simulation raster. The renumbering is redone so that cells that refugial were not adjacent at the original resolution but are in the new resolution are assigned to the same refuge. \cr #' Then, a "simAbund" raster is created with the same extent and resolution as the simulation raster. For each each cell in this raster, the function determines if it contains at least one cell in the "abundId" raster that is assigned to a refuge. The challenge here is that a single "simAbund" cell can contain cells that are assigned to multiple refugia in the "abundId" raster, and that "simAbund" cell can also include cells that have abundances that are assigned to no refugia in the abundance raster. Thus, if we simply assigned abundances to the "simAbund" cell by resampling the abundance raster, we would in some cases be too generous because a single "simAbund" cell can include cells that do not belong to this refuge. \cr #' The procedure assigns abundances by first calculating a proportionality scalar where the numerator is the sum of abundances of abundance raster cells in this refugium and in the "simAbund" cell, and the denominator the sum of all abundances of all cells in this "simAbund" cell. The abundance assigned to this "simAbund" cell for this particular refugium is this scalar times the abundance from the resampling of the abundance raster to the extent/resolution of the simulation raster. Thus, abundances assigned to any particular cell in a refuge will be equal to or less than the abundance of the resampled values. \cr #' The procedure then assigns each cell an integer number identifying which refugium to belongs to and an abundance corresponding to the given refuge. When cells contain more than one "abundId" refuge cell, the refuge with the greater abundance is assigned to the cell. As a consequence, a refuge that appears in the "abundId" raster could be trimmed in extent or even eliminated if it is only represented by a few cells that have small abundances relative to a more "massive" refugium in the same cell. Also, as a result, it is possible to have distinct refugia in cells that are adjacent to one another when rescaled to the extent/resolution of the simulation raster but are spatially distinct at the scale of the abundance raster. #' @return #' \itemize{ #' A list with: #' \item{1) A raster stack representing refuge ID numbers and abundances at the \emph{simulation} resolution and extent} #' \item{2) a vector of cell numbers for refugial cells at the \emph{simulation} scale} #' \item{3) a single numeric value representing mean refugial abundance across cells at the \emph{simulation} extent.} #' } #' #' @examples #' library(raster) #' abund <- brick(system.file("extdata/rasters/ccsm_160kmExtent_maxent.tif", package = "holoSimCell")) #' abund <- abund[[1]] #' #' load(file=paste0(system.file(package="holoSimCell"),"/extdata/landscapes/",pollenPulls[[1]]$file)) #' sim <- landscape$sumrast #' #' threshold <- 0.6 #' refs <- assignRefugiaFromAbundanceRaster(abund, sim, threshold) #' #' cols <- c('red', 'orange', 'yellow', 'green', 'blue', 'purple', 'gray', #' 'chartreuse', 'darkgreen', 'cornflowerblue', 'goldenrod3', 'black', #' 'steelblue3', 'forestgreen', 'pink', 'cyan', 'darkred') #' #' par(mfrow=c(1, 2)) #' #' col <- cols[1:maxValue(refs$sim[['refugiaId']])] #' plot(refs$simulationScale[['refugiaId']], col=col, main='refuge ID') #' plot(refs$simulationScale[['refugiaAbund']], main='refuge abundance') #' #' @seealso \code{\link{getpophist2.cells}}, \code{\link[raster]{calc}}, \code{\link[raster]{resample}} #' #' @export assignRefugiaFromAbundanceRaster <- function( abund, sim, threshold ) { # ### abundance raster # ###################### # # create data frame for abundance raster with: # # cell number in abundance frame # # long, lat # # a mask of refugia # # ID number of each refuge # # abundance (abundance) # # cell number in simulation raster # # "abundance" # names(abund) <- 'origAbund' # # mask refugia # origMask <- abund >= threshold # names(origMask) <- 'origMask' # # identify refugia # idsOrig <- raster::clump(origMask, directions=8, gaps=FALSE) # names(idsOrig) <- 'idOrig' # # abundance in refugial cells # abundRefugeAbund <- abund * origMask # names(abundRefugeAbund) <- 'abundOrigRefuge' # # long/lat # ll <- enmSdm::longLatRasters(abund) # # re-assess ID number based on resolution of simulation raster # idsSim <- raster::resample(idsOrig, sim) # idsSim <- raster::clump(idsSim, directions=8, gaps=FALSE) # idsSim <- raster::extract(idsSim, raster::as.data.frame(ll)) # numRefugia <- max(idsSim, na.rm=TRUE) # # cell numbers # cellsAbund <- raster::setValues(abund, 1:raster::ncell(abund)) # names(cellsAbund) <- 'cellNumOrig' # suitStack <- raster::stack(cellsAbund, ll, origMask, idsOrig, abund, abundRefugeAbund) # suitFrame <- as.data.frame(suitStack) # suitFrame$idSim <- idsSim # # cell numbers of simulation raster in the layout used by the demo/genetic simulations: # # cell in lower left is 1, to its right is 2, etc, then wraps to next row so cell [nrow - 1, 1] is next in line # nrows <- nrow(sim) # ncols <- ncol(sim) # ncells <- raster::ncell(sim) # v <- rep(seq(nrows * (ncols - 1) - 1, 1, by=-ncols), each=ncols) + 0:(ncols - 1) # cellNumSim <- matrix(v, nrow=nrows, ncol=ncols, byrow=TRUE) # cellNumSim <- raster::raster(cellNumSim, template=sim) # suitFrame$cellNumSim <- raster::extract(cellNumSim, suitFrame[ , c('longitude', 'latitude')]) # ### simulation raster # ##################### # # create data frame with: # # simulation raster cell number # # abundance resampled from abundance raster # # sum of abundances of cells from abundance raster, by refuge ID # # refuge ID # # rescaled abundances (to match resampled abundances) for the refuge to which this cell is assigned accounting for: # # * empty cells (outside a refuge in the abundance raster but with non-NA values) # # * abundance cells that fall into other refugia (should not be counted toward this cell's abundance) # # "abundance" # abundSim <- raster::resample(abund, sim) # names(abundSim) <- 'abundSim' # # cell numbers # cellsSim <- raster::setValues(sim, 1:raster::ncell(sim)) # names(cellsSim) <- 'cellNumSim' # simStack <- raster::stack(cellsSim, abundSim) # simFrame <- as.data.frame(simStack) # ### calculate abundances in simulation raster for each refuge # for (countRefuge in 1:numRefugia) { # simFrame$DUMMY <- NA # names(simFrame)[ncol(simFrame)] <- paste0('refuge', countRefuge) # suitFrameOutsideRefuge <- suitFrame[!is.na(suitFrame$origAbund) & (is.na(suitFrame$idSim) | omnibus::naCompare('!=', suitFrame$idSim, countRefuge)), ] # suitFrameInsideRefuge <- suitFrame[omnibus::naCompare('==', suitFrame$idSim, countRefuge), ] # # assign scaled abundances to each simulation raster cell in this refuge # # For each simulation cell that overlaps with at least one cell in the abundance raster assigned to a particular refuge, find: # # * a proportionality factor as a proportion of the sum of suitabilities in the abundance raster cells in this refuge divided by the sum of all suitabilities in all cells that fall into this simulation raster cell (regardless of whether they're in a refuge or not) # # * the resampled abundance (resampling the abundance raster to the simulation raster) # # Final abundance in this cell for a particular refuge refuge is the product of these two values. # simCellsInRefuge <- sort(unique(suitFrameInsideRefuge$cellNumSim)) # for (simCell in simCellsInRefuge) { # simCellInterpAbund <- simFrame$abundSim[simFrame$cellNumSim == simCell] # abundInSimCellOutsideRefuge <- suitFrameOutsideRefuge$origAbund[suitFrameOutsideRefuge$cellNumSim == simCell] # abundInSimCellInsideRefuge <- suitFrameInsideRefuge$origAbund[suitFrameInsideRefuge$cellNumSim == simCell] # if (length(abundInSimCellOutsideRefuge) == 0) { # simAbund <- simCellInterpAbund # } else { # insideAbund <- sum(abundInSimCellInsideRefuge) # outsideAbund <- sum(abundInSimCellOutsideRefuge) # totalAbund <- insideAbund + outsideAbund # simAbund <- simCellInterpAbund * (insideAbund / totalAbund) # } # simFrame[simFrame$cellNumSim == simCell, paste0('refuge', countRefuge)] <- simAbund # } # next simulation raster cell # } # next refuge # ### assign refuge ID and abundance # simIdsList <- apply(simFrame[ , paste0('refuge', 1:numRefugia), drop=FALSE], 1, which.max) # simFrame$id <- NA # for (i in seq_along(simIdsList)) simFrame$id[i] <- ifelse(length(simIdsList[[i]]) == 0, NA, simIdsList[[i]]) # simFrame$refugeAbund <- NA # for (countRefuge in 1:numRefugia) { # refugeIndex <- which(omnibus::naCompare('==', simFrame$id, countRefuge)) # simFrame$refugeAbund[refugeIndex] <- simFrame[refugeIndex, paste0('refuge', countRefuge)] # } # # set values of ID and abundance rasters # idsSimRast <- abundSim <- NA * sim # idsSimRast <- raster::setValues(idsSimRast, simFrame$id) # abundSim <- raster::setValues(abundSim, simFrame$refugeAbund) # # flip up/down because we've renumbered simulation raster cell numbers as per demographic/genetic simulations # idsSimRast <- raster::as.matrix(idsSimRast) # abundSim <- raster::as.matrix(abundSim) # idsSimRast <- idsSimRast[nrows:1, ] # abundSim <- abundSim[nrows:1, ] # idsSimRast <- raster::raster(idsSimRast, template=sim) # abundSim <- raster::raster(abundSim, template=sim) # names(idsSimRast) <- 'id' # names(abundSim) <- 'abundance' # # cell numbers: renumber so bottom left is (1, 1), increments to the right, then wraps around to next row up # refugeCellIds <- simFrame$cellNumSim[which(!is.na(simFrame$refugeAbund))] # gets "raster" cell numbers # # mean abundance in all refugia # meanRefugeAbund <- raster::cellStats(abundSim, 'mean') # rescale origRefugia <- abund >= threshold origRefugiaAbund <- abund * origRefugia simAbund <- raster::resample(origRefugiaAbund, sim) simAbund <- raster::calc(simAbund, fun=function(x) ifelse(x > 1, 1, x)) simAbund <- raster::calc(simAbund, fun=function(x) ifelse(x < 0, 0, x)) # identify refugia simRefugia <- simAbund >= threshold simRefugiaId <- raster::clump(simRefugia, directions=8, gaps=FALSE) names(simRefugiaId) <- 'refugiaId' # calculate abundance in refugia simAbund <- simAbund * simRefugia names(simAbund) <- 'refugiaAbund' # refuge cell IDs # cell in lower left is 1, to its right is 2, etc, then wraps to next row so cell [nrow - 1, 1] is next in line nrows <- nrow(sim) ncols <- ncol(sim) ncells <- raster::ncell(sim) v <- rep(seq(nrows * (ncols - 1) - 1, 1, by=-ncols), each=ncols) + 0:(ncols - 1) cellNumSim <- matrix(v, nrow=nrows, ncol=ncols, byrow=TRUE) cellNumSim <- raster::raster(cellNumSim, template=sim) cellNumSim <- as.vector(cellNumSim) simRefugiaBinary <- as.vector(simRefugia) refugeCellNum <- cellNumSim[simRefugiaBinary] if (any(is.na(refugeCellNum))) refugeCellNum <- refugeCellNum[!is.na(refugeCellNum)] # mean refuge abundance meanRefugeAbund <- raster::cellStats(simAbund, 'sum') / length(refugeCellNum) out <- list( simulationScale = raster::stack(simRefugiaId, simAbund), refugeCellNum = refugeCellNum, meanRefugeAbund = meanRefugeAbund ) out }
1dbb3b66a7dfcf2eccba4819fa79c8da9654cc9c
508bae0c1b6e8b9bc6817eebfa135667b58db1d4
/Code File.R
c46675e38dc5d7da4d294ce0479da27dfbb92a36
[]
no_license
dcohron/RepData_PeerAssessment1
4588f91e8f06ddef99e4114b6b3e1a4512773909
99c46cacaaef8b5fb6c1da56f334d9388750168b
refs/heads/master
2020-12-11T07:32:33.973541
2016-01-15T13:09:12
2016-01-15T13:09:12
49,222,540
0
0
null
2016-01-07T18:29:57
2016-01-07T18:29:56
null
UTF-8
R
false
false
5,321
r
Code File.R
# Course Project #1 # Reproducible Research # globallye suppress warnings oldwarn<- getOption("warn") options(warn = -1) # install libraries/packages library(plyr) library(dplyr) library(tidyr) library(data.table) library(lubridate) # read file into data frame for manipulation file<- "activity.csv" main<- read.csv(file) # refactor raw date to type date main<- mutate(main, date=as.Date(as.character(main$date))) # group by days to get sum of steps per day # ignore days with no steps recorded stepsbyday<- group_by(main, date) %>% summarize_each(funs(sum)) na.omit(stepsbyday) #calculate mean and median of number of steps per day meansteps<-mean(stepsbyday$steps, na.rm=TRUE) mediansteps<- median(stepsbyday$steps, na.rm=TRUE) # plot histogram hist(stepsbyday$steps, main = "Steps per Day", xlab = "Sum of steps taken per day", ylab = "Number of days at that number of daily steps", xlim = c(0, 25000), ylim = c(0, 30)) abline(v = meansteps, col = "blue", lwd=4) abline(v = mediansteps, col = "red", lwd=2) legend('topright', c("mean", "median"), col=c("blue", "red"), lwd=3) # group by 5 minute interval # ignore intervals with no steps recorded stepsbyinterval<- group_by(main, interval) %>% summarize_each(funs(mean(., na.rm=TRUE))) # plot time series of 5 minute interval average steps with(stepsbyinterval, plot(interval, steps, type = "l", main = "Average Number of Steps Throughout the Day", xlab = "5 Minute Interval (midnight to midnight)", ylab = "Mean Number of Steps", xlim = c(0, 2400), ylim = c(0, 235))) # calculate which 5 minute interval has highest average number of steps maxintervalrow<- which.max(stepsbyinterval$steps) maxinterval<- stepsbyinterval$interval[maxintervalrow] # calculate the number of rows with missing (NA) data numrowtotal<- nrow(main) numrownona<- nrow(na.omit(main)) numrowwithna<- numrowtotal - numrownona # impute missing values and replace with interval mean impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE)) mainimputed <- ddply(main, ~ interval, transform, steps = impute.mean(steps)) # group new data frame by days to get sum of steps per day # all days/intervals have steps recorded stepsbyday2<- group_by(mainimputed, date) %>% summarize_each(funs(sum)) # calculate mean and median of number of steps per day meansteps2<-mean(stepsbyday2$steps) mediansteps2<- median(stepsbyday2$steps) # plot histogram on imputed data hist(stepsbyday2$steps, main = "Steps per Day", xlab = "Sum of steps taken per day", ylab = "Number of days at that number of daily steps", xlim = c(0, 25000), ylim = c(0, 40)) abline(v = meansteps2, col = "blue", lwd=4) abline(v = mediansteps2, col = "red", lwd=2) legend('topright', c("mean", "median"), col=c("blue", "red"), lwd=3) # add columns showing day of the week stepsbyday3<- mutate(mainimputed, dayofweek = weekdays(date, abbreviate=TRUE)) # add column with logical vector as to weekday/weekend stepsbyday3<- mutate(stepsbyday3, weekend = (dayofweek == "Sun" | dayofweek == "Sat")) # subset for weekday and weekend in new data frames weekdaysteps<- subset(stepsbyday3, !weekend) weekendsteps<- subset(stepsbyday3, weekend) # convert logical vector to factors with labels # Note: I did not need to do this for my analysis, # but it was a requirement of the project stepsbyday3$weekend<-factor(stepsbyday3$weekend,levels=c(FALSE, TRUE), labels=c('Weekday', 'Weekend')) #group by date weekdaystepsum<- group_by(weekdaysteps, date) %>% summarize_each(funs(sum(steps))) weekendstepsum<- group_by(weekendsteps, date) %>% summarize_each(funs(sum(steps))) # calculate mean and median of number of steps per day meanstepsweekday<-mean(weekdaystepsum$steps) medianstepsweekend<- median(weekendstepsum$steps) # group by 5 minute interval # ignore intervals with no steps recorded weekdaystepsbyinterval<- group_by(weekdaysteps, interval) %>% summarize_each(funs(mean(., na.rm=TRUE))) weekendstepsbyinterval<- group_by(weekendsteps, interval) %>% summarize_each(funs(mean(., na.rm=TRUE))) # plot time series of 5 minute interval average steps for weekday and weekends par(mfrow = c(2,1), height = 500) with(weekdaystepsbyinterval, plot(interval, steps, type = "l", main = "Average Number of Steps on Average Weekday", xlab = "5 Minute Interval (midnight to midnight)", ylab = "Mean Number of Steps", xlim = c(0, 2400), ylim = c(0, 235))) with(weekendstepsbyinterval, plot(interval, steps, type = "l", main = "Average Number of Steps on Average Weekend Day", xlab = "5 Minute Interval (midnight to midnight)", ylab = "Mean Number of Steps", xlim = c(0, 2400), ylim = c(0, 235))) # restore warnings options(warn = oldwarn)
74d4e855c62dd898c74af1ca64759ecfecb33790
9fecce6f3ef41202cdcc855f4b0baff36131eacc
/Analysis/new_analysis/catch_shares/Analysis/01_create_vessel_df.R
7cbd7f68d19d1a37214cc9ba3d40f49d647e456b
[]
no_license
emfuller/cnh
0487e9647837d8fc999850b5951ff6331f9a5159
8b36faf8c73607d92e59e392fff3c0094b389d26
refs/heads/master
2021-05-01T08:02:52.200343
2019-04-06T18:25:48
2019-04-06T18:25:48
28,717,834
0
0
null
null
null
null
UTF-8
R
false
false
1,415
r
01_create_vessel_df.R
# create vessel level landings data create_vessel_landings <- function(minrev){ library(dplyr) dat <- readRDS("processedData/catch/1_cleaningData/tickets.RDS") # vessels should have less than min_rev on average across 5 years AND # flagg landings before and after catch shares # then drop 2011 data # also drop any ZZZ drvids # and drop non-commercial landings (pargrp = C and removal type in C, D) min_rev = 5000 # find minimum revenue and whether vessel present in both periods div_dat <- dat %>% filter(drvid != "NONE", year > 2008, year < 2014) %>% group_by(drvid, year) %>% summarize(annual_revenue = sum(adj_revenue, na.rm = T)) %>% # calculate yr rev mutate(av.annual.rev = mean(annual_revenue, na.rm = T)) %>% # mean yr rev filter(av.annual.rev >= min_rev) %>% # drop vessels with < min_rev filter(year != 2011) %>% group_by(drvid) %>% summarize(both.periods = ifelse(any(year %in% c(2009:2010)) & any(year %in% c(2012:2013)), 1, 0)) # drop 2015 landings, not complete div_landings <- subset(dat, drvid %in% unique(div_dat$drvid) & year < 2014 & year!=2011 & year > 2008) %>% left_join(div_dat, by = 'drvid') saveRDS(div_landings, file="Analysis/new_analysis/catch_shares/Analysis/vessel_landings_data.RDS") return(div_landings) }
4c76339411cb4552987d516c04c141bb3cc0a909
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/letsR/examples/plot.PresenceAbsence.Rd.R
504c007757d0523dc86f08f1fc4b36534c7e00d8
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
407
r
plot.PresenceAbsence.Rd.R
library(letsR) ### Name: plot.PresenceAbsence ### Title: Plot an object of class PresenceAbsence ### Aliases: plot.PresenceAbsence ### ** Examples ## Not run: ##D data(PAM) ##D plot(PAM) ##D plot(PAM, xlab = "Longitude", ylab = "Latitude", ##D main = "Phyllomedusa species richness") ##D plot(PAM, name = "Phyllomedusa atelopoides") ##D plot(PAM, name = "Phyllomedusa azurea") ## End(Not run)
7cfaa73b396204499f05f9109376d842dbe8da9f
f079415f68017da59b404ad532a9214b86949dad
/inst/app/server.R
72b960f1e7a3dbd7086e7680e74c08b1ef673ab2
[]
no_license
mpeeples2008/NAA_analytical_dashboard
8094dfcd4c1487d28ac4bdb60ccf21ceb4881004
15241447a45a533ebd8b7c5da05fdf47f785be25
refs/heads/master
2023-03-17T16:05:27.400357
2023-03-09T17:48:05
2023-03-09T17:48:05
137,390,525
6
1
null
2018-09-13T00:28:53
2018-06-14T17:47:20
R
UTF-8
R
false
false
774
r
server.R
#' server.R library(ArchaeoDash) library(shiny) shinyServer(function(input, output, session) { #### create reactive values #### # rvals = reactiveValues() ## for testing rvals <<- reactiveValues(); showNotification("warning: global variable is only for testing") input <<- input #### Import data #### dataInputServer(input,output,session,rvals) #### Impute & Transform #### imputeTransformServer(input,output,session,rvals) #### Ordination #### ordinationServer(input,output,session,rvals) #### Cluster #### clusterServer(input,output,session,rvals) #### Visualize & Assign #### visualizeAssignServer(input,output,session,rvals) #### Save & Export #### saveExportServer(input,output,session,rvals) }) # end server
e9e123d808793cb897a4caf57c2a032063721a61
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/alakazam/man/bulk.Rd
4d7d5b46a3467adbd1eed01c235ff78903a3a114
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
true
1,445
rd
bulk.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AminoAcids.R \name{bulk} \alias{bulk} \title{Calculates the average bulkiness of amino acid sequences} \usage{ bulk(seq, bulkiness = NULL) } \arguments{ \item{seq}{vector of strings containing amino acid sequences.} \item{bulkiness}{named numerical vector defining bulkiness scores for each amino acid, where names are single-letter amino acid character codes. If \code{NULL}, then the Zimmerman et al, 1968 scale is used.} } \value{ A vector of bulkiness scores for the sequence(s). } \description{ \code{bulk} calculates the average bulkiness score of amino acid sequences. Non-informative positions are excluded, where non-informative is defined as any character in \code{c("X", "-", ".", "*")}. } \examples{ # Default bulkiness scale seq <- c("CARDRSTPWRRGIASTTVRTSW", "XXTQMYVRT") bulk(seq) # Use the Grantham, 1974 side chain volumn scores from the seqinr package library(seqinr) data(aaindex) x <- aaindex[["GRAR740103"]]$I # Rename the score vector to use single-letter codes names(x) <- translateStrings(names(x), ABBREV_AA) # Calculate average volume bulk(seq, bulkiness=x) } \references{ \enumerate{ \item Zimmerman JM, Eliezer N, Simha R. The characterization of amino acid sequences in proteins by statistical methods. J Theor Biol 21, 170-201 (1968). } } \seealso{ For additional size related indices see \link[seqinr]{aaindex}. }
b447a047fad764db2df5c8e39d3b0be2670d42e6
a841b5ffb7caaee2ddfbc05ec6dd4953d4f8f29c
/newIS_dootika.R
0a7dcaf85a236825b7e301ce2f61ab0ea08fdab0
[]
no_license
uttiyamaji/SVE
921c625ea145b34f07aaa2dac410fa1ec7e68aa4
45102a3e983f622d2bd75e532570e3b9b9fca1c9
refs/heads/master
2021-03-20T16:23:58.018375
2020-05-08T15:03:56
2020-05-08T15:03:56
247,218,669
0
0
null
2020-03-14T12:35:45
2020-03-14T05:36:59
C++
UTF-8
R
false
false
1,793
r
newIS_dootika.R
library(mcmc) HAC1 <- function (mcond , m ) { require ( fftwtools ) dimmcond <- dim( mcond ) Nlen <- dimmcond [1] qlen <- dimmcond [2] ww <- weight(m,Nlen) ww <- c(1, ww [1:( Nlen -1)], 0, ww [( Nlen -1) :1]) ww <- Re( fftw (ww)) FF <- rbind (mcond , matrix (0, Nlen , qlen )) FF <- (mvfftw (FF)) FF <- FF * matrix ( rep(ww , qlen ), ncol = qlen ) FF <- Re( mvfftw (FF , inverse = TRUE )) / (2* Nlen ) FF <- FF [1: Nlen ,] return ((t( mcond ) %*% FF) / Nlen ) } weight = function(m, dimN){ w = numeric(dimN) w[1:(2*m+1)] = 1 return (w) } initseq_new = function(foo) { truncs <- apply(foo, 2, function(t) length(initseq(t)[[2]]) -1) print(truncs) chosen <- min(truncs) sig <- HAC1(foo, chosen) # for(m in 0:(n/2)){ # sig = HAC1(foo, m) # if(!(any(eigen(sig)$values <= 0))){ # sn = m # break # } # if(sn > (n/2 - 1)){ # stop("Not enough samples") # } # } # Dtm = det(sig) # for(m in (sn+1):(n/2)){ # sig1 = HAC1(foo, m) # dtm = det(sig1) # if(dtm <= Dtm[m-sn]) # break # Dtm = c(Dtm, dtm) # sig = sig1 # } return(list("Sig" = sig, "trunc" = chosen) ) } library(Rcpp) library(rbenchmark) library(mAr) sourceCpp("inseq.cpp") p <- 5 n <- 1e4 omega <- 5*diag(1,p) ## Making correlation matrix var(1) model foo <- matrix(rnorm(p^2, sd = 1), nrow = p) foo <- foo %*% t(foo) phi <- foo / (max(eigen(foo)$values) + 1) foo <- scale(as.matrix(mAr.sim(rep(0,p), phi, omega, N = n)), scale = F) a = initseq_new(foo) b = inseq(foo) c(a$trunc, b$trunc) c(det(a$Sig), det(b$Sig))^(1/p) all.equal(a$Sig,b$Sig) benchmark(initseq_new(foo),inseq(foo), replications = 2) library(lineprof) library(mcmcse) lineprof(mcse.initseq(foo)) lineprof(initseq_new(foo))
8edfca92318c25d97bf6752e4b5e834da903baf5
b228e595fb3bf49e550329d20c0fdc18e5ebd476
/R/docMatrix2.R
e4886b53e430915377315670b8ca6b1e0347ef56
[]
no_license
IshidaMotohiro/RMeCab
ab0e8a6c3be2b0be1057f8a5eb4410c63bc62075
365af330092b77c61d7395320af0df205e2901ad
refs/heads/master
2022-11-06T16:20:34.109663
2022-10-18T08:07:54
2022-10-18T08:07:54
28,012,861
29
15
null
2022-10-15T06:46:30
2014-12-15T00:03:22
C++
UTF-8
R
false
false
3,991
r
docMatrix2.R
## sym = 0, pos = c("名詞", "形容詞"),kigo = "記号", docMatrix2 <- function( directory, pos = "Default" , minFreq = 1, weight = "no", kigo = 0, co = 0, dic = "" , mecabrc = "", etc = "" ) { # posN <- length(pos) # gc() if(any(suppressWarnings(dir(directory) ) > 0)){ ft <- 1 ##ディレクトリが指定された file <- dir(directory) } else if (file.exists(directory)){ ft <- 0 # 単独ファイル file <- basename(directory) directory <- dirname(directory) } else{ stop("specify directory or a file!") } fileN = length(file) if(any( pos == "" | is.na(pos)) ){ stop("specify pos argument!") } if( length(pos) == 1 && pos == "Default" ){ posN <- 0 }else{ posN <- length(pos) } ## if( posN < 1){ ## stop("specify pos argument") ## } else if("記号" %in% pos){ ## sym = 1 # 記号を頻度に含めて出力する ## } if( is.null(dic) || is.na(dic)){ dic = "" } else if( (xl <- nchar(dic)) > 0 ) { dic <- paste(dirname(dic), basename(dic), sep = "/") if ( !(file.exists(dic)) ) { cat ("specified dictionary file not found; result by default dictionary.\n")# dic = "" } else { dic <- paste(" -u", dic) } } # if( is.null(mecabrc) || is.na(mecabrc) || (nchar(mecabrc)) < 2 ){ mecabrc = "" } else { mecabrc <- paste(dirname(mecabrc), basename(mecabrc), sep = "/") if ( !(file.exists(mecabrc)) ) { cat ("specified mecabrc not found; result by default mecabrc.\n") mecabrc = "" } else { mecabrc <- paste("-r", mecabrc) } } # opt <- paste(dic, mecabrc, etc) if(minFreq < 1){ stop("minFreq argument must be equal to or larger than 1!") } dtm <- .Call("docMatrix2", as.character(directory), as.character(file), as.numeric(fileN), as.numeric(ft), as.character(pos), as.numeric(posN), as.numeric(minFreq), as.numeric(kigo), as.character(opt), PACKAGE="RMeCab")## as.numeric(sym), as.character(kigo), if(is.null(dtm)){ stop("chage the value of minFreq argument!") } dtm <- t(dtm) # environment(dtm) = new.env() ## ## class(dtm) <- "RMeCabMatrix" if(co == 1 || co == 2 || co == 3){ dtm <- coOccurrence( removeInfo (dtm), co) ## invisidoble(dtm) } ## ######### < 2008 05 04 uncommented> if(weight == ""){ ## invisible( dtm) ## break }else{ argW <- unlist(strsplit(weight, "*", fixed = T)) for(i in 1:length(argW)){ if(argW[i] == "no"){ invisible( dtm) ## cat("Term Document Matrix includes 2 information rows!", "\n") ## cat("whose names are [[LESS-THAN-", minFreq,"]] and [[TOTAL-TOKENS]]", "\n", sep = "") ## cat("if you remove these rows, execute", "\n", "result[ row.names(result) != \"[[LESS-THAN-", minFreq, "]]\" , ]", "\n", "result[ row.names(result) != \"[[TOTAL-TOKENS]]\" , ]","\n" , sep = "") break }else if(argW[i] == "tf"){ dtm <- localTF(dtm) }else if(argW[i] == "tf2"){ dtm <- localLogTF(dtm) }else if(argW[i] == "tf3"){ dtm <- localBin(dtm) }else if(argW[i] == "idf"){ dtm <- dtm * globalIDF(dtm) }else if(argW[i] == "idf2"){ dtm <- dtm * globalIDF2(dtm) }else if(argW[i] == "idf3"){ dtm <- dtm * globalIDF3(dtm) }else if(argW[i] == "idf4"){ dtm <- dtm * globalEntropy(dtm) } else if(argW[i] == "norm"){ dtm <- t(t(dtm) * mynorm(dtm)) } } if(any(is.na ( dtm))){ cat("Warning! Term document matrix includes NA!", "\n") } } invisible( dtm) }
d1161b164e6da7ba5e9bb6b6b40e3d7a9d341b24
dc1bdfbf8da66baa07b1e201021fdc687005dcd3
/Sandbox/test_file.R
6378135e4ebe6c0adeca397c336ff06cd07e7f86
[]
no_license
Kyle-J-Sun/CMEE_HPC
ca6144facf3fed4756fa51b3e0f151567f5690e9
078c341a70586aa7797aac4491823eed39980439
refs/heads/main
2023-03-14T18:13:33.105659
2021-03-07T13:01:18
2021-03-07T13:01:18
345,346,200
0
0
null
null
null
null
UTF-8
R
false
false
2,347
r
test_file.R
rm(list = ls()) library(ggplot2) # Question 15 sum_vect <- function(x = c(1, 3, 5, 8, 9, 8), y = c(1, 0, 5, 2)) { if (length(x) > length(y)){ y <- c(y, rep(0, length(x) - length(y))) } else if(length(x) < length(y)){ x <- c(x, rep(0, length(y) - length(x))) } return(x + y) } # sum_abundance <- c( ) sum_size <- c() combined_results <- list() #create your list output here to return i <- 0 while (i < 100){ i <- i + 1 fileName <- paste("Results/ks3020_result", i, ".rda", sep = "") load(fileName) # Obtain mean octaves for each abundance octave for (j in 1:length(oct)){ sum_abundance <- sum_vect(sum_abundance, oct[[j]]) } oct_mean <- sum_abundance/length(oct) sum_abundance <- c() sum_size <- sum_vect(sum_size, oct_mean) if (i %% 25 == 0){ print(i) combined_results <- c(combined_results, list(sum_size / 25)) sum_abundance <- c() sum_size <- c() } # save results to an .rda file save(combined_results, file = "combined_results.rda") } # # names <- c() # for (n in 1:12){ # if (n == 1){ # names <- c(names, "1") # } else { # names <- c(names, paste(2^(n-1),"~",2^n-1, sep = "")) # } # } # # df <- data.frame(Ranges = c(names[1:9], names[1:10], names[1:11], names[1:11]), # Octaves = c(combined_results[[1]], combined_results[[2]], combined_results[[3]], combined_results[[4]]), # Sizes = c(rep("Size = 500 Simulation", 9), rep("Size = 1000 Simulation", 10), rep("Size = 2500 Simulation", 11), rep("Size = 5000 Simulation", 11))) # # df$Ranges <- as.character(df$Ranges) # df$Ranges <- factor(df$Ranges, levels = unique(df$Ranges)) # # df$Sizes <- as.character(df$Sizes) # df$Sizes <- factor(df$Sizes, levels = unique(df$Sizes)) # # ggplot(df, aes(x = Ranges, y = Octaves, fill = Sizes)) + # geom_bar(stat = "identity") + # facet_grid(Sizes ~ .) + # theme(legend.position = "bottom") # load("Sandbox/test/neutral_simulation_3.rda") load("Results/ks3020_result3.rda") i <- 3 fileName <- paste("Results/ks3020_result", i, ".rda", sep = "") load(fileName) # Obtain mean octaves for each abundance octave for (j in 1:length(oct)){ sum_abundance <- sum_vect(sum_abundance, oct[[j]]) } oct_mean <- sum_abundance/length(oct) load("Sandbox/test/ks3020_result3.rda") # load("Week9_HPC/Sandbox/test/ks3020_result3.rda")
34bf0edb0729218b7b36e69d5567487f7011368f
48c5a905e1ca9350c8a10e76e8facb3f02558459
/cap15_AnaliseDeDadosEMachineLearning/packages/DMwR/man/bestScores.Rd
8a6bcf767085f265f7cb159c6ae1504091dc8bea
[]
no_license
brunotrindademachado/DSA-PBIparaDS-v2
01a953a4db9c2f286b8e92f6886446ff42235f1f
9a9ca73cf018b63b4a344ba3c8bd2d104745e7d2
refs/heads/main
2023-06-26T05:11:31.871661
2021-07-29T14:46:31
2021-07-29T14:46:31
377,211,843
0
0
null
null
null
null
UTF-8
R
false
false
3,159
rd
bestScores.Rd
\name{bestScores} \alias{bestScores} \title{ Obtain the best scores from an experimental comparison } \description{ This function can be used to obtain the learning systems that obtained the best scores on an experimental comparison. This information will be shown for each of the evaluation statistics involved in the comparison and also for all data sets that were used. } \usage{ bestScores(compRes, maxs = rep(F, dim(compRes@foldResults)[2])) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{compRes}{ A \code{compExp} object with the results of your experimental comparison. } \item{maxs}{ A vector of booleans with as many elements are there are statistics measured in the experimental comparison. A True value means the respective statistic is to be maximized, while a False means minimization. Defaults to all False values. } } \details{ This is a handy function to check what were the best performers in a comparative experiment for each data set and each evaluation metric. The notion of "best performance" depends on the type of evaluation metric, thus the need of the second parameter. Some evaluation statistics are to be maximized (e.g. accuracy), while others are to be minimized (e.g. mean squared error). If you have a mix of these types on your experiment then you can use the \code{maxs} parameter to inform the function of which are to be maximized (minimized). } \value{ The function returns a list with named components. The components correspond to the data sets used in the experimental comparison. For each component you get a data.frame, where the rows represent the statistics. For each statistic you get the name of the best performer (1st column of the data frame) and the respective score on that statistic (2nd column). } \references{ Torgo, L. (2010) \emph{Data Mining using R: learning with case studies}, CRC Press (ISBN: 9781439810187). \url{http://www.dcc.fc.up.pt/~ltorgo/DataMiningWithR} } \author{ Luis Torgo \email{ltorgo@dcc.fc.up.pt} } \seealso{ \code{\link{experimentalComparison}}, \code{\link{rankSystems}}, \code{\link{statScores}} } \examples{ ## Estimating several evaluation metrics on different variants of a ## regression tree and of a SVM, on two data sets, using one repetition ## of 10-fold CV data(swiss) data(mtcars) ## First the user defined functions cv.rpartXse <- function(form, train, test, ...) { require(DMwR) t <- rpartXse(form, train, ...) p <- predict(t, test) mse <- mean((p - resp(form, test))^2) c(nmse = mse/mean((mean(resp(form, train)) - resp(form, test))^2), mse = mse) } ## run the experimental comparison results <- experimentalComparison( c(dataset(Infant.Mortality ~ ., swiss), dataset(mpg ~ ., mtcars)), c(variants('cv.rpartXse',se=c(0,0.5,1))), cvSettings(1,10,1234) ) ## get the best scores for dataset and statistic bestScores(results) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ models }
0e32f6fd4b55d2a8d65d2a00aed5a8205b272ca7
8d7ffc7c9043a7fb1b590a69154b77d9cead1c88
/cachematrix.R
ef5c640beb0c7f7eba6f6692c8ec68532e442d8a
[]
no_license
karenshoop/ProgrammingAssignment2
529a83fa8e94102b3cee4121e6a54aafa23ae39e
e644dfb4931aa2835d5237c4fedaec4c3d7e81d1
refs/heads/master
2021-01-18T06:03:30.761172
2014-06-18T13:37:41
2014-06-18T13:37:41
null
0
0
null
null
null
null
UTF-8
R
false
false
903
r
cachematrix.R
## These functions store a matrix and cache its inverse ## to ensure for subsequent calls that the inverse ## does not have to be calculated each time ## Function creates a vector to get/set the value of ## a matrix and get/set the value of its inverse makeCacheMatrix <- function(x = matrix()) { i<-NULL set<-function(y){ x<<-y i<<-NULL } get<-function() x setinverse<-function(inverse)i<<-inverse getinverse<-function() i list(set=set,get=get,setinverse=setinverse,getinverse=getinverse) } ## returns the inverse if already calculate else ## calculates and stores it for future calls cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inv<-x$getinverse() if(!is.null(inv)){ message("returning cached inverse") return(inv) } data<-x$get() #solve() calculates the inverse inv<-solve(data) x$setinverse(inv) inv }
18a45e8a17cba78a368fc963b7eeee5d9384661e
f24edb31e7cbdf4e08cbe50b4a228e98d2ff5d13
/R/lattes_to_list.R
f5cb870ef8ce400939536c69c1177c19b29f34bf
[]
no_license
fcampelo/ChocoLattes
b870f2edbb55d2742ef9f946882f727fd65a185b
14df29beb5d32668d209c3d378d0a7e3898567d3
refs/heads/master
2021-09-09T13:54:10.879361
2018-03-09T13:14:55
2018-03-09T13:14:55
57,807,314
9
5
null
2018-03-09T13:14:56
2016-05-01T20:33:18
R
UTF-8
R
false
false
4,274
r
lattes_to_list.R
#' Convert a set of Lattes CV XML files to a list object #' #' Extract information from a set of Lattes XML files and convert it to a list #' vector #' #' This function extracts relevant information from a set of Lattes CV XML files #' and outputs a list object containing specific information on the following #' aspects of a group's production: #' - Accepted journal papers #' - Published journal papers #' - Published conference papers #' - Published book chapters #' - Published books #' - Ph.D. student defenses #' - M.Sc. student defenses #' #' Journal and conference papers are checked for duplication using DOI and Title #' information. Duplicated entries are registered only once. #' @param CV.dir folder where CVs are contained. If NULL #' then the current working directory is used. #' @param author.aliases list vector with author aliases. #' See \code{Examples} for details. #' #' @return list vector where each element is a dataframe with information on a #' specific aspect of the academic production #' #' @export #' #' @examples #' my.dir <- system.file("extdata", package="ChocoLattes") #' #' # Define the aliases of authors "Felipe Campelo" and "Lucas S. Batista": #' # (all aliases will be converted to the first name provided for each author) #' my.aliases <- list(c("Felipe Campelo", #' "Felipe Campelo Franca Pinto", #' "Felipe Campelo F. Pinto", #' "F.C.F. Pinto"), #' c("Lucas S. Batista", #' "Lucas Batista", #' "Lucas de Souza Batista", #' "Lucas Souza Batista")) #' #' lattes.list <- lattes_to_list(CV.dir = my.dir, #' author.aliases = my.aliases) lattes_to_list <- function(CV.dir = NULL, author.aliases = list()){ # Standardize CV.dir if(!R.utils::isAbsolutePath(CV.dir)){ CV.dir <- paste0(getwd(), "/", gsub(pattern = "[.]/", "", CV.dir)) } # get filenames filenames <- paste0(CV.dir, "/", dir(CV.dir, pattern = ".xml")) filenames <- gsub("//", "/", filenames) # Prepare list for results out.list <- vector("list", 7) names(out.list) <- c("Accepted for Publication", "Journal Papers", "Conference Papers", "Book Chapters", "Books", "MSc Dissertations", "PhD Theses") for (indx in seq_along(filenames)){ # Read XML to a list object x <- XML::xmlToList(XML::xmlTreeParse(filenames[indx], useInternal = TRUE, encoding = "latin")) # Get productions MyPapers <- get_journal_papers(x, ID = indx) MyAccept <- get_accepted_papers(x, ID = indx) MyConfs <- get_conference_papers(x, ID = indx) MyChaps <- get_book_chapters(x, ID = indx) MyBooks <- get_books(x, ID = indx) MyMsc <- get_advised_dissertations(x, ID = indx) MyPhd <- get_advised_theses(x, ID = indx) # ========================================== if (indx == 1) { out.list[[1]] <- MyAccept out.list[[2]] <- MyPapers out.list[[3]] <- MyConfs out.list[[4]] <- MyChaps out.list[[5]] <- MyBooks out.list[[6]] <- MyMsc out.list[[7]] <- MyPhd } else { out.list[[1]] <- rbind(out.list[[1]], MyAccept) out.list[[2]] <- rbind(out.list[[2]], MyPapers) out.list[[3]] <- rbind(out.list[[3]], MyConfs) out.list[[4]] <- rbind(out.list[[4]], MyChaps) out.list[[5]] <- rbind(out.list[[5]], MyBooks) out.list[[6]] <- rbind(out.list[[6]], MyMsc) out.list[[7]] <- rbind(out.list[[7]], MyPhd) } } # Sort: most recent first out.list <- lapply(out.list, FUN = sort_papers) # Get good capitalization of authornames out.list <- lapply(out.list, FUN = capitalize_authors, author.aliases = author.aliases) # Get good capitalization of Titles out.list <- lapply(out.list, FUN = capitalize_titles) # Remove duplicated works (by DOI, ISSN or Title) out.list <- lapply(out.list, FUN = remove_duplicates) return(out.list) }
b1b9efc9193a8d38ec7a3c0753095e069a6cea12
85a9566b5760703872ad1d43af649110a5ac9928
/Code/Lakes_hu12id_forgeo.R
1bd71ac1a70e2862e5e8e1bb9b8dd78087525001
[]
no_license
limnoliver/CSI-Nutrient-Time-Series
32862f6b69b92ef189c01c6766d5a80a9db374cf
bee5acaca08f98302ebe964e89b54580be7c6970
refs/heads/master
2020-05-21T12:28:11.117885
2017-08-23T01:39:22
2017-08-23T01:39:22
47,137,691
2
2
null
2017-10-17T18:23:19
2015-11-30T18:27:28
R
UTF-8
R
false
false
782
r
Lakes_hu12id_forgeo.R
setwd("~/Dropbox/CSI/CSI-LIMNO_DATA/LAGOSData/Version1.054.1") data.lake.specific = read.table("lagos_lakes_10541.txt", header = TRUE, sep = "\t", quote = "", dec = ".", strip.white = TRUE, comment.char = "") lakehu12<-data.lake.specific[,c(1,20)] modern.15.h12id<-merge(modern.15, lakehu12, by="lagoslakeid", all.x=TRUE, all.y=FALSE) limnohu12s<-modern.15.h12id$hu12_zoneid limnohu12s<-as.vector(limnohu12s) hu12list<-unique(limnohu12s) setwd("~/Dropbox/CSI/CSI_LIMNO_Manuscripts-presentations/CSI_Nitrogen MSs/Time series/GeoTS") write.csv(hu12list, "hu12withlimnodata.csv")
1658415615fa45d7b8d02e0106cb9d733ebb954a
a2374ebbed3a48790cb6f0b84b99083d5e1bc974
/no longer in use/2017_even_older/practice_piwa_170817.R
1abe83c617b320c73f7ba330ad69950c26306bd1
[]
no_license
woodjessem/Songbird-pine-project
9eacaedeabf1d34a34b2965fcff30932b69da4a0
55b4a29b616acfbe267b82c8baaf3dc07c28cd80
refs/heads/master
2021-01-18T18:47:04.464375
2018-12-04T14:12:35
2018-12-04T14:12:35
100,524,860
0
0
null
null
null
null
UTF-8
R
false
false
3,096
r
practice_piwa_170817.R
library("unmarked") setwd("~/GRAD SCHOOL - CLEMSON/Project-Specific/R_Work") test <-read.csv("piwa_abund.csv") summary(test) str(test) #y.4 and Noise.4 and Wind.4 and Sky.4 JDate.4 are factors and shouldn't be #stringsAsFactors=FALSE, but this only works for reading, not for below. piwa.abund<- csvToUMF("piwa_abund.csv", long = FALSE, type = "unmarkedFramePCount") ##type may need to change for occupancy (occuRN, pcountOpen, or whichever used) ## summary(piwa.abund) #obsCovs(piwa.abund)= scale(obsCovs(piwa.abund)) #siteCovs(piwa.abund)= scale(siteCovs(piwa.abund)) ?pcount #detection covariates first det.null.piwa <- pcount(~1 ~1, piwa.abund) det.weather.piwa <- pcount(~ Wind + Sky ~1, piwa.abund) det.global.piwa <- pcount(~ Jdate + Wind + Sky + Noise ~1, piwa.abund) det.sound.piwa <- pcount(~ Noise + Wind ~1, piwa.abund) det.date.piwa <- pcount(~ Jdate ~1, piwa.abund) det.detect.piwa <- pcount(~ Jdate + Noise ~1, piwa.abund) det.notdate.piwa <-pcount(~ Wind + Sky + Noise ~1, piwa.abund) fms <- fitList(det.null.piwa, det.weather.piwa, det.global.piwa, det.sound.piwa, det.date.piwa, det.detect.piwa, det.notdate.piwa) ms1.piwa <- modSel(fms) ms1.piwa@Full ms1.piwa #found that weather (wind + sky) was top model # and sound (wind + noise) was really close behind (delta 0.76) # but global was least, and date was really not that relevant! # added "not date" which is wind + sky + noise & it was the third highest model (1.29) #site covariates next #no K and no mixture type set (NB or P or ZIP) yet null.piwa <- pcount(~1 ~1, piwa.abund) global.piwa <- pcount(~ 1 ~ Treatment + BA + Nsnags + Ccover + Ldepth + TreeHt + Age + TimeSinceB + Herbicide , piwa.abund) local.piwa <- pcount(~ 1 ~ BA + Ccover + TreeHt + Ldepth, piwa.abund) lh.piwa <- pcount(~ 1 ~ Ccover + TreeHt + BA, piwa.abund) #landscape.piwa <- pcount(~ 1 ~ cov 5 + 6, piwa.abund) treatment.piwa <- pcount(~ 1 ~ Treatment + BA + TimeSinceB + Herbicide, piwa.abund) fms2 <- fitList(null.piwa, global.piwa, local.piwa, lh.piwa, treatment.piwa) ms2.piwa <- modSel(fms2) ms2.piwa@Full ms2.piwa #no K and no mixture type set (NB or P or ZIP) yet null2.piwa <- pcount(~ Wind + Sky + Noise ~1, piwa.abund) global2.piwa <- pcount(~ Wind + Sky + Noise ~ Treatment + BA + Nsnags + Ccover + Ldepth + TreeHt + Age + TimeSinceB + Herbicide , piwa.abund) local2.piwa <- pcount(~ Wind + Sky + Noise ~ BA + Ccover + TreeHt + Ldepth, piwa.abund) lh2.piwa <- pcount(~ Wind + Sky + Noise ~ Ccover + TreeHt + BA, piwa.abund) #landscape.piwa <- pcount(~ Wind + Sky + Noise ~ cov 5 + 6, piwa.abund) treatment2.piwa <- pcount(~ Wind + Sky + Noise ~ Treatment + BA + TimeSinceB + Herbicide, piwa.abund) fms3 <- fitList(null.piwa, global.piwa, local.piwa, lh.piwa, treatment.piwa) ms3.piwa <- modSel(fms3) ms3.piwa@Full ms3.piwa #for some reason, those ones are no different at all from ms2... #see help for package "xlsReadWrite" in old notes, if need be# #write.table(ms1.cawr@Full, file="C:/Users/path.type",sep="\t")
1b08ef4ab653e849f3faee230f10b98a751de5c6
a6ac32e43c91a3e4594685a585455ebe89c9a04e
/R/taxon.R
9f51756af0fba592c477d75cea1d04141fe898c1
[]
no_license
heibl/megaptera
6aeb20bc83126c98603d9271a3f1ae87311eedc1
5e8b548b01c40b767bd3bb3eb73d89c33b0bc379
refs/heads/master
2021-07-08T16:44:30.106073
2021-01-11T13:58:04
2021-01-11T13:58:04
55,764,237
5
0
null
2019-02-13T13:50:43
2016-04-08T08:44:44
R
UTF-8
R
false
false
2,771
r
taxon.R
## This code is part of the megaptera package ## © C. Heibl 2014 (last update 2019-11-24) #' @include taxon-class.R #' @importFrom methods new #' @export ## USER LEVEL CONSTRUCTOR ## ---------------------- "taxon" <- function(ingroup, extend.ingroup = FALSE, outgroup, extend.outgroup = FALSE, kingdom, exclude.hybrids = FALSE, tip.rank = "species", reference.rank = "auto"){ if (missing(ingroup)){ new("taxon", ingroup = list("undefined"), extend.ingroup = extend.ingroup, outgroup = list("undefined"), extend.outgroup = extend.outgroup, kingdom = "undefined", exclude.hybrids = exclude.hybrids, tip.rank = tip.rank, reference.rank = reference.rank) } else { ## ingroup <- unique(ingroup); outgroup <- unique(outgroup) if (is.factor(ingroup)) ingroup <- levels(ingroup)[ingroup] if (is.factor(outgroup)) outgroup <- levels(outgroup)[outgroup] if (is.character(ingroup)) ingroup <- as.list(ingroup) if (is.character(outgroup)) outgroup <- as.list(outgroup) tip.rank <- match.arg(tip.rank, c("genus", "species")) new("taxon", ingroup = ingroup, extend.ingroup = extend.ingroup, outgroup = outgroup, extend.outgroup = extend.outgroup, kingdom = kingdom, exclude.hybrids = exclude.hybrids, tip.rank = tip.rank, reference.rank = reference.rank) } } setMethod("show", signature(object = "taxon"), function (object) { arg <- c("tip rank", "ingroup", "is extended" , "outgroup", "is extended", "in kingdom", "exclude.hybrids", "guide tree") arg <- format(arg) formatTaxa <- function(taxa){ n <- length(taxa) taxa <- paste(head(taxa, 2), collapse = ", ") if ( n > 2 ) taxa <- paste(taxa, ", ... [", n, "]") taxa } out <- c( object@tip.rank, formatTaxa(object@ingroup), ifelse(object@extend.ingroup, "yes", "no"), formatTaxa(object@outgroup), ifelse(object@extend.outgroup, "yes", "no"), object@kingdom, ifelse(object@exclude.hybrids, "excluded", "included"), ifelse(inherits(object, "taxonGuidetree"), "user-defined", "taxonomy-based") ) out <- paste(arg, out, sep = " : ") out <- c("--- megaptera taxon class ---", out) out <- paste("\n", out, sep = "") cat(paste(out, collapse = "")) } )
ad11c759a0ebf852c042c5a26b955484d8baed64
ee8492dc3bc1f00b85332e63ca5e1da0ec8c9bb7
/man/outputMicroFusion.Rd
096949648d8534a6dd9636eed7fb0e84e3e9077a
[]
no_license
NHPatterson/aimsMSRC
ee151b0f007e44dd8e25257ccac8a252c0613eec
7f257af1e4366cf41be8f587b9ca9ae9c9601b7b
refs/heads/master
2020-03-08T17:24:26.814750
2019-04-27T23:16:52
2019-04-27T23:16:52
128,267,435
0
2
null
null
null
null
UTF-8
R
false
true
939
rd
outputMicroFusion.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/outputMicroFusion.R \name{outputMicroFusion} \alias{outputMicroFusion} \title{Output microscopy fusion files} \usage{ outputMicroFusion(micro_image_array, filename = "myfusionmicrodata", mask_image_array = NULL, data_label = "microscopy data", micro_spatial_res = 1) } \arguments{ \item{micro_image_array}{an image array [x,y,channel] from the RGB microscopy data loaded into R through the tiff, jpeg, or png library} \item{filename}{output file name without extension. a '_micro_data.txt' and '_micro_info.xml' will be tagged onto files approrpiately} \item{data_label}{a description of the data(i.e. rat brain, 1 um / pixel)} \item{micro_spatial_res}{microscopy image spatial resolution in microns / pixel} } \value{ writes outputs in working directory } \description{ Outputs a comma seperated .txt file in UNIX format for the fusion prototype tool }
a38e5adb3e9d540dad7400cd26684a3312866854
aa901107b9501f99c5f835881d3b42131ef581e3
/server.R
90cf421e81e25f2ed9cda5d114163712e7982b89
[ "MIT" ]
permissive
fcrawford/indiana-hiv
75a9d76810275365484d3ead70f7cfed4a7c9e65
116e38bf93d8a2f264f0c150ee4b990dbfe7a67e
refs/heads/master
2021-03-24T10:09:51.226739
2018-10-09T18:38:06
2018-10-09T18:38:06
110,284,836
3
1
null
null
null
null
UTF-8
R
false
false
3,838
r
server.R
library(shiny) source("indiana-hiv-util.R") shinyServer(function(input, output, session) { observe({ # observe the intvxday variable; this is to correct the width if an impossible combination is entered. if(input$intvxday[1]>first_dx_date) { updateSliderInput(session, "intvxday", value=c(first_dx_date, input$intvxday[2])) } }) observe({ d1 = NA d2 = NA if(input$scenario == "actual") { d1 = intvx_actual_date d2 = end_date } else if(input$scenario == "mid") { d1 = intvx_mid_date d2 = d1+scaleup_peak_offset } else if(input$scenario == "early") { d1 = intvx_early_date d2 = d1+scaleup_peak_offset } else { error("invalid choice") } updateSliderInput(session, "intvxday", value=c(d1, d2)) }) observe({ if(input$removal_scenario == "low") { v = removal_rate_low } else if(input$removal_scenario == "moderate") { v = removal_rate_mid } else if(input$removal_scenario == "high") { v = removal_rate_high } else { error("invalid choice") } updateSliderInput(session, "removal_rate", value=v) }) observe({ # observe the smoother selection input$reset # leave this alone. Makes the smoothers reset updateSliderInput(session, "smooth_dx", step=smoothers[[which(smoothernames==input$smoother)]]$step, value=smoothers[[which(smoothernames==input$smoother)]]$dxrange[2], min=smoothers[[which(smoothernames==input$smoother)]]$dxrange[1], max=smoothers[[which(smoothernames==input$smoother)]]$dxrange[3]) updateSliderInput(session, "smooth_Iudx", step=smoothers[[which(smoothernames==input$smoother)]]$step, value=smoothers[[which(smoothernames==input$smoother)]]$Iudxrange[2], min=smoothers[[which(smoothernames==input$smoother)]]$Iudxrange[1], max=smoothers[[which(smoothernames==input$smoother)]]$Iudxrange[3]) updateSliderInput(session, "smooth_I", step=smoothers[[which(smoothernames==input$smoother)]]$step, value=smoothers[[which(smoothernames==input$smoother)]]$Irange[2], min=smoothers[[which(smoothernames==input$smoother)]]$Irange[1], max=smoothers[[which(smoothernames==input$smoother)]]$Irange[3]) updateSliderInput(session, "smooth_S", step=smoothers[[which(smoothernames==input$smoother)]]$step, value=smoothers[[which(smoothernames==input$smoother)]]$Srange[2], min=smoothers[[which(smoothernames==input$smoother)]]$Srange[1], max=smoothers[[which(smoothernames==input$smoother)]]$Srange[3]) }) output$epidemicPlot <- renderPlot({ if(input$intvxday[1]<=first_dx_date) { plot_indiana_bounds(input$N, input$intvxday[1], input$intvxday[2], input$showDates, input$smooth_dx, input$smooth_Iudx, input$smooth_I, input$smooth_S, input$showSusc, input$smoother, input$removal_rate, input$plotType, input$calibration_scale, input$beta_scale) } }) #output$results <- renderText({ #get_indiana_results_text(input$N, input$intvxday[1], input$intvxday[2], input$smooth_dx, input$smooth_Iudx, input$smooth_I, input$smooth_S, input$smoother, input$removal_rate) #}) output$downloadDiagnoses <- downloadHandler( filename = function() { "scott_county_cases_by_week.csv" }, content = function(file) { file.copy("data/scott_county_cases_by_week.csv", file) } ) output$downloadIncidence <- downloadHandler( filename = function() { "incidence.csv" }, content = function(file) { file.copy("data/extracted_infection_curves.csv", file) } ) })
a6c95a86dab731323b889a479a5001938279a2c1
ae093209e6bfab6f3d4b9afc6b96f0fe0ea0d383
/man/repo_manager_init.Rd
98fcbcfe590e5876aba82f025d03ddb678bf8cff
[]
no_license
cran/RSuite
76eb522aa0cc4f48ffad9e2641a678b4b0a35baa
e0c72e5b38b49144794220f165c23a538ebc5cbf
refs/heads/master
2020-03-27T03:57:08.441251
2019-06-10T13:20:02
2019-06-10T13:20:02
145,900,970
0
0
null
null
null
null
UTF-8
R
false
true
1,831
rd
repo_manager_init.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/27_repo_manager.R \name{repo_manager_init} \alias{repo_manager_init} \title{Initializes managed repository structure.} \usage{ repo_manager_init(repo_manager, types) } \arguments{ \item{repo_manager}{repo manager object} \item{types}{package types for which repository should be initialized. If missing all project supported package types will be initialized (type: character)} } \value{ TRUE if initialized repository for at least one type, FALSE if the structure was fully initialized already. (type:logical, invisible) } \description{ Initializes managed repository structure. } \examples{ # create you own Repo adapter repo_adapter_create_own <- function() { result <- repo_adapter_create_base("Own") class(result) <- c("repo_adapter_own", class(result)) return(result) } #' create own repo manager #' @export repo_adapter_create_manager.repo_adapter_own <- function(repo_adapter, ...) { repo_manager <- list() # create you own repo manager class(repo_manager) <- c("repo_manager_own", "rsuite_repo_manager") return(repo_manager) } #' @export repo_manager_init.repo_manager_own <- function(repo_manager, types) { was_inited_already <- TRUE # ... if repository structure was not initialized initialize it ... return(invisible(was_inited_already)) } } \seealso{ Other in extending RSuite with Repo adapter: \code{\link{repo_adapter_create_base}}, \code{\link{repo_adapter_create_manager}}, \code{\link{repo_adapter_get_info}}, \code{\link{repo_adapter_get_path}}, \code{\link{repo_manager_destroy}}, \code{\link{repo_manager_get_info}}, \code{\link{repo_manager_remove}}, \code{\link{repo_manager_upload}} } \concept{in extending RSuite with Repo adapter}
ad1ff25cc2196d7afd2aecf71d3b05aea6c99e87
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/model4you/examples/binomial_glm_plot.Rd.R
3bfd17d4066fd5ba5ffe384b84243c81e27764d8
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
1,248
r
binomial_glm_plot.Rd.R
library(model4you) ### Name: binomial_glm_plot ### Title: Plot for a given logistic regression model (glm with binomial ### family) with one binary covariate. ### Aliases: binomial_glm_plot ### ** Examples set.seed(2017) # number of observations n <- 1000 # balanced binary treatment # trt <- factor(rep(c("C", "A"), each = n/2), # levels = c("C", "A")) # unbalanced binary treatment trt <- factor(c(rep("C", n/4), rep("A", 3*n/4)), levels = c("C", "A")) # some continuous variables x1 <- rnorm(n) x2 <- rnorm(n) # linear predictor lp <- -0.5 + 0.5*I(trt == "A") + 1*I(trt == "A")*I(x1 > 0) # compute probability with inverse logit function invlogit <- function(x) 1/(1 + exp(-x)) pr <- invlogit(lp) # bernoulli response variable y <- rbinom(n, 1, pr) dat <- data.frame(y, trt, x1, x2) # logistic regression model mod <- glm(y ~ trt, data = dat, family = "binomial") binomial_glm_plot(mod, plot_data = TRUE) # logistic regression model tree ltr <- pmtree(mod) plot(ltr, terminal_panel = node_pmterminal(ltr, plotfun = binomial_glm_plot, confint = TRUE, plot_data = TRUE))
d10be6ee86d4028e23a2a60045e2e6ae00f8cdff
b8778aaa0785b9ad3b591b366f5abc780b3a1825
/1.PrepareDataBCR6.R
c82ef53b528201cfb9f9808c7aadda05e7aba406
[]
no_license
tati-micheletti/NationalModel
9371d218db5171721cc116521f782ec220218edc
12460f9f7575f376ab5d0470e43f14e807d5bd58
refs/heads/master
2020-04-17T05:28:27.237798
2019-01-22T16:42:17
2019-01-22T16:42:17
166,280,590
0
0
null
2019-01-17T19:05:45
2019-01-17T19:05:45
null
UTF-8
R
false
false
8,644
r
1.PrepareDataBCR6.R
library(raster) library(maptools) library(dplyr) library(data.table) library(reshape2) LCC <- CRS("+proj=lcc +lat_1=49 +lat_2=77 +lat_0=0 +lon_0=-95 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs") w <-"G:/Boreal/NationalModelsV2/BCR6/" bcr6 <- raster("G:/Boreal/NationalModelsV2/BCR6/bcr6.tif") offl <- read.csv("G:/Boreal/NationalModelsV2/Quebec/BAMoffsets.csv") offla <- read.csv("G:/Boreal/NationalModelsV2/Quebec/Atlasoffsets.csv") load("F:/BAM/BAMData/data_package_2016-04-18.Rdata") load("F:/BAM/BAMData/offsets-v3_2016-04-18.Rdata") coordinates(SS) <- c("X", "Y") proj4string(SS) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") SSBAM <- as.data.frame(spTransform(SS, LCC)) PCBAM <- PCTBL PKEYBAM <- PKEY load("F:/BAM/BAMData/atlas_data_processed-20181018.RData") SS <- na.omit(SS) coordinates(SS) <- c("X", "Y") proj4string(SS) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") SSAtlas <- as.data.frame(spTransform(SS, LCC)) PCAtlas <- PCTBL PKEYAtlas <- PKEY names(PKEYAtlas)[4] <- "YEAR" load("F:/BAM/BamData/ARU/nwt-wildtrax-offsets-2019-01-16.RData") SSWT <- unique(dd[,c(33,39:40)]) PKEYWT <- unique(dd[,c(33,34,36)]) #PCWT <- dd[,c(33,34,36,38,47)] PCWT <- melt(y) names(PCBU) <- c("PKEY","SPECIES","ABUND") offWT <- data.table(melt(off)) names(offWT) <- c("PKEY","SPECIES","logoffset") offWT$SPECIES <- as.character(offWT$SPECIES) offWT$PKEY <- as.character(offWT$PKEY) load("F:/BAM/BamData/ARU/nwt-BU-offsets-2019-01-14.RData") SSBU <- unique(dd[,c(14,20:21)]) PKEYBU <- unique(dd[,c(14,15,17)]) PCBU <- melt(y) names(PCBU) <- c("PKEY","SPECIES","ABUND") offBU <- data.table(melt(off)) names(offBU) <- c("PKEY","SPECIES","logoffset") offBU$SPECIES <- as.character(offBU$SPECIES) offBU$PKEY <- as.character(offBU$PKEY) SScombo <- rbind(SSBAM[,c(2,48,49)],SSAtlas[,c(1,6,7)],SSWT,SSBU) PKEYcombo <- rbind(PKEYBAM[,c(1,2,8)],PKEYAtlas[,c(1,2,4)],PKEYWT,PKEYBU) eco <- raster("F:/GIS/ecoregions/CEC/quebececo1.tif") nalc <- raster("F:/GIS/landcover/NALC/LandCover_IMG/NA_LandCover_2005/data/NA_LandCover_2005/NA_LandCover_2005_LCC.img") bcr6 <- raster("G:/Boreal/NationalModelsV2/BCR6/bcr6.tif") urbag <- raster("G:/Boreal/NationalModelsV2/urbag2011_lcc1.tif") ua6 <- crop(urbag,bcr6) ua6 <- mask(ua6,bcr6) dev25 <- focal(ua6, fun=mean, w=matrix(1/25, nc=5, nr=5), na.rm=TRUE) wat <- raster("G:/Boreal/NationalModelsV2/wat2011_lcc1.tif") wat6 <- crop(wat,bcr6) wat6 <- mask(wat6,bcr6) led25 <- focal(wat6, fun=mean, w=matrix(1/25, nc=5, nr=5), na.rm=TRUE) lf <- raster("D:/NorthAmerica/topo/lf_lcc1.tif") lf6 <- crop(lf,bcr6) b2011 <- list.files("F:/GIS/landcover/Beaudoin/Processed_sppBiomass/2011/",pattern="tif$") setwd("F:/GIS/landcover/Beaudoin/Processed_sppBiomass/2011/") bs2011 <- stack(raster(b2011[1])) for (i in 2:length(b2011)) {bs2011 <- addLayer(bs2011, raster(b2011[i]))} names(bs2011) <- gsub("NFI_MODIS250m_2011_kNN_","",names(bs2011)) bs2011bcr6 <- crop(bs2011,bcr6) bs2011bcf6 <- mask(bs2011bcr6,bcr6) bs2011bcr6_1km <- aggregate(bs2011bcr6, fact=4, fun=mean) wat1km <- resample(wat6, bs2011bcr6_1km, method='ngb') bs2011bcr6_1km <- addLayer(bs2011bcr6_1km, wat1km) names(bs2011bcr6_1km)[nlayers(bs2011bcr6_1km)] <- "wat" led251km <- resample(led25, bs2011bcr6_1km, method='bilinear') bs2011bcr6_1km <- addLayer(bs2011bcr6_1km, led251km) names(bs2011bcr6_1km)[nlayers(bs2011bcr6_1km)] <- "led25" urbag1km <- resample(ua6, bs2011bcr6_1km, method='ngb') bs2011bcr6_1km <- addLayer(bs2011bcr6_1km, urbag1km) names(bs2011bcr6_1km)[nlayers(bs2011bcr6_1km)] <- "urbag" dev251km <- resample(dev25, bs2011bcr6_1km, method='bilinear') bs2011bcr6_1km <- addLayer(bs2011bcr6_1km, dev251km) names(bs2011bcr6_1km)[nlayers(bs2011bcr6_1km)] <- "dev25" lf_1km <- resample(lf6, bs2011bcr6_1km, method='ngb') bs2011bcr6_1km <- addLayer(bs2011bcr6_1km, lf_1km) names(bs2011bcr6_1km)[nlayers(bs2011bcr6_1km)] <- "landform" writeRaster(bs2011bcr6_1km,file=paste(w,"bcr6_2011rasters",sep=""),overwrite=TRUE) bs2011bcr6 <- addLayer(bs2011bcr6,wat6) names(bs2011bcr6)[nlayers(bs2011bcr6)] <- "wat" bs2011bcr6 <- addLayer(bs2011bcr6,led25) names(bs2011bcr6)[nlayers(bs2011bcr6)] <- "led25" bs2011bcr6 <- addLayer(bs2011bcr6,ua6) names(bs2011bcr6)[nlayers(bs2011bcr6)] <- "urbag" bs2011bcr6 <- addLayer(bs2011bcr6,dev25) names(bs2011bcr6)[nlayers(bs2011bcr6)] <- "dev25" lf250 <- resample(lf6, bs2011bcr6, method='ngb') bs2011bcr6 <- addLayer(bs2011bcr6, lf250) names(bs2011bcr6)[nlayers(bs2011bcr6)] <- "landform" writeRaster(bs2011bcr6,file=paste(w,"bcr6_2011rasters250",sep=""),overwrite=TRUE) b2001 <- list.files("F:/GIS/landcover/Beaudoin/Processed_sppBiomass/2001/",pattern="tif$") setwd("F:/GIS/landcover/Beaudoin/Processed_sppBiomass/2001/") bs2001 <- stack(raster(b2001[1])) for (i in 2:length(b2001)) {bs2001 <- addLayer(bs2001, raster(b2001[i]))} names(bs2001) <- gsub("NFI_MODIS250m_2001_kNN_","",names(bs2001)) bs2001bcr6 <- crop(bs2001,bcr6) bs2001bcf6 <- mask(bs2001bcr6,bcr6) # # bs2001bcr6_1km <- aggregate(bs2001bcr6, fact=4, fun=mean) # wat1km <- resample(wat6, bs2001bcr6_1km, method='ngb') # bs2001bcr6_1km <- addLayer(bs2001bcr6_1km, wat1km) # names(bs2001bcr6_1km)[nlayers(bs2001bcr6_1km)] <- "wat" # led251km <- resample(led25, bs2001bcr6_1km, method='bilinear') # bs2001bcr6_1km <- addLayer(bs2001bcr6_1km, led251km) # names(bs2001bcr6_1km)[nlayers(bs2001bcr6_1km)] <- "led25" # urbag1km <- resample(ua6, bs2001bcr6_1km, method='ngb') # bs2001bcr6_1km <- addLayer(bs2001bcr6_1km, urbag1km) # names(bs2001bcr6_1km)[nlayers(bs2001bcr6_1km)] <- "urbag" # dev251km <- resample(dev25, bs2001bcr6_1km, method='bilinear') # bs2001bcr6_1km <- addLayer(bs2001bcr6_1km, dev251km) # names(bs2001bcr6_1km)[nlayers(bs2001bcr6_1km)] <- "dev25" # lf_1km <- resample(lf6, bs2001bcr6_1km, method='ngb') # bs2001bcr6_1km <- addLayer(bs2001bcr6_1km, lf_1km) # names(bs2001bcr6_1km)[nlayers(bs2001bcr6_1km)] <- "landform" # writeRaster(bs2001bcr6_1km,file=paste(w,"bcr6_2001rasters",sep=""),overwrite=TRUE) bs2001bcr6 <- addLayer(bs2001bcr6,wat6) names(bs2001bcr6)[nlayers(bs2001bcr6)] <- "wat" bs2001bcr6 <- addLayer(bs2001bcr6,led25) names(bs2001bcr6)[nlayers(bs2001bcr6)] <- "led25" bs2001bcr6 <- addLayer(bs2001bcr6,ua6) names(bs2001bcr6)[nlayers(bs2001bcr6)] <- "urbag" bs2001bcr6 <- addLayer(bs2001bcr6,dev25) names(bs2001bcr6)[nlayers(bs2001bcr6)] <- "dev25" lf250 <- resample(lf6, bs2001bcr6, method='ngb') bs2001bcr6 <- addLayer(bs2001bcr6, lf250) names(bs2001bcr6)[nlayers(bs2001bcr6)] <- "landform" writeRaster(bs2001bcr6,file=paste(w,"bcr6_2001rasters250",sep=""),overwrite=TRUE) bs2011bcr6 <- dropLayer(bs2011bcr6,98) dat2011 <- cbind(SScombo, extract(bs2011bcr6,as.matrix(cbind(QCSS$X,QCSS$Y)))) dat2011 <-cbind(dat2011,extract(nalc,as.matrix(cbind(dat2011$X,dat2011$Y)))) names(dat2011)[ncol(dat2011)] <- "LCC" dat2011 <-cbind(dat2011,extract(eco,as.matrix(cbind(dat2011$X,dat2011$Y)))) names(dat2011)[ncol(dat2011)] <- "eco" dat2011 <-cbind(dat2011,extract(lfq,as.matrix(cbind(dat2011$X,dat2011$Y)))) names(dat2011)[ncol(dat2011)] <- "landform" dat2011$SS <- as.character(dat2011$SS) dat2011$PCODE <- as.character(dat2011$PCODE) write.csv(dat2011,paste(w,"bcr6_dat2011.csv",sep=""),row.names=FALSE) bs2001bcr6 <- dropLayer(bs2001bcr6,98) dat2001 <- cbind(SScombo, extract(bs2001bcr6,as.matrix(cbind(QCSS$X,QCSS$Y)))) dat2001 <-cbind(dat2001,extract(nalc,as.matrix(cbind(dat2001$X,dat2001$Y)))) names(dat2001)[ncol(dat2001)] <- "LCC" dat2001 <-cbind(dat2001,extract(eco,as.matrix(cbind(dat2001$X,dat2001$Y)))) names(dat2001)[ncol(dat2001)] <- "eco" dat2001 <-cbind(dat2001,extract(lfq,as.matrix(cbind(dat2001$X,dat2001$Y)))) names(dat2001)[ncol(dat2001)] <- "landform" samprast2001 <- rasterize(cbind(dat2001$X,dat2001$Y), led25, field=1) gf <- focalWeight(samprast2001, 100, "Gauss") sampsum25 <- focal(samprast2001, w=gf, na.rm=TRUE) dat2001 <- cbind(dat2001,extract(sampsum25,as.matrix(cbind(dat2001$X,dat2001$Y)))) names(dat2001)[ncol(dat2001)] <- "sampsum25" dat2001$wt <- 1/dat2001$sampsum25 dat2001$SS <- as.character(dat2001$SS) dat2001$PCODE <- as.character(dat2001$PCODE) write.csv(dat2001,paste(w,"bcr6_dat2001.csv",sep=""),row.names=FALSE) PC <- inner_join(PCTBL[,2:10],PKEY[,1:8],by=c("PKEY","SS")) #n=5808402 QCPC <- inner_join(PC, QCSS[,c(2,5)], by=c("SS")) #n=465693 QCPC$SS <- as.character(QCPC$SS) QCPC$PKEY <- as.character(QCPC$PKEY) QCPC$PCODE <- as.character(QCPC$PCODE) QCPC$SPECIES <- as.character(QCPC$SPECIES) QCPC2001 <- QCPC[QCPC$YEAR < 2006,] #n=212901 QCPC2011 <- QCPC[QCPC$YEAR > 2005,] #n=252792 write.csv(QCPC2011,paste(w,"BCR6PC2011.csv",sep=""),row.names=FALSE) write.csv(QCPC2001,paste(w,"BCR6PC2001.csv",sep=""),row.names=FALSE)
c62a2b57233ab6d0b0817a23348fa5b050fab810
d5ea152b86f0a35b94f759f3163e4f8030b609b6
/R/create_cells.R
b18a9c977644514500b25098057376190356d5f2
[]
no_license
R-ramljak/MNOanalyze
04c32a2c648fc44c8b282fa4b5c2a653f0463960
0e0237ab5f51d7f94904ece21b954e9eb9a21cb8
refs/heads/master
2023-06-03T05:53:25.787276
2021-06-18T21:23:47
2021-06-18T21:23:47
378,082,885
0
0
null
null
null
null
UTF-8
R
false
false
3,041
r
create_cells.R
#' @title create_cells #' #' @description Create a specific tower layer with attached directional cells #' #' @param area.sf sf dataframe, focus area with geometry column (tile polygons) #' @param tower.dist numeric value, distance between towers (e.g., in meters, however in general dimensionless) #' @param rotation.deg numeric value, layer rotation of directional cells, sectorized, in reference to the northern direction #' @param jitter numeric value, amount of jitter (e.g., in meters, however in general dimensionless) #' @param small logical value, TRUE for omnidirectional cell and FALSE for directional cell #' @param subscript character value, abbreviation for layer id #' @param seed numeric value, seed for reproducibility #' #' #' @return A data frame with antennas of the specfic layer in the rows and the #' the following columns: point location (x, y), tower.id, cell.id, cell.kind #' (layer), intra.cell.number (in case of directional cells, three antennas per tower, #' sectorized), kind of cell (directional or omnidirectional), and rotation degree. #' This data frame corresponds to an unvalidated cell plan that can be validated #' with `create_cellplan()`. #' #' @export #' @importFrom dplyr "%>%" #' #' create_cells <- function(area.sf, tower.dist, rotation.deg, jitter, small = FALSE, subscript, seed) { set.seed = seed rotation = function(a){ r = a * pi / 180 #degrees to radians matrix(c(cos(r), sin(r), -sin(r), cos(r)), nrow = 2, ncol = 2) } layer_network_generate = function(x, tower.dist, rotation.deg){ layer.geo <- x %>% sf::st_make_grid(cellsize = tower.dist, square = F, # hexagon flat_topped = T) %>% # different cell size (qm) sf::st_geometry() layer.centroid <- sf::st_centroid(layer.geo) layer <- (layer.geo - layer.centroid) * rotation(rotation.deg) + layer.centroid # rotate by 35 degrees return(layer) } # create layer object, placing towers layer <- layer_network_generate(x = area.sf, tower.dist = tower.dist, rotation.deg = rotation.deg) # specify exact location of towers and labelling towers <- layer %>% sf::st_centroid() %>% sf::st_jitter(jitter) %>% sf::st_coordinates() %>% tibble::as_tibble() %>% dplyr::select(X.tow = X, Y.tow = Y) %>% dplyr::mutate(tower.id = paste0(subscript, ".", 1:dplyr::n())) # create 3 cells per tower and labelling cells.unparam <- towers %>% dplyr::slice(rep(1:dplyr::n(), each = 3)) %>% dplyr::group_by(tower.id) %>% dplyr::mutate(cell = paste(tower.id, "C", 1:3, sep = ".")) %>% dplyr::ungroup() %>% dplyr::mutate(cell.kind = subscript) %>% dplyr::mutate(intra.cell.number = stringr::str_sub(cell, -1)) %>% dplyr::mutate(small = small) %>% dplyr::mutate(rotation.deg = rotation.deg) return(cells.unparam) }
cd80e6897629295023490d6b0eb2f2c809ead528
7a95abd73d1ab9826e7f2bd7762f31c98bd0274f
/metacoder/inst/testfiles/centroid/AFL_centroid/centroid_valgrind_files/1615765860-test.R
a0a239c59309fe899f6e9a0fb000d7c0c089e7b5
[ "MIT" ]
permissive
akhikolla/updatedatatype-list3
536d4e126d14ffb84bb655b8551ed5bc9b16d2c5
d1505cabc5bea8badb599bf1ed44efad5306636c
refs/heads/master
2023-03-25T09:44:15.112369
2021-03-20T15:57:10
2021-03-20T15:57:10
349,770,001
0
0
null
null
null
null
UTF-8
R
false
false
187
r
1615765860-test.R
testlist <- list(b = c(NaN, NaN, -4.91790800486089e-166, 6.47517494783079e-319, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) result <- do.call(metacoder:::centroid,testlist) str(result)
8a1cf932fac2c19fbb31c0378d5af49c1fd97d2b
cacf9d286229e3cd8b352f45f5c665469613c836
/tests/testthat.R
bc52a94777d4ca3922b105c5f8026d4dbcc4cff2
[ "MIT" ]
permissive
alan-turing-institute/network-comparison
e42a102c84874b54aff337bcd6a76a1089b9eab7
ee67bd42320a587adae49bafea6a59bfb50aafc6
refs/heads/master
2022-07-03T04:30:06.450656
2022-06-06T20:14:30
2022-06-06T20:14:30
75,952,713
13
1
MIT
2022-06-10T12:58:41
2016-12-08T15:57:35
R
UTF-8
R
false
false
58
r
testthat.R
library(testthat) library(netdist) test_check("netdist")
ed6f7d080fd12e7103642ba55a920730c6358a9f
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/rstanarm/man/kfold.stanreg.Rd
ef903462f6bb6c1f63e37ec304e0a8b16da2ee90
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
true
5,414
rd
kfold.stanreg.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/loo-kfold.R \name{kfold.stanreg} \alias{kfold.stanreg} \alias{kfold} \title{K-fold cross-validation} \usage{ \method{kfold}{stanreg}( x, K = 10, ..., folds = NULL, save_fits = FALSE, cores = getOption("mc.cores", 1) ) } \arguments{ \item{x}{A fitted model object returned by one of the rstanarm modeling functions. See \link{stanreg-objects}.} \item{K}{For \code{kfold}, the number of subsets (folds) into which the data will be partitioned for performing \eqn{K}-fold cross-validation. The model is refit \code{K} times, each time leaving out one of the \code{K} folds. If the \code{folds} argument is specified then \code{K} will automatically be set to \code{length(unique(folds))}, otherwise the specified value of \code{K} is passed to \code{loo::\link[loo:kfold-helpers]{kfold_split_random}} to randomly partition the data into \code{K} subsets of equal (or as close to equal as possible) size.} \item{...}{Currently ignored.} \item{folds}{For \code{kfold}, an optional integer vector with one element per observation in the data used to fit the model. Each element of the vector is an integer in \code{1:K} indicating to which of the \code{K} folds the corresponding observation belongs. There are some convenience functions available in the \pkg{loo} package that create integer vectors to use for this purpose (see the \strong{Examples} section below and also the \link[loo]{kfold-helpers} page).} \item{save_fits}{For \code{kfold}, if \code{TRUE}, a component \code{'fits'} is added to the returned object to store the cross-validated \link[=stanreg-objects]{stanreg} objects and the indices of the omitted observations for each fold. Defaults to \code{FALSE}.} \item{cores}{The number of cores to use for parallelization. Instead fitting separate Markov chains for the same model on different cores, by default \code{kfold} will distribute the \code{K} models to be fit across the cores (using \code{\link[parallel:clusterApply]{parLapply}} on Windows and \code{\link[parallel]{mclapply}} otherwise). The Markov chains for each model will be run sequentially. This will often be the most efficient option, especially if many cores are available, but in some cases it may be preferable to fit the \code{K} models sequentially and instead use the cores for the Markov chains. This can be accomplished by setting \code{options(mc.cores)} to be the desired number of cores to use for the Markov chains \emph{and} also manually specifying \code{cores=1} when calling the \code{kfold} function. See the end of the \strong{Examples} section for a demonstration.} } \value{ An object with classes 'kfold' and 'loo' that has a similar structure as the objects returned by the \code{\link{loo}} and \code{\link{waic}} methods and is compatible with the \code{\link{loo_compare}} function for comparing models. } \description{ The \code{kfold} method performs exact \eqn{K}-fold cross-validation. First the data are randomly partitioned into \eqn{K} subsets of equal size (or as close to equal as possible), or the user can specify the \code{folds} argument to determine the partitioning. Then the model is refit \eqn{K} times, each time leaving out one of the \eqn{K} subsets. If \eqn{K} is equal to the total number of observations in the data then \eqn{K}-fold cross-validation is equivalent to exact leave-one-out cross-validation (to which \code{\link[=loo.stanreg]{loo}} is an efficient approximation). } \examples{ \donttest{ fit1 <- stan_glm(mpg ~ wt, data = mtcars, refresh = 0) fit2 <- stan_glm(mpg ~ wt + cyl, data = mtcars, refresh = 0) fit3 <- stan_glm(mpg ~ disp * as.factor(cyl), data = mtcars, refresh = 0) # 10-fold cross-validation # (if possible also specify the 'cores' argument to use multiple cores) (kfold1 <- kfold(fit1, K = 10)) kfold2 <- kfold(fit2, K = 10) kfold3 <- kfold(fit3, K = 10) loo_compare(kfold1, kfold2, kfold3) # stratifying by a grouping variable # (note: might get some divergences warnings with this model but # this is just intended as a quick example of how to code this) fit4 <- stan_lmer(mpg ~ disp + (1|cyl), data = mtcars, refresh = 0) table(mtcars$cyl) folds_cyl <- loo::kfold_split_stratified(K = 3, x = mtcars$cyl) table(cyl = mtcars$cyl, fold = folds_cyl) kfold4 <- kfold(fit4, folds = folds_cyl, cores = 2) print(kfold4) } # Example code demonstrating the different ways to specify the number # of cores and how the cores are used # # options(mc.cores = NULL) # # # spread the K models over N_CORES cores (method 1) # kfold(fit, K, cores = N_CORES) # # # spread the K models over N_CORES cores (method 2) # options(mc.cores = N_CORES) # kfold(fit, K) # # # fit K models sequentially using N_CORES cores for the Markov chains each time # options(mc.cores = N_CORES) # kfold(fit, K, cores = 1) } \references{ Vehtari, A., Gelman, A., and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. \emph{Statistics and Computing}. 27(5), 1413--1432. doi:10.1007/s11222-016-9696-4. arXiv preprint: \url{http://arxiv.org/abs/1507.04544/} Yao, Y., Vehtari, A., Simpson, D., and Gelman, A. (2018) Using stacking to average Bayesian predictive distributions. \emph{Bayesian Analysis}, advance publication, doi:10.1214/17-BA1091. (\href{https://projecteuclid.org/euclid.ba/1516093227}{online}). }
d37c9390b6198d85f68a203f371bdce9dd3ed6c2
12e614cf86cf2ebbd977d5822d7fad99c939a8d5
/OurBiCopSelect.R
beb45957695910bea5ab448ffae10897a1481fba
[]
no_license
sghosh89/BIVAN
201aebd7474557b3c97265c9885cd5a08261d2f4
502c367a6431574e6605673b0a905e71a2cb9b1d
refs/heads/master
2021-03-30T16:41:25.419643
2020-03-16T12:07:17
2020-03-16T12:07:17
120,802,555
2
1
null
null
null
null
UTF-8
R
false
false
9,518
r
OurBiCopSelect.R
library(VineCopula) source("MyBiCopGofTest.R") #This function takes a sample from a bivariate distribution #consisting of values between 0 and 1 and: #a) tests for independence and for positive correlation #b) if independence can be rejected and correlation is positive, it # fit a series of bivariate copula models and provides fitted # parameters, log likelihood, AIC and BIC for each, and other info #c) for the best copula model (by AIC or BIC), the function tests # for the goodness of fit in two ways #d) optionally tests for the goodness of fit of the normal copula # #The function is a re-implementation of the BiCopSelect function #in the VineCopula package, re-done to ensure we could understand and #control what we were getting. # #Args #u1, u2 The sample. These can be obtained, for instance, # by applying pobs in the VineCopula package to # samples from any bivariate distribution or to # any bivariate dataset #level Significance level to be used for the independence # test #families The copula families to use in b above. Uses codes # as specified in the docs for BiCopEst in the # VineCopula package. #AICBIC Which one to use for model selection. #numBSsmall #pthresh #numBSlarge Number of bootstraps to use for goodness of fit. # First, tests are run with numBSsmall, and if p-values # are ever less than pthresh, tests are re-run with # numBSlarge. Watch out, large values can mean long # run times. #gofnormal T/F on whether a goodness of fit test for the normal # copula should be run. #status T/F - should status updates on the run be printed? # #Output: a list with these elements #IndepTestRes p-value result of the independence test #TauVal Kendall correlation #InfCritRes data frame of results from the information- # criterion-based model fitting and selection #GofRes_CvM p-value result for Cramer-von-Mises-based # goodness of fit test for top-ranking copula # by AIC or BIC #GofRes_KS Same, but using a Kolmogorov-Smirnov-based # test. See docs for MyBiCopGofTest in the # VineCopula package #GofRes_CvM_stat #GofRes_KS_stat Statistics for the tests #Numboot Number of bootstraps (numBSsmall/large) #Numboot_success Number of succeeded bootstraps out of Numboot #GofRes_Normal_CvM #GofRes_Normal_KS #GofRes_Normal_CvM_stat #GofRes_Normal_KS_stat Same as above, but for testing the goodness of fit of the normal copula. #Numboot_Normal Number of bootstraps for the normal test (numBSsmall/large) #Numboot_success_Normal Number of succeeded bootstraps out of Numboot_Normal #relLTdep_AICw Model-averaged lower-tail dependence statistic (AIC-weightage based) #relUTdep_AICw Model-averaged upper-tail dependence statistic (AIC-weightage based) #relLTdep_BICw Model-averaged lower-tail dependence statistic (BIC-weightage based) #relUTdep_BICw Model-averaged upper-tail dependence statistic (BIC-weightage based) OurBiCopSelect<-function(u1,u2,families,level=0.05,AICBIC="AIC", numBSsmall=100,pthresh=0.2,numBSlarge=1000, gofnormal=TRUE,status=TRUE) { #first, test for independence (H0 is independence) if (status) {cat(paste("Starting independence test: ",Sys.time(),"\n"))} IndepTestRes<-BiCopIndTest(u1,u2)$p.value if (status) {cat(paste("Done:",Sys.time(),"\n"))} tauval<-cor(u1,u2,method="kendall") # print(paste0("IndepTestRes=",IndepTestRes,"; tauval=",tauval)) #if independence rejected and tau>0, then get AICs for copulas and do #goodness of fit stuff if (IndepTestRes<level && tauval>0){ # print("Entering main work if statement in BiCopGofTest") #AIC/BIC stuff if (status) {cat(paste("Starting A/BIC model selection: ",Sys.time(),"\n"))} InfCritRes<-data.frame(copcode=families, copname=BiCopName(families, short=TRUE), par1=NA, par2=NA, logLik=NA, AIC=NA, BIC=NA, LTdep=NA, UTdep=NA, AICw=NA, BICw=NA) for (counter in 1:(dim(InfCritRes)[1])){ # print(paste0("About to call BiCopEst for counter=",counter)) tres<-BiCopEst(u1,u2,family=InfCritRes[counter,1]) InfCritRes$par1[counter]<-tres$par InfCritRes$par2[counter]<-tres$par2 InfCritRes$logLik[counter]<-tres$logLik InfCritRes$AIC[counter]<-tres$AIC InfCritRes$BIC[counter]<-tres$BIC InfCritRes$LTdep[counter]<-tres$taildep$lower InfCritRes$UTdep[counter]<-tres$taildep$upper } for(counter in 1:(dim(InfCritRes)[1])){ InfCritRes$AICw[counter]<-exp(-0.5*(InfCritRes$AIC[counter]-min(InfCritRes$AIC,na.rm=T))) InfCritRes$BICw[counter]<-exp(-0.5*(InfCritRes$BIC[counter]-min(InfCritRes$BIC,na.rm=T))) } InfCritRes$AICw<-InfCritRes$AICw/sum(InfCritRes$AICw,na.rm=T) InfCritRes$BICw<-InfCritRes$BICw/sum(InfCritRes$BICw,na.rm=T) # check : sum(InfCritRes$AICw)=1, sum(InfCritRes$BICw)=1 relLTdep_AICw<-sum((InfCritRes$LTdep*InfCritRes$AICw)/sum(InfCritRes$AICw,na.rm=T),na.rm=T) relUTdep_AICw<-sum((InfCritRes$UTdep*InfCritRes$AICw)/sum(InfCritRes$AICw,na.rm=T),na.rm=T) relLTdep_BICw<-sum((InfCritRes$LTdep*InfCritRes$BICw)/sum(InfCritRes$BICw,na.rm=T),na.rm=T) relUTdep_BICw<-sum((InfCritRes$UTdep*InfCritRes$BICw)/sum(InfCritRes$BICw,na.rm=T),na.rm=T) if (status) {cat(paste("Done: ",Sys.time(),"\n"))} #g.o.f. stuff for the A/BIC-best copula if (status) {cat(paste("Starting gof for A/BIC-best copula: ",Sys.time(),"\n"))} if (AICBIC=="AIC"){ ind<-which.min(InfCritRes$AIC) } if (AICBIC=="BIC"){ ind<-which.min(InfCritRes$BIC) } if (AICBIC!="AIC" && AICBIC!="BIC"){ stop("Error in OurBiCopSelect: incorrect AICBIC") } Numboot<-numBSsmall # print("About to call MyBiCopGofTest") gres<-MyBiCopGofTest(u1,u2,family=InfCritRes$copcode[ind], method="kendall",B=numBSsmall) # print("Finished calling MyBiCopGofTest") GofRes_CvM<-gres$p.value.CvM GofRes_KS<-gres$p.value.KS Numboot_success<-gres$B_success if (GofRes_CvM<pthresh || GofRes_KS<pthresh) { Numboot<-numBSlarge # print("About to call MyBiCopGofTest second time") gres<-MyBiCopGofTest(u1,u2,family=InfCritRes$copcode[ind], method="kendall",B=numBSlarge) # print("Finished calling MyBiCopGofTest second time") GofRes_CvM<-gres$p.value.CvM GofRes_KS<-gres$p.value.KS Numboot_success<-gres$B_success } GofRes_CvM_stat<-gres$statistic.CvM GofRes_KS_stat<-gres$statistic.KS if (status) {cat(paste("Done: ",Sys.time(),"\n"))} #g.o.f. stuff for the normal copula if(gofnormal==T){ if (status) {cat(paste("Starting gof for normal copula: ",Sys.time(),"\n"))} Numboot_Normal<-numBSsmall gres_normal_cop<-MyBiCopGofTest(u1,u2,family=1,method="kendall",B=numBSsmall) GofRes_Normal_CvM<-gres_normal_cop$p.value.CvM GofRes_Normal_KS<-gres_normal_cop$p.value.KS Numboot_success_Normal<-gres_normal_cop$B_success if (GofRes_Normal_CvM<pthresh || GofRes_Normal_KS<pthresh) { Numboot_Normal<-numBSlarge gres_normal_cop<-MyBiCopGofTest(u1,u2,family=1,method="kendall",B=numBSlarge) GofRes_Normal_CvM<-gres_normal_cop$p.value.CvM GofRes_Normal_KS<-gres_normal_cop$p.value.KS } GofRes_Normal_CvM_stat<-gres_normal_cop$statistic.CvM GofRes_Normal_KS_stat<-gres_normal_cop$statistic.KS Numboot_success_Normal<-gres_normal_cop$B_success if (status) {cat(paste("Done: ",Sys.time(),"\n"))} }else{ GofRes_Normal_CvM<-NA GofRes_Normal_KS<-NA GofRes_Normal_CvM_stat<-NA GofRes_Normal_KS_stat<-NA Numboot_Normal<-NA Numboot_success_Normal<-NA } } else { InfCritRes<-NA GofRes_CvM<-NA GofRes_KS<-NA GofRes_CvM_stat<-NA GofRes_KS_stat<-NA Numboot<-NA Numboot_success<-NA GofRes_Normal_CvM<-NA GofRes_Normal_KS<-NA GofRes_Normal_CvM_stat<-NA GofRes_Normal_KS_stat<-NA Numboot_Normal<-NA Numboot_success_Normal<-NA relLTdep_AICw<-NA relUTdep_AICw<-NA relLTdep_BICw<-NA relUTdep_BICw<-NA } return(list(IndepTestRes=IndepTestRes, TauVal=tauval, InfCritRes=InfCritRes, GofRes_CvM=GofRes_CvM, GofRes_KS=GofRes_KS, GofRes_CvM_stat=GofRes_CvM_stat, GofRes_KS_stat=GofRes_KS_stat, Numboot=Numboot, Numboot_success=Numboot_success, GofRes_Normal_CvM=GofRes_Normal_CvM, GofRes_Normal_KS=GofRes_Normal_KS, GofRes_Normal_CvM_stat=GofRes_Normal_CvM_stat, GofRes_Normal_KS_stat=GofRes_Normal_KS_stat, Numboot_Normal=Numboot_Normal, Numboot_success_Normal= Numboot_success_Normal, relLTdep_AICw=relLTdep_AICw, relUTdep_AICw=relUTdep_AICw, relLTdep_BICw=relLTdep_BICw, relUTdep_BICw=relUTdep_BICw)) }
34d98b3416d129e60a6a546cf467465eb6ca7c5b
40962c524801fb9738e3b450dbb8129bb54924e1
/DAY - 3/Assignment/Q1 - Convert.R
13ca9e6acc6163781329101681b8c58c1f8aa759
[]
no_license
klmsathish/R_Programming
628febe334d5d388c3dc51560d53f223585a0843
93450028134d4a9834740922ff55737276f62961
refs/heads/master
2023-01-14T12:08:59.068741
2020-11-15T13:23:31
2020-11-15T13:23:31
309,288,498
1
0
null
null
null
null
UTF-8
R
false
false
265
r
Q1 - Convert.R
#collapse function convert=function(x) { #Using collapse for cancatenating into one string y=paste(x,collapse=",") print(y) } #Checking for 3 values convert(c("sathish","kumar","good")) convert(c("sathish","kumar")) #Checking for 1 value convert(c("sathish"))
9b23b34b1bd18d696eddafd481a03e2e6de5304c
034acc4479cbdcd31e08730a45b908be55032692
/R/square_usa.R
b45a7e75a9914c8e58d207dc95b2a4711b8d14ee
[]
no_license
EmilHvitfeldt/tilemapr
97ac78c112f9e4ba8ebac4a8a144489a637226fb
23edc1ab6495892e8040a866995fe34c8ab47d78
refs/heads/master
2021-01-21T07:13:36.930060
2017-12-22T17:39:12
2017-12-22T17:39:12
91,603,168
8
0
null
null
null
null
UTF-8
R
false
false
3,265
r
square_usa.R
#' Creates square tile map for the states of USA. #' #' @param d Numeric. Number between 0 and 1. Procentwise Diameter (length from #' center to corner) of the tiles. #' @param center Logical. When TRUE returns the center coordinates of the tile #' map. #' @param style Character. Selets the layout style of the tile map. #' @param size Numeric. Size of the tiles. #' @param long_offset Numeric. Value to offset the long output. #' @param lat_offset Numeric. Value to offset the lat output. #' @param exclude Character. Vector of state names which should be excluded #' from the output. Matched with lowercase full state names. #' @return The available styles for this functions are "NPR", #' "The New York Times", "538", "Propublica", "Bloomberg", "The Guardian", #' "Wall Street Journal", "WNYC" or "The Marshall Project". #' @examples #' \dontrun{ #' library(ggplot2) #' crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests) #' states_map <- square_usa() #' ggplot(crimes, aes(map_id = state)) + #' geom_map(aes(fill = Murder), map = states_map) + #' expand_limits(x = states_map$long, y = states_map$lat) #' #' states_map <- square_usa(d = 0.5) #' #' ggplot(crimes, aes(map_id = state)) + #' geom_map(aes(fill = Murder), map = states_map) + #' expand_limits(x = states_map$long, y = states_map$lat) + #' geom_text(data = square_usa(d = 0.5, center = TRUE), #' aes(x = long, y = lat, label = states_abb), #' inherit.aes = FALSE) #'} #'@export square_usa <- function(d = 0.95, center = FALSE, style = "NPR", size = 1, long_offset = 0, lat_offset = 0, exclude = character()) { if(d <= 0 || d > 1) { warning("d must be in the interval (0, 1], defaulted to 0.95") d <- 0.95 } if(!(style %in% c("NPR", "The New York Times", "538", "Propublica", "Bloomberg", "The Guardian", "Wall Street Journal", "WNYC", "The Marshall Project"))) { warning("Unable to recognize style, defaulted to NPR") STYLE <- "NPR" } else { STYLE <- style } exclude <- intersect(square_usa_data$region, exclude) d <- d / 2 * size dat0 <- square_usa_data %>% dplyr::filter(style == STYLE) %>% dplyr::select(- style) %>% dplyr::mutate(long = ~long * size, lat = ~lat * size) dat1 <- rbind(dat0 %>% dplyr::mutate(long = ~long + d, lat = ~lat + d), dat0 %>% dplyr::mutate(long = ~long - d, lat = ~lat + d), dat0 %>% dplyr::mutate(long = ~long - d, lat = ~lat - d), dat0 %>% dplyr::mutate(long = ~long + d, lat = ~lat - d)) %>% dplyr::mutate(group = as.numeric(~group)) if (center) { dat2 <- dat0 %>% dplyr::mutate(long = ~long - dat1[114, "long"] + long_offset, lat = ~lat - dat1[114, "lat"] + lat_offset) %>% dplyr::filter(!(~region %in% exclude)) return(dat2) } else { dat2 <- dat1 %>% dplyr::mutate(long = ~long - dat1[114, "long"] + long_offset, lat = ~lat - dat1[114, "lat"] + lat_offset) %>% dplyr::filter(!(~region %in% exclude)) return(dat2[order(dat2$region), ] %>% dplyr::mutate(order = 1:(204 - length(exclude) * 4))) } }
739daa466d69d524512077137b8b9fbc5a409d80
02d2c444204db4fa4f85d3f53591c10fec6a813c
/R/helpers.R
8f2a54cc4ea644c10444f31e8303ac908e231948
[ "MIT" ]
permissive
berdaniera/preparer
ac199b075f031709985a432bd4ae27b0768ce6ad
201f5fb40fe6f1b2aed4a8e274933628972a8f8a
refs/heads/master
2021-01-21T21:14:47.900087
2017-06-22T20:05:03
2017-06-22T20:05:03
94,791,103
0
1
null
2017-06-22T17:40:53
2017-06-19T15:19:08
R
UTF-8
R
false
false
2,054
r
helpers.R
na_fill = function(x, tol){ # x is a vector of data # tol is max number of steps missing (if greater, it retains NA) ina = is.na(x) csum = cumsum(!ina) wg = as.numeric(names(which(table(csum) > tol))) # which gaps are too long x[ina] = approx(x, xout=which(ina))$y x[which(csum%in%wg)[-1]] = NA return(x) } # This is a test. # I added something here, just a test # stack data files from the same data logger but different dates load_stack_file = function(files, gmtoff, logger){ dates = sub(".*_(.*)_.*\\..*", "\\1", files) # get all dates xx = lapply(dates, function(x) load_file(grep(x,files,value=TRUE), gmtoff$offs[which(gmtoff$dnld_date==x)], logger) ) # load data for each date xx = Reduce(function(df1,df2) bind_rows(df1,df2), xx) # stack them up arrange(xx, DateTimeUTC) } # Snap timestamps to the closest interval snap_ts = function(x, samp_freq, nearest=FALSE){ # x is a date-time vector to be snapped # freq is the frequency of observations as a string # containing the number of units and the unit (S,M,H,D) # e.g., '15M', '1H', '3D', '66S' # nearest is logical to snap to floor (default) or to nearest time cut re = regexec("([0-9]+)([A-Z])",samp_freq)[[1]] if(-1%in%re){ stop("Please enter a correct string") }else{ ml = attr(re,"match.length") nn = as.numeric(substr(samp_freq, re[2], ml[2])) uu = substr(samp_freq, re[3], ml[1]) if(uu=="D"){td = 24*60*60*nn }else if(uu=="H"){td = 60*60*nn }else if(uu=="M"){td = 60*nn }else if(uu=="S"){td = nn }else{stop("Please enter a correct string")} } if(nearest){ # round to closest interval as.POSIXct(round(as.double(x)/td)*td,origin="1970-01-01") }else{ # round to floor as.POSIXct(floor(as.double(x)/td)*td,origin="1970-01-01") } } # Fold the data together into one data frame fold_ts = function(...){ ll = (...) if(length(ll)>1){ x = Reduce(function(df1,df2) full_join(df1,df2,by="DateTime"), ll) }else{ x = ll[[1]] } cat("Your data are cleaned.\n") arrange(x, DateTime) }
3ed98e277c6ad80555a1d24810788bea45ea2a8e
a4c6332c239ea98e1e5cef105ba2c3befcfcf310
/WangzhenTools/R/WangzhenTools-package.r
b5c39a15dfe4ad5c13e0af3f03a35e58d083553d
[]
no_license
maxx0290/myfirstpackage
8f75f15159e15c7be70393b955349a4d1ece1cb4
168b76faedd741f89e3c7b7ab66b8a2f0f28d5c9
refs/heads/master
2021-04-28T02:27:08.931955
2018-03-10T01:22:58
2018-03-10T01:22:58
122,114,159
0
0
null
null
null
null
UTF-8
R
false
false
69
r
WangzhenTools-package.r
#' WangzhenTools. #' #' @name WangzhenTools #' @docType package NULL
267f65148b6498044d81ef54a646e946d7c6a5c1
db2b46e4e013ad57459645ff45d62e8a2afe9365
/R/scatter_libdepth.R
f92ac6bce545a4878acda39369b647b87ea7bcfd
[]
no_license
ahadkhalilnezhad/rimmi.rnaseq
b22aeab379094b7ce1e1b88820d19315b23bcc34
27e1ff9e9093203897abe168f26cb952bdfef606
refs/heads/master
2020-09-07T13:19:29.184587
2019-11-08T10:51:54
2019-11-08T10:51:54
null
0
0
null
null
null
null
UTF-8
R
false
false
1,165
r
scatter_libdepth.R
#' Plot clusters in 2 umaps with the point size corresponting to the library size #' #' This function allows you to see if the library size influences in your clustering #' #' @param Seurat_obj your Seurat object #' #' @return scatter plot with the library size correponding to the point size #' #' @keywords Seurat, single cell sequencing, RNA-seq, gene signature #' #' @examples #' #' scatter_libdepth(A07) #' #' @export #' scatter_libdepth <- function(Seurat_obj){ library(ggplot2) library(cowplot) df <- data.frame(umap1 = Seurat_obj@dr$umap@cell.embeddings[,1 ], umap2 = Seurat_obj@dr$umap@cell.embeddings[,2 ], cells = as.character(Seurat_obj@ident), lsize = Seurat_obj@meta.data$nUMI, ngene = Seurat_obj@meta.data$nGene ) p1 <- ggplot(df, aes(x = umap1, y = umap2, col = cells))+ geom_point(aes(size = lsize)) + scale_size_continuous(range = c(0.001, 3)) p2 <- ggplot(df, aes(x = umap1, y = umap2, col = cells))+ geom_point(aes(size = ngene)) + scale_size_continuous(range = c(0.001, 3)) plot_grid(p1, p2) }
ea7ccdfbf3c115e86afaa95f857ffeccde7bb87e
c4685427cf56a2fdaf436c481d4e7ee9a391d081
/ui.R
281250396110101140598a412c2a75de7edf7ef7
[]
no_license
makleks/newrepo
180c24eabf069088e976590fc5152958125508fb
2c974f2a51f05e0ccf6bb2c45dc1a0ca5547f4c7
refs/heads/master
2021-01-10T07:51:07.292760
2015-12-27T11:33:05
2015-12-27T11:33:05
48,642,553
0
1
null
null
null
null
UTF-8
R
false
false
1,195
r
ui.R
shinyUI( pageWithSidebar( headerPanel("Volume of Cuboid Calculator"), sidebarPanel( numericInput('width', 'length of the base of the cuboid in cm', 90, min = 50, max = 200, step = 5), #submitButton('Submit'), sliderInput('height', 'height of the cuboid in cm', 90, min = 50, max = 200, step = 5) ), mainPanel( tabsetPanel( tabPanel('Output', p(h3('Results of Calculation'), h4('The Area of the base of the cuboid in sqcm is'), verbatimTextOutput("inputValue"), h4('Which resulted in a calculation of the volume in cubic cm of '), textOutput("prediction") ) ), tabPanel('Documentation', p(h4("Area of Cuboid Calculator:")), br(), helpText("This application calculates the area of a cuboid given the base width and its height. The base of the cuboid is a square whose length is given as numeric input. The height of the cuboid is adjusted with the use of the slider.") ) ) ) ) )
6e65a947c75ae8670661a162fa602d1fa09bc427
e51a9c634d3a2fcf5b2a3b66d258b81c00ce10aa
/14a-impact-functions.R
fc8a912de8bc9eca8bc4bcc60963adf496fe2395
[]
no_license
bennysalo/MI
48aef59d7db4fb96120a9feb94aa8f7b95c7422a
ba07fe422d06fd9c92799e27d12799d2296f6f34
refs/heads/master
2020-05-22T23:27:41.118765
2018-02-17T10:22:42
2018-02-17T10:22:42
84,733,582
0
0
null
null
null
null
UTF-8
R
false
false
12,581
r
14a-impact-functions.R
# rm(list = ls()) # Define a model with the drug factor regressed on group get_impact_model <- function(base_model) { pt <- lavaanify(base_model) # Identify factors factors <- subset(pt, op == "=~") factors <- unique(factors$lhs) # Define regression paths reg_paths <- paste(factors, '~ group \n', collapse = " ") # Define model impact_model <- paste(base_model, '\n', reg_paths) } # Function for replacing the 'ustart' values in a parameter table # with the fitted coefficents from another parameter table # Returns a paramter table that can be used with 'lavaan:simulateData' # Setup for use in functions 'create_invariant_data' and 'create_biased_data' #c Takes arguments: # pt.frame = The paramenter table where a parameter should be replaced and then returned # pt.replacement = The parameter table from where the replacing parameter should be taken replace_coefs_in_pt <- function(pt.frame, pt.replacement) { require(lavaan) # Ensure the same order of parameters in both paramter tables order_frame <- order(pt.frame$op, pt.frame$lhs, pt.frame$rhs) order_replacement <- order(pt.replacement$op, pt.replacement$lhs, pt.replacement$rhs) frame <- pt.frame[order_frame, ] replacement <- pt.replacement[order_replacement, ] # Put in the same data.frame, side by side, (to avoid differing row numbers claiming differences) both <- cbind(frame[,2:4], replacement[,2:4]) # Continue only if the parameters are identical (otherwise give error message) if (!(identical(both[,1:3], both[,4:6]))) { stop("Table parameters do not match", call. = FALSE) } # Replace the 'ustart' values in the frame with the coefficients in the replacing parameter table frame$ustart <- replacement$est # Return in original order # and only the columns from output of a arbitrary model in lavaan:lavaanify return(frame[order(frame$id), names(lavaanify('factor =~ item'))]) } # Function for replacing a single paramenter. Takes arguments: # pt.frame = The paramenter table where a parameter should be replaced and then returned # pt.replacement = The parameter table from where the replacing parameter should be taken # lhs, op and rhs = column names in parameter tables used to identify parameter # Setup for use in function 'create_biased_data' replace_1_coef_in_pt <- function (pt.frame, pt.replacement, lhs, op, rhs = "") { # locate row number for parameter (to be changed) in both tables, grab that index i i_frame <- which(pt.frame$lhs == lhs & pt.frame$op == op & pt.frame$rhs == rhs) i_replacement <- which(pt.replacement$lhs == lhs & pt.replacement$op == op & pt.replacement$rhs == rhs) # Check that there is one (and only one) index for both tables if (length(i_frame) != 1 | length(i_replacement) != 1) { stop("No, or more than one, matching parameter", call. = FALSE) } # Make replacement pt.frame[i_frame, "ustart"] <- pt.replacement[i_replacement, "est"] return(pt.frame) } # Create data list for use in simulations. # Setup for use in functions 'create_invariant_data' and 'create_biased_data' # Takes arguments: # parameter table 1 and 2, the group sizes, the number of datasets to produce, and # labels for the groups (defaults to 1 & 2) create_data_list<- function (pt1, pt2, n1, n2, n_sets) { data_list <- list() for(i in 1:n_sets) { simulated_data.group1 <- simulateData(pt1, sample.nobs = n1) simulated_data.group2 <- simulateData(pt2, sample.nobs = n2) simulated_data <- rbind(simulated_data.group1, simulated_data.group2) # Add column with group membership - if labels are defined, use those simulated_data <- data.frame(simulated_data, group = rep(c(1, 2), times = c(n1, n2))) # Make all variables ordered simulated_data[c(1:length(simulated_data))] <- lapply(simulated_data[c(1:length(simulated_data))], ordered) # Add the latest simulated dataset to the list data_list[[i]] <- simulated_data } return(data_list) } # Create simulated datasets based on parameters from strong invariance model. # Takes arguments; # single_group = a fitted single group model # strong_fit = a fitted strong group model # n_sets = number of datasets to create create_invariant_data <- function(single_group, strong_fit, n_sets) { pt.single <- parameterTable(single_group) pt.strong <- parameterTable(strong_fit) # Create parameter tables for the two groups # Use single group model as frame and use parameter values from strong model # See function 'replace_coefs_in_pt' above pt.invariant1 <- replace_coefs_in_pt(pt.frame = pt.single, pt.replacement = pt.strong[pt.strong$group == 1, ]) pt.invariant2 <- replace_coefs_in_pt(pt.single, pt.strong[pt.strong$group == 2, ]) # Grab group sizes for the two groups n1 <- lavInspect(strong_fit, what = "nobs")[1] n2 <- lavInspect(strong_fit, what = "nobs")[2] # Use 'create_data_list' to simulate datasets invariant_data <- create_data_list(pt.invariant1, pt.invariant2, n1, n2, n_sets) return(invariant_data) } # Create simulated datasets based on parameters from configural invariance model, # exept factor means taken from strong invariance model. # Takes arguments; # single_group = a fitted single group model # strong_fit = a fitted strong group model # n_sets = number of datasets to create create_biased_data <- function(single_group, strong_fit, configural_fit, n_sets) { # Grab parameter tables from the three fitted models pt.single <- parameterTable(single_group) pt.strong <- parameterTable(strong_fit) pt.configural <- parameterTable(configural_fit) # Identify factors factors <- subset(pt.single, op == "=~") factors <- unique(factors$lhs) # Create parameter tables for groups 1 and 2 # with single group as frame and parameter values from configural model # See function 'replace_coefs_in_pt' above pt.biased1 <- replace_coefs_in_pt(pt.single, pt.configural[pt.configural$group == 1, ]) pt.biased2 <- replace_coefs_in_pt(pt.single, pt.configural[pt.configural$group == 2, ]) # Replace means with those from strong model. This to make the mean difference comparable # with the invariant data # See function 'replace_1_coef_in_pt' above for (i in 1:length(factors)) { pt.biased1 <- replace_1_coef_in_pt(pt.frame = pt.biased1, pt.replacement = pt.strong[pt.strong$group == 1,], lhs = factors[i], op = "~1") pt.biased2 <- replace_1_coef_in_pt(pt.frame = pt.biased2, pt.replacement = pt.strong[pt.strong$group == 2,], lhs = factors[1], op = "~1") } # Grab group sizes for the two groups n1 <- lavInspect(strong_fit, what = "nobs")[1] n2 <- lavInspect(strong_fit, what = "nobs")[2] # Simulate biased data using parameter tables biased_data <- create_data_list(pt.biased1, pt.biased2, n1, n2, n_sets) return(biased_data) } # Function for calculating difference in standardized coeffiecient # setup for use in function 'get_all_path_differences' # between invariant and biased datasets. Takes arguments: # reg.coef = the regression coefficient to analyze # sim.invariant = SimResult from runs on invariant data # sim.biased = SimResult from runs on biased data get_path_difference <- function (reg_coef, sim.invariant, sim.biased) { # pick standardized coefficients of the parameter defined by 'reg_coef' std_coeff.inv <- sim.invariant@stdCoef[, reg_coef] std_coeff.bias <- sim.biased@stdCoef[, reg_coef] # calculate Fisher's Z Fz.inv <- atanh(std_coeff.inv) Fz.bias <- atanh(std_coeff.bias) # Calculate mean, difference in means (using Fisher's Z) n.inv <- length(std_coeff.inv ) m.inv <- mean(Fz.inv) sd.inv <- sd(Fz.inv) se.inv <- sd(Fz.inv)/sqrt(length(Fz.inv)) n.bias <- length(std_coeff.bias) m.bias <- mean(Fz.bias) sd.bias <- sd(Fz.bias) se.bias <- sd(Fz.bias)/sqrt(length(Fz.bias)) diff <- mean(Fz.inv - Fz.bias) sd.diff <- sd(Fz.inv - Fz.bias) se.diff <- sd(Fz.inv - Fz.bias)/sqrt(length(Fz.bias)) # Create vector and convert back to standardized coefficient out <- c(m.inv, m.bias , diff , sd.inv, sd.bias, sd.diff, se.inv, se.bias, se.diff) out <- tanh(out) out <- matrix(out, 3,3, byrow = FALSE) out <- cbind(out, c(length(Fz.inv), length(Fz.bias), mean(c(length(Fz.inv), length(Fz.bias))))) rownames(out) <- c("Invariant datasets", "Biased datasets", "Difference") colnames(out) <- c("Mean", "sd", "se", "n of repl") return(out) } get_all_path_differences <- function(sim.invariant, sim.biased, impact_model) { require(purrr) pt <- lavaanify(impact_model) # Identify regressions regressions <- subset(pt, op == "~") regressions <- paste(regressions$lhs, regressions$op, regressions$rhs) # get rid of spaces regressions <- gsub(pattern = " ", replacement = "", x = regressions) results <- map(.x = regressions, .f = get_path_difference, sim.invariant = sim.invariant, sim.biased = sim.biased) names(results) <- regressions return(results) } # Function that will eventually be integrated to earlier step. Add info of base_model and data to the list. add_info <- function(results, base_model, used_data) { results[["base_model"]] <- base_model # move to earlier step results[["data"]] <- used_data # move to earlier step return(results) } # Do all impact analyses all_impact_analyses <- function(results, base_model, used_data, n_sets = 10) { results[["impact_model"]] <- get_impact_model(results[["base_model"]]) # Set up single group fit. No need to run the analysis. results[["single_group"]] <- cfa(model = results[["base_model"]], data = FinPrisonMales2, std.lv = TRUE, estimator = "WLSMV", do.fit = FALSE) results[["invariant_data"]] <- create_invariant_data(single_group = results[["single_group"]], strong_fit = results[["strong_fit"]], n_sets = n_sets) results[["biased_data"]] <- create_biased_data(single_group = results[["single_group"]], strong_fit = results[["strong_fit"]], configural_fit = results[["configural_fit"]], n_sets = n_sets) results[["invariant_fits"]] <- simsem::sim(model = results[["impact_model"]], rawData = results[["invariant_data"]], lavaanfun = "sem", std.lv = TRUE, estimator = "WLSMV") results[["biased_fits"]] <- simsem::sim(model = results[["impact_model"]], rawData = results[["biased_data"]], lavaanfun = "sem", std.lv = TRUE, estimator = "WLSMV") results[["groups"]] <- paste("Group 1 is " , lavInspect(results$strong_fit, what = "group.label")[1], " - Group 2 is", lavInspect(results$strong_fit, what = "group.label")[2]) results[["path_differences"]] <- get_all_path_differences(sim.invariant = results[["invariant_fits"]], sim.biased = results[["biased_fits"]], impact_model = results[["impact_model"]]) return(results) } #save.image("~/Dropbox/to aws/impact functions.RData") save.image("C:/Users/benny_000/Dropbox/to aws/MI-0-all functions and data.R.RData")
e149d00a75bc8240e23df103950f39736c4f7bdc
2b15d68409bf3983b1f3108cf2172117d9f9a39e
/scripts/Education-MR-MOE.R
d4c148b7311da5284fff46484c37071801c0e89e
[]
no_license
jahnvipatel1/ARDC-MR-MoE-main
2b90e27456912bcff1078c928df19637a9e46500
e6238b37009be9d9b4989246b07763185e8e648e
refs/heads/main
2023-06-17T09:00:19.509770
2021-07-20T18:55:24
2021-07-20T18:55:24
383,582,116
1
0
null
null
null
null
UTF-8
R
false
false
6,762
r
Education-MR-MOE.R
library(devtools) library(tidyverse) library(TwoSampleMR) library(ggnewscale) library(ggplot2) library(glue) library(ggpubr) #EXPOSURE DATA --------------------------------------------- education.file <- "~/Desktop/Lee2018educ.chrall.CPRA_b37.tsv" education_dat <- read_exposure_data( filename = education.file, sep = "\t", snp_col = "DBSNP_ID", beta_col = "BETA", se_col = "SE", effect_allele_col = "ALT", other_allele_col = "REF", eaf_col = "AF", pval_col = "P", samplesize_col = "N", chr_col = "CHROM", pos_col = "POS", phenotype_col = "TRAIT" ) #filter education_dat<- filter(education_dat, pval.exposure < 0.00000005) %>% distinct(SNP, .keep_all = TRUE) #CLUMP DATA education_dat <- clump_data(education_dat) #OUTCOME DATA --------------------------------------------- AD.file <- "~/Desktop/Kunkle2019load_stage123.chrall.CPRA_b37.tsv" AD_dat <- read_outcome_data( snps = education_dat$SNP, filename = AD.file, sep = "\t", snp_col = "DBSNP_ID", beta_col = "BETA", se_col = "SE", effect_allele_col = "ALT", other_allele_col = "REF", eaf_col = "AF", pval_col = "P", samplesize_col = "N", chr_col = "CHROM", pos_col = "POS" ) #HARMONISE DATA -------------------------------------------------------- education.dat <- harmonise_data(education_dat,AD_dat) #MR-MoE----------------------------------------------------------------- load("/Users/jahnvipatel/Downloads/rf.rdata") res <- mr_wrapper(education.dat) res_moe <- mr_moe(res,rf) #PREFORM MR ------------------------------------------------------------ res.mr <- mr(education.dat) #each MR method for each combination of exposure-outcome traits generate_odds_ratios(res.mr) #MAKE PLOTS ------------------------------------------------------------ #create a scatter plot res.mr <- mr(education.dat, method_list=c( "mr_ivw", "mr_weighted_mode", "mr_weighted_median", "mr_simple_median", "mr_simple_mode", "mr_egger_regression") ) p1 <- mr_scatter_plot(res.mr,education.dat) p1[[1]] ggsave(p1[[1]], file="educationscatterplot.png", width=7, height=8) view(education.dat) view(p1$NCFz7e.oQE1lc$data) mr_scatter_plot2 <- function(mrdat,res){ message("Plotting Scatters: ", mrdat$exposure[1], " - ", mrdat$outcome[1]) ## reoriante effect direction of negative exposure values d <- mrdat %>% mutate(beta.outcome = ifelse(beta.exposure < 0, beta.outcome * -1, beta.outcome), beta.exposure = ifelse(beta.exposure < 0, beta.exposure * -1, beta.exposure)) ## Make scatter plot ggplot(data = d, aes(x = beta.exposure, y = beta.outcome)) + geom_errorbar(aes(ymin = beta.outcome - se.outcome, ymax = beta.outcome + se.outcome), colour = "grey", width = 0) + geom_errorbarh(aes(xmin = beta.exposure - se.exposure, xmax = beta.exposure + se.exposure), colour = "grey", height = 0) + geom_point(aes(colour = "!mrpresso_keep")) + scale_colour_manual(values = c("black", "#CD534CFF")) + new_scale_color() + geom_abline(data = res, aes(intercept = a, slope = b, color = method, linetype = method), show.legend = TRUE) + scale_color_brewer(palette = "Set3") + labs(x = paste("SNP effect on\n", d$exposure[1]), y = paste("SNP effect on\n", d$outcome[1])) + theme_bw() + theme(legend.position = "bottom", legend.direction = "horizontal", text = element_text(size=8)) + guides(linetype = guide_legend(nrow = 1), colour_new = FALSE) } a<-c(0,0,-0.106,0.0842,0,0,0,0,0,0,0,0,0,0,0,0,0.0421,0.0842,0.0421,0,0.0853,0,0,0,0,0,0,0,0,0,0.0853,0,0,0,0,0,0,0,-0.0106,0,0,0,0,0) res_moe$NCFz7e.oQE1lc$estimates$a=a p <- mr_scatter_plot2(mrdat = education.dat, res = res_moe$NCFz7e.oQE1lc$estimates) p + facet_wrap(vars(selection)) + theme(legend.position = 'top') #create a forest plot res_single_educ <- mr_singlesnp(education.dat, all_method=c( "mr_ivw", "mr_weighted_mode", "mr_weighted_median", "mr_simple_median", "mr_simple_mode", "mr_egger_regression")) p2 <- mr_forest_plot(res_single_educ) p2[[1]] ggsave(p2[[1]], file="educationforestplot.png", width=7, height=20) view #create a funnel plot res_single_educ <- mr_singlesnp( education.dat, all_method=c("mr_ivw", "mr_weighted_mode", "mr_weighted_median", "mr_simple_median", "mr_simple_mode", "mr_egger_regression") ) p4 <- mr_funnel_plot(res_single_educ) p4[[1]] ggsave(p3[[1]], file="educationfunnelplot.png", width=7, height=7) res.filter <- res_single_educ %>% slice(1:304) res_moe2 <- subset(res_moe$NCFz7e.oQE1lc$estimates,select = -c(nsnp,ci_low,ci_upp,steiger_filtered,outlier_filtered,selection,method2,MOE,a)) res_methods <- paste0("All - ",res_moe2$method) res_moe2 <- subset(res_moe2,select=-c(method)) res_moe2 <- cbind(res_methods,res_moe2) colnames(res_moe2)[1] <- "SNP" exposure <- rep(c("Education"),times=c(44)) outcome <- rep(c("outcome"),times=c(44)) samplesize <- rep(c(63926),times=c(44)) res_moe3<- cbind(exposure,outcome,samplesize) res_moe_filter <- merge(res_moe2,res_moe3,by=0) res_moe_filter <- subset(res_moe_filter,select = -c(Row.names)) colnames(res_moe_filter)[6] <- "p" res.filter2 <- rbind(res.filter,res_moe_filter) p3 <- mr_funnel_plot(res.filter2) p3[[1]] p3a <- p3[[1]] + theme_bw() + theme(legend.position = 'bottom') steiger <- mr_funnel_plot(slice(res.filter2,-c(11,45,61,86,90,95,111,135,188,212,216,246,258,271,276,288))) steigera <- steiger[[1]] + theme_bw() + theme(legend.position = 'bottom') #steiger outlier <- mr_funnel_plot(slice(res.filter2,-c(9,11,41,42,45,61,81,86,95,135,143,188,216,258,276,288))) outliera <- outlier[[1]] + theme_bw() + theme(legend.position = 'bottom') #outlier both <- mr_funnel_plot(slice(res.filter2,-c(9,11,41,42,45,61,81,86,90,95,111,135,143,188,212,216,246,258,271,276,288))) botha <- both[[1]] + theme_bw() + theme(legend.position = 'bottom') #both ggpubr::ggarrange(p3a,steigera, outliera, botha,common.legend = T) #generate report mr_report(education.dat) #generate spreadsheet library(writexl) write_xlsx(res_moe$NCFz7e.oQE1lc$snps_retained,"\\Desktop\\snps MR-MOE.xlsx") write_xlsx(res_moe$w8C1MU.DWrQTt,"\\Desktop\\Education MR-MOE.xlsNCFz7e.oQE1lc)
3d892f5b09de9cd7f535141fe12f645c92b561e8
2a7e19a09c4c2b2a4495b8d55b7cc3792b756b82
/Exercise_1.R
634efc8d83c48211b3a8ce968f72f97e6065dd88
[]
no_license
rohitturankar/R_Projects
7b558dbc32088417ebe627e278fa15c13e761b22
e2d06d168c5eb1df8972503427aa9aa8541d0a47
refs/heads/master
2022-10-14T09:16:09.949255
2020-06-12T18:14:53
2020-06-12T18:14:53
271,861,227
0
0
null
null
null
null
UTF-8
R
false
false
826
r
Exercise_1.R
rm(list=ls()) getwd() setwd("C:/Users/user/Documents/R/Practical_1") dat08<-read.table("Sight2008.txt",sep = "\t",header=TRUE) dat09<-read.table("sight2009.txt",sep = "\t", header=TRUE) names(dat08) dim(dat08) str(dat08) summary(dat08) dat08[6,3] #If data frames is having different columns and rows add them using merge all=true dat<- merge(dat08, dat09, all=TRUE) dat #For fetching a column for data frame use square brackets temps<- dat[,"Temperature"] tempsF<- temps*9/5+32 id<- dat[,"Indiv_ID"] id #for adding a coloumn use cbind dat<-cbind(dat,tempsF) dat #Exporting data of data frame to Excel that can be readed. write.table(dat, "SightE.xls", sep = "\t", row.names = FALSE, col.names = TRUE) typeof(temps) length(dat) objects() names(dat) abcd<- list(1:3, "a", c(TRUE, FALSE, TRUE), c(2.3, 5.9)) names(abcd)
03e4ece14ef140941ad56730cb2fdc628b76be79
b7dba66d68ffa4f5b42038f48ec53ac0e91cf0c6
/code/chapter4/covariates_ran.R
5e4c3ed351456135a357beb48485b52b4a59d14a
[]
no_license
aarizvi/dissertation
46118d37e5e6d4923b6f1201836ddbb0475ba56b
de9fd7a8d092e8a7b1063212492e0487ee96a4cc
refs/heads/master
2020-04-05T19:18:48.746222
2019-03-24T18:05:25
2019-03-24T18:05:25
157,128,463
0
1
null
null
null
null
UTF-8
R
false
false
994
r
covariates_ran.R
outcomes <- c("TRM", "DRM", "OS", "PFS", "REL", "GVHD", "OF", "INF") time_var <- c("time to death", "time to death", "time to death", "time to relapse", "time to relapse", "time to death", "time to death", "time to death") covariates <- c("recipient age, BMI, graft source", "recipient age, disease status", "age, disease status, graft source", "recipient age, disease status", "conditioning regimen and intensity", "recipient age, donor age, BMI", "disease status, graft source", "age, BMI, CMV status") df <- setNames(data.frame( outcomes, time_var, covariates, stringsAsFactors = FALSE), c("Survival Outcomes", "Time Interval", "Covariates")) knitr::kable(df, caption="\\label{tab:models_run} Survival Models Analyzed", booktabs=TRUE) %>% kableExtra::kable_styling(latex_options="striped", font_size=9) #%>%
62c3a0a4a537df01a2c08d938662ad100ede720c
c00f3e0d8e09fa678391ea36b0af7019a3e61592
/lib/tests/HSV.R
9605fd772350831d3d02d2d2b45ef4ae229438e4
[]
no_license
jpchamps/Project_CatsVsDogs
e12c919210180647669be02da4df6dbb70d24ea2
4b4404e8ef6f2c5789cb387d6173869ac9f494d3
refs/heads/master
2021-01-16T01:07:51.881420
2016-03-12T18:49:37
2016-03-12T18:49:37
52,730,463
0
0
null
2016-02-28T16:19:43
2016-02-28T16:19:42
null
UTF-8
R
false
false
1,254
r
HSV.R
library(grDevices) library(e1071) # Convert 3d array of RGB to 2d matrix setwd("images") extract.features <- function(img){ mat <- imageData(img) mat_rgb <- mat dim(mat_rgb) <- c(nrow(mat)*ncol(mat), 3) mat_hsv <- rgb2hsv(t(mat_rgb)) nH <- 10 nS <- 6 nV <- 6 # Caution: determine the bins using all images! The bins should be consistent across all images. The following code is only used for demonstration on a single image. hBin <- seq(0, 1, length.out=nH) sBin <- seq(0, 1, length.out=nS) vBin <- seq(0, 0.005, length.out=nV) freq_hsv <- as.data.frame(table(factor(findInterval(mat_hsv[1,], hBin), levels=1:nH), factor(findInterval(mat_hsv[2,], sBin), levels=1:nS), factor(findInterval(mat_hsv[3,], vBin), levels=1:nV))) hsv_feature <- as.numeric(freq_hsv$Freq)/(ncol(mat)*nrow(mat)) # normalization return(hsv_feature) } labels <- read.table("annotations/list.txt",stringsAsFactors = F) n <- 200 X <- array(rep(0,n*360),dim=c(n,360)) for (i in 1:n){ img <- readImage(paste0(labels$V1[i],".jpg")) X[i,] <- extract.features(img) } X <- as.data.frame(X) y <- as.factor(labels$V3[1:n]) svm.model<-svm(x = X[,1:10],y = y,kernel="linear",scale=F)
581155b3ef49605464e35e07fa89094a11a9349a
e2d4208757b01fd9afc23b37b2e249d224bb9a09
/previous_work/downsampling/LDA_analysis.R
b9dfdab7edc96c858bbeaf2cc7d322d88d2b132e
[]
no_license
ethanwhite/LDATS
221eec07a3f75a2f9f75cd80726dba89ddc3751f
e938d3ce0ac9fec9d8362fcf9136b1cb8e2cc512
refs/heads/master
2020-03-11T19:38:31.051741
2018-04-19T01:38:45
2018-04-19T01:38:45
130,213,339
0
0
null
2018-04-19T12:37:58
2018-04-19T12:37:58
null
UTF-8
R
false
false
2,272
r
LDA_analysis.R
# ============================================================================ #' Run through whole pipeline of LDA analysis, VEM method #' #' #' #' @param dat Table of integer data (species counts by time step) #' @param SEED set seed to keep LDA model runs consistent (default 2010) #' @param test_topics numbers of topics to test, of the form (topic_min, #' topic_max) #' @param dates vector of dates that correspond to time steps from 'dat' -- #' for plotting purposes #' @param n_chpoints number of change points the changepoint model should #' look for #' @param maxit max iterations for changepoint model (more=slower) #' #' @examples LDA_analysis(dat, 2010, c(2, 3), dates, 2) #' @export LDA_analysis_VEM <- function(dat, SEED, test_topics){ # choose number of topics -- model selection using AIC aic_values <- aic_model(dat, SEED, test_topics[1], test_topics[2]) # run LDA model ntopics <- filter(aic_values,aic == min(aic)) %>% select(k) %>% as.numeric() ldamodel <- LDA(dat, ntopics, control = list(seed = SEED), method = 'VEM') return(ldamodel) } # ============================================================================ #' Run through whole pipeline of LDA analysis, Gibbs method --- WIP #' #' #' #' @param dat Table of integer data (species counts by time step) #' @param ngibbs number of iterations for gibbs sampler -- must be greater #' than 200 (default 1000) #' @param test_topics numbers of topics to test, of the form (topic_min, #' topic_max) #' @param dates vector of dates that correspond to time steps from 'dat' -- #' for plotting purposes #' #' @examples LDA_analysis_gibbs(dat, 200, c(2, 3), dates) #' @export LDA_analysis_gibbs <- function(dat, ngibbs, test_topics, dates){ # choose number of topics -- model selection using AIC aic_values <- aic_model_gibbs(dat, ngibbs, test_topics[1], test_topics[2], F) # run LDA model ntopics <- filter(aic_values, aic == min(aic)) %>% select(k) %>% as.numeric() ldamodel <- gibbs.samp(dat.agg = dat, ngibbs = ngibbs, ncommun = ntopics, a.betas = 1, a.theta = 1) return(ldamodel) }
c7b81408cb8afbeca0dac3d33d83bdbf362c2697
d35be146b06ff6d133f8041f8667dfa9fff8c27c
/man/RunRobPCA.Rd
d89c791f45995219df9342c6eeb2969fce6c836d
[]
no_license
gmstanle/scRobustPCA
91d4b80b6a3da3276434bd79dfc84582cc8d8204
bc5be0e4f0cadecbe6f146cfc2cb78d96043d79c
refs/heads/master
2021-09-12T18:21:08.866688
2018-04-19T21:50:30
2018-04-19T21:50:30
125,469,525
0
0
null
null
null
null
UTF-8
R
false
true
1,220
rd
RunRobPCA.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rpca.R \name{RunRobPCA} \alias{RunRobPCA} \title{Perform robust PCA (Hubert PCA) with modified PC scores on a Seurat object} \usage{ RunRobPCA(object, npcs = 10, pc.genes = NULL, use.modified.pcscores = TRUE) } \arguments{ \item{object}{Seurat object} \item{npcs}{Number of principal components to calculate} \item{pc.genes}{Genes as input to PC. If \code{pc.genes==NULL}, the var.genes slot is used. If var.genes is empty and \code{pc.genes==NULL}, then all genes are used.} \item{use.modified.pcscores}{If \code{FALSE}, then the raw pc score output from robust PCA is used. If \code{TRUE}, then pc scores are replaced with the sum of the top 30 genes by positive loading minus the sum of the top 30 genes by negative loading. Each gene is scaled to a max of 1 and min of 0.} } \value{ A Seurat object with the 'rpca' field filled. } \description{ \code{scRobustPCA} performs the variant of robust PCA developed by Mia Hubert et al. on the gene expression matrix "data" in a Seurat object. Set reduction.type='rpca' in other Seurat functions to use the rPCA results, for example to calculate clusters with FindClusters. } \examples{ }
3296801d10e9a0b1bbaf1b7bd80c92dcfb01d50c
29585dff702209dd446c0ab52ceea046c58e384e
/mGSZ/R/toTable.R
424e37ba99331c21da7117c0b831b8cb6612e8f7
[]
no_license
ingted/R-Examples
825440ce468ce608c4d73e2af4c0a0213b81c0fe
d0917dbaf698cb8bc0789db0c3ab07453016eab9
refs/heads/master
2020-04-14T12:29:22.336088
2016-07-21T14:01:14
2016-07-21T14:01:14
null
0
0
null
null
null
null
UTF-8
R
false
false
878
r
toTable.R
toTable <- function(mGSZobj, sample = FALSE, m = c("mGSZ","mGSA","mAllez","WRS","SS","SUM","KS","wKS"), n = 5){ if(!mGSZobj$gene.perm.log & !sample & !mGSZobj$other.methods){ table <- mGSZobj$mGSZ[1:n,] } else if(mGSZobj$gene.perm.log & !sample & !mGSZobj$other.methods){ table <- mGSZobj$mGSZ.gene.perm[1:n,] } else if(mGSZobj$gene.perm.log & sample & !mGSZobj$other.methods){ table <- mGSZobj$mGSZ.sample.perm[1:n,] } else if(!mGSZobj$gene.perm.log & !sample & mGSZobj$other.methods){ m <- match.arg(m) table <- mGSZobj[[m]][1:n,] } else if(mGSZobj$gene.perm.log & !sample & mGSZobj$other.methods){ m <- match.arg(m) table <- mGSZobj$gene.perm[[m]][1:n,] } else if(mGSZobj$gene.perm.log & sample & mGSZobj$other.methods){ m <- match.arg(m) table <- mGSZobj$sample.perm[[m]][1:n,] } return(table) }
3da37d320bb9bd27093cebe199f7348bebb16cfd
a2c4c7b961cecf08c3e88ac9571d8ca60b0b1ce4
/futures_data.R
eb8b36b4e64303fae2144fbe43ddf74623beb1fc
[]
no_license
darobertson/r-commodity-index
d6a159245fc535512c7ce181d5473ae89d4e4c49
41844fe4a36b68924728d0bd5914a569ae158cc3
refs/heads/master
2021-01-20T01:35:59.171429
2016-05-16T09:04:44
2016-05-16T09:04:44
null
0
0
null
null
null
null
UTF-8
R
false
false
10,637
r
futures_data.R
# TODO: Add comment ############################################################################################################## rm(list=ls(all=TRUE)) options(width = 438L) library(WindR) w.start() #w.menu() #w.isconnected() #---------------- parameters ---------------- #can only roll within next 12 months, i.e., RollMonth <= FrontMonth < BackMonth Exchange = "SHF" Underlying = "CU" TradingCalendar="SHFE" RollMonth = c(4,8,12) FrontMonth = c(5,9,13) BackMonth = c(9,13,17) Exchange = "SHF" Underlying = "CU" TradingCalendar="SHFE" RollMonth = seq(1:12) FrontMonth = RollMonth + 1 BackMonth = RollMonth + 2 #historical price range DataStart = "2011-01-01" DataEnd = "2015-08-30" #roll days, i.e., trading day of the month TradingDayOfMonthRollStart = 6 TradingDayOfMonthRollEnd = 10 #index and ETN initial value IndexER0 = 1000 IndexTR0 = 1000 ETNIV0 = 100 #interest rate InterestRate = 0.0035 InterestTerm = 1 #ETN products LevInd = c("LEV1X", "INV1X") Leverage = c(1, -1) YearlyFee = c(0.0055, 0.0075) #---------------- ---------------- #trading day of an exchange TradingDate = w.tdays(DataStart, DataEnd, paste("TradingCalendar=",TradingCalendar,sep="")) if (Underlying == "CU") { IndexBenchmark = c("CUFI.WI", "NH0012.NHF") } else if (Underlying == "AL") { IndexBenchmark = c("ALFI.WI", "NH0013.NHF") } else { } #---------------- trading month and number of tradings in a month ----------------- FutureData = data.frame(cbind(as.character(TradingDate$Data[,1]), matrix(as.numeric(unlist(strsplit(as.character(TradingDate$Data[,1]),'-'))), ncol=3, byrow=TRUE))) colnames(FutureData) = c("TradingDate", "Year", "Month", "Day") FutureData$Year2 = as.numeric(substr(FutureData$Year,3,4)) FutureData$IsRollMonth = FutureData$Month %in% RollMonth #> head(TradingMonth) #Year Month IsRollMonth #1 2014 5 FALSE #21 2014 6 FALSE #41 2014 7 FALSE #64 2014 8 TRUE #85 2014 9 FALSE #106 2014 10 FALSE TradingMonth = unique(FutureData[,c("Year","Month")]) TradingMonth$IsRollMonth = TradingMonth$Month %in% RollMonth #trading day sequence in a year-month FutureData$TradingDayOfMonth = 0 for(i in 1:dim(TradingMonth)[1]) { ind = (FutureData$Year == TradingMonth[i,]$Year) & (FutureData$Month == TradingMonth[i,]$Month) if (sum(ind) > 0) { FutureData[ind,]$TradingDayOfMonth = seq(1,sum(ind)) } } #----------------- roll percentage weight change schedule ----------------- #> head(RollWeightSchedule) #Month TradingDayOfMonth PW1 #1 4 6 0.8 #2 8 6 0.8 #3 12 6 0.8 #4 4 7 0.6 #5 8 7 0.6 #6 12 7 0.6 nRollDays = TradingDayOfMonthRollEnd - TradingDayOfMonthRollStart + 1 RollWeight = data.frame(cbind(seq(TradingDayOfMonthRollStart,TradingDayOfMonthRollEnd), 1 - seq(1:nRollDays) / nRollDays)) RollWeightSchedule = merge(RollMonth, RollWeight) colnames(RollWeightSchedule) = c("Month", "TradingDayOfMonth", "PW1") #percentage weight schedule FutureData$PW1 = 1 for (i in 1:dim(RollWeightSchedule)[1]){ ind = (FutureData$Month == RollWeightSchedule[i,]$Month) & (FutureData$TradingDayOfMonth == RollWeightSchedule[i,]$TradingDayOfMonth) if (sum(ind) > 0) { FutureData[ind,]$PW1 = RollWeightSchedule[i,]$PW1 } } #----------------- roll contract schedule ----------------- #> RollContractSchedule #Month FrontMonth BackMonth IsRollMonth #1 1 5 9 FALSE #2 2 5 9 FALSE #3 3 5 9 FALSE #4 4 5 9 TRUE #5 5 9 13 FALSE #6 6 9 13 FALSE #7 7 9 13 FALSE #8 8 9 13 TRUE #9 9 13 17 FALSE #10 10 13 17 FALSE #11 11 13 17 FALSE #12 12 13 17 TRUE RollContractSchedule = data.frame(seq(1,12), rep(0,12), rep(0,12)) colnames(RollContractSchedule) = c("Month","FrontMonth","BackMonth") RollContractSchedule$IsRollMonth = RollContractSchedule$Month %in% RollMonth #"FrontMonth" and "BackMonth" are defined in parameters t1 = c(0, RollMonth) for (i in 1:length(RollMonth)) { ind = (t1[i] < RollContractSchedule$Month) & (RollContractSchedule$Month <= t1[i+1]) if (sum(ind) > 0) { RollContractSchedule[ind,]$FrontMonth = FrontMonth[i] RollContractSchedule[ind,]$BackMonth = BackMonth[i] } } #----------------- decide the front month and back month contracts ----------------- FutureData$FrontMonth = "" FutureData$BackMonth = "" for (i in 1:dim(RollContractSchedule)[1]) { # front month ind = (FutureData$Month == RollContractSchedule[i,]$Month) if(sum(ind) > 0) { t2 = floor(RollContractSchedule[i,]$FrontMonth / 13) FutureData[ind,]$FrontMonth = paste(Underlying, FutureData[ind,]$Year2+t2, formatC(RollContractSchedule[i,]$FrontMonth-12*t2, width=2, flag='0'), ".", Exchange, sep="") } # back month ind2 = ind & (FutureData$PW1 != 1) if(sum(ind2) > 0) { t2 = floor(RollContractSchedule[i,]$BackMonth / 13) FutureData[ind2,]$BackMonth = paste(Underlying, FutureData[ind2,]$Year2+t2, formatC(RollContractSchedule[i,]$BackMonth-12*t2, width=2, flag='0'), ".", Exchange, sep="") } # days after TradingDayOfMonthRollEnd of roll month ind3 = ind & FutureData$IsRollMonth & (FutureData$TradingDayOfMonth > TradingDayOfMonthRollEnd) if(sum(ind3) > 0) { t2 = floor(RollContractSchedule[i,]$BackMonth / 13) FutureData[ind3,]$FrontMonth = paste(Underlying, FutureData[ind3,]$Year2+t2, formatC(RollContractSchedule[i,]$BackMonth-12*t2, width=2, flag='0'), ".", Exchange, sep="") } } #----------------- get the price for both front month and back month ----------------- FutureData$FrontMonthPrice = 0 FutureData$BackMonthPrice = 0 FutureData$FrontMonthReturnHigh = 0 FutureData$BackMonthReturnHigh = 0 FutureData$FrontMonthReturnLow = 0 FutureData$BackMonthReturnLow = 0 fmc = unique(FutureData$FrontMonth) bmc = unique(FutureData$BackMonth) #front month price for (i in fmc) { if (i != "") { ind = (FutureData$FrontMonth==i) if (sum(ind > 0)) { start = as.character(head(FutureData[ind,]$TradingDate,n=1)) end = as.character(tail(FutureData[ind,]$TradingDate,n=1)) w_wsd_data = w.wsd(i, "open,high,low,close,pre_settle,settle,volume,oi", start, end, paste("TradingCalendar=",TradingCalendar,sep="")) FutureData[ind,]$FrontMonthPrice = w_wsd_data$Data$SETTLE print(paste("Front Month",i,start,end)) } } } #back month price for (i in bmc) { if (i != "") { ind = (FutureData$BackMonth==i) if (sum(ind > 0)) { start = as.character(head(FutureData[ind,]$TradingDate,n=1)) end = as.character(tail(FutureData[ind,]$TradingDate,n=1)) w_wsd_data = w.wsd(i, "open,high,low,close,pre_settle,settle,volume,oi", start, end, paste("TradingCalendar=",TradingCalendar,sep="")) FutureData[ind,]$BackMonthPrice = w_wsd_data$Data$SETTLE print(paste("Back Month",i,start,end)) } } } #----------------- get index benchmark for the underlying ----------------- #DataStart and DataEnd maybe different from start and end start = as.character(head(FutureData$TradingDate,n=1)) end = as.character(tail(FutureData$TradingDate,n=1)) for (i in IndexBenchmark) { w_wsd_data = w.wsd(i, "open,high,low,close,settle,volume,oi", start, end) FutureData[,i] = w_wsd_data$Data$CLOSE } #----------------- index calculation ----------------- nData = dim(FutureData)[1] #--- contract daily return --- #percentage weight of previous trading day, see spreadsheet pwt = FutureData[1:nData-1,]$PW1 pwt[FutureData[1:nData-1,]$PW1==0] = 1 #numerator, current trading day price, previous trading day weight FutureData$DifNum = c(1, pwt * FutureData[2:nData,]$FrontMonthPrice + (1 - pwt) * FutureData[2:nData,]$BackMonthPrice) #denominator, previous trading day weighted price FutureData$DifDen = c(1, FutureData[1:nData-1,]$PW1 * FutureData[1:nData-1,]$FrontMonthPrice + (1 - FutureData[1:nData-1,]$PW1) * FutureData[1:nData-1,]$BackMonthPrice) FutureData$CDR = FutureData$DifNum / FutureData$DifDen - 1 #--- Treasury Bill Return, use previous trading day interest rate --- FutureData$InterestRate = InterestRate FutureData$InterestDays = c(0, as.numeric(as.Date(FutureData[2:nData,]$TradingDate)-as.Date(FutureData[1:nData-1,]$TradingDate))) FutureData$TBR = c(0, (1 / (1 - FutureData[1:nData-1,]$InterestRate*InterestTerm/360)) ^ (FutureData[2:nData,]$InterestDays/InterestTerm) - 1) #index excess return FutureData$IndexER = IndexER0 * cumprod(1 + FutureData$CDR) #index total return FutureData$IndexTR = IndexTR0 * cumprod(1 + FutureData$CDR + FutureData$TBR) #----------------- ETN ----------------- CONST1 = paste("CONST1", LevInd, sep="_") CONST2 = paste("CONST2", LevInd, sep="_") IV = paste("IV", LevInd, sep="_") FutureData[,c(CONST1,CONST2,IV)] = rep(0,3*length(LevInd)) FutureData[1,IV] = rep(ETNIV0, length(LevInd)) #--- pricing model, depends on IV(T-1) and InterestRate(T-1) ---- for (i in 2:nData) { FutureData[i,CONST1] = FutureData[i-1,IV] * (1-YearlyFee/365)^FutureData[i,]$InterestDays * Leverage / FutureData[i,]$DifDen ir = (1 / (1 - FutureData[i-1,]$InterestRate*InterestTerm/360)) ^ (FutureData[i,]$InterestDays/InterestTerm) FutureData[i,CONST2] = FutureData[i-1,IV] * (1-YearlyFee/365)^FutureData[i,]$InterestDays * (ir - Leverage) FutureData[i,IV] = FutureData[i,CONST1] * FutureData[i,]$DifNum + FutureData[i,CONST2] } #----------------- plot ----------------- #cumulative return as reference to FutureData[1,i] IndexCol = c("IndexER", "IndexTR", IndexBenchmark, IV) mm = data.frame(as.Date(FutureData$TradingDate)) for (i in IndexCol) { mm[,i] = FutureData[,i] / FutureData[1,i] } colnames(mm) = c("TradingDate", IndexCol) #matrix plot matplot(mm[,IndexCol], type="l", xaxt="n", ylab="Cumulative Return", col=seq(1:length(IndexCol)), main=paste("BOCI Commodity Index", Underlying)) tt = paste(IndexCol, c(rep("",length(IndexCol)-length(YearlyFee)), paste(" Annual Fee = ",YearlyFee*100,"%",sep="")), sep="") legend("bottomleft",legend=tt, lty=1, col=seq(1:length(IndexCol)), cex=0.7) ind = c(1, seq(1:dim(TradingMonth)[1]) * floor(dim(mm)[1]/dim(TradingMonth)[1])) axis(1, at=ind, labels=mm[ind,1]) grid() # print(head(FutureData)) print(tail(FutureData))
2c31b44ae2045eae018ed10abbdae3cb774ba8a2
83855fae27ecebcdb8fa96d5607af6682948e98b
/Projects/DataCamp/visualizing_covid19.r
d7959287e6f65a372da67d6935b851aa2739dd49
[]
no_license
cgalmeida/machine-learning
94357827a312139b23410711e19e26a5bbd6b9ae
c9e90d9ae4714293a43c4d1e18d25db5b07d9391
refs/heads/main
2023-01-24T00:45:11.450453
2020-11-29T16:15:37
2020-11-29T16:15:37
305,099,220
0
0
null
null
null
null
UTF-8
R
false
false
316
r
visualizing_covid19.r
# Load the readr, ggplot2, and dplyr packages library(readr) library(ggplot2) library(dplyr) # Read datasets/confirmed_cases_worldwide.csv into confirmed_cases_worldwide confirmed_cases_worldwide <- read_csv("datasets/confirmed_cases_worldwide.csv") # Print out confirmed_cases_worldwide confirmed_cases_worldwide
81eb2e8d4e6d5b1158a31833d60920a9a11bd79c
8a733106605304b1326d1d46955a80a85764a7ee
/tests/testthat/test-viz_fitted_line.R
c21abac7701ca873472f8cd8f09bdeea5c77d060
[ "MIT" ]
permissive
EmilHvitfeldt/horus
2a7500335301d84f5c33de5da169c37a3d9584c4
86a9b9367d29be768e7573062cd2792fe2275027
refs/heads/master
2021-06-14T17:56:44.778717
2021-06-11T03:34:53
2021-06-11T03:34:53
146,670,308
15
0
null
null
null
null
UTF-8
R
false
false
857
r
test-viz_fitted_line.R
library(testthat) library(parsnip) library(workflows) set.seed(1234) knn_spec <- nearest_neighbor() %>% set_mode("regression") %>% set_engine("kknn") knn_fit <- workflow() %>% add_formula(mpg ~ disp) %>% add_model(knn_spec) %>% fit(mtcars) test_that("viz_fitted_line works", { vdiffr::expect_doppelganger( "viz_fitted_line simple", viz_fitted_line(knn_fit, mtcars), "viz_fitted_line" ) vdiffr::expect_doppelganger( "viz_fitted_line resolution", viz_fitted_line(knn_fit, mtcars, resolution = 20), "viz_fitted_line" ) vdiffr::expect_doppelganger( "viz_fitted_line expand", viz_fitted_line(knn_fit, mtcars, expand = 1), "viz_fitted_line" ) vdiffr::expect_doppelganger( "viz_fitted_line style", viz_fitted_line(knn_fit, mtcars, color = "pink", size = 4), "viz_fitted_line" ) })
1f5c7a85857b3b34b56ae9fd105e0d556b74c96d
9722196e4d8b6cad9458e9fca12dc2d310384569
/R-Scripts/twitter.R
6e49852e3def856b294b2eb121d80f9fc8810dd3
[]
no_license
siyafrica/Agenda_Setter
5ad77ae961adae806aea9844300f9f3116ca4c2c
fab67f768258237846e15097675aee4ad6e4c8f6
refs/heads/master
2021-01-10T20:21:07.873184
2014-10-30T19:56:19
2014-10-30T19:56:19
null
0
0
null
null
null
null
UTF-8
R
false
false
2,635
r
twitter.R
#I used this website for the main recipe to get my Twitter authorization: http://www.datablog.sytpp.net/2014/04/scraping-twitter-with-r-a-how-to/ rm(list=ls()) library(twitteR) library(RCurl) library(ROAuth) consumerKey <- "5yViSuSbNLBBDaUZA03wQ" consumerSecret <- "EuLTI61ncd8O7mmdpiStR86UtoXPgo6LMiFphEKeM" reqURL <- "https://api.twitter.com/oauth/request_token" accessURL <- "https://api.twitter.com/oauth/access_token" authURL <- "http://api.twitter.com/oauth/authorize" twitCred <- OAuthFactory$new(consumerKey=consumerKey, consumerSecret=consumerSecret, requestURL=reqURL, accessURL=accessURL, authURL=authURL) twitCred$handshake() #Retrieve the first 200 tweets for the folowing profiles johnTweets <- userTimeline("John", n = 200) johnDataFrame <- twListToDF(johnTweets) write.csv(johnDataFrame, file="john.csv") head(johnDataFrame) barryTweets <- userTimeline("barrybateman", n = 200) barryDataFrame <- twListToDF(barryTweets) write.csv(barryDataFrame, file="barry.csv") head(barryDataFrame) robbieTweets <- userTimeline("702JohnRobbie", n = 200) robbieDataFrame <- twListToDF(robbieTweets) write.csv(robbieDataFrame, file="robbie.csv") head(robbieDataFrame) rediTweets <- userTimeline("RediTlhabi", n = 200) rediDataFrame <- twListToDF(rediTweets) write.csv(rediDataFrame, file="robbie.csv") head(rediDataFrame) ferialTweets <- userTimeline("ferialhaffajee", n = 200) ferialDataFrame <- twListToDF(ferialTweets) write.csv(ferialDataFrame, file="ferial.csv") head(ferialDataFrame) leanneTweets <- userTimeline("LeanneManas", n = 200) leanneDataFrame <- twListToDF(leanneTweets) write.csv(leanneDataFrame, file="leanne.csv") head(leanneDataFrame) mandyTweets <- userTimeline("MandyWiener", n = 200) mandyDataFrame <- twListToDF(mandyTweets) write.csv(mandyDataFrame, file="mandy.csv") head(mandyDataFrame) ulrichTweets <- userTimeline("UlrichJvV", n = 200) ulrichDataFrame <- twListToDF(ulrichTweets) write.csv(ulrichDataFrame, file="ulrich.csv") head(ulrichDataFrame) stephenTweets <- userTimeline("StephenGrootes", n = 200) stephenDataFrame <- twListToDF(stephenTweets) write.csv(stephenDataFrame, file="stephan.csv") head(stephenDataFrame) akiTweets <- userTimeline("akianastasiou", n = 200) akiDataFrame <- twListToDF(akiTweets) write.csv(akiDataFrame, file="aki.csv") head(akiDataFrame) sportTweets <- userTimeline("Sport24News", n = 200) sportDataFrame <- twListToDF(sportTweets) write.csv(sportDataFrame, file="sport.csv") head(sportDataFrame)
5f7c76d5b2b82968e91501477b1076bd736243ad
ed84e202329a582d370c29daf5bd6fbb360fe2b3
/R/praise.R
788d44343926a65b480b485c46bf34fd642c3961
[ "MIT" ]
permissive
kristyrobledo/praiseMe
a01658e9718daa0d9cc7a01307ab723cbf332f01
b4c6cbd5b8d24b8413a3bae6b5ddb7f24aaab5cb
refs/heads/master
2020-09-30T10:57:50.435756
2019-12-11T06:56:02
2019-12-11T06:56:02
227,273,894
0
0
null
null
null
null
UTF-8
R
false
false
890
r
praise.R
#' Delivers praise #' #' @description This function is useful when you are #' feeling sad, and would like to recieve some praise. #' @param name Text string of the name I would like to praise #' @param punctuation This is our punctionation as a text input #' @return Returns text string with praise #' @export #' #' @examples #' praise(name = "Kristy", punctuation="!") #' praise <-function(name, punctuation="!"){ glue::glue("You're the best, {name}{punctuation}") } ## code >Insert royxygen skeleton ## devtools::document() ## license - mit license ## usethis::use_mit_license("Kristy Robledo") # in the terminal: ##git config --global user.name 'kristy.robledo' ##git config --global user.email 'robledo.kristy@gmail.com' ##git config --global --list #this is stolen from github repo: #git remote add origin https://github.com/kristyrobledo/praiseMe.git #git push -u origin master
a1e092b33d483dc46f5ac080ef4ae9f61a4704c7
b05784abd2d22efa58aca731e276ab4b722ddeb6
/plot2.R
f9d5c273463dffc7aaf61adf62df521073e6f96e
[]
no_license
luisepultura/ExData_Plotting1
08162d297350befe006242b9b084690100c878da
f289842078c2c03197d919f019959afcb81d8f07
refs/heads/master
2021-01-23T16:40:28.818390
2014-11-07T20:30:33
2014-11-07T20:30:33
null
0
0
null
null
null
null
UTF-8
R
false
false
563
r
plot2.R
#load libraries library(sqldf) fileName<-"household_power_consumption.txt" #load data data<-read.csv.sql(fileName, sql = "select * from file where Date = '1/2/2007' or Date = '2/2/2007' ", header=TRUE,sep=";") ##create a datetime variable data$DateTime<-strptime(paste(data$Date,data$Time),format = "%d/%m/%Y %H:%M:%S") #plot2 png(file="plot2.png", bg = "transparent", width = 480, height = 480, units = "px") with(data,plot(DateTime,Global_active_power,xlab="",ylab="Global Active Power (Kilowatts)",type="l")) dev.off()
de4a2e72335909c98e9e990e4a181870146d099e
e715b2171a8ffca7214101f21bbaedf6dfd77a2d
/RStudio/SEM II/Lab 8/8.R
81cec01ff88070a1a7596d31c5a10dffdeb6b8f6
[]
no_license
r-harini/Code
17de2f9d671593cd86d023b053e5b13a82d72620
3e2572b34a7dc10863efad9a84646f47d20082ac
refs/heads/master
2021-06-18T01:03:09.808004
2021-04-06T05:52:41
2021-04-06T05:52:41
194,418,227
0
0
null
null
null
null
UTF-8
R
false
false
837
r
8.R
rm(list=ls()) setwd("C:/Code/RStudio/SEM II/Lab 8") data <- read.csv("iris.csv",row.names=1) #as it is distance based metric, we scale to obtain better accuracy. df <- scale(data) #computing dis-similarity matrix dissim <- dist(df, method = 'euclidean') hierClust <- hclust(dissim, method = 'complete') plot(hierClust) cluster <- cutree(hierClust, k = 3) #minimize inter-cluster distance and maximize intra-cluster distance library(clValid) #higher the dunn index, more compact(better) the clusters are dunn(dissim, cluster) # plot(hclust_avg) rect.hclust(hierClust, k = 3, border = 2:4) abline(h = 3, col = 'red') Kmax <- 10 D <- rep(0,Kmax) for (i in 2:Kmax){ cluster<- cutree(hierClust, k=i) D[i] <- dunn(dissim, cluster) } plot(2:Kmax,D[2:Kmax],type="b",pch=19) # Best value of k is the one with the ighest Dunn index
bee45af31655bb676168afbf78380609706c47a3
20fb140c414c9d20b12643f074f336f6d22d1432
/man/NISTpascalSecTOslugPerFtSec.Rd
49db86c1af6706e27a43ffca454b9654698bb855
[]
no_license
cran/NISTunits
cb9dda97bafb8a1a6a198f41016eb36a30dda046
4a4f4fa5b39546f5af5dd123c09377d3053d27cf
refs/heads/master
2021-03-13T00:01:12.221467
2016-08-11T13:47:23
2016-08-11T13:47:23
27,615,133
0
0
null
null
null
null
UTF-8
R
false
false
878
rd
NISTpascalSecTOslugPerFtSec.Rd
\name{NISTpascalSecTOslugPerFtSec} \alias{NISTpascalSecTOslugPerFtSec} \title{Convert pascal second to slug per foot second } \usage{NISTpascalSecTOslugPerFtSec(pascalSec)} \description{\code{NISTpascalSecTOslugPerFtSec} converts from pascal second (Pa * s) to slug per foot second [slug/(ft * s)] } \arguments{ \item{pascalSec}{pascal second (Pa * s) } } \value{slug per foot second [slug/(ft * s)] } \source{ National Institute of Standards and Technology (NIST), 2014 NIST Guide to SI Units B.8 Factors for Units Listed Alphabetically \url{http://physics.nist.gov/Pubs/SP811/appenB8.html} } \references{ National Institute of Standards and Technology (NIST), 2014 NIST Guide to SI Units B.8 Factors for Units Listed Alphabetically \url{http://physics.nist.gov/Pubs/SP811/appenB8.html} } \author{Jose Gama} \examples{ NISTpascalSecTOslugPerFtSec(10) } \keyword{programming}
4dc3cfb53e86e3e3a536fbfaf38986a4760aa4a9
1c021e92bc426479ec85455835ba10ca7c9615fc
/2.scrap_youtube.R
fefd212ff0c6f39b19e1979d2377262f266ce601
[ "MIT" ]
permissive
KeunhoLee/dtcu4_first_ep
38188e53528fe6bb1fa77c7138f148036dd79232
a9e05af10bb7f1dde38fec8208db584990f677ab
refs/heads/main
2023-06-18T22:33:14.536846
2021-07-23T08:09:53
2021-07-23T08:09:53
386,939,182
0
0
null
null
null
null
UTF-8
R
false
false
1,038
r
2.scrap_youtube.R
library('rvest') library('RSelenium') library('stringr') library('dplyr') library('lubridate') DATA_ROOT <- "./data" SRC_ROOT <- "." SOURCE_NAME <- "youtube" timestamp <- strftime(now(), format="%Y%m%d%H%M%S") file_name <- str_interp("${DATA_ROOT}/${SOURCE_NAME}_${timestamp}.rds") # source functions -------------------------------------------------------- source(str_interp('${SRC_ROOT}/youtube_utils.R'), encoding = 'UTF-8') # code run ---------------------------------------------------------------- #remDr$server$stop() #remDr$client$open() # remDr$client$screenshot(display = TRUE) remDr <- fn_start_driver(4443L) # URL MAIN_URL <- "https://www.youtube.com/watch?v=Tnp_2FceTlQ" init_page_to_crawl(remDr, MAIN_URL) open_all_details(remDr) reply_list <- list() # open_all_details(remDr) page_src <- remDr$client$getPageSource() replies <- get_replies(page_src) remDr$server$stop() remDr$client$close() rm(remDr) gc() # save result ------------------------------------------------------------- saveRDS(replies, file_name)
4acc482b021c54727abbe453d0320bdbcc64a6da
efca2158ca2f34f4ccdb99ada1099595c3877862
/src/titanic_deck_plot.R
435eb5f945028fcbab4c17d85867695917889309
[ "MIT" ]
permissive
UBC-MDS/DSCI_532_GROUP_109_R
50d4142ca97f66add3b6692a19233a4e694efcff
ffdd32b11c69e17fac848ab75d12ea114b241d7b
refs/heads/master
2020-09-26T08:49:27.843773
2019-12-14T19:21:44
2019-12-14T19:21:44
226,220,727
0
3
MIT
2019-12-14T19:21:45
2019-12-06T01:28:09
R
UTF-8
R
false
false
1,033
r
titanic_deck_plot.R
library(tidyverse) library(ggplot2) # plot survival rate by deck level make_deck_plot <- function() { titanic_deck_df = read.csv("data/wrangled_titanic_df.csv") titanic_deck_df$deck <- factor(titanic_deck_df$deck, levels = c( "G", "F", "E", "D", "C", "B", "A")) survival_deck <- titanic_deck_df %>% group_by(deck) %>% summarise(stat = mean(survived)) ggplot(survival_deck, aes(x = deck, y = stat*100)) + geom_bar(stat = "identity", width = 0.5, color = "blue", fill = "blue") + labs(x = "Deck", y = "Rate of Survival (%)", title = "Survival Rate by Deck") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "grey"), plot.title = element_text(hjust = 0.5)) + coord_flip() }
c457a67850fceb6c38ce4bca78b16bb19af39e22
7a7375245bc738fae50df9e8a950ee28e0e6ec00
/man/LGA__Year_labourForceParticipation.Rd
827573b8f93ee4ecdece49ec97255b565b710045
[]
no_license
HughParsonage/Census2016.DataPack.TimeSeries
63e6d35c15c20b881d5b337da2f756a86a0153b5
171d9911e405b914987a1ebe4ed5bd5e5422481f
refs/heads/master
2021-09-02T11:42:27.015587
2018-01-02T09:01:39
2018-01-02T09:02:17
112,477,214
3
0
null
null
null
null
UTF-8
R
false
true
459
rd
LGA__Year_labourForceParticipation.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/LGA__Year_labourForceParticipation.R \docType{data} \name{LGA__Year_labourForceParticipation} \alias{LGA__Year_labourForceParticipation} \title{by LGA, Year} \format{1,689 observations and 3 variables.} \usage{ LGA__Year_labourForceParticipation } \description{ Labour by LGA, Year #' @description Force by LGA, Year #' @description Participation by LGA, Year } \keyword{datasets}
2c98fe2ae0006bd43a0906274f4823cd6787d1a9
a9a9af4f010a883720f70391d2af66f437cb15c3
/man/retrieve_validation_set_from_db_for_emulator.Rd
726ec412d958cd73efcf363c4784db5a462fb80f
[]
no_license
kalden/spartanDB
ad4162c78ef54170c21c08a8a7a822fafc457636
bc698715cdce55f593e806ac0c537c3f2d59ac7a
refs/heads/master
2020-03-26T23:32:14.724243
2019-02-20T11:05:17
2019-02-20T11:05:17
145,549,860
0
0
null
null
null
null
UTF-8
R
false
true
995
rd
retrieve_validation_set_from_db_for_emulator.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/emulation_generation.R \name{retrieve_validation_set_from_db_for_emulator} \alias{retrieve_validation_set_from_db_for_emulator} \title{To demonstrate use of emulator, we return validation set from the database to show how the emulator can make predictions on output} \usage{ retrieve_validation_set_from_db_for_emulator(dblink, parameters, measures, experiment_id) } \arguments{ \item{dblink}{A link to the database in which this table is being created} \item{parameters}{The parameters of the simulation that are being analysed} \item{measures}{The measures of the simulation that are being assessed} \item{experiment_id}{ID of the experiment for which the validation set is being returned} } \value{ Set of parameter values that can be used to make predictions } \description{ To demonstrate use of emulator, we return validation set from the database to show how the emulator can make predictions on output }
4166e35062082f3edd3e1c62f745fa1603bbeb90
0142ea48c3ca7a18da74e9e67afc9b6a2e830588
/hwscript.R
5720d0a63fcf0b17e2010d96682a5bb5d190c584
[]
no_license
yechenghao/RepData_PeerAssessment1
5f0b9c7516df4eb40e6ae65858404ff29aba8377
17b0ae4bc4a9940fbd547933462fa805754a6602
refs/heads/master
2020-03-22T16:07:40.663436
2018-07-10T02:04:12
2018-07-10T02:04:12
140,304,623
0
0
null
2018-07-09T15:22:59
2018-07-09T15:22:59
null
UTF-8
R
false
false
3,046
r
hwscript.R
# wk 2 assignment from Reproducible Research #required libraries for this exercise library(lubridate) library(dplyr) library(ggplot2) # Loading and processing the data activity<-read.table("activity.csv", sep=",", header=TRUE) activity$date <- ymd(activity$date) # what is the mean total number of steps taken per day? # for this part of the assignment, you can ignore missing values in the dataset # 1. calculate the total number of steps taken per day # 2. make a histogram of the total number of steps taken per day # 3. calculate and report the mean and median of the total number of steps taken per day daily_step_summary <-activity %>% filter(!is.na(steps)) %>% group_by(date) %>% summarize(total_steps=sum(steps)) ggplot(data=daily_step_summary, aes(x=date, y=total_steps)) + geom_bar(stat="identity") mean(daily_step_summary$total_steps) median(daily_step_summary$total_steps) # what is the average daily activity pattern? # 1. Make a time series plot (type="l") of the 5-minute interval (x-axis) and the average number # of steps taken, averaged across all days (y-axis) # 2. which 5-minute interval, on average across all days in the dataset, contains the # maximum number of steps? interval_step_summary<-activity %>% filter(!is.na(steps)) %>% group_by(interval) %>% summarize(interval_mean_steps = ceiling(mean(steps))) ggplot(data=interval_step_summary, aes(x=interval, y=interval_mean_steps)) + geom_line() interval_step_summary$interval[which.max(interval_step_summary$interval_mean_steps)] interval_step_summary$interval_mean_steps[which.max(interval_step_summary$interval_mean_steps)] # calculate number of missing values sum(is.na(activity$steps)) # imputing missing values activity_copy<-activity activity_copy$steps[is.na(activity$steps)] <- (activity %>% filter(is.na(steps)) %>% left_join(interval_step_summary, by="interval"))$interval_mean_steps daily_step_summary_nafilled <-activity_copy %>% group_by(date) %>% summarize(total_steps=sum(steps)) ggplot(data=daily_step_summary_nafilled, aes(x=date, y=total_steps)) + geom_bar(stat="identity") mean(daily_step_summary_nafilled$total_steps) median(daily_step_summary_nafilled$total_steps) # Are there differences in activity pattern between weekdays and weekends? activity_copy_wdays<-activity_copy %>% mutate(day_of_week = wday(date, label=TRUE)) %>% mutate(day_class = if_else(day_of_week=="Sat"| day_of_week=="Sun", "weekend", "weekday")) activity_copy_wdays$day_class <- as.factor(activity_copy_wdays$day_class) interval_step_summary_wday <- activity_copy_wdays %>% group_by(day_class, interval) %>% summarize(interval_mean_steps = ceiling(mean(steps))) ggplot(data=interval_step_summary_wday, aes(x=interval, y=interval_mean_steps)) + geom_line() + facet_grid(.~day_class)
c6bcfd5a2b836bc0669163e637b05610efc7a7a1
4e302606dc7bb42178651bdddb28b5d1f14d51d1
/apps/ui/ui_06.R
e1d0f28e979f12a52cb1a82fd71720efff3f78a7
[]
no_license
jcheng5/shiny-training-rstudioconf-2018
5bf2092d661ae89c56ec88eddb8310fe044bcae4
2966e76519e8c12eefacd036979d49146b25bd6f
refs/heads/master
2021-09-06T02:17:46.639529
2018-02-01T16:24:07
2018-02-01T16:24:07
118,834,801
47
23
null
2018-01-29T07:41:02
2018-01-24T23:22:32
R
UTF-8
R
false
false
1,000
r
ui_06.R
library(shiny) # Define function that takes a YouTube URL,title, and description --- # and returns a thumbnail frame, implemented using a template videoThumbnail <- function(videoUrl, title, description) { htmltools::htmlTemplate("youtube_thumbnail_template.html", videoUrl = videoUrl, title = title, description = description) } # Define UI for YouTube player -------------------------------------- ui <- fluidPage( h1("Random videos"), fluidRow( column(6, videoThumbnail("https://www.youtube.com/embed/hou0lU8WMgo", "You are technically correct", "The best kind of correct!" ) ), column(6, videoThumbnail("https://www.youtube.com/embed/4F4qzPbcFiA", "Admiral Ackbar", "It's a trap!" ) ) ) ) # Define server logic ----------------------------------------------- server <- function(input, output, session) { } # Run the app ------------------------------------------------------- shinyApp(ui, server)
1f536095e1729eb01886eb54fd8b48a8a8e51e6d
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/dtwclust/R/DISTANCES-lb-improved.R
bea7dae06a620deae3b9fb472b5c8e1737ba38c3
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
false
6,927
r
DISTANCES-lb-improved.R
#' Lemire's improved DTW lower bound #' #' This function calculates an improved lower bound (LB) on the Dynamic Time Warp (DTW) distance #' between two time series. It uses a Sakoe-Chiba constraint. #' #' @export #' #' @param x A time series (reference). #' @param y A time series with the same length as `x` (query). #' @param window.size Window size for envelope calculation. See details. #' @param norm Vector norm. Either `"L1"` for Manhattan distance or `"L2"` for Euclidean. #' @param lower.env Optionally, a pre-computed lower envelope for **`y`** can be provided (non-proxy #' version only). See [compute_envelope()]. #' @param upper.env Optionally, a pre-computed upper envelope for **`y`** can be provided (non-proxy #' version only). See [compute_envelope()]. #' @param force.symmetry If `TRUE`, a second lower bound is calculated by swapping `x` and `y`, and #' whichever result has a *higher* distance value is returned. The proxy version can only work if #' a square matrix is obtained, but use carefully. #' @template error-check #' #' @details #' #' The reference time series should go in `x`, whereas the query time series should go in `y`. #' #' If the envelopes are provided, they should be provided together. If either one is missing, both #' will be computed. #' #' @template window #' #' @return The improved lower bound for the DTW distance. #' #' @template proxy #' #' @section Note: #' #' The lower bound is only defined for time series of equal length and is **not** symmetric. #' #' If you wish to calculate the lower bound between several time series, it would be better to use #' the version registered with the `proxy` package, since it includes some small optimizations. The #' convention mentioned above for references and queries still holds. See the examples. #' #' The proxy version of `force.symmetry` should only be used when only `x` is provided or both `x` #' and `y` are identical. It compares the lower and upper triangular of the resulting distance #' matrix and forces symmetry in such a way that the tightest lower bound is obtained. #' #' @references #' #' Lemire D (2009). ``Faster retrieval with a two-pass dynamic-time-warping lower bound .'' *Pattern #' Recognition*, **42**(9), pp. 2169 - 2180. ISSN 0031-3203, #' \url{http://dx.doi.org/10.1016/j.patcog.2008.11.030}, #' \url{http://www.sciencedirect.com/science/article/pii/S0031320308004925}. #' #' @examples #' #' # Sample data #' data(uciCT) #' #' # Lower bound distance between two series #' d.lbi <- lb_improved(CharTraj[[1]], CharTraj[[2]], window.size = 20) #' #' # Corresponding true DTW distance #' d.dtw <- dtw(CharTraj[[1]], CharTraj[[2]], #' window.type = "sakoechiba", window.size = 20)$distance #' #' d.lbi <= d.dtw #' #' # Calculating the LB between several time series using the 'proxy' package #' # (notice how both argments must be lists) #' D.lbi <- proxy::dist(CharTraj[1], CharTraj[2:5], method = "LB_Improved", #' window.size = 20, norm = "L2") #' #' # Corresponding true DTW distance #' D.dtw <- proxy::dist(CharTraj[1], CharTraj[2:5], method = "dtw_basic", #' norm = "L2", window.size = 20) #' #' D.lbi <= D.dtw #' lb_improved <- function(x, y, window.size = NULL, norm = "L1", lower.env = NULL, upper.env = NULL, force.symmetry = FALSE, error.check = TRUE) { norm <- match.arg(norm, c("L1", "L2")) if (length(x) != length(y)) stop("The series must have the same length") window.size <- check_consistency(window.size, "window") if (is_multivariate(list(x, y))) stop("lb_improved does not support multivariate series.") if (error.check) { check_consistency(x, "ts") check_consistency(y, "ts") } if (is.null(lower.env) || is.null(upper.env)) { envelopes <- compute_envelope(y, window.size = window.size, error.check = FALSE) lower.env <- envelopes$lower upper.env <- envelopes$upper } else { check_consistency(lower.env, "ts") check_consistency(upper.env, "ts") if (length(lower.env) != length(x)) stop("Length mismatch between 'x' and the lower envelope") if (length(upper.env) != length(x)) stop("Length mismatch between 'x' and the upper envelope") } p <- switch(norm, L1 = 1L, L2 = 2L) d <- .Call(C_lbi, x, y, window.size, p, lower.env, upper.env, PACKAGE = "dtwclust") if (force.symmetry) { d2 <- lb_improved(x = y, y = x, window.size = window.size, norm = norm, error.check = FALSE) if (d2 > d) d <- d2 # nocov } # return d } # ================================================================================================== # Loop without using native 'proxy' looping (to avoid multiple calculations of the envelope) # ================================================================================================== lb_improved_proxy <- function(x, y = NULL, window.size = NULL, norm = "L1", ..., force.symmetry = FALSE, pairwise = FALSE, error.check = TRUE) { x <- tslist(x) if (is.null(y)) y <- x else y <- tslist(y) if (length(x) == 0L || length(y) == 0L) stop("Empty list received in x or y.") # nocov start if (error.check) check_consistency(c(x,y), "tslist") if (is_multivariate(c(x,y))) stop("lb_improved does not support multivariate series.") # nocov end symmetric <- FALSE fill_type <- mat_type <- dim_names <- NULL # avoid warning about undefined globals eval(prepare_expr) # UTILS-expressions.R # adjust parameters for this distance norm <- match.arg(norm, c("L1", "L2")) window.size <- check_consistency(window.size, "window") envelopes <- lapply(y, function(s) { compute_envelope(s, window.size, error.check = FALSE) }) lower.env <- lapply(envelopes, "[[", "lower") upper.env <- lapply(envelopes, "[[", "upper") # calculate distance matrix distance <- "LBI" # read in C++, can't be temporary! distargs <- list( p = switch(norm, "L1" = 1L, "L2" = 2L), len = length(x[[1L]]), window.size = window.size, lower.env = lower.env, upper.env = upper.env ) num_threads <- get_nthreads() .Call(C_distmat_loop, D, x, y, distance, distargs, fill_type, mat_type, num_threads, PACKAGE = "dtwclust") # adjust D's attributes if (pairwise) { dim(D) <- NULL class(D) <- "pairdist" } else { dimnames(D) <- dim_names class(D) <- "crossdist" } if (force.symmetry && !pairwise) { if (nrow(D) != ncol(D)) warning("Unable to force symmetry. Resulting distance matrix is not square.") # nocov else .Call(C_force_lb_symmetry, D, PACKAGE = "dtwclust") } attr(D, "method") <- "LB_Improved" # return D }
cdf8f3870eec237e68d9f7e4a79e59328ddce3a3
40313f5eec63c4a2e28961181b72881f748fc02c
/man/asset_data.Rd
f98411cb00a25e00c3cf5e9ad56661e1a7a51099
[]
no_license
snowvil/HenryQuant
00e6050a2905e37a9cfa248a02c43ff08114dccf
e6492fd82ca9eafd34662b43fc30c76c5cd548f3
refs/heads/master
2021-06-09T21:39:47.510151
2021-04-06T07:42:55
2021-04-06T07:42:55
143,132,372
0
0
null
2018-08-01T09:13:22
2018-08-01T09:13:22
null
UTF-8
R
false
false
558
rd
asset_data.Rd
\name{asset_data} \alias{asset_data} \docType{data} \title{Gloal Asset Return Data} \description{Daily data of ten global asset return data beginning on 1993-01-01 and ending 2017-12-31. The ETF price was used first, and public funds and index prices were used before listing. All returns include dividends. } \format{xts type with daily observations} \details{ The indexes are: US Equity, Europe Equity, Japan Equity, EM Equity, US LongTerm Bond, US MidTerm Bond, US REITs, Global REITs, Gold, Commodities } \examples{ data(asset_data) } \keyword{datasets}
3d989ba403723879fbfad44260ac70f448901921
6a7538e4d3b6850800178315064f7e9213112b78
/ERP_measurements_analysis/LOTP_4AFC_stat_analysis.R
e0e132cb0cd003a09ebaf22745a8ba6596544f5e
[]
no_license
kylefrankovich/ERP_analysis_scripts
07816fe48f421cd1eea432808cd172ce4196e465
53640cf06f6d79658803cc12014c08bdf59fbed0
refs/heads/master
2020-05-29T16:09:16.973872
2016-09-06T00:44:57
2016-09-06T00:44:57
59,140,299
0
0
null
null
null
null
UTF-8
R
false
false
7,937
r
LOTP_4AFC_stat_analysis.R
# statistical analysis for LOTP_4AFC_ERP library(ez) library(dplyr) library(ggplot2) setwd("~/Desktop/ERP_analysis_scripts/ERP_measurements_analysis") ## load data: # files: # blocked_correct_resp_N2pc.txt # blocked_correct_resp_SPCN.txt # mixed_correct_resp_N2pc.txt # mixed_correct_resp_SPCN.txt # blocked_all_resp_N2pc.txt # blocked_all_resp_SPCN.txt # mixed_all_resp_N2pc.txt # mixed_all_resp_SPCN.txt # blocked_all_resp_N2pc_12_sub.txt # blocked_all_resp_SPCN_12_sub.txt # only correct responses: df_blocked_correct_N2pc <- read.table('blocked_correct_resp_N2pc.txt', sep="\t", header = TRUE) df_blocked_correct_SPCN <- read.table('blocked_correct_resp_SPCN.txt', sep="\t", header = TRUE) df_mixed_correct_N2pc <- read.table('mixed_correct_resp_N2pc.txt', sep="\t", header = TRUE) df_mixed_correct_SPCN <- read.table('mixed_correct_resp_SPCN.txt', sep="\t", header = TRUE) # all responses: df_blocked_all_resp_N2pc <- read.table('blocked_all_resp_N2pc.txt', sep="\t", header = TRUE) df_blocked_all_resp_SPCN <- read.table('blocked_all_resp_SPCN.txt', sep="\t", header = TRUE) df_blocked_all_resp_N2pc_12_sub <- read.table('blocked_all_resp_N2pc_12_sub.txt', sep="\t", header = TRUE) df_blocked_all_resp_SPCN_12_sub <- read.table('blocked_all_resp_SPCN_12_sub.txt', sep="\t", header = TRUE) df_mixed_all_resp_N2pc <- read.table('mixed_all_resp_N2pc.txt', sep="\t", header = TRUE) df_mixed_all_resp_SPCN <- read.table('mixed_all_resp_SPCN.txt', sep="\t", header = TRUE) # filtered data frames/factorization: # correct responses: df_blocked_correct_N2pc$bini = factor(df_blocked_correct_N2pc$bini) df_blocked_correct_N2pc_occip = filter(df_blocked_correct_N2pc, chindex == 12) df_blocked_correct_N2pc_PO7_PO8 = filter(df_blocked_correct_N2pc, chindex == 9) df_blocked_correct_SPCN$bini = factor(df_blocked_correct_SPCN$bini) df_blocked_correct_SPCN_occip = filter(df_blocked_correct_SPCN, chindex == 12) df_blocked_correct_SPCN_PO7_PO8 = filter(df_blocked_correct_SPCN, chindex == 9) df_mixed_correct_N2pc$bini = factor(df_mixed_correct_N2pc$bini) df_mixed_correct_N2pc_occip = filter(df_mixed_correct_N2pc, chindex == 12) df_mixed_correct_N2pc_PO7_PO8 = filter(df_mixed_correct_N2pc, chindex == 9) df_mixed_correct_SPCN$bini = factor(df_mixed_correct_SPCN$bini) df_mixed_correct_SPCN_occip = filter(df_mixed_correct_SPCN, chindex == 12) df_mixed_correct_SPCN_PO7_PO8 = filter(df_mixed_correct_SPCN, chindex == 9) # all responses df_blocked_all_resp_N2pc$bini = factor(df_blocked_all_resp_N2pc$bini) df_blocked_all_resp_N2pc_occip = filter(df_blocked_all_resp_N2pc, chindex == 12) df_blocked_all_resp_N2pc_PO7_PO8 = filter(df_blocked_all_resp_N2pc, chindex == 9) df_blocked_all_resp_SPCN$bini = factor(df_blocked_all_resp_SPCN$bini) df_blocked_all_resp_SPCN_occip = filter(df_blocked_all_resp_SPCN, chindex == 12) df_blocked_all_resp_SPCN_PO7_PO8 = filter(df_blocked_all_resp_SPCN, chindex == 9) # for overall anova (steve's notes): df_blocked_all_resp_N2pc_12_sub$bini = factor(df_blocked_all_resp_N2pc_12_sub$bini) df_blocked_all_resp_N2pc_12_sub_occip = filter(df_blocked_all_resp_N2pc_12_sub, chindex == 12) df_blocked_all_resp_SPCN_12_sub$bini = factor(df_blocked_all_resp_SPCN_12_sub$bini) df_blocked_all_resp_SPCN_12_sub_occip = filter(df_blocked_all_resp_SPCN_12_sub, chindex == 12) df_mixed_all_resp_N2pc$bini = factor(df_mixed_all_resp_N2pc$bini) df_mixed_all_resp_N2pc_occip = filter(df_mixed_all_resp_N2pc, chindex == 12) df_mixed_all_resp_N2pc_PO7_PO8 = filter(df_mixed_all_resp_N2pc, chindex == 9) df_mixed_all_resp_SPCN$bini = factor(df_mixed_all_resp_SPCN$bini) df_mixed_all_resp_SPCN_occip = filter(df_mixed_all_resp_SPCN, chindex == 12) df_mixed_all_resp_SPCN_PO7_PO8 = filter(df_mixed_all_resp_SPCN, chindex == 9) # Steve's analysis notes: # Hi Kyle. I think you should go with all responses (now that it is working right). # Also, I think you should put blocked and mixed into a single ANOVA and add a # blocked/mixed factor. You can then do separate analyses if there are any # significant differences between blocked and mixed (which I don’t think you’ll find). # This should increase our power. # Which electrode sites are in the occipital average? # Is it all the P, PO, and O sites? class(df_blocked_all_resp_N2pc_12_sub_occip$bini) class(df_blocked_all_resp_SPCN_12_sub_occip$bini) df_blocked_all_resp_N2pc_12_sub_occip$blocked = 1 df_blocked_all_resp_SPCN_12_sub_occip$blocked = 1 df_mixed_all_resp_N2pc_occip$blocked = 0 df_mixed_all_resp_SPCN_occip$blocked = 0 df_blocked_all_resp_N2pc_12_sub_occip$blocked = factor(df_blocked_all_resp_N2pc_12_sub_occip$blocked) df_mixed_all_resp_N2pc_occip$blocked = factor(df_mixed_all_resp_N2pc_occip$blocked) df_blocked_all_resp_SPCN_12_sub_occip$blocked = factor(df_blocked_all_resp_SPCN_12_sub_occip$blocked) df_mixed_all_resp_SPCN_occip$blocked = factor(df_mixed_all_resp_SPCN_occip$blocked) # combine blocked and mixed together: # df_blocked_all_resp_N2pc_12_sub_occip 26 obs # df_mixed_all_resp_N2pc_occip class(df_blocked_all_resp_N2pc_12_sub_occip$bini) class(df_blocked_all_resp_N2pc_12_sub_occip$blocked) class(df_blocked_all_resp_N2pc_12_sub_occip$value) class(df_mixed_all_resp_N2pc_occip$bini) class(df_mixed_all_resp_N2pc_occip$blocked) class(df_mixed_all_resp_N2pc_occip$value) class(df_blocked_all_resp_SPCN_occip$bini) class(df_blocked_all_resp_SPCN_occip$value) df_N2pc_blocked_mixed = bind_rows(df_blocked_all_resp_N2pc_12_sub_occip, df_mixed_all_resp_N2pc_occip) df_N2pc_blocked_mixed$bini = factor(df_N2pc_blocked_mixed$bini) df_N2pc_blocked_mixed$blocked = factor(df_N2pc_blocked_mixed$blocked) class(df_N2pc_blocked_mixed$bini) class(df_N2pc_blocked_mixed$blocked) class(df_N2pc_blocked_mixed$value) class(df_N2pc_blocked_mixed$ERPset) length(unique(df_N2pc_blocked_mixed$ERPset)) test = select(df_N2pc_blocked_mixed, value, bini, ERPset, blocked) class(test$value) class(test$bini) class(test$ERPset) class(test$blocked) # bini: # 1 = blocked fast # 2 = blocked slow # 3 = mixed fast # 4 = mixed slow # sites recorded: (FP1/2, F3/4, F7/8, C3/4, P3/4, P5/6, P7/8, P9/10, P03/04, # P07/08, O1/2, Fz, Cz, Pz, POz, Oz, mastoid R/L, HEOG R/L, VEOG) electrode_site = 'occip' # 'occip' or 'PO7_PO8' # electrode_site = 'PO7_PO8' condition = 'mixed' # condition = 'blocked' # response = 'correct' response = 'all_resp' time_window = 'SPCN' # time_window = 'N2pc' data_frame = paste('df',condition,response,time_window,electrode_site, sep = "_") data_frame View(eval(parse(text = data_frame))) current_anova = ezANOVA( data = eval(parse(text = data_frame)) , dv = .(value) , wid = .(ERPset) , within = .(bini) ) print(current_anova) current_anova_data_output = ezStats( data = eval(parse(text = data_frame)) , dv = .(value) , wid = .(ERPset) , within = .(bini) ) data(ANT2) ANT2 = ANT2[!is.na(ANT2$rt),] ezDesign( data = ANT2 , x = trial , y = subnum , row = block , col = group ) ezDesign( data = df_N2pc_blocked_mixed , x = bini , y = ERPset , row = block , col = blocked ) current_anova = ezANOVA( data = test , dv = .(value) , wid = .(ERPset) , within = .(bini,blocked) ) print(current_anova) current_anova_data_output = ezStats( data = df_N2pc_blocked_mixed , dv = .(value) , wid = .(ERPset) , within = .(blocked) ) print(current_anova_data_output) ezPlot( data = df_N2pc_blocked_mixed , dv = .(value) , wid = .(ERPset) , within = .(bini,blocked) , x = bini )
401ca6aae24bd1af908d7314a786bd42a0dcdefd
5df2b9430e84caf4775a4d632dda4e352f13a1f9
/data_clean_file.R
5799e4c0037ca90912174d05eb8e5af4a76f8c69
[]
no_license
BouranDS/Project1Exploratory
aa36c8cd3973c6a71b2a505620a41f4ff10db274
c2e0977fa64752b5a3c7702816cd40cc280af656
refs/heads/main
2023-01-12T19:02:22.208150
2020-10-31T09:30:22
2020-10-31T09:30:22
308,840,233
0
0
null
null
null
null
UTF-8
R
false
false
1,095
r
data_clean_file.R
## Project 1 for Week 1 # author : ibrahima dit bouran sidibe # require(magrittr) data_in <- read.csv2(file = "D:/MyR/exdata_data_household_power_consumption/household_power_consumption.txt", header = TRUE, sep = ";", stringsAsFactors = FALSE) # head(data_in) # tail(data_in) # str(data_in) data_in <- base::transform(data_in, Date = lubridate::as_date(Date, format = "%d/%m/%Y")) #data_in <- base::transform(data_in, Time = lubridate::hms(Time)) # my_name <- colnames(data_in) != "Date" & colnames(data_in) != "Time" for(ikl in 1:length(colnames(data_in))){ if(my_name[ikl]){ data_in[, ikl] <- base::as.numeric(data_in[, ikl]) #print(colnames(data_in)[ikl]) } } data_in_sub <- data_in$Date %>% dplyr::between(as.Date("2007-02-01"), as.Date("2007-02-02")) data_in_select <- data_in[data_in_sub, ] Date_compl <- lubridate::ymd_hms( paste(lubridate::ymd(data_in_select$Date), data_in_select$Time) ) data_in_select$Date_complete <- Date_compl # summary(data_in[, my_name]) # table(data_in$Global_reactive_power) # as.Date(data_in$Time, format = "%H:%M:%S")
27023058b7ca082ac40d21e7e1ab994e29050563
bded5e8f66fa9edd65ea4d9f44e2b15351856293
/other/sqf_files/prob_any_force_used_black_vs_white.R
2e0bfd37a1bf5b028cd1bfdee7f860054fa1a2ae
[]
no_license
msr-ds3/stop-question-frisk
79a3112395c9d09413dbcd5c73c30ca777489c65
86b367093c3bb5c6c0ba927184b7fbb1bc5b35fa
refs/heads/master
2022-11-06T01:46:55.393468
2020-05-11T20:21:50
2020-05-11T20:21:50
196,596,341
3
4
null
2020-06-18T19:27:45
2019-07-12T14:47:23
HTML
UTF-8
R
false
false
5,712
r
prob_any_force_used_black_vs_white.R
library(tidyverse) library(tidycensus) library(totalcensus) library(sf) library(tmap) library(tmaptools) library(tigris) library(leaflet) library(sp) library(ggmap) library(maptools) library(broom) library(httr) library(rgdal) library(htmlwidgets) library(webshot) ########## LOAD AND CREATE/CLEAN DATAFRAMES ########## # Load stop and frisk data for 2003-2013 load("sqf_03_13.RData") # Load census data for race distributions by precinct load("census_race_data.RData") sqf_data <- sf_data1 %>% # filter out unknown races filter(race != " " & race != "U" & race != "X") %>% # recode Black Hispanic as Black, American Indian as Other mutate(race = recode_factor(race,"P" = "B", "I" = "Z"), # create an any_force_used column - ADDED pf_other TO THIS CALCULATION any_force_used = paste(pf_hands, pf_grnd, pf_wall, pf_drwep, pf_ptwep, pf_hcuff,pf_baton, pf_pepsp, sep = ""), # create factors from columns any_force_used = if_else(grepl("Y",any_force_used), 1, 0), # recode race names for clarity race = recode_factor(race, "W" = "White", "B" = "Black", "Q" ="Hispanic", "A" = "Asian", "Z" = "Other")) %>% select(addrpct, race, any_force_used) force_used <- sqf_data %>% group_by(addrpct, race) %>% summarize(prop_w_force_used = mean(any_force_used)) force_used_black <- force_used %>% filter(race == "Black") force_used_white <- force_used %>% filter(race == "White") comparing_races <- force_used %>% spread(race, prop_w_force_used) %>% mutate(B_over_W = (Black/White)) comparing_Hispanic_White <- force_used %>% spread(race, prop_w_force_used) %>% mutate(H_over_W = Hispanic/White) ########## MAP THE RESULTS ########## # read in police precinct shape data r <- GET('http://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nypp/FeatureServer/0/query?where=1=1&outFields=*&outSR=4326&f=geojson') police_precincts <- readOGR(content(r,'text'), 'OGRGeoJSON', verbose = F) # Join the precinct shape data with the data about the precincts joint_black <- geo_join(police_precincts, force_used_black, "Precinct", "addrpct") joint_white <- geo_join(police_precincts, force_used_white, "Precinct", "addrpct") joint_bw <- geo_join(police_precincts, comparing_races, "Precinct", "addrpct") joint_hw <- geo_join(police_precincts, comparing_Hispanic_White, "Precinct", "addrpct") mypopup <- paste0("Precinct: ", joint_bw$addrpct, "<br>", "Black/White Prop w/ Force Used: ", joint_bw$B_over_W) mypal <- colorNumeric( palette = "Spectral", domain = c(-.5,.5), reverse = TRUE ) prob_force_used_b_over_w <- leaflet(joint_bw) %>% addTiles() %>% addPolygons(fillColor = ~mypal(log10(joint_bw$B_over_W)), fillOpacity = 1, weight = 1, popup = mypopup) %>% addProviderTiles("CartoDB.Positron") %>% addLegend(pal = mypal, values = c(-.5,.5), position = "topleft", labFormat = labelFormat(transform = function(x) signif(10^x, 1)), #title = "Probability of <br> any force used <br>Black over White" ) prob_force_used_b_over_w mypopuphw <- paste0("Precinct: ", joint_hw$addrpct, "<br>", "Hispanic/White Prop w/ Force Used: ", joint_hw$H_over_W) mypalhw <- colorNumeric( palette = "Spectral", domain = c(-.5,.5), reverse = TRUE ) prob_force_used_h_over_w <- leaflet(joint_hw) %>% addTiles() %>% addPolygons(fillColor = ~mypalhw(log10(joint_hw$H_over_W)), fillOpacity = 1, weight = 1, popup = mypopuphw) %>% addProviderTiles("CartoDB.Positron") %>% addLegend(pal = mypal, values = c(-.5,.5), position = "topleft", labFormat = labelFormat(transform = function(x) signif(10^x, 1)), #title = "Probability of <br> any force used <br>Black over White" ) prob_force_used_h_over_w mypopup1 <- paste0("Precinct: ", joint_black$addrpct, "<br>", "Hispanic/White Prop w/ Force Used: ", joint_black$prop_w_force_used) mypal1 <- colorNumeric( palette = "YlOrRd", domain = c(-1,1), reverse = TRUE ) prob_force_used_black <- leaflet(joint_black) %>% addTiles() %>% addPolygons(fillColor = ~mypal1(joint_black$prop_w_force_used), fillOpacity = 1, weight = 1, popup = mypopup1, ) %>% addProviderTiles("CartoDB.Positron") %>% addLegend(pal = mypal1, values = c(-1, 1), position = "topleft", #title = "Probability of <br> any force used <br>given Black" ) prob_force_used_black mypopup2 <- paste0("Precinct: ", joint_white$addrpct, "<br>", "Black/White Prop w/ Force Used: ", joint_white$prop_w_force_used) mypal2 <- colorNumeric( palette = "YlOrRd", domain = c(-1,1), reverse = TRUE ) prob_force_used_white <- leaflet(joint_white) %>% addTiles() %>% addPolygons(fillColor = ~mypal(joint_white$prop_w_force_used), fillOpacity = 1, weight = 1, popup = mypopup2, ) %>% addProviderTiles("CartoDB.Positron") %>% addLegend(pal = mypal2, values = c(-1,1), position = "topleft", # title = "Probability of any force used <br> # given White" ) prob_force_used_white saveWidget(prob_force_used, "../figures/prob_force_used.html", selfcontained = FALSE) webshot("../figures/prob_force_used.html", file = "../figures/prob_force_used.png", cliprect = "viewport")
edf2079540a3454795f51c1623b6520b9546181f
16d9103d6d54fac9937389187ca3ffaa27089c24
/R/channel_analytic.r
f411e57907e3f9904864f9dd2e528f30debb3c15
[]
no_license
CodifiedHashtagsCoding/rTwChannel
7ca17456d5d1eaac0899bae90fe3abb10294cb22
08b71e359bed4b855fc073a45c1e644fe3c561e7
refs/heads/master
2020-12-11T05:46:00.013455
2015-11-20T16:48:15
2015-11-20T16:48:15
null
0
0
null
null
null
null
UTF-8
R
false
false
36,237
r
channel_analytic.r
#' channel_analytic #' #' @description Extract many informative stats and object from a set of tweet messages parsed as channel #' #' @param channel_obj Data.frame Dataset of tweets #' @param use_channel_dates Logical Use temporal indication of channel #' @param start_date Character Date of analisys starting. #' @param end_date Character Date of analisys ending. #' @param Ntop Integer indicate the maximum number for top statistics #' @param temporal_check Logical indicate if exist time consistency between dates and data #' @param Nmin Integer indicate the minimal data numerosity #' @param naming Character Indicate which naming framework is adopted. #' @param only_original_tweet Logical Taking into account only original. Default all tweets are considered. #' @param lowercase logical Consider all text as lower case. Default is TRUE. #' @param stopword Character stopword set to be use to calculate word frequency matrix. Default italian stopwords of R tm package. #' @param corpus_hashtag logical Corpus not taking into account the hashtag. #' @param account_tw User account if naming parameter is an "account_statistics" #' @return Return a R list object for channel analisys #' @return **channel_stat** : channel summaries of following parameters. #' @return * *N_tweets* : Number of tweet within unique ID #' @return * N_retweets (channel_stat):Number of retweet #' @return * N_native_tweets (channel_stat):Number of original tweets #' @return * N_hash (channel_stat):Number of hashtags detected in channel #' @return * N_mention (channel_stat): Number of mention detected in channel #' @return * N_links (channel_stat):Number of links detected in channel #' @return * Nuniq_authors (channel_stat):Number of unique authors #' @return * Nuniq_hash (channel_stat): Number of unique hashs #' @return * Nuniq_mentions (channel_stat): Number of unique mentions #' @return * Nuniq_links (channel_stat): Number of unique links #' @return * Nmean_links (channel_stat): Mean links for tweet #' @return * Nfull_retweet (channel_stat): Number of all retweets given by platorm #' @return * Nfull_retweet_missing (channel_stat): Number of tweet given without platform statistics #' @return * Nreplies (channel_stat): Number of of replies #' @return * Nfavor (channel_stat): Number of of cumulative favorites given by platform #' @return * Ntweets0links (channel_stat): Number of tweets with no links #' @return * Ntweets1link (channel_stat): N of tweets with 1 link #' @return * NtweetsNlinks (channel_stat): Number of tweets more than links #' @return * Ntweets0mentions (channel_stat): Number of tweets with no mentions #' @return * Ntweets1mention (channel_stat): Number of tweets with 1 mention #' @return * NtweetsNmentions (channel_stat): Number of tweets more than mentions #' @return * Ntweets0hashs (channel_stat): Number of tweets with no hashtags #' @return * Ntweets1hash (channel_stat): Number of tweets with 1 hashtag #' @return * NtweetsNhashs (channel_stat): Number of tweets more than hashtags #' @return **table_message** : Frequency data.frame of message #' @return **table_hash** : Frequency data.frame of hashtag #' @return **table_mentions** : Frequency data.frame of mentions #' @return **table_authors** : Frequency data.frame of authors #' @return **table_replies** : Frequency data.frame of replies #' @return **table_authors_retweeted** : Frequency data.frame of authors retweeted #' @return **table_authors_retweeter** : Frequency data.frame of authors that is a retweeter #' @return **rank_authors_retweet** : Frequency data.frame of retweet by using platform data #' @return **rank_message_retweet** : Frequency data.frame of message by using platform data #' @return **top_message** : TopN messages in channel #' @return **top_authors** : TopN authors in channel #' @return **top_hash** : TopN hashtag #' @return **top_mentions** : TopN user mentioned #' @return **top_replies** : TopN user have made replies #' @return **top_authors_retweeted** : TopN user that have retweeted in channel #' @return **top_authors_retweeter** : TopN user that have made retweet in channel #' @return **topfull_authors_retweeted** : TopN author that have retweeted in platform #' @return **topfull_message_retweeted** : TopN message that have retweeted in platform #' @return **daily_stat** : Daily Temporal data of channel statistic data #' @return **authors_date** : DateTime authors activity in channel #' @return **links_date** : DateTime authors activity in channel #' @return **hash_date** : DateTime hashtag presence in channel #' @return **mentions_date** : DateTime mentions presence in channel #' @return **unique_message** : Unique message in channel #' @return **unique_authors** : Unique authors in channel #' @return **unique_hash** : Unique hashtag in channel #' @return **unique_mentions** : Unique mentions in channel #' @return **unique_authors_retweeted** : Unique retweeted user in channel #' @return **unique_authors_retweeter** : Unique retweeter user in channel #' @return **uniquefull_authors_retweeted** : Unique retweeted user in platform #' @return **uniquefull_message_retweeted** : Unique retweeted message in platform #' @return **graph_retweet_df** : Data used for retweet graph #' @return **graph_hash_df** : Data used for hashtag graph #' @return **graph_mentions_df** : Data for used mention graph #' @return **replies_df** : Data for replies #' @return **graph_retweet** : Retweet graph object as igraph R object #' @return **graph_mentions** : Mention graph object as igraph R object #' @return **authors_favorite** : rank of authors favorite #' @return **favorite_message_top** : TopN favorite message #' @return **channel_data** : Channel_data #' @return **channel_corpus** : Tm Corpus of messages without mentions and links and optionally without hashtag #' @return **word_freq_matr** : qdap wfm object Word frequency matrix. #' @return **account_stats** : Statistic account's activity by date. #' #' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \email{a.crisci@@ibimet.cnr.it} #' @keywords channel,stats #' #' #' #' @export #' #' channel_analytic=function(channel_obj,use_channel_dates=TRUE, start_date=NULL, end_date=NULL,Ntop=11,temporal_check=FALSE, Nmin=25,naming="",only_original_tweet=FALSE,lowercase=TRUE,stopword = tm::stopwords("it"), account_tw="", corpus_hashtag=TRUE) { ##################################################################################### # Data checks rows=nrow(channel_obj) if (rows < Nmin) { stop("Channel with too few records.")}; message(paste(" Channel:", deparse(substitute(channel_obj)),"\n", "Elements:", rows ,"\n", "Ntop:", Ntop ,"\n", "Temporal Check:",temporal_check,"\n", "Minimum data:",Nmin,"\n", "Type stream:",naming,"\n", "Native Channel:",only_original_tweet,"\n", "Lowering case message's text:",lowercase,"\n")) if ( naming == "account_analitics") {message(paste("Account Twitter:",account_tw,"\n"))} if ( (naming == "account_analitics") && (account_tw == "") ) { stop("Channel analitics need an Twitter account!")}; if ( naming == "TAGS") { channel_obj$created <- lubridate::dmy_hms(channel_obj$time) channel_obj=channel_obj[which(!is.na(channel_obj$created)),] channel_obj$data <- as.Date(channel_obj$created) channel_obj$screeName=channel_obj$from_user channel_obj$id=as.numeric(channel_obj$id_str) channel_obj$lang=channel_obj$user_lang channel_obj$from_user<-NULL channel_obj$user_lang<-NULL channel_obj$message<-NULL channel_obj$created_at<-NULL channel_obj$retweetCount<-rep(0,nrow(channel_obj)) channel_obj$entities_str<-NULL channel_obj$retweetCount<-rep(0,nrow(channel_obj)) channel_obj$favoriteCount<-rep(0,nrow(channel_obj)) channel_obj$ls_hash_full<-rep(NA,nrow(channel_obj)) channel_obj$ls_links=rep(NA,nrow(channel_obj)) channel_obj$time<-NULL channel_obj=channel_obj[rev(1:nrow(channel_obj)),] } if ( naming == "DISIT") { channel_obj$text=channel_obj$message channel_obj$data=as.character(as.Date(channel_obj$publicationTime)) channel_obj$screeName=channel_obj$twitterUser channel_obj$created=channel_obj$publicationTime channel_obj$ls_hash_full=channel_obj$hashtagsOnTwitter channel_obj$ls_links=channel_obj$links channel_obj$id=channel_obj$twitterId channel_obj$message<-NULL channel_obj$hashtagsOnTwitter<-NULL channel_obj$twitterId<-NULL channel_obj$links<-NULL channel_obj$hour=lubridate::hour(channel_obj$publicationTime) channel_obj$month=lubridate::month(channel_obj$publicationTime) channel_obj$publicationTime<-NULL } if (naming == "account_analitics") { channel_obj=channel_obj[,1:22] name_user_tweet_activity=c("id","link_tweet","text","dateTime","impress","interazioni","inter_rate", "retweetCount","repliesCount","favoriteCount","clickonuserprofile","clickonlink", "clickonlinkhash","details","clickonPermalinks","open_app","n_install_app", "followsCount","email_send","tel_calls","mediaVisCount","interVisCount") names(channel_obj)=name_user_tweet_activity channel_obj$data=as.Date(channel_obj$dateTime) channel_obj$hour=lubridate::hour(channel_obj$dateTime) channel_obj$month=lubridate::month(channel_obj$dateTime) channel_obj$screeName=account_tw } if ( naming == "twitter") { channel_obj$data=as.Date(channel_obj$created) channel_obj$hour=lubridate::hour(channel_obj$created) channel_obj$month=lubridate::month(channel_obj$created) channel_obj$text=iconv(channel_obj$text,"utf-8") channel_obj$isRetweet=as.integer(channel_obj$isRetweet) channel_obj$screeName=channel_obj$screenName channel_obj$screenName<-NULL } ##################################################################################### # Temporal filter of channel if ( use_channel_dates == TRUE) { start_date=head(channel_obj$data[which(channel_obj$data== as.character(min(as.Date(channel_obj$data))))],1); end_date=tail(channel_obj$data[which(channel_obj$data== as.character(max(as.Date(channel_obj$data))))],1); } if (as.Date(start_date) > as.Date(end_date)) { stop(" End Date is older than Start date. ")}; if ( temporal_check==TRUE) { if (as.Date(start_date) < as.Date(head(channel_obj$data,1))) { stop("Start Date of analisys not defined." )}; if (as.Date(end_date) > as.Date(tail(channel_obj$data,1))) { stop("End Date of analisys not defined." )}; channel_obj=channel_obj[min(which(channel_obj$data==as.character(start_date))):max(which(channel_obj$data==as.character(end_date))),] } ##################################################################################### # Create data.frames for other count statistics. ls_retweet=unlist(lapply(channel_obj$text,FUN=function(x) is.retweet(x))) ls_retweeted_authors=as.character(rep(NA,nrow(channel_obj))) for ( i in 1:length(ls_retweeted_authors)) {ls_retweeted_authors[i]=retweeted_users(channel_obj$text[i]) } if (only_original_tweet==TRUE) { channel_obj=channel_obj[which(ls_retweet==0),] ls_retweet=unlist(lapply(channel_obj$text,FUN=function(x) is.retweet(x))) } #################################################################################### # Create lists to be used for count statistics. ls_links=lapply(channel_obj$text,FUN=function(x) qdapRegex::rm_url(x, extract=TRUE)) if ( lowercase == TRUE) { channel_obj$text=tolower(channel_obj$text) } ls_hash=lapply(channel_obj$text,FUN=function(x) qdapRegex::rm_hash(x,extract=T)) ls_tag=lapply(channel_obj$text,FUN=function(x) extract_mentions(x)) ls_lenhash=unlist(lapply(ls_hash,FUN=function(x) ifelse(is.na(x),0, length(qdapRegex::rm_hash(x,extract=T)[[1]])))) ls_lenlinks=unlist(lapply(ls_links,FUN=function(x) ifelse(is.na(x),0, length(qdapRegex::rm_url(x, extract=TRUE)[[1]])))) ls_lentag=unlist(lapply(ls_tag,FUN=function(x) ifelse(is.na(x),0, length(extract_mentions(x)[[1]])))) ls_words=unlist(lapply(channel_obj$text,FUN=function(x) qdap::word_count(x))) message("Text message are processed!\n") ####################################################################################### # Create data.frame date,retweeted_authors and authors. ls_retweeted_df=na.omit(data.frame(data=channel_obj$data, retweeted_authors=ls_retweeted_authors, authors=channel_obj$screeName)) #################################################################################### # Extract replies and organize a frame replies_id=grep("^@",channel_obj$text) channel_obj$replies=NA channel_obj$replies[replies_id]=1 ls_replies_df=data.frame(data=channel_obj$data,authors=channel_obj$screeName,replies=channel_obj$replies) #################################################################################### # Replies stats fullretweet_day=aggregate(channel_obj$retweetCount[which(!duplicated(channel_obj$text)==TRUE)],list(channel_obj$data[which(!duplicated(channel_obj$text)==TRUE)]),sum,na.rm = TRUE) names(fullretweet_day)=c("date","retweetCount") fullretweet_day$date=as.Date(fullretweet_day$date) fullreplies_day=aggregate(channel_obj$replies,list(channel_obj$data),sum,na.rm = TRUE) names(fullreplies_day)=c("date","repliesCount") fullreplies_day$date=as.Date(fullreplies_day$date) fullretweet_missing=length(which(is.na(channel_obj$retweetCount[which(!duplicated(channel_obj$text)==TRUE)]))) fullretweet_channel_stat_sum=sum(channel_obj$retweetCount[which(!duplicated(channel_obj$text)==TRUE)],na.rm=T) replies_channel_stat_sum=length(replies_id) ####################################################################################### # Create data.frame date,message and authors. ls_favorite_df=data.frame(data=channel_obj$data[which(!duplicated(channel_obj$text)==TRUE)], message=channel_obj$text[which(!duplicated(channel_obj$text)==TRUE)], authors=channel_obj$screeName[which(!duplicated(channel_obj$text)==TRUE)], favoriteCount=channel_obj$favoriteCount[which(!duplicated(channel_obj$text)==TRUE)], is.retweet=ls_retweet[which(!duplicated(channel_obj$text)==TRUE)]) day_favorite=aggregate(ls_favorite_df$favoriteCount,list(ls_favorite_df$data),sum) names(day_favorite)<-c("date","N_favor") day_favorite$date=as.Date(day_favorite$date) ls_favorite_df=ls_favorite_df[order(-ls_favorite_df$favoriteCount),] rank_authors_favorite=aggregate(channel_obj$favoriteCount[which(!duplicated(channel_obj$text)==TRUE)], list(channel_obj$screeName[which(!duplicated(channel_obj$text)==TRUE)]) ,sum) rank_authors_favorite=rank_authors_favorite[order(-rank_authors_favorite[,2]),] names(rank_authors_favorite)<-c("authors","favoriteCount") ######################################################################### ls_message_df=data.frame(data=channel_obj$data[which(!duplicated(channel_obj$text)==TRUE)], message=channel_obj$text[which(!duplicated(channel_obj$text)==TRUE)], authors=channel_obj$screeName[which(!duplicated(channel_obj$text)==TRUE)], retweetCount=channel_obj$retweetCount[which(!duplicated(channel_obj$text)==TRUE)], is.retweet=ls_retweet[which(!duplicated(channel_obj$text)==TRUE)]) rank_authors_retweet=aggregate(ls_message_df$retweetCount,list(ls_message_df$authors),sum) rank_authors=rank_authors_retweet[order(-rank_authors_retweet[,2]),] names(rank_authors_retweet)<-c("authors","retweetCount") rank_message_retweet=aggregate(ls_message_df$retweetCount,list(ls_message_df$message),sum) rank_message_retweet=rank_message_retweet[order(-rank_message_retweet[,2]),] names(rank_message_retweet)<-c("message","retweetCount") rank_authors_retweet=rank_authors_retweet[ order(-rank_authors_retweet[,2]), ] rank_message_retweet=rank_message_retweet[ order(-rank_message_retweet[,2]), ] ########################################################################################################################################## # retrieve other information from channel stack. rank_message_retweet$retweeted_authors=retweeted_users(rank_message_retweet$message) id_na_message_retweet=which(is.na(rank_message_retweet$retweeted_authors)) not_retweet_with_authors=as.character(rank_message_retweet$message[id_na_message_retweet]) for ( i in seq_along(not_retweet_with_authors)) { rank_message_retweet$retweeted_authors[id_na_message_retweet[i]]=as.character(channel_obj$screeName[min(which(channel_obj$text ==not_retweet_with_authors[i]))]) } rank_message_retweet$data=NA for ( i in seq_along(rank_message_retweet$message)) { rank_message_retweet$data[i]=as.character(channel_obj$data[min(which((channel_obj$text %in% rank_message_retweet$message[i] )==T))]) } ####################################################################################### # Create data.frame date,authors and is retweet. ls_authors_df=data.frame(data=channel_obj$data,authors=channel_obj$screeName,ls_retweet) names(ls_authors_df)=c("data","authors","retweet") ##################################################################################### # Create data.frame date and hashtag. ls_hash_long=list() for ( i in seq_along(ls_hash)) {ls_hash_long[[i]]=cbind(as.character(channel_obj$data[i]),unlist(ls_hash[[i]]),ls_retweet[i],as.character(channel_obj$screeName[i]))} ls_hash_df=as.data.frame(do.call(rbind,ls_hash_long)) names(ls_hash_df)=c("data","hashtag","retweet","authors") ##################################################################################### # Create data.frame date and mentions. ls_tag_long=list() for ( i in seq_along(ls_tag)){ls_tag_long[[i]]=cbind(as.character(channel_obj$data[i]),unlist(ls_tag[[i]]),ls_retweet[i],as.character(channel_obj$screeName[i]))} ls_tag_df=as.data.frame(do.call(rbind,ls_tag_long)) names(ls_tag_df)=c("data","mention","retweet","authors") ls_tag_df$mention=gsub("^@","",ls_tag_df$mention) ##################################################################################### # Create data.frame date and links. ls_links_long=list() for ( i in seq_along(ls_links)) {ls_links_long[[i]]=cbind(as.character(channel_obj$data[i]),unlist(ls_links[[i]]),ls_retweet[i],as.character(channel_obj$screeName[i]))} ls_links_df=as.data.frame(do.call(rbind,ls_links_long)) names(ls_links_df)=c("data","links","retweet","authors") ########################################################################################### # Creating arrays date and elements authors_unique=na.omit(unique(ls_authors_df[,1:2])) links_unique=na.omit(unique(ls_links_df[,1:2])) hash_unique=na.omit(unique(ls_hash_df[,1:2])) tag_unique=na.omit(unique(ls_tag_df[,1:2])) authors_purged=na.omit(ls_authors_df) links_purged=na.omit(ls_links_df) hash_purged=na.omit(ls_hash_df) tag_purged=na.omit(ls_tag_df) ##################################################################################### lenhash_df=data.frame(data=as.Date(channel_obj$data),lenhash=ls_lenhash) lenhash_df_day_mean=aggregate(lenhash_df$lenhash,list(lenhash_df$data),mean) names(lenhash_df_day_mean)=c("date","Nmean_hashtag") lentag_df=data.frame(data=as.Date(channel_obj$data),lentag=ls_lentag) lentag_df_day_mean=aggregate(lentag_df$lentag,list(lentag_df$data),mean) names(lentag_df_day_mean)=c("date","Nmean_mentions") lenwords_df=data.frame(data=as.Date(channel_obj$data),lenwords=ls_words) lenwords_df_day_mean=aggregate(lenwords_df$lenwords,list(lenwords_df$data),mean) names(lenwords_df_day_mean)=c("date","Nmean_words") lenlinks_df=data.frame(data=as.Date(channel_obj$data),lenlinks=ls_lenlinks) lenlinks_df_day_mean=aggregate(lenlinks_df$lenlinks,list(lenlinks_df$data),mean) names(lenlinks_df_day_mean)=c("date","Nmean_links") ##################################################################################### # retweet stats the ratio is ever ntive retweet/ native check_retweet=sum(ls_retweet) retweet_df=data.frame(data=channel_obj$data,is.retweet=ls_retweet) retweet_df_stats=data.frame(native_tweets=rep(0,length(levels(as.factor(retweet_df$data)))), native_retweets=rep(0,length(levels(as.factor(retweet_df$data))))) if ((only_original_tweet==FALSE) && (check_retweet == length(ls_retweet))) { retweet_df_stats$native_retweets=as.data.frame.array(table(retweet_df$data,retweet_df$is.retweet))[,1] } if ((only_original_tweet==FALSE) && (check_retweet > 0)) {retweet_df_stats$native_tweets=as.data.frame.array(table(retweet_df$data,retweet_df$is.retweet))[,1]; retweet_df_stats$native_retweets=as.data.frame.array(table(retweet_df$data,retweet_df$is.retweet))[,2]; } if (only_original_tweet==TRUE) {retweet_df_stats$native_tweets=as.data.frame.array(table(retweet_df$data,retweet_df$is.retweet))[,1]} retweet_df_stats$ratio=retweet_df_stats$native_retweets/retweet_df_stats$native_tweets retweet_df_stats$ratio[which(retweet_df_stats$ratio==Inf)]=NA retweet_df_stats$ratio[which(retweet_df_stats$ratio==NaN)]=NA retweet_df_stats$ratio[which(is.na(retweet_df_stats$ratio))]=0 retweet_stat=data.frame(date=as.Date(rownames(as.data.frame.array(table(retweet_df$data,retweet_df$is.retweet)))), native_tweets=retweet_df_stats$native_tweets, native_retweets=retweet_df_stats$native_retweets, retweet_ratio=retweet_df_stats$ratio) ######################################################################################## # Creating daily stats lenauthorsunique_day=as.data.frame.array(table(authors_unique$data)) lenauthorsunique_day_df=data.frame(date=as.Date(rownames(lenauthorsunique_day)),Nunique_authors=as.vector(lenauthorsunique_day[,1])) lenauthors_day=as.data.frame.array(table(authors_purged$data)) lenauthors_day_df=data.frame(date=as.Date(rownames(lenauthors_day)),Nday_authors=as.vector(lenauthors_day[,1])) ######################################################################### lenlinksunique_day=as.data.frame.array(table(links_unique$data)) lenlinksunique_day_df=data.frame(date=as.Date(rownames(lenlinksunique_day)),Nuniq_links=as.vector(lenlinksunique_day[,1])) lenlinks_day=as.data.frame.array(table(links_purged$data)) lenlinks_day_df=data.frame(date=as.Date(rownames(lenlinks_day)),Nday_links=as.vector(lenlinks_day[,1])) ######################################################################### lenhashunique_day=as.data.frame.array(table(hash_unique$data)) lenhashunique_day_df=data.frame(date=as.Date(rownames(lenhashunique_day)),Nuniq_hash=as.vector(lenhashunique_day[,1])) lenhash_day=as.data.frame.array(table(hash_purged$data)) lenhash_day_df=data.frame(date=as.Date(rownames(lenhash_day)),Nday_hash=as.vector(lenhash_day[,1])) ######################################################################### lentagunique_day=as.data.frame.array(table(tag_unique$data)) lentagunique_day_df=data.frame(date=as.Date(rownames(lentagunique_day)),Nuniq_mention=as.vector(lentagunique_day[,1])) lentag_day=as.data.frame.array(table(tag_purged$data)) lentag_day_df=data.frame(date=as.Date(rownames(lentag_day)),Nday_mention=as.vector(lentag_day[,1])) ######################################################################### # Create daily channel stats # Create a continuous data series ts_date=data.frame(date=seq.Date(as.Date(start_date),as.Date(end_date),1)) daily_stat=merge(ts_date,retweet_stat,all.x=T) daily_stat=merge(daily_stat,lenauthors_day_df,all.x=T) daily_stat=merge(daily_stat,lenhash_day_df,all.x=T) daily_stat=merge(daily_stat,lentag_day_df,all.x=T) daily_stat=merge(daily_stat,lenlinks_day_df,all.x=T) daily_stat=merge(daily_stat,lenhash_df_day_mean,all.x=T) daily_stat=merge(daily_stat,lentag_df_day_mean,all.x=T) daily_stat=merge(daily_stat,lenwords_df_day_mean,all.x=T) daily_stat=merge(daily_stat,lenlinks_df_day_mean,all.x=T) daily_stat=merge(daily_stat,lenauthorsunique_day_df,all.x=T) daily_stat=merge(daily_stat,lenhashunique_day_df,all.x=T) daily_stat=merge(daily_stat,lentagunique_day_df,all.x=T) daily_stat=merge(daily_stat,lenlinksunique_day_df,all.x=T) daily_stat=merge(daily_stat,fullretweet_day,all.x=T) daily_stat=merge(daily_stat,fullreplies_day,all.x=T) daily_stat=merge(daily_stat,day_favorite,all.x=T) ####################à daily_stat$retweet_ratio=round(as.numeric(daily_stat$retweet_ratio),2) daily_stat$Nmean_hashtag=round(as.numeric(daily_stat$Nmean_hashtag),2) daily_stat$Nmean_mentions=round(as.numeric(daily_stat$Nmean_mentions),2) daily_stat$Nmean_words=round(as.numeric(daily_stat$Nmean_words),2) daily_stat$Nmean_links=round(as.numeric(daily_stat$Nmean_links),2) message("Daily stats calculated!\n") ################################################################################# # Frequency analisys table_message=as.data.frame.array(sort(table(channel_obj$text),decreasing=T)) table_message=data.frame(message=rownames(table_message), Freq=as.vector(table_message)) names(table_message)<-c("message","freq") rownames(table_message)<-NULL table_message$data=NA table_message$authors=NA ind=sapply(table_message$message,FUN=function(x) match(x,channel_obj$text)) for ( i in 1:length(ind)) { table_message$data[i]=as.character(channel_obj$data[ind[i]]) table_message$authors[i]=as.character(channel_obj$screeName[ind[i]]) } table_message=na.omit(table_message) table_message$retweeted_authors=NA for ( i in 1:nrow(table_message)) { table_message$retweeted_authors[i]=retweeted_users(as.character(table_message$message[i])) } message("Table_message stats calculated!\n") ########################################################################## if ((only_original_tweet==FALSE ) && (naming!="account_statistics")) { table_authors_retweeted=as.data.frame.array(sort(table(ls_retweeted_df$retweeted_authors),decreasing=T)) table_authors_retweeted=data.frame(authors=rownames(table_authors_retweeted), Freq=as.vector(table_authors_retweeted)) names(table_authors_retweeted)<-c("authors_retweeted","freq") rownames(table_authors_retweeted)<-NULL message("Table authors retweeted stats calculated!\n") } if (only_original_tweet==TRUE || (naming=="account_statistics")) { table_authors_retweeted=data.frame(authors_retweeted=NA,freq=NA) }; ########################################################################## if ((only_original_tweet==FALSE ) && (naming!="account_statistics")) { table_authors_retweeter=as.data.frame.array(sort(table(ls_retweeted_df$authors),decreasing=T)) table_authors_retweeter=data.frame(authors=rownames(table_authors_retweeter), Freq=as.vector(table_authors_retweeter)) names(table_authors_retweeter)<-c("authors_retweeter","freq") rownames(table_authors_retweeter)<-NULL message("Table authors retweeter stats calculated!\n") } if ((only_original_tweet==TRUE) || (naming=="account_statistics")) { table_authors_retweeter=data.frame(authors_retweeter=NA,freq=NA) }; ########################################################################## table_authors=as.data.frame.array(sort(table(ls_authors_df$authors),decreasing=T)) table_authors=data.frame(authors=rownames(table_authors), Freq=as.vector(table_authors)) names(table_authors)<-c("authors","freq") rownames(table_authors)<-NULL ########################################################################## table_hash=as.data.frame.array(sort(table(ls_hash_df$hashtag),decreasing=T)) table_hash=data.frame(hashtag=rownames(table_hash), Freq=as.vector(table_hash)) names(table_hash)<-c("hashtag","freq") rownames(table_hash)<-NULL ########################################################################## table_mentions=as.data.frame.array(sort(table(ls_tag_df$mention),decreasing=T)) table_mentions=data.frame(users=rownames(table_mentions), Freq=as.vector(table_mentions)) names(table_mentions)<-c("mentions","freq") rownames(table_mentions)<-NULL ########################################################################## table_replies=as.data.frame.array(sort(table(ls_replies_df$authors),decreasing=T)) table_replies=data.frame(users=rownames(table_replies), Freq=as.vector(table_replies)) names(table_replies)<-c("replies","freq") rownames(table_replies)<-NULL message("Tables of authors and replies are calculated!\n") ######################################################################### # Create full channel stats full_stat=data.frame(N_tweets=length(channel_obj$text), N_retweets=sum(retweet_stat$native_retweets,na.rm=T), N_native_tweets=sum(retweet_stat$native_tweets,na.rm=T), N_hash=nrow(hash_purged), N_mention=nrow(tag_purged), N_links=nrow(links_purged), Nuniq_authors=length(unique(ls_authors_df[,2])), Nuniq_hash=length(unique(ls_hash_df[,2])), Nuniq_mentions=length(unique(ls_tag_df[,2])), Nuniq_links=length(unique(ls_links_df[,2])), Nmean_links=round(mean(lenlinks_df_day_mean$Nmean_links),2), Nfull_retweet=fullretweet_channel_stat_sum, Nfull_retweet_missing=fullretweet_missing, Nreplies=replies_channel_stat_sum, Nfavor=sum(ls_favorite_df$N_favor,na.rm=T), Ntweets0hashs = length(which(ls_lenhash==0)), Ntweets1hashs = length(which(ls_lenhash==1)), NtweetsNhashs = length(which(ls_lenhash>1)), Ntweets0mentions = length(which(ls_lentag==0)), Ntweets1mentions = length(which(ls_lentag==1)), NtweetsNmentions = length(which(ls_lentag>1)), Ntweets0links = length(which(ls_lenlinks==0)), Ntweets1links = length(which(ls_lenlinks==1)), NtweetsNlinks = length(which(ls_lenlinks>1)) ) message("Full stats of channel are done!\n") ############################################################################################################ # Create a mention graph graph_mentions_df=na.omit(ls_tag_df) mat_men_graph=na.omit(data.frame(whopost=graph_mentions_df[,4],whomentioned=graph_mentions_df[,2])) men_graph = igraph::graph.edgelist(as.matrix(na.omit(mat_men_graph))) E(men_graph )$weight <- 1 men_graph <- igraph::simplify(men_graph, remove.loops=FALSE) message("Mention Graph of channel are done!\n") ############################################################################################################ # Create a retweet graph rt_graph=NULL if (naming!="account_statistics") { rt_graph= igraph::graph.edgelist(as.matrix(cbind(ls_retweeted_df[,3],ls_retweeted_df[,2]))) E(rt_graph )$weight <- 1 rt_graph <- igraph::simplify(rt_graph, remove.loops=FALSE) message("Retweet Graph of channel are done!\n") } ############################################################################################################ # Get corpus and termdocfrequency matrix as qdap object corpus=getCorpus(channel_obj$text,hashtag=corpus_hashtag) word_freq_matr=qdap::wfm(corpus,stopwords=stopword) message("Corpus of words and frequency qdap matrix of channel are done!\n") ######################################################################################## channel_obj$hashtagCount=lenhash_df$lenhash channel_obj$linksCount=lenlinks_df$lenlinks channel_obj$mentionCount=lentag_df$lentag ######################################################################################## res=list(channel_stat=full_stat, table_message=table_message, table_hash=table_hash, table_mentions=table_mentions, table_authors=table_authors, table_replies=table_replies, table_authors_retweeted=table_authors_retweeted, table_authors_retweeter=table_authors_retweeter, rank_authors_retweet=rank_authors_retweet, rank_message_retweet=rank_message_retweet, top_message=table_message[1:Ntop,], top_authors=table_authors[1:Ntop,], top_hash=table_hash[1:Ntop,], top_mentions=table_mentions[1:Ntop,], top_replies=table_replies[1:Ntop,], top_authors_retweeted=table_authors_retweeted[1:Ntop,], top_authors_retweeter=table_authors_retweeter[1:Ntop,], topfull_authors_retweeted=rank_authors_retweet[1:Ntop,], topfull_message_retweeted=rank_message_retweet[1:Ntop,], daily_stat=daily_stat, authors_date=authors_purged, links_date=links_purged, hash_date=hash_purged, mentions_date=tag_purged, unique_message=unique(table_message[,1]), unique_authors=unique(table_authors[,1]), unique_hash=unique(table_hash[,1]), unique_mentions=unique(table_mentions[,1]), unique_authors_retweeted=unique(table_authors_retweeted[,1]), unique_authors_retweeter=unique(table_authors_retweeter[,1]), uniquefull_authors_retweeted=unique(rank_authors_retweet[,1]), uniquefull_message_retweeted=unique(rank_message_retweet[,1]), graph_retweet_df=ls_retweeted_df, graph_hash_df=na.omit(ls_hash_df), graph_mentions_df=na.omit(ls_tag_df), replies_df=ls_replies_df, graph_retweet=rt_graph, graph_mentions=men_graph, authors_favorite=rank_authors_favorite, favorite_message_top=head(ls_favorite_df,Ntop), channel_data=channel_obj, account_stats=NULL, channel_corpus=corpus, word_freq_matr=word_freq_matr ) if (naming=="account_statistics") { stats_activity=aggregate(channel_obj[,5:22], list(channel_obj$data), sum) names(stats_activity)[1]="data" rownames(stats_activity)=stats_activity$data res$account_stats=stats_activity } return(res) }
dde78b071315b313212fdd3e43c261ecddd35b53
37b51ada441c3679a42b82754d0e2f24c3ce70a2
/man/isAngleBetweenEdgesAlwaysSuperiorToMinAngle.Rd
ac70eb2abccfd618e307436f5ab135129a0371c1
[]
no_license
cran/AFM
a01d77751de195ca8a701cdf44ee3134ebaa00b4
98e8b5222e078af4d2840a20a2b58ec2196d684d
refs/heads/master
2021-05-04T11:23:09.648739
2020-10-07T07:00:06
2020-10-07T07:00:06
48,076,498
1
1
null
null
null
null
UTF-8
R
false
true
837
rd
isAngleBetweenEdgesAlwaysSuperiorToMinAngle.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AFMNetworksAnalyser.R \name{isAngleBetweenEdgesAlwaysSuperiorToMinAngle} \alias{isAngleBetweenEdgesAlwaysSuperiorToMinAngle} \title{check if all the angles between one edge and a list of edges is superior to a specified value.} \usage{ isAngleBetweenEdgesAlwaysSuperiorToMinAngle( binaryAFMImage, edge1, edges2, minAngle ) } \arguments{ \item{binaryAFMImage}{a binary \code{\link{AFMImage}} from Atomic Force Microscopy} \item{edge1}{one edge} \item{edges2}{list of edges} \item{minAngle}{the minimum angle value} } \value{ TRUE if all the angle are superior to the specified value } \description{ check if all the angles between one edge and a list of edges is superior to a specified value. } \author{ M.Beauvais }
b1981bcc3d3081fc6af18ff6fcecc3e013ed3586
787f2e5c1ec651cc69ea0a053eb0fe09be80cf65
/HW1.R
1fe3b9a4c44149117201c9898ee98d2cb0b091e5
[]
no_license
rstieger/CS1156x
7b9a4164aae05eff912c0c47bc3f46e36d2f03a6
016a272a35313be7f92ae80cdc94691b8f560f9b
refs/heads/master
2021-01-19T07:46:04.512092
2014-11-20T01:08:58
2014-11-20T01:08:58
null
0
0
null
null
null
null
UTF-8
R
false
false
1,509
r
HW1.R
makeTarget <- function() { p1 <- runif(2, min=-1, max=1) p2 <- runif(2, min=-1, max=1) b <- (p1[2]-p2[2])/(p1[1]-p2[1]) a <- p1[2]-b*p1[1] function(x) { sign(c(a,b,-1) %*% rbind(1,matrix(x,nrow=2)))} } makeHypothesis <- function(w) { function(x) { sign(t(w) %*% rbind(1,matrix(x,nrow=2)))} } makeInputs <- function(N) { matrix(data=runif(2 * N, min=-1, max=1), nrow=2, ncol = N, byrow=TRUE) } checkHypothesis <- function(f, h, x) { apply(x,2,function(x) {f(x) == h(x)}) } outOfSampleError <- function(f, g) { x <- makeInputs(100) 1-mean(checkHypothesis(f,g,x)) } runPLA <- function(x, f) { w <- c(0,0,0) N <- ncol(x) loopCount <- 1 done <- FALSE while (!done && loopCount < 100) { h <- makeHypothesis(w) c <- checkHypothesis(f,h,x) if (sum(c) == N) { done <- TRUE } else { element <- ceiling(runif(1,max=N)) while (c[element] == TRUE) { element <- element + 1 if (element > N) { element <- 1 } } w <- w + f(x[,element])[1] * rbind(1,matrix(x[,element],nrow=2)) } loopCount = loopCount + 1 } data.frame(iterations=loopCount, error=outOfSampleError(f, makeHypothesis(w))) } doExperiment <- function(N) { f <- makeTarget() x <- makeInputs(N) y <- f(x) # plot(x=x[1,],y=x[2,],col=y+3,xlim=c(-1,1),ylim=c(-1,1)) # abline(a=a,b=b) runPLA(x,f) }
af555156d6293dd280e4e14a1a1830e5d11d3686
9d515dfeb17d7ff8a3f00d960c2c799dfccc12b3
/Getting and Cleaning Data/Assighnment W2/Q2.R
9aab4ddfa1d7c13c5e9127e6edbd78f96459d79f
[]
no_license
rokbohinc86/2019.3.28.Data_Science-Specialization
af8e1c106f4ad6b6cb38a9c6aec2c1f09f0bd45c
066d2a4ec5b61edbf38ae643eac3c286ca9e0298
refs/heads/master
2020-08-05T14:17:39.837996
2019-10-03T12:34:17
2019-10-03T12:34:17
212,575,890
0
0
null
null
null
null
UTF-8
R
false
false
548
r
Q2.R
# library(RMySQL) do not read otherwise you will get an error library(sqldf) # set working directory and create dir named data where I download data setwd("/home/rok/Edjucation/2019.3.28. Data_Science-Specialization/Getting and Cleaning Data/Assighnment W2") if (!file.exists("data")){ dir.create("data") } fileURL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv" # download data download.file(fileURL, destfile = "./data/temp.csv", method = "curl") dateDownloaded <- date() # read acs <- read.csv("./data/temp.csv")
1ae9582506183a26162df6d9d6eb164821b41995
0595e02cc1e9f24d0abc59b30b3054469613980f
/R/utils.R
bdafcf46756bca582f20341965528ef2ab962a7a
[]
no_license
arturochian/ProteinVis
37cf342f47206a12c5cf2e2c44133966d46411b6
8f775d0246382dfa81045aa61134de82c82fa60b
refs/heads/master
2021-01-16T22:46:49.509149
2012-04-10T18:04:30
2012-04-10T18:04:30
null
0
0
null
null
null
null
UTF-8
R
false
false
2,187
r
utils.R
combineTMDomains = function(tmdf, poscols = c("start", "end")) { tmmat = matrix(NA, ncol = 2, nrow = nrow(tmdf)) curnumrow = 1 for (i in 1:nrow(tmdf)) { inserted = 0 for(j in 1:curnumrow) { if(!is.na(tmmat[j, 1])) { if (any(tmdf[i ,poscols] >= tmmat[j, 1] & tmdf[i, poscols ] <= tmmat[j, 2]) ) { tmmat[j , 1 ] = min( tmdf[ i , poscols[ 1 ] ] , tmmat[ j , 1 ] ) tmmat[j , 2 ] = max( tmdf[ i , poscols[ 2 ] ] , tmmat[ j , 2 ] ) inserted = 1 break() } } } if (!inserted) { tmmat[curnumrow,] = as.numeric(tmdf[i,poscols]) curnumrow = curnumrow + 1 } } tmmat = tmmat[!is.na(tmmat[,1]), , drop=FALSE] tmmat } calcPlotHeight = function(baseheight, type = "metaCount", pfam, categories) { if(!is.null(pfam) & nrow(pfam)) { myPFIRanges = IRanges(start = pfam$start, end = pfam$end) bins = disjointBins(myPFIRanges) } else { bins = 1 } denom = .20 + .25 + 1 #assume 1 pfam row and 5 categories if (type == "struct") { #.20 + .25 + .25 #the .25 is for the hydro, which isn't in the above plot. categories = NULL } baseheight * (1 + .2 /denom * ( max(bins) - 1) + .2 / denom* (length(unique(categories)) - 5 + 2)) #2 fake categories } spoofLevelsInDF = function(df, colname, newlevs, before = TRUE, force.factor = TRUE) { oldnrow = nrow(df) if(is.factor(df[[colname]])) oldlevs = levels(df[[colname]]) else oldlevs = unique(df[[colname]]) #XXX this doesn't seem to give us the right order!!! df[[colname]] = as.character(df[[colname]]) if(before) alllevs = unique(c(newlevs, oldlevs)) else alllevs = unique(c(oldlevs, newlevs)) for(i in seq(along = newlevs)) df[oldnrow + i, colname] = newlevs[i] if(force.factor) df[[colname]] = factor(df[[colname]], levels = alllevs) return(df) }
dabd16b2a892fc97abefa93cc4fb259e6dcee412
5f160e0117368a4864f0784ba163067ae705d5dc
/myR/R/dif.plot.R
f99e12e9680489d7b6119c091165ef70edbd52f0
[]
no_license
brunnothadeu/myR_package
e1a006a78c30f52970531decf824ff3d53ac3b3c
f56fb21c11a541bf6402bccd52760e9464e7c835
refs/heads/master
2020-04-04T06:38:54.029864
2018-11-20T19:19:43
2018-11-20T19:19:43
155,751,907
0
0
null
2018-11-01T18:02:06
2018-11-01T17:32:46
null
UTF-8
R
false
false
5,392
r
dif.plot.R
#' @title Gera os graficos de DIF #' @name dif.plot #' #' @description Cria um diretorio chamado 'DIF' e gera os graficos de Funcionamento Diferenciado Do Item (DIF). #' #' @param EXP Objeto resultante da funcao calcDIF. #' @param SCO Uma lista nomeada de acordo com os indices dos grupos em analise, contendo os percentis das distribuicoes de proficiencias. #' @param main String ou vetor com o(s) titulo(s) dos graficos. #' @param groups Vetor com o nome a ser plotado para cada um dos grupos, ordenado pelo indice do respectivo grupo. #' @param probs Quantiles utilizados para o calculo dos intervalos de interesse. #' @param col.dif Vetor com as cores a serem utilizadas nas curvas empiricas dos grupos. #' @param density Plotar na imagem a densidade das proficiencias de cada grupo ('area', 'points'). Caso NULL, a densidade sera omitida. #' @param dir.create Nome do diretorio a ser criado para guardar os graficos. #' @param xlim Limites do eixo X a ser plotados. #' @param height Altura em polegadas da imagem. #' @param width Largura em polegadas da imagem. #' @param shinyDemo Argumento auxiliar para o uso da funcao 'myR.app'. #' #' @details Etapa Anterior: 'checkDIF'. #' #' @author Brunno Bittencourt #' #' @examples #' EXP = remakeEXP(readLines("EXPtest.EXP")) #' #' newGroup = c(6, 7) #' #' EXP = calcDIF(EXP, newGroup) #' #' SCO = read.SCO(readLines("SCOtest.SCO")) #' #' SCO = lapply(split(SCO$SCO, SCO$Grupo), quantile, probs = c(.05, .95)) #' #' dif.plot(EXP, SCO) #' #' @import magrittr #' @import ggplot2 #' @importFrom grid pushViewport #' @importFrom gridBase baseViewports #' @importFrom randomcoloR distinctColorPalette #' @export dif.plot <- function(EXP, SCO, main = NULL, groups = NULL, probs = c(.05, .95), col.dif = NULL, density = "area", dir.create = "DIF", xlim = c(-4, 4), width = 9.6, height = 6.8, shinyDemo = NULL){ if(is.null(groups)) groups = paste0("Grupo", unique(SCO$Grupo)) if(is.null(col.dif)) col.dif = distinctColorPalette(length(groups)) if(is.null(shinyDemo)) dir.create(dir.create, showWarnings = FALSE) if(is.null(main)) main = names(EXP) if(length(main) < length(EXP) & is.null(shinyDemo)) stop("Dimensoes invalidas para main") if(!is.null(density)){ habs = SCO if(density == "points"){ habs = split(habs$SCO, habs$Grupo) for(i in seq_along(habs)) habs[[i]] = density(habs[[i]]) } } SCO = lapply(split(SCO$SCO, SCO$Grupo), quantile, probs = c(probs[1], probs[2])) for(i in seq_along(EXP)){ if(is.null(shinyDemo)){ pdf(file = paste0(getwd(), "/", dir.create,"/", paste0(names(EXP)[i], "_DIF.pdf")), width = width, height = height) }else{ i = shinyDemo } if(!is.null(density)){ layout(matrix(c(2, 1), ncol = 1, byrow = TRUE), widths = c(5/7, 2/7), heights = c(2/7, 5/7)) if(density == "area") par(mar = c(4, 4, 1, 1), mai = c(1.02, 0.82, 0.02, 0.42)) if(density == "points") par(mar = c(4.5, 4.5, 0, 1.5), bty = "o") } temp = EXP[[i]] nqp = nrow(temp) / (temp$Grupo %>% unique %>% length) plot(temp$POINT[1:nqp], seq(0, 1, length = nqp), type = "n", main = ifelse(is.null(density), main[i], ""), xlab = "Proficiencia", ylab = "Percentual de Respostas", ylim = c(0, 1), xlim = c(xlim[1], xlim[2])) lines(temp$POINT[1:nqp], temp$MODEL.PROP[1:nqp], lwd = 2) for(g in unique(temp$Grupo)){ lines(temp$POINT[temp$Grupo == g], temp$PROPORTION[temp$Grupo == g], col = col.dif[g], lwd = 2) abline(v = SCO[[g]][1], lty = 2, col = col.dif[g]) abline(v = SCO[[g]][2], lty = 2, col = col.dif[g]) } legend(-4.2, 1, lty = 1, lwd = 2, col = col.dif[unique(temp$Grupo)], legend = groups[1:length(groups) %in% unique(temp$Grupo)], box.lty = 0, text.font = 2) if(!is.null(density)){ if(density == "area"){ plot.new() vps = baseViewports() pushViewport(vps$figure) vp1 = plotViewport(c(-1, 3.4, 1, 1.5)) g = ggplot(habs[habs$Grupo %in% temp$Grupo, ], aes(SCO, fill = Grupo)) + geom_density(alpha = 0.2) + ggtitle(main[i]) + labs(x = NULL, y = NULL) + xlim(c(xlim[1], xlim[2])) + scale_y_continuous(breaks = NULL) + scale_fill_manual(breaks = unique(temp$Grupo), values = col.dif[unique(temp$Grupo)]) + theme(legend.position = "none", panel.background = element_rect(fill = "transparent", colour = NA), plot.background = element_rect(fill = "transparent", colour = NA), axis.text.x = element_blank(), plot.title = element_text(hjust = .5)) print(g, vp = vp1) } if(density == "points"){ par(mar = c(0, 4.5, 2, 1.5), bty = "n") plot(temp$POINT[1:nqp], seq(0, max(unlist(lapply(habs, FUN = function(x) x[[2]]))), length = nqp), type = "n", main = main[i], xaxt = "n", yaxt = "n", ann = FALSE) for(i in seq_along(habs)[seq_along(habs) %in% temp$Grupo]){ info = cbind(habs[[i]][["x"]], habs[[i]][["y"]]); info = info[seq(1, nrow(info), 4), ] points(info[, 1], info[, 2], col = col.dif[i], pch = 16, cex = .5) } } } if(is.null(shinyDemo)){ dev.off() }else{ break } } }
c99ee1d0eb27cca43f110900df5a5ff4a36fb655
bb1fc4854812f2efe4931ca3c0d791317309e425
/scripts/older_scripts/tiger_one_at_a_time.R
a64c0ee0296c326d4a80fea0d281d610351a10fa
[ "Apache-2.0" ]
permissive
dlab-berkeley/Geocoding-in-R
890e491d84808e29d07897508dc44f2bd9a3f646
40a0369f3b29a5874394ffafd793edc7012144ea
refs/heads/master
2023-03-06T07:54:41.997542
2021-02-18T17:42:22
2021-02-18T17:42:22
47,520,653
5
1
null
null
null
null
UTF-8
R
false
false
2,471
r
tiger_one_at_a_time.R
#library(httr) library(RJSONIO) gurl <- "http://geocoding.geo.census.gov/geocoder/geographies/address?street=912+Kingston+Ave&city=Piedmont&state=CA&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&format=json" bad_gurl <-"http://geocoding.geo.census.gov/geocoder/geographies/address?street=912+Kingston+Ave&city=donkey&state=CA&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&format=json" tiger_prefix <- "http://geocoding.geo.census.gov/geocoder/geographies/address?" tiger_suffix <- "&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&format=json" #g_out <- GET(gurl) g_out <- fromJSON(gurl) str(g_out) # take the first returned values in case > 1 matches lon <- g_out$result$addressMatches[[1]]$coordinates[['x']] lat <- g_out$result$addressMatches[[1]]$coordinates[['y']] matchedAddress <- g_out$result$addressMatches[[1]]$matchedAddress tractfips <- g_out$result$addressMatches[[1]]$geographies$`Census Tracts`[[1]]$GEOID blockfips <- g_out$result$addressMatches[[1]]$geographies$`Census Blocks`[[1]]$GEOID # another way g_out2 <- unlist(g_out) head(g_out2) g_out2['result.addressMatches.coordinates.x'] #Now process a file of addresses: tiger_input_addressFile <- "tiger/tiger_12addresses_to_geocode.csv" # let's take a look at the addresses that we will geocode addresses_to_geocode <- read.csv(tiger_input_addressFile, stringsAsFactors = FALSE, col.names = c('id','street','city','state','zip')) addresses_to_geocode addresses_to_geocode$tiger_format <- paste0( "street=",addresses_to_geocode$street, "&city=",addresses_to_geocode$city, "&state=",addresses_to_geocode$state, "&zip=",addresses_to_geocode$zip ) # geocode a file of addresses - one at at time tgeocode <- function(address){ address <- URLencode(address) g_address <- paste0(tiger_prefix, address,tiger_suffix) print(g_address) g_out <- tryCatch( fromJSON(g_address) # result will be returned if no error ) if (length(g_out$result$addressMatches) > 0) { print(g_out$result$addressMatches[[1]]$matchedAddress) } else{ #no results } } ## apply the geocoding function to the CSV file library(plyr) ldply(addresses_to_geocode$tiger_format,function(x) tgeocode(x)) #address <- c("The White House, Washington, DC","The Capitol, Washington, DC") #locations <- ldply(address, function(x) geoCode(x)) #names(locations) <- c("lat","lon","location_type", "formatted") #head(locations)
ad1bb28122d7a556f6efd46677b6cc346ca72fe9
4f77ba4fdc074fdd2b119c293653011af6c6dcda
/R/haplo-match-cif.r
fb00c59fc33a9b77a1a1df601876eedc14999100
[]
no_license
karthy257/HaploSurvival
526125cd792efb91b88db1ad2b9a445393f5e3a0
4661eab94edd62e79dcdaefbe2dc05fb01840c5b
refs/heads/master
2021-03-06T14:54:05.583732
2019-05-16T11:21:43
2019-05-16T11:21:43
null
0
0
null
null
null
null
UTF-8
R
false
false
1,106
r
haplo-match-cif.r
haplomatch.cif<-function(formula,data=sys.parent(), cause,times,designfuncX,designfuncZ,Nit=50, clusters=NULL,gamma=0,n.sim=500,weighted=0,model="additive", causeS=1,cens.code=0,detail=0,interval=0.01,resample.iid=1, cens.model="KM",time.pow=0,fix.haplofreq=0,haplo.freq=NULL,alpha.iid=NULL, geno.setup=NULL,fit.haplofreq=NULL,design.test=0,covnamesX=NULL,covnamesZ=NULL) { call <- match.call() m <- match.call(expand = FALSE) out<- haplo.cif( formula = formula,data=data, cause,times, designfuncX,designfuncZ, Nit = Nit, clusters=clusters, gamma=gamma, n.sim = n.sim, match=TRUE, weighted=weighted,model=model,causeS=causeS, cens.code=cens.code, detail = detail, interval=interval, resample.iid=resample.iid, cens.model=cens.model,time.pow=time.pow, fix.haplofreq = fix.haplofreq, haplo.freq =haplo.freq, alpha.iid=alpha.iid, geno.setup=geno.setup, fit.haplofreq=fit.haplofreq,design.test=design.test, covnamesX=covnamesX,covnamesZ=covnamesZ) attr(out, "Call") <- sys.call() attr(out, "Formula") <- formula return(out) }
905da2c370ff1e2d49a15d3a450d5b274fa48f20
0a906cf8b1b7da2aea87de958e3662870df49727
/grattan/inst/testfiles/anyOutside/libFuzzer_anyOutside/anyOutside_valgrind_files/1610129556-test.R
55bdf735643771f41cb65dd4eb9623ff48279347
[]
no_license
akhikolla/updated-only-Issues
a85c887f0e1aae8a8dc358717d55b21678d04660
7d74489dfc7ddfec3955ae7891f15e920cad2e0c
refs/heads/master
2023-04-13T08:22:15.699449
2021-04-21T16:25:35
2021-04-21T16:25:35
360,232,775
0
0
null
null
null
null
UTF-8
R
false
false
371
r
1610129556-test.R
testlist <- list(a = -1L, b = -230L, x = c(8388608L, 536873984L, -1L, 1560281088L, 0L, 0L, 0L, 0L, 0L, -163L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 255L, -193L, -14155813L, -250L, 50331647L, -193L, -14155904L, 8192L, 201523195L, -16814507L, -14024705L, -37L, -1L, -12583129L, -56833L, -8650752L, 14869218L, 41L)) result <- do.call(grattan:::anyOutside,testlist) str(result)
cbc724f66c331f314ea96ee7977df8e7761ac986
352056ed20f0739afde982c5115417582ed1f92d
/run_analysis.R
cdef09cd9267325abfb204e6d097f0f32e12084c
[]
no_license
arunchaudharee/Getting-and-Cleaning-Data-Project
ba8c6a7068fa740415544f56ceaba9485cb97fc4
f7a0edd85cc9c275f67f32a730c458feef762c48
refs/heads/master
2021-04-06T08:16:16.452139
2018-03-13T01:08:30
2018-03-13T01:08:30
124,890,112
0
0
null
null
null
null
UTF-8
R
false
false
6,332
r
run_analysis.R
## Getting and Cleaning Data Course Project ## This R script called run_analysis.R downloads the data from the following link and does the following: ## download link - https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip ## 1. Merges the training and the test sets to create one data set. ## 2. Extracts only the measurements on the mean and standard deviation for each measurement. ## 3. Uses descriptive activity names to name the activities in the data set ## 4. Appropriately labels the data set with descriptive variable names. ## 5. From the data set in step 4, creates a second, independent tidy data set with ## the average of each variable for each activity and each subject. ## This code is written in RStudio, R version 3.4.3, in Windows 10 OS. ## First download the zipped dataset, unzip it and read readme file, activity_labels, features, features_info files ## and check data files in each of the folders ## Downloading of file and unzip can be done manually or through coding ## tidying of dataset will require dplyr package or reshape2 package so install if not already installed ## In this code, "reshape2" package is used for data tidying ## First clear the environment rm(list=ls()) ## Downloading of file and unzip can be done manually or through coding ## tidying of dataset will require dplyr package or reshape2 package, install if not already installed ## In this code, reshape2 package is used for data tidying ## Check if the "reshape2" package is installed. if(!is.element("reshape2", installed.packages())) { # It package is not installed,install it, and then load it install.packages("reshape2") library(reshape2) } ## Initialize some initial values for folders that are to be downloaded and unzipped ## Get the path of working directory path <- getwd() downloadFolder <- "UCI HAR Dataset" zippedfile <- "dataset.zip" url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" # Check if the user has already unzipped the file if(!file.exists(downloadFolder)) { # Is there a zip file? if(!file.exists(zippedfile)) { # if zip file is not downloaded, downlaod it download.file(url,file.path(path, zippedfile)) } # Now, unzip the file unzip(zippedfile) } ## unzipped files are in the folder UCI HAR Dataset. See the list of files in it. downloaded_path <- file.path(path, "UCI HAR Dataset") files<-list.files(downloaded_path, recursive=TRUE) files ## 1. Merges the training and the test sets to create one data set. # To merge different data files, first rbind it and then cbind it. # Read in the data of train folders # Use file.data function for the path to a file train_subjects <- read.table(file.path(path, "UCI HAR Dataset/train/subject_train.txt")) train_data <- read.table(file.path(path, "UCI HAR Dataset/train/X_train.txt")) train_activities <- read.table(file.path(path, "UCI HAR Dataset/train/y_train.txt")) # Read in the data of test folders test_subjects <- read.table(file.path(path, "UCI HAR Dataset/test/subject_test.txt")) test_data <- read.table(file.path(path, "UCI HAR Dataset/test/X_test.txt")) test_activities <- read.table(file.path(path, "UCI HAR Dataset/test/y_test.txt")) ## Look at the structure/properties of the above variables str(train_subjects) str(train_data) str(train_activities) str(test_subjects) str(test_data) str(test_activities) ## Combine the all tables by the rows together row_data <- rbind(train_data, test_data) row_activities <- rbind(train_activities, test_activities) row_subjects <- rbind(train_subjects, test_subjects) # Now combine all different columns together into one table combined_data <- cbind(row_subjects, row_activities, row_data) ## 2. Extracts only the measurements on the mean and standard deviation for each measurement. # Load features of the dataset ## Read features.txt file features <- read.table(file.path(path, "UCI HAR Dataset/features.txt")) ## Extract only the mean and std (standard deviation) of measurements into the combined table. mean_std_Features <- features[grep("-(mean|std)\\(\\)", features[, 2 ]), 2] combined_data <- combined_data[, c(1, 2, mean_std_Features)] ## 3. Uses descriptive activity names to name the activities in the data set # Load activity labels of the dataset where activity names are found. ## Read activity_label.txt file activityNames <- read.table(file.path(path, "UCI HAR Dataset/activity_labels.txt")) # Update the activity names into the combined table combined_data[, 2] <- activityNames[combined_data[,2], 2] ## 4. Appropriately labels the data set with descriptive variable names. ## Remove the brackets from the features columns measurements <- gsub("[()]", "", as.character(mean_std_Features)) ## Name the column names of the combined data with "subjectNum", "activity" and features names found in measurements colnames(combined_data) <- c("subjectNum", "activity", measurements) ## Now name the features labelled with descriptive variable names. # Replace prefix t by time names(combined_data)<-gsub("^t", "time", names(combined_data)) # Replace prefix f by frequency names(combined_data)<-gsub("^f", "frequency", names(combined_data)) # Replace Gyro by Gyroscope names(combined_data)<-gsub("Gyro", "Gyroscope", names(combined_data)) # Replace Acc by Accelerometer names(combined_data)<-gsub("Acc", "Accelerometer", names(combined_data)) # Replace Mag by Magnitude names(combined_data)<-gsub("Mag", "Magnitude", names(combined_data)) # Replace BodyBody by Body names(combined_data)<-gsub("BodyBody", "Body", names(combined_data)) ## Let's coerce the data of 2nd column - "activity" into strings combined_data[, 2] <- as.character(combined_data[, 2]) ## 5. From the data set in step 4, creates a second, independent tidy data set with ## the average of each variable for each activity and each subject. ## Melt the data so we have a unique row for each combination of subject and activities melted_data <- reshape2::melt(combined_data, id = c("subjectNum", "activity")) # Cast the melted data getting the mean value. mean_data <- reshape2::dcast(melted_data, subjectNum + activity ~ variable, fun.aggregate = mean) # Write the data out to a file write.table(mean_data, file=file.path("tidydata.txt"), row.names = FALSE, quote = FALSE)
e2079bfbf755538e1feb173eb22babfa184c10cf
dde087158294465134dee9ddaba934b73f42e6ef
/get_weather.R
277bc02c956f6510bd7524e41e0108462be9f0d3
[]
no_license
joebrew/tbd
ef332510b4cd43fddf9311ba146e0404d3932885
fb22c30a922c99c538474b818234cb06125dec13
refs/heads/master
2021-08-22T23:48:17.213421
2017-12-01T18:52:02
2017-12-01T18:52:02
112,350,548
0
0
null
null
null
null
UTF-8
R
false
false
9,840
r
get_weather.R
library(tidyverse) library(RCurl) # Define function to replace NAs (coded in noaa as 99.9 by NOAA) detect_noaa_na <- function(x){ x <- as.character(x) y <- gsub('.', '', x, fixed = TRUE) oks <- y == x out <- unlist(lapply(strsplit(y, ''), function(x){all(x == '9')})) out[oks] <- FALSE out } # Define functions for converting from farenheit to celcius f_to_c <- function(x){ x <- x - 32 x <- x * (5/9) x } # Define function for converting from inches to milimeters i_to_m <- function(x){ x <- x * 25.4 x } # Define function to calculate distance from each district centroid to the weather stations get_distance <- function (lon1, lat1, lon2, lat2) { rad <- pi/180 a1 <- lat1 * rad a2 <- lon1 * rad b1 <- lat2 * rad b2 <- lon2 * rad dlon <- b2 - a2 dlat <- b1 - a1 a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2 c <- 2 * atan2(sqrt(a), sqrt(1 - a)) R <- 6378.145 d <- R * c return(d) } # Define function to get weather for certain location get_weather_for_location <- function(noaa, lng, lat){ out <- noaa y <- lat x <- lng # Get distance to all locations out$distance <- NA for (i in 1:nrow(out)){ out$distance[i] <- get_distance(lon1 = lng, lat1 = lat, lon2 = out$lon[i], lat2 = out$lat[i]) } # Create a weight column out$weight <- 1 / out$distance out$weight[is.infinite(out$weight)] <- 1 # Group by date and get weighted averages out <- out %>% group_by(date) %>% summarise(lat = y, lon = x, temp = weighted.mean(temp, w = weight, na.rm = TRUE), dewp = weighted.mean(dewp, w = weight, na.rm = TRUE), wdsp = weighted.mean(wdsp, w = weight, na.rm = TRUE), mxspd = weighted.mean(mxspd, w = weight, na.rm = TRUE), max = weighted.mean(max, w = weight, na.rm = TRUE), min = weighted.mean(min, w = weight, na.rm = TRUE), prcp = weighted.mean(prcp, w = weight, na.rm = TRUE)) return(out) } get_data <- function(years = 2000:2017){ if(!dir.exists('gsod')){ dir.create('gsod') } owd <- getwd() setwd('gsod') for (i in 1:length(years)){ this_year <- years[i] system(paste0('wget -m ftp://ftp.ncdc.noaa.gov/pub/data/gsod/', this_year)) } setwd(owd) } get_data() # # Function for manually retrieving, no longer relevant # # get_data <- function(directory = 'noaa_raw', # # year = 2017){ # # url_base <- "ftp://ftp.ncdc.noaa.gov/pub/data/gsod/" # # url <- paste0(url_base, year, '/') # # # userpwd <- "yourUser:yourPass" # # filenames <- getURL(url, # # # userpwd = userpwd, # # ftp.use.epsv = FALSE, # # dirlistonly = TRUE) # # filenames <- unlist(strsplit(filenames, '\n')) # # for (i in 1:length(filenames)){ # # this_file <- filenames[i] # # new_name <- paste0(directory, '/', gsub('.gz', '', this_file, fixed = TRUE)) # # if(!file.exists(new_name)){ # # try({ # # message('Retrieiving ', this_file, ' (', i, ' of ', length(filenames), ' for year ', year, ')') # # # Delete before downloading # # if(file.exists('temp.op.gz')){ # # file.remove('temp.op.gz') # # } # # if(file.exists('temp.op')){ # # file.remove('temp.op') # # } # # # Download # # download.file(url = paste0(url, this_file), # # destfile = 'temp.op.gz') # # # Extract # # R.utils::gunzip('temp.op.gz') # # # Move # # file.copy(from = 'temp.op', # # to = new_name) # # }) # # } # # } # # } # # # for(i in 2010:2017){ # # get_data(year = i) # # } # # # # # # # Read in all data # raw_data <- dir('noaa_raw/') # data_list <- list() # for (i in 1:length(raw_data)){ # message(i, ' of ', length(raw_data)) # this_file <- raw_data[i] # suppressMessages(this_table <- read_table(paste0('noaa_raw/', this_file))) # this_table <- # this_table %>% # dplyr::select(`STN---`, YEARMODA, TEMP, DEWP, SLP, STP, VISIB, WDSP, MXSPD, GUST, MAX, MIN, PRCP, SNDP, FRSHTT) # names(this_table)[1] <- 'USAF' # this_table$USAF <- as.character(this_table$USAF) # this_table <- data.frame(this_table) # for(j in 1:ncol(this_table)){ # this_table[,j] <- as.character(this_table[,j]) # } # data_list[[i]] <- this_table # } # a <- bind_rows(data_list) # # # # Join to station information # # Read in station info # b <- read_table('noaa_data/isd-history_may_2017.txt', skip = 20) # b <- b %>% dplyr::select(USAF, `STATION NAME`, CTRY, LAT, LON, `ELEV(M)`) # b <- b %>% rename(station_name = `STATION NAME`, country = CTRY, lat = LAT, lon = LON, elevation = `ELEV(M)`) # # b$USAF <- as.numeric(b$USAF) # b <- b %>% # filter(!duplicated(USAF)) # # # Join # noaa <- left_join(a, b, # by = 'USAF') # # # Make date column # noaa$date <- as.Date(paste0(substr(noaa$YEARMODA,start = 1, stop = 4), # '-', # substr(noaa$YEARMODA,start = 5, stop = 6), # '-', # substr(noaa$YEARMODA,start = 7, stop = 8))) # # # Make lowercase column names # names(noaa) <- tolower(names(noaa)) # # # Keep only columns of interest # noaa <- # noaa %>% # dplyr::select(country, # station_name, # usaf, # date, # temp, # dewp, # slp, # stp, # visib, # wdsp, # mxspd, # gust, # max, # min, # prcp, # sndp, # frshtt, # lat, # lon, # elevation) # # # Clean up NAs # noaa <- data.frame(noaa) # for (j in 5:ncol(noaa)){ # noaa[,j] <- ifelse(detect_noaa_na(noaa[,j]), # NA, # noaa[,j]) # } # # # Convert to number # convert_to_number <- # function(x){ # x <- regmatches(x, gregexpr("[[:digit:]]+", x)) # if(length(unlist(x)) == 0){ # y <- NA # } else { # y <- lapply(x, function(z){ # if(length(z) == 2){ # out <- as.numeric(paste0(z[1], '.', z[2])) # } else { # out <- unlist(z)[1] # } # return(out) # }) # } # return(as.numeric(unlist(y))) # } # # # # Clean up column types # noaa <- # noaa %>% # mutate(temp = convert_to_number(`temp`), # max = convert_to_number(`max`), # min = convert_to_number(`min`), # prcp = convert_to_number(`prcp`), # wdsp = convert_to_number(`wdsp`), # visib = convert_to_number(`visib`), # stp = convert_to_number(`stp`), # sndp = convert_to_number(`sndp`), # dewp = convert_to_number(`dewp`), # slp = convert_to_number(`slp`), # mxspd = convert_to_number(`mxspd`), # gust = convert_to_number(gust)) # # # Since noaa has some missing days, interpolate # left <- expand.grid(station_name = sort(unique(noaa$station_name)), # date = sort(unique(noaa$date))) # noaa <- left_join(left, # noaa, # by = c('station_name', 'date')) # # Flag estimations # noaa$estimated <- ifelse(is.na(noaa$lat), TRUE, FALSE) # # Performance interpolation # x <- # noaa %>% # arrange(date) %>% # group_by(station_name) %>% # mutate(temp = zoo::na.approx(object = temp, # x = date, # na.rm = FALSE), # dewp = zoo::na.approx(object = dewp, # x = date, # na.rm = FALSE), # wdsp = zoo::na.approx(object = wdsp, # x = date, # na.rm = FALSE), # mxspd = zoo::na.approx(object = mxspd, # x = date, # na.rm = FALSE), # max = zoo::na.approx(object = max, # x = date, # na.rm = FALSE), # min = zoo::na.approx(object = min, # x = date, # na.rm = FALSE), # prcp = zoo::na.approx(object = prcp, # x = date, # na.rm = FALSE), # visib = zoo::na.approx(object = visib, # x = date, # na.rm = FALSE), # slp = zoo::na.approx(object = slp, # x = date, # na.rm = FALSE), # stp = zoo::na.approx(object = stp, # x = date, # na.rm = FALSE), # gust = zoo::na.approx(object = gust, # x = date, # na.rm = FALSE), # sndp = zoo::na.approx(object = sndp, # x = date, # na.rm = FALSE), # elevation = zoo::na.approx(object = elevation, # x = date, # na.rm = FALSE)) # # # Fix missing lat/lons # ll <- noaa %>% # group_by(station_name) %>% # summarise(lat = dplyr::first(lat[!is.na(lat)]), # lon = dplyr::first(lon[!is.na(lon)])) # # noaa <- x %>% ungroup %>% # dplyr::select(-lat, # -lon) %>% # left_join(ll, # by = 'station_name') #
819aeb80a39f515621f34d2b36a18d67316c8e0a
adecabf2b7801f7be4ef7dce51dece192406ec45
/Misc. Charts/SpC & NOx Violin Plots_POR 20180914 to 20190709.R
34c12289faf049ac412c2306b31c364c9c8bb780
[]
no_license
ETaylor21/gnv_streams
ae6933c46f384a0d75644c114840a3f3d6d69789
6a54e58738ff2beae9afb36e04dae855a1a1b935
refs/heads/master
2021-11-04T04:33:19.212474
2021-11-01T05:38:47
2021-11-01T05:38:47
171,563,273
0
0
null
2019-03-14T14:05:21
2019-02-19T22:55:41
R
UTF-8
R
false
false
1,683
r
SpC & NOx Violin Plots_POR 20180914 to 20190709.R
##### Violin Plots of NOx and SpC For AJ NSF Proposal 10/16/19#### ####NOx, O_P, NH4 all filtered samples### #NOx - Nitrate(NO3)-Nitrite(NO2)-N (mg/L) #SpCond - specific conductivity (uS/cm) ####Sample Replications (col = Rep) #a = 1; b = 2; c = 3; d = not a rep just a reading ########################Call in and format data######################################## #call in packages library(tidyverse) library(lubridate) library(RColorBrewer) #set working directory setwd('C:/Users/Emily/Documents/gnv_streams/Misc. Charts') #call in data file data_nut = read_csv('gnv_nutspdata_20191016.csv', col_types = cols( Site = col_character(), Date = col_date(format = "%m/%d/%Y"), Analyte = col_character(), Result = col_double()))#nutrient data; fixed date format for date column\ #####NOx and SpC Violin Plots (nvp)#### nd2 = data_nut %>% group_by(Date, Site, Analyte) %>% summarise(mean = mean(Result)) windows() nvp = ggplot(nd2, aes(x = Site, y = mean, fill = Analyte)) + geom_violin(scale = 'count', adjust = 0.5) + ylab('Results (uS/cm) Results (mg/L)') nvp2 = nvp + scale_x_discrete(labels = c('Hatchet', 'N. Hogtown', 'S. Hogtown', 'Possum', 'Sweetwater', 'Tumblin'))#change the names on the x axis, use discrete since non-numeric values nvp3 = nvp2 + facet_wrap( . ~ Analyte , scales = 'free_y', nrow = 2) + theme(strip.text = element_text(size = 18)) + scale_fill_manual(values = c('#56B4E9','#D55E00', '#009E73' )) + guides(fill = FALSE) + theme(axis.text = element_text(size = rel(1.2))) + theme(axis.title = element_text(size = rel(1.3))) + theme(axis.title.x = element_blank()) nvp3