blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
327
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
91
| license_type
stringclasses 2
values | repo_name
stringlengths 5
134
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 46
values | visit_date
timestamp[us]date 2016-08-02 22:44:29
2023-09-06 08:39:28
| revision_date
timestamp[us]date 1977-08-08 00:00:00
2023-09-05 12:13:49
| committer_date
timestamp[us]date 1977-08-08 00:00:00
2023-09-05 12:13:49
| github_id
int64 19.4k
671M
⌀ | star_events_count
int64 0
40k
| fork_events_count
int64 0
32.4k
| gha_license_id
stringclasses 14
values | gha_event_created_at
timestamp[us]date 2012-06-21 16:39:19
2023-09-14 21:52:42
⌀ | gha_created_at
timestamp[us]date 2008-05-25 01:21:32
2023-06-28 13:19:12
⌀ | gha_language
stringclasses 60
values | src_encoding
stringclasses 24
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 7
9.18M
| extension
stringclasses 20
values | filename
stringlengths 1
141
| content
stringlengths 7
9.18M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35af5b40e5a0c4ae21474e856243a5766256eab3
|
c9a3d2e2c5ee33ec96691e85c4c01517c1c83b08
|
/Data_Science_with_R/8_Deploying_to_Production/simple_shiny_app.R
|
ffa2cbfc704a4d78b1691a5913d1dab463a1225a
|
[] |
no_license
|
glegru/pluralsight
|
61d010dd542f325d31b6fc6d34b1cdc2c2276961
|
7bb9707c69e8e252e35d1267df4d73eb969c25f0
|
refs/heads/master
| 2021-01-01T19:43:56.936734
| 2017-10-24T14:55:34
| 2017-10-24T14:55:34
| 98,661,031
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 871
|
r
|
simple_shiny_app.R
|
# simple_shiny_app.R
# Further exploration of shiny, especially the ui and server interactions.
# date: 2017-09-15
# Needed : install.packages("shiny") # the Shiny R framework
# -------------------------------------------------------
library(shiny)
# ui
ui <- fluidPage(
titlePanel("Input and Output"),
sidebarLayout(
sidebarPanel(
sliderInput(
inputId = "num",
label = "Choose a Number",
min = 0,
max = 100,
value = 25
)
),
mainPanel(
textOutput(
outputId = "text"
)
)
)
)
# server
server <- function(input, output) {
output$text <- renderText({
paste("You selected ", input$num)
})
}
# create the actual shiny app
shinyApp(
ui = ui,
server = server
)
|
5df17749e40b697b4e40665d82abdaad03324f78
|
4d9162efdb96e47c794129359a799b58c865b276
|
/man/evaluate_CV.Rd
|
fdcc8d5d24fc2fb488e4934e461ea9ce0e788b39
|
[] |
no_license
|
cran/convoSPAT
|
a0b83dfc61315b999d44bafe1015760784979f58
|
2073c51e8630a7edc1e9682aa1e77927f1d5ed50
|
refs/heads/master
| 2021-06-22T17:02:49.412275
| 2021-01-15T23:50:04
| 2021-01-15T23:50:04
| 39,428,854
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,082
|
rd
|
evaluate_CV.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/convoSPAT_summplot.R
\name{evaluate_CV}
\alias{evaluate_CV}
\title{Evaluation criteria}
\usage{
evaluate_CV(holdout.data, pred.mean, pred.SDs)
}
\arguments{
\item{holdout.data}{Observed/true data that has been held out for model
comparison.}
\item{pred.mean}{Predicted mean values corresponding to the hold-out
locations.}
\item{pred.SDs}{Predicted standard errors corresponding to the hold-out
locations.}
}
\value{
A list with the following components:
\item{CRPS}{The CRPS averaged over all hold-out locations.}
\item{MSPE}{The mean squared prediction error.}
\item{pMSDR}{The prediction mean square deviation ratio.}
}
\description{
Calculate three evaluation criteria -- continuous rank probability score
(CRPS), prediction mean square deviation ratio (pMSDR), and mean squared prediction
error (MSPE) -- comparing hold-out data and predictions.
}
\examples{
\dontrun{
evaluate_CV( holdout.data = simdata$sim.data[holdout.index],
pred.mean = pred.NS$pred.means, pred.SDs = pred.NS$pred.SDs )
}
}
|
8ce42f4acd44407e992daeec129e7b8ba92b9cfc
|
cd2e6a05bbf1196bf447f7b447b01f0790f81e04
|
/ch4-classification/4.R-classification-in-R/k-nearest-neighbors/4.6.5-k-nearest-neighbors.R
|
90ac573f668184530434211ac8f277427e6f5ded
|
[] |
no_license
|
AntonioPelayo/stanford-statistical-learning
|
d534a54b19f06bc5c69a3981ffa6b57ea418418f
|
c4e83b25b79a474426bb24a29110a881174c5634
|
refs/heads/master
| 2022-04-21T07:33:00.988232
| 2020-04-22T05:44:46
| 2020-04-22T05:44:46
| 242,658,021
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 671
|
r
|
4.6.5-k-nearest-neighbors.R
|
# 4.6.5 K-Nearest Neighbors
library(class)
attach(Smarket)
# Split data for train and test
train = (Year < 2005)
train.X = cbind(Lag1, Lag2)[train,] # Train predictors
test.X = cbind(Lag1, Lag2)[!train,] # Test predictors
train.Direction = Direction[train] # Direction labels for train data
# Predict movement with one neighbor
set.seed(1)
knn.pred = knn(train.X, test.X, train.Direction, k=1)
table(knn.pred, Direction.2005) # Observe 50% correct observations
# Predict with 3 neighbors
knn.pred = knn(train.X, test.X, train.Direction, k=3)
table(knn.pred, Direction.2005)
mean(knn.pred == Direction.2005) # 53.6% though still not better than QDA
|
b6f74133c6fcefa1488832e91697e729d0504a98
|
a4a6a8efee03e6cf1002f4062e07791f62dfff19
|
/Data_Preprocessing_Full.R
|
5c0115fde58de5c1113f483297a71ce5c1663dc0
|
[] |
no_license
|
Mahmoud333/Data-Preprocessing
|
092323a0a0aa9ecc74250b08db7607a4befe00ba
|
29375c24fee03ebc822cd61eb7b8864ee0b1a789
|
refs/heads/master
| 2021-05-15T03:11:18.430495
| 2017-09-30T10:20:45
| 2017-09-30T10:20:45
| 105,361,647
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,866
|
r
|
Data_Preprocessing_Full.R
|
# Data Preprocessing
#-- Importing the dataset
dataset = read.csv('Data.csv')
#dataset = dataset[, 2:3] subset of it
#-- Taking care of missing data
{dataset$Age = ifelse(is.na(dataset$Age), #true if missing, false if not missing
ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)), #true ,missing
dataset$Age) #false ,not missing
#$Age we taking the column age of dataset
#is.na function that tells if the value is missing or not
#checking if all the values of the column age are empty will return true
#ave average in R, average of column Age
#add function "FUN = " which is "mean" and its an existed function in R
#if value in column age is not missing then make "$Age = $Age"
dataset$Salary = ifelse(is.na(dataset$Salary),
ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)),
dataset$Salary)
}
#-- Encoding categorical data
#will use factor function
{
dataset$Country = factor(dataset$Country,
levels = c('France', 'Spain', 'Germany'),
labels = c(1 , 2 , 3)) #1 for france 2 for spain 3 for germany
dataset$Purchased = factor(dataset$Purchased,
levels = c('No', 'Yes'),
labels = c(0 , 1)) #1 for france 2 for spain 3 for germany
}
#-- Splitting the dataset into the Training set and Test set
# install.packages('caTools') comment it just download it once
library(caTools) #use the library by code or check it from packages tab
set.seed(123) #use seed to get same result, like we used random_state in python
split = sample.split( dataset$Purchased, SplitRatio = 0.8) #put only y in python we had to put X and y
#we hve to be careful in python we put the % of test set but here
#we have to put it for the train set
#will return true or false for each observation so each one will have true or false
#True observation goes to train set and False goes to test set
training_set = subset(dataset, split == TRUE) #subset of Our dataset, who's values are TRUE
test_set = subset(dataset, split == FALSE) #subset of Our dataset who's values are FALSE
#-- Feature Scaling #scale is already programmed function
{
training_set[, 2:3] = scale(training_set[,2:3]) #country and purschased are not numiric by default so we hve to specify the age and salary to scale them
test_set[, 2:3] = scale(test_set[, 2:3])
}
|
b292c30a8787141dafedfd156ebce9b57990b740
|
f29e1bbb05d7cf6c9136a6eb413038e2353d40f7
|
/R/zzz.R
|
3c3c5fdc9e176b9c9da52829b2f2b20d6c2633a5
|
[] |
no_license
|
LiamDBailey/climwin
|
46fdb4e668e125a8064de090473864d3aedd0c5e
|
3c28479c04ba858e83f6d6f3dcab8758d40e5751
|
refs/heads/master
| 2023-02-02T21:35:12.772236
| 2020-05-25T09:55:21
| 2020-05-25T09:55:21
| 32,844,500
| 12
| 10
| null | 2023-01-24T15:13:52
| 2015-03-25T05:29:40
|
R
|
UTF-8
|
R
| false
| false
| 270
|
r
|
zzz.R
|
.onAttach <- function(...) {
if (!interactive() || stats::runif(1) > 0.5) return()
intro <- c("To learn how to use climwin see our vignette. \n",
"See help documentation and release notes for details on changes."
)
packageStartupMessage(intro)
}
|
39b44764d2bff42ab5027ed7ed4315cda0ef4cb4
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/CoopGame/examples/getDualGameVector.Rd.R
|
18b42598ea91f7d8a025b9d29efa05417cdd879e
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 209
|
r
|
getDualGameVector.Rd.R
|
library(CoopGame)
### Name: getDualGameVector
### Title: Compute dual game vector
### Aliases: getDualGameVector
### ** Examples
library(CoopGame)
v<-unanimityGameVector(4,c(1,2))
getDualGameVector(v)
|
5d477bd154f37d69bea9a5704d8a8570d5cd9b8c
|
bdf1e6c71d3cc42492f0e3aa10abd42e9cc8b8ef
|
/R/xlsx_exp.R
|
3ffc904b84de37ceead39be17b6aa56dd2fa6116
|
[
"MIT"
] |
permissive
|
cristhianlarrahondo/cristhiansPackage
|
ec78aca1c3d5bd0ccbd1e10ed29d9a56055590b0
|
f58d3963949d49755276c133e1c794e96e12d58a
|
refs/heads/master
| 2023-05-03T07:47:02.932995
| 2021-05-11T19:05:11
| 2021-05-11T19:05:11
| 365,832,031
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,389
|
r
|
xlsx_exp.R
|
#' Exporting data into .xlsx files
#'
#' Exporting one or multiple tables into a .xlsx file.
#' If there are multiple tables, each one will be stored in the same file in
#' different sheets.
#'
#' @param data data frame or list of data frames
#' @param sheetnames character vector used to name each file sheet
#' @param filename character to name the exported file
#' @param path path where to store the file inside the working directory
#' @param keepNA logical, indicating if missing values should be displayed or
#' not. If TRUE, are displayed. Default set to FALSE. Note: if keepNA = TRUE,
#' and the column is numeric, it would turn into character.
#' @param colnames logical, indicating if column names should be in the output. If
#' true, column names are in the first row. Default set to TRUE.
#' @param rownames logical, indicating if row names should be in the output. If
#' true, row names are in the first column. Default set to TRUE.
#'
#' @return .xlsx file exported in the indicated path.
#' @export
#'
#' @examples
#' xlsx_exp(data = mtcars, filename = "prueba", rownames = TRUE)
xlsx_exp =
function(
data,
sheetnames = NULL,
filename,
path,
keepNA = F,
colnames = T,
rownames = F
) {
# data parameter checking:
## To list class: needed to use every list element as a
## workbook sheet
if (inherits(data, "list")) {
dt = data
} else {
dt = list(data)
}
# sheetnames parameter:
## There are three options:
### 1. list has its own names and sheetnames were given
### 2. list hasn't its own names and sheetnames weren't given
### 3. list hasn't its own names and sheetnames were given
### 4. list has its own names and sheetnames weren't given
if (is.null(names(dt))) {
if (is.null(sheetnames)) {
# Option 2:
sheetnames = paste0("Sheet", seq(1:length(dt)))
} else {
# Option 3
sheetnames = sheetnames
}
} else {
if (is.null(sheetnames)) {
# Option 4
sheetnames = names(dt)
} else {
# Option 1
sheetnames = sheetnames
warning("Although data has it's own names, user given sheetnames were used instead")
}
}
# Keep NA's or not
if (keepNA) {
kNA = T
message("Missing values will be displayed as NA")
} else {
kNA = F
message("Missing values will be empty")
}
# Defaults about colnames and rownames
if (colnames == T) {
CN = T
} else {
CN = F
}
if (rownames == T) {
RN = T
} else {
RN = F
}
# Creating the workbook
Wb = openxlsx::createWorkbook(".xlsx")
# Adding each sheet
for (i in 1:length(sheetnames)) {
openxlsx::addWorksheet(
wb = Wb, sheetName = sheetnames[i]
)
openxlsx::writeData(
wb = Wb,
sheet = i,
x = dt[[i]],
colNames = CN,
rowNames = RN,
keepNA = kNA
)
}
# Saving the file
if (missing(path)) {
openxlsx::saveWorkbook(
wb = Wb,
file = paste0(filename,".xlsx" ),
overwrite = T
)
message("Since there is not path, file saved in working directory")
} else {
openxlsx::saveWorkbook(
wb = Wb,
file = paste0("./",path,"/",filename,".xlsx" ),
overwrite = T
)
}
}
|
d7362448253fe4ef199e729fbc05ddc2a168650e
|
50819e94eaf31ca6360a1038b9079fc60abe738f
|
/Funmap2/R/zzz.r
|
95d3862a5eb79dbd057660a4ad6acda3f81e14bd
|
[] |
no_license
|
wzhy2000/R
|
a2176e5ff2260fed0213821406bea64ecd974866
|
2ce4d03e1ab8cffe2b59d8e7fee24e7a13948b88
|
refs/heads/master
| 2021-05-01T11:49:17.856170
| 2017-12-11T04:44:15
| 2017-12-11T04:44:15
| 23,846,343
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 810
|
r
|
zzz.r
|
.onAttach<- function(libname, pkgName)
{
date <- date();
x <- regexpr("[0-9]{4}", date);
yr <- substr(date, x[1], x[1] + attr(x, "match.length") - 1);
packageStartupMessage("||");
packageStartupMessage("|| Funmap2 Package v.2.5");
packageStartupMessage("|| Build date: ", date(), "");
packageStartupMessage("|| Copyright (C) 2011-", yr, ", http://statgen.psu.edu", sep="");
packageStartupMessage("|| Written by Zhong Wang(wzhy2000@hotmail.com)");
packageStartupMessage("||");
}
.onLoad<- function(libname, pkgName)
{
FM_sys <<- NULL;
FM2.curves <<- list();
FM2.covars <<- list();
FM2.crosss <<- list();
FM2.curve <<- NULL;
FM2.covar <<- NULL;
FM2.cross <<- NULL;
FM2.start();
ZZZ.regcovar();
ZZZ.regcross();
ZZZ.regcurve();
ZZZ.regmodel();
}
|
352a4a9d6d94700b878d240eeb438bffb0a1bae5
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/ggalt/examples/geom_bkde2d.Rd.R
|
21a18e3a798671ce92c1f6813b4b605b62012463
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 970
|
r
|
geom_bkde2d.Rd.R
|
library(ggalt)
### Name: geom_bkde2d
### Title: Contours from a 2d density estimate.
### Aliases: geom_bkde2d stat_bkde2d
### ** Examples
m <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
geom_point() +
xlim(0.5, 6) +
ylim(40, 110)
m + geom_bkde2d(bandwidth=c(0.5, 4))
m + stat_bkde2d(bandwidth=c(0.5, 4), aes(fill = ..level..), geom = "polygon")
# If you map an aesthetic to a categorical variable, you will get a
# set of contours for each value of that variable
set.seed(4393)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsmall, aes(x, y)) +
geom_bkde2d(bandwidth=c(0.5, 0.5), aes(colour = cut))
d
# If we turn contouring off, we can use use geoms like tiles:
d + stat_bkde2d(bandwidth=c(0.5, 0.5), geom = "raster",
aes(fill = ..density..), contour = FALSE)
# Or points:
d + stat_bkde2d(bandwidth=c(0.5, 0.5), geom = "point",
aes(size = ..density..), contour = FALSE)
|
0a11531f7135cda5b892e97004f06cbdd87a8d15
|
0dddd513e0dc84f80c46ddb2e1c7b4d6a050993d
|
/resources/methylation/methylation_pcs.R
|
424db3760d57b1675c5ce03b182c6ed9a5914c62
|
[] |
no_license
|
AST87/godmc
|
843542337e9f51fa7c96c83dd1070bac166cd270
|
3dd1949ede6500e134652e1b98a6f8d8a35e116c
|
refs/heads/master
| 2022-12-04T04:59:35.495587
| 2020-08-21T09:26:13
| 2020-08-21T09:26:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,969
|
r
|
methylation_pcs.R
|
suppressMessages(library(meffil))
arguments <- commandArgs(T)
beta_file <- arguments[1]
prop_var <- as.numeric(arguments[2])
max_pcs <- as.numeric(arguments[3])
phen_file <- arguments[4]
pc_out <- arguments[5]
message("Loading methylation data")
load(beta_file)
message("Extracting most variable probes and calculate PCs")
featureset <- meffil:::guess.featureset(rownames(norm.beta))
autosomal.sites <- meffil.get.autosomal.sites(featureset)
autosomal.sites <- intersect(autosomal.sites, rownames(norm.beta))
norm.beta.aut <- norm.beta[autosomal.sites, ]
message("Calculating variances")
var.sites <- meffil.most.variable.cpgs(norm.beta.aut, n = 20000)
var.idx <- match(var.sites, rownames(norm.beta.aut))
message("Calculating beta PCs")
pc <- prcomp(t(meffil:::impute.matrix(norm.beta.aut[var.idx, ], margin = 1)))
message("Identifying PCs that cumulatively explain ", prop_var, " of variance")
cumvar <- cumsum(pc$sdev^2) / sum(pc$sdev^2)
n_pcs <- which(cumvar > prop_var)[1]
message(n_pcs, " PCs required to explain ", prop_var, " of methylation variance")
n_pcs <- min(n_pcs, max_pcs)
message(n_pcs, " will be used.")
pc <- pc$x[,1:n_pcs]
if(phen_file != "NULL")
{
message("Removing PCs associated with EWAS phenotypes")
phen <- read.table(phen_file, he=T)
rownames(phen) <- phen$IID
phen <- subset(phen, IID %in% rownames(pc), select=-c(IID))
pc1 <- pc[rownames(pc) %in% rownames(phen), ]
phen <- phen[match(rownames(pc1), rownames(phen)), , drop=FALSE]
stopifnot(all(rownames(phen) == rownames(pc1)))
l <- lapply(1:ncol(phen), function(i)
{
pvals <- coefficients(summary(lm(phen[,i] ~ pc1)))[-1,4]
which(pvals < 0.05/ncol(phen))
})
l <- sort(unique(unlist(l)))
message("Identified ", length(l), " PC(s) associated with phenotypes")
if(length(l) > 0)
{
pc <- pc[,! 1:ncol(pc) %in% l, drop=FALSE]
}
}
pc1 <- t(pc)
save(pc, file=paste0(pc_out, ".RData"))
write.table(pc1, file=paste0(pc_out, ".txt"), row=T, col=T, qu=F, sep="\t")
|
25419fa38bf459ed43afec4363f8dcfda7908ad5
|
7b8478fa05b32da12634bbbe313ef78173a4004f
|
/R/ops.R
|
476a13db0251601b163450fe7db9361fb1b67c6f
|
[] |
no_license
|
jeblundell/multiplyr
|
92d41b3679184cf1c3a637014846a92b2db5b8e2
|
079ece826fcb94425330f3bfb1edce125f7ee7d1
|
refs/heads/develop
| 2020-12-25T18:02:10.156393
| 2017-11-07T12:48:41
| 2017-11-07T12:48:41
| 58,939,162
| 4
| 1
| null | 2017-11-07T12:01:35
| 2016-05-16T14:30:38
|
R
|
UTF-8
|
R
| false
| false
| 37,240
|
r
|
ops.R
|
# Operations on Multiplyr objects
#' Add a new column with row names
#'
#' @family column manipulations
#' @param .self Data frame
#' @param var Optional name of column
#' @return Data frame
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (x=rnorm(100), alloc=1, cl=2)
#' dat %>% add_rownames()
#' dat %>% shutdown()
#' }
add_rownames <- function (.self, var="rowname") {
if (!is(.self, "Multiplyr")) {
stop ("add_rownames operation only valid for Multiplyr objects")
}
col <- .self$alloc_col (var)
.self$bm.master[, col] <- 1:nrow(.self$bm.master)
return (.self)
}
#' @rdname arrange
#' @export
arrange_ <- function (.self, ..., .dots) {
#This works on the presumption that factors have levels
#sorted already
if (!is(.self, "Multiplyr")) {
stop ("arrange operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0 || .self$empty) {
return (.self)
}
sort.names <- c()
sort.desc <- c()
for (i in 1:length(.dots)) {
if (length(.dots[[i]]) == 1) {
sort.names <- c(sort.names, as.character(.dots[[i]]))
sort.desc <- c(sort.desc, FALSE)
} else {
fn <- as.character(.dots[[i]][[1]])
if (length(.dots[[i]]) == 2 && fn == "desc") {
sort.names <- c(sort.names, as.character(.dots[[i]][[2]]))
sort.desc <- c(sort.desc, TRUE)
} else {
stop (paste0 ("arrange can't handle sorting expression: ", deparse(.dots[[i]])))
}
}
}
cols <- match(sort.names, .self$col.names)
if (any(is.na(cols))) {
stop (sprintf("Undefined columns: %s", paste0(sort.names[is.na(cols)], collapse=", ")))
}
.self$sort(decreasing=sort.desc, cols=cols)
return (.self)
}
#' @rdname define
#' @export
define_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("arrange operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No column names specified")
}
nm <- names(.dots)
if (any(nm %in% .self$col.names)) {
stop (sprintf("Columns already defined: %s", paste0(.self$col.names[.self$col.names %in% nm], collapse=", ")))
}
for (i in 1:length(.dots)) {
col <- .self$alloc_col (nm[i])
if (nm[i] != as.character(.dots[[i]])) { #x=y
#Set type based on template
tpl <- as.character(.dots[[i]])
tcol <- match (tpl, .self$col.names)
.self$type.cols[col] <- .self$type.cols[tcol]
#Copy levels from template
if (.self$type.cols[tcol] > 0) {
f <- match (tcol, .self$factor.cols)
.self$factor.cols <- c(.self$factor.cols, col)
.self$factor.levels <- append(.self$factor.levels,
list(.self$factor.levels[[f]]))
}
}
}
.self$update_fields (c("col.names", "type.cols", "factor.cols", "factor.levels"))
return (.self)
}
#' @rdname distinct
#' @export
distinct_ <- function (.self, ..., .dots, auto_compact = NULL) {
if (!is(.self, "Multiplyr")) {
stop ("distinct operation only valid for Multiplyr objects")
}
if (.self$empty) { return() }
.dots <- dotscombine (.dots, ...)
if (is.null(auto_compact)) {
auto_compact <- .self$auto_compact
}
N <- length (.self$cls)
if (length(.dots) > 0) {
namelist <- names (.dots)
.cols <- match(namelist, .self$col.names)
if (any(is.na(.cols))) {
stop (sprintf("Undefined columns: %s", paste0(namelist[is.na(.cols)], collapse=", ")))
}
} else {
.cols <- .self$order.cols > 0
.cols <- (1:length(.cols))[.cols]
}
if (.self$grouped) {
idx <- match (.self$groupcol, .cols)
if (!is.na(idx)) {
.cols <- .cols[-idx]
}
.cols <- c(.self$groupcol, .cols)
}
if (nrow(.self$bm) == 1) {
return (.self)
}
.self$sort (decreasing=FALSE, cols=.cols)
if (N == 1) {
if (nrow(.self$bm) == 2) {
.self$bm[2, .self$filtercol] <- ifelse (
all(.self$bm[1, .cols] == .self$bm[2, .cols]), 0, 1)
return (.self)
}
sm1 <- bigmemory.sri::attach.resource(sm_desc_comp (.self, 1))
sm2 <- bigmemory.sri::attach.resource(sm_desc_comp (.self, 2))
if (length(.cols) == 1) {
breaks <- which (sm1[,.cols] != sm2[,.cols])
} else {
breaks <- which (!apply (sm1[,.cols] == sm2[,.cols], 1, all))
}
breaks <- c(0, breaks) + 1
.self$filter_rows (breaks)
return (.self)
}
.self$cluster_export (c(".cols"))
# (0) If partitioned by group, temporarily repartition evenly
rg_grouped <- .self$grouped
rg_partition <- .self$group_partition
rg_cols <- .self$group.cols
if (rg_partition) {
.self$partition_even()
}
# (1) determine local distinct rows
trans <- .self$cluster_eval ({
if (.local$empty) {
.res <- NA
} else {
if (nrow(.local$bm) == 1) {
.breaks <- 1
.res <- 1
} else if (nrow(.local$bm) == 2) {
i <- ifelse (all(.local$bm[1, .cols] ==
.local$bm[2, .cols]), 1, 2)
.breaks <- 1:i
.res <- i
} else {
.sm1 <- bigmemory.sri::attach.resource(sm_desc_comp (.local, 1))
.sm2 <- bigmemory.sri::attach.resource(sm_desc_comp (.local, 2))
if (length(.cols) == 1) {
.breaks <- which (.sm1[,.cols] != .sm2[,.cols])
.breaks <- .breaks + 1
.res <- .local$last
} else {
if (nrow(.local$bm) == 1) {
.breaks <- 1
.res <- 1
} else if (nrow(.local$bm) == 2) {
i <- ifelse (all(.local$bm[1, .cols] ==
.local$bm[2, .cols]), 1, 2)
.breaks <- 1:i
.res <- i
} else {
if (length(.cols) == 1) {
.breaks <- which (.sm1[,.cols] != .sm2[,.cols])
} else {
.breaks <- which (!apply (.sm1[,.cols] == .sm2[,.cols], 1, all))
}
rm (.sm1, .sm2)
.breaks <- .breaks + 1
.res <- .local$last
}
}
}
}
.res
})
# (2) work out if there's a group change between local[1] and local[2] etc.
trans <- do.call (c, trans)
trans <- trans[-length(trans)] #last row not a transition
tg <- test_transition (.self, .cols, trans)
tg <- c(TRUE, tg) #first node is a pseudo-transition
# (3) set breaks=1 for all where there's a transition
.self$cluster_export_each ("tg", ".tg")
.self$cluster_eval ({
if (!.local$empty) {
if (.tg) {
.breaks <- c(1, .breaks)
}
}
NULL
})
# (4) filter at breaks
.self$cluster_eval ({
if (!.local$empty) {
.local$filter_rows (.breaks)
}
NULL
})
.self$filtered <- TRUE
.self$grouped <- rg_grouped
.self$group_partition <- rg_partition
.self$group.cols <- rg_cols
if (auto_compact) {
.self$compact()
.self$calc_group_sizes()
return (.self)
}
.self$calc_group_sizes()
# Repartition by group if appropriate
if (rg_partition) {
return (partition_group_(.self))
} else {
if (.self$grouped) {
.self$rebuild_grouped()
}
return (.self)
}
return(.self)
}
#' @rdname filter
#' @export
filter_ <- function (.self, ..., .dots, auto_compact = NULL) {
if (!is(.self, "Multiplyr")) {
stop ("filter operation only valid for Multiplyr objects")
}
if (.self$empty) {
return (.self)
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No filtering criteria specified")
}
if (is.null(auto_compact)) {
auto_compact <- .self$auto_compact
}
.self$cluster_export (c(".dots"))
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 3] > 0) {
for (.i in 1:length(.dots)) {
.local$group_restrict (.g)
.res <- dotseval (.dots[.i], .local$envir())
.local$filter_vector (.res[[1]])
.local$group_restrict ()
}
}
}
} else {
for (.i in 1:length(.dots)) {
.res <- dotseval (.dots[.i], .local$envir())
.local$filter_vector (.res[[1]])
}
}
}
NULL
})
.self$filtered <- TRUE
if (auto_compact) {
.self$compact()
}
.self$calc_group_sizes()
return (.self)
}
#' @rdname group_by
#' @export
group_by_ <- function (.self, ..., .dots, .cols=NULL, auto_partition=NULL) {
if (!is(.self, "Multiplyr")) {
stop ("group_by operation only valid for Multiplyr objects")
}
if (.self$empty) { return (.self) }
if (is.null(.cols)) {
.dots <- dotscombine (.dots, ...)
namelist <- names (.dots)
.cols <- match(namelist, .self$col.names)
if (any(is.na(.cols))) {
stop (sprintf("Undefined columns: %s", paste0(namelist[is.na(.cols)], collapse=", ")))
}
}
if (length(.cols) == 0) {
stop ("No grouping columns specified")
}
if (is.null(auto_partition)) {
auto_partition <- .self$auto_partition
}
N <- length(.self$cls)
.self$sort (decreasing=FALSE, cols=.cols, with.group=FALSE)
.self$group.cols <- .cols
.self$grouped <- TRUE
.self$group_sizes_stale <- FALSE
if (nrow(.self$bm) == 1) {
.self$bm[, .self$groupcol] <- 1
.self$group_cache <- bigmemory::big.matrix (nrow=1, ncol=3)
.self$group_cache[1, ] <- c(1, 1, 1)
.self$group_max <- 1
return (.self)
}
#(0) If partitioned by group, temporarily repartition evenly
regroup_partition <- .self$group_partition
#(1) Find all breaks locally, but extend each "last" by 1 to catch
# transitions
#(2) Add (first-1) to each break
#(3) Return # breaks in each cluser (b.len)
.self$partition_even (extend=TRUE)
.self$cluster_export (".cols")
res <- .self$cluster_eval ({
if (nrow(.local$bm) == 1) {
.breaks <- c()
} else if (nrow(.local$bm) == 2) {
.breaks <- ifelse (all(.local$bm[1, .cols] ==
.local$bm[2, .cols]), c(), .local$first+1)
} else {
sm1 <- bigmemory.sri::attach.resource (sm_desc_comp (.local, 1))
sm2 <- bigmemory.sri::attach.resource (sm_desc_comp (.local, 2))
if (length(.cols) == 1 || nrow(.local$bm) == 1) {
.breaks <- which (sm1[, .cols] != sm2[, .cols])
} else {
.breaks <- which (!apply (sm1[, .cols] == sm2[, .cols], 1, all))
}
if (.local$first == 1) {
.breaks <- c(0, .breaks)
}
.breaks <- .breaks + .local$first
}
.length <- length(.breaks)
})
b.len <- do.call (c, res)
G.count <- sum(b.len)
#(4) Allocate group_cache with nrow=sum(b.len)+1
.self$group_cache <- bigmemory::big.matrix (nrow=G.count, ncol=3)
#(5) Pass offset into group_cache[, 2] to each cluster node
b.off <- c(0, cumsum(b.len))[-(length(b.len)+1)] + 1
gcdesc <- bigmemory.sri::describe (.self$group_cache)
.self$cluster_export_each ("b.off", ".offset")
.self$cluster_export ("gcdesc", ".gcdesc")
#(6) Each cluster node constructs group_cache[, 2]
.self$cluster_eval ({
.local$group_cache_attach (.gcdesc)
if (.length > 0) {
.local$group_cache[.offset:(.offset+.length-1), 1] <- .breaks
#.local$group_cache <- bigmemory.sri::attach.resource(sm_desc_subset(.gcdesc, .offset, .offset+.length-1))
#.local$group_cache[, 1] <- .breaks
}
NULL
})
#(7) Fill in the blanks
if (G.count > 1) {
.self$group_cache[1:(G.count-1), 2] <- .self$group_cache[2:G.count, 1] - 1
}
.self$group_cache[G.count, 2] <- .self$last
#(8) Calculate group sizes
#(9) Assign group IDs
#FIXME: make parallel (use calc_group_sizes?)
.self$group_cache[, 3] <- (.self$group_cache[, 2] - .self$group_cache[, 1]) + 1
.self$group_max <- G.count
for (i in 1:G.count) {
.self$bm[.self$group_cache[i, 1]:.self$group_cache[i, 2], .self$groupcol] <- i
}
#Needed to allow $group_restrict on master node
.self$group <- 1:G.count
if (auto_partition && !regroup_partition) {
.self$group_partition <- TRUE
regroup_partition <- TRUE
}
# Repartition by group if appropriate
if (regroup_partition) {
.self$grouped <- TRUE
return (partition_group_(.self))
} else {
.self$rebuild_grouped()
.self$update_fields ("grouped")
return (.self)
}
}
#' Return size of groups
#'
#' This function is used to find the size of groups in a Multiplyr data frame
#'
#' @param .self Data frame
#' @return Group sizes
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (x=1:100, G=rep(c("A", "B", "C", "D"), length.out=100))
#' dat %>% group_by (G)
#' group_sizes (dat)
#' dat %>% shutdown()
#' }
group_sizes <- function (.self) {
if (!is(.self, "Multiplyr")) {
stop ("group_sizes operation only valid for Multiplyr objects")
}
if (!.self$grouped) {
stop ("group_sizes may only be used after group_by")
}
.self$calc_group_sizes (delay=FALSE)
.self$group_cache[, 3]
}
#' Return number of groups
#'
#' @family utility functions
#' @param .self Data frame
#' @return Number of groups in data frame
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (x=1:100, G=rep(1:4, each=25), cl=2)
#' dat %>% group_by (G)
#' n_groups (dat)
#' dat %>% shutdown()
#' }
n_groups <- function (.self) {
if (!is(.self, "Multiplyr")) {
stop ("n_groups operation only valid for Multiplyr objects")
}
if (!.self$grouped) {
return (0)
} else {
return (nrow(.self$group_cache))
}
}
#' @rdname mutate
#' @export
mutate_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("mutate operation only valid for Multiplyr objects")
}
if (.self$empty) { return (.self) }
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No mutation operations specified")
}
.resnames <- names(.dots)
.rescols <- .self$alloc_col (.resnames, update=TRUE)
if (any(.rescols == .self$group.cols)) {
if (.self$grouped) {
stop("mutate on a group column is not permitted")
} else {
.self$group.cols <- numeric(0)
}
}
.self$cluster_export (c(".resnames", ".rescols", ".dots"))
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 1] > 0) {
for (.i in 1:length(.dots)) {
.local$group_restrict (.g)
.res <- dotseval (.dots[.i], .local$envir())
.local$set_data (, .rescols[.i], .res[[1]])
.local$group_restrict ()
}
}
}
} else {
for (.i in 1:length(.dots)) {
.res <- dotseval (.dots[.i], .local$envir())
.local$set_data (, .rescols[.i], .res[[1]])
}
}
}
NULL
})
return (.self)
}
#' No strings attached mode
#'
#' This function may be used to set or unset whether a data frame is in no
#' strings attached mode, potentially speeding up various operations.
#'
#' This function will place a data frame in no strings attached mode, which
#' disables translation of character values to and from numeric representation.
#' This allows for much faster calculations.
#'
#' @family data manipulations
#' @param .self Data frame
#' @param enabled TRUE to enable, FALSE to disable. Defaults to TRUE.
#' @return Data frame
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (G=rep(c("A", "B", "C", "D"), length.out=100))
#' dat %>% nsa () %>% mutate (G=max(G)) %>% nsa(FALSE)
#' dat %>% shutdown()
#' }
nsa <- function (.self, enabled=TRUE) {
if (!is(.self, "Multiplyr")) {
stop ("nsa operation only valid for Multiplyr objects")
}
if (.self$nsamode && enabled) {
warning ("nsa() operation applied when data frame already in NSA-mode")
} else if (!.self$nsamode && !enabled) {
warning ("nsa(FALSE) operation applied when data frame already not in NSA-mode")
}
.self$nsamode <- enabled
.self$update_fields ("nsamode")
return (.self)
}
#' Partition data evenly amongst cluster nodes
#'
#' This function results in data being repartitioned evenly across cluster nodes,
#' ignoring any grouping variables.
#'
#' @family cluster functions
#' @param .self Data frame
#' @return Data frame
#' @export
partition_even <- function (.self) {
if (!is(.self, "Multiplyr")) {
stop ("partition_even operation only valid for Multiplyr objects")
}
.self$partition_even ()
.self$group_partition <- FALSE
.self$update_fields ("group_partition")
return(.self)
}
#' @rdname partition_group
#' @export
partition_group_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("partition_group operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) > 0) {
.self$group_partition <- TRUE
return (group_by_ (.self, .dots=.dots))
#group_by_ calls partition_group() on its return
}
if (!.self$grouped) {
stop ("Need to specify grouping factors or apply group_by first")
}
N <- length(.self$cls)
G <- .self$group_cache[, 3]
if (length(G) == 1) {
Gi <- distribute (1, N)
Gi[Gi == 0] <- NA
} else {
Gi <- distribute (G, N)
}
.self$cluster_export_each ("Gi", ".groups")
.self$destroy_grouped()
.self$cluster_profile()
.self$cluster_eval ({
if (NA %in% .groups) {
.local$empty <- TRUE
}
if (!.local$empty) {
.local$group <- .groups
}
NULL
})
.self$group_partition <- .self$grouped <- TRUE
.self$update_fields (c("grouped", "group_partition"))
.self$build_grouped ()
return (.self)
}
#' @rdname reduce
#' @export
reduce_ <- function (.self, ..., .dots, auto_compact = NULL) {
if (!is(.self, "Multiplyr")) {
stop ("reduce operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No reduce operations specified")
}
if (is.null(auto_compact)) {
auto_compact <- .self$auto_compact
}
avail <- which (substr (.self$col.names, 1, 1) != ".")
if (.self$grouped) {
avail <- avail[!(avail %in% .self$group.cols)]
}
avail <- sort(c(avail, which (is.na(.self$col.names))))
newnames <- names(.dots)
if (length(newnames) > length(avail)) {
stop ("Insufficient free columns available")
}
newcols <- avail[1:length(newnames)]
if (!.self$empty) {
if (.self$grouped) {
for (g in 1:.self$group_max) {
.self$group_restrict (g)
res <- dotseval (.dots, .self$envir())
len <- 0
for (i in 1:length(res)) {
.self$bm[, newcols[i]] <- res[[i]]
if (length(res[[i]]) > len) {
len <- length(res[[i]])
}
}
.self$bm[, .self$filtercol] <- 0
.self$bm[1:len, .self$filtercol] <- 1
.self$filtered <- TRUE
.self$group_restrict ()
}
} else {
res <- dotseval (.dots, .self$envir())
len <- 0
for (i in 1:length(res)) {
.self$bm[, newcols[i]] <- res[[i]]
if (length(res[[i]]) > len) {
len <- length(res[[i]])
}
}
.self$bm[, .self$filtercol] <- 0
.self$bm[1:len, .self$filtercol] <- 1
.self$filtered <- TRUE
}
}
if (auto_compact) {
.self$compact()
}
.self$free_col (avail, update=TRUE)
.self$alloc_col (newnames, update=TRUE)
.self$calc_group_sizes()
return (.self)
}
#' Return to grouped data
#'
#' After a data frame has been grouped and then ungrouped, this function acts
#' as a shorthand (and faster way) to reinstate grouping.
#'
#' @param .self Data frame
#' @param auto_partition Re-partition across cluster after operation
#' @return Data frame
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (x=1:100, G=rep(c("A", "B"), length.out=100))
#' dat %>% group_by (G)
#' dat %>% ungroup() %>% regroup()
#' dat %>% summarise (N=length(x))
#' dat %>% shutdown()
#' }
regroup <- function (.self, auto_partition=NULL) {
if (!is(.self, "Multiplyr")) {
stop ("regroup operation only valid for Multiplyr objects")
}
if (.self$grouped) {
warning ("regroup attempted on an object that's already grouped")
return (.self)
}
if (length(.self$group.cols) == 0) {
stop ("regroup may only be used after group_by (and without modifying the group columns)")
}
if (is.null(auto_partition)) {
auto_partition <- .self$auto_partition
}
.self$grouped <- TRUE
.self$update_fields ("grouped")
if (auto_partition) {
.self$group_partition <- TRUE
.self$update_fields ("group_partition")
}
.self$build_grouped()
return (.self)
}
#' @rdname rename
#' @export
rename_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("rename operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No renaming operations specified")
}
newnames <- names(.dots)
oldnames <- simplify2array (as.character(.dots))
m <- match(oldnames, .self$col.names)
if (any(is.na(m))) {
stop (sprintf("Undefined columns: %s", paste0(oldnames[is.na(m)], collapse=", ")))
}
.self$col.names[m] <- newnames
.self$update_fields ("col.names")
return (.self)
}
#' @rdname select
#' @export
select_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("select operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No select columns specified")
}
coln <- simplify2array (as.character(.dots))
cols <- match (coln, .self$col.names)
if (any(is.na(cols))) {
stop (sprintf("Undefined columns: %s", paste0(coln[is.na(cols)], collapse=", ")))
}
.self$order.cols[sort(cols)] <- order(cols)
#rest set to zero by free_col (del)
del <- substr(.self$col.names, 1, 1) != "."
del[is.na(del)] <- FALSE
del[cols] <- FALSE
if (.self$grouped) {
del[.self$group.cols] <- FALSE
}
del <- which (del)
.self$free_col (del, update=TRUE)
return (.self)
}
#' Shutdown running cluster
#'
#' Theoretically a Multiplyr data frame will have its cluster implicitly
#' shutdown when R's garbage collection kicks in. This function exists to
#' execute it explicitly. This does not affect any of the data.
#'
#' @family cluster functions
#' @param .self Data frame
#' @export
shutdown <- function (.self) {
if (!is(.self, "Multiplyr")) {
stop ("shutdown operation only valid for Multiplyr objects")
} else if (!.self$cluster_running()) {
warning ("Attempt to shutdown cluster that's already not running")
}
.self$cluster_profile ()
if (.self$grouped) {
.self$calc_group_sizes(delay=FALSE)
}
.self$cluster_stop (only.if.started=FALSE)
return (.self)
}
#' Select rows by position
#'
#' This function is used to filter out everything except a specified subset of
#' the data. The each parameter is used to change slice's behaviour to filter
#' out all except a specified subset within each group or, if no grouping,
#' within each node.
#'
#' @family row manipulations
#' @param .self Data frame
#' @param rows Rows to select
#' @param start Start of range of rows
#' @param end End of range of rows
#' @param each Apply slice to each cluster/group
#' @param auto_compact Compact data
#' @return Data frame
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (x=1:100, G=rep(c("A", "B", "C", "D"), each=25))
#' dat %>% group_by (G)
#' dat %>% slice (1:10, each=TRUE)
#' dat %>% slice (1:10)
#' dat %>% shutdown()
#' }
slice <- function (.self, rows=NULL, start=NULL, end=NULL, each=FALSE, auto_compact=NULL) {
if (!is(.self, "Multiplyr")) {
stop ("slice operation only valid for Multiplyr objects")
} else if (is.null(rows) && (is.null(start) || is.null(end))) {
stop ("Must specify either rows or start and stop")
} else if (!is.null(rows) && !(is.null(start) || is.null(end))) {
stop ("Can either specify rows or start and stop; not both")
}
if (is.null(auto_compact)) {
auto_compact <- .self$auto_compact
}
if (each) {
if (is.null(rows)) {
.self$cluster_export (c("start", "end"), c(".start", ".end"))
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 1] > 0) {
.local$group_restrict (.g)
.local$filter_range (.start, .end)
.local$group_restrict()
}
}
} else {
.local$filter_range (.start, .end)
}
}
NULL
})
} else if (is.logical(rows)) {
.self$cluster_export ("rows", ".rows")
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 3] > 0) {
.local$group_restrict (.g)
.local$filter_vector (.rows)
.local$group_restrict ()
}
}
} else {
.local$filter_vector (.rows)
}
}
NULL
})
} else {
.self$cluster_export ("rows", ".rows")
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 3] > 0) {
.local$group_restrict (.g)
.local$filter_rows (.rows)
.local$group_restrict ()
}
}
} else {
.local$filter_rows (.rows)
}
}
NULL
})
}
} else {
if (is.null(rows)) {
.self$filter_range (start, end)
} else if (is.logical(rows)) {
.self$filter_vector (rows)
} else {
.self$filter_rows (rows)
}
}
.self$filtered <- TRUE
.self$calc_group_sizes()
if (auto_compact) {
.self$compact()
}
.self
}
#' @rdname summarise
#' @export
summarise_ <- function (.self, ..., .dots, auto_compact = NULL) {
if (!is(.self, "Multiplyr")) {
stop ("summarise operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No summarise operations specified")
}
if (is.null(auto_compact)) {
auto_compact <- .self$auto_compact
}
avail <- which (substr (.self$col.names, 1, 1) != ".")
if (.self$grouped) {
avail <- avail[!(avail %in% .self$group.cols)]
}
avail <- sort(c(avail, which (is.na(.self$col.names))))
newnames <- names(.dots)
if (length(newnames) > length(avail)) {
stop ("Insufficient free columns available")
}
.newcols <- avail[1:length(newnames)]
.self$cluster_export (c(".dots", ".newcols"))
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 1] > 0) {
.local$group_restrict (.g)
.res <- dotseval (.dots, .local$envir())
.len <- 0
for (.i in 1:length(.res)) {
.local$bm[, .newcols[.i]] <- .res[[.i]]
if (length(.res[[.i]]) > .len) {
.len <- length(.res[[.i]])
}
}
.local$bm[, .local$filtercol] <- 0
.local$bm[1:.len, .local$filtercol] <- 1
.local$filtered <- TRUE
.local$group_restrict()
}
}
} else {
.res <- dotseval (.dots, .local$envir())
.len <- 0
for (.i in 1:length(.res)) {
.local$bm[, .newcols[.i]] <- .res[[.i]]
if (length(.res[[.i]]) > .len) {
.len <- length(.res[[.i]])
.local$bm[, .local$filtercol] <- 0
.local$bm[1:.len, .local$filtercol] <- 1
.local$filtered <- TRUE
}
}
}
}
NULL
})
.self$filtered <- TRUE
if (auto_compact) {
.self$compact()
}
.self$free_col (avail, update=TRUE)
.self$alloc_col (newnames, update=TRUE)
.self$calc_group_sizes()
return (.self)
}
#' @rdname transmute
#' @export
transmute_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("transmute operation only valid for Multiplyr objects")
}
if (.self$empty) { return (.self) }
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No mutation operations specified")
}
#mutate
.resnames <- names(.dots)
.rescols <- .self$alloc_col (.resnames, update=TRUE)
if (any(.rescols == .self$group.cols)) {
if (.self$grouped) {
stop("transmute on a group column is not permitted")
} else {
.self$group.cols <- numeric(0)
}
}
.self$cluster_export (c(".resnames", ".rescols", ".dots"))
.self$cluster_eval ({
if (!.local$empty) {
if (.local$grouped) {
for (.g in .local$group) {
if (.local$group_cache[.g, 1] > 0) {
for (.i in 1:length(.dots)) {
.local$group_restrict (.g)
.res <- dotseval (.dots[.i], .local$envir())
.local$set_data (, .rescols[.i], .res[[1]])
.local$group_restrict ()
}
}
}
} else {
for (.i in 1:length(.dots)) {
.res <- dotseval (.dots[.i], .local$envir())
.local$set_data (, .rescols[.i], .res[[1]])
}
}
}
NULL
})
#/mutate
dropcols <- .self$order.cols > 0
dropcols[.rescols] <- FALSE
if (.self$grouped) {
dropcols[.self$group.cols] <- FALSE
}
dropcols <- which (dropcols)
.self$free_col (dropcols, update=TRUE)
.self$update_fields (c("col.names", "type.cols", "order.cols"))
return (.self)
}
#' @rdname undefine
#' @export
undefine_ <- function (.self, ..., .dots) {
if (!is(.self, "Multiplyr")) {
stop ("undefine operation only valid for Multiplyr objects")
}
.dots <- dotscombine (.dots, ...)
if (length(.dots) == 0) {
stop ("No undefine operations specified")
}
dropnames <- names (.dots)
dropcols <- match (dropnames, .self$col.names)
if (any(is.na(dropcols))) {
stop (sprintf("Undefined columns: %s", paste0(dropnames[is.na(dropcols)], collapse=", ")))
}
.self$free_col (dropcols, update=TRUE)
return (.self)
}
#' @rdname undefine
#' @export
unselect_ <- undefine_
#' Return data to non-grouped
#'
#' After grouping data with group_by, there may be a need to return to a
#' non-grouped form. Running ungroup() will drop any grouping. This can be
#' reinstated again with regroup().
#'
#' @param .self Data frame
#' @return Data frame
#' @export
ungroup <- function (.self) {
if (!is(.self, "Multiplyr")) {
stop ("ungroup operation only valid for Multiplyr objects")
}
if (!.self$grouped) {
warning ("ungroup attempted on an object that's not grouped")
return (.self)
}
.self$destroy_grouped ()
.self$grouped <- .self$group_partition <- FALSE
.self$update_fields (c("grouped", "group_partition"))
.self$partition_even ()
return (.self)
}
#' @rdname ungroup
#' @export
rowwise <- ungroup
#' @rdname regroup
#' @export
groupwise <- regroup
#' Execute code within a group
#'
#' This is the mainstay of parallel computation for a data frame. This will
#' execute the specified expression within each group. Each group will have a
#' persistent environment, so that variables created in that environment can
#' be referred to by, for example, later calls to summarise. This environment
#' contains active bindings to the columns of that data frame.
#'
#' @family data manipulations
#' @param .self Data frame
#' @param expr Code to execute
#' @return Data frame
#' @export
#' @examples
#' \donttest{
#' dat <- Multiplyr (G = rep(c("A", "B"), each=50),
#' m = rep(c(5, 10), each=50),
#' alloc=1)
#' dat %>% group_by (G) %>% mutate (x=rnorm(length(m), mean=m))
#' dat %>% within_group ({
#' mdl <- lm (x ~ 1)
#' })
#' dat %>% summarise (x.mean = coef(mdl)[[1]])
#' dat %>% shutdown()
#' }
within_group <- function (.self, expr) {
if (!is(.self, "Multiplyr")) {
stop ("within_group operation only valid for Multiplyr objects")
}
if (!.self$grouped) {
stop ("within_group may only be used after group_by")
}
expr <- substitute(expr)
.self$cluster_export ("expr", ".expr")
.self$cluster_eval({
if (!.local$empty) {
for (.g in .local$group) {
.local$group_restrict (.g)
if (!.local$empty) {
eval (.expr, envir = .local$envir())
}
.local$group_restrict ()
}
}
NULL
})
.self
}
#' Execute code within a node
#'
#' This is the mainstay of parallel computation for a data frame. This will
#' execute the specified expression within each node. Each node will have a
#' persistent environment, so that variables created in that environment can
#' be referred to by, for example, later calls to summarise. This environment
#' contains active bindings to the columns of that data frame.
#'
#' @family data manipulations
#' @param .self Data frame
#' @param expr Code to execute
#' @export
within_node <- function (.self, expr) {
if (!is(.self, "Multiplyr")) {
stop ("within_node operation only valid for Multiplyr objects")
}
expr <- substitute(expr)
.self$cluster_export ("expr", ".expr")
.self$cluster_eval({
if (!.local$empty) {
eval (.expr, envir = .local$envir())
}
NULL
})
.self
}
|
874caac47bf01bf9e98a26fe913b98a022ff0ef9
|
1c1c55fe1159201edbe63e537b2b8914a0d8e2ae
|
/R/create_ecospace.R
|
c9646640a0c8375bc4b0889a073069ee54152d58
|
[
"CC0-1.0"
] |
permissive
|
pnovack-gottshall/ecospace
|
02b4290e4267a9d9eb28c190f78eb5b4e8fb1e79
|
3b1464498a5e0ec539aa3ab8c0859d2791a40ffc
|
refs/heads/master
| 2021-01-10T06:20:32.845527
| 2020-06-13T17:19:06
| 2020-06-13T17:19:06
| 45,119,337
| 5
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 20,877
|
r
|
create_ecospace.R
|
#' Create Ecospace Framework.
#'
#' Create ecospace frameworks (functional trait spaces) of specified structure.
#'
#' @param nchar Number of life habit characters (functional traits).
#' @param char.state Numeric vector of number of character states in each
#' character.
#' @param char.type Character string listing type for each character. See
#' 'Details' for explanation. Allowed types include: \itemize{ \item
#' \code{numeric} for numeric and binary characters, \item \code{ord.num} for
#' ordered numeric characters, \item \code{ord.fac} for ordered factor
#' characters, or \item \code{factor} for factor characters. }
#' @param char.names Optional character string listing character names.
#' @param state.names Optional character string listing character state names.
#' @param constraint Positive integer specifying the maximum number of "multiple
#' presences" to allow if using multistate binary/numeric character types. The
#' default \code{Inf} allows all possible permutations (except for "all
#' absences"). See 'Details' for additional explanation.
#' @param weight.file Data frame (species X trait matrix) or a vector (of mode
#' numeric, integer, or array) of relative weights for ecospace
#' character-state probabilities. Default action omits such probabilities and
#' creates equal weighting among states. If a data frame is supplied, the
#' first three columns must be (1) class [or similar taxonomic identifier],
#' (2) genus, and (3) species names (or three dummy columns that will be
#' ignored by algorithm).
#'
#' @details This function specifies the data structure for a theoretical
#' ecospace framework used in Monte Carlo simulations of ecological
#' diversification. An ecospace framework (functional trait space) is a
#' multidimensional data structure describing how organisms interact with
#' their environments, often summarized by a list of the individual life habit
#' characters (functional traits) inhabited by organisms. Commonly used
#' characters describe diet and foraging habit, mobility, microhabitat, among
#' others, with the individual diets, modes of locomotions, and microhabitats
#' as possible character states. When any combination of character states is
#' allowed, the framework serves as a theoretical ecospace; actually occurring
#' life-habit combinations circumscribe the realized ecospace.
#'
#' Arguments \code{nchar, char.state, char.type} specify the number and types
#' of characters and their states. Character names and state names are
#' optional, and assigned using numeric names (i.e., character 1, character 2,
#' etc.) if not provided. The function returns an error if the number of
#' states and names is different than numbers specified in provided arguments.
#'
#' Allowed character types include the following: \itemize{ \item
#' \code{numeric} for numeric and binary characters, whether present/absent or
#' multistate. See below for examples and more discussion on these
#' implementations. \item \code{ord.num} for ordered numeric values, whether
#' discrete or continuous. Examples include body size, metabolic rate, or
#' temperature tolerance. States are pulled as sorted unique levels from
#' \code{weight.file}, if provided. \item \code{ord.fac} for ordered factor
#' characters (factors with a specified order). An example is mobility:
#' habitual > intermittent > facultative > passive > sedentary. (If wish to
#' specify relative distances between these ordered factors, it is best to use
#' an ordered numeric character type instead). \item \code{factor} for
#' discrete, unordered factors (e.g., diet can have states of autotrophic,
#' carnivorous, herbivorous, or microbivorous).}
#'
#' Binary characters can be treated individually (e.g., states of
#' present = 1/absent = 0) or can be treated as multiple binary character states.
#' For example, the character 'reproduction' could be treated as including two
#' states [sexual, asexual] with exclusively sexual habits coded as [0,1],
#' exclusively asexual as [1,0], and hermaphrodites as [1,1]. The
#' \code{constraint} argument allows additional control of such combinations.
#' Setting \code{constraint = 2} only allows a maximum of "two-presence"
#' combinations (e.g., [1,0,0], [0,1,0], [0,0,1], [1,1,0], [1,0,1], and
#' [0,1,1]) as state combinations, but excludes [1,1,1]; setting
#' \code{constraint = 1} only allows the first three of these combinations; the
#' default behavior (\code{Inf}) allows all of these combinations. In all
#' cases, the nonsensical "all-absence" state combination [0,0,0] is
#' disallowed.
#'
#' Character states can be weighted using the optional \code{weight.file}.
#' This is useful so that random draws of life habits (functional-trait
#' combinations) from the ecospace framework are biased in specified ways. If
#' not provided, the default action assigns equal weighting among states. If a
#' vector of mode array, integer, or numeric is provided, character states (or
#' character-state combinations, if multistate binary) are assigned the
#' specified relative weight. The function returns an error if the supplied
#' vector has a length different that the number of states allowed.
#'
#' If a data frame is supplied for the weight file (such as a species-by-trait
#' matrix, with species as rows and traits as columns, describing a regional
#' species pool), weights are calculated according to the observed relative
#' frequency of states in this pool. If such a data frame is supplied, the
#' first three columns must be (1) class [or similar taxonomic identifier],
#' (2) genus, and (3) species names, although these can be left blank. In all
#' cases, character state probabilities are calculated separately within each
#' character (including only those allowed by the specified
#' \code{constraint}).
#'
#' @return Returns a list of class \code{ecospace} describing the structure of
#' the theoretical ecospace framework needed for running simulations. The list
#' has a length equal to \code{nchar + 1}, with one list component for each
#' character, plus a final list component recording constraints used in
#' producing allowable character states.
#'
#' Each character component has the following list components:\describe{
#' \item{\code{char}}{character name.}\item{\code{type}}{character type.}
#' \item{\code{char.space}}{data frame listing each allowable state
#' combination in each row, the calculated proportional weight (\code{pro}),
#' frequency (\code{n}) of observed species with such state combination in
#' species pool (\code{weight.file}, if supplied).}
#' \item{\code{allowed.combos}}{allowed character state combinations allowed
#' by \code{constraint} and \code{weight.file}, if supplied.}}
#'
#' The last component lists the following components:\describe{
#' \item{\code{constraint}}{\code{constraint} argument
#' used.}\item{\code{wts}}{vector of character-state weights used.}
#' \item{\code{pool}}{species by trait matrix used in assigning
#' character-state weights, if supplied. Note that this matrix may differ from
#' that supplied as \code{weight.file} when, for example, the supplied file
#' includes character-state combinations not allowed by \code{constraint]}. It
#' also excludes taxonomic identifiers (class, genus, species).}}
#'
#' @note If you have trouble matching the characters with \code{char.state} and
#' \code{char.type}, see \code{data.frame} in first example for easy way to
#' trouble-shoot. If you have trouble supplying correct length of
#' \code{char.name, state.name} and \code{weight.file}, consider producing an
#' ecospace framework with defaults first, then using these to supply custom
#' names and weights.
#'
#' @author Phil Novack-Gottshall \email{pnovack-gottshall@@ben.edu}
#'
#' @references Bambach, R. K. 1983. Ecospace utilization and guilds in marine
#' communities through the Phanerozoic. Pp. 719-746. \emph{In} M. J. S.
#' Tevesz, and P. L. McCall, eds. \emph{Biotic Interactions in Recent and
#' Fossil Benthic Communities}. Plenum, New York.
#' @references Bambach, R. K. 1985. Classes and adaptive variety: the ecology of
#' diversification in marine faunas through the Phanerozoic. Pp. 191-253.
#' \emph{In} J. W. Valentine, ed. \emph{Phanerozoic Diversity Patterns:
#' Profiles in Macroevolution}. Princeton University Press, Princeton, NJ.
#' @references Bambach, R. K., A. M. Bush, and D. H. Erwin. 2007. Autecology and
#' the filling of ecospace: key metazoan radiations. \emph{Palaeontology}
#' 50(1):1-22.
#' @references Bush, A. M. and R. K. Bambach. 2011. Paleoecologic megatrends in
#' marine Metazoa. \emph{Annual Review of Earth and Planetary Sciences}
#' 39:241-269.
#' @references Bush, A. M., R. K. Bambach, and G. M. Daley. 2007. Changes in
#' theoretical ecospace utilization in marine fossil assemblages between the
#' mid-Paleozoic and late Cenozoic. \emph{Paleobiology} 33(1):76-97.
#' @references Bush, A. M., R. K. Bambach, and D. H. Erwin. 2011. Ecospace
#' utilization during the Ediacaran radiation and the Cambrian eco-explosion.
#' Pp. 111-134. \emph{In} M. Laflamme, J. D. Schiffbauer, and S. Q. Dornbos,
#' eds. \emph{Quantifying the Evolution of Early Life: Numerical Approaches to
#' the Evaluation of Fossils and Ancient Ecosystems}. Springer, New York.
#' @references Novack-Gottshall, P.M. 2007. Using a theoretical ecospace to
#' quantify the ecological diversity of Paleozoic and modern marine biotas.
#' \emph{Paleobiology} 33: 274-295.
#' @references Novack-Gottshall, P.M. 2016a. General models of ecological
#' diversification. I. Conceptual synthesis. \emph{Paleobiology} 42: 185-208.
#' @references Novack-Gottshall, P.M. 2016b. General models of ecological
#' diversification. II. Simulations and empirical applications.
#' \emph{Paleobiology} 42: 209-239.
#'
#' @examples
#' # Create random ecospace framework with all character types
#' set.seed(88)
#' nchar <- 10
#' char.state <- rpois(nchar, 1) + 2
#' char.type <- replace(char.state, char.state <= 3, "numeric")
#' char.type <- replace(char.type, char.state == 4, "ord.num")
#' char.type <- replace(char.type, char.state == 5, "ord.fac")
#' char.type <- replace(char.type, char.state > 5, "factor")
#' # Good practice to confirm everything matches expectations:
#' data.frame(char = seq(nchar), char.state, char.type)
#' ecospace <- create_ecospace(nchar, char.state, char.type, constraint = Inf)
#' ecospace
#'
#' # How many life habits in this ecospace are theoretically possible?
#' seq <- seq(nchar)
#' prod(sapply(seq, function(seq) length(ecospace[[seq]]$allowed.combos)))
#' # ~12 million
#'
#' # Observe effect of constraint for binary characters
#' create_ecospace(1, 4, "numeric", constraint = Inf)[[1]]$char.space
#' create_ecospace(1, 4, "numeric", constraint = 2)[[1]]$char.space
#' create_ecospace(1, 4, "numeric", constraint = 1)[[1]]$char.space
#' try(create_ecospace(1, 4, "numeric", constraint = 1.5)[[1]]$char.space) # ERROR!
#' try(create_ecospace(1, 4, "numeric", constraint = 0)[[1]]$char.space) # ERROR!
#'
#' # Using custom-weighting for traits (singletons weighted twice as frequent
#' # as other state combinations)
#' weight.file <- c(rep(2, 3), rep(1, 3), 2, 2, 1, rep(1, 4), rep(2, 3), rep(1, 3),
#' rep(1, 14), 2, 2, 1, rep(1, 4), rep(2, 3), rep(1, 3), rep(1, 5))
#' create_ecospace(nchar, char.state, char.type, constraint = 2,
#' weight.file = weight.file)
#'
#' # Bambach's (1983, 1985) classic ecospace framework
#' # 3 characters, all factors with variable states
#' nchar <- 3
#' char.state <- c(3, 4, 4)
#' char.type <- c("ord.fac", "factor", "factor")
#' char.names <- c("Tier", "Diet", "Activity")
#' state.names <- c("Pelag", "Epif", "Inf", "SuspFeed", "Herb", "Carn", "DepFeed",
#' "Mobile/ShallowActive", "AttachLow/ShallowPassive", "AttachHigh/DeepActive",
#' "Recline/DeepPassive")
#' ecospace <- create_ecospace(nchar, char.state, char.type, char.names, state.names)
#' ecospace
#' seq <- seq(nchar)
#' prod(sapply(seq, function(seq) length(ecospace[[seq]]$allowed.combos)))
#' # 48 possible life habits
#'
#' # Bush and Bambach's (Bambach et al. 2007, bush et al. 2007) updated ecospace
#' # framework, with Bush et al. (2011) and Bush and Bambach (2011) addition of
#' # osmotrophy as a possible diet category
#' # 3 characters, all factors with variable states
#' nchar <- 3
#' char.state <- c(6, 6, 7)
#' char.type <- c("ord.fac", "ord.fac", "factor")
#' char.names <- c("Tier", "Motility", "Diet")
#' state.names <- c("Pelag", "Erect", "Surfic", "Semi-inf", "ShallowInf", "DeepInf",
#' "FastMotile", "SlowMotile ", "UnattachFacMot", "AttachFacMot", "UnattachNonmot",
#' "AttachNonmot", "SuspFeed", "SurfDepFeed", "Mining", "Grazing", "Predation",
#' "Absorpt/Osmotr", "Other")
#' ecospace <- create_ecospace(nchar, char.state, char.type, char.names, state.names)
#' ecospace
#' seq <- seq(nchar)
#' prod(sapply(seq, function(seq) length(ecospace[[seq]]$allowed.combos)))
#' # 252 possible life habits
#'
#' # Novack-Gottshall (2007) ecospace framework, updated in Novack-Gottshall (2016b)
#' # Fossil species pool from Late Ordovician (Type Cincinnatian) Kope and
#' # Waynesville Formations, with functional-trait characters coded according
#' # to Novack-Gottshall (2007, 2016b)
#' data(KWTraits)
#' head(KWTraits)
#' nchar <- 18
#' char.state <- c(2, 7, 3, 3, 2, 2, 5, 5, 2, 5, 2, 2, 5, 2, 5, 5, 3, 3)
#' char.type <- c("numeric", "ord.num", "numeric", "numeric", "numeric", "numeric",
#' "ord.num", "ord.num", "numeric", "ord.num", "numeric", "numeric", "ord.num",
#' "numeric", "ord.num", "numeric", "numeric", "numeric")
#' char.names <- c("Reproduction", "Size", "Substrate composition", "Substrate
#' consistency", "Supported", "Attached", "Mobility", "Absolute tier", "Absolute
#' microhabitat", "Relative tier", "Relative microhabitat", "Absolute food
#' microhabitat", "Absolute food tier", "Relative food microhabitat", "Relative
#' food tier", "Feeding habit", "Diet", "Food condition")
#' state.names <- c("SEXL", "ASEX", "BVOL", "BIOT", "LITH", "FLUD", "HARD", "SOFT",
#' "INSB", "SPRT", "SSUP", "ATTD", "FRLV", "MOBL", "ABST", "AABS", "IABS", "RLST",
#' "AREL", "IREL", "FAAB", "FIAB", "FAST", "FARL", "FIRL", "FRST", "AMBT", "FILT",
#' "ATTF", "MASS", "RAPT", "AUTO", "MICR", "CARN", "INCP", "PART", "BULK")
#' ecospace <- create_ecospace(nchar, char.state, char.type, char.names, state.names,
#' constraint = 2, weight.file = KWTraits)
#' ecospace
#' seq <- seq(nchar)
#' prod(sapply(seq, function(seq) length(ecospace[[seq]]$allowed.combos)))
#' # ~57 billion life habits
#'
#' ecospace <- create_ecospace(nchar, char.state, char.type, char.names, state.names,
#' constraint = Inf)
#' ecospace
#' seq <- seq(nchar)
#' prod(sapply(seq, function(seq) length(ecospace[[seq]]$allowed.combos)))
#' # ~3.6 trillion life habits
#'
#' @export
create_ecospace <- function(nchar, char.state, char.type, char.names = NA,
state.names = NA, constraint = Inf, weight.file = NA) {
if (is.finite(constraint) &
(constraint < 1 |
(abs(constraint - round(constraint)) > .Machine$double.eps)))
stop("'constraint' must be a positive integer (or Inf)\n")
if (is.logical(char.names))
char.names <- paste(rep("char", nchar), seq.int(nchar), sep = "")
ncs <- replace(char.state, which(char.type == "ord.num"), 1)
if (is.logical(state.names))
state.names <-
paste(rep("state", sum(ncs)), seq.int(sum(ncs)), sep = "")
if (sum(ncs) != length(state.names))
stop("state names is a different length than number of state names specified.\n")
lcn <- length(char.names)
lct <- length(char.type)
if (nchar != lcn | nchar != lct | lcn != lct)
stop("character names and/or types a different length than number of characters specified.\n")
wf <- weight.file
wt <- 1
out <- vector("list", nchar + 1)
wf.tally <- st.tally <- 1
for (ch in seq_len(nchar)) {
out[[ch]]$char <- char.names[ch]
out[[ch]]$type <- char.type[ch]
if (char.type[ch] == "numeric") {
traits <- seq(from = wf.tally, length = char.state[ch])
seq <- seq_len(char.state[ch])
grid <- do.call(expand.grid, lapply(seq, function (seq)
0:1))
grid <- grid[order(apply(grid, 1, sum)), ]
# Delete character combinations that are "all absences" or disallowed by constraint
sums <- apply(grid, 1, sum)
grid <- grid[which(sums > 0 & sums <= constraint), ]
colnames(grid) <-
state.names[seq(from = st.tally, length = char.state[ch])]
grid <- cbind(grid, pro = NA, n = NA, row = NA)
if (!is.logical(wf)) {
if (is.data.frame(wf)) {
for (s in 1:nrow(grid)) {
grid[s, length(traits) + 2] <-
length(which(apply(wf[, traits + 3], 1, paste, collapse = ".") == paste(grid[s, seq_along(traits)], collapse = ".")))
}
} else {
grid$n <- wf[seq(from = wt, length = nrow(grid))]
wt <- wt + nrow(grid)
}
grid$pro <- grid$n / sum(grid$n)
} else {
grid$pro <- 1 / nrow(grid)
}
st.tally <- st.tally + char.state[ch]
wf.tally <- wf.tally + char.state[ch]
}
if (char.type[ch] == "ord.num") {
if (is.data.frame(wf)) {
grid <- data.frame(sort(unique(wf[, wf.tally + 3])))
if (nrow(grid) != char.state[ch]) {
warning(paste("You specified that there were", char.state[ch],
"char.states for character", ch, "but weight.file\n", "has",
nrow(grid), "char.states. Ecospace built using number in
weight.file\n"))
}
} else {
grid <-
data.frame(round(seq(from = 0, to = 1, length = char.state[ch]), 3))
}
colnames(grid) <- state.names[st.tally]
grid <- cbind(grid, pro = NA, n = NA, row = row(grid)[, 1])
if (!is.logical(wf)) {
if (is.data.frame(wf)) {
grid$n <- table(factor(wf[, wf.tally + 3], levels = grid[, 1]))
grid$pro <- grid$n / sum(grid$n)
} else {
grid$n <- wf[seq(from = wt, length = nrow(grid))]
grid$pro <- grid$n / sum(grid$n)
wt <- wt + nrow(grid)
}
} else {
grid$pro <- 1 / nrow(grid)
}
st.tally <- st.tally + 1
wf.tally <- wf.tally + 1
}
if (char.type[ch] == "ord.fac" | char.type[ch] == "factor") {
traits <- seq(from = st.tally, length = char.state[ch])
if (char.type[ch] == "ord.fac") {
ord = TRUE
} else {
ord = FALSE
}
grid <- data.frame(factor(state.names[traits], ordered = ord))
colnames(grid) <- char.names[ch]
grid <- cbind(grid, pro = NA, n = NA, row = row(grid)[, 1])
if (!is.logical(wf)) {
if (is.data.frame(wf)) {
grid$n <- table(factor(wf[, wf.tally + 3], levels = state.names[traits]))
grid$pro <- grid$n / sum(grid$n)
} else {
grid$n <- wf[seq(from = wt, length = nrow(grid))]
grid$pro <- grid$n / sum(grid$n)
wt <- wt + nrow(grid)
}
} else {
grid$pro <- 1 / nrow(grid)
}
st.tally <- st.tally + char.state[ch]
wf.tally <- wf.tally + 1
}
# Delete character combinations not realized in weight.file
grid <- grid[which(grid$pro > 0), ]
grid$row <- seq.int(grid$row)
out[[ch]]$char.space <- grid
out[[ch]]$allowed.combos <-
as.vector(apply(as.matrix(grid[, seq_len(ncol(grid) - 3)]), 1, paste, collapse = "."))
}
out[[nchar + 1]]$constraint <- constraint
# Prepare species pool (if using) and update to exclude those taxa not allowed by constraints of ecospace (and create array of state weights)
seq <- seq_len(nchar)
cs <- sapply(seq, function(seq)
ncol(out[[seq]]$char.space) - 3)
c.start <- c(1, cumsum(cs)[1:nchar - 1] + 1)
c.end <- cumsum(cs)
out[[nchar + 1]]$wts <-
as.vector(unlist(sapply(seq, function(seq)
as.numeric(out[[seq]]$char.space$pro))))
if (!is.data.frame(wf)) {
pool <- NA
} else {
pool <- wf[, 4:ncol(wf)]
allow <- matrix(FALSE, nrow = nrow(pool), ncol = nchar)
seq <- seq_len(nrow(allow))
for (ch in 1:nchar) {
allow[, ch] <-
apply(as.matrix(pool[seq, c.start[ch]:c.end[ch]]), 1, paste, collapse =
".") %in% out[[ch]]$allowed.combos
}
allow <- apply(allow, 1, all)
pool <- pool[allow == TRUE, ]
}
if (any(is.numeric(wf), is.integer(wf), is.array(wf)) &
(wt - 1) != length(wf))
stop("weight file is a different length than number of allowable state combinations.\n")
out[[nchar + 1]]$pool <- pool
class(out) <- "ecospace"
return(out)
}
|
5e99f02402ee92e99004c0ec811f8795c8375e4e
|
c9e0c41b6e838d5d91c81cd1800e513ec53cd5ab
|
/man/gtkTreeModelGetValue.Rd
|
3ca67f58fb5fe9fd47f642c5514800af5b498973
|
[] |
no_license
|
cran/RGtk2.10
|
3eb71086e637163c34e372c7c742922b079209e3
|
75aacd92d4b2db7d0942a3a6bc62105163b35c5e
|
refs/heads/master
| 2021-01-22T23:26:26.975959
| 2007-05-05T00:00:00
| 2007-05-05T00:00:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 679
|
rd
|
gtkTreeModelGetValue.Rd
|
\alias{gtkTreeModelGetValue}
\name{gtkTreeModelGetValue}
\title{gtkTreeModelGetValue}
\description{Sets initializes and sets \code{value} to that at \code{column}. When done with \code{value}.}
\usage{gtkTreeModelGetValue(object, iter, column)}
\arguments{
\item{\code{object}}{[\code{\link{GtkTreeModel}}] A \code{\link{GtkTreeModel}}.}
\item{\code{iter}}{[\code{\link{GtkTreeIter}}] The \code{\link{GtkTreeIter}}.}
\item{\code{column}}{[integer] The column to lookup the value at.}
}
\value{
A list containing the following elements:
\item{\code{value}}{[R object] An empty \code{R object} to set.}
}
\author{Derived by RGtkGen from GTK+ documentation}
\keyword{internal}
|
178b26e4cf1443f2dc235d13e51d05c7394eaa7a
|
9f723e2f26cada7472ec3b8f5ae313f477a11281
|
/Wrangling/src/tidy_text.R
|
841365c4d0328aa935cf0be71ec5696258c53883
|
[] |
no_license
|
hallchr/TidySumData
|
4386851d459e946453e89fa45549a9c3c5a97c41
|
85f5705336f82b9997be93b6a9eaf49dcf8a08ca
|
refs/heads/main
| 2023-05-12T08:08:37.872466
| 2021-06-06T17:38:05
| 2021-06-06T17:38:05
| 366,885,602
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,212
|
r
|
tidy_text.R
|
#Working with Text
library(tidyverse)
#install.packages('janitor')
library(janitor)
#install.packages('skimr')
library(skimr)
library(stringr)
#install.packages('htmlwidgets')
library(htmlwidgets)
#Beyond working with single strings and string literals, sometimes the information you’re analyzing is a whole body of text.
#Tidy text used to analyze whole bodies of text - like books, etc!
#Tidy Text
# install.packages("tidytext")
library(tidytext)
carrots <- c("They say that carrots are good for your eyes",
"They swear that they improve your sight",
"But I'm seein' worse than I did last night -",
"You think maybe I ain't usin' em right?")
carrots
#put in tibble for tidyness
library(tibble)
text_df <- tibble(line = 1:4, text = carrots)
text_df
#tokenization turning each row into a single word
text_df %>%
unnest_tokens(word, text) #word is splitting into one-word, text is selecting column of text_df to use.
#Sentiment Analysis
#Often, once you’ve tokenized your dataset, there is an analysis you want to do - a question you want to answer. Sometimes,
#this involves wanting to measure the sentiment of a piece by looking at the emotional content of the words in that piece.
#To do this, the analyst must have access to or create a lexicon, a dictionary with the sentiment of common words. There
#are three single word-based lexicons available within the tidytext package: afinn, bing, loughran and nrc. Each differs
#in how they categorize sentiment, and to get a sense of how words are categorized in any of these lexicon, you can use the
#get_sentiments() function.
library(textdata)
# be sure textdata is installed
#install.packages("textdata", repos = 'http://cran.us.r-project.org')
# see information stored in NRC lexicon
get_sentiments('nrc')
text_df %>%
unnest_tokens(word, text) %>%
inner_join(get_sentiments('nrc'))
## Joining, by = "word"
text_df %>%
unnest_tokens(word, text) %>%
inner_join(get_sentiments('nrc')) %>%
count(sentiment, sort = TRUE)
#Word and document frequency
#Beyond sentiment analysis, analysts of text are often interested in quantifying what a document is about.
#A document’s inverse document frequency (idf) weights each term by its frequency in a collection of documents. Those words
#that are quite common in a set of documents are down-weighted. The weights for words that are less common are increased. By
#combining idf with term frequency (tf) (through multiplication), words that are common and unique to that document (relative
#to the collection of documents) stand out.
#so looking at relative weights are important because no one cares how many words such as "and" or "or" there are....
library(tibble)
invitation <- c("If you are a dreamer, come in,",
"If you are a dreamer, a wisher, a liar",
"A hope-er, a pray-er, a magic bean buyer…",
"If you’re a pretender, come sit by my fire",
"For we have some flax-golden tales to spin.",
"Come in!",
"Come in!")
invitation <- tibble(line = 1:7, text = invitation, title = "Invitation")
invitation
masks <- c("She had blue skin.",
"And so did he.",
"He kept it hid",
"And so did she.",
"They searched for blue",
"Their whole life through",
"Then passed right by—",
"And never knew")
masks <- tibble(line = 1:8, text = masks, title = "Masks")
masks
# add title to carrots poem
carrots <- text_df %>% mutate(title = "Carrots")
# combine all three poems into a tidy data frame
poems <- bind_rows(carrots, invitation, masks)
# count number of times word appwars within each text
poem_words <- poems %>%
unnest_tokens(word, text) %>%
count(title, word, sort = TRUE)
# count total number of words in each poem
total_words <- poem_words %>%
group_by(title) %>%
summarize(total = sum(n))
## `summarise()` ungrouping output (override with `.groups` argument)
# combine data frames
poem_words <- left_join(poem_words, total_words)
## Joining, by = "title"
poem_words
library(ggplot2)
# visualize frequency / total words in poem
ggplot(poem_words, aes(n/total, fill = title)) +
geom_histogram(show.legend = FALSE, bins = 5) +
facet_wrap(~title, ncol = 3, scales = "free_y")
#look at frequency of words relative to document length
freq_by_rank <- poem_words %>%
group_by(title) %>%
mutate(rank = row_number(),
`term frequency` = n/total)
#look at relative frequency while taking into account common words!
poem_words <- poem_words %>%
bind_tf_idf(word, title, n)
# sort ascending
poem_words %>%
arrange(tf_idf)
poem_words %>%
arrange(desc(tf_idf))
#We can summarize these tf-idf results by visualizing the words with the highest tf-idf in each of these poems:
poem_words %>%
arrange(desc(tf_idf)) %>%
mutate(word = factor(word, levels = rev(unique(word)))) %>%
group_by(title) %>%
top_n(3) %>%
ungroup() %>%
ggplot(aes(word, tf_idf, fill = title)) +
geom_col(show.legend = FALSE) +
labs(x = NULL, y = "tf-idf") +
facet_wrap(~title, ncol = 3, scales = "free") +
coord_flip()
|
07e1c49e887ec2a7ef17f5106ed3720e6d15fefb
|
96aba36ec950b4752423cd352e56001e4f14d33b
|
/ExploratoryDataAnalysis/Week1/BasePlottingDemo.R
|
fec1a9a769b04d2c1d64a3f1fc6d21335bd22743
|
[] |
no_license
|
figoyouwei/datasciencecoursera
|
4f879e6cd23cbcd0b99981741520d9ea8443c817
|
ddd307451d8158fa6a58c655a513748a6dcfbf4e
|
refs/heads/master
| 2021-01-10T20:25:35.309704
| 2014-09-21T06:52:59
| 2014-09-21T06:52:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,109
|
r
|
BasePlottingDemo.R
|
# ----- show the example of plotting symbols
example(points)
# ----- little scatter plot demo with a model fit
x <- rnorm(100)
y <- rnorm(100)
plot(x, y, pch=20, xlab="Weight", ylab="Height")
title("scatter plot")
text(-2, -2, "label")
legend("topleft", legend="data", pch=20)
fit <- lm(y ~ x)
abline(fit, lwd=3, col="red")
# ----- separate groups of data points
par(mfrow=c(1,1),mar=c(4,4,2,2))
x <- rnorm(100)
y <- x + rnorm(100)
g <- gl(2, 50, labels=c("Male", "Female"))
plot(x, y, type="n") # not display anything on the canvas
points(x[g=="Male"],y[g=="Male"],col="blue",pch=19)
points(x[g=="Female"],y[g=="Female"],col="red")
legend("topleft", legend=c("male","female"), col=c("blue","red"), pch=c(19,1))
# ----- ----- ----- ----- Base Graphics ----- ----- ----- ----- #
# 1. initialize a new plot
# 2. annotate an existing plot
# It offers a high degree of control over plotting
# ----- Simple Base Graphics: Histogram, Scatter,Boxplot
library(datasets)
hist(airquality$Ozone)
with(airquality,plot(Wind,Ozone))
airquality <- transform(airquality,Month=factor(Month))
boxplot(Ozone ~ Month, airquality, xlab="Month", ylab="Ozone")
# ----- Some important Base Graphics Parameters
colors()
par(bg="gray")
with(airquality,plot(Wind,Ozone,pch="a",col="red")) # take a character element
with(airquality,plot(Wind,Ozone,pch=3,col="blue")) # take a shape element (numbered)
with(airquality,plot(Wind,Ozone,xlab="windy",ylab="O3"))
# ----- multiple panels on one canvas
par(mfrow = c(2, 3))
for (i in 1:6) {
with(airquality,plot(Wind,Ozone,xlab="windy",ylab="O3",col=colors()[i]))
}
# ----- margin of a plot (bottom->left->top->right)
par("mar"=c(5,4,3,3))
with(airquality,plot(Wind,Ozone,xlab="windy",ylab="O3",col=colors()[i]))
# ----- lines/points/text/title/mtext/axis
par(mfrow = c(1, 1))
with(airquality,plot(Wind,Ozone,xlab="windy",ylab="O3",col="blue"))
title(main = "Ozone and Wind")
with(subset(airquality,Month==5),points(Wind,Ozone,col="red"))
lines()
# ----- type = "n"
with(airquality,plot(Wind,Ozone,type="n")) # just set up the canvas
with(subset(airquality,Month=!5),points(Wind,Ozone,col="red"))
with(subset(airquality,Month==5),points(Wind,Ozone,col="blue"))
legend("topright",pch=1,col=c("red","blue"),legend=c("May","Other months"))
# ----- Regression Line ***
with(airquality,plot(Wind,Ozone,main="Ozone and Wind in New York City",pch=20))
model <- lm(Ozone ~ Wind, airquality)
abline(model,lwd=2)
# ----- Multiple Panels within with()
par(mfrow = c(1,2))
with(airquality,{
plot(Wind,Ozone,main="Ozone and Wind")
plot(Solar.R,Ozone,main="Ozone and Solar Radiation")
})
# ----- set inner margin and outer margin
par(mfrow=c(1,3), mar=c(4,4,2,1), oma=c(0,0,2,0))
with(airquality,{
plot(Wind,Ozone,main="Ozone and Wind")
plot(Solar.R,Ozone,main="Ozone and Solar Radiation")
plot(Temp,Ozone,main="Ozone and Temperature")
})
mtext("New York City",outer=TRUE, side=3, at=c(0.5))
# ----- little function to reset par() and call par(resetPar())
resetPar <- function() {
dev.new()
op <- par(no.readonly = TRUE)
dev.off()
op
}
|
c009baf676501334da0b5e848a4d2f17b087008f
|
8627421980f3a8e357a1590aac3a9d73eeef6561
|
/R/getThePercent.R
|
5387d4f086b1d7366b3397f42edf41848f6e8f53
|
[] |
no_license
|
zhaodexuan/NERF
|
00a62b7987d8cc764f36719ecaa211de77179fe4
|
798076c3ca5ec36016a18bfa168e8650d75d15d4
|
refs/heads/master
| 2023-08-10T09:01:44.037413
| 2023-07-24T15:48:05
| 2023-07-24T15:48:05
| 228,681,419
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,516
|
r
|
getThePercent.R
|
#' @title Step Percent of Random Replacement Deviation
#'
#' @description Step by step list the proportionally random expectation deviations.
#'
#' @param theData The prepared data matrix.
#'
#' @param theExpectPoint The expectation list.
#'
#' @param theCategory The Calculated Category.
#'
#' @param theDim The Calculated Dimensions.
#'
#' @param theStep An array of random replacement ratio.
#'
#' @param maxBoot The maximum steps of bootstrap.
#'
#' @param theCompare = 'between', 'lower', 'upper', 'mean'
#'
#' @param theAlt = 'two.sided', 'greater', 'less'
#'
#' @param theSig = 0.05
#'
#' @param ifItem = FALSE, calculate the items when TRUE.
#'
#' @param theCompareItem = 'between', 'lower', 'upper', 'mean'
#'
#' @param theAltItem = 'two.sided', 'greater', 'less'
#'
#' @param theSigItem = 0.05
#'
#' @return The function returns a list.
#'
#' @author zdx, \email{zhaodexuan@aliyun.com}
#'
#' @examples
#' \dontrun{
#' thePercent <- getThePercent(theData, theExpectPoint, theCategory, theDim)
#' }
#'
#' @export
#'
getThePercent <- function(theData, theExpectPoint, theCategory, theDim,
theStep = c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1), maxBoot = 1000,
theCompare = 'upper', theAlt = 'less', theSig = 0.05, ifItem = FALSE,
theCompareItem = 'upper', theAltItem = 'less', theSigItem = 0.05){
nFac <- max(theDim)
thePR <- list()
names(theExpectPoint) <- c('probability','expectation')
for (s in 1:length(theStep)) {
# s <- 1
tempPrintP <- paste0('percent', theStep[s], ':')
# print(tempPrintP)
theDeviation <- getTheDeviation(theData, theExpectPoint, theCategory, theDim,
RandomReplaceRatio = theStep[s], maxBoot = maxBoot, theCompare = theCompare,
theAlt = theAlt, theSig = theSig, tempPrint = tempPrintP, ifItem = ifItem,
theCompareItem = theCompareItem, theAltItem = theAltItem, theSigItem = theSigItem)
theOutMAD <- list()
theOutRMSD <- list()
theOutWMAD <- list()
theOutWRMSD <- list()
for (k in 1:nFac) {
MAD <- unlist(theDeviation[[1]]) # nTestee, 1observe_2mean_3lower_4upper_5sign, nFac
RMSD <- unlist(theDeviation[[2]])
WMAD <- unlist(theDeviation[[3]])
WRMSD <- unlist(theDeviation[[4]])
theFacMAD <- c()
for (i in 1:length(theData[,1])) {
if(!is.na(MAD[i,5,k])){
theFacMAD <- c(theFacMAD,i)
}
}
theFacRMSD <- c()
for (i in 1:length(theData[,1])) {
if(!is.na(RMSD[i,5,k])){
theFacRMSD <- c(theFacRMSD,i)
}
}
theFacWMAD <- c()
for (i in 1:length(theData[,1])) {
if(!is.na(WMAD[i,5,k])){
theFacWMAD <- c(theFacWMAD,i)
}
}
theFacWRMSD <- c()
for (i in 1:length(theData[,1])) {
if(!is.na(WRMSD[i,5,k])){
theFacWRMSD <- c(theFacWRMSD,i)
}
}
theOutMAD[[k]] <- theFacMAD
theOutRMSD[[k]] <- theFacRMSD
theOutWMAD[[k]] <- theFacWMAD
theOutWRMSD[[k]] <- theFacWRMSD
}
theStepPR <- list()
theStepPR[[1]] <- theOutMAD
theStepPR[[2]] <- theOutRMSD
theStepPR[[3]] <- theOutWMAD
theStepPR[[4]] <- theOutWRMSD
theStepPR[[5]] <- theDeviation
names(theStepPR) <- c('outMAD','outRMSD','outWMAD','outWRMSD','theDeviation')
thePR[[s]] <- theStepPR
}
names(thePR) <- c(paste0('percent', theStep))
return(thePR)
}
|
2c827fc8f925ffc93892ee478a030ee0eb496106
|
ec60103c7e33e6c2180c2efc6b33a7f83ae0b877
|
/dynamicAnalysis.R
|
57f24ee9aa28308f5bbec23e7dc35c94a72112e0
|
[] |
no_license
|
standardgalactic/adaptiveSharingSimulations
|
bc27ec5f1bb64367cb46d025752c8d1dd665b7a9
|
728becc37057e02da9f43b2dbb41f3075780afbc
|
refs/heads/master
| 2023-03-15T16:25:35.965790
| 2018-07-21T15:40:20
| 2018-07-21T15:40:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 12,750
|
r
|
dynamicAnalysis.R
|
#Script to analyize dynamic simulation data
#Charley Wu and Imen Bouhlel
rm(list=ls())
#load packages
packages <- c('zoo', 'RColorBrewer', 'scales', 'data.table', 'plyr', 'ggplot2')
lapply(packages, require, character.only=TRUE)
###################################
#Compile data
###################################
#Simplified data, mean score averaged over round; TAKES LESS TIME
# Data <- data.frame( score = numeric(), round = numeric(), agent = numeric(), sharer = numeric(), numAgents = numeric(), numDimensions = numeric(), changeProbability = numeric(), freeLocalInfoRadius = numeric(), sharingCondition = character(), changeRate = numeric(), decayRate = numeric(), nb_sharers = numeric(), environmentType = character())
# for (comb in 1:540){
# singleData <- get(load(paste0("simulationData/dynamic/",comb,".Rdata")))
# singleData <- ddply(singleData, ~agent+sharer+numAgents+numDimensions+changeProbability+freeLocalInfoRadius+sharingCondition+changeRate+decayRate,summarise,meanScore=mean(score))
# Data <- rbind(Data, singleData)
# }
# Data$sharingCondition <- factor(Data$sharingCondition, levels = c("All", "Free-rider", "Free-giver", "None"))
# save(Data, file = "simulationData/dynamic/simplified.Rdata") #save simplified version
simplifiedDF <- get(load("simulationData/dynamic/simplified.Rdata")) #must run above block of code first
simplifiedDF$meanScore <- simplifiedDF$meanScore * 100 #normalize to 100
###################################
#Preparing heatmap analysis data
###################################
#Make sure this matches simulation parameters
agentVec <- c(10) #c(4)
Dimensions<- c(7) #c(14)
changeProbabilityVec <- c(0, 0.5, 1)
localInfoRadiusVec <- c(0,1,2)
sharingConditions <- c("All", "None", "Free-rider", "Free-giver")
numValues <- 10 # number of different values that a dimension could take
changeRate <- c(0.25, 0.5, 0.75)
decayRate <- c(0.9, 0.8, 0.7, 0.6, 0.5)
turns<-100
#Combination of parameter values
heatMapOps <- expand.grid(agentVec, # numAgents
changeProbabilityVec, # changeProbability
Dimensions, # numDimensions
localInfoRadiusVec,# freeLocalInfoRadius
changeRate, #likelihood of environmental change
decayRate, #decay rate of memory of previous rewards
sharingConditions) #Sharing conditions
colnames(heatMapOps)<- c('numAgents', 'changeProbability', 'numDimensions', 'freeLocalInfoRadius', "changeRate", "decayRate", "sharingCondition" )
#heatMapData
heatMapData <- data.frame(numAgents = numeric(), Innovation = numeric(), numDimensions = numeric(), Visibility = numeric(), EnvironmentChange = numeric(), DiscountRate=numeric(), relativeBenefit_FreeRiding=numeric(), relativeBenefit_FreeGiving=numeric())
#calculte MarginalBenefit_FreeRiding and MarginalBenefit_FreeGiving (for each agent!) for each parameter values combination and add it to heatMapData
for (row in (1:nrow(heatMapOps))){
cond <- heatMapOps[row,] #condition
singleData <- subset (simplifiedDF, numAgents==cond$numAgents & changeProbability==cond$changeProbability & numDimensions==cond$numDimensions & freeLocalInfoRadius==cond$freeLocalInfoRadius & changeRate == cond$changeRate & decayRate == cond$decayRate)
targetAgent <- subset(singleData, agent==1)
#Compute marginal benefits
relativeBenefitsFreeRiding <- (subset(targetAgent, sharingCondition=="All")$meanScore - subset(targetAgent, sharingCondition=="Free-rider" )$meanScore) #/ subset(targetAgent, sharingCondition=="Free-rider" )$meanScore #note: positive value means sharing is beneficial
relativeBenefitsFreeGiving <- (subset(targetAgent, sharingCondition=="Free-giver" )$meanScore - subset(targetAgent, sharingCondition=="None")$meanScore) #/ subset(targetAgent, sharingCondition=="None")$meanScore #note: positive value means sharing is beneficial
relativeBenefits <-data.frame( numAgents=cond$numAgents, Innovation=cond$changeProbability, numDimensions=cond$numDimensions, Visibility=cond$freeLocalInfoRadius, EnvironmentChange =cond$changeRate, DiscountRate = cond$decayRate, relativeBenefit_FreeRiding=relativeBenefitsFreeRiding, relativeBenefit_FreeGiving=relativeBenefitsFreeGiving)
heatMapData <- rbind(heatMapData, relativeBenefits)
}
#compute average across freeriding and freegiving benefits
heatMapData$sharingBenefit <- (heatMapData$relativeBenefit_FreeRiding + heatMapData$relativeBenefit_FreeGiving) /2
###################################
#Heatmaps
###################################
cols <- rev(brewer.pal(11, 'RdBu'))
p1 <- ggplot(heatMapData, aes(x=EnvironmentChange, y = DiscountRate, fill = sharingBenefit)) +
geom_tile()+
scale_fill_distiller(palette = "Spectral", na.value = 'white', name = "Benefit of Sharing")+
theme_classic() +
coord_equal() +
facet_grid( Visibility~ Innovation, labeller = label_both)+
theme(text = element_text(size=14, family="sans"))+
#scale_x_continuous(breaks = round(seq(5,15, by = 2),1))+
xlab("log Memory Window")+
ylab("Change Rate")+
theme(legend.position="right", strip.background=element_blank(), legend.key=element_rect(color=NA))+
ggtitle('Combined benefits of sharing')
p1
ggsave(filename = "plots/aggregatedBenefits.pdf", plot = p1, height =9, width = 8, units = "in")
p2<- ggplot(heatMapData, aes(x=DiscountRate, y = EnvironmentChange, fill = relativeBenefit_FreeRiding)) +
geom_tile()+
#scale_fill_distiller(palette = "Spectral", na.value = 'white', name = "Benefit of Sharing")+
scale_fill_gradientn(colours = cols, limits = c(-1.9, 1.9), name = "Benefits\nof Sharing" )+ # limits = c(-0.035, 0.035),
#scale_fill_gradient2(low = "darkred", mid = "white", high = "midnightblue", midpoint = 0) +
theme_classic() +
facet_grid( Visibility~ Innovation, labeller = label_both)+
theme(text = element_text(size=14, family="sans"))+
scale_x_continuous(breaks = round(seq(0.5,1, by = 0.1),1))+
xlab("Discount Rate")+
ylab("Environmental Change")+
theme(legend.position="right", strip.background=element_blank(), legend.key=element_rect(color=NA))+
ggtitle('Sharing when others share')
p2
ggsave(filename = "plots/dynamicbenefitOthersShare.pdf", plot = p2, height =5, width = 8, units = "in")
p3<- ggplot(heatMapData, aes(x=DiscountRate, y = EnvironmentChange, fill = relativeBenefit_FreeGiving)) +
geom_tile()+
#scale_fill_distiller(palette = "Spectral", na.value = 'white', name = "Benefit of Sharing")+
scale_fill_gradientn(colours = cols, limits = c(-21, 21), name = "Benefits\nof Sharing" )+ # limits = c(-0.035, 0.035),
#scale_fill_gradient2(low = "darkred", mid = "white", high = "midnightblue", midpoint = 0) +
theme_classic() +
facet_grid( Visibility~ Innovation, labeller = label_both)+
theme(text = element_text(size=14, family="sans"))+
scale_x_continuous(breaks = round(seq(0.5,1, by = 0.1),1))+
xlab("Discount Rate")+
ylab("Environmental Change")+
theme(legend.position="right", strip.background=element_blank(), legend.key=element_rect(color=NA))+
ggtitle('Sharing when others don\'t share')
p3
ggsave(filename = "plots/dynamicbenefitOthersDontShare.pdf", plot = p3, height =5, width = 8, units = "in")
###################################
#Learning Curves
###################################
# #Full data; TAKES A LONG TIME!
# #Takes a long time!
# fullData <- data.frame( score = numeric(), round = numeric(), agent = numeric(), sharer = numeric(), numAgents = numeric(), numDimensions = numeric(), changeProbability = numeric(), freeLocalInfoRadius = numeric(), sharingCondition = character(), changeRate = numeric(), decayRate=numeric(), nb_sharers = numeric(), environmentType = character())
# for (comb in 1:540){
# singleData <- get(load(paste0("simulationData/dynamic/",comb,".Rdata")))
# fullData <- rbind(fullData, singleData)
# }
# fullData$sharingCondition <- factor(fullData$sharingCondition, levels = c("All", "Free-rider", "Free-giver", "None"))
# save(fullData, file = "simulationData/dynamic/fullData.Rdata") #save simplified version
fullData <- get(load("simulationData/dynamic/fullData.Rdata")) #run above block of code first
fullData$score <- fullData$score *100 #normalize to 100
#5 trial average
fullData$trial5<-round((fullData$round+1)/5)*5
fullData$trial5<-ifelse(fullData$trial5<5,0,fullData$trial5)
dplot5<-ddply(fullData,~trial5+numAgents+numDimensions+changeProbability+freeLocalInfoRadius+sharingCondition+agent+changeRate+decayRate,summarise,meanScore=mean(score))
summary(dplot5)
panel1 <- subset(dplot5, changeRate==0.25 & decayRate == 0.8 )
panel1$Visibility <- panel1$freeLocalInfoRadius
panel1$Innovation <- panel1$changeProbability
panel1$EnvironmentChange <- panel1$changeRate
panel1$DiscountRate <- panel1$decayRate
levels(panel1$sharingCondition) <- c("All sharers", "Free-rider", "Free-giver", "No sharers")
p4target<- ggplot(subset(panel1, agent==1), aes(x=trial5, y = meanScore, color = sharingCondition, fill= sharingCondition, shape = sharingCondition)) +
#geom_smooth(fill=NA, size = 0.7, method = "lm", formula = y ~ poly(x, 20))+
geom_line(size = 0.7)+
geom_point(data=subset(panel1, agent==1 & trial5%%10==0), aes(x=trial5, y = meanScore, color = sharingCondition, fill= sharingCondition, shape = sharingCondition), size = 2)+
theme_classic()+
scale_color_brewer(palette='Dark2', name ="")+
scale_fill_brewer(palette= 'Dark2', name = "")+
scale_shape_discrete(solid = TRUE, name = "")+
xlab("Trial") +
ylab("Mean Score") +
facet_grid(Visibility~Innovation , labeller = label_both)+
scale_x_continuous(breaks = scales::pretty_breaks(n = 4))+
theme(legend.position="right", strip.background=element_blank(), legend.key=element_rect(color=NA), text = element_text(size=16, family="sans"))
p4target
ggsave(filename = "plots/dynamicCurves.pdf", plot = p4target, height =4.5, width =8, units = "in")
p4all<- ggplot(panel1, aes(x=round, y = score, color = sharingCondition, fill= sharingCondition, shape = sharingCondition)) +
geom_smooth(fill=NA, size = 0.7)+
stat_summary(data=subset(panel1, round%%10==1), fun.y = mean, geom='point', aes(x=round, y = score, color = sharingCondition, fill= sharingCondition, shape = sharingCondition))+
theme_classic()+
scale_color_brewer(palette='Dark2', name ="")+
scale_fill_brewer(palette= 'Dark2', name = "")+
scale_shape_discrete(solid = TRUE, name = "")+
xlab("Trial") +
ylab("Mean Score") +
facet_grid( ~Visibility , labeller = label_both)+
theme(legend.position="bottom", strip.background=element_blank(), legend.key=element_rect(color=NA), text = element_text(size=16, family="sans"))
p4all
ggsave(filename = "plots/visibilityAll.pdf", plot = p4all, height =3.5, width = 5.5, units = "in")
panel2 <- subset(fullData, numAgents == 4 & numDimensions == 8 & changeProbability %in% c(0,0.5,1) & freeLocalInfoRadius %in% c(0,1,2))
panel2$Visibility <- panel2$freeLocalInfoRadius
panel2$Innovation <- panel2$changeProbability
p5target<- ggplot(subset(panel2, agent==1), aes(x=round, y = score, color = sharingCondition, fill= sharingCondition, shape = sharingCondition)) +
geom_smooth(fill=NA, size = 0.7, method = )+
geom_point(data=subset(panel2, agent==1 & round%%10==1), aes(x=round, y = score, color = sharingCondition, fill= sharingCondition, shape = sharingCondition))+
theme_classic()+
scale_color_brewer(palette='Dark2', name ="")+
scale_fill_brewer(palette= 'Dark2', name = "")+
scale_shape_discrete(solid = TRUE, name = "")+
xlab("Trial") +
ylab("Mean Score") +
facet_grid(Innovation ~Visibility , labeller = label_both)+
theme(legend.position="bottom", strip.background=element_blank(), legend.key=element_rect(color=NA), text = element_text(size=16, family="sans"))
p5target
ggsave(filename = "plots/innovationTarget.pdf", plot = p5target, height =3.5, width = 5.5, units = "in")
p5all<- ggplot(panel2, aes(x=round, y = score, color = sharingCondition, fill= sharingCondition, shape = sharingCondition)) +
geom_smooth(fill=NA, size = 0.7, method = )+
stat_summary(data=subset(panel2, round%%10==1), fun.y = mean, geom='point', aes(x=round, y = score, color = sharingCondition, fill= sharingCondition, shape = sharingCondition))+
theme_classic()+
scale_color_brewer(palette='Dark2', name ="")+
scale_fill_brewer(palette= 'Dark2', name = "")+
scale_shape_discrete(solid = TRUE, name = "")+
xlab("Trial") +
ylab("Mean Score") +
facet_grid(Innovation ~Visibility , labeller = label_both)+
theme(legend.position="bottom", strip.background=element_blank(), legend.key=element_rect(color=NA), text = element_text(size=16, family="sans"))
p5all
ggsave(filename = "plots/innovationall.pdf", plot = p5all, height =3.5, width = 5.5, units = "in")
|
e581c3f6c5c65a2873f23ded963f0044aa87f851
|
a811d5440137a37907dc8e50b45c4ebe0664b61f
|
/cachematrix.R
|
3049d0188c3903ad417ba2ebd5e61a6a8fee877f
|
[] |
no_license
|
puikchan/ProgrammingAssignment2
|
84d038af2bd8fac1e77a02f2588a2a5fe760aa4c
|
a9ab1fa804befbef22dcdd528295580524a3e873
|
refs/heads/master
| 2021-01-14T12:15:05.219372
| 2014-04-24T03:27:55
| 2014-04-24T03:27:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,403
|
r
|
cachematrix.R
|
## Function makeCacheMatrix
## It takes an argument x of type numeric matrix
## It returns a list of 4 functions
## list (set = set, get - get, getInv = set Inv, getInv = getInv)
## Example usage:
## a <- makeCacheMatrix(matrix(1:4,2))
## a$get()
## a$getInv()
## a$set(matrix(5:8,2))
## a$get()
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setInv <- function(solve) m <<- solve
getInv <- function() m
list(set = set, get = get,
setInv = setInv,
getInv = getInv)
}
## Function cacheSolve -- returns a matrix that is the inverse of argument x
## Example usage:
## a <- makeCacheMatrix(matrix(1:4,2))
## cacheSolve(a)
## cacheSolve(a)
## a$getInv()
## b = a$getInv()
## a$get() %*% b
cacheSolve <- function(x, ...) {
m <- x$getInv() # query the x Inverse Matrix's cache
if(!is.null(m)) { # if there is a cache
message("getting cached data")
return(m) # just return the cache, no computation needed
}
data <- x$get() # if there's no cache
m <- solve(data, ...) # we actually compute them here
x$setInv(m) # save the result back to x's cache
m # return the result
}
|
21b1897238b37db65ed39f7d1f76a87fd86c147d
|
b8a14c99a9a982009d6bfb17cd38f5f15877c40a
|
/man/eblupgeo.Rd
|
d752d5861d9c3fb8d87aa97790e80082ac0cda61
|
[] |
no_license
|
ketutdika/geoSAE
|
9ff07f7a5b1e641df43856276df0a0465dee1856
|
18710b2937d718617a99f9abb366cf35a3f4d8a9
|
refs/heads/master
| 2023-06-02T13:29:15.924404
| 2021-06-15T09:25:47
| 2021-06-15T09:25:47
| 374,709,910
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 2,015
|
rd
|
eblupgeo.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/eblupGeo.R
\name{eblupgeo}
\alias{eblupgeo}
\title{EBLUP's for domain means using Geoadditive Small Area Model}
\usage{
eblupgeo(formula, zspline, dom, xmean, zmean, data)
}
\arguments{
\item{formula}{the model that to be fitted}
\item{zspline}{n*k matrix that used in model for random effect of spline-2 (n is the number of observations, and k is the number of knots used)}
\item{dom}{a*1 vector with domain codes (a is the number of small areas)}
\item{xmean}{a*p matrix of auxiliary variables means for each domains (a is the number of small areas, and p is the number of auxiliary variables)}
\item{zmean}{a*k matrix of spline-2 means for each domains}
\item{data}{data unit level that used as data frame that containing the variables named in formula and dom}
}
\value{
This function returns a list of the following objects:
\item{eblup}{A Vector with a list of EBLUP with Geoadditive Small Area Model}
\item{fit}{A list of components of the formed Geoadditive Small Area Model that containing the following objects such as model structure of the model, coefficients of the model, method, and residuals}
\item{sigma2}{Variance (sigma square) of random effect and error with Geoadditive Small Area Model}
}
\description{
This function calculates EBLUP's based on unit level using Geoadditive Small Area Model
}
\examples{
#Load the dataset for unit level
data(dataUnit)
#Load the dataset for spline-2
data(zspline)
#Load the dataset for area level
data(dataArea)
#Construct the data frame
y <- dataUnit$y
x1 <- dataUnit$x1
x2 <- dataUnit$x2
x3 <- dataUnit$x3
formula <- y~x1+x2+x3
zspline <- as.matrix(zspline[,1:6])
dom <- dataUnit$area
xmean <- cbind(1,dataArea[,3:5])
zmean <- dataArea[,7:12]
number <- dataUnit$number
area <- dataUnit$area
data <- data.frame(number, area, y, x1, x2, x3)
#Estimate EBLUP
eblup_geosae <- eblupgeo(formula, zspline, dom, xmean, zmean, data)
}
|
c5c7520fa1c30c12a741df5b0cd969b5e5187d4f
|
e5836fa0f8b22d303c5299f3fc2a23638430203f
|
/scripts/owls-example/diagnostics-stage-one-table.R
|
954ca863bef451edf33265b6012e43e9908971d0
|
[] |
no_license
|
hhau/melding-multiple-phi
|
dbd668cebf031428680126bb1a6d3abdf26a12d4
|
52c71674b75ff6a530581aa669bac0bce916f7fa
|
refs/heads/master
| 2023-04-17T12:21:21.671249
| 2022-08-31T13:15:17
| 2022-08-31T13:15:17
| 251,345,078
| 6
| 1
| null | 2021-03-02T11:03:39
| 2020-03-30T15:20:22
|
TeX
|
UTF-8
|
R
| false
| false
| 1,494
|
r
|
diagnostics-stage-one-table.R
|
library(rstan)
library(kableExtra)
library(dplyr)
library(tibble)
# load model 1 and model 3 samples
capture_recapture_submodel_samples <- readRDS(
"rds/owls-example/capture-recapture-subposterior-samples.rds"
)
fecunditiy_submodel_samples <- readRDS(
"rds/owls-example/fecundity-subposterior-samples.rds"
)
# find then parameters within each model that have
# minimum ESS
# Maximum Rhat
# and plot the traces for each
pars <- sprintf("v[%d]", c(1, 2))
fecundity_diagnostics <- monitor(fecunditiy_submodel_samples, print = FALSE)
capture_recapture_diagnostics <- monitor(
capture_recapture_submodel_samples[, , pars],
print = FALSE
)
parameter_recode_vector <- c(
'v[1]' = '$\\alpha_{0}$',
'v[2]' = '$\\alpha_{2}$',
'rho' = '$\\rho$'
)
res <- bind_rows(
rownames_to_column(as.data.frame(capture_recapture_diagnostics)),
rownames_to_column(as.data.frame(fecundity_diagnostics))
) %>%
select(par = rowname, n_eff, Rhat, Bulk_ESS, Tail_ESS) %>%
rename(
"Parameter" = par,
"$N_{\\text{eff}}$" = n_eff,
"$\\widehat{R}$" = Rhat,
"Bulk ESS" = Bulk_ESS,
"Tail ESS" = Tail_ESS,
)
res$Parameter <- res$Parameter %>%
recode(!!!parameter_recode_vector)
kable_res <- kable(
x = res,
format = "latex",
digits = 2,
booktabs = TRUE,
escape = FALSE
) %>%
kable_styling(latex_options = c("striped", "hold_position")) %>%
column_spec(1, "2cm")
cat(
kable_res,
file = "tex-input/owls-example/appendix-info/0010-stage-one-diagnostics.tex"
)
|
cd31585c972e6aba39cd568c64824bb7d6b60388
|
7456d3eae8574560e823cd4180579e7e16a5c9f0
|
/tests/testthat/test_differential_expression.R
|
787b5e05893decc015f8fece90ec40e77e18f989
|
[] |
no_license
|
fbertran/ebadimex
|
7f362e82315f4172eef5798c57765611b3a311bc
|
e0db30de62b1b4d8fbd59cd567ffb4c4af498ba9
|
refs/heads/master
| 2021-09-22T03:20:25.246862
| 2018-09-05T18:34:46
| 2018-09-05T18:34:46
| 257,308,813
| 1
| 0
| null | 2020-04-20T14:36:00
| 2020-04-20T14:35:59
| null |
UTF-8
|
R
| false
| false
| 1,765
|
r
|
test_differential_expression.R
|
library(testthat)
context("Differential Expression")
# Agree with t-test
test_that("Agreement with t.test",{
x <- rnorm(30, 0, 0.4)
y <- rnorm(50, 0.2, 0.4)
irksome_test <- testDE(c(x,y), rep(c(T,F), times = c(30, 50)), k_win = 100)[1]
t_test <- log(t.test(x, y, var.equal = T)$p.value)
expect_lt(abs(irksome_test[['p_location']] - t_test), 1e-9)
})
test_that("Agreement with moderated t-test",{
x <- rnorm(3, 0)
y <- rnorm(7, 0)
d0 <- 4
s0 <- 1.2
ep <- cbind(expr = c(1,2), d0 = c(d0,d0), s0 = c(s0,s0))
# Moderated t-test within ebadimex
ebadimex_test <- testDE(c(x,y), rep(c(T,F), times = c(3, 7)), prior = ep, k_win = 100)[1]
# Compute moderated t by hand
ssd1 <- sum((x - mean(x))^2)
ssd2 <- sum((y - mean(y))^2)
d_g <- 3 + 7 - 2
s2 <- (ssd1+ssd2) / d_g
s2_mod <- (d_g * s2 + d0 * s0) / (d_g + d0)
mod_t_test_statistic <- (mean(x) - mean(y)) / sqrt(s2_mod) / sqrt(1/3+1/7)
mod_t_test <- log(2*pt(-abs(mod_t_test_statistic), d_g + d0))
expect_lt(abs(ebadimex_test[['p_location']] - mod_t_test), 1e-9)
})
test_that("Agreement with Welch t.test",{
x <- rnorm(30, 0, 0.4)
y <- rnorm(50, 0.2, 0.4)
irksome_test <- testDE(c(x,y), rep(c(T,F), times = c(30, 50)), k_win = 100)
t_test <- log(t.test(x, y, var.equal = F)$p.value)
expect_lt(abs(irksome_test[['p_location_welch']] - t_test), 1e-9)
})
# Agree with F-test
test_that("Agreement with var.test",{
x <- rnorm(30, 0, 0.4)
y <- rnorm(50, 0.2, 0.4)
irksome_test <- testDE(c(x,y), rep(c(T,F), times = c(30, 50)), k_win = 100)
var_test <- log(var.test(x,y)$p.value)
expect_lt(abs(irksome_test[['p_scale']] - var_test), 1e-9)
})
# Agree with moderated F-test
test_that("Agreement with moderated F-test",{
})
|
6bb64190e5ab5de38465ce1b88e9832e765d12a8
|
9eddf4b44d0fe0d8bcb1884bf4c5bff35cee31a0
|
/ProgrammingAssignment5/plot4.R
|
6d70a5739278434ac46849d2bc67e0c147e3a753
|
[] |
no_license
|
istanton1/datasciencecoursera
|
e8dd34946d0ac543e2e2694adc8fc9b6c3970d5d
|
a6a69351708ac0cc95ccc8dbff334e7339ab9cbb
|
refs/heads/master
| 2021-01-01T20:34:53.118431
| 2017-02-27T16:10:34
| 2017-02-27T16:10:34
| 78,565,002
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 638
|
r
|
plot4.R
|
# Across the United States, how have emissions from coal
# combustion-related sources changed from 1999-2008?
library(ggplot2)
summary <- readRDS("./summarySCC_PM25.rds")
source <- readRDS("./Source_Classification_Code.rds")
merged <- merge(summary, source, by="SCC")
coal <- grepl("coal", merged$Short.Name, ignore.case=TRUE)
coalFinal <- merged[coal, ]
agg <- aggregate(Emissions ~ year, coalFinal, sum)
png("plot4.png")
plot <- ggplot(agg, aes(factor(year), Emissions)) +
geom_bar(stat = "identity") +
xlab("Year") +
ylab("Total PM2.5 Emissions") +
ggtitle('Total Coal Emissions from 1999 to 2008')
print(plot)
dev.off()
|
7139d1d4bb0ccdd94f37cefca06506a065052710
|
ff301c36e9ff64817554bd8d5198360cf0e07949
|
/MovieLensDataset - Project - MTD Final.R
|
cf9f2f53b04519a55d512462386934941fbef343
|
[] |
no_license
|
mtwistondavies/Capstone---Movielens-Project---MTD
|
0dc75f770d0500111a16d53e23ce4f0abc1c8ab1
|
5ebd3074624435091b28ebb55349c2c571c3a90f
|
refs/heads/main
| 2023-02-09T19:29:56.326302
| 2021-01-03T21:24:50
| 2021-01-03T21:24:50
| 326,502,995
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 30,700
|
r
|
MovieLensDataset - Project - MTD Final.R
|
# ---
# title: "MovieLens Project"
# author: "Michael Twiston Davies"
# date: "07/12/2020"
# output: html_document
# ---
# # Introduction
# ## History
# In 2006 Netflix created a $1m competition challenging data scientists to create a movie recommendation system better than their own "Cinematch". In order to qualify for the prize the challengers had to be 10% more accurate than Cinematch's predictions. In June 2009 it was beaten by multinational team called BellKor's Pragmatic Chaos. The winning model used a combination of Normalisation of Global Effects, Neighbourhood Models, Matrix Factorisation and Regression.
#
# ## The dataset
# The data set provided contains Userid, movieid, rating, timestamp, title and genres. Though we will note later on that in order to perform our complete analysis we will have to convert the timestamp into a more useful format and also will split the release year which currently is within the title.
#
# We will visualise the data within the method section.
#
# ## Aim
# This analysis aims to create a machine learning algorithm using techniques learnt in the Harvardx Data Science course. We will be utilising the MovieLens dataset provided to us and will go through a few different techniques to try and improve upon this model. The final model will then be validated against the validation data set. RMSE will be used to evaluate how close our predictions are to the true values in the validation set (the final hold-out test set). We intend to gain a RMSE < 0.86490 with our final validation.
#
# # Method
#
# ## Method - Overview
# We will use the "edx" data set created from the "Movie 10M data set" to develop our algorithm and the "validation" set to predict movie ratings as if they were unknown. RMSE will be used to evaluate how close the predictions are to the true values in the validation set (the final hold-out test set).
#
# Firstly we will split the "edx" data set into testing and training data sets.
#
# We will apply the following methods, the first of which were shown on the course, though we will build on these as we go through:
#
# - Model 1 - Just the average
# - Model 2 - Movie Effect Model
# - Model 3 - Movie + User Effects Model
# - Model 4 - Movie + User + Genre Effects Model
# - Model 5 - Movie + User + Genre + Time Effects Model
# - Model 6 - Regularized Movie Effect Model
# - Model 7 - Regularized Movie + User Effect Model
# - Model 8 - Regularized Movie + User + Genre Effect Model
# - Model 9 - Matrix Factorisation
#
# Regularisation will apply less weight to ratings with smaller n. For example some movies may have only been rated a handful of times and achieved a 5 star rating, this would likely decrease upon subsequent ratings therefore regularisation accounts for this.
#
# Our final model utilises matrix factorisation which decomposes the user-item interaction matrix into the product of two lower dimensionality rectangular matrices.
#
# # Data Preparation
#
# As mentioned above the below code will firstly pull the data, wrangle it into a useful format and split out the validation set.
# {r CreateDatasets, message=FALSE}
##########################################################
# Create edx set, validation set (final hold-out test set)
##########################################################
# packages to be used
library(tidyverse) # a multitude of useful functions
library(caret) # for prediction formulas
library(data.table)
library(lubridate) # easy date/time manipulation
library(recosystem) # Matrix factorisation
# Suppress summarise info
library(dplyr, warn.conflicts = FALSE) # use to supress grouping warning messages
options(dplyr.summarise.inform = FALSE) # use to supress grouping warning messages
# MovieLens 10M dataset:
# https://grouplens.org/datasets/movielens/10m/
# http://files.grouplens.org/datasets/movielens/ml-10m.zip
dl <- tempfile()
download.file("http://files.grouplens.org/datasets/movielens/ml-10m.zip", dl)
ratings <- fread(text = gsub("::", "\t", readLines(unzip(dl, "ml-10M100K/ratings.dat"))),
col.names = c("userId", "movieId", "rating", "timestamp"))
movies <- str_split_fixed(readLines(unzip(dl, "ml-10M100K/movies.dat")), "\\::", 3)
colnames(movies) <- c("movieId", "title", "genres")
movies <- as.data.frame(movies) %>% mutate(movieId = as.numeric(movieId),
title = as.character(title),
genres = as.character(genres))
movielens <- left_join(ratings, movies, by = "movieId")
# Validation set will be 10% of MovieLens data
set.seed(1, sample.kind="Rounding") # if using R 3.5 or earlier, use `set.seed(1)`
test_index <- createDataPartition(y = movielens$rating, times = 1, p = 0.1, list = FALSE)
edx <- movielens[-test_index,]
temp <- movielens[test_index,]
# Make sure userId and movieId in validation set are also in edx set
validation <- temp %>%
semi_join(edx, by = "movieId") %>%
semi_join(edx, by = "userId")
# Add rows removed from validation set back into edx set
removed <- anti_join(temp, validation)
edx <- rbind(edx, removed)
# Remove items no longer needed.
rm(dl, ratings, movies, test_index, temp, movielens, removed)
#
# The below code will then make the Timestamp more useful by creating Date and Weekday columns from it whilst also extracting the release year from the title.
# {r CreateDatasets1, message=FALSE}
##########################################################
# Timestamp/title split and Partition Edx dataset into test and training datasets
##########################################################
# Though firstly lets just add a few extra columns now which we will be using when adjusting for variations in time.
edx <- edx %>%
# The below creates Weekday/Date from Timestamp
mutate( Date = date(as.POSIXct(timestamp, origin='1970-01-01')) , Weekday = weekdays(Date)) %>%
#The below separates the title into title/release year.
extract(title, c("title_1", "releaseyear"), regex = "^(.*) \\(([0-9 \\-]*)\\)$", remove = F) %>%
mutate(releaseyear = if_else(str_length(releaseyear) > 4, as.integer(str_split(releaseyear, "-", simplify = T)[1]), as.integer(releaseyear))) %>%
mutate(title = if_else(is.na(title_1), title, title_1)) %>%
select(-title_1) %>%
# For genres with a blank for genre we will replace this with "no genre".
mutate(genres = if_else(genres == "(no genre)", `is.na<-`(genres), genres)) %>%
mutate( ReleasetoRatingTime = year(Date) - releaseyear)
# Partition Edx dataset into test and training datasets
test_index <- createDataPartition(y = edx$rating, times = 1,
p = 0.2, list = FALSE)
train_set <- edx[-test_index,]
test_set <- edx[test_index,]
rm(test_index)
# To make sure we don't include users and movies in the test set that do not appear in the training set, we removed these using the semi_join function, using this simple code.
test_set <- test_set %>%
semi_join(train_set, by = "movieId") %>%
semi_join(train_set, by = "userId")
#
# The below is a function created to calculate the residual means squared error for a vector of ratings and their corresponding predictors.
# {r RMSEFunction, message=FALSE}
RMSE <- function(true_ratings, predicted_ratings){
sqrt(mean((true_ratings - predicted_ratings)^2))
}
#
## Method - Data exploration
#
# To start us off lets just have a quick look at the first 6 lines in the data set.
# {r HeadEDX, echo=FALSE}
head(edx)
paste('There are',
edx %>%
summarize(n_users = n_distinct(userId)),
'users and',
edx %>%
summarize(n_movies = n_distinct(movieId)),
'movies in the edx dataset')
#
# If we take 100 userids and view their ratings we can see how sparsely populated the database is. Now we start to get an idea of the mountainous challenge we face in predicting the gaps.
# {r Sparsley }
OneHundredusers <- sample(unique(edx$userId), 100)
edx %>% filter(userId %in% OneHundredusers) %>%
select(userId, movieId, rating) %>%
mutate(rating = 1) %>%
spread(movieId, rating) %>% select(sample(ncol(.), 100)) %>%
as.matrix() %>% t(.) %>%
image(1:100, 1:100,. , xlab="Movies", ylab="Users") +
abline(h=0:100+0.5, v=0:100+0.5, col = "grey")
#
# We are attempting to predict the ratings for movies (i) based on the users (u) though they have rated different movies and have given different ratings.
### Method - Data exploration - Movies
# If we count the number of times each movie has been rated we can see that some are rated more than others.
# {r MoviesExp}
# Lets look at the distribution of the data. We can see that some movies are rated more than others.
edx %>%
dplyr::count(movieId) %>%
ggplot(aes(n)) +
geom_histogram(bins = 30, color = "black", fill = "gray") +
scale_x_log10() +
ggtitle("How Often Each Movie (n) is Rated")
#
### Method - Data exploration - Users
# Further to this we can see some users are more active than others when rating movies.
# {r UsersExp}
edx %>%
dplyr::count(userId) %>%
ggplot(aes(n)) +
geom_histogram(bins = 30, color = "black") +
scale_x_log10() +
ggtitle("How Often Users Rate Movies")
#
### Method - Data exploration - Genres
# The genres are collated as a string in each data row therefore currently the exploration of this data in this format is quite difficult. We will split these out for visual representation of the data though will not be doing so for the analysis.
#
# We can see from the data that there are a large number of genres. This is actually due to most films having more than 1 film genre, therefore we are seeing the 797 combinations of films in the database.
# {r GenreExp}
length(unique(edx$genres))
# Therefore we have to split the Genres (for which most films have more than 1) into separate lines in order to make any sense of the data.
genresep <- edx %>%
separate_rows(genres,sep = "\\|")
# The below summarises the actual number of genres in the data.
genresexp <- genresep %>%
group_by(genres) %>%
summarise(n = n()) %>%
arrange(desc(n))
knitr::kable(genresexp)
# The below shows us that there are actually 19 genres (and 7 instances of no genres).
length(unique(genresexp$genres))
# We can graph how popular each film genre is in each year with the below. This shows the number of ratings given to each genre based on the year each film was released. Note this doesnt show popularity but number of ratings.
GenreRatingsbyYear <- genresep %>%
na.omit() %>% # remove missing values
select(movieId, releaseyear, genres) %>% # select columns
mutate(genres = as.factor(genres)) %>% # genres in factors
group_by(releaseyear, genres) %>% # group by release year and genre
summarise(n = n()) # summarise by number of ratings
GenreRatingsbyYear %>%
filter(genres != "(no genres listed)") %>%
na.omit() %>%
ggplot(aes(x = releaseyear, y = n)) +
geom_line(aes(color=genres)) +
ggtitle("Number of Ratings for Genres by Release Year")
#
# We would utlise the data split into genres with the 19 different outcomes rather than the 797 different combinations but this unfortunately leads to each rating being duplicated by the number of genres for each film. This will massively skew the data and therefore is not useful.
### Method - Data exploration - Time
# We will now look at the effect of time on ratings.
# {r TimeExp}
# Weekday
edx %>%
ggplot(aes( x = Weekday , rating)) +
geom_violin()
#
# There does seem to be some variation here though it doesn't seem very over bearing.
# {r TimeExp2}
# Month
edx %>%
mutate(Year = year(Date) , Month = as.factor(month(Date))) %>%
ggplot(aes( x = Month , rating)) +
geom_violin()
#
# There seems to be even less variation when we look at ratings by months. There may still be a seasonal effect but we will continue to investigate.
# {r TimeExp3}
# Year
edx %>%
mutate(Year = as.factor(year(Date))) %>%
ggplot(aes( x = Year , rating)) +
geom_violin()
#
# It seems from this output that 0.5 ratings were only introduced from 2003. Therefore they could be some unintended bias here due to this but we will again continue to investigate the data.
# We will look at the time since release in the below code. In order to visualise this a little easier (due to overcrowding by number of years) we will group release years into every 5 years.
# {r TimeExp4}
# Time since release
# Code to round to every 5th year.
mround <- function(x,base){
base*round(x/base)
}
# Here we have rounded the release dates to every 5th year. This allows us to visualise the violin plots with more ease.
edx %>%
mutate(releaseyear5years = mround(releaseyear, 5)) %>%
ggplot(aes( x = as.factor(releaseyear5years) , rating)) +
geom_violin()
#
# We can definitely see a change over the years, though what is probably more useful to utilise as a bias is the length of time between the films release and each rating.
# {r TimeExp5}
# Time between release and rating.
edx %>%
ggplot(aes(ReleasetoRatingTime)) +
geom_bar() +
ggtitle("Time from release to rating (years)")
edx %>%
dplyr::count(ReleasetoRatingTime) %>%
ggplot(aes(n)) +
geom_histogram(bins = 30, color = "black") +
scale_x_log10() +
ggtitle("Time from release to rating")
#
# Results - Building the Recommendation System
## Model 1 - Just the average
# The estimate that reduces the residual mean squared error is the least squares estimate of mu. Here it would be the average of all ratings which we can calculate as below.
# {r Model1}
mu_hat <- mean(train_set$rating)
mu_hat
#
# We can calculate this on the training data to get the residual mean squared error ("RMSE") as below.
# {r Model1.2}
naive_rmse <- RMSE(test_set$rating, mu_hat)
naive_rmse
# Here we add the results to a table.
rmse_results <- tibble(method = "Model 1 - Just the average", RMSE = naive_rmse)
rmse_results
#
# This is quite large, though we will be improving this as we go on.
## Model 2 - Movie Effect Model
# We will firstly improve upon this model by accounting for our first bias, movie bias, which we will call b_i. Some movies we saw in the data exploration section are rated higher than others, we want to adjust our model for this.
# {r Model2Movie , message=FALSE}
mu <- mean(train_set$rating)
# Movie bias
movie_avgs <- train_set %>%
group_by(movieId) %>%
summarize(b_i = mean(rating - mu))
movie_avgs %>% qplot(b_i, geom ="histogram", bins = 10, data = ., color = I("black"))
#
# We can see from the above q plot that these vary somewhat. The average rating is 3.5 so a 1.5 score shows a perfect 5.0 rating.
#
# Now lets see if accounting for movie bias improves our model.
# {r Model2Movie.2}
predicted_ratings2 <- mu + test_set %>%
left_join(movie_avgs, by='movieId') %>%
.$b_i
model_2_rmse <- RMSE(predicted_ratings2, test_set$rating)
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 2 - Movie Effect Model",
RMSE = model_2_rmse ))
rmse_results %>% knitr::kable()
#
# We can see that this has improved, though we will now try to account for User, Genre and Time biases.
## Model 3 - Movie + User Effects Model
# Now we will add in a bias for user effects which we will call b_u. Again, as seen in the data exploration stage different users give different ratings and rate different numbers of movies. So we should be able to improve the model based on this.
#
# We will add this onto the model along with b_i.
# {r Model3MovieUserEffectsModel , message=FALSE}
#User bias
user_avgs <- test_set %>%
left_join(movie_avgs, by='movieId') %>%
group_by(userId) %>%
summarize(b_u = mean(rating - mu - b_i))
predicted_ratings3 <- test_set %>%
left_join(movie_avgs, by='movieId') %>%
left_join(user_avgs, by='userId') %>%
mutate(pred = mu + b_i + b_u) %>%
.$pred
model_3_rmse <- RMSE(predicted_ratings3, test_set$rating)
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 3 - Movie + User Effects Model",
RMSE = model_3_rmse ))
rmse_results %>% knitr::kable()
#
# We again have made an improvement, we have added this to the results table above.
## Model 4 - Movie + User + Genre Effects Model
# We will now build genre bias into the model which we will call b_g.
#
# The data will be left with the genres in their "non split out" format. Although we had split this to visualise the 19 different genres previously if we did this for the calculation it would create duplicate rating rows. We previously showed that different genres were rated differently in different release years.
# {r Model4MovieUserGenreEffectsModel , message=FALSE}
#Genre bias
genre_avgs <- test_set %>%
left_join(movie_avgs, by='movieId') %>%
left_join(user_avgs, by='userId') %>%
group_by(genres) %>%
summarize(b_g = mean(rating - mu - b_i - b_u))
predicted_ratings4 <- test_set %>%
left_join(movie_avgs, by='movieId') %>%
left_join(user_avgs, by='userId') %>%
left_join(genre_avgs, by='genres') %>%
mutate(pred = mu + b_i + b_u + b_g) %>%
.$pred
model_4_rmse <- RMSE(predicted_ratings4, test_set$rating)
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 4 - Movie + User + Genre Effects Model",
RMSE = model_4_rmse ))
rmse_results %>% knitr::kable()
#
# The model has again improved but not as much. We will now add a final bias before moving on to other methods.
## Model 5 - Movie + User + Genre + Time Effects Model
# We showed in the inspection stage that the release year seems to have an effect on ratings. We will create another bias b_t to be the number of years from release year to year of rating.
# {r Model5MovieUserGenreTimeEffectsModel , message=FALSE}
time_avgs <- test_set %>%
left_join(movie_avgs, by='movieId') %>%
left_join(user_avgs, by='userId') %>%
left_join(genre_avgs, by="genres") %>%
group_by(ReleasetoRatingTime) %>%
summarize(b_t = mean(rating - mu - b_i - b_u - b_g))
predicted_ratings5 <- test_set %>%
left_join(movie_avgs, by='movieId') %>%
left_join(user_avgs, by='userId') %>%
left_join(genre_avgs, by='genres') %>%
left_join(time_avgs, by='ReleasetoRatingTime') %>%
mutate(pred = mu + b_i + b_u + b_g + b_t) %>%
.$pred
model_5_rmse <- RMSE(predicted_ratings5, test_set$rating)
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 5 - Movie + User + Genre + Time Effects Model",
RMSE = model_5_rmse ))
rmse_results %>% knitr::kable()
#
#
# Our final 4th bias has barely made an improvement on the model. We shall now move onto the method of regularisation.
## Model 6 - Regularized Movie Effect Model
# The last two models didn't improve much, so we will now introduce regularisation which was one of the techniques used by the Netflix challenge winners.
# Below we summarise the 10 best and 10 worst films per the data. We can see that these are all pretty niche films. There is something awry here.
# {r Model6RegularizedMovieEffectModel}
# Create a list of movie titles
movie_titles <- edx %>%
select(movieId, title) %>%
distinct()
# Below are the top 10 best films according to our estimates.
movie_avgs %>% right_join(movie_titles, by="movieId") %>%
arrange(desc(b_i)) %>%
select(title, b_i) %>%
slice(1:10) %>%
knitr::kable()
# Below are the top 10 worst films according to our estimates.
movie_avgs %>% right_join(movie_titles, by="movieId") %>%
arrange(b_i) %>%
select(title, b_i) %>%
slice(1:10) %>%
knitr::kable()
## Lets see how often these top 10 good movies were rated.
train_set %>% dplyr::count(movieId) %>%
left_join(movie_avgs) %>%
right_join(movie_titles, by="movieId") %>%
arrange(desc(b_i)) %>%
select(title, b_i, n) %>%
slice(1:10) %>%
knitr::kable()
# We can see the same for the bad movies.
train_set %>% dplyr::count(movieId) %>%
left_join(movie_avgs) %>%
right_join(movie_titles, by="movieId") %>%
arrange(b_i) %>%
select(title, b_i, n) %>%
slice(1:10) %>%
knitr::kable()
#
# So it seems the top best and worst are skewed by niche films with a low number of ratings. We would define these as noisy estimates.
#
# With regularisation we want to add a penalty (lambda) for large values of b to the sum of squares equations that we minimize.
#
# The larger the lambda the more we shrink these values. Lambda is a tuning parameter, we will use cross-validation to pick the ideal value.
# {r Model6RegularizedMovieEffectModel.2, , message=FALSE}
##### Picking a Lambda and running regularisation for movie effect.
# Now note that lambda is a tuning parameter.
# We can use cross-validation to choose it.
lambdas <- seq(0, 10, 0.25) # Choose a range of lambas to test
mu <- mean(train_set$rating) # define mu
just_the_sum <- train_set %>%
group_by(movieId) %>%
summarize(s = sum(rating - mu), n_i = n())
rmses <- sapply(lambdas, function(l){
predicted_ratings <- test_set %>%
left_join(just_the_sum, by='movieId') %>%
mutate(b_i = s/(n_i+l)) %>%
mutate(pred = mu + b_i) %>%
.$pred
return(RMSE(predicted_ratings, test_set$rating))
})
#
# The below graph gives us a visualisation of why we pick the lamda we do (the lowest).
# {r Model6RegularizedMovieEffectModel.3}
qplot(lambdas, rmses)
# Below is the lambda selected
lambdas[which.min(rmses)]
lambda <- lambdas[which.min(rmses)] # make lambda the lowest value.
#
# We will run the model again but this time with the optimal lambda.
# {r Model6RegularizedMovieEffectModel.4 , message=FALSE}
movie_reg_avgs <- train_set %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+lambda), n_i = n())
#
# We can visualise how the estimates shrink by plotting the regularised estimates vs the least squares estimates with the size of the circles being how large n_i was.
# When n is small the values shink more towards zero.
# {r Model6RegularizedMovieEffectModel.5 , message=FALSE}
tibble(original = movie_avgs$b_i,
regularlized = movie_reg_avgs$b_i,
n = movie_reg_avgs$n_i) %>%
ggplot(aes(original, regularlized, size=sqrt(n))) +
geom_point(shape=1, alpha=0.5)
#
# So if we now look at the top 10 best/worst movies we can see what affect this has had. These now look a lot more reasonable!
# {r Model6RegularizedMovieEffectModel.6 , message=FALSE}
train_set %>%
dplyr::count(movieId) %>%
left_join(movie_reg_avgs) %>%
left_join(movie_titles, by="movieId") %>%
arrange(desc(b_i)) %>%
select(title, b_i, n) %>%
slice(1:10) %>%
knitr::kable()
train_set %>%
dplyr::count(movieId) %>%
left_join(movie_reg_avgs) %>%
left_join(movie_titles, by="movieId") %>%
arrange(b_i) %>%
select(title, b_i, n) %>%
slice(1:10) %>%
knitr::kable()
#
# Though do we improve our RMSE? Yes we do and can see this below. Please note that this is an improvement from Model 2, not Model 6.
# {r Model6RegularizedMovieEffectModel.7 , message=FALSE}
predicted_ratings6 <- test_set %>%
left_join(movie_reg_avgs, by='movieId') %>%
mutate(pred = mu + b_i) %>%
.$pred
model_6_rmse <- RMSE(predicted_ratings6, test_set$rating)
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 6 - Regularized Movie Effect Model",
RMSE = model_6_rmse ))
rmse_results %>% knitr::kable()
#
# Now lets do the same but add in b_u and then again with b_g.
## Model 7 - Regularized Movie + User Effect Model
# {r Model7RegularizedMovieUserEffectModel, message=FALSE}
##### Picking a Lambda and running regularisation for movie + user effect.
lambdas <- seq(0, 10, 0.25)
rmses <- sapply(lambdas, function(l){
mu <- mean(train_set$rating)
b_i <- train_set %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+l))
b_u <- train_set %>%
left_join(b_i, by="movieId") %>%
group_by(userId) %>%
summarize(b_u = sum(rating - b_i - mu)/(n()+l))
predicted_ratings <-
test_set %>%
left_join(b_i, by = "movieId") %>%
left_join(b_u, by = "userId") %>%
mutate(pred = mu + b_i + b_u) %>%
.$pred
return(RMSE(predicted_ratings, test_set$rating))
})
qplot(lambdas, rmses)
lambda <- lambdas[which.min(rmses)]
lambda
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 7 - Regularized Movie + User Effect Model",
RMSE = min(rmses)))
rmse_results %>% knitr::kable()
#
# It doesnt seem to have improved from Model 3. Perhaps b_u wasn't the best bias to add in? We can try with b_g but if it doesn't improve more we will move onto a different method.
## Model 8 - Regularized Movie + User + Genre Effect Model
# {r Model8RegularizedMovieUserGenreEffectModel , message=FALSE}
##### Picking a Lambda and running regularisation for movie + user + genre effect.
lambdas <- seq(0, 10, 0.25)
rmses <- sapply(lambdas, function(l){
mu <- mean(train_set$rating)
b_i <- train_set %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+l))
b_u <- train_set %>%
left_join(b_i, by="movieId") %>%
group_by(userId) %>%
summarize(b_u = sum(rating - b_i - mu)/(n()+l))
b_g <- train_set %>%
left_join(b_i, by='movieId') %>%
left_join(b_u, by='userId') %>%
group_by(genres) %>%
summarize(b_g = sum(rating - b_i - b_u - mu)/(n()+l))
predicted_ratings <-
test_set %>%
left_join(b_i, by = "movieId") %>%
left_join(b_u, by = "userId") %>%
left_join(b_g, by = "genres") %>%
mutate(pred = mu + b_i + b_u + b_g) %>%
.$pred
return(RMSE(predicted_ratings, test_set$rating))
})
qplot(lambdas, rmses)
lambda <- lambdas[which.min(rmses)]
lambda
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 8 - Regularized Movie + User + Genre Effect Model",
RMSE = min(rmses)))
rmse_results %>% knitr::kable()
#
# Again we didnt seem to add an improvement. Now we could likely improve this again if we optimised the lambda for each bias rather than using one for all.
# However, we shall instead try Matrix Factorisation instead.
## Model 9 - Matrix Factorisation
# We will be using the recosystem package for the matrix factorisation analysis.
#
# Using this package we will do the below steps.
#
# - Make our data into matrices to be used by the package
# - Create a model (calling the function reco() )
# - Tune the model to use the best parameters using tune()
# - Train the model
# - Calculate predicted values
# {r Model9MatrixFactorisation , message=FALSE}
# We firstly need to change our data into matrices to be used by the recosytem package.
train_set_MF <- train_set %>%
select(userId, movieId, rating) %>%
spread(movieId, rating) %>%
as.matrix()
test_set_MF <- test_set %>%
select(userId, movieId, rating) %>%
spread(movieId, rating) %>%
as.matrix()
train_set_MF <- with(train_set, data_memory(user_index = userId,
item_index = movieId,
rating = rating))
test_set_MF <- with(test_set, data_memory(user_index = userId,
item_index = movieId,
rating = rating))
# Now we create a model object by calling Reco()
r <- Reco()
# Now we tune our model to use the best parameters.
opts <- r$tune(train_set_MF, opts = list(dim = c(10, 20, 30), lrate = c(0.1, 0.2),
costp_l1 = 0, costq_l1 = 0,
nthread = 1, niter = 10))
# Train the model
r$train(train_set_MF, opts = c(opts$min, nthread = 4, niter = 20))
# Calculate the predicted values
y_hat_reco <- r$predict(test_set_MF, out_memory())
rmses <- RMSE(test_set$rating, y_hat_reco)
# Save the results
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 9 - Matrix Factorisation with Recosystem",
RMSE = min(rmses)))
rmse_results %>% knitr::kable()
#
# This has shown a massive improvement! Now we shall test it on the validation set to be sure we have created a real result.
## Present Modeling Results
# Now it seems that Models 3, 4, 5 and 9 all have given us a RMSE < 0.86490. However we will utilise Model 9, the best outcome to test against our validation set.
# {r TestingOnValidationSet , message=FALSE}
validation_set_MF <- validation %>%
select(userId, movieId, rating) %>%
spread(movieId, rating) %>%
as.matrix()
validation_set_MF <- with(validation, data_memory(user_index = userId,
item_index = movieId,
rating = rating))
# Calculate the predicted values
y_hat_reco <- r$predict(validation_set_MF, out_memory())
rmses <- RMSE(validation$rating, y_hat_reco)
# Save the results
rmse_results <- bind_rows(rmse_results,
tibble(method="Model 10 - Final Validation by Matrix Factorisation with Recosystem",
RMSE = min(rmses)))
rmse_results %>% knitr::kable()
#
## Discuss Model Performance
# Our final model had held true shown by our final value of RMSE < 0.86490.
#
# As we went through the various models it seems that movie and user biases had a significant effect on reducing our RMSE, regularisation did somewhat to improve it but the real game changer was matrix factorisation.
# Conclusion
## Summary
# We managed to gain a value of RMSE < 0.86490 at around 0.79 whilst showing significant improvement as we went on. Matrix factorisation was by far the best and (in terms of complexity of code) the simplest to run.
## Limitations/Future work
# When applying bias to genres it would have been great to have applied this to the 19 genres rather than the 797 combinations. If we would devise a way to analyse these without creating duplicate rows we may be able to improve the model further.
#
# The final model provides our best results but the real question is "Can this be applied in real time in the real world?" This final code took a few minutes to run and I doubt netflix users would consider waiting for this to run when looking for a film to watch. A way to improve would perhaps to be able to store results on a dataframe and update this each time new data is added.
|
11fdb07b906b08272d3de3264f3ee1aeb06f5200
|
58da677e82d96ec6ac400e3578f190718c9ad78a
|
/server.R
|
8d78e0e38c5030f800293eaeea909d7f58dc9226
|
[] |
no_license
|
zhangxudongsteven/DataProductAssignment
|
8025ebc462c002808643590eb59b880b271609e9
|
c8b729487c40237901b2b1533b100708dce8038f
|
refs/heads/master
| 2021-06-12T00:01:08.695721
| 2016-12-09T16:28:10
| 2016-12-09T16:28:33
| 76,049,843
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,729
|
r
|
server.R
|
# This is the server logic for a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
library(shiny)
shinyServer(function(input, output) {
library(dplyr)
library(zoo)
library(forecast)
df <- read.csv("hr.data.csv")
dpo <- tbl_df(df) %>%
group_by(year, quarter, department) %>%
summarise(
CapitaIncome = sum(CapitaIncome),
Profitability = sum(Profitability),
NetProfit = sum(NetProfit),
LaborCost = sum(LaborCost),
LaborCostProfitRatio = mean(LaborCostProfitRatio),
ReturnOnHumanCapital = mean(ReturnOnHumanCapital)
)
output$forecastPlot <- renderPlot({
dp <- dpo %>% filter(department == input$department)
finalColumn <- dp[,input$measure]
ts1 <- ts(finalColumn, frequency = 4, start = c(2008, 1))
ts1Train <- window(ts1, start = 2008, end = 2012)
ts1Test <- window(ts1, start = 2012, end = 2017)
ets1 <- ets(ts1Train, model = "MMM")
fcast <- forecast(ets1)
plot(fcast)
lines(ts1Test, col = "red")
})
output$decomposePlot <- renderPlot({
dp <- dpo %>% filter(department == input$department)
finalColumn <- dp[,input$measure]
ts1 <- ts(finalColumn, frequency = 4, start = c(2008, 1))
plot(decompose(ts1), xlab = "Year+1")
})
output$dataTable <- renderTable({
dpo %>%
filter(department == input$department) %>%
select(year, quarter, CapitaIncome, Profitability, NetProfit,
LaborCost, LaborCostProfitRatio, ReturnOnHumanCapital)
})
})
|
cb8892390fc579e3b9cce68486cd33ca75b29e6f
|
c7eb6366e11f8b80b1cbeb476d1cd2ff398de1c2
|
/pflamelet/man/permutation.test.Rd
|
33847d1837367bae08713d5c05930172355dac77
|
[] |
no_license
|
tulliapadellini/pflamelet
|
ad787218bb9b9d737da527a90012f0553cc92bed
|
debfc343ac40ce5777c0707e7dab11f8630c8837
|
refs/heads/master
| 2021-06-30T20:25:14.645653
| 2020-12-16T21:31:18
| 2020-12-16T21:31:18
| 205,159,987
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 3,477
|
rd
|
permutation.test.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/functions.R
\name{permutation.test}
\alias{permutation.test}
\title{Two-sample permutation test}
\usage{
permutation.test(sample1, sample2, n.rep = NULL, seed = NULL)
}
\arguments{
\item{sample1}{a k x m x n1 array corresponding to the Persistence Flamelet for the n1 subjects in sample 1}
\item{sample2}{a k x m x n2 array corresponding to the Persistence Flamelet for the n2 subjects in sample 2}
\item{n.rep}{an integer representing the number of bootstrap iterations. If \code{NULL} only the test statistics
on the observed samples is returned}
\item{seed}{an integer specifying a seed for the random shuffling}
}
\value{
a bootstrapped p-value
}
\description{
Performs a permutation test to assess whether two samples of Persistence Flamelets
are likely be random draw from the same distribution or if they come from different
generating mechanisms, with p-value computed by means of bootstrap.
}
\examples{
\donttest{
library(eegkit)
library(dplyr)
# import data from the eegkit package
data("eegdata") # electroencephalography data
data("eegcoord") # location of the electrodes
# add eeg channel name as variable and select only the 2d projection of the electrode location
eegcoord <- mutate(eegcoord, channel = rownames(eegcoord)) \%>\% select(channel, xproj, yproj)
# as EEG recordings are extremely unstable, they are typically averaged across repetitions
# here we average them across the 5 trials from each subject
eegmean <- eegdata \%>\% group_by(channel, time, subject) \%>\% summarise(mean = mean(voltage))
dim(eegmean) # 64 channels x 256 time points x 20 subjects
subjects <- unique(eegdata$subject)
# subjects 1:10 are alcoholic, 11:20 are control
# eegmean2 <- tapply(eegdata$voltage, list(eegdata$channel, eegdata$time, eegdata$subject), mean)
# Start by computing the list of Persistence Diagrams needed to build the flamelet for each subject
diag.list <- list()
t0 <- Sys.time()
for (sbj in subjects){
# select signal for one subject and then remove channels for which there are no coordinates
sbj.data = dplyr::filter(eegmean, subject == sbj, !(channel \%in\% c("X", "Y", "nd") ))
# add 2d projection of electrodes location
sbj.data = left_join(sbj.data, eegcoord, by = "channel")
# scale data
sbj.data[, c(4:6)] = scale(sbj.data[,c(4:6)])
# dsucc.List = list()
diag.list.sbj = lapply(unique(sbj.data$time), function(time.idx){
time.idx.data = filter(sbj.data, time == time.idx) \%>\% ungroup \%>\%
select(mean, xproj, yproj)
time.idx.diag = ripsDiag(time.idx.data, maxdimension = 1, maxscale = 5,
library = "GUDHI", printProgress = F)
return(time.idx.diag$diagram)
})
diag.list[[which(sbj== subjects)]] = diag.list.sbj
print(paste("subject ", which(sbj == subjects), " of 20"))
}
t1 <- Sys.time()-t0
t1 # will take less than 5 minutes
tseq <- seq(0, 5, length = 500) # consider 5 as it is the
# same value as maxscale (hence largest possible persistence)
p_silh0 <- sapply(diag.list, FUN = build.flamelet,
base.type = "silhouette", dimension = 0,
tseq = tseq, precomputed.diagram = TRUE, simplify = 'array')
prova = permutation_test(p_sih0[,,1:10], p_silh0[,,11:20], n.rep = 10, seed = 1)
}
}
\references{
T. Padellini and P. Brutti (2017) Persistence Flamelets: multiscale Persistent Homology for kernel density exploration \url{https://arxiv.org/abs/1709.07097}
}
|
9bac3af815b8101913e0ae3409e7635e3f56fb58
|
c573e2ac247817ee7c8ef35a26ba3197df424fd5
|
/code/BCX_miscellaneous/clinvar_annotation.R
|
55facf965755080e42731ad98521afc6cd27206c
|
[] |
no_license
|
epiheather/manuscript_code
|
6188b8200caeaca32e5af1cc3ff1ddabf5815a5f
|
e9ce4a3bfa566b4f0bb132106283b1c693a1482d
|
refs/heads/master
| 2022-11-09T03:35:49.164706
| 2020-06-30T14:29:27
| 2020-06-30T14:29:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,019
|
r
|
clinvar_annotation.R
|
###########################################
### CLINVAR annotation for GWAS results ###
###########################################
# overlap our findings with ClinVar db to see which pathogenic variants we detect
# and if we can re-assign pathogenicity based on effect sizes distribution.
setwd("/Users/dv3/Desktop/finemapping_ukbb500k_final_release/Results_final_fine_mapping/")
res=read.table("FM_vars_PP_gt_0.95.txt", he=T, strings=F)
#res=read.table("FM_vars_PP_gt_0.50.txt", he=T, strings=F)
head(res)
dim(res)
# read and format clinvar downloaded dataset
clinvar=read.csv("../../Clinvar_variant_summary_051118.txt", he=T, strings=F, sep="\t", encoding="UTF-8", fill=T, comment.char = "")
head(clinvar)
clinvar=clinvar[which(clinvar$Assembly=="GRCh37"),]
dim(clinvar) # 459080
clinvar$STAR=NA
clinvar$STAR[which(clinvar$ReviewStatus=="practice guideline")]=4
clinvar$STAR[which(clinvar$ReviewStatus=="reviewed by expert panel")]=3
clinvar$STAR[which(clinvar$ReviewStatus=="criteria provided, multiple submitters, no conflicts")]=2
clinvar$STAR[which(clinvar$ReviewStatus=="criteria provided, conflicting interpretations")]=1
clinvar$STAR[which(clinvar$ReviewStatus=="criteria provided, single submitter")]=1
clinvar$STAR[which(is.na(clinvar$STAR))]=0
table(clinvar$ClinSigSimple,clinvar$STAR)
clinvar$VAR=paste(clinvar$Chromosome,clinvar$Start,sep=":")
clinvar$VAR=paste(clinvar$VAR, clinvar$ReferenceAllele, clinvar$AlternateAllele, sep="_")
dim(clinvar)
clinv=clinvar[,c("ClinSigSimple","PhenotypeList","OriginSimple","VAR","STAR","ReviewStatus")]
dim(clinv)
head(clinv)
table(clinv$STAR)
tail(clinv)
length(unique(clinv$VAR))
clinv[which(duplicated(clinv$VAR)),]
# merge with results file
head(res)
res$VAR=paste(res$chromosome,res$position,sep=":")
res$VAR=paste(res$VAR, res$allele1, res$allele2, sep="_")
fin=merge(res, clinv, by="VAR", all.x=T)
dim(fin)
head(fin)
length(unique(fin$VAR))
table(fin$ClinSigSimple, fin$STAR)
# plot effect sizes by clinvar STAR rating
library(ggplot2)
tmp=fin[which(fin$ClinSigSimple %in% c(0,1)),]
ggplot(data=tmp, aes(x=factor(STAR), y=abs(beta)))+
geom_violin()+geom_boxplot(width = 0.2,aes(fill = "grey"))+scale_y_continuous(trans='log10')+
theme(axis.text=element_text(size=14),axis.title.x=element_blank())+theme(legend.position="none")+facet_wrap(~ClinSigSimple)
### annotate 95% credible sets
setwd("/Users/dv3/Desktop/finamapping_ukbb500k_final_release/Results_final_fine_mapping")
res=read.table("Credible_sets/All_traits.95credSet_summStat", he=F, strings=F)
hedd=scan("Credible_sets/header_snp_files.txt", "char")
head(res)
dim(res)
hedd=c("Trait", hedd)
names(res)=hedd
res$VAR=paste(res$chromosome,res$position,sep=":")
res$VAR=paste(res$VAR, res$allele1, res$allele2, sep="_")
length(unique(res$VAR))
fin=merge(res, clinv, by="VAR", all.x=T)
dim(fin)
head(fin)
length(unique(fin$VAR))
table(fin$ClinSigSimple, fin$STAR)
write.table(fin, "Credible_sets/All_traits.95credSet_summStat_clinvar_annotated.txt", row.names=F, quote=F, sep="\t")
|
f60a37a00f39f777ce674dad56064468e7345df3
|
dcab57188f2a7b82af1d865824b205b380d45cc8
|
/cytof/src/model3/cytof3/man/yZ_inspect.Rd
|
bed5a78aed825f77659f7e619a7456d455e353ed
|
[] |
no_license
|
luiarthur/ucsc_litreview
|
5e718a951ce86a6a620d497d7d797f1c52da6aa3
|
791a2841fc285fcdaa1fac4be5590817e08ba04f
|
refs/heads/master
| 2021-05-02T16:49:14.082267
| 2020-05-11T17:35:14
| 2020-05-11T17:35:14
| 72,487,240
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 693
|
rd
|
yZ_inspect.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/yZ_inspect.R
\name{yZ_inspect}
\alias{yZ_inspect}
\title{Plot y and Z together}
\usage{
yZ_inspect(out, y, zlim, i, thresh = 0.7, col = list(blueToRed(7),
greys(10))[[1]], prop_lower_panel = 0.3, is.postpred = FALSE,
decimals_W = 1, na.color = "transparent", fy = function(lami) {
abline(h = cumsum(table(lami)) + 0.5, lwd = 3, col = "yellow", lty = 1)
}, fZ = function(Z) abline(v = 1:NCOL(Z) + 0.5, h = 1:NROW(Z) + 0.5,
col = "grey"), ...)
}
\arguments{
\item{fy}{function to execute after making y image}
\item{fZ}{function to execute after making Z image}
}
\description{
Plot y and Z together
}
|
12a761ed1c02e3f09a3dbdb9d475e9bb7c7bb7a9
|
c786b84eaa1c289d2680d4d786d5916aa53522c6
|
/combining_mixtures/R/Wholesale_customers.R
|
789b02edb2974073463acd72301d3becab8b3251
|
[] |
no_license
|
mcomas/mixtures
|
99a60ed6a320c2afb82b5ac60ebc78cc9dad7b84
|
dd59832a744c6c6a56311ab7bed3c14690435d83
|
refs/heads/master
| 2021-01-10T21:26:46.280660
| 2015-07-20T18:27:30
| 2015-07-20T18:27:30
| 21,209,290
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 250
|
r
|
Wholesale_customers.R
|
data <- read.csv("~/Research/mixtures/combining_mixtures/data/Wholesale_customers_data.csv")
devtools::load_all('../../packages/mixpack')
X = data[,3:8]
ggbiplot(clr_coordinates(X), obs.col = factor(data$Channel), transparency = 1, size = 2)
|
af0290a44fac7d0bfabf09882f3af10fc5168c9c
|
d45af762e445c3ed93a96f2c52e5750114e72446
|
/Lecture2.r
|
f4bf97c552d6a8816db2adb0e6491810c05aa0fa
|
[] |
no_license
|
doublezz10/relearning_stats
|
fb6c7dbbf53d0bc71d5bcfef75bacd983e9d4f12
|
21b8ef76b97af5c2d039161647c4e25f1eafaf58
|
refs/heads/master
| 2023-01-07T05:17:21.209504
| 2020-11-09T22:05:07
| 2020-11-09T22:05:07
| 295,513,870
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,580
|
r
|
Lecture2.r
|
data(Howell1,package='rethinking')
library(brms)
# Fit a Bayesian model without setting priors (it'll do the median for us)
fit <- brm(height ~ 1, data=Howell1, family="normal")
summary(fit)
prior_summary(fit)
# Fit another model by setting priors
fit2 <- brm(height ~ 1, data=Howell1, family="normal",
prior = c(prior(normal(160,20),class="Intercept"),
prior(normal(0,30),class="sigma")
))
summary(fit2)
# Use a bad prior!
fit3 <- brm(height ~ 1, data=Howell1, family="normal",
prior = c(prior(normal(3600,10),class="Intercept"),
prior(normal(0,10),class="sigma")
))
summary(fit3)
# Plot the bad prior and the posterior
plot(seq(0, 300, length.out=1000),
dnorm(seq(0, 300, length.out=1000), mean=0, sd=10),
add = TRUE, type='l', xlim=c(0, 900))
hist(extract_draws(fit3)$dpars$sigma, breaks=50,prob=TRUE,add=TRUE)
# What should this look like?
plot(seq(0, 300, length.out=1000),
dnorm(seq(0, 300, length.out=1000), mean=0, sd=30),
add = TRUE, type='l', xlim=c(0, 90))
hist(extract_draws(fit2)$dpars$sigma, breaks=50,prob=TRUE,add=TRUE)
# Add a covariate (and its prior)
fit4 <- brm(height ~ weight, data=Howell1, family="normal",
prior = c(prior(normal(160,20),class="Intercept"),
prior(normal(0,30),class="sigma"),
#prior(normal(0,30),coef="weight"), #prior only on weight
prior(normal(0,20),class="b") #prior on all regression weights
))
summary(fit4)
|
7a161d3a8f7f139c807ee394c912ac916303e87f
|
5bd4b82811be11bcf9dd855e871ce8a77af7442f
|
/kinship/R/solve.bdsmatrix.R
|
88627aeeda3f99cd23934d509da5f2c33473aab3
|
[] |
no_license
|
jinghuazhao/R
|
a1de5df9edd46e53b9dc90090dec0bd06ee10c52
|
8269532031fd57097674a9539493d418a342907c
|
refs/heads/master
| 2023-08-27T07:14:59.397913
| 2023-08-21T16:35:51
| 2023-08-21T16:35:51
| 61,349,892
| 10
| 8
| null | 2022-11-24T11:25:51
| 2016-06-17T06:11:36
|
R
|
UTF-8
|
R
| false
| false
| 4,082
|
r
|
solve.bdsmatrix.R
|
# $Id: solve.bdsmatrix.s,v 1.6 2002/12/26 22:54:55 Therneau Exp $
# Cholesky decompostion and solution
solve.bdsmatrix<- function(a, b, tolerance=1e-10, full=T, ...) {
if (class(a) != 'bdsmatrix')
stop("First argument must be a bdsmatrix")
if (a@offdiag !=0) solve(as.matrix(a), b, tolerance=tolerance)
nblock <- length(a@blocksize)
adim <- dim(a)
if (missing(b)) {
# The inverse of the Cholesky is sparse, but if rmat is not 0
# the inverse of the martrix as a whole is not
# For df computations in a Cox model, however, it turns out that
# I only need the diagonal of the matrix anyway.
if (length(a@rmat)==0 || full==F) {
# The C-code will do the inverse for us
temp <- .C("gchol_bdsinv", as.integer(nblock),
as.integer(a@blocksize),
as.integer(a@.Dim),
dmat= as.double(a@blocks),
rmat= as.double(a@rmat),
flag= as.double(tolerance),
as.integer(0),
copy=c(F,F,T,T,T,F), PACKAGE="kinship")
if (length(a@rmat) >0) {
new("bdsmatrix", blocksize=as.integer(a@blocksize),
blocks = temp$dmat, offdiag=0,
rmat = matrix(temp$rmat, nrow=nrow(a@rmat)),
.Dim=as.integer(a@.Dim), .Dimnames= a@.Dimnames)
}
else {
new("bdsmatrix", blocksize=as.integer(a@blocksize),
blocks = temp$dmat, offdiag=0,
.Dim=as.integer(a@.Dim), .Dimnames= a@.Dimnames)
}
}
else {
# Get back the inverse of the cholesky from the C code
# and then multiply out the results ourselves (the C
# program doesn't have the memory space assigned to
# write out a full matrix). The odds of a "not enough
# memory" message are high, if a is large.
temp <- .C("gchol_bdsinv", as.integer(nblock),
as.integer(a@blocksize),
as.integer(a@.Dim),
dmat= as.double(a@blocks),
rmat= as.double(a@rmat),
flag= as.double(tolerance),
as.integer(2),
copy=c(F,F,T,T,T,F), PACKAGE="kinship")
inv <- new('gchol.bdsmatrix', blocksize=as.integer(a@blocksize),
blocks=temp$dmat,
rmat=matrix(temp$rmat, ncol=ncol(a@rmat)),
.Dim=as.integer(a@.Dim),
rank=as.integer(temp$flag),
.Dimnames=a@.Dimnames)
dd <- diag(inv)
rtemp <- as.matrix(inv) #This may well complain about "too big"
t(rtemp) %*% (dd* rtemp)
}
}
else {
#
# If the rhs is a vector, save a little time by doing the decomp
# and the backsolve in a single .C call
#
if (length(b) == adim[1]) {
.C("gchol_bdssolve",as.integer(nblock),
as.integer(a@blocksize),
as.integer(a@.Dim),
block = as.double(a@blocks),
rmat= as.double(a@rmat),
as.double(tolerance),
beta= as.double(b),
flag=as.integer(0),
copy=c(F,F,F,T,T,F,T,F), PACKAGE="kinship")$beta
}
else {
# The rhs is a matrix.
# In this case, it's faster to do the decomp once, and then
# solve against it multiple times.
#
if (!is.matrix(b) || nrow(b) != adim[1])
stop("number or rows of b must equal number of columns of a")
else solve(gchol(a, tolerance=tolerance), b)
}
}
}
|
60c30d730b5af291003e8fce2a7684fbcf19f699
|
002929791137054e4f3557cd1411a65ef7cad74b
|
/man/checkChangedColsLst.Rd
|
484f2d1cb929beb7126bcba0383a5d93bf675f69
|
[
"MIT"
] |
permissive
|
jhagberg/nprcgenekeepr
|
42b453e3d7b25607b5f39fe70cd2f47bda1e4b82
|
41a57f65f7084eccd8f73be75da431f094688c7b
|
refs/heads/master
| 2023-03-04T07:57:40.896714
| 2023-02-27T09:43:07
| 2023-02-27T09:43:07
| 301,739,629
| 0
| 0
|
NOASSERTION
| 2023-02-27T09:43:08
| 2020-10-06T13:40:28
| null |
UTF-8
|
R
| false
| true
| 1,395
|
rd
|
checkChangedColsLst.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/checkChangedColsLst.R
\name{checkChangedColsLst}
\alias{checkChangedColsLst}
\title{checkChangedColsLst examines list for non-empty fields}
\usage{
checkChangedColsLst(changedCols)
}
\arguments{
\item{changedCols}{list with fields for each type of column change
\code{qcStudbook}.}
}
\value{
Returns \code{NULL} if all fields are empty
else the entire list is returned.
}
\description{
checkChangedColsLst examines list for non-empty fields
}
\examples{
\donttest{
library(nprcgenekeepr)
library(lubridate)
pedOne <- data.frame(ego_id = c("s1", "d1", "s2", "d2", "o1", "o2", "o3",
"o4"),
`si re` = c(NA, NA, NA, NA, "s1", "s1", "s2", "s2"),
dam_id = c(NA, NA, NA, NA, "d1", "d2", "d2", "d2"),
sex = c("F", "M", "M", "F", "F", "F", "F", "M"),
birth_date = mdy(
paste0(sample(1:12, 8, replace = TRUE), "-",
sample(1:28, 8, replace = TRUE), "-",
sample(seq(0, 15, by = 3), 8, replace = TRUE) +
2000)),
stringsAsFactors = FALSE, check.names = FALSE)
errorLst <- qcStudbook(pedOne, reportErrors = TRUE, reportChanges = TRUE)
checkChangedColsLst(errorLst$changedCols)
}
}
|
5b6710f87a94ce325bbaa3f0a5e8ec606b11def6
|
1cc35a9425e25715e2f4dacc36efa31385925e1c
|
/rDataVis.R
|
ca51f403c14f30011b1d669fdd2e5c463180f34d
|
[] |
no_license
|
freewillx/msba-datavis
|
6c0f32db3872b4da8f87de80626453b64ea78f8f
|
74c28d78f5e7949cf4c608d6d4c622d3405588f9
|
refs/heads/master
| 2021-01-24T11:00:25.817493
| 2016-10-10T03:22:50
| 2016-10-10T03:22:50
| 70,284,794
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,431
|
r
|
rDataVis.R
|
library(ggplot2)
library(ggthemes)
library(lattice)
## Exercise E
# China Internet Usage - source: world bank 2012
chinainternet <- read.csv("./data/chinainternet.csv")
summary(chinainternet)
ggplot(data=chinainternet, aes(x=Year, y=Internet.Usage)) +
geom_line(size=3) +
ggtitle("Internet Usage in China: 1990 to 2011") +
labs(x="",y="Usage") +
theme(panel.grid = element_blank(),
panel.background=element_blank())
# China Export
chinaexports <- read.csv("./data/chinaexports.csv")
names(chinaexports) <- c("2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011")
summary(t(chinaexports))
# Wait for ggplot
Sys.sleep(0.5)
barplot(as.matrix(chinaexports), border = NA, space = 0.25, ylim = c(0,40),
ylab = "% of GDP",
main = "Exports of Goods and Services in China as % of GDP: 2000 to 2011")
# Exercise F - 20 world exporters
worldexports <- read.csv("./data/worldexports_transform.csv")
summary(worldexports)
# Remove outliers
worldexports.plot <- worldexports[worldexports$volume > 0,]
summary(worldexports.plot)
worldexports.plot$year <- as.character(worldexports.plot$year)
h <- histogram(~ volume | year, data = worldexports.plot, layout=c(4,4),
scales=list(
y=list(at=seq(20,60,20),labels=seq(20,60,20)),
x=list(at=seq(0,120,40),labels=seq(0,120,40))
))
update(h, index.cond=list(c(1,14:16,5:2,9:6,13:10)))
|
ef75571010bc44c123558638c0fb85b108f4369b
|
39ed3b2824bef64238359d514f380be813dff1b9
|
/tests/testthat.R
|
16516e4b134aa80995dc8d0241765b346474d8d3
|
[] |
no_license
|
sathie/z11
|
cb202a965b6a352c988f108e52e75a7b2928d015
|
80bf2820b767b2a711cb3f0aa5de2a223fa1f517
|
refs/heads/main
| 2023-09-01T04:52:00.809531
| 2021-11-10T01:05:44
| 2021-11-10T01:05:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 50
|
r
|
testthat.R
|
library(testthat)
library(z11)
test_check("z11")
|
d1b2a2e7be9ef81199802925a1de57f645b467f2
|
a9c8054f50f0eaf7dd8c4f1a0a2c041753158d2a
|
/daniel/switch_paper_plotting_in_R/qPCR/Delta_CT_qPCR plotting.R
|
dd734388d368d2556d9f37cc8a848e904614aa0e
|
[] |
no_license
|
YH-Cali/scripts
|
91469c2161b46decb0ef184c3ef59f02bed840b4
|
b306ebe59c509f0af8286f379ce838570fce96a1
|
refs/heads/master
| 2022-10-15T10:34:45.840733
| 2020-06-11T01:29:38
| 2020-06-11T01:29:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,560
|
r
|
Delta_CT_qPCR plotting.R
|
##don't forget the library dependencies
require(dplyr)
require(ggplot2)
#For these files, I used a separate text file to manually seek and replace gene names and time points in order to generate all 28 or so plots. Then I faceted them in Illustrator.
png("/home/daniel/Sync/Google Drive/Niyogi Lab/Zofingiensis/Switch Paper/qPCR/qPCR rPlots/gene.png", height = 600, width = 600)
qpcr <- read.csv("/home/daniel/Sync/Google Drive/Niyogi Lab/Zofingiensis/Switch Paper/qPCR/qPCR_Data_all2.csv", header=TRUE,as.is=TRUE) %>% tbl_df
qpcr <- qpcr %>% group_by(strain, bio_reps, treatment, timepoint, rxn, target) %>% mutate(mean_ct = mean(ct)) %>% ungroup
qpcr_apps <- qpcr %>% filter(target == "APPS") %>% group_by(strain, bio_reps, tech_reps, treatment, timepoint, rxn) %>% summarize(apps_ct = mean(mean_ct))
qpcr2 <- left_join(qpcr, qpcr_apps, by=c("strain", "bio_reps", "tech_reps", "treatment", "timepoint", "rxn")) %>% filter(target != "APPS")
qpcr3 <- qpcr2 %>% mutate(delta_ct = mean_ct - apps_ct)
tmp <- qpcr3 %>% distinct(strain, treatment, target, timepoint, bio_reps, delta_ct)
p1 <- tmp %>% filter(target == "HXK1", timepoint == 0.5) %>% ggplot(aes( x= interaction(treatment,strain),y=delta_ct)) +
geom_jitter(width=0.001, alpha=1, color = "blue") +
geom_boxplot(alpha = 0.1)+
ggtitle(expression(paste(italic("HXK1")," 0.5h"))) +
xlab("") +
ylab("Delta CT") +
theme(plot.title = element_text(color = "black", size = 14, face = "bold", hjust = 0.5))+theme_bw(base_size = 20) + ylim(-13,13)
p1
dev.off()
#ggsave(p1, filename="HXK_12h")
|
b5f38426115c29598ea1cd0377a92461a8dbe814
|
f1556a59213e9dafb25db0d01760a1443c55b6b2
|
/models/Ensemble/Stacking/tag_points/functions_Stacking_tag_points.R
|
c29cf2cbac2372c107e94f5f6dadf28c1bd21719
|
[] |
no_license
|
you1025/probspace_youtube_view_count
|
0e53b0e6931a97b39f04d50a989a1c59522d56a7
|
f53d3acd6c4e5e6537f8236ad545d251278decaa
|
refs/heads/master
| 2022-11-13T13:22:51.736741
| 2020-07-12T04:14:35
| 2020-07-12T04:14:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,436
|
r
|
functions_Stacking_tag_points.R
|
source("models/functions_Global.R", encoding = "utf-8")
load_tag_dict <- function(train_data, test_data) {
# 辞書のパス
filepath <- "models/Ensemble/Stacking/tag_points/dictdata/tagdict.csv"
if(file.exists(filepath)) {
# 辞書の読み込み
readr::read_csv(
filepath,
col_types = cols(
tag = col_character(),
count = col_integer()
)
) %>%
# ベクトルに変換
tibble::deframe()
} else {
# 辞書の生成&保存
c(
train_data$tags,
test_data$tags
) %>%
# "|" で分割
stringr::str_split(pattern = "\\|") %>%
base::unlist(use.names = F) %>%
# カウントして tibble に変換
table() %>%
tibble::enframe(name = "tag", value = "count") %>%
dplyr::arrange(desc(count)) %>%
# ファイル書き込み
readr::write_csv(path = filepath, append = F, col_names = T)
}
}
make_tag_points <- function(data, tag_dict) {
# タグポイントの算出
v.tag_points <- data$tags %>%
purrr::map_int(function(tags) {
# タグを分割
stringr::str_split(tags, pattern = "\\|")[[1]] %>%
# カウントを集計
purrr::map_int(~ tag_dict[.x]) %>%
sum()
})
data %>%
# タグポイント項目の追加
dplyr::mutate(tag_point = ifelse(is.na(v.tag_points), 0, v.tag_points)) %>%
dplyr::select(
id,
tag_point
)
}
save_tag_points <- function(train_data, test_data) {
# 対象時刻
yyyymmddThhmmss <- lubridate::now(tz = "Asia/Tokyo") %>% format("%Y%m%dT%H%M%S")
# 格納先ディレクトリ
dirpath <- stringr::str_c(
"models/Ensemble/Stacking/tag_points/output",
yyyymmddThhmmss,
sep = "/"
)
dir.create(dirpath)
# 訓練データの書き出し
write_file(train_data, dirpath, yyyymmddThhmmss, stringr::str_c("tag_points", "train", sep = "_"))
# テストデータの書き出し
write_file(test_data, dirpath, yyyymmddThhmmss, stringr::str_c("tag_points", "test", sep = "_"))
}
write_file <- function(data, dirpath, yyyymmddThhmmss, file_prefix) {
# 出力ファイル名
filename <- stringr::str_c(
file_prefix,
yyyymmddThhmmss,
sep = "_"
) %>%
stringr::str_c("csv", sep = ".")
# 出力ファイルパス
filepath <- stringr::str_c(dirpath, filename, sep = "/")
# 書き出し
readr::write_csv(data, filepath, col_names = T)
}
|
2f458353bd73a8da706322304c01c29a59f139b9
|
329fbe8bdd0f52b7f1d02df40cdad09c865b0485
|
/plot4.R
|
18f58a19b86dfbe95f433d74a399ab7e9c571bdb
|
[] |
no_license
|
svijetaj/ExData_Plotting1
|
ced3390fa1d25f8e441b0936c7d1d0a24c7a7634
|
43fc036013c5d000df89590e427524e2c6562282
|
refs/heads/master
| 2021-05-01T20:24:16.357227
| 2017-01-17T07:03:36
| 2017-01-17T07:03:36
| 79,188,931
| 0
| 0
| null | 2017-01-17T04:39:05
| 2017-01-17T04:39:05
| null |
UTF-8
|
R
| false
| false
| 1,542
|
r
|
plot4.R
|
#read data into variable
hhpc <- read.table(hhpc_file, header = TRUE, sep = ";", stringsAsFactors = FALSE, dec = ".")
#subset data for the range
sub_hhpc <- hhpc[hhpc$Date %in% c("1/2/2007","2/2/2007"),]
#histogram for global active power
#convert the global active power to numeric data
global_active_power <- as.numeric(sub_hhpc$Global_active_power)
grp <- as.numeric(sub_hhpc$Global_reactive_power)
#merge date and time as single column
datetime <- strptime(paste(sub_hhpc$Date, sub_hhpc$Time, sep = " "), "%d/%m/%Y %H:%M:%S")
#submetering 1 2 3 make them as numeric columns
sm1 <- as.numeric(sub_hhpc$Sub_metering_1)
sm2 <- as.numeric(sub_hhpc$Sub_metering_2)
sm3 <- as.numeric(sub_hhpc$Sub_metering_3)
#make voltage as numerice column
volt <- as.numeric(sub_hhpc$Voltage)
#plot a graph on to png file
png("plot4.png")
#make a plot of two rows and two columns fill row wise
par(mfrow=c(2,2))
#plot all the graphs one by one
plot(datetime, global_active_power, type="l", xlab="", ylab="Global Active Power", cex=0.2)
plot(datetime, volt, type="l", xlab="datetime", ylab="Voltage")
plot(datetime, sm1, type="l", ylab="Energy Submetering", xlab="")
lines(datetime, sm2, type="l", col="red")
lines(datetime, sm3, type="l", col="blue")
legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=, lwd=2.5, col=c("black", "red", "blue"), bty="o")
plot(datetime, grp, type="l", xlab="datetime", ylab="Global_reactive_power")
dev.off()
|
085134271ac3d8db97a10d99e54423e3afb63aaa
|
1edd2d4fcbe8756ef5c43bb5af1281c1e2384b50
|
/R/liguria.r
|
0999f44b01f3a1f6356538372429ee95630619c2
|
[
"MIT"
] |
permissive
|
guidofioravanti/regioniItalia
|
c232ce6dae60884f960cd90e1499141fbf90a0ae
|
5607ce1334f1dffa4e30e3ee9721dbde01d86477
|
refs/heads/main
| 2023-05-06T07:37:27.133169
| 2021-05-28T12:00:02
| 2021-05-28T12:00:02
| 337,431,937
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 48
|
r
|
liguria.r
|
#' Oggetto sf della regione liguria
#'
"liguria"
|
ec99479653b61c1921896ce927be7b7b6299f07a
|
92951f9fef15b6c664bbf7a57ac7833a1f55a052
|
/R/gimage.R
|
89f2bfa72434f95c061d3d303eb18450b66eb1b1
|
[] |
no_license
|
jverzani/gWidgetsWWW2
|
ac2727344c0aba50cc082e92617b874b6d0e8c2b
|
37ca4b89419ced286627ccec1a8df26fface702c
|
refs/heads/master
| 2021-01-01T18:48:10.743913
| 2020-02-06T16:46:51
| 2020-02-06T16:46:51
| 3,021,944
| 2
| 1
| null | 2014-10-16T11:36:16
| 2011-12-20T19:32:24
|
JavaScript
|
UTF-8
|
R
| false
| false
| 3,952
|
r
|
gimage.R
|
## Copyright (C) 2011 John Verzani
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##' @include gwidget.R
NULL
##' Container for an image
##'
##' The image shows a url. This url can be external. For local urls,
##' the file must be accessible by the server. The function
##' \code{get_tempfile} can be used to create a file that is so
##' accessible. See the example.
##' @param filename A url or file from \code{get_tempfile}.
##' @param dirname ignored.
##' @param size A vector passed to \code{width} and \code{height} arguments.
##' Can also be set by the \code{size<-} method later.
##' @inheritParams gwidget
##' @return an GImage reference object
##' @export
##' @examples
##' w <- gwindow("hello")
##' sb <- gstatusbar("Powered by gWidgetsWWW and Rook", cont=w)
##' g <- ggroup(cont=w, horizontal=FALSE)
##'
##' f <- get_tempfile(ext=".png")
##' png(f)
##' hist(rnorm(100))
##' dev.off()
##'
##' i <- gimage(f, container=g, size = c(400, 400))
##' b <- gbutton("click", cont=g, handler=function(h,...) {
##' f <- get_tempfile(ext=".png")
##' png(f)
##' hist(rnorm(100))
##' dev.off()
##' svalue(i) <- f
##' })
##' @note requires tempdir to be mapped to a specific url, as this is
##' assumed by \code{get_tempfile} and \code{get_tempfile_url}
gimage <- function(filename = "", dirname = "", size = NULL,
handler = NULL, action = NULL, container = NULL,...,
width=NULL, height=NULL, ext.args=NULL
) {
i <- GImage$new(container, ...)
i$init(filename, container, ...,
width=width, height=height, ext.args=ext.args)
if(!is.null(size))
size(i) <- size
i
}
GImage <- setRefClass("GImage",
contains="GHtml",
fields=list(
filename="ANY"
),
method=list(
init=function(filename, container, ...,
width=NULL, height=NULL, ext.args=NULL) {
filename <<- filename
callSuper(img_wrap(filename), container, ...,
width=width, height=height, ext.args=ext.args)
},
img_wrap =function(x, alt="") {
"wrap image file into HTML call"
if(missing(x)) {
value <<- ""
} else if(is(x, "StaticTempFile")) {
value <<- get_tempfile_url(x)
} else {
value <<- x # assume a url
}
sprintf("<img src=\"%s\" alt=\"%s\" />", value, alt)
},
set_value = function(f, alt="", ...) {
filename <<- filename
x <- img_wrap(f, alt=alt)
callSuper(x)
},
get_value = function(...) {
filename
},
get_index=function(...) {
get_value()
}
))
|
25fc93c8c70a4deb24da7c0de30c7c52025e1e79
|
6f1be98f6fd2b7e860882a4c51737048d606c190
|
/server.r
|
eb706f1a8c5a8f64d5b159e6ae6cb5b9522f6241
|
[] |
no_license
|
donalgorman/hello-world
|
031cb3225f9d6abcdfcaeb47d1129d4ae3e71cd5
|
7540d716d5aac2f202d8919ed67e520d2e7e0c65
|
refs/heads/master
| 2021-01-09T20:27:11.758787
| 2019-03-05T19:25:07
| 2019-03-05T19:25:07
| 65,292,779
| 0
| 0
| null | 2016-08-09T12:28:03
| 2016-08-09T12:22:07
| null |
UTF-8
|
R
| false
| false
| 109,964
|
r
|
server.r
|
################################################
# #
# Operating Characteristic Curve Generator #
# [Version 2.0] #
# #
################################################
### Search: 'TESTING' for notes as updating program - and UP TO HERE
### NOTE: Potential problem when switch from a completed run in normal to binomial getting un-informative error message
### - Similarly when go from completed binomial to normal
# - NEED TO HAVE BETTER DEFAULTS FOR PRECISION IF USING BINOMIAL OR NORMAL - i.e. NOT DEFAULT (Although may not be an
# issue when have blank initial values!)
### - Likely partly due to not having any prob ref and other design criteria
### - Looks like not having "N & Reference" for 'select precision option' causing the issue
### - Only occurs when have default value for 'precision' - need to add in a change to the inital value of precision != 3
### NEXT STEPS:
#server script
#Creator D Gorman
#Date: 30 Dec 2015
shinyServer(function(input,output){
########################################
########################################
###### Dynamic UI for Inputs: ######
########################################
########################################
#
# Study Section:
#
output$studyUI_ocType <- renderUI({
if(is.null(input$study_comparison)){
return(NULL)
} else {
outList <- NULL
if(input$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
outList <- list(selectInput("study_comparison_type","Select output scale",choices=c(label_study_abs,label_study_perc,label_study_ratio),selected=init_study_comparison_type))
}
return(c(outList,list(selectInput("study_ocType","Select OC Type:",choices=c(label_study_conv,label_study_interim),selected=init_study_ocType),
uiOutput("studyUI_studyDesign"))))
}
})
output$studyUI_studyDesign <- renderUI({
if(is.null(input$study_ocType)){
return(NULL)
} else {
if(input$study_ocType==label_study_interim){
return(computerSaysNo())
} else if (!(input$study_comparison %in% c(label_study_1Normal,label_study_1Binomial))){
return(list(selectInput("study_studyDesign","Select Study Design:",choices=c(label_study_CrossOver,label_study_Parallel),selected=init_study_studyDesign)))
} else {
return(list(selectInput("study_studyDesign","Select Study Design:",choices=c(label_study_Single),selected=init_study_studyDesign)))
}
}
})
#
# Decision Criteria Section:
#
output$decisionUI_start <- renderUI({
if(is.null(input$study_ocType)){
return(NULL)
} else {
if(input$study_ocType==label_study_conv){
return(list(uiOutput("decisionUI_convCriteriaStart")))
} else {
return(computerSaysNo())
}
}
})
### Conventional 1 or 2 decision criteria for end of study: ###
output$decisionUI_convCriteriaStart <- renderUI({
if(is.null(input$study_ocType)){
return(NULL)
} else {
if(input$study_ocType==label_study_conv){
return(list(radioButtons("decision_nCriteria",label=("Number of criteria"),choices=list("1 decision criterion"=1,"2 decision criteria"=2),selected=init_decision_nCriteria),
radioButtons("decision_direction",label=("Direction of treatment effect"),choices=list("Greater than TV"=1,"Less than TV"=2),selected=init_decision_direction,inline=TRUE),
uiOutput("decisionUI_convCriteria")))
} else {
return(list(radioButtons("decision_nCriteria",label=("Number of criteria"),choices=list("1 decision criterion"=1),selected=init_decision_nCriteria),
radioButtons("decision_direction",label=("Direction of treatment effect"),choices=list("Greater than TV"=1,"Less than TV"=2),selected=init_decision_direction,inline=TRUE),
uiOutput("decisionUI_convCriteria")))
}
}
})
output$decisionUI_convCriteria <- renderUI({
if(is.null(input$decision_nCriteria)){
return(NULL)
} else {
addText <- ""
addText_zero <- "0"
if(input$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial) || (input$study_comparison %in% c(label_study_2Normal,label_study_1Normal) & input$study_comparison_type==label_study_perc)){
addText <- " (%)"
addText_zero <- "0%"
} else if(input$study_comparison %in% c(label_study_2Normal,label_study_1Normal) && input$study_comparison_type==label_study_ratio){
addText <- " (Ratio)"
addText_zero <- "1"
}
defVec1 <- list(numericInput("decision_c1_tv",paste0("C1 value",addText,":"),init_decision_c1_tv),
numericInput("decision_c1_sig","C1 Confidence (%):",init_decision_c1_sig))
if(input$decision_nCriteria==1){
return(c(list(h4(strong("C1 criterion options:")),
h5(em(paste0("Typically 'C1 value' is ",addText_zero," and 'C1 confidence' is 95%")))),
defVec1))
} else if(input$decision_nCriteria==2){
return(c(list(h4(strong("C1 criterion options:")),
h5(em(paste0("Typically 'C1 value' is ",addText_zero," (or the LRV) and 'C1 confidence' is 95%")))),
defVec1,
list(h4(strong("C2 criterion options:")),
h5(em("Typically 'C2 value' is the target value and 'C2 confidence' is 50%")),
numericInput("decision_c2_tv",paste0("C2 value",addText,":"),init_decision_c2_tv),
numericInput("decision_c2_sig","C2 Confidence (%):",init_decision_c2_sig))))
}
}
})
#
# Design Section:
#
output$designUI_start <- renderUI({
if(is.null(input$study_ocType)){
return(NULL)
} else {
if(input$study_ocType==label_study_conv){
return(uiOutput("designUI_conv"))
} else {
return(computerSaysNo())
}
}
})
### Conventional design options for a study: ###
output$designUI_conv <- renderUI({
if(is.null(input$study_studyDesign)){
return(NULL)
} else {
if(input$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
return(list(radioButtons("design_precision",label="Select precision option:",choices=list("N & SD"=1,"SE"=2),selected=init_design_precision),
uiOutput("designUI_precision_start")))
} else if(input$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
return(list(radioButtons("design_bin_method",label="Estimation method:",choices=list("Formula"=1,"Simulation"=2),
selected=init_design_bin_method),
uiOutput("designUI_conv_binomial")))
}
}
})
output$designUI_conv_binomial <- renderUI({
if(is.null(input$design_bin_method)){
return(NULL)
} else {
if(input$design_bin_method==1){
return(list(checkboxInput("design_normApprox",label="Normal Approximation",value=init_design_normApprox),
uiOutput("designUI_conv_binomial_sub")))
} else if(input$design_bin_method==2){
return(computerSaysNo())
#return(list(radioButtons("design_bin_test",label="Testing method:",choices=list("Normal evaluation"=1),selected=init_design_bin_test),
# uiOutput("designUI_conv_binomial_sub")))
}
}
})
output$designUI_conv_binomial_sub <- renderUI({
if(is.null(input$design_bin_method)){
return(NULL)
} else {
if(input$design_bin_method==1 && !input$design_normApprox){
return(computerSaysNo())
} else {
return(list(radioButtons("design_precision",label="Select precision option:",choices=list("N & Reference"=3),selected=init_design_precision),
uiOutput("designUI_precision_start")))
}
}
})
### Generic UI outputs: ###
output$designUI_precision_start <- renderUI({
if(is.null(input$design_precision)){
return(NULL)
} else {
if(input$study_studyDesign==label_study_Parallel){
return(list(checkboxInput("design_equalN",label="Equal N in each arm?",value=init_design_equalN),
uiOutput("designUI_precision")))
} else {
return(uiOutput("designUI_precision"))
}
}
})
output$designUI_precision <- renderUI({
if(is.null(input$design_precision) || (input$study_studyDesign==label_study_Parallel & is.null(input$design_equalN))){
return(NULL)
} else {
choices <- list(parallel=(input$study_studyDesign==label_study_Parallel),
n1=FALSE,n2=FALSE,sigma=FALSE,probRef=FALSE,SE=FALSE,log=FALSE)
outWidgets <- NULL
### Determine which widgets to return:
if(input$design_precision==1 | input$design_precision==3){ ### N & SD or N & Prob Ref precision selected
if(!choices$parallel){n1Name <- "total"
} else if(input$design_equalN){n1Name <- "per arm"
} else {
n1Name <- "treatment"
choices$n2 <- TRUE
}
choices$n1 <- TRUE
if(input$design_precision==1){choices$sigma <- TRUE
} else {choices$probRef <- TRUE}
}
if(input$design_precision==2){ ### SE precision selected
choices$parallel <- FALSE
choices$SE <- TRUE
}
if(input$study_comparison %in% c(label_study_2Normal,label_study_1Normal) && (input$study_comparison_type==label_study_perc || input$study_comparison_type==label_study_ratio)){
choices$log <- TRUE
}
### Return applicable widgets:
if(choices$log){outWidgets <- c(outWidgets,list(uiOutput("designUI_log_start")))}
if(choices$n1){
outWidgets <- c(outWidgets,list(radioButtons("design_n1_n",label=paste0("Number of sample sizes (",n1Name,") to plot:"),
choices=list("1"=1,"2"=2,"3"=3,"4"=4),selected=init_design_n1_n,inline=TRUE),
uiOutput("designUI_n1_multiple")))
}
if(choices$n2){outWidgets <- c(outWidgets,list(uiOutput("designUI_n2_start")))}
if(choices$sigma){outWidgets <- c(outWidgets,list(uiOutput("designUI_sigma_start")))}
if(choices$probRef){outWidgets <- c(outWidgets,list(uiOutput("designUI_probRef_start")))}
if(choices$SE){outWidgets <- c(outWidgets,list(uiOutput("designUI_SE_start")))}
if(input$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
outWidgets <- c(outWidgets,list(uiOutput("designUI_normalApprox_prompt"),
uiOutput("designUI_normalApprox")))
}
return(outWidgets)
}
})
### Log:
output$designUI_log_start <- renderUI({
if(is.null(input$study_comparison_type)){
return(NULL)
} else {
if(input$design_precision==1){
addText <- "Standard Deviation"
} else if(input$design_precision==2){
addText <- "Standard Error"
} else {
addText <- "ERROR"
}
return(list(radioButtons("design_log",label=paste0("Scale for ",addText,":"),
choices=list("Log[e]"=1,"Log10"=2),selected=init_design_log,inline=TRUE)))
}
})
### N1:
output$designUI_n1_multiple <- renderUI({
if(is.null(input$design_n1_n)){
return(NULL)
} else {
return(widC_MultipleNumericRowEntries("design_n1_","Sample size",input$design_n1_n))
}
})
### N2:
output$designUI_n2_start <- renderUI({
if(is.null(input$design_precision)){
return(null)
} else{
return(list(radioButtons("design_n2_n",label="Number of sample sizes (control) to plot:",
choices=list("1"=1,"2"=2,"3"=3,"4"=4),selected=init_design_n2_n,inline=TRUE),
uiOutput("designUI_n2_multiple")))
}
})
output$designUI_n2_multiple <- renderUI({
if(is.null(input$design_n2_n)){
return(NULL)
} else {
return(widC_MultipleNumericRowEntries("design_n2_","Sample size",input$design_n2_n))
}
})
### SD:
output$designUI_sigma_start <- renderUI({
if(is.null(input$design_precision)){
return(null)
} else{
if(input$study_comparison_type==label_study_abs){
addText <- ""
} else {
addText <- " (log scale)"
}
return(list(radioButtons("design_sigma_n",label=paste0("Number of standard deviations",addText," to plot:"),
choices=list("1"=1,"2"=2,"3"=3,"4"=4),selected=init_design_sigma_n,inline=TRUE),
uiOutput("designUI_sigma_multiple")))
}
})
output$designUI_sigma_multiple <- renderUI({
if(is.null(input$design_sigma_n)){
return(NULL)
} else {
return(widC_MultipleNumericRowEntries("design_sigma_","Standard Deviation",input$design_sigma_n))
}
})
### Reference Percentage:
output$designUI_probRef_start <- renderUI({
if(is.null(input$design_precision)){
return(NULL)
} else {
return(list(radioButtons("design_probRef_n",label="Number of reference percentages to plot:",
choices=list("1"=1,"2"=2,"3"=3,"4"=4),selected=init_design_probRef_n,inline=TRUE),
uiOutput("designUI_probRef_multiple")))
}
})
output$designUI_probRef_multiple <- renderUI({
if(is.null(input$design_probRef_n)){
return(NULL)
} else {
return(widC_MultipleNumericRowEntries("design_probRef_","Reference Percentage",input$design_probRef_n,"(%)"))
}
})
### SE:
output$designUI_SE_start <- renderUI({
if(is.null(input$design_precision)){
return(null)
} else{
if(input$study_comparison_type==label_study_abs){
addText <- ""
} else {
addText <- " (log scale)"
}
return(list(radioButtons("design_se_n",label=paste0("Number of standard errors",addText," to plot:"),
choices=list("1"=1,"2"=2,"3"=3,"4"=4),selected=init_design_se_n,inline=TRUE),
uiOutput("designUI_SE_multiple")))
}
})
output$designUI_SE_multiple <- renderUI({
if(is.null(input$design_se_n)){
return(NULL)
} else {
return(widC_MultipleNumericRowEntries("design_se_","Standard Error",input$design_se_n))
}
})
### Normal approximation:
output$designUI_normalApprox_prompt <- renderUI({
if(is.null(input$design_precision)){
return(NULL)
} else {
return(checkboxInput("design_normApprox",label="Normal Approximation (DF= 999)",value=init_design_normApprox))
}
})
output$designUI_normalApprox <- renderUI({
if(is.null(input$design_normApprox)){
return(NULL)
} else if(!input$design_normApprox){
return(numericInput("design_df","Degrees of freedom:",init_design_df))
} else {
return(NULL)
}
})
#
# Output Options Section:
#
output$optionsOutUI_start <- renderUI({
if(is.null(input$study_comparison) || is.null(input$study_ocType)){
return(NULL)
} else {
if(input$study_ocType==label_study_interim){
return(computerSaysNo())
} else {
addText <- ""
if(input$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial) || (input$study_comparison %in% c(label_study_2Normal,label_study_1Normal) & input$study_comparison_type==label_study_perc)){
addText <- " (%)"
} else if(input$study_comparison %in% c(label_study_2Normal,label_study_1Normal) && input$study_comparison_type==label_study_ratio){
addText <- " (Ratio)"
}
return(list(textInput("plot_title","Title of plot:",init_plot_title),
textInput("plot_userID","User ID:",init_plot_userID),
numericInput("plot_xlow",paste0("X lower limit",addText,":"),init_plot_xlow),
numericInput("plot_xupp",paste0("X upper limit",addText,":"),init_plot_xupp)))
}
}
})
#
# Additional Options Section:
#
output$advanced_legendUI <- renderUI({
if(is.null(input$design_precision)){
return(NULL)
} else {
uiList <- list()
if(input$decision_nCriteria==2){
uiList <- list(uiList,textInput("advanced_legend_label_dec_2_both","Two decision criteria plot - Label for green curve (leave blank for default):",init_advanced_legend_label_dec_2_both),
textInput("advanced_legend_label_dec_2_one","Two decision criteria plot - Label for orange curve (leave blank for default):",init_advanced_legend_label_dec_2_one),
textInput("advanced_legend_label_dec_2_none","Two decision criteria plot - Label for red curve (leave blank for default):",init_advanced_legend_label_dec_2_none))
}
uiList <- list(uiList,textInput("advanced_legend_label_dec_1_one","One decision criterion plot(s) - Label for green curve (leave blank for default):",init_advanced_legend_label_dec_1_one),
textInput("advanced_legend_label_dec_1_none","One decision criterion plot(s) - Label for red curve (leave blank for default):",init_advanced_legend_label_dec_1_none))
if(input$design_precision==1 | input$design_precision==3){
if(as.numeric(input$design_n1_n)>1){
uiList <- list(uiList,textInput("advanced_legend_title_n1","Sample size legend title:",init_advanced_legend_title_n1))
}
if(input$study_studyDesign==label_study_Parallel && !input$design_equalN){
if(as.numeric(input$design_n2_n)>1){
uiList <- list(uiList,textInput("advanced_legend_title_n2","Sample size (control) legend title:",init_advanced_legend_title_n2))
}
}
if(input$design_precision==1){
if(as.numeric(input$design_sigma_n)>1){
uiList <- list(uiList,textInput("advanced_legend_title_sigma","Standard deviation legend title:",init_advanced_legend_title_sigma))
}
} else {
if(as.numeric(input$design_probRef_n)>1){
uiList <- list(uiList,textInput("advanced_legend_title_probRef","Reference percentage legend title:",init_advanced_legend_title_probRef))
}
}
}
if(input$design_precision==2){
if(as.numeric(input$design_se_n)>1){
uiList <- list(uiList,textInput("advanced_legend_title_se","Standard error legend title:",init_advanced_legend_title_se))
}
}
return(uiList)
}
})
output$advanced_linesVertUI <- renderUI({
if(is.null(input$advanced_lines_vert_number)){
return(NULL)
} else if(input$advanced_lines_vert_number!=0){
uiList <- list()
for(i in 1:input$advanced_lines_vert_number){
uiList[[(2*i)-1]] <- numericInput(paste0("advanced_lines_vert_pos",i),paste0("Vertical line position ",i,":"),get(paste0("init_advanced_lines_vert_pos",i)))
uiList[[2*i]] <- selectInput(paste0("advanced_lines_vert_col",i),paste0("Vertical line colour ",i,":"),
choices=label_advanced_lines_vert_colours,selected=init_advanced_lines_vert_colour)
}
return(uiList)
} else {
return(NULL)
}
})
output$advanced_linesHorzUI <- renderUI({
if(is.null(input$advanced_lines_horz_number)){
return(NULL)
} else if (input$advanced_lines_horz_number!=0){
uiList <- list()
for(i in 1:input$advanced_lines_horz_number){
uiList[[(2*i)-1]] <- numericInput(paste0("advanced_lines_horz_pos",i),paste0("Horizontal line position ",i,":"),get(paste0("init_advanced_lines_horz_pos",i)))
uiList[[2*i]] <- selectInput(paste0("advanced_lines_horz_col",i),paste0("Horizontal line colour ",i,":"),
choices=label_advanced_lines_horz_colours,selected=init_advanced_lines_horz_colour)
}
return(uiList)
} else {
return(NULL)
}
})
output$advanced_plotSimUI <- renderUI({
if(is.null(input$study_ocType) || (input$study_ocType==label_study_conv)){
return(NULL)
} else {
return(numericInput("advanced_plot_sim","Number of simulations:",init_advanced_plot_sim))
}
})
########################################
########################################
###### Observe input changes: ######
########################################
########################################
# This section ensures that when update button is pressed all inputs are appropriately updated for downstream outputs
study_obs <- reactiveValues(study_comparison=NULL,study_comparison_type=NULL,study_ocType=NULL,study_studyDesign=NULL)
decision_obs <- reactiveValues(decision_nCriteria=NULL,decision_direction=NULL,decision_c1_tv=NULL,decision_c1_sig=NULL,
decision_c2_tv=NULL,decision_c2_sig=NULL)
design_obs <- reactiveValues(design_precision=NULL,design_bin_method=NULL,design_bin_test=NULL,
design_equalN=NULL,design_log=NULL,design_n1_n=NULL,
design_n1_1=NULL,design_n1_2=NULL,design_n1_3=NULL,design_n1_4=NULL,
design_n2_n=NULL,design_n2_1=NULL,design_n2_2=NULL,design_n2_3=NULL,
design_n2_4=NULL,design_sigma_n=NULL,design_sigma_1=NULL,design_sigma_2=NULL,
design_sigma_3=NULL,design_sigma_4=NULL,design_probRef_n=NULL,design_probRef_1=NULL,
design_probRef_2=NULL,design_probRef_3=NULL,design_probRef_4=NULL,design_se_n=NULL,
design_se_1=NULL,design_se_2=NULL,design_se_3=NULL,design_se_4=NULL,design_interim_prop=NULL,
design_normApprox=NULL,design_df=NULL)
plot_obs <- reactiveValues(plot_title=NULL,plot_userID=NULL,plot_xlow=NULL,plot_xupp=NULL)
advanced_obs <- reactiveValues(advanced_yaxis_title=NULL,advanced_yaxis_break=NULL,advanced_yaxis_low=NULL,
advanced_yaxis_upp=NULL,advanced_xaxis_title=NULL,advanced_xaxis_break=NULL,
advanced_legend_title=NULL,
advanced_legend_label_dec_2_both=NULL,advanced_legend_label_dec_2_one=NULL,advanced_legend_label_dec_2_none=NULL,
advanced_legend_label_dec_1_one=NULL,advanced_legend_label_dec_1_none=NULL,
advanced_legend_title_interim=NULL,advanced_legend_title_se=NULL,
advanced_legend_title_n1=NULL,advanced_legend_title_n2=NULL,advanced_legend_title_sigma=NULL,
advanced_legend_title_probRef=NULL,advanced_lines_vert_number=NULL,advanced_lines_vert_pos1=NULL,
advanced_lines_vert_col1=NULL,advanced_lines_vert_pos2=NULL,advanced_lines_vert_col2=NULL,
advanced_lines_vert_pos3=NULL,advanced_lines_vert_col3=NULL,advanced_lines_horz_number=NULL,
advanced_lines_horz_pos1=NULL,advanced_lines_horz_col1=NULL,advanced_lines_horz_pos2=NULL,
advanced_lines_horz_col2=NULL,advanced_lines_horz_pos3=NULL,advanced_lines_horz_col3=NULL,
advanced_footnote_choice=NULL,advanced_plot_gap=NULL,advanced_plot_sim=NULL,
advanced_plot_width=NULL,advanced_plot_height=NULL,advanced_plot_curves=NULL,advanced_plot_size=NULL)
observeEvent(input$updateOutput,{
study_obs$study_comparison <- input$study_comparison
study_obs$study_comparison_type <- input$study_comparison_type
study_obs$study_ocType <- input$study_ocType
study_obs$study_studyDesign <- input$study_studyDesign
decision_obs$decision_nCriteria <- input$decision_nCriteria
decision_obs$decision_direction <- input$decision_direction
decision_obs$decision_c1_tv <- input$decision_c1_tv
decision_obs$decision_c1_sig <- input$decision_c1_sig
decision_obs$decision_c2_tv <- input$decision_c2_tv
decision_obs$decision_c2_sig <- input$decision_c2_sig
design_obs$design_precision <- input$design_precision
design_obs$design_bin_method <- input$design_bin_method
design_obs$design_bin_test <- input$design_bin_test
design_obs$design_equalN <- input$design_equalN
design_obs$design_log <- input$design_log
design_obs$design_n1_n <- input$design_n1_n
design_obs$design_n1_1 <- input$design_n1_1
design_obs$design_n1_2 <- input$design_n1_2
design_obs$design_n1_3 <- input$design_n1_3
design_obs$design_n1_4 <- input$design_n1_4
design_obs$design_n2_n <- input$design_n2_n
design_obs$design_n2_1 <- input$design_n2_1
design_obs$design_n2_2 <- input$design_n2_2
design_obs$design_n2_3 <- input$design_n2_3
design_obs$design_n2_4 <- input$design_n2_4
design_obs$design_sigma_n <- input$design_sigma_n
design_obs$design_sigma_1 <- input$design_sigma_1
design_obs$design_sigma_2 <- input$design_sigma_2
design_obs$design_sigma_3 <- input$design_sigma_3
design_obs$design_sigma_4 <- input$design_sigma_4
design_obs$design_probRef_n <- input$design_probRef_n
design_obs$design_probRef_1 <- input$design_probRef_1
design_obs$design_probRef_2 <- input$design_probRef_2
design_obs$design_probRef_3 <- input$design_probRef_3
design_obs$design_probRef_4 <- input$design_probRef_4
design_obs$design_se_n <- input$design_se_n
design_obs$design_se_1 <- input$design_se_1
design_obs$design_se_2 <- input$design_se_2
design_obs$design_se_3 <- input$design_se_3
design_obs$design_se_4 <- input$design_se_4
design_obs$design_normApprox <- input$design_normApprox
design_obs$design_df <- input$design_df
plot_obs$plot_title <- input$plot_title
plot_obs$plot_userID <- input$plot_userID
plot_obs$plot_xlow <- input$plot_xlow
plot_obs$plot_xupp <- input$plot_xupp
advanced_obs$advanced_yaxis_title <- input$advanced_yaxis_title
advanced_obs$advanced_yaxis_break <- input$advanced_yaxis_break
advanced_obs$advanced_yaxis_low <- input$advanced_yaxis_low
advanced_obs$advanced_yaxis_upp <- input$advanced_yaxis_upp
advanced_obs$advanced_xaxis_title <- input$advanced_xaxis_title
advanced_obs$advanced_xaxis_break <- input$advanced_xaxis_break
advanced_obs$advanced_legend_title <- input$advanced_legend_title
advanced_obs$advanced_legend_label_dec_2_both <- input$advanced_legend_label_dec_2_both
advanced_obs$advanced_legend_label_dec_2_one <- input$advanced_legend_label_dec_2_one
advanced_obs$advanced_legend_label_dec_2_none <- input$advanced_legend_label_dec_2_none
advanced_obs$advanced_legend_label_dec_1_one <- input$advanced_legend_label_dec_1_one
advanced_obs$advanced_legend_label_dec_1_none <- input$advanced_legend_label_dec_1_none
advanced_obs$advanced_legend_title_interim <- input$advanced_legend_title_interim
advanced_obs$advanced_legend_title_se <- input$advanced_legend_title_se
advanced_obs$advanced_legend_title_n1 <- input$advanced_legend_title_n1
advanced_obs$advanced_legend_title_n2 <- input$advanced_legend_title_n2
advanced_obs$advanced_legend_title_sigma <- input$advanced_legend_title_sigma
advanced_obs$advanced_legend_title_probRef <- input$advanced_legend_title_probRef
advanced_obs$advanced_lines_vert_number <- input$advanced_lines_vert_number
advanced_obs$advanced_lines_vert_pos1 <- input$advanced_lines_vert_pos1
advanced_obs$advanced_lines_vert_col1 <- input$advanced_lines_vert_col1
advanced_obs$advanced_lines_vert_pos2 <- input$advanced_lines_vert_pos2
advanced_obs$advanced_lines_vert_col2 <- input$advanced_lines_vert_col2
advanced_obs$advanced_lines_vert_pos3 <- input$advanced_lines_vert_pos3
advanced_obs$advanced_lines_vert_col3 <- input$advanced_lines_vert_col3
advanced_obs$advanced_lines_horz_number <- input$advanced_lines_horz_number
advanced_obs$advanced_lines_horz_pos1 <- input$advanced_lines_horz_pos1
advanced_obs$advanced_lines_horz_col1 <- input$advanced_lines_horz_col1
advanced_obs$advanced_lines_horz_pos2 <- input$advanced_lines_horz_pos2
advanced_obs$advanced_lines_horz_col2 <- input$advanced_lines_horz_col2
advanced_obs$advanced_lines_horz_pos3 <- input$advanced_lines_horz_pos3
advanced_obs$advanced_lines_horz_col3 <- input$advanced_lines_horz_col3
advanced_obs$advanced_footnote_choice <- input$advanced_footnote_choice
advanced_obs$advanced_plot_gap <- input$advanced_plot_gap
advanced_obs$advanced_plot_sim <- input$advanced_plot_sim
advanced_obs$advanced_plot_width <- input$advanced_plot_width
advanced_obs$advanced_plot_height <- input$advanced_plot_height
advanced_obs$advanced_plot_curves <- input$advanced_plot_curves
advanced_obs$advanced_plot_size <- input$advanced_plot_size
})
##################################
##################################
###### Validate inputs: ######
##################################
##################################
#
# Tab names:
# - Study
# - Decision
# - Design
# - Plot
# - Advanced
`%then%` <- shiny:::`%OR%`
#
# Study inputs:
#
study_comparison_val <- reactive({
validate_generic_function(study_obs$study_comparison,"Study comparison [Study Tab]")
})
study_comparison_type_val <- reactive({
validate_generic_function(study_obs$study_comparison_type,"Study comparison type [Study Tab]")
})
study_ocType_val <- reactive({
validate_generic_function(study_obs$study_ocType,"Study OC Type [Study Tab]")
})
study_studyDesign_val <- reactive({
validate_generic_function(study_obs$study_studyDesign,"Study Design [Study Tab]")
})
#
# Decision criteria inputs:
#
decision_nCriteria_val <- reactive({
validate_generic_function(decision_obs$decision_nCriteria,"Number of decision criteria [Criteria Tab]")
})
decision_direction_val <- reactive({
if(decision_obs$decision_direction==1){decision_direction <- TRUE
} else {decision_direction <- FALSE}
return(decision_direction)
})
decision_c1_tv_val_sub <- reactive({
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
if(study_obs$study_comparison_type==label_study_abs){
validate_numeric_function(decision_obs$decision_c1_tv,"C1 Value [Criteria Tab]")
} else if(study_obs$study_comparison_type==label_study_perc){
validate_percDiffNorm_function(decision_obs$decision_c1_tv,"C1 Value [Criteria Tab]")
} else if(study_obs$study_comparison_type==label_study_ratio){
validate_prec_function(decision_obs$decision_c1_tv,"C1 Value [Criteria Tab]")
}
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiff_function(decision_obs$decision_c1_tv,"C1 Value [Criteria Tab]")
}
return(decision_obs$decision_c1_tv)
})
decision_c1_tv_val <- reactive({
return(decision_c1_tv_val_sub())
})
decision_c1_tv_val_for <- function(){
formatInputConvert(decision_c1_tv_val())
}
decision_c1_sig_val <- reactive({
validate_sig_function(decision_obs$decision_c1_sig,"C1 [Criteria Tab]")
return(decision_obs$decision_c1_sig/100)
})
decision_c2_tv_val_sub <- reactive({
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
if(study_obs$study_comparison_type==label_study_abs){
validate_numeric_function(decision_obs$decision_c2_tv,"C2 Value [Criteria Tab]")
} else if(study_obs$study_comparison_type==label_study_perc){
validate_percDiffNorm_function(decision_obs$decision_c2_tv,"C2 Value [Criteria Tab]")
} else if(study_obs$study_comparison_type==label_study_ratio){
validate_prec_function(decision_obs$decision_c2_tv,"C2 Value [Criteria Tab]")
}
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiff_function(decision_obs$decision_c2_tv,"C2 Value [Criteria Tab]")
}
return(decision_obs$decision_c2_tv)
})
decision_c2_tv_val <- reactive({
if(decision_direction_val()){
validate(
need(decision_c2_tv_val_sub() > decision_c1_tv_val(),"Target value C2 should be greater than Target value C1")
)
} else {
validate(
need(decision_c2_tv_val_sub() < decision_c1_tv_val(),"Target value C2 should be less than Target value C1")
)
}
return(decision_c2_tv_val_sub())
})
decision_c2_tv_val_for <- function(){
formatInputConvert(decision_c2_tv_val())
}
decision_c2_sig_val_sub <- reactive({
validate_sig_function(decision_obs$decision_c2_sig,"C2 [Criteria Tab]")
})
decision_c2_sig_val <- reactive({
validate(
need(decision_c2_sig_val_sub()/100 <= decision_c1_sig_val(),"C2 confidence should be smaller than or equal to C1 confidence")
)
return(decision_c2_sig_val_sub()/100)
})
#
# Design inputs:
#
design_precision_val <- reactive({
validate_generic_function(design_obs$design_precision,"the precision option of the design [Design Tab]")
})
design_bin_method_val <- reactive({
return(design_obs$design_bin_method)
})
design_bin_test_val <- reactive({
return(design_obs$design_bin_test)
})
design_equalN_val <- reactive({
#validate_generic_function(design_obs$design_equalN,"whether equal N in each study arm [Design Tab]")
return(design_obs$design_equalN)
})
design_log_val <- reactive({
validate_generic_function(design_obs$design_log,"Scale for percentage difference [Design Tab]")
if(design_obs$design_log==3){validate(need(FALSE,"CV Scale not currently supported [Design Tab]"))}
return(design_obs$design_log)
})
design_n1_n_val <- reactive({
validate_generic_function(design_obs$design_n1_n,"Number of N1 sample sizes [Design Tab]")
})
design_n1_1_val <- reactive({
validate_integer_function(design_obs$design_n1_1,"Sample size 1 [Design Tab]")
})
design_n1_2_val <- reactive({
validate_integer_function(design_obs$design_n1_2,"Sample size 2 [Design Tab]")
})
design_n1_3_val <- reactive({
validate_integer_function(design_obs$design_n1_3,"Sample size 3 [Design Tab]")
})
design_n1_4_val <- reactive({
validate_integer_function(design_obs$design_n1_4,"Sample size 4 [Design Tab]")
})
design_n2_n_val <- reactive({
validate_generic_function(design_obs$design_n2_n,"Number of N2 sample sizes [Design Tab]")
})
design_n2_1_val <- reactive({
validate_integer_function(design_obs$design_n2_1,"Sample size 1 [Design Tab]")
})
design_n2_2_val <- reactive({
validate_integer_function(design_obs$design_n2_2,"Sample size 2 [Design Tab]")
})
design_n2_3_val <- reactive({
validate_integer_function(design_obs$design_n2_3,"Sample size 3 [Design Tab]")
})
design_n2_4_val <- reactive({
validate_integer_function(design_obs$design_n2_4,"Sample size 4 [Design Tab]")
})
design_sigma_n_val <- reactive({
validate_generic_function(design_obs$design_sigma_n,"Number of standard deviations [Design Tab]")
})
design_sigma_1_val <- reactive({
validate_prec_function(design_obs$design_sigma_1,"Standard Deviation 1 [Design Tab]")
})
design_sigma_2_val <- reactive({
validate_prec_function(design_obs$design_sigma_2,"Standard Deviation 2 [Design Tab]")
})
design_sigma_3_val <- reactive({
validate_prec_function(design_obs$design_sigma_3,"Standard Deviation 3 [Design Tab]")
})
design_sigma_4_val <- reactive({
validate_prec_function(design_obs$design_sigma_4,"Standard Deviation 4 [Design Tab]")
})
design_probRef_n_val <- reactive({
validate_generic_function(design_obs$design_probRef_n,"Number of reference percentage [Design Tab]")
})
design_probRef_1_val <- reactive({
validate_perc100_function(design_obs$design_probRef_1,"Reference Percentage 1 [Design Tab]")
})
design_probRef_2_val <- reactive({
validate_perc100_function(design_obs$design_probRef_2,"Reference Percentage 2 [Design Tab]")
})
design_probRef_3_val <- reactive({
validate_perc100_function(design_obs$design_probRef_3,"Reference Percentage 3 [Design Tab]")
})
design_probRef_4_val <- reactive({
validate_perc100_function(design_obs$design_probRef_4,"Reference Percentage 4 [Design Tab]")
})
# Create formatted (i.e. as a proportion) for use with calculations:
design_probRef_1_val_for <- function(){
formatInputConvert(design_probRef_1_val())
}
design_probRef_2_val_for <- function(){
formatInputConvert(design_probRef_2_val())
}
design_probRef_3_val_for <- function(){
formatInputConvert(design_probRef_3_val())
}
design_probRef_4_val_for <- function(){
formatInputConvert(design_probRef_4_val())
}
design_se_n_val <- reactive({
validate_generic_function(design_obs$design_se_n,"Number of standard errors [Design Tab]")
})
design_se_1_val <- reactive({
validate_prec_function(design_obs$design_se_1,"Standard Error 1 [Design Tab]")
})
design_se_2_val <- reactive({
validate_prec_function(design_obs$design_se_2,"Standard Error 2 [Design Tab]")
})
design_se_3_val <- reactive({
validate_prec_function(design_obs$design_se_3,"Standard Error 3 [Design Tab]")
})
design_se_4_val <- reactive({
validate_prec_function(design_obs$design_se_4,"Standard Error 4 [Design Tab]")
})
design_normApprox_val <- reactive({
validate_logical_function(design_obs$design_normApprox,"Design Normal Approximation [Design Tab]")
})
design_df_val <- reactive({
validate_integer_function(design_obs$design_df,"Degrees of freedom [Design Tab]")
})
#
# Plot output inputs:
#
plot_title_val <- reactive({
return(plot_obs$plot_title)
})
plot_userID_val <- reactive({
return(plot_obs$plot_userID)
})
plot_xlow_val_sub <- reactive({
if(determineEmpty(plot_obs$plot_xlow) & decision_direction_val() & FALSE){
#### TESTING: If it appears interim wouldn't be too difficult can incorporate these automatic calculations for now
#### HOWEVER, this potentially has impact on graph re-drawing each time update is hit for some reason - i.e.
### maybe not such a good idea!
plot_obs$plot_xlow <- decision_c1_tv_val()
} else {
### TESTING: Will need to write stand alone function for this, housed within server to begin with
### - This will allow dealing with i.e. interim a lot easier!
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
if(study_obs$study_comparison_type==label_study_abs){
validate_numeric_function(plot_obs$plot_xlow,"X lower limit [Output Tab]")
} else if(study_obs$study_comparison_type==label_study_perc){
validate_percDiffNorm_function(plot_obs$plot_xlow,"X lower limit [Output Tab]")
} else if(study_obs$study_comparison_type==label_study_ratio){
validate_prec_function(plot_obs$plot_xlow,"X lower limit [Output Tab]")
}
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiffAxis_function(plot_obs$plot_xlow,"X lower limit [Output Tab]")
}
}
})
plot_xlow_val <- reactive({
if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
lowXlowValue <- design_probRef_1_val()
if(design_probRef_n_val()>2){
for(i in 2:design_probRef_n_val()){
lowXlowValue <- max(lowXlowValue,get(paste0("design_probRef_",i,"_val"))())
}
}
validate(
need(plot_xlow_val_sub() + lowXlowValue>= 0,paste0("X-axis lower limit cannot be less than -",lowXlowValue,"% (based on difference to reference percentage) [Output Tab]"))
)
}
return(plot_xlow_val_sub())
})
plot_xlow_val_for <- function(){
formatInputConvert(plot_xlow_val())
}
plot_xupp_val_sub <- reactive({
if(determineEmpty(plot_obs$plot_xupp) & !decision_direction_val() & FALSE){
plot_obs$plot_xupp <- decision_c1_tv_val()
} else {
### TESTING: Similar to plot_xlow_val as above:
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
if(study_obs$study_comparison_type==label_study_abs){
validate_numeric_function(plot_obs$plot_xupp,"X upper limit [Output Tab]")
} else if(study_obs$study_comparison_type==label_study_perc){
validate_percDiffNorm_function(plot_obs$plot_xupp,"X upper limit [Output Tab]")
} else if(study_obs$study_comparison_type==label_study_ratio){
validate_prec_function(plot_obs$plot_xupp,"X upper limit [Output Tab]")
}
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiffAxis_function(plot_obs$plot_xupp,"X upper limit [Output Tab]")
}
}
})
plot_xupp_val <- reactive({
validate(
need(plot_xupp_val_sub() > plot_xlow_val(),"X-axis upper limit must be greater than lower limit [Output Tab]")
)
if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
uppXuppValue <- design_probRef_1_val()
if(design_probRef_n_val()>2){
for(i in 2:design_probRef_n_val()){
uppXuppValue <- min(uppXuppValue,get(paste0("design_probRef_",i,"_val"))())
}
}
validate(
need(plot_xupp_val_sub() + uppXuppValue<= 100,paste0("X-axis upper limit cannot be greater than ",100-uppXuppValue,"% (based on difference to reference percentage) [Output Tab]"))
)
}
return(plot_xupp_val_sub())
})
plot_xupp_val_for <- function(){
formatInputConvert(plot_xupp_val())
}
#
# Advanced options:
#
advanced_yaxis_title_val <- reactive({
if(determineEmpty(advanced_obs$advanced_yaxis_title)){
advanced_obs$advanced_yaxis_title <- "Probability of Passing Criteria (%)"
}
return(advanced_obs$advanced_yaxis_title)
})
advanced_yaxis_break_val <- reactive({
if(determineEmpty(advanced_obs$advanced_yaxis_break)){
advanced_obs$advanced_yaxis_break <- 20
}
validate(
need(advanced_obs$advanced_yaxis_break > 0,paste0("Y-axis breaks must be greater than zero [Advanced Tab/Y-axis]")) %then%
need(advanced_obs$advanced_yaxis_break <= 100,paste0("Y-axis lower breaks must be less than or equal to 100 [Advanced Tab/Y-axis]"))
)
return(advanced_obs$advanced_yaxis_break)
})
advanced_yaxis_low_val <- reactive({
if(determineEmpty(advanced_obs$advanced_yaxis_low)){
advanced_obs$advanced_yaxis_low <- 0
}
validate(
need(advanced_obs$advanced_yaxis_low >= 0,paste0("Y-axis lower limit must be greater than or equal to zero [Advanced Tab/Y-axis]")) %then%
need(advanced_obs$advanced_yaxis_low < 100,paste0("Y-axis lower limit must be less than 100 [Advanced Tab/Y-axis]"))
)
return(advanced_obs$advanced_yaxis_low)
})
advanced_yaxis_upp_val <- reactive({
if(determineEmpty(advanced_obs$advanced_yaxis_upp)){
advanced_obs$advanced_yaxis_upp <- 100
}
validate(
need(advanced_obs$advanced_yaxis_upp > 0,paste0("Y-axis upper limit must be greater than zero [Advanced Tab/Y-axis]")) %then%
need(advanced_obs$advanced_yaxis_upp <= 100,paste0("Y-axis upper limit must be less than or equal to 100 [Advanced Tab/Y-axis]")) %then%
need(advanced_obs$advanced_yaxis_upp > advanced_obs$advanced_yaxis_low,paste0("Y-axis upper limit must be greater than Y-axis lower limit [Advanced Tab/Y-axis]"))
)
return(advanced_obs$advanced_yaxis_upp)
})
advanced_xaxis_title_val <- reactive({
if(determineEmpty(advanced_obs$advanced_xaxis_title)){
if(study_obs$study_comparison==label_study_2Normal){
if(study_obs$study_comparison_type==label_study_abs){
advanced_obs$advanced_xaxis_title <- "True Effect over Placebo"
} else if(study_obs$study_comparison_type==label_study_perc){
advanced_obs$advanced_xaxis_title <- "True Effect over Placebo (%)"
} else if(study_obs$study_comparison_type==label_study_ratio){
advanced_obs$advanced_xaxis_title <- "True Ratio to Placebo"
}
} else if(study_obs$study_comparison==label_study_1Normal){
if(study_obs$study_comparison_type==label_study_abs){
advanced_obs$advanced_xaxis_title <- "True Effect"
} else if(study_obs$study_comparison_type==label_study_perc){
advanced_obs$advanced_xaxis_title <- "True Effect (%)"
} else if(study_obs$study_comparison_type==label_study_ratio){
advanced_obs$advanced_xaxis_title <- "True Ratio"
}
} else if(study_obs$study_comparison==label_study_2Binomial){
advanced_obs$advanced_xaxis_title <- "True Difference to Placebo (%)"
} else if(study_obs$study_comparison==label_study_1Binomial){
advanced_obs$advanced_xaxis_title <- "True Difference to Reference Proportion (%)"
}
}
return(advanced_obs$advanced_xaxis_title)
})
advanced_xaxis_break_val <- reactive({
validate(
if(!is.null(advanced_obs$advanced_xaxis_break) && !is.na(advanced_obs$advanced_xaxis_break)){
if(advanced_obs$advanced_xaxis_break != ""){
need(advanced_obs$advanced_xaxis_break > 0,paste0("X-axis breaks must be greater than zero [Advanced Tab/X-axis]"))
}
}
)
return(advanced_obs$advanced_xaxis_break)
})
advanced_legend_title_val <- reactive({
if(determineEmpty(advanced_obs$advanced_legend_title)){
advanced_obs$advanced_legend_title <- "Criteria Passed"
}
return(advanced_obs$advanced_legend_title)
})
advanced_legend_label_dec_2_both_val <- reactive({
if(determineEmpty(advanced_obs$advanced_legend_label_dec_2_both)){
advanced_obs$advanced_legend_label_dec_2_both <- label_decision_2_both
}
return(advanced_obs$advanced_legend_label_dec_2_both)
})
advanced_legend_label_dec_2_one_val <- reactive({
if(determineEmpty(advanced_obs$advanced_legend_label_dec_2_one)){
advanced_obs$advanced_legend_label_dec_2_one <- label_decision_2_one
}
return(advanced_obs$advanced_legend_label_dec_2_one)
})
advanced_legend_label_dec_2_none_val <- reactive({
if(determineEmpty(advanced_obs$advanced_legend_label_dec_2_none)){
advanced_obs$advanced_legend_label_dec_2_none <- label_decision_2_none
}
return(advanced_obs$advanced_legend_label_dec_2_none)
})
advanced_legend_label_dec_1_one_val <- reactive({
if(determineEmpty(advanced_obs$advanced_legend_label_dec_1_one)){
advanced_obs$advanced_legend_label_dec_1_one <- label_decision_1_one
}
return(advanced_obs$advanced_legend_label_dec_1_one)
})
advanced_legend_label_dec_1_none_val <- reactive({
if(determineEmpty(advanced_obs$advanced_legend_label_dec_1_none)){
advanced_obs$advanced_legend_label_dec_1_none <- label_decision_1_none
}
return(advanced_obs$advanced_legend_label_dec_1_none)
})
advanced_legend_title_interim_val <- reactive({
return(advanced_obs$advanced_legend_title_interim)
})
advanced_legend_title_se_val <- reactive({
if(is.null(advanced_obs$advanced_legend_title_se)){
return(init_advanced_legend_title_se)
} else {
return(advanced_obs$advanced_legend_title_se)
}
})
advanced_legend_title_n1_val <- reactive({
if(is.null(advanced_obs$advanced_legend_title_n1)){
return(init_advanced_legend_title_n1)
} else {
return(advanced_obs$advanced_legend_title_n1)
}
})
advanced_legend_title_n2_val <- reactive({
if(is.null(advanced_obs$advanced_legend_title_n2)){
return(init_advanced_legend_title_n2)
} else {
return(advanced_obs$advanced_legend_title_n2)
}
})
advanced_legend_title_sigma_val <- reactive({
if(is.null(advanced_obs$advanced_legend_title_sigma)){
return(init_advanced_legend_title_sigma)
} else {
return(advanced_obs$advanced_legend_title_sigma)
}
})
advanced_legend_title_probRef_val <- reactive({
if(is.null(advanced_obs$advanced_legend_title_probRef)){
return(init_advanced_legend_title_probRef)
} else {
return(advanced_obs$advanced_legend_title_probRef)
}
})
advanced_lines_vert_number_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_vert_number,"Number of vertical lines [Advanced Tab/Add lines]")
})
advanced_lines_vert_pos1_val <- reactive({
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
validate_numeric_function(advanced_obs$advanced_lines_vert_pos1,"Vertical line position 1 [Advanced Tab/Add lines]")
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiffAxis_function(advanced_obs$advanced_lines_vert_pos1,"Vertical line position 1 [Advanced Tab/Add lines]")
}
})
advanced_lines_vert_col1_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_vert_col1,"Vertical line colour 1 [Advanced Tab/Add lines]")
})
advanced_lines_vert_pos2_val <- reactive({
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
validate_numeric_function(advanced_obs$advanced_lines_vert_pos2,"Vertical line position 2 [Advanced Tab/Add lines]")
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiffAxis_function(advanced_obs$advanced_lines_vert_pos2,"Vertical line position 2 [Advanced Tab/Add lines]")
}
})
advanced_lines_vert_col2_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_vert_col2,"Vertical line colour 2 [Advanced Tab/Add lines]")
})
advanced_lines_vert_pos3_val <- reactive({
if(study_obs$study_comparison %in% c(label_study_2Normal,label_study_1Normal)){
validate_numeric_function(advanced_obs$advanced_lines_vert_pos3,"Vertical line position 3 [Advanced Tab/Add lines]")
} else if(study_obs$study_comparison %in% c(label_study_2Binomial,label_study_1Binomial)){
validate_percDiffAxis_function(advanced_obs$advanced_lines_vert_pos3,"Vertical line position 3 [Advanced Tab/Add lines]")
}
})
advanced_lines_vert_col3_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_vert_col3,"Vertical line colour 3 [Advanced Tab/Add lines]")
})
advanced_lines_horz_number_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_horz_number,"Number of horizontal lines [Advanced Tab/Add lines]")
})
advanced_lines_horz_pos1_val <- reactive({
validate_sig_function(advanced_obs$advanced_lines_horz_pos1,"Horizontal line position 1 [Advanced Tab/Add lines]")
})
advanced_lines_horz_col1_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_horz_col1,"Horizontal line colour 1 [Advanced Tab/Add lines]")
})
advanced_lines_horz_pos2_val <- reactive({
validate_sig_function(advanced_obs$advanced_lines_horz_pos2,"Horizontal line position 2 [Advanced Tab/Add lines]")
})
advanced_lines_horz_col2_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_horz_col2,"Horizontal line colour 2 [Advanced Tab/Add lines]")
})
advanced_lines_horz_pos3_val <- reactive({
validate_sig_function(advanced_obs$advanced_lines_horz_pos3,"Horizontal line position 3 [Advanced Tab/Add lines]")
})
advanced_lines_horz_col3_val <- reactive({
validate_generic_function(advanced_obs$advanced_lines_horz_col3,"Horizontal line colour 3 [Advanced Tab/Add lines]")
})
advanced_footnote_choice_val <- reactive({
validate_generic_function(advanced_obs$advanced_footnote_choice,"Footnote options [Advanced Tab/Footnote]")
})
advanced_plot_gap_val <- reactive({
validate_integer_function(advanced_obs$advanced_plot_gap,"Number of points [Advanced Tab/Plots]")
validate(
need(advanced_obs$advanced_plot_gap < 5000,paste0("Behave yourself (EASTER EGG)!\nNumber of points should be less than 5,000 [Advanced Tab/Plots]"))
)
return(advanced_obs$advanced_plot_gap)
})
advanced_plot_sim_val_sub <- reactive({
if(is.null(advanced_obs$advanced_plot_sim)){
return(init_advanced_plot_sim)
} else {
return(advanced_obs$advanced_plot_sim)
}
})
advanced_plot_sim_val <- reactive({
validate_integer_function(advanced_plot_sim_val_sub(),"Number of simulations [Advanced Tab/Plots]")
})
advanced_plot_width_val <- reactive({
validate_integer_function(advanced_obs$advanced_plot_width,"Width of plot [Advanced Tab/Plots]")
})
advanced_plot_height_val <- reactive({
validate_integer_function(advanced_obs$advanced_plot_height,"Height of plot [Advanced Tab/Plots]")
})
advanced_plot_curves_val <- reactive({
validate(
need(advanced_obs$advanced_plot_curves,paste0("Need to select at least one colour to plot [Advanced Tab/Plots]"))
)
return(advanced_obs$advanced_plot_curves)
})
advanced_plot_size_val <- reactive({
if(determineEmpty(advanced_obs$advanced_plot_size)){
advanced_obs$advanced_plot_size <- 1
} else {
validate_prec_function(advanced_obs$advanced_plot_size,"Line size [Advanced Tab/Plots]")
}
return(advanced_obs$advanced_plot_size)
})
#########################################
#########################################
###### Format input functions: ######
#########################################
#########################################
formatInputConvert <- function(value){
### Function to convert input onto scale for analysis (if applicable)
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && study_comparison_type_val()==label_study_abs){
### Normal absolute difference:
return(value)
} else if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && study_comparison_type_val()==label_study_perc){
### Normal percentage difference:
return(formatPercDiffNorm(value,design_log_val()))
} else if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && study_comparison_type_val()==label_study_ratio){
### Normal ratio difference:
return(formatRatioNorm(value,design_log_val()))
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
### Binomial difference:
return(formatPercDiffBin(value))
}
}
#########################################
#########################################
###### Dynamic UI for Outputs: ######
#########################################
#########################################
output$outputUI_start <- renderUI({
if(!is.null(study_obs$study_ocType)){
if(study_ocType_val()==label_study_conv){
### Conventional OC output:
optList4 <- tabPanel("Summary Table",h3("Summary of key points of interest"),br(),
downloadButton("download_table_summary_key","Download"),br(),
br(),tableOutput("table_summary_key"),br(),
h4("Use drop-downs below to filter table (or download as csv and open in excel)"),br(),
uiOutput("outputUI_table_summary_key"))
optList5 <- tabPanel("Options Summary",h3("Summary of options used to create curves"),br(),
downloadButton("download_table_summary_options","Download"),br(),br(),tableOutput("table_summary_options"))
if(decision_nCriteria_val()==1){
optList1 <- tabPanel("OC Curves",h3(textOutput("text_1dec_c1_text")),br(),
plotOutput("plot_OC_1dec_C1",width=advanced_plot_width_val(),height=advanced_plot_height_val()))
optList6 <- tabPanel("Data Downloads",h3("1. Data behind main OC curve:"),
downloadButton("download_data_c1","Download"))
### Create tab panel:
tabsetPanel(type = "tabs",optList1,optList4,optList5,optList6)
} else if(decision_nCriteria_val()==2){
optList1 <- tabPanel("OC Curves",h3(textOutput("text_2dec_c1_text")),h3(textOutput("text_2dec_c2_text")),
h3(htmlOutput("text_warning_prec")),
plotOutput("plot_OC_2dec",width=advanced_plot_width_val(),height=advanced_plot_height_val()))
optList2 <- tabPanel("C1 Curve",h3(textOutput("text_1dec_c1_text")),br(),
plotOutput("plot_OC_1dec_C1",width=advanced_plot_width_val(),height=advanced_plot_height_val()))
optList3 <- tabPanel("C2 Curve",h3(textOutput("text_1dec_c2_text")),br(),
plotOutput("plot_OC_1dec_C2",width=advanced_plot_width_val(),height=advanced_plot_height_val()))
optList6 <- tabPanel("Data Downloads",h3("1. Data behind main OC curve:"),
downloadButton("download_data_main","Download"),
h3("2. Data behind C1 Curve:"),
downloadButton("download_data_c1","Download"),
h3("3. Data behind C2 Curve:"),
downloadButton("download_data_c2","Download"))
### Create tab panel:
tabsetPanel(type = "tabs",optList1,optList2,optList3,optList4,optList5,optList6)
}
} else {
return(NULL)
}
}
})
### Interactive key summary table control panel:
output$outputUI_table_summary_key <- renderUI({
keyTable <- eRec_table_key()
tempDeltaLabel <- names(keyTable)[grepl("Delta",names(keyTable))]
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
tempList <- list(selectInput("keyTable_input_sigma",paste0(key_lab_sigma,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_sigma]))))),
selectInput("keyTable_input_se",paste0(key_lab_se,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_se]))))))
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
tempList <- list(selectInput("keyTable_input_probref",paste0(key_lab_probref,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_probref]))))))
}
return(list(selectInput("keyTable_input_graph",paste0(key_lab_graph,":"),c(key_lab_table_all,unique(as.character(keyTable[,key_lab_graph])))),
selectInput("keyTable_input_ntreat",paste0(key_lab_ntreat,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_ntreat]))))),
selectInput("keyTable_input_ncontrol",paste0(key_lab_ncontrol,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_ncontrol]))))),
tempList,
selectInput("keyTable_input_delta",paste0(tempDeltaLabel,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,tempDeltaLabel]))))),
selectInput("keyTable_input_go",paste0(key_lab_go,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_go]))))),
selectInput("keyTable_input_discuss",paste0(key_lab_discuss,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_discuss]))))),
selectInput("keyTable_input_stop",paste0(key_lab_stop,":"),c(key_lab_table_all,sort(unique(as.numeric(keyTable[,key_lab_stop]))))))
)
})
#################################
#################################
###### Output objects: ######
#################################
#################################
#################
# TEXT objects: #
#################
output$text_2dec_c1_text <- renderText({
eRec_text_decCrit1()
})
output$text_2dec_c2_text <- renderText({
eRec_text_decCrit2()
})
### For some reason SHINY doesn't like to access the same render object twice so have to re-name if referencing more than once:
output$text_1dec_c1_text <- renderText({
eRec_text_decCrit1()
})
output$text_1dec_c2_text <- renderText({
eRec_text_decCrit2()
})
output$text_warning_prec <- renderText({
eRec_text_warning()
})
###################
# FIGURE objects: #
###################
output$plot_OC_2dec <- renderPlot({
warn <- determine_minimum_prec()
if(warn & study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
return(NULL)
} else {
return(eRec_plot_2_0()$outPlot)
}
})
output$plot_OC_1dec_C1 <- renderPlot({
eRec_plot_1_1()$outPlot
})
output$plot_OC_1dec_C2 <- renderPlot({
eRec_plot_1_2()$outPlot
})
##################
# TABLE objects: #
##################
output$table_summary_options <- renderTable({
sumTable <- eRec_table_options()
head(sumTable,n=nrow(sumTable))
})
output$table_summary_key <- renderTable({
keyTable <- eRec_table_key()
tempDeltaLabel <- names(keyTable)[grepl("Delta",names(keyTable))]
# Limit printed key summary table based on user-options:
keyTable <- key_table_utility(keyTable,input$keyTable_input_graph,key_lab_graph)
keyTable <- key_table_utility(keyTable,input$keyTable_input_ntreat,key_lab_ntreat)
keyTable <- key_table_utility(keyTable,input$keyTable_input_ncontrol,key_lab_ncontrol)
keyTable <- key_table_utility(keyTable,input$keyTable_input_probref,key_lab_probref)
keyTable <- key_table_utility(keyTable,input$keyTable_input_sigma,key_lab_sigma)
keyTable <- key_table_utility(keyTable,input$keyTable_input_se,key_lab_se)
keyTable <- key_table_utility(keyTable,input$keyTable_input_delta,tempDeltaLabel)
keyTable <- key_table_utility(keyTable,input$keyTable_input_go,key_lab_go)
keyTable <- key_table_utility(keyTable,input$keyTable_input_discuss,key_lab_discuss)
keyTable <- key_table_utility(keyTable,input$keyTable_input_stop,key_lab_stop)
head(keyTable,n=nrow(keyTable))
})
#####################
# DOWNLOAD objects: #
#####################
### Main OC downloads:
output$download_data_main <- downloadHandler(
filename="Data_main.csv",
content = function(file) {
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
tempPlotData <- eRec_data_normal_plot()$data_2_0
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
tempPlotData <- eRec_data_binomial_plot()$data_2_0
}
write.csv(tempPlotData,file,row.names=F,quote=T)
}
)
output$download_data_c1 <- downloadHandler(
filename="Data_C1.csv",
content = function(file) {
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
tempPlotData <- eRec_data_normal_plot()$data_1_1
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
tempPlotData <- eRec_data_binomial_plot()$data_1_1
}
write.csv(tempPlotData,file,row.names=F,quote=T)
}
)
output$download_data_c2 <- downloadHandler(
filename="Data_C2.csv",
content = function(file) {
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
tempPlotData <- eRec_data_normal_plot()$data_1_2
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
tempPlotData <- eRec_data_binomial_plot()$data_1_2
}
write.csv(tempPlotData,file,row.names=F,quote=T)
}
)
### Summary tables:
output$download_table_summary_key <- downloadHandler(
filename="Summary_Table_Key points.csv",
content = function(file) {
write.csv(eRec_table_key(),file,row.names=F,quote=T)
}
)
output$download_table_summary_options <- downloadHandler(
filename="Summary_Table_Options.csv",
content = function(file) {
write.csv(eRec_table_options(),file,row.names=F,quote=T)
}
)
#########################################
#########################################
###### Event Reactive Objects: ######
#########################################
#########################################
###########
# Figures #
###########
eRec_plot_2_0 <- reactive({
ocPlot <- create_OC_Plot(2,0)
outPlot <- create_OC_dec_Text(ocPlot,2)
return(list(outPlot=outPlot))
})
eRec_plot_1_1 <- reactive({
ocPlot <- create_OC_Plot(1,1)
outPlot <- create_OC_dec_Text(ocPlot,1,1)
return(list(outPlot=outPlot))
})
eRec_plot_1_2 <- reactive({
ocPlot <- create_OC_Plot(1,2)
outPlot <- create_OC_dec_Text(ocPlot,1,2)
return(list(outPlot=outPlot))
})
############
# DATASETS #
############
### Conventional OC, normal outcomes:
eRec_data_normal_plot <- reactive({
if(decision_nCriteria_val()==2){
data_2_0 <- recD_normal_2_0()
data_1_1 <- recD_normal_1_1()
data_1_2 <- recD_normal_1_2()
return(list(data_2_0=data_2_0,data_1_1=data_1_1,data_1_2=data_1_2))
} else if(decision_nCriteria_val()==1){
data_1_1 <- recD_normal_1_1()
return(list(data_1_1=data_1_1))
}
})
### Conventional OC, binomial outcomes:
eRec_data_binomial_plot <- reactive({
if(decision_nCriteria_val()==2){
data_2_0 <- recD_binomial_2_0()
data_1_1 <- recD_binomial_1_1()
data_1_2 <- recD_binomial_1_2()
return(list(data_2_0=data_2_0,data_1_1=data_1_1,data_1_2=data_1_2))
} else if(decision_nCriteria_val()==1){
data_1_1 <- recD_binomial_1_1()
return(list(data_1_1=data_1_1))
}
})
##########
# TABLES #
##########
eRec_table_options <- reactive({
return(create_summary_options_table())
})
eRec_table_key <- reactive({
return(create_summary_key_table())
})
########
# TEXT #
########
### Decision criteria text:
eRec_text_decCrit1 <- reactive({
return(create_decision_criteria_text("C1",decision_direction_val(),decision_c1_tv_val(),decision_c1_sig_val(),study_comparison_val(),study_comparison_type_val()))
})
eRec_text_decCrit2 <- reactive({
return(create_decision_criteria_text("C2",decision_direction_val(),decision_c2_tv_val(),decision_c2_sig_val(),study_comparison_val(),study_comparison_type_val()))
})
### Warning (precision) text:
eRec_text_warning <- reactive({
warn <- determine_minimum_prec()
if(warn & study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
return(HTML(paste0("WARNING: Given decision criteria and precision, C2 criteria has become redundant<br/>",
"<br/>'OC Curves' tab should be used with caution<br/>")))
} else if(warn & study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
return(HTML(paste0("WARNING: Given decision criteria and precision, C2 criteria has become redundant<br/>",
"<br/>'OC Curves' tab has not been generated - simulation should be used instead<br/>")))
} else {
return(NULL)
}
})
###################################
###################################
###### Reactive datasts: ######
###################################
###################################
### NOTE: For whatever reason can't nest these reactive commands inside an event reactive without it re-calculating regardless of no changes
### Conventional OC, normal outcomes:
recD_normal_2_0 <- reactive({
tempPrec <- create_prec_table()
tempDF <- getDFinfo()
return(normalMeansPlotData(tempPrec,tempDF,2,0))
})
recD_normal_1_1 <- reactive({
tempPrec <- create_prec_table()
tempDF <- getDFinfo()
return(normalMeansPlotData(tempPrec,tempDF,1,1))
})
recD_normal_1_2 <- reactive({
tempPrec <- create_prec_table()
tempDF <- getDFinfo()
return(normalMeansPlotData(tempPrec,tempDF,1,2))
})
### Conventional OC, binomial outcomes:
recD_binomial_2_0 <- reactive({
tempPrec <- create_prec_table()
return(binomialMeansPlotData(tempPrec,2,0))
})
recD_binomial_1_1 <- reactive({
tempPrec <- create_prec_table()
return(binomialMeansPlotData(tempPrec,1,1))
})
recD_binomial_1_2 <- reactive({
tempPrec <- create_prec_table()
return(binomialMeansPlotData(tempPrec,1,2))
})
###############################################
###############################################
###### Functions for output objects: ######
###############################################
###############################################
create_OC_Plot <- function(nDec=NULL,tvInfo=NULL){
if(study_ocType_val()==label_study_conv){
### Conventional design:
return(create_conv_plot(nDec,tvInfo))
} else {
### Interim analysis:
return(NULL)
}
}
create_conv_plot <- function(nDec=NULL,tvInfo=NULL){
### Generate plot data:
### TESTING - it seems to be something to do with this function that is causing headaches moving from 1 to 2 or vice versus
# decision criteria. Presumably something to do with the nature of being a function, but not sure
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
tempPlotData <- eRec_data_normal_plot()[[paste0("data_",nDec,"_",tvInfo)]]
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
tempPlotData <- eRec_data_binomial_plot()[[paste0("data_",nDec,"_",tvInfo)]]
}
### Format line lines for legend:
tempPlotData$variable <- as.character(tempPlotData$variable)
if(nDec==2){
tempPlotData[tempPlotData$variable==label_decision_2_both,"variable"] <- advanced_legend_label_dec_2_both_val()
tempPlotData[tempPlotData$variable==label_decision_2_one,"variable"] <- advanced_legend_label_dec_2_one_val()
tempPlotData[tempPlotData$variable==label_decision_2_none,"variable"] <- advanced_legend_label_dec_2_none_val()
if(length(unique(c(advanced_legend_label_dec_2_both_val(),advanced_legend_label_dec_2_one_val(),advanced_legend_label_dec_2_none_val())))!=3){
validate(need(NULL,paste0("Can't have the same label twice for plotting - see two decision criteria plot labels [Advanced Tab/Legend]")))
}
tempPlotData$variable <- factor(tempPlotData$variable,levels=c(advanced_legend_label_dec_2_both_val(),advanced_legend_label_dec_2_one_val(),advanced_legend_label_dec_2_none_val()))
} else {
tempPlotData[tempPlotData$variable==label_decision_1_one,"variable"] <- advanced_legend_label_dec_1_one_val()
tempPlotData[tempPlotData$variable==label_decision_1_none,"variable"] <- advanced_legend_label_dec_1_none_val()
if(length(unique(c(advanced_legend_label_dec_1_one_val(),advanced_legend_label_dec_1_none_val())))!=2){
validate(need(NULL,paste0("Can't have the same label twice for plotting - see one decision criteria plot labels [Advanced Tab/Legend]")))
}
tempPlotData$variable <- factor(tempPlotData$variable,levels=c(advanced_legend_label_dec_1_one_val(),advanced_legend_label_dec_1_none_val()))
}
### Plot options (curves to plot):
lcolours <- c("green","orange","red")[as.numeric(advanced_plot_curves_val())]
if(nDec==2){
in_tv <- decision_c2_tv_val()
selection <- c(advanced_legend_label_dec_2_both_val(),advanced_legend_label_dec_2_one_val(),advanced_legend_label_dec_2_none_val())[as.numeric(advanced_plot_curves_val())]
tempPlotData <- tempPlotData[tempPlotData$variable %in% selection,]
} else {
in_tv <- getTVinfo(tvInfo)$tv
selection <- c(advanced_legend_label_dec_1_one_val(),advanced_legend_label_dec_1_none_val())[c("1" %in% advanced_plot_curves_val(),"3" %in% advanced_plot_curves_val())]
tempPlotData <- tempPlotData[tempPlotData$variable %in% selection,]
lcolours <- lcolours[lcolours %in% c("green","red")]
if(length(lcolours)==0){
lcolours <- c("green","red")
}
}
### Plot options (style of curves):
multDec <- create_plot_options_curveStyle()
### Create plot:
tempPlot <- createPlot(tempPlotData,in_tv,
c(plot_title_val(),advanced_xaxis_title_val(),advanced_yaxis_title_val(),advanced_legend_title_val()),
c(plot_xlow_val(),plot_xupp_val(),advanced_xaxis_break_val()),
c(advanced_yaxis_break_val(),advanced_yaxis_low_val(),advanced_yaxis_upp_val()),
lcolours,create_vert_lines_info(),create_horz_lines_info(),
multDec[[1]],multDec[[2]],multDec[[3]],
c(advanced_plot_size_val()))
return(tempPlot)
}
create_prec_table <- function(){
outTable <- NULL
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
outTable <- create_normal_prec_table()
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
outTable <- create_binomial_prec_table()
}
return(outTable)
}
create_normal_prec_table <- function(){
seTable <- data.frame(N1=NULL,N2=NULL,Sigma=NULL,SE=NULL,stringsAsFactors=F)
tempSE <- NULL
if(design_precision_val()==2){
for(i in 1:design_se_n_val()){
if(study_comparison_val()==label_study_2Normal){
tempSE <- normal2MeansSE(design_precision_val(),NULL,NULL,NULL,get(paste0("design_se_",i,"_val"))())
} else if(study_comparison_val()==label_study_1Normal){
tempSE <- normal1MeansSE(design_precision_val(),NULL,NULL,get(paste0("design_se_",i,"_val"))())
}
seTable <- rbind(seTable,data.frame(N1=NA,N2=NA,Sigma=NA,SE=tempSE,stringsAsFactors=F))
}
} else {
for(i in 1:design_n1_n_val()){
for(j in 1:design_sigma_n_val()){
if(study_comparison_val()==label_study_1Normal){
tempSE <- normal1MeansSE(design_precision_val(),get(paste0("design_n1_",i,"_val"))(),get(paste0("design_sigma_",j,"_val"))(),NULL)
seTable <- rbind(seTable,data.frame(N1=get(paste0("design_n1_",i,"_val"))(),N2=NA,Sigma=get(paste0("design_sigma_",j,"_val"))(),SE=tempSE,stringsAsFactors=F))
} else {
if(study_studyDesign_val()==label_study_Parallel && !design_equalN_val()){
for(k in 1:design_n2_n_val()){
tempSE <- normal2MeansSE(design_precision_val(),get(paste0("design_n1_",i,"_val"))(),get(paste0("design_n2_",k,"_val"))(),get(paste0("design_sigma_",j,"_val"))(),NULL)
seTable <- rbind(seTable,data.frame(N1=get(paste0("design_n1_",i,"_val"))(),N2=get(paste0("design_n2_",k,"_val"))(),Sigma=get(paste0("design_sigma_",j,"_val"))(),SE=tempSE,stringsAsFactors=F))
}
} else {
tempSE <- normal2MeansSE(design_precision_val(),get(paste0("design_n1_",i,"_val"))(),get(paste0("design_n1_",i,"_val"))(),get(paste0("design_sigma_",j,"_val"))(),NULL)
seTable <- rbind(seTable,data.frame(N1=get(paste0("design_n1_",i,"_val"))(),N2=get(paste0("design_n1_",i,"_val"))(),Sigma=get(paste0("design_sigma_",j,"_val"))(),SE=tempSE,stringsAsFactors=F))
}
}
}
}
}
return(seTable)
}
create_binomial_prec_table <- function(){
precTable <- data.frame(N1=NULL,N2=NULL,ProbRef=NULL,stringsAsFactors=F)
if(design_precision_val()==3){
for(i in 1:design_n1_n_val()){
for(j in 1:design_probRef_n_val()){
if(study_studyDesign_val()==label_study_Parallel && !design_equalN_val()){
for(k in 1:design_n2_n_val()){
tempPrec <- binomialMeansPrec(study_studyDesign_val(),design_precision_val(),design_equalN_val(),get(paste0("design_n1_",i,"_val"))(),get(paste0("design_n2_",k,"_val"))(),get(paste0("design_probRef_",j,"_val_for"))())
precTable <- rbind(precTable,data.frame(N1=tempPrec[1],N2=tempPrec[2],ProbRef=tempPrec[3],stringsAsFactors=F))
}
} else {
tempPrec <- binomialMeansPrec(study_studyDesign_val(),design_precision_val(),design_equalN_val(),get(paste0("design_n1_",i,"_val"))(),NULL,get(paste0("design_probRef_",j,"_val_for"))())
precTable <- rbind(precTable,data.frame(N1=tempPrec[1],N2=tempPrec[2],ProbRef=tempPrec[3],stringsAsFactors=F))
}
}
}
if(study_comparison_val()==label_study_2Binomial){
precTable <- cbind(Outcomes=2,precTable)
} else if(study_comparison_val()==label_study_1Binomial){
precTable <- cbind(Outcomes=1,precTable)
}
} else {
validate(need(NULL,paste0("Need to select precision option [Design Tab]")))
}
return(precTable)
}
normalMeansPlotData <- function(precTable,tempDF,nDec,tvInfo=NULL){
withProgress(message="Generating data",detail="",value=0,{
if(nDec==2){
tv1 <- decision_c1_tv_val_for()
sig1 <- decision_c1_sig_val()
tv2 <- decision_c2_tv_val_for()
sig2 <- decision_c2_sig_val()
} else {
tvInfo <- getTVinfo_for(tvInfo)
tv1 <- tvInfo$tv
sig1 <- tvInfo$sig
tv2 <- NULL
sig2 <- NULL
}
outTable <- data.frame(N1=NULL,N2=NULL,Sigma=NULL,SE=NULL,delta=NULL,variable=NULL,value=NULL,stringsAsFactors=F)
for(i in 1:nrow(precTable)){
setProgress(0.10,detail=paste0("Starting curve set ",i," of ",nrow(precTable)))
tempTable <- normalMeansData(as.numeric(precTable[i,"SE"]),tempDF,nDec,decision_direction_val(),tv1,sig1,tv2,sig2,
plot_xlow_val_for(),plot_xupp_val_for(),advanced_plot_gap_val())
tempTable <- cbind(N1=precTable[i,"N1"],N2=precTable[i,"N2"],Sigma=precTable[i,"Sigma"],tempTable)
outTable <- rbind(outTable,tempTable)
}
setProgress(0.90,detail="Completed creating data")
#Format results:
outTable <- formatPlotData(outTable,"Normal",study_comparison_type_val(),design_log_val())
})
return(outTable)
}
binomialMeansPlotData <- function(precTable,nDec,tvInfo=NULL){
withProgress(message="Generating data",detail="",value=0,{
if(nDec==2){
tv1 <- decision_c1_tv_val_for()
sig1 <- decision_c1_sig_val()
tv2 <- decision_c2_tv_val_for()
sig2 <- decision_c2_sig_val()
} else {
tvInfo <- getTVinfo_for(tvInfo)
tv1 <- tvInfo$tv
sig1 <- tvInfo$sig
tv2 <- NULL
sig2 <- NULL
}
outTable <- data.frame(N1=NULL,N2=NULL,ProbRef=NULL,delta=NULL,variable=NULL,value=NULL,stringsAsFactors=F)
for(i in 1:nrow(precTable)){
setProgress(0.10,detail=paste0("Starting curve set ",i," of ",nrow(precTable)))
if(design_bin_method_val()==1){
### Use formula with normal approximation:
tempDF <- getDFinfo()
tempTable <- binomialMeansData(precTable[i,],tempDF,nDec,decision_direction_val(),tv1,sig1,tv2,sig2,
plot_xlow_val_for(),plot_xupp_val_for(),advanced_plot_gap_val())
} else if(design_bin_method_val()==2){
### Use simulation method:
validate(NULL,"WIP!")
tempTable <- binomial2MeansData_Sim(as.numeric(precTable[i,"N1"]),as.numeric(precTable[i,"N2"]),as.numeric(precTable[i,"ProbRef"]),
tempDF,nDec,decision_direction_val(),tv1,sig1,tv2,sig2,
plot_xlow_val_for(),plot_xupp_val_for(),advanced_plot_gap_val(),
advanced_plot_sim_val(),design_bin_test_val())
}
outTable <- rbind(outTable,tempTable)
}
setProgress(0.90,detail="Completed creating data")
#Format results:
outTable <- formatPlotData(outTable,"Binomial")
})
return(outTable)
}
create_summary_options_table <- reactive({
### Study options:
sumTable <- data.frame(VarName=c("study_comparison"),Value=c(study_comparison_val()),stringsAsFactors=F)
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
sumTable <- rbind(sumTable,data.frame(VarName=c("study_comparison_type"),Value=c(study_comparison_type_val()),stringsAsFactors=F))
}
sumTable <- rbind(sumTable,data.frame(VarName=c("study_ocType","study_studyDesign"),
Value=c(study_ocType_val(),study_studyDesign_val()),stringsAsFactors=F))
### Criteria options:
sumTable <- rbind(sumTable,data.frame(VarName=c("decision_nCriteria","decision_direction","decision_c1_tv","decision_c1_sig"),
Value=c(decision_nCriteria_val(),decision_direction_val(),
decision_c1_tv_val(),decision_c1_sig_val()),stringsAsFactors=F))
if(decision_nCriteria_val()==2){
sumTable <- rbind(sumTable,data.frame(VarName=c("decision_c2_tv","decision_c2_sig"),Value=c(decision_c2_tv_val(),decision_c2_sig_val()),stringsAsFactors=F))
}
### Design options:
sumTable <- rbind(sumTable,data.frame(VarName=c("design_precision"),Value=c(design_precision_val()),stringsAsFactors=F))
if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
sumTable <- rbind(sumTable,data.frame(VarName=c("design_bin_method"),Value=c(design_bin_method_val()),stringsAsFactors=F))
}
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && (study_comparison_type_val() %in% c(label_study_perc,label_study_ratio))){
sumTable <- rbind(sumTable,data.frame(VarName=c("design_log"),Value=c(design_log_val()),stringsAsFactors=F))
}
if(design_precision_val()==2){
sumTable <- create_summary_multiple_values(sumTable,"design_se_")
} else {
if(study_studyDesign_val()==label_study_Parallel){
sumTable <- rbind(sumTable,data.frame(VarName=c("design_equalN"),Value=c(design_equalN_val()),stringsAsFactors=F))
if(design_equalN_val()){
sumTable <- create_summary_multiple_values(sumTable,"design_n1_")
if(study_comparison_val()==label_study_2Normal){
sumTable <- create_summary_multiple_values(sumTable,"design_sigma_")
} else if(study_comparison_val()==label_study_2Binomial){
sumTable <- create_summary_multiple_values(sumTable,"design_probRef_")
}
} else {
sumTable <- create_summary_multiple_values(sumTable,"design_n1_")
sumTable <- create_summary_multiple_values(sumTable,"design_n2_")
if(study_comparison_val()==label_study_2Normal){
sumTable <- create_summary_multiple_values(sumTable,"design_sigma_")
} else if(study_comparison_val()==label_study_2Binomial){
sumTable <- create_summary_multiple_values(sumTable,"design_probRef_")
}
}
} else {
sumTable <- create_summary_multiple_values(sumTable,"design_n1_")
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
sumTable <- create_summary_multiple_values(sumTable,"design_sigma_")
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
sumTable <- create_summary_multiple_values(sumTable,"design_probRef_")
}
}
}
### Normal approximation - TESTING with simulation based methods for e.g. binomial will need this to be updated:
sumTable <- rbind(sumTable,data.frame(VarName=c("design_normApprox","design_df"),
Value=c(design_normApprox_val(),as.character(getDFinfo())),
stringsAsFactors=F))
### Output options:
sumTable <- rbind(sumTable,data.frame(VarName=c("plot_title","plot_userID","plot_xlow","plot_xupp"),
Value=c(plot_title_val(),plot_userID_val(),plot_xlow_val(),plot_xupp_val()),stringsAsFactors=F))
### Advanced options:
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_yaxis_title","advanced_yaxis_break",
"advanced_yaxis_low","advanced_yaxis_upp",
"advanced_xaxis_title","advanced_xaxis_break",
"advanced_legend_title"),
Value=c(advanced_yaxis_title_val(),advanced_yaxis_break_val(),
advanced_yaxis_low_val(),advanced_yaxis_upp_val(),
advanced_xaxis_title_val(),advanced_xaxis_break_val(),
advanced_legend_title_val()),stringsAsFactors=F))
if(decision_nCriteria_val()==2){
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_label_dec_2_both","advanced_legend_label_dec_2_one",
"advanced_legend_label_dec_2_none"),
Value=c(advanced_legend_label_dec_2_both_val(),advanced_legend_label_dec_2_one_val(),
advanced_legend_label_dec_2_none_val()),stringsAsFactors=F))
}
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_label_dec_1_one","advanced_legend_label_dec_1_none"),
Value=c(advanced_legend_label_dec_1_one_val(),advanced_legend_label_dec_1_none_val()),stringsAsFactors=F))
if(design_precision_val()==2){
if(as.numeric(design_se_n_val())>1){
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_title_se"),
Value=c(advanced_legend_title_se_val()),stringsAsFactors=F))
}
} else {
if(as.numeric(design_n1_n_val())>1){
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_title_n1"),
Value=c(advanced_legend_title_n1_val()),stringsAsFactors=F))
}
if(study_studyDesign_val()==label_study_Parallel && !design_equalN_val()){
if(!is.null(design_n2_n_val()) && as.numeric(design_n2_n_val())>1){
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_title_n2"),
Value=c(advanced_legend_title_n2_val()),stringsAsFactors=F))
}
}
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
if(as.numeric(design_sigma_n_val())>1){
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_title_sigma"),
Value=c(advanced_legend_title_sigma_val()),stringsAsFactors=F))
}
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
if(as.numeric(design_probRef_n_val())>1){
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_legend_title_probRef"),
Value=c(advanced_legend_title_probRef_val()),stringsAsFactors=F))
}
}
}
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_lines_vert_number"),Value=c(advanced_lines_vert_number_val()),stringsAsFactors=F))
if(advanced_lines_vert_number_val() != 0){
for(i in 1:advanced_lines_vert_number_val()){
sumTable <- rbind(sumTable,data.frame(VarName=c(paste0("advanced_lines_vert_pos",i),paste0("advanced_lines_vert_col",i)),
Value=c(get(paste0("advanced_lines_vert_pos",i,"_val"))(),
get(paste0("advanced_lines_vert_col",i,"_val"))()),stringsAsFactors=F))
}
}
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_lines_horz_number"),Value=c(advanced_lines_horz_number_val()),stringsAsFactors=F))
if(advanced_lines_horz_number_val() != 0){
for(i in 1:advanced_lines_horz_number_val()){
sumTable <- rbind(sumTable,data.frame(VarName=c(paste0("advanced_lines_horz_pos",i),paste0("advanced_lines_horz_col",i)),
Value=c(get(paste0("advanced_lines_horz_pos",i,"_val"))(),
get(paste0("advanced_lines_horz_col",i,"_val"))()),stringsAsFactors=F))
}
}
sumTable <- rbind(sumTable,data.frame(VarName=c("advanced_footnote_choice","advanced_plot_gap",
"advanced_plot_sim","advanced_plot_width",
"advanced_plot_height","advanced_plot_curves",
"advanced_plot_size","version"),
Value=c(advanced_footnote_choice_val(),advanced_plot_gap_val(),
advanced_plot_sim_val(),advanced_plot_width_val(),
advanced_plot_height_val(),paste(advanced_plot_curves_val(),collapse=","),
advanced_plot_size_val(),versionNumber),stringsAsFactors=F))
return(sumTable)
})
create_summary_key_table <- reactive({
if(study_ocType_val()==label_study_conv){
### Conventional design:
keyTable <- create_summary_key_table_conv()
} else {
### Interim analysis:
keyTable <- create_summary_key_table_interim()
}
return(keyTable)
})
create_summary_key_table_conv <- reactive({
### Set-up table:
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
keyTable <- data.frame(Graph=as.character(),N1=as.numeric(),N2=as.numeric(),Sigma=as.numeric(),SE=as.numeric(),Delta=as.numeric(),Prob_Go=as.numeric(),Prob_Discuss=as.numeric(),Prob_Stop=as.numeric(),stringsAsFactors=F)
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
keyTable <- data.frame(Graph=as.character(),N1=as.numeric(),N2=as.numeric(),ProbRef=as.numeric(),Delta=as.numeric(),Prob_Go=as.numeric(),Prob_Discuss=as.numeric(),Prob_Stop=as.numeric(),stringsAsFactors=F)
}
### Determine study characteristics to loop through:
tempPrec <- create_prec_table()
tempDF <- getDFinfo()
### Determine deltas to loop through:
delta <- c(0,decision_c1_tv_val_for())
#50% and 80% points (C1 criteria):
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
delta <- c(delta,normalMeansPowerPoint(decision_c1_tv_val_for(),decision_c1_sig_val(),decision_direction_val(),as.numeric(tempPrec$SE),tempDF,0.5))
delta <- c(delta,normalMeansPowerPoint(decision_c1_tv_val_for(),decision_c1_sig_val(),decision_direction_val(),as.numeric(tempPrec$SE),tempDF,0.8))
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
delta <- c(delta,binomialMeansPowerPoint_All(0.5,tempPrec,tempDF,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),alg_binomial_power_gap,alg_binomial_power_step))
delta <- c(delta,binomialMeansPowerPoint_All(0.8,tempPrec,tempDF,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),alg_binomial_power_gap,alg_binomial_power_step))
}
#Include lines of interest:
if(advanced_lines_vert_number_val() != 0){
for(i in 1:advanced_lines_vert_number_val()){
delta <- c(delta,formatInputConvert(get(paste0("advanced_lines_vert_pos",i,"_val"))()))
}
}
if(advanced_lines_horz_number_val() != 0){
for(i in 1:advanced_lines_horz_number_val()){
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
delta <- c(delta,normalMeansPowerPoint(decision_c1_tv_val_for(),decision_c1_sig_val(),decision_direction_val(),as.numeric(tempPrec$SE),tempDF,get(paste0("advanced_lines_horz_pos",i,"_val"))()/100))
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
delta <- c(delta,binomialMeansPowerPoint_All(get(paste0("advanced_lines_horz_pos",i,"_val"))()/100,tempPrec,tempDF,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),alg_binomial_power_gap,alg_binomial_power_step))
}
}
}
if(decision_nCriteria_val()==2){
### 2 decision criteria selected:
delta <- c(delta,decision_c2_tv_val_for())
#50% and 80% points (C2 criteria):
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
delta <- c(delta,normalMeansPowerPoint(decision_c2_tv_val_for(),decision_c2_sig_val(),decision_direction_val(),as.numeric(tempPrec$SE),tempDF,0.5))
delta <- c(delta,normalMeansPowerPoint(decision_c2_tv_val_for(),decision_c2_sig_val(),decision_direction_val(),as.numeric(tempPrec$SE),tempDF,0.8))
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
delta <- c(delta,binomialMeansPowerPoint_All(0.5,tempPrec,tempDF,decision_direction_val(),decision_c2_tv_val_for(),decision_c2_sig_val(),alg_binomial_power_gap,alg_binomial_power_step))
delta <- c(delta,binomialMeansPowerPoint_All(0.8,tempPrec,tempDF,decision_direction_val(),decision_c2_tv_val_for(),decision_c2_sig_val(),alg_binomial_power_gap,alg_binomial_power_step))
}
#Include lines of interest:
if(advanced_lines_horz_number_val() != 0){
for(i in 1:advanced_lines_horz_number_val()){
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
delta <- c(delta,normalMeansPowerPoint(decision_c2_tv_val_for(),decision_c2_sig_val(),decision_direction_val(),as.numeric(tempPrec$SE),tempDF,get(paste0("advanced_lines_horz_pos",i,"_val"))()/100))
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
delta <- c(delta,binomialMeansPowerPoint_All(get(paste0("advanced_lines_horz_pos",i,"_val"))()/100,tempPrec,tempDF,decision_direction_val(),decision_c2_tv_val_for(),decision_c2_sig_val(),alg_binomial_power_gap,alg_binomial_power_step))
}
}
}
}
### Loop through delta and determine probabilities of decisions:
delta <- sort(unique(delta))
for(i in 1:length(delta)){
#For each delta:
for(j in 1:nrow(tempPrec)){
#For each study characteristic:
if(decision_nCriteria_val()==2){
### Both decision criteria:
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
### C1 & C2:
keyTable <- create_summary_key_table_conv_normal(keyTable,tempPrec[j,],tempDF,2,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),
decision_c2_tv_val_for(),decision_c2_sig_val(),
delta[i],"OC Curves")
### Criteria C1:
keyTable <- create_summary_key_table_conv_normal(keyTable,tempPrec[j,],tempDF,1,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),NULL,NULL,
delta[i],"C1 Curve")
### Criteria C2:
keyTable <- create_summary_key_table_conv_normal(keyTable,tempPrec[j,],tempDF,1,decision_direction_val(),decision_c2_tv_val_for(),decision_c2_sig_val(),NULL,NULL,
delta[i],"C2 Curve")
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
### C1 & C2:
keyTable <- create_summary_key_table_conv_binomial(keyTable,tempPrec[j,],tempDF,2,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),
decision_c2_tv_val_for(),decision_c2_sig_val(),
delta[i],"OC Curves")
### Criteria C1:
keyTable <- create_summary_key_table_conv_binomial(keyTable,tempPrec[j,],tempDF,1,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),NULL,NULL,
delta[i],"C1 Curve")
### Criteria C2:
keyTable <- create_summary_key_table_conv_binomial(keyTable,tempPrec[j,],tempDF,1,decision_direction_val(),decision_c2_tv_val_for(),decision_c2_sig_val(),NULL,NULL,
delta[i],"C2 Curve")
}
} else if(decision_nCriteria_val()==1){
### Single criteria:
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
keyTable <- create_summary_key_table_conv_normal(keyTable,tempPrec[j,],tempDF,1,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),NULL,NULL,
delta[i],"OC Curves")
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
keyTable <- create_summary_key_table_conv_binomial(keyTable,tempPrec[j,],tempDF,1,decision_direction_val(),decision_c1_tv_val_for(),decision_c1_sig_val(),NULL,NULL,
delta[i],"OC Curves")
}
}
}
}
### Format table:
# Format delta (if applicable):
deltaAdd <- ""
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && study_comparison_type_val()==label_study_perc){
keyTable$Delta <- formatPercDiffNorm_Inv(keyTable$Delta,design_log_val())
deltaAdd <- "(%)"
} else if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && study_comparison_type_val()==label_study_ratio){
keyTable$Delta <- formatRatioNorm_Inv(keyTable$Delta,design_log_val())
deltaAdd <- "(Ratio)"
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
keyTable$Delta <- formatPercDiffBin_Inv(keyTable$Delta)
keyTable$ProbRef <- 100*keyTable$ProbRef
deltaAdd <- "(%)"
}
if(deltaAdd != ""){
names(keyTable)[which(names(keyTable)=="Delta")] <- paste("Delta",deltaAdd)
}
# Format probabilities of decisions:
keyTable$Prob_Go <- 100*keyTable$Prob_Go
names(keyTable)[which(names(keyTable)=="Prob_Go")] <- key_lab_go
keyTable$Prob_Discuss <- 100*keyTable$Prob_Discuss
names(keyTable)[which(names(keyTable)=="Prob_Discuss")] <- key_lab_discuss
keyTable$Prob_Stop <- 100*keyTable$Prob_Stop
names(keyTable)[which(names(keyTable)=="Prob_Stop")] <- key_lab_stop
# Format column names (if applicable):
names(keyTable)[which(names(keyTable)=="Graph")] <- key_lab_graph
names(keyTable)[which(names(keyTable)=="N1")] <- key_lab_ntreat
names(keyTable)[which(names(keyTable)=="N2")] <- key_lab_ncontrol
names(keyTable)[which(names(keyTable)=="Sigma")] <- key_lab_sigma
names(keyTable)[which(names(keyTable)=="SE")] <- key_lab_se
names(keyTable)[which(names(keyTable)=="ProbRef")] <- key_lab_probref
### Remove results (if applicable):
if(decision_nCriteria_val()==2){
warn <- determine_minimum_prec()
if(warn & study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
keyTable <- keyTable[keyTable$Graph != "OC Curves",]
}
}
### Return completed table:
return(keyTable)
})
###################################################################
###################################################################
###### Key functions for extracting generic information: ######
###################################################################
###################################################################
getTVinfo <- function(tvInfo){
if(tvInfo==1){
tvOut <- list(tvName="C1",tv=decision_c1_tv_val(),sig=decision_c1_sig_val())
} else if (tvInfo==2){
tvOut <- list(tvName="C2",tv=decision_c2_tv_val(),sig=decision_c2_sig_val())
} else {
stop("This is not a valid option for decision criteria")
}
return(tvOut)
}
getTVinfo_for <- function(tvInfo){
if(tvInfo==1){
tvOut <- list(tvName="C1",tv=decision_c1_tv_val_for(),sig=decision_c1_sig_val())
} else if (tvInfo==2){
tvOut <- list(tvName="C2",tv=decision_c2_tv_val_for(),sig=decision_c2_sig_val())
} else {
stop("This is not a valid option for decision criteria")
}
return(tvOut)
}
getDFinfo <- function(interim=FALSE){
if(interim){
return(normalMeansDF(design_interim_normApprox_val(),design_interim_df_val()))
} else {
return(normalMeansDF(design_normApprox_val(),design_df_val()))
}
}
#######################################################
#######################################################
###### Utility functions for output objects: ######
#######################################################
#######################################################
determine_minimum_prec <- function(){
### Determine 50% points to determine whether precision needs to be increased
warn <- FALSE
tempPrec <- create_prec_table()
tempDF <- getDFinfo()
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
tempComp <- "Normal"
} else if (study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
tempComp <- "Binomial"
}
warn <- determine_minimum_prec_sub(tempComp,tempPrec,tempDF,decision_direction_val(),
decision_c1_tv_val_for(),decision_c1_sig_val(),
decision_c2_tv_val_for(),decision_c2_sig_val())
return(warn)
}
create_OC_dec_Text <- function(plot,nCriteria,tvInfo=1){
if(advanced_footnote_choice_val()==1){
grid.newpage()
mainView <- viewport(layout=grid.layout(nrow=2,ncol=1,heights=unit(c(1,8),c("null","lines"))))
topView <- viewport(layout.pos.row=1,layout.pos.col=1,name="top1")
botView <- viewport(layout.pos.row=2,layout.pos.col=1,name="bottom1")
splot <- vpTree(mainView,vpList(topView,botView))
pushViewport(splot)
seekViewport("top1")
print(plot,vp="top1")
seekViewport("bottom1")
### OC type description:
comparisonText <- study_comparison_val()
if(study_comparison_val()==label_study_2Normal){
comparisonText <- paste0(unlist(strsplit(study_comparison_type_val()," "))[1]," ",tolower(comparisonText))
}
grid.text(paste0("OC Type: ",study_ocType_val()," (",comparisonText,")"),
x=0.01,y=0.75,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("left"))
if(design_normApprox_val()){
dfInfo <- ""
} else {
dfInfo <- paste0(", DF = ",getDFinfo())
}
### Design description:
precVec <- create_prec_table()
precVec <- precVec$SE
precVec <- paste(signif(as.numeric(precVec),3),collapse=",")
precPref <- ""
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal) && (study_comparison_type_val() %in% c(label_study_perc,label_study_ratio))){
if(design_log_val()==1){
precPref <- "log[e] scale: "
} else if(design_log_val()==2){
precPref <- "log10 scale: "
} else if (design_log_val()==3){
precPref <- "log[e] scale: "
}
}
if(design_precision_val()==2){
precInfo <- paste0("(",precPref,"SE = ",precVec,dfInfo,")")
} else {
n1Vec <- NULL
for(i in 1:design_n1_n_val()){
n1Vec <- c(n1Vec,get(paste0("design_n1_",i,"_val"))())
}
n1Vec <- paste(n1Vec,collapse=",")
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
sdVec <- NULL
for(i in 1:design_sigma_n_val()){
sdVec <- c(sdVec,get(paste0("design_sigma_",i,"_val"))())
}
sdVec <- paste(sdVec,collapse=",")
endVec <- paste0(", ",precPref,"SD = ",sdVec,", SE = ",precVec,dfInfo,")")
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
pRVec <- NULL
for(i in 1:design_probRef_n_val()){
pRVec <- c(pRVec,get(paste0("design_probRef_",i,"_val"))())
}
pRVec <- paste(as.numeric(pRVec),collapse=",")
endVec <- paste0(", Reference Percentage = ",pRVec,"%",dfInfo,")")
}
if(study_studyDesign_val() %in% c(label_study_CrossOver,label_study_Single)){
precInfo <- paste0("(N total = ",n1Vec,endVec)
} else {
if(design_equalN_val()){
precInfo <- paste0("(N per arm = ",n1Vec,endVec)
} else {
n2Vec <- NULL
for(i in 1:design_n2_n_val()){
n2Vec <- c(n2Vec,get(paste0("design_n2_",i,"_val"))())
}
n2Vec <- paste(n2Vec,collapse=",")
precInfo <- paste0("(N treatment = ",n1Vec,", N control = ",n2Vec,endVec)
}
}
}
grid.text(paste0("Design: ",study_studyDesign_val()," ",precInfo),
x=0.01,y=0.525,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("left"))
### Criteria description:
if(nCriteria==2){
grid.text(eRec_text_decCrit1(),
x=0.01,y=0.30,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("left"))
grid.text(eRec_text_decCrit2(),
x=0.01,y=0.10,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("left"))
} else {
tvData <- getTVinfo(tvInfo)
grid.text(get(paste0("eRec_text_decCrit",tvInfo))(),
x=0.01,y=0.30,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("left"))
}
if(study_ocType_val()==label_study_interim){
grid.text(eRec_text_intCrit1()$text,
x=0.01,y=0.10,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("left"))
}
### Plot description:
grid.text(paste0("Plot created: ",format(Sys.time(), "%d-%b-%Y %H:%M")),
x=0.99,y=0.75,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("right"))
### User ID:
grid.text(paste0("Created by: ",plot_userID_val()),
x=0.99,y=0.30,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("right"))
### Version Number:
grid.text(paste0("Version ",versionNumber),
x=0.99,y=0.10,gp=gpar(fontsize=footnote_font_size,col="Black"),just=c("right"))
} else {
return(plot)
}
}
create_vert_lines_info <- function(){
if(is.null(advanced_lines_vert_number_val())){
return(NULL)
} else if(advanced_lines_vert_number_val()!= 0){
outList <- list()
for(i in 1:advanced_lines_vert_number_val()){
outList[[i]] <- c(get(paste0("advanced_lines_vert_pos",i,"_val"))(),get(paste0("advanced_lines_vert_col",i,"_val"))())
}
return(outList)
} else {
return(NULL)
}
}
create_horz_lines_info <- function(){
if(is.null(advanced_lines_horz_number_val())){
return(NULL)
} else if(advanced_lines_horz_number_val()!= 0){
outList <- list()
for(i in 1:advanced_lines_horz_number_val()){
outList[[i]] <- c(get(paste0("advanced_lines_horz_pos",i,"_val"))(),get(paste0("advanced_lines_horz_col",i,"_val"))())
}
return(outList)
} else {
return(NULL)
}
}
create_summary_multiple_values <- function(dataset,name){
outData <- data.frame(VarName=c(paste0(name,"n")),Value=c(get(paste0(name,"n_val"))()),stringsAsFactors=F)
for(i in 1:get(paste0(name,"n_val"))()){
outData <- rbind(outData,data.frame(VarName=paste0(name,i),
Value=get(paste0(name,i,"_val"))(),stringsAsFactors=F))
}
outData <- rbind(dataset,outData)
return(outData)
}
create_plot_options_curveStyle <- function(){
noType <- c("variable","Nothing",FALSE)
multDec <- list()
if(design_precision_val()==2){
multDec[[1]] <- c("SE",advanced_legend_title_se_val(),TRUE)
multDec[[2]] <- noType
multDec[[3]] <- noType
} else {
n1Type <- c("N1",advanced_legend_title_n1_val(),TRUE)
n2Type <- c("N2",advanced_legend_title_n2_val(),TRUE)
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
sdType <- c("Sigma",advanced_legend_title_sigma_val(),TRUE)
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
sdType <- c("ProbRef",advanced_legend_title_probRef_val(),TRUE)
}
multDec <- list(n1Type,sdType,n2Type)
if(as.numeric(design_n1_n_val())==1){multDec[[1]] <- NULL}
if(study_comparison_val() %in% c(label_study_2Normal,label_study_1Normal)){
if(as.numeric(design_sigma_n_val())==1){multDec[[length(multDec)-1]] <- NULL}
} else if(study_comparison_val() %in% c(label_study_2Binomial,label_study_1Binomial)){
if(as.numeric(design_probRef_n_val())==1){multDec[[length(multDec)-1]] <- NULL}
}
if(study_studyDesign_val()!=label_study_Parallel || design_equalN_val() || as.numeric(design_n2_n_val())==1){
multDec[[length(multDec)]] <- NULL
}
if(length(multDec)<3){
for(i in (length(multDec)+1):3){
multDec[[i]] <- noType
}
}
}
return(multDec)
}
})
#End of big bad server script
|
37492b9602c8920dcbac7abb3db0735a04ea30bd
|
df02cb94ad5ac3ad922d46682b448da09a49bcdb
|
/R_teaching/code_data_in_III_R_courses/practice_datamining.R
|
bfd14db850a24d8674995b591081c3157f6f93c3
|
[] |
no_license
|
Liumingyuans/III_R
|
0ec01fd39e3797ba7dfb0fdf0472538d4e4b738e
|
fc4f227ea6c02e204f8d25f5ef12b80c749db80d
|
refs/heads/master
| 2020-12-24T20:14:37.836083
| 2016-05-07T06:36:46
| 2016-05-07T06:36:46
| 58,252,918
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,978
|
r
|
practice_datamining.R
|
######## Practice 2 ##########
library(arules)# for dataset "Adult" & functions
data(AdultUCI) # the "Census Income" Database
help(AdultUCI)
# dim(AdultUCI)
str(AdultUCI)
AdultUCI[1:3,] #head(AdultUCI, 3)
AdultUCI[["fnlwgt"]] <- NULL #其時就是移除該變數
#AdultUCI[["fnlwgt]] 其實就是 AdultUCI$fnlwgt <- NULL
#age 是定量變數, 須因子化
summary(AdultUCI$age)
AdultUCI$age <- ordered(cut(AdultUCI$age, c(15,25,45,65,100)),labels = c("Young", "Middle-aged", "Senior", "Old")) #min age is 17
AdultUCI[["hours-per-week"]] <- ordered(cut(AdultUCI[["hours-per-week"]], c(0,25,40,60,168)),labels = c("Part-time", "Full-time", "Over-time", "Workaholic"))
median(AdultUCI[["capital-gain"]][AdultUCI[["capital-gain"]]>0])
AdultUCI[["capital-gain"]]<- ordered(cut(AudltUCI[["capital-gain"]][AdultUCI[["capital-gain"]]>0]), Inf), labels=c("None", "Low", "High")) # the median is 7298
)
AudltUCI[["capital-loss"]]<- ordered(cut(AdultUCI[["capital-loss"]][AudltUCI[["capital-loss"]]>0]), Inf), labels=c("None", "Low", "High"))
summary(AdultUCI)
Adult <- as(AdultUCI, "transactions")
######## Practise 3 #########
library(DMwR)
data(algae)
str(algae)
help(algae)
help(outliers.ranking)
## Trying to obtain a reanking of the 200 samples
o <- outliers.ranking(algae[,-(1:3)])
o$rank.ouliers
o$rank.ouliers[1:5]
o$prob.ouliers
sort(o$prob.outliers)
sort(o$prob.outliers, decreasing=TRUE, index.return=TRUE) #Six is same as rank.outlies
########### Practice 4###### 沒抄完~~~~~~~~~~~
library(DMnR)
str(algae)
algae[manyNAs(algae),])
algae <- algae[-manyNAs(algae),]
library(rpart) # for function rpart
rt.a1 <-
prettyTree(rt.a1) # {DMnr}
printcp(rt.a1)
rt2.a1<- prune(rt.1,cp=0.08) #min, xerror+xstd=?+?=?, so rel error (tree?)=?<?, its cp is?
rt2.a1
prettyTree(rt2.a1)
#print(bodyfat_rpart$cptable)
#opt <- which.min(bodyfat_rpart$cptable[,"xerror])
|
6ca6a0f1380f656b94cee5fc29fb9ccabccf3ea3
|
c2b4c38fe19acc9a0a83436c260b9bdacac39332
|
/CourseSessions/Sessions67/tools/ui.R
|
d88e2559f841efa70ffeeb75a8310e0dcc2915c8
|
[
"MIT"
] |
permissive
|
konstantinosStouras/INSEADjan2014
|
5049245670a7b5b3d51778c94c06a1b617542fab
|
b65313be73753d7236f51239ba2126f4a1dc3857
|
refs/heads/master
| 2021-01-21T19:40:18.611191
| 2014-01-15T15:01:27
| 2014-01-15T15:01:27
| 15,969,639
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,017
|
r
|
ui.R
|
shinyUI(pageWithSidebar(
##########################################
# STEP 1: The name of the application
headerPanel("Classification Analysis Web App"),
##########################################
# STEP 2: The left menu, which reads the data as
# well as all the inputs exactly like the inputs in RunStudy.R
# STEP 2.1: read the data
sidebarPanel(
HTML("<center><h3>Data Upload </h3>
<strong> Note: File must contain data matrix named ProjectData</strong>
</center>"),
fileInput('datafile_name', 'Choose File (R data)'),
#tags$hr(),
HTML("<hr>"),
HTML("<center><strong> Note:Please go to the Parameters Tab when you change the parameters below </strong>
</center>"),
HTML("<hr>"),
###########################################################
# STEP 2.2: read the INPUTS.
# THESE ARE THE *SAME* INPUT PARAMETERS AS IN THE RunStudy.R
textInput("dependent_variable","Enter the name of the dependent variable","Visit"),
textInput("attributes_used","Enter the attributes to use as independent variables (consecutive e.g 1:5 or separate e.g 8,11) separated with comma","1:2,4"),
numericInput("estimation_data_percent", "Enter % of data to use for estimation", 80),
numericInput("validation1_data_percent", "Enter % of data to use for first validation set:", 20),
numericInput("Probability_Threshold", "Enter the Probability Threshold for classfication (default is 50):", 50),
selectInput("classification_method", "Select the classification method to use:",
choices = c("WORK IN PROGRESS", "WORK IN PROGRESS", "WORK IN PROGRESS")),
###########################################################
# STEP 2.3: buttons to download the new report and new slides
HTML("<hr>"),
HTML("<h4>Download the new report </h4>"),
downloadButton('report', label = "Download"),
HTML("<hr>"),
HTML("<h4>Download the new slides </h4>"),
downloadButton('slide', label = "Download"),
HTML("<hr>")
),
###########################################################
# STEP 3: The output tabs (these follow more or less the
# order of the Rchunks in the report and slides)
mainPanel(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
# Now these are the taps one by one.
# NOTE: each tab has a name that appears in the web app, as well as a
# "variable" which has exactly the same name as the variables in the
# output$ part of code in the server.R file
# (e.g. tableOutput('parameters') corresponds to output$parameters in server.r)
tabsetPanel(
tabPanel("Parameters", tableOutput('parameters')),
tabPanel("Summary", tableOutput('summary')),
tabPanel("Euclidean Pairwise Distances",tableOutput('euclidean_pairwise')),
tabPanel("Manhattan Pairwise Distance",tableOutput('manhattan_pairwise')),
tabPanel("Histograms",
numericInput("var_chosen", "Select the attribute to see the Histogram for:", 1),
plotOutput('histograms')),
tabPanel("Pairwise Distances Histogram", plotOutput("dist_histogram")),
tabPanel("The Dendrogram", plotOutput("dendrogram")),
tabPanel("The Dendrogram Heights Plot", plotOutput("dendrogram_heights")),
tabPanel("Hclust Membership",
numericInput("hclust_obs_chosen", "Select the observation to see the Hclust cluster membership for:", 1),
tableOutput('hclust_membership')),
tabPanel("Kmeans Membership",
numericInput("kmeans_obs_chosen", "Select the observation to see the Kmeans cluster membership for:", 1),
tableOutput('kmeans_membership')),
tabPanel("Kmeans Profiling", tableOutput('kmeans_profiling')),
tabPanel("The Snake Plot", plotOutput("snake_plot"))
)
)
))
|
69af2fe820c40ff69b7460ff6f0dbdf7f9d902bd
|
37f1f9432d01b363a153ca881843826744e1ef3f
|
/man/SplitGraphs.Rd
|
62e526f6d5b2f13dfcb27e7291edf0d06da06c2d
|
[] |
no_license
|
sagade/inf460
|
d50fa72d79e7f2fb075c5fe285290a7bce0040ff
|
009f21a041f32ce96f15bb0c804606756a3eed7f
|
refs/heads/master
| 2023-01-13T22:51:13.875007
| 2020-11-16T18:35:49
| 2020-11-16T18:35:49
| 310,693,208
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 568
|
rd
|
SplitGraphs.Rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/graphics.R
\name{SplitGraphs}
\alias{SplitGraphs}
\title{SplitGraphs
Splits list of ggplot2 plots into several grids od define size and plots them}
\usage{
SplitGraphs(plot.list, nrow = 3, ncol = 2, ...)
}
\arguments{
\item{plot.list}{the list with gglot2 graphs}
\item{nrow,}{the number of rows for one grid, default to 3}
\item{ncol,}{the number of columns of one grid, default to 2}
\item{...}{additional arguments to grid.arrange}
}
\description{
}
\author{
Stephan Gade
}
|
eb44a3fd6f93946cf313b02a4281d8b038d8f9c1
|
7dc9f4bf9a154a45b034733f4445e1b2cf79e352
|
/Week5_DecisionTree_Music_Ashley.R
|
40f39fca668df558c41be27c0118fa578f60d1ba
|
[] |
no_license
|
aggiemusic/R
|
c67cb89e489bc21a48495f8173e4d9425a54c3bc
|
d40b46f82122b63e8f70ba227a0a6c1638da6720
|
refs/heads/master
| 2022-12-17T11:28:25.789005
| 2020-09-13T16:39:34
| 2020-09-13T16:39:34
| 294,177,054
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,575
|
r
|
Week5_DecisionTree_Music_Ashley.R
|
#############################################
# #
# Name: Ashley Music #
# Date: 07/28/2020 #
# Subject: Predict Botson Housing #
# Class: BDAT 625 #
# File Name: #
# Week5_DecisionTree_HW_Music_Ashley #
# #
#############################################
setwd("C:/Users/aggie/Desktop/Data Mining")
rm(list = ls())
library(readr)
FlightDelays <- read_csv("C:/Users/aggie/Desktop/Data Mining/FlightDelays.csv")
View(FlightDelays)
FlightDelays <- as.data.frame(FlightDelays)
# Transform variable day of week (DAY_WEEK) info a categorical variable.
FlightDelays$DAY_WEEK <- factor(FlightDelays$DAY_WEEK)
# Bin the scheduled departure time into eight bins (in R use function cut()).
options(scipen=999)
FlightDelays$CRS_DEP_TIME <- cut(FlightDelays$CRS_DEP_TIME, 8, include.lowest = FALSE, dig.lab = 8 )
# Use these and all other columns as predictors (excluding DAY_OF_MONTH).
#Also excluding actual departure time, FL Num and Tail Num.
selected.var <- c(1:2, 4:6,8:10,13)
colnames(FlightDelays)
# Partition the data into training and validation sets.
train.index <- sample(c(1:dim(FlightDelays)[1]), dim(FlightDelays)[1]*0.6)
train.df <- FlightDelays[train.index, selected.var]
valid.df <- FlightDelays[-train.index, selected.var]
dim(train.df)
dim(valid.df)
# Fit a classification tree to the flight delay variable using all the relevant predictors.
install.packages('rpart')
install.packages('adabag')
library(rpart)
library(adabag)
library(caret)
library(ggplot2)
install.packages('rpart.plot')
library(rpart.plot)
default.ct <- rpart(`Flight Status` ~ . , data = train.df, method = "class")
prp(default.ct, type = 1, extra = 1, under = TRUE, split.font = 1, varlen = -10)
# Use a pruned tree with maximum of 8 levels, setting cp = 0.001. Express the resulting tree as a set of rules.
library(caret)
#I have tried prune three different ways. Appears to work best with prune
FlightPruned <- rpart(`Flight Status` ~ ., data = train.df, method = "class", maxdepth = 8)
printcp(FlightPruned)
pruned.ct <- prune(FlightPruned, cp = 0.001)
prp(pruned.ct, type = 1,
box.col=ifelse(pruned.ct$frame$var == "<leaf>", 'gray', 'white'))
#Decision Rules:
summary(pruned.ct)
print(pruned.ct)
# Tell me: If you needed to fly between DCA and EWR on a Monday at 7:00 AM, would you be able to use this tree? What other information would you need? Is it available in practice? What information is redundant?
# No, I would not be able to use this tree. I would need to know the date the flight was departing in order to use this tree.
# Fit the same tree as you did initially, this time excluding the Weather predictor. Display both the pruned and unpruned tree. You will find that the pruned tree contains a single terminal node.
#Full Tree
train.df.2 <- train.df[ , -7]
default.ct.2 <- rpart(`Flight Status` ~ . , data = train.df.2, method = "class")
prp(default.ct.2, type = 1, extra = 1, under = TRUE, split.font = 1, varlen = -10)
#Pruned Tree
set.seed(1)
default.ct.2.p <- rpart(`Flight Status` ~ ., data = train.df.2, method = "class", maxdepth = 8)
printcp(default.ct.2.p)
pruned.noweather <- prune(default.ct.2.p , cp = 0.001 )
prp(pruned.noweather, type = 1,
box.col=ifelse(pruned.ct$frame$var == "<leaf>", 'gray', 'white'))
|
a9b2ee0f4ae1d01512d945e5281a0b4e379ea507
|
bccaf9ca75d67fef6bec733e784c582149a32ed1
|
/tilit/R/ij.R
|
91c9af36503557cd0693a6a485d4cccc1425930a
|
[] |
no_license
|
brooksambrose/pack-dev
|
9cd89c134bcc80711d67db33c789d916ebcafac2
|
af1308111a36753bff9dc00aa3739ac88094f967
|
refs/heads/master
| 2023-05-10T17:22:37.820713
| 2023-05-01T18:42:08
| 2023-05-01T18:42:08
| 43,087,209
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 366
|
r
|
ij.R
|
#' List of row and column indices for accessing 2D square matrix upper triangle
#'
#' @param n square matrix or length of one of its dimensions
#'
#' @return
#' @export
#'
#' @examples
ij<-function(n) {
if(!is.vector(n)) {
if(length(dim(n))!=2) stop('Too many dimensions')
if(diff(dim(n))) stop('Not square')
n<-nrow(n)
}
mlist(combn(1:n,2))
}
|
effc2cab714d959c4ca7285dd1bc3c4117a777fd
|
c4e2f1eaf9ae10bb5e8998c7d731606a45624e8c
|
/scDD_analyses/scDD_analysis.R
|
c5e76f1870a22335361f9efb2ee8f064b43f949e
|
[] |
no_license
|
systemsgenomics/ETV6-RUNX1_scRNAseq_Manuscript_2020_Analysis
|
c0e7483950990b9c5bf16f7f28f4b9c6acbfb31b
|
eb08df603f52779ffc781e71461c9175f83f8f24
|
refs/heads/master
| 2021-05-26T02:49:44.847600
| 2020-11-24T20:52:20
| 2020-11-24T20:52:20
| 254,022,211
| 0
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 16,866
|
r
|
scDD_analysis.R
|
# scDD analysis with vst
#
# - HCA data: HSC + B lineage cells
# - ALL data: leukemic cells from ALL1, ALL3, ALL8, ALL9, ALL10, ALL10d15, ALL12 and ALL12d15
# - Nalm6 cell line: LUC and E/R induced
# - Use vst normalized data
# - Custom scDD installation devtools::install_github("juhaa/scDD")
# - adds jitter to counts of genes which cause numerical problems with mclust
#
# Load libraries, setup options
source("scDD_wrapper_scripts.R")
future::plan(strategy = 'multicore', workers = 2)
options(future.globals.maxSize = 10 * 1024 ^ 3, stringsAsFactors = F)
setwd("/research/groups/allseq/data/scRNAseq/results/ER_project/new_2019/scDD/vst")
# Set up HCA + ALL data
load("/research/groups/allseq/data/scRNAseq/results/ER_project/new_2019/data/HCA_ALL_combined.RData")
X <- t(X)
metadata$log_umi <- log10(colSums(X))
metadata$n_counts <- colSums(X)
metadata$celltype_leukemic <- metadata$celltype
metadata$celltype_leukemic[! metadata$batch %in% paste0("MantonBM", 1:8)] <- metadata$batch[! metadata$batch %in% paste0("MantonBM", 1:8)]
metadata$celltype_leukemic_noI <- metadata$celltype
metadata$celltype_leukemic_noI[metadata$batch %in% c("ALL10d15", "ALL12d15")] <- "I"
metadata$celltype_leukemic_noI_noCC <- metadata$celltype_leukemic_noI
metadata$celltype_leukemic_noI_noCC[metadata$phase != "G1"] <- "CC"
metadata$celltype_leukemic_noI_CC <- metadata$celltype_leukemic_noI
metadata$celltype_leukemic_noI_CC[metadata$phase == "G1"] <- "G1"
metadata$celltype2 <- metadata$celltype
metadata$celltype2[metadata$celltype == "leukemic"] <- paste0("leukemic_", metadata$batch[metadata$celltype == "leukemic"])
# Set up Nalm6 data
nalm <- data.table::fread("/research/groups/allseq/data/scRNAseq/results/juha_wrk/Nalm6_scanpy/data/raw/X.csv.gz", data.table = F)
colnames(nalm) <- readLines("/research/groups/allseq/data/scRNAseq/results/juha_wrk/Nalm6_scanpy/data/raw/var.txt")
nalm.anno <- read.csv("/research/groups/allseq/data/scRNAseq/results/juha_wrk/Nalm6_scanpy/data/obs.csv", stringsAsFactors = F, row.names = 1)
rownames(nalm) <- rownames(nalm.anno) <- gsub("-1", "", rownames(nalm.anno))
nalm <- t(nalm)
nalm.anno$log_umi <- log10(colSums(nalm))
# vst
set.seed(42)
HCA_ALL <- sctransform::vst(umi = X, cell_attr = metadata, batch_var = "batch", return_corrected_umi = T)
saveRDS(HCA_ALL, "vst_HCABlineage_ALL_log_counts_batch.rds")
write.csv(t(as.matrix(HCA_ALL$umi_corrected)), gzfile("vst_HCABlineage_ALL_log_counts_batch_UMIcorrected.csv.gz"))
#HCA_ALL <- readRDS("vst_HCABlineage_ALL_log_counts_batch.rds")
set.seed(42)
nalm.vst <- sctransform::vst(umi = nalm, cell_attr = nalm.anno, batch_var = "batch", return_corrected_umi = T)
saveRDS(nalm.vst, "vst_batch_Nalm6_log_counts.rds")
write.csv(t(as.matrix(nalm.vst$umi_corrected)), gzfile("vst_batch_Nalm6_log_counts_UMIcorrected.csv.gz"))
#nalm.vst <- readRDS("vst_batch_Nalm6_log_counts.rds")
# scDD runs
metadata$n_counts_vst <- Matrix::colSums(HCA_ALL$umi_corrected)
scDD_run(HCA_ALL$umi_corrected, metadata$celltype, grep("1_|2_", metadata$celltype, value = T), n_cores = 5, prefix = "HCA_Blineage_ALL_sct_batch_2_earlyLymphoid_vs_1_HSC", ref = "2_earlyLymphoid", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected, metadata$celltype, grep("2_|3_", metadata$celltype, value = T), n_cores = 5, prefix = "HCA_Blineage_ALL_sct_batch_3_proB_G2MS_vs_2_earlyLymphoid", ref = "3_proB_G2MS", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected, metadata$celltype, grep("3_|5_", metadata$celltype, value = T), n_cores = 20, prefix = "HCA_Blineage_ALL_sct_batch_5_preB_G2MS_vs_3_proB_G2MS", ref = "5_preB_G2MS", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected[, metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500], metadata$celltype[metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500], grep("4_|6_", metadata$celltype, value = T), n_cores = 10, prefix = "HCA_Blineage_ALL_sct_batch_6_preB_G1_vs_4_proB_G1_minncounts3000_maxncounts3500", ref = "6_preB_G1", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected, metadata$louvain, c("HCA.0", "HCA.4"), n_cores = 10, prefix = "HCA_Blineage_ALL_sct_batch_cluster0_vs_cluster4", ref = "HCA.4", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected[, metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500], metadata$celltype_leukemic_noI_noCC[metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500], c("leukemic", "4_proB_G1"), n_cores = 20, prefix = "HCA_Blineage_ALL_sct_batch_4_proB_G1_vs_leukemic_G1_noI_minncounts3000_maxncounts3500", ref = "leukemic", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected, metadata$celltype_leukemic_noI_CC, grep("leukemic|3_proB_G2MS", metadata$celltype_leukemic_noI_CC, value = T), n_cores = 20, prefix = "HCA_Blineage_ALL_sct_batch_3_proB_G2MS_vs_leukemic_noG1_noI", ref = "leukemic", reuse = F, min.size = 30)
scDD_run(HCA_ALL$umi_corrected[, metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500 & metadata$batch != "ALL12"],
metadata$celltype_leukemic_noI_noCC[metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500 & metadata$batch != "ALL12"],
c("leukemic", "4_proB_G1"),
n_cores = 10,
prefix = "HCA_Blineage_ALL_sct_batch_4_proB_G1_vs_leukemic_G1_noI_no_ALL12_minncounts3000_maxncounts3500",
ref = "leukemic",
reuse = F,
min.size = 30)
scDD_run(HCA_ALL$umi_corrected[, metadata$batch != "ALL12"],
metadata$celltype_leukemic_noI_CC[metadata$batch != "ALL12"],
c("leukemic", "3_proB_G2MS"),
n_cores = 10,
prefix = "HCA_Blineage_ALL_sct_batch_3_proB_G2MS_vs_leukemic_noG1_noI_noALL12",
ref = "leukemic",
reuse = F,
min.size = 30)
scDD_run(HCA_ALL$umi_corrected[, metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500 & metadata$phase == "G1"],
metadata$celltype2[metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500 & metadata$phase == "G1"],
c("leukemic_ALL12", "4_proB_G1"),
n_cores = 10,
prefix = "HCA_Blineage_ALL_sct_batch_4_proB_G1_vs_leukemic_ALL12_G1_minncounts3000_maxncounts3500",
ref = "leukemic_ALL12",
reuse = F,
min.size = 30)
scDD_run(HCA_ALL$umi_corrected[, metadata$phase != "G1"],
metadata$celltype2[metadata$phase != "G1"],
c("leukemic_ALL12", "3_proB_G2MS"),
n_cores = 10,
prefix = "HCA_Blineage_ALL_sct_batch_3_proB_G2MS_vs_leukemic_ALL12_noG1",
ref = "leukemic_ALL12",
reuse = F,
min.size = 30)
scDD_run(nalm.vst$umi_corrected, nalm.anno$batch, nalm.anno$batch, n_cores = 20, prefix = "Nalm6_vst_batch_LUC_vs_ER", ref = "ER", reuse = F, min.size = 30)
# Density plots of selected genes
data <- as.matrix(HCA_ALL$umi_corrected)
proB <- data[, (metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500 & metadata$celltype_leukemic_noI_noCC == "4_proB_G1") | metadata$celltype == "3_proB_G2MS"]
leukemic <- data[, metadata$celltype == "leukemic"]
df <- data.frame(log(t(cbind(proB, leukemic)) + 1),
celltype = factor(c(rep("proB", ncol(proB)), rep("leukemic", ncol(leukemic))), levels = c("leukemic", "proB")))
colnames(df) <- gsub("[.]", "-", colnames(df))
mdata <- metadata[rownames(df), ]
genes <- sort(c("TERF2", "INSR", "TGFB1", "HLA-DOB", "HLA-E", "LY6E", "ISG20", "IGLL1", "LAT2", "CYFIP2", "VPREB1"))
library(ggplot2)
pdf("proB_all_vs_leukemic_all_densityPlots.pdf", width = 5, height = 3)
for(i in genes) {
df.tmp <- data.frame(gexp = df[, i], celltype = df$celltype)
p <- ggplot(df.tmp, aes(x = gexp, fill = celltype, colour = celltype)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
df2 <- df[mdata$phase == "G1", ]
pdf("proB_G1_vs_leukemic_G1_densityPlots.pdf", width = 5, height = 3)
for(i in genes) {
df.tmp <- data.frame(gexp = df2[, i], celltype = df2$celltype)
p <- ggplot(df.tmp, aes(x = gexp, fill = celltype, colour = celltype)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
# Density plots of selected genes per sample
data <- as.matrix(HCA_ALL$umi_corrected)
proB <- data[, (metadata$n_counts_vst > 3000 & metadata$n_counts_vst < 3500 & metadata$celltype_leukemic_noI_noCC == "4_proB_G1") | metadata$celltype == "3_proB_G2MS"]
genes <- sort(c("TERF2", "INSR", "TGFB1", "HLA-DOB", "HLA-E", "LY6E", "ISG20", "IGLL1", "LAT2", "CYFIP2", "VPREB1"))
for(j in unique(metadata$batch[metadata$celltype == "leukemic"])) {
leukemic <- data[, metadata$celltype == "leukemic" & metadata$batch == j]
df <- data.frame(log(t(cbind(proB, leukemic)) + 1),
celltype = factor(c(rep("proB", ncol(proB)), rep("leukemic", ncol(leukemic))), levels = c("leukemic", "proB")))
colnames(df) <- gsub("[.]", "-", colnames(df))
mdata <- metadata[rownames(df), ]
pdf(paste0("proB_all_vs_leukemic_", j, "_all_densityPlots.pdf"), width = 5, height = 3)
for(i in genes) {
df.tmp <- data.frame(gexp = df[, i], celltype = df$celltype)
p <- ggplot(df.tmp, aes(x = gexp, fill = celltype, colour = celltype)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
}
for(j in unique(metadata$batch[metadata$celltype == "leukemic"])) {
leukemic <- data[, metadata$celltype == "leukemic" & metadata$batch == j]
df <- data.frame(log(t(cbind(proB, leukemic)) + 1),
celltype = factor(c(rep("proB", ncol(proB)), rep("leukemic", ncol(leukemic))), levels = c("leukemic", "proB")))
colnames(df) <- gsub("[.]", "-", colnames(df))
mdata <- metadata[rownames(df), ]
df <- df[mdata$phase == "G1", ]
pdf(paste0("proB_G1_vs_leukemic_", j, "_G1_densityPlots.pdf"), width = 5, height = 3)
for(i in genes) {
df.tmp <- data.frame(gexp = df[, i], celltype = df$celltype)
p <- ggplot(df.tmp, aes(x = gexp, fill = celltype, colour = celltype)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
}
for(j in unique(metadata$batch[metadata$celltype == "leukemic"])) {
leukemic <- data[, metadata$celltype == "leukemic" & metadata$batch == j]
df <- data.frame(log(t(cbind(proB, leukemic)) + 1),
celltype = factor(c(rep("proB", ncol(proB)), rep("leukemic", ncol(leukemic))), levels = c("leukemic", "proB")))
colnames(df) <- gsub("[.]", "-", colnames(df))
mdata <- metadata[rownames(df), ]
df <- df[mdata$phase != "G1", ]
pdf(paste0("proB_G2MS_vs_leukemic_", j, "_G2MS_densityPlots.pdf"), width = 5, height = 3)
for(i in genes) {
df.tmp <- data.frame(gexp = df[, i], celltype = df$celltype)
p <- ggplot(df.tmp, aes(x = gexp, fill = celltype, colour = celltype)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
}
# Density plots for selected genes from diag vs d15 results
genes_both <- sort(c("RUNX1", "TCF3", "LEF1", "SOX4", "SMAD1", "JUNB"))
genes_ALL12 <- sort(c("ERG", "IKZF1", "ARID5A", "JUN", "ETS2", "POU4F1", "TCF4", "ELK3"))
genes_ALL10 <- sort(c("IRF8", "CEBPD", "POU2F2", "KLF2", "KLF6", "AFF3", "SPIB", "MS4A1"))
genes_all <- c(genes_both, genes_ALL10, genes_ALL12)
df <- data.frame(log(t(data[, metadata$batch %in% c("ALL10", "ALL12", "ALL10d15", "ALL12d15")] + 1)),
sample = metadata$batch[metadata$batch %in% c("ALL10", "ALL12", "ALL10d15", "ALL12d15")])
pdf("densityPlots_ALL10_ALL10d15.pdf", width = 5, height = 3)
for(i in genes_all) {
df.tmp <- data.frame(gexp = df[df$sample %in% c("ALL10", "ALL10d15"), i], sample = df$sample[df$sample %in% c("ALL10", "ALL10d15")])
p <- ggplot(df.tmp, aes(x = gexp, fill = sample, colour = sample)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
pdf("densityPlots_ALL12_ALL12d15.pdf", width = 5, height = 3)
for(i in genes_all) {
df.tmp <- data.frame(gexp = df[df$sample %in% c("ALL12", "ALL12d15"), i], sample = df$sample[df$sample %in% c("ALL12", "ALL12d15")])
p <- ggplot(df.tmp, aes(x = gexp, fill = sample, colour = sample)) +
geom_density(alpha = 0.4, adjust = 2) +
scale_fill_brewer(palette = "Dark2") +
scale_colour_brewer(palette = "Dark2") +
labs(title = i) +
theme_classic()
plot(p)
}
graphics.off()
library(dplyr)
df2 <- df[, c(genes_all, "sample")] %>% group_by(sample) %>% summarise_all(mean)
mat <- as.data.frame(df2)
rownames(mat) <- mat[, 1]
mat <- mat[, -1]
mat <- t(scale(mat))
mat <- mat[, c(1, 3, 2, 4)]
hmr <- Heatmap(mat,
cluster_rows = F,
cluster_columns = F,
show_row_names = T,
show_column_names = T,
row_names_gp = gpar(fontsize = 4),
show_heatmap_legend = T,
use_raster = F
)
pdf("heatmap_diag_d15.pdf", width = 5, height = 12)
draw(hmr)
graphics.off()
# Ridge plots from selected genes (Fig5D)
# Note: Add CD20 represented as protein level (FACS)
TFs <- c("RUNX1", "POU2F2", "ERG",
"TCF3", "KLF6", "ELK3",
"SOX4", "AFF3", "MS4A1",
"SMAD1", "SPIB")
labels <- c(TFs, "CD20")
CD20 <- read.delim("/research/groups/allseq/data/scRNAseq/results/ER_project/data/CD20_FACS.txt")
load("/research/groups/allseq/data/scRNAseq/results/ER_project/new_2019/data/HCA_ALL_combined.RData")
HCA_ALL <- readRDS("vst_HCABlineage_ALL_log_counts_batch.rds")
data <- as.matrix(HCA_ALL$umi_corrected)[TFs]
df <- data.frame(log(t(data[, metadata$batch %in% c("ALL10", "ALL12", "ALL10d15", "ALL12d15") & metadata$phase == "G1"] + 1)),
batch = metadata$batch[metadata$batch %in% c("ALL10", "ALL12", "ALL10d15", "ALL12d15") & metadata$phase == "G1"])
df$day <- "d0"
df$day[df$batch %in% c("ALL10d15", "ALL12d15")] <- "d15"
df$donor <- "ALL10"
df$donor[df$batch %in% c("ALL12", "ALL12d15")] <- "ALL12"
df$day <- factor(df$day)
df$donor <- factor(df$donor)
library(ggridges)
library(ggpubr)
pl <- lapply(TFs, function(x) {
ggplot(df, aes_string(x = x, y = "donor", fill = "day")) +
geom_density_ridges(alpha = .5) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
coord_cartesian(clip = "off") +
theme_ridges()
})
CD20.df <- rbind.data.frame(data.frame(CD20 = CD20$ALL10_d0_CD20[! is.na(CD20$ALL10_d0_CD20)], donor = "ALL10", day = "d0"),
data.frame(CD20 = CD20$ALL10_d15_CD20[! is.na(CD20$ALL10_d15_CD20)], donor = "ALL10", day = "d15"),
data.frame(CD20 = CD20$ALL12_d0_CD20[! is.na(CD20$ALL12_d0_CD20)], donor = "ALL12", day = "d0"),
data.frame(CD20 = CD20$ALL12_d15_CD20[! is.na(CD20$ALL12_d15_CD20)], donor = "ALL12", day = "d15"))
pl[[12]] <- ggplot(CD20.df, aes(x = CD20, y = donor, fill = day)) +
geom_density_ridges(alpha = .5) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
coord_cartesian(clip = "off") +
theme_ridges()
pb <- ggarrange(pl[[1]], pl[[2]], pl[[3]],
pl[[4]], pl[[5]], pl[[6]],
pl[[7]], pl[[8]], pl[[9]],
pl[[10]], pl[[11]], pl[[12]], nrow = 4, ncol = 3, common.legend = T)
pdf("Fig5_TFs_ridgePlot.pdf")
plot(pb)
graphics.off()
# Fix bandwidth of gexp to 0.2
pl <- lapply(TFs, function(x) {
ggplot(df, aes_string(x = x, y = "donor", fill = "day", color = "day")) +
stat_density_ridges(alpha = .5, bandwidth = .2) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
coord_cartesian(clip = "off") +
theme_ridges()
})
pl[[12]] <- ggplot(CD20.df, aes(x = CD20, y = donor, fill = day, color = day)) +
geom_density_ridges(alpha = .5) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
coord_cartesian(clip = "off") +
theme_ridges()
pb <- ggarrange(pl[[1]], pl[[2]], pl[[3]],
pl[[4]], pl[[5]], pl[[6]],
pl[[7]], pl[[8]], pl[[9]],
pl[[10]], pl[[11]], pl[[12]], nrow = 4, ncol = 3, common.legend = T)
pdf("Fig5_TFs_ridgePlot_bw_adjusted.pdf")
plot(pb)
graphics.off()
|
6ad1cf13a375d62eab165a8a6e4e88a9423c9798
|
d24aadf70825c32f150537bdd9f68d99fe6a8f5f
|
/ch11-apis/exercise-1/exercise.R
|
548b98184ac9fde611432594bc9f7d30ce818962
|
[
"MIT"
] |
permissive
|
yprisma/INFO-201
|
fd516762f77bbd208bc390db0e6dbc12e382ebf1
|
d86d7f8a5ba5cafa8aa5765ce23dd8a79c191fd8
|
refs/heads/master
| 2020-05-25T08:38:50.010596
| 2019-03-22T08:34:28
| 2019-03-22T08:34:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,075
|
r
|
exercise.R
|
### Exercise 1 ###
# Load the httr and jsonlite libraries for accessing data
library(httr)
library(jsonlite)
## For these questions, look at the API documentation to identify the appropriate endpoint and information.
## Then send GET() request to fetch the data, then extract the answer to the question
response <- GET("https://api.github.com/search/repositories?q=d3&sort=forks&order=desc")
body <- content(response, "text")
parsed.data <- fromJSON(body)
View(parsed.data)
most.popular.forks <- parsed.data$items[1, 'forks']
# For what years does the API have statistical data?
# What is the "country code" for the "Syrian Arab Republic"?
# How many persons of concern from Syria applied for residence in the USA in 2013?
# Hint: you'll need to use a query parameter
# Use the `str()` function to print the data of interest
# See http://www.unhcr.org/en-us/who-we-help.html for details on these terms
## And this was only 2013...
# How many *refugees* from Syria settled the USA in all years in the data set (2000 through 2013)?
# Hint: check out the "time series" end points
# Use the `plot()` function to plot the year vs. the value.
# Add `type="o"` as a parameter to draw a line
# Pick one other country in the world (e.g., Turkey).
# How many *refugees* from Syria settled in that country in all years in the data set (2000 through 2013)?
# Is it more or less than the USA? (Hint: join the tables and add a new column!)
# Hint: To compare the values, you'll need to convert the data (which is a string) to a number; try using `as.numeric()`
## Bonus (not in solution):
# How many of the refugees in 2013 were children (between 0 and 4 years old)?
## Extra practice (but less interesting results)
# How many total people applied for asylum in the USA in 2013?
# - You'll need to filter out NA values; try using `is.na()`
# - To calculate a sum, you'll need to convert the data (which is a string) to a number; try using `as.numeric()`
## Also note that asylum seekers are not refugees
|
4b5b6e0d96c3041bb12515f6b3adaac725e0b6e6
|
908d7f88068d50284bab29bb08355666a2342808
|
/man/numberdiffs.Rd
|
34c7b1453d0046bcc708c916dd8bc5b964d395d1
|
[] |
no_license
|
ttnsdcn/forecast-package
|
88bd3ece3af7b001ed824cbdae65bc0efc1b7b2d
|
0776e8b89790009c633f3598dd0701f03cd60e82
|
refs/heads/master
| 2020-12-31T04:42:08.682697
| 2012-01-31T02:29:17
| 2012-01-31T02:29:17
| 48,546,474
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,058
|
rd
|
numberdiffs.Rd
|
\name{ndiffs}
\alias{ndiffs}
\alias{nsdiffs}
\title{Number of differences required for a stationary series}
\usage{ndiffs(x, alpha=0.05, test=c("kpss","adf", "pp"))
nsdiffs(x, m=frequency(x), test=c("ocsb","ch"))
}
\arguments{
\item{x}{A univariate time series}
\item{alpha}{Level of the test}
\item{m}{Length of seasonal period}
\item{test}{Type of unit root test to use}
}
\description{Functions to estimate the number of differences required to make a given time series stationary. \code{ndiffs} estimates the number of first differences and \code{nsdiffs} estimates the number of seasonal differences.}
\details{\code{ndiffs} uses a unit root test to determine the number of differences required for time series \code{x} to be made stationary. If \code{test="kpss"}, the KPSS test is used with the null hypothesis that \code{x} has a stationary root against a unit-root alternative. Then the test returns the least number of differences required to pass the test at the level \code{alpha}. If \code{test="adf"}, the Augmented Dickey-Fuller test is used and if \code{test="pp"} the Phillips-Perron test is used. In both of these cases, the null hypothesis is that \code{x} has a unit root against a stationary root alternative. Then the test returns the least number of differences required to fail the test at the level \code{alpha}.
\code{nsdiffs} uses seasonal unit root tests to determine the number of seasonal differences required for time series \code{x} to be made stationary (possibly with some lag-one differencing as well). If \code{test="ch"}, the Canova-Hansen (1995) test is used (with null hypothesis of deterministic seasonality) and if \code{test="ocsb"}, the Osborn-Chui-Smith-Birchenhall (1988) test is used (with null hypothesis that a seasonal unit root exists).}
\seealso{\code{\link{auto.arima}}}
\references{
Canova F and Hansen BE (1995) "Are Seasonal Patterns Constant over Time? A Test for Seasonal Stability", \emph{Journal of Business and Economic Statistics} \bold{13}(3):237-252.
Dickey DA and Fuller WA (1979), "Distribution of the Estimators for Autoregressive Time Series with a Unit Root", \emph{Journal of the American Statistical Association} \bold{74}:427-431.
Kwiatkowski D, Phillips PCB, Schmidt P and Shin Y (1992) "Testing the Null Hypothesis of Stationarity against the Alternative of a Unit Root", \emph{Journal of Econometrics} \bold{54}:159-178.
Osborn DR, Chui APL, Smith J, and Birchenhall CR (1988) "Seasonality and the order of integration for consumption", \emph{Oxford Bulletin of Economics and Statistics} \bold{50}(4):361-377.
Osborn, D.R. (1990) "Seasonality and the order of integration in consumption", \emph{International Journal of Forecasting}, \bold{6}:327-336.
Said E and Dickey DA (1984), "Testing for Unit Roots in Autoregressive Moving Average Models of Unknown Order", \emph{Biometrika} \bold{71}:599-607.
}
\value{An integer.}
\author{Rob J Hyndman and Slava Razbash}
\examples{ndiffs(WWWusage)
nsdiffs(log(AirPassengers))
ndiffs(diff(log(AirPassengers),12))
}
\keyword{ts}
|
ddd2b5f6b8cad66999b68e720276de6a4434876c
|
cba876fd1bab6561907b4bcdb58e3f0ac4f5decf
|
/R/accum_cruve_camdays.R
|
b20e9cf5478f3a85f79655c009f53ab605157671
|
[] |
no_license
|
ccheng91/occupancy
|
a004ee9cee0276a98cd7f6f3f9ef7a836e6e020d
|
c111181f3a95d9688d6a451a2eaab510612ae10e
|
refs/heads/master
| 2021-01-19T06:25:56.680725
| 2017-11-23T21:04:04
| 2017-11-23T21:04:04
| 59,855,841
| 3
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 10,310
|
r
|
accum_cruve_camdays.R
|
### accumlative curve of camdays
library(vegan)
##
rm(list=ls(all=TRUE))
data.photo <- read.csv("data/All_photo.csv")
str(data.photo)
data.photo <- dplyr::filter(data.photo, data.photo$species != "bat" & data.photo$species != "commongreenmagpie" &
data.photo$species != "greateryellownape"& data.photo$species !="greenmagpie"&
data.photo$species!="treeshrew"& data.photo$species != "junglefowl"& data.photo$species!="silverpheasant"&
data.photo$species!="squirrel"& data.photo$species!="bird" &
data.photo$species!="rat" & data.photo$species != "unknown" & data.photo$species != "human" )
data.photo <- data.photo[which(data.photo$species != "bat" & data.photo$species != "commongreenmagpie" &
data.photo$species != "greateryellownape"& data.photo$species !="greenmagpie"&
data.photo$species!="treeshrew"& data.photo$species != "junglefowl"& data.photo$species!="silverpheasant"&
data.photo$species!="squirrel"& data.photo$species!="bird" &
data.photo$species!="rat" & data.photo$species != "unknown" & data.photo$species != "human"), ]
## richness of each site
list <- as.data.frame.matrix(table(data.photo$site,data.photo$species))
list <- list[, colSums(list) != 0] ### delet col that are all zero
list <- subset( list, select = -human2 )
list <- subset( list, select = -hunter )
list <- subset( list, select = -watermonitor )
list <- subset( list, select = -dog )
list <- subset( list, select = -cattle )
allmammal <- colnames(list)
############# make long data for all mammal ##############
SE_date <- read.csv("data/start_end_date.csv", header = TRUE, stringsAsFactors=FALSE) # enter start end date
SE_date$NO <- tolower(SE_date$NO) # change camera name to lower case
str(SE_date)
# data.long <- data.frame(station=character(), year=double(), month=double(),days=double(),individuals=double(),
# camhours=double(),stringsAsFactors=FALSE)
## making first col(station col) of datalong
sumcam<-cumsum(SE_date$Cam_days) # cumsum give you accumulate sum of days, to indicate where to add next station name
data.long <- matrix(999, sum(SE_date$Cam_days), 6, byrow=T) # make a matrix fill with 999
k <- 1 # initial k
for(i in 1:length(data.long[,1])) {
if(i < sumcam[k]){ # if sumcam > i, start to add next station name
data.long[i,1] <- SE_date$NO[k]
} else {
data.long[i,1] <- SE_date$NO[k]
k <- k+1
}
}
# make a vector that contain all date
all.date <-data.frame() # make a empty data.frame
for(i in 1:length(SE_date[,1])) {
c.date <-data.frame(seq(as.Date(toString(SE_date$START_DATE[i])), as.Date(toString(SE_date$END_DATE[i])), by = "day"))
all.date <- dplyr::bind_rows(all.date, c.date ) # adding dates to empty data frame
}
names(all.date)<-c("date")
all.date <- as.Date(all.date$date)
# make 2,3,4 col of long data, basically seprate year,month,day from a date
for(i in 1:length(data.long[,1])) {
data.long[i,2] <- year(all.date[i])
data.long[i,3] <- month(all.date[i])
data.long[i,4] <- day(all.date[i])
}
#### data for individual
data.wildboar <- dplyr::filter(data.photo, species == "guar") # filter one spp
df.dl <- as.data.frame(data.long, stringsAsFactors=FALSE)
df.dl$ymd.dt <- all.date # need a new variable to match
names(df.dl)[1:6] <- c("station","year","month","day","individuals","camhours")
df.dl$individuals <- 0
datetime.x <- as.Date(data.wildboar$datetime)
data.wildboar <- cbind(data.wildboar,datetime.x)
#‘data.wildboar <- ddply(data.wildboar, .(camera, datetime.x) , summarize, n = max(n))
data.wbsum <- aggregate(n ~ camera + datetime.x, FUN = max, data = data.wildboar) # funtion chose max/sum depends
data.wbsum$camera <- as.character(data.wbsum$camera)
nrow(data.wbsum)
data.wildboar <- data.wbsum
# if camera & date all matched then write in indivadule number
for(i in 1:nrow(data.wildboar)){
index <- which(df.dl$ymd.dt == data.wildboar$datetime.x[i] & df.dl$station == data.wildboar$camera[i])
# if(df.dl$individuals[index] != 0) {
# df.dl$individuals[index] <- df.dl$individuals[index] + data.wildboar$n[i]
# } else {
# }
df.dl$individuals[index] <- data.wildboar$n[i]
}
sum(data.wildboar$n) # to check whether have right indivdule numbers
sum(df.dl$individuals)#
## fill in camhours
df.dl$camhours <- 24
for(i in 1:nrow(SE_date)) {
ds <- which(df.dl$ymd.dt == SE_date$START_DATE[i] & df.dl$station == SE_date$NO[i])
df.dl$camhours[ds] <- SE_date$DAY1[i]
de <- which(df.dl$ymd.dt == SE_date$END_DATE[i] & df.dl$station == SE_date$NO[i])
df.dl$camhours[de] <- SE_date$END_TIME[i]
}
## checking
sum(df.dl$camhours)-((nrow(df.dl) - (nrow(SE_date)*2))*24)
sum(SE_date$DAY1)+sum(SE_date$END_TIME)
sum(df.dl$camhours)
## enter the intervals for BLS1005 & BLS 3005 if there are lots of interval need re-write
c2 <- which(df.dl$ymd.dt >= as.Date("2014-05-29") & df.dl$ymd.dt <= as.Date("2014-06-30") & df.dl$station == "bls3005")
inters <- which(df.dl$ymd.dt == as.Date("2014-05-29") & df.dl$station == "bls3005")
intere <- which(df.dl$ymd.dt == as.Date("2014-06-30") & df.dl$station == "bls3005")
df.dl$camhours[c2] <- 0
df.dl$camhours[inters] <- 16.5
df.dl$camhours[intere] <- 19.5
### remove redundance and write long data sheet ###
df.dl$ymd.dt <- NULL
write.csv(df.dl, file="data/guar_long.csv", row.names = FALSE )
allmammal
#########
spp1 <- read.csv("data/blackbear_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp2 <- read.csv("data/brushtailedporcupine_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp3 <- read.csv("data/chineseferretbadger_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp4 <- read.csv("data/commonmacaque_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp5 <- read.csv("data/commonpalmcivet_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp6 <- read.csv("data/crabeatingmongoose_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp7 <- read.csv("data/dhole_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp8 <- read.csv("data/goral_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp9 <- read.csv("data/guar_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp10 <- read.csv("data/hogbadger_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp11 <- read.csv("data/leopardcat_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp12 <- read.csv("data/maskedpalmcivet_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp13 <- read.csv("data/muntjac_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp14 <- read.csv("data/pigtailedmacaque_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp15 <- read.csv("data/porcupine_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp16 <- read.csv("data/sambar_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp17 <- read.csv("data/serow_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp18 <- read.csv("data/smallindiancivet_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp19 <- read.csv("data/spotedlinsang_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp20 <- read.csv("data/weasel_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp21 <- read.csv("data/wildboar_long.csv", header = TRUE, stringsAsFactors=FALSE)
spp22 <- read.csv("data/yellowthroatedmarten_long.csv", header = TRUE, stringsAsFactors=FALSE)
long_list <- list(spp1,spp2,spp3,spp4,spp5,spp6,spp7,spp8,spp9,spp10,spp11,spp12,spp13,spp14,spp15,spp16
,spp17,spp18,spp19,spp21,spp22)
richness <- data.frame(1:12296)
for(i in long_list) {
a <- data.frame(i[,5])
richness <- dplyr::bind_cols(richness, a) #add cols each col is indivadual for each spp
}
colnames(richness) <-allmammal
richness[,1] <- spp1[,5]
#data(BCI)
data(BCI)
S <- specnumber(BCI) # observed number of species
(raremax <- min(rowSums(BCI)))
Srare <- rarefy(BCI, raremax)
plot(S, Srare, xlab = "Observed No. of Species", ylab = "Rarefied No. of Species")
abline(0, 1)
rarecurve(BCI, step = 20, sample = raremax, col = "blue", cex = 0.6)
spa <- specaccum(richness, method = "rarefaction")
#data(BCI)
raremax<-min(rowSums((richness)))
Srare <- rarefy(richness, raremax)
rarecurve(richness)
head(richness)
plot(n,Srare, xlab = "Observed No. of Species", ylab = "Rarefied No. of Species")
sp1 <- specaccum(richness)
sp2 <- specaccum(richness, "random")
#sp2
summary(sp2)
n <- specnumber(richness)
plot(sp2, ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
boxplot(sp2, col="yellow", add=TRUE, pch="+")
### Fit Lomolino model to the exact accumulation
mod1 <- fitspecaccum(sp1, "lomolino")
coef(mod1)
fitted(mod1)
plot(sp1)
#### Add Lomolino model using argument 'add'
plot(mod1, add = TRUE, col=2, lwd=2)
### Fit Arrhenius models to all random accumulations
mods <- fitspecaccum(sp2, "arrh")
plot(mods, col="hotpink")
#boxplot(sp2, col = "yellow", border = "blue", lty=1, cex=0.3, add= TRUE)
### Use nls() methods to the list of models
sapply(mods$models, AIC)
head(richness)
head(spp1)
c1 <- max(which(spp1$station == "ml3006"))
c2 <- max(which(spp1$station == "mg2007"))
c3 <- max(which(spp1$station == "lsl2006"))
c4 <- max(which(spp1$station == "bls7003"))
c5 <- max(which(spp1$station == "ms5004"))
c6 <- max(which(spp1$station == "nbh5005"))
richness.ml <- richness[1:c1,]
richness.mg <- richness[c1:c2,]
richness.lsl <- richness[c2:c3,]
richness.bls <- richness[c3:c4,]
richness.ms <- richness[c4:c5,]
richness.nbh <- richness[c5:c6,]
sp.ml <- specaccum(richness.ml, "rarefaction")
sp.mg <- specaccum(richness.mg, "rarefaction")
sp.lsl <- specaccum(richness.lsl, "rarefaction")
sp.bls <- specaccum(richness.bls, "rarefaction")
sp.ms <- specaccum(richness.ms, "rarefaction")
sp.nbh <- specaccum(richness.nbh, "rarefaction")
str(sp.ml)
plot(sp.ml,ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
plot(sp.mg,ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
plot(sp.lsl,ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
plot(sp.bls,ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
plot(sp.ms,ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
plot(sp.nbh,ci.type="poly", col="blue", lwd=2, ci.lty=0, ci.col="lightblue")
|
f0f0ce6a6bd52bd72fdcc3492e12d47bfc31e189
|
03f9b872f9e89453d1faf9b545d23fbad83bb303
|
/man/summary_genotypes.Rd
|
bdbc463b3c396cee0927b7e72aadb2f34ca301ac
|
[] |
no_license
|
kawu001/stackr
|
99fa54f4b4e1c8194550752bb238864597442c08
|
684b29b9895c773f48d0e58cba3af22fc2c98a56
|
refs/heads/master
| 2023-01-06T06:47:55.234575
| 2020-11-05T13:51:20
| 2020-11-05T13:51:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 3,707
|
rd
|
summary_genotypes.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/summary_genotypes.R
\name{summary_genotypes}
\alias{summary_genotypes}
\title{Summary of \code{batch_x.genotypes.txt} and
\code{batch_x.markers.tsv} files.}
\usage{
summary_genotypes(
genotypes,
markers,
filter.monomorphic = TRUE,
filter.missing.band = TRUE,
filter.mean.log.likelihood = NULL,
B = NULL,
filter.GOF = NULL,
filter.GOF.p.value = NULL,
ind.genotyped = 1,
joinmap = NULL,
onemap = NULL,
filename = NULL
)
}
\arguments{
\item{genotypes}{The \code{genotypes = batch_x.genotypes.txt} created by STACKS genotypes
module.}
\item{markers}{The \code{markers = batch_x.markers.tsv} created by STACKS genotypes
module.}
\item{filter.monomorphic}{(optional) Should monomorphic loci be filtered out.
Default: \code{filter.monomorphic = TRUE}.}
\item{filter.missing.band}{(optional) Should loci with missing
band be filtered out. Default: \code{filter.missing.band = TRUE}.}
\item{filter.mean.log.likelihood}{(optional, integer) Apply a mean log likelihood
filter to the loci. e.g. filter.mean.log.likelihood = -10.
Default: \code{filter.mean.log.likelihood = NULL} (no filter)}
\item{B}{(optional, integer) The segregation distortion p-value
will be computed with a Monte Carlo test with \code{B} replicates,
if \code{B} is supplied.
For more details, see \code{\link[stats]{chisq.test}}.
Default: \code{B = NULL}.}
\item{filter.GOF}{(optional, integer) Filer value of the goodness-of-fit for segregation
distortion. Default: \code{filter.GOF = NULL}.}
\item{filter.GOF.p.value}{(optional, double) Filer the goodness-of-fit p-value of
GOF segregation distortion. Default: \code{filter.GOF.p.value = NULL}.}
\item{ind.genotyped}{(optional, integer) Filter the number of individual
progenies required to keep the marker. Default: \code{ind.genotyped = 1}.}
\item{joinmap}{(optional) Name of the JoinMap file to write
in the working directory. e.g. "joinmap.turtle.family3.loc".
Default: \code{joinmap = NULL}.}
\item{onemap}{(optional) Name of the OneMap file to write
in the working directory. e.g. "onemap.turtle.family3.txt".
Default: \code{onemap = NULL}.}
\item{filename}{(optional) The name of the summary file written
in the directory. No default.
Default: \code{filename = NULL}.}
}
\value{
The function returns a list with the
genotypes summary \code{$geno.sum}, joinmap markers \code{$joinmap.sum}
and onemap markers \code{$onemap.sum} summary (use $ to access each
components). A JoinMap and/or OneMap file can also be exported to
the working direcvtory.
}
\description{
Useful summary of \code{batch_x.genotypes.txt} and
\code{batch_x.markers.tsv} files produced by STACKS genotypes module use
for linkage mapping. Filter segregation distortion and output JoinMap and or
OneMap file.
}
\details{
SIGNIFICANCE results pvalue (goodness-of-fit pvalue):
<= 0.0001 = ****, <= 0.001 & > 0.0001 = ***,
<= 0.01 & > 0.001 = **, <= 0.05 & > 0.01 = *.
work in progress...
}
\examples{
\dontrun{
linkage.map.crab <- summary_genotypes(
genotypes = "batch_10.markers.tsv",
markers = "batch_10.genotypes_300.txt",
filter.monomorphic = TRUE,
filter.missing.band = TRUE,
filter.mean.log.likelihood = -10,
B = NULL,
ind.genotyped = 300,
joinmap = "test.loc",
onemap = "test.onemap.txt",
filename = "genotypes.summary.tsv"
)
}
}
\references{
Catchen JM, Amores A, Hohenlohe PA et al. (2011)
Stacks: Building and Genotyping Loci De Novo From Short-Read Sequences.
G3, 1, 171-182.
Catchen JM, Hohenlohe PA, Bassham S, Amores A, Cresko WA (2013)
Stacks: an analysis tool set for population genomics.
Molecular Ecology, 22, 3124-3140.
}
\author{
Thierry Gosselin \email{thierrygosselin@icloud.com}
}
|
63565b31cd62ff2c77423f5096dd1eb87594b6c9
|
57aa5e623b0a037c424fa257d259f59393436f24
|
/DR_Method/SEQ_DIFF.R
|
7a5e6517189f0d319edd04fdc42fcc0c0037e2ce
|
[] |
no_license
|
emathian/DRMetrics
|
24a0ab942562ac6f1d4a41cb39b7b386d0652a10
|
ceeeb9501d838c4b0743dadb3cf942dc59020216
|
refs/heads/master
| 2020-06-27T05:59:15.403081
| 2019-09-30T09:52:44
| 2019-09-30T09:52:44
| 199,863,555
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 21,102
|
r
|
SEQ_DIFF.R
|
# __________
# Tools :
# _________
Merging_function <- function(l_data, dataRef){
colnames(dataRef)[1] <- "Sample_ID"
res_l_data <- list()
for (i in 1:length(l_data)){
c_data <- l_data[[i]]
colnames(c_data)[1] <- "Sample_ID"
if (dim(c_data)[1] != dim(dataRef)[1]){
warning(paste("Warning : the data frame[" , i ,")] doesn't have the same number of lines than `dataRef`. An inner join will be effecte") )
}
else if(sum(c_data[, 1] == dataRef[, 1]) != length(c_data[, 1])){
warning(paste("Sample_IDs in data frame [", i,"] and dataRef are not the same, or are not in the same order. An inner join will be effected.", sep =""))
}
data_m <- merge(dataRef, c_data, by = "Sample_ID")
dataRef <- dataRef[, 1:dim(dataRef)[2]]
r_data <- data_m[,(dim(dataRef)[2] + 1):dim(data_m)[2]]
r_data <- cbind(data_m[, 1], r_data)
colnames(r_data)[1] <- 'Sample_ID'
res_l_data[[i]] <- r_data
}
return(list(res_l_data, dataRef))
}
# ------------------------------
############################################################################################
Seq_calcul <- function( l_data, dataRef, listK){
# __________ Clusters initialization ______
no_cores <- detectCores() # - 1
cl <- makeCluster(no_cores)
registerDoParallel(cl)
# _________________________________________
global_seq_list <- list()
for (I in 1:length(l_data)){
c_data <- l_data[[I]]
colnames(c_data)[1] <- 'Sample_ID' ; colnames(dataRef)[1] <- 'Sample_ID'
if (dim(c_data)[1] != dim(dataRef)[1]){
warning("The number of lines between `c_data` and `dataRef` differs. A merge will be effected.")
}
else if (sum(c_data[, 1] == dataRef[, 1]) != length(c_data[, 1])){
warning("Sample_IDs in `c_data` and `dataRef` are not the same, or are not in the same order. An inner join will be effected.")
}
data_m <- merge(c_data, dataRef, by = 'Sample_ID')
ncol_c_data <- dim(c_data)[2]
c_data <- data_m[, 1:dim(c_data)[2]]
dataRef <- data_m[, (dim(c_data)[2]+1):dim(data_m)[2]]
dataRef <- cbind(data_m[, 1], dataRef)
colnames(dataRef)[1] <- 'Sample_ID'
#________________ Distances matrices __________
dist1 <- as.matrix(dist(c_data[, 2:dim(c_data)[2]], method = "euclidian", diag = TRUE, upper = TRUE))
rownames(dist1) <- as.character(c_data[ ,1])
colnames(dist1) <- as.character(c_data[ ,1])
dist2 <- as.matrix(dist(dataRef[, 2:dim(dataRef)[2]], method = "euclidian", diag = TRUE, upper = TRUE))
rownames(dist2) <- as.character(dataRef[ ,1])
colnames(dist2) <- as.character(dataRef[ ,1])
# ____________________________________________
seq_c_data <- data.frame()
seq_c_data <- foreach(i=1:length(listK),.combine=rbind) %dopar% {
#for(i in 1:length(listK)){
k <- listK[i]
colnames(c_data)[1] <- 'Sample_ID' ; colnames(dataRef)[1] <- 'Sample_ID'
if (dim(c_data)[1] != dim(dataRef)[1]){
warning("The number of lines between `c_data` and `dataRef` differs. A merge will be effected")
}
else if (sum(c_data[, 1] == dataRef[, 1]) != length(c_data[, 1])){
warning("Sample_IDs in `c_data` and `dataRef` are not the same, or are not in the same order. An inner join will be effected.")
}
data_m <- merge(c_data, dataRef, by = 'Sample_ID')
ncol_c_data <- dim(c_data)[2]
c_data <- data_m[, 1:dim(c_data)[2]]
dataRef <- data_m[, (dim(c_data)[2]+1):dim(data_m)[2]]
dataRef <- cbind(data_m[, 1], dataRef)
colnames(dataRef)[1] <- 'Sample_ID'
#________________ Distances matrices __________
dist1 <- as.matrix(dist(c_data[, 2:dim(c_data)[2]], method = "euclidian", diag = TRUE, upper = TRUE))
rownames(dist1) <- as.character(c_data[ ,1])
colnames(dist1) <- as.character(c_data[ ,1])
dist2 <- as.matrix(dist(dataRef[, 2:dim(dataRef)[2]], method = "euclidian", diag = TRUE, upper = TRUE))
rownames(dist2) <- as.character(dataRef[ ,1])
colnames(dist2) <- as.character(dataRef[ ,1])
# ____________________________________________
seq_diff_l <- c()
n <- dim(dist1)[1]
for (ii in 1:n){
c_point <- rownames(dist1)[ii]
N1_dist_l <- list(dist1[ii, ])[[1]]
N2_dist_l <- list(dist2[ii, ])[[1]]
names(N1_dist_l) <- rownames(dist1)
names(N2_dist_l) <- rownames(dist2)
N1_dist_l <- sort(N1_dist_l)
N2_dist_l <- sort(N2_dist_l)
N1_rank_l <- seq(length(N1_dist_l))
N2_rank_l <- seq(length(N2_dist_l))
names(N1_rank_l) <- names(N1_dist_l)
names(N2_rank_l) <- names(N2_dist_l)
N1_rank_l <- N1_rank_l[1:k]
N2_rank_l <- N2_rank_l[1:k]
N1_df <- data.frame("Sample_ID" = names(N1_rank_l) , "Rank1" = N1_rank_l)
N2_df <- data.frame("Sample_ID" = names(N2_rank_l) , "Rank2" = N2_rank_l)
All_neighbors <- unique(c(as.character(N1_df$Sample_ID),as.character(N2_df$Sample_ID)))
s1 = 0
s2 = 0
for (j in 1:length( All_neighbors)){
if (All_neighbors[j] %in% N1_df$Sample_ID & All_neighbors[j] %in% N2_df$Sample_ID ){
N1_index_j = which(N1_df$Sample_ID == All_neighbors[j] )
N2_index_j = which(N2_df$Sample_ID == All_neighbors[j] )
if( s1 + ((k - N1_df$Rank1[N1_index_j]) * abs(N1_df$Rank1[N1_index_j] - N2_df$Rank2[N2_index_j])) < s1 ){
}
s1 = s1 + ((k - N1_df$Rank1[N1_index_j]) * abs(N1_df$Rank1[N1_index_j] - N2_df$Rank2[N2_index_j]))
s2 = s2 + ((k - N2_df$Rank2[N2_index_j]) * abs(N1_df$Rank1[N1_index_j] - N2_df$Rank2[N2_index_j]))
}
else if (All_neighbors[j] %in% N1_df$Sample_ID){
N1_index_j = which(N1_df$Sample_ID == All_neighbors[j] )
s1 = s1 + ((k - N1_df$Rank1[N1_index_j]) * abs(N1_df$Rank1[ N1_index_j]))
s2 = s2
}
else{
N2_index_j = which(N2_df$Sample_ID == All_neighbors[j] )
s1 = s1
s2 = s2 + ((k - N2_df$Rank2[N2_index_j]) * abs( N2_df$Rank2[N2_index_j]))
}
}
S = 0.5 * s1 + 0.5 * s2
seq_diff_l <- c(seq_diff_l, S)
}
seq_diff_k_df <- data.frame('Sample_ID' = c_data$Sample_ID, 'K' = rep(k, length(c_data$Sample_ID)), 'Seq' = seq_diff_l)
# seq_diff_k_df
seq_c_data <- rbind( seq_c_data, seq_diff_k_df )
}
seq_c_data <- seq_c_data[order(seq_c_data$K),]
global_seq_list[[I]] <- seq_c_data
}
stopCluster(cl)
return(global_seq_list)
}
############################################################################################
############################################################################################
Seq_main <- function(l_data, dataRef, listK, colnames_res_df = NULL , filename = NULL , graphics = FALSE, stats = FALSE){
l_data <- Merging_function(l_data, dataRef)
L_data <- list()
for (i in 1:length(l_data[[1]])){
L_data[[i]] <- l_data[[1]][[i]]
}
dataRef <- l_data[[2]]
l_data <- L_data
if (length(l_data) == 1 & stats == TRUE){
warning("Statistical option are not available if `l_data` length is equal to 1.")
stats = FALSE
}
global_seq_list <- Seq_calcul(l_data , dataRef , listK )
for (i in 1:length(global_seq_list)){
global_seq_list[[i]] <- global_seq_list[[i]][complete.cases(global_seq_list[[i]]), ]
}
# _______________ Writing _________________
df_to_write <- data.frame('Sample_ID' = global_seq_list[[1]]$Sample_ID, 'K' = global_seq_list[[1]]$K )
for (i in 1:length(global_seq_list)){
df_to_write <- cbind(df_to_write, global_seq_list[[i]]$Seq)
}
if (is.null(colnames_res_df) == FALSE){
colnames(df_to_write)[3:length(colnames(df_to_write))] <- colnames_res_df
}
else{
colnames(df_to_write)[dim(df_to_write)[2]] <- paste('V', i, sep="")
}
if (is.null(filename) == FALSE) {
if (file.exists(as.character(filename))){
warning("The filename gives as argument exist in the current directory, this name will be 'incremented'.")
c = 2
while(file.exists(as.character(filename))){
filename <- paste(filename, c, sep = "" )
c = c+1
}
}
write.table(df_to_write, file = filename, sep = "\t")
}
data_Seq <- df_to_write
data_diff_mean_k <- data.frame("k" = unique(data_Seq$K))
for (j in seq(from = 3, to = dim(data_Seq)[2], by = 1)) {
mean_by_k <- tapply(data_Seq[, j], data_Seq$K, mean)
data_diff_mean_k <- cbind(data_diff_mean_k, mean_by_k)
}
colnames(data_diff_mean_k)[2:length(colnames(data_diff_mean_k))] <- colnames(data_Seq)[3:dim(data_Seq)[2]]
if (graphics == FALSE & stats == FALSE){
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k))
}
if (graphics == TRUE){
p <- Seq_graph_by_k('nothing', Names=colnames_res_df, list_col=NULL, data_diff_mean_K = data_diff_mean_k)
}
else{ # graphics == False
p <- 0 # Only to respect algorithm structure
}
if (graphics == TRUE & stats == FALSE){
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k, 'graphics' = p))
}
if (stats == TRUE){
if(dim(data_diff_mean_k)[2] == 2){
warning("Statics cannot be computed if length list of `l_data` is smaller than two.")
if (graphics == TRUE){
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k, 'graphics' = p))
}
else{
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k))
}
}
if(dim(data_diff_mean_k)[2] == 3){
if(dim(data_diff_mean_k)[1] < 30){
WT = wilcox.test(data_diff_mean_k[,2], data_diff_mean_k[, 3], paired = TRUE)
print(WT)
}
else{
WT = t.test(data_diff_mean_k[,2], data_diff_mean_k[, 3], paired = TRUE)
print(WT)
}
if (graphics == TRUE){
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k, 'graphics' = p, 'stats' = list("WT" = WT)))
}
else{
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k, 'stats' = list("WT" = WT)))
}
}
else{
pwt_df <- data.frame('mean_seq' = data_diff_mean_k[, 2], 'method'= rep(paste(colnames(data_diff_mean_k)[2], 2, sep = ""), dim(data_diff_mean_k)[1]))
for (i in 3:dim(data_diff_mean_k)[2]){
c_df <- data.frame('mean_seq' = data_diff_mean_k[, i], 'method'=rep(paste(colnames(data_diff_mean_k)[i], i, sep = ""), dim(data_diff_mean_k)[1]))
pwt_df <- rbind(pwt_df, c_df )
}
if (dim(data_diff_mean_k)[1] < 30){
paired_test_m <- pairwise.wilcox.test(pwt_df$mean_seq, pwt_df$method, paired = TRUE)$p.value #p.adj = "holm",
}
else{
paired_test_m <- pairwise.t.test(pwt_df$mean_seq, pwt_df$method, paired = TRUE)$p.value #p.adj = "holm",
}
if (graphics == TRUE){
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k, 'graphics' = p, 'pWT' = paired_test_m ))
}
else{
return(list('Seq_df' = df_to_write, 'Seq_mean_by_k' = data_diff_mean_k, 'pWT' = paired_test_m ))
}
}
warning('Unexpected request ')
}
}
############################################################################################
############################################################################################
Seq_graph_by_k <-function (data_Seq, Names=NULL, list_col=NULL, data_diff_mean_K = NULL, log = FALSE){
if (is.null(data_diff_mean_K) == TRUE) {
data_diff_mean_k <- data.frame("k" = unique(data_Seq$K))
for (j in seq(from = 3, to = dim(data_Seq)[2], by = 1)) {
mean_by_k <- tapply(data_Seq[, j], data_Seq$K , mean)
data_diff_mean_k <- cbind(data_diff_mean_k, mean_by_k)
}
colnames(data_diff_mean_k)[2:length(colnames(data_diff_mean_k))] <- colnames(data_Seq)[3:dim(data_Seq)[2]]
if (is.null(Names) == FALSE){
if (length(Names) != (dim(data_Seq)[2] - 3)){
warning("The list of names gave as input doesn't match with the number of curve.")
}
else{
colnames(data_diff_mean_k)[2:length(colnames(data_diff_mean_k))] <- Names
}
}
}
else{
data_diff_mean_k <- data_diff_mean_K
}
if (log == FALSE){
data_diff_mean_k_graph <- data.frame('k' = data_diff_mean_k$k , 'diff_seq' =( data_diff_mean_k[, 2]), 'Method' = rep(as.character(colnames(data_diff_mean_k)[2]), length(data_diff_mean_k$k)))
if (dim(data_diff_mean_k)[2]>=3){
for (i in 3:(dim(data_diff_mean_k)[2])){
c_df <- data.frame('k' = data_diff_mean_k$k , 'diff_seq' = (data_diff_mean_k[, i]), 'Method' = rep(as.character(colnames(data_diff_mean_k)[i]), length(data_diff_mean_k$k)))
data_diff_mean_k_graph <- rbind(data_diff_mean_k_graph, c_df)
}
}
theme_set(theme_bw())
p <- ggplot(data_diff_mean_k_graph, aes(x=k, y=diff_seq, color=Method)) + geom_line() + geom_point()+
scale_color_viridis(discrete=TRUE)
p <- p + labs(title="Sequence difference metric", y=("$log(\\bar{SD_k})$"), x="K") +theme(plot.title=element_text(size=18, face="bold", color="#17202A", hjust=0.5,lineheight=1.2), # title
plot.subtitle =element_text(size=13, color="#17202A", hjust=0.5), # caption
plot.caption =element_text(size=10, color="#17202A", hjust=0.5), # caption
axis.title.x=element_text(size=12, face="italic"), # X axis title
axis.title.y=element_text(size=12, face="bold"), # Y axis title
axis.text.x=element_text(size=12), # X axis text
axis.text.y=element_text(size=12),
legend.title = element_blank()) # Y axis text
print(p)
return(p)
}
else {
data_diff_mean_k_graph <- data.frame('k' = data_diff_mean_k$k , 'diff_seq' = log( data_diff_mean_k[, 2]), 'Method' = rep(as.character(colnames(data_diff_mean_k)[2]), length(data_diff_mean_k$k)))
if (dim(data_diff_mean_k)[2]>=3){
for (i in 3:(dim(data_diff_mean_k)[2])){
c_df <- data.frame('k' = data_diff_mean_k$k , 'diff_seq' = log(data_diff_mean_k[, i]), 'Method' = rep(as.character(colnames(data_diff_mean_k)[i]), length(data_diff_mean_k$k)))
data_diff_mean_k_graph <- rbind(data_diff_mean_k_graph, c_df)
}
}
theme_set(theme_bw())
p <- ggplot(data_diff_mean_k_graph, aes(x=k, y=diff_seq, color=Method)) + geom_line() + geom_point()+
scale_color_viridis(discrete=TRUE)
p <- p + labs(title="Sequence difference metric", y=("$log(\\bar{SD_k})$"), x="K") +theme(plot.title=element_text(size=18, face="bold", color="#17202A", hjust=0.5,lineheight=1.2), # title
plot.subtitle =element_text(size=13, color="#17202A", hjust=0.5), # caption
plot.caption =element_text(size=10, color="#17202A", hjust=0.5), # caption
axis.title.x=element_text(size=12, face="italic"), # X axis title
axis.title.y=element_text(size=12, face="bold"), # Y axis title
axis.text.x=element_text(size=12), # X axis text
axis.text.y=element_text(size=12),
legend.title = element_blank()) # Y axis text
print(p)
return(p)
}
}
############################################################################################
############################################################################################
seq_permutation_test <- function(data, data_ref, list_K, n=30, graph = TRUE){
if (n > 30){
warning("the calcul could be long !")
}
colnames(data)[1] <- 'Sample_ID' ; colnames(data_ref)[1] <- 'Sample_ID'
if (dim(data)[1] != dim(data_ref)[1]){
warning("Sample IDs don't match between `data` and `data_ref` a merge will be effected.")
}
else if( dim(data)[1] == dim(data_ref)[1] & sum(as.character(data[, 1]) == as.character(data_ref[, 1])) != length(data_ref[, 1])){
warning("Sample IDs don't match between `data` and `data_ref` a merge will be effected.")
}
data_m <- merge(data, data_ref, by=c('Sample_ID'))
data <- data_m[, 1:dim(data)[2]]
data_ref <- data_m[, (dim(data)[2]+1):dim(data_m)[2]]
data_ref <- cbind(data_m[, 1], data_ref)
colnames(data_ref)[1] <- "Sample_ID"
global_seq_df <- Seq_calcul(list(data), dataRef = data_ref , listK = list_K)[[1]]
mean_k <- tapply(global_seq_df$Seq, global_seq_df$K, mean)
main_df <- data.frame('k' = unique(global_seq_df$K) , "means_ref" = mean_k)
for (i in 1:n){
data_shuffle <- data[,2:dim(data)[2]]
data_shuffle <- data_shuffle[,sample(ncol(data_shuffle))]
data_shuffle <- data_shuffle[sample(nrow(data_shuffle)),]
data_shuffle <- cbind(data[,1], data_shuffle, row.names = NULL)
colnames(data_shuffle)[1] <- "Sample_ID"
Seq_data_A <- Seq_calcul(list(data_shuffle), dataRef = data_ref , listK = list_K)[[1]]
mean_k <- tapply(Seq_data_A$Seq, Seq_data_A$K, mean)
main_df <- cbind(main_df , mean_k)
}
by_k_alea <- main_df[,3:dim(main_df)[2]]
Means_alea <- rowMeans(by_k_alea)
WT = wilcox.test(main_df[ ,1], Means_alea, alternative = "less")
#print(WT)
theme_set(theme_bw())
p <- ggplot()
for (i in 3:(dim(main_df)[2])){
c_df <- data.frame('k' = main_df[ ,1] , 'main_df' = main_df[ ,i])
p <- p + geom_line(data = c_df, aes(x=k, y=main_df), colour = '#848484')+geom_point(data = c_df, aes(x=k, y= main_df), colour = '#848484')
}
c_df <- data.frame('k' = main_df[ ,1] , 'main_df' = main_df[ ,2])
p <- p + geom_line(data = c_df, aes(x=k, y = main_df), colour = '#B40404')+geom_point(data = c_df, aes(x=k, y=main_df), colour = '#B40404')
c_MA_df <- data.frame('k' = main_df[ ,1] , 'main_df' = Means_alea)
p <- p + geom_line(data = c_MA_df, aes(x=k, y = main_df), colour = '#388E3C')+geom_point(data = c_MA_df, aes(x=k, y=main_df), colour ='#388E3C')
p <- p + labs(title="Significance test of the Sequence difference metric",
y=TeX("$\\bar{SD_k} = \\frac{1}{N} \\sum_{i=1}^N SD_{i,k}$"), x="K") +theme(plot.title=element_text(size=18, face="bold", color="#17202A", hjust=0.5,lineheight=1.2), # title
plot.subtitle =element_text(size=13, color="#17202A", hjust=0.5), # caption
plot.caption =element_text(size=10, color="#17202A", hjust=0.5), # caption
axis.title.x=element_text(size=12, face="bold"), # X axis title
axis.title.y=element_text(size=12, face="bold"), # Y axis title
axis.text.x=element_text(size=12), # X axis text
axis.text.y=element_text(size=12)) # Y axis text
print(p)
return(list(WT,p))
}
############################################################################################################
SD_map_f <- function(SD_df, Coords_df, legend_pos = "right" ){
# SD_df data frame such as :
# col1 = Sample_ID, col2 = k, col3 = SD_values
# Coords_df data frame such as :
# col1 = Sample_ID, col2 = AxisX, col3 = AxisY
colnames(SD_df) <- c("Sample_ID", "k", "SD")
SD_df <- SD_df[order(SD_df$Sample_ID),]
SD_df$Sample_ID <- as.character( SD_df$Sample_ID)
unique_sample_id <- as.character(unique(SD_df$Sample_ID))
SDmeans_ID <- unlist(lapply(1:length(unique_sample_id), function(i){
mean(SD_df$SD[which(SD_df$Sample_ID == unique_sample_id [i])])
}))
colnames(Coords_df) <- c("Sample_ID", "V1", "V2")
Coords_df <- Coords_df[order(Coords_df$Sample_ID),]
SD_Coords_df <- cbind( Coords_df, "SD" = SDmeans_ID)
SD_Coords_df <- SD_Coords_df[order(SD_Coords_df$SD, decreasing = T),]
pSD_Main <- ggplot( SD_Coords_df, aes(x=V1, y=V2, color=SD/max(SD))) + geom_point(size=4, alpha =.8) + scale_color_distiller(palette = "Spectral")
pSD_Main <- pSD_Main + labs(title="",
y=TeX("dim2"), x="dim1") +
theme( legend.position = legend_pos,
plot.title=element_text(size=16, face="bold", hjust=0.5,lineheight=1.2), # title
plot.subtitle =element_text(size=14, hjust=0.5),
plot.caption =element_text(size=12, hjust=0.5),
axis.title.x=element_text(size=16), # X axis title
axis.title.y=element_text(size=16), # Y axis title
axis.text.x=element_text(size=14), # X axis text
axis.text.y=element_text(size=14),
legend.text = element_text(size = 10) ,
legend.title = element_blank())#+ guides(col = guide_legend( ncol = 2)) # Y axis text
return(list(SD_Coords_df,pSD_Main))
}
|
857632c69fc3c463a8b042d5a163671ffe000f9f
|
114e25c8be120bd53bac2c4b15f3352065163599
|
/R/Create_Run_File_WEPP_2012_600_for_call_from_batch_file.R
|
861a8bc50f31f6174156e609e35f52ee6349cc26
|
[] |
no_license
|
devalc/WEPP-Recipies
|
a71de08f97dd633c80424aef6de162ef6d1a85a1
|
79acbfa8f47bd3e27e45f36bf6ed63d92e5a596f
|
refs/heads/master
| 2023-06-10T13:08:01.928430
| 2021-07-07T22:31:35
| 2021-07-07T22:31:35
| 238,544,617
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,733
|
r
|
Create_Run_File_WEPP_2012_600_for_call_from_batch_file.R
|
## --------------------------------------------------------------------------------------##
##
## Script name: Create_Run_File_WEPP_2012_600.R
##
## Purpose of the script: Creates Run file for the WEPP 2012.600_for_calling_from_batch_File.exe
##
## Author: Chinmay Deval
##
## Created On: 2020-04-14
##
##
## --------------------------------------------------------------------------------------##
## Notes: This file create the run file for running multiple hillslopes
## and also includes lines in the run file that are needed to run
## the watershed
##
##
## --------------------------------------------------------------------------------------##
## --------------------------Get arguments passed in batch file-------------------------------##
args <- commandArgs(trailingOnly = TRUE)
cat(args, sep = "\n")
## ----------------------------------Initialization---------------------------------------##
# dir_location_to_create_run_file = "C:/Users/Chinmay/Desktop/WEPPcloud_test_run_Blackwood/R_Run_file_Creator/"
# Number_of_Hillslopes = 546
# SimYears = 26
dir_location_to_create_run_file = args[1]
Number_of_Hillslopes = args[2]
SimYears = args[3]
## ----------------------------------creat run file---------------------------------------##
pass_suffix = "pass.txt"
loss_suffix = "loss.txt"
wat_suffix = "wat.txt"
sink(paste(dir_location_to_create_run_file,"pwa0.run", sep = ""))
#[e]nglish or [m]etric units
cat("m", sep = "\n")
#Drop out of the model upon invalid input and write over identical output file names?
cat("n",sep = "\n")
# 1- continuouts simulation 2- single storm
cat("1",sep = "\n")
# 1- hillslope version (single hillslopes only), 2- hillslope/watershed version(multiple hillslopes, channels and impoundments), 3- watershed versions ( channels and impoundments)
cat("2",sep = "\n")
# Enter name for master watershed pass file
cat("pass_pw0.txt",sep = "\n")
#enter number of hillslopes
cat(Number_of_Hillslopes, sep = "\n")
for (number in 1:Number_of_Hillslopes) {
#[e]nglish or [m]etric units
cat("m", sep = "\n")
# use existing hillslope file?
cat("n", sep = "\n")
# provide hillslope pass file name
cat(paste0("./output/",number, "_", pass_suffix), sep = "\n")
# soil loss option
cat("1", sep = "\n")
# want initial condition scenario output?
cat("n", sep = "\n")
# name of soil loss output
cat(paste0("./output/",number,"_", loss_suffix), sep = "\n")
# water balance output?
cat("y", sep = "\n")
# water balance file name
cat(paste0("./output/",number,"_", wat_suffix), sep = "\n")
##crop output?
cat("n", sep = "\n")
#soil output?
cat("n", sep = "\n")
#distance and sediment loss output?
cat("n", sep = "\n")
#large graphic output?
cat("n", sep = "\n")
#event by event output?
cat("n", sep = "\n")
#element output?
cat("n", sep = "\n")
#final summary output?
cat("n", sep = "\n")
#daily winter output?
cat("n", sep = "\n")
#plant yield output?
cat("n", sep = "\n")
#management file
cat(paste0("./runs/p",number,"",".man"), sep = "\n")
#slope file
cat(paste0("./runs/p",number,"",".slp"), sep = "\n")
#climate file
cat(paste0("./runs/p",number,"",".cli"), sep = "\n")
# soil file
cat(paste0("./runs/p",number,"",".sol"), sep = "\n")
#irrigation option
cat("0", sep = "\n")
# number of simulation years
cat(SimYears, sep = "\n")
}
#Some random trigger needed (using space for now). I guess a blank will work too. Check with Erin/Anurag/Mariana.
cat("", sep = "\n")
# do you wish to model impoundments
cat("y", sep = "\n")
# initial scenario output
cat("n", sep = "\n")
# wshed soil loss ouput options
cat("1", sep = "\n")
# watershed soil loss name
cat("loss_pw0.txt", sep="\n")
# wbal output?
cat("y", sep = "\n")
# file name for wbal
cat("chnwb_pw0.txt", sep="\n")
# crop output
cat("n", sep = "\n")
# soil output
cat("y", sep = "\n")
# soil output file name
cat("soil_pw0.txt", sep = "\n")
# chan erosion plotting output?
cat("n", sep = "\n")
# wshed large graphics output?
cat("n", sep = "\n")
# evenet by event output?
cat("y", sep = "\n")
# event by event file name
cat("ebe_pw0.txt", sep = "\n")
#final summary output?
cat("n", sep = "\n")
#daily winter output?
cat("n", sep = "\n")
# daily yield output?
cat("n", sep = "\n")
# want impoundment output?
cat("n", sep = "\n")
#watershed Structure file
cat("runs/pw0.str", sep = "\n")
#watershed channel file
cat("runs/pw0.chn", sep = "\n")
#watershed impoundment file
cat("runs/pw0.imp", sep = "\n")
#watershed management file
cat("runs/pw0.man", sep = "\n")
#watershed Slope file
cat("runs/pw0.slp", sep = "\n")
#watershed climate file
cat("runs/pw0.cli", sep = "\n")
#watershed soil file
cat("runs/pw0.sol", sep = "\n")
#irrigation option
cat("0", sep = "\n")
# number of simulation years
cat(SimYears, sep = "\n")
sink()
|
df3ac37d724ff055d3bf03f08196e7cc54e0793f
|
f186b57cf6e8f1d67055001dbc55a7d6e6d0681e
|
/man/dap_to_local.Rd
|
0e16fb696ab3d5d8bd711e4a35754a88559db44f
|
[
"MIT"
] |
permissive
|
mikejohnson51/climateR
|
7f005e7ba5e8eb59245cc899b96362d8ed1256a2
|
4d02cd9ccc73f1fd7ad8760b50895a0daaa2f058
|
refs/heads/master
| 2023-09-04T08:57:09.854817
| 2023-08-21T19:53:33
| 2023-08-21T19:53:33
| 158,620,263
| 138
| 35
|
MIT
| 2023-08-14T22:52:00
| 2018-11-22T00:07:16
|
R
|
UTF-8
|
R
| false
| true
| 1,118
|
rd
|
dap_to_local.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{dap_to_local}
\alias{dap_to_local}
\title{Convert OpenDAP to start/count call}
\usage{
dap_to_local(dap, get = TRUE)
}
\arguments{
\item{dap}{dap description}
\item{get}{should data be collected?}
}
\value{
numeric array
}
\description{
Convert OpenDAP to start/count call
}
\seealso{
Other dap:
\code{\link{.resource_grid}()},
\code{\link{.resource_time}()},
\code{\link{climater_dap}()},
\code{\link{climater_filter}()},
\code{\link{dap_crop}()},
\code{\link{dap_get}()},
\code{\link{dap_meta}()},
\code{\link{dap_summary}()},
\code{\link{dap_xyzv}()},
\code{\link{dap}()},
\code{\link{extract_sites}()},
\code{\link{get_data}()},
\code{\link{go_get_dap_data}()},
\code{\link{grid_meta}()},
\code{\link{make_ext}()},
\code{\link{make_vect}()},
\code{\link{merge_across_time}()},
\code{\link{parse_date}()},
\code{\link{read_dap_file}()},
\code{\link{read_ftp}()},
\code{\link{time_meta}()},
\code{\link{try_att}()},
\code{\link{var_to_terra}()},
\code{\link{variable_meta}()},
\code{\link{vrt_crop_get}()}
}
\concept{dap}
|
a127f4e3f661b6a4fd53a6a6bf30b3cc257d4b76
|
985070b5dbc05cc0a162389048b24701e2be83b9
|
/src/03_job_scripts/01_helpers/phenotypes.R
|
d6d3f810d2ce1470da21377d8a5ce1d3617bec06
|
[
"MIT"
] |
permissive
|
RezaJF/cardiometabolic_prs_plasma_proteome
|
b284a06aecf7a1d1486fa9d14babf4c0806343f5
|
08799ac3558376ec6e696dfcff56229c54d7199d
|
refs/heads/main
| 2023-03-28T04:08:46.821158
| 2021-02-22T11:13:04
| 2021-02-22T11:13:04
| 351,812,208
| 1
| 0
|
MIT
| 2021-03-26T14:38:16
| 2021-03-26T14:38:15
| null |
UTF-8
|
R
| false
| false
| 693
|
r
|
phenotypes.R
|
library(data.table)
# Not in its own directory so it doesnt get picked up by the polygenic association scan scripts
out_dir <- "analyses/processed_traits"
# Load phenotype data, set identifier to the genetic identifier, and remove blood cell traits
pheno <- fread("data/INTERVAL/project_1074/INTERVALdata_17JUL2018.csv", colClasses=c("identifier"="IID"))
id_map <- fread("data/INTERVAL/project_1074/omicsMap.csv", colClasses="character", na.strings=c("NA", ""))
pheno[id_map, on = .(identifier), IID := Affymetrix_gwasQC_bl]
pheno <- pheno[, c("IID", names(pheno)[1:57], names(pheno)[147:149]), with=FALSE]
fwrite(pheno, file=sprintf("%s/phenotypes.tsv", out_dir), sep="\t", quote=FALSE)
|
4af876e582b8b2478327b7e11a57b66d3c3b1db1
|
dc0dfacaa2d82b87ea71a9e951ab2716d5459dd7
|
/man/baseline.norm.cl.Rd
|
6e5ec3e257a692e30b52cfef5406bdc99dd8b603
|
[] |
no_license
|
navinlabcode/copykat
|
7e797eaad48a5a98883024dc0ee2194f9d7010e0
|
b795ff793522499f814f6ae282aad1aab790902f
|
refs/heads/master
| 2023-09-05T13:42:47.124206
| 2022-09-23T17:43:44
| 2022-09-23T17:43:44
| 231,153,766
| 158
| 53
| null | 2021-03-05T22:20:36
| 2019-12-31T22:45:07
|
R
|
UTF-8
|
R
| false
| true
| 815
|
rd
|
baseline.norm.cl.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/baseline.norm.cl.R
\name{baseline.norm.cl}
\alias{baseline.norm.cl}
\title{find a cluster of diploid cells with integrative clustering method}
\usage{
baseline.norm.cl(norm.mat.smooth, min.cells = 5, n.cores = n.cores)
}
\arguments{
\item{norm.mat.smooth}{smoothed data matrix; genes in rows; cell names in columns.}
\item{min.cells}{minimal number of cells per cluster.}
\item{n.cores}{number of cores for parallel computing.}
}
\value{
1) predefined diploid cell names; 2) clustering results; 3) inferred baseline.
}
\description{
find a cluster of diploid cells with integrative clustering method
}
\examples{
test.bnc <- baseline.norm.cl(norm.mat.smooth=norm.mat.smooth, min.cells=5, n.cores=10)
test.bnc.cells <- test.bnc$preN
}
|
c82e894325ebc9b312242251209cd4c89965750d
|
0ae69401a429092c5a35afe32878e49791e2d782
|
/trinker-lexicon-4c5e22b/man/pos_preposition.Rd
|
5391ec27321d845de737260cba8ae95749408bbf
|
[] |
no_license
|
pratyushaj/abusive-language-online
|
8e9156d6296726f726f51bead5b429af7257176c
|
4fc4afb1d524c8125e34f12b4abb09f81dacd50d
|
refs/heads/master
| 2020-05-09T20:37:29.914920
| 2019-06-10T19:06:30
| 2019-06-10T19:06:30
| 181,413,619
| 3
| 0
| null | 2019-06-05T17:13:22
| 2019-04-15T04:45:06
|
Jupyter Notebook
|
UTF-8
|
R
| false
| true
| 351
|
rd
|
pos_preposition.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pos_preposition.R
\docType{data}
\name{pos_preposition}
\alias{pos_preposition}
\title{Preposition Words}
\format{A character vector with 162 elements}
\usage{
data(pos_preposition)
}
\description{
A dataset containing a vector of common prepositions.
}
\keyword{datasets}
|
6b207386fd879723cc74ff17a512bdebf33f45f0
|
946f724c55b573ef4c0d629e0914bb6bca96f9e9
|
/R/intrinsic2.R
|
047a4a9fdb2f88dd48f56f3334f00bad08e46473
|
[] |
no_license
|
stla/brr
|
84fb3083383e255a56812f2807be72b0ace54fd6
|
a186e16f22b9828c287e3f22891be22b89144ca6
|
refs/heads/master
| 2021-01-18T22:59:46.721902
| 2016-05-30T09:42:14
| 2016-05-30T09:42:14
| 35,364,602
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,214
|
r
|
intrinsic2.R
|
#' Second intrinsic discrepancy
#'
#' Intrinsic discrepancy from \code{phi0} to \code{phi} in the marginal model.
#'
#' @param phi0 the proxy value of \code{phi}
#' @param phi the true value of the parameter
#' @param a,b, the parameters of the prior Gamma distribution on \eqn{\mu}
#' @param S,T sample sizes
#' @return A number, the intrinsic discrepancy from \code{phi0} to \code{phi}.
#' @export
intrinsic2_discrepancy <- function(phi0, phi, a, b, S, T){
tmp <- phi
phi <- pmin(phi,phi0)
phi0 <- pmax(tmp,phi0)
bphi <- phi*S/(T+b)
bphi0 <- phi0*S/(T+b)
N <- log1p(bphi0) - log1p(bphi) # log((bphi0+1)/(bphi+1))
return( a/b*(T+b)*(N+ifelse(bphi<.Machine$double.eps^5, 0, bphi*(N+log(bphi/bphi0)))) )
}
#' @name Intrinsic2Inference
#' @rdname Intrinsic2Inference
#' @title Intrinsic inference on the rates ratio based on the second intrinsic discrepancy.
#'
#' @param a,b,c,d Prior parameters
#' @param S,T sample sizes
#' @param x,y Observed counts
#' @param phi0 the proxy value of \code{phi}
#' @param beta_range logical, if \code{TRUE} (default), an internal method is used to avoid a possible failure in numerical integration; see the main vignette for details
#' @param nsims number of simulations
#' @param conf credibility level
#' @param phi.star the hypothesized value of \code{phi}
#' @param alternative alternative hypothesis, "less" for H1: \code{phi0 < phi.star},
#' "greater" for H1: \code{phi0 > phi.star}
#' @param parameter parameter of interest: relative risk \code{"phi"} or vaccine efficacy \code{"VE"}
#' @param tol accuracy requested
#' @param ... arguments passed to \code{\link{integrate}}
#' @param otol desired accuracy for optimization
#'
#' @return \code{intrinsic2_phi0} returns the posterior expected loss,
#' \code{intrinsic2_estimate} returns the intrinsic estimate,
#' \code{intrinsic2_H0} performs intrinsic hypothesis testing, and
#' \code{intrinsic2_bounds} returns the intrinsic credibility interval.
#'
#' @examples
#' a<-2; b<-10; c<-1/2; d<-0; S<-100; T<-S; x<-0; y<-20
#' intrinsic2_phi0(0.5, x, y, S, T, a, b, c, d)
#' intrinsic2_phi0_sims(0.5, x, y, S, T, a, b, c, d)
#' intrinsic2_estimate(x, y, S, T, a, b, c, d)
#' bounds <- intrinsic2_bounds(x, y, S, T, a, b, c, d, conf=0.95); bounds
#' ppost_phi(bounds[2], a, b, c, d, S, T, x, y)- ppost_phi(bounds[1], a, b, c, d, S, T, x, y)
#'
#' @importFrom stats dbeta integrate optimize
NULL
#'
#' @rdname Intrinsic2Inference
#' @export
intrinsic2_phi0 <- function(phi0, x, y, S, T, a, b, c=0.5, d=0, beta_range=TRUE, tol=1e-8, ...){
post.c <- x+c
post.d <- y+a+d
lambda <- (T+b)/S
return( vapply(phi0, FUN = function(phi0){
f <- function(u) intrinsic2_discrepancy(phi0, lambda * u/(1-u), a=a, b=b, S=S, T=T)
range <- if(beta_range) beta_integration_range(post.c, post.d, f, accuracy=tol) else c(0,1)
integrande <- function(u){
return( f(u)*dbeta(u, post.c, post.d) )
}
I <- integrate(integrande, range[1], range[2], ...)
return(I$value)
}, FUN.VALUE=numeric(1)) )
}
#'
#' @rdname Intrinsic2Inference
#' @export
intrinsic2_phi0_sims <- function(phi0, x, y, S, T, a, b, c=0.5, d=0, nsims=1e6){
post.c <- x+c
post.d <- y+a+d
lambda <- (T+b)/S
sims <- rbeta2(nsims, post.c, post.d, lambda)
return( vapply(phi0, FUN = function(phi0){
return(mean(intrinsic2_discrepancy(phi0, sims, a=a, b=b, S=S, T=T)))
}, FUN.VALUE=numeric(1)) )
}
#'
#' @rdname Intrinsic2Inference
#' @export
intrinsic2_estimate <- function(x, y, S, T, a, b, c=0.5, d=0, otol = 1e-8, ...){
post.cost <- function(u0){
phi0 <- u0/(1-u0)
intrinsic2_phi0(phi0, x, y, S, T, a, b, c, d, ...)
}
optimize <- optimize(post.cost, c(0, 1), tol=otol)
u0.min <- optimize$minimum
estimate <- u0.min/(1-u0.min)
loss <- optimize$objective
out <- estimate
attr(out, "loss") <- loss
return(out)
}
#'
#' @rdname Intrinsic2Inference
#' @export
intrinsic2_H0 <- function(phi.star, alternative, x, y, S, T, a, b, c=0.5, d=0, ...){
post.c <- x+c
post.d <- y+a+d
lambda <- (T+b)/S
integrande <- function(u){
intrinsic2_discrepancy(phi.star, lambda * u/(1-u), S=S, T=T, a=a, b=b)*dbeta(u, post.c, post.d)
}
psi.star <- phi.star/lambda
u.star <- psi.star/(1+psi.star)
bounds <- switch(alternative, less=c(0,u.star), greater=c(u.star, 1))
value <- integrate(integrande, bounds[1], bounds[2], ...)$value
return(value)
}
#'
#' @rdname Intrinsic2Inference
#' @export
intrinsic2_bounds <- function(x, y, S, T, a, b, c=0.5, d=0, conf=.95, parameter="phi", otol = 1e-08, ...){
post.cost <- function(phi0){
intrinsic2_phi0(phi0, x, y, S, T, a, b, c, d, ...)
}
post.icdf <- function(p){
qpost_phi(p, a=a, b=b, c=c, d=d, S=S, T=T, x=x, y=y)
}
conf <- min(conf, 1 - conf)
f <- function(p, post.icdf, conf){
u.phi <- post.icdf(1 - conf + p)
l.phi <- post.icdf(p)
(post.cost(u.phi)-post.cost(l.phi))^2
}
minimize <- optimize(f, c(0, conf), post.icdf = post.icdf,
conf = conf, tol=otol)$minimum
out <- switch(parameter,
phi=c(post.icdf(minimize), post.icdf(1 - conf + minimize)),
VE = sort(1-c(post.icdf(minimize), post.icdf(1 - conf + minimize))))
out
}
|
37b27fa1a641255619cdd38ac0258634f82f8fff
|
120e91e531a48f01e83c6a59bd0344316065ffef
|
/load_ODIN_ECan_data.R
|
750f4c9ed9611e62e147b3f4946b1824ec25dcab
|
[
"MIT"
] |
permissive
|
guolivar/cona
|
0198a82b5be629d39d183070102806e2f57ae8d7
|
63b80d25ce6fc25da8e825a98acdfe2605cff83b
|
refs/heads/master
| 2020-05-21T23:09:48.707117
| 2017-11-09T23:54:30
| 2017-11-09T23:54:30
| 41,452,370
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,881
|
r
|
load_ODIN_ECan_data.R
|
#' ---
#' title: "ODIN CONA"
#' author: "Gustavo Olivares"
#' output: html_document
#' ---
# Load libraries
require('openair')
require('reshape2')
require('ggplot2')
# load_odin data
## ODIN_02.
odin_02 <- read.table("/home/gustavo/data/CONA/ODIN/deployment/odin_02.data",
header=T, quote="")
odin_02$date=as.POSIXct(paste(odin_02$Date,odin_02$Time),tz='NZST')
odin_02$Time<-NULL
odin_02$Date<-NULL
odin_02$Batt<-5*odin_02$Batt/1024
timePlot(odin_02,pollutant = c('Dust','Temperature'), main = 'ODIN 02')
## ODIN_03
odin_03 <- read.table("/home/gustavo/data/CONA/ODIN/deployment/odin_03.data",
header=T, quote="")
odin_03$date=as.POSIXct(paste(odin_03$Date,odin_03$Time),tz='NZST')
odin_03$Time<-NULL
odin_03$Date<-NULL
odin_03$Batt<-5*odin_03$Batt/1024
timePlot(odin_03,pollutant = c('Dust','Temperature'), main = 'ODIN 03')
## ODIN_04
odin_04 <- read.table("/home/gustavo/data/CONA/ODIN/deployment/odin_04.data",
header=T, quote="")
odin_04$date=as.POSIXct(paste(odin_04$Date,odin_04$Time),tz='NZST')
odin_04$Time<-NULL
odin_04$Date<-NULL
odin_04$Batt<-5*odin_04$Batt/1024
timePlot(odin_04,pollutant = c('Dust','Temperature'), main = 'ODIN 04')
## ODIN_05
odin_05 <- read.table("/home/gustavo/data/CONA/ODIN/deployment/odin_05.data",
header=T, quote="")
odin_05$date=as.POSIXct(paste(odin_05$Date,odin_05$Time),tz='NZST')
odin_05$Time<-NULL
odin_05$Date<-NULL
odin_05$Batt<-5*odin_05$Batt/1024
timePlot(odin_05,pollutant = c('Dust','Temperature'), main = 'ODIN 05')
## ODIN_06
odin_06 <- read.table("/home/gustavo/data/CONA/ODIN/deployment/odin_06.data",
header=T, quote="")
#force GMT as the time zone to avoid openair issues with daylight saving switches
#The actual time zone is 'NZST'
odin_06$date=as.POSIXct(paste(odin_06$Date,odin_06$Time),tz='NZST')
odin_06$Time<-NULL
odin_06$Date<-NULL
odin_06$Batt<-5*odin_06$Batt/1024
timePlot(odin_06,pollutant = c('Dust','Temperature'), main = 'ODIN 06')
## ODIN_07.
odin_07 <- read.table("/home/gustavo/data/CONA/ODIN/deployment/odin_07.data",
header=T, quote="")
odin_07$date=as.POSIXct(paste(odin_07$Date,odin_07$Time),tz='NZST')
odin_07$Time<-NULL
odin_07$Date<-NULL
odin_07$Batt<-5*odin_07$Batt/1024
timePlot(odin_07,pollutant = c('Dust','Temperature'), main = 'ODIN 07')
# Load ECan data
download.file(url = "http://data.ecan.govt.nz/data/29/Air/Air%20quality%20data%20for%20a%20monitored%20site%20(Hourly)/CSV?SiteId=5&StartDate=14%2F08%2F2015&EndDate=29%2F09%2F2015",destfile = "ecan_data.csv",method = "curl")
system("sed -i 's/a.m./AM/g' ecan_data.csv")
system("sed -i 's/p.m./PM/g' ecan_data.csv")
ecan_data_raw <- read.csv("ecan_data.csv",stringsAsFactors=FALSE)
ecan_data_raw$date<-as.POSIXct(ecan_data_raw$DateTime,format = "%d/%m/%Y %I:%M:%S %p",tz='NZST')
ecan_data<-as.data.frame(ecan_data_raw[,c('date','PM10.FDMS','Temperature..2m')])
names(ecan_data)<-c('date','PM10.FDMS','Temperature..1m')
## Merging the data
# ECan's data was provided as 10 minute values while ODIN reports every 1 minute so before merging the data, the timebase must be homogenized
names(odin_02)<-c('Dust.02','RH.02','Temperature.02','Batt.02','date')
names(odin_03)<-c('Dust.03','RH.03','Temperature.03','Batt.03','date')
names(odin_04)<-c('Dust.04','RH.04','Temperature.04','Batt.04','date')
names(odin_05)<-c('Dust.05','RH.05','Temperature.05','Batt.05','date')
names(odin_06)<-c('Dust.06','RH.06','Temperature.06','Batt.06','date')
names(odin_07)<-c('Dust.07','RH.07','Temperature.07','Batt.07','date')
odin <- merge(odin_02,odin_03,by = 'date', all = TRUE)
odin <- merge(odin,odin_04,by='date',all=TRUE)
odin <- merge(odin,odin_05,by='date',all=TRUE)
odin <- merge(odin,odin_06,by='date',all=TRUE)
odin <- merge(odin,odin_07,by='date',all=TRUE)
odin_raw <- odin
#######################
|
7542b93e52b67e9f1bd6dc323f46ea6c92ad11b4
|
52b4102632b1c7efa62151499e8e5edd6289861c
|
/code/Coweeta_threshold_testing.R
|
b6299a8e3a8c79661ccf1fb121236c4805bb93c1
|
[] |
no_license
|
phenomismatch/moth-caterpillar-comparison
|
4bbfbb00227fd02a35bc0e185de623db5cd1dddd
|
c82999468c2e9dd4c6af206e32079612fd330a5a
|
refs/heads/master
| 2020-07-08T08:31:52.200714
| 2020-03-16T17:40:11
| 2020-03-16T17:40:11
| 203,619,400
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,765
|
r
|
Coweeta_threshold_testing.R
|
source('../caterpillars-analysis-public/code/analysis_functions.r')
source('code/formatting_coweeta.r')
#Function to filter by year and julian week, then gives the number of weeks that fulfill the designated threshold value and plot
threshold<-function(threshold_value, plot){
cow_thresh<-cowplusnotes%>%
filter(Year>2009, Plot%in% c(plot), TreeSpecies%in% c("American-Chestnut", "Striped-Maple", "Red-Oak", "Red-Maple"))%>%
dplyr::select(Year,Yearday,Plot,Point,TreeSpecies,Sample)%>%
distinct()%>%
group_by(Year,Yearday)%>%
tally()%>%
rename(nSurveys=n)%>%
mutate(JulianWeek=7*floor((Yearday)/7)+4)%>%
#aggregate(cow_thresh$nSurveys,by=list(Year=cow_thresh$Year,cow_thresh$JulianWeek=JWeek),FUN=sum)
group_by(Year,JulianWeek)%>%
summarize(nJulianWeekSurvey=sum(nSurveys))%>%
filter(nJulianWeekSurvey>threshold_value)%>%
#count()
group_by(Year)%>%
add_count()%>%
rename(nWeeks=n)
}
thresh_100<-threshold(100, "BB")
thresh_50<-threshold(50,"BB")
#At this point, I decide to use 50 as the threshold value for both sites, so we can now filter the coweeta dataset and convert into catcount format
#Plot of sample frequency
freq_plot<-function(field_year, field_plot){
group_cow_set<-cowplusnotes%>%
filter(cowplusnotes$Year==field_year, cowplusnotes$Plot==field_plot)%>%
dplyr::select(Plot,Yearday,Point,TreeSpecies,Sample)%>%
distinct()%>%
group_by(Point,Plot,TreeSpecies,Sample,Yearday)%>%
summarise(n())%>%
mutate(freq=(lead(Yearday)-Yearday), gridLetter = substr(Point, 1, 1),
gridY = as.numeric(substr(Point, 2, nchar(Point))),
gridX = which(LETTERS == gridLetter))
par(mfrow = c(6, 5), mar = c(4, 4, 1, 1), mgp = c(2.5, 1, 0))
pdf(paste0("coweeta_plots_",field_year,"_",field_plot,".pdf"))
for (j in unique(group_cow_set$Yearday)) {
tmp = filter(group_cow_set, Yearday == j)
plot(group_cow_set$gridX, group_cow_set$gridY, pch = 16, xlab = "", ylab = "",main="Plot Samples")
}
dev.off()
return(group_cow_set)
}
freq_plot(2010,"BB")
treesByYear = cowplusnotes %>%
filter(Plot != "RK") %>%
dplyr::select(Year, Plot,Yearday,Point,TreeSpecies,Sample)%>%
distinct()%>%
count(Year, TreeSpecies) %>%
arrange(Year, desc(n)) %>%
spread(key = TreeSpecies,value = n, fill = 0)
#pdf("coweeta_tree_surveys_by_year.pdf", height = 11, width = 8)
#par(mfrow = c(length(unique(treesByYear$Year)), 1))
#for (y in unique(treesByYear$Year)) {
# bplot = barplot(as.matrix(treesByYear[treesByYear$Year == y, 4:ncol(treesByYear)]), col = 'darkorchid', xaxt = "n", xlab = "", ylab = "")
#}
#text(bplot, rep(-1, ncol(treesByYear)-4), xpd = TRUE, srt = 45)
#dev.off()
#BBfreq <- NA
#for(i in 2015:2018){
# g<-freq_plot(i,"BB")
# print(g)
#}
#Function to filter coweeta data for field year/plot, then get frequency for each day that was sampled
samp_days<-function(field_year,field_plot){
coweeta_data<-cowplusnotes%>%
filter(cowplusnotes$Year==field_year,cowplusnotes$Plot==field_plot)%>%
dplyr::select(Plot, Yearday, Point,TreeSpecies, Sample)%>%
distinct()%>%
group_by(Plot,Point, Yearday)%>%
summarize(obsv=n())%>%
arrange(Yearday)%>%
mutate(gridLetter=substr(Point,1,1),
gridY=as.numeric(substr(Point,2,nchar(Point))),
gridX=which(LETTERS == gridLetter))
par(mfrow = c(6, 5), mar = c(4, 4, 1, 1), mgp = c(2.5, 1, 0))
plots<-list()
for (i in 1:length(unique(coweeta_data$Yearday))){
tmp = filter(coweeta_data, Yearday == unique(coweeta_data$Yearday)[i])
#plots[[i]]<-ggplot(tmp,aes_string(x=gridX,y=gridY))+geom_point(aes_string(size=n))+xlim(0,26)+ylim(0,max(coweeta_data$gridY))
plots[[i]]<-ggplot()+theme_bw(base_size=12*.3)+
geom_point(aes_string(x=tmp$gridX,y=tmp$gridY,size=tmp$obsv))+
xlim(0,26)+ylim(0,max(coweeta_data$gridY))+theme(legend.text=element_text(size=4), legend.key.size=unit(.5,"cm"))
}
pdf(paste0("coweeta_plots_",field_year,"_",field_plot,".pdf"))
grid.arrange(grobs=plots)
dev.off()
return(coweeta_data)
}
BBsamp10<-samp_days(2010,"BB")
BBsamp11<-samp_days(2011,"BB")
BBsamp12<-samp_days(2012,"BB")
BSsamp12<-samp_days(2012,"BS")
#Histogram of frequency of survey efforts
cow_samples<-cowplusnotes%>%
filter(Year>2009, Plot%in% c("BS", "BB"), TreeSpecies%in% c("American-Chestnut", "Striped-Maple", "Red-Oak", "Red-Maple"))%>%
dplyr::select(Year,Yearday,Plot, Point, TreeSpecies, Sample)%>%
distinct()%>%
count(Year, Yearday)%>%
rename(nSurveys=n)
hist(cow_samples$nSurveys, 20)
# cow_samp_hist<-ggplot(cow_samples,aes(x=Yearday,y=nSurveys))+geom_histogram(stat="identity")
# cow_samp_hist
# fit<-cow_phen%>%
# filter(Year==i)
# gfit1=fitG(x=fit$JulianWeek,y=fit$avg,mu=weighted.mean(fit$JulianWeek,fit$avg),sig=10,scale=150,control=list(maxit=10000),method="L-BFGS-B",lower=c(0,0,0,0,0,0))
# p=gfit1$par
# r2=cor(fit$JulianWeek,p[3]*dnorm(fit$JulianWeek,p[1],p[2]))^2
# totalAvg=sum(fit$avg)
# plot(x=fit$JulianWeek,y=fit$avg,main=i, sub=j,type="l")
#lines(0:365,p[3]*dnorm(0:365,p[1],p[2]),col='blue')
# altpheno<-cow_pheno%>%
# filter(Year==i)
# catsum<-cumsum(altpheno$NumCaterpillars)
# ten<-min(which(catsum>(0.1*sum(altpheno$photos))))
# fifty<-min(which(catsum>(0.5*sum(altpheno$photos))))
# halfcycle<-min(which(fit$avg>0.5*max(fit$avg)))
# abline(v = fit[ten,2], col="red", lwd=3, lty=2)
# abline(v = fit[fifty,2], col="blue", lwd=3, lty=2)
# abline(v = fit[halfcycle,2], col="green", lwd=4, lty=2)
# WeekSurveys<-sum(cowplusnotes$nSurveys)
#ggplot(cow_thresh,aes(x=Yearday,y=nSurveys))+geom_histogram(stat="identity")
#coweeta_data<-cowplusnotes%>%
# filter(cowplusnotes$Year==2010,cowplusnotes$Plot=="BB")%>%
# select(Plot, Yearday, Point, Sample,TreeSpecies)%>%
# distinct()%>%
# group_by(Plot,Point, Yearday)%>%
# summarize(n=n())%>%
#coweeta_data<-cowplusnotes%>%
# filter(cowplusnotes$Year==2010,cowplusnotes$Plot=="BB")%>%
# select(Plot, Yearday, Point, Sample,TreeSpecies)%>%
# distinct()%>%
# group_by(Plot,Point, Yearday)%>%
# summarize(n=n())%>%
# mutate(gridLetter=substr(Point,1,1),
# gridY=as.numeric(substr(Point,2,nchar(Point))),
# gridX=which(LETTERS==gridLetter))
#par(mfrow = c(6, 5), mar = c(4, 4, 1, 1), mgp = c(2.5, 1, 0))
#for (j in unique(coweeta_data$Yearday)){
# tmp=filter(coweeta_data,Yearday==j)
# plot<-ggplot(coweeta_data,aes(x=gridX,y=gridY))+geom_point(aes(size=n))
#}
#aggregate(BBday10$n,by=list(Sampled=BBday10$Yearday),FUN=sum)
sampled_days_BB<-cowplusnotes%>%
filter(cowplusnotes$Plot=="BB",cowplusnotes$TreeSpecies!="8",cowplusnotes$TreeSpecies!="9")%>%
group_by(TreeSpecies)%>%
summarize(n=n())
sampled_days_BS<-cowplusnotes%>%
filter(cowplusnotes$Plot=="BS",cowplusnotes$TreeSpecies!="8",cowplusnotes$TreeSpecies!="9")%>%
group_by(TreeSpecies)%>%
summarize(n=n())
sum(sampled_days_BB$n)
sum(sampled_days_BS$n)
sampled_days_BS<-cowplusnotes%>%
filter(cowplusnotes$Plot=="BS",cowplusnotes$TreeSpecies!="8",cowplusnotes$TreeSpecies!="9")%>%
group_by(TreeSpecies)%>%
summarize(n=n())
#barplot(sampled_days$n, main=sampled_days$n,xlab="",width=1,names.arg=sampled_days$TreeSpecies, ylab="",)
site_plot_BB<-ggplot(data=sampled_days_BB,aes(x=sampled_days_BB$TreeSpecies,y=sampled_days_BB$n))+
geom_bar(stat="identity")+
theme(axis.text.x = element_text( color="black", size=8, angle=45,vjust=1,hjust=1))+
xlab("Tree Species")+
ylab("Number of Samples")
pdf(paste("BB_Tree_Samples.pdf"))
site_plot_BB
dev.off()
site_plot_BS<-ggplot(data=sampled_days_BS,aes(x=sampled_days_BS$TreeSpecies,y=sampled_days_BS$n))+
geom_bar(stat="identity")+
theme(axis.text.x = element_text( color="black", size=8, angle=45,vjust=1,hjust=1))+
xlab("Tree Species")+
ylab("Number of Samples")
pdf(paste0("BS_Tree_Samples.pdf"))
site_plot_BS
dev.off()
#Also we might want to create a plot of the amount of tree species surveyed, as in how many were surveyed, and whether it's the same amount each time.
BBfreq10<-freq_plot(2010, "BB")
BSfreq10<-freq_plot(2010, "BS")
BBfreq11<-freq_plot(2011, "BB")
BBday10<-samp_days(2010,"BB")
Bsday10<-samp_days(2010,"BS")
widecowplusnotes_2010<- grouped_cow_2010%>%
spread(Yearday,'n()',fill=NA,convert=TRUE)%>%
arrange(`136`)
write.csv(widecowplusnotes_2010,'widecowplusnotes_2010.csv')
widecowpointtally<-widecowplusnotes%>%
group_by(Point)%>%
tally()
# Plots examining # visits by grid point by yearday
BBfreq10 = filter(cow_freq_2010, Plot=="BB")
par(mfrow = c(5, 5), mar = c(4, 4, 1, 1), mgp = c(2.5, 1, 0))
for (j in unique(BBfreq10$Yearday)) {
tmp = filter(BBfreq10, Yearday == j)
plot(BBfreq10$gridX, BBfreq10$gridY, pch = 16, xlab = "", ylab = "")
}
|
c84796389e8187dab0f26d0a71950e8c2eb9d9f8
|
681e00803a9d998ab9871fb141e55f0e4036687b
|
/R/FuzzyMatch.R
|
af33aebaaf03233d9f4e65dc7b4086faeae1439c
|
[] |
no_license
|
altingia/evobir
|
8cfdbaa10e0e51e9271386da1ac0f3ae2aa850dc
|
b3912ca77f4e23b6c70f51829bf265451c0dfdd6
|
refs/heads/master
| 2020-03-26T09:05:39.510817
| 2018-06-23T18:47:28
| 2018-06-23T18:47:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,021
|
r
|
FuzzyMatch.R
|
FuzzyMatch <- function(tree, data, max.dist){
if(class(tree)=="multiPhylo"){
warning("Multiple trees were supplied only first is being used")
tree <- tree[[1]]
}
tree.names <- tree$tip.label # lets get the names on the tree
close.taxa <- data.frame()
counter <- 1
data.names <- unique(data)
for(i in 1:length(data.names)){
name.dist <- min(adist(data.names[i], as.character(tree.names)))
if( name.dist <= max.dist & name.dist > 0){
fuq <- which.min(adist(data.names[i], as.character(tree.names)))
close.taxa[counter, 1] <- data.names[i]
close.taxa[counter, 2] <- tree.names[fuq]
close.taxa[counter, 3] <- name.dist
counter <- counter + 1
}
}
if(counter == 1){
cat("Found", counter - 1, "names that were close but imperfect matches\n")
}
if(counter > 1){
cat("Found", counter - 1, "names that were close but imperfect matches\n")
colnames(close.taxa) <- c("name.in.data", "name.in.tree", "differences")
return(close.taxa)
}
}
|
5271edb4a4f47babda8094ff8b39d670bd1637cf
|
8bba25c2a3bc4725ba2a4760eec705fb5338f227
|
/code/2_methods/2_rare variants/2_rvTDT/1_evs.R
|
5493ad9590e8d822630f442d3ff3ba214c4d8fff
|
[] |
no_license
|
lindagai/8q24_project
|
b5852d2c7950f2ccaba0e2f08e3c69d47e3d020e
|
d9bff162b56c55dd3baddac7c2fdfdc6f8dd1386
|
refs/heads/master
| 2021-04-03T08:26:56.634094
| 2019-12-03T14:24:06
| 2019-12-03T14:24:06
| 124,985,924
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,202
|
r
|
1_evs.R
|
ssh -Y lgai@jhpce01.jhsph.edu
#Allocate memory
qrsh -l mem_free=15G,h_vmem=16G,h_fsize=18G
module load R
R
################################
library(dplyr)
library(VariantAnnotation)
################################
##############################
#get raw.evs
filepath.annovar<-"/users/lgai/8q24_project/data/processed_data/annotation/8q24_annovar_report_useful_variables.txt"
filepath.evs.raw<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs/evs.raw.txt"
get.evs.raw(filepath.annovar,filepath.evs.raw)
#get evs for only the SNPs in the vcf:
filepath.evs.raw<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs/evs.raw.txt"
filepath.vcf<-"/users/lgai/8q24_project/data/processed_data/vcfs/rare_var_only/8q24.cleaned.phased.filtered.annotation.rarevar.monomorphs.removed.recode.vcf"
filepath.filtered.geno <- "/users/lgai/8q24_project/data/processed_data/geno_matrix/filtered/8q24.cleaned.phased.filtered.annotation.rarevar.monomorphs.removed.rds"
filepath.evs.filtered<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs/8q24.cleaned.phased.filtered.annotation.rarevar.monomorphs.removed.evs"
get.evs.filtered(filepath.evs.raw,filepath.vcf,filepath.evs.filtered)
##############################
#Scratch
################
# # #TODO: Do this more efficiently :/
# geno<-readRDS(filepath.geno)
# snps<-colnames(geno)
#
# filepath.vcf.snp.pos<-"/users/lgai/8q24_project/data/processed_data/vcf_snp_pos.txt"
# vcf.snp.pos<-read.table(filepath.vcf.snp.pos,sep="\t",quote ="",header=TRUE)
# head(vcf.snp.pos)
# pos<-vcf.snp.pos[vcf.snp.pos$snp %in% snps,"pos"]
################
#annovar filepaths
# filepath.annovar.filt.annotation<-"/users/lgai/8q24_project/data/processed_data/annotation/filtered_annovar/8q24_annovar_report_functional_annnotation.txt"
# filepath.annovar.filt.peak<-"/users/lgai/8q24_project/data/processed_data/annotation/filtered_annovar/8q24_annovar_report_TDT_peak.txt"
# filepath.annovar.filt.both<-"/users/lgai/8q24_project/data/processed_data/annotation/filtered_annovar/8q24_annovar_report_filtered_by_both.txt"
# annovar.filt.filepaths<-c(filepath.annovar.filt.annotation,filepath.annovar.filt.peak,filepath.annovar.filt.both)
#evs filepaths
# filepath.evs.annotation<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs/evs.annotation.txt"
# filepath.evs.peak<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs/evs.peak.txt"
# filepath.evs.both<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs/evs.both.txt"
# evs.filepaths<-c(filepath.evs.annotation,filepath.evs.peak,filepath.evs.both)
#geno filepaths
# filepath.geno.annotation <- "/users/lgai/8q24_project/data/processed_data/geno_matrix/filtered/geno_phased_annotation.rds"
# filepath.geno.peak <-"/users/lgai/8q24_project/data/processed_data/geno_matrix/filtered/geno_phased_peak.rds"
# filepath.geno.both <-"/users/lgai/8q24_project/data/processed_data/geno_matrix/filtered/geno_phased_both.rds"
# filtered.geno.filepaths<-c(filepath.geno.annotation,filepath.geno.peak,filepath.geno.both)
# vcf<-readVcf(filepath.vcf,"hg19")
# pos<- start(rowRanges(vcf))
# pos
> ## Return all 'fixed' fields, "LAF" from 'info' and "GT" from 'geno'
filepath<-"/users/lgai/8q24_project/data/processed_data/vcfs/filtered_by_annotation/8q24.cleaned.phased.filtered.annotation.vcf"
fl <- system.file(file=filepath, package="VariantAnnotation")
svp <- ScanVcfParam(rowRanges="start")
vcf1 <- readVcf(filepath, "hg19", svp)
names(geno(vcf1))
> ## Return all 'fixed' fields, "LAF" from 'info' and "GT" from 'geno'
> svp <- ScanVcfParam(info="LDAF", geno="GT")
> vcf1 <- readVcf(fl, "hg19", svp)
> names(geno(vcf1))
filepath.sm.annovar<-"/users/lgai/8q24_project/data/processed_data/rvTDT/rvTDT_ped.txt"
#file.path("/users","lgai","8q24_project","data","processed_data","annotation","8q24_annovar_report.txt")
annovar_report<-read.table(filepath.sm.annovar,sep="\t",header=TRUE, quote ="")
annovar.filt<-annovar_report %>%
filter(!is.na(Afalt_1000g2015aug_eur)) %>%
filter(TotalDepth>20) %>%
filter(CADDgt20 > 10 | WG_GWAVA_score > 0.4 | WG_EIGEN_score > 4)
dim(annovar.filt)
#TODO: This could be a function
evs.raw<-annovar.filt %>%
mutate(geno0 = (1-Afalt_1000g2015aug_eur)^2) %>%
mutate(geno1 = (1-Afalt_1000g2015aug_eur)*Afalt_1000g2015aug_eur) %>%
mutate(geno2 = (Afalt_1000g2015aug_eur)^2*10000) %>%
select("StartPosition",
"geno2",
"geno1",
"geno0",
"TotalDepth"
)
head(evs.raw)
filepath.evs.raw<-"/users/lgai/rvTDT_test/evs_raw.txt"
write.table(evs.raw, filepath.evs.raw, sep="\t",row.names = FALSE,quote = FALSE)
filepath.cluster<-"/users/lgai/rvTDT_test/evs_raw.txt"
filepath.destination<-" '/Users/lindagai 1/Documents/classes/4th year/2nd term/Research/testing/' "
#On your laptop's R console, if you want to transfer it
scp.command<-paste0("scp lgai@jhpce01.jhsph.edu:", filepath.cluster, " ", filepath.destination)
scp.command
system(scp.command)
#################
#B. Subset to the part contained in your vcf
#TODO: eventually, you should do all this on the cluster
#TODO: add filtering
#Load the raw evs file
filepat.evs.raw<-"/Users/lindagai 1/Documents/classes/4th year/2nd term/Research/testing/evs_raw.txt"
evs.raw<-read.table(filepat.evs.raw,sep="\t",quote ="",header=TRUE,stringsAsFactors=FALSE)
head(evs.raw)
#Get the positions/rsIDs in the vcf
filepath.vcf.snp.pos<-"/Users/lindagai 1/Documents/classes/4th year/2nd term/Research/testing/vcf_snp_positions.txt"
vcf.snp.pos<-read.table(filepath.vcf.snp.pos, header=TRUE)
head(vcf.snp.pos)
#Subset the raw evs to the positions/rsIDs in the vcf and remove position #
evs.processed<-left_join(vcf.snp.pos,evs.raw, by = c("pos" = "StartPosition"))[,-2]
evs.processed$geno0<-evs.processed2$geno0 + 0.0000001
evs.processed$geno1<-evs.processed2$geno1 + 0.0000001
evs.processed$geno2<-evs.processed2$geno1 + 0.0000001
dim(evs.processed)
#filepath.rvTDT.ped<-"/Users/lindagai 1/Documents/classes/4th year/2nd term/Research/testing/rvTDT_ped.txt"
filepath.evs.processed<-"/users/lgai/8q24_project/data/processed_data/rvTDT/evs.processed.txt"
write.table(evs.processed,filepath.evs.processed,sep="\t",quote=FALSE,row.name=FALSE)
|
a68ed9446b20ca4f942246b53ed9c4a8585308fe
|
fde81cadf1e4a84951526027f702b9577d399d0f
|
/tools/ngs/R/annotate-variant.R
|
39cf1cf922f009faec4e32aff9a64cc5eaa9e701
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
oheil/chipster-tools
|
d69a0fae3c2b904e3e521509fa228c2fcdc915cf
|
a74bc97ce05cb2907f812b5fdba689f7a397ec22
|
refs/heads/master
| 2022-12-14T19:07:46.599754
| 2022-12-02T11:36:21
| 2022-12-02T11:36:21
| 51,596,532
| 0
| 0
| null | 2016-02-12T15:20:33
| 2016-02-12T15:20:32
| null |
UTF-8
|
R
| false
| false
| 6,433
|
r
|
annotate-variant.R
|
# TOOL annotate-variant.R: "Annotate variants" (Annotate variants listed in a VCF file using the Bioconductor package VariantAnnotation. Coding, UTR, intronic and promoter variants are annotated, intergenic variants are ignored.)
# INPUT input.vcf: "Sorted or unsorted VCF file" TYPE GENERIC
# OUTPUT all-variants.tsv
# OUTPUT coding-variants.tsv
# OUTPUT OPTIONAL polyphen-predictions.tsv
# PARAMETER genome: "Genome" TYPE [hg19: "Human (hg19\)", hg38: "Human (hg38\)"] DEFAULT hg38 (Reference sequence)
# 31.8.2012 JTT
# 15.11.2012 JTT,EK Uses VariantAnnotation package 1.4.3.
# 01.06.2015 ML Modifications to move the tool to new R version
# 20.7.2015 ML Fixed the problems with different kinds of vcf-files
# 27.7.2015 ML Add hg38
# 09.09.2015 ML Add rsIDs to result table
# 10.09.2015 ML Polyphen predictions
# 28.04.2017 ML Update / fix (changes in readVcf output format)
# 10.6.2018 ML Bug fix
# Read data
library(VariantAnnotation)
vcf<-readVcf("input.vcf", genome)
# vcf@rowData@seqnames@values <- factor(vcf@rowData@seqnames@values)
# Correct the chromosome names:
if(length(grep("chr", vcf@rowRanges@seqnames@values))>=1) {
vcf2<-vcf
rd<-rowRanges(vcf)
} else {
vcf2 <- vcf
seqlevelsStyle(vcf2) <- "UCSC"
rd<-rowRanges(vcf)
rd2 <- rd
seqlevelsStyle(rd2) <- "UCSC"
if(genome=="hg19") {
# Exon isoform database
library("TxDb.Hsapiens.UCSC.hg19.knownGene")
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene
library("BSgenome.Hsapiens.UCSC.hg19")
}
if(genome=="hg38") {
# Exon isoform database
library("TxDb.Hsapiens.UCSC.hg38.knownGene")
txdb <- TxDb.Hsapiens.UCSC.hg38.knownGene
library("BSgenome.Hsapiens.UCSC.hg38")
}
}
# remove mitochonrial DNA (it is causing problems with genome versions)
# vcf2 <- keepSeqlevels(vcf2, seqlevels(vcf2)[1:24])
vcf2 <- keepSeqlevels(vcf2, c("chr1","chr2","chr3","chr4","chr5","chr6","chr7","chr8","chr9","chr10","chr11","chr12","chr13","chr14","chr15","chr16","chr17","chr18","chr19","chr20","chr21","chr22","chrX","chrY"))
txdb2 <- keepSeqlevels(txdb, c("chr1","chr2","chr3","chr4","chr5","chr6","chr7","chr8","chr9","chr10","chr11","chr12","chr13","chr14","chr15","chr16","chr17","chr18","chr19","chr20","chr21","chr22","chrX","chrY"))
# Test if the annotation was correct:
if(all(seqlengths(vcf2) == seqlengths(txdb2))==FALSE){
stop(paste('CHIPSTER-NOTE: You seem to have chosen an unmatching reference genome.'))
}
# Locate all variants
codvar <- locateVariants(vcf2, txdb, CodingVariants())
intvar <- locateVariants(vcf2, txdb, IntronVariants())
utr5var <- locateVariants(vcf2, txdb, FiveUTRVariants())
utr3var <- locateVariants(vcf2, txdb, ThreeUTRVariants())
#intgvar <- locateVariants(vcf2, txdb, IntergenicVariants())
spsgvar <- locateVariants(vcf2, txdb, SpliceSiteVariants())
promvar <- locateVariants(vcf2, txdb, PromoterVariants())
allvar<-c(codvar, intvar, utr5var, utr3var, spsgvar, promvar)
#allvar <- locateVariants(rd, txdb, AllVariants())
allvar2<-as.data.frame(allvar, row.names=1:length(allvar))
colnames(allvar2)<-toupper(colnames(allvar2))
# Get gene annotations from EntrezIDs
ig<-allvar2[!is.na(allvar2$GENEID),]
nig<-allvar2[is.na(allvar2$GENEID),]
library(org.Hs.eg.db)
symbol <- select(org.Hs.eg.db, keys=unique(ig[ig$LOCATION=="coding",]$GENEID), keytype="ENTREZID", columns="SYMBOL")
genename <- select(org.Hs.eg.db, keys=unique(ig[ig$LOCATION=="coding",]$GENEID), keytype="ENTREZID", columns="GENENAME")
ensg <- select(org.Hs.eg.db, keys=unique(ig[ig$LOCATION=="coding",]$GENEID), keytype="ENTREZID", columns="ENSEMBL")
ig2<-merge(ig, symbol, by.x="GENEID", by.y="ENTREZID", all.x=TRUE)
ig3<-merge(ig2, genename, by.x="GENEID", by.y="ENTREZID", all.x=TRUE)
ig4<-merge(ig3, ensg, by.x="GENEID", by.y="ENTREZID", all.x=TRUE)
nig$SYMBOL<-rep(NA, nrow(nig))
nig$GENENAME<-rep(NA, nrow(nig))
nig$ENSEMBL<-rep(NA, nrow(nig))
allvar3<-rbind(ig4, nig)
# Predict coding amino acid changes
# library(BSgenome.Hsapiens.UCSC.hg19)
coding <- predictCoding(vcf2, txdb, seqSource=Hsapiens)
cod<-elementMetadata(coding)
cod2<-as.list(cod)
names(cod2)<-toupper(names(cod2))
# PolyPhen
nms <- names(coding)
idx <- mcols(coding)$CONSEQUENCE == "nonsynonymous"
nonsyn <- coding[idx]
names(nonsyn) <- nms[idx]
rsids <- unique(names(nonsyn)[grep("rs", names(nonsyn), fixed=TRUE)])
library(PolyPhen.Hsapiens.dbSNP131)
pp <- select(PolyPhen.Hsapiens.dbSNP131, keys=rsids, cols=c("PREDICTION", "RSID"))
if(length(pp)>0) {
prediction <- pp[!is.na(pp$PREDICTION), ]
polyphen <- prediction[, c("RSID", "TRAININGSET", "PREDICTION", "BASEDON", "COMMENTS")]
write.table(polyphen, "polyphen-predictions.tsv", col.names=T, row.names=F, sep="\t", quote=FALSE)
}
# cod3<-data.frame(geneID=cod2$GENEID, cdsID=sapply(cod2$CDSID, FUN=function(x) paste(x, collapse=", ")), txID=cod2$TXID, consequence=cod2$CONSEQUENCE, cdsStart=as.data.frame(cod2$CDSLOC)[,1], cdsEnd=as.data.frame(cod2$CDSLOC)[,2], width=as.data.frame(cod2$CDSLOC)[,3], varAllele=as.data.frame(cod2$VARALLELE)[,1], refCodon=as.data.frame(cod2$REFCODON)[,1], varCodon=as.data.frame(cod2$VARCODON)[,1], refAA=as.data.frame(cod2$REFAA)[,1], varAA=as.data.frame(cod2$VARAA)[,1])
cod3<-data.frame(geneID=cod2$GENEID, rsID=names(coding), cdsID=sapply(cod2$CDSID, FUN=function(x) paste(x, collapse=", ")), txID=cod2$TXID, consequence=cod2$CONSEQUENCE, cdsStart=as.data.frame(cod2$CDSLOC)[,1], cdsEnd=as.data.frame(cod2$CDSLOC)[,2], width=as.data.frame(cod2$CDSLOC)[,3], varAllele=as.data.frame(cod2$VARALLELE)[,1], refCodon=as.data.frame(cod2$REFCODON)[,1], varCodon=as.data.frame(cod2$VARCODON)[,1], refAA=as.data.frame(cod2$REFAA)[,1], varAA=as.data.frame(cod2$VARAA)[,1])
symbol <- select(org.Hs.eg.db, keys=as.character(unique(cod3$geneID)), keytype="ENTREZID", columns="SYMBOL")
genename <- select(org.Hs.eg.db, keys=as.character(unique(cod3$geneID)), keytype="ENTREZID", columns="GENENAME")
ensg <- select(org.Hs.eg.db, keys=as.character(unique(cod3$geneID)), keytype="ENTREZID", columns="ENSEMBL")
cod32<-merge(cod3, symbol, by.x="geneID", by.y="ENTREZID", all.x=TRUE)
cod33<-merge(cod32, genename, by.x="geneID", by.y="ENTREZID", all.x=TRUE)
cod34<-merge(cod33, ensg, by.x="geneID", by.y="ENTREZID", all.x=TRUE)
# Write results to disk
write.table(allvar3, "all-variants.tsv", col.names=T, row.names=F, sep="\t", quote=FALSE)
write.table(cod34, "coding-variants.tsv", col.names=T, row.names=F, sep="\t", quote=FALSE)
|
b147c83de5a31f4e1b50211a841f8f3aade94599
|
4ed6dfdbac828314df254c82b9dab547d7167a79
|
/04.ExploratoryDataAnalysis/course_projects/assignment1/plot3.R
|
4ec5e28893abff487d7153adff11cb76e6026a61
|
[] |
no_license
|
minw2828/datasciencecoursera
|
beb40d1c29fc81755a7b1f37fc5559d450b5a9e0
|
e1b1d5d0c660bc434b1968f65c52987fa1394ddb
|
refs/heads/master
| 2021-03-22T00:15:15.147227
| 2015-08-21T07:55:10
| 2015-08-21T07:55:10
| 35,082,087
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,451
|
r
|
plot3.R
|
# /usr/bin/rscript
## Coursera Data Science Certificates
## by Jeff Leek, PhD, Roger D. Peng, PhD, Brian Caffo, PhD
## Johns Hopkins University
##
## 04. Exploratory Data Analysis
##
## Course Project 1
##
## Dataset: Electric power consumption [20Mb]
## https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
##
## Author:
## Min Wang (min.wang@ecodev.vic.gov.au)
##
## Date Created:
## 27 July 2015
##
## Date modified and reason:
##
## Execution:
## Rscript <MODULE_NAME>
download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip",
"electric_power_consumption.zip", method="curl")
unzip("electric_power_consumption.zip")
dat <- read.table("household_power_consumption.txt", sep=";", header=TRUE, na.strings = "?")
dat$Date <- as.Date(dat$Date, "%d/%m/%Y")
data <- dat[which(dat$Date=="2007-02-01" | dat$Date=="2007-02-02"), ]
data <- transform(data, timestamp=as.POSIXct(paste(Date, Time)), "%d/%m/%Y %H:%M:%S")
png("plot3.png")
plot(data$timestamp, data$Sub_metering_1, col="black", type="l", xlab="", ylab="Energy sub metering")
lines(data$timestamp, data$Sub_metering_2, col="red")
lines(data$timestamp, data$Sub_metering_3, col="blue")
legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1","Sub_metering_2", "Sub_metering_3"),
lty=c(1, 1), lwd=c(1, 1), bty="n")
dev.off()
|
96c19e1dae03c94c2d5b8b3d39810f7273361244
|
76687fd358d99e4edb73adae1d5bf20d0582b70c
|
/auxiliary_code_construct_generative_model/main_DGM1_pY_mimicTE.R
|
a0de28538184e2e64cf00246fa3a7c0ff4e840ca
|
[] |
no_license
|
tqian/gst_tmle
|
04008179e38627b06119bf5798f8d75dd845f2e0
|
6031c5aaf2b4339a69434f0fe5576b4ac0c78066
|
refs/heads/master
| 2020-06-19T23:17:30.410011
| 2019-07-25T18:39:14
| 2019-07-25T18:39:14
| 196,910,161
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 931
|
r
|
main_DGM1_pY_mimicTE.R
|
rm(list = ls())
library(ltmle)
source("fcn_DGM.R")
dt100 <- read.csv("data100pts(updated).csv")
dt <- dt100
## Generate twin data set
dtaug <- DGM.step0.twins(dt)
### Now, dt is the original data set, dtaug is the augmented data set
## compute trt effect for dt and dtaug
# without calibration, dtaug has larger treatment effect than dt
compute.unadj(dt) # 0.1215278
compute.ltmle(dt) # 0.1087564
compute.unadj(dtaug) # 0.11
compute.ltmle(dtaug) # 0.11
set.seed(123)
### Use root finding algorithm to find pY, to mimic treatment effect
find.pY(dtaug, nsim = 50000, true_trteff = 0.1215278, direction = "up")
# 0.02955846
# # look at combined
# nsim <- 10000
# dtaug_unadj <- rep(NA, nsim)
#
# for (i in 1:nsim){
# dtaug.cal <- calibrate.TE(dtaug, pY = 0.02955846, direction = "up")
#
# dtaug_unadj[i] <- compute.unadj(dtaug.cal)
# }
#
# mean(dtaug_unadj)
# # 0.121467
|
e654f1e65dd93e634a9592939d63c367a95be414
|
0921ca89e1cfb9eefd2227f417bdb91457895b48
|
/src/spin_example.R
|
4450fe30a806b0e89884eed0f40a442346551d57
|
[] |
no_license
|
BarryDigby/Rscript2html
|
4a6662885c73fff9992d9d7c878ef44bd844930e
|
e7fc2c9ca27c64dd00009b169013f712f83636fa
|
refs/heads/main
| 2023-01-02T22:04:46.294810
| 2020-10-22T09:46:40
| 2020-10-22T09:46:40
| 306,291,043
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 540
|
r
|
spin_example.R
|
#' # This is just an R script
#' ## Rendered to a html report with knitr::spin()
#' * just by adding comments we can make a really nice output
#'
#' > And the code runs just like normal, eg. via `Rscript` after all,
#' __comments__ are just *comments*.
#'
#' ## The report begins here
#+
head(mtcars)
#' ## A chart
#+ fig.width=8, fig.height=8
heatmap(cor(mtcars))
#' ## Some tips
#'
#' 1. Optional chunk options are written using `#+`
#' 1. You can write comments between `/*` and `*/` like C comments
#' (the preceding # is optional)
|
9a99bf560c333850e5d8598a84cc923085966d37
|
dabfc981b18d08363e0688156812c0891d288c9b
|
/cachematrix.R
|
79fe7f2ef6566c70f14a836e846c04f20593be75
|
[] |
no_license
|
ericxue77/ProgrammingAssignment2
|
bcdc54589be98bdebcb743e4b3e453af2ea88f5f
|
5f4c218d81134a422d3bea1bed019257c0852869
|
refs/heads/master
| 2021-01-09T09:34:03.399936
| 2014-12-15T20:25:22
| 2014-12-15T20:25:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 948
|
r
|
cachematrix.R
|
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
## This function will get an input matrix, and then will create the cache for the inverse matrix
makeCacheMatrix <- function(x = matrix()) {
m<-NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinvers <- function(invers) m <<- invers
getinvers <- function() m
list(set = set, get = get,
setinvers = setinvers,
getinvers = getinvers)
}
## Write a short comment describing this function
## This will return the invers matrix.
## If the invers matrix is cached, then it will return from the cache
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinvers()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setinvers(m)
m
}
|
fab84f0c00012cb47d37fa6ca8de6a2054389db7
|
1eee16736f5560821b78979095454dea33b40e98
|
/thirdParty/HiddenMarkov.mod/man/forwardback.Rd
|
e16836781fdc96519faedd9987f41456a60d443e
|
[] |
no_license
|
karl616/gNOMePeaks
|
83b0801727522cbacefa70129c41f0b8be59b1ee
|
80f1f3107a0dbf95fa2e98bdd825ceabdaff3863
|
refs/heads/master
| 2021-01-21T13:52:44.797719
| 2019-03-08T14:27:36
| 2019-03-08T14:27:36
| 49,002,976
| 4
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,013
|
rd
|
forwardback.Rd
|
\name{forwardback}
\alias{forwardback}
\alias{forward}
\alias{backward}
\alias{forwardback.dthmm}
\title{Forward and Backward Probabilities of DTHMM}
\description{
These functions calculate the forward and backward probabilities for a \code{\link{dthmm}} process, as defined in MacDonald & Zucchini (1997, Page 60).
}
\usage{
backward(x, Pi, distn, pm, pn = NULL)
forward(x, Pi, delta, distn, pm, pn = NULL)
forwardback(x, Pi, delta, distn, pm, pn = NULL, fortran = TRUE)
forwardback.dthmm(Pi, delta, prob, fortran = TRUE, fwd.only = FALSE)
}
\arguments{
\item{x}{is a vector of length \eqn{n} containing the observed process.}
\item{Pi}{is the \eqn{m \times m}{m*m} transition probability matrix of the hidden Markov chain.}
\item{delta}{is the marginal probability distribution of the \eqn{m} hidden states.}
\item{distn}{is a character string with the distribution name, e.g. \code{"norm"} or \code{"pois"}. If the distribution is specified as \code{"wxyz"} then a probability (or density) function called \code{"dwxyz"} should be available, in the standard \R format (e.g. \code{\link{dnorm}} or \code{\link{dpois}}).}
\item{pm}{is a list object containing the current (Markov dependent) parameter estimates associated with the distribution of the observed process (see \code{\link{dthmm}}).}
\item{pn}{is a list object containing the observation dependent parameter values associated with the distribution of the observed process (see \code{\link{dthmm}}).}
\item{prob}{an \eqn{n \times m}{n*m} matrix containing the observation probabilities or densities (rows) by Markov state (columns).}
\item{fortran}{logical, if \code{TRUE} (default) use the Fortran code, else use the \R code.}
\item{fwd.only}{logical, if \code{FALSE} (default) calculate both forward and backward probabilities; else calculate and return only forward probabilities and log-likelihood.}
}
\value{
The function \code{forwardback} returns a list with two matrices containing the forward and backward (log) probabilities, \code{logalpha} and \code{logbeta}, respectively, and the log-likelihood (\code{LL}).
The functions \code{backward} and \code{forward} return a matrix containing the forward and backward (log) probabilities, \code{logalpha} and \code{logbeta}, respectively.
}
\details{
Denote the \eqn{n \times m}{n*m} matrices containing the forward and backward probabilities as \eqn{A} and \eqn{B}, respectively. Then the \eqn{(i,j)}th elements are
\deqn{
\alpha_{ij} = \Pr\{ X_1 = x_1, \cdots, X_i = x_i, C_i = j \}
}{
alpha_{ij} = Pr{ X_1 = x_1, ..., X_i = x_i, C_i = j }
}
and
\deqn{
\beta_{ij} = \Pr\{ X_{i+1} = x_{i+1}, \cdots, X_n = x_n \,|\, C_i = j \} \,.
}{
beta_{ij} = Pr{ X_{i+1} = x_{i+1}, ..., X_n = x_n | C_i = j } .
}
Further, the diagonal elements of the product matrix \eqn{A B^\prime}{AB'} are all the same, taking the value of the log-likelihood.
}
\author{The algorithm has been taken from Zucchini (2005).}
\seealso{
\code{\link{logLik}}
}
\references{
Cited references are listed on the \link{HiddenMarkov} manual page.
}
\examples{
# Set Parameter Values
Pi <- matrix(c(1/2, 1/2, 0, 0, 0,
1/3, 1/3, 1/3, 0, 0,
0, 1/3, 1/3, 1/3, 0,
0, 0, 1/3, 1/3, 1/3,
0, 0, 0, 1/2, 1/2),
byrow=TRUE, nrow=5)
p <- c(1, 4, 2, 5, 3)
delta <- c(0, 1, 0, 0, 0)
#------ Poisson HMM ------
x <- dthmm(NULL, Pi, delta, "pois", list(lambda=p), discrete=TRUE)
x <- simulate(x, nsim=10)
y <- forwardback(x$x, Pi, delta, "pois", list(lambda=p))
# below should be same as LL for all time points
print(log(diag(exp(y$logalpha) \%*\% t(exp(y$logbeta)))))
print(y$LL)
#------ Gaussian HMM ------
x <- dthmm(NULL, Pi, delta, "norm", list(mean=p, sd=p/3))
x <- simulate(x, nsim=10)
y <- forwardback(x$x, Pi, delta, "norm", list(mean=p, sd=p/3))
# below should be same as LL for all time points
print(log(diag(exp(y$logalpha) \%*\% t(exp(y$logbeta)))))
print(y$LL)
}
\keyword{distribution}
|
7a5de2f11525a36c237088fe4dbcb03cae1d1419
|
788f5854c1c23cee0ea77238ffad7dcdcf9683c2
|
/inst/bn/tests/mytest.R
|
63ed71e3b3d0ae74f04e060222e7fc8db19b8696
|
[
"Apache-2.0"
] |
permissive
|
paulgovan/BayesianNetwork
|
78b6978f43f9163b6de05338d7cf2270ffbf2768
|
b0094d79234ba8b4db61203c0318b2fbb34c372d
|
refs/heads/master
| 2023-08-04T13:05:45.085458
| 2023-07-15T21:21:12
| 2023-07-15T21:21:12
| 42,831,223
| 118
| 46
| null | null | null | null |
UTF-8
|
R
| false
| false
| 945
|
r
|
mytest.R
|
app <- ShinyDriver$new("../", seed = 123)
app$snapshotInit("mytest")
app$snapshot()
Sys.sleep(2)
app$setInputs(sidebarMenu = "structure")
Sys.sleep(4)
app$snapshot()
app$setInputs(net = "3")
app$setInputs(alg = "hc")
app$setInputs(type = "aic")
app$setInputs(sidebarMenu = "parameters")
Sys.sleep(1)
app$snapshot()
app$setInputs(met = "bayes")
app$setInputs(param = "dotplot")
app$setInputs(Node = "PCWP")
app$setInputs(sidebarMenu = "inference")
Sys.sleep(1)
app$snapshot()
app$setInputs(evidenceNode = "PCWP")
app$setInputs(evidence = "HIGH")
app$setInputs(event = "HIST")
app$setInputs(sidebarMenu = "measures")
app$setInputs(nodeMeasure = "nbr")
app$setInputs(nodeMeasure = "parents")
app$setInputs(nodeNames = "PCWP")
app$setInputs(dendrogram = "row")
app$setInputs(sidebarMenu = "editor")
app$setInputs(bookmark = "click")
app$setInputs(sidebarMenu = "structure")
app$setInputs(dataInput = "2")
app$uploadFile(file = "learning_test.csv")
|
4a020f890f12c0f6bd28679f9ac293131744dd08
|
af550edba65daf05752ed515b830e4ffce9de7f7
|
/man/plot.rmtfit.Rd
|
0b55f8613aef333a7515f859f167b7edda6e1623
|
[] |
no_license
|
cran/rmt
|
01bf3ccebbc134edab9f2034b282beae1e1454f9
|
16616c69c55ba10e42908d0afd77bc0c07c46dd5
|
refs/heads/master
| 2023-05-06T03:59:19.202575
| 2021-05-25T05:40:03
| 2021-05-25T05:40:03
| 370,748,790
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 2,117
|
rd
|
plot.rmtfit.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/generic.R
\name{plot.rmtfit}
\alias{plot.rmtfit}
\title{Plot the estimated treatment effect curve}
\usage{
\method{plot}{rmtfit}(
x,
k = NULL,
conf = FALSE,
main = NULL,
xlim = NULL,
ylim = NULL,
xlab = "Follow-up time",
ylab = "Restricted mean time in favor",
conf.col = "black",
conf.lty = 3,
...
)
}
\arguments{
\item{x}{An object returned by \code{\link{rmtfit}}.}
\item{k}{If specified, \eqn{\mu_k(\tau)} is plotted; otherwise, \eqn{\mu(\tau)} is plotted.}
\item{conf}{If TRUE, 95\% confidence limits for the target curve are overlaid.}
\item{main}{A main title for the plot}
\item{xlim}{The x limits of the plot.}
\item{ylim}{The y limits of the plot.}
\item{xlab}{A label for the x axis, defaults to a description of x.}
\item{ylab}{A label for the y axis, defaults to a description of y.}
\item{conf.col}{Color for the confidence limits if \code{conf=TRUE}.}
\item{conf.lty}{Line type for the confidence limits if \code{conf=TRUE}.}
\item{...}{Other arguments that can be passed to the underlying \code{plot} method.}
}
\value{No return value, called for side effects.}
\description{
Plot the estimated overall or stage-wise restricted mean times in favor of treatment as a
function of follow-up time.
}
\examples{
# load the colon cancer trial data
library(rmt)
head(colon_lev)
# fit the data
obj=rmtfit(ms(id,time,status)~rx,data=colon_lev)
# plot overal effect mu(tau)
plot(obj)
# set-up plot parameters
oldpar <- par(mfrow = par("mfrow"))
par(mfrow=c(1,2))
# Plot of component-wise RMT in favor of treatment over time
plot(obj,k=2,conf=TRUE,col='red',conf.col='blue', xlab="Follow-up time (years)",
ylab="RMT in favor of treatment (years)",main="Survival")
plot(obj,k=1,conf=TRUE,col='red',conf.col='blue', xlab="Follow-up time (years)",
ylab="RMT in favor of treatment (years)",main="Pre-relapse")
par(oldpar)
}
\seealso{
\code{\link{rmtfit}}, \code{\link{summary.rmtfit}}, \code{\link{bouquet}}.
}
\keyword{rmtfit}
|
8b0ddc0e615605ac432ad549e3770b72fecaaf43
|
251a3940e544dd6277fbdbc9f5cfebd53f98d3af
|
/man/count..Rd
|
c2966451a8e20c2faddb6ddf8be822eaa277164f
|
[
"MIT"
] |
permissive
|
lionel-/tidytable
|
641c45c6a367a17b8ece2babfeb27b89ca0e101b
|
72c29f0e14d96343ba6e5dcd0517f7032d67c400
|
refs/heads/master
| 2022-07-11T22:33:29.352960
| 2020-05-10T18:33:10
| 2020-05-10T18:33:10
| 263,058,395
| 0
| 0
|
NOASSERTION
| 2020-05-11T13:59:12
| 2020-05-11T13:59:11
| null |
UTF-8
|
R
| false
| true
| 649
|
rd
|
count..Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/count.R
\name{count.}
\alias{count.}
\alias{dt_count}
\title{Count observations by group}
\usage{
count.(.data, ...)
dt_count(.data, ...)
}
\arguments{
\item{.data}{A data.frame or data.table}
\item{...}{Columns to group by. \code{tidyselect} compatible.}
}
\description{
Returns row counts of the dataset. If bare column names are provided, \code{count.()} returns counts by group.
}
\examples{
example_df <- tidytable(
x = 1:3,
y = 4:6,
z = c("a", "a", "b"))
example_df \%>\%
count.()
example_df \%>\%
count.(z)
example_df \%>\%
count.(is.character)
}
|
d771f7df480438057780d49b75e4d58bef879cfd
|
eeadff12f42f4393bfc48136f33c9fb59fa96fde
|
/man/KmerCount.Rd
|
9ac50b72aef508a520b3701b7b73ca8a6ae4e4ce
|
[] |
no_license
|
larssnip/microclass
|
654c2b6f3ca3b517a9cfb6f149f91dbba02e0267
|
7e549a441003b1e806061cb47a85fea2377fc0e6
|
refs/heads/master
| 2023-07-12T03:01:04.095770
| 2023-06-29T11:49:10
| 2023-06-29T11:49:10
| 99,898,801
| 3
| 3
| null | 2023-06-01T14:45:24
| 2017-08-10T08:16:07
|
R
|
UTF-8
|
R
| false
| true
| 1,048
|
rd
|
KmerCount.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/KmerCount.R
\name{KmerCount}
\alias{KmerCount}
\title{K-mer counting}
\usage{
KmerCount(sequences, K = 1, col.names = FALSE)
}
\arguments{
\item{sequences}{Vector of sequences (text).}
\item{K}{Word length (integer).}
\item{col.names}{Logical indicating if the words should be added as columns names.}
}
\value{
A matrix with one row for each sequence in \code{sequences} and one column for
each possible word of length\code{K}.
}
\description{
Counting overlapping words of length K in DNA/RNA sequences.
}
\details{
For each input sequence, the frequency of every word of length \code{K} is counted.
Counting is done with overlap. The counting itself is done by a C++ function.
With \code{col.names = TRUE} the K-mers are added as column names, but this makes the
computations slower.
}
\examples{
KmerCount("ATGCCTGAACTGACCTGC", K = 2)
}
\seealso{
\code{\link{multinomTrain}}, \code{\link{multinomClassify}}.
}
\author{
Kristian Hovde Liland and Lars Snipen.
}
|
d105ee9bb8d4ae326929a8911f7ef0630ed7df76
|
5341f4511794b81b66ac2ab41008b3ceb05e62ad
|
/R/search_pubmed.R
|
d798d5d47c23a035268eb2f158b40655200f3720
|
[] |
no_license
|
kamclean/impactr
|
f96d281ce114e14035a1f9b2869a0db7af14bd97
|
b15f2a072c46f939537a9c90d0acb06e6963639b
|
refs/heads/master
| 2022-12-23T01:15:03.958208
| 2022-12-13T19:56:46
| 2022-12-13T19:56:46
| 194,408,033
| 9
| 2
| null | 2020-02-16T15:41:07
| 2019-06-29T13:21:00
|
R
|
UTF-8
|
R
| false
| false
| 2,924
|
r
|
search_pubmed.R
|
# search_pubmed------------------------------
# Documentation
#' Perform a focused pubmed search to identify the PMID associated with specified authors or registry identifiers.
#' @description Search pubmed to identify PMID associated with specified authors or registry identifiers.
#' @param search_type Type of search desired (either "author" or "registry_id").
#' @param search_list Vector of search terms (either author last name and initial, or registry identifers).
#' @param date_min String of a date in "Year-Month-Day" format to provide a lower limit to search within (default = NULL).
#' @param date_max String of a date in "Year-Month-Day" format to provide an upper limit to search within (default = current date).
#' @param keywords Vector of keywords or patterns that are required to be present for inclusion (default = NULL).
#' @return Vector of pubmed identifiers (PMID)
#' @import magrittr
#' @import dplyr
#' @import RCurl
#' @import lubridate
#' @import tibble
#' @import jsonlite
#' @import stringr
#' @export
search_pubmed <- function(search_type = "author", search_list, date_min=NULL, date_max=Sys.Date(),keywords = NULL){
# The E-utilities In-Depth: Parameters, Syntax and More (https://www.ncbi.nlm.nih.gov/books/NBK25499/)
require(dplyr); require(lubridate); require(RCurl); require(jsonlite); require(stringr)
url_search <- "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&esearch.fcgi?db=pubmed"
return_format = "&retmode=json&retmax=100000"
if(is.null(keywords)==F){keywords <- keywords %>%
stringr::str_replace(" AND ", "+AND+") %>%
stringr::str_replace(" OR ", "+OR+") %>%
stringr::str_replace(" NOT ", "+NOT+") %>%
stringr::str_replace("\\?", "%3F") %>%
paste0("(", ., ")") %>% paste(collapse = "+OR+") %>% paste0("AND(",.,")")}
search_list <- tolower(search_list)
search_list <- unique(stringr::str_extract_all(search_list, "^[a-z]+ [a-z]")) %>% unlist()
if(search_type == "author"){search_list_formatted <- gsub(" ",
"%20",
paste0("&term=(",paste(search_list, collapse = '[author]+OR+'), '[author])'))}
if(search_type == "registry_id"){search_list_formatted <- paste0("&term=",
paste(paste0(search_list,"%5BSecondary%20Source%20ID%5D"), collapse = "+OR+"))}
limit_date = NULL
if(is.null(date_min)==F){date_min <- paste0("&mindate=", format(lubridate::as_date(date_min), "%Y/%m/%d"))}
if(is.null(date_max)==F){date_max <- paste0("&maxdate=", format(lubridate::as_date(date_max), "%Y/%m/%d"))}
limit_date = paste0("&datetype=pdat", date_min, date_max)
search <- RCurl::getURL(paste0(url_search, limit_date, search_list_formatted, keywords, return_format)) %>%
jsonlite::fromJSON()
return(search$esearchresult$idlist)}
|
7c7f6ec4f2bbb80e2d86af238769c07e9b18bae9
|
aca48d46c64bb105b10b6cab1a30dcc5bd76eb50
|
/R script_v3/Time_frequency_User.R
|
c28db5b8f86304349269ead7bc3f40c4bac57994
|
[] |
no_license
|
Inkdit/Codes_Yile
|
395cb66f7abbacafe7eb00713b10c1a8abb29236
|
fa830cd1baee5848f6ab9d34a136477156713462
|
refs/heads/master
| 2021-01-11T02:37:39.257104
| 2016-10-13T21:57:27
| 2016-10-13T21:57:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,252
|
r
|
Time_frequency_User.R
|
rm(list = ls())
setwd("G:\\Codes\\Text_Mining\\R script_v3")
library(RPostgreSQL)
source("Time_Interval_Generator.R")
TimeGen <- function(Year = 2011, Month = 1, Day = 1){
return(paste("'", as.character(Year), "-", as.character(Month), "-", as.character(Day), "'", sep=""))
}
source("User_Frequency.R")
FrequentList = FrequentUser(100)
n = 20
Interval_FreqCount <- function(Time1, Time2){
QueryC = paste("SELECT creator_id, created_at FROM contracts WHERE created_at BETWEEN ", Time1, " AND ", Time2, "AND creator_id =" , as.character(FrequentList[nrow(FrequentList)-n+1, 1]) ,
" ORDER BY created_at")
drv <- dbDriver("PostgreSQL")
conn <- dbConnect(drv, dbname = "Inkdit", user = "postgres", password = "314159")
result_temp <- dbGetQuery(conn, QueryC)
dbDisconnect(conn)
return(result_temp)
}
Year1 = 2011
Month1 = 10
Year2 = 2016
Month2 = 10
A = Time_Generator(c(Year1, Month1), c(Year2, Month2))
d = 0
for(i in 1:(nrow(A)-1)){
a = Interval_FreqCount(TimeGen(A[i, 1], A[i, 2]), TimeGen(A[i+1, 1], A[i+1, 2]))
temp = nrow(a)
print(temp)
d = c(d, temp)
}
x = 1:(length(d)-1)
y = d[2:length(d)]
plot(x, y, xaxt = "n", xlab='Month')
axis(1,at = 1:length(d), labels = A[,2])
lines(x,predict(loess(y~x)))
|
56e228d01f22b582046aa6d90b1ded2893ab5a5f
|
caf99a85f73911f5215f1a136735bf01a8444843
|
/drug_name_generator.r
|
640a053755fa5df6807f2718d849c302fc267cd4
|
[] |
no_license
|
CrumpLab/MinervaReasoning
|
289b0ca046451f535031cf8feda12f6b09c2e622
|
bc214ea6245e6f2bc807eef136b2db03caf15dc1
|
refs/heads/master
| 2020-07-05T09:03:48.314112
| 2019-09-03T20:13:14
| 2019-09-03T20:13:14
| 202,600,744
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,480
|
r
|
drug_name_generator.r
|
# Drug name generator
library(tidyverse)
# 40 common drug names, with the beginings and endings split
drugs <- data.frame(stringsAsFactors=FALSE,
Original = c("Acetaminophen", "Adderall", "Alprazolam", "Amitriptyline",
"Amlodipine", "Amoxicillin", "Ativan", "Atorvastatin",
"Azithromycin", "Ciprofloxacin", "Citalopram", "Clindamycin",
"Clonazepam", "Codeine", "Cyclobenzaprine", "Cymbalta", "Doxycycline",
"Gabapentin", "Hydrochlorothiazide", "Ibuprofen", "Lexapro",
"Lisinopril", "Loratadine", "Lorazepam", "Losartan", "Lyrica",
"Meloxicam", "Metformin", "Metoprolol", "Naproxen", "Omeprazole",
"Oxycodone", "Pantoprazole", "Prednisone", "Tramadol", "Trazodone",
"Viagra", "Wellbutrin", "Xanax", "Zoloft"),
First = c("Aceta", "Adde", "Alpra", "Amitri", "Amlo", "Amoxi", "Ati",
"Atorva", "Azithro", "Cipro", "Citalo", "Clinda", "Clona",
"Co", "Cyclo", "Cym", "Doxy", "Gaba", "Hydro", "Ibu", "Lexa",
"Lisino", "Lorata", "Loraze", "Losa", "Lyri", "Melo", "Metfo",
"Meto", "Napro", "Ome", "Oxy", "Panto", "Predni", "Trama", "Trazo",
"Via", "Wellbu", "Xa", "Zo"),
Last = c("minophen", "rall", "zolam", "ptyline", "dipine", "cillin",
"van", "statin", "mycin", "floxacin", "pram", "mycin",
"zepam", "deine", "benzaprine", "balta", "cycline", "pentin",
"thiazide", "profen", "pro", "pril", "dine", "pam", "tan", "ca", "xicam",
"rmin", "prolol", "xen", "prazole", "codone", "prazole",
"sone", "dol", "done", "gra", "trin", "nax", "loft")
)
# create new drug names by recombining first and last parts, take only new and unique combinations
new_first <- rep(drugs$First,40)
new_last <- rep(drugs$Last, each=40)
new_drugs <- paste(new_first,new_last, sep="")
new_drugs <- new_drugs[new_drugs %in% drugs$Original == FALSE]
new_drugs <- unique(new_drugs)
# sample enough unique drug names to cover the experiment
sample_drugs <- sample(new_drugs, 22*3)
# stimulus generator
# create dataframe to code and assign stimuli
general_design <- data.frame(stringsAsFactors=FALSE,
premise_one = c("A+", "A+", "A-", "A-", "AB+", "AB-", "AB+", "AB-", "A+",
"A-", "AB+", "AB-", "C+", "C-", "C+",
"C+", "C-", "C-", "AB+", "AB-", "AB+",
"AB-"),
premise_two = c("AB+", "AB-", "AB+", "AB-", "A+", "A+", "A-", "A-", NA,
NA, NA, NA, NA, NA, "AB+", "AB-", "AB+",
"AB-", "C+", "C+", "C-", "C-"),
Question_type = c("experimental", "experimental", "experimental",
"experimental", "experimental",
"experimental", "experimental", "experimental",
"control", "control", "control", "control",
"control", "control", "control",
"control", "control", "control", "control",
"control", "control", "control")
) %>%
mutate(drug_one = str_replace(premise_one,"[+-]",""),
drug_two = str_replace(premise_two,"[+-]",""),
drug_A = sample_drugs[1:22],
drug_B = sample_drugs[23:44],
drug_C = sample_drugs[45:66],
p1_outcome = as.factor(str_detect(premise_one,"[+]")),
p2_outcome = as.factor(str_detect(premise_two,"[+]"))) %>%
mutate(p1_wording = factor(p1_outcome,labels=c("not cured","cured")),
p2_wording = factor(p2_outcome,labels=c("not cured","cured")),
p1_sentence = NA,
p2_sentence = NA,
p1_question = list(NA),
p2_question = list(NA))
# write the premise and question for each trial
for(i in 1:dim(general_design)[1]){
# write drug one premise
if (general_design$drug_one[i] == "A") {
premise <- paste("People who took",
general_design$drug_A[i],"were",
general_design$p1_wording[i])
question <- paste("How well does", general_design$drug_A[i],"work?")
}
if (general_design$drug_one[i] == "B") {
premise <- paste("People who took",
general_design$drug_B[i],"were",
general_design$p1_wording[i])
question <- paste("How well does", general_design$drug_B[i],"work?")
}
if (general_design$drug_one[i] == "AB") {
premise <- paste("People who took",
general_design$drug_A[i],"and",
general_design$drug_B[i],"were",
general_design$p1_wording[i])
question <- c(paste("How well does", general_design$drug_A[i],"work?"),
paste("How well does", general_design$drug_B[i],"work?"),
paste("How well does the combination of",
general_design$drug_A[i],"and",
general_design$drug_B[i],"work?")
)
}
if (general_design$drug_one[i] == "C") {
premise <- paste("People who took",
general_design$drug_C[i],"were",
general_design$p1_wording[i])
question <- paste("How well does", general_design$drug_C[i],"work?")
}
general_design$p1_sentence[i] <- premise
general_design$p1_question[[i]] <- question
# write drug two premise
if (is.na(general_design$drug_two[i])) {
premise <- NA
question <- NA}
else{
if (general_design$drug_two[i] == "A") {
premise <- paste("People who took",
general_design$drug_A[i],"were",
general_design$p2_wording[i])
question <- paste("How well does", general_design$drug_A[i],"work?")
}
if (general_design$drug_two[i] == "B") {
premise <- paste("People who took",
general_design$drug_B[i],"were",
general_design$p2_wording[i])
question <- paste("How well does", general_design$drug_B[i],"work?")
}
if (general_design$drug_two[i] == "AB") {
premise <- paste("People who took",
general_design$drug_A[i],"and",
general_design$drug_B[i],"were",
general_design$p2_wording[i])
question <- c(paste("How well does", general_design$drug_A[i],"work?"),
paste("How well does", general_design$drug_B[i],"work?"),
paste("How well does the combination of",
general_design$drug_A[i],"and",
general_design$drug_B[i],"work?")
)
}
if (general_design$drug_two[i] == "C") {
premise <- paste("People who took",
general_design$drug_C[i],"were",
general_design$p2_wording[i])
question <- paste("How well does", general_design$drug_B[i],"work?")
}
}
general_design$p2_sentence[i] <- premise
general_design$p2_question[[i]] <- question
}
# create unique list of questions for each set of premises
general_design <- general_design %>%
mutate(all_questions = list(NA),
num_questions = 0,
q1 = NA,
q2 = NA,
q3 = NA,
q4 = NA)
for(i in 1:dim(general_design)[1]){
all_questions <- c(general_design$p1_question[[i]],general_design$p2_question[[i]])
all_questions <- all_questions[!is.na(all_questions)]
all_questions <- unique(all_questions)
general_design$all_questions[[i]] <- all_questions
general_design$num_questions[i] <- length(all_questions)
general_design$q1[i] <- all_questions[1]
general_design$q2[i] <- all_questions[2]
general_design$q3[i] <- all_questions[3]
general_design$q4[i] <- all_questions[4]
}
general_design <- general_design %>%
mutate(stimulus = paste(premise_one,premise_two,sep=","))
library(xprmntr)
stimulus_json <- stimulus_df_to_json(general_design,
stimulus= "stimulus",
data = c("premise_one","premise_two",
"p1_outcome","p2_outcome",
"p1_sentence","p2_sentence",
"q1","q2","q3","q4"))
|
b21c945d48c3f3f9de834c0eeb37557302d9599b
|
476c57e42c9361abaa79ffe1d82acda81a0cc402
|
/7.quality traits/1.ANOVA/stripchart.R
|
c3f9c518996a811f4f3d0e54d250c5f652672e57
|
[] |
no_license
|
zzl2516/Using-gut-microbiota-to-predict-origins-and-qualities-of-cultured-sea-cucumbers
|
210566d207d537f0e05ab64a7a25bcc79c021d9b
|
a0ac3450f052c69dc71038c948bc1d6c0b1256a7
|
refs/heads/main
| 2023-03-29T21:05:01.014582
| 2021-03-13T05:54:39
| 2021-03-13T05:54:39
| 347,279,463
| 3
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,922
|
r
|
stripchart.R
|
class <- read.table("nutrition.txt",header = TRUE,sep = "\t")
colnames(class) <- c("Group","Protein (%)","Fat (%)","Sugar (%)",
"Saponin (g/kg)","Collagen (g/kg)","VA (μg/kg)","VE (mg/kg)",
"Taurine (g/kg)","CS (mg/kg)")
library(dplyr)
library(ggplot2)
library(reshape2)
bb <- class
bb1 <- melt(class)
cbbPalette <- c("#B2182B","#E69F00","#56B4E9","#009E73","#F0E442","#0072B2",
"#D55E00","#CC79A7","#CC6666","#9999CC","#66CC99","#99999",
"#ADD1E5")
bb$Group <- factor(bb$Group,levels = c("BCD","WFD","JZ","SZ","DY","YT","QD","XP"),
labels = c("DLE","DLW","JZ","QHD","DY","YT","QD","XP"))
bb1$Group <- factor(bb1$Group,levels = c("BCD","WFD","JZ","SZ","DY","YT","QD","XP"),
labels = c("DLE","DLW","JZ","QHD","DY","YT","QD","XP"))
library(multcomp)
bb.sample <- colnames(bb)[2:ncol(bb)]
test.b <- c()
for (i in bb.sample) {
fit1 <- aov(as.formula(sprintf("`%s` ~ Group",i)),
data = bb)
tuk1<-glht(fit1,linfct=mcp(Group="Tukey"))
res1 <- cld(tuk1,alpah=0.05)
test.b <- cbind(test.b,res1$mcletters$Letters)
}
colnames(test.b) <- colnames(bb)[2:ncol(bb)]
test.b <- melt(test.b)
colnames(test.b) <- c("Group","variable","value")
library(tidyverse)
test.b1 <- bb %>% gather(variable,value,-Group) %>% group_by(variable,Group) %>%
summarise(Max = max(value))
test.b11 <- dcast(test.b1,Group~variable)
for (i in 2:ncol(test.b11)) {
test.b11[,i] <- test.b11[,i] + max(test.b11[,i])*0.05
}
test.b11 <- melt(test.b11)
test.b1 <- merge(test.b1,test.b11,by = c("variable","Group"))
test.b2 <- merge(test.b,test.b1,by = c("variable","Group"))
png("nutrition_anova.png",width = 6400,height = 5000,res = 600)
ggplot(bb1,aes(x = Group,y = value,color = Group)) +
geom_boxplot(color = "black",outlier.colour = NA) +
geom_jitter(position = position_jitter(0.2)) +
facet_wrap(.~variable,scales = "free_y",ncol = 3) +
scale_color_manual(values=cbbPalette,guide = FALSE) +
geom_text(data = test.b2,aes(x = Group,y = value.y,label = value.x),
size = 5,color = "black",fontface = "bold") +
ylab("The values of nutrients in body wall of sea cucumbers") +
theme_bw()+
theme(axis.ticks.length = unit(0.4,"lines"),
axis.ticks = element_line(color='black'),
axis.line = element_line(colour = "black"),
axis.title.x=element_blank(),
axis.title.y=element_text(colour='black', size=20,face = "bold",vjust = 3),
axis.text.y=element_text(colour='black',size=12),
axis.text.x=element_text(colour = "black",size = 14,face = "bold",
angle = 45,hjust = 1,vjust = 1),
plot.margin = margin(t = 5,r = 5,b = 5, l = 20, unit = "pt"),
text = element_text(colour = "black",size = 20,face = "bold"),
legend.position = "none")
dev.off()
|
23e2286d48fd4bae71f8616f23dd54aa9400c4e4
|
fda4611281af0bc21fd28b376e26266a101bdd3b
|
/Helper/helper_udell.R
|
02f7e2a23088da04f1cbf6c267cec0900e3fbba0
|
[
"MIT"
] |
permissive
|
imkemayer/causal-inference-missing
|
bc75749682273ef2a5536540ff4af84cd7276ee8
|
e440ecc7084bc80205f2291c1a9e1dff55723325
|
refs/heads/master
| 2021-09-27T00:13:39.469262
| 2021-09-22T13:32:50
| 2021-09-22T13:32:50
| 185,151,389
| 8
| 2
| null | 2020-10-13T14:08:06
| 2019-05-06T08:05:23
|
HTML
|
UTF-8
|
R
| false
| false
| 3,747
|
r
|
helper_udell.R
|
make_V <- function(r, p){
matrix(rnorm(r*p), nrow = p, ncol = r)
}
design_matrix <- function(V, n, r, p){
# this function constructs the design list with U, V, X components
# U: n * r matrix with entries from standard gaussian distribution
# V: n * p matrix given in the input
# X: X = UV^T
design = vector("list")
design$U = matrix(rnorm(n*r), nrow = n, ncol = r)
design$V = V
design$X = design$U %*% t(design$V)
assert_that(are_equal(dim(design$U), c(n, r)))
assert_that(are_equal(dim(design$V), c(p, r)))
assert_that(are_equal(dim(design$X), c(n, p)))
design
}
perturbation_gaussian <- function(design, noise_sd = 5){
# add Gaussian noise to the UV^T matrix, which creates Gaussian noisy proxies
n = nrow(design$X)
p = ncol(design$X)
design$X + matrix(rnorm(n*p, 0, noise_sd), nrow = n, ncol = p)
}
compute_folds <- function(Xm, nfolds = 3){
# create cross-validation folds for gaussian matrix factorization
n = nrow(Xm); p = ncol(Xm)
nfold_train = createFolds(1:n, nfolds, returnTrain = T)
pfold_train = createFolds(1:p, nfolds, returnTrain = T)
nfold_test = lapply(nfold_train, function(x) setdiff(1:n, x))
pfold_test = lapply(pfold_train, function(x) setdiff(1:p, x))
list(nfold_train = nfold_train, pfold_train = pfold_train,
nfold_test = nfold_test, pfold_test = pfold_test)
}
cross_valid <- function(X, r, warm, folds, nfolds = 3){
# compute the cross validation error for gaussian matrix factorization with different ranks
assert_that(length(folds$nfold_train) == nfolds)
nfold_train = folds$nfold_train
pfold_train = folds$pfold_train
nfold_test = folds$nfold_test
pfold_test = folds$pfold_test
error_folds = numeric(nfolds)
fit_folds = list()
for (f in 1:nfolds){
temp_data = X
temp_data[nfold_test[[f]], pfold_test[[f]]] = NA
fit = softImpute(temp_data, rank.max = r, type = "als", maxit = 1000, warm.start = warm)
pred = impute(fit, i = rep(nfold_test[[f]], length(pfold_test[[f]])),
j = rep(pfold_test[[f]], each = length(nfold_test[[f]])))
assert_that(length(c(X[nfold_test[[f]], pfold_test[[f]]])) == length(pred))
error = mean((c(X[nfold_test[[f]], pfold_test[[f]]]) - pred)^2, na.rm = T)
error_folds[f] = error
fit_folds[[f]] = fit
}
list(error = mean(error_folds), fit = fit_folds[[which.min(error_folds)]])
}
recover_pca_gaussian_cv <- function(X, r_seq, nfolds = 3){
# Gaussian matrix factorization on the noisy proxy matrix design$Xm
# with rank chosen by cross validation from r_seq
# the matrix factorization is carried out by the softImpute package
cv_error = numeric(length(r_seq))
warm_list = list()
folds = compute_folds(X)
for (r in 1:length(r_seq)){
if (r == 1){
temp = cross_valid(X, r_seq[r], warm = NULL, folds = folds, nfolds = nfolds)
cv_error[r] = temp$error
warm_list[[r]] = temp$fit
} else{
temp = cross_valid(X, r_seq[r], warm = warm_list[[r-1]], folds = folds, nfolds = nfolds)
cv_error[r] = temp$error
warm_list[[r]] = temp$fit
}
}
best_r = r_seq[which.min(cv_error)]
warm = warm_list[[which.min(cv_error)]]
result = softImpute(X, rank.max = best_r, type = "als", maxit = 1000, warm.start = warm)
list(Uhat = result$u, best_r = best_r, Xhat = result$u%*%diag(result$d)%*%t(result$v))
}
recover_pca_gaussian <- function(X, r){
# Gaussian matrix factorization on the noisy proxy matrix design$Xm
# with given rank
# the matrix factorization is carried out by the softImpute package
result = softImpute(X, rank.max = r, type = "als", maxit = 1000)
list(Uhat = result$u, Xhat = result$u%*%diag(result$d)%*%t(result$v))
}
|
d014341f44f7eca74bcfe33528bdc9e4dc3fb268
|
d84d23c8eef6d63e4fba75d545d906508ffaba71
|
/R/ipsimlist.R
|
a5edd4010477ae23571891ddcee900e0451dee92
|
[] |
no_license
|
cran/idar
|
eba09954b967015aad0e8ff44c5056964059653e
|
9eb164fb099979980ed6e9e6878239018dbb71bf
|
refs/heads/master
| 2023-01-25T03:12:10.573323
| 2023-01-05T14:50:08
| 2023-01-05T14:50:08
| 90,233,829
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 657
|
r
|
ipsimlist.R
|
ipsimlist<- function(pp, mimark,listsim){
# inhomogeneous simulation of a type within a
# multivariate point pattern
# listsim: list with simulated pp from simulador2
listsim <- lapply(listsim, function(x, pp2=pp, mimark2=mimark) {
# First split the multivariate pp
u <- split(pp2)
# Second, put the fit inhomogenous simulated IPP
u[[mimark2]] <- unmark(x)
# recompose back the splited as a multivariate pp
split(pp2) <- u
return(pp2)
}
)
return(listsim)
}
|
3ebd32663454aae59f662e6d35af10c240a4e2d4
|
11ca614b32749f369af93febbb04571b7f95748a
|
/statistical_inference/notes/useful_stat_scripts.R
|
b722f6f8a1de2a4cb4a28564468de4fd1f4b1924
|
[] |
no_license
|
richelm/course_notes
|
61c525ca433d4faf90216509575432665fd7f461
|
0677708e8a05e67063a94a6dbee7e303b7b5d55a
|
refs/heads/master
| 2021-01-18T21:51:10.181408
| 2019-12-03T22:36:29
| 2019-12-03T22:36:29
| 42,669,012
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,711
|
r
|
useful_stat_scripts.R
|
# ----------------------------------------------------------------------------
# Standard error sample mean
m =
s =
n =
se = s/sqrt(n)
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Standard error of differnce of sample means.
m1
m2
s1
s2
n1
n2
se = sqrt(s1^2/n1 + s2^2/n2)
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# pooled sample standard error
n1
n2
s1
s2
sp = sqrt(((n1-1)*s1^2 + (n2-1)*s2^2)/(n1+n2-2))
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Z confidence interval
m
n
s
m + c(-1,1) * qnorm(0.975)*s/sqrt(n)
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Z conf interval for sample proportions (ie each Xi is 0 or 1)
# Example:
# Random sample of 100 likely voters, 56 intend to vote for you. What is a 95%
# confidence interval?
p <- 0.56
n <- 100
p + c(-1,1)*qnorm(0.975) * sqrt(p*(1-p)/n)
# with binom.test
binom.test(56,100)$conf.int
# ----------------------------------------------------------------------------
# Poisson interval
# Example:
# A nuclear pump failed 5 times out of 94.32 days. Give a 95% confidence
# interval for the failure rate per day.
x <- 5
t <- 94.32
lambda <- x/t
lambda + c(-1,1) * qnorm(0.975) * sqrt(lambda/t)
# ----------------------------------------------------------------------------
#
|
ebefd1dc5c6f62a85843a177ce26f060487adbae
|
49e1ad0295bf55151565814a531942c830fcd26b
|
/man/tmt_save.Rd
|
7e19734e39cd0cd5f6b81d73548e8952e4be1cc0
|
[
"MIT"
] |
permissive
|
backlin/treesmapstheorems
|
6d5fbdf78a0b78d895dc6fd835021b807c6be1b7
|
543d57a21526c2daa1df82f7391acb077a6c367c
|
refs/heads/master
| 2021-01-11T11:46:12.368671
| 2018-08-09T08:43:18
| 2018-08-09T08:43:18
| 76,788,457
| 8
| 0
| null | 2017-05-15T10:57:16
| 2016-12-18T14:42:22
|
R
|
UTF-8
|
R
| false
| true
| 638
|
rd
|
tmt_save.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/output.R
\name{tmt_save}
\alias{tmt_save}
\title{Save a plot}
\usage{
tmt_save(filename, plot, width, height, units = "cm", ...)
}
\arguments{
\item{filename}{Output filename.}
\item{plot}{Plot drawn with ggplot.}
\item{width}{Output width (in cm unless \code{units} is set).}
\item{height}{Output height (in cm unless \code{units} is set).}
\item{units}{Unit for \code{width} and \code{height}.}
\item{...}{Sent to \code{\link{ggsave}}.}
}
\description{
Sets a few default values for \code{\link{ggsave}}.
}
\author{
Christofer \enc{Bäcklin}{Backlin}
}
|
8f0c87bad5839e22ad7077297a00a17249cb05dd
|
647f90beb58faebe1f51114d964a75ba6dfa931e
|
/scripts/r_shiny_scripts/shiny_app_1/server.R
|
6d9da12d2afe7f1bd0f9cb15bf0fe2b5d70e5931
|
[] |
no_license
|
cjfiscus/INDELible
|
f48c30a9f5724262e97e948a4dc9005c37950a29
|
5930be97c892528d6249c47c6c68f4ef3e006618
|
refs/heads/master
| 2021-08-29T12:03:50.563286
| 2017-12-13T04:52:27
| 2017-12-13T04:52:27
| 114,177,086
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 262
|
r
|
server.R
|
library(shiny)
#
server <- function(input, output) {
# Generate a plot
output$chrm_histPlot <- renderPlot({
chrom_hist_plot(x, chrm = input$chrm_select,
bins = input$nbins, in_or_del = input$indel_type, test = input$test_select)
})
}
|
e6d3e9192caa355fda5cccc09fb14688dc5f44d4
|
0cce806b7204607bd673ff5e6a790a748179c785
|
/Review.R
|
b5810073fa2434dd6ae4150f28d5a91c6e7f962d
|
[] |
no_license
|
AshutoshAcharya/CMAP-R
|
0fa94c44e5acfd71b8d4a3acc1bff41ff2e5418e
|
d1c36a783678b80dd41970c1a521b8edd8eaedc6
|
refs/heads/master
| 2020-03-30T06:38:07.580791
| 2018-10-02T07:14:12
| 2018-10-02T07:14:12
| 150,876,420
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,269
|
r
|
Review.R
|
population= sample(c('M','F'),size = 100,replace = T)
population
spl=sample(c('marketing','finance','HR'),size = 100,replace =T,prob =c(.33,.33,.34))
spl
grade=sample(c('a', 'b', 'c' , 'd' , 'e'),size = 100,replace = T)
grade
placement=sample(c('yes','no'),size = 100,replace = T)
age=ceiling(runif(100,min = 21,max = 30))
age
xps=rnorm(100,3,1)
df=data.frame(age,population,grade,xps,spl)
summary(df)
df
df$grade=factor(df$grade,ordered = T,c('e','d','c','b','a'))
?plot
plot(df$age,df$spl,'p')
prop.table(table(population))
write.csv(df,file="./R work/Review.csv")
library(dplyr)
?summarise
df%>%group_by(population)%>%summarise(mean(xps),max(xps),mean(age))
filter(df,spl==c("Finace"))
hist(df$age)
t1=table(df$population)
barplot(t1,col=1:2)
boxplot(df$age)
pie(df$placement)
hist(df$xps)
table(df)
pie(table(df$population,df$xps))
students2= read.csv('./data/Review.csv')
head(students2)
#clustering
km3=kmeans(df[,c('age','xps')],centers = 3)
km3
km3$centers
plot(df[,c('age','xps')],col=km3$cluster)
#decision tree
library(rpart)
library(rpart.plot)
tree=rpart(placement~.,data = df)
tree
rpart.plot(tree,nn=T,cex = .8)
printcp(tree)
ndata=sample_n(df,3)
ndata
#logistic regression
logitmodel1=glm(placement~.,data=df,family = 'binomial')
|
6b7125aa0d7a2959b23685e474109d4111229c20
|
1e73cf11adf8b14a966dda08bc16263a5439b613
|
/stanhw.R
|
e6d27d1aaaf30695c5fdb791093b2682bc7d7214
|
[] |
no_license
|
qchenclaire/Approximate-Inference
|
70d390f90fae8bc601c55108cac21e4a9fbea2c2
|
ca2bd253a0358e302b2fafd25b5cfeb83ccfa4e2
|
refs/heads/master
| 2020-05-05T03:29:59.220638
| 2019-04-05T18:07:03
| 2019-04-05T18:07:03
| 179,674,980
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,076
|
r
|
stanhw.R
|
library(rstan)
y <- read.table("hw2data.txt")
N <- length(y[,1])
plot(density(y[,1]))
plot(density(y[,2]))
plot(density(y[,3]))
plot(density(y[,4]))
## stan data
stan_data <- list(N = N, y = y, K = 3, D = 4)
write("// Stan model
data {
int N; // sample size
int D; // dimension of observed vars
int K; // number of latent groups
vector[D] y[N]; // data
}
parameters {
ordered[K] mu; // locations of hidden states
vector<lower = 0>[K] sigma; // variances of hidden states
simplex[K] theta[D]; // mixture components
}
model {
vector[K] obs[D];
// adjust priors according to observation of ys
mu[1] ~ normal(-10, 1);
mu[2] ~ normal(5, 1);
mu[3] ~ normal(10, 1);
for(k in 1:K){
//mu[k] ~ normal(0, 10);
sigma[k] ~ inv_gamma(1,1);
}
for(d in 1:D){
theta[d] ~ dirichlet(rep_vector(2.0, K));
}
// likelihood
for(d in 1:D){
for(i in 1:N) {
for(k in 1:K) {
obs[d][k] = log(theta[d][k]) + normal_lpdf(y[i][d] | mu[k], sigma[k]);
}
target += log_sum_exp(obs[d]);
}
}
} ",
"stan_model.stan")
## check
stanc("stan_model.stan")
## save filepath
stan_model <- "stan_model.stan"
## fit
#fit <- stan(file = stan_model, data = stan_data, warmup = 500, iter = 1000, chains = 1, cores = 4, thin = 1)
fit <- stan(file = stan_model, data = stan_data, warmup = 500, iter = 1000, chains = 2, cores = 4, thin = 1)
## check it out
fit
## look at posterior
posterior <- extract(fit)
hist(posterior$mu)
## some other diagnostics
traceplot(fit)
stan_dens(fit)
stan_hist(fit)
## try out some variational inference methods in Stan...
m <- stan_model(file = "stan_model.stan")
fit2 <- vb(m, data = stan_data, algorithm = "fullrank")
fit2
## look at posterior
posterior2 <- extract(fit2)
hist(posterior2$mu)
print(fit)
print(fit2)
#library(shinystan)
#launch_shinystan(fit2)
|
64efa91b912def8cef4f5cc94b1a3d510559f564
|
0d15e0e25f3e5441169557203c65b971a2d4fb60
|
/r code/code/pfix_time_since_onset.R
|
fa05b1fb09937f3d03523c26b060ea503848c6f7
|
[] |
no_license
|
mickeypash/maxi-lex-r
|
c206219b172220b595f25829a62ce08ced46e900
|
e76207e9f490d5d556fc2296d9bbf28482a4d81d
|
refs/heads/master
| 2016-09-03T07:24:41.604897
| 2014-12-20T23:53:54
| 2014-12-20T23:53:54
| 17,442,614
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,600
|
r
|
pfix_time_since_onset.R
|
## This script generates figures for activation over time for
## the four images
# Setwd
setwd("D:/Dropbox/Maxi/R/r\ code/output")
load(file="preprocessed.RData")
load(file="alldat.RData")
#colnames(alldat) <- sub("\\.x$", "", colnames(alldat))
#rownames(alldat) <- NULL
# Useful function for creating pdfs
to.pdf <- function(expr, filename, ..., verbose=TRUE) {
if ( verbose )
cat(sprintf("Creating %s\n", filename))
pdf(filename, ...)
on.exit(dev.off())
eval.parent(substitute(expr))
}
# Cross tabulation
mx <- as.matrix(xtabs(~AOI+Msec, alldat))
props <- mx / apply(mx, 2, sum)
# Code for generating the figure for lexical activation
fig.lex <- function(){
line.width <- 1
line.type <- 'b'
bins <- seq(0,1488,24)
plot(bins, rep(NA, length(bins)),
xlim=c(400,1400),
ylim=c(0,1),
#type=line.type,
xlab="Time from Word Onset (ms)",
ylab="Target Probability")
lineinfo <- list(PComp=list(mpch=1,mcol=2),
SComp=list(mpch=2,mcol=22),
Targ=list(mpch=3,mcol=1),
Unrl=list(mpch=4,mcol=20))
draw.lines <- function(x) {
inf <- lineinfo[[x]]
points(bins, props[x, ],
type=line.type,
#xlim=c(500,1400),
pch=inf$mcol,
lwd=line.width
)
abline(v=700, lty=2)
axis(side=1, at=700, label="")
grid()
}
lapply(rownames(props), draw.lines)
legend("topleft",
legend=c("Target", "Phonological", "Semantic", "Unrelated"),
pch=c(1, 2, 22, 20), lty=1, lwd=line.width)
}
# Preview
fig.lex()
# This saves the figure to pdf
to.pdf(fig.lex(), "fixations.pdf", height=6, width=10)
|
e6faf49e90c71cee1fb023597e80cc2726186ae5
|
2e7550600103108edbb7e1f01760766907a6b5c3
|
/tests/testthat/test-verified-anovarepeatedmeasures.R
|
99148696ba40583ed58a094b64b44e00ce38d80c
|
[] |
no_license
|
djdekker/jaspAnova
|
94db3b98ecf6c7031559b671c3ff3449c3ac1904
|
95f132a9756a20660e81b3ccb9868f2500bbce1f
|
refs/heads/master
| 2023-08-18T03:31:46.691705
| 2021-09-18T02:43:16
| 2021-09-18T02:43:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,196
|
r
|
test-verified-anovarepeatedmeasures.R
|
context("Repeated Measures ANOVA -- Verification project")
# Does not test:
# - type I and type II sum of squares
# - Contrasts apart from 'repeated'
opts <- options()
on.exit(options(opts))
options(list(
afex.type = 3,
afex.set_data_arg = FALSE,
afex.check_contrasts = TRUE,
afex.method_mixed = "KR",
afex.return_aov = "afex_aov",
afex.es_aov = "ges",
afex.correction_aov = "GG",
afex.factorize = TRUE,
afex.lmer_function = "lmerTest",
afex.sig_symbols = c(" +", " *", " **", " ***"),
afex.emmeans_model = c("univariate"),
afex.include_aov = TRUE
))
## Testing standard RM ANOVA
options <- jaspTools::analysisOptions("AnovaRepeatedMeasures")
options$repeatedMeasuresFactors <- list(
list(name = "RMFactor1", levels = c("control", "experimental"))
)
options$repeatedMeasuresCells <- c("A2.control.", "A1.experimental.")
options$withinModelTerms <- list(
list(components = "RMFactor1")
)
results <- jaspTools::runAnalysis(name = "AnovaRepeatedMeasures",
dataset = "Ranova.csv",
options = options)
# https://jasp-stats.github.io/jasp-verification-project/anova.html#one-way-repeated-measures-anova
test_that("Main results match R, SPSS, SAS, MiniTab", {
# Main table
resultTable <- results[["results"]]$rmAnovaContainer$collection$rmAnovaContainer_withinAnovaTable$data
jaspTools::expect_equal_tables(
"test"=resultTable,
"ref"=list("TRUE", 22.5, 20, 20, "RMFactor1", 1, 0.00105387125701656, "TRUE",
"", 0.88888888888889, 8.00000000000001, "Residuals", 9, "")
)
})
# https://jasp-stats.github.io/jasp-verification-project/anova.html#one-way-repeated-measures-anova
test_that("Between effects results match R, SPSS, SAS, MiniTab", {
# Between effects table
resultTable <- results$results$rmAnovaContainer$collection$rmAnovaContainer_betweenTable$data
jaspTools::expect_equal_tables(
"test"=resultTable,
"ref"=list("TRUE", "", 20.2222222222222, "", 182, "Residuals", 9)
)
})
## Testing Friedman ----
options <- jaspTools::analysisOptions("AnovaRepeatedMeasures")
options$repeatedMeasuresFactors <- list(
list(name = "RMFactor1", levels = c("treatment1", "treatment2", "treatment3", "treatment4"))
)
options$repeatedMeasuresCells <- c("Treatment.I", "Treatment.II", "Treatment.III", "Treatment.IV")
options$withinModelTerms <- list(
list(components = "RMFactor1")
)
options$friedmanWithinFactor <- "RMFactor1"
results <- jaspTools::runAnalysis(name = "AnovaRepeatedMeasures",
dataset = "Friedman.csv",
options = options)
# https://jasp-stats.github.io/jasp-verification-project/anova.html#friedman-test
test_that("Main results match R, SPSS, SAS, MiniTab 2", {
# Main table
resultTable <- results[["results"]]$rmAnovaContainer$collection$rmAnovaContainer_withinAnovaTable$data
jaspTools::expect_equal_tables(
"test"=resultTable,
"ref"=list("TRUE", 3.38639427564036, 49.4772727272727, 148.431818181818,
"RMFactor1", 3, 0.0307909821225901, "TRUE", "", 14.6106060606061,
438.318181818182, "Residuals", 30, "")
)
})
# https://jasp-stats.github.io/jasp-verification-project/anova.html#friedman-test
test_that("Between effects results match R, SPSS, SAS, MiniTab 2", {
# Between effects table
resultTable <- results$results$rmAnovaContainer$collection$rmAnovaContainer_betweenTable$data
jaspTools::expect_equal_tables(
"test"=resultTable,
"ref"=list("TRUE", "", 24.2045454545455, "", 242.045454545455, "Residuals",
10)
)
})
# https://jasp-stats.github.io/jasp-verification-project/anova.html#friedman-test
test_that("Friedman results match R, SPSS, SAS, MiniTab 2", {
# Nonparametric Friedman
resultContainer <- results$results$rmAnovaContainer$collection$rmAnovaContainer_nonparametricContainer$collection
resultTable <- resultContainer$rmAnovaContainer_nonparametricContainer_friedmanTable$data
jaspTools::expect_equal_tables(
"test"=resultTable,
"ref"=list("RMFactor1", 11.9454545454546, 3, 0.345631641086186, 0.00757236506542182
)
)
})
|
a98d9664aca0064adc903c644ec318de4b831d91
|
80badebbbe4bd0398cd19b7c36492f5ab0e5facf
|
/R/flipSGDF.R
|
6cb2ab679323b02c65aa02db938be22d6f9f405f
|
[] |
no_license
|
edzer/sp
|
12012caba5cc6cf5778dfabfc846f7bf85311f05
|
0e8312edc0a2164380592c61577fe6bc825d9cd9
|
refs/heads/main
| 2023-06-21T09:36:24.101762
| 2023-06-20T19:27:01
| 2023-06-20T19:27:01
| 48,277,606
| 139
| 44
| null | 2023-08-19T09:19:39
| 2015-12-19T10:23:36
|
R
|
UTF-8
|
R
| false
| false
| 674
|
r
|
flipSGDF.R
|
flipHorizontal <- function(x) {
if (!inherits(x, "SpatialGridDataFrame")) stop("x must be a SpatialGridDataFrame")
grd <- getGridTopology(x)
idx = 1:prod(grd@cells.dim[1:2])
m = matrix(idx, grd@cells.dim[2], grd@cells.dim[1], byrow = TRUE)[,grd@cells.dim[1]:1]
idx = as.vector(t(m))
x@data <- x@data[idx, TRUE, drop = FALSE]
x
}
flipVertical <- function(x) {
if (!inherits(x, "SpatialGridDataFrame")) stop("x must be a SpatialGridDataFrame")
grd <- getGridTopology(x)
idx = 1:prod(grd@cells.dim[1:2])
m = matrix(idx, grd@cells.dim[2], grd@cells.dim[1], byrow = TRUE)[grd@cells.dim[2]:1, ]
idx = as.vector(t(m))
x@data <- x@data[idx, TRUE, drop = FALSE]
x
}
|
6d3c4b05766611a9c5387f2a54667cbbae0691a5
|
22057bf4f2eb001f739761e53a5578de578e6920
|
/scripts_on_file1/Compare_FlowBC_Prior_Post.R
|
8adff57540315dc15dd9bba88032e88cd83e7433
|
[] |
no_license
|
mrubayet/archived_codes_for_sfa_modeling
|
3e26d9732f75d9ea5e87d4d4a01974230e0d61da
|
f300fe8984d1f1366f32af865e7d8a5b62accb0d
|
refs/heads/master
| 2020-07-01T08:16:17.425365
| 2019-08-02T21:47:18
| 2019-08-02T21:47:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,812
|
r
|
Compare_FlowBC_Prior_Post.R
|
#This file is used for comparing boundary conditions prior and post to EnKF update
rm(list=ls())
output_folder = 'BC_CondSim_Mar2011_wo121A'
BCfile_ext = '_Exp_drift0_Mar2011_192to291h.txt'
subdir_plot = 'plots'
subdir_data = 'data'
#create the folders if they do not exist
if (!file.exists(output_folder))
dir.create(output_folder)
if (!file.exists(file.path(output_folder,subdir_plot)))
dir.create(file.path(output_folder, subdir_plot))
if (!file.exists(file.path(output_folder,subdir_data)))
dir.create(file.path(output_folder, subdir_data))
linwd1 = 1.5
linwd2 = 1.5
pwidth = 10
pheight = 10
plotfile = '.jpg'
#load the prior samples of the boundary conditions
#the start and end of boundary conditions to be updated
i_BC_start = 1
i_BC_end = 97
ngrid_BC = 480
ngrid4 = ngrid_BC/4
nsamp = 500
nt_BC = i_BC_end - i_BC_start + 1
BC_par_prior = matrix(0,ngrid_BC*nt_BC,nsamp)
for(ifield in 1:nsamp)
{
BC_filename = paste(file.path(output_folder,subdir_data),'/BC_Data_Rel',ifield,BCfile_ext,sep='')
BC_temp = read.table(BC_filename)
BC_par_prior[,ifield] = c(as.matrix(BC_temp[,i_BC_start:i_BC_end]))
}
#the posterior samples of boundary conditions
BC_par_post = read.table(paste(output_folder,'/BC_Post_samples_96h.txt',sep=''))
for(i in i_BC_start:i_BC_end)
{
H_2d_prior = BC_par_prior[((i-1)*ngrid_BC+1):(i*ngrid_BC),]
H_2d_post = BC_par_post[((i-1)*ngrid_BC+1):(i*ngrid_BC),]
#cat(iset,'\t',min_error,'\t',ceiling(min_error/400),'\t', min_error%%400,'\n')
jpeg(paste(file.path(output_folder,subdir_plot),'/Compare_BC_prior_post',(i+190),plotfile, sep = ''), width = pwidth, height = pheight,units="in",res=150,quality=100)
par(mfrow=c(2,2))
H_lim = c(min(min(H_2d_prior,na.rm=T),min(H_2d_post,na.rm=T)),max(max(H_2d_prior,na.rm=T),max(H_2d_post,na.rm=T)))
#South boundary
plot(seq(0,119), H_2d_prior[1:ngrid4,1], main=paste('t=',(i+190),' hour, South',sep=''),xlab = "South Coord (m)", ylab = "Elevation(m)", xlim=c(0,120),ylim=H_lim,type='l',frame.plot=F)
for (isamp in 2:nsamp)
lines(seq(0,119),H_2d_prior[1:ngrid4,isamp])
#add average line
#lines(seq(0,119),rowMeans(H_2d_prior[1:ngrid4,]),col='red')
#add posterior lines
for (isamp in 1:nsamp)
lines(seq(0,119),H_2d_post[1:ngrid4,isamp],col='red')
#north boundary
plot(seq(0,119), H_2d_prior[(ngrid4+1):(ngrid4*2),1], main=paste('t=',(i+190),' hour, North',sep=''),xlab = "North Coord (m)", ylab = "Elevation(m)", xlim=c(0,120),ylim=H_lim,type='l',frame.plot=F)
for (isamp in 2:nsamp)
lines(seq(0,119),H_2d_prior[(ngrid4+1):(ngrid4*2),isamp])
#add average line
#lines(seq(0,119),rowMeans(H_2d_prior[(ngrid4+1):(ngrid4*2),]),col='red')
#add posterior lines
for (isamp in 1:nsamp)
lines(seq(0,119),H_2d_post[(ngrid4+1):(ngrid4*2),isamp],col='red')
#west boundary
plot(H_2d_prior[(ngrid4*2+1):(ngrid4*3),1], seq(0,119), main=paste('t=',(i+190),' hour, West',sep=''),ylab = "West Coord (m)", xlab = "Elevation(m)", ylim=c(0,120),xlim=H_lim,type='l',frame.plot=F)
for (isamp in 2:nsamp)
lines(H_2d_prior[(ngrid4*2+1):(ngrid4*3),isamp], seq(0,119))
#add average line
#lines(rowMeans(H_2d_prior[(ngrid4*2+1):(ngrid4*3),]), seq(0,119),col='red')
#add posterior lines
for (isamp in 1:nsamp)
lines(H_2d_post[(ngrid4*2+1):(ngrid4*3),isamp],seq(0,119),col='red')
#East boundary
plot(H_2d_prior[(ngrid4*3+1):ngrid_BC,1], seq(0,119), main=paste('t=',(i+190),' hour, East',sep=''),ylab = "East Coord (m)", xlab = "Elevation(m)", ylim=c(0,120),xlim=H_lim,type='l',frame.plot=F)
for (isamp in 2:nsamp)
lines(H_2d_prior[(ngrid4*3+1):ngrid_BC,isamp], seq(0,119))
#add average line
#lines(rowMeans(H_2d_prior[(ngrid4*3+1):ngrid_BC,]), seq(0,119),col='red')
#add posterior lines
for (isamp in 1:nsamp)
lines(H_2d_post[(ngrid4*3+1):ngrid_BC,isamp],seq(0,119),col='red')
dev.off()
}
|
c84ac1c22a7d54c83fc082b6dd0283255a728b83
|
8986978a933ddcd9dbacb83b30bb37c88d52fe54
|
/man/cut_pretty.Rd
|
7d98ca21bf683da787e0c48f3633415c8221e71f
|
[] |
no_license
|
ramhiser/pocketknife
|
7625ee1bd21d48f0f3f76e7bbb2ebb5ecea9da59
|
51e669b49c758bbdae8f6101a8d098837965b3c4
|
refs/heads/master
| 2021-01-01T05:49:27.322019
| 2015-02-22T17:30:25
| 2015-02-22T17:30:25
| 26,447,783
| 2
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 598
|
rd
|
cut_pretty.Rd
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/cut-pretty.r
\name{cut_pretty}
\alias{cut_pretty}
\title{Cuts a vector into factors with pretty levels}
\usage{
cut_pretty(x, breaks, collapse = " to ", ...)
}
\arguments{
\item{x}{numeric vectory}
\item{breaks}{numeric vector of two ore more unique cut points}
\item{...}{arguments passed to \code{\link[base]{cut}}}
}
\value{
A \code{\link{factor}} is returned
}
\description{
Cuts a vector into factors with pretty levels
}
\examples{
set.seed(42)
x <- runif(n=50, 0, 50)
cut_pretty(x, breaks=pretty(x))
}
|
2303319a30f47ea720dce7a3b12a92e1268a87e6
|
6dd311e67e479610e93d44cdbf6827bb1fa40939
|
/Projects/murders/download-data.R
|
f5042deb3b40481af3bbc4564664706f6786e7b6
|
[
"MIT"
] |
permissive
|
JayChart/harvardx-ph125x
|
e81ea96df911f4d61bdb604007eff2b269f5f0aa
|
4be7c7cabd99e05ac12975ac8ccdbe0a2070f6d5
|
refs/heads/master
| 2020-07-18T03:28:22.403155
| 2019-08-24T20:55:02
| 2019-08-24T20:55:02
| 206,165,329
| 1
| 0
|
MIT
| 2019-09-03T20:20:48
| 2019-09-03T20:20:48
| null |
UTF-8
|
R
| false
| false
| 162
|
r
|
download-data.R
|
url <- 'https://raw.githubusercontent.com/rafalab/dslabs/master/inst/extdata/murders.csv'
dest_file <- 'data/murders.csv'
download.file(url, destfile = dest_file)
|
132cedc52b5eae820ba412ed8fb21c2c8dbd4cfa
|
004e568967af944540411d5b0a9607258c5620b0
|
/scripts/Conjoint analysis AMR final.R
|
66d52decd0be1ecba87807bb26120341607abd99
|
[] |
no_license
|
kassteele/AMR-index
|
14361600af0a2f7385d073e62433d93b7814185b
|
29a20a7fb4fffb25c8c1bd8bda5ace86a061b928
|
refs/heads/master
| 2021-07-23T20:50:24.218177
| 2017-11-03T13:46:59
| 2017-11-03T13:46:59
| 109,375,902
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,019
|
r
|
Conjoint analysis AMR final.R
|
#
# R-script belonging to the manuscript
# A summary index for antimicrobial resistance in food animals in the Netherlands
# Arie H. Havelaar, Haitske Graveland, Jan Van De Kassteele, Tizza P. Zomer, Kees Veldman, Martijn Bouwknegt
# Submitted to BMC Vet Res
#
# Author: Jan van de Kassteele
# Last revision date: October 3, 2016
#
#
# Init
#
# Load packages
library(openxlsx)
library(survival)
library(MASS)
#
# Read data
#
# The data are in a folder called 'data'. This folder contains three folders for this script:
# questback: Questback questionnaire data (5 files = 5 versions)
# profielen: link between version and comparison (1 file)
# vergelijkingen: link between comparison and profile (1 file)
# Read Questback questionnaire data
file.list <- list.files(path = "data/questback", full.names = TRUE)
questback.data <- NULL
for (i in 1:5) {
tmp <- read.xlsx(xlsxFile = file.list[i], sheet = "Ruwe data")
# Skip if there is nothing there
if (nrow(tmp) == 0) next
# Put data into one dataframe named questback.data
questback.data <- rbind(questback.data, cbind(data.frame(Version = i), tmp))
}
# Read profiles
profiles.data <- read.xlsx(xlsxFile = "data/profielen/Profielen V3 24 juni.xlsx", sheet = "Onder elkaar")
# Read comparisons
comparisons.data <- rbind(
read.xlsx(xlsxFile = "data/vergelijkingen/Opmaak vergelijkingen V3.xlsx", sheet = "Forward"),
read.xlsx(xlsxFile = "data/vergelijkingen/Opmaak vergelijkingen V3.xlsx", sheet = "Backward"))
#
# Clean data
#
#
# Questback data
#
# Rename variables
# Remove X in front of column names in columns 4:9
names(questback.data)[4:9] <- substr(names(questback.data)[4:9], start = 5, stop = nchar(names(questback.data)[4:9]))
# Rename columns 10:39 to Q1 to Q30 (question 1 to 30)
names(questback.data)[10:39] <- paste0("Q", 1:30)
# Remove "Profiel " in Q1 t/m Q30
questback.data[, 10:39] <- as.data.frame(
lapply(X = questback.data[, 10:39], FUN = gsub, pattern = "Profiel ", replacement = ""),
stringsAsFactors = FALSE)
# Reshape into long format for analysis
questback.data.long <- reshape(
data = questback.data,
varying = paste0("Q", 1:30),
v.names = "Profile",
timevar = "Question",
times = 1:30,
idvar = "Respondent",
new.row.names = 1:(30*nrow(questback.data)),
direction = "long")
#
# Profiles data
#
# Give columns informative names
names(profiles.data) <- c("Version", "Comparison", "Direction")
# Add Question 1 to 30
profiles.data <- within(profiles.data, {
Question <- 1:30
})
#
# Comparisons data
#
# Translate first two columns from Dutch to English
names(comparisons.data)[1:2] <- c("Comparison", "Profile")
# Split variable Comparison into two variables: Comparison and Direction
comparisons.data <- within(comparisons.data, {
Direction <- substr(Comparison, start = nchar(Comparison), stop = nchar(Comparison))
Comparison <- as.numeric(substr(Comparison, start = 1, stop = nchar(Comparison)-1))
})
#
# Merge questback data and profiles data
#
# Merge questback data and profiles data, call it amr.data
amr.data <- merge(questback.data.long, profiles.data)
# Re-order records
amr.data <- amr.data[with(amr.data, order(Version, Respondent, Question)), ]
# Check: amr.data should have the same number of rows as questback.data.long
dim(questback.data.long)
dim(amr.data)
#
# Consistency check
#
# Split to Respondent
tmp <- split(amr.data, f = amr.data$Respondent)
# For each respondent, calculate fraction consistent (max = 1)
x <- sapply(tmp, function(x) {
# Find oud which rows are duplicated (=2*6 = 12 rows)
index <- with(x, is.element(Comparison, Comparison[duplicated(Comparison)]))
# Remove those rows
data <- x[index, c("Comparison", "Direction", "Profile")]
# Split by Comparison
data.comparison <- split(data, f = data$Comparison)
# If chosen profiles within comparision differ -> consistent
is.consistent <- sapply(data.comparison, function(x) {
with(x, Profile[1] != Profile[2])
})
# Calculate fraction consistent
mean(is.consistent)
})
# Test consistency (H0: p = 1/2, Ha: p > 1/2)
print(x)
(z.val <- (mean(x)-0.5)/(sd(x)/sqrt(length(x))))
(p.val <- 1-pnorm(z.val))
# Conclusion: there is enough evidence for consistency
#
# Prepare data for conjoint analysis
#
# Conjoint analysis: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1118112/
# Stage 1: Identifying the attributes: Cip, Cef, Tet & Amp
# Stage 2: Assigning levels to the attributes: + / -
# Stage 3: Choice of scenarios: 24 profiles
# Stage 4: Establishing preferences: discrete choices A / B
# Stage 5: Data analysis: Organise data in preferred (1) and not preferred (0). Then do conditional logistic regression
# Also see http://www.xlstat.com/en/products-solutions/feature/conditional-logit-model.html
# Remove the 6 duplicates
# (is allowed to do this using the duplicated function, because of the randomness in the questionnaire data)
# Split to respondent
tmp <- split(amr.data, f = amr.data$Respondent)
# For each respondent, remove duplicates
tmp <- lapply(tmp, function(x) x[with(x, !duplicated(Comparison)), ])
# Put tmp back together in amr.data1
amr.data1 <- do.call(rbind, tmp)
# Check
dim(amr.data1) # 510 records minus 17 participants * 6 questions = 408 records
with(amr.data1, table(Comparison, Direction)) # 24 questions, row totals equal 17
# The data in its current form only shows the chosen option
# For a conditional logistic regression, we also need the not chosen option
# We therefore make our amr.data1 twice as large
amr.data2 <- rbind(
within(amr.data1, {
# The first part has been chosen. This is what we have observed
Chosen <- 1
}),
within(amr.data1, {
# The second part has not been chosen
Chosen <- 0
# For the not-chosen part, the profile should of course be swapped A -> B and B -> A
Profile <- ifelse(Profile == "A", yes = "B", no = "A")
})
)
# Add resistance profiles to amr.data2
amr.data2 <- merge(amr.data2, comparisons.data)
# Create strata on which conditionling will take place
# In this case each combination of Respondent and Comparison
amr.data2 <- within(amr.data2, strata <- interaction(Respondent, Comparison))
#
# Model
#
# Model: conditional logistic regression on Chosen
amr.mod <- clogit(Chosen ~ Ciprofloxacine + Cefotaxim + Tetracycline + Ampicilline + strata(strata), data = amr.data2)
summary(amr.mod)
# Determine weights
# The coefficients are the contribution to the utility score
# The weights are the normalized coefficients (add up to 1)
# Determine confidence intervals by simulation
coef.sim <- mvrnorm(n = 1000, mu = coef(amr.mod), Sigma = vcov(amr.mod))
w <- coef.sim/rowSums(coef.sim)
w.mean <- colMeans(w)
w.conf <- apply(w, MARGIN = 2, FUN = quantile, prob = c(0.025, 0.975))
# The result (Table 3 in the paper)
round(cbind(w.mean, t(w.conf)), digits = 3)
# Barplot of weights
par(mar = c(2.5, 2.5, 0.5, 0.5))
bar.mid <- barplot(w.mean, width = 1, space = 0.1, ylim = c(0, max(w.conf)))
arrows(bar.mid, w.conf[1, ], bar.mid, w.conf[2, ], code = 3, length = 0.1, angle = 90)
|
a4e2148a274ba7494cecd749e15105f643f81b5d
|
81f68c4397dec52c5129cbff33988669d7431f36
|
/man/perspective_projection.Rd
|
c6bf9e5a4663955737714acfdb0345b10f8818fa
|
[
"MIT"
] |
permissive
|
coolbutuseless/threed
|
b9bb73da1bbbc4bd6f0fb8d3b4f310d013326dfd
|
35d10852ef08f327011c82a586e85b1c39e64382
|
refs/heads/master
| 2020-04-05T07:47:24.436328
| 2018-12-02T07:41:17
| 2018-12-02T07:41:17
| 156,688,668
| 42
| 1
| null | null | null | null |
UTF-8
|
R
| false
| true
| 581
|
rd
|
perspective_projection.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/project-perspective.R
\name{perspective_projection}
\alias{perspective_projection}
\title{Perspective projection (symmetric frustrum)}
\usage{
perspective_projection(x, w = 2, h = 2, n = 1, f = 10)
}
\arguments{
\item{x}{matrix, mesh3d, vector or data.frame object}
\item{w}{width, height, near, far boundaries}
\item{h}{width, height, near, far boundaries}
\item{n}{width, height, near, far boundaries}
\item{f}{width, height, near, far boundaries}
}
\description{
Perform perspective projection
}
|
8ac7d1b5c62c3b2f0a3fd364612af4c53b48cc23
|
44ae58ea68bf99fa22fe6f61aed41c263a34f249
|
/cor_msms_genus.R
|
160428d888e372d77ce1ddc2c56054ee42b8b9ee
|
[] |
no_license
|
kyl1989/cor-heatmap
|
a3a5e57a9039965a586b79ca4c981704ade77a4a
|
646e7cae60f46ac9e149912185dcf3c34a44afe5
|
refs/heads/master
| 2021-04-09T10:22:15.933232
| 2018-04-26T07:49:19
| 2018-04-26T07:49:19
| 125,492,922
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 658
|
r
|
cor_msms_genus.R
|
library(pheatmap)
library(psych)
Genus = read.table('Genus.txt', header = TRUE, row.names = 1, sep = '\t')
Msms = read.table('msms.txt', header = TRUE, row.names = 1, sep = '\t')
Msms1 = t(Msms)
Genus1 = t(Genus)
Msms2 = Msms1[sort(row.names(Msms1)),]
Genus2 = Genus1[sort(row.names(Genus1)),]
Cor_P = corr.test(Msms2, Genus2, adjust='none')
write.table(Cor_P$r, file = 'Cor.xls', sep = '\t', col.names = NA)
write.table(Cor_P$p, file = 'P.xls', sep = '\t', col.names = NA)
pheatmap(Cor_P$r, display_numbers = matrix(ifelse(Cor_P$p < 0.05 , "*", ""), nrow(Cor_P$r)), cellwidth = 10, cellheight = 10, height = 10, width = 22, filename = 'heat.pdf')
|
1374719c705ed76c47ba069ec9bbe9a278beffb4
|
2d70c8e87de02da7b7d7d30f7a451d4bd941e0ed
|
/R/plotROC.r
|
43c5b1f22073ef262ad6a6549923bdf6ebe89ffd
|
[
"MIT"
] |
permissive
|
andybeeching/discern
|
44601fc864cc8ed2fce6f59e0f097551f9e0d5b3
|
9b0a6b6d43fbc9f72b7ab7c74eae239986185c93
|
refs/heads/master
| 2021-01-18T21:10:10.739597
| 2016-05-22T18:22:40
| 2016-05-22T19:41:38
| 50,298,754
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,568
|
r
|
plotROC.r
|
# !/usr/bin/Rscript
#' Utility function to plot multiple ROC curves against each other. Wraps the
#' *roc* method of the pROC package.
#'
#' - Comparison helps determine which models favour more TPs or less FPs
#' - Curves are shown overlaid in the same panel upto a max threshold, upon
#' when a new panel will be created.
#' - Refer to pROC#roc method documentation for further information on the
#' *res*, *predictor*, and *cv* parameters.
#'
#' @param models {List} - List of model objects (models expected to have
#' been trained with the ROC performance metric).
#' @param res {String} - The response variable to predict.
#' @param cv {Data} - Dataset containing variables in the formula.
#' @param labels {List} - *Optional*; List of labels for each model
#' @param colors {List} - *Optional*; List of colors for each model
#' @param maxCurves {Number} - *Optional*; # curves per panel, defaults to 3.
#' @export
#' @examples
#' plotROC(
#' models = list(glmFit, rfFit)
#' res = "Foo",
#' cv = validDf,
#' colors = c("black", "orange")
#' )
library(pROC)
plotROC <- function(models, res, cv, colors, labels, maxCurves = 3) {
len <- length(models)
scores <- list()
panels <- max(c(ceiling(len/maxCurves), 1))
par(mfrow=c(1, panels))
for (i in 1:len) {
model <- models[[i]]
label <- if (length(labels) < i) model$method else labels[[i]]
auc <- round(max(model$result$ROC), digits=4)
color <- if (length(colors) < i) rainbow(i) else colors[[i]]
# track panels
isLimit <- i > maxCurves & maxCurves %% (i-1) == 0
isFirst <- i == 1
isLast <- i == len
# predict and generate curve
predProb <- as.numeric(predict(model, cv, type="prob"))
curve <- roc(
response = cv[[res]],
predictor = predProb[[res]],
levels = levels(cv[[res]])
)
# create labels
scores[[length(scores)+1]] <- paste(label, auc, sep=" - ")
if (isLimit) {
a <- i - maxCurves
b <- i - 1
legend("bottomright",
legend=scores[a:b],
lwd=c(2,2),
col=colors[a:b]
)
}
# draw curve and manage partitions
if (isFirst | isLimit) {
plot(curve, type="S", col=color, ylim=c(0,1))
} else {
plot(curve, add=TRUE, col=color)
}
if (isLast) {
a <- i - ((i - (maxCurves * (panels-1))) - 1)
b <- i
legend("bottomright",
legend=scores[a:b],
lwd=c(2,2),
col=colors[a:b]
)
}
}
}
|
d43879eb73d2a8c0d0b2b06cb770a12fc6a7e506
|
beb7e8c8000b6e23aa559090f557b6bab4543eef
|
/model/R/update_subsurface.r
|
5cf0295b85af606c23532de8ec7450a66d8814f3
|
[] |
no_license
|
PeterMetcalfe/dynatopmodel
|
4b06ae681a96beea63639b80400f021522571b65
|
3b24ce7a16165c5fff6a9c21784a138d65d9965f
|
refs/heads/master
| 2021-01-10T16:07:17.615695
| 2016-01-05T18:29:27
| 2016-01-05T18:30:12
| 49,082,610
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,043
|
r
|
update_subsurface.r
|
#source("kinematic_desolve.r")
#c.route.kinematic.euler <- cmpfun(route.kinematic.euler)
################################################################################
# run inner loop Solve kinematic equation for base flow at given base flows at
# previous steps and input at this one
# Input (all)
# w : weighting matrix
# pe : potential evap
# tm, : current simulation time
# ntt, : no. inner time steps
# dt, : main time step
# dqds, : gradient functions
# ------------------------------------------------------------------------------
# Input (each HSU)
# ------------------------------------------------------------------------------
# flows$qbf : base (specific) flow at previous time step
# flows$qin : input (total) flow at previous time step
# flows$uz : drainage recharge from unsaturated zone (m/hr)
# groups$area : plan area
#
# stores$sd : specific storage deficits
# ichan : channel identifiers
# ------------------------------------------------------------------------------
# Input
# ------------------------------------------------------------------------------
# Returns (each HSU)
# ------------------------------------------------------------------------------
# flows$qbf : specific base flow at time step, per grouping
# flows$qin : total input (upslope) input, per grouping
# stores$sd : updated specific storage deficits: unsat drainage and qin inputs, qbf out
# flows$qof : updated specific overland flux per areal grouping
#
# weighting matrix
################################################################################
update.subsurface <- function (groups, flows, stores,
w,
pe=0, # potential evap
tm, # current simulation time
ntt, # no. inner time steps
dt, # main time step
dqds, # gradient functions
ichan=1)
{
# save storages
stores1 <- stores
dtt <- dt/ntt
# intial river flux is given by the saturation excess storage redistributed from
Qriv <- 0
# subsurface flows for subsurface and channels at inner time steps
qriv.in <- matrix(0,ncol=length(ichan), nrow=ntt)
colnames(qriv.in) <- groups[ichan,"id"]
qriv.out <- qriv.in
# base flow excess (per inner time step)
# qb.ex <- matrix(0,ncol=nrow(groups), nrow=ntt)
# record of actual evapotranpiration over each inner step
ae.dtt <- matrix(0,ncol=nrow(groups), nrow=ntt)
timei<-tm
for(inner in 1:ntt)
{
iter <- 1
# apply rain input and evapotranspiration (*rates*) across the inner time step
# note that rain and actual evap are maintained in flows
updated <- root.zone(groups, flows, stores, pe,
dtt, timei, ichan) #
# ae is removed from root zone only - note that original DynaTM has code to remove evap
# at max potential rate from unsat zone
flows <- updated$flows # includes ae and rain
stores <- updated$stores # storage excess
# route excess flow from root zone into unsaturated zone and drainage into water table
updated <- unsat.zone(groups, flows, stores, dtt, timei, ichan)
flows <- updated$flows
stores <- updated$stores
# Distribute baseflows downslope through areas using precalculated inter-group
# flow weighting matrix to give input flows for at next time step - required for ann implicit soln
# note total input qin returned andconverted within kinematic routine
# if(any(flows$qbf > groups$qbmax*0.75, na.rm=T))
# {
# # iter <- round(20/ntt)
# # browser()
# }
# dtt.ode <- dtt/iter
# for(i in 1:iter)
# {
# message("Increasing no. iterations")
# solution of ODE system. Now uses the Livermore solver by default
updated <- route.kinematic.euler(groups, flows, stores, dtt,
ichan=ichan, w=w, time=timei,
dqds=dqds)
flows <- updated$flows
# update stores and route any excess flow
updated <- update.storages(groups, flows, stores, dtt, ichan, tm=time)
stores <- updated$stores
# if(any(flows$ex>0, na.rm=T))
# {
# browser()
# }
# stores updated by net baseflow and drainage from unsat zone across time step
# }
# distribute fluxes to give new estimate for qin(t) given qbf(t) determined above
# base flux transferred from other areas across inner time step
flows$qin <- as.vector(dist.flux(groups, flows$qbf,
ichan = ichan,
W=w))
# channel flow into input
qriv.in[inner,] <- flows[ichan,]$qin
# actual ae at this time step
ae.dtt[inner,] <- flows$ae
# total excess over inner time step: sat excess surface storage and base flow excess
# record base flow into and out of all river reaches
# qriv.out[inner,] <- flows[ichan,"qbf"]
flows$ex <- 0
timei <- timei + dtt*3600
}
# average out total ae
flows$ae <- colMeans(ae.dtt) #Sums(ae.dtt)*dtt/dt
# channel flows are rain in over time step minus evapotranspiration, which doesn't vary according
# to root zone storage, only whether rain is falling at the time. take mean of total input across inner loop
flows[ichan,]$qin <- colMeans(qriv.in) + (flows[ichan,]$rain-flows[ichan,]$ae)*groups[ichan,]$area
Qriv <- colMeans(qriv.out)#+stores[ichan,]$ex
# specific overland flow (rate)
# flows$qof <- stores$ex/dt
# ############################## water balance check ###########################
# stores.diff <- stores - stores0
# store.gain <- stores.diff$ex + stores.diff$srz + stores.diff$suz-stores.diff$sd
# net.in <- (flows$rain- flows$ae)*dtt
# bal <- store.gain-net.in
# ############################## water balance check ###########################
# return updated fluxes and storages, total discharge into river
return(list("flows"=flows, "stores"=stores))
}
# adjust storages given updated base flow and inputs over this time step
# if max storage deficit or saturation recahed due to net inflow (outflow) then
# route the excess overland
update.storages <- function(groups, flows, stores, dtt, ichan, tm)
{
# initially add any excess baseflow to the excess(surface) storage
stores$ex <- stores$ex + flows$ex*dtt
noflow <- setdiff(which(stores$sd>=groups$sd_max), ichan)
if(length(noflow)>0)
{
LogEvent("SD > SDmax") #, tm=tm) #, paste0(groups[noflow,]$id, collapse=",")), tm=tm)
stores[noflow,]$sd<- groups[noflow,]$sd_max
#cat("Maximum storage deficit reached. This usually indicates pathological behaviour leading to extreme performance degradation. Execution halted")
# stop()
flows[noflow,]$qbf <- 0 # flows[noflow,]$qbf - (stores[noflow,]$sd - groups[noflow,]$sd_max) / dtt
}
# check for max saturated flow for grouping, in which case set SD to zero and
# route excess as overland flow update storage deficits using the inflows and
# outflows (fluxes) - note that sd is a deficit so is increased by base flow
# out of groups and increased by flow from unsaturated zone and upslope areas
# inc drainage from unsat zone
# net outflow from land zone - adds to sd.
bal <- dtt*(flows$qbf - flows$uz -flows$qin/groups$area)
# inflow / outflow for channel is handled by the time delay histogram so storage isn't relevant here
bal[ichan]<-0
stores$sd <- stores$sd + bal
# do not allow base flow to reduce storage below zero. This should be routed overland
saturated <- which(stores$sd<=0) # #setdiff(which(stores$sd<=0), ichan)
if(length(saturated)>0)
{
#LogEvent(paste("Base flow saturation in zones ", paste(groups[saturated,]$tag, collapse=",")), tm=time)
# browser()
# transfer negative deficit to excess store
stores[saturated,]$ex <- stores[saturated,]$ex - stores[saturated,]$sd
#
# # add to overland storage
# flows[saturated,]$ex <-
stores[saturated,]$sd<- 0
}
# check channels
return(list("flows"=flows, "stores"=stores))
}
|
f4efba984962cab6ba87d108b7f400db298d6eb3
|
db2d21bef6376995a5b0684049a149944b46881a
|
/dist_data_prep.R
|
9f787a2b152e4c7d61782a2101a74453cab6eba0
|
[] |
no_license
|
matkalinowski/whyR_hackaton
|
3e2ee4305f39659c7f07b4958c978bfb79d2f7af
|
337a4324df4a39af465650cacd4f1700e93d97c2
|
refs/heads/master
| 2020-08-01T14:38:24.878754
| 2019-09-26T16:12:31
| 2019-09-26T16:12:31
| 211,024,223
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,379
|
r
|
dist_data_prep.R
|
library(tidyverse)
library(RANN)
add_km_coordinates = function(df, lat_mean = 52.22922, lng_mean = 21.04778){
m_x = 111132.954 - 559.822 * cos(2 * lat_mean * pi / 180) + 1.175 * cos(4 * lat_mean * pi / 180)
m_y = 111132.954 * cos(lat_mean * pi / 180)
x = df$lat * m_x
y = df$lng * m_y
x = x - lat_mean * m_x
y = y - lng_mean * m_y
df$x = x
df$y = y
df
}
places = read_csv('data/places.csv')
warsaw_100m = read_tsv("data/warsaw_wgs84_every_100m.txt", col_names = c("lng", "lat", "district"))
warsaw_100m = warsaw_100m %>%
mutate(
district = case_when(
district == "REMBERT├ôW" ~ "Rembertów",
district == "OCHOTA" ~ "Ochota",
district == "┼╗oliborz" ~ "Żoliborz",
district == "WAWER" ~ "Wawer",
district == "┼ÜR├ôDMIE┼ÜCIE" ~ "Śródmieście",
district == "WOLA" ~ "Wola",
district == "URSUS" ~ "Ursus",
TRUE ~ district
)
)
category_mappings = read_csv("app_data/categories.csv")
category_mappings = category_mappings %>%
mutate(category = type)
# category_mappings = places %>%
# group_by(type) %>%
# tally() %>%
# arrange(n) %>%
# filter(n > 1000) %>%
# mutate(category = type) %>%
# select(-n)
places_with_categories = places %>%
inner_join(category_mappings, by = 'type')
categories = unique(places_with_categories$category)
places_with_categories = add_km_coordinates(places_with_categories)
warsaw_100m = add_km_coordinates(warsaw_100m)
# save(places_with_categories, file = "app_data/places_with_categories.RData", compress = TRUE)
# save(warsaw_100m, file = "app_data/warsaw_100m.RData", compress = TRUE)
grid100m_category_distances = tibble()
for(ctg in categories){
print(ctg)
obj = places_with_categories %>%
filter(category == ctg)
closest_grid_to_obj = nn2(obj[,c('x', 'y')], warsaw_100m[,c('x', 'y')], k = 1, searchtype = "radius", radius = 30000)
grid_category_dist = cbind(warsaw_100m, distance = closest_grid_to_obj$nn.dists, category = ctg)
grid100m_category_distances = rbind(grid100m_category_distances, grid_category_dist)
}
grid100m_category_distances = as_tibble(grid100m_category_distances) %>%
mutate(
distance = pmin(distance, 4000),
category = as.character(category)
)
save(grid100m_category_distances, file = "app_data/grid100m_category_distances.RData", compress = TRUE)
|
49aa29e2d2894a7daa71dacfd2d07cb174ac727f
|
83c13c6670c1f3527537ae22bcf05544bc9a91b7
|
/Between_sample_effects.r
|
88deb6a533e4a199a91083f183fddbcd62d2ed69
|
[] |
no_license
|
MatthewASimonson/gene_set_scripts
|
3888e9daefe8f8bfce88f574ae531a22fe7a32d3
|
9b54d593eef3eeee56ad25aaad0661edb494d0b2
|
refs/heads/master
| 2020-08-23T17:26:13.902790
| 2015-05-01T13:05:21
| 2015-05-01T13:05:21
| 32,985,048
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,899
|
r
|
Between_sample_effects.r
|
# Examine between sample bias that may be occuring:
###################################################
# First load data:
setwd("/home/simonsom/Obesity/Study_Merge/GenePath")
dataset <- 'MERGE.clean.FINAL'
#load("Cross_Validation.Rdata")
load("resid.models.Rdata") # load total phenotype with covariates for all subjects
total <- total[(!is.na(total$IID) & !is.na(total$BMI) & !is.na(total$SEX) & !is.na(total$AGE) & !is.na(total$BATCH) & !is.na(total$C1)),] # remove any subjects with missing data
# Read in list of all genes that have PCAs:
####################################################################################################
#system("ls *.min_PCA | sed 's/\\(.*\\)......../\\1/' > PCA.genes") # write list of all genes that have .min_PCA format to file
PCA.genes <- read.table("PCA.genes",header=FALSE)
names(PCA.genes) <- c('NAME')
gene.count <- nrow(PCA.genes)
ARIC.index <- which(total$set=='ARIC')
CARDIA.index <- which(total$set=='CARDIA')
MESA.index <- which(total$set=='MESA')
ARIC.mod <- lm(formula = as.numeric(BMI) ~ as.numeric(AGE) + as.factor(SEX) +
as.numeric(C1) + as.numeric(C2) + as.numeric(C3) + as.numeric(C4) +
as.numeric(C5) + as.numeric(C6) + as.numeric(C7) + as.numeric(C8) +
as.numeric(C9) + as.numeric(C10) + as.numeric(C11) + as.numeric(C12) +
as.numeric(C13) + as.numeric(C14) + as.numeric(C15) + as.numeric(C16) +
as.numeric(C17) + as.numeric(C18) + as.numeric(C19) + as.numeric(C20) + as.factor(BATCH), data = total[ARIC.index,])
CARDIA.mod <- lm(formula = as.numeric(BMI) ~ as.numeric(AGE) + as.factor(SEX) +
as.numeric(C1) + as.numeric(C2) + as.numeric(C3) + as.numeric(C4) +
as.numeric(C5) + as.numeric(C6) + as.numeric(C7) + as.numeric(C8) +
as.numeric(C9) + as.numeric(C10) + as.numeric(C11) + as.numeric(C12) +
as.numeric(C13) + as.numeric(C14) + as.numeric(C15) + as.numeric(C16) +
as.numeric(C17) + as.numeric(C18) + as.numeric(C19) + as.numeric(C20) + as.factor(BATCH), data = total[CARDIA.index,])
MESA.mod <- lm(formula = as.numeric(BMI) ~ as.numeric(AGE) + as.factor(SEX) +
as.numeric(C1) + as.numeric(C2) + as.numeric(C3) + as.numeric(C4) +
as.numeric(C5) + as.numeric(C6) + as.numeric(C7) + as.numeric(C8) +
as.numeric(C9) + as.numeric(C10) + as.numeric(C11) + as.numeric(C12) +
as.numeric(C13) + as.numeric(C14) + as.numeric(C15) + as.numeric(C16) +
as.numeric(C17) + as.numeric(C18) + as.numeric(C19) + as.numeric(C20) + as.factor(BATCH), data = total[MESA.index,])
total.mod <- lm(formula = as.numeric(BMI) ~ as.numeric(AGE) + as.factor(SEX) +
as.numeric(C1) + as.numeric(C2) + as.numeric(C3) + as.numeric(C4) +
as.numeric(C5) + as.numeric(C6) + as.numeric(C7) + as.numeric(C8) +
as.numeric(C9) + as.numeric(C10) + as.numeric(C11) + as.numeric(C12) +
as.numeric(C13) + as.numeric(C14) + as.numeric(C15) + as.numeric(C16) +
as.numeric(C17) + as.numeric(C18) + as.numeric(C19) + as.numeric(C20) + as.factor(set) + as.factor(BATCH), data = total)
ARIC.phe<- resid(ARIC.mod)
MESA.phe<- resid(MESA.mod)
CARDIA.phe<- resid(CARDIA.mod)
total.phe <- resid(total.mod)
ARIC.set <- cbind.data.frame(rep(0,length(ARIC.phe)),total[ARIC.index,1],ARIC.phe)
names(ARIC.set) <- c('FID','IID','PHE')
MESA.set <- cbind.data.frame(rep(0,length(MESA.phe)),total[MESA.index,1],MESA.phe)
names(MESA.set) <- c('FID','IID','PHE')
CARDIA.set <- cbind.data.frame(rep(0,length(CARDIA.phe)),total[CARDIA.index,1],CARDIA.phe)
names(CARDIA.set) <- c('FID','IID','PHE')
ARIC.stat <- as.matrix(unlist(lapply(gene.PCAs,lin.mod,ARIC.set)))
MESA.stat <- as.matrix(unlist(lapply(gene.PCAs,lin.mod,MESA.set)))
CARDIA.stat <- as.matrix(unlist(lapply(gene.PCAs,lin.mod,CARDIA.set)))
getES <- function(set.idx, gene.stats, p=1){ # This function is called in the next function; returns deviation from what is expected by random chance given normal distribution for each pathway
ES=rep(0,length(set.idx))
rk <- rank(-gene.stats,ties.method="first") # return order index based on ranked z-values (first of a tie is chosen as ordered first); greatest to least
N=length(gene.stats) ## total number of genes
for (i in 1:length(set.idx)){
path.idx=set.idx[[i]] ## the gene indice for this i-th pathway
Nh=length(path.idx) ## number of genes in this pathway
oo <- sort(rk[path.idx]) # sort ranks of genes for path i
ES.all= -(1:N)/(N-Nh) # 1 through total number of genes, divided by total genes - genes in pathway
statj=gene.stats[path.idx]
statj=-sort(-statj)
Nr=sum(abs(statj)^p) #
for (j in 1:(Nh-1)){ # loop through number of genes in pathway
jj=sum(abs(statj[1:j])^p)
ES.all[oo[j]:(oo[j+1]-1)] = ES.all[oo[j]:(oo[j+1]-1)]+jj/Nr+j/(N-Nh)
}
ES.all[N]=0
ES[i]=max(ES.all)
}
return(ES)
}
stats <- ARIC.stat[,1] # assign z-value from each gene to array
ES.ARIC=getES(set.idx=set.idx,gene.stats=stats) # returns deviation from what is expected by random chance given normal distribution (Enrichment Scores)
NES.ARIC=(ES-mES)/sdES # normalized observed enrichment scores for observed data; ONE FOR EACH PATHWAY
stats <- MESA.stat[,1] # assign z-value from each gene to array
ES.MESA=getES(set.idx=set.idx,gene.stats=stats) # returns deviation from what is expected by random chance given normal distribution (Enrichment Scores)
NES.MESA=(ES.MESA-mES)/sdES # normalized observed enrichme
stats <- CARDIA.stat[,1] # assign z-value from each gene to array
ES.CARDIA=getES(set.idx=set.idx,gene.stats=stats) # returns deviation from what is expected by random chance given normal distribution (Enrichment Scores)
NES.CARDIA=(ES.CARDIA-mES)/sdES # normalized observed enrichme
plot(tot.NES$NES~tot.NES$Path)
abline(aric.mod,col="green")
abline(cardia.mod,col="blue")
abline(mesa.mod,col="red")
|
f09605c27c48120cef1cd4d42010d4e2d5e777db
|
5ed2eda1f12a981732f42a363a3cce46c72c4e67
|
/R/plot_issues_pending_response.r
|
73b4447334239d994f166ef2fdb3957c62111965
|
[] |
no_license
|
mgaldino/r_we_the_people
|
8f7e0029a3af243bb1cb06a3e1bd461e93987921
|
eab1e11d26de81b9aa1955824744bd88a23437f0
|
refs/heads/master
| 2021-01-15T17:02:18.669278
| 2013-06-24T13:42:58
| 2013-06-24T13:43:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 591
|
r
|
plot_issues_pending_response.r
|
#' Generates a plot of issues pending response over time.
#' @param petitions a data frame of petitions
#' @importFrom ggplot2 ggplot aes geom_point labs
#' @export
#' @examples
#' data(petitions)
#' plot_issues_pending_response(petitions)
plot_issues_pending_response <- function(petitions) {
issues <- melt_issues(petitions)
ggplot(
subset(issues, status=='pending response'),
aes(
x=deadline_POSIXct,
y=issue,
size=signatureCount
)
) +
geom_point() +
labs(
title="Petitions Pending Response",
x="Deadline",
y="Issue"
)
}
|
bc142eccec219b00089c73673951a8be61312ab1
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/auk/examples/read_ebd.Rd.R
|
1a5c3e97b285ffe87837337dd4385ac2e3ae5a73
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 438
|
r
|
read_ebd.Rd.R
|
library(auk)
### Name: read_ebd
### Title: Read an EBD file
### Aliases: read_ebd read_ebd.character read_ebd.auk_ebd read_sampling
### read_sampling.character read_sampling.auk_ebd
### read_sampling.auk_sampling
### ** Examples
f <- system.file("extdata/ebd-sample.txt", package = "auk")
read_ebd(f)
# read a sampling event data file
x <- system.file("extdata/zerofill-ex_sampling.txt", package = "auk") %>%
read_sampling()
|
e36137e2ed1e97538091604a449ef57bee0d5806
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/dga/examples/makeAdjMatrix.Rd.R
|
97a94aa63c468612d8ad7275872e108b2758eb0b
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 711
|
r
|
makeAdjMatrix.Rd.R
|
library(dga)
### Name: makeAdjMatrix
### Title: Adjacency Matrix Converter
### Aliases: makeAdjMatrix
### Keywords: adjacency matrix graph
### ** Examples
## The function is currently defined as
function (graph, p)
{
Adj <- matrix(0, nrow = p, ncol = p)
diag(Adj) <- 1
for (i in 1:length(graph$C)) {
if (length(graph$C[[i]]) > 1) {
combns <- combn(graph$C[[i]], 2)
Adj[combns[1], combns[2]] <- 1
}
}
for (i in 1:length(graph$S)) {
if (length(graph$S[[i]]) > 1) {
combns <- combn(graph$S[[i]], 2)
Adj[combns[1], combns[2]] <- 1
}
}
Adj <- Adj + t(Adj)
Adj[Adj > 1] <- 1
return(Adj)
}
|
2ced63dd20f3525fa7312363ff2342b19b935297
|
555a96d19c5ba05d7c481549188219b0ee2b5855
|
/man/calc_kobeII_matrix.Rd
|
055b309c521f0ce50c326fd6399077b0c9da4f5f
|
[
"GPL-3.0-only"
] |
permissive
|
ShotaNishijima/frasyr
|
9023aede3b3646ceafb2167130f40b70c9c7d176
|
2bee5572aab4cee692d47dfb9d8e83ce478c889c
|
refs/heads/master
| 2023-08-16T11:43:39.327357
| 2020-01-21T07:49:29
| 2020-01-21T07:49:29
| 199,401,086
| 0
| 0
|
Apache-2.0
| 2019-07-29T07:26:21
| 2019-07-29T07:26:20
| null |
UTF-8
|
R
| false
| true
| 591
|
rd
|
calc_kobeII_matrix.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utilities.r
\encoding{UTF-8}
\name{calc_kobeII_matrix}
\alias{calc_kobeII_matrix}
\title{Kobe II matrixを計算するための関数}
\usage{
calc_kobeII_matrix(fres_base, refs_base, Btarget = c("Btarget0"),
Blimit = c("Blimit0"), Bban = c("Bban0"), year.lag = 0,
beta = seq(from = 0.5, to = 1, by = 0.1))
}
\arguments{
\item{fres_base}{future.vpaの結果のオブジェクト}
\item{refs_base}{est.MSYから得られる管理基準値の表}
}
\description{
Kobe II matrixを計算するための関数
}
|
8823b9e923f5b49a1e860eba7e221cc64bd73cb4
|
2fb8f7de5622243765b6697a2d5d0a83578b59dc
|
/session 4/credit_linear_models.R
|
d815202446fd9752c012ceac7035089add5d09a8
|
[] |
no_license
|
kostis-christodoulou/c170
|
b71b6741e73b1ee9656d773ff87d14d9a00008b8
|
6ae496b97bc61b9d5d709e9cab68a540fe9472df
|
refs/heads/main
| 2023-08-01T07:55:13.586506
| 2021-09-16T16:11:53
| 2021-09-16T16:11:53
| 400,156,320
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,590
|
r
|
credit_linear_models.R
|
library(tidyverse)
library(GGally)
library(skimr)
library(mosaic)
library(ggfortify)
library(car)
# while it's fine to know about working directories, I suggest
# you learn to use the package 'here' that makes organising files easy
# https://malco.io/2018/11/05/why-should-i-use-the-here-package/
credit <- read_csv(here::here('data', 'credit.csv'))
# ---------------------------
# Model building
favstats(~balance, data=credit)
model1 <- lm(balance~1, data=credit)
summary(model1)
credit %>%
select(income, limit, rating, cards, age, education, balance) %>%
ggpairs() +
theme_bw()
# balance vs income and students: is it parallel slopes or interaction?
ggplot(credit, aes(x=income, y=balance, colour=student))+
geom_point()+
geom_smooth()
# balance vs income and own: is it parallel slopes or interaction?
ggplot(credit, aes(x=income, y=balance, colour=married))+
geom_point()+
geom_smooth()
model1 <- lm(balance ~ rating, data=credit)
mosaic::msummary(model1)
model2 <- lm(balance ~ income, data=credit)
mosaic::msummary(model2)
model3 <- lm(balance ~ income + rating, data=credit)
mosaic::msummary(model3)
model4 <- lm(balance ~ income + rating + limit, data=credit)
mosaic::msummary(model4)
colinear_model <- lm(balance ~ ., data = credit)
mosaic::msummary(colinear_model)
vif(colinear_model)
autoplot(colinear_model)
model5 <- lm(balance ~ . - limit, data=credit)
mosaic::msummary(model5)
autoplot(model5)
vif(model5)
model6 <- lm(balance ~ income + rating + age + married, data=credit)
mosaic::msummary(model6)
autoplot(model6)
vif(model6)
|
b8cb921888a1f954269aab2e2b6e1cd29ee24ff0
|
2dc78a3377c57e0e5fbe8ee41e85942946666a36
|
/man/fishcoverEx.Rd
|
aa3471ca8c73d5991af2817b8fbfd07a85dab269
|
[] |
no_license
|
jasonelaw/aquamet
|
e5acce53127de4505486669597aed3dd74564282
|
3464af6dbd1acc7b163dc726f86811249293dd92
|
refs/heads/master
| 2020-03-25T16:19:46.810382
| 2018-08-07T20:51:01
| 2018-08-07T20:51:01
| 143,925,702
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 830
|
rd
|
fishcoverEx.Rd
|
\name{fishcoverEx}
\alias{fishcoverEx}
\docType{data}
\title{Example Fish Cover Dataset}
\description{
A dataset containing raw fish cover physical habitat data for use in function examples.
}
\usage{data(fishcoverEx)}
\format{
A data frame with 396 observations on the following 6 variables.
\describe{
\item{SITE}{unique site visit ID.}
\item{TRANSECT}{reach transect label.}
\item{SAMPLE_TYPE}{indicator of field form from which data obtained.}
\item{PARAMETER}{character variable of parameter measured in field.}
\item{VALUE}{value of measured parameter.}
\item{FLAG}{flag of value of measured parameter.}
}
}
\details{
These data are a small subset of the NRSA 2008-2009 fish cover dataset for example purposes only.
}
\examples{
data(fishcoverEx)
head(fishcoverEx)
}
\keyword{datasets}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.