content large_stringlengths 0 6.46M | path large_stringlengths 3 331 | license_type large_stringclasses 2 values | repo_name large_stringlengths 5 125 | language large_stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.46M | extension large_stringclasses 75 values | text stringlengths 0 6.46M |
|---|---|---|---|---|---|---|---|---|---|
# run this only once
if(exists("configs") == F){
library(deepnet)
#Creating list to store the differents outputs and information
configs = data.frame(hidden_rbm=integer(), numempochs_rbm=integer(), batchsize_rbm=integer(), lr_rbm=numeric(), cd=integer(), hidden_nn=character(), lr_nn=numeric(), numepochs_nn=integer(), batchsize_nn=numeric(), onehot=integer(), err_score=numeric(), err_score_norm=numeric())
predict_list <- list()
predict_norm_list <- list()
nn_list <- list()
}
#in order to work with the labels coded as onehot vector or not, leave it 1
onehot <- 1
#Hyperparameters for the rbm
hidden_rbm <- 100
numepochs_rbm <- 10
batchsize_rbm <- 100
learningrate_rbm <- 0.1
learningrate_scale_rbm <- 1
cd <- 3
#Hyperparameters for the neural net
hidden_nn <- c(100)
learningrate_nn <- 0.1
learningrate_scale_nn <- 1
numepochs_nn <- 10
batchsize_nn <- 100
#Loading the files
X_train <- read.csv(file="../csv/X_train_AAL.csv", header=T, sep=",", row.names=1)
X_test <- read.csv(file="../csv/X_test_AAL.csv", header=T, sep=",", row.names=1)
y_train_org <- read.csv(file="../csv/y_train_AAL.csv", header=T, sep=",", row.names=1)
y_test_org <- read.csv(file="../csv/y_test_AAL.csv", header=T, sep=",", row.names=1)
#Removing the first row because it has no return
X_train <- X_train[2:nrow(X_train),]
X_test <- X_test[2:nrow(X_test),]
#Onehot vector encoding
onehot_test <- matrix(0L, nrow=dim(y_test_org)[1], ncol=max(y_test_org)+1)
counter <- 1
for(y in 1:dim(y_test_org)[1]){
onehot_test[counter,y_test_org[y,]+1] <- 1
counter <- counter+1
}
onehot_train <- matrix(0L, nrow=dim(y_train_org)[1], ncol=max(y_train_org)+1)
counter <- 1
for(y in 1:dim(y_train_org)[1]){
onehot_train[counter, y_train_org[y,]+1] <- 1
counter <- counter+1
}
#Coverting dataframes to matrices
X_train <- as.matrix(X_train)
X_test <- as.matrix(X_test)
y_train <- as.matrix(y_train_org)
y_test <- as.matrix(y_test_org)
#Asigning onehot vecto labels to the variables used in the model
if(onehot){
y_test <- onehot_test
y_train <- onehot_train
}
#Training the rbm
rbm <- rbm.train(x=X_train, hidden=hidden_rbm, numepochs = numepochs_rbm, batchsize = batchsize_rbm, learningrate = learningrate_rbm, learningrate_scale = learningrate_scale_rbm, momentum = 0.5, visible_type = "bin", hidden_type = "bin", cd = cd)
#Transforming input values
transformed_train <- rbm.up(rbm, X_train)
transformed_test <- rbm.up(rbm, X_test)
#Training the neural net
nn = nn.train(x=transformed_train, y_train, initW = NULL, initB = NULL, hidden = hidden_nn, activationfun = "sigm", learningrate = learningrate_nn, momentum = 0.5, learningrate_scale = learningrate_scale_nn, output = "sigm", numepochs = numepochs_nn, batchsize = batchsize_nn, hidden_dropout = 0, visible_dropout = 0)
#Calculating the score normalized
score <- 0
score <- nn.test(nn, transformed_test, y_test, t = 0.5)
pred <- nn.predict(nn, transformed_test)
pred_norm <- matrix(0L, nrow=dim(pred)[1], ncol=dim(pred)[2])
for(i in 1:dim(pred)[1]){
max_row <- which.max(pred[i,])
pred_norm[i,max_row] <- 1
}
score_norm <- 0
for(i in 1:dim(pred_norm)[1]){
if(which.max(pred_norm[i,]) == which.max(y_test[i,])){
score_norm <- score_norm +1
}
}
score_norm <- 1- score_norm/dim(pred)[1]
#Saving data into lists
configs <- rbind(configs,data.frame(hidden_rbm=hidden_rbm, numempochs_rbm = numepochs_rbm, batchsize_rbm=batchsize_rbm, lr_rbm=learningrate_rbm, cd=cd, hidden_nn=paste(hidden_nn,collapse=" "), lr_nn=learningrate_nn, numepochs_nn=numepochs_nn, batchsize_nn=batchsize_nn, onehot=onehot, err_score=score, err_score_norm = score_norm))
predict_list[[dim(configs)[1]]] <- pred
predict_norm_list[[dim(configs)[1]]] <- pred_norm
nn_list[[dim(configs)[1]]] <- nn
# Histogram of y_train
sort(table(y_train_org),decreasing=TRUE)
#Printing information
configs | /R/rbm - deepnet.R | no_license | NotAnyMike/ML-and-stocks | R | false | false | 3,811 | r | # run this only once
if(exists("configs") == F){
library(deepnet)
#Creating list to store the differents outputs and information
configs = data.frame(hidden_rbm=integer(), numempochs_rbm=integer(), batchsize_rbm=integer(), lr_rbm=numeric(), cd=integer(), hidden_nn=character(), lr_nn=numeric(), numepochs_nn=integer(), batchsize_nn=numeric(), onehot=integer(), err_score=numeric(), err_score_norm=numeric())
predict_list <- list()
predict_norm_list <- list()
nn_list <- list()
}
#in order to work with the labels coded as onehot vector or not, leave it 1
onehot <- 1
#Hyperparameters for the rbm
hidden_rbm <- 100
numepochs_rbm <- 10
batchsize_rbm <- 100
learningrate_rbm <- 0.1
learningrate_scale_rbm <- 1
cd <- 3
#Hyperparameters for the neural net
hidden_nn <- c(100)
learningrate_nn <- 0.1
learningrate_scale_nn <- 1
numepochs_nn <- 10
batchsize_nn <- 100
#Loading the files
X_train <- read.csv(file="../csv/X_train_AAL.csv", header=T, sep=",", row.names=1)
X_test <- read.csv(file="../csv/X_test_AAL.csv", header=T, sep=",", row.names=1)
y_train_org <- read.csv(file="../csv/y_train_AAL.csv", header=T, sep=",", row.names=1)
y_test_org <- read.csv(file="../csv/y_test_AAL.csv", header=T, sep=",", row.names=1)
#Removing the first row because it has no return
X_train <- X_train[2:nrow(X_train),]
X_test <- X_test[2:nrow(X_test),]
#Onehot vector encoding
onehot_test <- matrix(0L, nrow=dim(y_test_org)[1], ncol=max(y_test_org)+1)
counter <- 1
for(y in 1:dim(y_test_org)[1]){
onehot_test[counter,y_test_org[y,]+1] <- 1
counter <- counter+1
}
onehot_train <- matrix(0L, nrow=dim(y_train_org)[1], ncol=max(y_train_org)+1)
counter <- 1
for(y in 1:dim(y_train_org)[1]){
onehot_train[counter, y_train_org[y,]+1] <- 1
counter <- counter+1
}
#Coverting dataframes to matrices
X_train <- as.matrix(X_train)
X_test <- as.matrix(X_test)
y_train <- as.matrix(y_train_org)
y_test <- as.matrix(y_test_org)
#Asigning onehot vecto labels to the variables used in the model
if(onehot){
y_test <- onehot_test
y_train <- onehot_train
}
#Training the rbm
rbm <- rbm.train(x=X_train, hidden=hidden_rbm, numepochs = numepochs_rbm, batchsize = batchsize_rbm, learningrate = learningrate_rbm, learningrate_scale = learningrate_scale_rbm, momentum = 0.5, visible_type = "bin", hidden_type = "bin", cd = cd)
#Transforming input values
transformed_train <- rbm.up(rbm, X_train)
transformed_test <- rbm.up(rbm, X_test)
#Training the neural net
nn = nn.train(x=transformed_train, y_train, initW = NULL, initB = NULL, hidden = hidden_nn, activationfun = "sigm", learningrate = learningrate_nn, momentum = 0.5, learningrate_scale = learningrate_scale_nn, output = "sigm", numepochs = numepochs_nn, batchsize = batchsize_nn, hidden_dropout = 0, visible_dropout = 0)
#Calculating the score normalized
score <- 0
score <- nn.test(nn, transformed_test, y_test, t = 0.5)
pred <- nn.predict(nn, transformed_test)
pred_norm <- matrix(0L, nrow=dim(pred)[1], ncol=dim(pred)[2])
for(i in 1:dim(pred)[1]){
max_row <- which.max(pred[i,])
pred_norm[i,max_row] <- 1
}
score_norm <- 0
for(i in 1:dim(pred_norm)[1]){
if(which.max(pred_norm[i,]) == which.max(y_test[i,])){
score_norm <- score_norm +1
}
}
score_norm <- 1- score_norm/dim(pred)[1]
#Saving data into lists
configs <- rbind(configs,data.frame(hidden_rbm=hidden_rbm, numempochs_rbm = numepochs_rbm, batchsize_rbm=batchsize_rbm, lr_rbm=learningrate_rbm, cd=cd, hidden_nn=paste(hidden_nn,collapse=" "), lr_nn=learningrate_nn, numepochs_nn=numepochs_nn, batchsize_nn=batchsize_nn, onehot=onehot, err_score=score, err_score_norm = score_norm))
predict_list[[dim(configs)[1]]] <- pred
predict_norm_list[[dim(configs)[1]]] <- pred_norm
nn_list[[dim(configs)[1]]] <- nn
# Histogram of y_train
sort(table(y_train_org),decreasing=TRUE)
#Printing information
configs |
require(readr)
require(arules)
require(dplyr)
discretize_all = function(table_d, type, n){
for (i in 1:ncol(table_d)) {
if (is.numeric(table_d[[i]])) {
table_d[[i]] = discretize(table_d[[i]], method = type, categories = n,
ordered=TRUE)
}
}
print(summary(table_d))
return(table_d);
}
# IMPORTANT: this header should be similiar in pretty much all scripts
args <- commandArgs(trailingOnly = TRUE)
dataset_path <- args[1]
min_support <- as.numeric(args[2])
csv_file_name = "crabs.csv"
csv_file_path = paste('../../resources/datasets/', csv_file_name, sep="")
# discritize columns and adapt dataset for the algorithm
# this part is specific to every script
data <- read_csv(csv_file_path)
data$index = NULL
data <- discretize_all(data, "interval", 6)
data <- mutate_if(data, is.character, as.factor)
# this part should be similiar in all scripts
rules <- apriori(data, parameter=list(supp=min_support, conf=0.8, target="rules"))
num_rules <- length(rules)
write(num_rules, stdout())
| /scripts/arngg/pygfrs/rscripts/crabs_6_discr.R | no_license | iluxonchik/dss-project-first-delivery | R | false | false | 992 | r | require(readr)
require(arules)
require(dplyr)
discretize_all = function(table_d, type, n){
for (i in 1:ncol(table_d)) {
if (is.numeric(table_d[[i]])) {
table_d[[i]] = discretize(table_d[[i]], method = type, categories = n,
ordered=TRUE)
}
}
print(summary(table_d))
return(table_d);
}
# IMPORTANT: this header should be similiar in pretty much all scripts
args <- commandArgs(trailingOnly = TRUE)
dataset_path <- args[1]
min_support <- as.numeric(args[2])
csv_file_name = "crabs.csv"
csv_file_path = paste('../../resources/datasets/', csv_file_name, sep="")
# discritize columns and adapt dataset for the algorithm
# this part is specific to every script
data <- read_csv(csv_file_path)
data$index = NULL
data <- discretize_all(data, "interval", 6)
data <- mutate_if(data, is.character, as.factor)
# this part should be similiar in all scripts
rules <- apriori(data, parameter=list(supp=min_support, conf=0.8, target="rules"))
num_rules <- length(rules)
write(num_rules, stdout())
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 11578
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 11146
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 11146
c
c Input Parameter (command line, file):
c input filename QBFLIB/Seidl/ASP_Program_Inclusion/T-adeu-49.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 4790
c no.of clauses 11578
c no.of taut cls 208
c
c Output Parameters:
c remaining no.of clauses 11146
c
c QBFLIB/Seidl/ASP_Program_Inclusion/T-adeu-49.qdimacs 4790 11578 E1 [81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 121 122 123 124 125 126 127 128 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 297 298 299 300 301 302 303 304 448 449 466 467 484 485 502 503 520 521 538 539 556 557 574 575 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 1238 1239 1240 1241 1242 1243 1244 1245 1319 1321 1334 1342 1345 1351 1363 1368 1370 1388 1390 1395 1406 1421 1429 1432 1439 1449 1459 1462 1478 1479 1493 1504 1509 1517 1521 1539 1540 1542 1544 1554 1560 1582 1584 1585 1590 1595 1601 1602 1656 1657 1682 1683 1708 1709 1734 1735 1923 1924 1941 1942 1959 1960 1977 1978 1995 1996 2013 2014 2031 2032 2049 2050 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2392 2394 2407 2415 2418 2424 2436 2441 2443 2461 2463 2468 2479 2494 2502 2505 2512 2522 2532 2535 2551 2552 2566 2577 2582 2590 2594 2612 2613 2615 2617 2627 2633 2655 2657 2658 2663 2668 2674 2675 2679 2680 2705 2706 2731 2732 2757 2758 2783 2784 2809 2810 2835 2836 2861 2862 2887 2888 2913 2914 2939 2940 2965 2966 2987 2988 2989 2990 2991 2992 2993 2994 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3551 3553 3566 3574 3577 3583 3595 3600 3602 3620 3622 3627 3638 3653 3661 3664 3671 3681 3691 3694 3710 3711 3725 3736 3741 3749 3753 3771 3772 3774 3776 3786 3792 3814 3816 3817 3822 3827 3833 3834 3838 3839 3864 3865 3890 3891 3916 3917 3942 3943 3968 3969 3994 3995 4020 4021 4046 4047 4072 4073 4098 4099 4124 4125 4171 4172 4173 4174 4175 4176 4177 4178] 208 160 4278 11146 RED
| /code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Seidl/ASP_Program_Inclusion/T-adeu-49/T-adeu-49.R | no_license | arey0pushpa/dcnf-autarky | R | false | false | 2,372 | r | c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 11578
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 11146
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 11146
c
c Input Parameter (command line, file):
c input filename QBFLIB/Seidl/ASP_Program_Inclusion/T-adeu-49.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 4790
c no.of clauses 11578
c no.of taut cls 208
c
c Output Parameters:
c remaining no.of clauses 11146
c
c QBFLIB/Seidl/ASP_Program_Inclusion/T-adeu-49.qdimacs 4790 11578 E1 [81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 121 122 123 124 125 126 127 128 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 297 298 299 300 301 302 303 304 448 449 466 467 484 485 502 503 520 521 538 539 556 557 574 575 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 1238 1239 1240 1241 1242 1243 1244 1245 1319 1321 1334 1342 1345 1351 1363 1368 1370 1388 1390 1395 1406 1421 1429 1432 1439 1449 1459 1462 1478 1479 1493 1504 1509 1517 1521 1539 1540 1542 1544 1554 1560 1582 1584 1585 1590 1595 1601 1602 1656 1657 1682 1683 1708 1709 1734 1735 1923 1924 1941 1942 1959 1960 1977 1978 1995 1996 2013 2014 2031 2032 2049 2050 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2392 2394 2407 2415 2418 2424 2436 2441 2443 2461 2463 2468 2479 2494 2502 2505 2512 2522 2532 2535 2551 2552 2566 2577 2582 2590 2594 2612 2613 2615 2617 2627 2633 2655 2657 2658 2663 2668 2674 2675 2679 2680 2705 2706 2731 2732 2757 2758 2783 2784 2809 2810 2835 2836 2861 2862 2887 2888 2913 2914 2939 2940 2965 2966 2987 2988 2989 2990 2991 2992 2993 2994 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3551 3553 3566 3574 3577 3583 3595 3600 3602 3620 3622 3627 3638 3653 3661 3664 3671 3681 3691 3694 3710 3711 3725 3736 3741 3749 3753 3771 3772 3774 3776 3786 3792 3814 3816 3817 3822 3827 3833 3834 3838 3839 3864 3865 3890 3891 3916 3917 3942 3943 3968 3969 3994 3995 4020 4021 4046 4047 4072 4073 4098 4099 4124 4125 4171 4172 4173 4174 4175 4176 4177 4178] 208 160 4278 11146 RED
|
# S3 method to deal with chunks and inline text respectively
process_group = function(x) {
UseMethod('process_group', x)
}
#' @export
process_group.block = function(x) call_block(x)
#' @export
process_group.inline = function(x) {
x = call_inline(x)
knit_hooks$get('text')(x)
}
call_block = function(block) {
# now try eval all options except those in eval.after and their aliases
af = opts_knit$get('eval.after'); al = opts_knit$get('aliases')
if (!is.null(al) && !is.null(af)) af = c(af, names(al[af %in% al]))
# expand parameters defined via template
if (!is.null(block$params$opts.label)) {
block$params = merge_list(opts_template$get(block$params$opts.label), block$params)
}
params = opts_chunk$merge(block$params)
opts_current$restore(params)
for (o in setdiff(names(params), af)) params[o] = list(eval_lang(params[[o]]))
params = fix_options(params) # for compatibility
label = ref.label = params$label
if (!is.null(params$ref.label)) ref.label = sc_split(params$ref.label)
params[["code"]] = params[["code"]] %n% unlist(knit_code$get(ref.label), use.names = FALSE)
if (opts_knit$get('progress')) print(block)
if (!is.null(params$child)) {
if (!is_blank(params$code)) warning(
"The chunk '", params$label, "' has the 'child' option, ",
"and this code chunk must be empty. Its code will be ignored."
)
if (!params$eval) return('')
cmds = lapply(sc_split(params$child), knit_child, options = block$params)
out = paste(unlist(cmds), collapse = '\n')
return(out)
}
params$code = parse_chunk(params$code) # parse sub-chunk references
ohooks = opts_hooks$get()
for (opt in names(ohooks)) {
hook = ohooks[[opt]]
if (!is.function(hook)) {
warning("The option hook '", opt, "' should be a function")
next
}
if (!is.null(params[[opt]])) params = as.strict_list(hook(params))
if (!is.list(params))
stop("The option hook '", opt, "' should return a list of chunk options")
}
# Check cache
if (params$cache > 0) {
content = c(
params[if (params$cache < 3) cache1.opts else setdiff(names(params), cache0.opts)],
getOption('width'), if (params$cache == 2) params[cache2.opts]
)
if (params$engine == 'R' && isFALSE(params$cache.comments)) {
content[['code']] = parse_only(content[['code']])
}
hash = paste(valid_path(params$cache.path, label), digest::digest(content), sep = '_')
params$hash = hash
if (cache$exists(hash, params$cache.lazy) &&
isFALSE(params$cache.rebuild) &&
params$engine != 'Rcpp') {
if (opts_knit$get('verbose')) message(' loading cache from ', hash)
cache$load(hash, lazy = params$cache.lazy)
if (!params$include) return('')
if (params$cache == 3) return(cache$output(hash))
}
if (params$engine == 'R')
cache$library(params$cache.path, save = FALSE) # load packages
} else if (label %in% names(dep_list$get()) && !isFALSE(opts_knit$get('warn.uncached.dep')))
warning2('code chunks must not depend on the uncached chunk "', label, '"')
params$params.src = block$params.src
opts_current$restore(params) # save current options
# set local options() for the current R chunk
if (is.list(params$R.options)) {
op = options(params$R.options); on.exit(options(op), add = TRUE)
}
block_exec(params)
}
# options that should affect cache when cache level = 1,2
cache1.opts = c('code', 'eval', 'cache', 'cache.path', 'message', 'warning', 'error')
# more options affecting cache level 2
cache2.opts = c('fig.keep', 'fig.path', 'fig.ext', 'dev', 'dpi', 'dev.args', 'fig.width', 'fig.height')
# options that should not affect cache
cache0.opts = c('include', 'out.width.px', 'out.height.px', 'cache.rebuild')
block_exec = function(options) {
# when code is not R language
if (options$engine != 'R') {
res.before = run_hooks(before = TRUE, options)
engine = get_engine(options$engine)
output = in_dir(input_dir(), engine(options))
res.after = run_hooks(before = FALSE, options)
output = paste(c(res.before, output, res.after), collapse = '')
output = knit_hooks$get('chunk')(output, options)
if (options$cache) block_cache(
options, output,
if (options$engine == 'stan') options$engine.opts$x else character(0)
)
return(if (options$include) output else '')
}
# eval chunks (in an empty envir if cache)
env = knit_global()
obj.before = ls(globalenv(), all.names = TRUE) # global objects before chunk
keep = options$fig.keep
keep.idx = NULL
if (is.numeric(keep)) {
keep.idx = keep
keep = "index"
}
tmp.fig = tempfile(); on.exit(unlink(tmp.fig), add = TRUE)
# open a device to record plots
if (chunk_device(options$fig.width[1L], options$fig.height[1L], keep != 'none',
options$dev, options$dev.args, options$dpi, options, tmp.fig)) {
# preserve par() settings from the last code chunk
if (keep.pars <- opts_knit$get('global.par'))
par2(opts_knit$get('global.pars'))
showtext(options$fig.showtext) # showtext support
dv = dev.cur()
on.exit({
if (keep.pars) opts_knit$set(global.pars = par(no.readonly = TRUE))
dev.off(dv)
}, add = TRUE)
}
res.before = run_hooks(before = TRUE, options, env) # run 'before' hooks
code = options$code
echo = options$echo # tidy code if echo
if (!isFALSE(echo) && options$tidy && length(code)) {
res = try_silent(do.call(
formatR::tidy_source, c(list(text = code, output = FALSE), options$tidy.opts)
))
if (!inherits(res, 'try-error')) {
code = res$text.tidy
} else warning('failed to tidy R code in chunk <', options$label, '>\n',
'reason: ', res)
}
# only evaluate certain lines
if (is.numeric(ev <- options$eval)) {
# group source code into syntactically complete expressions
if (!options$tidy) code = sapply(highr:::group_src(code), paste, collapse = '\n')
iss = seq_along(code)
code = comment_out(code, '##', setdiff(iss, iss[ev]), newline = FALSE)
}
# guess plot file type if it is NULL
if (keep != 'none' && is.null(options$fig.ext))
options$fig.ext = dev2ext(options$dev)
cache.exists = cache$exists(options$hash, options$cache.lazy)
evaluate = knit_hooks$get('evaluate')
# return code with class 'source' if not eval chunks
res = if (is_blank(code)) list() else if (isFALSE(ev)) {
as.source(code)
} else if (cache.exists && isFALSE(options$cache.rebuild)) {
fix_evaluate(cache$output(options$hash, 'list'), options$cache == 1)
} else in_dir(
input_dir(),
evaluate(
code, envir = env, new_device = FALSE,
keep_warning = !isFALSE(options$warning),
keep_message = !isFALSE(options$message),
stop_on_error = if (options$error && options$include) 0L else 2L,
output_handler = knit_handlers(options$render, options)
)
)
if (options$cache %in% 1:2 && (!cache.exists || isTRUE(options$cache.rebuild))) {
# make a copy for cache=1,2; when cache=2, we do not really need plots
res.orig = if (options$cache == 2) remove_plot(res, keep == 'high') else res
}
# eval other options after the chunk
if (!isFALSE(ev))
for (o in opts_knit$get('eval.after'))
options[o] = list(eval_lang(options[[o]], env))
# remove some components according options
if (isFALSE(echo)) {
res = Filter(Negate(evaluate::is.source), res)
} else if (is.numeric(echo)) {
# choose expressions to echo using a numeric vector
res = if (isFALSE(ev)) {
as.source(code[echo])
} else {
filter_evaluate(res, echo, evaluate::is.source)
}
}
if (options$results == 'hide') res = Filter(Negate(is.character), res)
if (options$results == 'hold') {
i = vapply(res, is.character, logical(1))
if (any(i)) res = c(res[!i], merge_character(res[i]))
}
res = filter_evaluate(res, options$warning, evaluate::is.warning)
res = filter_evaluate(res, options$message, evaluate::is.message)
# rearrange locations of figures
figs = find_recordedplot(res)
if (length(figs) && any(figs)) {
if (keep == 'none') {
res = res[!figs] # remove all
} else {
if (options$fig.show == 'hold') res = c(res[!figs], res[figs]) # move to the end
figs = find_recordedplot(res)
if (length(figs) && sum(figs) > 1) {
if (keep %in% c('first', 'last')) {
res = res[-(if (keep == 'last') head else tail)(which(figs), -1L)]
} else {
# keep only selected
if (keep == 'index') res = res[which(figs)[keep.idx]]
# merge low-level plotting changes
if (keep == 'high') res = merge_low_plot(res, figs)
}
}
}
}
# number of plots in this chunk
if (is.null(options$fig.num))
options$fig.num = if (length(res)) sum(sapply(res, evaluate::is.recordedplot)) else 0L
# merge neighbor elements of the same class into one element
for (cls in c('source', 'message', 'warning')) res = merge_class(res, cls)
if (isTRUE(options$fig.beforecode)) res = fig_before_code(res)
on.exit({
plot_counter(reset = TRUE)
shot_counter(reset = TRUE)
}, add = TRUE) # restore plot number
output = unlist(wrap(res, options)) # wrap all results together
res.after = run_hooks(before = FALSE, options, env) # run 'after' hooks
output = paste(c(res.before, output, res.after), collapse = '') # insert hook results
output = knit_hooks$get('chunk')(output, options)
if (options$cache > 0) {
# if cache.vars has been specifically provided, only cache these vars and no
# need to look for objects in globalenv()
obj.new = if (is.null(options$cache.vars)) setdiff(ls(globalenv(), all.names = TRUE), obj.before)
copy_env(globalenv(), env, obj.new)
objs = if (isFALSE(ev) || length(code) == 0) character(0) else
options$cache.vars %n% codetools::findLocalsList(parse_only(code))
# make sure all objects to be saved exist in env
objs = intersect(c(objs, obj.new), ls(env, all.names = TRUE))
if (options$autodep) {
# you shall manually specify global object names if find_symbols() is not reliable
cache$objects(
objs, options$cache.globals %n% find_symbols(code), options$label,
options$cache.path
)
dep_auto()
}
if (options$cache < 3) {
if (options$cache.rebuild || !cache.exists) block_cache(options, res.orig, objs)
} else block_cache(options, output, objs)
}
if (options$include) output else if (is.null(s <- options$indent)) '' else s
}
block_cache = function(options, output, objects) {
hash = options$hash
outname = cache_output_name(hash)
assign(outname, output, envir = knit_global())
purge_cache(options)
cache$library(options$cache.path, save = TRUE)
cache$save(objects, outname, hash, lazy = options$cache.lazy)
}
purge_cache = function(options) {
# purge my old cache and cache of chunks dependent on me
cache$purge(paste0(valid_path(
options$cache.path, c(options$label, dep_list$get(options$label))
), '_????????????????????????????????'))
}
# open a device for a chunk; depending on the option global.device, may or may
# not need to close the device on exit
chunk_device = function(
width, height, record = TRUE, dev, dev.args, dpi, options, tmp = tempfile()
) {
dev_new = function() {
# actually I should adjust the recording device according to dev, but here I
# have only considered the png and tikz devices (because the measurement
# results can be very different especially with the latter, see #1066), and
# also the cairo_pdf device (#1235)
if (identical(dev, 'png')) {
do.call(grDevices::png, c(list(
filename = tmp, width = width, height = height, units = 'in', res = dpi
), get_dargs(dev.args, 'png')))
} else if (identical(dev, 'tikz')) {
dargs = c(list(
file = tmp, width = width, height = height
), get_dargs(dev.args, 'tikz'))
dargs$sanitize = options$sanitize; dargs$standAlone = options$external
if (is.null(dargs$verbose)) dargs$verbose = FALSE
do.call(tikz_dev, dargs)
} else if (identical(dev, 'cairo_pdf')) {
do.call(grDevices::cairo_pdf, c(list(
filename = tmp, width = width, height = height
), get_dargs(dev.args, 'cairo_pdf')))
} else if (identical(getOption('device'), pdf_null)) {
if (!is.null(dev.args)) {
dev.args = get_dargs(dev.args, 'pdf')
dev.args = dev.args[intersect(names(dev.args), c('pointsize', 'bg'))]
}
do.call(pdf_null, c(list(width = width, height = height), dev.args))
} else dev.new(width = width, height = height)
}
if (!opts_knit$get('global.device')) {
dev_new()
dev.control(displaylist = if (record) 'enable' else 'inhibit') # enable recording
# if returns TRUE, we need to close this device after code is evaluated
return(TRUE)
} else if (is.null(dev.list())) {
# want to use a global device but not open yet
dev_new()
dev.control('enable')
}
FALSE
}
# filter out some results based on the numeric chunk option as indices
filter_evaluate = function(res, opt, test) {
if (length(res) == 0 || !is.numeric(opt) || !any(idx <- sapply(res, test)))
return(res)
idx = which(idx)
idx = setdiff(idx, na.omit(idx[opt])) # indices of elements to remove
if (length(idx) == 0) res else res[-idx]
}
# find recorded plots in the output of evaluate()
find_recordedplot = function(x) {
vapply(x, is_plot_output, logical(1))
}
is_plot_output = function(x) {
evaluate::is.recordedplot(x) || inherits(x, 'knit_image_paths')
}
# move plots before source code
fig_before_code = function(x) {
s = vapply(x, evaluate::is.source, logical(1))
if (length(s) == 0 || !any(s)) return(x)
s = which(s)
f = which(find_recordedplot(x))
f = f[f >= min(s)] # only move those plots after the first code block
for (i in f) {
j = max(s[s < i])
tmp = x[i]; x[[i]] = NULL; x = append(x, tmp, j - 1)
s = which(vapply(x, evaluate::is.source, logical(1)))
}
x
}
# merge neighbor elements of the same class in a list returned by evaluate()
merge_class = function(res, class = c('source', 'message', 'warning')) {
class = match.arg(class)
idx = if (length(res)) which(sapply(res, inherits, what = class))
if ((n <- length(idx)) <= 1) return(res)
k1 = idx[1]; k2 = NULL; res1 = res[[k1]]
el = c(source = 'src', message = 'message', warning = 'message')[class]
for (i in 1:(n - 1)) {
idx2 = idx[i + 1]; idx1 = idx[i]
if (idx2 - idx1 == 1) {
res2 = res[[idx2]]
# merge warnings/messages only if next one is identical to previous one
if (class == 'source' || identical(res1, res2) ||
(class == 'message' && !grepl('\n$', tail(res1[[el]], 1)))) {
res[[k1]][[el]] = c(res[[k1]][[el]], res2[[el]])
k2 = c(k2, idx2)
} else {
k1 = idx2
res1 = res[[k1]]
}
} else k1 = idx2
}
if (length(k2)) res = res[-k2] # remove lines that have been merged back
res
}
# merge character output for output='hold', if the subsequent character is of
# the same class(es) as the previous one (e.g. should not merge normal
# characters with asis_output())
merge_character = function(res) {
if ((n <- length(res)) <= 1) return(res)
k = NULL
for (i in 1:(n - 1)) {
cls = class(res[[i]])
if (identical(cls, class(res[[i + 1]]))) {
res[[i + 1]] = paste0(res[[i]], res[[i + 1]])
class(res[[i + 1]]) = cls
k = c(k, i)
}
}
if (length(k)) res = res[-k]
res
}
call_inline = function(block) {
if (opts_knit$get('progress')) print(block)
in_dir(input_dir(), inline_exec(block))
}
inline_exec = function(block, envir = knit_global(), hook = knit_hooks$get('inline')) {
# run inline code and substitute original texts
code = block$code; input = block$input
if ((n <- length(code)) == 0) return(input) # untouched if no code is found
loc = block$location
for (i in 1:n) {
options = opts_chunk$get()
if(!is.null(names(code)) && names(code)[i] != "")
options$engine = names(code)[i]
if(options$engine == "R")
{
v = withVisible(eval(parse_only(code[i]), envir = envir))
res = if (v$visible) knit_print(v$value, inline = TRUE, options = options)
if (inherits(res, 'knit_asis')) res = wrap(res, inline = TRUE)
}
else
{
options$code = code[i]
options$echo = FALSE
options$results = 'asis'
options$inline = TRUE
engine = get_engine(options$engine)
res = engine(options)
}
d = nchar(input)
# replace with evaluated results
stringr::str_sub(input, loc[i, 1], loc[i, 2]) = if (length(res)) {
paste(hook(res), collapse = '')
} else ''
if (i < n) loc[(i + 1):n, ] = loc[(i + 1):n, ] - (d - nchar(input))
# may need to move back and forth because replacement may be longer or shorter
}
input
}
process_tangle = function(x) {
UseMethod('process_tangle', x)
}
#' @export
process_tangle.block = function(x) {
params = opts_chunk$merge(x$params)
for (o in c('purl', 'eval', 'child'))
try(params[o] <- list(eval_lang(params[[o]])))
if (isFALSE(params$purl)) return('')
label = params$label; ev = params$eval
if (params$engine != 'R') return(comment_out(knit_code$get(label)))
code = if (!isFALSE(ev) && !is.null(params$child)) {
cmds = lapply(sc_split(params$child), knit_child)
paste(unlist(cmds), collapse = '\n')
} else knit_code$get(label)
# read external code if exists
if (!isFALSE(ev) && length(code) && grepl('read_chunk\\(.+\\)', code)) {
eval(parse_only(unlist(stringr::str_extract_all(code, 'read_chunk\\(([^)]+)\\)'))))
}
code = parse_chunk(code)
if (isFALSE(ev)) code = comment_out(code, params$comment, newline = FALSE)
if (opts_knit$get('documentation') == 0L) return(paste(code, collapse = '\n'))
label_code(code, x$params.src)
}
#' @export
process_tangle.inline = function(x) {
output = if (opts_knit$get('documentation') == 2L) {
output = paste(line_prompt(x$input.src, "#' ", "#' "), collapse = '\n')
} else ''
code = x$code
if (length(code) == 0L) return(output)
if (getOption('knitr.purl.inline', FALSE)) output = c(output, code)
idx = grepl('knit_child\\(.+\\)', code)
if (any(idx)) {
cout = sapply(code[idx], function(z) eval(parse_only(z)))
output = c(output, cout, '')
}
paste(output, collapse = '\n')
}
# add a label [and extra chunk options] to a code chunk
label_code = function(code, label) {
code = paste(c('', code, ''), collapse = '\n')
paste0('## ----', stringr::str_pad(label, max(getOption('width') - 11L, 0L), 'right', '-'),
'----', code)
}
as.source = function(code) {
list(structure(list(src = code), class = 'source'))
}
| /R/block.R | no_license | mwouts/knitr | R | false | false | 18,800 | r | # S3 method to deal with chunks and inline text respectively
process_group = function(x) {
UseMethod('process_group', x)
}
#' @export
process_group.block = function(x) call_block(x)
#' @export
process_group.inline = function(x) {
x = call_inline(x)
knit_hooks$get('text')(x)
}
call_block = function(block) {
# now try eval all options except those in eval.after and their aliases
af = opts_knit$get('eval.after'); al = opts_knit$get('aliases')
if (!is.null(al) && !is.null(af)) af = c(af, names(al[af %in% al]))
# expand parameters defined via template
if (!is.null(block$params$opts.label)) {
block$params = merge_list(opts_template$get(block$params$opts.label), block$params)
}
params = opts_chunk$merge(block$params)
opts_current$restore(params)
for (o in setdiff(names(params), af)) params[o] = list(eval_lang(params[[o]]))
params = fix_options(params) # for compatibility
label = ref.label = params$label
if (!is.null(params$ref.label)) ref.label = sc_split(params$ref.label)
params[["code"]] = params[["code"]] %n% unlist(knit_code$get(ref.label), use.names = FALSE)
if (opts_knit$get('progress')) print(block)
if (!is.null(params$child)) {
if (!is_blank(params$code)) warning(
"The chunk '", params$label, "' has the 'child' option, ",
"and this code chunk must be empty. Its code will be ignored."
)
if (!params$eval) return('')
cmds = lapply(sc_split(params$child), knit_child, options = block$params)
out = paste(unlist(cmds), collapse = '\n')
return(out)
}
params$code = parse_chunk(params$code) # parse sub-chunk references
ohooks = opts_hooks$get()
for (opt in names(ohooks)) {
hook = ohooks[[opt]]
if (!is.function(hook)) {
warning("The option hook '", opt, "' should be a function")
next
}
if (!is.null(params[[opt]])) params = as.strict_list(hook(params))
if (!is.list(params))
stop("The option hook '", opt, "' should return a list of chunk options")
}
# Check cache
if (params$cache > 0) {
content = c(
params[if (params$cache < 3) cache1.opts else setdiff(names(params), cache0.opts)],
getOption('width'), if (params$cache == 2) params[cache2.opts]
)
if (params$engine == 'R' && isFALSE(params$cache.comments)) {
content[['code']] = parse_only(content[['code']])
}
hash = paste(valid_path(params$cache.path, label), digest::digest(content), sep = '_')
params$hash = hash
if (cache$exists(hash, params$cache.lazy) &&
isFALSE(params$cache.rebuild) &&
params$engine != 'Rcpp') {
if (opts_knit$get('verbose')) message(' loading cache from ', hash)
cache$load(hash, lazy = params$cache.lazy)
if (!params$include) return('')
if (params$cache == 3) return(cache$output(hash))
}
if (params$engine == 'R')
cache$library(params$cache.path, save = FALSE) # load packages
} else if (label %in% names(dep_list$get()) && !isFALSE(opts_knit$get('warn.uncached.dep')))
warning2('code chunks must not depend on the uncached chunk "', label, '"')
params$params.src = block$params.src
opts_current$restore(params) # save current options
# set local options() for the current R chunk
if (is.list(params$R.options)) {
op = options(params$R.options); on.exit(options(op), add = TRUE)
}
block_exec(params)
}
# options that should affect cache when cache level = 1,2
cache1.opts = c('code', 'eval', 'cache', 'cache.path', 'message', 'warning', 'error')
# more options affecting cache level 2
cache2.opts = c('fig.keep', 'fig.path', 'fig.ext', 'dev', 'dpi', 'dev.args', 'fig.width', 'fig.height')
# options that should not affect cache
cache0.opts = c('include', 'out.width.px', 'out.height.px', 'cache.rebuild')
block_exec = function(options) {
# when code is not R language
if (options$engine != 'R') {
res.before = run_hooks(before = TRUE, options)
engine = get_engine(options$engine)
output = in_dir(input_dir(), engine(options))
res.after = run_hooks(before = FALSE, options)
output = paste(c(res.before, output, res.after), collapse = '')
output = knit_hooks$get('chunk')(output, options)
if (options$cache) block_cache(
options, output,
if (options$engine == 'stan') options$engine.opts$x else character(0)
)
return(if (options$include) output else '')
}
# eval chunks (in an empty envir if cache)
env = knit_global()
obj.before = ls(globalenv(), all.names = TRUE) # global objects before chunk
keep = options$fig.keep
keep.idx = NULL
if (is.numeric(keep)) {
keep.idx = keep
keep = "index"
}
tmp.fig = tempfile(); on.exit(unlink(tmp.fig), add = TRUE)
# open a device to record plots
if (chunk_device(options$fig.width[1L], options$fig.height[1L], keep != 'none',
options$dev, options$dev.args, options$dpi, options, tmp.fig)) {
# preserve par() settings from the last code chunk
if (keep.pars <- opts_knit$get('global.par'))
par2(opts_knit$get('global.pars'))
showtext(options$fig.showtext) # showtext support
dv = dev.cur()
on.exit({
if (keep.pars) opts_knit$set(global.pars = par(no.readonly = TRUE))
dev.off(dv)
}, add = TRUE)
}
res.before = run_hooks(before = TRUE, options, env) # run 'before' hooks
code = options$code
echo = options$echo # tidy code if echo
if (!isFALSE(echo) && options$tidy && length(code)) {
res = try_silent(do.call(
formatR::tidy_source, c(list(text = code, output = FALSE), options$tidy.opts)
))
if (!inherits(res, 'try-error')) {
code = res$text.tidy
} else warning('failed to tidy R code in chunk <', options$label, '>\n',
'reason: ', res)
}
# only evaluate certain lines
if (is.numeric(ev <- options$eval)) {
# group source code into syntactically complete expressions
if (!options$tidy) code = sapply(highr:::group_src(code), paste, collapse = '\n')
iss = seq_along(code)
code = comment_out(code, '##', setdiff(iss, iss[ev]), newline = FALSE)
}
# guess plot file type if it is NULL
if (keep != 'none' && is.null(options$fig.ext))
options$fig.ext = dev2ext(options$dev)
cache.exists = cache$exists(options$hash, options$cache.lazy)
evaluate = knit_hooks$get('evaluate')
# return code with class 'source' if not eval chunks
res = if (is_blank(code)) list() else if (isFALSE(ev)) {
as.source(code)
} else if (cache.exists && isFALSE(options$cache.rebuild)) {
fix_evaluate(cache$output(options$hash, 'list'), options$cache == 1)
} else in_dir(
input_dir(),
evaluate(
code, envir = env, new_device = FALSE,
keep_warning = !isFALSE(options$warning),
keep_message = !isFALSE(options$message),
stop_on_error = if (options$error && options$include) 0L else 2L,
output_handler = knit_handlers(options$render, options)
)
)
if (options$cache %in% 1:2 && (!cache.exists || isTRUE(options$cache.rebuild))) {
# make a copy for cache=1,2; when cache=2, we do not really need plots
res.orig = if (options$cache == 2) remove_plot(res, keep == 'high') else res
}
# eval other options after the chunk
if (!isFALSE(ev))
for (o in opts_knit$get('eval.after'))
options[o] = list(eval_lang(options[[o]], env))
# remove some components according options
if (isFALSE(echo)) {
res = Filter(Negate(evaluate::is.source), res)
} else if (is.numeric(echo)) {
# choose expressions to echo using a numeric vector
res = if (isFALSE(ev)) {
as.source(code[echo])
} else {
filter_evaluate(res, echo, evaluate::is.source)
}
}
if (options$results == 'hide') res = Filter(Negate(is.character), res)
if (options$results == 'hold') {
i = vapply(res, is.character, logical(1))
if (any(i)) res = c(res[!i], merge_character(res[i]))
}
res = filter_evaluate(res, options$warning, evaluate::is.warning)
res = filter_evaluate(res, options$message, evaluate::is.message)
# rearrange locations of figures
figs = find_recordedplot(res)
if (length(figs) && any(figs)) {
if (keep == 'none') {
res = res[!figs] # remove all
} else {
if (options$fig.show == 'hold') res = c(res[!figs], res[figs]) # move to the end
figs = find_recordedplot(res)
if (length(figs) && sum(figs) > 1) {
if (keep %in% c('first', 'last')) {
res = res[-(if (keep == 'last') head else tail)(which(figs), -1L)]
} else {
# keep only selected
if (keep == 'index') res = res[which(figs)[keep.idx]]
# merge low-level plotting changes
if (keep == 'high') res = merge_low_plot(res, figs)
}
}
}
}
# number of plots in this chunk
if (is.null(options$fig.num))
options$fig.num = if (length(res)) sum(sapply(res, evaluate::is.recordedplot)) else 0L
# merge neighbor elements of the same class into one element
for (cls in c('source', 'message', 'warning')) res = merge_class(res, cls)
if (isTRUE(options$fig.beforecode)) res = fig_before_code(res)
on.exit({
plot_counter(reset = TRUE)
shot_counter(reset = TRUE)
}, add = TRUE) # restore plot number
output = unlist(wrap(res, options)) # wrap all results together
res.after = run_hooks(before = FALSE, options, env) # run 'after' hooks
output = paste(c(res.before, output, res.after), collapse = '') # insert hook results
output = knit_hooks$get('chunk')(output, options)
if (options$cache > 0) {
# if cache.vars has been specifically provided, only cache these vars and no
# need to look for objects in globalenv()
obj.new = if (is.null(options$cache.vars)) setdiff(ls(globalenv(), all.names = TRUE), obj.before)
copy_env(globalenv(), env, obj.new)
objs = if (isFALSE(ev) || length(code) == 0) character(0) else
options$cache.vars %n% codetools::findLocalsList(parse_only(code))
# make sure all objects to be saved exist in env
objs = intersect(c(objs, obj.new), ls(env, all.names = TRUE))
if (options$autodep) {
# you shall manually specify global object names if find_symbols() is not reliable
cache$objects(
objs, options$cache.globals %n% find_symbols(code), options$label,
options$cache.path
)
dep_auto()
}
if (options$cache < 3) {
if (options$cache.rebuild || !cache.exists) block_cache(options, res.orig, objs)
} else block_cache(options, output, objs)
}
if (options$include) output else if (is.null(s <- options$indent)) '' else s
}
block_cache = function(options, output, objects) {
hash = options$hash
outname = cache_output_name(hash)
assign(outname, output, envir = knit_global())
purge_cache(options)
cache$library(options$cache.path, save = TRUE)
cache$save(objects, outname, hash, lazy = options$cache.lazy)
}
purge_cache = function(options) {
# purge my old cache and cache of chunks dependent on me
cache$purge(paste0(valid_path(
options$cache.path, c(options$label, dep_list$get(options$label))
), '_????????????????????????????????'))
}
# open a device for a chunk; depending on the option global.device, may or may
# not need to close the device on exit
chunk_device = function(
width, height, record = TRUE, dev, dev.args, dpi, options, tmp = tempfile()
) {
dev_new = function() {
# actually I should adjust the recording device according to dev, but here I
# have only considered the png and tikz devices (because the measurement
# results can be very different especially with the latter, see #1066), and
# also the cairo_pdf device (#1235)
if (identical(dev, 'png')) {
do.call(grDevices::png, c(list(
filename = tmp, width = width, height = height, units = 'in', res = dpi
), get_dargs(dev.args, 'png')))
} else if (identical(dev, 'tikz')) {
dargs = c(list(
file = tmp, width = width, height = height
), get_dargs(dev.args, 'tikz'))
dargs$sanitize = options$sanitize; dargs$standAlone = options$external
if (is.null(dargs$verbose)) dargs$verbose = FALSE
do.call(tikz_dev, dargs)
} else if (identical(dev, 'cairo_pdf')) {
do.call(grDevices::cairo_pdf, c(list(
filename = tmp, width = width, height = height
), get_dargs(dev.args, 'cairo_pdf')))
} else if (identical(getOption('device'), pdf_null)) {
if (!is.null(dev.args)) {
dev.args = get_dargs(dev.args, 'pdf')
dev.args = dev.args[intersect(names(dev.args), c('pointsize', 'bg'))]
}
do.call(pdf_null, c(list(width = width, height = height), dev.args))
} else dev.new(width = width, height = height)
}
if (!opts_knit$get('global.device')) {
dev_new()
dev.control(displaylist = if (record) 'enable' else 'inhibit') # enable recording
# if returns TRUE, we need to close this device after code is evaluated
return(TRUE)
} else if (is.null(dev.list())) {
# want to use a global device but not open yet
dev_new()
dev.control('enable')
}
FALSE
}
# filter out some results based on the numeric chunk option as indices
filter_evaluate = function(res, opt, test) {
if (length(res) == 0 || !is.numeric(opt) || !any(idx <- sapply(res, test)))
return(res)
idx = which(idx)
idx = setdiff(idx, na.omit(idx[opt])) # indices of elements to remove
if (length(idx) == 0) res else res[-idx]
}
# find recorded plots in the output of evaluate()
find_recordedplot = function(x) {
vapply(x, is_plot_output, logical(1))
}
is_plot_output = function(x) {
evaluate::is.recordedplot(x) || inherits(x, 'knit_image_paths')
}
# move plots before source code
fig_before_code = function(x) {
s = vapply(x, evaluate::is.source, logical(1))
if (length(s) == 0 || !any(s)) return(x)
s = which(s)
f = which(find_recordedplot(x))
f = f[f >= min(s)] # only move those plots after the first code block
for (i in f) {
j = max(s[s < i])
tmp = x[i]; x[[i]] = NULL; x = append(x, tmp, j - 1)
s = which(vapply(x, evaluate::is.source, logical(1)))
}
x
}
# merge neighbor elements of the same class in a list returned by evaluate()
merge_class = function(res, class = c('source', 'message', 'warning')) {
class = match.arg(class)
idx = if (length(res)) which(sapply(res, inherits, what = class))
if ((n <- length(idx)) <= 1) return(res)
k1 = idx[1]; k2 = NULL; res1 = res[[k1]]
el = c(source = 'src', message = 'message', warning = 'message')[class]
for (i in 1:(n - 1)) {
idx2 = idx[i + 1]; idx1 = idx[i]
if (idx2 - idx1 == 1) {
res2 = res[[idx2]]
# merge warnings/messages only if next one is identical to previous one
if (class == 'source' || identical(res1, res2) ||
(class == 'message' && !grepl('\n$', tail(res1[[el]], 1)))) {
res[[k1]][[el]] = c(res[[k1]][[el]], res2[[el]])
k2 = c(k2, idx2)
} else {
k1 = idx2
res1 = res[[k1]]
}
} else k1 = idx2
}
if (length(k2)) res = res[-k2] # remove lines that have been merged back
res
}
# merge character output for output='hold', if the subsequent character is of
# the same class(es) as the previous one (e.g. should not merge normal
# characters with asis_output())
merge_character = function(res) {
if ((n <- length(res)) <= 1) return(res)
k = NULL
for (i in 1:(n - 1)) {
cls = class(res[[i]])
if (identical(cls, class(res[[i + 1]]))) {
res[[i + 1]] = paste0(res[[i]], res[[i + 1]])
class(res[[i + 1]]) = cls
k = c(k, i)
}
}
if (length(k)) res = res[-k]
res
}
call_inline = function(block) {
if (opts_knit$get('progress')) print(block)
in_dir(input_dir(), inline_exec(block))
}
inline_exec = function(block, envir = knit_global(), hook = knit_hooks$get('inline')) {
# run inline code and substitute original texts
code = block$code; input = block$input
if ((n <- length(code)) == 0) return(input) # untouched if no code is found
loc = block$location
for (i in 1:n) {
options = opts_chunk$get()
if(!is.null(names(code)) && names(code)[i] != "")
options$engine = names(code)[i]
if(options$engine == "R")
{
v = withVisible(eval(parse_only(code[i]), envir = envir))
res = if (v$visible) knit_print(v$value, inline = TRUE, options = options)
if (inherits(res, 'knit_asis')) res = wrap(res, inline = TRUE)
}
else
{
options$code = code[i]
options$echo = FALSE
options$results = 'asis'
options$inline = TRUE
engine = get_engine(options$engine)
res = engine(options)
}
d = nchar(input)
# replace with evaluated results
stringr::str_sub(input, loc[i, 1], loc[i, 2]) = if (length(res)) {
paste(hook(res), collapse = '')
} else ''
if (i < n) loc[(i + 1):n, ] = loc[(i + 1):n, ] - (d - nchar(input))
# may need to move back and forth because replacement may be longer or shorter
}
input
}
process_tangle = function(x) {
UseMethod('process_tangle', x)
}
#' @export
process_tangle.block = function(x) {
params = opts_chunk$merge(x$params)
for (o in c('purl', 'eval', 'child'))
try(params[o] <- list(eval_lang(params[[o]])))
if (isFALSE(params$purl)) return('')
label = params$label; ev = params$eval
if (params$engine != 'R') return(comment_out(knit_code$get(label)))
code = if (!isFALSE(ev) && !is.null(params$child)) {
cmds = lapply(sc_split(params$child), knit_child)
paste(unlist(cmds), collapse = '\n')
} else knit_code$get(label)
# read external code if exists
if (!isFALSE(ev) && length(code) && grepl('read_chunk\\(.+\\)', code)) {
eval(parse_only(unlist(stringr::str_extract_all(code, 'read_chunk\\(([^)]+)\\)'))))
}
code = parse_chunk(code)
if (isFALSE(ev)) code = comment_out(code, params$comment, newline = FALSE)
if (opts_knit$get('documentation') == 0L) return(paste(code, collapse = '\n'))
label_code(code, x$params.src)
}
#' @export
process_tangle.inline = function(x) {
output = if (opts_knit$get('documentation') == 2L) {
output = paste(line_prompt(x$input.src, "#' ", "#' "), collapse = '\n')
} else ''
code = x$code
if (length(code) == 0L) return(output)
if (getOption('knitr.purl.inline', FALSE)) output = c(output, code)
idx = grepl('knit_child\\(.+\\)', code)
if (any(idx)) {
cout = sapply(code[idx], function(z) eval(parse_only(z)))
output = c(output, cout, '')
}
paste(output, collapse = '\n')
}
# add a label [and extra chunk options] to a code chunk
label_code = function(code, label) {
code = paste(c('', code, ''), collapse = '\n')
paste0('## ----', stringr::str_pad(label, max(getOption('width') - 11L, 0L), 'right', '-'),
'----', code)
}
as.source = function(code) {
list(structure(list(src = code), class = 'source'))
}
|
library(glmnet)
mydata = read.table("../../../../TrainingSet/FullSet/Correlation/NSCLC.csv",head=T,sep=",")
x = as.matrix(mydata[,4:ncol(mydata)])
y = as.matrix(mydata[,1])
set.seed(123)
glm = cv.glmnet(x,y,nfolds=10,type.measure="mse",alpha=0.45,family="gaussian",standardize=FALSE)
sink('./NSCLC_054.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
| /Model/EN/Correlation/NSCLC/NSCLC_054.R | no_license | esbgkannan/QSMART | R | false | false | 349 | r | library(glmnet)
mydata = read.table("../../../../TrainingSet/FullSet/Correlation/NSCLC.csv",head=T,sep=",")
x = as.matrix(mydata[,4:ncol(mydata)])
y = as.matrix(mydata[,1])
set.seed(123)
glm = cv.glmnet(x,y,nfolds=10,type.measure="mse",alpha=0.45,family="gaussian",standardize=FALSE)
sink('./NSCLC_054.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
|
# plot2.R -- Exploratory Data Analysis project 1
#The dataset has 2,075,259 rows and 9 columns. We will only be using data from the #dates 2007-02-01 and 2007-02-02. Missing values are coded as "?"
library(downloader, quietly = TRUE)
library(readr, quietly = TRUE)
library(stringr, quietly = TRUE)
library(dplyr, quietly = TRUE)
library(lubridate, quietly = TRUE)
fname <- "household_power_consumption.txt"
url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
# Download and unzip if the data file is not here.
if (!file.exists(fname)) {
print("Downloading and unzipping the data sets.")
download(url, "exdata-data-household_power_consumption.zip")
unzip("exdata-data-household_power_consumption.zip", "household_power_consumption.txt")}
# Read the whole data and then filter
df <- read_csv2(fname, na = "?") %>%
filter(Date == "1/2/2007" | Date == "2/2/2007")
# Add a new variable "datetime"
df <- df %>%
mutate(datetime =
parse_date_time(str_c(Date, Time, sep = " "),"dmy_hms", truncated = 3))
xlable <- c("1/2/2007", "2/2/2007", "3/2/2007") %>%
dmy %>%
weekdays(abbreviate = TRUE)
# Plot 2: Open png file graphics device and plot, then close the device.
png("plot2.png", width = 480, height = 480)
with(df, plot(Global_active_power,
type = 'l',
ylab = "Glabal Active Power (Killowatts)",
xaxt = "n", xlab = ""))
axis(1, at = c(0., 1440.5, 2881.0), label = xlable)
dev.off()
| /plot2.R | no_license | mjdata/ExData_Plotting1 | R | false | false | 1,525 | r | # plot2.R -- Exploratory Data Analysis project 1
#The dataset has 2,075,259 rows and 9 columns. We will only be using data from the #dates 2007-02-01 and 2007-02-02. Missing values are coded as "?"
library(downloader, quietly = TRUE)
library(readr, quietly = TRUE)
library(stringr, quietly = TRUE)
library(dplyr, quietly = TRUE)
library(lubridate, quietly = TRUE)
fname <- "household_power_consumption.txt"
url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
# Download and unzip if the data file is not here.
if (!file.exists(fname)) {
print("Downloading and unzipping the data sets.")
download(url, "exdata-data-household_power_consumption.zip")
unzip("exdata-data-household_power_consumption.zip", "household_power_consumption.txt")}
# Read the whole data and then filter
df <- read_csv2(fname, na = "?") %>%
filter(Date == "1/2/2007" | Date == "2/2/2007")
# Add a new variable "datetime"
df <- df %>%
mutate(datetime =
parse_date_time(str_c(Date, Time, sep = " "),"dmy_hms", truncated = 3))
xlable <- c("1/2/2007", "2/2/2007", "3/2/2007") %>%
dmy %>%
weekdays(abbreviate = TRUE)
# Plot 2: Open png file graphics device and plot, then close the device.
png("plot2.png", width = 480, height = 480)
with(df, plot(Global_active_power,
type = 'l',
ylab = "Glabal Active Power (Killowatts)",
xaxt = "n", xlab = ""))
axis(1, at = c(0., 1440.5, 2881.0), label = xlable)
dev.off()
|
#Expectations
#SivaguruB
- Class: text
Output: "Expectations. (Slides for this and other Data Science courses may be found at github https://github.com/DataScienceSpecialization/courses/. If you care to use them, they must be downloaded as a zip file and viewed locally. This lesson corresponds to 06_Statistical_Inference/04_Expectations.)"
- Class: text
Output: In this lesson, as you might expect, we'll discuss expected values. Expected values of what, exactly?
- Class: text
Output: The expected value of a random variable X, E(X), is a measure of its central tendency. For a discrete random variable X with PMF p(x), E(X) is defined as a sum, over all possible values x, of the quantity x*p(x). E(X) represents the center of mass of a collection of locations and weights, {x, p(x)}.
- Class: text
Output: Another term for expected value is mean. Recall your high school definition of arithmetic mean (or average) as the sum of a bunch of numbers divided by the number of numbers you added together. This is consistent with the formal definition of E(X) if all the numbers are equally weighted.
- Class: cmd_question
Output: Consider the random variable X representing a roll of a fair dice. By 'fair' we mean all the sides are equally likely to appear. What is the expected value of X?
CorrectAnswer: 3.5
AnswerTests: equiv_val(3.5)
Hint: Add the numbers from 1 to 6 and divide by 6.
- Class: cmd_question
Output: We've defined a function for you, expect_dice, which takes a PMF as an input. For our purposes, the PMF is a 6-long array of fractions. The i-th entry in the array represents the probability of i being the outcome of a dice roll. Look at the function expect_dice now.
CorrectAnswer: expect_dice
AnswerTests: omnitest(correctExpr='expect_dice')
Hint: Type 'expect_dice' at the command prompt.
- Class: cmd_question
Output: We've also defined PMFs for three dice, dice_fair, dice_high and dice_low. The last two are loaded, that is, not fair. Look at dice_high now.
CorrectAnswer: dice_high
AnswerTests: omnitest(correctExpr='dice_high')
Hint: Type 'dice_high' at the command prompt.
- Class: cmd_question
Output: Using the function expect_dice with dice_high as its argument, calculate the expected value of a roll of dice_high.
CorrectAnswer: expect_dice(dice_high)
AnswerTests: omnitest(correctExpr='expect_dice(dice_high)')
Hint: Type 'expect_dice(dice_high)' at the command prompt.
- Class: cmd_question
Output: See how the expected value of dice_high is higher than that of the fair dice. Now calculate the expected value of a roll of dice_low.
CorrectAnswer: expect_dice(dice_low)
AnswerTests: omnitest(correctExpr='expect_dice(dice_low)')
Hint: Type 'expect_dice(dice_low)' at the command prompt.
- Class: text
Output: You can see the effect of loading the dice on the expectations of the rolls. For high-loaded dice the expected value of a roll (on average) is 4.33 and for low-loaded dice 2.67. We've stored these off for you in two variables, edh and edl. We'll need them later.
- Class: text
Output: One of the nice properties of the expected value operation is that it's linear. This means that, if c is a constant, then E(cX) = c*E(X). Also, if X and Y are two random variables then E(X+Y)=E(X)+E(Y). It follows that E(aX+bY)=aE(X)+bE(Y).
- Class: cmd_question
Output: Suppose you were rolling our two loaded dice, dice_high and dice_low. You can use this linearity property of expectation to compute the expected value of their average. Let X_hi and X_lo represent the respective outcomes of the dice roll. The expected value of the average is E((X_hi + X_lo)/2) or .5 *( E(X_hi)+E(X_lo) ). Compute this now. Remember we stored the expected values in edh and edl.
CorrectAnswer: 3.5
AnswerTests: equiv_val(3.5)
Hint: Type '.5*(edh+edl)' at the command prompt.
- Class: mult_question
Output: Did you expect that?
AnswerChoices: Yes; No
CorrectAnswer: Yes
AnswerTests: omnitest(correctVal='Yes')
Hint: The dice were loaded in opposite ways so their average should be fair. No?
- Class: text
Output: For a continuous random variable X, the expected value is defined analogously as it was for the discrete case. Instead of summing over discrete values, however, the expectation integrates over a continuous function.
- Class: text
Output: It follows that for continuous random variables, E(X) is the area under the function t*f(t), where f(t) is the PDF (probability density function) of X. This definition borrows from the definition of center of mass of a continuous body.
- Class: figure
Output: Here's a figure from the slides. It shows the constant (1) PDF on the left and the graph of t*f(t) on the right.
Figure: plot1.R
FigureType: new
- Class: mult_question
Output: Knowing that the expected value is the area under the triangle, t*f(t), what is the expected value of the random variable with this PDF?
AnswerChoices: 1.0; 2.0; .5; .25
CorrectAnswer: .5
AnswerTests: omnitest(correctVal='.5')
Hint: The area of the triangle is base*height/2.
- Class: figure
Output: For the purposes of illustration, here's another figure using a PDF from our previous probability lesson. It shows the triangular PDF f(t) on the left and the parabolic t*f(t) on the right. The area under the parabola between 0 and 2 represents the expected value of the random variable with this PDF.
Figure: plot2.R
FigureType: new
- Class: cmd_question
Output: To find the expected value of this random variable you need to integrate the function t*f(t). Here f(t)=t/2, the diagonal line. (You might recall this from the last probability lesson.) The function you're integrating over is therefore t^2/2. We've defined a function myfunc for you representing this. You can use the R function 'integrate' with parameters myfunc, 0 (the lower bound), and 2 (the upper bound) to find the expected value. Do this now.
CorrectAnswer: integrate(myfunc,0,2)
AnswerTests: omnitest(correctExpr='integrate(myfunc,0,2)')
Hint: Type 'integrate(myfunc,0,2)' at the command prompt.
- Class: text
Output: As all the examples have shown, expected values of distributions are useful in characterizing them. The mean characterizes the central tendency of the distribution. However, often populations are too big to measure, so we have to sample them and then we have to use sample means. That's okay because sample expected values estimate the population versions. We'll show this first with a very simple toy and then with some simple equations.
- Class: cmd_question
Output: We've defined a small population of 5 numbers for you, spop. Look at it now.
CorrectAnswer: spop
AnswerTests: omnitest(correctExpr='spop')
Hint: Type 'spop' at the command prompt.
- Class: cmd_question
Output: The R function mean will give us the mean of spop. Do this now.
CorrectAnswer: mean(spop)
AnswerTests: omnitest(correctExpr='mean(spop)')
Hint: Type 'mean(spop)' at the command prompt.
- Class: cmd_question
Output: Suppose spop were much bigger and we couldn't measure its mean directly and instead had to sample it with samples of size 2. There are 10 such samples, right? We've stored this for you in a 10 x 2 matrix, allsam. Look at it now.
CorrectAnswer: allsam
AnswerTests: omnitest(correctExpr='allsam')
Hint: Type 'allsam' at the command prompt.
- Class: cmd_question
Output: Each of these 10 samples will have a mean, right? We can use the R function apply to calculate the mean of each row of the matrix allsam. We simply call apply with the arguments allsam, 1, and mean. The second argument, 1, tells 'apply' to apply the third argument 'mean' to the rows of the matrix. Try this now.
CorrectAnswer: apply(allsam,1,mean)
AnswerTests: omnitest(correctExpr='apply(allsam,1,mean)')
Hint: Type 'apply(allsam,1,mean)' at the command prompt.
- Class: text
Output: You can see from the resulting vector that the sample means vary a lot, from 2.5 to 11.5, right? Not unexpectedly, the sample mean depends on the sample. However...
- Class: cmd_question
Output: ... if we take the expected value of these sample means we'll see something amazing. We've stored the sample means in the array smeans for you. Use the R function mean on the array smeans now.
CorrectAnswer: mean(smeans)
AnswerTests: omnitest(correctExpr='mean(smeans)')
Hint: Type 'mean(smeans)' at the command prompt.
- Class: text
Output: Look familiar? The result is the same as the mean of the original population spop. This is not because the example was specially cooked. It would work on any population. The expected value or mean of the sample mean is the population mean. What this means is that the sample mean is an unbiased estimator of the population mean.
- Class: text
Output: Formally, an estimator e of some parameter v is unbiased if its expected value equals v, i.e., E(e)=v. We can show that the expected value of a sample mean equals the population mean with some simple algebra.
- Class: text
Output: Let X_1, X_2, ... X_n be a collection of n samples from a population with mean mu. The mean of these is (X_1 + X_2 + ... + X_n)/n.
- Class: text
Output: What's the expected value of the mean? Recall that E(aX)=aE(X), so E( (X_1+..+X_n)/n ) =
- Class: text
Output: 1/n * (E(X_1) + E(X_2) + ... + E(X_n)) = (1/n)*n*mu = mu. Each E(X_i) equals mu since X_i is drawn from the population with mean mu. We expect, on average, a random X_i will equal mu.
- Class: text
Output: Now that was theory. We can also show this empirically with more simulations.
- Class: figure
Output: Here's another figure from the slides. It shows how a sample mean and the mean of averages spike together. The two shaded distributions come from the same data. The blue portion represents the density function of randomly generated standard normal data, 100000 samples. The pink portion represents the density function of 10000 averages, each of 10 random normals. (The original data was stored in a 10000 x 10 array and the average of each row was taken to generate the pink data.)
Figure: normalMeans.R
FigureType: new
- Class: figure
Output: Here's another figure from the slides. Rolling a single die 10000 times yields the first figure. Each of the 6 possible outcomes appears with about the same frequency. The second figure is the histogram of outcomes of the average of rolling two dice. Similarly, the third figure is the histogram of averages of rolling three dice, and the fourth four dice. As we showed previously, the center or mean of the original distribution is 3.5 and that's exactly where all the panels are centered.
Figure: diceRolls.R
FigureType: new
- Class: text
Output: Let's recap. Expected values are properties of distributions. The average, or mean, of random variables is itself a random variable and its associated distribution itself has an expected value. The center of this distribution is the same as that of the original distribution.
- Class: text
Output: Now let's review!
- Class: mult_question
Output: Expected values are properties of what?
AnswerChoices: demanding parents; distributions; fulcrums; variances
CorrectAnswer: distributions
AnswerTests: omnitest(correctVal='distributions')
Hint: What would you expect to have a center?
- Class: mult_question
Output: A population mean is a center of mass of what?
AnswerChoices: a family; a distribution; a population; a sample
CorrectAnswer: a population
AnswerTests: omnitest(correctVal='a population')
Hint: What word appears in the question?
- Class: mult_question
Output: A sample mean is a center of mass of what?
AnswerChoices: a family; a distribution; a population; observed data
CorrectAnswer: observed data
AnswerTests: omnitest(correctVal='observed data')
Hint: If you're sampling you need to observe data, right?
- Class: mult_question
Output: True or False? A population mean estimates a sample mean.
AnswerChoices: True; False
CorrectAnswer: False
AnswerTests: omnitest(correctVal='False')
Hint: We can only sample a population and calculate the sample mean.
- Class: mult_question
Output: True or False? A sample mean is unbiased.
AnswerChoices: True; False
CorrectAnswer: True
AnswerTests: omnitest(correctVal='True')
Hint: The sample mean is the population mean, so by definition it's unbiased.
- Class: mult_question
Output: True or False? The more data that goes into the sample mean, the more concentrated its density / mass function is around the population mean.
AnswerChoices: True; False
CorrectAnswer: True
AnswerTests: omnitest(correctVal='True')
Hint: It's better to have more data than less, right?
- Class: text
Output: Congrats! You've concluded this lesson on expectations. We hope it met yours.
| /Swirl/Expectations.R | no_license | SivaguruB/Coursera-Statistical-Inference | R | false | false | 12,851 | r | #Expectations
#SivaguruB
- Class: text
Output: "Expectations. (Slides for this and other Data Science courses may be found at github https://github.com/DataScienceSpecialization/courses/. If you care to use them, they must be downloaded as a zip file and viewed locally. This lesson corresponds to 06_Statistical_Inference/04_Expectations.)"
- Class: text
Output: In this lesson, as you might expect, we'll discuss expected values. Expected values of what, exactly?
- Class: text
Output: The expected value of a random variable X, E(X), is a measure of its central tendency. For a discrete random variable X with PMF p(x), E(X) is defined as a sum, over all possible values x, of the quantity x*p(x). E(X) represents the center of mass of a collection of locations and weights, {x, p(x)}.
- Class: text
Output: Another term for expected value is mean. Recall your high school definition of arithmetic mean (or average) as the sum of a bunch of numbers divided by the number of numbers you added together. This is consistent with the formal definition of E(X) if all the numbers are equally weighted.
- Class: cmd_question
Output: Consider the random variable X representing a roll of a fair dice. By 'fair' we mean all the sides are equally likely to appear. What is the expected value of X?
CorrectAnswer: 3.5
AnswerTests: equiv_val(3.5)
Hint: Add the numbers from 1 to 6 and divide by 6.
- Class: cmd_question
Output: We've defined a function for you, expect_dice, which takes a PMF as an input. For our purposes, the PMF is a 6-long array of fractions. The i-th entry in the array represents the probability of i being the outcome of a dice roll. Look at the function expect_dice now.
CorrectAnswer: expect_dice
AnswerTests: omnitest(correctExpr='expect_dice')
Hint: Type 'expect_dice' at the command prompt.
- Class: cmd_question
Output: We've also defined PMFs for three dice, dice_fair, dice_high and dice_low. The last two are loaded, that is, not fair. Look at dice_high now.
CorrectAnswer: dice_high
AnswerTests: omnitest(correctExpr='dice_high')
Hint: Type 'dice_high' at the command prompt.
- Class: cmd_question
Output: Using the function expect_dice with dice_high as its argument, calculate the expected value of a roll of dice_high.
CorrectAnswer: expect_dice(dice_high)
AnswerTests: omnitest(correctExpr='expect_dice(dice_high)')
Hint: Type 'expect_dice(dice_high)' at the command prompt.
- Class: cmd_question
Output: See how the expected value of dice_high is higher than that of the fair dice. Now calculate the expected value of a roll of dice_low.
CorrectAnswer: expect_dice(dice_low)
AnswerTests: omnitest(correctExpr='expect_dice(dice_low)')
Hint: Type 'expect_dice(dice_low)' at the command prompt.
- Class: text
Output: You can see the effect of loading the dice on the expectations of the rolls. For high-loaded dice the expected value of a roll (on average) is 4.33 and for low-loaded dice 2.67. We've stored these off for you in two variables, edh and edl. We'll need them later.
- Class: text
Output: One of the nice properties of the expected value operation is that it's linear. This means that, if c is a constant, then E(cX) = c*E(X). Also, if X and Y are two random variables then E(X+Y)=E(X)+E(Y). It follows that E(aX+bY)=aE(X)+bE(Y).
- Class: cmd_question
Output: Suppose you were rolling our two loaded dice, dice_high and dice_low. You can use this linearity property of expectation to compute the expected value of their average. Let X_hi and X_lo represent the respective outcomes of the dice roll. The expected value of the average is E((X_hi + X_lo)/2) or .5 *( E(X_hi)+E(X_lo) ). Compute this now. Remember we stored the expected values in edh and edl.
CorrectAnswer: 3.5
AnswerTests: equiv_val(3.5)
Hint: Type '.5*(edh+edl)' at the command prompt.
- Class: mult_question
Output: Did you expect that?
AnswerChoices: Yes; No
CorrectAnswer: Yes
AnswerTests: omnitest(correctVal='Yes')
Hint: The dice were loaded in opposite ways so their average should be fair. No?
- Class: text
Output: For a continuous random variable X, the expected value is defined analogously as it was for the discrete case. Instead of summing over discrete values, however, the expectation integrates over a continuous function.
- Class: text
Output: It follows that for continuous random variables, E(X) is the area under the function t*f(t), where f(t) is the PDF (probability density function) of X. This definition borrows from the definition of center of mass of a continuous body.
- Class: figure
Output: Here's a figure from the slides. It shows the constant (1) PDF on the left and the graph of t*f(t) on the right.
Figure: plot1.R
FigureType: new
- Class: mult_question
Output: Knowing that the expected value is the area under the triangle, t*f(t), what is the expected value of the random variable with this PDF?
AnswerChoices: 1.0; 2.0; .5; .25
CorrectAnswer: .5
AnswerTests: omnitest(correctVal='.5')
Hint: The area of the triangle is base*height/2.
- Class: figure
Output: For the purposes of illustration, here's another figure using a PDF from our previous probability lesson. It shows the triangular PDF f(t) on the left and the parabolic t*f(t) on the right. The area under the parabola between 0 and 2 represents the expected value of the random variable with this PDF.
Figure: plot2.R
FigureType: new
- Class: cmd_question
Output: To find the expected value of this random variable you need to integrate the function t*f(t). Here f(t)=t/2, the diagonal line. (You might recall this from the last probability lesson.) The function you're integrating over is therefore t^2/2. We've defined a function myfunc for you representing this. You can use the R function 'integrate' with parameters myfunc, 0 (the lower bound), and 2 (the upper bound) to find the expected value. Do this now.
CorrectAnswer: integrate(myfunc,0,2)
AnswerTests: omnitest(correctExpr='integrate(myfunc,0,2)')
Hint: Type 'integrate(myfunc,0,2)' at the command prompt.
- Class: text
Output: As all the examples have shown, expected values of distributions are useful in characterizing them. The mean characterizes the central tendency of the distribution. However, often populations are too big to measure, so we have to sample them and then we have to use sample means. That's okay because sample expected values estimate the population versions. We'll show this first with a very simple toy and then with some simple equations.
- Class: cmd_question
Output: We've defined a small population of 5 numbers for you, spop. Look at it now.
CorrectAnswer: spop
AnswerTests: omnitest(correctExpr='spop')
Hint: Type 'spop' at the command prompt.
- Class: cmd_question
Output: The R function mean will give us the mean of spop. Do this now.
CorrectAnswer: mean(spop)
AnswerTests: omnitest(correctExpr='mean(spop)')
Hint: Type 'mean(spop)' at the command prompt.
- Class: cmd_question
Output: Suppose spop were much bigger and we couldn't measure its mean directly and instead had to sample it with samples of size 2. There are 10 such samples, right? We've stored this for you in a 10 x 2 matrix, allsam. Look at it now.
CorrectAnswer: allsam
AnswerTests: omnitest(correctExpr='allsam')
Hint: Type 'allsam' at the command prompt.
- Class: cmd_question
Output: Each of these 10 samples will have a mean, right? We can use the R function apply to calculate the mean of each row of the matrix allsam. We simply call apply with the arguments allsam, 1, and mean. The second argument, 1, tells 'apply' to apply the third argument 'mean' to the rows of the matrix. Try this now.
CorrectAnswer: apply(allsam,1,mean)
AnswerTests: omnitest(correctExpr='apply(allsam,1,mean)')
Hint: Type 'apply(allsam,1,mean)' at the command prompt.
- Class: text
Output: You can see from the resulting vector that the sample means vary a lot, from 2.5 to 11.5, right? Not unexpectedly, the sample mean depends on the sample. However...
- Class: cmd_question
Output: ... if we take the expected value of these sample means we'll see something amazing. We've stored the sample means in the array smeans for you. Use the R function mean on the array smeans now.
CorrectAnswer: mean(smeans)
AnswerTests: omnitest(correctExpr='mean(smeans)')
Hint: Type 'mean(smeans)' at the command prompt.
- Class: text
Output: Look familiar? The result is the same as the mean of the original population spop. This is not because the example was specially cooked. It would work on any population. The expected value or mean of the sample mean is the population mean. What this means is that the sample mean is an unbiased estimator of the population mean.
- Class: text
Output: Formally, an estimator e of some parameter v is unbiased if its expected value equals v, i.e., E(e)=v. We can show that the expected value of a sample mean equals the population mean with some simple algebra.
- Class: text
Output: Let X_1, X_2, ... X_n be a collection of n samples from a population with mean mu. The mean of these is (X_1 + X_2 + ... + X_n)/n.
- Class: text
Output: What's the expected value of the mean? Recall that E(aX)=aE(X), so E( (X_1+..+X_n)/n ) =
- Class: text
Output: 1/n * (E(X_1) + E(X_2) + ... + E(X_n)) = (1/n)*n*mu = mu. Each E(X_i) equals mu since X_i is drawn from the population with mean mu. We expect, on average, a random X_i will equal mu.
- Class: text
Output: Now that was theory. We can also show this empirically with more simulations.
- Class: figure
Output: Here's another figure from the slides. It shows how a sample mean and the mean of averages spike together. The two shaded distributions come from the same data. The blue portion represents the density function of randomly generated standard normal data, 100000 samples. The pink portion represents the density function of 10000 averages, each of 10 random normals. (The original data was stored in a 10000 x 10 array and the average of each row was taken to generate the pink data.)
Figure: normalMeans.R
FigureType: new
- Class: figure
Output: Here's another figure from the slides. Rolling a single die 10000 times yields the first figure. Each of the 6 possible outcomes appears with about the same frequency. The second figure is the histogram of outcomes of the average of rolling two dice. Similarly, the third figure is the histogram of averages of rolling three dice, and the fourth four dice. As we showed previously, the center or mean of the original distribution is 3.5 and that's exactly where all the panels are centered.
Figure: diceRolls.R
FigureType: new
- Class: text
Output: Let's recap. Expected values are properties of distributions. The average, or mean, of random variables is itself a random variable and its associated distribution itself has an expected value. The center of this distribution is the same as that of the original distribution.
- Class: text
Output: Now let's review!
- Class: mult_question
Output: Expected values are properties of what?
AnswerChoices: demanding parents; distributions; fulcrums; variances
CorrectAnswer: distributions
AnswerTests: omnitest(correctVal='distributions')
Hint: What would you expect to have a center?
- Class: mult_question
Output: A population mean is a center of mass of what?
AnswerChoices: a family; a distribution; a population; a sample
CorrectAnswer: a population
AnswerTests: omnitest(correctVal='a population')
Hint: What word appears in the question?
- Class: mult_question
Output: A sample mean is a center of mass of what?
AnswerChoices: a family; a distribution; a population; observed data
CorrectAnswer: observed data
AnswerTests: omnitest(correctVal='observed data')
Hint: If you're sampling you need to observe data, right?
- Class: mult_question
Output: True or False? A population mean estimates a sample mean.
AnswerChoices: True; False
CorrectAnswer: False
AnswerTests: omnitest(correctVal='False')
Hint: We can only sample a population and calculate the sample mean.
- Class: mult_question
Output: True or False? A sample mean is unbiased.
AnswerChoices: True; False
CorrectAnswer: True
AnswerTests: omnitest(correctVal='True')
Hint: The sample mean is the population mean, so by definition it's unbiased.
- Class: mult_question
Output: True or False? The more data that goes into the sample mean, the more concentrated its density / mass function is around the population mean.
AnswerChoices: True; False
CorrectAnswer: True
AnswerTests: omnitest(correctVal='True')
Hint: It's better to have more data than less, right?
- Class: text
Output: Congrats! You've concluded this lesson on expectations. We hope it met yours.
|
# ##############################################################################
# Author: Georgios Kampolis
#
# Description: Sets up Box-Cox transformations and plots their effects.
#
# ##############################################################################
# Determine best lamda via Guerrero method.
lambdaProposed <- BoxCox.lambda(windTS, method = "guerrero") # approx. 0.32533
plotMeasured <- windTS %>%
autoplot() +
labs(x = "Time (Days)",
y = "Wind Speed (m/s)",
subtitle = bquote("Measurements - untransformed series."*" | " *
"Variance: "*.(round(var(windTS),2))
)
)
plotProposed <- BoxCox(windTS, lambda = lambdaProposed) %>%
autoplot() +
labs(x = "Time (Days)",
y = "Transformed Speed",
subtitle = bquote("Box-Cox transformed. " *
lambda*": " *
.(round(lambdaProposed, digits = 3))*" | " *
"Variance: "*.(round(var(BoxCox(windTS, lambda = lambdaProposed)),2))
)
)
plotLogTrans <- BoxCox(windTS, lambda = 0) %>%
autoplot() +
labs(x = "Time (Days)",
y = "Transformed Speed",
subtitle = bquote("Box-Cox (log) transformed. "*lambda*": 0" *
" | "*"Variance: "*.(round(var(BoxCox(windTS, lambda = 0)),2))
)
)
plotLogTransDual <- BoxCox(windTS + 1, lambda = 0) %>%
autoplot() +
labs(x = "Time (Days)",
y = "Transformed Speed",
subtitle = bquote("Dual parameter Box-Cox (log) transformed. " *
lambda[1]*": 0 "*lambda[2]*": 1"*" | " *
"Variance: "*.(round(var(BoxCox(windTS + 1, lambda = 0)),2))
)
)
plot <- cowplot::plot_grid(plotMeasured + theme(axis.title.x = element_blank()),
plotProposed + theme(axis.title.x = element_blank()),
plotLogTrans + theme(axis.title.x = element_blank()),
plotLogTransDual,
ncol = 1,
align = "v", axis = "tblr"
)
saveA5(plot, "BoxCoxExplore", "V")
rm(plot, plotMeasured, plotProposed, plotLogTrans, plotLogTransDual)
## Histograms & Density plots ##
windSummary <- summary(windTS)
histWind <- ggplot(windTS, aes(x = windTS)) +
geom_histogram(aes(y = ..density..),
binwidth = 0.5,
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = "Measurements - untransformed series.",
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" m/s | Median: ", round(windSummary[3], digits = 2),
" m/s | Mean: ", round(windSummary[4], digits = 2),
" m/s | Max: ", round(windSummary[6], digits = 2), " m/s"
)
)
windSummary <- summary(BoxCox(windTS, lambda = lambdaProposed))
histWindProposed <- ggplot(windTS, aes(x = BoxCox(windTS, lambda = lambdaProposed))) +
geom_histogram(aes(y = ..density..),
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = bquote("Box-Cox transformed. "*lambda*": " *
.(round(lambdaProposed, digits = 3))
),
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" | Median: ", round(windSummary[3], digits = 2),
" | Mean: ", round(windSummary[4], digits = 2),
" | Max: ", round(windSummary[6], digits = 2)
)
)
windSummary <- summary(BoxCox(windTS, lambda = 0))
histWindLogTrans <- ggplot(windTS, aes(x = BoxCox(windTS, lambda = 0))) +
geom_histogram(aes(y = ..density..),
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = bquote("Box-Cox (log) transformed. "*lambda*": 0"),
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" | Median: ", round(windSummary[3], digits = 2),
" | Mean: ", round(windSummary[4], digits = 2),
" | Max: ", round(windSummary[6], digits = 2)
)
)
windSummary <- summary(BoxCox(windTS + 1, lambda = 0))
histWindLogTransDual <- ggplot(windTS, aes(x = BoxCox(windTS + 1, lambda = 0))) +
geom_histogram(aes(y = ..density..),
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = bquote("Dual parameter Box-Cox (log) transformed. " *
lambda[1]*": 0 "*lambda[2]*": 1"
),
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" | Median: ", round(windSummary[3], digits = 2),
" | Mean: ", round(windSummary[4], digits = 2),
" | Max: ", round(windSummary[6], digits = 2)
)
)
histPlot <- plot_grid(
histWind + theme(axis.title.x = element_blank()),
histWindProposed + theme(axis.title.x = element_blank()),
histWindLogTrans + theme(axis.title.x = element_blank()),
histWindLogTransDual + theme(axis.title.x = element_blank()),
ncol = 1,
align = "v", axis = "tblr"
)
saveA5(histPlot, "BoxCoxExploreHistogram", "V")
rm(lambdaProposed, windSummary, histWind, histWindProposed,
histWindLogTrans, histWindLogTransDual, histPlot)
## Notify that script's end has been reached ##
if (require(beepr)) {beepr::beep(1)}
| /scripts/3_4BoxCox.R | permissive | gkampolis/ChilWind | R | false | false | 5,947 | r | # ##############################################################################
# Author: Georgios Kampolis
#
# Description: Sets up Box-Cox transformations and plots their effects.
#
# ##############################################################################
# Determine best lamda via Guerrero method.
lambdaProposed <- BoxCox.lambda(windTS, method = "guerrero") # approx. 0.32533
plotMeasured <- windTS %>%
autoplot() +
labs(x = "Time (Days)",
y = "Wind Speed (m/s)",
subtitle = bquote("Measurements - untransformed series."*" | " *
"Variance: "*.(round(var(windTS),2))
)
)
plotProposed <- BoxCox(windTS, lambda = lambdaProposed) %>%
autoplot() +
labs(x = "Time (Days)",
y = "Transformed Speed",
subtitle = bquote("Box-Cox transformed. " *
lambda*": " *
.(round(lambdaProposed, digits = 3))*" | " *
"Variance: "*.(round(var(BoxCox(windTS, lambda = lambdaProposed)),2))
)
)
plotLogTrans <- BoxCox(windTS, lambda = 0) %>%
autoplot() +
labs(x = "Time (Days)",
y = "Transformed Speed",
subtitle = bquote("Box-Cox (log) transformed. "*lambda*": 0" *
" | "*"Variance: "*.(round(var(BoxCox(windTS, lambda = 0)),2))
)
)
plotLogTransDual <- BoxCox(windTS + 1, lambda = 0) %>%
autoplot() +
labs(x = "Time (Days)",
y = "Transformed Speed",
subtitle = bquote("Dual parameter Box-Cox (log) transformed. " *
lambda[1]*": 0 "*lambda[2]*": 1"*" | " *
"Variance: "*.(round(var(BoxCox(windTS + 1, lambda = 0)),2))
)
)
plot <- cowplot::plot_grid(plotMeasured + theme(axis.title.x = element_blank()),
plotProposed + theme(axis.title.x = element_blank()),
plotLogTrans + theme(axis.title.x = element_blank()),
plotLogTransDual,
ncol = 1,
align = "v", axis = "tblr"
)
saveA5(plot, "BoxCoxExplore", "V")
rm(plot, plotMeasured, plotProposed, plotLogTrans, plotLogTransDual)
## Histograms & Density plots ##
windSummary <- summary(windTS)
histWind <- ggplot(windTS, aes(x = windTS)) +
geom_histogram(aes(y = ..density..),
binwidth = 0.5,
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = "Measurements - untransformed series.",
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" m/s | Median: ", round(windSummary[3], digits = 2),
" m/s | Mean: ", round(windSummary[4], digits = 2),
" m/s | Max: ", round(windSummary[6], digits = 2), " m/s"
)
)
windSummary <- summary(BoxCox(windTS, lambda = lambdaProposed))
histWindProposed <- ggplot(windTS, aes(x = BoxCox(windTS, lambda = lambdaProposed))) +
geom_histogram(aes(y = ..density..),
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = bquote("Box-Cox transformed. "*lambda*": " *
.(round(lambdaProposed, digits = 3))
),
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" | Median: ", round(windSummary[3], digits = 2),
" | Mean: ", round(windSummary[4], digits = 2),
" | Max: ", round(windSummary[6], digits = 2)
)
)
windSummary <- summary(BoxCox(windTS, lambda = 0))
histWindLogTrans <- ggplot(windTS, aes(x = BoxCox(windTS, lambda = 0))) +
geom_histogram(aes(y = ..density..),
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = bquote("Box-Cox (log) transformed. "*lambda*": 0"),
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" | Median: ", round(windSummary[3], digits = 2),
" | Mean: ", round(windSummary[4], digits = 2),
" | Max: ", round(windSummary[6], digits = 2)
)
)
windSummary <- summary(BoxCox(windTS + 1, lambda = 0))
histWindLogTransDual <- ggplot(windTS, aes(x = BoxCox(windTS + 1, lambda = 0))) +
geom_histogram(aes(y = ..density..),
colour = "black",
fill = "white") +
geom_rug(sides = "b") +
geom_density(colour = "gray", fill = "gray", alpha = 1/2) +
theme(axis.title.x = element_blank()) +
labs(y = "Density",
title = bquote("Dual parameter Box-Cox (log) transformed. " *
lambda[1]*": 0 "*lambda[2]*": 1"
),
subtitle = paste0(
"Min: ", round(windSummary[1], digits = 2),
" | Median: ", round(windSummary[3], digits = 2),
" | Mean: ", round(windSummary[4], digits = 2),
" | Max: ", round(windSummary[6], digits = 2)
)
)
histPlot <- plot_grid(
histWind + theme(axis.title.x = element_blank()),
histWindProposed + theme(axis.title.x = element_blank()),
histWindLogTrans + theme(axis.title.x = element_blank()),
histWindLogTransDual + theme(axis.title.x = element_blank()),
ncol = 1,
align = "v", axis = "tblr"
)
saveA5(histPlot, "BoxCoxExploreHistogram", "V")
rm(lambdaProposed, windSummary, histWind, histWindProposed,
histWindLogTrans, histWindLogTransDual, histPlot)
## Notify that script's end has been reached ##
if (require(beepr)) {beepr::beep(1)}
|
# Tracks and table names ------------------------------------------------
.gpatterns.downsampled_track_name <- function(track, dsn) {qqv('@{track}.ds@{dsn}') }
.gpatterns.cov_track_name <- function(track) { qqv('@{track}.cov') }
.gpatterns.avg_track_name <- function(track) { qqv('@{track}.avg') }
.gpatterns.meth_track_name <- function(track) { qqv('@{track}.meth') }
.gpatterns.unmeth_track_name <- function(track) { qqv('@{track}.unmeth') }
.gpatterns.pat_cov_track_name <- function(track, pat_len) { qqv('@{track}.pat@{pat_len}') }
.gpatterns.frag_cov_track_name <- function(track) { qqv('@{track}.frag_cov')}
.gpatterns.fid_track_name <- function(track) { qqv('@{track}.fid')}
.gpatterns.ncpg_track_name <- function(track) { qqv('@{track}.ncpg')}
.gpatterns.n_track_name <- function(track) { qqv('@{track}.n')}
.gpatterns.n0_track_name <- function(track) { qqv('@{track}.n0')}
.gpatterns.n1_track_name <- function(track) { qqv('@{track}.n1')}
.gpatterns.nx_track_name <- function(track) { qqv('@{track}.nx')}
.gpatterns.nc_track_name <- function(track) { qqv('@{track}.nc')}
.gpatterns.pat_meth_track_name <- function(track) { qqv('@{track}.pat_meth')}
.gpatterns.pat_space_intervs_name <- function(track) { qqv('@{track}.pat_space')}
.gpatterns.epipolymorphism_track_name <- function(track) { qqv('@{track}.epipoly')}
.gpatterns.patterns_track_names <- function(track) {paste0(track, '.', c('n', 'n0', 'n1', 'nx', 'nc', 'pat_meth', 'epipoly', 'fid'))}
.gpatterns.mix_qval_track_name <- function(track) { qqv('@{track}.mix_qval')}
.gpatterns.mix_meth_track_name <- function(track) { qqv('@{track}.mix_meth')}
.gpatterns.mix_unmeth_track_name <- function(track) { qqv('@{track}.mix_unmeth')}
.gpatterns.gain_meth_track_name <- function(track) { qqv('@{track}.gain_meth')}
.gpatterns.gain_unmeth_track_name <- function(track) { qqv('@{track}.gain_unmeth')}
.gpatterns.loss_meth_track_name <- function(track) { qqv('@{track}.loss_meth')}
.gpatterns.loss_unmeth_track_name <- function(track) { qqv('@{track}.loss_unmeth')}
.gpatterns.center_meth_track_name <- function(track) { qqv('@{track}.center_meth_ones')}
.gpatterns.center_unmeth_track_name <- function(track) { qqv('@{track}.center_unmeth_ones')}
.gpatterns.center_uni_track_name <- function(track) { qqv('@{track}.center_uni_ones')}
.gpatterns.gain_uni_track_name <- function(track) { qqv('@{track}.gain_uni')}
.gpatterns.loss_uni_track_name <- function(track) { qqv('@{track}.loss_uni')}
.gpatterns.patterns_tab_name <- function(track) { 'patterns'}
.gpatterns.patterns_file_name <- function(track) { file.path(.gpatterns.base_dir(track), 'patterns.RData')}
.gpatterns.fids_tab_name <- function(track) { 'fids' }
.gpatterns.fids_file_name <- function(track) { file.path(.gpatterns.base_dir(track), 'fids.RData') }
.gpatterns.stats_file_name <- function(track) { qq('@{.gpatterns.base_dir(track)}/stats.tsv') }
.gpatterns.tidy_cpgs_files <- function(track) {
list.files(paste0(.gpatterns.base_dir(track), '/tidy_cpgs'), full.names=TRUE, pattern='tcpgs.gz')
}
.gpatterns.tidy_cpgs_dir <- function(track){
paste0(.gpatterns.base_dir(track), '/tidy_cpgs')
}
.gpatterns.bipolar_model_tab_name <- function(track) { 'mix' }
.gpatterns.bipolar_model_file_name <- function(track) {
file.path(.gpatterns.base_dir(track), 'bipolar.RData')
}
.gpatterns.bipolar_model_stats <- c('qval', 'mix.meth', 'mix.unmeth', 'center.meth', 'center.meth.ones', 'gain.meth', 'loss.meth', 'center.unmeth', 'center.unmeth.ones','gain.unmeth', 'loss.unmeth', 'center.uni', 'center.uni.ones', 'gain.uni', 'loss.uni')
.gpatterns.genome_cpgs_track <- 'seq.CG'
.gpatterns.genome_cpgs_intervals <- 'intervs.global.seq_CG'
.gpatterns.genome_next_cpg_intervals <- 'intervs.global.next_CG'
.gpatterns.cg_cont_500_track <- 'seq.CG_500_mean'
.gpatterns.special_intervals <- function(name){
intervs_map <- list(tss = 'intervs.global.tss',
exon = 'intervs.global.exon',
utr3 = 'intervs.global.utr3',
intron = 'intervs.global.introns',
cgi = 'intervs.global.cgi_ucsc')
if (name %in% names(intervs_map)){
return(intervs_map[[name]])
} else {
stop(qq('interval @{name} does not exist'))
}
}
.gpatterns.get_intervals <- function(intervals){
if (is.character(intervals)){
if (!gintervals.exists(intervals)){
intervals <- .gpatterns.special_intervals(intervals)
}
}
return(intervals)
}
# Color palettes ------------------------------------------------
# .blue_red_pal <- colorRampPalette(c("#87FFFF", "black", "#FF413D"))(1000)
#' @export
.blue_red_pal <- colorRampPalette(c("#00688B", "white", "#FF413D"))(1000)
.blue_black_red_yellow_pal <- colorRampPalette(c("white", "blue", "black", "red", "yellow"))(1000)
.red_blue_pal <- rev(colorRampPalette(c("#87FFFF", "black", "#FF413D"))(1000))
.blue_red_yellow_pal <- colorRampPalette(c("white", "blue", "red", "yellow"))(1000)
.smooth_scatter_pal2 <- colorRampPalette(c("white", "white", "deepskyblue4", "gray",
"darkgray", "black", "brown"))
.smooth_scatter_pal <- colorRampPalette(c("white", "white", "darkgrey", "black",
"#FF413D", "yellow"))
.smooth_scatter_pal3 <- colorRampPalette(c("white", "blue", "red", "yellow", "black"))
| /R/defs.R | no_license | tanaylab/gpatterns | R | false | false | 5,361 | r | # Tracks and table names ------------------------------------------------
.gpatterns.downsampled_track_name <- function(track, dsn) {qqv('@{track}.ds@{dsn}') }
.gpatterns.cov_track_name <- function(track) { qqv('@{track}.cov') }
.gpatterns.avg_track_name <- function(track) { qqv('@{track}.avg') }
.gpatterns.meth_track_name <- function(track) { qqv('@{track}.meth') }
.gpatterns.unmeth_track_name <- function(track) { qqv('@{track}.unmeth') }
.gpatterns.pat_cov_track_name <- function(track, pat_len) { qqv('@{track}.pat@{pat_len}') }
.gpatterns.frag_cov_track_name <- function(track) { qqv('@{track}.frag_cov')}
.gpatterns.fid_track_name <- function(track) { qqv('@{track}.fid')}
.gpatterns.ncpg_track_name <- function(track) { qqv('@{track}.ncpg')}
.gpatterns.n_track_name <- function(track) { qqv('@{track}.n')}
.gpatterns.n0_track_name <- function(track) { qqv('@{track}.n0')}
.gpatterns.n1_track_name <- function(track) { qqv('@{track}.n1')}
.gpatterns.nx_track_name <- function(track) { qqv('@{track}.nx')}
.gpatterns.nc_track_name <- function(track) { qqv('@{track}.nc')}
.gpatterns.pat_meth_track_name <- function(track) { qqv('@{track}.pat_meth')}
.gpatterns.pat_space_intervs_name <- function(track) { qqv('@{track}.pat_space')}
.gpatterns.epipolymorphism_track_name <- function(track) { qqv('@{track}.epipoly')}
.gpatterns.patterns_track_names <- function(track) {paste0(track, '.', c('n', 'n0', 'n1', 'nx', 'nc', 'pat_meth', 'epipoly', 'fid'))}
.gpatterns.mix_qval_track_name <- function(track) { qqv('@{track}.mix_qval')}
.gpatterns.mix_meth_track_name <- function(track) { qqv('@{track}.mix_meth')}
.gpatterns.mix_unmeth_track_name <- function(track) { qqv('@{track}.mix_unmeth')}
.gpatterns.gain_meth_track_name <- function(track) { qqv('@{track}.gain_meth')}
.gpatterns.gain_unmeth_track_name <- function(track) { qqv('@{track}.gain_unmeth')}
.gpatterns.loss_meth_track_name <- function(track) { qqv('@{track}.loss_meth')}
.gpatterns.loss_unmeth_track_name <- function(track) { qqv('@{track}.loss_unmeth')}
.gpatterns.center_meth_track_name <- function(track) { qqv('@{track}.center_meth_ones')}
.gpatterns.center_unmeth_track_name <- function(track) { qqv('@{track}.center_unmeth_ones')}
.gpatterns.center_uni_track_name <- function(track) { qqv('@{track}.center_uni_ones')}
.gpatterns.gain_uni_track_name <- function(track) { qqv('@{track}.gain_uni')}
.gpatterns.loss_uni_track_name <- function(track) { qqv('@{track}.loss_uni')}
.gpatterns.patterns_tab_name <- function(track) { 'patterns'}
.gpatterns.patterns_file_name <- function(track) { file.path(.gpatterns.base_dir(track), 'patterns.RData')}
.gpatterns.fids_tab_name <- function(track) { 'fids' }
.gpatterns.fids_file_name <- function(track) { file.path(.gpatterns.base_dir(track), 'fids.RData') }
.gpatterns.stats_file_name <- function(track) { qq('@{.gpatterns.base_dir(track)}/stats.tsv') }
.gpatterns.tidy_cpgs_files <- function(track) {
list.files(paste0(.gpatterns.base_dir(track), '/tidy_cpgs'), full.names=TRUE, pattern='tcpgs.gz')
}
.gpatterns.tidy_cpgs_dir <- function(track){
paste0(.gpatterns.base_dir(track), '/tidy_cpgs')
}
.gpatterns.bipolar_model_tab_name <- function(track) { 'mix' }
.gpatterns.bipolar_model_file_name <- function(track) {
file.path(.gpatterns.base_dir(track), 'bipolar.RData')
}
.gpatterns.bipolar_model_stats <- c('qval', 'mix.meth', 'mix.unmeth', 'center.meth', 'center.meth.ones', 'gain.meth', 'loss.meth', 'center.unmeth', 'center.unmeth.ones','gain.unmeth', 'loss.unmeth', 'center.uni', 'center.uni.ones', 'gain.uni', 'loss.uni')
.gpatterns.genome_cpgs_track <- 'seq.CG'
.gpatterns.genome_cpgs_intervals <- 'intervs.global.seq_CG'
.gpatterns.genome_next_cpg_intervals <- 'intervs.global.next_CG'
.gpatterns.cg_cont_500_track <- 'seq.CG_500_mean'
.gpatterns.special_intervals <- function(name){
intervs_map <- list(tss = 'intervs.global.tss',
exon = 'intervs.global.exon',
utr3 = 'intervs.global.utr3',
intron = 'intervs.global.introns',
cgi = 'intervs.global.cgi_ucsc')
if (name %in% names(intervs_map)){
return(intervs_map[[name]])
} else {
stop(qq('interval @{name} does not exist'))
}
}
.gpatterns.get_intervals <- function(intervals){
if (is.character(intervals)){
if (!gintervals.exists(intervals)){
intervals <- .gpatterns.special_intervals(intervals)
}
}
return(intervals)
}
# Color palettes ------------------------------------------------
# .blue_red_pal <- colorRampPalette(c("#87FFFF", "black", "#FF413D"))(1000)
#' @export
.blue_red_pal <- colorRampPalette(c("#00688B", "white", "#FF413D"))(1000)
.blue_black_red_yellow_pal <- colorRampPalette(c("white", "blue", "black", "red", "yellow"))(1000)
.red_blue_pal <- rev(colorRampPalette(c("#87FFFF", "black", "#FF413D"))(1000))
.blue_red_yellow_pal <- colorRampPalette(c("white", "blue", "red", "yellow"))(1000)
.smooth_scatter_pal2 <- colorRampPalette(c("white", "white", "deepskyblue4", "gray",
"darkgray", "black", "brown"))
.smooth_scatter_pal <- colorRampPalette(c("white", "white", "darkgrey", "black",
"#FF413D", "yellow"))
.smooth_scatter_pal3 <- colorRampPalette(c("white", "blue", "red", "yellow", "black"))
|
#####################################################################
### Some stuffs that have to be somewhere
### Arthur Allignol <arthur.allignol@uni-ulm.de>
#####################################################################
utils::globalVariables(c("entry",
"exit",
"from",
"to",
"id",
"idd",
"masque",
"entree",
"Haz",
"time",
"V1",
"dhaz"),
package = "etm")
| /fuzzedpackages/etm/R/zzz.R | no_license | akhikolla/testpackages | R | false | false | 714 | r | #####################################################################
### Some stuffs that have to be somewhere
### Arthur Allignol <arthur.allignol@uni-ulm.de>
#####################################################################
utils::globalVariables(c("entry",
"exit",
"from",
"to",
"id",
"idd",
"masque",
"entree",
"Haz",
"time",
"V1",
"dhaz"),
package = "etm")
|
#' gammaCK2par
#'
#' Field comparisons for string variables. Two possible agreement patterns are considered:
#' 0 total disagreement, 2 agreement.
#' The distance between strings is calculated using a Jaro-Winkler distance.
#'
#' @usage gammaCK2par(matAp, matBp, n.cores, cut.a, method, w)
#'
#' @param matAp vector storing the comparison field in data set 1
#' @param matBp vector storing the comparison field in data set 2
#' @param n.cores Number of cores to parallelize over. Default is NULL.
#' @param cut.a Lower bound for full match, ranging between 0 and 1. Default is 0.92
#' @param method String distance method, options are: "jw" Jaro-Winkler (Default), "jaro" Jaro, and "lv" Edit
#' @param w Parameter that describes the importance of the first characters of a string (only needed if method = "jw"). Default is .10
#'
#' @return \code{gammaCK2par} returns a list with the indices corresponding to each
#' matching pattern, which can be fed directly into \code{tableCounts} and \code{matchesLink}.
#'
#' @author Ted Enamorado <ted.enamorado@gmail.com>, Ben Fifield <benfifield@gmail.com>, and Kosuke Imai
#'
#' @examples
#' \dontrun{
#' g1 <- gammaCK2par(dfA$firstname, dfB$lastname)
#' }
#' @export
## ------------------------
## gammaCK2par: Now it takes values 0, 2
## This function applies gamma.k
## in parallel
## ------------------------
gammaCK2par <- function(matAp, matBp, n.cores = NULL, cut.a = 0.92, method = "jw", w = .10) {
if(any(class(matAp) %in% c("tbl_df", "data.table"))){
matAp <- as.data.frame(matAp)[,1]
}
if(any(class(matBp) %in% c("tbl_df", "data.table"))){
matBp <- as.data.frame(matBp)[,1]
}
matAp[matAp == ""] <- NA
matBp[matBp == ""] <- NA
if(sum(is.na(matAp)) == length(matAp) | length(unique(matAp)) == 1){
cat("WARNING: You have no variation in this variable, or all observations are missing in dataset A.\n")
}
if(sum(is.na(matBp)) == length(matBp) | length(unique(matBp)) == 1){
cat("WARNING: You have no variation in this variable, or all observations are missing in dataset B.\n")
}
if(!(method %in% c("jw", "jaro", "lv"))){
stop("Invalid string distance method. Method should be one of 'jw', 'jaro', or 'lv'.")
}
if(method == "jw" & !is.null(w)){
if(w < 0 | w > 0.25){
stop("Invalid value provided for w. Remember, w in [0, 0.25].")
}
}
if(is.null(n.cores)) {
n.cores <- detectCores() - 1
}
matrix.1 <- as.matrix(as.character(matAp))
matrix.2 <- as.matrix(as.character(matBp))
matrix.1[is.na(matrix.1)] <- "1234MF"
matrix.2[is.na(matrix.2)] <- "9876ES"
u.values.1 <- unique(matrix.1)
u.values.2 <- unique(matrix.2)
n.slices1 <- max(round(length(u.values.1)/(4500), 0), 1)
n.slices2 <- max(round(length(u.values.2)/(4500), 0), 1)
limit.1 <- round(quantile((0:nrow(u.values.2)), p = seq(0, 1, 1/n.slices2)), 0)
limit.2 <- round(quantile((0:nrow(u.values.1)), p = seq(0, 1, 1/n.slices1)), 0)
temp.1 <- temp.2 <- list()
n.cores <- min(n.cores, n.slices1 * n.slices2)
for(i in 1:n.slices2) {
temp.1[[i]] <- list(u.values.2[(limit.1[i]+1):limit.1[i+1]], limit.1[i])
}
for(i in 1:n.slices1) {
temp.2[[i]] <- list(u.values.1[(limit.2[i]+1):limit.2[i+1]], limit.2[i])
}
stringvec <- function(m, y, cut, strdist = method, p1 = w) {
x <- as.matrix(m[[1]])
e <- as.matrix(y[[1]])
if(strdist == "jw") {
t <- 1 - stringdistmatrix(e, x, method = "jw", p = p1, nthread = 1)
t[ t < cut ] <- 0
t <- Matrix(t, sparse = T)
}
if(strdist == "jaro") {
t <- 1 - stringdistmatrix(e, x, method = "jw", nthread = 1)
t[ t < cut ] <- 0
t <- Matrix(t, sparse = T)
}
if(strdist == "lv") {
t <- stringdistmatrix(e, x, method = method, nthread = 1)
t.1 <- nchar(as.matrix(e))
t.2 <- nchar(as.matrix(x))
o <- t(apply(t.1, 1, function(w){ ifelse(w >= t.2, w, t.2)}))
t <- 1 - t * (1/o)
t[ t < cut ] <- 0
t <- Matrix(t, sparse = T)
}
t@x[t@x >= cut] <- 2; gc()
slice.1 <- m[[2]]
slice.2 <- y[[2]]
indexes.2 <- which(t == 2, arr.ind = T)
indexes.2[, 1] <- indexes.2[, 1] + slice.2
indexes.2[, 2] <- indexes.2[, 2] + slice.1
list(indexes.2)
}
do <- expand.grid(1:n.slices2, 1:n.slices1)
if (n.cores == 1) '%oper%' <- foreach::'%do%'
else {
'%oper%' <- foreach::'%dopar%'
cl <- makeCluster(n.cores)
registerDoParallel(cl)
on.exit(stopCluster(cl))
}
temp.f <- foreach(i = 1:nrow(do), .packages = c("stringdist", "Matrix")) %oper% {
r1 <- do[i, 1]
r2 <- do[i, 2]
stringvec(temp.1[[r1]], temp.2[[r2]], cut.a)
}
gc()
reshape2 <- function(s) { s[[1]] }
temp.2 <- lapply(temp.f, reshape2)
indexes.2 <- do.call('rbind', temp.2)
ht1 <- new.env(hash=TRUE)
ht2 <- new.env(hash=TRUE)
n.values.2 <- as.matrix(cbind(u.values.1[indexes.2[, 1]], u.values.2[indexes.2[, 2]]))
if(sum(n.values.2 == "1234MF") > 0) {
t1 <- which(n.values.2 == "1234MF", arr.ind = T)[1]
n.values.2 <- n.values.2[-t1, ]; rm(t1)
}
if(sum(n.values.2 == "9876ES") > 0) {
t1 <- which(n.values.2 == "9876ES", arr.ind = T)[1]
n.values.2 <- n.values.2[-t1, ]; rm(t1)
}
matches.2 <- lapply(seq_len(nrow(n.values.2)), function(i) n.values.2[i, ])
if(Sys.info()[['sysname']] == 'Windows') {
if (n.cores == 1) '%oper%' <- foreach::'%do%'
else {
'%oper%' <- foreach::'%dopar%'
cl <- makeCluster(n.cores)
registerDoParallel(cl)
on.exit(stopCluster(cl))
}
if(length(matches.2) > 0) {
final.list2 <- foreach(i = 1:length(matches.2)) %oper% {
ht1 <- which(matrix.1 == matches.2[[i]][[1]]); ht2 <- which(matrix.2 == matches.2[[i]][[2]])
list(ht1, ht2)
}
}
} else {
no_cores <- n.cores
final.list2 <- mclapply(matches.2, function(s){
ht1 <- which(matrix.1 == s[1]); ht2 <- which(matrix.2 == s[2]);
list(ht1, ht2) }, mc.cores = getOption("mc.cores", no_cores))
}
if(length(matches.2) == 0){
final.list2 <- list()
warning("There are no identical (or nearly identical) matches. We suggest either changing the value of cut.p")
}
na.list <- list()
na.list[[1]] <- which(matrix.1 == "1234MF")
na.list[[2]] <- which(matrix.2 == "9876ES")
out <- list()
out[["matches2"]] <- final.list2
out[["nas"]] <- na.list
class(out) <- c("fastLink", "gammaCK2par")
return(out)
}
## ------------------------
## End of gammaCK2par
## ------------------------
| /fastLink/R/gammaCK2par.R | no_license | akhikolla/TestedPackages-NoIssues | R | false | false | 7,002 | r | #' gammaCK2par
#'
#' Field comparisons for string variables. Two possible agreement patterns are considered:
#' 0 total disagreement, 2 agreement.
#' The distance between strings is calculated using a Jaro-Winkler distance.
#'
#' @usage gammaCK2par(matAp, matBp, n.cores, cut.a, method, w)
#'
#' @param matAp vector storing the comparison field in data set 1
#' @param matBp vector storing the comparison field in data set 2
#' @param n.cores Number of cores to parallelize over. Default is NULL.
#' @param cut.a Lower bound for full match, ranging between 0 and 1. Default is 0.92
#' @param method String distance method, options are: "jw" Jaro-Winkler (Default), "jaro" Jaro, and "lv" Edit
#' @param w Parameter that describes the importance of the first characters of a string (only needed if method = "jw"). Default is .10
#'
#' @return \code{gammaCK2par} returns a list with the indices corresponding to each
#' matching pattern, which can be fed directly into \code{tableCounts} and \code{matchesLink}.
#'
#' @author Ted Enamorado <ted.enamorado@gmail.com>, Ben Fifield <benfifield@gmail.com>, and Kosuke Imai
#'
#' @examples
#' \dontrun{
#' g1 <- gammaCK2par(dfA$firstname, dfB$lastname)
#' }
#' @export
## ------------------------
## gammaCK2par: Now it takes values 0, 2
## This function applies gamma.k
## in parallel
## ------------------------
gammaCK2par <- function(matAp, matBp, n.cores = NULL, cut.a = 0.92, method = "jw", w = .10) {
if(any(class(matAp) %in% c("tbl_df", "data.table"))){
matAp <- as.data.frame(matAp)[,1]
}
if(any(class(matBp) %in% c("tbl_df", "data.table"))){
matBp <- as.data.frame(matBp)[,1]
}
matAp[matAp == ""] <- NA
matBp[matBp == ""] <- NA
if(sum(is.na(matAp)) == length(matAp) | length(unique(matAp)) == 1){
cat("WARNING: You have no variation in this variable, or all observations are missing in dataset A.\n")
}
if(sum(is.na(matBp)) == length(matBp) | length(unique(matBp)) == 1){
cat("WARNING: You have no variation in this variable, or all observations are missing in dataset B.\n")
}
if(!(method %in% c("jw", "jaro", "lv"))){
stop("Invalid string distance method. Method should be one of 'jw', 'jaro', or 'lv'.")
}
if(method == "jw" & !is.null(w)){
if(w < 0 | w > 0.25){
stop("Invalid value provided for w. Remember, w in [0, 0.25].")
}
}
if(is.null(n.cores)) {
n.cores <- detectCores() - 1
}
matrix.1 <- as.matrix(as.character(matAp))
matrix.2 <- as.matrix(as.character(matBp))
matrix.1[is.na(matrix.1)] <- "1234MF"
matrix.2[is.na(matrix.2)] <- "9876ES"
u.values.1 <- unique(matrix.1)
u.values.2 <- unique(matrix.2)
n.slices1 <- max(round(length(u.values.1)/(4500), 0), 1)
n.slices2 <- max(round(length(u.values.2)/(4500), 0), 1)
limit.1 <- round(quantile((0:nrow(u.values.2)), p = seq(0, 1, 1/n.slices2)), 0)
limit.2 <- round(quantile((0:nrow(u.values.1)), p = seq(0, 1, 1/n.slices1)), 0)
temp.1 <- temp.2 <- list()
n.cores <- min(n.cores, n.slices1 * n.slices2)
for(i in 1:n.slices2) {
temp.1[[i]] <- list(u.values.2[(limit.1[i]+1):limit.1[i+1]], limit.1[i])
}
for(i in 1:n.slices1) {
temp.2[[i]] <- list(u.values.1[(limit.2[i]+1):limit.2[i+1]], limit.2[i])
}
stringvec <- function(m, y, cut, strdist = method, p1 = w) {
x <- as.matrix(m[[1]])
e <- as.matrix(y[[1]])
if(strdist == "jw") {
t <- 1 - stringdistmatrix(e, x, method = "jw", p = p1, nthread = 1)
t[ t < cut ] <- 0
t <- Matrix(t, sparse = T)
}
if(strdist == "jaro") {
t <- 1 - stringdistmatrix(e, x, method = "jw", nthread = 1)
t[ t < cut ] <- 0
t <- Matrix(t, sparse = T)
}
if(strdist == "lv") {
t <- stringdistmatrix(e, x, method = method, nthread = 1)
t.1 <- nchar(as.matrix(e))
t.2 <- nchar(as.matrix(x))
o <- t(apply(t.1, 1, function(w){ ifelse(w >= t.2, w, t.2)}))
t <- 1 - t * (1/o)
t[ t < cut ] <- 0
t <- Matrix(t, sparse = T)
}
t@x[t@x >= cut] <- 2; gc()
slice.1 <- m[[2]]
slice.2 <- y[[2]]
indexes.2 <- which(t == 2, arr.ind = T)
indexes.2[, 1] <- indexes.2[, 1] + slice.2
indexes.2[, 2] <- indexes.2[, 2] + slice.1
list(indexes.2)
}
do <- expand.grid(1:n.slices2, 1:n.slices1)
if (n.cores == 1) '%oper%' <- foreach::'%do%'
else {
'%oper%' <- foreach::'%dopar%'
cl <- makeCluster(n.cores)
registerDoParallel(cl)
on.exit(stopCluster(cl))
}
temp.f <- foreach(i = 1:nrow(do), .packages = c("stringdist", "Matrix")) %oper% {
r1 <- do[i, 1]
r2 <- do[i, 2]
stringvec(temp.1[[r1]], temp.2[[r2]], cut.a)
}
gc()
reshape2 <- function(s) { s[[1]] }
temp.2 <- lapply(temp.f, reshape2)
indexes.2 <- do.call('rbind', temp.2)
ht1 <- new.env(hash=TRUE)
ht2 <- new.env(hash=TRUE)
n.values.2 <- as.matrix(cbind(u.values.1[indexes.2[, 1]], u.values.2[indexes.2[, 2]]))
if(sum(n.values.2 == "1234MF") > 0) {
t1 <- which(n.values.2 == "1234MF", arr.ind = T)[1]
n.values.2 <- n.values.2[-t1, ]; rm(t1)
}
if(sum(n.values.2 == "9876ES") > 0) {
t1 <- which(n.values.2 == "9876ES", arr.ind = T)[1]
n.values.2 <- n.values.2[-t1, ]; rm(t1)
}
matches.2 <- lapply(seq_len(nrow(n.values.2)), function(i) n.values.2[i, ])
if(Sys.info()[['sysname']] == 'Windows') {
if (n.cores == 1) '%oper%' <- foreach::'%do%'
else {
'%oper%' <- foreach::'%dopar%'
cl <- makeCluster(n.cores)
registerDoParallel(cl)
on.exit(stopCluster(cl))
}
if(length(matches.2) > 0) {
final.list2 <- foreach(i = 1:length(matches.2)) %oper% {
ht1 <- which(matrix.1 == matches.2[[i]][[1]]); ht2 <- which(matrix.2 == matches.2[[i]][[2]])
list(ht1, ht2)
}
}
} else {
no_cores <- n.cores
final.list2 <- mclapply(matches.2, function(s){
ht1 <- which(matrix.1 == s[1]); ht2 <- which(matrix.2 == s[2]);
list(ht1, ht2) }, mc.cores = getOption("mc.cores", no_cores))
}
if(length(matches.2) == 0){
final.list2 <- list()
warning("There are no identical (or nearly identical) matches. We suggest either changing the value of cut.p")
}
na.list <- list()
na.list[[1]] <- which(matrix.1 == "1234MF")
na.list[[2]] <- which(matrix.2 == "9876ES")
out <- list()
out[["matches2"]] <- final.list2
out[["nas"]] <- na.list
class(out) <- c("fastLink", "gammaCK2par")
return(out)
}
## ------------------------
## End of gammaCK2par
## ------------------------
|
#' Prettifies the table returned by population stats for the pipeline
#'
#' This function updates the rownames to retain only the number of nodes
#' specified. For example, suppose the full path to the node is
#' /singlet/viable/Lymph/CD3/CD8/IFNg. By default, this is updated to IFNg.
#' If instead we specify \code{nodes = 2}, then the corresponding row is
#' CD8/IFNg.
#'
#' @param population_stats a data frame containing the population summaries,
#' which is returned from the \code{getPopStats} function in the
#' \code{flowWorkspace} package.
#' @param nodes numeric. How many nodes should be preserved in the prettified
#' population statistics data frame returned? Default: 1
#' @return a data frame containing the population statistics but with prettified
#' row names
pretty_popstats <- function(popstats) {
# Remove all population statistics for the following markers
markers_remove <- c("root", "burnin", "boundary", "debris", "cd8gate_neg",
"cd8gate_pos", "cd4-", "cd4+", "singlet", "viable", "lymph")
popstats_remove <- sapply(strsplit(rownames(popstats), "/"), tail, n = 1)
popstats_remove <- popstats_remove %in% markers_remove
popstats <- popstats[!popstats_remove, ]
rownames_popstats <- rownames(popstats)
# Updates any markers with a tolerance value to something easier to parse.
# Example: "cd4:TNFa_tol1&cd4:IFNg_tol1&cd4:IL2_tol1" => "cd4:TNFa&cd4:IFNg&cd4:IL2_1e-1"
which_tol <- grep("tol", rownames_popstats)
tol_append <- sapply(strsplit(rownames_popstats[which_tol], "_tol"), tail, n = 1)
rownames_popstats[which_tol] <- gsub("_tol.", "", rownames_popstats[which_tol])
rownames_popstats[which_tol] <- paste(rownames_popstats[which_tol], tol_append, sep = "_1e-")
# Updates all cytokine combinations having the name of the form 'cd4/TNFa' to
# 'TNFa'
which_combo <- grep("[&|]", rownames_popstats)
rownames_combo <- rownames_popstats[which_combo]
rownames_combo <- gsub("cd[48]:TNFa", "TNFa", rownames_combo)
rownames_combo <- gsub("cd[48]:IFNg", "IFNg", rownames_combo)
rownames_combo <- gsub("cd[48]:IL2", "IL2", rownames_combo)
rownames_popstats[which_combo] <- rownames_combo
# Updates all cytokines gates to the form 'cd4:TNFa'
which_cytokines <- grep("TNFa|IFNg|IL2", rownames_popstats)
rownames_cytokines <- rownames_popstats[which_cytokines]
rownames_cytokines <- sapply(strsplit(rownames_cytokines, "cd3/"), tail, n = 1)
rownames_cytokines <- gsub("/", ":", rownames_cytokines)
rownames_popstats[which_cytokines] <- rownames_cytokines
# Retains the last marker name for all non-cytokine gates
rownames_noncytokines <- rownames_popstats[-which_cytokines]
rownames_noncytokines <- sapply(strsplit(rownames_noncytokines, "/"), tail, n = 1)
rownames_popstats[-which_cytokines] <- rownames_noncytokines
# Reformats cytokine-marker combinations: !TNFa&IFNg&IL2 => TNFa-IFNg+IL2+
rownames_popstats <- gsub("TNFa", "TNFa+", rownames_popstats)
rownames_popstats <- gsub("!TNFa\\+", "TNFa-", rownames_popstats)
rownames_popstats <- gsub("IFNg", "IFNg+", rownames_popstats)
rownames_popstats <- gsub("!IFNg\\+", "IFNg-", rownames_popstats)
rownames_popstats <- gsub("IL2", "IL2+", rownames_popstats)
rownames_popstats <- gsub("!IL2\\+", "IL2-", rownames_popstats)
rownames_popstats <- gsub("&", "", rownames_popstats)
# Updates popstats rownames
rownames(popstats) <- rownames_popstats
popstats
}
#' Removes commas from a numeric stored as a string.
#'
#' In the summary for the HVTN065 manual gates, the cellular population counts
#' are stored as character strings with commas denoting the thousands place. For
#' instance, 3000 is stored as "3,000". We remove the commas from the strings
#' and convert to the resulting string to a numeric.
#'
#' @param x character string with the nuisance commas
#' @return the updated numeric value
no_commas <- function(x) {
as.numeric(gsub(",", "", x))
}
#' Constructs a vector of all the combinations of A & B & C
#'
#' The \code{permutations} function is from the \code{gtools} package on CRAN.
#' @param markers character vector of marker names
#' @return vector containing all combinations of the markers
#' @examples
#' polyfunction_nodes(c("IFNg", "IL2", "TNFa", "GzB", "CD57"))
polyfunction_nodes <- function(markers) {
num_markers <- length(markers)
plusminus_list <- permutations(n = 2, r = num_markers, c("+", "-"),
repeats = TRUE)
apply(plusminus_list, 1, function(plusminus_row) {
paste0(markers, plusminus_row, collapse = "")
})
}
#' Prepare manual gates population statistics data for classification study
#'
#'
#' @param popstats a data.frame containing population statistics derived from
#' manual gates
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @return list containing the various data to use in a classification study
prepare_manual <- function(popstats, treatment_info, pdata,
stimulation = "GAG-1-PTEG", train_pct = 0.6) {
# Next, we include only the negative controls and the specified stimulation group.
popstats <- subset(popstats, Stimulation %in% c("negctrl", stimulation))
popstats$Stimulation <- factor(as.character(popstats$Stimulation), labels = c(stimulation, "negctrl"))
popstats$PTID <- factor(popstats$PTID)
popstats$VISITNO <- factor(popstats$VISITNO)
m_popstats <- reshape2:::melt.data.frame(popstats, variable.name = "Marker",
value.name = "Proportion")
# Here, we summarize the population statistics within Stimulation group.
# Effectively, this averages the two negative-control proportions for each
# marker.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Stimulation, Marker),
summarize, Proportion = mean(Proportion))
# Next, we normalize the population proportions for the stimulated samples to
# adjust for the background (negative controls) by calculating the difference of
# the proportions for the stimulated samples and the negative controls.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Marker), summarize,
diff_Proportion = diff(Proportion))
# Converts the melted data.frame to a wider format to continue the classification study.
m_popstats <- dcast(m_popstats, PTID + VISITNO ~ Marker, value.var = "diff_Proportion")
m_popstats <- plyr:::join(m_popstats, treatment_info)
m_popstats$VISITNO <- factor(m_popstats$VISITNO, labels = c("2", "12"))
placebo_data <- subset(m_popstats, Treatment == "Placebo", select = -Treatment)
treatment_data <- subset(m_popstats, Treatment == "Treatment", select = -Treatment)
# Partitions GAG data for classification study
treated_patients <- unique(treatment_data$PTID)
num_treated_patients <- length(treated_patients)
patients_train <- sample.int(num_treated_patients, train_pct * num_treated_patients)
train_data <- subset(treatment_data, PTID %in% treated_patients[patients_train])
test_data <- subset(treatment_data, PTID %in% treated_patients[-patients_train])
list(train_data = train_data, test_data = test_data, placebo_data = placebo_data)
}
#' Prepare population statistics data for classification study
#'
#'
#' @param popstats a data.frame containing population statistics from
#' \code{getPopStats}
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param other_features a data.frame of additional features to add. By default,
#' no additional features are used.
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @return list containing the various data to use in a classification study
prepare_classification <- function(popstats, treatment_info, pdata, other_features = NULL,
stimulation = "GAG-1-PTEG", train_pct = 0.6) {
m_popstats <- reshape2:::melt(popstats)
colnames(m_popstats) <- c("Marker", "Sample", "Value")
m_popstats$Marker <- as.character(m_popstats$Marker)
m_popstats$Sample <- as.character(m_popstats$Sample)
if (!is.null(other_features)) {
m_popstats <- rbind(m_popstats, other_features)
}
m_popstats <- plyr:::join(m_popstats, pdata, by = "Sample")
m_popstats$VISITNO <- factor(m_popstats$VISITNO)
m_popstats$PTID <- factor(m_popstats$PTID)
# We stored the 'negctrl' with sample numbers appended to the strings so that
# plotGate could identify unique samples. Here, we strip the sample numbers to
# summarize the negative controls as a whole.
m_popstats$Stimulation <- as.character(m_popstats$Stimulation)
m_popstats$Stimulation <- replace(m_popstats$Stimulation,
grep("^negctrl", m_popstats$Stimulation), "negctrl")
# Next, we include only the negative controls and the specified stimulation groups.
m_popstats <- subset(m_popstats, Stimulation %in% c("negctrl", stimulation))
m_popstats$Stimulation <- factor(m_popstats$Stimulation, labels = c(stimulation, "negctrl"))
# Here, we summarize the population statistics within Stimulation group.
# Effectively, this averages the two negative-control proportions for each
# marker.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Stimulation, Marker),
summarize, Value = mean(Value))
# Next, we normalize the population proportions for the stimulated samples to
# adjust for the background (negative controls) by calculating the difference of
# the proportions for the stimulated samples and the negative controls.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Marker), summarize,
diff_Value = diff(Value))
# Converts the melted data.frame to a wider format to continue the classification study.
m_popstats <- dcast(m_popstats, PTID + VISITNO ~ Marker, value.var = "diff_Value")
m_popstats <- plyr:::join(m_popstats, treatment_info)
m_popstats$PTID <- as.character(m_popstats$PTID)
placebo_data <- subset(m_popstats, Treatment == "Placebo", select = -Treatment)
treatment_data <- subset(m_popstats, Treatment == "Treatment", select = -Treatment)
# Partitions GAG data for classification study
treated_patients <- unique(treatment_data$PTID)
num_treated_patients <- length(treated_patients)
patients_train <- sample.int(num_treated_patients, train_pct * num_treated_patients)
train_data <- subset(treatment_data, PTID %in% treated_patients[patients_train])
test_data <- subset(treatment_data, PTID %in% treated_patients[-patients_train])
list(train_data = train_data, test_data = test_data, placebo_data = placebo_data)
}
#' Classification summary for population statistics
#'
#' For a data.frame of population statistics, we conduct a classification summary
#' of the the stimulation groups using the given treatment information.
#'
#' Per Greg, we apply the following classification study:
#' 1. Remove placebos before subsetting treatment group train classifier.
#' 2. Predict placebos (should expect poor classification accuracy because there
#' should be no separation in the placebos)
#' 3. Predict test data set (should expect good results)
#'
#' Per Greg:
#' "We also want to do this paired, using the difference in classification
#' probabilities for two samples from the same subject. i.e.
#' d = Pr(sample 1 from subject 1 = post-vaccine) -
#' Pr(sample 2 from subject 1 = post-vaccine).
#' If d > threshold, then classify sample 1 as post-vaccine and sample 2 as
#' pre-vaccine, otherwise if d < threshold classify sample 1 as pre-vaccine and
#' sample 2 as post-vaccine, otherwise mark them as unclassifiable."
#'
#' Hence, we compute classification accuracies by pairing the visits by patient
#' and then computing the proportion of correctly classified patients. Otherwise,
#' we calculate the proportion of visits that are correctly classified.
#'
#' @param popstats a data.frame containing population statistics from
#' \code{getPopStats}
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @param prob_threshold a numeric value above which the difference in
#' classification probabilities for two samples from the same subject indicates
#' that the first sample is classified as post-vaccine. Ignored if \code{paired}
#' is \code{FALSE}. See details.
#' @param other_features a data.frame of additional features to add. By default,
#' no additional features are used. Passed to \code{\link{prepare_classification}}.
#' @param ... Additional arguments passed to \code{\link{glmnet}}.
#' @return list containing classification results
classification_summary <- function(popstats, treatment_info, pdata,
stimulation = "GAG-1-PTEG", train_pct = 0.6,
prob_threshold = 0, other_features = NULL, ...) {
classif_data <- prepare_classification(popstats = popstats,
treatment_info = treatment_info, pdata = pdata,
other_features = other_features,
stimulation = stimulation, train_pct = train_pct)
train_data <- classif_data$train_data
test_data <- classif_data$test_data
placebo_data <- classif_data$placebo_data
train_x <- as.matrix(subset(train_data, select = -c(PTID, VISITNO)))
train_y <- train_data$VISITNO
test_x <- as.matrix(subset(test_data, select = -c(PTID, VISITNO)))
test_y <- test_data$VISITNO
placebo_x <- as.matrix(subset(placebo_data, select = -c(PTID, VISITNO)))
placebo_y <- placebo_data$VISITNO
# Trains the 'glmnet' classifier using cross-validation.
glmnet_cv <- cv.glmnet(x = train_x, y = train_y, family = "binomial", ...)
glmnet_fit <- glmnet(x = train_x, y = train_y, family = "binomial", ...)
# Computes classification accuracies in two different ways. If the visits are
# paired by patient, then we compute the proportion of correctly classified
# patients. Otherwise, we calculate the proportion of visits that are correctly
# classified.
predictions_treated <- as.vector(predict(glmnet_cv, test_x, s = "lambda.min",
type = "response"))
predictions_placebo <- as.vector(predict(glmnet_cv, placebo_x,
s = "lambda.min", type = "response"))
# If the difference in classification probabilities exceeds the probability
# threshold, we assign the first sample as visit 2 and the second as visit 12.
# Otherwise, we assign the first sample as visit 12 and the second as visit 2.
correct_patients <- tapply(seq_along(test_data$PTID), test_data$PTID, function(i) {
if (diff(predictions_treated[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == test_y[i])
})
correct_placebo <- tapply(seq_along(placebo_data$PTID), placebo_data$PTID, function(i) {
if (diff(predictions_placebo[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == placebo_y[i])
})
accuracy_treated <- mean(correct_patients)
accuracy_placebo <- mean(correct_placebo)
# Determines which features should be kept for classification
# If present, we manually remove the "(Intercept)"
# In the case that all markers are removed and only the intercept remains, we
# add the "(Intercept)" back, for clarity.
coef_glmnet <- coef(glmnet_fit, s = glmnet_cv$lambda.min)
markers_kept <- rownames(coef_glmnet)[as.vector(coef_glmnet) != 0]
markers_kept <- markers_kept[!grepl("(Intercept)", markers_kept)]
if (length(markers_kept) == 0) {
markers_kept <- "(Intercept)"
}
# We return the classification accuracies, the classification probabilities and
# markers kept using 'glmnet', the corresponding test data sets for further
# analysis (e.g., ROC curves), and the markers kept by 'glmnet'.
list(accuracy = list(treatment = accuracy_treated, placebo = accuracy_placebo),
classification_probs = list(treated = predictions_treated,
placebo = predictions_placebo),
markers = markers_kept, coef_glmnet = coef_glmnet,
test_data = list(treated = test_data, placebo = placebo_data))
}
#' Classification summary for population statistics using logistic regression
#'
#' For a data.frame of population statistics, we conduct a classification summary
#' of the the stimulation groups using the given treatment information.
#'
#' Per Greg, we apply the following classification study:
#' 1. Remove placebos before subsetting treatment group train classifier.
#' 2. Predict placebos (should expect poor classification accuracy because there
#' should be no separation in the placebos)
#' 3. Predict test data set (should expect good results)
#'
#' Per Greg:
#' "We also want to do this paired, using the difference in classification
#' probabilities for two samples from the same subject. i.e.
#' d = Pr(sample 1 from subject 1 = post-vaccine) -
#' Pr(sample 2 from subject 1 = post-vaccine).
#' If d > threshold, then classify sample 1 as post-vaccine and sample 2 as
#' pre-vaccine, otherwise if d < threshold classify sample 1 as pre-vaccine and
#' sample 2 as post-vaccine, otherwise mark them as unclassifiable."
#'
#' Hence, we compute classification accuracies by pairing the visits by patient
#' and then computing the proportion of correctly classified patients. Otherwise,
#' we calculate the proportion of visits that are correctly classified.
#'
#' @param popstats a data.frame containing population statistics from
#' \code{getPopStats}
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @param prob_threshold a numeric value above which the difference in
#' classification probabilities for two samples from the same subject indicates
#' that the first sample is classified as post-vaccine. Ignored if \code{paired}
#' is \code{FALSE}. See details.
#' @param ... Additional arguments passed to \code{\link{glm}}.
#' @return list containing classification results
classification_summary_logistic <- function(popstats, treatment_info, pdata,
stimulation = "GAG-1-PTEG", train_pct = 0.6,
prob_threshold = 0, manual_gates = FALSE, ...) {
if (manual_gates) {
classif_data <- prepare_manual(popstats = popstats, treatment_info = treatment_info,
pdata = pdata, stimulation = stimulation, train_pct = train_pct)
} else {
classif_data <- prepare_classification(popstats = popstats,
treatment_info = treatment_info, pdata = pdata,
stimulation = stimulation, train_pct = train_pct)
}
train_data <- classif_data$train_data
test_data <- classif_data$test_data
placebo_data <- classif_data$placebo_data
train_data$PTID <- as.character(train_data$PTID)
test_data$PTID <- as.character(test_data$PTID)
placebo_data$PTID <- as.character(placebo_data$PTID)
train_x <- as.matrix(subset(train_data, select = -c(PTID, VISITNO)))
train_y <- train_data$VISITNO
test_x <- as.matrix(subset(test_data, select = -c(PTID, VISITNO)))
test_y <- test_data$VISITNO
placebo_x <- as.matrix(subset(placebo_data, select = -c(PTID, VISITNO)))
placebo_y <- placebo_data$VISITNO
# It is much easier to use 'glm' with data.frames. We oblige here.
# The Dude does oblige.
train_df <- data.frame(VISITNO = train_y, train_x, check.names = FALSE)
test_df <- data.frame(VISITNO = test_y, test_x, check.names = FALSE)
placebo_df <- data.frame(VISITNO = placebo_y, placebo_x, check.names = FALSE)
# Trains the 'glmnet' classifier using cross-validation.
glm_out <- glm(VISITNO ~ ., data = train_df, family = binomial(logit), ...)
# Computes classification accuracies in two different ways. If the visits are
# paired by patient, then we compute the proportion of correctly classified
# patients. Otherwise, we calculate the proportion of visits that are correctly
# classified.
predictions_treated <- as.vector(predict(glm_out, test_df, type = "response"))
predictions_placebo <- as.vector(predict(glm_out, placebo_df, type = "response"))
# If the difference in classification probabilities exceeds the probability
# threshold, we assign the first sample as visit 2 and the second as visit 12.
# Otherwise, we assign the first sample as visit 12 and the second as visit 2.
correct_patients <- tapply(seq_along(test_data$PTID), test_data$PTID, function(i) {
if (diff(predictions_treated[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == test_y[i])
})
correct_placebo <- tapply(seq_along(placebo_data$PTID), placebo_data$PTID, function(i) {
if (diff(predictions_placebo[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == placebo_y[i])
})
accuracy_treated <- mean(correct_patients)
accuracy_placebo <- mean(correct_placebo)
# Extracts the fitted coefficients for each feature
coef_glm <- coef(glm_out)
# We return the classification accuracies, the classification probabilities and
# markers kept using 'glmnet', the corresponding test data sets for further
# analysis (e.g., ROC curves), and the markers kept by 'glmnet'.
list(accuracy = list(treatment = accuracy_treated, placebo = accuracy_placebo),
classification_probs = list(treated = predictions_treated,
placebo = predictions_placebo),
coef_glm = coef_glm,
test_data = list(treated = test_data, placebo = placebo_data))
}
#' Scales a vector of data using the Huber robust estimator for mean and
#' standard deviation
#'
#' This function is an analog to \code{\link{scale}} but using Huber robust
#' estimators instead of the usual sample mean and standard deviation.
#'
#' @param x numeric vector
#' @param center logical value. Should \code{x} be centered?
#' @param scale logical value. Should \code{x} be scaled?
#' @return numeric vector containing the scaled data
scale_huber <- function(x, center = TRUE, scale = TRUE) {
x <- as.vector(x)
huber_x <- huber(x)
# If 'center' is set to TRUE, we center 'x' by the Huber robust location
# estimator.
center_x <- FALSE
if (center) {
center_x <- huber_x$mu
}
# If 'scale' is set to TRUE, we scale 'x' by the Huber robust standard
# deviation estimator.
scale_x <- FALSE
if (scale) {
scale_x <- huber_x$s
}
as.vector(base:::scale(x, center = center_x, scale = scale_x))
}
#' Centers a vector of data using the mode of the kernel density estimate
#'
#' @param x numeric vector
#' @param ... additional arguments passed to \code{\link{density}}
#' @return numeric vector containing the centered data
center_mode <- function(x, ...) {
x <- as.vector(x)
density_x <- density(x)
mode <- density_x$x[which.max(density_x$y)]
as.vector(scale(x, center = mode, scale = FALSE))
}
#' Extracts legend from ggplot2 object
#'
#' Code from Hadley Wickham:
#' https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
#'
#' @param a.gplot a \code{ggplot2} object
#' @return a \code{ggplot2} legend
g_legend <- function(a.gplot) {
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)
}
#' Look up channel name for cytokine
#'
#' @param x cytokine marker name
#' @return the corresponding channel name
cytokine2channel <- function(x) {
switch(x,
TNFa = "Alexa 680-A",
IFNg = "PE Cy7-A",
IL2 = "PE Green laser-A"
)
}
#' Standardizes a cytokine data with respect to a reference stimulation group
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' @param ref_stimulation reference stimulation group
#' @return data.frame with cytokine data standardized with respect to the
#' reference stimulation group
standardize_cytokines <- function(x) {
# Standardizes the cytokine samples within stimulation group with respect to
# the reference stimulation group.
# First, centers the values by the mode of the kernel density estimate for
# the stimulation group.
x <- tapply(x$value, x$Stim, center_mode)
# Scales the stimulation groups by their Huber estimator of the
# standard deviation to put all stimulations on the same scale.
x <- lapply(x, scale_huber, center = FALSE)
x <- melt(x)
colnames(x) <- c("value", "Stim")
x
}
#' Reads the specified cytokine from a gating set
#' @param gs gating set object
#' @param PTID patient ID
#' @param VISITNO patient visit number
#' @param tcells which T-cell type?
#' @param cytokine which cytokine?
#' @return a data.frame with the appropriate cytokine data
read_cytokines <- function(gs, PTID, VISITNO = c("2", "12"), tcells = c("cd4", "cd8"),
cytokine = c("TNFa", "IFNg", "IL2")) {
pData_gs <- pData(gs)
pData_gs <- pData_gs[pData_gs$PTID == PTID & pData_gs$VISITNO == VISITNO, ]
x <- lapply(seq_along(pData_gs$name), function(i) {
flow_set <- getData(gs[pData_gs$name[i]], tcells)
# In the case that 0 or 1 cells are present, we return NULL. The case of 1
# cell is ignored because a density cannot be estimated from it. In fact,
# density(...) throws an error in this case.
if (nrow(flow_set[[1]]) >= 2) {
cbind("Stim" = as.character(pData_gs$Stim[i]), "value" = exprs(flow_set[[1]])[, cytokine2channel(cytokine)])
} else {
NULL
}
})
x <- do.call(rbind, x)
x <- data.frame(x, stringsAsFactors = FALSE)
x$value <- as.numeric(x$value)
x
}
#' Constructs the kernel density estimates for each stimulation group for a
#' given set of cytokine data
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' @param ... additional arguments passed to \code{\link{density}}
#' @return data.frame with the cytokine densities for each stimulation group
density_cytokines <- function(x, ...) {
density_x <- tapply(x$value, x$Stim, density, ...)
density_x <- lapply(seq_along(density_x), function(i) {
cbind(Stim = names(density_x)[i], x = density_x[[i]]$x,
y = density_x[[i]]$y)
})
do.call(rbind, density_x)
}
#' Constructs the derivatives of the kernel density estimates for each
#' stimulation group for a given set of cytokine data
#'
#' For guidance on selecting the bandwidth, see this post:
#' http://stats.stackexchange.com/questions/33918/is-there-an-optimal-bandwidth-for-a-kernel-density-estimator-of-derivatives
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' @param adjust a numeric weight on the automatic bandwidth
#' @param collapse If \code{TRUE}, the values are collapsed from all stimulation
#' groups before estimating the derivative of the density function
#' @param ... additional arguments passed to \code{\link{density}}
#' @return data.frame with the cytokine densities for each stimulation group
deriv_cytokines <- function(x, deriv = 1, adjust = 1, collapse = FALSE) {
require('feature')
require('ks')
if (collapse) {
deriv_x <- drvkde(x = x$value, drv = deriv, bandwidth = adjust * hpi(x$value))
deriv_x <- cbind(x = deriv_x$x.grid[[1]], y = deriv_x$est)
} else {
deriv_x <- tapply(seq_along(x$Stim), x$Stim, function(i) {
drvkde(x = x$value[i], drv = deriv, bandwidth = adjust * hpi(x$value[i]))
})
deriv_x <- lapply(seq_along(deriv_x), function(i) {
cbind(Stim = names(deriv_x)[i], x = deriv_x[[i]]$x.grid[[1]],
y = deriv_x[[i]]$est)
})
deriv_x <- do.call(rbind, deriv_x)
}
deriv_x
}
#' Constructs a cutpoint by collapsing the values of a stimulation group and
#' using the first derivative of the kernel density estimate to establish a
#' cutpoint
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' groups before estimating the derivative of the density function
#' @param ... additional arguments passed to \code{\link{deriv_cytokine}}
#' @return the cutpoint along the x-axis
cytokine_cutpoint <- function(x, tol = 0.001, ...) {
deriv_out <- deriv_cytokines(x = x, deriv = 1, collapse = TRUE, ...)
x <- deriv_TNFa[, 1]
y <- deriv_TNFa[, 2]
lowest_valley <- x[which.min(y)]
cutpoint <- x[which(x > lowest_valley & abs(y) < tol)[1]]
cutpoint
}
#' Partitions the population statistics by tolerance values
#'
#' Partitions the population statistics into upstream and cytokines for each
#' processing below. The cytokine population statistics are stored in a named
#' list, where each element corresponds to a cytokine tolerance value.
#' The tolerance value is then stripped from the marker names.
#'
#' @param data.frame containing population statistics
#' @param tolerances a vector of the tolerance values
#' @return a list of data.frames, each of which is the data.frame of population
#' statistics for the current tolerance value.
partition_popstats <- function(popstats, tolerances) {
popstats <- lapply(tolerances, function(tol) {
popstats_tol <- popstats[grep(tol, rownames(popstats)), ]
rownames(popstats_tol) <- sapply(strsplit(rownames(popstats_tol), "_"), head, n = 1)
popstats_tol
})
names(popstats) <- tolerances
popstats
}
#' Summarizes paired classification study and generates ROC results
#'
#' @param results named list containing the results for each cytokine tolerance value
#' @param tolerances a vector of the tolerance values
#' @return data.frame with ROC results
ROC_summary <- function(results, tolerances) {
treated <- lapply(results, function(x) {
cbind(subset(x$test_data$treated, select = c(PTID, VISITNO)),
Truth = "Treatment",
Probability = x$classification_probs$treated)
})
placebo <- lapply(results, function(x) {
cbind(subset(x$test_data$placebo, select = c(PTID, VISITNO)),
Truth = "Placebo",
Probability = x$classification_probs$placebo)
})
probs <- lapply(tolerances, function(tol) {
cbind(Tolerance = tol, rbind(treated[[tol]], placebo[[tol]]))
})
probs <- do.call(rbind, probs)
# For each PTID, we compute the absolute value of the difference in
# classification probabilties for visits 2 and 12 and then order by the
# differences.
summary <- ddply(probs, .(Tolerance, PTID), summarize,
delta = 1 - abs(diff(Probability[VISITNO %in% c("2", "12")])),
Truth = unique(Truth))
summary <- summary[with(summary, order(Tolerance, delta, Truth, decreasing = FALSE)), ]
# Calculates true and false positive rates based on Treatment and Placebo
# samples, respectively. Because we are using Treatments and Placebos, we
# calculate TPRs and FPRs differently than usual. The basic idea is that when we
# add to the TPR each time we classify a patient as Treatment and to the FPR
# each time we classify a patient as Placebo. The ordering here is determined by
# the rank of the differences in classification probabilities.
ddply(summary, .(Tolerance), summarize,
FPR = cumsum(Truth == "Placebo") / sum(Truth == "Placebo"),
TPR = cumsum(Truth == "Treatment") / sum(Truth == "Treatment"))
}
#' Summarizes classification study and generates ROC results for manual gates
#'
#' @param results named list containing the results for each cytokine tolerance value
#' @return data.frame with ROC results
ROC_summary_manual <- function(results) {
treated <- cbind(subset(results$test_data$treated, select = c(PTID, VISITNO)),
Truth = "Treatment",
Probability = results$classification_probs$treated)
placebo <- cbind(subset(results$test_data$placebo, select = c(PTID, VISITNO)),
Truth = "Placebo",
Probability = results$classification_probs$placebo)
probs <- rbind(treated, placebo)
# For each PTID, we compute the absolute value of the difference in
# classification probabilties for visits 2 and 12 and then order by the
# differences.
summary <- ddply(probs, .(PTID), summarize,
delta = 1 - abs(diff(Probability[VISITNO %in% c("2", "12")])),
Truth = unique(Truth))
summary <- summary[with(summary, order(delta, Truth, decreasing = FALSE)), ]
# Calculates true and false positive rates based on Treatment and Placebo
# samples, respectively. Because we are using Treatments and Placebos, we
# calculate TPRs and FPRs differently than usual. The basic idea is that when we
# add to the TPR each time we classify a patient as Treatment and to the FPR
# each time we classify a patient as Placebo. The ordering here is determined by
# the rank of the differences in classification probabilities.
summarize(summary, FPR = cumsum(Truth == "Placebo") / sum(Truth == "Placebo"),
TPR = cumsum(Truth == "Treatment") / sum(Truth == "Treatment"))
}
| /lib/helpers.R | no_license | RGLab/paper-opencyto | R | false | false | 34,384 | r | #' Prettifies the table returned by population stats for the pipeline
#'
#' This function updates the rownames to retain only the number of nodes
#' specified. For example, suppose the full path to the node is
#' /singlet/viable/Lymph/CD3/CD8/IFNg. By default, this is updated to IFNg.
#' If instead we specify \code{nodes = 2}, then the corresponding row is
#' CD8/IFNg.
#'
#' @param population_stats a data frame containing the population summaries,
#' which is returned from the \code{getPopStats} function in the
#' \code{flowWorkspace} package.
#' @param nodes numeric. How many nodes should be preserved in the prettified
#' population statistics data frame returned? Default: 1
#' @return a data frame containing the population statistics but with prettified
#' row names
pretty_popstats <- function(popstats) {
# Remove all population statistics for the following markers
markers_remove <- c("root", "burnin", "boundary", "debris", "cd8gate_neg",
"cd8gate_pos", "cd4-", "cd4+", "singlet", "viable", "lymph")
popstats_remove <- sapply(strsplit(rownames(popstats), "/"), tail, n = 1)
popstats_remove <- popstats_remove %in% markers_remove
popstats <- popstats[!popstats_remove, ]
rownames_popstats <- rownames(popstats)
# Updates any markers with a tolerance value to something easier to parse.
# Example: "cd4:TNFa_tol1&cd4:IFNg_tol1&cd4:IL2_tol1" => "cd4:TNFa&cd4:IFNg&cd4:IL2_1e-1"
which_tol <- grep("tol", rownames_popstats)
tol_append <- sapply(strsplit(rownames_popstats[which_tol], "_tol"), tail, n = 1)
rownames_popstats[which_tol] <- gsub("_tol.", "", rownames_popstats[which_tol])
rownames_popstats[which_tol] <- paste(rownames_popstats[which_tol], tol_append, sep = "_1e-")
# Updates all cytokine combinations having the name of the form 'cd4/TNFa' to
# 'TNFa'
which_combo <- grep("[&|]", rownames_popstats)
rownames_combo <- rownames_popstats[which_combo]
rownames_combo <- gsub("cd[48]:TNFa", "TNFa", rownames_combo)
rownames_combo <- gsub("cd[48]:IFNg", "IFNg", rownames_combo)
rownames_combo <- gsub("cd[48]:IL2", "IL2", rownames_combo)
rownames_popstats[which_combo] <- rownames_combo
# Updates all cytokines gates to the form 'cd4:TNFa'
which_cytokines <- grep("TNFa|IFNg|IL2", rownames_popstats)
rownames_cytokines <- rownames_popstats[which_cytokines]
rownames_cytokines <- sapply(strsplit(rownames_cytokines, "cd3/"), tail, n = 1)
rownames_cytokines <- gsub("/", ":", rownames_cytokines)
rownames_popstats[which_cytokines] <- rownames_cytokines
# Retains the last marker name for all non-cytokine gates
rownames_noncytokines <- rownames_popstats[-which_cytokines]
rownames_noncytokines <- sapply(strsplit(rownames_noncytokines, "/"), tail, n = 1)
rownames_popstats[-which_cytokines] <- rownames_noncytokines
# Reformats cytokine-marker combinations: !TNFa&IFNg&IL2 => TNFa-IFNg+IL2+
rownames_popstats <- gsub("TNFa", "TNFa+", rownames_popstats)
rownames_popstats <- gsub("!TNFa\\+", "TNFa-", rownames_popstats)
rownames_popstats <- gsub("IFNg", "IFNg+", rownames_popstats)
rownames_popstats <- gsub("!IFNg\\+", "IFNg-", rownames_popstats)
rownames_popstats <- gsub("IL2", "IL2+", rownames_popstats)
rownames_popstats <- gsub("!IL2\\+", "IL2-", rownames_popstats)
rownames_popstats <- gsub("&", "", rownames_popstats)
# Updates popstats rownames
rownames(popstats) <- rownames_popstats
popstats
}
#' Removes commas from a numeric stored as a string.
#'
#' In the summary for the HVTN065 manual gates, the cellular population counts
#' are stored as character strings with commas denoting the thousands place. For
#' instance, 3000 is stored as "3,000". We remove the commas from the strings
#' and convert to the resulting string to a numeric.
#'
#' @param x character string with the nuisance commas
#' @return the updated numeric value
no_commas <- function(x) {
as.numeric(gsub(",", "", x))
}
#' Constructs a vector of all the combinations of A & B & C
#'
#' The \code{permutations} function is from the \code{gtools} package on CRAN.
#' @param markers character vector of marker names
#' @return vector containing all combinations of the markers
#' @examples
#' polyfunction_nodes(c("IFNg", "IL2", "TNFa", "GzB", "CD57"))
polyfunction_nodes <- function(markers) {
num_markers <- length(markers)
plusminus_list <- permutations(n = 2, r = num_markers, c("+", "-"),
repeats = TRUE)
apply(plusminus_list, 1, function(plusminus_row) {
paste0(markers, plusminus_row, collapse = "")
})
}
#' Prepare manual gates population statistics data for classification study
#'
#'
#' @param popstats a data.frame containing population statistics derived from
#' manual gates
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @return list containing the various data to use in a classification study
prepare_manual <- function(popstats, treatment_info, pdata,
stimulation = "GAG-1-PTEG", train_pct = 0.6) {
# Next, we include only the negative controls and the specified stimulation group.
popstats <- subset(popstats, Stimulation %in% c("negctrl", stimulation))
popstats$Stimulation <- factor(as.character(popstats$Stimulation), labels = c(stimulation, "negctrl"))
popstats$PTID <- factor(popstats$PTID)
popstats$VISITNO <- factor(popstats$VISITNO)
m_popstats <- reshape2:::melt.data.frame(popstats, variable.name = "Marker",
value.name = "Proportion")
# Here, we summarize the population statistics within Stimulation group.
# Effectively, this averages the two negative-control proportions for each
# marker.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Stimulation, Marker),
summarize, Proportion = mean(Proportion))
# Next, we normalize the population proportions for the stimulated samples to
# adjust for the background (negative controls) by calculating the difference of
# the proportions for the stimulated samples and the negative controls.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Marker), summarize,
diff_Proportion = diff(Proportion))
# Converts the melted data.frame to a wider format to continue the classification study.
m_popstats <- dcast(m_popstats, PTID + VISITNO ~ Marker, value.var = "diff_Proportion")
m_popstats <- plyr:::join(m_popstats, treatment_info)
m_popstats$VISITNO <- factor(m_popstats$VISITNO, labels = c("2", "12"))
placebo_data <- subset(m_popstats, Treatment == "Placebo", select = -Treatment)
treatment_data <- subset(m_popstats, Treatment == "Treatment", select = -Treatment)
# Partitions GAG data for classification study
treated_patients <- unique(treatment_data$PTID)
num_treated_patients <- length(treated_patients)
patients_train <- sample.int(num_treated_patients, train_pct * num_treated_patients)
train_data <- subset(treatment_data, PTID %in% treated_patients[patients_train])
test_data <- subset(treatment_data, PTID %in% treated_patients[-patients_train])
list(train_data = train_data, test_data = test_data, placebo_data = placebo_data)
}
#' Prepare population statistics data for classification study
#'
#'
#' @param popstats a data.frame containing population statistics from
#' \code{getPopStats}
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param other_features a data.frame of additional features to add. By default,
#' no additional features are used.
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @return list containing the various data to use in a classification study
prepare_classification <- function(popstats, treatment_info, pdata, other_features = NULL,
stimulation = "GAG-1-PTEG", train_pct = 0.6) {
m_popstats <- reshape2:::melt(popstats)
colnames(m_popstats) <- c("Marker", "Sample", "Value")
m_popstats$Marker <- as.character(m_popstats$Marker)
m_popstats$Sample <- as.character(m_popstats$Sample)
if (!is.null(other_features)) {
m_popstats <- rbind(m_popstats, other_features)
}
m_popstats <- plyr:::join(m_popstats, pdata, by = "Sample")
m_popstats$VISITNO <- factor(m_popstats$VISITNO)
m_popstats$PTID <- factor(m_popstats$PTID)
# We stored the 'negctrl' with sample numbers appended to the strings so that
# plotGate could identify unique samples. Here, we strip the sample numbers to
# summarize the negative controls as a whole.
m_popstats$Stimulation <- as.character(m_popstats$Stimulation)
m_popstats$Stimulation <- replace(m_popstats$Stimulation,
grep("^negctrl", m_popstats$Stimulation), "negctrl")
# Next, we include only the negative controls and the specified stimulation groups.
m_popstats <- subset(m_popstats, Stimulation %in% c("negctrl", stimulation))
m_popstats$Stimulation <- factor(m_popstats$Stimulation, labels = c(stimulation, "negctrl"))
# Here, we summarize the population statistics within Stimulation group.
# Effectively, this averages the two negative-control proportions for each
# marker.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Stimulation, Marker),
summarize, Value = mean(Value))
# Next, we normalize the population proportions for the stimulated samples to
# adjust for the background (negative controls) by calculating the difference of
# the proportions for the stimulated samples and the negative controls.
m_popstats <- ddply(m_popstats, .(PTID, VISITNO, Marker), summarize,
diff_Value = diff(Value))
# Converts the melted data.frame to a wider format to continue the classification study.
m_popstats <- dcast(m_popstats, PTID + VISITNO ~ Marker, value.var = "diff_Value")
m_popstats <- plyr:::join(m_popstats, treatment_info)
m_popstats$PTID <- as.character(m_popstats$PTID)
placebo_data <- subset(m_popstats, Treatment == "Placebo", select = -Treatment)
treatment_data <- subset(m_popstats, Treatment == "Treatment", select = -Treatment)
# Partitions GAG data for classification study
treated_patients <- unique(treatment_data$PTID)
num_treated_patients <- length(treated_patients)
patients_train <- sample.int(num_treated_patients, train_pct * num_treated_patients)
train_data <- subset(treatment_data, PTID %in% treated_patients[patients_train])
test_data <- subset(treatment_data, PTID %in% treated_patients[-patients_train])
list(train_data = train_data, test_data = test_data, placebo_data = placebo_data)
}
#' Classification summary for population statistics
#'
#' For a data.frame of population statistics, we conduct a classification summary
#' of the the stimulation groups using the given treatment information.
#'
#' Per Greg, we apply the following classification study:
#' 1. Remove placebos before subsetting treatment group train classifier.
#' 2. Predict placebos (should expect poor classification accuracy because there
#' should be no separation in the placebos)
#' 3. Predict test data set (should expect good results)
#'
#' Per Greg:
#' "We also want to do this paired, using the difference in classification
#' probabilities for two samples from the same subject. i.e.
#' d = Pr(sample 1 from subject 1 = post-vaccine) -
#' Pr(sample 2 from subject 1 = post-vaccine).
#' If d > threshold, then classify sample 1 as post-vaccine and sample 2 as
#' pre-vaccine, otherwise if d < threshold classify sample 1 as pre-vaccine and
#' sample 2 as post-vaccine, otherwise mark them as unclassifiable."
#'
#' Hence, we compute classification accuracies by pairing the visits by patient
#' and then computing the proportion of correctly classified patients. Otherwise,
#' we calculate the proportion of visits that are correctly classified.
#'
#' @param popstats a data.frame containing population statistics from
#' \code{getPopStats}
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @param prob_threshold a numeric value above which the difference in
#' classification probabilities for two samples from the same subject indicates
#' that the first sample is classified as post-vaccine. Ignored if \code{paired}
#' is \code{FALSE}. See details.
#' @param other_features a data.frame of additional features to add. By default,
#' no additional features are used. Passed to \code{\link{prepare_classification}}.
#' @param ... Additional arguments passed to \code{\link{glmnet}}.
#' @return list containing classification results
classification_summary <- function(popstats, treatment_info, pdata,
stimulation = "GAG-1-PTEG", train_pct = 0.6,
prob_threshold = 0, other_features = NULL, ...) {
classif_data <- prepare_classification(popstats = popstats,
treatment_info = treatment_info, pdata = pdata,
other_features = other_features,
stimulation = stimulation, train_pct = train_pct)
train_data <- classif_data$train_data
test_data <- classif_data$test_data
placebo_data <- classif_data$placebo_data
train_x <- as.matrix(subset(train_data, select = -c(PTID, VISITNO)))
train_y <- train_data$VISITNO
test_x <- as.matrix(subset(test_data, select = -c(PTID, VISITNO)))
test_y <- test_data$VISITNO
placebo_x <- as.matrix(subset(placebo_data, select = -c(PTID, VISITNO)))
placebo_y <- placebo_data$VISITNO
# Trains the 'glmnet' classifier using cross-validation.
glmnet_cv <- cv.glmnet(x = train_x, y = train_y, family = "binomial", ...)
glmnet_fit <- glmnet(x = train_x, y = train_y, family = "binomial", ...)
# Computes classification accuracies in two different ways. If the visits are
# paired by patient, then we compute the proportion of correctly classified
# patients. Otherwise, we calculate the proportion of visits that are correctly
# classified.
predictions_treated <- as.vector(predict(glmnet_cv, test_x, s = "lambda.min",
type = "response"))
predictions_placebo <- as.vector(predict(glmnet_cv, placebo_x,
s = "lambda.min", type = "response"))
# If the difference in classification probabilities exceeds the probability
# threshold, we assign the first sample as visit 2 and the second as visit 12.
# Otherwise, we assign the first sample as visit 12 and the second as visit 2.
correct_patients <- tapply(seq_along(test_data$PTID), test_data$PTID, function(i) {
if (diff(predictions_treated[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == test_y[i])
})
correct_placebo <- tapply(seq_along(placebo_data$PTID), placebo_data$PTID, function(i) {
if (diff(predictions_placebo[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == placebo_y[i])
})
accuracy_treated <- mean(correct_patients)
accuracy_placebo <- mean(correct_placebo)
# Determines which features should be kept for classification
# If present, we manually remove the "(Intercept)"
# In the case that all markers are removed and only the intercept remains, we
# add the "(Intercept)" back, for clarity.
coef_glmnet <- coef(glmnet_fit, s = glmnet_cv$lambda.min)
markers_kept <- rownames(coef_glmnet)[as.vector(coef_glmnet) != 0]
markers_kept <- markers_kept[!grepl("(Intercept)", markers_kept)]
if (length(markers_kept) == 0) {
markers_kept <- "(Intercept)"
}
# We return the classification accuracies, the classification probabilities and
# markers kept using 'glmnet', the corresponding test data sets for further
# analysis (e.g., ROC curves), and the markers kept by 'glmnet'.
list(accuracy = list(treatment = accuracy_treated, placebo = accuracy_placebo),
classification_probs = list(treated = predictions_treated,
placebo = predictions_placebo),
markers = markers_kept, coef_glmnet = coef_glmnet,
test_data = list(treated = test_data, placebo = placebo_data))
}
#' Classification summary for population statistics using logistic regression
#'
#' For a data.frame of population statistics, we conduct a classification summary
#' of the the stimulation groups using the given treatment information.
#'
#' Per Greg, we apply the following classification study:
#' 1. Remove placebos before subsetting treatment group train classifier.
#' 2. Predict placebos (should expect poor classification accuracy because there
#' should be no separation in the placebos)
#' 3. Predict test data set (should expect good results)
#'
#' Per Greg:
#' "We also want to do this paired, using the difference in classification
#' probabilities for two samples from the same subject. i.e.
#' d = Pr(sample 1 from subject 1 = post-vaccine) -
#' Pr(sample 2 from subject 1 = post-vaccine).
#' If d > threshold, then classify sample 1 as post-vaccine and sample 2 as
#' pre-vaccine, otherwise if d < threshold classify sample 1 as pre-vaccine and
#' sample 2 as post-vaccine, otherwise mark them as unclassifiable."
#'
#' Hence, we compute classification accuracies by pairing the visits by patient
#' and then computing the proportion of correctly classified patients. Otherwise,
#' we calculate the proportion of visits that are correctly classified.
#'
#' @param popstats a data.frame containing population statistics from
#' \code{getPopStats}
#' @param treatment_info a data.frame containing a lookup of \code{PTID} and
#' placebo/treatment information
#' @param pdata an object returned from \code{pData} from the \code{GatingSet}
#' @param stimulation the stimulation group
#' @param train_pct a numeric value determining the percentage of treated
#' patients used as training data and the remaining patients as test data
#' @param prob_threshold a numeric value above which the difference in
#' classification probabilities for two samples from the same subject indicates
#' that the first sample is classified as post-vaccine. Ignored if \code{paired}
#' is \code{FALSE}. See details.
#' @param ... Additional arguments passed to \code{\link{glm}}.
#' @return list containing classification results
classification_summary_logistic <- function(popstats, treatment_info, pdata,
stimulation = "GAG-1-PTEG", train_pct = 0.6,
prob_threshold = 0, manual_gates = FALSE, ...) {
if (manual_gates) {
classif_data <- prepare_manual(popstats = popstats, treatment_info = treatment_info,
pdata = pdata, stimulation = stimulation, train_pct = train_pct)
} else {
classif_data <- prepare_classification(popstats = popstats,
treatment_info = treatment_info, pdata = pdata,
stimulation = stimulation, train_pct = train_pct)
}
train_data <- classif_data$train_data
test_data <- classif_data$test_data
placebo_data <- classif_data$placebo_data
train_data$PTID <- as.character(train_data$PTID)
test_data$PTID <- as.character(test_data$PTID)
placebo_data$PTID <- as.character(placebo_data$PTID)
train_x <- as.matrix(subset(train_data, select = -c(PTID, VISITNO)))
train_y <- train_data$VISITNO
test_x <- as.matrix(subset(test_data, select = -c(PTID, VISITNO)))
test_y <- test_data$VISITNO
placebo_x <- as.matrix(subset(placebo_data, select = -c(PTID, VISITNO)))
placebo_y <- placebo_data$VISITNO
# It is much easier to use 'glm' with data.frames. We oblige here.
# The Dude does oblige.
train_df <- data.frame(VISITNO = train_y, train_x, check.names = FALSE)
test_df <- data.frame(VISITNO = test_y, test_x, check.names = FALSE)
placebo_df <- data.frame(VISITNO = placebo_y, placebo_x, check.names = FALSE)
# Trains the 'glmnet' classifier using cross-validation.
glm_out <- glm(VISITNO ~ ., data = train_df, family = binomial(logit), ...)
# Computes classification accuracies in two different ways. If the visits are
# paired by patient, then we compute the proportion of correctly classified
# patients. Otherwise, we calculate the proportion of visits that are correctly
# classified.
predictions_treated <- as.vector(predict(glm_out, test_df, type = "response"))
predictions_placebo <- as.vector(predict(glm_out, placebo_df, type = "response"))
# If the difference in classification probabilities exceeds the probability
# threshold, we assign the first sample as visit 2 and the second as visit 12.
# Otherwise, we assign the first sample as visit 12 and the second as visit 2.
correct_patients <- tapply(seq_along(test_data$PTID), test_data$PTID, function(i) {
if (diff(predictions_treated[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == test_y[i])
})
correct_placebo <- tapply(seq_along(placebo_data$PTID), placebo_data$PTID, function(i) {
if (diff(predictions_placebo[i]) > prob_threshold) {
classification <- c("2", "12")
} else {
classification <- c("12", "2")
}
all(classification == placebo_y[i])
})
accuracy_treated <- mean(correct_patients)
accuracy_placebo <- mean(correct_placebo)
# Extracts the fitted coefficients for each feature
coef_glm <- coef(glm_out)
# We return the classification accuracies, the classification probabilities and
# markers kept using 'glmnet', the corresponding test data sets for further
# analysis (e.g., ROC curves), and the markers kept by 'glmnet'.
list(accuracy = list(treatment = accuracy_treated, placebo = accuracy_placebo),
classification_probs = list(treated = predictions_treated,
placebo = predictions_placebo),
coef_glm = coef_glm,
test_data = list(treated = test_data, placebo = placebo_data))
}
#' Scales a vector of data using the Huber robust estimator for mean and
#' standard deviation
#'
#' This function is an analog to \code{\link{scale}} but using Huber robust
#' estimators instead of the usual sample mean and standard deviation.
#'
#' @param x numeric vector
#' @param center logical value. Should \code{x} be centered?
#' @param scale logical value. Should \code{x} be scaled?
#' @return numeric vector containing the scaled data
scale_huber <- function(x, center = TRUE, scale = TRUE) {
x <- as.vector(x)
huber_x <- huber(x)
# If 'center' is set to TRUE, we center 'x' by the Huber robust location
# estimator.
center_x <- FALSE
if (center) {
center_x <- huber_x$mu
}
# If 'scale' is set to TRUE, we scale 'x' by the Huber robust standard
# deviation estimator.
scale_x <- FALSE
if (scale) {
scale_x <- huber_x$s
}
as.vector(base:::scale(x, center = center_x, scale = scale_x))
}
#' Centers a vector of data using the mode of the kernel density estimate
#'
#' @param x numeric vector
#' @param ... additional arguments passed to \code{\link{density}}
#' @return numeric vector containing the centered data
center_mode <- function(x, ...) {
x <- as.vector(x)
density_x <- density(x)
mode <- density_x$x[which.max(density_x$y)]
as.vector(scale(x, center = mode, scale = FALSE))
}
#' Extracts legend from ggplot2 object
#'
#' Code from Hadley Wickham:
#' https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
#'
#' @param a.gplot a \code{ggplot2} object
#' @return a \code{ggplot2} legend
g_legend <- function(a.gplot) {
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)
}
#' Look up channel name for cytokine
#'
#' @param x cytokine marker name
#' @return the corresponding channel name
cytokine2channel <- function(x) {
switch(x,
TNFa = "Alexa 680-A",
IFNg = "PE Cy7-A",
IL2 = "PE Green laser-A"
)
}
#' Standardizes a cytokine data with respect to a reference stimulation group
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' @param ref_stimulation reference stimulation group
#' @return data.frame with cytokine data standardized with respect to the
#' reference stimulation group
standardize_cytokines <- function(x) {
# Standardizes the cytokine samples within stimulation group with respect to
# the reference stimulation group.
# First, centers the values by the mode of the kernel density estimate for
# the stimulation group.
x <- tapply(x$value, x$Stim, center_mode)
# Scales the stimulation groups by their Huber estimator of the
# standard deviation to put all stimulations on the same scale.
x <- lapply(x, scale_huber, center = FALSE)
x <- melt(x)
colnames(x) <- c("value", "Stim")
x
}
#' Reads the specified cytokine from a gating set
#' @param gs gating set object
#' @param PTID patient ID
#' @param VISITNO patient visit number
#' @param tcells which T-cell type?
#' @param cytokine which cytokine?
#' @return a data.frame with the appropriate cytokine data
read_cytokines <- function(gs, PTID, VISITNO = c("2", "12"), tcells = c("cd4", "cd8"),
cytokine = c("TNFa", "IFNg", "IL2")) {
pData_gs <- pData(gs)
pData_gs <- pData_gs[pData_gs$PTID == PTID & pData_gs$VISITNO == VISITNO, ]
x <- lapply(seq_along(pData_gs$name), function(i) {
flow_set <- getData(gs[pData_gs$name[i]], tcells)
# In the case that 0 or 1 cells are present, we return NULL. The case of 1
# cell is ignored because a density cannot be estimated from it. In fact,
# density(...) throws an error in this case.
if (nrow(flow_set[[1]]) >= 2) {
cbind("Stim" = as.character(pData_gs$Stim[i]), "value" = exprs(flow_set[[1]])[, cytokine2channel(cytokine)])
} else {
NULL
}
})
x <- do.call(rbind, x)
x <- data.frame(x, stringsAsFactors = FALSE)
x$value <- as.numeric(x$value)
x
}
#' Constructs the kernel density estimates for each stimulation group for a
#' given set of cytokine data
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' @param ... additional arguments passed to \code{\link{density}}
#' @return data.frame with the cytokine densities for each stimulation group
density_cytokines <- function(x, ...) {
density_x <- tapply(x$value, x$Stim, density, ...)
density_x <- lapply(seq_along(density_x), function(i) {
cbind(Stim = names(density_x)[i], x = density_x[[i]]$x,
y = density_x[[i]]$y)
})
do.call(rbind, density_x)
}
#' Constructs the derivatives of the kernel density estimates for each
#' stimulation group for a given set of cytokine data
#'
#' For guidance on selecting the bandwidth, see this post:
#' http://stats.stackexchange.com/questions/33918/is-there-an-optimal-bandwidth-for-a-kernel-density-estimator-of-derivatives
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' @param adjust a numeric weight on the automatic bandwidth
#' @param collapse If \code{TRUE}, the values are collapsed from all stimulation
#' groups before estimating the derivative of the density function
#' @param ... additional arguments passed to \code{\link{density}}
#' @return data.frame with the cytokine densities for each stimulation group
deriv_cytokines <- function(x, deriv = 1, adjust = 1, collapse = FALSE) {
require('feature')
require('ks')
if (collapse) {
deriv_x <- drvkde(x = x$value, drv = deriv, bandwidth = adjust * hpi(x$value))
deriv_x <- cbind(x = deriv_x$x.grid[[1]], y = deriv_x$est)
} else {
deriv_x <- tapply(seq_along(x$Stim), x$Stim, function(i) {
drvkde(x = x$value[i], drv = deriv, bandwidth = adjust * hpi(x$value[i]))
})
deriv_x <- lapply(seq_along(deriv_x), function(i) {
cbind(Stim = names(deriv_x)[i], x = deriv_x[[i]]$x.grid[[1]],
y = deriv_x[[i]]$est)
})
deriv_x <- do.call(rbind, deriv_x)
}
deriv_x
}
#' Constructs a cutpoint by collapsing the values of a stimulation group and
#' using the first derivative of the kernel density estimate to establish a
#' cutpoint
#'
#' @param x melted data.frame containing cytokine data for each stimulation
#' group (column labeled 'Stim')
#' groups before estimating the derivative of the density function
#' @param ... additional arguments passed to \code{\link{deriv_cytokine}}
#' @return the cutpoint along the x-axis
cytokine_cutpoint <- function(x, tol = 0.001, ...) {
deriv_out <- deriv_cytokines(x = x, deriv = 1, collapse = TRUE, ...)
x <- deriv_TNFa[, 1]
y <- deriv_TNFa[, 2]
lowest_valley <- x[which.min(y)]
cutpoint <- x[which(x > lowest_valley & abs(y) < tol)[1]]
cutpoint
}
#' Partitions the population statistics by tolerance values
#'
#' Partitions the population statistics into upstream and cytokines for each
#' processing below. The cytokine population statistics are stored in a named
#' list, where each element corresponds to a cytokine tolerance value.
#' The tolerance value is then stripped from the marker names.
#'
#' @param data.frame containing population statistics
#' @param tolerances a vector of the tolerance values
#' @return a list of data.frames, each of which is the data.frame of population
#' statistics for the current tolerance value.
partition_popstats <- function(popstats, tolerances) {
popstats <- lapply(tolerances, function(tol) {
popstats_tol <- popstats[grep(tol, rownames(popstats)), ]
rownames(popstats_tol) <- sapply(strsplit(rownames(popstats_tol), "_"), head, n = 1)
popstats_tol
})
names(popstats) <- tolerances
popstats
}
#' Summarizes paired classification study and generates ROC results
#'
#' @param results named list containing the results for each cytokine tolerance value
#' @param tolerances a vector of the tolerance values
#' @return data.frame with ROC results
ROC_summary <- function(results, tolerances) {
treated <- lapply(results, function(x) {
cbind(subset(x$test_data$treated, select = c(PTID, VISITNO)),
Truth = "Treatment",
Probability = x$classification_probs$treated)
})
placebo <- lapply(results, function(x) {
cbind(subset(x$test_data$placebo, select = c(PTID, VISITNO)),
Truth = "Placebo",
Probability = x$classification_probs$placebo)
})
probs <- lapply(tolerances, function(tol) {
cbind(Tolerance = tol, rbind(treated[[tol]], placebo[[tol]]))
})
probs <- do.call(rbind, probs)
# For each PTID, we compute the absolute value of the difference in
# classification probabilties for visits 2 and 12 and then order by the
# differences.
summary <- ddply(probs, .(Tolerance, PTID), summarize,
delta = 1 - abs(diff(Probability[VISITNO %in% c("2", "12")])),
Truth = unique(Truth))
summary <- summary[with(summary, order(Tolerance, delta, Truth, decreasing = FALSE)), ]
# Calculates true and false positive rates based on Treatment and Placebo
# samples, respectively. Because we are using Treatments and Placebos, we
# calculate TPRs and FPRs differently than usual. The basic idea is that when we
# add to the TPR each time we classify a patient as Treatment and to the FPR
# each time we classify a patient as Placebo. The ordering here is determined by
# the rank of the differences in classification probabilities.
ddply(summary, .(Tolerance), summarize,
FPR = cumsum(Truth == "Placebo") / sum(Truth == "Placebo"),
TPR = cumsum(Truth == "Treatment") / sum(Truth == "Treatment"))
}
#' Summarizes classification study and generates ROC results for manual gates
#'
#' @param results named list containing the results for each cytokine tolerance value
#' @return data.frame with ROC results
ROC_summary_manual <- function(results) {
treated <- cbind(subset(results$test_data$treated, select = c(PTID, VISITNO)),
Truth = "Treatment",
Probability = results$classification_probs$treated)
placebo <- cbind(subset(results$test_data$placebo, select = c(PTID, VISITNO)),
Truth = "Placebo",
Probability = results$classification_probs$placebo)
probs <- rbind(treated, placebo)
# For each PTID, we compute the absolute value of the difference in
# classification probabilties for visits 2 and 12 and then order by the
# differences.
summary <- ddply(probs, .(PTID), summarize,
delta = 1 - abs(diff(Probability[VISITNO %in% c("2", "12")])),
Truth = unique(Truth))
summary <- summary[with(summary, order(delta, Truth, decreasing = FALSE)), ]
# Calculates true and false positive rates based on Treatment and Placebo
# samples, respectively. Because we are using Treatments and Placebos, we
# calculate TPRs and FPRs differently than usual. The basic idea is that when we
# add to the TPR each time we classify a patient as Treatment and to the FPR
# each time we classify a patient as Placebo. The ordering here is determined by
# the rank of the differences in classification probabilities.
summarize(summary, FPR = cumsum(Truth == "Placebo") / sum(Truth == "Placebo"),
TPR = cumsum(Truth == "Treatment") / sum(Truth == "Treatment"))
}
|
# use Houston crime data, included as part of the ggmap package
library(ggmap)
# We obtained this csv file from the Houston Police Beats page of the City of Houston GIS Open Data web site
# http://cohgis.mycity.opendata.arcgis.com/
beats_table <- read.csv(file="Houston_Police_Beats.csv",head=TRUE,sep=",")
colnames(beats_table)[1] = "Beats"
# reorder the beats so that we can map them later
beat_ordering <- beats_table$Beats
plottable_crimes = subset(crime, beat%in% beat_ordering)
tensor = table(plottable_crimes[, c("hour", "beat", "offense")])
tensor = tensor[,setdiff(beat_ordering,'24C60'),]
write.csv(tensor[,,1], 'hour-by-beat_AggravatedAssault2.csv')
write.csv(tensor[,,2], 'hour-by-beat_AutoTheft2.csv')
write.csv(tensor[,,3], 'hour-by-beat_Burglary2.csv')
write.csv(tensor[,,4], 'hour-by-beat_Murder2.csv')
write.csv(tensor[,,5], 'hour-by-beat_Rape2.csv')
write.csv(tensor[,,6], 'hour-by-beat_Robbery2.csv')
write.csv(tensor[,,7], 'hour-by-beat_Theft2.csv')
| /data/saveCrimeTensor.R | permissive | GRSEB9S/sctd | R | false | false | 999 | r | # use Houston crime data, included as part of the ggmap package
library(ggmap)
# We obtained this csv file from the Houston Police Beats page of the City of Houston GIS Open Data web site
# http://cohgis.mycity.opendata.arcgis.com/
beats_table <- read.csv(file="Houston_Police_Beats.csv",head=TRUE,sep=",")
colnames(beats_table)[1] = "Beats"
# reorder the beats so that we can map them later
beat_ordering <- beats_table$Beats
plottable_crimes = subset(crime, beat%in% beat_ordering)
tensor = table(plottable_crimes[, c("hour", "beat", "offense")])
tensor = tensor[,setdiff(beat_ordering,'24C60'),]
write.csv(tensor[,,1], 'hour-by-beat_AggravatedAssault2.csv')
write.csv(tensor[,,2], 'hour-by-beat_AutoTheft2.csv')
write.csv(tensor[,,3], 'hour-by-beat_Burglary2.csv')
write.csv(tensor[,,4], 'hour-by-beat_Murder2.csv')
write.csv(tensor[,,5], 'hour-by-beat_Rape2.csv')
write.csv(tensor[,,6], 'hour-by-beat_Robbery2.csv')
write.csv(tensor[,,7], 'hour-by-beat_Theft2.csv')
|
source("thin.r")
# Rotate starting & ending points so that they coincide with a
# neighbour change
rotate <- function(df) {
n <- nrow(df)
first <- which.max(df$change)
rbind(df[first:n, ], df[1:first, ])
}
add_tol <- function(df) {
df$hash <- paste(df$long, df$lat)
if (is.null(df$order)) df$order <- 1:nrow(df)
neighbours <- ddply(df, .(hash), nrow)
names(neighbours) <- c("hash", "count")
df <- merge(df, neighbours, by = "hash")
df <- df[order(df$order), ]
# A point is a change point if the count is:
# * one greater than the surrounding points (neighbour has joined)
# * two or more (must be a corner)
df <- ddply(df, .(group), transform,
change = diff(c(count[length(count)], count)) > 0 | count > 2
)
df <- ddply(df, .(group), rotate)
df <- ddply(df, .(group), thin_poly, .progress = "text")
df$hash <- NULL
df
}
thin_poly <- function(df) {
breaks <- unique(c(1, which(df$change), nrow(df)))
pieces <- as.data.frame(embed(breaks, 2)[, c(2, 1), drop = FALSE])
colnames(pieces) <- c("start", "end")
pieces$last <- rep(c(F, T), c(nrow(pieces) - 1, 1))
mdply(pieces, thin_piece, data = df)
}
# Given a data frame representing a region, and the starting and
# end pointing of a single polyline, augment that line with dp tolerances
thin_piece <- function(data, start, end, last = FALSE) {
sub <- data[start:end, ]
# Remove any duplicated locations
sub <- sub[!duplicated(sub[c("long", "lat")]), ]
if (nrow(sub) < 3) {
sub$tol <- Inf
return(sub)
}
tol <- c(Inf, compute_tol(sub), Inf)
if (length(tol) != nrow(sub)) browser()
sub$tol <- tol
# The last row is duplicated for all pieces except the last
if (!last) {
sub[-nrow(sub), ]
} else {
sub
}
}
| /thin-better.r | permissive | metaphorz/data-counties | R | false | false | 1,774 | r | source("thin.r")
# Rotate starting & ending points so that they coincide with a
# neighbour change
rotate <- function(df) {
n <- nrow(df)
first <- which.max(df$change)
rbind(df[first:n, ], df[1:first, ])
}
add_tol <- function(df) {
df$hash <- paste(df$long, df$lat)
if (is.null(df$order)) df$order <- 1:nrow(df)
neighbours <- ddply(df, .(hash), nrow)
names(neighbours) <- c("hash", "count")
df <- merge(df, neighbours, by = "hash")
df <- df[order(df$order), ]
# A point is a change point if the count is:
# * one greater than the surrounding points (neighbour has joined)
# * two or more (must be a corner)
df <- ddply(df, .(group), transform,
change = diff(c(count[length(count)], count)) > 0 | count > 2
)
df <- ddply(df, .(group), rotate)
df <- ddply(df, .(group), thin_poly, .progress = "text")
df$hash <- NULL
df
}
thin_poly <- function(df) {
breaks <- unique(c(1, which(df$change), nrow(df)))
pieces <- as.data.frame(embed(breaks, 2)[, c(2, 1), drop = FALSE])
colnames(pieces) <- c("start", "end")
pieces$last <- rep(c(F, T), c(nrow(pieces) - 1, 1))
mdply(pieces, thin_piece, data = df)
}
# Given a data frame representing a region, and the starting and
# end pointing of a single polyline, augment that line with dp tolerances
thin_piece <- function(data, start, end, last = FALSE) {
sub <- data[start:end, ]
# Remove any duplicated locations
sub <- sub[!duplicated(sub[c("long", "lat")]), ]
if (nrow(sub) < 3) {
sub$tol <- Inf
return(sub)
}
tol <- c(Inf, compute_tol(sub), Inf)
if (length(tol) != nrow(sub)) browser()
sub$tol <- tol
# The last row is duplicated for all pieces except the last
if (!last) {
sub[-nrow(sub), ]
} else {
sub
}
}
|
library(tidyverse)
# Get samples sequenced ---------------------------------------------------
# Import from the bamlist
seqed_samples <- read_delim(file = "genomics/bamlists/all_samples_bamlist.txt", delim = "\t", col_names = "bam_file") %>%
mutate(sample = basename(bam_file)) %>%
mutate(sample = str_remove(sample, ".realigned.sorted.bam")) %>%
mutate(sample = str_remove(sample, "_realigned_sorted.bam"))
samples <- seqed_samples %>%
pull(sample)
# Import beagle GLs -------------------------------------------------------
# Also gives us allele identity
# A function to convert the numeric allele identites from angsd to characters
angsd_allele_ids <- function(numeric) {
switch (numeric,
"0" = {out <- "A"},
"1" = {out <- "C"},
"2" = {out <- "G"},
"3" = {out <- "T"},
stop("Not a valid entry")
)
out
}
angsd_allele_ids <- Vectorize(angsd_allele_ids)
# Import each
asip_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/asip_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
corin_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/corin_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
ednrb_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/ednrb_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
scaff380_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/scaff380_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
# Import Massarray info on allele identity --------------------------------
# Massarry is based on orycun coords,
# which are the reverse complement of WTJR
# So, need to complement them here
complement <- function(dnachar) {
switch(dnachar,
"A" = out <- "T",
"C" = out <- "G",
"G" = out <- "C",
"T" = out <- "A",
stop("Not valid base")
)
out
}
complement <- Vectorize(complement)
allele_ids <- read_csv("genomics/03_color-polymorphism-across-range/white_brown_allele_ids.csv") %>%
filter(!is.na(gene)) %>%
mutate(white_allele = complement(white_allele)) %>%
mutate(brown_allele = complement(brown_allele))
# Import info on translating between coord systems ------------------------
translate_coords <- read_csv("genomics/03_color-polymorphism-across-range/color_allele_coord_translation.csv", col_types = "cc") %>%
separate(orycun_location, into = c("scaffold_orycun", "position_orycun"), remove = T, convert = T) %>%
separate(wtjr_location, into = c("scaffold", "position"), remove = T, convert = T)
# Get "color" of minor allele for each site -------------------------------
# Sort of an ungodly way to do it, but works for now
asip_colors <- asip_GLs %>%
select(location, scaffold, position, major_allele, minor_allele) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = minor_allele == brown_allele) %>%
mutate(white = minor_allele == white_allele) %>%
mutate(other = minor_allele != brown_allele & minor_allele != white_allele) %>%
dplyr::select(location, scaffold, position, major_allele, brown, white, other) %>%
pivot_longer(brown:other, names_to = "minor_color") %>%
filter(value) %>%
select(-value) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = major_allele == brown_allele) %>%
mutate(white = major_allele == white_allele) %>%
mutate(other = major_allele != brown_allele & major_allele != white_allele) %>%
dplyr::select(location, scaffold, position, minor_color, brown:other) %>%
pivot_longer(brown:other, names_to = "major_color") %>%
filter(value) %>%
select(-value)
corin_colors <- corin_GLs %>%
select(location, scaffold, position, major_allele, minor_allele) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = minor_allele == brown_allele) %>%
mutate(white = minor_allele == white_allele) %>%
mutate(other = minor_allele != brown_allele & minor_allele != white_allele) %>%
dplyr::select(location, scaffold, position, major_allele, brown, white, other) %>%
pivot_longer(brown:other, names_to = "minor_color") %>%
filter(value) %>%
select(-value) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = major_allele == brown_allele) %>%
mutate(white = major_allele == white_allele) %>%
mutate(other = major_allele != brown_allele & major_allele != white_allele) %>%
dplyr::select(location, scaffold, position, minor_color, brown:other) %>%
pivot_longer(brown:other, names_to = "major_color") %>%
filter(value) %>%
select(-value)
ednrb_colors <- ednrb_GLs %>%
select(location, scaffold, position, major_allele, minor_allele) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = minor_allele == brown_allele) %>%
mutate(white = minor_allele == white_allele) %>%
mutate(other = minor_allele != brown_allele & minor_allele != white_allele) %>%
dplyr::select(location, scaffold, position, major_allele, brown, white, other) %>%
pivot_longer(brown:other, names_to = "minor_color") %>%
filter(value) %>%
select(-value) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = major_allele == brown_allele) %>%
mutate(white = major_allele == white_allele) %>%
mutate(other = major_allele != brown_allele & major_allele != white_allele) %>%
dplyr::select(location, scaffold, position, minor_color, brown:other) %>%
pivot_longer(brown:other, names_to = "major_color") %>%
filter(value) %>%
select(-value)
# With scaffold 380, don't have MASSarray data. Figure out color alleles by looking
# at dosages of individuals with known phenotype.
# First, will subset to only sites/individuals with good enough QC scores to try to
# figure out which allele is brown and which is white.
scaff380_qc <- scaff380_GLs %>%
dplyr::select(-(scaffold:minor_allele)) %>%
pivot_longer(-location, names_to = "sample") %>%
mutate(sample = str_remove(sample, "_[[Mm]]+")) %>%
mutate(dist = (value - (1/3))^2) %>%
group_by(location, sample) %>%
summarize(qc_score = sqrt(sum(dist))/0.8164966) %>%
ungroup()
# Then, pull in the color info for each sample from table S3
sample_colors <- read_csv("genomics/05_dosage-environment-correlation/sample_colors.csv") %>%
mutate(sample = str_replace(sample, "_", "-"))
scaff380_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/scaff380_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T)
z <- scaff380_dosages %>%
pivot_longer(`AMNH-123030`:last_col(), names_to = "sample", values_to = "dosage") %>%
left_join(sample_colors) %>%
filter(!is.na(color)) %>%
group_by(location, scaffold, position, color) %>%
summarize(mean_dosage = mean(dosage))
# Higher dosage == more brown. Dosages are for the brown allele.
# Import Genotype dosages -------------------------------------------------
asip_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/asip_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
left_join(asip_colors) %>%
relocate(minor_color:major_color, .after = position)
corin_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/corin_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
left_join(corin_colors) %>%
relocate(minor_color:major_color, .after = position)
ednrb_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/ednrb_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
left_join(ednrb_colors) %>%
relocate(minor_color:major_color, .after = position)
# Get all dosages in terms of white allele
dosages_white <- function(dosage_row) {
if (dosage_row["minor_color"] == "white") { # if minor is already white
return(dosage_row) # don't do anything
} else if (dosage_row["major_color"] == "white") { # if major is white, switch dosage
dosage_white <- dosage_row
dosage_white[6:length(dosage_row)] <- 2 - as.numeric(dosage_row[6:length(dosage_row)])
return(dosage_white)
} else { # minor was other and major was brown
# Can't use a site like that
dosage_out <- dosage_row
dosage_out[6:length(dosage_row)] <- NA
return(dosage_out)
}
}
asip_white_dosage <- as_tibble(t(apply(X = asip_dosages, MARGIN = 1, FUN = dosages_white)))
corin_white_dosage <- as_tibble(t(apply(X= corin_dosages, MARGIN = 1, FUN = dosages_white)))
ednrb_white_dosage <- as_tibble(t(apply(X= ednrb_dosages, MARGIN = 1, FUN = dosages_white)))
scaff380_white_dosage <- scaff380_dosages %>%
pivot_longer(`AMNH-123030`:last_col()) %>%
mutate(value = 2 - value) %>%
pivot_wider()
# Save them all
asip_white_dosage %>%
select(-minor_color, -major_color) %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/asip_dosages_white.csv", col_names = T)
corin_white_dosage %>%
select(-minor_color, -major_color) %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/corin_dosages_white.csv", col_names = T)
ednrb_white_dosage %>%
select(-minor_color, -major_color) %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/ednrb_dosages_white.csv", col_names = T)
scaff380_white_dosage %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/scaff380_dosages_white.csv", col_names = T)
| /genomics/05_dosage-environment-correlation/process_dosages_for_color_alleles.R | no_license | tjthurman/wtjr_sdm | R | false | false | 11,498 | r |
library(tidyverse)
# Get samples sequenced ---------------------------------------------------
# Import from the bamlist
seqed_samples <- read_delim(file = "genomics/bamlists/all_samples_bamlist.txt", delim = "\t", col_names = "bam_file") %>%
mutate(sample = basename(bam_file)) %>%
mutate(sample = str_remove(sample, ".realigned.sorted.bam")) %>%
mutate(sample = str_remove(sample, "_realigned_sorted.bam"))
samples <- seqed_samples %>%
pull(sample)
# Import beagle GLs -------------------------------------------------------
# Also gives us allele identity
# A function to convert the numeric allele identites from angsd to characters
angsd_allele_ids <- function(numeric) {
switch (numeric,
"0" = {out <- "A"},
"1" = {out <- "C"},
"2" = {out <- "G"},
"3" = {out <- "T"},
stop("Not a valid entry")
)
out
}
angsd_allele_ids <- Vectorize(angsd_allele_ids)
# Import each
asip_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/asip_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
corin_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/corin_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
ednrb_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/ednrb_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
scaff380_GLs <- read_delim("genomics/results/angsd/beagle_GL_scaffold/filter_95ind_10X/scaff380_site_GLs.beagle", delim = "\t",
col_names = c("location",
"major_allele",
"minor_allele",
paste(rep(samples, each = 3), c("MM", "Mm", "mm"), sep = "_"))) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
mutate(major_allele = angsd_allele_ids(as.character(major_allele))) %>%
mutate(minor_allele = angsd_allele_ids(as.character(minor_allele)))
# Import Massarray info on allele identity --------------------------------
# Massarry is based on orycun coords,
# which are the reverse complement of WTJR
# So, need to complement them here
complement <- function(dnachar) {
switch(dnachar,
"A" = out <- "T",
"C" = out <- "G",
"G" = out <- "C",
"T" = out <- "A",
stop("Not valid base")
)
out
}
complement <- Vectorize(complement)
allele_ids <- read_csv("genomics/03_color-polymorphism-across-range/white_brown_allele_ids.csv") %>%
filter(!is.na(gene)) %>%
mutate(white_allele = complement(white_allele)) %>%
mutate(brown_allele = complement(brown_allele))
# Import info on translating between coord systems ------------------------
translate_coords <- read_csv("genomics/03_color-polymorphism-across-range/color_allele_coord_translation.csv", col_types = "cc") %>%
separate(orycun_location, into = c("scaffold_orycun", "position_orycun"), remove = T, convert = T) %>%
separate(wtjr_location, into = c("scaffold", "position"), remove = T, convert = T)
# Get "color" of minor allele for each site -------------------------------
# Sort of an ungodly way to do it, but works for now
asip_colors <- asip_GLs %>%
select(location, scaffold, position, major_allele, minor_allele) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = minor_allele == brown_allele) %>%
mutate(white = minor_allele == white_allele) %>%
mutate(other = minor_allele != brown_allele & minor_allele != white_allele) %>%
dplyr::select(location, scaffold, position, major_allele, brown, white, other) %>%
pivot_longer(brown:other, names_to = "minor_color") %>%
filter(value) %>%
select(-value) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = major_allele == brown_allele) %>%
mutate(white = major_allele == white_allele) %>%
mutate(other = major_allele != brown_allele & major_allele != white_allele) %>%
dplyr::select(location, scaffold, position, minor_color, brown:other) %>%
pivot_longer(brown:other, names_to = "major_color") %>%
filter(value) %>%
select(-value)
corin_colors <- corin_GLs %>%
select(location, scaffold, position, major_allele, minor_allele) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = minor_allele == brown_allele) %>%
mutate(white = minor_allele == white_allele) %>%
mutate(other = minor_allele != brown_allele & minor_allele != white_allele) %>%
dplyr::select(location, scaffold, position, major_allele, brown, white, other) %>%
pivot_longer(brown:other, names_to = "minor_color") %>%
filter(value) %>%
select(-value) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = major_allele == brown_allele) %>%
mutate(white = major_allele == white_allele) %>%
mutate(other = major_allele != brown_allele & major_allele != white_allele) %>%
dplyr::select(location, scaffold, position, minor_color, brown:other) %>%
pivot_longer(brown:other, names_to = "major_color") %>%
filter(value) %>%
select(-value)
ednrb_colors <- ednrb_GLs %>%
select(location, scaffold, position, major_allele, minor_allele) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = minor_allele == brown_allele) %>%
mutate(white = minor_allele == white_allele) %>%
mutate(other = minor_allele != brown_allele & minor_allele != white_allele) %>%
dplyr::select(location, scaffold, position, major_allele, brown, white, other) %>%
pivot_longer(brown:other, names_to = "minor_color") %>%
filter(value) %>%
select(-value) %>%
left_join(translate_coords) %>%
left_join(allele_ids) %>%
mutate(brown = major_allele == brown_allele) %>%
mutate(white = major_allele == white_allele) %>%
mutate(other = major_allele != brown_allele & major_allele != white_allele) %>%
dplyr::select(location, scaffold, position, minor_color, brown:other) %>%
pivot_longer(brown:other, names_to = "major_color") %>%
filter(value) %>%
select(-value)
# With scaffold 380, don't have MASSarray data. Figure out color alleles by looking
# at dosages of individuals with known phenotype.
# First, will subset to only sites/individuals with good enough QC scores to try to
# figure out which allele is brown and which is white.
scaff380_qc <- scaff380_GLs %>%
dplyr::select(-(scaffold:minor_allele)) %>%
pivot_longer(-location, names_to = "sample") %>%
mutate(sample = str_remove(sample, "_[[Mm]]+")) %>%
mutate(dist = (value - (1/3))^2) %>%
group_by(location, sample) %>%
summarize(qc_score = sqrt(sum(dist))/0.8164966) %>%
ungroup()
# Then, pull in the color info for each sample from table S3
sample_colors <- read_csv("genomics/05_dosage-environment-correlation/sample_colors.csv") %>%
mutate(sample = str_replace(sample, "_", "-"))
scaff380_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/scaff380_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T)
z <- scaff380_dosages %>%
pivot_longer(`AMNH-123030`:last_col(), names_to = "sample", values_to = "dosage") %>%
left_join(sample_colors) %>%
filter(!is.na(color)) %>%
group_by(location, scaffold, position, color) %>%
summarize(mean_dosage = mean(dosage))
# Higher dosage == more brown. Dosages are for the brown allele.
# Import Genotype dosages -------------------------------------------------
asip_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/asip_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
left_join(asip_colors) %>%
relocate(minor_color:major_color, .after = position)
corin_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/corin_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
left_join(corin_colors) %>%
relocate(minor_color:major_color, .after = position)
ednrb_dosages <- read_csv("genomics/results/pcangsd/95ind_10X_filter/ednrb_dosages.csv", col_names = c("location", samples)) %>%
separate(location, into = c("scaffold", "position"), remove = F, convert = T) %>%
left_join(ednrb_colors) %>%
relocate(minor_color:major_color, .after = position)
# Get all dosages in terms of white allele
dosages_white <- function(dosage_row) {
if (dosage_row["minor_color"] == "white") { # if minor is already white
return(dosage_row) # don't do anything
} else if (dosage_row["major_color"] == "white") { # if major is white, switch dosage
dosage_white <- dosage_row
dosage_white[6:length(dosage_row)] <- 2 - as.numeric(dosage_row[6:length(dosage_row)])
return(dosage_white)
} else { # minor was other and major was brown
# Can't use a site like that
dosage_out <- dosage_row
dosage_out[6:length(dosage_row)] <- NA
return(dosage_out)
}
}
asip_white_dosage <- as_tibble(t(apply(X = asip_dosages, MARGIN = 1, FUN = dosages_white)))
corin_white_dosage <- as_tibble(t(apply(X= corin_dosages, MARGIN = 1, FUN = dosages_white)))
ednrb_white_dosage <- as_tibble(t(apply(X= ednrb_dosages, MARGIN = 1, FUN = dosages_white)))
scaff380_white_dosage <- scaff380_dosages %>%
pivot_longer(`AMNH-123030`:last_col()) %>%
mutate(value = 2 - value) %>%
pivot_wider()
# Save them all
asip_white_dosage %>%
select(-minor_color, -major_color) %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/asip_dosages_white.csv", col_names = T)
corin_white_dosage %>%
select(-minor_color, -major_color) %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/corin_dosages_white.csv", col_names = T)
ednrb_white_dosage %>%
select(-minor_color, -major_color) %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/ednrb_dosages_white.csv", col_names = T)
scaff380_white_dosage %>%
write_csv("genomics/results/pcangsd/95ind_10X_filter/scaff380_dosages_white.csv", col_names = T)
|
library(xhmmScripts)
### Name: phenotypeDataToBinarySampleProperties
### Title: Convert a parsed Plink/Seq phenotype file into a matrix of
### binary sample properties.
### Aliases: phenotypeDataToBinarySampleProperties
### Keywords: ~kwd1 ~kwd2
### ** Examples
## Not run: phenotypeDataToBinarySampleProperties(readPhenotypesFile("a.phe"))
| /data/genthat_extracted_code/xhmmScripts/examples/phenotypeDataToBinarySampleProperties.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 350 | r | library(xhmmScripts)
### Name: phenotypeDataToBinarySampleProperties
### Title: Convert a parsed Plink/Seq phenotype file into a matrix of
### binary sample properties.
### Aliases: phenotypeDataToBinarySampleProperties
### Keywords: ~kwd1 ~kwd2
### ** Examples
## Not run: phenotypeDataToBinarySampleProperties(readPhenotypesFile("a.phe"))
|
#Times Series Analysis
# is the price of Johnson and Johnson shares change over time
# are there quarterly effects with share prices rising & falling in a regular fashion throughtout the year
# Can you forecast what future share prices will be and to what degree of accuracy
#dataset - Johnson
#Quarterly earnings per Johnson Shares
#Steps - Plot, Describe, Decompose, Forecast - Simple MA, Exp, ARIMA
JohnsonJohnson
install.packages('forecast')
library(forecast)
#ets auto select best predicton model
fit1 = ets(JohnsonJohnson)
fit1
#alpha - trend
#beta = seasonal
#gamma - irregular
JohnsonJohnson
head(JohnsonJohnson)
tail(JohnsonJohnson)
(f1= forecast(fit1))
plot(f1, main='Johnson Shares', ylab='Quartery Earnings', xlab='Time', flty = 3) # linetype for forecast area
par(mfrow=c(1,1))
# ARIMA
#http://slideplayer.com/5259056/16/images/98/Seasonal+Components--Model+Selection.jpg
f2 = auto.arima(JohnsonJohnson)
summary(f2)
tail(JohnsonJohnson)
forecast(f2,5)
#ARIMA Forecasting : compare two datasets
library(tseries)
plot(JohnsonJohnson)
ndiffs(JohnsonJohnson)
plot(diff(JohnsonJohnson))
plot(Nile)
plot(diff(Nile))
ndiffs(Nile)
#-----
djj = diff(JohnsonJohnson)
plot(djj)
dnile = diff(Nile)
plot(dnile)
#----
adf.test(djj)
#if pv < 0.05 accept Alt Hypothesis that series is stationary
#Model Selection
#parameters p, d , q
# d = no of diffs applied to make the series stationary
#https://people.duke.edu/~rnau/arimrule.htm
Acf(dnile)
#Trail off to zero : Zero after lag ; 0,1(p)
#Zero after lag q : Trails off to zero ; 1(q), 0
#Trails off to zero : Trial off to zero : 0,0
#Nile - 1 large auto correlation at lag 1 :
#Nile - pacf trails off to zero as the lags gets bigger
?arima
Pacf(dnile)
fit3 = arima(Nile, order=c(0,1,1)) # p,d,q
fit3
(fit3b = arima(Nile, order=c(1,1,1)))
#Model Test
qqnorm(fit3$residuals) # residuals ND
qqline(fit3$residuals)
#auto correl = 0 : check
Box.test(fit3$residuals, type='Ljung-Box')
#Test auto corr : H0= r=0 (True)
#Forecast
forecast(fit3,4)
#Auto ARIMA
#forecast::auto.arima()
fit4 = auto.arima(Nile)
fit4
| /kf.R | no_license | amit2625/FA_5_2018 | R | false | false | 2,088 | r | #Times Series Analysis
# is the price of Johnson and Johnson shares change over time
# are there quarterly effects with share prices rising & falling in a regular fashion throughtout the year
# Can you forecast what future share prices will be and to what degree of accuracy
#dataset - Johnson
#Quarterly earnings per Johnson Shares
#Steps - Plot, Describe, Decompose, Forecast - Simple MA, Exp, ARIMA
JohnsonJohnson
install.packages('forecast')
library(forecast)
#ets auto select best predicton model
fit1 = ets(JohnsonJohnson)
fit1
#alpha - trend
#beta = seasonal
#gamma - irregular
JohnsonJohnson
head(JohnsonJohnson)
tail(JohnsonJohnson)
(f1= forecast(fit1))
plot(f1, main='Johnson Shares', ylab='Quartery Earnings', xlab='Time', flty = 3) # linetype for forecast area
par(mfrow=c(1,1))
# ARIMA
#http://slideplayer.com/5259056/16/images/98/Seasonal+Components--Model+Selection.jpg
f2 = auto.arima(JohnsonJohnson)
summary(f2)
tail(JohnsonJohnson)
forecast(f2,5)
#ARIMA Forecasting : compare two datasets
library(tseries)
plot(JohnsonJohnson)
ndiffs(JohnsonJohnson)
plot(diff(JohnsonJohnson))
plot(Nile)
plot(diff(Nile))
ndiffs(Nile)
#-----
djj = diff(JohnsonJohnson)
plot(djj)
dnile = diff(Nile)
plot(dnile)
#----
adf.test(djj)
#if pv < 0.05 accept Alt Hypothesis that series is stationary
#Model Selection
#parameters p, d , q
# d = no of diffs applied to make the series stationary
#https://people.duke.edu/~rnau/arimrule.htm
Acf(dnile)
#Trail off to zero : Zero after lag ; 0,1(p)
#Zero after lag q : Trails off to zero ; 1(q), 0
#Trails off to zero : Trial off to zero : 0,0
#Nile - 1 large auto correlation at lag 1 :
#Nile - pacf trails off to zero as the lags gets bigger
?arima
Pacf(dnile)
fit3 = arima(Nile, order=c(0,1,1)) # p,d,q
fit3
(fit3b = arima(Nile, order=c(1,1,1)))
#Model Test
qqnorm(fit3$residuals) # residuals ND
qqline(fit3$residuals)
#auto correl = 0 : check
Box.test(fit3$residuals, type='Ljung-Box')
#Test auto corr : H0= r=0 (True)
#Forecast
forecast(fit3,4)
#Auto ARIMA
#forecast::auto.arima()
fit4 = auto.arima(Nile)
fit4
|
getwd()
setwd("/Users/manishreddybendhi/Desktop/Fun/Rprogramming/Assigenment2DataScience/Assigenment3")
getwd()
data1=read.table("heart.dat",header = TRUE)
head(data1)
data1
colnames(data1)=c("age","sex","Chestpain","rbp","serum","fbp","fendographic","maxHR","exericseInduced","oldpeak","slopepaekexce","vessels","defecttype","Diseace")
#data1$Diseace=as.integer(data1$Diseace)
data1
#glmmodel1=glm(Diseace~ age+sex+Chestpain+rbp+serum+fbp+fendographic+maxHR+exericseInduced+oldpeak+slopepaekexce+vessels+defecttype+Diseace,family = binomial(link = "logit"),data1)
#glmmodel1=glm(Diseace ~ age+sex,family = binomial(link = "logit"),data1)
#glmmodel1=glm(X2 ~ X3.0.1+X3.0+X2.0.1+X2.4+X0.0.1+X109.0+X2.0+X0.0+X322.0+X130.0+X4.0+X1.0+X70.0,family = binomial(link = "logit"),data1)
#Setting the value of defect type to 3
data1$defecttype[data1$defecttype==3]=0
data1$defecttype[data1$defecttype==6]=1
data1$defecttype[data1$defecttype==7]=1
data1$defecttype
data1
glmmodel1=glm(defecttype~ age+sex+Chestpain+rbp+serum+fbp+fendographic+maxHR+exericseInduced+oldpeak+slopepaekexce+vessels+Diseace,family = binomial(link = "logit"),data1)
summary(glmmodel1)
##Using the sub set values sex and disease
#glmmodel1=glm(defecttype~ sex+Diseace,family = binomial(link = "logit"),data1)
summary(glmmodel1)
#plot( data1$defecttype,data1$sex , xlab="sex", ylab="disease")
#lines(data1$age, glmmodel1$fitted, type="l", col="red", lwd=3)
#data1
plot(glmmodel1)
newdata1=c(data1$sex,data1$Diseace)
newdata1
#data1[2]
#data1[data1$sex,data1$Diseace]
#predict(glmmodel1,(12))
#new.df <- data.frame(sex=c(0,1),Disease=c(1,0))
predict(glmmodel1,newdata1=new)
data1$defecttype
| /Assigenment_2_2.R | no_license | manirox/LinearRegressions | R | false | false | 1,667 | r |
getwd()
setwd("/Users/manishreddybendhi/Desktop/Fun/Rprogramming/Assigenment2DataScience/Assigenment3")
getwd()
data1=read.table("heart.dat",header = TRUE)
head(data1)
data1
colnames(data1)=c("age","sex","Chestpain","rbp","serum","fbp","fendographic","maxHR","exericseInduced","oldpeak","slopepaekexce","vessels","defecttype","Diseace")
#data1$Diseace=as.integer(data1$Diseace)
data1
#glmmodel1=glm(Diseace~ age+sex+Chestpain+rbp+serum+fbp+fendographic+maxHR+exericseInduced+oldpeak+slopepaekexce+vessels+defecttype+Diseace,family = binomial(link = "logit"),data1)
#glmmodel1=glm(Diseace ~ age+sex,family = binomial(link = "logit"),data1)
#glmmodel1=glm(X2 ~ X3.0.1+X3.0+X2.0.1+X2.4+X0.0.1+X109.0+X2.0+X0.0+X322.0+X130.0+X4.0+X1.0+X70.0,family = binomial(link = "logit"),data1)
#Setting the value of defect type to 3
data1$defecttype[data1$defecttype==3]=0
data1$defecttype[data1$defecttype==6]=1
data1$defecttype[data1$defecttype==7]=1
data1$defecttype
data1
glmmodel1=glm(defecttype~ age+sex+Chestpain+rbp+serum+fbp+fendographic+maxHR+exericseInduced+oldpeak+slopepaekexce+vessels+Diseace,family = binomial(link = "logit"),data1)
summary(glmmodel1)
##Using the sub set values sex and disease
#glmmodel1=glm(defecttype~ sex+Diseace,family = binomial(link = "logit"),data1)
summary(glmmodel1)
#plot( data1$defecttype,data1$sex , xlab="sex", ylab="disease")
#lines(data1$age, glmmodel1$fitted, type="l", col="red", lwd=3)
#data1
plot(glmmodel1)
newdata1=c(data1$sex,data1$Diseace)
newdata1
#data1[2]
#data1[data1$sex,data1$Diseace]
#predict(glmmodel1,(12))
#new.df <- data.frame(sex=c(0,1),Disease=c(1,0))
predict(glmmodel1,newdata1=new)
data1$defecttype
|
#' Mixed Random Forest
#'
#' The function to fit a random forest with random effects.
#'
#' @param Y The outcome variable.
#' @param X A data frame or matrix contains the predictors.
#' @param random A string in lme4 format indicates the random effect model.
#' @param data The data set as a data frame.
#' @param initialRandomEffects The initial values for random effects.
#' @param ErrorTolerance The tolerance for log-likelihood.
#' @param MaxIterations The maximum iteration times.
#'
#' @return A list contains the random forest ($forest), mixed model ($MixedModel), and random effects ($RandomEffects).
#' See the example below for the usage.
#' @export
#' @import randomForest lme4
#' @examples
#'
#' data(sleepstudy)
#'
#' tmp = MixRF(Y=sleepstudy$Reaction, X=as.data.frame(sleepstudy$Days), random='(Days|Subject)',
#' data=sleepstudy, initialRandomEffects=0, ErrorTolerance=0.01, MaxIterations=100)
#'
#' # tmp$forest
#'
#' # tmp$MixedModel
#'
#' # tmp$RandomEffects
MixRF = function(Y, X, random, data, initialRandomEffects=0,
ErrorTolerance=0.001, MaxIterations=1000) {
Target = Y
# Condition that indicates the loop has not converged or run out of iterations
ContinueCondition = TRUE
iterations <- 0
# Get initial values
AdjustedTarget <- Target - initialRandomEffects
oldLogLik <- -Inf
while(ContinueCondition){
iterations <- iterations+1
# randomForest
rf = randomForest(X, AdjustedTarget)
# y - X*beta (out-of-bag prediction)
resi = Target - rf$predicted
## Estimate New Random Effects and Errors using lmer
f0 = as.formula(paste0('resi ~ -1 + ',random))
lmefit <- lmer(f0, data=data)
# check convergence
newLogLik <- as.numeric(logLik(lmefit))
ContinueCondition <- (abs(newLogLik-oldLogLik)>ErrorTolerance & iterations < MaxIterations)
oldLogLik <- newLogLik
# Extract random effects to make the new adjusted target
AllEffects <- predict(lmefit)
# y-Zb
AdjustedTarget <- Target - AllEffects
}
result <- list(forest=rf, MixedModel=lmefit, RandomEffects=ranef(lmefit),
IterationsUsed=iterations)
return(result)
}
| /MixRF/R/MixRF.r | no_license | ingted/R-Examples | R | false | false | 2,259 | r | #' Mixed Random Forest
#'
#' The function to fit a random forest with random effects.
#'
#' @param Y The outcome variable.
#' @param X A data frame or matrix contains the predictors.
#' @param random A string in lme4 format indicates the random effect model.
#' @param data The data set as a data frame.
#' @param initialRandomEffects The initial values for random effects.
#' @param ErrorTolerance The tolerance for log-likelihood.
#' @param MaxIterations The maximum iteration times.
#'
#' @return A list contains the random forest ($forest), mixed model ($MixedModel), and random effects ($RandomEffects).
#' See the example below for the usage.
#' @export
#' @import randomForest lme4
#' @examples
#'
#' data(sleepstudy)
#'
#' tmp = MixRF(Y=sleepstudy$Reaction, X=as.data.frame(sleepstudy$Days), random='(Days|Subject)',
#' data=sleepstudy, initialRandomEffects=0, ErrorTolerance=0.01, MaxIterations=100)
#'
#' # tmp$forest
#'
#' # tmp$MixedModel
#'
#' # tmp$RandomEffects
MixRF = function(Y, X, random, data, initialRandomEffects=0,
ErrorTolerance=0.001, MaxIterations=1000) {
Target = Y
# Condition that indicates the loop has not converged or run out of iterations
ContinueCondition = TRUE
iterations <- 0
# Get initial values
AdjustedTarget <- Target - initialRandomEffects
oldLogLik <- -Inf
while(ContinueCondition){
iterations <- iterations+1
# randomForest
rf = randomForest(X, AdjustedTarget)
# y - X*beta (out-of-bag prediction)
resi = Target - rf$predicted
## Estimate New Random Effects and Errors using lmer
f0 = as.formula(paste0('resi ~ -1 + ',random))
lmefit <- lmer(f0, data=data)
# check convergence
newLogLik <- as.numeric(logLik(lmefit))
ContinueCondition <- (abs(newLogLik-oldLogLik)>ErrorTolerance & iterations < MaxIterations)
oldLogLik <- newLogLik
# Extract random effects to make the new adjusted target
AllEffects <- predict(lmefit)
# y-Zb
AdjustedTarget <- Target - AllEffects
}
result <- list(forest=rf, MixedModel=lmefit, RandomEffects=ranef(lmefit),
IterationsUsed=iterations)
return(result)
}
|
grades <- read.table ("gradesW4315.dat", header=T)
midterm <- grades[,"Midterm"]
final <- grades[,"Final"]
lm.1 <- lm (final ~ midterm)
display (lm.1)
n <- length (final)
X <- cbind (rep(1,n), midterm)
predicted <- X %*% beta.hat(lm.1)
resid <- final - predicted
postscript ("c:/books/multilevel/fakeresid1a.ps", height=3.8, width=4.5)
plot (predicted, resid, xlab="predicted value", ylab="residual", main="Residuals vs.\ predicted values", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
postscript ("c:/books/multilevel/fakeresid1b.ps", height=3.8, width=4.5)
plot (final, resid, xlab="observed value", ylab="residual", main="Residuals vs.\ observed values", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
# now simulate fake data
a <- 65
b <- 0.7
sigma <- 15
y.fake <- a + b*midterm + rnorm (n, 0, 15)
lm.fake <- lm (y.fake ~ midterm)
predicted.fake <- X %*% beta.hat(lm.fake)
resid.fake <- y.fake - predicted.fake
postscript ("c:/books/multilevel/fakeresid2a.ps", height=3.8, width=4.5)
plot (predicted.fake, resid.fake, xlab="predicted value", ylab="residual", main="Fake data: resids vs.\ predicted", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
postscript ("c:/books/multilevel/fakeresid2b.ps", height=3.8, width=4.5)
plot (y.fake, resid.fake, xlab="observed value", ylab="residual", main="Fake data: resids vs.\ observed", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
| /Gelman_BDA_ARM/doc/arm2/simulation/fakeresid.R | no_license | burakbayramli/books | R | false | false | 1,689 | r | grades <- read.table ("gradesW4315.dat", header=T)
midterm <- grades[,"Midterm"]
final <- grades[,"Final"]
lm.1 <- lm (final ~ midterm)
display (lm.1)
n <- length (final)
X <- cbind (rep(1,n), midterm)
predicted <- X %*% beta.hat(lm.1)
resid <- final - predicted
postscript ("c:/books/multilevel/fakeresid1a.ps", height=3.8, width=4.5)
plot (predicted, resid, xlab="predicted value", ylab="residual", main="Residuals vs.\ predicted values", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
postscript ("c:/books/multilevel/fakeresid1b.ps", height=3.8, width=4.5)
plot (final, resid, xlab="observed value", ylab="residual", main="Residuals vs.\ observed values", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
# now simulate fake data
a <- 65
b <- 0.7
sigma <- 15
y.fake <- a + b*midterm + rnorm (n, 0, 15)
lm.fake <- lm (y.fake ~ midterm)
predicted.fake <- X %*% beta.hat(lm.fake)
resid.fake <- y.fake - predicted.fake
postscript ("c:/books/multilevel/fakeresid2a.ps", height=3.8, width=4.5)
plot (predicted.fake, resid.fake, xlab="predicted value", ylab="residual", main="Fake data: resids vs.\ predicted", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
postscript ("c:/books/multilevel/fakeresid2b.ps", height=3.8, width=4.5)
plot (y.fake, resid.fake, xlab="observed value", ylab="residual", main="Fake data: resids vs.\ observed", mgp=c(1.5,.5,0), pch=20, yaxt="n")
axis (2, seq(-40,40,20), mgp=c(1.5,.5,0))
abline (0, 0, col="gray", lwd=.5)
dev.off()
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
class.output = "output",
class.message = "message"
)
## ----setup--------------------------------------------------------------------
library(EValue)
| /inst/doc/selection-bias.R | no_license | cran/EValue | R | false | false | 297 | r | ## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
class.output = "output",
class.message = "message"
)
## ----setup--------------------------------------------------------------------
library(EValue)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/civis_ml_workflows.R
\name{civis_ml_extra_trees_classifier}
\alias{civis_ml_extra_trees_classifier}
\title{CivisML Extra Trees Classifier}
\usage{
civis_ml_extra_trees_classifier(x, dependent_variable, primary_key = NULL,
excluded_columns = NULL, n_estimators = 500, criterion = c("gini",
"entropy"), max_depth = NULL, min_samples_split = 2,
min_samples_leaf = 1, min_weight_fraction_leaf = 0,
max_features = "sqrt", max_leaf_nodes = NULL,
min_impurity_split = 1e-07, bootstrap = FALSE, random_state = 42,
class_weight = NULL, fit_params = NULL,
cross_validation_parameters = NULL, calibration = NULL,
oos_scores_table = NULL, oos_scores_db = NULL,
oos_scores_if_exists = c("fail", "append", "drop", "truncate"),
model_name = NULL, cpu_requested = NULL, memory_requested = NULL,
disk_requested = NULL, notifications = NULL, polling_interval = NULL,
verbose = FALSE)
}
\arguments{
\item{x}{See the Data Sources section below.}
\item{dependent_variable}{The dependent variable of the training dataset.
For a multi-target problem, this should be a vector of column names of
dependent variables. Nulls in a single dependent variable will
automatically be dropped.}
\item{primary_key}{Optional, the unique ID (primary key) of the training
dataset. This will be used to index the out-of-sample scores. In
\code{predict.civis_ml}, the primary_key of the training task is used by
default \code{primary_key = NA}. Use \code{primary_key = NULL} to
explicitly indicate the data have no primary_key.}
\item{excluded_columns}{Optional, a vector of columns which will be
considered ineligible to be independent variables.}
\item{n_estimators}{The number of boosting stages to perform. Gradient
boosting is fairly robust to over-fitting, so a large number usually
results in better predictive performance.}
\item{criterion}{The function to measure the quality of a split. Supported
criteria are \code{gini} for the Gini impurity and \code{entropy} for the
information gain.}
\item{max_depth}{Maximum depth of the individual regression estimators. The
maximum depth limits the number of nodes in the tree. Tune this parameter
for best performance. The best value depends on the interaction of the
input variables.}
\item{min_samples_split}{The minimum number of samples required to split
an internal node. If an integer, then consider \code{min_samples_split}
as the minimum number. If a float, then \code{min_samples_split} is a
percentage and \code{ceiling(min_samples_split * n_samples)} are the
minimum number of samples for each split.}
\item{min_samples_leaf}{The minimum number of samples required to be in
a leaf node. If an integer, then consider \code{min_samples_leaf} as the
minimum number. If a float, the \code{min_samples_leaf} is a percentage
and \code{ceiling(min_samples_leaf * n_samples)} are the minimum number
of samples for each leaf node.}
\item{min_weight_fraction_leaf}{The minimum weighted fraction of the sum
total of weights required to be at a leaf node.}
\item{max_features}{The number of features to consider when looking for the
best split.
\describe{
\item{integer}{consider \code{max_features} at each split.}
\item{float}{then \code{max_features} is a percentage and
\code{max_features * n_features} are considered at each split.}
\item{auto}{then \code{max_features = sqrt(n_features)}}
\item{sqrt}{then \code{max_features = sqrt(n_features)}}
\item{log2}{then \code{max_features = log2(n_features)}}
\item{NULL}{then \code{max_features = n_features}}
}}
\item{max_leaf_nodes}{Grow trees with \code{max_leaf_nodes} in best-first
fashion. Best nodes are defined as relative reduction to impurity. If
\code{max_leaf_nodes = NULL} then unlimited number of leaf nodes.}
\item{min_impurity_split}{Threshold for early stopping in tree growth. A node
will split if its impurity is above the threshold, otherwise it is a leaf.}
\item{bootstrap}{Whether bootstrap samples are used when building trees.}
\item{random_state}{The seed of the random number generator.}
\item{class_weight}{A \code{list} with \code{class_label = value} pairs, or
\code{balanced}. When \code{class_weight = "balanced"}, the class weights
will be inversely proportional to the class frequencies in the input data
as:
\deqn{ \frac{n_samples}{n_classes * table(y)} }
Note, the class weights are multiplied with \code{sample_weight}
(passed via \code{fit_params}) if \code{sample_weight} is specified.}
\item{fit_params}{Optional, a mapping from parameter names in the model's
\code{fit} method to the column names which hold the data, e.g.
\code{list(sample_weight = 'survey_weight_column')}.}
\item{cross_validation_parameters}{Optional, parameter grid for learner
parameters, e.g. \code{list(n_estimators = c(100, 200, 500),
learning_rate = c(0.01, 0.1), max_depth = c(2, 3))}
or \code{"hyperband"} for supported models.}
\item{calibration}{Optional, if not \code{NULL}, calibrate output
probabilities with the selected method, \code{sigmoid}, or \code{isotonic}.
Valid only with classification models.}
\item{oos_scores_table}{Optional, if provided, store out-of-sample
predictions on training set data to this Redshift "schema.tablename".}
\item{oos_scores_db}{Optional, the name of the database where the
\code{oos_scores_table} will be created. If not provided, this will default
to \code{database_name}.}
\item{oos_scores_if_exists}{Optional, action to take if
\code{oos_scores_table} already exists. One of \code{"fail"}, \code{"append"}, \code{"drop"}, or \code{"truncate"}.
The default is \code{"fail"}.}
\item{model_name}{Optional, the prefix of the Platform modeling jobs.
It will have \code{" Train"} or \code{" Predict"} added to become the Script title.}
\item{cpu_requested}{Optional, the number of CPU shares requested in the
Civis Platform for training jobs or prediction child jobs.
1024 shares = 1 CPU.}
\item{memory_requested}{Optional, the memory requested from Civis Platform
for training jobs or prediction child jobs, in MiB.}
\item{disk_requested}{Optional, the disk space requested on Civis Platform
for training jobs or prediction child jobs, in GB.}
\item{notifications}{Optional, model status notifications. See
\code{\link{scripts_post_custom}} for further documentation about email
and URL notification.}
\item{polling_interval}{Check for job completion every this number of seconds.}
\item{verbose}{Optional, If \code{TRUE}, supply debug outputs in Platform
logs and make prediction child jobs visible.}
}
\value{
A \code{civis_ml} object, a list containing the following elements:
\item{job}{job metadata from \code{\link{scripts_get_custom}}.}
\item{run}{run metadata from \code{\link{scripts_get_custom_runs}}.}
\item{outputs}{CivisML metadata from \code{\link{scripts_list_custom_runs_outputs}} containing the locations of
files produced by CivisML e.g. files, projects, metrics, model_info, logs, predictions, and estimators.}
\item{metrics}{Parsed CivisML output from \code{metrics.json} containing metadata from validation.
A list containing the following elements:
\itemize{
\item run list, metadata about the run.
\item data list, metadata about the training data.
\item model list, the fitted scikit-learn model with CV results.
\item metrics list, validation metrics (accuracy, confusion, ROC, AUC, etc).
\item warnings list.
\item data_platform list, training data location.
}}
\item{model_info}{Parsed CivisML output from \code{model_info.json} containing metadata from training.
A list containing the following elements:
\itemize{
\item run list, metadata about the run.
\item data list, metadata about the training data.
\item model list, the fitted scikit-learn model.
\item metrics empty list.
\item warnings list.
\item data_platform list, training data location.
}}
}
\description{
CivisML Extra Trees Classifier
}
\section{Data Sources}{
For building models with \code{civis_ml}, the training data can reside in
four different places, a file in the Civis Platform, a CSV or feather-format file
on the local disk, a \code{data.frame} resident in local the R environment, and finally,
a table in the Civis Platform. Use the following helpers to specify the
data source when calling \code{civis_ml}:
\describe{
\item{\code{data.frame}}{\code{civis_ml(x = df, ...)}}
\item{local csv file}{\code{civis_ml(x = "path/to/data.csv", ...)}}
\item{file in Civis Platform}{\code{civis_ml(x = civis_file(1234))}}
\item{table in Civis Platform}{\code{civis_ml(x = civis_table(table_name = "schema.table", database_name = "database"))}}
}
}
\examples{
\dontrun{
df <- iris
names(df) <- stringr::str_replace(names(df), "\\\\.", "_")
m <- civis_ml_extra_trees_classifier(df,
dependent_variable = "Species",
n_estimators = 100,
max_depth = 5,
max_features = NULL)
yhat <- fetch_oos_scores(m)
# Grid Search
cv_params <- list(
n_estimators = c(100, 200, 500),
max_depth = c(2, 3))
m <- civis_ml_extra_trees_classifier(df,
dependent_variable = "Species",
max_features = NULL,
cross_validation_parameters = cv_params)
pred_info <- predict(m, civis_table("schema.table", "my_database"),
output_table = "schema.scores_table")
}
}
| /man/civis_ml_extra_trees_classifier.Rd | no_license | JosiahParry/civis-r | R | false | true | 9,290 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/civis_ml_workflows.R
\name{civis_ml_extra_trees_classifier}
\alias{civis_ml_extra_trees_classifier}
\title{CivisML Extra Trees Classifier}
\usage{
civis_ml_extra_trees_classifier(x, dependent_variable, primary_key = NULL,
excluded_columns = NULL, n_estimators = 500, criterion = c("gini",
"entropy"), max_depth = NULL, min_samples_split = 2,
min_samples_leaf = 1, min_weight_fraction_leaf = 0,
max_features = "sqrt", max_leaf_nodes = NULL,
min_impurity_split = 1e-07, bootstrap = FALSE, random_state = 42,
class_weight = NULL, fit_params = NULL,
cross_validation_parameters = NULL, calibration = NULL,
oos_scores_table = NULL, oos_scores_db = NULL,
oos_scores_if_exists = c("fail", "append", "drop", "truncate"),
model_name = NULL, cpu_requested = NULL, memory_requested = NULL,
disk_requested = NULL, notifications = NULL, polling_interval = NULL,
verbose = FALSE)
}
\arguments{
\item{x}{See the Data Sources section below.}
\item{dependent_variable}{The dependent variable of the training dataset.
For a multi-target problem, this should be a vector of column names of
dependent variables. Nulls in a single dependent variable will
automatically be dropped.}
\item{primary_key}{Optional, the unique ID (primary key) of the training
dataset. This will be used to index the out-of-sample scores. In
\code{predict.civis_ml}, the primary_key of the training task is used by
default \code{primary_key = NA}. Use \code{primary_key = NULL} to
explicitly indicate the data have no primary_key.}
\item{excluded_columns}{Optional, a vector of columns which will be
considered ineligible to be independent variables.}
\item{n_estimators}{The number of boosting stages to perform. Gradient
boosting is fairly robust to over-fitting, so a large number usually
results in better predictive performance.}
\item{criterion}{The function to measure the quality of a split. Supported
criteria are \code{gini} for the Gini impurity and \code{entropy} for the
information gain.}
\item{max_depth}{Maximum depth of the individual regression estimators. The
maximum depth limits the number of nodes in the tree. Tune this parameter
for best performance. The best value depends on the interaction of the
input variables.}
\item{min_samples_split}{The minimum number of samples required to split
an internal node. If an integer, then consider \code{min_samples_split}
as the minimum number. If a float, then \code{min_samples_split} is a
percentage and \code{ceiling(min_samples_split * n_samples)} are the
minimum number of samples for each split.}
\item{min_samples_leaf}{The minimum number of samples required to be in
a leaf node. If an integer, then consider \code{min_samples_leaf} as the
minimum number. If a float, the \code{min_samples_leaf} is a percentage
and \code{ceiling(min_samples_leaf * n_samples)} are the minimum number
of samples for each leaf node.}
\item{min_weight_fraction_leaf}{The minimum weighted fraction of the sum
total of weights required to be at a leaf node.}
\item{max_features}{The number of features to consider when looking for the
best split.
\describe{
\item{integer}{consider \code{max_features} at each split.}
\item{float}{then \code{max_features} is a percentage and
\code{max_features * n_features} are considered at each split.}
\item{auto}{then \code{max_features = sqrt(n_features)}}
\item{sqrt}{then \code{max_features = sqrt(n_features)}}
\item{log2}{then \code{max_features = log2(n_features)}}
\item{NULL}{then \code{max_features = n_features}}
}}
\item{max_leaf_nodes}{Grow trees with \code{max_leaf_nodes} in best-first
fashion. Best nodes are defined as relative reduction to impurity. If
\code{max_leaf_nodes = NULL} then unlimited number of leaf nodes.}
\item{min_impurity_split}{Threshold for early stopping in tree growth. A node
will split if its impurity is above the threshold, otherwise it is a leaf.}
\item{bootstrap}{Whether bootstrap samples are used when building trees.}
\item{random_state}{The seed of the random number generator.}
\item{class_weight}{A \code{list} with \code{class_label = value} pairs, or
\code{balanced}. When \code{class_weight = "balanced"}, the class weights
will be inversely proportional to the class frequencies in the input data
as:
\deqn{ \frac{n_samples}{n_classes * table(y)} }
Note, the class weights are multiplied with \code{sample_weight}
(passed via \code{fit_params}) if \code{sample_weight} is specified.}
\item{fit_params}{Optional, a mapping from parameter names in the model's
\code{fit} method to the column names which hold the data, e.g.
\code{list(sample_weight = 'survey_weight_column')}.}
\item{cross_validation_parameters}{Optional, parameter grid for learner
parameters, e.g. \code{list(n_estimators = c(100, 200, 500),
learning_rate = c(0.01, 0.1), max_depth = c(2, 3))}
or \code{"hyperband"} for supported models.}
\item{calibration}{Optional, if not \code{NULL}, calibrate output
probabilities with the selected method, \code{sigmoid}, or \code{isotonic}.
Valid only with classification models.}
\item{oos_scores_table}{Optional, if provided, store out-of-sample
predictions on training set data to this Redshift "schema.tablename".}
\item{oos_scores_db}{Optional, the name of the database where the
\code{oos_scores_table} will be created. If not provided, this will default
to \code{database_name}.}
\item{oos_scores_if_exists}{Optional, action to take if
\code{oos_scores_table} already exists. One of \code{"fail"}, \code{"append"}, \code{"drop"}, or \code{"truncate"}.
The default is \code{"fail"}.}
\item{model_name}{Optional, the prefix of the Platform modeling jobs.
It will have \code{" Train"} or \code{" Predict"} added to become the Script title.}
\item{cpu_requested}{Optional, the number of CPU shares requested in the
Civis Platform for training jobs or prediction child jobs.
1024 shares = 1 CPU.}
\item{memory_requested}{Optional, the memory requested from Civis Platform
for training jobs or prediction child jobs, in MiB.}
\item{disk_requested}{Optional, the disk space requested on Civis Platform
for training jobs or prediction child jobs, in GB.}
\item{notifications}{Optional, model status notifications. See
\code{\link{scripts_post_custom}} for further documentation about email
and URL notification.}
\item{polling_interval}{Check for job completion every this number of seconds.}
\item{verbose}{Optional, If \code{TRUE}, supply debug outputs in Platform
logs and make prediction child jobs visible.}
}
\value{
A \code{civis_ml} object, a list containing the following elements:
\item{job}{job metadata from \code{\link{scripts_get_custom}}.}
\item{run}{run metadata from \code{\link{scripts_get_custom_runs}}.}
\item{outputs}{CivisML metadata from \code{\link{scripts_list_custom_runs_outputs}} containing the locations of
files produced by CivisML e.g. files, projects, metrics, model_info, logs, predictions, and estimators.}
\item{metrics}{Parsed CivisML output from \code{metrics.json} containing metadata from validation.
A list containing the following elements:
\itemize{
\item run list, metadata about the run.
\item data list, metadata about the training data.
\item model list, the fitted scikit-learn model with CV results.
\item metrics list, validation metrics (accuracy, confusion, ROC, AUC, etc).
\item warnings list.
\item data_platform list, training data location.
}}
\item{model_info}{Parsed CivisML output from \code{model_info.json} containing metadata from training.
A list containing the following elements:
\itemize{
\item run list, metadata about the run.
\item data list, metadata about the training data.
\item model list, the fitted scikit-learn model.
\item metrics empty list.
\item warnings list.
\item data_platform list, training data location.
}}
}
\description{
CivisML Extra Trees Classifier
}
\section{Data Sources}{
For building models with \code{civis_ml}, the training data can reside in
four different places, a file in the Civis Platform, a CSV or feather-format file
on the local disk, a \code{data.frame} resident in local the R environment, and finally,
a table in the Civis Platform. Use the following helpers to specify the
data source when calling \code{civis_ml}:
\describe{
\item{\code{data.frame}}{\code{civis_ml(x = df, ...)}}
\item{local csv file}{\code{civis_ml(x = "path/to/data.csv", ...)}}
\item{file in Civis Platform}{\code{civis_ml(x = civis_file(1234))}}
\item{table in Civis Platform}{\code{civis_ml(x = civis_table(table_name = "schema.table", database_name = "database"))}}
}
}
\examples{
\dontrun{
df <- iris
names(df) <- stringr::str_replace(names(df), "\\\\.", "_")
m <- civis_ml_extra_trees_classifier(df,
dependent_variable = "Species",
n_estimators = 100,
max_depth = 5,
max_features = NULL)
yhat <- fetch_oos_scores(m)
# Grid Search
cv_params <- list(
n_estimators = c(100, 200, 500),
max_depth = c(2, 3))
m <- civis_ml_extra_trees_classifier(df,
dependent_variable = "Species",
max_features = NULL,
cross_validation_parameters = cv_params)
pred_info <- predict(m, civis_table("schema.table", "my_database"),
output_table = "schema.scores_table")
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/transmission_chain_map.R
\name{transmission_chains_map}
\alias{transmission_chains_map}
\title{transmission_chain_map}
\usage{
transmission_chains_map(geocoded_dataset, cve_edo, locality, dengue_cases)
}
\arguments{
\item{geocoded_dataset}{is the dengue geocoded dataset.}
\item{cve_edo}{is the id of state.}
\item{locality}{is the target locality}
\item{dengue_cases}{is string for define the positive of suspected dengue cases}
}
\value{
a mapview
}
\description{
the function generate the space-time links map with mapview package.
}
\examples{
1+1
}
\author{
Felipe Antonio Dzul Manzanilla \email{felipe.dzul.m@gmail.com}
}
| /man/transmission_chains_map.Rd | permissive | fdzul/denhotspots | R | false | true | 709 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/transmission_chain_map.R
\name{transmission_chains_map}
\alias{transmission_chains_map}
\title{transmission_chain_map}
\usage{
transmission_chains_map(geocoded_dataset, cve_edo, locality, dengue_cases)
}
\arguments{
\item{geocoded_dataset}{is the dengue geocoded dataset.}
\item{cve_edo}{is the id of state.}
\item{locality}{is the target locality}
\item{dengue_cases}{is string for define the positive of suspected dengue cases}
}
\value{
a mapview
}
\description{
the function generate the space-time links map with mapview package.
}
\examples{
1+1
}
\author{
Felipe Antonio Dzul Manzanilla \email{felipe.dzul.m@gmail.com}
}
|
# PLot 1 ------------------------------------------------------------------
load("household_power_consumption-subset.Rda")
png("plot1.png", height = 480, width = 480, units = "px")
hist(df$global_active_power,
col = "red",
xlim = c(0, 6),
ylim = c(0, 1200),
xlab = "Global Active Power (kilowatts)",
main = "Global Active Power")
dev.off()
| /plot1.R | no_license | KevinHeron/ExData_Plotting1 | R | false | false | 373 | r | # PLot 1 ------------------------------------------------------------------
load("household_power_consumption-subset.Rda")
png("plot1.png", height = 480, width = 480, units = "px")
hist(df$global_active_power,
col = "red",
xlim = c(0, 6),
ylim = c(0, 1200),
xlab = "Global Active Power (kilowatts)",
main = "Global Active Power")
dev.off()
|
# set directory
setwd('/Volumes/GoogleDrive/내 드라이브/학교 수업/20-1학기/데이터마이닝/data')
# load data
df = read.csv('creditcard.csv')
head(df)
dim(df)
# unbalance data
# 이상치가 부정하지 않은 사람에게 당연히 많을 수 밖에 없다. 따라서 그것을 감안해서 boxplot을 보도록 하자.
a = table(df$Class)
a['1']/(a['0']+a['1'])
a['0']/(a['0']+a['1'])
barplot(a)
# check V1~V28, time and amount
boxplot(formula = Time~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="Time vs Class")
# V1의 경우 부정한 사람이 평균적으로 더 낮은 것을 볼 수 있다. 그러나 부정하지 않은 사람의 경우 대부분 0에 가깝다.
boxplot(formula = V1~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V1 vs Class")
# V2의 경우 부정한 사람은 0보다 조금 높게 평균이 형성되어 있다. 부정하지 않은 사람의 경우 평균이 0에 가깝다.
# 모델에서는 이 변수가 나름 유의미하다고 나왔다.
boxplot(formula = V2~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V2 vs Class")
# V3의 경우 부정한 사람은 0 이하에 대부분 형성되어 있는 것을 볼 수 있고, 부정하지 않은 사람의 경우 대부분 0에 가깝게 분포해 있다.
boxplot(formula = V3~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V3 vs Class")
# V4의 경우 부정한 사람은 5애 가깝게 분포되어 있고, 부정하지 않은 사람의 경우 0에 가깝게 분포되어 있다. 특이한 점이 있다면 부정한 사람의 경우 이상치가 없지만, 부정하지 않은 사람은 이상치가 많이 존재하는 것을 볼 수 있다.
# 예상한대로 매우 유의미한 변수로 나왔다.
boxplot(formula = V4~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V4 vs Class")
# V5의 경우 엄청 큰 차이를 보이고 있지는 않지만 부정한 사람이 부정하지 않은 사람보다 조금 더 낮게 형성되어 있다.
# 모델에서는 매우 유의미한 변수로 채택되었다.
boxplot(formula = V5~Class, data = df
, col=c("yellow","green"),
ylim = c(-50,10),
xlab="Class",
main="V5 vs Class")
# V6의 경우 둘 다 0에 가깝게 분포되어 있는 것을 볼 수 있다.
boxplot(formula = V6~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-20,20),
main="V6 vs Class")
# V7의 경우 부정한 사람들이 좀 더 낮게 형성되어 있는 것을 볼 수 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
boxplot(formula = V7~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-40,40),
main="V7 vs Class")
# V8의 경우 둘이 큰 차이를 보이고 있지는 않지만, 부정한 사람들이 좀 더 넓게 분포하고 있는 것을 볼 수 있다.
# 모델에서는 매우 유의미하게 나왔다. 아마 분포의 차이가 많이 나서 그런듯 하다.
boxplot(formula = V8~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-10,10),
main="V8 vs Class")
# V9의 경우 부정한 사람들이 0보다 낮게 형성되어 있는 것을 볼 수 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
boxplot(formula = V9~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V9 vs Class")
# V10의 경우 부정한 사람들은 0보다 낮게 형성되어 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
# 예상한대로 모델에서 유의미한 변수로 채택했다.
boxplot(formula = V10~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V10 vs Class")
# V11의 경우 부정한 사람들은 0보다 크게 형성되어 있고, 5애 더 가깝다. 반명 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
boxplot(formula = V11~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V11 vs Class")
# V12의 경우 부정한 사람들은 -5에 가깝게 형성되어 있다. 반명 부정하지 않은 사람은 0에 가깝게 형성되 있다.
# 예상한대로 모델에서 유의미한 변수로 채택했다. 그러나 분포에 비하면 pvalue가 생각보다 조금 높게 나왔다.
boxplot(formula = V12~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V12 vs Class")
# V13의 경우 둘이 큰 차이를 보이고 있지 않다.
# 분포에서는 큰 차이를 보이고 있지 않지만 매우 유의미하다고 나왔다.
boxplot(formula = V13~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-4,4),
main="V13 vs Class")
# V14의 경우 부정한 사람은 -6~-7에 가깝게 형성되어 있다. 반면 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
# 예상한대로 매우 유의미하게 나왔다.
boxplot(formula = V14~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V14 vs Class")
# V15의 경우 큰 차이를 보이고 있지 않다.
boxplot(formula = V15~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V15 vs Class")
# V16의 경우 부정한 사람은 -3에 가깝게 형성되어 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다. 부정한 사람에게는 이상치가 없지만, 부정하지 않은 사람의 경우 위 아래로 이상치가 존재.
# 예상한대로 매우 유의미하게 나왔다.
boxplot(formula = V16~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V16 vs Class")
# V17의 경우 부정한 사람은 -5에 가깝게 형성되어 있지만, -10까지도 많은 분포를 가지고 있는 것을 볼 수 있다. 반면 부정하지 않은 사람은 0에 가깝게 형성되어 있다. 이 또한 부정하지 않은 사람에게만 이상치 존재.
boxplot(formula = V17~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V17 vs Class")
# V18의 경우 부정한 사람들은 0에서 -5 사이에 가장 많이 분포 되어있다. 부정하지 않은 사람은 0에 가깝게 분포하고 있다.
boxplot(formula = V18~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V18 vs Class")
# V19의 경우 극적인 차이가 보이지 않지만, 부정한 사람들이 좀 더 넓게 분포되어 있는 것을 볼 수 있다. 부정하지 않은 사람은 0에 가깝게 분포되어 있다.
boxplot(formula = V19~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V19 vs Class")
# V20의 부정한 사람들이 좀 더 넓은 범위를 가지고 있다.
# 매우 유의미한 변수로 채택되었다.
boxplot(formula = V20~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim=c(-5,5),
main="V20 vs Class")
# V21의 경우 부정한 사람들이 좀 더 많은 분포를 가지고 있다.
# 매우 유의미한 변수로 채택되었다. 범위로 인한 차이가 있던것으로 보여짐.
boxplot(formula = V21~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-5,5),
main="V21 vs Class")
# V22의 경우에는 둘 다 거의 비슷하다.
# 거의 비슷한데... 왜 채택된걸까...
boxplot(formula = V22~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V22 vs Class")
# V23의 경우 거의 비슷하다.
boxplot(formula = V23~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-5,5),
main="V23 vs Class")
# V24의 경우 거의 비슷하다.
# 일단 채택은 됐지만, p-value가 높지 않다.
boxplot(formula = V24~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V24 vs Class")
# V25의 경우 거의 비슷하다.
boxplot(formula = V25~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-5,5),
main="V25 vs Class")
# V26의 경우 부정한 사람들이 좀 더 넓게 분포하고 있지만 유의미한 차이는 아니다.
boxplot(formula = V26~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V26 vs Class")
# V27의 경우 부정한 사람들이 더 넓게 분포하고 있기 때문에 꽤 유의미해 보인다.
# 예상대로 유의미하게 나왔다.
boxplot(formula = V27~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim=c(-2,3),
main="V27 vs Class")
# V28의 경우 부정한 사람들이 더 넓게 분포하고 있기 때문에 꽤 유의미해 보인다.
# 아마도 분포로 인해 뽑힌 거 같은데, 막 그렇다고 엄청 유의미하진 않다.
boxplot(formula = V28~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim=c(-2,2),
main="V28 vs Class")
# amount의 경우 둘 다 큰 차이가 없다. 단지 부정하지 않은 사람의 경우 이상치가 꽤 높다.
boxplot(formula = Amount~Class, data = df
, col=c("yellow","green"),
ylim=c(0,400),
xlab="Class",
main="Amount vs Class")
# 2번
summary(df)
# 3번
nobs=nrow(df)
set.seed(1234)
i = sample(1:nobs, round(nobs*0.7)) #70% for training data, 30% for testdata
train = df[i,]
test = df[-i,]
unique(train$Class)
unique(test$Class)
table(train$Class)
table(test$Class)
model_first = glm(Class~., family="binomial", data=train)
step_model_for = step(model_first, direction='forward')
step_model_back = step(model_first, direction='backward')
step_model_both = step(model_first, direction='both')
summary(model_first)
summary(step_model_for)
summary(step_model_back)
summary(step_model_both)
# f1 score로 모델 평가해서 최적의 모델을 찾을 것!
library(MLmetrics)
prob_pred1 = predict(model_first, newdata=test, type='response')
prob_pred2 = predict(step_model_for, newdata=test, type='response')
prob_pred3 = predict(step_model_back, newdata=test, type='response')
prob_pred4 = predict(step_model_both, newdata=test, type='response')
pred1 <- ifelse(prob_pred1 < 0.0017, 0, 1)
pred2 <- ifelse(prob_pred2 < 0.0017, 0, 1)
pred3 <- ifelse(prob_pred3 < 0.0017, 0, 1)
pred4 <- ifelse(prob_pred4 < 0.0017, 0, 1)
# forward는 원래 모델과 큰 차이 없지만, backward와 both는 약간의 성능 향상이 있었다.
# 여기서 both 모델 채택
F1_Score(y_pred = pred1, y_true = test$Class, positive = "1")
F1_Score(y_pred = pred2, y_true = test$Class, positive = "1")
F1_Score(y_pred = pred3, y_true = test$Class, positive = "1")
F1_Score(y_pred = pred4, y_true = test$Class, positive = "1")
# 4번
# 대부분 예상한대로 변수가 채택되었으나, 몇몇 변수를 보면 큰 차이가 없지만 유의미한 변수가 된 경우도 여럿 별 수 있다.
# 해석에 대한 지식 부족이거나 이상치에 대한 문제가 있을수도 있다. 이 부분은 따로 확인을 해봐야 될 것 같다.
# 5번
# p-value가 0.05 이하인 odds ratio를 해석하려고 한다.
exp(coef(step_model_both))
# V2가 1 증가하면 부정 사용자일 가능성이 약 1.1배 오르게 된다.
# V4가 1 증가하면 부정 사용자일 가능성이 약 2.2배 오르게 된다.
# V5가 1 증가하면 부정 사용자일 가능성이 약 1.2배 오르게 된다.
# V8가 1 증가하면 부정 사용자일 가능성이 약 0.9배 떨어지게 된다.
# V10가 1 증가하면 부정 사용자일 가능성이 약 0.42배 떨어지게 된다.
# V12가 1 증가하면 부정 사용자일 가능성이 약 1.2배 오르게 된다.
# V13가 1 증가하면 부정 사용자일 가능성이 약 0.7배 떨어지게 된다.
# V14가 1 증가하면 부정 사용자일 가능성이 약 0.6배 떨어지게 된다.
# V16가 1 증가하면 부정 사용자일 가능성이 약 0.7배 떨어지게 된다.
# V20이 1 증가하면 부정 사용자일 가능성이 약 0.7배 떨어지게 된다.
# V21이 1 증가하면 부정 사용자일 가능성이 약 1.4배 오르게 된다.
# V22이 1 증가하면 부정 사용자일 가능성이 약 1.8배 오르게 된다.
# V27이 1 증가하면 부정 사용자일 가능성이 약 0.6배 떨어지게 된다.
# Amount가 1 증가하면 부정 사용자일 가능성이 약 1.001배 오르게 된다.
# 6번
three_rd = apply(df, 2, quantile)
three_rd
q3 = three_rd['75%',]
q3 = q3[1:30]
q3 = data.frame(t(q3))
prob_pred5 = predict(step_model_both, newdata=q3, type='response')
prob_pred5
| /두번째 과제 코드.R | no_license | YooGunWook/DataMining | R | false | false | 12,889 | r | # set directory
setwd('/Volumes/GoogleDrive/내 드라이브/학교 수업/20-1학기/데이터마이닝/data')
# load data
df = read.csv('creditcard.csv')
head(df)
dim(df)
# unbalance data
# 이상치가 부정하지 않은 사람에게 당연히 많을 수 밖에 없다. 따라서 그것을 감안해서 boxplot을 보도록 하자.
a = table(df$Class)
a['1']/(a['0']+a['1'])
a['0']/(a['0']+a['1'])
barplot(a)
# check V1~V28, time and amount
boxplot(formula = Time~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="Time vs Class")
# V1의 경우 부정한 사람이 평균적으로 더 낮은 것을 볼 수 있다. 그러나 부정하지 않은 사람의 경우 대부분 0에 가깝다.
boxplot(formula = V1~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V1 vs Class")
# V2의 경우 부정한 사람은 0보다 조금 높게 평균이 형성되어 있다. 부정하지 않은 사람의 경우 평균이 0에 가깝다.
# 모델에서는 이 변수가 나름 유의미하다고 나왔다.
boxplot(formula = V2~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V2 vs Class")
# V3의 경우 부정한 사람은 0 이하에 대부분 형성되어 있는 것을 볼 수 있고, 부정하지 않은 사람의 경우 대부분 0에 가깝게 분포해 있다.
boxplot(formula = V3~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V3 vs Class")
# V4의 경우 부정한 사람은 5애 가깝게 분포되어 있고, 부정하지 않은 사람의 경우 0에 가깝게 분포되어 있다. 특이한 점이 있다면 부정한 사람의 경우 이상치가 없지만, 부정하지 않은 사람은 이상치가 많이 존재하는 것을 볼 수 있다.
# 예상한대로 매우 유의미한 변수로 나왔다.
boxplot(formula = V4~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V4 vs Class")
# V5의 경우 엄청 큰 차이를 보이고 있지는 않지만 부정한 사람이 부정하지 않은 사람보다 조금 더 낮게 형성되어 있다.
# 모델에서는 매우 유의미한 변수로 채택되었다.
boxplot(formula = V5~Class, data = df
, col=c("yellow","green"),
ylim = c(-50,10),
xlab="Class",
main="V5 vs Class")
# V6의 경우 둘 다 0에 가깝게 분포되어 있는 것을 볼 수 있다.
boxplot(formula = V6~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-20,20),
main="V6 vs Class")
# V7의 경우 부정한 사람들이 좀 더 낮게 형성되어 있는 것을 볼 수 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
boxplot(formula = V7~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-40,40),
main="V7 vs Class")
# V8의 경우 둘이 큰 차이를 보이고 있지는 않지만, 부정한 사람들이 좀 더 넓게 분포하고 있는 것을 볼 수 있다.
# 모델에서는 매우 유의미하게 나왔다. 아마 분포의 차이가 많이 나서 그런듯 하다.
boxplot(formula = V8~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-10,10),
main="V8 vs Class")
# V9의 경우 부정한 사람들이 0보다 낮게 형성되어 있는 것을 볼 수 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
boxplot(formula = V9~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V9 vs Class")
# V10의 경우 부정한 사람들은 0보다 낮게 형성되어 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
# 예상한대로 모델에서 유의미한 변수로 채택했다.
boxplot(formula = V10~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V10 vs Class")
# V11의 경우 부정한 사람들은 0보다 크게 형성되어 있고, 5애 더 가깝다. 반명 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
boxplot(formula = V11~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V11 vs Class")
# V12의 경우 부정한 사람들은 -5에 가깝게 형성되어 있다. 반명 부정하지 않은 사람은 0에 가깝게 형성되 있다.
# 예상한대로 모델에서 유의미한 변수로 채택했다. 그러나 분포에 비하면 pvalue가 생각보다 조금 높게 나왔다.
boxplot(formula = V12~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V12 vs Class")
# V13의 경우 둘이 큰 차이를 보이고 있지 않다.
# 분포에서는 큰 차이를 보이고 있지 않지만 매우 유의미하다고 나왔다.
boxplot(formula = V13~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-4,4),
main="V13 vs Class")
# V14의 경우 부정한 사람은 -6~-7에 가깝게 형성되어 있다. 반면 부정하지 않은 사람은 0에 가깝게 형성되어 있다.
# 예상한대로 매우 유의미하게 나왔다.
boxplot(formula = V14~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V14 vs Class")
# V15의 경우 큰 차이를 보이고 있지 않다.
boxplot(formula = V15~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V15 vs Class")
# V16의 경우 부정한 사람은 -3에 가깝게 형성되어 있다. 부정하지 않은 사람은 0에 가깝게 형성되어 있다. 부정한 사람에게는 이상치가 없지만, 부정하지 않은 사람의 경우 위 아래로 이상치가 존재.
# 예상한대로 매우 유의미하게 나왔다.
boxplot(formula = V16~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V16 vs Class")
# V17의 경우 부정한 사람은 -5에 가깝게 형성되어 있지만, -10까지도 많은 분포를 가지고 있는 것을 볼 수 있다. 반면 부정하지 않은 사람은 0에 가깝게 형성되어 있다. 이 또한 부정하지 않은 사람에게만 이상치 존재.
boxplot(formula = V17~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V17 vs Class")
# V18의 경우 부정한 사람들은 0에서 -5 사이에 가장 많이 분포 되어있다. 부정하지 않은 사람은 0에 가깝게 분포하고 있다.
boxplot(formula = V18~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V18 vs Class")
# V19의 경우 극적인 차이가 보이지 않지만, 부정한 사람들이 좀 더 넓게 분포되어 있는 것을 볼 수 있다. 부정하지 않은 사람은 0에 가깝게 분포되어 있다.
boxplot(formula = V19~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V19 vs Class")
# V20의 부정한 사람들이 좀 더 넓은 범위를 가지고 있다.
# 매우 유의미한 변수로 채택되었다.
boxplot(formula = V20~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim=c(-5,5),
main="V20 vs Class")
# V21의 경우 부정한 사람들이 좀 더 많은 분포를 가지고 있다.
# 매우 유의미한 변수로 채택되었다. 범위로 인한 차이가 있던것으로 보여짐.
boxplot(formula = V21~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-5,5),
main="V21 vs Class")
# V22의 경우에는 둘 다 거의 비슷하다.
# 거의 비슷한데... 왜 채택된걸까...
boxplot(formula = V22~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V22 vs Class")
# V23의 경우 거의 비슷하다.
boxplot(formula = V23~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-5,5),
main="V23 vs Class")
# V24의 경우 거의 비슷하다.
# 일단 채택은 됐지만, p-value가 높지 않다.
boxplot(formula = V24~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V24 vs Class")
# V25의 경우 거의 비슷하다.
boxplot(formula = V25~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim = c(-5,5),
main="V25 vs Class")
# V26의 경우 부정한 사람들이 좀 더 넓게 분포하고 있지만 유의미한 차이는 아니다.
boxplot(formula = V26~Class, data = df
, col=c("yellow","green"),
xlab="Class",
main="V26 vs Class")
# V27의 경우 부정한 사람들이 더 넓게 분포하고 있기 때문에 꽤 유의미해 보인다.
# 예상대로 유의미하게 나왔다.
boxplot(formula = V27~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim=c(-2,3),
main="V27 vs Class")
# V28의 경우 부정한 사람들이 더 넓게 분포하고 있기 때문에 꽤 유의미해 보인다.
# 아마도 분포로 인해 뽑힌 거 같은데, 막 그렇다고 엄청 유의미하진 않다.
boxplot(formula = V28~Class, data = df
, col=c("yellow","green"),
xlab="Class",
ylim=c(-2,2),
main="V28 vs Class")
# amount의 경우 둘 다 큰 차이가 없다. 단지 부정하지 않은 사람의 경우 이상치가 꽤 높다.
boxplot(formula = Amount~Class, data = df
, col=c("yellow","green"),
ylim=c(0,400),
xlab="Class",
main="Amount vs Class")
# 2번
summary(df)
# 3번
nobs=nrow(df)
set.seed(1234)
i = sample(1:nobs, round(nobs*0.7)) #70% for training data, 30% for testdata
train = df[i,]
test = df[-i,]
unique(train$Class)
unique(test$Class)
table(train$Class)
table(test$Class)
model_first = glm(Class~., family="binomial", data=train)
step_model_for = step(model_first, direction='forward')
step_model_back = step(model_first, direction='backward')
step_model_both = step(model_first, direction='both')
summary(model_first)
summary(step_model_for)
summary(step_model_back)
summary(step_model_both)
# f1 score로 모델 평가해서 최적의 모델을 찾을 것!
library(MLmetrics)
prob_pred1 = predict(model_first, newdata=test, type='response')
prob_pred2 = predict(step_model_for, newdata=test, type='response')
prob_pred3 = predict(step_model_back, newdata=test, type='response')
prob_pred4 = predict(step_model_both, newdata=test, type='response')
pred1 <- ifelse(prob_pred1 < 0.0017, 0, 1)
pred2 <- ifelse(prob_pred2 < 0.0017, 0, 1)
pred3 <- ifelse(prob_pred3 < 0.0017, 0, 1)
pred4 <- ifelse(prob_pred4 < 0.0017, 0, 1)
# forward는 원래 모델과 큰 차이 없지만, backward와 both는 약간의 성능 향상이 있었다.
# 여기서 both 모델 채택
F1_Score(y_pred = pred1, y_true = test$Class, positive = "1")
F1_Score(y_pred = pred2, y_true = test$Class, positive = "1")
F1_Score(y_pred = pred3, y_true = test$Class, positive = "1")
F1_Score(y_pred = pred4, y_true = test$Class, positive = "1")
# 4번
# 대부분 예상한대로 변수가 채택되었으나, 몇몇 변수를 보면 큰 차이가 없지만 유의미한 변수가 된 경우도 여럿 별 수 있다.
# 해석에 대한 지식 부족이거나 이상치에 대한 문제가 있을수도 있다. 이 부분은 따로 확인을 해봐야 될 것 같다.
# 5번
# p-value가 0.05 이하인 odds ratio를 해석하려고 한다.
exp(coef(step_model_both))
# V2가 1 증가하면 부정 사용자일 가능성이 약 1.1배 오르게 된다.
# V4가 1 증가하면 부정 사용자일 가능성이 약 2.2배 오르게 된다.
# V5가 1 증가하면 부정 사용자일 가능성이 약 1.2배 오르게 된다.
# V8가 1 증가하면 부정 사용자일 가능성이 약 0.9배 떨어지게 된다.
# V10가 1 증가하면 부정 사용자일 가능성이 약 0.42배 떨어지게 된다.
# V12가 1 증가하면 부정 사용자일 가능성이 약 1.2배 오르게 된다.
# V13가 1 증가하면 부정 사용자일 가능성이 약 0.7배 떨어지게 된다.
# V14가 1 증가하면 부정 사용자일 가능성이 약 0.6배 떨어지게 된다.
# V16가 1 증가하면 부정 사용자일 가능성이 약 0.7배 떨어지게 된다.
# V20이 1 증가하면 부정 사용자일 가능성이 약 0.7배 떨어지게 된다.
# V21이 1 증가하면 부정 사용자일 가능성이 약 1.4배 오르게 된다.
# V22이 1 증가하면 부정 사용자일 가능성이 약 1.8배 오르게 된다.
# V27이 1 증가하면 부정 사용자일 가능성이 약 0.6배 떨어지게 된다.
# Amount가 1 증가하면 부정 사용자일 가능성이 약 1.001배 오르게 된다.
# 6번
three_rd = apply(df, 2, quantile)
three_rd
q3 = three_rd['75%',]
q3 = q3[1:30]
q3 = data.frame(t(q3))
prob_pred5 = predict(step_model_both, newdata=q3, type='response')
prob_pred5
|
# Below are generators and helpers that create and manipulate ScoreTable objects
#' Score Table generator
#' @description A function to formally create an object of class Score Table.
#' @param confounders
#' For simple generation.
#' A character vector that declares derived components in the score table (1) or
#' a named list (2) whose names define the derived components in the score table and
#' whose values define their respective possible levels
#' @param scores
#' For simple generation.
#' A numeric vector that declares score for derived components using method (1) or
#' a named list whose names follow the derived component names defined in method (2) and
#' whose values define their respective possible scores
#' @param aliases
#' A named list that define a pretty representatives for defined confounders
#' following the structure of list(confounder = aliases).
#' Unmentioned confounders will be left intact.
#' @param custom_cases
#' A named list that define a sophisticated way to define confounders and scoring algorithm,
#' following the structure of list(name = list(formulas))
#' Each name is the name for derived confounders.
#' Each formula in each sub-list folllows the form of condition ~ score in a "specific to general" order.
#' This is based on \link[dplyr]{case_when}.
#' @return
#' An object of class ScoreTable.
#' When called with no data, this will print out the structure of the ScoreTable.
#' When called with data passed, this will return a data frame of class score_tbl.
#' @examples
#' charlson = ScoreTable(
#'confounders = c('myocardial_infarct', 'congestive_heart_failure', 'peripheral_vascular_disease',
#' 'cerebrovascular_disease', 'dementia', 'chronic_pulmonary_disease',
#' 'connective_tissue_disease', 'ulcer_disease', 'mild_liver_disease', 'diabetes',
#' 'hemiplegia', 'moderate_or_severe_renal_disease', 'diabetes_with_end_organ_damage', 'any_tumor',
#' 'moderate_or_severe_liver_disease', 'metastatic_solid_tumor', 'AIDS'),
#'scores = c(rep(1, 10), rep(2, 4), 3, 6, 6),
#'aliases = c('Myocardial infarction', 'Congestive heart failure', 'Peripheral vascular disease',
#' 'Cerebrovascular disease', 'Dementia', 'Chronic pulmonary disease',
#' 'Connective tissue disease', 'Ulcer disease', 'Mild liver disease', 'Diabetes',
#' 'Hemiplegia', 'Moderate or severe renal disease', 'Diabetes with end organ damage', 'any tumor',
#' 'Moderate or severe liver disease', 'Metastatic solid tumor', 'AIDS')
#')
#'
#'apache.ii <- ScoreTable(
#'aliases = list(temp ='Temperature', map ='Maximum Aterial Pressure',
#' hr = 'Heart Rate', rr = 'Respiratory Rate', aapo2 = 'AaPO2',
#' pao2 = 'PaO2', ph = 'PH', hco3 = 'HCO3-', sodium = 'Sodium', potassium = 'Potassium',
#' creatinine = 'Creatinine', hct = 'HCT', wbc = 'White-blood cell',
#' gcs = 'Glasgow Comma Score', age = 'Age', chronic = 'Chronic'),
#'custom_cases =
#' list(
#' temp = list(
#' temp >= 41 | temp < 30 ~ 4,
#' temp >= 39 | temp < 32 ~ 3,
#' temp < 34 ~ 2,
#' temp >= 38.5 | temp < 36 ~ 1,
#' !is.na(temp) ~ 0
#' ),
#' map = list(
#' map >= 160 | map < 50 ~ 4,
#' map >= 130 ~ 3,
#' map >= 110 | map < 70 ~ 2,
#' !is.na(map) ~ 0
#' ),
#' hr = list(
#' hr >= 180 | hr < 40 ~ 4,
#' hr >= 140 | hr < 55 ~ 3,
#' hr >= 110 | hr < 70 ~ 2,
#' !is.na(hr) ~ 0
#' ),
#' rr = list(
#' rr >= 50 | rr < 6 ~ 4,
#' rr >= 35 ~ 3,
#' rr < 10 ~ 2,
#' rr >= 25 | rr < 12 ~ 1,
#' !is.na(rr) ~ 0
#' ),
#' aapo2 = list(
#' fio2 < .5 | is.na(fio2) ~ 0,
#' aapo2 >= 500 ~ 5,
#' aapo2 >= 350 ~ 3,
#' aapo2 >= 200 ~ 2,
#' !is.na(aapo2) ~ 0
#' ),
#' pao2 = list(
#' fio2 >= .5 ~ 0,
#' pao2 < 55 ~ 4,
#' pao2 <= 60 ~ 3,
#' pao2 <= 70 ~ 1,
#' !is.na(pao2) ~ 0
#' ),
#' ph = list(
#' ph >= 7.7 | ph < 7.15 ~ 4,
#' ph >= 7.6 | ph < 7.25 ~ 3,
#' ph < 7.33 ~ 2,
#' ph >= 7.5 ~ 1,
#' TRUE ~ 0
#' ),
#' hco3 = list(
#' !is.na(ph) ~ 0,
#' hco3 >= 52 | hco3 < 15 ~ 4,
#' hco3 >= 41 | hco3 < 18 ~ 3,
#' hco3 < 22 ~ 2,
#' hco3 >= 32 ~ 1,
#' !is.na(hco3) ~ 0
#' ),
#' sodium = list(
#' sodium >= 180 | sodium <= 110 ~ 4,
#' sodium >= 160 | sodium < 120 ~ 3,
#' sodium >= 155 | sodium < 130 ~ 2,
#' sodium >= 150 ~ 1,
#' !is.na(sodium) ~ 0
#' ),
#' potassium = list(
#' potassium >= 7 | potassium < 2.5 ~ 4,
#' potassium >= 6 ~ 3,
#' potassium < 3 ~ 2,
#' potassium >= 5.5 | potassium < 3.5 ~ 1,
#' !is.na(potassium) ~ 0
#' ),
#' creatinine = list(
#' creatinine >= 3.5 ~ 4,
#' creatinine >= 2 ~ 3,
#' creatinine >= 1.5 | creatinine < .6 ~ 2,
#' !is.na(creatinine) ~ 0
#' ),
#' hct = list(
#' hct >= 60 | hct < 20 ~ 4,
#' hct >= 50 | hct < 30 ~ 2,
#' hct >= 46 ~ 1,
#' !is.na(hct) ~ 0
#' ),
#' wbc = list(
#' wbc >= 40 | wbc < 1 ~ 4,
#' wbc >= 20 | wbc < 3 ~ 2,
#' wbc >= 15 ~ 1,
#' !is.na(wbc) ~ 0
#' ),
#' gcs = list(
#' !is.na(gcs) ~ 15 - gcs
#' ),
#' age = list(
#' age >= 75 ~ 6,
#' age >= 65 ~ 5,
#' age >= 55 ~ 3,
#' age >= 45 ~ 2,
#' TRUE ~ 0
#' ),
#' chronic = list(
#' rowSums(liver, heart, lung, kidney) == 0 ~ 0,
#' as.logical(emergency) ~ 5,
#' as.logical(elective) ~ 2,
#' sum(elective, emergency, na.rm = TRUE) == 0 ~ 5
#' )
#' )
#')
#' @seealso
#' \link[dplyr]{case_when}, \link{as.data.frame.ScoreTable}, \link{apache.ii}, \link{summary.score_tbl}
#' @export
ScoreTable <- function(confounders, scores, aliases = NULL, custom_cases){
# First, we need to determine what we have
# A type of binary will only have two levels, while categorical will have more than 2
# Complex is a type where we have >1 conditional layers
type <- character()
.aliases <- character()
if (!missing(confounders) | !missing(scores)){
if (!(length(unlist(confounders)) == length(unlist(scores))))
stop('Length mismatched!')
if (is.character(confounders)) type <- 'binary' else type <- 'categorical'
if (type == 'categorical' & length(names(scores)) < length(confounders))
stop('Score must be named in multi-level conditions')
.aliases <-
if (type == 'binary') confounders
else unlist(lapply(seq_along(confounders),
function(i)
rep(names(confounders[i]), length(confounders[[i]]))))
# if (!length(names(aliases))){
# names(aliases) <- aliases
# aliases <- .aliases
# }
}
if (!missing(custom_cases)) type <- c(type, 'complex')
if ('complex'%in%type){
.aliases <- unique(c(.aliases, names(custom_cases)))
}
# browser()
.aliases <- unique(.aliases)
.aliases <-
if (length(aliases) & length(names(aliases))) dplyr::recode(.aliases, !!!aliases)
else dplyr::recode(.aliases, !!!structure(aliases, names = .aliases))
# browser()
#Construction condition tree from confounder and scores
if (!missing(confounders)){
conf <-
if ('binary' %in% type) structure(rep(TRUE, length(confounders)), names = confounders)
else confounders
if ('binary' %in% type) scores <- structure(scores, names = confounders)
simple_cases <- .tree_construct(conf, scores)
names(simple_cases$name) <- simple_cases$name
} else simple_cases <- NULL
if (!missing(custom_cases)){
# browser()
custom_cases_var <-
lapply(custom_cases, function(custom_case) {
out <- unique(unlist(lapply(custom_case, all.vars)))
out[!out %in% c('.', '.id')]
})
names(custom_cases_var) <- names(custom_cases)
custom_cases <- list(name = names(custom_cases),
var = custom_cases_var,
fml = custom_cases)
# cases <- c(simple_cases, custom_cases)
} else custom_cases <- NULL
cases <- list(name = c(simple_cases$name, custom_cases$name),
fml = c(simple_cases$fml, custom_cases$fml),
var = c(simple_cases$name, custom_cases$var))
# browser()
score_table <- structure(cases$fml,
names = cases$name,
score_names = paste(cases$name, 'score', sep = '_'),
vars = cases$var,
aliases = .aliases)
score_object <- structure(
function(data, id = names(data)[1], which = names(score_table),...){
if (missing(data)) get(deparse(sys.call()[[1]]))
else purrr::partial(.calc, score_table = score_table)(data, id, which, ...)
},
class = c('ScoreTable', 'function'),
fml = cases$fml,
name = cases$name,
score_name = paste(cases$name, 'score', sep = '_'),
alias = .aliases,
score_table = score_table
)
return(score_object)
}
.tree_construct <- function(conf, scores){
# browser()
conf_name <- names(conf)
conf_fml <-
lapply(conf_name,
function(.conf_name){
.conf <- unlist(conf[names(conf) == .conf_name])
.score <- unlist(scores[names(scores) == .conf_name])
c(
unlist(lapply(seq_along(.conf),
function(i){
as.formula(paste(.conf_name, '==', .conf[i], '~', .score[i]))
})),
as.formula(paste('!is.na(', .conf_name, ') ~ 0'))
)
})
names(conf_fml) <- conf_name
return(list(name = conf_name, fml = conf_fml))
}
#' A method to print out ScoreTable object
#' @description A method to print out ScoreTable object
#' @method print ScoreTable
#' @param x An object of class ScoreTable
#' @param pretty A logical value. Default = TRUE will print out the pretty version of the table.
#' @seealso \link{as.data.frame.ScoreTable}, \link{huxtable.ScoreTable}, \link{flextable.ScoreTable}
#' @export
print.ScoreTable <- function(x, pretty = TRUE,...){
print(as.data.frame(x, pretty = pretty))
}
#' A method to coerce ScoreTable object to analysable data frame
#' @description A method to coerce ScoreTable object to analysable data frame
#' @method as.data.frame ScoreTable
#' @param x An object of class ScoreTable
#' @param pretty A logical value. Default = FALSE will create a analysable version of the table.
#' @param ... Additional parameters passed to data.frame()
#' @seealso \link{print.ScoreTable}, \link{huxtable.ScoreTable}, \link{flextable.ScoreTable}
#' @export
as.data.frame.ScoreTable <- function(x, pretty = FALSE, ...){
score_table <- attr(x, 'score_table')
aliases <- attr(x, 'alias')
aliases.expand <- unlist(lapply(attr(x, 'name'),
function(name){
if (pretty)
c(aliases[attr(x, 'name') == name], rep('', length(score_table[[name]]) -1))
else
c(rep(aliases[attr(x, 'name') == name], length(score_table[[name]])))
}))
fml <- attr(x, 'fml')
# browser()
condition_score <- lapply(lapply(fml, function(.fml) as.character(.fml)), strsplit, '\\s*~\\s*', perl = TRUE)
condition <- unlist(lapply(condition_score,
function(.condition_score) sapply(.condition_score,
function(.c_s) .c_s[1])))
score <- unlist(lapply(condition_score,
function(.condition_score) sapply(.condition_score,
function(.c_s) .c_s[2])))
# browser()
dt <- data.frame(Variable = aliases.expand, Condition = condition, Score = score, ...)
dt
}
#' @export
flextable <- function(x,...){
UseMethod('flextable')
}
#' A method to convert score table to flextable
#' @description A method to convert score table to flextable
#' @method flextable ScoreTable
#' @param x An object of class ScoreTable
#' @param ... Additional params passed to flextable::flextable.
#' @seealso \link{print.ScoreTable}, \link{huxtable.ScoreTable}, \link{as.data.frame.ScoreTable},
#' \link[flextable]{flextable}
#' @export
flextable.ScoreTable <- function(x,...){
flextable::flextable(as.data.frame(x, pretty = TRUE),...)
}
#' @export
huxtable <- function(x,...){
UseMethod('huxtable')
}
#' A method to convert score table to huxtable
#' @description A method to convert score table to huxtable
#' @method huxtable ScoreTable
#' @param x An object of class ScoreTable
#' @param ... Additional params passed to huxtable::hux.
#' @seealso \link{print.ScoreTable}, \link{huxtable.ScoreTable}, \link{as.data.frame.ScoreTable},
#' \link[huxtable]{huxtable}
#' @export
huxtable.ScoreTable <- function(x,...){
hux <- huxtable::huxtable(as.data.frame(x, pretty = TRUE))
C306::ht_theme_markdown(hux, header_rows = 1)
}
| /R/ScoreTable.R | no_license | choisy/ST306 | R | false | false | 12,958 | r | # Below are generators and helpers that create and manipulate ScoreTable objects
#' Score Table generator
#' @description A function to formally create an object of class Score Table.
#' @param confounders
#' For simple generation.
#' A character vector that declares derived components in the score table (1) or
#' a named list (2) whose names define the derived components in the score table and
#' whose values define their respective possible levels
#' @param scores
#' For simple generation.
#' A numeric vector that declares score for derived components using method (1) or
#' a named list whose names follow the derived component names defined in method (2) and
#' whose values define their respective possible scores
#' @param aliases
#' A named list that define a pretty representatives for defined confounders
#' following the structure of list(confounder = aliases).
#' Unmentioned confounders will be left intact.
#' @param custom_cases
#' A named list that define a sophisticated way to define confounders and scoring algorithm,
#' following the structure of list(name = list(formulas))
#' Each name is the name for derived confounders.
#' Each formula in each sub-list folllows the form of condition ~ score in a "specific to general" order.
#' This is based on \link[dplyr]{case_when}.
#' @return
#' An object of class ScoreTable.
#' When called with no data, this will print out the structure of the ScoreTable.
#' When called with data passed, this will return a data frame of class score_tbl.
#' @examples
#' charlson = ScoreTable(
#'confounders = c('myocardial_infarct', 'congestive_heart_failure', 'peripheral_vascular_disease',
#' 'cerebrovascular_disease', 'dementia', 'chronic_pulmonary_disease',
#' 'connective_tissue_disease', 'ulcer_disease', 'mild_liver_disease', 'diabetes',
#' 'hemiplegia', 'moderate_or_severe_renal_disease', 'diabetes_with_end_organ_damage', 'any_tumor',
#' 'moderate_or_severe_liver_disease', 'metastatic_solid_tumor', 'AIDS'),
#'scores = c(rep(1, 10), rep(2, 4), 3, 6, 6),
#'aliases = c('Myocardial infarction', 'Congestive heart failure', 'Peripheral vascular disease',
#' 'Cerebrovascular disease', 'Dementia', 'Chronic pulmonary disease',
#' 'Connective tissue disease', 'Ulcer disease', 'Mild liver disease', 'Diabetes',
#' 'Hemiplegia', 'Moderate or severe renal disease', 'Diabetes with end organ damage', 'any tumor',
#' 'Moderate or severe liver disease', 'Metastatic solid tumor', 'AIDS')
#')
#'
#'apache.ii <- ScoreTable(
#'aliases = list(temp ='Temperature', map ='Maximum Aterial Pressure',
#' hr = 'Heart Rate', rr = 'Respiratory Rate', aapo2 = 'AaPO2',
#' pao2 = 'PaO2', ph = 'PH', hco3 = 'HCO3-', sodium = 'Sodium', potassium = 'Potassium',
#' creatinine = 'Creatinine', hct = 'HCT', wbc = 'White-blood cell',
#' gcs = 'Glasgow Comma Score', age = 'Age', chronic = 'Chronic'),
#'custom_cases =
#' list(
#' temp = list(
#' temp >= 41 | temp < 30 ~ 4,
#' temp >= 39 | temp < 32 ~ 3,
#' temp < 34 ~ 2,
#' temp >= 38.5 | temp < 36 ~ 1,
#' !is.na(temp) ~ 0
#' ),
#' map = list(
#' map >= 160 | map < 50 ~ 4,
#' map >= 130 ~ 3,
#' map >= 110 | map < 70 ~ 2,
#' !is.na(map) ~ 0
#' ),
#' hr = list(
#' hr >= 180 | hr < 40 ~ 4,
#' hr >= 140 | hr < 55 ~ 3,
#' hr >= 110 | hr < 70 ~ 2,
#' !is.na(hr) ~ 0
#' ),
#' rr = list(
#' rr >= 50 | rr < 6 ~ 4,
#' rr >= 35 ~ 3,
#' rr < 10 ~ 2,
#' rr >= 25 | rr < 12 ~ 1,
#' !is.na(rr) ~ 0
#' ),
#' aapo2 = list(
#' fio2 < .5 | is.na(fio2) ~ 0,
#' aapo2 >= 500 ~ 5,
#' aapo2 >= 350 ~ 3,
#' aapo2 >= 200 ~ 2,
#' !is.na(aapo2) ~ 0
#' ),
#' pao2 = list(
#' fio2 >= .5 ~ 0,
#' pao2 < 55 ~ 4,
#' pao2 <= 60 ~ 3,
#' pao2 <= 70 ~ 1,
#' !is.na(pao2) ~ 0
#' ),
#' ph = list(
#' ph >= 7.7 | ph < 7.15 ~ 4,
#' ph >= 7.6 | ph < 7.25 ~ 3,
#' ph < 7.33 ~ 2,
#' ph >= 7.5 ~ 1,
#' TRUE ~ 0
#' ),
#' hco3 = list(
#' !is.na(ph) ~ 0,
#' hco3 >= 52 | hco3 < 15 ~ 4,
#' hco3 >= 41 | hco3 < 18 ~ 3,
#' hco3 < 22 ~ 2,
#' hco3 >= 32 ~ 1,
#' !is.na(hco3) ~ 0
#' ),
#' sodium = list(
#' sodium >= 180 | sodium <= 110 ~ 4,
#' sodium >= 160 | sodium < 120 ~ 3,
#' sodium >= 155 | sodium < 130 ~ 2,
#' sodium >= 150 ~ 1,
#' !is.na(sodium) ~ 0
#' ),
#' potassium = list(
#' potassium >= 7 | potassium < 2.5 ~ 4,
#' potassium >= 6 ~ 3,
#' potassium < 3 ~ 2,
#' potassium >= 5.5 | potassium < 3.5 ~ 1,
#' !is.na(potassium) ~ 0
#' ),
#' creatinine = list(
#' creatinine >= 3.5 ~ 4,
#' creatinine >= 2 ~ 3,
#' creatinine >= 1.5 | creatinine < .6 ~ 2,
#' !is.na(creatinine) ~ 0
#' ),
#' hct = list(
#' hct >= 60 | hct < 20 ~ 4,
#' hct >= 50 | hct < 30 ~ 2,
#' hct >= 46 ~ 1,
#' !is.na(hct) ~ 0
#' ),
#' wbc = list(
#' wbc >= 40 | wbc < 1 ~ 4,
#' wbc >= 20 | wbc < 3 ~ 2,
#' wbc >= 15 ~ 1,
#' !is.na(wbc) ~ 0
#' ),
#' gcs = list(
#' !is.na(gcs) ~ 15 - gcs
#' ),
#' age = list(
#' age >= 75 ~ 6,
#' age >= 65 ~ 5,
#' age >= 55 ~ 3,
#' age >= 45 ~ 2,
#' TRUE ~ 0
#' ),
#' chronic = list(
#' rowSums(liver, heart, lung, kidney) == 0 ~ 0,
#' as.logical(emergency) ~ 5,
#' as.logical(elective) ~ 2,
#' sum(elective, emergency, na.rm = TRUE) == 0 ~ 5
#' )
#' )
#')
#' @seealso
#' \link[dplyr]{case_when}, \link{as.data.frame.ScoreTable}, \link{apache.ii}, \link{summary.score_tbl}
#' @export
ScoreTable <- function(confounders, scores, aliases = NULL, custom_cases){
# First, we need to determine what we have
# A type of binary will only have two levels, while categorical will have more than 2
# Complex is a type where we have >1 conditional layers
type <- character()
.aliases <- character()
if (!missing(confounders) | !missing(scores)){
if (!(length(unlist(confounders)) == length(unlist(scores))))
stop('Length mismatched!')
if (is.character(confounders)) type <- 'binary' else type <- 'categorical'
if (type == 'categorical' & length(names(scores)) < length(confounders))
stop('Score must be named in multi-level conditions')
.aliases <-
if (type == 'binary') confounders
else unlist(lapply(seq_along(confounders),
function(i)
rep(names(confounders[i]), length(confounders[[i]]))))
# if (!length(names(aliases))){
# names(aliases) <- aliases
# aliases <- .aliases
# }
}
if (!missing(custom_cases)) type <- c(type, 'complex')
if ('complex'%in%type){
.aliases <- unique(c(.aliases, names(custom_cases)))
}
# browser()
.aliases <- unique(.aliases)
.aliases <-
if (length(aliases) & length(names(aliases))) dplyr::recode(.aliases, !!!aliases)
else dplyr::recode(.aliases, !!!structure(aliases, names = .aliases))
# browser()
#Construction condition tree from confounder and scores
if (!missing(confounders)){
conf <-
if ('binary' %in% type) structure(rep(TRUE, length(confounders)), names = confounders)
else confounders
if ('binary' %in% type) scores <- structure(scores, names = confounders)
simple_cases <- .tree_construct(conf, scores)
names(simple_cases$name) <- simple_cases$name
} else simple_cases <- NULL
if (!missing(custom_cases)){
# browser()
custom_cases_var <-
lapply(custom_cases, function(custom_case) {
out <- unique(unlist(lapply(custom_case, all.vars)))
out[!out %in% c('.', '.id')]
})
names(custom_cases_var) <- names(custom_cases)
custom_cases <- list(name = names(custom_cases),
var = custom_cases_var,
fml = custom_cases)
# cases <- c(simple_cases, custom_cases)
} else custom_cases <- NULL
cases <- list(name = c(simple_cases$name, custom_cases$name),
fml = c(simple_cases$fml, custom_cases$fml),
var = c(simple_cases$name, custom_cases$var))
# browser()
score_table <- structure(cases$fml,
names = cases$name,
score_names = paste(cases$name, 'score', sep = '_'),
vars = cases$var,
aliases = .aliases)
score_object <- structure(
function(data, id = names(data)[1], which = names(score_table),...){
if (missing(data)) get(deparse(sys.call()[[1]]))
else purrr::partial(.calc, score_table = score_table)(data, id, which, ...)
},
class = c('ScoreTable', 'function'),
fml = cases$fml,
name = cases$name,
score_name = paste(cases$name, 'score', sep = '_'),
alias = .aliases,
score_table = score_table
)
return(score_object)
}
.tree_construct <- function(conf, scores){
# browser()
conf_name <- names(conf)
conf_fml <-
lapply(conf_name,
function(.conf_name){
.conf <- unlist(conf[names(conf) == .conf_name])
.score <- unlist(scores[names(scores) == .conf_name])
c(
unlist(lapply(seq_along(.conf),
function(i){
as.formula(paste(.conf_name, '==', .conf[i], '~', .score[i]))
})),
as.formula(paste('!is.na(', .conf_name, ') ~ 0'))
)
})
names(conf_fml) <- conf_name
return(list(name = conf_name, fml = conf_fml))
}
#' A method to print out ScoreTable object
#' @description A method to print out ScoreTable object
#' @method print ScoreTable
#' @param x An object of class ScoreTable
#' @param pretty A logical value. Default = TRUE will print out the pretty version of the table.
#' @seealso \link{as.data.frame.ScoreTable}, \link{huxtable.ScoreTable}, \link{flextable.ScoreTable}
#' @export
print.ScoreTable <- function(x, pretty = TRUE,...){
print(as.data.frame(x, pretty = pretty))
}
#' A method to coerce ScoreTable object to analysable data frame
#' @description A method to coerce ScoreTable object to analysable data frame
#' @method as.data.frame ScoreTable
#' @param x An object of class ScoreTable
#' @param pretty A logical value. Default = FALSE will create a analysable version of the table.
#' @param ... Additional parameters passed to data.frame()
#' @seealso \link{print.ScoreTable}, \link{huxtable.ScoreTable}, \link{flextable.ScoreTable}
#' @export
as.data.frame.ScoreTable <- function(x, pretty = FALSE, ...){
score_table <- attr(x, 'score_table')
aliases <- attr(x, 'alias')
aliases.expand <- unlist(lapply(attr(x, 'name'),
function(name){
if (pretty)
c(aliases[attr(x, 'name') == name], rep('', length(score_table[[name]]) -1))
else
c(rep(aliases[attr(x, 'name') == name], length(score_table[[name]])))
}))
fml <- attr(x, 'fml')
# browser()
condition_score <- lapply(lapply(fml, function(.fml) as.character(.fml)), strsplit, '\\s*~\\s*', perl = TRUE)
condition <- unlist(lapply(condition_score,
function(.condition_score) sapply(.condition_score,
function(.c_s) .c_s[1])))
score <- unlist(lapply(condition_score,
function(.condition_score) sapply(.condition_score,
function(.c_s) .c_s[2])))
# browser()
dt <- data.frame(Variable = aliases.expand, Condition = condition, Score = score, ...)
dt
}
#' @export
flextable <- function(x,...){
UseMethod('flextable')
}
#' A method to convert score table to flextable
#' @description A method to convert score table to flextable
#' @method flextable ScoreTable
#' @param x An object of class ScoreTable
#' @param ... Additional params passed to flextable::flextable.
#' @seealso \link{print.ScoreTable}, \link{huxtable.ScoreTable}, \link{as.data.frame.ScoreTable},
#' \link[flextable]{flextable}
#' @export
flextable.ScoreTable <- function(x,...){
flextable::flextable(as.data.frame(x, pretty = TRUE),...)
}
#' @export
huxtable <- function(x,...){
UseMethod('huxtable')
}
#' A method to convert score table to huxtable
#' @description A method to convert score table to huxtable
#' @method huxtable ScoreTable
#' @param x An object of class ScoreTable
#' @param ... Additional params passed to huxtable::hux.
#' @seealso \link{print.ScoreTable}, \link{huxtable.ScoreTable}, \link{as.data.frame.ScoreTable},
#' \link[huxtable]{huxtable}
#' @export
huxtable.ScoreTable <- function(x,...){
hux <- huxtable::huxtable(as.data.frame(x, pretty = TRUE))
C306::ht_theme_markdown(hux, header_rows = 1)
}
|
## check working directory
## plot1.R - Frequency / Global Active Power (kilowatts)
dataUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
datasetFile <- "household_power_consumption.txt"
zipFile <- "./data/epc.zip"
plotName <- 'plot1.png'
# A directory to put the data in.
if(!file.exists('data')) {
dir.create('data')
}
# Ensure we have the dataset file.
if(!file.exists(zipFile)) {
download.file(dataUrl, destfile = zipFile, method = 'curl')
epc_date <- date();
}
unzip(zipFile, datasetFile) #unzip file and save it
library(data.table)
## read in the household power consumption data into a data table
data<-fread("household_power_consumption.txt",sep=";",na.strings=c("?"))
data$Date <- as.Date(data$Date,format="%d/%m/%Y") #read date column in the specified format
## only using data from the dates 2007-02-01 and 2007-02-02
Date1<-as.Date("01/02/2007",format="%d/%m/%Y")
Date2<-as.Date("02/02/2007",format="%d/%m/%Y")
## create the subset of data we're interested in (keep only if dates fulfil the criteria above)
data<-subset(data, Date == Date1 | Date == Date2)
## save the plot in the specified format
png(filename= plotName, width=480, height=480)
hist(as.numeric(data$Global_active_power), main="Global Active Power", xlab="Global Active Power (kilowatts)",col="red") #<- as.numeric is needed??
hist(data$Global_active_power, main="Global Active Power", xlab="Global Active Power (kilowatts)",col="red") #<- without as.numeric
dev.off() #end the connection to the device
| /Plot1.R | no_license | anastasiaya/ExData_Plotting1 | R | false | false | 1,559 | r | ## check working directory
## plot1.R - Frequency / Global Active Power (kilowatts)
dataUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
datasetFile <- "household_power_consumption.txt"
zipFile <- "./data/epc.zip"
plotName <- 'plot1.png'
# A directory to put the data in.
if(!file.exists('data')) {
dir.create('data')
}
# Ensure we have the dataset file.
if(!file.exists(zipFile)) {
download.file(dataUrl, destfile = zipFile, method = 'curl')
epc_date <- date();
}
unzip(zipFile, datasetFile) #unzip file and save it
library(data.table)
## read in the household power consumption data into a data table
data<-fread("household_power_consumption.txt",sep=";",na.strings=c("?"))
data$Date <- as.Date(data$Date,format="%d/%m/%Y") #read date column in the specified format
## only using data from the dates 2007-02-01 and 2007-02-02
Date1<-as.Date("01/02/2007",format="%d/%m/%Y")
Date2<-as.Date("02/02/2007",format="%d/%m/%Y")
## create the subset of data we're interested in (keep only if dates fulfil the criteria above)
data<-subset(data, Date == Date1 | Date == Date2)
## save the plot in the specified format
png(filename= plotName, width=480, height=480)
hist(as.numeric(data$Global_active_power), main="Global Active Power", xlab="Global Active Power (kilowatts)",col="red") #<- as.numeric is needed??
hist(data$Global_active_power, main="Global Active Power", xlab="Global Active Power (kilowatts)",col="red") #<- without as.numeric
dev.off() #end the connection to the device
|
# Copyright 2012 Alexander W Blocker
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#' Function to run IPFP (iterative proportional fitting procedure)
#'
#' Use IPFP starting from x0 to produce vector x s.t. Ax = y within tolerance.
#' Need to ensure that x0 > 0.
#'
#' @param y numeric constraint vector (length nrow)
#' @param A constraint matrix (nrow x ncol)
#' @param x0 numeric initial vector (length ncol)
#' @param tol numeric tolerance for IPFP; defaults to
#' \code{sqrt(.Machine$double.eps)}
#' @param maxit integer maximum number of iterations for IPFP; defaults to 1e3
#' @param verbose logical parameter to select verbose output from C function
#' @param full logical parameter to select full return (with diagnostic info)
#' @return if not full, a vector of length ncol containing solution obtained by
#' IPFP. If full, a list containing solution (as x), the number of iterations
#' (as iter), and the L2 norm of Ax - y (as errNorm)
#' @keywords iteration array
#' @export
#' @useDynLib ipfp
#' @examples
#' A <- matrix(c(1,0,0, 1,0,0, 0,1,0, 0,1,0, 0,0,1), nrow=3)
#' x <- rgamma(ncol(A), 10, 1/100)
#' y <- A %*% x
#' x0 <- x * rgamma(length(x), 10, 10)
#' ans <- ipfp(y, A, x0, full=TRUE)
#' print(ans)
#' print(x)
ipfp <- function(y, A, x0,
tol=sqrt(.Machine$double.eps), maxit=1e3, verbose=FALSE, full=FALSE) {
# Get active rows
activeRows <- which(y > 0)
# Zero inactive columns
if ( any(y==0) ) {
activeCols <- !pmin(1, colSums(A[y==0,,drop=FALSE]))
} else {
activeCols <- rep(TRUE, ncol(A))
}
x0[!activeCols] <- 0
# Run IPF
ans <- .Call("ipfp", y[activeRows], A[activeRows, activeCols, drop=FALSE],
dim(A[activeRows, activeCols, drop=FALSE]), x0[activeCols],
as.numeric(tol), as.integer(maxit), as.logical(verbose),
PACKAGE='ipfp')
x0[activeCols] <- ans$x
if (full)
return( list(x=x0, iter=ans$iter, errNorm=ans$errNorm) )
return(x0)
}
| /R/ipfp.R | no_license | awblocker/ipfp | R | false | false | 2,491 | r | # Copyright 2012 Alexander W Blocker
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#' Function to run IPFP (iterative proportional fitting procedure)
#'
#' Use IPFP starting from x0 to produce vector x s.t. Ax = y within tolerance.
#' Need to ensure that x0 > 0.
#'
#' @param y numeric constraint vector (length nrow)
#' @param A constraint matrix (nrow x ncol)
#' @param x0 numeric initial vector (length ncol)
#' @param tol numeric tolerance for IPFP; defaults to
#' \code{sqrt(.Machine$double.eps)}
#' @param maxit integer maximum number of iterations for IPFP; defaults to 1e3
#' @param verbose logical parameter to select verbose output from C function
#' @param full logical parameter to select full return (with diagnostic info)
#' @return if not full, a vector of length ncol containing solution obtained by
#' IPFP. If full, a list containing solution (as x), the number of iterations
#' (as iter), and the L2 norm of Ax - y (as errNorm)
#' @keywords iteration array
#' @export
#' @useDynLib ipfp
#' @examples
#' A <- matrix(c(1,0,0, 1,0,0, 0,1,0, 0,1,0, 0,0,1), nrow=3)
#' x <- rgamma(ncol(A), 10, 1/100)
#' y <- A %*% x
#' x0 <- x * rgamma(length(x), 10, 10)
#' ans <- ipfp(y, A, x0, full=TRUE)
#' print(ans)
#' print(x)
ipfp <- function(y, A, x0,
tol=sqrt(.Machine$double.eps), maxit=1e3, verbose=FALSE, full=FALSE) {
# Get active rows
activeRows <- which(y > 0)
# Zero inactive columns
if ( any(y==0) ) {
activeCols <- !pmin(1, colSums(A[y==0,,drop=FALSE]))
} else {
activeCols <- rep(TRUE, ncol(A))
}
x0[!activeCols] <- 0
# Run IPF
ans <- .Call("ipfp", y[activeRows], A[activeRows, activeCols, drop=FALSE],
dim(A[activeRows, activeCols, drop=FALSE]), x0[activeCols],
as.numeric(tol), as.integer(maxit), as.logical(verbose),
PACKAGE='ipfp')
x0[activeCols] <- ans$x
if (full)
return( list(x=x0, iter=ans$iter, errNorm=ans$errNorm) )
return(x0)
}
|
#----------------------------------------------------------------------------
# moderndive.book.pkgs
#
# Package logger setup
#----------------------------------------------------------------------------
.logger_name <- "moderndive.book.pkgs"
.pkg_logger <- logging::getLogger(.logger_name)
.pkg_logger$setLevel("FINEST")
pkg_loginfo <- function(msg, ...) tryCatch(logging::loginfo(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logdebug <- function(msg, ...) tryCatch(logging::logdebug(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logerror <- function(msg, ...) tryCatch(logging::logerror(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logwarn <- function(msg, ...) tryCatch(logging::logwarn(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logfinest <- function(msg, ...) tryCatch(logging::logfinest(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
#'
#' Retrieves moderndive.book.pkgs logger.
#'
#' @return logger object
#'
#' @export
#'
moderndive.book.pkgs_getLogger <- function() {
.pkg_logger
}
| /packages/moderndive.book.pkgs/R/package_logger.R | no_license | f0nzie/moderndive-book-rsuite | R | false | false | 1,333 | r | #----------------------------------------------------------------------------
# moderndive.book.pkgs
#
# Package logger setup
#----------------------------------------------------------------------------
.logger_name <- "moderndive.book.pkgs"
.pkg_logger <- logging::getLogger(.logger_name)
.pkg_logger$setLevel("FINEST")
pkg_loginfo <- function(msg, ...) tryCatch(logging::loginfo(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logdebug <- function(msg, ...) tryCatch(logging::logdebug(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logerror <- function(msg, ...) tryCatch(logging::logerror(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logwarn <- function(msg, ...) tryCatch(logging::logwarn(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
pkg_logfinest <- function(msg, ...) tryCatch(logging::logfinest(msg, ..., logger = .pkg_logger),
error = function(e) warning(e))
#'
#' Retrieves moderndive.book.pkgs logger.
#'
#' @return logger object
#'
#' @export
#'
moderndive.book.pkgs_getLogger <- function() {
.pkg_logger
}
|
library("shiny")
library("tm")
library("ngramrr")
# Load functions
preprocess_corpus <- function(corpus) {
# Remove punctuation from text.
corpus_preprocessed <- tm_map(corpus, removePunctuation)
# Remove numbers from text.
corpus_preprocessed <- tm_map(corpus_preprocessed, removeNumbers)
# Convert text to lowercase.
corpus_preprocessed <-
tm_map(corpus_preprocessed, content_transformer(tolower))
# Strip whitespace from text.
corpus_preprocessed <- tm_map(corpus_preprocessed, stripWhitespace)
# Stem the text.
# corpus_preprocessed <- tm_map(corpus_preprocessed, stemDocument)
# Remove stopwords.
corpus_preprocessed <-
tm_map(corpus_preprocessed, removeWords, stopwords("en"))
# Return value.
return(corpus_preprocessed)
}
katz_backoff_model <- function(phrase) {
if (typeof(phrase) == "character") {
trigram_model <- function(tokens) {
key <- function(tokens) {
paste(
tail(
tokens,
n = 2
)[1],
tail(
tokens,
n = 2
)[2]
)
}
# find matches and their count
matches_count <- function(phrase) {
sapply(
names(
which(
sapply(
Terms(tdm_trigram),
function(terms) {
grepl(
phrase,
paste(
strsplit(
terms, split = " "
)[[1]][1],
strsplit(
terms, split = " "
)[[1]][2]
),
ignore.case = TRUE
)
}
)
)
),
function(match) sum(tm_term_score(tdm_trigram, match))
)
}
# find the last word of the most frequent match
tail_of_most_frequent_match <- function(phrase) {
matches <- matches_count(phrase)
if (length(matches) > 0) {
tail(
strsplit(
names(
head(
which(matches == max(matches)),
n = 1
)
)
, split = " ")[[1]],
n = 1
)
} else bigram_model(tail(corpus_input, n = 1))
}
return(
tail_of_most_frequent_match(key(tokens))
)
}
bigram_model <- function(token) {
# find matches and their count
matches_count <- function(phrase) {
sapply(
names(
which(
sapply(
Terms(tdm_bigram),
function(terms) {
grepl(
phrase,
strsplit(
terms, split = " "
)[[1]][1],
ignore.case = TRUE
)
}
)
)
),
function(match) sum(tm_term_score(tdm_bigram, match))
)
}
# find the last word of the most frequent match
tail_of_most_frequent_match <- function(phrase) {
matches <- matches_count(phrase)
if (length(matches) > 0) {
tail(
strsplit(
names(
head(
which(matches == max(matches)),
n = 1
)
)
, split = " ")[[1]],
n = 1
)
} else unigram_model(tail(corpus_input, n = 1))
}
return(
tail_of_most_frequent_match(token)
)
}
unigram_model <- function(token) {
associations <-
findAssocs(tdm_unigram, token, corlimit = .99)[[1]]
if (length(associations) > 0) {
names(sample(which(associations == max(associations)), 1))
} else return("will")
}
# preprocess phrase
corpus_input <-
VCorpus(
VectorSource(phrase),
list(reader = PlainTextDocument)
)
corpus_input <- preprocess_corpus(corpus_input)
corpus_input <- scan_tokenizer(corpus_input[[1]][[1]][1])
return(
if (length(corpus_input) >= 2) {
trigram_model(corpus_input)
} else if (length(corpus_input) == 1) {
bigram_model(corpus_input)
} else return("will")
)
} else {
stop("non-character or null input")
}
}
# Load term-document matrices
load("ngrams.RData")
# Main function
shinyServer(
function(input, output) {
output$phrase <-
renderText(
{
if (input$predictButton == 0) "waiting for input ..."
else input$phrase
}
)
output$word <-
renderText(
{
if (input$predictButton == 0) "waiting for input ..."
else katz_backoff_model(input$phrase)
}
)
}
)
| /server.R | no_license | HONOKAYU/Data-Science-Capstone-Final-Project | R | false | false | 6,423 | r | library("shiny")
library("tm")
library("ngramrr")
# Load functions
preprocess_corpus <- function(corpus) {
# Remove punctuation from text.
corpus_preprocessed <- tm_map(corpus, removePunctuation)
# Remove numbers from text.
corpus_preprocessed <- tm_map(corpus_preprocessed, removeNumbers)
# Convert text to lowercase.
corpus_preprocessed <-
tm_map(corpus_preprocessed, content_transformer(tolower))
# Strip whitespace from text.
corpus_preprocessed <- tm_map(corpus_preprocessed, stripWhitespace)
# Stem the text.
# corpus_preprocessed <- tm_map(corpus_preprocessed, stemDocument)
# Remove stopwords.
corpus_preprocessed <-
tm_map(corpus_preprocessed, removeWords, stopwords("en"))
# Return value.
return(corpus_preprocessed)
}
katz_backoff_model <- function(phrase) {
if (typeof(phrase) == "character") {
trigram_model <- function(tokens) {
key <- function(tokens) {
paste(
tail(
tokens,
n = 2
)[1],
tail(
tokens,
n = 2
)[2]
)
}
# find matches and their count
matches_count <- function(phrase) {
sapply(
names(
which(
sapply(
Terms(tdm_trigram),
function(terms) {
grepl(
phrase,
paste(
strsplit(
terms, split = " "
)[[1]][1],
strsplit(
terms, split = " "
)[[1]][2]
),
ignore.case = TRUE
)
}
)
)
),
function(match) sum(tm_term_score(tdm_trigram, match))
)
}
# find the last word of the most frequent match
tail_of_most_frequent_match <- function(phrase) {
matches <- matches_count(phrase)
if (length(matches) > 0) {
tail(
strsplit(
names(
head(
which(matches == max(matches)),
n = 1
)
)
, split = " ")[[1]],
n = 1
)
} else bigram_model(tail(corpus_input, n = 1))
}
return(
tail_of_most_frequent_match(key(tokens))
)
}
bigram_model <- function(token) {
# find matches and their count
matches_count <- function(phrase) {
sapply(
names(
which(
sapply(
Terms(tdm_bigram),
function(terms) {
grepl(
phrase,
strsplit(
terms, split = " "
)[[1]][1],
ignore.case = TRUE
)
}
)
)
),
function(match) sum(tm_term_score(tdm_bigram, match))
)
}
# find the last word of the most frequent match
tail_of_most_frequent_match <- function(phrase) {
matches <- matches_count(phrase)
if (length(matches) > 0) {
tail(
strsplit(
names(
head(
which(matches == max(matches)),
n = 1
)
)
, split = " ")[[1]],
n = 1
)
} else unigram_model(tail(corpus_input, n = 1))
}
return(
tail_of_most_frequent_match(token)
)
}
unigram_model <- function(token) {
associations <-
findAssocs(tdm_unigram, token, corlimit = .99)[[1]]
if (length(associations) > 0) {
names(sample(which(associations == max(associations)), 1))
} else return("will")
}
# preprocess phrase
corpus_input <-
VCorpus(
VectorSource(phrase),
list(reader = PlainTextDocument)
)
corpus_input <- preprocess_corpus(corpus_input)
corpus_input <- scan_tokenizer(corpus_input[[1]][[1]][1])
return(
if (length(corpus_input) >= 2) {
trigram_model(corpus_input)
} else if (length(corpus_input) == 1) {
bigram_model(corpus_input)
} else return("will")
)
} else {
stop("non-character or null input")
}
}
# Load term-document matrices
load("ngrams.RData")
# Main function
shinyServer(
function(input, output) {
output$phrase <-
renderText(
{
if (input$predictButton == 0) "waiting for input ..."
else input$phrase
}
)
output$word <-
renderText(
{
if (input$predictButton == 0) "waiting for input ..."
else katz_backoff_model(input$phrase)
}
)
}
)
|
load("dados.Rda")
library(gamlss)
# modelo binomial negativa ------------------------------------------------
#zero inflated
dados_zinb <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "ZINBI")
dados_c_zinb <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "ZINBI")
dados_col_zinb <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "ZINBI")
dados_c_col_zinb <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "ZINBI")
#normal
dados_nb <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "NBI")
dados_c_nb <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "NBI")
dados_col_nb <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "NBI")
dados_c_col_nb <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "NBI")
# modelos poisson ---------------------------------------------------------
#zero inflated
dados_zip <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "ZIP")
dados_c_zip <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "ZIP")
dados_col_zip <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "ZIP")
dados_c_col_zip <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "ZIP")
#normal
dados_p <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "PO")
dados_c_p <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "PO")
dados_col_p <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "PO")
dados_c_col_p <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "PO")
# salvar modelos ----------------------------------------------------------
save(dados_nb, dados_c_nb, dados_c_col_nb, dados_col_nb, file='modelos_nb.Rda')
save(dados_zinb, dados_c_zinb, dados_c_col_zinb, dados_col_zinb, file='modelos_zinb.Rda')
save(dados_p, dados_c_p, dados_c_col_p, dados_col_p, file='modelos_p.Rda')
save(dados_zip, dados_c_zip, dados_c_col_zip, dados_col_zip, file='modelos_zip.Rda')
# analisando modelos ------------------------------------------------------
# plots modelos zinb
plot(dados_c_col_zinb, summary=TRUE)
plot(dados_c_zinb, summary=TRUE)
plot(dados_col_zinb, summary=TRUE)
plot(dados_zinb, summary=TRUE)
# plots modelos nb
plot(dados_c_col_nb, summary=TRUE)
plot(dados_c_nb, summary=TRUE)
plot(dados_col_nb, summary=TRUE)
plot(dados_nb, summary=TRUE)
# analisando modelos poisson ----------------------------------------------
plot(dados_c_col_zip, summary=TRUE)
plot(dados_c_zip, summary=TRUE)
plot(dados_col_zip, summary=TRUE)
plot(dados_zip, summary=TRUE)
plot(dados_c_col_p, summary=TRUE)
plot(dados_c_p, summary=TRUE)
plot(dados_col_p, summary=TRUE)
plot(dados_p, summary=TRUE)
# exportando coeficientes -------------------------------------------------
broom::tidy(dados_col_zinb) %>% xtable::xtable()
# modelo poisson (pacote glm) ---------------------------------------------
# Modelo de poisson multivariado
ajuste <- glm(qtde ~ sexo*comida, data = dados_col, poisson(link = "log"))
ajuste
anova(ajuste)
qqplot(ajuste$residuals, dados_col$qtde, title("Gráfico de Resíduos"))
plot(ajuste$residuals, title("Ajuste dos Resíduos"))
#Shapiro
shapiro.test(dados_col$qtde)
shapiro.test(ajuste$residuals)
plot(fitted(ajuste), residuals(ajuste)) | /modelos.R | no_license | andradecarolina/ME714 | R | false | false | 3,215 | r | load("dados.Rda")
library(gamlss)
# modelo binomial negativa ------------------------------------------------
#zero inflated
dados_zinb <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "ZINBI")
dados_c_zinb <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "ZINBI")
dados_col_zinb <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "ZINBI")
dados_c_col_zinb <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "ZINBI")
#normal
dados_nb <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "NBI")
dados_c_nb <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "NBI")
dados_col_nb <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "NBI")
dados_c_col_nb <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "NBI")
# modelos poisson ---------------------------------------------------------
#zero inflated
dados_zip <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "ZIP")
dados_c_zip <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "ZIP")
dados_col_zip <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "ZIP")
dados_c_col_zip <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "ZIP")
#normal
dados_p <- gamlss(qtde ~ sexo*comida*estacao, data = dados, family = "PO")
dados_c_p <- gamlss(qtde ~ sexo*comida*estacao, data = dados_c, family = "PO")
dados_col_p <- gamlss(qtde ~ sexo*comida, data = dados_col, family = "PO")
dados_c_col_p <- gamlss(qtde ~ sexo*comida, data = dados_c_col, family = "PO")
# salvar modelos ----------------------------------------------------------
save(dados_nb, dados_c_nb, dados_c_col_nb, dados_col_nb, file='modelos_nb.Rda')
save(dados_zinb, dados_c_zinb, dados_c_col_zinb, dados_col_zinb, file='modelos_zinb.Rda')
save(dados_p, dados_c_p, dados_c_col_p, dados_col_p, file='modelos_p.Rda')
save(dados_zip, dados_c_zip, dados_c_col_zip, dados_col_zip, file='modelos_zip.Rda')
# analisando modelos ------------------------------------------------------
# plots modelos zinb
plot(dados_c_col_zinb, summary=TRUE)
plot(dados_c_zinb, summary=TRUE)
plot(dados_col_zinb, summary=TRUE)
plot(dados_zinb, summary=TRUE)
# plots modelos nb
plot(dados_c_col_nb, summary=TRUE)
plot(dados_c_nb, summary=TRUE)
plot(dados_col_nb, summary=TRUE)
plot(dados_nb, summary=TRUE)
# analisando modelos poisson ----------------------------------------------
plot(dados_c_col_zip, summary=TRUE)
plot(dados_c_zip, summary=TRUE)
plot(dados_col_zip, summary=TRUE)
plot(dados_zip, summary=TRUE)
plot(dados_c_col_p, summary=TRUE)
plot(dados_c_p, summary=TRUE)
plot(dados_col_p, summary=TRUE)
plot(dados_p, summary=TRUE)
# exportando coeficientes -------------------------------------------------
broom::tidy(dados_col_zinb) %>% xtable::xtable()
# modelo poisson (pacote glm) ---------------------------------------------
# Modelo de poisson multivariado
ajuste <- glm(qtde ~ sexo*comida, data = dados_col, poisson(link = "log"))
ajuste
anova(ajuste)
qqplot(ajuste$residuals, dados_col$qtde, title("Gráfico de Resíduos"))
plot(ajuste$residuals, title("Ajuste dos Resíduos"))
#Shapiro
shapiro.test(dados_col$qtde)
shapiro.test(ajuste$residuals)
plot(fitted(ajuste), residuals(ajuste)) |
library(shiny)
library(shinythemes)
shinyUI(navbarPage("Coursera Data Science Capstone: Word Prediction Application",
theme = shinytheme("cosmo"),
mainPanel(
h3("App Information"),
h5("This application will predict the next word in
the entered phrase. Up to 5 words will be predicted.
Words are returned in order of their probability
(highest to lowest)."),
h3("Instructions"),
h5("1. Type in an incomplete phrase."),
h5("2. Click the 'Submit' button."),
textInput("textEntry",
h4("Type in any phrase"),
value = "Pick up a case of"),
submitButton("Submit"),
h3("Predicted Words:"),
h1(textOutput("text"))
)
))
| /shiny/ui.R | no_license | bikeCommuterDC/DSCapstone | R | false | false | 972 | r | library(shiny)
library(shinythemes)
shinyUI(navbarPage("Coursera Data Science Capstone: Word Prediction Application",
theme = shinytheme("cosmo"),
mainPanel(
h3("App Information"),
h5("This application will predict the next word in
the entered phrase. Up to 5 words will be predicted.
Words are returned in order of their probability
(highest to lowest)."),
h3("Instructions"),
h5("1. Type in an incomplete phrase."),
h5("2. Click the 'Submit' button."),
textInput("textEntry",
h4("Type in any phrase"),
value = "Pick up a case of"),
submitButton("Submit"),
h3("Predicted Words:"),
h1(textOutput("text"))
)
))
|
library(NSM3)
### Name: cFligPoli
### Title: Computes a critical value for the Fligner-Policello U
### distribution.
### Aliases: cFligPoli
### Keywords: Fligner-Policello
### ** Examples
##Chapter 4 example Hollander-Wolfe-Chicken##
cFligPoli(.0504,8,7)
cFligPoli(.101,8,7)
| /data/genthat_extracted_code/NSM3/examples/cFligPoli.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 284 | r | library(NSM3)
### Name: cFligPoli
### Title: Computes a critical value for the Fligner-Policello U
### distribution.
### Aliases: cFligPoli
### Keywords: Fligner-Policello
### ** Examples
##Chapter 4 example Hollander-Wolfe-Chicken##
cFligPoli(.0504,8,7)
cFligPoli(.101,8,7)
|
# read the data
source("R/read_riat.R")
library(dplyr)
library(glue)
library(futile.logger)
runs <- c( "bpa4fvg_pm10popavg_tech_nontech_2025",
"fvg4fvg_pm10popavg_tech_nontech_2025",
"bpa4fvg_pm10popavg_tech_2025",
"fvg4fvg_pm10popavg_tech_2025"
)
models <- c("farm_pi",
"ninfa_er")
pollutant <- "PM10"
Dat <- NULL
for (mm in models) {
for (pp in 1:5) {
for (rr in runs) {
filein <- glue("data/data_prepair_{mm}/run/{rr}/AD{pp}.xls")
flog.info(glue("Reading {filein}"))
read_activity_details_xls(filein=glue(filein)) %>%
mutate(Model=mm, Point=pp, Run=rr, Pollutant=pollutant) %>%
bind_rows(Dat) -> Dat
}
}
}
# prepare for plotting
library(tidyr)
source("~/src/rutilante/R/gg_themes.R")
library(stringr)
library(forcats)
library(ggrepel)
library(scales)
library(RColorBrewer)
Dat %>%
mutate(Cost=`CostOverCle[M€]`) %>%
group_by(Macrosector,Point,Model,Run) %>%
summarize(Cost=sum(Cost,na.rm=T),.groups="drop") %>%
group_by(Macrosector,Point,Run) %>%
summarize(Cost=mean(Cost),.groups="drop") %>%
group_by(Point,Run) %>%
mutate(TotalCost=round(sum(Cost))) %>%
ungroup()%>%
filter(TotalCost>0,
Cost>=0.01*TotalCost) %>%
mutate(TotalCost=as.factor(TotalCost),
Macrosector=as.factor(Macrosector)) -> dd
ms <- sort(unique(Dat$Macrosector))
cols <- brewer.pal(n = length(ms), name = "Set3")
names(cols) <- ms
# costs synthetic plot
fileout <- glue("scenariosTotCosts_{pollutant}_synthetic.pdf")
pdf(fileout, width=7,height=3)
for (rr in unique(dd$Run)) {
ggplot(data=dd%>%filter(Run==rr)) +
geom_col(aes(x=TotalCost,y=Cost,fill=Macrosector),color="grey40") +
labs(title="",
subtitle=glue("run: {rr}",
"\nmodel{ifelse(length(models)>1,'s','')}: {paste(models,collapse=', ')}")) +
xlab("total cost of the scenario (MEUR)")+
ylab(glue("cost (MEUR)")) +
coord_flip()+
scale_fill_manual(values=cols)+
theme_fvg()+
theme(panel.grid.major.x = element_line(colour="grey90",size=0.35),
panel.grid.major.y = element_blank(),
aspect.ratio = 0.4,
legend.position="right") -> p
print(p)
}
dev.off()
embed_fonts(fileout)
| /R/plot_costs.R | no_license | jobonaf/riat-postproc | R | false | false | 2,207 | r | # read the data
source("R/read_riat.R")
library(dplyr)
library(glue)
library(futile.logger)
runs <- c( "bpa4fvg_pm10popavg_tech_nontech_2025",
"fvg4fvg_pm10popavg_tech_nontech_2025",
"bpa4fvg_pm10popavg_tech_2025",
"fvg4fvg_pm10popavg_tech_2025"
)
models <- c("farm_pi",
"ninfa_er")
pollutant <- "PM10"
Dat <- NULL
for (mm in models) {
for (pp in 1:5) {
for (rr in runs) {
filein <- glue("data/data_prepair_{mm}/run/{rr}/AD{pp}.xls")
flog.info(glue("Reading {filein}"))
read_activity_details_xls(filein=glue(filein)) %>%
mutate(Model=mm, Point=pp, Run=rr, Pollutant=pollutant) %>%
bind_rows(Dat) -> Dat
}
}
}
# prepare for plotting
library(tidyr)
source("~/src/rutilante/R/gg_themes.R")
library(stringr)
library(forcats)
library(ggrepel)
library(scales)
library(RColorBrewer)
Dat %>%
mutate(Cost=`CostOverCle[M€]`) %>%
group_by(Macrosector,Point,Model,Run) %>%
summarize(Cost=sum(Cost,na.rm=T),.groups="drop") %>%
group_by(Macrosector,Point,Run) %>%
summarize(Cost=mean(Cost),.groups="drop") %>%
group_by(Point,Run) %>%
mutate(TotalCost=round(sum(Cost))) %>%
ungroup()%>%
filter(TotalCost>0,
Cost>=0.01*TotalCost) %>%
mutate(TotalCost=as.factor(TotalCost),
Macrosector=as.factor(Macrosector)) -> dd
ms <- sort(unique(Dat$Macrosector))
cols <- brewer.pal(n = length(ms), name = "Set3")
names(cols) <- ms
# costs synthetic plot
fileout <- glue("scenariosTotCosts_{pollutant}_synthetic.pdf")
pdf(fileout, width=7,height=3)
for (rr in unique(dd$Run)) {
ggplot(data=dd%>%filter(Run==rr)) +
geom_col(aes(x=TotalCost,y=Cost,fill=Macrosector),color="grey40") +
labs(title="",
subtitle=glue("run: {rr}",
"\nmodel{ifelse(length(models)>1,'s','')}: {paste(models,collapse=', ')}")) +
xlab("total cost of the scenario (MEUR)")+
ylab(glue("cost (MEUR)")) +
coord_flip()+
scale_fill_manual(values=cols)+
theme_fvg()+
theme(panel.grid.major.x = element_line(colour="grey90",size=0.35),
panel.grid.major.y = element_blank(),
aspect.ratio = 0.4,
legend.position="right") -> p
print(p)
}
dev.off()
embed_fonts(fileout)
|
# Import and clean the 2011 Zambia Presidental Election results -----------
# At the constituency level
# Laura Hughes, lhughes@usaid.gov, USAID | GeoCenter
# setup -------------------------------------------------------------------
# taken care of in ZMB_E01_helpers.R
# library(readxl)
# library(dplyr)
# library(stringr)
# library(tidyr)
# library(readr)
#
# base_dir = '~/Documents/GitHub/Zambia/'
# goals -------------------------------------------------------------------
# (0) Import the data
# (1) Calculate the vote totals for each candidate by constituency
# (2) Calculate voting turnout per constituency
# import data -------------------------------------------------------------
# data pulled from http://www.elections.org.zm/media/28092011_public_notice_-_2011_presidential_election_results.pdf
# on 29 June 2017
# Extracted from pdf using Tabula (http://tabula.technology/) to begin the cleaning process
pr11_raw = read_csv('rawdata/tabula-2011_presidential_election_results.csv')
# glance at structure
# glimpse(pr11_raw)
# check if columns are necessary
# t(pr11_raw %>% summarise_all(funs(sum(!is.na(.)))))
# (0) import and prelim clean ---------------------------------------------
# So, annoyingly, the data is structured as such:
# candidate_region contains an initial row specifying the constituency name
# then are the constituency vote totals by party
# followed by the constituency summary totals
pr11_all = pr11_raw %>%
mutate(
# constituencies are all labeled by numbers (yay order);
# province totals specified by "Province" (though tried to remove all of them so they don't muck things up)
constit = ifelse(str_detect(candidate_region, '[0-9]') | str_detect(candidate_region, 'Province'), candidate_region, NA),
# constituency totals have NA in the candidate regions
total = ifelse(is.na(candidate_region), 1, 0),
# convert votes to numeric
vote_count = str2num(Votes),
year = 2011,
# create copy of candidate_region and a flag for if it's a candidate row
# candidate names and their parties are separated by a comma
isCandidate = ifelse(str_detect(candidate_region, '\\,'), 1, 0)
) %>%
# fill down constituency names
fill(constit) %>%
# split constit into id and name
separate(constit, into = c('constit_id', 'constit1', 'constit2'), sep = ' ') %>%
# split candidate_region into candidate name and party affiliation
separate(candidate_region, into = c('candidate', 'party'), sep = '\\,', remove = FALSE) %>%
# split name into first, middle, last name
split_candid('candidate') %>%
# make constit purty
mutate(website2011 = ifelse(is.na(constit2), str_to_title(constit1),
str_to_title(paste(constit1, constit2))),
# remove names if not a candidate
first_name = ifelse(isCandidate, first_name, NA),
last_name = ifelse(isCandidate, last_name, NA),
candidate = ifelse(isCandidate, candidate, NA)
)
# check import looks right ------------------------------------------------
# should all have 12
# View(pr11_all %>% count(constit_id))
# # (1) Votes per candidate -----------------------------------------------
pr11 = pr11_all %>%
filter(isCandidate == 1) %>%
select(constit_id, website2011, year,
candidate, first_name, last_name, party,
vote_count, contains('pct')) %>%
mutate(
# convert to number, percent
pct_cast_web = str2pct(pct_cast_web),
pct_registered_web = str2pct(pct_registered_web)) %>%
# merge_geo
left_join(geo_base %>% select(constituency, province2006, district2006, website2011), by = 'website2011') %>%
rename(province = province2006, district = district2006) %>%
calc_stats()
#http://lightonphiri.org/blog/visualising-the-zambia-2015-presidential-by-election-results
#http://documents.worldbank.org/curated/en/766931468137977527/text/952760WP0Mappi0mbia0Report00PUBLIC0.txt
# (2) Voting turnout by constituency --------------------------------------
# totals at the constituency level; also includes number of rejected votes
pr11_total = pr11_all %>%
filter(total == 1,
# remove extra text taken along for the ride
!is.na(vote_count)
) %>%
mutate(
# convert to number
rejected = str2num(rejected_ballotpapers),
cast = str2num(total_votes),
registered = str2num(total_registered),
# convert to number, percent
pct_cast_web = str2pct(pct_cast_web),
pct_registered_web = str2pct(pct_registered_web),
turnout_web = str2pct(turnout_web),
pct_rejected_web = str2pct(pct_rejected_web)
) %>%
calc_turnout() %>%
# merge_geo
left_join(geo_base %>% select(constituency, province2006, district2006, website2011), by = 'website2011') %>%
rename(province = province2006, district = district2006)
# After check by eye, pct_rejected calc looks on target with what Zambia reports; dropping their formatted number
# pct_poll is equivalent to turnout.
# finish pr11 calcs -------------------------------------------------------
# merges the total number of votes cast, to calculate the percent of votes received by the toal number cast.
pr11 = pr11 %>% merge_turnout(pr11_total)
# run checks --------------------------------------------------------------
check_pct(pr11)
check_turnout(pr11_total)
check_constit(pr11, pr11_total)
# cleanup -----------------------------------------------------------------
rm(pr11_all, pr11_raw)
pr11 = filter_candid(pr11)
pr11_total = filter_turnout(pr11_total)
| /ZMB_E05_pres2011_clean.R | permissive | tessam30/Zambia | R | false | false | 5,538 | r |
# Import and clean the 2011 Zambia Presidental Election results -----------
# At the constituency level
# Laura Hughes, lhughes@usaid.gov, USAID | GeoCenter
# setup -------------------------------------------------------------------
# taken care of in ZMB_E01_helpers.R
# library(readxl)
# library(dplyr)
# library(stringr)
# library(tidyr)
# library(readr)
#
# base_dir = '~/Documents/GitHub/Zambia/'
# goals -------------------------------------------------------------------
# (0) Import the data
# (1) Calculate the vote totals for each candidate by constituency
# (2) Calculate voting turnout per constituency
# import data -------------------------------------------------------------
# data pulled from http://www.elections.org.zm/media/28092011_public_notice_-_2011_presidential_election_results.pdf
# on 29 June 2017
# Extracted from pdf using Tabula (http://tabula.technology/) to begin the cleaning process
pr11_raw = read_csv('rawdata/tabula-2011_presidential_election_results.csv')
# glance at structure
# glimpse(pr11_raw)
# check if columns are necessary
# t(pr11_raw %>% summarise_all(funs(sum(!is.na(.)))))
# (0) import and prelim clean ---------------------------------------------
# So, annoyingly, the data is structured as such:
# candidate_region contains an initial row specifying the constituency name
# then are the constituency vote totals by party
# followed by the constituency summary totals
pr11_all = pr11_raw %>%
mutate(
# constituencies are all labeled by numbers (yay order);
# province totals specified by "Province" (though tried to remove all of them so they don't muck things up)
constit = ifelse(str_detect(candidate_region, '[0-9]') | str_detect(candidate_region, 'Province'), candidate_region, NA),
# constituency totals have NA in the candidate regions
total = ifelse(is.na(candidate_region), 1, 0),
# convert votes to numeric
vote_count = str2num(Votes),
year = 2011,
# create copy of candidate_region and a flag for if it's a candidate row
# candidate names and their parties are separated by a comma
isCandidate = ifelse(str_detect(candidate_region, '\\,'), 1, 0)
) %>%
# fill down constituency names
fill(constit) %>%
# split constit into id and name
separate(constit, into = c('constit_id', 'constit1', 'constit2'), sep = ' ') %>%
# split candidate_region into candidate name and party affiliation
separate(candidate_region, into = c('candidate', 'party'), sep = '\\,', remove = FALSE) %>%
# split name into first, middle, last name
split_candid('candidate') %>%
# make constit purty
mutate(website2011 = ifelse(is.na(constit2), str_to_title(constit1),
str_to_title(paste(constit1, constit2))),
# remove names if not a candidate
first_name = ifelse(isCandidate, first_name, NA),
last_name = ifelse(isCandidate, last_name, NA),
candidate = ifelse(isCandidate, candidate, NA)
)
# check import looks right ------------------------------------------------
# should all have 12
# View(pr11_all %>% count(constit_id))
# # (1) Votes per candidate -----------------------------------------------
pr11 = pr11_all %>%
filter(isCandidate == 1) %>%
select(constit_id, website2011, year,
candidate, first_name, last_name, party,
vote_count, contains('pct')) %>%
mutate(
# convert to number, percent
pct_cast_web = str2pct(pct_cast_web),
pct_registered_web = str2pct(pct_registered_web)) %>%
# merge_geo
left_join(geo_base %>% select(constituency, province2006, district2006, website2011), by = 'website2011') %>%
rename(province = province2006, district = district2006) %>%
calc_stats()
#http://lightonphiri.org/blog/visualising-the-zambia-2015-presidential-by-election-results
#http://documents.worldbank.org/curated/en/766931468137977527/text/952760WP0Mappi0mbia0Report00PUBLIC0.txt
# (2) Voting turnout by constituency --------------------------------------
# totals at the constituency level; also includes number of rejected votes
pr11_total = pr11_all %>%
filter(total == 1,
# remove extra text taken along for the ride
!is.na(vote_count)
) %>%
mutate(
# convert to number
rejected = str2num(rejected_ballotpapers),
cast = str2num(total_votes),
registered = str2num(total_registered),
# convert to number, percent
pct_cast_web = str2pct(pct_cast_web),
pct_registered_web = str2pct(pct_registered_web),
turnout_web = str2pct(turnout_web),
pct_rejected_web = str2pct(pct_rejected_web)
) %>%
calc_turnout() %>%
# merge_geo
left_join(geo_base %>% select(constituency, province2006, district2006, website2011), by = 'website2011') %>%
rename(province = province2006, district = district2006)
# After check by eye, pct_rejected calc looks on target with what Zambia reports; dropping their formatted number
# pct_poll is equivalent to turnout.
# finish pr11 calcs -------------------------------------------------------
# merges the total number of votes cast, to calculate the percent of votes received by the toal number cast.
pr11 = pr11 %>% merge_turnout(pr11_total)
# run checks --------------------------------------------------------------
check_pct(pr11)
check_turnout(pr11_total)
check_constit(pr11, pr11_total)
# cleanup -----------------------------------------------------------------
rm(pr11_all, pr11_raw)
pr11 = filter_candid(pr11)
pr11_total = filter_turnout(pr11_total)
|
# This code runs the Montoya & Hayes (2016) MEMORE within-subjects mediation
# boostrap resampling analysis in R.
# Written by Richard Stephens
#Open libraries
library(broom)
library(dplyr)
library(boot)
library(tidyverse)
#Set working directory
setwd("C:/Users/user/R/MEMORE in R")
# open dataset
data <- read.csv("Montoya_data.csv")
#Identify M1, M2, Y1, Y2 by renaming pertinent columns in the dataset
#If data columns already labelled M1 etc, then use # to ignore next 4 lines
#names(data)[names(data) == 'Your_M1'] <- 'M1'
#names(data)[names(data) == 'Your_M2'] <- 'M2'
#names(data)[names(data) == 'Your_Y1'] <- 'Y1'
#names(data)[names(data) == 'Your_Y2'] <- 'Y2'
# Calculate M_diff, Y_diff, Msum, MeanMsum, MsumCen (centred)
data$M_diff <- data$M2 - data$M1
data$Y_diff <- data$Y2 - data$Y1
data$Msum <- data$M1 + data$M2
data$MeanMsum <- mean (data$Msum)
data$MsumCen <- data$Msum - data$MeanMsum
# calculate value of coef a
a <- mean(data$M_diff)
# calculate value of coef b, SE of coef b, and 95% CI of b
# via regression of M_diff and MsumCen on Y_diff
# Uses matrix function to send regression output to a matrix...
# and then extracts b and SE b from the matrix
# final two lines calculate the upper and lower 95% CI
matrix_b <- summary(lm(Y_diff ~ M_diff + MsumCen, data))$coefficients
b <- matrix_b[2 , 1]
b_se <- matrix_b[2 , 2]
lower_ci_b <- b -(1.96 * b_se)
upper_ci_b <- b +(1.96 * b_se)
# calculate ab, coef of indirect effect, as product a*b
ab <- a * b
# function to calculate a*b for the bootstrap resampling
# this is entered into the boot command
foo <- function(data, i){
d2 <- data[i,]
f_M_diff <- d2$M2 - d2$M1
f_Y_diff <- d2$Y2 - d2$Y1
f_Msum <- d2$M1 + d2$M2
f_MeanMsum <- mean (f_Msum)
f_MsumCen <- f_Msum - f_MeanMsum
f_a <- mean(f_M_diff)
f_matrix_b <- summary(lm(f_Y_diff ~ f_M_diff + f_MsumCen, data))$coefficients
f_b <- f_matrix_b[2 , 1]
f_ab <- f_a * f_b
return(f_ab)
}
# Does X predict Y? Paired samples t-test
# the mutate command changes Y1 to Y3 to correct sign of t and 95% CI
beta_ydiff <- mean (data$Y_diff)
beta_ydiff #beta value (c)
data_y.long <- data %>%
select(Y2, Y1) %>%
gather(key = "group_y", value = "score_y", Y2, Y1) %>%
mutate(group_y = ifelse(as.character(group_y) == "Y1", "Y3", as.character(group_y)))
res_y <- t.test(score_y ~ group_y, data = data_y.long, paired = TRUE)
# Does X predict M? Paired samples t-test
# the mutate command changes M1 to M3 to correct sign of t and 95% CI
beta_mdiff <- mean (data$M_diff)
beta_mdiff #beta value (a)
data_m.long <- data %>%
select(M1, M2) %>%
gather(key = "group_m", value = "score_m", M2, M1) %>%
mutate(group_m = ifelse(as.character(group_m) == "M1", "M3", as.character(group_m)))
res_m <- t.test(score_m ~ group_m, data = data_m.long, paired = TRUE)
# Run boostrap for a*b
# Recommend use "percentile" bootstrap estimate of 95% CI
# Use value R = x to set number of boostrap samples
set.seed(42)
result <- boot(data, foo, R=5000)
# *******************OUTPUT STARTS HERE************************************
# ********Does X predict Y? Paired samples t-test output********
# ********Coefficient c is "mean of the differences" ********
res_y
# ********Does X predict M? Paired samples t-test output********
# ********Coefficient a is "mean of the differences"********
res_m
# ********Does M predict Y? Regression of M_diff and MsumCen on Y_diff********
# ********Coefficient b (M_diff) is labelled "b" ********
b
lower_ci_b
upper_ci_b
# ********Indirect effect of X on Y, via M (ab)********
# ********Coefficient c' (ab)********
ab
# Boostrap analysis of distribution of Coefficient c' (ab)
# Recommend use "percentile" bootstrap estimate of 95% CI
boot.ci(result, index=1) | /rs_memore_bootstrap.R | no_license | PsychologyRich/PsychologyRich.github.io | R | false | false | 3,849 | r | # This code runs the Montoya & Hayes (2016) MEMORE within-subjects mediation
# boostrap resampling analysis in R.
# Written by Richard Stephens
#Open libraries
library(broom)
library(dplyr)
library(boot)
library(tidyverse)
#Set working directory
setwd("C:/Users/user/R/MEMORE in R")
# open dataset
data <- read.csv("Montoya_data.csv")
#Identify M1, M2, Y1, Y2 by renaming pertinent columns in the dataset
#If data columns already labelled M1 etc, then use # to ignore next 4 lines
#names(data)[names(data) == 'Your_M1'] <- 'M1'
#names(data)[names(data) == 'Your_M2'] <- 'M2'
#names(data)[names(data) == 'Your_Y1'] <- 'Y1'
#names(data)[names(data) == 'Your_Y2'] <- 'Y2'
# Calculate M_diff, Y_diff, Msum, MeanMsum, MsumCen (centred)
data$M_diff <- data$M2 - data$M1
data$Y_diff <- data$Y2 - data$Y1
data$Msum <- data$M1 + data$M2
data$MeanMsum <- mean (data$Msum)
data$MsumCen <- data$Msum - data$MeanMsum
# calculate value of coef a
a <- mean(data$M_diff)
# calculate value of coef b, SE of coef b, and 95% CI of b
# via regression of M_diff and MsumCen on Y_diff
# Uses matrix function to send regression output to a matrix...
# and then extracts b and SE b from the matrix
# final two lines calculate the upper and lower 95% CI
matrix_b <- summary(lm(Y_diff ~ M_diff + MsumCen, data))$coefficients
b <- matrix_b[2 , 1]
b_se <- matrix_b[2 , 2]
lower_ci_b <- b -(1.96 * b_se)
upper_ci_b <- b +(1.96 * b_se)
# calculate ab, coef of indirect effect, as product a*b
ab <- a * b
# function to calculate a*b for the bootstrap resampling
# this is entered into the boot command
foo <- function(data, i){
d2 <- data[i,]
f_M_diff <- d2$M2 - d2$M1
f_Y_diff <- d2$Y2 - d2$Y1
f_Msum <- d2$M1 + d2$M2
f_MeanMsum <- mean (f_Msum)
f_MsumCen <- f_Msum - f_MeanMsum
f_a <- mean(f_M_diff)
f_matrix_b <- summary(lm(f_Y_diff ~ f_M_diff + f_MsumCen, data))$coefficients
f_b <- f_matrix_b[2 , 1]
f_ab <- f_a * f_b
return(f_ab)
}
# Does X predict Y? Paired samples t-test
# the mutate command changes Y1 to Y3 to correct sign of t and 95% CI
beta_ydiff <- mean (data$Y_diff)
beta_ydiff #beta value (c)
data_y.long <- data %>%
select(Y2, Y1) %>%
gather(key = "group_y", value = "score_y", Y2, Y1) %>%
mutate(group_y = ifelse(as.character(group_y) == "Y1", "Y3", as.character(group_y)))
res_y <- t.test(score_y ~ group_y, data = data_y.long, paired = TRUE)
# Does X predict M? Paired samples t-test
# the mutate command changes M1 to M3 to correct sign of t and 95% CI
beta_mdiff <- mean (data$M_diff)
beta_mdiff #beta value (a)
data_m.long <- data %>%
select(M1, M2) %>%
gather(key = "group_m", value = "score_m", M2, M1) %>%
mutate(group_m = ifelse(as.character(group_m) == "M1", "M3", as.character(group_m)))
res_m <- t.test(score_m ~ group_m, data = data_m.long, paired = TRUE)
# Run boostrap for a*b
# Recommend use "percentile" bootstrap estimate of 95% CI
# Use value R = x to set number of boostrap samples
set.seed(42)
result <- boot(data, foo, R=5000)
# *******************OUTPUT STARTS HERE************************************
# ********Does X predict Y? Paired samples t-test output********
# ********Coefficient c is "mean of the differences" ********
res_y
# ********Does X predict M? Paired samples t-test output********
# ********Coefficient a is "mean of the differences"********
res_m
# ********Does M predict Y? Regression of M_diff and MsumCen on Y_diff********
# ********Coefficient b (M_diff) is labelled "b" ********
b
lower_ci_b
upper_ci_b
# ********Indirect effect of X on Y, via M (ab)********
# ********Coefficient c' (ab)********
ab
# Boostrap analysis of distribution of Coefficient c' (ab)
# Recommend use "percentile" bootstrap estimate of 95% CI
boot.ci(result, index=1) |
loadData<-function() {
#download zip and unzip .txt file
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
message("downloading file...")
download.file(fileUrl, destfile="household_power_consumption.zip", method="curl")
txtfile <- unz("household_power_consumption.zip", "household_power_consumption.txt")
#load
data<-read.csv(txtfile, header=TRUE, sep=";", na.strings="?")
#subset and formatting
subset<-subset(data, data$Date=="1/2/2007" | data$Date=="2/2/2007")
#subset$DateTime <- as.POSIXct(paste(subset$Date,subset$Time))
subset$DateTime <- strptime(paste(subset$Date, subset$Time), "%d/%m/%Y %H:%M:%S")
subset[,2:8]<-sapply(subset[,2:8],as.numeric)
subset
} | /loadData.R | no_license | ernene/ExData_Plotting1 | R | false | false | 778 | r | loadData<-function() {
#download zip and unzip .txt file
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
message("downloading file...")
download.file(fileUrl, destfile="household_power_consumption.zip", method="curl")
txtfile <- unz("household_power_consumption.zip", "household_power_consumption.txt")
#load
data<-read.csv(txtfile, header=TRUE, sep=";", na.strings="?")
#subset and formatting
subset<-subset(data, data$Date=="1/2/2007" | data$Date=="2/2/2007")
#subset$DateTime <- as.POSIXct(paste(subset$Date,subset$Time))
subset$DateTime <- strptime(paste(subset$Date, subset$Time), "%d/%m/%Y %H:%M:%S")
subset[,2:8]<-sapply(subset[,2:8],as.numeric)
subset
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/he10coordinates.R
\name{he10coordinates}
\alias{he10coordinates}
\title{City data in the United Kingdom}
\value{
a \sQuote{data.frame} of longitude and lattitude for each town.
}
\description{
Longitude and lattitude for the 20 towns in England and Wales studied by
He et al (2010).
}
\references{
\he2010
}
\seealso{
Other datasets he10:
\code{\link{he10demography}},
\code{\link{he10measles}},
\code{\link{he10mle}}
}
\concept{datasets he10}
| /man/he10coordinates.Rd | no_license | kidusasfaw/spatPomp | R | false | true | 523 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/he10coordinates.R
\name{he10coordinates}
\alias{he10coordinates}
\title{City data in the United Kingdom}
\value{
a \sQuote{data.frame} of longitude and lattitude for each town.
}
\description{
Longitude and lattitude for the 20 towns in England and Wales studied by
He et al (2010).
}
\references{
\he2010
}
\seealso{
Other datasets he10:
\code{\link{he10demography}},
\code{\link{he10measles}},
\code{\link{he10mle}}
}
\concept{datasets he10}
|
library(rredis)
### Name: redisHExists
### Title: Test the existence of a hash.
### Aliases: redisHExists
### ** Examples
## Not run:
##D redisHSet('A','x',runif(5))
##D redisHExists('A','x')
## End(Not run)
| /data/genthat_extracted_code/rredis/examples/redisHExists.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 216 | r | library(rredis)
### Name: redisHExists
### Title: Test the existence of a hash.
### Aliases: redisHExists
### ** Examples
## Not run:
##D redisHSet('A','x',runif(5))
##D redisHExists('A','x')
## End(Not run)
|
## create error models to be released wtih polyester
## from the GemSIM/GemErr estimation model
modfolder = '../polyester_paper/error_models'
platforms = c('ill100v4_mate1', 'ill100v4_mate2',
'ill100v4_single', 'ill100v5_mate1', 'ill100v5_mate2',
'ill100v5_single', 'r454ti_single')
for(platform in platforms){
i = which(platforms == platform)
model = read.table(paste(modfolder, platform, sep='/'), header=TRUE)
names(model)[1] = 'refbase'
model$refbase = substr(model$refbase, 4, 4)
eval(parse(text=paste0('model', i, ' <- model')))
save(list=paste0('model',i), file=paste0('data/', platform, '.rda'),
compress='xz')
}
## figures for paper:
## put one example in true manuscript,
## include the others in supplementary data.
library(RSkittleBrewer)
library(usefulstuff)
colrs = RSkittleBrewer('tropical')
getColor = function(nt){
switch(nt, A='black', C=colrs[1], G=colrs[2], T='deeppink', N=colrs[4])
}
nts = c('A','C','G','T','N')
plot_nt = function(model, nt){
d = subset(model, refbase==nt)
wrongnts = nts[-which(nts==nt)]
errCols = paste0('read', wrongnts)
mnum = as.matrix(model[,2:6])
ymax = max(mnum[mnum<0.8])
plot(1:100, as.matrix(d[errCols[1]])[-1], col=makeTransparent(getColor(wrongnts[1])),
pch=19, cex=0.5, xlab='Read Position', ylab='Error Probability',
type='o', ylim=c(0,ymax))
for(i in 2:4){
points(1:100, as.matrix(d[errCols[i]])[-1], pch=19, cex=0.5, type='o',
col=makeTransparent(getColor(wrongnts[i])))
}
title(nt)
legend('topleft', wrongnts, pch=19, col=sapply(wrongnts, getColor), cex=0.7)
}
plot_model = function(model, file){
pdf(file)
par(mfrow=c(2,2))
for(nt in c('A','C','G','T')){
plot_nt(model, nt)
}
dev.off()
}
plot_model(model1, 'illumina4_mate1.pdf')
plot_model(model2, 'illumina4_mate2.pdf')
plot_model(model3, 'illumina4_single.pdf')
plot_model(model4, 'illumina5_mate1.pdf')
plot_model(model5, 'illumina5_mate2.pdf')
plot_model(model6, 'illumina5_single.pdf')
| /make_error_models.R | no_license | Christina-hshi/polyester-LC | R | false | false | 2,063 | r | ## create error models to be released wtih polyester
## from the GemSIM/GemErr estimation model
modfolder = '../polyester_paper/error_models'
platforms = c('ill100v4_mate1', 'ill100v4_mate2',
'ill100v4_single', 'ill100v5_mate1', 'ill100v5_mate2',
'ill100v5_single', 'r454ti_single')
for(platform in platforms){
i = which(platforms == platform)
model = read.table(paste(modfolder, platform, sep='/'), header=TRUE)
names(model)[1] = 'refbase'
model$refbase = substr(model$refbase, 4, 4)
eval(parse(text=paste0('model', i, ' <- model')))
save(list=paste0('model',i), file=paste0('data/', platform, '.rda'),
compress='xz')
}
## figures for paper:
## put one example in true manuscript,
## include the others in supplementary data.
library(RSkittleBrewer)
library(usefulstuff)
colrs = RSkittleBrewer('tropical')
getColor = function(nt){
switch(nt, A='black', C=colrs[1], G=colrs[2], T='deeppink', N=colrs[4])
}
nts = c('A','C','G','T','N')
plot_nt = function(model, nt){
d = subset(model, refbase==nt)
wrongnts = nts[-which(nts==nt)]
errCols = paste0('read', wrongnts)
mnum = as.matrix(model[,2:6])
ymax = max(mnum[mnum<0.8])
plot(1:100, as.matrix(d[errCols[1]])[-1], col=makeTransparent(getColor(wrongnts[1])),
pch=19, cex=0.5, xlab='Read Position', ylab='Error Probability',
type='o', ylim=c(0,ymax))
for(i in 2:4){
points(1:100, as.matrix(d[errCols[i]])[-1], pch=19, cex=0.5, type='o',
col=makeTransparent(getColor(wrongnts[i])))
}
title(nt)
legend('topleft', wrongnts, pch=19, col=sapply(wrongnts, getColor), cex=0.7)
}
plot_model = function(model, file){
pdf(file)
par(mfrow=c(2,2))
for(nt in c('A','C','G','T')){
plot_nt(model, nt)
}
dev.off()
}
plot_model(model1, 'illumina4_mate1.pdf')
plot_model(model2, 'illumina4_mate2.pdf')
plot_model(model3, 'illumina4_single.pdf')
plot_model(model4, 'illumina5_mate1.pdf')
plot_model(model5, 'illumina5_mate2.pdf')
plot_model(model6, 'illumina5_single.pdf')
|
\docType{package}
\name{Rd2roxygen-package}
\alias{Rd2roxygen-package}
\title{Convert Rd to roxygen documentation and utilities to enhance documentation
and building packages}
\description{
This package contains functions to convert Rd to roxygen documentation. It
can parse an Rd file to a list (\code{\link{parse_file}}), create the roxygen
documentation (\code{\link{create_roxygen}}) and update the original R script
(e.g. the one containing the definition of the function) accordingly
(\code{\link{Rd2roxygen}}). This package also provides utilities which can
help developers build packages using roxygen more easily (\code{\link{rab}}).
}
\note{
There is no guarantee to generate perfect roxygen comments that can
convert back to the original Rd files. Usually manual manipulations on the
roxygen comments are required. For example, currently `@S3method` is not
included in the comments, and `@rdname` is not supported either (users
have to move the roxygen comments around and add the appropriate tags by
themselves). Patches are welcome through GitHub:
\url{https://github.com/yihui/Rd2roxygen/}.
This package is not thoroughly tested, so it is likely that it fails to
convert certain parts of Rd files to roxygen comments. As mentioned before,
we have to manually deal with these problems. You are welcome to report
other serious issues via \url{https://github.com/yihui/Rd2roxygen/issues}.
}
\examples{
## see the package vignette: vignette('Rd2roxygen')
}
\author{
Hadley Wickham and Yihui Xie
}
| /man/Rd2roxygen-package.Rd | no_license | yfyang86/Rd2roxygen | R | false | false | 1,528 | rd | \docType{package}
\name{Rd2roxygen-package}
\alias{Rd2roxygen-package}
\title{Convert Rd to roxygen documentation and utilities to enhance documentation
and building packages}
\description{
This package contains functions to convert Rd to roxygen documentation. It
can parse an Rd file to a list (\code{\link{parse_file}}), create the roxygen
documentation (\code{\link{create_roxygen}}) and update the original R script
(e.g. the one containing the definition of the function) accordingly
(\code{\link{Rd2roxygen}}). This package also provides utilities which can
help developers build packages using roxygen more easily (\code{\link{rab}}).
}
\note{
There is no guarantee to generate perfect roxygen comments that can
convert back to the original Rd files. Usually manual manipulations on the
roxygen comments are required. For example, currently `@S3method` is not
included in the comments, and `@rdname` is not supported either (users
have to move the roxygen comments around and add the appropriate tags by
themselves). Patches are welcome through GitHub:
\url{https://github.com/yihui/Rd2roxygen/}.
This package is not thoroughly tested, so it is likely that it fails to
convert certain parts of Rd files to roxygen comments. As mentioned before,
we have to manually deal with these problems. You are welcome to report
other serious issues via \url{https://github.com/yihui/Rd2roxygen/issues}.
}
\examples{
## see the package vignette: vignette('Rd2roxygen')
}
\author{
Hadley Wickham and Yihui Xie
}
|
nnumattr <-
function(df){
# Number of numeric attributes
pct<-0
for (i in 1:dim(df)[2]){
if (is.numeric(df[,i])) pct<-pct+1
}
pct
}
| /parviol/R/nnumattr.R | no_license | ingted/R-Examples | R | false | false | 149 | r | nnumattr <-
function(df){
# Number of numeric attributes
pct<-0
for (i in 1:dim(df)[2]){
if (is.numeric(df[,i])) pct<-pct+1
}
pct
}
|
# Initial settings
rm(list = ls())
gc()
require(pedometrics)
sapply(list.files("R", full.names = TRUE, pattern = ".R$"), source)
sapply(list.files("src", full.names = TRUE, pattern = ".cpp$"), Rcpp::sourceCpp)
# 0) DEFAULT EXAMPLE ###########################################################
require(sp)
require(SpatialTools)
data(meuse.grid)
candi <- meuse.grid[, 1:2]
# Define the objective function - number of points per lag distance class
objUSER <-
function (points, lags, n_lags, n_pts) {
dm <- SpatialTools::dist1(points[, 2:3])
ppl <- vector()
for (i in 1:n_lags) {
n <- which(dm > lags[i] & dm <= lags[i + 1], arr.ind = TRUE)
ppl[i] <- length(unique(c(n)))
}
distri <- rep(n_pts, n_lags)
res <- sum(distri - ppl)
}
lags <- seq(1, 1000, length.out = 10)
# Run the optimization using the user-defined objective function
set.seed(2001)
timeUSER <- Sys.time()
resUSER <- optimUSER(points = 100, fun = objUSER, lags = lags, n_lags = 9,
n_pts = 100, candi = candi)
timeUSER <- Sys.time() - timeUSER
# Run the optimization using the respective function implemented in spsann
set.seed(2001)
timePPL <- Sys.time()
resPPL <- optimPPL(points = 100, candi = candi, lags = lags)
timePPL <- Sys.time() - timePPL
# Compare results
timeUSER
timePPL
lapply(list(resUSER, resPPL), countPPL, candi = candi, lags = lags)
objSPSANN(resUSER) # 58
objSPSANN(resPPL) # 58
| /battlefield/optimUSER_battle.R | no_license | gmvasques/spsann | R | false | false | 1,405 | r | # Initial settings
rm(list = ls())
gc()
require(pedometrics)
sapply(list.files("R", full.names = TRUE, pattern = ".R$"), source)
sapply(list.files("src", full.names = TRUE, pattern = ".cpp$"), Rcpp::sourceCpp)
# 0) DEFAULT EXAMPLE ###########################################################
require(sp)
require(SpatialTools)
data(meuse.grid)
candi <- meuse.grid[, 1:2]
# Define the objective function - number of points per lag distance class
objUSER <-
function (points, lags, n_lags, n_pts) {
dm <- SpatialTools::dist1(points[, 2:3])
ppl <- vector()
for (i in 1:n_lags) {
n <- which(dm > lags[i] & dm <= lags[i + 1], arr.ind = TRUE)
ppl[i] <- length(unique(c(n)))
}
distri <- rep(n_pts, n_lags)
res <- sum(distri - ppl)
}
lags <- seq(1, 1000, length.out = 10)
# Run the optimization using the user-defined objective function
set.seed(2001)
timeUSER <- Sys.time()
resUSER <- optimUSER(points = 100, fun = objUSER, lags = lags, n_lags = 9,
n_pts = 100, candi = candi)
timeUSER <- Sys.time() - timeUSER
# Run the optimization using the respective function implemented in spsann
set.seed(2001)
timePPL <- Sys.time()
resPPL <- optimPPL(points = 100, candi = candi, lags = lags)
timePPL <- Sys.time() - timePPL
# Compare results
timeUSER
timePPL
lapply(list(resUSER, resPPL), countPPL, candi = candi, lags = lags)
objSPSANN(resUSER) # 58
objSPSANN(resPPL) # 58
|
#' Run mcl.
#'
#' This is a wrapper for the Markov Cluster Algorithm (mcl), a clustering algorithm
#' for graphs. Here, it is meant to be used on genetic distances from BLAST.
#'
#' @param mcl_input Character vector of length one; the path to the input file
#' for mcl clustering.
#' @param mcl_output Character vector of length one; the path to the output
#' file produced by the mcl algorithm.
#' @param i_value Numeric or character vector of length one; the inflation value.
#' @param e_value Numeric or character vector of length one; the minimal -log
#' transformed evalue to be considered by the algorithm.
#' @param other_args Character vector; other arguments to pass to mcl. Each should
#' be an element of the vector. For example, to pass "-abc" to specify the input
#' file format and "--te" to specify number of threads, use \code{c("--abc", "-te", "2")}.
#' @param ... Other arguments. Not used by this function, but meant to be used
#' by \code{\link[drake]{drake_plan}} for tracking during workflows.
#'
#' @return A plain text file of tab-separated values, where each value on a line
#' belongs to the same cluster.
#' @author Joel H Nitta, \email{joelnitta@@gmail.com}
#' @references Stijn van Dongen, A cluster algorithm for graphs. Technical Report INS-R0010, National Research Institute for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. \url{https://micans.org/mcl/}
#' @examples
#' \dontrun{mcl(mcl_input = "some/folder/distance.file", mcl_output = "some/folder/mcl_output.txt", i_value = 1.4, evalue = 5)}
#' @export
mcl <- function (mcl_input, mcl_output, i_value, e_value, other_args = NULL, ...) {
# modify arguments
arguments <- c(mcl_input, "-I", i_value, "-tf", paste0("'gq(", e_value, ")'"), "-o", mcl_output, other_args )
# run command
system2("mcl", arguments)
}
| /R/mcl.R | permissive | joelnitta/baitfindR | R | false | false | 1,832 | r | #' Run mcl.
#'
#' This is a wrapper for the Markov Cluster Algorithm (mcl), a clustering algorithm
#' for graphs. Here, it is meant to be used on genetic distances from BLAST.
#'
#' @param mcl_input Character vector of length one; the path to the input file
#' for mcl clustering.
#' @param mcl_output Character vector of length one; the path to the output
#' file produced by the mcl algorithm.
#' @param i_value Numeric or character vector of length one; the inflation value.
#' @param e_value Numeric or character vector of length one; the minimal -log
#' transformed evalue to be considered by the algorithm.
#' @param other_args Character vector; other arguments to pass to mcl. Each should
#' be an element of the vector. For example, to pass "-abc" to specify the input
#' file format and "--te" to specify number of threads, use \code{c("--abc", "-te", "2")}.
#' @param ... Other arguments. Not used by this function, but meant to be used
#' by \code{\link[drake]{drake_plan}} for tracking during workflows.
#'
#' @return A plain text file of tab-separated values, where each value on a line
#' belongs to the same cluster.
#' @author Joel H Nitta, \email{joelnitta@@gmail.com}
#' @references Stijn van Dongen, A cluster algorithm for graphs. Technical Report INS-R0010, National Research Institute for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. \url{https://micans.org/mcl/}
#' @examples
#' \dontrun{mcl(mcl_input = "some/folder/distance.file", mcl_output = "some/folder/mcl_output.txt", i_value = 1.4, evalue = 5)}
#' @export
mcl <- function (mcl_input, mcl_output, i_value, e_value, other_args = NULL, ...) {
# modify arguments
arguments <- c(mcl_input, "-I", i_value, "-tf", paste0("'gq(", e_value, ")'"), "-o", mcl_output, other_args )
# run command
system2("mcl", arguments)
}
|
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly = TRUE)
source("Utilities.R")
if (length(args) < 3) {stop("At least 3 arguments must be supplied (2 input files and a reference)", call.=FALSE)}
File1 = args[1]
File2 = args[2]
databaseFile = args[3]
OutputDir = ifelse(length(args) == 3, getwd(), args[4])
print(paste("The arguments were:", paste(File1, File2, databaseFile, OutputDir, collapse = ",")))
myAlign = parseNex(databaseFile)
prunedTypes = pruneTypes(myAlign, threshold = THRESH)
redAlign = prunedTypes[[1]]
clusterMap = prunedTypes[[2]]
curFiles = c(File1, File2)
myOutput = wrapperKnownNew(curFiles, redAlign, N = K, graph = GRAPH, unique = UNIQ, split = SPLIT, hidden = FALSE,
maxFrac = MMF, cMap = clusterMap, outDir = OutputDir)
foundFractions = myOutput[[2]]
initDir = getwd()
setwd(OutputDir)
dir.create("Results")
setwd("Results")
dir.create("Fractions")
setwd("Fractions")
Filename = paste0(longestCommonPrefix(File1, File2), "Fractions.csv")
write.table(foundFractions, file = Filename, row.names = FALSE, col.names = TRUE, quote = FALSE, sep = ",")
setwd(initDir) | /Wrapper.R | no_license | WGS-TB/Borrelia | R | false | false | 1,107 | r | #!/usr/bin/env Rscript
args = commandArgs(trailingOnly = TRUE)
source("Utilities.R")
if (length(args) < 3) {stop("At least 3 arguments must be supplied (2 input files and a reference)", call.=FALSE)}
File1 = args[1]
File2 = args[2]
databaseFile = args[3]
OutputDir = ifelse(length(args) == 3, getwd(), args[4])
print(paste("The arguments were:", paste(File1, File2, databaseFile, OutputDir, collapse = ",")))
myAlign = parseNex(databaseFile)
prunedTypes = pruneTypes(myAlign, threshold = THRESH)
redAlign = prunedTypes[[1]]
clusterMap = prunedTypes[[2]]
curFiles = c(File1, File2)
myOutput = wrapperKnownNew(curFiles, redAlign, N = K, graph = GRAPH, unique = UNIQ, split = SPLIT, hidden = FALSE,
maxFrac = MMF, cMap = clusterMap, outDir = OutputDir)
foundFractions = myOutput[[2]]
initDir = getwd()
setwd(OutputDir)
dir.create("Results")
setwd("Results")
dir.create("Fractions")
setwd("Fractions")
Filename = paste0(longestCommonPrefix(File1, File2), "Fractions.csv")
write.table(foundFractions, file = Filename, row.names = FALSE, col.names = TRUE, quote = FALSE, sep = ",")
setwd(initDir) |
server = function(input, output, session) {
rv1 <- reactiveValues( data.mat = NULL )
observeEvent(input$takeSample.pp, {
data<-rweibull(input$plotposn, shape = 1.25, scale = 10)
orig.dat<-sort(data)
rank.dat<-rank(orig.dat)
pp.1<-function(a) {(cumsum(rank.dat/rank.dat)-a)/(length(rank.dat)+1-2*a)}
pp.2<-(cumsum(rank.dat/rank.dat))/(length(rank.dat))
rv1$data.mat<-matrix(NA, ncol = 5, nrow = length(data), byrow = FALSE)
rv1$data.mat[,1]<-orig.dat
rv1$data.mat[,2]<-log(log(1/(1-pp.2)))
rv1$data.mat[,3]<-log(log(1/(1-pp.1(0.5))))
rv1$data.mat[,4]<-log(log(1/(1-pp.1(0.3))))
rv1$data.mat[,5]<-log(log(1/(1-pp.1(0.0))))
colnames(rv1$data.mat)<-c("Data","N-P","Hazen","M-R","Weib")
})
leg<-c(NA,NA,NA)
pch<-c(NA,NA,NA)
col<-c(NA,NA,NA)
output$probplotcompare <- renderPlot({
par(family = "serif", bg = NA, mar = c(4.1,4.25,0.1,2.1))
plot(NA, log = "x", xlab = expression(t[p]),
ylab = expression(Phi[SEV]*" "*(t[p])), ylim = c(-5,2),xlim = c(1,30))
points(rv1$data.mat[,1],rv1$data.mat[,2], pch = 16)
if (1%in%input$plotpos) {points(rv1$data.mat[,1],rv1$data.mat[,3], pch = 16, col = 2)}
if (2%in%input$plotpos) {points(rv1$data.mat[,1],rv1$data.mat[,4], pch = 16, col = "green")}
if (3%in%input$plotpos) {points(rv1$data.mat[,1],rv1$data.mat[,5], pch = 16, col = "blue")}
legend("topleft", legend = leg, bg = NA, bty = "n", pch = pch,col = col)
})
} | /inst/apps/plotting_positions/server.R | no_license | Auburngrads/teachingApps | R | false | false | 1,393 | r | server = function(input, output, session) {
rv1 <- reactiveValues( data.mat = NULL )
observeEvent(input$takeSample.pp, {
data<-rweibull(input$plotposn, shape = 1.25, scale = 10)
orig.dat<-sort(data)
rank.dat<-rank(orig.dat)
pp.1<-function(a) {(cumsum(rank.dat/rank.dat)-a)/(length(rank.dat)+1-2*a)}
pp.2<-(cumsum(rank.dat/rank.dat))/(length(rank.dat))
rv1$data.mat<-matrix(NA, ncol = 5, nrow = length(data), byrow = FALSE)
rv1$data.mat[,1]<-orig.dat
rv1$data.mat[,2]<-log(log(1/(1-pp.2)))
rv1$data.mat[,3]<-log(log(1/(1-pp.1(0.5))))
rv1$data.mat[,4]<-log(log(1/(1-pp.1(0.3))))
rv1$data.mat[,5]<-log(log(1/(1-pp.1(0.0))))
colnames(rv1$data.mat)<-c("Data","N-P","Hazen","M-R","Weib")
})
leg<-c(NA,NA,NA)
pch<-c(NA,NA,NA)
col<-c(NA,NA,NA)
output$probplotcompare <- renderPlot({
par(family = "serif", bg = NA, mar = c(4.1,4.25,0.1,2.1))
plot(NA, log = "x", xlab = expression(t[p]),
ylab = expression(Phi[SEV]*" "*(t[p])), ylim = c(-5,2),xlim = c(1,30))
points(rv1$data.mat[,1],rv1$data.mat[,2], pch = 16)
if (1%in%input$plotpos) {points(rv1$data.mat[,1],rv1$data.mat[,3], pch = 16, col = 2)}
if (2%in%input$plotpos) {points(rv1$data.mat[,1],rv1$data.mat[,4], pch = 16, col = "green")}
if (3%in%input$plotpos) {points(rv1$data.mat[,1],rv1$data.mat[,5], pch = 16, col = "blue")}
legend("topleft", legend = leg, bg = NA, bty = "n", pch = pch,col = col)
})
} |
#' Example of Lab Time Data for Tacrolimus
#'
#' An example dataset used in \code{\link{processLastDose}} that contains lab time data. This dataset should
#' have one row per patient ID-date pair, and contain the time a lab was performed as a datetime variable.
#'
#' @format A data frame with 2 observations on the following variables.
#' \describe{
#' \item{pid}{A character vector, patient ID associated with the lab value}
#' \item{date}{A character vector, date associated with the lab value}
#' \item{labtime}{A POSIXct vector, datetime at which the lab was performed formatted as YYYY-MM-DD HH:MM:SS}
#' }
#'
#' @usage data(tac_lab, package = 'EHR')
#'
#' @keywords datasets
#'
#' @examples
#' data(tac_lab)
"tac_lab"
| /EHR/R/tacLab.R | no_license | choileena/EHR | R | false | false | 731 | r | #' Example of Lab Time Data for Tacrolimus
#'
#' An example dataset used in \code{\link{processLastDose}} that contains lab time data. This dataset should
#' have one row per patient ID-date pair, and contain the time a lab was performed as a datetime variable.
#'
#' @format A data frame with 2 observations on the following variables.
#' \describe{
#' \item{pid}{A character vector, patient ID associated with the lab value}
#' \item{date}{A character vector, date associated with the lab value}
#' \item{labtime}{A POSIXct vector, datetime at which the lab was performed formatted as YYYY-MM-DD HH:MM:SS}
#' }
#'
#' @usage data(tac_lab, package = 'EHR')
#'
#' @keywords datasets
#'
#' @examples
#' data(tac_lab)
"tac_lab"
|
#' Produce a ProPublica- or GovTrack-style House roll call vote cartogram
#'
#' @md
#' @param vote_tally either a `pprc` object (the result of a call to [roll_call()]) or
#' a `data.frame` of vote tallies for the house It expects 3 columns. `state_abbrev` : the
#' 2-letter U.S. state abbreviation; `district` : either `1` or `2` to distinguish between
#' each representative; `party` : `R`, `D` or `ID`; `position` : `yes`, `no`, `present`, `none` for
#' how the representative voted.
#' @param style either ProPublica-ish (`pp` or `propublica`) or GovTrack-ish (`gt` or `govtrack`)
#' @return a `ggplot2` object that you can further customize with scales, labels, etc.
#' @note No "themeing" is applied to the returned ggplot2 object. You can use [theme_voteogram()]
#' if you need a base theme. Also, GovTrack-style cartograms will have `coord_equal()`
#' applied by default.
#' @export
house_carto <- function(vote_tally, style = c("pp", "gt", "propublica", "govtrack")) {
if (inherits(vote_tally, "pprc")) vote_tally <- vote_tally$votes
if (!inherits(vote_tally, "data.frame")) stop("Needs a data.frame", call.=FALSE)
style <- match.arg(tolower(style), c("pp", "gt", "propublica", "govtrack"))
cdiff <- setdiff(c("state_abbrev", "party", "district", "position"), colnames(vote_tally))
if (length(cdiff) > 0) stop(sprintf("Missing: %s", paste0(cdiff, collapse=", ")), call.=FALSE)
if (style %in% c("pp", "propublica")) {
vote_tally <- dplyr::mutate(vote_tally, id=sprintf("%s_%s", toupper(state_abbrev), district))
vote_tally <- dplyr::mutate(vote_tally, fill=sprintf("%s-%s", toupper(party), tolower(position)))
vote_tally <- dplyr::mutate(vote_tally, fill=ifelse(grepl("acant", fill), "Vacant", fill))
plot_df <- left_join(house_df, vote_tally, by="id")
ggplot(plot_df) +
geom_rect(aes(xmin=x, ymin=y, xmax=xmax, ymax=ymax, fill=fill), color="white", size=0.25) +
scale_y_reverse() +
scale_fill_manual(name=NULL, values=vote_carto_fill)
} else {
zeroes <- c("ak", "as", "dc", "de", "gu", "mp", "mt", "nd", "pr", "sd", "vi", "vt", "wy")
vote_tally <- dplyr::mutate(vote_tally, district=ifelse(tolower(state_abbrev) %in% zeroes, 0, district))
vote_tally <- dplyr::mutate(vote_tally, id=sprintf("%s%02d", tolower(state_abbrev), district))
vote_tally <- dplyr::mutate(vote_tally, fill=sprintf("%s-%s", toupper(party), tolower(position)))
vote_tally <- dplyr::mutate(vote_tally, fill=ifelse(grepl("acant", fill), "Vacant", fill))
plot_df <- dplyr::left_join(gt_house_polys, vote_tally, by="id")
plot_df <- dplyr::filter(plot_df, !is.na(fill))
ggplot() +
geom_polygon(data=plot_df, aes(x, y, group=id, fill=fill), size=0) +
geom_line(data=gt_house_lines, aes(x, y, group=id),
size=gt_house_lines$size, color=gt_house_lines$color, lineend="round", linejoin="round") +
geom_text(data=gt_house_labs, aes(x, y, label=lab), size=2.25, hjust=0, vjust=0) +
scale_y_reverse() +
scale_fill_manual(name=NULL, values=vote_carto_fill, na.value="white") +
coord_equal()
}
}
| /R/gghouse.r | no_license | cderv/voteogram | R | false | false | 3,150 | r | #' Produce a ProPublica- or GovTrack-style House roll call vote cartogram
#'
#' @md
#' @param vote_tally either a `pprc` object (the result of a call to [roll_call()]) or
#' a `data.frame` of vote tallies for the house It expects 3 columns. `state_abbrev` : the
#' 2-letter U.S. state abbreviation; `district` : either `1` or `2` to distinguish between
#' each representative; `party` : `R`, `D` or `ID`; `position` : `yes`, `no`, `present`, `none` for
#' how the representative voted.
#' @param style either ProPublica-ish (`pp` or `propublica`) or GovTrack-ish (`gt` or `govtrack`)
#' @return a `ggplot2` object that you can further customize with scales, labels, etc.
#' @note No "themeing" is applied to the returned ggplot2 object. You can use [theme_voteogram()]
#' if you need a base theme. Also, GovTrack-style cartograms will have `coord_equal()`
#' applied by default.
#' @export
house_carto <- function(vote_tally, style = c("pp", "gt", "propublica", "govtrack")) {
if (inherits(vote_tally, "pprc")) vote_tally <- vote_tally$votes
if (!inherits(vote_tally, "data.frame")) stop("Needs a data.frame", call.=FALSE)
style <- match.arg(tolower(style), c("pp", "gt", "propublica", "govtrack"))
cdiff <- setdiff(c("state_abbrev", "party", "district", "position"), colnames(vote_tally))
if (length(cdiff) > 0) stop(sprintf("Missing: %s", paste0(cdiff, collapse=", ")), call.=FALSE)
if (style %in% c("pp", "propublica")) {
vote_tally <- dplyr::mutate(vote_tally, id=sprintf("%s_%s", toupper(state_abbrev), district))
vote_tally <- dplyr::mutate(vote_tally, fill=sprintf("%s-%s", toupper(party), tolower(position)))
vote_tally <- dplyr::mutate(vote_tally, fill=ifelse(grepl("acant", fill), "Vacant", fill))
plot_df <- left_join(house_df, vote_tally, by="id")
ggplot(plot_df) +
geom_rect(aes(xmin=x, ymin=y, xmax=xmax, ymax=ymax, fill=fill), color="white", size=0.25) +
scale_y_reverse() +
scale_fill_manual(name=NULL, values=vote_carto_fill)
} else {
zeroes <- c("ak", "as", "dc", "de", "gu", "mp", "mt", "nd", "pr", "sd", "vi", "vt", "wy")
vote_tally <- dplyr::mutate(vote_tally, district=ifelse(tolower(state_abbrev) %in% zeroes, 0, district))
vote_tally <- dplyr::mutate(vote_tally, id=sprintf("%s%02d", tolower(state_abbrev), district))
vote_tally <- dplyr::mutate(vote_tally, fill=sprintf("%s-%s", toupper(party), tolower(position)))
vote_tally <- dplyr::mutate(vote_tally, fill=ifelse(grepl("acant", fill), "Vacant", fill))
plot_df <- dplyr::left_join(gt_house_polys, vote_tally, by="id")
plot_df <- dplyr::filter(plot_df, !is.na(fill))
ggplot() +
geom_polygon(data=plot_df, aes(x, y, group=id, fill=fill), size=0) +
geom_line(data=gt_house_lines, aes(x, y, group=id),
size=gt_house_lines$size, color=gt_house_lines$color, lineend="round", linejoin="round") +
geom_text(data=gt_house_labs, aes(x, y, label=lab), size=2.25, hjust=0, vjust=0) +
scale_y_reverse() +
scale_fill_manual(name=NULL, values=vote_carto_fill, na.value="white") +
coord_equal()
}
}
|
# Week 1
# Create a vector and fill the variable with
#a <- c(1, 2, 3, 4, 5)
# Create vector from:to
#b <- c(1:10)
# Display vector from:to
#barplot(b[1:5])
# Display a barplot with the vector as data
#barplot(a)
#x <- 20
#y <- 10
#z <- "Hello, world!"
# Get datatype from variable
#class(x)
# Week 2
# Read CSV file
#ozone <- read.csv(file = "air.csv", head = TRUE, sep = ",")
# Week 3
#Question 1:
#n <- 25
#p <- 0.25
#1 - pbinom(0, n, p)
# Question 2:
#n <- 20
#p <- 1 / 3
#dbinom(12, n, p)
#Question 3:
#n <- 50
#p <- 1 - (1 / 100)
#dbinom(48, n, p)
#Question 4:
#n <- 3
#p <- 1/3
#barplot(dbinom(0:3, n, p))
#x <- 12
#n <- 17
#p <- 0.8
#dbinom(x, n, p)
# X (number of successes) is a integer value with the number of successes
# N (size) is the number of trials
# P (probability) is the probability success of one trial
# Compute the probability of exactly 5 successes out of 10 independent trials where the probability of success on 1 trial is .6.
#x <- 5
#n <- 10
#p <- 0.6
#dbinom(x, n , p)
# Compute the probability of exactly 12 successes out of 17 trials with probability of success = .8.
#x <- 12
#n <- 17
#p <- 0.8
#dbinom(x, n, p)
# Compute the probability of more than 5 successes out of 13 trials with probability of success = .2.
#x <- 6:13
#n <- 13
#p <- 0.2
#sum(dbinom(x, n, p))
# A test consists of 10 true/false questions. To pass the test a student must answer at least 6 questions correctly. If a student guesses on each question, what is the probability that the student will pass the test?
#x <- 6:10
#n <- 10
#p <- 1 / 2
#sum(dbinom(x, n, p))
#A machine has 9 identical components which function independently. The probability that a component will fail is 0.2 . The machine will stop working if more than three components fail. Find the probability that the machine will be working.
x <- 0:3
n <- 9
p <- 0.2
sum(dbinom(x, n, p)) | /Assignments/rproject1/Assignments/script.R | no_license | andybhadai/INFDEV2-7 | R | false | false | 1,881 | r | # Week 1
# Create a vector and fill the variable with
#a <- c(1, 2, 3, 4, 5)
# Create vector from:to
#b <- c(1:10)
# Display vector from:to
#barplot(b[1:5])
# Display a barplot with the vector as data
#barplot(a)
#x <- 20
#y <- 10
#z <- "Hello, world!"
# Get datatype from variable
#class(x)
# Week 2
# Read CSV file
#ozone <- read.csv(file = "air.csv", head = TRUE, sep = ",")
# Week 3
#Question 1:
#n <- 25
#p <- 0.25
#1 - pbinom(0, n, p)
# Question 2:
#n <- 20
#p <- 1 / 3
#dbinom(12, n, p)
#Question 3:
#n <- 50
#p <- 1 - (1 / 100)
#dbinom(48, n, p)
#Question 4:
#n <- 3
#p <- 1/3
#barplot(dbinom(0:3, n, p))
#x <- 12
#n <- 17
#p <- 0.8
#dbinom(x, n, p)
# X (number of successes) is a integer value with the number of successes
# N (size) is the number of trials
# P (probability) is the probability success of one trial
# Compute the probability of exactly 5 successes out of 10 independent trials where the probability of success on 1 trial is .6.
#x <- 5
#n <- 10
#p <- 0.6
#dbinom(x, n , p)
# Compute the probability of exactly 12 successes out of 17 trials with probability of success = .8.
#x <- 12
#n <- 17
#p <- 0.8
#dbinom(x, n, p)
# Compute the probability of more than 5 successes out of 13 trials with probability of success = .2.
#x <- 6:13
#n <- 13
#p <- 0.2
#sum(dbinom(x, n, p))
# A test consists of 10 true/false questions. To pass the test a student must answer at least 6 questions correctly. If a student guesses on each question, what is the probability that the student will pass the test?
#x <- 6:10
#n <- 10
#p <- 1 / 2
#sum(dbinom(x, n, p))
#A machine has 9 identical components which function independently. The probability that a component will fail is 0.2 . The machine will stop working if more than three components fail. Find the probability that the machine will be working.
x <- 0:3
n <- 9
p <- 0.2
sum(dbinom(x, n, p)) |
#-------------------------------
# CONSIGN
# v0.1 - 29 June 2021
# authors: Claudia Bartolini, Rosa Gini, Giorgio Limoncella, Olga Paoletti, Davide Messina
# based on ConcePTIONAlgorithmPregnancies https://github.com/ARS-toscana/ConcePTIONAlgorithmPregnancies
# -----------------------------
rm(list=ls(all.names=TRUE))
#set the directory where the file is saved as the working directory
if (!require("rstudioapi")) install.packages("rstudioapi")
thisdir<-setwd(dirname(rstudioapi::getSourceEditorContext()$path))
thisdir<-setwd(dirname(rstudioapi::getSourceEditorContext()$path))
#load parameters
source(paste0(thisdir,"/p_parameters/01_parameters_program.R"))
source(paste0(thisdir,"/p_parameters/02_parameters_CDM.R"))
source(paste0(thisdir,"/p_parameters/03_concept_sets.R"))
source(paste0(thisdir,"/p_parameters/04_prompts.R"))
source(paste0(thisdir,"/p_parameters/05_subpopulations_restricting_meanings.R"))
source(paste0(thisdir,"/p_parameters/06_algorithms.R"))
source(paste0(thisdir,"/p_parameters/07_itemsets.R"))
source(paste0(thisdir,"/p_parameters/08_check_coding_system.R"))
#run scripts
# 01 RETRIEVE RECORDS FRM CDM
system.time(source(paste0(thisdir,"/p_steps/step_01_1_T2.1_create_conceptset_datasets.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_2_T2.1_create_spells.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_3_T2.1_create_dates_in_PERSONS.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_4_T2.1_create_prompt_datasets.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_5_T2.1_create_itemsets_datasets.R"))) # -->fare prove con TEST!!
# 02 COUNT CODES
#system.time(source(paste0(thisdir,"/p_steps/step_02_T2.2_count_codes.R")))
# 03 CREATE PREGNANCIES
source(paste0(thisdir,"/p_steps/step_03_01_T2.2_create_pregnancies_from_prompts.R")) #--> D3_Stream_PROMPTS
source(paste0(thisdir,"/p_steps/step_03_02_T2.2_create_pregnancies_from_conceptsets.R")) #--> D3_Stream_CONCEPTSETS
source(paste0(thisdir,"/p_steps/step_03_03_T2.2_create_pregnancies_from_EUROCAT.R")) #--> D3_Stream_EUROCAT
source(paste0(thisdir,"/p_steps/step_03_04_T2.2_create_pregnancies_from_itemsets.R")) #--> D3_Stream_ITEMSETS
source(paste0(thisdir,"/p_steps/step_03_05a_T2.2_internal_consistency_for_prompts.R"))
source(paste0(thisdir,"/p_steps/step_03_05b_T2.2_internal_consistency_for_conceptsets.R"))
source(paste0(thisdir,"/p_steps/step_03_05c_T2.2_internal_consistency_for_EUROCAT.R"))
source(paste0(thisdir,"/p_steps/step_03_05d_T2.2_internal_consistency_for_itemsets.R"))
source(paste0(thisdir,"/p_steps/step_03_06_1_T2.2_process_pregnancies_excluded.R"))
source(paste0(thisdir,"/p_steps/step_03_06_2_T2.3_merge_stream_of_same_person.R"))
# # 04 CREATE PREGNANCIES outcomes
# source(paste0(thisdir,"/p_steps/step_04_01_T2_create_pregnancy_outcomes.R"))
# source(paste0(thisdir,"/p_steps/step_04_02_create_aggregated_outcomes.R"))
# source(paste0(thisdir,"/p_steps/step_04_03_distance_description.R"))
# 05 MEDICATION in pregnancies
source(paste0(thisdir,"/p_steps/step_05_01_create_risk_in_pregnancy.R"))
source(paste0(thisdir,"/p_steps/step_05_02_create_pregnancy_trimesters.R"))
source(paste0(thisdir,"/p_steps/step_05_03_create_medication_in_pregnancy.R"))
| /to_run.R | no_license | ARS-toscana/CONSIGN | R | false | false | 3,229 | r | #-------------------------------
# CONSIGN
# v0.1 - 29 June 2021
# authors: Claudia Bartolini, Rosa Gini, Giorgio Limoncella, Olga Paoletti, Davide Messina
# based on ConcePTIONAlgorithmPregnancies https://github.com/ARS-toscana/ConcePTIONAlgorithmPregnancies
# -----------------------------
rm(list=ls(all.names=TRUE))
#set the directory where the file is saved as the working directory
if (!require("rstudioapi")) install.packages("rstudioapi")
thisdir<-setwd(dirname(rstudioapi::getSourceEditorContext()$path))
thisdir<-setwd(dirname(rstudioapi::getSourceEditorContext()$path))
#load parameters
source(paste0(thisdir,"/p_parameters/01_parameters_program.R"))
source(paste0(thisdir,"/p_parameters/02_parameters_CDM.R"))
source(paste0(thisdir,"/p_parameters/03_concept_sets.R"))
source(paste0(thisdir,"/p_parameters/04_prompts.R"))
source(paste0(thisdir,"/p_parameters/05_subpopulations_restricting_meanings.R"))
source(paste0(thisdir,"/p_parameters/06_algorithms.R"))
source(paste0(thisdir,"/p_parameters/07_itemsets.R"))
source(paste0(thisdir,"/p_parameters/08_check_coding_system.R"))
#run scripts
# 01 RETRIEVE RECORDS FRM CDM
system.time(source(paste0(thisdir,"/p_steps/step_01_1_T2.1_create_conceptset_datasets.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_2_T2.1_create_spells.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_3_T2.1_create_dates_in_PERSONS.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_4_T2.1_create_prompt_datasets.R")))
system.time(source(paste0(thisdir,"/p_steps/step_01_5_T2.1_create_itemsets_datasets.R"))) # -->fare prove con TEST!!
# 02 COUNT CODES
#system.time(source(paste0(thisdir,"/p_steps/step_02_T2.2_count_codes.R")))
# 03 CREATE PREGNANCIES
source(paste0(thisdir,"/p_steps/step_03_01_T2.2_create_pregnancies_from_prompts.R")) #--> D3_Stream_PROMPTS
source(paste0(thisdir,"/p_steps/step_03_02_T2.2_create_pregnancies_from_conceptsets.R")) #--> D3_Stream_CONCEPTSETS
source(paste0(thisdir,"/p_steps/step_03_03_T2.2_create_pregnancies_from_EUROCAT.R")) #--> D3_Stream_EUROCAT
source(paste0(thisdir,"/p_steps/step_03_04_T2.2_create_pregnancies_from_itemsets.R")) #--> D3_Stream_ITEMSETS
source(paste0(thisdir,"/p_steps/step_03_05a_T2.2_internal_consistency_for_prompts.R"))
source(paste0(thisdir,"/p_steps/step_03_05b_T2.2_internal_consistency_for_conceptsets.R"))
source(paste0(thisdir,"/p_steps/step_03_05c_T2.2_internal_consistency_for_EUROCAT.R"))
source(paste0(thisdir,"/p_steps/step_03_05d_T2.2_internal_consistency_for_itemsets.R"))
source(paste0(thisdir,"/p_steps/step_03_06_1_T2.2_process_pregnancies_excluded.R"))
source(paste0(thisdir,"/p_steps/step_03_06_2_T2.3_merge_stream_of_same_person.R"))
# # 04 CREATE PREGNANCIES outcomes
# source(paste0(thisdir,"/p_steps/step_04_01_T2_create_pregnancy_outcomes.R"))
# source(paste0(thisdir,"/p_steps/step_04_02_create_aggregated_outcomes.R"))
# source(paste0(thisdir,"/p_steps/step_04_03_distance_description.R"))
# 05 MEDICATION in pregnancies
source(paste0(thisdir,"/p_steps/step_05_01_create_risk_in_pregnancy.R"))
source(paste0(thisdir,"/p_steps/step_05_02_create_pregnancy_trimesters.R"))
source(paste0(thisdir,"/p_steps/step_05_03_create_medication_in_pregnancy.R"))
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/my_lm.R
\name{my_lm}
\alias{my_lm}
\title{Fitting Linear Model function}
\usage{
my_lm(fnc, data)
}
\arguments{
\item{fnc}{An object of class "formula": a symbolic description
of the model to be fitted.}
\item{data}{An optional data frame, list or environment
(or object coercible by as.data.frame to a data frame) containing
the variables in the model.}
}
\value{
Numeric represrnting the coefficients and statistics of the fitting
}
\description{
This function is used to fit linear models. It can be
used to carry out regression, single stratum analysis
of variance and analysis of covariance.
}
\examples{
my_model <- my_lm(Sepal.Length~Sepal.Width, data = my_iris)
}
\keyword{inference}
| /man/my_lm.Rd | no_license | Xiaoying-Z/Stat302Project03 | R | false | true | 772 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/my_lm.R
\name{my_lm}
\alias{my_lm}
\title{Fitting Linear Model function}
\usage{
my_lm(fnc, data)
}
\arguments{
\item{fnc}{An object of class "formula": a symbolic description
of the model to be fitted.}
\item{data}{An optional data frame, list or environment
(or object coercible by as.data.frame to a data frame) containing
the variables in the model.}
}
\value{
Numeric represrnting the coefficients and statistics of the fitting
}
\description{
This function is used to fit linear models. It can be
used to carry out regression, single stratum analysis
of variance and analysis of covariance.
}
\examples{
my_model <- my_lm(Sepal.Length~Sepal.Width, data = my_iris)
}
\keyword{inference}
|
#!/usr/bin/R
library(edgeR)
library(limma)
library(gplots)
rep.file = 'overlap_rna_rep_PYR.txt'
out.tab = 'repeat_expdiff_results_PYR.xls'
expclfile = 'exp_clustering_PYR.pdf'
HCtitle = 'Hierarchical clustering dendrogram for raw counts in PYRAMIDAL'
MDStitle = 'MDS clustering of PYRAMIDAL samples'
cluster.file = 'CLUSTERING_PYR.pdf'
clname = 'PYRAMIDAL DE RE in'
TSA = c(4,5,6,10,11,12,1,2,3,7,8,9)
VPA = c(22,23,24,16,17,18,19,20,21,13,14,15)
ALL = c(TSA,VPA)
rep = read.delim(file=rep.file)
norm = read.delim(file='norm.txt')
raw = read.delim(file='raw.txt')
coord = read.delim(file='coord.txt')
exp.rep = raw
eset = exp.rep[,-1]
rownames(eset) = exp.rep$id
# TSA_2d TSA_2h VEHtsa_2d VEHtsa_2h VEHvpa_2d VEHvpa_2h VPA_2d VPA_2h
target = read.delim(file='target.txt')
target$TSA_2h = c(2,2,2,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0)
target$TSA_2d = c(1,1,1,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0)
target$TSA_2hd = c(1,1,1,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0)
target$VPA_2h = c(0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,1,1,1)
target$VPA_2d = c(0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,1,1,1,2,2,2)
target$VPA_2hd = c(0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,1,1,1,1,1,1)
target$T.V_2h = c(2,2,2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1)
target$T.V_2d = c(1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,2,2,2)
target$T.V_2hd = c(1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1)
target$chem_time = paste(target$chem,target$time,sep='_')
# Exp clustering
pdf(file=expclfile,paper='a4r',width=8.3,height=11.7,pointsize=8,title=MDStitle)
ecTr = dist(t(eset), method = "euclidean")
hecTr = hclust(ecTr, method = "average")
plot(hecTr, main = HCtitle, xlab = "")
# MDS generation
dd = DGEList(eset,group=target$chem_time)
col = c(2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9)
plotMDS.dge(dd,col=col,main=MDStitle)
dev.off()
pdf(file=cluster.file,paper='a4r',width=8.3,height=11.7,pointsize=8)
make.comparison = function(eset,group,rep,name,chem) {
d = DGEList(eset,group=as.character(group))
d = d[rowSums(1e+06 * d$counts/expandAsMatrix(d$samples$lib.size, dim(d)) > 10) >= 3, ]
d = calcNormFactors(d)
d = estimateCommonDisp(d)
# It seems the calculation is done so the FC = 1-2
# Code checked it does the second minus the first
et = exactTest(d,pair=as.character(c('2','1')))
stat = topTags(et,n=Inf)
tab = stat$table
sig.tab = tab[tab$adj.P.Val<=0.05,]
res = sig.tab[rownames(sig.tab) %in% rep$id,]
res$comparison = name
res.ordered = res[order(res$logFC,decreasing=T),]
fitted = d$pseudo.alt
mat = as.matrix(fitted[rownames(res.ordered),])
heatmap.2(mat[,chem],col=redgreen(75),trace="none",dendrogram='none',
Colv=F,Rowv=F,density.info='none',labRow=NA,margins=c(10,1),
scale='row',colsep=seq(3,ncol(mat)-3,3),keysize=1,
main=paste(clname,name,sep=' '))
res$id = rownames(res)
res[order(res$adj.P.Val),]
}
name = 'TSA_2h'
group = target$TSA_2h
RES = make.comparison(eset,group,rep,name,TSA)
name = 'TSA_2d'
group = target$TSA_2d
res = make.comparison(eset,group,rep,name,TSA)
RES = rbind(RES,res)
name = 'TSA_2hd'
group = target$TSA_2hd
res = make.comparison(eset,group,rep,name,TSA)
RES = rbind(RES,res)
name = 'VPA_2h'
group = target$VPA_2h
res = make.comparison(eset,group,rep,name,VPA)
RES = rbind(RES,res)
name = 'VPA_2d'
group = target$VPA_2d
res = make.comparison(eset,group,rep,name,VPA)
RES = rbind(RES,res)
name = 'VPA_2hd'
group = target$VPA_2hd
res = make.comparison(eset,group,rep,name,VPA)
RES = rbind(RES,res)
name = 'T.V_2h'
group = target$T.V_2h
res = make.comparison(eset,group,rep,name,ALL)
RES = rbind(RES,res)
name = 'T.V_2d'
group = target$T.V_2d
res = make.comparison(eset,group,rep,name,ALL)
RES = rbind(RES,res)
name = 'T.V_2hd'
group = target$T.V_2hd
res = make.comparison(eset,group,rep,name,ALL)
RES = rbind(RES,res)
dev.off()
# SIGNIFICANT
SIG = RES[RES$adj.P.Val<=0.05,]
TAB = merge(SIG[,c(6,2,4,5)],rep[,c(1,2,3,4,5,8,14,15,16,17)],by.x='id', by.y='id', all.x=T)
write.table(TAB,file=out.tab,sep="\t",row.names=F,quote=F)
| /RIKEN_STUFF/diffexp_edgeR_pseudocomplex_simple.R | no_license | silverkey/RANDOM | R | false | false | 4,067 | r | #!/usr/bin/R
library(edgeR)
library(limma)
library(gplots)
rep.file = 'overlap_rna_rep_PYR.txt'
out.tab = 'repeat_expdiff_results_PYR.xls'
expclfile = 'exp_clustering_PYR.pdf'
HCtitle = 'Hierarchical clustering dendrogram for raw counts in PYRAMIDAL'
MDStitle = 'MDS clustering of PYRAMIDAL samples'
cluster.file = 'CLUSTERING_PYR.pdf'
clname = 'PYRAMIDAL DE RE in'
TSA = c(4,5,6,10,11,12,1,2,3,7,8,9)
VPA = c(22,23,24,16,17,18,19,20,21,13,14,15)
ALL = c(TSA,VPA)
rep = read.delim(file=rep.file)
norm = read.delim(file='norm.txt')
raw = read.delim(file='raw.txt')
coord = read.delim(file='coord.txt')
exp.rep = raw
eset = exp.rep[,-1]
rownames(eset) = exp.rep$id
# TSA_2d TSA_2h VEHtsa_2d VEHtsa_2h VEHvpa_2d VEHvpa_2h VPA_2d VPA_2h
target = read.delim(file='target.txt')
target$TSA_2h = c(2,2,2,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0)
target$TSA_2d = c(1,1,1,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0)
target$TSA_2hd = c(1,1,1,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0)
target$VPA_2h = c(0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,1,1,1)
target$VPA_2d = c(0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,1,1,1,2,2,2)
target$VPA_2hd = c(0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,1,1,1,1,1,1)
target$T.V_2h = c(2,2,2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1)
target$T.V_2d = c(1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,2,2,2)
target$T.V_2hd = c(1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1)
target$chem_time = paste(target$chem,target$time,sep='_')
# Exp clustering
pdf(file=expclfile,paper='a4r',width=8.3,height=11.7,pointsize=8,title=MDStitle)
ecTr = dist(t(eset), method = "euclidean")
hecTr = hclust(ecTr, method = "average")
plot(hecTr, main = HCtitle, xlab = "")
# MDS generation
dd = DGEList(eset,group=target$chem_time)
col = c(2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9)
plotMDS.dge(dd,col=col,main=MDStitle)
dev.off()
pdf(file=cluster.file,paper='a4r',width=8.3,height=11.7,pointsize=8)
make.comparison = function(eset,group,rep,name,chem) {
d = DGEList(eset,group=as.character(group))
d = d[rowSums(1e+06 * d$counts/expandAsMatrix(d$samples$lib.size, dim(d)) > 10) >= 3, ]
d = calcNormFactors(d)
d = estimateCommonDisp(d)
# It seems the calculation is done so the FC = 1-2
# Code checked it does the second minus the first
et = exactTest(d,pair=as.character(c('2','1')))
stat = topTags(et,n=Inf)
tab = stat$table
sig.tab = tab[tab$adj.P.Val<=0.05,]
res = sig.tab[rownames(sig.tab) %in% rep$id,]
res$comparison = name
res.ordered = res[order(res$logFC,decreasing=T),]
fitted = d$pseudo.alt
mat = as.matrix(fitted[rownames(res.ordered),])
heatmap.2(mat[,chem],col=redgreen(75),trace="none",dendrogram='none',
Colv=F,Rowv=F,density.info='none',labRow=NA,margins=c(10,1),
scale='row',colsep=seq(3,ncol(mat)-3,3),keysize=1,
main=paste(clname,name,sep=' '))
res$id = rownames(res)
res[order(res$adj.P.Val),]
}
name = 'TSA_2h'
group = target$TSA_2h
RES = make.comparison(eset,group,rep,name,TSA)
name = 'TSA_2d'
group = target$TSA_2d
res = make.comparison(eset,group,rep,name,TSA)
RES = rbind(RES,res)
name = 'TSA_2hd'
group = target$TSA_2hd
res = make.comparison(eset,group,rep,name,TSA)
RES = rbind(RES,res)
name = 'VPA_2h'
group = target$VPA_2h
res = make.comparison(eset,group,rep,name,VPA)
RES = rbind(RES,res)
name = 'VPA_2d'
group = target$VPA_2d
res = make.comparison(eset,group,rep,name,VPA)
RES = rbind(RES,res)
name = 'VPA_2hd'
group = target$VPA_2hd
res = make.comparison(eset,group,rep,name,VPA)
RES = rbind(RES,res)
name = 'T.V_2h'
group = target$T.V_2h
res = make.comparison(eset,group,rep,name,ALL)
RES = rbind(RES,res)
name = 'T.V_2d'
group = target$T.V_2d
res = make.comparison(eset,group,rep,name,ALL)
RES = rbind(RES,res)
name = 'T.V_2hd'
group = target$T.V_2hd
res = make.comparison(eset,group,rep,name,ALL)
RES = rbind(RES,res)
dev.off()
# SIGNIFICANT
SIG = RES[RES$adj.P.Val<=0.05,]
TAB = merge(SIG[,c(6,2,4,5)],rep[,c(1,2,3,4,5,8,14,15,16,17)],by.x='id', by.y='id', all.x=T)
write.table(TAB,file=out.tab,sep="\t",row.names=F,quote=F)
|
#---How To USE---#
# main functions for the majority of the E. coli analysis
# Aidan Foo 2021 - Liverpool School of Tropical Medicine -
# Functions
library(tidyverse)
library(Biostrings)
# Manipulate HMMER outputs ####
# Function to clean HMMER outputs.Produces a tibble with an id column to represent the lineage
# and a target column to represent the gene hit with lineage variation information retained
clean_the_tablev2 <- function(HMMERhits_table){
HMMERhits_table_filter <- HMMERhits_table %>%
filter(target != "#") %>%
filter(target != "#-------------------")
HMMERhits_table_filter %>%
select(target, accession, E_value)
HMMERhits_table_filter$target2 <- HMMERhits_table_filter$target
HMMERhits_table_filter$target <- substr(HMMERhits_table_filter$target, 1, nchar(HMMERhits_table_filter$target)-2)
HMMERhits_table_filter$target <- str_sub(HMMERhits_table_filter$target, 3)
HMMERhits_table_filter <- mutate(HMMERhits_table_filter, target = as.character(gsub("^_", "", target)))
HMMER_table_final <- HMMERhits_table_filter %>%
separate(target2, into = c("id", "gene")) %>%
mutate(id = as.numeric(id)) %>%
select(id, target)
}
# Add superfamily information
add_superfamily <- function(joined_table, superfamily){
anot <- joined_table %>%
mutate(superfamily = superfamily)
}
# Apply MetaData to HMMER Outputs ####
# Metadata from Gal Horesh E. coli genome repository
join_protein_hits_with_lineage <- function(tidy_protein_table){
lineage_summary <- read_csv("metadata/F2_lineage_summary.csv")
protein_lineage_table <- lineage_summary %>%
inner_join(tidy_protein_table, by = "id")
return(protein_lineage_table)
}
join_with_gene_classification_data <- function(protein_table){
protein_table2 <- protein_table %>%
left_join(gene_classification, by = c("target" = "gene")) %>%
na.exclude()
}
add_superfamily <- function(joined_table, superfamily){
anot <- joined_table %>%
mutate(superfamily = superfamily)
}
# Convert HMMER hits to Sequence information ####
#These functions add sequences to gene names
# remove redundant characters from HMMER hits
fix_target_name <- function(table){
as_tibble(substr(table$target, 1, nchar(table$target)-2)) # remove last two characters
}
# join genes with E. coli sequences
join_with_sequences <- function(reference_table, protein_table){
protein_table %>%
left_join(reference_table, by = c('target' = 'seq_names'))
}
# do all in one go
extract_sequences <- function(HMMER_hits){
e_coli_sequences <- readAAStringSet("e_coli_peptide.fa") # load from current working directory
seq_names <- names(e_coli_sequences)
sequences <- paste(e_coli_sequences)
e_coli_sequences_df <- as_tibble(data.frame(seq_names, sequences))
HMMER_sequence_hit <- join_with_sequences(e_coli_sequences_df, HMMER_hits)
}
# Convert the dataframe to a fasta file
writeFASTA <- function(data, filename) {
fastalines = c()
for(rowNum in 1:nrow(data)){
fastalines = c(fastalines, as.character(paste(">", data[rowNum, "target"], sep = "")))
fastalines = c(fastalines, as.character(data[rowNum, "sequences"]))
}
fileConn <- file(filename)
writeLines(fastalines, fileConn)
close(fileConn)
}
# Convert BLAST outputs to files ready for cytoscape ####
filter_eval <- function(BLAST_table){
BLAST_table %>%
filter(evalue < 0.01)
}
convert_for_cytoscape <- function(file, eval_threshold){
column_names <- c("qseqid", "sseqid", "pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore")
sequence_table <- read_tsv(file, col_names = column_names)
sequence_table_filtd <- filter_eval(sequence_table)
sequence_table_filtd$qseqid <- substr(sequence_table_filtd$qseqid, 1, nchar(sequence_table_filtd$qseqid)-2)
sequence_table_filtd$sseqid <- substr(sequence_table_filtd$sseqid, 1, nchar(sequence_table_filtd$sseqid)-2)
sequence_table_tidy <- sequence_table_filtd %>%
select(qseqid, sseqid, evalue, bitscore, pident) %>%
filter(evalue != 0) %>%
filter(!grepl("group", qseqid)) %>%
filter(!grepl("group", sseqid)) %>%
filter(evalue < eval_threshold)
node_list <- sequence_table_tidy %>%
select(qseqid, sseqid, evalue)
return(node_list)
}
convert_for_cytoscape_with_annotv2 <- function(file, annot_file, eval){
column_names <- c("qseqid", "sseqid", "pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore")
sequence_table <- read_tsv(file, col_names = column_names)
column_names_interpro <- c("qseqid", "misc", "site", "website", "id", "domain", "two", "three", "evalue", "date", "interproID", "interprodomain", "site2")
interpro_annotation <- read_tsv(annot_file, col_names = column_names_interpro)
sequence_table2 <- sequence_table %>%
distinct(qseqid, sseqid, .keep_all = TRUE) %>%
mutate(gene = qseqid) %>%
mutate(gene2 = sseqid) %>%
separate(gene, into = c("id", "gene")) %>%
separate(gene2, into = c("id2", "gene2")) %>%
filter(evalue < eval)
select(qseqid, sseqid, id, id2, evalue)
sequence_table2[,3] <- apply(sequence_table2[, 3], 2, function(x) as.numeric(as.character(x)))
sequence_table2[,4] <- apply(sequence_table2[, 4], 2, function(x) as.numeric(as.character(x)))
interpro_annotation[,9] <- apply(interpro_annotation[,9], 2, function(x) as.numeric(as.character(x)))
interpro_annotation$qseqid <- substr(interpro_annotation$qseqid, 1, nchar(interpro_annotation$qseqid)-2)
interpro_annotation$sseqid <- substr(interpro_annotation$sseqid, 1, nchar(interpro_annotation$sseqid)-2)
sequence_table2$qseqid <- substr(sequence_table2$qseqid, 1, nchar(sequence_table2$qseqid)-2)
sequence_table2$sseqid <- substr(sequence_table2$sseqid, 1, nchar(sequence_table2$sseqid)-2)
interpro_annotation2 <- interpro_annotation %>%
filter(website == "Pfam") %>%
filter(domain != "-") %>%
mutate(sseqid = qseqid) %>%
select(qseqid, domain)
interpro_annotation3 <- interpro_annotation %>%
filter(website == "Pfam") %>%
filter(domain != "-") %>%
mutate(sseqid = qseqid) %>%
select(sseqid, domain)
proteins_joined <- sequence_table2 %>%
left_join(interpro_annotation2, by = c("qseqid" = "qseqid"))
proteins_joined2 <- interpro_annotation3 %>%
left_join(proteins_joined, by = c("sseqid" = "sseqid"))
proteins_joined3 <- subset(proteins_joined2, !duplicated(subset(proteins_joined2, select=c(qseqid, sseqid, domain.y))))
# Convert Cytoscape Session Clusters into FASTA Files ####
# Set of functions to conver the cytoscape CSV export into fasta files
fix_target_name <- function(table){
as_tibble(substr(table$target, 1, nchar(table$target)-2)) # remove last two characters
}
tidy_import <- function(cluster_file){
cluster_file_tidy <- cluster_file %>%
select(name)
cluster_file_tidy$name <- substring(cluster_file_tidy$name, 2)
cluster_file_tidy$name <- substr(cluster_file_tidy$name, 1, nchar(cluster_file_tidy$name)-1)
return(as_tibble(cluster_file_tidy))
}
join_with_sequences <- function(reference_table, protein_table){
protein_table %>%
left_join(reference_table, by = c('name' = 'seq_names'))
}
extract_sequences <- function(clustered_names){
e_coli_sequences <- readAAStringSet("e_coli_peptide.fa") # load from current working directory
seq_names <- names(e_coli_sequences)
sequences <- paste(e_coli_sequences)
e_coli_sequences_df <- as_tibble(data.frame(seq_names, sequences))
e_coli_sequences_df[] <- lapply(e_coli_sequences_df, as.character)
e_coli_sequences_df$seq_names <- substr(e_coli_sequences_df$seq_names, 1, nchar(e_coli_sequences_df$seq_names)-2)
HMMER_sequence_hit <- join_with_sequences(e_coli_sequences_df, clustered_names)
}
writeFASTAclust <- function(data, filename) {
fastalines = c()
for(rowNum in 1:nrow(data)){
fastalines = c(fastalines, as.character(paste(">", data[rowNum, "name"], sep = "")))
fastalines = c(fastalines, as.character(data[rowNum, "sequences"]))
}
fileConn <- file(filename)
writeLines(fastalines, fileConn)
close(fileConn)
}
# Plot Phylogroup - Gene Distribution Heatmaps ####
plot_heatmap_transporter_proportions <- function(joined_proteins){
total_num_genes <- joined_proteins %>%
dplyr::group_by(gene) %>%
dplyr::summarise(total_gene_num = length(gene))
discrete_num_genes <- joined_proteins %>%
dplyr::group_by(gene, Phylogroup) %>%
dplyr::summarise(dist_gene_num = n_distinct(gene))
joined_table <- discrete_num_genes %>%
left_join(total_num_genes, by = "gene") %>%
mutate(prop_gene_num = dist_gene_num / total_gene_num)
ggplot(joined_table, aes(x = Phylogroup, y = gene)) +
geom_tile(aes(fill = prop_gene_num), colour = "white") +
scale_fill_gradient(low = "blue", high = "green") +
theme_classic()
}
# Make clustered heatmaps for gene 'rarity' metadata ####
# insert a gene transporter list in tibble format
make_clustered_heatmap <- function(transporter_gene_list){
transporter_gene_list_matrix <- as.matrix(transporter_gene_list[, -1])
rownames(transporter_gene_list_matrix) <- transporter_gene_list$target
dendro <- as.dendrogram(hclust(d = dist(x = transporter_gene_list_matrix)))
dendro.plot <- ggdendrogram(data = dendro, rotate = TRUE)
dendro.plot <- dendro.plot + theme(axis.text.y = element_text(size = 4))
order <- order.dendrogram(dendro)
transporter_gene_list$target <- factor(x = transporter_gene_list$target,
levels = transporter_gene_list$target[order],
ordered = TRUE)
heatmap <- ggplot(data = transporter_gene_list, aes(x = gene_class, y = target)) +
geom_tile(aes(fill = count)) +
scale_fill_gradient(low = "#FF7F50", high = "#66CD00") +
theme_tufte() +
theme(axis.text.y = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
legend.position = "top")
print(heatmap, vp = viewport(x = 0.4, y = 0.5, width = 0.8, height = 1.0))
print(dendro.plot, vp = viewport(x = 0.80, y = 0.465, width = 0.2, height = 1.04))
}
| /R_Scripts/Junk/Functions_Script.R | no_license | aidanfoo96/e.coli_efflux_transporter_diversity | R | false | false | 10,257 | r | #---How To USE---#
# main functions for the majority of the E. coli analysis
# Aidan Foo 2021 - Liverpool School of Tropical Medicine -
# Functions
library(tidyverse)
library(Biostrings)
# Manipulate HMMER outputs ####
# Function to clean HMMER outputs.Produces a tibble with an id column to represent the lineage
# and a target column to represent the gene hit with lineage variation information retained
clean_the_tablev2 <- function(HMMERhits_table){
HMMERhits_table_filter <- HMMERhits_table %>%
filter(target != "#") %>%
filter(target != "#-------------------")
HMMERhits_table_filter %>%
select(target, accession, E_value)
HMMERhits_table_filter$target2 <- HMMERhits_table_filter$target
HMMERhits_table_filter$target <- substr(HMMERhits_table_filter$target, 1, nchar(HMMERhits_table_filter$target)-2)
HMMERhits_table_filter$target <- str_sub(HMMERhits_table_filter$target, 3)
HMMERhits_table_filter <- mutate(HMMERhits_table_filter, target = as.character(gsub("^_", "", target)))
HMMER_table_final <- HMMERhits_table_filter %>%
separate(target2, into = c("id", "gene")) %>%
mutate(id = as.numeric(id)) %>%
select(id, target)
}
# Add superfamily information
add_superfamily <- function(joined_table, superfamily){
anot <- joined_table %>%
mutate(superfamily = superfamily)
}
# Apply MetaData to HMMER Outputs ####
# Metadata from Gal Horesh E. coli genome repository
join_protein_hits_with_lineage <- function(tidy_protein_table){
lineage_summary <- read_csv("metadata/F2_lineage_summary.csv")
protein_lineage_table <- lineage_summary %>%
inner_join(tidy_protein_table, by = "id")
return(protein_lineage_table)
}
join_with_gene_classification_data <- function(protein_table){
protein_table2 <- protein_table %>%
left_join(gene_classification, by = c("target" = "gene")) %>%
na.exclude()
}
add_superfamily <- function(joined_table, superfamily){
anot <- joined_table %>%
mutate(superfamily = superfamily)
}
# Convert HMMER hits to Sequence information ####
#These functions add sequences to gene names
# remove redundant characters from HMMER hits
fix_target_name <- function(table){
as_tibble(substr(table$target, 1, nchar(table$target)-2)) # remove last two characters
}
# join genes with E. coli sequences
join_with_sequences <- function(reference_table, protein_table){
protein_table %>%
left_join(reference_table, by = c('target' = 'seq_names'))
}
# do all in one go
extract_sequences <- function(HMMER_hits){
e_coli_sequences <- readAAStringSet("e_coli_peptide.fa") # load from current working directory
seq_names <- names(e_coli_sequences)
sequences <- paste(e_coli_sequences)
e_coli_sequences_df <- as_tibble(data.frame(seq_names, sequences))
HMMER_sequence_hit <- join_with_sequences(e_coli_sequences_df, HMMER_hits)
}
# Convert the dataframe to a fasta file
writeFASTA <- function(data, filename) {
fastalines = c()
for(rowNum in 1:nrow(data)){
fastalines = c(fastalines, as.character(paste(">", data[rowNum, "target"], sep = "")))
fastalines = c(fastalines, as.character(data[rowNum, "sequences"]))
}
fileConn <- file(filename)
writeLines(fastalines, fileConn)
close(fileConn)
}
# Convert BLAST outputs to files ready for cytoscape ####
filter_eval <- function(BLAST_table){
BLAST_table %>%
filter(evalue < 0.01)
}
convert_for_cytoscape <- function(file, eval_threshold){
column_names <- c("qseqid", "sseqid", "pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore")
sequence_table <- read_tsv(file, col_names = column_names)
sequence_table_filtd <- filter_eval(sequence_table)
sequence_table_filtd$qseqid <- substr(sequence_table_filtd$qseqid, 1, nchar(sequence_table_filtd$qseqid)-2)
sequence_table_filtd$sseqid <- substr(sequence_table_filtd$sseqid, 1, nchar(sequence_table_filtd$sseqid)-2)
sequence_table_tidy <- sequence_table_filtd %>%
select(qseqid, sseqid, evalue, bitscore, pident) %>%
filter(evalue != 0) %>%
filter(!grepl("group", qseqid)) %>%
filter(!grepl("group", sseqid)) %>%
filter(evalue < eval_threshold)
node_list <- sequence_table_tidy %>%
select(qseqid, sseqid, evalue)
return(node_list)
}
convert_for_cytoscape_with_annotv2 <- function(file, annot_file, eval){
column_names <- c("qseqid", "sseqid", "pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore")
sequence_table <- read_tsv(file, col_names = column_names)
column_names_interpro <- c("qseqid", "misc", "site", "website", "id", "domain", "two", "three", "evalue", "date", "interproID", "interprodomain", "site2")
interpro_annotation <- read_tsv(annot_file, col_names = column_names_interpro)
sequence_table2 <- sequence_table %>%
distinct(qseqid, sseqid, .keep_all = TRUE) %>%
mutate(gene = qseqid) %>%
mutate(gene2 = sseqid) %>%
separate(gene, into = c("id", "gene")) %>%
separate(gene2, into = c("id2", "gene2")) %>%
filter(evalue < eval)
select(qseqid, sseqid, id, id2, evalue)
sequence_table2[,3] <- apply(sequence_table2[, 3], 2, function(x) as.numeric(as.character(x)))
sequence_table2[,4] <- apply(sequence_table2[, 4], 2, function(x) as.numeric(as.character(x)))
interpro_annotation[,9] <- apply(interpro_annotation[,9], 2, function(x) as.numeric(as.character(x)))
interpro_annotation$qseqid <- substr(interpro_annotation$qseqid, 1, nchar(interpro_annotation$qseqid)-2)
interpro_annotation$sseqid <- substr(interpro_annotation$sseqid, 1, nchar(interpro_annotation$sseqid)-2)
sequence_table2$qseqid <- substr(sequence_table2$qseqid, 1, nchar(sequence_table2$qseqid)-2)
sequence_table2$sseqid <- substr(sequence_table2$sseqid, 1, nchar(sequence_table2$sseqid)-2)
interpro_annotation2 <- interpro_annotation %>%
filter(website == "Pfam") %>%
filter(domain != "-") %>%
mutate(sseqid = qseqid) %>%
select(qseqid, domain)
interpro_annotation3 <- interpro_annotation %>%
filter(website == "Pfam") %>%
filter(domain != "-") %>%
mutate(sseqid = qseqid) %>%
select(sseqid, domain)
proteins_joined <- sequence_table2 %>%
left_join(interpro_annotation2, by = c("qseqid" = "qseqid"))
proteins_joined2 <- interpro_annotation3 %>%
left_join(proteins_joined, by = c("sseqid" = "sseqid"))
proteins_joined3 <- subset(proteins_joined2, !duplicated(subset(proteins_joined2, select=c(qseqid, sseqid, domain.y))))
# Convert Cytoscape Session Clusters into FASTA Files ####
# Set of functions to conver the cytoscape CSV export into fasta files
fix_target_name <- function(table){
as_tibble(substr(table$target, 1, nchar(table$target)-2)) # remove last two characters
}
tidy_import <- function(cluster_file){
cluster_file_tidy <- cluster_file %>%
select(name)
cluster_file_tidy$name <- substring(cluster_file_tidy$name, 2)
cluster_file_tidy$name <- substr(cluster_file_tidy$name, 1, nchar(cluster_file_tidy$name)-1)
return(as_tibble(cluster_file_tidy))
}
join_with_sequences <- function(reference_table, protein_table){
protein_table %>%
left_join(reference_table, by = c('name' = 'seq_names'))
}
extract_sequences <- function(clustered_names){
e_coli_sequences <- readAAStringSet("e_coli_peptide.fa") # load from current working directory
seq_names <- names(e_coli_sequences)
sequences <- paste(e_coli_sequences)
e_coli_sequences_df <- as_tibble(data.frame(seq_names, sequences))
e_coli_sequences_df[] <- lapply(e_coli_sequences_df, as.character)
e_coli_sequences_df$seq_names <- substr(e_coli_sequences_df$seq_names, 1, nchar(e_coli_sequences_df$seq_names)-2)
HMMER_sequence_hit <- join_with_sequences(e_coli_sequences_df, clustered_names)
}
writeFASTAclust <- function(data, filename) {
fastalines = c()
for(rowNum in 1:nrow(data)){
fastalines = c(fastalines, as.character(paste(">", data[rowNum, "name"], sep = "")))
fastalines = c(fastalines, as.character(data[rowNum, "sequences"]))
}
fileConn <- file(filename)
writeLines(fastalines, fileConn)
close(fileConn)
}
# Plot Phylogroup - Gene Distribution Heatmaps ####
plot_heatmap_transporter_proportions <- function(joined_proteins){
total_num_genes <- joined_proteins %>%
dplyr::group_by(gene) %>%
dplyr::summarise(total_gene_num = length(gene))
discrete_num_genes <- joined_proteins %>%
dplyr::group_by(gene, Phylogroup) %>%
dplyr::summarise(dist_gene_num = n_distinct(gene))
joined_table <- discrete_num_genes %>%
left_join(total_num_genes, by = "gene") %>%
mutate(prop_gene_num = dist_gene_num / total_gene_num)
ggplot(joined_table, aes(x = Phylogroup, y = gene)) +
geom_tile(aes(fill = prop_gene_num), colour = "white") +
scale_fill_gradient(low = "blue", high = "green") +
theme_classic()
}
# Make clustered heatmaps for gene 'rarity' metadata ####
# insert a gene transporter list in tibble format
make_clustered_heatmap <- function(transporter_gene_list){
transporter_gene_list_matrix <- as.matrix(transporter_gene_list[, -1])
rownames(transporter_gene_list_matrix) <- transporter_gene_list$target
dendro <- as.dendrogram(hclust(d = dist(x = transporter_gene_list_matrix)))
dendro.plot <- ggdendrogram(data = dendro, rotate = TRUE)
dendro.plot <- dendro.plot + theme(axis.text.y = element_text(size = 4))
order <- order.dendrogram(dendro)
transporter_gene_list$target <- factor(x = transporter_gene_list$target,
levels = transporter_gene_list$target[order],
ordered = TRUE)
heatmap <- ggplot(data = transporter_gene_list, aes(x = gene_class, y = target)) +
geom_tile(aes(fill = count)) +
scale_fill_gradient(low = "#FF7F50", high = "#66CD00") +
theme_tufte() +
theme(axis.text.y = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
legend.position = "top")
print(heatmap, vp = viewport(x = 0.4, y = 0.5, width = 0.8, height = 1.0))
print(dendro.plot, vp = viewport(x = 0.80, y = 0.465, width = 0.2, height = 1.04))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/coef.BayesSUR.R
\name{coef.BayesSUR}
\alias{coef.BayesSUR}
\title{coef method for class \code{BayesSUR}}
\usage{
\method{coef}{BayesSUR}(object, beta.type = "marginal", Pmax = 0, ...)
}
\arguments{
\item{object}{an object of class \code{BayesSUR}}
\item{beta.type}{type of output beta. Default is \code{marginal}, giving marginal beta estimation. If \code{beta.type="conditional"}, it gives beta estimation conditional on gamma=1.}
\item{Pmax}{If \code{Pmax=0.5} and \code{beta.type="conditional"}, it gives median probability model betas. Default is 0.}
\item{...}{other arguments}
}
\value{
Estimated coefficients are from an object of class \code{BayesSUR}. If the \code{BayesSUR} specified data standardization, the fitted values are base based on standardized data.
}
\description{
Extract the posterior mean of the coefficients of a \code{BayesSUR} class object
}
\examples{
data("exampleQTL", package = "BayesSUR")
hyperpar <- list( a_w = 2 , b_w = 5 )
set.seed(9173)
fit <- BayesSUR(Y = exampleEQTL[["blockList"]][[1]],
X = exampleEQTL[["blockList"]][[2]],
data = exampleEQTL[["data"]], outFilePath = tempdir(),
nIter = 100, burnin = 50, nChains = 2, gammaPrior = "hotspot",
hyperpar = hyperpar, tmpFolder = "tmp/" )
## check prediction
beta.hat <- coef(fit)
}
| /BayesSUR/man/coef.BayesSUR.Rd | permissive | ocbe-uio/BayesSUR | R | false | true | 1,418 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/coef.BayesSUR.R
\name{coef.BayesSUR}
\alias{coef.BayesSUR}
\title{coef method for class \code{BayesSUR}}
\usage{
\method{coef}{BayesSUR}(object, beta.type = "marginal", Pmax = 0, ...)
}
\arguments{
\item{object}{an object of class \code{BayesSUR}}
\item{beta.type}{type of output beta. Default is \code{marginal}, giving marginal beta estimation. If \code{beta.type="conditional"}, it gives beta estimation conditional on gamma=1.}
\item{Pmax}{If \code{Pmax=0.5} and \code{beta.type="conditional"}, it gives median probability model betas. Default is 0.}
\item{...}{other arguments}
}
\value{
Estimated coefficients are from an object of class \code{BayesSUR}. If the \code{BayesSUR} specified data standardization, the fitted values are base based on standardized data.
}
\description{
Extract the posterior mean of the coefficients of a \code{BayesSUR} class object
}
\examples{
data("exampleQTL", package = "BayesSUR")
hyperpar <- list( a_w = 2 , b_w = 5 )
set.seed(9173)
fit <- BayesSUR(Y = exampleEQTL[["blockList"]][[1]],
X = exampleEQTL[["blockList"]][[2]],
data = exampleEQTL[["data"]], outFilePath = tempdir(),
nIter = 100, burnin = 50, nChains = 2, gammaPrior = "hotspot",
hyperpar = hyperpar, tmpFolder = "tmp/" )
## check prediction
beta.hat <- coef(fit)
}
|
% Generated by roxygen2 (4.0.2): do not edit by hand
\name{gini}
\alias{gini}
\title{Gini coefficient}
\usage{
gini(x)
}
\arguments{
\item{x}{a vector}
}
\value{
a scalar
}
\description{
Compute the Gini coefficient (Gini index or Gini ratio) which is a mesure of statistical dispersion
}
\author{
Hans Ole Orka \email{hans.ole.orka@gmail.org}
}
\references{
Gini, C (1909) Concentration and dependency ratios (in Italian). English translation in Rivista di Politica Economica, 87 (1997), 769-789.
}
| /man/gini.Rd | no_license | hansoleorka/myR | R | false | false | 501 | rd | % Generated by roxygen2 (4.0.2): do not edit by hand
\name{gini}
\alias{gini}
\title{Gini coefficient}
\usage{
gini(x)
}
\arguments{
\item{x}{a vector}
}
\value{
a scalar
}
\description{
Compute the Gini coefficient (Gini index or Gini ratio) which is a mesure of statistical dispersion
}
\author{
Hans Ole Orka \email{hans.ole.orka@gmail.org}
}
\references{
Gini, C (1909) Concentration and dependency ratios (in Italian). English translation in Rivista di Politica Economica, 87 (1997), 769-789.
}
|
# count_lowflow_outliers_using_baseline function
# purpose: find outliers in SWAT .rch file for low flow risk analysis
# last updated: 20171120
# author: sheila saia
# contact: ssaia [at] ncsu [dot] edu
count_lowflow_outliers_using_baseline=function(baseline_outlier_cutoffs,projection_rch_data) {
# baseline_outlier_cutoffs comes from count_lowflow_outliers()[[2]] (second list output)
# projection_data is formatted using reformat_rch_file()
# uses baseline data to calculate minor and major outlier cutoffs and then applies this
# to select projection data
# load libraries
library(tidyverse) # data management
# select necessary info
projection_data_sel=projection_rch_data %>% select(RCH,MO,YR,FLOW_OUTcms)
# define output data frames
output_counts_df=data.frame(RCH=as.integer(),
YR=as.integer(),
n_minor_lowflow=as.integer(),
n_major_lowflow=as.integer())
output_bounds_df=data.frame(RCH=as.integer(),
minor_outlier_cutoff=as.numeric(),
major_outlier_cutoff=as.numeric())
# calculate number of subbasins for for loop
num_rchs=length(unique(projection_rch_data$RCH))
# find minor and major outliers for each subbasin
for (i in 1:num_rchs) {
# select one subbasin
baseline_cutoff_df_temp=baseline_outlier_cutoffs %>% filter(RCH==i)
projection_df_temp=projection_data_sel %>% filter(RCH==i) %>% mutate(dataset="all_data")
# baseline minor outlier cutoff
lowbound_minor_outlier=baseline_cutoff_df_temp$minor_outlier_cutoff
# baseline major outlier cutoff
lowbound_major_outlier=baseline_cutoff_df_temp$major_outlier_cutoff
# save projection outlier data
minor_lowflow_df=projection_df_temp %>%
filter(FLOW_OUTcms<=lowbound_minor_outlier) %>%
mutate(dataset="minor_outlier")
major_lowflow_df=projection_df_temp %>%
filter(FLOW_OUTcms<=lowbound_major_outlier) %>%
mutate(dataset="major_outlier")
# count outliers
output_counts_df_temp=bind_rows(projection_df_temp,minor_lowflow_df,major_lowflow_df) %>% # bind baseline_df_temp too so make sure to get all years
group_by(RCH,YR) %>%
summarize(n_minor_lowflow=sum(dataset=="minor_outlier"),
n_major_lowflow=sum(dataset=="major_outlier"))
# format bounds information (this should be the same as for baseline_outlier_cutoffs)
output_bounds_df_temp=data.frame(RCH=i,
minor_outlier_cutoff=lowbound_minor_outlier,
major_outlier_cutoff=lowbound_major_outlier)
# append temp output
output_counts_df=bind_rows(output_counts_df,output_counts_df_temp)
output_bounds_df=bind_rows(output_bounds_df,output_bounds_df_temp)
}
return(list(output_counts_df,output_bounds_df)) # returns list element with both dataframes
}
| /functions/count_lowflow_outliers_using_baseline.R | no_license | sheilasaia/yadkin-analysis | R | false | false | 2,990 | r | # count_lowflow_outliers_using_baseline function
# purpose: find outliers in SWAT .rch file for low flow risk analysis
# last updated: 20171120
# author: sheila saia
# contact: ssaia [at] ncsu [dot] edu
count_lowflow_outliers_using_baseline=function(baseline_outlier_cutoffs,projection_rch_data) {
# baseline_outlier_cutoffs comes from count_lowflow_outliers()[[2]] (second list output)
# projection_data is formatted using reformat_rch_file()
# uses baseline data to calculate minor and major outlier cutoffs and then applies this
# to select projection data
# load libraries
library(tidyverse) # data management
# select necessary info
projection_data_sel=projection_rch_data %>% select(RCH,MO,YR,FLOW_OUTcms)
# define output data frames
output_counts_df=data.frame(RCH=as.integer(),
YR=as.integer(),
n_minor_lowflow=as.integer(),
n_major_lowflow=as.integer())
output_bounds_df=data.frame(RCH=as.integer(),
minor_outlier_cutoff=as.numeric(),
major_outlier_cutoff=as.numeric())
# calculate number of subbasins for for loop
num_rchs=length(unique(projection_rch_data$RCH))
# find minor and major outliers for each subbasin
for (i in 1:num_rchs) {
# select one subbasin
baseline_cutoff_df_temp=baseline_outlier_cutoffs %>% filter(RCH==i)
projection_df_temp=projection_data_sel %>% filter(RCH==i) %>% mutate(dataset="all_data")
# baseline minor outlier cutoff
lowbound_minor_outlier=baseline_cutoff_df_temp$minor_outlier_cutoff
# baseline major outlier cutoff
lowbound_major_outlier=baseline_cutoff_df_temp$major_outlier_cutoff
# save projection outlier data
minor_lowflow_df=projection_df_temp %>%
filter(FLOW_OUTcms<=lowbound_minor_outlier) %>%
mutate(dataset="minor_outlier")
major_lowflow_df=projection_df_temp %>%
filter(FLOW_OUTcms<=lowbound_major_outlier) %>%
mutate(dataset="major_outlier")
# count outliers
output_counts_df_temp=bind_rows(projection_df_temp,minor_lowflow_df,major_lowflow_df) %>% # bind baseline_df_temp too so make sure to get all years
group_by(RCH,YR) %>%
summarize(n_minor_lowflow=sum(dataset=="minor_outlier"),
n_major_lowflow=sum(dataset=="major_outlier"))
# format bounds information (this should be the same as for baseline_outlier_cutoffs)
output_bounds_df_temp=data.frame(RCH=i,
minor_outlier_cutoff=lowbound_minor_outlier,
major_outlier_cutoff=lowbound_major_outlier)
# append temp output
output_counts_df=bind_rows(output_counts_df,output_counts_df_temp)
output_bounds_df=bind_rows(output_bounds_df,output_bounds_df_temp)
}
return(list(output_counts_df,output_bounds_df)) # returns list element with both dataframes
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/scalecurve.R
\name{scaleCurve}
\alias{scaleCurve}
\title{Scale curve}
\usage{
scaleCurve(
x,
y = NULL,
alpha = seq(0, 1, 0.01),
name = "X",
name_y = "Y",
title = "Scale Curve",
depth_params = list(method = "Projection")
)
}
\arguments{
\item{x}{Multivariate data as a matrix.}
\item{y}{Additional matrix with multivariate data.}
\item{alpha}{Vector with values of central area to be used in computation.}
\item{name}{Name of matrix X used in legend.}
\item{name_y}{Name of matrix Y used in legend.}
\item{title}{title of the plot.}
\item{depth_params}{list of parameters for function depth (method, threads, ndir, la, lb, pdim, mean, cov, exact).}
}
\value{
Returns the volume of the convex hull containing subsequent central points of \code{X}.
}
\description{
Draws a scale curve: measure of dispersion.
}
\details{
For sample depth function \eqn{ D({x}, {{{Z}} ^ {n}}) }, \eqn{ {x} \in {{{R}} ^ {d}} }, \eqn{ d \ge 2 }, \eqn{ {Z} ^ {n} = \{{{{z}}_{1}}, ..., {{{z}}_{n}}\} \subset {{{R}} ^ {d}} }, \eqn{ {{D}_{\alpha}}({{{Z}} ^ {n}}) } denoting \eqn{\alpha} --- central region, we can define the scale curve \eqn{ SC(\alpha) = \left(\alpha, vol({{D}_{\alpha}}({{{Z}} ^ {n}})\right) \subset {{{R}} ^ {2}} }, for \eqn{ \alpha \in [0, 1] }
The scale curve is a two-dimensional method of describing the dispersion of random vector around the depth induced median.
Function scalecurve for determining the volumes of the convex hull containing points from alpha central regions, uses function convhulln from geometry package.
The minimal dimension of data in X or Y is 2.
ggplot2 package is used to draw a plot.
}
\examples{
library(mvtnorm)
x <- mvrnorm(n = 100, mu = c(0, 0), Sigma = 3 * diag(2))
y <- rmvt(n = 100, sigma = diag(2), df = 2)
scaleCurve(x, y, depth_params = list(method = "Projection"))
# Comparing two scale curves
# normal distribution and mixture of normal distributions
x <- mvrnorm(100, c(0, 0), diag(2))
y <- mvrnorm(80, c(0, 0), diag(2))
z <- mvrnorm(20, c(5, 5), diag(2))
scaleCurve(x, rbind(y, z), name = "N", name_y = "Mixture of N",
depth_params = list(method = "Projection"))
}
\references{
Liu, R.Y., Parelius, J.M. and Singh, K. (1999), Multivariate analysis by data depth: Descriptive statistics, graphics and inference (with discussion), \emph{Ann. Statist.}, \bold{27}, 783--858.
Chaudhuri, P. (1996), On a Geometric Notion of Quantiles for Multivariate Data, \emph{Journal of the American Statistical Association}, 862--872.
Dyckerhoff, R. (2004), Data Depths Satisfying the Projection Property, \emph{Allgemeines Statistisches Archiv.}, \bold{88}, 163--190.
}
\seealso{
\code{\link{depthContour}} and \code{\link{depthPersp}} for depth graphics.
}
\author{
Daniel Kosiorowski, Mateusz Bocian, Anna Wegrzynkiewicz and Zygmunt Zawadzki from Cracow University of Economics.
}
\keyword{curve}
\keyword{depth}
\keyword{function}
\keyword{multivariate}
\keyword{nonparametric}
\keyword{robust}
\keyword{scale}
| /man/scaleCurve.Rd | no_license | zzawadz/DepthProc | R | false | true | 3,052 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/scalecurve.R
\name{scaleCurve}
\alias{scaleCurve}
\title{Scale curve}
\usage{
scaleCurve(
x,
y = NULL,
alpha = seq(0, 1, 0.01),
name = "X",
name_y = "Y",
title = "Scale Curve",
depth_params = list(method = "Projection")
)
}
\arguments{
\item{x}{Multivariate data as a matrix.}
\item{y}{Additional matrix with multivariate data.}
\item{alpha}{Vector with values of central area to be used in computation.}
\item{name}{Name of matrix X used in legend.}
\item{name_y}{Name of matrix Y used in legend.}
\item{title}{title of the plot.}
\item{depth_params}{list of parameters for function depth (method, threads, ndir, la, lb, pdim, mean, cov, exact).}
}
\value{
Returns the volume of the convex hull containing subsequent central points of \code{X}.
}
\description{
Draws a scale curve: measure of dispersion.
}
\details{
For sample depth function \eqn{ D({x}, {{{Z}} ^ {n}}) }, \eqn{ {x} \in {{{R}} ^ {d}} }, \eqn{ d \ge 2 }, \eqn{ {Z} ^ {n} = \{{{{z}}_{1}}, ..., {{{z}}_{n}}\} \subset {{{R}} ^ {d}} }, \eqn{ {{D}_{\alpha}}({{{Z}} ^ {n}}) } denoting \eqn{\alpha} --- central region, we can define the scale curve \eqn{ SC(\alpha) = \left(\alpha, vol({{D}_{\alpha}}({{{Z}} ^ {n}})\right) \subset {{{R}} ^ {2}} }, for \eqn{ \alpha \in [0, 1] }
The scale curve is a two-dimensional method of describing the dispersion of random vector around the depth induced median.
Function scalecurve for determining the volumes of the convex hull containing points from alpha central regions, uses function convhulln from geometry package.
The minimal dimension of data in X or Y is 2.
ggplot2 package is used to draw a plot.
}
\examples{
library(mvtnorm)
x <- mvrnorm(n = 100, mu = c(0, 0), Sigma = 3 * diag(2))
y <- rmvt(n = 100, sigma = diag(2), df = 2)
scaleCurve(x, y, depth_params = list(method = "Projection"))
# Comparing two scale curves
# normal distribution and mixture of normal distributions
x <- mvrnorm(100, c(0, 0), diag(2))
y <- mvrnorm(80, c(0, 0), diag(2))
z <- mvrnorm(20, c(5, 5), diag(2))
scaleCurve(x, rbind(y, z), name = "N", name_y = "Mixture of N",
depth_params = list(method = "Projection"))
}
\references{
Liu, R.Y., Parelius, J.M. and Singh, K. (1999), Multivariate analysis by data depth: Descriptive statistics, graphics and inference (with discussion), \emph{Ann. Statist.}, \bold{27}, 783--858.
Chaudhuri, P. (1996), On a Geometric Notion of Quantiles for Multivariate Data, \emph{Journal of the American Statistical Association}, 862--872.
Dyckerhoff, R. (2004), Data Depths Satisfying the Projection Property, \emph{Allgemeines Statistisches Archiv.}, \bold{88}, 163--190.
}
\seealso{
\code{\link{depthContour}} and \code{\link{depthPersp}} for depth graphics.
}
\author{
Daniel Kosiorowski, Mateusz Bocian, Anna Wegrzynkiewicz and Zygmunt Zawadzki from Cracow University of Economics.
}
\keyword{curve}
\keyword{depth}
\keyword{function}
\keyword{multivariate}
\keyword{nonparametric}
\keyword{robust}
\keyword{scale}
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/validation.r
\name{isValidICD10}
\alias{isValidICD10}
\title{Checks if ICD10 code(s) are valid.}
\usage{
isValidICD10(icd10)
}
\arguments{
\item{icd10}{icd10 code}
}
\description{
Checks if ICD10 code(s) are valid.
}
| /R Packages/icdcoder/man/isValidICD10.Rd | no_license | ryerex/Research_and_Methods | R | false | false | 304 | rd | % Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/validation.r
\name{isValidICD10}
\alias{isValidICD10}
\title{Checks if ICD10 code(s) are valid.}
\usage{
isValidICD10(icd10)
}
\arguments{
\item{icd10}{icd10 code}
}
\description{
Checks if ICD10 code(s) are valid.
}
|
#' function to clean tweets
#'
#' requires stringr to be loaded
#'
#' cleans tweets into more useable format, removes unrecognised characters,
#' control characters, links, digits, double spaces, whitespaces from start and
#' end of tweets, and converts everything to lower case
#'
#' @param tweets the text(tweets) to be cleaned
#' @param concat_terms terms/phrases you may wish to be concatenated
#' @param rename_odds replace digits that are likely betting odds, dates, or
#' times (eg, 3/1, 3.55, 3-1, 4:50) and replaces them with the word 'odds'
#' @param rm_punct remove punctuation
tweet_cleaner <- function(tweets, concat_terms = NULL, rename_odds = FALSE, rm_punct = FALSE) {
# remove emoticons/unrecognised characters
tweets <- iconv(tweets, from = "latin1", to = "ASCII", sub = "")
# remove control characters
tweets <- stringr::str_replace_all(tweets, "[[:cntrl:]]", " ")
# remove links
tweets <- stringr::str_replace_all(tweets, "(http[^ ]*)|(www\\.[^ ]*)", " ")
# convert tweets to lower case
tweets <- tolower(tweets)
# if concat_terms is provided, loop through and concatenate
if(!is.null(concat_terms)) {
concat_terms <- tolower(concat_terms)
for(term in seq_along(concat_terms)) {
t_pattern <- stringr::str_replace_all(string = concat_terms[term], "\\s+", " ?")
t_replace <- stringr::str_pad(stringr::str_replace_all(t_pattern, "\\s+|[[:punct:]]", ""),
width = 25, side = "both")
tweets <- stringr::str_replace_all(tweets, t_pattern, t_replace)
tweets <- stringr::str_replace_all(tweets, "\\s+", " ")
}
}
# replace numerical odds (and times) with 'odds'
if(rename_odds) {
tweets <- stringr::str_replace_all(tweets, "[[:digit:]]+[[:punct:]]+[[:digit:]]+", "odds")
}
# remove punctuation
if(rm_punct) {
tweets <- stringr::str_replace_all(tweets, "[[:punct:]]", " ")
}
# remove digits
tweets <- stringr::str_replace_all(tweets, "[[:digit:]]+", "")
# remove space from start/end of tweets
tweets <- stringr::str_trim(tweets, side = "both")
# remove double spaces from tweets
tweets <- stringr::str_replace_all(tweets, "\\s+", " ")
return(tweets)
}
#' find tweets
#'
#' locates terms/phrases in tweets, returning indices
#'
#' @param tweets the tweets to be searched
#' @param searchfor terms/phrases to be searched for
#' @param counts will duplicate indices if more than one term from searchfor is
#' found in that tweet
findtweets <- function(tweets, searchfor, counts = FALSE) {
# make terms lower case, replace spaces/punctuation with " ?" for flexible searches
searchfor <- tolower(stringr::str_replace_all(searchfor, "\\s+|[[:punct:]]", " ?"))
# if counts for number of terms per tweet then counts = TRUE
if(counts) {
# for each term in the searchfor argument, return the indices of the tweets
# in which the term appears
indices <- as.vector(unlist(sapply(searchfor, function(x) {
grep(x, tweets, ignore.case = TRUE)
})))
} else {
# otherwise a TRUE/FALSE index is returned
indices <- grepl(paste0(searchfor, collapse = "|"), tweets)
}
return(indices)
}
#' find and concatenate terms
#'
#' @param tweets the tweets to be searched
#' @param concat_terms terms/phrases you wish to concatenate
find_n_concat <- function(tweets, concat_terms) {
# make terms to be concatenated lower case
concat_terms <- tolower(concat_terms)
# loop through terms, replace spaces with a " ?" for flexible searches
# pad term with a space either side - isolating term - remove any punctuation
# or spaces in terms
for(term in concat_terms) {
tweets <- stringr::str_replace_all(tweets,
stringr::str_replace_all(term, "\\s+", " ?"),
stringr::str_pad(term, width = 30, side = "both"))
tweets <- stringr::str_replace_all(tweets,
stringr::str_replace_all(term, "\\s+", " ?"),
stringr::str_replace_all(term, "\\s+|[[:punct:]]", ""))
}
# replace double spaces with single spaces
tweets <- stringr::str_replace_all(tweets, "\\s+", " ")
return(tweets)
}
#' sentiment score
#'
#' will look for words in tweets that in dictionaries of positive and negative
#' words, heavily borrowed code from Jeffrey Breen
#'
#' @param tweets the tweets to be scored
#' @param pos_words positive dictionary
#' @param neg_words negative dictionary
#' @param .progress progress bar
senti_score <- function(tweets, pos_words, neg_words, .progress = "none") {
scores <- plyr::laply(tweets, function(tweet, pos_words, neg_words) {
# split words
word_list <- stringr::str_split(tweet, "\\s+")
words <- unlist(word_list)
# check for matches in tweets to positive and negative dictionaries
pos_matches <- match(words, pos_words)
neg_matches <- match(words, neg_words)
# ignore NA values
pos_matches <- !is.na(pos_matches)
neg_matches <- !is.na(neg_matches)
# calculate score per tweet
score <- sum(pos_matches) - sum(neg_matches)
return(score)
}, pos_words, neg_words, .progress = .progress)
return(scores)
}
| /R/functions.R | no_license | durtal/KYDerby2015-twitter | R | false | false | 5,440 | r | #' function to clean tweets
#'
#' requires stringr to be loaded
#'
#' cleans tweets into more useable format, removes unrecognised characters,
#' control characters, links, digits, double spaces, whitespaces from start and
#' end of tweets, and converts everything to lower case
#'
#' @param tweets the text(tweets) to be cleaned
#' @param concat_terms terms/phrases you may wish to be concatenated
#' @param rename_odds replace digits that are likely betting odds, dates, or
#' times (eg, 3/1, 3.55, 3-1, 4:50) and replaces them with the word 'odds'
#' @param rm_punct remove punctuation
tweet_cleaner <- function(tweets, concat_terms = NULL, rename_odds = FALSE, rm_punct = FALSE) {
# remove emoticons/unrecognised characters
tweets <- iconv(tweets, from = "latin1", to = "ASCII", sub = "")
# remove control characters
tweets <- stringr::str_replace_all(tweets, "[[:cntrl:]]", " ")
# remove links
tweets <- stringr::str_replace_all(tweets, "(http[^ ]*)|(www\\.[^ ]*)", " ")
# convert tweets to lower case
tweets <- tolower(tweets)
# if concat_terms is provided, loop through and concatenate
if(!is.null(concat_terms)) {
concat_terms <- tolower(concat_terms)
for(term in seq_along(concat_terms)) {
t_pattern <- stringr::str_replace_all(string = concat_terms[term], "\\s+", " ?")
t_replace <- stringr::str_pad(stringr::str_replace_all(t_pattern, "\\s+|[[:punct:]]", ""),
width = 25, side = "both")
tweets <- stringr::str_replace_all(tweets, t_pattern, t_replace)
tweets <- stringr::str_replace_all(tweets, "\\s+", " ")
}
}
# replace numerical odds (and times) with 'odds'
if(rename_odds) {
tweets <- stringr::str_replace_all(tweets, "[[:digit:]]+[[:punct:]]+[[:digit:]]+", "odds")
}
# remove punctuation
if(rm_punct) {
tweets <- stringr::str_replace_all(tweets, "[[:punct:]]", " ")
}
# remove digits
tweets <- stringr::str_replace_all(tweets, "[[:digit:]]+", "")
# remove space from start/end of tweets
tweets <- stringr::str_trim(tweets, side = "both")
# remove double spaces from tweets
tweets <- stringr::str_replace_all(tweets, "\\s+", " ")
return(tweets)
}
#' find tweets
#'
#' locates terms/phrases in tweets, returning indices
#'
#' @param tweets the tweets to be searched
#' @param searchfor terms/phrases to be searched for
#' @param counts will duplicate indices if more than one term from searchfor is
#' found in that tweet
findtweets <- function(tweets, searchfor, counts = FALSE) {
# make terms lower case, replace spaces/punctuation with " ?" for flexible searches
searchfor <- tolower(stringr::str_replace_all(searchfor, "\\s+|[[:punct:]]", " ?"))
# if counts for number of terms per tweet then counts = TRUE
if(counts) {
# for each term in the searchfor argument, return the indices of the tweets
# in which the term appears
indices <- as.vector(unlist(sapply(searchfor, function(x) {
grep(x, tweets, ignore.case = TRUE)
})))
} else {
# otherwise a TRUE/FALSE index is returned
indices <- grepl(paste0(searchfor, collapse = "|"), tweets)
}
return(indices)
}
#' find and concatenate terms
#'
#' @param tweets the tweets to be searched
#' @param concat_terms terms/phrases you wish to concatenate
find_n_concat <- function(tweets, concat_terms) {
# make terms to be concatenated lower case
concat_terms <- tolower(concat_terms)
# loop through terms, replace spaces with a " ?" for flexible searches
# pad term with a space either side - isolating term - remove any punctuation
# or spaces in terms
for(term in concat_terms) {
tweets <- stringr::str_replace_all(tweets,
stringr::str_replace_all(term, "\\s+", " ?"),
stringr::str_pad(term, width = 30, side = "both"))
tweets <- stringr::str_replace_all(tweets,
stringr::str_replace_all(term, "\\s+", " ?"),
stringr::str_replace_all(term, "\\s+|[[:punct:]]", ""))
}
# replace double spaces with single spaces
tweets <- stringr::str_replace_all(tweets, "\\s+", " ")
return(tweets)
}
#' sentiment score
#'
#' will look for words in tweets that in dictionaries of positive and negative
#' words, heavily borrowed code from Jeffrey Breen
#'
#' @param tweets the tweets to be scored
#' @param pos_words positive dictionary
#' @param neg_words negative dictionary
#' @param .progress progress bar
senti_score <- function(tweets, pos_words, neg_words, .progress = "none") {
scores <- plyr::laply(tweets, function(tweet, pos_words, neg_words) {
# split words
word_list <- stringr::str_split(tweet, "\\s+")
words <- unlist(word_list)
# check for matches in tweets to positive and negative dictionaries
pos_matches <- match(words, pos_words)
neg_matches <- match(words, neg_words)
# ignore NA values
pos_matches <- !is.na(pos_matches)
neg_matches <- !is.na(neg_matches)
# calculate score per tweet
score <- sum(pos_matches) - sum(neg_matches)
return(score)
}, pos_words, neg_words, .progress = .progress)
return(scores)
}
|
#!/usr/bin/env Rscript
library("R.utils")
source("http://www.bioconductor.org/biocLite.R")
library("affy")
library("simpleaffy")
library("scales")
library("limma")
library("SAGx")
library("Hmisc")
library("Heatplus")
library("gplots")
library("cluster")
library("GEOquery")
library("topGO")
library("gridExtra")
#cwd = getwd() # this works from the command line but not in RStudio
cwd = "/Users/kyclark/work/abe516-project1"
setwd(cwd)
data_dir = file.path(cwd, 'data')
if (!dir.exists(data_dir)) {
stop(paste0("Missing data dir ", data_dir))
}
figures_dir = file.path(cwd, 'figures')
if (!dir.exists(figures_dir)) {
dir.create(figures_dir)
}
tables_dir = file.path(cwd, 'tables')
if (!dir.exists(tables_dir)) {
dir.create(tables_dir)
}
dat = ReadAffy(celfile.path = "data")
num_samples = length(dat)
groups = c("C", "Bs", "Efs", "Efm")
fl <- factor(c(rep('0', 2), rep('1', 3), rep('2', 3), rep('3', 3), rep('0', 2)),
labels=groups)
printf("There are %s features in %s samples\n", length(featureNames(dat)), num_samples)
#
# Raw plots
#
printf("Examing raw values\n")
palette(brewer_pal(type = "seq", palette = "Set2")(length(groups)))
png(filename = file.path(figures_dir, "raw-box-plot.png"))
boxplot(dat, names = fl, main = "Raw", las = 2, col = fl)
invisible(dev.off())
png(filename = file.path(figures_dir, "raw-ma-plot.png"), width = 600, height = 800)
par(mfrow = c(5,3))
MAplot(dat, plot.method = "smoothScatter")
invisible(dev.off())
dat.rmabg = bg.correct(dat, "rma")
dat.norm = normalize(dat.rmabg, "quantiles")
png(filename = file.path(figures_dir, "norm-box-plot.png"))
boxplot(dat.norm, main = "Normalized", las = 2, col = as.factor(groups))
invisible(dev.off())
png(filename = file.path(figures_dir, "norm-ma-plot.png"), width = 600, height = 800)
par(mfrow = c(5,3))
MAplot(dat.norm, plot.method = "smoothScatter")
#
# Rather than manually running each error-correcting step, we can use "expresso"
#
print("Running expresso")
eset <- expresso(dat,
bgcorrect.method = "rma",
normalize.method = "quantiles",
pmcorrect.method = "pmonly",
summary.method = "medianpolish")
design <- model.matrix(~ 0 + fl) # original
colnames(design) = groups
#
# To get the metadata we want to see in the output, it's necessary to use the SOFT file
# ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE95nnn/GSE95636/soft/GSE95636_family.soft.gz
# The GEOquery library provides a "getGEO" function that will download this and
# provide us with the corrected expression data.
#
gset <- getGEO("GSE95636", GSEMatrix = TRUE, AnnotGPL = TRUE)
if (length(gset) > 1) idx <- grep("GPL200", attr(gset, "names")) else idx <- 1
gset <- gset[[idx]]
gset$description <- fl
design <- model.matrix(~ description + 0, gset)
colnames(design) <- levels(fl)
fit <- lmFit(gset, design)
contrast.matrix <- makeContrasts(Efm-C, Efs-C, Bs-C, Efs-Bs, Efm-Efs, levels = design)
fit1 <- contrasts.fit(fit, contrast.matrix)
fit2 <- eBayes(fit1)
tt.all = topTable(fit2,
adjust = "fdr",
p.value = 0.05,
lfc = 1,
sort.by = "B",
number = 250)
write.table(tt.all,
file = file.path(tables_dir, "top_overall.tab"),
row.names = FALSE,
sep = "\t")
for (coef in 1:5) {
filename = file.path(tables_dir, paste0("top250-c", coef, ".tab"))
printf("Writing '%s'\n", filename)
tt = topTable(fit2,
coef = coef,
adjust = "fdr",
sort.by = "B",
lfc = 1,
number = 250)
write.table(tt, file = filename, row.names = F, sep = "\t")
}
results = decideTests(fit2,
adjust = "fdr",
p = 0.05,
lfc = 1)
summary(results)
printf("Writing Venn diagrams\n")
png(filename = file.path(figures_dir, "venn.png"), width = 800, height = 400)
par(mfrow = c(1, 2))
#vennDiagram(results, main = "Diff Exp Genes")
vennDiagram(results, include = "down", main = "Down Regulated")
vennDiagram(results, include = "up", main = "Up Regulated")
invisible(dev.off())
printf("Writing volcano plots\n")
png(filename = file.path(figures_dir, "volcano.png"),
width = 800,
height = 800)
par(mfrow = c(2,3))
volcanoplot(fit2,
coef = 1,
main = "E_faecium-Control",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 2,
main = "B_subtilis-Control",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 3,
main = "E_faecium-B_subtilis",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 4,
main = "E_faecium-E_faecalis",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 5,
main = "E_faecium-E_faecalis",
names = row.names(fit2$coefficients),
highlight = 10)
invisible(dev.off())
#
# Find the top GO functions; many of the function fields have multiple
# functions separated by "///", so we split on that; additionally, some
# of the function names are very long, so we remove (gsub) everything after
# a comma to get a usable name. As there are so many, we use only those
# occuring with a frequency greater than X
#
go_functions = sub(",.*", "",
unlist(strsplit(tt.all$GO.Function, '///', fixed = T)))
function_count = as.data.frame(table(go_functions))
colnames(function_count) = c("func", "freq")
top_functions = function_count[function_count$freq > 3,]
#
# There are too many processes to show, so we need to filter
# to those with a frequency greater than X
#
go_processes = unlist(strsplit(tt.all$GO.Process, '///', fixed = T))
process_count = as.data.frame(table(go_processes))
colnames(process_count) = c("process", "freq")
top_processes = process_count[process_count$freq > 3,]
#
# This code is ugly, but it's necessary to force ggplot to keep the order
#
top_functions$func = factor(top_functions$func,
levels = top_functions$func[order(top_functions$freq)])
top_processes$process = factor(top_processes$process,
levels = top_processes$process[order(top_processes$freq)])
#
# ggplot doesn't play nicely with par, so we have to use gridExtra
#
png(filename = file.path(figures_dir, "go.png"),
width = 800,
height = 600)
p1 = ggplot(data=top_functions, aes(x=func, y=freq)) +
geom_bar(stat="identity", fill="#56B4E9", colour="black") +
coord_flip()
p2 = ggplot(data=top_processes, aes(x=process, y=freq)) +
geom_bar(stat="identity", fill="#56B4E9", colour="black") +
coord_flip()
grid.arrange(p1, p2, ncol=2, nrow = 1)
invisible(dev.off())
#
# Genomic location
#
locs = unlist(strsplit(tt.all$Chromosome.annotation, '///', fixed = T))
chromosome = sub('Chromosome ', '', sub(',.*', '', locs))
png(filename = file.path(figures_dir, 'chromosomes.png'))
qplot(chromosome)
invisible(dev.off())
#
# Clustering
#
printf("Cluster analysis\n")
#get the expression matrix form eset
eset.expr = exprs(eset)
#extract overall differential expressed genes from expression matrix
DE.all = eset.expr[rownames(tt.all),]
#compute distance matrix
dist.cor = as.dist(1 - cor(t(DE.all)))
#hierarchical clustering
hcfit = hclust(dist.cor, method = 'ave')
#
# Using gap statistic to determine k in HC
#
png(filename = file.path(figures_dir, "gapstat.png"),
width = 800,
height = 800)
k = 6
Gap = rep(0,k)
se = rep(0,k)
for (i in 2:k) {
mem = cutree(hcfit, i)
result = gap(DE.all, class=mem)
Gap[i] = result[1]
se[i] = result[2]
}
errbar(1:k, Gap, Gap-se, Gap+se, xlab = "Number of clusters")
lines(1:k, Gap)
invisible(dev.off())
#
# Using silhoutte width to determine k
#
png(filename = file.path(figures_dir, "silhouette.png"),
width = 800,
height = 800)
k = 10
sil = rep(0,k)
for (i in 2:k){
mem = cutree(hcfit,i)
aa = silhouette(mem, dist(DE.all))
sil[i] = mean(aa[,3])
}
plot(1:k,sil)
lines(1:k,sil)
invisible(dev.off())
#
# Heatmap
#
png(filename = file.path(figures_dir, "heatmap.png"),
width = 800,
height = 800)
c2 = cutree(hcfit,k=2)
colnames(DE.all) = c(rep('E. coli', 2),
rep('B. subtilis', 3),
rep('E. faecalis', 3),
rep('E. faecium', 3),
rep('E. coli', 2))
heatmap_plus(t(scale(t(DE.all))),
clus = c2,
addvar = design,
col = greenred(20))
invisible(dev.off())
#
# plot the resulting dendrogram
#
png(filename = file.path(figures_dir, "dendrogram.png"),
width = 800,
height = 400)
plot(hcfit)
invisible(dev.off())
# cut the tree at height 1.25
hcfit1 = cutree(hcfit, h = 1.25)
# generate 2 clusters and save them in a table
clus = table(names(hcfit1), hcfit1)
write.table(clus,
file = file.path(tables_dir, "clus.tab"),
row.names = TRUE,
sep = "\t")
invisible(dev.off())
printf("All done!\n") | /project1/c_elegans.r | permissive | kyclark/abe516 | R | false | false | 9,226 | r | #!/usr/bin/env Rscript
library("R.utils")
source("http://www.bioconductor.org/biocLite.R")
library("affy")
library("simpleaffy")
library("scales")
library("limma")
library("SAGx")
library("Hmisc")
library("Heatplus")
library("gplots")
library("cluster")
library("GEOquery")
library("topGO")
library("gridExtra")
#cwd = getwd() # this works from the command line but not in RStudio
cwd = "/Users/kyclark/work/abe516-project1"
setwd(cwd)
data_dir = file.path(cwd, 'data')
if (!dir.exists(data_dir)) {
stop(paste0("Missing data dir ", data_dir))
}
figures_dir = file.path(cwd, 'figures')
if (!dir.exists(figures_dir)) {
dir.create(figures_dir)
}
tables_dir = file.path(cwd, 'tables')
if (!dir.exists(tables_dir)) {
dir.create(tables_dir)
}
dat = ReadAffy(celfile.path = "data")
num_samples = length(dat)
groups = c("C", "Bs", "Efs", "Efm")
fl <- factor(c(rep('0', 2), rep('1', 3), rep('2', 3), rep('3', 3), rep('0', 2)),
labels=groups)
printf("There are %s features in %s samples\n", length(featureNames(dat)), num_samples)
#
# Raw plots
#
printf("Examing raw values\n")
palette(brewer_pal(type = "seq", palette = "Set2")(length(groups)))
png(filename = file.path(figures_dir, "raw-box-plot.png"))
boxplot(dat, names = fl, main = "Raw", las = 2, col = fl)
invisible(dev.off())
png(filename = file.path(figures_dir, "raw-ma-plot.png"), width = 600, height = 800)
par(mfrow = c(5,3))
MAplot(dat, plot.method = "smoothScatter")
invisible(dev.off())
dat.rmabg = bg.correct(dat, "rma")
dat.norm = normalize(dat.rmabg, "quantiles")
png(filename = file.path(figures_dir, "norm-box-plot.png"))
boxplot(dat.norm, main = "Normalized", las = 2, col = as.factor(groups))
invisible(dev.off())
png(filename = file.path(figures_dir, "norm-ma-plot.png"), width = 600, height = 800)
par(mfrow = c(5,3))
MAplot(dat.norm, plot.method = "smoothScatter")
#
# Rather than manually running each error-correcting step, we can use "expresso"
#
print("Running expresso")
eset <- expresso(dat,
bgcorrect.method = "rma",
normalize.method = "quantiles",
pmcorrect.method = "pmonly",
summary.method = "medianpolish")
design <- model.matrix(~ 0 + fl) # original
colnames(design) = groups
#
# To get the metadata we want to see in the output, it's necessary to use the SOFT file
# ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE95nnn/GSE95636/soft/GSE95636_family.soft.gz
# The GEOquery library provides a "getGEO" function that will download this and
# provide us with the corrected expression data.
#
gset <- getGEO("GSE95636", GSEMatrix = TRUE, AnnotGPL = TRUE)
if (length(gset) > 1) idx <- grep("GPL200", attr(gset, "names")) else idx <- 1
gset <- gset[[idx]]
gset$description <- fl
design <- model.matrix(~ description + 0, gset)
colnames(design) <- levels(fl)
fit <- lmFit(gset, design)
contrast.matrix <- makeContrasts(Efm-C, Efs-C, Bs-C, Efs-Bs, Efm-Efs, levels = design)
fit1 <- contrasts.fit(fit, contrast.matrix)
fit2 <- eBayes(fit1)
tt.all = topTable(fit2,
adjust = "fdr",
p.value = 0.05,
lfc = 1,
sort.by = "B",
number = 250)
write.table(tt.all,
file = file.path(tables_dir, "top_overall.tab"),
row.names = FALSE,
sep = "\t")
for (coef in 1:5) {
filename = file.path(tables_dir, paste0("top250-c", coef, ".tab"))
printf("Writing '%s'\n", filename)
tt = topTable(fit2,
coef = coef,
adjust = "fdr",
sort.by = "B",
lfc = 1,
number = 250)
write.table(tt, file = filename, row.names = F, sep = "\t")
}
results = decideTests(fit2,
adjust = "fdr",
p = 0.05,
lfc = 1)
summary(results)
printf("Writing Venn diagrams\n")
png(filename = file.path(figures_dir, "venn.png"), width = 800, height = 400)
par(mfrow = c(1, 2))
#vennDiagram(results, main = "Diff Exp Genes")
vennDiagram(results, include = "down", main = "Down Regulated")
vennDiagram(results, include = "up", main = "Up Regulated")
invisible(dev.off())
printf("Writing volcano plots\n")
png(filename = file.path(figures_dir, "volcano.png"),
width = 800,
height = 800)
par(mfrow = c(2,3))
volcanoplot(fit2,
coef = 1,
main = "E_faecium-Control",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 2,
main = "B_subtilis-Control",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 3,
main = "E_faecium-B_subtilis",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 4,
main = "E_faecium-E_faecalis",
names = row.names(fit2$coefficients),
highlight = 10)
volcanoplot(fit2,
coef = 5,
main = "E_faecium-E_faecalis",
names = row.names(fit2$coefficients),
highlight = 10)
invisible(dev.off())
#
# Find the top GO functions; many of the function fields have multiple
# functions separated by "///", so we split on that; additionally, some
# of the function names are very long, so we remove (gsub) everything after
# a comma to get a usable name. As there are so many, we use only those
# occuring with a frequency greater than X
#
go_functions = sub(",.*", "",
unlist(strsplit(tt.all$GO.Function, '///', fixed = T)))
function_count = as.data.frame(table(go_functions))
colnames(function_count) = c("func", "freq")
top_functions = function_count[function_count$freq > 3,]
#
# There are too many processes to show, so we need to filter
# to those with a frequency greater than X
#
go_processes = unlist(strsplit(tt.all$GO.Process, '///', fixed = T))
process_count = as.data.frame(table(go_processes))
colnames(process_count) = c("process", "freq")
top_processes = process_count[process_count$freq > 3,]
#
# This code is ugly, but it's necessary to force ggplot to keep the order
#
top_functions$func = factor(top_functions$func,
levels = top_functions$func[order(top_functions$freq)])
top_processes$process = factor(top_processes$process,
levels = top_processes$process[order(top_processes$freq)])
#
# ggplot doesn't play nicely with par, so we have to use gridExtra
#
png(filename = file.path(figures_dir, "go.png"),
width = 800,
height = 600)
p1 = ggplot(data=top_functions, aes(x=func, y=freq)) +
geom_bar(stat="identity", fill="#56B4E9", colour="black") +
coord_flip()
p2 = ggplot(data=top_processes, aes(x=process, y=freq)) +
geom_bar(stat="identity", fill="#56B4E9", colour="black") +
coord_flip()
grid.arrange(p1, p2, ncol=2, nrow = 1)
invisible(dev.off())
#
# Genomic location
#
locs = unlist(strsplit(tt.all$Chromosome.annotation, '///', fixed = T))
chromosome = sub('Chromosome ', '', sub(',.*', '', locs))
png(filename = file.path(figures_dir, 'chromosomes.png'))
qplot(chromosome)
invisible(dev.off())
#
# Clustering
#
printf("Cluster analysis\n")
#get the expression matrix form eset
eset.expr = exprs(eset)
#extract overall differential expressed genes from expression matrix
DE.all = eset.expr[rownames(tt.all),]
#compute distance matrix
dist.cor = as.dist(1 - cor(t(DE.all)))
#hierarchical clustering
hcfit = hclust(dist.cor, method = 'ave')
#
# Using gap statistic to determine k in HC
#
png(filename = file.path(figures_dir, "gapstat.png"),
width = 800,
height = 800)
k = 6
Gap = rep(0,k)
se = rep(0,k)
for (i in 2:k) {
mem = cutree(hcfit, i)
result = gap(DE.all, class=mem)
Gap[i] = result[1]
se[i] = result[2]
}
errbar(1:k, Gap, Gap-se, Gap+se, xlab = "Number of clusters")
lines(1:k, Gap)
invisible(dev.off())
#
# Using silhoutte width to determine k
#
png(filename = file.path(figures_dir, "silhouette.png"),
width = 800,
height = 800)
k = 10
sil = rep(0,k)
for (i in 2:k){
mem = cutree(hcfit,i)
aa = silhouette(mem, dist(DE.all))
sil[i] = mean(aa[,3])
}
plot(1:k,sil)
lines(1:k,sil)
invisible(dev.off())
#
# Heatmap
#
png(filename = file.path(figures_dir, "heatmap.png"),
width = 800,
height = 800)
c2 = cutree(hcfit,k=2)
colnames(DE.all) = c(rep('E. coli', 2),
rep('B. subtilis', 3),
rep('E. faecalis', 3),
rep('E. faecium', 3),
rep('E. coli', 2))
heatmap_plus(t(scale(t(DE.all))),
clus = c2,
addvar = design,
col = greenred(20))
invisible(dev.off())
#
# plot the resulting dendrogram
#
png(filename = file.path(figures_dir, "dendrogram.png"),
width = 800,
height = 400)
plot(hcfit)
invisible(dev.off())
# cut the tree at height 1.25
hcfit1 = cutree(hcfit, h = 1.25)
# generate 2 clusters and save them in a table
clus = table(names(hcfit1), hcfit1)
write.table(clus,
file = file.path(tables_dir, "clus.tab"),
row.names = TRUE,
sep = "\t")
invisible(dev.off())
printf("All done!\n") |
batting <- read.csv('Batting.csv')
head(batting)
str(batting)
head(batting$AB)
head(batting$X2B)
batting$BA <- batting$H/batting$AB
tail(batting$BA,5)
batting$X1B <- batting$H - batting$X2B - batting$X3B - batting$HR
batting$OBP <- (batting$H + batting$BB + batting$HBP)/(batting$AB + batting$BB + batting$HBP + batting$SF)
batting$SLG <- (batting$X1B + 2*batting$X2B + 3*batting$X3B + 4*batting$HR)/batting$AB
str(batting)
sal <- read.csv('Salaries.csv')
batting <- subset(batting, yearID >= 1985)
combo <- merge(x = batting, y= sal,by = c('playerID','yearID'))
summary(combo)
# Analyzing the Lost Players
lost_players <- subset(combo, subset = playerID %in% c('giambja01','damonjo01','saenzol01'))
lost_players <- subset(lost_players, yearID == 2001)
combo <- subset(combo, yearID == 2001)
lost_players[,c('playerID','H','X2B','X3B','HR','OBP','SLG','BA','AB')]
# Replacement Players
library(dplyr)
ggplot(combo, aes(x=OBP,y=salary)) + geom_point(size=2)
combo <- subset(combo,salary < 8000000 & OBP > 0 & AB >= 450)
str(combo)
con1 <- 15*10^6
con2 <- sum(select(lost_players, AB))
con3 <- sum(select(lost_players, OBP))/3
options <- head(arrange(combo,OBP),10)
options[,c('playerID','AB','salary','OBP')]
# 3 Replacement Players
# heltoto01
# berkmala01
# gonzalu01
# since thses players have above avg of OBP with reasonable salary | /Capstone Data Project.R | no_license | nyone00/MoneyBall_Project_R | R | false | false | 1,415 | r | batting <- read.csv('Batting.csv')
head(batting)
str(batting)
head(batting$AB)
head(batting$X2B)
batting$BA <- batting$H/batting$AB
tail(batting$BA,5)
batting$X1B <- batting$H - batting$X2B - batting$X3B - batting$HR
batting$OBP <- (batting$H + batting$BB + batting$HBP)/(batting$AB + batting$BB + batting$HBP + batting$SF)
batting$SLG <- (batting$X1B + 2*batting$X2B + 3*batting$X3B + 4*batting$HR)/batting$AB
str(batting)
sal <- read.csv('Salaries.csv')
batting <- subset(batting, yearID >= 1985)
combo <- merge(x = batting, y= sal,by = c('playerID','yearID'))
summary(combo)
# Analyzing the Lost Players
lost_players <- subset(combo, subset = playerID %in% c('giambja01','damonjo01','saenzol01'))
lost_players <- subset(lost_players, yearID == 2001)
combo <- subset(combo, yearID == 2001)
lost_players[,c('playerID','H','X2B','X3B','HR','OBP','SLG','BA','AB')]
# Replacement Players
library(dplyr)
ggplot(combo, aes(x=OBP,y=salary)) + geom_point(size=2)
combo <- subset(combo,salary < 8000000 & OBP > 0 & AB >= 450)
str(combo)
con1 <- 15*10^6
con2 <- sum(select(lost_players, AB))
con3 <- sum(select(lost_players, OBP))/3
options <- head(arrange(combo,OBP),10)
options[,c('playerID','AB','salary','OBP')]
# 3 Replacement Players
# heltoto01
# berkmala01
# gonzalu01
# since thses players have above avg of OBP with reasonable salary |
pm25data <- readRDS(file = "summarySCC_PM25.rds")
#first run the str() function.
#str(pm25data)
#'data.frame': 6497651 obs. of 6 variables:
#$ fips : chr "09001" "09001" "09001" "09001" ...
#$ SCC : chr "10100401" "10100404" "10100501" "10200401" ...
#$ Pollutant: chr "PM25-PRI" "PM25-PRI" "PM25-PRI" "PM25-PRI" ...
#$ Emissions: num 15.714 234.178 0.128 2.036 0.388 ...
#$ type : chr "POINT" "POINT" "POINT" "POINT" ...
#$ year : int 1999 1999 1999 1999 1999 1999 1999 1999 1999 1999 ...
#Check the integrity of data: number of NA's and number of negative numbers (negative measurements)
mean(is.na(pm25data$Emissions))
#0
sum(pm25data$Emissions[pm25data$Emissions<0], na.rm=TRUE)
#0
#Question 2: Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (fips == 24510) from 1999 to 2008?
#Use the base plotting system to a plot answering this question
#subset the main dataframe to the data regarding only the city of Baltimore
pm25baltimore <- subset(x = pm25data, fips == "24510")
#Asign the total of the sum per year to the variable pm25baltimoretotal
pm25baltimoretotal <- with(data = pm25baltimore, expr = tapply(pm25baltimore$Emissions, pm25baltimore$year, sum, na.rm=TRUE))
#Open the pgn device
png(file = "plot2.png", width = 480, height = 480)
#Plot usign the plot function the years in x and the total pm25 in Baltimore
plot(x = unique(pm25baltimore$year), y = pm25baltimoretotal, pch = 20, col = "red", xlab = "Years", ylab = "Total PM2.5 Emissions in tons")
title("Total PM 2.5 Emissions in Baltimore")
#close the png device
dev.off()
#Answer: Indeed, the Total PM 2.5 Emissions in Baltimore have decreased. | /Plot2.R | no_license | oscarmendozach/ExData_CourseProject2 | R | false | false | 1,675 | r | pm25data <- readRDS(file = "summarySCC_PM25.rds")
#first run the str() function.
#str(pm25data)
#'data.frame': 6497651 obs. of 6 variables:
#$ fips : chr "09001" "09001" "09001" "09001" ...
#$ SCC : chr "10100401" "10100404" "10100501" "10200401" ...
#$ Pollutant: chr "PM25-PRI" "PM25-PRI" "PM25-PRI" "PM25-PRI" ...
#$ Emissions: num 15.714 234.178 0.128 2.036 0.388 ...
#$ type : chr "POINT" "POINT" "POINT" "POINT" ...
#$ year : int 1999 1999 1999 1999 1999 1999 1999 1999 1999 1999 ...
#Check the integrity of data: number of NA's and number of negative numbers (negative measurements)
mean(is.na(pm25data$Emissions))
#0
sum(pm25data$Emissions[pm25data$Emissions<0], na.rm=TRUE)
#0
#Question 2: Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (fips == 24510) from 1999 to 2008?
#Use the base plotting system to a plot answering this question
#subset the main dataframe to the data regarding only the city of Baltimore
pm25baltimore <- subset(x = pm25data, fips == "24510")
#Asign the total of the sum per year to the variable pm25baltimoretotal
pm25baltimoretotal <- with(data = pm25baltimore, expr = tapply(pm25baltimore$Emissions, pm25baltimore$year, sum, na.rm=TRUE))
#Open the pgn device
png(file = "plot2.png", width = 480, height = 480)
#Plot usign the plot function the years in x and the total pm25 in Baltimore
plot(x = unique(pm25baltimore$year), y = pm25baltimoretotal, pch = 20, col = "red", xlab = "Years", ylab = "Total PM2.5 Emissions in tons")
title("Total PM 2.5 Emissions in Baltimore")
#close the png device
dev.off()
#Answer: Indeed, the Total PM 2.5 Emissions in Baltimore have decreased. |
# Simulated data
# Arseniy Khvorov
# Created 2019/11/22
# Last edit 2019/11/22
library(tidyverse)
library(extraDistr)
# Directories to be used lated
data_dir <- "data"
# Functions ===================================================================
# Simulate linear data
sim_lin <- function(nsam, b0, b1, b2, res_sd,
seed = sample.int(.Machine$integer.max, 1)) {
set.seed(seed)
tibble(
x1 = rnorm(nsam, 0, 5),
x2 = rnorm(nsam, 10, 3),
y = rnorm(nsam, b0 + b1 * x1 + b2 * x2, res_sd)
)
}
sim_bin <- function(nsam, b0, b1, b2,
seed = sample.int(.Machine$integer.max, 1)) {
set.seed(seed)
tibble(
x1 = rnorm(nsam, 0, 2),
x2 = rnorm(nsam, 1, 1.5),
probs = 1 - 1 / (1 + exp(b0 + b1 * x1 + b2 * x2)),
y = rbern(nsam, probs)
)
}
# Adds missing values to generated data
add_miss <- function(dat, miss_y, miss_x1, miss_x2,
seed = sample.int(.Machine$integer.max, 1)) {
set.seed(seed)
dat %>%
mutate(
x1_miss = rbern(n(), miss_x1),
x1_obs = if_else(as.logical(x1_miss), NA_real_, x1),
x2_miss = rbern(n(), miss_x2),
x2_obs = if_else(as.logical(x2_miss), NA_real_, x2),
y_miss = rbern(n(), miss_y),
y_obs = if_else(as.logical(y_miss), NA_real_, y),
) %>%
select(-contains("_miss"))
}
# Saves the csv
save_csv <- function(dat, name, folder) {
write_csv(dat, file.path(folder, paste0(name, ".csv")))
}
# Script ======================================================================
lin_nomiss <- sim_lin(300, -3, 2, 5, 3, 20191122) %>% add_miss(0, 0, 0)
save_csv(lin_nomiss, "lin_nonmiss", data_dir)
lin_x1miss <- lin_nomiss %>% add_miss(0, 0.1, 0, 20191122)
save_csv(lin_x1miss, "lin_x1miss", data_dir)
lin_x1x2miss <- lin_nomiss %>% add_miss(0, 0.1, 0.1, 20191122)
save_csv(lin_x1x2miss, "lin_x1x2miss", data_dir)
lin_x1x2ymiss <- lin_nomiss %>% add_miss(0.1, 0.1, 0.1, 20191122)
save_csv(lin_x1x2ymiss, "lin_x1x2ymiss", data_dir)
bin_nomiss <- sim_bin(300, -5, 1.5, 1.5, 20191122) %>% add_miss(0, 0, 0)
save_csv(bin_nomiss, "bin_nonmiss", data_dir)
bin_x1miss <- bin_nomiss %>% add_miss(0, 0.1, 0, 20191122)
save_csv(bin_x1miss, "bin_x1miss", data_dir)
bin_x1x2miss <- bin_nomiss %>% add_miss(0, 0.1, 0.1, 20191122)
save_csv(bin_x1x2miss, "bin_x1x2miss", data_dir)
bin_x1x2ymiss <- bin_nomiss %>% add_miss(0.1, 0.1, 0.1, 20191122)
save_csv(bin_x1x2ymiss, "bin_x1x2ymiss", data_dir)
| /data/data.R | no_license | khvorov45/stan-missing | R | false | false | 2,437 | r | # Simulated data
# Arseniy Khvorov
# Created 2019/11/22
# Last edit 2019/11/22
library(tidyverse)
library(extraDistr)
# Directories to be used lated
data_dir <- "data"
# Functions ===================================================================
# Simulate linear data
sim_lin <- function(nsam, b0, b1, b2, res_sd,
seed = sample.int(.Machine$integer.max, 1)) {
set.seed(seed)
tibble(
x1 = rnorm(nsam, 0, 5),
x2 = rnorm(nsam, 10, 3),
y = rnorm(nsam, b0 + b1 * x1 + b2 * x2, res_sd)
)
}
sim_bin <- function(nsam, b0, b1, b2,
seed = sample.int(.Machine$integer.max, 1)) {
set.seed(seed)
tibble(
x1 = rnorm(nsam, 0, 2),
x2 = rnorm(nsam, 1, 1.5),
probs = 1 - 1 / (1 + exp(b0 + b1 * x1 + b2 * x2)),
y = rbern(nsam, probs)
)
}
# Adds missing values to generated data
add_miss <- function(dat, miss_y, miss_x1, miss_x2,
seed = sample.int(.Machine$integer.max, 1)) {
set.seed(seed)
dat %>%
mutate(
x1_miss = rbern(n(), miss_x1),
x1_obs = if_else(as.logical(x1_miss), NA_real_, x1),
x2_miss = rbern(n(), miss_x2),
x2_obs = if_else(as.logical(x2_miss), NA_real_, x2),
y_miss = rbern(n(), miss_y),
y_obs = if_else(as.logical(y_miss), NA_real_, y),
) %>%
select(-contains("_miss"))
}
# Saves the csv
save_csv <- function(dat, name, folder) {
write_csv(dat, file.path(folder, paste0(name, ".csv")))
}
# Script ======================================================================
lin_nomiss <- sim_lin(300, -3, 2, 5, 3, 20191122) %>% add_miss(0, 0, 0)
save_csv(lin_nomiss, "lin_nonmiss", data_dir)
lin_x1miss <- lin_nomiss %>% add_miss(0, 0.1, 0, 20191122)
save_csv(lin_x1miss, "lin_x1miss", data_dir)
lin_x1x2miss <- lin_nomiss %>% add_miss(0, 0.1, 0.1, 20191122)
save_csv(lin_x1x2miss, "lin_x1x2miss", data_dir)
lin_x1x2ymiss <- lin_nomiss %>% add_miss(0.1, 0.1, 0.1, 20191122)
save_csv(lin_x1x2ymiss, "lin_x1x2ymiss", data_dir)
bin_nomiss <- sim_bin(300, -5, 1.5, 1.5, 20191122) %>% add_miss(0, 0, 0)
save_csv(bin_nomiss, "bin_nonmiss", data_dir)
bin_x1miss <- bin_nomiss %>% add_miss(0, 0.1, 0, 20191122)
save_csv(bin_x1miss, "bin_x1miss", data_dir)
bin_x1x2miss <- bin_nomiss %>% add_miss(0, 0.1, 0.1, 20191122)
save_csv(bin_x1x2miss, "bin_x1x2miss", data_dir)
bin_x1x2ymiss <- bin_nomiss %>% add_miss(0.1, 0.1, 0.1, 20191122)
save_csv(bin_x1x2ymiss, "bin_x1x2ymiss", data_dir)
|
testlist <- list(doy = -1.72131968218895e+83, latitude = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), temp = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 1.86807199752012e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, 2.70002939528686e-16, 2.16562581831091e+161))
result <- do.call(meteor:::ET0_ThornthwaiteWilmott,testlist)
str(result) | /meteor/inst/testfiles/ET0_ThornthwaiteWilmott/AFL_ET0_ThornthwaiteWilmott/ET0_ThornthwaiteWilmott_valgrind_files/1615827607-test.R | no_license | akhikolla/updatedatatype-list3 | R | false | false | 735 | r | testlist <- list(doy = -1.72131968218895e+83, latitude = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), temp = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 1.86807199752012e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, 2.70002939528686e-16, 2.16562581831091e+161))
result <- do.call(meteor:::ET0_ThornthwaiteWilmott,testlist)
str(result) |
area <-function()
{
a = 5
b = 6
c = 7
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return (area)
}
| /data/test_dataset/R/triangle.r | no_license | rakeshamireddy/Automatic-Code-Translation | R | false | false | 110 | r | area <-function()
{
a = 5
b = 6
c = 7
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return (area)
}
|
# Process stress-responsive genes from Gasch et al., 2000 and Nadal-Ribelles et al., 2014
## Gasch et al., 2000
outGasch <- "data/original_data/responsive_Gasch.txt"
# Download data
if (!file.exists(outGasch)){
system2(command = "wget", args = c("http://genome-www.stanford.edu/yeast_stress/data/rawdata/complete_dataset.txt",
"-O",
outGasch))
}
resGasch <- read.delim(outGasch,
stringsAsFactors = F,
check.names = F)
# 1 and 2 are UID and NAME, respectively
# The data contained in all files represents the normalized,
# background-corrected log2 values of the Red/Green ratios measured on the DNA microarrays.
# select only sorbitol samples
osmoResGasch <- resGasch[,c(1, 2,grep("sorbitol", colnames(resGasch)))]
# select sorbitol 15min and write the output
osmoFc = subset(osmoResGasch, ,c(UID,`1M sorbitol - 15 min`))
write.table(osmoFc,
file = "data/derived_data/1M_Sorbitol_15min_FC_Gasch.txt",
quote = F,
row.names = F,
col.names = T,
sep = "\t")
## Tiling arrays, from Mariona directly (Nadal-Ribelles et al., 2014). The data here is in FC.
resTilings <- read.delim("data/original_data/responsive_tilings.txt",
stringsAsFactors = F,
check.names = F)
# Only ORFs and from SteinmetzLab
resTilingsF <- subset(resTilings, source=="SteinmetzLab" & type == "ORF-T")
# Write full FC for 0.4M, 15m
tilingsFc = subset(resTilingsF, , c(name,`wt 15' 0.4M - wt 0`))
write.table(tilingsFc,
"data/derived_data/0.4M_NaCl_FC_15min_responsive_Tilings.txt",
quote = F,
col.names = T,
row.names = F,
sep = "\t") | /scr/previousResponsive.R | no_license | PabloLatorre/OsmoAtlas_StressFeatures_2021 | R | false | false | 1,827 | r | # Process stress-responsive genes from Gasch et al., 2000 and Nadal-Ribelles et al., 2014
## Gasch et al., 2000
outGasch <- "data/original_data/responsive_Gasch.txt"
# Download data
if (!file.exists(outGasch)){
system2(command = "wget", args = c("http://genome-www.stanford.edu/yeast_stress/data/rawdata/complete_dataset.txt",
"-O",
outGasch))
}
resGasch <- read.delim(outGasch,
stringsAsFactors = F,
check.names = F)
# 1 and 2 are UID and NAME, respectively
# The data contained in all files represents the normalized,
# background-corrected log2 values of the Red/Green ratios measured on the DNA microarrays.
# select only sorbitol samples
osmoResGasch <- resGasch[,c(1, 2,grep("sorbitol", colnames(resGasch)))]
# select sorbitol 15min and write the output
osmoFc = subset(osmoResGasch, ,c(UID,`1M sorbitol - 15 min`))
write.table(osmoFc,
file = "data/derived_data/1M_Sorbitol_15min_FC_Gasch.txt",
quote = F,
row.names = F,
col.names = T,
sep = "\t")
## Tiling arrays, from Mariona directly (Nadal-Ribelles et al., 2014). The data here is in FC.
resTilings <- read.delim("data/original_data/responsive_tilings.txt",
stringsAsFactors = F,
check.names = F)
# Only ORFs and from SteinmetzLab
resTilingsF <- subset(resTilings, source=="SteinmetzLab" & type == "ORF-T")
# Write full FC for 0.4M, 15m
tilingsFc = subset(resTilingsF, , c(name,`wt 15' 0.4M - wt 0`))
write.table(tilingsFc,
"data/derived_data/0.4M_NaCl_FC_15min_responsive_Tilings.txt",
quote = F,
col.names = T,
row.names = F,
sep = "\t") |
# numeric
print(class(4))
# integer
print(class(4L))
# logical (TRUE, FALSE, T, F)
print(class(TRUE))
# complex
print(class(1 + 4i))
# character
print(class("Sample"))
# raw when converted into raw bytes
print(class(charToRaw("Sample")))
# You can check an objects class with
# is.integer(), is.numeric(), is.matrix(), is.data.frame(),
# is.logical(), is.vector(), is.character()
# You can convert to different classes with
# as.integer(), as.numeric(),...
# ----- ARITHMETIC OPERATORS -----
sprintf("4 + 5 = %d", 4 + 5)
sprintf("4 - 5 = %d", 4 - 5)
sprintf("4 * 5 = %d", 4 * 5)
sprintf("4 / 5 = %1.3f", 4 / 5)
# Modulus or remainder of division
sprintf("5 %% 4 = %d", 5 %% 4)
# Value raised to the exponent of the next
sprintf("4^2 = %d", 4^2)
# ----- VECTORS -----
# Vectors store multiple values
# Create a vector
numbers = c(3, 2, 0, 1, 8)
numbers
# Get value by index
numbers[1]
# Get the number of items
length(numbers)
# Get the last value
numbers[length(numbers)]
# Get everything but an index
numbers[-1]
# Get the 1st 2 values
numbers[c(1,2)]
# Get the 2nd and 3rd
numbers[2:3]
# Replace a value
numbers[5] = 1
numbers
# Replace the 4th and 5th with 2
numbers[c(4,5)] = 2
numbers
# sort values (decreasing can be TRUE or FALSE)
sort(numbers, decreasing=TRUE)
# Generate a sequence from 1 to 10
oneToTen = 1:10
oneToTen
# Sequence from 3 to 27 adding 3 each time
add3 = seq(from=3, to=27, by=3)
add3
# Create 10 evens from 2
evens = seq(from=2, by=2, length.out=10)
evens
# Find out if a value is in vector
sprintf("4 in evens %s", 4 %in% evens)
# rep() repeats a value/s x, a number of times and
# each defines how many times to repeat each item
rep(x=2, times=5, each=2)
rep(x=c(1,2,3), times=2, each=2)
# ----- RELATIONAL OPERATORS -----
iAmTrue = TRUE
iAmFalse = FALSE
sprintf("4 == 5 : %s", 4 == 5)
sprintf("4 != 5 : %s", 4 != 5)
sprintf("4 > 5 : %s", 4 > 5)
sprintf("4 < 5 : %s", 4 < 5)
sprintf("4 >= 5 : %s", 4 >= 5)
sprintf("4 <= 5 : %s", 4 <= 5)
# Relational operator vector tricks
oneTo20 = c(1:20)
# Create vector of Ts and Fs depending on condition
isEven = oneTo20 %% 2 == 0
isEven
# Create array of evens
justEvens = oneTo20[oneTo20 %% 2 == 0]
justEvens
# ----- LOGICAL OPERATORS -----
cat("TRUE && FALSE = ", T && F, "\n")
cat("TRUE || FALSE = ", T || F, "\n")
cat("!TRUE = ", !T, "\n")
# ----- DECISION MAKING -----
age = 18
# if, else and else if works like other languages
if(age >= 18) {
print("Drive and Vote")
} else if (age >= 16){
print("Drive")
} else {
print("Wait")
}
# ----- SWITCH -----
# Used when you have a limited set of possible values
grade = "Z"
switch(grade,
"A" = print("Great"),
"B" = print("Good"),
"C" = print("Ok"),
"D" = print("Bad"),
"F" = print("Terrible"),
print("No Such Grade"))
# ----- STRINGS -----
str1 = "This is a string"
# String length
nchar(string1)
# You can compare strings where later letters are considered
# greater than
sprintf("Dog > Egg : %s", "Dog" > "Egg")
sprintf("Dog == Egg : %s", "Dog" == "Egg")
# Combine strings and define sperator if any
str2 = paste("Owl", "Bear", sep="")
str2
# Remove bear from the string
substr(x=str2, start=4, stop=7)
# Substitute one string with another
sub(pattern="Owl", replacement="Hawk", x=str2)
# Substitute all matches
gsub(pattern="Egg", replacement="Chicken", x="Egg Egg")
# Split string into vector
strVect = strsplit("A dog ran fast", " ")
strVect
# ----- FACTORS ------
# Factors are used when you have a limited number of values
# that are strings or integers
# Create a factor vector
direction = c("Up", "Down", "Left", "Right", "Left", "Up")
factorDir = factor(direction)
# Check if it's a Factor
is.factor(factorDir)
# A Factor object contains levels which store all possible
# values
levels(x=factorDir)
# You can define your levels and their orders
dow = c("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday")
wDays = c("Tuesday", "Thursday", "Monday")
wdFact = factor(x=wDays, levels=dow, ordered=T)
wdFact
# ----- DATA FRAMES -----
# A Data Frame is a table which contains any type
# of data and an equal amount of data in each column
# Each row is called a record and each column a varaible
# Create customer data frame
custData = data.frame(name=c("Tom", "Sally", "Sue"),
age=c(43, 28, 35),
stringsAsFactors=F)
custData
# Get data in row 1 column 1
custData[1,1]
# Get all data in 1st row
custData[1,1:2]
# Get all ages
custData[1:3, 2]
# Get dimensions
dim(custData)
# Add another record
recordMark = data.frame(name="Mark", age=33)
custData = rbind(custData, recordMark)
custData
# Add a column representing debt
debt = c(0, 25.50, 36, 48.19)
custData = cbind(custData, debt)
custData
# Check if money is owed
owesMoney = custData[custData$debt > 0,]
owesMoney
# ----- LOOPING -----
# Repeat until a condition is met
num = 1
repeat{
print(num)
num = num + 1
if(num > 5){
# Jumps out of loop
break
}
}
# Repeat while condition is true
while(num > 0){
num = num - 1
# next skips the rest of the loop and jumps
# back to the top
if(num %% 2 == 0){
next
}
print(num)
}
# For can be used to cycle through a vector
# or do the same thing a specific number of times
oneTo5 = 1:5
for (i in oneTo5){
print(i)
}
# ----- MATRICES -----
# A Matrix stores values in rows and columns
# Create a Matrix with a single column
matrix1 = matrix(data=c(1,2,3,4))
matrix1
# Create a matrix with defined rows and columns
matrix2 = matrix(data=c(1,2,3,4), nrow=2, ncol=2)
matrix2
# You can also fill by row (You can use T or TRUE)
matrix3 = matrix(data=c(1,2,3,4), nrow=2, ncol=2, byrow=T)
matrix3
# Get a Matrix dimension
dim(matrix3)
# A value at row, column
matrix3[1,2]
# Get a whole row
matrix3[1,]
# Get a whole column
matrix3[,2]
# Combine vectors to make a Matrix
matrix4 = rbind(1:3, 4:6, 7:9)
matrix4
# Get 2nd and 3rd row
matrix4[2:3,]
# Get 2nd and 3rd row by ommitting the 1st
matrix4[-1,]
# Change the first value
matrix4[1,1] = 0
matrix4
# Change the 1st row
matrix4[1,] = c(10,11,12)
matrix4
# ----- MULTI-DIMENSIONAL ARRAYS -----
# You can also create Matrices in layers
# Create a MDA with 2 rows, columns and layers
array1 = array(data=1:8, dim=c(2,2,2))
array1
# Get a value
array1[1,2,2]
# Experiment grabbing values like we did with the Matrix
# Everything is the same
# ----- FUNCTIONS -----
# A function is R is an object that performs operations
# on passed attributes and then returns results
# or simply control back
getSum = function(num1, num2){
return(num1 + num2)
}
sprintf("5 + 6 = %d", getSum(5,6))
# If there is no return the last expression is returned
# You can define default attribute values
getDifference = function(num1=1, num2=1){
num1 - num2
}
sprintf("5 - 6 = %d", getDifference(5,6))
# Return multiple values in a list
makeList = function(theString){
return (strsplit(theString, " "))
}
makeList("Random Words")
# Handling missing arguments
missFunc = function(x){
if(missing(x)){
return("Missing Argument")
} else {
return(x)
}
}
missFunc()
# Excepting variable number of arguments with ellipses
getSumMore = function(...){
numList = list(...)
sum = 0
for(i in numList){
sum = sum + i
}
sum
}
getSumMore(1,2,3,4)
# Disposable / Anonymous Functions are great for
# quick operations like doubling everything in a list
numList = 1:10
dblList = (function(x) x * 2)(numList)
dblList
# Closures are functions created by functions
# Create a function that finds x to a user defined
# power
power = function(exp){
function(x){
x ^ exp
}
}
cubed = power(3)
cubed(2)
cubed(1:5)
# You can store functions in lists
addFunc = list(
add2 = function(x) x + 2,
add3 = function(x) x + 3
)
addFunc$add2(5)
# ----- EXCEPTION HANDLING -----
# Used to gracefully handle errors
# I handle a division with string error
divide = function(num1, num2){
tryCatch(
num1 / num2,
error = function(e) {
if(is.character(num1) || is.character(num2)){
print("Can't Divide with Strings")
}
})
}
divide(10,"5")
# ----- READING WRITING FILES -----
# Create a text file with headers fname lname sex
# and the data in a txt file Use `for missing values
# Save in the same directory as your R file
# Supply the file to read, whether the 1st line is
# headers, what seperates the data, what is being used
# for missing data and false because you don't want to
# convert string vectors to factors
# myPeople is a data frame
myPeople = read.table(file=file.choose(),
header=T, sep=" ",
na.strings="`",
stringsAsFactors=F)
myPeople
# Add another person
donnaRecord = data.frame(fname="Donna",
lname="Heyward",
sex="female")
myPeople = rbind(myPeople, donnaRecord)
# Update a record
myPeople[7,2] = "Smith"
# Update the file by supplying the data.frame,
# the file to write, seperator, na, whether to
# quote strings, whether to include row numbers
write.table(x=myPeople, file=file.choose(),
sep=" ", na="`",
quote=F, row.names=F)
# Get 1st 3 records
head(myPeople, 3)
# Get remaining records
tail(myPeople)
# ----- BASIC PLOTTING -----
# R provides great plotting tools
# Plotting x y coordinates from a matrix
# 1st 5 are x and 2nd 5 are y
xy1 = matrix(data=c(1,2,3,4,5,
1,2,3,4,5), nrow=5, ncol=5)
plot(xy1)
# Draw a line
x2 = c(1,2,3,4,5)
y2 = c(1,2,3,4,5)
plot(x2, y2, type="l")
# Points and lines
plot(x2, y2, type="b")
# Points and lines with no space around points,
# labels, a blue line (Find more with colors())
plot(x2, y2, type="o",
main="My Plot", xlab="x axis", ylab="y axis",
col="steelblue")
# pch (1-25) defines different points
# lty (1-6) defines different lines
# xlim defines the max and min x plotting region
# ylim defines the max and min y plotting region
plot(x2, y2, type="b", pch=2, lty=2,
xlim=c(-8,8), ylim=c(-8,8))
# Multiple plots
plot(x2, y2, type="b")
# Adds straight lines at 2 and 4 coordinates
abline(h=c(2,4), col="red",lty=2)
# Draw a 2 segmented lines with starting and ending x
# and y points
segments(x0=c(2,4), y0=c(2,2), x1=c(2,4), y1=c(4,4),
col="red",lty=2)
# Draw an arrow
arrows(x0=1.5, y0=4.55, x1=2.7, y1=3.3, col="blue")
# Print Text
text(x=1.25, y=4.75, labels="Center")
# Load a built in data.frame
plot(faithful)
# Highlight eruptions with a waiting time greater
# then 4
eruptions4 = with(faithful, faithful[eruptions > 4,])
# Draw specific points
points(eruptions4, col="red", pch=3)
# ----- MATH FUNCTIONS -----
sqrt(x=100)
# Get the power you raise the base to get x
log(x=4, base=2)
# Euler's number 2.718 to the power of x
exp(x=2)
# Sum all vector values
sum(c(1,2,3))
# Find the mean (average)
randD1 = c(1,5,6,7,10,16)
mean(randD1)
# The median (Middle Number or avg of middle 2)
median(randD1)
# Minimum value
min(randD1)
# Maximum value
max(randD1)
# Min and max
range(randD1)
# Rounding
ceiling(4.5)
floor(4.5)
# Cumulatives
cumsum(c(1,2,3))
cumprod(c(1,2,3))
cummax(c(7:9, 4:6, 1:3))
cummin(c(4:6, 1:3, 7:9))
# Generating Random samples
# Flipping a coin 10 times and weigh the probability
# of the next flip based on the previous
sample(0:1,10,replace=T)
sample(1:20,10,replace=T)
# ----- PIE CHARTS -----
# List percentages
foodPref = c(15, 35, 10, 25, 15)
# Labels associated with percentages
foodLabels = c("Spaghetti", "Pizza", "Mac n' Cheese",
"Chicken Nuggets", "Tacos")
# Where to save the image
png(file="child_food_pref.png")
# Colors used for each option
colors = rainbow(length(foodPref))
# Create the chart
pie(foodPref, foodLabels, main="Food Prefs",
col=colors)
# Print legend and cex shrinks the size
legend("topright", foodLabels, cex=0.8,
fill=colors)
# Save the chart
dev.off()
# 3D Pie Chart
# Download package in console install.packages("plotrix")
# Get the library
library(plotrix)
# Name the chart file
png(file="3d_child_food_pref.png")
# Create the chart
pie3D(foodPref, labels=foodLabels, explode=0.1,
start=pi/2, main="Food Prefs", labelcex=0.8)
# Save the chart
dev.off()
# ----- BAR CHARTS -----
# Define the bar chart file
png(file="food_pref_bar_chart.png")
# Plot the chart
barplot(foodPref, names.arg=foodLabels, xlab="Votes",
ylab="Food Options", col=colors,
main="Food Prefs")
# Save File
dev.off()
# ----- REGRESSION ANALYSIS -----
# Used to study a relationship between 2 separate
# pieces of data (What is the relation between batting
# average and RBIS)
# Create relationship model between AVG and RBIs
relation = lm(playerData$RBI~playerData$AVG)
# Create file
png(file="RBI_AVG_Regression.png")
# Plot the chart
plot(playerData$AVG, playerData$RBI,
main="AVG & RBI Regression",
abline(lm(playerData$RBI~playerData$AVG)),
xlab="AVG", ylab="RBIs")
# Save chart
dev.off()
# ----- MULTIPLE REGRESSION -----
# Used to study the impact on one variable from numerous
# others
# Estimate RBIs based on other player stats
playerData2 = mlbPlayers[,c("RBI","AVG","HR","OBP",
"SLG","OPS")]
# Create the relationship model
relation2 = lm(playerData2$RBI ~ playerData2$AVG +
playerData2$HR + playerData2$OBP +
playerData2$SLG + playerData2$OPS)
sprintf("Intercept : %f1.4", coef(relation2)[1])
# How stats effect RBIs
sprintf("AVG : %f1.4", coef(relation2)[2])
sprintf("HR : %f1.4", coef(relation2)[3])
sprintf("OBP : %f1.4", coef(relation2)[4])
sprintf("SLG : %f1.4", coef(relation2)[5])
sprintf("OPS : %f1.4", coef(relation2)[6])
# Calculate expected RBIs based on stats
# Evan Longoria
# RBIs AVG HR OBP SLG OPS
# 86 .261 20 .313 .424 .737
RBIGuess = -5.05 + (372.96 * .261) + (2.56 * 20) +
(-5.41 * .313) + (-167.37 * .424)
RBIGuess | /testing.R | no_license | Henkolicious/DeliveryMan-R | R | false | false | 13,991 | r | # numeric
print(class(4))
# integer
print(class(4L))
# logical (TRUE, FALSE, T, F)
print(class(TRUE))
# complex
print(class(1 + 4i))
# character
print(class("Sample"))
# raw when converted into raw bytes
print(class(charToRaw("Sample")))
# You can check an objects class with
# is.integer(), is.numeric(), is.matrix(), is.data.frame(),
# is.logical(), is.vector(), is.character()
# You can convert to different classes with
# as.integer(), as.numeric(),...
# ----- ARITHMETIC OPERATORS -----
sprintf("4 + 5 = %d", 4 + 5)
sprintf("4 - 5 = %d", 4 - 5)
sprintf("4 * 5 = %d", 4 * 5)
sprintf("4 / 5 = %1.3f", 4 / 5)
# Modulus or remainder of division
sprintf("5 %% 4 = %d", 5 %% 4)
# Value raised to the exponent of the next
sprintf("4^2 = %d", 4^2)
# ----- VECTORS -----
# Vectors store multiple values
# Create a vector
numbers = c(3, 2, 0, 1, 8)
numbers
# Get value by index
numbers[1]
# Get the number of items
length(numbers)
# Get the last value
numbers[length(numbers)]
# Get everything but an index
numbers[-1]
# Get the 1st 2 values
numbers[c(1,2)]
# Get the 2nd and 3rd
numbers[2:3]
# Replace a value
numbers[5] = 1
numbers
# Replace the 4th and 5th with 2
numbers[c(4,5)] = 2
numbers
# sort values (decreasing can be TRUE or FALSE)
sort(numbers, decreasing=TRUE)
# Generate a sequence from 1 to 10
oneToTen = 1:10
oneToTen
# Sequence from 3 to 27 adding 3 each time
add3 = seq(from=3, to=27, by=3)
add3
# Create 10 evens from 2
evens = seq(from=2, by=2, length.out=10)
evens
# Find out if a value is in vector
sprintf("4 in evens %s", 4 %in% evens)
# rep() repeats a value/s x, a number of times and
# each defines how many times to repeat each item
rep(x=2, times=5, each=2)
rep(x=c(1,2,3), times=2, each=2)
# ----- RELATIONAL OPERATORS -----
iAmTrue = TRUE
iAmFalse = FALSE
sprintf("4 == 5 : %s", 4 == 5)
sprintf("4 != 5 : %s", 4 != 5)
sprintf("4 > 5 : %s", 4 > 5)
sprintf("4 < 5 : %s", 4 < 5)
sprintf("4 >= 5 : %s", 4 >= 5)
sprintf("4 <= 5 : %s", 4 <= 5)
# Relational operator vector tricks
oneTo20 = c(1:20)
# Create vector of Ts and Fs depending on condition
isEven = oneTo20 %% 2 == 0
isEven
# Create array of evens
justEvens = oneTo20[oneTo20 %% 2 == 0]
justEvens
# ----- LOGICAL OPERATORS -----
cat("TRUE && FALSE = ", T && F, "\n")
cat("TRUE || FALSE = ", T || F, "\n")
cat("!TRUE = ", !T, "\n")
# ----- DECISION MAKING -----
age = 18
# if, else and else if works like other languages
if(age >= 18) {
print("Drive and Vote")
} else if (age >= 16){
print("Drive")
} else {
print("Wait")
}
# ----- SWITCH -----
# Used when you have a limited set of possible values
grade = "Z"
switch(grade,
"A" = print("Great"),
"B" = print("Good"),
"C" = print("Ok"),
"D" = print("Bad"),
"F" = print("Terrible"),
print("No Such Grade"))
# ----- STRINGS -----
str1 = "This is a string"
# String length
nchar(string1)
# You can compare strings where later letters are considered
# greater than
sprintf("Dog > Egg : %s", "Dog" > "Egg")
sprintf("Dog == Egg : %s", "Dog" == "Egg")
# Combine strings and define sperator if any
str2 = paste("Owl", "Bear", sep="")
str2
# Remove bear from the string
substr(x=str2, start=4, stop=7)
# Substitute one string with another
sub(pattern="Owl", replacement="Hawk", x=str2)
# Substitute all matches
gsub(pattern="Egg", replacement="Chicken", x="Egg Egg")
# Split string into vector
strVect = strsplit("A dog ran fast", " ")
strVect
# ----- FACTORS ------
# Factors are used when you have a limited number of values
# that are strings or integers
# Create a factor vector
direction = c("Up", "Down", "Left", "Right", "Left", "Up")
factorDir = factor(direction)
# Check if it's a Factor
is.factor(factorDir)
# A Factor object contains levels which store all possible
# values
levels(x=factorDir)
# You can define your levels and their orders
dow = c("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday")
wDays = c("Tuesday", "Thursday", "Monday")
wdFact = factor(x=wDays, levels=dow, ordered=T)
wdFact
# ----- DATA FRAMES -----
# A Data Frame is a table which contains any type
# of data and an equal amount of data in each column
# Each row is called a record and each column a varaible
# Create customer data frame
custData = data.frame(name=c("Tom", "Sally", "Sue"),
age=c(43, 28, 35),
stringsAsFactors=F)
custData
# Get data in row 1 column 1
custData[1,1]
# Get all data in 1st row
custData[1,1:2]
# Get all ages
custData[1:3, 2]
# Get dimensions
dim(custData)
# Add another record
recordMark = data.frame(name="Mark", age=33)
custData = rbind(custData, recordMark)
custData
# Add a column representing debt
debt = c(0, 25.50, 36, 48.19)
custData = cbind(custData, debt)
custData
# Check if money is owed
owesMoney = custData[custData$debt > 0,]
owesMoney
# ----- LOOPING -----
# Repeat until a condition is met
num = 1
repeat{
print(num)
num = num + 1
if(num > 5){
# Jumps out of loop
break
}
}
# Repeat while condition is true
while(num > 0){
num = num - 1
# next skips the rest of the loop and jumps
# back to the top
if(num %% 2 == 0){
next
}
print(num)
}
# For can be used to cycle through a vector
# or do the same thing a specific number of times
oneTo5 = 1:5
for (i in oneTo5){
print(i)
}
# ----- MATRICES -----
# A Matrix stores values in rows and columns
# Create a Matrix with a single column
matrix1 = matrix(data=c(1,2,3,4))
matrix1
# Create a matrix with defined rows and columns
matrix2 = matrix(data=c(1,2,3,4), nrow=2, ncol=2)
matrix2
# You can also fill by row (You can use T or TRUE)
matrix3 = matrix(data=c(1,2,3,4), nrow=2, ncol=2, byrow=T)
matrix3
# Get a Matrix dimension
dim(matrix3)
# A value at row, column
matrix3[1,2]
# Get a whole row
matrix3[1,]
# Get a whole column
matrix3[,2]
# Combine vectors to make a Matrix
matrix4 = rbind(1:3, 4:6, 7:9)
matrix4
# Get 2nd and 3rd row
matrix4[2:3,]
# Get 2nd and 3rd row by ommitting the 1st
matrix4[-1,]
# Change the first value
matrix4[1,1] = 0
matrix4
# Change the 1st row
matrix4[1,] = c(10,11,12)
matrix4
# ----- MULTI-DIMENSIONAL ARRAYS -----
# You can also create Matrices in layers
# Create a MDA with 2 rows, columns and layers
array1 = array(data=1:8, dim=c(2,2,2))
array1
# Get a value
array1[1,2,2]
# Experiment grabbing values like we did with the Matrix
# Everything is the same
# ----- FUNCTIONS -----
# A function is R is an object that performs operations
# on passed attributes and then returns results
# or simply control back
getSum = function(num1, num2){
return(num1 + num2)
}
sprintf("5 + 6 = %d", getSum(5,6))
# If there is no return the last expression is returned
# You can define default attribute values
getDifference = function(num1=1, num2=1){
num1 - num2
}
sprintf("5 - 6 = %d", getDifference(5,6))
# Return multiple values in a list
makeList = function(theString){
return (strsplit(theString, " "))
}
makeList("Random Words")
# Handling missing arguments
missFunc = function(x){
if(missing(x)){
return("Missing Argument")
} else {
return(x)
}
}
missFunc()
# Excepting variable number of arguments with ellipses
getSumMore = function(...){
numList = list(...)
sum = 0
for(i in numList){
sum = sum + i
}
sum
}
getSumMore(1,2,3,4)
# Disposable / Anonymous Functions are great for
# quick operations like doubling everything in a list
numList = 1:10
dblList = (function(x) x * 2)(numList)
dblList
# Closures are functions created by functions
# Create a function that finds x to a user defined
# power
power = function(exp){
function(x){
x ^ exp
}
}
cubed = power(3)
cubed(2)
cubed(1:5)
# You can store functions in lists
addFunc = list(
add2 = function(x) x + 2,
add3 = function(x) x + 3
)
addFunc$add2(5)
# ----- EXCEPTION HANDLING -----
# Used to gracefully handle errors
# I handle a division with string error
divide = function(num1, num2){
tryCatch(
num1 / num2,
error = function(e) {
if(is.character(num1) || is.character(num2)){
print("Can't Divide with Strings")
}
})
}
divide(10,"5")
# ----- READING WRITING FILES -----
# Create a text file with headers fname lname sex
# and the data in a txt file Use `for missing values
# Save in the same directory as your R file
# Supply the file to read, whether the 1st line is
# headers, what seperates the data, what is being used
# for missing data and false because you don't want to
# convert string vectors to factors
# myPeople is a data frame
myPeople = read.table(file=file.choose(),
header=T, sep=" ",
na.strings="`",
stringsAsFactors=F)
myPeople
# Add another person
donnaRecord = data.frame(fname="Donna",
lname="Heyward",
sex="female")
myPeople = rbind(myPeople, donnaRecord)
# Update a record
myPeople[7,2] = "Smith"
# Update the file by supplying the data.frame,
# the file to write, seperator, na, whether to
# quote strings, whether to include row numbers
write.table(x=myPeople, file=file.choose(),
sep=" ", na="`",
quote=F, row.names=F)
# Get 1st 3 records
head(myPeople, 3)
# Get remaining records
tail(myPeople)
# ----- BASIC PLOTTING -----
# R provides great plotting tools
# Plotting x y coordinates from a matrix
# 1st 5 are x and 2nd 5 are y
xy1 = matrix(data=c(1,2,3,4,5,
1,2,3,4,5), nrow=5, ncol=5)
plot(xy1)
# Draw a line
x2 = c(1,2,3,4,5)
y2 = c(1,2,3,4,5)
plot(x2, y2, type="l")
# Points and lines
plot(x2, y2, type="b")
# Points and lines with no space around points,
# labels, a blue line (Find more with colors())
plot(x2, y2, type="o",
main="My Plot", xlab="x axis", ylab="y axis",
col="steelblue")
# pch (1-25) defines different points
# lty (1-6) defines different lines
# xlim defines the max and min x plotting region
# ylim defines the max and min y plotting region
plot(x2, y2, type="b", pch=2, lty=2,
xlim=c(-8,8), ylim=c(-8,8))
# Multiple plots
plot(x2, y2, type="b")
# Adds straight lines at 2 and 4 coordinates
abline(h=c(2,4), col="red",lty=2)
# Draw a 2 segmented lines with starting and ending x
# and y points
segments(x0=c(2,4), y0=c(2,2), x1=c(2,4), y1=c(4,4),
col="red",lty=2)
# Draw an arrow
arrows(x0=1.5, y0=4.55, x1=2.7, y1=3.3, col="blue")
# Print Text
text(x=1.25, y=4.75, labels="Center")
# Load a built in data.frame
plot(faithful)
# Highlight eruptions with a waiting time greater
# then 4
eruptions4 = with(faithful, faithful[eruptions > 4,])
# Draw specific points
points(eruptions4, col="red", pch=3)
# ----- MATH FUNCTIONS -----
sqrt(x=100)
# Get the power you raise the base to get x
log(x=4, base=2)
# Euler's number 2.718 to the power of x
exp(x=2)
# Sum all vector values
sum(c(1,2,3))
# Find the mean (average)
randD1 = c(1,5,6,7,10,16)
mean(randD1)
# The median (Middle Number or avg of middle 2)
median(randD1)
# Minimum value
min(randD1)
# Maximum value
max(randD1)
# Min and max
range(randD1)
# Rounding
ceiling(4.5)
floor(4.5)
# Cumulatives
cumsum(c(1,2,3))
cumprod(c(1,2,3))
cummax(c(7:9, 4:6, 1:3))
cummin(c(4:6, 1:3, 7:9))
# Generating Random samples
# Flipping a coin 10 times and weigh the probability
# of the next flip based on the previous
sample(0:1,10,replace=T)
sample(1:20,10,replace=T)
# ----- PIE CHARTS -----
# List percentages
foodPref = c(15, 35, 10, 25, 15)
# Labels associated with percentages
foodLabels = c("Spaghetti", "Pizza", "Mac n' Cheese",
"Chicken Nuggets", "Tacos")
# Where to save the image
png(file="child_food_pref.png")
# Colors used for each option
colors = rainbow(length(foodPref))
# Create the chart
pie(foodPref, foodLabels, main="Food Prefs",
col=colors)
# Print legend and cex shrinks the size
legend("topright", foodLabels, cex=0.8,
fill=colors)
# Save the chart
dev.off()
# 3D Pie Chart
# Download package in console install.packages("plotrix")
# Get the library
library(plotrix)
# Name the chart file
png(file="3d_child_food_pref.png")
# Create the chart
pie3D(foodPref, labels=foodLabels, explode=0.1,
start=pi/2, main="Food Prefs", labelcex=0.8)
# Save the chart
dev.off()
# ----- BAR CHARTS -----
# Define the bar chart file
png(file="food_pref_bar_chart.png")
# Plot the chart
barplot(foodPref, names.arg=foodLabels, xlab="Votes",
ylab="Food Options", col=colors,
main="Food Prefs")
# Save File
dev.off()
# ----- REGRESSION ANALYSIS -----
# Used to study a relationship between 2 separate
# pieces of data (What is the relation between batting
# average and RBIS)
# Create relationship model between AVG and RBIs
relation = lm(playerData$RBI~playerData$AVG)
# Create file
png(file="RBI_AVG_Regression.png")
# Plot the chart
plot(playerData$AVG, playerData$RBI,
main="AVG & RBI Regression",
abline(lm(playerData$RBI~playerData$AVG)),
xlab="AVG", ylab="RBIs")
# Save chart
dev.off()
# ----- MULTIPLE REGRESSION -----
# Used to study the impact on one variable from numerous
# others
# Estimate RBIs based on other player stats
playerData2 = mlbPlayers[,c("RBI","AVG","HR","OBP",
"SLG","OPS")]
# Create the relationship model
relation2 = lm(playerData2$RBI ~ playerData2$AVG +
playerData2$HR + playerData2$OBP +
playerData2$SLG + playerData2$OPS)
sprintf("Intercept : %f1.4", coef(relation2)[1])
# How stats effect RBIs
sprintf("AVG : %f1.4", coef(relation2)[2])
sprintf("HR : %f1.4", coef(relation2)[3])
sprintf("OBP : %f1.4", coef(relation2)[4])
sprintf("SLG : %f1.4", coef(relation2)[5])
sprintf("OPS : %f1.4", coef(relation2)[6])
# Calculate expected RBIs based on stats
# Evan Longoria
# RBIs AVG HR OBP SLG OPS
# 86 .261 20 .313 .424 .737
RBIGuess = -5.05 + (372.96 * .261) + (2.56 * 20) +
(-5.41 * .313) + (-167.37 * .424)
RBIGuess |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/connect_operations.R
\name{connect_delete_hours_of_operation}
\alias{connect_delete_hours_of_operation}
\title{This API is in preview release for Amazon Connect and is subject to
change}
\usage{
connect_delete_hours_of_operation(InstanceId, HoursOfOperationId)
}
\arguments{
\item{InstanceId}{[required] The identifier of the Amazon Connect instance. You can \href{https://docs.aws.amazon.com/connect/latest/adminguide/find-instance-arn.html}{find the instance ID}
in the Amazon Resource Name (ARN) of the instance.}
\item{HoursOfOperationId}{[required] The identifier for the hours of operation.}
}
\description{
This API is in preview release for Amazon Connect and is subject to change.
See \url{https://www.paws-r-sdk.com/docs/connect_delete_hours_of_operation/} for full documentation.
}
\keyword{internal}
| /cran/paws.customer.engagement/man/connect_delete_hours_of_operation.Rd | permissive | paws-r/paws | R | false | true | 892 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/connect_operations.R
\name{connect_delete_hours_of_operation}
\alias{connect_delete_hours_of_operation}
\title{This API is in preview release for Amazon Connect and is subject to
change}
\usage{
connect_delete_hours_of_operation(InstanceId, HoursOfOperationId)
}
\arguments{
\item{InstanceId}{[required] The identifier of the Amazon Connect instance. You can \href{https://docs.aws.amazon.com/connect/latest/adminguide/find-instance-arn.html}{find the instance ID}
in the Amazon Resource Name (ARN) of the instance.}
\item{HoursOfOperationId}{[required] The identifier for the hours of operation.}
}
\description{
This API is in preview release for Amazon Connect and is subject to change.
See \url{https://www.paws-r-sdk.com/docs/connect_delete_hours_of_operation/} for full documentation.
}
\keyword{internal}
|
\name{lacunaritycovariance-package}
\alias{lacunaritycovariance-package}
\alias{lacunaritycovariance}
\docType{package}
\title{
\packageTitle{lacunaritycovariance}
}
\description{
\packageDescription{lacunaritycovariance}
}
\details{
Random closed sets (RACS) (Chiu et al., 2013; Molchanov, 2005) are a well known tool for modelling binary coverage maps.
The package author recently developed new, improved estimators of gliding box lacunarity (GBL) for RACS (Hingee et al., 2017) and described contagion-like properties for RACS (Hingee, 2016).
A forthcoming PhD thesis (Hingee, 2019) will provide additional background for GBL, and for RACS in landscape metrics (which includes contagion).
This package expects RACS observations to be in the form of binary maps either in raster format, or as a set representing foreground with a second set giving the observation window.
If in raster format, the binary map is expected to be a \pkg{spatstat} \code{im} object with pixel values that are only 1 and 0, or are logically valued (i.e. TRUE or FALSE). In both cases the observation window is taken to be the set of pixels with values that are not \code{NA} (i.e. \code{NA} values are considered outside the observation window).
The foreground of the binary map, corresponding to locations within the realisation of the RACS, is taken to be pixels that have value 1 or TRUE.
If the binary map is in set format then a \pkg{spatstat} \code{owin} object is used to represent foreground and a second \code{owin} object is used to represent the observation window.
We will usually denote a RACS as \eqn{\Xi} ('Xi') and a realisation of \eqn{\Xi} observed as a binary map as \eqn{xi}. We will usually denote the observation window as \code{obswin}.
A demonstration converting remotely sensed data into a binary map in \code{im} format can be accessed by typing \code{demo("import_remote_sense_data", package = "lacunaritycovariance")}.
A short example of estimating RACS properties can be found in the vignette \code{estimate_RACS_properties}, which can be accessed with \code{vignette("estimate_RACS_properties")}.
The key functions within this package for estimating properties of RACS are:
\itemize{
\item{\code{\link{coverageprob}}}{ estimates the coverage probability of a stationary RACS}
\item{\code{\link{racscovariance}}}{ estimates the covariance of a stationary RACS}
\item{\code{\link{gbl}}} { estimates the GBL of a stationary RACS}
\item{\code{\link{cencovariance}}} { estimates the centred covariance of a stationary RACS}
\item{\code{\link{paircorr}}} { estimates the pair-correlation of a stationary RACS}
\item{\code{\link{secondorderprops}}} { estimates GBL, covariance and other second order properties of stationary RACS}
\item{\code{\link{contagdiscstate}}} { estimates the disc-state contagion of a stationary RACS}
}
Key functions for simulating RACS are:
\itemize{
\item{\code{\link{rbdd}}}{ simulates a Boolean model with grains that are discs with fixed radius (deterministic discs).}
\item{\code{\link{rbdr}}}{ simulates a Boolean model with grains that are rectangles of fixed size and orientation.}
\item{\code{\link{rbpto}}}{ simulates a Boolean model with grains that of fixed shape and random scale distributed according to a truncated Pareto distribution.}
\item{\code{\link{placegrainsfromlib}}}{ randomly places grains on a set of points (used to simulate Boolean models and other germ-grain models).}
}
}
\author{
\packageAuthor{lacunaritycovariance}
Maintainer: \packageMaintainer{lacunaritycovariance}
}
\references{
Chiu, S.N., Stoyan, D., Kendall, W.S. and Mecke, J. (2013) \emph{Stochastic Geometry and Its Applications}, 3rd ed. Chichester, United Kingdom: John Wiley & Sons.
Hingee, K.L. (2016) Statistics for patch observations. \emph{International Archives of the Photogrammetry, Remote Sensing and Spatial Information Sciences} pp. 235-242. Prague: ISPRS.
Hingee, K.L. (2019) \emph{Spatial Statistics of Random Closed Sets for Earth Observations}. PhD: Perth, Western Australia: University of Western Australia. Submitted.
Hingee K, Baddeley A, Caccetta P, Nair G (2019). Computation of lacunarity from covariance of spatial binary maps. \emph{Journal of Agricultural, Biological and Environmental Statistics}, 24, 264-288. DOI: 10.1007/s13253-019-00351-9.
Molchanov, I.S. (2005) \emph{Theory of Random Sets}. USA: Springer.
}
\keyword{ package }
\keyword{ spatial }
\examples{
# Estimates from the heather data in spatstat
xi_owin <- heather$coarse
xi_owin_obswin <- Frame(heather$coarse)
# Convert binary map to an im object (optional)
xi <- as.im(xi_owin, value = TRUE, na.replace = FALSE)
# Estimate coverage probability, covariance, GBL, and disc-state contagion
cphat <- coverageprob(xi)
cvchat <- racscovariance(xi, estimator = "pickaH")
\donttest{
gblhat <- gbl(xi, seq(0.1, 5, by = 1), estimators = "GBLcc.pickaH")
contagds <- contagdiscstate(Hest(xi), Hest(!xi), p = cphat)
}
# Simulate a Boolean model with grains that are discs of fixed radius:
\donttest{
xi_sim <- rbdd(10, 0.1, owin())
}
}
| /man/lacunaritycovariance-package.Rd | no_license | cran/lacunaritycovariance | R | false | false | 5,062 | rd | \name{lacunaritycovariance-package}
\alias{lacunaritycovariance-package}
\alias{lacunaritycovariance}
\docType{package}
\title{
\packageTitle{lacunaritycovariance}
}
\description{
\packageDescription{lacunaritycovariance}
}
\details{
Random closed sets (RACS) (Chiu et al., 2013; Molchanov, 2005) are a well known tool for modelling binary coverage maps.
The package author recently developed new, improved estimators of gliding box lacunarity (GBL) for RACS (Hingee et al., 2017) and described contagion-like properties for RACS (Hingee, 2016).
A forthcoming PhD thesis (Hingee, 2019) will provide additional background for GBL, and for RACS in landscape metrics (which includes contagion).
This package expects RACS observations to be in the form of binary maps either in raster format, or as a set representing foreground with a second set giving the observation window.
If in raster format, the binary map is expected to be a \pkg{spatstat} \code{im} object with pixel values that are only 1 and 0, or are logically valued (i.e. TRUE or FALSE). In both cases the observation window is taken to be the set of pixels with values that are not \code{NA} (i.e. \code{NA} values are considered outside the observation window).
The foreground of the binary map, corresponding to locations within the realisation of the RACS, is taken to be pixels that have value 1 or TRUE.
If the binary map is in set format then a \pkg{spatstat} \code{owin} object is used to represent foreground and a second \code{owin} object is used to represent the observation window.
We will usually denote a RACS as \eqn{\Xi} ('Xi') and a realisation of \eqn{\Xi} observed as a binary map as \eqn{xi}. We will usually denote the observation window as \code{obswin}.
A demonstration converting remotely sensed data into a binary map in \code{im} format can be accessed by typing \code{demo("import_remote_sense_data", package = "lacunaritycovariance")}.
A short example of estimating RACS properties can be found in the vignette \code{estimate_RACS_properties}, which can be accessed with \code{vignette("estimate_RACS_properties")}.
The key functions within this package for estimating properties of RACS are:
\itemize{
\item{\code{\link{coverageprob}}}{ estimates the coverage probability of a stationary RACS}
\item{\code{\link{racscovariance}}}{ estimates the covariance of a stationary RACS}
\item{\code{\link{gbl}}} { estimates the GBL of a stationary RACS}
\item{\code{\link{cencovariance}}} { estimates the centred covariance of a stationary RACS}
\item{\code{\link{paircorr}}} { estimates the pair-correlation of a stationary RACS}
\item{\code{\link{secondorderprops}}} { estimates GBL, covariance and other second order properties of stationary RACS}
\item{\code{\link{contagdiscstate}}} { estimates the disc-state contagion of a stationary RACS}
}
Key functions for simulating RACS are:
\itemize{
\item{\code{\link{rbdd}}}{ simulates a Boolean model with grains that are discs with fixed radius (deterministic discs).}
\item{\code{\link{rbdr}}}{ simulates a Boolean model with grains that are rectangles of fixed size and orientation.}
\item{\code{\link{rbpto}}}{ simulates a Boolean model with grains that of fixed shape and random scale distributed according to a truncated Pareto distribution.}
\item{\code{\link{placegrainsfromlib}}}{ randomly places grains on a set of points (used to simulate Boolean models and other germ-grain models).}
}
}
\author{
\packageAuthor{lacunaritycovariance}
Maintainer: \packageMaintainer{lacunaritycovariance}
}
\references{
Chiu, S.N., Stoyan, D., Kendall, W.S. and Mecke, J. (2013) \emph{Stochastic Geometry and Its Applications}, 3rd ed. Chichester, United Kingdom: John Wiley & Sons.
Hingee, K.L. (2016) Statistics for patch observations. \emph{International Archives of the Photogrammetry, Remote Sensing and Spatial Information Sciences} pp. 235-242. Prague: ISPRS.
Hingee, K.L. (2019) \emph{Spatial Statistics of Random Closed Sets for Earth Observations}. PhD: Perth, Western Australia: University of Western Australia. Submitted.
Hingee K, Baddeley A, Caccetta P, Nair G (2019). Computation of lacunarity from covariance of spatial binary maps. \emph{Journal of Agricultural, Biological and Environmental Statistics}, 24, 264-288. DOI: 10.1007/s13253-019-00351-9.
Molchanov, I.S. (2005) \emph{Theory of Random Sets}. USA: Springer.
}
\keyword{ package }
\keyword{ spatial }
\examples{
# Estimates from the heather data in spatstat
xi_owin <- heather$coarse
xi_owin_obswin <- Frame(heather$coarse)
# Convert binary map to an im object (optional)
xi <- as.im(xi_owin, value = TRUE, na.replace = FALSE)
# Estimate coverage probability, covariance, GBL, and disc-state contagion
cphat <- coverageprob(xi)
cvchat <- racscovariance(xi, estimator = "pickaH")
\donttest{
gblhat <- gbl(xi, seq(0.1, 5, by = 1), estimators = "GBLcc.pickaH")
contagds <- contagdiscstate(Hest(xi), Hest(!xi), p = cphat)
}
# Simulate a Boolean model with grains that are discs of fixed radius:
\donttest{
xi_sim <- rbdd(10, 0.1, owin())
}
}
|
library(knitr)
opts_chunk$set(cache = FALSE,
tidy = FALSE,
fig.width = 8,
fig.height = 6,
fig.align = "center",
eval.after = "fig.cap",
dpi = 100,
dev = "png",
warning = FALSE,
error = FALSE,
message = FALSE,
dev.args = list(family = "Palatino"))
options(width = 68)
library(latticeExtra)
mycol <- c("#E41A1C", "#377EB8", "#4DAF4A",
"#984EA3", "#FF7F00", "#FFFF33")
# TODO incluir como um objeto do pacote.
# Trellis graphical style.
ps <- list(box.rectangle = list(col = 1, fill = c("gray70")),
box.umbrella = list(col = 1, lty = 1),
dot.symbol = list(col = 1, pch = 19),
dot.line = list(col = "gray50", lty = 3),
plot.symbol = list(col = 1, cex = 0.8),
plot.line = list(col = 1),
plot.polygon = list(col = "gray95"),
superpose.line = list(col = mycol, lty = 1),
superpose.symbol = list(col = mycol, pch = 1),
superpose.region = list(col = mycol, pch = 1),
superpose.polygon = list(col = mycol),
strip.background = list(col = c("gray80", "gray50")),
axis.text = list(cex = 0.8))
trellis.par.set(ps)
# show.settings()
library(captioner)
tbn_ <- captioner(prefix = "Tabela")
fgn_ <- captioner(prefix = "Figura")
tbl_ <- function(label) tbn_(label, display = "cite")
fgl_ <- function(label) fgn_(label, display = "cite")
# Carrega o pacote.
# devtools::load_all()
# if (dir.exists("~/repos/wzRfun")) {
# devtools::load_all("~/repos/wzRfun")
# } else {
# library(wzRfun)
# }
| /vignettes/config/setup.R | no_license | walmes/RDASC | R | false | false | 1,694 | r | library(knitr)
opts_chunk$set(cache = FALSE,
tidy = FALSE,
fig.width = 8,
fig.height = 6,
fig.align = "center",
eval.after = "fig.cap",
dpi = 100,
dev = "png",
warning = FALSE,
error = FALSE,
message = FALSE,
dev.args = list(family = "Palatino"))
options(width = 68)
library(latticeExtra)
mycol <- c("#E41A1C", "#377EB8", "#4DAF4A",
"#984EA3", "#FF7F00", "#FFFF33")
# TODO incluir como um objeto do pacote.
# Trellis graphical style.
ps <- list(box.rectangle = list(col = 1, fill = c("gray70")),
box.umbrella = list(col = 1, lty = 1),
dot.symbol = list(col = 1, pch = 19),
dot.line = list(col = "gray50", lty = 3),
plot.symbol = list(col = 1, cex = 0.8),
plot.line = list(col = 1),
plot.polygon = list(col = "gray95"),
superpose.line = list(col = mycol, lty = 1),
superpose.symbol = list(col = mycol, pch = 1),
superpose.region = list(col = mycol, pch = 1),
superpose.polygon = list(col = mycol),
strip.background = list(col = c("gray80", "gray50")),
axis.text = list(cex = 0.8))
trellis.par.set(ps)
# show.settings()
library(captioner)
tbn_ <- captioner(prefix = "Tabela")
fgn_ <- captioner(prefix = "Figura")
tbl_ <- function(label) tbn_(label, display = "cite")
fgl_ <- function(label) fgn_(label, display = "cite")
# Carrega o pacote.
# devtools::load_all()
# if (dir.exists("~/repos/wzRfun")) {
# devtools::load_all("~/repos/wzRfun")
# } else {
# library(wzRfun)
# }
|
## Lab 10: parameter estimation
## serial interval and R0
## install the packages first
require(flexsurv) # for survivial analysis
require(survival) # for survivial analysis
require(R0); # for estimating R0
####################################################################################
## Part 1. Estimate the serial inteval for SARS using data from Lipsitch et al. 2003
####################################################################################
## read in data
#getwd() ## use "getwd()" to see your current directory and the path
#setwd('YOUR DIRECTORY SAVING THE DATA')
da.sars=read.csv('SARS_serial_intervals.csv')
## each row is 1 case
## 1st column 'tm1' is the lower bound of the interval
## 2nd column 'tm2' is the upper bound of the interval
## they are the same for this dataset, as we only have a single value for each case
## 3rd column 'event' is the The status indicator, normally
## 0=alive, 1=dead. Other choices are TRUE/FALSE (TRUE = death) or 1/2 (2=death).
## here we have event=1 (showing symptoms)
## before doing the analysis, plot the dataset to see how it looks
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
hist(da.sars[,1],breaks=20,col='grey',ylim=c(0,25), main='',
xlab='Serial Interval (days)',ylab='Number of cases')
## to use the survival function in the package (either flexsurv or survival)
## we have to first covert the data to a survival object
## to do so, run the command:
xsurv=Surv(da.sars$tm1,da.sars$tm2,da.sars$event,type='interval')
####################################################
## Fit to the Weibull distribution
####################################################
## First try the survival function, with a Weibull distribution:
surv1=flexsurvreg(xsurv~1,dist='weibull')
surv1; # check the model output
surv1$res; # model parm estimates are save in 'res'
## Calculate the mean based on the estimates
## for Weibull distribution:
surv1.mean=surv1$res['scale','est']*gamma(1+1/surv1$res['shape','est']); # the mean for weibull
surv1.sd=sqrt(surv1$res['scale','est']^2*(gamma(1+2/surv1$res['shape','est'])-(gamma(1+1/surv1$res['shape','est']))^2))
print(paste(round(surv1.mean,1),'+/-',round(surv1.sd,1)))
## compute the model fit:
tm=seq(min(da.sars[,'tm1']),max(da.sars[,'tm2']),by=.2) # more time points than the observed, so we can fill the gap
# compute the number of cases per the survival model
fit1=nrow(da.sars)*dweibull(tm,scale=surv1$res['scale','est'],
shape=surv1$res['shape','est']);
# Super-impose the model fit on the data for comparison
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
hist(da.sars[,1],breaks=20,col='grey',ylim=c(0,25), main='',
xlab='Serial Interval (days)',ylab='Number of cases')
lines(tm,fit1,col='red',lwd=2)
legend('topright',cex=.9,seg.len = .8,
legend=c('Observed','Fitted (Weibull)'),
lty=c(0,1),pch=c(22,NA),lwd=c(NA,2),pt.bg = c('grey',NA),
col=c('grey','red'),bty='n')
####################################################
## Fit to the Exponential distribution
####################################################
surv2=flexsurvreg(xsurv~1,dist='exponential')
surv2; # check the model output
surv2$res; # model parm estimates are save in 'res'
# compute the number of cases per the model
fit2=nrow(da.sars)*dexp(tm,rate=surv2$res['rate','est'])
####################################################
## Fit to the log-normal distribution
####################################################
surv3=flexsurvreg(xsurv~1,dist='lognormal')
surv3; # check the model output
surv3$res; # model parm estimates are save in 'res'
# compute the number of cases per the model
fit3=nrow(da.sars)*dlnorm(tm,meanlog=surv3$res['meanlog','est'],sdlog = surv3$res['sdlog','est'])
####################################################
# Plot results all together:
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
hist(da.sars[,1],breaks=20,col='grey',ylim=c(0,25), main='',xlim=c(0,24),
xlab='Serial Interval (days)',ylab='Number of cases')
lines(tm,fit1,col='red',lwd=2)
lines(tm,fit2,col='blue',lwd=2)
lines(tm,fit3,col='orange',lwd=2)
legend('topright',cex=.9,seg.len = .8,
legend=c('Observed','Fitted (Weibull)','Fitted (Exponential)','Fitted (Log-normal)'),
lty=c(0,1,1,1),pch=c(22,NA,NA,NA),lwd=c(NA,2,2,2),pt.bg = c('grey',NA,NA,NA),
col=c('grey','red','blue','orange'),bty='n')
############################################################
## LQ2: compute the mean, sd, and AIC and compare
############################################################
## Weibull
surv1.mean=surv1$res['scale','est']*gamma(1+1/surv1$res['shape','est']); # the mean for weibull
surv1.sd=sqrt(surv1$res['scale','est']^2*(gamma(1+2/surv1$res['shape','est'])-(gamma(1+1/surv1$res['shape','est']))^2))
surv1.AIC=surv1$AIC
## Exponential:
surv2.mean=1/surv2$res['rate','est'];
surv2.sd=1/surv2$res['rate','est'];
surv2.AIC=surv2$AIC
## Log-normal:
## NOTE: IT IS ON LOG SCALE
surv3.mean=exp(surv3$res['meanlog','est'])
surv3.sd=exp(surv3$res['sdlog','est'])
surv3.AIC=surv3$AIC
####################################################################################
## Part 2: Estimating R0 from the exponential growth phase of the epidemic
####################################################################################
## data: daily incidence during 1918 influenza pandemic in Germany (from 'R0' library)
da.flu=read.csv('data_1918pandemic_Germany.csv')
## Always plot and check the data first
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
plot(da.flu[,1],da.flu[,2],cex=2,xlab='',ylab='Cases')
## cumpute the cumulative incidence using the cumsum function
cumI=cumsum(da.flu[,2]);
# plot and see:
plot(da.flu[,1],log(cumI),cex=2,xlab='',ylab='Log(Cumulative Incidence)')
# Fit the first 7, 14, 21 days:
D=3; # set the generation time to 3 days
Ndays=21; # ADJUST THE NUMBER OF DAYS INCLUDED IN THE FIT HERE
tm1=1:Ndays;
fit1=lm(log(cumI[1:Ndays])~tm1)
summary(fit1)
# compute R0 based on the model-fit
R=1+fit1$coefficients[2]*D
#slope:fit1$coefficients[2]
####################################################################################
## Part 3: R0 - Maximum Likelihood Estimation (MLE)
####################################################################################
data("Germany.1918") # Request the data (it's from the package)
Germany.1918 # print the data to see the structure
# First we need the distribution of generation time (i.e. serial interval)
mGT<-generation.time("gamma", c(2.45, 1.38))
# Maximum Likelihood Estimation using the est.R0.ML function
est.R0.ML(Germany.1918, # the data
mGT, # the distribution of serial interval
begin=1, # the start of the data
end=14, # ADJUST THE NUMBER OF DAYS TO INCLUDE IN THE MODEL HERE
range=c(0.01,50) # the range of possible values to test
)
| /Lab10_parm_est_forstudents.R | no_license | ericdavidmorris/P8477Labs | R | false | false | 6,862 | r | ## Lab 10: parameter estimation
## serial interval and R0
## install the packages first
require(flexsurv) # for survivial analysis
require(survival) # for survivial analysis
require(R0); # for estimating R0
####################################################################################
## Part 1. Estimate the serial inteval for SARS using data from Lipsitch et al. 2003
####################################################################################
## read in data
#getwd() ## use "getwd()" to see your current directory and the path
#setwd('YOUR DIRECTORY SAVING THE DATA')
da.sars=read.csv('SARS_serial_intervals.csv')
## each row is 1 case
## 1st column 'tm1' is the lower bound of the interval
## 2nd column 'tm2' is the upper bound of the interval
## they are the same for this dataset, as we only have a single value for each case
## 3rd column 'event' is the The status indicator, normally
## 0=alive, 1=dead. Other choices are TRUE/FALSE (TRUE = death) or 1/2 (2=death).
## here we have event=1 (showing symptoms)
## before doing the analysis, plot the dataset to see how it looks
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
hist(da.sars[,1],breaks=20,col='grey',ylim=c(0,25), main='',
xlab='Serial Interval (days)',ylab='Number of cases')
## to use the survival function in the package (either flexsurv or survival)
## we have to first covert the data to a survival object
## to do so, run the command:
xsurv=Surv(da.sars$tm1,da.sars$tm2,da.sars$event,type='interval')
####################################################
## Fit to the Weibull distribution
####################################################
## First try the survival function, with a Weibull distribution:
surv1=flexsurvreg(xsurv~1,dist='weibull')
surv1; # check the model output
surv1$res; # model parm estimates are save in 'res'
## Calculate the mean based on the estimates
## for Weibull distribution:
surv1.mean=surv1$res['scale','est']*gamma(1+1/surv1$res['shape','est']); # the mean for weibull
surv1.sd=sqrt(surv1$res['scale','est']^2*(gamma(1+2/surv1$res['shape','est'])-(gamma(1+1/surv1$res['shape','est']))^2))
print(paste(round(surv1.mean,1),'+/-',round(surv1.sd,1)))
## compute the model fit:
tm=seq(min(da.sars[,'tm1']),max(da.sars[,'tm2']),by=.2) # more time points than the observed, so we can fill the gap
# compute the number of cases per the survival model
fit1=nrow(da.sars)*dweibull(tm,scale=surv1$res['scale','est'],
shape=surv1$res['shape','est']);
# Super-impose the model fit on the data for comparison
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
hist(da.sars[,1],breaks=20,col='grey',ylim=c(0,25), main='',
xlab='Serial Interval (days)',ylab='Number of cases')
lines(tm,fit1,col='red',lwd=2)
legend('topright',cex=.9,seg.len = .8,
legend=c('Observed','Fitted (Weibull)'),
lty=c(0,1),pch=c(22,NA),lwd=c(NA,2),pt.bg = c('grey',NA),
col=c('grey','red'),bty='n')
####################################################
## Fit to the Exponential distribution
####################################################
surv2=flexsurvreg(xsurv~1,dist='exponential')
surv2; # check the model output
surv2$res; # model parm estimates are save in 'res'
# compute the number of cases per the model
fit2=nrow(da.sars)*dexp(tm,rate=surv2$res['rate','est'])
####################################################
## Fit to the log-normal distribution
####################################################
surv3=flexsurvreg(xsurv~1,dist='lognormal')
surv3; # check the model output
surv3$res; # model parm estimates are save in 'res'
# compute the number of cases per the model
fit3=nrow(da.sars)*dlnorm(tm,meanlog=surv3$res['meanlog','est'],sdlog = surv3$res['sdlog','est'])
####################################################
# Plot results all together:
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
hist(da.sars[,1],breaks=20,col='grey',ylim=c(0,25), main='',xlim=c(0,24),
xlab='Serial Interval (days)',ylab='Number of cases')
lines(tm,fit1,col='red',lwd=2)
lines(tm,fit2,col='blue',lwd=2)
lines(tm,fit3,col='orange',lwd=2)
legend('topright',cex=.9,seg.len = .8,
legend=c('Observed','Fitted (Weibull)','Fitted (Exponential)','Fitted (Log-normal)'),
lty=c(0,1,1,1),pch=c(22,NA,NA,NA),lwd=c(NA,2,2,2),pt.bg = c('grey',NA,NA,NA),
col=c('grey','red','blue','orange'),bty='n')
############################################################
## LQ2: compute the mean, sd, and AIC and compare
############################################################
## Weibull
surv1.mean=surv1$res['scale','est']*gamma(1+1/surv1$res['shape','est']); # the mean for weibull
surv1.sd=sqrt(surv1$res['scale','est']^2*(gamma(1+2/surv1$res['shape','est'])-(gamma(1+1/surv1$res['shape','est']))^2))
surv1.AIC=surv1$AIC
## Exponential:
surv2.mean=1/surv2$res['rate','est'];
surv2.sd=1/surv2$res['rate','est'];
surv2.AIC=surv2$AIC
## Log-normal:
## NOTE: IT IS ON LOG SCALE
surv3.mean=exp(surv3$res['meanlog','est'])
surv3.sd=exp(surv3$res['sdlog','est'])
surv3.AIC=surv3$AIC
####################################################################################
## Part 2: Estimating R0 from the exponential growth phase of the epidemic
####################################################################################
## data: daily incidence during 1918 influenza pandemic in Germany (from 'R0' library)
da.flu=read.csv('data_1918pandemic_Germany.csv')
## Always plot and check the data first
par(mar=c(3,3,1,1),cex=1.2,mgp=c(1.5,.5,0))
plot(da.flu[,1],da.flu[,2],cex=2,xlab='',ylab='Cases')
## cumpute the cumulative incidence using the cumsum function
cumI=cumsum(da.flu[,2]);
# plot and see:
plot(da.flu[,1],log(cumI),cex=2,xlab='',ylab='Log(Cumulative Incidence)')
# Fit the first 7, 14, 21 days:
D=3; # set the generation time to 3 days
Ndays=21; # ADJUST THE NUMBER OF DAYS INCLUDED IN THE FIT HERE
tm1=1:Ndays;
fit1=lm(log(cumI[1:Ndays])~tm1)
summary(fit1)
# compute R0 based on the model-fit
R=1+fit1$coefficients[2]*D
#slope:fit1$coefficients[2]
####################################################################################
## Part 3: R0 - Maximum Likelihood Estimation (MLE)
####################################################################################
data("Germany.1918") # Request the data (it's from the package)
Germany.1918 # print the data to see the structure
# First we need the distribution of generation time (i.e. serial interval)
mGT<-generation.time("gamma", c(2.45, 1.38))
# Maximum Likelihood Estimation using the est.R0.ML function
est.R0.ML(Germany.1918, # the data
mGT, # the distribution of serial interval
begin=1, # the start of the data
end=14, # ADJUST THE NUMBER OF DAYS TO INCLUDE IN THE MODEL HERE
range=c(0.01,50) # the range of possible values to test
)
|
library(Rsurrogate)
### Name: d_example
### Title: Hypothetical data
### Aliases: d_example
### Keywords: datasets
### ** Examples
data(d_example)
names(d_example)
| /data/genthat_extracted_code/Rsurrogate/examples/d_example.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 171 | r | library(Rsurrogate)
### Name: d_example
### Title: Hypothetical data
### Aliases: d_example
### Keywords: datasets
### ** Examples
data(d_example)
names(d_example)
|
# create shapefile from raster
# from: https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/
library(raster)
path='/scratch/glacio1/cw14910/synthetic_channels_SCRATCH/separate-channels' # also see O:/..
maskF=capture.output( cat(path, "/mask_correct_BamberPstere_100m_GRIGGS_dims.tif", sep=''))
#maskF=capture.output( cat(path, "/mask_correct_BamberPstere_5000m_GRIGGS_dims.tif", sep=''))
mask=raster(maskF)
## amend raster values to 1/0 (land or ice or ice shelf VS. ocean)
## 0 = ocean | 1 = land | 2 = ice | 3 = ice shelf
mask[round(mask)==2]=1
mask[round(mask)==3]=1
mask=round(mask)
## Define the function
gdal_polygonizeR <- function(x, outshape=NULL, gdalformat = 'ESRI Shapefile', pypath=NULL, readpoly=TRUE, quiet=TRUE) {
if (isTRUE(readpoly)) require(rgdal)
if (is.null(pypath)) {
pypath <- Sys.which('gdal_polygonize.py')
}
if (!file.exists(pypath)) stop("Can't find gdal_polygonize.py on your system.")
owd <- getwd()
on.exit(setwd(owd))
setwd(dirname(pypath))
if (!is.null(outshape)) {
outshape <- sub('\\.shp$', '', outshape)
f.exists <- file.exists(paste(outshape, c('shp', 'shx', 'dbf'), sep='.'))
if (any(f.exists))
stop(sprintf('File already exists: %s',
toString(paste(outshape, c('shp', 'shx', 'dbf'),
sep='.')[f.exists])), call.=FALSE)
} else outshape <- tempfile()
if (is(x, 'Raster')) {
require(raster)
writeRaster(x, {f <- tempfile(fileext='.tif')})
rastpath <- normalizePath(f)
} else if (is.character(x)) {
rastpath <- normalizePath(x)
} else stop('x must be a file path (character string), or a Raster object.')
system2('python', args=(sprintf('"%1$s" "%2$s" -f "%3$s" "%4$s.shp"',
pypath, rastpath, gdalformat, outshape)))
if (isTRUE(readpoly)) {
shp <- readOGR(dirname(outshape), layer = basename(outshape), verbose=!quiet)
return(shp)
}
return(NULL)
}
polygonizer <- function(x, outshape=NULL, gdalformat = 'ESRI Shapefile', pypath=NULL, readpoly=TRUE, quietish=TRUE) {
# x: an R Raster layer, or the file path to a raster file recognised by GDAL
# outshape: the path to the output shapefile (if NULL, a temporary file will be created)
# gdalformat: the desired OGR vector format
# pypath: the path to gdal_polygonize.py (if NULL, an attempt will be made to determine the location
# readpoly: should the polygon shapefile be read back into R, and returned by this function? (logical)
# quietish: should (some) messages be suppressed? (logical)
if (isTRUE(readpoly)) require(rgdal)
if (is.null(pypath)) {
pypath <- Sys.which('gdal_polygonize.py')
}
## The line below has been commented:
# if (!file.exists(pypath)) stop("Can't find gdal_polygonize.py on your system.")
owd <- getwd()
on.exit(setwd(owd))
setwd(dirname(pypath))
if (!is.null(outshape)) {
outshape <- sub('\\.shp$', '', outshape)
f.exists <- file.exists(paste(outshape, c('shp', 'shx', 'dbf'), sep='.'))
if (any(f.exists))
stop(sprintf('File already exists: %s',
toString(paste(outshape, c('shp', 'shx', 'dbf'),
sep='.')[f.exists])), call.=FALSE)
} else outshape <- tempfile()
if (is(x, 'Raster')) {
require(raster)
writeRaster(x, {f <- tempfile(fileext='.asc')})
rastpath <- normalizePath(f)
} else if (is.character(x)) {
rastpath <- normalizePath(x)
} else stop('x must be a file path (character string), or a Raster object.')
## Now 'python' has to be substituted by OSGeo4W
#system2('python',
system2('C:\\OSGeo4W64\\OSGeo4W.bat',
args=(sprintf('"%1$s" "%2$s" -f "%3$s" "%4$s.shp"',
pypath, rastpath, gdalformat, outshape)))
if (isTRUE(readpoly)) {
shp <- readOGR(dirname(outshape), layer = basename(outshape), verbose=!quietish)
return(shp)
}
return(NULL)
}
## create polygons
#system.time(p <- gdal_polygonizeR(mask))
outshape=capture.output(cat("/home/cw14910/Github/Greenland_outline/Greenland_mask_outline_100m.shp", sep=''))
#system.time(p <- gdal_polygonizeR(mask, outshape=outshape))
gdal_polygonizeR(mask, outshape=outshape)
| /create_greenland_outline_polygon.r | no_license | albamesp/Greenland_outline | R | false | false | 4,230 | r | # create shapefile from raster
# from: https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/
library(raster)
path='/scratch/glacio1/cw14910/synthetic_channels_SCRATCH/separate-channels' # also see O:/..
maskF=capture.output( cat(path, "/mask_correct_BamberPstere_100m_GRIGGS_dims.tif", sep=''))
#maskF=capture.output( cat(path, "/mask_correct_BamberPstere_5000m_GRIGGS_dims.tif", sep=''))
mask=raster(maskF)
## amend raster values to 1/0 (land or ice or ice shelf VS. ocean)
## 0 = ocean | 1 = land | 2 = ice | 3 = ice shelf
mask[round(mask)==2]=1
mask[round(mask)==3]=1
mask=round(mask)
## Define the function
gdal_polygonizeR <- function(x, outshape=NULL, gdalformat = 'ESRI Shapefile', pypath=NULL, readpoly=TRUE, quiet=TRUE) {
if (isTRUE(readpoly)) require(rgdal)
if (is.null(pypath)) {
pypath <- Sys.which('gdal_polygonize.py')
}
if (!file.exists(pypath)) stop("Can't find gdal_polygonize.py on your system.")
owd <- getwd()
on.exit(setwd(owd))
setwd(dirname(pypath))
if (!is.null(outshape)) {
outshape <- sub('\\.shp$', '', outshape)
f.exists <- file.exists(paste(outshape, c('shp', 'shx', 'dbf'), sep='.'))
if (any(f.exists))
stop(sprintf('File already exists: %s',
toString(paste(outshape, c('shp', 'shx', 'dbf'),
sep='.')[f.exists])), call.=FALSE)
} else outshape <- tempfile()
if (is(x, 'Raster')) {
require(raster)
writeRaster(x, {f <- tempfile(fileext='.tif')})
rastpath <- normalizePath(f)
} else if (is.character(x)) {
rastpath <- normalizePath(x)
} else stop('x must be a file path (character string), or a Raster object.')
system2('python', args=(sprintf('"%1$s" "%2$s" -f "%3$s" "%4$s.shp"',
pypath, rastpath, gdalformat, outshape)))
if (isTRUE(readpoly)) {
shp <- readOGR(dirname(outshape), layer = basename(outshape), verbose=!quiet)
return(shp)
}
return(NULL)
}
polygonizer <- function(x, outshape=NULL, gdalformat = 'ESRI Shapefile', pypath=NULL, readpoly=TRUE, quietish=TRUE) {
# x: an R Raster layer, or the file path to a raster file recognised by GDAL
# outshape: the path to the output shapefile (if NULL, a temporary file will be created)
# gdalformat: the desired OGR vector format
# pypath: the path to gdal_polygonize.py (if NULL, an attempt will be made to determine the location
# readpoly: should the polygon shapefile be read back into R, and returned by this function? (logical)
# quietish: should (some) messages be suppressed? (logical)
if (isTRUE(readpoly)) require(rgdal)
if (is.null(pypath)) {
pypath <- Sys.which('gdal_polygonize.py')
}
## The line below has been commented:
# if (!file.exists(pypath)) stop("Can't find gdal_polygonize.py on your system.")
owd <- getwd()
on.exit(setwd(owd))
setwd(dirname(pypath))
if (!is.null(outshape)) {
outshape <- sub('\\.shp$', '', outshape)
f.exists <- file.exists(paste(outshape, c('shp', 'shx', 'dbf'), sep='.'))
if (any(f.exists))
stop(sprintf('File already exists: %s',
toString(paste(outshape, c('shp', 'shx', 'dbf'),
sep='.')[f.exists])), call.=FALSE)
} else outshape <- tempfile()
if (is(x, 'Raster')) {
require(raster)
writeRaster(x, {f <- tempfile(fileext='.asc')})
rastpath <- normalizePath(f)
} else if (is.character(x)) {
rastpath <- normalizePath(x)
} else stop('x must be a file path (character string), or a Raster object.')
## Now 'python' has to be substituted by OSGeo4W
#system2('python',
system2('C:\\OSGeo4W64\\OSGeo4W.bat',
args=(sprintf('"%1$s" "%2$s" -f "%3$s" "%4$s.shp"',
pypath, rastpath, gdalformat, outshape)))
if (isTRUE(readpoly)) {
shp <- readOGR(dirname(outshape), layer = basename(outshape), verbose=!quietish)
return(shp)
}
return(NULL)
}
## create polygons
#system.time(p <- gdal_polygonizeR(mask))
outshape=capture.output(cat("/home/cw14910/Github/Greenland_outline/Greenland_mask_outline_100m.shp", sep=''))
#system.time(p <- gdal_polygonizeR(mask, outshape=outshape))
gdal_polygonizeR(mask, outshape=outshape)
|
#' @import methods
#' @export
print.onephase<- function(x, ...){
# print-method for one-phase outputs:
cat("\n")
cat("One-phase estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Estimator used:")
cat("\n")
if (x$input$cluster){
cat("One-phase estimator for cluster sampling")
} else {
cat("One-phase estimator")
}
cat("\n", "\n")
# cat("\n")
# cat("Number of areas calculated: ",nrow(sae_obj$estimation))
# cat("\n \n")
}
#' @export
print.twophase<- function(x, ...){
# print-method for all two-phase outputs:
# --------------------------------#
# summary for twophase-smallarea:
if(is(x, "smallarea") & inherits(x, "twophase")){ # if class(x) is c("smallarea", "twophase")
cat("\n")
cat("Two-phase small area estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Estimator used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Small area estimator")}
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator for cluster sampling")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Small area estimator for cluster sampling")}
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator")}
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator for cluster sampling")}
}
cat("\n", "\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n")
cat("Number of small areas calculated: ",nrow(x$estimation))
cat("\n \n")
} # end of smallarea-print
# ------------------------------#
# print for twophase-global:
if(is(x, "global") & inherits(x, "twophase")){# if class(x) is c("global", "twophase")
cat("\n")
cat("Two-phase global estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Method used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
cat("Exhaustive global estimator")
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
cat("Exhaustive global estimator for cluster sampling")
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
cat("Non-exhaustive global estimator")
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
cat("Non-exhaustive global estimator for cluster sampling")
}
# cat("\n", "\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n \n")
}
}# end of print.twophase
#' @export
print.threephase<- function(x, ...){
# print-method for all three-phase outputs:
# --------------------------------#
# summary for threephase-smallarea:
if(is(x, "smallarea") & inherits(x, "threephase")){ # if class(x) is c("smallarea", "threephase")
cat("\n")
cat("Three-phase small area estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Estimator used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Small area estimator")}
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator for cluster sampling")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Small area estimator for cluster sampling")}
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator")}
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator for cluster sampling")}
}
cat("\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n")
cat("Number of small areas calculated: ",nrow(x$estimation))
cat("\n \n")
}# end of smallarea-summary
# --------------------------------#
# summary for threephase-global:
if(is(x, "global") & inherits(x, "threephase")){ # if class(x) is c("global", "threephase")
cat("\n")
cat("Three-phase global estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Method used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
cat("Exhaustive global estimator")
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
cat("Exhaustive global estimator for cluster sampling")
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
cat("Non-exhaustive global estimator")
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
cat("Non-exhaustive global estimator for cluster sampling")
}
# cat("\n", "\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n \n")
}# end of global-print
} # end of print.threephase
#' @method print confint.smallarea
#' @export
print.confint.smallarea<- function(x, ...){
# print-method for small area confint-objects:
cat("\n")
if(x$adjust.method != "none"){
cat(paste(x[["level"]]*100, "% Simultaneous Confidence Intervals for ", class(x)[2] ," small area estimation" ,sep = ""))
} else {
cat(paste(x[["level"]]*100, "% Confidence Intervals for ", class(x)[2] ," small area estimation" ,sep = ""))
}
cat("\n \n")
print(x[[1]])
cat("\n")
if(x$adjust.method != "none"){
cat(paste("Confidence Interval adjustment by method: ", x$adjust.method))
cat("\n \n")
}
}
#' @method print confint.global
#' @export
print.confint.global<- function(x, ...){
# print-method for global confint-objects:
cat("\n")
if(x$adjust.method != "none"){
cat(paste(x[["level"]]*100, "% Simultaneous Confidence Intervals for ", class(x)[2] ," global estimation" ,sep = ""))
} else{
cat(paste(x[["level"]]*100, "% Confidence Intervals for ", class(x)[2] ," global estimation" ,sep = ""))
}
cat("\n \n")
print(x[[1]])
cat("\n")
if(x$adjust.method != "none"){
cat(paste("Confidence Interval adjustment by method: ", x$adjust.method))
cat("\n \n")
}
}
#' @method print esttable
#' @export
print.esttable<- function(x, ...){
# print-method for estable-objects:
print(data.frame(x))
}
| /R/print_methods.R | no_license | AndreasChristianHill/forestinventory | R | false | false | 8,313 | r |
#' @import methods
#' @export
print.onephase<- function(x, ...){
# print-method for one-phase outputs:
cat("\n")
cat("One-phase estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Estimator used:")
cat("\n")
if (x$input$cluster){
cat("One-phase estimator for cluster sampling")
} else {
cat("One-phase estimator")
}
cat("\n", "\n")
# cat("\n")
# cat("Number of areas calculated: ",nrow(sae_obj$estimation))
# cat("\n \n")
}
#' @export
print.twophase<- function(x, ...){
# print-method for all two-phase outputs:
# --------------------------------#
# summary for twophase-smallarea:
if(is(x, "smallarea") & inherits(x, "twophase")){ # if class(x) is c("smallarea", "twophase")
cat("\n")
cat("Two-phase small area estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Estimator used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Small area estimator")}
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator for cluster sampling")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Small area estimator for cluster sampling")}
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator")}
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator for cluster sampling")}
}
cat("\n", "\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n")
cat("Number of small areas calculated: ",nrow(x$estimation))
cat("\n \n")
} # end of smallarea-print
# ------------------------------#
# print for twophase-global:
if(is(x, "global") & inherits(x, "twophase")){# if class(x) is c("global", "twophase")
cat("\n")
cat("Two-phase global estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Method used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
cat("Exhaustive global estimator")
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
cat("Exhaustive global estimator for cluster sampling")
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
cat("Non-exhaustive global estimator")
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
cat("Non-exhaustive global estimator for cluster sampling")
}
# cat("\n", "\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n \n")
}
}# end of print.twophase
#' @export
print.threephase<- function(x, ...){
# print-method for all three-phase outputs:
# --------------------------------#
# summary for threephase-smallarea:
if(is(x, "smallarea") & inherits(x, "threephase")){ # if class(x) is c("smallarea", "threephase")
cat("\n")
cat("Three-phase small area estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Estimator used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Small area estimator")}
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
if(x$input$method == "synth") { cat("Synthetic small area estimator for cluster sampling")}
if(x$input$method == "synth extended") { cat("Extended synthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Small area estimator for cluster sampling")}
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator")}
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
if(x$input$method == "psynth") { cat("Pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psynth extended") { cat("Extended pseudosynthetic small area estimator for cluster sampling")}
if(x$input$method == "psmall"){ cat("Pseudo small area estimator for cluster sampling")}
}
cat("\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n")
cat("Number of small areas calculated: ",nrow(x$estimation))
cat("\n \n")
}# end of smallarea-summary
# --------------------------------#
# summary for threephase-global:
if(is(x, "global") & inherits(x, "threephase")){ # if class(x) is c("global", "threephase")
cat("\n")
cat("Three-phase global estimation")
cat("\n \n")
cat("Call: ")
cat("\n")
print(x$input$call)
cat("\n")
cat("Method used:")
cat("\n")
if (x$input$exhaustive & !x$input$cluster){ # exhaustive & non-cluster
cat("Exhaustive global estimator")
}
if (x$input$exhaustive & x$input$cluster){ # exhaustive & cluster
cat("Exhaustive global estimator for cluster sampling")
}
if (!x$input$exhaustive & !x$input$cluster){ # non-exhaustive & non-cluster
cat("Non-exhaustive global estimator")
}
if (!x$input$exhaustive & x$input$cluster){ # non-exhaustive & cluster
cat("Non-exhaustive global estimator for cluster sampling")
}
# cat("\n", "\n")
# cat("Regression Model:")
# cat("\n")
# print(x$input$formula, showEnv=FALSE)
cat("\n \n")
}# end of global-print
} # end of print.threephase
#' @method print confint.smallarea
#' @export
print.confint.smallarea<- function(x, ...){
# print-method for small area confint-objects:
cat("\n")
if(x$adjust.method != "none"){
cat(paste(x[["level"]]*100, "% Simultaneous Confidence Intervals for ", class(x)[2] ," small area estimation" ,sep = ""))
} else {
cat(paste(x[["level"]]*100, "% Confidence Intervals for ", class(x)[2] ," small area estimation" ,sep = ""))
}
cat("\n \n")
print(x[[1]])
cat("\n")
if(x$adjust.method != "none"){
cat(paste("Confidence Interval adjustment by method: ", x$adjust.method))
cat("\n \n")
}
}
#' @method print confint.global
#' @export
print.confint.global<- function(x, ...){
# print-method for global confint-objects:
cat("\n")
if(x$adjust.method != "none"){
cat(paste(x[["level"]]*100, "% Simultaneous Confidence Intervals for ", class(x)[2] ," global estimation" ,sep = ""))
} else{
cat(paste(x[["level"]]*100, "% Confidence Intervals for ", class(x)[2] ," global estimation" ,sep = ""))
}
cat("\n \n")
print(x[[1]])
cat("\n")
if(x$adjust.method != "none"){
cat(paste("Confidence Interval adjustment by method: ", x$adjust.method))
cat("\n \n")
}
}
#' @method print esttable
#' @export
print.esttable<- function(x, ...){
# print-method for estable-objects:
print(data.frame(x))
}
|
#' Title
#'
#' @param estimaciones
#'
#' @return
#' @export
#'
#' @examples
evaluar_n_cobertura <- function(estimaciones){
resumen <- estimaciones %>%
as_tibble() %>%
group_by(n,candidato) %>%
summarise(cobertura=sum(contiene)/n())
letrero <- resumen %>% summarise(cobertura=median(cobertura))
resumen %>%
ggplot()+
geom_hline(yintercept = .95, linetype=2, color="#1b998b")+
geom_line(aes(group=candidato, x=n,y=cobertura), alpha=.2,color="#f46036")+
geom_line(data=letrero, aes(x=n,y=cobertura), color="#f46036")+
geom_point(data=letrero, aes(x=n,y=cobertura), color="#f46036")+
# annotate(x=min(resumen$n),
# y=min(resumen$cobertura),
# geom = "point",
# color="#f46036",
# hjust="inward")+
# annotate(x=min(resumen$n)*1.01,
# y=min(resumen$cobertura),
# label="cobertura mediana",
# color="#2e294e",
# geom = "text", hjust=0)+
scale_y_continuous(name="Cobertura (%)",
labels = scales::percent_format(),
limits=c(min(c(.7, min(resumen$cobertura))), 1))+
scale_x_continuous(name="Tamaño de la muestra (n)", breaks = unique(resumen$n)) +
theme(panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.background =element_blank(),
)
}
#' Title
#'
#' @param estimaciones
#'
#' @return
#' @export
#'
#' @examples
evaluar_n_error <- function(estimaciones, error=0.01){
g <- estimaciones %>%
group_by(n,muestra) %>%
summarise(max_longitud=max(abs(sesgo))) %>%
ggplot(aes(x=n, y=max_longitud, group=n)) +
scale_y_continuous(name=expression(paste(D[i]," = max{",hat(p[i])-p[i],"}")),
labels = scales::percent_format())+
scale_x_continuous(name="Tamaño de la muestra (n)", breaks = unique(estimaciones$n))+
geom_boxplot(color="#2e294e",fill="#2e294e",alpha=.7)+
geom_hline(yintercept = error, linetype=2, color="#e71d36")+
# labs(
# # title = "Diferencia máxima por muestra entre el estimador puntual y el resultado",
# subtitle = glue::glue("{scales::comma(max(evaluacion$muestra))} muestras"))+
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey70"),
axis.line.x = element_line(),
panel.background = element_blank()
)
}
#' Title
#'
#' @param estimaciones
#' @param precision
#'
#' @return
#' @export
#'
#' @examples
evaluar_n_precision <- function(estimaciones,precision=0.02){
estimaciones %>%
group_by(n,muestra) %>%
summarise(max_longitud=max(longitud_intervalo)) %>%
ggplot(aes(x=n, y=max_longitud, group=n)) +
geom_hline(yintercept = precision, linetype=2, color="#e71d36")+
scale_y_continuous(name=expression(paste(L[i],"=max{",q[.975i]-q[.025i],"}")),
labels = scales::percent_format())+
scale_x_continuous(name="Tamaño de la muestra (n)", breaks = unique(estimaciones$n))+
# labs(
# title = "Longitud máxima por muestra del intervalo de estimación",
# subtitle = glue::glue("{scales::comma(max(evaluacion$muestra))} muestras"))+
geom_boxplot(color="#2e294e",fill="#2e294e",alpha=.7)+
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey70"),
axis.line.x = element_line(),
panel.background = element_blank()
)
}
| /R/evaluar_n.R | permissive | gorantesj/abcr | R | false | false | 3,694 | r | #' Title
#'
#' @param estimaciones
#'
#' @return
#' @export
#'
#' @examples
evaluar_n_cobertura <- function(estimaciones){
resumen <- estimaciones %>%
as_tibble() %>%
group_by(n,candidato) %>%
summarise(cobertura=sum(contiene)/n())
letrero <- resumen %>% summarise(cobertura=median(cobertura))
resumen %>%
ggplot()+
geom_hline(yintercept = .95, linetype=2, color="#1b998b")+
geom_line(aes(group=candidato, x=n,y=cobertura), alpha=.2,color="#f46036")+
geom_line(data=letrero, aes(x=n,y=cobertura), color="#f46036")+
geom_point(data=letrero, aes(x=n,y=cobertura), color="#f46036")+
# annotate(x=min(resumen$n),
# y=min(resumen$cobertura),
# geom = "point",
# color="#f46036",
# hjust="inward")+
# annotate(x=min(resumen$n)*1.01,
# y=min(resumen$cobertura),
# label="cobertura mediana",
# color="#2e294e",
# geom = "text", hjust=0)+
scale_y_continuous(name="Cobertura (%)",
labels = scales::percent_format(),
limits=c(min(c(.7, min(resumen$cobertura))), 1))+
scale_x_continuous(name="Tamaño de la muestra (n)", breaks = unique(resumen$n)) +
theme(panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.background =element_blank(),
)
}
#' Title
#'
#' @param estimaciones
#'
#' @return
#' @export
#'
#' @examples
evaluar_n_error <- function(estimaciones, error=0.01){
g <- estimaciones %>%
group_by(n,muestra) %>%
summarise(max_longitud=max(abs(sesgo))) %>%
ggplot(aes(x=n, y=max_longitud, group=n)) +
scale_y_continuous(name=expression(paste(D[i]," = max{",hat(p[i])-p[i],"}")),
labels = scales::percent_format())+
scale_x_continuous(name="Tamaño de la muestra (n)", breaks = unique(estimaciones$n))+
geom_boxplot(color="#2e294e",fill="#2e294e",alpha=.7)+
geom_hline(yintercept = error, linetype=2, color="#e71d36")+
# labs(
# # title = "Diferencia máxima por muestra entre el estimador puntual y el resultado",
# subtitle = glue::glue("{scales::comma(max(evaluacion$muestra))} muestras"))+
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey70"),
axis.line.x = element_line(),
panel.background = element_blank()
)
}
#' Title
#'
#' @param estimaciones
#' @param precision
#'
#' @return
#' @export
#'
#' @examples
evaluar_n_precision <- function(estimaciones,precision=0.02){
estimaciones %>%
group_by(n,muestra) %>%
summarise(max_longitud=max(longitud_intervalo)) %>%
ggplot(aes(x=n, y=max_longitud, group=n)) +
geom_hline(yintercept = precision, linetype=2, color="#e71d36")+
scale_y_continuous(name=expression(paste(L[i],"=max{",q[.975i]-q[.025i],"}")),
labels = scales::percent_format())+
scale_x_continuous(name="Tamaño de la muestra (n)", breaks = unique(estimaciones$n))+
# labs(
# title = "Longitud máxima por muestra del intervalo de estimación",
# subtitle = glue::glue("{scales::comma(max(evaluacion$muestra))} muestras"))+
geom_boxplot(color="#2e294e",fill="#2e294e",alpha=.7)+
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey70"),
axis.line.x = element_line(),
panel.background = element_blank()
)
}
|
context("ods_query_database")
test_that("Excessively large dataset throws error", {
skip_on_cran()
expect_that(
httptest::with_mock_api({
ods_query_database("http://statistics.gov.scot/sparql",
"PREFIX qb: <http://purl.org/linked-data/cube#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> select ?refArea ?refPeriod ?measureType ?weekend ?value where { ?data qb:dataSet <http://statistics.gov.scot/data/bus-accessibility>. ?data <http://purl.org/linked-data/sdmx/2009/dimension#refArea> ?refArea. ?data <http://purl.org/linked-data/sdmx/2009/dimension#refPeriod> ?refPeriod. ?data <http://purl.org/linked-data/cube#measureType> ?measureType. ?data <http://statistics.gov.scot/def/dimension/weekday/weekend> ?weekend. ?data ?measureType ?value. } order by ?refPeriod ?refArea")
}), throws_error("Requested data is too large for statistics.gov.scot to return. Either add more filters to ods_dataset(), or use get_csv().\n Check ods_structure for categories to filter on."
, fixed = TRUE))
})
| /tests/testthat/test_ods_query_database.R | permissive | DataScienceScotland/opendatascot | R | false | false | 1,142 | r | context("ods_query_database")
test_that("Excessively large dataset throws error", {
skip_on_cran()
expect_that(
httptest::with_mock_api({
ods_query_database("http://statistics.gov.scot/sparql",
"PREFIX qb: <http://purl.org/linked-data/cube#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> select ?refArea ?refPeriod ?measureType ?weekend ?value where { ?data qb:dataSet <http://statistics.gov.scot/data/bus-accessibility>. ?data <http://purl.org/linked-data/sdmx/2009/dimension#refArea> ?refArea. ?data <http://purl.org/linked-data/sdmx/2009/dimension#refPeriod> ?refPeriod. ?data <http://purl.org/linked-data/cube#measureType> ?measureType. ?data <http://statistics.gov.scot/def/dimension/weekday/weekend> ?weekend. ?data ?measureType ?value. } order by ?refPeriod ?refArea")
}), throws_error("Requested data is too large for statistics.gov.scot to return. Either add more filters to ods_dataset(), or use get_csv().\n Check ods_structure for categories to filter on."
, fixed = TRUE))
})
|
# algoritmo para criar aleatoriamente parametros para funcao resposta sigmuiodal de uma especies
# aas variaveis bio1 e bio12
# Anderson A. Eduardo
# 29/jan/2019
makeRespFunc = function(x){
datMatCurrent = x
names(datMatCurrent) = c('lon','lat','bio1','bio12','fSp')
##condicao para nao permitir distribuicoes vazias (i.e. inexistente) ou tbm sobre a Am. Sul toda. Condicao: distribuicao > 1% ou <95% da america do sul
#while( (sum(datMatCurrent[,paste('sp',i,sep='')]) < 0.05*(nrow(datMatCurrent))) | (sum(datMatCurrent[,paste('sp',i,sep='')]) > 0.5*(nrow(datMatCurrent))) ){
#while( (sum(datMatCurrent$fSp, na.rm=TRUE) < 0.05*(nrow(datMatCurrent))) | (sum(datMatCurrent$fSp, na.rm=TRUE) > 0.5*(nrow(datMatCurrent))) ){
##patametros
betaBio1 = runif(n=1, min=0.001, max=1)*sample(x=c(-1,1), size=1) #parametro para cada equacao de cada especie
betaBio12 = runif(n=1, min=0.001, max=1)*sample(x=c(-1,1), size=1) #parametro para cada equacao de cada especie
##
alphaBio1 = runif(n=1, min=quantile(datMatCurrent$bio1, probs=0.25, na.rm=TRUE), max=quantile(datMatCurrent$bio1, probs=0.75, na.rm=TRUE)) #parametro para cada equacao de cada especie
alphaBio12 = runif(n=1, min=quantile(datMatCurrent$bio12, probs=0.25, na.rm=TRUE), max=quantile(datMatCurrent$bio12, probs=0.75, na.rm=TRUE)) #parametro para cada equacao de cada especie
#}
output = data.frame(betaBio1=betaBio1, betaBio12=betaBio12, alphaBio1=alphaBio1, alphaBio12=alphaBio12)
class(output) = "respFuncObject"
return(output)
} | /makeRespFunc.R | no_license | AndersonEduardo/R-Scripts | R | false | false | 1,551 | r | # algoritmo para criar aleatoriamente parametros para funcao resposta sigmuiodal de uma especies
# aas variaveis bio1 e bio12
# Anderson A. Eduardo
# 29/jan/2019
makeRespFunc = function(x){
datMatCurrent = x
names(datMatCurrent) = c('lon','lat','bio1','bio12','fSp')
##condicao para nao permitir distribuicoes vazias (i.e. inexistente) ou tbm sobre a Am. Sul toda. Condicao: distribuicao > 1% ou <95% da america do sul
#while( (sum(datMatCurrent[,paste('sp',i,sep='')]) < 0.05*(nrow(datMatCurrent))) | (sum(datMatCurrent[,paste('sp',i,sep='')]) > 0.5*(nrow(datMatCurrent))) ){
#while( (sum(datMatCurrent$fSp, na.rm=TRUE) < 0.05*(nrow(datMatCurrent))) | (sum(datMatCurrent$fSp, na.rm=TRUE) > 0.5*(nrow(datMatCurrent))) ){
##patametros
betaBio1 = runif(n=1, min=0.001, max=1)*sample(x=c(-1,1), size=1) #parametro para cada equacao de cada especie
betaBio12 = runif(n=1, min=0.001, max=1)*sample(x=c(-1,1), size=1) #parametro para cada equacao de cada especie
##
alphaBio1 = runif(n=1, min=quantile(datMatCurrent$bio1, probs=0.25, na.rm=TRUE), max=quantile(datMatCurrent$bio1, probs=0.75, na.rm=TRUE)) #parametro para cada equacao de cada especie
alphaBio12 = runif(n=1, min=quantile(datMatCurrent$bio12, probs=0.25, na.rm=TRUE), max=quantile(datMatCurrent$bio12, probs=0.75, na.rm=TRUE)) #parametro para cada equacao de cada especie
#}
output = data.frame(betaBio1=betaBio1, betaBio12=betaBio12, alphaBio1=alphaBio1, alphaBio12=alphaBio12)
class(output) = "respFuncObject"
return(output)
} |
#
#======================== Fit Gaussian graphical model
#
#
fitGGM <- function(data = NULL,
S = NULL, n = NULL,
graph,
model = c("covariance", "concentration"), # inverse covariance to be implemented - omega # LSTODO: ??
start = NULL,
ctrlICF = controlICF(),
regularize = FALSE,
regHyperPar = NULL,
verbose = FALSE, ...)
{
call <- match.call()
if ( all(is.null(data), is.null(S)) )
stop("We need some data to estimate a model! Please input 'data' or 'S' and 'n")
if ( is.null(S) & !is.null(data) )
{
data <- data.matrix(data)
n <- nrow(data)
S <- cov(data)*(n-1)/n
} else
if ( is.null(n) & is.null(data) )
stop("You need to provide the sample size 'n' in input if don't supply 'data'")
if(missing(graph))
stop("'graph' argument is missing. Please provide a square symmetric binary adjacency matrix corresponding to the association structure of the graph.")
graph <- as.matrix(graph)
if ( !isSymmetric(graph) )
stop ("'graph' must be a square symmetric binary adjacency matrix")
# if ( any(diag(graph) != 0) )
# stop ("'graph' must be a square symmetric binary adjacency matrix with null diagonal")
# LSTODO: forced to be binary with 0s along the diagonal
diag(graph) <- 0
graph[abs(graph) > 0] <- 1
model <- match.arg(model, choices = eval(formals(fitGGM)$model))
V <- ncol(S)
if ( is.null(colnames(S) ) ) colnames(S) <- paste0("V", 1:V)
varnames <- colnames(S)
S <- as.matrix(S)
nPar <- sum(graph)/2
tot <- choose(V, 2)
#### TODO: regularization for inverse covariance
if ( regularize ) {
if ( is.null(regHyperPar) ) {
psi <- V + 2
S <- if ( V > n ) {
( diag(diag(S)) + S*n ) / (psi + n + V + 1)
} else ( S + S*n ) / (psi + n + V + 1)
} else {
psi <- regHyperPar$psi
if ( !inherits(regHyperPar, "EM") ) S <- ( regHyperPar$scale + S*n ) / (regHyperPar$psi + n + V + 1)
# if the function is not used in 'mixGGM' we compute the regularized S
# if the function is used in 'mixGGM', regularized S is provided in input
}
} else {
psi <- scale <- 0
}
if( min( eigen(S, only.values = TRUE)$val ) < sqrt(.Machine$double.eps)/10 )
stop("Covariance matrix is not positive definite")
# the graph is complete ....................................................
if ( nPar == tot ) {
sigma <- S
if ( regularize ) n <- n + psi + V + 1
lk <- profileloglik(sigma, S, n)
dimnames(sigma) <- dimnames(lk$omega) <- dimnames(graph) <- list(varnames, varnames)
res <- list(sigma = sigma, omega = lk$omega, graph = graph, model = model,
loglik = lk$loglik, nPar = nPar + V, V = V, iter = 1)
class(res) <- "fitGGM"
return(res)
}
# the graph is fully disconnected ..........................................
if ( nPar == 0 ) {
sigma <- diag( diag(S) )
dimnames(sigma) <- list(varnames, varnames)
if ( regularize ) n <- n + psi + V + 1
lk <- profileloglik(sigma, S, n)
dimnames(lk$omega) <- dimnames(graph) <- list(varnames, varnames)
res <- list(sigma = sigma, omega = lk$omega, graph = graph, model = model,
loglik = lk$loglik, nPar = nPar + V, V = V, iter = 1)
class(res) <- "fitGGM"
return(res)
}
# get spouses and non spouses .............................................
# SP <- NS <- SP2 <- list()
# for ( i in 1:V ) {
# SP[[i]] <- which(graph[,i] == 1) - 1
# SP2[[i]] <- ifelse( SP[[i]] > i-1, SP[[i]] - 1, SP[[i]] )
# NS[[i]] <- setdiff(which(graph[,i] == 0), i) - 1
# }
# numSpo <- sapply(SP, length) != 0
# nonTrivial <- which( numSpo != 0 )
# noSpo <- which(numSpo == 0)
# spouse <- findspouse(graph)
# initialization ...........................................................
if ( is.null(start) ) { #### only used for covariance model
sigma <- diag( diag(S) )
# sigma <- S # better?
} else {
temp <- diag(start)
start[graph == 0] <- 0
diag(start) <- temp
sigma <- as.matrix(start)
if ( min( eigen(sigma, only.values = TRUE)$values ) <= 0 )
sigma <- diag( diag(S) )
}
#...........................................................................
# icf ......................................................................
out <- switch(model,
covariance = icf(sigma, S, graph, n,
ctrlICF$tol, ctrlICF$itMax,
verbose, regularize, psi),
concentration = conggm(S, graph, n,
ctrlICF$tol, ctrlICF$itMax,
verbose)
)
dimnames(out$sigma) <- dimnames(out$omega) <- list(varnames, varnames)
res <- list(call = call,
model = model, graph = graph, n = n, V = V,
loglik = out$loglik, iter = out$it, nPar = nPar + V,
sigma = out$sigma, omega = out$omega)
class(res) <- "fitGGM"
return(res)
}
print.fitGGM <- function(x, ...)
{
if(!is.null(cl <- x$call))
{
cat("Call:\n")
dput(cl, control = NULL)
}
cat("\n'fitGGM' object containing:","\n")
print(names(x)[-1])
invisible()
}
# print.fitGGM <- function(x, ...)
# {
# cat("\n")
# txt <- paste(" ", "Gaussian", x$model, "graph model", "\n")
# cat(txt)
# cat(" for", ifelse(x$model == "covariance", "marginal", "conditional"), "independence", "\n")
# sep <- paste0(rep("=", max(nchar(txt)) + 1),
# collapse = "")
# cat(sep, "\n")
# cat( paste0(" ", "N. dependence parameters: ", x$nPar - x$V) )
# cat("\n")
# cat( paste0(" ", "Log-likelihood: ", round(x$loglik, 2), "\n") )
# if ( !is.null(x$penalty) ) {
# cat( paste0(" Penalized log-likelihood: ", round(x$loglikPen, 2), "\n") )
# cat( paste0(" Penalty: ", x$penalty, "\n") )
# cat( paste0(" Search: ", x$search, "\n") )
# }
# }
| /R/fitGGM.R | no_license | lkampoli/mixggm | R | false | false | 6,045 | r | #
#======================== Fit Gaussian graphical model
#
#
fitGGM <- function(data = NULL,
S = NULL, n = NULL,
graph,
model = c("covariance", "concentration"), # inverse covariance to be implemented - omega # LSTODO: ??
start = NULL,
ctrlICF = controlICF(),
regularize = FALSE,
regHyperPar = NULL,
verbose = FALSE, ...)
{
call <- match.call()
if ( all(is.null(data), is.null(S)) )
stop("We need some data to estimate a model! Please input 'data' or 'S' and 'n")
if ( is.null(S) & !is.null(data) )
{
data <- data.matrix(data)
n <- nrow(data)
S <- cov(data)*(n-1)/n
} else
if ( is.null(n) & is.null(data) )
stop("You need to provide the sample size 'n' in input if don't supply 'data'")
if(missing(graph))
stop("'graph' argument is missing. Please provide a square symmetric binary adjacency matrix corresponding to the association structure of the graph.")
graph <- as.matrix(graph)
if ( !isSymmetric(graph) )
stop ("'graph' must be a square symmetric binary adjacency matrix")
# if ( any(diag(graph) != 0) )
# stop ("'graph' must be a square symmetric binary adjacency matrix with null diagonal")
# LSTODO: forced to be binary with 0s along the diagonal
diag(graph) <- 0
graph[abs(graph) > 0] <- 1
model <- match.arg(model, choices = eval(formals(fitGGM)$model))
V <- ncol(S)
if ( is.null(colnames(S) ) ) colnames(S) <- paste0("V", 1:V)
varnames <- colnames(S)
S <- as.matrix(S)
nPar <- sum(graph)/2
tot <- choose(V, 2)
#### TODO: regularization for inverse covariance
if ( regularize ) {
if ( is.null(regHyperPar) ) {
psi <- V + 2
S <- if ( V > n ) {
( diag(diag(S)) + S*n ) / (psi + n + V + 1)
} else ( S + S*n ) / (psi + n + V + 1)
} else {
psi <- regHyperPar$psi
if ( !inherits(regHyperPar, "EM") ) S <- ( regHyperPar$scale + S*n ) / (regHyperPar$psi + n + V + 1)
# if the function is not used in 'mixGGM' we compute the regularized S
# if the function is used in 'mixGGM', regularized S is provided in input
}
} else {
psi <- scale <- 0
}
if( min( eigen(S, only.values = TRUE)$val ) < sqrt(.Machine$double.eps)/10 )
stop("Covariance matrix is not positive definite")
# the graph is complete ....................................................
if ( nPar == tot ) {
sigma <- S
if ( regularize ) n <- n + psi + V + 1
lk <- profileloglik(sigma, S, n)
dimnames(sigma) <- dimnames(lk$omega) <- dimnames(graph) <- list(varnames, varnames)
res <- list(sigma = sigma, omega = lk$omega, graph = graph, model = model,
loglik = lk$loglik, nPar = nPar + V, V = V, iter = 1)
class(res) <- "fitGGM"
return(res)
}
# the graph is fully disconnected ..........................................
if ( nPar == 0 ) {
sigma <- diag( diag(S) )
dimnames(sigma) <- list(varnames, varnames)
if ( regularize ) n <- n + psi + V + 1
lk <- profileloglik(sigma, S, n)
dimnames(lk$omega) <- dimnames(graph) <- list(varnames, varnames)
res <- list(sigma = sigma, omega = lk$omega, graph = graph, model = model,
loglik = lk$loglik, nPar = nPar + V, V = V, iter = 1)
class(res) <- "fitGGM"
return(res)
}
# get spouses and non spouses .............................................
# SP <- NS <- SP2 <- list()
# for ( i in 1:V ) {
# SP[[i]] <- which(graph[,i] == 1) - 1
# SP2[[i]] <- ifelse( SP[[i]] > i-1, SP[[i]] - 1, SP[[i]] )
# NS[[i]] <- setdiff(which(graph[,i] == 0), i) - 1
# }
# numSpo <- sapply(SP, length) != 0
# nonTrivial <- which( numSpo != 0 )
# noSpo <- which(numSpo == 0)
# spouse <- findspouse(graph)
# initialization ...........................................................
if ( is.null(start) ) { #### only used for covariance model
sigma <- diag( diag(S) )
# sigma <- S # better?
} else {
temp <- diag(start)
start[graph == 0] <- 0
diag(start) <- temp
sigma <- as.matrix(start)
if ( min( eigen(sigma, only.values = TRUE)$values ) <= 0 )
sigma <- diag( diag(S) )
}
#...........................................................................
# icf ......................................................................
out <- switch(model,
covariance = icf(sigma, S, graph, n,
ctrlICF$tol, ctrlICF$itMax,
verbose, regularize, psi),
concentration = conggm(S, graph, n,
ctrlICF$tol, ctrlICF$itMax,
verbose)
)
dimnames(out$sigma) <- dimnames(out$omega) <- list(varnames, varnames)
res <- list(call = call,
model = model, graph = graph, n = n, V = V,
loglik = out$loglik, iter = out$it, nPar = nPar + V,
sigma = out$sigma, omega = out$omega)
class(res) <- "fitGGM"
return(res)
}
print.fitGGM <- function(x, ...)
{
if(!is.null(cl <- x$call))
{
cat("Call:\n")
dput(cl, control = NULL)
}
cat("\n'fitGGM' object containing:","\n")
print(names(x)[-1])
invisible()
}
# print.fitGGM <- function(x, ...)
# {
# cat("\n")
# txt <- paste(" ", "Gaussian", x$model, "graph model", "\n")
# cat(txt)
# cat(" for", ifelse(x$model == "covariance", "marginal", "conditional"), "independence", "\n")
# sep <- paste0(rep("=", max(nchar(txt)) + 1),
# collapse = "")
# cat(sep, "\n")
# cat( paste0(" ", "N. dependence parameters: ", x$nPar - x$V) )
# cat("\n")
# cat( paste0(" ", "Log-likelihood: ", round(x$loglik, 2), "\n") )
# if ( !is.null(x$penalty) ) {
# cat( paste0(" Penalized log-likelihood: ", round(x$loglikPen, 2), "\n") )
# cat( paste0(" Penalty: ", x$penalty, "\n") )
# cat( paste0(" Search: ", x$search, "\n") )
# }
# }
|
############################################################################################################
################### Coursera - Getting and Cleaning Data Assignment ########################################
############################################################################################################
# Clear R-Environment of all variables
rm(list = setdiff(ls(), lsf.str()))
# load required libraries
library(reshape2)
# read data
sub_train <- read.table("train\subject_train.txt")
sub_test <- read.table("test\subject_test.txt")
X_train <- read.table("train\X_train.txt")
X_test <- read.table("test\X_test.txt")
y_train <- read.table("train\y_train.txt")
y_test <- read.table("test\y_test.txt")
# add column name for subject files
names(sub_train) <- "subjectID"
names(sub_test) <- "subjectID"
# add column name for label files
names(y_train) <- "activity"
names(y_test) <- "activity"
# add column names for measurement files
featureNames <- read.table("features.txt")
names(X_train) <- featureNames$V2
names(X_test) <- featureNames$V2
# combine files into one dataset
traindata <- cbind(sub_train, y_train, X_train)
testdata <- cbind(sub_test, y_test, X_test)
combined <- rbind(traindata, testdata)
# find columns with "mean()" or "std()"
meanstdcols <- grepl("mean\\(\\)", names(combined)) |
grepl("std\\(\\)", names(combined))
# keep the subjectID and activity columns
meanstdcols[1:2] <- TRUE
# remove unwanted columns
combined <- combined[, meanstdcols]
# adding activity labels
combined$activity <- factor(combined$activity, labels=c("Walking","Walking Upstairs", "Walking Downstairs", "Sitting", "Standing", "Laying"))
# creating tidy data set
melted <- melt(combined, id=c("subjectID","activity"))
tidy <- dcast(melted, subjectID+activity ~ variable, mean)
# writing tidy data set to a file
write.table(tidy, "tidy.txt", sep="\t", row.names=FALSE)
| /run_analysis.r | no_license | sunswam/GettingCleaningData-Coursera | R | false | false | 1,900 | r |
############################################################################################################
################### Coursera - Getting and Cleaning Data Assignment ########################################
############################################################################################################
# Clear R-Environment of all variables
rm(list = setdiff(ls(), lsf.str()))
# load required libraries
library(reshape2)
# read data
sub_train <- read.table("train\subject_train.txt")
sub_test <- read.table("test\subject_test.txt")
X_train <- read.table("train\X_train.txt")
X_test <- read.table("test\X_test.txt")
y_train <- read.table("train\y_train.txt")
y_test <- read.table("test\y_test.txt")
# add column name for subject files
names(sub_train) <- "subjectID"
names(sub_test) <- "subjectID"
# add column name for label files
names(y_train) <- "activity"
names(y_test) <- "activity"
# add column names for measurement files
featureNames <- read.table("features.txt")
names(X_train) <- featureNames$V2
names(X_test) <- featureNames$V2
# combine files into one dataset
traindata <- cbind(sub_train, y_train, X_train)
testdata <- cbind(sub_test, y_test, X_test)
combined <- rbind(traindata, testdata)
# find columns with "mean()" or "std()"
meanstdcols <- grepl("mean\\(\\)", names(combined)) |
grepl("std\\(\\)", names(combined))
# keep the subjectID and activity columns
meanstdcols[1:2] <- TRUE
# remove unwanted columns
combined <- combined[, meanstdcols]
# adding activity labels
combined$activity <- factor(combined$activity, labels=c("Walking","Walking Upstairs", "Walking Downstairs", "Sitting", "Standing", "Laying"))
# creating tidy data set
melted <- melt(combined, id=c("subjectID","activity"))
tidy <- dcast(melted, subjectID+activity ~ variable, mean)
# writing tidy data set to a file
write.table(tidy, "tidy.txt", sep="\t", row.names=FALSE)
|
#let's start with a 5 night quarantine intervention.
#how do we calculate the probability that a random case will get into the community?
#probability of a case being infectious on release
#probability of a case infecting another person in quarantine
#probability of a case infecting another person on the aeroplane
verbose <- TRUE
printv <-function(to_print){
if(verbose){
cat(to_print)
cat("\n")
}
}
run_sim <- function(
pcr_test_list_to_avoid_boarding = list(list(-2,-3)),
pcr_test_to_remain_in_quarantine = c(5),
quarantine_release_day = 6,
temp_and_symptoms_test_to_avoid_boarding = c(0),
p_flight_infection_risk_per_case_contact = 0.005*.15, #with mask wearing
quarantine_contacts_per_day=2,
set_density_at_1_per_day = FALSE
){
#let's start a list of all cases started in the prior 14 days from day 0
case_list_day_begin = c()
case_list_weight = c()
#all these should start from day 0 the day of infection
#not infectious on 0th day of infection.
p_pcr_detectable_by_day <- c(0,0, 0,5, 40, 65, 75, 80, 85, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, 62, 60, 58,rep(0,20))/100
p_symptomatic_by_day <- plnorm(0:40, 1.621,0.418)*0.4
p_infection_remains_infectious_by_day <<- c(0,rep(1,14),0.75,0.5,0.25,rep(0,30))
get_p_case_remains_infectious <- function(case_list_weight,case_list_day_begin,t){
#now calculate the odds that each current case remains infectious
if(length(case_list_weight)>0){
p_case_remains_infectious = vector("numeric",length(case_list_weight))
for (case_n in 1:length(case_list_weight)){
#case_n<-1
case_n_days_ago = t-case_list_day_begin[case_n]
p_case_remains_infectious[case_n] = p_infection_remains_infectious_by_day[case_n_days_ago+1]
}
}
return(p_case_remains_infectious)
}
sim_days_before_flight_start = 20
days_to_measure <- sim_days_before_flight_start+quarantine_release_day
community_exposure_by_day <- vector("numeric",days_to_measure)
proportional_infections_by_day <- vector("numeric",days_to_measure)
p_infectious_in_pipeline_by_day <- vector("numeric",days_to_measure)
#duration_to_flight
#spawn one case from t-13 onward to t=0
for (t in 1:days_to_measure){
# by convention t will be 20 days before flight.
duration_to_flight <- t-sim_days_before_flight_start
#flight occurs on day 14 then
printv("\n\n")
printv(paste("days after flight:",as.character(duration_to_flight)))
#create one infection per day constant, if we're pre-flight
if(duration_to_flight==0){ #include equal infections of day of flight
warning("excluded day of flight from infections. No special accounting for airport risk occurs.")
}
if(duration_to_flight<0){ #exclude day of flight
#if(duration_to_flight<=0){ #include day of flight
case_list_day_begin[length(case_list_day_begin) + 1] <- t
if(set_density_at_1_per_day){ #just for debugging
proportional_infections_by_day[t] <- 1
}else{
proportional_infections_by_day[t] <- 1/sum(p_infection_remains_infectious_by_day)
#we add cases using this very specific and odd figure so that we're scaling to 1 infectious case over the whole period
#that way we can talk about percentage of infectious cases
#I think we need to think about this a little bit more....
#was easier when it was a uniform distribution.
}
case_list_weight[length(case_list_weight) + 1] <- proportional_infections_by_day[t]
#this weight should really be divided by the sum of our "remains infectious" value
#but we'll leave that to start.
}
#mark the cases by the days since they occured
case_list_days_since_case <- t - case_list_day_begin
p_case_remains_infectious <- get_p_case_remains_infectious(case_list_weight,case_list_day_begin,t)
#at t=0 there is flight spread risk.
#each case, proportionally to its current infectiousness, can result in another case being generated
#that begins on the day of flight.
if(duration_to_flight==0){
# case_list_weight[t] <- case_list_weight[t]
# probably will deprecate this at some point when we go probabilistic
# for now it's useful to count the probability
# probably will deprecate this at some point when we go probabilistic
# case WEIGHT (the odds this is still in pipeline) is important
# case INFECTIOUSNESS is also important)
printv("flying")
num_contacts_on_flight=16
infectious_cases_on_flight <- sum(case_list_weight*p_case_remains_infectious)
#probability of infection per case
infectiousness_on_flight_per_case = p_flight_infection_risk_per_case_contact*num_contacts_on_flight
#I want to add an extra value to this series rather than
#augment the one already on there
#because strictly speaking each item in the case_list series is one case,
#weighted down by case_list_weight
#not necessarily a days worth of cases
case_list_day_begin[length(case_list_day_begin) + 1] <- t
proportional_infections_by_day[t] <- infectiousness_on_flight_per_case
case_list_weight[length(case_list_weight) + 1] <- infectiousness_on_flight_per_case
}
#OK great, we've got to the border
#now we want to know the probability of infection within quarantine each day
if(duration_to_flight>0){
# case WEIGHT (the odds this is still in pipeline) is important
# case INFECTIOUSNESS is also important)
#num_contacts_per_case_per_day=2.5
infectious_cases_in_environment <- sum(case_list_weight*p_case_remains_infectious)
#probability of infection per case
infectiousness_per_contact = 0.0036
#calibrated to produce a roughly 0.02% difference in success when moving from 5 contacts a day to 0
# as in Steyn, Binny, Hendy
expected_infections_today <-infectious_cases_in_environment*infectiousness_per_contact*quarantine_contacts_per_day
#I want to add an extra value to this series rather than
#augment the one already on there
#because strictly speaking each item in the case_list series is one case,
#weighted down by case_list_weight
#not necessarily a days worth of cases
case_list_day_begin[length(case_list_day_begin) + 1] <- t
case_list_weight[length(case_list_weight) + 1] <- expected_infections_today
proportional_infections_by_day[t] <- expected_infections_today
}
#mark the cases by the days since they occured again
case_list_days_since_case <- t - case_list_day_begin
p_case_remains_infectious <- get_p_case_remains_infectious(case_list_weight,case_list_day_begin,t)
current_infectious_cases <- case_list_weight*p_case_remains_infectious
current_infectious_cases_sum <- sum(current_infectious_cases)
if(duration_to_flight>0){
#OK. What's the odds of community exposure?
#breach odds per case should be something like
#breach odds are calculated from
breach_odds_per_day_with_30_cases <- exp(mean(c(log(1/30),log(12/9000))))
breach_odds_per_case <- breach_odds_per_day_with_30_cases/30
#this is the odds of any individual breaking out on any day
#we need the current
expected_quarantine_breaches_today <- current_infectious_cases_sum*breach_odds_per_case
community_exposure_by_day[t]=+expected_quarantine_breaches_today
}
#then the next day, we're gonna let the travelers out.
if(duration_to_flight==quarantine_release_day){
printv("releasing all travellers who haven't been tested positive.")
printv(paste("There are",current_infectious_cases_sum,"cases being released."))
#this is the probability that each case is detected and removed
#we now adjust our weights
community_exposure_by_day[t]=+current_infectious_cases_sum
printv("cases detected are removed and results shown on next day")
}
#PCR tests
for (pcr_test_set_to_avoid_boarding in pcr_test_list_to_avoid_boarding){
#pcr_test_set_to_avoid_boarding<-pcr_test_list_to_avoid_boarding[[1]]
#we have a specific set of tests
#how many tests are there?
test_possibilities <- length(pcr_test_set_to_avoid_boarding)
test_set_max_day <- max(unlist(pcr_test_set_to_avoid_boarding))
#what we want to do is apply equally to the case list weight based on the LAST day
if(duration_to_flight==test_set_max_day){
printv("doing PCR test...")
#if we're on the last day then iterate through each of the days to build a combined probability of
#either test detecting cases
#we assume that each test has an equal probability of being run
test_set_relative_to_now <- unlist(pcr_test_set_to_avoid_boarding) - test_set_max_day
test_set_combined_prob <- rep(0,length(case_list_days_since_case))
for (test_relative in test_set_relative_to_now){
test_day_prob <- c(p_pcr_detectable_by_day[case_list_days_since_case+1+test_relative],rep(0,-test_relative))
test_set_combined_prob= test_set_combined_prob + test_day_prob/test_possibilities
}
p_case_list_detected <- test_set_combined_prob#p_pcr_detectable_by_day[case_list_days_since_case+1]*(1/test_possibilities)
printv(p_case_list_detected)
# printv("\n")
cases_detected_by_tests <- case_list_weight*p_case_list_detected
case_list_weight <- case_list_weight - cases_detected_by_tests
#so the cases detected are the reciprocal of this????
print("cases detected are removed and results shown on next day")
}
#now probabilistically a PCR test on this day, the result of which will be to avoid boarding.
# if(duration_to_flight %in% pcr_test_set_to_avoid_boarding){
# print("doing PCR test...")
# warning("can't calculate PCR test this way because you're effectively multiplying the two probabilities together. They need to be added or averaged instead.")
# # better way is to find the LAST day in the test set
# # then run it on there but stagger the probability detections and work on that basis.
# p_case_list_detected <- p_pcr_detectable_by_day[case_list_days_since_case+1]*(1/test_possibilities)
# print(p_case_list_detected)
# print(t)
# print(duration_to_flight)
# #weighted to account for the probabiliyt of actually running the test
# #this is the probability that each case is detected and removed
# #we now adjust our weights
# case_list_weight <- case_list_weight*(1-p_case_list_detected)
# print("cases detected are removed and results shown on next day")
#
# }
}
#now we do a temperature test if there is one on this day.
if(duration_to_flight %in% temp_and_symptoms_test_to_avoid_boarding){
printv("doing temperature and symptom screening...")
p_case_list_detected <- p_symptomatic_by_day[case_list_days_since_case+1]
#this is the probability that each case is detected and removed
#we now adjust our weights
case_list_weight <- case_list_weight*(1-p_case_list_detected)
printv("cases detected are removed and results shown on next day")
}
#now we do a PCR test within the quarantine if there is one on this day.
if(duration_to_flight %in% pcr_test_to_remain_in_quarantine){
printv("doing PCR test to hold patients in quarantine...")
p_case_list_detected <- p_pcr_detectable_by_day[case_list_days_since_case+1]
#this is the probability that each case is detected and removed
#we now adjust our weights
case_list_weight <- case_list_weight*(1-p_case_list_detected)
printv("cases detected are removed and results shown on next day")
}else if (duration_to_flight>0){
warning("not counting daily health checks. But to do that we need to keep track of a specific subpopulation of the infected population who are symptomatic")
printv("doing managed isolation health check...")
#we remove 1/3 of the symptomatic patients from both the symptomatic pool and the total pool
#p_case_list_detected <- p_symptomatic_by_day[case_list_days_since_case+1]*1/3
#we'd need a "cases by day symptomatic" here.
#cases_by_day_symptomatic[case_list_days_since_case+1] = p_symptomatic_by_day[case_list_days_since_case+1]- p_case_list_detected
#round(p_case_list_detected,2)
round(p_symptomatic_by_day,2)
# #if there is no PCR on a given day,
# #then patients who are symptomatic have 33% odds of being detected during an interview
# #I don't think we can do this because we haven't actually modeled separate populations
# #of people who are symptomatic and asymptomatic
# #we would need to actually store a list of asymptomatic patients
# p_case_list_detected <- p_symptomatic_by_day[case_list_days_since_case+1]*1/3
# case_list_weight <- case_list_weight*(1-p_case_list_detected)
}
#now look at hte odds cases remain infectious and undetected
if(length(case_list_day_begin)>0){
printv("Case beginning by case:")
printv(round(case_list_day_begin,3))
printv("Case infectiousness by case:")
printv(round(current_infectious_cases,3))
printv("total infectious cases in the journey at the moment:")
printv(current_infectious_cases_sum)
printv("expected community exposure today:")
printv(community_exposure_by_day[t])
# print("log community exposure, by day, to date:")
# print(log(community_exposure_by_day))
}
#the below would be useful to visualize infectiousness from each day.
# data.frame("day_of_infection" = case_list_day_begin-sim_days_before_flight_start,
# "p_remains_in_pipeline" = case_list_weight,
# "p_remains_infectious" = p_case_remains_infectious)
p_infectious_in_pipeline_by_day[t] <- sum(current_infectious_cases)
}
return(list(
"data_by_infection_source" = data.frame(
"day_of_infection" = case_list_day_begin-sim_days_before_flight_start,
"cases_undetected" = case_list_weight,
"p_case_remains_infectious"=p_case_remains_infectious,
"p_remains_infectious_and_in_pipeline" = current_infectious_cases),
"data_by_day" = data.frame(
"days_past_flight"= 1:days_to_measure - sim_days_before_flight_start,
"p_community_exposure_by_day" = community_exposure_by_day,
"proportional_infections_by_day" = proportional_infections_by_day,
"p_infectious_in_pipeline_by_day" = p_infectious_in_pipeline_by_day
),
"total_community_exposure_by_day" = sum(community_exposure_by_day)
)
)
}
library(ggplot2)
# df_result <- run_sim()
# df_result$simulation <- c("with temp check")
# df_result2 <- run_sim(temp_and_symptoms_test_to_avoid_boarding=c())
# df_result2$simulation <- c("no temp check")
# ggplot(rbind(df_result,df_result2),
# aes(x=day_of_infection,y=p_remains_in_pipeline*p_remains_infectious,
# group=simulation,color=simulation))+geom_line()+
# labs(y="P(risk)",
# title="Probability density of case risk over the period by day of original infection")
# #later we may incorporate prevalence into this
# #and apply interventions along the way
#
# ####MATCHING STEYN, BINNY, HENDY
# #14 day quarantine
# verbose=TRUE
# quarantine_length <- 14
# sim_result <- run_sim(
# pcr_test_list_to_avoid_boarding = list(list(-2,-3)),
# pcr_test_to_remain_in_quarantine = c(3,12),
# quarantine_release_day = quarantine_length,
# temp_and_symptoms_test_to_avoid_boarding = c(0),
# p_flight_infection_risk_per_case_contact=0 #EXCLUDE flight risk.
# )
# ggplot(sim_result$data_by_infection_source,aes(x=day_of_infection,y=p_remains_infectious_and_in_pipeline))+geom_point()
#
# sim_result <- run_sim(
# pcr_test_list_to_avoid_boarding = list(list(-2,-3)),
# pcr_test_to_remain_in_quarantine = c(3),
# quarantine_release_day = quarantine_length,
# temp_and_symptoms_test_to_avoid_boarding = c(0),
# p_flight_infection_risk_per_case_contact=0 #EXCLUDE flight risk.
# )
# ggplot(sim_result$data_by_infection_source,aes(x=day_of_infection,y=p_remains_infectious_and_in_pipeline))+geom_point()
#
#now, this includes:
# inherent risk
# cabin exposure
# breaches (escapees and exceptions)
# spread to other guests during quarantine
#Does NOT include:
# - spread to workers during quarantine
| /app/journey_simulation_probablistic.R | permissive | bjsmith/infection_rate | R | false | false | 16,671 | r | #let's start with a 5 night quarantine intervention.
#how do we calculate the probability that a random case will get into the community?
#probability of a case being infectious on release
#probability of a case infecting another person in quarantine
#probability of a case infecting another person on the aeroplane
verbose <- TRUE
printv <-function(to_print){
if(verbose){
cat(to_print)
cat("\n")
}
}
run_sim <- function(
pcr_test_list_to_avoid_boarding = list(list(-2,-3)),
pcr_test_to_remain_in_quarantine = c(5),
quarantine_release_day = 6,
temp_and_symptoms_test_to_avoid_boarding = c(0),
p_flight_infection_risk_per_case_contact = 0.005*.15, #with mask wearing
quarantine_contacts_per_day=2,
set_density_at_1_per_day = FALSE
){
#let's start a list of all cases started in the prior 14 days from day 0
case_list_day_begin = c()
case_list_weight = c()
#all these should start from day 0 the day of infection
#not infectious on 0th day of infection.
p_pcr_detectable_by_day <- c(0,0, 0,5, 40, 65, 75, 80, 85, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, 62, 60, 58,rep(0,20))/100
p_symptomatic_by_day <- plnorm(0:40, 1.621,0.418)*0.4
p_infection_remains_infectious_by_day <<- c(0,rep(1,14),0.75,0.5,0.25,rep(0,30))
get_p_case_remains_infectious <- function(case_list_weight,case_list_day_begin,t){
#now calculate the odds that each current case remains infectious
if(length(case_list_weight)>0){
p_case_remains_infectious = vector("numeric",length(case_list_weight))
for (case_n in 1:length(case_list_weight)){
#case_n<-1
case_n_days_ago = t-case_list_day_begin[case_n]
p_case_remains_infectious[case_n] = p_infection_remains_infectious_by_day[case_n_days_ago+1]
}
}
return(p_case_remains_infectious)
}
sim_days_before_flight_start = 20
days_to_measure <- sim_days_before_flight_start+quarantine_release_day
community_exposure_by_day <- vector("numeric",days_to_measure)
proportional_infections_by_day <- vector("numeric",days_to_measure)
p_infectious_in_pipeline_by_day <- vector("numeric",days_to_measure)
#duration_to_flight
#spawn one case from t-13 onward to t=0
for (t in 1:days_to_measure){
# by convention t will be 20 days before flight.
duration_to_flight <- t-sim_days_before_flight_start
#flight occurs on day 14 then
printv("\n\n")
printv(paste("days after flight:",as.character(duration_to_flight)))
#create one infection per day constant, if we're pre-flight
if(duration_to_flight==0){ #include equal infections of day of flight
warning("excluded day of flight from infections. No special accounting for airport risk occurs.")
}
if(duration_to_flight<0){ #exclude day of flight
#if(duration_to_flight<=0){ #include day of flight
case_list_day_begin[length(case_list_day_begin) + 1] <- t
if(set_density_at_1_per_day){ #just for debugging
proportional_infections_by_day[t] <- 1
}else{
proportional_infections_by_day[t] <- 1/sum(p_infection_remains_infectious_by_day)
#we add cases using this very specific and odd figure so that we're scaling to 1 infectious case over the whole period
#that way we can talk about percentage of infectious cases
#I think we need to think about this a little bit more....
#was easier when it was a uniform distribution.
}
case_list_weight[length(case_list_weight) + 1] <- proportional_infections_by_day[t]
#this weight should really be divided by the sum of our "remains infectious" value
#but we'll leave that to start.
}
#mark the cases by the days since they occured
case_list_days_since_case <- t - case_list_day_begin
p_case_remains_infectious <- get_p_case_remains_infectious(case_list_weight,case_list_day_begin,t)
#at t=0 there is flight spread risk.
#each case, proportionally to its current infectiousness, can result in another case being generated
#that begins on the day of flight.
if(duration_to_flight==0){
# case_list_weight[t] <- case_list_weight[t]
# probably will deprecate this at some point when we go probabilistic
# for now it's useful to count the probability
# probably will deprecate this at some point when we go probabilistic
# case WEIGHT (the odds this is still in pipeline) is important
# case INFECTIOUSNESS is also important)
printv("flying")
num_contacts_on_flight=16
infectious_cases_on_flight <- sum(case_list_weight*p_case_remains_infectious)
#probability of infection per case
infectiousness_on_flight_per_case = p_flight_infection_risk_per_case_contact*num_contacts_on_flight
#I want to add an extra value to this series rather than
#augment the one already on there
#because strictly speaking each item in the case_list series is one case,
#weighted down by case_list_weight
#not necessarily a days worth of cases
case_list_day_begin[length(case_list_day_begin) + 1] <- t
proportional_infections_by_day[t] <- infectiousness_on_flight_per_case
case_list_weight[length(case_list_weight) + 1] <- infectiousness_on_flight_per_case
}
#OK great, we've got to the border
#now we want to know the probability of infection within quarantine each day
if(duration_to_flight>0){
# case WEIGHT (the odds this is still in pipeline) is important
# case INFECTIOUSNESS is also important)
#num_contacts_per_case_per_day=2.5
infectious_cases_in_environment <- sum(case_list_weight*p_case_remains_infectious)
#probability of infection per case
infectiousness_per_contact = 0.0036
#calibrated to produce a roughly 0.02% difference in success when moving from 5 contacts a day to 0
# as in Steyn, Binny, Hendy
expected_infections_today <-infectious_cases_in_environment*infectiousness_per_contact*quarantine_contacts_per_day
#I want to add an extra value to this series rather than
#augment the one already on there
#because strictly speaking each item in the case_list series is one case,
#weighted down by case_list_weight
#not necessarily a days worth of cases
case_list_day_begin[length(case_list_day_begin) + 1] <- t
case_list_weight[length(case_list_weight) + 1] <- expected_infections_today
proportional_infections_by_day[t] <- expected_infections_today
}
#mark the cases by the days since they occured again
case_list_days_since_case <- t - case_list_day_begin
p_case_remains_infectious <- get_p_case_remains_infectious(case_list_weight,case_list_day_begin,t)
current_infectious_cases <- case_list_weight*p_case_remains_infectious
current_infectious_cases_sum <- sum(current_infectious_cases)
if(duration_to_flight>0){
#OK. What's the odds of community exposure?
#breach odds per case should be something like
#breach odds are calculated from
breach_odds_per_day_with_30_cases <- exp(mean(c(log(1/30),log(12/9000))))
breach_odds_per_case <- breach_odds_per_day_with_30_cases/30
#this is the odds of any individual breaking out on any day
#we need the current
expected_quarantine_breaches_today <- current_infectious_cases_sum*breach_odds_per_case
community_exposure_by_day[t]=+expected_quarantine_breaches_today
}
#then the next day, we're gonna let the travelers out.
if(duration_to_flight==quarantine_release_day){
printv("releasing all travellers who haven't been tested positive.")
printv(paste("There are",current_infectious_cases_sum,"cases being released."))
#this is the probability that each case is detected and removed
#we now adjust our weights
community_exposure_by_day[t]=+current_infectious_cases_sum
printv("cases detected are removed and results shown on next day")
}
#PCR tests
for (pcr_test_set_to_avoid_boarding in pcr_test_list_to_avoid_boarding){
#pcr_test_set_to_avoid_boarding<-pcr_test_list_to_avoid_boarding[[1]]
#we have a specific set of tests
#how many tests are there?
test_possibilities <- length(pcr_test_set_to_avoid_boarding)
test_set_max_day <- max(unlist(pcr_test_set_to_avoid_boarding))
#what we want to do is apply equally to the case list weight based on the LAST day
if(duration_to_flight==test_set_max_day){
printv("doing PCR test...")
#if we're on the last day then iterate through each of the days to build a combined probability of
#either test detecting cases
#we assume that each test has an equal probability of being run
test_set_relative_to_now <- unlist(pcr_test_set_to_avoid_boarding) - test_set_max_day
test_set_combined_prob <- rep(0,length(case_list_days_since_case))
for (test_relative in test_set_relative_to_now){
test_day_prob <- c(p_pcr_detectable_by_day[case_list_days_since_case+1+test_relative],rep(0,-test_relative))
test_set_combined_prob= test_set_combined_prob + test_day_prob/test_possibilities
}
p_case_list_detected <- test_set_combined_prob#p_pcr_detectable_by_day[case_list_days_since_case+1]*(1/test_possibilities)
printv(p_case_list_detected)
# printv("\n")
cases_detected_by_tests <- case_list_weight*p_case_list_detected
case_list_weight <- case_list_weight - cases_detected_by_tests
#so the cases detected are the reciprocal of this????
print("cases detected are removed and results shown on next day")
}
#now probabilistically a PCR test on this day, the result of which will be to avoid boarding.
# if(duration_to_flight %in% pcr_test_set_to_avoid_boarding){
# print("doing PCR test...")
# warning("can't calculate PCR test this way because you're effectively multiplying the two probabilities together. They need to be added or averaged instead.")
# # better way is to find the LAST day in the test set
# # then run it on there but stagger the probability detections and work on that basis.
# p_case_list_detected <- p_pcr_detectable_by_day[case_list_days_since_case+1]*(1/test_possibilities)
# print(p_case_list_detected)
# print(t)
# print(duration_to_flight)
# #weighted to account for the probabiliyt of actually running the test
# #this is the probability that each case is detected and removed
# #we now adjust our weights
# case_list_weight <- case_list_weight*(1-p_case_list_detected)
# print("cases detected are removed and results shown on next day")
#
# }
}
#now we do a temperature test if there is one on this day.
if(duration_to_flight %in% temp_and_symptoms_test_to_avoid_boarding){
printv("doing temperature and symptom screening...")
p_case_list_detected <- p_symptomatic_by_day[case_list_days_since_case+1]
#this is the probability that each case is detected and removed
#we now adjust our weights
case_list_weight <- case_list_weight*(1-p_case_list_detected)
printv("cases detected are removed and results shown on next day")
}
#now we do a PCR test within the quarantine if there is one on this day.
if(duration_to_flight %in% pcr_test_to_remain_in_quarantine){
printv("doing PCR test to hold patients in quarantine...")
p_case_list_detected <- p_pcr_detectable_by_day[case_list_days_since_case+1]
#this is the probability that each case is detected and removed
#we now adjust our weights
case_list_weight <- case_list_weight*(1-p_case_list_detected)
printv("cases detected are removed and results shown on next day")
}else if (duration_to_flight>0){
warning("not counting daily health checks. But to do that we need to keep track of a specific subpopulation of the infected population who are symptomatic")
printv("doing managed isolation health check...")
#we remove 1/3 of the symptomatic patients from both the symptomatic pool and the total pool
#p_case_list_detected <- p_symptomatic_by_day[case_list_days_since_case+1]*1/3
#we'd need a "cases by day symptomatic" here.
#cases_by_day_symptomatic[case_list_days_since_case+1] = p_symptomatic_by_day[case_list_days_since_case+1]- p_case_list_detected
#round(p_case_list_detected,2)
round(p_symptomatic_by_day,2)
# #if there is no PCR on a given day,
# #then patients who are symptomatic have 33% odds of being detected during an interview
# #I don't think we can do this because we haven't actually modeled separate populations
# #of people who are symptomatic and asymptomatic
# #we would need to actually store a list of asymptomatic patients
# p_case_list_detected <- p_symptomatic_by_day[case_list_days_since_case+1]*1/3
# case_list_weight <- case_list_weight*(1-p_case_list_detected)
}
#now look at hte odds cases remain infectious and undetected
if(length(case_list_day_begin)>0){
printv("Case beginning by case:")
printv(round(case_list_day_begin,3))
printv("Case infectiousness by case:")
printv(round(current_infectious_cases,3))
printv("total infectious cases in the journey at the moment:")
printv(current_infectious_cases_sum)
printv("expected community exposure today:")
printv(community_exposure_by_day[t])
# print("log community exposure, by day, to date:")
# print(log(community_exposure_by_day))
}
#the below would be useful to visualize infectiousness from each day.
# data.frame("day_of_infection" = case_list_day_begin-sim_days_before_flight_start,
# "p_remains_in_pipeline" = case_list_weight,
# "p_remains_infectious" = p_case_remains_infectious)
p_infectious_in_pipeline_by_day[t] <- sum(current_infectious_cases)
}
return(list(
"data_by_infection_source" = data.frame(
"day_of_infection" = case_list_day_begin-sim_days_before_flight_start,
"cases_undetected" = case_list_weight,
"p_case_remains_infectious"=p_case_remains_infectious,
"p_remains_infectious_and_in_pipeline" = current_infectious_cases),
"data_by_day" = data.frame(
"days_past_flight"= 1:days_to_measure - sim_days_before_flight_start,
"p_community_exposure_by_day" = community_exposure_by_day,
"proportional_infections_by_day" = proportional_infections_by_day,
"p_infectious_in_pipeline_by_day" = p_infectious_in_pipeline_by_day
),
"total_community_exposure_by_day" = sum(community_exposure_by_day)
)
)
}
library(ggplot2)
# df_result <- run_sim()
# df_result$simulation <- c("with temp check")
# df_result2 <- run_sim(temp_and_symptoms_test_to_avoid_boarding=c())
# df_result2$simulation <- c("no temp check")
# ggplot(rbind(df_result,df_result2),
# aes(x=day_of_infection,y=p_remains_in_pipeline*p_remains_infectious,
# group=simulation,color=simulation))+geom_line()+
# labs(y="P(risk)",
# title="Probability density of case risk over the period by day of original infection")
# #later we may incorporate prevalence into this
# #and apply interventions along the way
#
# ####MATCHING STEYN, BINNY, HENDY
# #14 day quarantine
# verbose=TRUE
# quarantine_length <- 14
# sim_result <- run_sim(
# pcr_test_list_to_avoid_boarding = list(list(-2,-3)),
# pcr_test_to_remain_in_quarantine = c(3,12),
# quarantine_release_day = quarantine_length,
# temp_and_symptoms_test_to_avoid_boarding = c(0),
# p_flight_infection_risk_per_case_contact=0 #EXCLUDE flight risk.
# )
# ggplot(sim_result$data_by_infection_source,aes(x=day_of_infection,y=p_remains_infectious_and_in_pipeline))+geom_point()
#
# sim_result <- run_sim(
# pcr_test_list_to_avoid_boarding = list(list(-2,-3)),
# pcr_test_to_remain_in_quarantine = c(3),
# quarantine_release_day = quarantine_length,
# temp_and_symptoms_test_to_avoid_boarding = c(0),
# p_flight_infection_risk_per_case_contact=0 #EXCLUDE flight risk.
# )
# ggplot(sim_result$data_by_infection_source,aes(x=day_of_infection,y=p_remains_infectious_and_in_pipeline))+geom_point()
#
#now, this includes:
# inherent risk
# cabin exposure
# breaches (escapees and exceptions)
# spread to other guests during quarantine
#Does NOT include:
# - spread to workers during quarantine
|
#' Model KTS function
#'
#' This function makes predictions with the Kampala Trauma Score (KTS) model.
#' @param data The study data frame. No default.
#' @export
#'
ModelKTS <- function(data)
{
## Define variables to be included in model. Same with
## nsi, change value to 3,2,1. Age is excluded
## and binded later with duplicate factor labels.
model_variables <- c("sbp",
"rr")
## Define cut points for variables; bind avpu, and change values
## to 1,2,3,4 later. Same with nsi, change value to 3,2,1
cut_points <- list(sbp = c(0, 1, 49, 89, Inf),
rr = c(0,10, 29, Inf))
## Define scores from bins
scores <- list(sbp = c("1","2","3","4"),
rr = c("1","3","2"))
## Get age from study_data
age <- data$age
## Bin age
binned_age <- as.numeric(cut(age,
breaks = c(0,5,55,Inf),
include.lowest = TRUE))
## Asign labels to binned variables
age_var <- c(1,2,1)[binned_age]
## Change levels of nsi to 3,2,1 to correspond to score
## and coerce to numeric vector
levels(data$nsi) <- c("3", "2", "1")
data$nsi <- as.numeric(as.character(data$nsi))
## Bin model variables
binned_variables <- BinModelVariables(data,
model_variables,
cut_points,
scores)
## Sum binned variables to generate score
kts_predictions <- rowSums(cbind(binned_variables,
age_var,
data$avpu,
data$nsi))
return(kts_predictions)
}
| /R/ModelKTS.R | no_license | warnbergg/predictionpackr | R | false | false | 1,698 | r | #' Model KTS function
#'
#' This function makes predictions with the Kampala Trauma Score (KTS) model.
#' @param data The study data frame. No default.
#' @export
#'
ModelKTS <- function(data)
{
## Define variables to be included in model. Same with
## nsi, change value to 3,2,1. Age is excluded
## and binded later with duplicate factor labels.
model_variables <- c("sbp",
"rr")
## Define cut points for variables; bind avpu, and change values
## to 1,2,3,4 later. Same with nsi, change value to 3,2,1
cut_points <- list(sbp = c(0, 1, 49, 89, Inf),
rr = c(0,10, 29, Inf))
## Define scores from bins
scores <- list(sbp = c("1","2","3","4"),
rr = c("1","3","2"))
## Get age from study_data
age <- data$age
## Bin age
binned_age <- as.numeric(cut(age,
breaks = c(0,5,55,Inf),
include.lowest = TRUE))
## Asign labels to binned variables
age_var <- c(1,2,1)[binned_age]
## Change levels of nsi to 3,2,1 to correspond to score
## and coerce to numeric vector
levels(data$nsi) <- c("3", "2", "1")
data$nsi <- as.numeric(as.character(data$nsi))
## Bin model variables
binned_variables <- BinModelVariables(data,
model_variables,
cut_points,
scores)
## Sum binned variables to generate score
kts_predictions <- rowSums(cbind(binned_variables,
age_var,
data$avpu,
data$nsi))
return(kts_predictions)
}
|
rm(list=ls())
library(abind)
library(akima)
compare.time = seq(1+24*7,24*17)
compare.time = seq(1+24*17,1081)
compare.time = seq(1+24*7,1081)
ntime = length(compare.time)
n.data = ntime
##observations
load("results/interp.data.r")
obs.value = spc.value[["S40"]][compare.time]
obs.var = (pmax(0.005,obs.value*0.03))^2 #lower bound
obs.var = rep(0.005^2,length(obs.value)) #lower bound
case.name = "regular.1"
load(paste(case.name,"/statistics/state.vector.r",sep=''))
load(paste(case.name,"/statistics/tracer.ensemble.r",sep=''))
x = state.vector[,1]
y = state.vector[,2]
z = state.vector[,3]
simu.ensemble = tracer.ensemble[,4,compare.time]
data.mismatch = rep(0,dim(state.vector)[1])
for (ireaz in 1:dim(state.vector)[1])
{
data.mismatch[ireaz] = (simu.ensemble[ireaz,]-obs.value) %*% diag(1/obs.var) %*% (simu.ensemble[ireaz,]-obs.value)/n.data
}
save(list=ls(),file="results/s40.r")
| /2D_model_initial_setup/mismatch.calculate.s40.R | no_license | mrubayet/archived_codes_for_sfa_modeling | R | false | false | 901 | r | rm(list=ls())
library(abind)
library(akima)
compare.time = seq(1+24*7,24*17)
compare.time = seq(1+24*17,1081)
compare.time = seq(1+24*7,1081)
ntime = length(compare.time)
n.data = ntime
##observations
load("results/interp.data.r")
obs.value = spc.value[["S40"]][compare.time]
obs.var = (pmax(0.005,obs.value*0.03))^2 #lower bound
obs.var = rep(0.005^2,length(obs.value)) #lower bound
case.name = "regular.1"
load(paste(case.name,"/statistics/state.vector.r",sep=''))
load(paste(case.name,"/statistics/tracer.ensemble.r",sep=''))
x = state.vector[,1]
y = state.vector[,2]
z = state.vector[,3]
simu.ensemble = tracer.ensemble[,4,compare.time]
data.mismatch = rep(0,dim(state.vector)[1])
for (ireaz in 1:dim(state.vector)[1])
{
data.mismatch[ireaz] = (simu.ensemble[ireaz,]-obs.value) %*% diag(1/obs.var) %*% (simu.ensemble[ireaz,]-obs.value)/n.data
}
save(list=ls(),file="results/s40.r")
|
library(RProtoBuf)
### Name: read-methods
### Title: Read a protocol buffer message from a connection
### Aliases: read read-methods read,Descriptor,character-method
### read,Descriptor,raw-method read,Descriptor,ANY-method
### Keywords: methods
### ** Examples
# example file that contains a "tutorial.AddressBook" message
book <- system.file( "examples", "addressbook.pb", package = "RProtoBuf" )
# read the message
message <- read( tutorial.AddressBook, book )
# or using the pseudo method
message <- tutorial.AddressBook$read( book )
# write its debug string
writeLines( as.character( message ) )
# grab the name of each person
sapply( message$person, function(p) p$name )
# read from a binary file connection
f <- file( book, open = "rb" )
message2 <- read( tutorial.AddressBook, f )
close( f )
# read from a message payload (raw vector)
payload <- readBin( book, raw(0), 5000 )
message3 <- tutorial.AddressBook$read( payload )
## Don't show:
stopifnot( identical( message, message2) )
stopifnot( identical( message, message3) )
## End(Don't show)
| /data/genthat_extracted_code/RProtoBuf/examples/read.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 1,072 | r | library(RProtoBuf)
### Name: read-methods
### Title: Read a protocol buffer message from a connection
### Aliases: read read-methods read,Descriptor,character-method
### read,Descriptor,raw-method read,Descriptor,ANY-method
### Keywords: methods
### ** Examples
# example file that contains a "tutorial.AddressBook" message
book <- system.file( "examples", "addressbook.pb", package = "RProtoBuf" )
# read the message
message <- read( tutorial.AddressBook, book )
# or using the pseudo method
message <- tutorial.AddressBook$read( book )
# write its debug string
writeLines( as.character( message ) )
# grab the name of each person
sapply( message$person, function(p) p$name )
# read from a binary file connection
f <- file( book, open = "rb" )
message2 <- read( tutorial.AddressBook, f )
close( f )
# read from a message payload (raw vector)
payload <- readBin( book, raw(0), 5000 )
message3 <- tutorial.AddressBook$read( payload )
## Don't show:
stopifnot( identical( message, message2) )
stopifnot( identical( message, message3) )
## End(Don't show)
|
#' @title Llama N veces a la funcion de prediccion presencia donde N es el numero de dispositivos relacionados con el activo recbido
#'
#' @description Llama N veces a la funcion de prediccion presencia donde N es el numero de dispositivos relacionados con el activo recbido
#'
#' @param fecha_inicial, fecha_final, tipo_estancia
#'
#' @return json
#'
#' @examples llamada_prediccion_presencia_temporal("2021-07-10 00:00:00", "2021-08-10 23:00:00", "aulas-pb")
#'
#' @import httr
#' jsonlite
#' rjson
#' RCurl
#' dplyr
#' prob
#' zoo
#' lubridate
#' timeDate
#' RWeka
#' caret
#' class
#' gmodels
#' rJava
#'
#' @export
llamada_prediccion_presencia_temporal <- function(fecha_inicial, fecha_final, tipo_estancia){
# Volcado parámetros
fecha_1 <- fecha_inicial
fecha_2 <- fecha_final
tipo_estancia <- tolower(tipo_estancia)
#df <- read.csv("inst/extdata/dispositivos.csv", sep = ",")
#id_aulas <- unlist(str_split(df$dev_id[c(grep("Aula ", df$Nombre),grep("Taller ", df$Nombre))],","))
#id_empresas <- unlist(str_split(df$dev_id[1:16],","))
#id_despachos_pb <- unlist(str_split(df$dev_id[17:27],","))
#id_seminarios <- unlist(str_split(df$dev_id[28:34],","))
#id_despachos_p1 <- unlist(str_split(df$dev_id[42:54],","))
id_aulas <- c("f4d0d070-24dd-11eb-b605-01af9c6dd825","fa1cb5d0-24dd-11eb-b605-01af9c6dd825","feccf770-24dd-11eb-b605-01af9c6dd825","03179970-24de-11eb-b605-01af9c6dd825","083542e0-24de-11eb-b605-01af9c6dd825","0e3d9a70-24de-11eb-b605-01af9c6dd825","0e3d9a70-24de-11eb-b605-01af9c6dd825","f4d371c0-2d9f-11eb-b605-01af9c6dd825","02d28360-2da0-11eb-b605-01af9c6dd825","0b615ec0-2da0-11eb-b605-01af9c6dd825")
id_empresas <- c("aa6cf240-24d6-11eb-b605-01af9c6dd825","af8e9350-24d6-11eb-b605-01af9c6dd825","7f2c2bf0-276a-11eb-b605-01af9c6dd825","b5fc6370-24d6-11eb-b605-01af9c6dd825","caaf8810-276a-11eb-b605-01af9c6dd825","c38cfbd0-24d6-11eb-b605-01af9c6dd825","cba93f40-24d6-11eb-b605-01af9c6dd825","cf2ac4e0-24d6-11eb-b605-01af9c6dd825","e7d0e380-24d6-11eb-b605-01af9c6dd825","ef5309d0-24d6-11eb-b605-01af9c6dd825","79a16980-2da4-11eb-b605-01af9c6dd825","f9bf09a0-24d6-11eb-b605-01af9c6dd825","00f6b970-24d7-11eb-b605-01af9c6dd825","04c79790-24d7-11eb-b605-01af9c6dd825","08af5910-24d7-11eb-b605-01af9c6dd825","575a6340-2da4-11eb-b605-01af9c6dd825")
id_despachos_pb <- c("1e6fea50-24df-11eb-b605-01af9c6dd825","229e9fe0-24df-11eb-b605-01af9c6dd825","27a84c20-24df-11eb-b605-01af9c6dd825","2c6781e0-24df-11eb-b605-01af9c6dd825","30d7fb60-24df-11eb-b605-01af9c6dd825","350fffc0-24df-11eb-b605-01af9c6dd825","39802b20-24df-11eb-b605-01af9c6dd825","43d0b3b0-24df-11eb-b605-01af9c6dd825","47b05ee0-24df-11eb-b605-01af9c6dd825","4c4e7810-24df-11eb-b605-01af9c6dd825","92a2d790-24dd-11eb-b605-01af9c6dd825")
id_seminarios <- c("a14e2ec0-24dd-11eb-b605-01af9c6dd825","b97ea830-24dd-11eb-b605-01af9c6dd825","b4f30590-24dd-11eb-b605-01af9c6dd825","a14e2ec0-24dd-11eb-b605-01af9c6dd825","cabeb400-24dd-11eb-b605-01af9c6dd825","d89f8f40-24dd-11eb-b605-01af9c6dd825","e2ca4050-24dd-11eb-b605-01af9c6dd825")
id_despachos_p1 <- c("5321b630-24de-11eb-b605-01af9c6dd825","59d9d5c0-24de-11eb-b605-01af9c6dd825","5eaeb660-24de-11eb-b605-01af9c6dd825","6311c260-24de-11eb-b605-01af9c6dd825","67f54900-24de-11eb-b605-01af9c6dd825","6d17ad60-24de-11eb-b605-01af9c6dd825","72dda4c0-24de-11eb-b605-01af9c6dd825","7d24b770-24de-11eb-b605-01af9c6dd825","1dda2880-309c-11eb-b605-01af9c6dd825","817d8a40-24de-11eb-b605-01af9c6dd825","860200f0-24de-11eb-b605-01af9c6dd825","8a7fe7f0-24de-11eb-b605-01af9c6dd825","900c7fd0-24de-11eb-b605-01af9c6dd825","9fef93b0-24de-11eb-b605-01af9c6dd825")
switch(tipo_estancia,
"aulas-pb"={
vector_ids <- id_aulas
},
"despachos-pb"={
vector_ids <- id_despachos_pb
},
"empresas-pb"={
vector_ids <- id_empresas
},
"seminarios-pb"={
vector_ids <- id_seminarios
},
"despachos-p1"={
vector_ids <- id_despachos_p1
}
)
for(i in 1:length(vector_ids)){
tryCatch({
print(vector_ids[i])
prediccion_presencia_temporal(fecha_1, fecha_2, vector_ids[i], tipo_estancia)
}, error=function(e){
cat("ERROR :",conditionMessage(e), "\n")
})
}
}
| /R/post_ids_pred_presencia.R | no_license | Borch97/pruebas_predicciones | R | false | false | 4,271 | r | #' @title Llama N veces a la funcion de prediccion presencia donde N es el numero de dispositivos relacionados con el activo recbido
#'
#' @description Llama N veces a la funcion de prediccion presencia donde N es el numero de dispositivos relacionados con el activo recbido
#'
#' @param fecha_inicial, fecha_final, tipo_estancia
#'
#' @return json
#'
#' @examples llamada_prediccion_presencia_temporal("2021-07-10 00:00:00", "2021-08-10 23:00:00", "aulas-pb")
#'
#' @import httr
#' jsonlite
#' rjson
#' RCurl
#' dplyr
#' prob
#' zoo
#' lubridate
#' timeDate
#' RWeka
#' caret
#' class
#' gmodels
#' rJava
#'
#' @export
llamada_prediccion_presencia_temporal <- function(fecha_inicial, fecha_final, tipo_estancia){
# Volcado parámetros
fecha_1 <- fecha_inicial
fecha_2 <- fecha_final
tipo_estancia <- tolower(tipo_estancia)
#df <- read.csv("inst/extdata/dispositivos.csv", sep = ",")
#id_aulas <- unlist(str_split(df$dev_id[c(grep("Aula ", df$Nombre),grep("Taller ", df$Nombre))],","))
#id_empresas <- unlist(str_split(df$dev_id[1:16],","))
#id_despachos_pb <- unlist(str_split(df$dev_id[17:27],","))
#id_seminarios <- unlist(str_split(df$dev_id[28:34],","))
#id_despachos_p1 <- unlist(str_split(df$dev_id[42:54],","))
id_aulas <- c("f4d0d070-24dd-11eb-b605-01af9c6dd825","fa1cb5d0-24dd-11eb-b605-01af9c6dd825","feccf770-24dd-11eb-b605-01af9c6dd825","03179970-24de-11eb-b605-01af9c6dd825","083542e0-24de-11eb-b605-01af9c6dd825","0e3d9a70-24de-11eb-b605-01af9c6dd825","0e3d9a70-24de-11eb-b605-01af9c6dd825","f4d371c0-2d9f-11eb-b605-01af9c6dd825","02d28360-2da0-11eb-b605-01af9c6dd825","0b615ec0-2da0-11eb-b605-01af9c6dd825")
id_empresas <- c("aa6cf240-24d6-11eb-b605-01af9c6dd825","af8e9350-24d6-11eb-b605-01af9c6dd825","7f2c2bf0-276a-11eb-b605-01af9c6dd825","b5fc6370-24d6-11eb-b605-01af9c6dd825","caaf8810-276a-11eb-b605-01af9c6dd825","c38cfbd0-24d6-11eb-b605-01af9c6dd825","cba93f40-24d6-11eb-b605-01af9c6dd825","cf2ac4e0-24d6-11eb-b605-01af9c6dd825","e7d0e380-24d6-11eb-b605-01af9c6dd825","ef5309d0-24d6-11eb-b605-01af9c6dd825","79a16980-2da4-11eb-b605-01af9c6dd825","f9bf09a0-24d6-11eb-b605-01af9c6dd825","00f6b970-24d7-11eb-b605-01af9c6dd825","04c79790-24d7-11eb-b605-01af9c6dd825","08af5910-24d7-11eb-b605-01af9c6dd825","575a6340-2da4-11eb-b605-01af9c6dd825")
id_despachos_pb <- c("1e6fea50-24df-11eb-b605-01af9c6dd825","229e9fe0-24df-11eb-b605-01af9c6dd825","27a84c20-24df-11eb-b605-01af9c6dd825","2c6781e0-24df-11eb-b605-01af9c6dd825","30d7fb60-24df-11eb-b605-01af9c6dd825","350fffc0-24df-11eb-b605-01af9c6dd825","39802b20-24df-11eb-b605-01af9c6dd825","43d0b3b0-24df-11eb-b605-01af9c6dd825","47b05ee0-24df-11eb-b605-01af9c6dd825","4c4e7810-24df-11eb-b605-01af9c6dd825","92a2d790-24dd-11eb-b605-01af9c6dd825")
id_seminarios <- c("a14e2ec0-24dd-11eb-b605-01af9c6dd825","b97ea830-24dd-11eb-b605-01af9c6dd825","b4f30590-24dd-11eb-b605-01af9c6dd825","a14e2ec0-24dd-11eb-b605-01af9c6dd825","cabeb400-24dd-11eb-b605-01af9c6dd825","d89f8f40-24dd-11eb-b605-01af9c6dd825","e2ca4050-24dd-11eb-b605-01af9c6dd825")
id_despachos_p1 <- c("5321b630-24de-11eb-b605-01af9c6dd825","59d9d5c0-24de-11eb-b605-01af9c6dd825","5eaeb660-24de-11eb-b605-01af9c6dd825","6311c260-24de-11eb-b605-01af9c6dd825","67f54900-24de-11eb-b605-01af9c6dd825","6d17ad60-24de-11eb-b605-01af9c6dd825","72dda4c0-24de-11eb-b605-01af9c6dd825","7d24b770-24de-11eb-b605-01af9c6dd825","1dda2880-309c-11eb-b605-01af9c6dd825","817d8a40-24de-11eb-b605-01af9c6dd825","860200f0-24de-11eb-b605-01af9c6dd825","8a7fe7f0-24de-11eb-b605-01af9c6dd825","900c7fd0-24de-11eb-b605-01af9c6dd825","9fef93b0-24de-11eb-b605-01af9c6dd825")
switch(tipo_estancia,
"aulas-pb"={
vector_ids <- id_aulas
},
"despachos-pb"={
vector_ids <- id_despachos_pb
},
"empresas-pb"={
vector_ids <- id_empresas
},
"seminarios-pb"={
vector_ids <- id_seminarios
},
"despachos-p1"={
vector_ids <- id_despachos_p1
}
)
for(i in 1:length(vector_ids)){
tryCatch({
print(vector_ids[i])
prediccion_presencia_temporal(fecha_1, fecha_2, vector_ids[i], tipo_estancia)
}, error=function(e){
cat("ERROR :",conditionMessage(e), "\n")
})
}
}
|
args=commandArgs(trailingOnly = TRUE)
grammy.file <- args[[1]]
blast.file <- args[[2]]
stats.file <- args[[3]]
REF <- args[[4]]
output.file <- args[[5]]
grammy.tab <- read.table(grammy.file, header = FALSE, fill = TRUE)
colnames(grammy.tab) <- c("SAMPLE", "Taxid", "GrAb", "GrEr")
#
blast <- read.table(blast.file, header = FALSE, fill = TRUE)
total.blast <- length(unique(blast$V1))
#
if (!grepl("CFS|admixture|wcmc|phix|GU", grammy.file)){
align.stats <- read.table(stats.file, header = TRUE, fill = TRUE)
hg.coverage <- align.stats$DEPTH[1]
}else{
hg.coverage<-1
}
#
grammy.LUT <- read.table(REF, header = TRUE, fill = TRUE)
grammy.tab.info <- merge(grammy.tab, grammy.LUT, by = "Taxid")
# weighted genome size
grammy.tab.info$hgcoverage <- hg.coverage
grammy.tab.info$WeightedGenome <- sum(grammy.tab.info$Length * grammy.tab.info$GrAb)
grammy.tab.info$AdjustedBlast <- total.blast*(grammy.tab.info$Length*grammy.tab.info$GrAb/grammy.tab.info$WeightedGenome)
grammy.tab.info$Coverage <- 75*grammy.tab.info$AdjustedBlast/grammy.tab.info$Length
grammy.tab.info$RelCoverage <- 2*75*grammy.tab.info$AdjustedBlast/grammy.tab.info$Length/hg.coverage
#
write.table(grammy.tab.info, output.file,sep ="\t", row.names = FALSE)
| /workflow/scripts/metagenome/annotate_grammy_apc.R | no_license | omrmzv/SIFTseq | R | false | false | 1,227 | r | args=commandArgs(trailingOnly = TRUE)
grammy.file <- args[[1]]
blast.file <- args[[2]]
stats.file <- args[[3]]
REF <- args[[4]]
output.file <- args[[5]]
grammy.tab <- read.table(grammy.file, header = FALSE, fill = TRUE)
colnames(grammy.tab) <- c("SAMPLE", "Taxid", "GrAb", "GrEr")
#
blast <- read.table(blast.file, header = FALSE, fill = TRUE)
total.blast <- length(unique(blast$V1))
#
if (!grepl("CFS|admixture|wcmc|phix|GU", grammy.file)){
align.stats <- read.table(stats.file, header = TRUE, fill = TRUE)
hg.coverage <- align.stats$DEPTH[1]
}else{
hg.coverage<-1
}
#
grammy.LUT <- read.table(REF, header = TRUE, fill = TRUE)
grammy.tab.info <- merge(grammy.tab, grammy.LUT, by = "Taxid")
# weighted genome size
grammy.tab.info$hgcoverage <- hg.coverage
grammy.tab.info$WeightedGenome <- sum(grammy.tab.info$Length * grammy.tab.info$GrAb)
grammy.tab.info$AdjustedBlast <- total.blast*(grammy.tab.info$Length*grammy.tab.info$GrAb/grammy.tab.info$WeightedGenome)
grammy.tab.info$Coverage <- 75*grammy.tab.info$AdjustedBlast/grammy.tab.info$Length
grammy.tab.info$RelCoverage <- 2*75*grammy.tab.info$AdjustedBlast/grammy.tab.info$Length/hg.coverage
#
write.table(grammy.tab.info, output.file,sep ="\t", row.names = FALSE)
|
## Prepared by Cyril Michel on 2019-07-10; cyril.michel@noaa.gov
#################################################################
#### HOW TO PULL IN REAL-TIME FISH DETECTION DATA INTO R ########
#################################################################
## install and load the 'rerddap' library
library(rerddap)
## It is important to delete your cache if you want the newest data.
## If not, when you rerun the same data queries as before, the command will likely return the old cached data and not the newest data
## If data is unlikely to change or be amended, not deleting your cache will speed up some data queries
cache_delete_all()
## Find out details on the database
db <- info('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/")
## This will tell you the avaialable columns
vars <- db$variables$variable_name
## This will tell you unique StudyID names
as.data.frame(tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", fields = c("Study_ID")))
## Below is the metadata for each field
## "TagCode", TagID code, in hexadecimal format
## "Study_ID", unifying name for all fish released in a year for a study
## "release_time", Date/time of fish release, Pacific Standard Time - i.e., no DST offset
## "location", Receiver location name
## "recv", receiver serial number
## "time", Detection Date/time, UTC
## "local_time", Detection Date/time, Pacific Standard Time - i.e., no DST offset
## "latitude", receiver location latitude, decimal degrees
## "longitude", receiver location longitude, decimal degrees
## "general_location", a unifying name when several receivers cover one location
## "river_km", General Location River Kilometer - distance from Golden Gate, km
## "length", fork length of fish, in mm
## "weight", fish weight, in gr
## "release_river_km", Release River Kilometer - distance from Golden Gate, km
## Download all data (will take a little while, large database).
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/")
## ALTERNATIVELY, download only the data you need, see following code snippets
## Download only data from 1 studyID, here for example, Juv_Green_Sturgeon_2018 study
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="Juv_Green_Sturgeon_2018"')
## Download only data from 1 receiver location
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'general_location="MiddleRiver"')
## Download only data from a specific time range (in UTC time)
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'time>=2019-01-01', 'time<=2019-01-10')
## Download data from a combination of conditions. For example, Study_ID="DeerCk-SH-Wild-2019" and general_location="ButteBr_RT"
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="MillCk_SH_Wild_S2019"', 'general_location="ButteBrRT"')
## Download only specific columns for a studyID (or a general location, time frame or other constraint)
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'general_location="MiddleRiver"', fields = c("TagCode","Study_ID"))
## Finally, download a summary of unique records. Say for example you want to know the unique TagCodes detected in the array from a studyID
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", fields = c("TagCode"), distinct = T, 'Study_ID="DeerCk-SH-Wild-2019"')
## Or, number of unique fish detected at each receiver location for a studyID
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="DeerCk-SH-Wild-2019"', fields = c("general_location","TagCode"), distinct = T)
## Now, bringing it all together to perform analyses
## Here, as a basic example, the percentage of fish released that were detected at Benicia Bridge for a study
# Find number of fish released per Study ID. NOTE, if a released fish was never detected again, it will have only one row, with blank for a timestamp and detection location info
released <- nrow(tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="Winter_H_2019"', fields = c("TagCode"), distinct = T))
benicia <- nrow(tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="Winter_H_2019"', 'general_location="ButteBrRT"', fields = c("TagCode"), distinct = T))
## Percent detected at Benicia:
round(benicia/released*100, 2)
## PLEASE NOTE: IF A DATA REQUEST ABOVE RETURNS SIMPLY "Error: ", THIS LIKELY MEANS THE DATA REQUEST CAME UP WITH ZERO RETURNS
| /data/accessing_ERDDAP_via_R_realtime.R | no_license | fishsciences/real-time | R | false | false | 4,650 | r |
## Prepared by Cyril Michel on 2019-07-10; cyril.michel@noaa.gov
#################################################################
#### HOW TO PULL IN REAL-TIME FISH DETECTION DATA INTO R ########
#################################################################
## install and load the 'rerddap' library
library(rerddap)
## It is important to delete your cache if you want the newest data.
## If not, when you rerun the same data queries as before, the command will likely return the old cached data and not the newest data
## If data is unlikely to change or be amended, not deleting your cache will speed up some data queries
cache_delete_all()
## Find out details on the database
db <- info('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/")
## This will tell you the avaialable columns
vars <- db$variables$variable_name
## This will tell you unique StudyID names
as.data.frame(tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", fields = c("Study_ID")))
## Below is the metadata for each field
## "TagCode", TagID code, in hexadecimal format
## "Study_ID", unifying name for all fish released in a year for a study
## "release_time", Date/time of fish release, Pacific Standard Time - i.e., no DST offset
## "location", Receiver location name
## "recv", receiver serial number
## "time", Detection Date/time, UTC
## "local_time", Detection Date/time, Pacific Standard Time - i.e., no DST offset
## "latitude", receiver location latitude, decimal degrees
## "longitude", receiver location longitude, decimal degrees
## "general_location", a unifying name when several receivers cover one location
## "river_km", General Location River Kilometer - distance from Golden Gate, km
## "length", fork length of fish, in mm
## "weight", fish weight, in gr
## "release_river_km", Release River Kilometer - distance from Golden Gate, km
## Download all data (will take a little while, large database).
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/")
## ALTERNATIVELY, download only the data you need, see following code snippets
## Download only data from 1 studyID, here for example, Juv_Green_Sturgeon_2018 study
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="Juv_Green_Sturgeon_2018"')
## Download only data from 1 receiver location
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'general_location="MiddleRiver"')
## Download only data from a specific time range (in UTC time)
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'time>=2019-01-01', 'time<=2019-01-10')
## Download data from a combination of conditions. For example, Study_ID="DeerCk-SH-Wild-2019" and general_location="ButteBr_RT"
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="MillCk_SH_Wild_S2019"', 'general_location="ButteBrRT"')
## Download only specific columns for a studyID (or a general location, time frame or other constraint)
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'general_location="MiddleRiver"', fields = c("TagCode","Study_ID"))
## Finally, download a summary of unique records. Say for example you want to know the unique TagCodes detected in the array from a studyID
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", fields = c("TagCode"), distinct = T, 'Study_ID="DeerCk-SH-Wild-2019"')
## Or, number of unique fish detected at each receiver location for a studyID
dat <- tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="DeerCk-SH-Wild-2019"', fields = c("general_location","TagCode"), distinct = T)
## Now, bringing it all together to perform analyses
## Here, as a basic example, the percentage of fish released that were detected at Benicia Bridge for a study
# Find number of fish released per Study ID. NOTE, if a released fish was never detected again, it will have only one row, with blank for a timestamp and detection location info
released <- nrow(tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="Winter_H_2019"', fields = c("TagCode"), distinct = T))
benicia <- nrow(tabledap('FEDcalFishTrack', url = "http://oceanview.pfeg.noaa.gov/erddap/", 'Study_ID="Winter_H_2019"', 'general_location="ButteBrRT"', fields = c("TagCode"), distinct = T))
## Percent detected at Benicia:
round(benicia/released*100, 2)
## PLEASE NOTE: IF A DATA REQUEST ABOVE RETURNS SIMPLY "Error: ", THIS LIKELY MEANS THE DATA REQUEST CAME UP WITH ZERO RETURNS
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/CreateSegmentAngle.R
\name{CreateSegmentAngle}
\alias{CreateSegmentAngle}
\title{Creates a matrix that represents the segment that starts from a point with certain length and angle}
\usage{
CreateSegmentAngle(P, angle, l)
}
\arguments{
\item{P}{Vector containing the xy-coordinates of the point}
\item{angle}{Angle in degrees (0-360) for the segment}
\item{l}{Positive number that indicates the length for the segment}
}
\value{
Returns a matrix which contains the points that determine the extremes of the segment
}
\description{
\code{DrawSegment} plots the segment that connects two points in a previously generated coordinate plane
}
\examples{
x_min <- -5
x_max <- 5
y_min <- -5
y_max <- 5
CoordinatePlane(x_min, x_max, y_min, y_max)
P <- c(0,0)
angle <- 30
l <- 1
Segment <- CreateSegmentAngle(P, angle, l)
Draw(Segment, "black")
}
| /man/CreateSegmentAngle.Rd | no_license | cran/LearnGeom | R | false | true | 951 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/CreateSegmentAngle.R
\name{CreateSegmentAngle}
\alias{CreateSegmentAngle}
\title{Creates a matrix that represents the segment that starts from a point with certain length and angle}
\usage{
CreateSegmentAngle(P, angle, l)
}
\arguments{
\item{P}{Vector containing the xy-coordinates of the point}
\item{angle}{Angle in degrees (0-360) for the segment}
\item{l}{Positive number that indicates the length for the segment}
}
\value{
Returns a matrix which contains the points that determine the extremes of the segment
}
\description{
\code{DrawSegment} plots the segment that connects two points in a previously generated coordinate plane
}
\examples{
x_min <- -5
x_max <- 5
y_min <- -5
y_max <- 5
CoordinatePlane(x_min, x_max, y_min, y_max)
P <- c(0,0)
angle <- 30
l <- 1
Segment <- CreateSegmentAngle(P, angle, l)
Draw(Segment, "black")
}
|
import_data = function(parameters_path) {
#Created by Daniel Ca?ueto 30/08/2016
#Import of variables stored in the parameters file and of the dataset to quantify
#List of parameters to use to create the dataset
params = list()
#Import fo parameters from the csv file
# TO DO: stringsasfactors=F
import_profile = read.delim(
parameters_path,
sep = ',',
header = T,
stringsAsFactors = F
)
import_profile = as.data.frame(sapply(import_profile, function(x)
gsub("\\\\", "/", x)))
#Getting the names of experiments, signals and ROIs to quantify and use
metadata_path = as.character(import_profile[3, 2])
dummy = read.delim(
metadata_path,
sep = ',',
header = T,
stringsAsFactors = F
)
Experiments=dummy[,1]
Experiments = as.vector(Experiments[Experiments != ''])
Metadata=dummy[,-1,drop=F]
# signals_names = read.delim(as.character(import_profile[6, 2]),
# header = F,
# stringsAsFactors = F)[, 1]
# signals_names = as.list(signals_names[signals_names != ''])
profile_folder_path = as.character(import_profile[6, 2])
ROI_data=read.csv(profile_folder_path)
signals_names=ROI_data[,4]
signals_codes = 1:length(signals_names)
#Preparing the structure of experiments and signals where to store the output
export_path = as.character(import_profile[7, 2])
#Other necessary variables
freq = as.numeric(as.character(import_profile[11, 2]))
biofluid=import_profile[14, 2]
repository=rio::import(as.character(import_profile[12, 2]))
if (biofluid=='Urine') {
repository=repository[which(repository[,3]==1),]
} else if (biofluid=='Serum') {
repository=repository[which(repository[,2]==1),]
} else {
}
#Kind of normalization
#TO DO: add PQN (but before standardize a way to find the regions to have into account)
normalization = import_profile[8, 2]
pqn='N'
params$norm_AREA = 'N'
params$norm_PEAK = 'N'
params$norm_left_ppm = 12
params$norm_right_ppm = -1
if (normalization == 1) {
#Eretic
params$norm_AREA = 'Y'
params$norm_left_ppm = 11.53
params$norm_right_ppm = 10.47
} else if (normalization == 2) {
#TSP
params$norm_AREA = 'Y'
params$norm_left_ppm = 0.1
params$norm_right_ppm = -0.1
} else if (normalization == 3) {
#Creatinine (intensity, not area, maybe dangerous for rats because of oxalacetate)
params$norm_PEAK = 'Y'
params$norm_left_ppm = 3.10
params$norm_right_ppm = 3
} else if (normalization == 4) {
#Spectrum AreA
params$norm_AREA = 'Y'
} else if (normalization == 5) {
#No normailzation
} else if (normalization == 6) {
#No normailzation
params$norm_AREA = 'Y'
pqn='Y'
}
#Alignment
alignment = import_profile[9, 2]
params$glucose_alignment = 'N'
params$tsp_alignment = 'N'
params$peak_alignment = 'N'
params$ref_pos = 8.452
if (alignment == 1) {
#Glucose
params$glucose_alignment = 'Y'
} else if (alignment == 2) {
#TSP
params$tsp_alignment = 'Y'
} else if (alignment == 3) {
#Formate
params$peak_alignment = 'Y'
}
#Suppresion regions
suppression = as.character(import_profile[10, 2])
if (suppression == '') {
params$disol_suppression = 'N'
} else {
params$disol_suppression = 'Y'
params$disol_suppression_ppm = as.numeric(strsplit(suppression, '-|;')[[1]])
dim(params$disol_suppression_ppm) = c(length(params$disol_suppression_ppm) /
2, 2)
params$disol_suppression_ppm = t(params$disol_suppression_ppm)
}
#Variables only necessary for reading Bruker files
bruker_path = import_profile[1, 2]
expno = as.character(import_profile[4, 2])
processingno = as.character(import_profile[5, 2])
#Variables only necessary for reading dataset in csv format
dataset_path = as.character(import_profile[2, 2])
if (bruker_path == '' || expno == '' || processingno == '') {
if (dataset_path != '') {
#Reading of dataset file (ideally with fread of data.table package, bu seems that the package is not compatible with R 3.3.1)
imported_data = list()
dummy = rio::import(dataset_path, sep = ',',header=F,colClasses='numeric')
pa=dim(dummy[-1,])
imported_data$dataset=as.numeric(as.matrix(dummy[-1,]))
dim(imported_data$dataset)=pa
colnames(imported_data$dataset) = dummy[1,]
imported_data$ppm = as.numeric(dummy[1,])
rownames(imported_data$dataset) = Experiments
params$buck_step = ifelse(
as.character(import_profile[13, 2]) == '',
abs(imported_data$ppm[1] - imported_data$ppm[length(imported_data$ppm)]) /
length(imported_data$ppm),
as.numeric(as.character(import_profile[13, 2]))
)
} else {
print('Problem when creating the dataset. Please revise the parameters.')
return()
}
} else {
#Reading of Bruker files
params$dir = bruker_path
params$expno = expno
params$processingno = processingno
params$buck_step = as.numeric(as.character(import_profile[13, 2]))
imported_data = Metadata2Buckets(Experiments, params)
}
imported_data$dataset[is.na(imported_data$dataset)]=min(abs(imported_data$dataset)[abs(imported_data$dataset)>0])
if (pqn=='Y') {
tra=rep(NA,20)
vardata3=apply(imported_data$dataset,2,function(x) sd(x,na.rm=T)/mean(x,na.rm=T))
ss=boxplot.stats(vardata3)$out
vardata3=vardata3[!(vardata3 %in% ss)]
param=seq(5,100,5)*max(vardata3,na.rm=T)/100
for (i in 1:length(param)) {
s=plele(param[i],imported_data$dataset,vardata3);
tra[i]=median(s$lol2[apply(imported_data$dataset,2,function(x) median(x,na.rm=T))>median(imported_data$dataset,na.rm=T)],na.rm=T);
}
s=plele(param[which.min(tra)],imported_data$dataset,vardata3);
imported_data$dataset=s$pqndatanoscale
}
#Storage of parameters needed to perform the fit in a single variable to return.
imported_data$buck_step = params$buck_step
imported_data$profile_folder_path = profile_folder_path
imported_data$metadata_path = metadata_path
imported_data$parameters_path = parameters_path
imported_data$signals_names = signals_names
imported_data$signals_codes = signals_codes
imported_data$Experiments = setdiff(Experiments, imported_data$not_loaded_experiments)
imported_data$export_path = export_path
imported_data$freq = freq
imported_data$Metadata=Metadata
imported_data$repository=repository
return(imported_data)
}
| /import_data.R | no_license | user05011988/shinyinterface | R | false | false | 6,760 | r | import_data = function(parameters_path) {
#Created by Daniel Ca?ueto 30/08/2016
#Import of variables stored in the parameters file and of the dataset to quantify
#List of parameters to use to create the dataset
params = list()
#Import fo parameters from the csv file
# TO DO: stringsasfactors=F
import_profile = read.delim(
parameters_path,
sep = ',',
header = T,
stringsAsFactors = F
)
import_profile = as.data.frame(sapply(import_profile, function(x)
gsub("\\\\", "/", x)))
#Getting the names of experiments, signals and ROIs to quantify and use
metadata_path = as.character(import_profile[3, 2])
dummy = read.delim(
metadata_path,
sep = ',',
header = T,
stringsAsFactors = F
)
Experiments=dummy[,1]
Experiments = as.vector(Experiments[Experiments != ''])
Metadata=dummy[,-1,drop=F]
# signals_names = read.delim(as.character(import_profile[6, 2]),
# header = F,
# stringsAsFactors = F)[, 1]
# signals_names = as.list(signals_names[signals_names != ''])
profile_folder_path = as.character(import_profile[6, 2])
ROI_data=read.csv(profile_folder_path)
signals_names=ROI_data[,4]
signals_codes = 1:length(signals_names)
#Preparing the structure of experiments and signals where to store the output
export_path = as.character(import_profile[7, 2])
#Other necessary variables
freq = as.numeric(as.character(import_profile[11, 2]))
biofluid=import_profile[14, 2]
repository=rio::import(as.character(import_profile[12, 2]))
if (biofluid=='Urine') {
repository=repository[which(repository[,3]==1),]
} else if (biofluid=='Serum') {
repository=repository[which(repository[,2]==1),]
} else {
}
#Kind of normalization
#TO DO: add PQN (but before standardize a way to find the regions to have into account)
normalization = import_profile[8, 2]
pqn='N'
params$norm_AREA = 'N'
params$norm_PEAK = 'N'
params$norm_left_ppm = 12
params$norm_right_ppm = -1
if (normalization == 1) {
#Eretic
params$norm_AREA = 'Y'
params$norm_left_ppm = 11.53
params$norm_right_ppm = 10.47
} else if (normalization == 2) {
#TSP
params$norm_AREA = 'Y'
params$norm_left_ppm = 0.1
params$norm_right_ppm = -0.1
} else if (normalization == 3) {
#Creatinine (intensity, not area, maybe dangerous for rats because of oxalacetate)
params$norm_PEAK = 'Y'
params$norm_left_ppm = 3.10
params$norm_right_ppm = 3
} else if (normalization == 4) {
#Spectrum AreA
params$norm_AREA = 'Y'
} else if (normalization == 5) {
#No normailzation
} else if (normalization == 6) {
#No normailzation
params$norm_AREA = 'Y'
pqn='Y'
}
#Alignment
alignment = import_profile[9, 2]
params$glucose_alignment = 'N'
params$tsp_alignment = 'N'
params$peak_alignment = 'N'
params$ref_pos = 8.452
if (alignment == 1) {
#Glucose
params$glucose_alignment = 'Y'
} else if (alignment == 2) {
#TSP
params$tsp_alignment = 'Y'
} else if (alignment == 3) {
#Formate
params$peak_alignment = 'Y'
}
#Suppresion regions
suppression = as.character(import_profile[10, 2])
if (suppression == '') {
params$disol_suppression = 'N'
} else {
params$disol_suppression = 'Y'
params$disol_suppression_ppm = as.numeric(strsplit(suppression, '-|;')[[1]])
dim(params$disol_suppression_ppm) = c(length(params$disol_suppression_ppm) /
2, 2)
params$disol_suppression_ppm = t(params$disol_suppression_ppm)
}
#Variables only necessary for reading Bruker files
bruker_path = import_profile[1, 2]
expno = as.character(import_profile[4, 2])
processingno = as.character(import_profile[5, 2])
#Variables only necessary for reading dataset in csv format
dataset_path = as.character(import_profile[2, 2])
if (bruker_path == '' || expno == '' || processingno == '') {
if (dataset_path != '') {
#Reading of dataset file (ideally with fread of data.table package, bu seems that the package is not compatible with R 3.3.1)
imported_data = list()
dummy = rio::import(dataset_path, sep = ',',header=F,colClasses='numeric')
pa=dim(dummy[-1,])
imported_data$dataset=as.numeric(as.matrix(dummy[-1,]))
dim(imported_data$dataset)=pa
colnames(imported_data$dataset) = dummy[1,]
imported_data$ppm = as.numeric(dummy[1,])
rownames(imported_data$dataset) = Experiments
params$buck_step = ifelse(
as.character(import_profile[13, 2]) == '',
abs(imported_data$ppm[1] - imported_data$ppm[length(imported_data$ppm)]) /
length(imported_data$ppm),
as.numeric(as.character(import_profile[13, 2]))
)
} else {
print('Problem when creating the dataset. Please revise the parameters.')
return()
}
} else {
#Reading of Bruker files
params$dir = bruker_path
params$expno = expno
params$processingno = processingno
params$buck_step = as.numeric(as.character(import_profile[13, 2]))
imported_data = Metadata2Buckets(Experiments, params)
}
imported_data$dataset[is.na(imported_data$dataset)]=min(abs(imported_data$dataset)[abs(imported_data$dataset)>0])
if (pqn=='Y') {
tra=rep(NA,20)
vardata3=apply(imported_data$dataset,2,function(x) sd(x,na.rm=T)/mean(x,na.rm=T))
ss=boxplot.stats(vardata3)$out
vardata3=vardata3[!(vardata3 %in% ss)]
param=seq(5,100,5)*max(vardata3,na.rm=T)/100
for (i in 1:length(param)) {
s=plele(param[i],imported_data$dataset,vardata3);
tra[i]=median(s$lol2[apply(imported_data$dataset,2,function(x) median(x,na.rm=T))>median(imported_data$dataset,na.rm=T)],na.rm=T);
}
s=plele(param[which.min(tra)],imported_data$dataset,vardata3);
imported_data$dataset=s$pqndatanoscale
}
#Storage of parameters needed to perform the fit in a single variable to return.
imported_data$buck_step = params$buck_step
imported_data$profile_folder_path = profile_folder_path
imported_data$metadata_path = metadata_path
imported_data$parameters_path = parameters_path
imported_data$signals_names = signals_names
imported_data$signals_codes = signals_codes
imported_data$Experiments = setdiff(Experiments, imported_data$not_loaded_experiments)
imported_data$export_path = export_path
imported_data$freq = freq
imported_data$Metadata=Metadata
imported_data$repository=repository
return(imported_data)
}
|
fileUrl<-"https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileUrl,destfile="data.zip")
unzip("data.zip",list=TRUE)
data<-read.csv2(unz("data.zip","household_power_consumption.txt"),
header=TRUE,colClasses=c("character"))
options(warn=-1)
for(i in 3:9){
class(data[,i])<-"numeric"
}
options(warn=0)
library("dplyr")
names(data)
data[,1]<-as.Date(data[,1],"%d/%m/%Y")
library(chron)
data[,2]<-chron(times=data[,2])
fil_data<-filter(data,Date=="2007-02-01" | Date=="2007-02-02")
png(file = "plot1.png",height = 480, width = 480)
with(fil_data,hist(Global_active_power,col="red2",
xlab="Global Active Power (kilowatts)",ylab="Frequency",
main="Global Active Power",xlim=c(0,6)))
dev.off()
| /plot1.R | no_license | metustat/ExData_Plotting1 | R | false | false | 794 | r | fileUrl<-"https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileUrl,destfile="data.zip")
unzip("data.zip",list=TRUE)
data<-read.csv2(unz("data.zip","household_power_consumption.txt"),
header=TRUE,colClasses=c("character"))
options(warn=-1)
for(i in 3:9){
class(data[,i])<-"numeric"
}
options(warn=0)
library("dplyr")
names(data)
data[,1]<-as.Date(data[,1],"%d/%m/%Y")
library(chron)
data[,2]<-chron(times=data[,2])
fil_data<-filter(data,Date=="2007-02-01" | Date=="2007-02-02")
png(file = "plot1.png",height = 480, width = 480)
with(fil_data,hist(Global_active_power,col="red2",
xlab="Global Active Power (kilowatts)",ylab="Frequency",
main="Global Active Power",xlim=c(0,6)))
dev.off()
|
##COURSE PROJECT 1 - EXPLORATORY DATA ANALYSIS
## DANIEL ARBOLEDA
## PLOT 4
unzip("exdata_data_household_power_consumption.zip")
elpwcons <- read.table("household_power_consumption.txt", sep = ";", header = TRUE,
stringsAsFactors = FALSE, dec = ".", na.strings = "?",
check.names = FALSE, comment.char = "", quote = '\"')
elpwcons$Date <- as.Date(elpwcons$Date, format = "%d/%m/%Y")
elpwcons$DT <- paste(elpwcons$Date, elpwcons$Time)
elpwcons$DT <- strptime(elpwcons$DT, format = "%Y-%m-%d %H:%M:%S")
#head(elpwcons)
#str(elpwcons$DT)
elpwcons2 <- subset(elpwcons, Date >= "2007-02-01" & Date <= "2007-02-02")
png("plot4.png", height = 480, width = 480)
par(mfrow = c(2,2))
plot(elpwcons2$DT, elpwcons2$Global_active_power, ylab = "Global Active Power",
xlab = "", type = "line")
plot(elpwcons2$DT, elpwcons2$Voltage, ylab = "Voltage", xlab = "datetime", type = "line")
plot(elpwcons2$DT, elpwcons2$Sub_metering_1, ylab = "Energy sub metering", xlab = "",
col = "black", type = "line")
lines(elpwcons2$DT, elpwcons2$Sub_metering_2, col = "red")
lines(elpwcons2$DT, elpwcons2$Sub_metering_3, col = "blue")
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lwd = c(3,3), col = c("black", "red", "blue"), bty = "n", cex = 0.9)
plot(elpwcons2$DT, elpwcons2$Global_reactive_power, ylab = "Global_reactive_power",
xlab = "datetime", type = "line")
dev.off() | /plot4.R | no_license | DJARBOL/ExData_Plotting1 | R | false | false | 1,456 | r | ##COURSE PROJECT 1 - EXPLORATORY DATA ANALYSIS
## DANIEL ARBOLEDA
## PLOT 4
unzip("exdata_data_household_power_consumption.zip")
elpwcons <- read.table("household_power_consumption.txt", sep = ";", header = TRUE,
stringsAsFactors = FALSE, dec = ".", na.strings = "?",
check.names = FALSE, comment.char = "", quote = '\"')
elpwcons$Date <- as.Date(elpwcons$Date, format = "%d/%m/%Y")
elpwcons$DT <- paste(elpwcons$Date, elpwcons$Time)
elpwcons$DT <- strptime(elpwcons$DT, format = "%Y-%m-%d %H:%M:%S")
#head(elpwcons)
#str(elpwcons$DT)
elpwcons2 <- subset(elpwcons, Date >= "2007-02-01" & Date <= "2007-02-02")
png("plot4.png", height = 480, width = 480)
par(mfrow = c(2,2))
plot(elpwcons2$DT, elpwcons2$Global_active_power, ylab = "Global Active Power",
xlab = "", type = "line")
plot(elpwcons2$DT, elpwcons2$Voltage, ylab = "Voltage", xlab = "datetime", type = "line")
plot(elpwcons2$DT, elpwcons2$Sub_metering_1, ylab = "Energy sub metering", xlab = "",
col = "black", type = "line")
lines(elpwcons2$DT, elpwcons2$Sub_metering_2, col = "red")
lines(elpwcons2$DT, elpwcons2$Sub_metering_3, col = "blue")
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lwd = c(3,3), col = c("black", "red", "blue"), bty = "n", cex = 0.9)
plot(elpwcons2$DT, elpwcons2$Global_reactive_power, ylab = "Global_reactive_power",
xlab = "datetime", type = "line")
dev.off() |
library(tidyverse)
library(nycflights13)
# 7.3 Variation
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut))
diamonds %>%
count(cut)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)
diamonds %>%
count(cut_width(x = carat, 0.5))
ggplot(data = diamonds) +
geom_freqpoly(mapping = aes(x = carat, colour = cut), binwidth = 0.1)
?geom_freqpoly
# 7.3.4 Exercises
# 1
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = z), binwidth = 0.5)
diamonds %>%
filter(x > 3) %>%
ggplot() +
geom_histogram(mapping = aes(x = x), binwidth = 0.5)
diamonds %>%
filter(z < 2 | z > 10) %>%
arrange(z)
# 2
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = price), binwidth = 50)
diamonds %>%
filter(price < 2000) %>%
ggplot() +
geom_histogram(mapping = aes(x = price), binwidth = 10)
# 3
range(diamonds$carat)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)
diamonds %>%
filter(carat > 0.9 & carat < 1.1) %>%
ggplot() +
geom_histogram(mapping = aes(x = carat))
# 4
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat))
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat)) +
coord_cartesian(ylim = c(0, 1000))
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat)) +
ylim(0,1000)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5) +
coord_cartesian(xlim = c(0, 1.0))
# 7.4 Missing values
diamonds2 <- diamonds %>%
mutate(y = ifelse(y < 3 | y > 20, NA, y))
ggplot(data = flights) +
geom_histogram(mapping = aes(x = dep_time))
table(is.na(flights$dep_time))
ggplot(data = flights) +
geom_bar(mapping = aes(x = dep_time), na.rm = T)
sum(flights$dep_time)
?geom_histogram
?geom_bar
# 7.5 Covariance
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot()
ggplot(data = mpg, mapping = aes(x = reorder(class, hwy, FUN = median), y = hwy)) +
geom_boxplot()
ggplot(data = mpg, mapping = aes(x = reorder(class, hwy, FUN = median), y = hwy)) +
geom_boxplot() +
coord_flip()
# 7.5.1.1 Exercises
# 1
nycflights13::flights %>%
mutate(
cancelled = is.na(dep_time),
sched_hour = sched_dep_time %/% 100,
sched_min = sched_dep_time %% 100,
sched_dep_time = sched_hour + sched_min / 60
) %>%
ggplot(mapping = aes(sched_dep_time)) +
geom_freqpoly(mapping = aes(colour = cancelled), binwidth = 1/4)
nycflights13::flights %>%
mutate(
cancelled = is.na(dep_time),
sched_hour = sched_dep_time %/% 100,
sched_min = sched_dep_time %% 100,
sched_dep_time = sched_hour + sched_min / 60
) %>%
ggplot(mapping = aes(x = sched_dep_time, y = ..density..)) +
geom_freqpoly(mapping = aes(colour = cancelled), binwidth = 1)
# 2
names(diamonds)
ggplot(data = diamonds) +
geom_point(mapping = aes(x = carat, y = price), alpha = 0.2)
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = color, y = price))
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = reorder(clarity, price, FUN = median), y = price))
ggplot(data = diamonds) +
geom_point(mapping = aes(x = table, y = price), alpha = 0.1)
str(diamonds)
range(diamonds$table)
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = cut, y = carat))
# 3
library(ggstance)
??ggstance
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = color, y = price)) +
coord_flip()
ggplot(data = diamonds) +
geom_boxploth(mapping = aes(x = price, y = color))
# 4
# library(lvplot)
# ggplot(data = diamonds) +
# geom_lv(mapping = aes(x = cut, y = price))
# 5
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = color, y = price))
ggplot(data = diamonds) +
geom_violin(mapping = aes(x = color, y = price))
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = price)) +
facet_wrap(~color)
ggplot(data = diamonds) +
geom_freqpoly(mapping = aes(x = price, y = ..density.., color = color), binwidth = 500)
# 6
library(ggbeeswarm)
R.Version()
?`ggbeeswarm-package`
ggplot(data = diamonds, mapping = aes(x = color, y = price)) +
geom_point() +
geom_jitter()
ggplot(data = diamonds, mapping = aes(x = color, y = price)) +
geom_quasirandom()
# 7.5.2 Two categorical variables !!!!!This is awesome!!!!!!
ggplot(data = diamonds) +
geom_count(mapping = aes(x = cut, y = color))
diamonds %>%
count(cut, color)
diamonds %>%
count(cut, color) %>%
ggplot(mapping = aes(x = color, y = cut)) +
geom_tile(mapping = aes(fill = n))
?fill
# 7.5.2.1 Exercises
# 1
diamonds %>%
count(cut, color) %>%
ggplot(mapping = aes(x = color, y = cut)) +
geom_tile(mapping = aes(fill = n)) +
scale_fill_continuous(low = 'black', high = 'white')
# 2
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
ggplot(mapping = aes(x = month, y = dest)) +
geom_point(mapping = aes(fill = Av_delay)) +
geom_jitter()
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
ggplot() +
geom_boxplot(mapping = aes(x = as.factor(month), y = Av_delay))
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
ggplot() +
geom_line(mapping = aes(x = month, y = Av_delay))
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
filter(Av_delay > 20) %>%
ggplot() +
geom_tile(mapping = aes(x = dest, y = month, fill = Av_delay))
# 7.5.3 Two Continuous variables
smaller <- diamonds %>%
filter(carat < 3)
ggplot(data = smaller) +
geom_bin2d(mapping = aes(x = carat, y = price))
library(hexbin)
ggplot(data = smaller) +
geom_hex(mapping = aes(x = carat, y = price))
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_boxplot(mapping = aes(group = cut_width(carat, 0.1)))
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_boxplot(mapping = aes(group = cut_number(carat, 20)))
# 7.5.3.1 Exercises
# 1
ggplot(data = smaller, mapping = aes(x = carat)) +
geom_freqpoly(mapping = aes(group = cut_width(carat, 0.1)))
# 2
ggplot(data = smaller, mapping = aes(x = price, y = carat)) +
geom_boxplot(mapping = aes(group = cut_number(price, 20)))
# 4 STUCK HERE
# ggplot(data = smaller, mapping = aes(x = cut, y = price)) +
# geom_boxplot() +
# facet_wrap(group = cut_number(carat, 3), nrow = 1, ncol = 3)
ggplot(data = smaller, mapping = aes(x = price, group = cut_number(carat, 3))) +
geom_freqpoly(mapping = aes(colour = cut)) +
facet_wrap(~group)
ggplot(data = smaller, mapping = aes(x = price, y = ..density..)) +
geom_freqpoly(mapping = aes(color = cut_number(carat, 3))) +
facet_wrap(~ cut)
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_hex(mapping = aes(fill = cut))
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_point(mapping = aes(color = cut), alpha = 0.3)
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_point(alpha = 0.2) +
facet_wrap(~ cut)
# 7.6 Patterns and models
ggplot(data = diamonds) +
geom_point(mapping = aes(x = carat, y = price))
library(modelr)
mod <- lm(log(price) ~ log(carat), data = diamonds)
diamonds2 <- diamonds %>%
add_residuals(mod) %>%
mutate(resid = exp(resid))
ggplot(data = diamonds2) +
geom_point(mapping = aes(x = carat, y = resid))
ggplot(data = diamonds2) +
geom_boxplot(mapping = aes(x = cut, y = resid))
| /07_ExploratoryDataAnalysis.R | no_license | jonleslie/R_for_Data_Science | R | false | false | 7,490 | r | library(tidyverse)
library(nycflights13)
# 7.3 Variation
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut))
diamonds %>%
count(cut)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)
diamonds %>%
count(cut_width(x = carat, 0.5))
ggplot(data = diamonds) +
geom_freqpoly(mapping = aes(x = carat, colour = cut), binwidth = 0.1)
?geom_freqpoly
# 7.3.4 Exercises
# 1
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = z), binwidth = 0.5)
diamonds %>%
filter(x > 3) %>%
ggplot() +
geom_histogram(mapping = aes(x = x), binwidth = 0.5)
diamonds %>%
filter(z < 2 | z > 10) %>%
arrange(z)
# 2
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = price), binwidth = 50)
diamonds %>%
filter(price < 2000) %>%
ggplot() +
geom_histogram(mapping = aes(x = price), binwidth = 10)
# 3
range(diamonds$carat)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)
diamonds %>%
filter(carat > 0.9 & carat < 1.1) %>%
ggplot() +
geom_histogram(mapping = aes(x = carat))
# 4
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat))
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat)) +
coord_cartesian(ylim = c(0, 1000))
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat)) +
ylim(0,1000)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5) +
coord_cartesian(xlim = c(0, 1.0))
# 7.4 Missing values
diamonds2 <- diamonds %>%
mutate(y = ifelse(y < 3 | y > 20, NA, y))
ggplot(data = flights) +
geom_histogram(mapping = aes(x = dep_time))
table(is.na(flights$dep_time))
ggplot(data = flights) +
geom_bar(mapping = aes(x = dep_time), na.rm = T)
sum(flights$dep_time)
?geom_histogram
?geom_bar
# 7.5 Covariance
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot()
ggplot(data = mpg, mapping = aes(x = reorder(class, hwy, FUN = median), y = hwy)) +
geom_boxplot()
ggplot(data = mpg, mapping = aes(x = reorder(class, hwy, FUN = median), y = hwy)) +
geom_boxplot() +
coord_flip()
# 7.5.1.1 Exercises
# 1
nycflights13::flights %>%
mutate(
cancelled = is.na(dep_time),
sched_hour = sched_dep_time %/% 100,
sched_min = sched_dep_time %% 100,
sched_dep_time = sched_hour + sched_min / 60
) %>%
ggplot(mapping = aes(sched_dep_time)) +
geom_freqpoly(mapping = aes(colour = cancelled), binwidth = 1/4)
nycflights13::flights %>%
mutate(
cancelled = is.na(dep_time),
sched_hour = sched_dep_time %/% 100,
sched_min = sched_dep_time %% 100,
sched_dep_time = sched_hour + sched_min / 60
) %>%
ggplot(mapping = aes(x = sched_dep_time, y = ..density..)) +
geom_freqpoly(mapping = aes(colour = cancelled), binwidth = 1)
# 2
names(diamonds)
ggplot(data = diamonds) +
geom_point(mapping = aes(x = carat, y = price), alpha = 0.2)
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = color, y = price))
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = reorder(clarity, price, FUN = median), y = price))
ggplot(data = diamonds) +
geom_point(mapping = aes(x = table, y = price), alpha = 0.1)
str(diamonds)
range(diamonds$table)
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = cut, y = carat))
# 3
library(ggstance)
??ggstance
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = color, y = price)) +
coord_flip()
ggplot(data = diamonds) +
geom_boxploth(mapping = aes(x = price, y = color))
# 4
# library(lvplot)
# ggplot(data = diamonds) +
# geom_lv(mapping = aes(x = cut, y = price))
# 5
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = color, y = price))
ggplot(data = diamonds) +
geom_violin(mapping = aes(x = color, y = price))
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = price)) +
facet_wrap(~color)
ggplot(data = diamonds) +
geom_freqpoly(mapping = aes(x = price, y = ..density.., color = color), binwidth = 500)
# 6
library(ggbeeswarm)
R.Version()
?`ggbeeswarm-package`
ggplot(data = diamonds, mapping = aes(x = color, y = price)) +
geom_point() +
geom_jitter()
ggplot(data = diamonds, mapping = aes(x = color, y = price)) +
geom_quasirandom()
# 7.5.2 Two categorical variables !!!!!This is awesome!!!!!!
ggplot(data = diamonds) +
geom_count(mapping = aes(x = cut, y = color))
diamonds %>%
count(cut, color)
diamonds %>%
count(cut, color) %>%
ggplot(mapping = aes(x = color, y = cut)) +
geom_tile(mapping = aes(fill = n))
?fill
# 7.5.2.1 Exercises
# 1
diamonds %>%
count(cut, color) %>%
ggplot(mapping = aes(x = color, y = cut)) +
geom_tile(mapping = aes(fill = n)) +
scale_fill_continuous(low = 'black', high = 'white')
# 2
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
ggplot(mapping = aes(x = month, y = dest)) +
geom_point(mapping = aes(fill = Av_delay)) +
geom_jitter()
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
ggplot() +
geom_boxplot(mapping = aes(x = as.factor(month), y = Av_delay))
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
ggplot() +
geom_line(mapping = aes(x = month, y = Av_delay))
flights %>%
group_by(month, dest) %>%
summarise(Av_delay = mean(dep_delay, na.rm = T)) %>%
filter(Av_delay > 20) %>%
ggplot() +
geom_tile(mapping = aes(x = dest, y = month, fill = Av_delay))
# 7.5.3 Two Continuous variables
smaller <- diamonds %>%
filter(carat < 3)
ggplot(data = smaller) +
geom_bin2d(mapping = aes(x = carat, y = price))
library(hexbin)
ggplot(data = smaller) +
geom_hex(mapping = aes(x = carat, y = price))
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_boxplot(mapping = aes(group = cut_width(carat, 0.1)))
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_boxplot(mapping = aes(group = cut_number(carat, 20)))
# 7.5.3.1 Exercises
# 1
ggplot(data = smaller, mapping = aes(x = carat)) +
geom_freqpoly(mapping = aes(group = cut_width(carat, 0.1)))
# 2
ggplot(data = smaller, mapping = aes(x = price, y = carat)) +
geom_boxplot(mapping = aes(group = cut_number(price, 20)))
# 4 STUCK HERE
# ggplot(data = smaller, mapping = aes(x = cut, y = price)) +
# geom_boxplot() +
# facet_wrap(group = cut_number(carat, 3), nrow = 1, ncol = 3)
ggplot(data = smaller, mapping = aes(x = price, group = cut_number(carat, 3))) +
geom_freqpoly(mapping = aes(colour = cut)) +
facet_wrap(~group)
ggplot(data = smaller, mapping = aes(x = price, y = ..density..)) +
geom_freqpoly(mapping = aes(color = cut_number(carat, 3))) +
facet_wrap(~ cut)
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_hex(mapping = aes(fill = cut))
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_point(mapping = aes(color = cut), alpha = 0.3)
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_point(alpha = 0.2) +
facet_wrap(~ cut)
# 7.6 Patterns and models
ggplot(data = diamonds) +
geom_point(mapping = aes(x = carat, y = price))
library(modelr)
mod <- lm(log(price) ~ log(carat), data = diamonds)
diamonds2 <- diamonds %>%
add_residuals(mod) %>%
mutate(resid = exp(resid))
ggplot(data = diamonds2) +
geom_point(mapping = aes(x = carat, y = resid))
ggplot(data = diamonds2) +
geom_boxplot(mapping = aes(x = cut, y = resid))
|
#!/usr/bin/env Rscript
# Copyright by Daniel Loos
#
# Research Group Systems Biology and Bioinformatics - Head: Assoc. Prof. Dr. Gianni Panagiotou
# https://www.leibniz-hki.de/en/systembiologie-und-bioinformatik.html
# Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Institute (HKI)
# Adolf-Reichwein-Straße 23, 07745 Jena, Germany
#
# The project code is licensed under BSD 2-Clause.
# See the LICENSE file provided with the code for the full license.
#
# Interactive project discovery module
#
projects_mod_UI <- function(id) {
ns <- shiny::NS(id)
shiny::fluidPage(
width = NULL,
shiny::h1("Database of fungal projects"),
shiny::selectizeInput(
inputId = ns("current_project"),
label = "Project",
choices = c("no project available"),
multiple = FALSE,
selected = "no project available"
),
shiny::htmlOutput(ns("project_description")) %>% withSpinner(),
ggiraph::girafeOutput(ns("samples_distribution")) %>% withSpinner()
)
}
projects_mod <- function(input, output, session) {
projects_l <- projects_tbl$bioproject_id
names(projects_l) <- projects_tbl$name
shiny::updateSelectizeInput(
session = session,
inputId = "current_project",
choices = projects_l,
selected = projects_l[1],
server = TRUE
)
samples_tbl <- shiny::reactive({
external_samples_tbl %>%
danielLib::filter_samples(input$current_project) %>%
dplyr::rename(bioproject_id = project)
})
current_project <- shiny::reactive({
current_project_tbl <-
projects_tbl %>%
dplyr::filter(bioproject_id == input$current_project) %>%
tidyr::gather(key, value)
res <- current_project_tbl$value
names(res) <- current_project_tbl$key
res
})
output$project_description <- shiny::renderUI({
samples_tbl() %>%
nrow() %>%
magrittr::is_greater_than(0) %>%
shiny::req()
shiny::tagList(
shiny::tags$h3(current_project()["name"]),
shiny::tags$p(current_project()["description"])
)
})
output$samples_distribution <- ggiraph::renderGirafe({
shiny::need(
expr = samples_tbl() %>% nrow() > 0,
message = "Please select a project"
) %>% shiny::validate()
plot_tbl <-
samples_tbl() %>%
danielLib::guess_coltypes() %>%
dplyr::select(-bioproject_id)
shiny::need(
expr = plot_tbl %>% select_if(~ is.logical(.x) || is.factor(.x)) %>% ncol() > 0,
message = "No sample attributes available"
) %>% shiny::validate()
samples_distribution_plt <- danielLib::plot_samples_distribution(plot_tbl, bg_color = bg_color)
ggiraph::girafe(ggobj = samples_distribution_plt)
})
}
| /front_end/modules/projects_mod.R | permissive | danlooo/DAnIEL | R | false | false | 2,713 | r | #!/usr/bin/env Rscript
# Copyright by Daniel Loos
#
# Research Group Systems Biology and Bioinformatics - Head: Assoc. Prof. Dr. Gianni Panagiotou
# https://www.leibniz-hki.de/en/systembiologie-und-bioinformatik.html
# Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Institute (HKI)
# Adolf-Reichwein-Straße 23, 07745 Jena, Germany
#
# The project code is licensed under BSD 2-Clause.
# See the LICENSE file provided with the code for the full license.
#
# Interactive project discovery module
#
projects_mod_UI <- function(id) {
ns <- shiny::NS(id)
shiny::fluidPage(
width = NULL,
shiny::h1("Database of fungal projects"),
shiny::selectizeInput(
inputId = ns("current_project"),
label = "Project",
choices = c("no project available"),
multiple = FALSE,
selected = "no project available"
),
shiny::htmlOutput(ns("project_description")) %>% withSpinner(),
ggiraph::girafeOutput(ns("samples_distribution")) %>% withSpinner()
)
}
projects_mod <- function(input, output, session) {
projects_l <- projects_tbl$bioproject_id
names(projects_l) <- projects_tbl$name
shiny::updateSelectizeInput(
session = session,
inputId = "current_project",
choices = projects_l,
selected = projects_l[1],
server = TRUE
)
samples_tbl <- shiny::reactive({
external_samples_tbl %>%
danielLib::filter_samples(input$current_project) %>%
dplyr::rename(bioproject_id = project)
})
current_project <- shiny::reactive({
current_project_tbl <-
projects_tbl %>%
dplyr::filter(bioproject_id == input$current_project) %>%
tidyr::gather(key, value)
res <- current_project_tbl$value
names(res) <- current_project_tbl$key
res
})
output$project_description <- shiny::renderUI({
samples_tbl() %>%
nrow() %>%
magrittr::is_greater_than(0) %>%
shiny::req()
shiny::tagList(
shiny::tags$h3(current_project()["name"]),
shiny::tags$p(current_project()["description"])
)
})
output$samples_distribution <- ggiraph::renderGirafe({
shiny::need(
expr = samples_tbl() %>% nrow() > 0,
message = "Please select a project"
) %>% shiny::validate()
plot_tbl <-
samples_tbl() %>%
danielLib::guess_coltypes() %>%
dplyr::select(-bioproject_id)
shiny::need(
expr = plot_tbl %>% select_if(~ is.logical(.x) || is.factor(.x)) %>% ncol() > 0,
message = "No sample attributes available"
) %>% shiny::validate()
samples_distribution_plt <- danielLib::plot_samples_distribution(plot_tbl, bg_color = bg_color)
ggiraph::girafe(ggobj = samples_distribution_plt)
})
}
|
Points <- function(x, y, pch=1, centers=FALSE, scale=1, cex.min=1, col=1, na.omit=TRUE, plot=TRUE, ...)
{
M.s <- na.omit(cbind(x, y))
if (na.omit) {
s <- paste(M.s[, 1], M.s[, 2])
} else {
s <- paste(x, y)
}
TAB.s <- table(s)
TAB.x <- as.numeric(unlist(strsplit(names(TAB.s), " "))[seq(1, 2*length(TAB.s), by=2)])
TAB.y <- as.numeric(unlist(strsplit(names(TAB.s), " "))[seq(2, 2*length(TAB.s), by=2)])
addsize <- (as.numeric(cut(TAB.s, 7)) - 1) * scale
if(plot) {
points(TAB.x, TAB.y, cex=cex.min + addsize, pch=pch, col=col, ...)
if (centers) points(TAB.x, TAB.y, cex=1, pch=".", col=col)
}
invisible(as.numeric(Recode(s, names(TAB.s), TAB.s)))
}
## ===
PPoints <- function(groups, x, y, cols=as.numeric(groups), pchs=as.numeric(groups), na.omit.all=TRUE, ...)
{
if (na.omit.all) {
D <- na.omit(data.frame(groups=groups, x=x, y=y))
x <- D$x ; y <- D$y ; groups <- D$groups
}
if (!is.factor(groups)) stop("Grouping variable must be a factor")
n <- nlevels(groups)
a <- as.numeric(groups)
if (length(pchs) == 1) pchs <- rep(pchs, length(groups))
if (length(cols) == 1) cols <- rep(cols, length(groups))
na.omit <- !na.omit.all # to save resources
res <- numeric(length(x))
for (i in 1:n) {
res[a == i] <- Points(x[a==i], y[a==i], col=(cols[a==i]), pch=(pchs[a==i]), na.omit=na.omit, ...)
}
invisible(res)
}
| /R/ppoints.r | no_license | cran/shipunov | R | false | false | 1,338 | r | Points <- function(x, y, pch=1, centers=FALSE, scale=1, cex.min=1, col=1, na.omit=TRUE, plot=TRUE, ...)
{
M.s <- na.omit(cbind(x, y))
if (na.omit) {
s <- paste(M.s[, 1], M.s[, 2])
} else {
s <- paste(x, y)
}
TAB.s <- table(s)
TAB.x <- as.numeric(unlist(strsplit(names(TAB.s), " "))[seq(1, 2*length(TAB.s), by=2)])
TAB.y <- as.numeric(unlist(strsplit(names(TAB.s), " "))[seq(2, 2*length(TAB.s), by=2)])
addsize <- (as.numeric(cut(TAB.s, 7)) - 1) * scale
if(plot) {
points(TAB.x, TAB.y, cex=cex.min + addsize, pch=pch, col=col, ...)
if (centers) points(TAB.x, TAB.y, cex=1, pch=".", col=col)
}
invisible(as.numeric(Recode(s, names(TAB.s), TAB.s)))
}
## ===
PPoints <- function(groups, x, y, cols=as.numeric(groups), pchs=as.numeric(groups), na.omit.all=TRUE, ...)
{
if (na.omit.all) {
D <- na.omit(data.frame(groups=groups, x=x, y=y))
x <- D$x ; y <- D$y ; groups <- D$groups
}
if (!is.factor(groups)) stop("Grouping variable must be a factor")
n <- nlevels(groups)
a <- as.numeric(groups)
if (length(pchs) == 1) pchs <- rep(pchs, length(groups))
if (length(cols) == 1) cols <- rep(cols, length(groups))
na.omit <- !na.omit.all # to save resources
res <- numeric(length(x))
for (i in 1:n) {
res[a == i] <- Points(x[a==i], y[a==i], col=(cols[a==i]), pch=(pchs[a==i]), na.omit=na.omit, ...)
}
invisible(res)
}
|
## makeCacheMatrix identifies the location of a cached (stored) inverse of a matrix. cacheSolve, the first time it is run,
## calculates the inverse of a matrix and stores it at a location identified in makeCacheMatrix. Each subsequent call to
## cacheSolve produces the matrix inverse without having to recalculate it.
## Input a square matrix, for example Zed <- makeCacheMatrix(matrix_y), and run it. Input Zed into
## cacheSolve as cacheSolve(Zed). The first time cacheSolve is run it calculates the inverse of
## matrix_y. Each time cacheSolve(Zed) is run thereafter it will call the inverse from cache with the
## message "getting cached data".
## makeCacheMatrix traces the location of four objects: 1) set assigns the input matrix x to y 2) get gets
## the value of the x matrix 3) setmatrix sets the value of the inverse matrix and 4) getmatrix gets the
## inverse matrix Minv
## The input matrix must be square otherwise the function will throw an error
makeCacheMatrix <- function(x = matrix()) {
Minv <- NULL
set <- function(y){
x <<- y #Set x to y
Minv <<- NULL #set matrix inverse to NULL
}
get <- function() x #Get matrix that will be inverted
setinv <- function(solve) Minv <<- solve #Set the value of inverse of matrix x
getinv <- function() Minv #Get the location for the value of the inverse
list(set = set, get = get, #Output the locations of the above to a list
setinv = setinv,
getinv = getinv)
}
## cacheSolve computes the inverse of the matrix output from makeCacheMatrix above.
## If the inverse has already been calculated and not changed it is retrieved from the cache.
cacheSolve <- function(x, ...) {
#input to cacheSolve is the assigned value of makeCacheMatrix, e.g. Zmat <- makeCacheMatrix(x), so
#input Zmat into cacheSolve, for example, cacheSolve(Zmat)
Minv <- x$getinv() #get the matrix inverse from cache
if(!is.null(Minv)){ #If it is in the cache return it
message("getting cached data")
return(Minv)
}
data <- x$get() #If not in the cache get the data and calculate the inverse
Minv <- solve(data,...)
x$setinv(Minv) #Set the value of the inverse in the cache such that on the
#next call to cacheSolve it is not recalculated, note that
#x$setinv(Minv) puts Minv in makeCacheMatrix
Minv #Output the inverse matrix
}
| /cachematrix.R | no_license | Tomdavan/ProgrammingAssignment2 | R | false | false | 2,714 | r |
## makeCacheMatrix identifies the location of a cached (stored) inverse of a matrix. cacheSolve, the first time it is run,
## calculates the inverse of a matrix and stores it at a location identified in makeCacheMatrix. Each subsequent call to
## cacheSolve produces the matrix inverse without having to recalculate it.
## Input a square matrix, for example Zed <- makeCacheMatrix(matrix_y), and run it. Input Zed into
## cacheSolve as cacheSolve(Zed). The first time cacheSolve is run it calculates the inverse of
## matrix_y. Each time cacheSolve(Zed) is run thereafter it will call the inverse from cache with the
## message "getting cached data".
## makeCacheMatrix traces the location of four objects: 1) set assigns the input matrix x to y 2) get gets
## the value of the x matrix 3) setmatrix sets the value of the inverse matrix and 4) getmatrix gets the
## inverse matrix Minv
## The input matrix must be square otherwise the function will throw an error
makeCacheMatrix <- function(x = matrix()) {
Minv <- NULL
set <- function(y){
x <<- y #Set x to y
Minv <<- NULL #set matrix inverse to NULL
}
get <- function() x #Get matrix that will be inverted
setinv <- function(solve) Minv <<- solve #Set the value of inverse of matrix x
getinv <- function() Minv #Get the location for the value of the inverse
list(set = set, get = get, #Output the locations of the above to a list
setinv = setinv,
getinv = getinv)
}
## cacheSolve computes the inverse of the matrix output from makeCacheMatrix above.
## If the inverse has already been calculated and not changed it is retrieved from the cache.
cacheSolve <- function(x, ...) {
#input to cacheSolve is the assigned value of makeCacheMatrix, e.g. Zmat <- makeCacheMatrix(x), so
#input Zmat into cacheSolve, for example, cacheSolve(Zmat)
Minv <- x$getinv() #get the matrix inverse from cache
if(!is.null(Minv)){ #If it is in the cache return it
message("getting cached data")
return(Minv)
}
data <- x$get() #If not in the cache get the data and calculate the inverse
Minv <- solve(data,...)
x$setinv(Minv) #Set the value of the inverse in the cache such that on the
#next call to cacheSolve it is not recalculated, note that
#x$setinv(Minv) puts Minv in makeCacheMatrix
Minv #Output the inverse matrix
}
|
model <- LogisticLogNormalSub(mean = c(-0.85, 1),
cov = matrix(c(1, -0.5, -0.5, 1), nrow = 2),
refDose = 50)
| /examples/Model-class-LogisticLogNormalSub.R | no_license | insightsengineering/crmPack | R | false | false | 167 | r |
model <- LogisticLogNormalSub(mean = c(-0.85, 1),
cov = matrix(c(1, -0.5, -0.5, 1), nrow = 2),
refDose = 50)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/rapt_extend.R
\name{intensity.pp3-deprecated}
\alias{intensity.pp3-deprecated}
\title{Extends \code{\link[spatstat.geom]{intensity}} to \code{\link[spatstat.geom]{pp3}}.}
\description{
Extends \code{\link[spatstat.geom]{intensity}} to \code{\link[spatstat.geom]{pp3}}.
}
\seealso{
\code{\link{rapt-deprecated}}
}
\keyword{internal}
| /man/intensity.pp3-deprecated.Rd | no_license | aproudian2/rapt | R | false | true | 410 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/rapt_extend.R
\name{intensity.pp3-deprecated}
\alias{intensity.pp3-deprecated}
\title{Extends \code{\link[spatstat.geom]{intensity}} to \code{\link[spatstat.geom]{pp3}}.}
\description{
Extends \code{\link[spatstat.geom]{intensity}} to \code{\link[spatstat.geom]{pp3}}.
}
\seealso{
\code{\link{rapt-deprecated}}
}
\keyword{internal}
|
## To create a mtrix inverse and caching the inverse in separate environment
##It creates the list of functions used by cachesolve function(like get or set)
makeCacheMatrix <- function(x = matrix()) {
#initialize to null
cache <- NULL
#matrix creation in present env.
set <- function(y) {
x <<- y
cache <<- NULL
}
#get matrix
get <- function() x
#inverting matrix
setMatrix <- function(inverse) cache <<- inverse
#getting inverted matrix
getInverse <- function() cache
#returning list
list(set = set, get = get,
setMatrix = setMatrix,
getInverse = getInverse)
}
##Solves the matrix if it not found in cache in envvironment.
cacheSolve <- function(x, ...) {
#get the inverse from cache if it is there
cache <- x$getInverse()
#if found the inverse in cache it returns
if (!is.null(cache)) {
message("cached data")
return(cache)
}
#ifnot found creates the matrix
matrix <- x$get()
#inverses the matrix
cache <- solve(matrix, ...)
#puts it in cache
x$setMatrix(cache)
#return the cache
return (cache)
}
| /cachematrix.R | no_license | jaswanthreddy01/ProgrammingAssignment2 | R | false | false | 1,170 | r |
## To create a mtrix inverse and caching the inverse in separate environment
##It creates the list of functions used by cachesolve function(like get or set)
makeCacheMatrix <- function(x = matrix()) {
#initialize to null
cache <- NULL
#matrix creation in present env.
set <- function(y) {
x <<- y
cache <<- NULL
}
#get matrix
get <- function() x
#inverting matrix
setMatrix <- function(inverse) cache <<- inverse
#getting inverted matrix
getInverse <- function() cache
#returning list
list(set = set, get = get,
setMatrix = setMatrix,
getInverse = getInverse)
}
##Solves the matrix if it not found in cache in envvironment.
cacheSolve <- function(x, ...) {
#get the inverse from cache if it is there
cache <- x$getInverse()
#if found the inverse in cache it returns
if (!is.null(cache)) {
message("cached data")
return(cache)
}
#ifnot found creates the matrix
matrix <- x$get()
#inverses the matrix
cache <- solve(matrix, ...)
#puts it in cache
x$setMatrix(cache)
#return the cache
return (cache)
}
|
ml_index_labels_metadata <- function(label_indexer_model, dataset, label_col) {
transformed_tbl <- ml_transform(label_indexer_model, dataset)
label_col <- if (inherits(label_indexer_model, "ml_r_formula_model"))
ml_param(label_indexer_model, "label_col")
else
ml_param(label_indexer_model, "output_col")
ml_column_metadata(transformed_tbl, label_col) %>%
`[[`("vals")
}
ml_feature_names_metadata <- function(pipeline_model, dataset, features_col) {
preprocessor <- ml_stage(pipeline_model, 1)
transformed_tbl <- ml_transform(preprocessor, dataset)
features_col <- if (inherits(preprocessor, "ml_r_formula_model"))
ml_param(preprocessor, "features_col")
else # vector assembler
ml_param(preprocessor, "output_col")
ml_column_metadata(transformed_tbl, features_col) %>%
`[[`("attrs") %>%
dplyr::bind_rows() %>%
dplyr::arrange(!!rlang::sym("idx")) %>%
dplyr::pull("name")
}
| /R/ml_model_utils.R | permissive | tnixon/sparklyr | R | false | false | 929 | r | ml_index_labels_metadata <- function(label_indexer_model, dataset, label_col) {
transformed_tbl <- ml_transform(label_indexer_model, dataset)
label_col <- if (inherits(label_indexer_model, "ml_r_formula_model"))
ml_param(label_indexer_model, "label_col")
else
ml_param(label_indexer_model, "output_col")
ml_column_metadata(transformed_tbl, label_col) %>%
`[[`("vals")
}
ml_feature_names_metadata <- function(pipeline_model, dataset, features_col) {
preprocessor <- ml_stage(pipeline_model, 1)
transformed_tbl <- ml_transform(preprocessor, dataset)
features_col <- if (inherits(preprocessor, "ml_r_formula_model"))
ml_param(preprocessor, "features_col")
else # vector assembler
ml_param(preprocessor, "output_col")
ml_column_metadata(transformed_tbl, features_col) %>%
`[[`("attrs") %>%
dplyr::bind_rows() %>%
dplyr::arrange(!!rlang::sym("idx")) %>%
dplyr::pull("name")
}
|
context("utility data")
test_that("utility data 2.0 files read correctly", {
d <- read_sdmx(
system.file("extdata/utility_2.0.xml", package = "readsdmx")
)
expect_equal(nrow(d), 12)
expect_equal(ncol(d), 14)
expect_equal(d[1, "OBS_VALUE"], "3.14")
expect_equal(d[1, "FREQ"], "M")
expect_equal(unique(d[["JD_CATEGORY"]]), "A")
expect_equal(unique(d[["JD_TYPE"]]), "P")
expect_equal(unique(d[["VIS_CTY"]]), "MX")
expect_equal(d[3, "TIME_PERIOD"], "2000-03")
expect_equal(d[3, "OBS_VALUE"], "5.26")
expect_equal(d[11, "OBS_VALUE"], "3.19")
expect_equal(d[11, "TIME_PERIOD"], "2000-11")
expect_equal(d[12, "OBS_VALUE"], "3.14")
})
| /tests/testthat/test_utility.R | no_license | mdequeljoe/readsdmx | R | false | false | 666 | r | context("utility data")
test_that("utility data 2.0 files read correctly", {
d <- read_sdmx(
system.file("extdata/utility_2.0.xml", package = "readsdmx")
)
expect_equal(nrow(d), 12)
expect_equal(ncol(d), 14)
expect_equal(d[1, "OBS_VALUE"], "3.14")
expect_equal(d[1, "FREQ"], "M")
expect_equal(unique(d[["JD_CATEGORY"]]), "A")
expect_equal(unique(d[["JD_TYPE"]]), "P")
expect_equal(unique(d[["VIS_CTY"]]), "MX")
expect_equal(d[3, "TIME_PERIOD"], "2000-03")
expect_equal(d[3, "OBS_VALUE"], "5.26")
expect_equal(d[11, "OBS_VALUE"], "3.19")
expect_equal(d[11, "TIME_PERIOD"], "2000-11")
expect_equal(d[12, "OBS_VALUE"], "3.14")
})
|
p=1; px=c(25,50,100,150,200); pp=c(4,16:18,15)
sx=as.numeric(rownames(fitm2$fitratio))[ c(1, seq(0,200, 10)[-1]) ]
set.seed(28)
sx1 = c(seq(0.01, 0.09, length.out = 40), 0.1 )
x1=sapply(sx1, function(i) wfsim(i,N=1000,start=50,len=200)) %>% reshape2::melt()
x1$col = rep(sx1, each=200)
x=x1[x1$value<1000,]
g = ggplot(x, aes(x=Var1, y=value, group=Var2, color=col, size=col)) +
geom_line(alpha=0.3) +
scale_size(range=c(0.1,2)) +
scale_color_viridis_c() +
theme_dark() +
coord_cartesian(xlim=c(55,180), ylim=c(5,1002), expand=0)+
annotate("text", x=176, y=900, label=
("Visualizing\nYour Data\nUsing\nR"),
hjust="right",vjust="top",
color=rgb(1,1,1,0.7) , size=16, fontface="bold") +
annotate("text", x=176, y=155, label=
("Workshop @ CDCS\nNovember 1, 2019"),
hjust="right",vjust="top",
color=rgb(1,1,1,0.7) , size=7, fontface="bold") +
theme(
plot.background = element_rect(fill="gray6", color="gray6"),
panel.background = element_rect(fill="gray6", color="gray6"),
panel.grid = element_line(color="gray3"),
axis.title = element_blank(),
legend.position = "none",
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(0,0,0,0), "mm")
)
ggsave("banner.png", g, device = "png", width = 1.75*6, height = 0.8*6, dpi = 600)
| /cdcs2019/bannerscript.R | permissive | andreskarjus/artofthefigure | R | false | false | 1,423 | r |
p=1; px=c(25,50,100,150,200); pp=c(4,16:18,15)
sx=as.numeric(rownames(fitm2$fitratio))[ c(1, seq(0,200, 10)[-1]) ]
set.seed(28)
sx1 = c(seq(0.01, 0.09, length.out = 40), 0.1 )
x1=sapply(sx1, function(i) wfsim(i,N=1000,start=50,len=200)) %>% reshape2::melt()
x1$col = rep(sx1, each=200)
x=x1[x1$value<1000,]
g = ggplot(x, aes(x=Var1, y=value, group=Var2, color=col, size=col)) +
geom_line(alpha=0.3) +
scale_size(range=c(0.1,2)) +
scale_color_viridis_c() +
theme_dark() +
coord_cartesian(xlim=c(55,180), ylim=c(5,1002), expand=0)+
annotate("text", x=176, y=900, label=
("Visualizing\nYour Data\nUsing\nR"),
hjust="right",vjust="top",
color=rgb(1,1,1,0.7) , size=16, fontface="bold") +
annotate("text", x=176, y=155, label=
("Workshop @ CDCS\nNovember 1, 2019"),
hjust="right",vjust="top",
color=rgb(1,1,1,0.7) , size=7, fontface="bold") +
theme(
plot.background = element_rect(fill="gray6", color="gray6"),
panel.background = element_rect(fill="gray6", color="gray6"),
panel.grid = element_line(color="gray3"),
axis.title = element_blank(),
legend.position = "none",
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(0,0,0,0), "mm")
)
ggsave("banner.png", g, device = "png", width = 1.75*6, height = 0.8*6, dpi = 600)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.