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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de5daeb60d46f8310d022b57d70b7b9906d6e743
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/MCPAN/examples/Simpsonci.Rd.R
|
8748b76ec55baa7f1407684d6e4c00cf557875e4
|
[] |
no_license
|
surayaaramli/typeRrh
|
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
|
66e6996f31961bc8b9aafe1a6a6098327b66bf71
|
refs/heads/master
| 2023-05-05T04:05:31.617869
| 2019-04-25T22:10:06
| 2019-04-25T22:10:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,299
|
r
|
Simpsonci.Rd.R
|
library(MCPAN)
### Name: Simpsonci
### Title: Confidence intervals for differences of Simpson indices
### Aliases: Simpsonci
### Keywords: htest
### ** Examples
data(HCD)
HCDcounts<-HCD[,-1]
HCDf<-HCD[,1]
# Rogers and Hsu (2001), Table 2:
# All pair wise comparisons:
Simpsonci(X=HCDcounts, f=HCDf, type = "Tukey",
conf.level = 0.95, dist = "MVN")
# Rogers and Hsu (2001), Table 3:
# Comparison to the lower cretaceous:
Simpsonci(X=HCDcounts, f=HCDf, type = "Dunnett",
alternative = "less", conf.level = 0.95, dist = "MVN")
# Note, that the confidence bounds here differ
# from the bounds in Rogers and Hsu (2001)
# in the second digit, whenever the group Upper
# is involved in the comparison.
# Stepwise comparison between the strata:
SimpsonS<-Simpsonci(X=HCDcounts, f=HCDf, type = "Sequen",
alternative = "greater", conf.level = 0.95, dist = "MVN")
SimpsonS
summary(SimpsonS)
plot(SimpsonS)
# # # Hell Creek Dinosaur data:
# Is there a downward trend in biodiversity during the
# Creataceous period?
# A trend test based on multiple contrasts:
cmatTREND<-rbind(
"U-LM"=c(-0.5,-0.5,1),
"MU-L"=c(-1,0.5,0.5),
"U-L"=c(-1,0,1)
)
TrendCI<-Simpsonci(X=HCDcounts, f=HCDf, cmat=cmatTREND,
alternative = "greater", conf.level = 0.95, dist = "MVN")
TrendCI
plot(TrendCI)
|
186ea51d74e2c7bdb83c06f5339b6a98b2ecf481
|
117fa6d4f8a1b13ef6b8193124592324816d5ca5
|
/man/number_range.Rd
|
b00d6bfd3e80ec46a3b52724cfb76dfa6eb89ff0
|
[] |
no_license
|
applied-statistic-using-r/rebus.numbers
|
6ae8ce7d9f68da7caeba7af1b6ba313324021725
|
721599e9b44e0a99fe3f611f7846f9277b34c1b7
|
refs/heads/master
| 2021-01-19T12:46:18.000591
| 2017-05-01T15:21:04
| 2017-05-01T15:21:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 971
|
rd
|
number_range.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/number_range.R
\name{number_range}
\alias{number_range}
\title{Generate a regular expression for a number range}
\usage{
number_range(lo, hi, allow_leading_zeroes = FALSE, capture = FALSE)
}
\arguments{
\item{lo}{An integer.}
\item{hi}{An integer greater than or equal to \code{lo}.}
\item{allow_leading_zeroes}{A logical value. Are leading zeroes allowed to
bulk the match up to the length of the number with the most digits?}
\item{capture}{A logical value. See \code{\link{or}} for details.}
}
\value{
A character vector representing part or all of a regular expression.
}
\description{
Generates a regular expression that matches a sequence of numbers.
}
\examples{
number_range(0, 255)
number_range(0, 255, allow_leading_zeroes = TRUE)
number_range(10000, 19999)
number_range(6, 54321)
number_range(-77, 77)
number_range(-77, 77, capture = TRUE)
number_range(-77, 77, capture = NA)
}
|
87afe95837f7cd0c29509a5ad31413fe46674363
|
8491183d56c8fc70ac58f8af10626875845b9dee
|
/Week 3/hw3/hw_R/hw3.R
|
5f951470c13ef2730a5aff5f470ba21150c823ea
|
[] |
no_license
|
yifeitung/HUDM_5126
|
7f0a48088f4df801fb5c998aef3863bda3b207b9
|
6c51d67b613f0ea98ae0e15f2b87247a36400574
|
refs/heads/master
| 2023-02-07T18:09:55.512673
| 2020-12-28T19:30:34
| 2020-12-28T19:30:34
| 307,020,222
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,902
|
r
|
hw3.R
|
# Linear Models and Regression Analysis HW3
################ Data Preparation #################
setwd("/Users/yifei/Documents/Teachers College/Linear Models and Regression/Week 3")
getwd()
library(ggplot2)
library(lmtest)
library(hrbrthemes)
library(extrafont)
# 1
# This question is adapted from Q3.3. Refer to Grade Point Average data in Problem 1.19.
# a. Prepare a boxplot of the ACT scores (X variable). Are there any noteworthy features on the plot?
mydata<-read.table("http://users.stat.ufl.edu/~rrandles/sta4210/Rclassnotes/data/textdatasets/KutnerData/Chapter%20%201%20Data%20Sets/CH01PR19.txt",header = FALSE)
names(mydata)=c("Y","X")
mydata
# Descriptive values for the variable X
summary(mydata$X)
# Boxplot of the ACT Scores
boxplot(mydata$X,main="Boxplot for Students' ACT Scores",ylab="Student's ACT scores")
# The boxplot looks "normal". It seems symmetric, which most of data clustered around the middle but with no extreme
# outliers. It looks to be from a random sample.
# b. Prepare a histogram of the residuals. What information does the plot provide?
# Fitting the Simple Linear Regression Model
reg<-lm(mydata$Y~mydata$X)
summary(reg)
# Obtain the residuals
e<-resid(reg)
mydata<-cbind(mydata,e)
# Histogram of the residuals
p1<-ggplot(mydata,aes(x=e))+geom_histogram(color="darkgreen",fill="lightgreen")+
labs(x="Residuals",y="Frequency",title = "Histogram of the Residuals")+
theme(plot.title = element_text(color = "black",size=11,face = "bold",hjust = 0.5))
p1
# According to the histogram of the residuals, the residuals are left-skewed, which means the mean of residuals is smaller
# than the median of residuals.
# c. Plot the residuals against the fitted value Yhat. What are your findings about departures from the regression assumption?
# Find the fitted values first
y.hat<-predict(reg)
mydata<-cbind(mydata,y.hat)
plot(mydata$y.hat,mydata$e,main = "Residuals against the Fitted Values",xlab="Fitted Values",ylab="Residuals")
abline(h=0,lty=2)
# The residuals against the fitted value plot is relatively shapeless without clear patterns in the data and be generally symmetrically distributed around the 0 line, except for those outliers.
# Therefore, the constant variance assumption is hold or we can say there is no heteroskedasticity.
# d. Prepare a normal probability plot of the residuals. Test the reasonableness of the normality assumption with the KS test using
# alpha=0.05. What do you conclude?
# A normal probability of the residuals
# We compute the standardlized residuals with the standard function first.
stdres<-rstandard(reg)
qqnorm(stdres,xlab="Normal Scores", ylab="Standardlized Residuals", main = "Normal Probability Plot of Residuals")
qqline(stdres)
# Test the reasonableness of the normality assumption: Kolmogorov-Smirnov test for normality
ks.test(rstandard(reg),"pnorm")
# Since p-value=0.8188, which is greater than 0.05, we cannot reject the null hypothesis. Therefore, normality assumption holds.
# e. Conduct the BP test to determine if the variance varies with the level of X. Use alpha=0.01. State your conclusion. Does your conclusion support your
# preliminary findings in part c)?
# Breusch-Pagan test for constant variance
bptest(reg)
# p-value=0.5877 is not less than 0.01. Do not reject H0. Conclude error variance constant. This conclusion support my preliminary findings in part c).
# Q 3.10
mydata2<-read.table("http://users.stat.ufl.edu/~rrandles/sta4210/Rclassnotes/data/textdatasets/KutnerData/Chapter%20%203%20Data%20Sets/CH03PR10.txt",header = FALSE)
names(mydata2)=c("Fitted Values","Semistudentized Residuals")
mydata2
# a. plot the semistudentized residuals against the fitted values. What does the plot suggest?
plot(mydata2$`Fitted Values`,mydata2$`Semistudentized Residuals`,main = "Semistudentized Residuals against Fitted Values",
xlab="Fitted Values",ylab="Semistudentized Residuals")
abline(h=0)
abline(h=-2,lty=2)
abline(h=2,lty=2)
# Based on the plot, there is an outlier outside +-2 standard deviation in the observations. The outlier is at the largest predicted value, which is Yhat=15.6 and it can be very influencial beacuse it is far away from the 0 line,
# which could change the slope coeffieicent significantly.
# b. How many semistudentized residuals are outside +-1 standard deviation? Approximately how many would you expect to see if the normal error model is appropriate?
plot(mydata2$`Fitted Values`,mydata2$`Semistudentized Residuals`,main = "Semistudentized Residuals against Fitted Values",
xlab="Fitted Values",ylab="Semistudentized Residuals")
abline(h=0)
abline(h=-1,lty=2)
abline(h=1,lty=2)
# 4 semistudentized residuals are outside +-1 standard deviation. If the normal error model is appropriate, there should be 4 points fall outside.
# 3
# Read the data frame from the file HW3.RData
load("HW3.RData")
mydata3<-data
# a. Prepare a scatterplot of X vs. Y overlaid with the estimated regression line.
p2<-ggplot(mydata3,aes(x=x,y=y))+geom_point(color="black")+
xlab("X")+ylab("Y")+ggtitle("Scatterplot of X vs.Y")+theme_ipsum(plot_title_size = 12)+
geom_smooth(method = lm,color="red",se=FALSE)
p2
# b. Calculate the correlation coefficient between X and Y and comment on the strength of the linear association,
# using the standard cutoff point of +-0.7.
cor(mydata3$x,mydata3$y)
# The correlation coefficient between X and Y is 0.664. Since it is smaller than standard cutoff point of 0.7, we can conclude that the variables are not strongly positively linearly related.
# c. Create a new variable X'=sqrt(X)
x2<-sqrt(mydata3$x)
mydata3<-cbind(mydata3,x2)
# d. Prepare a scatterplot of X' vs. Y overlaid with the estimated regression line.
p3<-ggplot(mydata3,aes(x=x2,y=y))+geom_point(color="black")+
xlab("X'")+ylab("Y")+ggtitle("Scatterplot of X' vs.Y")+theme_ipsum(plot_title_size = 12)+
geom_smooth(method = lm,color="red",se=FALSE)
p3
# e. Caculate the correlation coefficient between X' and Y and comment on the strength of the linear association.
cor(mydata3$x2,mydata3$y)
# The correlation coefficient between X' and Y is 0.717. Since it is larger than standard cutoff point of 0.7, we conclude that the variables are strongly positively linearly related.
# f. Obtain the estimated linear regression function for the transformed data.
reg2<-lm(mydata3$y~mydata3$x2)
summary(reg2)
# y.hat=1.7636+9.3497*x
# g. Plot the residuals vs. fitted values.
y.hat2<-predict(reg2)
e2<-resid(reg2)
mydata3<-cbind(mydata3,y.hat2,e2)
p4<-ggplot(mydata3,aes(x=y.hat2,y=e2))+geom_point(color="black")+
xlab("fitted values")+ylab("Residuals")+ggtitle("Residuals vs. Fitted Values")+theme_ipsum(plot_title_size = 12)+
geom_hline(yintercept = 0,linetype="dashed",color="red",size=1.5)
p4
# h. What does the plot from part g) show?
# The plot from part g) shows that after the transformation of data, we observe a constant variance for the residuals.
|
60361dfcc316c8eb57ea7a5512cfc7998c4e4890
|
fb4ee97814efccd540d909a1a19cec8c170646fd
|
/Python/python_mini_batch/pomoc.R
|
81820ac81546701b79b9e1320a296ef57dc075f3
|
[] |
no_license
|
potockan/Text-clustering-basing-on-string-metrics
|
6ba1ac23f5d29a2cf59e8ea57f7ea43985dc614e
|
babdf79db3a0ab875cc8641160fe41533e3ec6e3
|
refs/heads/master
| 2021-01-15T17:46:10.962750
| 2016-05-16T10:52:52
| 2016-05-16T10:52:52
| 25,786,834
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,051
|
r
|
pomoc.R
|
library(RSQLite)
library(dplyr)
library(stringi)
source("./R/db_exec.R")
nazwy <- c('_', '_lcs', '_dl','_jaccard','_qgram',
'_red_lcs','_red_dl','_red_jaccard','_red_qgram',
'_red_lcs_lcs','_red_dl_dl','_red_jaccard_jaccard','_red_qgram_qgram')
for(n in nazwy){
print(n)
i <- 1
if(n == "_")
typ <- ""
else
typ <- n
con1 <- dbConnect(SQLite(), dbname =
sprintf("/dragon/Text-clustering-basing-on-string-metrics/Data/DataBase/partitions/czesc%d/wiki%s.sqlite", i, typ))
for(j in 2){
con <- dbConnect(SQLite(), dbname =
sprintf("/dragon/Text-clustering-basing-on-string-metrics/Data/DataBase/partitions/czesc%d/wiki%s.sqlite", j, typ))
dane <- dbGetQuery(con, sprintf("select id_title, id_stem_word, freq
from art_word_freq%s
", typ))
message("To insert...")
to_insert <- sprintf("(%d, %d, %d)",
dane$id_title,
dane$id_stem_word,
dane$freq)
to_insert <- split(to_insert,
rep(1:ceiling(length(to_insert)/500),
length.out=length(to_insert)))
message("Insert")
lapply(to_insert, function(to_insert) {
dbExecQuery(con1, sprintf("INSERT into art_word_freq%s(id_title, id_stem_word, freq)
values %s", typ, stri_flatten(to_insert, collapse=", ")))
})
dbDisconnect(con)
dbDisconnect(con1)
}
}
nazwy <- c('', '_lcs', '_dl','_jaccard','_qgram',
'_red_lcs','_red_dl','_red_jaccard','_red_qgram',
'_red_lcs_lcs','_red_dl_dl','_red_jaccard_jaccard','_red_qgram_qgram')
aa <- list()
for(n in 1:length(nazwy)){
i <- 1
typ <- nazwy[n]
con1 <- dbConnect(SQLite(), dbname =
sprintf("/dragon/Text-clustering-basing-on-string-metrics/Data/DataBase/partitions/czesc%d/wiki%s.sqlite", i, typ))
aa[n] <- dbGetQuery(con1, sprintf("select distinct id_title from art_word_freq%s", typ))
dbDisconnect(con1)
}
## bb - z cat_art
i <- 1
message("Connecting to db ", i)
con1 <- dbConnect(SQLite(), dbname =
sprintf("/dragon/Text-clustering-basing-on-string-metrics/Data/DataBase/partitions/czesc%d/wiki_art_cat.sqlite", i))
dbExecQuery(con1, "drop table if exists cat_art2;")
dbExecQuery(con1, "create table if not exists cat_art2 (
id_title INTEGER NOT NULL,
id_cat
);")
dbExecQuery(con1, sprintf("insert into cat_art2 (id_title, id_cat)
select * from cat_art
where id_title not in (%s)",
stri_flatten(
c(411278, 907399, 473644, 411388, 193317, 358425, 18152, 473968, 474017,
327107, 280615, 544189, 278771, 712304, 200423, 578374, 418763, 190832), collapse = ", ")
#391868
)
)
dbDisconnect(con1)
|
9598913a3812420a46740a3ffbd20facd4d9cf50
|
2c64352c0495f9b12466a0e99d02804f3454c398
|
/man/mod_function.Rd
|
07c71eb4a710fa8786163a55cd5b690555a1430b
|
[] |
no_license
|
cran/nmm
|
b8596e22b6b680ab3e8300273e1047b1ad48bc74
|
154ad5c5cdffb916fb015aaa10469bfa13a1f17b
|
refs/heads/master
| 2023-02-23T00:53:03.370934
| 2021-01-07T10:20:03
| 2021-01-07T10:20:03
| 334,164,780
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 349
|
rd
|
mod_function.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/007functions.R
\name{mod_function}
\alias{mod_function}
\title{Modifies function to optimize sigma and rho}
\usage{
mod_function(obj)
}
\arguments{
\item{obj}{nmm object}
}
\value{
Function
}
\description{
Modifies function to optimize sigma and rho
}
\keyword{internal}
|
2f933e3fd634ede162f560df9817e9d709e046db
|
690c2ec7e296ea6073db3e45dbfc8ee04e7789b0
|
/man/Tinamus_solitarius_env.Rd
|
cae93d47a7fc3bbc350813d62ab41d3219e1c2a8
|
[] |
no_license
|
cran/bossMaps
|
e42bf359733dcba0f1a1eaebe40a5510b6e47974
|
6779fe6fdd1445b0511cfa5a1c770ffce326670f
|
refs/heads/master
| 2021-04-29T10:22:02.824527
| 2016-12-30T00:07:50
| 2016-12-30T00:07:50
| 77,647,518
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| true
| 530
|
rd
|
Tinamus_solitarius_env.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{Tinamus_solitarius_env}
\alias{Tinamus_solitarius_env}
\title{Expert range environmental data for the Solitary Tinamou (Tinamus solitarius)}
\format{A rasterStack object}
\usage{
Tinamus_solitarius_env
}
\description{
Environmental data (from WorldClim) for the Solitary Tinamou's range (\url{mol.org}).
Bio1 is Mean Annual Temperature and Bio12 is Mean Annual Precipitation.
}
\author{
Adam M. Wilson
}
\keyword{datasets}
|
8cfe948b465564645f29ea4abb149b849ed4ce78
|
4f1c86ccd1daa1e7129cdfeb33b1e795362acfad
|
/09-case_study_03.R
|
ea6c55f024134a0a98d710ed91e5259fdd21e4b4
|
[] |
no_license
|
ua-dt-sci/fall2020_002_class_scripts
|
5ff323f176d5643bfe13dd01fb93ee5dd94f1c2f
|
3797a44c1e0f9e46496a4ece70eb1ead10995c2f
|
refs/heads/main
| 2023-01-22T22:28:08.165438
| 2020-12-08T20:43:37
| 2020-12-08T20:43:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,116
|
r
|
09-case_study_03.R
|
# load libraries
library(tidyverse)
# read data in
url <- "https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-10-20/beer_awards.csv"
beer_awards <- read_csv(url)
# alternatively
beer_awards <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-10-20/beer_awards.csv")
# state codes have multiple casing
beer_awards %>%
count(state)
# clean data: ensure state is standardized
beer_awards <- beer_awards %>%
mutate(state = toupper(state))
# what questions can you ask about the data?
# what plots can you draw?
# Question: How many medals total per state?
beer_awards %>%
count(state) %>%
top_n(10) %>%
ggplot(aes(x = reorder(state, -n), y = n)) +
geom_col() +
geom_label(aes(label = n)) +
labs(x = "state",
y = "award count",
caption = "data from Great American Beer Festival (2020)") +
ggtitle("Great American Beer Festival -- Award count by state",
subtitle = "Top 10 states with the most awards") +
theme_bw()
# reorder medal factors
beer_awards <- beer_awards %>%
mutate(medal = factor(medal,
levels = c("Gold",
"Silver",
"Bronze")))
# Question: How many medals per category (gold, silver, bronze) per state?
# draw similar plot as above, but now we have a third variable (medal)
beer_awards %>%
group_by(medal) %>%
count(state, medal) %>%
top_n(10) %>%
ggplot(aes(x = reorder(state, -n),
y = n,
fill = medal)) +
geom_col(position = "dodge") +
geom_label(aes(label = n),
position = position_dodge(width=1),
show.legend = FALSE,
color = "white") +
labs(x = "state",
y = "award count",
caption = "data from Great American Beer Festival (2020)") +
theme_bw() +
scale_fill_manual(values = c("#e79e4f",
"#898b8a",
"#aa3a3a"))
############### NOVEMBER 05 #############################
# installing usmap library
#install.packages("usmap")
library(usmap)
statepop
statepov
state.x
# create a data frame with medal count per state
medals_per_state <- beer_awards %>%
count(state)
# use statepop to add population info to medals_per_state
statepop
# create a new data frame called us_pop with two columns
# abbr and pop_2015
us_pop <- statepop %>%
select("state" = abbr,
"population" = pop_2015)
# add population by state to medals_per_state
medals_per_state <- left_join(medals_per_state,
us_pop, by = "state")
# change default to non-scientific notation
options(scipen = 999)
# starting medals_per_state
# plot n, state, and population
# first try: bar plot
medals_per_state %>%
top_n(20, wt = n) %>%
ggplot(aes(x = reorder(state, -n),
y = n,
fill = population)) +
geom_col()
# second try: scatter plot
medals_per_state %>%
ggplot(aes(x = population,
y = n)) +
geom_point() +
geom_label(aes(label = state))
medals_per_state %>%
filter(population < 10000000) %>%
ggplot(aes(x = population,
y = n)) +
geom_point() +
geom_label(aes(label = state))
# first establish direct rel. between pop. and n
medals_per_state %>%
mutate(people_per_medal = population/n) %>%
ggplot(aes(x = reorder(state, people_per_medal),
y = people_per_medal)) +
geom_col()
# plot a map, with color representing n (i.e., number of medals)
plot_usmap(data = medals_per_state,
values = "n") +
theme(legend.position = "right") +
scale_fill_continuous(name = "Medal Count",
low = "cornsilk",
high = "darkgoldenrod4")
# plot a map
medals_per_state %>%
mutate(medals_per_10kppl = (n/population) * 10000) %>%
plot_usmap(data = .,
values = "medals_per_10kppl") +
theme(legend.position = "right") +
scale_fill_continuous(name = "Medals per 10K Persons",
low = "#56B1F7",
high = "#132B43")
|
7619610471fddf11c903aa3991f7ccb78092f605
|
6954021dc0a2e5d648fcc5fc6b549ad85d41e46b
|
/Diurnal Separation Code.R
|
86c296d06f67e282f994c183ce60d31a00967965
|
[] |
no_license
|
aaronzsun/weather
|
8ad92e2796aaf12cc0a181191d868f6d61871fe3
|
95936b3e36ef0a806711dd28a93149e52af65cb5
|
refs/heads/master
| 2020-07-29T05:03:59.353778
| 2020-01-25T17:39:44
| 2020-01-25T17:39:44
| 209,679,746
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,609
|
r
|
Diurnal Separation Code.R
|
#7/2/19 Dinural Separation Code | Aaron Sun
#Attached dataset (change name throughout program for different sets)
#insert dataset name
name <- "BR1"
#insert table name
DATA <- BR1
attach(DATA)
#insert timestamp column
DATA$timestamp <- DATA$V1
#insert desired data columns / column names
DATA$column1 <- V7
DATA$column2 <- V8
#Changes timestamp to hours
DATA$Hours <- format(as.POSIXct(DATA$timestamp, "%Y-%m-%d %H:%M:%S", tz = ""), format = "%H:%M")
DATA$Dates <- format(as.POSIXct(DATA$timestamp, "%Y-%m-%d %H:%M:%S", tz = ""), format = "%Y-%m-%d ")
#Creates new data subset of hours, windspd, and winddirection (edit windspeed and winddirection to column variables)
NewData <- subset(DATA, select=c(Dates,Hours,column1,column2))
#Sets Hours as a list
b <- c(NewData$Hours)
#Converts Hours:Minutes to decimal form
NewData$Hours <- sapply(strsplit(b,":"), function(x) {
x <- as.numeric(x)
x[1]+x[2]/60
}
)
NewData$column1 <- as.numeric(as.character(NewData$column1))
NewData$column2 <- as.numeric(as.character(NewData$column2))
NewData$TimeStamp <- paste(NewData$Dates, " ", NewData$Hours)
#Creates new dataset for day (edit numbers if needed)
DaytimeData <- NewData[NewData$Hours > 7 & NewData$Hours < 19, ]
#Creates new dataset for night (edit numbers if needed)
NighttimeData <- NewData[NewData$Hours < 7 | NewData$Hours > 19, ]
#Creates CSV files comma seperated
write.csv(DaytimeData, file = "BR1DaytimeData.csv")
write.csv(NighttimeData, file = "BR1NighttimeData.csv")
|
7ee547aa7f70d4f769e5f921c1a5b09147c1ebba
|
345813866b606f3f3faf9ac9096479214a0df3c6
|
/Dataset.R
|
64cfd2d9d1997491da13a756d89e8ef6c1854252
|
[] |
no_license
|
cooma/Auction_price-of-real-estate
|
ce7cea14de268d6955fc0da52d43f96ecffeb37b
|
2ce61b3ec7c8b92c3351876a6b331400ab93336c
|
refs/heads/master
| 2020-04-28T17:03:26.023342
| 2019-03-13T14:46:12
| 2019-03-13T14:46:12
| 175,432,839
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 14,360
|
r
|
Dataset.R
|
suppressMessages({
library(readr)
library(dplyr)
library(caret)
})
setwd("C:/Users/seol/Desktop/Analysis/DACON")
##### Data set Making ######
Auction_master_train <- read_csv("Auction_master_kr/Auction_master_train.csv",
col_types = cols(Appraisal_company = col_skip(),
Creditor = col_skip(),
Close_date = col_skip(), Close_result = col_skip(),
Final_result = col_skip(), First_auction_date = col_skip(),
addr_bunji1 = col_skip(), addr_bunji2 = col_skip(),
addr_dong = col_skip(), addr_etc = col_skip(),
addr_li = col_skip(), addr_san = col_skip(),
point.x = col_skip(), point.y = col_skip(),
road_bunji1 = col_skip(), road_bunji2 = col_skip(),
road_name = col_skip(),
Total_building_area=col_skip(),Total_land_real_area=col_skip(),
Specific= col_skip()))
Auction_master_test <- read_csv("Auction_master_kr/Auction_master_test.csv",
col_types = cols(Appraisal_company = col_skip(),
Creditor = col_skip(),
Close_date = col_skip(), Close_result = col_skip(),
Final_result = col_skip(), First_auction_date = col_skip(),
addr_bunji1 = col_skip(), addr_bunji2 = col_skip(),
addr_dong = col_skip(), addr_etc = col_skip(),
addr_li = col_skip(), addr_san = col_skip(),
point.x = col_skip(), point.y = col_skip(),
road_bunji1 = col_skip(), road_bunji2 = col_skip(),
road_name = col_skip(),
Total_building_area=col_skip(),Total_land_real_area=col_skip(),
Specific= col_skip()))
Auction_master_train %>% ggplot(aes(y=Hammer_price))+
geom_boxplot()+
scale_y_continuous(labels=comma)
#install.packages('dplyr')
#outlier removal
train<-Auction_master_train %>% filter(Hammer_price<5000000000)
# EDA
train %>% ggplot(aes(group=Auction_miscarriage_count,y=Hammer_price))+
geom_boxplot()+
scale_y_continuous(labels=comma)
train %>%
group_by(addr_do,addr_si) %>%
summarize(mean_hammer= mean(Hammer_price))
train %>%
group_by(Auction_miscarriage_count) %>%
tally()
train %>%
group_by(Auction_miscarriage_count) %>%
dplyr::summarize(mean_hammer=mean(Hammer_price))
train %>%
group_by(addr_si) %>%
tally() %>% View()
# outlier 확인
quantile(train$Hammer_price)
train %>% ggplot(aes(y=Hammer_price))+
geom_boxplot()+
scale_y_continuous(labels=comma)+
geom_hline(yintercept = quantile(train$Hammer_price,probs = 0.90),color='red')
# outlier 제거 --상위 10%절삭
train_rm_outline <- train %>% filter(Hammer_price <quantile(train$Hammer_price,probs = 0.90))
train_rm_outline %>% ggplot(aes(y=Hammer_price))+
geom_boxplot()+
scale_y_continuous(labels=comma)
train_add<-train_rm_outline %>%
group_by(addr_si) %>%
summarise(mean_hammer=mean(Hammer_price)) %>% arrange(desc(mean_hammer))
train_add %>% ggplot(aes(y=mean_hammer,x=reorder(addr_si, -mean_hammer, fun= mean, desc=T)))+
geom_point()+
scale_y_continuous(labels=comma)+
theme(axis.text.x = element_text(angle=-90))
train_2 <- train_rm_outline %>% select(-point.x,-point.y, -addr_do,-Auction_key)
df_train <- Auction_master_train
## 이상치제거 및 변환 ##
df_train %>% summary # Current_floor ==0 , Total_land_gross_area ==3511936
# [land_auction_area=0 -> 건물만 경매, Claim_price=0 -> 형식적 경매]
#df_train %>% arrange(desc(Total_land_gross_area)) %>% View()
df_train$Total_land_gross_area[df_train$Total_land_gross_area==3511936]<-351193.6
df_train$Total_land_gross_area[df_train$Total_land_gross_area>=825056] <- 82056.4
df_train$Current_floor[df_train$Current_floor==0][1]<-13
df_train$Current_floor[df_train$Current_floor==0][1]<-14
#df_train %>% View
df_test <- Auction_master_test
df_test %>% summary # Current_floor = -1
df_test[df_test$Current_floor==0,]
df_test$Current_floor[df_test$Current_floor==0][1]<-3
df_test$Current_floor[df_test$Current_floor==0][1]<-6
df_test$Current_floor[df_test$Current_floor==0][1]<-3
df_test$Current_floor[df_test$Current_floor==0][1]<-1
df_test[df_test$Current_floor==-1,]
df_test$Current_floor[df_test$Current_floor==-1][1]<-1 # -값은 임의로 변경 -> scaling 오류 피하기
n<-nrow(df_train)
nrow(df_test)
data_full <- df_train %>% rbind(df_test)
## date 처리, 아파트 경과년도 생성, 대출금리 ##
library(lubridate)
library(zoo)
a<-data_full %>% select(ends_with('date'),-c(Final_auction_date)) %>% colnames()
data_full[,a] <- data_full[,a] %>% apply(2,year)
#View(data_full)
data_full$Final_auction_date<-data_full$Final_auction_date %>% zoo::as.yearmon(format="%Y-%m-%d UTC") %>% format(format='%Y-%m')
i_rate<-read_csv('i_rate.csv') #대출금리 자료 -http://housta.khug.or.kr/khhi/web/hi/fi/hifi050008.jsp
i_rate %>% t() %>% as.data.frame %>% colnames
i_rate<-i_rate %>% t() %>% as.data.frame %>% select(V3)
i_rate$Final_auction_date<- rownames(i_rate)
i_rate %>% head()
i_rate<- i_rate[2:nrow(i_rate),]
rownames(i_rate)<-c()
colnames(i_rate)[1]<-'interest_rate'
i_rate %>% glimpse()
i_rate$Final_auction_date <- i_rate$Final_auction_date %>% as.yearmon(format='%Y.%m') %>% format('%Y-%m')
head(i_rate)
data_full<-data_full %>% merge(i_rate,by='Final_auction_date')
data_full <- data_full %>% select(-c(Final_auction_date))
data_full$interest_rate <- data_full$interest_rate %>% as.character %>% as.numeric
data_full %>% glimpse()
#install.packages('naniar')
library(naniar)
data_full<-replace_with_na(data_full,list(Preserve_regist_date=1111))
data_full$Preserve_regist_date<-tidyr::replace_na(data_full$Preserve_regist_date,round(mean(data_full$Preserve_regist_date,na.rm = T),digits=0))
#data_full %>% View
data_full <-data_full %>% mutate(date_diff=Appraisal_date-Preserve_regist_date)
data_full <- data_full %>% select(-c(Appraisal_date,Preserve_regist_date))
data_full$date_diff[data_full$date_diff %in% -1]<-0
class(data_full$date_diff)
data_full$date_diff<- as.vector(data_full$date_diff)
#View(data_full)
#################
regist <- read_csv("Auction_master_kr/Auction_regist.csv")
rent <- read_csv("Auction_master_kr/Auction_rent.csv")
View(rent)
View(regist)
rent_in <- data.frame(unique(rent[,"Auctiuon_key"]))
rent_in$rent <- 'Y'
colnames(rent_in)[1]<-'Auction_key'
data_full<-data_full %>% merge(rent_in, by='Auction_key',all=TRUE)
data_full$rent[data_full$rent %in% NA ] <- 'N'
colnames(data_full)
#colnames(data_full)[21] <- 'rent'
#####regist
regist_n <- regist[,c("Auction_key","Regist_price")]
regist_n<-regist_n %>% filter(Regist_price!=0)
#regist_1 <- regist_n %>% group_by(Auction_key) %>% filter(row_number()==n()) #row_number()
regist_n %>% group_by(Auction_key) %>% summarise(regist_sum=sum(Regist_price)) %>% View
regist %>% select(Regist_class) %>% unique()
regist[,"Regist_class"] %>% table()
#regist %>% View()
regist_ga<- regist[regist$Regist_class=='가등기',] %>% filter(!is.na(Auction_key)) %>% select(Auction_key)
regist[regist$Regist_class=='가처분',]
#################
data_full <- data_full %>% arrange(desc(Hammer_price))
#data_full %>% View
data_full %>% glimpse
data_r <- data_full %>% mutate(Claim_price=Claim_price/Total_building_auction_area,
Total_appraisal_price=Total_appraisal_price/Total_building_auction_area,
Minimum_sales_price=Minimum_sales_price/Total_building_auction_area,
Hammer_price=Hammer_price/Total_building_auction_area) %>%
mutate(Current_floor=as.double(Current_floor),
Total_floor=as.double(Total_floor)) %>% select(-c(Total_building_auction_area,Auction_key))
data_r <- data_r %>% mutate_if(is.character,as.factor) %>% mutate_if(is.integer,as.factor)
minmax <- function(x){
(x-min(x)) / (max(x)-min(x))
}
##### data Scailing , dummy ########
b<-data_r %>% select_if(is.numeric) %>% colnames()
data_r_num<- data_r[,b]
#data_r[,b] <- data_r[,b] %>% apply(2,minmax) %>% as.data.frame()
library(GGally)
library(fBasics)
data_r[,b] %>% ggpairs()
data_r[,b] %>% apply(2,skewness)
data_r[,b] %>% View
### preprocess ### - Normalizing
# Normalizing - Countinous variables
d_price<-data_r %>% select(ends_with('price')) %>% colnames()
d_area<- data_r %>% select(ends_with('area')) %>% colnames()
data_r[,d_price]<-data_r[,d_price] %>% apply(2,function(x){log(x+1)}) %>% as.data.frame()
data_r[,d_area]<- data_r[,d_area] %>% apply(2,function(x){log(x+1)}) %>% as.data.frame()
data_r_num_log <- data_r_num %>% apply(2,function(x){log(x+1)}) %>% as.data.frame()
data_r[,b] %>% ggpairs()
data_r[,b] %>% View()
## Min max scaling
data_r[,b] <- data_r[,b] %>% apply(2,minmax) %>% as.data.frame() # Scaling
data_r[,b] %>% sapply(range) # Check
data_r %>% View()
dummies <- dummyVars(~.,data_r)
processed_data <- predict(dummies,data_r)
#write.csv(processed_data,'processed_data.csv')
colnames(processed_data)
processed_data %>% View
train_set<-processed_data[1:n,] %>% as.data.frame()
test_set<-processed_data[(n+1):nrow(processed_data),] %>% as.data.frame()
nrow(train_set)
nrow(test_set)
View(data_full)
######### making partition ##########
inTrain <- createDataPartition(y=train_set$Hammer_price,p=0.75,list=FALSE)
training <- train_set[inTrain,]
testing <- train_set[-inTrain,]
testing <- testing %>% select(-c(Hammer_price)) # Cross validation
###### Model Making & Fitting ######## ## Dataset 변화에 따른 RMSE값 변화
### NNET #####
library(neuralnet)
n <- colnames(train_set)
n
f <- as.formula(paste("Hammer_price ~", paste(n[!n %in% "Hammer_price"], collapse = " + ")))
f
nn <- neuralnet(
f , threshold = 0.01,algorithm = "rprop+",
learningrate.factor =
list(minus = 0.5, plus = 1.2),
data=train_set, hidden=c(74,37,18,10), err.fct="sse",
linear.output=TRUE)
test_set2<-test_set %>% select(-c(Hammer_price))
nn_predict <- compute(nn,test_set2)
nn_predict_rescale <-nn_predict$net.result*(max(data_r_num_log$Hammer_price)-min(data_r_num_log$Hammer_price))+min(data_r_num_log$Hammer_price)
submit <- exp(nn_predict_rescale)-1
submit_final<- submit * Auction_master_test$Total_building_auction_area
write.csv(submit_final,'NN_new_dataset.csv')
#################
rf.caret <- train(f, data = training,
method='rf', # random forest 옵션
trControl=my_control)
library(randomForest)
rf <- randomForest(f,
data = training,
ntree = 10000, # Tree 개수
importance = TRUE,
type='regression')
varImpPlot(rf, type=1, n.var=10)
###### NNET ############
fitGrid <- expand.grid(.size = c(3,5), .decay = c(0.1))
library(pROC)
fitControl <- trainControl(method = "cv", # Cross validation 으로 찾도록 지정
number = 10)
model.ct.nn <- train(Hammer_price ~ .,
data = train_set,
method = 'nnet',
maxit = 1000,
linout = TRUE,
trControl = fitControl,
tuneGrid = fitGrid,
metric = "RMSE",
allowParallel = TRUE)
preds.ct.nn.f <- predict(model.ct.nn, newdata=test_set)
preds.ct.nn.f.l <- preds.ct.nn.f*(max(data_r_num_log$Hammer_price)-min(data_r_num_log$Hammer_price))+min(data_r_num_log$Hammer_price)
preds.ct.nn.f.l<-preds.ct.nn.f.l*df_test$Total_building_auction_area
########### Model Stacking, Ensemble #############
#install.packages('pROC')
library(pROC)
#install.packages('mlbench')
library(mlbench)
#install.packages('caretEnsemble')
library(caretEnsemble)
library(rpart)
View(train_set)
set.seed(2018)
inTrain <- createDataPartition(y=train_set$Hammer_price,p=0.75,list=FALSE)
training <- train_set[inTrain,]
testing <- train_set[-inTrain,]
my_control <- trainControl(
method='cv',
number=10,)
model_list <- caretList(
Hammer_price~., data=training,
trControl=my_control,
metric = "RMSE",
methodList=c("glm", "rpart",'avNNet')
)
p <- as.data.frame(predict(model_list, newdata=head(testing)))
print(p)
modelCor(resamples(model_list))
greedy_ensemble <- caretEnsemble(
model_list,
metric="RMSE",
trControl=trainControl(
number=3,
))
summary(greedy_ensemble)
glm_ensemble <- caretStack(
model_list,
method="nnet",
metric="RMSE",
trControl=trainControl(
method="boot",
number=10,
savePredictions="final",
)
)
model_preds2 <- predict(glm_ensemble, newdata=testing)
CF <- coef(glm_ensemble$ens_model$finalModel)[-1]
install.packages('caTools')
library(caTools)
colAUC(model_preds2, testing$Hammer_price)
test_result <- predict(glm_ensemble, newdata = test_set)
nn_fit <- unlist(nn$net.result)*(max(df_train_num_log$Hammer_price)-min(df_train_num_log$Hammer_price))+min(df_train_num_log$Hammer_price)
nn_fit <- exp(nn_fit)-1
test_result<-test_result*(max(data_r_num_log$Hammer_price)-min(data_r_num_log$Hammer_price))+min(data_r_num_log$Hammer_price)
test_restult <- exp(test_result)-1
Final_result<-test_restult*df_test$Total_building_auction_area
write.csv(Final_result,'model_stacking.csv')
|
e3b2168118e1eff5b2fb520b86cbe20338a46781
|
aef437f42d60224cb103037538ddaa0fd1281024
|
/plot3.R
|
f8cbde63563088968150d2c382d58871dbb92a50
|
[] |
no_license
|
armelad/ExData_Plotting1
|
2a67db74a23f7f20adff1efee64f1837d1c1009c
|
ccdfeb2c4befbd0253fd48125acf9700406b2472
|
refs/heads/master
| 2020-09-19T16:51:26.109027
| 2017-06-23T02:53:18
| 2017-06-23T02:53:18
| 94,495,127
| 0
| 0
| null | 2017-06-16T02:01:54
| 2017-06-16T02:01:53
| null |
UTF-8
|
R
| false
| false
| 2,074
|
r
|
plot3.R
|
#load library for quick load of the csv data
library(readr)
if (!file.exists("data.zip")) {
#assign the location of the file
fileUrl <-
"https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
# download the file
download.file(fileUrl, destfile = "data.zip", method = "libcurl")
#UNzip the file
unzip ("data.zip", exdir = ".")
}
#get the current folder
curdir <- getwd()
#get the file name with path
data_file <-
paste0(curdir, "/", unzip(paste0(curdir, "/", "data.zip"), list = TRUE)[1])
#function that processes the file and subsets the required data
proc_file <- function(filepath) {
full_df <- read.csv2(filepath)
result <-
full_df[full_df$Date %in% c('1/2/2007', '2/2/2007'),]
return(result)
}
working_df <- proc_file(data_file)
#Convert characters to dates and times
working_df$Time <-
strptime(paste(working_df$Date, working_df$Time), "%d/%m/%Y %H:%M:%S")
#Convert factors to numbers
working_df$Global_active_power <-
as.numeric(as.character(working_df$Global_active_power))
working_df$Global_reactive_power <-
as.numeric(as.character(working_df$Global_reactive_power))
working_df$Voltage <- as.numeric(as.character(working_df$Voltage))
working_df$Sub_metering_1 <-
as.numeric(as.character(working_df$Sub_metering_1))
working_df$Sub_metering_2 <-
as.numeric(as.character(working_df$Sub_metering_2))
working_df$Sub_metering_3 <-
as.numeric(as.character(working_df$Sub_metering_3))
# Plot #3
png("plot3.png",
width = 480,
height = 480,
res = 72)
with(working_df, {
plot(Time,
Sub_metering_1,
type = "l",
ylab = "Energy sub metering")
lines(Time, Sub_metering_2, col = "red")
lines(Time, Sub_metering_3, col = "blue")
})
legend(
"topright",
lty = "solid",
col = c("black", "red", "blue"),
legend = names(working_df)[7:9]
)
dev.off()
rm(list=ls())
|
a935127a4ff626acc0069891417bf9989a3844e7
|
8beadb1abfb098d312f2db476d7aae71d3ebcc2a
|
/install-packages.R
|
29c7c1b6a40c229de3af9006f63035a947437391
|
[] |
no_license
|
qianli10000/image-metabolomics-r
|
3b455042ba2a701cfbce79b7bca062ba811f7094
|
108d2fff4661c968f6db2985a870e0c8c741e216
|
refs/heads/master
| 2021-08-22T10:54:13.233606
| 2017-11-29T21:41:25
| 2017-11-29T21:41:25
| 112,549,843
| 0
| 0
| null | 2017-11-30T01:42:45
| 2017-11-30T01:42:45
| null |
UTF-8
|
R
| false
| false
| 485
|
r
|
install-packages.R
|
install.packages(c(
'Rserve',
'ptw',
'gplots',
'baseline',
'hyperSpec',
'ggplot2',
'erah',
'mclust', 'matrixStats',
'glmnet'))
source("https://bioconductor.org/biocLite.R")
biocLite(c(
'xcms',
'CAMERA',
'PROcess',
'targetSearch',
'limma',
'RUVnormalize',
'RUVSeq',
'sva'))
# show installed packges
ip = as.data.frame(installed.packages()[,c(1,3:4)])
ip = ip[is.na(ip$Priority),1:2, drop=FALSE]
print(ip[order(ip$Package),c(1,2)], row.names=FALSE)
|
87ef79e372fe06441b97662292bc95f48cc411a2
|
cf681440d20cde6f629d96c10f2a1496a22b99dc
|
/man/build_M_Lambda.Rd
|
f76c9aac6a8328c2dbe12806dfcdb4875ef60cd1
|
[] |
no_license
|
mmkuang/mfbvar
|
b15ddd881b8d411455b8be322d30d0dcc8061027
|
85f25f00bc4060dd3e2944b6a26bd0b78fffc7c3
|
refs/heads/master
| 2022-04-12T08:23:24.242462
| 2020-03-19T06:46:46
| 2020-03-19T06:46:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 949
|
rd
|
build_M_Lambda.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/builders.R
\name{build_M_Lambda}
\alias{build_M_Lambda}
\title{Build the \eqn{M_t\Lambda} matrices}
\usage{
build_M_Lambda(Y, Lambda, n_vars, n_lags, n_T)
}
\arguments{
\item{Y}{The data matrix of size \code{(n_T + n_lags) * n_vars} with \code{NA} representing missingness. All monthly variables must be placed before quarterly variables.}
\item{Lambda}{The Lambda matrix (size \code{n_vars* (n_vars*n_lags)}).}
\item{n_vars}{The number of variables.}
\item{n_lags}{The number of lags.}
\item{n_T}{The number of time points.}
}
\value{
\item{M_Lambda}{A list of length \code{n_T}.}
}
\description{
Builds the selection matrices \eqn{M_t\Lambda}.
}
\details{
The element \code{M_Lambda[[t]]} corresponds to \eqn{M_t\Lambda}. Currently, if element \code{i} of \code{Y[t, ]} is \code{NA}, then row \code{i} of \code{M_Lambda[[t]]} is all \code{NA}.
}
\keyword{internal}
|
dbf6cb45d6eb0261b2f043c60ab28ce3eb88b437
|
4b55b60d764da1051c38e6e4b93627335afa0150
|
/Flight delay prediction and analysis/knn_kknn.R
|
ab5a883ae14f6d7b726f09184bdb4a5b54be97e7
|
[] |
no_license
|
vyadav06/R-Project-for-Statistical-Computing
|
f87b09c79c71e5650fbe34154844fdf85ac5eb3e
|
0e92e2db05d3bba0f6ec9e358d740d416aed06ef
|
refs/heads/master
| 2021-01-12T06:00:26.228654
| 2016-12-24T07:48:32
| 2016-12-24T07:48:32
| 77,271,457
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,853
|
r
|
knn_kknn.R
|
#Course : CS 513
#Vandna Yadav
rm(list=ls())
#********************loading the dataset**************************
data<-read.csv("C:/Users/vandna/Desktop/Stevens/SEM 2/513/Project/Code/dataset/2008.csv")
odataset<-data
attach(odataset)
#********************categorizing Departure Delay *****************
odataset$DepDelay_cat[DepDelay < -5] <- "EARLY"
odataset$DepDelay_cat[DepDelay >= -5 & DepDelay <= 5] <- "ONTIME"
odataset$DepDelay_cat[DepDelay > 5] <- "LATE"
#********************categorizing Arrival Delay*******************
odataset$ArrDelay_cat[ArrDelay < -5] <- "EARLY"
odataset$ArrDelay_cat[ArrDelay >= -5 & ArrDelay <= 10] <- "ONTIME"
odataset$ArrDelay_cat[ArrDelay > 10]<-"LATE"
#***********creating a data frame
filtereddataset <- data.frame(Month,DayofMonth,DayOfWeek,DepTime,CRSDepTime,ArrTime,CRSArrTime,UniqueCarrier,Origin,Dest,Distance,Diverted,Cancelled,CarrierDelay,WeatherDelay,NASDelay,SecurityDelay,LateAircraftDelay,ArrDelay,DepDelay,"ArrDelay_cat"=odataset$ArrDelay_cat,"DepDelay_cat"=odataset$DepDelay_cat)
detach (odataset)
attach(filtereddataset)
#we are filtering out the flights which are cancelled
filtereddataset<-filtereddataset[filtereddataset[,"Cancelled"]==0,]
#we are filtering out the flights which are Diverted
filtereddataset<-filtereddataset[filtereddataset[,"Diverted"]==0,]
#we are filtering out the flights which are latedeparture
filtereddataset<-filtereddataset[filtereddataset[,"DepDelay"]>=5,]
#*****we are taking 3 highest freq unique carrier
filtereddataset<-filtereddataset[filtereddataset$UniqueCarrier =="WN" | filtereddataset$UniqueCarrier =="OO" | filtereddataset$UniqueCarrier =="AA", ]
#*****we are taking 3 highest freq origin
filtereddataset<-filtereddataset[filtereddataset$Origin =="ATL" | filtereddataset$Origin =="ORD" | filtereddataset$Origin =="LAX", ]
#removing arrival time NA
filtereddataset<-filtereddataset[complete.cases(filtereddataset[,6]),]
attach(filtereddataset)
library(plyr)
data<-join(filtereddataset,count(filtereddataset,'Dest'))
attach(filtereddataset)
#*******categoraizing dest type according to the num of flights
filtereddataset$Dest_Type[data$freq > 500 & data$freq<1000] <- "Med Busy"
filtereddataset$Dest_Type[data$freq < 500] <- "Less Busy"
filtereddataset$Dest_Type[data$freq >1000] <- "High Busy"
detach(odataset)
#************normalization & removal of na values functions ***********
na.zero <- function (x) {
x[is.na(x)] <- 0
return(x)
}
mmnorm <-function(x) {z<-((x-min(x))/(max(x)-min(x)));return(z) }
data<-filtereddataset
data_new<-cbind(Month=mmnorm(data$Month),
DayOfMonth=mmnorm(data$DayofMonth),
DayOfWeek=mmnorm(data$DayOfWeek),
CRSDepTime=mmnorm(data$CRSDepTime),
CRSArrTime=mmnorm(data$CRSArrTime) ,
UniqueCarrier=mmnorm(as.numeric(factor(data$UniqueCarrier))),
Origin=mmnorm(as.numeric(factor(data$Origin))),
Dest=mmnorm(as.numeric(factor(data$Dest_Type))),
ArrDelay_cat=as.character(data$ArrDelay_cat)
)
#*****taking 5000 entries*******
idx1<-seq(1:5000)
data_new<-data_new[idx1,]
#****sampling data**************
idx<-sample(nrow(data_new),as.integer(.70*nrow(data_new)))
#****training & test dataset***********
training<-data5,]
test<-data_new[-idx,]
library(class)
####to find proper k value::
#running knn 50 time for itterative k starting from k=1 to k=20
# here which k's average error rate is minimumm,that k is best.
for (j in 1:40){
counter<- 0
total<-0
for (i in 1:50) {
newpredict<-knn(training[,-9],test[,-9],training[,9],k <- j)
newresults<-cbind(test,as.character(newpredict) )
wrong<-newresults[,9]!=newresults[,10]
rate<-sum(wrong)/length(wrong)
rates<-rbind(rate,rate)
total<-total+rate
counter<-counter+1
}
print(j)
avg=total/counter
print(avg)
}
######################
#******applying knn***************
newpredict<-knn(training[,-9],test[,-9],training[,9],k=30)
newresults<-cbind(test,as.character(newpredict) )
head(newresults)
table(newresults[,9],newresults[,10])
#############################################################################
#####################-----------KKnn---------------------
rm(list=ls())
library(kknn)
?kknn
#normalization and na removal functions
na.zero <- function (x) {
x[is.na(x)] <- 0
return(x)
}
mmnorm <-function(x) {z<-((x-min(x))/(max(x)-min(x)));return(z) }
#loading dataset
filtereddataset<-read.csv("C:/Users/anki/Desktop/Stevens/SEM 1/513/Project/Code/dataset/new4.csv")
attach(filtereddataset)
#categorizing Arrival delay
filtereddataset$ArrDelay_catnew[ArrDelay < -5] <- "Early"
filtereddataset$ArrDelay_catnew[ArrDelay >= -5 & ArrDelay <= 5] <- "ONTIME"
filtereddataset$ArrDelay_catnew[ArrDelay > 5 & ArrDelay < 20] <- "late"
filtereddataset$ArrDelay_catnew[ArrDelay >= 20] <- "VERY_late"
data<-filtereddataset
data_new_k<-cbind(
DayOfMonth=mmnorm(data$DayofMonth),
DayOfWeek=mmnorm(data$DayOfWeek),
CRSDepTime=mmnorm(data$CRSDepTime),
CRSArrTime=mmnorm(data$CRSArrTime) ,
UniqueCarrier=mmnorm(as.numeric(factor(data$UniqueCarrier))),
Origin=mmnorm(as.numeric(factor(data$Origin))),
Dest=mmnorm(as.numeric(factor(data$Dest_Type))),
ArrDelay_cat=as.character(data$ArrDelay_catnew)
)
data_new_k<-as.data.frame(data_new_k)
data_new_k<-na.omit(data_new_k)
factor(data_new_k$ArrDelay_cat)
is.data.frame(data_new_k)
idx1<-seq(1:5000)
data_new_k<-data_new_k[idx1,]
idx<-sample(nrow(data_new_k),as.integer(.70*nrow(data_new_k)))
trainingk<-data_new_k[idx,]
testk<-data_new_k[-idx,]
is.data.frame(trainingk)
#applying kknn
predict_1 <- kknn(formula=ArrDelay_cat~., trainingk, testk, k=38,kernel="optimal")
head(predict_1)
fitWalc <- fitted(predict_1)
results <- cbind(testk$ArrDelay_cat, fitWalc)
wrong <- results[,1]!=results[,2]
rateWalc <- sum(wrong)/length(wrong)
rateWalc
|
167b7930d61cc92dc996b2ce2757d397be032fec
|
44b28da4d2fa37ca7542a575c2d1be2a8716efa6
|
/Efficient Behavior Mapper/test_smts.r
|
942cf93cbac271b792d41b0fbde44d4a60157ed9
|
[] |
no_license
|
mertedali/ISDC2018SummerSchool
|
bee492e7f1c84cd673221904ca790d82c07b5667
|
920dbb7c4bc3e8fda95887f8fddc3a137a973ee5
|
refs/heads/master
| 2020-03-24T21:06:57.247039
| 2018-08-06T11:31:24
| 2018-08-06T11:31:24
| 143,014,133
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 398
|
r
|
test_smts.r
|
params = result[, 1:2]
result = result[, -c(1:2)]
result = cbind(1, result)
testdata = result
source("prepare_test.r")
test_terminal=attr(predict(RFins, as.matrix(finaltest[,2:ncol(finaltest)]) ,nodes=TRUE), "nodes")
codetst=matrix(generatecodebook(RFins$forest$nodestatus,test_terminal,nofnode,ntestobs),noftest,noftree*nofnode)
predicted=predict(RFts,codetst,type='response')
|
1f01c3e440be9c2eb206a577316af7f43c3891d4
|
7312924a61cc00cac1c9f2d4ed082ad8ce551d03
|
/data-raw/nga_highlights.R
|
ebceb72048fcce4748636a371fbc3041744510e7
|
[] |
no_license
|
mdlincoln/breadbox
|
33d2f31d9b657b030aa924a93a33983aa54cd9be
|
0b20f4c23587d1ae9debde3dab310b2987428f43
|
refs/heads/master
| 2020-03-17T09:12:59.058451
| 2018-05-15T05:56:56
| 2018-05-15T05:56:56
| 133,466,130
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 445
|
r
|
nga_highlights.R
|
library(tidyverse)
library(stringr)
nga_highlights <- clean_collection_data %>%
filter(onview == "true") %>%
filter(!is.na(area)) %>%
mutate(
label = str_wrap(glue("{artists.0.name}, \"{title}\""), width = 30),
long_label = glue("{artists.0.name}, \"{title}\" (National Gallery of Art)", width = 30)) %>%
select(label, long_label, width, height, area) %>%
arrange(area)
save(nga_highlights, file = "data/nga_highlights.rda")
|
71dbd087f07d27474ec994ed9ad1038b9e1e3c98
|
4b4c0c48f4004383b728dce2654b56ec7a4c6851
|
/Exploratory-Analysis/Summary.R
|
7b3d8f05656dd54a73bc7ea40cbabdbec5d45eb3
|
[] |
no_license
|
AmirrorImage/INFO-201-Final-Project
|
5c5e0a3a713f75a7e21c649ba3b8d4053f2f6b85
|
4e331f3e67ccf73f1fb36723ae4604947a7d33e8
|
refs/heads/main
| 2023-03-23T13:48:34.641730
| 2021-03-18T02:00:24
| 2021-03-18T02:00:24
| 334,546,015
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,015
|
r
|
Summary.R
|
library(tidyverse)
data <- read.csv("https://raw.githubusercontent.com/AmirrorImage/INFO-201-Final-Project/main/Data/Use_Of_Force.csv")
# This file shows some facts I calculated from the data
total_observations <- print(nrow(data))
total_features <- print(ncol(data))
num_male_female <- data %>%
count(Subject_Gender)
num_male <- num_male_female %>%
filter(Subject_Gender == "Male") %>%
pull(n)
num_female <- num_male_female %>%
filter(Subject_Gender == "Female") %>%
pull(n)
num_unknown <- num_male_female %>%
filter(Subject_Gender =="Not Specified") %>%
pull(n)
num_officers <- data %>%
count(Officer_ID)
off_num <- nrow(num_officers)
repeat_officers <- data %>%
count(Officer_ID) %>%
filter(n > 1)
rep_off <- nrow(repeat_officers)
dates <- as.Date(data$Occured_date_time)
most_recent <- max(dates, na.rm = T)
date_earliest <- min(dates, na.rm = T)
race_unspecified <- data %>%
filter(Subject_Race == "Not Specified")
race_unspecified <- nrow(race_unspecified)
|
220d94168b5896d22e2ad9ee05e1ba5ab110fc9f
|
d931c381ae927719bfed81a3b9ea16aeaf78022f
|
/data_analysis/plotting/logistic_plot.R
|
a3fe7150d145959dd39f1b1ef9a45a8b6288f52a
|
[] |
no_license
|
samcheyette/transfer_learning_v1
|
ce5e3109411f36e26d481ef49263b474f6e2dc8d
|
daad6d7261199b7a59dad7d896a358a403d3c9f1
|
refs/heads/master
| 2020-04-05T13:04:33.994131
| 2017-08-04T14:48:38
| 2017-08-04T14:48:38
| 95,061,035
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,803
|
r
|
logistic_plot.R
|
library(ggplot2)
library(reshape)
library(grid)
library(dplyr)
library(aod)
data <- read.csv("outR.csv")
head(data)
t1 <- theme(axis.text=element_text(size=18),
strip.text.x = element_text(size = 20),
plot.title=element_text(size=18),
#axis.text.x=element_blank(),
axis.text.x=element_text(size=15),
axis.title.x=element_text(size=18),
axis.title.y=element_text(size=18),
axis.text.y=element_text(size=16),
legend.title=element_blank(),
legend.text=element_text(size=17),
legend.key.size = unit(4, 'lines'))
###################################################
##############SEQUENCE 2###########################
bin <- 3
m.1 <- data %>% filter(which == 0) %>%
mutate(timestep2=floor(timestep/bin)+1) %>%
group_by(subject, timestep2) %>%
mutate(correct=sum(correct)/bin) %>%
group_by(timestep2) %>%
mutate(n_cond=sum(which + 1)) %>%
mutate(prob_at_time_real=sum(correct)/n_cond) %>%
mutate(prob_at_time=prob_at_time_real - 0.5) %>%
group_by(timestep2) %>%
top_n(n=1, wt=timestep) %>%
top_n(n=1, wt=subject) %>%
ungroup %>%
mutate(std_err=((prob_at_time_real * (1-prob_at_time_real)/n_cond)**0.5)) %>%
select(timestep, timestep2, prob_at_time_real, prob_at_time, consistent, std_err)
m.2 <- data %>% filter(which == 1) %>%
mutate(timestep2=floor(timestep/bin)+1) %>%
group_by(subject, timestep2) %>%
mutate(correct=sum(correct)/bin) %>%
group_by(consistent, timestep2) %>%
mutate(n_cond=sum(which)) %>%
mutate(prob_at_time_real=sum(correct)/n_cond) %>%
mutate(prob_at_time=prob_at_time_real - 0.5) %>%
group_by(timestep2) %>%
top_n(n=1, wt=timestep) %>%
group_by(consistent) %>%
top_n(1, wt=subject) %>%
ungroup %>%
mutate(std_err=((prob_at_time_real * (1-prob_at_time_real)/n_cond)**0.5)) %>%
select(timestep, timestep2, prob_at_time, prob_at_time_real, consistent, std_err)
head(m.2)
m.2$consistent <- factor(m.2$consistent)
#m.2 <- m.2 %>% filter(consistent==0)
#p.2 <- ggplot(data=m.2, aes(x=timestep, y=prob_at_time, group=consistent)) +
# geom_line(aes(color=consistent))
#p.2 <- ggplot(data=m.2, aes(x=timestep2, y=prob_at_time, group=consistent)) +
# geom_bar(stat='identity', position='dodge', aes(fill=consistent)) +
# geom_errorbar(stat='identity', position='dodge',
# aes(ymax=std_err+prob_at_time,
# ymin=prob_at_time-std_err, group=consistent),
# size=0.5, alpha=0.6) +
#geom_point(data=m.1, aes(x=timestep2, y=prob_at_time,
# colour="Training"), size=6.0)
p.2 <- ggplot(data=m.2, aes(x=timestep2, y=prob_at_time_real,
group=consistent)) +
geom_line(aes(color=consistent), size=3.0) +
geom_errorbar(stat='identity',
aes(ymax=std_err+prob_at_time_real,
ymin=prob_at_time_real-std_err,
group=consistent), width=0.4,
size=0.5, alpha=0.6) +
geom_line(data=m.1, aes(x=timestep2,
y=prob_at_time_real,
linetype="Training"),
size=3.0) +
geom_errorbar(data=m.1, aes(x=timestep2,
ymax=std_err+prob_at_time_real,
ymin=prob_at_time_real-std_err,
group=consistent), width=0.4,
size=0.5, alpha=0.6)
p.2 <- p.2 + xlab("Trial bins") + ylab("Accuracy") +
t1 + ylim(0.45,0.88) +
ggtitle("Performance on transfer sequence") +
scale_x_discrete( expand = waiver(),
limits=c("1-3", "4-6", "7-9", "10-12", "13-15")) +
scale_fill_manual(values=c("#990000", "#009900", "#000000"),
labels=c("Incongruent", "Congruent")) +
scale_color_manual(values=c("#990000", "#009900","#000000"),
labels=c("Incongruent Transfer", "Congruent Transfer",
"Training"))+
scale_linetype_manual(values=c("dotted"),
labels=c("Training "))
ggsave("acc_over_time.png", height=9, width=16)
|
0dc35358f6847dcc8a422ca7751eeba1960dbbc9
|
6287bd279463ebc8ab78da4f84eb5adee88f7c8c
|
/R/fit_models_JRSSA.R
|
66ec4ed13d04ff7f401d9e1eadca969c38417c51
|
[] |
no_license
|
spatialstatisticsupna/Dowry_JRSSA_article
|
ac7803418bd63e66d6c1e9cfc901c71851e698a5
|
0bc961b558c72ec2c7330ddbb60d4e00c7218fc6
|
refs/heads/master
| 2022-05-04T21:06:55.990162
| 2022-03-29T11:19:19
| 2022-03-29T11:19:19
| 220,030,538
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,578
|
r
|
fit_models_JRSSA.R
|
##########################################################################################
## Title: Crime against women in India: unveiling spatial patterns and temporal trends ##
## of dowry deaths in the districs of Uttar Pradesh ##
## ##
## Authors: Vicente, G. - Goicoa, T. - Fernandez-Rasines, P. - Ugarte, M.D. ##
## ##
## https://doi.org/10.1111/rssa.12545 ##
## ##
##########################################################################################
rm(list = ls())
## Load library
library(spdep); library(INLA); library(tmap)
## Working directory
dir.main<-"" # Set an appropiate directory
setwd(dir.main)
## Load data and cartographies
load("data_JRSSA.RData")
##################################
## Data organization
##################################
## Expected number of cases and Standardized mortality ratio (SMR)
data$exp<- data$pop_linear * (sum(data$obs)/sum(data$pop_linear))
data$smr<- data$obs/data$exp
## Identifiers: "ID_area", "ID_year" and "ID_area_year"
ID<- data.frame(dist=carto_up$dist, ID_area=carto_up$ID_area)
data<- merge(data, ID, by=c("dist"))
data <- data[order(data$year, data$ID_area),]; rownames(data)<-NULL
data$ID_year<- rep(1:length(unique(data$year)), each=length(unique(data$ID_area)))
data$ID_area_year<-seq(1,length(unique(data$ID_year))*length(unique(data$ID_area)))
## Number of areas and number of time periods
n<- length(unique(data$ID_area))
t<- length(unique(data$ID_year))
## Initial and final time periods
t.from<- min(data$year)
t.to<- max(data$year)
## Covariates standardization
for(i in c(1,5,6)){ eval(parse(text= paste0("data$x",i,"_stand<- scale(data$x",i,")" ))) }
## Spatial neighborhood matrix (Q_{xi})
spdep::nb2INLA("uttar_pradesh_nb.graph", spdep::poly2nb(carto_up))
g <- INLA::inla.read.graph("uttar_pradesh_nb.graph")
Q_xi <- matrix(0, g$n, g$n)
for (i in 1:g$n){
Q_xi[i,i]=g$nnbs[[i]]
Q_xi[i,g$nbs[[i]]]=-1
}
## Structure matrix to implement the LCAR prior.
Q_Leroux <- diag(n)-Q_xi
## Temporal structure matrix for a RW1 prior
D1 <- diff(diag(t), differences=1)
Q_gammaRW1 <- t(D1)%*%D1
## Temporal structure matrix for a RW2 prior
D2 <- diff(diag(t),differences=2)
Q_gammaRW2 <- t(D2)%*%D2
##########################################################################################
## Fitting models: log(p_{it}) = eta + xi_{i} + gamma_{t} + delta_{it} + beta*x ##
## mu_{it}= n_{it} * p_{it} ##
##########################################################################################
## Define appropriate hyperprior distributions (for LCAR)
sdunif="expression:
logdens=-log_precision/2;
return(logdens)"
lunif = "expression:
a = 1;
b = 1;
beta = exp(theta)/(1+exp(theta));
logdens = lgamma(a+b)-lgamma(a)-lgamma(b)+(a-1)*log(beta)+(b-1)*log(1-beta);
log_jacobian = log(beta*(1-beta));
return(logdens+log_jacobian)"
## Define appropriate constraint matrices
## (a) Spatio-temporal random effect: Type I
id_nt<-diag(1,nrow=n*t)
## (b) Spatio-temporal random effect: Type II
## (b.1) Temporal random effect: RW1
R_1_2 <- kronecker(Q_gammaRW1,diag(n)); r_def_1_2 <- n; A_constr_1_2 <- kronecker(matrix(1,1,t),diag(n)) # LCAR, DCAR, ICAR
A_constr_1_2 <- A_constr_1_2[-1,]
R_1_2_scaled<- R_1_2*exp(mean(log(diag(INLA:::inla.ginv(R_1_2))))) # BYM2
## (b.2) Temporal random effect: RW2
R_2_2 <- kronecker(Q_gammaRW2,diag(n)); r_def_2_2 <- 2*n; A_constr_2_2 <- kronecker(matrix(1,1,t),diag(n)) # LCAR, DCAR, ICAR
A_constr_2_2 <- A_constr_2_2[-1,]
R_2_2_scaled<- R_2_2*exp(mean(log(diag(INLA:::inla.ginv(R_2_2))))) # BYM2
## (c) Spatio-temporal random effect: Type III
## (c.1) Temporal random effect: iid
R_0_3 <- kronecker(diag(t),Q_xi); r_def_0_3 <- t; A_constr_0_3 <- kronecker(diag(t),matrix(1,1,n)) # LCAR, DCAR, ICAR
A_constr_0_3 <- A_constr_0_3[-1,]
R_0_3_scaled<- R_0_3*exp(mean(log(diag(INLA:::inla.ginv(R_0_3))))) # BYM2
## (c.2) Temporal random effect: RW1
R_1_3 <- kronecker(diag(t),Q_xi); r_def_1_3 <- t; A_constr_1_3 <- kronecker(diag(t),matrix(1,1,n)) # LCAR, DCAR, ICAR
A_constr_1_3 <- A_constr_1_3[-1,]
R_1_3_scaled<- R_1_3*exp(mean(log(diag(INLA:::inla.ginv(R_1_3))))) # BYM2
## (c.3) Temporal random effect: RW2
R_2_3 <- kronecker(diag(t),Q_xi); r_def_2_3 <- t; A_constr_2_3 <- kronecker(diag(t),matrix(1,1,n)) # LCAR, DCAR, ICAR
A_constr_2_3 <- A_constr_2_3[-1,]
R_2_3_scaled<- R_2_3*exp(mean(log(diag(INLA:::inla.ginv(R_2_3))))) # BYM2
## (d) Spatio-temporal random effect: Type IV
## (d.1) Temporal random effect: RW1
R_1_4 <- kronecker(Q_gammaRW1,Q_xi); r_def_1_4 <- n+t-1; A.1.1 <- kronecker(matrix(1,1,t),diag(n)); A.1.2 <- kronecker(diag(t),matrix(1,1,n)); A_constr_1_4 <- rbind(A.1.1[-1,],A.1.2[-1,]) # LCAR, DCAR, ICAR
R_1_4_scaled<- R_1_4*exp(mean(log(diag(INLA:::inla.ginv(R_1_4))))) # BYM2
## (d.2) Temporal random effect: RW1
R_2_4 <- kronecker(Q_gammaRW2,Q_xi); r_def_2_4 <- 2*n+t-2; A.2.1 <- kronecker(matrix(1,1,t),diag(n)); A.2.2 <- kronecker(diag(t),matrix(1,1,n)); A_constr_2_4 <- rbind(A.2.1[-1,],A.2.2[-1,]) # LCAR, DCAR, ICAR
R_2_4_scaled<- R_2_4*exp(mean(log(diag(INLA:::inla.ginv(R_2_4))))) # BYM2
## Load formulas
source("inla_formulas_JRSSA.R")
##################################
## Fitting models with x1, x5, and x6
##################################
Data.INLA<- data.frame(O=data$obs, E=data$exp, pop=data$pop_linear,
x1_stand=data$x1_stand, x5_stand=data$x5_stand, x6_stand=data$x6_stand,
ID.area= data$ID_area, ID.year=data$ID_year, ID.area.year=data$ID_area_year)
models<-list(lcar.iid.ad=NULL, lcar.rw1.ad=NULL, lcar.rw2.ad=NULL, bym2.iid.ad=NULL, bym2.rw1.ad=NULL, bym2.rw2.ad=NULL, dcar.iid.ad=NULL, dcar.rw1.ad=NULL, dcar.rw2.ad=NULL, icar.iid.ad=NULL, icar.rw1.ad=NULL, icar.rw2.ad=NULL,
lcar.iid.t1=NULL, lcar.rw1.t1=NULL, lcar.rw2.t1=NULL, bym2.iid.t1=NULL, bym2.rw1.t1=NULL, bym2.rw2.t1=NULL, dcar.iid.t1=NULL, dcar.rw1.t1=NULL, dcar.rw2.t1=NULL, icar.iid.t1=NULL, icar.rw1.t1=NULL, icar.rw2.t1=NULL,
lcar.rw1.t2=NULL, lcar.rw2.t2=NULL, bym2.rw1.t2=NULL, bym2.rw2.t2=NULL, dcar.rw1.t2=NULL, dcar.rw2.t2=NULL, icar.rw1.t2=NULL, icar.rw2.t2=NULL,
lcar.iid.t3=NULL, lcar.rw1.t3=NULL, lcar.rw2.t3=NULL, bym2.iid.t3=NULL, bym2.rw1.t3=NULL, bym2.rw2.t3=NULL, dcar.iid.t3=NULL, dcar.rw1.t3=NULL, dcar.rw2.t3=NULL, icar.iid.t3=NULL, icar.rw1.t3=NULL, icar.rw2.t3=NULL,
lcar.rw1.t4=NULL, lcar.rw2.t4=NULL, bym2.rw1.t4=NULL, bym2.rw2.t4=NULL, dcar.rw1.t4=NULL, dcar.rw2.t4=NULL, icar.rw1.t4=NULL, icar.rw2.t4=NULL)
for(i in 1:length(formulas)){
models[[i]]<- INLA::inla(formulas[[i]], family="poisson", data=Data.INLA, E=pop, control.predictor=list(compute=TRUE, cdf=c(log(1))), control.compute=list(dic=TRUE, cpo=TRUE, waic=TRUE), control.inla=list(strategy="laplace", npoints=21))
}
## save models
##########################################################################################
##########################################################################################
|
87f686bf7187fc562e1a8a6e8b5350c0089a5887
|
827c9202f56d6a50b357ccc37d81fdc1683a5955
|
/tests/testthat.R
|
9e0e489989efa7367dbd3068f583ceafec9c8f9b
|
[] |
no_license
|
AlexPiche/DPsurv
|
7fef615c1d97bc7da2f924542cf8b4a41fa32e29
|
b696cd9fc1fda6d45c1f2640f2f3818b4ee8543e
|
refs/heads/master
| 2020-04-01T19:27:12.926209
| 2016-11-29T20:51:34
| 2016-11-29T20:51:34
| 62,817,221
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 54
|
r
|
testthat.R
|
library(testthat)
library(DPsurv)
test_check("DPsurv")
|
acc227a7d42d78c6eb90687ad3e1044293f7fdf2
|
cc30a22201e5f3ddce6e53d60c651c210ef3fe00
|
/Cap.7/07_03/DM_07_03.R
|
ae800913c3ba35ab1f327cfb43a70b477ccf6539
|
[] |
no_license
|
Varnei/Ciencia_de_Dados_LL_Fundamentos_da_Ciencia_de_Dados_Mineracao_de_Dados_Barton_Poulson
|
2357667cd2d59d128f9b6977bd98c9e92638df83
|
f33902949cd7d5a4dfa9dcd4e6f848334972e4b9
|
refs/heads/main
| 2023-07-04T11:56:27.829806
| 2021-08-07T03:12:15
| 2021-08-07T03:12:15
| 389,764,836
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,730
|
r
|
DM_07_03.R
|
# DM_07_03.R
# INSTALAR E CARREGAR PACOTES ##############################
pacman::p_load(lars, caret) # Importando bibliotecas
# DADOS ####################################################
# Importar os dados
data = read.csv("~/Desktop/winequality-red.csv")
# Definir grupos de variáveis
x <- as.matrix(data[-12])
y <- data[, 12]
# Seleção regressiva de características com o algoritmo de
# eliminação recursiva de características (RFE, um método
# incorporado comumente usado com máquinas
# de vetores de suporte)
ctrl <- rfeControl(method = "repeatedcv",
repeats = 5,
verbose = TRUE,
functions = lmFuncs)
# Isso demora um pouco.
rfe <- rfe(x, y ,
sizes = c(1:11),
rfeControl = ctrl)
# Ver resultados
rfe
# Manter características identificadas pela RFE
x <- as.matrix(data[rfe$optVariables])
# MODELOS ADICIONAIS #######################################
# Regressão stepwise convencional
stepwise <- lars(x,y, type = "stepwise")
# Stagewise: como a stepwise, mas com melhor generalização
forward <- lars(x,y, type = "forward.stagewise")
# LAR: Least Angle Regression, ou regressão de ângulo mínimo
lar <- lars(x,y, type= "lar")
# LASSO: Least Absolute Shrinkage and Selection Operator,
# ou mínimos absolutos reduzidos e operador de seleção
lasso <- lars(x, y, type = "lasso")
# Comparação de modelos
r2comp <- c(stepwise$R2[6], forward$R2[6],
lar$R2[6], lasso$R2[6])
names(r2comp) <- c("stepwise", "forward", "lar", "lasso")
r2comp
# LIMPAR ###################################################
# Limpar espaço de trabalho
rm(list = ls())
# Limpar pacotes
pacman::p_unload(lars, caret)
# Limpar console
cat("\014") # CTRL+L
|
91e13532b0b212e393a093ca1a478d64e0d56a75
|
cd19071385b5760d51c5c9fa687d4c8bf74e5d57
|
/scripts/helper_file.R
|
4f43847fa2cf97f2e950a29c1768e8cf0e021763
|
[] |
no_license
|
shiva-g/The-Cube
|
b7ee893b6fb04b6b1e1921e756bc3005548b3c6b
|
ab235a5cc4367abf587fdaf1d152122e41ec7de2
|
refs/heads/master
| 2022-12-25T23:08:30.661267
| 2020-09-14T15:22:58
| 2020-09-14T15:22:58
| 197,828,206
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,695
|
r
|
helper_file.R
|
library(optparse,quietly = T)
library(yaml,quietly = T)
library(tidyverse, quietly = T)
library(dplyr, quietly = T)
library(ggplot2,quietly = T)
library(ggridges,quietly = T)
library(ggrepel, quietly = T)
if(exists("input.yaml")){
input.yaml <- input.yaml
}else{
message('Input YAML not found.\n')
break;
}
if(is.null(input.yaml$outputDir)){
message("Please specify the outputDir in input yaml file.")
break
} else {
dir.create(paste0(input.yaml$outputDir,"/temp"),showWarnings = F)
}
if( is.null(input.yaml$aed.encounter)){
message('Parameter aed.encounter is not provided. Please provide full path to the file. \n')
break
} else if(!file.exists(input.yaml$aed.encounter)){
message('File aed.encounter does not exist. Please provide full path to the file. \n')
break
} else {
merge_count <- read_csv(input.yaml$aed.encounter)
}
if( is.null(input.yaml$diagnosis)){
message('Parameter diagnosis is not provided. Please provide full path to the file. \n')
break
} else if(!file.exists(input.yaml$diagnosis)){
message('File diagnosis does not exist. Please provide full path to the file. \n')
} else {
dx_shifted_hpo_raw <- read_csv(input.yaml$diagnosis)
}
if( is.null(input.yaml$survival)){
message('Parameter survival is not provided. Please provide full path to the file. \n')
break
} else if(!file.exists(input.yaml$survival)){
message('File survival does not exist. Please provide full path to the file. \n')
} else {
survival <- read_csv(input.yaml$survival)
}
if(is.null(input.yaml$hpo_tree)){
hpo_tree = read_csv("files/hpo_is.a_tree.csv")
} else {
hpo_tree = read_csv(input.yaml$hpo_tree)
}
if(is.null(input.yaml$hpo_ancs)){
hpo_ancs = read_csv("files/hpo_ancestors.csv")
} else {
hpo_ancs = read_csv(input.yaml$hpo_ancs)
}
# Filtering the datasets for patients with encounter before the age of 25.
dx_shifted_hpo_raw %>% filter(! NEURO_DX %>% is.na) -> tmp
merge_count %>% filter(lower < 25) %>%
filter(STUDY_ID %in% tmp$STUDY_ID) -> merge_count
dx_shifted_hpo_raw %>% filter(STUDY_ID %in% merge_count$STUDY_ID & AGE < 25 & !(is.na(NEURO_DX))) -> dx_shifted_hpo
survival %>% filter(STUDY_ID %in% merge_count$STUDY_ID ) -> survival
merge_count$upper[which(merge_count$upper > 25)] = 25
rm(tmp)
length(unique(survival$STUDY_ID)) -> tmp
length(unique(dx_shifted_hpo$STUDY_ID)) -> tmp_1
length(unique(merge_count$STUDY_ID)) -> tmp_2
if(tmp == tmp_1) {
if(tmp == tmp_2){
if(tmp_1 == tmp_2){
indv <- tmp
} else {
message('Number of individuals in diagnosis and aed enconters are different')
break
}
} else {
message('Number of individuals in survival and aed enconters are different')
break
}
} else {
message('Number of individuals in survival and diagnosis are different')
break
}
rm(tmp,tmp_1,tmp_2)
message(paste0('Numbers from the data provided :\n ',
length(unique(survival$STUDY_ID)),'\tIndividuals \n',
round(sum(merge_count$upper) - sum(merge_count$lower)) ,'\tPatient years.\n'))
######### base to prop v1
# base_temp <- adding def of HPO terms to diagnosis table
base_temp <- dx_shifted_hpo %>%
select(HPO_IMO_ID,AGE,STUDY_ID) %>%
unique() %>%
separate_rows(HPO_IMO_ID,sep=';') %>%
left_join((hpo_tree %>% select(term, def)), by = c("HPO_IMO_ID" = "term")) %>%
rename(HPO_IMO_def = def)
base_temp %>% filter( !is.na(HPO_IMO_def)) -> base_temp
#all base terms propagate up to the parent term
prop2 <- base_temp %>%
select(STUDY_ID,AGE,HPO_IMO_ID) %>%
left_join(hpo_ancs,by = c("HPO_IMO_ID"="term")) %>%
mutate(complete = grepl('HP:0000001',ancs)) %>%
group_by(complete) %>% summarize(n = n())
prop2 <- base_temp %>%
select(STUDY_ID,AGE,HPO_IMO_ID) %>%
left_join(hpo_ancs,by = c("HPO_IMO_ID"="term"))
prop3 <- prop2 %>%
select(STUDY_ID,AGE,ancs) %>%
separate_rows(ancs,sep=';') %>%
rename(HPO_ID_prop = ancs)
prop4 <- prop3 %>%
unique()
prop4b <- prop4 %>%
left_join(hpo_ancs,by = c("HPO_ID_prop"="term")) %>%
select(STUDY_ID,AGE,HPO_ID_prop,def) %>%
rename(HPO_def_prop = def)
#Does every time point have 'HP:0000001'
prop5 <- prop4 %>% filter(HPO_ID_prop == 'HP:0000001') %>% group_by(AGE) %>% summarise(n = n())
if( prop5 %>% filter(n == 0) %>% NROW() != 0)
{
message("Every time point did not propogate to HP:0000001, check the datasets.")
break;
} else {
rm(prop5,prop3,prop4,prop2)
prop_temp <- prop4b; rm(prop4b)
}
prop_temp %>% filter( !is.na(HPO_ID_prop)) -> prop_temp
write_csv(base_temp, paste0(input.yaml$outputDir,"/temp/base_hpo.csv"))
write_csv(prop_temp, paste0(input.yaml$outputDir,"/temp/prop_hpo.csv"))
|
681ac6df393f6d43801b948c9eb6951f235e008a
|
bb9b8b991fecd538c5f93a8303373030b31e59d9
|
/scripts/coverage_plots_g.R
|
f417877f6a966104d9db0a0b0f5971c5400d0243
|
[] |
no_license
|
LuffyLuffy/assembly_pipeline
|
54a4b8cdb91302cee9250764c0ea25fdf30ef128
|
ce8d1b5a291cb00b79484da1f59d9869c81572ca
|
refs/heads/master
| 2023-09-03T10:11:54.106672
| 2021-11-02T05:40:52
| 2021-11-02T05:40:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 907
|
r
|
coverage_plots_g.R
|
#coverage.files<-list.files("~/coverage_plotting", full.names = TRUE, pattern = ".txt")
#coverage.names<-list.files("~/coverage_plotting", full.names = F, pattern=".txt")
args<- commandArgs(trailingOnly = TRUE)
coverage.file <-args[1]
#setwd("/Volumes/Georgia's Hard drive/temp_work")
pdf.file <- gsub("txt","pdf", coverage.file)
plot.colors <- c("red","blue","green","yellow","purple")
coverage <- read.delim(coverage.file)
pdf(pdf.file, width = 5, height= 4)
plot(-100,-100, xlim=c(0,250), ylim=c(1,1e6), xlab="Coverage", ylab="Number of basepairs", log="y")
colnames(coverage) <- c("contig", "position", "coverage")
contigs <- unique(coverage[,1])
for(j in 1:length(contigs)) {
contig.cov <- subset(coverage,contig==contigs[j])
cov.hist <- hist(contig.cov$coverage, plot=F, breaks=50)
points(cov.hist$mids, cov.hist$counts, ty="o", col=plot.colors[j], pch=19, cex=0.5)
}
dev.off()
|
a9257a11b22a30477ff0d80c845bd1326e59bb9d
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/imaginator/examples/ClaimsByFirstReport.Rd.R
|
c34fb1763eaf5ea9fb59552e73a85f626c12fe57
|
[] |
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
| 456
|
r
|
ClaimsByFirstReport.Rd.R
|
library(imaginator)
### Name: ClaimsByFirstReport
### Title: Claims by first report
### Aliases: ClaimsByFirstReport
### ** Examples
# This will generate a claim data frame which has 1,000 records
# each of which has a severity of 100
dfPolicy <- NewPolicyYear(100, 2001)
dfClaims <- ClaimsByFirstReport(
dfPolicy
, Frequency = FixedHelper(10)
, PaymentSeverity = FixedHelper(100)
, Lags = 1)
|
6925899de6e992c035f8b0f5a889077120cea2d9
|
9e26b0d278981b82487e0c60fbf7f2b975d63fea
|
/R/register_smacof.R
|
e338c4f69846732f6e308775f4c001a521af10db
|
[] |
no_license
|
cran/seriation
|
1ea5b4817e7edca61f2e252753f5763b0c4e2d73
|
84790e8861d5a41c56dffb7761fd38070f284291
|
refs/heads/master
| 2023-08-27T21:40:36.310265
| 2023-07-20T21:20:02
| 2023-07-20T21:30:42
| 17,699,608
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,766
|
r
|
register_smacof.R
|
#######################################################################
# seriation - Infrastructure for seriation
# Copyright (C) 2015 Michael Hahsler, Christian Buchta and Kurt Hornik
#
# 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 2 of the License, or
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#' Register Seriation Methods from Package smacof
#'
#' Registers the `"MDS_smacof"` method for [seriate()] based on multidemensional
#' scaling using stress majorization and the corresponding `"smacof_stress0"`
#' criterion implemented in package smacof (de Leeuw & Mair, 2009).
#'
#' Seriation method `"smacof"` implements stress majorization with several transformation functions.
#' These functions are passed on as the type control parameter. We default
#' to `"ratio"`, which together with `"interval"` performs metric MDS.
#' `"ordinal"` can be used
#' for non-metric MDS. See [smacof::smacofSym()] for details on the
#' control parameters.
#'
#' The corresponding criterion calles `"smacof_stress0"` is also registered.
#' There additional parameter `type` is used to specify the used
#' transformation function. It should agree with the function used for seriation.
#' See [smacof::stress0()] for details on the stress calculation.
#'
#' Note: Package \pkg{smacof} needs to be installed.
#'
#' @aliases registersmacof smacof
#' @family seriation
#' @returns Nothing.
#'
#' @references
#' Jan de Leeuw, Patrick Mair (2009). Multidimensional Scaling Using Majorization: SMACOF in R.
#' _Journal of Statistical Software, 31(3),_ 1-30. \doi{10.18637/jss.v031.i03}
#' @keywords optimize cluster
#' @examples
#' \dontrun{
#' register_smacof()
#'
#' get_seriation_method("dist", "MDS_smacof")
#'
#' d <- dist(random.robinson(20, pre = TRUE))
#'
#' ## use Banded AR form with default clustering (complete-link)
#' o <- seriate(d, "MDS_smacof", verbose = TRUE)
#' pimage(d, o)
#'
#' # recalculate stress for the order
#' MDS_stress(d, o)
#'
#' # ordinal MDS. stress needs to be calculated using the correct type with stress0
#' o <- seriate(d, "MDS_smacof", type = "ordinal", verbose = TRUE)
#' criterion(d, o, method = "smacof_stress0", type = "ordinal")
#' }
#' @export
register_smacof <- function() {
check_installed("smacof")
.smacof_control <- structure(
list(
type = "ratio",
init = "torgerson",
relax = FALSE,
modulus = 1,
itmax = 1000,
eps = 1e-06,
verbose = FALSE
),
help = list(
type = 'MDS type: "interval", "ratio", "ordinal" (nonmetric MDS)',
init = 'start configuration method ("torgerson"/"random")',
relax = "use block relaxation for majorization?",
modulus = "number of smacof iterations per monotone regression call",
itmax = "maximum number of iterations",
eps = "convergence criterion"
)
)
seriate_dist_smacof <- function(x, control = NULL) {
control <- .get_parameters(control, .smacof_control)
r <-
smacof::smacofSym(
x,
ndim = 1,
type = control$type,
verbose = control$verbose,
init = control$init,
relax = control$relax,
modulus = control$modulus,
itmax = control$itmax,
eps = control$eps
)
if (control$verbose)
print(r)
config <- drop(r$conf)
names(config) <- labels(x)
o <- order(config)
attr(o, "configuration") <- config
o
}
seriation::set_seriation_method(
"dist",
"MDS_smacof",
seriate_dist_smacof,
"Seriation based on multidemensional scaling using stress majorization (de Leeuw & Mair, 2009).",
.smacof_control,
optimizes = "Other (MDS stress)",
verbose = TRUE
)
smacof_crit_stress0 <-
function(x,
order,
type = "ratio",
warn = FALSE,
...) {
conf <- get_config(order)
if (is.null(conf))
conf <- uniscale(x, order, warn = warn)
smacof::stress0(x, cbind(conf), type = type, ...)$stress
}
seriation::set_criterion_method(
"dist",
"smacof_stress0",
smacof_crit_stress0,
"Stress0 calculated for different transformation types from package smacof.",
FALSE,
verbose = TRUE
)
}
|
8e1f0208a97ec1bcc0d524abdec8324495a82541
|
6ab148f7967e3de987c9b87ea7f9b0092ab0dc8e
|
/01-EDA-e-vis/1-eda-dados-posgraduandos.R
|
1978435bbb633bfd714753c5fa785de152a7afb1
|
[] |
no_license
|
guilhermemg/fpcc2
|
6d53a8a12ed066ba64e9158724cc0a4fe54b239a
|
c1e8cb98f3ef7141cb64f891f19bd88dbb73c3a5
|
refs/heads/master
| 2020-03-25T15:48:56.349295
| 2018-05-28T12:11:10
| 2018-05-28T12:11:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,650
|
r
|
1-eda-dados-posgraduandos.R
|
# Você precisará instalar esses pacotes. Faça install.packages("nome") para cada um.
library(dplyr, warn.conflicts = F)
library(readr)
library(ggplot2)
# theme_set(theme_bw()) # você pode preferir os gráficos assim
library(gmodels)
# ====================================
# LER, ARRUMAR, LIMPAR
# ====================================
# Repare que estou usando readr::read_csv em vez de base::read.csv
# read_csv é bem mais rápido, adivinha melhor os tipos das colunas
# e nunca usa Factor, sempre usa String no lugar. Geralmente ajuda.
dados = read_csv("dados//Dados de alunos para as aulas de FPCC-report.csv")
View(dados)
# usando dplyr
dados %>% View()
# Renomeia as colunas e mantém apenas as que quero
dados = dados %>%
select(curso = `De que curso você é aluno?`,
sexo = `Você é...`,
altura = `Qual a sua altura em centímetros?`,
repositorios = `Em quantos repositórios de software você lembra ter contribuído nos últimos 2 anos?`,
linguagens = `Em quantas linguagens de programação você se considera fluente?`,
projetos_de_pesquisa = `Em quantos projetos de pesquisa você lembra ter participado?`,
confianca_estatistica = `Qual seu nível de confiança hoje no uso de métodos estatísticos para analisar o resultado de um experimento?`,
gosta_de_forms = `O quanto você gosta de formulários online? (Obrigado por ter respondido este!)`,
submissao = `Submit Date (UTC)`,
fpcc2 = `Você já cursou, está cursando ou não cursou FPCC 2?`)
# Remove NAs
dados = dados %>%
filter(complete.cases(dados))
glimpse(dados)
# ====================================
# EXPLORAR, VISUALIZAR
# ====================================
# ------------------------------------
# Variáveis numéricas
# ------------------------------------
# Altura
ggplot(data = dados,
mapping = aes(x = "valor",
y = altura)) +
geom_point(alpha = 0.5, position = position_jitter(width = .1))
dados %>%
ggplot(mapping = aes(x = altura)) +
geom_histogram(bins = 10) +
geom_rug(alpha = 0.7)
dados %>%
ggplot(mapping = aes(x = altura)) +
geom_density()
#geom_freqpoly(bins = 10)
ggplot(dados, aes(x = "altura", y = altura)) +
geom_violin() +
geom_point(position = position_jitter(width = 0.1, height = 0), size = 2, alpha = 0.5)
ggplot(dados, mapping = aes(x = altura)) +
#geom_histogram(bins = 12)
# geom_freqpoly(bins = 20)
geom_density()
# geom_rug()
# boxplots
ggplot(dados, aes(x = "altura", y = altura)) +
geom_boxplot(width = .3) +
geom_point(position = position_jitter(width = 0.1, height = 0), size = 2, alpha = 0.5)
ggplot(dados, aes(x = sexo, y = altura)) +
geom_boxplot(width = .3) +
geom_point(position = position_jitter(width = 0.1, height = 0), size = 2, alpha = 0.5)
dados %>%
group_by(sexo) %>%
summarise(iqr = IQR(altura),
sd = sd(altura))
# Linguagens de programação
dados %>%
ggplot(mapping = aes(x = "Quantas", y = linguagens)) +
# geom_point()
geom_count()
dados %>%
ggplot(mapping = aes(x = linguagens)) +
geom_histogram(bins = 6)
# Compare com repos
dados %>%
#filter(repositorios < 10) %>%
ggplot(mapping = aes(x = repositorios)) +
geom_histogram(bins = 16) +
geom_vline(xintercept = mean(dados$repositorios), colour = "orange") +
geom_vline(xintercept = median(dados$repositorios), colour = "blue")
# Qual o formato esperado da distribuição para as demais variáveis?
# Validade e confiabilidade das variáveis
# Medias e medianas
dados %>%
#filter(repositorios < 10) %>%
ggplot(mapping = aes(x = repositorios, fill = curso)) +
geom_histogram(bins = 6) +
facet_grid(curso ~ .) +
geom_rug()
dados %>%
group_by(curso) %>%
summarise(linguagens.media = mean(linguagens),
repos.medio = mean(repositorios))
dados %>%
group_by(sexo) %>%
summarise(altura.media = mean(altura),
sd.altura = sd(altura))
dados %>%
ggplot(mapping = aes(x = linguagens)) +
geom_histogram(bins = 7) +
geom_rug()
# ------------------------------------
# CATEGÓRICAS
# ------------------------------------
# Curso e sexo são categóricos
ggplot(dados) +
geom_bar(mapping = aes(x = curso), stat = "count") +
coord_flip()
ggplot(dados) +
geom_bar(mapping = aes(x = sexo), stat = "count") +
coord_flip()
ggplot(dados) +
geom_bar(mapping = aes(x = curso, fill = sexo), position = "fill") + # tente position = "stack"/"dodge"/"fill"
coord_flip()
# ------------------------------------
# DUAS VARIÁVEIS
# ------------------------------------
ggplot(dados, aes (y = repositorios,
x = linguagens)) +
geom_count(alpha = 0.6)
ggplot(dados, aes (y = confianca_estatistica,
x = projetos_de_pesquisa)) +
geom_point(alpha = 0.4)
ggplot(dados, aes (y = confianca_estatistica,
x = projetos_de_pesquisa, group = projetos_de_pesquisa)) +
geom_boxplot(alpha = 0.4)
#geom_violin(alpha = 0.4)
ggplot(dados, aes (y = altura,
x = linguagens)) +
geom_point(alpha = 0.6)
ggplot(dados, aes(x = curso,
y = linguagens)) +
geom_boxplot() +
geom_point(position = position_jitter(width = .2),
alpha = .2)
ggplot(dados, aes(x = curso,
y = linguagens)) +
geom_count()
ggplot(dados, aes(x = curso, y = altura)) +
#geom_boxplot(alpha = 0.2) +
geom_violin() +
geom_point(position = position_jitter(width = 0.07), size = 4, alpha = 0.5)
CrossTable(dados$sexo, dados$curso, prop.chisq = FALSE)
|
38b5372ea37c49d69fbc59794f982f7c3cfa47f4
|
9fbaf8e2920166916c5c038ca17c6c055b9ef135
|
/tests/testthat/test_errorfunctions.R
|
b963e9537cbae7597fb29f671a7f51e4e7cc8f0e
|
[] |
no_license
|
RMHogervorst/heisertransform
|
4fcff64d0440990818dc1505a3c87010237a04ec
|
60066346a4c227728cf32875d184822c8bdc83b9
|
refs/heads/master
| 2021-01-18T21:47:17.601914
| 2016-06-01T21:05:48
| 2016-06-01T21:05:48
| 48,912,939
| 0
| 0
| null | 2016-12-06T13:18:56
| 2016-01-02T14:50:01
|
R
|
UTF-8
|
R
| false
| false
| 1,995
|
r
|
test_errorfunctions.R
|
context("general functioning of errors and warnings")
## creation of errorsdataset
n <-15
var1 <- rnorm(n, mean = .40, sd = .04)
var2<- rnorm(n, .30, 0.02)
delete<-var1+var2 >1
var1<-var1[!delete]
var2<-var2[!delete]
var3<- 1-(var1+var2)
varfactor<-as.factor(var3)
varcharacter<-as.character(var3)
vartoomuch<-var2*2 # will be more than 1.
vartoolittle<-var1*.5 # will be less than 1
varNA<-var3
varNA[which(varNA %in% sample(varNA, 3, replace = T))]<-NA
errorset<-data.frame(var1, var2, var3, varfactor, varcharacter, vartoomuch, vartoolittle, varNA)
rm(n,delete, var1, var2, var3, varfactor, varcharacter, vartoomuch,vartoolittle, varNA)
test_that("errors column means are correct", {
expect_error(Prob2Coord(errorset, "var1", "var2", "vartoomuch"),regexp = "column means are not equal")
})
test_that("check and fix num gives error with unconvertible characters", {
expect_warning(check_and_fix_num(sample(letters, 8)), regexp = "NAs")
})
test_that("verticeName error works", {
expect_error(CreateVertices(errorset,"var1", "var2", "var3", verticeName = "name"), regexp = "verticeName needs to be TRUE or FALSE")
})
test_that("rowsums larger or smaller than 1 are failing", {
expect_error(CreateVertices(errorset,"var1", "var2", "vartoomuch", verticeName = T),regexp = "column means are not equal to 1" )
expect_error(CreateVertices(errorset,"var1", "var2", "vartoolittle", verticeName = T),regexp = "column means are not equal to 1" )
})
#stop("row sums are not identical")
#test_that("")
# library(testthat)
# #expectation - test
# #creer datasets die niet voldoen en kijk of de ze de juiste error geven.
#
# ### errortests
# #tests of errors inderdaad kloppen. Dus bij niet nummeriek, niet gemiddelde optellen tot 1.
#
# #check assumption that column means are equal to 1
# if(!sum(C1,C2,C3)==1){stop("column means are not equal to 1")}
#
# testdata
# View(testdata)
# CreateVertices(F_testdata, "test1", "test2","test3",verticeName = F)
# ?test
|
f88f515cf5a0ad0005bf1957bafe09f8e7a4b1ba
|
5b7a0942ce5cbeaed035098223207b446704fb66
|
/R/lsGetSummary.R
|
52847cf0e925c53ec7afc8fd5e279ce8ebd5f06e
|
[
"MIT"
] |
permissive
|
k127/LimeRick
|
4f3bcc8c2204c5c67968d0822b558c29bb5392aa
|
a4d634981f5de5afa5b5e3bee72cf6acd284c92a
|
refs/heads/master
| 2023-04-11T21:56:54.854494
| 2020-06-19T18:36:05
| 2020-06-19T18:36:05
| 271,702,292
| 0
| 1
| null | 2020-06-12T03:45:14
| 2020-06-12T03:45:14
| null |
UTF-8
|
R
| false
| false
| 1,709
|
r
|
lsGetSummary.R
|
#' Get survey summary, regarding token usage and survey participation
#'
#' @param surveyID ID of the survey
#' @param status \emph{(optional)} To request a specific status (\code{"completed_responses"},
#' \code{"incomplete_responses"}, \code{"full_responses"}, \code{"token_count"}, \code{"token_invalid"},
#' \code{"token_sent"}, \code{"token_opted_out"}, \code{"token_completed"}, \code{"token_screenout"})
#' as string or \code{"all"} as a list
#' @param lsAPIurl \emph{(optional)} The URL of the \emph{LimeSurvey RemoteControl 2} JSON-RPC API
#' @param sessionKey \emph{(optional)} Authentication token, see \code{\link{lsGetSessionKey}}
#'
#' @return A string if \code{status} is provided and not \code{"all"},
#' otherwise a list containing all available values
#'
#' @examples \dontrun{
#' lsGetSummary("123456")
#' }
#'
#' @references \url{https://api.limesurvey.org/classes/remotecontrol_handle.html#method_get_summary}
#'
#' @export
#'
lsGetSummary = function(surveyID,
status = "all",
lsAPIurl = getOption("lsAPIurl"),
sessionKey = NULL){
stati = c("all", "completed_responses", "incomplete_responses",
"full_responses", "token_count", "token_invalid", "token_sent",
"token_opted_out", "token_completed", "token_screenout")
status = match.arg(status, stati)
if (is.null(surveyID))
stop("Need to specify surveyID.")
params = list(sSessionKey = sessionKey,
iSurveyID = surveyID,
sStatName = status)
data = lsAPI(method = "get_summary",
params = params,
lsAPIurl = lsAPIurl)
data
}
|
9978d83ef9847ccff3886cc5c4e21a6316879a35
|
a4801f5f15cfe478585286cd1986ca04bcc65eef
|
/tests/testthat/test-updateBindingConstraint.R
|
795fea7a12f2452188738929b806d42248b3e281
|
[] |
no_license
|
rte-antares-rpackage/antaresEditObject
|
acfa8ad126149fb6a38943919e55567a5af155f8
|
452b09e9b98d4425d6ee2474b9bbd06548e846d2
|
refs/heads/master
| 2023-08-10T21:01:21.414683
| 2023-07-13T13:06:02
| 2023-07-13T13:06:02
| 96,431,226
| 10
| 16
| null | 2023-09-08T09:31:25
| 2017-07-06T13:07:19
|
R
|
UTF-8
|
R
| false
| false
| 1,730
|
r
|
test-updateBindingConstraint.R
|
context("Function editBindingConstraint")
sapply(studies, function(study) {
setup_study(study, sourcedir)
opts <- antaresRead::setSimulationPath(studyPath, "input")
#Create a new binding constraint
createBindingConstraint(
name = "myconstraint",
values = matrix(data = rep(0, 8760 * 3), ncol = 3),
enabled = FALSE,
timeStep = "hourly",
operator = "both"
)
###Write params
bc <- antaresRead::readBindingConstraints()
bc <- bc[["myconstraint"]]
editBindingConstraint("myconstraint", enabled = TRUE)
bc2 <- antaresRead::readBindingConstraints()
bc2 <- bc2[["myconstraint"]]
expect_true(bc2$enabled)
bc2$enabled <- FALSE
bc$values <- data.frame(bc$values)
bc2$values <- data.frame(bc2$values)
expect_true(identical(bc, bc2))
editBindingConstraint("myconstraint", coefficients = c("a%b" = 10))
##Write coef
bc <- antaresRead::readBindingConstraints()
expect_true(bc$myconstraint$coefs == c("a%b" = 10))
editBindingConstraint("myconstraint", coefficients = c("a%b" = 100))
bc <- antaresRead::readBindingConstraints()
expect_true(bc$myconstraint$coefs == c("a%b" = 100))
editBindingConstraint("myconstraint", coefficients = c("b%c" = 10))
bc <- antaresRead::readBindingConstraints()
expect_true(identical(bc$myconstraint$coefs,c("a%b" = 100, "b%c" = 10)))
##Write values
expect_true(sum(bc$myconstraint$values) == 0)
bc$myconstraint$timeStep
editBindingConstraint("myconstraint", values = matrix(data = rep(1, 8760 * 3), ncol = 3))
bc <- antaresRead::readBindingConstraints()
expect_true(sum(bc$myconstraint$values) > 0 )
# remove temporary study
unlink(x = file.path(pathstd, "test_case"), recursive = TRUE)
})
|
a88c1a395b14224400f76478980465db26239831
|
b12b4d4c22f4aae84bcd2621654aa010ca8f26f5
|
/scripts/figures/Bnapus_figure2_venn.R
|
89f4f4b7fc06db3a910cfd70570c3ac4c2ec381c
|
[] |
no_license
|
gavinmdouglas/canola_pseudomonas_RNAseq
|
20fa3e0ad33e3bc859225ba57cac40b1777723d3
|
d92849ab758c5490144fa78e4626ce7d0d55f66d
|
refs/heads/master
| 2021-03-30T15:51:16.800416
| 2021-02-14T22:26:32
| 2021-02-14T22:26:32
| 99,141,112
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,944
|
r
|
Bnapus_figure2_venn.R
|
# Figure of main venn diagrams
rm(list=ls(all.names=TRUE))
setwd("/home/gavin/projects/pseudomonas_RNAseq/canola_pseudomonas_RNAseq/")
library(cowplot)
library(ggVennDiagram)
# Venn diagrams for each tissue of overall DE genes (lfc > 2) by day. Four panels in total for up/down in both shoots and roots
# Panel A - root up Venn diagram
root_up_sig <- list()
root_up_sig[["Day 1"]] <- read.table("Bnapus_sig_gene_sets/day1_up/Bnapus_day1_genes_Root_up_padj_0.1_l2fc_2.txt", stringsAsFactors = FALSE)$V1
root_up_sig[["Day 3"]] <- read.table("Bnapus_sig_gene_sets/day3_up/Bnapus_day3_genes_Root_up_padj_0.1_l2fc_2.txt", stringsAsFactors = FALSE)$V1
root_up_sig[["Day 5"]] <- read.table("Bnapus_sig_gene_sets/day5_up/Bnapus_day5_genes_Root_up_padj_0.1_l2fc_2.txt", stringsAsFactors = FALSE)$V1
root_up_sig_venn <- ggVennDiagram(x = root_up_sig) +
scale_fill_gradient(low="light grey", high = "red", limits = c(0, 2000)) +
labs(fill="Count") +
ggtitle("Root up-regulated") +
theme(plot.title = element_text(hjust = 0.5))
# Panel B - root down Venn diagram
root_down_sig <- list()
root_down_sig[["Day 1"]] <- read.table("Bnapus_sig_gene_sets/day1_down/Bnapus_day1_genes_Root_down_padj_0.1_l2fc_-2.txt", stringsAsFactors = FALSE)$V1
root_down_sig[["Day 3"]] <- read.table("Bnapus_sig_gene_sets/day3_down/Bnapus_day3_genes_Root_down_padj_0.1_l2fc_-2.txt", stringsAsFactors = FALSE)$V1
root_down_sig[["Day 5"]] <- read.table("Bnapus_sig_gene_sets/day5_down/Bnapus_day5_genes_Root_down_padj_0.1_l2fc_-2.txt", stringsAsFactors = FALSE)$V1
root_down_sig_venn <- ggVennDiagram(x = root_down_sig) +
scale_fill_gradient(low="light grey", high = "red", limits = c(0, 2000)) +
labs(fill="Count") +
ggtitle("Root down-regulated") +
theme(plot.title = element_text(hjust = 0.5))
# Panel C - shoot up Venn diagram
shoot_up_sig <- list()
shoot_up_sig[["Day 1"]] <- read.table("Bnapus_sig_gene_sets/day1_up/Bnapus_day1_genes_Shoot_up_padj_0.1_l2fc_2.txt", stringsAsFactors = FALSE)$V1
shoot_up_sig[["Day 3"]] <- read.table("Bnapus_sig_gene_sets/day3_up/Bnapus_day3_genes_Shoot_up_padj_0.1_l2fc_2.txt", stringsAsFactors = FALSE)$V1
shoot_up_sig[["Day 5"]] <- read.table("Bnapus_sig_gene_sets/day5_up/Bnapus_day5_genes_Shoot_up_padj_0.1_l2fc_2.txt", stringsAsFactors = FALSE)$V1
shoot_up_sig_venn <- ggVennDiagram(x = shoot_up_sig) +
scale_fill_gradient(low="light grey", high = "red", limits = c(0, 2000)) +
labs(fill="Count") +
ggtitle("Shoot up-regulated") +
theme(plot.title = element_text(hjust = 0.5))
# Panel D - shoot down Venn diagram
shoot_down_sig <- list()
shoot_down_sig[["Day 1"]] <- read.table("Bnapus_sig_gene_sets/day1_down/Bnapus_day1_genes_Shoot_down_padj_0.1_l2fc_-2.txt", stringsAsFactors = FALSE)$V1
shoot_down_sig[["Day 3"]] <- read.table("Bnapus_sig_gene_sets/day3_down/Bnapus_day3_genes_Shoot_down_padj_0.1_l2fc_-2.txt", stringsAsFactors = FALSE)$V1
shoot_down_sig[["Day 5"]] <- read.table("Bnapus_sig_gene_sets/day5_down/Bnapus_day5_genes_Shoot_down_padj_0.1_l2fc_-2.txt", stringsAsFactors = FALSE)$V1
shoot_down_sig_venn <- ggVennDiagram(x = shoot_down_sig) +
scale_fill_gradient(low="light grey", high = "red", limits = c(0, 2000)) +
labs(fill="Count") +
ggtitle("Shoot down-regulated") +
theme(plot.title = element_text(hjust = 0.5))
# Plot figure
pdf(file = "plots/main/Figure2_venn.pdf", width=7.3, height=7.3, onefile=FALSE)
plot_grid(root_up_sig_venn, root_down_sig_venn, shoot_up_sig_venn, shoot_down_sig_venn,
labels=c('A', 'B', 'C', 'D'), nrow=2, ncol=2)
dev.off()
tiff(file = "plots/main/Figure2_venn.tiff", width=7.3, height=7.3,
compression = "lzw", res=300, units="in")
plot_grid(root_up_sig_venn, root_down_sig_venn, shoot_up_sig_venn, shoot_down_sig_venn,
labels=c('A', 'B', 'C', 'D'), nrow=2, ncol=2)
dev.off()
|
dd6afde292f47760752d92d0810957cb74ef290f
|
fc7841b1e7c4cc7b3839fb57ccd9802c6f4d3d8f
|
/test/fixtures/test.number.R
|
b81ea48a1b35418e8658527d044456668ac90f54
|
[
"MIT"
] |
permissive
|
distributions-io/hypergeometric-pmf
|
d74810fc581a8d3a67a9758bf4e8596704f04114
|
bf6c5a64a8118c366a152cf88fe24c25c7937544
|
refs/heads/master
| 2021-01-22T07:35:17.913997
| 2015-10-24T01:44:10
| 2015-10-24T01:44:10
| 39,271,045
| 3
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 296
|
r
|
test.number.R
|
options( digits = 16 )
library( jsonlite )
m = 5
n = 5
k = 3
x = c( -1, 0.5, 0, 1, 2, 3, 4, 5)
y = dhyper( x, m,n,k )
cat( y, sep = ",\n" )
data = list(
m = m,
n = n,
k = k,
data = x,
expected = y
)
write( toJSON( data, digits = 16, auto_unbox = TRUE ), "./test/fixtures/number.json" )
|
a002482eb485f9cf4f46c27f93bfabb4ccbea983
|
2448d4800d4336b53489bcce3c17a32e442a7716
|
/tests/test-that.R
|
764f4a7e4c73cdcb050d48f19c40b983b6c6ee37
|
[] |
no_license
|
vsbuffalo/devtools
|
17d17fd1d2fb620fef8d9883dffed389f80e39fb
|
782e6b071d058eea53aae596a3c120d61df2f0b4
|
refs/heads/master
| 2020-12-24T10:41:24.637105
| 2016-02-18T14:03:05
| 2016-02-18T14:03:05
| 52,121,375
| 2
| 0
| null | 2016-02-19T22:42:43
| 2016-02-19T22:42:43
| null |
UTF-8
|
R
| false
| false
| 41
|
r
|
test-that.R
|
library(testthat)
test_check("devtools")
|
42ff03322a699e4a895403a107cf10db11a1c00e
|
10898984bdd86ccff61363d2aff9c1fc5fbb1545
|
/man/computeLTA.Rd
|
343fe54800bc987e078fce759182ecc19ecc9eb7
|
[] |
no_license
|
victoriaknutson/SpatioTemporal
|
69e2b251f2b861f88d3d06c91695f61fffdc4736
|
9980dc005018fd18abeea5eec6228ef4522791f5
|
refs/heads/master
| 2023-07-10T06:44:58.350806
| 2021-04-14T01:49:02
| 2021-04-14T01:49:02
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
R
| false
| false
| 2,462
|
rd
|
computeLTA.Rd
|
\name{computeLTA}
\alias{computeLTA}
\title{Computes the Long Term Average for Each Sites.}
\usage{
computeLTA(object, transform = function(x) {
return(x) })
}
\arguments{
\item{object}{A \code{predCVSTmodel} object, the result
of \code{\link{predictCV.STmodel}}.}
\item{transform}{Transform observations (\emph{without}
bias correction) and predictions \emph{before} computing
averages; e.g. \code{transform=exp} gives the long term
averages as \code{mean( exp(obs) )} and \code{mean(
exp(pred) )}.}
}
\value{
Returns a (number of locations) - by - 4 matrix with the
observed and predicted value (using the three different
model parts) for each location.
}
\description{
Computes the long term average of observations and
cross-validated predictions for each of the sites in
\code{object}. The long term averages are computed using
\emph{only} timepoints that have observations, this
applies to both the observed and predicted. Also the
function allows for a transformation: if requested the
transformation is applied \emph{before} the averaging.
}
\examples{
##load data
data(pred.cv.mesa)
##compute long term averages of predictions and observations
pred.lta <- computeLTA(pred.cv.mesa)
##we can now compare observed and predicted averages at each site
plot(pred.lta[,"obs"], pred.lta[,"EX.mu"], pch=1,
xlim=range(pred.lta), ylim=range(pred.lta),
xlab="obs", ylab="predictions")
##for the different model components
points(pred.lta[,"obs"], pred.lta[,"EX.mu.beta"], pch=3, col=2)
points(pred.lta[,"obs"], pred.lta[,"EX"], pch=4, col=3)
abline(0,1)
##we could also try computaitons on the original scale
pred.lta <- computeLTA(pred.cv.mesa, exp)
##compare observed and predicted averages
plot(pred.lta[,"obs"], pred.lta[,"EX.mu"], pch=1,
xlim=range(pred.lta), ylim=range(pred.lta),
xlab="obs", ylab="predictions")
points(pred.lta[,"obs"], pred.lta[,"EX.mu.beta"], pch=3, col=2)
points(pred.lta[,"obs"], pred.lta[,"EX"], pch=4, col=3)
abline(0,1)
}
\author{
Johan Lindström
}
\seealso{
Other cross-validation functions: \code{\link{createCV}},
\code{\link{dropObservations}}, \code{\link{estimateCV}},
\code{\link{estimateCV.STmodel}},
\code{\link{predictCV}}, \code{\link{predictCV.STmodel}},
\code{\link{predictNaive}}
Other predCVSTmodel functions: \code{\link{estimateCV}},
\code{\link{estimateCV.STmodel}},
\code{\link{predictCV}}, \code{\link{predictCV.STmodel}}
}
|
1f19f306e86ae083a0ed7427b9f17c28e5701a6c
|
dd1102ed8f681e5dfb675075b870ee948f017ccc
|
/paths.R
|
143eff092ac9582e1562e38bbed650742b260930
|
[] |
no_license
|
garridoo/ljsphere
|
a726ec88922bd967bcee1c44ff13f73de8e146dc
|
647a1bc7d6a8ae15f50a4f751c94baae89727771
|
refs/heads/master
| 2021-06-12T19:59:49.903325
| 2021-05-20T11:25:13
| 2021-05-20T11:25:13
| 254,386,539
| 3
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 284
|
r
|
paths.R
|
# path to the project folder
project_folder <- "/biodata/dep_psl/grp_rgo/ljsphere/"
# paths to sub-directories
results.dir <- paste(project_folder, "/results/", sep="")
data.dir <- paste(project_folder, "/data/", sep="")
figures.dir <- paste(project_folder, "/figures/", sep="")
|
a00d99e9c6cd76048e76e9e10eadd683dc81f572
|
5390b30d1f233b024479c7e5199a39ccab75db24
|
/man/recencySendReceiver.Rd
|
698f1c0d49fb5077b84504e8b053b6944d5528bc
|
[] |
no_license
|
TilburgNetworkGroup/remstats
|
65d5c6046612bc6b954a61f8e78f8471887400c9
|
19799f91a9906312e89ba7fe58bef33e49a6b6f1
|
refs/heads/master
| 2023-07-19T18:21:13.674451
| 2023-07-13T14:11:23
| 2023-07-13T14:11:23
| 248,442,585
| 4
| 1
| null | 2023-09-05T08:36:29
| 2020-03-19T07:54:52
|
R
|
UTF-8
|
R
| false
| true
| 1,472
|
rd
|
recencySendReceiver.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/effects.R
\name{recencySendReceiver}
\alias{recencySendReceiver}
\title{recencySendReceiver}
\usage{
recencySendReceiver(consider_type = FALSE)
}
\arguments{
\item{consider_type}{logical, indicates whether to compute the recency
separately for each event type (TRUE) or regardless of event types (FALSE,
default).}
}
\description{
Specifies the statistic for a recency send of receiver effect in the
\code{effects} argument of \code{\link{tomstats}} or the
\code{receiver_effects} argument of \code{\link{aomstats}}.
}
\details{
The recencySendReceiver effect refers to a recency statistic similar to what
is described in Vu et al. (2017) and Mulder and Leenders (2019). For each
timepoint t, for directed dyad (i,j) the statistic is equal to 1/(the time
that has past since receiver j was last active as sender + 1). Note that the
'recencySendReceiver' effect is only defined for directed events.
}
\examples{
effects <- ~ recencySendReceiver()
reh_tie <- remify::remify(history, model = "tie")
remstats(tie_effects = effects, reh = reh_tie)
reh_actor <- remify::remify(history, model = "actor")
remstats(receiver_effects = effects, reh = reh_actor)
}
\seealso{
\code{\link{rrankSend}}, \code{\link{rrankReceive}},
\code{\link{recencySendSender}}, \code{\link{recencyReceiveSender}},
\code{\link{recencyReceiveReceiver}} and \code{\link{recencyContinue}} for
other type of recency effects
}
|
57793493bc861a339019dc5e3429032804fac6c0
|
a83fe101098fad2b7da530ce7c867df7ac7226dd
|
/Video.R
|
70f969229bde5e2d04011cbc1e711ec62a2cb380
|
[] |
no_license
|
orzkng2015/R
|
3fb0a6cf98d0d38a5fcf6bb5f5327bc713dc6c62
|
aba78fcf739914c4aba5764bcf069df1f2934da1
|
refs/heads/master
| 2020-12-24T20:51:40.722461
| 2016-05-01T22:50:05
| 2016-05-01T22:50:05
| 56,644,079
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,246
|
r
|
Video.R
|
####progress
CourseView <- function(courseID, playVideo){
# Used to filter the course_id.
index <- list()
for(i in 1:lengths(playVideo)[1]){
# If the playVideo$course_id equals to courseID, the index set to true.
index[length(index)+1] <- ifelse(playVideo$course_id[i] == courseID, T, F)
}
# Get the course data by index.
courseData <- playVideo[unlist(index),]
return(courseData)
}
UserViewsOverNum <- function(CourseData, percent, totalVideosNum, up){
# Compute the numbers of videos a user watch is greater than or equals to a percent of total videos in a course.
# Get the numbers of videos a user watch by freqency.
videos <- as.data.frame(table(CourseData$user_id), stringsAsFactors = F)
colnames(videos)[1] <- 'user_id'
# Left join the country and videos.
videos <- dplyr::left_join(videos, up, by = 'user_id')
index <- list()
for(i in 1:lengths(videos)[1]){
# If the numbers of videos a user watch is greater than or equals to a percent of total videos.
# Index will set to true.
index[length(index)+1] <- ifelse(videos$Freq[i] >= percent*totalVideosNum, T, F)
}
# Column bind videos and index.
videos <- cbind(videos, as.data.frame(unlist(index)))
colnames(videos)[4] <- 'WatchOver'
# Compute the country and index.
watchOver <- as.data.frame(table(videos$country, videos$WatchOver), stringsAsFactors = F)
colnames(watchOver)[1] <- 'country'
colnames(watchOver)[2] <- 'WatchOver'
return(watchOver)
}
VideoNumbers <- function(CourseData, up){
# Compute a number of video viewers.(e.g. 2 user watch 1 video => 2)
users <- as.data.frame(CourseData$user_id, stringsAsFactors = F)
colnames(users)[1] <- 'user_id'
# Left join country and user_id.
users <- dplyr::left_join(users, up, by = 'user_id')
# Get the country frequency.
users <- as.data.frame(table(users$country), stringsAsFactors = F)
colnames(users)[1] <- 'country'
return(users)
}
VideoViews <- function(CourseData, up){
# Left join country and course data.
views <- dplyr::left_join(CourseData, up, by = 'user_id')
# Compute the country frequency. It means views in a course.
views <- as.data.frame(table(views$country))
colnames(views)[1] <- 'country'
return(views)
}
|
3d5ef46471ead9d8c7da630ccd34f3cd5b076491
|
1cad4dcc0c0f921644be13ebcccf9d8c45c5dc83
|
/run_analysis.R
|
f4da7a182bf4be75130615a4d6820b1bab8077b7
|
[] |
no_license
|
renato145/GettingandCleaningDataCourseProject
|
31b2e54b5e235cef40f6b7280b0a227a0628c53b
|
6aaed5d74be852868f6ae93777b8d95a3cbb4bf6
|
refs/heads/master
| 2021-01-24T14:27:58.898901
| 2015-06-15T21:55:05
| 2015-06-15T21:55:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,650
|
r
|
run_analysis.R
|
library(plyr)
library(dplyr)
#1 - Merges the training and the test sets to create one data set.
mergedSet <- rbind(read.table("UCI HAR Dataset/train/X_train.txt"),
read.table("UCI HAR Dataset/test/X_test.txt"))
#2 - Extracts only the measurements on the mean and standard
# deviation for each measurement.
features <- read.table("UCI HAR Dataset/features.txt", stringsAsFactors = FALSE)
features <- features$V2
validFeatures <- grepl(".*(mean|std).*", features)
mergedSet <- mergedSet[, validFeatures]
#3 - Uses descriptive activity names to name the activities in the data set.
activityLabels <- read.table("UCI HAR Dataset/activity_labels.txt")
activities <- rbind(read.table("UCI HAR Dataset/train/y_train.txt"),
read.table("UCI HAR Dataset/test/y_test.txt"))
activities <- join(activities, activityLabels)
mergedSet <- cbind(activities$V2, mergedSet)
#4 - Appropriately labels the data set with descriptive variable names.
names(mergedSet) <- c("activity", features[validFeatures])
names(mergedSet) <- gsub("\\(|)|-", "", names(mergedSet))
#5 - From the data set in step 4, creates a second, independent tidy
# data set with the average of each variable for each activity
# and each subject.
subjects <- rbind(read.table("UCI HAR Dataset/train/subject_train.txt"),
read.table("UCI HAR Dataset/test/subject_test.txt"))
mergedSet2 <- cbind(subjects, mergedSet)
mergedSet2 <- rename(mergedSet2, subject=V1)
mergedSet2 <- mergedSet2 %>% group_by(activity, subject)
%>% summarise_each(funs(mean))
write.table(mergedSet2, file = "dataSet.txt", row.names = FALSE)
|
927e3e1f893c928d91bb6196ebdcb51b7a977a6d
|
c750c1991c8d0ed18b174dc72f3014fd35e5bd8c
|
/pkgs/oce/man/ctdRaw.Rd
|
f4a6cd60e143f87a67a8fed374b1ffab5a9f6018
|
[] |
no_license
|
vaguiar/EDAV_Project_2017
|
4b190e66fe7a6b4078cfe1b875bccd9b5a594b25
|
288ffaeec1cfdd873fe7439c0fa0c46a90a16a4f
|
refs/heads/base
| 2021-01-23T02:39:36.272851
| 2017-05-01T23:21:03
| 2017-05-01T23:21:03
| 86,010,131
| 1
| 0
| null | 2017-05-01T23:43:04
| 2017-03-24T00:21:20
|
HTML
|
UTF-8
|
R
| false
| true
| 2,398
|
rd
|
ctdRaw.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ctd.R
\docType{data}
\name{ctdRaw}
\alias{ctdRaw}
\title{Seawater CTD Profile, Without Trimming of Extraneous Data}
\usage{
data(ctdRaw)
}
\description{
This is sample CTD profile provided for testing. It includes not just the
(useful) portion of the dataset during which the instrument was being lowered,
but also data from the upcast and from time spent near the surface. Spikes are
also clearly evident in the pressure record. With such real-world wrinkles,
this dataset provides a good example of data that need trimming with
\code{\link{ctdTrim}}.
}
\details{
This station was sampled by students enrolled in the Dan Kelley's
Physical Oceanography class at Dalhousie University.
The data were acquired near the centre of the Bedford Basin of the
Halifax Harbour, during an October 2003 field trip of Dalhousie University's
Oceanography 4120/5120 class. The original \code{.cnv} data file had
temperature in the IPTS-68 scale, but this was converted to the more modern
scale using \code{\link{T90fromT68}}.
}
\seealso{
A similar dataset (trimmed to the downcast) is available as
\code{data(\link{ctd})}.
Other things related to \code{ctd} data: \code{\link{[[,ctd-method}},
\code{\link{[[<-,ctd-method}}, \code{\link{as.ctd}},
\code{\link{cnvName2oceName}}, \code{\link{ctd-class}},
\code{\link{ctdDecimate}}, \code{\link{ctdFindProfiles}},
\code{\link{ctdTrim}}, \code{\link{ctd}},
\code{\link{handleFlags,ctd-method}},
\code{\link{plot,ctd-method}}, \code{\link{plotProfile}},
\code{\link{plotScan}}, \code{\link{plotTS}},
\code{\link{read.ctd.itp}}, \code{\link{read.ctd.odf}},
\code{\link{read.ctd.sbe}},
\code{\link{read.ctd.woce.other}},
\code{\link{read.ctd.woce}}, \code{\link{read.ctd}},
\code{\link{subset,ctd-method}},
\code{\link{summary,ctd-method}},
\code{\link{woceNames2oceNames}}, \code{\link{write.ctd}}
Other datasets provided with \code{oce}: \code{\link{adp}},
\code{\link{adv}}, \code{\link{argo}}, \code{\link{cm}},
\code{\link{coastlineWorld}}, \code{\link{colors}},
\code{\link{ctd}}, \code{\link{echosounder}},
\code{\link{landsat}}, \code{\link{lisst}},
\code{\link{lobo}}, \code{\link{met}}, \code{\link{rsk}},
\code{\link{sealevelTuktoyaktuk}},
\code{\link{sealevel}}, \code{\link{section}},
\code{\link{topoWorld}}, \code{\link{wind}}
}
|
cf0ceddf03387c38279bf96e510f18df85702aac
|
9d221239bfd8e36f09fb151c492f2cd1c21348e7
|
/R/pvaluer.R
|
c5df60f088c1173e122bd53dd4e40d45a074a6c9
|
[] |
no_license
|
wmhall/cul_hsp
|
d877e031a792eb4f8504fd45869277de73037287
|
f5af9abc690d4a6fe360bde85180760989475d12
|
refs/heads/master
| 2021-01-19T21:42:02.945696
| 2017-04-19T02:50:41
| 2017-04-19T02:50:41
| 88,691,012
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 764
|
r
|
pvaluer.R
|
#functions for working with p values.
fixed_digits <- function(xs, n = 2) {
formatC(xs, digits = n, format = "f")
}
fixed_zero <- . %>% fixed_digits(n=0)
remove_leading_zero <- function(xs) {
# Problem if any value is greater than 1.0
digit_matters <- xs %>% as.numeric %>%
abs %>% magrittr::is_greater_than(1)
if (any(digit_matters, na.rm =T)) {
warning("Non-zero leading digit")
}
stringr::str_replace(xs, "^(-?)0", "\\1")
}
format_pval <- function(ps) {
v_tiny <- "< .001"
#tiny <- "<.01"
#v_small <- "<.05"
ps_chr <- ps %>% fixed_digits(3) %>%
remove_leading_zero
#ps_chr[ps < 0.05] <- v_small
#ps_chr[ps < 0.01] <- tiny
ps_chr[ps < 0.001] <- v_tiny
ps_chr
}
z2p <- function(z) {return(2*pnorm(-abs(z)))}
|
d66b8819407b58ddc99111c41e528ce3a9071067
|
36844710bcf289e8c056550767f4fb508b6395ff
|
/src/Exercise5_1.R
|
81bc5f7f3a9844935da77334c4626dbf6d78f880
|
[] |
no_license
|
3100/do_bayesian
|
500ac3da587f82d4fd10342320bb3078db92702f
|
1114f5bd9c0b1965bbe54a3b1170e0896d7c5657
|
refs/heads/master
| 2021-01-19T05:45:08.728766
| 2017-08-19T23:00:11
| 2017-08-19T23:00:11
| 100,582,198
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 961
|
r
|
Exercise5_1.R
|
## 陽性だった後の再検査で陰性になったとき、その人が病気である確率を求める。
# p(D=陽|θ=病) = 0.99 # ある人が病気の時に、陽性になる確率
pPositiveWhenTrue = 0.99
# 病気でないのに陽性になる確率0.05
# p(D=陽|θ=無)
pPositiveWhenFalse = 0.05
# p(θ=病) = pPositive = 0.001
pTrue <- 0.001
# p(D=陽) = Σp(D=陽|θ*)p(θ*) # すべてのθ値での和 : 周辺確率
pPositive <- pPositiveWhenTrue*pTrue + pPositiveWhenFalse*(1-pTrue)
# 1回目の検査で陽性のときの事後確率 P(θ=病|D=陽)
# すなわち、2回めの検査での事前確率
p1 <- pPositiveWhenTrue * pTrue / pPositive
print(p1) # for debug
# 病気のときに陰性になる確率
pNegativeWhenTrue = 0.01
# 病気じゃない時に陰性になる確率
pNegativeWhenFalse = 0.95
# p(D=陰)
pNegative <- pNegativeWhenTrue*p1 + pNegativeWhenFalse * (1-p1)
p2 <- pNegativeWhenTrue * p1 / pNegative
print(p2)
|
5525faa064c75659f6d955da554d7952170444b2
|
1828faa2103627f8e8d50af213efed04d10a67d4
|
/cachematrix.R
|
fa169a21727243d7b84dd8dbb8bf4a8aa1ed974a
|
[] |
no_license
|
mcs2712/ProgrammingAssignment2
|
871dfc10075bdd6217544d98a975955f92b6e4a9
|
b7f8f35f31fbe15ca501d0967db3566763e4a50c
|
refs/heads/master
| 2020-12-14T09:57:43.290307
| 2015-05-24T09:15:52
| 2015-05-24T09:15:52
| 36,126,503
| 0
| 0
| null | 2015-05-23T14:20:27
| 2015-05-23T14:20:26
| null |
UTF-8
|
R
| false
| false
| 2,113
|
r
|
cachematrix.R
|
## Put comments here that give an overall description of what your
## functions do
# -- DESCRIPTION --
# makeCacheMatrix
# - creates an object with four function elements: set, get, setinv and getinv
# - you can give the function a matrix argument
# if no argument given, it takes an empty matrix as default
# cacheSolve
# - computes the inverse of an object created with makeCacheMatrix
# - prints "getting cached data" if the inverse was already computed before
# -- EXAMPLE WALKTHROUGH --
# 1) create object 'matr' containing a 2x2 matrix with 1:4 elements ordered column-first
# matr <- makeCacheMatrix(matrix(1:4, nrow=2, ncol=2))
# 2) check if 'matr' indeed contains a 2x2 matrix
# matr$get()
# 3) compute inverse of 'matr' with cacheSolve; prints the inverse
# cacheSolve(matr)
# 4) execute cacheSolve again on 'matr' to see if it prints "getting cached data"
# cacheSolve(matr)
## Write a short comment describing this function
# returns list with four functions:
# - set() sets the matrix 'x'
# - get() returns matrix 'x'
# - setinv() sets the inverse 'i' of matrix 'x'
# NB can be set efficiently with cachSolve()
# - getinv() returns the inverse 'i' of matrix 'x'
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinv <- function(inv) i <<- inv
getinv <- function() i
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## Write a short comment describing this function
# returns a matrix that is the inverse of 'x'
# 53) attempts to get inverse 'i' from 'x'
# 54) checks if 'i' already exists (is not null);
# if so, then 55-56) print "getting cached data", return 'í' and exit function
# if not, then
# 58) get the 'data' (matrix) from 'x'
# 59) compute inverse 'i' of 'data'
# 60) set inverse of 'x' to inverse 'i'
# 61) print inverse 'i' and exit function
cacheSolve <- function(x, ...) {
i <- x$getinv()
if(!is.null(i)) {
message("getting cached data")
return(i)
}
data <- x$get()
i <- solve(data)
x$setinv(i)
i
}
|
375d2184f165b3c56ce52ea81a107268681c8ed5
|
b749e2826f9c85a87dc3b1270c45ddbf83c10809
|
/SimulationLoop.R
|
9b105fa49d377a15a99822acd05396736dd76a58
|
[] |
no_license
|
moedancer/SequentialDesigns
|
4e7a53d2356549b3804c6013932fe072548757ac
|
59f0294242a73b613e93810256918f629fb615f8
|
refs/heads/master
| 2020-08-23T07:35:28.859385
| 2019-10-21T13:55:58
| 2019-10-21T13:55:58
| 216,572,182
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 13,125
|
r
|
SimulationLoop.R
|
#Execute simulations for all scnearios to be considered in the mauscript
#"setup_[...].R" scripts will be sourced in the loop according to the currently investigated distribution
require(Hmisc) #function: rcorr
#setwd() according to folder containing scripts
set.seed(1)
#####################################################################################################################
#set up loop for simulation with different parameters
copulas.vector <- c("Clayton", "Gumbel", "Frank")
intensities <- c("low", "medium", "high")
num.copulas <- length(copulas.vector)
copula.parameters <- matrix(c(1, 5, 15, 1.5, 4, 8, 5, 20, 50), ncol = num.copulas)
colnames(copula.parameters) <- copulas.vector
rownames(copula.parameters) <- intensities
fixed.median <- 2
fixed.shape <- 1
alternative.median <- 1
alternative.shapes <- c(1/2, 1, 2)
sample.sizes <- c(50, 100, 250, 500)
emp.alpha.level <- matrix(rep(0, num.copulas * length(intensities) * length(alternative.median) * length(alternative.shapes) * length(sample.sizes) * 13), ncol=13)
colnames(emp.alpha.level) <- c("Sample size", "m1", "k1", "m2", "k2", "Copula", "Copula parameter", "alpha.maxnorm", "alpha.L2", "alpha.maxnorm.weight1", "alpha.L2.weight1", "alpha.maxnorm.weight2", "alpha.L2.weight2")
#Calculate rejection levels and rejection bounds for standard and weighted cases
alpha <- 0.05
weight1 <- 1/2
weight2 <- 1/4
u.maxnorm <- qnorm( 1 - ( 1 - (1-alpha)^(1/4) ) / 2)
u.L2 <- qchisq( 1 - ( 1 - (1-alpha)^(1/2) ), df = 2)
alpha_star.maxnorm.weight1 <- ((1+weight1)/(2*weight1)) - sqrt(((1+weight1)/(2*weight1))^2 - (1/weight1) * (1 - sqrt(1-alpha)))
u1.maxnorm.weight1 <- qnorm(1 - weight1*alpha_star.maxnorm.weight1/2)
u2.maxnorm.weight1 <- qnorm(1 - alpha_star.maxnorm.weight1/2)
alpha_star.L2.weight1 <- ((1+weight1)/(2*weight1)) - sqrt(((1+weight1)/(2*weight1))^2 - (1/weight1) * alpha)
u1.L2.weight1 <- qchisq(1 - weight1*alpha_star.L2.weight1, df = 2)
u2.L2.weight1 <- qchisq(1 - alpha_star.L2.weight1, df = 2)
alpha_star.maxnorm.weight2 <- ((1+weight2)/(2*weight2)) - sqrt(((1+weight2)/(2*weight2))^2 - (1/weight2) * (1 - sqrt(1-alpha)))
u1.maxnorm.weight2 <- qnorm(1 - weight2*alpha_star.maxnorm.weight2/2)
u2.maxnorm.weight2 <- qnorm(1 - alpha_star.maxnorm.weight2/2)
alpha_star.L2.weight2 <- ((1+weight2)/(2*weight2)) - sqrt(((1+weight2)/(2*weight2))^2 - (1/weight2) * alpha)
u1.L2.weight2 <- qchisq(1 - weight2*alpha_star.L2.weight2, df = 2)
u2.L2.weight2 <- qchisq(1 - alpha_star.L2.weight2, df = 2)
current.row.to.fill <- 0
for(sample.size.temp in sample.sizes){
for(med2.temp in alternative.median){
for(kappa2.temp in alternative.shapes){
for(copula.temp in copulas.vector){
for(intensity.temp in intensities){
current.row.to.fill <- current.row.to.fill + 1
print(current.row.to.fill)
#set up distribution for simulation
Sim.Copula <- copula.temp
#Choose copula parameter for chosen copula
a <- copula.parameters[intensity.temp, copula.temp]
#Choose marginal distributions! Choose among "weibull", "gamma" and "lnorm"
marginal1 <- "weibull"
marginal2 <- "weibull"
#Choose parameters for marginal distributions: a1 and b1 refer to 1st marginal, a2 and b2 refer to 2nd marginal
#In case of Weibull or Gamma-distribution: a is shape and b is scale parameter
#In case of log-normal distribution: a is meanlog and b is sdlog
m1 <- fixed.median
a1 <- fixed.shape
b1 <- m1 * log(2)^(-1/a1)
m2 <- med2.temp
a2 <- kappa2.temp
b2 <- m2 * log(2)^(-1/a2)
#####################################################################################################################
#do the setup according to the chosen distribution
source("setup_marginals.R")
source(paste("setup_", Sim.Copula, ".r", sep = ""))
#####################################################################################################################
t1 <- 2.5
t2 <- 5
accrual.period <- 3
followup <- 2
simulations <- 10000
resultscol <- 12 #number of results needed for each simulation step (2 events; 2 timesteps; martingale and variation; 4 columns for final statistics)
results <- data.frame(matrix(rep(0,simulations * resultscol),ncol = resultscol))
colnames(results) <- c("Event1.t1", "Var.Event1.t1", "Event2.t1", "Var.Event2.t1", "Event1.t2", "Var.Event1.t2", "Event2.t2", "Var.Event2.t2", "Z1.t1", "Z2.t1", "Z1.t2", "Z2.t2")
n <- sample.size.temp
for(i in 1:simulations){
tryCatch({
arrival.times <- runif(n, min = 0, max = accrual.period)
censoring.times <- rep(followup, n)
event.times <- generate.event.times()
trial.data <- data.frame(arrival.times, event.times, event.times + arrival.times, censoring.times + arrival.times)
colnames(trial.data) <- c("Arrival", "Event1", "Event2", "Event1Calendar", "Event2Calendar", "Censoring")
#Compute bounds for integrals in calculation of compensators
trial.data$changestate.t1 <- pmin(trial.data$Event1, trial.data$Event2, followup, pmax(0,(t1 - trial.data$Arrival)))
trial.data$upperbound.comp1.t1 <- pmin(trial.data$Event1, followup, pmax(0,(t1 - trial.data$Arrival)))
trial.data$upperbound.comp2.t1 <- pmin(trial.data$Event2, followup, pmax(0,(t1 - trial.data$Arrival)))
trial.data$changestate.t2 <- pmin(trial.data$Event1, trial.data$Event2, followup, pmax(0,(t2 - trial.data$Arrival)))
trial.data$upperbound.comp1.t2 <- pmin(trial.data$Event1, followup, pmax(0,(t2 - trial.data$Arrival)))
trial.data$upperbound.comp2.t2 <- pmin(trial.data$Event2, followup, pmax(0,(t2 - trial.data$Arrival)))
#calculate compensators
trial.data$compensator.comp1.initialstate.t1 <- unlist(mapply(function(u,v) ifelse(u==v, 0, integrate(lambda.1a, u, v, rel.tol = 1e-10)), 0, trial.data$changestate.t1))
trial.data$compensator.comp1.changedstate.t1 <- unlist(mapply(function(u,v,w) ifelse(u==v, 0, integrate(lambda.1b, u, v, x2 = w)), trial.data$changestate.t1, trial.data$upperbound.comp1.t1, trial.data$Event2))
trial.data$compensator.comp2.initialstate.t1 <- unlist(mapply(function(u,v) ifelse(u==v, 0, integrate(lambda.2a, u, v)), 0, trial.data$changestate.t1))
trial.data$compensator.comp2.changedstate.t1 <- unlist(mapply(function(u,v,w) ifelse(u==v, 0, integrate(lambda.2b, u, v, x2 = w)), trial.data$changestate.t1, trial.data$upperbound.comp2.t1, trial.data$Event1))
trial.data$compensator.comp1.initialstate.t2 <- unlist(mapply(function(u,v) ifelse(u==v, 0, integrate(lambda.1a, u, v, rel.tol = 1e-10)), 0, trial.data$changestate.t2))
trial.data$compensator.comp1.changedstate.t2 <- unlist(mapply(function(u,v,w) ifelse(u==v, 0, integrate(lambda.1b, u, v, x2 = w)), trial.data$changestate.t2, trial.data$upperbound.comp1.t2, trial.data$Event2))
trial.data$compensator.comp2.initialstate.t2 <- unlist(mapply(function(u,v) ifelse(u==v, 0, integrate(lambda.2a, u, v)), 0, trial.data$changestate.t2))
trial.data$compensator.comp2.changedstate.t2 <- unlist(mapply(function(u,v,w) ifelse(u==v, 0, integrate(lambda.2b, u, v, x2 = w)), trial.data$changestate.t2, trial.data$upperbound.comp2.t2, trial.data$Event1))
#calculate martingales on patient level
trial.data$martingale.comp1.t1 <- ifelse(trial.data$Event1 <= pmin(followup, pmax(0,t1 - trial.data$Arrival)), 1, 0) - trial.data$compensator.comp1.initialstate.t1 - trial.data$compensator.comp1.changedstate.t1
trial.data$martingale.comp2.t1 <- ifelse(trial.data$Event2 <= pmin(followup, pmax(0,t1 - trial.data$Arrival)), 1, 0) - trial.data$compensator.comp2.initialstate.t1 - trial.data$compensator.comp2.changedstate.t1
trial.data$martingale.comp1.t2 <- ifelse(trial.data$Event1 <= pmin(followup, pmax(0,t2 - trial.data$Arrival)), 1, 0) - trial.data$compensator.comp1.initialstate.t2 - trial.data$compensator.comp1.changedstate.t2
trial.data$martingale.comp2.t2 <- ifelse(trial.data$Event2 <= pmin(followup, pmax(0,t2 - trial.data$Arrival)), 1, 0) - trial.data$compensator.comp2.initialstate.t2 - trial.data$compensator.comp2.changedstate.t2
#calculate overall martingales
results$Event1.t1[i] <- n^(-1/2) * sum(trial.data$martingale.comp1.t1)
results$Event2.t1[i] <- n^(-1/2) * sum(trial.data$martingale.comp2.t1)
results$Event1.t2[i] <- n^(-1/2) * sum(trial.data$martingale.comp1.t2)
results$Event2.t2[i] <- n^(-1/2) * sum(trial.data$martingale.comp2.t2)
results$Var.Event1.t1[i] <- sum(trial.data$Event1 <= pmin(followup, pmax(0,t1 - trial.data$Arrival)))
results$Var.Event2.t1[i] <- sum(trial.data$Event2 <= pmin(followup, pmax(0,t1 - trial.data$Arrival)))
results$Var.Event1.t2[i] <- sum(trial.data$Event1 <= pmin(followup, pmax(0,t2 - trial.data$Arrival)))
results$Var.Event2.t2[i] <- sum(trial.data$Event2 <= pmin(followup, pmax(0,t2 - trial.data$Arrival)))
}, error = function(e){cat("ERROR in simulation ", i, ": ", conditionMessage(e), sep = "", "\n")})
}
#Calculate final statistics
results$Z1.t1 <- sqrt(n) * results$Event1.t1/sqrt(results$Var.Event1.t1)
results$Z2.t1 <- sqrt(n) * results$Event2.t1/sqrt(results$Var.Event2.t1)
results$Z1.t2 <- sqrt(n) * (results$Event1.t2 - results$Event1.t1)/sqrt(results$Var.Event1.t2 - results$Var.Event1.t1)
results$Z2.t2 <- sqrt(n) * (results$Event2.t2 - results$Event2.t1)/sqrt(results$Var.Event2.t2 - results$Var.Event2.t1)
emp.alpha.level[current.row.to.fill,"Sample size"] <- sample.size.temp
emp.alpha.level[current.row.to.fill,"m1"] <- fixed.median
emp.alpha.level[current.row.to.fill,"k1"] <- fixed.shape
emp.alpha.level[current.row.to.fill,"m2"] <- med2.temp
emp.alpha.level[current.row.to.fill,"k2"] <- kappa2.temp
emp.alpha.level[current.row.to.fill,"Copula"] <- copula.temp
emp.alpha.level[current.row.to.fill,"Copula parameter"] <- copula.parameters[intensity.temp, copula.temp]
#compute empirical error level for standard and weighted maxnorm and L2 rejection regions and fill the corresponding cells
results$rejection.maxnorm <- 1-(abs(results$Z1.t1)<u.maxnorm)*(abs(results$Z2.t1)<u.maxnorm)*(abs(results$Z1.t2)<u.maxnorm)*(abs(results$Z2.t2)<u.maxnorm)
emp.alpha.level[current.row.to.fill,"alpha.maxnorm"] <- sum(results$rejection.maxnorm, na.rm = TRUE)/simulations
results$rejection.L2 <- 1-((results$Z1.t1)^2 + (results$Z2.t1)^2 < u.L2)*((results$Z1.t2)^2 + (results$Z2.t2)^2 < u.L2)
emp.alpha.level[current.row.to.fill,"alpha.L2"] <- sum(results$rejection.L2, na.rm = TRUE)/simulations
results$rejection.maxnorm.weight1 <- 1-(abs(results$Z1.t1)<u1.maxnorm.weight1)*(abs(results$Z2.t1)<u1.maxnorm.weight1)*(abs(results$Z1.t2)<u2.maxnorm.weight1)*(abs(results$Z2.t2)<u2.maxnorm.weight1)
emp.alpha.level[current.row.to.fill,"alpha.maxnorm.weight1"] <- sum(results$rejection.maxnorm.weight1, na.rm = TRUE)/simulations
results$rejection.L2.weight1 <- 1-((results$Z1.t1)^2 + (results$Z2.t1)^2 < u1.L2.weight1)*((results$Z1.t2)^2 + (results$Z2.t2)^2 < u2.L2.weight1)
emp.alpha.level[current.row.to.fill,"alpha.L2.weight1"] <- sum(results$rejection.L2.weight1, na.rm = TRUE)/simulations
results$rejection.maxnorm.weight2 <- 1-(abs(results$Z1.t1)<u1.maxnorm.weight2)*(abs(results$Z2.t1)<u1.maxnorm.weight2)*(abs(results$Z1.t2)<u2.maxnorm.weight2)*(abs(results$Z2.t2)<u2.maxnorm.weight2)
emp.alpha.level[current.row.to.fill,"alpha.maxnorm.weight2"] <- sum(results$rejection.maxnorm.weight2, na.rm = TRUE)/simulations
results$rejection.L2.weight2 <- 1-((results$Z1.t1)^2 + (results$Z2.t1)^2 < u1.L2.weight2)*((results$Z1.t2)^2 + (results$Z2.t2)^2 < u2.L2.weight2)
emp.alpha.level[current.row.to.fill,"alpha.L2.weight2"] <- sum(results$rejection.L2.weight2, na.rm = TRUE)/simulations
}
}
}
}
}
|
66366c6d33166d16b7f797b41851d9a3c51f1e55
|
75db022357f0aaff30d419c13eafb9dddfce885a
|
/inst/IP/GLORYS_ESS_Shrimp.r
|
5eeeb57f87f3a8760e6a4e9837ee61732bf50eeb
|
[] |
no_license
|
LobsterScience/bio.lobster
|
d4c553f0f55f561bb9f9cd4fac52c585e9cd16f8
|
b2af955291cb70c2d994e58fd99d68c6d7907181
|
refs/heads/master
| 2023-09-01T00:12:23.064363
| 2023-08-23T16:34:12
| 2023-08-23T16:34:12
| 60,636,005
| 11
| 5
| null | 2017-01-20T14:35:09
| 2016-06-07T18:18:28
|
R
|
UTF-8
|
R
| false
| false
| 541
|
r
|
GLORYS_ESS_Shrimp.r
|
#Pruning GLORYS to ESS Shrimp
require(bio.lobster)
require(satin)
require(tidyr)
require(PBSmapping)
setwd(file.path(project.datadirectory('bio.lobster'),'data','GLORYS'))
y1 = read.cmems('GLORYS1993')
a = y1$bottomT
image(a@lon, a@lat, t(a@data[,,1,]))
po = data.frame(X=c(-62,-62,-57,-57),Y=c(44,46,46,44),PID=1,POS=c(1,2,3,4))
fil = dir()
fil = fil[grep('GLO',fil)]
for(i in 1:length(fil)){
g = glorysSubset(glorysfile=fil[i], polygon=po)
saveRDS(g,file = file.path('SummaryFiles',paste(fil[i],'ESSShrimp.rds',sep="_")))
}
|
b1f6f869ba02c5350a3c67ba9ca1034b302b1540
|
df4614ac59318c9c284d1d0337812e169ef74a59
|
/45-SimpleLinearRegression.R
|
ff6f212efed973079869b00d0c5796c93aabafbe
|
[] |
no_license
|
kushalpoudel35/r-scripts
|
354e9a97e2f2df0e12cdda5f5fc16b7ea04f6d9b
|
6d1c762a47f6500842e2fa93f7494b3d36289b9b
|
refs/heads/master
| 2021-06-27T14:22:48.885772
| 2021-06-04T12:55:11
| 2021-06-04T12:55:11
| 231,202,478
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,152
|
r
|
45-SimpleLinearRegression.R
|
LungCapData = read.table(file='data/LungCapData.txt', header=TRUE, sep='\t')
head(LungCapData)
names(LungCapData)
LungCap = LungCapData$LungCap
Age = LungCapData$Age
Height = LungCapData$Height
Smoke = LungCapData$Smoke
Gender = LungCapData$Gender
Caesarean = LungCapData$Caesarean
class(Age)
class(LungCap)
plot(Age, LungCap, las=1, main='Scatterplot')
cor(Age, LungCap)
# Regression is used to predict one variable based on another
# regression is based on causality i.e. one variable affects another
# variables cannot be flipped i.e. prediction can be done one way only
help(lm)
mod = lm(LungCap~Age)
summary(mod)
attributes(mod)
mod$coefficients
plot(Age, LungCap, las=1, main='Scatterplot')
abline(mod)
abline(mod, col=2, lwd=3)
# using ggplot2 (much easier)
library(ggplot2)
coef(mod)
# regression equation is
# LungCap = 1.147 + 0.545*Age
# lets plot
ggplot(LungCapData, aes(x=Age, y=LungCap)) +
geom_point() +
stat_smooth(method='lm', formula=y~x, geom='line', size=1, color='red') +
labs(title='Lung capacity Vs Age')
confint(mod)
confint(mod, level=0.99)
summary(mod)
anova(mod)
|
bed8241f50813c74b0e66aac05d51ff2116448ea
|
6ae574fc7fa9b720c361b9a47c51684cdd302f96
|
/R/print.CADFtestsummary.R
|
53d505700bbec2bf6bcb6611b84eadb1720b6f70
|
[] |
no_license
|
cran/CADFtest
|
7e498795d51f7bf72394d634daf327426c68dde8
|
405d9d90df237f6c5dbaa4da644172c178c1f8ef
|
refs/heads/master
| 2021-01-21T12:23:33.687891
| 2017-06-02T16:10:31
| 2017-06-02T16:10:31
| 17,678,203
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 265
|
r
|
print.CADFtestsummary.R
|
print.CADFtestsummary <- function(x, ...)
{
# x is an object of class `CADFtestsummary'
ttype <- "Covariate Augmented DF test"
if (nrow(x$test.summary)==3) ttype <- "Augmented DF test"
cat(ttype, "\n")
print(x$test.summary, ...)
print(x$model.summary, ...)
}
|
2825d9682289f488843079ac217e68c7e1f6fda8
|
2f4503595629446439b6c794a34840c6ce5d66a3
|
/If-else.R
|
a15249aa5bec14e9d685e68a644492052ccddfa3
|
[] |
no_license
|
nikhil4111995/R-for-Data-Analysis
|
caeed4530cc49e81143d420ea21c426a5a434df6
|
bc2a4c0ca75145b59fce64ae3096fe7d16a12ed0
|
refs/heads/main
| 2023-02-02T22:27:45.944739
| 2020-12-23T03:50:23
| 2020-12-23T03:50:23
| 323,795,553
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 176
|
r
|
If-else.R
|
rm(answer)
x <- rnorm(1)
if(x > 1){
answer <- "greater than one"
}else if (x<1 & x>0){
answer <- "Between 0 and 1"
} else {
answer <- "Less than 0"
}
|
222c82ae5ea6d9db263b6392dea1fd69f25f1b19
|
77157987168fc6a0827df2ecdd55104813be77b1
|
/MGDrivE/inst/testfiles/calcCos/libFuzzer_calcCos/calcCos_valgrind_files/1612727253-test.R
|
7c815f29f669d6d36be34e8d105831c0c4e22099
|
[] |
no_license
|
akhikolla/updatedatatype-list2
|
e8758b374f9a18fd3ef07664f1150e14a2e4c3d8
|
a3a519440e02d89640c75207c73c1456cf86487d
|
refs/heads/master
| 2023-03-21T13:17:13.762823
| 2021-03-20T15:46:49
| 2021-03-20T15:46:49
| 349,766,184
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 211
|
r
|
1612727253-test.R
|
testlist <- list(latLongs = structure(c(2.12687638151216e-310, 4.87418056037875e-241, 2.12687638151216e-310), .Dim = c(1L, 3L)), r = 1.668805394687e-307)
result <- do.call(MGDrivE::calcCos,testlist)
str(result)
|
63b2bbab93feaee6599831b27547e10c6ae78c14
|
4fed9d47a2af0bd99de61068b7ab54f08b109ebd
|
/Rmetapop/inst/examples/simulate_metapop.R
|
87e8f7867666bee74b4cd4beed48d11f7cc0454b
|
[] |
no_license
|
dkokamoto/Rmetapop
|
402d5dde93b103df757d54e1852ce20e61c490f1
|
281c1fbf4c233c1504ba0c116ffbbff9836cf351
|
refs/heads/master
| 2022-10-12T14:55:11.954234
| 2018-05-28T18:48:43
| 2018-05-28T18:48:43
| 38,710,185
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 13,733
|
r
|
simulate_metapop.R
|
#' @param n_loc number of locations at which a stock assessment is implemented
# #n_subloc <- rep(10,5) ### vector of number of sublocations
#' @param n_iter number of years to simulate, including the warmup period
#' @param n_stages number of stages including eggs and recruits
#' @param stage_mat stage # that indicates maturity
#' @param warmup number of warmup iterations prior to starting a fishery
#' @param M natural mortality (either a vector, matrix, or single value)
#' @param point.estimate logical for whether to estimate a point estimate or a fully Bayesian posterior
#' @param obs_sd observation standard deviation
#' @param spat_scale spatial scale of stray connectivity
#' @param C degree of stochasticity in the stray matrix where higher numbers are less stochastic
# ###
#' @param alpha BH stock-recruit parameter
#' @param beta BH stock-recruit parameters
#' @param phi first order recruitment autocorrelation
#' @param spat_sd gaussian spatial correlation parameter
#' @param site_sd overall log-scale recruitment standard deviation
fishery_simulate <- function(n_loc,stock_IDs,n_stages,stage_mat,#n_subloc,
alpha, beta, phi,M, spat_scale,spat_sd,surv_rho,
site_sd,C,obs_sd,cor_mat=NULL,
n_iter,point.estimate,warmup,h_crit){
Nstocks <- length(unique(stock_IDs))
### 9 x L mortality matrix (can also be a single number or a single row with L
### columns)
mort <- matrix(M, ncol = n_loc, nrow = length((stage_mat - 1):(n_stages)))
surv_array <- array(0, dim = c(n_stages - 1, n_stages - 1, n_loc))
### create identifier of survival array entries that correspond to each survival rate for quick
### replacement in the array
surv_array_id <- array(matrix(1:n_stages^2, ncol = n_stages) %in%
c(diag(matrix(1:n_stages^2,ncol = n_stages)[-c(1), ]), n_stages^2),
dim = c(n_stages, n_stages, n_loc))[-1,-1, ]
### fecundity at age
fec_at_age <- fecundity_age(stage_mat:(n_stages))
### biomass at age in tons (by the ten thousand)
tons_at_age <- LVBweight(stage_mat:(n_stages))/1000/10000
# matrix of mean stray probabilities, controled by a Cauchy distribution with scale spat_scale
stray_probs <- spat_cor_mat(n_loc, spat_scale = spat_scale, sumto1 = TRUE)
round(stray_probs,2)# columns are probability of coming from, and row is probability going to (i.e. column 2 row 1 is going from location 2 to location 1)
colSums(stray_probs) # check to make sure it sums to 1
### stochastic realizations of the stray matrix for each year using the Dirichlet
### distribution with scale = 1000 (higher = less stochastic probabiliies)
Crand <- ran_stray_prob(stray_mat=stray_probs,n_iter=n_iter,scale= C)
Crand[,,1:3] #examine the first three stray matrices in the array
### create matrices and vectors from parameters ### create spatiotemporal
### recruitment errors
errors <- spat_temp_ts(n_iter = n_iter, n_loc = n_loc, site_sd = site_sd, spat_sd = .1,
phi = phi,cor_mat)
errors$cor_mat ### correlation matrix among sites in log-scale recruitment error
errors$pacf ### within site partial-autocorrelation function
error_mat <- errors$ts ### save the ts for use in the simulation
### initial conditions ### create the data arrays
d1 <- c(0, 2:n_stages)
d2 <- paste("Location", 1:n_loc, sep = "_")
d2b <- paste("Stock",1:Nstocks,sep= "_")
d3 <- 1:n_iter
## set up the abundance array
X <- array(as.numeric(NA), dim = c(n_stages, n_loc, n_iter), dimnames = list(d1, d2, d3))
X[, , 1:2] <- matrix(rep(1e+08, each = n_loc), ncol = n_loc, byrow = T)
## set up the adult biomass array
B <- array(NA, dim = c(n_loc, n_iter+1), dimnames = list(d2, 1:(n_iter+1)))
B_s <- array(NA, dim = c(Nstocks, n_iter+1,2), dimnames = list(d2b, 1:(n_iter+1),c("actual","observed")))
B[, 1] <- tons_at_age %*% X[3:10,, 1]
B[, 2] <- tons_at_age %*% X[3:10,, 2]
for(i in 1:Nstocks){
B_s[i, 1,] <- sum(B[stock_IDs==i, 1])
B_s[i, 2,] <- sum(B[stock_IDs==i, 2])
}
## set up the Forecast adult biomass array
BF <- array(NA, dim = c(Nstocks, n_iter+1, n_iter,6), dimnames = list(d2b, 1:(n_iter+1), d3,c("Estimated Stock Size","Prediction","ESS_UP","ESS_LOW","P_UP","P_LOW")))
## set up the age frequnecy arrays
S_freq <- array(NA, dim = c(n_stages-2,n_loc, n_iter), dimnames = list(d1[-c(1,2)],d2,d3))
S_freq_s <- array(NA, dim = c(n_stages-2,Nstocks, n_iter), dimnames = list(d1[-c(1,2)],d2b,d3))
for (i in 1:2){
S_freq[,,i] <- t(t(X[-c(1,2),,i])/colSums(X[-c(1,2),,i]))
SN <- mapply(function(x) rowSums(X[-c(1,2),stock_IDs==x,i]),1:Nstocks)
S_freq_s[,,i] <- t(t(SN)/colSums(SN))
}
H <- array(NA, dim = c(n_iter+1,Nstocks), dimnames = list(1:(n_iter+1),d2b))
for (i in 1:n_iter){
H[i,] <- 0
}
for (i in 3:n_iter) {
surv_array[surv_array_id] <- ran_surv_prob(mean=exp(-mort),corr=0.05)
X[, , i] <- ssr_linear(alpha=alpha,beta=beta, fec_at_age = fec_at_age,
n_loc = n_loc, n_stages = n_stages,harvest=rep(0,Nstocks),
tons_at_age=tons_at_age,DI_selectivity= rep(1,length(stage_mat:n_stages)),
stage_mat = stage_mat,surv_array = surv_array,
s_ID=stock_IDs,N_s=Nstocks,
eggs = X[1, , i - 2], X0 = X[(stage_mat - 1):n_stages, , i - 1],
stray_mat = stray_probs, errors = 0)
B[, i] <- tons_at_age %*% X[3:10, , i]
B_s[, i,] <- mapply(function(x) sum(B[stock_IDs==x,i]),1:Nstocks)
### age frequency ###
SN <- mapply(function(x) rowSums(X[-c(1,2),stock_IDs==x,i]),1:Nstocks)
S_freq[,,i] <- t(t(X[-c(1,2),,i])/colSums(X[-c(1,2),,i]))
S_freq_s[,,i] <- t(t(SN)/colSums(SN))
}
B0 <- tons_at_age %*% mapply(function(x) rowSums(X[-c(1,2),stock_IDs==x,n_iter]),1:Nstocks)
B0_loc <- tons_at_age %*% X[-c(1,2),,n_iter]
fit.compile <- nlss_assess(b_obs=array(B0,dim= c(Nstocks,n_iter)),
b_true=array(B0,dim= c(Nstocks,n_iter)),
age_freq=S_freq_s[,,1:n_iter],obs_sd=obs_sd,sd_R=site_sd,
alpha_BH= alpha,beta_BH=beta/(n_loc/Nstocks),harvest= H[1:n_iter,],
selectivity=rep(1,length(stage_mat:n_stages)),n_loc=Nstocks,
fec_at_age=fec_at_age,weight_at_age=tons_at_age,
mort=rep(M,Nstocks),stage_mat=stage_mat,
n_stages=n_stages,phi=phi,n_warmup=3,
compile=TRUE,optimize=point.estimate,n_iter=n_iter)
### reset initial values as last two values of deterministic simulation
B[, 1] <- B[, n_iter-1]
B[, 2] <- B[, n_iter]
B_s[, 1,] <- B_s[, n_iter-1,]
B_s[, 2,] <- B_s[, n_iter,]
for (i in 1:2){
S_freq[,,i] <- S_freq[,,n_iter-2+i]
S_freq_s[,,i] <- S_freq_s[,,n_iter-2+i]
}
### project the population with stochastic recruitment and harvesting ###
for (i in 3:(n_iter)) {
ptm <- proc.time()
surv_array[surv_array_id] <- ran_surv_prob(mean=exp(-mort),corr=0.05)
X[, , i] <- ssr_linear(alpha=alpha,beta=beta, fec_at_age = fec_at_age,
n_loc = n_loc, n_stages = n_stages,
N_s=Nstocks,s_ID=stock_IDs,
tons_at_age=tons_at_age,harvest=H[i,],
stage_mat = stage_mat,
surv_array = surv_array,
DI_selectivity= rep(1,length(stage_mat:n_stages)),
eggs = X[1, , i - 2],
X0 = X[(stage_mat - 1):n_stages, , i - 1],
stray_mat = Crand[,, i - 1], errors = errors$ts[i - 1, ])
B[, i] <- tons_at_age %*% X[3:10, , i]
B_s[, i,1] <- mapply(function(x) sum(B[stock_IDs==x,i]),1:Nstocks)
B_s[, i,2] <- B_s[, i,1]* exp(rnorm(Nstocks, 0, obs_sd) - 0.5 * obs_sd^2)
### age frequency ###
SN <- mapply(function(x) rowSums(X[-c(1,2),stock_IDs==x,i]),1:Nstocks)
S_freq[,,i] <- t(t(X[-c(1,2),,i])/colSums(X[-c(1,2),,i]))
S_freq_s[,,i] <- t(t(SN)/colSums(SN))
### stock assessment
if(i>warmup){
assess <- nlss_assess(b_obs=B_s[, 1:i,2],b_true=B_s[, 1:i,1],sd_R=site_sd,
age_freq=S_freq_s[,,1:i],obs_sd=obs_sd,
alpha_BH= alpha,beta_BH=I(beta/(n_loc/Nstocks)),harvest= H[1:i,],
selectivity=rep(1,length(stage_mat:n_stages)),n_loc=Nstocks,
fec_at_age=fec_at_age,weight_at_age=tons_at_age,
mort=rep(M,Nstocks),stage_mat=stage_mat,
n_stages=n_stages,phi=phi,n_warmup=3,compile= FALSE,
n_iter=i,optimize=point.estimate,compiled_model= fit.compile)
if(point.estimate==TRUE){
BF[, 1:(i), i,1] <- t(assess$assess$mean)
BF[, 1:(i+1), i,2] <- t(assess$assess$pred)
}
else{
BF[, 1:(i), i,1] <- t(assess$assess$mean)
BF[, 1:(i+1), i,2] <- t(assess$assess$pred)
BF[, 1:(i), i,3] <- t(assess$assess$upper)
BF[, 1:(i), i,4] <- t(assess$assess$lower)
BF[, 1:(i+1), i,5] <- t(assess$assess$pred_upper)
BF[, 1:(i+1), i,6] <- t(assess$assess$pred_lower)
}
### forecast array
Hcrit <- ifelse(h_crit*B0<BF[,i+1,i,2],1,0)
H[i+1,] <- mapply(min,BF[,i+1,i,2]-h_crit*B0,0.2*BF[,i+1,i,2])*Hcrit
cat(noquote(paste("iteration",i, "of", n_iter, "completed in", signif(proc.time()[3]-ptm[3],digits=4),"sec\n")))
}
else{
H[i+1,] <- rep(0,Nstocks)
if(i==warmup){
cat(noquote(paste("iterations 1:",i," of ",n_iter," complete (warmup)\n",sep= "")))
}
}
}
B0.df <- melt(B0,varnames=c("time","location"),value.name= "B0")
pred <- melt(apply(BF[,-1,,2],1,diag),varnames=c("time","site"),value.name= "pred")
mean <- melt(apply(BF[,-n_iter,,1],1,diag),varnames=c("time","site"),value.name= "mean")
forecast_array <- join(pred,mean,by =c("time","site"))
assess2 <- reshape(melt(assess$assess,varnames= c("time","location")), timevar = "L1", idvar = c("time","location"), direction = "wide")
names(assess2) <- gsub("value.","",names(assess2))
if(point.estimate==TRUE){
plot1 <- ggplot(aes(time,observed),data= assess2)+
geom_line(aes(y=mean),col= "black")+
geom_line(aes(y=pred),col= "blue")+
geom_point(shape= 21, fill= "black",size= 0.5)+
geom_point(aes(y=actual),shape= 21, fill= "pink",col= "red",size =0.5)+
facet_wrap(~location)+
geom_hline(aes(yintercept= B0),data= B0.df,linetype="dotted")+
geom_hline(aes(yintercept= 0.25*B0),data= B0.df,col= "red")+
theme_bw()+geom_vline(xintercept= warmup+1)
}
else{
plot1 <- ggplot(aes(time,observed),data= assess2)+
geom_ribbon(aes(ymin= lower,ymax= upper),col= "grey70",fill= "grey70")+
geom_line(aes(y=mean),col= "black")+
#geom_ribbon(aes(ymin= pred_lower,ymax= pred_upper),col= "blue",fill= NA)+
geom_line(aes(y=pred),col= "blue")+
geom_point(shape= 21, fill= "black",size= 0.5)+
geom_point(aes(y=actual),shape= 21, fill= "pink",col= "red",size =0.5)+
facet_wrap(~location)+
geom_hline(aes(yintercept= B0),data= B0.df,linetype="dotted")+
geom_hline(aes(yintercept= 0.25*B0),data= B0.df,col= "red")+
theme_bw()+geom_vline(xintercept= warmup+1)
}
### create a dataframe for plotting
df_ts <- as.data.frame.table(X)
names(df_ts) <- c("Age", "Location", "Time", "Number")
df_ts$Time <- as.numeric(as.character(df_ts$Time))
df_ts$Age <- as.numeric(as.character(df_ts$Age))
df_ts$Stage <- with(df_ts, ifelse(Age == 2, "Recruits", ifelse(Age == 0, "Eggs", "Adults")))
df_ts$Age_Class <- with(df_ts, ifelse(Age == 2, "Recruits", ifelse(Age == 0, "Eggs",ifelse(Age>9,"9+", Age))))
### plot the time series of adults plotting options
plot.options <- theme(strip.background = element_rect(fill = NA, colour = NA),
panel.grid.minor = element_line(colour = NA),
panel.grid.major = element_line(colour = NA),
legend.key = element_blank(),
legend.key.size = unit(0.6, "cm"), legend.position = "right",
legend.direction = "vertical",
panel.background = element_rect(fill = NA, colour = "black"),
legend.key.width = unit(1.5, "lines"),
panel.margin = unit(1, "lines"),
legend.background = element_rect(fill = NA, colour = NA),
plot.background = element_rect(fill = NA),
plot.margin = unit(c(0.075, 0.075, 0.075, 0.2), "inches"))
### generate the plot ###
plot2 <- ggplot(aes(Time, Number/1e+06), data = df_ts) +
geom_line(aes(colour = Age_Class)) +
facet_grid(Stage ~ Location,scales= "free_y") +
plot.options +
ylab("Number (Millions)")+
scale_x_continuous(expand = c(0, 0))
### correlation in recruitment among sites
rec_cor <- cor(t(X[2, ,warmup:n_iter ]))
### correlation in biomass among sites
B_cor <- cor(t(B[, warmup:n_iter]))
# stats <- data.frame(
# list(
# "B_hat_lt_h_crit"=c(mean(apply(B_s[,(warmup+2):n_iter,1],2,function(x)h_crit*t(B0)/x)>1),
# mean(colMeans(apply(B_s[,(warmup+2):n_iter,1],2,function(x)h_crit*t(B0)/x)>1)==1)),
# "B_lt_h_crit"=c(mean(H[(warmup+2):n_iter,]==0),
# mean(rowMeans(H[(warmup+2):n_iter,]==0)==1)),
# "Bloc_lt_h_crit"=c(mean(c(test$B[,(warmup+2):n_iter]<=0.25*B0_loc)),
# mean(rowMeans(test$H[(warmup+2):n_iter,]==0)==1)),
# "CV" = c(mean(apply(H[(warmup+2):n_iter,],2,function(x)sd(x)/mean(x))),
# sd(rowSums(H[(warmup+2):n_iter,]))/mean(rowSums(H[(warmup+2):n_iter,]))),
# source= c("Local","Global")))
return(list(B=B,asess=BF,B_stocks=B_s,ages=X,B0=B0.df,Harvest=H,forcast=forecast_array,plot_biomass=plot1,plot_nums=plot2,corrs= list(recruitment=rec_cor,biomass=B_cor,B0_loc)))
}
|
ce1947925c4a729ec181556ead2c543b7f7267e2
|
f67acc22852d59399366ed9d1453c6ee39c9e7e1
|
/fancy_plot_survival.R
|
dc80813f1e5c0ce772a0eddaa9cbeb6017e5ffdc
|
[] |
no_license
|
daboe01/fancy_plot_survival
|
aee4df56b2c5c39fe410dc83a992cf505ed0f17a
|
6bf81e480e52e0a833fa5f854d5b2fa413a066f3
|
refs/heads/master
| 2020-06-06T13:04:35.292247
| 2015-07-01T11:52:19
| 2015-07-01T11:52:19
| 38,367,704
| 3
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,378
|
r
|
fancy_plot_survival.R
|
# 1.9.2008: survival plot tool by dr. boehringer
# todo: option to append the n= per group to the legends
# rework jitter.groups to give deterministic results
library(ggplot2)
library(survival)
plot.survival.fancy=function(s, conf.int=F, auto.scale=F, xmax=0, marker=c("point","blank"), displace.groups=F, levels=c(), reorder.groups=T, reorder.groups.FUN=NULL, xlim=NULL, ...){
s.plot=data.frame(time=NA, surv=NA, min=NA, max=NA, group=NA, evnt=NA) # is there a better way to create an empty data.frame?
pind=1
if(length(names(s$strata)))
{ off=0
for(j in names(s$strata))
{ if(displace.groups ==F) off=0
s.plot=rbind(data.frame(time=0*max(s$time), surv=1+off, min=1, max=1, group=j, evnt=0), s.plot)
uind= pind+s$strata[j]-1
s.plot=rbind(s.plot,data.frame(time=s$time[pind: uind]+ off*max(s$time), surv=s$surv[pind: uind]+ off, min=s$upper[pind:uind], max=s$lower[pind:uind], group= rep(j, s$strata[j]), evnt=s$n.event[pind:uind] ) )
pind= uind+1
off=off+0.005
}
} else
{ s.plot=rbind(data.frame(time=0, surv=1, min=1, max=1, group=NA, evnt=0), s.plot)
s.plot=rbind(s.plot,data.frame(time=s$time, surv=s$surv, min=s$upper, max=s$lower, group= NA, evnt=s$n.event ) )
}
s.plot=s.plot[!is.na(s.plot$evnt),]
s.plot$stratum=NA
if(xmax) s.plot=subset(s.plot, time< xmax)
if( max (is.na(s.plot$group)) )
{ s.plot=s.plot[order(s.plot$time), ];
q=qplot(time, surv, data= subset(s.plot, evnt==0 & time>0), geom=marker,...)
if(!is.null(xlim)) q=q+ coord_cartesian(xlim = xlim)
if(auto.scale)
if(conf.int)
q+
geom_step(data=s.plot, aes(x=time, y=surv, group=group), size=1.2)+
geom_ribbon(data=s.plot, aes(x=time, min=min, max=max), size=0, alpha=0.3)
else
q+
geom_step(data=s.plot, aes(x=time, y=surv), size=1.2)
else
if(conf.int)
q+scale_y_continuous(limits=c(0,1))+
geom_step(data=s.plot, aes(x=time, y=surv), size=1.2)+
geom_ribbon(data=s.plot, aes(x=time, min=min, max=max), size=0,alpha=0.3)
else
q+
scale_y_continuous(limits=c(0,1))+
geom_step(data=s.plot, aes(x=time, y=surv), size=1.2) }
else
{ stratavec=c()
if(length(grep('.*strata.*?=',s.plot$group, perl=T)))
{ stratavec=levels(as.factor(sub('.*strata.*?=','',s.plot$group, perl=T) ))
for(j in stratavec )
{ i= grep(j,s.plot$group)
s.plot$stratum[i]=j;
}
s.plot$group=sub(', strata.*$', '', s.plot$group, perl = TRUE) #crude hack to elim the strata...
}
s.plot$stratum =sub('.*=', '', s.plot$stratum, perl = TRUE)
s.plot$group.stripped=sub('.*=', '', s.plot$group, perl = TRUE) # another crude hack...
s.plot$group= s.plot$group.stripped
if(length(levels)) s.plot$group=factor(s.plot$group.stripped, levels=levels, ordered=T)
else
if(!is.null(reorder.groups.FUN))
{ s.plot$group=as.factor(s.plot$group)
X= reorder.groups.FUN(s.plot$group)
s.plot$group=reorder(s.plot$group, X )
} else if(reorder.groups) s.plot$group=reorder(as.factor(s.plot$group), s.plot$surv, FUN= function(x) sum(-x)/pmax(length(x),1) )
s.plot=s.plot[order(s.plot$group,s.plot$time), ];
if(length(stratavec))
q=qplot(time, surv, data= subset(s.plot, evnt==0&time>0), geom=marker, colour=group, facets= stratum ~., ...)
else
{ my.df= subset(s.plot, evnt==0&time>0)
my.geom= marker
if(nrow(my.df)==0)
{
my.df=s.plot
my.geom="blank"
}
q=qplot(time, surv, data= my.df, geom= my.geom, colour=group, ...)
}
if(!is.null(xlim)) q=q+ coord_cartesian(xlim = xlim)
if(auto.scale)
if(conf.int)
return(q+
geom_step(data=s.plot, aes(x=time, y=surv, group=group, colour=group), size=1.2)+scale_colour_brewer(palette = 3)+
geom_ribbon(data=s.plot, aes(x=time, min=min, max=max, fill=group), size=0, alpha=0.3)+ scale_fill_brewer(palette = 3))
else
{ return(q+
geom_step(data=s.plot, aes(x=time, y=surv, group=group, colour=group), size=1.2))
}
else
if(conf.int)
return(q+scale_y_continuous(limits=c(-0.05,1.1))+
geom_step(data=s.plot, aes(x=time, y=surv, group=group, colour=group), size=1.2)+scale_colour_brewer(palette = 3)+
geom_ribbon(data=s.plot, aes(x=time, min=min, max=max, fill=group), size=0, alpha=0.3)+ scale_fill_brewer(palette = 3))
else
{ return(q+
scale_y_continuous(limits=c(-0.05,1.1))+
geom_step(data=s.plot, aes(x=time, y=surv, group=group, colour=group), size=1.2))
}
}
}
|
8eb00d8d47673630b66bb856562729d79124ce55
|
8ec902c3b48d757aa459caf17f3fac723b20187c
|
/R/make.thresholds.character.R
|
c9c838ee5d28090ae68f6595192ba7d164aba535
|
[
"BSD-2-Clause"
] |
permissive
|
david-ti/wrightmap
|
47d34578a087d890033a47c4e8d62e261f29c532
|
daed7f30eb01d065a2c4ae7c245154abdaf7cb1c
|
refs/heads/master
| 2022-06-30T09:07:29.029247
| 2022-05-15T22:44:32
| 2022-05-15T22:44:32
| 17,348,470
| 2
| 5
|
NOASSERTION
| 2022-05-15T22:44:33
| 2014-03-02T22:24:15
|
R
|
UTF-8
|
R
| false
| false
| 159
|
r
|
make.thresholds.character.R
|
make.thresholds.character <-
function(item.params,design.matrix="normal",...) {
#print("character")
return(make.thresholds(CQmodel(show=item.params),...))
}
|
c8eb739901ce8fb1ceac2176a194cc3a926a6794
|
d58b6bcfc847a1f8fafa5de52f308d6546a422ac
|
/2020_WTCW/0-1.Illustrations.R
|
298c9c98b1ba26a931e6921d6be4249ca31b48ef
|
[
"MIT"
] |
permissive
|
baruuum/Replication_Code
|
814d25f873c6198971afcff62b6734d3847f38f6
|
23e4ec0e6df4cf3666784a0d18447452e3e79f97
|
refs/heads/master
| 2022-03-01T19:42:13.790846
| 2022-02-15T07:32:47
| 2022-02-15T07:32:47
| 138,830,546
| 9
| 10
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,384
|
r
|
0-1.Illustrations.R
|
###############################################################################
## ##
## Hypothetical Scenarioes, Graphics for Illustration ##
## ##
###############################################################################
if (!exists('wd.base')) {
# base directory
stop('Specify "wd.base"!')
}
# set paths
if (!exists('code.path'))
code.path <- paste0(wd.base, 'code/')
if (!exists('raw.data.path'))
raw.data.path <- paste0(wd.base, 'raw_data/')
if (!exists('data.path'))
data.path <- paste0(wd.base, 'data/')
if (!exists('graphics.path'))
graphics.path <- paste0(wd.base, 'plots/')
if (!exists('stan.path'))
stan.path <- paste0(wd.base, 'stan/')
# line widths
l.width <- 1.5
lab.dist <- .7
seg.wd <- 1
# old plotting parameters
old.par <- par()
# Symmetric Issue partisanship
pdf(paste0(graphics.path, 'Figure1A.pdf'), height=7, width=3)
par(mfrow=c(3,1))
par(mar=rep(.5,4))
par(oma=rep(2,4))
plot(c(0,1), c(0,1), type="n", axes=F)
box()
mtext('Issue Partisanship',font=2,side=3,outer=F, line=lab.dist)
abline(h=.5, lwd=l.width)
mtext('% Liberal', side=2, outer=F, line=lab.dist)
plot(c(0,1), c(0,1), type="n", axes=F)
box()
abline(.5, .3, lwd=l.width, lty=1)
abline(.5, -.3, lwd=l.width, lty=2, col='darkgray')
for (v in seq(0,1,.1)) {
segments(v,.5 + -.3*v, v, .5+.3*v, col='gray80', lwd=seg.wd, lty=3)
}
mtext('% Liberal (by Party ID)', side=2, outer=F, line=lab.dist)
plot(c(0,1), c(-1,1), type="n", axes=F)
box()
abline(0, .6, lwd=l.width)
mtext('% Liberal (Dem - Rep)', side=2, outer=F, line=lab.dist)
mtext('Time', side=1, outer=F, line=lab.dist)
dev.off()
# Secular Trend (I)
pdf(paste0(graphics.path, 'Figure1B.pdf'), height=7, width=3)
par(mfrow=c(3,1))
par(mar=rep(.5,4))
par(oma=rep(2,4))
plot(c(-4,4), c(0,1), type="n", axes=F)
box()
mtext('Secular Trend', outer=F, side=3, font=2, line=lab.dist)
curve(pnorm(x), xlim=c(-4,4), add=T, lwd=l.width)
plot(c(-3,3), c(0,1), type="n", axes=F)
box()
curve(pnorm(x), xlim=c(-4,4), add=T, lwd=l.width)
curve(pnorm(x), add=T, lty=2, col='darkgray', lwd=l.width)
plot(c(0,1), c(-1,1), type="n", axes=F)
box()
abline(h=0, lwd=l.width)
mtext('Time', side=1, outer=F, line=lab.dist)
dev.off()
# Partisan Secular Trend
pdf(paste0(graphics.path, 'Figure1C.pdf'), height=7, width=3)
par(mfrow=c(3,1))
par(mar=rep(.5,4))
par(oma=rep(2,4))
plot(c(-4,4), c(0,1), type="n", axes=F)
box()
mtext('Partisan Secular Trend', font=2, side=3, outer=F, line=lab.dist)
curve(pnorm(x), xlim=c(-4,4), add=T, lwd=l.width)
plot(c(-4,4), c(0,1), type="n", axes=F)
box()
curve(pnorm(x+.75), xlim=c(-4,4), add=T, lwd=l.width)
curve(pnorm(x-.75), add=T, col='darkgray', lwd=l.width, lty=2)
for (v in seq(-4,4,.8)) {
segments(v,pnorm(v-.75), v, pnorm(v+.75), col='gray80', lwd=seg.wd, lty=3)
}
plot(c(0,1), c(-1,1), type="n", axes=F)
box()
curve(3*x + -3*x^2, add=T, lwd=l.width)
# plot(c(-1,1), c(-1,1), type = 'n', axes =F)
# box()
# curve(exp(-x^2/.5) - exp(-1/.5), add = T, lwd=l.width)
mtext('Time', side=1, outer=F, line=lab.dist)
dev.off()
suppressWarnings(par(old.par))
#### END OF CODE ####
|
91c3ae3889ebeb8ce1dcb6fdabd9e47e268d96bd
|
0ff5853af9fd557f6591979a834d9fe82708d234
|
/R/hatvalues.drc.R
|
d26fb78f36ea2cb2c0b1aa8428e7f5a7a008ac44
|
[] |
no_license
|
csetraynor/drc
|
4c6deed9b783802852cfd3ed60c87dec6afc0ce5
|
8719d43a09711250cd791d7d2bc965558d3e62a6
|
refs/heads/master
| 2023-04-11T03:15:00.881506
| 2021-05-04T02:42:06
| 2021-05-04T02:42:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 195
|
r
|
hatvalues.drc.R
|
hatvalues.drc <- function(model, ...)
{
xmat <- model$der
diag(xmat %*% ginv(t(xmat) %*% xmat) %*% t(xmat))
# names(hvector) <- as.character(1:length(hvector))
# hvector
}
|
a03a697f5cffcca2405cceb09beaf6b8dfbc6ace
|
66aba2d5193e0a918e558f8681d9814f3472ad31
|
/run_analysis.R
|
d6feb52ed037203777bfccd8904052f6b6e96410
|
[] |
no_license
|
jonleogane/Getting-and-Cleaning-Data-project
|
7a5889a68ae8aea4d2abcf073e57de9c5566a709
|
15f6714e9c92387088f3461339e840b0b3e13b19
|
refs/heads/master
| 2021-01-25T10:28:43.225677
| 2015-07-22T17:07:18
| 2015-07-22T17:07:18
| 39,506,016
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,008
|
r
|
run_analysis.R
|
library(plyr)
# Step 1 - Merge the test and training datasets
# read data into variables
x_train <- read.table("data/getdata-projectfiles-UCI HAR Dataset/train/X_train.txt")
y_train <- read.table("data/getdata-projectfiles-UCI HAR Dataset/train/y_train.txt")
subject_train <- read.table("data/getdata-projectfiles-UCI HAR Dataset/train/subject_train.txt")
x_test <- read.table("data/getdata-projectfiles-UCI HAR Dataset/test/X_test.txt")
y_test <- read.table("data/getdata-projectfiles-UCI HAR Dataset/test/y_test.txt")
subject_test <- read.table("data/getdata-projectfiles-UCI HAR Dataset/test/subject_test.txt")
# merge x_train and x_test
x_data <- rbind(x_train,x_test)
# merge y_train and y_test
y_data <- rbind(y_train,y_test)
# merge subject_train and subject_test
subject_data <- rbind(subject_train, subject_test)
# Step 2 - extract mean and standard deviation for each measurement
features <- read.table("data/getdata-projectfiles-UCI HAR Dataset/features.txt")
# get columns with mean and std in their names
mean_std <- grep("-(mean|std)\\(\\)", features[, 2])
# subset the desired columns
x_data <- x_data[, mean_std]
# fix columns names
names(x_data) <- features[mean_std, 2]
# Step 3
# Use descriptive activity names to name the activities in the data set
activities <- read.table("data/getdata-projectfiles-UCI HAR Dataset/activity_labels.txt")
# update values with correct activity names
y_data[, 1] <- activities[y_data[, 1], 2]
names(y_data) <- "activity"
# correct column name
# Step 4
# Appropriately label using descriptive variable names
# change column name
names(subject_data) <- "subject"
# bind all into a single data set
combine_data <- cbind(x_data, y_data, subject_data)
# Step 5
# Create a tidy data set with the average of each variable
# for each activity and each subject
# don't include last 2 cols
avg_data <- ddply(combine_data, .(subject, activity), function(x) colMeans(x[, 1:66]))
write.table(avg_data, "tidy_data.txt", row.name=FALSE)
|
3a373db105659406b6e15b5ebdc5688c55f937ce
|
7a89c1c240c0935f0d7ea809717961ad28657769
|
/R/approximate_entropy.R
|
d6d217d7385292dd007f64b058562a1d2a7f3c6f
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
abhishektiwari/Rptsentropy
|
ae5a7315fb1efebf64be311c0df20424cba15ab8
|
9787d53ebbd965ebcebc370ddfa4ee5d0c6d6894
|
refs/heads/master
| 2020-06-05T08:56:39.109622
| 2011-02-25T15:01:20
| 2011-02-25T15:01:20
| 1,380,223
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 488
|
r
|
approximate_entropy.R
|
#! /usr/bin/env Rscript
# Copyright © 2010-2011 Abhishek Tiwari (abhishek@abhishek-tiwari.com)
#
# This file is part of ptsentropy.
#
# Files included in this package ptsentropy are copyrighted freeware
# distributed under the terms and conditions as specified in file LICENSE.
ApEn <- function(entropy3) {
cmr <- Cmr(entropy3[["conc"]], entropy3[["m"]], entropy3[["r"]], TRUE)
cmr1 <- Cmr(entropy3[["conc"]], entropy3[["m"]]+1, entropy3[["r"]], TRUE)
return (log(cmr/cmr1))
}
|
65223ab3691ca6d575bf16caf409f665014d62a0
|
effe14a2cd10c729731f08b501fdb9ff0b065791
|
/paws/man/pinpoint_get_user_endpoints.Rd
|
4b0056439fc52f6a101443aeeabd8b2fd2fcd51c
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
peoplecure/paws
|
8fccc08d40093bb25e2fdf66dd5e38820f6d335a
|
89f044704ef832a85a71249ce008f01821b1cf88
|
refs/heads/master
| 2020-06-02T16:00:40.294628
| 2019-06-08T23:00:39
| 2019-06-08T23:00:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 697
|
rd
|
pinpoint_get_user_endpoints.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pinpoint_operations.R
\name{pinpoint_get_user_endpoints}
\alias{pinpoint_get_user_endpoints}
\title{Returns information about the endpoints that are associated with a User
ID}
\usage{
pinpoint_get_user_endpoints(ApplicationId, UserId)
}
\arguments{
\item{ApplicationId}{[required] The unique ID of your Amazon Pinpoint application.}
\item{UserId}{[required] The unique ID of the user.}
}
\description{
Returns information about the endpoints that are associated with a User ID.
}
\section{Request syntax}{
\preformatted{svc$get_user_endpoints(
ApplicationId = "string",
UserId = "string"
)
}
}
\keyword{internal}
|
fe382a32faa13aa7680ca97eee7d53c399376cbe
|
d1cc6e32ab5af2ac5b974b0ad0ce2a2a4b453e31
|
/man/split_path.Rd
|
3438b1bbc2d661fa0b4eb6e3fe6946f52e102911
|
[] |
no_license
|
CarragherLab/ImageXpressR
|
ed5e192328acee9586e04d7b0b317151c2e56a73
|
262086967ad4158cf494ed8777ae1582323c903c
|
refs/heads/master
| 2021-01-02T09:23:19.279811
| 2017-08-03T07:16:44
| 2017-08-03T07:16:44
| 99,202,967
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 322
|
rd
|
split_path.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/parse.R
\name{split_path}
\alias{split_path}
\title{split path into components by file separator}
\usage{
split_path(path)
}
\arguments{
\item{path}{string, ImageExpress file path}
}
\description{
split path into components by file separator
}
|
36c1c1c1f25d542293775f5369c31d1e091c47d0
|
17f2a5bda68e2df016bfc0833e29b4ff7841d517
|
/R/Functions for PSMD.Psychometrics (JC).R
|
465c3d5420d5798c0aeda9f1bf1ce44f913032eb
|
[] |
no_license
|
PSMD-Psychometrics/-old-psychometricsPSMD-old-
|
3a5b6b51896c41154f547b7251a9d0edef1b28fc
|
3a5c817fd6e0ddc357590e94c5ca2b7f803ad3c4
|
refs/heads/master
| 2021-07-03T09:22:30.848231
| 2017-09-22T09:03:09
| 2017-09-22T09:03:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,001
|
r
|
Functions for PSMD.Psychometrics (JC).R
|
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#### Jo's Functions ####
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#### Converting integers to characters (<10) ####
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Function to convert integers <10 to strings
fnNumToWord<-function(x){
ifelse(x==0,"no",ifelse(x==1,"one",ifelse(x==2,"two",ifelse(x==3,"three",ifelse(x==4,"four",ifelse(x==5,"five",
ifelse(x==6,"six",ifelse(x==7,"seven",ifelse(x==8,"eight",ifelse(x==9,"nine",x))))))))))
}
fnNumToWordCap<-function(x){
ifelse(x==0,"no",ifelse(x==1,"One",ifelse(x==2,"Two",ifelse(x==3,"Three",ifelse(x==4,"Four",ifelse(x==5,"Five",
ifelse(x==6,"Six",ifelse(x==7,"Seven",ifelse(x==8,"Eight",ifelse(x==9,"Nine",x))))))))))
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#### Plot - boxplots ####
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fnPlotBoxplot1<-function(dataframe,xGroup="Stage",yGroup="Score",maxScore=100){
xAxis<-dataframe[[xGroup]]
yAxis<-dataframe[[yGroup]]
dataPlot<-data.frame(xAxis,yAxis)
# code to identify xScheme from the data
#if(class(dataPlot[,1]=="numeric" & max(dataPlot[,1]>5)){xScheme<-"Assessor"}
#if(class(dataPlot[,1]=="numeric" & max(dataPlot[,1]<6)){xScheme<-"Stage"}
if(class(dataPlot[,1])=="numeric") {xScheme<-ifelse(max(dataPlot[,1]>5),"Assessor","Stage")}
if(class(dataPlot[,1])=="character" | class(dataPlot[,1])=="factor") {
dataPlot$Code<-substr(dataPlot[,1],1,1)
variables<-as.character(unique(dataPlot[,1])) # a list of the unique (non-numeric) variables values in this df variables<-variables[sort.list(variables)] # sort alphabetically
variablesCode<-sort(variables)
# loop to get grades as a string
groupCode<-""
for (i in 1:length(variablesCode)){ # loop to bring it together as a groupCode
text<-variablesCode[i]
groupCode<-paste(groupCode,text,sep="") }
groupCode<<-groupCode
if(groupCode=="BESU"){xScheme<-"UBSE"}
if(groupCode=="BES") {xScheme<-"UBSE"}
if(groupCode=="ESU") {xScheme<-"USE"}
if(groupCode=="EFP") {xScheme<-"PassFailEx"}
if(groupCode=="FP") {xScheme<-"PassFail"}
if(groupCode=="P") {xScheme<-"PassFail"}
if(groupCode=="ES") {xScheme<-"UBSE"} # add a message to check right group
# Convert all abbreviated grades in data (e.g. "U","B","S","E") to full strings ("Unsatisfactory","Borderline","Satisfactory","Excellent")
maxNChar<-max(nchar(as.character(dataPlot[,1]))) # to find the longest character string in Grade column
if(xScheme=="UBSE" | xScheme=="USE" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="U"]<-"Unsatisfactory"}
if(xScheme=="UBSE" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="B"]<-"Borderline"}
if(xScheme=="UBSE" | xScheme=="USE" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="S"]<-"Satisfactory"}
if(xScheme=="UBSE" | xScheme=="USE" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="E"]<-"Excellent"}
#if(xScheme=="UBSE" | xScheme=="USE"){dataPlot[,3][dataPlot[,3]=="U"]<-"Unsatisfactory"}
#if(xScheme=="UBSE" ){dataPlot[,3][dataPlot[,3]=="B"]<-"Borderline"}
#if(xScheme=="UBSE" | xScheme=="USE"){dataPlot[,3][dataPlot[,3]=="S"]<-"Satisfactory"}
#if(xScheme=="UBSE" | xScheme=="USE"){dataPlot[,3][dataPlot[,3]=="E"]<-"Excellent"}
#if(xScheme=="PassFailEx" | xScheme=="PassFail"){dataPlot[,3][dataPlot[,3]=="P"]<-"Pass"}
#if(xScheme=="PassFailEx" | xScheme=="PassFail"){dataPlot[,3][dataPlot[,3]=="F"]<-"Fail"}
#if(xScheme=="PassFailEx" ){dataPlot[,3][dataPlot[,3]=="E"]<-"Excellent"}
if(xScheme=="PassFailEx" | xScheme=="PassFail" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="P"]<-"Pass"}
if(xScheme=="PassFailEx" | xScheme=="PassFail" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="F"]<-"Fail"}
if(xScheme=="PassFailEx" & maxNChar==1){dataPlot[,3][dataPlot[,3]=="E"]<-"Excellent"}
dataPlot$xAxis<-dataPlot[,3]
}
xScheme<<-xScheme
# need to build in error/warning messages with query if function is not sure (e.g. allocate to UBSE but ask of correct and if not to add #something 'Force.Scheme="USE")
if(xScheme=="UBSE"){dataPlot$xAxis<-factor(dataPlot$xAxis, levels=c("Unsatisfactory","Borderline","Satisfactory","Excellent"),ordered=TRUE )}
if(xScheme=="USE"){dataPlot$xAxis<-factor(dataPlot$xAxis, levels=c("Unsatisfactory","Satisfactory","Excellent"),ordered=TRUE)}
if(xScheme=="PassFailEx"){dataPlot$xAxis<-factor(dataPlot$xAxis, levels=c("Fail","Pass","Excellent"),ordered=TRUE)}
if(xScheme=="PassFail"){dataPlot$xAxis<-factor(dataPlot$xAxis, levels=c("Fail","Pass"),ordered=TRUE)}
if(xScheme=="Stage"){dataPlot$xAxis<-factor(dataPlot$xAxis)} # levels will be numerical ascending for whichever Stage groups are in the data
if(xScheme=="Assessor"){dataPlot$xAxis<-factor(dataPlot$xAxis)}
###
##### need to calculate the median values within the function to enable ordering by these
###
if(xScheme=="Assessor") {
oind<-order(as.numeric(by(dataPlot$yAxis,dataPlot$xAxis,median)))
dataPlot$xAxis<-ordered(dataPlot$xAxis,levels=levels(dataPlot$xAxis)[oind])
}
# dataPlot$xAxis<-Data.Example$Assessor.ID
# factor the numeric ID
#if(xScheme=="Assessor"){orderAssessors<- order(as.numeric(by(dataPlot$yAxis,dataPlot$xAxis,median)))} # define the order of assessors by median ascending
#if(xScheme=="Assessor"){dataPlot$xAxis<-dataPlot$xAxis,levels=c(orderAssessors),ordered=TRUE)}
#dataAssessors$Assessor <- ordered(dataAssessors$Assessor, levels=levels(dataAssessors$Assessor)[oind])
# Colours for each group
if(xScheme=="UBSE"){colFill<-c("red","orange","#117733","#332288")}
if(xScheme=="USE"){colFill<-c("red","#117733","#332288")}
if(xScheme=="PassFailEx"){colFill<-c("red","#117733","#332288")}
if(xScheme=="PassFail"){colFill<-c("red","#117733")}
if(xScheme=="Stage"){colFill<-"maroon"}
if(xScheme=="Assessor"){colFill<-"darkgrey"}
dataPlot<<-dataPlot
ggplot(dataPlot, aes(x=xAxis, y=yAxis, group=xAxis)) +
geom_boxplot(fill=colFill) +
expand_limits(y=c(0,maxScore)) +
ylab(ifelse(maxScore==100,"Score (%)","Score")) +
xlab(ifelse(xScheme=="Assessor",xScheme,ifelse(xScheme=="Stage",xScheme,"Grade"))) +
stat_summary(fun.y="mean", geom="point", shape=8, size=3.5, position=position_dodge(width=0.75), color="white") +
theme_psmd()
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
##
##
##
##
##
##
####
###
##
#
|
ef500fd11635dd56a5f292fa07656066e2d6d611
|
883a4a0c1eae84485e1d38e1635fcae6ecca1772
|
/nCompiler/tests/testthat/test-nCompile_nFunction.R
|
d04041ec0cf5589cc524fd6bc883aef10dd2abd2
|
[
"BSD-3-Clause"
] |
permissive
|
nimble-dev/nCompiler
|
6d3a64d55d1ee3df07775e156064bb9b3d2e7df2
|
392aabaf28806827c7aa7b0b47f535456878bd69
|
refs/heads/master
| 2022-10-28T13:58:45.873095
| 2022-10-05T20:14:58
| 2022-10-05T20:14:58
| 174,240,931
| 56
| 7
|
BSD-3-Clause
| 2022-05-07T00:25:21
| 2019-03-07T00:15:35
|
R
|
UTF-8
|
R
| false
| false
| 3,074
|
r
|
test-nCompile_nFunction.R
|
context("Testing nFunction compilation")
nc <- nClass(
Cpublic = list(
go = nFunction(
fun = function(x = 'numericVector') {
y <- x
for(i in 1:10) {
y[i] <- 2 * x[i]
}
return(y)
},
returnType = 'numericVector'
)
)
)
Cnc <- nCompile_nClass(nc)
Cnc$new()$go(1:10)
test_that("addScalars double",
{
addScalars <- nFunction(
fun = function(x = double(0),
y = double(0)) {
returnType(double(0))
ans <- x + y
return(ans)
}
)
test <- nCompile_nFunction(addScalars)
expect_equal(test(2, 3), 5)
})
test_that("addVectors double",
{
addVectors <- nFunction(
fun = function(x = double(1),
y = double(1)) {
returnType(double(1))
ans <- x + 1.1 ## 1 is mistaken for integer
return(ans)
}
)
test <- nCompile_nFunction(addVectors)
set.seed(1)
x <- rnorm(3)
y <- rnorm(3)
expect_equal(test(x, y), array(x + 1.1, dim = length(x)))
})
test_that("addVectors double with a reference argument",
{
addVectors <- nFunction(
fun = function(x,
y) {
returnType(double(1))
ans <- x + 1.1 ## 1 is mistaken for integer
return(ans)
},
argTypes = list(x = 'numericVector',
y = 'numericVector'),
refArgs = 'x'
)
test <- nCompile_nFunction(addVectors)
set.seed(1)
x <- rnorm(3)
y <- rnorm(3)
expect_equal(test(x, y), array(x + 1.1, dim = length(x)))
})
test_that("addArrays double",
{
addArrays <- nFunction(
fun = function(x = double(2),
y = double(2)) {
returnType(double(2))
ans <- x + 1.1 ## 1 is mistaken for integer
return(ans)
}
)
test <- nCompile_nFunction(addArrays)
x <- matrix(as.numeric(1:4), nrow = 2)
y <- matrix(as.numeric(2:5), nrow = 2)
expect_equal(test(x, y), x + 1.1)
})
test_that("add3D double",
{
library(nCompiler)
addArrays <- nFunction(
fun = function(x = double(3),
y = double(3)) {
returnType(double(3))
ans <- x + 1.1 ## 1 is mistaken for integer
return(ans)
}
)
test <- nCompile_nFunction(addArrays)
x <- array(as.numeric(1:8), dim = c(2,2,2))
y <- array(as.numeric(2:9), dim = c(2,2,2))
expect_equal(test(x, y), x + 1.1)
cat('Add tests of argument casting\n')
})
test_that("nullary function works",
{
library(nCompiler)
say1p1 <- nFunction(
fun = function() {
returnType(double())
ans <- 1.1
return(ans)
}
)
test <- nCompile_nFunction(say1p1)
expect_equal(test(), 1.1)
})
|
b33d7e314c86bda8af35e9c134f8d630f1df49d8
|
df40822e65bfcdb5996b068cc53964d6c752e567
|
/R/StoredProcedures.R
|
25d518d5b859403f7f3726f4ce67318c36ec1fdb
|
[] |
no_license
|
mfalbertsGMail/Solvas-Capital-R-Utility
|
6f420cd1d42d73b70465faf3a93d9d8b644998f3
|
c8c6079a8b00103938abc097d7e94a1edff9eb1e
|
refs/heads/master
| 2021-01-12T10:13:21.543777
| 2016-11-23T01:06:53
| 2016-11-23T01:06:53
| 76,387,933
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,790
|
r
|
StoredProcedures.R
|
# Low-level access to the database stored procedures. Not public - use
# the object model to access these functions. All functions that directly
# call any SPs should be at this level.
#
# Note: @keywords internal keeps the documentation from being published.
#
# Initializes the financial instrument records - must be done on scenarios
# that have not been run
#
# Takes a connection string (connection_string) and scenario id (fs_id) and
# loads the financial instruments on the server. No action will take place
# on a scenario that has already been run.
#
#' Internal Solvas|Capital Function
#' Load Property Values
#' @param connection_string - The string representing the connection string...
#' @param fs_id - The scenario id
#' @return A data frame containing the financial instrument data
#' @import RODBC
#' @export
#' @keywords internal
SPInstrumentPropertyLoad <- function(connection_string, fs_id) {
cn <- odbcDriverConnect(connection_string)
if (is.null(fs_id) == FALSE) {
sp <- paste("EXEC [app_r].[FI_Financial_Instrument_Property_load] @fs_id = ", fs_id)
sqlQuery(cn, sp, errors=TRUE)
}
odbcClose(cn)
}
#' Internal Solvas|Capital Function
#' Get financial instruments
#' @param connection_string The string representing the connection string...
#' @param fs_id The scenario ID
#' @param effective_date - The date to use for schedule data types
#' @param effective_period - The period to use for schedule data types (1=first period)
#' @return data frame containing the financial instrument data
#' @import RODBC
#' @export
#' @keywords internal
SPFIInstrumentGet <- function(connection_string, fs_id, effective_date, effective_period) {
cn <- odbcDriverConnect(connection_string)
# note: this will return zero rows if the scenario has not been run or fi_instruments_init_sp has not been called
sp <- paste("EXEC [app_r].[FI_Financial_Instrument_Effective_Scalar_get] @fs_id = ",
fs_id,
",@effective_scalar_date = ",ifelse(is.null(effective_date), "NULL", paste("'",effective_date,"'")),
",@effective_scalar_period = ", ifelse(is.null(effective_period), "NULL", effective_period),
",@match_LTE = 1")
data <- sqlQuery(cn, sp, errors=TRUE)
odbcClose(cn)
return(data)
}
#' Internal Solvas|Capital Function
#' gets Solvas|Capital assumptions
#' @param connection_string - the string representing the connection string...
#' @param fs_id The scenario ID
#' @param tm_desc - description/name of transformation (i.e. '(apply to all)'). the first
# transformation by sequence order will be used if NULL, if two or more transformations have the
# same description an error message is returned
#' @param use_dates - if true then matrix columns will be dates, else periods. default to false
#' @return data frame containing the economic factors
#' @import RODBC
#' @import reshape2
#' @export
#' @keywords internal
SPFSAssumptionsGet <- function(connection_string, fs_id, tm_desc, use_dates) {
cn <- odbcDriverConnect(connection_string)
# make this a SP when done testing
sp <- paste("EXEC [app_r].[FS_Assumptions_get] ",
"@fs_id = ", fs_id, ", ",
"@tm_desc = ", ifelse(is.null(tm_desc), "NULL", paste("'",tm_desc,"'"))
)
data <- sqlQuery(cn, sp, errors=TRUE)
# reshape so rather than rows of data it is by period in the column
if (use_dates == TRUE) {
data <- reshape2::dcast(data, property_code ~date, value.var = 'unified_value')
} else {
data <- reshape2::dcast(data, property_code ~period, value.var = 'unified_value')
}
rownames(data) <- data[,'property_code']
odbcClose(cn)
return(data)
}
|
05baee565676728dca4a57e78a6a45441c6984e8
|
d1a4917b7dca113817df475ed0a44525de77d994
|
/man/sidarthe.Rd
|
d68bb90242ecce8b7835e0af1d3ab068c2f5a3de
|
[
"MIT"
] |
permissive
|
shill1729/odeSolveR
|
8cdf673a7af96bc1cc081b7b66b2c02f7e15e6c0
|
183bc0ddbcd81c4ea3b7fd57c0677708db90c2fe
|
refs/heads/master
| 2023-03-27T12:42:04.861729
| 2021-03-24T20:16:33
| 2021-03-24T20:16:33
| 258,375,739
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 5,422
|
rd
|
sidarthe.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sidarthe.R
\name{sidarthe}
\alias{sidarthe}
\title{Euler scheme for the SIDARTHE model}
\usage{
sidarthe(
parameters,
initial_conditions,
t0 = 0,
tn = 1,
n = 1000,
verbose = TRUE
)
}
\arguments{
\item{parameters}{named list of parameters see details}
\item{initial_conditions}{named list of initial conditions, see details}
\item{t0}{initial time point}
\item{tn}{the terminal time point}
\item{n}{number of sub-intervals in time-grid}
\item{verbose}{whether to plot the populations over time and print parameter+reproductive ratio}
}
\value{
list consisting of (1) parameters, a data.frame containing the contact rates, etc and (2) sidarthe, a matrix whose columns consist of the
eight (fractions of) populations over time:
\itemize{
\item suspected
\item infected
\item diagnosed
\item ailing
\item recognized
\item threatened
\item healed
\item extinct}
and finally (3) the basic reproductive ratio as defined for this extended SIR model as a consequence of Proposition 2 in the original paper.
}
\description{
{A basic Euler scheme is used to numerically solve the ODE system of the novel SIDARTHE model.}
}
\details{
{The parameters must be a named list containing values
\itemize{
\item \eqn{\alpha}, \eqn{\beta}, \eqn{\gamma}, \eqn{\delta} "represent the transimission rate
(i.e. the probability of disease transmission in a singlecontact times the average number of contacts
per person) due to contacts between a Susceptible subject and an Infected, a Diagnosed, an Ailing,
a Recognised subject. Typically, \eqn{\alpha} is larger than \eqn{\gamma} (assuming that people tend to
avoid contacts with subjects showing symptoms, even though diagnosis has not been made yet), which in turn
is probably larger than \eqn{\beta} and \eqn{\delta} (assuming that subjects who have been diagnosed are
properly isolated). These parameters can be modified by social distancing policies (e.g., closing schools,
remote working, etc.). The risk of contagion due to Threatened subjects, treated in proper ICUs, is assumed negligible."
\item \eqn{\epsilon} and \eqn{\theta} "capture capture the probability rate of detection, relative
to asymptomatic and mildly symptomatic casesrespectively. These parameters, also modifiable,
reflect the level of attention on the disease and the numberof tests performed over the population. Note that
\eqn{\theta} is typically larger than \eqn{\epsilon}, since symptomatic individuals are more likely to get tested."
\item \eqn{\zeta} and \eqn{\eta} "denote the probability rate at which an infected subject,
respectively not aware and aware of being infected, develops clinically relevant symptoms, and
are probably comparable. These parameters are disease-dependent and hardly modifiable."
\item \eqn{\mu} and \eqn{\nu} "respectively denote the rate at which undetected and detected infected
subjects develop life-threatening symptoms, and are likely to be comparable if there is no known specific
treatment that is effective against the disease, otherwise \eqn{\mu} is likely to be larger.
These parameters can be reduced by means of improved therapies and acquisition of immunity against
the virus."
\item \eqn{\tau} "denotes the mortality rate (for infected subjects with life-threatening symptoms) and
can be reduced bymeans of improved therapies and treatments."
\item \eqn{\lambda, \kappa, \xi, \rho} and \eqn{\sigma} "denote the rate of recovery for the five
classes of infected subjects, and may differ significantly if an appropriate treatment for the
disease is known and adopted to diagnosed patients, while are probably comparable otherwise.
These parameters can be increased thanks to improved treatments and acquisition of immunity against the
virus."
}
These descriptions of the model parameters are directly taken from the 2020-03-21 paper "A SIDARTHE model of COVID-19 Epidemic in Italy"
by the COVID19 IRCCS San Matteo Pavia Task Force et al. to mitigate any misinterpretation of the input into the model.
(Note the named list must actually have the greek letter names written out, i.e. \code{alpha}, \code{beta},...)
Finally the list \code{initial_conditions} must contain the following, all as fractions of the total population
\itemize{
\item \code{s0} the initial level of susceptible individuals
\item \code{i0} the initial level of infected individuals
\item \code{d0} the initial level of diagnosed individuals
\item \code{a0} the initial level of ailing individuals
\item \code{r0} the initial level of recognized individuals
\item \code{thr0} the initial level of threatened individuals
\item \code{h0} the initial level of heal individuals
\item \code{e0} the initial level of extinct individuals}
It is best to specify all but \code{s0} and then set the initial susceptible fraction to 1 less the sum of the rest.
}
}
\references{
{The Euler scheme implemented by this function is for the model developed in the following paper. It is 8 coupled non-linear ODEs describing dynamics of sub-populations under a pandemic.
The descriptions within the novel paper were used to document the initial conditions and parameters of this model in this package.
\itemize{\item "A SIDARTHE Model of COVID-19 Epidemic in Italy" by the COVID19 IRCCS San Matteo Pavia Task Force et al. \href{https://arxiv.org/abs/2003.09861}{https://arxiv.org/abs/2003.09861}}}
}
|
480cd7f236349ad81207690cd5c482146a007011
|
6412622f5b2ba024096e04fc506135cb4f61695c
|
/Lectures/Lesson 04 Seasonal Models.R
|
1e44ff811b01bacfcd08612ede4830766c847cdc
|
[] |
no_license
|
PyRPy/tsa4_textbook
|
4de940ca2b93989c6e4706591447b238568ce010
|
e6b1e347c3d2334b112eca78af1f74a4e21b90ad
|
refs/heads/master
| 2021-06-08T06:09:30.262389
| 2021-05-13T21:05:49
| 2021-05-13T21:05:49
| 159,443,131
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,767
|
r
|
Lesson 04 Seasonal Models.R
|
# Lesson 4: Seasonal Models
# 4.1 Seasonal ARIMA models -----------------------------------------------
# Example 4-2: ARIMA(1,0,0) x (1,0,0)12
thepacf=ARMAacf (ar = c(.6,0,0,0,0,0,0,0,0,0,0,.5,-.30),lag.max=30,pacf=T)
plot (thepacf,type="h")
# 4.2 Identifying Seasonal Models and R Code ------------------------------
# R code for the Colorado River Analysis
library(astsa)
flow <- ts(scan("coloradoflow.dat"))
plot(flow, type="b")
# examined the ACF and PACF of the 12th differences (seasonal differencing)
diff12 <- diff(flow, 12)
acf2(diff12, 48)
# possible model
sarima(flow, 1,0,0,0,1,1,12)
# generate forecasts for the next 24 months
sarima.for(flow, 24, 1,0,0,0,1,1,12)
# command in R code directly
themodel = arima(flow, order=c(1,0,0), seasonal=list(order=c(0,1,1), period=12))
themodel
predict(themodel, n.ahead=24)
# plot the monthly average
flowm <- matrix(flow, ncol=12, byrow = TRUE)
col.means <- apply(flowm, 2, mean)
plot(col.means, type = "b", main = "Monthly flow means ",
xlab = "Month", ylab = "Mean")
# Example 4-4: Beer Production in Australia
## use data set ausbeer from fpp2 package for now
library(fpp2)
data("ausbeer")
plot(ausbeer)
beer <- window(ausbeer, start=1960, end=c(1975, 4))
diff4 <- diff(beer, 4)
plot(diff4)
diff1and4 <- diff(diff4, 1)
acf2(diff1and4)
# detrend by subtracting an estimated linear trend from each observation as follows
dtb <- residuals(lm (diff4~time(diff4)))
acf2(dtb)
# try the following models
sarima (dtb, 0,0,1,0,0,1,4)
sarima (dtb, 1,0,0,0,0,1,4)
sarima (dtb, 0,0,0,0,0,1,4)
sarima (dtb, 1,0,0,0,0,2,4)
# use auto.arima
library(forecast)
auto.arima(beer)
sarima(beer, 2,0,2, 0,1,1, 4)
## residuals variances not ideal
|
c3e9c3e17c9a7594cd350efe87ad1a69dd41acd3
|
551b9335dcc91791535095126beb86b4bd132a06
|
/man/imageplot_output.Rd
|
af99c10127ea230b00aa805de7f8fa4d99d46325
|
[
"MIT"
] |
permissive
|
dungates/ImagePlotting
|
214a8d4488327f8e0e6e16c85fd119277c641cf8
|
b8bf80a4a086e6938fa0c159147a9822a13d489c
|
refs/heads/master
| 2023-07-15T15:50:44.380292
| 2021-08-11T17:52:30
| 2021-08-11T17:52:30
| 325,050,470
| 1
| 2
|
NOASSERTION
| 2021-06-25T20:32:55
| 2020-12-28T15:41:32
|
R
|
UTF-8
|
R
| false
| true
| 513
|
rd
|
imageplot_output.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Functions.R
\name{imageplot_output}
\alias{imageplot_output}
\title{function that allows you to pass alpha to a GG plot that also encodes other things}
\usage{
imageplot_output(Q, X, Y, A)
}
\arguments{
\item{X}{is the X var}
\item{Y}{is the Y var}
\item{A}{is the alpha}
\item{D}{is where the data is}
}
\description{
This function is designed to simplify passing arguments into a ggplot with geom_image to produce an image plot
}
|
515be618d897d8cc54b3a47cb542a0293cc9afdf
|
91f211177a9fc2b20a2b808c6200e5a8dfaa21b1
|
/Options Pricing Code.R
|
2d244bb48455da556a554faa8bd71b46aac0ad79
|
[] |
no_license
|
SaifRehman11/Options-Pricing
|
8f63f3725886e5b4abbb13165357c2981bd56d93
|
d9f81b251e36e92dad773a60d3bb2f3f82df85ec
|
refs/heads/master
| 2022-11-04T02:53:26.322193
| 2020-06-18T23:54:43
| 2020-06-18T23:54:43
| 273,350,026
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 13,205
|
r
|
Options Pricing Code.R
|
setwd("E:/Google Drive/Saif/USC MBA/Statistics/Project")
data <- read.csv("option_train.csv")
str(data)
testing <- read.csv("option_test.csv")
summary(data)
summary(testing)
stddata <- scale(data$Value)
stddata[which(abs(stddata)>3)]
library(MASS)
cor(data)
plot(data)
boxplot(data$Value, xlab = "Value", main = "Training Value Boxplot")
boxplot(data$S, xlab = "S", main = "Training S Boxplot")
boxplot(data$K, xlab = "K", main = "Training K Boxplot")
boxplot(data$tau, xlab = "Tau", main = "Training tau Boxplot")
boxplot(data$r, xlab = "r", main = "Training r Boxplot")
boxplot(testing$S, xlab = "S", main = "Testing S Boxplot")
boxplot(testing$K, xlab = "K", main = "Testing K Boxplot")
boxplot(testing$tau, xlab = "Tau", main = "Testing tau Boxplot")
boxplot(testing$r, xlab = "r", main = "Testing r Boxplot")
library(car)
sum(is.na(data))
data2 <- data
data$BS <- as.numeric(data$BS)
data$BS <- data$BS -1
data$BS <- data$BS -1
data$BS <- data$BS * -1
data$diff <- data$S-data$K
set.seed(101) # Set Seed so that same sample can be reproduced in future also
hist(data$Value)
hist(data$S)
hist(data$K)
hist(data$tau)
hist(data$r)
hist(data$BS)
# Now Selecting 50% of data as sample from total 'n' rows of the data
sample <- sample.int(n = nrow(data), size = floor(.80*nrow(data)), replace = F)
train <- data[sample, ]
test <- data[-sample, ]
glm1 <- glm(BS ~ S + K + tau + r, family = binomial(link="logit"),data = data)
summary(glm1)
plot(glm1)
# Assessing Outliers
outlierTest(glm1) # Bonferonni p-value for most extreme obs
qqPlot(glm1, main="QQ Plot") #qq plot for studentized resid
leveragePlots(glm1) # leverage plots
# Influential Observations
# added variable plots
av.Plots(glm1)
# Cook's D plot
# identify D values > 4/(n-k-1)
cutoff <- 4/((nrow(data)-length(glm1$coefficients)-2))
plot(glm1, which=4, cook.levels=cutoff)
# Influence Plot
influencePlot(glm1, id.method="identify", main="Influence Plot", sub="Circle size is proportial to Cook's Distance" )
qqplot(glm1)
qqline(glm1)
pred = predict.glm(glm1, newdata=test, type = "response")
library(InformationValue)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misclass <- misClassError(test$BS, pred, threshold = 0.5)
1-misclass
fitted.results <- ifelse(pred > 0.6499,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
accuracy <- table(pred, test[,"BS"])
sum(diag(accuracy))/sum(accuracy)
accuracy
###Using Difference
glm2 <- glm(BS ~ diff + tau + r, family = binomial(link="logit"),data = train)
summary(glm2)
plot(glm2)
pred = predict.glm(glm2, newdata=test, type = "response")
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misclass <- misClassError(test$BS, pred, threshold = 0.5)
1-misclass
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
library(pROC)
roc_obj <- roc(test$BS, pred)
plot(roc_obj)
auc(roc_obj)
#
glm3 <- glm(BS ~ (diff + tau + r)^2, family = binomial(link="logit"),data = train)
summary(glm3)
fit <- step(glm3, direction = "both")
summary(fit)
pred = predict(fit, newdata=test, type = "response")
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misclass <- misClassError(test$BS, pred, threshold = 0.5)
1-misclass
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
##Using Naive Bayesian Filter
library(e1071)
# Naive_Bayes_Model=naiveBayes(BS ~ S + K + tau + r, data=train)
# #What does the model say? Print the model summary
# Naive_Bayes_Model
# summary(Naive_Bayes_Model)
#
# #Prediction on the dataset
# NB_Predictions=predict(Naive_Bayes_Model,train)
# #Confusion matrix to check accuracy
# table(NB_Predictions,train$BS)
#Decision Trees
library(rpart)
library(rpart.plot)
fit <- rpart(BS~K+S+tau+r, data = train, method = 'class')
fit
plot(fit)
text(fit)
rpart.plot(fit)
pred = predict(fit, train, type = 'class')
pred = as.numeric(pred)-1
optCutOff <- optimalCutoff(train$BS, pred)[1]
optCutOff
misClassError(train$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
fit <- rpart(BS~diff+tau+r, data = train, method = 'class')
fit
plot(fit)
text(fit)
rpart.plot(fit)
pred = predict(fit, train, type = 'class')
pred = as.numeric(pred)-1
optCutOff <- optimalCutoff(train$BS, pred)[1]
optCutOff
misClassError(train$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != train$BS)
print(paste('Accuracy',1-misClasificError))
#SVM
svm1 <- svm(BS ~ diff + tau + r, data = train)
summary(svm1)
# pred = predict(svm1, train)
# optCutOff <- optimalCutoff(train$BS, pred)[1]
# optCutOff
# misClassError(train$BS, pred, threshold = 0.5)
# fitted.results <- ifelse(pred > 0.5,1,0)
# misClasificError <- mean(fitted.results != train$BS)
# print(paste('Accuracy',1-misClasificError))
pred = predict(svm1, test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasifiedError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasifiedError))
svm1 <- svm(BS ~ K + S + tau + r, data = train)
summary(svm1)
# pred = predict(svm1, train)
# optCutOff <- optimalCutoff(train$BS, pred)[1]
# optCutOff
# misClassError(train$BS, pred, threshold = 0.5)
# fitted.results <- ifelse(pred > 0.5,1,0)
# misClasificError <- mean(fitted.results != train$BS)
# print(paste('Accuracy',1-misClasificError))
pred = predict(svm1, test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasifiedError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasifiedError))
predfinal <- predict(fit, validation)
fitted.results <- ifelse(predfinal > 0.5,1,0)
write.csv(x = fitted.results, "bspredictions4.csv")
svm1 <- svm(BS ~ (K + S + tau + r)^2, data = train)
summary(svm1)
pred = predict(svm1, test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasifiedError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasifiedError))
#
library(MASS)
fit <- lda(BS ~ diff + tau + r, data = train)
summary(fit)
pred = predict(fit, test)
pred <- as.numeric(pred$class)-1
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasifiedError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasifiedError))
#kNN
library(class)
fit <- knn(train = train, test = test, cl=train$BS)
summary(fit)
table(test$BS, fit)
misClasificError <- mean(fit != test$BS)
print(paste('Accuracy',1-misClasificError))
predfinal <- predict(fit, validation)
#RandomForest
library(randomForest)
fit <- randomForest(BS ~ K + S + tau + r, train, ntree=500)
summary(fit)
pred= predict(fit,train)
optCutOff <- optimalCutoff(train$BS, pred)[1]
optCutOff
misClassError(train$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != train$BS)
print(paste('Accuracy',1-misClasificError))
pred= predict(fit,test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
##predicting on final data
validation <- read.csv("option_test.csv")
validation$diff <- validation$S - validation$K
fit <- randomForest(BS ~ diff+ tau + r, train, ntree=8)
summary(fit)
plot(fit)
pred= predict(fit,test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
predfinal <- predict(fit, validation)
fitted.results <- ifelse(predfinal > 0.5,1,0)
write.csv(x = fitted.results, "bspredictions3.csv")
fit <- randomForest(BS ~ diff+ tau + r, train, ntree=6)
summary(fit)
plot(fit)
pred= predict(fit,test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
##nnet
library(nnet)
fit <- nnet(BS ~ diff + tau + r, train, size = 20)
pred= predict(fit,test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.5)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
##xgboost
library(xgboost)
traintest <- train[,c(4,5,7)]
trainlabel <- train$BS
testtest <- test[,c(4,5,7)]
testlabel <- test$BS
xgb_train <- xgb.DMatrix(data=as.matrix(traintest), label=trainlabel)
xgb_test <- xgb.DMatrix(data=as.matrix(testtest), label=testlabel)
#fit <- xgboost()
params <- list(booster = "gbtree", objective = "binary:logistic", eta=0.3, gamma=0, max_depth=6, min_child_weight=1, subsample=1, colsample_bytree=1)
xgbcv <- xgb.cv( params = params, data = xgb_train, nrounds = 100, nfold = 5, showsd = T, stratified = T, maximize = F)
min(xgbcv$test.error.mean)
xgb1 <- xgb.train (params = params, data = xgb_train, nrounds = 79, watchlist = list(val=xgb_test,train=xgb_train), maximize = F , eval_metric = "error")
pred <- predict (xgb1,xgb_test)
optCutOff <- optimalCutoff(test$BS, pred)[1]
optCutOff
misClassError(test$BS, pred, threshold = 0.469)
fitted.results <- ifelse(pred > 0.5,1,0)
misClasificError <- mean(fitted.results != test$BS)
print(paste('Accuracy',1-misClasificError))
summary(xgb1)
#xgb with caret
library(caret)
TrainControl <- trainControl( method = "repeatedcv", number = 10, repeats = 4)
fit<- train(as.factor(BS) ~ diff + tau + r, data = train, method = "xgbTree", trControl = TrainControl)
plot(fit)
summary(fit)
pred <- predict (fit,test)
pred = as.numeric(pred)-1
misClassError(test$BS, pred)
misClasificError <- mean(pred != test$BS)
print(paste('Accuracy',1-misClasificError))
#######Value Prediction
#GLM
glm1 <- glm(Value ~ S+K + tau + r,data = train)
summary(glm1)
plot(glm1)
# Assessing Outliers
outlierTest(glm1) # Bonferonni p-value for most extreme obs
qqPlot(glm1$residuals, main="QQ Plot") #qq plot for studentized resid
leveragePlots(glm1) # leverage plots
# Influential Observations
# added variable plots
av.Plots(glm1)
# Cook's D plot
# identify D values > 4/(n-k-1)
cutoff <- 4/((nrow(data)-length(glm1$coefficients)-2))
plot(glm1, which=4, cook.levels=cutoff)
# Influence Plot
influencePlot(glm1, id.method="identify", main="Influence Plot", sub="Circle size is proportial to Cook's Distance" )
pred = predict.glm(glm1, newdata=train)
summary(glm1)
library(forecast)
accuracy(pred, train$Value)
pred = predict.glm(glm1, newdata=test)
accuracy(pred, test$Value)
plot(pred)
plot(pred,test$Value)
#
glm1 <- glm(Value ~ diff + tau + r,data = train)
summary(glm1)
pred = predict.glm(glm1, newdata=train)
accuracy(pred, train$Value)
pred = predict.glm(glm1, newdata=test)
accuracy(pred, test$Value)
#
glm1 <- glm(Value ~ (diff + tau + r)^2,data = train)
summary(glm1)
fit <- step(glm1, direction = "both")
summary(fit)
pred = predict.glm(fit, newdata=train)
accuracy(pred, train$Value)
pred = predict.glm(fit, newdata=test)
accuracy(pred, test$Value)
plot(fit)
#SVM
svm1 <- svm(Value ~ diff + tau + r, data = train)
summary(svm1)
pred = predict(svm1, train)
accuracy(pred, train$Value)
pred = predict(svm1, test)
accuracy(pred, test$Value)
plot(svm1$residuals)
#randomForest
fit <- randomForest(Value ~ diff + tau + r, train, ntree=200)
summary(fit)
pred= predict(fit,train)
accuracy(pred, train$Value)
pred = predict(fit, test)
accuracy(pred, test$Value)
plot(fit)
#xgb with caret
TrainControl <- trainControl( method = "repeatedcv", number = 10, repeats = 4)
fit<- train(Value ~ diff + tau + r, data = train, method = "xgbLinear", trControl = TrainControl,verbose = FALSE)
plot(fit)
summary(fit)
pred <- predict (fit,train)
accuracy(pred, train$Value)
pred <- predict (fit,test)
accuracy(pred, test$Value)
##predicting on final data
validation <- read.csv("option_test.csv")
validation$diff <- validation$S - validation$K
predfinal <- predict (fit,validation)
write.csv(x = predfinal, "valuepredictions.csv")
|
c814525408855c4b972eb8aee539795dbd3a43b2
|
c28b23b0a89094f2024b796879b60a364168aacf
|
/quiz2.R
|
b21c30939b6ce72be465e57f33fe779f30f5f5e0
|
[] |
no_license
|
ofirsh/BiostatisticsBootCamp2
|
b60ae32d949d5d3d03635c71a83dc3ce2f2726c8
|
5b7ac11390e64eed6792c7258fd4110f08fde384
|
refs/heads/master
| 2021-01-10T19:57:56.198814
| 2015-02-08T04:24:39
| 2015-02-08T04:24:39
| 30,019,487
| 4
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,511
|
r
|
quiz2.R
|
# Solution by Ofir Shalev, February 2015
----------------------------------------
# Question 1
# ----------
#
# What is the delta method asymptotic standard error of sqrt(phat) where phat is X/n where
# X∼Binomial(n,p)?
# Answer 1 (pseudo code)
# ----------------------
# pseudo algorithm, just to show the method - not running code!
# SE.theta = sqrt( p*(1-p) / n )
# Asymptotic standard error of f(theta) can be estimated with f'(theta) * SE.theta (lecture 6, page 4)
# f(x) = sqrt(x)
# f'(x) = 0.5 * (1 / sqrt(x) )
# standard error: sqrt( (1-p)/(4*n) )
# Question 2
# ----------
#
#
# You are a bookie taking $1 bets on the NFL Ravens game.
# The odds you give betters determines their payout.
# If you give 4 to 1 odds against the Ravens winning, then if a person bets on the Ravens winning and they win,
# you owe them their original dollar, plus an additional $4 (a total of $5).
# If a person bets on the Ravens losing and they lose, then you owe them their original dollar back,
# plus $0.25 (a total of $1.25).
#
# Suppose you collect a > 0 one dollar bets on the Ravens winning and b > 0 one dollar bets on the Ravens losing.
# What should you set the odds so that, regardless of the outcome of the game, you neither win nor lose money?
# Note, in this case, the betters place their bets and learn the odds later.
# Note also, the odds are something that you set in this case, not a direct measure of probability or randomness.
# Question 3
# ----------
#
#
# In a randomly sampled survey of self-reported stress levels from two occupations, the following data were obtained
# High Stress Low Stress
# Professor 70
# Lion Tamer 15
#
# What is the P-value for a Z score test of equality of the proportions of high stress?
# (Note the notation 1e-5, for example, is 1×10−5).
#
# 4e-15
# 1e-14
# 1e-5
# 1e-3
X <- 70
n1 <- 100
Y <- 15
n2 <- 100
p1 <- X / n1
p2 <- Y / n2
# difference base (lecture 4, pp 11)
# ----------------------------------
p.hat <- (X+Y)/(n1+n2)
# [1] 0.425
test.statistics.null <- (p1-p2)/ ( sqrt( p.hat * ( 1 - p.hat ) * ( 1 / n1 + 1 / n2 ) ) )
# [1] 7.867184
# Two sided test
2 * pnorm(test.statistics.null, lower.tail = FALSE)
# [1] 3.627132e-15
# ratio base (just to compare to the diff base)
# ---------------------------------------------
RR <- p1 / p2
RR.log <- log(RR)
# [1] 1.540445
Standard.Error.Log.RR <- sqrt( ((1-p1)/(p1*n1)) + ((1-p2)/(p2*n2)) )
# [1] 0.2468854
# 2 * pnorm(0, mean = RR.log, sd = Standard.Error.Log.RR, lower.tail = TRUE )
z.1.minus.half.alpha <- RR.log / Standard.Error.Log.RR
# [1] 6.239516
alpha <- 1 * pnorm(-z.1.minus.half.alpha)
# [1] 2.194641e-10
# Question 4
# ----------
#
#
# Consider the following data recording case status relative to an environmental exposure
# Case Control
# Exposed 45 21
# Unexposed 15 52
#
# What would be the estimated asymptotic standard error for the log relative risk for this data?
# Consider case status as the outcome. That is, we're interested in evaluating the ratio of the proportion of
# cases comparing exposed to unexposed groups.
#
# Around 0.05
# Around 1.25
# Around 0.25
# Around 1.05
n1 <- 45+21
p1 <- 45/n1
n2 <- 15+52
p2 <- 15/n2
RR <- p1 / p2
RR.log <- log(RR)
Standard.Error.Log.RR <- sqrt( ((1-p1)/(p1*n1)) + ((1-p2)/(p2*n2)) )
# 0.2425119
Standard.Error.RR <- exp(Standard.Error.Log.RR)
# [1] 1.274446
# Question 5
# ----------
#
# If x1∼Binomial(n1,p1) and x2∼Binomial(n2,p2) and independent Beta(2,2) priors are placed on p1 and p2,
# what is the posterior mean for p1−p2?
# Question 6
# ----------
#
# Researchers conducted a blind taste test of Coke versus Pepsi.
# Each of four people was asked which of two blinded drinks given in random order that they preferred.
# The data was such that 3 of the 4 people chose Coke.
# Assuming that this sample is representative, report a P-value for a test of the hypothesis that
# Coke is preferred to Pepsi using a **two sided** exact test.
#
# Around 0.6
# Around 0.5
# Around 0.4
# Around 0.3
# null - Coke is the same like Pepsi, so p = 0.5 (should be no difference)
binom.test(x=3, n = 4, p = 0.5, alternative = c("two.sided") )
# Exact binomial test
#
# data: 3 and 4
# number of successes = 3, number of trials = 4, p-value = 0.625
# alternative hypothesis: true probability of success is not equal to 0.5
# 95 percent confidence interval:
# 0.1941204 0.9936905
# sample estimates:
# probability of success
# 0.75
|
3cf3bb55f7d90d2bc50086d13097c2c85ee0eb57
|
f67d1d9e539d11d907423710ddc49095b9845891
|
/R/accessMSigDB.R
|
e532e1ffc87a63db057ac6a51bd4751e3c1a7050
|
[
"CC-BY-4.0"
] |
permissive
|
bhuvad/msigdb
|
9ef5b2692474b395ef02a0e935b3e618563c505c
|
a33991bcb143de33dd7303164a16755cdd0851c7
|
refs/heads/main
| 2023-07-04T09:11:01.269999
| 2021-08-12T02:19:49
| 2021-08-12T02:19:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,895
|
r
|
accessMSigDB.R
|
#' Retrieve MSigDB data hosted on the hub
#'
#' Download molecular signatures database (MSigDB) hosted on the ExperimentHub
#' or retrieve pre-downloaded version from cache. This package currently hosts
#' versions greater than 7.2 for human and mouse with both symbol and Entrez
#' identifiers.
#'
#' @param org a character, representing the organism whose signature database
#' needs to be retrieved ("hs" for human and "mm" for mouse).
#' @param id a character, representing the ID type to use ("SYM" for gene
#' symbols and "EZID" for Entrez IDs).
#' @param version a character, stating the version of MSigDB to be retrieved
#' (should be >= 7.2). See `getMsigdbVersions()`.
#'
#' @return a GeneSetCollection, containing GeneSet objects from the specified
#' version of the molecular signatures database (MSigDB).
#' @export
#'
#' @examples
#' gsc = getMsigdb('hs', 'SYM')
#'
getMsigdb <- function(org = c('hs', 'mm'), id = c('SYM', 'EZID'), version = getMsigdbVersions()) {
org = match.arg(org)
id = match.arg(id)
version = match.arg(version)
checkMsigdbVersion(version)
#create object name
obj_name = paste0('msigdb.v', version, '.', org, '.', id)
gsc = getMSigdbObject(obj_name)
return(gsc)
}
getMsigdbIDF <- function(org = c('hs', 'mm'), version = getMsigdbVersions()) {
org = match.arg(org)
version = match.arg(version)
checkMsigdbVersion(version)
#create object name
obj_name = paste0('msigdb.v', version, '.', org, '.idf')
idf = getMSigdbObject(obj_name)
return(idf)
}
getMSigdbObject <- function(obj_name) {
#load object
eh = ExperimentHub::ExperimentHub()
info = AnnotationHub::mcols(AnnotationHub::query(eh, 'msigdb'))
id = rownames(info)[info$title %in% obj_name]
if (length(id) != 1)
stop('Data not found')
return(suppressWarnings(eh[[id]]))
}
#' Subset collections and sub-collections of MSigDB
#'
#' The molecular signatures database (MSigDB) is composed of collections and
#' sub-collection. Many analyses (e.g. gene-set enrichment using limma::fry) are
#' best carried out within specific collections rather than across the entire
#' database of signatures. This function allows subsetting of MSigDB data
#' objects within this package using collection and sub-collection types.
#'
#' @param collection a character, stating the collection(s) to be retrieved. The
#' collection(s) must be one from the [listCollections()] function.
#' @param subcollection a character, stating the sub-collection(s) to be
#' retrieved. The sub-collection(s) must be one from the
#' [listSubCollections()] function. If NULL, all sub-collections are
#' retrieved.
#'
#' @inheritParams getMsigdb
#'
#' @return a GeneSetCollection object, containing gene sets belonging to the
#' queries collection and/or sub-collection.
#' @export
#'
#' @examples
#' gsc = getMsigdb('hs', 'SYM')
#' subsetCollection(gsc, collection = "h")
#'
subsetCollection <- function(gsc, collection, subcollection = NULL) {
stopifnot(length(gsc) > 0)
stopifnot(collection %in% listCollections(gsc))
stopifnot(is.null(subcollection) | subcollection %in% listSubCollections(gsc))
if (is.null(subcollection))
subcollection = c(listSubCollections(gsc), NA)
#filter collection & sub-collection
ctype = lapply(gsc, GSEABase::collectionType)
gsc = gsc[sapply(ctype, GSEABase::bcCategory) %in% collection &
sapply(ctype, GSEABase::bcSubCategory) %in% subcollection]
return(gsc)
}
#' List all collection types within a MSigDB gene set collection
#'
#' This function lists all the collection types present in a MSigDB gene set
#' collection. Descriptions of collections can be found at the MSigDB website.
#'
#' @inheritParams getMsigdb
#'
#' @return a character vector, containing character codes for all collections
#' present in the GeneSetCollection object.
#' @export
#'
#' @examples
#' gsc = getMsigdb('hs', 'SYM')
#' listCollections(gsc)
#'
listCollections <- function(gsc) {
cat = unique(sapply(lapply(gsc, GSEABase::collectionType), GSEABase::bcCategory))
cat = as.character(stats::na.omit(cat))
return(cat)
}
#' List all sub-collection types within a MSigDB gene set collection
#'
#' This function lists all the sub-collection types present in a MSigDB gene set
#' collection. Descriptions of sub-collections can be found at the MSigDB
#' website.
#'
#' @inheritParams getMsigdb
#'
#' @return a character vector, containing character codes for all
#' sub-collections present in the GeneSetCollection object.
#' @export
#'
#' @examples
#' gsc = getMsigdb('hs', 'SYM')
#' listSubCollections(gsc)
#'
listSubCollections <- function(gsc) {
subcat = unique(sapply(lapply(gsc, GSEABase::collectionType), GSEABase::bcSubCategory))
subcat = as.character(stats::na.omit(subcat))
return(subcat)
}
checkMsigdbVersion <- function(version) {
stopifnot(version %in% getMsigdbVersions())
}
|
de682b19e089c3a5abcc5ae4fd25922f3026b9e1
|
ef55cbf38be57a866e520e2d13ad85df5f32e9a3
|
/server.R
|
c13ddfa749b612cb8c67892eacb29bad749deddd
|
[] |
no_license
|
Chihengwang/RShinyApp
|
85f6c191d49453f863fb72134e87253a67df359e
|
c6401de03419e7cf33047dff86b2e121887ac374
|
refs/heads/master
| 2021-08-24T13:19:45.076849
| 2017-11-21T07:24:53
| 2017-11-21T07:24:53
| 111,513,833
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,935
|
r
|
server.R
|
#===========================================================================
# Library
#===========================================================================
library(shiny)
library(dplyr)
library(data.table)
library(RCurl)
library(rjson)
#===========================================================================
# Server
#===========================================================================
function(input, output) {
#==== Get UI.R's input ====
UI_input <- reactive({ v_1 <- input$PassengerClass
v_2 <- input$Gender
v_3 <- as.character(input$Age)
return(list( v_1,v_2,v_3 ))
})
#==== Output : Prediction ====
output$result_plot <- renderImage({
#---- Connect to Azure ML workspace ----
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
# Accept SSL certificates issued by public Certificate Authorities
h = basicTextGatherer()
hdr = basicHeaderGatherer()
input_data = UI_input()
#---- Put input_data to Azure ML workspace ----
req = list(
Inputs = list(
"input1" = list(
"ColumnNames" = list("Pclass", "Sex", "Age"),
"Values" = list( input_data )
#Example: input_data = list("3", "male", "50", "0", "0", "0", "A")
)
),
GlobalParameters = setNames(fromJSON('{}'), character(0))
)
#---- Web service : API key ----
body = enc2utf8(toJSON(req))
api_key = "htGVAkrhVI9OcqgpkJY14Nw0EBX0HCNSt+tUVnf+OLoZfHdgrjdNQrV5SiYzP3AP3IsHY8Q41mCiaQgy71XheQ=="
authz_hdr = paste('Bearer', api_key, sep=' ')
h$reset()
curlPerform(url = "https://ussouthcentral.services.azureml.net/workspaces/ae5e6b1aa49847228498327c4960d383/services/976c45d08c57424db5b2ab78d466d9a0/execute?api-version=2.0&details=true",
httpheader=c('Content-Type' = "application/json", 'Authorization' = authz_hdr),
postfields=body,
writefunction = h$update,
headerfunction = hdr$update,
verbose = TRUE
)
#---- Get Result ----
result = h$value()
result= fromJSON(result)
#================Check http status is 200=====================
httpStatus = headers["status"]
if (httpStatus >= 400)
{
print(paste("The request failed with status code:", httpStatus, sep=" "))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(headers)
}
if (as.numeric(result$Results$output1$value$Values)==1) {
return( list(
src = "www/survived.png",
height = 480, width = 700,
alt = "Survived"
))
}else if (as.numeric(result$Results$output1$value$Values)==0) {
return(list(
src = "www/deceased.png",
height = 480, width = 700,
alt = "Deceased"
))
}
}, deleteFile = FALSE)
}
|
8a485361f45a3b83212362cdf261e57b7def4423
|
583143369a62d0af35cba7dcdbab7094b2a63b57
|
/man/hello.Rd
|
feb1710de964d9d81640c492671a672e7df25ffd
|
[] |
no_license
|
weekendwarri0r/HowToMakeRProject
|
5b2242701baa808cbd1e0bc532fd070f189c51aa
|
bc0853b738c90e496f2bf9f4f63d9fbaba31ba93
|
refs/heads/master
| 2021-07-24T14:18:04.812882
| 2017-11-04T09:15:17
| 2017-11-04T09:15:17
| 109,371,566
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 324
|
rd
|
hello.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hello.R
\name{hello}
\alias{hello}
\title{Say "Hello" to arg}
\usage{
hello(name)
}
\arguments{
\item{whom}{the function says "Hello" to}
}
\value{
chr
}
\description{
Say "Hello" to arg
}
\examples{
\dontrun{
hello("Bob")
hello("My friend")
}
}
|
f4ecf6b179341f5a4458719da9067e0bab8ddcdf
|
93933cc91cea975577d5a693fe047bc1939e88ec
|
/server.R
|
2056ba07ce609866e5f5b05c6e6e2623361b647a
|
[] |
no_license
|
Gayathriramanathan13/EPA-SO2-Emissions-Visualization-using-R-Shiny
|
123e6be2358d6126ab1f2bbbcca29c38b5ca8e35
|
c8c71f4684b743beabca3d07369d9463f92aabb3
|
refs/heads/master
| 2021-01-18T22:53:50.758025
| 2017-04-03T14:10:37
| 2017-04-03T14:10:37
| 87,080,365
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,679
|
r
|
server.R
|
library(shiny)
library(shinydashboard)
library(dplyr)
library(tidyr)
library(ggplot2)
library(googleVis)
library(xlsx)
library(plotly)
#Start of Server side code
shinyServer(
function(input, output, session) {
output$stateEmission<-renderPlotly({
state.years.so2.tdy$hover <- with(state.years.so2.tdy, paste("State",State, '<br>',
"So2 Emissions in Tons",
Emission))
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
data <- reactive({
# filter data according to user input
plotdata <- state.years.so2.tdy %>%
as.data.frame() %>%
filter(
Year %in% input$radio
)
scalecalc <- plotdata %>%
group_by(`Year`) %>%
summarize(value = sum(Emission))
scalemax <- max(scalecalc$value)
scalesteps <- round(scalemax/5, digits = -1)
list(plotdata = plotdata,
scalemax = scalemax,
scalesteps = scalesteps
)
})
plot_geo(data()$plotdata, locationmode = 'USA-states') %>%
add_trace(
z = ~Emission,key=~State, text = ~hover, locations = ~State,
color = ~Emission, colors = 'Purples'
) %>%
colorbar(title = "So2 Emissions in Tons") %>%
layout(
title = 'State wise S02 Emission by year<br>(Hover for emission value in tons)',
geo = g
)
})
output$stateEmission1<-renderPlotly({
data1 <- reactive({
# filter data according to user input
plotdata <- state.years.so2.tdy %>%
as.data.frame() %>%
filter(
State %in% input$stateselect
)
scalecalc <- plotdata %>%
group_by(`State`) %>%
summarize(value = sum(`Emission`))
scalemax <- max(scalecalc$value)
scalesteps <- round(scalemax/5, digits = -1)
list(plotdata = plotdata,
scalemax = scalemax,
scalesteps = scalesteps
)
})
ggplot(data = data1()$plotdata,
aes(x=`State`, y=Emission,
fill=factor(`Year`,
levels = c("1990","2000","2005","2014")))) +
geom_bar(position = "dodge", stat = "identity") + ylab("Emission") +
xlab("State") + theme(legend.position="bottom"
,plot.title = element_text(size=15, face="bold")) +
labs(fill = "Status")
})
})
|
c49946fb1b4732b0830bbd5f976cf03348b400ec
|
1ff8cc01489c730dd6cd0750f1018e29e02fc493
|
/man/read_eseal_meta.Rd
|
026456a3ad88578f9c1e01e4bd9b9f1f237fd6e2
|
[
"MIT"
] |
permissive
|
abfleishman/esealUltrasounds
|
ff7fd9e2da96428934f3dae2d0fe346255ff2303
|
e0baa6fbd6b258d49482d96f2c0eb723c435b3b7
|
refs/heads/master
| 2020-04-27T15:38:39.161240
| 2019-03-22T06:12:35
| 2019-03-22T06:12:35
| 174,454,088
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 546
|
rd
|
read_eseal_meta.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/read_eseal_meta.R
\name{read_eseal_meta}
\alias{read_eseal_meta}
\title{Read Ultra Sound Metadata}
\usage{
read_eseal_meta(image_dir)
}
\arguments{
\item{image_dir}{path to a Session_* directory}
}
\value{
a data frame with ultrasound metadata
}
\description{
Read in a selection of metadata fields from a ultrasound Session_* folder
including image dimentions, y resolution (for converting to cm, image_dir, image_file,
imagename, givenname, familyname, createtime
}
|
2fdd97e60b6c44b1b5c1970831e70f522d49c617
|
785955fd58c7c8cfd20d60c0e3d2f9a787d95bc0
|
/install_dga.r
|
be5548d70c9f2a37df16b083f98c74c6abb5a9d8
|
[] |
no_license
|
mienkofax/research-base
|
cba6ba3e813fc24ef69495b6dcf7bc9810de4ab4
|
5319c87160f0cf6d49e71889403923ab8209f751
|
refs/heads/master
| 2023-02-10T17:23:31.867674
| 2021-01-15T07:48:13
| 2021-01-15T07:48:13
| 324,749,272
| 0
| 0
| null | 2020-12-27T12:23:57
| 2020-12-27T11:43:28
| null |
UTF-8
|
R
| false
| false
| 277
|
r
|
install_dga.r
|
install.packages("devtools", dependencies = TRUE, lib = "/usr/lib/R/site-library")
install.packages("randomForest", dependencies = TRUE, lib = "/usr/lib/R/site-library")
library(devtools)
devtools::install_github("jayjacobs/dga", lib = "/usr/lib/R/site-library", force=TRUE)
|
c6f6eec68a61660ea3affb818cc891604c29a29e
|
9110e4952edfbb758826c2f2d05751247181c8ac
|
/Codigo R/ordenarCartas.R
|
cffc70c75f2f531cc8dcf4b6d5586a11e6d54cba
|
[] |
no_license
|
Aokaen/Poker_Simu
|
db7b0665d0b3709e6a0e276729ad18ca854dd460
|
6c3c6cc3ed66d6cb47312dc9b91b6ebe3afe2880
|
refs/heads/master
| 2022-11-09T13:37:18.903883
| 2020-06-25T23:58:58
| 2020-06-25T23:58:58
| 216,742,645
| 0
| 0
| null | 2020-06-24T15:00:30
| 2019-10-22T06:48:15
|
R
|
WINDOWS-1250
|
R
| false
| false
| 394
|
r
|
ordenarCartas.R
|
#funcion para juntar y ordenar las cartas de mano y mesa en una única jugada
ordenarCartas<-function(Mano,Mesa)
{
jugada<-rbind(Mano,Mesa)
tamano<-nrow(jugada)
a<-tamano-1
b<-tamano
for(i in 1:a)
{
for(j in i:b)
{
ni<-as.numeric(jugada[i,1])
nj<-as.numeric(jugada[j,1])
if(ni<nj)
{
aux<-jugada[i,]
jugada[i,]<-jugada[j,]
jugada[j,]<-aux
}
}
}
return(jugada)
}
|
6ef233d2f366c4b1918cf4abc2568bf220dc6928
|
2dfa786120788b2faaa655928ac94b3f8d3c78c1
|
/Bayesian Statistics/Linear_Regression_Quiz7A.R
|
805946143961c7c1e78ab16aa8a26d3debefd5cb
|
[] |
no_license
|
heihei2015/ai
|
cdf7cb8fa91cbe9abb6996457aabd192a3bfc86e
|
d5885b1b8edf701957a84574ac9c5e9b899efdf8
|
refs/heads/master
| 2022-12-04T20:37:53.678364
| 2020-07-29T11:05:12
| 2020-07-29T11:05:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,864
|
r
|
Linear_Regression_Quiz7A.R
|
library("car") # load the 'car' package
data("Anscombe") # load the data set
?Anscombe # read a description of the data
head(Anscombe) # look at the first few lines of the data
pairs(Anscombe) # scatter plots for each pair of variables
#linear model non-informative
lmod = lm( Anscombe$education ~ income + young + urban, data = Anscombe )
plot(lmod)
resid(lmod)
plot(resid(lmod))
qqnorm(y = resid(lmod))
str(lmod)
summary(lmod)
##coefficients : Named num [1:4] -286.8388 0.0807 0.8173 -0.1058
# Bayesian Model
library("rjags")
mod_string = " model {
for (i in 1:length(education)) {
education[i] ~ dnorm(mu[i], prec)
mu[i] = b0 + b[1]*income[i] + b[2]*young[i] + b[3]*urban[i]
}
b0 ~ dnorm(0.0, 1.0/1.0e6)
for (i in 1:3) {
b[i] ~ dnorm(0.0, 1.0/1.0e6)
}
prec ~ dgamma(1.0/2.0, 1.0*1500.0/2.0)
## Initial guess of variance based on overall
## variance of education variable. Uses low prior
## effective sample size. Technically, this is not
## a true 'prior', but it is not very informative.
sig2 = 1.0 / prec
sig = sqrt(sig2)
} "
data_jags = as.list(Anscombe)
inits = function(){
init = list("b0"=0.0, "b"= rnorm(n = 3, mean = 0, sd = 1.0e6), "prec"= rgamma(n = 1, shape = 1.0, rate = 1.0))
}
lmod1 = jags.model(textConnection(mod_string),data = data_jags,n.chains = 3, inits = inits)
update(lmod1, n.iter = 1000)
params = c("b0","b","sig")
lmod1_sim = coda.samples(lmod1, variable.names =params, n.iter = 1e5 )
plot(lmod1_sim )
#check gelman rubin diag
gelman.diag(lmod1_sim)
# values above 1.0 means converged
# check autocorrelation
autocorr.diag(lmod1_sim)
autocorr.plot(lmod1_sim, lag.max = 1000)
# posterior means
summary(lmod1_sim)
# coefficients : -284.1802 0.0805 0.8110 -0.1057
# from lm
##coefficients : -286.8388 0.0807 0.8173 -0.1058
|
ac26d0a350ceb0aee76c8653402fb25239c63404
|
c1213fbeb2b3a509c370630a05738030edf1b4c2
|
/R/max_rowlength.R
|
e1a1e71ee46437e1035edcf8d6310ded47c9b7a1
|
[
"MIT"
] |
permissive
|
moshejasper/lampshade
|
79d31cd26c9ed4790f342a89ba4595518aa2efab
|
96c4becb90f093b39d633ce4c94245ab143372b9
|
refs/heads/main
| 2023-08-12T23:00:49.774854
| 2021-10-04T12:27:06
| 2021-10-04T12:27:06
| 413,237,471
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 294
|
r
|
max_rowlength.R
|
#' Max rowlength
#'
#' @param n Number of bases in DNA sequence
#'
#' @return Returns integer number of bases in a DNA row (currently under A5 page assumptions)
#' @export
#'
#' @examples
#' max_rowlength(100)
max_rowlength <- function(n){
rnum <- sqrt(n / 12.5) * 12.5
return(rnum %/% 1)
}
|
b9538e74427059c5863fb9b2041342d5897817ad
|
e2c4df2516f7a5743bfd2491f30d5f1150ef691c
|
/GetPValue.R
|
cd9bdbd7767e786fc12f459e6a6474ea220064b6
|
[] |
no_license
|
LaurenSamuels/BOOM
|
4be62bf0109dbb3966d1ac319d08e28efa2f295a
|
c418a15017a6a53197584269727ddbe5c5c2a82d
|
refs/heads/master
| 2021-01-17T06:07:49.092508
| 2016-11-14T15:05:11
| 2016-11-14T15:05:11
| 54,785,430
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 97
|
r
|
GetPValue.R
|
GetPValue <- function(TE, SE){
zval <- abs(TE / SE)
2 * pnorm(zval, lower.tail= FALSE)
}
|
c3832d9271d386545e1b647a88db274c0d66632d
|
5a411c9d7b3edd84ef34b94eede3ce85fbc7909c
|
/man/HRM.Rd
|
f36693c14a52ee45fd2bec2794c49b9436f56a07
|
[] |
no_license
|
happma/HRM
|
e10d039c178ce396a42d6b90e87ea4e3c7a48dec
|
69b77d40431cd70763acab54aa813268a394e94d
|
refs/heads/master
| 2020-03-12T02:42:19.292507
| 2018-08-10T11:15:39
| 2018-08-10T11:15:39
| 100,510,794
| 0
| 0
| null | 2018-02-01T23:12:24
| 2017-08-16T16:34:50
|
R
|
UTF-8
|
R
| false
| false
| 1,443
|
rd
|
HRM.Rd
|
\name{HRM-package}
\alias{HRM}
\docType{package}
\title{
Inference on low- and high-dimensional multi-group reapeted-measures designs with unequal covariance matrices.
}
\description{
Tests for main and simple treatment effects, time effects, as well as treatment by time interactions in possibly high-dimensional multi-group repeated measures designs. The groups are allowed to have different variance-covariance matrices but the observations must follow a multivariate normal distribution.
}
\details{
\tabular{ll}{
Package: \tab HRM\cr
Type: \tab Package\cr
Version: \tab 0.9.4\cr
Date: \tab 2018-07-08\cr
License: \tab GPL-2 | GPL-3 \cr
}
}
\author{
Maintainer: martin.happ@aon.at
}
\references{
Happ, M., Harrar, S. W. and Bathke, A. C. (2016), Inference for low- and high-dimensional multigroup repeated measures designs with unequal covariance matrices. Biom. J., 58: 810-830. doi: 10.1002/bimj.201500064
Happ, M., Harrar, S. W. and Bathke, A. C. (2017), High-dimensional Repeated Measures. Journal of Statistical Theory and Practice. doi: 10.1080/15598608.2017.1307792
Staffen, W., Strobl, N., Zauner, H., Hoeller, Y., Dobesberger, J. and Trinka, E. (2014). Combining SPECT and EEG analysis for assessment of disorders with amnestic symptoms to enhance accuracy in early diagnostics. Poster A19 Presented at the 11th Annual Meeting of the Austrian Society of Neurology. 26th-29th March 2014, Salzburg, Austria.
}
\keyword{ package }
|
566796477bac9a49c27e412a93cab9c79c2a5fdb
|
afdde8a124424dbc1c66112834be4723a3984406
|
/R/additional_analysis/cox.R
|
bca59e964e2f16f5d42bd65dfc290831d289cee4
|
[] |
no_license
|
nnh/NHOH-R-miniCHP
|
70fa4baa33db7bad1fd5e83e0a54147f6c13f5eb
|
baf796d1f1e675994815dc038fc553bd07db20e9
|
refs/heads/master
| 2020-04-19T09:20:54.569562
| 2019-05-17T01:23:03
| 2019-05-17T01:23:03
| 168,107,576
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,896
|
r
|
cox.R
|
# cox.R
# Created date: 2019/3/26
# Author: mariko ohtsuka
#' @title
#' round2
#' @description
#' Customize round function
#' Reference URL
#' r - Round up from .5 - Stack Overflow
#' https://stackoverflow.com/questions/12688717/round-up-from-5
#' @param
#' x : Number to be rounded
#' digits : Number of decimal places
#' @return
#' Rounded number
#' @examples
#' round2(3.1415, 2)
round2 <- function(x, digits) {
posneg = sign(x)
z = abs(x) * 10^digits
z = z + 0.5
z = trunc(z)
z = z / 10^digits
return(z * posneg)
}
compare_df <- data.frame(matrix(rep(NA, 4), nrow=1))[numeric(0), ]
#' ## 年齢
#' ### 0:84歳未満、1:84歳以上
coxds$cox_age <- ifelse(coxds$agec == "<84", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_age, data=coxds), conf.int=0.95)
x
z <- c("age", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
compare_df[,1] <- as.character(compare_df[,1])
compare_df[,2] <- as.character(compare_df[,2])
compare_df[,3] <- as.character(compare_df[,3])
compare_df[,4] <- as.character(compare_df[,4])
colnames(compare_df) <- c("項目", "ハザード比", "ハザード比95%信頼区間", "Pr")
#' ## 性別
#' ### 0:男性, 1:女性
coxds$cox_sex <- ifelse(coxds$sex == "男性", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_sex, data=coxds), conf.int=0.95)
x
z <- c("sex", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## PS
#' ### 0:1以下, 1:2以上
coxds$cox_ps <- ifelse(coxds$ps == "=<1", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_ps, data=coxds), conf.int=0.95)
x
z <- c("ps", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## stage
#' ### 0:II以下、1:III以上
coxds$cox_stage <- ifelse(coxds$stagec == "=<II", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_stage, data=coxds), conf.int=0.95)
x
z <- c("stage", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## ipi
x <- summary(coxph(Surv(years, censor) ~ ipi, data=coxds))
x
z <- c("ipi", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Marrow involvement
#' ### 0:陽性、1:陰性
coxds$cox_marrow <- ifelse(coxds$marrow == "陰性", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_marrow, data=coxds), conf.int=0.95)
x
z <- c("marrow", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Bulky disease
#' ### 0:なし、1:あり
coxds$cox_bulky <- ifelse(coxds$bulky == "なし", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_bulky, data=coxds), conf.int=0.95)
x
z <- c("bulky", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Bulky mass
coxds$cox_bulkymass <- ifelse(coxds$bulkymass == "なし", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_bulkymass, data=coxds), conf.int=0.95)
x
z <- c("bulkymass", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ### 0:なし、1:あり
#' ## 肝_病変の有無
#' ### 0:なし、1:あり
coxds$cox_liver <- ifelse(coxds$liver == "なし", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_liver, data=coxds), conf.int=0.95)
x
z <- c("liver", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## 脾_病変の有無
#' ### 0:なし、1:あり
coxds$cox_spleen <- ifelse(coxds$spleen == "なし", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_spleen, data=coxds), conf.int=0.95)
x
z <- c("spleen", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## 腎_病変の有無
#' ### 0:なし、1:あり
coxds$cox_kidney <- ifelse(coxds$kidney == "なし", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_kidney, data=coxds), conf.int=0.95)
x
z <- c("kidney", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## B symptoms
#' ### 0:なし、1:あり
coxds$cox_bsymptom <- ifelse(coxds$bsymptom == "なし", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_bsymptom, data=coxds), conf.int=0.95)
x
z <- c("bsymptoms", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Weight loss
#' ### 0:False、1:True
coxds$cox_weight <- ifelse(coxds$weight == F, 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_weight, data=coxds), conf.int=0.95)
x
z <- c("weightloss", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Night sweats
#' ### 0:False、1:True
coxds$cox_nsweats <- ifelse(coxds$nsweats == F, 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_nsweats, data=coxds), conf.int=0.95)
x
z <- c("nightsweats", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Fever
#' ### 0:False、1:True
coxds$cox_fever <- ifelse(coxds$fever == F, 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_fever, data=coxds), conf.int=0.95)
x
z <- c("fever", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## LDH IU/L
#' ### 0:<250、1:250=<
coxds$cox_ldh <- ifelse(coxds$ldh == "<250", 0, 1)
x <- summary(coxph(Surv(years, censor) ~ cox_ldh, data=coxds), conf.int=0.95)
x
z <- c("ldh", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## β2MG(mg/L)
x <- summary(coxph(Surv(years, censor) ~ b2mg, data=coxds), conf.int=0.95)
x
z <- c("β2MG", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## 血清sIL-2R
x <- summary(coxph(Surv(years, censor) ~ sil2r, data=coxds), conf.int=0.95)
x
z <- c("sIL-2R", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## alb
coxds$cox_alb <- ifelse(coxds$alb == "3.5<=", 1, 0)
x <- summary(coxph(Surv(years, censor) ~ alb, data=coxds), conf.int=0.95)
x
z <- c("alb", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
#' ## Sex IPI scores B symptoms β2MG
#' ## 性別
#' ### 0:男性, 1:女性
#' ## B symptoms
#' ### 0:なし、1:あり
x <- summary(coxph(Surv(years, censor) ~ cox_sex + ipi + cox_bsymptom + b2mg, data=coxds), conf.int=0.95)
x
z <- c("Sex IPI scores B symptoms β2MG", round2(x$coefficients[2], digits=3),
paste(round2(x$conf.int[3], digits=3), round2(x$conf.int[4], digits=3), sep=" - "),
round2(x$coefficients[5], digits=4))
compare_df <- rbind(compare_df, z)
# output csv
write.csv(compare_df, paste0(output_path, "/", pfsos, "cox_compare.csv"), row.names=F, fileEncoding = "cp932", na="")
|
b2af64d4845004b10e9c2323943eaa932d52369b
|
512cc7446bfc05b392ba7e697d316eb00c620c01
|
/bin/R/benchmark_mnn.R
|
8ef0ff4ef253a1ddbbc782f4ba13539e45ec0956
|
[
"MIT"
] |
permissive
|
brianhie/scanorama
|
b4ce1c947b097a5098850aeafa92cb0126791ad1
|
3fbff622d8c6c0122e699e2e72e9ab4e2a531c7f
|
refs/heads/master
| 2022-12-13T05:23:11.764455
| 2022-11-28T18:50:30
| 2022-11-28T18:50:30
| 141,593,152
| 228
| 47
|
MIT
| 2022-11-28T18:48:41
| 2018-07-19T14:43:41
|
Python
|
UTF-8
|
R
| false
| false
| 1,463
|
r
|
benchmark_mnn.R
|
library(methods)
library(scran)
names = list(
"data/pancreas/pancreas_inDrop_table.txt",
"data/pancreas/pancreas_multi_celseq2_expression_matrix_table.txt",
"data/pancreas/pancreas_multi_celseq_expression_matrix_table.txt",
"data/pancreas/pancreas_multi_fluidigmc1_expression_matrix_table.txt",
"data/pancreas/pancreas_multi_smartseq2_expression_matrix_table.txt"
)
data.tables <- list()
for (i in 1:length(names)) {
data.tables[[i]] <- as.matrix(
read.table(names[[i]], sep="\t")
)
}
print("Done loading")
ptm <- proc.time()
Xmnn <- mnnCorrect(
data.tables[[1]],
data.tables[[2]],
data.tables[[3]],
data.tables[[4]],
data.tables[[5]]#,
#data.tables[[6]],
#data.tables[[7]],
#data.tables[[8]],
#data.tables[[9]],
#data.tables[[10]],
#data.tables[[11]],
#data.tables[[12]],
#data.tables[[13]],
#data.tables[[14]],
#data.tables[[15]],
#data.tables[[16]],
#data.tables[[17]],
#data.tables[[18]],
#data.tables[[19]],
#data.tables[[20]],
#data.tables[[21]],
#data.tables[[22]],
#data.tables[[23]],
#data.tables[[24]],
#data.tables[[25]],
#data.tables[[26]]
)
print("Done correcting")
print(proc.time() - ptm)
corrected.df <- do.call(cbind.data.frame, Xmnn$corrected)
corrected.mat <- as.matrix(t(corrected.df))
write.table(corrected.mat, file = "data/mnn_corrected_pancreas.txt",
quote = FALSE, sep = "\t")
|
c008a0e0fbe664fea4f9dae44302ddab583a2d67
|
321d64b8075c68a8472aa712114ea9f5131607d1
|
/plot4.R
|
6f22481f470f081e15b1068803ad8f11fab8d7ae
|
[] |
no_license
|
fengkehh/Exploratory_Data_Final
|
9ac6a4239450a70cfec0be4373512346e2a3e6e3
|
c28fb065569451be4397e307f8c40f0a59a1618f
|
refs/heads/master
| 2021-01-19T11:18:30.936074
| 2017-02-18T22:19:54
| 2017-02-18T22:19:54
| 82,237,867
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,484
|
r
|
plot4.R
|
# Plot 4
# Load data if necessary
data_load <- function() {
# Check that both data files exist
if (!prod(c('Source_Classification_Code.rds', 'summarySCC_PM25.rds') %in% dir())) {
download.file('https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip',
destfile = 'dataset.zip')
unzip('dataset.zip')
}
code <- readRDS('Source_Classification_Code.rds')
data <- readRDS('summarySCC_PM25.rds')
return(list(code, data))
}
if (!prod(c('code', 'data') %in% ls())) {
result <- data_load()
code <- result[[1]]
data <- result[[2]]
}
# Design: match the phrases 'Comb' and 'Coal' at least once with any other stuff
# in front, in between or after from the code list to determine proper source
# codes to extract
expr <- '(Comb)+.*(Coal)+'
target <- code[grep(expr, code$Short.Name),]
# Compute total annual emission from just coal combustion related sources.
coal <- data[data$SCC %in% target$SCC,]
coal_annual <- aggregate(coal$Emissions, by = list(coal$year), FUN = sum)
names(coal_annual) <- c('year', 'totalemission')
# Plot and save to a png file
png('plot4.png')
plot(coal_annual$year, coal_annual$totalemission, pch = 16, xlab = 'Year',
ylab = 'Total Annual Emission (tons)',
main = 'PM 2.5 Emissions from Coal Sources vs Year in the U.S.')
abline(lm(totalemission ~ year, data = coal_annual))
dev.off()
# Variable clean up
rm(list = setdiff(ls(), c('data', 'code')))
|
32f7fbce68a0c26fb9b5501a9976cf5432d62344
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/fulltext/examples/ft_search.Rd.R
|
100489aa6bcaac5fac80d3be9d939d5da5cbbedf
|
[] |
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
| 2,291
|
r
|
ft_search.Rd.R
|
library(fulltext)
### Name: ft_search
### Title: Search for full text
### Aliases: ft_search ft_search_ls
### ** Examples
# List publishers included
ft_search_ls()
## Not run:
##D # Plos
##D (res1 <- ft_search(query='ecology', from='plos'))
##D res1$plos
##D ft_search(query='climate change', from='plos', limit=500,
##D plosopts=list(
##D fl=c('id','author','eissn','journal','counter_total_all',
##D 'alm_twitterCount')))
##D
##D # Crossref
##D (res2 <- ft_search(query='ecology', from='crossref'))
##D res2$crossref
##D
##D # BioRxiv
##D (res <- ft_search(query='owls', from='biorxiv'))
##D res$biorxiv
##D
##D # Entrez
##D (res <- ft_search(query='ecology', from='entrez'))
##D res$entrez
##D
##D # arXiv
##D (res <- ft_search(query='ecology', from='arxiv'))
##D res$arxiv
##D
##D # BMC - can be very slow
##D (res <- ft_search(query='ecology', from='bmc'))
##D res$bmc
##D
##D # Europe PMC
##D (res <- ft_search(query='ecology', from='europmc'))
##D res$europmc
##D ## get the next batch of results, using the cursorMark result
##D ft_search(query='ecology', from='europmc',
##D euroopts = list(cursorMark = res$europmc$cursorMark))
##D
##D # Scopus
##D (res <- ft_search(query = 'ecology', from = 'scopus', limit = 100,
##D scopusopts = list(key = Sys.getenv('ELSEVIER_SCOPUS_KEY'))))
##D res$scopus
##D ## pagination
##D (res <- ft_search(query = 'ecology', from = 'scopus',
##D scopusopts = list(key = Sys.getenv('ELSEVIER_SCOPUS_KEY')), limit = 5))
##D ## lots of results
##D (res <- ft_search(query = "ecology community elk cow", from = 'scopus',
##D limit = 100,
##D scopusopts = list(key = Sys.getenv('ELSEVIER_SCOPUS_KEY'))))
##D res$scopus
##D ## facets
##D (res <- ft_search(query = 'ecology', from = 'scopus',
##D scopusopts = list(
##D key = Sys.getenv('ELSEVIER_SCOPUS_KEY'),
##D facets = "subjarea(count=5)"
##D ), limit = 5))
##D res$scopus
##D
##D # PLOS, Crossref, and arxiv
##D (res <- ft_search(query='ecology', from=c('plos','crossref','arxiv')))
##D res$plos
##D res$arxiv
##D res$crossref
##D
##D # Microsoft academic search
##D key <- Sys.getenv("MICROSOFT_ACADEMIC_KEY")
##D (res <- ft_search("Y='19'...", from = "microsoft", maopts = list(key = key)))
##D res$ma
##D res$ma$data$DOI
## End(Not run)
|
86e0ee66fd8ad32d65d9ef6a2460d7c3462505f7
|
2da2406aff1f6318cba7453db555c7ed4d2ea0d3
|
/inst/snippet/prob-cdf02.R
|
73ac2f7c535997962329e451e29f294ebe84f25a
|
[] |
no_license
|
rpruim/fastR2
|
4efe9742f56fe7fcee0ede1c1ec1203abb312f34
|
d0fe0464ea6a6258b2414e4fcd59166eaf3103f8
|
refs/heads/main
| 2022-05-05T23:24:55.024994
| 2022-03-15T23:06:08
| 2022-03-15T23:06:08
| 3,821,177
| 11
| 8
| null | null | null | null |
UTF-8
|
R
| false
| false
| 150
|
r
|
prob-cdf02.R
|
# compute the variance using E(X^2) - E(X)^2
value(integrate(f, k=2, lower = 0, upper = 2)) -
value(integrate(f, k=1, lower = 0, upper = 2))^2
|
43d2c6a727417f5318fa4cda11a8f85242378643
|
444654820df65d00eeb06d1ffdc9c29e968642ec
|
/scenario_0/scripts/0.setup.R
|
cdc4b7bfd8fb67ee13610407500c86df2cd221a6
|
[] |
no_license
|
michaelgras/MSE_CSH_monitoring_TAC2
|
207f7949dbea4dd9185e0c2307e7417dcae7eb9d
|
494d91bd142ce4562bf5b84e1f1741b2dbf273c7
|
refs/heads/master
| 2020-08-06T12:52:25.462201
| 2019-10-05T10:37:57
| 2019-10-05T10:37:57
| 212,981,950
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,219
|
r
|
0.setup.R
|
#initial environment setup
#install.packages("devtools")
#install.packages("FLCore", repo = "http://flr-project.org/R")
#install.packages(c("ggplotFL"), repos="http://flr-project.org/R")
#library(devtools)
#install_github("ices-tools-prod/msy")
#pathR<-paste("C:/Program Files/R/R-",substr(R.Version()$version.string, start=11, stop=15), "/library", sep="")
#pathFLR<-paste("D:/pro/MI/stock_assessment/FLR-library/R-",substr(R.Version()$version.string, start=11, stop=15), sep="")
#.libPaths(c(pathR, pathFLR))
# To be updated
setwd("D:/pro/MI/stock_assessment/CSH/scenario_0")
MSE.Dir <- "D:/pro/MI/stock_assessment/CSH/scenario_0"
rm(list=ls())
gc()
try(dev.off(),silent=TRUE)
library(devtools)
#install_github("msy", "einarhjorleifsson", ref = "master")
library(FLCore)
library(msy)
library(tidyverse)
library(Hmisc)
library(xtable)
library(scales)
library(gplots)
library(Cairo)
library(reshape2)
library(stringr)
#globals
#reference points (as set 2018 WKPELA)
Blim <- 34000
Bpa <- 54000
BtrigMP <- 61000 #prev MP trigger
Fpa <- 0.27
Flim <- 0.45
Fmsy <- 0.26
Ftgt <- 0.23 #prev MP target F
#Drive <- "D:"
#Assessment.Dir <- file.path(Drive,"Stocks","her.27.irls","Assessment")
#MSE.Dir <- file.path(Drive,"Stocks","her.27.irls","MSE","Rebuilding2018","her.27.irls.MSE2018.SimpSim")
## Source SimpSIM functions
#source(file.path(MSE.Dir,"Source","SimpSIM_v3.R"))
source(file.path(MSE.Dir,"Source","SimpSIM_CSH.R")) #CSH version
source(file.path(MSE.Dir,"Source","SimpSIM_additional_Funcs.r"))
source(file.path(MSE.Dir,"Source","MSE_StatPlot_Funcs_2016.r"))
#Assessment upon which to base the initialisation/SRR fits
#WG <- "HAWG2015"
#WG <- "HAWG2016"
#WG <- "HAWG2017"
#WG <- "WKPELA18" #benchmark of January 2018
#WG <- "HAWG2018" #Herring WG of March 2018
WG <- "HAWG2019" #Herring WG of March 2018
#stock name
stockName <- "her-irls"
#statistical periods for reporting
lStatPer <- list()
#annual stats
for (y in seq(1980,2047)){
lStatPer[[ac(y)]]<-c(y,y)
}
#Short, Medium and Long Term
lStatPer[['ST']] <- c(2017,2021)
lStatPer[['MT']] <- c(2022,2026)
lStatPer[['LT']] <- c(2027,2046)
#iterations to run
nits <- 1000
#nits <- 10
#years to project
nyr <- 35
#long term
#nyr <- 200
|
06e46e14040432fa8243ee1f6bdd7d73068a1bde
|
53ad81079abbff55ee82b8905d005f250897844c
|
/GMHomework/man/remove_contradict.Rd
|
a513a7fb39cfef517beda117f7717881634daeef
|
[] |
no_license
|
isfong1/Gradient_Metrics_Assigment
|
0aa475ccaffd09992426713604b324107805d425
|
f0d012be70bb1bddde800f2d03578dfe5699dfea
|
refs/heads/main
| 2023-01-30T00:45:52.191987
| 2020-12-04T02:19:54
| 2020-12-04T02:19:54
| 317,860,587
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| true
| 638
|
rd
|
remove_contradict.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/remove_contradict.R
\name{remove_contradict}
\alias{remove_contradict}
\title{Remove contradict ID}
\usage{
remove_contradict(data, ..., score, id)
}
\arguments{
\item{data}{a data frame}
\item{...}{variables or computations to group by.}
\item{score}{variable which is used for score}
\item{id}{key variable of the data frame}
}
\value{
dataframe
}
\description{
Return data table that remove respondents provided different answer in the same questions combination
}
\examples{
\dontrun{
remove_contradict(experiment_data, rtb, answer, response_id)
}
}
|
0ef3a5a0b038cfef8d388da368de3c9240469ef8
|
11e5a075d5b0da27d5f3563bdc7ee573e20a6574
|
/man/ctpopulator.Rd
|
3a6fc34071af5bd33c82d910df80a6f8082581a2
|
[] |
no_license
|
carlosvirgen/ctnamecleaner
|
4d7767b6ae06054954f66d9532c0fce98899371e
|
ef17c564b4cb51df5a1b420090739c9db6ba266b
|
refs/heads/master
| 2021-01-12T02:05:34.207937
| 2016-01-26T18:39:52
| 2016-01-26T18:39:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 747
|
rd
|
ctpopulator.Rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/cpopulator.R, R/ctpopulator.R
\name{ctpopulator}
\alias{ctpopulator}
\title{CT Population Appender}
\arguments{
\item{name}{Column with town names}
\item{data}{Name of dataframe}
\item{name}{Column with town names}
\item{data}{Name of dataframe}
\item{filename}{Name of CSV to export. Default is `nope` which creates dataframe without exporting.}
}
\value{
Whatever
Whatever
}
\description{
Adds population of CT towns in extra column to dataframe.
Adds population of CT towns in extra column to dataframe.
}
\examples{
\dontrun{
ctpopulator(name_column, ctdata, filename="analysis")
}
\dontrun{
ctpopulator(name_column, ctdata, filename="analysis")
}
}
|
b5c4ba33c665f81ffa25f39ebbe5343894994e02
|
c4670bf1594581622401a727791cd4d8283c5f4e
|
/2015_MLR/RiskAdj_Enroll_Match.R
|
e4a6d87010a5299d426ee40b59bcaaaf26f44c86
|
[] |
no_license
|
conor-ryan/Imperfect_Insurance_Competition_Code
|
db274b3818a97b240de08f05e79a5dedee246da1
|
e9ed4927f6a7a7670ec235a669b61b23509cc372
|
refs/heads/master
| 2023-07-20T05:51:29.180132
| 2023-07-05T23:06:10
| 2023-07-05T23:06:10
| 112,538,023
| 0
| 3
| null | null | null | null |
WINDOWS-1252
|
R
| false
| false
| 3,817
|
r
|
RiskAdj_Enroll_Match.R
|
rm(list = ls())
library(doBy)
library(noncensus)
setwd("C:/Users/Conor/Documents/Research/Imperfect_Insurance_Competition/")
##### Firm IDs ####
firms = read.csv("Data/2015_MLR/MR_Submission_Template_Header.csv",stringsAsFactors=FALSE)
firms = firms[,c("ï..MR_SUBMISSION_TEMPLATE_ID","BUSINESS_STATE","GROUP_AFFILIATION","COMPANY_NAME","DBA_MARKETING_NAME")]
# #### eHealth Market Shares ####
eHealth = read.csv("C:/Users/Conor/Documents/Research/eHealth Data/eHealth_2015.csv",stringsAsFactors = FALSE)
# Drop "referential integrity" rows
eHealth = eHealth[eHealth$PLAN_NAME!="UNKNOWN PLAN - this row is used for referential integrity - DSTOCK",]
# Drop eHealth observations with NA or 0 zip code
eHealth = eHealth[with(eHealth,!is.na(TRUNCATED_ZIP)&TRUNCATED_ZIP!=0 ),]
eHealth = eHealth[with(eHealth,PLAN_METAL_LEVEL!="N/A"),]
# State Level Market Shares
eHealth$count = 1
shares = summaryBy(count~STATE+CARRIER_NAME,data=eHealth,FUN=sum,keep.names=TRUE)
shares$share = shares$count/ave(shares$count,shares$STATE,FUN=sum)
#### Plan Counts ####
planData = read.csv("Data/2015_Premiums/2015_RWJF.csv")
planData$planCount = 1
planData = summaryBy(planCount~CARRIER+ST,data=planData,FUN=sum,keep.names = TRUE)
##### Individual Market Shares #####
claims = read.csv("Data/2015_MLR/Part1_2_Summary_Data_Premium_Claims.csv")
payments = claims[claims$ROW_LOOKUP_CODE=="FED_RISK_ADJ_NET_PAYMENTS",c("ï..MR_SUBMISSION_TEMPLATE_ID","CMM_INDIVIDUAL_Q1","CMM_INDIVIDUAL_RC")]
names(payments) = c("ï..MR_SUBMISSION_TEMPLATE_ID","Payments1","Payments2")
enroll =claims[claims$ROW_LOOKUP_CODE=="NUMBER_OF_LIFE_YEARS",c("ï..MR_SUBMISSION_TEMPLATE_ID","CMM_INDIVIDUAL_Q1","CMM_INDIVIDUAL_RC")]
names(enroll) = c("ï..MR_SUBMISSION_TEMPLATE_ID","Enrollment","EnrollmentQHP")
indMarket = merge(payments,enroll,by="ï..MR_SUBMISSION_TEMPLATE_ID")
# Remove non-Individual Market Insurers
indMarket$absent1 = is.na(indMarket$Enrollment) | indMarket$Enrollment==0
indMarket$absent2 = is.na(indMarket$EnrollmentQHP) | indMarket$EnrollmentQHP==0
indMarket = indMarket[!(indMarket$absent1&indMarket$absent2),c("ï..MR_SUBMISSION_TEMPLATE_ID","Payments1","Payments2","Enrollment","EnrollmentQHP")]
#### Merge-in Firm Info ####
firmCrosswalk = read.csv("Intermediate_Output/FirmCrosswalk.csv")
indMarket = merge(indMarket,firmCrosswalk,by="ï..MR_SUBMISSION_TEMPLATE_ID",all.y=TRUE)
indMarket = merge(indMarket,shares[shares$STATE%in%firmCrosswalk$STATE,],by.y=c("STATE","CARRIER_NAME"),by.x=c("STATE","eHealth_CARRIER_NAME"),all=TRUE)
indMarket = merge(indMarket,planData[planData$ST%in%firmCrosswalk$STATE,],by.y=c("ST","CARRIER"),by.x=c("STATE","RWJF_CARRIER"),all=TRUE)
#Drop un-matched plan choices (These firms are not present in eHealth Data)
indMarket = indMarket[!(is.na(indMarket$DBA_MARKETING_NAME)&is.na(indMarket$eHealth_CARRIER_NAME)),]
indMarket$TOTAL_LIVES = ave(indMarket$Enrollment,indMarket$BUSINESS_STATE,FUN=function(x){sum(x,na.rm=TRUE)})
indMarket$MARKET_SHARE1 = with(indMarket,Enrollment/TOTAL_LIVES)
indMarket$TOTAL_LIVES = ave(indMarket$EnrollmentQHP,indMarket$BUSINESS_STATE,FUN=function(x){sum(x,na.rm=TRUE)})
indMarket$MARKET_SHARE2 = with(indMarket,EnrollmentQHP/TOTAL_LIVES)
indMarket = indMarket[with(indMarket,order(BUSINESS_STATE,-MARKET_SHARE2)),]
indMarket$shareRank = indMarket$MARKET_SHARE1
indMarket$shareRank[is.na(indMarket$shareRank)] = indMarket$share[is.na(indMarket$shareRank)]
indMarket = indMarket[order(indMarket$BUSINESS_STATE,-indMarket$shareRank),]
write.csv(indMarket[,c("STATE","Firm","GROUP_AFFILIATION","COMPANY_NAME","DBA_MARKETING_NAME","eHealth_CARRIER_NAME","RWJF_CARRIER","Payments1","Payments2",
"MARKET_SHARE1","MARKET_SHARE2","count","share","planCount")],
"firmNamesTest.csv",row.names=FALSE)
|
9d2aae17de8ad0d4a298f17b67d8fdc71f966b23
|
191c6535c0c2b4a3d7025569eee619ad3c1ad0fc
|
/p3-timeseries/ingest-osx.R
|
df66481149ad3a441df8b6dc1bec20b3ee1cf6d9
|
[] |
no_license
|
pj201/csc791-projects
|
4e8c60c5d5a183a0971e8dc93fb5b851ef4063e4
|
c8fb1ad7b712c11bbc05c390fb6d96d7e61a5ac9
|
refs/heads/master
| 2020-05-31T01:26:28.868547
| 2015-05-06T03:44:36
| 2015-05-06T03:44:36
| 32,999,761
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,045
|
r
|
ingest-osx.R
|
############################################################
# CSC791 P3: Function to ingest data from OSX Journaling project
# Kshitij Sharma, ksharma3@ncsu.edu, Last updated: 4/2/2015
############################################################
#library(Rcurl)
#library(TimeSeries)
library(jsonlite)
library(httr)
library(RJSONIO)
# Returns an object containing a time series of CSC791 OSX data since timestamp
ingest_osx <- function(fromTimestamp, toTimestamp) {
# Get latest data - equivalent curl command looks like:
# curl -H "Content-Type: application/json"
# -H "AuthToken: ${AUTH_TOKEN}"
# -d '{"type":"find","query":{"data.UserId”:”${UNITYID}","data.ProjId":"journaling-chrome",
# "data.EvtTime":{"$gte":1423717200000,"$lte":1424303540000}}}'
# https://las-skylr-token.oscar.ncsu.edu/api/data/document/query
# TO DO: Insert timestamp into request
resp <- POST("https://las-skylr-token.oscar.ncsu.edu/api/data/document/query",
accept_json(),
verbose(),
add_headers("Content-Type" = "application/json", "AuthToken" = "9c0c9a9e0ec177d2bf9fd55edff5272cb2a3b9823babf07d6f762e3f9c9509bb"),
body = toJSON(list(
"type" = "find",
"query" = list(
"data.ProjId" = "skylr-osx-instrumenter",
"data.UserId" = "pjones",
"data.EvtTime" = list(
"$gte" = fromTimestamp,
"$lte" = toTimestamp
)
)
))
)
# Download query content from server
h<-content(resp, "text", encoding = "ISO-8859-1", col.names=FALSE, row.names=FALSE)
# Parse JSON
data.OSX <- jsonlite::fromJSON(h)
# Extract nested data object into data frame
data.OSX<-data.OSX$data$data
# For debugging only
#head(data.OSX)
#data.OSX
# Just return the data frame (gets converted to a timeSeries object
# by the create_timeseries function in preprocess.R)
return(data.OSX)
}
|
507481e08b0aedd4559f5fe0b82eaab3c8707059
|
685d6ca2be8ac49f81584fa157a60a801d8d1f60
|
/R/dwplot.R
|
a982c722d617cba251f690c6eabbf74cd983c4ca
|
[] |
no_license
|
cran/dotwhisker
|
eff2c85a13b87bab8e2a32ad4f0a017612cf02bb
|
748c1d47fd2123c9756005450c9c6ae43a240c44
|
refs/heads/master
| 2023-04-08T12:38:30.053853
| 2021-09-02T13:50:35
| 2021-09-02T13:50:35
| 39,861,333
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 23,836
|
r
|
dwplot.R
|
#' Dot-and-Whisker Plots of Regression Results
#'
#' \code{dwplot} is a function for quickly and easily generating dot-and-whisker plots of regression models saved in tidy data frames.
#'
#' @param x Either a model object to be tidied with \code{\link[broom]{tidy}}, or a list of such model objects, or a tidy data frame of regression results (see 'Details').
#' @param ci A number indicating the level of confidence intervals; the default is .95.
#' @param dodge_size A number indicating how much vertical separation should be between different models' coefficients when multiple models are graphed in a single plot. Lower values tend to look better when the number of independent variables is small, while a higher value may be helpful when many models appear on the same plot; the default is 0.4.
#' @param vars_order A vector of variable names that specifies the order in which the variables are to appear along the y-axis of the plot. Note that the order will be overwritten by \code{\link[dotwhisker]{relabel_predictors}}, if the function is following called.
#' @param show_intercept A logical constant indicating whether the coefficient of the intercept term should be plotted.
#' @param margins A logical value indicating whether presenting the average marginal effects of the estimates. See the Details for more information.
#' @param model_name The name of a variable that distinguishes separate models within a tidy data frame.
#' @param model_order A character vector defining the order of the models when multiple models are involved.
#' @param style Either \code{"dotwhisker"} or \code{"distribution"}. \code{"dotwhisker"}, the default, shows the regression coefficients' point estimates as dots with confidence interval whiskers. \code{"distribution"} shows the normal distribution with mean equal to the point estimate and standard deviation equal to the standard error, underscored with a confidence interval whisker.
#' @param by_2sd When x is model object or list of model objects, should the coefficients for predictors that are not binary be rescaled by twice the standard deviation of these variables in the dataset analyzed, per Gelman (2008)? Defaults to \code{FALSE}. Note that when x is a tidy data frame, one can use \code{\link[dotwhisker]{by_2sd}} to rescale similarly.
#' @param vline A \code{geom_vline()} object, typically with \code{xintercept = 0}, to be drawn behind the coefficients.
#' @param dot_args When \code{style} is "dotwhisker", a list of arguments specifying the appearance of the dots representing mean estimates. For supported arguments, see \code{\link[ggplot2]{geom_point}}.
#' @param whisker_args When \code{style} is "dotwhisker", a list of arguments specifying the appearance of the whiskers representing the confidence intervals. For supported arguments, see \code{\link[ggstance]{geom_linerangeh}}.
#' @param dist_args When \code{style} is "distribution", a list of arguments specifying the appearance of normally distributed regression estimates. For supported arguments, see \code{\link[ggplot2]{geom_polygon}}.
#' @param line_args When \code{style} is "distribution", a list of arguments specifying the appearance of the line marking the confidence interval beneath the normal distribution. For supported arguments, see \code{\link[ggstance]{geom_linerangeh}}.
#' @param \dots Extra arguments to pass to \code{\link[parameters]{parameters}}.
#'
#' @details \code{dwplot} visualizes regression model objects or regression results saved in tidy data frames as dot-and-whisker plots generated by \code{\link[ggplot2]{ggplot}}.
#'
#' Tidy data frames to be plotted should include the variables \code{term} (names of predictors), \code{estimate} (corresponding estimates of coefficients or other quantities of interest), \code{std.error} (corresponding standard errors), and optionally \code{model} (when multiple models are desired on a single plot; a different name for this last variable may be specified using the model_name argument).
#' In place of \code{std.error} one may substitute \code{conf.low} (the lower bounds of the confidence intervals of each estimate) and \code{conf.high} (the corresponding upper bounds).
#'
#' For convenience, \code{dwplot} also accepts as input those model objects that can be tidied by \code{\link[broom]{tidy}} (or \code{\link[broomExtra]{tidy_parameters}}, \code{\link[parameters]{parameters}} (with proper formatting)), or a list of such model objects.
#'
#' By default, the plot will display 95-percent confidence intervals. To display a different interval when passing a model object or objects, specify a \code{ci} argument. When passing a data frame of results, include the variables \code{conf.low} and \code{conf.high} describing the bounds of the desired interval.
#'
#' Because the function can take a data frame as input, it is easily employed for a wide range of models, including those not supported by \code{broom}, \code{broomExtra}, or \code{parameters}.
#' And because the output is a \code{ggplot} object, it can easily be further customized with any additional arguments and layers supported by \code{ggplot2}.
#' Together, these two features make \code{dwplot} extremely flexible.
#'
#' \code{dwplot} provides an option to present the average marginal effect directly based on \code{\link[margins]{margins}}. Users can alter the confidence intervals of the margins through the \code{ci} argument. See the full list of supported functions in the document of the package \code{\link{margins}}. The `margins` argument also works for \code{small_multiple} and \code{secret_weapon}.
#'
#' @references
#' Kastellec, Jonathan P. and Leoni, Eduardo L. 2007. "Using Graphs Instead of Tables in Political Science." *Perspectives on Politics*, 5(4):755-771.
#'
#' Gelman, Andrew. 2008. "Scaling Regression Inputs by Dividing by Two Standard Deviations." *Statistics in Medicine*, 27:2865-2873.
#'
#' @return The function returns a \code{ggplot} object.
#'
#' @import ggplot2
#' @importFrom parameters parameters standardize_names
#' @importFrom dplyr "%>%" n filter arrange left_join full_join bind_rows group_by if_else mutate distinct
#' @importFrom stats qnorm reorder model.matrix
#' @importFrom ggstance geom_pointrangeh position_dodgev GeomLinerangeh
#' @importFrom purrr map_dfr map
#' @importFrom stats dnorm model.frame
#' @importFrom utils modifyList
#' @importFrom utils globalVariables
#'
#' @examples
#' library(dplyr)
#' # Plot regression coefficients from a single model object
#' data(mtcars)
#' m1 <- lm(mpg ~ wt + cyl + disp, data = mtcars)
#' dwplot(m1, vline = geom_vline(xintercept = 0, colour = "grey50", linetype = 2)) +
#' xlab("Coefficient")
#' # using 99% confidence interval
#' dwplot(m1, ci = .99)
#' # Plot regression coefficients from multiple models
#' m2 <- update(m1, . ~ . - disp)
#' dwplot(list(full = m1, nodisp = m2))
#' # Change the appearance of dots and whiskers
#' dwplot(m1, dot_args = list(size = 3, pch = 21, fill = "white"))
#' # Plot regression coefficients from multiple models on the fly
#' mtcars %>%
#' split(.$am) %>%
#' purrr::map(~ lm(mpg ~ wt + cyl + disp, data = .x)) %>%
#' dwplot() %>%
#' relabel_predictors(c(wt = "Weight", cyl = "Cylinders", disp = "Displacement")) +
#' theme_bw() + xlab("Coefficient") + ylab("") +
#' geom_vline(xintercept = 0, colour = "grey60", linetype = 2) +
#' ggtitle("Predicting Gas Mileage, OLS Estimates") +
#' theme(plot.title = element_text(face = "bold"),
#' legend.position = c(.995, .99),
#' legend.justification = c(1, 1),
#' legend.background = element_rect(colour="grey80"),
#' legend.title.align = .5) +
#' scale_colour_grey(start = .4, end = .8,
#' name = "Transmission",
#' breaks = c("Model 0", "Model 1"),
#' labels = c("Automatic", "Manual"))
#'
#' @export
dwplot <- function(x,
ci = .95,
dodge_size = .4,
vars_order = NULL,
show_intercept = FALSE,
margins = FALSE,
model_name = "model",
model_order = NULL,
style = c("dotwhisker", "distribution"),
by_2sd = FALSE,
vline = NULL,
dot_args = list(size = 1.2),
whisker_args = list(size = .5),
dist_args = list(alpha = .5),
line_args = list(alpha = .75, size = 1),
...) {
# argument checks
if (length(style) > 1)
style <- style[[1]]
if (!style %in% c("dotwhisker", "distribution"))
stop("style must be dotwhisker or distribution")
# If x is model object(s), convert to a tidy data frame
df <- dw_tidy(x, ci, by_2sd, margins, ...)
if (!show_intercept)
df <-
df %>% filter(!grepl("^\\(Intercept\\)$|^\\w+\\|\\w+$", term)) # enable detecting intercept in polr objects
# Set variables that will appear in pipelines to NULL to make R CMD check happy
estimate <-
model <-
conf.low <-
conf.high <- term <- std.error <- n <- loc <- dens <- NULL
n_vars <- length(unique(df$term))
dodge_size <- dodge_size
# Confirm number of models, get model names
if (model_name %in% names(df)) {
dfmod <- df[[model_name]]
n_models <- length(unique(dfmod))
l_models <- if(is.null(model_order)) unique(dfmod) else model_order
## re-order/restore levels by order in data set
df[[model_name]] <- factor(dfmod, levels = rev(l_models))
} else {
if (length(df$term) == n_vars) {
df[[model_name]] <- factor("one")
n_models <- 1
} else {
stop(
"Please add a variable named '",
model_name,
"' to distinguish different models"
)
}
}
mod_names <- unique(df[[model_name]])
# Specify order of variables if an order is provided
if (!is.null(vars_order)) {
df$term <- factor(df$term, levels = vars_order)
df <- df[order(df$term),] %>% filter(!is.na(term))
}
# Add rows of NAs for variables not included in a particular model
if (n_models > 1) {
df <- add_NAs(df, n_models, mod_names)
}
# Prep arguments to ggplot
var_names <- unique(df$term)
df <- df %>%
mutate(y_ind = n_vars - as.numeric(factor(term, levels = var_names)) + 1)
y_ind <- df$y_ind
# Make the plot
if (style == "distribution") {
if (nrow(df) > n_models * n_vars) {
# reset df if it was passed by relabel_predictors
df <- df %>%
select(-n,-loc,-dens) %>%
distinct()
}
df1 <- purrr::map_dfr(1:101, function(x)
df) %>%
arrange(term, model) %>%
group_by(term, model) %>%
dplyr::mutate(
n = 1:dplyr::n(),
loc = estimate - 3 * std.error + (6 * std.error) /
100 * (n - 1),
dens = dnorm(loc, mean = estimate, sd = std.error) + y_ind
) %>%
filter(!is.na(estimate))
p <- ggplot(data = df) +
vline +
geom_dwdist(df1 = df1,
line_args = line_args,
dist_args = dist_args) +
scale_y_continuous(breaks = unique(df$y_ind), labels = var_names) +
guides(color = guide_legend(reverse = TRUE),
fill = guide_legend(reverse = TRUE)) +
ylab("") + xlab("")
} else {
# style == "dotwhisker"
point_args0 <- list(na.rm = TRUE)
point_args <- c(point_args0, dot_args)
segment_args0 <- list(na.rm = TRUE)
segment_args <- c(segment_args0, whisker_args)
p <- ggplot(data = df) +
vline +
geom_dw(
df = df,
point_args = point_args,
segment_args = segment_args,
dodge_size = dodge_size
) +
guides(color = guide_legend(reverse = TRUE)) +
ylab("") + xlab("")
}
# Omit the legend if there is only one model
if (n_models == 1) {
p <- p + theme(legend.position = "none")
}
p$args <- list(
dodge_size = dodge_size,
vars_order = vars_order,
show_intercept = show_intercept,
model_name = model_name,
model_order = model_order,
style = style,
by_2sd = FALSE,
vline = vline,
dot_args = dot_args,
whisker_args = whisker_args,
dist_args = dist_args,
line_args = line_args,
list(...)
)
return(p)
}
dw_tidy <- function(x, ci, by_2sd, margins,...) {
# Set variables that will appear in pipelines to NULL to make R CMD check happy
estimate <- model <- std.error <- conf.high <- conf.low <- NULL
AME <- SE <- lower <- p <- upper <- z <- NULL
## return model matrix *or* model frame
get_dat <- function(x) {
tryCatch(
as.data.frame(model.matrix(x)),
error = function(e)
model.frame(x)
)
}
## prepend "Model" to numeric-convertable model labels
mk_model <- function(x) {
if (all(!is.na(suppressWarnings(as.numeric(x))))) {
paste("Model", x)
} else
x
}
if (!is.data.frame(x)) {
if (!inherits(x, "list")) {
if(margins){
df <- margins::margins(x) %>%
summary(level = ci) %>%
rename(term = factor,
estimate = AME,
std.error = SE,
conf.low = lower,
conf.high = upper,
statistic = z,
p.value = p)
}else{
df <- standardize_names(parameters(x, ci, conf.int = TRUE, ...), style = "broom")
}
if (by_2sd) {
df <- df %>% by_2sd(get_dat(x))
}
} else {
# list of models
if (by_2sd) {
df <- purrr::map_dfr(x, .id = "model",
## . has special semantics, can't use
## it here ...
function(x) {
if(margins){
df <- margins::margins(x) %>%
summary(level = ci) %>%
rename(term = factor,
estimate = AME,
std.error = SE,
conf.low = lower,
conf.high = upper,
statistic = z,
p.value = p)
}else{
df <- standardize_names(parameters(x, ci, conf.int = TRUE, ...), style = "broom")
}
dotwhisker::by_2sd(df, dataset = get_dat(x))
}) %>%
mutate(model = mk_model(model))
} else {
df <- purrr::map_dfr(x, .id = "model",
function(x) {
if(margins){
df <- margins::margins(x) %>%
summary(level = ci) %>%
rename(term = factor,
estimate = AME,
std.error = SE,
conf.low = lower,
conf.high = upper,
statistic = z,
p.value = p)
}else{
df <- standardize_names(parameters(x, ci, conf.int = TRUE, ...), style = "broom")
}
}) %>%
mutate(model = if_else(
!is.na(suppressWarnings(as.numeric(
model
))),
paste("Model", model),
model
))
}
}
} else {
# x is a dataframe
df <- x
if ((!"conf.low" %in% names(df)) ||
(!"conf.high" %in% names(df))) {
if ("std.error" %in% names(df)) {
df <- transform(
df,
conf.low = estimate - stats::qnorm(1 - (1 - ci) /
2) * std.error,
conf.high = estimate + stats::qnorm(1 - (1 - ci) /
2) * std.error
)
} else {
df <- transform(df,
conf.low = NA,
conf.high = NA)
}
}
}
return(df)
}
add_NAs <-
function(df = df,
n_models = n_models,
mod_names = mod_names,
model_name = "model") {
# Set variables that will appear in pipelines to NULL to make R CMD check happy
term <- model <- NULL
if (!is.factor(df$term)) {
df$term <- factor(df$term, levels = unique(df$term))
}
if (!is.factor(dfmod <- df[[model_name]])) {
df[[model_name]] <- factor(dfmod, levels = unique(dfmod))
}
for (i in seq(n_models)) {
m <-
df %>% filter(model == factor(mod_names[[i]], levels = mod_names))
not_in <- setdiff(unique(df$term), m$term)
for (j in seq(not_in)) {
t <- data.frame(
term = factor(not_in[j], levels = levels(df$term)),
model = factor(mod_names[[i]], levels = mod_names)
)
if ("submodel" %in% names(m)) {
t$submodel <- m$submodel[1]
}
if ("submodel" %in% names(m)) {
m <- full_join(m, t, by = c("term", "model", "submodel"))
} else {
m <- full_join(m, t, by = c("term", "model"))
}
}
if (i == 1) {
dft <- m %>% arrange(term)
} else {
dft <- bind_rows(dft, m %>% arrange(term))
}
}
df <- dft
df$estimate <- as.numeric(df$estimate)
if ("std.error" %in% names(df)) {
df$std.error <- as.numeric(df$std.error)
}
if ("conf.high" %in% names(df)) {
df$conf.high <- as.numeric(df$conf.high)
}
if ("conf.low" %in% names(df)) {
df$conf.low <- as.numeric(df$conf.low)
}
return(df)
}
geom_dwdist <- function(data = NULL, df1, line_args, dist_args) {
# Set variables to NULL to make R CMD check happy
loc <-
dens <- model <- term <- y_ind <- conf.high <- conf.low <- NULL
l1 <- layer(
data = df1,
mapping = aes(
x = loc,
y = dens,
group = interaction(model, term),
color = model,
fill = model
),
stat = "identity",
position = "identity",
geom = GeomPolygon,
params = dist_args
)
l2 <- layer(
data = data,
mapping = aes(
y = y_ind,
xmin = conf.low,
xmax = conf.high,
color = model
),
stat = "identity",
position = "identity",
geom = ggstance::GeomLinerangeh,
show.legend = FALSE,
params = line_args
)
return(list(l1, l2))
}
geom_dw <- function(df, point_args, segment_args, dodge_size) {
# Set variables to NULL to make R CMD check happy
loc <-
dens <-
model <- term <- y_ind <- conf.high <- conf.low <- estimate <- NULL
point_arguments <-
tryCatch({
added_point_aes <- point_args[names(point_args) == ""][[1]]
point_mapping <-
modifyList(
aes(
y = stats::reorder(term, y_ind),
x = estimate,
group = interaction(model, term),
color = model
),
added_point_aes
)
point_arguments <- point_args[names(point_args) != ""]
list(point_mapping, point_arguments)
},
error = function(e) {
point_mapping <-
aes(
y = stats::reorder(term, y_ind),
x = estimate,
group = interaction(model, term),
color = model
)
return(list(point_mapping, point_args))
})
segment_arguments <-
tryCatch({
added_segment_aes <- segment_args[names(segment_args) == ""][[1]]
segment_mapping <-
modifyList(
aes(
y = stats::reorder(term, y_ind),
xmin = conf.low,
xmax = conf.high,
group = interaction(model, term),
color = model
),
added_segment_aes
)
segment_arguments <- segment_args[names(segment_args) != ""]
list(segment_mapping, segment_arguments)
},
error = function(e) {
segment_mapping <-
aes(
y = stats::reorder(term, y_ind),
xmin = conf.low,
xmax = conf.high,
group = interaction(model, term),
color = model
)
return(list(segment_mapping, segment_args))
})
l1 <- layer(
data = df,
mapping = point_arguments[[1]],
stat = "identity",
position = ggstance::position_dodgev(height = dodge_size),
geom = "point",
params = point_arguments[[2]]
)
l2 <- layer(
data = df,
mapping = segment_arguments[[1]],
stat = "identity",
position = ggstance::position_dodgev(height = dodge_size),
geom = ggstance::GeomLinerangeh,
show.legend = FALSE,
params = segment_arguments[[2]]
)
return(list(l2, l1))
}
#' @rdname dwplot
dw_plot <- dwplot
|
28ca4b0073e46e7adc6ae74947a5d9e74435a1d2
|
d86762bc2c7fc458ff3968532b40e1305191fff7
|
/sub_scripts/covertToCSV.R
|
fa5125ccc5080aa982b146eeb08af4430be1f224
|
[] |
no_license
|
hjakupovic/SNPextractor
|
4a8bfe47d8f1f4eed7d77e96516a364071cea191
|
c8c0b35f11f58a1646f022913072792c80099771
|
refs/heads/master
| 2022-06-22T11:51:15.544028
| 2018-02-09T11:38:26
| 2018-02-09T11:38:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,707
|
r
|
covertToCSV.R
|
#!/usr/local/bin/Rscript
args <- commandArgs(trailingOnly=T)
folder <- args[1]
outputName <- args[2]
userSNPsFile <- args[3]
geno <- read.table(paste(folder,'genoFile.noHead',sep=''),h=F,as.is=T)
genoHeader <- read.table(paste(folder,'newHeader',sep=''),h=F,as.is=T)
colnames(geno) <- t(genoHeader)
#Writing info as numeric
geno$INFO <- as.numeric(substr(geno$INFO,6,nchar(geno$INFO)))
#Info file
info <- geno[,which(colnames(geno) %in% c("ID","REF","ALT","POS","CHROM","INFO"))]
#Adding users SNPnames from SNPlist file:
SNPnames <- read.table(userSNPsFile,h=F,as.is=T)
colnames(SNPnames) <- c('SNP','CHROM','POS')
finalInfo <- merge(info,SNPnames,by=c('CHROM','POS'),all.x=T)
#Ordering
finalInfo <- finalInfo[,c('ID','SNP','CHROM','POS','REF','ALT','INFO')]
colnames(finalInfo)[5:6] <- c("REF(0)","ALT(2)")
#Getting the final format for the genofile
finalGeno <- geno[,-which(colnames(geno) %in% c("QUAL", "FILTER", "INFO", "FORMAT","REF","ALT","POS","CHROM"))]
finalGeno <- t(finalGeno)
genoColnames <- finalGeno['ID',]
if(ncol(finalGeno)>1){
finalGeno <- finalGeno[-which(rownames(finalGeno)=='ID'),]
}else{
finalGeno <- as.data.frame(finalGeno[-which(rownames(finalGeno)=='ID'),],stringsAsFactors=F)
}
colnames(finalGeno) <- genoColnames
#Removing phasing info in genotypes
genotypeFromPhase <- function(x){
y <- strsplit(x,'|')[[1]]
z <- as.numeric(y[1])+as.numeric(y[3])
return(z)
}
if(any(grepl('|',finalGeno,fixed=T))){
finalGeno <- apply(finalGeno,c(1,2),genotypeFromPhase)
}
#Write out as csv
write.csv(finalGeno,paste(outputName,'geno','csv',sep='.'),row.names=T,quote=F)
write.csv(finalInfo,paste(outputName,'info','csv',sep='.'),row.names=F,quote=F)
|
bfc52ad7e58b414fdfd093506790694e072e9350
|
3f6beaa6c2c36d7ee730c38e80553342171a984a
|
/Assignment2/Mandatory2_Code.R
|
08772863f936ba9f6449c5c4b40d44e03a3eb33a
|
[] |
no_license
|
vladmaksyk/StatisticalModeling
|
ed2368aae19e120bced057f7db6fd223469156ca
|
678b66bdfb15ce8a49ab124b4c63f44d22fbe5a8
|
refs/heads/master
| 2020-06-11T23:57:20.344173
| 2019-06-27T16:33:55
| 2019-06-27T16:33:55
| 194,128,624
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 14,937
|
r
|
Mandatory2_Code.R
|
rm(list=ls()) # clear all variables
graphics.off() # clear all figures
cat("\014") # clear console window
###################################################################
##################### Problem 1c ###################################
###################################################################
cat("Problem 1c \n")
#Odds for different outcomes
NorKyp = c(1.3, 4.1, 8.1)
TysFra = c(2.35, 3.0, 2.65)
PorKro = c(2.2, 2.9, 2.85)
NedPer = c(1.6, 3.4, 4.45)
#Real probabilities for diferrent outcomes
NorKyp2 = c(0.67, 0.22, 0.11)
TysFra2 = c(0.38, 0.29, 0.33)
PorKro2 = c(0.40, 0.29, 0.31)
NedPer2 = c(0.54, 0.26, 0.20)
ProfitCalculation = function(Game,odd){
Nsim = 10000
MoneySpent = 1000000
MoneyWon = 0
GameOutcomes <- sample(1:3,size=Nsim,replace=TRUE,prob=c(Game[1],Game[2],Game[3]))
for (i in GameOutcomes){
if (i == 1){
winnings = 100 * odd
MoneyWon = MoneyWon + winnings
}
}
profit = MoneyWon - MoneySpent
return(profit)
}
ProfitRecords = c()
for (j in 1:100){
RealProfit1 = ProfitCalculation(NorKyp2, NorKyp[1])
RealProfit2 = ProfitCalculation(TysFra2, TysFra[1])
RealProfit3 = ProfitCalculation(PorKro2, PorKro[1])
RealProfit4 = ProfitCalculation(NedPer2, NedPer[1])
ProfitRecords[j] = RealProfit1 + RealProfit2 + RealProfit3 + RealProfit4
}
cat("The expected profit:",mean(ProfitRecords),"\n")
cat("\n")
###################################################################
##################### Problem 1e ###################################
###################################################################
cat("Problem 1e \n")
#All game outcomes probabilities combined in one vector
CombinedProb = c(NorKyp2, TysFra2, PorKro2, NedPer2)
ProfitCalculation2 = function(GameProb){
Nsim = 10000
Stake = 400
MoneySpent1 = Stake*Nsim
MoneyWon1 = 0
CombinedOdd = 10.75
GameResults1 <- sample(1:3,size=Nsim,replace=TRUE,prob=c(GameProb[1],GameProb[2],GameProb[3]))
GameResults2 <- sample(1:3,size=Nsim,replace=TRUE,prob=c(GameProb[4],GameProb[5],GameProb[6]))
GameResults3 <- sample(1:3,size=Nsim,replace=TRUE,prob=c(GameProb[7],GameProb[8],GameProb[9]))
GameResults4 <- sample(1:3,size=Nsim,replace=TRUE,prob=c(GameProb[10],GameProb[11],GameProb[12]))
for (k in 1:Nsim){
if (sum(GameResults1[k],GameResults2[k],GameResults3[k],GameResults4[k]) == 4){
MoneyWon1 = MoneyWon1 + (Stake*CombinedOdd)
}
}
Profit1 = MoneyWon1 - MoneySpent1
}
ProfitRecords1 = c()
for (z in 1:100){
ProfitRecords1[z] = ProfitCalculation2(CombinedProb)
}
cat("The expected profit:",mean(ProfitRecords1),"\n")
cat("\n")
###################################################################
##################### Problem 2b ###################################
###################################################################
cat("Problem 2b \n")
# Intensity function for the arrival of visitors to the website
IntensityFunc <- function(t)
5+50*sin(pi*t/24)^2+190*exp(-(t-20)^2/3)
curve(IntensityFunc,0,24) # Expected number of guest arriving at every hour in time 0:24
max(IntensityFunc(seq(0,24,length.out = 100))) # max value in the plot
nsim <- (1.96^2*208^2*24^2*0.25)/10^2
# Hit or miss method
nsim <- 243957
c <- 208
y <- runif(nsim,0,c)
x <- runif(nsim,0,24)
z = y <= IntensityFunc(x) # hit or miss
intHM <- c*24*mean(z) # hit or miss estimate (mean(x) is probability of True in x)
intHM
# More precise calculation of required number of simulations:
phat <- mean(z) # estimated proportion of hit
nsim2 <- 1.96^2*208^2*24^2*phat*(1-phat)/(10^2)
y2 <- runif(nsim2,0,c)
x2 <- runif(nsim2,0,24)
z2 = y2 <= IntensityFunc(x2) # hit or miss
intHM2 <- c*24*mean(z2)
cat("Probability of having more than 1250 visitors during a day:",ppois(intHM, 1250),"\n")
cat("\n")
###################################################################
##################### Problem 2d ###################################
###################################################################
cat("Problem 2d \n")
# Function for simulating arrival times for a NHPP between a and b using thinning
simtNHPP <- function(a,b,lambdamax,lambdafunc){
# Simple check that a not too small lambdamax is set
if(max(lambdafunc(seq(a,b,length.out = 100)))>lambdamax)
stop("lambdamax is smaller than max of the lambdafunction")
# First simulate HPP with intensity lambdamax on a to b
expectednumber <- (b-a)*lambdamax
Nsim <- 3*expectednumber # Simulate more than the expected number to be certain to exceed stoptime
timesbetween <- rexp(Nsim,lambdamax) # Simulate interarrival times
timesto <- a+cumsum(timesbetween) # Calculate arrival times starting at a
timesto <- timesto[timesto<b] # Dischard the times larger than b
Nevents <- length(timesto) # Count the number of events
# Next do the thinning. Only keep the times where u<lambda(s)/lambdamax
U <- runif(Nevents)
timesto <- timesto[U<lambdafunc(timesto)/lambdamax]
return(timesto) # Return the remaining times
}
# The intensity function
lambdafunction <- function(t)
5+50*sin(pi*t/24)^2+190*exp(-(t-20)^2/3)
# Plot the intensity function
tvec <- seq(0,24,by=0.01)
plot(tvec,lambdafunction(tvec),type="l",ylim=c(0,220))
# Generate data with the traffic intensity and plot them
NHPPtimesV1 <- simtNHPP(a=0,b=24,lambdamax=210,lambdafunc=lambdafunction)
plot(NHPPtimesV1,1:length(NHPPtimesV1),type="s",xlab = "time",
ylab = "Event number",lwd=1.5)
points(NHPPtimesV1,rep(0,length(NHPPtimesV1)),pch=21,bg="red")
########################################################################################
#Verify the proportion of arrival times being deleted in the thinning step
# Function for simulating arrival times for a NHPP between a and b using thinning
Proportion <- function(a,b,lambdamax,lambdafunc){
# First simulate HPP with intensity lambdamax on a to b
expectednumber <- (b-a)*lambdamax
Nsim <- 3*expectednumber # Simulate more than the expected number to be certain to exceed stoptime
timesbetween <- rexp(Nsim,lambdamax) # Simulate interarrival times
timesto <- a+cumsum(timesbetween) # Calculate arrival times starting at a
timesto <- timesto[timesto<b] # Dischard the times larger than b
Nevents <- length(timesto) # Count the number of events
# Next do the thinning. Only keep the times where u<lambda(s)/lambdamax
U <- runif(Nevents)
timesto <- timesto[U<lambdafunc(timesto)/lambdamax]
Nevents2 <- length(timesto)
ProportionOfTimesDel = 1 - Nevents2/Nevents
return(ProportionOfTimesDel)
}
Records = numeric(100)
for (z in 1:100){
Records[z] <- Proportion(a=0,b=24,lambdamax=210,lambdafunc=lambdafunction)
}
cat("Proportion of times being deleted in the thinning step:",mean(Records),"\n")
#############################################################################################
##########################################################################################
### Simulating the number of active visitors over time for one the day
calculatequeue <- function(arrivaltimes, servicetimes){
Narrivals <- length(arrivaltimes) # Total number of arrival
departuretimes <- sort(arrivaltimes+servicetimes) # Calculate and sort the departure times
eventtimes <- 0 # This will be the vector for event times
numbersinqueue <- 0 # This will be the vector for current active visitors, updated at each event time
currentnumber <- 0 # Keeps track of the current number of visitors
acounter <- 1 # Counter for the arrivals vector
dcounter <- 1 # Counter for the departures vector
while(acounter<=Narrivals){
if(arrivaltimes[acounter]<departuretimes[dcounter]){ # If the next event is an arrival
currentnumber <- currentnumber+1
numbersinqueue <- c(numbersinqueue,currentnumber)
eventtimes <- c(eventtimes,arrivaltimes[acounter])
acounter <- acounter+1
}
else{ # If the next event is an departure
currentnumber <- currentnumber-1
numbersinqueue <- c(numbersinqueue,currentnumber)
eventtimes <- c(eventtimes,departuretimes[dcounter])
dcounter <- dcounter+1
}
}
return(list(numbers=numbersinqueue,times=eventtimes))
}
# The intensity function
lambdafunction <- function(t)
5+50*sin(pi*t/24)^2+190*exp(-(t-20)^2/3)
# Plot the intensity function
tvec <- seq(0,24,by=0.1)
plot(tvec,lambdafunction(tvec),type="l")
# Generate and plot the number of active visitors at the website a day
arrivaltimes <- simtNHPP(a=0,b=24,lambdamax=210,lambdafunc=lambdafunction)
servicetimes <- rgamma(length(arrivaltimes),shape=2,scale=3)/60
novertime <- calculatequeue(arrivaltimes,servicetimes)
plot(novertime$times,novertime$numbers,type="s",xlab = "time",
ylab = "Number of visitors at the website",lwd=1.5)
#Estimation of the probability that the maximum number of visitors exeeds 30
Nsim <- 100
maxvalues <- numeric(Nsim)
count = 0
for(i in 1:Nsim){
arrivaltimes <- simtNHPP(a=0,b=24,lambdamax=210,lambdafunc=lambdafunction)
servicetimes <- rgamma(length(arrivaltimes),shape=2,scale=3)/60
novertime <- calculatequeue(arrivaltimes,servicetimes)
maxvalues[i] <- max(novertime$numbers)
if (maxvalues[i]> 30){
count = count +1
}
}
cat("The probability that the maximum number of visitor exeeds 30:",count/Nsim,"\n")
# calculation of median, 5% and 95% quantiles of the number of visitors at time 12
Nsim <- 100 # This simulation takes some time
maxvalues <- numeric(Nsim)
for(i in 1:Nsim){
arrivaltimes <- simtNHPP(a=0,b=12,lambdamax=210,lambdafunc=lambdafunction)
servicetimes <- rgamma(length(arrivaltimes),shape=2,scale=3)/60
novertime <- calculatequeue(arrivaltimes,servicetimes)
maxvalues[i] <- max(novertime$numbers)
}
cat("The median of the number of visitors at time 12:",median(maxvalues),"\n")
cat("The 5% and 95% quantiles of number of visitors at time 12:",quantile(maxvalues,probs = seq(0.05, 0.95, 0.9)),"\n")
summary(maxvalues)
cat("\n")
###################################################################
##################### Problem 2f ###################################
###################################################################
cat("Problem 2f \n")
# The function below simulate guest arrival times over [0,tau] to the website from
# the intensity function.(Each time denotes a time of an gues arrival to the website)
NHPPsim <- function(tau=24){
HPPtimes <- rexp(4000) # Simulate 4000 interarrival times on HPP scale
HPPtimescumsum <- cumsum(HPPtimes) # Calculate arrival times on HPP scale
NHPPtimes <- sqrt((HPPtimescumsum/5)+1)-1 # Transform to NHPP scale
NHPPtimes <- NHPPtimes[NHPPtimes<tau] # Delete the times larger than tau
return(NHPPtimes)
}
# Generate and plot the data
NHPPtimes <- NHPPsim(tau=24)
plot(NHPPtimes,1:length(NHPPtimes),type="s",xlab = "hour",
ylab = "Event number",lwd=1.5)
points(NHPPtimes,rep(0,length(NHPPtimes)),pch=21,bg="red")
cat("\n")
###################################################################
##################### Problem 2g ###################################
###################################################################
cat("Problem 2g \n")
par(mfrow=c(1,2)) #split plot erea in 2
# The intensity functions
lambdafunction <- function(t)
5+50*sin(pi*t/24)^2+190*exp(-(t-20)^2/3)
lambdafunction2 <- function(t)
10+10*t
# Plot the intensity functions
tvec <- seq(0,24,by=0.01)
plot(tvec,lambdafunction(tvec),type="l")
tvec <- seq(0,24,by=0.01)
plot(tvec,lambdafunction2(tvec),type="l")
par(mfrow=c(1,1))
#Implementation of the alternative thinning algorithm
simtNHPP2 <- function(tau,lambdafunc,lambdafunc2){
HPPtimes <- rexp(4000) # Simulate 4000 interarrival times on HPP scale
HPPtimescumsum <- cumsum(HPPtimes) # Calculate arrival times on HPP scale
NHPPtimes <- sqrt((HPPtimescumsum/5)+1)-1 # Transform to NHPP scale
NHPPtimes <- NHPPtimes[NHPPtimes<tau] # Delete the times larger than tau
Nevents <- length(NHPPtimes) # Count the number of events
# Next do the thinning. Only keep the times where u<lambda(s)/lambdamax
U <- runif(Nevents)
NHPPtimes <- NHPPtimes[U<lambdafunc(NHPPtimes)/lambdafunc2(NHPPtimes)] #lambdasi/lambdamax
return(NHPPtimes) # Return the remaining times
}
# Generate data with the traffic intensity and plot them
NHPPtimesV2 <- simtNHPP2(tau=24,lambdafunc=lambdafunction,lambdafunc2=lambdafunction2)
plot(NHPPtimesV2,1:length(NHPPtimesV2),type="s",xlab = "time",
ylab = "Event number",lwd=1.5)
points(NHPPtimesV2,rep(0,length(NHPPtimesV2)),pch=21,bg="red")
#####################################################################################################
# One way to verify that the algorithm seems to be correct is to plot thinning methods
# And see if they are identical
cat("One way to verify that the algorithm seems to be correct is to plot thinning methods","\n")
cat("and see if they are identical.","\n")
par(mfrow=c(1,2)) #split plot erea in 2
# Standart thinning method
NHPPtimesV1 <- simtNHPP(a=0,b=24,lambdamax=210,lambdafunc=lambdafunction)
plot(NHPPtimesV1,1:length(NHPPtimesV1),type="s",xlab = "time",
ylab = "Event number",lwd=1.5)
points(NHPPtimesV1,rep(0,length(NHPPtimesV1)),pch=21,bg="red")
# Alternative thinning method
NHPPtimesV2 <- simtNHPP2(tau=24,lambdafunc=lambdafunction,lambdafunc2=lambdafunction2)
plot(NHPPtimesV2,1:length(NHPPtimesV2),type="s",xlab = "time",
ylab = "Event number",lwd=1.5)
points(NHPPtimesV2,rep(0,length(NHPPtimesV2)),pch=21,bg="red")
par(mfrow=c(1,1))
#####################################################################################################
# Estimation of the proportion of times being deleted in the thinning step for the alternative algorithm
Proportion2 <- function(tau,lambdafunc,lambdafunc2){
HPPtimes <- rexp(4000) # Simulate 4000 interarrival times on HPP scale
HPPtimescumsum <- cumsum(HPPtimes) # Calculate arrival times on HPP scale
NHPPtimes <- sqrt((HPPtimescumsum/5)+1)-1 # Transform to NHPP scale
NHPPtimes <- NHPPtimes[NHPPtimes<tau] # Delete the times larger than tau
Nevents <- length(NHPPtimes) # Count the number of events
# Next do the thinning. Only keep the times where u<lambda(s)/lambdamax
U <- runif(Nevents)
NHPPtimes <- NHPPtimes[U<lambdafunc(NHPPtimes)/lambdafunc2(NHPPtimes)]
Nevents2 <- length(NHPPtimes)
ProportionOfTimesDel2 = 1 - Nevents2/Nevents
return(ProportionOfTimesDel2)
}
Records2 = numeric(100)
for (g in 1:100){
Records2[g] <- Proportion2(tau=24,lambdafunc=lambdafunction,lambdafunc2=lambdafunction2)
}
cat("Proportion of times being deleted in the thinning step:",mean(Records2),"\n")
cat("The proportion of the deleted times in the alternative thinning algorithm became smaller.","\n")
cat("So we can state that it is not very efficeient to use lambda(max) when it is much higher","\n")
cat("compared to most lambda(t) as most of the proposed arrival times will be rejected.","\n")
cat("\n")
|
2e85c5d416cd3625501e9323d24a29ee3473f6a7
|
4213a7ada3a3c816876b8094f3903c746410a95f
|
/transposes.r
|
71d0ad3b910352ab2e44f3272c4e164ce7e128be
|
[
"CC0-1.0"
] |
permissive
|
sarahsmason/Health
|
d90bf8809c29318d6524094bea187e5d1e936561
|
73f13bf0755ff27b7ea8ec46c7d48223b6a0de99
|
refs/heads/master
| 2023-04-19T22:10:17.302888
| 2021-05-10T00:20:58
| 2021-05-10T00:20:58
| 284,592,708
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 476
|
r
|
transposes.r
|
install.packages("dplyr")
install.packages("stringr")
install.packages("ggplot2")
install.packages("data.table")
library(dplyr)
library(stringr)
library(ggplot2)
library(class)
library(data.table)
setwd("#your.dir#")
#Load data
tableGenes <- read.csv("#your.file.csv", sep=",",
header = F, fill = T, stringsAsFactors = FALSE)
DataSetnew = transpose(tableGenes)
write.csv(DataSetnew, '#your.path.filename', row.names = FALSE)
|
d275c834f55b9efb5a25e9535c6100112bf2ed06
|
35d850f46b513c3d9abb71e84e4d1eead94c6914
|
/man/DataValidation.Rd
|
7b201d81738cb3c4fea67bc0aee66685c6490411
|
[] |
no_license
|
smockin/RedcapData
|
4690dc8696a1214c94b3a99b53b94ad9844755e1
|
63b14a033f866ac7a9511b92e36ea8ed74e07d90
|
refs/heads/v1.1.1
| 2023-02-08T01:19:15.523402
| 2023-01-23T06:41:50
| 2023-01-23T06:41:50
| 182,263,613
| 2
| 1
| null | 2020-12-19T13:08:11
| 2019-04-19T12:46:25
|
R
|
UTF-8
|
R
| false
| true
| 648
|
rd
|
DataValidation.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data_checks.R
\name{date_can_be_validated}
\alias{date_can_be_validated}
\alias{data_can_be_validated}
\alias{data_missing}
\title{Check whether a date can be used for validation}
\usage{
date_can_be_validated(var)
data_can_be_validated(var)
data_missing(var)
}
\arguments{
\item{var}{The variable to check}
}
\description{
Check whether a date can be used for validation
}
\details{
This performs checks to see if a date can be used for validation in error reporting.
This prevents unnecessary errors and validations resulting from invalid or default data inputs.
}
|
0e99cea06f8801c361eb121123f530fe20a6867e
|
42a5c6d0fb7ab6263e6f86bbc6d46b5231ee7215
|
/make.map.R
|
54804812a618829401a03c05349c91f1c743c143
|
[] |
no_license
|
mcrossley3/whiteflyPopGenReview
|
a4412b313aa61ca6112ea62623ed3bd04170f64c
|
6fef655807f763bc8b94778022ba40b57363a28b
|
refs/heads/master
| 2023-01-24T08:22:14.511251
| 2020-12-04T20:54:36
| 2020-12-04T20:54:36
| 298,055,616
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,886
|
r
|
make.map.R
|
setwd('C:/Users/mcros/Desktop/Postdoc UGA/Whitefly project 2020/manuscripts/review Insects special issue')
library(rgdal)
library(rgeos)
library(tidyverse)
library(sf) # for manipulation of simple features objects
library(lwgeom)
winkel_tripel = "+proj=wintri +datum=WGS84 +no_defs +over"
world = spTransform(readOGR(dsn='./shapefiles/99bfd9e7-bb42-4728-87b5-07f8c8ac631c2020328-1-1vef4ev.lu5nk.shp',layer='99bfd9e7-bb42-4728-87b5-07f8c8ac631c2020328-1-1vef4ev.lu5nk',verbose=F,stringsAsFactors=F),CRS(winkel_tripel))
grat_sf = st_graticule(lat = c(-89.9, seq(-80, 80, 20), 89.9)) %>% st_transform_proj(crs = winkel_tripel) #grid for mapping
st_write(grat_sf,'./shapefiles/graticule_winkel-tripel.shp')
dat = read.table('whitefly.review.summary.txt',sep='\t',as.is=T,check.names=F,header=T)
dat2 = data.frame('Country'=NA,'Biotype'=NA,'Year1'=-999,'Year2'=-999,'Marker'=NA,'N.markers'=-999)
dx = 1
for (i in 1:nrow(dat)){
cs = strsplit(dat$Geography[i],';')[[1]]
biotypes = strsplit(dat$Biotypes[i],';')[[1]]
for (j in 1:length(cs)){
for (k in 1:length(biotypes)){
dat2[dx,1] = cs[j]
dat2[dx,2] = biotypes[k]
dat2[dx,3] = dat$Year1[i]
dat2[dx,4] = dat$Year2[i]
dat2[dx,5] = dat$Marker[i]
dat2[dx,6] = dat$N.markers[i]
dx = dx + 1
}
}
}
uc = unique(dat2$Country)
out = data.frame('Country'=uc,'Biotypes'=NA,'Markers'=NA,'SSR'=NA,'MEAM1'=NA,'MED'=NA,'SNP'=NA)
for (i in 1:length(uc)){
biotypes = sort(unique(dat2$Biotype[which(dat2$Country==uc[i])]))
if (length(which(biotypes=='Unknown'))==length(biotypes)){
biotypes2 = biotypes
} else {
biotypes2 = paste0(biotypes[which(biotypes!='Unknown')],collapse=';')
}
markers = paste0(unique(dat2$Marker[which(dat2$Country==uc[i])]),collapse=';')
out[i,2] = biotypes2
out[i,3] = markers
out[i,4] = ceiling(length(grep('SSR',markers))/length(markers))
out[i,5] = ceiling(length(grep('MEAM 1',biotypes2))/length(biotypes2))
out[i,6] = ceiling(length(grep('MED',biotypes2))/length(biotypes2))
out[i,7] = ceiling(length(grep('SNP',markers))/length(markers))
}
out$MEAM1.MED = paste(out$MEAM1,out$MED,sep='_')
world_sf = as(world,'sf') #for mapping
world_sf2 = merge(world_sf,out,by.x='CNTRY_NAME',by.y='Country',all.x=T)
st_write(world_sf2,'./shapefiles/world_winkel-tripel_whitefly.shp')
states = spTransform(readOGR(dsn='D:/Landscape_Environmental_data/National_atlas/statesp010g.shp',layer='statesp010g',verbose=F,stringsAsFactors=F),CRS(winkel_tripel))
ak_hi = as(states[which(states@data$STATE_ABBR=='AK' | states@data$STATE_ABBR=='HI'),],'sf')
st_write(ak_hi,'./shapefiles/AK_HI.shp')
#library(cowplot) # for theme_map()
#ggplot() +
# geom_sf(data = grat_sf, color = "gray80", size = 0.25/.pt) +
# geom_sf(data = world_sf, color = "white", size = 0.5/.pt) +
# coord_sf(datum = NULL) +
# theme_map()
|
b24fb52c324cd5ff917b3f7be3b173ddae825af7
|
87bc2495102f8555b1c4ec66f561c868e2d5495b
|
/man/calculaVolumeDefault.Rd
|
675e0e2ef9ce0c8cd72c4368e411b0afad5edc19
|
[] |
no_license
|
cran/Fgmutils
|
a4b716bfb5eccff5cb89133314ab18eb01047875
|
52b9c01a4ee269acc66a2efa29df8411033f0306
|
refs/heads/master
| 2020-05-21T04:22:25.850012
| 2018-11-17T23:50:22
| 2018-11-17T23:50:22
| 48,080,087
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 583
|
rd
|
calculaVolumeDefault.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/calculaVolumeDefault.R
\name{calculaVolumeDefault}
\alias{calculaVolumeDefault}
\title{calculates Volume Default}
\usage{
calculaVolumeDefault(ht, dap, ...)
}
\arguments{
\item{ht}{is list of height of individuals}
\item{dap}{is list of diameter of individuals}
\item{...}{only for compatibility with other functions}
}
\value{
will be returned a list of volume calc
}
\description{
this function calculates the volume based on the height and volume of literature of the equation
}
|
532f0b2cab0ccdb6b56659b7a86ae2f812eb5db0
|
20e30d05121195b59f3ee09a90fc6ba6922418a8
|
/Deprecated/To Dropbox/depreciated/figure.scripts/fig3.taxa.R
|
9ef2b6b0fb88c5bfd3d03082c84b9a65547d8d3c
|
[] |
no_license
|
NW-Anderson/Ancestral-Condition-Test
|
17fb7ba92221ae273cb9921655c8547761a8692f
|
c9d344b4185638e125a39ee989e27bb408e20122
|
refs/heads/master
| 2022-01-27T13:58:16.453852
| 2022-01-12T20:09:10
| 2022-01-12T20:09:10
| 187,305,273
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,860
|
r
|
fig3.taxa.R
|
##### Fig 3 #####
load('../results/UnidirectionalTaxaFPResults.RData')
load('../results/UnidirectionalTaxaPowerResults.RData')
x <- seq(from=20, to=200, by=20)
y <- vector()
for(i in 1:10){
y <- c(y, taxa.uni.power.results[1:100, i])
}
probs <- vector()
for(i in 1:10){
probs[i] <- sum(taxa.uni.power.results[1:100, i] <= .05)
}
probsfp <- vector()
for(i in 1:10){
probsfp[i] <- sum(taxa.uni.fp.results[1:100, i] <= .05)
}
load('../results/BidirectionalTaxaPowerResults.RData')
load('../results/BidirectionalTaxaFPResults.RData')
## THIS LOOP IS GENERATING WARNINGS CAN YOU COMMENT SO I CAN FIGURE OUT WHATS UP
y <- vector()
for(i in 1:10){
for(j in 1:10){
for(i in 1:100){
y[2 * (100 * (j - 1) + i - 1) + 1] <- as.numeric(gsub(",.*", "",taxa.bi.power.results[i,j]))
y[2 * (100 * (j - 1) + i - 1) + 2] <- as.numeric(substr(taxa.bi.power.results[i,j], (nchar(gsub(",.*", "",taxa.bi.power.results[i,j])) + 2),
nchar(taxa.bi.power.results[i,j])))
}
}
}
biprobs <- vector()
for(i in 1:10){
biprobs[i] <-
round(100 * sum(y[(200 * (i - 1) + 1):(200 * i)] <= .025, na.rm = T) / sum(!is.na(y[(200 * (i - 1) + 1):(200 * i)])),
digits = 0)
}
### SAME FOR THIS LOOP
y <- vector()
for(i in 1:10){
for(j in 1:10){
for(i in 1:100){
y[2 * (100 * (j - 1) + i - 1) + 1] <- as.numeric(gsub(",.*", "",taxa.bi.fp.results[i,j]))
y[2 * (100 * (j - 1) + i - 1) + 2] <- as.numeric(substr(taxa.bi.fp.results[i,j], (nchar(gsub(",.*", "",taxa.bi.fp.results[i,j])) + 2),
nchar(taxa.bi.fp.results[i,j])))
}
}
}
biprobsfp <- vector()
for(i in 1:10){
biprobsfp[i] <- round(100 * sum(y[(200 * (i - 1) + 1):(200 * i)] <= .025, na.rm = T) /
sum(!is.na(y[(200 * (i - 1) + 1):(200 * i)])),
digits = 0)
}
plot(x, (probs/100), type = 'b', xaxt="n",xlab="", ylab= "",
pch='o',cex=1.1,
main = 'Taxa Number vs Power and False Positive',
adj = 0, ylim = c(0,.8), col = 'blue', lwd = 4)
lines(x, (probsfp/100), type = 'b', pch = 'o', cex = 1.1, col = 'red', lwd = 4, lty = 1)
lines(x, (biprobs/100), type = 'b', pch = '+', cex = 1.5, col = 'blue', lwd = 4, lty = 2)
lines(x, (biprobsfp/100), type = 'b', pch = '+', cex = 1.5, col = 'red', lwd = 4, lty = 2)
abline(h = .05, lty = 2)
mtext(c(20,40,60,80,100,120,140,160,180,200), side=1,
at=c(20,40,60,80,100,120,140,160,180,200), cex=.85)
mtext("Taxa", side=1, line=1)
mtext("Percent Significant", side=2, line=2.2)
legend(x = 'topleft',
legend = c('Unidirectional Power','Bidirectional Power',
'Unidirectional False Positive', 'Bidirectional False Positive'),
col = c('blue', 'blue','red','red'), bty = 'n',
lwd = 2, lty = c(1,2,1,2))
|
c49f8a55befb639a048b68fe18da4e8d161213ec
|
6c38c5850f822a151b3930a1574d80718876e69c
|
/StatLearning for Analytics/Week 4 - Logistic Regression/server.R
|
d3576f4bb456e3b2140e4dec44c4b9ff699072e0
|
[] |
no_license
|
christianmconroy/Georgetown-Coursework
|
7eb30f7c3d20a831ade19c21177b0eb7ad30d288
|
d301800adc35cb6a509be5c75fc6c46c3263537b
|
refs/heads/master
| 2020-05-09T13:59:33.434366
| 2020-05-07T16:10:16
| 2020-05-07T16:10:16
| 181,173,259
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 524
|
r
|
server.R
|
shinyServer(function(input, output) {
library(ggplot2)
output$plot<- renderPlot({
x <- seq(0,8,length.out=50)
beta_0 <- input$beta_0
beta_1 <- input$beta_1
beta_2 <- input$beta_2
beta_3 <- input$beta_3
y_hat <- exp(beta_0 + beta_1*x +beta_2 + beta_3*x*beta_2 )
logit <- y_hat / (1 + y_hat)
df <- data.frame("X" = x, "logit" = logit)
ggplot(df, aes(x=X, y=logit)) + geom_line(colour='#3690C0', size=3) + labs(y = "p(y=1)", x="Age (Decades)") +ylim(0,1)
})
})
|
f8260c0913263b72334ef7a3d5d059eec3096792
|
f77d4ae139d960f6138e29f4e5e9e39fcba528fb
|
/R_CODES/Previous/Junk codes/rej2.R
|
8ca771c150a01c27a68006050150eab6a5531dc0
|
[] |
no_license
|
zenabu-suboi/masters_project
|
fc80eb077af8e92bf81cda94952d4dec196bb263
|
d865eb68e66d35c52229023d7aa83b78fd7518f4
|
refs/heads/master
| 2022-04-22T15:01:15.063667
| 2020-04-28T10:50:17
| 2020-04-28T10:50:17
| 179,095,292
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,988
|
r
|
rej2.R
|
### ABC rejection, we need to run it 1000000 times in the end
nreprej= 100000
tolp= 1 ### see ?ABC_rejection, provides us with the parameters that produce
### summary statistics X% closest to the target
### e.g. when we set it to 0.1, and we start with nreprej=100, we end up with 10.
#?ABC_rejection
set.seed(234)
### don't forget to run set.seed and code to get the targets on page 1 Obtaining the targets...
ABC_rej2<-ABC_rejection(model=modelABC2, prior=list(c("unif",0,1),c("unif",0,0.5)),
summary_stat_target=save_targ2, nb_simul=nreprej,
tol=tolp, progress_bar = T)
ABC_rej2$computime
### save results for rejabc0.1
Tabc0.1rej2= proc.time()
rej2abc0.1 <- abc(target = c(save_targ2),
param = ABC_rej2$param,
sumstat = ABC_rej2$stats,
tol = 0.1,
method = "rejection") ### change method here!
Tabc0.1rej2= proc.time()-Tabc0.1rej2
Tabc0.1rej2
par(mfrow=c(3,1))
plot(rej2abc0.1$unadj.values[,1],rej2abc0.1$unadj.values[,2],main="rejabc0.1, beta=1.0, gamma=0.02")
### save results for rejabc0.01
Tabc0.01rej2= proc.time()
rej2abc0.01 <- abc(target = c(save_targ2),
param = ABC_rej2$param,
sumstat = ABC_rej2$stats,
tol = 0.01,
method = "rejection") ### change method here!
Tabc0.01rej2= proc.time()-Tabc0.01rej2
Tabc0.01rej2
plot(rej2abc0.01$unadj.values[,1],rej2abc0.01$unadj.values[,2],main="rejabc0.01,beta=1.0, gamma=0.02")
### save results for rejabc0.001
Tabc0.001rej2= proc.time()
rej2abc0.001 <- abc(target = c(save_targ2),
param = ABC_rej2$param,
sumstat = ABC_rej2$stats,
tol = 0.001,
method = "rejection") ### change method here!
Tabc0.001rej2= proc.time()-Tabc0.01rej2
Tabc0.01rej2
plot(rej2abc0.001$unadj.values[,1],rej2abc0.001$unadj.values[,2],main="rejabc0.001, beta=1.0, gamma=0.02")
|
b41432d787c7e099545a893c2f0df9738566aab3
|
7670b011e2504fc6213456b2f0f5992f056470bb
|
/Lectures/Lecture_4/advanced_profiling.R
|
13d596b7278edde10fdbc2c4668cb7d98edc5adc
|
[
"MIT"
] |
permissive
|
ogencoglu/R_for_VTT
|
448f57387e4131c11d5f47f00b392ba2225e82da
|
a7f15e1feedc745cadbd7db7d43d192265c047fd
|
refs/heads/master
| 2021-01-01T03:53:28.362701
| 2016-05-15T06:31:06
| 2016-05-15T06:31:06
| 56,995,798
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,126
|
r
|
advanced_profiling.R
|
# R Lecture to VTT - Lecture 4
# Author : Oguzhan Gencoglu
# Latest Version : 11.05.2016
# Contact : oguzhan.gencoglu@tut.fi
# -------------- Advanced Profiling --------------
# Removing incomplete rows example
fake = matrix(rnorm(200000),10000,20)
fake[fake>2] = NA
f = as.data.frame(fake)
funAgg = function(x) {
res = NULL
n = nrow(x)
for (i in 1:n) {
if (!any(is.na(x[i,]))) res = rbind(res, x[i,])
}
res
}
# Call the R code profiler and give it an output file to hold results
Rprof("exampleAgg.out", line.profiling=TRUE)
y1 <- funAgg(f)
Rprof(NULL)
summaryRprof("exampleAgg.out")
funApply = function(x) {
drop = apply(is.na(x), 1, any)
x[!drop, ]
}
Rprof("exampleApply.out", line.profiling=TRUE)
y3 = funApply(f)
Rprof(NULL)
summaryRprof("exampleApply.out")
# install profvis package from github repo
devtools::install_github("rstudio/profvis")
library(profvis)
library(ggplot2)
profvis({
g <- ggplot(diamonds, aes(carat, price)) + geom_point(size = 1, alpha = 0.2)
print(g)
})
|
f6421a01cee8232af1e4f4d9a145546371846593
|
da401ba918d2fe3c7f6d558c65e660cdd1535d0e
|
/R/coxphmulti.R
|
d3d0bb4c37b490355330eb9748b4f86c5292ecdc
|
[] |
no_license
|
tomdrake/summarizer
|
84d62db144666a90d4eeb1b1ece9306e8bc9f6de
|
ee714dfe55056eeaccd286346dff6cdcd3a1963e
|
refs/heads/master
| 2021-05-09T01:59:20.619177
| 2018-01-28T17:27:46
| 2018-01-28T17:27:46
| 94,934,964
| 0
| 0
| null | 2017-06-20T21:05:09
| 2017-06-20T21:05:09
| null |
UTF-8
|
R
| false
| false
| 611
|
r
|
coxphmulti.R
|
#Survival multivariable with weights - clusters also possible
coxphmulti <- function(df.in, dependent, explanatory, weights = NULL){
require(survival)
result = list()
if (is.null(weights)){
for (i in 1:length(dependent)){
result[[i]] = coxph(as.formula(paste0(dependent, "~", paste(explanatory, collapse="+"))), data=df.in)
}
}else{
for (i in 1:length(dependent)){
result[[i]] = coxph(as.formula(paste0(dependent, "~", paste(explanatory, collapse="+"))), weights = weights, data=df.in)
}
}
result = setNames(result, dependent)
class(result) = "coxphlist"
return(result)
}
|
11ba7533ac46eaedf1dc68371884f13b931f5960
|
b7f0d300ee724bf170f08394257391ea12703945
|
/c9-data-products/plotly-demo.R
|
9529db68943bb72b126720ce0bedfe15708fdef1
|
[] |
no_license
|
TheYuanLiao/datasciencecoursera
|
c36a62d1f4af6e4cad2d9188cb9814d0d8ed6bd1
|
e227991e3ab6169f01476557a8987d1e840b5d64
|
refs/heads/master
| 2023-01-23T19:02:49.647831
| 2020-10-24T15:31:28
| 2020-10-24T15:31:28
| 281,198,019
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 221
|
r
|
plotly-demo.R
|
library(plotly)
library(shiny)
set.seed(777)
temp <- rnorm(100, mean=30, sd=5)
pressure <- rnorm(100)
dtime <- 1:100
p <- plot_ly(x=temp, y=pressure, z=dtime,
type='scatter3d', mode='markers', color=temp)
p
|
4107381cbb50e44e608efca6f60bedfc0f96f73f
|
3ec39ea137d1aaa0c7106c1ae49ddf395b5fda20
|
/R/addSetting.R
|
c51e30c5c5220686b185f1d4165aeb4b13b1ed78
|
[] |
no_license
|
mli1/safetyGraphics
|
e48c5bee150926f008d6185c764a179d5a3e5a71
|
165651d98c6894646f84884d1c9f7a24336d25f7
|
refs/heads/master
| 2023-01-22T17:00:10.267847
| 2020-01-16T14:26:14
| 2020-01-16T14:26:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,746
|
r
|
addSetting.R
|
#' Adds a new setting for use in the safetyGraphics shiny app
#'
#' This function updates settings objects to add a new setting parameter to the safetyGraphics shiny app
#'
#' This function makes it easy for users to adds a new settings to the safetyGraphics shiny app by making updates to the underlying metadata used by the package. Specifically, the function adds a row to settingsMetadata.rda describing the setting.
#'
#' @param text_key Text key indicating the setting name. \code{'--'} delimiter indicates a nested setting
#' @param label Label
#' @param description Description
#' @param setting_type Expected type for setting value. Should be "character", "vector", "numeric" or "logical"
#' @param setting_required Flag indicating if the setting is required
#' @param column_mapping Flag indicating if the setting corresponds to a column in the associated data
#' @param column_type Expected type for the data column values. Should be "character","logical" or "numeric"
#' @param field_mapping Flag indicating whether the setting corresponds to a field-level mapping in the data
#' @param field_column_key Key for the column that provides options for the field-level mapping in the data
#' @param setting_cat Setting category (data, measure, appearance)
#' @param default Default value for non-data settings
#' @param charts character vector of charts using this setting
#' @param settingsLocation path where the custom settings will be loaded/saved. If metadata is not found in that location, it will be read from the package (e.g. safetyGraphics::settingsMetadata), and then written to the specified location once the new setting has been added.
#' @param overwrite overwrite any existing setting metadata? Note that having settings with the same name is not supported and will cause unexpected results. default = true
#'
#' @export
#'
addSetting<-function(
text_key,
label,
description,
setting_type,
setting_required=FALSE,
column_mapping=FALSE,
column_type=NA,
field_mapping=FALSE,
field_column_key='',
setting_cat,
default='',
charts=c(),
settingsLocation=getwd(),
overwrite=TRUE
){
# check inputs
stopifnot(
typeof(text_key)=="character",
typeof(label)=="character",
typeof(description)=="character",
typeof(setting_type)=="character",
setting_type %in% c("character","numeric","logical"),
typeof(setting_required)=="logical",
typeof(column_mapping)=="logical",
typeof(field_mapping)=="logical",
typeof(setting_cat)=="character"
)
if(nchar(label)==0){
label = text_key
}
# create object for new setting
newSetting <- list(
text_key=text_key,
label=label,
description=description,
setting_type=setting_type,
setting_required=setting_required,
column_mapping=column_mapping,
column_type=column_type,
field_mapping=field_mapping,
field_column_key=field_column_key,
setting_cat=setting_cat,
default=default
)
# load settings metadata
settingsMetaPath <- paste(settingsLocation,"settingsMetadata.Rds",sep="/")
if(file.exists(settingsMetaPath)){
settingsMeta <- readRDS(settingsMetaPath)
}else{
settingsMeta <- safetyGraphics::settingsMetadata
}
# set chart flags for new setting
chartVars <- names(settingsMeta)[substr(names(settingsMeta),0,6)=="chart_"]
settingCharts <- paste0("chart_",charts)
for(varName in chartVars){
newSetting[varName] <- varName %in% settingCharts
}
#delete row for the specified chart if overwrite is true
if(overwrite){
settingsMeta <- settingsMeta %>% filter(.data$text_key != !!text_key)
}
# add custom chart settings and save
settingsMeta[nrow(settingsMeta)+1,] <- newSetting
saveRDS(settingsMeta, settingsMetaPath)
}
|
5e58b7a50ee617b3ed59f84eba29f8838b67f351
|
f5611051efee3fe799b5c7b17eb36a73a19bf37e
|
/man/get_stringdb.Rd
|
c16f5e7ddee4027b81f453b076e7b136fd2bfcac
|
[
"LicenseRef-scancode-proprietary-license",
"MIT",
"GPL-2.0-only"
] |
permissive
|
InfOmics/LErNet
|
975104c3845ea91079f1cd4fbfd852efa740f0d2
|
7a1a1652009fc4f99c7c18ece0bc8733a8cb482b
|
refs/heads/master
| 2021-08-17T10:32:54.744114
| 2021-04-07T16:31:10
| 2021-04-07T16:31:10
| 171,709,544
| 0
| 1
|
MIT
| 2020-10-28T15:43:40
| 2019-02-20T16:32:12
|
R
|
UTF-8
|
R
| false
| true
| 1,024
|
rd
|
get_stringdb.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/support.R
\name{get_stringdb}
\alias{get_stringdb}
\title{Retrieving of information from the STRING database}
\usage{
get_stringdb(stringdb_tax = 9606, stringdb_thr = 900)
}
\arguments{
\item{stringdb_tax}{taxa of the species. Default human (9606)}
\item{stringdb_thr}{threshold to be applied to the score on the edges of the PPI. Default threshold value 900}
}
\value{
a list
\describe{
\item{\code{ppi}}{a two columns data.frame representing the PPI network by listing its edges.}
}
}
\description{
Retrieves the PPI network form the STRING database via the STRINGdb.
STRINGdb often only associates a primary product to a gene,
thus other products are not reported.
The function also returns the proteins associated to each gene within the STRING database.
}
\examples{
library(STRINGdb)
library(igraph)
stringdb_tax = 9606
stringdb_thr = 900
ppi_network <- LErNet::get_stringdb( stringdb_tax = stringdb_tax, stringdb_thr = stringdb_thr)
}
|
6a6da3c7817a074e05862efc549d990f5ecb91e6
|
60a99dc425d9edca7b3dec562f5cf6367d9c61ec
|
/MExPosition/R/mpDOACT.STATIS.core.R
|
d34e1583f3e404a8ac71757833074ab44c3f0ed7
|
[] |
no_license
|
LukeMoraglia/ExPosition1
|
e7718ae848608f1dc3934513c6588f53f2c45a7f
|
a69da6c5b0f14ef9fd031b98c3b40b34dad5240f
|
refs/heads/master
| 2022-12-31T17:45:10.909002
| 2020-10-22T19:45:49
| 2020-10-22T19:45:49
| 255,486,130
| 0
| 1
| null | 2020-10-22T18:08:38
| 2020-04-14T02:01:12
|
R
|
UTF-8
|
R
| false
| false
| 8,860
|
r
|
mpDOACT.STATIS.core.R
|
mpDOACT.STATIS.core <- function(dataset1, column.design.1, dataset2, column.design.2)
{
num.groups <- dim(column.design.1)[1]
# cross product of dataset 1
CubeSP.1= array(0,dim=c(dim(dataset1)[1],dim(dataset1)[1],dim(column.design.1)[1]))
from = 1
for(i in 1:dim(column.design.1)[1])
{ from = sum(column.design.1[i-1,])+from
to = from + sum(column.design.1[i,])-1
CubeSP.1[,,i] = dataset1[,from:to] %*% t(dataset1[,from:to])
}
# cross product of dataset 2
CubeSP.2= array(0,dim=c(dim(dataset2)[1],dim(dataset2)[1],dim(column.design.2)[1]))
from = 1
for(i in 1:dim(column.design.2)[1])
{ from = sum(column.design.2[i-1,])+from
to = from + sum(column.design.2[i,])-1
CubeSP.2[,,i] = dataset2[,from:to] %*% t(dataset2[,from:to])
}
CubeSP2.1 <- array(CubeSP.1,dim=c(dim(dataset1)[1]*dim(dataset1)[1],dim(column.design.1)[1]))
CubeSP2.2 <- array(CubeSP.2,dim=c(dim(dataset2)[1]*dim(dataset2)[1],dim(column.design.2)[1]))
### NEED TO ADD RV HERE
# C Matrix using cross products of dataset 1 and dataset 2
CMatrix = t(CubeSP2.1) %*% CubeSP2.2
C.decomp = corePCA(CMatrix)
decomp.C = C.decomp$pdq
# contribution
ci = C.decomp$ci
#rownames(ci)=paste('assessor',1:num.groups)
if(is.null(rownames(column.design.1)))
{ rownames(ci) <- paste("Table", 1:dim(column.design.1)[1], sep = "")
table.names <- rownames(ci)
}
else
{ rownames(ci) <- rownames(column.design.1)
table.names <- rownames(ci)
}
# contribution
cj = C.decomp$cj
rownames(cj) <- rownames(ci)
# eigen vectors
P = decomp.C$p
rownames(P) <- rownames(ci)
Q = decomp.C$q
rownames(Q) <- rownames(ci)
# eigen values
D= (decomp.C$Dv)
# factor scores
G = decomp.C$p %*% diag(sqrt(D))
rownames(G) <- rownames(P)
# percent of variance explained
tau <- D/sum(D) * 100
# alpha and beta weights
alphaWeights = P[,1] / sum(P[,1])
betaWeights = Q[,1] / sum(Q[,1])
##########################################
#Compromise
##########################################
#compromise (S+)
compromiseMatrix.1 <- apply(apply(CubeSP.1,c(1,2),'*',t(alphaWeights)),c(2,3),sum)
compromiseMatrix.2 <- apply(apply(CubeSP.2,c(1,2),'*',t(betaWeights)),c(2,3),sum)
#analyze the compromise
PCA.compromise.1 <- corePCA(compromiseMatrix.1)
compromise.PCA.1 <- PCA.compromise.1$pdq
PCA.compromise.2 <- corePCA(compromiseMatrix.2)
compromise.PCA.2 <- PCA.compromise.2$pdq
#contribution
compromise.ci.1 <- PCA.compromise.1$ci
rownames(compromise.ci.1) = rownames(dataset1)
compromise.cj.1 <- PCA.compromise.1$cj
rownames(compromise.cj.1) = rownames(dataset1)
compromise.ci.2 <- PCA.compromise.2$ci
rownames(compromise.ci.1) = rownames(dataset1)
compromise.cj.2 <- PCA.compromise.2$cj
rownames(compromise.cj.2) = rownames(dataset1)
#eigen vectors
compromise.P.1 = compromise.PCA.1$p
rownames(compromise.P.1) = rownames(dataset1)
compromise.P.2 = compromise.PCA.2$p
rownames(compromise.P.2) = rownames(dataset1)
# eigen values
compromise.dd.1 = (compromise.PCA.1$Dv)
compromise.dd.2 = (compromise.PCA.2$Dv)
# factor scores
compromise.G.1 = compromise.PCA.1$p %*% diag(sqrt(compromise.PCA.1$Dv))
rownames(compromise.G.1)=rownames(dataset1)
compromise.G.2 = compromise.PCA.2$p %*% diag(sqrt(compromise.PCA.2$Dv))
rownames(compromise.G.2)=rownames(dataset1)
# % of variance explained
compromise.tau.1 <- compromise.PCA.1$Dv/sum(compromise.PCA.1$Dv) * 100
compromise.tau.2 <- compromise.PCA.2$Dv/sum(compromise.PCA.2$Dv) * 100
##########################################
# Tables: Generalized PCA of data
##########################################
# alpha weights
table.1.alphaWeights <- alphaWeights
table.2.betaWeights <- alphaWeights
# weights and masses
M.1 = rep(1/(dim(dataset1)[1]),dim(dataset1)[1])
M.2 = rep(1/(dim(dataset2)[1]),dim(dataset2)[1])
w.1 = c()
for(i in 1:length(rowSums(column.design.1)))
{ w.1 = c(w.1, rep(alphaWeights[i],rowSums(column.design.1)[i]))
}
w.2 = c()
for(i in 1:length(rowSums(column.design.2)))
{ w.2 = c(w.2, rep(betaWeights[i],rowSums(column.design.2)[i]))
}
#general PDQ
pdq.general.1 = corePCA(dataset1,M=M.1,W=w.1)
general.pdq.1 = pdq.general.1$pdq
pdq.general.2 = corePCA(dataset2,M=M.2,W=w.2)
general.pdq.2 = pdq.general.2$pdq
# contribution
table.1.ci = pdq.general.1$ci
table.2.ci = pdq.general.2$ci
# contribution
table.1.cj = pdq.general.1$cj
table.2.cj = pdq.general.2$cj
# Eigen vectors of the tables
gpdq.vectors.1 = general.pdq.1$p
gpdq.vectors.2 = general.pdq.2$p
# Eigen values of the tables
gpdq.eigenvalues.1 = (general.pdq.1$Dd)^2
gpdq.eigenvalues.2 = (general.pdq.2$Dd)^2
# Inertia
gpdq.inertia.1 = ((general.pdq.1$Dv) / sum(general.pdq.1$Dv))*100
gpdq.inertia.2 = ((general.pdq.2$Dv) / sum(general.pdq.2$Dv))*100
# Loadings of the tables
gpdq.loadings.1 = general.pdq.1$q
rownames(gpdq.loadings.1) = colnames(dataset1)
gpdq.loadings.2 = general.pdq.2$q
rownames(gpdq.loadings.2) = colnames(dataset2)
# Factor scores of the tables
gpdq.factorscores.1 = general.pdq.1$p %*% (general.pdq.1$Dd)
rownames(gpdq.factorscores.1)=rownames(dataset1)
gpdq.factorscores.2 = general.pdq.2$p %*% (general.pdq.2$Dd)
rownames(gpdq.factorscores.2)=rownames(dataset2)
# Partial Factor Scores
gpdq.partial.1 = array(0,dim=c(dim(dataset1)[1],dim(gpdq.loadings.1)[2],dim(column.design.1)[1]))
to_partial = 0
from_partial = 1
for(i in 1:dim(column.design.1)[1])
{ from = sum(column.design.1[i-1,]) + from_partial
to = sum(column.design.1[i,]) + to_partial
to_partial = to
from_partial = from
gpdq.partial.1[,,i] = dataset1[,from:to] %*% gpdq.loadings.1[from:to,]
}
gpdq.partial.2 = array(0,dim=c(dim(dataset2)[1],dim(gpdq.loadings.2)[2],dim(column.design.2)[1]))
to_partial = 0
from_partial = 1
for(i in 1:dim(column.design.2)[1])
{ from = sum(column.design.2[i-1,]) + from_partial
to = sum(column.design.2[i,]) + to_partial
to_partial = to
from_partial = from
gpdq.partial.2[,,i] = dataset2[,from:to] %*% gpdq.loadings.2[from:to,]
}
gpdq.partialFS.1 <- matrix(0,dim(dataset1)[1]*dim(column.design.1)[1],dim(gpdq.loadings.1)[2])
to.total = 0
for(i in 1:dim(column.design.1)[1])
{ from = to.total + 1
to = i*dim(gpdq.partial.1)[1]
to.total = to
gpdq.partialFS.1[from:to,]= gpdq.partial.1[,,i]
}
# rownames(gpdq.partialFS.1) = paste(rep(table.names,each=dim(data)[1]),rep(rownames(data)))
gpdq.partialFS.2 <- matrix(0,dim(dataset2)[1]*dim(column.design.2)[1],dim(gpdq.loadings.2)[2])
to.total = 0
for(i in 1:dim(column.design.2)[1])
{ from = to.total + 1
to = i*dim(gpdq.partial.2)[1]
to.total = to
gpdq.partialFS.2[from:to,]= gpdq.partial.2[,,i]
}
##########################################
# Results
##########################################
res.doact.statis.core <- list(S.1 = CubeSP.1, S.2 = CubeSP.2, C = CMatrix, ci = ci, cj = cj, eigs.vector = P, eigs = D,
fi = G, alphaWeights = alphaWeights, tau = tau,
alphaWeights = alphaWeights, betaWeights = betaWeights,
compromiseMatrix.1 = compromiseMatrix.1, compromise.ci.1 = compromise.ci.1, compromise.cj.1 = compromise.cj.1, compromise.P.1 = compromise.P.1,
compromise.eigs.value.1 = compromise.dd.1, compromise.fi.1 = compromise.G.1, compromise.tau.1 = compromise.tau.1,
compromiseMatrix.2 = compromiseMatrix.2, compromise.ci.2 = compromise.ci.2, compromise.cj.2 = compromise.cj.2, compromise.P.2 = compromise.P.2,
compromise.eigs.value.2 = compromise.dd.2, compromise.fi.2 = compromise.G.2, compromise.tau.2 = compromise.tau.2,
masses.1 = M.1,
table.partial.fi.array.1 = gpdq.partial.1, table.cj.1 = table.1.cj, table.ci.1 = table.1.ci,
table.eigs.1 = gpdq.eigenvalues.1, table.tau.1 = gpdq.inertia.1, table.eigs.vector.1 = gpdq.vectors.1,
table.loadings.1 = gpdq.loadings.1, table.fi = gpdq.factorscores.1,
table.partial.fi.1 = gpdq.partialFS.1,
masses.2 = M.2,
table.partial.fi.array.2 = gpdq.partial.2, table.cj.2 = table.2.cj, table.ci.2 = table.2.ci,
table.eigs.2 = gpdq.eigenvalues.2, table.tau.2 = gpdq.inertia.2, table.eigs.vector.2 = gpdq.vectors.2,
table.loadings.2 = gpdq.loadings.2, table.fi.2 = gpdq.factorscores.2,
table.partial.fi.2 = gpdq.partialFS.2)
return (res.doact.statis.core)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.