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
cfd4c27c3dfe783305ba901d9f4a81733bee1886
91134c9c434ee7ce2529efa478faa820dce61e0a
/Programs/Method_eval/method_eval4_run2.R
c06923f641a0dc9e12a1cf80c0c21c93ec77f5d0
[]
no_license
Adam-Brand/Pooled_Testing_HIV
9855603f21eac6f479b035cadf446907d2a550e8
c82c184da1a028fdc4170ba4b105e6e212d09e6f
refs/heads/master
2023-06-19T00:59:02.218768
2021-07-19T11:48:31
2021-07-19T11:48:31
266,970,102
0
0
null
null
null
null
UTF-8
R
false
false
16,489
r
method_eval4_run2.R
#============================================================================== # FILENAME: method_eval4_run2.R # PROJECT: Pooled testing in HIV # PURPOSE: This program calls the main evaluation function to evaluate the pooled testing methods # in different scenarios, 4 different scenarios each evaluated in 13 different MEs using # the SD=0 data; does not evaluate the hypred method, that is a separate program # # # AUTHOR: Adam Brand # INPUT datasets: Uganda_SimData_SD0.rds # SD0_data_500_run2_perm.rds # OUTPUT datasets: 52 results table located here: Pooled_Testing_HIV/Results/SimResults # 13 file names beginning with Results_AGAIG_SD0 # 13 file names beginning with Results_reverse_SD0 # 13 file names beginning with Results_noassoc_SD0 # 13 file names beginning with Results_misspec_SD0 # R VERSION: 3.6.1 #============================================================================== #Notes: # ============================================================================= ### Evaluating the methods (except for Hypred) in the AGAIG and reverse scenarios using the ### simulated data with SD=0 library(tidyverse) library(dplyr) library(here) #### sourcing the main source file with all the needed functions source("Programs/method_eval_source.R") ############################################################################################## ##### AGAIG scenarios using SD=0 and estimated betas data <- readRDS("SimData/Uganda_SimData_SD0.rds") #### these betas are the same that generated the data; scenario of perfect prediction accuracy data <- predictVL(data, b0star=0.5, b1star=0.1, b2star=2, b3star=0.1) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=0, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME0_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.025, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.025_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.05, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.05_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.075, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.075_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.1, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.1_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.125, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.125_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.15, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.15_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.175, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.175_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.2, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.2_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.225, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.225_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.25, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.25_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.5, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.5_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.75, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_AGAIG_SD0_ME.75_rand.rds")) ##### reverse scenarios using SD=0 and estimated betas from the reverse training set data <- readRDS("SimData/Uganda_SimData_SD0.rds") data <- predictVL(data, b0star=6, b1star=-0.1, b2star=-2, b3star=-0.1) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=0, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME0_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.025, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.025_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.05, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.05_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.075, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.075_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.1, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.1_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.125, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.125_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.15, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.15_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.175, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.175_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.2, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.2_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.225, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.225_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.25, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.25_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.5, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.5_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.75, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_reverse_SD0_ME.75_rand.rds")) ##### no prediction association scenarios using SD=0 and estimated betas data <- readRDS("SimData/Records_used_in_500_matrices_hypred/SD0_data_500_run2_perm.rds") #### these betas are the same that generated the data to provide perfect prediction #### the data used has had the VL permuted, so there is no association to the prediction model data <- predictVL(data, b0star=0.5, b1star=0.1, b2star=2, b3star=0.1) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=0, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME0_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.025, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.025_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.05, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.05_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.075, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.075_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.1, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.1_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.125, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.125_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.15, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.15_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.175, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.175_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.2, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.2_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.225, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.225_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.25, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.25_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.5, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.5_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.75, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_noassoc_SD0_ME.75_rand.rds")) ##### misspecified model scenarios using SD=0 and estimated betas data <- readRDS("SimData/Uganda_SimData_SD0.rds") #### these betas are set to reflect a misspecified model data <- predictVL(data, b0star=2, b1star=0.3, b2star=0, b3star=0) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=0, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME0_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.025, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.025_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.05, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.05_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.075, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.075_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.1, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.1_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.125, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.125_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.15, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.15_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.175, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.175_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.2, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.2_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.225, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.225_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.25, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.25_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.5, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.5_rand.rds")) set.seed(18) result1 <- pool.alg.cov(reps=500, data=data, matsize=10, prec=10, precrd=20, cutoff=1000, SE=.75, tstperd=5, lowlimit=50, filltyp="rnd") saveRDS(result1, file=here("Results","SimResults","Results_misspec_SD0_ME.75_rand.rds"))
e2c5d172f20474e30f0fcd404c2dbd54254c2309
49688b6a367dbfa82bfa1c96f00fd6291bcf2de3
/functions.R
6bb09a3537a9c1b7c8629e03e7e6aead72350ca5
[ "MIT", "CC-BY-3.0" ]
permissive
yanirmor/shiny-soccer-analysis
45ce69203c97ebe8e98b10a7c9cb49f3b655fdc6
64320404b99ca831cb2f7db2fc9df5fa6ce24c94
refs/heads/master
2021-06-28T11:32:27.961617
2021-01-18T14:40:39
2021-01-18T14:40:39
200,484,757
0
1
MIT
2021-01-18T14:40:40
2019-08-04T11:33:22
R
UTF-8
R
false
false
401
r
functions.R
nudge_small_nodes <- function(dimension, value, main_axis = T) { max_value <- if (dimension == "x") 10500 else 6750 if (main_axis) { case_when( value < max_value * 0.06 ~ max_value * 0.03, value > max_value * 0.94 ~ -1 * max_value * 0.03, T ~ 0 ) } else { case_when( value < max_value / 2 ~ max_value * 0.06, T ~ -1 * max_value * 0.05 ) } }
935151e01e3764b882dc317ea97864fdda67420f
aa6b6bf70b316244ff92673456daac851f1c35ee
/ultraseq/man/mutect.Rd
55f6f39c06ada682805cc5134d51ecfb79b71024
[]
no_license
flow-r/ultraseq
742035de86d55019d5c52b1b9a2c1795ec6ac5b9
58f72866c5b2504c18fd3e472ae187b5471826c8
refs/heads/master
2022-10-05T01:22:44.717599
2016-05-12T03:55:19
2016-05-12T03:55:19
42,262,784
0
1
null
2016-05-25T15:57:52
2015-09-10T18:28:31
R
UTF-8
R
false
true
1,935
rd
mutect.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mutect.R \name{mutect} \alias{mutect} \title{A wrapper around somatic mutation caller MuTect} \usage{ mutect(tumor_bam, normal_bam, samplename = opts_flow$get("samplename"), out_prefix, is_merged = TRUE, split_by_chr = TRUE, java_exe = opts_flow$get("java_exe"), java_tmp = opts_flow$get("java_tmp"), mutect_jar = opts_flow$get("mutect_jar"), cpu_mutect = opts_flow$get("cpu_mutect"), mem_mutect = opts_flow$get("java_mem"), ref_fasta_path = opts_flow$get("ref_fasta_path"), mutect_opts = opts_flow$get("mutect_opts")) } \arguments{ \item{tumor_bam}{path to a tumor bam file} \item{normal_bam}{path to a normal bam file} \item{samplename}{name of the sample, to be added to the flowmat} \item{out_prefix}{output file name [optional]. By default, this is created using names of tumor and normal bam files.} \item{is_merged}{specify if the input bam is already split by chromosomes (FALSE) or is a merged file with all chromosome (TRUE). [FALSE]} \item{split_by_chr}{fork running mutect by chromosome to make it faster [TRUE]. Turning is option OFF is not fully supported.} \item{java_exe}{path to java's executable [java]} \item{java_tmp}{path to a temp folder to be used by java} \item{mutect_jar}{path to mutect's jar file} \item{cpu_mutect}{integer specifying number of thread to be used per mutect fork} \item{mem_mutect}{amount of memory to be used by mutect [-Xmx12g]} \item{ref_fasta_path}{path to the reference genome in fasta format} \item{mutect_opts}{additional arguments passed onto mutect} } \value{ The function returns a flowmat with all the commands. The final file is called \code{'out_prefix'_merged.mutect.tsv}. } \description{ This generates a set of commandlines, per chromosome } \examples{ \dontrun{ x = "tumor.bam" y = "normal.bam" out = mutect(x, y, samplename="tumor_normal", is_merged = TRUE) } }
498e5c5d3d9aa4e7e40e10b21332e2ecf40f418f
45eac501e19509f6d23b582d5758295ac18318dd
/Section3Lecture24 - Section Recap.R
1faa26b0ad429ba4997c04543d7bbfc03106b745
[]
no_license
ghettocounselor/R
2788bccfd72c69bb490fe47ca266c403e5f17c65
21755d048b15ae9ca85194c15b4893ddac194f67
refs/heads/master
2020-04-28T07:17:33.356620
2019-05-26T20:03:24
2019-05-26T20:03:24
175,086,650
1
1
null
null
null
null
UTF-8
R
false
false
40
r
Section3Lecture24 - Section Recap.R
#Kirill ran through the items we learned
7ddbff2a26a207281c6a4262c61159da389fc98b
ff6f6f2425660d2e2e0a68d8c30697cb04c30a82
/modules/module5.R
c2893c9ee1035c766b137e9c5b00be0b0f7c82eb
[]
no_license
muschellij2/summerR_2015
0425bfa3d189788749d0a5c5607a6d9f107e5ba5
986f517782d756a034f74d7dbc7c55c8ede66397
refs/heads/gh-pages
2020-12-24T14:01:01.039281
2015-09-02T21:04:01
2015-09-02T21:04:01
41,681,611
1
1
null
2015-08-31T14:54:49
2015-08-31T14:54:49
null
UTF-8
R
false
false
2,464
r
module5.R
## ----writecsv------------------------------------------------------------ circ = read.csv("../data/Charm_City_Circulator_Ridership.csv", header=TRUE,as.is=TRUE) circ2 = circ[,c("day","date", "orangeAverage","purpleAverage","greenAverage", "bannerAverage","daily")] write.csv(circ2, file="../data/charmcitycirc_reduced.csv", row.names=FALSE) ## ----xlsx1,eval=FALSE---------------------------------------------------- ## install.packages("xlsx") # OR: ## install.packages("xlsx", ## repos="http://cran.us.r-project.org") ## library(xlsx) # or require(xlsx) ## ----save1--------------------------------------------------------------- save(circ,circ2,file="../data/charmcirc.rda") ## ----ls------------------------------------------------------------------ ls() ## ----loadData------------------------------------------------------------ tmp=load("../data/charmcirc.rda") tmp ls() ## ----negativeIndex------------------------------------------------------- x = c(1,3,77,54,23,7,76,5) x[1:3] # first 3 x[-2] # all but the second ## ----negativeIndex2------------------------------------------------------ x[-c(1,2,3)] # drop first 3 # x[-1:3] # shorthand. R sees as -1 to 3 x[-(1:3)] # needs parentheses ## ----andEx--------------------------------------------------------------- # which Mondays had more than 3000 average riders? which(circ$day =="Monday" & circ$daily > 3000)[1:20] ## ----andEx2-------------------------------------------------------------- Index=which(circ$daily > 10000 & circ$purpleAverage > 3000) length(Index) # the number of days head(circ[Index,],2) # first 2 rows ## ----orEx1--------------------------------------------------------------- Index=which(circ$daily > 10000 | circ$purpleAverage > 3000) length(Index) # the number of days head(circ[Index,],2) # first 2 rows ## ----naEval-------------------------------------------------------------- circ$purpleAverage[1:10] > 0 which(circ$purpleAverage > 0)[1:10] ## ----inEx---------------------------------------------------------------- (circ$day %in% c("Monday","Tuesday"))[1:20] # select entries that are monday or tuesday which(circ$day %in% c("Monday","Tuesday"))[1:20] # which indices are true? ## ----colSelect----------------------------------------------------------- circ[1:3, c("purpleAverage","orangeAverage")] circ[1:3, c(7,5)] ## ----colRemove----------------------------------------------------------- tmp = circ2 tmp$daily=NULL tmp[1:3,]
6b3300f699163a2b6b41552443e377b332169aa6
fd093d5729ebc5979eadd02bfe41167d5f7ced46
/man/smallexample.Rd
d5805e4927b5ee2cf5b813643ff63e97aea747d6
[]
no_license
JohnlNguyen/freqparcoord.cd
6b42923b62d72c2a7a8c549757a11880c92445d8
2ebc98c9c358deb58825830338d353366e79e360
refs/heads/master
2021-01-22T03:22:59.717265
2017-05-25T07:26:39
2017-05-25T07:26:39
92,376,429
0
0
null
2017-05-25T07:18:00
2017-05-25T07:18:00
null
UTF-8
R
false
false
572
rd
smallexample.Rd
\name{smallexample} \alias{smallexample} \title{ A small example demonstrating freqparcoord.cd. } \description{ A small example showing how the freqparcoord.cd package creates parallel coordinate plots. } \usage{ smallexample(n) } \arguments{ \item{n}{ The optional number of top frequencies you'd like to select. } } \author{ Norm Matloff <matloff@cs.ucdavis.edu>, Harrison Nguyen <hhnguy@ucdavis.edu>, and Vincent Yang <vinyang@ucdavis.edu> } \examples{ # This will draw a plot for the smallexample.csv dataset smallexample() }
5139d6d6c53926104454b07fe3c95da76cc2cc0a
58a0cfa3891ea8fb2780cbd6a946b87825cd30a8
/calibration_joint_classic_phlo_MAR_90/compute.summary.statistics.classic.R
e9c36f8d1bd4ee1c4a0cfdf5dc578d46f01b06f3
[]
no_license
niyukuri/benchmark_master_model
e32d563345ae465b355618e18a635366a9cacede
e0c117f85d60eabf714f0eebbb056fab1cf576f7
refs/heads/master
2020-04-06T14:49:12.282181
2019-06-01T20:14:50
2019-06-01T20:14:50
157,555,333
0
0
null
null
null
null
UTF-8
R
false
false
10,701
r
compute.summary.statistics.classic.R
#' Computing epidmiological, demographical, sexual behavioural, and interventions realted summary statistics #' #' @param datalist.agemix Data list of simpact output produced by \code{\link{readthedata()}} #' @param timewindow Time window in which the experience is carried out #' @export # The outputs of the function are: # (i) Demographic # - Population growth # (ii) Epidemic # - Prevalence # - Incidence # (iii) Sexual behaviour # - point prevalence of conurrent relationships # - relationship per person per year # - mean, median and standard deviation of age gap # (iv) Interventions # - ART coverage # - Viral load suppression # "Pop.growthrate", # # "prev.15.25.men", "prev.15.25.women", # "prev.25.40.men", "prev.25.40.women", # "prev.40.50.men", "prev.40.50.women", # # "incid.15.24.men", "incid.15.24.women", # "incid.25.39.men", "incid.25.39.women", # "incid.40.49.men", "incid.40.49.women", # # "pp.cp.6months.male.rels", # # "relsperpersonperyear", # "agegap.mean", "agegap.med", "agegap.sd", # # "ART.cov.vector", "VL.suppression.fraction" compute.summary.statistics.classic <- function(datalist = datalist.agemix, timewindow = c(30, 40)){ source("/home/dniyukuri/lustre/calibration_joint_classic_phlo_MAR_90/needed.functions.RSimpactHelp.R") # source("/home/david/benchmark_master_model/needed.functions.RSimpactHelp.R") datalist.agemix <- datalist ######################################## # I. Behavioural and epidemic features # ######################################## # 1.2. Features from sexual and transmission network # # 1.2.1. Demographic feature: # (i) Population growth rate (pop.growth.calculator function) growthrate <- pop.growth.calculator(datalist = datalist.agemix, timewindow = timewindow) # c(0, datalist.agemix$itable$population.simtime[1]) # 1.2.2. Prevalence hiv.prev.lt25.women <- prevalence.calculator(datalist = datalist.agemix, agegroup = c(15, 25), timepoint = timewindow[2]) %>% dplyr::select(pointprevalence) %>% dplyr::slice(2) %>% as.numeric() hiv.prev.lt25.men <- prevalence.calculator(datalist = datalist.agemix, agegroup = c(15, 25), timepoint = timewindow[2]) %>% dplyr::select(pointprevalence) %>% dplyr::slice(1) %>% as.numeric() hiv.prev.25.40.women <- prevalence.calculator(datalist = datalist.agemix, agegroup = c(25, 40), timepoint = timewindow[2]) %>% dplyr::select(pointprevalence) %>% dplyr::slice(2) %>% as.numeric() hiv.prev.25.40.men <- prevalence.calculator(datalist = datalist.agemix, agegroup = c(25, 40), timepoint = timewindow[2]) %>% dplyr::select(pointprevalence) %>% dplyr::slice(1) %>% as.numeric() hiv.prev.40.50.women <- prevalence.calculator(datalist = datalist.agemix, agegroup = c(40, 50), timepoint = timewindow[2]) %>% dplyr::select(pointprevalence) %>% dplyr::slice(2) %>% as.numeric() hiv.prev.40.50.men <- prevalence.calculator(datalist = datalist.agemix, agegroup = c(40, 50), timepoint = timewindow[2]) %>% dplyr::select(pointprevalence) %>% dplyr::slice(1) %>% as.numeric() # Incidence incid.15.24.men <- incidence.calculator(datalist = datalist.agemix, agegroup = c(15, 25), timewindow = c(39, 40), only.active = "No") %>% dplyr::select(incidence) %>% dplyr::slice(1) %>% as.numeric() incid.15.24.women <- incidence.calculator(datalist = datalist.agemix, agegroup = c(15, 25), timewindow = c(39, 40), only.active = "No") %>% dplyr::select(incidence) %>% dplyr::slice(2) %>% as.numeric() incid.25.39.men <- incidence.calculator(datalist = datalist.agemix, agegroup = c(25, 40), timewindow = c(39, 40), only.active = "No") %>% dplyr::select(incidence) %>% dplyr::slice(1) %>% as.numeric() incid.25.39.women <- incidence.calculator(datalist = datalist.agemix, agegroup = c(25, 40), timewindow = c(39, 40), only.active = "No") %>% dplyr::select(incidence) %>% dplyr::slice(2) %>% as.numeric() incid.40.49.men <- incidence.calculator(datalist = datalist.agemix, agegroup = c(40, 50), timewindow = c(39, 40), only.active = "No") %>% dplyr::select(incidence) %>% dplyr::slice(1) %>% as.numeric() incid.40.49.women <- incidence.calculator(datalist = datalist.agemix, agegroup = c(40, 50), timewindow = c(39, 40), only.active = "No") %>% dplyr::select(incidence) %>% dplyr::slice(2) %>% as.numeric() # # Sexual behaviour # Point prevalence of concurrency in the adult population # Concurrency point prevalence 6 months before a survey, among men pp.cp.6months.male.rels <- concurr.pointprev.calculator(datalist = datalist.agemix, timepoint = timewindow[2] - 0.5) # pp.cp.6months.male.rels <- concurr.pointprev.calculator(datalist = datalist.agemix, # timepoint = timewindow[2] - 0.5) %>% # dplyr::select(concurr.pointprev) %>% # dplyr::slice(1) %>% # as.numeric() # # pp.cp.6months.female.rels <- concurr.pointprev.calculator(datalist = datalist.agemix, # timepoint = timewindow[2] - 0.5) %>% # dplyr::select(concurr.pointprev) %>% # dplyr::slice(2) %>% # as.numeric() # # (ii) Relationship per person per year ?? relsperpersonperyear <- nrow(datalist.agemix$rtable) / (nrow(datalist.agemix$ptable)/2) / (timewindow[2] - timewindow[1]) # (iv) SD age gap between couples agegap.mean <- mean(datalist.agemix$rtable$AgeGap) agegap.med <- median(datalist.agemix$rtable$AgeGap) agegap.sd <- sd(datalist.agemix$rtable$AgeGap) #### # ART coverage among adults 15+ years old from UNAIDS (2010 - 2017 estimates) #### ART.cov.eval.timepoints <- seq(from = 33, to = 40) ART.cov.vector <- rep(NA, length(ART.cov.eval.timepoints)) for (art.cov.index in 1:length(ART.cov.vector)){ ART.cov.vector[art.cov.index] <- sum(ART.coverage.calculator(datalist = datalist.agemix, agegroup = c(15, 50), timepoint = ART.cov.eval.timepoints[art.cov.index])$sum.onART) / sum(ART.coverage.calculator(datalist = datalist.agemix, agegroup = c(15, 50), timepoint = ART.cov.eval.timepoints[art.cov.index])$sum.cases) } names(ART.cov.vector) <- paste0("ART.", ART.cov.eval.timepoints) #### # VL suppression fraction (all ages in 2017 ~ >= 15 yo) 0.74 #### VL.suppression.fraction <- VL.suppression.calculator(datalist = datalist.agemix, agegroup = c(15, 50), timepoint = timewindow[2], vl.cutoff = 1000, site="All") %>% dplyr::select(vl.suppr.frac) %>% dplyr::slice(3) %>% as.numeric() names(VL.suppression.fraction) <- "VL.suppr." classic.features <- c(exp(growthrate), hiv.prev.lt25.men, hiv.prev.lt25.women, hiv.prev.25.40.men, hiv.prev.25.40.women, hiv.prev.40.50.men, hiv.prev.40.50.women, exp(incid.15.24.men), exp(incid.15.24.women), exp(incid.25.39.men), exp(incid.25.39.women), exp(incid.40.49.men), exp(incid.40.49.women), pp.cp.6months.male.rels, # pp.cp.6months.female.rels, relsperpersonperyear, agegap.mean, agegap.med, agegap.sd, ART.cov.vector, VL.suppression.fraction) classic.features.names <- c("Pop.growthrate", "prev.15.25.men", "prev.15.25.women", "prev.25.40.men", "prev.25.40.women", "prev.40.50.men", "prev.40.50.women", "incid.15.24.men", "incid.15.24.women", "incid.25.39.men", "incid.25.39.women", "incid.40.49.men", "incid.40.49.women", "pp.cp.6months.male.rels", "relsperpersonperyear", "agegap.mean", "agegap.med", "agegap.sd", paste0(names(ART.cov.vector)), paste0(names(VL.suppression.fraction))) names(classic.features) <- classic.features.names # classic.features.num <- as.numeric(classic.features) return(classic.features) }
798c278c6e0dd5b83c7d99f877c533a5d39b0aec
c58bc4d218260a2f195aeb885e20f19dcdd95eda
/GPareto.R
2c82cc5414f5b02599800dc93760b44a4f93793b
[]
no_license
misteliy/Rscripts
bdfca0452cbe220c6a23eea5d185c6b4bd00756c
a70029aff43d5d5625d729d956860acc4ec9c477
refs/heads/master
2020-03-21T17:32:41.993459
2018-09-11T21:26:47
2018-09-11T21:26:47
138,838,129
0
1
null
null
null
null
UTF-8
R
false
false
1,058
r
GPareto.R
library(GPareto) design.init <- matrix(seq(0, 1, length.out = 6), ncol = 1) response.init <- MOP2(design.init) mf1 <- km(~1, design = design.init, response = response.init[, 1]) mf2 <- km(~1, design = design.init, response = response.init[, 2]) model <- list(mf1, mf2) res <- GParetoptim(model = model, fn = MOP2, crit = "EHI", nsteps = 7, lower = 0, upper = 1, critcontrol = list(refPoint = c(2, 2))) plotParetoGrid(P1) myobj <- function (x) { if (is.null(dim(x))) { x <- matrix(x, nrow = 1) } #n <- ncol(x) #g <- 1 + rowSums(x[, 2:n, drop = FALSE]) * 9/(n - 1) #return(cbind(x[, 1], g * (1 - sqrt(x[, 1]/g)))) return(cbind(x^2,x[, 1])) # f1 <- x1, f2 <- g(x)*(1-sqrt(x1/g(x))) } res <- easyGParetoptim(fn = myobj, budget = 50, lower = rep(0, 4),upper = rep(1, 4)) library(caret) data("iris") control <- trainControl(method="cv", number = 5, classProbs = TRUE, summaryFunction = mnLogLoss) set.seed(7) fit <- train(Species~. ,data = iris, method = "rf", metric="logLoss", trControl = control) print(fit)
38a7a58e1586572aff389a395b9ecce561f5eb20
9ee0ab61b9d870fa5237a2869b60e9e8877f8403
/man/setFunctionData.Rd
0beac3764d8114d93d83fd05c5af51dfcee1cf9c
[]
no_license
AustralianAntarcticDivision/EPOC
79390dc3456a9cbacfb64884f10cdcf5fedad393
778be35f146197c571bb1ebfb76eb2a629eaad70
refs/heads/master
2020-09-09T22:12:49.843987
2019-11-14T01:55:36
2019-11-14T01:55:36
221,583,790
0
0
null
null
null
null
UTF-8
R
false
false
998
rd
setFunctionData.Rd
\name{setFunctionData} \alias{setFunctionData} \title{ Element methods } \description{ Set additonal user function data for element object./cr Set either the entire list or a single list item. } \usage{ setFunctionData(.Object, item = c("character", "missing"), value) } \arguments{ \item{.Object}{ Element object } \item{item}{ List item in functions list to set value at. Optional if value="list" } \item{value}{ Value to be set } } \details{} \value{ Returns modified element object invisibly } \references{} \author{ Troy Robertson } \note{} \seealso{ \code{\linkS4class{Element}, \linkS4class{EPOCObject}, \link{getFunctionData}} } \examples{ ## Set function data item "printState" to TRUE # setFunctionData(element, item="printState", value=TRUE) ## Set entire function data list # setFunctionData(element, value=fdlist) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ ~kwd1 } \keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
2a00dd1951709b1c8ab35a6f1694ceb392747c88
09e89406e888251996277b441feb5b84162bdaf5
/tests/run_tests.R
3f5092087a8e599ef4420c57b4983721b82b9375
[]
no_license
HarlanH/futile.logger
6d3e137a2b3587ae341346806468c554c51c9c08
0a4a90b4c7c40473a5926548fe78d7c1e5019bff
refs/heads/master
2021-01-16T22:23:37.983736
2015-03-19T17:36:22
2015-03-19T17:36:22
31,793,920
0
0
null
2015-03-06T23:32:25
2015-03-06T23:32:25
R
UTF-8
R
false
false
84
r
run_tests.R
library(testthat) library_if_available(futile.logger) test_package('futile.logger')
c2b062fcad33ed527eda02f2054153074ec816f1
3b4f982be895984cc74638d36da8f3fd64148a19
/man/tomsTools.Rd
08638a496e19d2b445f6e06111573da948b16f2e
[]
no_license
TomfromWales/tomsTools
f2a9de031c08dd6b7f995fa0aa041199dabd700e
8b779af57996a6e3e8867d635cb77dc8c5c40d3f
refs/heads/master
2021-09-19T21:26:21.779829
2017-12-24T16:39:46
2017-12-24T16:39:46
112,975,453
0
0
null
null
null
null
UTF-8
R
false
true
257
rd
tomsTools.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tomsTools-package.R \docType{package} \name{tomsTools} \alias{tomsTools} \alias{tomsTools-package} \title{Describe the package. TEST.} \description{ Describe the package. TEST. }
126f08dbb78f728ad8185902f88cf72a2f3c45ee
81c0158c28d8bf0de94ef8676083dbbfbce06e73
/R/kaefa-package.r
0f668ad27ce73794d120c7fadc5ac2b4fbf3bf2b
[]
no_license
seonghobae/kaefa
3daf1c294292b30b2589ee0d23bfb5788f20a217
266b7cfbc3d117cd8e85095970b4184a1cb315be
refs/heads/master
2022-05-16T09:50:53.236346
2022-05-03T05:12:20
2022-05-03T05:12:20
102,938,712
3
0
null
2018-03-06T14:37:56
2017-09-09T08:18:23
R
UTF-8
R
false
false
6,509
r
kaefa-package.r
#' kaefa: kwangwoon automated exploratory factor analysis #' #' This library stands for improving research capability to identify #' unexplained factor structure with complexly cross-classified #' multilevel structured data in R environment #' in the automated exploratory factor analysis framework what imports #' \code{mirt::mirt}, \code{mirt::mixedmirt} and \code{mirt::mdirt} #' (Chalmers, 2012; Chalmers, 2015). #' #' In practice of applied psychological resarch, so much researcher ignoring #' the impact of the MMMM (Multiple Membership Multilevel Model) and MM #' in exploratory factor analysis from unfamiliar with statistical innovations #' who noted in Sharpe (2013) and Foster, Min, and Zickar (2017). #' #' Moreover, A lot of researcher do not know what is the improper solution #' in the exploratory factor analysis. That may lead wrong conclusion to #' research society, The kaefa will filter possible improper solutions during #' the automated exploratory factor analysis. #' Filtering the Heywood cased models and fail to pass the second-order test #' model will help this work. These model will not consider to model selection #' that they are possible improper solutions. #' #' The kaefa may inspect this issues from the MMMM or MM #' in statistical learning theory perspectives using model #' selection criteria like the DIC (Kang, 2008; Kang, Cohen, & Sung, 2009; #' Jiao, Kamata, Wang, & Jin, 2012; Jiao & Zhang, 2015) with maximising #' generalisability of the number of factor decisions in every calibration #' (Kang, 2008; Preacher, Zhang, Kim, & Mels, 2013). #' #' If researcher provide of demographical information in kaefa, #' kaefa will inspect the optimal number of factor and optimal IRT model, #' and possible error variances or latent differences from #' demographic information of respondents. #' #' During the calibration, kaefa consider the these item response models: #' Rasch, 2PL, 3PL, 3PLu, 4PL, ideal (for dichotomous) #' nominal, gpcm, graded, grsm, ggum, pcm, rsm, monopoly (for polytomous). #' #' Moreover, factor rotation will decide automatically using \emph{Zh} for #' minimizing potential outage of the item as actual criteria. #' As the default, "bifactorQ","geominQ", "geominT", "bentlerQ", "bentlerT", #' "oblimin", "oblimax", "simplimax", "tandemII", "tandemI", "entropy", #' and "quartimax" will try to inspect the optimal structure of actual criteria #' reflect to the conceptual criterion. It is make a way to increase interpretability #' of the exploratory factor analysis without the human intervention #' as objectivity and reproducibility what principles of the science. #' #' After the every \emph{n-th} calibration, kaefa do the item appropriateness test #' for check which item contribute to explain conceptual criterion with #' robustness of aberrant response using \emph{Zh, S-X2, PV-Q1}. If kaefa #' find out the improper item, kaefa will exclude the worst one automatically #' and recalibrating the models until all items are acceptable via statistcal #' criteria. #' #' This software can be pallelise to multiple computers via LAN #' even heterogeneous environment, so that applied researchers may expand #' their research capability more easy with kaefa #' even data has too complicated structure to calibrate in single machine. #' #' This project started in 2013, and restructured in 2017. #' Hope to help exploring human behavioural mechanisms in complex contexts. #' #' @name kaefa #' @title kwangwoon automated exploratory factor analysis. #' @author Seongho Bae \email{seongho@kw.ac.kr} #' @references #' Chalmers, R., P. (2012). mirt: A Multidimensional Item Response Theory #' Package for the R Environment. \emph{Journal of Statistical Software, 48}(6), 1-29. #' \doi{10.18637/jss.v048.i06} #' @references #' Chalmers, R. P. (2015). Extended Mixed-Effects Item Response Models #' with the MH-RM algorithm. \emph{Journal of Educational Measurement, 52}(2), 200–222. #' \doi{10.1111/jedm.12072} #' @references #' Foster, G. C., Min, H., & Zickar, M. J. (2017). Review of Item Response Theory #' Practices in Organizational Research. #' \emph{Organizational Research Methods, 20}(3), 465–486. #' \doi{10.1177/1094428116689708} #' @references #' Jennrich, R. I., & Bentler, P. M. (2011). Exploratory Bi-Factor Analysis. #' \emph{Psychometrika, 76}(4), 537–549. #' \doi{10.1007/s11336-011-9218-4} #' @references #' Jiao, H., Kamata, A., Wang, S., & Jin, Y. (2012). A Multilevel Testlet Model #' for Dual Local Dependence. \emph{Journal of Educational Measurement, 49}(1), 82-100. #' \doi{10.1111/j.1745-3984.2011.00161.x} #' @references #' Jiao, H., & Zhang, Y. (2015). Polytomous multilevel testlet models for testlet-based #' assessments with complex sampling designs. #' \emph{British Journal of Mathematical and Statistical Psychology, 68}(1), 65–83. #' \doi{10.1111/bmsp.12035} #' @references #' Kang, T. (2008). Application of Statistical Model Selection Methods to Assessing #' Test Dimensionality. \emph{Journal of Educational Evaluation, 21}(4), 153–175. #' Retrieved from \url{http://scholar.dkyobobook.co.kr/searchDetail.laf?barcode=4010022701731} #' @references #' Kang, T., Cohen, A. S., & Sung, H.-J. (2009). Model Selection Indices for #' Polytomous Items. \emph{Applied Psychological Measurement, 33}(7), 499–518. #' \doi{10.1007/s00330-011-2364-3} #' @references #' Mansolf, M., & Reise, S. P. (2016). Exploratory Bifactor Analysis: #' The Schmid-Leiman Orthogonalization and Jennrich-Bentler Analytic Rotations. #' \emph{Multivariate Behavioral Research, 51}(5), 698–717. #' \doi{10.1080/00273171.2016.1215898} #' @references #' Preacher, K. J., Zhang, G., Kim, C., & Mels, G. (2013). Choosing the optimal #' number of factors in exploratory factor analysis: A model selection perspective. #' \emph{Multivariate Behavioral Research, 48}(1), 28–56. #' \doi{10.1080/00273171.2012.710386} #' @references #' Reise, S. P., & Waller, N. G. (2009). Item Response Theory and Clinical Measurement. #' \emph{Annual Review of Clinical Psychology, 5}(1), 27–48. #' \doi{10.1146/annurev.clinpsy.032408.153553} #' @references #' Reise, S. P. (2012). The Rediscovery of Bifactor Measurement Models. #' \emph{Multivariate Behavioral Research, 47}(5), 667–696. #' \doi{10.1080/00273171.2012.715555} #' @references #' Sharpe, D. (2013). Why the resistance to statistical innovations? #' Bridging the communication gap. \emph{Psychological Methods, 18}(4), 572–582. #' \doi{10.1037/a0034177} #' @docType package NULL
258fe5a22f3819f6a6102cc23481a0adc84a2197
def7897686c993371f1848f0ba8c079be8d8b8bf
/evaluation.R
1440a3802ba291bea497ff3628596205ece54a81
[]
no_license
kcf-jackson/ACEMS_2016_Advanced_Sampling
1fe54883c8a7bc0eb8dc59e598870e31cb6b5cf5
497b2ceb28e65852093e84cbab74198facca3d9d
refs/heads/master
2021-01-12T14:43:38.556758
2016-10-27T08:04:34
2016-10-27T08:04:34
72,070,871
0
0
null
null
null
null
UTF-8
R
false
false
1,397
r
evaluation.R
# evaluate_train_nn <- function(train_data, oracle) { # oracle$FUN(train_data)$net.result %>% `>=`(0.5) %>% as.numeric() # } # evaluate_test_nn <- function(test_data, oracle) { # map( # seq_along(test_data), # ~oracle(test_data[[.x]])$net.result %>% `>=`(0.5) %>% as.numeric() # ) # } # evaluate_test <- function(test_data, oracle) { map(seq_along(test_data), ~evaluate_df_by_row(test_data[[.x]], oracle)) } evaluate_df_by_row <- function(df0, oracle) { map_dbl(1:nrow(df0), ~( df0[.x, ] %>% oracle$FUN() )) } evaluate_train <- evaluate_df_by_row # print_result_summary <- function(oracle_1, my_fun_1, test_data_1) { # test_perf <- map2_dbl( # evaluate_test(test_data_1, oracle_1), # evaluate_test(test_data_1, my_fun_1), # ~sum(.x == .y) # ) # # cat("Oracle\n") # cat("z: \n") # print(oracle_1$z) # cat("threshold:", oracle_1$threshold, "\n\n") # # cat("My function\n") # cat("z: \n") # print(my_fun_1$z) # cat("threshold:", my_fun_1$threshold, "\n\n") # # cat("Differences\n") # cat("z:", sum(xor(oracle_1$z, my_fun_1$z)), "\n") # cat("threshold:", abs(oracle_1$threshold - my_fun_1$threshold), "\n") # cat("test data:", min(test_perf), "\n") # # return(data.frame( # z = sum(xor(oracle_1$z, my_fun_1$z)), # threshold = abs(oracle_1$threshold - my_fun_1$threshold), # test_perf = min(test_perf) # )) # }
c32da64300fe303867793befcb2c672d14ae10db
77c937453ccca0a048a1bc1a0f80240698543aa0
/pkg/man/dist_data_cdf-methods.Rd
20335c85daa1b73847ccef4bb4615b4ee04fc1f6
[]
no_license
way2joy/poweRlaw
17b3e8657cea144811a90fde02e1a4549c08a639
5f65a4408b6fe77fb8d828bd5c0fc6639d1bb107
refs/heads/master
2021-01-18T07:37:34.434193
2014-07-28T12:08:25
2014-07-28T12:08:25
null
0
0
null
null
null
null
UTF-8
R
false
false
1,383
rd
dist_data_cdf-methods.Rd
% Generated by roxygen2 (4.0.1): do not edit by hand \docType{methods} \name{dist_data_cdf} \alias{dist_data_cdf} \alias{dist_data_cdf,ctn_distribution-method} \alias{dist_data_cdf,discrete_distribution-method} \title{The data cumulative distribution function} \usage{ dist_data_cdf(m, lower_tail = TRUE, all_values = FALSE) \S4method{dist_data_cdf}{discrete_distribution}(m, lower_tail = TRUE, all_values = FALSE) \S4method{dist_data_cdf}{ctn_distribution}(m, lower_tail = TRUE) } \arguments{ \item{m}{a reference class distribution object.} \item{lower_tail}{logical; if \code{TRUE} (default), probabilities are \eqn{P[X \le x]}, otherwise, \eqn{P[X > x]}.} \item{all_values}{logical, if \code{FALSE} (default), evaluate at the data values. If \code{TRUE}, then the cdf is evaluated at points xmin, xmin+1, ..., xmax.} } \description{ This is generic function for distribution objects. This function calculates the data cdf. } \note{ This method does *not* alter the internal state of the distribubtion objects. } \examples{ ########################################## #Load data and create distribution object# ########################################## data(moby_sample) m = displ$new(moby_sample) m$setXmin(7);m$setPars(2) ########################################## # The data cdf # ########################################## dist_data_cdf(m) }
cb645236bf678b93e67a078c6780aca832a12d15
8e98acb706449542a9e4e40038da103f8c2704b6
/elicitation/experimental/thrombo-stopping.R
38a21506ac342e8feecdafa2251820e42b826827
[]
no_license
tommite/pubs-code
f4e21dcafd999f8d7b995cefdffb3786c49b247e
b2b33e97adbef68787122519384000c55f956811
refs/heads/master
2016-09-05T09:01:44.793555
2014-05-09T12:08:03
2014-05-09T12:08:03
5,935,181
1
0
null
null
null
null
UTF-8
R
false
false
6,611
r
thrombo-stopping.R
set.seed(1911) source('code.R') source('problem.R') source('ratio-problem.R') cuts1 <- dget('cuts1') #cuts2 <- dget('cuts2') #cuts3 <- dget('cuts3') ra <- function(w) { smaa.ra(smaa.ranks(smaa.values(meas=meas, pref=w))) } entropy <- function(w) { smaa.entropy.choice(ra=ra(w)) } cu <- function(h, h.min) { (h - h.min) / h } stopping.calc <- function(cut) { wn <- if (plane.side(rat.pt, cut$point, cut$normal)) { cut$w1 } else { cut$w2 } hn <- entropy(wn) i.min <- which.min(apply(wn, 1, entropy)) i.max <- which.max(apply(wn, 1, entropy)) list(h=hn, ra=ra(wn), w.min=wn[i.min,], h.min=entropy(wn[i.min,]), w.max=wn[i.max,], h.max=entropy(wn[i.max,])) } w0 <- simplex.sample(n=3, N=1E4)$samples h0 <- entropy(w0) h0.min <- min(apply(w0, 1, entropy)) cu(h0, h0.min) stopping1 <- lapply(cuts1, stopping.calc) #stopping3 <- lapply(cuts3, stopping.calc) source('simplex.heat.R') max.entropy <- 1 data <- simplex.calc.raster(entropy, 0.01) criteria <- c("p", "d", "b") plot.raster.polytope(data$data[,,1]/max.entropy, data$xrng, data$yrng, criteria=criteria, bounds=0.15) polytope.verts <- function(cuts) { constr <- mergeConstraints(lapply(cuts, function(cut) { plane.constraint(cut$point, cut$normal, plane.side(rat.pt, cut$point, cut$normal)) })) transform <- simplex.createTransform(3) constr <- simplex.createConstraints(transform, constr) verts <- findVertices(constr, TRUE) centr <- apply(verts, 2, mean) ord <- order(apply(verts, 1, function(x) { atan2(x[1]-centr[1],x[2]-centr[2]) })) verts[ord,] } verts <- polytope.verts(cuts1)[,1:2] polygon(verts) w.point <- function(w) { (simplex.createTransform(3, inverse=TRUE) %*% c(w, 1))[1:2] } ### START PLOTTING pdf() lapply(1:10, function(i) { plot.raster.polytope(pmin(data$data[,,1]/max.entropy*2, 1), data$xrng, data$yrng, criteria=criteria, bounds=0.15, main=paste("After Q", i)) polygon(polytope.verts(cuts1[1:i])) points(t(w.point(rat.pt)), pch='*') points(t(w.point(stopping1[[i]]$w.max)), pch='o') points(t(w.point(stopping1[[i]]$w.min)), pch='x') }) ra.est <- sapply(stopping1, function(s) { s$ra[2,1] }) ra.min <- sapply(stopping1, function(s) { ra(s$w.max)[2,1] }) ra.max <- sapply(stopping1, function(s) { ra(s$w.min)[2,1] }) plot(ra.est, ylim=c(0,1), type='l', lty=1, xlab="question", ylab="RAI(Enox, 1)") lines(ra.min, lty=2) lines(ra.max, lty=2) abline(h=ra(rat.pt)[2,1], lty=3) plot(sapply(stopping1, function(s) { s$h }), ylim=c(0,1), type='l', xlab="question", ylab="entropy") lines(sapply(stopping1, function(s) { s$h.min }), lty=2) lines(sapply(stopping1, function(s) { s$h.max }), lty=2) abline(h=entropy(rat.pt), lty=3) plot(sapply(stopping1, function(s) { cu(s$h, s$h.min) }), ylim=c(0,1), xlab="question", ylab="uncertainty coefficient") dev.off() ### END PLOTTING ### What's wrong with question entropy?? h1 <- sapply(cuts1, function(cut) { entropy(cut$w1) }) h2 <- sapply(cuts1, function(cut) { entropy(cut$w2) }) p <- sapply(cuts1, function(cut) { cut$share / 100 }) qh <- p*h1 + (1-p)*h2 qh - sapply(cuts1, function(cut) { cut$h }) bla <- sapply(cuts1, function(cut) { cut$entropies[which.min(cut$entropies[,'h']),] }) h1 - bla['h1',] ### What would be the value of asking one of the "good" questions? evaluate.cut.w <- function(constr, cut, w) { w1 <- harSample(mergeConstraints(constr, plane.constraint(cut$point, cut$normal, TRUE)), nrW) w2 <- harSample(mergeConstraints(constr, plane.constraint(cut$point, cut$normal, FALSE)), nrW) h1 <- entropy(w1) h2 <- entropy(w2) p <- sum(partition.points(w, cut$point, cut$normal))/nrow(w) qh <- p*h1 + (1-p)*h2 c(qh=qh, h1=h1, h2=h2, p=p) } evaluate.cut <- function(constr, cut) { w <- harSample(constr, nrW) evaluate.cut.w(constr, cut, w) } ## skip question 9? constr <- mergeConstraints(lapply(cuts1[1:8], function(cut) { plane.constraint(cut$point, cut$normal, plane.side(rat.pt, cut$point, cut$normal)) })) hyp9 <- evaluate.cut(constr, cuts1[[10]]) hyp9['qh'] < qh[9] # TRUE ## question 7 directly after 3? constr <- mergeConstraints(lapply(cuts1[1:3], function(cut) { plane.constraint(cut$point, cut$normal, plane.side(rat.pt, cut$point, cut$normal)) })) hyp4 <- evaluate.cut(constr, cuts1[[7]]) hyp4['qh'] < qh[4] # TRUE ## question 7 directly after 2? constr <- mergeConstraints(lapply(cuts1[1:2], function(cut) { plane.constraint(cut$point, cut$normal, plane.side(rat.pt, cut$point, cut$normal)) })) hyp3 <- evaluate.cut(constr, cuts1[[7]]) hyp3['qh'] < qh[3] # FALSE ## question 2 immediately? hyp1 <- evaluate.cut(NULL, cuts1[[2]]) hyp1['qh'] < qh[1] # FALSE cu(c(h0, sapply(stopping1, function(s) { s$h }))[1:10], qh) cu(c(h0, sapply(stopping1, function(s) { s$h }))[1:10], pmin(h1,h2)) ## experiment: better hyperplane sampling? source('hyperplane-sample.R') sample.planes.test <- function(constr, N) { state <- har.init(mergeConstraints(simplexConstraints(3), constr)) state.to.cut <- function(s) { list( point = as.vector(state$transform %*% s$point), normal = as.vector(state$basis$basis %*% s$normal) ) } lapply( hyperplane.sample(state$constr, N, homogeneous=TRUE), state.to.cut) } sample.planes.old <- function(constr, N) { W <- harSample(constr, N) sample.planes.unrestricted()(W) } # evaluate resulting cuts constr <- mergeConstraints(lapply(cuts1[1:3], function(cut) { plane.constraint(cut$point, cut$normal, plane.side(rat.pt, cut$point, cut$normal)) })) plot.planes <- function(constr, planes) { plot.raster.polytope(pmin(data$data[,,1]/max.entropy*2, 1), data$xrng, data$yrng, criteria=criteria, bounds=0.15) polygon(polytope.verts(cuts1[1:3])) lapply(planes, lines.cut) } testRuns <- function(constr, nrRuns, nrW, nrPlanes, planesFn) { lapply(1:nrRuns, function(i) { w <- harSample(constr, nrW) planes <- planesFn(constr, nrPlanes) eval <- sapply(planes, function(plane) { evaluate.cut.w(constr, plane, w) }) list(planes=planes, entropy=eval) }) } eval.old <- testRuns(constr, 20, 1E4, 1E4, sample.planes.old) win.old <- sapply(eval.old, function(e) { which.min(e$entropy['qh',]) }) eval.new <- testRuns(constr, 20, 1E4, 1E4, sample.planes.test) win.new <- sapply(eval.new, function(e) { which.min(e$entropy['qh',]) }) plane.old <- mapply(function(e, i) { e$planes[[i]] }, eval.old, win.old, SIMPLIFY=FALSE) plane.new <- mapply(function(e, i) { e$planes[[i]] }, eval.new, win.new, SIMPLIFY=FALSE) entr.old <- mapply(function(e, i) { e$entropy[,i] }, eval.old, win.old) entr.new <- mapply(function(e, i) { e$entropy[,i] }, eval.new, win.new)
98a4e3286e552d886dee1a59174fc6f32aa6827d
06b6a2c2008c7f5e8400f8eb402d490ebb4bfd54
/man/isCountsOrZeros.Rd
24da44139055e9bba35e7a588884f456d3d34e0f
[ "MIT" ]
permissive
BMEngineeR/midasHLA
55265be7baae2259c976bb5ea7f112737c0b7d1a
9ce02c8192852c16a296f63ecbd3e4791e5dbd83
refs/heads/master
2023-03-05T15:59:52.362313
2021-02-17T00:53:19
2021-02-17T00:53:19
null
0
0
null
null
null
null
UTF-8
R
false
true
590
rd
isCountsOrZeros.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/asserts.R \name{isCountsOrZeros} \alias{isCountsOrZeros} \title{Check if vector contains only counts or zeros} \usage{ isCountsOrZeros(x, na.rm = TRUE) } \arguments{ \item{x}{Numeric vector or object that can be \code{unlist} to numeric vector.} \item{na.rm}{Logical indicating if \code{NA} values should be accepted.} } \value{ Logical indicating if provided vector contains only positive integers or zeros. } \description{ \code{isCountsOrZeros} checks if vector contains only positive integers or zeros. }
accbc0034ab20234750e3c7af05e4d6751a6c4d0
72186ca45fef2d8ffe88dcd9ab44265c293cb4c4
/Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022/MakeEMLChemistry.R
dcee82eeb9475f124a91c27b7ff3a2276d7b0478
[]
no_license
CareyLabVT/Reservoirs
a4b3d025ade448cb54dd7a7c1d91fea5ff0368b6
2b6d62376d24e9e24d1841b83ebead8a21d57aa0
refs/heads/master
2023-08-17T10:28:24.450403
2023-08-10T18:23:14
2023-08-10T18:23:14
91,721,780
2
8
null
2023-09-11T16:08:55
2017-05-18T17:43:27
HTML
UTF-8
R
false
false
17,739
r
MakeEMLChemistry.R
##MakeEMLChemistry ##Author: Mary Lofton ##Modified by Whitney Woelmer ##Slight modification by Jacob Wynne ##29Mar2023 - 2022 nutrient aggregation #NOTE - 11 samples need to be rerun with 2023 samples - will need to average/add these data when we publish 2022 field season samples (HLW) #F100 5Jul22 0.1m NO3, F50 2May22 1.6m DOC, F50 23May22 5m SRP, B50 21Mar23 0.1, 6, and 9m NO3, B50 11Oct22 7m SRP, B50 19Sep22 6m SRP #C50 30Jun22 21m SRP, C50 19Aug22 20m NH4, C50 17Nov22 21m NO3 #good site for step-by-step instructions #https://ediorg.github.io/EMLassemblyline/articles/overview.html #and links therein #append this year's chemistry to last year's published data library(tidyverse) library(viridis) library(plotly) old <- read.csv("./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2021/chemistry_2013_2021.csv") new <- read.csv("./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022/2022_chemistry_collation_final_nocommas.csv") new <- new %>% select(-X) #change column names to match new format old <- old %>% rename(Flag_TP_ugL = Flag_TP, Flag_TN_ugL = Flag_TN, Flag_SRP_ugL = Flag_SRP, Flag_NO3NO2_ugL = Flag_NO3NO2, Flag_NH4_ugL = Flag_NH4, Flag_DC_mgL = Flag_DC, Flag_DIC_mgL = Flag_DIC, Flag_DOC_mgL = Flag_DOC, Flag_DN_mgL = Flag_DN) #also drop ISCO samples bc being published in separate data product old <- old[old$Site!=100.1,] #add 8 flag for all DIC and DOC values run with NPOC old$Flag_DN_mgL[old$Flag_DOC_mgL==8] <- 8 #manual manipulation - NA for 2 2014 SRP values and associated 5 demonic intrusion flag old$SRP_ugL[as.Date(old$DateTime)=="2014-04-30" & old$Reservoir=="BVR" & old$Depth_m==0.1] <- NA old$Flag_SRP_ugL[as.Date(old$DateTime)=="2014-04-30" & old$Reservoir=="BVR" & old$Depth_m==0.1] <- 5 old$SRP_ugL[as.Date(old$DateTime)=="2014-06-04" & old$Reservoir=="BVR" & old$Depth_m==0.1] <- NA old$Flag_SRP_ugL[as.Date(old$DateTime)=="2014-06-04" & old$Reservoir=="BVR" & old$Depth_m==0.1] <- 5 #and suspect sample flag (9) for 2017 TP sample old$Flag_TP_ugL[as.Date(old$DateTime)=="2017-07-20" & old$Reservoir=="BVR" & old$Depth_m==0.1 & old$TP_ugL==247.0 ] <- 9 old$Flag_TN_ugL[as.Date(old$DateTime)=="2017-07-20" & old$Reservoir=="BVR" & old$Depth_m==0.1 & old$TN_ugL==3680 ] <- 9 #get cols in same order new <- new[,colnames(old)] #manually remove 11 samples from 2022 data pub to be published at a later date after reruns new$NO3NO2_ugL[new$Reservoir=="FCR" & as.Date(new$DateTime)=="2022-07-05" & new$Depth_m==0.1 & new$Site==100] <- NA new$DOC_mgL[new$Reservoir=="FCR" & as.Date(new$DateTime)=="2022-05-02" & new$Depth_m==1.6 & new$Site==50] <- NA new$SRP_ugL[new$Reservoir=="FCR" & as.Date(new$DateTime)=="2022-05-23" & new$Depth_m==5 & new$Site==50] <- NA new$NO3NO2_ugL[new$Reservoir=="BVR" & as.Date(new$DateTime)=="2023-03-21" & new$Depth_m==0.1 & new$Site==50] <- NA new$NO3NO2_ugL[new$Reservoir=="BVR" & as.Date(new$DateTime)=="2023-03-21" & new$Depth_m==6 & new$Site==50] <- NA new$NO3NO2_ugL[new$Reservoir=="BVR" & as.Date(new$DateTime)=="2023-03-21" & new$Depth_m==9 & new$Site==50] <- NA new$SRP_ugL[new$Reservoir=="BVR" & as.Date(new$DateTime)=="2022-10-11" & new$Depth_m==7 & new$Site==50] <- NA new$SRP_ugL[new$Reservoir=="BVR" & as.Date(new$DateTime)=="2022-09-19" & new$Depth_m==6 & new$Site==50] <- NA new$SRP_ugL[new$Reservoir=="CCR" & as.Date(new$DateTime)=="2022-06-30" & new$Depth_m==21 & new$Site==50] <- NA new$NH4_ugL[new$Reservoir=="CCR" & as.Date(new$DateTime)=="2022-08-19" & new$Depth_m==20 & new$Site==50] <- NA new$NO3NO2_ugL[new$Reservoir=="CCR" & as.Date(new$DateTime)=="2022-11-17" & new$Depth_m==21 & new$Site==50] <- NA #merge old and new dfs chem <- rbind(old, new) #replace NA flags with 0 chem$Flag_DateTime[is.na(chem$Flag_DateTime)] <- 0 chem$Flag_TN_ugL[is.na(chem$Flag_TN_ugL)] <- 0 chem$Flag_TP_ugL[is.na(chem$Flag_TP_ugL)] <- 0 chem$Flag_NH4_ugL[is.na(chem$Flag_NH4_ugL)] <- 0 chem$Flag_NO3NO2_ugL[is.na(chem$Flag_NO3NO2_ugL)] <- 0 chem$Flag_SRP_ugL[is.na(chem$Flag_SRP_ugL)] <- 0 chem$Flag_DOC_mgL[is.na(chem$Flag_DOC_mgL)] <- 0 chem$Flag_DIC_mgL[is.na(chem$Flag_DIC_mgL)] <- 0 chem$Flag_DC_mgL[is.na(chem$Flag_DC_mgL)] <- 0 chem$Flag_DN_mgL[is.na(chem$Flag_DN_mgL)] <- 0 #change B1 to B40 chem$Site[chem$Site==1 & chem$Reservoir=="BVR"] <- 40 #add a 1 flag for all NA samples chem$Flag_TN_ugL[is.na(chem$TN_ugL)] <- 1 chem$Flag_TP_ugL[is.na(chem$TP_ugL)] <- 1 chem$Flag_NH4_ugL[is.na(chem$NH4_ugL)] <- 1 chem$Flag_NO3NO2_ugL[is.na(chem$NO3NO2_ugL)] <- 1 chem$Flag_SRP_ugL[is.na(chem$SRP_ugL)] <- 1 chem$Flag_DOC_mgL[is.na(chem$DOC_mgL)] <- 1 chem$Flag_DIC_mgL[is.na(chem$DIC_mgL)] <- 1 chem$Flag_DC_mgL[is.na(chem$DC_mgL)] <- 1 chem$Flag_DN_mgL[is.na(chem$DN_mgL)] <- 1 write.csv(chem, "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022/chemistry_2013_2022.csv",row.names = FALSE) #select columns for plotting raw_chem <- chem [,(names(chem) %in% c("Reservoir","Site","DateTime", "Depth_m","Rep","TP_ugL","TN_ugL","NH4_ugL","SRP_ugL","NO3NO2_ugL","DOC_mgL"))] #### Chemistry diagnostic plots #### chemistry_long <- raw_chem %>% gather(metric, value, TN_ugL:DOC_mgL) %>% mutate(month = strftime(DateTime, "%b")) %>% mutate(DateTime = as.Date(DateTime)) # FCR deep hole data time series plot ggplot(subset(chemistry_long, metric=="DOC_mgL" & Depth_m==0.1 & Reservoir=="FCR"), aes(x=DateTime, y=value )) + geom_point(cex=2) + theme_bw() #plots for each variable by reservoir fcrplots <- chemistry_long %>% filter(Reservoir == 'FCR') %>% #filter(Site == 50) %>% #filter(Depth_m %in% c(0.1, 1.6, 3.8, 5, 6.2, 8, 9)) %>% #If you want to just see the routine depths ggplot(aes(x = DateTime, y = value, color = as.factor(Depth_m)))+ geom_point()+ ggtitle("FCR chem")+ theme_bw()+ facet_wrap(~metric, scales = 'free_y') ggsave(file.path(getwd(),"./Data/DataNotYetUploadedToEDI/NutrientData/Figures/2022/FCR_allyears_andnutrients.jpg"), width=4, height=4) ggplotly(fcrplots) #interactive plot bvrplots <- chemistry_long %>% filter(Reservoir == 'BVR') %>% # filter(Site == 50) %>% ggplot(aes(x = DateTime, y = value, color = as.factor(Depth_m)))+ geom_point()+ ggtitle("BVR chem")+ theme_bw()+ facet_wrap(~metric, scales = 'free_y') ggplotly(bvrplots) ggsave(file.path(getwd(),"./Data/DataNotYetUploadedToEDI/NutrientData/Figures/2022/BVR_allyears_andnutrients.jpg"), width=4, height=4) ccrplots <- chemistry_long %>% filter(Reservoir == 'CCR') %>% # filter(Site == 50) %>% ggplot(aes(x = DateTime, y = value, color = as.factor(Depth_m)))+ geom_point()+ ggtitle("CCR chem")+ theme_bw()+ facet_wrap(~metric, scales = 'free_y') ccrplots ggsave(file.path(getwd(),"./Data/DataNotYetUploadedToEDI/NutrientData/Figures/2022/CCR_allyears_andnutrients.jpg"), width=4, height=4) # (install and) Load EMLassemblyline ##### # install.packages('devtools') #devtools::install_github("EDIorg/EMLassemblyline") #note that EMLassemblyline has an absurd number of dependencies and you #may exceed your API rate limit; if this happens, you will have to wait an #hour and try again or get a personal authentification token (?? I think) #for github which allows you to submit more than 60 API requests in an hour library(EMLassemblyline) #Step 1: Create a directory for your dataset #in this case, our directory is Reservoirs/Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2018 #Step 2: Move your dataset to the directory #Step 3: Identify an intellectual rights license #ours is CCBY #Step 4: Identify the types of data in your dataset #right now the only supported option is "table"; happily, this is what #we have! #Step 5: Import the core metadata templates #for our application, we will need to generate all types of metadata #files except for taxonomic coverage, as we have both continuous and #categorical variables and want to report our geographic location # View documentation for these functions ?template_core_metadata ?template_table_attributes ?template_categorical_variables #don't run this till later ?template_geographic_coverage # Import templates for our dataset licensed under CCBY, with 1 table. template_core_metadata(path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", license = "CCBY", file.type = ".txt", write.file = TRUE) template_table_attributes(path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.table = c("chemistry_2013_2022.csv", "reservoir_site_descriptions.csv"), write.file = TRUE) #we want empty to be true for this because we don't include lat/long #as columns within our dataset but would like to provide them template_geographic_coverage(path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.table = c("chemistry_2013_2022.csv","reservoir_site_descriptions.csv"), empty = TRUE, write.file = TRUE) #Step 6: Script your workflow #that's what this is, silly! #Step 7: Abstract #copy-paste the abstract from your Microsoft Word document into abstract.txt #if you want to check your abstract for non-allowed characters, go to: #https://pteo.paranoiaworks.mobi/diacriticsremover/ #paste text and click remove diacritics # updated for 2019 to include info on RC sites #Step 8: Methods #copy-paste the methods from your Microsoft Word document into abstract.txt #if you want to check your abstract for non-allowed characters, go to: #https://pteo.paranoiaworks.mobi/diacriticsremover/ #paste text and click remove diacritics #Step 9: Additional information #I put the notes about FCR manipulations and pubs documenting it in this file #Step 10: Keywords #DO NOT EDIT KEYWORDS FILE USING A TEXT EDITOR!! USE EXCEL!! #not sure if this is still true...let's find out! :-) #see the LabKeywords.txt file for keywords that are mandatory for all Carey Lab data products #Step 11: Personnel #copy-paste this information in from your metadata document #Cayelan needs to be listed several times; she has to be listed separately for her roles as #PI, creator, and contact, and also separately for each separate funding source (!!) # Updated this for 2019 to include HLW and WMW #Step 12: Attributes #grab attribute names and definitions from your metadata word document #for units.... # View and search the standard units dictionary #view_unit_dictionary() #put flag codes and site codes in the definitions cell #force reservoir to categorical #Step 13: Close files #if all your files aren't closed, sometimes functions don't work #Step 14: Categorical variables # Run this function for your dataset #THIS WILL ONLY WORK once you have filled out the attributes_chemistry.txt and #identified which variables are categorical template_categorical_variables(path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", write.file = TRUE) #open the created value IN A SPREADSHEET EDITOR and add a definition for each category #Step 15: Geographic coverage #copy-paste the bounding_boxes.txt file (or geographic_coverage.txt file) that is Carey Lab specific into your working directory ## Step 16: Obtain a package.id. #### # Go to the EDI staging environment (https://portal-s.edirepository.org/nis/home.jsp), # then login using one of the Carey Lab usernames and passwords. # Select Tools --> Data Package Identifier Reservations and click # "Reserve Next Available Identifier" # A new value will appear in the "Current data package identifier reservations" # table (e.g., edi.123) # Make note of this value, as it will be your package.id below #Step 17: Make EML # View documentation for this function ?make_eml # Run this function make_eml( path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", eml.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", dataset.title = "Water chemistry time series for Beaverdam Reservoir, Carvins Cove Reservoir, Falling Creek Reservoir, Gatewood Reservoir, and Spring Hollow Reservoir in southwestern Virginia, USA 2013-2022", temporal.coverage = c("2013-04-04", "2023-03-21"), maintenance.description = 'ongoing', data.table = c("chemistry_2013_2022.csv", "reservoir_site_descriptions.csv"), data.table.description = c("Reservoir water chemistry dataset", "Description, latitude, and longitude of reservoir sampling sites"), other.entity = "QAQC_chemistry_2015_2022.R", other.entity.description = "Nutrient QAQC script", user.id = 'ccarey', user.domain = 'EDI', package.id = 'edi.1025.6') #reserve new staging environment package id each year ## Step 8: Check your data product! #### # Return to the EDI staging environment (https://portal-s.edirepository.org/nis/home.jsp), # then login using one of the Carey Lab usernames and passwords. # Select Tools --> Evaluate/Upload Data Packages, then under "EML Metadata File", # choose your metadata (.xml) file (e.g., edi.270.1.xml), check "I want to # manually upload the data by selecting files on my local system", then click Upload. # Now, Choose File for each file within the data package (e.g., each zip folder), # then click Upload. Files will upload and your EML metadata will be checked # for errors. If there are no errors, your data product is now published! # If there were errors, click the link to see what they were, then fix errors # in the xml file. # Note that each revision results in the xml file increasing one value # (e.g., edi.270.1, edi.270.2, etc). Re-upload your fixed files to complete the # evaluation check again, until you receive a message with no errors. ## Step 9: PUBLISH YOUR DATA! #### # #DO NOT REQUEST A NEW PACKAGE ID FOR UPDATING THE CHEMISTRY DATASET # SIMPLY INCREASE THE LAST DIGIT OF THE PREVIOUS PACKAGE ID BY 1 TO UPDATE THE CURRENT PUBLICATION # DIRECTIONS ON HOW TO GET A NEW ID ARE HERE, BUT DO NOT USE THEM FOR ALREADY PUBLISHED DATASETS BEING UPDATED (E.G. CHEMISTRY, CATWALK, CTD, ETC.) # NEVER ASSIGN this identifier to a staging environment package. # Go to the EDI Production environment (https://portal.edirepository.org/nis/home.jsp) # and login using the ccarey (permanent) credentials. # Select Tools --> Data Package Identifier Reservations and click "Reserve Next # Available Identifier". A new value will appear in the "Current data package # identifier reservations" table (e.g., edi.518) # This will be your PUBLISHED package.id # In the make_eml command below, change the package.id to match your # PUBLISHED package id. This id should end in .1 (e.g., edi.518.1) # ALL OTHER entries in the make_eml() command should match what you ran above, # in step 7 make_eml( path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", data.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", eml.path = "./Data/DataAlreadyUploadedToEDI/EDIProductionFiles/MakeEMLChemistry/2022", dataset.title = "Water chemistry time series for Beaverdam Reservoir, Carvins Cove Reservoir, Falling Creek Reservoir, Gatewood Reservoir, and Spring Hollow Reservoir in southwestern Virginia, USA 2013-2022", temporal.coverage = c("2013-04-04", "2023-03-21"), maintenance.description = 'ongoing', data.table = c("chemistry_2013_2022.csv", "reservoir_site_descriptions.csv"), data.table.description = c("Reservoir water chemistry dataset", "Description, latitude, and longitude of reservoir sampling sites"), other.entity = "QAQC_chemistry_2015_2022.R", other.entity.description = "Nutrient QAQC script", user.id = 'ccarey', user.domain = 'EDI', package.id = 'edi.199.11') #DO NOT REQUEST A NEW PACKAGE ID, SIMPLY INCREASE THE LAST DIGIT HERE BY 1 TO UPDATE THE CURRENT PUBLICATION # 2023 data pub = 199.10 # Once your xml file with your PUBLISHED package.id is Done, return to the # EDI Production environment (https://portal.edirepository.org/nis/home.jsp) # Select Tools --> Preview Your Metadata, then upload your metadata (.xml) file # associated with your PUBLISHED package.id. Look through the rendered # metadata one more time to check for mistakes (author order, bounding box, etc.) # Select Tools --> Evaluate/Upload Data Packages, then under "EML Metadata File", # choose your metadata (.xml) file associated with your PUBLISHED package.id # (e.g., edi.518.1.xml), check "I want to manually upload the data by selecting # files on my local system", then click Upload. # Now, Choose File for each file within the data package (e.g., each zip folder), # then click Upload. Files will upload and your EML metadata will be checked for # errors. Since you checked for and fixed errors in the staging environment, this # should run without errors, and your data product is now published! # Click the package.id hyperlink to view your final product! HOORAY!
798821c90f1c83edf8b3201090dc0068cc0ecd0d
9d903aaeb20640d77ed94b682c5e026b9ee0735a
/code/26_myeloid_tcell_intersect_DEG.R
13d4332ec41f489933c79be7db279e8b5c794b79
[]
no_license
Winnie09/GBM_t
c0a36a4140c47f8dfb124ca3c05620276d4effa7
c16f3df279e7b380871bbdbba3a525fba195fce3
refs/heads/master
2022-11-09T20:33:10.321563
2020-06-22T11:07:46
2020-06-22T11:07:46
274,114,440
0
0
null
null
null
null
UTF-8
R
false
false
1,534
r
26_myeloid_tcell_intersect_DEG.R
Mclu = list() Mclu[['EMDSC_MMDSC_PMNMDSC']] = c(1,3) Mclu[['EMDSC_MMDSC']] = c(1,2) Mclu[['EMDSC_MMDSC_MAC1']] = c(1,2) Mclu[['EMDSC_MAC1']] = c(4) source('/home-4/whou10@jhu.edu/scratch/Wenpin/trajectory_variability/function/01_function.R') for (path1 in names(Mclu)){ print(path1) for (path2 in c('dm_CD8EM_CD8EX', 'dm_CD8RM_CD8EX')){ print(path2) rdir1 <- paste0('/home-4/whou10@jhu.edu/scratch/Wenpin/GBM_myeloid/result/testtime/M_MDSC/', path1, '/') rdir2 = paste0('/home-4/whou10@jhu.edu/scratch/Wenpin/GBM_t/result/testtime/M_MDSC/', path2, '/') rdir = paste0('/home-4/whou10@jhu.edu/scratch/Wenpin/GBM_t/result/testtime/M_MDSC/', path1,'_and_', path2, '/') dir.create(rdir, recursive = T) res1 <- read.csv(paste0(rdir1, 'fdr_foldchange_cluster.csv'), row.names = 1, stringsAsFactors = F) res2 <- read.csv(paste0(rdir2, 'fdr_foldchange_cluster.csv'), row.names = 1, stringsAsFactors = F) for (i in Mclu[[path1]]){ df <- sapply(seq(1, max(res2[,3])), function(j){ g = intersect(rownames(res1[res1[,'Cluster']==i, ]), rownames(res2[res2[,'Cluster']==j, ])) }) mlen = max(sapply(df, length)) df <- sapply(seq(1, max(res2[,3])), function(j){ g = intersect(rownames(res1[res1[,'Cluster']==i, ]), rownames(res2[res2[,'Cluster']==j, ])) c(g, rep("", mlen-length(g))) }) colnames(df) <- paste0(path1, '_clu', i, '_and_', path2, '_clu', 1:ncol(df)) write.csv(df, paste0(rdir, 'intersect_DEG.csv')) } } }
2b12a83975b85bd28e67ced2f611a79c49ddb61a
8f222104a54c6831982c03f592da5905d481e2a7
/Reddit Data Analysis.R
a97d668a63c4f743a5fbaf214147d46a04dfb058
[]
no_license
sthobbs/Reddit-Analysis
df1c5c0b7e75eb9043ce049c0a277959728526c8
2d30f32341efcdd8c543b5361fa4af9a765256cf
refs/heads/master
2021-03-12T22:19:19.001142
2015-11-01T23:51:43
2015-11-01T23:51:43
42,701,494
0
0
null
null
null
null
UTF-8
R
false
false
15,269
r
Reddit Data Analysis.R
# Install and load packages install.packages("ggplot2") install.packages("RMySQL") install.packages("scales") install.packages("reshape2") library(ggplot2) library(RMySQL) library(scales) library("reshape2") # melt # Open connection to MySQL database con<-dbConnect(MySQL(),user="root",password="",db="db2",host="localhost") # Read in the database # lot is a list of data frames. Element i is post_ranki for the MySQL database lot<-list() for (i in 1:100){ suppressWarnings(lot[[i]]<-dbReadTable(con,paste0("post_rank",i))) } # Close connection dbDisconnect(con) # Create some data frames to work with post_rank1<-lot[[1]] # Top post data frame top5_post_rank<-post_rank1 # Top 5 posts data frame for (i in 2:5){ top5_post_rank<-rbind(top5_post_rank,lot[[i]]) } top10_post_rank<-top5_post_rank # Top 10 posts data frame for (i in 6:10){ top10_post_rank<-rbind(top10_post_rank,lot[[i]]) } p1_post_rank<-top10_post_rank # Top 25 posts data frame (front page/page 1) for (i in 11:25){ p1_post_rank<-rbind(p1_post_rank,lot[[i]]) } full_post_rank<-p1_post_rank # Top 100 posts data frame for (i in 26:100){ full_post_rank<-rbind(full_post_rank,lot[[i]]) } # The post url can be derived from the data as follows # go to https://www.reddit.com/r/subreddit/xxxxxx # where subreddit is the value in the 'subreddit' column # and xxxxxx is the last 6 digits of the value in the 'name' column # e.g. For the number 7 post, at time unit 6, go to paste0("https://www.reddit.com/r/",lot[[7]]$subreddit[6],"/",substring(lot[[7]]$name[6],4,9)) ##### Plots ##### ## Distribution of how long a post is on the front page (given that it reaches ## the front page) # We need to end the time window before any current front page posts reached # the front page so that the lower (left) tail is not inflated. It is still # possible that some of the posts that were included (which went off the # front page a while ago) will come back to the front page and bias the result. # However, this probably isn't the case, so the approximation is reasonable. # EDIT: I forgot to remove the initial post, changing code now. # Start collecting data ----- Start time ------------ end time ----- current time # in other words we look at all posts from start time to end time, then from # end time to current time we continue to track posts that were in the first # interval but we don't look at any new ones. We also posts that were in the # Top at the start of data collections. This elimiates almost all if not # all of the bias from our density estimate. # Picking the appropriate time window for data we should use current_posts<-NULL # 'names' of all post currently on the front page for (i in 1:25){ current_posts[i]<-lot[[i]]$name[nrow(lot[[1]])] } time_window_endpoint<-1 time_posts<-0 # Look forward from time 1 until I first encounter one of the current top posts while (!any(time_posts%in%current_posts)){ for (i in 1:25){ time_posts[i]<-lot[[i]]$name[time_window_endpoint] } time_window_endpoint=time_window_endpoint+1 } time_window_endpoint=time_window_endpoint-1 start_posts<-NULL # 'names' of all post currently on the front page for (i in 1:25){ start_posts[i]<-lot[[i]]$name[1] } time_window_startpoint<-nrow(lot[[1]]) time_posts<-0 # Look backwards until I first encounter one of the starting top posts while (!any(time_posts%in%start_posts)){ for (i in 1:25){ time_posts[i]<-lot[[i]]$name[time_window_startpoint] } time_window_startpoint=time_window_startpoint-1 } time_window_startpoint=time_window_startpoint+1 # Now we have a time window that ends right before the first appearence of the # current top posts. # Determine the unique names in the time window #and look at the frequencies p1_post_names_int<-NULL for (i in 1:25){ p1_post_names_int<-unique(c(p1_post_names_int,lot[[i]]$name[time_window_startpoint:time_window_endpoint])) } # Collect names from all time which are in the time interval p1_post_names_trunc<-NULL for (i in 1:25){ p1_post_names_trunc<-c(p1_post_names_trunc,lot[[i]]$name[lot[[i]]$name%in%p1_post_names_int]) } time_dist_df<-data.frame(hours=as.vector(sort(table(p1_post_names_trunc)))/6) # Plot density approximation ggplot(time_dist_df,aes(x=hours))+ geom_density(aes(fill="a"),size=2)+ geom_vline(xintercept=mean(time_dist_df$hours))+ ggtitle("Density Estimate of How Long a Post Lasts on the Front Page")+ theme(legend.position="none")+ annotate("text", label = "mean", x = mean(time_dist_df$hours)+0.83, y = 0.078, size = 6, colour = "black") # Mean time a front page post spends on the front page mean(time_dist_df$hours) ## Historical positions of the current top n posts n<-25 # Formatting the data post_tracking_df<-data.frame(time=(-nrow(lot[[1]])+1):0) cur_top_post_names<-NULL # Current top n post names for (i in 1:n){ cur_top_post_names[i]<-lot[[i]]$name[nrow(lot[[1]])] rank<-rep(100,nrow(lot[[1]])) # Vector of rank positions over time for (t in 1:nrow(lot[[1]])){ # Time int for (pos in 1:100){ # Post rank position if (cur_top_post_names[i]==lot[[pos]]$name[t]){ rank[t]<-pos break } } } post_tracking_df<-cbind(post_tracking_df,rank) } names(post_tracking_df)<-c("time",cur_top_post_names) post_tracking_df_long<-melt(post_tracking_df, id="time") # convert to long format # Plot (warnings are okay) ggplot(data=post_tracking_df_long,aes(x=time/6, y=value, colour=variable,alpha=0.8))+ geom_line()+ ylim(100,1)+ xlim((-sum(rowSums(post_tracking_df[,2:(n+1)]!=100)>0)-5)/6,0) + # x-axis limits calculated to be based how much info we have on these posts # + 5 extra time units ggtitle("Historical Positions of the Current Top 25 Posts")+ xlab("Time (hours)")+ ylab("Relative Position")+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) ## Historical Positions of the top n posts k hours ago n<-10 k<-15 # Use an increment of 1/6 # Formatting the data post_tracking_df<-data.frame(time=(-nrow(lot[[1]])+1):0) top_post_names<-NULL # Top n post at specific time names for (i in 1:n){ top_post_names[i]<-lot[[i]]$name[nrow(lot[[1]])-6*k] rank<-rep(100,nrow(lot[[1]])) # Vector of rank positions over time for (t in 1:nrow(lot[[1]])){ # Time int for (pos in 1:100){ # Post rank position if (top_post_names[i]==lot[[pos]]$name[t]){ rank[t]<-pos break } } } post_tracking_df<-cbind(post_tracking_df,rank) } names(post_tracking_df)<-c("time",top_post_names) post_tracking_df_long<-melt(post_tracking_df, id="time") # convert to long format # Plot (warnings are okay) ggplot(data=post_tracking_df_long,aes(x=time/6, y=value, colour=variable,alpha=0.8))+ geom_line()+ ylim(100,1)+ xlim((-sum(rowSums(post_tracking_df[,2:(n+1)]!=100)>0)-5)/6,0) + # x-axis limits calculated to be how much info we have on these posts # + 5 extra time units. doesn't work well for large k. ggtitle(paste("Historical Positions of Top", n, "Posts", k, "Hours Ago"))+ xlab("Time (hours)")+ ylab("Relative Position")+ geom_vline(xintercept=-k)+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) ## Bar plots of subreddit representation # I couldn't find any built in option to sort the bar plot in descending order # of frequency so I hacked this function together. # Creates a bar plot, in descending order, of a factor (or character) # variable var. Groups all frequencies less than x% into an "other" # bar on the right. # df is a data frame containing var # percent is TRUE <=> use %s rather than counts for y-axis sorted_bar_plot<-function(df,var,x=0,percent=TRUE){ dfa<-df # Defining duplicate data frame to alter # So I can use the variable name as an argument arguments <- as.list(match.call()) var = eval(arguments$var, dfa) dfa<-within(dfa,var<-as.character(var)) # If var is a factor variable, this makes it a character variable # Create a vector (sorted by frequencies) of all values with frequencies above the threshold levels<-names(sort(table(dfa$var)[table(dfa$var)>nrow(dfa)*x/100],decreasing=T)) # If any values are below the threshold, then add an "other" bar if (!all(table(dfa$var)>=nrow(dfa)*x/100)){ levels<-c(levels,"other") # Changing the values with frequencies below the threshold to "other" dfa$var[dfa$var%in%names(table(dfa$var)[table(dfa$var)<nrow(dfa)*x/100])]="other" } # Reordering levels based on frequencies, turning var into a factor (for the duplicate dataframe) dfa<-within(dfa,var<-factor(var,levels=levels)) # Plot if (percent==T){ p <- ggplot(dfa, aes(x = var)) + geom_bar(aes(y = (..count..)/sum(..count..),fill = ..count../sum(..count..)),col="black") scale_y_continuous(labels = percent_format()) } else{ p <- ggplot(dfa, aes(x = var)) + geom_bar(aes(y=..count..,fill=..count..),col="black") } return(p) } p<-sorted_bar_plot(post_rank1,subreddit,x=0) p + ggtitle("Subreddit Representation of Top Post") + xlab("Subreddit") + ylab("Representation")+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) p<-sorted_bar_plot(top5_post_rank,subreddit,x=0) p + ggtitle("Subreddit Representation of Top 5 Posts") + xlab("Subreddit") + ylab("Representation")+ theme(axis.text.x = element_text(angle=90, vjust=1))+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) p<-sorted_bar_plot(top10_post_rank,subreddit,x=0) p + ggtitle("Subreddit Representation of Top 10 Posts") + xlab("Subreddit") + ylab("Representation")+ theme(axis.text.x = element_text(angle=90, vjust=1))+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) p<-sorted_bar_plot(p1_post_rank,subreddit,x=0) p + ggtitle("Subreddit Representation of Top 25 Posts") + xlab("Subreddit") + ylab("Representation")+ theme(axis.text.x = element_text(angle=90, vjust=1))+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) p<-sorted_bar_plot(full_post_rank,subreddit,x=0) p + ggtitle("Subreddit Representation of Top 100 Posts") + xlab("Subreddit") + ylab("Representation")+ theme(axis.text.x = element_text(angle=90, vjust=1))+ theme(legend.position="none",text = element_text(size=16,vjust=1), axis.text.x = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain"), axis.text.y = element_text(colour="black",size=12,angle=0,hjust=1,vjust=0,face="plain"), axis.title.x = element_text(colour="black",size=12,angle=0,hjust=.5,vjust=0,face="plain"), axis.title.y = element_text(colour="black",size=12,angle=90,hjust=.5,vjust=.5,face="plain")) ## Historical Positions of the all posts in a specific subreddit sub<-"funny" # Formatting the data post_tracking_df<-data.frame(time=(-nrow(lot[[1]])+1):0) post_names<-NULL # All post names of posts in sub in the top 100 for (i in 1:100){ post_names<-unique(c(post_names,lot[[i]]$name[lot[[i]]$subreddit==sub])) } for (i in 1:length(post_names)){ rank<-rep(100,nrow(lot[[1]])) # Vector of rank positions over time for (t in 1:nrow(lot[[1]])){ # Time int for (pos in 1:100){ # Post rank position if (post_names[i]==lot[[pos]]$name[t]){ rank[t]<-pos break } } } post_tracking_df<-cbind(post_tracking_df,rank) } names(post_tracking_df)<-c("time",post_names) post_tracking_df_long<-melt(post_tracking_df, id="time") # Convert to long format # Plot ggplot(data=post_tracking_df_long,aes(x=time/6, y=value, colour=variable,alpha=0.8))+ geom_line()+ ylim(100,1)+ xlim((-sum(rowSums(post_tracking_df[,2:(n+1)]!=100)>0)-5)/6,0) + # x-axis limits calculated to be how much info we have on these posts # + 5 extra time units ggtitle(paste0("Historical Positions of all r/", sub, " Posts in the Top 100"))+ xlab("Time (hours)")+ ylab("Relative Position")+ theme(legend.position="none")#+ #geom_hline(yintercept=43) ## Prints the % of time that all posts came from unique subreddits for (k in 1:50){ count=0 for (i in 1:nrow(lot[[1]])){ fp_subs<-NULL for (j in 1:k){ fp_subs<-c(fp_subs,lot[[j]]$subreddit[i]) } if (length(unique(fp_subs))==k){ count=count+1 } } #if (count==nrow(lot[[1]])){ # print("at most one post from any subreddit on the front page at any time") print(paste0("the top ", k," posts were in unique subreddits ",100*count/nrow(lot[[1]]),"% of the time")) }
1b0354524db2e5c5bfdb7f797495cb4e85a9a4bc
820f53ee7d0f5b7038816bfbd13502b5bac81209
/google_maps.R
4b709bff5ce55b3e68c049fa3ae3290fb4169ed7
[]
no_license
uw-ischool-info-201a-2019-autumn/json-example
481688d5c1add7fbc6f5f117dfd4da5d59d275e0
63b632e1f307e556a21dbd74cf500057072d4574
refs/heads/master
2020-09-03T23:51:32.140808
2019-11-13T17:47:30
2019-11-13T17:47:30
219,607,901
0
0
null
null
null
null
UTF-8
R
false
false
57
r
google_maps.R
install.packages("ggmap") library(ggmap) qmap("seattle")
594357ac274c585d347215a8498b132fd97edc3b
fbea782e161a7173ef98e7fa34d90743d75743e1
/R_analytics/mtc/mtc.R
695526e59271b29ce63f629df54f155c5ab9b148
[]
no_license
edimaudo/R-projects
c3523a0bb551b0a945f12aa8d6c34107d7dd7ced
80af84e08fef61dfec4c87e7059f6dc50e24f868
refs/heads/master
2022-10-27T03:08:59.306013
2022-10-23T00:55:24
2022-10-23T00:55:24
94,769,351
2
0
null
null
null
null
UTF-8
R
false
false
5,466
r
mtc.R
#=================== ## Load Libraries #=================== rm(list = ls()) #clear environment # libraries packages <- c('ggplot2', 'corrplot','tidyverse',"caret","dummies","fastDummies" ,'FactoMineR','factoextra','readxl','scales','dplyr','mlbench','caTools', 'gridExtra','doParallel','readxl','grid','gridExtra') # load packages for (package in packages) { if (!require(package, character.only=T, quietly=T)) { install.packages(package) library(package, character.only=T) } } #=================== ## Load Data #=================== df <- read_excel("mtc.xlsx") #=================== # Data Overview #=================== # Summary summary(df) # Check for missing variables missing_data <- apply(df, 2, function(x) any(is.na(x))) print(missing_data) # Check for for imbalance table(df$label) # drop missing values df <- na.omit(df) #================= # Modeling #================= # Select columns df <- df %>% select(CANTIDAD,CANTIDAD_FISICA,CODIGO_CERTIFICADO,NOMBRE_PROVEEDOR,NOMBRE_EQUIPO, MODELO, PARTIDA_ARANCELARIA,MARCA_EQUIPO,FACTURA,UM_FISICA_ID,label) # Label Encoder labelEncoder <-function(x){ as.numeric(factor(x))-1 } # Normalize data normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x))) } df_other <- df %>% select(UM_FISICA_ID,label) df_cts <- df %>% select(CANTIDAD_FISICA) df_cat<- df %>% select(CODIGO_CERTIFICADO,NOMBRE_PROVEEDOR,NOMBRE_EQUIPO, MODELO, PARTIDA_ARANCELARIA,MARCA_EQUIPO,FACTURA) # Combine data df_cts <- as.data.frame(lapply(df_cts, normalize)) df_cat <- as.data.frame(lapply(df_cat, labelEncoder)) df_new <- cbind(df_cts,df_cat,df_other) df_new <- na.omit(df_new) df_new$label <- as.factor(df_new$label) # Create train and test data set.seed(2020) sample <- sample.split(df_new,SplitRatio = 0.75) train <- subset(df_new,sample ==TRUE) test <- subset(df_new, sample==FALSE) # Weights model_weights <- ifelse(train$label == 0, (1/table(train$label)[1]) * 0.5, (1/table(train$label)[2]) * 0.5) # Cross fold validation control <- trainControl(method="repeatedcv", number=10, repeats=5, classProbs = FALSE) # Models cl <- makePSOCKcluster(4) registerDoParallel(cl) # glm fit.glm <- train(label~., data=train, method="glm",family=binomial(), metric = "Accuracy", trControl = control, weights = model_weights) # random forest fit.rf <- train(as.factor(label)~., data=train, method="rf", metric = "Accuracy", trControl = control, weights = model_weights) # boosting algorithm - Stochastic Gradient Boosting fit.gbm <- train(as.factor(label)~., data=train, method="gbm", metric = "Accuracy", trControl = control, weights = model_weights) # svm fit.svm <- train(as.factor(label)~., data=train, method="svmRadial", metric = "Accuracy", trControl = control, weights = model_weights) # nnet fit.nnet <- train(as.factor(label)~., data=train, method="nnet", metric = "Accuracy", trControl = control, weights = model_weights) # naive fit.naive <- train(as.factor(label)~., data=train, method="naive_bayes", metric = "Accuracy", trControl = control, weights = model_weights) # extreme gradient boosting fit.xgb <- train(as.factor(label)~., data=train, method="xgbTree", metric = "Accuracy", trControl = control, weights = model_weights) # bagged cart fit.bg <- train(as.factor(label)~., data=train, method="treebag", metric = "Accuracy", trControl = control, weights = model_weights) # decision tree fit.dtree <- train(as.factor(label)~., data=train, method="C5.0", metric = "Accuracy", trControl = control, weights = model_weights) # knn fit.knn <- train(as.factor(label)~., data=train, method="kknn", metric = "Accuracy", trControl = control, weights = model_weights) stopCluster(cl) #------------------ #compare models #------------------ results <- resamples(list(randomforest = fit.rf, `gradient boost` = fit.gbm, `support vector machine` = fit.svm, baggedCart = fit.bg, neuralnetwork = fit.nnet, xgboost = fit.xgb, logisticregression = fit.glm, `decision tree` = fit.dtree, `naive bayes` = fit.naive, `knn` = fit.knn)) summary(results) # boxplot comparison bwplot(results) # Dot-plot comparison dotplot(results) # Model accuracy #mean(predicted.classes == test$label) # Test data accuracy # Make predictions predicted.classes <- fit.knn %>% predict(test) output <- confusionMatrix(data = predicted.classes, reference = test$label, mode = "everything") output # Variable Importance caret::varImp(fit.rf) #plot confusion matrix of selected option # plotting the matrix output2 <- as.data.frame(output$table) colnames(output2) <- c("Predicted",'Actual',"Freq") cm_d_p <- ggplot(data =output2, aes(x = Predicted , y = Actual, fill = Freq))+ geom_tile() + geom_text(aes(label = paste("",Freq)), color = 'white', size = 8) + theme_light() + guides(fill=FALSE) cm_d_p
6b85c559e1100a39f44237563e42caa704845727
144e1b215a8546d820f929055138b06eb67eda74
/stock_download.R
e52d00715effa1bcaa0a6e32112d5b1b67a92a34
[]
no_license
Mentalaborer/TradeNow
9acdb1bd5a9e0822fded0ec89aab9f80771845cb
7b82093f0324ab2a314216fa950f7a8e42c7a5e2
refs/heads/master
2020-11-26T01:04:15.277242
2020-07-05T20:52:12
2020-07-05T20:52:12
228,915,006
1
1
null
null
null
null
UTF-8
R
false
false
1,597
r
stock_download.R
# purpose - identify baskets of stocks want to analyze mary_jane <- c('FB', 'ARNA', 'IAN', 'CARA', 'GWPH', 'HEXO', 'OGI', 'TGOD', 'ACRG', 'WEED', 'ACB', 'CURA', 'KSHB', 'NWKRF', 'GTII', 'IIPR', 'HARV', 'CRON', 'TLRY', 'LABS', 'SMG', 'CRBP', 'CVSI', 'APHA', 'CWEB', 'VFF') restaurant <- c('EAT', 'DRI', 'DIN', 'MCD', 'QSR', 'SBUX', 'YUM', 'YUMC') real_estate <- c('KRG', 'OHI', 'SNH', 'STAG', 'VER') oil_gas <- c('EQM', 'BP', 'EP', # Energy Transfer LP (high yield) 'CVX', # chevron 'PTR', # petro china company limited (china's equivalent to chevon and exxon) 'CEQP',# Crestwood equity partners (high yield) 'OXY', # occidental petroleum 'BEP', # brookfield renewable 'PSXP', # 'EPD') tech <- c('FB', 'MSFT', 'GOOGL', 'BABA', 'IBM', 'AMZN', 'LOGI', 'WORK', 'TWTR', 'TCEHY') pharma <- c('NVAX', 'GILD', 'ABT', 'MRNA', 'RHHBY')
5c2eefc64d98273767ee3e706b02c091a93044ae
06aec25dadf0e5c54939fe87f845ee9007e144e0
/RStudioConf2018/examples/plumber/test.R
25fe3514b43d6ae1cb055cf6e2a620e331cb9ee3
[]
no_license
rundel/Presentations
67beac96f767669d1c5cded0f122df007c37da12
bce5c7ba02eff9159c5252068aafe936e5bfd0aa
refs/heads/master
2023-08-17T00:01:37.099095
2023-08-07T18:03:03
2023-08-07T18:03:03
4,659,430
20
5
null
null
null
null
UTF-8
R
false
false
456
r
test.R
library(httr) for(i in 1:10) { x = suppressWarnings( st_read("data/precincts.json", quiet = TRUE) %>% st_buffer(0.001 + (i-1)/1000) ) st_write(x,"data/precincts2.geojson", quiet=TRUE, delete_dsn=TRUE) file = base64enc::base64encode("data/precincts2.geojson") body = list( team="Team00", key="0000000000000000", file=file ) POST("http://127.0.0.1:7887/prediction", body=body, encode = "json") Sys.sleep(2) }
4dee79a4d23ad4dc47a3e2f0bde0406b712e7676
93d1fcc7758e5e99927be0529fb9d681db71e70c
/R/correct_d.R
b0a05d1270416196f7db59c543e755e16086eb7d
[]
no_license
psychmeta/psychmeta
ef4319169102b43fd87caacd9881014762939e33
b790fac3f2a4da43ee743d06de51b7005214e279
refs/heads/master
2023-08-17T20:42:48.778862
2023-08-14T01:22:19
2023-08-14T01:22:19
100,509,679
37
15
null
2023-08-14T01:06:53
2017-08-16T16:23:28
R
UTF-8
R
false
false
15,015
r
correct_d.R
#' Correct for small-sample bias in Cohen's \eqn{d} values #' #' Corrects a vector of Cohen's \eqn{d} values for small-sample bias, as Cohen's \eqn{d} #' has a slight positive bias. The bias-corrected \eqn{d} value is often called #' Hedges's \eqn{g}. #' #' The bias correction is: #' \deqn{g = d_{c} = d_{obs} \times J}{g = d_c = d * J} #' #' where #' \deqn{J = \frac{\Gamma(\frac{n - 2}{2})}{\sqrt{\frac{n - 2}{2}} \times \Gamma(\frac{n - 3}{2})}}{J = \Gamma((n - 2) / 2) / (sqrt(n - 2) * \Gamma((n - 2) / 2))} #' #' and \eqn{d_{obs}}{d} is the observed effect size, \eqn{g = d_{c}}{g = d_c} is the #' corrected (unbiased) estimate, \eqn{n} is the total sample size, and #' \eqn{\Gamma()}{\Gamma()} is the [gamma function][base::gamma()]. #' #' Historically, using the gamma function was computationally intensive, so an #' approximation for \eqn{J} was used (Borenstein et al., 2009): #' \deqn{J = 1 - 3 / (4 * (n - 2) - 1)}{J = 1 - 3 / (4 * (n - 2) - 1} #' #' This approximation is no longer necessary with modern computers. #' #' @param d Vector of Cohen's d values. #' @param n Vector of sample sizes. #' #' @return Vector of g values (d values corrected for small-sample bias). #' @export #' #' @references #' Hedges, L. V., & Olkin, I. (1985). #' *Statistical methods for meta-analysis*. #' Academic Press. p. 104 #' #' Borenstein, M., Hedges, L. V., Higgins, J. P. T., & Rothstein, H. R. (2009). #' *Introduction to meta-analysis*. #' Wiley. p. 27. #' #' @md #' #' @examples #' correct_d_bias(d = .3, n = 30) #' correct_d_bias(d = .3, n = 300) #' correct_d_bias(d = .3, n = 3000) correct_d_bias <- function(d, n){ df <- n J <- exp(lgamma(df/2) - log(sqrt(df/2)) - lgamma((df - 1)/2)) out <- d out[!is.na(n)] <- d[!is.na(n)] * J[!is.na(n)] out } #' Correct for small-sample bias in Glass' \eqn{\Delta} values #' #' Correct for small-sample bias in Glass' \eqn{\Delta} values. #' #' @param delta Vector of Glass' \eqn{\Delta} values. #' @param nc Vector of control-group sample sizes. #' @param ne Vector of experimental-group sample sizes. #' @param use_pooled_sd Logical vector determining whether the pooled standard deviation was used (`TRUE`) or not (`FALSE`; default). #' #' @return Vector of d values corrected for small-sample bias. #' @export #' #' @references #' Hedges, L. V. (1981). Distribution theory for Glass’s estimator of effect #' size and related estimators. *Journal of Educational Statistics, 6*(2), #' 107–128. \doi{10.2307/1164588} #' #' @details #' The bias correction is estimated as: #' #' \deqn{\Delta_{c}=\Delta_{obs}\frac{\Gamma\left(\frac{n_{control}-1}{2}\right)}{\Gamma\left(\frac{n_{control}-1}{2}\right)\Gamma\left(\frac{n_{control}-2}{2}\right)}}{delta_c = delta * gamma((nc - 1) / 2) / (sqrt((nc - 1) / 2) * gamma((nc - 2) / 2))} #' #' where \eqn{\Delta} is the observed effect size, \eqn{\Delta_{c}}{\Delta_c} is the #' corrected estimate of \eqn{\Delta}, #' \eqn{n_{control}}{nc} is the control-group sample size, and #' \eqn{\Gamma()}{gamma()} is the [gamma function][base::gamma()]. #' #' @encoding UTF-8 #' @md #' #' @examples #' correct_glass_bias(delta = .3, nc = 30, ne = 30) correct_glass_bias <- function(delta, nc, ne, use_pooled_sd = rep(FALSE, length(delta))){ n <- nc * ne / (nc + ne) m <- nc - 1 m[use_pooled_sd] <- m[use_pooled_sd] + ne[use_pooled_sd] - 1 cm <- exp(lgamma(m/2) - log(sqrt(m/2)) - lgamma((m - 1)/2)) delta * cm } #' Correct \eqn{d} values for measurement error and/or range restriction #' #' @description #' This function is a wrapper for the [correct_r()] function to correct \eqn{d} values #' for statistical and psychometric artifacts. #' #' @param correction Type of correction to be applied. Options are "meas", "uvdrr_g", "uvdrr_y", "uvirr_g", "uvirr_y", "bvdrr", "bvirr" #' @param d Vector of \eqn{d} values. #' @param ryy Vector of reliability coefficients for Y (the continuous variable). #' @param uy Vector of u ratios for Y (the continuous variable). #' @param uy_observed Logical vector in which each entry specifies whether the corresponding uy value is an observed-score u ratio (`TRUE`) or a true-score u ratio. All entries are `TRUE` by default. #' @param ryy_restricted Logical vector in which each entry specifies whether the corresponding rxx value is an incumbent reliability (`TRUE`) or an applicant reliability. All entries are `TRUE` by default. #' @param ryy_type String vector identifying the types of reliability estimates supplied (e.g., "alpha", "retest", "interrater_r", "splithalf"). See the documentation for [ma_r()] for a full list of acceptable reliability types. #' @param k_items_y Numeric vector identifying the number of items in each scale. #' @param rGg Vector of reliabilities for the group variable (i.e., the correlations between observed group membership and latent group membership). #' @param pi Proportion of cases in one of the groups in the observed data (not necessary if `n1` and `n2` reflect this proportionality). #' @param pa Proportion of cases in one of the groups in the population. #' @param sign_rgz Vector of signs of the relationships between grouping variables and the selection mechanism. #' @param sign_ryz Vector of signs of the relationships between Y variables and the selection mechanism. #' @param n1 Optional vector of sample sizes associated with group 1 (or the total sample size, if \code{n2} is \code{NULL}). #' @param n2 Optional vector of sample sizes associated with group 2. #' @param conf_level Confidence level to define the width of the confidence interval (default = .95). #' @param correct_bias Logical argument that determines whether to correct error-variance estimates for small-sample bias in correlations (`TRUE`) or not (`FALSE`). #' For sporadic corrections (e.g., in mixed artifact-distribution meta-analyses), this should be set to \code{FALSE} (the default). #' #' @return Data frame(s) of observed \eqn{d} values (`dgyi`), operational range-restricted \eqn{d} values corrected for measurement error in Y only (`dgpi`), operational range-restricted \eqn{d} values corrected for measurement error in the grouping only (`dGyi`), and range-restricted true-score \eqn{d} values (`dGpi`), #' range-corrected observed-score \eqn{d} values (\code{dgya}), operational range-corrected \eqn{d} values corrected for measurement error in Y only (`dgpa`), operational range-corrected \eqn{d} values corrected for measurement error in the grouping only (`dGya`), and range-corrected true-score \eqn{d} values (`dGpa`). #' #' @export #' @encoding UTF-8 #' @md #' #' @references #' Alexander, R. A., Carson, K. P., Alliger, G. M., & Carr, L. (1987). #' Correcting doubly truncated correlations: An improved approximation for #' correcting the bivariate normal correlation when truncation has occurred on #' both variables. *Educational and Psychological Measurement, 47*(2), 309–315. #' \doi{10.1177/0013164487472002} #' #' Dahlke, J. A., & Wiernik, B. M. (2020). Not restricted to selection research: #' Accounting for indirect range restriction in organizational research. #' *Organizational Research Methods, 23*(4), 717–749. \doi{10.1177/1094428119859398} #' #' Hunter, J. E., Schmidt, F. L., & Le, H. (2006). Implications of direct and #' indirect range restriction for meta-analysis methods and findings. #' *Journal of Applied Psychology, 91*(3), 594–612. #' \doi{10.1037/0021-9010.91.3.594} #' #' Le, H., Oh, I.-S., Schmidt, F. L., & Wooldridge, C. D. (2016). #' Correction for range restriction in meta-analysis revisited: #' Improvements and implications for organizational research. #' *Personnel Psychology, 69*(4), 975–1008. \doi{10.1111/peps.12122} #' #' Schmidt, F. L., & Hunter, J. E. (2015). #' *Methods of meta-analysis: Correcting error and bias in research findings* (3rd ed.). #' Sage. \doi{10.4135/9781483398105}. pp. 43–44, 140–141. #' #' @examples #' ## Correction for measurement error only #' correct_d(correction = "meas", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "meas", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for direct range restriction in the continuous variable #' correct_d(correction = "uvdrr_y", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "uvdrr_y", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for direct range restriction in the grouping variable #' correct_d(correction = "uvdrr_g", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "uvdrr_g", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for indirect range restriction in the continuous variable #' correct_d(correction = "uvdrr_y", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "uvdrr_y", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for indirect range restriction in the grouping variable #' correct_d(correction = "uvirr_g", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "uvirr_g", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for indirect range restriction in the continuous variable #' correct_d(correction = "uvdrr_y", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "uvdrr_y", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for direct range restriction in both variables #' correct_d(correction = "bvdrr", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "bvdrr", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) #' #' ## Correction for indirect range restriction in both variables #' correct_d(correction = "bvirr", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = .7, pa = .5) #' correct_d(correction = "bvirr", d = .5, ryy = .8, uy = .7, #' rGg = .9, pi = NULL, pa = .5, n1 = 100, n2 = 200) correct_d <- function(correction = c("meas", "uvdrr_g", "uvdrr_y", "uvirr_g", "uvirr_y", "bvdrr", "bvirr"), d, ryy = 1, uy = 1, rGg = 1, pi = NULL, pa = NULL, uy_observed = TRUE, ryy_restricted = TRUE, ryy_type = "alpha", k_items_y = NA, sign_rgz = 1, sign_ryz = 1, n1 = NULL, n2 = NA, conf_level = .95, correct_bias = FALSE){ correction <- match.arg(correction) correction <- gsub(x = correction, pattern = "_g", replacement = "_x") n <- n1 if(!is.null(n)){ n[!is.na(n2)] <- n[!is.na(n2)] + n2[!is.na(n2)] n1[is.na(n2)] <- n2[is.na(n2)] <- n[is.na(n2)] / 2 pi <- n1 / n pi[pi == 1] <- .5 } if(!is.null(pi)){ rxyi <- convert_es.q_d_to_r(d = d, p = pi) }else{ rxyi <- convert_es.q_d_to_r(d = d, p = .5) } if(!is.null(rGg)){ rxx <- rGg^2 }else{ rxx <- NULL } if(!is.null(pi) & !is.null(pa)){ ux <- sqrt((pi * (1 - pi)) / (pa * (1 - pa))) }else{ ux <- NULL } if(is.null(pa) & !is.null(pi)){ if(correction == "uvdrr_y" | correction == "uvirr_y"){ uy_temp <- uy if(length(uy_observed) == 1) uy_observed <- rep(uy_observed, length(d)) if(length(ryy_restricted) == 1) ryy_restricted <- rep(ryy_restricted, length(d)) if(correction == "uvdrr_y"){ uy_temp[!uy_observed] <- estimate_ux(ut = uy_temp[!uy_observed], rxx = ryy[!uy_observed], rxx_restricted = ryy_restricted[!uy_observed]) rxpi <- rxyi } if(correction == "uvirr_y"){ ryyi_temp <- ryy uy_temp[uy_observed] <- estimate_ut(ux = uy_temp[uy_observed], rxx = ryy[uy_observed], rxx_restricted = ryy_restricted[uy_observed]) ryyi_temp[ryy_restricted] <- estimate_rxxa(rxxi = ryy[ryy_restricted], ux = uy[ryy_restricted], ux_observed = uy_observed[ryy_restricted], indirect_rr = TRUE) rxpi <- rxyi / ryyi_temp^.5 } pqa <- pi * (1 - pi) * ((1 / uy_temp^2 - 1) * rxpi^2 + 1) pqa[pqa > .25] <- .25 pa <- convert_pq_to_p(pq = pqa) }else{ pa <- pi } } if(is.null(pi)) pi <- .5 if(is.null(pa)) pa <- pi out <- correct_r(correction = correction, rxyi = rxyi, ux = ux, uy = uy, rxx = rxx, ryy = ryy, ux_observed = TRUE, uy_observed = uy_observed, rxx_restricted = TRUE, rxx_type = "group_treatment", ryy_restricted = ryy_restricted, ryy_type = ryy_type, k_items_y = k_items_y, sign_rxz = sign_rgz, sign_ryz = sign_ryz, n = n, conf_level = conf_level, correct_bias = correct_bias) if(is.data.frame(out[["correlations"]])){ if(!is.null(pi)){ out[["correlations"]] <- convert_es.q_r_to_d(r = out[["correlations"]], p = matrix(pa, nrow(out[["correlations"]]), ncol(out[["correlations"]]))) }else{ out[["correlations"]] <- convert_es.q_r_to_d(r = out[["correlations"]], p = pa) } new_names <- colnames(out[["correlations"]]) new_names <- gsub(x = new_names, pattern = "r", replacement = "d") new_names <- gsub(x = new_names, pattern = "x", replacement = "g", ignore.case = FALSE) new_names <- gsub(x = new_names, pattern = "t", replacement = "G", ignore.case = FALSE) colnames(out[["correlations"]]) <- new_names }else{ out_names <- names(out[["correlations"]]) for(i in out_names){ if(!is.null(pi)){ out[["correlations"]][[i]][,1:3] <- convert_es.q_r_to_d(r = out[["correlations"]][[i]][,1:3], p = matrix(pa, nrow(out[["correlations"]][[i]]), 3)) }else{ out[["correlations"]][[i]][,1:3] <- convert_es.q_r_to_d(r = out[["correlations"]][[i]][,1:3], p = pa) } } new_names <- gsub(x = out_names, pattern = "r", replacement = "d") new_names <- gsub(x = new_names, pattern = "x", replacement = "g", ignore.case = FALSE) new_names <- gsub(x = new_names, pattern = "t", replacement = "G", ignore.case = FALSE) names(out[["correlations"]])[names(out[["correlations"]]) %in% out_names] <- new_names } names(out)[names(out) == "correlations"] <- "d_values" class(out)[class(out) == "correct_r"] <- "correct_d" out }
f9a2744de35475b8c5ee0703773a2903be29c78f
51e22345b740b9ec1e2ddbf54a8cada4b0caf93e
/yams_pike_bootstrap.R
4eb8ead0ee7406cede1bfd850a19e036b5981e1c
[]
no_license
kimwhoriskey/yams
9598673979de2a0f0df80dc13a75ae66cb5d3168
b61f0eafe0b7e875f3a7fae90a621468c813f32b
refs/heads/main
2023-04-16T19:13:34.745108
2022-01-28T15:33:26
2022-01-28T15:33:26
375,415,917
0
0
null
null
null
null
UTF-8
R
false
false
13,911
r
yams_pike_bootstrap.R
# bootstrap the 2 behaviour model #### set up working directory setwd("~/Desktop/yams") rm(list=ls()) library(data.table) library(ggplot2) library(yaps) library(TMB) library(tidyverse) library(gridExtra) library(mgcv) library(sp) source('yapsfunctions.R') source('issmfunctions.R') source("simtrack.R") fmf <- wesanderson::wes_palette("FantasticFox1", type = "discrete") # TMB functions compile("yaps_ssm.cpp") dyn.load(dynlib("yaps_ssm")) compile("yaps_hmm.cpp") dyn.load(dynlib("yaps_hmm")) #### load mods and data #### load mods and data # bring in sync data to extract hydro positions sync <- readRDS('data/sync.RDS') hydros <- data.table::data.table(sync$pl$TRUE_H) colnames(hydros) <- c('x','y','z') # bring in the lake lake <- readRDS("data/lake.rds") # bring in time of arrival data (see yams_prepdata.R) toalist <- readRDS('output/toalist.RDS') # extract toa and burst interval vector toa <- toalist$toa bivec <- toalist$seq # bring in the model results mods21 <- readRDS("output/m2svhmm1.RDS") mods22 <- readRDS("output/m2svhmm60.RDS") mods31 <- readRDS("output/m3svhmm1.RDS") mods32 <- readRDS("output/m3svhmm60.RDS") # need this too rbi_min <- 10 rbi_max <- 30 ####### pick the best mod for each group # compare nlls cbind(sapply(mods21, function(x)min(x$ssm_nll$nll)), sapply(mods22, function(x)min(x$ssm_nll$nll))) mods2winners <- apply(cbind(sapply(mods21, function(x)min(x$ssm_nll$nll)), sapply(mods22, function(x)min(x$ssm_nll$nll))), 1, which.min) mods2winners cbind(sapply(mods31, function(x)min(x$ssm_nll$nll)), sapply(mods32, function(x)min(x$ssm_nll$nll))) mods3winners <- apply(cbind(sapply(mods31, function(x)min(x$ssm_nll$nll)), sapply(mods32, function(x)min(x$ssm_nll$nll))), 1, which.min) mods3winners allmods2 <- list(mods21, mods22) allmods3 <- list(mods31, mods32) # get the best mods for 2 and 3 mods2 <- list() for(i in 1:5) mods2[[i]] <- allmods2[[mods2winners[i]]][[i]] mods3 <- list() for(i in 1:5) mods3[[i]] <- allmods3[[mods3winners[i]]][[i]] # pick a single mod to calculate the detection efficiency # we'll pick the first group of the 2 state model mod <- mods2[[1]] modidx <- rep(1:5, each=5000) toamats <- split(data.table(toa), factor(modidx)) %>% lapply(as.matrix) bivecs <- split(bivec, factor(modidx)) ######################################################### ########### estimate the detection efficiency ########### ######################################################### # we need to estimate the detection efficiency for the simulation study # i explored several options, this one worked by far the best # to get the data in the right format, translate toa into 0s and 1s toa01 <- ifelse(is.na(toamats[[1]]), 0, 1) # this is only for one subset dets <- reshape2::melt(toa01 %>% t()) %>% rename(hydro=Var1, pingidx=Var2, det=value) # var1 is row of original data frame / matrix (in our case hydro) # var 2 is column of original data frame / matrix (in our case time) # value is the value of the element obj <- mod$ssm_results[[mod$winner]]$obj # get the distances from the tmb object dets$dist <- reshape2::melt(obj$report()$dist)$value dets <- data.table(dets) ####### # basic approach is to bin the data and calculating detection probabilities empirically # then fit a binomial glm with weights # use 5 m intervals # assuming detection probability is constant through space and time distidx <- seq(0, max(dets$dist), by=5) dets$distidx <- findInterval(dets$dist, distidx)*5 # basically rounding to the nearest five deteff <- dets %>% group_by(distidx) %>% arrange(distidx) %>% summarize(eff = mean(det), totdet = n()) head(deteff) # find the largest distance without a 0 value max(deteff[deteff$eff!=0,]$distidx) # everything above 930 is = 0 (deteff that is) # we'll assume everything over 1000m has a zero probability # that is pretty standard for acoustic telemetry which(deteff$eff==1) # we also have two rows with efficiency = 1 deteff <- deteff[deteff$distidx < 1000,] deteff %>% ggplot(aes(x=distidx, y=eff, col=totdet)) + geom_point() + xlim(0, 1000) + theme_bw() # fit the binomial with weights de <- gam(eff~ s(distidx), data = deteff, family=binomial, weights = totdet) deteff %>% ggplot(aes(x=distidx, y=eff, col=totdet)) + geom_point() + geom_line(aes(x=distidx, y=fitted(de)), col='tomato') + theme_bw() # quick cross validation, sample 70% in inidx, the rest go into outidx inidx <- sort(sample(1:nrow(deteff), size=round(.7*nrow(deteff)))) outidx <- (1:nrow(deteff))[!(1:nrow(deteff)) %in% inidx] detefftrain <- deteff[inidx,] detrain <- gam(eff~ s(distidx), data = detefftrain, family=binomial, weights = totdet) outpreds <- predict(detrain, newdata=deteff[outidx,], type="response") predpts <- rbind( cbind(deteff[outidx,c('distidx', 'eff')], type=rep("Observed", length(outidx))), cbind(deteff[outidx,'distidx'], eff=outpreds, type=rep("Predicted", length(outidx))) ) # plot the training/testing results detefftrain %>% ggplot(aes(x=distidx, y=eff, col=totdet)) + geom_point() + scale_color_gradient(low=fmf[3], high="navyblue", name="Total No. of\nDetections") + geom_line(aes(x=distidx, y=fitted(detrain)), col=fmf[5]) + ggnewscale::new_scale("col") + #whoa ggnewscale FOR THE WIN, man that was a b geom_point(data=predpts, aes(x=distidx, y=eff, col=factor(type)), size=2, inherit.aes = FALSE) + scale_color_manual(values=c(fmf[4], fmf[5]), name='Testing Data') + xlab("Distance (m)") + ylab("Detection Efficiency") + theme_bw() # efficiency at 250 and 500 m predict(de, newdata=data.frame(distidx=c(100, 250, 500, 750)), type='response') # really cool # these are the same regardless of using mod2 or mod3 ######################################## # run simulation studies # need the lake data because we want to place the sim dat randomly within the lake # have to input the centered hydros and lake to match the predictions from yaps centeredlake <- lake[, c("X", "Y")] - hydros[, c("x", "y")][rep(1, nrow(lake))] centeredhydros <- hydros[, c("x", "y")] - hydros[, c("x", "y")][rep(1, nrow(hydros))] lakepoly <- Orcs::coords2Polygons(as.matrix(centeredlake), ID="lake") # pick mod to base sim on mod <- mods2[[1]] # starting values: use second choice because it was better for the first set boot <- bootstrap(mod, startseed=42, # started at 42, so now do 72 nsims=60, savepath='output/twostatesboot', useSSMds = FALSE, dstart=60, simargs = list( hydropos = centeredhydros, poly=lakepoly, nloc = 5000, bi = c(10,30), demod = de, me="t", sos=1465, multipath=NULL, move="Wiener", case=2, timescale=60), issm.args = list(maxsteps=5, fixsteps=TRUE, allowfc=FALSE, fcmax=3, jiggle_fc=0.01, initssmargs = list(mapping = list(working_A = factor(matrix(NA)))), ssmargs = list(mapping = list(working_A = factor(matrix(NA, nrow=2, ncol=2))), optimizer='nlminb'), timescalehmm=60, logdstart = c(log(60), log(60)),#c(1,3), setinitstatdist=1) ) mod <- mods3[[1]] # starting values: use second choice because it was better for the first set boot <- bootstrap(mod, startseed=42, nsims=60, savepath='output/threestatesboot', dstart=60, simargs = list( hydropos = centeredhydros, poly=lakepoly, nloc = 5000, bi = c(10,30), demod = de, me="t", sos=1465, multipath=NULL, move="Wiener", case=2, timescale=60), issm.args = list(maxsteps=7, m=3, fixsteps=TRUE, allowfc=FALSE, fcmax=3, jiggle_fc=0.03, initssmargs = list(mapping = list(working_A = factor(matrix(NA)))), ssmargs = list(mapping = list(working_A = factor(matrix(NA, nrow=3, ncol=3))), inner_control = list(maxit=1500), optimizer='nlminb'), timescalehmm=60, logdstart = c(log(60), log(60), log(60)),#c(1,3), setinitstatdist=1) ) ################################## # look at simulation results boot2 <- readRDS('output/twostatesboot.RDS') boot3 <- readRDS('output/threestatesboot.RDS') # check if any didn't work sapply(boot2$mods, length) %>% length sapply(boot3$mods, length) %>% length # only 57 worked # check convergence sapply(boot2$mods, function(x)x$ssm_results[[x$winner]]$mess) sapply(boot2$mods, function(x)x$ssm_results[[x$winner]]$opt$convergence) fcidx2 <- which(sapply(boot2$mods, function(x)x$ssm_results[[x$winner]]$opt$convergence)>0) length(fcidx2) length(boot2$mods)-length(fcidx2) sapply(boot3$mods, function(x)x$ssm_results[[x$winner]]$mess) sapply(boot3$mods, function(x)x$ssm_results[[x$winner]]$opt$convergence) fcidx3 <- which(sapply(boot3$mods, function(x)x$ssm_results[[x$winner]]$opt$convergence)>0) length(fcidx3) length(boot3$mods)-length(fcidx3) # summary stats summary(1-boot2$err.rate[-fcidx2]) summary(boot2$lon.rmse[-fcidx2]) summary(boot2$lat.rmse[-fcidx2]) summary(boot2$rmse) summary(1-boot3$err.rate[-fcidx3]) summary(boot3$lon.rmse[-fcidx3]) summary(boot3$lat.rmse[-fcidx3]) summary(boot3$rmse) # get bootstrap results ready for plotting bootdat <- data.frame(val=c(1-boot2$err.rate[-fcidx2], 1-boot3$err.rate[-fcidx3], boot2$lon.rmse[-fcidx2], boot3$lon.rmse[-fcidx3], boot2$lat.rmse[-fcidx2],boot3$lat.rmse[-fcidx3], boot2$rmse[-fcidx2], boot3$rmse[-fcidx3]), type=rep(c('bstateacc', 'Eastings', 'Northings', 'locstateacc'), each=length(boot2$err.rate[-fcidx2])+length(boot3$err.rate[-fcidx3])), m=factor(rep(c('Two-State Model', 'Three-State Model'), times=c(length(boot2$err.rate[-fcidx2]),length(boot3$err.rate[-fcidx3]))), levels=c('Two-State Model', 'Three-State Model'))) ########################## # look at state accuracy bootdat %>% filter(type=='bstateacc') %>% ggplot(aes(x=m, y=val, group=m, fill=m)) + geom_boxplot() + ylim(0.6, 1) + theme_bw() + ylab('Proportion') + ggtitle('Behavioural State Accuracy') + scale_fill_manual(values=c('slategray1', 'cadetblue')) + theme(legend.position = 'none', axis.title.x=element_blank(), plot.title = element_text(hjust = 0.5)) # location state accuracy in each axis bootdat %>% filter(type %in% c('Eastings', 'Northings')) %>% ggplot(aes(x=m, y=val, fill=m)) + geom_boxplot() + theme_bw() + ylab('Root Mean Squared Error (m)') + xlab('Location Axis') + ggtitle('Location State Accuracy') + facet_wrap(~type) + scale_fill_manual(values=c('slategray1', 'cadetblue')) + theme(legend.position = 'none', strip.background = element_blank(), panel.border = element_rect(colour = "black", fill = NA), axis.title.x=element_blank(), plot.title = element_text(hjust = 0.5)) # location state accuracy total bootdat %>% filter(type=='locstateacc') %>% ggplot(aes(x=m, y=val, fill=m)) + geom_boxplot() + theme_bw() + ylab('Root Mean Squared Error (m)') + xlab('Location Axis') + ggtitle('Location State Accuracy') + scale_fill_manual(values=c('slategray1', 'cadetblue')) + theme(legend.position = 'none', axis.title.x=element_blank(), plot.title = element_text(hjust = 0.5)) # let's look at the winners sapply(boot2$mods, function(x)x$winner) sapply(boot3$mods, function(x)x$winner) # don't need many iterations ################################## # let's look at the parameters now boot2$true.pars boot2$pars # lets do some tables boot2$pars %>% select(-par, -true) %>% select(-fcidx2) %>% mutate(mean=rowMeans(.), sd=sqrt(apply(., 1, var)), lower2.5=apply(., 1, quantile, 0.025), upper97.5=apply(., 1, quantile, 0.975), median=apply(., 1, median)) %>% mutate(true=boot2$true.pars, par=as.character(boot2$pars$par)) %>% select(par, true, mean, median, sd, lower2.5, upper97.5) %>% xtable::xtable(digits=3) %>% print(include.rownames=FALSE) boot3$pars %>% select(-par, -true) %>% select(-fcidx3) %>% mutate(mean=rowMeans(.), sd=sqrt(apply(., 1, var)), lower2.5=apply(., 1, quantile, 0.025), upper97.5=apply(., 1, quantile, 0.975), median=apply(., 1, median)) %>% mutate(true=boot3$true.pars, par=as.character(boot3$pars$par)) %>% select(par, true, mean, median, sd, lower2.5, upper97.5) %>% xtable::xtable(digits=3) %>% print(include.rownames=FALSE)
160216624fd0ac0580ba6bf70a7f0494ebe1cdd8
f804b28e0d1b4a12587f84c52cf9742c6bd845c6
/Plot2.R
13159fe498d770815a36620408b6d093ea59f21b
[]
no_license
zzzz88/ExData_Plotting1
b56c943187f3fac2b6aa789fd14c02343c66316c
00488b832b8d10ba4336b67aff8be6220cacd3d9
refs/heads/master
2020-04-15T04:17:20.842313
2019-01-09T04:57:11
2019-01-09T04:57:11
164,377,202
0
0
null
2019-01-07T04:14:42
2019-01-07T04:14:42
null
UTF-8
R
false
false
533
r
Plot2.R
data <- read.table("household_power_consumption.txt",sep = ";", header = TRUE,stringsAsFactors = FALSE) data[,"Date"]= as.Date(data[,"Date"], format = "%d/%m/%Y") my_data <- subset (data, Date == "2007-02-01"| Date =="2007-02-02") datatime <- strptime(paste(my_data[,"Date"], my_data[,"Time"], sep = " "), format = "%Y-%m-%d %H:%M:%S") GlobalAP <-as.numeric(my_data$Global_active_power) png("plot2.png", width = 480, height = 480) plot(datatime, GlobalAP, type = "l", xlab = " ", ylab = "Global Active Power (kilowattes)") dev.off()
e2338a535abe91d3e472872761f46c79984f7e56
7858fc8a03b2a14debcb4aadcc3ef2a221b911c3
/DSP/4.5.r
e7fe63e261ff0650dba89f490cf7f22a89f69b09
[]
no_license
T-Oxy/free-depot
2cbf9bc8d13a648fc6175989753efee5c07fbb73
84396b989ada99a7e20f42b9bf73812cc434c530
refs/heads/master
2023-08-22T11:02:05.863276
2021-09-29T05:17:14
2021-09-29T05:17:14
241,281,261
0
0
null
null
null
null
UTF-8
R
false
false
144
r
4.5.r
x <- c(0.0,3.0,4.0 ,1.0 ,-2.0 ,-1.0 ,0.0 ,10 ,-1.0 ,0.0) sum =0 N =length(x) for(i in 1:N){ sum = sum +x[i] } mean <- (sum / N) #平均値
12f33f40a39af47f055eb52b4eeda35d870f88ef
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/datarobot/examples/UploadTransferrableModel.Rd.R
38a3e9d4265cf33660225f1757d9c1d7d79f4a18
[]
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
255
r
UploadTransferrableModel.Rd.R
library(datarobot) ### Name: UploadTransferrableModel ### Title: Import a previously exported model for predictions. ### Aliases: UploadTransferrableModel ### ** Examples ## Not run: ##D UploadTransferrableModel("model.drmodel") ## End(Not run)
6196f6a95b67d8e8ba65dd7b28559e82719084d7
e256b7f59b8a9e59a025279f799cc1414b556bd6
/run_analysis.r
860dedf3caab940b91653f6e311fb2be3f1a07e3
[]
no_license
nitinaggarwal1986/Getting_and_cleaning_data_Project
e44bcf3ccb75d7b39a030a0ee2efe14eb0e52e10
082c3ff838c30bd8c32909375d7f39474eea9885
refs/heads/master
2020-04-07T11:48:23.207903
2015-07-26T19:27:09
2015-07-26T19:27:09
39,737,573
0
0
null
null
null
null
UTF-8
R
false
false
1,747
r
run_analysis.r
#Load the data from the files with training set. train<-read.table("UCI HAR Dataset/train/X_train.txt") train_a<-read.table("UCI HAR Dataset/train/y_train.txt") train_s<-read.table("UCI HAR Dataset/train/subject_train.txt") #Load the data from the files with test set. test<-read.table("UCI HAR Dataset/test/X_test.txt") test_a<-read.table("UCI HAR Dataset/test/y_test.txt") test_s<-read.table("UCI HAR Dataset/test/subject_test.txt") #Load the list of features. features<-read.table("UCI HAR Dataset/features.txt") #Initializing the result with all the observations with the activity index. Tidy<-rbind(cbind(subject=train_s,activity=train_a,train),cbind(subject=test_s,activity=test_a,test)) #Giving the columns proper names. colnames(Tidy)<-c("subject","activity",as.character(features[,2])) names<-as.character(colnames(Tidy)) #Identifying the indices with activity, mean and standard deviation of variables. indices<-c("subject","activity",names[grep("-mean()",names)],names[grep("-std()",names)]) indices<-indices[order(indices)] #Subsetting the Dataset to get the Tidy dataset required. Tidy<-Tidy[,indices] #Reading the activity lables from the activity_labels.txt file and then replacing the #numbers with corresponding labels in the activity column. activity<-read.table("UCI HAR Dataset/activity_labels.txt") Tidy$activity<-activity$V2[Tidy$activity] #Creating the second Tidy data set with the averages of each variable for each activity #and each subject. Tidy2<-NULL for(i in 1:30){ for(j in 1:5){ ind<-which(Tidy[,"subject"]==i&Tidy[,"activity"]==as.character(activity[j,2]), arr.ind=TRUE) Tidy2<-rbind(Tidy2, cbind(subject=i, activity=as.character(activity[j,2]), t(colMeans(Tidy[ind,3:81])))) } }
fbe3bb65dfb6e1efcf66690db84fab5bfd3acf8e
43b93fc1d6a858ee1eb09f037954b5a3c8bf3195
/R/utilities.R
d8e88b49dd41bc01175d7988a68bbc6319cd4a9a
[]
no_license
abarbour/irisws
dfd7e7965d9c92c75fdc03cdaa58b9a23865f718
33c019c8550e319273859e1e558cd3230ba697f8
refs/heads/master
2021-01-17T07:26:00.671670
2016-06-10T22:15:21
2016-06-10T22:15:21
13,811,412
1
0
null
null
null
null
UTF-8
R
false
false
21,784
r
utilities.R
#' Constructs a query function #' #' @details #' These functions form correctly formatted queries for IRIS WS. #' #' \code{\link{constructor}} is a basic constructor which simply #' collapses the arguments into a single query. #' #' \code{\link{constructor2}} also does this, but enforces #' parameter inputs so the #' query at least has a chance for success. #' #' \code{\link{params2queryparams}} is a function #' to collapse arguments into a single query string #' #' @param ... query parameters. #' For \code{\link{constructor}} these are comma-separated character strings (\code{"a=1", "b=2"} etc) #' For \code{\link{constructor2}} these are comma-separated arguments (\code{a=1, b=2} etc) #' @param service character; the type of web service to construct for. #' @param defaults list; the parameters to merge \code{...} with #' @param list.fields.only logical; return names of default arguments #' @param exclude.empty.options logical; should the result \emph{not} contain #' optional arguments which were not specified? #' @param exclude.null.fields logical; should \code{NULL} fields in \code{...} #' or \code{defaults} be removed prior to operations? #' @param ws.version character; corresponds to the documentation version (See [1]). #' @param query.field character; the user should not need to change this (it only exists #' to give the function wider applicability). #' @return character string(s) #' #' @name irisws-queryconstruction #' @author A.J. Barbour; and, see [2] #' #' @references #' [1] \url{http://service.iris.edu/irisws/} #' @references #' [2] \url{http://pages.stern.nyu.edu/~dbackus/BCH/data/FRED/fredplot.R} #' was the motivation for \code{\link{params2queryparams}}. #' #' @seealso #' \code{\link{iris.query}} to query IRIS WS #' #' @seealso \code{\link{irisws-wadl}} for using .wadl files #' #' \code{\link{irisws-package}} #' #' @family Utilities #' #' @examples #' \dontrun{ #' # Basic construction: #' constructor() #' constructor("net=1","sta=2") #' # #' # parameter flattening #' params2queryparams(net=1,sta=2) #' params2queryparams(net=1,sta=NULL) #' # this only adds parameters #' params2queryparams(a=1, b=2, defaults=c(a=1, b=1,c=2)) #' # this adds mandatory/optional (TRUE/FALSE) parameters: #' params2queryparams(a=1, b=2, defaults=c(a=TRUE, b=FALSE)) #' # missing optionals are excluded by default #' params2queryparams(a=1, defaults=c(a=TRUE, b=FALSE, c=TRUE)) #' # include them: #' params2queryparams(a=1, defaults=c(a=TRUE, b=FALSE, c=TRUE), exclude.empty.options=FALSE) #' # #' # Constrained construction: #' Q <- constructor2(net=1, sta=2) #' print(Q) # note the 'MISSING.MANDATORY' field values #' # check that it's valid: #' try(check.query(Q)) # it's not. #' # #' # Another... Distaz #' # What needs to be given though?? #' constructor2(service="distaz", list.fields.only=TRUE) #' # fill them in... #' Q <- constructor2(stalat=45, stalon=-120, evtlat=30.0, evtlon=-100.0, service="distaz") #' print(Q) #' # check that it's valid: #' try(check.query(Q)) # it is. #' # #' # 'endtime' is an optional default, by default, and also #' not recognized if it is NULL #' all.equal(constructor2(), constructor2(endtime=NULL)) #' } NULL #' @rdname irisws-queryconstruction #' @export constructor <- function(..., service=c("timeseries","distaz","traveltime","flinnengdahl","resp"), ws.version=c("1","2"), query.field="query?"){ # # service here DOES need to match iris specification service <- match.arg(service) # ver <- match.arg(ws.version) # service.iris.edu <- .iriswsBaseUrl query <- query.field irisquery <- paste(service.iris.edu, service, ver, query, sep="/") query <- paste0(irisquery, paste(..., sep="&")) # return(query) } #' @rdname irisws-queryconstruction #' @export constructor2 <- function(...) UseMethod("constructor2") #' @rdname irisws-queryconstruction #' @export constructor2.default <- function(..., service=c("timeseries","distaz","tt.deg","tt.km","tt.llpairs","resp","flinnengdahl"), list.fields.only=FALSE, ws.version="1"){ # # service here does NOT need to match iris specification service <- match.arg(service) # # minimum defaults # FALSE fields are considered optional (was NULL) # TRUE fields are considered mandatory mandatory <- TRUE optional <- FALSE if (service=="timeseries"){ #http://service.iris.edu/irisws/timeseries/1/ # opts <- list(...) # # default: endtime is optional d.et <- optional # and duration is mandatory d.dur <- mandatory # if ("endtime" %in% names(opts)){ # endtime was given if (!is.null(opts[["endtime"]])){ # and it was not null, so # endtime is mandatory d.et <- mandatory # duration is optional d.dur <- optional } } mlst <- list(#rqd: net=mandatory, sta=mandatory, loc=mandatory, cha=mandatory, starttime=mandatory, # these are either/or endtime=d.et, duration=d.dur, # filter options: (order matters!) taper=optional, envelope=optional, lpfilter=optional, hpfilter=optional, bpfilter=optional, demean=optional, differentiate=optional, integrate=optional, scale=optional, divscale=optional, correct=optional, freqlimits=optional, autolimits=optional, units=optional, decimate=optional, antialiasplot=optional, audiocompress=optional, audiosamplerate=optional, # and rqd: output=mandatory) } else if (service=="flinnengdahl"){ #http://service.iris.edu/irisws/flinnengdahl/2/ mlst <- list(lat=mandatory, lon=mandatory, output=mandatory) } else if (service=="distaz"){ #http://service.iris.edu/irisws/distaz/1/ mlst <- list(stalat=mandatory, stalon=mandatory, evtlat=mandatory, evtlon=mandatory) } else if (service=="tt.deg"){ #http://service.iris.edu/irisws/traveltime/1/ # where distance is epicentral degrees #/query? (distdeg=<degrees>) [evdepth=<km>] [model=<iasp91|prem|ak135>] [phases=<phaselist>] [output-params] service <- "traveltime" mlst <- list(distdeg=mandatory, evdepth=optional, model=optional, phases=optional, noheader=optional, traveltimeonly=optional, rayparamonly=optional, mintimeonly=optional) } else if (service=="tt.km"){ #http://service.iris.edu/irisws/traveltime/1/ # where distance is kilometers #/query? (distdeg=<km>) [evdepth=<km>] [model=<iasp91|prem|ak135>] [phases=<phaselist>] [output-params] service <- "traveltime" mlst <- list(distkm=mandatory, evdepth=optional, model=optional, phases=optional, noheader=optional, traveltimeonly=optional, rayparamonly=optional, mintimeonly=optional) } else if (service=="tt.llpairs"){ #http://service.iris.edu/irisws/traveltime/1/ # where distance is lat/lon pairs #/query? (evtloc=<LatLonPair>) [evdepth=<km>] (staloc=<LatLonList>) [model=<iasp91|prem|ak135>] [phases=<phaselist>] [output-params] service <- "traveltime" mlst <- list(evloc=mandatory, evdepth=optional, staloc=mandatory, model=optional, phases=optional, noheader=optional, traveltimeonly=optional, rayparamonly=optional, mintimeonly=optional) } else if (service=="resp"){ #http://service.iris.edu/irisws/resp/1/ # opts <- list(...) nopts <- names(opts) # mlst <- list(net=mandatory, sta=mandatory, loc=mandatory, cha=mandatory) # if ("time" %in% nopts){ # some time field was given #[time=<time>] | [start=<time> & end=<time>] | [start = <time> ] | [end = <time>] timepar <- opts[["time"]] if ( !is.null(timepar) & (nchar(timepar)>0) ){ # and it was not null, so mlst$time <- optional } else { mlst$starttime <- optional mlst$endtime <- optional } } } if (list.fields.only){ ## Return only the field names defs <- unlist(mlst) optional.fields <- !defs defsn <- names(defs) f.req <- defsn[!optional.fields] f.opt <- defsn[optional.fields] query <- list(required.fields=f.req, optional.fields=f.opt) } else { ## or the actual query qparams <- params2queryparams(..., defaults=mlst, exclude.empty.options=TRUE, exclude.null.fields=TRUE) query <- constructor(qparams, service=service, ws.version=ws.version) } #print(query) return(query) } #' @rdname irisws-queryconstruction #' @export params2queryparams <- function(..., defaults, exclude.empty.options=TRUE, exclude.null.fields=TRUE){ # creates a list of parameters: e.g., a, b plist <- list(...) #print(plist) if (missing(defaults)){ defaults <- list() } else { if (!inherits(defaults, "list")){ defaults <- as.list(defaults) warning("'defaults' was not of class 'list' and was therfore coerced to one: values may have been changed") } } #print(defaults) if (exclude.null.fields){ plist <- plist[!sapply(plist, is.null)] defaults <- defaults[!sapply(defaults, is.null)] } if (exclude.empty.options){ NCFUN <- function(X){ # # function returns logical depending if # the string is empty, and fails # if arg is of multiple-length # # nzchar?? # if (length(X)>1){ stop(c("invalid multiple-length argument given. ", "\nOffending values: ", paste(X, collapse=" "))) } else { nchar(X) == 0 } } pEmpties <- sapply(plist, NCFUN) plist <- plist[!pEmpties] dEmpties <- sapply(defaults, NCFUN) defaults <- defaults[!dEmpties] } params <- RCurl::merge.list(plist, defaults) param.names <- names(params) # flattens to strings with, e.g., "a=1", "b=1", etc miss.opt <- .field.optional miss.mand <- .field.mandatory not.applic <- .field.na Eparams <- sapply(param.names, function(Pname, Dat=params) { val <- Dat[[Pname]] ##print(val) if (!is.na(val)){ if (val=="TRUE"){ # mandatory, but missing val <- miss.mand } else if (val=="FALSE"){ # optional, and missing val <- miss.opt } } else { val <- not.applic } #print(c(Pname,val)) paste0(Pname, "=", val) }) # collapse them into a single line #print(Eparams) if (exclude.empty.options){ optionals <- grepl(pattern=miss.opt, Eparams) Eparams <- Eparams[!optionals] #empties <- sapply(Eparams, function(X) nchar(X)==0) #Eparams <- Eparams[!empties] } #print(Eparams) Qparams <- paste(Eparams, collapse="&") return(Qparams) } #' Perform a query to IRIS-WS #' @details #' This function uses \code{\link{curlPerform}} in the \strong{RCurl} package #' to query the IRIS WS. #' Firstly, it #' checks \code{query} #' for internal consistency, with \code{\link{check.query}}; #' then, \code{query} is checked externally with \code{\link{url.exists}}. #' If \code{query} passes the checks, then it is sent to the IRIS WS #' and successfull results are written to \code{filename} (which is instantiated #' with \code{\link{CFILE}}). #' #' \code{\link{iris.query}} is simply a pointer to \code{\link{query.iris}} #' #' @author AJ Barbour #' @export #' #' @param iquery character; the web service query #' @param filename character; the file to save query results to. #' If this is \code{NULL} a #' temporary file from \code{\link{tempfile}} is used. #' @param is.binary logical; will the output be binary? (e.g., \code{TRUE} for SAC binary, and \code{FALSE} for a plot) #' @param check logical; should \code{\link{check.query}} be used to check the quality of \code{iquery} #' @param verbose logical; should messages be given by this function, and \code{\link{curlPerform}}? #' @param ... additional arguments to \code{\link{curlPerform}} #' #' @return A list (invisibly) with the filename, the query string, and a success flag #' #' @seealso #' \code{\link{irisws-package}} #' #' @family Utilities #' #' @examples #' \dontrun{ #' # #' # irisws can be used to get timeseries, etc #' # but there is also a fair amount invested in #' # preventing failure because of bad args, etc #' # #' # This query will create ANMO.png (setting duration, but could also use end=2005.002T00:00:00) #' # constructor2 assembles all the options for a given webservice into a query #' Q <- constructor2(net="IU", sta="ANMO", loc="00", cha="BHZ", starttime="2005.001T00:00:00", duration="1000", output="plot") #' # and this performs the query #' query.iris(Q, "ANMO.png") #' # again, but in a temporary file #' query.iris(Q, NULL) #' #... and in the default file #' query.iris(Q) #' # #' # This query will fail, obviously (unless there's a seismic network named 'XXXTHISWILLFAILXXX') #' Q <- constructor("net=XXXTHISWILLFAILXXX") #' query.iris(Q) #' #' # Arbitrary query generation #' q1 <- params2queryparams(a=1, defaults=list(a=TRUE)) #' q2 <- params2queryparams(a=1, defaults=list(a=TRUE,b=2,c=NA)) #' q3 <- params2queryparams(a=1, defaults=list(a=TRUE,b=2,c=FALSE)) #' q4 <- params2queryparams(a=1, defaults=list(a=TRUE,b=2,c=FALSE), exclude.empty.options=FALSE) #' q5 <- params2queryparams(a=1, defaults=list(a=TRUE,b=2,c=TRUE)) #' q6 <- params2queryparams(a=1, defaults=list(a=TRUE,b=2,c=FALSE,d=NA,e="")) #' q7 <- params2queryparams(a=1, defaults=list(a=TRUE,b=2,c=FALSE,d=NA,e=""), exclude.empty.options = FALSE, exclude.null.fields = FALSE) #' q1;q2;q3;q4;q5;q6;q7 #' #' # Arbitrary query validation #' try(check.query(q1)) # succeeds #' try(check.query(q2)) # fails #' try(check.query(q3)) # succeeds #' try(check.query(q4)) # fails #' try(check.query(q5)) # fails #' try(check.query(q6)) # fails #' try(check.query(q7)) # fails #' } query.iris <- function(iquery, filename="iris.query.results", is.binary=FALSE, check=TRUE, verbose=TRUE, ...){ if (check) check.query(iquery) ure <- RCurl::url.exists(iquery) if (ure){ if (is.null(filename)){ filename <- tempfile('iris.query.results') } # binary mode for file init md <- paste0("w", ifelse(is.binary, "b", "")) lf = RCurl::CFILE(filename, mode=md) # perform curl ops RC <- RCurl::curlPerform(url = iquery, writedata = lf@ref, verbose=verbose, ...) # close file RCurl::close(lf) if (verbose) message(sprintf("IRIS WS query complete: %s", filename)) } else { if (verbose) warning(sprintf("IRIS WS query FAILED: %s", iquery)) } toret <- list(file=filename, query=iquery, success=ure) assign("last_irisquery", toret, envir=.iriswsEnv) return(invisible(toret)) } #' @export #' @rdname query.iris iris.query <- query.iris #' @export #' @rdname query.iris check.query <- function(iquery){ QQ <- unlist(strsplit(as.character(iquery), "query?")) nq <- length(QQ) #[1] "http://service.iris.edu/irisws/timeseries/1/" "net=1&sta=2&loc=MISSING.MANDATORY&..." Q <- QQ[nq] Qs <- unlist(strsplit(Q,"&")) grtests <- c( gr1 <- grepl(pattern=.field.mandatory, Qs), gr2 <- grepl(pattern=.field.optional, Qs), gr3 <- grepl(pattern='=$', Qs), # empty field gr4 <- grepl(pattern=' $', Qs), # white space at end gr5 <- grepl(pattern=.field.na, Qs) ) #[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE not.ok <- any(grtests) if (not.ok){ offenders <- unique(c(Qs[gr1], Qs[gr2], Qs[gr3], Qs[gr4], Qs[gr5])) stop(paste("Invalid query:", paste(offenders, collapse=" "))) } return(invisible(list(Q=iquery, Qs=Qs, successful=!not.ok))) } #' Utilities to deal with time #' #' @description #' \code{\link{timestring}} produces properly formatted #' strings for the time-fields of, say, \code{\link{query.iris}}, #' acceptable to IRIS WS. #' #' \code{\link{ISOdatetime.j}} produces a \code{POSIXct} object #' using the Julian date (day of year), or from an appropriately #' formatted character string #' in \code{tstr} (as produced by \code{\link{timestring}}). #' #' @details #' An IRIS WS time-string can be formatted in two ways: #' (1a) using year-month-day, (e.g., \code{'1997-01-31T12:04:32.123'}) or #' (2) using year-day (e.g.,\code{'1997.031T12:04:32.123'}), #' where the string after 'T' corresponds to hour:minute:fractional-seconds. #' The string can also be of the form (1b) #' \code{'1997-01-31'} (in this case \code{'00:00:00'} is assumed), but #' we have found this format can lead to query failures. #' \emph{\strong{ #' In this program the string is always returned in format (2): #' \code{<year>.<day>T<hour>:<min>:<sec>} #' }} #' #' \code{sec} may be fractional, but is formatted with \code{\link{sprintf}} #' (\code{02.06f}) so #' values less than 1 microsecond will be truncated (\emph{not} rounded). #' #' Note that IRIS WS accepts values for hour, minute, and second which are less #' than 100. Return data will have times adjusted to account for values in excess of #' the normal limits (i.e., 24, 60, 60). #' #' The functionality of \code{\link{ISOdatetime.j}} is roughly equivalent to #' \code{\link{ISOdatetime}}, but is somewhat more flexible. #' #' @param year numeric; the \emph{full} year A.D. (e.g., 2012 \emph{not} 12) #' @param day numeric; the day, either of-the-year, or of-the-month (see \code{month}) #' @param hour numeric; the hour of the day (less than 100) #' @param min numeric; the minute (less than 100) #' @param sec numeric; fractional seconds (less than 100; will be truncated to 6 decimal places) #' @param month numeric; the month of the year. #' If this is \code{NULL} then \code{day} is assumed #' to be the Julian day of year. #' @param tz character; the timezone #' @param tstr character; an alternative wat of specifying a datetime, #' e.g., \code{"2012.350T32:12:12.222000"}. See details. #' #' @name irisws-timeutilities #' @author AJ Barbour #' @references [1] \url{http://service.iris.edu/irisws/timeseries/1/} #' #' @seealso #' \code{\link{irisws-package}} #' #' @family Utilities #' #' @examples #' \dontrun{ #' # #' # Specify the month #' timestring(2012, 15, 32, 12, 12.222, month=12) #' # [1] "2012.350T32:12:12.222000" #' # #' # or not #' timestring(2012, 15, 32, 12, 12.222) #' # [1] "2012.015T32:12:12.222000" #' # #' # some errors: #' try(timestring(2012, 15, 32, 100, 12.222)) # min too large #' try(timestring(2012, 75755, 32, 12, 12.222)) # day too large #' try(timestring(2012, 15, 32, 100, 12.222, 13)) # month too large #' # etc... #' # #' ISOdatetime.j(tstr=timestring(2010,111,sec=0.12123)) #' # or use the wrapper #' ISOtimestring(timestring(2010,111,sec=0.12123)) #' } NULL #' @rdname irisws-timeutilities #' @export timestring <- function(year, day, hour=0, min=0, sec=0.0, tz = "UTC", month=NULL){ # #stopifnot(length(c(year, day, hour, min, sec, month)) <= 6 ) hour <- as.numeric(hour) min <- as.numeric(min) sec <- as.numeric(sec) irislim <- 100 if (any(c(sec, min, hour) >= irislim)){ stop(paste("IRISWS requires that 'sec', 'min', and 'hour all be less than", irislim)) } # if (is.null(month)){ # day is julian-day nd <- as.numeric(strftime(sprintf("%04i-12-31",year),"%j", tz=tz)) stopifnot(day <= nd) yjd <- sprintf("%04i.%03i", year, day) } else { # day is month-day stopifnot(month <= 12 & day <= 31) yjd <- strftime(sprintf("%04i-%02i-%02i", year, month, day), "%Y.%j", tz=tz) } isec <- floor(sec) rsec <- signif(sec - isec, 5) tstr <- sprintf("%sT%02i:%02i:%02i.%06i", yjd, hour, min, isec, 1e6*rsec) return(tstr) } #' @rdname irisws-timeutilities #' @export ISOtimestring <- function(tstr, tz="UTC"){ ISOdatetime.j(tstr=tstr, tz=tz) } #' @rdname irisws-timeutilities #' @export ISOdatetime.j <- function(year, day, hour=0, min=0, sec=0.0, tz = "UTC", month=NULL, tstr=NULL) { # #op <- options(digits.secs=6) #on.exit(options(op)) # no.tstr <- is.null(tstr) no.year <- missing(year) no.day <- missing(day) # do.tstr <- no.year & no.day & !no.tstr # if (do.tstr){ #x <- gsub("T", "-", paste(tstr)) # not necessary (just replace - with T in fmt) x <- paste(tstr) fmt <- "%Y.%jT%H:%M:%OS" } else { no.month <- is.null(month) if (no.month){ x <- paste(year, day, hour, min, sec, sep = "-") fmt <- "%Y-%j-%H-%M-%OS" } else { x <- paste(year, month, day, hour, min, sec, sep = "-") fmt <- "%Y-%m-%d-%H-%M-%OS" } } stopifnot(exists('fmt') & exists('x')) as.POSIXct(strptime(x, format=fmt, tz = tz), tz = tz) }
0c396707e12a2e27571906350311830fad65aa0a
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/QCApro/examples/findTh.Rd.R
53cc3a37886e78cf34709ec8820f0a45e7145611
[]
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
311
r
findTh.Rd.R
library(QCApro) ### Name: findTh ### Title: Find Calibration Thresholds ### Aliases: findTh ### Keywords: functions ### ** Examples # 15 random values between 1 and 100 x <- sample(1:100, size = 15) # split into two groups for csQCA findTh(x) # split into three groups for mvQCA findTh(x, groups = 3)
20259811b7bb82b3d3b496d39277592826db18cd
3ed4722997fe6e01b014879d2646f451dbf8e4a5
/014-R/moritz.R
2936c3ce84660dbe33f448c3341fd5f83e0fe94a
[]
no_license
ChristerNilsson/2020
7a83efd778dea37262174a4796cb9a2e5a0cd586
e6d22f9d7ce99f287ea374631eaf4bec1a36056c
refs/heads/master
2023-01-12T02:56:33.367492
2020-11-17T20:39:05
2020-11-17T20:39:05
298,788,667
0
0
null
null
null
null
UTF-8
R
false
false
670
r
moritz.R
# if (!requireNamespace("BiocManager", quietly = TRUE)) # install.packages("BiocManager") setwd(file.path("/Lab/2020/014-R")) # BiocManager::install("infercnv") library(infercnv) infercnv_obj = readRDS('run.final.infercnv_obj') # ?plot_cnv # apply median filtering adding on to the one before infercnv_obj_medianfiltered = infercnv::apply_median_filtering(infercnv_obj) infercnv::plot_cnv(infercnv_obj_medianfiltered, #out_dir= o.dir, output_filename='infercnv.median_filtered', x.range="auto", x.center=1, title = "infercnv", color_safe_pal = FALSE)
064db3e901e1a85c1185bd54fdfbf7af907070fa
6bef9d7657a42a76d01fd7b6e6ffac51dd3f4256
/man/iana-package.Rd
26faea2728faa8030fedeaa10f283e0fc2fcdd92
[]
no_license
mihock/iana
131deacf848593ffe831bdaa7e245b6d38f0e4ed
ae6f881a48f250280cef99446bbe3cbebd14ea56
refs/heads/master
2022-09-04T00:26:09.067272
2022-08-29T13:58:31
2022-08-29T13:58:31
11,193,882
0
1
null
null
null
null
UTF-8
R
false
true
2,201
rd
iana-package.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/itemanalysis.R \docType{package} \name{iana-package} \alias{iana-package} \alias{iana} \title{GUI for Item Analysis and Scale Construction} \description{ Iana is a browser-based GUI for classical item and test analysis, factor analysis, and item response modeling with a focus on items with an ordered-category response format. } \details{ Iana is a browser-based graphical user interface to R functions for the psychometric analysis of questionnaires and tests with an ordinal response format. Iana tries to integrate the essential statistical analysis steps into a convenient interface. Iana covers classical item and test analysis (reliability, item discrimation), dimensionality tests (parallel analysis and MAP test), principal components and exploratory factor analysis (including factor analysis based on polychoric correlations), one-factor confirmatory analysis, and item response models (partial credit model). Graphical output includes histograms of item and test scores, empirical item characteric curves, and person-item maps, among others. Iana is based on the \href{http://www.rstudio.com/shiny/}{Shiny Web Framework for R}, which allows a fast bidirectional communication between the browser and R. Iana is "reactive", meaning that its output is instantly updated if any of the inputs (e.g., the selected variables) are changed by the user. This makes it easy to compare the impact of item selection and/or modeling options on the results. Iana keeps track of the R commands it constructs as a response to user input, so the analysis steps are documented and can be replicated. Iana comes with some built-in data sets, with which the interface can be tested. However, other data can easily be used. The basic usage is documented in \code{\link{runiana}}. \tabular{ll}{ Package: \tab iana\cr Type: \tab Package\cr Version: \tab 0.1\cr Date: \tab 2019-06-10\cr License: \tab GPL (>= 2)\cr LazyLoad: \tab yes\cr } } \examples{ \dontrun{runiana()} } \references{ Shiny web framework for R: \url{http://www.rstudio.com/shiny/} } \author{ Michael Hock (\email{michael.hock@uni-bamberg.de}) } \keyword{package}
6fa259ef1429da8dc64fadc7b443fc328dbf6e57
823cae650090d7ffda822d708b674286d7317228
/TCGA_Project/Mutation_Correction/Mutation-Correction.R
0f959bbb58911ec57243ef1c24ed1fc2b4062f75
[]
no_license
JiFansen/JiFansen_CentOS
f1ff6f2b97d3d6629d558b497f137b5b87a43bac
4cdc22a7d28dfa24ca53a7540e4db7ea9c74ad45
refs/heads/master
2020-04-11T10:49:25.437139
2018-12-15T08:34:38
2018-12-15T08:34:38
161,727,352
0
0
null
null
null
null
UTF-8
R
false
false
5,422
r
Mutation-Correction.R
w <- 1 for(file in list.files('/Share/home/JiFansen/JiFansen/Mutation-Correction/Background/New-196-Mutation-Signature-Calculation/')){ tmp <- read.table(file = paste0('/Share/home/JiFansen/JiFansen/Mutation-Correction/Background/New-196-Mutation-Signature-Calculation/', file), header = T, sep = '\t', row.names = 1) colnames(tmp) <- unlist(strsplit(file,'\\.'))[1] if(w==1){ background <- tmp w <- w+1 }else{ background <- cbind.data.frame(background, tmp) } } sampleNumber <- c() w <- 1 for(file in list.files('/Share/home/JiFansen/JiFansen/Mutation-Correction/MAF-summary/', pattern = '.barcode.txt')){ cancertype <- unlist(strsplit(file, '-'))[1] print(cancertype) tmp <- read.table(file = paste0('/Share/home/JiFansen/JiFansen/Mutation-Correction/MAF-summary/', file), header = T, sep = '\t') tmp$cancertype <- cancertype sample.barcode <- substr(as.character(tmp$Tumor_Sample_Barcode), 1, 16) sampleNumber <- c(sampleNumber, length(unique(sample.barcode))) if(w==1){ data.initial <- tmp w <- w+1 }else{ data.initial <- rbind.data.frame(data.initial, tmp) w <- w+1 } } total.background <- as.matrix(apply(background, 1, FUN = function(x){return(sum(x*sampleNumber))})) write.table(total.background, file = '/Share/home/JiFansen/JiFansen/Mutation-Correction/Correction/total-cancertype-background.txt', sep = '\t', quote = FALSE, col.names = FALSE) data.initial <- data.initial[which(data.initial$Variant_Classification=='Missense_Mutation'),] match.result <- match(as.character(data.initial$change), rownames(total.background)) data.initial$true.value <- as.numeric(total.background[,1])[match.result] data.initial$count <- 1 data.summary <- aggregate(x = data.initial[,13:14], by = list(data.initial$gene, data.initial$Protein_position), FUN = sum) data.summary$absolute <- data.summary$true.value/data.summary$count write.table(data.summary, file = '/Share/home/JiFansen/JiFansen/Mutation-Correction/Correction/Gene-Count-TrueValue.txt', sep = '\t', quote = FALSE, row.names = FALSE) uniq.gene <- unique(as.character(data.summary$Group.1)) w <- 1 for(genename in uniq.gene){ tmp <- data.summary[which(data.summary$Group.1==genename),] tmp$scale <- (tmp$absolute-min(tmp$absolute))/(max(tmp$absolute)-min(tmp$absolute)) if(w == 1){ score.correction <- tmp w <- w+1 }else{ score.correction <- rbind.data.frame(score.correction, tmp) } } sig.genes <- read.table(file = '/Share/home/JiFansen/JiFansen/Mutation-Correction/Background/Cancertype/New-Overlap.txt', header = F, sep = '\t') sig.genes <- as.character(sig.genes[,1]) match.result <- match(as.character(score.correction$Group.1), sig.genes) sig.index <- which(is.na(match.result)==FALSE) score.correction.sig <- score.correction[sig.index, ] write.table(score.correction.sig, file = '/Share/home/JiFansen/JiFansen/Mutation-Correction/Correction/Total-Codon-Score.txt', sep = '\t', quote = FALSE, row.names = FALSE) gene.codon <- paste0(as.character(score.correction.sig$Group.1), '-', as.character(score.correction.sig$Group.2)) for(file in list.files('/Share/home/JiFansen/JiFansen/Mutation-Correction/MAF-summary/', pattern = '.barcode.txt')){ cancertype <- unlist(strsplit(file, '-'))[1] tmp <- read.table(file = paste0('/Share/home/JiFansen/JiFansen/Mutation-Correction/MAF-summary/', file), header = T, sep = '\t') tmp <- tmp[which(tmp$Variant_Classification=='Missense_Mutation'), ] tmp$cancertype <- cancertype sample.barcode <- substr(as.character(tmp$Tumor_Sample_Barcode), 1, 16) tmp$Tumor_Sample_Barcode <- sample.barcode tmp.gene.codon <- paste0(as.character(tmp$gene), '-',as.character(tmp$Protein_position)) match.result <- match(tmp.gene.codon, gene.codon) big.index <- which(is.na(match.result)==FALSE) small.index <- match.result[big.index] tmp.sig <- tmp[big.index,] tmp.sig$score <- score.correction.sig$scale[small.index] tmp.sig <- tmp.sig[,c(1,10,13)] frameshift <- read.table(file = paste0('/Share/home/JiFansen/JiFansen/Mutation-Correction/Frameshift/', cancertype, '-shift.txt-New'), header = T, sep = '\t', stringsAsFactors = FALSE) frameshift <- t(frameshift) colnames(frameshift) <- as.character(frameshift[1,]) frameshift <- frameshift[-c(1,2),] frameshift <- frameshift[-nrow(frameshift),] frameshift <- as.data.frame(frameshift) for(m in 1:dim(frameshift)[1]){ index <- which(as.numeric(as.matrix(frameshift[m,]))>0) frame.tmp <- data.frame(gene = rownames(frameshift)[m], Tumor_Sample_Barcode = colnames(frameshift)[index], score = 0) tmp.sig <- rbind.data.frame(tmp.sig, frame.tmp) } Sample.uniq <- unique(as.character(tmp.sig$Tumor_Sample_Barcode)) p <- 1 for(i in Sample.uniq){ gene.score <- c() test.1 <- tmp.sig[which(tmp.sig$Tumor_Sample_Barcode==i),] Gene.uniq <- unique(as.character(test.1$gene)) for(j in Gene.uniq){ test.2 <- test.1[which(test.1$gene==j),] gene.score <- c(gene.score,prod(as.numeric(test.2$score))) } result <- data.frame(sample = i, gene = Gene.uniq, score = gene.score) if(p==1){ result.cancertype <- result p <- p+1 }else{ result.cancertype <- rbind.data.frame(result.cancertype, result) } } write.table(result.cancertype, file = paste0('/Share/home/JiFansen/JiFansen/Mutation-Correction/Correction/', cancertype, '-Score-Correction.txt'), sep = '\t', quote = FALSE, row.names = FALSE) }
0813e191f612f6488f019fa4c474816ece730413
d26b1b446e18850cae39119828067d21a5079acd
/R/DEVarSelect.R
70ad75dbcb5eee8ce4b77d69266916a3ebbc2380
[]
no_license
ziyili20/TOAST
c623dcb2c64a89f00f84fddfab759da62d6434a5
102b6b1fa801561976b070adf1e15378bde43f76
refs/heads/master
2022-08-31T11:28:40.598741
2022-08-24T19:35:31
2022-08-24T19:35:31
145,612,563
12
4
null
2021-07-20T06:07:43
2018-08-21T19:53:08
R
UTF-8
R
false
false
1,403
r
DEVarSelect.R
DEVarSelect <- function(Y_raw, Prop0, nMarker = 1000, bound_negative = FALSE){ if (is(Y_raw, "SummarizedExperiment")) { se <- Y_raw Y_raw <- assays(se)$counts } else if (!is(Y_raw, "matrix")) { stop("Y_raw should be a matrix or a SummarizedExperiment object!") } if (nrow(Prop0) < ncol(Prop0)) { stop("Prop0 should have dimension N (samples) by K (cell types)!") } if (!ncol(Y_raw) == nrow(Prop0)) { stop("Y_raw should have dimension P (features) by N (samples)!") } K <- ncol(Prop0) N_sample <- nrow(Prop0) ## find tissue specific genes idx <- NULL for(k in seq_len(K)) { cvec <- rep(-1/(K-1),K) cvec[k] <- 1 design <- rep(0,N_sample) tmp <- DEKTissue(K, Y=Y_raw, Prop=Prop0, design=design, contrast_vec=cvec, bound_negative=bound_negative) idx[[k]] <- sort(abs(tmp$t_stat), decreasing=TRUE, index=TRUE)$ix } nmarker <- nMarker ## number of markers per tissue. Consider overlaps nmarker_tissue <- nmarker/K * 1.2 idxMarker <- NULL for(k in seq_len(K)) { idxMarker <- c(idxMarker, idx[[k]][seq_len(nmarker_tissue)]) } idxMarker <- unique(idxMarker) return(idxMarker) }
fb79ab3a1a101233a14bde322c9c55fb2511108a
046f9a3127441ccaa03e6f644996ac78f30f0f37
/NDE1snps-exp-finns.R
f205654ae5a68c9e1c9b75857481011c171104ea
[]
no_license
amandazheutlin/misc_scripts
07bcdedbdb4391caf5968844ad92300a7efdbddc
0789d17ea48e0a345d45d7e645dcf785eb32014a
refs/heads/master
2021-01-15T11:03:49.421125
2017-08-07T20:48:38
2017-08-07T20:48:38
99,610,768
0
0
null
null
null
null
UTF-8
R
false
false
10,370
r
NDE1snps-exp-finns.R
# check 2 SNPs in NDE1 against genome-wide gene expression # Finnish twins # load data, libraries libs <- c("nlme","dplyr") invisible(lapply(libs, require, character.only = TRUE)) workDir <- "/data/swe_gwas/ABZ/NDE1/" setwd(workDir) load("finlandclean.rdata") colnames(finlandclean)[2:18567] <- colnames(finlandclean)[1:18566] finlandclean <- finlandclean[,2:18567] demo <- read.table("demo_finns.txt",header=T,stringsAsFactors = F) demo$age <- as.numeric(demo$age) finlandclean$age2 <- demo[match(finlandclean$Persnb,demo$pid),6] geno <- read.table("NDE1.ped",header=F,sep="\t") geno <- geno[,c(1:2,7:8)] names(geno) <- c("FID","IID","rs2242549","rs1050162") # update finlandclean FIDs that are missing! # USE FID NOT PAIRNB finlandclean$FID <- geno[match(finlandclean$Persnb, geno$IID),1] %>% as.character # snps = rs2242549 (snp1), rs1050162 (snp2) # snps were coded 1 1, 1 2, 2 2; 1 = minor; 2 = major # minor allele = G (snp1), C (snp2); major allele = T (both) # additive = 1, 2, 3 # recessive = 1, 2, 2 (name = rs rec) # dominant = 1, 1, 2 (name = rs dom) NDE1 <- finlandclean NDE1$rs2242549 <- geno[match(NDE1$Persnb,geno$IID),3] NDE1$rs2242549rec <- NDE1$rs2242549 NDE1$rs2242549dom <- NDE1$rs2242549 NDE1$rs1050162 <- geno[match(NDE1$Persnb,geno$IID),4] NDE1$rs1050162rec <- NDE1$rs1050162 NDE1$rs1050162dom <- NDE1$rs1050162 NDE1$rs2242549 <- ifelse(NDE1$rs2242549=="1 1", 1, ifelse(NDE1$rs2242549=="1 2",2,3)) # N(1,2,3) = 6,38,26 NDE1$rs2242549rec <- ifelse(NDE1$rs2242549rec=="1 1", 1, 2) # N(1,2) = 6,64 NDE1$rs2242549dom <- ifelse(NDE1$rs2242549dom=="2 2", 2, 1) # N(1,2) = 44,26 NDE1$rs1050162 <- ifelse(NDE1$rs1050162=="1 1", 1, ifelse(NDE1$rs1050162=="1 2",2,3)) # N(1,2,3) = 10,37,23 NDE1$rs1050162rec <- ifelse(NDE1$rs1050162rec=="1 1", 1, 2) # N(1,2) = 10,60 NDE1$rs1050162dom <- ifelse(NDE1$rs1050162dom=="2 2", 2, 1) # N(1,2) = 47,23 genes <- names(NDE1)[8:18566] # 18,559 markers ####################################### residual values for all genes # effects of sex, diagnosis ('Analysis'), and age (use 'age2') # Analysis = case/co-twin/control df <- NDE1[complete.cases(NDE1$age2),] df <- df[complete.cases(df$rs2242549),] residuals <- lapply(genes, function(x) { lm(eval(substitute(i ~ Sex + Analysis + age2, list(i = as.name(x)))), data = df, na.action = na.omit) }) res_vals <- lapply(residuals, function(x) residuals(x)) %>% as.data.frame() resdf <- cbind(df[,c(1,18568,18569,18571,18572,18574)],res_vals) names(resdf) <- c("IID","FID","rs2242549","rs2242549dom", "rs1050162","rs1050162dom",genes) ####################################### snps x expression (residuals) # effect of snp on all genes (N = 18,559 genes) # residual values excluding effects of sex, diagnosis ('Analysis') # random effect = family # using lmeControl to deal with convergence issues ######################################################### # snp1 - additive model models_snp1 <- lapply(genes, function(x) { lme(eval(substitute(i ~ rs2242549, list(i = as.name(x)))), random = ~1|FID, data = resdf, na.action = na.omit, control=lmeControl(returnObject=T, opt="optim")) }) # stats model_stats_snp1 <- lapply(models_snp1, function(x) summary(x)$tTable) # naming genes getResponse <- function(formula) { tt <- summary(formula)$terms vars <- as.character(attr(tt, "variables"))[-1] ## [1] is the list call response <- attr(tt, "response") # index of response var vars[response] } # list of overall effects snp1 = NULL for (i in 1:18559) { temp <- as.data.frame(model_stats_snp1[[i]]) temp$marker <- getResponse(models_snp1[[i]]) snp1 <- rbind(snp1,temp[2,]) } colnames(snp1)[4:5] <- c("tvalue","pvalue") snp1 <- snp1[order(snp1$pvalue),] write.table(snp1,"RNA-GWAS-snp1-add-res-agecov-june16.txt", sep="\t",col.names=T,row.names=F,quote=F) rm(models_snp1) rm(model_stats_snp1) rm(snp1) ######################################################### # snp1 - dominant model models_snp1dom <- lapply(genes, function(x) { lme(eval(substitute(i ~ rs2242549dom, list(i = as.name(x)))), random= ~1|FID, data = resdf, na.action = na.omit, control=lmeControl(returnObject=T, opt="optim")) }) # stats model_stats_snp1dom <- lapply(models_snp1dom, function(x) summary(x)$tTable) # list of overall effects snp1_dom = NULL for (i in 1:18559) { temp <- as.data.frame(model_stats_snp1dom[[i]]) temp$marker <- getResponse(models_snp1dom[[i]]) snp1_dom <- rbind(snp1_dom,temp[2,]) } colnames(snp1_dom)[4:5] <- c("tvalue","pvalue") snp1_dom <- snp1_dom[order(snp1_dom$pvalue),] write.table(snp1_dom,"RNA-GWAS-snp1-dom-res-agecov-june16.txt", sep="\t",col.names=T,row.names=F,quote=F) rm(models_snp1dom) rm(model_stats_snp1dom) rm(snp1_dom) ######################################################### # snp2 - additive model models_snp2 <- lapply(genes, function(x) { lme(eval(substitute(i ~ rs1050162, list(i = as.name(x)))), random= ~1|FID, data = resdf, na.action = na.omit, control=lmeControl(returnObject=T, opt="optim")) }) # stats model_stats_snp2 <- lapply(models_snp2, function(x) summary(x)$tTable) # list of overall effects snp2 = NULL for (i in 1:18559) { temp <- as.data.frame(model_stats_snp2[[i]]) temp$marker <- getResponse(models_snp2[[i]]) snp2 <- rbind(snp2,temp[2,]) } names(snp2)[4:5] <- c("tvalue","pvalue") snp2 <- snp2[order(snp2$pvalue),] write.table(snp2,"RNA-GWAS-snp2-add-res-agecov-june16.txt", sep="\t",col.names=T,row.names=F,quote=F) rm(models_snp2) rm(model_stats_snp2) rm(snp2) ######################################################### # snp2 - dominant model models_snp2dom <- lapply(genes, function(x) { lme(eval(substitute(i ~ rs1050162dom, list(i = as.name(x)))), random= ~1|FID, data = resdf, na.action = na.omit, control=lmeControl(returnObject=T, opt="optim")) }) # stats model_stats_snp2dom <- lapply(models_snp2dom, function(x) summary(x)$tTable) # list of overall effects snp2_dom = NULL for (i in 1:18559) { temp <- as.data.frame(model_stats_snp2dom[[i]]) temp$marker <- getResponse(models_snp2dom[[i]]) snp2_dom <- rbind(snp2_dom,temp[2,]) } names(snp2_dom)[4:5] <- c("tvalue","pvalue") snp2_dom <- snp2_dom[order(snp2_dom$pvalue),] write.table(snp2_dom,"RNA-GWAS-snp2-dom-res-agecov-june16.txt", sep="\t",col.names=T,row.names=F,quote=F) rm(models_snp2dom) rm(model_stats_snp2dom) rm(snp2_dom) ########################################################### # tvab famID <- unique(df$FID) twin1 <- df[!duplicated(df$FID),] twin2 <- df[!(df$Persnb %in% twin1$Persnb),] ########################################################### ########################################################### ####################################### snps x expression # effect of snp on all genes (N = 18,559 genes) # covar = sex, diagnosis ('Analysis') # random effect = family # Analysis = case/co-twin/control # ######################################################### # # snp1 - additive model # models_snp1 <- lapply(genes, function(x) { # lme(eval(substitute(i ~ rs2242549 + Sex + Analysis, list(i = as.name(x)))), # random = ~1|Pairnb, data = NDE1, na.action = na.omit) # }) # # # stats # model_stats_snp1 <- lapply(models_snp1, function(x) summary(x)$tTable) # # # naming genes # getResponse <- function(formula) { # tt <- summary(formula)$terms # vars <- as.character(attr(tt, "variables"))[-1] ## [1] is the list call # response <- attr(tt, "response") # index of response var # vars[response] # } # # # list of overall effects # snp1 = NULL # for (i in 1:18559) { # temp <- as.data.frame(model_stats_snp1[[i]]) # temp$marker <- getResponse(models_snp1[[i]]) # snp1 <- rbind(snp1,temp[2,]) # } # # colnames(snp1)[4:5] <- c("tvalue","pvalue") # snp1 <- snp1[order(snp1$pvalue),] # # write.table(snp1,"RNA-GWAS-finns-snp1-add.txt", # sep="\t",col.names=T,row.names=F,quote=F) # # ######################################################### # # snp1 - recessive model # models_snp1rec <- lapply(genes, function(x) { # lme(eval(substitute(i ~ rs2242549rec + Sex + Analysis, list(i = as.name(x)))), # random= ~1|Pairnb, data = NDE1, na.action = na.omit) # }) # # # stats # model_stats_snp1rec <- lapply(models_snp1rec, function(x) summary(x)$tTable) # # # list of overall effects # snp1_rec = NULL # for (i in 1:18559) { # temp <- as.data.frame(model_stats_snp1rec[[i]]) # temp$marker <- getResponse(models_snp1rec[[i]]) # snp1_rec <- rbind(snp1_rec,temp[2,]) # } # # colnames(snp1_rec)[4:5] <- c("tvalue","pvalue") # snp1_rec <- snp1_rec[order(snp1_rec$pvalue),] # # write.table(snp1_rec,"RNA-GWAS-finns-snp1-rec.txt", # sep="\t",col.names=T,row.names=F,quote=F) # # ######################################################### # # snp2 - additive model # models_snp2 <- lapply(genes, function(x) { # lme(eval(substitute(i ~ rs1050162 + Sex + Analysis, list(i = as.name(x)))), # random= ~1|Pairnb, data = NDE1, na.action = na.omit) # }) # # # stats # model_stats_snp2 <- lapply(models_snp2, function(x) summary(x)$tTable) # # # list of overall effects # snp2 = NULL # for (i in 1:18559) { # temp <- as.data.frame(model_stats_snp2[[i]]) # temp$marker <- getResponse(models_snp2[[i]]) # snp2 <- rbind(snp2,temp[2,]) # } # # names(snp2)[4:5] <- c("tvalue","pvalue") # snp2 <- snp2[order(snp2$pvalue),] # # write.table(snp2,"RNA-GWAS-finns-snp2-add.txt", # sep="\t",col.names=T,row.names=F,quote=F) # # ######################################################### # # snp2 - recessive model # models_snp2rec <- lapply(genes, function(x) { # lme(eval(substitute(i ~ rs1050162rec + Sex + Analysis, list(i = as.name(x)))), # random= ~1|Pairnb, data = NDE1, na.action = na.omit) # }) # # # stats # model_stats_snp2rec <- lapply(models_snp2rec, function(x) summary(x)$tTable) # # # list of overall effects # snp2_rec = NULL # for (i in 1:18559) { # temp <- as.data.frame(model_stats_snp2rec[[i]]) # temp$marker <- getResponse(models_snp2rec[[i]]) # snp2_rec <- rbind(snp2_rec,temp[2,]) # } # # names(snp2_rec)[4:5] <- c("tvalue","pvalue") # snp2_rec <- snp2_rec[order(snp2_rec$pvalue),] # # write.table(snp2_rec,"RNA-GWAS-finns-snp2-rec.txt", # sep="\t",col.names=T,row.names=F,quote=F) #
a40843550c5015c533820d5f8734add8d0fb3d6b
3ae1e8d5bccc46c43b26e01d66192aa271880e6f
/R/alignCurves.R
3f891b83095450ec7350b7e913a3d8c8c350ddd0
[]
no_license
oliviertastet/eaeCurves
ff587b7b8a32b9c9db5a7d131e3a5571171d6348
ecddce643e5c7adca8c24d976d73783389fc90ad
refs/heads/master
2022-06-20T06:55:29.925997
2020-05-14T13:17:49
2020-05-14T13:17:49
263,908,916
0
0
null
null
null
null
UTF-8
R
false
false
2,441
r
alignCurves.R
#' Align the curves #' #' @param data Do you love cats? Defaults to TRUE. #' @param days Do you love cats? Defaults to TRUE. #' @param k Do you love cats? Defaults to TRUE. #' @keywords alignCurves #' @examples #' alignCurves() #' @export alignCurves<-function(data, days = 1:263, k=3, n=5){ title='Mean clinical score' m=melt(data[,c('condition','sex','souris',days)],id.vars=c('condition','sex','souris')) m=na.omit(m) m$key = paste(m$souris,m$sex,m$condition,m$variable,sep='.') m$souris.id = paste(m$souris,m$sex,m$condition,sep='.') vec=c() ages = c() vars = c() sums=c() m=m[!duplicated(m$key),] m=m[order(m$souris.id,m$variable),] for(mouse in unique(m$souris.id)){ sub = subset(m, souris.id==mouse) sick = F check = T for(day in unique(as.character(sub$variable))){ if(check){ if(is.na(sub[which(sub$variable==day),'value'])){ if(!is.na(sub[which(sub$variable==as.character(as.numeric(day)+1)),'value'])){ sub[which(sub$variable==day),'value']=0 } } if(sub[which(sub$variable==day),'value']>0){ ages=c(ages,day) sick=T check=F vec[(length(vec)-n):(length(vec))]=1 } } if(sick){ vec=c(vec,1) }else{ vec=c(vec,0) } } } m$sick = vec m.sick=subset(m, sick==1) m.sick$variable=as.numeric(as.character(m.sick$variable)) df=data.frame(matrix(ncol=264)) m.sick$souris.id=paste(m.sick$souris,m.sick$sex,m.sick$condition,sep='.') for(mouse in unique(m.sick$souris.id)){ vec=rep(NA,264) names(vec)=1:263 colnames(df)=names(vec) sub = subset(m.sick, souris.id==mouse) sums=c(sums, sum(as.numeric(sub$value))) vars=c(vars, var(as.numeric(sub$value))) sub$variable=(sub$variable-min(sub$variable))+1 vec[sub$variable]=sub$value df=rbind(df,vec) } df=df[2:nrow(df),] df=data.frame(cbind(unique(m.sick$souris.id),df)) colnames(df)=gsub('X','',colnames(df)) df$souris = unlist(strsplit(as.character(df[,1]),'\\.'))[seq(1,nrow(df)*3,3)] df$sex = unlist(strsplit(as.character(df[,1]),'\\.'))[seq(2,nrow(df)*3,3)] df$condition = unlist(strsplit(as.character(df[,1]),'\\.'))[seq(3,nrow(df)*3,3)] df=df[,c('souris','sex','condition',1:263)] df$max_score = as.numeric(apply(df[,4:266],1,FUN=max,na.rm=T)) df$age.at.onset = ages rownames(df)=paste(df[,1],df[,2],df[,3],sep='.') hc=hclust(dist(df[,as.character(1:263)])) df$cluster = cutree(hc,k=k) df$var = vars df$score_sum=sums #df[is.na(df)]=5 df }
6ab3926c9b04a3eb48aea62329581c0dbc12ee46
beaa721938b098c82ab768f01ad858487c32f59d
/report/miss_sent_report.R
2249c864e10fd490c81f31f3274b1e92d196d575
[]
no_license
RanaivosonHerimanitra/Sentinel
3f354256fb26cc0d1b6ea77caf8395ab82539268
9393d2f69369110bd78e3cd080d4bcd72e664b76
refs/heads/master
2020-12-29T02:22:04.597292
2017-04-08T22:55:26
2017-04-08T22:55:26
50,108,349
10
1
null
null
null
null
UTF-8
R
false
false
5,390
r
miss_sent_report.R
#setwd("/media/herimanitra/Document/IPM_sentinelle/sentinel_hrmntr 291115/Sentinel") ###############################Missing sent report ############################ library(ReporteRs); #require(Hmisc) doc <- docx() path1="/media/herimanitra/Document/IPM_sentinelle/sentinel_hrmntr 291115/Sentinel/report/logo.png" path2="/srv/shiny-server/sentinel_hrmntr/Sentinel/report/logo.png" mylogo=ifelse(file.exists(path1),path1,path2) doc=addImage(doc, mylogo, par.properties = parProperties(text.align = "left", padding = 5), width=5, height=1.5) # Change the default font size and font family options('ReporteRs-fontsize'=10, 'ReporteRs-default-font'='Arial') # Add a formatted paragraph of texts: doc = addTitle(doc, "Sms hebdomadaire du réseau sentinelle", level=1) doc = addParagraph(doc , pot( Sys.Date(), textItalic() ) ) doc = addParagraph(doc, " ") baseCellProp = cellProperties( padding = 2 ) vertical_text= cellProperties(text.direction = "btlr", padding = 2) horizontal_text= cellProperties(text.direction = "lrtb", padding = 2) cat("load data and preprocess missing sent...") require(data.table) path1="/media/herimanitra/Document/IPM_sentinelle/sentinel_hrmntr 291115/Sentinel/data/missing_sent.csv" path2="/srv/shiny-server/sentinel_hrmntr/Sentinel/data/missing_sent.csv" myfile=ifelse(file.exists(path1),path1,path2) missing_sent= fread(myfile) missing_sent[,code:=paste0(substr(Annee,3,4),"/",ifelse(nchar(Semaine)<2,paste0("0",Semaine),Semaine))] cat("DONE\n") cat("crosstabulation of weeks and Sites...") #missing_sent[,Centre:=capitalize(tolower(Centre))] missing_sent[,Centre:=(tolower(Centre))] X=table(missing_sent$code,missing_sent$Centre) cat("DONE\n") cat("Add Semaine épidémiologique...") X=cbind(Semaine=row.names(X),X) cat("DONE\n") cat("load sentinel lat/long define 34sites vs other...") path1="/media/herimanitra/Document/IPM_sentinelle/sentinel_hrmntr 291115/Sentinel/data/sentinel.csv" path2="/srv/shiny-server/sentinel_hrmntr/Sentinel/data/sentinel.csv" myfile=ifelse(file.exists(path1),path1,path2) sentinel_latlong = fread(myfile) sites34 = which( tolower(colnames(X)) %in% tolower(c("CSBU MANANJARY MNJ", "TSIMADILO", sentinel_latlong$centre) )) other_site =which( !( tolower(colnames(X)) %in% tolower(c("CSBU MANANJARY MNJ", "TSIMADILO", sentinel_latlong$centre)) )) cat("DONE\n") cat("divide data into 03 parts...") #X=table(missing_sent$code,missing_sent$Centre) X1=X[,c(1,sites34[1:15])] X2=X[,c(1,sites34[16:33])] #select only period where data collection has begun X3=X[95:nrow(X),other_site[1:10]] X4=X[95:nrow(X),c(1,other_site[11:length(other_site)])] cat("DONE\n") #vertical test for headers mytable1 = vanilla.table(X1,text.direction = "btlr") mytable2 = vanilla.table(X2,text.direction = "btlr") mytable3 = vanilla.table(X3,text.direction = "btlr") mytable4 = vanilla.table(X4,text.direction = "btlr") #loop through columns and change into red those cells with value <4: #First line in vertical order for ( k in 2:ncol(X1) ) { cat(k,"\n") mytable1[as.numeric(X1[,k]) >= 4, k] = textProperties( font.size = 10) mytable1[as.numeric(X1[,k]) < 4, k] = textProperties( color="#FF3333",font.size = 10) } for ( k in 2:ncol(X2) ) { cat(k,"\n") mytable2[as.numeric(X2[,k]) >= 4, k] = textProperties( font.size = 10) mytable2[as.numeric(X2[,k]) < 4, k] = textProperties( color="#FF3333",font.size = 10) } for ( k in 2:ncol(X3) ) { cat(k,"\n") mytable3[as.numeric(X3[,k]) >= 4, k] = textProperties( font.size = 10) mytable3[as.numeric(X3[,k]) < 4, k] = textProperties( color="#FF3333",font.size = 10) } for ( k in 2:ncol(X4) ) { cat(k,"\n") mytable4[as.numeric(X4[,k]) >= 4, k] = textProperties( font.size = 10) mytable4[as.numeric(X4[,k]) < 4, k] = textProperties( color="#FF3333",font.size = 10) } cat("Writing document to a word document...") mytable1 = addFooterRow( mytable1, value = c("En rouge , les cas <4"), cell.properties = horizontal_text ,colspan = ncol(X1)) mytable2 = addFooterRow( mytable2, value = c("En rouge , les cas <4"), cell.properties = horizontal_text ,colspan = ncol(X2)) mytable3 = addFooterRow( mytable3, value = c("En rouge , les cas <4"), cell.properties = horizontal_text ,colspan = ncol(X3)) mytable4 = addFooterRow( mytable4, value = c("En rouge , les cas <4"), cell.properties = horizontal_text ,colspan = ncol(X4)) # doc = addFlexTable( doc, mytable1 ) doc = addParagraph(doc, " ") doc = addFlexTable( doc, mytable2 ) doc = addParagraph(doc, " ") doc = addFlexTable( doc, mytable3 ) doc = addParagraph(doc, " ") doc = addFlexTable( doc, mytable4 ) writeDoc(doc, file = "missing_sent.docx") #sudo apt-get install unoconv Sys.sleep(5) system("doc2pdf missing_sent.docx") #write in pdf using cli command cat('DONE\n')
16ffe919344c99e998e4d6358a21341356ad638b
650af521421421f5e12f58b9ee9ce7e4b23db0bd
/app_ui.R
070354aabcf6a0e7ef66e4380a382c71513cc848
[ "MIT" ]
permissive
info-201a-sp20/final-project-christiancruz-124
f15f752d17a217f03c7982246d5f95ae802938c2
aa8284437d081d24c92d7c13561e033eead74f57
refs/heads/master
2022-09-26T15:03:09.867197
2020-06-08T05:28:22
2020-06-08T05:28:22
262,849,108
0
0
MIT
2020-06-08T03:13:31
2020-05-10T18:22:06
HTML
UTF-8
R
false
false
6,278
r
app_ui.R
library(shiny) source("maps/app_ui.R") source("platformpage/app_ui.R") source("Opinion/app_ui.R") ui <- navbarPage( "Effectiveness and influences of social media marketing", # first panel: overview tabPanel( "Overview", includeCSS("style.css"), tags$h1(class = "header", "Overview"), sidebarLayout( sidebarPanel( tags$h3(class= "sub", "Purpose"), hr(), tags$p("In an effort to understand the effects social media marketing has on users, we have decided to explore social media and how marketing affects spending on popular social media sites as well as it's over all reception by users. The importance in such analysis lies in the ability to have a better understanding of the strategies used to influence shoppers, understand the feelings of users, identify social medias that have the most effect to then question why they are most effective, and finally to use demographical knowledge in conjunction with marketing data to evaluate their effectiveness in certain groups."), br(), tags$h3(class= "sub", "Data Sources"), hr(), tags$p("In this project we have successfully found data on", a("data world.", href= "https://data.world/"), "All of the datasets we chose from data.world was collected via survey on an app known as Whatsgoodly. The datasets provided information about demographics, location, and asked questions that showed opinions of different demographics about social media marketing as well as questions realting to the effectiveness of different social media platforms.")), mainPanel( tags$img(id = "img", "", src = "https://images.pexels.com/photos/927629/pexels-photo-927629.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260", height = 500, width = 900) ) ) ), # second panel: leaflet map on reactions map_page, # third panel: col chart on opinion by demographic race_panel, # fouth panel: col chart on platform effectiveness by demographic ui_platform, # fifth panel: conclusions page tabPanel( "Conclusions", tags$h1(class = "header", "Conclusions"), br(), tags$h4(class = "insight", "Mapping Opinions: General Trends Show Negative Responses Throughout"), tags$p("When comparing attitudes toward marketing in different locations,", "the connection between user attitude and location is not abosolute.", "However, we see a general trend of dislike across the country", "followed by neutrality in second, and finally positivity as last.", "This does not show whether that social media marketing is effective or not,", "but consumers definitely have a generally negative attitude towards this kind of marketing.", "Via this dataset, many of the ways effectiveness is measured is through", "the perspective of the users and this leads us the question their objectivity", "in the influence that social media holds in their own lives."), DT::dataTableOutput("table"), tags$p("The table above further highlights the points above, as we take percentage of opinion from 5 different locations and compare them. We can clearly see that almost all regions lean toward negative or neutral as opposed to positive."), br(), tags$h4(class = "insight", "Demographics and Opinion: General Consensus"), tags$p("Based on the summary of opinion of people who took the survey,", "It could be found that among different group of people, opinions are varied.", "The general trend, however, shows a negative/neutral attitute towards social media marketing", "Whether social media marketing is effective cannot be told from the summary since the inluence", "of the advertisements may be underestimated."),br(), "According to",a("social media impact.", href= "http://www.socialmediaimpact.com/impact-social-media-marketing-today/ #:~:text=Using%20social%20media%20platforms%20like,helps%20in%20developing%20business%20tactics."), "Social Media Marketing is having a tremendous impact on business and market as business growth.", "It helps in developing business tactics.", "Social media marketing helps a brand/company to build a strong online presence", "by innovative social media marketing techniques and customer satisfaction.", br(), tags$h4(class = "insight", "Platform Effectiveness: Are They Really Effective?"), tags$p("A quick look at each of the demographic categories on platform influence will easily show that there are a couple platforms that dominate the ad game. Both Facebook and instagram show clear signs as far as numbers that they provide the most effective platform for social media marketting out of the options provided by the Whatsgoodly survey. However, an even more prevelant platform with bigger numbers than the two powerhouses seems to be neither and none of the listed apps. \"None\" is among the listed categories that also has a high relative count of answers in each demographic category, which means a large amount of people feel they haven't been influenced by social media marketing. This poses the question of whether social media ads are effective at all."), plotOutput("platforms_overall"), tags$p("Something to consider is the objectivity of the data and thus the insights from the data. Becuase all of the data for this report is survey based, the data is all user reported. This means that a survey taker may answer \"None\" when in reality, they have purchased a product directly from a platform without knowing or may have unknowingly bought a product advertised to them while on a certain platform. There is no way to accurately determine this without better, more direct data, so further investigation with better data is needed to fully determine the effectiveness of social media marketing.") ) )
778410ae6e8994942cc5d31aeeea503d2b5abe55
9e6ca0e896acf5d7a02bed7e8d2d8e0a6bfd50e5
/man/sc_weights.Rd
c38fd484c1fccf82e3d9f9abee76122f20294003
[]
no_license
cran/NonProbEst
986ea321fe9d213b63170a24fe2b9d2c015db455
978c6f6d645c01cb367ff0ad9100b9565de3190f
refs/heads/master
2020-07-21T19:38:17.932468
2020-06-03T11:10:03
2020-06-03T11:10:03
206,957,607
0
0
null
null
null
null
UTF-8
R
false
true
1,137
rd
sc_weights.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/NonProbEst.R \name{sc_weights} \alias{sc_weights} \title{Calculates Schonlau and Couper weights} \usage{ sc_weights(propensities) } \arguments{ \item{propensities}{A vector with the propensities associated to the elements of the convenience sample.} } \value{ A vector with the corresponding weights. } \description{ Computes weights from propensity estimates using the (1 - pi_i)/pi_i formula introduced in Schonlau and Couper (2017). } \details{ The function takes the vector of propensities \eqn{\pi(x)} and calculates the weights to be applied in the Hajek estimator using the formula that can be found in Schonlau and Couper (2017). For an individual \emph{i}, weight is calculated as follows: \deqn{w_i = \frac{1 - \pi_i (x)}{\pi_i (x)}} } \examples{ covariates = c("education_primaria", "education_secundaria") data_propensities = propensities(sampleNP, sampleP, covariates) sc_weights(data_propensities$convenience) } \references{ Schonlau, M., & Couper, M. P. (2017). \emph{Options for conducting web surveys.} Statistical Science, 32(2), 279-292. }
9bfc6af00950a8c7e9f20339bff2c854a53251d2
86d11da7198eb29441a365f742e7e0c7f10a5632
/pipelineHead.R
4f2f099c3b4d6a62538862663200b13c431628fa
[ "MIT" ]
permissive
mTEC-pipelines/tufts-pipelines
5d9fa8b3cdd2f3316b4eeb88c157a260ba675da5
f5cfa303550c90cc2027b06c3685b225ab4967c3
refs/heads/master
2021-09-10T14:40:30.727146
2018-03-27T23:41:55
2018-03-27T23:41:55
112,393,503
0
0
null
null
null
null
UTF-8
R
false
false
3,891
r
pipelineHead.R
############################################################################### # Author: Aparna Rajpurkar # Date: 2.15.17 # # Required custom scripts: # MainPipelineDriver.R # funcs.R # Required data files: # Data files should be contained within a subdirectory named: # tuft_analysis_datafiles # # Purpose # # These scripts perform analysis for single cell analysis of Tuft cells. # No guarantees made. These scripts were written for personal use. # Contact: arrajpur@stanford.edu with questions. # # Usage: Rscript MainPipelineDriver.R # Modify the driver file for different plots ############################################################################### #source("funcs.R", print.eval=TRUE) library(scran) #needed for SingleCellExperiment library(scater) #needed for calculateQCMetrics ENSEMBL_MOUSE_CONVERSION_FILE<-"tuft_analysis_datafiles/mouse_ensembl_genesymbol_conversion.txt" NORMALIZED_DATA_FILE<-"tuft_analysis_datafiles/POR_all_data.rda" WT_COUNTS<-"tuft_analysis_datafiles/all_wt_counts.txt" AIREKO_COUNTS<-"tuft_analysis_datafiles/aireko_counts.txt" BATCH_INFO<-"tuft_analysis_datafiles/samples_all.txt" conversion<-read.delim(ENSEMBL_MOUSE_CONVERSION_FILE, header=T) convertNames<-function(gene_list, convert_from="mgi_symbol", convert_to="ensembl_gene_id") { result<-conversion[match(gene_list, conversion[,convert_from]), convert_to] result } # get normalized data pos_control<-"kw_tuft_142" vars<-load(NORMALIZED_DATA_FILE) norm.exprs<-normalized norm.exprs<-norm.exprs[,!(colnames(norm.exprs)==pos_control)] norm.exprs<-norm.exprs[!(grepl("ERCC", rownames(norm.exprs))),,drop=FALSE] # get raw counts for basic metadata wt_file <- WT_COUNTS aire_file <- AIREKO_COUNTS controls<-c("kw_tuft_141", "kw_tuft_142", "kw_tuft_143", "kw_tuft_144", "June29_KW.96.featureCounts") DATA_WT <- read.csv(wt_file, header = T, row.names = 1, sep="\t") DATA_AIRE <- read.csv(aire_file, header = T, row.names = 1, sep="\t") DATA <- cbind.data.frame(DATA_WT, DATA_AIRE[rownames(DATA_WT),,drop=FALSE]) raw.counts<-DATA[,!(colnames(DATA) %in% controls),drop=FALSE] raw.counts<-raw.counts[!(grepl("ERCC", rownames(raw.counts))),,drop=FALSE] # get total number of cells from raw counts numCells <- ncol(raw.counts) # set batches batch_info<-read.delim(BATCH_INFO, header=T, row.names=1) batch<-batch_info[colnames(raw.counts),,drop=FALSE] ########################################################################## # deal with the ENSEMBL gene name issue ensembl_mouse<-rownames(raw.counts)[grepl("ENSMUSG", rownames(raw.counts))] rownames(raw.counts)<-sub("(ENSMUSG\\d+|ERCC.+)\\.*\\d*", "\\1", rownames(raw.counts), perl=TRUE) geneNamesForMito<-convertNames(rownames(raw.counts), convert_from="ensembl_gene_id", convert_to="mgi_symbol") mito_bool<-grepl("mt", geneNamesForMito) # get ercc names from raw raw.counts erccs_raw<-rownames(raw.counts[grepl("ERCC",rownames(raw.counts)),]) mito_raw<-rownames(raw.counts[mito_bool,]) # set phenotype data (describe cells) pd<-data.frame(batch=batch) rownames(pd)<-colnames(raw.counts) colnames(pd)<-colnames(batch) fd<-data.frame(rownames(raw.counts)) rownames(fd)<-rownames(raw.counts) colnames(fd)<-"ensembl" # create SingleCellExperiment to hold all data mtecdev<-SingleCellExperiment( list(counts=as.matrix(raw.counts)), colData=pd, rowData=fd ) # calculate basic QC, setting controls as ERCCs mtecdev<-calculateQCMetrics( mtecdev, feature_controls=list(ERCC=erccs_raw, MITO=mito_raw) ) # get phenotype data / sample metadata sampleData<-cbind.data.frame(colData(mtecdev)) rownames(sampleData)<-colnames(mtecdev) norm.cells<-colnames(norm.exprs) sampleData<-sampleData[norm.cells,]
e39d38caaa0d7921393c413bba62c81d5241feba
a388530e188ad749f79545cc06f7c341cf9472d9
/man/spatialHEAT.Rd
21559858906f30b066f21f4355e7e351c302dcc3
[]
no_license
atfutures-labs/spatialHEAT
178a724a4e7e532833f0208d3dd24898e39ffd44
53b8d594b09bd97ed2162514de5b7e63781b75c5
refs/heads/master
2020-03-22T05:19:46.422409
2018-10-31T16:48:54
2018-10-31T16:48:54
null
0
0
null
null
null
null
UTF-8
R
false
true
233
rd
spatialHEAT.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/spatialheat-package.R \docType{package} \name{spatialHEAT} \alias{spatialHEAT} \alias{spatialHEAT-package} \title{spatialHEAT} \description{ spatialHEAT }
cab5459dbaf1a16328ba5c944a4eb6c6d30e2039
208358d9640a4280cb937011c91352403957b24a
/scripts/check/02-cor-top-pcs.R
60526bc68d38b450e2447077e0e7650cf4238eb3
[ "MIT" ]
permissive
variani/paper-neff
9c91fe22d37ab04c902cb769004a00bb19cf1021
0e0bbc90c63ffb7c77a8331df6b07d99ca8e6452
refs/heads/master
2023-01-28T05:41:21.881878
2020-12-10T02:30:10
2020-12-10T02:30:10
278,204,788
3
0
null
null
null
null
UTF-8
R
false
false
1,019
r
02-cor-top-pcs.R
### inc library(tidyverse) library(glue) library(data.table) library(BEDMatrix) library(bigsnpr) library(devtools) load_all("~/git/variani/biglmmz/") ## arguments trait <- "hip" ntop <- 500 ## parameters file_phen <- "out/phen.sync.tsv.gz" file_pcs <- "out/pcs.sync.tsv.gz" file_clump <- glue("out/clump/{trait}.top.5000.clump.gz") ## read top variants cat(" - read clump\n") clump <- read_tsv(file_clump) %>% arrange(P) if(nrow(clump) < ntop) { stop(glue("#rows in clump ({nrow(clump)}) < #top ({ntop})")) } clump <- head(clump, ntop) snps_top <- clump$SNP ## load Z cat(" - load Z\n") Z <- glue("out/fbm/{trait}.rds") %>% big_attach snps_z <- glue("out/fbm/{trait}.variants") %>% read_lines ## read phen. phen <- file_phen %>% fread %>% as_tibble stopifnot(trait %in% colnames(phen)) y <- phen[[trait]] pcs <- file_pcs %>% fread %>% as_tibble ## compute corr. G <- Z[, seq(ntop)] cor(pcs$PC1, G) %>% as.numeric %>% sort %>% head %>% round(2) cor(pcs$PC2, G) %>% as.numeric %>% sort %>% head %>% round(2)
9d30e267f058e578a3c715f523367a0579c2c8c3
d01ef90f1b72ae02ac5055c7c93c69fcf5a7be5c
/pedigree/plotRelDraft.R
9e0abb33f2cd2eb10131d6f6bce92fa14d0c695e
[]
no_license
ngon/LgSm-DataProcessing
3b8dde9e4e75f1e2e6791ec342cda80b6d54070f
37c816f5257dcc87802124e87dbd9e445f6d146f
refs/heads/master
2020-07-04T15:07:14.876067
2015-11-21T02:52:33
2015-11-21T02:52:33
22,928,887
0
1
null
null
null
null
UTF-8
R
false
false
2,465
r
plotRelDraft.R
load("C:/Users/Administrator/Desktop/Scripts/LgSm-DataProcessing/pedigree/grm.geno.samples.RData") load("C:/Users/Administrator/Desktop/Scripts/LgSm-DataProcessing/pedigree/genotypedRelatives.RData") row.names(grm) <- as.numeric(row.names(grm))-0.1 colnames(grm) <- row.names(grm) names(grm) <- colnames(grm) asib <- c() bsib <- c() for (i in seq_along(sibPairs)) { asib <- c(asib, as.character(sibPairs[[i]][1])) bsib <- c(bsib, as.character(sibPairs[[i]][2])) } aidx <- c() bidx <- c() for (i in 1:length(asib)) { aidx[[i]] <- which(row.names(grm) == asib[i]) bidx[[i]] <- which(row.names(grm) == bsib[i]) } sibValues <- c() for (i in seq_along(aidx)) { sibValues[[i]] <- grm[aidx[i], bidx[i]] } ped.geno <- ped[ped$id %in% geno.samples$id,] pedsib <- ped.geno[721:1830,] pedsib$id <- pedsib$id - 0.1 sibgrm <- which(names(grm) %in% as.character(pedsib$id)) sibgrm <- grm[sibgrm,sibgrm] plot(1:1229, sibgrm[1,]) library(lattice) cols<- brewer.pal(11, 'PiYG') test<-colorRampPalette(cols, alpha = TRUE)(50) levelplot(sibgrm, col.regions=test, cuts=49, cex.axis=0.8, scales=list(x=list(rot=45))) # sibships > 2 # 46043 46166 46203 48335 50277 50291 51967 51999 52129 # 63 90 102 137 265 268 436 442 464 # sibPairs[[510]] <- c(48355, 48417) # sibPairs[[511]] <- c(48358, 48417) # sibPairs[[512]] <- c(50150, 49217) # sibPairs[[513]] <- c(50150, 49218) # sibPairs[[514]] <- c(50150, 50150) # sibPairs[[515]] <- c(50151, 49217) # sibPairs[[516]] <- c(50151, 49218) # sibPairs[[517]] <- c(49255, 49258) # sibPairs[[518]] <- c(49255, 49234) # sibPairs[[519]] <- c(49255, 49233) # sibPairs[[520]] <- c(49233, 49258) # sibPairs[[521]] <- c(49234, 49258) # sibPairs[[522]] <- c(50147, 50189) # sibPairs[[523]] <- c(50148, 50189) # sibPairs[[524]] <- c(51304, 51295) # sibPairs[[525]] <- c(51304, 51275) # sibPairs[[526]] <- c(51313, 51216) # sibPairs[[527]] <- c(51313, 51209) # sibPairs[[528]] <- c(54315, 54304) # sibPairs[[529]] <- c(54315, 54253) # sibPairs[[530]] <- c(54315, 54244) # sibPairs[[531]] <- c(54304, 54253) # sibPairs[[532]] <- c(54304, 54244) # sibPairs[[533]] <- c(54207, 54190) # sibPairs[[534]] <- c(54207, 54187) # sibPairs[[535]] <- c(54872, 54871) # sibPairs[[536]] <- c(54872, 54817) # sibPairs[[537]] <- c(54872, 54816) # sibPairs[[538]] <- c(54871, 54817) # sibPairs[[539]] <- c(54871, 54816) # # which(lapply(sibPairs, length) < 2) # sibPairs <- sibPairs[-c(162,166,323,328,333)]
a8e5ec194b28262117061cb857ce65fde5133c5c
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/fungible/examples/faAlign.Rd.R
d93ddf80d96a053dac9df5bf8cde96ebfa6a17a3
[]
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
3,167
r
faAlign.Rd.R
library(fungible) ### Name: faAlign ### Title: Align the columns of two factor loading matrices ### Aliases: faAlign ### Keywords: fungible Statistics ### ** Examples # This example demonstrates the computation of # non-parametric bootstrap confidence intervals # for rotated factor loadings. library(GPArotation) data(HS9Var) HS9 <- HS9Var[HS9Var$school == "Grant-White",7:15] # Compute an R matrix for the HSVar9 Mental Abilities Data R.HS9 <- cor(HS9) varnames <- c( "vis.per", "cubes", "lozenges", "paragraph.comp", "sentence.comp","word.mean", "speed.add", "speed.count.dots", "speed.discr") # Extract and rotate a 3-factor solution # via unweighted least squares factor extraction # and oblimin rotation. NFac <- 3 NVar <- 9 B <- 200 # Number of boostrap samples NSubj <- nrow(HS9) # Unrotated 3 factor uls solution F3.uls <- fals(R = R.HS9, nfactors = NFac) # Rotate via oblimin F3.rot <- oblimin(F3.uls$loadings, gam = 0, normalize = FALSE) F3.loadings <- F3.rot$loadings F3.phi <- F3.rot$Phi # Reflect factors so that salient loadings are positive Dsgn <- diag(sign(colSums(F3.loadings^3))) F3.loadings <- F3.loadings %*% Dsgn F3.phi <- Dsgn %*% F3.phi %*% Dsgn rownames(F3.loadings) <- varnames colnames(F3.loadings) <- paste0("f", 1:3) colnames(F3.phi) <- rownames(F3.phi) <- paste0("f", 1:3) cat("\nOblimin rotated factor loadings for 9 Mental Abilities Variables") print( round(F3.loadings, 2)) cat("\nFactor correlation matrix") print( round( F3.phi, 2)) # Declare variables to hold bootstrap output Flist <- Philist <- as.list(rep(0, B)) UniqueMatchVec <- rep(0, B) rows <- 1:NSubj # Analyze bootstrap samples and record results for(i in 1:B){ cat("\nWorking on sample ", i) set.seed(i) # Create bootstrap sanples bsRows <- sample(rows, NSubj, replace= TRUE) Fuls <- fals(R = cor(HS9[bsRows, ]), nfactors = NFac) # rotated loadings Fboot <- oblimin(Fuls$loadings, gam = 0, normalize = FALSE) out <- faAlign(F1 = F3.loadings, F2 = Fboot$loadings, MatchMethod = "LS") Flist[[i]] <- out$F2 # aligned version of Fboot$loadings UniqueMatchVec[i] <- out$UniqueMatch } cat("\nNumber of Unique Matches: ", 100*round(mean(UniqueMatchVec),2),"%\n") # Make a 3D array from list of matrices arr <- array( unlist(Flist) , c(NVar, NFac, B) ) # Get quantiles of factor elements over third dimension (samples) F95 <- apply( arr , 1:2 , quantile, .975 ) F05 <- apply( arr , 1:2 , quantile, .025 ) Fse <- apply( arr , 1:2, sd ) cat("\nUpper Bound 95% CI\n") print( round(F95,3)) cat("\n\nLower Bound 95% CI\n") print( round(F05,3)) # plot distribution of bootstrap estimates # for example element hist(arr[5,1,], xlim=c(.4,1), main = "Bootstrap Distribution for F[5,1]", xlab = "F[5,1]") print(round (F3.loadings, 2)) cat("\nStandard Errors") print( round( Fse, 2))
186157efc60528b96683c7a0318173d59ccbfebf
0d66d47a81f3e54cc30e08f23dfcf0210800bf96
/R/buildtrigger_objects.R
d80232cee1ecf329b8f080538871f485b3b25b54
[]
no_license
cran/googleCloudRunner
cda2c85a766dd811b03b3730f17475cb666b60fb
ae7eff0dcd74d28cec34bf7f9766fd8a9d5fe62a
refs/heads/master
2022-03-12T07:08:12.993736
2022-02-28T08:40:01
2022-02-28T08:40:01
238,888,139
0
0
null
null
null
null
UTF-8
R
false
false
7,504
r
buildtrigger_objects.R
#' BuildTrigger Object #' #' Configuration for an automated build in response to source repositorychanges. #' #' @param substitutions A named list of Build macro variables #' @param filename Path, from the source root, to a file whose contents is used for the build #' @param name User assigned name of the trigger #' @param tags Tags for annotation of a `BuildTrigger` #' @param build Contents of the build template #' @param ignoredFiles ignored_files and included_files are file glob matches extended with support for "**". #' @param github a \link{GitHubEventsConfig} object - mutually exclusive with \code{triggerTemplate} #' @param includedFiles If any of the files altered in the commit pass the ignored_files #' @param disabled If true, the trigger will never result in a build #' @param sourceToBuild A \link{cr_buildtrigger_repo} object (but no regex allowed for branch or tag) This field is currently only used by Webhook, Pub/Sub, Manual, and Cron triggers and is the source of the build will execute upon. #' @param triggerTemplate a \link{RepoSource} object - mutually exclusive with \code{github} #' @param description Human-readable description of this trigger #' @param pubsubConfig PubsubConfig describes the configuration of a trigger that creates a build whenever a Pub/Sub message is published. #' @param webhookConfig WebhookConfig describes the configuration of a trigger that creates a build whenever a webhook is sent to a trigger's webhook URL. #' #' @seealso \url{https://cloud.google.com/build/docs/api/reference/rest/v1/projects.triggers} #' #' @return BuildTrigger object #' #' @family BuildTrigger functions #' @export BuildTrigger <- function(filename = NULL, name = NULL, tags = NULL, build = NULL, ignoredFiles = NULL, github = NULL, substitutions = NULL, includedFiles = NULL, disabled = NULL, sourceToBuild = NULL, triggerTemplate = NULL, webhookConfig = NULL, description = NULL, pubsubConfig = NULL) { assert_that( xor(is.null(build), is.null(filename)), !is.null(webhookConfig) || !is.null(pubsubConfig) || xor(is.null(github), is.null(triggerTemplate)) ) if (!is.null(github)) { assert_that(is.gar_GitHubEventsConfig(github)) } if (!is.null(triggerTemplate)) { assert_that(is.gar_RepoSource(triggerTemplate)) } if (!is.null(pubsubConfig)) { assert_that(is.gar_pubsubConfig(pubsubConfig)) } structure(rmNullObs(list( filename = filename, name = name, tags = tags, build = build, ignoredFiles = ignoredFiles, github = github, substitutions = substitutions, sourceToBuild = sourceToBuild, includedFiles = includedFiles, disabled = disabled, triggerTemplate = triggerTemplate, pubsubConfig = pubsubConfig, webhookConfig = webhookConfig, description = description )), class = c("BuildTrigger", "list") ) } is.gar_BuildTrigger <- function(x) { inherits(x, "BuildTrigger") } as.BuildTrigger <- function(x) { assert_that(is.buildTriggerResponse(x)) BuildTrigger( filename = x$filename, name = x$name, tags = x$tags, build = x$build, ignoredFiles = x$ignoredFiles, github = x$github, substitutions = x$substitutions, sourceToBuild = x$sourceToBuild, includedFiles = x$includedFiles, disabled = x$disabled, triggerTemplate = x$triggerTemplate, description = x$description ) } #' Pubsub Config (Build Trigger) #' #' PubsubConfig describes the configuration of a trigger that creates a build whenever a Pub/Sub message is published. #' #' @param subscription Output only. Name of the subscription. #' @param topic The name of the topic from which this subscription is receiving messages. #' @param serviceAccountEmail Service account that will make the push request. #' @param state Potential issues with the underlying Pub/Sub subscription configuration. Only populated on get requests. #' #' @return A PubsubConfig object #' @seealso `https://cloud.google.com/build/docs/api/reference/rest/v1/projects.locations.triggers#BuildTrigger.PubsubConfig` #' #' @export PubsubConfig <- function(subscription = NULL, topic = NULL, serviceAccountEmail = NULL, state = NULL) { structure(rmNullObs( list( subscription = subscription, topic = topic, serviceAccountEmail = serviceAccountEmail, state = state ) ), class = c("gar_pubsubConfig", "list") ) } is.gar_pubsubConfig <- function(x) { inherits(x, "gar_pubsubConfig") } as.gar_pubsubConfig <- function(x){ PubsubConfig( subscription = x$subscription, topic = x$topic, serviceAccountEmail = x$serviceAccountEmail, state = x$state ) } #' WebhookConfig (Build Triggers) #' #' WebhookConfig describes the configuration of a trigger that creates a build whenever a webhook is sent to a trigger's webhook URL. #' #' @param state Potential issues with the underlying Pub/Sub subscription configuration. Only populated on get requests. #' @param secret Resource name for the secret required as a URL parameter. #' #' @return A WebhookConfig object #' #' @export WebhookConfig <- function(secret, state = NULL) { structure(rmNullObs( list( secret = secret, state = state ) ), class = c("gar_webhookConfig", "list") ) } is.gar_webhookConfig <- function(x) { inherits(x, "gar_webhookConfig") } #' GitRepoSource #' Used for PubSub triggers #' @noRd GitRepoSource <- function(uri, ref, repoType = c("GITHUB","CLOUD_SOURCE_REPOSITORIES")){ assert_that( is.string(uri), is.string(ref), isTRUE(grepl("^refs/", ref)), !grepl("[^A-Za-z0-9/.]", ref) # regex not allowed ) repoType <- match.arg(repoType) structure( list( uri = uri, ref = ref, repoType = repoType ), class = c("gar_gitRepoSource","list") ) } is.gitRepoSource <- function(x){ inherits(x, "gar_gitRepoSource") } as.gitRepoSource <- function(x){ if(!is.buildtrigger_repo(x)){ stop("is not buildtrigger_repo") } if(is.gar_GitHubEventsConfig(x$repo)){ if(!is.null(x$repo$push$tag)){ ref <- paste0("refs/tags/", x$repo$push$tag) } else if(!is.null(x$repo$push$branch)){ ref <- paste0("refs/heads/", x$repo$push$branch) } else { stop("No refs/ found", call. = FALSE) } return( GitRepoSource( uri = sprintf("https://github.com/%s/%s", x$repo$owner, x$repo$name), ref = ref, repoType = "GITHUB" ) ) } if(is.gar_RepoSource(x$repo)){ if(!is.null(x$repo$tagName)){ ref <- paste0("refs/tags/", x$repo$tagName) } else if(!is.null(x$repo$branchName)){ ref <- paste0("refs/heads/", x$repo$branchName) } else { stop("No refs/ found", call. = FALSE) } return( GitRepoSource( uri = sprintf("https://source.developers.google.com/p/%s/r/%s", x$repo$projectId, x$repo$repoName), ref = ref, repoType = "CLOUD_SOURCE_REPOSITORIES" ) ) } stop("Could not convert object via as.gitRepoSource") }
b04feb6caa8e9fb04be331233fa7779661d4214f
b88a25004b23282d65b5683c177eac9cc4df0638
/00_30diasDeGraficos/05_arco/05_arco.R
ba5ceb1a17e4699548a927edfd5cf6652af71cfe
[]
no_license
AnguloB/datosdemiercoles
8eb140f3cf4e8bcd658063628c12647d367eb1e2
2ef5716544136faa0ab56a348fc44f6dec179171
refs/heads/master
2022-11-21T13:21:59.329486
2020-09-03T11:49:04
2020-09-03T11:49:04
241,910,703
14
4
null
2022-11-07T16:34:02
2020-02-20T14:52:29
HTML
UTF-8
R
false
false
4,063
r
05_arco.R
library(tidyverse) # dia 4 facetas #Datos del SIDC Cat (link directo en el script ) backcolor<-"white" colortext<-"black" #Defino paleta de colores palette30<- c("#FD7FC4", "#FF8A33", "#EC4176", "#A13770" , "#33DDFF", "#FFEC33", "#5564eb", "#4c2882") #Eligo la fuente que quiero utilizar library(extrafont) # la primera vez ejecutar font_import() loadfonts() font<- "Trebuchet MS" #Fuente que voy a utlizar library(readr) Citaciones <- read_csv("Citaciones.csv") #selecciono solo las variables que me interesan Citaciones%>% select(Authors, Title) ->data data<-data%>%separate_rows(Authors, sep = ",") #Separo por coma los autores en cada linea data<-data[seq(1,nrow(data),2) ,] #me quedo solo con los pares data$Authors<-str_trim(data$Authors) #saco espacios en blanco data<-data%>% group_by(Title) %>% mutate(titleid=factor(group_indices())) #cambio el titulo por un ID data<-data[,c("titleid","Authors")] library(stringi) data$Authors<-stri_trans_general(data$Authors, "Latin-ASCII") totals<-data%>% #Creo el total de articulos de cada group_by(Authors)%>% count()%>% arrange(desc(n)) names(totals)<-c("from", "totalreal") # transformo los datos de forma que haya la correspondencia entre autores dta <- full_join(data, data, c('titleid' = 'titleid')) %>% select(-titleid) %>% filter(Authors.x != Authors.y) %>% group_by(Authors.x, Authors.y) %>% summarise(total = n()) names(dta)<- c("from", "to", "total") dta<-dta%>% left_join(totals)%>% select(from, to, totalreal) library(ggraph) palette30 <- c("grey60","#FFEC33","#33DDFF","#EC4176","#FF8A33","#5564eb") p1<-ggraph(dta, 'linear') + geom_edge_arc(aes(color=factor(totalreal), alpha=factor(totalreal)), fold=FALSE)+theme_bw()+ geom_node_point(size=2,alpha=0.5) + scale_edge_colour_manual(values=palette30)+ theme(text=element_text(family = font), plot.background = element_rect(fill = "white", color=NA), strip.background =element_blank(), panel.border = element_blank(), panel.grid.minor = element_blank(), panel.grid.major = element_blank(), axis.ticks = element_blank(), legend.background = element_rect(fill=backcolor, size=0.5, linetype="solid"), plot.title = element_text(size=20, hjust=0,face="bold", color="#9B77CF"), plot.subtitle = element_text(face="italic", size=12), axis.text.x = element_blank(), axis.text.y = element_blank(), legend.position = "none")+ labs(title= "Día 5: arco", fill="", subtitle = "A journey around alpha and omega to estimate internal consistency reliability: \n autores y autoras que han citado el articulo y relación entre ellos", y = "", x = "")+ expand_limits(x = c(-1.2, 1.2), y = c(-5.6, 1.2)) p2<-totals%>% group_by(totalreal)%>% count()%>% ggplot(aes(x=factor(totalreal), y=n, fill=factor(totalreal)))+ geom_col(aes( alpha=factor(totalreal)))+ geom_text(aes(label=paste0("N = ",n), hjust=-.25))+ scale_fill_manual(values=palette30)+ coord_flip()+theme_bw()+ theme(text=element_text(family = font, color="#9B77CF"), plot.background = element_rect(fill = "white", color=NA), strip.background =element_blank(), panel.border = element_blank(), panel.grid.minor = element_blank(), panel.grid.major = element_blank(), axis.ticks = element_blank(), axis.text.x = element_blank(), legend.position = "none", plot.caption = element_text( face="italic", size=10, hjust = 1, color="black"))+ labs(title ="", subtitle="\n \n", caption = "Viladrich, Angulo-Brunet y Doval (2017) \n Hecho por @AnguloBrunet \n #30díasdegráficos \n Fuente: Scopus 15 mayo 2020", y="Autores", x="Nº articulos")+ scale_y_continuous(position = "right", limits=c(0,180)) library(cowplot) plot_grid(p1, p2, nrow=1, rel_widths = c(0.8, .2)) ggsave("05_arco.png", height = 5.89, width=8.58)
1061e4eb8e832915d9065fa1a5ece018e3760252
c4514cfc6f5e132de24709ccebf057007714ef5e
/dsx_project/all_data.r
1b0df0ce5d7b232d19a69c4ee9eb7eb6230c75a2
[]
no_license
mmaccoun/dsx_project-
af53b58035226973ff5a439eac4dd538d0f31aa3
82e85ad4c1ff315bc371a95adae56508d4055f1f
refs/heads/master
2020-04-24T00:22:24.884499
2019-03-06T22:08:57
2019-03-06T22:08:57
171,564,285
0
0
null
null
null
null
UTF-8
R
false
false
886
r
all_data.r
setwd("~/Desktop/mmaccoun/dsx_project--master/master_files") #move all_M_data.csv and all_F_data.csv to directory to work in male <- read.csv('all_M_data.csv') male$sex <- "M" female <- read.csv('all_F_data.csv') female$sex <- "F" dat <- rbind(male, female) dat$sample<- as.character(dat$sample) dat$rep <- gsub(".*_", "", dat$sample) dat$strain <- gsub("_.*", "", dat$sample) str(dat) names(dat) <- c(' ', 'exonic region id', 'sample id', 'number of mapped reads', 'number of reads in the exonic region', 'coverage in exonic region (number of reads in exonic region / read length)', 'exonic region length','average per nucleotide coverage,','RPKM', 'sample','sex', 'rep', 'strain') #write.csv(dat,'all_dat.csv') hist(dat$RPKM) #hist of RPKM data # hist(log(dat$RPKM)) #adj for bellc dat$logRPKM = log(dat$RPKM) # shapiro.test(log(dat$RPKM)) test to bellcurve
985c42c7df16c1fe37441b903c27095e9a2266a0
37a31c0ed3873b42397033cc218f381b887d91e9
/BNK48-Analysis.r
30ff629936241bad9dd900b3a43e125ee13dcee9
[]
no_license
lebrancconvas/R-Analysis
ef48b443e8f740fb4311cf576b78251c1b897317
9358388c482ecbb17f2fe571a126ffa1d7847e3a
refs/heads/master
2020-03-11T10:27:27.225560
2018-04-18T17:45:50
2018-04-18T17:45:50
129,943,284
1
0
null
null
null
null
UTF-8
R
false
false
175
r
BNK48-Analysis.r
install.packages("tuber") library(tuber) yt_oauth(app id = "762981940110-r663ca3n6onh4vvlas4mtcnofrcubc0c.apps.googleusercontent.com", app_secret = "dDaYjoXgc6JRArETwQXq5e_2")
eba9edba64af61f2d8ca0344ec13f81111402bde
89326a15b8f6506ed5b75feda9d8857980efcd4d
/discreteRV.R
5fa6d75d2ee9d480773a55ccc9207f4d2ac5a163
[ "MIT" ]
permissive
andrei-micuda/ShinyRV
f6bd8ff69f4caa4a9c971b955d502e5b576489e5
54707bdad4e1f1c064814baa873c87c47f1e1a47
refs/heads/main
2023-03-02T07:00:05.945757
2021-02-07T16:20:59
2021-02-07T16:20:59
328,680,559
0
0
null
null
null
null
UTF-8
R
false
false
807
r
discreteRV.R
validate_probability <- function(v, p) { values <- array(v) probs <- array(p) print(sum(probs)) #if(!is.array(values) && !is.array(probs)) # stop("values are not arrays.") if(length(values) != length(probs)) stop("values do not have the same length") if(abs(1 - sum(probs)) > 0.000001) stop("probabilites must add up to 1") if(length(unique(values)) != length(values)) stop("all values must occur only once") random_variable <- matrix(data=c(values,probs), nrow=2, byrow=TRUE) rownames(random_variable) <- c('Outcomes', 'Probs') random_variable } applyFunction <- function(m, f) { m[1,] = f(m[1,]) m } getMean <- function(m) { sum(m[2,] * m[1,]) } getVariance <- function(m) { getMean(applyFunction(m, function(x) x**2)) - getMean(m) ** 2 }
c30c92c14852dd2d5beddedfe5143cb99183a0b4
fff814356f63080b30cb2d47f3d6297c5b9841d5
/kmedoids.R
f6d6efcdcbe4107cfcd799b819d0f939d4ebe9e7
[]
no_license
dasasathyan/datamining
117526e3416646ae6713cc52a10bae417b61c6bb
6c3878bf391235f501301d206ea7fb73cb6e0ab7
refs/heads/master
2021-05-10T13:13:38.098096
2018-01-22T14:30:51
2018-01-22T14:30:51
118,467,921
0
0
null
null
null
null
UTF-8
R
false
false
369
r
kmedoids.R
library(fpc) pam.result <- pam(IrisDataset1,3) table(pam.result$clustering, IrisDataset1$Class) layout(matrix(c(1,2),1,2)) # 2 graphs per page plot(pam.result) layout(matrix(1)) # change back to one graph per page plot(pam.result) return() return() pam.result2 <- pam(IrisDataset1,4) table(pam.result2$clustering, IrisDataset1$Class) plot(pam.result2) return() return()
76c00cbade342ce7cc260cf55bcd95a696fc2925
d490fa1324d85e5e5c0a327358c09c9a5da969e8
/R/select_data.R
e9bae3e6bc788a4b45b569e17065afaab94eecde
[]
no_license
HaikunXu/IATTCassessment
63e990425800bd0f3e2ae8b193e21cda597d0624
cb584cf47f2a22a616aaacd71a92542fe85e6dbd
refs/heads/master
2023-07-19T15:18:17.521122
2023-07-10T21:09:50
2023-07-10T21:09:50
191,084,703
0
0
null
null
null
null
UTF-8
R
false
false
1,330
r
select_data.R
#' Generate area code for longline #' #' \code{data_selection} This function filter the data for LL CPUE standardization #' #' @param c1 minimal sets by vessel #' @param c2 minimal quarters by vessel #' @param c3 minimal sets by grid #' @param c4 minimal quarters by grid #' @export # Data selection criterion for JPN operational LL data in the EPO # Inspired by http://www.iotc.org/sites/default/files/documents/2018/10/IOTC-2018-WPM09-12_Rev1.pdf # Haikun Xu; 1/30/2019 select_data <- function(data,c1,c2,c3,c4) { # Generate the quantities for data selection Data <- data %>% mutate(year=ceiling(Year/4)+1974) %>% group_by(Vessel) %>% mutate(setsbyvessel=n(), # total number of sets per vessel quartersbyvessel=length(unique(Year))) %>% # total number of quarters fished per vessel group_by(Lat,Lon) %>% mutate(setsbygrid=n(), # total number of sets per grid cell quartersbygrid=length(unique(Year))) # # total number of quarters per grid cell # Data selection data_selected <- Data %>% filter(setsbyvessel>=c1, # select vessel quartersbyvessel>=c2, # select vessel setsbygrid>=c3, # select grid quartersbygrid>=c4) # select grid return(data_selected) }
cef5c81de6c8a296a57f3c26d9ca2571a7156479
320e9a7c8d2f6d0aa3b009b8ba599a59745bdd6b
/man/numUniqueValues.Rd
033fea99f4e21138225b192a97fd0edf27698d70
[]
no_license
AlejandroKantor/akmisc
acaeeabd35bed31f6c8c9a033427ab6c5bb23a5f
5af7e9cd40edda6530f22aab5f3d87703041fa3d
refs/heads/master
2020-07-19T05:46:37.635593
2017-10-20T00:57:53
2017-10-20T00:57:53
73,770,909
0
0
null
null
null
null
UTF-8
R
false
true
523
rd
numUniqueValues.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/numUniqueValues.R \name{numUniqueValues} \alias{numUniqueValues} \title{Gives the number of unique values of a vector} \usage{ numUniqueValues(v_values) } \arguments{ \item{v_values}{a vector.} } \value{ An integer of the number of unique que values in v_values. If v_value has length zero returns 0. } \description{ Gives the number of unique values of a vector } \examples{ numUniqueValues(1:10) numUniqueValues(c("a","a","b","c","c","c")) }
13c9ed6f963fe7ee665464b16ebdab35150afe89
7e5dfa53a52b3aad29a22ebb12916a41a0e62e6b
/R/ic.icc.R
67e13c65b892eb9b2c9e49d94b40f0b8181cd758
[]
no_license
cran/cccrm
3a12b3fd0f834c302006e691d37547d9d41b9f79
302e8dc1f85494f28ac3b39c52e5c2f3de9c0136
refs/heads/master
2022-09-14T18:01:05.004119
2022-08-31T16:30:02
2022-08-31T16:30:02
17,695,003
0
0
null
null
null
null
UTF-8
R
false
false
405
r
ic.icc.R
ic.icc <- function(ccc,dev,S,alpha,m){ se.ccc <- as.numeric(sqrt(dev%*%S%*%t(dev))) z<-ZF(ccc,m) se.z<-dZF(ccc,m)*se.ccc ic.z=z+c(-1,1)*qnorm(1-alpha/2)*se.z ic.icc=(exp(2*ic.z)-1)/(exp(2*ic.z)+1) result<-c(ccc,ic.icc,se.ccc,z,se.z) conf.lab=paste((1-alpha)*100,"%",sep="") names(result)<-c("ICC",paste("LL CI",conf.lab),paste("UL CI",conf.lab),"SE ICC","Z","SE Z") return(result) }
52cc64080d140d7461af4769e3d843a6d7b48c43
99ffac052ed1a630a9572b166d0b1f8f1f27fa63
/Scripts/StatFunctions/rN.R
47dfff39058beb76bee985815ad2d579bcb74dc1
[]
no_license
rBatt/trawl
a253ed1cf4912c2dbf6c7599292283610f4b28a6
0d11503d900ddc5bf6777fbebcf01f585d6d264f
refs/heads/master
2021-06-04T03:50:35.595206
2016-07-13T02:29:42
2016-07-13T02:29:42
25,880,485
0
0
null
null
null
null
UTF-8
R
false
false
161
r
rN.R
# http://stackoverflow.com/questions/8664976/r-round-to-nearest-5-or-1/8665511#8665511 rN <- function(a,b){ # round a to the nearest decimal (b) round(a/b)*b }
991744a194662259f3e067a1d11f858015ea3f2d
a47ce30f5112b01d5ab3e790a1b51c910f3cf1c3
/B_analysts_sources_github/topepo/R-Ladies-London/Scat.R
536e6515a81122bd8185bb5f8f12bd73513323c7
[]
no_license
Irbis3/crantasticScrapper
6b6d7596344115343cfd934d3902b85fbfdd7295
7ec91721565ae7c9e2d0e098598ed86e29375567
refs/heads/master
2020-03-09T04:03:51.955742
2018-04-16T09:41:39
2018-04-16T09:41:39
128,578,890
5
0
null
null
null
null
UTF-8
R
false
false
9,199
r
Scat.R
##################################################################### ## Code for "Whose Scat Is That? An 'Easily Digestible' Introduction ## to Predictive Modeling in R and the caret Package" for the ## R-Ladies London RUG. Files are at ## https://github.com/topepo/R-Ladies-London library(ggplot2) theme_set(theme_bw()) plot_col <- scale_color_manual(values=c("#0072B2", "#D55E00", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#000000", "#CC79A7")) opts_chunk$set(comment=NA, digits = 3, size = 'scriptsize', prompt = TRUE, cache = FALSE, tidy = FALSE, message = FALSE, warning = FALSE, fig.path = "Figures/", background = 'white') ## A trick to make sure in-line code is formatted the same as in chunks hook_inline = knit_hooks$get('inline') knit_hooks$set(inline = function(x) { if (is.character(x)) highr::hi_latex(x) else hook_inline(x) }) ################################################################### ## Slide 5: Load Data library(caret) data(scat) str(scat) ################################################################### ## Slide 6: Missing Data Profile pct_nonmissing <- function(x) mean(!is.na(x)) unlist(lapply(scat, pct_nonmissing)) ################################################################### ## Slide 8: Split the Data set.seed(11218) in_train <- createDataPartition(scat$Species, p = 3/4, list = FALSE) head(in_train) train_data <- scat[ in_train,] test_data <- scat[-in_train,] ## It isn't much data but it's better than nothing... table(test_data$Species) ################################################################### ## Slide 9: Interaction Plot Code int_plot <- function(dat, y, x, group) { library(plyr) if(!is.factor(dat[,group])) dat[,group] <- factor(dat[,group]) means <- ddply(dat, c(y, group), function(obj) c(mean = mean(obj[,x], na.rm = TRUE))) ggplot(dat, aes_string(y = x, x = y, color = group, group = group)) + geom_point(position = position_dodge(width = 0.2)) + geom_line(data = means, aes_string(y = "mean")) + theme(legend.position = "top") } ################################################################### ## Slides 10-15 int_plot(train_data, y = "Species", x = "Mass", group = "ropey") int_plot(train_data, y = "Species", x = "Mass", group = "Location") int_plot(train_data, y = "Species", x = "Mass", group = "segmented") int_plot(train_data, y = "Species", x = "Length", group = "Location") int_plot(train_data, y = "Species", x = "Length", group = "ropey") int_plot(train_data, y = "Species", x = "CN", group = "ropey") ################################################################### ## Slide 21: An Initial Model Specification small_form <- paste("Species ~ Month + Year + Site + Age +", "Number + Length*ropey + (Location + segmented)*Mass + ", "flat + scrape") small_form <- as.formula(small_form) small_tr_dat <- train_data[, all.vars(small_form)] small_tr_dat <- small_tr_dat[complete.cases(small_tr_dat),] ################################################################### ## Slide 29: Multinomial Model ctrl <- trainControl(method = "repeatedcv", repeats = 5, classProbs = TRUE) set.seed(2592) ## locks in the resamples mnr_tune <- train(small_form, data = small_tr_dat, method = "multinom", preProc = c("center", "scale"), ## avoid regularization for now tuneGrid = data.frame(decay = 0), trControl = ctrl, ## this next argument is passed to `multinom` trace = FALSE) ################################################################### ## Slide 30: Multinomial Model mnr_tune predict(mnr_tune, head(test_data)) ## or type = "prob" ################################################################### ## Slide 31: Multinomial Model Variable Importance print(varImp(mnr_tune, scale = FALSE), top = 10) ################################################################### ## Slide 34: Multinomial Model -- All Data full_form <- paste("Species ~ Month + Year + Site + Age + Number + ", "Length*ropey + (Location + segmented)*Mass + ", "flat + scrape + ", "TI + d13C + d15N + CN + Diameter + Taper") full_form <- as.formula(full_form) set.seed(2592) mnr_impute <- train(full_form, data = train_data, method = "multinom", ## Add imputation to the list of pre-processing steps preProc = c("center", "scale", "knnImpute", "zv"), tuneGrid = data.frame(decay = 0), trControl = ctrl, ## do not remove missing data before modeling na.action = na.pass, trace = FALSE) mnr_impute ################################################################### ## Slide 36: Multinomial Model -- All Data Variable Importance print(varImp(mnr_impute, scale = FALSE), top = 10) ################################################################### ## Slide 37: Resampled Confusion Matrix confusionMatrix(mnr_tune) ################################################################### ## Slide 44: Model Tuning Grid glmn_grid <- expand.grid(alpha = c(0.05, seq(.1, 1, by = 0.025)), lambda = c(.001, .01, .1)) nrow(glmn_grid) ################################################################### ## Slide 45: Model Tuning set.seed(2592) ## use the same resamples as mnr_impute glmn_tune <- train(full_form, data = train_data, method = "glmnet", preProc = c("center", "scale", "knnImpute", "zv"), ## pass in the tuning grid tuneGrid = glmn_grid, ## pick the sub-model with the best kappa value metric = "Kappa", na.action = na.pass, trControl = ctrl) ## best sub-model results: glmn_tune$bestTune getTrainPerf(glmn_tune) ################################################################### ## Slide 46: Model Tuning Plot theme_set(theme_bw()) ggplot(glmn_tune) + theme(legend.position = "top") ################################################################### ## Slide 47: Resampled Confusion Matrix confusionMatrix(glmn_tune) ################################################################### ## Slide 49: Model Comparison compare_models(glmn_tune, mnr_impute, metric = "Kappa") ################################################################### ## Slide 50: Fitting Other Models set.seed(2592) bagged_tree <- train(Species ~ ., data = train_data, method = "treebag", metric = "Kappa", na.action = na.pass, trControl = ctrl) getTrainPerf(bagged_tree) ################################################################### ## Slide 51: Fitting Other Models set.seed(2592) knn_tune <- train(Species ~ ., data = train_data, method = "knn", preProc = c("center", "scale", "knnImpute", "zv"), ## pass in the tuning grid _size_ tuneLength = 20, metric = "Kappa", na.action = na.pass, trControl = ctrl) getTrainPerf(knn_tune) ################################################################### ## Slide 52: Preprocessing Too set.seed(2592) transformed <- train(full_form, data = train_data, method = "glmnet", ## Also transform the predictors preProc = c("center", "scale", "knnImpute", "zv", "YeoJohnson"), tuneGrid = glmn_grid, metric = "Kappa", na.action = na.pass, trControl = ctrl) getTrainPerf(transformed) ################################################################### ## Slide 53: Collecting the Results rs <- resamples(list(knn = knn_tune, bagged = bagged_tree, multinomial = mnr_impute, glmnet = glmn_tune, "glmnet + trans" = transformed)) summary(rs, metric = "Kappa") ################################################################### ## Slide 54: Resampling Distributions bwplot(rs, metric = "Kappa") ################################################################### ## Slide 55: Resampling Distributions dotplot(rs, metric = "Kappa") ################################################################### ## Slide 56: Test Set Results test_pred <- predict(glmn_tune, newdata = test_data, na.action = na.pass) str(test_pred) test_prob <- predict(glmn_tune, newdata = test_data, na.action = na.pass, type = "prob") str(test_prob) ################################################################### ## Slide 57: Test Set Results confusionMatrix(test_pred, test_data$Species)
f5026524d3737b35f0e9e01ac444fa887a5450f6
13756dddacf2e8c3c3355ad32adcf94700576a8e
/R/processLandsat.R
c96cf59da1cf93486ea9258800161368db0c338f
[ "Apache-2.0" ]
permissive
mengluchu/bfastspatial2
6e96b2b2af96448626b03cdffc584e28aa95936e
1254e661e33404d8b2ad3e5d830f864204b33a4f
refs/heads/master
2016-09-06T00:06:39.757295
2014-12-10T09:51:48
2014-12-10T09:51:48
null
0
0
null
null
null
null
UTF-8
R
false
false
5,554
r
processLandsat.R
#' @title Wrapper function to process Landsat data #' #' @description Processes a single Landsat scene, from tarball or zip archive (or hdf/tiff if untar is set to FALSE) to vegetation index. Easy to batch using sapply or mclapply for parallel implementation. Data obtained from espi may already contained pre-processed indices layers, in which case they are directly used. #' @param x Character. filename of the tarball or zip archive of the hdf/tiff file. #' @param vi Character. Vegetation index to be computed or extracted from the archive. Can be either 'ndvi', 'evi', 'savi', 'ndmi'*, 'nbr', 'nbr2'* or 'msavi'*. Indices with * need to be present in the archive. #' @param srdir Character. Directory where the tarball should be uncompressed. Can be ommited if \code{untar} is set to \code{FALSE} #' @param outdir Character. Directory where the vegetation index rasterLayer should be written. #' @param untar Logical. Is there a need to untar data, or have they been previously unpacked. #' @param delete Logical. Should surface reflectance files (hdf/tiff) be deleted after vegetation index calculated? (usefull for disk space management; surface reflectance files are very voluminous and a user may want to keep the Landsat archive in compressed format only) #' @param mask Character or NULL. The name of the mask to be applied to the bands (e.g.: \code{mask = 'fmask'}) #' @param L Numeric. Soil-adjustment factor for SAVI (ignored if vi != 'savi'). L can take on values between 0 and 1, and a default of 0.5 is typically used. #' @param ... Arguments to be passed to \link{sr2vi}. Do not specify \code{filename} since it is automatically generated #' @author Loic Dutrieux #' @return rasterLayer Object also written to file (in \code{outdir}) with an automatically generated filename #' @seealso \link{sr2vi} #' #' @import stringr #' @import raster #' @import rgdal #' @import gdalUtils #' #' @examples #' # Get list of test data files #' dir <- system.file('external', package='bfastSpatial') #' list <- list.files(dir, full.names=TRUE) #' #' # Set the location of output and intermediary directories (everything in tmpdir in that case) #' srdir <- dirout <- file.path(rasterOptions()$tmpdir, 'bfmspatial') #' dir.create(dirout, showWarning=FALSE) #' # Generate (or extract, depending on whether the layer is already in the archive or not) NDVI for the first archive file #' processLandsat(x=list[1], vi='ndvi', outdir=dirout, srdir=srdir, delete=TRUE, mask='fmask', keep=0, overwrite=TRUE) #' #' # Visualize one of the layers produced #' list <- list.files(dirout, pattern=glob2rx('*.grd'), full.names=TRUE) #' plot(r <- raster(list[1])) #' #' @export #' processLandsat <- function(x, vi='ndvi', srdir, outdir, untar=TRUE, delete=FALSE, mask=NULL, L=0.5, ...) { # x is the full path of a tarball containing the Landsat data or the path of a hdf file # hdf dir is where the hdf files are extracted # Output layers (NDVI for example) are generated in outdir # ... arguments to be passed to hdf2ndvi (filename is automatically generated and therefore does not need to be passed) # Although x can be a zip archive, Names are untar, tarlist, etc, since the function was first developped to deal with tar.gz compressed Landsat data if(untar){ ex <- extension(x) if(ex == '.gz') { tarlist <- untar(x, list=TRUE) } else if(ex == '.zip') { tarlist <- unzip(x, list=TRUE)$Name } else { stop('The archive is neither tar.gz nor .zip; we don\'t know what to do with that.') } if(any(grepl(pattern="^.*\\.hdf$", x=tarlist))) { # are there any hdf files x0 <- grep(pattern="^.*\\.hdf$", x=tarlist, value=TRUE) } else if (any(grepl(pattern="^.*\\.tif$", x=tarlist))) { # Contains tiff if(any(grepl(pattern=sprintf("^.*%s\\.tif$", vi), x=tarlist))) { # Contains pre-processed vi x0 <- grep(pattern=sprintf("^.*%s\\.tif$", vi), x=tarlist, value=TRUE) } else { # extract the bands needed to process vi # Get viFormula object (in order to know which bands to extract) if(vi == 'ndvi') { viFormula <- .ndvi() } else if(vi == 'evi') { viFormula <- .evi() } else if(vi == 'nbr') { viFormula <- .nbr() } else if(vi == 'savi') { viFormula <- .savi(L=L) } else { stop("Unsupported vi") } x0 <- grep(pattern=sprintf("^.*(%s)\\.tif$", paste(viFormula$ind, collapse='|')), x=tarlist, value=TRUE) } } else { stop("Did not find any .tif or .hdf files in the archive") } if (!is.null(mask)) { x0 <- c(x0, grep(pattern=sprintf("^.*%s\\.tif$", mask), x=tarlist, value=TRUE)) } if(ex == '.gz') { untar(x, files=x0, exdir=srdir) } else if(ex == '.zip') { unzip(x, files=x0, exdir=srdir) } x <- file.path(srdir, x0) } name <- str_extract(string=basename(x[1]), '(LT4|LT5|LE7|LC8)\\d{13}') # Filename generation (below) will have to be edited when dynamic indices will be implemented # Also note that in case of geotiff length(x)>1 sr2vi(x=x, vi=vi, filename=sprintf('%s/%s.%s.grd', outdir, vi, name), datatype='INT2S', mask=mask, ...) if(delete) { file.remove(x) } }
510bf43f4fd4ca924d9ea3384c45ced5c4827e89
3bdea023069b55b7aa2c7172e124c6e02bfeacda
/200+ beamer 模板合集/awesome-beamers(18个主题合集)/proposal thesis presentation/code/code 1/gambia地图.R
52349f774fd6f43232588f59754c54c5527b672c
[ "MIT" ]
permissive
is-xiaoyx/Awesome-Beamer-Collection
2df82009c18ba6c36f15ec6a58fbca82a9b0624d
3ab28a23fb60cb0a97fcec883847e2d8728b98c0
refs/heads/master
2022-02-13T08:10:09.167023
2019-07-22T10:00:38
2019-07-22T10:00:38
null
0
0
null
null
null
null
UTF-8
R
false
false
1,248
r
gambia地图.R
library(maps) library(mapdata) library(ggplot2) ga <- ggplot2::map_data('worldHires', 'gambia') class(ga) ggplot(ga, aes(x = long, y = lat, group = group)) + geom_polygon() library(ggfortify) ga <- map('worldHires', 'gambia', plot = FALSE, fill = TRUE) autoplot(ga) ################ p <- autoplot(ga, geom = 'polygon', fill = 'subregion') + theme(legend.position="none") p cities <- get('world.cities') cities <- cities[cities$country.etc == 'Gambia', ] head(cities) p + geom_point(data = cities, aes(x = long, y = lat), colour = 'blue', size = 0.1) library(sp) df <- data.frame(long = c(139.691704, 135.519711), lat = c(35.689521, 34.686316), label = c('Tokyo', 'Osaka'), population = c(1335, 886)) coordinates(df) <- ~ long + lat class(df) library(ggmap) bbox <- c(130.0, 30.0, 145.0, 45.0) map <- get_openstreetmap(bbox = bbox, scale = 475000) p <- ggmap(map) autoplot(df, p = p, colour = 'red', size = 'population') + scale_size_area() + theme(legend.justification = c(1, 0), legend.position = c(1, 0)) ## library(ggmap) bbox <- c(-17, 13, -13.5,14) map <- get_openstreetmap(bbox = bbox, scale = 475000) p <- ggmap(map)
966e67010fcd3cb436ca76da53bdc07edcd0ff1c
f0258ba2add23ceff662478182f91545a880f6f4
/DuguTogo/server.R
13f3600bbcef3bd8e9034815949ac5a7599f66b5
[]
no_license
mcooper/village-names
cb3e46cfe4e55f24863cbca607e18441eac9e372
329a2ddeac54dd2c58c5d9244f9e273607212775
refs/heads/master
2021-06-27T17:02:44.609077
2021-01-26T18:39:06
2021-01-26T18:39:06
64,983,725
3
0
null
null
null
null
UTF-8
R
false
false
785
r
server.R
library(maps) library(mapdata) library(stringr) vills <- readRDS('data/vills.Rda') villsearchpoints <- function(str,norm){ map(database='world',regions=c('Senegal','Guinea-Bissau','Guinea','Liberia','Sierra Leone','Ivory Coast','Niger','Mauritania','Burkina Faso','Mali','Gambia','Ghana','Benin','Togo'),xlim=c(-18,16),ylim=c(4,27)) if (norm==FALSE){ points(vills$longitude[str_detect(vills$asciiname,str)],vills$latitude[str_detect(vills$asciiname,str)],pch=19,col="red",cex=.25) } if (norm==TRUE){ points(vills$longitude[str_detect(vills$new,str)],vills$latitude[str_detect(vills$new,str)],pch=19,col="red",cex=.25) } } shinyServer( function(input, output) { output$map <- renderPlot({ villsearchpoints(toupper(input$str),input$norm) }) } )
8628452d26df6c27b7e58cc4abab2c6731cc5246
8cbc16b08945e437eab544222356c451aaf80d8f
/analysis/Fig5c-e-bulk-analyses.R
312a651faa681b63f098a4d01c045a182c802a39
[ "MIT" ]
permissive
gladelephant/singlecellglioma-verhaaklab
f18b6b77596ba9adc5696f0d3224c470d6d0ddbe
b785e86484e826d94bd9c9ac1e88cead624f1762
refs/heads/master
2023-08-19T08:27:28.521716
2021-10-01T18:03:46
2021-10-01T18:03:46
null
0
0
null
null
null
null
UTF-8
R
false
false
16,849
r
Fig5c-e-bulk-analyses.R
################################## # Investigate relationships between promoter DNAme and other variables (Klughammer et al. Nature Medicine). # Updated: 2021.05.12 # Author: Kevin J. ################################### # Working directory for this analysis. mybasedir = "/Users/johnsk/github/" setwd(mybasedir) ################################### # Necessary packages: library(tidyverse) library(DBI) library(ggpubr) library(openxlsx) library(survminer) library(survival) library(EnvStats) ################################### ## Generate plot theme. plot_theme <- theme_bw(base_size = 12) + theme(axis.title = element_text(size = 12), axis.text = element_text(size = 12), panel.background = element_rect(fill = "transparent"), axis.line = element_blank(), strip.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "black"), axis.line.y = element_line(size = 0.5, linetype = "solid", colour = "black")) ## Retrieve the chromosome arm-data for SCNA value estimates from database. con <- DBI::dbConnect(odbc::odbc(), "VerhaakDB3") chr_arms = dbReadTable(con, Id(schema="ref", table="chr_arms")) ## Load the metadata available from Klughammer (http://www.medical-epigenomics.org/papers/GBMatch/). klughammer_dat_all <- read.delim("data/GBMatch_sampleAnnotation.tsv", sep="\t", header=T, stringsAsFactors = F) klughammer_dict <- read.delim("data/GBMatch_columnAnnotation.tsv", sep="\t", header=T, stringsAsFactors = F) # Restrict to tumor tissue by removing non-tumor tissue from epilepsy patients. Add some additional filtering criteria. klughammer_dat = klughammer_dat_all %>% # A few tumors do not have IDH status and a single sample appears to have an DNAme disorder of 0. filter(tissue != "White matter", mean_pdr > 0, !is.na(IDH)) # "IDH" status separates based on IDHmut status. klughammer_idh_mut = klughammer_dat %>% filter(IDH == "mut") klughammer_idh_wt = klughammer_dat %>% filter(IDH == "wt") # Create a new variable to account for the different data types as they might relate with the idh_codel_subtype project. klughammer_dat$idh_codel_subtype <- c() klughammer_dat$idh_codel_subtype[klughammer_dat$IDH=="mut"] <- "IDHmut_noncodel" klughammer_dat$idh_codel_subtype[klughammer_dat$WHO2016_classification%in%c("Anaplastic Oligodendroglioma", "Oligo II")] <- "IDHmut_codel" klughammer_dat$idh_codel_subtype[klughammer_dat$IDH=="wt"] <- "IDHwt" ## There are clear differences across the subtypes with IDHmut tumors having a higher promoter level, but likely also greater tumor purity. kruskal.test(klughammer_dat$mean_pdr~klughammer_dat$idh_codel_subtype) # Overall, what are some factors that are related with DNAme disorder? Promoter DNAme disorder is nearly normally distributed. epi_mut_model <- glm(mean_pdr ~ Age + idh_codel_subtype + material + cohort, family = gaussian, data = klughammer_dat) summary(epi_mut_model) # There's a slight association between PDR and 1) IDHmut, 2) FFPE, and 3) cohort. ################################################## ### Somatic Copy Number Alteration (SCNA) burden ################################################## ## Investigate the relationship between SCNAs and DNAme disorder, ## First, examine general SCNA burden. klughammer_cnv = klughammer_dat %>% select(patID, surgery, id, Age, MIB, idh_codel_subtype, mean_pdr, ends_with("_amplification"), ends_with("_deletion")) %>% # Remove sex chromosomes. select(-c(X_p_amplification,X_q_amplification, Y_p_amplification, Y_q_amplification, X_p_deletion, X_q_deletion, Y_p_deletion, Y_q_deletion)) ## Calculate the total bases affected by copy number alteration. # FGA = fraction of genome with copy number alterations. klughammer_fga = klughammer_cnv %>% ## Retrieve the amplification estimates for 22 autosomes. mutate(amp_bp = apply(klughammer_cnv[, 8:49], 1, sum, na.rm=TRUE), ## Retrieve the deletion estimates for 22 autosomes. del_bp = apply(klughammer_cnv[, 50:91], 1, sum, na.rm=TRUE)) %>% select(patID, surgery, id, Age, MIB, idh_codel_subtype, mean_pdr, amp_bp, del_bp) # What's the max number of bases altered for each chromosome. We can consider this the theoretical maximum MEASURED. chrom_amp_max <- apply(klughammer_cnv[, 8:49], 2, max, na.rm=TRUE) chrom_del_max <- apply(klughammer_cnv[, 50:91], 2, max, na.rm=TRUE) ## There were 46 samples that had no amplifications or deletions. ## This would be HIGH:Y unusual in glioma so filtering out as these are likely low purity or quality. sum(klughammer_fga$del_bp==0 & klughammer_fga$amp_bp==0) ## Remove these samples from analysis, as they likely represent contaminating normal or low quality segmentations. klughammer_fga_filtered = klughammer_fga %>% # Calculate the fraction of the genome with amplifications and deletions. mutate(amp_fga = amp_bp/sum(chrom_amp_max), del_fga = del_bp/sum(chrom_del_max), # To derive total fraction of the genome measured with alterations add both features together. total_fga = amp_fga+del_fga) %>% filter(total_fga!=0, surgery%in%c(1, 2)) %>% mutate(idh_status = ifelse(idh_codel_subtype=="IDHwt", "IDHwt", "IDHmut"), timepoint = ifelse(surgery=="1", "Initial", "Recurrence")) ## Restrict to IDHwt samples that have the highest sample size needed for bulk cohort validation analyses. klughammer_fga_filtered_wt = klughammer_fga_filtered %>% filter(idh_status=="IDHwt") # Perform a statistical test to determine the association between genetic (SCNA) and epigenetic (DNAme disorder) instability. # Add back some additional covariates. SCNA seems generally positively associated with promoter DNAme disorder. disorder_fga_model <- glm(mean_pdr~ Age + total_fga, family = gaussian, data = klughammer_fga_filtered_wt) summary(disorder_fga_model) disorder_amp_model <- glm(mean_pdr~ Age + as.factor(surgery) + MIB + amp_fga, family = gaussian, data = klughammer_fga_filtered_wt) summary(disorder_amp_model) disorder_del_model <- glm(mean_pdr~ Age + as.factor(surgery) + MIB + del_fga, family = gaussian, data = klughammer_fga_filtered_wt) summary(disorder_del_model) disorder_fga_surgery_model <- glm(mean_pdr~ Age + as.factor(surgery) + MIB + total_fga, family = gaussian, data = klughammer_fga_filtered_wt) summary(disorder_fga_surgery_model) ## How many samples? (384 across all conditions) dim(klughammer_fga_filtered_wt) ## Create a bubble chart for each of these variables. Color = direction of relationship, Height -log10(p-value). variables <- c("Age", "Timepoint", "Proliferation\n(MIB staining)", "SCNA") ## P-values from disorder_fga_surgery_model results pvalues <- c(summary(disorder_fga_surgery_model)$coefficients[2,4], summary(disorder_fga_surgery_model)$coefficients[3,4], summary(disorder_fga_surgery_model)$coefficients[4,4], summary(disorder_fga_surgery_model)$coefficients[5,4]) sign <- c("-", "+", "-", "+") disorder_assoc <- data.frame(pvalues, sign, variables) disorder_assoc$variables <- factor(disorder_assoc$variables, levels = c("Age", "Timepoint", "Proliferation\n(MIB staining)", "SCNA")) ## Can demonstrate that copy number alterations are associated with DNAme disorder. pdf(file = "results/Fig5/klughammer-disorder-vars.pdf", height = 4, width = 6, bg = "transparent", useDingbats = FALSE) ggplot(disorder_assoc, aes(x=variables, y=-log10(pvalues), size = -log10(pvalues), color = sign)) + geom_point() + geom_hline(yintercept = -log10(0.05), alpha=0.8, linetype=2) + labs(x="", y = "-log10(P-value)", size="-log10(P-value)", color = "Direction of assoc.") + plot_theme + theme(axis.text.x = element_text(angle = 45, hjust = 1)) dev.off() ## It appears that the relationship is stronger for the initial IDHwt samples. This could be a bias of sample size. pdf(file = "github/results/Fig5/Fig5c-disorder-SCNA-nolegend.pdf", height = 4, width = 6, bg = "transparent", useDingbats = FALSE) ggplot(klughammer_fga_filtered_wt, aes(x=total_fga, y=mean_pdr, color=idh_status)) + geom_point() + ylab("Promoter DNAme disorder") + xlab("SCNA burden") + plot_theme + theme(legend.position="bottom", panel.spacing.x = unit(1.5, "lines")) + geom_smooth(method = "lm") + xlim(0, 1) + scale_color_manual(name='Glioma subtype', values=c('IDHmut'='#AF8DC3', "IDHwt"="#7FBF7B")) + facet_grid(. ~ timepoint, scales = "free_x", space = "free") + stat_cor(method = "spearman", label.x = 0.4) + guides(color=FALSE) dev.off() ## What's the breakdown by sample type? table(klughammer_fga_filtered_wt$timepoint) ############################################################## ### Analyze longitudinal changes in SCNA and DNAme disorder. ### How do they correlated? ############################################################## ## Create a longitudinal data frame for fraction of the genome with copy number alterations. ## Determine the longitudinal differences in FGA. long_fga = klughammer_fga_filtered %>% group_by(patID, surgery) %>% summarise(avg_total_fga = mean(total_fga), avg_mean_pdr = mean(mean_pdr)) %>% select(-avg_mean_pdr, -surgery) %>% mutate(grouped_id = row_number()) %>% spread(grouped_id, avg_total_fga) %>% filter(!is.na(`2`)) %>% mutate(aneuploidy_diff = `2`-`1`) %>% select(patID, fga_1 = `1`, fga_2 = `2`, aneuploidy_diff) # Determine the longitudinal differences in epimutation rate. long_epi_mut = klughammer_fga_filtered %>% group_by(patID, surgery) %>% summarise(avg_total_fga = mean(total_fga), avg_mean_pdr = mean(mean_pdr)) %>% select(-avg_total_fga, -surgery) %>% mutate(grouped_id = row_number()) %>% spread(grouped_id, avg_mean_pdr) %>% filter(!is.na(`2`)) %>% mutate(disorder_diff = `2`-`1`) %>% select(patID, epi_mut_1 = `1`, epi_mut_2 = `2`, disorder_diff) ## Be able to stitch together the metadata. # meta_data for all filtered samples. long_meta_data = klughammer_fga_filtered %>% select(patID, idh_codel_subtype) %>% distinct() ## There should be distinct ind. for whose genomic data passed QC. long_instability = long_fga %>% inner_join(long_epi_mut, by="patID") %>% inner_join(long_meta_data, by="patID") n_distinct(long_instability$patID) # Separate by subtype. IDHmut does not have much information. long_instability_idh_wt = long_instability %>% filter(idh_codel_subtype =="IDHwt") ## Restrict only to the IDHwt tumors to aid in clarity. pdf(file = "results/Fig5/Fig5d-longitudinal-SCNA-disorder.pdf", height = 4, width = 4, bg = "transparent", useDingbats = FALSE) ggplot(long_instability_idh_wt, aes(x=aneuploidy_diff, y=disorder_diff, color=idh_codel_subtype)) + geom_point() + ylab("Delta DNAme disorder\n (Recurrence - Initial)") + xlab("Delta SCNA burden\n(Recurrence - Initial)") + theme_bw() + geom_smooth(method = "lm") + ylim(-0.1, 0.1) + xlim(-0.5, 0.5) + guides(color=FALSE) + scale_color_manual(name='Glioma subtype', values=c("IDHwt"="#7FBF7B")) + plot_theme + stat_cor(method = "spearman", label.x = -0.5, label.y = 0.08) dev.off() ###################### ### Survival ###################### ## Retrieve survival information for these samples. klughammer_clin = klughammer_dat %>% select(patID, Age, IDH, timeToFirstProg, timeToSecSurg, VitalStatus, DateOfDeath_LastFollow.up, Follow.up_years, treatment, Sex) %>% mutate(patient_vital = ifelse(VitalStatus=="alive", 0, 1), ## All patients had a second surgery event. patient_vital_surgical_int = 1) ## Only retain the first instance for a particular patient. klughammer_clin_filt = klughammer_clin[match(unique(klughammer_clin$patID), klughammer_clin$patID), ] ## Create a set of data.frames on which to perform survival analyses. long_instability_clin_wt = long_instability %>% left_join(klughammer_clin_filt, by="patID") %>% ungroup() %>% ## Restrict to IDHwt only. filter(IDH=="wt") %>% mutate(disorder_diff_group = ifelse(disorder_diff>median(disorder_diff), "1", "0"), ## Convert days to months. timeToSecSurg.mo = timeToSecSurg/30.4167, timeToFirstProg.mo = timeToFirstProg/30.4167, primary_disorder_group = ifelse(epi_mut_1>median(epi_mut_1), "1", "0"), recurrence_disorder_group = ifelse(epi_mut_2>median(epi_mut_2), "1", "0")) ## Perform Cox-proportional hazards models with epimutation rate + Age. primary_pdr_cox <- coxph(Surv(Follow.up_years, patient_vital) ~ Age + Sex + primary_disorder_group, data = long_instability_clin_wt) summary(primary_pdr_cox) recurrent_pdr_cox <- coxph(Surv(Follow.up_years, patient_vital) ~ Age + Sex + recurrence_disorder_group, data = long_instability_clin_wt) summary(recurrent_pdr_cox) ## Delta DNAme disorder with overall survival. ## Continuous variable. diff_pdr_cox <- coxph(Surv(Follow.up_years, patient_vital) ~ Age + Sex + disorder_diff, data = long_instability_clin_wt) summary(diff_pdr_cox) ## Treated as a discrete variable. diff_pdr_cox <- coxph(Surv(Follow.up_years, patient_vital) ~ Age + Sex + disorder_diff_group, data = long_instability_clin_wt) summary(diff_pdr_cox) ## Add in the delta SCNA value to account for potential shifts in tumor purity (i.e., loss of CNVs may represent decrease in purity). diff_pdr_cox <- coxph(Surv(Follow.up_years, patient_vital) ~ Age + Sex + disorder_diff_group + aneuploidy_diff, data = long_instability_clin_wt) summary(diff_pdr_cox) ## Generate visualizations based on groupings: fit_wt_os <- survfit(Surv(Follow.up_years, patient_vital) ~ disorder_diff_group, data = long_instability_clin_wt) ggsurvplot(fit_wt_os, data = long_instability_clin_wt, risk.table = FALSE, pval= TRUE, pval.coord = c(6, 0.75), palette = c("royalblue4", "tomato3"), ylab = "Overall survival\n probability", xlab = "Time (years)") ## Examining only the primary tumor samples. fit_wt_os_primary <- survfit(Surv(Follow.up_years, patient_vital) ~ primary_disorder_group, data = long_instability_clin_wt) ggsurvplot(fit_wt_os_primary, data = long_instability_clin_wt, risk.table = FALSE, pval= TRUE, pval.coord = c(6, 0.75), palette = c("royalblue4", "tomato3"), ylab = "Overall survival\n probability", xlab = "Time (years)") ## Examining only the recurrent tumor samples. fit_wt_os_recurence <- survfit(Surv(Follow.up_years, patient_vital) ~ recurrence_disorder_group, data = long_instability_clin_wt) ggsurvplot(fit_wt_os_recurence, data = long_instability_clin_wt, risk.table = FALSE, pval= TRUE, pval.coord = c(6, 0.75), palette = c("royalblue4", "tomato3"), ylab = "Overall survival\n probability", xlab = "Time (years)") ############################################## ### Assess the "time to second surgery" ### ############################################## ## Make sure to use the separate patient vital variable for surgical interval. table(long_instability_clin_wt$patient_vital_surgical_int) pdr_surg_cox_con <- coxph(Surv(timeToSecSurg, patient_vital_surgical_int) ~ Age + Sex + disorder_diff , data = long_instability_clin_wt) summary(pdr_surg_cox_con) ## Second surgery analysis treated as a group. Doesn't change much. pdr_surg_cox_bi <- coxph(Surv(timeToSecSurg, patient_vital_surgical_int) ~ Age + Sex + disorder_diff_group, data = long_instability_clin_wt) summary(pdr_surg_cox_bi) ## The relationship gets stronger when accounting for SCNA differences. pdr_surg_cox_bi <- coxph(Surv(timeToSecSurg, patient_vital_surgical_int) ~ Age + Sex + disorder_diff_group + aneuploidy_diff, data = long_instability_clin_wt) summary(pdr_surg_cox_bi) ## Generate visualizations based on groupings: fit_wt_pdr <- survfit(Surv(timeToSecSurg.mo, patient_vital_surgical_int) ~ disorder_diff_group, data = long_instability_clin_wt) pdf(file = "results/Fig5/Fig5e-disorder-diff-secondsurg.pdf", height = 4, width = 6, bg = "transparent", useDingbats = FALSE) ggsurvplot(fit_wt_pdr, data = long_instability_clin_wt, risk.table = FALSE, pval= TRUE, pval.coord = c(30, 0.75), palette = c("royalblue4", "tomato3"), ylab = "Time to Second Surgery\n probability", xlab = "Time (months)") dev.off() #### END #####
a7ecaf7291fdeb88b42ecad7e8b485d7ca889df4
1912eacc09bcf390de60316b48c3a0ee99783b87
/primarypackage/man/createRace.Rd
0c6a580355e204377941720670558a5d8e0b89cd
[]
no_license
mau-vela/PS6
c1ffe09c321772f0dbb355f337fcd2c8aea70449
7ee1540852ce51266181c000118c4906382c1bf1
refs/heads/master
2021-01-17T20:29:04.747428
2016-03-21T08:05:31
2016-03-21T08:05:31
54,323,673
0
0
null
2016-03-20T15:01:15
2016-03-20T15:01:15
null
UTF-8
R
false
true
858
rd
createRace.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/createRace.R \name{createRace} \alias{createRace} \alias{createRace,ANY-method} \title{Create an object of class 'Race'} \usage{ createRace(Candidates, party) } \arguments{ \item{party}{Party} \item{name}{List of canidates of object class 'Candidate'} } \value{ An object of class 'Race' containing \itemize{ \item Candidates of class 'Candidate' \item party Party \item delegatesNeeded Number of delegates needed to win \item delegatesRemaining Number of delegates remaining } } \description{ Function creates an object of class 'Race' } \examples{ clinton <- createCandidate("Clinton", 1614, "Democrat") sanders <- createCandidate("Sanders", 856, "Democrat") Race <- createRace(Candidates = list(clinton, sanders), party = "Democrat") plot(Race) } \author{ Mauricio Vela }
a49bfb84cc0b89abc32da4270ae70adfff553209
6c0eb363f0da0bf2ba6c5d602f08bbdefb0ccc94
/Poster/Nigeria/Circular_Bar_Plot.R
f61b20e43a442eae9dee139bd3d621ba3c58d84a
[]
no_license
bteinstein/COVID-19-Nigeria
4831ce5f82670899820d43e77fa08d95f4267472
f202a209fa4255d9f68bef80e59ad64b99924db2
refs/heads/master
2023-03-30T14:46:08.554494
2021-04-06T21:36:49
2021-04-06T21:36:49
272,509,194
0
0
null
null
null
null
UTF-8
R
false
false
12,689
r
Circular_Bar_Plot.R
--- title: "00. Learning" author: "Babatunde Adebayo" date: "8/21/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## Basic Idea () The basic idea of this viz is circular barplot. I saw this a part of #TidyTuesday challenge contribution by Joseph Pope (Aug 18, 2020) on endangered plant. ## Recreation Attempt ```{r setup} library(tidyverse) library(extrafont) library(ggthemes) library(kableExtra) ``` ```{r data} tuesdata <- tidytuesdayR::tt_load(2020, week = 34) threats <- tuesdata$threats # readr::write_csv(tuesdata$plants, path = here::here("data",'plant.csv')) # readr::write_csv(tuesdata$actions, path = here::here("data",'actions.csv')) # readr::write_csv(tuesdata$threats, path = here::here("data",'threats.csv')) # plants <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-08-18/plants.csv') # actions <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-08-18/actions.csv') # threats <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-08-18/threats.csv') rm(tuesdata) ``` ### Explore Data Attempt to use {skimr} package to get a sense of overview about the size of your data, missing values, mean rates, and a basic histogram to show the distribution of numerical data-type columns. ```{r exploration} skimr::skim(threats) ``` - We have 500 unique plants in this dataset base on their Specie name (Genus+species) comprising of 6 taxonomic groups - They type of threats for these plants are grouped into 12 different classes - Data collected are from 72 countries in 6 continents - All variable/column are complete except year_last_seen with 180 (3%) missing values - threatened, which is the only numerical variable out of 8 variables in total is binary in nature. 1 indicates the plant is endangered (threatened with extinction) and 0 otherwise #### Exploring futher ```{r type-of-threat-vs-threat-status} threats %>% group_by(threat_type) %>% count(threatened) table(threats$threat_type, threats$threatened) ``` The data shows that the top threat to this plants are related to Agriculture & Aquaculture, Biological Resources Use, Transportation Corridor and Natural System Modification. Interestingly, Pollution is found to be the least threat factor to threaten - As expected fellow plants are really protecting themeselves in detoxification. ### Data Processing Getting data ready for visualization. - Here the focus here are threatened plants by country and continent - Saint Helena will be used as a truncted name for the Country Saint Helena, Ascension and Tristan da Cunha is too long, Basic idea here is to filter just only threatened plant, group by continents then country and count. I created two versions, one scaled count between 0-100 and unscaled count ```{r data_prep} # data_scaled data <- threats %>% filter(threatened == 1) %>% group_by(continent, country) %>% count(name = "threatened_plants", sort = TRUE) %>% ungroup() %>% mutate(continent = factor(continent), country = ifelse(str_detect(country, "Saint Helena"), "Saint Helena", country), threatened_plants = scales::rescale(threatened_plants, to = c(0, 100))) %>% filter(threatened_plants != 0) data_unscaled <- threats %>% filter(threatened == 1) %>% group_by(continent, country) %>% count(name = "threatened_plants", sort = TRUE) %>% ungroup() %>% mutate(continent = factor(continent), country = ifelse(str_detect(country, "Saint Helena"), "Saint Helena", country)) data_unscaled ``` ### Plotting Setup The goal is to create circular barplot plot with extra-sauce of grouped format structure. The extra-sauce here include some extra row space to separate groups, arc line for group labelling and smooth grid for y-axis labelling. Hence, there is a need for some data preps and geometry calculations (not to worry on this data-to-viz to the rescue). The basic steps are as follow: 1. Create empty bar rows in the data to allow grouping 2. Build labels and add to data. In this case, we will label the country per bar and use continent for the grouping. More importantly for angular geometry for labels rotation. 3. Base Data - Dataframe handles continent labelling and line arc aesthetics. 4. Grid Data - A dataframe to structure y-axis scale (It basically acts as the y-axis label) - in the case of the scaled data it will handle bar of 0-20-40-60-80 ```{r plot_setup} # Step 1 # Set a number of 'empty bar' to add at the end of each group empty_bar=3 to_add = data.frame( matrix(NA, empty_bar*nlevels(data$continent), ncol(data)) ) colnames(to_add) = colnames(data) to_add$continent = rep(levels(data$continent), each=empty_bar) data= full_join(data, to_add) %>% #rbind(data, to_add) arrange(continent) %>% mutate(id = row_number()) # Step 2 # Get the name and the y position of each label label_data=data number_of_bar=nrow(label_data) angle= 90 - 360 * (label_data$id-0.5) /number_of_bar # I substract 0.5 because the letter must have the angle of the center of the bars. Not extreme right(1) or extreme left (0) label_data$hjust<-ifelse( angle < -90, 1, 0) label_data$angle<-ifelse(angle < -90, angle+180, angle) # step 3 # prepare a data frame for base lines base_data=data %>% group_by(continent) %>% summarize(start=min(id), end=max(id) - empty_bar) %>% rowwise() %>% mutate(title=mean(c(start, end))) # Step 4 # prepare a data frame for grid (scales) grid_data = base_data grid_data$end = grid_data$end[ c( nrow(grid_data), 1:nrow(grid_data)-1)] + 1 grid_data$start = grid_data$start - 1 grid_data=grid_data[-1,] ``` ### Build Plot Most of the code are patterned on that of sample provided by data-to-viz https://www.data-to-viz.com/graph/circularbarplot.html with few modification - removing redundate code, margin correction and theme #### Scaled Data ```{r build_plot, fig.height=9, fig.width=8} p <- ggplot(data, aes(x=as.factor(id), y=threatened_plants, fill=continent)) + #NB id variable is a factor geom_bar(stat = "identity", alpha =0.5) + # Add a val=100/75/50/25 lines. I do it at the beginning to make sur barplots are OVER it. geom_segment(data=grid_data, aes(x = end, y = 80, xend = start, yend = 80), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + geom_segment(data=grid_data, aes(x = end, y = 60, xend = start, yend = 60), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + geom_segment(data=grid_data, aes(x = end, y = 40, xend = start, yend = 40), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + geom_segment(data=grid_data, aes(x = end, y = 20, xend = start, yend = 20), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + # Add text showing the value of each 100/75/50/25 lines # Modify this accordingly for an unscaled data annotate("text", x = rep(max(data$id),4), y = c(20, 40, 60, 80), label = c("20", "40", "60", "80") , color="white", size=3 , angle=0, fontface="bold", hjust=1) + # geom_bar(aes(x=as.factor(id), y=threatened_plants, fill=continent), stat="identity", alpha=0.5) + ylim(-100,120) + labs( title = "Number of Threatened Plants by Geo", subtitle = "Scaled from 0-100", caption = "Joseph Pope | @joepope44" ) + theme_minimal() + theme( legend.position = "none", axis.text = element_blank(), # Modify this to keep x or y axis text axis.title = element_blank(), panel.grid = element_blank(), plot.background = element_rect(fill = "#a3b18a"), plot.title = element_text(hjust = 0.5, size = 24, family = "Garamond"), plot.subtitle = element_text(hjust = 0.5, family = "Garamond"), plot.caption = element_text(hjust = 0.5, family = "Garamond") # plot.margin = unit(rep(-1,4), "cm") <- this hides the plot title if not commented out ) + coord_polar() + # Make it a circle # add labels - save to remove inherit.aes = FALSE (soft-deprecated I believe) geom_text(data=label_data, aes(x=id, y=threatened_plants+10, label=country, hjust=hjust), color="black", fontface="bold",alpha=0.7, size=3.5, angle= label_data$angle) + # Add base line information - Arc (a line in a polar coordinate) Then Label ( gridText Can be use to enhance text placement - say for a two line display) geom_segment(data=base_data, aes(x = start, y = -5, xend = end, yend = -5), colour = "black", alpha=0.8, size=0.6 , inherit.aes = FALSE ) + geom_text(data=base_data, aes(x = title, y = -18, label=continent), hjust=c(1,1,.5,0,0,0), colour = "black", alpha=0.8, size=4, fontface="bold", inherit.aes = FALSE) ``` ### Unscaled Data ```{r} empty_bar=3 to_add = data.frame( matrix(NA, empty_bar*nlevels(data_unscaled$continent), ncol(data_unscaled)) ) colnames(to_add) = colnames(data_unscaled) to_add$continent = rep(levels(data_unscaled$continent), each=empty_bar) data_uscl <- full_join(data_unscaled, to_add) %>% #rbind(data, to_add) arrange(continent) %>% mutate(id = row_number()) # Step 2 # Get the name and the y position of each label label_data=data_uscl number_of_bar=nrow(label_data) angle= 90 - 360 * (label_data$id-0.5) /number_of_bar # I substract 0.5 because the letter must have the angle of the center of the bars. Not extreme right(1) or extreme left (0) label_data$hjust<-ifelse( angle < -90, 1, 0) label_data$angle<-ifelse(angle < -90, angle+180, angle) # step 3 # prepare a data frame for base lines base_data=data_uscl %>% group_by(continent) %>% summarize(start=min(id), end=max(id) - empty_bar) %>% rowwise() %>% mutate(title=mean(c(start, end))) # Step 4 # prepare a data frame for grid (scales) grid_data = base_data grid_data$end = grid_data$end[ c( nrow(grid_data), 1:nrow(grid_data)-1)] + 1 grid_data$start = grid_data$start - 1 grid_data=grid_data[-1,] ``` ```{r build_plot, fig.height=8, fig.width=7} ggplot(data_uscl, aes(x=as.factor(id), y=threatened_plants, fill=continent)) + #NB id variable is a factor geom_bar(stat = "identity", alpha =0.5) + # Add a val=100/75/50/25 lines. I do it at the beginning to make sure barplots are OVER it. geom_segment(data=grid_data, aes(x = end, y = 200, xend = start, yend = 200), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + geom_segment(data=grid_data, aes(x = end, y = 150, xend = start, yend = 150), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + geom_segment(data=grid_data, aes(x = end, y = 100, xend = start, yend = 100), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + geom_segment(data=grid_data, aes(x = end, y = 50, xend = start, yend = 50), colour = "white", alpha=1, size=0.3 , inherit.aes = FALSE ) + # Add text showing the value of each 100/75/50/25 lines # Modify this accordingly for an unscaled data annotate("text", x = rep(max(data$id),4), y = c(50, 100, 150, 200), label = c("50", "100", "150", "200") , color="white", size=3 , angle=0, fontface="bold", hjust=1) + # geom_bar(aes(x=as.factor(id), y=threatened_plants, fill=continent), stat="identity", alpha=0.5) + ylim(-320,300) + # Modify Y Lim labs( title = "Number of Threatened Plants by Geo", subtitle = "Scaled from 0-100", caption = "Joseph Pope | @joepope44" ) + theme_minimal() + theme( legend.position = "none", axis.text = element_blank(), # Modify this to keep x or y axis text axis.title = element_blank(), panel.grid = element_blank(), plot.background = element_rect(fill = "#a3b18a"), plot.title = element_text(hjust = 0.5, size = 24, family = "Garamond"), plot.subtitle = element_text(hjust = 0.5, family = "Garamond"), plot.caption = element_text(hjust = 0.5, family = "Garamond") # plot.margin = unit(rep(-1,4), "cm") <- this hides the plot title if not commented out ) + coord_polar() + # Make it a circle # add labels - save to remove inherit.aes = FALSE (soft-deprecated I believe) geom_text(data=label_data, aes(x=id, y=threatened_plants+10, label=country, hjust=hjust), color="black", fontface="bold",alpha=0.7, size=3.5, angle= label_data$angle) + # Add base line information - Arc (a line in a polar coordinate) Then Label ( gridText Can be use to enhance text placement - say for a two line display) geom_segment(data=base_data, aes(x = start, y = -5, xend = end, yend = -5), colour = "black", alpha=0.8, size=0.6 , inherit.aes = FALSE ) + geom_text(data=base_data, aes(x = title, y = -18, label=continent), hjust=c(1,1,.5,0,0,0), colour = "black", alpha=0.8, size=4, fontface="bold", inherit.aes = FALSE) ```
8af9ab0cc4398cc0cd836d2990d6f6883e349446
b234deb3176fcfbf8c72628350cf12f4a0508349
/xCell/Dev_scripts/xCell_train_functions.R
232cd1e6ecc93561f31627475d0b06add32f3786
[]
no_license
tsofiya/xCell2-old
23fc210c70b3484a1b8d4c0bf601304df1617dba
8b15fd7abd3686d5c157d749b6f68dcb54077871
refs/heads/master
2023-04-30T00:39:20.834379
2021-05-13T06:27:57
2021-05-13T06:27:57
null
0
0
null
null
null
null
UTF-8
R
false
false
2,871
r
xCell_train_functions.R
library(GSVA) library(GSEABase) library(pracma) library(RColorBrewer) library(pheatmap) read.types.dependencies = function(file.name) { con <- file(file.path(file.name), open = "r") out <- list() i=1 while (length(oneLine <- readLines(con, n = 1, warn = FALSE)) > 0) { vec <- unlist(strsplit(oneLine, "\t")) out$types[i] = vec[1] n = max(which(!(vec==""))) if (n<2) out$dep[i] = list(types="") else out$dep[i] = list(types=vec[2:n]) i=i+1 } close(con) out } create.signatures = function(ref,dependencies){ probs = c(.1,.25,.33333333,.5,.6666666,.75,.9) diff_vals = c(0, 0.1, 0.585, 1, 1.585, 2,3,4,5) types=unique(colData(ref)$label.main) #TODO: add dependencies message('get quantiles...') q = lapply(types,function(y){ q = apply(assays(ref)$logcounts,1,function(z) quantile(z,probs,na.rm=TRUE)) }) message('create all signatures...') ntypes= length(types) signature= data.frame(ref@colData) listIn= list() for (i in 1:ntypes) { for (diff in diff_vals) { for (j in 1:round(length(probs)/2+0.5)) { diff_genes = lapply(q,function(x) q[[i]][j,]>x[length(probs)-j,]+diff) output <- matrix(unlist(diff_genes), nrow = ntypes, byrow = TRUE) for (n in (ntypes-1):(ntypes-3)) { g = colSums(output)>=n if (sum(g)>7 & sum(g)<201){ gs=GeneSet(rownames(ref)[g], setName=sprintf("%%%s%%j%g%%d%g%%n%g",toupper(colnames(ref)[i]),round(probs[j]*100),diff,ntypes-n, sep="\t",row.names=FALSE,quote =FALSE,col.names = FALSE)) listIn<-c(listIn, gs) } # write.table(rownames(ref)[g],file=file.path(working.dir,'signatures', # sprintf("%%%s%%j%g%%d%g%%n%g.txt",toupper(colnames(ref)[i]),round(probs[j]*100),diff,ntypes-n)),sep="\t",row.names=FALSE,quote =FALSE,col.names = FALSE) } } } } gsc= GeneSetCollection(listIn) return gsc } score.ref.signatures = function(ref,working.dir) { dir.create(file.path(working.dir, 'scores'), showWarnings = FALSE) egc = read.signatures.dir(paste0(file.path(working.dir,'signatures'))) scores = gsva(as.matrix(assays(ref)$logcounts),egc,method='ssgsea',ssgsea.norm=FALSE) write.table(scores,file=file.path(paste0(working.dir,"scores",paste(ref@colData$label.main,"_ssgsea.txt"))),sep="\t",row.names=TRUE,quote =FALSE,col.names = NA) } # TODO: delete this when replacing files with objects. read.signatures.dir = function(path) { sig = list() files = list.files(path=path) for (i in 1:length(files)) { sig[i] = GeneSet(scan(paste0(path,'/',files[i]), what="", sep="\n"), setName=files[i]) } signatures <- GeneSetCollection(sig) #toGmt(signatures,'~/Documents/signatures/Mouse/signatures.txt') signatures }
e25ca5fb238ba2673157787634a8e2a0124e44d0
a1240975d6bcdbe14fe32c1f92139636d415ca8d
/man/read_statGenGroupOutFile.Rd
e9b683fa328f66d67b5de296499b36df80d069b3
[]
no_license
pvrqualitasag/qgengroup
56eccd0cac9080643b8aec48e6d68caacd8b1497
6ecb06d1ca1b75f39281b4a57392675dc4538008
refs/heads/master
2020-12-10T14:43:29.105294
2020-01-16T12:43:30
2020-01-16T12:43:30
233,622,368
0
0
null
null
null
null
UTF-8
R
false
true
417
rd
read_statGenGroupOutFile.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ReadGG.R \name{read_statGenGroupOutFile} \alias{read_statGenGroupOutFile} \title{Reading statistics on missing parents} \usage{ read_statGenGroupOutFile(psInputFile, pbLog = FALSE) } \arguments{ \item{psInputFile}{file including number of missing parents per year and breed} } \description{ Read a table of statistics on missing parents }
343fc46d3486e1d67bd50da71a0e23f0f89f724d
386cb146e762d1940f1e36d0b0d183072d6cc969
/NBA_Fan_Engagement_on_Twitter/Analysis.R
51347d71ee95b749c9f1bbea775dccf93dc4d30b
[]
no_license
coderita/MSc_Business_Analytics_Portfolio
2e448c52e7bcfd6eb6f059b3ff1a7cc0c9b2f7d8
32bc59d465d8c34d055b04243e5d0ee26ff9370d
refs/heads/main
2023-08-01T14:44:48.376901
2021-09-18T00:47:13
2021-09-18T00:47:13
null
0
0
null
null
null
null
UTF-8
R
false
false
32,998
r
Analysis.R
#' --- #' title: "Text Analysis: NBA Fan Engagement via Twitter" #' author: "by Jack Daoud" #' output: #' html_notebook: #' number_sections: yes #' theme: readable #' highlight: pygments #' toc: yes #' toc_float: #' collapsed: no #' html_document: #' toc: yes #' df_print: paged #' --- #' ## ----options & packages, message=FALSE, warning=FALSE, include=FALSE------------------------------------------- # REMOVE # to install packages #install.packages("plyr") #install.packages("qdap") #install.packages("tm") #install.packages("docstring") #install.packages("ggthemes") #install.packages("lubridate") #install.packages('dendextend') #install.packages('circlize') #install.packages("magrittr") #install.packages('wordcloud') #install.packages('wordcloud2') # load Packages lapply(c("lubridate", "plyr", "stringi", "ggdendro", 'dendextend', 'circlize', "qdap", "tm", "docstring", "ggthemes", 'magrittr', 'ggplot2', 'dplyr', 'readr', 'stringr', 'tidyr', 'ggalt', 'plotrix', 'wordcloud'), library, character.only = TRUE) # set options options(stringsAsFactors = FALSE) Sys.setlocale('LC_ALL', 'C') set.seed(123) # set working directory #setwd('./personal/case_NBA') #' #' # Data Exploration #' #' ## Import #' ## ----import & sample data, message=FALSE, warning=FALSE-------------------------------------------------------- # import and merge all data sets Oct 2019-20 data_directory <- "./_data/original" csv_files <- list.files(path = data_directory, pattern = "*.csv", full.names = TRUE) tweets <- ldply(csv_files, read_csv) # take a sample of 1% tweets <- slice_sample(tweets, prop = 0.01) # export tweet sample write.csv(tweets,'./_data/manipulated/tweets_sample.csv', row.names = F) #' #' ## Wrangle #' ## ----data wrangling, message=FALSE, warning=FALSE-------------------------------------------------------------- # import tweet sample tweets <- read_csv('./_data/manipulated/tweets_sample.csv') ################################################################################ # Create placeholder for Region column tweets$region <- '' # Loop through each row and match teams with their respective region for (i in 1:nrow(tweets)) { if (tweets[i, "team"] == "Boston Celtics" | tweets[i, "team"] == "Brooklyn Nets" | tweets[i, "team"] == "New York Knicks" | tweets[i, "team"] == "Philadelphia Sixers" | tweets[i, "team"] == "Toronto Raptors") { tweets[i, "region"] <- "Atlantic" } else if (tweets[i, "team"] == "Chicago Bulls" | tweets[i, "team"] == "Cleveland Cavaliers" | tweets[i, "team"] == "Detroit Pistons" | tweets[i, "team"] == "Indiana Pacers" | tweets[i, "team"] == "Milwaukee Bucks") { tweets[i, "region"] <- "Central" } else if (tweets[i, "team"] == "Atlanta Hawks" | tweets[i, "team"] == "Charlotte Hornets" | tweets[i, "team"] == "Miami Heat" | tweets[i, "team"] == "Orlando Magic" | tweets[i, "team"] == "Washington Wizards") { tweets[i, "region"] <- "Southeast" } else if (tweets[i, "team"] == "Denver Nuggets" | tweets[i, "team"] == "Minnesota Timberwolves" | tweets[i, "team"] == "Oklahoma City Thunder" | tweets[i, "team"] == "Portland Trail Blazers" | tweets[i, "team"] == "Utah Jazz") { tweets[i, "region"] <- "Northwest" } else if (tweets[i, "team"] == "Golden State Warriors" | tweets[i, "team"] == "LA Clippers" | tweets[i, "team"] == "LA Lakers" | tweets[i, "team"] == "Phoenix Suns" | tweets[i, "team"] == "Sacramento Kings") { tweets[i, "region"] <- "Pacific" } else if (tweets[i, "team"] == "Dallas Mavericks" | tweets[i, "team"] == "Houston Rockets" | tweets[i, "team"] == "Memphis Grizzlies" | tweets[i, "team"] == "New Orleans Pelicans" | tweets[i, "team"] == "San Antonio Spurs") { tweets[i, "region"] <- "Southwest" } } ################################################################################ # Feature engineering date & time values tweets <- tweets %>% rename(timestamp = created) tweets$year <- year(tweets$timestamp) tweets$month <- month(tweets$timestamp, label = T) tweets$day <- day(tweets$timestamp) tweets$weekday <- wday(tweets$timestamp, label = T) tweets$hour <- hour(tweets$timestamp) # remove Sep 2019 tweets so upcoming tweets per month plot tweets <- tweets %>% filter(year != 2019 | month != 'Sep') ################################################################################ # Export wrangled data write.csv(tweets,'./_data/manipulated/tweets_sample_wrangled.csv', row.names = F) #' #' ## Data Overview Plots #' #' **Tweets per Region not used in presentation** #' ## ----high level data exploration, message=FALSE, warning=FALSE------------------------------------------------- # import wrangled tweets tweets <- read_csv('./_data/manipulated/tweets_sample_wrangled.csv') # Ordinal factors tweets$month <- factor(tweets$month, levels = c('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) tweets$weekday <- factor(tweets$weekday, levels = c('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')) tweets$year <- factor(tweets$year, levels = c('2019', '2020')) ################################################################################ # plot tweets per month tweets_per_month <- tweets %>% group_by(month, year) %>% summarize(count = n()) %>% ggplot(., aes(x = month, y = count, fill = year)) + geom_bar(stat = 'identity') + scale_fill_manual(values=c("#2E86C1", "#201449")) + geom_text(aes(label=count), position = "stack", vjust=-0.7, size=3) + theme(legend.background = element_rect(fill="transparent", colour=NA), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.line = element_line(colour = "black"), axis.text = element_text(face="bold", color="#000000", size=10), axis.text.x = element_text(angle = 45, hjust = 1), axis.title = element_text(face="bold", color="#000000", size=12), plot.title = element_text(face="bold", color="#000000", size=16)) + labs(title = "Tweets per Month", x = "Month", y = "Count", fill = "Year") + theme(plot.title = element_text(hjust = 0.5)) # save plot ggsave("./_images/tweets_per_month.png", tweets_per_month, bg = "transparent") ################################################################################ # plot tweets per region tweets_per_region <- tweets %>% group_by(region, team) %>% summarize(count = n()) %>% arrange(desc(count)) %>% ggplot(., aes(x = reorder(region, -count), y = count), color="black") + geom_bar(stat = 'identity', fill = '#FFFFFF', color = "black") + #scale_fill_manual(values = c('#E03A3E', '#007A33', '#FFFFFF', '#1D1160', # '#CE1141', '#860038', '#00538C', '#0E2240', # '#C8102E', '#FFC72C', '#CE1141', '#002D62', # '#C8102E', '#552583', '#5D76A9', '#98002E', # '#00471B', '#0C2340', '#236192', '#F58426', # '#007AC1', '#0077C0', '#006BB6', '#1D1160', # '#E03A3E', '#5A2D81', '#E03A3E', '#5A2D81', # '#C4CED4', '#CE1141', '#002B5C', '#002B5C')) + geom_text(aes(label=count), position = "stack", vjust=-0.7, size=3) + theme(legend.background = element_rect(fill="transparent", colour=NA), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.line = element_line(colour = "black"), axis.text = element_text(face="bold", color="#000000", size=10), axis.text.x = element_text(angle = 45, hjust = 1), axis.title = element_text(face="bold", color="#000000", size=12), plot.title = element_text(face="bold", color="#000000", size=16)) + labs(title = "Tweets per Region", x = "Region", y = "Count", fill = "Teams") + theme(plot.title = element_text(hjust = 0.5)) # save plot ggsave("./_images/tweets_per_region.png", tweets_per_region, bg = "transparent") #' #' #' # Corpus Preprocessing #' #' ## Define Stop Words #' ## ----stop words, message=FALSE, warning=FALSE------------------------------------------------------------------ nbaStopwords = c('nba','teams','fans','live','games','points','pacers', 'pts', 'year','back','coach','tonight','city','time','today', 'season','win','state','basketball','team','game','sports', 'play', 'player', 'players', 'played', 'playoff', 'playing', 'won', 'fan', 'lead', 'series', 'playoffs', 'star', 'home', 'center', 'championship', 'jersey', 'point', 'draft', 'loss', 'quarter', 'lost', 'highlights', 'winning', 'reb', 'tickets', 'allstar', 'national', 'arena', 'rankings', 'rookie', 'wins', 'round', 'rebounds', 'told', 'ball', 'swingman') # print team names for nba_stopwords #team_names <- as.character(unique(unlist(tweets$team))) #team_names <- tryTolower(team_names) #team_names <- scan(text = team_names, what = "") #team_names <- paste0(team_names, sep = "'", collapse=",'") #team_names teamStopwords <- c('la','clippers','denver','nuggets','boston','celtics', 'brooklyn','nets','chicago','bulls','portland','trail', 'blazers','philadelphia','sixers','milwaukee','bucks','san', 'antonio','spurs','la','lakers','sacramento','kings', 'miami','heat','indiana','pacers','toronto','raptors', 'atlanta','hawks','golden','state','warriors','utah', 'jazz','dallas','mavericks','houston','rockets','orlando', 'magic','detroit','pistons','charlotte','hornets', 'minnesota','timberwolves','cleveland','cavaliers', 'new','york','knicks','memphis','grizzlies','phoenix', 'suns','new','orleans','pelicans','oklahoma','city', 'thunder','washington','wizards', 'los', 'angeles') abbreviationStopwords = c('lol', 'smh', 'rofl', 'lmao', 'lmfao', 'wtf', 'btw', 'nbd','nvm', 'lmk', 'kk', 'obvi', 'obv', 'srsly', 'rly', 'tmi', 'ty', 'tyvm', 'yw', 'fomo', 'ftw', 'icymi', 'icyww', 'ntw', 'omg', 'omfg', 'idk', 'idc', 'jell', 'iirc', 'ffs', 'fml', 'idgaf', 'stfu', 'tf', 'omw', 'rn', 'ttyl', 'tyt', 'bball') # from https://stylecaster.com/social-media-acronyms-abbreviations-what-they-mean/ # These are stopwords that I've identified after making visualizations iterativeStopwords <- c('amp', 'years', 'beat', 'ufc', 'day', 'night', 'league', 'finals', 'watch', 'espn', 'guard', 'trade', 'pick', 'free', 'ago', 'head', 'big', 'center', 'love', 'ufa', 'make', 'itus', 'ers', 'theu', 'man', 'conference', 'forward', 'history', 'donut', 'ium', 'made', 'great', 'deal', 'harden', 'owner', 'full', 'news', 'ast', 'thu', 'left', 'breaking', 'bubble', 'uff', 'power', 'usa', 'assistant', 'contract', 'starting', 'video', 'sources', 'good', 'ufb', 'le', 'ad', 'de', 'uf', 'nbachallengefr', 'hu', 'makes', 'ua', 'ufd', 'gt', 'ufecu', 'check', 'nwt', 'blanku', 'grizzliesfr', 'stream', 'top', 'final', 'record', 'people', 'week', 'young', 'edition', 'gagnez', 'concours', 'maillot', 'ownsu', 'green', 'closet', 'closet', 'red', 'blue', 'yellow', 'white', 'size', 'medium', 'xl', 'xxl', 'xlarge', 'million', 'air', 'large', 'small', 'color', 'retweet', 'black') customStopwords <- c( stopwords('english'), stopwords('SMART'), nbaStopwords, teamStopwords, abbreviationStopwords, iterativeStopwords) #' #' ## Preprocessing Functions #' ## ----define text processing functions, message=FALSE, warning=FALSE-------------------------------------------- ################################################################################ tryTolower <- function(text_column) { #' Returns NA instead of tolower error y = NA # tryCatch error try_error = tryCatch(tolower(text_column), error = function(e) e) # if not an error if (!inherits(try_error, 'error')) y = tolower(text_column) return(y) } ################################################################################ basicSubs <- function(text_column) { #' Run a variety of text cleaning functions #' #' Remove URLs, RTs, and non-ASCII text (i.e emojis) #' Remove punctuation #' Lower all text (case wise) text_column <- gsub('http\\S+\\s*', '', text_column) text_column <- gsub('(RT|via)((?:\\b\\W*@\\w+)+)', '', text_column) text_column <- gsub("[^\x01-\x7F]", '', text_column) text_column <- str_replace_all(text_column, "[[:punct:]]", " ") text_column <- tryTolower(text_column) return(text_column) } ################################################################################ cleanCorpus <- function(corpus, customStopwords) { #' Run a variety of corpus cleaning functions #' #' Functions that run: #' - Remove numbers #' - Remove punctuation #' - Strip white space #' - Remove stopwords # corpus <- tm_map(corpus, content_transformer(replace_contraction)) corpus <- tm_map(corpus, removeNumbers) corpus <- tm_map(corpus, stripWhitespace) corpus <- tm_map(corpus, removePunctuation) # corpus <- tm_map(corpus, content_transformer(tryTolower)) corpus <- tm_map(corpus, removeWords, customStopwords) return(corpus) } ################################################################################ # correct spelling function #correct_spelling <- function(text_column) { # check <- check_spelling(text_column) # splitted <- strsplit(text_column, split=' ') # for (i in 1:length(check$row)) { # splitted[[check$row[i]]][as.numeric(check$word.no[i])] = check$suggestion[i] # } # df <- unlist(lapply(splitted, function(x) paste(x, collapse = ' '))) # return(df) #} # Did not include this function because the trade off in terms of accuracy is too high ################################################################################ cleanMatrix <- function(pth, columnName, collapse = F, customStopwords, type, wgt){ print(type) if(grepl('.csv', pth, ignore.case = T)==T){ print('reading in csv') text <- read.csv(pth) text <- text[,columnName] } if(grepl('.fst', pth)==T){ print('reading in fst') text <- fst::read_fst(pth) text <- text[,columnName] } if(grepl('csv|fst', pth, ignore.case = T)==F){ stop('the specified path is not a csv or fst') } if(collapse == T){ text <- paste(text, collapse = ' ') } print('cleaning text') txtCorpus <- VCorpus(VectorSource(text)) txtCorpus <- cleanCorpus(txtCorpus, customStopwords) if(type =='TDM'){ if(wgt == 'weightTfIdf'){ termMatrix <- TermDocumentMatrix(txtCorpus, control = list(weighting = weightTfIdf)) } else { termMatrix <- TermDocumentMatrix(txtCorpus) } response <- as.matrix(termMatrix) } if(type =='DTM'){ if(wgt == 'weightTfIdf'){ termMatrix <- DocumentTermMatrix(txtCorpus, control = list(weighting = weightTfIdf)) } else { termMatrix <- DocumentTermMatrix(txtCorpus) } response <- as.matrix(termMatrix) if(grepl('dtm|tdm', type, ignore.case=T) == F){ stop('type needs to be either TDM or DTM') } } print('complete!') return(response) } ################################################################################ bigramTokens <- function(x) { unlist(lapply(NLP::ngrams(words(x), 2), paste, collapse = " "), use.names = F) } #' #' #' ## Corpus & TDM #' ## ----create, clean & export corpus, message=FALSE, warning=FALSE----------------------------------------------- # import wrangled tweets sample tweets <- read_csv('./_data/manipulated/tweets_sample_wrangled.csv') # Partially text column & save partially cleaned data tweets$text <- basicSubs(tweets$text) partially_cleaned_tweets <- tweets # Export partially cleaned tweets as csv write.csv(partially_cleaned_tweets,'./_data/manipulated/partially_cleaned_tweets.csv', row.names = F) # Create a volatile corpus tweetCorpus <- VCorpus(DataframeSource(tweets)) # Clean the corpus tweetCorpus <- cleanCorpus(tweetCorpus, customStopwords) # Save corpus as dataframe cleaned_corpora <- data.frame(text = unlist(sapply(tweetCorpus, `[`,"content")), stringsAsFactors=F) # Export corpus as dataframe in csv format write.csv(cleaned_corpora,'./_data/manipulated/cleaned_corpora.csv', row.names = F) # Convert corpus into Term Document Matrix tweetTDM <- TermDocumentMatrix(tweetCorpus) tweetTDMm <- as.matrix(tweetTDM) #' #' ## Bigram TDM #' ## ----create bigram df, corpus, & TDM--------------------------------------------------------------------------- # Reduce size in order to process bigram TDM bigram_tweets <- slice_sample(tweets, prop = 0.1) # Create a volatile bigram corpus bigramCorpus <- VCorpus(DataframeSource(bigram_tweets)) # Clean the bigram corpus bigramCorpus <- cleanCorpus(bigramCorpus, customStopwords) # Create a bigram TDM bigramTDM <- TermDocumentMatrix(bigramCorpus, control=list(tokenize=bigramTokens)) bigramTDMm <- as.matrix(bigramTDM) #' #' #' # Visualizations #' #' ## Share of Brand #' ## ----share of brand, message=FALSE, warning=FALSE-------------------------------------------------------------- # Import cleaned corpora #cleaned_corpora <- read_csv('./_data/manipulated/cleaned_corpora.csv') # calculate frequency per brand adidas <- sum(stri_count(cleaned_corpora$text, fixed ='adidas')) nike <- sum(stri_count(cleaned_corpora$text, fixed ='nike')) under_armour <- sum(stri_count(cleaned_corpora$text, fixed ='armour')) reebok <- sum(stri_count(cleaned_corpora$text, fixed ='reebok')) puma <- sum(stri_count(cleaned_corpora$text, fixed ='puma')) # create data frame of brand & frequencies brandFreq <- data.frame(terms = c('Adidas','Nike', 'Under Armour', 'Reebok', 'Puma'), freq = c(adidas, nike, under_armour, reebok, puma)) # plot share of brand mentions_per_brand <- ggplot(brandFreq, aes(x = reorder(terms, freq), y = freq, fill=freq)) + geom_bar(stat = "identity") + coord_flip() + theme_gdocs() + geom_text(aes(label=freq), position = "stack", hjust = -0.1, size = 4) + theme(legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.line = element_line(colour = "black"), axis.text = element_text(face="bold", color="#000000", size=10), axis.title = element_text(face="bold", color="#000000", size=12), plot.title = element_text(face="bold", color="#000000", size=16)) + expand_limits(y = 200) + labs(title = "Mentions per Brand", x = "Brand", y = "Frequency") + theme(plot.title = element_text(hjust = 0.5)) # save image ggsave("./_images/mentions_per_brand.png", mentions_per_brand, bg = "transparent") #' #' ## Word Frequency #' #' **Unigram & Bigram top names plots not used in presentation** #' #' ### Unigram #' ## ----unigram frequencies, message=FALSE, warning=FALSE--------------------------------------------------------- # Frequency Data Frame tweetSums <- rowSums(tweetTDMm) tweetFreq <- data.frame(word=names(tweetSums),frequency=tweetSums) rownames(tweetFreq) <- NULL # Top Names unigram_topNames <- subset(tweetFreq, tweetFreq$frequency > 500) unigram_topNames$word <- stri_trans_totitle(unigram_topNames$word) unigram_topNames <- unigram_topNames[order(unigram_topNames$frequency, decreasing=F),] unigram_topNames$word <- factor(unigram_topNames$word, levels=unique(as.character(unigram_topNames$word))) # Plot top names as bar plot unigrams_top_names<- ggplot(unigram_topNames, aes(x=word, y=frequency, fill=frequency)) + geom_bar(stat="identity") + coord_flip() + theme_gdocs() + geom_text(aes(label=frequency), colour="black",hjust=-0.25, size=3.3) + theme_gdocs() + theme(legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.line = element_line(colour = "black"), axis.text = element_text(face="bold", color="#000000", size=10), axis.title = element_text(face="bold", color="#000000", size=13), plot.title = element_text(face="bold", color="#000000", size=16)) + expand_limits(y = 1200) + labs(title = "Top Names of the 2019-20 NBA Season", x = "Names", y = "Frequency") + theme(plot.title = element_text(hjust = 0.3, vjust = 1), axis.title.y = element_text(hjust = 1, vjust = 1.2)) # save image ggsave("./_images/top_names_unigrams.png", unigrams_top_names, bg = "transparent") #' #' ### Bigram #' ## ----bigram frequencies, message=FALSE, warning=FALSE---------------------------------------------------------- # Frequency Data Frame bigramSums <- rowSums(bigramTDMm) bigramFreq <- data.frame(word=names(bigramSums),frequency=bigramSums) rownames(bigramFreq) <- NULL # Top Names bigram_topNames <- subset(bigramFreq, bigramFreq$frequency > 18) bigram_topNames$word <- stri_trans_totitle(bigram_topNames$word) bigram_topNames <- bigram_topNames[order(bigram_topNames$frequency, decreasing=F),] bigram_topNames$word <- factor(bigram_topNames$word, levels=unique(as.character(bigram_topNames$word))) # Plot top names as bar plot bigrams_top_names <- ggplot(bigram_topNames, aes(x=word, y=frequency, fill = frequency)) + geom_bar(stat="identity") + coord_flip() + theme_gdocs() + geom_text(aes(label=frequency), colour="black",hjust=-0.25, size=3.3) + theme_gdocs() + theme(legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.line = element_line(colour = "black"), axis.text = element_text(face="bold", color="#000000", size=10), axis.title = element_text(face="bold", color="#000000", size=13), plot.title = element_text(face="bold", color="#000000", size=16)) + expand_limits(y = 60) + labs(title = "Top Names of the 2019-20 NBA Season", x = "Names", y = "Frequency") + theme(plot.title = element_text(hjust = -0.5, vjust = 1), axis.title.y = element_text(hjust = 1, vjust = 1.2)) # save image ggsave("./_images/top_names_bigrams.png", bigrams_top_names, bg = "transparent") #' #' #' ## Word Clouds #' ## ----word clouds, message=FALSE, warning=FALSE----------------------------------------------------------------- #cleaned_corpora <- read_csv('./_data/manipulated/cleaned_corpora.csv') # worldcloud of words associated with Nike nike_wordcloud<- word_associate(cleaned_corpora$text, match.string = 'nike', stopwords = c(customStopwords), min.freq = 5, wordcloud = T, caps = T, cloud.colors = c('black','darkblue')) # wordcloud of words associated with Adidas adidas_wordcloud<- word_associate(cleaned_corpora$text, match.string = 'adidas', stopwords = c(customStopwords), min.freq = 3, wordcloud = T, caps = T, cloud.colors = c('black','darkred')) # General word cloud of cleaned corpus wordcloud(words = tweetFreq$word, freq = tweetFreq$frequency, min.freq = 7, random.order = F, rot.per = 0.35, colors = c('black', 'darkred','darkblue'), use.r.layout = T) #' #' ## Word Associations #' ## ----word associations, message=FALSE, warning=FALSE----------------------------------------------------------- ################################################################################ # Nike associations nikeAssociations <- findAssocs(tweetTDM, 'nike', 0.15) # Organize the word associations nikeAssocDF <- data.frame(terms=names(nikeAssociations[[1]]), value=unlist(nikeAssociations)) nikeAssocDF$terms <- factor(nikeAssocDF$terms, levels=nikeAssocDF$terms) rownames(nikeAssocDF) <- NULL # Make a dot plot nikeAssocPlot <- ggplot(nikeAssocDF, aes(y=terms)) + geom_point(aes(x=value), data=nikeAssocDF, col='#00008b') + theme_gdocs() + geom_text(aes(x=value,label=value), colour="darkblue",hjust=-0.5, vjust ="inward" , size=3) + labs(title = "Nike Associations", x = 'Association Level', y = 'Terms') + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position = "none", panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.text = element_text(face="bold", color="#000000", size=10), axis.title = element_text(face="bold", color="#000000", size=12), plot.title = element_text(face="bold", color="#000000", size=16)) + expand_limits(x = 0.3) # save image ggsave("./_images/associations_nike.png", nikeAssocPlot, bg = "transparent") ################################################################################ # Adidas associations adidasAssociations <- findAssocs(tweetTDM, 'adidas', 0.15) # Organize the word associations adidasAssocDF <- data.frame(terms=names(adidasAssociations[[1]]), value=unlist(adidasAssociations)) adidasAssocDF$terms <- factor(adidasAssocDF$terms, levels=adidasAssocDF$terms) rownames(adidasAssocDF) <- NULL # Make a dot plot adidasAssocPlot <- ggplot(adidasAssocDF, aes(y = terms)) + geom_point(aes(x = value), data = adidasAssocDF, col = '#8b0000') + theme_gdocs() + geom_text(aes(x=value,label=value), colour = "darkred", hjust = -0.5, vjust = "inward", size = 3) + labs(title = "Adidas Associations", x = 'Association Level', y = 'Terms') + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position = "none", panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.text = element_text(face="bold", color="#000000", size=10), axis.title = element_text(face="bold", color="#000000", size=12), plot.title = element_text(face="bold", color="#000000", size=16)) + expand_limits(x = 0.35) # save image ggsave("./_images/associations_adidas.png", adidasAssocPlot, bg = "transparent") #' #' ## Dendograms #' #' **Not used in Presentation** #' ## ----NOT USED dendrogram, message=FALSE, warning=FALSE--------------------------------------------------------- # Reduce corpus by removing documents with more than 99.5% 0 terms reducedTDM <- removeSparseTerms(tweetTDM, sparse=0.993) reducedTDM <- as.data.frame(as.matrix(reducedTDM)) # Plot hierarchical dendogram hierarchical_cluster <- hclust(dist(reducedTDM)) ggdendrogram(hierarchical_cluster, yaxt='n', rotate = F) + labs(title = "NBA Dendogram", x = 'Terms', y = 'Frequency') + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", colour=NA), axis.text = element_text(face="bold", color="#000000", size=10), axis.title = element_text(face="bold", color="#000000", size=12), plot.title = element_text(face="bold", color="#000000", size=16)) # Create function to color clusters of dendogram dend_change <- function(n) { if (is.leaf(n)) { a <- attributes(n) labCol <- labelColors[clusMember[which( names(clusMember) == a$label)]] attr(n, 'nodePar') <- c(a$nodePar, lab.col = labCol) } n } # Plot a Hierarchical dendogram with colored clusters hierarchical_cluster_dendogram <- as.dendrogram(hierarchical_cluster) clusMember <- cutree(hierarchical_cluster, 4) labelColors <- c('darkgrey', 'darkred', 'black', '#bada55') clusDendro <- dendrapply(hierarchical_cluster_dendogram, dend_change) plot(clusDendro, main = "NBA Dendogram",type = "triangle",yaxt='n') # Plot circular dendogram hierarchical_cluster_dendogram <- color_labels(hierarchical_cluster_dendogram, 4, col = c('#bada55','darkgrey', "black", 'darkred')) hierarchical_cluster_dendogram <- color_branches(hierarchical_cluster_dendogram, 4, col = c('#bada55','darkgrey', "black", 'darkred')) circlize_dendrogram(hierarchical_cluster_dendogram, labels_track_height = 0.4, dend_track_height = 0.3) #' #' ## Pyramid Plot #' ## ----adidas vs nike, message=FALSE, warning=FALSE-------------------------------------------------------------- # Import cleaned tweets #partially_cleaned_tweets <- # read_csv('./_data/manipulated/partially_cleaned_tweets.csv') # Create data frames containing 'nike' and 'adidas' nike_df <- partially_cleaned_tweets[ str_detect(partially_cleaned_tweets$text, "nike"), ] adidas_df <- partially_cleaned_tweets[ str_detect(partially_cleaned_tweets$text, "adidas"), ] # Export above dataframes write.csv(nike_df,'./_data/manipulated/nike.csv', row.names = F) write.csv(adidas_df,'./_data/manipulated/adidas.csv', row.names = F) # Read in data, clean & organize textA <- cleanMatrix(pth = './_data/manipulated/nike.csv', columnName = 'text', collapse = T, customStopwords = c(customStopwords, 'nike'), type = 'TDM', wgt = 'weightTf') # weightTfIdf or weightTf textB <- cleanMatrix(pth = './_data/manipulated/adidas.csv', columnName = 'text', collapse = T, customStopwords = c(customStopwords, 'adidas'), type = 'TDM', wgt = 'weightTf') # Create merged data set pyramid_df <- merge(textA, textB, by ='row.names') names(pyramid_df) <- c('terms', 'nike', 'adidas') # Calculate the absolute differences among in common terms pyramid_df$diff <- abs(pyramid_df$nike - pyramid_df$adidas) # Organize data frame for plotting pyramid_df <- pyramid_df[order(pyramid_df$diff, decreasing=TRUE), ] top15 <- pyramid_df[1:15, ] # Pyarmid Plot pyramid.plot(lx = top15$nike, #left rx = top15$adidas, #right labels = top15$terms, #terms top.labels = c('', '', ''), #corpora gap = 7, # space for terms to be read main = 'Words in Common', # title unit = 'Word Frequency', lxcol = 'darkblue', rxcol = 'darkred') #'
93dd33da36028ca71a76dee6dd66f19a47c05b92
61c091c21d06b7c61f35a24d4fe3d8882e9fb254
/man/plot_cpue.Rd
0dcdd047e32c263522ec44b7455820307eeb045e
[]
no_license
pfmc-assessments/nwfscSurvey
b3be76b410bdc5dae168e84d2ee1a2c64c98e098
423800ecb91137cba1587ac19226a3ebb8d50c2d
refs/heads/main
2023-07-28T08:35:55.810331
2023-07-20T17:10:25
2023-07-20T18:17:33
26,344,817
4
2
null
2023-07-20T17:31:58
2014-11-08T00:38:17
R
UTF-8
R
false
true
641
rd
plot_cpue.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_cpue.R \name{plot_cpue} \alias{plot_cpue} \title{This function plots cpue and length by latitude and depth} \usage{ plot_cpue(dir = NULL, catch, plot = 1:3, width = 7, height = 7) } \arguments{ \item{dir}{Directory to save files to} \item{catch}{Data catch file} \item{plot}{A vector of integers specifying the figures you want.} \item{width}{Numeric figure width in inches, defaults to 7} \item{height}{Numeric figure height in inches, defaults to 7} } \description{ This function plots cpue and length by latitude and depth } \author{ Chantel Wetzel }
8bdf09c225065831da3c38aee0e18bd43f210ac5
23ced6ff5ba16d2bcf6701070dc840ca133ac22f
/Graficas_desempeño_votos.R
905601bc810c4851d0a11ac7551641a6aa6e53ad
[]
no_license
dhumbertojs/random
2df79ec3c092e5de41c55ad8c100bd84d2442a77
63e54716249b4c383c57f8b108f4e8a5d61bbf47
refs/heads/master
2020-05-18T03:34:51.580014
2019-10-06T22:50:15
2019-10-06T22:50:15
null
0
0
null
null
null
null
UTF-8
R
false
false
11,751
r
Graficas_desempeño_votos.R
rm(list=ls()) setwd("~") inp = "/Users/Emmanuel RB/Documents/tesis/Datos" out = "/Users/Emmanuel RB/Documents/tesis/out" ####Paquetes#### library(dplyr) library(ggplot2) require(scales) ####Datos#### del <- read.csv(paste(inp, "delitos_b.csv", sep = "/")) ser <- read.csv(paste(inp, "servicios_b.csv", sep = "/")) del <- del %>% group_by(muni) %>% mutate( PAN_lag = lag(PAN, n=1, order_by = muniYear), PRI_lag = lag(PRI, n=1, order_by = muniYear), PRD_lag = lag(PRD, n=1, order_by = muniYear), PAN_PRD_lag = lag(PAN_PRD, n=1, order_by = muniYear), PAN_perf = PAN - PAN_lag, PRI_perf = PRI - PRI_lag, PRD_perf = PRD - PRD_lag, PAN_PRD_perf = PAN_PRD - PAN_PRD_lag ) %>% ungroup(muni) ser <- ser %>% group_by(muni) %>% mutate( PAN_lag = lag(PAN, n=1, order_by = muniYear), PRI_lag = lag(PRI, n=1, order_by = muniYear), PRD_lag = lag(PRD, n=1, order_by = muniYear), PAN_PRD_lag = lag(PAN_PRD, n=1, order_by = muniYear), PAN_perf = PAN - PAN_lag, PRI_perf = PRI - PRI_lag, PRD_perf = PRD - PRD_lag, PAN_PRD_perf = PAN_PRD - PAN_PRD_lag ) %>% ungroup(muni) ####Gráficas nuevas#### #scatter delitos por partido#### delPAN1 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_total , 0.9, na.rm = T)), aes(x = PAN_perf, y = change_total, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Total de delitos", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) delPAN2 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_hom , 0.9, na.rm = T)), aes(x = PAN_perf, y = change_hom, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Homicidios", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(delPAN1, delPAN2) annotate_figure(zscat_del, top = text_grob("Tipo de delito y desempeño electoral del PAN (1994-2010)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sdel_PAN.png", path = out, dpi = 320) delPRI1 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_total , 0.9, na.rm = T)), aes(x = PRI_perf, y = change_total, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Total de delitos", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) delPRI2 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_hom , 0.9, na.rm = T)), aes(x = PRI_perf, y = change_hom, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Homicidios", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(delPRI1, delPRI2) annotate_figure(zscat_del, top = text_grob("Tipo de delito y desempeño electoral del PRI (1994-2010)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sdel_PRI.png", path = out, dpi = 320) delPRD1 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_total , 0.9, na.rm = T)), aes(x = PRD_perf, y = change_total, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Total de delitos", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) delPRD2 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_hom , 0.9, na.rm = T)), aes(x = PRD_perf, y = change_hom, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Homicidios", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(delPRD1, delPRD2) annotate_figure(zscat_del, top = text_grob("Tipo de delito y desempeño electoral del PRD (1994-2010)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sdel_PRD.png", path = out, dpi = 320) delPAN_PRD1 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_total , 0.9, na.rm = T)), aes(x = PAN_PRD_perf, y = change_total, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Total de delitos", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) delPAN_PRD2 <- ggplot(data = subset(del, !is.na(alt) & win_top != "Otros" & quantile(change_hom , 0.9, na.rm = T)), aes(x = PAN_PRD_perf, y = change_hom, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Homicidios", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(delPAN_PRD1, delPAN_PRD2) annotate_figure(zscat_del, top = text_grob("Tipo de delito y desempeño electoral del PAN_PRD (1994-2010)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sdel_PAN_PRD.png", path = out, dpi = 320) #scatter servicios por partido#### serPAN1 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_agua , 0.9, na.rm = T)), aes(x = PAN_perf, y = change_agua, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Agua", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPAN2 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_elec , 0.9, na.rm = T)), aes(x = PAN_perf, y = change_elec, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Electricidad", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPAN3 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_dren , 0.9, na.rm = T)), aes(x = PAN_perf, y = change_dren, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Drenaje", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(serPAN1, serPAN2, serPAN3) annotate_figure(zscat_del, top = text_grob("Tipo de servicio y desempeño electoral del PAN (1994-2015)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sser_PAN.png", path = out, dpi = 320) serPRI1 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_agua , 0.9, na.rm = T)), aes(x = PRI_perf, y = change_agua, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Agua", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPRI2 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_elec , 0.9, na.rm = T)), aes(x = PRI_perf, y = change_elec, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Electricidad", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPRI3 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_dren , 0.9, na.rm = T)), aes(x = PRI_perf, y = change_dren, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Drenaje", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(serPRI1, serPRI2, serPRI3) annotate_figure(zscat_del, top = text_grob("Tipo de servicio y desempeño electoral del PRI (1994-2015)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sser_PRI.png", path = out, dpi = 320) serPRD1 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_agua , 0.9, na.rm = T)), aes(x = PRD_perf, y = change_agua, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Agua", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPRD2 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_elec , 0.9, na.rm = T)), aes(x = PRD_perf, y = change_elec, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Electricidad", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPRD3 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_dren , 0.9, na.rm = T)), aes(x = PRD_perf, y = change_dren, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Drenaje", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(serPRD1, serPRD2, serPRD3) annotate_figure(zscat_del, top = text_grob("Tipo de servicio y desempeño electoral del PRD (1994-2015)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sser_PRD.png", path = out, dpi = 320) serPAN_PRD1 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_agua , 0.9, na.rm = T)), aes(x = PAN_PRD_perf, y = change_agua, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Agua", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPAN_PRD2 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_elec , 0.9, na.rm = T)), aes(x = PAN_PRD_perf, y = change_elec, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Electricidad", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) serPAN_PRD3 <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros" & quantile(change_dren , 0.9, na.rm = T)), aes(x = PAN_PRD_perf, y = change_dren, col = factor(alt))) + geom_point(alpha = 0.4) + ylim(-200, 200) + scale_x_continuous(labels = comma) + labs(y = "Drenaje", x = "Desempeño electoral", col = "Alt") + geom_smooth(method = lm, se= F) zscat_del <- ggarrange(serPAN_PRD1, serPAN_PRD2, serPAN_PRD3) annotate_figure(zscat_del, top = text_grob("Tipo de servicio y desempeño electoral del PAN_PRD (1994-2015)", color = "black", face = "bold", size = 14), bottom = text_grob("Diferencial entre el año electoral t-1 y t", color = "blue", hjust = 1, x = 1, face = "italic", size = 10)) ggsave("sser_PAN_PRD.png", path = out, dpi = 320) #este es otro tema#### try <- ggplot(data = subset(ser, !is.na(alt) & win_top != "Otros"), aes(x = PAN_perf, y = change_dren#, col = factor(alt) )) + geom_point(alpha = 0.4) + ylim(-200, 200) + labs(y = "", x = "", col = "Alt") + geom_smooth()#(method = lm, se= F)
663c05eb0890f97f733da3e5a30f242500dfe6ae
c900792007ef419990fb6ef194cfd9edf14f7e9c
/man/finn.Rd
98b547880b208b46dd28c467dfb80f45102d1091
[]
no_license
ybkamaleri/boligfinn
1e6c01eb00a11ad15e9b5967ebd4ec58987e5cef
02833b372448b8268cf49a746508442bc0a4e9a9
refs/heads/master
2021-02-13T20:06:06.835470
2020-06-18T21:10:07
2020-06-18T21:10:07
244,728,060
6
0
null
2020-04-28T21:44:43
2020-03-03T19:52:01
R
UTF-8
R
false
true
642
rd
finn.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/finn.R \name{finn} \alias{finn} \title{Create table from Finn search} \usage{ finn(area = 1, pmin = 35, pmax = 5, add = NULL, ...) } \arguments{ \item{area}{Areas in Oslo to choose from \itemize{ \item 1:Bygdøy/Frogner \item 2:Grünerløkka/Sofienberg \item 3:Sagene/Torshov \item 4:St.Hanshaugen/Ullevål \item 5:Uranienborg/Majorstuen }} \item{pmin}{Minimum price} \item{pmax}{Maximum price} \item{add}{Other areas to choose from which isn't included in the default} \item{...}{Extra arguments} } \description{ Create table from Finn search }
54dbab51341236f4750065f3f316851cc18c4878
3b1c82ecb7622ce0030470c19732c17f6fda89ff
/SC2019Lab-7-王哲涵-16081043.R
1d0e8439525cdc021284e41b27fe3b5613343b00
[]
no_license
anhnguyendepocen/SC2019-assignments
64bbb7a8d82afba4cc636122ed89268db8aca25e
a4cc348c40c4dc4cb373cbbde2cf92acb71cd69b
refs/heads/master
2020-09-02T03:41:35.656473
2019-04-12T12:48:48
2019-04-12T12:48:48
null
0
0
null
null
null
null
UTF-8
R
false
false
944
r
SC2019Lab-7-王哲涵-16081043.R
f<-function(X){ x1<-X[1] x2<-X[2] x1^2+x2^2 } A=c(1,1) B=c(1,2) C=c(2,2) x<-rbind(A,B,C) y<-rbind(f(A),f(B),f(C)) r2=1 r3=2 while(sqrt((x[r2,1]-x[r3,1])^2+(x[r2,2]-x[r3,2])^2)>0.0001){ h<-rank(y) r1<-which(h==3) r2<-which(h==2) r3<-which(h==1) R<-c(as.numeric(x[r2,1]+x[r3,1]-x[r1,1]),as.numeric(x[r2,2]+x[r3,2]-x[r1,2])) if (y[r3]<f(R)<y[r1]){ y[r1]<-f(R) x[r1,1]<-R[1] x[r1,2]<-R[2] } else if (y[r3]-f(R)>0){ Q<-c(as.numeric(x[r2,1]*1.5+x[r3,1]*1.5-x[r1,1]*2),as.numeric(x[r2,2]*1.5+x[r3,2]*1.5-x[r1,2]*2)) if (f(Q)<f(R)){ y[r1]<-f(Q) x[r1,1]<-Q[1] x[r1,2]<-Q[2] } else{ y[r1]<-f(R) x[r1,1]<-R[1] x[r1,2]<-R[2] } } else{ R<-c(as.numeric(x[r2,1]*0.25+x[r3,1]*0.25+x[r1,1]*0.5),as.numeric(x[r2,2]*0.25+x[r3,2]*0.25+x[r1,2]*0.5)) y[r1]<-f(R) x[r1,1]<-R[1] x[r1,2]<-R[2] } } print(y[1])
cbc29240e748059b3811079605d127fdb7796c7a
0216347b37fe7f78222e3e0729b105f4fb3e8b93
/Plot4.R
e5164d6f8be3805a30722524791ab3504f586654
[]
no_license
serbrach/Eploratory-Data-Analysis
d2139950cec1529f4b8be7575314ffed4477cbdc
46da2ab9dd3c6d579dc36b61178420b4980e8a73
refs/heads/main
2023-03-08T00:14:09.561569
2021-02-20T17:31:13
2021-02-20T17:31:13
340,712,252
0
0
null
null
null
null
UTF-8
R
false
false
674
r
Plot4.R
setwd("E:/Descargas/exdata_data_NEI_data/") library(dplyr) library(ggplot2) NEI <- readRDS("summarySCC_PM25.rds") SCC <- readRDS("Source_Classification_Code.rds") CoalVect<-grepl("Coal",SCC$EI.Sector) SCC.sub<-SCC[CoalVect,] NEI.mod<-NEI%>% filter(SCC %in% SCC.sub$SCC)%>% group_by(year)%>%summarise(Total.EM=sum(Emissions),) png("Plot4.png", height=480 ,width =480) ggplot(NEI.mod,aes(x=factor(year),y=Total.EM/1000,fill=year,label=round(Total.EM/1000)))+geom_bar(stat="identity")+ xlab("Year")+ylab("Total Emissions (*1000 Tons)")+ggtitle("Total coal-related emissions in the Country")+ theme(legend.position = "none") dev.off()
2cea3ff243bbb6acbd932cab32cdb1441b6a29cf
33b6111a3ebc6a3c24e521bda012dafb3fa8c7e5
/task1/data_cleaning_scripts/decathlon.R
1332443f4d155b3f726383b4edf4b69ac77f7541
[]
no_license
pjbateman/dirty_data_codeclan_project_paul
bb17b62f8f893e468c1852e98bdc8052270446b3
d527a03350757e5236e46dd70de72d87094a54f7
refs/heads/main
2023-06-24T05:54:48.751676
2021-07-15T16:17:39
2021-07-15T16:17:39
384,486,186
0
0
null
null
null
null
UTF-8
R
false
false
1,141
r
decathlon.R
# loading in the necessary libraries library(tidyverse) # loads the tibble package to convert rownmes_to_col library(janitor) # to use the clean names function library(readr) # used to read in the raw data file type .rds library(here) # to enable the file locations to be reproducible # fetching the raw data file decathlon <- read_rds(here("raw_data/decathlon.rds")) # the first column contains row names and needs to be fixed decathlon <- decathlon %>% rownames_to_column(var = "athlete") # cleaning the column names decathlon_clean_names <- clean_names(decathlon) # check the column data types make sense glimpse(decathlon_clean_names) # The athlete names should feature a consistent format decathlon_clean_names <- decathlon_clean_names %>% mutate( athlete = str_to_title(athlete) ) # we need to make the data "tidy", as rank 1 for example, appears twice # use the pivot_wider() function decathlon_wide <- decathlon_clean_names %>% pivot_wider(names_from = competition, values_from = rank) # finally, output the clean data to a new file write_csv(decathlon_wide, "clean_data/decathlon_clean.csv")
3a2a007bd8d552b52404b0b8ceab161ac8c2e5f0
7670b011e2504fc6213456b2f0f5992f056470bb
/Lectures/Lecture_2/ggplot2_example.R
fda9af14f1e8fd55003bde4598de3172dfe34a54
[ "MIT" ]
permissive
ogencoglu/R_for_VTT
448f57387e4131c11d5f47f00b392ba2225e82da
a7f15e1feedc745cadbd7db7d43d192265c047fd
refs/heads/master
2021-01-01T03:53:28.362701
2016-05-15T06:31:06
2016-05-15T06:31:06
56,995,798
2
0
null
null
null
null
UTF-8
R
false
false
1,141
r
ggplot2_example.R
# R Lecture to VTT - Lecture 2 # Author : Oguzhan Gencoglu # Latest Version : 03.05.2016 # Contact : oguzhan.gencoglu@tut.fi # -------------- Yet another ggplot2 example -------------- # Read the data (temperature in chicago) nmmaps <- read.csv("chicago-nmmaps.csv", as.is=T) nmmaps$year <- substring(nmmaps$date, 1, 4) # year nmmaps$date<-as.Date(nmmaps$date) nmmaps <- nmmaps[nmmaps$date>as.Date("1996-12-31"),] # subset nmmaps$season <- as.factor(nmmaps$season) # change to factor # simple stuff library(ggplot2) g1 <- ggplot(nmmaps, aes(date, temp)) + geom_point(color = "firebrick") g1 g2 <- ggplot(nmmaps, aes(date, temp, color = season)) + geom_point() g2 # facet plot g3 <- ggplot(nmmaps, aes(date,temp)) + geom_point(color="aquamarine4") + facet_wrap(~year, nrow=1) g3 # facet plot g4 <- ggplot(nmmaps, aes(date,temp)) + geom_point(color="chartreuse4") + facet_wrap(~year, ncol=2) g4 # box plots g5 <- ggplot(nmmaps, aes(x=season, y=o3)) + geom_boxplot(fill="chartreuse4") + coord_flip() g5 g6 <- g5 + geom_jitter(alpha=0.5, aes(color=season), position = position_jitter(width = .2)) g6
f70a4e4e45ab4df535cc52e663bc677f70f45c1b
aee2c11aff6bd0874a03fbd16f852ad785efe5ba
/man/sirs.fct.Rd
0df5932233efbd88260cbc05d1e36de6d2ea9fbe
[ "MIT" ]
permissive
maciejrosolowski/progressdatenbankderivate
bca72eadf47ba2dcffeed80cc120f25458f13581
1a2e31ed7e62970a0206883173d32e14d888563d
refs/heads/master
2021-02-18T18:34:28.100509
2020-08-02T13:07:09
2020-08-02T13:07:09
245,223,654
0
0
null
null
null
null
UTF-8
R
false
true
3,041
rd
sirs.fct.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sirs.fct.R \name{sirs.fct} \alias{sirs.fct} \title{Compute the SIRS score.} \usage{ sirs.fct( DID_PROBAND, FRM_BAS, FRM_BEF, FRM_B24, FRM_DIL_LABORWERTE, DID_CLIN, FRM_RR, FRM_KAT, zp_fabian = "d0", event2zeitpunkt_df = progressdatenbankderivate::event2zeitpunkt_table ) } \arguments{ \item{DID_PROBAND}{data.table containing the table with the same name from the database of the PROGRESS study} \item{FRM_BAS}{data.table containing the table with the same name from the database of the PROGRESS study} \item{FRM_BEF}{data.table containing the table with the same name from the database of the PROGRESS study} \item{FRM_B24}{data.table containing the table with the same name from the database of the PROGRESS study} \item{FRM_DIL_LABORWERTE}{data.table containing the table with the same name from the database of the PROGRESS study} \item{DID_CLIN}{data.table containing the table with the same name from the database of the PROGRESS study} \item{FRM_RR}{data.table containing the table with the same name from the database of the PROGRESS study} \item{FRM_KAT}{data.table containing the table with the same name from the database of the PROGRESS study} \item{zp_fabian}{vector of characters. They must be present in event2zeitpunkt_table$zp_fabianref.} \item{event2zeitpunkt_df}{data.table event2zeitpunkt_table (available with the package).} } \value{ a named list with components: input, input2 and out. out is a data.table with one row corresponding to a combination of PATSTUID (patient) and "EVENT" (time point). infec.septic.servsept contains the number of the met SIRS criteria (infected (1), sepsis (2), severe sepsis(3)); septischer.schock indicates if criteria for septic shock are met. If 50% or less of the 16 input parameters are NA then the score is set to NA. } \description{ Compute the SIRS score. } \examples{ \dontrun{ excel_fn <- paste0("/net/ifs1/san_projekte/projekte/", "PROGRESS/Datenmanagement/Data_freezes/", "20190320/PROGRESS-freeze_201903_01.xlsx") DID_PROBAND <- readxl::read_excel(excel_fn, 'DID_PROBAND') FRM_BAS <- readxl::read_excel(excel_fn, 'FRM_BAS') FRM_BEF <- readxl::read_excel(excel_fn, 'FRM_BEF') FRM_B24 <- readxl::read_excel(excel_fn, 'FRM_B24') FRM_DIL_LABORWERTE <- readxl::read_excel(excel_fn, "FRM_DIL_LABORWERTE") DID_CLIN <- readxl::read_excel(excel_fn, 'DID_CLIN') FRM_RR <- readxl::read_excel(excel_fn, 'FRM_RR', guess_max = 10e5) FRM_KAT <- readxl::read_excel(excel_fn, 'FRM_KAT') data.table::setDT(DID_PROBAND) data.table::setDT(FRM_BAS) data.table::setDT(FRM_BEF) data.table::setDT(FRM_B24) data.table::setDT(FRM_DIL_LABORWERTE) data.table::setDT(DID_CLIN) data.table::setDT(FRM_RR) data.table::setDT(FRM_KAT) erg_d0 <- sirs.fct(DID_PROBAND, FRM_BAS, FRM_BEF, FRM_B24, FRM_DIL_LABORWERTE, DID_CLIN, FRM_RR, FRM_KAT, zp_fabian = "d0") erg_d0 erg_d1 <- sirs.fct(DID_PROBAND, FRM_BAS, FRM_BEF, FRM_B24, FRM_DIL_LABORWERTE, DID_CLIN, FRM_RR, FRM_KAT, zp_fabian = "d1") erg_d1 } }
f4185e4894c2e18bce23424c9d413cce1b3529cf
72d52da12b677aeebb7490c20c06738b179f2856
/man/cong1f.Rd
63f57eef93203f948a63613d73f173c89645db27
[]
no_license
cran/Lambda4
94ac2cbd0f5213050a20a4c2920c939a531d109c
0ace2eaffe6b1f2c9d4afa19fe416c3bb5bc1ad6
refs/heads/master
2016-09-10T12:39:03.901179
2013-07-30T00:00:00
2013-07-30T00:00:00
17,680,297
1
0
null
null
null
null
UTF-8
R
false
false
899
rd
cong1f.Rd
\name{cong1f} \alias{cong1f} \docType{data} \title{One-Factor Congeneric Covariance Matrix} \description{ This Covariance matrix was used as the population model for one set of simulations. It was used to represent a congeneric data structure in which the factor loadings are set at .5, .6, .7, .8, .5, .6, .7, and .8. The error variances were set at .6^2, .7^2, .8^2, .9^2, .6^2, .7^2, .8^2, and .9^2. } \usage{data(cong1f)} \format{ A covariance matrix of 8 theoretical items. } \examples{ ###---Loadings fx<-t(matrix(c( .5, .6, .7, .8, .5, .6, .7, .8), nrow=1)) ###--Error Variances err<-diag(c(.6^2,.7^2,.8^2,.9^2, .6^2,.7^2,.8^2,.9^2)) ###---matrix of factor covariances phi<-matrix(1, nrow=1) ###---Reliability Calculation---### t1<-matrix(c(rep(1,8)), nrow=1) t1t<-matrix(c(rep(1,8)), ncol=1) (fx\%*\%phi\%*\%t(fx)+err) } \keyword{datasets}
704a2bdb2df10b950fd6ae020fda760306a9ca6e
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/TMDb/examples/tv_season_external_ids.Rd.R
ea9c89be1bce24890e98b23ba8d2904a85b268d2
[]
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
500
r
tv_season_external_ids.Rd.R
library(TMDb) ### Name: tv_season_external_ids ### Title: Retrieve external ids for a TV season. ### Aliases: tv_season_external_ids ### Keywords: tv_season_external_ids ### ** Examples ## Not run: ##D ##D ## An example of an authenticated request, ##D ## where api_key is fictitious. ##D ## You can obtain your own at https://www.themoviedb.org/documentation/api ##D ##D api_key <- "key" ##D ##D tv_season_external_ids(api_key = api_key, id = 1396, season_number = 3) ## End(Not run)
69f1c7585021984e485d28213f6b3156a57bffc5
f3f8a429bdfd404f8cbeb4e325b414a2bbfb0e61
/RProgram-Assigment2.R
9976156a615d32d2aa62d75ffdc298cfc7406ffd
[]
no_license
karthickanand/ProgrammingAssignment2
a5d4ae146d148b073819c09be4420f9b1f03011b
f4d04d384a466d51ab6085e479eeee3facaa494e
refs/heads/master
2020-12-28T19:07:28.706214
2015-06-21T16:02:15
2015-06-21T16:02:15
37,814,467
0
0
null
2015-06-21T15:41:07
2015-06-21T15:41:07
null
UTF-8
R
false
false
497
r
RProgram-Assigment2.R
makeCacheMatrix <- function(x=matrix()) { set <- function(y) { x <<- y m <<- NULL } get <- function() x setinv <- function(solve) m <<- solve getinv <- function () m list(set= set, get=get, setinv=setinv, getinv=getinv) } cacheSolve <- function(x=matrix()) { m <- x$getinv() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data) x$setinv(m) m } a<-makeCacheMatrix() a$set(matrix(c(1,2,2,1),2,2)) cacheSolve(a)
48fc5bfeba6b4c84f6431e47d366b4e9461cde63
0dc13ef62f4809459ae85579937ab857544658ab
/coursera-data-sci/02_GettingAndCleaningData/02_02_reading_from_hdf5.R
4325146121328da5c771e6d47509d28f2f259b13
[]
no_license
dsk1/coursera-data-sci
aed19dd908ac5b1261f04c7edce92a97017e294a
d0eac7c8bc21f64a011f2c7fd85090ffce4e808d
refs/heads/master
2016-08-11T09:50:24.997982
2016-03-01T04:36:34
2016-03-01T04:36:34
46,252,940
0
0
null
null
null
null
UTF-8
R
false
false
906
r
02_02_reading_from_hdf5.R
source("http://bioconductor.org/biocLite.R") biocLite("rhdf5") library(rhdf5) created = h5createFile("example.h5") created created = h5createGroup("example.h5", "foo") created = h5createGroup("example.h5", "baa") created = h5createGroup("example.h5", "foo/foobaa") h5ls("example.h5") # write a group INTO the hdf5 file A = matrix(1:10, nr = 5, nc =2) A h5write(A, "example.h5", "foo/A") B = array(seq(0.1, 2.0, by=0.1), dim = c(5,2,2)) B attr(B, "scale") <- "liter" B h5write(B, "example.h5", "foo/foobaa/B") h5ls("example.h5") # writing a data frame into hdf5 file df <- data.frame(1L:5L, seq(0,1,length.out = 5), c("abc", "cde", "fghi", "a", "s"), stringsAsFactors = FALSE) df h5write(df, "example.h5", "df") h5ls("example.h5") h5write(c(12, 13, 14), "example.h5", "foo/A", index = list(1:3, 1)) h5read("example.h5", "foo/A") h5read("example.h5", "foo/foobaa") h5read("example.h5", "df") H5close()
5eef0a0354c88888ecfda82df05e2176f038e258
b150872f2739c4efc1b21c2b4b1edd2bcfcf51be
/man/predict.epplab.Rd
f6a5b93d25280de0daf49f7ef37924e42d5f70da
[]
no_license
fischuu/REPPlab
51378051c9a88cbcb705b055975b75c3f735b4cc
4587d0534c23a64fc06ac5118c66e2f6f84e17bc
refs/heads/master
2023-04-30T01:57:20.872407
2023-04-14T06:00:23
2023-04-14T06:00:23
40,982,012
0
0
null
null
null
null
UTF-8
R
false
true
1,439
rd
predict.epplab.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/predict.epplab.R \docType{methods} \name{predict.epplab} \alias{predict,epplab-method} \alias{predict-method} \alias{predict.epplab} \title{Calculates projections for a new Data Object} \usage{ \method{predict}{epplab}(object, which = 1, data = NULL, ...) } \arguments{ \item{object}{Object of class \code{epplab}.} \item{which}{Onto which direction should the new data be projected.} \item{data}{The new data object} \item{...}{Additional parameters} } \value{ A matrix having in each column the projection onto the direction of a certain run and in each row the projected value. } \description{ Calculates the projections of a new data object onto the directions from an existing \code{ebblab} object. } \details{ The default projection direction is the direction with the best objective criterion. In case that no data is given to the function, the fitted scores for the original data will be returned. } \examples{ library(tourr) data(olive) res <- EPPlab(olive[,3:10], PPalg="PSO", PPindex="KurtosisMin", n.simu=10, maxiter=20) newData <- matrix(rnorm(80), ncol=8) # Projection on the best direction predict(res, data=newData) # Projection on the best 3 directions predict(res, which=1:3, data=newData) # Similar with function fitted() when no data is given: predict(res) fitted(res) } \author{ Daniel Fischer } \keyword{methods} \keyword{print}
a3a045759b816caaa6b07990a09d1bfaeb6ada97
95c0e1e6e4a69ac2cb20955b96692cabc7db6533
/ss_compare_fn.R
5ca850072c4250aac8a64b8c774eee76c9418ba5
[]
no_license
mkapur/SS_compare
ac67effd102e100ba055be444aa96d0c1ec366cc
fb90d73e90c90a4f05ebec7ac053acf8338f061e
refs/heads/master
2018-07-19T19:19:03.699944
2018-06-02T00:14:57
2018-06-02T00:14:57
114,181,109
0
0
null
null
null
null
UTF-8
R
false
false
2,365
r
ss_compare_fn.R
## Function to generate and save plots from SSComparePlots and compute by-fleet likelihoods. ## M Kapur maia.kapur@noaa.gov ## Dec 2017 ss_compare <- function(rootdir, pattern = "00_", llabels = c('W 0.1','W 0.2','W 0.3','W 0.4','W 0.5','W 0.6','W 0.7','W 0.8','W 0.9','W 1','Survey05'), likeCSV = T, likeLabel = c('Surv_like','SizeFreq_like:_2'), lambdaLabel = c('Surv_lambda','SizeFreq_lambda:_2'), fishery = "Deep7", fleetIdx = c(2,3)){ dir.create("plots") ## make storage for plots ## make summary object mods = list.dirs(rootdir) %>% .[grepl(pattern, .)] summaryoutput = mods %>% SSgetoutput(dirvec = ., getcovar = F, ncols = 1000) %>% SSsummarize() ## dump plots to file SSplotComparisons(summaryoutput, plot=T, pdf=F, png=F, print = T,plotdir = "plots", legendloc='bottomright', legendlabels=llabels) ## dump special fleets to file for (ii in 1:length(fleetIdx)) { SSplotComparisons(summaryoutput, plot=F, pdf=F, png=T, plotdir="plots", legendloc='bottomright', legendlabels=llabels, indexfleets=fleetIdx[ii]) } ## Not working - doxx says "needs to be generalized" # SSplotSummaryF(summaryoutput,plot=T,print = T,plotdir="plots") message("rendered plots") if(likeCSV) { dir.create("By-Fleet Likelihoods") data.frame( 'model' = sub('.*/', '', mods), 'totlike' = as.numeric(summaryoutput$likelihoods[summaryoutput$likelihoods$Label == 'TOTAL', 1:length(mods)]), summaryoutput$likelihoods_by_fleet %>% filter(Label == lambdaLabel[2]) %>% select(fishery) %>% head(length(mods)), summaryoutput$likelihoods_by_fleet %>% filter(Label == likeLabel[2]) %>% select(fishery) %>% head(length(mods)) ) %>% plyr::rename(c( "Deep7" = paste0(fishery, lambdaLabel[2]), "Deep7.1" = paste0(fishery, likeLabel[2]) )) %>% write.csv( ., file = paste( 'By-Fleet Likelihoods/LBF', format(Sys.time(), "%Y%m%d_%H%M.csv"), sep = '_' ), row.names = F ) } message("created by-fleet likelihood CSV") graphics.off() }
34024dc159d52cdb175ea355b03e93c7fe562de9
d84acfead13e18553a2c04c8fa8bf51ed60d11a8
/Movies_da_App/system2_functions.R
67120425f9ba34b709432c88c9452f2119f0f67b
[]
no_license
Z-Jarrah/PSL-FALL-2020
3d931f040092ad2a8b6611af3954c4d8fe8d40dd
59164ee31e51f5b2b6e18f76ed663038c2fde2ac
refs/heads/master
2023-01-30T00:12:37.501179
2020-12-15T06:01:38
2020-12-15T06:01:38
291,346,837
1
2
null
null
null
null
UTF-8
R
false
false
2,558
r
system2_functions.R
#system2_functions.R library(dplyr) library(data.table) library(Matrix) library(plyr) library(recommenderlab) # load rating data ---- # ratings = read.csv(paste0(data_url, 'ratings.dat?raw=true'), # sep = ':', # colClasses = c('integer', 'NULL'), # header = FALSE) ratings = readLines("data/ratings.dat") ratings = strsplit(ratings, split = "::", fixed = TRUE, useBytes = TRUE) #seperated by :: ratings = matrix(unlist(ratings), ncol = 4, byrow = TRUE) #is a list of lists ratings = data.frame(ratings, stringsAsFactors = FALSE) # one line per movie unlike the ratings colnames(ratings) = c('UserID', 'MovieID', 'Rating', 'Timestamp') ratings = ratings[, -4] #dont need timestamp sample_UserIDs = sample(ratings$UserID, size = 1000) ratings = ratings[ratings$UserID %in% sample_UserIDs, ] #assumes ratings and movies have already been loaded into a dataframe #assumes new user ratings are being returned in a two column data frame of (movieID, Rating) newuserID = 9999 #include the active user in the ratings dataframe system2_recs = function(input, n = 10){ active_user_ratings = cbind(newuserID, input) colnames(active_user_ratings) = c('UserID', 'MovieID', 'Rating') ratings = rbind(ratings, active_user_ratings) Rmat = create_rating_matrix(ratings) active_user_ID = paste0('u', newuserID) active_user_Rmat_row = which(rownames(Rmat) == active_user_ID) rec_SVD = Recommender(Rmat, method = 'SVD', parameter = list(normalize = 'center', k = 25, maxiter = 50)) preds = predict(rec_SVD, Rmat[active_user_Rmat_row,], n = n) preds_list = as(preds, "list")[[1]] movie_ids = unlist(lapply(preds_list, left)) return(movie_ids) } #returns a movie ID without the m in front of the actual ID left = function(string){ return(substr(string, 2, nchar(string))) } create_rating_matrix = function(ratings_df){ #create a sparse matrix with data x at location i,j u = paste0('u', ratings_df$UserID) #user number ... m = paste0('m', ratings_df$MovieID) #movie number ... x = ratings_df$Rating cat("in rating matrix") #nessecary to prevent sparseMatrix freaking out over i + j being characters instead of integers tmp = data.frame(u, m, x, stringsAsFactors = T) Rmat = sparseMatrix(as.integer(tmp$u), as.integer(tmp$m), x = as.integer(tmp$x)) #the levels for each are the order in which the data is already entered into the matrix rownames(Rmat) = levels(tmp$u) colnames(Rmat) = levels(tmp$m) Rmat = new('realRatingMatrix', data = Rmat) return(Rmat) }
3664eedfaf1979da0e64929fd6253da2127bdf83
873f2f21ba9477f77fbd63471f68fb74f0096fa7
/helpers.R
d110b37904bd8a99f5b5f5192b0c24a6529e32f8
[]
no_license
cashoes/shinyDIABLO
9724036ecbc28bf0944873cec712e5cdce90b1aa
6849c1dffa10db61f497ed8b94aeba85dc2ce4dd
refs/heads/master
2021-09-06T00:15:44.371020
2018-01-31T22:21:46
2018-01-31T22:21:46
119,751,598
1
0
null
null
null
null
UTF-8
R
false
false
1,785
r
helpers.R
#' Get correlation matrix # #' @param model A DIABLO model object. getCorMat <- function(model, selection, method = 'pearson') { object <- model keepA <- lapply(object$loadings, function(i) apply(abs(i), 1, sum) > 0) cord <- mapply(function(x, y, keep){ cor(x[, keep], y, use = "pairwise", method = method) }, x = object$X, y = object$variates[-length(object$variates)], keep = keepA[-length(keepA)]) simMatList <- vector("list", length(model$X)) for(i in 1:length(cord)){ for(j in 1:length(cord)){ simMatList[[i]][[j]] <- cord[[i]] %*% t(cord[[j]]) } } corMat <- do.call(rbind, lapply(simMatList, function(i) do.call(cbind, i))) } #' Gene set enrichment analysis # #' @param geneSet A list of gene symbols. #' @param featureMapping A list of data frames containing 'Data.Names', 'Gene.Symbols', 'Display.Names' for each of the data blocks. genesetEnrichment <- function(geneSet, featureMapping = NULL) { # Get dataset library(sear) candidates <- geneSet if (!is.null(featureMapping)){ for (name in candidates){ warning(sprintf("%s", name)) } } # Perform 'sear' result <- sear::sear(candidates) result <- dplyr::arrange(result, fdr) result <- result[1:20, c("collection", "geneset", "fdr")] result[, -c(1,2)] <- signif(result[, -c(1,2)], digits = 3) result } #' Match with existing Protein-Protein Interaction data # #' If there is a match, returns the index of the match in the PPI data in a vector of length 'edges' #' 'edges' and 'data' both two column data frames # #' @param edges A data frame consisting of two proteins that have an edge. #' @param data A data frame consisting of two columns of proteins that interact matchPPI <- function(edges, data){ matches <- prodlim::row.match(edges, data) }
6c1574f30212ddf02e2c9e60f6276b8a4427a392
72db92ef4526cd72a71440244d5b4e9d9cd0568d
/lib/feature_3.R
3145b31b369e27b1e9f3b1b73b741bc7a7651707
[]
no_license
TZstatsADS/Spr2016-Proj3-Grp5
e962ce0451b24332bad0bb17a6d9ae962cc47199
92406adeb942ff15c1317a247f11265552251ece
refs/heads/master
2021-01-18T06:58:58.255224
2016-03-23T20:32:07
2016-03-23T20:32:07
52,483,433
0
1
null
null
null
null
UTF-8
R
false
false
5,130
r
feature_3.R
############################################################# ### Construct features out of images for training/testing ### ############################################################# # CONSTRUCTS HARMONIC COEFFICIENTS FROM ELLIPTICAL FOURIER OUTLINE ANALYSIS source("http://bioconductor.org/biocLite.R") biocLite("EBImage") library(EBImage) install.packages("devtools") devtools::install_github("vbonhomme/Momocs") library(Momocs) feature <- function(img_dir, data_dir) { ### Constructs features out of images for training/testing ### img_dir: class "character", path to directory of images to be processed ### data_dir: class "character", path to directory to place feature data files in ### Output: .rds files, one for each image, containing the features for that image ##### CURRENT STATUS (2016/03/18 19:30): ##### This function constructs only harmonic coefficient features. ##### WARNING: This function also writes a new processed image file per image. ##### This will thus double the number of images in your image directory. ##### Maybe a separate directory for the processed files should be created. ##### Running time on Arnold's computer: ##### user: 2655.92 system: 43.69 elapsed 2824.62 (approx 47 minutes) file_names <- list.files(img_dir, pattern = "[[:digit:]].jpg") # THIS IS NOT A GOOD SOLUTION file_names <- sort(file_names) file_paths <- rep(NA_character_, length(file_names)) for (i in 1:length(file_names)) { file_paths[i] <- paste(img_dir, file_names[i], sep = "/") } file_paths <- sort(file_paths) # Construct harmonic coefficient features from image outline # Note: Some images may be invalid; features will not be constructed for those images # Note: Some images may result in outlines with too little detail; features will not be # constructed for those images for (i in 1:length(file_paths)) { tryCatch({ img <- readImage(file_paths[i]) img_bin <- channel(img, mode = "gray") # convert image to greyscale img_bin <- gblur(img_bin, sigma = 5) # smooth image with a low-pass filter threshold <- otsu(img_bin) img_bin <- img_bin > threshold # create binary black/white image using Otsu threshold writeImage(img_bin, paste(img_dir, "/", unlist(strsplit(file_names[i], split = "[.]"))[1], "_bin.jpg", sep = ""), type = "jpeg") momocs_out <- import_jpg1(jpg.path = paste(img_dir, "/", unlist(strsplit(file_names[i], split = "[.]"))[1], "_bin.jpg", sep = ""), threshold = threshold) momocs_out <- Out(list(momocs_out)) momocs_out <- coo_smooth(momocs_out, 5) %>% coo_scale() %>% coo_center() momocs_ef <- efourier(momocs_out, nb.h = 10) momocs_coeff <- momocs_ef$coe[1, ] if(length(momocs_coeff) != 40) { next } mat <- imageData(img) nR <- 5 nG <- 5 nB <- 5 rBin <- seq(0, 1, length.out=nR) gBin <- seq(0, 1, length.out=nG) bBin <- seq(0, 1, length.out=nB) freq_rgb <- as.data.frame(table(factor(findInterval(mat[,,1], rBin), levels=1:nR), factor(findInterval(mat[,,2], gBin), levels=1:nG), factor(findInterval(mat[,,3], bBin), levels=1:nB))) rgb_feature <- as.numeric(freq_rgb$Freq)/(ncol(mat)*nrow(mat)) # normalization final <- c(rgb_feature, momocs_coeff) saveRDS(final, file = paste(data_dir, "/", unlist(strsplit(file_names[i], "[.]"))[1], ".rds", sep = "")) }, error = function(c) "invalid or corrupt JPEG file") } } feature_mat <- function(data_dir) { ### Create a matrix with features for all observations ### data_dir: class "character", path to directory where feature data files are placed ### Output: matrix with features for all observations feature_file_names <- Sys.glob(paste(data_dir, "/*.rds", sep = "")) feature_file_names <- sort(feature_file_names) # create feature matrix catdog <- do.call('rbind', lapply(feature_file_names, readRDS)) return(catdog) } label_vec <- function(data_dir) { ### Create a vector with labels for all observations ### data_dir: class "character", path to directory where feature data files are placed ### Output: vector with labels for all observations feature_names <- list.files(data_dir, pattern = "rds") feature_names <- sort(feature_names) # extract vector of labels (cat = 1, dog = 0) breed_name <- rep(NA, length(feature_names)) for(i in 1:length(feature_names)){ tt <- unlist(strsplit(feature_names[i], "_")) tt <- tt[-length(tt)] breed_name[i] = paste(tt, collapse="_", sep="") } cat_breed <- c("Abyssinian", "Bengal", "Birman", "Bombay", "British_Shorthair", "Egyptian_Mau", "Maine_Coon", "Persian", "Ragdoll", "Russian_Blue", "Siamese", "Sphynx") iscat <- breed_name %in% cat_breed y_cat <- as.numeric(iscat) return(y_cat) }
ec31fec634eeda657628452fa8ef582d1741a3c0
063ac42ba9d2dd563946f8a68936d89414bcbefc
/man/numverify.Rd
0372a87dc25de19a8d880c99c37f3db1ad27dd4c
[ "MIT" ]
permissive
ashleylijie/rdevt
ed9e10668bac5e856543a8e09dfe7d81fd1f7178
54b0bfe22eae587ded3b869286a302e74c9968e7
refs/heads/master
2020-04-22T14:43:34.863678
2019-02-14T08:07:25
2019-02-14T08:07:25
170,453,586
0
0
null
null
null
null
UTF-8
R
false
true
468
rd
numverify.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{numverify} \alias{numverify} \title{Numverify : Validate Phone Number} \usage{ numverify(country_code = "CN", number = NULL) } \arguments{ \item{country_code}{Country code, default China : "CN".} \item{number}{Phone number} } \value{ the results from the validation } \description{ Numverify : Validate Phone Number } \examples{ \dontrun{ numverify(number = 14158586273) } }
5bd7112e78f791d93f57d5b1e17b0c6619a84c9d
c72b8531677736413ffdd39b157248445756b0ef
/man/compare_normalized_nearest_neighbor.Rd
8108ef541ea0ad06f9c034805ac57258febb946b
[ "MIT" ]
permissive
gusef/IrisSpatialFeatures
731b7333ac3a54355c8a7b1058f4dcd079bef77f
c9f7eac1b7c13000aa1f04cbf0266c32c2b400ab
refs/heads/master
2021-03-27T19:22:00.769564
2019-04-04T02:55:41
2019-04-04T02:55:41
72,760,221
5
1
null
null
null
null
UTF-8
R
false
true
1,048
rd
compare_normalized_nearest_neighbor.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/normalized.nearest.neighbor.R \docType{methods} \name{compare_normalized_nearest_neighbor} \alias{compare_normalized_nearest_neighbor} \alias{compare_normalized_nearest_neighbor,NNN,character,character,character-method} \title{Compare distances between two markers to a reference marker.} \usage{ compare_normalized_nearest_neighbor(NNN, markerA, markerB, reference, order = FALSE) \S4method{compare_normalized_nearest_neighbor}{NNN,character,character,character}(NNN, markerA, markerB, reference, order = FALSE) } \arguments{ \item{NNN}{Normalized nearest neighbor object} \item{markerA}{Additional arguments} \item{markerB}{Additional arguments} \item{reference}{Additional arguments} \item{order}{Optional character vector with sample names in an order for plotting} } \value{ Analysis data } \description{ Compare distances between two markers to a reference marker. } \examples{ dataset <- IrisSpatialFeatures_data dataframe <- as.data.frame(dataset) }
e51f555609d1dbacfd5d86ef33f9ac8081e48951
258290d6dd1fe844720553b340dd64768ef08f46
/cachematrix.R
2217379b683cf7ee61ecbd104c5b5e08057e199b
[]
no_license
pvasilyev/ProgrammingAssignment2
cc7cd3d933d0c50123fa29b3d813bae38de09965
a902ca58795f8ff554d19e70c3560ce5385e3dc1
refs/heads/master
2020-12-31T02:31:44.860870
2014-10-27T10:07:17
2014-10-27T10:07:17
null
0
0
null
null
null
null
UTF-8
R
false
false
1,252
r
cachematrix.R
## Following functions can be used to create special wrapper over given matrix, ## which is able to cache invertion of this matrix, a.k.a. solve(matrix). ## So if the matrix is not changed - then the invertion computed only once and after that ## returned only cached result. ## When the data of the wrapper is changed - then cache is expired and invertion is re-computed. ## This function creates a caching-wrapper for a given matrix 'x'. makeCacheMatrix <- function(x = matrix()) { inverted <- NULL set <- function(y) { x <<- y inverted <<- NULL } get <- function() x setCachedInverted <- function(inv) inverted <<- inv getCachedInverted <- function() inverted list(set = set, get = get, setCachedInverted = setCachedInverted, getCachedInverted = getCachedInverted) } ## This function computes the invertion for the wrapper if is hasn't computed so far. ## Otherwise it returns cached result for the 'x'. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inverted <- x$getCachedInverted() if(!is.null(inverted)) { message("getting cached data") return(inverted) } data <- x$get() inverted <- solve(data, ...) x$setCachedInverted(inverted) inverted }
e65d019d722befa851612b2ae7476cbb9e0380c4
2709949bcb37fad772575f1516b07910ee1e0389
/man/addExposure2ExposomeSetDS.Rd
a809215a14b7d01742ab8ee95c0cce75c6155787
[ "MIT" ]
permissive
isglobal-brge/dsExposome
fa87a72471535a9c1445383aff9dec8b458eb346
f6346fa576bcced74baafd0f0b27c416df2f5afd
refs/heads/master
2023-02-20T21:32:41.084519
2023-02-14T10:45:22
2023-02-14T10:45:22
238,680,883
0
6
MIT
2023-02-13T10:40:50
2020-02-06T12:11:54
R
UTF-8
R
false
true
1,133
rd
addExposure2ExposomeSetDS.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/addExposure2ExposomeSetDS.R \name{addExposure2ExposomeSetDS} \alias{addExposure2ExposomeSetDS} \title{Add Phenotype data to ExposomeSet} \usage{ addExposure2ExposomeSetDS( x, exposure, identifier_ExposomeSet, identifier_new_exposures, families ) } \arguments{ \item{x}{\code{ExposomeSet} ExposomeSet to which add phenotype information} \item{exposure}{\code{data.frame} Table with the new exposures} \item{identifier_ExposomeSet}{\code{character} Name of the ID column on the already present phenotypes data.frame on the ExposomeSet} \item{identifier_new_exposures}{\code{character} Name of the ID column on the new exposure data.frame} \item{complete_cases}{\code{bool} If \code{TRUE} only the matching individuals between the ExpressionSet and the phenotypes table will be included on the resulting ExpressionSet. If \code{FALSE} all the individuals on the input ExpressionSet will be on the output ExpressionSet} } \value{ \code{ExposomeSet} with updated phenotypes information } \description{ Add phenotype data to an ExpressionSet }
2be4222f2ed3376b1f916aa1aa3a4bea881b0c9b
4682b24e96eb3deaef0be092d395c6a1fb8e6446
/from_rmd_to_R.R
f296053c717bc9b264f6f86a96dc8d441f838c9f
[]
no_license
vjilmari/exproj
f7b76a4598bcd16ddcb51402c4a57aab9d65f9d4
88287513c2d60a9728dcd8569d54eff352c4696b
refs/heads/master
2022-04-22T17:23:45.057229
2020-04-23T07:59:14
2020-04-23T07:59:14
256,155,203
0
0
null
null
null
null
UTF-8
R
false
false
86
r
from_rmd_to_R.R
library(knitr) purl("testmarkdown.Rmd", output = "testmarkdown.R", documentation = 2)
0fff4c7fc92bf2ec5135b2237ecfd2161a7df73f
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/RobExtremes/examples/WeibullFamily.Rd.R
bfb7a5cbedfd9b44fc91636a9788086f10365f3b
[]
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
222
r
WeibullFamily.Rd.R
library(RobExtremes) ### Name: WeibullFamily ### Title: Generating function for Weibull family ### Aliases: WeibullFamily ### Keywords: models ### ** Examples (G1 <- WeibullFamily()) FisherInfo(G1) checkL2deriv(G1)
fd3e997b61045ee508977bb83485cbe8cd5a6af9
c9f45c5b10ecdf1b324cdc5a35179bbcc7b79d67
/plot3.R
a4256be2be4baa1a31fa896f62d48d8c34458aab
[]
no_license
Jose230600/ExData_Plotting1
630e6acc8d530901e6c2461c61a329918ee85eb8
5bc5a77a4cb257da7672d27268e64e7ed8c27ec5
refs/heads/master
2022-11-29T23:31:05.815971
2020-08-09T23:38:39
2020-08-09T23:38:39
286,161,007
0
0
null
2020-08-09T03:39:07
2020-08-09T03:39:06
null
UTF-8
R
false
false
1,223
r
plot3.R
#Once the file is in your work directory data <- read.table("household_power_consumption.txt",sep=";",header=TRUE) data2 <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007", ] data2$Date <- as.Date(data2$Date, format="%d/%m/%Y") data2$Time <- strptime(data2$Time, format="%H:%M:%S") data2[1:1440,"Time"] <- format(data2[1:1440,"Time"],"2007-02-01 %H:%M:%S") data2[1441:2880,"Time"] <- format(data2[1441:2880,"Time"],"2007-02-02 %H:%M:%S") data2$Sub_metering_1 <- as.character(data2$Sub_metering_1) data2$Sub_metering_2 <- as.character(data2$Sub_metering_2) data2$Sub_metering_3 <- as.character(data2$Sub_metering_3) data2$Sub_metering_1 <- as.numeric(data2$Sub_metering_1) data2$Sub_metering_2 <- as.numeric(data2$Sub_metering_2) data2$Sub_metering_3 <- as.numeric(data2$Sub_metering_3) with(data2,plot(Time,Sub_metering_1, type="n", ylab="Energy sub metering",xlab=" ")) with(data2,points(Time,Sub_metering_1,col="black",type="l")) with(data2,points(Time,Sub_metering_2,col="red",type="l")) with(data2,points(Time,Sub_metering_3,col="blue",type="l")) legend("topright", lty=1, col=c("black","red","blue"),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) dev.copy(png,file="plot3.png") dev.off()
c8c5b0b43cb3cb55afd7993a5670d413567789d9
9598c94fe076830bfece6e366b87cff83c4c66b6
/trade spillovers/Trade spillovers NL and DE v3 1.R
c365b7ed0e674f63627e31732ffaacad4b129fa4
[]
no_license
mdg9709/spilloversNL
1b8d836ad4f5d1145f6cc15345745358d5f15b24
04388fe2bfcf764ab4a256b456db3de00ba824f9
refs/heads/master
2022-11-18T22:37:24.704113
2020-07-17T17:07:07
2020-07-17T17:07:07
280,177,983
0
0
null
null
null
null
UTF-8
R
false
false
8,248
r
Trade spillovers NL and DE v3 1.R
# --- Effect of Dutch govt spending shock on German exports # Data period:1980q1-2018q4 and 1999q1-2018q4 # 95% and 68% confidence intervals # h = 4, 8 and 12 # OLS with left-hand side in growth rates, 4 lags of x(t-1), and shock2 * (100)^3 source('~/Studie/MSc ECO/Period 5-6 MSc thesis/MSc thesis RStudio project/Scripts/Spillovers NL and DE v4 1.R') # Load packages library(ggplot2) library(gridExtra) library(dplyr) library(data.table) library(lmtest) library(sandwich) rmNL.l <- data.frame(shift(data2$rmNL, n = 1:12, type = "lead")) names(rmNL.l) = c("rmNL.l1", "rmNL.l2", "rmNL.l3", "rmNL.l4", "rmNL.l5", "rmNL.l6", "rmNL.l7", "rmNL.l8", "rmNL.l9", "rmNL.l10", "rmNL.l11", "rmNL.l12") rxNL.l <- data.frame(shift(data2$rxNL, n = 1:12, type = "lead")) names(rxNL.l) = c("rxNL.l1", "rxNL.l2", "rxNL.l3", "rxNL.l4", "rxNL.l5", "rxNL.l6", "rxNL.l7", "rxNL.l8", "rxNL.l9", "rxNL.l10", "rxNL.l11", "rxNL.l12") l.rmNL <- data.frame(shift(data2$rmNL, n = 1:4, type = "lag")) names(l.rmNL) = c("l1.rmNL", "l2.rmNL", "l3.rmNL", "l4.rmNL") l.rxNL <- data.frame(shift(data2$rxNL, n = 1:4, type = "lag")) names(l.rxNL) = c("l1.rxNL", "l2.rxNL", "l3.rxNL", "l4.rxNL") rmDE.l <- data.frame(shift(data2$rmDE, n = 1:12, type = "lead")) names(rmDE.l) = c("rmDE.l1", "rmDE.l2", "rmDE.l3", "rmDE.l4", "rmDE.l5", "rmDE.l6", "rmDE.l7", "rmDE.l8", "rmDE.l9", "rmDE.l10", "rmDE.l11", "rmDE.l12") rxDE.l <- data.frame(shift(data2$rxDE, n = 1:12, type = "lead")) names(rxDE.l) = c("rxDE.l1", "rxDE.l2", "rxDE.l3", "rxDE.l4", "rxDE.l5", "rxDE.l6", "rxDE.l7", "rxDE.l8", "rxDE.l9", "rxDE.l10", "rxDE.l11", "rxDE.l12") l.rmDE <- data.frame(shift(data2$rmDE, n = 1:4, type = "lag")) names(l.rmDE) = c("l1.rmDE", "l2.rmDE", "l3.rmDE", "l4.rmDE") l.rxDE <- data.frame(shift(data2$rxDE, n = 1:4, type = "lag")) names(l.rxDE) = c("l1.rxDE", "l2.rxDE", "l3.rxDE", "l4.rxDE") data3$shockNL2 <- (data3$shockNL / unlist(l.rxNL[1])) / sd((data3$shockNL / unlist(l.rxNL[1])), na.rm = TRUE) data3$shockNL3 <- data3$shockNL2 / 100 data3$shockDE2 <- (data3$shockDE / unlist(l.rxDE[1])) / sd((data3$shockDE / unlist(l.rxDE[1])), na.rm = TRUE) data3$shockDE3 <- data3$shockDE2 / 100 shockFR5 <- data.frame(data3$shockFR2 * 100); names(shockFR5) <- "shockFR5" shockNL5 <- data.frame(data3$shockNL2 * 100); names(shockNL5) <- "shockNL5" shockDE5 <- data.frame(data3$shockDE2 * 100); names(shockDE5) <- "shockDE5" shockES5 <- data.frame(data3$shockES2 * 100); names(shockES5) <- "shockES5" shockIT5 <- data.frame(data3$shockIT2 * 100); names(shockIT5) <- "shockIT5" data4 <- cbind(data3, shockFR5, shockNL5, shockDE5, shockIT5, shockES5, l.rmNL, l.rxNL, rmNL.l, rxNL.l, l.rmDE, l.rxDE, rmDE.l, rxDE.l) data5 <- subset(data4, select = -c(30:32, 35:37, 152:203)) h <- 12 # -- OLS regressions # -- Equation 5 lhsNLDE50 <- (data5$rxDE - data5$l1.rxDE) / data5$l1.rxDE lhsNLDE5 <- lapply(1:h, function(x) (data5[, 202+x] - data5$l1.rxDE) / data5$l1.rxDE) lhsNLDE5 <- data.frame(lhsNLDE5) names(lhsNLDE5) = paste("lhsNLDE5", 1:h, sep = "") data6 <- cbind(data5, lhsNLDE50, lhsNLDE5) NLDE5 <- lapply(1:13, function(x) lm(data6[, 214+x] ~ shockNL2 + l1.debtDE + l1.intDE + l1.lrtrDE + l1.lrgDE + l1.lryDEc + l2.debtDE + l2.intDE + l2.lrtrDE + l2.lrgDE + l2.lryDEc + l3.debtDE + l3.intDE + l3.lrtrDE + l3.lrgDE + l3.lryDEc + l4.debtDE + l4.intDE + l4.lrtrDE + l4.lrgDE + l4.lryDEc + shockDE2 + shockFR2 + shockES2 + shockIT2, data = data6)) summariDENLDE5 <- lapply(NLDE5, summary) NLDE5conf95 <- lapply(NLDE5, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.95) NLDE5conf68 <- lapply(NLDE5, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.68) NLDE5up95 <- lapply(1:13, function(x) NLDE5conf95[[x]][2,2]) NLDE5low95 <- lapply(1:13, function(x) NLDE5conf95[[x]][2,1]) NLDE5up68 <- lapply(1:13, function(x) NLDE5conf68[[x]][2,2]) NLDE5low68 <- lapply(1:13, function(x) NLDE5conf68[[x]][2,1]) betaNLDEt <- lapply(summariDENLDE5, function(x) x$coefficients[2,1]) names(betaNLDEt) <- paste("betaNLDEt", 0:h, sep = "") # -- Equation 6 lhsNLDE60 <- (data6$rgNL - data6$l1.rgNL) / data6$l1.rxDE lhsNLDE6 <- lapply(1:h, function(x) (data6[, 96+x] - data6$l1.rgNL) / data6$l1.rxDE) lhsNLDE6 <- data.frame(lhsNLDE6) names(lhsNLDE6) = paste("lhsNLDE6", 1:h, sep = "") data6 <- cbind(data6, lhsNLDE60, lhsNLDE6) NLDE6 <- lapply(1:13, function(x) lm(data6[, 227+x] ~ shockNL3 + l1.debtNL + l1.intNL + l1.lrtrNL + l1.lrgNL + l1.lryNLc + l2.debtNL + l2.intNL + l2.lrtrNL + l2.lrgNL + l2.lryNLc + l3.debtNL + l3.intNL + l3.lrtrNL + l3.lrgNL + l3.lryNLc + l4.debtNL + l4.intNL + l4.lrtrNL + l4.lrgNL + l4.lryNLc + shockDE3 + shockFR3 + shockES3 + shockIT3, data = data6)) summariesNLDE6 <- lapply(NLDE6, summary) NLDE6conf95 <- lapply(NLDE6, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.95) NLDE6conf68 <- lapply(NLDE6, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.68) NLDE6up95 <- lapply(1:13, function(x) NLDE6conf95[[x]][2,2]) NLDE6low95 <- lapply(1:13, function(x) NLDE6conf95[[x]][2,1]) NLDE6up68 <- lapply(1:13, function(x) NLDE6conf68[[x]][2,2]) NLDE6low68 <- lapply(1:13, function(x) NLDE6conf68[[x]][2,1]) gammaNLDEt <- lapply(summariesNLDE6, function(x) x$coefficients[2,1]) names(gammaNLDEt) <- paste("gammaNLDEt", 0:h, sep = "") # -- Cumulative multiplier mNLDEtc <- cumsum(betaNLDEt) / cumsum(as.numeric(gammaNLDEt)); as.numeric(mNLDEtc) # --- Effect of German govt spending shock on Dutch exports # -- Equation 5 lhsDENL50 <- (data6$rxNL - data6$l1.rxNL) / data6$l1.rxNL lhsDENL5 <- lapply(1:h, function(x) (data6[, 170+x] - data6$l1.rxNL) / data6$l1.rxNL) lhsDENL5 <- data.frame(lhsDENL5) names(lhsDENL5) = paste("lhsDENL5", 1:h, sep = "") data6 <- cbind(data6, lhsDENL50, lhsDENL5) DENL5 <- lapply(1:13, function(x) lm(data6[, 240+x] ~ shockDE2 + l1.debtNL + l1.intNL + l1.lrtrNL + l1.lrgNL + l1.lryNLc + l2.debtNL + l2.intNL + l2.lrtrNL + l2.lrgNL + l2.lryNLc + l3.debtNL + l3.intNL + l3.lrtrNL + l3.lrgNL + l3.lryNLc + l4.debtNL + l4.intNL + l4.lrtrNL + l4.lrgNL + l4.lryNLc + shockFR2 + shockES2 + shockIT2 + shockNL2, data = data6)) summariDEDENL5 <- lapply(DENL5, summary) DENL5conf95 <- lapply(DENL5, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.95) DENL5conf68 <- lapply(DENL5, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.68) DENL5up95 <- lapply(1:13, function(x) DENL5conf95[[x]][2,2]) DENL5low95 <- lapply(1:13, function(x) DENL5conf95[[x]][2,1]) DENL5up68 <- lapply(1:13, function(x) DENL5conf68[[x]][2,2]) DENL5low68 <- lapply(1:13, function(x) DENL5conf68[[x]][2,1]) betaDENLt <- lapply(summariDEDENL5, function(x) x$coefficients[2,1]) names(betaDENLt) <- paste("betaDENLt", 0:h, sep = "") # -- Equation 6 lhsDENL60 <- (data6$rgDE - data6$l1.rgDE) / data6$l1.rxNL lhsDENL6 <- lapply(1:h, function(x) (data6[, 84+x] - data6$l1.rgDE) / data6$l1.rxNL) lhsDENL6 <- data.frame(lhsDENL6) names(lhsDENL6) = paste("lhsDENL6", 1:h, sep = "") data6 <- cbind(data6, lhsDENL60, lhsDENL6) DENL6 <- lapply(1:13, function(x) lm(data6[, 253+x] ~ shockDE3 + l1.debtDE + l1.intDE + l1.lrtrDE + l1.lrgDE + l1.lryDEc + l2.debtDE + l2.intDE + l2.lrtrDE + l2.lrgDE + l2.lryDEc + l3.debtDE + l3.intDE + l3.lrtrDE + l3.lrgDE + l3.lryDEc + l4.debtDE + l4.intDE + l4.lrtrDE + l4.lrgDE + l4.lryDEc + shockNL3 + shockFR3 + shockES3 + shockIT3, data = data6)) summariesDENL6 <- lapply(DENL6, summary) DENL6conf95 <- lapply(DENL6, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.95) DENL6conf68 <- lapply(DENL6, coefci, vcov = NeweyWest, lag = 0, prewhite = FALSE, level = 0.68) DENL6up95 <- lapply(1:13, function(x) DENL6conf95[[x]][2,2]) DENL6low95 <- lapply(1:13, function(x) DENL6conf95[[x]][2,1]) DENL6up68 <- lapply(1:13, function(x) DENL6conf68[[x]][2,2]) DENL6low68 <- lapply(1:13, function(x) DENL6conf68[[x]][2,1]) gammaDENLt <- lapply(summariesDENL6, function(x) x$coefficients[2,1]) names(gammaDENLt) <- paste("gammaDENLt", 0:h, sep = "") # -- Cumulative multiplier mDENLtc <- cumsum(betaDENLt) / cumsum(as.numeric(gammaDENLt)); as.numeric(mDENLtc)
05131cde1e2784cf342ecaa29e7b756fecc45636
a42930bc351c40f425fc147763193990c267e0c2
/app.R
6c78102e258b7320934a3b2c876ad7b141961397
[]
no_license
kggen/Feba-Sofia-Air
555677b83137ad5e059156c69db87e6c50908a54
1307a740a16e7d857cf4c1767b5b47b3cc670b6b
refs/heads/master
2020-04-25T00:41:27.147258
2019-02-24T20:41:40
2019-02-24T20:41:40
172,386,092
0
0
null
null
null
null
UTF-8
R
false
false
2,198
r
app.R
library(shiny) library(leaflet) library(RColorBrewer) ui <- bootstrapPage( titlePanel("FEBA - Sofia Air Project (Under construction)"), tags$style(type = "text/css", "html, body {width:100%;height:100%}"), leafletOutput("map", width = "100%", height = "100%"), absolutePanel(top = 70, right = 10, sliderInput("date_range", "Date and time of prediction: (NOT INTEGRATED YET)", min = as.POSIXct("2019-02-25 00:00"), max = as.POSIXct("2019-02-25 23:00"), value = c(as.POSIXct("2019-02-25 01:00")), timeFormat = "%a %H:%M", ticks = F, animate = T ) ) ) server <- function(input, output, session) { # Reactive expression for the data subsetted to what the user selected sofia_summary <- read.csv("./data/sofia_summary.csv") filteredData <- reactive({ sofia_summary[] }) # This reactive expression represents the palette function, # which changes as the user makes selections in UI. output$map <- renderLeaflet({ # Use leaflet() here, and only include aspects of the map that # won't need to change dynamically (at least, not unless the # entire map is being torn down and recreated). leaflet(sofia_summary) %>% addTiles() %>% fitBounds(~min(lng), ~min(lat), ~max(lng), ~max(lat)) }) # Incremental changes to the map (in this case, replacing the # circles when a new color is chosen) should be performed in # an observer. Each independent set of things that can change # should be managed in its own observer. observe({ leafletProxy("map", data = filteredData()) %>% clearShapes() %>% addCircleMarkers(weight = 0.1, color = "red") %>% addRectangles(lat1 = (min(sofia_summary$lat)-0.01), lng1 = (max(sofia_summary$lng)-0.18), lat2 = (min(sofia_summary$lat)+0.13), lng2 = (min(sofia_summary$lng)+0.18), fillColor = "transparent") }) # Use a separate observer to recreate the legend as needed. } shinyApp(ui, server)
ae3a7708f6bbe574adab76ef7c0656696dbfa1f6
846d6f743403ba31d3e70c5f502a2fd90200fcb1
/impl/03_data_analysis/03_univariate/00_History/ARIMA_fitting_XBT_v08.R
ab6572086cc5c5f7426ba4f63d9618bc7f6a4c25
[]
no_license
yangboyubyron/thesis-google-crypto-trading
4c5fb17721c62f97f7b75f1125110b575f6a948d
c920cbf3547d6fa670a389b4dcce9d7433c9e5e3
refs/heads/master
2022-01-05T15:15:17.005009
2019-02-03T16:31:44
2019-02-03T16:31:44
null
0
0
null
null
null
null
WINDOWS-1250
R
false
false
12,764
r
ARIMA_fitting_XBT_v08.R
setwd("C:/Users/Vojtěch Pulec/OneDrive/Dokumenty/HU/Thesis/master-thesis_Pulec") # thats for me to get to proprer level wd <- getwd() wd <- paste(wd, "/data/03_final_sample/Kraken", sep = "") setwd(wd) rm(list=ls()) library("tseries") library("zoo") library("forecast") library("ggplot2") library('stats') library("gridExtra") library("reshape2") library("tcltk") library("sarima") # 1) *********** data prep ****************************************** load(file="XBT_5minute_returns.Rdata") # 2) *********** preparing structure for fit ****************************** #setting up parametr of the window window_start <- 81200 #any number from number of lags to nrow-1 window_end <- 82200 #any number from start to nrow lookback <- 48 five_minute_data <- five_minute_data[c((window_start-lookback):window_end),] # Progress bar # before loop pb <- tkProgressBar(title = "progress bar", min = 0, max = nrow(OM_uni), width = 1000) # into the loop setTkProgressBar(pb, i, label=paste( round(i/(nrow(OM_uni))*1000, 0),"‰ done")) #preparing struncture five_minute_data[,19:50] <- 1 colnames(five_minute_data)[c(19,22,25,28,31)] <- c("A_m5","A_m10","A_m15","A_m30", "A_m60") #mean for x minutes forward estimate colnames(five_minute_data)[c(20,23,26,29,32)] <- c("A_u5(95%)", "A_u10(95%)", "A_u15(95%)", "A_u30(95%)","A_u60(95%)") #upper bound for x minutes forward estimate colnames(five_minute_data)[c(21,24,27,30,33)] <- c("A_l5(95%)" ,"A_l10(95%)", "A_l15(95%)", "A_l30(95%)", "A_l60(95%)") # lower bound for x minutes forward estimate colnames(five_minute_data)[c(34,35)] <- c("A_BIC", "A_AICC") # AIC a BIC criteria for choosing proper order colnames(five_minute_data)[c(36:40)] <- c("R_5","R_10","R_15","R_30", "R_60") #real values colnames(five_minute_data)[c(41:45)] <- c("A_SQe_5","A_SQe_10","A_SQe_15","A_SQe_30", "A_SQe_60") #squared errors of estimate colnames(five_minute_data)[c(46:50)] <- c("A_DA_5","A_DA_10","A_DA_15","A_DA_30", "A_DA_60") #directional accuracy # 4) *************** looping to fit ARIMA ****************************************************************************************** timeframe <- lookback #reference period shift <- timeframe - 1 # last block of time frame it starts forecasting 5/10/15/30/60 mins pb <- tkProgressBar(title = "progress bar", min = 0, max = (nrow(five_minute_data)- timeframe), width = 1000) for(i in 1:(nrow(five_minute_data)-timeframe)){ fit <- auto.arima(five_minute_data[(i:(i+shift)),18], d = 0) forecast60 <- forecast(fit, h=12) # fitting 5 minutes ahead five_minute_data[i+shift,19] <- forecast60$mean[1] + 1 five_minute_data[i+shift,20] <- forecast60$upper[1,2] + 1 five_minute_data[i+shift,21] <- forecast60$lower[1,2] + 1 # fitting 10 minute ahead for(z in 1:2){ five_minute_data[i+shift,22] <- (forecast60$mean[z] + 1) * five_minute_data[i+shift,22] five_minute_data[i+shift,23] <- (forecast60$upper[z,2] + 1) * five_minute_data[i+shift,23] five_minute_data[i+shift,24] <- (forecast60$lower[z,2] + 1) * five_minute_data[i+shift,24] } # fitting 15 minute ahead for(z in 1:3){ five_minute_data[i+shift,25] <- (forecast60$mean[z] + 1) * five_minute_data[i+shift,25] five_minute_data[i+shift,26] <- (forecast60$upper[z,2] + 1) * five_minute_data[i+shift,26] five_minute_data[i+shift,27] <- (forecast60$lower[z,2] + 1) * five_minute_data[i+shift,27] } # fitting 30 minute ahead for(z in 1:6){ five_minute_data[i+shift,28] <- (forecast60$mean[z] + 1) * five_minute_data[i+shift,28] five_minute_data[i+shift,29] <- (forecast60$upper[z,2] + 1) * five_minute_data[i+shift,29] five_minute_data[i+shift,30] <- (forecast60$lower[z,2] + 1) * five_minute_data[i+shift,30] } # fitting 60 minute ahead for(z in 1:12){ five_minute_data[i+shift,31] <- (forecast60$mean[z] + 1) * five_minute_data[i+shift,31] five_minute_data[i+shift,32] <- (forecast60$upper[z,2] + 1) * five_minute_data[i+shift,32] five_minute_data[i+shift,33] <- (forecast60$lower[z,2] + 1) * five_minute_data[i+shift,33] } five_minute_data[i+shift,34] <- forecast60$model$bic five_minute_data[i+shift,35] <- forecast60$model$aicc # gettting real returns five_minute_data[i+shift,36] <- log(five_minute_data[i+shift+1,3]/five_minute_data[i+shift,3]) + 1 five_minute_data[i+shift,37] <- log(five_minute_data[i+shift+2,3]/five_minute_data[i+shift,3]) + 1 five_minute_data[i+shift,38] <- log(five_minute_data[i+shift+3,3]/five_minute_data[i+shift,3]) + 1 five_minute_data[i+shift,39] <- log(five_minute_data[i+shift+6,3]/five_minute_data[i+shift,3]) + 1 five_minute_data[i+shift,40] <- log(five_minute_data[i+shift+12,3]/five_minute_data[i+shift,3]) + 1 # gettting squred error five_minute_data[i+shift,41] <- (five_minute_data[i+shift,36] - five_minute_data[i+shift,19])^2 five_minute_data[i+shift,42] <- (five_minute_data[i+shift,37] - five_minute_data[i+shift,22])^2 five_minute_data[i+shift,43] <- (five_minute_data[i+shift,38] - five_minute_data[i+shift,25])^2 five_minute_data[i+shift,44] <- (five_minute_data[i+shift,39] - five_minute_data[i+shift,28])^2 five_minute_data[i+shift,45] <- (five_minute_data[i+shift,40] - five_minute_data[i+shift,31])^2 # gettting direction accuracy five_minute_data[i+shift,46] <- (sign(five_minute_data[i+shift,36]-1) == sign(five_minute_data[i+shift,19]-1))*1 five_minute_data[i+shift,47] <- (sign(five_minute_data[i+shift,37]-1) == sign(five_minute_data[i+shift,22]-1))*1 five_minute_data[i+shift,48] <- (sign(five_minute_data[i+shift,38]-1) == sign(five_minute_data[i+shift,25]-1))*1 five_minute_data[i+shift,49] <- (sign(five_minute_data[i+shift,39]-1) == sign(five_minute_data[i+shift,28]-1))*1 five_minute_data[i+shift,50] <- (sign(five_minute_data[i+shift,40]-1) == sign(five_minute_data[i+shift,31]-1))*1 setTkProgressBar(pb, i, label=paste( round(i/(nrow(five_minute_data)-timeframe)*1000, 0),"‰ done")) } save(five_minute_data,file=paste(window_start,"_", window_end,"_", lookback,"_five_minut_ARIMA_fit_XBT.Rdata", sep = "")) forecasts <- five_minute_data[which(five_minute_data$A_m5 !=1),] time_vector <- forecasts$time save(time_vector,file=paste(window_start,"_", window_end,"_", lookback,"_time_vector_five_minut_ARIMA_fit_XBT.Rdata", sep = "")) #actual returns share returns_benchmark <- five_minute_data[which(five_minute_data$A_m5 !=1),] returns_benchmark$five <- nrow(returns_benchmark[which(returns_benchmark$R_5 > 1),])/(nrow(returns_benchmark)-sum(is.na(five_minute_data$A_m5)))*100 returns_benchmark$ten <- nrow(returns_benchmark[which(returns_benchmark$R_10 > 1),])/(nrow(returns_benchmark)-sum(is.na(five_minute_data$A_m10)))*100 returns_benchmark$fifteen <- nrow(returns_benchmark[which(returns_benchmark$R_15 > 1),])/(nrow(returns_benchmark)-sum(is.na(five_minute_data$A_m15)))*100 returns_benchmark$thirty <- nrow(returns_benchmark[which(returns_benchmark$R_30 > 1),])/(nrow(returns_benchmark)-sum(is.na(five_minute_data$A_m30)))*100 returns_benchmark$sixty <- nrow(returns_benchmark[which(returns_benchmark$R_60 > 1),])/(nrow(returns_benchmark)-sum(is.na(five_minute_data$A_m60)))*100 returns_benchmark <- returns_benchmark[1,-c(1:50)] #MDA returns_benchmark[2,1] <- sum(forecasts$A_DA_5,na.rm = TRUE) / (nrow(forecasts) - sum(is.na(forecasts$A_DA_5)))*100 returns_benchmark[2,2] <- sum(forecasts$A_DA_10, na.rm = TRUE) / (nrow(forecasts) - sum(is.na(forecasts$A_DA_10)))*100 returns_benchmark[2,3] <- sum(forecasts$A_DA_15,na.rm = TRUE) / (nrow(forecasts) - sum(is.na(forecasts$A_DA_15)))*100 returns_benchmark[2,4] <- sum(forecasts$A_DA_30,na.rm = TRUE) / (nrow(forecasts) - sum(is.na(forecasts$A_DA_30)))*100 returns_benchmark[2,5] <- sum(forecasts$A_DA_60, na.rm = TRUE) / (nrow(forecasts) - sum(is.na(forecasts$A_DA_60)))*100 #actual change in % temp <- as.data.frame(matrix(1, ncol = 5, nrow = nrow(forecasts))) for(i in 1:nrow(forecasts)){ temp[i,1] <- (forecasts$R_5[i] - 1)*100 temp[i,2] <- (forecasts$R_10[i] -1)*100 temp[i,3] <- (forecasts$R_15[i] -1)*100 temp[i,4] <- (forecasts$R_30[i] -1)*100 temp[i,5] <- (forecasts$R_60[i] -1)*100 } returns_benchmark[3,1] <- mean(temp[,1],na.rm = TRUE) returns_benchmark[3,2] <- mean(temp[,2],na.rm = TRUE) returns_benchmark[3,3] <- mean(temp[,3],na.rm = TRUE) returns_benchmark[3,4] <- mean(temp[,4],na.rm = TRUE) returns_benchmark[3,5] <- mean(temp[,5],na.rm = TRUE) #Actual preditcion temp <- as.data.frame(matrix(1, ncol = 5, nrow = nrow(forecasts))) for(i in 1:nrow(forecasts)){ temp[i,1] <- ((forecasts$A_m5[i]) - 1)*100 temp[i,2] <- ((forecasts$A_m10[i]) -1)*100 temp[i,3] <- ((forecasts$A_m15[i]) -1)*100 temp[i,4] <- ((forecasts$A_m30[i]) -1)*100 temp[i,5] <- ((forecasts$A_m60[i]) -1)*100 } returns_benchmark[4,1] <- mean(temp[,1],na.rm = TRUE) returns_benchmark[4,2] <- mean(temp[,2],na.rm = TRUE) returns_benchmark[4,3] <- mean(temp[,3],na.rm = TRUE) returns_benchmark[4,4] <- mean(temp[,4],na.rm = TRUE) returns_benchmark[4,5] <- mean(temp[,5],na.rm = TRUE) # MSE of the prediction temp <- as.data.frame(matrix(1, ncol = 5, nrow = nrow(forecasts))) for(i in 1:nrow(forecasts)){ temp[i,1] <- ((forecasts$A_m5[i] - forecasts$R_5[i])^2) temp[i,2] <- ((forecasts$A_m10[i] - forecasts$R_10[i])^2) temp[i,3] <- ((forecasts$A_m15[i] - forecasts$R_15[i])^2) temp[i,4] <- ((forecasts$A_m30[i] - forecasts$R_30[i])^2) temp[i,5] <- ((forecasts$A_m60[i] - forecasts$R_60[i])^2) } returns_benchmark[5,1] <- mean(temp[,1],na.rm = TRUE) returns_benchmark[5,2] <- mean(temp[,2],na.rm = TRUE) returns_benchmark[5,3] <- mean(temp[,3],na.rm = TRUE) returns_benchmark[5,4] <- mean(temp[,4],na.rm = TRUE) returns_benchmark[5,5] <- mean(temp[,5],na.rm = TRUE) save(returns_benchmark,file=paste(window_start,"_", window_end,"_", lookback,"_five_minut_ARIMA_benchmark_XBT.Rdata", sep = "")) # ******************* plot "analysis"********************** # ********** 5 minute******************************************* ggplot(five_minute_data, aes(five_minute_data$time)) + geom_line(aes(y=five_minute_data$A_m5), colour="red") + #estimates geom_line(aes(y=five_minute_data$R_5), colour="green")+ #real geom_line(aes(y=five_minute_data$`A_u5(95%)`), colour="black")+ #upper estimated bound geom_line(aes(y=five_minute_data$`A_l5(95%)`), colour="black") #lower estimated bound # ********** 10 minute******************************************* ggplot(five_minute_data, aes(five_minute_data$time)) + geom_line(aes(y=five_minute_data$A_m10), colour="red") + #estimates geom_line(aes(y=five_minute_data$R_10), colour="green")+ #real geom_line(aes(y=five_minute_data$`A_u10(95%)`), colour="black")+ #upper estimated bound geom_line(aes(y=five_minute_data$`A_l10(95%)`), colour="black") #lower estimated bound # ********** 15 minute******************************************* ggplot(five_minute_data, aes(five_minute_data$time)) + geom_line(aes(y=five_minute_data$A_m15), colour="red") + #estimates geom_line(aes(y=five_minute_data$R_15), colour="green")+ #real geom_line(aes(y=five_minute_data$`A_u15(95%)`), colour="black")+ #upper estimated bound geom_line(aes(y=five_minute_data$`A_l15(95%)`), colour="black") #lower estimated bound # ********** 30 minute******************************************* ggplot(five_minute_data, aes(five_minute_data$time)) + geom_line(aes(y=five_minute_data$A_m30), colour="red") + #estimates geom_line(aes(y=five_minute_data$R_30), colour="green")+ #real geom_line(aes(y=five_minute_data$`A_u30(95%)`), colour="black")+ #upper estimated bound geom_line(aes(y=five_minute_data$`A_l30(95%)`), colour="black") #lower estimated bound # ********** 60 minute******************************************* ggplot(five_minute_data, aes(five_minute_data$time)) + geom_line(aes(y=five_minute_data$A_m60), colour="red") + #estimates geom_line(aes(y=five_minute_data$R_60), colour="green")+ #real geom_line(aes(y=five_minute_data$`A_u60(95%)`), colour="black")+ #upper estimated bound geom_line(aes(y=five_minute_data$`A_l60(95%)`), colour="black") #lower estimated bound
aefebcd7480041944d4930ad64e621ada2459f97
7f72ac13d08fa64bfd8ac00f44784fef6060fec3
/RGtk2/man/pangoGlyphItemIterInitStart.Rd
b3c2d88633380bacba9c597dc5b415875fc9e2c0
[]
no_license
lawremi/RGtk2
d2412ccedf2d2bc12888618b42486f7e9cceee43
eb315232f75c3bed73bae9584510018293ba6b83
refs/heads/master
2023-03-05T01:13:14.484107
2023-02-25T15:19:06
2023-02-25T15:20:41
2,554,865
14
9
null
2023-02-06T21:28:56
2011-10-11T11:50:22
R
UTF-8
R
false
false
784
rd
pangoGlyphItemIterInitStart.Rd
\alias{pangoGlyphItemIterInitStart} \name{pangoGlyphItemIterInitStart} \title{pangoGlyphItemIterInitStart} \description{Initializes a \code{\link{PangoGlyphItemIter}} structure to point to the first cluster in a glyph item. See \code{\link{PangoGlyphItemIter}} for details of cluster orders.} \usage{pangoGlyphItemIterInitStart(object, glyph.item, text)} \arguments{ \item{\verb{object}}{[\code{\link{PangoGlyphItemIter}}] a \code{\link{PangoGlyphItemIter}}} \item{\verb{glyph.item}}{[\code{\link{PangoGlyphItem}}] the glyph item to iterate over} \item{\verb{text}}{[char] text corresponding to the glyph item} } \details{ Since 1.22} \value{[logical] \code{FALSE} if there are no clusters in the glyph item} \author{Derived by RGtkGen from GTK+ documentation} \keyword{internal}
afc030be36daade19166162d0c4e28beecf80d96
5588a0105e712197f67b459ad2101436005cf57c
/Assignments/Getting and Cleaning Data/UCI_HAR/run_analysis.R
4871323a178408dc1d4d1588ce76a39be4ba8d45
[]
no_license
emersson126/Data-Science-Specialization-program
189ef3386a4b65315d95f1dc192a142539d17c8e
ae4b22e4265256278219d5a385927f79d71a4d4b
refs/heads/master
2020-04-12T04:57:55.375286
2016-04-29T19:21:54
2016-04-29T19:21:54
162,311,999
0
0
null
null
null
null
UTF-8
R
false
false
4,695
r
run_analysis.R
## run_analysis.R # 0-a Load packages #---------------------------------------------------------------------------------------- library(magrittr) # %>% library(dplyr) # bind_cols(), bind_rows(), left_join() library(stringr) # str_to_title() #---------------------------------------------------------------------------------------- # 0-b. Download, unzip, and read the data #---------------------------------------------------------------------------------------- url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(url, "dataset.zip") newwd <- paste(getwd(), "dataset", sep = "/") unzip("dataset.zip", exdir = newwd) files <- list.files(newwd, recursive = TRUE, full.names = TRUE) raw_files <- files[c((1:2), (14:16), (26:28))] %>% lapply(function(x) read.delim( x, header = F, sep = " " ) ) x_files <- lapply(raw_files[c(4,7)], function(x) apply( x, 1, function(y) y[!is.na(y)] ) ) %>% lapply(function(x) data.frame( matrix( unlist(x), byrow = T, ncol = 561 ), stringsAsFactors = F ) ) #---------------------------------------------------------------------------------------- # 1. Merge files and union the `test` and `training` datasets #---------------------------------------------------------------------------------------- colnames(raw_files[[5]]) <- "V2" colnames(raw_files[[8]]) <- "V2" test <- bind_cols(raw_files[[3]], raw_files[[5]], x_files[[1]]) training <- bind_cols(raw_files[[6]], raw_files[[8]], x_files[[2]]) all_trials <- bind_rows(test, training) #---------------------------------------------------------------------------------------- # 2. Extract only the mean and standard deviation measurements #---------------------------------------------------------------------------------------- features <- raw_files[2] col_vec1 <- c("mean()", "std()") %>% paste(collapse = "|") %>% grep(features[[1]]$V2) col_vec2 <- col_vec1 + 2 col_vec2 <- c(c(1,2), col_vec2) all_trials <- all_trials[ ,col_vec2] #---------------------------------------------------------------------------------------- # 3. Give descriptive activity names #---------------------------------------------------------------------------------------- activities <- raw_files[1] activities[[1]]$V2 <- gsub("_", " ", activities[[1]]$V2) %>% str_to_title() analysis_table <- left_join(x = all_trials, y = activities[[1]], by = c("V2" = "V1")) %>% select(1,-2,82,3:81) #---------------------------------------------------------------------------------------- # 4. Give descriptive variable names #---------------------------------------------------------------------------------------- features <- features[[1]] features <- features[col_vec1, ] cnames <- c("Subject", "Activity", as.character(features$V2)) colnames(analysis_table) <- cnames write.table(analysis_table, "analysis_table.txt", row.names = TRUE) #---------------------------------------------------------------------------------------- # 5. GROUP BY average(*), activity -- and -- GROUP BY average(*), subject #---------------------------------------------------------------------------------------- summary_table <- aggregate(analysis_table[-(1:2)], by = list(analysis_table$Subject, analysis_table$Activity), FUN = mean) write.table(summary_table, "summary_table.txt", row.names = TRUE) #----------------------------------------------------------------------------------------
3f242dc62375a324fa6ad3529a4e3daba5f8d9b0
76f4e6ea643bad0c60ab2485cd40e5b87cdc8b51
/nanopore_example_run/scripts/basic_sequence_qc.r
9c2794b323dc6ba1558f1d3f3feda8641b1c300f
[]
no_license
ngleadall/train_malta_nanopore
aeff1c240b4b871f75410098784e61aa9f0cd055
53e2d0cdb364e4ce494fef0202db0e2c80114fc0
refs/heads/master
2020-03-28T17:33:50.646166
2018-09-17T14:30:01
2018-09-17T14:30:01
148,801,909
0
0
null
null
null
null
UTF-8
R
false
false
798
r
basic_sequence_qc.r
# Plotting sequence run summary data # Nick Gleadall - ng384@cam.ac.uk #Pre-step - clear R envronment ( good practice ) rm( list=ls() ) # Step 1 - set the working directory setwd( "~/data/" ) # Step 2 - read in the sequencing summary file summary_data <- read.table( "nanopore_example_run/basecalled_reads/sequencing_summary.txt", sep="\t", header=TRUE) # Step 3 - quickly view the data View( summary_data ) # Step 4 - plot read length historgram hist( summary_data$sequence_length_template , main="Read length distribution" , xlab = "Read Length" ) # Step 5 - plot quality against read length plot( summary_data$mean_qscore_template , summary_data$sequence_length_template , main="Sequence length against quality score", ylab="Read length" , xlab="Quality score")
df5d43cb2f9c0440ba5b26652f812a9a196c7709
7896e7eabb12e7a6d9417e83d0a3155603815a2a
/euler/R/tests/tests.R
64ad8c88ec5897ad129885f20555e0215d94d18b
[]
no_license
ajdust/euler
7461df96a0926577a7c326e152b730f9c8e4dbb0
428d9f06bb7789741289e7642b764c5eb7220482
refs/heads/master
2023-08-24T16:26:51.233397
2021-10-28T23:52:37
2021-10-28T23:52:37
null
0
0
null
null
null
null
UTF-8
R
false
false
428
r
tests.R
library(euler) library(RUnit) library(jsonlite) library(hash) ans <- fromJSON("../answers.json") ans <- lapply(ans, as.numeric) problem01_is_correct <- function() { checkEquals(ans$`1`, problem01()) } problem02_is_correct <- function() { checkEquals(ans$`2`, problem02()) } problem03_is_correct <- function() { checkEquals(ans$`3`, problem03()) } problem04_is_correct <- function() { checkEquals(ans$`4`, problem04()) }
4807d83da65f612ca496ff4780dfb0825c413ed8
50a3642a16fdc6e3e30141eb64066766a822d67f
/man/PC_model.Rd
77a8200a91a26d1c8212930fbfc0ea4783208fb1
[ "BSD-2-Clause" ]
permissive
JGCRI/pridr
85687b997325ce2a3254f617d94fcc6d354f940c
5db4e202fc4e8606a74c080e0d7fcae8cb71703b
refs/heads/main
2023-04-27T03:49:03.966193
2023-04-07T18:10:57
2023-04-07T18:10:57
432,577,581
4
0
BSD-2-Clause
2023-04-07T18:10:59
2021-11-27T23:35:43
R
UTF-8
R
false
true
610
rd
PC_model.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/pca_ineq.R \name{PC_model} \alias{PC_model} \title{Function to calculate deciles using PC model} \usage{ PC_model( df, grouping_variables = c("country", "year"), value_col = "Income..net.", id_col = c("country") ) } \arguments{ \item{df}{dataframe with all IV data. These are output by `compile_IV_data()`.} \item{grouping_variables}{variables to group by} \item{value_col}{Name of values to be output.} \item{id_col}{column to split by for parallelization} } \description{ Function to calculate deciles using PC model }
23421883df890b842d39c8a387b5e5e9d6e6a0f9
ac42c7b87b90f08c8ec9b12d5e17a534ffb84b02
/man/cr_buildstep_secret.Rd
760cc8c67793aaa1ccd7318ecfd142edb15c5a0c
[]
no_license
alainlompo/googleCloudRunner
990c819c9f4f46ca5a39a720627da4003a6410f3
6622d22f1c19d58f6b5888ae929f32d86b57a1c6
refs/heads/master
2023-09-03T15:33:00.968050
2021-10-27T21:18:23
2021-10-27T21:18:23
null
0
0
null
null
null
null
UTF-8
R
false
true
2,022
rd
cr_buildstep_secret.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/buildsteps_templates.R \name{cr_buildstep_secret} \alias{cr_buildstep_secret} \title{Create a buildstep for using Secret Manager} \usage{ cr_buildstep_secret(secret, decrypted, version = "latest", ...) } \arguments{ \item{secret}{The secret data name in Secret Manager} \item{decrypted}{The name of the file the secret will be decrypted into} \item{version}{The version of the secret} \item{...}{Other arguments sent to \link{cr_buildstep_bash}} } \description{ This is the preferred way to manage secrets for files, rather than \link{cr_buildstep_decrypt}, as it stores the encrypted file in the cloud rather than in your project workspace. For single environment values, \link{cr_build_yaml_secrets} may be more suitable. } \details{ This is for downloading encrypted files from Google Secret Manager. You will need to add the Secret Accessor Cloud IAM role to the Cloud Build service account to use it. Once you have uploaded your secret file and named it, it is available for Cloud Build to use. } \examples{ cr_buildstep_secret("my_secret", decrypted = "/workspace/secret.json") } \seealso{ How to set up secrets using \href{https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-secrets-credentials}{Secret Manager} \link{cr_build_yaml_secrets} let you directly support environment arguments in the buildsteps Other Cloud Buildsteps: \code{\link{cr_buildstep_bash}()}, \code{\link{cr_buildstep_decrypt}()}, \code{\link{cr_buildstep_df}()}, \code{\link{cr_buildstep_docker}()}, \code{\link{cr_buildstep_edit}()}, \code{\link{cr_buildstep_extract}()}, \code{\link{cr_buildstep_gcloud}()}, \code{\link{cr_buildstep_gitsetup}()}, \code{\link{cr_buildstep_mailgun}()}, \code{\link{cr_buildstep_nginx_setup}()}, \code{\link{cr_buildstep_pkgdown}()}, \code{\link{cr_buildstep_run}()}, \code{\link{cr_buildstep_r}()}, \code{\link{cr_buildstep_slack}()}, \code{\link{cr_buildstep}()} } \concept{Cloud Buildsteps}
fc69950d25196f4ef02a5d0e1f8d796e8946de7a
80ccc4b25a784d6d93c4c5efdc88fa5174c64b94
/challenge.r
086724a67f8dc76ed8d661e958fcb11af1d1874c
[]
no_license
zimmermankz/fullstory-challenge
0eba87c004fa129f403dfcd91cd6bb26d4241745
93a50cbb8758cb9cda6ef4bcc532782c1c7e73d7
refs/heads/master
2020-06-08T19:21:28.239192
2019-06-23T02:12:15
2019-06-23T02:12:15
193,291,692
0
0
null
null
null
null
UTF-8
R
false
false
6,348
r
challenge.r
library(dplyr) #load data trip.data <- read.csv("yellow_tripdata_2017-06.csv") zone.lookup <- read.csv("taxi+_zone_lookup.csv") ######## create additional columns ######## #find length of trip (trip time will be in seconds) trip.data$tpep_dropoff_datetime <- as.POSIXct(as.character(trip.data$tpep_dropoff_datetime), format="%Y-%m-%d %H:%M:%S") trip.data$tpep_pickup_datetime <- as.POSIXct(as.character(trip.data$tpep_pickup_datetime), format="%Y-%m-%d %H:%M:%S") trip.data$trip_time <- as.numeric(trip.data$tpep_dropoff_datetime - trip.data$tpep_pickup_datetime) #compute income to driver as sum of fare and tips trip.data$income <- trip.data$fare_amount + trip.data$tip_amount #compute total income per hour, as well as tips/hour and fare/hour trip.data$income_per_hour <- (trip.data$income / trip.data$trip_time) * 3600 trip.data$tips_per_hour <- (trip.data$tip_amount / trip.data$trip_time) * 3600 trip.data$fare_per_hour <- (trip.data$fare_amount / trip.data$trip_time) * 3600 #separate out hour as own column (to find best time of day) trip.data$pickup_hour <- strftime(trip.data$tpep_pickup_datetime, format="%H") trip.data$day_of_week <- weekdays(trip.data$tpep_pickup_datetime, F) #remove trips with 0 length, those seem like errors trip.data <- trip.data[which(trip.data$trip_distance > 0), ] #some trips are 0 seconds (or other unreasonably low numbers), define minimum length to avoid what seem to be errors min.trip.time = 30 min.at.location = 30 ######## find the best pickup location ######## #by income income.by.pickup.location <- trip.data[which(trip.data$trip_time >= min.trip.time), c("PULocationID", "income_per_hour", "trip_time")] %>% group_by(PULocationID) %>% filter(n() >= min.at.location) %>% summarise(income_per_hour = weighted.mean(income_per_hour, trip_time)) income.by.pickup.location <- merge(income.by.pickup.location, zone.lookup[,c("LocationID", "Borough", "Zone")], by.x="PULocationID", by.y="LocationID") income.by.pickup.location[order(-income.by.pickup.location$income_per_hour), ] #by fare # fare.by.pickup.location <- trip.data[which(trip.data$trip_time >= min.trip.time), c("PULocationID", "fare_per_hour", "trip_time")] %>% # group_by(PULocationID) %>% # filter(n() >= min.at.location) %>% # summarise(fare_per_hour = weighted.mean(fare_per_hour, trip_time)) # fare.by.pickup.location <- merge(fare.by.pickup.location, zone.lookup[,c("LocationID", "Borough", "Zone")], by.x="PULocationID", by.y="LocationID") # head(fare.by.pickup.location[order(-fare.by.pickup.location$fare_per_hour), ]) #by tips # tips.by.pickup.location <- trip.data[which(trip.data$trip_time >= min.trip.time), c("PULocationID", "tips_per_hour", "trip_time")] %>% # group_by(PULocationID) %>% # filter(n() >= min.at.location) %>% # summarise(tips_per_hour = weighted.mean(tips_per_hour, trip_time)) # tips.by.pickup.location <- merge(tips.by.pickup.location, zone.lookup[,c("LocationID", "Borough", "Zone")], by.x="PULocationID", by.y="LocationID") # head(tips.by.pickup.location[order(-tips.by.pickup.location$tips_per_hour), ]) ######## find best pickup time ######## #by income (time only) income.by.pickup.time <- data.frame(trip.data[which(trip.data$trip_time >= min.trip.time), c("pickup_hour", "income_per_hour", "trip_time")] %>% group_by(pickup_hour) %>% summarise(income_per_hour = weighted.mean(income_per_hour, trip_time))) income.by.pickup.time[order(-income.by.pickup.time$income_per_hour), ] #by income (day of week only) income.by.pickup.day <- data.frame(trip.data[which(trip.data$trip_time >= min.trip.time), c("day_of_week", "income_per_hour", "trip_time")] %>% group_by(day_of_week) %>% summarise(income_per_hour = weighted.mean(income_per_hour, trip_time))) income.by.pickup.day[order(-income.by.pickup.day$income_per_hour), ] #by income (time and day) income.by.pickup.day.and.time <- data.frame(trip.data[which(trip.data$trip_time >= min.trip.time), c("pickup_hour", "day_of_week", "income_per_hour", "trip_time")] %>% group_by(pickup_hour, day_of_week) %>% summarise(income_per_hour = weighted.mean(income_per_hour, trip_time))) income.by.pickup.day.and.time[order(-income.by.pickup.day.and.time$income_per_hour), ] ######## make some pretty pictures ######## #simple barplot of average income/hr by hour of the day barplot(income.by.pickup.time$income_per_hour, names.arg = income.by.pickup.time$pickup_hour, xlab = "Hour of the Day", ylab = "Avg Income/Hr with Passenger in Cab", ylim = c(0, 80), col = "darkgreen") ### shade map of NYC taxi zones with average income/hr # NOTE - this will install any packages in the following list that are not installed needed_packages <- c("rgdal", "leaflet", "RColorBrewer") for(package in needed_packages) { if(!require(package, character.only = TRUE)) { install.packages(package) library(package, character.only = TRUE) } } #load zone map of NYC - source for map: https://data.cityofnewyork.us/Transportation/NYC-Taxi-Zones/d3c5-ddgc new.york.zone.map <- readOGR("NYC Taxi Zones.kml") #create color palette, bin cutoffs were chosen manually after inspecting the data palette <- colorBin(brewer.pal(11, "RdYlGn"), bins=c(20, 40, 50, 55, 60, 65, 70, 80, 90, 100, 300, 500)) #prepare to fill out all zones, even ones without sufficient data incomes.by.location.completed <- merge(income.by.pickup.location, zone.lookup[,c("LocationID", "Borough")], by.x="PULocationID", by.y="LocationID", all.y=T)[1:263,] incomes.by.location.completed$income_per_hour[is.na(incomes.by.location.completed$income_per_hour)] <- 0 #shade the map and display it shaded.map <- leaflet() %>% addPolygons(data = new.york.zone.map, fillColor = ~palette(incomes.by.location.completed$income_per_hour), fillOpacity = 1, weight = 1) %>% addLegend(position = "bottomright", colors = brewer.pal(11, "RdYlGn"), labels = c("$20/hr - $40/hr", "$40/hr - $50/hr", "$50/hr - $55/hr", "$55/hr - $60/hr", "$60/hr - $65/hr", "$65/hr - $70/hr", "$70/hr - $80/hr", "$80/hr - $90/hr", "$90/hr - $100/hr", "$100/hr - $300/hr", "$300/hr - $500/hr"), bins = 11, opacity = 0.7) print(shaded.map)
0071ee1838da18ff1f201b4683625a178d908103
ddcc526b8544b5be7bb9d6f744f318f2b871fbc7
/man/netherlands.Rd
b00ea197e40eca743c3ffe0193a8403200d6aa23
[]
no_license
cran/mapmisc
9d21d865151541f607ae0818ce3cbe3ac7876390
3dab0a3c80ca64fc0709eeb1b5aaff632cb72e40
refs/heads/master
2021-05-16T02:36:00.435354
2021-03-10T22:50:02
2021-03-10T22:50:02
17,697,269
0
0
null
null
null
null
UTF-8
R
false
false
2,275
rd
netherlands.Rd
\name{netherlands} \alias{netherlands} \alias{nldElev} \alias{nldTiles} \alias{nldCities} \alias{world} \docType{data} \title{ Data from the Netherlands } \description{ Elevation data and map tiles for the Netherlands } \usage{data("netherlands")} \format{ \code{nldElev} is a raster of elevation \code{nltTiles} is a background map \code{nldCities} is a SpatialPointsDataFrame of city locations. } \details{ The inclusion of these datasets is intended to allow the package to build when an internet connection is not present. } \source{ See examples. } \seealso{\link[sp]{meuse}, \link[raster]{getData}, \link{openmap}} \examples{ # soil data library("sp") data("meuse") coordinates(meuse) <- ~x+y # proj4string(meuse) <- CRS("+init=epsg:28992") proj4string(meuse) <- CRS( paste("+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889", "+k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m", "+no_defs +datum=WGS84") ) meuse$soilFac = factor(meuse$soil, levels=c(1,2,3), labels=c("Calcareous","Non-Calc's","Red Brick")) soilCol = colourScale(meuse$soilFac) data("netherlands") map.new(meuse) plot(nldTiles,add=TRUE) points(nldCities) text(nldCities,label=nldCities$name, pos=2) points(meuse, pch=16, col=soilCol$plot) legend('topleft', fill=soilCol$col,legend=soilCol$legend) if(requireNamespace('rgdal', quietly=TRUE)) insetMap(meuse, "bottomright",map=world) # location won't be marked on the inset map unless rgdal is available \dontrun{ # this is how the data were obtained # map tiles nldTiles = openmap(meuse, zoom=12) # cities nldCities = GNcities(nldTiles, maxRows=25) # world world = openmap(extent(-10,30,40,60)) # elevation data require('rgdal') meuseLL = spTransform(meuse, mapmisc::crsLL) getData("SRTM", lon=xmin(extent(meuseLL)), lat=ymin(extent(meuseLL)),path=tempdir()) nldElev = raster(paste(tempdir(), "/", "srtm_38_02.tif", sep="")) nldElev = crop(nldElev, extend(extent(meuseLL), 0.1)) nldElev = projectRaster(nldElev, crs=proj4string(meuse)) nldElev = crop(nldElev, extent(nldTiles)) # save the files where the package builder wants them # save(nldElev, nldTiles, nldCities,world, # file="~/research/diseasemapping/pkg/mapmisc/data/netherlands.RData", # compress="xz") } } \keyword{datasets}