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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ba46edb97b7335f3623e4a22265e6450c3e1911f
|
e7723850062b82014898b1626e1c6353b407d5e8
|
/man/extract_model.Rd
|
5e88eb414d1820d1745ac4a885f29b0b38dcb8b7
|
[] |
no_license
|
d3m-purdue/d3mLm
|
79431d0ca62c1a8a7a0b18a0700c4ca88c16b526
|
11f9f3d7daa2c60fb69844868d9fad436494ffb7
|
refs/heads/master
| 2021-01-20T18:04:14.601327
| 2017-09-21T15:04:15
| 2017-09-21T15:04:15
| 90,900,432
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 649
|
rd
|
extract_model.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lm.R
\name{extract_model}
\alias{extract_model}
\title{Extract linear model diagnostics}
\usage{
extract_model(x, ..., data = stats::model.frame(x))
}
\arguments{
\item{x}{linear model object of class 'lm'}
\item{...}{items passed to update_response}
\item{data}{data to be modeled}
}
\value{
object of class 'ModelResponse'
}
\description{
Extract all information possible with broom::tidy, broom::glance, and broom::augment.
}
\examples{
radon_model <- lm(Uppm ~ typebldg + basement + dupflag, data = radon_mn)
result <- extract_model(radon_model)
result$as_json()
}
|
d69022ca27297bdf5526e7606d795dbb1f3ba8f3
|
96f7ffe9c1e24aae5f45a4de15b0e2d6e68ee477
|
/ex_14_4.R
|
b503fdd32017971cd1ae34bc9de4e215f4dc5e3b
|
[] |
no_license
|
lukaszgatarek/bayesianEconometricMethodsKoop
|
67fa714750098d71f2a3426d2d327ea3a893d8c3
|
cf08856d6f238841f1da5533b4d93ec84bd1a053
|
refs/heads/master
| 2020-03-15T01:10:41.004438
| 2018-05-17T17:51:53
| 2018-05-17T17:51:53
| 131,887,182
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,493
|
r
|
ex_14_4.R
|
# implementation of exercise 14.4 from Koop et al. Bayesian Econometric Methods
## posterior simulation in the panel probit model
rm(list = ls())
require(mvtnorm)
require(msm)
require("PerformanceAnalytics")
# simulate from the data generating process
T <- 50
# number of explanatory variables in latent variable equation (common for every i); those are variables corresponding only to beta (alpha is not included in r)
r <- 3
## select the number of individuals in the panel
# the accuracy of estimation grows with n; for low n, the accuracy is usually very poor in terms of estimating alpha parameter
n <- 400
# select beta parameter that is common across individuals
beta <- rnorm(r, 0, 1)
## select alphas which is associated with i-th individual
# to that end we need some value of alpha, which drives the distribution of alpha_i's (all alpha_i's are centered around alpha)
alpha <- rnorm(1, 0, 1)
# in the general model sigma_alpha_2 is also a model parameter, here we just assume that it is equal to 1
sigma2_alpha <- 1
alpha_i <- rnorm(n, alpha, sigma2_alpha) # for the time being sigma2_alpha is fixed at 1
# to work with the stacked, panel data structure, we need to repeat the values of each alpha_i element T times
alpha_is <- matrix(t(matrix(alpha_i, length(alpha_i), T)))
# error in the latent variable equation (stacked i-th by (i-1)-th, forming a Txn length vector)
eps <- as.matrix(rnorm(n * T, 0, 1))
# matrix of regressors (again, we stack them indivdidual by individual)
X <- matrix(rnorm(n * T * r, 0, 0.1), n * T, r) # we simulate n x T x r values and then we structure them into nT x r matrix
# having all the components, we can simulate from this data generating process according to 14.10
z <- alpha_is + X %*% beta + eps
# derive y from z
y <- (z > 0)
y[y == TRUE] <- 1
y[y == FALSE] <- 0
## implement the Gibbs sampler
# number of iterations in Gibbs sampler
nSim <- 100
# prior for beta
mubeta <- matrix(0, r, 1) # there is r values in beta vector, each corresponding to different variable x
Vbeta <- diag(r) * 100 # this is a variance beta matrix; following example in ex. 14.2 we assume diag(r) x 100
# prior for alpha
mualpha <- 0
Valpha <- 1
# arrange variables for the sampler
betaSim <- matrix(0, r, nSim) # all individuals have the same parameter vector beta
alphaiSim <- matrix(0, n, nSim) # every individual has different value
alphaSim <- matrix(0, 1, nSim) # there is a common value which drives all alpha_i's
## we neet to start the Gibbs somewhere, let us get some first z's to initialize the mcmc
# formula 14.11
for(i in 1:n){ # for each individual
for (j in 1:T){ # for each time series dimension observation
observation <- ((i-1) * T) + j # values are stack one on another [T' T' ... T']'
if (y[observation] == 0){
# sample from the truncated normal [-Inf, 0]
z[observation] <- rtnorm(1, mean = alphaiSim[i,1] + X[observation,] %*% betaSim[,1], sd = 1, lower = -Inf, upper = 0)
} else if (y[observation] == 1){
# sample from the truncated normal [0, Inf]
z[observation] <- rtnorm(1, mean = alphaiSim[i,1] + X[observation,] %*% betaSim[,1], sd = 1, lower = 0, upper = Inf)
}
}
}
## after getting some initial vector of z's, we can run the mcmc sampler
for (s in 2:nSim){
print(s)
## alpha_i's step according to the formula 14.11 and 14.12
for(i in 1:n){
D_alpha_i <- (T + 1)^(-1)
d_alpha_i <- sum(z[ ((i-1) * T + 1) : (i * T) ] - X[((i-1) * T + 1) : (i * T), ] %*% betaSim[, s-1]) + alphaSim[s-1]
alphaiSim[i, s] <- rnorm(1, D_alpha_i %*% d_alpha_i, sqrt(D_alpha_i) )
}
## beta step according to the formula 14.13
alpha_is <- matrix(t(matrix(alphaiSim[, s], length(alphaiSim[, s]), T)))
Dbeta <- solve(t(X) %*% X + solve(Vbeta) )
dbeta <- t(X) %*% (z - alpha_is) + solve(Vbeta) %*% mubeta
# draw from a respective distribution
betaSim[,s] <- t(rmvnorm(1, Dbeta %*% dbeta, Dbeta) )
## alpha step according to the fomrula 14.14
D_alpha <- (n + (Valpha)^(-1) )^(-1)
d_alpha <- sum(alphaiSim[, s]) + Valpha^(-1) * mualpha
alphaSim[s] <- rnorm(1, D_alpha * d_alpha, sqrt(D_alpha))
## z step accroding to the formula 14.11
for(i in 1:n){ # for each individual
for (j in 1:T){
observation <- ((i-1) * T) + j
if (y[observation] == 0){
# rtnorm(n, mean=0, sd=1, lower=-Inf, upper=Inf)
z[observation] <- rtnorm(1, mean = alphaiSim[i,s] + X[observation,] %*% betaSim[,s], sd = 1, lower = -Inf, upper = 0)
} else if (y[observation] == 1){
z[observation] <- rtnorm(1, mean = alphaiSim[i,s] + X[observation,] %*% betaSim[,s], sd = 1, lower = 0, upper = Inf)
}
}
}
}
## plot the densities of betas' samples vs the true value
for (i in 1:r){
plot(density(betaSim[i,]), main = paste('beta_', toString(i)))
abline(v = beta[i], col = "red")
}
## plot the densities of individual alphas samples vs the true value
for (i in 1:n){
plot(density(alphaiSim[i,]), main = paste('alpha_', toString(i)))
abline(v = alpha_i[i], col = "red")
}
# expanding window mean function
expMean <- function(i){
return(mean(alphaSim[1,1:i]))
}
# compute the expanidng mean of alpha posterior samples
expMeanCalc <- apply(matrix(1:dim(alphaSim)[2]), 1, expMean)
# plot the (exapnding) mean of the draws posterior of alpha and the true value
plot(expMeanCalc)
abline(a = alpha, b = 0, col = "red")
|
b11c3a1ee8141febd951a4064aeb42713d72f072
|
94304ae0875d0c6164922de503a12b13add2d2d1
|
/R/check_that_compiled.R
|
695974c88ecae7e9c6c184f15aaa54cf7dbdd3d9
|
[] |
no_license
|
alexander-pastukhov/eyelinkReader
|
279482e7de0ef456bfde2b8fda56b27370eee385
|
e915798bb56b2ce46883536a379d4127812fef8b
|
refs/heads/master
| 2022-10-19T22:09:20.088415
| 2022-09-27T08:53:41
| 2022-09-27T08:53:41
| 134,551,196
| 9
| 2
| null | 2023-09-05T15:58:07
| 2018-05-23T10:10:00
|
R
|
UTF-8
|
R
| false
| false
| 946
|
r
|
check_that_compiled.R
|
#' Checks whether EDF API library was present and
#' interface was successfully be compiled
#'
#' @param fail_loudly logical, whether lack of compiled library means
#' error (\code{TRUE}), just warning (\code{FALSE}), or silent (\code{NA},
#' for test use only).
#'
#' @export
#' @return No return value. Stops the computation, if compiled interface to EDF API in missing.
#' @keywords internal
#'
#' @examples
#' check_that_compiled(fail_loudly = FALSE)
check_that_compiled <- function(fail_loudly = TRUE){
# try to compile
if (!eyelinkReader::compiled_library_status() && !is.na(fail_loudly)) {
if (fail_loudly) {
stop("Failed to compile interface to EDF API, function will return NULL. Please read the manual for further details.")
} else {
warning("Failed to compile interface to EDF API, function will return NULL. Please read the manual for further details.")
}
}
eyelinkReader::compiled_library_status()
}
|
38d402366f189f2ee413993179c70638fede6c70
|
4c0d6f649306f4800bb7164e1daf04b86dcc5358
|
/IM4D_Voronoi_HSR.R
|
de457a5416b2407041bc4bbb61177574231c133b
|
[] |
no_license
|
TANGJunPro/IM4D
|
61518867f1b3d83daf0575dead19898ecff4975c
|
e3a836bae45b7556a3823bd1873cef0e3cad3f36
|
refs/heads/master
| 2022-11-25T08:24:11.494023
| 2020-07-29T04:03:04
| 2020-07-29T04:03:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,201
|
r
|
IM4D_Voronoi_HSR.R
|
#####################################
# Dummy for Dummies---Lecture 3 #
# Voronoi Diagram #
# Lecturer: SHI Shuang #
#####################################
#install.packages("ggvoronoi")
#https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/JIISNB
library(tidyverse)
library(readxl)
library(scales)
library(quantmod)
library(sf)
library(ggspatial)
library(rnaturalearth)
library(rnaturalearthdata)
library(foreign)
library(lubridate)
library(ggmap)
library(maps) #https://www.rdocumentation.org/packages/maps/versions/3.3.0
library(mapdata)
library(readr)
library(ggvoronoi)
setwd("D:/Dropbox/SOE0330/LaTex/R course/spatial analysis/China_HSR_2016_stations")
mainstation <- read_excel("China_HSR_2016_stations.xlsx")
#directly plot the dots
mainstation_sf <- mainstation %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326)
ggplot() + geom_sf(data = mainstation_sf)
chn <- ggplot2::map_data('world2', region='china')
names(chn) <- c("lon","lat", "group","order","region","subregion")
chn
#write_excel_csv(chn, "chn.csv")
chn_outline <- chn %>% filter(group %in% c("13"))
chn_outline_detailed <- map_data("china")
mainstation %>%
ggplot(aes(x=lon, y=lat)) +
theme_void(base_family="Roboto Condensed") +
geom_polygon(data=chn_outline,fill="#ffffff", color="dimgrey") +
geom_point(aes(color=speed_kph),size=0.1, alpha=0.8) +
scale_color_viridis_c(end=0.5, guide="none") +
labs(title="Each HIgh-Speed Railway Station as a Point in Year 2016") +
coord_quickmap()
mainstation %>%
ggplot(aes(x=lon, y=lat)) +
theme_void(base_family="Roboto Condensed") +
geom_polygon(data=chn_outline,fill="#ffffff", color="dimgrey") +
geom_path(stat="voronoi", size=0.1, aes(color=speed_kph)) +
coord_quickmap() +
scale_color_viridis_c(end=0.5, guide="none") +
labs(title="Voronoi Diagram with station as a seed")
mainstation %>%
ggplot(aes(x=lon, y=lat)) +
theme_void(base_family="Hiragino Sans W5") +
geom_voronoi(aes(fill=lon), size=0.05, color="#ffffff",
outline=chn_outline) +
coord_quickmap() +
scale_fill_viridis_c(end=0.8, option="magma", guide="none")
|
f5f0aa65967b99c185cb8bc3bda495b8fda6b650
|
7a816abc129b2353103cb1098555ca81e1873c44
|
/tests/testthat/test_get_gage_forecast.R
|
e0428e191be1e701abcec852439a4129fc7c0e25
|
[
"CC0-1.0"
] |
permissive
|
mpdougherty/rahps
|
22e45ef78832ba3427db082506ad90b6bdeb235e
|
b3dc72527d73aa15b62db3848e7cf985588894e5
|
refs/heads/main
| 2023-04-12T11:16:08.934332
| 2021-05-18T22:20:56
| 2021-05-18T22:20:56
| 368,174,811
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 391
|
r
|
test_get_gage_forecast.R
|
library(rahps)
library(XML)
library(xml2)
library(dplyr)
gage_id <- "canm7"
gage_file <- file.path(system.file("extdata", "canm7.xml",
package = "rahps"))
gage_forecast_df <- get_gage_forecast(gage_id, gage_file)
test_that("check data structure", {
expect_true(is.data.frame(gage_forecast_df))
expect_true(length(gage_forecast_df$gage_id) == 55)
})
|
d468b32f324121a313e2e017ef26074c61da4028
|
eb07a38895136311fe2e83789d010b42f4b73947
|
/mike/modelbased/pheno2numeric.R
|
78b4b2d066ad543e8b72b09427abaa8c5d35e204
|
[] |
no_license
|
samesense/tozerenlab
|
6f1fb94e14fe2d2f27e6ff687365e8c19f5f60c4
|
bac483ccf8fb00f7f170e789c39c9ed2f3cd75e5
|
refs/heads/master
| 2021-01-10T18:44:28.575988
| 2010-05-16T05:03:35
| 2010-05-16T05:03:35
| 32,263,874
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 544
|
r
|
pheno2numeric.R
|
pheno2numeric<-function(phenotype){
#Convert phenotype information from string format to numeric
#Inputs
#phenotype[n,1] = phenotype information for all samples
#Outputs
#List with two components:
#pheno[n] = phenotype in numeric format
#types[nphenotypes] = key linking number to string
#nphenotypes = number of unique phenotypes
types<-sort(unique(phenotype))
pheno<-rep(0,length(phenotype))
for(i in 1:length(types)){
pheno[phenotype==types[i]]<-i
names(types)[i]<-i
}
return(list(pheno=pheno,types=types))
}
|
b5e28c7bd4d8b49b24311e83370e0778ffb3b8d4
|
8289fd6c2315dd84a2abc443e56c33eb09fd6346
|
/Applied Econometrics/maxwell/replication/1_samples.R
|
c99bb03b196f39aa0bc483c0fdb1a34e8d3b8e32
|
[] |
no_license
|
elmerli/econometrics-essential
|
826f9f2f3d2f46a1d1f3b262cf25fb0161b16025
|
45d6f8d0e21c9393a97312bdaf65d19f1c3a6024
|
refs/heads/master
| 2023-08-05T00:10:56.285099
| 2020-05-14T03:16:55
| 2020-05-14T03:16:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,013
|
r
|
1_samples.R
|
# 1_samples.R
# Maxwell Austensen
# AEM Replication
# NYU Wagner
# 19-12-2016
library(tidyverse)
library(haven)
library(stringr)
library(feather)
library(knitr)
library(broom)
library(sandwich)
# load function to assign poverty threshold
source("get_pov_threshold_1990.R")
raw <- read_stata(str_c(raw_, "usa_00005.dta")) %>% zap_labels()
names(raw) <- names(raw) %>% str_to_lower()
mothers <- raw %>%
group_by(serial) %>% # Create vars requiring info on all household members (eg. standardized household income)
mutate(hh_adults = sum(age >= 18, na.rm = TRUE),
hh_children = sum(age < 18, na.rm = TRUE),
hh_head_65p = if_else(pernum == 1, if_else(age >= 65, 1, 0), NA_real_) %>% sum(na.rm = TRUE),
inc_adjuster = (hh_adults + (0.7 * hh_children)) ^ 0.7,
hh_income = if_else(hhincome == 9999999, NA_real_, hhincome),
hh_income_std = if_else(is.na(hh_income), NA_real_, hh_income / inc_adjuster)) %>%
ungroup() %>%
filter(bpl %>% between(1, 56), # US born (inc'l us territories etc.)
race == 1, # white
sex == 2, # female
age %>% between(21, 40), # age 21-40
marrno %>% between(1, 2), # ever married
agemarr %>% between(17, 26), # married age 17-26
chborn %>% between(2, 13), # ever child
marst %>% between(1, 4), # ever married but not widow
qage == 0, # not allocated: age
qmarrno == 0, # not allocated: number of marriages
qmarst == 0, # not allocated: current marital status
qagemarr== 0, # not allocated: age at first marriage
qchborn == 0, # not allocated: number of chilren ever born
qrelate == 0, # not allocated: relation to household head
qsex == 0) # not allocated: sex
children <- raw %>%
filter(momloc != 0,
stepmom == 0) %>%
group_by(serial, momloc, age, birthqtr) %>%
mutate(twin = ifelse(n() > 1, 1, 0)) %>%
group_by(serial, momloc) %>%
arrange(serial, momloc, desc(age), birthqtr) %>%
filter(row_number() == 1) %>% # keep only one child per mother
ungroup()
names(children) <- names(children) %>% str_c("_c")
sample1 <- left_join(mothers, children, by = c("serial" = "serial_c", "pernum" = "momloc_c")) %>%
filter(is.na(qage_c) | qage_c == 0, # not allocated: child's age
is.na(qsex_c) | qsex_c == 0, # not allocated: child's sex
is.na(qrelate_c) | qrelate_c == 0, # not allocated: child's relation to head of household
is.na(qbirthmo_c) | qbirthmo_c == 0, # not allocated: child's birth month
is.na(momrule_c) | momrule_c %>% between(1, 2)) %>%
mutate(marriage_ended = if_else(marst %in% c(3, 4) | marrno == 2, 1, 0),
firstborn_girl = if_else(sex_c == 2, 1, 0),
educ_yrs = if_else(higrade < 4, 0, higrade - 3),
age_birth = age - age_c,
age_married = agemarr,
marital_status = if_else(marst %in% c(1, 2) & marrno == 2, 1, 0),
urban = if_else(metarea == 0, 0, 1),
n_children = if_else(chborn <= 1, 0, chborn - 1),
n_children_hh = nchild,
hh_income_1990 = hh_income * 1.72,
pov_threshold_1990 = pmap_dbl(list(hh_adults, hh_children, hh_head_65p), get_pov_treshold_1990),
poverty_status = if_else(hh_income_1990 < pov_threshold_1990, 1, 0),
woman_inc = if_else(inctot == 9999999, NA_real_, if_else(inctot == -9995, -9900, inctot)),
nonwoman_inc = hh_income - woman_inc,
woman_earn = if_else(incwage %in% c(999999, 999998), NA_real_, incwage),
employed = if_else(empstat == 1, 1, 0),
weeks_worked = wkswork1,
hours_worked = uhrswork,
state_birth = bpl,
state_current = statefip) %>%
select(serial,
pernum,
perwt,
hh_adults,
hh_children,
hh_head_65p,
state_birth,
state_current,
marriage_ended,
firstborn_girl,
educ_yrs,
age_birth,
age_married,
marital_status,
urban,
n_children,
n_children_hh,
hh_income_std,
hh_income,
hh_income_1990,
pov_threshold_1990,
poverty_status,
nonwoman_inc,
woman_inc,
woman_earn,
employed,
weeks_worked,
hours_worked,
age,
age_c,
twin_c)
sample2 <- sample1 %>%
filter(n_children == n_children_hh,
age_c < 18,
twin_c != 1)
sample3 <- sample2 %>%
mutate(marr_len = age - age_married,
marr_yr_born = marr_len - age_c) %>%
filter(marr_yr_born %>% between(0, 5)) %>%
select(-marr_len, - marr_yr_born)
rm(raw, mothers, children)
write_feather(sample1, str_c(clean_, "sample1.feather"))
write_feather(sample2, str_c(clean_, "sample2.feather"))
write_feather(sample3, str_c(clean_, "sample3.feather"))
|
38d360ca44aa86b7c24d522dba977274e2dfcc37
|
35dd8e7238c83180c5b025d4994271627264b5f9
|
/functions.R
|
fd9d1a1ff336e00254c21213d3cfba28df475f49
|
[
"Apache-2.0"
] |
permissive
|
finarb/k3d3
|
d07ac0ca66fb67640d25b2322542840f869f7543
|
c6c5520fead2817746ac9b7e8ce6087cee4408ed
|
refs/heads/master
| 2022-04-28T08:25:00.214855
| 2022-04-14T05:24:54
| 2022-04-14T05:24:54
| 83,480,892
| 0
| 0
| null | 2017-02-28T21:27:29
| 2017-02-28T21:27:29
| null |
UTF-8
|
R
| false
| false
| 1,096
|
r
|
functions.R
|
findValues <- function(df){
#dframe <- as.data.frame(rep(1,length(which(df$parent_name == df$node_name[1]))))
dframe <- as.data.frame(df$node_name[2:(length(which(df$parent_name == df$node_name[1]))+1)])
colnames(dframe) <- "name"
dframe$name <- as.character(dframe$name)
# Go through each node, finding the names of the children
for(i in 1:20){
round = i
level <- paste0("level", round)
for(i in 1:dim(dframe)[1]){
dframe[i,level] <- paste(df$node_name[which(df$parent_name %in% strsplit(dframe[i,round], ";")[[1]])], collapse = ";")
}
}
# Trim off anything extra
dframe <- dframe[ ,which(sapply(dframe, function(x) all(x == "")) == FALSE)]
# Find the column with the maximum numbers of leaves
dd <- dim(dframe)[2]
for(i in 1:dd){
dframe[,(i+dd)] <- 1
for(j in 1:20){
dframe[j,(i+dd)] <- max(length(which(df$parent_name %in% strsplit(dframe[j,i], ";")[[1]])),1)
}
}
HT <<- max(colSums(dframe[,(dd+1):dim(dframe)[2]]))
WD <<- dd + 1
}
findValues(df)
|
d48642b26c6eb42868cf3b705e36b7abd386f0ff
|
7e57133cd2ace6c4d7673274f776696a73435712
|
/Lab6/R/Lab6-internal.R
|
ffb23e2fd5aebf260963347f4846a8e897dc27ec
|
[] |
no_license
|
5uriya/Lab6
|
612ff626077026df0ad6403f95ab2b18c9b99142
|
e1181ff15256f3bf29b0a4997d1fd236ace372c8
|
refs/heads/master
| 2021-07-21T16:34:53.159669
| 2017-10-30T15:59:12
| 2017-10-30T15:59:12
| 106,200,058
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,259
|
r
|
Lab6-internal.R
|
.Random.seed <-
c(403L, 10L, -237827430L, 1848592613L, -1317946753L, -2060409850L,
1184675728L, 1210546739L, 512143825L, 2117579648L, -668766626L,
944788905L, -1587530661L, -388723606L, -1854450420L, 1941321551L,
699376645L, -2020844868L, -910169198L, -86644595L, -1344835897L,
368437166L, 984314376L, 1135572491L, -847069463L, 2004801976L,
-1078749594L, -1777634559L, 185709971L, 2121551426L, 2007773684L,
-1122153481L, 171962349L, 1541150852L, -176652630L, -489655275L,
114681007L, -650679626L, 571123936L, -1862691805L, -239137983L,
1558746672L, -1782602674L, -1215664967L, -440538933L, 1707603322L,
98076796L, 122281151L, -1307108971L, 10482092L, -1163967614L,
-596989603L, -1676171177L, -618864834L, -1485486216L, -1842500517L,
-1358767175L, 139717128L, 321482934L, -2097895439L, -1352224221L,
-1240008078L, -158449468L, 619693703L, -1689321891L, 1421795412L,
-146816390L, 1120131525L, -274519265L, -1560279386L, -1567156176L,
-57554221L, -1530044175L, 1339870240L, 430676670L, 1782918857L,
-245552005L, -1270169014L, 1193129644L, -1065995857L, -491742875L,
41649948L, -1712551054L, 404973549L, 825215015L, 1473007694L,
-1305733976L, -612279637L, -393170999L, -1316011048L, 959324806L,
1584853857L, 772437747L, 1220110690L, -124184620L, 1783063255L,
-1846433587L, -1948901276L, 1380355658L, 399989685L, -1616287985L,
-259148778L, -375906624L, 710609027L, -1492966239L, 809650832L,
-1030784658L, 1328928537L, -759215189L, -656926310L, -2004468388L,
572609631L, 487230517L, -545712180L, 686474018L, 1279966589L,
-331526537L, 2100131742L, -229550504L, 2036613051L, 370790745L,
-1032860952L, 1415222038L, -1538354031L, -167851709L, -1661746094L,
1179014884L, -1592389337L, 1885323645L, -620590988L, -2013500838L,
-390060379L, -686164801L, -1267087546L, 1741776336L, -733333517L,
1735528209L, 828395328L, -572180706L, -627103767L, -617919205L,
-1446598870L, -1548994484L, -994209777L, 1161747269L, 991939836L,
780090194L, -2107777843L, 1891409031L, 2137991022L, 1451972936L,
-893674165L, -276610903L, -206609928L, -389525210L, -1877306815L,
1687641043L, -1424938622L, 1151720884L, 625404215L, 1845689389L,
335341892L, -358916502L, -1439639339L, -380553617L, -332913802L,
138007712L, 1921830243L, -2080055807L, -1004823184L, -1149862642L,
-1865072775L, 1786068747L, 426131514L, 1618464572L, -1401705345L,
-2032648235L, 387871212L, -1716731070L, -466072419L, -1811434217L,
1800211582L, -1218403272L, 2063794971L, 1788045433L, 1019769032L,
-1500161802L, 1217751345L, 1856397667L, -239176910L, 868285572L,
-1104590649L, 1240953757L, 479885076L, 659369402L, 718146565L,
-2072993313L, 20800614L, -1133698064L, -1778098925L, 344753L,
-1595576992L, 511091454L, 1264918153L, 1588709819L, -174361718L,
478845548L, 976344047L, -1302488027L, -877050660L, 1977080498L,
-911835731L, -773537433L, -1079157106L, 481281896L, -1780514965L,
497379593L, -289734760L, -739113274L, 965235745L, -406290253L,
936172066L, 906648596L, -196915049L, 807281293L, 1577022372L,
-1573646966L, 1587231221L, 811390031L, -512920324L, -461660780L,
-1499172030L, 647965184L, 1919641660L, -240512432L, 1902776482L,
-1591991480L, -1963324916L, -1490576676L, -1939910574L, 1715252352L,
-953358508L, -1419063320L, 780862202L, 626476880L, -599841748L,
833378676L, -312209774L, -383770016L, 2096189580L, -1764388512L,
-801482526L, -121656152L, -1143085364L, 1473321468L, 2065652658L,
-883842064L, 2094256580L, 938282328L, 326001018L, -67669584L,
-1731622468L, 1677475412L, 908122562L, 1708286752L, 1225077692L,
1749954640L, -16524318L, -1316061336L, -439437492L, 889687804L,
-1003317518L, -616121088L, 639274100L, -1629958648L, -1732655686L,
-218827312L, -1187498004L, 1728957332L, -816101166L, 1047520352L,
-403665588L, 197038880L, -1652344190L, -84475416L, 131054572L,
461536828L, -691788174L, 1377282928L, -172892892L, -818759112L,
-2017922662L, -1305940528L, -2010577476L, -1360892268L, -1050090878L,
637722048L, -2061682884L, 948843152L, -1505954014L, -1591003640L,
1084130060L, -2000157796L, -506160110L, 31648640L, 980130580L,
2094167336L, -1963970502L, -1229765680L, -2063992212L, -752628684L,
97300626L, -1858520736L, -1369023156L, 900224480L, -1262101598L,
1397054376L, 521100428L, -1120128068L, 1491870834L, -359643152L,
-1780865980L, -1464776616L, -1560707014L, 1649068144L, 1516142140L,
-25467116L, -993260862L, 1830572768L, -406092676L, -505819952L,
-1302998110L, -780464600L, -10616564L, -1979643972L, -1626951374L,
730912960L, -2073947596L, -1549542712L, 925663930L, 1001671824L,
1193019116L, -482879916L, -658610542L, -1155160288L, -893192244L,
-814978848L, 1088835266L, 504353832L, 126884780L, 396151484L,
-342302222L, 1970005552L, 196147108L, 770818488L, 680270682L,
1072338064L, -1508369540L, 1595612948L, -774382270L, 2017922816L,
512146364L, 223747920L, 1405804834L, -1576359352L, -115927028L,
1391594588L, -377024046L, 21730816L, -1831587500L, 588816616L,
93704442L, -431528240L, 235424044L, 429947124L, 1435200914L,
-1334277792L, 1019643916L, 1988504288L, -338746782L, 1583200936L,
-414860724L, 470927228L, 1211714866L, 1198204528L, 459291460L,
-1721088040L, 531095418L, -844370384L, -784459844L, 1120507476L,
-297744318L, 610091168L, 1891315388L, -1976186416L, -1310219422L,
1828668136L, -1875558196L, 1163969020L, 1956243954L, -1578812800L,
1625978356L, 1323935368L, -456941766L, -1775385776L, -244337556L,
1978743188L, -1274387374L, -575428128L, -1962640180L, -1229869920L,
1184159106L, -2129452824L, -947716372L, -1998287556L, 1257012338L,
122871920L, 551417892L, 725167160L, 255817498L, -1619018544L,
1036670780L, -1443014764L, -1135850622L, -750865984L, -307376580L,
1045505424L, 1403512354L, 1505860872L, 1560675980L, -812460260L,
1723244690L, 201099648L, 1498144276L, -745763032L, -660712902L,
752047568L, 1825638764L, 1740186548L, -705427438L, 1132768736L,
862683084L, 979099872L, 1717098530L, 1793278248L, -169755124L,
-1770528964L, -368133134L, -87774480L, 946710084L, 637690456L,
932601658L, -1332595216L, -1149038916L, -495003372L, 1275476674L,
421456842L, -460970776L, 1488459729L, 140331459L, -551677244L,
-947097230L, -628442041L, -2003554287L, 767474070L, -1519829772L,
1757738629L, 2060664783L, 931573448L, -1140373658L, -1397736045L,
1394319093L, 2030780114L, 183839008L, 902531337L, -1361437125L,
-1321987188L, -2063879654L, 1124823695L, -820912679L, 20038254L,
969134588L, -1020935315L, -1033687785L, -1736554272L, 498265790L,
-81462133L, -2138080499L, 61344570L, 467231608L, -1745178335L,
1809635795L, -332363532L, 1247693186L, 825777175L, -713774367L,
1409020966L, 414601508L, 580653525L, -72594049L, -2050345960L,
-1090823370L, 568450499L, -751111163L, 701812642L, 1795345296L,
1028968249L, 933673963L, 1365159132L, 1689023754L, 1232600063L,
-1938178487L, -1318278178L, 520819596L, 1166168925L, 1426428775L,
1648261264L, -1667455314L, 1757856603L, -779562179L, 2018564522L,
-1312704952L, 49514097L, 2018605027L, 1859355364L, 1129634322L,
1269337575L, -2134861391L, -1997066250L, -1113656812L, 716668197L,
1155730991L, -474022936L, 965119174L, 475249011L, -2129460779L,
1833260466L, -671962240L, -110350487L, -1341250597L, 2002258732L,
1774605626L, 926329839L, 934706809L, -747239154L, -418653988L,
-1056977075L, -1998373193L, 1614097472L, -1703090914L, 1983348715L,
1251296109L, -1552346662L, -1382134888L, 597127681L, 524379059L,
2142733012L, -1343724574L, 968734327L, -862081087L, 797429062L,
-1230447484L, 1230004789L, 1443932703L, 637201784L, -1936823210L,
-27561757L, 360437413L, -1084449982L, -1648660176L, 1664141657L,
-282408245L, 353415996L, -1064887446L, -31622753L, 1030254633L,
-540292418L, 974556076L, 1283700989L, 1472836679L, -1642376400L,
1461408846L, -1662437253L, 984316893L, 22028810L, 894322472L,
483514769L, 984637315L, -131394428L, 1956041394L, -579271161L,
-25360815L, 1807007190L, 1340379316L, 2104806597L, 637079055L,
1192691336L, 2025941926L, -191519917L, -1573950283L, -1925412334L,
1368180704L, -1675699639L, -26816389L, -1809809076L, 1672549594L,
995644623L, 103121049L, 320937134L, 788375996L, -1501195731L,
864150999L, -839013344L, -329608834L, -284737717L, -176650931L,
1628031866L, 1856622008L, 2122903393L, 1253263123L, -1694441676L,
-16675518L, 772227415L, 1272286369L, 288626022L, 1032406193L)
|
6830f895a78495e749e6ee7abf300de0d5a8267c
|
c9e0c41b6e838d5d91c81cd1800e513ec53cd5ab
|
/man/gdkDisplayPointerIsGrabbed.Rd
|
dd53ce12c69ad4addaf0c7c0fc6cc239e554dacc
|
[] |
no_license
|
cran/RGtk2.10
|
3eb71086e637163c34e372c7c742922b079209e3
|
75aacd92d4b2db7d0942a3a6bc62105163b35c5e
|
refs/heads/master
| 2021-01-22T23:26:26.975959
| 2007-05-05T00:00:00
| 2007-05-05T00:00:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 448
|
rd
|
gdkDisplayPointerIsGrabbed.Rd
|
\alias{gdkDisplayPointerIsGrabbed}
\name{gdkDisplayPointerIsGrabbed}
\title{gdkDisplayPointerIsGrabbed}
\description{Test if the pointer is grabbed.}
\usage{gdkDisplayPointerIsGrabbed(object)}
\arguments{\item{\code{object}}{[\code{\link{GdkDisplay}}] a \code{\link{GdkDisplay}}}}
\details{ Since 2.2}
\value{[logical] \code{TRUE} if an active X pointer grab is in effect}
\author{Derived by RGtkGen from GTK+ documentation}
\keyword{internal}
|
0dd78213a481911b013d3b851624a01ac1ca5e12
|
ece0486d37f96aa4b1d1537b04320b1fd427d51d
|
/R/select.cov.R
|
ea7ff7659ffb9d71a15312be1bcc60d3c00aba94
|
[] |
no_license
|
superggbond/multilinear
|
55e258a41b32fe18bfe9d7cd8a0f5d7d09124696
|
f3d4ae04a9eb81b664df1487537916973d8bfabd
|
refs/heads/master
| 2023-01-22T14:43:18.801191
| 2020-11-27T02:31:07
| 2020-11-27T02:31:07
| 316,322,015
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 538
|
r
|
select.cov.R
|
#'select.cov
#'
#'Select covariates passing a given threshold of significance
#'
#'@param res the result object from mlr function
#'@param alpha the given threshold of p-value, default is 0.05
#'
#'@return A vector of names of selected covariates
#'
#'@examples
#'data(longley)
#'obj = mlr("Employed", c("GNP.deflator","GNP","Unemployed","Armed.Forces","Population"), longley, 5)
#'select.cov(obj)
#'
#'@export
#'
select.cov = function(res, alpha=0.05) {
covs = rownames(res$summary[res$summary[,"p.value"] <= alpha,])
return(covs)
}
|
b8399eb6289b76d052b9b52360588f5b85ad8640
|
63caf4d9e0f4b9c9cb5ab101f5795a94f27d575d
|
/man/swSoundAbsorption.Rd
|
571e99114785e4f9a71bdb1103978bf07a34bd87
|
[] |
no_license
|
marie-geissler/oce
|
b2e596c29050c5e2076d02730adfc0c4f4b07bb4
|
2206aaef7c750d6c193b9c6d6b171a1bdec4f93d
|
refs/heads/develop
| 2021-01-17T20:13:33.429798
| 2015-12-24T15:38:23
| 2015-12-24T15:38:23
| 48,561,769
| 1
| 0
| null | 2015-12-25T01:36:30
| 2015-12-25T01:36:30
| null |
UTF-8
|
R
| false
| false
| 2,161
|
rd
|
swSoundAbsorption.Rd
|
% vim:textwidth=80:expandtab:shiftwidth=2:softtabstop=2
\name{swSoundAbsorption}
\alias{swSoundAbsorption}
\title{Seawater sound absorption in dB/m}
\description{Compute the sound absorption of seawater, in dB/m}
\usage{swSoundAbsorption(frequency, salinity, temperature, pressure, pH=8,
formulation=c("fisher-simmons", "francois-garrison"))}
\arguments{
\item{frequency}{frequency of sound in Hz}
\item{salinity}{salinity in PSU}
\item{temperature}{\emph{in-situ} temperature [\eqn{^\circ}{deg}C], defined
on the ITS-90 scale; see \dQuote{Temperature units} in the documentation for
\code{\link{swRho}}.}
\item{pressure}{water pressure in dbar}
\item{pH}{seawater pH}
\item{formulation}{specify the formulation to use; see references}
}
\details{Salinity and pH are ignored in this formulation. Several formulae may
be found in the literature, and they give results differing by 10 percent,
as shown at [3] for example. For this reason, it is likely that more
formulations will be added to this function, and entirely possible that the
default may change.}
\value{Sound absorption in dB/m.}
\examples{
## Fisher & Simmons (1977 table IV) gives 0.52 dB/km for 35 PSU, 5 degC, 500 atm
## (4990 dbar of water)a and 10 kHz
alpha <- swSoundAbsorption(35, 4, 4990, 10e3)
## reproduce part of Fig 8 of Francois and Garrison (1982 Fig 8)
f <- 1e3 * 10^(seq(-1,3,0.1)) # in KHz
plot(f/1000, 1e3*swSoundAbsorption(f, 35, 10, 0, formulation='fr'),
xlab=" Freq [kHz]", ylab=" dB/km", type='l', log='xy')
lines(f/1000, 1e3*swSoundAbsorption(f, 0, 10, 0, formulation='fr'), lty='dashed')
legend("topleft", lty=c("solid", "dashed"), legend=c("S=35", "S=0"))
}
\references{[1] F. H. Fisher and V. P. Simmons, 1977. Sound absorption in sea
water. J. Acoust. Soc. Am., 62(3), 558-564.
[2] R. E. Francois and G. R. Garrison, 1982. Sound absorption based on
ocean measurements. Part II: Boric acid contribution and equation for
total absorption. J. Acoust. Soc. Am., 72(6):1879-1890.
[3] \url{http://resource.npl.co.uk/acoustics/techguides/seaabsorption/}
}
\author{Dan Kelley}
\keyword{misc}
|
3187e0a28e885b43685f8b0607b61206a08bdc9c
|
f6d161ff467ede155da635bb9e69ba99cc53b601
|
/man/bball.Rd
|
dfe2616c03eaf6f1e81e2f36f7d7bda238400c9d
|
[] |
no_license
|
jalapic/ratingsR
|
09ea74787c952b07fbedcd6e26ac5e012f3c4e0b
|
e3acadb745838c5e297ed4ce28eaa11efbd6bd3c
|
refs/heads/master
| 2020-05-22T05:33:36.742972
| 2017-03-11T20:27:07
| 2017-03-11T20:27:07
| 84,674,052
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 494
|
rd
|
bball.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/bball.R
\docType{data}
\name{bball}
\alias{bball}
\title{Example Basketball Results dataframe}
\format{A dataframe with 10 rows and 4 variables:
\describe{
\item{team1}{Home team name}
\item{team2}{Visiting team name}
\item{t1}{Points scored by home team}
\item{t2}{Points scored by visiting team}
}}
\usage{
bball
}
\description{
Sample results from Hypothetical Basketball tournament
}
\keyword{datasets}
|
713856a98bb930e5b23ef8940e0d4152c7bcb6eb
|
3b62fb6cfb2a9de90945a98849fd9354751d4432
|
/results/assignments/Assignmnent_corrected.R
|
06b6a17191f77c50a39509a8e8d930f57ea68261
|
[] |
no_license
|
Rajani462/eda_rhine
|
490b2e9e55eaabff28103b91285f81d1979edf3e
|
95cdefc003f26c49e4d948d0716845d4fd527f67
|
refs/heads/master
| 2022-05-10T11:57:15.604207
| 2022-03-23T08:53:54
| 2022-03-23T08:53:54
| 253,453,477
| 0
| 0
| null | 2020-04-06T09:36:45
| 2020-04-06T09:36:44
| null |
UTF-8
|
R
| false
| false
| 3,599
|
r
|
Assignmnent_corrected.R
|
#rewtite in a claen code format
library(data.table)
temperatures <- c(3,6,10,14)
weights <- c(1,0.8,1.2,1)
multiplier <- function(x, y) {
x * y
}
temp_wgt <- multiplier(temperatures,weights)
#Explorer’s Questions Answers
#1.How big is the Rhine catchment (km2)?
catchment_area <- 185000 #km2
catchment_area <- 18500 * 1000 ^ 2 #(m2)
#2.If it rained for one full day over the whole catchment area at 5mm/hour and all the precipitated water ended up in the river, how much would be the increase in the average river runoff?
rain_hour <- 5 #mm / m2 h (5 mm correspond to surface of 1 m2)
rain_day <- rain_hour * 24 /1000 # rain in m/ m2 day
water_over_catchment <- catchment_area * rain_day #m3 / day
river_runoff <- 2900 #m3 / s
river_runoff_day <- river_runoff * 60 * 60 * 24 #m3/d
#The water that fell over the catchment in a single day is
water_over_catchment / river_runoff_day
#3.How much time does a rain drop falling at Alpine Rhine need to reach the ocean? Write a script that performs the calculation.
river_length <- 1233000 #m
river_depth <- 30 #m - assumption 1
river_width <- 200 #m - assumption 2
water_velocity <- river_runoff / (river_depth * river_width) #m/s - Velocity = Flux / Area
time_to_sea <- river_length / water_velocity #s - Time = Length / Velocity
time_to_sea <- time_to_sea / (60 * 60 * 24) #days or about a month.
#4.
#a.Which other hydroclimatic changes reported in the article and not discussed above?
# Ans: There is a major shift of the climatic variables in the entire Rhine basin. These include mainly temperature and precipitation. Higher temperatures will reduce the amount of snow accumulation during winter and evapotranspiration in summer months. Winter precipitation is expected to increase, while it may decrease in summer months.
#b.Can you detect three assumptions made by Middelkoop et al. (2001)?
#Ans: Assumptions around modelling of temperature in climate models, human use of water resources will be similar, CO2 emissions scenario (2.5 degrees temperature increase), percentage of precipitation increase has been evenly distributed in all months, number of days with precipitation remains unchanged (it does not rain more or less often).
#c.Why Middelkoop and his colleagues made this study? Why is it important? For example, the reason for searching for a way to the Orient was that Ottoman Empire monopolized the trade routes across Asia.
#Ans:The study motivation is the consequences of hydroclimatic change to: -winter sports in Alps -flood defense -inland navigation -hydropower generation -water availability for industry, agriculture and domestic use -floodplain development
#d.Are there other studies that have a similar analysis over Rhine, or a similar hypothesis in other regions? (hint: use google scholar or web of science/scopus)
#Ans: Yes.
#https://www.mdpi.com/2073-4441/9/9/684
#https://bioone.org/journals/ambio-a-journal-of-the-human-environment/volume-33/issue-4/0044-7447-33.4.235/Climate-Change-Effects-on-River-Flow-to-the-Baltic-Sea/10.1579/0044-7447-33.4.235.short
#https://www.sciencedirect.com/science/article/pii/S0022169401003481?via%3Dihub
#e. Is there any evidence in the news about low or high flow events of Rhine since 2000?
#Ans :Yes
#https://dredgingandports.com/news/2019/billions-lost-due-to-rhine-traffic-decline-during-low-water/
#https://www.eia.gov/todayinenergy/detail.php?id=37414
#https://www.nytimes.com/2018/11/04/world/europe/rhine-drought-water-level.html
#https://www.cnbc.com/2019/07/31/low-water-levels-in-the-river-rhine-could-create-havoc-for-germanys-economy.html
|
968411ce615b01f4fb1ddda75f1f522f5f088940
|
8cad150740551138011a538485bd487163de2562
|
/Modulo 3 (Aplicaciones Interactivas Web)/Clase 1/Ejemplo3/app.R
|
b306c9f85847902350f38e990fef1f6319008692
|
[] |
no_license
|
MathConsultoresEcuador/Escuela-de-Software-Libre-EPN-
|
9d4fd7c5316abb819bb6561f2a440760d67ddc6c
|
4b0ff9bdd28ba1a4564268d0282a9574700d4d11
|
refs/heads/master
| 2021-04-26T23:46:47.285808
| 2018-05-21T04:37:55
| 2018-05-21T04:37:55
| 123,854,651
| 2
| 3
| null | null | null | null |
UTF-8
|
R
| false
| false
| 222
|
r
|
app.R
|
library(shiny)
ui = fluidPage(
titlePanel("Titulo de la App"),
fluidRow(
column(6,wellPanel("Entrada prueba")),
column(6,"Salida prueba")
)
)
server= function(input,output){
}
shinyApp(ui,server)
|
f1d50604be3372419b27827fc105fd08aed7df6a
|
8d3802e95db4894cb52c6070be475476d49c6cd5
|
/aaplKmean.R
|
7dc70e2df00b4419f91a0f8b809486897bd25fe3
|
[] |
no_license
|
c3h3/RSummer
|
31c82001bf516acc81b70e8fe424df2f6ce9b67e
|
693b8b69dc2d69612d9b7da047499f4206a965a6
|
refs/heads/master
| 2020-04-30T18:58:47.358593
| 2016-07-18T14:28:53
| 2016-07-18T14:28:53
| 63,615,446
| 1
| 2
| null | 2016-07-18T15:36:23
| 2016-07-18T15:36:23
| null |
UTF-8
|
R
| false
| false
| 550
|
r
|
aaplKmean.R
|
AAPL = read.csv("AAPL.csv")
K = 3
id = c(2,6)
X = AAPL[,id]
for( i in 1:length(X[1,]))
{
X[,i] = (X[,i] - mean(X[,i])) / sd(X[,i])
}
centers = X[1:K,]
result = kmeans(X, centers, algorithm = "MacQueen")
print(result$centers)
mat = data.frame()
mat = cbind(X, result$cluster)
for( i in 1:K )
{
id = which(mat$`result$cluster`==i)
plot(X$AAPL.Volume[id], X$AAPL.Open[id], col = i,
xlim=c(min(X$AAPL.Volume),max(X$AAPL.Volume)),
ylim=c(min(X$AAPL.Open),max(X$AAPL.Open)))
par(new=T)
}
points(result$centers, col="blue", pch = 8)
|
c3429abc66ddfb2eca2ba09f3838260a7f9e1174
|
c0f05ce4420f75549c7fa080c288765274c864a0
|
/data.R
|
d8e8bbd84b2099e48591bf82d61e8ec51eeea9ac
|
[] |
no_license
|
xulong82/Lupus
|
2040bffe26acdf492e71895ca55236d41fcfb48d
|
34bae6cb5722cefb8ed5e6cea429c1918af5e748
|
refs/heads/master
| 2021-01-10T21:56:33.582643
| 2018-05-24T15:55:20
| 2018-05-24T15:55:20
| 30,125,168
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,557
|
r
|
data.R
|
rm(list = ls())
setwd("~/Dropbox/GitHub/Lupus")
fname <- list.files(path = "/data/xwang/Lupus/RSEM_BXSB", pattern = "*.genes.results")
fname <- list.files(path = "/data/xwang/Lupus/RSEM_B6", pattern = "*.genes.results")
gene_expression <- lapply(fname, function(x) { cat(x, "\n")
# filepath = file.path("/data/xwang/Lupus/RSEM_B6", x)
filepath = file.path("/data/xwang/Lupus/RSEM_BXSB", x)
read.delim(filepath, stringsAsFactors = F)[, -2]
}); names(gene_expression) <- gsub("_Y.*", "", fname)
gene_expression_tpm <- sapply(gene_expression, function(x) x$TPM)
rownames(gene_expression_tpm) <- gene_expression[[1]]$gene_id
gene_expression_cnt <- sapply(gene_expression, function(x) x$expected_count)
rownames(gene_expression_cnt) <- gene_expression[[1]]$gene_id
setwd("~/Dropbox/GitHub/Lupus/BXSB(rnaseq)")
save(gene_expression_tpm, file = "gene_expression_tpm.rdt")
save(gene_expression_cnt, file = "gene_expression_cnt.rdt")
save(gene_expression_tpm, file = "gene_expression_tpm_b6.rdt")
save(gene_expression_cnt, file = "gene_expression_cnt_b6.rdt")
list.files()
sample <- read.csv("trim.sh.o622832", stringsAsFactors = F, header = F)
sample <- gsub("_GES.*", "", sample$V1[2:8])
trim <- read.csv("trim.sh.e622832", stringsAsFactors = F, header = F)
trim <- trim$V1[grep("^Input", trim$V1)]
trim <- gsub(".*\\(", "", gsub("%.*","", trim)) %>% as.numeric
files <- list.files("log_rsem_b6", pattern = ".sh.e")
align_b6 <- lapply(files, function(x) read.csv(paste0("log_rsem_b6/", x), stringsAsFactors = F, header = F))
align_b6 <- lapply(align_b6, function(x) x$V1[grep("at least one", x$V1)])
align_b6 <- sapply(align_b6, function(x) gsub(".*\\((.*)%.*", "\\1", x)) %>% as.numeric
files <- list.files("log_rsem_pseudo_bxsb", pattern = ".sh.e")
align_bxsb <- lapply(files, function(x) read.csv(paste0("log_rsem_pseudo_bxsb/", x), stringsAsFactors = F, header = F))
align_bxsb <- lapply(align_bxsb, function(x) x$V1[grep("at least one", x$V1)])
align_bxsb <- sapply(align_bxsb, function(x) gsub(".*\\((.*)%.*", "\\1", x)) %>% as.numeric
df <- data.frame(Sample = sample, Trim = trim, B6 = align_b6, BXSB = align_bxsb)
df <- df[c(4, 2, 5, 7, 3, 6, 1), ]
pdf("pipeline.pdf", width = 8, height = 5)
plot(df$Trim, type = "b", col = "black", xaxt = "n", xlab = "", ylab = "%", ylim = c(70, 100))
lines(df$B6, type = "b", col = "blue")
lines(df$BXSB, type = "b", col = "red")
legend("topright", c("Trim","Align(B6)","Align(BXSB)"), fill = c("black", "blue", "red"), horiz = TRUE)
axis(1, at = 1:7, labels = gsub("BXSB_", "", df$Sample))
dev.off()
|
6557de1252ad53c90fcca40fe510e1ce35b95c17
|
d161a144cca6f876557c5f716d43e4fc40fe0eb9
|
/tests/testthat/test_prior_precision.R
|
c35be3ee39f2a3e91c536910d448bdd7a0bb1b6b
|
[] |
no_license
|
SimoneTiberi/BANDITS
|
d57c02cf85ec56c87900265ed3264d106480640d
|
3c42091edf5533197695b2d8bf2a1e22d7cc754d
|
refs/heads/master
| 2022-06-19T01:23:45.396288
| 2022-05-20T14:56:55
| 2022-05-20T14:56:55
| 178,011,248
| 19
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 648
|
r
|
test_prior_precision.R
|
test_that("prior_precision() works faultlessly.", {
gene = rep(LETTERS[1:2], each = 3)
transcript = LETTERS[1:6]
gene_tr_id = data.frame(gene = gene, transcript = transcript)
# 2 samples, 6 transcripts
counts <- 10 * matrix(1:6, nrow=6, ncol=2, byrow = FALSE)
rownames(counts) = transcript
precision = prior_precision(gene_to_transcript = gene_tr_id,
transcript_counts = counts,
n_cores = 2)
expect_is(precision, "list")
expect_is(precision$prior, "numeric")
expect_is(precision$genewise_log_precision, "numeric")
expect_true(length(precision$prior) == 2)
})
|
8a633645c61324b0b7b9303e1be25e2a09bc1c50
|
ad5087b0c611e7cd4295d24360ae5cff1aac13b3
|
/R/draw_graphs_top200.R
|
5a40a604b15d6097c255e2303442ae7a82c8ee28
|
[] |
no_license
|
SGMAP-AGD/exploreDataGouv
|
600e193cb5966b89edbeb7f1445a0bdd8ebc4e59
|
0fe91a42103522b7c5bc26fa841b1dac38638f65
|
refs/heads/master
| 2021-04-26T14:31:25.199179
| 2016-02-11T17:27:46
| 2016-02-11T17:27:46
| 51,451,641
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 727
|
r
|
draw_graphs_top200.R
|
library(ggplot2)
load("data/df_data_top200.Rda")
gg_data_followers_top20 <- df_data_top200 %>%
mutate(followers_n_rank = rank(-followers_n, ties.method = "first")) %>%
arrange(desc(followers_n)) %>%
slice(1:20) %>%
ggplot() +
geom_point(
mapping = aes(
x = followers_n,
y = reorder(dataset_title, -followers_n_rank)
),
color = "tomato"
) +
scale_y_discrete(name = "Jeu de données (classés par rang)") +
scale_x_continuous(name = "Nombre de followers",
limits = c(0,60))
gg_data_followers_top20
ggsave(plot = gg_data_followers_top20,
file = "output/data_followers_top20.png",
width = 294,
height = 294/2, units = "mm"
)
|
f7ec3af4a5059d124548e5985c24b89c1938abf0
|
2b106b4488e294b561de4cdd8492d5341229d6d4
|
/man/set_freeze_model.Rd
|
b906e7c7a7b54c28d9102a6d573db8fc50cea24a
|
[
"Apache-2.0"
] |
permissive
|
ysnghr/fastai
|
120067fcf5902b3e895b1db5cd72d3b53f886682
|
b3953ad3fd925347362d1c536777e935578e3dba
|
refs/heads/master
| 2022-12-15T17:04:53.154509
| 2020-09-09T18:39:31
| 2020-09-09T18:39:31
| 292,399,169
| 0
| 0
|
Apache-2.0
| 2020-09-09T18:34:06
| 2020-09-02T21:32:58
|
R
|
UTF-8
|
R
| false
| true
| 266
|
rd
|
set_freeze_model.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/GAN.R
\name{set_freeze_model}
\alias{set_freeze_model}
\title{set_freeze_model}
\usage{
set_freeze_model(m, rg)
}
\arguments{
\item{m}{m}
\item{rg}{rg}
}
\description{
set_freeze_model
}
|
93546d2f75f3329148b12803a183611afedf0fa8
|
914b474ae1536940fed953c14659ec3b3c1ca2e2
|
/man/reorderFactors.Rd
|
a71fc83facb1d8f373cdfa004f6c26250c0ce6a2
|
[] |
no_license
|
neuhier/rospd
|
74a16cd4b2cbce36fd954272e9eba157bb076f2a
|
503b6e9fcbf856559e53507312f1d03370f75c8c
|
refs/heads/master
| 2020-04-01T20:14:33.460189
| 2018-10-29T14:23:37
| 2018-10-29T14:23:37
| 153,595,141
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 719
|
rd
|
reorderFactors.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/doeDesign.R
\name{reorderFactors}
\alias{reorderFactors}
\title{Function to reorder the factors in a DOE from hard to change to easy to change.}
\usage{
reorderFactors(doe)
}
\arguments{
\item{doe}{An object of class \code{\link{doeDesign-class}}.}
}
\value{
The same object that was passed as argument just with sorted factors.
}
\description{
This function is supposed to be used internally. Mostly the \code{\link{GenerateOptimalDesign}}-functions
expects that the factors are sorted from hard to change to easy to change. This happens automatically
when a design is created using \code{\link{GenerateNewDoeDesign}}.
}
|
3af000551e87b006c5fb8229c41a396556bdf55f
|
ae2163d4f32495d07d1405b69a27f51c7ea77bd1
|
/run_analysis.R
|
1266ac86ceedf3c5adbdfc591435c50faf383184
|
[] |
no_license
|
ehines623/GettingAndCleaningDataCourseProject
|
cc5d827fc4f31d99ec66e8a5ac9af48bd8722a87
|
56a55178bae4f6789f03660ac4a0a39f9631c771
|
refs/heads/master
| 2020-03-28T19:41:58.444055
| 2014-12-22T00:17:34
| 2014-12-22T00:17:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,048
|
r
|
run_analysis.R
|
## run_analysis.R
## Script to run analysis for programming assignment for Getting and Cleaning
## Data course
library(dplyr)
#read in all of the data
X_test <- read.table("./data/test/X_test.txt")
Y_test <- read.table("./data/test/y_test.txt")
subject_test <- read.table("./data/test/subject_test.txt")
X_train <- read.table("./data/train/X_train.txt")
Y_train <- read.table("./data/train/y_train.txt")
subject_train <- read.table("./data/train/subject_train.txt")
#join the test and training samples
X <- rbind(X_test, X_train)
Y <- rbind(Y_test, Y_train)
subject <- rbind(subject_test, subject_train)
feature_labels <-read.table("./data/features.txt", stringsAsFactors= FALSE)
feature_names<-make.unique(feature_labels[,2])
feature_names <-gsub('\\()', '', feature_names)
feature_names <-gsub('-','.',feature_names)
colnames(X)<- feature_names
#only select the mean and std values (excluding meanFreq)
X_sub <- select(X,contains("mean", ignore.case = FALSE), contains("std")
, -contains("meanFreq"))
# do some cleanup
rm(X_test,Y_test,subject_test,X_train,Y_train,subject_train, X)
#give some labels to what will be the first 2 columns
colnames(Y) <- "Activity"
colnames(subject) <- "Subject"
#add the subject and activity colums to the table
all_measurements <- cbind(subject, Y, X_sub)
#get the useful labels for the data frame from the text files
activity_labels <- read.table("./data/activity_labels.txt")
colnames(activity_labels) <- c("Number","Name")
#sub activity numbers with the descriptive names
all_measurements$Activity <- factor(all_measurements$Activity,
activity_labels$Number,
activity_labels$Name)
#group the measurements by subject and activity (30 subjects x 6 activities)
grouped <- group_by(all_measurements, Subject, Activity)
#take the average of all the measurement columns
final_table <- summarise_each(grouped, funs(mean))
#output the final table
write.table(final_table, file = "tidy_data.txt",row.names = FALSE)
|
ade33c17250787ace775d26043c71444f1556c23
|
cea7b5b1a105534c57ddbfb9382553758f94ab0f
|
/Lectures/Week 8/Gompertz_example_0.R
|
38fe51c39e0b53d13db3b37777af0fa7e6aa1dc9
|
[] |
no_license
|
YanVT/atsa2017
|
973ed4dc7fe812d0794421c516225da668cf6477
|
60313ca2e5a3aae47de68e1adb4f32c9c5cef4e0
|
refs/heads/master
| 2023-08-31T08:47:02.631251
| 2019-05-09T02:46:04
| 2019-05-09T02:46:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,041
|
r
|
Gompertz_example_0.R
|
#################################################################
## Discrete Gompertz
## Example 0. Observation error leads to spurious dens-dep
#################################################################
require(MARSS)
library(forecast)
#-----
set.seed(123)
#-----
##A mean-reverting model
K=log(2000)
u=1
b=1-u/K
x0=1
q=.02
#generate an underlying true process
#x(1)
x=b*x0+u+rnorm(1,0,sqrt(q))
#add x(2:n)
n=40
for(i in 2:n) x[i]=b*x[i-1]+u+rnorm(1,0,sqrt(q))
#No observation error
y=x
#fit with Arima
fit.Arima=Arima(y, order=c(1,0,0))
# true versus estimated
c(true=b, est=coef(fit.Arima)["ar1"])
#that's not so good why did that happen?
#Plot y
plot(y, type="l")
#fit with MARSS
mod.list=list(
U=matrix("u"),
x0=matrix(y[1]),
B=matrix("b"),
Q=matrix("q"),
Z=matrix(1),
A=matrix(0),
R=matrix(0),
tinitx=1)
#Note u and b estimation is hard; you might need to use method="BFGS"
fit.marss=MARSS(y,model=mod.list, method="BFGS")
# true versus estimated
c(true=b,
est.Arima=coef(fit.Arima)["ar1"],
est.marss=coef(fit.marss)$B)
#Let's add some observation error
r=.1
y = x + rnorm(n,0,sqrt(r))
mod.list=list(
U=matrix("u"),
x0=matrix(y[1]),
B=matrix("b"),
Q=matrix("q"),
Z=matrix(1),
A=matrix(0),
R=matrix(0),
tinitx=1)
#fit
fit.Arima2=Arima(y, order=c(1,0,0))
fit.marss2=MARSS(y,model=mod.list, method="BFGS")
# true versus estimated
c(true=b,
est.Arima=coef(fit.Arima2)["ar1"],
est.marss=coef(fit.marss2)$B)
#Look at the acfs
#-----
par.old=par(mfrow=c(3,1), mai=c(0.4,0.7,0.1,0.1))
#-----
#take a look at the acf of the diff( white noise )
acf(x) #acf of AR-1 b!=1
acf(diff(x)) #acf of diff of that
acf(diff(rnorm(100))) #characteristic of diff of iid error
#take a look at the acf of the diff( white noise )
acf(y) #acf of AR-1 b!=1
acf(diff(y)) #acf of diff of that
acf(diff(rnorm(100))) #characteristic of diff of iid error
plot(1:n,exp(x),xlim=c(0,n),type="l",lwd=2)
points(exp(y))
acf(diff(x),ylab="ACF diff x")
acf(diff(y),ylab="ACF diff y")
par(par.old)
|
d9fdcf506af9e2c51326b36161856554d6585e68
|
98736320ccfeb5b0baac8fd6a0ac49e0c7de1953
|
/mainIPI.R
|
5ee3982b9067318e74c6bf4c0e8378ce74c81519
|
[] |
no_license
|
frehbach/rebo19a
|
cc62305ed7d00edcd22687bb2906177fc4d00a9a
|
2597b095506f6bc4372905aab3601a9663d6f316
|
refs/heads/master
| 2022-04-23T15:28:13.470982
| 2020-04-21T14:13:26
| 2020-04-21T14:13:26
| 257,517,246
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,272
|
r
|
mainIPI.R
|
library(SPOT)
source("runBBOB.R")
source("readBBOB.R")
source("wrapExternalFunction.R")
library(dplyr)
source("funRobots.R")
args = commandArgs(trailingOnly=TRUE)
### RUN Parameters #########################################
# 1) Instance ID
# 2) Seed / Repeat
# 3) Function ID of BBOB set
# 4) nDim - Amount of dimensions
# 5) Algo Setup ID
### Recieve Seed + Instance
instance <- as.numeric(args[1])
seed <- as.numeric(args[2])
set.seed(seed)
### BUDGET
TOTAL_FUN_BUDGET <- 100
## Parallel Factor
N_CPUS <- 6
### Recieve Function ID
### 1-24 bbob functions
funID <- as.numeric(args[3])
### NDIM
nDim <- as.numeric(args[4])
###### Algorithm Setup:
######
algoID <- as.numeric(args[5])
## 2-3) BO - PM
## 4-5) BO - EI
## 6-7) BO - LCB
## 8) BO-Multi (6 internen)
solver <- function(fun,lower,upper,solverParameterList){
########target function wrapper for SPOT
tfun <- function(x){
print(x)
cat(paste("time=",Sys.time(),"samples=",nrow(x),"\n"), file = paste("timeRes/SPOT",paste(args,collapse="_"),sep="_"), append = T)
matrix(apply(x,1,fun), ncol=1)
}
X <- designLHD(,lower,upper)
y <- tfun(X)
modelControl = list(target = c("y", "s"),
useLambda = T,
lambdaUpper = -4,
algTheta = optimDE,
budgetAlgTheta = 250)
optimizerControl = list(funEvals = nDim * 300,
populationSize = 5 * nDim)
while(nrow(X) < TOTAL_FUN_BUDGET){
model <- buildKriging(X,y,modelControl)
model$target <- c("y","s")
evalIPI = function(x,tVal){
yVal = predict(model, x)$y
yMin = min(y)
s = predict(model,x)$s
return(-(0.5*pnorm((yMin-yVal)/(1.05-tVal))+pnorm((-(s-tVal)^2)/(0.05))))
}
tVals <- NULL
for(i in 1:N_CPUS)
tVals = c(tVals,i*(1/(N_CPUS+1)))
newX = NULL
for(tVal in tVals)
{
newX = rbind(newX, optimDE(,fun = function(x){evalIPI(x,tVal = tVal)}, lower,upper,optimizerControl)$xbest)
}
newY <- tfun(newX)
X <- rbind(X, newX)
y <- rbind(y,newY)
}
}
if(funID > 24){
if(funID == 25){
robotFun <- createRobotFitness(paste("robot",paste(args,collapse="_"),sep="_"),"gBase.yaml")
}
if(funID == 26){
robotFun <- createRobotFitness(paste("robot",paste(args,collapse="_"),sep="_"),"spBase.yaml")
}
if(funID == 27){
robotFun <- createRobotFitness(paste("robot",paste(args,collapse="_"),sep="_"),"snBase.yaml")
}
wrappedRobotFun <- bbobr::wrapToBBOBFunction(fun = robotFun, functionID = funID, nDim = nDim, algoID = paste("IPI",paste(args,collapse="_"),sep="_")
, instanceID = instance,
experimentPath = "robotTest")
solver(wrappedRobotFun,lower = c(rep(c(0.01,0.01),nDim/2)), upper = c(rep(c(10,2*3.14159),nDim/2)), list())
}else{
runCOCO(solver,current_batch = 1,number_of_batches = 1,dimensions=nDim, instances = instance,
functions = funID,solver_name = paste("IPI",paste(args,collapse="_"),sep="_"))
}
|
4345da8e7bfb71db4affaad12f308d1449b1198f
|
1ca04513e59d6184c6d8d9a06c6929b33e8cb42e
|
/Test.R
|
90d532109326c7d5ada3f389f1858e3a70d932f1
|
[] |
no_license
|
zhangyingalice/Prediction-Assignment-Writeup
|
fd8ab76ae26309538e07a92ba45d26d93ecb9ab5
|
0c0de7f1a8e23b5bf0ce70501ba94883e07a7390
|
refs/heads/master
| 2020-04-02T15:38:10.315320
| 2018-10-24T22:31:25
| 2018-10-24T22:31:25
| 154,576,142
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,129
|
r
|
Test.R
|
rm(list = ls())
library(caret)
#Load datasets
training= read.csv("C:/YZ_R/Data/pml-training.csv",na.strings=c("NA","#DIV/0!",""))
testing= read.csv("C:/YZ_R/Data/pml-testing.csv", na.strings=c("NA","#DIV/0!",""))
##########################################################################################
######################### Data preprocessing & PARTITIONING #########################
##########################################################################################
training <- training[,colSums(is.na(testing))==0]
testing <- testing[,colSums(is.na(testing))==0]
# Delete irrelevent columns [X, user_name, raw_timestamp_part_1, raw_timestamp_part_2, cvtd_timestamp, new_window, num_window]
training <-training[,-c(1:7)]
testing <-testing[,-c(1:7)]
# Divide training data to subtraining and subtesting (70% subtraining, 30% subtesting)
inTrain <- createDataPartition(y=training$classe, p=0.7, list=F,)
subTraining <- training[inTrain,]
subTesting <- training[-inTrain,]
##########################################################################################
################# Model1 Decision Tree ####################
##########################################################################################
library(rpart)
model_dt <- rpart(classe ~., data=subTraining, method="class")
pred_dt <- predict(model_dt, subTesting, type="class")
res_dt <- confusionMatrix(pred_dt,subTesting$classe)
res_dt
##########################################################################################
################# Model2 Recursive partitioning ####################
##########################################################################################
library("party")
party_tree <- ctree(formula=classe ~., data=subTraining)
partypredict <- predict(party_tree, newdata=subTesting)
res_party<- confusionMatrix(partypredict ,subTesting$classe)
res_party
##########################################################################################
################# Model3 Random Forest ####################
##########################################################################################
library(randomForest)
model_rf <- randomForest(classe ~., data=subTraining, na.action=na.omit)
pred_rf <- predict(model_rf,subTesting, type="class")
# Summarize randomForest results.
res_rf <- confusionMatrix(pred_rf,subTesting$classe)
res_rf
##########################################################################################
################# Compare Models ####################
##########################################################################################
df_res <- data.frame(res_dt$overall, res_party$overall, res_rf$overall)
df_res
##########################################################################################
################# Predict the Test Data ####################
##########################################################################################
res <- predict(model_rf, testing, type="class")
res
|
2d2c1a301c3bc06999603f92654696beb8588734
|
84c3e18e0e28d7494d2a3aa34cf2b62376368157
|
/man/ggsave-tk.rd
|
44c3ad1c385989a2a566a03a2d293d7b7c14099a
|
[] |
no_license
|
genome-vendor/r-cran-ggplot2
|
01859b20e506b1b4e282b3d321afd92fb5628a86
|
6430a6765bc27a9d68a4c2e70530f1cd4718aebc
|
refs/heads/master
| 2021-01-01T20:05:23.558551
| 2012-07-17T19:48:36
| 2012-07-17T19:48:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,732
|
rd
|
ggsave-tk.rd
|
\name{ggsave}
\alias{ggsave}
\title{ggsave}
\author{Hadley Wickham <h.wickham@gmail.com>}
\description{
Save a ggplot with sensible defaults
}
\usage{ggsave(filename=default_name(plot), plot = last_plot(), device=default_device(filename), path = NULL, scale=1, width=par("din")[1], height=par("din")[2], dpi=300, keep = plot$options$keep, drop = plot$options$drop, ...)}
\arguments{
\item{filename}{file name/filename of plot}
\item{plot}{plot to save, defaults to last plot displayed}
\item{device}{device to use, automatically extract from file name extension}
\item{path}{path to save plot to (if you just want to set path and not filename)}
\item{scale}{scaling factor}
\item{width}{width (in inches)}
\item{height}{height (in inches)}
\item{dpi}{dpi to use for raster graphics}
\item{keep}{plot components to keep}
\item{drop}{plot components to drop}
\item{...}{other arguments passed to graphics device}
}
\details{ggsave is a convenient function for saving a plot. It defaults to
saving the last plot that you displayed, and for a default size uses
the size of the current graphics device. It also guesses the type of
graphics device from the extension. This means the only argument you
need to supply is the filename.
\code{ggsave} currently recognises the extensions eps/ps, tex (pictex), pdf,
jpeg, tiff, png, bmp, svg and wmf (windows only).}
\examples{\dontrun{
ratings <- qplot(rating, data=movies, geom="histogram")
qplot(length, data=movies, geom="histogram")
ggsave(file="length-hist.pdf")
ggsave(file="length-hist.png")
ggsave(ratings, file="ratings.pdf")
ggsave(ratings, file="ratings.pdf", width=4, height=4)
# make twice as big as on screen
ggsave(ratings, file="ratings.pdf", scale=2)
}}
\keyword{file}
|
2e20dba7b8e95332a2507def66691882c601b3a3
|
0e9e88fc7d19c72b5eda82a166f4adc1175db881
|
/adiliorosa/scripts/Client.r
|
3b08a531624d8b34b3aae92a5e383cc08f846555
|
[] |
no_license
|
AdilioR/tccs
|
af778560ef5b35f38d950f654f457115b946037a
|
ab25b7930f67b58c72e91852edbee1237e2e3dad
|
refs/heads/master
| 2020-06-12T23:13:04.499031
| 2019-07-03T21:48:19
| 2019-07-03T21:48:19
| 194,456,946
| 0
| 0
| null | 2019-06-29T23:33:11
| 2019-06-29T23:33:10
| null |
UTF-8
|
R
| false
| false
| 4,348
|
r
|
Client.r
|
# Remove todos os objetos do workspace
rm(list = ls())
# Carrega a biblioteca de análise técnica
require(TTR)
# Carrega os scripts necessários para gerar e avaliar as estratégias
source("https://raw.githubusercontent.com/AdilioR/tccs/master/adiliorosa/scripts/Asset.R")
source("https://raw.githubusercontent.com/AdilioR/tccs/master/adiliorosa/scripts/Result.R")
source("https://raw.githubusercontent.com/AdilioR/tccs/master/adiliorosa/scripts/TechnicalAnalysis.r")
source("https://raw.githubusercontent.com/AdilioR/tccs/master/adiliorosa/scripts/Main.R")
asset.name <<- "ABEV3.SA"
# Carrega o CSV para a memória
Main.loadCsvIntoWorkspace(asset.name, csv_fullpath = "https://raw.githubusercontent.com/AdilioR/tccs/adilio/adiliorosa/rworkingdirectory/ABEV3.SA.csv", as.Date("1970-01-01"), header = TRUE, sep = ",")
# Prepara os dados caso sejam empregados subconjuntos do dataset original
setup <- function()
{
Asset.First_Date <<- Asset.TransactionList$Date[1]
Asset.Last_Date <<- Asset.TransactionList$Date[nrow(Asset.TransactionList)]
rm(list=ls(pattern="Result."))
}
start <- function(sample.name)
{
# SMA
for(nFast in seq(from=10, to=25, by=5)) # 1 a 199 no tcc, de 1 em 1
{
for(nSlow in seq(from=(nFast + 1), to=36, by=5))# 2 a 200 no tcc , de 1 em 1
{
predicted_decision_list <- TechnicalAnalysis.getDecisionList.SMA(nFast, nSlow) #lista ok
Main.setStrategyResults(asset.name = asset.name, asset.transaction_list.prices = Asset.TransactionList$Adj_Close, asset.transaction_list.dates = Asset.TransactionList$Date, strategy_name = "SMA", strategy_details = paste("long-", nSlow, "_short-", nFast, sep = ""), predicted_decision_list = predicted_decision_list, percent_train = 0.8)
}
}
# MACD
for(nFast in seq(from=10, to=25, by=5)) # 1 a 199 no tcc, de 1 em 1
{
for(nSlow in seq(from=(nFast + 1), to=36, by=5)) # 2 a 200 no tcc , de 1 em 1
{
nSig <- 9
predicted_decision_list <- TechnicalAnalysis.getDecisionList.MACD(nFast, nSlow, nSig)
Main.setStrategyResults(asset.name = asset.name, asset.transaction_list.prices = Asset.TransactionList$Adj_Close, asset.transaction_list.dates = Asset.TransactionList$Date, strategy_name = "MACD", strategy_details = paste("long-", nSlow, "_short-", nFast, "_nsig-", nSig, sep = ""), predicted_decision_list = predicted_decision_list, percent_train = 0.8)
}
}
# RSI
for(MALength in seq(from=9, to=12, by=1)) # 9 a 30 no TCC
{ # Cada ?dice ?um tamanho de m?ia m?el
for(nivelInferior in seq(from=30, to=35, by=1))
{
for(nivelSuperior in seq(from=60, to=65, by=1))
{
predicted_decision_list <- TechnicalAnalysis.getDecisionList.RSI(MALength, nivelInferior, nivelSuperior)
Main.setStrategyResults(asset.name = asset.name, asset.transaction_list.prices = Asset.TransactionList$Adj_Close, asset.transaction_list.dates = Asset.TransactionList$Date, strategy_name = "RSI", strategy_details = paste("MAType-", "SMA_", "MaLength-", MALength, "_inf-level-", nivelInferior, "_sup-level-", nivelSuperior, sep = ""), predicted_decision_list = predicted_decision_list, percent_train = 0.8)
}
}
}
Main.avoidFactors()
save.image(file = paste(asset.name, sample.name, "workspace.RData", sep = "_"))
print(paste("Finalizado as: ", Sys.time()))
}
subsample1 <- Asset.TransactionList[c(1 : (round(NROW(Asset.TransactionList) * 0.25, digits = 0))),]
subsample2 <- Asset.TransactionList[c((round(NROW(Asset.TransactionList) * 0.25, digits = 0) + 1) : (round(NROW(Asset.TransactionList) * 0.50, digits = 0))),]
subsample3 <- Asset.TransactionList[c((round(NROW(Asset.TransactionList) * 0.50, digits = 0) + 1) : (round(NROW(Asset.TransactionList) * 0.75 + 1, digits = 0))),]
subsample4 <- Asset.TransactionList[c((round(NROW(Asset.TransactionList) * 0.75, digits = 0) + 2) : (NROW(Asset.TransactionList))),]
start("FullSample")
Asset.TransactionList <- subsample1
rm(subsample1)
setup()
start("Subsample1")
Asset.TransactionList <- subsample2
rm(subsample2)
setup()
start("Subsample2")
Asset.TransactionList <- subsample3
rm(subsample3)
setup()
start("Subsample3")
Asset.TransactionList <- subsample4
rm(subsample4)
setup()
start("Subsample4")
carregarDataset <- function(fileNameWithExtension)
{
setwd(workingDirectory)
load(fileNameWithExtension)
}
|
7f9ea267d477f2184e24fd6097721ecee58eb494
|
e0c88d1cbddc58d65b460afcac2eb1bd3696ca8a
|
/R/rte_engine_examdesign.R
|
7e12f40796786070eb53b02300932865b9d8a1d1
|
[] |
no_license
|
cran/RndTexExams
|
d6d52acfff0c031f8a3b086330bb017267d175ba
|
e7875e6e1679dc01741148a52981aebcc32ec821
|
refs/heads/master
| 2021-01-21T14:04:33.785157
| 2018-10-09T20:00:03
| 2018-10-09T20:00:03
| 51,207,954
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,428
|
r
|
rte_engine_examdesign.R
|
#' Function that breaks latex file of exam class examdesign into a dataframe (internal use)
#'
#' @param my.text Text of latex file written in class examdesign (UTF-8)
#'
#' @return A dataframe with several information (see rte.analyze.tex.file)
#'
#' @examples
#' f.in <- system.file("extdata", "MyRandomTest_examdesign.tex", package = "RndTexExams")
#' my.text <- stringi::stri_read_lines(f.in)
#' Encoding(my.text) <- 'UTF-8'
#'
#' out <- engine.analyze.class.examdesign(my.text)
#'
#' @export
engine.analyze.class.examdesign <- function(my.text){
# specific error checking for examdesign
detect.nokey <- stringr::str_detect(my.text,
stringr::fixed('\\NoKey'))
if (!any(detect.nokey)){
warning('wARNING: Could not find command "\\NoKey". The exams will be printed with all answer keys!')
}
detect.norearrange <- stringr::str_detect(my.text,
stringr::fixed('\\NoRearrange '))
if (!any(detect.norearrange)){
stop('ERROR: Could not find command "\\NoRearrange". Please add it to the preamble of tex file')
}
# get parameters
l.def <- rte.get.classes.def(exam.class = 'examdesign')
# find idx of text of multiple choice questions
line.beg.mchoice <- which(stringr::str_detect(string = my.text,
stringr::fixed(l.def$str.pattern.beg.mchoice)))
line.end.mchoice <- which(stringr::str_detect(string = my.text,
stringr::fixed(l.def$str.pattern.end.mchoice)))
mchoice.text <- my.text[line.beg.mchoice:line.end.mchoice]
# find beggining and ending of all multiple choice questions
idx.beg.mchoices <- which(stringr::str_detect(string = mchoice.text, stringr::fixed(l.def$str.pattern.beg.question)))
idx.end.mchoices <- which(stringr::str_detect(string = mchoice.text, stringr::fixed(l.def$str.pattern.end.question)))
# find text part before and after multiple choice questions
my.preamble <- paste0(my.text[1:(line.beg.mchoice[1]-1)], collapse = ' \n')
my.last.part <- paste0(my.text[(line.end.mchoice[length(line.end.mchoice)]+1):length(my.text)], collapse = '\n')
# Find text with options for \begin{multiplechoice}
idx.mchoice.comm <- which(stringr::str_detect(string = my.text, stringr::fixed(l.def$str.pattern.beg.mchoice)))
my.begin.mchoice.line <- my.text[idx.mchoice.comm]
# build dataframe with questions to be randomized
df.questions <- data.frame(n.question = seq(1,length(idx.beg.mchoices)),
idx.begin = idx.beg.mchoices,
idx.end = idx.end.mchoices)
# function to get text from m.questions
locate.questions <- function(x,mchoice.text){
q.temp <- mchoice.text[x['idx.begin']:(x['idx.end'])]
q.temp <- paste0(q.temp,collapse = '\n')
return(q.temp)
}
df.questions$q.text <- apply(df.questions,MARGIN = 1 , FUN = locate.questions, mchoice.text=mchoice.text)
# function to locate main text (header) of all m.questions
locate.header <- function(x, l.def){
q.temp <- x['q.text']
idx1 <- stringr::str_locate(q.temp, stringr::fixed(l.def$str.pattern.choice))[1]
idx2 <- stringr::str_locate(q.temp, stringr::fixed(l.def$str.pattern.correct))[1]
idx3 <- stringr::str_locate(q.temp, stringr::fixed('[1]'))[1]
if ( (is.na(idx2))&(!is.na(idx1))&(is.na(idx3))){
stop(paste('ERROR: Correct choice mark not found for question\n\n:',
q.temp,
'\n\n You must edit the latex file, assigning the correct choice with \\choice[!]{} or [ver]',
'(see examdesign manual or examples of latex files for rndtexexam for details) '))
}
idx<- min(c(idx1,idx2), na.rm = T)
if (!is.na(idx)){
q.temp <- stringr::str_sub(q.temp,1,idx-2)
}
return(q.temp)
}
df.questions$main.text <- apply(df.questions,MARGIN = 1 , FUN = locate.header, l.def)
df.answers <- data.frame() # Dataframe with all answers to all questions
for (i.q in df.questions$n.question){
q.temp <- df.questions$q.text[i.q]
q.temp <- stringr::str_split(q.temp, pattern = '\\n')[[1]] # break lines
idx.choice <- which(stringr::str_detect(string = q.temp, pattern = stringr::fixed(l.def$str.pattern.choice)))
my.main.text <- as.character(paste0('\n',q.temp[1:(idx.choice[1]-1)], collapse = '\n'))
my.answers <- as.character(q.temp[idx.choice])
# Build data.frame for output
df.answers <- rbind(df.answers, data.frame(n.question = rep(i.q, length(my.answers)),
main.text = rep(my.main.text,length(my.answers)),
text.answer = my.answers,
stringsAsFactors=F ))
}
# return a list with questions, answers, preamble and last part of tex file
out <- list(df.questions=df.questions, # df with all questions
df.answers = df.answers, # df with all answers
my.begin.mchoice.line = my.begin.mchoice.line, # text with begging of mchoice enviroment
my.preamble = my.preamble, # preamble of tex file
my.last.part = my.last.part) # last part of tex file
return(out)
}
|
efaec42a79f77d65755f4fc2dbd3a3545410a082
|
8e40e37dd427d26f2849446a6e24a83480471346
|
/codes/plot4.R
|
1f57c8772832bc28cd6e28b0e8c8d5320faccd7a
|
[] |
no_license
|
davidkeyes/ExData_Plotting1
|
2764ba3a4e945b3def4267cfca4e452ff0a01ac3
|
f91dd90365b028f18d77829c316e47225637a0c2
|
refs/heads/master
| 2020-12-24T18:23:32.430153
| 2015-03-08T20:29:59
| 2015-03-08T20:29:59
| 30,511,692
| 0
| 0
| null | 2015-02-09T00:36:29
| 2015-02-09T00:36:29
| null |
UTF-8
|
R
| false
| false
| 1,789
|
r
|
plot4.R
|
## Install and load the sqldf package for importing a subset of the large data file
install.packages("sqldf")
library(sqldf)
## Import the data
data <- read.csv.sql("household_power_consumption.txt",
sql = "select * from file where (Date = '2/2/2007' or Date = '1/2/2007') ",
header = TRUE,
sep = ";")
## Join date and time data in single column
data$Datetime <- paste(data$Date, data$Time, sep = " ")
## Convert Datetime column to calendar object
data$Datetime <- strptime(data$Datetime, format = "%d/%m/%Y %H:%M:%S")
## Activate the png device
png(file="plot4.png",width=400,height=350,res=72)
## Set the parameters
par(mar = c(5,5,2,2), mfrow = c(2,2))
## Create the first graph
plot(data$Datetime, data$Global_active_power[!data$Global_active_power == "?"],
type = "l", xlab = "", ylab = "Global Active Power (kilowatts)")
## Create the second graph
plot(data$Datetime, data$Voltage[!data$Voltage == "?"],
type = "l", xlab = "datetime", ylab = "Voltage")
## Create the third graph
plot(data$Datetime, data$Sub_metering_1[!data$Sub_metering_1 == "?"],
type = "l", xlab = "", ylab = "Energy sub metering")
lines(data$Datetime, data$Sub_metering_2[!data$Sub_metering_2 == "?"],
type = "l", col = "red")
lines(data$Datetime, data$Sub_metering_3[!data$Sub_metering_3 == "?"],
type = "l", col = "blue")
legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lwd = 1,
bty = "n",
col = c("black", "red", "blue"),
cex = 0.75)
## Create the fourth graph
plot(data$Datetime, data$Global_reactive_power[!data$Global_reactive_power == "?"],
type = "l", xlab = "datetime", ylab = "Global reactive power")
## Turn off the device
dev.off()
|
1f1f3dfceb4f26ae290db894c36b75109d4c433d
|
2100c1474efb2c6788dead3d7c10f32be7140db2
|
/man/mww_eval.Rd
|
6a2b1dcde09151a469320bac31d24b53e27fc2cf
|
[] |
no_license
|
cran/multiwave
|
e4f4d82528c6819732eea30e9cd4cb4b1261cbb6
|
b2aa6560558a9a35aef2be44da71609386353dbb
|
refs/heads/master
| 2021-01-10T13:17:27.092461
| 2019-05-06T06:20:09
| 2019-05-06T06:20:09
| 48,084,624
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,611
|
rd
|
mww_eval.Rd
|
\name{mww_eval}
\alias{mww_eval}
\title{
evaluation of multivariate wavelet Whittle estimation
}
\description{
Evaluates the multivariate wavelet Whittle criterion at a given long-memory parameter vector \code{d} using \code{DWTexact} for the wavelet decomposition.
}
\usage{
mww_eval(d, x, filter, LU = NULL)
}
\arguments{
\item{d}{vector of long-memory parameters (dimension should match dimension of x).
}
\item{x}{
data (matrix with time in rows and variables in columns).
}
\item{filter}{
wavelet filter as obtain with \code{scaling_filter}.
}
\item{LU}{
bivariate vector (optional) containing
\code{L}, the lowest resolution in wavelet decomposition
\code{U}, the maximal resolution in wavelet decomposition.
(Default values are set to \code{L}=1, and \code{U=Jmax}.)
}
}
\details{
\code{L} is fixing the lower limit of wavelet scales. \code{L} can be increased to avoid finest frequencies that can be corrupted by the presence of high frequency phenomena.
\code{U} is fixing the upper limit of wavelet scales. \code{U} can be decreased when highest frequencies have to be discarded.
}
\value{
multivariate wavelet Whittle criterion.
}
\references{
E. Moulines, F. Roueff, M. S. Taqqu (2009) A wavelet whittle estimator of the memory parameter of a nonstationary Gaussian time series. \emph{Annals of statistics}, vol. 36, N. 4, pages 1925-1956
S. Achard, I. Gannaz (2016)
Multivariate wavelet Whittle estimation in long-range dependence. \emph{Journal of Time Series Analysis}, Vol 37, N. 4, pages 476-512. \code{http://arxiv.org/abs/1412.0391}.
S. Achard, I Gannaz (2019)
Wavelet-Based and Fourier-Based Multivariate Whittle Estimation: multiwave. \emph{Journal of Statistical Software}, Vol 89, N. 6, pages 1-31.
}
\author{
S. Achard and I. Gannaz
}
\seealso{
\code{\link{mww}}, \code{\link{mww_cov_eval}},\code{\link{mww_wav}},\code{\link{mww_wav_eval}},\code{\link{mww_wav_cov_eval}}
}
\examples{
### Simulation of ARFIMA(0,d,0)
rho <- 0.4
cov <- matrix(c(1,rho,rho,1),2,2)
d <- c(0.4,0.2)
J <- 9
N <- 2^J
resp <- fivarma(N, d, cov_matrix=cov)
x <- resp$x
long_run_cov <- resp$long_run_cov
## wavelet coefficients definition
res_filter <- scaling_filter('Daubechies',8);
filter <- res_filter$h
M <- res_filter$M
alpha <- res_filter$alpha
LU <- c(2,11)
res_mww <- mww_eval(d,x,filter,LU)
k <- length(d)
res_d <- optim(rep(0,k),mww_eval,x=x,filter=filter,
LU=LU,method='Nelder-Mead',lower=-Inf,upper=Inf)$par
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ts}
\keyword{nonparametric}
|
7a45dcc45eb3199fd9daec3ae810ceef8c5cc2e5
|
f513fd2de05d25ff72f3b2e57c0b4a07c91252f7
|
/Data mining/Assignment 1/Assignment1-Gyaneshwar/customercluster.R
|
e1ec99c9e00bd2bb09f808cb2dc3c2559c3040c3
|
[] |
no_license
|
A00431429/MCDA2
|
6a7d8fc93450a856887a7ed3d5efd8d057ae041a
|
95e23c23d305a4579d97e62d3e6b6b710181fff1
|
refs/heads/master
| 2020-07-05T17:53:42.484689
| 2019-08-10T01:18:06
| 2019-08-10T01:18:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,009
|
r
|
customercluster.R
|
#Load All Libraries
install.packages("lattice")
install.packages("gridBase")
install.packages("GGally") # OPTIONAL - only if you don't have
install.packages("DMwR") # OPTIONAL - only if you don't have
install.packages("ggplot2")
options(repos = getOption("repos")["CRAN"])
library(grid)
library(ggplot2)
library(GGally)
library(DMwR)
prod <- read.csv("D:/assignment/pawan/assignment1/customer_retail.csv") # You can use option "import Dataset" to import CSV file if you are getting path error
View(prod) # To View the loaded dataset
ggpairs(prod[, which(names(prod) != "CustomerID")], upper = list(continuous = ggally_points),lower = list(continuous = "points"), title = "Products before outlier removal") # To visualize data
boxplot(prod$baskets) # For Box and Whisker plot. here prod is dataset and BASKETS is column
prod.clean <- prod[prod$CustomerID != 0, ] # Remove outliers
prod.scale = scale(prod.clean[-1]) # Normalize data using scale and exclude ITEM_SK column. -1 will remove first column that is ITEM_SK and keep all other.
View(prod.scale)
withinSSrange <- function(data,low,high,maxIter)
{
withinss = array(0, dim=c(high-low+1));
for(i in low:high)
{
withinss[i-low+1] <- kmeans(data, i, maxIter)$tot.withinss
}
withinss
}
plot(withinSSrange(prod.scale,1,50,150)) # Elbow plot to determine the optimal number of clusters between 1 and 50.
# plot mentions 6 to 9 are good clusters to consider.
pkm = kmeans(prod.scale, 6, 150) # K-means using k=6 for products based on results of elbow plot.
View(pkm)
prod.realCenters = unscale(pkm$centers, prod.scale) # Denormalize data by reversing scale function
clusteredProd = cbind(prod.clean, pkm$cluster) # Bind clusers to cleansed Data
View(clusteredProd)
plot(clusteredProd[,2:5], col=pkm$cluster) # Visualizing clusering results. Here we want all rows so we are not mentioning anything but we want columns only from 2 to 5 (we don't want to visualize first column - CustomerID).
|
2d902a8b66206566453626ea17b4a31cc769e13c
|
fe612f81a3118bf3ebef644bae3281bd1c156442
|
/man/h2o.bottomN.Rd
|
95714edea7e257569e9264a1336a82f8b0cf634e
|
[] |
no_license
|
cran/h2o
|
da1ba0dff5708b7490b4e97552614815f8d0d95e
|
c54f9b40693ae75577357075bb88f6f1f45c59be
|
refs/heads/master
| 2023-08-18T18:28:26.236789
| 2023-08-09T05:00:02
| 2023-08-09T06:32:17
| 20,941,952
| 3
| 3
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,231
|
rd
|
h2o.bottomN.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/frame.R
\name{h2o.bottomN}
\alias{h2o.bottomN}
\title{H2O bottomN}
\usage{
h2o.bottomN(x, column, nPercent)
}
\arguments{
\item{x}{an H2OFrame}
\item{column}{is a column name or column index to grab the top N percent value from}
\item{nPercent}{is a bottom percentage value to grab}
}
\value{
An H2OFrame with 2 columns. The first column is the original row indices, second column contains the bottomN values
}
\description{
bottomN function will will grab the bottom N percent of values of a column and return it in a H2OFrame.
Extract the top N percent of values of a column and return it in a H2OFrame.
}
\examples{
\dontrun{
library(h2o)
h2o.init()
f1 <- "https://s3.amazonaws.com/h2o-public-test-data/bigdata/laptop/jira/TopBottomNRep4.csv.zip"
f2 <- "https://s3.amazonaws.com/h2o-public-test-data/smalldata/jira/Bottom20Per.csv.zip"
data_Frame <- h2o.importFile(f1)
bottom_Answer <- h2o.importFile(f2)
nPercent <- c(1, 2, 3, 4)
frame_Names <- names(data_Frame)
nP <- nPercent[sample(1:length(nPercent), 1, replace = FALSE)]
col_Index <- sample(1:length(frame_Names), 1, replace = FALSE)
h2o.bottomN(data_Frame, frame_Names[col_Index], nP)
}
}
|
c51978c94639bdf34d141e78a05199c784e049a1
|
512251113212381e4704309f9b5f386118125bc6
|
/R/getISOlist.R
|
459db48182f36842518106b13136fbbae830e079
|
[] |
no_license
|
johanneskoch94/madrat
|
74f07ee693d53baa5e53772fc41829438bdf1862
|
2a321caad22c2b9b472d38073bc664ae2991571f
|
refs/heads/master
| 2023-08-09T11:07:47.429880
| 2021-09-03T13:04:32
| 2021-09-03T13:04:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,631
|
r
|
getISOlist.R
|
#' get official ISO list
#'
#' Function which returns the ISO list which is used as default for the input
#' data preparation. It contains the countries to which all source data has to
#' be up- or downscaled to.
#'
#'
#' @param type Determines what countries should be returned. "all" returns all
#' countries, "important" returns all countries which are above the population
#' threshold set in the configuration and "dispensable" returns all countries
#' which are below the threshold.
#' @return vector of default ISO country codes.
#' @note Please always use this function instead of directly referring to the data
#' object as the format in this data list might change in the future!
#' @author Jan Philipp Dietrich
#' @seealso \code{\link{getSources}}, \code{\link{getCalculations}}
#' @examples
#'
#' head(getISOlist())
#' head(getISOlist("dispensable"))
#'
#' @importFrom magclass ncells
#' @export
getISOlist <- function(type="all") {
iso_country <- read.csv2(system.file("extdata","iso_country.csv",package = "madrat"), row.names = NULL)
iso_country1 <- as.vector(iso_country[,"x"])
names(iso_country1) <- iso_country[,"X"]
ref <- robustSort(iso_country1)
if (type == "all") return(ref)
pop2015 <- read.magpie(system.file("extdata","pop2015.csv",package = "madrat"))
names(dimnames(pop2015)) <- c("ISO2_WB_CODE","Year","data")
if (type == "important") {
return(ref[as.vector(pop2015[,1,1] >= getConfig("pop_threshold")/10^6)])
} else if (type == "dispensable") {
return(ref[as.vector(pop2015[,1,1] < getConfig("pop_threshold")/10^6)])
} else {
stop("Unknown type ",type)
}
}
|
eb0b2282b9d1e86ef5438c5a216e0edab45d5671
|
b93692d4994c13351b5ab5f4152b92273a8fbcd0
|
/man/seCor.Rd
|
7962129ceaf6273bcb627d98d81e81c347b2b6c1
|
[] |
no_license
|
RCFilm/lognorm
|
5ebca25a8ba6cfc7ecb968cfdf5f24fbdfad2415
|
553b9b8ee4e3b4b0347037ab9ab5cb9884654322
|
refs/heads/master
| 2021-03-29T05:48:59.292165
| 2019-12-02T15:36:16
| 2019-12-02T15:36:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,039
|
rd
|
seCor.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/autocorr.R
\name{seCor}
\alias{seCor}
\title{Compute the standard error accounting for empirical autocorrelations}
\usage{
seCor(
x,
na.rm = FALSE,
effCov = computeEffectiveAutoCorr(x, type = "covariance")
)
}
\arguments{
\item{x}{numeric vector}
\item{na.rm}{logical. Should missing values be removed?}
\item{effCov}{numeric vector of effective covariance components
first entry is the variance. See \code{\link{computeEffectiveAutoCorr}}}
}
\value{
numeric scalar of standard error of the mean of x
}
\description{
Compute the standard error accounting for empirical autocorrelations
}
\details{
Computation follows
https://stats.stackexchange.com/questions/274635/calculating-error-of-mean-of-time-series.
The default uses empirical autocorrelation
estimates from the supplied data up to first negative component.
For short series of \code{x} it is strongly recommended to to
provide \code{effCov} that was estimated on a longer time series.
}
|
79b1e5905821ab4a24ccaa118bc7ca7c9f891b6f
|
27c8ebd8e889bf2b5297a1d4728a0979da0713f3
|
/Lab_12/MovieRecommendation.R
|
d632e643da2da96a37855ae478582f8819ed399f
|
[] |
no_license
|
fruxc/R-Programming
|
57694c3f704b30b5745c9cc486520d2b26eaf669
|
c8042bfc677cc90b3221eac1edc0aaaae2ff551a
|
refs/heads/master
| 2023-01-04T06:57:35.345534
| 2020-11-04T04:56:41
| 2020-11-04T04:56:41
| 284,708,982
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,550
|
r
|
MovieRecommendation.R
|
# Importing libraries
library(dplyr)
library(ggplot2)
library(knitr)
library(recommenderlab)
# Data Exploration
# Importing dataset
data(MovieLense)
MovieLense
class(MovieLense)
slotNames(MovieLense)
class(MovieLense@data)
head(names(colCounts(MovieLense)))
vector_ratings <- as.vector(MovieLense@data)
kable(table(vector_ratings), caption = "Rating frequency")
# Since a rating of 0 represents the absence of a rating in this data set, we can remove such
# ratings from the ratings vector.
vector_ratings = vector_ratings[vector_ratings != 0]
hist(vector_ratings, main = "Histogram of Ratings", xlab = "Rating Value")
# Data Preparation
# Minimum threshold
ratings = MovieLense[rowCounts(MovieLense) > 50, colCounts(MovieLense) > 100]
dim(ratings)
# Normalizing the data
ratings.n = normalize(ratings)
ratings.n.vec = as.vector(ratings.n@data)
ratings.n.vec = ratings.n.vec[ratings.n.vec != 0]
hist(ratings.n.vec, main = "Histogram of Normalized Ratings", xlab = "Rating")
# Splitting data for test and train
percent_train = 0.8
#min(rowCounts(ratings.n))
items_to_keep = 15 # items to use for each user
rating_threshold = 3 # good rating implies >=3
n_eval = 1 # number of times to run eval
eval_sets = evaluationScheme(data = ratings, method = "split",
train = percent_train, given = items_to_keep,
goodRating = rating_threshold, k = n_eval)
eval_sets
# User-User Collaborative Filtering
eval_recommender = Recommender(data = getData(eval_sets, "train"),
method = "UBCF", parameter = NULL)
items_to_recommend = 10
eval_prediction = predict(object = eval_recommender,
newdata = getData(eval_sets, "known"),
n = items_to_recommend,
type = "ratings")
eval_accuracy = calcPredictionAccuracy(x = eval_prediction,
data = getData(eval_sets, "unknown"),
byUser = TRUE)
head(eval_accuracy)
# Item-Item Collaborative Filtering
eval_recommender = Recommender(data = getData(eval_sets, "train"),
method = "IBCF", parameter = NULL)
items_to_recommend = 10
eval_prediction = predict(object = eval_recommender,
newdata = getData(eval_sets, "known"),
n = items_to_recommend,
type = "ratings")
eval_accuracy = calcPredictionAccuracy(x = eval_prediction,
data = getData(eval_sets, "unknown"),
byUser = TRUE)
head(eval_accuracy)
# Evaluating Models using different Similarity Parameters
models_to_evaluate = list(IBCF_cos = list(name = "IBCF", param = list(method = "cosine")),
IBCF_cor = list(name = "IBCF", param = list(method = "pearson")),
UBCF_cos = list(name = "UBCF", param = list(method = "cosine")),
UBCF_cor = list(name = "UBCF", param = list(method = "pearson")),
random = list(name = "RANDOM", param = NULL))
n_recommendations = c(1, 3, 5, 10, 15, 20)
results = evaluate(x = eval_sets, method = models_to_evaluate, n = n_recommendations)
# Comparing the Collaborative Filtering Models
# Draw ROC curve
plot(results, y = "ROC", annotate = 1, legend = "topleft")
title("ROC Curve")
# Draw precision / recall curve
plot(results, y = "prec/rec", annotate = 1)
title("Precision-Recall")
|
55ab5e4b9f6aa3ad00b78becb5f9a081b94bcacc
|
fea414c872ff5303f30a6fcfb77e4e305ed8998f
|
/man/write_out_csv.Rd
|
c6b17cd9b8c9b110c2f713bd15cc5ecbfa185e79
|
[] |
no_license
|
Spatial-Time-R/DENVclimate
|
a766299ae8edd767fb1a0c45fac3b8579302932e
|
7bfeacd1b9b74eb8fac71ba7dbf43e180106d7b4
|
refs/heads/master
| 2020-05-28T11:30:50.965933
| 2019-05-24T18:15:58
| 2019-05-24T18:15:58
| 188,986,429
| 1
| 0
| null | 2019-05-28T08:24:20
| 2019-05-28T08:24:19
| null |
UTF-8
|
R
| false
| true
| 388
|
rd
|
write_out_csv.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utilities.R
\name{write_out_csv}
\alias{write_out_csv}
\title{write_out_csv}
\usage{
write_out_csv(dat, my_path, file_name)
}
\arguments{
\item{dat}{the dataframe to save.}
\item{my_path}{the output directory.}
\item{file_name}{the output file name.}
}
\description{
\code{write_out_csv} saves a csv file.
}
|
b84bfafa5e00b2e71c07dc26af439723d39e13b3
|
819245726a6eb792f46003fbbe2b8aa32839da7f
|
/code/3Extract_TrapVolumeColor.R
|
d92f84d749a498130695a79c8b9e4c33caeaea4b
|
[] |
no_license
|
melaniekamm/CleanParseDroegeBees
|
45df956cdbe5096d24dc327ec92bce64a3f69cfb
|
1270d863b181c682d8bd5bca3356b4d250b884df
|
refs/heads/master
| 2020-08-10T03:30:53.251946
| 2020-05-05T18:43:23
| 2020-05-05T18:43:23
| 214,245,995
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 19,516
|
r
|
3Extract_TrapVolumeColor.R
|
#Extract trap volume, color, and number information for abundance analyses
#add trap information to each specimen, calculate Abundance per trap per day
#then aggregate by TransectID or site-year (sum AbundDayTrap and concatenate color and volume strings)
library(dplyr); library(tidyr); library(stringr); library(reshape2); library(data.table); library(dplyr)
#if necessary, read in clean up MDDE specimen data
mdde <- read.csv('./data/Droege_MDDE_cleaned.csv')
##### Part One: Manually clean up some string patterns in field notes that cause issues for regular expressions (below)
#manually change field notes formatting that is not handled by 'extract color' function
mdde$field_note <- gsub(mdde$field_note, pattern='10 bowls each fl yellow fl blue white', replacement="10 fl yellow, 10 fl blue, 10 white", fixed=T) %>%
gsub(pattern='30 w,y,b', replacement="10w, 10y, 10b", fixed=T) %>%
gsub(pattern='[(]', replacement="") %>%
gsub(pattern='[)]', replacement="") %>%
gsub(pattern='blue, yellow, and white uv 10 of each', replacement="10 w, 10 flyl, 10 flbl", fixed=T) %>%
gsub(pattern='15 BOWLs alternating between blue, yellow and white', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='8 BOWLs 2bl, 2 y, 2lpink, 4 white 1or', replacement="8 BOWLs 2bl, 2 y, 2lpink, 2 white 1or", fixed=T) %>%
gsub(pattern='three yellow, three blue, three white', replacement="3 yellow, 3 blue, 3 white", fixed=T) %>%
gsub(pattern='bue', replacement="blue", fixed=T) %>%
gsub(pattern='3 12 ounce glycol traps , fl bl, fl yl, white;', replacement="12 ounce glycol traps, 1 fl bl,1 fl yl,1 white", fixed=T) %>%
gsub(pattern='9 12 ounce glycol traps run all year along the powerlines on the estuary center.
dates are variable and the usual 3 colors were used',
replacement="9 12 ounce glycol traps run all year along the powerlines on the estuary center. 3 fl bl; 3 fl yl; 3 w", fixed=T) %>%
gsub(pattern='15 blue, yellow and white solo BOWLs', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='no missing', replacement="0 missing", fixed=T) %>%
gsub(pattern='none missing', replacement="0 missing", fixed=T) %>%
gsub(pattern='lost : ', replacement="lost:", fixed=T) %>%
gsub(pattern='lost :', replacement="lost:", fixed=T) %>%
gsub(pattern='unknown color lost', replacement="lost", fixed=T) %>%
gsub(pattern='1b, 1y spilled', replacement="2 spilled", fixed=T) %>%
gsub(pattern='1b, 1w spilled', replacement="2 spilled", fixed=T) %>%
gsub(pattern='2b, 1w spilled', replacement="3 spilled", fixed=T) %>%
gsub(pattern='2y, 3b, 1w spilled', replacement="6 spilled", fixed=T) %>%
gsub(pattern='1y, 1w spilled', replacement="2 spilled", fixed=T) %>%
gsub(pattern='1 yellow cup spilled', replacement="1 spilled", fixed=T) %>%
gsub(pattern='1 yellow cup broken', replacement="1 spilled", fixed=T) %>%
gsub(pattern='1w spilled, 1w gone', replacement="2 spilled", fixed=T) %>%
gsub(pattern='3 spilled, 4y crushed', replacement="7 spilled", fixed=T) %>%
gsub(pattern='3 spilled, 4y crushed', replacement="7 spilled", fixed=T) %>%
gsub(pattern='4w, 3b, 3y knocked over', replacement="10 spilled", fixed=T) %>%
gsub(pattern='1 cup knocked over', replacement="1 spilled", fixed=T) %>%
gsub(pattern='1y spilled;', replacement="1 spilled;", fixed=T) %>%
gsub(pattern='2w,2y,3b lost', replacement="7 lost", fixed=T) %>%
gsub(pattern='2w,3b,2y lost', replacement="7 lost", fixed=T) %>%
gsub(pattern='2b,1w lost', replacement="3 lost", fixed=T) %>%
gsub(pattern='3y,3b,3w lost', replacement="9 lost", fixed=T) %>%
gsub(pattern='1b,1w lost', replacement="2 lost", fixed=T) %>%
gsub(pattern='2y,1w,1b lost', replacement="4 lost", fixed=T) %>%
gsub(pattern='lost 6 blue, 5 white, 5 yellow', replacement="16 lost", fixed=T) %>%
gsub(pattern='missing-', replacement="missing", fixed=T) %>%
gsub(pattern='12 oz. BOWL missing', replacement="missing, 12 oz.", fixed=T) %>%
gsub(pattern='full BOWL missing', replacement="missing", fixed=T) %>%
gsub(pattern='half ones missing', replacement="missing", fixed=T) %>%
gsub(pattern='half missing', replacement="missing", fixed=T) %>%
gsub(pattern='BOWL missing', replacement="missing", fixed=T) %>%
gsub(pattern='missing;1y 0b 0w', replacement="1 missing", fixed=T) %>%
gsub(pattern='missing;0y 0b 1w', replacement="1 missing", fixed=T) %>%
gsub(pattern='missing;0y 2b 1w', replacement="3 missing", fixed=T) %>%
gsub(pattern='missing;1y 0b 1w', replacement="2 missing", fixed=T) %>%
gsub(pattern='missing;0y 0b 1w', replacement="1 missing", fixed=T) %>%
gsub(pattern='missing;0y 1b 1w', replacement="2 missing", fixed=T) %>%
gsub(pattern='missing;1y 2b 2w', replacement="5 missing", fixed=T) %>%
gsub(pattern='missing 1w 1y 1b', replacement="3 missing", fixed=T) %>%
gsub(pattern='1w 1y missing', replacement="2 missing", fixed=T) %>%
gsub(pattern='2y 1w', replacement="3 missing", fixed=T) %>%
gsub(pattern='8y 2w missing', replacement="10 missing", fixed=T) %>%
gsub(pattern='12y 10w missing', replacement="22 missing", fixed=T) %>%
gsub(pattern='1 w 1 y missing', replacement="2 missing", fixed=T) %>%
gsub(pattern='1 yellow cup overturned', replacement="1 missing", fixed=T) %>%
gsub(pattern='2 blue missing;run#112BOWL 1 white missing;run#124BOWL 1 blue, 1 yellow missing', replacement="", fixed=T) %>%
gsub(pattern='20 fl 20 fb 20 w;0 missing;sunny 90s', replacement="20 fy 20 fb 20 w;0 missing;sunny 90s", fixed=T) %>%
gsub(pattern='16 BOWLs mostly yellow but 4 blue and a couple white', replacement="16 BOWLs placed, 4 blue,
9 yellow, 3 white, yellow and white approx", fixed=T) %>%
gsub(pattern='north-south direction;22 jul: 10 blue, 10 white, 10 yellow;24 jul: 10 blue, 10 white, 10 yellow;',
replacement="20 blue, 20 white, 20 yellow; represents two dates, 22 jul and 24 jul; north-south direction", fixed=T) %>%
gsub(pattern='east-west direction;22 jul: 5 blue, 5 white, 5 yellow;24 jul: 5 blue, 5 white, 5 yellow;',
replacement="15 blue, 15 white, 15 yellow; represents two dates, 22 jul and 24 jul; east-west direction;", fixed=T) %>%
gsub(pattern='8 w, 8 fy, 8 fb, 8 fy/for;', replacement="8 w, 16 fy, 8 fb", fixed=T) %>%
gsub(pattern='hq ballfield 1;missing;0y 0b 1w;sunny;', replacement="hq ballfield 1", fixed=T) %>%
gsub(pattern='hq ballfield 2;missing;0y 0b 1w;sunny;', replacement="hq ballfield 2", fixed=T) %>%
gsub(pattern='golf course 3;missing;1y 0b 1w;sunny;', replacement="golf course 3", fixed=T) %>%
gsub(pattern='golf course 2;missing;1y 0b 0w;sunny;', replacement="golf course 2", fixed=T) %>%
gsub(pattern='annuals library;missing;0y 2b 1w;sunny at setup, cloudy at pickup;', replacement="annuals library", fixed=T) %>%
gsub(pattern='butterfly habitat;missing;1y 0b 1w;sunny;', replacement="butterfly habitat", fixed=T) %>%
gsub(pattern='heirloom garden;missing;0y 0b 1w;sunny at setup, cloudy at pickup;', replacement="heirloom garden", fixed=T) %>%
gsub(pattern='san martin park;missing;1y 2b 2w;sunny;', replacement="san martin park", fixed=T) %>%
gsub(pattern='john marshall park;missing;1y 0b 0w;sunny at setup, cloudy at pickup;', replacement="john marshall park", fixed=T) %>%
gsub(pattern='blue dawn', replacement="original dawn dish soap", fixed=T) %>%
gsub(pattern='dawn blue', replacement="original dawn dish soap", fixed=T) %>%
gsub(pattern='1y spilled;', replacement="1 spilled;", fixed=T) %>%
gsub(pattern='dark blue has 6 BOWLs and that white has 7', replacement="6 blue, 7 white", fixed=T)
#same thing for second field notes ('note') column
mdde$note <- gsub(mdde$note, pattern='bombus', replacement="BOMBUS", fixed=T) %>%
gsub(pattern='15 blue, yellow and white', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='15 blue,yellow and white', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='15 blue yellow and white', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='15 blue, yellow and white', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='15 yellow, blue and white bowls', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='15 yellow,blue and white solo bowls', replacement="5b, 5y, 5w", fixed=T) %>%
gsub(pattern='*2 yellow and one blue cups were empty when picking', replacement="3 empty", fixed=T) %>%
gsub(pattern='*one cup was empty', replacement="1 empty", fixed=T) %>%
gsub(pattern='1 white cup destroyed', replacement="1 empty", fixed=T)
##### Part Two: Extract trap color, trap number, and number of missing traps from field_note and note columns for each specimen
#create binary color variables (i.e. isBlue) to enable summarized color by transect or site
source('./code/functions/ExtractColor_function.R')
storecolor <- extractcolor(DroegeDF=mdde)
#add trap color and number to dataset
storecolor <- dplyr::select(mdde, -X, -V1) %>%
dplyr::full_join(storecolor)
#make binary color colums to indicate which colors were used for each transect
storecolor <- dplyr::mutate(storecolor, isblue=dplyr::if_else(TrapColor == 'blue' | nblue > 0, "blue", "no"),
isyellow=dplyr::if_else(TrapColor == 'yellow' | nyellow > 0, "yellow", "no"),
iswhite=dplyr::if_else(TrapColor == 'white' | nwhite > 0, "white", "no"),
isFLblue=dplyr::if_else(TrapColor == 'blue-uv' | nFLblue > 0, "FLblue", "no"),
isFLyellow=dplyr::if_else(TrapColor == 'yellow-uv' | nFLyellow > 0, "FLyellow", "no"),
isFLwhite=dplyr::if_else(TrapColor == 'white-uv' | nFLwhite > 0, "FLwhite", "no"),
ispaleblue=dplyr::if_else(TrapColor == 'pale blue', 'PaleBlue', "no"),
isFLpaleblue=dplyr::if_else(TrapColor == 'pale blue-uv','FLPaleBlue', "no"))
#identify transects that are missing color information
trans_check <- dplyr::select(storecolor, TransectID, SiteID, year,state, field_note, note, starts_with('is'), nmissing) %>%
filter(!duplicated(TransectID)) %>%
filter( year %in% c('2004', '2005') & state == 'District of Columbia')
#assign colors to a few observations where trap color could be assumed from field notes indicating all specimens were the same study
#washington dc study field_notes all same style, and other observations record 'b', 'y', 'w' characters in other words as colors
storecolor$isblue[is.na(storecolor$isblue) & storecolor$year %in% c('2004', '2005') &
storecolor$state == 'District of Columbia' &
!storecolor$SiteID %in% c('DCbf0934a8', 'DC0199853a', 'DC27cac6c4', 'DC4deb18cf', 'DCb8f4b6c7') ] <- 'blue'
storecolor$isyellow[is.na(storecolor$isyellow) & storecolor$year %in% c('2004', '2005') &
storecolor$state == 'District of Columbia' &
!storecolor$SiteID %in% c('DCbf0934a8', 'DC0199853a', 'DC27cac6c4', 'DC4deb18cf', 'DCb8f4b6c7') ] <- 'yellow'
storecolor$iswhite[is.na(storecolor$iswhite) & storecolor$year %in% c('2004', '2005') &
storecolor$state == 'District of Columbia' &
!storecolor$SiteID %in%c('DCbf0934a8', 'DC0199853a', 'DC27cac6c4', 'DC4deb18cf', 'DCb8f4b6c7') ] <- 'white'
storecolor$iswhite[storecolor$note == 'groundworks farm, in wicomico county' & storecolor$field_note == "fl bl;fl yl;white; "] <- 'white'
storecolor$isFLblue[storecolor$note == 'groundworks farm, in wicomico county' & storecolor$field_note == "fl bl;fl yl;white; "] <- 'FLblue'
storecolor$isFLyellow[storecolor$note == 'groundworks farm, in wicomico county' & storecolor$field_note == "fl bl;fl yl;white; "] <- 'FLyellow'
#parse field notes to extract color (which colors are present, not the number of traps of specific colors)
#fl blue
toMatchFLblue <- "(?:fb|fl bl|flbl|flb|fl blue|fluorescent blue|uv-blue|fl. blue|uv blue|florescent blue|blue-uv)"
flbluetransects <- unique(storecolor$TransectID[!is.na(str_match(storecolor$field_note, toMatchFLblue))])
storecolor$isFLblue[storecolor$TransectID %in% flbluetransects] <- 'FLblue'
#fl yellow
toMatchFLyellow <- "(?:fy|fl yl|flyl|fly|fl yellow|fluorescent yellow|uv-yellow|fl. yellow|uv yellow|yellow-uv|florescent yellow)"
flyellowtransects <- unique(storecolor$TransectID[!is.na(str_match(storecolor$field_note, toMatchFLyellow))])
storecolor$isFLyellow[storecolor$TransectID %in% flyellowtransects] <- 'FLyellow'
#fl white
toMatchFLwhite <- "(?:fw|fl wh|flwh|flw|fl white|fluorescent white|uv-white|fl. white|uv white)"
flwhitetransects <- storecolor$TransectID[!is.na(str_match(storecolor$field_note, toMatchFLwhite))]
storecolor$isFLwhite[storecolor$TransectID %in% flwhitetransects] <- 'FLwhite'
#blue
toMatchblue <- "[ ,;.]+(?:b|bl|bly)[ ,;.)]|[ ,;.]+(?:b|bl|bly)[ ,;.]|blue"
bluetransects <- storecolor$TransectID[!is.na(str_match(storecolor$field_note, toMatchblue))]
bluetransects <- bluetransects[!bluetransects %in% flbluetransects]
storecolor$isblue[storecolor$TransectID %in% bluetransects] <- 'blue'
#yellow
toMatchyellow <- "[ ,;.]+(?:y|yl|ylw|yllw)[,;.]|yellow"
yellowtransects <- storecolor$TransectID[!is.na(str_match(storecolor$field_note, toMatchyellow))]
yellowtransects <- yellowtransects[!yellowtransects %in% flyellowtransects]
storecolor$isyellow[storecolor$TransectID %in% yellowtransects] <- 'yellow'
#white
toMatchwhite <- "[ ,;.]+(?:w|wh|wt|wht)[,;.]|white"
whitetransects <- storecolor$TransectID[!is.na(str_match(storecolor$field_note, toMatchwhite))]
whitetransects <- whitetransects[!whitetransects %in% flwhitetransects]
storecolor$iswhite[storecolor$TransectID %in% whitetransects] <- 'white'
##### Part Three: Extract trap volume from field_note and note columns for each specimen
#Fill in trap volume from external data sources
#glycol woods study used 12 oz bowls (personal communication from Grace Savoy Burke, University of Delaware)
storecolor$TrapVolume[grepl(storecolor$note, pattern='woods glycol study', fixed=T)] <- 'bowl 12.0oz'
storecolor$TrapVolume[storecolor$TrapVolume == 'in field note'] <- NA
#parse trap volume from field notes if not recorded in 'TrapVolume' column
toMatchVolume <- "([0-9]+(\\.[0-9]+)?)(?:oz|oz.|ounce|Oz|Oz.)[ ,;.]|([0-9]+(\\.[0-9]+)?)[ ,;.]+(?:oz|oz.|ounce|Oz|Oz.)[ ,;.]"
matching <- str_match(storecolor$field_note, toMatchVolume)
matching <- data.frame(matching); matching <- dplyr::select(matching, X1, X2, X4)
matching$X2 <- as.numeric(as.character(matching$X2)); matching$X4 <- as.numeric(as.character(matching$X4))
matching2 <- str_match(storecolor$note, toMatchVolume)
matching2 <- data.frame(matching2); matching2 <- dplyr::select(matching2, X1, X2, X4)
matching2$X2 <- as.numeric(as.character(matching2$X2)); matching2$X4 <- as.numeric(as.character(matching2$X4))
#For trap volume > 40 oz, assign NA value. > 40 oz is a mistake in parsing, not actual sampling method
sum1 <- rowSums(matching[,2:length(matching)], na.rm=T); sum1[sum1 > 40] <- 0
sum2 <- rowSums(matching2[,2:length(matching2)], na.rm=T); sum2[sum2 > 40] <- 0
trapvolume <- sum1 + sum2
storecolor$TrapVolumeParsed <- paste0("bowl ", trapvolume, "oz")
storecolor$TrapVolumeParsed[storecolor$TrapVolumeParsed == 'bowl 0oz'] <- NA
#reassign trap volumes within half an ounce to the most frequent value (3, 3,25, and 3.5 become 3.25)
storecolor$TrapVolumeParsed[storecolor$TrapVolumeParsed %in% c("bowl 3oz", "bowl 3.5oz")] <- "bowl 3.25oz"
#reformat parsed volumes so they match 'TrapVolume' column
storecolor$TrapVolume <- gsub(storecolor$TrapVolume, pattern=".0", replacement="", fixed=T)
#how many observations have trap volume information that conflicts?
storecolor <- dplyr::mutate(storecolor, VolumesAgree= TrapVolume == TrapVolumeParsed) %>%
dplyr::mutate(VolumesAgree = replace_na(VolumesAgree, FALSE))
#when recorded trapvolume and parsed trap volume disagree, use recorded value assuming field note is incorrect
#(seems to be same field note with different pan volumes recorded, maybe different volume traps at same site, but probably unlikely)
storecolor <- dplyr::mutate(storecolor, TrapVolumeFinal= dplyr::if_else(is.na(TrapVolume), TrapVolumeParsed, TrapVolume)) %>%
dplyr::mutate(TrapVolumeFinal= if_else(is.na(TrapVolumeFinal), "UNK", TrapVolumeFinal))
##### Part Four: Summarize number of successful traps associated with each specimen (successful = number set out - number missing)
#create columns for number of traps reported and NTraps parsed from field notes
#create column for final number of traps by taking minimum of reported and parsed NTraps
#evidence that sometimes missing traps were excluded from field notes and recorded in NTraps AND
#sometimes the reverse. aka NTraps doesn't include missing traps, but they are noted in field notes.
storecolor <- dplyr::mutate(storecolor, Nreported=as.character(NTraps)) %>%
dplyr::mutate(Nreported=if_else(Nreported %in% c('in field note', 'UNK', "") | is.na(Nreported), '0', Nreported)) %>%
dplyr::mutate(Nreported= as.numeric(Nreported),
Nparse=rowSums(dplyr::select(storecolor, nwhite, nblue, nyellow, nFLblue, nFLyellow, nFLwhite), na.rm=T),
Nmissing=nmissing,
Nmatch= (Nreported == (Nparse-Nmissing))) %>%
dplyr::group_by(identifier) %>%
dplyr::mutate(NTrapsFinal = dplyr::if_else(Nreported > 0 & Nparse > 0 , min(Nreported, (Nparse-Nmissing)), max(Nreported, (Nparse-Nmissing))),
trapdays = as.numeric(trapdays)) %>%
dplyr::select(-nmissing)
#check NTrapsFinal (against field notes and NTraps reported)
ntraps_check <- ungroup(storecolor) %>%
dplyr::select(TransectID, year,state, field_note, note, starts_with("N"),starts_with("is"), -name) %>%
dplyr::filter(!duplicated(paste(TransectID, NTrapsFinal))) %>%
dplyr::arrange(TransectID)
#create Abundance per day and Abundance per trap per day variables
#subset data to observations that have number of traps reported (from NTraps OR parsed field_note)
storecolor2 <- dplyr::mutate(storecolor, MaxNTraps = if_else(NTrapsFinal == 0, NTraps, as.factor(NTrapsFinal)))
storecolor2$MaxNTraps[storecolor2$MaxNTraps %in% c("", "in field note", "UNK")] <- NA
storecolor2$MaxNTraps <- as.numeric(storecolor2$MaxNTraps)
storecolor <- dplyr::filter(storecolor2, MaxNTraps > 0) %>%
dplyr::mutate(Abundance=as.numeric(Abundance),
trapdays= if_else(trapdays == 0, 1, trapdays),
AbundDay=Abundance/trapdays,
AbundTrap=Abundance/NTrapsFinal,
AbundDayTrap=AbundDay/NTrapsFinal)
storecolor <- ungroup(storecolor) %>%
dplyr::na_if('no')
write.csv(storecolor, './data/Droege_MDDE_subset_withtrapinfo.csv')
rm(list=ls())
|
215aea937bde226ceb1cda53ce05dcad9474d4a0
|
c7c8a7014ed39e8f94f81cc5d148aba8ee42efc6
|
/R/emd.R
|
c640c0c7b295e784ac6570accddfd6798901c550
|
[
"MIT"
] |
permissive
|
s-u/emdist
|
22b637d8fdb982d922d786622e22e18885dec07d
|
ccb2f64492716856ab3c1e78d1e62a0da1772211
|
refs/heads/master
| 2023-06-25T13:04:38.147833
| 2023-06-13T04:13:10
| 2023-06-13T04:13:10
| 41,175,417
| 2
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 851
|
r
|
emd.R
|
# this was the original API but now we just map it to the matrix API
emd2d <- function(A, B, xdist = 1, ydist = 1, dist="euclidean", ...) {
if (!is.matrix(A) || !is.matrix(B) || !identical(dim(A), dim(B))) stop("A and B must be matrices of the same dimensions")
m = dim(A)[1]
n = dim(B)[2]
A[is.na(A)] = 0
B[is.na(B)] = 0
A = matrix(c(A, rep((1:m) * ydist, n), rep((1:n) * xdist, each = m)), m * n)
B = matrix(c(B, A[,2], A[,3]), m * n)
emd(A[A[,1] != 0,,drop=FALSE], B[B[,1] != 0,,drop=FALSE], dist=dist, ...)
}
emdr <- function(A, B, extrapolate=NA, flows=FALSE, dist="euclidean", max.iter=500L, ...) .Call(emd_r, A, B, extrapolate, flows, dist, max.iter)
emd <- function(A, B, dist="euclidean", ...) emdr(A, B, dist=dist, ...)
emdw <- function(A, wA, B, wB, dist="euclidean", ...) emd(cbind(wA, A), cbind(wB, B), dist=dist, ...)
|
b002bb045d8f4991d86a961e0eb014c57e595131
|
1f6f5f8305d88a0e731d29ea7f95f4336a3d30e1
|
/R/simple.R
|
5b4a3754dbd79ff25e0a7aab9376e144bac226fe
|
[] |
no_license
|
lucillemellor/bugSigSimple
|
f385fc5232f29ae760ce1ec1a7f3f4df78d89810
|
b6472dd02f7028f3d60999bd0927f289d27aaee3
|
refs/heads/master
| 2022-10-25T15:23:04.147170
| 2020-05-02T12:54:40
| 2020-05-02T12:54:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,279
|
r
|
simple.R
|
############################################################
#
# author: Ludwig Geistlinger
# date: 2019-03-13 17:01:25
#
# descr: simple exploratory analysis for curated signatures
#
###########################################################
readCurationSheet <- function(data.file)
{
dat <- read.delim(data.file, skip=1, as.is=TRUE)
ind <- dat[,"PMID"] != ""
dat <- dat[ind,]
dat <- dat[-1,]
return(dat)
}
subsetByCondition <- function(dat, condition, condition.column="condition")
{
ind <- dat[,condition.column] == condition
return(dat[ind,])
}
subsetByCurator <- function(dat, curator, curator.column="curator")
{
ind <- dat[,curator.column] == curator
return(dat[ind,])
}
extractSignatures <- function(dat)
{
ind <- grep("^taxon.1$", colnames(dat))
ind <- ind:ncol(dat)
msc <- apply(as.matrix(dat[,ind]), 1, function(x) x[!is.na(x) & x != ""])
return(msc)
}
getMostFrequentTaxa <- function(dat, n=10, sig.type=c("BOTH", "UP", "DOWN"))
{
sig.type <- match.arg(sig.type)
if(sig.type %in% c("UP", "DOWN"))
{
ind <- dat[,"UP.or.DOWN"] == sig.type
dat <- dat[ind,]
}
msc <- extractSignatures(dat)
msc.tab <- sort(table(unlist(msc)), decreasing=TRUE)
head(msc.tab, n=n)
}
|
e99e9818accc8fdf33faa751495f23b98cfbeea8
|
a7ce793ccaacf9745409ed24cb755a69445825fb
|
/R/make_updated_layout.R
|
79627836eca17965419a3dc5d822c2b2e694b664
|
[
"MIT"
] |
permissive
|
taiawu/echowritr
|
0b88a386a52d041ed087de5eb3b79bef18637fce
|
2c03951edeefdb080394a025afc6925d639f79ee
|
refs/heads/master
| 2023-05-04T23:43:01.378936
| 2021-05-27T22:38:06
| 2021-05-27T22:38:06
| 366,892,363
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,436
|
r
|
make_updated_layout.R
|
#' Update starting layout with final conditions
#'
#' @param transfers the transfers tibble
#' @param raw_layout the raw layout, as uploaded by the user
#'
#' @return a list of 2 elements. layout, the updated layout, and wide_layout, the updated layout in wideform, ready to be saved as a csv.
#'
#' @importFrom dplyr filter rename select across right_join
#' @importFrom tidyselect all_of everything
#' @importFrom purrr set_names
#' @export
make_updated_layout <- function(transfers, raw_layout) {
updated_layout <- transfers %>%
filter(.data$transfer_type == "compound_transfer") %>% # not dilutions
rename("well" = .data$`Destination Well`) %>%
select(all_of(c("well", "compound", "final_conc", "rounded_up"))) %>%
set_names(c("well", "final_compound", "final_concentration", "concentration_rounded_by")) %>%
right_join( . , raw_layout, by = "well")
to_layout_block <- updated_layout %>%
select(-any_of(c("row", "column", "well"))) %>%
names()
for_wide <- updated_layout %>%
mutate(across(.cols = everything(), as.character)) %>%
add_empty_wells() %>%
replace(is.na(.), "Empty") %>%
bind_layouts( . , to_layout_block )
list(layout = updated_layout,
wide_layout = for_wide)
}
#' Make wideform layouts for multiple variables
#'
#' A helper function for make_updated_layout().
#' Relies on its own helper function, make_layout_wide().
#' Ultimately, this function and its helpers should be a part of a different package--likely the layouts package, if we ever get that thing done.
#'
#' @param data a layout
#' @param var_list the columns in the layout to be make into individual layout blocks
#'
#' @return a tibble of wideform layout blocks, ready to be saved as a csv
#'
#' @importFrom dplyr bind_rows
#' @importFrom purrr set_names
#'
#' @export
bind_layouts <- function(data, var_list) {
var_list %>%
lapply( . , function(x) make_layout_wide(data, x)) %>%
bind_rows() %>%
set_names(c("Type", "row", c(1:(ncol(.)-2))))
}
#' Convert a single layout variable into a wideform layout block
#'
#' A helper function to make_updated_layout.
#' Ultimately, this function should be a part of a different package--likely the layouts package, if we ever get that thing done.
#'
#' @param data the layout
#' @param .filt_col a single column in data to be converted into a layout block
#' @param .fill_empties what to fill in for wells without contents. Defaults to "Empty"
#'
#' @return A tibble, containing a wideform layout block.
#'
#' @importFrom dplyr select mutate distinct arrange across relocate
#' @importFrom tidyr replace_na pivot_wider unnest
#' @importFrom tidyselect everything
#' @importFrom rlang `:=`
#'
#' @export
make_layout_wide <- function(data, .filt_col, .fill_empties = "Empty") {
data %>%
select(.data$row, .data$column, {{ .filt_col }}) %>%
mutate("{.filt_col}" := replace_na(!!sym(.filt_col), .fill_empties)) %>%
distinct() %>%
mutate(column = as.numeric(.data$column)) %>%
arrange(.data$column) %>%
pivot_wider(id_cols = .data$row, names_from = .data$column, values_from = {{ .filt_col }}) %>%
mutate(across(cols = everything(), as.character())) %>%
rbind(names(.), .) %>%
mutate(Type = {{ .filt_col }} ) %>%
relocate(all_of("Type")) %>%
unnest(cols = c(everything())) # this is a save that keeps bind_rows() from failing if these are list columns, but they really shouldn't be...
}
|
ef7c11f5faa46df1f18b8ff09c43c847e5ad2d13
|
859a2bdab8ba9943fffde77a0a930ba877c80fd9
|
/man/get_bam_SM.Rd
|
9bfff5911877acc7a5051656a952028c55256abc
|
[
"MIT"
] |
permissive
|
alkodsi/ctDNAtools
|
e0ed01de718d3239d58f1bfd312d2d91df9f0f0d
|
30bab89b85951282d1bbb05c029fc333a139e044
|
refs/heads/master
| 2022-03-20T11:47:06.481129
| 2022-02-20T11:25:48
| 2022-02-20T11:25:48
| 208,288,617
| 30
| 9
| null | null | null | null |
UTF-8
|
R
| false
| true
| 387
|
rd
|
get_bam_SM.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_bam_SM.R
\name{get_bam_SM}
\alias{get_bam_SM}
\title{Helper function to extract SM from a bam file}
\usage{
get_bam_SM(bam, tag = "")
}
\arguments{
\item{bam}{Path to the bam file}
\item{tag}{The RG tag for the bam file}
}
\description{
Helper function to extract SM from a bam file
}
\keyword{internal}
|
9727b8a09c342b8a8226923b072c4852345ae29d
|
d8f5550dbbe4696c170d391e09d00738714c5dd0
|
/man/getCosmicSignatures.Rd
|
73adb17d2f948f4bb027a5aed3d86bb6fafa2415
|
[] |
no_license
|
dami82/mutSignatures
|
19e044eb99ee8c65c4123c131fa978bd5bd9d93c
|
ad406018266f80a3048ae6219bf6c09cf6f69134
|
refs/heads/master
| 2023-01-24T00:39:46.026623
| 2023-01-18T21:22:55
| 2023-01-18T21:22:55
| 123,127,851
| 12
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,346
|
rd
|
getCosmicSignatures.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/s03_all_functions.R
\name{getCosmicSignatures}
\alias{getCosmicSignatures}
\title{Obtain COSMIC mutational Signatures.}
\usage{
getCosmicSignatures(forceUseMirror = FALSE, asMutSign = TRUE)
}
\arguments{
\item{forceUseMirror}{logical, shall signatures be downloaded from a mirror. Set to TRUE if the COSMIC
server goes down.}
\item{asMutSign}{logical, shall data be returned as a mutSignatures-class object. Defaults to TRUE}
}
\value{
an object storing COSMIC mutational signature data
}
\description{
Obtain latest mutational Signature definitions from COSMIC. FOr more info, please visit: \url{http://cancer.sanger.ac.uk/}
}
\details{
This function is part of the user-interface set of tools included in mutSignatures. This is an exported function.
}
\references{
More information and examples about mutational signature analysis can be found here:
\enumerate{
\item \bold{Official website}: \url{http://www.mutsignatures.org}
\item \bold{More info and examples} about the mutSignatures R library: \url{https://www.data-pulse.com/dev_site/mutsignatures/}
\item \bold{Oncogene paper}, Mutational Signatures Operative in Bladder Cancer: \url{https://www.nature.com/articles/s41388-017-0099-6}
}
}
\author{
Damiano Fantini, \email{damiano.fantini@gmail.com}
}
|
ce748e8f76fe081f947a4f0083538c7d19f731df
|
e24a971a2eca8d0029dbaf4ee2332a4a9feeb343
|
/housing data second attempt.R
|
102dcfa433aa4b2a569d87dcf069d568d91ea390
|
[] |
no_license
|
kdani99/mid-term.R
|
3b61bc8ef899bee9ea18884016b769d532093c19
|
881ada94ea0e038f97efbe3048ec8aee4f59df33
|
refs/heads/master
| 2021-01-21T08:14:54.189657
| 2017-09-02T05:57:49
| 2017-09-02T05:57:49
| 101,956,048
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,801
|
r
|
housing data second attempt.R
|
#mydata1<-read.csv("train_2016_v2.csv")
#mydata1
#mydata2<-read.csv("properties_2016.csv")
#mydata2
#mydata<-merge(mydata1,mydata2,by="parcelid",all= FALSE)#merge two datasets 2016; mydata only contains 2016 observations
#summary(mydata)
#######generate the 2016 dataset
#write.table(mydata, "/Users/andy/desktop/data1.txt", sep="\t")
setwd("/Users/andy/desktop");getwd()
mydata2016<-read.table("data2016.txt",header=TRUE)
######deleting variables whose missing values are bigger than 50%.
mydata2016$airconditioningtypeid <- NULL
mydata2016$architecturalstyletypeid <- NULL
mydata2016$basementsqft <- NULL
mydata2016$buildingclasstypeid <- NULL
mydata2016$decktypeid <- NULL
mydata2016$threequarterbathnbr<- NULL
mydata2016$finishedfloor1squarefeet <- NULL
mydata2016$finishedsquarefeet6 <- NULL
mydata2016$finishedsquarefeet13 <- NULL
mydata2016$finishedsquarefeet15 <- NULL
mydata2016$finishedsquarefeet50 <- NULL
mydata2016$fireplacecnt <- NULL
mydata2016$fips <- NULL
mydata2016$garagecarcnt <- NULL
mydata2016$garagetotalsqft <- NULL
mydata2016$hashottuborspa <- NULL
mydata2016$latitude <- NULL
mydata2016$longitude <- NULL
mydata2016$numberofstories <- NULL
mydata2016$poolcnt <- NULL
mydata2016$poolsizesum <- NULL
mydata2016$pooltypeid10 <- NULL
mydata2016$pooltypeid2 <- NULL
mydata2016$pooltypeid7 <- NULL
mydata2016$rawcensustractandblock <- NULL
mydata2016$censustractandblock<- NULL
mydata2016$regionidcounty <- NULL
mydata2016$regionidzip <- NULL
mydata2016$regionidneighborhood <- NULL
mydata2016$storytypeid <- NULL
mydata2016$typeconstructiontypeid<- NULL
mydata2016$yardbuildingsqft17 <- NULL
mydata2016$yardbuildingsqft26 <- NULL
mydata2016$assessmentyear <- NULL
mydata2016$taxdelinquencyyear <- NULL
###take out a few variables for the for loop
mydata2016$transactiondate <- NULL
mydata2016$parcelid <- NULL
mydata2016$fireplaceflag <- NULL
####deleting all observations with missing values
mydata2016_noNA <- na.omit(mydata2016)
mydata2016_noNA
dim(mydata2016_noNA)
summary(mydata2016_noNA)
attach(mydata2016_noNA)
######tease out outliers:Q3+1.5IQR
lapply(mydata2016_noNA,class)###find classes for all columns
ThresholdforOutlier <- rep(0,24)
order=c(1:10,12,14:21) #exclude the factor variables
for (i in order){
t1 <- quantile(mydata2016_noNA[,i], 0.75)
t2 <- IQR(mydata2016_noNA[,i], 0.75)
ThresholdforOutlier[i] <- t1 + 1.5*t2
}
for (i in 1:50652)
for (j in order){
if (mydata2016_noNA[i,j] > ThresholdforOutlier[j]) mydata2016_noNA[i,j] <- NA
}
summary(mydata2016_noNA)
####mydata contains clean data with all 22 variables and 32575 observations
mydata <- na.omit(mydata2016_noNA)
dim(mydata)
### delete
mydata$propertycountylandusecode<- NULL
mydata$propertyzoningdesc<- NULL
###build a new variable:age
mydata$age = 2016-mydata$yearbuilt##age= 2016-year when it built
mydata$yearbuilt<- NULL
summary(mydata)
###turn factor variable taxdelinquencyflag into numberic variable: 0 means No, 1 means YES.
mydata$taxdelinquencyflag_new <- as.numeric(mydata$taxdelinquencyflag)#turn factor variable into numeric variable
mydata$taxdelinquencyflag_newDUMMY = mydata$taxdelinquencyflag_new-1##create a 0/1 dummy variable for taxdelinquencyflag
mydata$taxdelinquencyflagY<- NULL
mydata$taxdelinquencyflag_new<- NULL
mydata$taxdelinquencyflag<- NULL
######
######create a training and test data
data.train = mydata[sample(nrow(mydata),22803),]
data.test = mydata[-sample(nrow(mydata),22803),]
####generate train and test datasets
write.table(data.train, "/Users/andy/desktop/data.train.txt", sep="\t")
write.table(data.test, "/Users/andy/desktop/data.test.txt", sep="\t")
# double check
summary(data.train)
dim(data.train)
summary(data.test)
dim(data.test)
#######
#######A Linear Regression Model
#######
####Check collinearity among variables.
#landtaxvaluedollarcnt & Other variables
cor(landtaxvaluedollarcnt,calculatedbathnbr)#0.3632316
cor(landtaxvaluedollarcnt,finishedsquarefeet12)#0.4497032
cor(landtaxvaluedollarcnt,fullbathcnt)#0.3632316
####unitcnt & Other variables: no high correlation
####roomcnt & Other variables: no high correlation
####fullbathcnt & Other variables.
cor(fullbathcnt,finishedsquarefeet12)###0.7862645; take out finishedsquarefeet12
cor(fullbathcnt,calculatedbathnbr)###1: only keep one variable fullbathcnt
####finishedsquarefeet12 & calculatedbathnbr
cor(finishedsquarefeet12,calculatedbathnbr)#0.7862645
#######build a linear regression model based on test dataset
fit<-lm(logerror~.-calculatedbathnbr-finishedsquarefeet12-landtaxvaluedollarcnt-fullbathcnt-roomcnt-unitcnt,data=data.train)
fitfinal<-step(fit,direction="both")#use forward and backward selections to get our final model.
summary(fitfinal)
############
############Decision Tree
############
library(rpart)
##grow tree
fitDT<-rpart(logerror~bedroomcnt+buildingqualitytypeid+calculatedfinishedsquarefeet+regionidcity+structuretaxvaluedollarcnt+taxvaluedollarcnt+taxvaluedollarcnt+taxamount+age+taxdelinquencyflag_newDUMMY,method="anova",na.action = na.rpart,data=data.train)
summary(fitDT)
######
printcp(fitDT)#display the results
plotcp(fitDT)#visualize cross-validation results
summary(fitDT)#detailed summary of splits
par(mfrow=c(1,2))#two plots on one page
rsq.rpart(fitDT)
plot(fitDT,uniform=TRUE,main="Housing Price for 2017");text(fitDT,use.n=TRUE, all=TRUE,cex=0.6)##fitted model is just a root, not a tree.
############
############Random Forest
############
setwd("/Users/andy/desktop");getwd()
data.train<-read.table("data.train",header=TRUE)
install.packages("randomForest")
library(randomForest)
fitRF<-randomForest(logerror~bedroomcnt+buildingqualitytypeid+calculatedfinishedsquarefeet+regionidcity+structuretaxvaluedollarcnt+taxvaluedollarcnt+taxvaluedollarcnt+taxamount,method="anova",data=data.train)
print(fitRF)
importance(fitRF)
|
e6f359293a2f1f7025cd45e181dd197ccb124efc
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/CorrToolBox/examples/pbs2bs.Rd.R
|
c563621709bd0f79330fe8cc0a22a1922cc76953
|
[] |
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
| 511
|
r
|
pbs2bs.Rd.R
|
library(CorrToolBox)
### Name: pbs2bs
### Title: Computation of the Biserial Correlation from the Point-Biserial
### Correlation
### Aliases: pbs2bs
### ** Examples
set.seed(123)
y1<-rweibull(n=100000, scale=1, shape=1.2)
gaussmix <- function(n,m1,m2,s1,s2,pi) {
I <- runif(n)<pi
rnorm(n,mean=ifelse(I,m1,m2),sd=ifelse(I,s1,s2))
}
y2<-gaussmix(n=100000, m1=0, s1=1, m2=3, s2=1, pi=0.6)
pbs2bs(pbs=0.25, bin.var=y1, cont.var=y2, p=0.55)
pbs2bs(pbs=0.25, bin.var=y1, cont.var=y2, cutpoint=0.65484)
|
886c0ad237971f43146336d97c37ab72428c3f92
|
1dfecbca8017ac66df7abd497f86982778628b3a
|
/man/datamaps-shiny.Rd
|
54b006d09faf5a3c3125a09f48d75610eaae22c1
|
[] |
no_license
|
jimsforks/datamaps
|
ff4972bf64b09b01bf634a29e17c0c76c674f741
|
e186d012f452c64814587ed1ce18a39fdbdcfabf
|
refs/heads/master
| 2022-12-08T11:33:35.297391
| 2020-08-27T09:46:44
| 2020-08-27T09:46:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,101
|
rd
|
datamaps-shiny.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/datamaps.R
\name{datamaps-shiny}
\alias{datamaps-shiny}
\alias{datamapsOutput}
\alias{renderDatamaps}
\alias{datamapsProxy}
\title{Shiny bindings for datamaps}
\usage{
datamapsOutput(outputId, width = "100\%", height = "400px")
renderDatamaps(expr, env = parent.frame(), quoted = FALSE)
datamapsProxy(id, session = shiny::getDefaultReactiveDomain())
}
\arguments{
\item{outputId}{output variable to read from}
\item{width, height}{Must be a valid CSS unit (like \code{'100\%'},
\code{'400px'}, \code{'auto'}) or a number, which will be coerced to a
string and have \code{'px'} appended.}
\item{expr}{An expression that generates a datamaps}
\item{env}{The environment in which to evaluate \code{expr}.}
\item{quoted}{Is \code{expr} a quoted expression (with \code{quote()})? This
is useful if you want to save an expression in a variable.}
\item{id}{id of map.}
\item{session}{shiny session.}
}
\description{
Output and render functions for using datamaps within Shiny
applications and interactive Rmd documents.
}
|
f360d42ab5e0d61e3c2a5c83e1e229e95ca87b1f
|
8d1eb4a9f2abcebe51ac93f0b8308763ce88f02a
|
/Clean Script.R
|
6eea85924e640fe2183828a2cf9c17a01caf7322
|
[
"MIT"
] |
permissive
|
sean-connelly/PBL-Networks
|
b907272810421f1edde5ea7c1e34183843810b12
|
6e09faf457858b59174e292388c7519fc3877faf
|
refs/heads/master
| 2020-03-16T17:16:19.490713
| 2018-06-02T17:45:23
| 2018-06-02T17:45:23
| 132,824,604
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,074
|
r
|
Clean Script.R
|
library(hrbrthemes);library(tidyverse)
library(stringr);library(lubridate)
library(zoo);library(scales)
library(sf);library(janitor)
library(viridis);library(leaflet)
options(scipen = 1000,stringsAsFactors = F)
setwd("E:/Data/PBL-Networks")
#=============
#Washington, DC
#=============
#Shapefile
dc <- st_read("Bicycle_Lanes.shp")
#Standardize
dc <- dc %>%
mutate(City = "Washington DC",
Facility_Type = FACILITY,
Facility_Class = NA_character_,
Miles = BIKELANELE,
Install_Year = ifelse(YEAR_INSTA==0,BIKELANE_Y,YEAR_INSTA)) %>%
select(City,Facility_Type,Facility_Class,Miles,Install_Year,geometry) %>%
filter(Facility_Type %in% c("Climbing Lane","Contraflow Bike Lane",
"Cycle Track","Existing Bike Lane"))
#Write local copy
st_write(dc,"./Shapefiles/Washington.shp")
#=============
#Seattle, WA
#=============
#Shapefile
seattle <- st_read("Existing_Bike_Facilities.shp")
#Standardize
seattle <- seattle %>%
mutate(City = "Seattle",
Facility_Type = existing_f,
Facility_Class = NA_character_,
Miles = length_mil,
Install_Year = year(date_compl)) %>%
select(City,Facility_Type,Facility_Class,Miles,Install_Year,geometry) %>%
filter(Facility_Type %in% c("In Street, Major Separation","Multi-use Trail",
"In Street, Minor Separation"))
#Write local copy
st_write(seattle,"./Shapefiles/Seattle.shp")
#=============
#New York, NY
#=============
#Shapefile
nyc <- st_read("geo_export_1f1902f2-5525-4be8-96e1-65cd9edee28a.shp")
#Standardize
nyc <- nyc %>%
mutate(City = "New York City",
Facility_Type = coalesce(ft_facilit,tf_facilit),
Facility_Class = paste0("Class ",allclasses),
Miles = NA_real_,
Install_Year = year(date_instd)) %>%
select(City,Facility_Type,Facility_Class,Miles,Install_Year,geometry) %>%
filter(Facility_Class %in% c("Class I","Class II"))
#Transform
nyc <- nyc %>%
st_transform(crs = "+proj=longlat +datum=WGS84 +no_defs")
#Write local copy
st_write(nyc,"./Shapefiles/New_York_City.shp")
#=============
#Madison, WI
#=============
#Shapefile
madison <- st_read("Bike_Paths.shp")
#Standardize
madison <- madison %>%
filter(Status=="EX") %>%
mutate(City = "Madison",
Facility_Type = NA_character_,
Facility_Class = case_when(BFuncClass=="P" ~
"Class I",
BFuncClass=="S" ~
"Class II",
TRUE ~ NA_character_),
Miles = NA_real_,
Install_Year = as.numeric(Year)) %>%
select(City,Facility_Type,Facility_Class,Miles,Install_Year,geometry) %>%
filter(Facility_Class %in% c("Class I","Class II"))
#Write local copy
st_write(madison,"./Shapefiles/Madison.shp")
#=============
#San Francisco, CA
#=============
#Shapefile
sfca <- st_read("geo_export_32227f06-1806-42d8-8b58-0bd06a3742f2.shp")
#Standardize
sfca <- sfca %>%
mutate(City = "San Francisco",
Facility_Type = symbology,
Facility_Class = facility_t,
"Miles" = length,
Install_Year = coalesce(install_yr,year(date_creat))) %>%
select(City,Facility_Type,Facility_Class,Miles,Install_Year,geometry) %>%
filter(Facility_Class %in% c("CLASS I","CLASS II"))
#Transform CRS
sfca <- sfca %>%
st_transform(crs = "+proj=longlat +datum=WGS84 +no_defs")
#Write local copy
st_write(sfca,"./Shapefiles/San_Francisco.shp")
#=============
#Portland, OR
#=============
#Shapefile
pdx <- st_read("Bicycle_Network.shp")
#Standardize
pdx <- pdx %>%
filter(Status=="ACTIVE") %>%
mutate(City = "Portland",
Facility_Type = case_when(Facility=="ABL" ~
"Advisory Bike Lane",
Facility=="BBL" ~
"Buffered Bike Lane",
Facility=="BL" ~
"Bike Lane",
Facility=="ESR" ~
"Enhanced Shared Roadway",
Facility=="NG" ~
"Neighborhood Greenway",
Facility=="PBL" ~
"Protected Bike Lane",
Facility=="SIR" ~
"Separated In Roadway",
Facility=="TRL" ~
"Trail",
TRUE ~ NA_character_),
Facility_Class = NA_character_,
Miles = LengthMile,
Install_Year = as.numeric(YearBuilt)) %>%
select(City,Facility_Type,Facility_Class,Miles,Install_Year,geometry) %>%
filter(Facility_Type %in% c("Buffered Bike Lane","Bike Lane","Protected Bike Lane",
"Separated In Roadway","Trail"))
#Write local copy
st_write(pdx,"./Shapefiles/Portland.shp")
|
c8174871c8340c17162f81c3817458a4640e7ee6
|
a38a7b8a426e0fd0232e73271119a06b780fd754
|
/man/ConvertQTableToArray.Rd
|
baf50c03fc18bb0a4da604d0099a8a4541fa4155
|
[] |
no_license
|
Displayr/flipTables
|
d78e1806ceea736e3bbb5671244fa8567c06f575
|
1eabee54b3afc680f40b297b2adb72dd73562f75
|
refs/heads/master
| 2023-08-08T17:05:18.365268
| 2023-08-08T02:03:47
| 2023-08-08T02:03:47
| 46,451,632
| 0
| 1
| null | 2023-08-08T02:03:49
| 2015-11-18T22:28:27
|
R
|
UTF-8
|
R
| false
| true
| 658
|
rd
|
ConvertQTableToArray.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/convertqtabletoarray.R
\name{ConvertQTableToArray}
\alias{ConvertQTableToArray}
\title{Converts a Q Table into an array}
\usage{
ConvertQTableToArray(x)
}
\arguments{
\item{x}{A Q table which is expected to have the attributes
typically associated with tables, e.g. "questions", "name"
and "statistic" (if there is only one statistic).}
}
\value{
The output is always a 3d array, so that 1-column vector
is converted to an array with 3 dimensions (but last two have
a length of 1). This makes it easy to identify the statistics.
}
\description{
Converts a Q Table into an array
}
|
22de2b80e63630c182c3ac9a719cfd810a380ea4
|
3fbe6c22107ec3a6287859b6d04bbc19e848e73a
|
/sankey2016.R
|
5fc827c54d0684bc0600de19afd68b248d5dcb42
|
[] |
no_license
|
angelamhkim/vizportfolio
|
4046c84ea957870cd16df6da8c98f0df9d1d2ddb
|
5a870ee26dc28877c06afe7dbbfc25acb42b1edc
|
refs/heads/master
| 2020-06-29T04:06:56.561254
| 2019-08-04T19:25:53
| 2019-08-04T19:25:53
| 200,436,490
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,838
|
r
|
sankey2016.R
|
#load libraries
library(foreign)
library(plotly)
#2016 elections
#read the data, downloaded DTA from the American National Election Studies Data Center
dat <- read.dta("anes_timeseries_2016_Stata12.dta")
#get a subset of the data for the variables we're interested in:
#V161006: Who did you vote for in 2012?
#V161027: Who did you vote for president?
dat <- dat[,which(names(dat)%in%c("V161006","V161027"))]
#make an answer key
previous2012 <- as.vector(unique(dat$V161006))
today2016 <- as.vector(unique(dat$V161027))
answers <- cbind(previous2012, today2016) %>% as.data.frame()
#from Obama in 2012 to
#Trump in 2016
OtoT <- length(which(as.vector(dat$V161006)==answers$previous2012[2] &
as.vector(dat$V161027)==answers$today2016[2]))
#Hilary in 2016
OtoH <- length(which(as.vector(dat$V161006)==answers$previous2012[2] &
as.vector(dat$V161027)==answers$today2016[4]))
#refused to answer or did not vote for president in 2016
OtoR <- length(which(as.vector(dat$V161006)==answers$previous2012[2] &
as.vector(dat$V161027)%in%answers$today2016[c(1,3)]))
#other candidate
OtoO <- length(which(as.vector(dat$V161006)==answers$previous2012[2] &
as.vector(dat$V161027)%in%answers$today2016[c(5,6,7)]))
#from Romney in 2012 to
#Trump in 2016
RtoT <- length(which(as.vector(dat$V161006)==answers$previous2012[3] &
as.vector(dat$V161027)==answers$today2016[2]))
#Hilary in 2016
RtoH <- length(which(as.vector(dat$V161006)==answers$previous2012[3] &
as.vector(dat$V161027)==answers$today2016[4]))
#refused to answer or did not vote for president in 2016
RtoR <- length(which(as.vector(dat$V161006)==answers$previous2012[3] &
as.vector(dat$V161027)%in%answers$today2016[c(1,3)]))
#other candidate
RtoO <- length(which(as.vector(dat$V161006)==answers$previous2012[3] &
as.vector(dat$V161027)%in%answers$today2016[c(5,6,7)]))
#2012 elections
#read and subset the data
dat12 <- read.dta("anes_timeseries_2012_Stata12.dta")
dat12 <- dat12[,which(names(dat12)%in%c("interest_whovote2008","postvote_presvtwho"))]
#make an answer key
previous2008 <- as.vector(unique(dat12$interest_whovote2008))
today2012 <- as.vector(unique(dat12$postvote_presvtwho))
answers <- cbind(previous2008, today2012) %>% as.data.frame()
#from Obama in 2008 to
#Obama in 2012
OtoOb <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[1] &
as.vector(dat12$postvote_presvtwho)==answers$today2012[2]))
#Romney in 2012
OtoRo <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[1] &
as.vector(dat12$postvote_presvtwho)==answers$today2012[4]))
#other candidate in 2012
OtoO <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[1] &
as.vector(dat12$postvote_presvtwho)==answers$today2012[5]))
#NA
OtoNA <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[1] &
as.vector(dat12$postvote_presvtwho)%in%answers$today2012[c(1,3,6,7)]))
#from McCain in 2008 to
#Obama in 2012
MtoOb <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[4] &
as.vector(dat12$postvote_presvtwho)==answers$today2012[2]))
#Romney in 2012
MtoRo <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[4] &
as.vector(dat12$postvote_presvtwho)==answers$today2012[4]))
#other candidate in 2012
MtoO <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[4] &
as.vector(dat12$postvote_presvtwho)==answers$today2012[5]))
#NA
MtoNA <- length(which(as.vector(dat12$interest_whovote2008)==answers$previous2008[4] &
as.vector(dat12$postvote_presvtwho)%in%answers$today2012[c(1,3,6,7)]))
#make sankey chart
p <- plot_ly(
type = "sankey",
orientation = "h",
node = list(
label = c("2012 Obama", "2012 Romney", "Hilary", "Trump", "2016 Other",
"2016 No Answer", "2008 Obama", "McCain", "2012 Other", "2012 No Answer"),
color = c("blue","red","blue","red","grey","grey","blue","red","grey","grey"),
pad = 15,
thickness = 20,
line = list(
color = "black",
width = 0.5
)
),
link = list(
source = c(0,0,0,0,1,1,1,1,6,6,6,6,7,7,7,7),
target = c(2,3,4,5,2,3,4,5,0,1,8,9,0,1,8,9),
value = c(62,7,3,1656,2,50,2,1214,1882,173,30,619,89,1200,31,382)
)
) %>%
layout(
title = "Basic Sankey Diagram",
font = list(
size = 10
)
)
htmlwidgets::saveWidget(as_widget(p), "sankey.html")
|
ca5d18d0bd6a29b2ee6f7ebbbe984263f7b53cd8
|
086208ed314b1b2398a80d149a09b42d4da35c1c
|
/Functions/HCM-SCS_2021-06_SeuratAnalysisPipeline.R
|
116c31cac20b117eb876b90a1534f301d8034ddc
|
[] |
no_license
|
vanrooij-lab/scRNAseq-HCM-human
|
9505497e055093a5a6b8d0feb07186c8ac2ed405
|
1b27e55e1762a69ef8faef6f0dcf30e108e31cb7
|
refs/heads/master
| 2023-08-14T13:44:48.798735
| 2023-07-21T12:19:29
| 2023-07-21T12:19:29
| 366,691,443
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 23,710
|
r
|
HCM-SCS_2021-06_SeuratAnalysisPipeline.R
|
################################################################################
# FUNCTION DEFINITIONS TO RUN ANALYSES
# Now perform the analysis
# Let's always define these functions
# To test:
# mySeuratObject = RHL_SeuratObject_merged_noMito_sel
mySeuratAnalysis = function(mySeuratObject, run_name, base_dir,
normalization.method='LogNormalize', scale.factor=10000,
do.scale=T,do.center=T,scale.max=10,features_to_use_choice='variable',
remove_genes=T, cluster_resolution=1, subdir='Rplots/') {
# type_features_to_use_PCA: variable or all
# First remove genes that are only in <5 cells
if (remove_genes) {
gene_in_cell_count = rowSums(mySeuratObject@assays[[mySeuratObject@active.assay]]@counts>0)
sel_genes = names(gene_in_cell_count)[gene_in_cell_count>4]
mySeuratObject = subset(mySeuratObject, features= sel_genes)
print(paste0('Genes removed: ', sum(gene_in_cell_count<5)))
print(paste0('Genes kept: ', sum(gene_in_cell_count>4)))
}
# Collect some info
all_genes = rownames(mySeuratObject)
# Normalize data
mySeuratObject <- NormalizeData(mySeuratObject,
normalization.method = normalization.method, scale.factor = scale.factor) # values are defaults
# Find variable features
# We won't necessarily use them for all of the analyses
mySeuratObject <- FindVariableFeatures(mySeuratObject, selection.method = "vst", nfeatures = 2000)
# Identify the 10 most highly variable genes
top30 <- head(VariableFeatures(mySeuratObject), 30)
# plot variable features with and without labels
plot1 <- VariableFeaturePlot(mySeuratObject)
ggsave(filename = paste0(base_dir,subdir,run_name,'_1_VariableFeatures.png'), plot = plot1)
plot2 <- LabelPoints(plot = plot1, points = top30, repel = TRUE, xnudge=0, ynudge=0)
ggsave(filename = paste0(base_dir,subdir,run_name,'_1_VariableFeatures_labeled.png'), plot = plot2, width=15, height=15)
# A custom hybrid method to determine which genes to take along in the analysis
VariableFeatures_mySeuratObject = VariableFeatures(mySeuratObject)
FeatureMeans = rowMeans(mySeuratObject@assays[[mySeuratObject@active.assay]]@counts)
HighestMeanFeatures = names(FeatureMeans)[order(FeatureMeans, decreasing = T)][1:100]
# venn_simple_plot_mw(list(HighestMeanFeatures=HighestMeanFeatures,VariableFeatures_mySeuratObject=VariableFeatures_mySeuratObject))
VariableOrHighMeanFeatures = unique(c(VariableFeatures_mySeuratObject, HighestMeanFeatures))
# Determine which features to use
features_to_use = if (features_to_use_choice=='all') { all_genes
} else if (features_to_use_choice=='hybrid') { VariableOrHighMeanFeatures
} else {VariableFeatures_mySeuratObject}
# scale the data
mySeuratObject <- ScaleData(mySeuratObject, features = features_to_use, do.scale=do.scale, do.center=do.center, scale.max=scale.max) # features = all_variable_features is default
mySeuratObject <- RunPCA(object=mySeuratObject, npcs = 30, verbose = FALSE, features=features_to_use)
mySeuratObject <- RunUMAP(mySeuratObject, reduction = "pca", dims = 1:30)
mySeuratObject <- FindNeighbors(mySeuratObject, reduction = "pca", dims = 1:30)
mySeuratObject <- FindClusters(mySeuratObject, resolution = cluster_resolution)
# save(list = c('mySeuratObject'), file = paste0(base_dir,'Rdata/WRL_object_bigbig_sel_AnaDone.Rdata'))
return(mySeuratObject)
}
myVarMeanPlot = function(mySeuratObject) {
print('Warning, with large matrices, this takes ages due to use of apply function')
geneSd = apply( mySeuratObject@assays[[mySeuratObject@active.assay]]@counts , 1, sd)
geneMean = rowMeans( mySeuratObject@assays[[mySeuratObject@active.assay]]@counts )
p=ggplot(data.frame(log10.count.sd=log10(geneSd), log10.count.mean=log10(.1+geneMean)),aes(x=log10.count.mean, y=log10.count.sd))+
geom_point()+theme_bw()+give_better_textsize_plot(8)
ggsave(plot = p, filename = paste0(base_dir,'Rplots/0_custom_SdVsMean_genes.png'), height=172/3-4, width=172/3-4, units='mm')
}
mySeuratAnalysis_verybasic_part2only = function(mySeuratObject,
do.scale=T,do.center=T,scale.max=10,features_to_use_choice='all', cluster_resolution=1, skip_scaling=F) {
assayType = if ('integrated' %in% names(mySeuratObject@assays)) {'integrated'} else {'RNA'}
features_to_use = if (features_to_use_choice=='all') { rownames(mySeuratObject@assays[[mySeuratObject@active.assay]]@data)
} else {VariableFeatures(mySeuratObject)}
if (!skip_scaling) {
mySeuratObject <- ScaleData(mySeuratObject, features = features_to_use, do.scale=do.scale, do.center=do.center, scale.max=scale.max) # features = all_variable_features is default
}
mySeuratObject <- RunPCA(object=mySeuratObject, npcs = 30, verbose = FALSE, features=features_to_use)
mySeuratObject <- RunUMAP(mySeuratObject, reduction = "pca", dims = 1:30)
mySeuratObject <- FindNeighbors(mySeuratObject, reduction = "pca", dims = 1:30)
mySeuratObject <- FindClusters(mySeuratObject, resolution = cluster_resolution)
return(mySeuratObject)
}
# e.g. mySeurat_genenames(current_analysis$HUonly, c('TTN','NPPA'))
mySeurat_genenames = function(mySeuratObject, gene_names, complete=T) {
if (complete) {
search_pattern = paste0(':',gene_names, '$')
} else { search_pattern = gene_names }
extended_names = sapply(search_pattern, function(current_search) {
hits = grepl(pattern = current_search, x = rownames(mySeuratObject))
if (sum(hits)==1) { return(rownames(mySeuratObject)[hits]) } else { return(NA) }
} )
return(extended_names)
}
mySeuratCommonPlots = function(mySeuratObject,
run_name,
mymarkers = c('MALAT1', 'TTN', 'MYH7', 'MYH6', 'NPPA', 'NPPB', 'ACTA1','MYL2','SORBS2','CSRP3','NDUFA4','CRYAB','HSPB1', 'KCNQ1OT1'),
mypointsize=NULL,
ANNOTATION_FIELDS=c('annotation_sample_str','annotation_patient_str','annotation_paper_str','annotation_region_str','ident','Seurat_Clusters_plus1'),
add_custom_fields=NULL,
base_dir,
subdir='Rplots/') {
mymarkers_ext = mySeurat_genenames(mySeuratObject, mymarkers)
print(paste0('Markers not found: ', paste0(mymarkers[is.na(mymarkers_ext)], collapse = ', ')))
clusterplus1mapping = 1:length(levels(Idents(mySeuratObject)))
names(clusterplus1mapping) = as.character(levels(Idents(mySeuratObject)))
mySeuratObject[['Seurat_Clusters_plus1']] = plyr::revalue(Idents(mySeuratObject), clusterplus1mapping)
# Show umap with annotations
for (current_annotation in c(ANNOTATION_FIELDS, add_custom_fields)) {
# create labeled and unlabeled version
p=DimPlot(mySeuratObject, group.by = current_annotation, cols = rep(col_vector_60,4), label = T, repel = T, label.size = 7/.pt, pt.size = mypointsize)+
theme_void()+ggtitle(element_blank())+theme(legend.position = 'none')
# p
p_nl=DimPlot(mySeuratObject, group.by = current_annotation, cols = rep(col_vector_60,4))
# remove legend if it's too large (prevents errors)
if(!(current_annotation=='ident')) {if (dim(unique(mySeuratObject[[current_annotation]]))[1]>30) {
p=p+theme(legend.position = 'none') # now redundant
p_nl=p_nl+theme(legend.position = 'none')
}}
# test
ggsave(plot = p, filename = paste0(base_dir,subdir,run_name,'_2_umapLabeled_by_',current_annotation,'_style3.pdf'), height=172/3-4, width=172/3-4, units='mm')
# Save files
ggsave(plot = p, filename = paste0(base_dir,subdir,run_name,'_2_umapLabeled_by_',current_annotation,'.pdf'), height=5.5, width=5.5, units='cm')
ggsave(plot = p_nl, filename = paste0(base_dir,subdir,run_name,'_2_umap_by_',current_annotation,'.pdf'), height=7, width=7, units='cm')
# More customized/stylized version, specific size
if(!(current_annotation=='ident')) {current_annotation='Seurat_Clusters_plus1'}
p=DimPlot(mySeuratObject, group.by = current_annotation, cols = rep(col_vector_60,4), label = T, repel = T, label.size = 6/.pt, pt.size = 1, label.box=T)+
theme_void()+ggtitle(element_blank())+theme(legend.position = 'none')
# p
ggsave(plot = p, filename = paste0(base_dir,subdir,run_name,'_2_umapLabeled_by_',current_annotation,'_morecustomized.pdf'), height=172/3-4, width=172/3-4, units='mm', device = cairo_pdf)
}
for (marker in mymarkers_ext[!is.na(mymarkers_ext)]) {
# marker = 'KCNQ1OT1'
# marker = 'ACTC1'
# marker = 'ENSG00000120937:NPPB'
# marker projection on umaps
p_cm = FeaturePlot(mySeuratObject, features = marker, cols = rainbow_colors)+theme_void()+ggtitle(element_blank())+theme(legend.position = 'none')
ggsave(filename = paste0(base_dir,subdir,run_name,'_2_umap_markers_',marker,'.png'), plot = p_cm, height=5, width=5)
# Violins
pViol_m = VlnPlot(object = mySeuratObject, features = marker, group.by = 'annotation_paper_str') #, group.by = 'from_paper')
ggsave(filename = paste0(base_dir,subdir,run_name,'_4_Violin_markers_',marker,'.png'), plot = pViol_m, height=7.5, width=7.5)
# Also create histograms
pHist=ggplot(data.frame(expression=mySeuratObject@assays[[mySeuratObject@active.assay]]@data[marker,],
source=mySeuratObject$annotation_paper_fct))+
geom_histogram(aes(x=expression, fill=source, after_stat(density)))+
facet_grid(rows='source')+theme_bw()+theme(legend.position = 'none', )+ggtitle(marker)+give_better_textsize_plot(10)
ggsave(filename = paste0(base_dir,subdir,run_name,'_4_histogram_markers_',marker,'.png'), plot = pHist, height=10, width=7.5, units='cm')
# More complicated histogram, split, x-lims @98% of data, such that shape of curve is visible in case of outliers
currentlims=list()
for (source in unique(mySeuratObject$annotation_paper_fct)) {
currentlims[[source]]=calc_limits(mySeuratObject@assays[[mySeuratObject@active.assay]]@data[marker,mySeuratObject$annotation_paper_fct==source], percentile = .02)
}
# then calculate breaks
max_val = max(sapply(currentlims, function(x) {x[2]}))
currentbreaks = seq(from=-(max_val/29)/2,by=(max_val/29),to=max_val+(max_val/29)/2)
# And make histogram, use density as y-value
pHist=ggplot(data.frame(expression=mySeuratObject@assays[[mySeuratObject@active.assay]]@data[marker,],
source=mySeuratObject$annotation_paper_fct),
)+
geom_histogram(aes(x=expression, y=..density.., fill=source), breaks=currentbreaks)+
give_better_textsize_plot(10)+
facet_grid(rows='source')+theme_bw()+theme(legend.position = 'none')+ggtitle(marker)
ggsave(filename = paste0(base_dir,subdir,run_name,'_4_histogram98Lim_markers_',marker,'.png'), plot = pHist, height=10, width=7.5, units='cm')
}
# Add one plot that has legend
p_cm = p_cm+theme(legend.position = 'bottom')
ggsave(filename = paste0(base_dir,subdir,run_name,'_2_umap_markers_',marker,'_LEGEND.png'), plot = p_cm, height=5, width=5)
# Custom plot that shows distribution of patients over clusters
# mymaxy=1.5*max(table(Idents(mySeuratObject)))
p=ggplot(data.frame( cluster = Idents(mySeuratObject)+1,
Donor = mySeuratObject$annotation_patient_fct))+
geom_bar(aes(x=cluster, fill=Donor))+theme_bw()+
xlab('Cluster')+ylab('Number of cells')+
give_better_textsize_plot(8)+
theme(legend.position = 'right', legend.key.size = unit(3, "mm"))
#theme(legend.position=c(.99,.99), legend.justification = c(1,1), legend.key.size = unit(3, "mm"))
# ylim(c(0,mymaxy)); p
# p
ggsave(filename = paste0(base_dir,subdir,run_name,'_5_Barplot_PatientCluster_distr.pdf'),
plot = p, height=172/3-4, width=172/3-4, units='mm', device = cairo_pdf)
# Custom plot that shows distribution of patients over clusters
# mymaxy=1.5*max(table(Idents(mySeuratObject)))
Donor2=gsub(pattern = '^R\\.|^H\\.|^T\\.', replacement = '', mySeuratObject$annotation_patient_str)
mySeuratObject$annotation_patient_fct_NS = factor(Donor2, sort(unique(Donor2)))
p=ggplot(data.frame( cluster = mySeuratObject$Seurat_Clusters_plus1,
Donor = mySeuratObject$annotation_patient_fct_NS))+
geom_bar(aes(x=cluster, fill=Donor))+theme_bw()+
xlab('Cluster')+ylab('Number of cells')+
give_better_textsize_plot(8)+
theme(legend.position = 'right', legend.key.size = unit(3, "mm"))
#theme(legend.position=c(.99,.99), legend.justification = c(1,1), legend.key.size = unit(3, "mm"))
# ylim(c(0,mymaxy)); p
# p
ggsave(filename = paste0(base_dir,subdir,run_name,'_5_Barplot_PatientCluster_distr_DonorNoSet.pdf'),
plot = p, height=172/3-4, width=172/3-4, units='mm', device = cairo_pdf)
}
diff_express_clusters = function(mySeuratObject, mc.cores=8, custom_ident=NULL) {
# set custom clustering gruop if desired
if (!is.null(custom_ident)) {
Idents(mySeuratObject) <- custom_ident
}
all_markers =
mclapply(X = levels(Idents(mySeuratObject)),
FUN = function(cluster_index) {
print(paste0('Initiating analysis of cl ',cluster_index))
# find all markers of cluster X
current_markers <- FindMarkers(mySeuratObject, ident.1 = cluster_index, min.pct = .05)
# done
print(paste0("Cluster ",cluster_index," DE done"))
return(current_markers)
},
mc.cores = mc.cores)
names(all_markers) = levels(Idents(mySeuratObject))
return(all_markers)
}
# note things are saved like
# load('/Users/m.wehrens/Data/_2019_02_HCM_SCS/2021_HPC_analysis.3/Rdata/DE_cluster_ROOIJonly_RID2l.Rdata')
# all_markers=DE_cluster[[ANALYSIS_NAME]]
diff_express_clusters_save_results = function(all_markers, run_name, base_dir, topX=10, easy_names=T, save=T, pval_cutoff=0.05, extendedOutput=F, FC_cutoff=1.2) {
# ****
# Now collect the top-10 (log2fold) genes for each
topHitsPerCluster=
data.frame(lapply(all_markers, function(x) {
x_sel = x[x$p_val_adj<pval_cutoff&x$avg_log2FC>0,]
c( rownames(x_sel[order(x_sel$avg_log2FC, decreasing = T),][1:min(length(x_sel$avg_log2FC), topX),]),
rep(NA, topX-min(length(x_sel$avg_log2FC), topX)))
} ))
colnames(topHitsPerCluster)=names(all_markers)
if (easy_names) {topHitsPerCluster=shorthand_cutname_table(topHitsPerCluster)}
# and save
if (save) {openxlsx::write.xlsx(x = as.data.frame(topHitsPerCluster), file = paste0(base_dir,'Rplots/ClusterTopHits_',run_name,'.xlsx'), overwrite=T)}
# ****
if (extendedOutput) {
# SAME table as above BUT INCLUDING FC
# Also return an overview that includes FC
# Now collect the top-10 (log2fold) genes for each
topHitsPerCluster_FC=
Reduce(cbind, lapply(all_markers, function(x) {
x_sel = x[x$p_val_adj<pval_cutoff&x$avg_log2FC>0,]
data.frame(
GENE=c( shorthand_cutname ( rownames(x_sel[order(x_sel$avg_log2FC, decreasing = T),][1:min(length(x_sel$avg_log2FC), topX),]) ),
rep(NA, topX-min(length(x_sel$avg_log2FC), topX))),
FC=c( sprintf("%.2f", round(2^(x_sel[order(x_sel$avg_log2FC, decreasing = T),][1:min(length(x_sel$avg_log2FC), topX),]$avg_log2FC),2) ) ,
rep(NA, topX-min(length(x_sel$avg_log2FC), topX)))
)
} ))
colnames(topHitsPerCluster_FC)=rep(names(all_markers), each=2)
# and save
if (save) {openxlsx::write.xlsx(x = as.data.frame(topHitsPerCluster_FC), file = paste0(base_dir,'Rplots/ClusterTopHits_',run_name,'_plusFC.xlsx'), overwrite=T)}
# SAME table as above BUT INCLUDING FC, AND MOST NEGATIVE GENES
# Also return an overview that includes FC
# Now collect the top-10 (log2fold) genes for each
topHitsPerCluster_FC_neg=
Reduce(cbind, lapply(all_markers, function(x) {
x_sel = x[x$p_val_adj<pval_cutoff&x$avg_log2FC<0,] # !!
data.frame(
GENE=c( shorthand_cutname ( rownames(x_sel[order(x_sel$avg_log2FC, decreasing = F),][1:min(length(x_sel$avg_log2FC), topX),]) ),
rep(NA, topX-min(length(x_sel$avg_log2FC), topX))),
FC=c( sprintf("%.2f", round(2^(x_sel[order(x_sel$avg_log2FC, decreasing = F),][1:min(length(x_sel$avg_log2FC), topX),]$avg_log2FC),2) ) ,
rep(NA, topX-min(length(x_sel$avg_log2FC), topX)))
)
} ))
colnames(topHitsPerCluster_FC_neg)=rep(names(all_markers), each=2)
# and save
if (save) {openxlsx::write.xlsx(x = as.data.frame(topHitsPerCluster_FC_neg), file = paste0(base_dir,'Rplots/ClusterTopHits_',run_name,'_plusFC_DOWNgenes.xlsx'), overwrite=T)}
# ****
# Enriched genes list based on FC_cutoff and pval_cutoff
enriched_genes_lists=list(); enriched_genes_lists_down=list()
for (subset_name in names(all_markers)) {
marker_df = all_markers[[subset_name]]
# Determine selection for genes up and down resp.
x_sel = marker_df[marker_df$p_val_adj<pval_cutoff & 2^(marker_df$avg_log2FC)>FC_cutoff,]
x_sel_down = marker_df[marker_df$p_val_adj<pval_cutoff & 2^(marker_df$avg_log2FC)<(1/FC_cutoff),]
current_genes = rownames(x_sel[order(x_sel$avg_log2FC, decreasing = T),])
current_genes_down = rownames(x_sel_down[order(x_sel_down$avg_log2FC, decreasing = F),])
print(paste0('Genes for cl.',subset_name,': ',length(current_genes)))
print(paste0('Genes down for cl.',subset_name,': ',length(current_genes_down)))
write.table(x=data.frame(gene=shorthand_cutname(current_genes)), file=paste0(base_dir,'GeneLists/ClusterHits_',run_name,'_table_cl',subset_name,'.txt'),
quote = F, row.names = F, col.names = F)
write.table(x=data.frame(gene=shorthand_cutname(current_genes_down)), file=paste0(base_dir,'GeneLists/ClusterHitsDown_',run_name,'_table_cl',subset_name,'.txt'),
quote = F, row.names = F, col.names = F)
enriched_genes_lists[[subset_name]] = current_genes
enriched_genes_lists_down[[subset_name]] = current_genes_down
}
# Now also produce lists of genes of interest
}
# Also save the whole thing to Excel
all_markers = lapply(all_markers, function(df) {df$gene = rownames(df); df$gene_short = shorthand_cutname(df$gene); df = df[order(df$avg_log2FC,decreasing = T),]; return(df)})
if (save) {openxlsx::write.xlsx(x = all_markers, file = paste0(base_dir,'Rplots/Cluster_DE_full_',run_name,'.xlsx'), overwrite=T)}
if (extendedOutput) {
return(list(topHitsPerCluster=topHitsPerCluster, enriched_genes_lists=enriched_genes_lists, enriched_genes_lists_down=enriched_genes_lists_down))
} else {
return(topHitsPerCluster)
}
}
# This function produces a Batch-corrected Seurat object according to our
# settings.
#
# (Note to self: See also dev folder, this was tested preliminary under the name "C1b";
# C1b, now including all genes, but correcting only for the patients.)
#
# This follows the tutorial, section "Performing integration on datasets normalized with SCTransform"
# https://satijalab.org/seurat/articles/integration_introduction.html
# Introduction to scRNA-seq integration
# Compiled: June 14, 2021
# Source: vignettes/integration_introduction.Rmd
#
Seurat_batch_correction_1c = function(set_name, base_dir, MinCellsRequired=50) {
# Load uncorrected pre-processed analysis object
current_analysis=list()
current_analysis[[set_name]] = LoadH5Seurat(file = paste0(base_dir,'Rdata/H5_RHL_SeuratObject_nM_sel_',set_name,'.h5seurat'))
# Split object and apply SCT transformation
currentSeuratObject_list3 <- SplitObject(current_analysis[[set_name]], split.by = "annotation_patient_str")
# Count number of cells in each, and select only ones with enough cells
nrCellsPerPatient = sapply(currentSeuratObject_list3, ncol)
currentSeuratObject_list3 = currentSeuratObject_list3[nrCellsPerPatient>MinCellsRequired]
if (sum(!(nrCellsPerPatient>MinCellsRequired)) > 0) {
warning(paste0('Throwing out the following patients, because too few cells: ',
paste0(names(currentSeuratObject_list3)[!(nrCellsPerPatient>MinCellsRequired)], collapse = '; ')))
}
# SCTransform
currentSeuratObject_list3 <- lapply(X = currentSeuratObject_list3, FUN = SCTransform); beepr::beep()
all_genenames = Reduce(intersect, lapply(currentSeuratObject_list3, rownames))
#currentFeatures3 <- SelectIntegrationFeatures(object.list = currentSeuratObject_list3, nfeatures = 3000)
currentFeatures3 <- all_genenames
currentSeuratObject_list3 <- PrepSCTIntegration(object.list = currentSeuratObject_list3, anchor.features = currentFeatures3); beepr::beep()
currentAnchors3 <- FindIntegrationAnchors(object.list = currentSeuratObject_list3,
normalization.method = 'SCT', anchor.features = currentFeatures3, dims=1:30); beepr::beep()
# dims=1:10, k.anchor = ..
# Instead of
#currentSeuratObject_recombined3 <- IntegrateData(anchorset = currentAnchors3, normalization.method = 'SCT'); beepr::beep()
#currentSeuratObject_recombined3 <- IntegrateData(anchorset = currentAnchors3, normalization.method = 'SCT', k.weight=10); beepr::beep()
# Automate these two options by trying first one first:
currentSeuratObject_recombined3 = tryCatch({
IntegrateData(anchorset = currentAnchors3, normalization.method = 'SCT')
}, error = function(e) {
print('Setting k.weight=10 because default k.weight failed.')
IntegrateData(anchorset = currentAnchors3, normalization.method = 'SCT', k.weight=10)
}) ; beepr::beep()
############################################################
# Run analysis again
currentSeuratObject_recombined3 = mySeuratAnalysis_verybasic_part2only(mySeuratObject = currentSeuratObject_recombined3)
############################################################
print(paste0('Saving object to: ', base_dir,'Rdata/H5_RHL_SeuratObject_nM_sel_',paste0(set_name, '_Int1c'),'.h5seurat'))
SaveH5Seurat(object = currentSeuratObject_recombined3,
filename = paste0(base_dir,'Rdata/H5_RHL_SeuratObject_nM_sel_',paste0(set_name, '_Int1c'),'.h5seurat'))
return(currentSeuratObject_recombined3)
}
################################################################################
|
7a182d7cb1f5e1c020129d3ae203835ecf2ec3c4
|
6bb0b671b86d0bd13d73aefd4ebf86ee025c1ca1
|
/inst/test_lmer.R
|
342da36424ed64c74ac3d31abd616fe30bf9d9a3
|
[
"MIT"
] |
permissive
|
WillemSleegers/tidystats
|
571f06defe8cb307fb34599fb973c67ee45dd5c2
|
0eec202d6acde83a3ee72a3c17c53d9b2e8e5cdc
|
refs/heads/master
| 2023-07-06T17:47:38.235789
| 2023-05-02T08:39:13
| 2023-05-02T08:39:13
| 191,048,439
| 17
| 4
|
NOASSERTION
| 2023-04-29T20:10:12
| 2019-06-09T19:44:14
|
R
|
UTF-8
|
R
| false
| false
| 2,388
|
r
|
test_lmer.R
|
# Setup -------------------------------------------------------------------
# Load packages
library(tidystats)
library(tidyverse)
# lme4’s lmer() -----------------------------------------------------------
results <- list()
# Load the package
library(lme4)
# Run multilevel models
lme4 <- lme4::lmer(Reaction ~ Days + (1 | Subject), sleepstudy)
lme4_ML <- lme4::lmer(Reaction ~ Days + (1 | Subject), sleepstudy,
REML = FALSE, verbose = 1)
lme4_slopes <- lme4::lmer(Reaction ~ Days + (Days || Subject), sleepstudy)
summary(lme4)
summary(lme4_ML)
summary(lme4_slopes)
# Tidy results
temp <- tidy_stats(lme4)
temp <- tidy_stats(lme4_ML)
temp <- tidy_stats(lme4_slopes)
# Add stats
results <- results %>%
add_stats(lme4) %>%
add_stats(lme4_ML) %>%
add_stats(lme4_slopes)
# anova.merMod ------------------------------------------------------------
# Run model
lmer_anova <- anova(lme4, lme4_slopes)
lmer_anova
# Tidy stats
temp <- tidy_stats(lmer_anova)
# Add stats
results <- results %>%
add_stats(lmer_anova)
# Save stats
write_stats(results, "inst/test_data/lmer.json")
# lmerTest’s lmer() -------------------------------------------------------
results <- list()
# Load packages
library(lme4)
library(lmerTest)
# Run multilevel models
lmerTest1 <- lmerTest::lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
lmerTest2 <- lmerTest::lmer(Informed.liking ~ Gender + Information *
Product + (1 | Consumer) + (1 | Consumer:Product), data = lmerTest::ham)
summary(lmerTest1)
summary(lmerTest2)
# Tidy results
temp <- tidy_stats(lmerTest1)
temp <- tidy_stats(lmerTest2)
# Add stats
results <- results %>%
add_stats(lmerTest1) %>%
add_stats(lmerTest2)
# anova.lmerModLmerTest ---------------------------------------------------
m0 <- lmerTest::lmer(Reaction ~ Days + (1 | Subject), sleepstudy)
m <- lmerTest::lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
anova_lmerTest <- anova(m)
anova_lmerTest_lme4 <- anova(m, ddf = "lme4")
anova_lmerTest_fit <- anova(m0, m)
anova_lmerTest
anova_lmerTest_lme4
anova_lmerTest_fit
# Tidy stats
temp <- tidy_stats(anova_lmerTest)
temp <- tidy_stats(anova_lmerTest_lme4)
temp <- tidy_stats(anova_lmerTest_fit)
# Add stats
results <- results %>%
add_stats(anova_lmerTest) %>%
add_stats(anova_lmerTest_lme4) %>%
add_stats(anova_lmerTest_fit)
write_stats(results, "inst/test_data/lmerTest.json")
|
7b95c15a268afe1a60f4ea4295b72cc9bb5d7c20
|
6b3783653f32e076a8c299845c948dc833a6ece9
|
/man/density.lpp.Rd
|
967a87ba941ce61e4dc839301a278d622ed12da6
|
[] |
no_license
|
nemochina2008/spatstat
|
774fbfd02bebb866b8c557c0bd3e35cc3c56e642
|
54dac256a6a4da1b6f3476fe75a5ed290c572487
|
refs/heads/master
| 2020-12-05T03:19:34.333911
| 2020-01-05T08:50:01
| 2020-01-05T08:50:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,330
|
rd
|
density.lpp.Rd
|
\name{density.lpp}
\alias{density.lpp}
\alias{density.splitppx}
\title{
Kernel Estimate of Intensity on a Linear Network
}
\description{
Estimates the intensity of a point process on a linear network
by applying kernel smoothing to the point pattern data.
}
\usage{
\method{density}{lpp}(x, sigma=NULL, \dots,
weights=NULL,
distance=c("path", "euclidean"),
kernel="gaussian",
continuous=TRUE,
epsilon = 1e-06, verbose = TRUE,
debug = FALSE, savehistory = TRUE,
old=FALSE)
\method{density}{splitppx}(x, sigma=NULL, \dots)
}
\arguments{
\item{x}{
Point pattern on a linear network (object of class \code{"lpp"})
to be smoothed.
}
\item{sigma}{
Smoothing bandwidth (standard deviation of the kernel)
in the same units as the spatial coordinates of \code{x}.
}
\item{\dots}{
Arguments passed to \code{\link{as.mask}} determining the
resolution of the result.
}
\item{weights}{
Optional. Numeric vector of weights associated with the
points of \code{x}. Weights may be positive, negative or zero.
}
\item{distance}{
Character string (partially matched) specifying whether to use
a kernel based on paths in the network (\code{distance="path"}, the default)
or a two-dimensional kernel (\code{distance="euclidean"}).
}
\item{kernel}{
Character string specifying the smoothing kernel.
See \code{\link{dkernel}} for possible options.
}
\item{continuous}{
Logical value indicating whether to compute the
\dQuote{equal-split continuous} smoother (\code{continuous=TRUE}, the
default) or the \dQuote{equal-split discontinuous} smoother
(\code{continuous=FALSE}). Applies only when \code{distance="path"}.
}
\item{epsilon}{
Tolerance value. A tail of the kernel with total mass
less than \code{epsilon} may be deleted.
}
\item{verbose}{
Logical value indicating whether to print progress reports.
}
\item{debug}{
Logical value indicating whether to print debugging information.
}
\item{savehistory}{
Logical value indicating whether to save the entire history of the
algorithm, for the purposes of evaluating performance.
}
\item{old}{
Logical value indicating whether to use the old, very slow algorithm
for the equal-split continuous estimator.
}
}
\details{
Kernel smoothing is applied to the points of \code{x}
using either a kernel based on path distances in the network,
or a two-dimensional kernel.
The result is a pixel image on the linear network (class
\code{"linim"}) which can be plotted.
\itemize{
\item If \code{distance="path"} (the default)
then the smoothing is performed
using a kernel based on path distances in the network, as described in
described in Okabe and Sugihara (2012) and McSwiggan et al (2016).
\itemize{
\item
If \code{continuous=TRUE} (the default), smoothing is performed
using the \dQuote{equal-split continuous} rule described in
Section 9.2.3 of Okabe and Sugihara (2012).
The resulting function is continuous on the linear network.
\item
If \code{continuous=FALSE}, smoothing is performed
using the \dQuote{equal-split discontinuous} rule described in
Section 9.2.2 of Okabe and Sugihara (2012). The
resulting function is not continuous.
\item
In the default case
(where \code{distance="path"} and
\code{continuous=TRUE} and \code{kernel="gaussian"}
and \code{old=FALSE}),
computation is performed rapidly by solving the classical heat equation
on the network, as described in McSwiggan et al (2016).
Computational time is short, but increases quadratically
with \code{sigma}.
The arguments \code{epsilon,debug,verbose,savehistory} are ignored.
\item
In all other cases, computation is performed by path-tracing
as described in Okabe and Sugihara (2012);
computation can be extremely slow, and time
increases exponentially with \code{sigma}.
}
\item If \code{distance="euclidean"}, the smoothing is performed
using a two-dimensional kernel. The arguments are passed to
\code{\link{densityQuick.lpp}} to perform the computation.
See the help for \code{\link{densityQuick.lpp}} for further details.
}
There is also a method for split point patterns on a linear network
(class \code{"splitppx"}) which will return a list of pixel images.
}
\value{
A pixel image on the linear network (object of class \code{"linim"}).
}
\references{
McSwiggan, G., Baddeley, A. and Nair, G. (2016)
Kernel density estimation on a linear network.
\emph{Scandinavian Journal of Statistics} \bold{44}, 324--345.
Okabe, A. and Sugihara, K. (2012)
\emph{Spatial analysis along networks}.
Wiley.
}
\author{
\adrian and Greg McSwiggan.
}
\seealso{
\code{\link{lpp}},
\code{\link{linim}},
\code{\link{densityQuick.lpp}}
}
\examples{
X <- runiflpp(3, simplenet)
D <- density(X, 0.2, verbose=FALSE)
plot(D, style="w", main="", adjust=2)
Dw <- density(X, 0.2, weights=c(1,2,-1), verbose=FALSE)
De <- density(X, 0.2, kernel="epanechnikov", verbose=FALSE)
Ded <- density(X, 0.2, kernel="epanechnikov", continuous=FALSE, verbose=FALSE)
}
\keyword{spatial}
\keyword{methods}
\keyword{smooth}
|
e29d348f227b863fe83335b2efa008f90b1fd615
|
3888397595a89ef486bd4b68fdbe7d7c713ac6f4
|
/munging/01_03_time-in-min-since-3am.R
|
0f0f7424776de88b086a0832cc4ebad6cb1824cc
|
[] |
no_license
|
e-mcbride/sequence-fragmentation-project
|
add43e6de089276cf516ec31d5629c020335cde8
|
c0c312e9d56c3e8d683683e1bfa99b7c11a5c913
|
refs/heads/master
| 2021-11-24T10:00:47.926114
| 2021-10-29T00:46:25
| 2021-10-29T00:46:25
| 167,236,471
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,289
|
r
|
01_03_time-in-min-since-3am.R
|
# 01_03_time-in-min-since-3am.R
library(tidyverse); library(here)
##' Crunch arrival/departure times to calculate stay duration
###' Since the survey asked for diaries from 3AM to 2:59AM the next day, it'll be helpful to recalculate times so that they are measured in minutes since 3AM.
###' Some functions to help with that:
get_time_srbi_Acts <- function(time_col) as.numeric(time_col) / 60
get_time_nust_Acts <- function(time_col) {
times = lubridate::fast_strptime(time_col, '%H:%M')
60*lubridate::hour(times) + lubridate::minute(times)
}
# converts a time in minutes since midnight to time in minutes since 3AM
convert_time_3A <- function(ext_time_col) {
t3 = ext_time_col - 180
if_else(t3 < 0, t3 + 24*60, t3)
}
# converts all NA values into FALSE in a column of logicals/booleans
nas_to_false <- function(log_col) if_else(is.na(log_col),F,log_col)
###' Run these functions on the Activities and Places tables:
# chts_rel <- readr::read_rds(here("data", "chts-all-tables_selection.rds"))
locations_timevars <- chts_rel$PLACE %>%
mutate(arrival_time_3 = convert_time_3A(ARR_HR * 60 + ARR_MIN),
departure_time_3 = convert_time_3A(DEP_HR * 60 + DEP_MIN),
place_duration = departure_time_3 - arrival_time_3 + 1,
trip_duration = TRIPDUR) %>%
select(SAMPN,PERNO,PLANO, arrival_time_3, departure_time_3, place_duration)
locations_timevars %>% readr::write_rds(here("data", "locations-time-vars_places.rds"))
activities_with_time <- chts_rel$ACTIVITY %>%
left_join(locations_timevars, by=c('SAMPN','PERNO','PLANO')) %>%
mutate(act_start_time_3 = case_when(source == 'SRBI' ~ get_time_srbi_Acts(STIME),
source == 'NuStats' ~ get_time_nust_Acts(STIME),
TRUE ~ as.numeric(NA)) %>% convert_time_3A(),
act_end_time_3 = case_when(source == 'SRBI' ~ get_time_srbi_Acts(ETIME),
source == 'NuStats' ~ get_time_nust_Acts(ETIME),
TRUE ~ as.numeric(NA)) %>% convert_time_3A(),
act_duration = act_end_time_3 - act_start_time_3 + 1) %>%
select(-s_Generation, -STIME,-ETIME)
activities_with_time %>% readr::write_rds(here("data", "activities-time-vars.rds"))
|
da574629310ea3620f95a343626621bb4246ad2f
|
a08b33edefe480ac618b19c8a42008ecad8bc650
|
/Scripts/inst/executables/com_x_sci_data_14_scientific_commercial_simple.R
|
91d33248b9a01ffc9c0973e9d33a06245592ce5c
|
[] |
no_license
|
ChloeTellier/projet_M2_sole
|
3c8ab84be5c099f507345bdd0c5889ed366ce981
|
48f0536cc32e65ef72cd2b14e94d2566e950ae3c
|
refs/heads/main
| 2023-01-23T07:56:04.427937
| 2020-11-26T09:54:28
| 2020-11-26T09:54:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 388
|
r
|
com_x_sci_data_14_scientific_commercial_simple.R
|
library( TMB )
dyn.load( dynlib('Scripts/inst/executables/com_x_sci_data_14_scientific_commercial_simple') )
setwd('C:/R_projects/projet_M2_stats')
load( 'All_inputs.RData' )
Obj = MakeADFun(data=All_inputs[['data']], parameters=All_inputs[['parameters']], random=All_inputs[['random']], All_inputs[['Other_inputs']])
save( Obj, file='Obj.RData')
|
f3dbcd7d36e506bd7e1d4b8c414963cc4d4151dc
|
64098b83f218221064dacb4307f9b844e9a70373
|
/R/estip2.R
|
901cc51839cfd1905173505b1647a3790c920c22
|
[
"MIT"
] |
permissive
|
takuizum/irtfun2
|
07800c5e6abeb9eb1892724582be7b9ed2202387
|
def9eac15a1150804f3702cf3f84df1c638a1c38
|
refs/heads/master
| 2021-07-19T00:29:21.794826
| 2020-05-06T09:28:05
| 2020-05-06T09:28:05
| 151,583,271
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 20,209
|
r
|
estip2.R
|
# M step
# gradient
gr_jm <- function(r, N, X, t0, D){
if(length(t0)==2){
a <- t0[1]
b <- t0[2]
c <- 0
p <- ptheta(X, a, b, c, D)
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))
res <- c(ga,gb)
}
if(length(t0)==3){
a <- t0[1]
b <- t0[2]
c <- t0[3]
p <- ptheta(X, a, b, c, D)
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))
gc <- sum((r-N*p)/((1-c)*p))
res <- c(ga,gb,gc)
}
res
}
Elnk_jm <- function(r,N,t0,X,D){
if(length(t0)==2){
a <- t0[1]
b <- t0[2]
c <- 0
p <- ptheta(X, a, b, c, D)
A <- suppressWarnings(r*log(p)+(N-r)*log(1-p))
}
if(length(t0)==3){
a <- t0[1]
b <- t0[2]
c <- t0[3]
p <- ptheta(X, a, b, c, D)
A <- suppressWarnings(r*log(p)+(N-r)*log(1-p))
}
sum(A)
}
Elnk_jm_1pl <- function(r,N,t0,X,D,fix_a){
a <- fix_a
b <- t0
c <- 0
p <- ptheta(X, a, b, c, D)
A <- r*log(p)
B <- (N-r)*log(1-p)
sum(A+B)
}
# gradient for marginal Bayes
gr_jm_b <- function(r, N, X, t0, D, meanlog, sdlog, mean, sd, shape1, shape2){
if(length(t0)==2){
a <- t0[1]
b <- t0[2]
c <- 0
p <- ptheta(X, a, b, c, D)
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))-1/a-(log(a)-meanlog)/(a*sdlog^2)
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))-(b-mean)/sd^2
res <- c(ga,gb)
}
if(length(t0)==3){
a <- t0[1]
b <- t0[2]
c <- t0[3]
p <- ptheta(X, a, b, c, D)
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))-1/a-(log(a)-meanlog)/(a*sdlog^2)
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))-(b-mean)/sd^2
gc <- sum((r-N*p)/((1-c)*p))+(shape1-2)/c-(shape2-2)/(1-c)
res <- c(ga,gb,gc)
}
res
}
Elnk_jm_b <- function(r,N,t0,X,D,meanlog,sdlog,mean,sd,shape1,shape2){
if(length(t0)==2){
a <- t0[1]
b <- t0[2]
c <- 0
p <- ptheta(X, a, b, c, D)
A <- suppressWarnings(r*log(p)+(N-r)*log(1-p))
res <- sum(A)+dnorm(b,mean,sd)+dlnorm(a,meanlog,sdlog)
}
if(length(t0)==3){
a <- t0[1]
b <- t0[2]
c <- t0[3]
p <- ptheta(X, a, b, c, D)
A <- suppressWarnings(r*log(p)+(N-r)*log(1-p))
res <- sum(A)+dnorm(b,mean,sd)+dlnorm(a,meanlog,sdlog)+dbeta(c,shape1,shape2)
}
res
}
Elnk_jm_1pl_b <- function(r,N,t0,X,D,fix_a,mean,sd){
a <- fix_a
b <- t0
c <- 0
p <- ptheta(X, a, b, c, D)
A <- r*log(p)
B <- (N-r)*log(1-p)
sum(A+B)+dnorm(b,mean,sd)
}
grjm_b <- function(r, N, X, a, b, c, D, model, meanlog, sdlog, mean, sd, shape1, shape2){
p <- ptheta(X, a, b, c, D)
if(model=="1PL"){
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))-(b-mean)/sd^2
res <- gb
}
if(model=="2PL"){
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))-1/a-(log(a)-meanlog)/(a*sdlog^2)
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))-(b-mean)/sd^2
res <- c(ga,gb)
}
if(model=="3PL"){
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))-1/a-(log(a)-meanlog)/(a*sdlog^2)
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))-(b-mean)/sd^2
gc <- sum((r-N*p)/((1-c)*p))+(shape1-2)/c-(shape2-2)/(1-c)
res <- c(ga,gb,gc)
}
res
}
# objective function for regularized marginal maximum likelihood estimation
Elnk_jm_r <- function(r,N,t0,X,D,penalty){
if(length(t0)==2){
a <- t0[1]
b <- t0[2]
c <- 0
p <- ptheta(X, a, b, c, D)
A <- suppressWarnings(r*log(p)+(N-r)*log(1-p))
res <- sum(A)-penalty
}
if(length(t0)==3){
a <- t0[1]
b <- t0[2]
c <- t0[3]
p <- ptheta(X, a, b, c, D)
A <- suppressWarnings(r*log(p)+(N-r)*log(1-p))
res <- sum(A)-penalty
}
res
}
#
en_penalty <- function(a, alpha=0.5, lambda=0.1){
penalty <- alpha*sum(abs(a))+(1-alpha)/2*sum(a^2)
penalty
}
# gradient for FS
grjm <- function(r, N, X, a, b, c, D, model){
p <- ptheta(X, a, b, c, D)
if(model=="1PL"){
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))
res <- gb
}
if(model=="2PL"){
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))
res <- c(ga,gb)
}
if(model=="3PL"){
ga <- sum(D*(X-b)*(r-N*p)*(p-c)/((1-c)*p))
gb <- sum(-D*a*(r-N*p)*(p-c)/((1-c)*p))
gc <- sum((r-N*p)/((1-c)*p))
res <- c(ga,gb,gc)
}
res
}
# Fisher information matrix
Ijm <- function(N, X, a, b, c, D, model){
p <- ptheta(X, a, b, c, D)
q <- 1-p
if(model=="1PL"){
jb <- sum(N*(p-c)^2*q*a^2*D^2/((1-c)^2*p))
res <- jb
}
if(model=="2PL"){
ja <- sum(N*(p-c)^2*q*(X-b)^2*D^2/((1-c)^2*p))
jb <- sum(N*(p-c)^2*q*a^2*D^2/((1-c)^2*p))
jab <- sum(-N*(p-c)^2*q*a*(X-b)*D^2/((1-c)^2*p))
res <- matrix(c(ja,jab,jab,jb),nrow = 2)
}
if(model=="3PL"){
ja <- sum(N*(p-c)^2*q*(X-b)^2*D^2/((1-c)^2*p))
jb <- sum(N*(p-c)^2*q*a^2*D^2/((1-c)^2*p))
jc <- sum(N*q/(p*(1-c)^2))
jab <- sum(-N*(p-c)^2*q*a*(X-b)*D^2/((1-c)^2*p))
jac <- sum(N*(p-c)*q*(X-b)*D/((1-c)^2*p))
jbc <- sum(-N*(p-c)*q*a*D/((1-c)^2*p))
res <- matrix(c(ja,jab,jac,
jab,jb,jbc,
jac,jbc,jc),nrow = 3)
}
res
}
#' Unidimensional Item Response Theory parameter estimation
#'
#' @param x DataFrame.
#' @param fc the first column.
#' @param IDc the ID column.
#' @param Gc the grade column.
#' @param bg a mumber of base grade.
#' @param D a scale constant.
#' @param Ntheta the number of the nodes of theta dist.
#' @param method the method of optimiser. Default is "Fisher_Scoring", but \code{\link[stats]{optim}} function also be able to use.
#' @param model a model vector
#' @param max_func a character of object function. "N" is MML-EM, "B" is marginal Bayes and "R" is Regularized MML.
#' @param mu_th a hyper parameter of normal dist for theta
#' @param sigma_th a hyper parameter of normal dist for theta
#' @param min_th a minimum value of theta distribution
#' @param max_th a maximum value of theta distribution
#' @param eEM a convergence criterion related to item parameters in EM cycle.
#' @param eMLL a convergence criterion related to negative twice log likelihood in EM cycle.
#' @param maxiter_em the number of iteration of EM cycle.
#' @param rm_list a vector of item U want to remove for estimation. NOT list.
#' @param fix_a a fix parameter for slope parameter of 1PLM
#' @param mu_a a hyper parameter for slope parameter prior distribution(lognormal) in marginal Bayes estimation.
#' @param sigma_a a hyper parameter for slope parameter prior distribution(lognormal) in marginal Bayes estimation.
#' @param mu_b a hyper parameter for location parameter prior distribution(normal) in marginal Bayes estimation.
#' @param sigma_b a hyper parameter for location parameter prior distribution(normal) in marginal Bayes estimation.
#' @param mu_c a hyper parameter for lower asymptote parameter prior distribution(beta) in marginal Bayes estimation.
#' @param sigma_c a hyper parameter for lower asymptote parameter prior distribution(beta) in marginal Bayes estimation.
#' @param w_c a weight parameter for lower asymptote parameter prior distribution(beta) in marginal Bayes estimation.
#' @param alpha tuning parameter of elastic net penalty.
#' @param lambda tuning parameter of elastic net penalty.
#' @param th_dist a type of theta dist."normal" or "empirical"
#' @param print How much information you want to display? from 1 to 3. The larger, more information is displayed.
#'
#' @return the output is a list that has item parameters data.frame and these Standard Error.
#' @examples
#' # MMLE
#' res1 <- estip2(x=sim_data_2, Gc=NULL, fc=2, Ntheta=21)
#' # check the parameters
#' res1$para
#' res1$SE
#'
#' # Multigroup MMLE
#' res2 <- estip2(x=sim_dat_st, Gc=2, bg=3, fc=3, Ntheta=10)
#'
#' # Marginal Bayes
#' res3 <- estip2(x=sim_data_2, Gc=NULL, fc=2, Ntheta=21, max_func="B")
#'
#' # Regularized MMLE
#' res4 <- estip2(x=sim_data_2, Gc=NULL, fc=2, Ntheta=21, max_func="R")
#' @export
#'
estip2 <- function(x, fc=3, IDc=1, Gc=NULL, bg=1, Ntheta=31, D=1.702, method="Fisher_Scoring", model="2PL", max_func="N", rm_list=NULL,
mu_th=0, sigma_th=1, min_th=-4, max_th=4, eEM=0.001, eMLL=0.001, maxiter_em=100, th_dist="normal",
fix_a=1, mu_a=0, sigma_a=1, mu_b=0, sigma_b=1, mu_c=0, sigma_c=1, w_c=1, alpha=0.5, lambda=1,
print=0){
if(!(method %in% c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN","Fisher_Scoring"))) stop("argument input of 'method' is improper string!!")
if(!(max_func %in% c("B","N","R"))) stop("argument input of 'max_func' is improper string!!")
if(max_func == "R"){
if(method == "Fisher_Scoring"){
cat("'Fisher scoring' cannot be selected as optimization method for Regularized MML !!\nChange 'BFGS'\n")
method <- "BFGS"
}
if(model == "1PL") stop("In 1PLM, Regularized MML cannot be conducted.")
}
if(th_dist %in% c("normal", "empirical"))
# data check
X <- as.matrix(x[,fc:ncol(x)])
Item <- colnames(X) %>% as.character()
nj <- ncol(X)
ni <- nrow(X)
nq <- Ntheta
if(is.null(IDc)) ID <- 1:ni
else ID <- x[,IDc]
if(is.null(Gc)) group <- rep(1,ni)
else group <- x[,Gc]
ng <- max(group)
if(!is.numeric(group)) stop("A group column must be numeric, but has non numeric scalar.")
if(min(group)==0) stop("A group column must be above 1, but has 0.")
if(length(model)!=nj) model <- rep(model, nj)
p_mean <- rep(mu_th, ng)
p_sd <- rep(sigma_th,ng)
# design matrix
ind <- matrix(nrow=ng, ncol=nj)
for(g in 1:ng){
ind[g,] <- X[group==g, ] %>% colSums(na.rm = T)
}
ind[ind!=0] <- 1
resp <- X %>% as.matrix()
resp[!is.na(resp)] <- 1
resp[is.na(resp)] <- 0
# weight and nodes
Xq <- seq(min_th, max_th, length.out = nq)
# initial weight
# AX <- matrix(nrow=nq, ncol=ng)
AX <- dnorm(Xq, mean=mu_th, sd=sigma_th)/sum(dnorm(Xq, mean=mu_th, sd=sigma_th))
AX <- AX %>% rep.int(times=ng) %>% matrix(ncol=ng)
# initial value
r <- as.vector(cor(rowSums(X, na.rm = T),X, use = "pair"))
pass <- colMeans(X, na.rm = T)
a0 <- D*r/sqrt(1-r^2)
b0 <- -log(pass/(1-pass))
c0 <- rep(0,nj)
for(j in 1:nj){
if(model[j]=="3PL")c0 <- 0.2
if(model[j]=="1PL")a0 <- fix_a
}
init <- t0 <- t1 <- data.frame(a=a0,b=b0,c=c0)
# remove selected item
if(!is.null(rm_list)){
rm_ind <- c(1:nj)[Item %in% rm_list]
model[rm_ind] <- "NONE"
resp[,rm_ind] <- 0
ind[,rm_ind] <- 0
init[rm_ind,] <- t0[rm_ind,] <- t1[rm_ind,] <- 0
a0 <- init$a
b0 <- init$b
c0 <- init$c
cat("Remove Item ", rm_list, "\n")
}
# cat
cat("The number of subject is " ,ni, ".\nThe number of item is ", nj-length(rm_list),
".\nThe number of remove item is ", length(rm_list), ".\n")
# for imputation
a1 <- b1 <- c1 <- numeric(nj)
# reshape beta dist hyper parameter
shape1 <- w_c*mu_c+1
shape2 <- w_c*(1-mu_c)+1
# set mll history vector
mll_history <- c(0)
cat("Estimating Item Parameter!\n")
# stand FLAG
t <- 0
convergence <- T
while(convergence){
t <- t + 1
#cat(t,"time EM cycle NOW\n")
# E step
Estep <- Estep_irt(xall=X, t0=as.matrix(t0), Xm=Xq, Wm=AX, group=group,
ind=ind, resp=resp, D=D, MLL=mll_history)
mll <- Estep$MLL[t+1]
if(print == 0) cat(t ,"times -2 Marginal Loglikelihood is",-2*mll,"\r")
if(print >= 1) cat(t ,"times -2 Marginal Loglikelihood is",-2*mll,"\n")
mll_history <- Estep$MLL
Njm <- matrix(0,nrow=nj, ncol=nq)
rjm <- matrix(0,nrow=nj, ncol=nq)
for(g in 1:ng){
# purrr::map(Estep$Njm,function(x){purrr::invoke(.f=rbind, .x=x)})
Njm <- Njm + purrr::invoke(rbind,Estep$Njm[[g]])
rjm <- rjm + purrr::invoke(rbind,Estep$rjm[[g]])
}
# M step
a0 <- t0$a
b0 <- t0$b
c0 <- t0$c
# penalty
penalty <- en_penalty(a0, alpha = alpha, lambda = lambda)
for(j in 1:nj){
convM <- TRUE
eM <- 0.001
while(convM){
if(model[j]=="NONE") next
#cat("Optimising item ",j,"\r")
# Let Nqr tidyr for FS
N <- Njm[j,]
rr <- rjm[j,]
# normal M step
if(max_func == "N"){
if(method != "Fisher_Scoring"){
#stop("This option dose not work now!!")
if(model[j]=="1PL"){
sol <- optimise(Elnk_jm_1pl, interval = c(min_th,max_th)+t0$b[j], maximum = T,
r=rr, N=N, X=Xq, D=D, fix_a=fix_a)
t1[j,2] <- sol$maximum
}
if(model[j]=="2PL"){
sol <- optim(par=c(t0$a[j],t0$b[j]), fn=Elnk_jm, gr=gr_jm, control = list(fnscale = -1),
r=rr, N=N, X=Xq, D=D, method = method)
t1[j,c(1,2)] <- sol$par
}
if(model[j]=="3PL"){
sol <- optim(par=c(t0$a[j],t0$b[j],t0$c[j]), fn=Elnk_jm, gr=gr_jm, control = list(fnscale = -1),
r=rr, N=N, X=Xq, D=D, method = method)
t1[j,c(1,2,3)] <- sol$par
}
}else{
# Fisher scoring
gr <- grjm(rr, N, Xq, t0$a[j], t0$b[j], t0$c[j], D=D, model=model[j])
FI <- Ijm(N, Xq, t0$a[j], t0$b[j], t0$c[j], D=D, model=model[j])
# solve
sol <- solve(FI)%*%gr
if(model[j]=="1PL") t1$b[j] <- t0$b[j]+sol
if(model[j]=="2PL") t1[j,c(1,2)] <- t0[j,c(1,2)]+sol
if(model[j]=="3PL") t1[j,] <- t0[j,]+sol
}
} else if (max_func=="B"){
if(method != "Fisher_Scoring"){
#stop("This option dose not work now!!")
if(model[j]=="1PL"){
sol <- optimise(Elnk_jm_1pl_b, interval = c(min_th,max_th)+t0$b[j], maximum = T,
r=rr, N=N, X=Xq, D=D, fix_a=fix_a, mean=mu_b, sd=sigma_b)
t1[j,2] <- sol$maximum
}
if(model[j]=="2PL"){
sol <- optim(par=c(t0$a[j],t0$b[j]), fn=Elnk_jm_b, gr=gr_jm_b, control = list(fnscale = -1),
r=rr, N=N, X=Xq, D=D, method = method,
meanlog=mu_a, sdlog=sigma_a, mean=mu_b, sd=sigma_b, shape1=shape1, shape2=shape2)
t1[j,c(1,2)] <- sol$par
}
if(model[j]=="3PL"){
sol <- optim(par=c(t0$a[j],t0$b[j],t0$c[j]), fn=Elnk_jm_b, gr=gr_jm_b, control = list(fnscale = -1),
r=rr, N=N, X=Xq, D=D, method = method,
meanlog=mu_a, sdlog=sigma_a, mean=mu_b, sd=sigma_b, shape1=shape1, shape2=shape2)
t1[j,c(1,2,3)] <- sol$par
}
}else{
# Fisher scoring
gr <- grjm_b(rr, N, Xq, t0$a[j], t0$b[j], t0$c[j], D=D, model=model[j],
meanlog=mu_a, sdlog=sigma_a, mean=mu_b, sd=sigma_b, shape1=shape1, shape2=shape2)
FI <- Ijm(N, Xq, t0$a[j], t0$b[j], t0$c[j], D=D, model=model[j])
# solve
sol <- solve(FI)%*%gr
if(model[j]=="1PL") t1$b[j] <- t0$b[j]+sol
if(model[j]=="2PL") t1[j,c(1,2)] <- t0[j,c(1,2)]+sol
if(model[j]=="3PL") t1[j,] <- t0[j,]+sol
}
}else if(max_func=="R"){
if(model[j]=="2PL"){
sol <- optim(par=c(t0$a[j],t0$b[j]), fn=Elnk_jm_r, control = list(fnscale = -1),
r=rr, N=N, X=Xq, D=D, method = method, penalty = penalty)
t1[j,c(1,2)] <- sol$par
}
if(model[j]=="3PL"){
sol <- optim(par=c(t0$a[j],t0$b[j],t0$c[j]), fn=Elnk_jm_r, control = list(fnscale = -1),
r=rr, N=N, X=Xq, D=D, method = method, penalty = penalty)
t1[j,c(1,2,3)] <- sol$par
}
}
# exception handling
if(t1$c[j] < 0){
warning(paste0("The model of item ",j," was changed to 2PLM"))
model[j] <- "2PL"
t1[j,1] <- init$a[j]
t1[j,2] <- init$b[j]
t1[j,3] <- 0
}
if(t1$a[j] < 0){
warning(paste0("In ",t," times iteration, Item ",j," was eliminated. 'a' must be positive, but was negative."))
model[j] <- "NONE"
t1[j,] <- t0[j,]
}
# conv check
# cat(max(abs(t1[j,]- t0[j,])), "\r")
if(all(abs(t1[j,]- t0[j,]) < eM))
convM <- FALSE
t0[j,] <- t1[j,]
}
} # end j
# calibration
# calculate mean and sd
Njm <- matrix(0,nrow=nj, ncol=nq)
p_mean_t0 <- p_mean
p_sd_t0 <- p_sd
for(g in 1:ng){
gind <- ind[g,]!=0
# purrr::map(Estep$Njm,function(x){purrr::invoke(.f=rbind, .x=x)})
Njm <- purrr::invoke(rbind, Estep$Njm[[g]])
#rjm <- rjm + purrr::invoke(rbind,Estep$rjm[[g]])
p_mean[g] <- mean(Njm[gind,]%*%matrix(Xq)/rowSums(Njm[gind,]))
p_sd[g] <- mean(sqrt(Njm[gind,]%*%matrix((Xq-p_mean[g])^2)/rowSums(Njm[gind,])))
}
# calculate calibration weight
A <- sigma_th/p_sd[bg]
K <- mu_th - A*p_mean[bg]
# calibrate mean and sd
p_mean <- A*p_mean+K
p_sd <- A*p_sd
for(g in 1:ng){
gind <- ind[g,]!=0
Njm <- purrr::invoke(rbind, Estep$Njm[[g]])
if(th_dist=="normal"){
# Gaussian dist
AX[,g] <- dnorm(Xq, mean=p_mean[g], sd=p_sd[g])/sum(dnorm(Xq, mean=p_mean[g], sd=p_sd[g]))
}
if(th_dist=="empirical"){
# empirical dist
constNjm <- rowSums(Njm[gind,]) %>% rep.int(times=nq) %>% matrix(ncol=nq)
AX[,g] <- (Njm[gind,]/constNjm) %>% colMeans(na.rm = T)
}
}
# calibrate item parameter
for(j in 1:nj){
if(model[j]=="NONE") next
if(model[j] != "1PL"){
a1[j] <- t1$a[j]/A
b1[j] <- t1$b[j]*A+K
c1[j] <- t1$c[j]
}else{
a1[j] <- fix_a
b1[j] <- t1$b[j]*A+K
c1[j] <- t1$c[j]
}
}
t1$a <- a1
t1$b <- b1
t1$c <- c1
# convergence check
conv1 <- c(abs(a0-a1),abs(b0-b1),abs(c0-c1))
conv4 <- abs(mll_history[t+1]-mll_history[t])
if(ng > 1){
conv2 <- c(abs(p_mean - p_mean_t0))
conv3 <- c(abs(p_sd - p_sd_t0))
}else{
conv2 <- conv3 <- 1
}
if(all(conv1<eEM) || conv4<eMLL || all(conv2<eEM) || all(conv3<eEM) || maxiter_em == t){
convergence <- F
cat("\nConverged!!\n")
item_para <- as.data.frame(t1)
break
}else{
if(print >= 1){
cat("Item maximum changed a is", Item[max(abs(a0-a1))==abs(a0-a1)],"=",max(abs(a0-a1)),"\n")
cat("Item maximum changed b is", Item[max(abs(b0-b1))==abs(b0-b1)],"=",max(abs(b0-b1)),"\n")
cat("Item maximum changed c is", Item[max(abs(c0-c1))==abs(c0-c1)],"=",max(abs(c0-c1)),"\n")
}
t0 <- t1
}
}
# LAST E step
# E step
Estep <- Estep_irt(xall=X, t0=as.matrix(t1), Xm=Xq, Wm=AX, group=group,
ind=ind, resp=resp, D=D, MLL=mll_history)
mll <- Estep$MLL[t+1]
mll_history <- Estep$MLL
Njm <- matrix(0,nrow=nj, ncol=nq)
rjm <- matrix(0,nrow=nj, ncol=nq)
for(g in 1:ng){
# purrr::map(Estep$Njm,function(x){purrr::invoke(.f=rbind, .x=x)})
Njm <- Njm + purrr::invoke(rbind,Estep$Njm[[g]])
rjm <- rjm + purrr::invoke(rbind,Estep$rjm[[g]])
}
# Standard Error
SE <- data.frame(a=rep(0,nj), b=rep(0,nj), c=rep(0,nj))
for(g in 1:ng){
# purrr::map(Estep$Njm,function(x){purrr::invoke(.f=rbind, .x=x)})
Njm <- Njm + purrr::invoke(rbind,Estep$Njm[[g]])
rjm <- rjm + purrr::invoke(rbind,Estep$rjm[[g]])
}
for(j in 1:nj){
#cat("Optimising item ",j,"\r")
if(model[j]=="NONE") next
# Let Nqr tidyr for FS
N <- Njm[j,]
rr <- rjm[j,]
# Fisher score matrix
FI <- Ijm(N, Xq, t1$a[j], t1$b[j], t1$c[j], D=D, model=model[j])
# solve
if(model[j]=="1PL") SE$b[j] <- sqrt(diag(solve(FI)))
if(model[j]=="2PL") SE[j,c(1,2)] <- sqrt(diag(solve(FI)))
if(model[j]=="3PL") SE[j,] <- sqrt(diag(solve(FI)))
}
# output result
# Item
t1 <- data.frame(Item = as.character(Item), t1, model = model)
# SE
SE <- data.frame(Item = as.character(Item), SE, model = model)
# th_dist
theta_dist <- data.frame(AX)
colnames(theta_dist) <- as.character(c(1:ng))
theta_dist$theta <- Xq
#th_para
theta_para <- rbind(p_mean,p_sd) %>% data.frame()
colnames(theta_para) <- as.character(c(1:ng))
res <- list(para=t1, SE=SE, th_dist=theta_dist, th_para=theta_para, mll_history=mll_history)
return(res)
}
|
b9d7c4f96b225ab6d9d332c4d7c8829c1ddc0641
|
a94c5dccdd6b25d40fde78abe2d6c95ad13f7cc2
|
/varios/R/win-library/3.5/Rmpfr/NEWS.Rd
|
9c6d522ef387629a1a06ec2c6426b1d05532bf3d
|
[] |
no_license
|
ngaitan55/Personal
|
5b3e500f9fd39d6e8e2430f1ce2c7cfca606f4bb
|
64a7ee7a4ebcecf7cc718211e7cfc51029a437e0
|
refs/heads/master
| 2022-12-17T04:50:09.088591
| 2020-09-19T02:23:50
| 2020-09-19T02:23:50
| 268,140,797
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,658
|
rd
|
NEWS.Rd
|
% Check from R:
% news(db = tools:::.build_news_db_from_package_NEWS_Rd("~/R/Pkgs/Rmpfr/inst/NEWS.Rd"))
\name{NEWS}
\title{Rmpfr News}
\encoding{UTF-8}
\section{Changes in version 0.7-2 [2019-01-14, r298]}{
\subsection{BUG FIXES}{
\itemize{
\item \code{str(<mpfr>)} no longer calls \code{formatMpfr(x, digits, *)}
with a \code{digits} \emph{vector} of the same length as \code{x}
(which never worked correctly).
\item \code{seqMpfr(1, length.out=8)} now works correctly.
}
}
\subsection{NEW FEATURES}{
\itemize{
\item \code{unirootR()} gets an option to \emph{not} warn on
non-convergence.
\item Provide a \code{summary()} method for \code{"mpfr"} numbers
closely modeled after \code{summary.default} for numeric.
\item \code{mpfr(NULL)} now works, returning \code{mpfr(logical())}.
\item a simple \code{sapplyMpfr()} function, showing how to work
around the fact that \code{sapply()} does typically not work with
\code{"mpfr"} numbers.
}
}
}
\section{Changes in version 0.7-1 [2018-07-24, r291]}{
\subsection{BUG FIXES}{
\itemize{
\item \code{formatMpfr()} for large low-precision numbers now uses
scientific representation, fixing the bug RMH was reporting March
17 already.
\item \code{outer()} is \dQuote{imported} from base, so it
behaves as an \pkg{Rmpfr} function which dispatches e.g., when
calling \code{\link{tcrossprod}()}.
}
}
}
\section{Changes in version 0.7-0 [2018-01-12, r284]}{
\subsection{NEW FEATURES}{
\itemize{
\item \code{.mpfr2list()} and \code{mpfrXport()} gain an option
\code{names} (for nicer output).
\item \code{formatMpfr()} and the \code{print()} method get a new
option \code{max.digits} with default \code{9999} for the print
methods, to limit the number of digits printed for high precision
numbers.
}
}
\subsection{BUG FIXES}{
\itemize{
\item For non-\dQuote{regular} mpfr numbers, the \code{d} slot in
the \code{"mpfr1"} representation is now empty instead of
\dQuote{random}. This also eliminates valgrind warnings about
uninitialized values in C.
}
}
}
\section{Changes in version 0.6-2 [2017-05-29, r264], never on CRAN}{
\subsection{NEW FEATURES}{
\itemize{
\item The S3 classes \code{"Hcharacter"} and \code{"Bcharacter"}
resulting from \code{formatHex()} and \code{formatBin()} now
\dQuote{inherit from} \code{"character"} formally.
\item They also got a \code{`[`} method, so subsetting should
work, including for \code{array}s of these.
\item The \code{"mpfr"} method of \code{str()} gains option
\code{internal}.
}
}
\subsection{BUG FIXES}{
\itemize{
\item when \code{print()}ing mpfr numbers, the result no longer sometimes
loses the last digit.
\item \code{dnorm()} now works correctly with mpfr numbers;
similarly \code{dbinom()} and \code{dpois()} should work in all
cases, now.
\item in \file{NAMESPACE}, also \code{exportMethods(apply)}, so
\pkg{SNscan} works.
\item \code{print(formatHex(..))}, \code{formatBin()} and
\code{formatDec()} now look better and are more correct; the first
two get a new option \code{expAlign} indicating to use the same
number of digits for exponents (in \dQuote{scientific} cases).
Notably, \code{mpfr(formatBin(mpx))} works for more \code{mpx}
objects (of class \code{"mpfr"}).
\item \code{format(mpfr(3,7), digits = 1, base = 2)} no longer
crashes (from inside MPFR).
\item \code{formatDec(mpfr(NA, 7))} now works.
\item For non-\dQuote{regular} mpfr numbers, the \code{d} slot in
the \code{"mpfr1"} representation is now empty instead of
\dQuote{random}. This also eliminates valgrind warnings about
uninitialized values in C.
}
}
}
\section{Changes in version 0.6-1 [2016-11-15, r249]}{
\subsection{NEW FEATURES}{
\itemize{
\item \code{head()} and \code{tail()} methods for \code{"mpfrMatrix"}.
}
}
\subsection{BUG FIXES}{
\itemize{
\item C-level \code{mpfr2str()} no longer calls S_realloc() with
wrong "old size" (thanks to Bill Dunlap).
\item \code{c()} now also works when its result is a length-0
\code{"mpfr"} object.
}
}
}
\section{Changes in version 0.6-0 [2015-12-04, r237]}{
\subsection{NEW FEATURES}{
\itemize{
\item \code{mpfr()} now is S3 generic with several methods, notably a
\code{"mpfr"} method allowing to change precision or rounding mode.
\item \code{mpfr()}, \code{formatMpfr()}, etc, now work with bases from 2
to 62 (using digits, upper and lower case ASCII letters, \code{62
== 10 + 2*26} characters), as this has been in MPFR since version
3.0.0 (see \code{\link{mpfrVersion}}), which is hence (implicitly)
required for \code{base} greater than 36.
\item \code{formatMpfr()} gets a new argument \code{base = 10} and can
be used to produce in other bases, notably binary (\code{base = 2})
or hexadecimal (\code{base = 16}).
\item \code{str(<mpfr>, ....)} is now based on \code{formatMpfr()}
and nicely shows numbers also out of the double precision range.
Further, it now chooses a smart default for optional argument
\code{vec.len}.
\item \code{matrix(mp, ..)} now also works when \code{mp} is of
class \code{"mpfr"}.
\item new matrix \code{norm()} for several \code{kind}s.
\item new functions \code{formatHex()} and \code{formatBin()}
thanks to Rich Heiberger.
\item \code{mpfr(x)} also works as \emph{inverse} of
\code{formatBin} and \code{formatHex}.
\item \code{roundMpfr()} and mathematical functions such as
\code{jn}, or \code{chooseMpfr()} get new optional argument
\code{rnd.mode} passed to the corresponding MPFR function.
\item \code{median(x)}, \code{mean(x, trim)} for \code{trim > 0}
now work fine for \code{"mpfr"} x, and \code{quantile(x, *)} no
longer needs \code{names=FALSE} to avoid a warning.
}
}
\subsection{BUG FIXES}{
\itemize{
\item \code{pnorm(.)}, \code{j0()} and similar special functions
now preserve \code{mpfrMatrix} and \code{mpfrArray} classes.
\item similarly, \code{is.finite()} etc keep the
\code{dim()}ensionality for \code{"mpfrArray"} arguments.
\item \code{mpfr("0xabc", base=16)} and \code{mpfr("0b101",
base=2)} and corresponding \code{getPrec()} now give the correct
precBits instead of too many.
\item \code{str(<0-length mpfr>)} now works correctly.
}
}
}
\section{Changes in version 0.5-7 [2014-11-27, r205]}{
\subsection{NEW FEATURES}{
\itemize{
\item .
}
}
\subsection{BUG FIXES}{
\itemize{
\item \code{as.integer()} now rounds \dQuote{to zero} as for
regular \R numbers (it accidentally did round \dQuote{to nearest}
previously).
}
}
}
\section{Changes in version 0.5-6 [2014-09-05, r203]}{
\subsection{NEW FEATURES}{
\itemize{
\item experimental \code{mpfrImport()}, \code{mpfrXport()}
utilities -- as we found cases, where save() \code{"mpfr"} objects
were \emph{not} portable between different platforms.
\item \code{as(*,"mpfr")} now also supports rounding mode
\code{"A"} (\dQuote{\bold{A}way from zero}).
\item Several hidden low level utilities also get a
\code{rnd.mode} option.
}
}
\subsection{BUG FIXES}{
\itemize{
\item .
}
}
}
\section{Changes in version 0.5-5 [2014-06-19, r190]}{
\subsection{NEW FEATURES}{
\itemize{
\item The result of \code{integrateR()} now prints even if a
warning happened.
\item \code{pbetaI(x, a,b)}, the arbitrarily accurate
\code{pbeta()} computation for \emph{integer} \eqn{a} and \eqn{b},
now works for larger \eqn{(a,b)}.
\item Newly providing \code{mpfr}-versions of \code{dbinom()},
\code{dpois()}, and \code{dnorm()}.
\item New utility functions \code{mpfr_default_prec()},
\code{.mpfr.minPrec()}, etc, to get, check, set default exponent
ranges and precision.
\item New \code{sinpi()}, \code{cospi()} etc, notably for \R >= 3.0.1.
}
}
%% \subsection{BUG FIXES}{
%% \itemize{
%% \item .
%% }
%% }
}
\section{Changes in version 0.5-4 [2013-10-22, r173]}{
\subsection{NEW FEATURES}{
\itemize{
\item .
}
}
\subsection{BUG FIXES}{
\itemize{
\item .
}
}
}
|
550bce953ccfdbab2dfb24726509782491a34a3d
|
18298c57b2ddbc4afedc82229199cbb0e5ac1124
|
/fort.R
|
2b38c095249b8506f77367e23fa89b0de121c411
|
[] |
no_license
|
korabum/hackathon-data
|
200dbecb03ded935b9b8b5859031474b685956c5
|
68ca9546213d999afd08d1baddf3cbf96c783abc
|
refs/heads/master
| 2021-03-27T16:25:45.347590
| 2017-04-29T03:05:39
| 2017-04-29T03:05:39
| 89,660,117
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,980
|
r
|
fort.R
|
# change the local_path to your workspace where the csv, json request and csv result will be
local_path <- "."
setwd(local_path)
#* @post /fort/log
log_regression<-function(file_name, target){
default_result_file_name <- "prediksi_score_all"
default_function_initial <- "lr"
print(file_name)
print(target)
now <- format(Sys.time(), "%Y%m%d%H%M%S")
csv_result_file_name <- paste("/var/www/node/hek/public/output/",default_function_initial,"_",as.character(now),".csv",sep="")
csv_file_name <- file_name
#Read json data
library(rjson)
input_target <- target
#Read csv data
training.data.raw <- read.csv(csv_file_name,header=T,na.strings=c(""))
training.data<-training.data.raw
#Change data type for discrete variable
training.data$E_X_aic_ipctry_issue<-as.factor(training.data$E_X_aic_ipctry_issue)
training.data$E_X_trx_last<-as.factor(training.data$E_X_trx_last)
training.data$learning_label<-as.factor(training.data$learning_label)
#Take specific colums from dataframe
data <- subset(training.data,select=c(2,3,4,5,6,7,8,9,10,11,14))
#Split dataframe to training and testing
train <- data[1:floor((nrow(data)*0.8)),]
test <- data[floor((nrow(data)*0.8)+1):nrow(data),]
#Build model
model <- glm(paste(input_target, "~."),family=binomial(link='logit'),data=train)
# model <- glm(paste(target),family=binomial(link='logit'),data=train)
summary(model)
#Predict data using model
fitted.results2 <- predict(model,newdata=subset(data,select=c(1,2,3,4,5,6,7,8,9,10)),type='response')
#Make score ranging from 0-1000
a22<-floor(fitted.results2*1000)
#Creating output id, ..., R_score
a2<-as.data.frame(a22)
a3<-cbind(training.data.raw$id, training.data.raw$blacklist, training.data.raw$whitelist, training.data.raw$learning_label, a2$a22)
colnames(a3) <- c("ID","Blacklist","Whitelist","Learning_Label", "R_Score")
a4<-as.data.frame(a3)
write.csv(a4,file = csv_result_file_name, row.names = FALSE)
csv_result_full_path <- paste(local_path,"/",csv_result_file_name,sep="")
response <- paste(default_function_initial,"_",as.character(now),".csv",sep="")
return (response)
}
#* @post /fort/rforest
rforest <- function(file_name,target){
default_result_file_name <- "res_all_h2o"
default_function_initial <- "output/rf"
now <- format(Sys.time(), "%Y%m%d%H%M%S")
csv_result_file_name <- paste(default_result_file_name,"_",as.character(now),".csv",sep="")
# json_file_name <- paste(default_function_initial,"_",as.character(timestamp),".json",sep="")
csv_file_name <- file_name
setwd(local_path)
library(h2o)
localH2O = h2o.init(ip = 'localhost', port = 54321)
library(rjson)
# input_target<-fromJSON(file = json_file_name)
input_target <- target
# Import data
data_raw <- read.csv(csv_file_name, header=T, na.string=c(""))
data = data_raw
train_raw <- data_raw[1:floor((nrow(data_raw)*0.8)),]
test_raw <- data_raw[floor((nrow(data_raw)*0.8)+1):nrow(data_raw),]
data$E_X_aic_ipctry_issue<-as.factor(data$E_X_aic_ipctry_issue)
data$E_X_trx_last<-as.factor(data$E_X_trx_last)
data$learning_label<-as.factor(data$learning_label)
train <- data[1:floor((nrow(data)*0.8)),]
test <- data[floor((nrow(data)*0.8)+1):nrow(data),]
train.h2o = as.h2o(train)
test.h2o = as.h2o(test)
summary(train)
summary(test)
summary(train.h2o)
summary(test.h2o)
# independent variables
y.dep = input_target
x.indep = c(2:11)
#Random Forest
system.time(rforest.model <- h2o.randomForest(y = y.dep, x=x.indep, training_frame = train.h2o, ntrees = 20, mtries = 3, max_depth = 4, seed = 1122))
h2o.performance(rforest.model)
#check variable importance
h2o.varimp(rforest.model)
# produce prediction results from the developed model (no bruce_id here)
pred_train_h2o = as.data.frame(predict(rforest.model, train.h2o))
pred_test_h2o = as.data.frame(predict(rforest.model, test.h2o))
# combining with bruce_id
res_train = cbind(train_raw$id, train_raw$blacklist, train_raw$whitelist, train_raw$learning_label, pred_train_h2o$p1)
res_test = cbind(test_raw$id, test_raw$blacklist, test_raw$whitelist, test_raw$learning_label, pred_test_h2o$p1)
res_train = as.data.frame(res_train)
res_test = as.data.frame(res_test)
res_all = as.data.frame(rbind(res_train,res_test))
colnames(res_train) = c("ID","Blacklist","Whitelist","Learning_Label","H2o_Score")
colnames(res_test) = c("ID","Blacklist","Whitelist","Learning_Label","H2o_Score")
colnames(res_all) = c("ID","Blacklist","Whitelist","Learning_Label","H2o_Score")
res_all$H2o_Score = floor(res_all$H2o_Score*1000)
# write.csv(res_train, "res_train.csv", row.names = FALSE)
# write.csv(res_test, "res_test.csv", row.names = FALSE)
write.csv(res_all, csv_result_file_name, row.names = FALSE)
csv_result_full_path <- paste(local_path,"/",csv_result_file_name,sep="")
return (csv_result_full_path)
}
|
599ad2639c1d596fcf496ca66d25ee9e344f8060
|
79b935ef556d5b9748b69690275d929503a90cf6
|
/R/percy.R
|
44aa9460278e76bfd623a47fca958ae21929d61a
|
[] |
no_license
|
spatstat/spatstat.core
|
d0b94ed4f86a10fb0c9893b2d6d497183ece5708
|
6c80ceb9572d03f9046bc95c02d0ad53b6ff7f70
|
refs/heads/master
| 2022-06-26T21:58:46.194519
| 2022-05-24T05:37:16
| 2022-05-24T05:37:16
| 77,811,657
| 6
| 10
| null | 2022-03-09T02:53:21
| 2017-01-02T04:54:22
|
R
|
UTF-8
|
R
| false
| false
| 2,860
|
r
|
percy.R
|
## percus.R
##
## Percus-Yevick style approximations to pcf and K
##
## $Revision: 1.6 $ $Date: 2022/01/20 00:47:44 $
pcfmodel.ppm <- local({
pcfmodel.ppm <- function(model, ...) {
if(is.multitype(model))
stop("Not yet implemented for multitype models")
if(is.poisson(model)) return(function(r) rep(1, length(r)))
if(!is.stationary(model))
stop("Not implemented for non-stationary Gibbs models")
inte <- as.interact(model)
if(inte$family$name != "pairwise")
stop("Only implemented for pairwise-interaction models")
lambda <- intensity(model)
beta <- exp(coef(model)[1])
par <- inte$par
pot <- inte$pot
f <- fitin(model)
Vcoefs <- f$coefs[f$Vnames]
Mayer <- inte$Mayer
G <- Mayer(Vcoefs, inte)
irange <- reach(inte, epsilon=1e-6)
G2fun <- inte$Percy
testit <- resolve.1.default(list(testit=FALSE), list(...))
if(testit || is.null(G2fun))
G2fun <- pairwisePercy
fun <- function(r) {
pcfapprox(r, beta, lambda, pot, par, Vcoefs, G, G2fun, irange)
}
return(fun)
}
pcfapprox <- function(r, beta, lambda, pot, par, Vcoefs, G, G2fun, irange) {
as.numeric((beta/lambda)^2 *
exp(logpairpot(r, pot, par, Vcoefs)
- lambda * G2fun(r, Vcoefs, par, pot=pot,
irange=irange, G=G)))
}
logpairpot <- function(r, pot, par, Vcoefs) {
as.numeric(pot(matrix(r, ncol=1), par) %*% Vcoefs)
}
negpair <- function(x,y, pot, par, Vcoefs) {
## evaluate 1 - g(x,y)
## where g(x,y) is pair interaction between (0,0) and (x,y)
1 - exp(logpairpot(sqrt(x^2+y^2), pot, par, Vcoefs))
}
pairwisePercy <- function(r, Vcoefs, par, ..., G, pot, irange, dimyx=256) {
S <- max(max(r), irange)
ng <- as.im(negpair, square(c(-S,S)),
pot=pot, par=par, Vcoefs=Vcoefs,
dimyx=dimyx)
ng2 <- convolve.im(ng)
rr <- seq(min(r), max(r), length=dimyx[1])
yy <- ng2[list(x=rr, y=rep.int(0, dimyx[1]))]
zz <- 2 * G - yy
z <- approx(rr, zz, r)$y
return(z)
}
pcfmodel.ppm
})
Kmodel.ppm <- local({
Kmodel.ppm <- function(model, ...) {
if(is.poisson(model)) return(function(r) { pi * r^2 })
pc <- pcfmodel(model, ...)
K <- function(r) pcf2K(r, pc)
return(K)
}
pcf2K <- function(r, pc) {
## integrate the pair correlation function to obtain the K-function
if(length(r) == 1) {
## definite integral
spcfs <- function(s) { s * pc(s) }
y <- 2 * pi * integrate(spcfs, lower=0, upper=r)$value
} else {
## indefinite integral
rr <- seq(0, max(r), length=1025)
dr <- max(r)/(length(rr) - 1)
ff <- 2 * pi * rr * pc(rr)
yy <- dr * cumsum(ff)
y <- approx(rr, yy, r)$y
}
return(y)
}
Kmodel.ppm
})
|
f8e30f5b5d7bbd436ece20f038989191a361802e
|
e46d25823e38f1f0885a2096c83c913b3c8d7172
|
/Data and Analysis Scripts/Eval.R
|
4aaf806aa3cff3b401f2ca1a34fc87a84b97f65b
|
[] |
no_license
|
brains-on-code/indentation
|
b061ef78785c1b9f0647c248d107555e3cee7c02
|
b07a7c7eefbb597c425a36b6a3d05ee5d985dfe0
|
refs/heads/master
| 2020-04-27T00:04:26.984763
| 2019-03-11T10:14:06
| 2019-03-11T10:14:06
| 173,923,218
| 1
| 0
| null | 2019-03-05T10:13:43
| 2019-03-05T10:13:43
| null |
UTF-8
|
R
| false
| false
| 2,597
|
r
|
Eval.R
|
results <- read.csv(Results.csv",head=TRUE,sep=";")
results$Indentation <- sub("^", "Indent ", results$Indentation )
generalInfos <- read.csv(file="GeneralInfo.csv",head=TRUE,sep=";", colClasses="character")
ratingReal <- read.csv(file="RatingsRealIndentations.csv",head=TRUE,sep=";")
ratingEqual <- read.csv(file="RatingsEqualIndentations.csv",head=TRUE,sep=";")
ogama <- read.csv(file="D:\CalculatedGaze.csv",head=TRUE,sep=";")
ogama_log <- ogama
ogama_log$FixationDurationMean <- log(ogama$FixationDurationMean)
ogama_log$FixationDurationMedian <- log(ogama$FixationDurationMedian)
ogama_log$FixationCountPerSec <- log(ogama$FixationCountPerSec)
ogama_log$SaccadeRatio <- log(ogama$SaccadeRatio)
ogama_log$SaccadeLengthAverage <- log(ogama$SaccadeLengthAverage)
#fixations <- read.csv(file="D:\\Dokumente\\ba\\PythonCode\\GazeData\\Fixations.csv",head=TRUE,sep=";")
#saccades <- read.csv(file="D:\\Dokumente\\ba\\PythonCode\\GazeData\\Saccades.csv",head=TRUE,sep=";")
#generalInfos <- merge(rightAnswersperSubject, generalInfos, by="SubjectID")
# print(summary(results))
# print(summary(generalInfos))
# print(summary(ratingEqual))
# print(summary(ratingReal))
# y <- log(rightResults$Time)
# qqnorm(y)
# qqline(y)
# print(shapiro.test(y))
# print( ks.test(y,"pexp"))
# x <- timesPerSubject
# iq <- IQR(x$Time)
# fq <- as.numeric(quantile(x$Time, .25))
# tq <- as.numeric(quantile(x$Time, .75))
# test <- x[x$Time > (fq - 1.5 * iq) & x$Time < (tq + 1.5*iq),]
library(ez)
anovData <- results_info
anovData$Indentation <- sub("^", "Indent ", anovData$Indentation )
anovData$Number <-sub("^", "Pos ", anovData$Number)
anovData$Time <- log(anovData$Time)
anovaTimeIndent <- ezANOVA(
data=anovData,
dv=.(Time),
wid=.(SubjectID),
within=.(Indentation),
)
anovaTimeClass <- ezANOVA(
data=anovData,
dv=.(Time),
wid=.(SubjectID),
within=.(Snippet),
)
anovaFixCOuntIndent <- ezANOVA(
data=ogama,
dv=.(FixationCount),
wid=.(SubjectID),
within=.(Indentation),
)
anovaFixDurationMeanIndent <- ezANOVA(
data=ogama,
dv=.(FixationDurationMean),
wid=.(SubjectID),
within=.(Indentation),
)
anovaFixDurationMedianIndent <- ezANOVA(
data=ogama,
dv=.(FixationDurationMedian),
wid=.(SubjectID),
within=.(Indentation),
)
anovaFixRateIndent <- ezANOVA(
data=ogama,
dv=.(FixationCountPerSec),
wid=.(SubjectID),
within=.(Indentation),
)
anovaSaccAmIndent <- ezANOVA(
data=ogama_log,
dv=.(SaccadeLengthAverage),
wid=.(SubjectID),
within=.(Indentation),
)
# Friedman
friedman.test(FixationCountPerSec ~ Indentation | SubjectID, ogama)
|
8337bc34ca04c3a70a440626b2564376dad21925
|
ae9065c400fd46a146b7d0cbc654d01294add5c6
|
/explore.R
|
92892ea7f9a0bd1b057dec285797e86d4786d0e6
|
[] |
no_license
|
ccjolley/favorita
|
8f71d04420bd8fe993bc2bc8da4452f49e4f1da9
|
463dd8aef49e5d6b5819103be0f06745861c298f
|
refs/heads/master
| 2021-08-06T19:18:57.729227
| 2017-11-06T22:01:05
| 2017-11-06T22:01:05
| 108,410,826
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,942
|
r
|
explore.R
|
# Feature engineering for favorita dataset
library(dplyr)
library(ggplot2)
library(ff)
library(ffbase2)
library(lubridate)
setwd("C:/Users/Craig/Desktop/Live projects/kaggle/favorita")
###############################################################################
# Load training data using ff to get around memory limitations
# Training dataset is 4.7GB and my laptop only has 8GB of RAM
###############################################################################
train <- read.csv.ffdf(file='train.csv',VERBOSE=TRUE)
# 125.5M rows; took about 10 minutes to load
ffsave(train,file='train.ff') # for faster loading next time
ffload(file='train.ff') # start here
###############################################################################
# Sample time series for one store
###############################################################################
all_dates <- data.frame(date=seq(ymd('2013-01-01'),ymd('2017-08-15'),by='1 day'))
store_25 <- train %>%
filter(store_nbr==25) %>%
group_by(date) %>%
summarize(total_sales=sum(unit_sales)) %>%
as.data.frame %>%
mutate(date = ymd(date)) %>%
full_join(all_dates,by='date') %>% # pad with zeros for missing dates
mutate(total_sales=ifelse(is.na(total_sales),0,total_sales))
ggplot(store_25,aes(x=date,y=total_sales)) +
geom_line(color='cornflowerblue') +
ggtitle('Total transactions for store #25') +
theme_classic() +
theme(axis.title=element_blank())
###############################################################################
# Compare time series for stores
# TODO: Something isn't right here -- revisit this.
###############################################################################
stores <- read.csv('stores.csv') # 54 stores
store_row <- function(snum) {
print(snum)
tmp <- train %>%
filter(store_nbr==snum) %>%
as.data.frame %>%
group_by(date) %>%
summarize(total_sales=sum(unit_sales)) %>%
mutate(date = ymd(date)) %>%
full_join(all_dates,by='date') %>% # pad with zeros for missing dates
mutate(total_sales=ifelse(is.na(total_sales),0,total_sales))
t(tmp$total_sales)
}
system.time(store_row(2)) # ~10s; 54 stores = <10 min
#store_totals <- plyr::ldply(c(1,2),store_row)
store_totals <- plyr::ldply(stores$store_nbr,store_row)
write.csv(store_totals,'store_totals.csv',row.names=FALSE) # for later
# Need to drop any constant columns before I can rescale for PCA
apply(store_totals,2,sd) %>% sort %>% head(20)
# Why are 1680-1688 constant? All stores had the same sales on those dates?
all_dates[1680:1688,]
last_day <- train %>%
filter(date=='2017-08-15') %>%
as.data.frame
last_day[last_day$store_nbr==1,'unit_sales'] %>% sum
# definitely not zero
store_pca <- prcomp(store_totals,center=TRUE,scale=TRUE)
plot(store_pca)
summary(store_pca) # 87% in first PC
stores$PC1 <- score_pca$x[,1]
stores$PC2 <- score_pca$x[,2]
# Try coloring points according to some of the categories they give us to
# see whether PCA separates them.
ggplot(stores,aes(x=PC1,y=PC2)) +
geom_point(size=2) +
theme_classic()
###############################################################################
# Sample time series for one item
###############################################################################
item_103665 <- train %>%
filter(item_nbr==103665) %>%
group_by(date) %>%
summarize(total_sales=sum(unit_sales)) %>%
as.data.frame %>%
mutate(date = ymd(date))
ggplot(item_103665,aes(x=date,y=total_sales)) +
geom_line(color='tomato3') +
ggtitle('Total transactions for item #103665') +
theme_classic() +
theme(axis.title=element_blank())
# Looks really different from distribution for store
###############################################################################
# How were total sales impacted by April 16th, 2016 earthquake?
###############################################################################
all_sales <- train4 %>%
group_by(date) %>%
summarize(tot <- sum(unit_sales)) %>%
as.data.frame %>%
mutate(date=ymd(date))
###############################################################################
# For a given item, figure out how much promotions boost sales
# Return 1 (no change) if not statistically-significant
###############################################################################
promo_ratio <- function(item_num,plot=FALSE) {
tmp <- train %>%
filter(item_nbr==item_num) %>%
filter(!is.na(onpromotion)) %>%
group_by(date,store_nbr,onpromotion) %>%
summarize(total_sales=sum(unit_sales)) %>%
as.data.frame %>%
mutate(logsales = log(total_sales+1))
if (plot==TRUE) {
ggplot(tmp,aes(x=logsales)) +
geom_density(aes(group=onpromotion,fill=onpromotion),alpha=0.3) +
theme_classic()
}
else {
if (mean(tmp$onpromotion) > 0.01 & mean(tmp$onpromotion) < 0.99) {
tt <- t.test(tmp[tmp$onpromotion==TRUE,'logsales'],
tmp[tmp$onpromotion==FALSE,'logsales'],
alternative='greater')
if (tt$p.value > 0.05) { return(1) }
return( (exp(tt$estimate[1])-1)/(exp(tt$estimate[2])-1) )
}
else { return(1) }
}
}
system.time(promo_ratio(2113914) %>% print) # 3.84s total
# Now do this for all items and see where promotions help the most
items <- read.csv('items.csv')
# 4100 rows; may take >4h to run all t-tests. Run overnight
promo <- sapply(items$item_nbr %>% head(200),promo_ratio)
# Really, my goal here should be feature engineering. I can enrich each
# data point with features related to the store, the item, or the day.
# Stores
# Use metadata provided with stores
# Which stores cluster together in terms of correlated fluctuations?
# PCA of sales time series?
# Separate stores into quantiles
# Items
# Use item metadata
# Which items cluster together?
# PCA of sales time series
# Item quantiles
# Promotion sensitivity
# Days
# Year, month, day of week
# Special events
# Public paydays
# Day quantiles
|
49caa2daa9010f9e45598a4254cbd3e90e70ed95
|
b37d771ab1a5c138be24aff631818957266310bd
|
/final_project/InitialCleanUp_2.R
|
a8fbae653001cb279582d70b0a803d91900ac5ae
|
[] |
no_license
|
shivAM2886/ENPM-808W-
|
e3b082bcb7044d6a5e78b70c46764ce59f8ac933
|
8dafe82a86c6ec5fdd0f23241b2add196af41bc7
|
refs/heads/master
| 2021-07-19T16:13:17.772255
| 2020-09-03T02:37:48
| 2020-09-03T02:37:48
| 211,268,009
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,616
|
r
|
InitialCleanUp_2.R
|
# This script further cleans the data after the InitialCleanUp.py script
rm(list=ls())
## Set Up Working Directory
DATA_LOCATION <- "/Users/Pende/Desktop/us-perm-visas"
setwd(DATA_LOCATION)
dataF <- read.csv('us_perm_visas_UPDATED.csv') # Load updated Dataset with some fixed variables (afer output of InitialCleanUp.py)
prop.table(summary(dataF$case_status))
length(dataF)
# Keep these fields
fieldsToKeep = c("case_no",
"case_status",
"agent_state",
"case_received_date_EPOCH",
"case_received_date_YEAR",
"class_of_admission",
"country_of_citizenship",
"employer_name",
"employer_state",
"application_type",
"decision_date_YEAR",
"employer_postal_code",
"foreign_worker_ownership_interest",
"foreign_worker_info_education",
"job_info_major",
"pw_amount_9089",
"pw_unit_of_pay_9089",
"us_economic_sector",
"wage_offer_from_9089",
"wage_offer_unit_of_pay_9089")
dataF = dataF[,fieldsToKeep]
dataF$Accepted = TRUE
# Certified Certified-Expired Denied Withdrawn
idxDenied = which(dataF$case_status == "Denied") # Definitly bad
idxWithdrawn = which(dataF$case_status == "Withdrawn") # Treat these as Bad as well
idxFalse = union(idxDenied, idxWithdrawn)
dataF$Accepted[idxFalse] = FALSE
write.csv(dataF,'us_perm_visas_SMALL.csv', row.names = FALSE)
|
2b4527ad68d6766b6ccc6189bef7eef5a0635b94
|
343486c41c6f6dab5fe39bcb65f5ea4d35e46645
|
/neural_network.R
|
5903db18c3ece3afd6125cfe95f7907411b55669
|
[] |
no_license
|
devgg/crime_sf
|
6c950c9f26ef65f4b966dc3c34c1b0089bdc542c
|
74ec28c808e8cd6142aaaf1aaea0c2ed00d3eb1b
|
refs/heads/master
| 2020-04-10T23:40:41.766845
| 2015-08-08T13:22:20
| 2015-08-08T13:22:20
| 40,196,752
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,688
|
r
|
neural_network.R
|
create_neural_network <- function(layer_sizes, input_layer_col_names, output_layer_col_names) {
network <- list()
for (i in 1:(length(layer_sizes)-1)) {
epsilon = sqrt(6) / sqrt(layer_sizes[i] + layer_sizes[i + 1])
rows = layer_sizes[i + 1]
cols = layer_sizes[i] + (if(i==1) 0 else 1)
network[[i]] = matrix(runif(rows * cols, -epsilon, epsilon), rows, cols)
}
colnames(network[[1]]) <- input_layer_col_names
rownames(network[[length(network)]]) <- output_layer_col_names
return(network)
}
forward_propagation <- function(network, records) {
z <- list(t(apply(records, 1, function(record) network[[1]] %*% record)))
a <- list(records, sigmoid(z[[1]]))
for (i in 2:length(network)) {
z[[i]] = t(apply(cbind(1, a[[i]]), 1, function(a_row) network[[i]] %*% a_row))
a[[i + 1]] = sigmoid(z[[i]])
}
colnames(a[[length(a)]]) <- rownames(network[[length(network)]])
return(list(z = z, a = a, h = a[[length(a)]]))
}
back_propagation <- function(network, forward_data, y) {
y <- outer(y, 1:ncol(forward_data$h), "==") * 1
delta3 = forward_data$h - y
delta2 = (delta3 %*% network[[2]])[,-1] * sigmoid_gradient(forward_data$z[[1]])
grad1 = matrix(0, nrow(network[[1]]), ncol(network[[1]]))
grad2 = matrix(0, nrow(network[[2]]), ncol(network[[2]]))
for(i in 1:nrow(y)) {
grad1 = grad1 + outer(delta2[i,], forward_data$a[[1]][i,], "*")
grad2 = grad2 + outer(delta3[i,], c(1, forward_data$a[[2]][i,]), "*")
}
return(list(grad1 / nrow(y), grad2 / nrow(y)))
}
batch_gradient_descent <- function(network, records_formated, iterations, alpha, momentum) {
v_old <- list();
v_new <- list();
for (j in 1:iterations) {
forward_data <- forward_propagation(network, records_formated$data)
print(sprintf("%d: %f", j, calculate_cost(records_formated$y, forward_data$h)))
gradients <- back_propagation(network, forward_data, records_formated$y)
for (i in 1: length(network)) {
v_new[[i]] = alpha * gradients[[i]]
network[[i]] = network[[i]] - (v_new[[i]] + (if(j == 1) 0 else momentum * v_old[[i]]))
v_old[[i]] = v_new[[i]]
}
}
return(network)
}
mini_batch_gradient_descent <- function(network, records_formated, iterations, alpha, momentum, batch_size) {
batch_indices <- c(1)
while(batch_indices[length(batch_indices)] < nrow(records_formated[[1]])) {
batch_indices[length(batch_indices) + 1] = min(batch_indices[length(batch_indices)] + batch_size, nrow(records_formated[[1]]))
}
v_old <- list();
v_new <- list();
for (j in 1:iterations) {
for (b in 1:(length(batch_indices) - 1)) {
forward_data <- forward_propagation(network, records_formated$data[batch_indices[b]:batch_indices[b+1],])
print(sprintf("%d: %f", j, calculate_cost(records_formated$y[batch_indices[b]:batch_indices[b+1]], forward_data$h)))
gradients <- back_propagation(network, forward_data, records_formated$y[batch_indices[b]:batch_indices[b+1]])
for (i in 1: length(network)) {
v_new[[i]] = alpha * gradients[[i]]
network[[i]] = network[[i]] - (v_new[[i]] + (if(j == 1) 0 else momentum * v_old[[i]]))
v_old[[i]] = v_new[[i]]
}
}
}
return(network)
}
calculate_cost <- function(y, h) {
epsilon = 1e-15
#h = matrix(sapply(h, function(h_row) min(1 - epsilon, max(epsilon, h_row))), nrow = nrow(h))
y <- outer(y, 1:ncol(h), "==") * 1
return(sum(-y * log(h) - (1 - y) * log(1 - h)) / nrow(h))
}
sigmoid <- function(value) {
return(1 / (1 + exp(-value)))
}
sigmoid_gradient <- function(value) {
value_sigmoid = sigmoid(value)
return(value_sigmoid * (1 - value_sigmoid))
}
|
35477e9433e442175b2e52e40d1055dc62538133
|
6034d565642a30876b7b7a025b74a31580c44613
|
/R/methods_gjrm.R
|
252c289c3813166a13b7fd11c2151c7b258ff89a
|
[] |
no_license
|
cran/parameters
|
a95beba8c8bd820a88b74ca407609cc08a62fcab
|
f19575ccdbbd303a1896a13d8b4b8210563cabfa
|
refs/heads/master
| 2023-06-08T08:58:24.080762
| 2023-05-26T09:20:02
| 2023-05-26T09:20:02
| 211,083,154
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,122
|
r
|
methods_gjrm.R
|
#' @rdname model_parameters.averaging
#' @export
model_parameters.SemiParBIV <- function(model,
ci = 0.95,
bootstrap = FALSE,
iterations = 1000,
standardize = NULL,
exponentiate = FALSE,
p_adjust = NULL,
keep = NULL,
drop = NULL,
verbose = TRUE,
...) {
out <- .model_parameters_generic(
model = model,
ci = ci,
bootstrap = bootstrap,
iterations = iterations,
component = "all",
merge_by = c("Parameter", "Component"),
standardize = standardize,
exponentiate = exponentiate,
keep_parameters = keep,
drop_parameters = drop,
p_adjust = p_adjust,
...
)
attr(out, "object_name") <- insight::safe_deparse_symbol(substitute(model))
out
}
#' @export
p_value.SemiParBIV <- function(model, ...) {
s <- summary(model)
s <- insight::compact_list(s[startsWith(names(s), "tableP")])
params <- do.call(rbind, lapply(seq_along(s), function(i) {
out <- as.data.frame(s[[i]])
out$Parameter <- rownames(out)
out$Component <- paste0("Equation", i)
out
}))
colnames(params)[4] <- "p"
rownames(params) <- NULL
insight::text_remove_backticks(params[c("Parameter", "p", "Component")], verbose = FALSE)
}
#' @export
standard_error.SemiParBIV <- function(model, ...) {
s <- summary(model)
s <- insight::compact_list(s[startsWith(names(s), "tableP")])
params <- do.call(rbind, lapply(seq_along(s), function(i) {
out <- as.data.frame(s[[i]])
out$Parameter <- rownames(out)
out$Component <- paste0("Equation", i)
out
}))
colnames(params)[2] <- "SE"
rownames(params) <- NULL
insight::text_remove_backticks(params[c("Parameter", "SE", "Component")], verbose = FALSE)
}
|
06240bf87f992f2b28c9e32e487f2a6bbe0c493f
|
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
|
/fuzzedpackages/GMMAT/tests/testthat/test_glmmkin.R
|
299deb2a87050010921840cbbcb6168e662b746d
|
[] |
no_license
|
akhikolla/testpackages
|
62ccaeed866e2194652b65e7360987b3b20df7e7
|
01259c3543febc89955ea5b79f3a08d3afe57e95
|
refs/heads/master
| 2023-02-18T03:50:28.288006
| 2021-01-18T13:23:32
| 2021-01-18T13:23:32
| 329,981,898
| 7
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 27,440
|
r
|
test_glmmkin.R
|
context("null model")
test_that("cross-sectional id le 400 binomial", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
pheno <- rbind(example$pheno, example$pheno[1:100, ])
pheno$id <- 1:500
pheno$disease[sample(1:500,20)] <- NA
pheno$age[sample(1:500,20)] <- NA
pheno$sex[sample(1:500,20)] <- NA
pheno <- pheno[sample(1:500,450), ]
pheno <- pheno[pheno$id <= 400, ]
kins <- example$GRM
obj1 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Brent")
expect_equal(signif(as.numeric(obj1$theta)), signif(c(1, 0.1925217)))
expect_equal(signif(as.numeric(obj1$coef)), signif(c(1.01676248, -0.01506251, -0.33240660)))
obj2 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Brent")
expect_equal(as.numeric(obj2$theta), c(1, 0))
expect_equal(signif(as.numeric(obj2$coef)), signif(c(0.94253959, -0.01429532, -0.32823930)))
obj3 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(signif(as.numeric(obj3$theta)), c(1, 0.1925))
expect_equal(signif(as.numeric(obj3$coef)), signif(c(1.0224921, -0.0151259, -0.3328061)))
obj4 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(as.numeric(obj4$theta), c(1, 0))
expect_equal(signif(as.numeric(obj4$coef)), signif(c(0.94253959, -0.01429532, -0.32823930)))
obj5 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(signif(as.numeric(obj5$theta)), signif(c(1, 0.1925225)))
expect_equal(signif(as.numeric(obj5$coef)), signif(c(1.01676230, -0.01506251, -0.33240659)))
obj6 <- glmmkin(disease ~ age + sex, data = pheno, kins = NULL, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(c(obj6$theta), 1)
expect_equal(signif(as.numeric(obj6$coef)), signif(c(0.94253958, -0.01429532, -0.32823930)))
obj <- glm(disease ~ age + sex, data = pheno, family = binomial(link = "logit"))
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = NULL, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
obj <- glm(disease ~ age + sex, data = pheno, family = binomial(link = "logit"))
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = NULL, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
})
test_that("cross-sectional id gt 400 binomial", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
pheno <- rbind(example$pheno, example$pheno[1:100, ])
pheno$id <- 1:500
pheno$disease[sample(1:500,20)] <- NA
pheno$age[sample(1:500,20)] <- NA
pheno$sex[sample(1:500,20)] <- NA
pheno <- pheno[sample(1:500,450), ]
kins <- diag(500)
kins[1:400, 1:400] <- example$GRM
rownames(kins) <- colnames(kins) <- 1:500
obj1 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Brent")
expect_equal(signif(as.numeric(obj1$theta)), signif(c(1, 0.1263608)))
expect_equal(signif(as.numeric(obj1$coef)), signif(c(0.92300941, -0.01457307, -0.18165857)))
obj2 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Brent")
expect_equal(as.numeric(obj2$theta), c(1, 0))
expect_equal(signif(as.numeric(obj2$coef)), signif(c(0.86840326, -0.01402939, -0.17898775)))
obj3 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(signif(as.numeric(obj3$theta)), c(1, 0.121))
expect_equal(signif(as.numeric(obj3$coef), digits = 5), signif(c(0.92527071, -0.01459762, -0.18179150), digits = 5))
obj4 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(as.numeric(obj4$theta), c(1, 0))
expect_equal(signif(as.numeric(obj4$coef)), signif(c(0.86840326, -0.01402939, -0.17898775)))
obj5 <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(signif(as.numeric(obj5$theta)), signif(c(1, 0.1263611)))
expect_equal(signif(as.numeric(obj5$coef)), signif(c(0.92300945, -0.01457307, -0.18165858)))
obj6 <- glmmkin(disease ~ age + sex, data = pheno, kins = NULL, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(c(obj6$theta), 1)
expect_equal(signif(as.numeric(obj6$coef)), signif(c(0.86840325, -0.01402939, -0.17898775)))
obj <- glm(disease ~ age + sex, data = pheno, family = binomial(link = "logit"))
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = NULL, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
obj <- glm(disease ~ age + sex, data = pheno, family = binomial(link = "logit"))
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = kins, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(disease ~ age + sex, data = pheno, kins = NULL, id = "id", family = binomial(link = "logit"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
})
test_that("cross-sectional id le 400 gaussian", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
pheno <- rbind(example$pheno, example$pheno[1:100, ])
pheno$id <- 1:500
pheno$disease[sample(1:500,20)] <- NA
pheno$age[sample(1:500,20)] <- NA
pheno$sex[sample(1:500,20)] <- NA
pheno <- pheno[sample(1:500,450), ]
pheno <- pheno[pheno$id <= 400, ]
kins <- example$GRM
obj1 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Brent")
expect_equal(signif(as.numeric(obj1$theta)), signif(c(0.7682478, 1.3037470)))
expect_equal(signif(as.numeric(obj1$coef)), signif(c(3.7634934, 0.0346562, 0.3062784)))
obj2 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Brent")
expect_equal(signif(as.numeric(obj2$theta)), signif(c(0.9391236, 1.0851816)))
expect_equal(signif(as.numeric(obj2$coef)), signif(c(3.76521261, 0.03451443, 0.30509914)))
obj3 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(signif(as.numeric(obj3$theta), digits = 5), signif(c(0.7174382, 1.2196450), digits = 5))
expect_equal(signif(as.numeric(obj3$coef)), signif(c(3.76315625, 0.03469074, 0.30656586)))
obj4 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(signif(as.numeric(obj4$theta)), signif(c(0.9622361, 1.0584597)))
expect_equal(signif(as.numeric(obj4$coef)), signif(c(3.76551377, 0.03449328, 0.30492363)))
obj5 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(signif(as.numeric(obj5$theta)), signif(c(0.7682481, 1.3037467)))
expect_equal(signif(as.numeric(obj5$coef)), signif(c(3.7634933, 0.0346562, 0.3062784)))
obj6 <- glmmkin(trait ~ age + sex, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(signif(as.numeric(obj6$theta)), signif(1.996857))
expect_equal(signif(as.numeric(obj6$coef)), signif(c(3.89665633, 0.03156906, 0.27860778)))
obj <- lm(trait ~ age + sex, data = pheno)
expect_equal(c(obj6$theta), summary(obj)$sigma^2)
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
obj <- lm(trait ~ age + sex, data = pheno)
expect_equal(c(obj6$theta), summary(obj)$sigma^2)
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
})
test_that("cross-sectional id gt 400 gaussian", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
pheno <- rbind(example$pheno, example$pheno[1:100, ])
pheno$id <- 1:500
pheno$disease[sample(1:500,20)] <- NA
pheno$age[sample(1:500,20)] <- NA
pheno$sex[sample(1:500,20)] <- NA
pheno <- pheno[sample(1:500,450), ]
kins <- diag(500)
kins[1:400, 1:400] <- example$GRM
rownames(kins) <- colnames(kins) <- 1:500
obj1 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Brent")
expect_equal(signif(as.numeric(obj1$theta)), signif(c(0.7205609, 1.3795640)))
expect_equal(signif(as.numeric(obj1$coef)), signif(c(3.90459575, 0.03650594, 0.37958367)))
obj2 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Brent")
expect_equal(signif(as.numeric(obj2$theta)), signif(c(0.7485909, 1.3321148)))
expect_equal(signif(as.numeric(obj2$coef)), signif(c(3.90396978, 0.03649397, 0.37960264)))
obj3 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(signif(as.numeric(obj3$theta)), signif(c(0.6044086, 1.2692581)))
expect_equal(signif(as.numeric(obj3$coef)), signif(c(3.90659373, 0.03654332, 0.37947361)))
obj4 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(signif(as.numeric(obj4$theta)), signif(c(0.7188051, 1.2219687)))
expect_equal(signif(as.numeric(obj4$coef)), signif(c(3.90453205, 0.03650473, 0.37958592)))
obj5 <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(signif(as.numeric(obj5$theta)), signif(c(0.7205609, 1.3795639)))
expect_equal(signif(as.numeric(obj5$coef)), signif(c(3.90459568, 0.03650594, 0.37958367)))
obj6 <- glmmkin(trait ~ age + sex, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(signif(as.numeric(obj6$theta)), signif(2.051809))
expect_equal(signif(as.numeric(obj6$coef)), signif(c(3.7836398, 0.0344577, 0.3602852)))
obj <- lm(trait ~ age + sex, data = pheno)
expect_equal(c(obj6$theta), summary(obj)$sigma^2)
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
obj <- lm(trait ~ age + sex, data = pheno)
expect_equal(c(obj6$theta), summary(obj)$sigma^2)
expect_equal(obj6$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Brent")
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Brent")
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "Nelder-Mead")
expect_equal(obj3$theta, obj$theta)
expect_equal(obj3$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "ML", method.optim = "Nelder-Mead")
expect_equal(obj4$theta, obj$theta)
expect_equal(obj4$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj5$theta, obj$theta)
expect_equal(obj5$coef, obj$coef)
obj <- glmmkin(trait ~ age + sex, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"), method = "REML", method.optim = "AI")
expect_equal(obj6$theta, obj$theta)
expect_equal(obj6$coef, obj$coef)
})
test_that("longitudinal repeated measures gaussian", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
pheno <- example$pheno2
kins <- example$GRM
obj1 <- glmmkin(y.repeated ~ sex, data = pheno, kins = kins, id = "id",random.slope = NULL, family = gaussian(link = "identity"))
expect_equal(signif(as.numeric(obj1$theta)), signif(c(0.5089983, 0.2410866, 0.2129918)))
expect_equal(signif(as.numeric(obj1$coef)), signif(c(0.9871441, 0.6134051)))
obj2 <- glmmkin(y.repeated ~ sex, data = pheno, kins = NULL, id = "id",random.slope = NULL, family = gaussian(link = "identity"))
expect_equal(signif(as.numeric(obj2$theta)), signif(c(0.5089982, 0.4374597)))
expect_equal(signif(as.numeric(obj2$coef)), signif(c(1.0237, 0.6141)))
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(y.repeated ~ sex, data = pheno, kins = kins, id = "id",random.slope = NULL, family = gaussian(link = "identity"))
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(y.repeated ~ sex, data = pheno, kins = NULL, id = "id",random.slope = NULL, family = gaussian(link = "identity"))
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(y.repeated ~ sex, data = pheno, kins = kins, id = "id",random.slope = NULL, family = gaussian(link = "identity"))
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(y.repeated ~ sex, data = pheno, kins = NULL, id = "id",random.slope = NULL, family = gaussian(link = "identity"))
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
})
test_that("longitudinal random time trend gaussian", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
pheno <- example$pheno2
kins <- example$GRM
obj1 <- glmmkin(y.trend ~ sex + time, data = pheno, kins = kins, id = "id",random.slope = "time", family = gaussian(link = "identity"))
expect_equal(signif(as.numeric(obj1$theta), digits = 5), signif(c(2.0139758, 1.5056913, 0.5443502, 1.2539360, -0.2469174, 1.1690885, 0.6931906), digits = 5))
expect_equal(signif(as.numeric(obj1$coef)), signif(c(1.1834620, 0.6320665, 1.0701016)))
obj2 <- glmmkin(y.trend ~ sex + time, data = pheno, kins = NULL, id = "id",random.slope = "time", family = gaussian(link = "identity"))
expect_equal(signif(as.numeric(obj2$theta)), signif(c(2.0139758, 1.8949301, 0.8748916, 1.7403904)))
expect_equal(signif(as.numeric(obj2$coef), digits = 5), signif(c(1.1532040, 0.6177671, 1.0189475), digits = 5))
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(y.trend ~ sex + time, data = pheno, kins = kins, id = "id",random.slope = "time", family = gaussian(link = "identity"))
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(y.trend ~ sex + time, data = pheno, kins = NULL, id = "id",random.slope = "time", family = gaussian(link = "identity"))
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(y.trend ~ sex + time, data = pheno, kins = kins, id = "id",random.slope = "time", family = gaussian(link = "identity"))
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(y.trend ~ sex + time, data = pheno, kins = NULL, id = "id",random.slope = "time", family = gaussian(link = "identity"))
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
})
test_that("multiple phenotypes gaussian", {
skip_on_cran()
data(example)
suppressWarnings(RNGversion("3.5.0"))
set.seed(103)
kins <- example$GRM
tau1 <- matrix(c(3,0.5,0,0.5,2.5,-0.1,0,-0.1,3),3,3)
tau2 <- matrix(c(2.5,0.8,0.2,0.8,4.8,-0.1,0.2,-0.1,2.8),3,3)
kins.chol <- chol(tau1 %x% kins + tau2 %x% diag(400))
tmp <- as.vector(crossprod(kins.chol, rnorm(1200)))
x1 <- rnorm(400)
x2 <- rbinom(400,1,0.5)
pheno <- data.frame(id = 1:400, x1 = x1, x2 = x2, y1 = 0.5*x1+0.8*x2+tmp[1:400], y2 = x1-0.3*x2+tmp[401:800], y3 = x2+tmp[801:1200])
obj1 <- glmmkin(cbind(y1,y2,y3)~x1+x2, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"))
expect_equal(signif(c(as.vector(obj1$theta[[1]]),as.vector(obj1$theta[[2]])), digits = 5), signif(c(3.13246847, 1.52966809, 0.27819033, 1.52966809, 5.21123625, -1.87847885, 0.27819033, -1.87847885, 3.04660044, 1.69332546, -0.36423974, -0.07708463, -0.36423974, 2.07095534, 1.62893810, -0.07708463, 1.62893810, 2.61803110), digits = 5))
expect_equal(signif(c(obj1$coef)), signif(c(0.20216323, 0.30601599, 0.74140916, 0.04119201, 1.04136078, -0.40556256, 1.08891927, 0.02044031, 1.01281152)))
obj2 <- glmmkin(cbind(y1,y2,y3)~x1+x2, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"))
expect_equal(signif(c(obj2$theta[[1]])), signif(c(4.6708159, 1.1614428, 0.1580549, 1.1614428, 7.2537122, -0.2297423, 0.1580549, -0.2297423, 5.6175721)))
expect_equal(signif(c(obj2$coef), digits = 5), signif(c(0.13897937, 0.31965037, 0.77867243, 0.26349000, 1.03272869, -0.46414252, 1.25165117, 0.01778239, 0.95851562), digits = 5))
idx <- sample(nrow(pheno))
pheno <- pheno[idx, ]
obj <- glmmkin(cbind(y1,y2,y3)~x1+x2, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"))
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(cbind(y1,y2,y3)~x1+x2, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"))
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
idx <- sample(nrow(kins))
kins <- kins[idx, idx]
obj <- glmmkin(cbind(y1,y2,y3)~x1+x2, data = pheno, kins = kins, id = "id", family = gaussian(link = "identity"))
expect_equal(obj1$theta, obj$theta)
expect_equal(obj1$coef, obj$coef)
obj <- glmmkin(cbind(y1,y2,y3)~x1+x2, data = pheno, kins = NULL, id = "id", family = gaussian(link = "identity"))
expect_equal(obj2$theta, obj$theta)
expect_equal(obj2$coef, obj$coef)
})
|
ef14018b070443c77055000a02b1447d0b052b1a
|
e76e882629e98c0c4023fc8103c60e0fa451ccf2
|
/R/int_plot_gene_dise.R
|
0210a593d80fbe0f0681ecb29046eb9e30e9ba58
|
[
"MIT"
] |
permissive
|
isglobal-brge/CTDquerier
|
e5269a74a63cb3df201d301c28d430ea6cbe16c6
|
d66b9fd83f81421ac45d83e1ca09dc4576f4c157
|
refs/heads/master
| 2022-11-07T01:18:03.481877
| 2022-10-05T22:14:11
| 2022-10-05T22:26:17
| 91,874,590
| 5
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,540
|
r
|
int_plot_gene_dise.R
|
int_plot_gene_disease_heatmap <- function( x, subset.gene, subset.disease,
field.score = "Inference", filter.score = 50, max.length = 30 ) {
field.score <- match.arg( field.score, choices = c( "Inference", "Reference" ) )
field.score <- ifelse( field.score == "Inference", "Inference.Score", "Reference.Count" )
tbl <- get_table( x, index_name = "diseases" )
if( !missing( subset.gene ) ) {
tbl <- tbl[ tbl$GeneSymbol %in% subset.gene, ]
}
if( !missing( subset.disease ) ) {
tbl <- tbl[ tbl$Disease.Name %in% subset.disease, ]
}
genes <- unique( tbl$GeneSymbol )
tbl[ is.na( tbl[ , field.score ] ), field.score ] <- 0
tbl <- tbl[ tbl[ , field.score ] >= filter.score, ]
tbl$Disease.Name <- vapply( tbl$Disease.Name, function( name ) {
if( nchar( name ) > max.length ) {
paste0( substr( name, 1, 17 ), "..." )
} else {
name
}
}, FUN.VALUE = "character" )
tbl <- data.frame( tbl )[ , c( "Disease.Name", "GeneSymbol", field.score ) ]
diseases <- unique( tbl$Disease.Name )
field.name <- gsub( "\\.", " ", field.score )
tbl[ , field.score ] <- as.numeric( tbl[ , field.score ] )
if( length( diseases ) > 1 ) {
ggplot2::ggplot( data.frame( tbl ),
ggplot2::aes_string( x = "GeneSymbol", y = "Disease.Name" ) ) +
ggplot2::theme_bw() +
ggplot2::geom_tile( ggplot2::aes_string( fill = field.score ) ) +
ggplot2::theme(
axis.text.x = ggplot2::element_text( angle = 90, hjust = 1 ),
axis.ticks = ggplot2::element_blank()
) +
ggplot2::scale_fill_gradient( low = "white", high = "steelblue",
name = field.name ) +
ggplot2::xlab( "" ) + ggplot2::ylab( "" )
} else {
tbl <- tbl[ order( tbl[ , field.score ], decreasing = TRUE ), ]
lbl <- tbl$GeneSymbol[ order( tbl[ , field.score ], decreasing = TRUE ) ]
lbl <- lbl[ !duplicated( lbl ) ]
tbl$GeneSymbol <- factor(tbl$GeneSymbol, levels = lbl )
ggplot2::ggplot( data.frame( tbl ),
ggplot2::aes_string( x = "GeneSymbol", y = field.score ) ) +
ggplot2::theme_bw() +
ggplot2::geom_bar( stat = "identity", fill = "steelblue" ) +
ggplot2::xlab( "" ) + ggplot2::ylab( field.name ) +
ggplot2::theme(
axis.text.x = ggplot2::element_text( angle = 90, hjust = 1 )
)
}
}
|
73f0b08754d99bbff51e1b0d037a2a00bd0244d8
|
b1af2ace3c7cf3c33fe84dc6f13ffbe83bbc041a
|
/man/EstradaIndex.Rd
|
09f4619d4c9ec522fb8c8a3bad23c603b2cfa2b2
|
[] |
no_license
|
cran/ldstatsHD
|
737211c8abae70e12ca02ab7e4840c41613a1f3b
|
3509aefd07784db9b29eea2e6f91ca4ac1f6c8cc
|
refs/heads/master
| 2020-12-08T01:56:14.161645
| 2017-08-14T09:52:13
| 2017-08-14T09:52:13
| 66,004,317
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,202
|
rd
|
EstradaIndex.Rd
|
\name{estradaIndex}
\alias{estradaIndex}
\title{
Estrada Index of a graph structure
}
\description{
Computes the Estrada Index given the adjacency matrix of a graph structure.
}
\usage{
estradaIndex(A)
}
\arguments{
\item{A}{
\code{\link{matrix}} or \code{\link{Matrix}} object with adjacency matrix of a graph.
}
}
\details{
The Estrada Index is calculated by
\deqn{
EE(\lambda) = \sum_{j=1}^p \exp(\gamma_j(\lambda)),
}
where \eqn{\gamma_1(\lambda), \ldots,\gamma_p(\lambda)} are the eigenvalues of \eqn{A_G^\lambda}.
}
\value{
Estrada index coefficient
}
\references{
Estrada, E. (2011). The structure of complex networks. New York: OXFORD University press.
}
\author{
Caballe, Adria <a.caballe@sms.ed.ac.uk>, Natalia Bochkina and Claus Mayer.
}
\seealso{
\code{\link{lambdaSelection}} for lambda selection approaches.\cr
}
\examples{
EX1 <- pcorSimulator(nobs = 50, nclusters=2, nnodesxcluster=c(40,30),
pattern="powerLaw")
y <- EX1$y
out3 <- huge(y, method = "mb", lambda = 0.4)
PATH <- out3$path[[1]]
hm <- estradaIndex(PATH)
}
|
83b92db2b81700e2a74e0e53f8d744d3fb9764bf
|
8bece88332b3ec544c33bb3b487a8fb456293bf3
|
/dataGen/combo coord.R
|
8368f060dc94404937cf8be5d2dfbf38ac8ed8d1
|
[] |
no_license
|
kokbent/intToolLULC
|
aea40c7f6fb19eb82429446b1636d5ce229c9d68
|
cc1fa8f61872d6f606253aa99ddb47c3fcfc3907
|
refs/heads/master
| 2020-03-22T21:57:37.731879
| 2018-07-26T14:37:36
| 2018-07-26T14:37:36
| 140,724,454
| 0
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 367
|
r
|
combo coord.R
|
rm(list=ls(all=TRUE))
# setwd('U:\\independent studies\\interactive tools\\conservation tool')
x=seq(from=0,to=100,by=10)
y=seq(from=0,to=100,by=10)
combo=expand.grid(x1=x,x2=x,x3=x,y1=y,y2=y,y3=y)
dim(combo)
#always going up
cond=combo$y2 >= combo$y1 & combo$y3 >= combo$y2
combo1=combo[cond,]
dim(combo1)
write.csv(combo1,'dataGen/comboCoord2.csv',row.names=F)
|
9b86589504c2bed6b802ada0ce8e2187147bf5b4
|
f8c876df7e8df9a41cf4646746d392ae50707ea4
|
/US/example/primary_iowa_2016/merge_ref_and_ext_2016.R
|
c37004f537440981509900485dc7f26bea30a67b
|
[] |
no_license
|
datamapio/geoid
|
745cffb4908ffe9e7ec5060936b002b81b3a9a01
|
16c368c9f4fd72df3f623390e5e694018476b409
|
refs/heads/master
| 2023-01-21T14:22:32.485076
| 2023-01-19T14:12:36
| 2023-01-19T14:12:36
| 49,221,590
| 10
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,852
|
r
|
merge_ref_and_ext_2016.R
|
## setwd("/Users/rogerfischer/datamap/geoid/US/example/primary_iowa_2016")
## getwd()
## How to merge external result data (EXT) with the geoid reference data (REF)
## ===========================================================================
## The EXT for 2016
## Currently only a template / you can call any file. Ideally it contains fips, because we merge the REF and EXT on fips
fileUrl <- "https://raw.githubusercontent.com/datamapio/geoid/master/US/example/primary_iowa_2016/primary_rep_iowa_county_2016_ext.csv"
download.file(fileUrl, destfile = "ext.csv", method = "curl")
## The REF 2010-2016
## Use "Raw" (=https://raw.githubusercontent.com/...) when downloading the file from Github
## https://github.com/datamapio/geoid/blob/master/US/county/by_state/iowa/iowa_county_2010-2016.csv
fileUrl <- "https://raw.githubusercontent.com/datamapio/geoid/master/US/county/by_state/iowa/iowa_county_2010-2016.csv"
download.file(fileUrl, destfile = "ref.csv", method = "curl")
list.files()
dateDownloaded <- date()
dateDownloaded # "Sat Jan 16 14:13:20 2016"
ext <- read.csv("ext.csv", header = TRUE, sep = ",", stringsAsFactors=FALSE)
ref <- read.csv("ref.csv", header = TRUE, sep = ",", stringsAsFactors=FALSE,
colClasses = c("character", "character", "character", "character",
"character", "character", "character"))
## Merge by fips
data <- merge(ref, ext, by="fips")
## Rearrange and delete unnecessary columns
data <- data[c("id", "county_name", "trump", "cruz", "rubio", "bush", "carson", "christie", "fiorina", "gilmore", "huckabee", "kasich", "santorum", "randpaul", "repnopref", "repother")]
## Create the new CSV file, which has the structure used in the dataviz index file
write.table(data, file="primary_rep_iowa_county_2016.csv", sep="," ,col.names=TRUE, row.names=FALSE)
|
b43c48eca2a7f90ef9223ac123110991c8fe1b09
|
932dba523258a20ba386695ed34a6f91da4688c7
|
/tests/testthat/test-tag_cols.R
|
4ca86615d1441fef97c1512a33c4718566ba6d67
|
[] |
no_license
|
trinker/termco
|
7f4859a548deb59a6dcaee64f76401e5ff616af7
|
aaa460e8a4739474f3f242c6b2a16ea99e1304f5
|
refs/heads/master
| 2022-01-18T23:43:46.230909
| 2022-01-05T19:06:43
| 2022-01-05T19:06:43
| 39,711,923
| 27
| 4
| null | 2018-02-02T05:57:38
| 2015-07-26T03:17:09
|
R
|
UTF-8
|
R
| false
| false
| 237
|
r
|
test-tag_cols.R
|
context("Checking tag_cols")
test_that("tag_cols is a tibble.",{
expect_true(methods::is(tag_cols(markers), 'tbl_df'))
})
test_that("tag_cols gets correct number of columns.",{
expect_true(ncol(tag_cols(markers)) == 4)
})
|
7bbc4cedb84e4b44cbc1c0c7a3a73f4411e3642e
|
f41e5ab3dcb15bd8802f9108bc89674334914603
|
/1-6-19 Mentor qs.R
|
00d03332e73c60ef757c8e39675b30f2b9ab763b
|
[] |
no_license
|
jaredcouncil/Mentor-feedback
|
c99930c7642f82c3510d54785c0956bbaf87d339
|
d33d3cc47593f160df834424e554f5757416cf27
|
refs/heads/master
| 2020-04-15T03:21:31.528223
| 2019-02-25T03:11:10
| 2019-02-25T03:11:10
| 164,345,409
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,824
|
r
|
1-6-19 Mentor qs.R
|
library(dplyr)
library(tidyr)
View(nycflights13::flights)
##### REMOVING NAs #####
# Main question: Is this the best way to filter NAs?
#Want to calculate the average arrival delay (arr_delay) to each destination
nycflights13::flights %>% group_by(dest) %>%
summarise(avg_delay = mean(arr_delay))
#This returned a 105x2 tbl with a lot of NAs
#I added a filter line
nycflights13::flights %>% group_by(dest) %>%
summarise(avg_delay = mean(arr_delay)) %>%
filter(avg_delay != "NA")
#This returned a 5x2 tbl with no NAs.
#So I moved the NA filter up in my code, which seemd to work.
nycflights13::flights %>% group_by(dest) %>%
filter(arr_delay != "NA") %>%
summarise(avg_delay = mean(arr_delay))
#### BUSIEST PLANES ####
#I wanted to figure out which planes (denoted by tailnum)
#had the most flights in 2013 and where they flew. I tried
#two approaches and am curious why each produced the results they did
#Method 1
nycflights13::flights %>%
group_by(tailnum, dest) %>%
summarise(trips = n()) %>%
arrange(-trips) %>%
filter(tailnum != "NA")
#Returned a tbl (44,396 x 3). Busiest plane was N328AA with 313 trips to LAX.
#I wondered why LAX was predominant destination, so I tried different approach
#Method 2 (removed "dest" from group_by)
nycflights13::flights %>%
group_by(carrier, tailnum) %>%
summarise(trips = n(), dest_count = n_distinct(dest)) %>%
arrange(-trips) %>%
filter(tailnum != "NA")
#Returned a tbl (4,060 x 4). Busiest plane was N725MQ with 575 trips to 10 destinations.
#Here are some of the things I'm wondering:
#What exactly is group_by doing to my results?
#Can I be confident that these results are exactly what I'm looking for? (Were MQ airline
#planes really the busiest?)
#When should I filter NAs?
|
7b0db78ce6449ff693dcf903a4696d79c7c6263f
|
9bb201e15d76fd8c376ea119757b9b3435d2c5da
|
/corr.R
|
31142b413f88055ec537b905546ba67cf1e29333
|
[] |
no_license
|
gsnelson/Programming-Assignment-1
|
236fc425c06c7776e0c1b291ff1e03708c32147a
|
91fac2e7a791c5b207766c475c70fcd72a18c293
|
refs/heads/master
| 2022-04-13T20:16:26.718754
| 2020-03-26T03:04:18
| 2020-03-26T03:04:18
| 247,726,908
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 875
|
r
|
corr.R
|
corr <- function(directory, threshold = 0) {
library(dplyr)
path <- file.path(getwd(), directory, fsep = .Platform$file.sep)
results <- numeric()
files <- c(list.files(path , pattern = "csv"))
# print(files)
for (i in files) {
data <-
read.csv(paste(path, .Platform$file.sep, i, sep = ""))
data.f <- filter(data, is.na(sulfate) == FALSE & is.na(nitrate) == FALSE)
good_count <- NROW(data.f)
if (good_count > threshold) {
xcol <- data.f$sulfate
ycol <- data.f$nitrate
correl <- cor(xcol, ycol)
# print(head(correl))
results <- append(results, correl, after = length(results))
}
}
return(results)
}
cr <- corr("specdata")
cr <- sort(cr)
RNGversion("3.5.1")
set.seed(868)
out <- round(cr[sample(length(cr), 5)], 4)
print(out)
|
008253c0918191704580326ce198b2a4514817bf
|
17fbc45992775680e922f5f9525ae99b9b02f3f1
|
/doc/KjorefilBeredsk.R
|
3715fc3be58cf83671f96d266c20a6f0b69b5cb1
|
[
"MIT"
] |
permissive
|
Rapporteket/intensivberedskap
|
d078c048b384f60fb0cbf3c22bce8e8da6f94d2d
|
9f5e97104e0560c4941e0e8f90f929eed5f2bea8
|
refs/heads/rel
| 2023-06-24T00:26:39.078883
| 2023-06-16T14:45:32
| 2023-06-16T14:45:32
| 246,884,430
| 0
| 0
|
NOASSERTION
| 2022-03-09T15:34:51
| 2020-03-12T16:43:37
|
R
|
UTF-8
|
R
| false
| false
| 13,849
|
r
|
KjorefilBeredsk.R
|
#Husk neste gang oppdaterer pakken intensiv:
#Felles preprosessfil, felles hentSamlerapport (Rpakke som innparameter)
CoroDataRaa <- NIRberedskDataSQL(kobleInt = 0)
CoroData <- NIRPreprosessBeredsk(RegData = CoroDataRaa, aggPers = 1, tellFlereForlop = 1)
ind2 <- grep('_2', CoroData$PasientID) #[1] 1318 1988
pas <- CoroData$PersonId[ind2]
CoroDataRaa[CoroDataRaa$PersonId %in% pas, c('PersonId', 'FormDate')]
CoroData[CoroData$PersonId %in% pas, c('PersonId', 'FormDate', 'PasientID')]
BeredIntRaa[BeredIntRaa$PersonId %in% pas, c('PersonId', 'FormDate', 'AgeAdmitted')]
pasUint <- unique(BeredIntRaa$PersonId[is.na(BeredIntRaa$PatientInRegistryGuidInt)])
pas %in% pasUint
BeredIntPas <- NIRPreprosessBeredsk(RegData = BeredIntRaa, kobleInt = 1, aggPers = 1, tellFlereForlop = 1)
BeredIntPas[BeredIntPas$PersonId %in% pas, c('PersonId', 'FormDate', 'PasientID')]
#Konklusjon: Begge forløp mangler intensivskjema. OK!
library(knitr)
library(intensivberedskap)
# CoroData <- read.table('C:/ResultattjenesteGIT/ReadinessFormDataContract2020-03-18.csv', sep=';',
# stringsAsFactors=FALSE, header=T, encoding = 'UTF-8')
#CoroData <- NIRberedskDataSQL()
# valgtRHF <- 'Alle'
# valgtRHF <- as.character(NIRPreprosessBeredsk(NIRberedskDataSQL())$RHF[3])
# 9.jan. 2022: Endrer til parametre reshID og enhetsNivaa
reshID <- 107717 #700720 #107717 #
enhetsNivaa <- 'HF'
#setwd('C:/ResultattjenesteGIT/intensivberedskap/')
#knit('C:/ResultattjenesteGIT/intensivberedskap/inst/BeredskapCorona.Rnw', encoding = 'UTF-8')
#tools::texi2pdf(file='BeredskapCorona.tex')
#knitr::knit('~/intensivberedskap/inst/BeredskapCorona.Rnw') #, encoding = 'UTF-8')
knitr::knit2pdf('~/intensivberedskap/inst/BeredskapCorona.Rnw') #, encoding = 'UTF-8')
#CoroData <- read.table('C:/ResultattjenesteGIT/ReadinessFormDataContract2020-03-18.csv', sep=';',
# stringsAsFactors=FALSE, header=T, encoding = 'UTF-8')
library(intensivberedskap)
library(korona)
Datafiler <- korona::lagDatafilerTilFHI()
PanPp <- Datafiler$PandemiDataPpFHI
BerPp <- Datafiler$BeredskapDataPpFHI
table(table(PanPp$PersonIdBC19Hash))
table(table(BerPp$PersonIdBC19Hash))
#Gir 108
KoronaRaa <- korona::KoronaDataSQL()
KoronaPp <- KoronaPreprosesser(RegData= KoronaRaa, aggPers = 1, tellFlereForlop = 1)
ind <- names(table(KoronaPp$PersonId)[which(table(KoronaPp$PersonId)>1)])
test <- KoronaPp[KoronaPp$PersonId %in% ind, ]
#underveis:
length(grep('_2',RegData$PasientID)) #117 Hvorfor da bare 108 PersonID??? Fordi det kan være flere opphold også i 2.forløp! SJEKK!!!
length(unique(RegData$PasientID[grep('_2',RegData$PasientID)]))
sum(table(RegDataRed$PersonId)>1) #108
length(unique(RegData$PasientID))
length(unique(RegData$PersonId))
length(unique(KoronaRaa$PatientInRegistryGuid))
length(unique(KoronaRaa$PersonId))
#Gir 117
KoronaRaa$Dato <- as.Date(KoronaRaa$FormDate)
PasFlere <- KoronaRaa %>% group_by(PatientInRegistryGuid) %>%
dplyr::summarise(.groups = 'drop',
InnNr0 = ifelse(Dato-min(Dato)>90, 2, 1))
antPasFlereForlAlle <- sum(PasFlere$InnNr0>1)
table(PasFlere$InnNr0)
RegDataRaa <- NIRberedskDataSQL(kobleInt = 1)
RegData <- NIRPreprosessBeredsk(RegDataRaa, kobleInt = 1)
CoroDataRaa <- NIRberedskDataSQL(kobleInt = 0)
CoroData <- NIRPreprosessBeredsk(RegData = CoroDataRaa)
test <- CoroDataRaa[CoroDataRaa$PatientInRegistryGuid == "4442C54B-848C-EB11-A970-00155D0B4E21", ]
first(test$CreationDate, order_by = test$FormDate)
ReinnNaar = max(which(difftime(sort(test$FormDate)[2:2],
test$DateDischargedIntensive[order(test$FormDate)][1],
units = 'hours') > 12))+1
ReinnNaar = ifelse(Reinn==0 , 1,
ifelse(sum(is.na(test$DateDischargedIntensive))>0,
max(which(difftime(sort(FormDate)[2:AntRegPrPas],
DateDischargedIntensive[order(FormDate)][1:(AntRegPrPas-1)],
units = 'hours') > 12))+1))
test <- CoroData[!is.na(CoroData$EcmoStart) & CoroData$RHF=='Vest',
c("RHF", 'HF',"ShNavn",'HFut', "ShNavnUt", "FormStatus", "FormDate", "DateDischargedIntensive")]
first(RegData$CreationDate, order_by = RegData$FormDate)
unique(RegData[ ,c('ReshId', 'ShNavn')])
RegDataOpph <- NIRPreprosessBeredsk(RegData = NIRberedskDataSQL(), aggPers = 0)
tab <- tabRegForsinkelse(RegData=RegDataOpph, pst = 0) #datoFra='2020-03-01', datoTil=Sys.Date())
table(table(RegDataRaa$PatientInRegistryGuid))
table(RegData$ReinnNaar)
table(RegData$ReinnNaarTest)
pasFeil <- 'E6C9B5FD-661F-EB11-A96D-00155D0B4D16'
pas <- c(RegData$PasientID[RegData$Reinn==1], pasFeil)
testRaa <- RegDataRaa[which(RegDataRaa$PatientInRegistryGuid %in% pas), ]
testPp <- RegData[which(RegData$PasientID %in% pas), ]
table(testRaa$PatientInRegistryGuid)
testRaa[order(testRaa$PatientInRegistryGuid, testRaa$FormDate),
c("PatientInRegistryGuid", "FormDate", "DateDischargedIntensive", "FormStatus")]
AntRegPrPas <- 2
ReinnNaar <- max(which(ReshId[order(test$FormDate)][2:AntRegPrPas] ==
ReshId[order(FormDate)][1:AntRegPrPas-1]))+1
CoroData <- NIRberedskDataSQL(kobleInt = 1)
RegData <- NIRPreprosessBeredsk(RegData = CoroData, kobleInt = 1)
CoroSjekk <- CoroData[which(CoroData$PatientInRegistryGuid == "C47F1C66-2F11-EB11-A96D-00155D0B4D16"),
c("DateAdmittedIntensive", "DateDischargedIntensive", 'FormDate',
"PatientInRegistryGuidInt", "PersonId")]
BeredDataRaa[which(BeredDataRaa$PatientInRegistryGuid == "C47F1C66-2F11-EB11-A96D-00155D0B4D16"),
c("DateAdmittedIntensive", "DateDischargedIntensive", 'FormDate',
"PersonId")]
IntDataRaa[which(IntDataRaa$PatientInRegistryGuid == "C47F1C66-2F11-EB11-A96D-00155D0B4D16"),
c("DateAdmittedIntensive", "DateDischargedIntensive", 'FormDate', "PersonId")]
PersonId <- '0x2EE6AD0CF8F2F06EC10EAD46C08B2FA5F965C63215A332A2E0707ABDF9E5A33E'
RegData$PersonId==PersonId
which(RegData$PersonId[is.na(RegData$PatientInRegistryGuidInt)]== PersonId)
RegData$PatientInRegistryGuid[21]
RegData <- CoroData
RegData[which(RegData$PatientInRegistryGuid == "C47F1C66-2F11-EB11-A96D-00155D0B4D16"),
c("DateAdmittedIntensive", "DateDischargedIntensive", 'FormDate', "PatientInRegistryGuidInt")]
as.data.frame(RegDataRed[RegDataRed$PasientID == "C47F1C66-2F11-EB11-A96D-00155D0B4D16", ])
IntDataRaa[IntDataRaa$PatientInRegistryGuid == "C47F1C66-2F11-EB11-A96D-00155D0B4D16",
c("DateAdmittedIntensive", "DateDischargedIntensive", 'FormDate')]
RegData <- NIRPreprosessBeredsk(RegData <- CoroData)
RegData[which(is.na(RegData$DateDischargedIntensive) & RegData$ShNavn == 'Lovisenberg'), ]
data <- RegData[(RegData$Reinn==1) | (RegData$ReinnGml==1) ,c("PasientID", "ShNavn", "ShNavnUt", "FormDate", "DateDischargedIntensive", "Reinn", "ReinnGml", "ReinnNaar", "ReinnTid")]
pas <- RegData$PasientID[RegData$Reinn==1 | RegData$ReinnGml==1]
dataRaa <- CoroData[CoroData$PatientInRegistryGuid %in% pas ,c("PatientInRegistryGuid", "FormDate", "HelseenhetKortnavn", "DateDischargedIntensive")]
dataRaa <- dataRaa[order(dataRaa$PatientInRegistryGuid, dataRaa$FormDate), ]
data <- NIRUtvalgBeredsk(RegData=RegData, datoTil = '2020-04-01')$RegData
inneliggere <- is.na(data$DateDischargedIntensive)
inne <- sum(inneliggere)
range(data$Liggetid, na.rm = T)
data[inneliggere, c('FormDate', "PasientID", "ShNavnUt")]
pas <- data$PasientID[inneliggere]
sjekkSkjema <- CoroData[which(CoroData$PatientInRegistryGuid %in% pas),
c("HelseenhetKortnavn", 'PatientInRegistryGuid', "FormDate", "DateDischargedIntensive","SkjemaGUID")]
sjekkSkjema[order(sjekkSkjema$HelseenhetKortnavn, sjekkSkjema$PatientInRegistryGuid, sjekkSkjema$FormDate),]
# sjekkSkjema <- CoroData[which(is.na(CoroData$DateDischargedIntensive) & as.Date(CoroData$FormDate)<'2020-04-01'),
# c("HelseenhetKortnavn","PatientInRegistryGuid", "FormDate", "SkjemaGUID")]
# sjekkSkjema[order(sjekkSkjema$HelseenhetKortnavn, sjekkSkjema$PatientInRegistryGuid, sjekkSkjema$FormDate),]
bekr <- RegData$Bekreftet==1
min(RegData$FormDate[inneliggere & bekr], na.rm=T)
min(RegData$FormDate, na.rm=T)
test <- RegData[inneliggere & bekr, ]
sort(RegData$RespReinnTid)
pas <- RegData$PasientID[which(RegData$ReinnTid > 25)] #ReinnTid< -10 =dobbeltregistrering
RegData$AntRegPas[which(RegData$PasientID %in% pas)]
data <- CoroData[which(CoroData$PatientInRegistryGuid %in% pas), ]
data[order(data$PatientInRegistryGuid, data$DateAdmittedIntensive),]
Data <- RegData[!(is.na(RegData$DateDischargedIntensive)), c("FormStatus", "Bekreftet")]
minald <- 0
maxald <- 110
reshID=0
erMann=0
bekr=9
skjemastatus=9
dodInt=9
valgtRHF <-RegData$RHF[3] #'Alle' #
valgtRHF <- 'Alle'
valgtRHF <- 'Nord'
tidsenhet='dag'
reshID <- 102090
library(tidyverse)
#risikofaktorer per aldersgruppe
RegData <- NIRberedskDataSQL()
RegData <- NIRPreprosessBeredsk()
RegData <- NIRUtvalgBeredsk(RegData = RegData, bekr = 1)$RegData
gr <- c(0, 30,40,50,60,70,80) #seq(30, 90, 10))
#--------------------Overføringer-------------------------
library(intensivberedskap)
library(tidyverse)
library(lubridate)
RegData <- NIRberedskDataSQL()
RegData <- NIRPreprosessBeredsk(RegData)
Nopph <- dim(RegData)[1]
Npas <- length(unique(RegData$PasientID))
AntOpphPas <- table(RegData$PasientID)
AntOpphPas[AntOpphPas>1]
EkstraOpph <- Nopph-Npas
#Eksempel på bruk av gruppering I dplyr (tidyverse).
library(tidyverse)
#Kan slå sammen hver enkelt variabel:
tmp <- RegData %>% group_by(PasientID) %>% summarise(mindato = min(InnDato), maxdato = max(InnDato), N=n())
#Jeg lagde forresten denne lille snutten for å ramse opp variablene som har mer enn 1 verdi på samme pasientID:
lengde_unik <- function(x){length(unique(x))}
aux <- RegData %>% group_by(PasientID) %>% summarise_all(lengde_unik)
names(colSums(aux[, -1])[colSums(aux[, -1]) > dim(aux)[1]])
library(intensivberedskap)
library(lubridate)
library(tidyverse)
RegData <- NIRberedskDataSQL()
test <- RegData[3:4,
c("MechanicalRespiratorStart", "MechanicalRespiratorEnd")]
Ut <-
#RegData$PatientInRegistryGuid %in% c('013F0C5E-7B6E-EA11-A96B-00155D0B4F09','03254625-EF73-EA11-A96B-00155D0B4F09'),
min(test[2:4])
RegData$Tid <- factor(format(RegData$FormDate, "%Y-%m-%d %H:%M:%S"),
levels = format(seq(min(RegData$FormDate), max(RegData$FormDate), by="min"), "%Y-%m-%d %H:%M:%S"))
min(RegData$Tid)
RegData$Innleggelsestidspunkt <- as.POSIXlt(RegData$FormDate, tz= 'UTC',
format="%Y-%m-%d %H:%M:%S" )
sort(RegData$Innleggelsestidspunkt)
RegDataRed <- RegData %>% group_by(PatientInRegistryGuid) %>%
summarise(sort(DateDischargedIntensive)[1])
testData <- NIRberedskDataSQL()
RegDataRed <- testData %>% group_by(PatientInRegistryGuid) %>%
summarise(min(format.Date(DateDischargedIntensive, tz='UTC'), na.rm = T))
summarise(DateDischargedIntensive = max(ymd_hms(DateDischargedIntensive), na.rm = T))
RegData <- NIRberedskDataSQL()
antPer <- table(RegData$PatientInRegistryGuid)
PID <- names(antPer[antPer==2])
test <- RegData[RegData$PatientInRegistryGuid %in% PID,
c('PatientInRegistryGuid', 'FormDate',"DateDischargedIntensive",
"MechanicalRespiratorStart", "MechanicalRespiratorEnd", 'AgeAdmitted')]
#------------------Sjekk beregning antall inneliggende---------------------------------
#Benytter aggregerte data ved beregning. Kan få avvik når personer er ute av intensiv og tilbake
library(intensivberedskap)
library(tidyverse)
CoroDataRaa <- NIRberedskDataSQL()
CoroDataRaa$HovedskjemaGUID <- toupper(CoroDataRaa$HovedskjemaGUID)
CoroData <- NIRPreprosessBeredsk(RegData = CoroDataRaa)
CoroData$UtDato <- as.Date(CoroData$DateDischargedIntensive, tz= 'UTC', format="%Y-%m-%d")
sum(is.na(CoroData$UtDato)) #Ingen variabel som heter UtDato...
#Evt. hent data koblet med intensivdata
# erInneliggende1 <- function(datoer, regdata){
# auxfunc <- function(x) {
# (x > regdata$InnDato & x <= regdata$UtDato) | (x > regdata$InnDato & is.na( regdata$UtDato))}
# map_df(datoer, auxfunc)
# }
erInneliggende <- function(datoer, regdata){
auxfunc <- function(x) {
x > regdata$InnDato & ((x <= regdata$UtDato) | is.na(regdata$UtDato))}
map_df(datoer, auxfunc)
}
erInneliggendeMut <- function(datoer, regdata){
regdata <- regdata[!is.na(regdata$UtDato),]
auxfunc <- function(x) {
(x > regdata$InnDato) & (x <= regdata$UtDato)}
map_df(datoer, auxfunc)
}
datoer <- seq(as.Date('2020-03-01', tz= 'UTC', format="%Y-%m-%d"), Sys.Date(), by="day")
names(datoer) <- format(datoer, '%Y-%m-%d') #'%d.%B')
aux <- erInneliggende(datoer = datoer, regdata = CoroData)
auxUt <- erInneliggendeMut(datoer = datoer, regdata = CoroData)
inneliggende <- t(rbind(Dato = names(datoer),
Inneliggende = colSums(aux),
InneliggendeMut = colSums(auxUt)))
write.table(inneliggende, file = 'data-raw/inneliggende.csv', sep = ';', row.names = F, fileEncoding = 'UTF-8')
#Diagnosis
# -1 = Velg verdi
# 100 = Påvist SARS-CoV-2
# 101 = Påvist SARS-CoV-2 med pneumoni
# 102 = Påvist SARS-CoV-2 med annen luftveissykdom
# 103 = Påvist SARS-CoV-2 med annen organmanifestasjon
# 104 = Mistenkt SARS-CoV-2
# 105 = Mistenkt SARS-CoV-2 med pneumoni
# 106 = Mistenkt SARS-CoV-2 med annen luftveissykdom
# 107 = Mistenkt SARS-CoV-2 med annen organmanifestasjon
#"Når ein opprettar eit Coronaskjema har ein per def. Mistanke om Corona. Vi meiner difor at skjema med verdi -1 også bør tellast med som mistenkt Corona." Antar dette også gjelder Corona.
|
3dbdd299c986bd2aa9dcb8d599d6c50bbeb57426
|
f10d371c75a093928fb95334fd9bbffa41630187
|
/Task_09/task09.r
|
ac8cee21d1eb04d1df88370d3f694da236b0a0e1
|
[] |
no_license
|
kes0042/Tasks
|
5fd49790c85091572cfdcef040e8cc30d75b2e49
|
0022572b7b24490b3dc389f662e1ab14c9c7ec00
|
refs/heads/master
| 2023-04-18T04:13:55.483361
| 2021-04-30T14:55:27
| 2021-04-30T14:55:27
| 331,984,011
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,220
|
r
|
task09.r
|
setwd("~/Desktop/Evolution/Tasks/Task_09")
library(phytools)
tsetwd('~/Desktop/Evolution/Tasks/Task_09')
library('phytools')
trees <- list()
births <- c()
Fractions <- c()
for(i in 1:100) {
births[i] <- runif(1)
Fractions[i] <- runif(1)
trees[[i]] <- pbtree(b = births[i], d = (births[i] * Fractions[i]), n = 100, nsim = 1)
}
trees
trees[[i]]
plot(trees[[i]])
install.packages('geiger')
library('geiger')
#QUESTION 4
install.packages('TreeTools')
yes
library('TreeTools')
Y
tips <- sapply(trees, NTip)
logtips <- log(tips)
diversification <- sapply(trees, bd.ms)
plot(diversification, logtips, xlab='net diversification', ylab='log of total number of tips')
abline(lm(diversification~logtips), col='red')
#There is a strong positive correlation between diversification and the number of tips
cor(diversification, logtips)
#positive correlation
#QUESTION 5
speciation <- sapply(trees, bd.km)
#for (t in 1:length(trees)) {
i <- 1
numtips <- c()
avgBL <- c()
for ( i in 1:length(trees)) {
# choose tree
y <- trees[[i]]
# find number of tips
numtips[i] <- Ntip(y)
# find average branch length
avgBL[i] <- mean(y$edge.length)
}
plot(speciation, avgBL, xlab='speciation rate', ylab='average branch length')
# the branch length is inversely proportional to speciation rate
#Question 6
cor(speciation, avgBL)
#correlation = -0.25
#Question 7
which.max(tips)
bigTree <- trees[[66]]
plot(bigTree)
rates <- c()
traits <- list()
for (i in 1:100) {
rates[i] <- runif(1)
traits[[i]] <- fastBM(tree = bigTree, sig2 = rates[i])
}
#Question 8
avgtrait <- sapply(traits, mean)
avgtrait
avgrate <- sapply(rates, mean)
avgrate
correlation <- cor(avgtrait, avgrate)
print(correlation)
plot(avgrate, avgtrait)
abline(lm(avgrate~avgtrait), col='purple')
#0.09 correlation in the simulation
#Question 9
vartraits <- sapply(traits, var)
cor(vartraits, rates)
#There is a positive correlation between rates and variance of traits.
#Question 10
trait1 <- traits[1]
trait1
trait2 <- traits[2]
trait2
traitmat <- cbind(traits[[1]], traits[[2]])
traitmat
var(traitmat)
cor(traitmat[,1], traitmat[,2])
#The correlation is around 0 which isn't significant
plot(traitmat[,1], traitmat[,2])
abline(lm(traitmat[,1]~traitmat[,2]), col='pink')
|
5e9972aeb36e0c0999b44762b6f0210380f2cc97
|
542922cee73ded319ff7052b298a48d654fe1e9e
|
/man/allele_table.Rd
|
38d1fdea4315237c35addeed9924cc51ab470391
|
[] |
no_license
|
gschofl/hlatools
|
8cdb3df9910ace8bba58c80080fd0801f018e891
|
a18aedeb47ae31274fee55f0d1c119bb11dfa49f
|
refs/heads/master
| 2021-08-09T01:03:34.298096
| 2021-07-01T13:37:34
| 2021-07-01T13:37:34
| 51,740,578
| 4
| 3
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,129
|
rd
|
allele_table.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/code_tables.R
\name{allele_table}
\alias{allele_table}
\title{Class: allele_tbl}
\source{
\href{https://www.hla.alleles.org/wmda}{hla.alleles.org}.
}
\usage{
allele_table(db_path = getOption("hlatools.local_repos"), remote = FALSE)
}
\arguments{
\item{db_path}{<\link{character}>; location of local IPD-IMGT/HLA repository.}
\item{remote}{<\link{logical}>; if \code{TRUE} pull data from \href{https://www.hla.alleles.org/wmda}{hla.alleles.org},
if \code{FALSE} retrieve data from \code{db_path}.}
}
\value{
A \link{tibble} with the fields:
\itemize{
\item "gene": The HLA gene.
\item "allele_name": HLA Allele name.
\item "date_assigned": Date assigned.
\item "date_deleted": Date deleted, if the name has now been abandoned or \code{NA}.
\item "identical_to": Allele that the deleted allele was shown to be identical to.
\item "reason_for_deletion": Reason for the Allele to be deleted.
}
}
\description{
Constructor for a <\code{allele_tbl}> object.
}
\examples{
\dontrun{
a_tbl <- allele_table()
}
}
\seealso{
\link{nmdp_table}, \link{g_table}
}
|
24bdc1260b0e940e6fffebe532734e599db6303a
|
6cc8e2e57cc6f906bc64f8394c6683dc0d614918
|
/R/L_bound.R
|
2b0853f919cba6026bbef536149170beb8d837d1
|
[] |
no_license
|
cran/mgcViz
|
cf3f445892ad2954e8ca06dec808cc551bd012d4
|
de825975b97a2f6a020b84f8f6d30b06bca65c60
|
refs/heads/master
| 2021-11-01T08:37:43.917586
| 2021-10-05T06:10:12
| 2021-10-05T06:10:12
| 145,894,342
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 949
|
r
|
L_bound.R
|
#'
#' Add boundaries to smooth effect plot
#'
#' @description This layer adds boundaries to a smooth effect plot.
#'
#' @param n number of discrete intervals along the boundary.
#' @param ... graphical arguments to be passed to \code{ggplot2::geom_path}.
#' @return An object of class \code{gamLayer}.
#' @seealso [plot.sos.smooth]
#' @export l_bound
#'
l_bound <- function(n = 200, ...){
arg <- list(...)
arg$xtra <- list("n" = n)
o <- structure(list("fun" = "l_bound",
"arg" = arg),
class = c("gamLayer"))
return(o)
}
######## Internal method
#' @noRd
l_bound.sos0 <- function(a){
n <- a$xtra$n
a$xtra <- NULL
theta <- seq(-pi/2, pi/2, length = n)
x <- sin(theta)
y <- cos(theta)
a$data <- data.frame("x" = c(x, rev(x)), "y" = c(y, -rev(y)))
a$inherit.aes <- FALSE
a$mapping <- aes(x = x, y = y)
fun <- "geom_path"
out <- do.call(fun, a)
return( out )
}
|
f431fdc9434737c66db00f3604acd4c5bdc47458
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/brms/examples/predict.brmsfit.Rd.R
|
8a9b1b38f49ed917becd51eb54ced44659010316
|
[] |
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
| 821
|
r
|
predict.brmsfit.Rd.R
|
library(brms)
### Name: predict.brmsfit
### Title: Model Predictions of 'brmsfit' Objects
### Aliases: predict.brmsfit posterior_predict.brmsfit posterior_predict
### ** Examples
## Not run:
##D ## fit a model
##D fit <- brm(time | cens(censored) ~ age + sex + (1+age||patient),
##D data = kidney, family = "exponential", inits = "0")
##D
##D ## predicted responses
##D pp <- predict(fit)
##D head(pp)
##D
##D ## predicted responses excluding the group-level effect of age
##D pp2 <- predict(fit, re_formula = ~ (1|patient))
##D head(pp2)
##D
##D ## predicted responses of patient 1 for new data
##D newdata <- data.frame(sex = factor(c("male", "female")),
##D age = c(20, 50),
##D patient = c(1, 1))
##D predict(fit, newdata = newdata)
## End(Not run)
|
d707880ddd445b7fb4f9f257ac4c0fa8a8f0bebe
|
155a8f96920b68d625a73c5d8680a994b31292f4
|
/ToolkitSDP_Analyze.R
|
3fba26252d0e3c48c99fe7cd10b5951dbdd7acc8
|
[
"MIT"
] |
permissive
|
snowdj/college-going-toolkit-r
|
420755d07acf7f060f5d9535aac1278c51088e3b
|
54aa753c7fa70c26782cac95d8bbfa7834c3e6fe
|
refs/heads/master
| 2020-12-02T00:20:46.220954
| 2018-04-19T20:38:05
| 2018-04-19T20:38:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 89,533
|
r
|
ToolkitSDP_Analyze.R
|
## ----knitrSetup, echo=FALSE, error=FALSE, message=FALSE, warning=FALSE, comment=NA----
# Set options for knitr
library(knitr)
knitr::opts_chunk$set(comment=NA, warning=FALSE, echo=TRUE,
error=FALSE, message=FALSE, fig.align='center',
fig.width=8, fig.height=6, dpi = 144,
fig.path = "figure/Analyze_")
options(width=80)
## ----preliminaries-------------------------------------------------------
library(tidyverse) # main suite of R packages to ease data analysis
library(magrittr) # allows for some easier pipelines of data
# Read in some R functions that are convenience wrappers
source("R/functions.R")
library(haven) # required for importing .dta files
# Read in global variables for sample restriction
# Agency name
agency_name <- "Agency"
# Ninth grade cohorts you can observe persisting to the second year of college
chrt_ninth_begin_persist_yr2 = 2005
chrt_ninth_end_persist_yr2 = 2005
# Ninth grade cohorts you can observe graduating high school on time
chrt_ninth_begin_grad = 2005
chrt_ninth_end_grad = 2006
# Ninth grade cohorts you can observe graduating high school one year late
chrt_ninth_begin_grad_late = 2005
chrt_ninth_end_grad_late = 2005
# High school graduation cohorts you can observe enrolling in college the
# fall after graduation
chrt_grad_begin = 2008
chrt_grad_end = 2009
# High school graduation cohorts you can observe enrolling in college
# two years after hs graduation
chrt_grad_begin_delayed = 2008
chrt_grad_end_delayed = 2008
# In RStudio these variables will appear in the Environment pane under "Values"
## ----loadCGdataAttainment------------------------------------------------
# Step 1: Load the college-going analysis file into Stata
# library(haven) # commented out, we've already read it in above
# To read data from a zip file and unzip it in R we can
# create a connection to the path of the zip file
tmpfileName <- "analysis/CG_Analysis.dta"
# This assumes analysis is a subfolder from where the file is read, in this
# case inside the zipfile
con <- unz(description = "data/analysis.zip", filename = tmpfileName,
open = "rb")
# The zipfile is located in the subdirectory data, called analysis.zip
cgdata <- read_stata(con) # read data in the data subdirectory
close(con) # close the connection to the zip file, keeps data in memory
## ----Remindersetglobals--------------------------------------------------
# Step 2: Read in global variables if you have not already done so
# Ninth grade cohorts you can observe persisting to the second year of college
chrt_ninth_begin_persist_yr2 = 2005
chrt_ninth_end_persist_yr2 = 2005
# Ninth grade cohorts you can observe graduating high school on time
chrt_ninth_begin_grad = 2005
chrt_ninth_end_grad = 2006
# Ninth grade cohorts you can observe graduating high school one year late
chrt_ninth_begin_grad_late = 2005
chrt_ninth_end_grad_late = 2005
# High school graduation cohorts you can observe enrolling in college the
# fall after graduation
chrt_grad_begin = 2008
chrt_grad_end = 2009
# High school graduation cohorts you can observe enrolling in college
# two years after hs graduation
chrt_grad_begin_delayed = 2008
chrt_grad_end_delayed = 2008
# In RStudio these variables will appear in the Environment pane under "Values"
## ----A1filterCalculate---------------------------------------------------
# Step 3: Keep students in ninth grade cohorts you can observe persisting to the
# second year of college
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_persist_yr2 &
chrt_ninth <= chrt_ninth_end_persist_yr2)
# Step 4: Create variables for the outcomes "regular diploma recipients",
# "seamless transitioners" and "second year persisters"
plotdf$grad <- ifelse(!is.na(plotdf$chrt_grad) & plotdf$ontime_grad ==1, 1, 0)
plotdf$seamless_transitioners_any <- as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$ontime_grad == 1)
plotdf$second_year_persisters = as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$enrl_1oct_ninth_yr2_any == 1 &
plotdf$ontime_grad == 1)
# // Step 4: Create agency-level average outcomes
# // 2. Calculate the mean of each outcome variable by agency
agencyData <- plotdf %>%
summarize(grad = mean(grad),
seamless_transitioners_any = mean(seamless_transitioners_any, na.rm=TRUE),
second_year_persisters = mean(second_year_persisters, na.rm=TRUE),
N = n())
agencyData$school_name <- "AGENCY AVERAGE"
# // 2. Calculate the mean of each outcome variable by first high school attended
schoolData <- plotdf %>% group_by(first_hs_name) %>%
summarize(grad = mean(grad),
seamless_transitioners_any = mean(seamless_transitioners_any,
na.rm=TRUE),
second_year_persisters = mean(second_year_persisters, na.rm=TRUE),
N = n())
# // 1. Create a variable school_name that takes on the value of students’ first
## high school attended
names(schoolData)[1] <- "school_name"
# // 3. Identify the agency maximum values for each of the three outcome variables
maxSchool <- schoolData %>% summarize_all(.funs = funs("max"))
maxSchool$school_name <- "AGENCY MAX HS"
# // 4. Identify the agency minimum values for each of the three outcome variables
minSchool <- schoolData %>% summarize_all(.funs = funs("min"))
minSchool$school_name <- "AGENCY MIN HS"
# // 5. Append the three tempfiles to the school-level file loaded into R
schoolData <- bind_rows(schoolData, agencyData,
minSchool, maxSchool)
rm(agencyData, minSchool, maxSchool)
## ----A1tidydata----------------------------------------------------------
# // Step 6: Prepare to graph the results
library(tidyr)
schoolData$cohort <- 1
schoolData <- schoolData %>% gather(key = outcome,
value = measure, -N, -school_name)
schoolData$subset <- grepl("AGENCY", schoolData$school_name)
library(ggplot2)
library(scales)
schoolData$outcome[schoolData$outcome == "cohort"] <- "Ninth Graders"
schoolData$outcome[schoolData$outcome == "grad"] <- "On-time Graduates"
schoolData$outcome[schoolData$outcome == "seameless_transitioners_any"] <-
"Seamless College Transitioner"
schoolData$outcome[schoolData$outcome == "second_year_persisters"] <-
"Second Year Persisters"
## ----A1graph-------------------------------------------------------------
## // Step 7: Graph the results
ggplot(schoolData[schoolData$subset,],
aes(x = outcome, y = measure, group = school_name,
color = school_name, linetype = school_name)) +
geom_line(size = 1.1) + geom_point(aes(group = 1), color = I("black")) +
geom_text(aes(label = round(measure * 100, 1)), vjust = -0.8, hjust = -0.25,
color = I("black")) +
scale_y_continuous(limits = c(0, 1), label = percent) +
theme_bw() + theme(legend.position = c(0.825, 0.825)) +
guides(color = guide_legend("", keywidth = 6,
label.theme = element_text(face = "bold",
size = 8,
angle = 0)),
linetype = "none") +
labs(y = "Percent of Ninth Graders",
title = "Student Progression from 9th Grade Through College",
subtitle = "Agency Average", x = "",
caption = paste0("Sample: 2004-2005 Agency first-time ninth graders. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."))
## ----A2filterCalculate---------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe persisting to
## the second year of college
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_persist_yr2 &
chrt_ninth <= chrt_ninth_end_persist_yr2)
# // Step 2: Create variables for the outcomes "regular diploma recipients",
## "seamless transitioners" and "second year persisters"
plotdf$grad <- ifelse(!is.na(plotdf$chrt_grad) & plotdf$ontime_grad ==1, 1, 0)
plotdf$seamless_transitioners_any <- as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$ontime_grad == 1)
plotdf$second_year_persisters = as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$enrl_1oct_ninth_yr2_any == 1 &
plotdf$ontime_grad == 1)
# // Step 3: Create agency-level average outcomes
progressRace <- plotdf %>% group_by(race_ethnicity) %>%
summarize(grad = mean(grad),
seameless_transitioners_any = mean(seamless_transitioners_any, na.rm=TRUE),
second_year_persisters = mean(second_year_persisters, na.rm=TRUE),
N = n())
## ----A2tidyandFormat-----------------------------------------------------
# // Step 4: Reformat the data for plotting
progressRace$cohort <- 1
progressRace <- progressRace %>% gather(key = outcome,
value = measure, -N, -race_ethnicity)
# // Step 5: Recode variables for plot-friendly labels
progressRace$outcome[progressRace$outcome == "cohort"] <- "Ninth Graders"
progressRace$outcome[progressRace$outcome == "grad"] <- "On-time Graduates"
progressRace$outcome[progressRace$outcome == "seameless_transitioners_any"] <-
"Seamless College Transitioner"
progressRace$outcome[progressRace$outcome == "second_year_persisters"] <-
"Second Year Persisters"
progressRace$subset <- ifelse(progressRace$race_ethnicity %in% c(1, 3, 2, 5),
TRUE, FALSE)
progressRace$race_ethnicity[progressRace$race_ethnicity == 1] <- "Black"
progressRace$race_ethnicity[progressRace$race_ethnicity == 2] <- "Asian"
progressRace$race_ethnicity[progressRace$race_ethnicity == 3] <- "Hispanic"
progressRace$race_ethnicity[progressRace$race_ethnicity == 4] <- "Native American"
progressRace$race_ethnicity[progressRace$race_ethnicity == 5] <- "White"
progressRace$race_ethnicity[progressRace$race_ethnicity == 6] <- "Multiple/Other"
progressRace$race_ethnicity <- as.character(zap_labels(progressRace$race_ethnicity))
## ----A2plot--------------------------------------------------------------
# Step 6: Graph the results
ggplot(progressRace[progressRace$subset,],
aes(x = outcome, y = measure, group = race_ethnicity,
color = race_ethnicity, linetype = race_ethnicity)) +
geom_line(size = 1.1) + geom_point(aes(group = 1), color = I("black")) +
geom_text(aes(label = round(measure * 100, 1)), vjust = -0.8, hjust = -0.25,
color = I("black")) +
scale_y_continuous(limits = c(0, 1), label = percent) +
theme_bw() + theme(legend.position = c(0.825, 0.825)) +
guides(color = guide_legend("", keywidth = 6,
label.theme =
element_text(face = "bold", size = 8,
angle = 0)), linetype = "none") +
labs(y = "Percent of Ninth Graders",
title = "Student Progression from 9th Grade Through College",
subtitle = "By Student Race/Ethnicity", x = "",
caption = paste0("Sample: 2004-2005 Agency first-time ninth graders. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."))
## ----A3 filterSample-----------------------------------------------------
## Step 1: Keep students in ninth grade cohorts you can observe persisting to
## the second year of college AND are ever FRPL-eligible
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_persist_yr2 &
chrt_ninth <= chrt_ninth_end_persist_yr2) %>%
filter(frpl_ever > 0)
# // Step 2: Create variables for the outcomes "regular diploma recipients",
## "seamless transitioners" and "second year persisters"
plotdf$grad <- ifelse(!is.na(plotdf$chrt_grad) & plotdf$ontime_grad == 1, 1, 0)
plotdf$seamless_transitioners_any <- ifelse(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$ontime_grad == 1, 1, 0)
plotdf$second_year_persisters = ifelse(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$enrl_1oct_ninth_yr2_any == 1 &
plotdf$ontime_grad == 1, 1, 0)
# // Step 4: Create agency-level average outcomes
# // Calculate the mean of each outcome variable by race/ethnicity
progressRaceFRL <- plotdf %>% group_by(race_ethnicity) %>%
summarize(grad = mean(grad),
seameless_transitioners_any = mean(seamless_transitioners_any, na.rm=TRUE),
second_year_persisters = mean(second_year_persisters, na.rm=TRUE),
N = n())
# // Step 5: Reformat the data file so that one variable contains all the
# outcomes of interest
progressRaceFRL %<>% filter(N >= 20)
## ----A3reshapeRecode-----------------------------------------------------
# // Step 6: Prepare to graph the results
## Reshape the data
progressRaceFRL$cohort <- 1
progressRaceFRL <- progressRaceFRL %>% gather(key = outcome,
value = measure, -N, -race_ethnicity)
## Recode the variables for plot friendly labels
progressRaceFRL$outcome[progressRaceFRL$outcome == "cohort"] <-
"Ninth Graders"
progressRaceFRL$outcome[progressRaceFRL$outcome == "grad"] <-
"On-time Graduates"
progressRaceFRL$outcome[progressRaceFRL$outcome == "seameless_transitioners_any"] <-
"Seamless College Transitioner"
progressRaceFRL$outcome[progressRaceFRL$outcome == "second_year_persisters"] <-
"Second Year Persisters"
progressRaceFRL$subset <- ifelse(progressRaceFRL$race_ethnicity %in% c(1, 3, 5),
TRUE, FALSE)
progressRaceFRL$race_ethnicity[progressRaceFRL$race_ethnicity == 1] <- "Black"
progressRaceFRL$race_ethnicity[progressRaceFRL$race_ethnicity == 2] <- "Asian"
progressRaceFRL$race_ethnicity[progressRaceFRL$race_ethnicity == 3] <- "Hispanic"
progressRaceFRL$race_ethnicity[progressRaceFRL$race_ethnicity == 4] <- "Native American"
progressRaceFRL$race_ethnicity[progressRaceFRL$race_ethnicity == 5] <- "White"
progressRaceFRL$race_ethnicity[progressRaceFRL$race_ethnicity == 6] <- "Multiple/Other"
progressRaceFRL$race_ethnicity <- as.character(zap_labels(progressRaceFRL$race_ethnicity))
## ----A3plot--------------------------------------------------------------
ggplot(progressRaceFRL[progressRaceFRL$subset,],
aes(x = outcome, y = measure, group = race_ethnicity,
color = race_ethnicity, linetype = race_ethnicity)) +
geom_line(size = 1.1) + geom_point(aes(group = 1), color = I("black")) +
geom_text(aes(label = round(measure * 100, 1)), vjust = -0.8, hjust = -0.25,
color = I("black")) +
scale_y_continuous(limits = c(0, 1), label = percent) +
theme_bw() + theme(legend.position = c(0.825, 0.825)) +
guides(color = guide_legend("", keywidth = 6,
label.theme = element_text(face = "bold",
size = 8,
angle = 0)),
linetype = "none") +
labs(y = "Percent of Ninth Graders",
title = "Student Progression from 9th Grade Through College",
subtitle = paste0(c(
"Among Students Qualifying for Free or Reduced Price Lunch \n",
"By Student Race/Ethnicity")),
x = "",
caption = paste0("Sample: 2004-2005 Agency first-time ninth graders. \n",
"Postsecondary enrollment outcomes from NSC matched records.\n",
"All other data from Agency administrative records."))
## ----A4filterAndSortData-------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe persisting
# to the second year of college AND are included in the on-track analysis sample
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_persist_yr2 &
chrt_ninth <= chrt_ninth_end_persist_yr2) %>%
filter(ontrack_sample == 1)
# // Step 2: Create variables for the outcomes "regular diploma recipients",
# "seamless transitioners" and "second year persisters"
plotdf$grad <- ifelse(!is.na(plotdf$chrt_grad) & plotdf$ontime_grad ==1, 1, 0)
plotdf$seamless_transitioners_any <- as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$ontime_grad == 1)
plotdf$second_year_persisters = as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$enrl_1oct_ninth_yr2_any == 1 &
plotdf$ontime_grad == 1)
# // Step 3: Generate on track indicators that take into account students’ GPAs
# upon completion of their first year in high school
plotdf$ot <- NA
plotdf$ot[plotdf$ontrack_endyr1 == 0] <- "Off-Track to Graduate"
# Check for correctness
plotdf$ot[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 < 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track to Graduate, GPA < 3.0"
plotdf$ot[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 >= 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track to Graduate, GPA >= 3.0"
## ----A4reshapeAndFormat--------------------------------------------------
# // Step 4: Calculate aggregates for the Agency by on track status
progressTrack <- plotdf %>% group_by(ot) %>%
summarize(grad = mean(grad),
seameless_transitioners_any = mean(seamless_transitioners_any, na.rm=TRUE),
second_year_persisters = mean(second_year_persisters, na.rm=TRUE),
N = n())
# // Step 5: Reformat the data file so that one variable contains all the outcomes
# of interest
progressTrack$cohort <- 1
progressTrack <- progressTrack %>% gather(key = outcome,
value = measure, -N, -ot)
progressTrack$outcome[progressTrack$outcome == "cohort"] <- "Ninth Graders"
progressTrack$outcome[progressTrack$outcome == "grad"] <- "On-time Graduates"
progressTrack$outcome[progressTrack$outcome == "seameless_transitioners_any"] <-
"Seamless College Transitioner"
progressTrack$outcome[progressTrack$outcome == "second_year_persisters"] <-
"Second Year Persisters"
## ----A4plot--------------------------------------------------------------
# Annotate for direct labels
ann_txt <- data.frame(outcome = rep("Second Year Persisters", 3),
measure = c(0.22, 0.55, 0.85),
textlabel = c("Off-Track \nto Graduate",
"On-Track to Graduate,\n GPA < 3.0",
"On-Track to Graduate,\n GPA >= 3.0"))
ann_txt$ot <- ann_txt$textlabel
ggplot(progressTrack,
aes(x = outcome, y = measure, group = ot,
color = ot, linetype = ot)) +
geom_line(size = 1.1) + geom_point(aes(group = 1), color = I("black")) +
geom_text(aes(label = round(measure * 100, 1)), vjust = -0.8, hjust = -0.25,
color = I("black")) +
geom_text(data = ann_txt, aes(label = textlabel)) +
scale_y_continuous(limits = c(0, 1), label = percent) +
theme_bw() + theme(legend.position = c(0.825, 0.825)) +
scale_color_brewer(type = "qual", palette = 2) +
guides(color = "none",
linetype = "none") +
labs(y = "Percent of Ninth Graders",
title = "Student Progression from 9th Grade Through College",
subtitle = "By Course Credits and GPA after First High School Year", x = "",
caption = paste0("Sample: 2004-2005 Agency first-time ninth graders. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."))
## ----B1filterAndSort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe graduating
# high school on time AND are part of the ontrack sample (attended the first
# semester of ninth grade and never transferred into or out of the system)
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad &
chrt_ninth <= chrt_ninth_end_grad) %>%
filter(ontrack_sample == 1)
# // Step 2: Create variables for the outcomes "regular diploma recipients",
# "seamless transitioners" and "second year persisters"
plotdf$grad <- ifelse(!is.na(plotdf$chrt_grad) & plotdf$ontime_grad ==1, 1, 0)
plotdf$seamless_transitioners_any <- as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$ontime_grad == 1)
plotdf$second_year_persisters = as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$enrl_1oct_ninth_yr2_any == 1 &
plotdf$ontime_grad == 1)
# // Step 3: Generate on track indicators that take into account students’ GPAs
# upon completion of their first year in high school
plotdf$ot <- NA
plotdf$ot[plotdf$ontrack_endyr1 == 0] <- "Off-Track to Graduate"
plotdf$ot[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 < 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track to Graduate, GPA < 3.0"
plotdf$ot[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 >= 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track to Graduate, GPA >= 3.0"
## ----B1reshape-----------------------------------------------------------
# // Step 4: Obtain the agency average for the key variables
# and obtain mean rates for each school and append the agency average
progressBars <- bind_rows(
plotdf %>% group_by(ot) %>% tally() %>% ungroup %>%
mutate(count = sum(n), first_hs_name = "Agency Average"),
plotdf %>% group_by(first_hs_name, ot) %>% tally() %>% ungroup %>%
group_by(first_hs_name) %>%
mutate(count = sum(n))
)
# replace first_hs_name = subinstr(first_hs_name, " High School", "", .)
progressBars$first_hs_name <- gsub(" High School", "", progressBars$first_hs_name)
# // Step 5: For students who are off-track upon completion of their first year
# of high school, convert the values to be negative for ease of
# visualization in the graph
progressBars$n[progressBars$ot == "Off-Track to Graduate"] <-
-progressBars$n[progressBars$ot == "Off-Track to Graduate"]
## ----B1plot--------------------------------------------------------------
# // Step 6: Plot
ggplot(progressBars, aes(x = reorder(first_hs_name, n/count),
y = n/count, group = ot)) +
geom_bar(aes(fill = ot), stat = 'identity') +
geom_text(aes(label = round(100* n/count, 0)),
position = position_stack(vjust=0.3)) +
theme_bw() +
scale_y_continuous(limits = c(-0.8,1), label = percent,
name = "Percent of Ninth Graders",
breaks = seq(-0.8, 1, 0.2)) +
scale_fill_brewer(name = "", type = "qual", palette = 6) +
theme(axis.text.x = element_text(angle = 30, color = "black", vjust = 0.5),
legend.position = c(0.15, 0.875)) +
labs(title = "Proportion of Students On-Track to Graduate by School",
subtitle = "End of Ninth Grade On-Track Status \n By High School", x = "",
caption = paste0("Sample: 2004-2005 and 2005-20065 Agency first-time ninth
graders. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."))
## ----B2filterAndSort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe graduating
# high school on time AND are part of the ontrack sample (attended the first
# semester of ninth grade and never transferred into or out of the system)
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad &
chrt_ninth <= chrt_ninth_end_grad) %>%
filter(ontrack_sample == 1)
# // Step 2: Create variables for the outcomes "regular diploma recipients",
# "seamless transitioners" and "second year persisters"
plotdf$grad <- ifelse(!is.na(plotdf$chrt_grad) & plotdf$ontime_grad ==1, 1, 0)
plotdf$seamless_transitioners_any <- as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$ontime_grad == 1)
plotdf$second_year_persisters = as.numeric(plotdf$enrl_1oct_ninth_yr1_any == 1 &
plotdf$enrl_1oct_ninth_yr2_any == 1 &
plotdf$ontime_grad == 1)
# // Step 3: Generate on track indicators that take into account students’ GPAs
# upon completion of their first year in high school
plotdf$ot <- NA
plotdf$ot[plotdf$ontrack_endyr1 == 0] <- "Off-Track to Graduate"
plotdf$ot[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 < 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track, GPA < 3.0"
plotdf$ot[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 >= 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track, GPA >= 3.0"
# // Step 4: Create indicators for students upon completion of their second
# year of high school
plotdf$ot_10 <- NA
plotdf$ot_10[plotdf$ontrack_endyr2 == 0] <- "Off-Track to Graduate"
plotdf$ot_10[plotdf$ontrack_endyr2 == 1 & plotdf$cum_gpa_yr2 < 3 &
!is.na(plotdf$cum_gpa_yr2)] <- "On-Track, GPA < 3.0"
plotdf$ot_10[plotdf$ontrack_endyr2 == 1 & plotdf$cum_gpa_yr2 >= 3 &
!is.na(plotdf$cum_gpa_yr2)] <- "On-Track, GPA >= 3.0"
plotdf$ot_10[plotdf$status_after_yr2 == 3 | plotdf$status_after_yr2 == 4] <-
"Dropout/Disappear"
## ----B2reshapeAndFormat--------------------------------------------------
# // Step 5: Obtain mean rates for each school and append the agency average
onTrackBar <- plotdf %>% group_by(ot, ot_10) %>%
select(ot) %>% tally() %>%
ungroup %>% group_by(ot) %>%
mutate(count = sum(n))
# // Step 6: For students who are off-track upon completion of their first year
# of high school, convert the values to be negative for ease of visualization
# in the graph
onTrackBar <- na.omit(onTrackBar) # drop missing
onTrackBar$n[onTrackBar$ot_10 == "Off-Track to Graduate"] <-
-onTrackBar$n[onTrackBar$ot_10 == "Off-Track to Graduate"]
onTrackBar$n[onTrackBar$ot_10 == "Dropout/Disappear"] <-
-onTrackBar$n[onTrackBar$ot_10 == "Dropout/Disappear"]
## ----B2plot--------------------------------------------------------------
ggplot(onTrackBar, aes(x = reorder(ot, n/count),
y = n/count, group = ot_10)) +
geom_bar(aes(fill = ot_10), stat = 'identity') +
geom_text(aes(label = round(100* n/count, 1)),
position = position_stack(vjust=0.3)) +
theme_bw() +
scale_y_continuous(limits = c(-1, 1), label = percent,
name = "Percent of Tenth Grade Students \n by Ninth Grade Status") +
scale_fill_brewer(name = "End of Tenth Grade \n On-Track Status",
type = "div", palette = 5) +
theme(axis.text.x = element_text(color = "black"),
legend.position = c(0.15, 0.825)) +
labs(title = "Proportion of Students On-Track to Graduate by School",
x = "Ninth Grade On-Track Status",
subtitle = "End of Ninth Grade On-Track Status \n By High School",
caption = paste0("Sample: 2004-2005 and 2005-2006 Agency first-time ninth
graders. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."))
## ----C1filterandSort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe
# graduating high school one year late
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad_late &
chrt_ninth <= chrt_ninth_end_grad_late)
## ----C1ReshapeCalculate--------------------------------------------------
# // Step 2: Obtain agency level high school and school level graduation
# rates
schoolLevel <- bind_rows(
plotdf %>% group_by(first_hs_name) %>%
summarize(ontime_grad = mean(ontime_grad, na.rm=TRUE),
late_grad = mean(late_grad, na.rm=TRUE),
count = n()),
plotdf %>% ungroup %>%
summarize(first_hs_name = "Agency AVERAGE",
ontime_grad = mean(ontime_grad, na.rm=TRUE),
late_grad = mean(late_grad, na.rm=TRUE),
count = n())
)
# // Step 3: Reshape the data wide
schoolLevel <- schoolLevel %>% gather(key = outcome,
value = measure, -count, -first_hs_name)
schoolLevel$first_hs_name <- gsub(" High School", "", schoolLevel$first_hs_name)
# // Step 4: Recode variables for plotting
schoolLevel$outcome[schoolLevel$outcome == "ontime_grad"] <- "On-Time HS Graduate"
schoolLevel$outcome[schoolLevel$outcome == "late_grad"] <- "Graduate in 4+ Years"
## ----C1plot--------------------------------------------------------------
# // Step 5: Plot
ggplot(schoolLevel, aes(x = reorder(first_hs_name, measure), y = measure,
group = first_hs_name, fill = outcome)) +
geom_bar(aes(fill = outcome), stat = 'identity') +
geom_text(aes(label = round(100 * measure, 0)),
position = position_stack(vjust = 0.8)) +
theme_bw() + theme(panel.grid = element_blank(), axis.ticks.x = element_blank()) +
scale_y_continuous(limits = c(0, 1), label = percent,
name = "Percent of Ninth Graders") +
scale_fill_brewer(name = "",
type = "qual", palette = 7) +
theme(axis.text.x = element_text(color = "black", angle = 30, vjust = 0.5),
legend.position = c(0.15, 0.825)) +
labs(title = "High School Graduation Rates by High School",
x = "",
caption = paste0("Sample: 2004-2005 Agency first-time ninth graders. \n",
"Data from Agency administrative records."))
## ----C2filterandSort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe graduating
# high school AND have non-missing eighth grade math scores
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad &
chrt_ninth <= chrt_ninth_end_grad) %>%
filter(!is.na(test_math_8_std))
## ----C2reshapeandCalculate-----------------------------------------------
# // Step 2: Obtain agency and school level completion and prior achievement
# rates
schoolLevel <- bind_rows(
plotdf %>% group_by(first_hs_name) %>%
summarize(ontime_grad = mean(ontime_grad, na.rm=TRUE),
std_score = mean(test_math_8_std, na.rm=TRUE),
count = n()),
plotdf %>% ungroup %>%
summarize(first_hs_name = "Agency AVERAGE",
ontime_grad = mean(ontime_grad, na.rm=TRUE),
std_score = mean(test_math_8_std, na.rm=TRUE),
count = n())
)
# // Step 3: Recode HS Name for display
schoolLevel$first_hs_name <- gsub(" High School", "", schoolLevel$first_hs_name)
## ----C2plot--------------------------------------------------------------
# // Step 4: Plot
ggplot(schoolLevel[schoolLevel$first_hs_name != "Agency AVERAGE", ],
aes(x = std_score, y = ontime_grad)) +
geom_vline(xintercept = as.numeric(schoolLevel[schoolLevel$first_hs_name ==
"Agency AVERAGE", "std_score"]),
linetype = 4, color = I("goldenrod"), size = 1.1) +
geom_hline(yintercept = as.numeric(schoolLevel[schoolLevel$first_hs_name ==
"Agency AVERAGE", "ontime_grad"]),
linetype = 4, color = I("purple"), size = 1.1) +
geom_point(size = I(2)) +
theme_bw() + theme(panel.grid = element_blank()) +
coord_cartesian() +
annotate(geom = "text", x = -.85, y = 0.025,
label = "Below average math scores & \n below average graduation rates",
size = I(2.5)) +
annotate(geom = "text", x = .85, y = 0.025,
label = "Above average math scores & \n below average graduation rates",
size = I(2.5)) +
annotate(geom = "text", x = .85, y = 0.975,
label = "Above average math scores & \n above average graduation rates",
size = I(2.5)) +
annotate(geom = "text", x = -.85, y = 0.975,
label = "Below average math scores & \n above average graduation rates",
size = I(2.5)) +
annotate(geom = "text", x = .205, y = 0.025,
label = "Agency Average \n Test Score",
size = I(2.5), color = I("goldenrod")) +
annotate(geom = "text", x = .85, y = 0.61,
label = "Agency Average Graduation Rate",
size = I(2.5)) +
scale_x_continuous(limits = c(-1, 1), breaks = seq(-1, 1, 0.2)) +
scale_y_continuous(limits = c(0, 1), label = percent,
name = "Percent of Ninth Graders", breaks = seq(0, 1, 0.1)) +
geom_text(aes(label = first_hs_name), nudge_y = 0.065, vjust = "top", size = I(4),
nudge_x = 0.01) +
labs(title = "High School Graduation Rates by High School",
x = "Average 8th Grade Math Standardized Score",
subtitle = "By Student Achievement Profile Upon High School Entry",
caption = paste0("Sample: 2004-2005 through 2005-2006 Agency first-time ",
"ninth graders with eighth grade math test scores. \n",
"Data from Agency administrative records."))
## ----C3filterAndSort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe graduating
# high school AND have non-missing eighth grade math scores
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad &
chrt_ninth <= chrt_ninth_end_grad) %>%
filter(!is.na(test_math_8_std))
## ----C3reshapeAndRecode--------------------------------------------------
# // Step 2: btain the agency-level and school level high school graduation
# rates by test score quartile
schoolLevel <- bind_rows(
plotdf %>% group_by(qrt_8_math, first_hs_name) %>%
summarize(ontime_grad = mean(ontime_grad, na.rm=TRUE),
count = n()),
plotdf %>% ungroup %>%
summarize(first_hs_name = "Agency AVERAGE",
qrt_8_math = 1,
ontime_grad = mean(ontime_grad, na.rm=TRUE),
count = n())
)
# // Step 3: Recode HS Name for display
schoolLevel$first_hs_name <- gsub(" High School", "", schoolLevel$first_hs_name)
## ----C3plot--------------------------------------------------------------
# // Step 4: Create plot template
# Load library for arranging multiple plots into one
library(gridExtra); library(grid)
# Create a plot template that you can drop different data elements into
p2 <- ggplot(schoolLevel[schoolLevel$qrt_8_math == 2 &
schoolLevel$first_hs_name != "Agency AVERAGE", ],
aes(x = reorder(first_hs_name, ontime_grad), y = ontime_grad)) +
geom_hline(yintercept =
as.numeric(schoolLevel$ontime_grad[schoolLevel$first_hs_name ==
"Agency AVERAGE"]),
linetype = 2, size = I(1.1)) +
geom_bar(stat = "identity", fill = "lightsteelblue4", color = I("black")) +
scale_y_continuous(limits = c(0,1), breaks = seq(0, 1, 0.2),
expand = c(0, 0), label = percent) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 30, color = "black",
vjust = 0.5, size = 6),
axis.ticks = element_blank(),
axis.text.y = element_blank(), axis.line.y = element_blank(),
panel.border = element_blank()) +
labs(y = "", x = "") +
geom_text(aes(label = round(ontime_grad * 100, 0)), vjust = -0.2) +
expand_limits(y = 0, x = 0)
# Step 5: Create four plots, three using the template above and with the legend,
# put these in a list
grobList <- list(
ggplot(schoolLevel[schoolLevel$qrt_8_math == 1 &
schoolLevel$first_hs_name != "Agency AVERAGE", ],
aes(x = reorder(first_hs_name, ontime_grad), y = ontime_grad)) +
geom_hline(yintercept =
schoolLevel$ontime_grad[schoolLevel$first_hs_name ==
"Agency AVERAGE"],
linetype = 2, size = I(1.1)) +
geom_bar(stat = "identity", fill = "lightsteelblue4", color = I("black")) +
scale_y_continuous(limits = c(0,1), breaks = seq(0, 1, 0.2),
expand = c(0, 0), label = percent) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 30, size = 6,
color = "black", vjust = 0.5),
axis.line.y = element_line(),
axis.ticks.x = element_blank(),panel.border = element_blank()) +
labs(y = "Percent of Ninth Graders", x = "") +
annotate(geom = "text", x = 5,
y = 0.025 + schoolLevel$ontime_grad[schoolLevel$first_hs_name == "Agency AVERAGE"],
label = "Agency Average") +
geom_text(aes(label = round(ontime_grad * 100, 0)), vjust = -0.2) +
expand_limits(y = 0, x = 0),
p2,
# Use the %+% argument to pass a different data element to the p2 plot template
p2 %+% schoolLevel[schoolLevel$qrt_8_math == 3 &
schoolLevel$first_hs_name != "Agency AVERAGE", ],
p2 %+% schoolLevel[schoolLevel$qrt_8_math == 4 &
schoolLevel$first_hs_name != "Agency AVERAGE", ]
)
# Step 6: Apply a label to the bottom of each plot object
wrap <- mapply(arrangeGrob, grobList,
bottom = c("Bottom Quartile", "2nd Quartile",
"3rd Quartile", "Top Quartile"),
SIMPLIFY=FALSE)
# Step 7: Draw the plot
grid.arrange(grobs=wrap, nrow=1,
top = "On-Time High School Graduation Rates \n by Prior Student Achievement",
bottom = textGrob(
label = paste0("Sample: 2004-2005 through 2005-2006 Agency first-time",
"ninth graders with eighth grade math test scores. \n",
"Data from Agency administrative records."),
gp=gpar(fontsize=10,lineheight=1), just = 1, x = unit(0.99, "npc")))
## ----C4filterandSort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe graduating
# high school AND have non-missing eighth grade math scores
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad &
chrt_ninth <= chrt_ninth_end_grad) %>%
filter(!is.na(test_math_8_std))
plotdf$race <- as_factor(plotdf$race_ethnicity)
## ----C4reshapeRecode-----------------------------------------------------
# // Step 2: Obtain average on-time completion by race for agency
plotOne <- plotdf %>% group_by(race) %>%
summarize(ontimeGrad = mean(ontime_grad, na.rm = TRUE),
N = n()) %>% ungroup %>%
filter(N > 100)
# // Step 3: Obtain average on-time completion by race for agency by
# math score quartile
plotTwo <- plotdf %>% group_by(race, qrt_8_math) %>%
summarize(ontimeGrad = mean(ontime_grad, na.rm=TRUE),
N = n()) %>% ungroup %>%
filter(race %in% c("Black", "Asian", "Hispanic", "White"))
# // Step 4: Make labels
plotTwo$qrt_label <- NA
plotTwo$qrt_label[plotTwo$qrt_8_math == 1] <- "Bottom Quartile"
plotTwo$qrt_label[plotTwo$qrt_8_math == 2] <- "2nd Quartile"
plotTwo$qrt_label[plotTwo$qrt_8_math == 3] <- "3rd Quartile"
plotTwo$qrt_label[plotTwo$qrt_8_math == 4] <- "Top Quartile"
plotTwo$qrt_label <- factor(plotTwo$qrt_label,
ordered = TRUE,
levels = c("Bottom Quartile",
"2nd Quartile",
"3rd Quartile",
"Top Quartile"))
## ----C4plot--------------------------------------------------------------
# // Step 5: Plot
ggplot(plotOne, aes( x= reorder(race, -N), y = ontimeGrad, fill = race)) +
geom_bar(stat = "identity", color = I("black")) +
scale_fill_brewer(type = "qual", palette = 4, guide = "none") +
geom_text(aes(label = round(ontimeGrad*100, 0)), vjust = -0.4) +
theme_bw() + theme(panel.grid = element_blank(), panel.border = element_blank(),
axis.line = element_line()) +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0),
breaks = seq(0, 1, 0.2), name = "Percent of Ninth Graders",
label = percent) +
labs(x = "", title = "On-Time High School Graduation Rates",
subtitle = "by Race",
caption = paste0(
"Sample: 2004-2005 through 2005-2006 Agency first-time ninth graders. \n",
"All data from Agency administrative records."))
ggplot(plotTwo, aes( x = qrt_label,
group= reorder(race, -N), y = ontimeGrad, fill = race)) +
geom_bar(stat = "identity", color = I("black"), position = "dodge") +
scale_fill_brewer(type = "qual", palette = 4) +
guides(fill = guide_legend(nrow=1, title = "", keywidth = 2)) +
geom_text(aes(label = round(ontimeGrad*100, 0)), position = position_dodge(0.9), vjust = -0.3) +
theme_bw() + theme(panel.grid = element_blank(), panel.border = element_blank(),
axis.line = element_line(), legend.position = "top") +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0),
breaks = seq(0, 1, 0.2), name = "Percent of Ninth Graders",
label = percent) +
labs(x = "", title = "On-Time High School Graduation Rates",
subtitle = "by Race",
caption = paste0(
"Sample: 2004-2005 through 2005-2006 Agency first-time ninth graders. \n ",
"All data from Agency administrative records."))
## ----C5filterandsort-----------------------------------------------------
# // Step 1: Keep students in ninth grade cohorts you can observe graduating
# high school AND have non-missing eighth grade math scores AND are part of
# the on-track sample
plotdf <- filter(cgdata, chrt_ninth >= chrt_ninth_begin_grad &
chrt_ninth <= chrt_ninth_end_grad) %>%
filter(!is.na(cum_gpa_yr1)) %>%
filter(ontrack_sample == 1)
# // Step 2: Recode status variables
plotdf$statusVar <- as_factor(plotdf$status_after_yr4)
# // Step 3: Generate on-track indicators that take into account students'
# GPA upon completion of their first year in high school
plotdf$ontrackStatus <- NA
plotdf$ontrackStatus[plotdf$ontrack_endyr1 == 0] <- "Off-Track to Graduate"
plotdf$ontrackStatus[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 < 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track, GPA < 3.0"
plotdf$ontrackStatus[plotdf$ontrack_endyr1 == 1 & plotdf$cum_gpa_yr1 >= 3 &
!is.na(plotdf$cum_gpa_yr1)] <- "On-Track, GPA >= 3.0"
## ----C5reshape-----------------------------------------------------------
# // Step 4: Create average outcomes by on-track status at the end of ninth grade
plotOne <- plotdf %>% group_by(ontrackStatus, statusVar) %>%
summarize(count = n()) %>% ungroup %>%
group_by(ontrackStatus) %>%
mutate(sum = sum(count))
# // Step 5: Recode negative values for dropped out and disappeared
plotOne$count[plotOne$statusVar == "Dropped Out"] <-
-plotOne$count[plotOne$statusVar == "Dropped Out"]
plotOne$count[plotOne$statusVar == "Disappeared"] <-
-plotOne$count[plotOne$statusVar == "Disappeared"]
plotOne$statusVar <- ordered(plotOne$statusVar,
c("Graduated On-Time", "Enrolled, Not Graduated",
"Disappeared", "Dropped Out"))
## ----C5plot--------------------------------------------------------------
ggplot(plotOne, aes(x = ontrackStatus, y = count/sum, fill = statusVar,
group = statusVar)) +
geom_bar(stat="identity") +
geom_text(aes(label = round((count/sum) * 100, digits = 0))) +
scale_fill_brewer(type = "div", palette=7, direction = -1) +
geom_hline(yintercept = 0, size =1.1) +
scale_y_continuous(limits = c(-0.6, 1), label = percent,
breaks = seq(-0.6, 1, 0.2), name = "Percent of Students") +
labs(x = "Ninth Grade On-Track Status", fill = "Status After Year Four",
title = "Enrollment Status After Four Years in High School",
subtitle = "By Course Credits and GPA after First Year of High School",
caption = paste0("Sample: 2004-2005 through 2005-2006 Agency",
" first-time ninth graders. \n",
"Students who transferred into or out of the agency are",
" excluded from the sample. \n",
"All data from Agency administrative records.")) +
theme_classic() + theme(legend.position = c(0.8, 0.2),
axis.text = element_text(color = "black"))
## ----D1filterAndSort-----------------------------------------------------
# // Step 2: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end)
## ----D1reshapeAndRecode--------------------------------------------------
# // Step 3: Obtain the agency-level and school averages for seamless enrollment
chartData <-
bind_rows(plotdf %>% select(last_hs_name, enrl_1oct_grad_yr1_2yr,
enrl_1oct_grad_yr1_4yr, hs_diploma) %>%
group_by(last_hs_name) %>%
summarize_all(funs(sum), na.rm=TRUE),
plotdf %>% select(enrl_1oct_grad_yr1_2yr, enrl_1oct_grad_yr1_4yr,
hs_diploma) %>%
summarize_all(funs(sum), na.rm=TRUE) %>%
mutate(last_hs_name = "Agency AVERAGE")
)
# // Step 4: Reshape agency data for plotting
chartData <- chartData %>% gather(key = outcome,
value = measure, -last_hs_name, -hs_diploma)
# // Step 5: Calculate rates
chartData %<>% group_by(last_hs_name) %>%
mutate(enroll_any = sum(measure) / hs_diploma[1]) %>%
ungroup
# // Step 6: Recode variables
chartData$last_hs_name <- gsub("High School", "", chartData$last_hs_name)
# Split levels
chartData$last_hs_name <- gsub(" ", "\n", chartData$last_hs_name)
chartData$outcome[chartData$outcome == "enrl_1oct_grad_yr1_2yr"] <-
"2-yr Seamless Enroller"
chartData$outcome[chartData$outcome == "enrl_1oct_grad_yr1_4yr"] <-
"4-yr Seamless Enroller"
## ----D1plot--------------------------------------------------------------
ggplot(chartData, aes(x = reorder(last_hs_name, enroll_any),
y = measure/hs_diploma,
fill = outcome, group = outcome)) +
geom_bar(stat = "identity", position = "stack", color = I("black")) +
geom_text(aes(label = round(100 * measure/hs_diploma)),
position = position_stack(vjust = 0.5)) +
geom_text(aes(label = round(100 * enroll_any), y = enroll_any),
vjust = -0.5, color = I("gray60")) +
theme_classic() +
scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.2),
expand = c(0,0),
label = percent) +
scale_fill_brewer(name = "", type = "qual", palette = 1) +
labs(x = "", y = "Percent of High School Graduates",
title = "College Enrollment by High School",
subtitle = "Seamless Enrollers",
caption = paste0(
"Sample: 2007-2008 through 2008-2009 Agency graduates.",
"Postsecondary enrollment outcomes from NSC matched records.",
"\n All other data from administrative records.")) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.8, color = "black"),
legend.position = c(0.1, 0.8), axis.ticks.x = element_blank())
## ----D2filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, enrl_1oct_grad_yr1_2yr, enrl_1oct_grad_yr1_4yr,
enrl_1oct_grad_yr1_any, enrl_ever_w2_grad_2yr, enrl_ever_w2_grad_any,
enrl_ever_w2_grad_4yr, hs_diploma, last_hs_code, last_hs_name)
## ----D2reshapeAndRecode--------------------------------------------------
# // Step 2: Create binary outcomes for late enrollers
plotdf$late_any <- ifelse(plotdf$enrl_1oct_grad_yr1_any == 0 &
plotdf$enrl_ever_w2_grad_any == 1, 1, 0)
plotdf$late_4yr <- ifelse(plotdf$enrl_1oct_grad_yr1_any == 0 &
plotdf$enrl_ever_w2_grad_4yr == 1, 1, 0)
plotdf$late_2yr <- ifelse(plotdf$enrl_1oct_grad_yr1_any == 0 &
plotdf$enrl_ever_w2_grad_2yr == 1, 1, 0)
# // Step 3: Obtain the agency and school average for seamless and
# delayed enrollment
chartData <- bind_rows(
plotdf %>% select(last_hs_name, enrl_1oct_grad_yr1_2yr,
enrl_1oct_grad_yr1_4yr, late_4yr, late_2yr,
hs_diploma) %>%
group_by(last_hs_name) %>%
summarize_all(funs(sum), na.rm=TRUE),
plotdf %>% select(enrl_1oct_grad_yr1_2yr,
enrl_1oct_grad_yr1_4yr, late_4yr, late_2yr,
hs_diploma) %>%
summarize_all(funs(sum), na.rm=TRUE) %>%
mutate(last_hs_name = "Agency AVERAGE")
)
# // Step 4: Reshape for plotting
chartData <- chartData %>% gather(key = outcome,
value = measure, -last_hs_name, -hs_diploma)
# // Step 5: Generate percentages of high school grads attending college.
chartData %<>% group_by(last_hs_name) %>%
mutate(enroll_any = sum(measure) / hs_diploma[1]) %>%
ungroup
# // Step 6: Recode values for plotting
chartData$last_hs_name <- gsub("High School", "", chartData$last_hs_name)
chartData$last_hs_name <- gsub(" ", "\n", chartData$last_hs_name)
chartData$outcome[chartData$outcome == "enrl_1oct_grad_yr1_2yr"] <- "2-yr Seamless"
chartData$outcome[chartData$outcome == "enrl_1oct_grad_yr1_4yr"] <- "4-yr Seamless"
chartData$outcome[chartData$outcome == "late_2yr"] <- "2-yr Delayed"
chartData$outcome[chartData$outcome == "late_4yr"] <- "4-yr Delayed"
## ----D2Plot--------------------------------------------------------------
# // Step 7: Plot
ggplot(chartData, aes(x = reorder(last_hs_name, enroll_any),
y = measure/hs_diploma,
fill = outcome, group = outcome)) +
geom_bar(stat = "identity", position = "stack", color = I("black")) +
geom_text(aes(label = round(100 * measure/hs_diploma)),
position = position_stack(vjust = 0.5)) +
geom_text(aes(label = round(100 * enroll_any), y = enroll_any),
vjust = -0.5, color = I("gray60")) +
theme_classic() +
scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.2),
expand = c(0,0),
label = percent) +
scale_fill_brewer(name = "", type = "seq", palette = "YlGnBu") +
labs(x = "", y = "Percent of High School Graduates",
title = "College Enrollment by High School",
subtitle = "Seamless and Delayed Enrollers",
caption = paste0("Sample: 2007-2008 through 2008-2009 Agency graduates.",
"Postsecondary enrollment outcomes from NSC matched records.",
"\n All other data from administrative records.")) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.8, color = "black"),
legend.position = c(0.1, 0.8), axis.ticks.x = element_blank())
## ----D3FilterAndSort-----------------------------------------------------
# // Step 2: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation AND have non-missing eighth
# grade math scores
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, enrl_1oct_grad_yr1_any, test_math_8_std,
last_hs_name) %>%
filter(!is.na(test_math_8_std))
## ----D3reshapeAndCalculate-----------------------------------------------
# // Step 2: Obtain agency-level college enrollment rate and prior
# achievement score for dotted lines. Also get position of their labels
AGENCYLEVEL <- plotdf %>%
summarize(agency_mean_enroll = mean(enrl_1oct_grad_yr1_any, na.rm=TRUE),
agency_mean_test = mean(test_math_8_std)) %>%
as.data.frame
# // Step 3: Obtain school-level college enrollment rates and prior
# achievement scores
chartData <- plotdf %>% group_by(last_hs_name) %>%
summarize(math_test = mean(test_math_8_std),
enroll_rate = mean(enrl_1oct_grad_yr1_any, na.rm=TRUE),
count = n())
# // Step 4: Shorten HS name for plotting
chartData$last_hs_name <- gsub("High School", "", chartData$last_hs_name)
chartData$last_hs_name <- gsub(" ", "\n", chartData$last_hs_name)
## ----D3plot--------------------------------------------------------------
# // Step 5: Plot
ggplot(chartData, aes(x = math_test, y = enroll_rate)) +
geom_point() + geom_text(aes(label = last_hs_name),
nudge_x = -0.02, nudge_y= 0.02, angle = 30,
check_overlap = FALSE) +
theme_classic() +
geom_hline(yintercept = AGENCYLEVEL$agency_mean_enroll, linetype = 2,
size = I(1.1), color = I("slateblue")) +
geom_vline(xintercept = AGENCYLEVEL$agency_mean_test, linetype = 2,
size = I(1.1), color = I("goldenrod")) +
scale_y_continuous(limits = c(0,1), breaks = seq(0, 1, 0.2), label = percent) +
scale_x_continuous(limits = c(-0.8, 1), breaks = seq(-0.8, 1, 0.2)) +
annotate(geom = "text", x = -.675, y = 0.025,
label = "Below average math scores & \n below average college enrollment",
size = I(2.5)) +
annotate(geom = "text", x = .88, y = 0.025,
label = "Above average math scores & \n below average college enrollment",
size = I(2.5)) +
annotate(geom = "text", x = .88, y = 0.975,
label = "Above average math scores & \n above average college enrollment",
size = I(2.5)) +
annotate(geom = "text", x = -.675, y = 0.975,
label = "Below average math scores & \n above average college enrollment",
size = I(2.5)) +
annotate(geom = "text", x = .255, y = 0.125,
label = "Agency Average \n Test Score",
size = I(2.5), color = I("goldenrod")) +
annotate(geom = "text", x = -.675, y = 0.71,
label = "Agency Average \nCollege Enrollment Rate",
size = I(2.5)) +
labs(x = "Percent of High School Graduates",
y = "Average 8th Grade Math Standardized Score",
title = "College Enrollment Rates by Prior Student Achievement",
subtitle = "Seamless Enrollers",
caption = paste0("Sample: 2007-2008 through 2008-2009 Agency graduates. Postsecondary",
" enrollment outcomes from NSC matched records. \n ",
"All other data from administrative records.")) +
theme(axis.text = element_text(color="black", size = 12))
## ----D4filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation AND have non-missing eighth
# grade math scores
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, enrl_1oct_grad_yr1_any, qrt_8_math,
last_hs_name) %>%
filter(!is.na(qrt_8_math))
## ----D4reshapeAndCalculate-----------------------------------------------
# // Step 2: Obtain the overall agency-level high school graduation rate for
# dotted line along with the position of its label
AGENCYLEVEL <- plotdf %>%
summarize(agency_mean_enroll = mean(enrl_1oct_grad_yr1_any, na.rm=TRUE)) %>%
as.data.frame
# // Step 5: Obtain school-level and agency level college enrollment rates by
# test score quartile and append the agency-level enrollment rates
# by quartile
chartData <- bind_rows(
plotdf %>% group_by(last_hs_name, qrt_8_math) %>%
summarize(enroll_rate = mean(enrl_1oct_grad_yr1_any, na.rm=TRUE),
count = n()),
plotdf %>% group_by(qrt_8_math) %>%
summarize(enroll_rate = mean(enrl_1oct_grad_yr1_any, na.rm=TRUE),
count = n(),
last_hs_name = "Agency AVERAGE")
)
# // Step 6: Recode HS Name for plotting
chartData$last_hs_name <- gsub("High School", "", chartData$last_hs_name)
# chartData$last_hs_name <- gsub(" ", "\n", chartData$last_hs_name)
## ----D4plot--------------------------------------------------------------
# // Step 7: Make plot for first panel with legend and labels
p1 <- ggplot(chartData[chartData$qrt_8_math == 1, ],
aes(x = reorder(last_hs_name, enroll_rate), y = enroll_rate)) +
geom_hline(yintercept = as.numeric(AGENCYLEVEL$agency_mean_enroll),
linetype = 2, size = I(1.1)) +
geom_bar(stat = "identity", fill = "lightsteelblue4", color = I("black")) +
scale_y_continuous(limits = c(0,1), breaks = seq(0, 1, 0.2),
expand = c(0, 0), label = percent) +
theme_bw() +
annotate(geom = "text", x = 6, y = 0.775, label = "Agency Average") +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 30, size=6,
color = "black", vjust = 0.5),
axis.line.y = element_line(), axis.line.x = element_line(),
axis.ticks.x = element_blank(),panel.border = element_blank()) +
labs(y = "Percent of Ninth Graders", x = "") +
geom_text(aes(label = round(enroll_rate * 100, 0)), vjust = -0.2) +
expand_limits(y = 0, x = 0)
# // Step 8 : Make Template for following 3 panels with fewer legends and
# labels
p2 <- ggplot(chartData[chartData$qrt_8_math == 2, ],
aes(x = reorder(last_hs_name, enroll_rate), y = enroll_rate)) +
geom_hline(yintercept = as.numeric(AGENCYLEVEL$agency_mean_enroll),
linetype = 2, size = I(1.1)) +
geom_bar(stat = "identity", fill = "lightsteelblue4", color = I("black")) +
scale_y_continuous(limits = c(0,1), breaks = seq(0, 1, 0.2),
expand = c(0, 0), label = percent) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 30, size=6,
color = "black", vjust = 0.5),
axis.ticks = element_blank(), axis.line.x = element_line(),
axis.text.y = element_blank(), axis.line.y = element_blank(),
panel.border = element_blank()) +
labs(y = "", x = "") +
geom_text(aes(label = round(enroll_rate * 100, 0)), vjust = -0.2) +
expand_limits(y = 0, x = 0)
# schoolLevel$order <-
# // Step 9: Combine first plot with template applied to quartiles 2, 3, and 4
# Use %+% operator to replace the data in the plot template with another data
# set
grobList <- list(
p1,
p2,
p2 %+% chartData[chartData$qrt_8_math == 3, ],
p2 %+% chartData[chartData$qrt_8_math == 4, ]
)
# // Step 10: Apply quartile labels to each panel
wrap <- mapply(arrangeGrob, grobList,
bottom = c("Bottom Quartile", "2nd Quartile",
"3rd Quartile", "Top Quartile"),
SIMPLIFY=FALSE)
# // Step 11: Plot with labels
grid.arrange(grobs=wrap, nrow=1,
top = paste0("College Enrollment Rates ",
"\n by Prior Student Achievement, Seamless Enrollers Only"),
bottom = textGrob(label = paste0(
"Sample: 2007-2008 through 2008-2009.",
"Agency graduates with eighth grade math scores. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."
), gp=gpar(fontsize=10,lineheight=1), just = 1,
x = unit(0.99, "npc")))
## ----D5filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, race_ethnicity, highly_qualified,
enrl_1oct_grad_yr1_any, enrl_1oct_grad_yr1_4yr, enrl_1oct_grad_yr1_2yr)
# Use race_ethnicity as a labeled factor for plotting
plotdf$race_ethnicity <- as_factor(plotdf$race_ethnicity)
# // Step 2: Take total of all students in sample
totalCount <- nrow(plotdf)
## ----D5recodeAndReshape--------------------------------------------------
# // Step 3: Create "undermatch" outcomes
plotdf$no_college <- ifelse(plotdf$enrl_1oct_grad_yr1_any == 0, 1, 0)
plotdf$enrl_2yr <- ifelse(plotdf$enrl_1oct_grad_yr1_2yr == 1, 1, 0)
plotdf$enrl_4yr <- ifelse(plotdf$enrl_1oct_grad_yr1_4yr == 1, 1, 0)
# // Step 3: Create agency-level outcomes for total undermatching rates
agencyLevel <- plotdf %>% filter(highly_qualified == 1) %>%
summarize(no_college = mean(no_college, na.rm=TRUE),
enrl_2yr = mean(enrl_2yr, na.rm=TRUE),
enrl_4yr = mean(enrl_4yr, na.rm=TRUE),
total_count = n(),
race_ethnicity = "TOTAL")
# // Step 4: Create race/ethnicity-level outcomes for undermatching rates by
# race/ethnicity
chartData <- plotdf %>% filter(highly_qualified == 1) %>%
group_by(race_ethnicity) %>%
summarize(no_college = mean(no_college, na.rm=TRUE),
enrl_2yr = mean(enrl_2yr, na.rm=TRUE),
enrl_4yr = mean(enrl_4yr, na.rm=TRUE),
total_count = n())
chartData <- bind_rows(chartData, agencyLevel)
# // Step 5: Convert negative outcomes to negative values and reshape
# data for plotting
chartData$no_college <- -chartData$no_college
chartData$enrl_2yr <- -chartData$enrl_2yr
chartData <- chartData %>% gather(key = outcome, value = measure,
-race_ethnicity, -total_count)
# // Step 7: Convert to percentages and relabel ethnicities for plot labels
chartData$groupPer <- round(100 * chartData$total_count/totalCount)
chartData$race_ethnicity[chartData$race_ethnicity == "Black"] <- "African American"
chartData$race_ethnicity[chartData$race_ethnicity == "Asian"] <- "Asian American"
chartData$race_ethnicity[chartData$race_ethnicity == "Hispanic"] <- "Hispanic American"
chartData$race_ethnicity[chartData$race_ethnicity == "TOTAL"] <- "Total"
chartData$label <- paste0(chartData$race_ethnicity, "\n ",
chartData$groupPer, "% of Graduates")
chartData %<>% filter(chartData$race_ethnicity != "Multiple/Other")
# // Step 8: Create a label variable to label the outcomes on the plot
chartData$outcomeLabel <- NA
chartData$outcomeLabel[chartData$outcome == "no_college"] <- "Not Enrolled in College"
chartData$outcomeLabel[chartData$outcome == "enrl_2yr"] <- "Enrolled at 2-Yr College"
chartData$outcomeLabel[chartData$outcome == "enrl_4yr"] <- "Enrolled at 4-Yr College"
# // Step 9: Order the factor to plot in the correct order
chartData$outcomeLabel <- factor(chartData$outcomeLabel,
ordered = TRUE,
levels = c("Enrolled at 4-Yr College",
"Not Enrolled in College",
"Enrolled at 2-Yr College"))
## ----D5plot--------------------------------------------------------------
#// Step 10: Create a caption to put under the figure
myCap <- paste0(
"Sample: 2007-2008 through 2008-2009 Agency first-time ninth graders. ",
"Students who transferred into or out of\nAgency are excluded ",
"from the sample. Eligibility to attend a public four-year university ",
"is based on students' cumulative GPA\nand ACT/SAT scores. ",
"Sample includes 30 African American, 82 Asian American students, ",
"53 Hispanic, \nand 198 White students. ",
"Post-secondary enrollment data are from NSC matched records.")
# // Step 11: Plot
ggplot(chartData, aes(x = reorder(label, total_count), y = measure,
group = outcomeLabel,
fill = outcomeLabel)) +
geom_bar(position = 'stack', stat = 'identity', color = I("black")) +
geom_hline(yintercept = 0) +
geom_text(aes(label = round(measure * 100, 0)),
position=position_stack(vjust = 0.85)) +
scale_y_continuous(limits = c(-.25, 1), breaks = seq(-.25, 1, 0.2),
label = percent) +
theme_classic() +
guides(fill = guide_legend(nrow=1, title = "", keywidth = 2)) +
scale_fill_brewer(type = "qual", palette = 2, direction = -1) +
theme(legend.position = "top", axis.text = element_text(color = "black"),
plot.caption = element_text(hjust = 0, size = 8),
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)) +
labs(x = "", y = "Percent of Highly-Qualified Graduates",
title = "Rates of Highly Qualified Students Attending College, by Race",
subtitle = "Among Graduates Eligible to Attend Four-Year Universities",
caption = myCap)
## ----D6filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation AND have non-missing eighth
# grade test scores AND non-missing FRPL status
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, race_ethnicity, test_math_8, frpl_ever,
enrl_1oct_grad_yr1_any, last_hs_code) %>%
filter(!is.na(frpl_ever) & !is.na(test_math_8)) %>%
filter(race_ethnicity %in% c(1, 3, 5) & !is.na(race_ethnicity)) %>%
filter(!is.na(enrl_1oct_grad_yr1_any))
# // Step 2: Recode variables and create cluster variable
plotdf$race_ethnicity <- as_factor(plotdf$race_ethnicity)
plotdf$race_ethnicity <- relevel(plotdf$race_ethnicity, ref = "White")
# // Step 3: Create a unique identifier for clustering standard errors
# at the cohort/school level
plotdf$cluster_var <- paste(plotdf$chrt_grad, plotdf$last_hs_code, sep = "-")
## ----D6modelAndReshape---------------------------------------------------
# Load the broom library to make working with model coefficients simple
# and uniform
library(broom)
# // Step 4: Estimate the unadjusted and adjusted differences in college
# enrollment between Latino and white students and between black and white
# students
# Estimate unadjusted enrollment gap
# Fit the model
mod1 <- lm(enrl_1oct_grad_yr1_any ~ race_ethnicity, data = plotdf)
# Extract the coefficients
betas_unadj <- tidy(mod1)
# Get the clustered variance-covariance matrix
# Use the get_CL_vcov function from the functions.R script
clusterSE <- get_CL_vcov(mod1, plotdf$cluster_var)
# Get the clustered standard errors and combine with the betas
betas_unadj$std.error <- sqrt(diag(clusterSE))
betas_unadj <- betas_unadj[, 1:3]
# Label
betas_unadj$model <- "Unadjusted enrollment gap"
# Estimate enrollment gap adjusting for prior achievement
mod2 <- lm(enrl_1oct_grad_yr1_any ~ race_ethnicity + test_math_8, data = plotdf)
betas_adj_prior_ach <- tidy(mod2)
clusterSE <- get_CL_vcov(mod2, plotdf$cluster_var)
betas_adj_prior_ach$std.error <- sqrt(diag(clusterSE))
betas_adj_prior_ach <- betas_adj_prior_ach[, 1:3]
betas_adj_prior_ach$model <- "Gap adjusted for prior achievement"
# Estimate enrollment gap adjusting for frpl status
plotdf$frpl_ever <- ifelse(plotdf$frpl_ever > 0, 1, 0)
mod3 <- lm(enrl_1oct_grad_yr1_any ~ race_ethnicity + frpl_ever, data = plotdf)
betas_adj_frpl <- tidy(mod3)
clusterSE <- get_CL_vcov(mod3, plotdf$cluster_var)
betas_adj_frpl$std.error <- sqrt(diag(clusterSE))
betas_adj_frpl <- betas_adj_frpl[, 1:3]
betas_adj_frpl$model <- "Gap adjusted for FRPL status"
# Estimate enrollment gap adjusting for prior achievement and frpl status
mod4 <- lm(enrl_1oct_grad_yr1_any ~ race_ethnicity + frpl_ever + test_math_8,
data = plotdf)
betas_adj_frpl_prior <- tidy(mod4)
clusterSE <- get_CL_vcov(mod4, plotdf$cluster_var)
betas_adj_frpl_prior$std.error <- sqrt(diag(clusterSE))
betas_adj_frpl_prior <- betas_adj_frpl_prior[, 1:3]
betas_adj_frpl_prior$model <- "Gap adjusted for prior achievement & FRPL status"
# // Step 5. Transform the regression coefficients to a data object for plotting
chartData <- bind_rows(betas_unadj, betas_adj_frpl, betas_adj_prior_ach,
betas_adj_frpl_prior)
# Cleanup workspace
rm(plotdf, betas_unadj, betas_adj_frpl, betas_adj_frpl_prior,
betas_adj_prior_ach)
## ----D6plot--------------------------------------------------------------
# // Step 6. Plot
ggplot(chartData[chartData$term == "race_ethnicityHispanic", ],
aes(x = model, y = -estimate, fill = model)) +
geom_bar(stat = 'identity', color = I("black")) +
scale_fill_brewer(type = "seq", palette = 8) +
geom_hline(yintercept = 0) +
guides(fill = guide_legend("", keywidth = 6, nrow = 2)) +
geom_text(aes(label = round(100 * -estimate, 0)), vjust = -0.3) +
scale_y_continuous(limits = c(-0.2, 0.5), breaks = seq(-0.2, 0.5, 0.1),
label = percent, name = "Percentage Points") +
theme_classic() + theme(legend.position = "bottom", axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
labs(title = paste0("Differences in Rates of College Enrollment",
" \nBetween Latino and White High School Graduates"),
x = "",
caption = paste0(
"Sample: 2007-2008 through 2008-2009 high school graduates. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records.")
)
## ----D7filterAndSOrt-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation AND have non-missing eighth
# grade test scores
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, qrt_8_math, hs_diploma,
enrl_1oct_grad_yr1_any, last_hs_name) %>%
filter(!is.na(qrt_8_math)) %>%
filter(!is.na(enrl_1oct_grad_yr1_any))
## ----D7reshapeAndCalculate-----------------------------------------------
# // Step 2: Create agency- and school-level average outcomes for each quartile
chartData <- plotdf %>% group_by(last_hs_name, qrt_8_math) %>%
summarize(enroll_count = sum(enrl_1oct_grad_yr1_any),
diploma_count = sum(hs_diploma)) %>%
mutate(pct_enrl = enroll_count/diploma_count)
agencyData <- plotdf %>% group_by(qrt_8_math) %>%
summarize(enroll_count = sum(enrl_1oct_grad_yr1_any),
diploma_count = sum(hs_diploma)) %>%
mutate(pct_enrl = enroll_count/diploma_count) %>% as.data.frame
## ----D7plot--------------------------------------------------------------
# // Step 3: Plot
ggplot(chartData, aes(x = factor(qrt_8_math), y = pct_enrl)) +
geom_point(aes(size = diploma_count), shape = 1) +
scale_size(range = c(3, 12), breaks = seq(0, 350, 75)) +
geom_point(data=agencyData, aes(x = factor(qrt_8_math),
y = pct_enrl, size = NULL),
color = I("red"), size = I(4)) +
theme_classic() +
scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.2),
label = percent) +
labs(y = "Percent of High School Graduates",
x = "Quartile of Prior Achievement",
title = "College Enrollment Rates Among High School Gradautes",
subtitle = "Within Quartile of Prior Achievement, by High School",
caption = paste0(
"Sample: 2007-2008 through 2008-2009 high school graduates. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records.")
)
## ----D8filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation AND are highy qualified
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_begin) %>%
select(sid, chrt_grad, highly_qualified, first_college_opeid_4yr,
enrl_1oct_grad_yr1_any, enrl_1oct_grad_yr1_4yr, enrl_1oct_grad_yr1_2yr) %>%
filter(!is.na(highly_qualified)) %>%
filter(highly_qualified ==1 )
# // Step 2: Link the analysis file with the college selectivity table to obtain
# the selectivity level for each college. Use this selectivity information to
# create college enrollment indicator variables for each college selectivity
# level. This script assumes that there are 5 levels of selectivity, as in
# Barron’s College Rankings—Most Competitive (1), Highly Competitive (2),
# Very Competitive (3), Competitive (4), Least Competitive (5)—as well as a
# category for colleges without assigned selectivity (assumed to be not
# competitive).
# Read in college selectivity data
tmpfileName <- "analysis/college_selectivity.dta"
con <- unz(description = "data/analysis.zip", filename = tmpfileName,
open = "rb")
coll_select <- read_stata(con) # read data in the data subdirectory
close(con)
# Merge on to subset from above
plotdf <- left_join(plotdf, coll_select,
by = c("first_college_opeid_4yr" = "college_id"))
# Filter out
plotdf %<>% filter(!(first_college_opeid_4yr == "" & enrl_1oct_grad_yr1_4yr == 1))
## ----D8recodeAndReshape--------------------------------------------------
# // Step 4. Create the undermatch outcomes
plotdf$rank[is.na(plotdf$rank)] <- 6
plotdf$outcome <- NA
plotdf$outcome[plotdf$enrl_1oct_grad_yr1_any == 0] <- "No college"
plotdf$outcome[plotdf$enrl_1oct_grad_yr1_2yr == 1] <- "Two year college"
plotdf$outcome[is.na(plotdf$outcome) &
plotdf$enrl_1oct_grad_yr1_any == 1 & (plotdf$rank > 4)] <- "Undermatch"
plotdf$outcome[plotdf$enrl_1oct_grad_yr1_any == 1 & plotdf$rank <= 4] <- "Match"
# // Step 5 Create agency-average undermatch outcomes and transform them into % terms
chartData <- plotdf %>% group_by(outcome) %>%
summarize(count = n()) %>% ungroup %>%
mutate(totalCount = sum(count))
chartData %<>% filter(outcome != "Match") %>%
arrange(count)
## ----D8plot--------------------------------------------------------------
# // Step 6: Plot
ggplot(arrange(chartData, -count),
aes(x = factor(1), fill = outcome, y = count/totalCount)) +
geom_bar(stat = 'identity', position = "stack", color = I("black")) +
scale_fill_brewer(type = "qual", palette= 3, direction=1) +
guides(fill = guide_legend("", keywidth = 6, nrow = 2)) +
geom_text(aes(label = round(100 * count/totalCount, 1)),
position = position_stack(vjust = 0.5)) +
scale_y_continuous(limits = c(0, 0.40), breaks = seq(0, 0.4, 0.1),
label = percent, name = "Percent of High School Graduates") +
theme_classic() + theme(legend.position = "bottom", axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
labs(title = "Undermatch Rates by Agency",
subtitle = "Among Highly Qualified High School Graduates",
x = "",
caption = paste0(
"Sample: 2007-2008 through 2008-2009 high school graduates. \n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from Agency administrative records."))
## ----E1filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, enrl_1oct_grad_yr1_2yr, enrl_1oct_grad_yr1_4yr,
enrl_1oct_grad_yr1_any, enrl_grad_persist_any,
enrl_grad_persist_2yr, enrl_grad_persist_4yr, last_hs_name,
enrl_ever_w2_grad_any)
# // Step 2: Rename and recode for simplicity
plotdf$groupVar <- NA
plotdf$groupVar[plotdf$enrl_1oct_grad_yr1_2yr == 1] <- "2-year College"
plotdf$groupVar[plotdf$enrl_1oct_grad_yr1_4yr == 1] <- "4-year College"
## ----E1ReshapeandRecode--------------------------------------------------
# // Step 3: Obtain the agency-level average for persistence and enrollment
agencyData <- plotdf %>% group_by(groupVar) %>%
summarize(persistCount = sum(enrl_grad_persist_any, na.rm=TRUE),
totalCount = n()) %>%
ungroup %>%
mutate(total = sum(persistCount)) %>%
mutate(persistRate = persistCount / totalCount,
last_hs_name = "Agency AVERAGE")
# // Step 4: Obtain the school-level average for persistence and enrollment
schoolData <- plotdf %>% group_by(groupVar, last_hs_name) %>%
summarize(persistCount = sum(enrl_grad_persist_any, na.rm=TRUE),
totalCount = n()) %>%
ungroup %>% group_by(last_hs_name) %>%
mutate(total = sum(persistCount)) %>%
mutate(persistRate = persistCount / totalCount)
# Combine for chart
chartData <- bind_rows(agencyData, schoolData)
# // Step 5: Recode variables for plotting
chartData$last_hs_name <- gsub(" High School", "", chartData$last_hs_name)
# // STep 6: Filter rows out with missing values or small cell sizes
chartData <- na.omit(chartData)
chartData <- filter(chartData, totalCount > 20)
# // Step 7: Calculate rank for plot order
chartData <- chartData %>% group_by(groupVar) %>%
mutate(order = min_rank(-persistRate))
chartData %<>% arrange(last_hs_name)
# Make ranks the same for 2 and 4 year colleges
chartData$order[chartData$groupVar == "2-year College"] <-
chartData$order[chartData$groupVar == "4-year College"]
# Conver to a factor and order for ggplot purposes
chartData$groupVar <- factor(chartData$groupVar)
chartData$groupVar <- relevel(chartData$groupVar, ref = "4-year College")
## ----E1plot--------------------------------------------------------------
# // Step 8: Plot
ggplot(chartData, aes(x = reorder(last_hs_name, -order),
group = groupVar,
y = persistRate, fill = groupVar,
color = I("black"))) +
geom_bar(stat = 'identity', position = 'dodge') +
geom_text(aes(label = round(persistRate * 100, 0)),
position = position_dodge(0.9), vjust = -0.4) +
scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.2),
name = "% Of Seamless Enrollers",
expand = c(0,0), label = percent) +
theme_classic() +
guides(fill = guide_legend("", keywidth = 3, nrow = 2)) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5, color = "black"),
legend.position = c(0.1, 0.925), axis.ticks.x = element_blank(),
legend.key = element_rect(color = "black")) +
scale_fill_brewer(type = "div", palette = 2) +
labs(x = "",
title = "College Persistence by High School, at Any College",
subtitle = "Seamless Enrollers by Type of College",
caption = paste0(
"Sample: 2007-2008 through 2008-2009 Agency high school graduates.\n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from agency administrative records"))
## ----E2filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, enrl_1oct_grad_yr1_2yr, enrl_1oct_grad_yr1_4yr,
enrl_1oct_grad_yr1_any, enrl_1oct_grad_yr2_2yr, enrl_1oct_grad_yr2_4yr,
enrl_1oct_grad_yr2_any, enrl_grad_persist_any,
enrl_grad_persist_2yr, enrl_grad_persist_4yr, last_hs_name)
## ----E2recodeAndReshape--------------------------------------------------
# Clean up missing data for binary recoding
plotdf$enrl_grad_persist_4yr <- zeroNA(plotdf$enrl_grad_persist_4yr)
plotdf$enrl_grad_persist_2yr <- zeroNA(plotdf$enrl_grad_persist_2yr)
plotdf$enrl_1oct_grad_yr1_2yr <- zeroNA(plotdf$enrl_1oct_grad_yr1_2yr)
plotdf$enrl_1oct_grad_yr1_4yr <- zeroNA(plotdf$enrl_1oct_grad_yr1_4yr)
# // Step 2: Create binary outcomes for enrollers who switch from 4-yr to 2-yr,
# or vice versa and recode variables
plotdf$persist_pattern <- "Not persisting"
plotdf$persist_pattern[plotdf$enrl_grad_persist_4yr == 1 &
!is.na(plotdf$chrt_grad)] <- "Persisted at 4-Year College"
plotdf$persist_pattern[plotdf$enrl_grad_persist_2yr ==1 &
!is.na(plotdf$chrt_grad)] <- "Persisted at 2-Year College"
plotdf$persist_pattern[plotdf$enrl_1oct_grad_yr1_4yr == 1 &
plotdf$enrl_1oct_grad_yr2_2yr == 1 &
!is.na(plotdf$chrt_grad)] <- "Switched to 2-Year College"
plotdf$persist_pattern[plotdf$enrl_1oct_grad_yr1_2yr == 1 &
plotdf$enrl_1oct_grad_yr2_4yr == 1 &
!is.na(plotdf$chrt_grad)] <- "Switched to 4-Year College"
plotdf$groupVar <- NA
plotdf$groupVar[plotdf$enrl_1oct_grad_yr1_2yr == 1] <- "2-year College"
plotdf$groupVar[plotdf$enrl_1oct_grad_yr1_4yr == 1] <- "4-year College"
# Drop NA
plotdf %<>% filter(!is.na(groupVar))
# // Step 3: Obtain agency and school level average for persistence outcomes
chartData <- plotdf %>%
group_by(last_hs_name, groupVar, persist_pattern) %>%
summarize(tally = n()) %>% # counts the occurrence persist_pattern
ungroup %>%
group_by(last_hs_name, groupVar) %>% # regroup by grouping variable and school
mutate(denominator = sum(tally)) %>% # sum all levels of persist_pattern
mutate(persistRate = tally / denominator) %>% # calculate rate
filter(persist_pattern != "Not persisting") %>%
mutate(rankRate = sum(persistRate))
agencyData <- plotdf %>%
group_by(groupVar, persist_pattern) %>%
summarize(tally = n(),
last_hs_name = "Agency AVERAGE") %>%
ungroup %>%
group_by(last_hs_name, groupVar) %>%
mutate(denominator = sum(tally)) %>%
mutate(persistRate = tally / denominator) %>%
filter(persist_pattern != "Not persisting") %>%
mutate(rankRate = sum(persistRate))
chartData <- bind_rows(chartData, agencyData)
# // Step 4: Recode variable names, sort data frame, and code labels for plot
chartData$last_hs_name <- gsub(" High School", "", chartData$last_hs_name)
chartData$last_hs_name <- gsub(" ", "\n", chartData$last_hs_name)
# chartData %<>% filter(persist_pattern != "Not persisting")
chartData %<>% arrange(persist_pattern)
chartData <- as.data.frame(chartData)
chartData$persist_pattern <- factor(as.character(chartData$persist_pattern),
ordered = TRUE,
levels = c("Switched to 4-Year College",
"Switched to 2-Year College",
"Persisted at 2-Year College",
"Persisted at 4-Year College"))
## ----E2plot--------------------------------------------------------------
# // Step 5: Prepare plot for 2-year colleges
p1 <- ggplot(chartData[chartData$groupVar == "2-year College",],
aes(x = reorder(last_hs_name, rankRate),
y = persistRate, group = persist_pattern,
fill = persist_pattern)) +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0),
label = percent, breaks = seq(0, 1, 0.2)) +
geom_bar(stat = 'identity', position = 'stack',
color = I("black")) +
geom_text(aes(label = round(persistRate * 100, 0)),
position = position_stack(vjust = 0.5)) +
geom_text(aes(label = round(rankRate * 100, 0), y = rankRate), vjust = -0.7) +
guides(fill = guide_legend("", keywidth = 2, nrow = 2)) +
scale_fill_brewer(type = "qual", palette = 1) +
labs(x = "", y = "Percent of Seamless Enrollers") +
theme_classic() + theme(axis.text.x = element_text(angle = 30, vjust = 0.2),
axis.ticks.x = element_blank(),
legend.position = c(0.3, 0.875),
plot.caption = element_text(hjust = 0, size = 7)) +
labs(subtitle = "Seamless Enrollers at 2-year Colleges",
caption = paste0(
"Sample: 2007-2008 through 2008-2009 Agency high school graduates.\n",
"Postsecondary enrollment outcomes from NSC matched records. \n",
"All other data from agency administrative records"))
# // Step 6: Prepare plot for 4-year colleges by replacing data in plot
# above with 4 year data
p2 <- p1 %+% chartData[chartData$groupVar == "4-year College",] +
labs(subtitle = "Seamless Enrollers at 4-year Colleges")
# // Step 7: Print out plots with labels
grid.arrange(grobs= list(p2, p1), nrow=1,
top = "College Persistence by High School")
## ----E3filterAndSort-----------------------------------------------------
# // Step 1: Keep students in high school graduation cohorts you can observe
# enrolling in college the fall after graduation
plotdf <- cgdata %>% filter(chrt_grad >= chrt_grad_begin &
chrt_grad <= chrt_grad_end) %>%
select(sid, chrt_grad, enrl_1oct_grad_yr1_2yr, enrl_1oct_grad_yr1_4yr,
enrl_1oct_grad_yr1_any, enrl_1oct_grad_yr2_2yr, enrl_1oct_grad_yr2_4yr,
enrl_1oct_grad_yr2_any, enrl_grad_persist_any,
enrl_grad_persist_2yr, enrl_grad_persist_4yr,
first_college_name_any, first_college_name_2yr, first_college_name_4yr)
# // Step 2: Indicate the number of institutions you would like listed
num_inst <- 5
## ----E3reshapeAndCalculate-----------------------------------------------
# // Step 3: Calculate the number and % of students enrolled in each college
# the fall after graduation, and the number and % of students persisting, by
# college type
chart4year <- bind_rows(
plotdf %>% group_by(first_college_name_4yr) %>%
summarize(enrolled = sum(enrl_1oct_grad_yr1_4yr, na.rm=TRUE),
persisted = sum(enrl_grad_persist_4yr, na.rm=TRUE)) %>%
ungroup %>%
mutate(total_enrolled = sum(enrolled)) %>%
mutate(perEnroll = round(100 * enrolled/total_enrolled, 1),
perPersist = round(100 * persisted/enrolled, 1)),
plotdf %>%
summarize(enrolled = sum(enrl_1oct_grad_yr1_4yr, na.rm=TRUE),
persisted = sum(enrl_grad_persist_4yr, na.rm=TRUE),
first_college_name_4yr = "All 4-Year Colleges") %>%
ungroup %>%
mutate(total_enrolled = sum(enrolled)) %>%
mutate(perEnroll = round(100 * enrolled/total_enrolled, 1),
perPersist = round(100 * persisted/enrolled, 1))
)
chart2year <- bind_rows(plotdf %>% group_by(first_college_name_2yr) %>%
summarize(enrolled = sum(enrl_1oct_grad_yr1_2yr, na.rm=TRUE),
persisted = sum(enrl_grad_persist_2yr, na.rm=TRUE)) %>%
ungroup %>%
mutate(total_enrolled = sum(enrolled)) %>%
mutate(perEnroll = round(100 * enrolled/total_enrolled, 1),
perPersist = round(100 * persisted/enrolled, 1)),
plotdf %>%
summarize(enrolled = sum(enrl_1oct_grad_yr1_2yr, na.rm=TRUE),
persisted = sum(enrl_grad_persist_2yr, na.rm=TRUE),
first_college_name_2yr = "All 2-Year Colleges") %>%
ungroup %>%
mutate(total_enrolled = sum(enrolled)) %>%
mutate(perEnroll = round(100 * enrolled/total_enrolled, 1),
perPersist = round(100 * persisted/enrolled, 1))
)
## ----E3createTables, results='markup'------------------------------------
# // Step 4: Create tables
chart4year %>% arrange(-enrolled) %>%
select(first_college_name_4yr, enrolled, perEnroll, persisted, perPersist) %>%
head(num_inst) %>%
kable(., col.names = c("Name", "Number Enrolled",
"% Enrolled", "Number Persisted",
"% Persisted"))
chart2year %>% arrange(-enrolled) %>%
select(first_college_name_2yr, enrolled, perEnroll, persisted, perPersist) %>%
head(num_inst) %>%
kable(., col.names = c("Name", "Number Enrolled",
"% Enrolled", "Number Persisted",
"% Persisted"))
|
9eda8df38f5606c71cc4fc21d9ca96d7bb2bfdf5
|
a6765365e0283e55d08318b82edce354c8a1f803
|
/R/print.R
|
fb5f3dc22484b7ea6686b99bba86456d485569bf
|
[] |
no_license
|
cran/CAST
|
4d0eaf33b479ae2dd92510cb5386742875d92560
|
5a87830535f3e7c1a720e4665c18db0083cdb486
|
refs/heads/master
| 2023-06-09T19:24:56.320841
| 2023-05-30T11:00:06
| 2023-05-30T11:00:06
| 116,807,860
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,180
|
r
|
print.R
|
#' Print CAST classes
#' @description Generic print function for trainDI and aoa
#' @name print
#' @param x trainDI object
#' @param ... other params
#' @export
print.trainDI = function(x, ...){
cat(paste0("DI of ", nrow(x$train), " observation \n"))
cat(paste0("Predictors:"), x$variables, "\n\n")
cat("AOA Threshold: ")
cat(x$threshold)
}
#' @name print
#' @param x trainDI object
#' @param ... other params
#' @export
show.trainDI = function(x, ...){
print.trainDI(x)
}
#' @name print
#' @param x aoa object
#' @param ... other params
#' @export
print.aoa = function(x, ...){
cat("DI:\n")
print(x$DI)
cat("AOA:\n")
print(x$AOA)
cat("\n\nPredictor Weights:\n")
print(x$parameters$weight)
cat("\n\nAOA Threshold: ")
cat(x$parameters$threshold)
}
#' @name print
#' @param x aoa object
#' @param ... other params
#' @export
show.aoa = function(x, ...){
print.aoa(x)
}
#' @name print
#' @param x An object of type \emph{nndm}.
#' @param ... other arguments.
#' @export
print.nndm <- function(x, ...){
mean_train <- round(mean(sapply(x$indx_train, length)), 2)
min_train <- round(min(sapply(x$indx_train, length)), 2)
cat(paste0("nndm object\n",
"Total number of points: ", length(x$Gj), "\n",
"Mean number of training points: ", mean_train, "\n",
"Minimum number of training points: ", min_train, "\n"))
}
#' @name print
#' @param x An object of type \emph{nndm}.
#' @param ... other arguments.
#' @export
show.nndm = function(x, ...){
print.nndm(x)
}
#' @name print
#' @param x An object of type \emph{knndm}.
#' @param ... other arguments.
#' @export
print.knndm <- function(x, ...){
cat(paste0("knndm object\n",
"Clustering algorithm: ", x$method, "\n",
"Intermediate clusters (q): ", x$q, "\n",
"W statistic: ", round(x$W, 4), "\n",
"Number of folds: ", length(unique(x$clusters)), "\n",
"Observations in each fold: "),
table(x$clusters), "\n")
}
#' @name print
#' @param x An object of type \emph{knndm}.
#' @param ... other arguments.
#' @export
show.knndm = function(x, ...){
print.knndm(x)
}
|
8b5e7417e7a8acd8795cce225a23d837e32b67f7
|
3eb206214b32e32f19a134e17f9194f586d2ca48
|
/scripts/lda.R
|
d93d6bbe762e7c26553cdb60d722deac4aaa5e61
|
[] |
no_license
|
nfraccaroli/text_mining_workshop
|
9acb8a7760d4d9e06bea57116d928b5c9ac2a25d
|
b059c74b04672b6d1bb386bf9185116cdfd516f2
|
refs/heads/master
| 2020-06-18T08:20:48.311751
| 2019-02-26T16:00:56
| 2019-02-26T16:00:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,487
|
r
|
lda.R
|
library(tidyverse)
library(gtools)
library(topicmodels)
library(tidytext)
rcat <- function(n, x, p) {
sample(x, size = n, replace = TRUE, prob = p)
}
generate_document <- function(z, k, w, beta) {
w <- map(seq_len(k), ~rcat(n = z[.], x = w, beta[[.]]))
flatten_chr(w)
}
generate_corpus <- function(M, k, lambda, alpha, w, beta) {
tibble(
d = seq_len(M),
N = rpois(M, lambda),
t = map(d, ~rdirichlet(1, alpha)[1, ]),
z = map2(N, t, ~rmultinom(1, .x, .y)[, 1]),
w = map(z, ~generate_document(., k, w, beta))
)
}
ps <- list(
M = 50,
k = 3,
lambda = 300,
alpha = c(1, 1, 1),
beta = tribble(
~w, ~z1, ~z2, ~z3,
"1_HICP", .9, .0, .0,
"2_GDP", .1, .9, .0,
"3_NPLs", .0, .1, .9,
"4_bank", .0, .0, .1
)
)
set.seed(2)
df <- generate_corpus(ps$M, ps$k, ps$lambda, ps$alpha, ps$beta$w, ps$beta[, -1])
dtm <- df %>%
unnest(w) %>%
count(d, w) %>%
cast_dtm(d, w, n)
k <- 3
lda <- LDA(dtm, k, control = list(seed = 1))
# Word distributions ("betas") successfully recovered
tidy(lda, "beta") %>%
spread(topic, beta) %>%
rename(z1 = `1`, z2 = `3`, z3 = `2`) %>%
select(term, z1, z2, z3) %>%
mutate_if(is.numeric, ~round(., 1))
lda_gamma_wide <- tidy(lda, matrix = "gamma") %>%
spread(topic, gamma) %>%
rename(d = document, z1 = `1`, z2 = `3`, z3 = `2`) %>%
mutate(d = as.numeric(d)) %>%
arrange(d) %>%
select(d, z1, z2, z3)
# Distribution of topics balanced across documents
# (corresponding to specified alpha parameter)
lda_gamma_wide %>%
gather(topic, gamma, -d) %>%
group_by(topic) %>%
summarise(m = mean(gamma))
df_gamma <- df %>%
mutate(topic = map(d, ~c("z1", "z2", "z3"))) %>%
unnest(t, topic) %>%
rename(gamma = t)
df_compare <- inner_join(
df_gamma,
gather(lda_gamma_wide, topic, gamma, -d),
by = c("d" = "d", "topic" = "topic")
)
# Topic distributions ("gammas") successfully recovered
p_lda_comparison <-
ggplot(df_compare, aes(gamma.x, gamma.y)) +
geom_abline(slope = 1, intercept = 0, color = "red", size = 0.1) +
geom_text(aes(label = d), size = 0.75, alpha = 0.75, color = "blue") +
facet_wrap(~topic) +
xlim(0, 1) +
ylim(0, 1) +
coord_equal() +
theme_light(4) +
labs(x = "Actual topic share", y = "Predicted topic share",
title = "LDA successfully recovering simulated topic shares",
subtitle = "Numbers denote document IDs in corpus")
ggsave("images/p_lda_comparison.png", p_lda_comparison, width = 2, height = 1)
|
2c21d3c660ba15c2cd86d3293068b580f1e278e5
|
35ccbe210f6b7df79bfd94ef3b9139433318bc57
|
/DTMbvs/R/bfdr.R
|
4839384dae26f33847eb073436cfdd0d32c0fda7
|
[] |
no_license
|
mkoslovsky/DTMbvs
|
56caea7c00fbaa884ff85d5bc95a1aa90f535542
|
663cf6a31a4cc52e0bcba6c48fedac3e6ed63dda
|
refs/heads/master
| 2020-04-13T12:39:34.859566
| 2020-02-20T18:02:11
| 2020-02-20T18:02:11
| 163,208,780
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 821
|
r
|
bfdr.R
|
bfdr <- function( mppi_vector, threshold = 0.1 ){
# Courtesy of D.Wadsworth
# arg checking
if( any( mppi_vector > 1 | mppi_vector < 0 ) ){
stop("Bad input: mppi_vector should contain probabilities")
}
if( threshold > 1 | threshold < 0 ){
stop( "Bad input: threshold should be a probability" )
}
# sorting the ppi's in decresing order
sorted_mppi_vector <- sort( mppi_vector, decreasing = TRUE )
# computing the fdr
fdr <- cumsum( ( 1 - sorted_mppi_vector ) )/seq( 1:length( mppi_vector ) )
# determine index of the largest fdr less than threshold
thecut.index <- max( which( fdr < threshold ) )
ppi_threshold <- sorted_mppi_vector[ thecut.index ]
selected <- mppi_vector > ppi_threshold
return( list( selected = selected, threshold = ppi_threshold ) )
}
|
780e75242053193db4cc666d5db0a7823658fee1
|
7a40d3f515979e7ae3e141299fc53114f1b69a0c
|
/man/plot.CMBWindow.Rd
|
966b23757b57a6991743ae41af5a4f9637904b06
|
[
"MIT"
] |
permissive
|
mingltu/rcosmo
|
491ad4bc3a29a583852bfc88d66492d97948b419
|
76727be295b54642a357a0cf9b527ae25f2c5254
|
refs/heads/master
| 2021-04-09T12:59:10.889777
| 2018-03-15T09:14:25
| 2018-03-15T09:14:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,327
|
rd
|
plot.CMBWindow.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/CMBWindowGenerics.R
\name{plot.CMBWindow}
\alias{plot.CMBWindow}
\title{visualise a \code{\link{CMBWindow}}}
\usage{
\method{plot}{CMBWindow}(win, add = TRUE, type = "l", col = "red",
size = 2, box = FALSE, axes = FALSE, aspect = FALSE, back.col, ...)
}
\arguments{
\item{win}{a CMBWindow}
\item{add}{if TRUE then this plot will be added to any existing plot.
Note that if \code{back.col} (see below) is specified then a new plot
window will be opened and \code{add = TRUE} will have no effect}
\item{type}{a single character indicating the type of item to plot.
Supported types are: 'p' for points, 's' for spheres, 'l' for lines,
'h' for line segments from z = 0, and 'n' for nothing.}
\item{col}{specify the colour(s) of the plotted points}
\item{size}{the size of plotted points}
\item{box}{whether to draw a box}
\item{axes}{whether to draw axes}
\item{aspect}{either a logical indicating whether to adjust the
aspect ratio, or a new ratio.}
\item{back.col}{specifies the background colour of
the plot. This argument is passed to rgl::bg3d.}
\item{...}{arguments passed to rgl::plot3d}
\item{eps}{the geodesic distance between consecutive points to draw
on the window boundary}
}
\description{
visualise a \code{\link{CMBWindow}}
}
|
769ca88a9a5525263ee3c336d3bd039bb8779cb4
|
9aafde089eb3d8bba05aec912e61fbd9fb84bd49
|
/codeml_files/newick_trees_processed/1779_1/rinput.R
|
4ee25673f19ec61f3e349f6afd35794245b99040
|
[] |
no_license
|
DaniBoo/cyanobacteria_project
|
6a816bb0ccf285842b61bfd3612c176f5877a1fb
|
be08ff723284b0c38f9c758d3e250c664bbfbf3b
|
refs/heads/master
| 2021-01-25T05:28:00.686474
| 2013-03-23T15:09:39
| 2013-03-23T15:09:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 135
|
r
|
rinput.R
|
library(ape)
testtree <- read.tree("1779_1.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="1779_1_unrooted.txt")
|
316d27a35189b2c8823548c61c3eb801cf22c35d
|
51703d55be207df29decc17441c323be93b8adaf
|
/HW11/Solutions/4.R
|
24765f49dc161b64c87d3ff20064a444eef6cbbf
|
[] |
no_license
|
Mahbodmajid/DataAnalysis
|
b4ee16f39e91dff0bbeea058e92162f91f28d84c
|
127e59a101d4847171fcb7728db38f4405a10e38
|
refs/heads/master
| 2021-06-10T02:04:52.153255
| 2019-11-25T00:58:18
| 2019-11-25T00:58:18
| 141,756,223
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 981
|
r
|
4.R
|
iequake %>%
select(time = OriginTime, mag = Mag) %>%
as.data.frame() %>%
filter(mag >= 7) %>%
mutate(year = as.numeric(format(time,"%Y")), month = as.numeric(format(time,"%m"))) %>%
select(-mag, -time)-> iequake_big
disaster %>%
filter(COUNTRY == "IRAN") %>%
select(year = YEAR, month = MONTH, mag = EQ_PRIMARY) %>%
filter(mag >= 7) %>%
as.data.frame() %>%
select(-mag)-> dis_iran
union(dis_iran, iequake_big) %>%
as.data.frame() %>%
arrange(-year, -month) %>%
mutate(month_from_before = month - lead(month) + 12 * (year - lead(year))) %>%
filter(year >= 1900) -> last_eqs
last_eqs[1,] %>% kable()
12*(as.numeric(format(Sys.time(),"%Y"))- last_eqs[1,]$year) +
as.numeric(format(Sys.time(),"%m")) - last_eqs[1,]$month -> months_past_from_last
(months_past_from_last + 60) -> desired_distance
last_eqs$month_from_before -> distances
paste0("probability: ", round(sum(distances <= desired_distance) / sum(!is.na(distances)),2))
|
5adb1d72dca79bf289ce97a8bb9b9f20e700b93b
|
79757a94409e5ef29c2ee181fc914e0fc76b34d8
|
/DNN, LSTM, Random Forest/Random Forest for Feature Selection.R
|
2ee3550374ed0732af7dab845c0158103c76ebc6
|
[] |
no_license
|
2ky1234/K-water-Bigdata-Contest
|
2cee59e64629e8d7b746a36c6a409a8c40f2b2bc
|
2b07ec4e82897cfc8bef6a863a0fd9072c775ee2
|
refs/heads/main
| 2023-05-14T06:03:33.747582
| 2021-06-10T13:40:35
| 2021-06-10T13:40:35
| 375,031,065
| 3
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,812
|
r
|
Random Forest for Feature Selection.R
|
library(randomForest)
library(dotCall64)
library(dplyr)
library(readr)
library(e1071)
gc()
rm(list=ls())
rm()
memory.limit(30000)
### 종속변수인
db <- read_csv('C:/Users/FESUB/Desktop/수자원 공모전/raw_river.csv')
##### 모델링
db_set <- db
## 샘플링
db_set$index <- 1:nrow(db_set)
db_set <- db_set %>% filter(db_set$index%%5==1)
db_set <- db_set[,-1]
db_set <- db_set[,-1]
db_set$ITEM_TEMP <- as.numeric(db_set$ITEM_TEMP)
db_set <- db_set %>% mutate_if(is.character, as.factor)
db_set <- round(db_set,digits=3)
# db_set <- as.data.frame(db_set)
#names(db_set)
# 변수개수를 전체변수 수의 제곱근으로 지정
db_set$ITEM_SS <- as.numeric(db_set$ITEM_SS)
mtrynum <- round(sqrt(ncol(db_set)))
model <- randomForest(ITEM_SS~., data=db_set, importance=TRUE, ntree=300, mtry=mtrynum, proximity=TRUE,na.action=na.omit)
model
summary(model)
#importance(model)
#varImpPlot(model, main="Importance of variables")
##### 저장
# importance of variables 저장/변수명 매칭
# matching <- read.csv("C:/Users/FESUB/Desktop/수자원 공모전/MATCHING.csv")
# matching$var <- as.character(matching$var)
a <- as.data.frame(importance(model))
a$var <- rownames(a)
#
# a_MDA <- a %>% select(c(var,MeanDecreaseAccuracy)) %>% arrange(desc(MeanDecreaseAccuracy)) %>% head(20)
# a_MDA <- left_join(a_MDA, matching, by="var")
# a_MDA <- subset(a_MDA, select=c(var, info, MeanDecreaseAccuracy))
# a_MDG <- a %>% select(c(var,MeanDecreaseGini)) %>% arrange(desc(MeanDecreaseGini)) %>% head(20)
# a_MDG <- left_join(a_MDG, matching, by="var")
# a_MDG <- subset(a_MDG, select=c(var, info, MeanDecreaseGini))
#
# imp_var <- bind_cols(a_MDA, a_MDG)
# 중요변수 저장
setwd("C:/Users/FESUB/Desktop/수자원 공모전/")
write.csv(imp_var, file="MS_importtance of variables.csv")
b <- a$var
|
168325cb73fea4c4cf2a4fd1a3e5df1e9f673222
|
3440f140c8fe9ef31a4e770be349523659880876
|
/run_clustering.R
|
23a1b44d328154eddc6c4951951a05ce5d682ba4
|
[] |
no_license
|
Rene-Gutierrez/BayTenPreClu_project
|
27651fa0160b86eb5a9c7b41aea24fa7c77f9088
|
9b0d29ee5cd63e0d58221a94987fe768612dd49a
|
refs/heads/master
| 2022-11-07T06:49:59.408905
| 2020-06-17T21:07:43
| 2020-06-17T21:07:43
| 273,078,712
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,477
|
r
|
run_clustering.R
|
###############################################################################
###
### Simulated Data Generation for Mixture Tensor Graphical Models and
### Clustering
###
###############################################################################
### Set-up
set.seed(240221)
library(BayTenPreClu)
library(BayTenGraMod)
library(Matrix)
library(Tlasso)
library(pheatmap)
### Parameter Settings
ii <- 1 # Replication Number
p <- c(40, 50, 60) # Matrix size for each dimension
d <- length(p) # Number of tensor dimensions
r <- c(0.15, 0.10, 0.05) # Sparity level for Random Matrices Only
l <- c(1/4, 1/4, 1/4, 1/4) # Mixture Weights
b <- 103 # Degrees of Freedom for Precision Matrices
n <- 100 # Number of Observations
nmcmc <-1000 # Number of MCMC samples
burnin <- 100 # Burn-In Period
theta <- 1 # Dirichlet Process Prior Parameter
### General Suffix
suffix <- paste0(p[1], "-", p[2], "-", p[3], "-",
r[1], "-", r[2], "-", r[3], "-",
l[1], "-", l[2], "-", l[3], "-",
n, "-", nmcmc, "-", burnin, "-", ii)
### Generates the Precision, Covariance and Adjacency matrix for each
### component
## Number of Components
H <- length(l)
K <- length(p)
PSE <- list()
for(h in 1:H){
PSE[[h]] <- spaPreMatGen(p = p,
type = "R",
sparsity = r,
covariance = FALSE)
}
### Identity list
I <- list()
for(i in 1:K){
I[[i]] <- diag(p[i])
}
### Asigns each Matrix List
O <- list()
S <- list()
E <- list()
for(h in 1: H){
O[[h]] <- PSE[[h]]$P
S[[h]] <- PSE[[h]]$S
E[[h]] <- PSE[[h]]$E
}
# Generates the Samples
print("Creating Samples")
## Initialization of Cample Tensor List
lT <- list()
## Component mebership
zT <- matrix(data = NA, nrow = n, ncol = H)
zF <- matrix(data = NA, nrow = n, ncol = H)
zF2 <- matrix(data = NA, nrow = n, ncol = 2)
zF5 <- matrix(data = NA, nrow = n, ncol = 5)
## Component membership by Category
zTC <- numeric(n)
zFC <- numeric(n)
zFC2 <- numeric(n)
zFC5 <- numeric(n)
for(i in 1:n){
## Component Membership
zT[i,] <- rmultinom(n = 1,
size = 1,
prob = l)
## Component Membership (Fake)
zF[i,] <- rmultinom(n = 1,
size = 1,
prob = l)
zF2[i,] <- rmultinom(n = 1,
size = 1,
prob = rep(1/2, 2))
zF5[i,] <- rmultinom(n = 1,
size = 1,
prob = rep(1/5, 5))
## By Category
zTC[i] <- which(zT[i,] == 1)
zFC[i] <- which(zF[i,] == 1)
zFC2[i] <- which(zF2[i,] == 1)
zFC5[i] <- which(zF5[i,] == 1)
## Samples According to the Category
lT[[i]] <- TNormalSampler(n = 1,
SigmaList = S[[zTC[i]]])[[1]]
}
### Computes the K-mode Matricization of each tensor and takes its covariance matrix for each mode and tensor
kCov <- list()
### For every mode
for(k in 1:K){
kM <- matrix(data = NA, nrow = p[k] * p[k], ncol = n)
### For Every tensor
for(i in 1:n){
kM[,i] <- as.vector(cov(kModMat(tensor = lT[[i]], mode = k)))
}
kCov[[k]] <- kM
}
### Runs the Stochastic Search Clustering
iP <- list()
iP[[1]] <- seq(1,n)
out <- PMBTC(iP = iP,
theta = theta,
kPseCov = kCov,
burnin = burnin,
nmcmc = nmcmc,
progress = TRUE)
### Computes the Probability Matrix
pM <- proMat(sP = out[(burnin + 1):(nmcmc + burnin)],
n = n)
## Cluster Distribution
### Cluster Number Initialization
cluNum <- numeric(length = nmcmc)
### Obtains the Number of Clusters
for(i in (burnin + 1):(burnin + nmcmc)){
cluNum[i] <- length(out[[i]])
}
# ARI Distribution
## Clusters
samClu <- out[101:1100]
reaClu <- list()
for(i in 1:3){
reaClu[[i]] <- seq(1:n)[zTC == i]
}
## ARI Samples
ariSam <- numeric(length = nmcmc)
## Computes the ARI for Each Sample
for(i in 1:nmcmc){
ariSam[i] <- ari(clu1 = samClu[[i]],
clu2 = reaClu)
}
# Partition Point Estimate
## Gets the Partition Estimate
estPar <- salso::salso(psm = pM / nmcmc)$estimate
## Builds the Clustering List
estClu <- list()
for(i in 1:max(estPar)){
estClu[[i]] <- seq(1:n)[estPar == i]
}
## ARI of the Best Estimate
ariEst <- ari(clu1 = reaClu, clu2 = estClu)
|
0e82afdd8e4ccd4309d20fed382fc54d3f37b021
|
b44032d37210f23d97d40420cf3547daa269ab97
|
/man/config_write_dummy.Rd
|
047d4b896d0d6b8af82cc764b9322bb556628ac9
|
[
"MIT"
] |
permissive
|
KWB-R/kwb.qmra
|
227c4a5d1ef1eb9bb2c863ab7a299175a46d6109
|
9e096057da37bf574626c60e9ad524dff0b1d89a
|
refs/heads/master
| 2022-07-02T08:21:21.895235
| 2021-06-14T20:28:22
| 2021-06-14T20:28:22
| 68,301,647
| 19
| 3
|
MIT
| 2022-06-08T14:10:17
| 2016-09-15T14:32:15
|
R
|
UTF-8
|
R
| false
| true
| 547
|
rd
|
config_write_dummy.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/config.R
\name{config_write_dummy}
\alias{config_write_dummy}
\title{Config: create dummy configuration}
\usage{
config_write_dummy(
confDir = system.file("extdata/configs/dummy", package = "kwb.qmra")
)
}
\arguments{
\item{confDir}{directory to save the dummy configuration files (Default:
system.file('extdata/config', package = 'kwb.qmra')")}
}
\value{
writes dummy configuration in confDir
}
\description{
Config: create dummy configuration
}
|
9b5047ea0bdcb808350926607d1fa2521da453da
|
5a5fd1f2f42fc8a83e18a42af87f81c125398913
|
/R/rsu.sssep.rsfreecalc.R
|
a9d977bd2513d8a8a0beef9092d1ed1f31a76e8e
|
[] |
no_license
|
cran/epiR
|
0c40ed842d2ee1af5f200ebab0916c78024725e2
|
c842d523e9277e7b8036f17cfefcac3e9cb85b42
|
refs/heads/master
| 2023-08-18T17:36:15.747432
| 2023-08-15T09:20:05
| 2023-08-15T10:30:53
| 17,695,822
| 8
| 4
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,845
|
r
|
rsu.sssep.rsfreecalc.R
|
rsu.sssep.rsfreecalc <- function(N, pstar, mse.p = 0.95, msp.p = 0.95, se.u, sp.u, method = "hypergeometric", max.ss = 32000){
type1 <- 1 - mse.p
type2 <- 1 - msp.p
pstar <- ifelse(pstar < 1, pstar, pstar / N)
N1 <- min(N, max.ss)
brks <- c(50, 100, 1000, 5000, 10000, Inf)
# brks <- c(50, 100, 1000, 5000, 10000, 50000, Inf)
steps <- c(5, 10, 50, 100, 200)
step <- steps[which(N1 < brks)[1]]
ss <- seq(from = 0, to = N1, by = step)
ss[1] <- 1
if (length(ss) == 1) ss[2] <- N1
cp <- c()
SeH <- c()
SpH <- c()
P1 <- c()
success <- FALSE
for(s in 1:length(ss)){
tmp <- zget.cp(ss[s], se.u, sp.u, type2)
cp[s] <- tmp[[1]]
SpH[s] <- tmp[[2]]
if(method == "hypergeometric"){
P1[s] <- 1 - rsu.sep.rsfreecalc(N = N, n = ss[s], c = cp[s], pstar = pstar, se.u = se.u, sp.u = sp.u)
} else{
P1[s] <- 1 - zsep.binom.imperfect(n = ss[s], c = cp[s], se = se.u, sp = sp.u, pstar = pstar)
}
SeH[s] <- 1 - P1[s]
cp[s] <- cp[s] - 1
if(P1[s] <= type1) {
success <- TRUE
n1 <- ss[s]
break
}
}
if(success == TRUE){
# Sample sizes to evaluate in addition to those already done:
ss[(s + 1):(s + step)] <- (ss[s - 1] + 1):(ss[s - 1] + step)
# Step through each of the additional sample size estimates:
for(x in 1:step){
# s equals the number of candidate sample sizes used to see if a solution could be found
tmp <- zget.cp(n.cp = ss[s + x], se = se.u, sp = sp.u, type2 = type2)
cp[s + x] <- tmp[[1]]
SpH[s + x] <- tmp[[2]]
if(method == "hypergeometric"){
P1[s + x] <- 1 - rsu.sep.rsfreecalc(N = N, n = ss[s + x], c = cp[s + x], pstar = pstar, se.u = se.u, sp.u = sp.u)
} else{
P1[s + x] <- 1 - zsep.binom.imperfect(n = ss[s + x], c = cp[s + x], se = se.u, sp = sp.u, pstar = pstar)
}
SeH[s + x] <- 1 - P1[s + x]
# Subtract one from the calculated number of cutpoints.
cp[s + x] <- cp[s + x] - 1
if(P1[s + x] <= type1){
success <- TRUE
n1 <- ss[s + x]
break
}
}
# Summary:
rval1 <- data.frame(n = n1, N = N, c = cp[s + x], pstar = pstar, p1 = P1[s + x], se.p = SeH[s + x], sp.p = SpH[s + x])
# Number of elements in detail data frame:
# ne <- length(seq(from = 1, to = N1, by = step)) + x
# Changed MS 011020:
ne <- s + x
rval2 <- data.frame(n = ss[1:ne], c = cp, p = P1, se.p = SeH, sp.p = SpH)
# Sort in order of n:
rval2 <- rval2[sort.list(rval2$n),]
rval <- list(summary = rval1, details = rval2)
}
else{
rval <- "Unable to achieve required accuracy by sampling every unit"
}
return(rval)
}
|
97c4b2b1e43618dd42e97dc1ffae81a4475c0b10
|
1bf4bc16ae1e516b82788227118778f9fa008dda
|
/HJA_scripts/12_sjsdm_general_model_outputs/old/kelpie_sjsdm/sjsdm_model.r
|
4b4ebe772f5be06c7ef668cb63040a2565eb767f
|
[
"MIT"
] |
permissive
|
dougwyu/HJA_analyses_Kelpie
|
93b6b165e4d2de41f46bacd04c266afa7af0541e
|
4ab9de1072e954eac854a7e3eac38ada568e924b
|
refs/heads/master
| 2021-11-03T19:45:17.811298
| 2021-10-26T09:45:15
| 2021-10-26T09:45:15
| 245,229,951
| 1
| 1
|
MIT
| 2021-09-10T07:19:04
| 2020-03-05T17:44:55
|
HTML
|
UTF-8
|
R
| false
| false
| 19,531
|
r
|
sjsdm_model.r
|
# Yuanheng
# create: Mar 23, 2020
# last modified: Apr , 2020
# apply sj-sdm & hmsc
# with data (in'data_Feb_25/', 'kelpie20200214')
# revised working directory code
library(here)
here() # this reads working directory as the pathname of the 9_ecological_analyses.Rproj file. It therefore varies transparently from user to user. You can then use 'here' as a drop-in for file.path(), as i show below
# [1] "/Users/Negorashi2011/Dropbox/Working_docs/Luo_Mingjie_Oregon/HJA_analyses_Kelpie/HJA_scripts/9_ecological_analyses"
# .................................................................
# rm(list=ls())
# setwd("/media/yuanheng/SD-64g2/files/Projects/Oregon")
# getwd()
source('R/source/sjsdm_function.r')
# missing from repo
lapply(c("ggplot2", "gridExtra",'vegan', 'labdsv','tidyverse','scatterplot3d', 'gridBase','grid', 'ggcorrplot', 'here'),library,character.only=T)
lapply(c('Hmsc','sjSDM', 'reticulate'),library, character.only=T)
# ...................... kelpie, lidar data ..............................
# (lidar data)
# lidar.env = read.csv('kelpie/lidar_data/biodiversity_site_info_multispectral_2020-04-13.txt', header=T, sep=',', stringsAsFactors = F, na.strings='NA')
lidar.env = read.csv(here("..", "10_eo_data", "biodiversity_site_info_multispectral_2020-04-13.txt"), header=T, sep=',', stringsAsFactors = F, na.strings='NA') # this formulation works on any computer with RStudio
str(lidar.env)
# ('data_Feb_25' folder)
# otu.env1.noS = read.csv('kelpie/data_Feb_25/sample_by_species_table_F2308_minimap2_20200221_kelpie20200214.csv', header=T, sep=',', stringsAsFactors = F, na.strings='NA')
otu.env1.noS = read.csv(here("..", "..", "Kelpie_maps", "outputs_minimap2_20200221_F2308_f0x2_q48_kelpie20200214_vsearch97", "sample_by_species_table_F2308_minimap2_20200221_kelpie20200214.csv"), header=T, sep=',', stringsAsFactors = F, na.strings='NA')
# otu.env1.spike = read.csv('kelpie/data_Feb_25/sample_by_species_corr_table_F2308_minimap2_20200221_kelpie20200214.csv', header=T, sep=',', stringsAsFactors = F, na.strings='NA')
otu.env1.spike = read.csv(here("..", "..", "Kelpie_maps", "outputs_minimap2_20200221_F2308_f0x2_q48_kelpie20200214_vsearch97", "sample_by_species_corr_table_F2308_minimap2_20200221_kelpie20200214.csv"), header=T, sep=',', stringsAsFactors = F, na.strings='NA')
print(c(dim(otu.env1.spike), dim(otu.env1.noS)))
# 1173-26, more otus
names(otu.env1.noS)[1:26] == names(otu.env1.spike)[1:26]
names(otu.env1.noS)[1:26]=c('SiteName', 'UTM_E','UTM_N','old.growth.str', 'yrs.disturb','point.ID','poly.ID','AGENCY','unit.log', 'name.log','log.yr','yrs.log.2018','log.treat','yrs.disturb.level', 'elevation','canopy.ht','min.T','max.T', 'precipitation','metre.road', 'metre.stream', 'yrs.disturb.min','hja','trap','session','site_trap_period')
names(otu.env1.spike)[1:26]=names(otu.env1.noS)[1:26]
str(otu.env1.spike[,1:27])
# ........ formate lidar.env .......
sort(lidar.env$SiteName) == sort(unique(otu.env1.spike$SiteName))
#NDVI - normalized difference vegetation index (calculated using bands 4 and 5): NDVI = (NearIR-Red)/(NearIR+Red)
# these values should range between -1 and 1. Values in these columns should be divided by 1000
#EVI - enhanced vegetation index (calculated using bands 4, 5, and 2): 2.5 * ((Band 5 – Band 4) / (Band 5 + 6 * Band 4 – 7.5 * Band 2 + 1))
# the values in these columns should be divided by 1000
names(lidar.env) #sort()
# 4 NDVI, 4 EVI
data.frame(lidar.env$nor.NDVI_20180717, lidar.env$EVI_20180818)
a = lidar.env %>% select(13,14,27,28,41,42,55,56) %>% rename(nor.NDVI_20180717=1, nor.EVI_20180717=2, nor.NDVI_20180726=3, nor.EVI_20180726=4, nor.NDVI_20180802=5, nor.EVI_20180802=6, nor.NDVI_20180818=7, nor.EVI_20180818=8)/1000
a[,c(1,3,5,7)]
# mean of all 4 NDVI, EVI
lidar.env= cbind(lidar.env, a)
str(lidar.env)
# pdf('kelpie/R/graph/lidar_describe_EVI_NDVI.pdf', height=5, width=5)
pdf(here("..", "..", "sjSDM", "lidar_describe_EVI_NDVI.pdf"), height=5, width=5)
range(lidar.env[,60:67])
plot(1:96, lidar.env[,61], ylim=c(0,3.3),type='l', main='solid - EVI, dash - NDVI')
lines(1:96, lidar.env[,63], col='red')
lines(1:96, lidar.env[,65], col='blue')
lines(1:96, lidar.env[,67], col='green')
lines(1:96, lidar.env[,60], lty=2, col='black')
lines(1:96, lidar.env[,62], lty=2, col='red')
lines(1:96, lidar.env[,64], lty=2, col='blue')
lines(1:96, lidar.env[,66], lty=2, col='green')
dev.off()
lidar.env$mean.NDVI = base::rowMeans(lidar.env[,c(60,62,64,66)])
lidar.env$mean.EVI = base::rowMeans(lidar.env[,c(61,63,65,67)])
lidar.env[,c(60,62,64,66,68)]
lidar.env[,c(61,63,65,67,69)]
# ... explore OTU reads ...
names(otu.env1.spike)[1:27]
hist(otu.env1.spike[,30])
sort(unique(otu.env1.noS[,30]))
which(is.na(otu.env1.noS[,28]))#:dim(otu.env1.noS)[2]
which(is.na(otu.env1.noS[,29]))
# 181 237+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
saveRDS(result, file = "s-jSDM_result_s1_m1_spike2.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
table(is.na(otu.env1.noS[c(181,23
for(i in 1:7) {
model = sjSDM(X = scale.env,
Y = as.matrix(dataI.1.spike2[,-c(1:36)]),
formula = ~ elevation.scale+canopy.ht.scale+min.T.scale+max.T.scale+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
saveRDS(result, file = "R/result/s-jSDM_result_s1_m1_spike2.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
7),27:1173]))
table(is.na(otu.env1.spike[c(181,237),27:1173]))
otu.env1.noS$SiteName[c(181,237)]
# delete row 181, 237 -> "HOBO-040", "290415"
dim(otu.env1.noS)
otu.env1.noS = otu.env1.noS[-c(181,237),]
dim(otu.env1.spike)
otu.env1.spike = otu.env1.spike[-c(181,237),]
# ....... scale variables .......
a = select(otu.env1.spike,15:22)%>%rename(elevation.scale=1,canopy.ht.scale=2,min.T.scale=3, max.T.scale=4, precipitation.scale=5, metre.road.scale=6, metre.stream.scale=7, yrs.disturb.min.scale=8)%>% scale()
for(i in 1:7) {
model = sjSDM(X = scale.env,
Y = as.matrix(dataI.1.spike2[,-c(1:36)]),
formula = ~ elevation.scale+canopy.ht.scale+min.T.scale+max.T.scale+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
saveRDS(result, file = "R/result/s-jSDM_result_s1_m1_spike2.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
otu.env1.spike =+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
saveRDS(result, file = "s-jSDM_result_s1_m1_spike2.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
cbind(otu.env1.spike[,1:26], data.frame(a), otu.env1.spike[,27:dim(otu.env1.spike)[2]])
dim(otu.env1.spike)
otu.env1.noS = dplyr::left_join(otu.env1.noS, otu.env1.spike[,26:34], by=c('site_trap_period', 'site_trap_period'), copy=F)
otu.env1.noS = otu.env1.noS[,c(1:26,1174:1181,27:1173)]
str(otu.env1.noS[,1:34])
# ..... combine lidar .....
for(i in 1:7) {
model = sjSDM(X = scale.env,
Y = as.matrix(dataI.1.spike2[,-c(1:36)]),
formula = ~ elevation.scale+canopy.ht.scale+min.T.scale+max.T.scale+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
saveRDS(result, file = "R/result/s-jSDM_result_s1_m1_spike2.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
str(lidar.env)
hist(lidar.env$mean.NDVI)
hist(lidar.env$mean.EVI)
a = select(lidar.env,68:69) %>% rename(mean.NDVI.scale=1,mean.EVI.scale=2) %>% scale()
lidar.env = cbind(lidar.env,data.frame(a))
hist(lidar.env$mean.NDVI.scale)
hist(lidar.env$mean.EVI.scale)
# row 181, 237 -> "HOBO-040", "290415" in OTU datasets
lidar.env$SiteName == sort(unique(otu.env1.noS$SiteName))
otu.env1.spike = dplyr::left_join(otu.env1.spike, lidar.env[,c(1,70:71)], by=c('SiteName', 'SiteName'), copy=F)
str(otu.env1.spike[,1:37])
otu.env1.spike = otu.env1.spike[,c(1:34,1182:1183,35:1181)]
dim(otu.env1.spike)
otu.env1.noS = dplyr::left_join(otu.env1.noS, lidar.env[,c(1,70:71)], by=c('SiteName', 'SiteName'), copy=F)
str(otu.env1.noS[,1:37])
otu.env1.noS = otu.env1.noS[,c(1:34,1182:1183,35:1181)]
dim(otu.env1.noS)
write.table(otu.env1.noS, 'kelpie/data_Feb_25/lidar_sample_by_species_table_F2308_minimap2_20200221_kelpie20200214.csv', row.names=F, sep=',')
write.table(otu.env1.spike, 'kelpie/data_Feb_25/lidar_sample_by_species_corr_table_F2308_minimap2_20200221_kelpie20200214.csv', row.names=F, sep=',')
write.table(lidar.env, 'kelpie/lidar_data/sjsdm_biodiversity_site_info_multispectral_2020-04-13.csv', row.names= F, sep=',')
# ......................... subsets of data ..................................
dataI.1.spike = subset(otu.env1.spike, session == 'S1' & trap == 'M1' )
dataI.2.spike = subset(otu.env1.spike, session == 'S1' & trap == 'M2' )
print(c(dim(dataI.1.spike), dim(dataI.2.spike)))
dataII.1.spike = subset(otu.env1.spike, session == 'S2' & trap == 'M1' )
dataII.2.spike = subset(otu.env1.spike, session == 'S2' & trap == 'M2' )
print(c(dim(dataII.1.spike), dim(dataII.2.spike)))
# .... if there's all zero OTUs ....
a = data.frame(c.name=names(dataI.1.spike), zero = c(rep('env',length=36), rep('F', length= dim(dataI.1.spike)[2]-36)))
a$zero=as.character(a$zero)
for (i in 37:dim(dataI.1.spike)[2]) {
print(i)
if (sum(dataI.1.spike[,i])==0) {
a$zero[i]='T'
}
}
dataI.1.spike2 = dataI.1.spike[,c(1:36,which(a$zero=='F'))]
dataI.1.spike2[1:5,34:40]
# according to nmds, precipitation, elevation, yrs.disturb.min, old.growth.str, T, canopy.height can be used for now
# ........................ sjSDM ..............................
# ... session 1, Malaise I, spike ...
lrs = seq(-18, -1, length.out = 7);f = function(x) 2^x;lrs = f(lrs)
result = vector("list", 7)
scale.env = dataI.1.spike2[,c(1:3,24:36)]
str(scale.env)
for(i in 1:7) {
model = sjSDM(X = scale.env,
Y = as.matrix(dataI.1.spike2[,-c(1:36)]),
formula = ~ elevation.scale+canopy.ht.scale+min.T.scale+max.T.scale+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
saveRDS(result, file = "R/result/s-jSDM_result_s1_m1_spike2.RDS")
# "R/result/s-jSDM_result_s1_m1_spike.RDS" -> with all OTUs (1147)
# ... session 1, Malaise I, spike, with lidar ...
lrs = seq(-18, -1, length.out = 7);f = function(x) 2^x;lrs = f(lrs)
result = vector("list", 7)
scale.env = dataI.1.spike2[,c(1:3,24:36)]
str(scale.env)
for(i in 1:7) { #1:30
model = sjSDM(X = scale.env,
Y = as.matrix(dataI.1.spike2[,-c(1:36)]),
formula = ~ elevation.scale+min.T.scale+max.T.scale+precipitation.scale+mean.NDVI.scale+mean.EVI.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
saveRDS(result, file = "s-jSDM_result_s1_m1_spike_lidar2.RDS")
# "s-jSDM_result_s1_m1_spike_lidar.RDS" -> with all OTUs
# ... all data, spiked ...
lrs = seq(-18, -1, length.out = 30);f = function(x) 2^x;lrs = f(lrs)
result = vector("list", 30)
for(i in c(1,5,10,15,20,25,30)) { #1:30
model = sjSDM(X = scale.env,
Y = as.matrix(otu.env1.spike[,-c(1:26)]),
formula = ~ elevation.scale+canopy.ht.scale+min.T.scale+max.T.scale+precipitation.scale+metre.road.scale+metre.stream.scale+yrs.disturb.min.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result[[i]] = weights
}
saveRDS(result, file = "s-jSDM_result_otu_env1_spike.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
# . with Lidar data
str(lidar.env)
# deleted row 181, 237 -> "HOBO-040", "290415" in OTU datasets
lidar.env$SiteName == sort(unique(scale.env$SiteName))
table(scale.env$SiteName)
scale.env = dplyr::left_join(scale.env, lidar.env[,c(1,68,69)], by=c('SiteName', 'SiteName'), copy=F)
str(scale.env)
hist(scale.env$mean.NDVI)
hist(scale.env$mean.EVI)
a = select(scale.env,19:20) %>% rename(mean.NDVI.scale=1,mean.EVI.scale=2) %>% scale()
scale.env = cbind(scale.env,data.frame(a))
hist(scale.env$mean.NDVI.scale)
hist(scale.env$mean.EVI.scale)
result2 = vector("list", 30)
for(i in c(1,5,10,15,20,25,30)) { #1:30
model = sjSDM(X = scale.env,
Y = as.matrix(otu.env1.spike[,-c(1:26)]),
formula = ~ elevation.scale+min.T.scale+max.T.scale+precipitation.scale+mean.NDVI.scale+mean.EVI.scale,
learning_rate = 0.01,
iter = 100L,
step_size = 27L, l1_coefs = 0.07*lrs[i], l2_coefs = 0.03*lrs[i], # should be normally tuned...
sampling = 100L,l1_cov = lrs[i], l2_cov = lrs[i])
loss=unlist(model$logLik)
history=model$history
weights = list(beta = coef(model), sigma = getCov(model),loss=loss,history=history)
rm(model)
result2[[i]] = weights
}
saveRDS(result2, file = "s-jSDM_result_otu_env1_spike_lidar1.RDS")
#iter = 1000L, step_size = 6L, sampling = 100L, learning_rate = 0.0003
# ........................ hmsc ..............................
Y.I.1.noS = as.matrix(dataI.1.noS[,-(1:26)])
df.I.1.noS = data.frame(dataI.1.noS[,c(1:6,15:26)])
md.I.1.noS = Hmsc(Y=Y.I.1.noS, XData = df.I.1.noS, XFormula = ~yrs.disturb.min+precipitation+max.T, distr='lognormal poisson')
# fit HMSC model with Bayesian inference -> sampleMcmc
m.I.1.noS = sampleMcmc(md.I.1.noS,
thin = 5, samples = 1000,
# num of samples to obtain per chain
transient = 500*5, nChains = 2,
verbose = 500*5
)
save(m.I.1.noS, file= "m.I.1.noS")
m.I.1.noS.2 = sampleMcmc(md.I.1.noS,
thin = 5, samples = 5000,
# num of samples to obtain per chain
transient = 500*5, nChains = 3,
verbose = 500*5
)
save(m.I.1.noS.2, file= "m.I.1.noS.2")
m.I.1.noS.3 = sampleMcmc(md.I.1.noS,
thin = 5, samples = 3000,
# num of samples to obtain per chain
transient = 500*5, nChains = 3,
verbose = 500*5
)
save(m.I.1.noS.3, file= "m.I.1.noS.3")
mpost = convertToCodaObject(m.normal)
load('m.I.1.noS.3')
# .... hmsc with coordinates ....
studyDesign = data.frame(sample=as.factor(dataI.1.noS$site))
xycoords = as.matrix(dataI.1.noS[,2:3], ncol=2)
rownames(xycoords) = studyDesign$sample
rL = HmscRandomLevel(sData=xycoords)
md.I.1.noS.II.poisson = Hmsc(Y=Y.I.1.noS, XData = df.I.1.noS, XFormula=~yrs.disturb.min+precipitation+max.T, studyDesign=studyDesign, ranLevels=list('sample'=rL), distr='lognormal poisson')
md.I.1.noS.II.normal = Hmsc(Y=Y.I.1.noS, XData = df.I.1.noS, XFormula=~yrs.disturb.min+precipitation+max.T, studyDesign=studyDesign, ranLevels=list('sample'=rL))
m.I.1.noS.II.n.1 = sampleMcmc(md.I.1.noS.II.normal,
thin = 5, samples = 1000,
# num of samples to obtain per chain
transient = 500*5, nChains = 3,
verbose = 500*5
)
save(m.I.1.noS.II.n.1, file= "m.I.1.noS.II.n.1")
m.I.1.noS.II.p.1 = sampleMcmc(md.I.1.noS.II.poisson,
thin = 5, samples = 1000,
# num of samples to obtain per chain
transient = 500*5, nChains = 3,
verbose = 500*5
)
save(m.I.1.noS.II.p.1, file= "m.I.1.noS.II.p.1")
# .......... analyze hmsc .............
# normal distribution
load('m.I.1.noS')
preds.m.I.1.noS = computePredictedValues(m.I.1.noS)
MF.m.I.1.noS = evaluateModelFit(hM=m.I.1.noS, predY=preds.m.I.1.noS)
str(MF.m.I.1.noS)
# RMSE: root-mean-square error
plot(MF.m.I.1.noS$O.AUC, MF.m.I.1.noS$O.TjurR2)
# O.AUC = 0.5, O.TjurR2 = 0, failed i think
load('m.I.1.noS.3')
preds.m.I.1.noS.3 = computePredictedValues(m.I.1.noS.3)
load('m.I.1.noS.2')
preds.m.I.1.noS.2 = computePredictedValues(m.I.1.noS.2)
# Error: cannot allocate vector of size 11.3 Gb
load('m.I.1.noS.3')
preds.m.I.1.noS.3 = computePredictedValues(m.I.1.noS.3)
# Error: cannot allocate vector of size 6.8 Gb
# (probably cuz running hmsc at the same time. memory in my laptop is used up)
MF.m.I.1.noS.3 = evaluateModelFit(hM=m.I.1.noS.3, predY=preds.m.I.1.noS.3)
mpost = convertToCodaObject(m.noS.inf)
eff.beta=effectiveSize(mpost$Beta) # effective sample size
hist(eff.beta)
psrf.beta=gelman.diag(mpost$Beta, multivariate=T)$psrf # potential scale reduction factor
|
9769839a1f440ff994dceacfd89e0602c52b44b3
|
ca5418a01faf094b74f13b7ba3b6bd29113a908e
|
/practice_r/190707_Bayes_Trend_Filtering_Gibbs_Server.R
|
c24d3a97de596714a8d25ea1254081a226a0dd51
|
[] |
no_license
|
ikarus702/pbd_KRLS
|
fae59baf048ac1ca928e602b3656a86a323eb8bf
|
c26509a52ccb6c26b1d3bab30f5c08b0b89a07d7
|
refs/heads/master
| 2020-05-30T08:58:47.472019
| 2019-07-29T16:37:29
| 2019-07-29T16:37:29
| 189,629,987
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,546
|
r
|
190707_Bayes_Trend_Filtering_Gibbs_Server.R
|
library(parallel)
## read in the command line arguments
## run with: R CMD BATCH '--args p.val <- 10 q.val <- 60 off.val1 <- 0 off.val2 <- 0 Data.num <- c(1:50) NCORES=specified number of cores' RNAME.R
args <- commandArgs(TRUE)
if(length(args) > 0)
for(i in 1:length(args))
eval(parse(text=args[[i]]))
# NCORES <- 2
cl <- makeCluster(NCORES)
parallel.Bayes.BTF <- function(Data.num, d.num=d.val, m.steps=m.val){
library(statmod)
library(invgamma)
library(mvtnorm)
library(VGAM)
load("~/src/RData/Trend3_Data.RData")
y <- matrix(data.list[[Data.num]]$y,ncol=1)
X <- matrix(data.list[[Data.num]]$X,ncol=1)
n <- length(X)
d.order <- d.val
gibbsBTF = function(x=diag(1,n), y, D.order, max.steps = m.steps) {
n <- nrow(x)
p <- n
XtX <- t(x) %*% x #Time saving
xy <- t(x) %*% y
r <- 1
delta <- 0.1 # 1.78
betaSamples <- matrix(0, max.steps, p)
sigma2Samples <- rep(0, max.steps)
#invTau2Samples <- matrix(0, max.steps, p)
invW2Samples <- matrix(0, max.steps, p-D.order-1)
lambdaSamples <- rep(0, max.steps)
#lambda2Samples <- rep(0, max.steps)
beta <- drop(backsolve(XtX + diag(nrow=p), xy))
residue <- drop(y - x %*% beta)
sigma2 <- drop((t(residue) %*% residue) / n)
#invTau2 <- 1 / (beta * beta)
D.opt <- matrix(0,n-1,n)
for(i in 1:(n-1)){
D.opt[i,c(i,i+1)] <- c(1,-1)
}
if(D.order==0){
D.matrix <- D.opt
}else if(D.order > 0 ){
D.matrix <- D.opt
for(d in 1:D.order)
D.matrix <- D.opt[1:c(n-d-1),1:c(n-d)] %*% D.matrix
}
diff.beta <- D.matrix %*% beta
invW2 <- as.numeric(1/(diff.beta * diff.beta))
#lambda1 <- sqrt(2*p / sum(beta^2))
lambda <- sqrt(2*(p-D.order-1)/ sum(diff.beta^2))
k <- 0
while (k < max.steps) {
k <- k + 1
if (k %% 1000 == 0) {
cat('Iteration:', k, "\r")
}
# sample beta
invBeta <- diag(invW2,c(p-D.order-1))
invBeta <- t(D.matrix)%*%invBeta%*%D.matrix
invA <- solve(XtX + invBeta)
mean <- invA %*% xy
varcov <- sigma2 * invA
beta <- drop(rmvnorm(1, mean, varcov))
betaSamples[k,] <- beta
# sample sigma2
shape <- n
residue <- drop(y - x %*% beta)
scale <- (t(residue) %*% residue + t(beta) %*% invBeta %*% beta)/2
sigma2 <- 1/rgamma(1, shape, 1/scale)
sigma2Samples[k] <- sigma2
# sample w2
diff.beta <- diff(beta)
muPrime <- sqrt(lambda^2 * sigma2 / diff.beta^2)
lambdaPrime <- lambda^2
invW2 <- rep(0, p-D.order-1)
for (i in seq(p-D.order-1)) {
invW2[i] <- rinv.gaussian(1, muPrime[i], lambdaPrime)
}
invW2Samples[k, ] <- invW2
# update lambda
shape = r + p -D.order-1
scale = delta + sum(1/invW2)/2
#lambda <- sqrt(2*(p-1)/sum(1/invW2))
lambda <- sqrt(rgamma(1, shape, 1/scale))
lambdaSamples[k] <- lambda
}
result.list <- list(beta=betaSamples,sigma2=sigma2Samples,lambda=lambdaSamples)
return(result.list)
}
est.summary <- gibbsBTF(y=y, D.order=d.order)
betas <- est.summary$beta[m.steps,]
MSE <- sum((y-betas)^2)/(n-1)
summary.result <- list(beta=est.summary$beta, sigma2= est.summary$sigma2, lambda = est.summary$lambda, MSE=MSE)
return(summary.result)
}
withGlobals <- function(FUN, ...){
environment(FUN) <- list2env(list(...))
FUN
}
#Data.num <- c(1:2)
result.summary <- parLapply(cl,Data.num,withGlobals(parallel.Bayes.BTF,d.val=d.val, m.val=m.val))
save(result.summary, file="~/src/RData/Trend3_Result.RData")
stopCluster(cl)
|
4056b9453030191ecc83fb98ce64af153d8566af
|
74bf5107855b1695a1ac7d128c4df7b485e9c429
|
/man/taperCoeffsGenerator.Rd
|
dc68e3b72419b14e2b7494c0ac5f4c2bbf078217
|
[
"Apache-2.0"
] |
permissive
|
bcgov/FAIBBase
|
6b3b284e78257006c282c530ab01f897cc33e4c7
|
1c15295015a448e9ebd2aebec469cbf2b58e88b8
|
refs/heads/master
| 2023-08-03T11:05:59.717645
| 2023-07-19T16:57:09
| 2023-07-19T16:57:09
| 195,133,665
| 0
| 0
|
Apache-2.0
| 2020-02-12T17:59:58
| 2019-07-03T22:24:25
|
R
|
UTF-8
|
R
| false
| true
| 773
|
rd
|
taperCoeffsGenerator.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/DIB_ICalculator.R
\docType{methods}
\name{taperCoeffsGenerator}
\alias{taperCoeffsGenerator}
\alias{taperCoeffsGenerator,character-method}
\alias{taperCoeffsGenerator,missing-method}
\title{Generate the coefficients table of taper equations}
\usage{
taperCoeffsGenerator(taperEquationForm)
\S4method{taperCoeffsGenerator}{character}(taperEquationForm)
\S4method{taperCoeffsGenerator}{missing}()
}
\arguments{
\item{taperEquationForm}{character, Specifies a taper equation form one of KBEC, KBECQCI, KFIZ3.}
}
\value{
A coeffients table
}
\description{
Generates the coefficients of the taper equations for based on specific
taper equation form (\code{taperEquationForm})
}
\author{
Yong Luo
}
|
c7668dcdebff838ca62e209f5997c3fa77d31645
|
7be551356fbadf4f0c2eea4e06c1f6d1856f6288
|
/Basics/R files/regression/poly_regression.R
|
7789cad1094b7184665314343f3023bcf77f9fc2
|
[
"MIT"
] |
permissive
|
AnanduR32/Datascience
|
160c686f770adc086637b6467bbe6dd84508ce12
|
17a0b3056f558d917cec222b2d27a9d16920a9b6
|
refs/heads/master
| 2023-08-25T07:46:10.391445
| 2021-10-04T17:05:27
| 2021-10-04T17:05:27
| 252,497,031
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,726
|
r
|
poly_regression.R
|
## Setting working directory
setwd(setwd_regression_ICE)
## Loading necessary libraries
library(caTools)
library(data.table)
library(ggplot2)
## Loading data
dataset = read.csv("Position_Salaries.csv")
View(dataset)
## Plotting charts to analyze data
plot(dataset)
ggplot(
dataset, aes(
x = Level,
y = Salary
)
) + geom_point()
## There is already level variable defined
## The position variable is redundent, hence removing
dataset = dataset[2:3]
## Split the dataset
set.seed(10)
split = sample.split(dataset$Salary,SplitRatio = 0.7)
train = dataset[split,]
test = dataset[!split,]
## removing Salary field from test
test_ = test[1]
## Fitting the data using linear model
lreg = lm(formula = Salary~Level, data = train)
## Predicting
y_pred = predict(lreg, newdata = test_)
## Comparing outcome and actual values
out_lin = cbind(Actual = test$Salary, Predicted = y_pred)
View(out_lin)
## Summary of linear function
summary(lreg)
## Using polynomial regressor
## Quadratic model
dataset$Level2 = dataset$Level^2
qreg = lm(formula = Salary~., data = dataset)
y_pred_q = predict(qreg, dataset)
summary(qreg)
predict(qreg, newdata = data.frame(Level=11,Level2=11^2))
## Visualizing the results
ggplot(
dataset,aes(
x=Level,
y=Salary
)
) + geom_point() + geom_line(
aes(
x=seq(1,10,1),y = y_pred_q
)
)
## Cubic model
dataset$Level3 = dataset$Level^3
creg = lm(formula = Salary~., data = dataset)
y_pred_c = predict(creg, dataset)
summary(qreg)
predict(qreg, newdata = data.frame(Level=11,Level2=11^2,Level3=11^3))
## Visualizing the results
ggplot(
dataset,aes(
x=Level,
y=Salary
)
) + geom_point() + geom_line(
aes(
x=seq(1,10,1),y = y_pred_c
)
)
|
cc720105bb96eb11c5f4434749b33673ad88bec5
|
478f52115b62b367d3a67936665575ade91c6c66
|
/man/sdf_num_partitions.Rd
|
10ee4e15eba8eee4e255275876ce471de841db29
|
[
"Apache-2.0"
] |
permissive
|
leosouzadias/sparklyr
|
209d5f90e7e3bd4be19d974c2785340f98de243f
|
38c4a60882c04313ea200dda4387cc0ed94c08af
|
refs/heads/master
| 2021-07-11T19:55:42.473022
| 2017-10-16T16:28:16
| 2017-10-16T16:28:16
| 106,004,105
| 1
| 0
| null | 2017-10-06T12:50:17
| 2017-10-06T12:50:17
| null |
UTF-8
|
R
| false
| true
| 395
|
rd
|
sdf_num_partitions.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sdf_interface.R
\name{sdf_num_partitions}
\alias{sdf_num_partitions}
\title{Gets number of partitions of a Spark DataFrame}
\usage{
sdf_num_partitions(x)
}
\arguments{
\item{x}{An object coercable to a Spark DataFrame (typically, a
\code{tbl_spark}).}
}
\description{
Gets number of partitions of a Spark DataFrame
}
|
272e8fa4410de91b38bf3edf702bb97e53dbbeb9
|
a485dcf08bd177648ac738919deb044d26f5682a
|
/PI_CALCULATION_ALONG_TOTAL_GENOME.R
|
fb504f74b13797aca852facb8fc6dfcc7569542e
|
[] |
no_license
|
NurislamSheih/Pv_population_genomics_scripts
|
78cb0eab4742561f58cba3183399cb1c0aa136ed
|
c1b9b096ab094479d582a7b770c1e1b74940ab33
|
refs/heads/main
| 2023-04-23T07:07:52.652746
| 2021-05-18T14:07:04
| 2021-05-18T14:07:04
| 368,541,594
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,625
|
r
|
PI_CALCULATION_ALONG_TOTAL_GENOME.R
|
#####Pp_genome_assembly
library(dplyr)
library(data.table)
library(ggplot2)
T3 <- read.table("AF_Malawi_CHIKOPA_Pp_genome_assembly_columns_passed.txt", sep = "")
print("Finished read AF_TASH_SC1")
T3 <- mutate(T3, V8 = paste(V1, V2))
T3 <- T3[,c(1,3:7)]
print("start joining data")
T3_T3 <- inner_join(T3, T3, by = "V8")
T3_T3 <- T3_T3[,c(1:6,8:11)]
rm(T3)
#T3_T3 <- T3_T3[!duplicated(T3_T3$V8), ]
#T3_T3[duplicated(T3_T3$V8), ]
end_first_join <- Sys.time()
colnames(T3_T3) <- c("CONTIG", "REF-1", "ALT-1", "GT-1","AF-1", "SHARED_POS", "REF-2", "ALT-2", "GT-2", "AF-2")
T3_T3 <- T3_T3[!(T3_T3$`GT-1` == "./." | T3_T3$`GT-2` == "./."),]
T3_T3 <- T3_T3[!(T3_T3$`GT-1` == "1/2" | T3_T3$`GT-2` == "1/2"),]
T3_T3 <- within(T3_T3, `ALT-1`[`GT-1`=="0/0"] <- `REF-1`[`GT-1`=="0/0"])
T3_T3 <- within(T3_T3, `ALT-2`[`GT-2`=="0/0"] <- `REF-2`[`GT-2`=="0/0"])
T3_T3 <- within(T3_T3, `REF-1`[`GT-1`=="1/1"] <- `ALT-1`[`GT-1`=="1/1"])
T3_T3 <- within(T3_T3, `REF-2`[`GT-2`=="1/1"] <- `ALT-2`[`GT-2`=="1/1"])
print("Measurment_GT_based_on_allele_frequency-start")
####Measurment_GT_based_on_allele_frequency
#T3_T3
T3_T3$AF_REF1 <- (1 - T3_T3$`AF-1`)
T3_T3$AF_REF2 <- (1 - T3_T3$`AF-2`)
T3_T3 <- T3_T3[, c("REF-1", "ALT-1", "AF_REF1", "AF-1", "REF-2", "ALT-2","AF_REF2", "AF-2", "SHARED_POS", "CONTIG")]
First_random_T3_T3 <- unname(apply(T3_T3[c(1:4)], 1, FUN = function(x) {return(sample(x[1:2], size = 1, prob = x[3:4]))}))
Second_random_T3_T3 <- unname(apply(T3_T3[c(5:8)], 1, FUN = function(x) {return(sample(x[1:2], size = 1, prob = x[3:4]))}))
Complete_sequnece_T3_T3 <- as.data.frame(First_random_T3_T3, stringsAsFactors = F)
rm(First_random_T3_T3)
Complete_sequnece_T3_T3$Second_population <- as.data.frame(Second_random_T3_T3, stringsAsFactors = F)
rm(Second_random_T3_T3)
Complete_sequnece_T3_T3_1 <- cbind(Complete_sequnece_T3_T3, T3_T3$CONTIG)
Complete_sequnece_T3_T3 <- Complete_sequnece_T3_T3_1
rm(Complete_sequnece_T3_T3_1)
rm(T3_T3)
colnames(Complete_sequnece_T3_T3) <- c("First_pop", "Second_pop", "Contig")
Complete_sequnece_T3_T3$First_pop <- sapply(Complete_sequnece_T3_T3$First_pop, as.character)
Complete_sequnece_T3_T3$Second_pop <- sapply(Complete_sequnece_T3_T3$Second_pop, as.character)
Complete_sequnece_T3_T3 <- na.omit(Complete_sequnece_T3_T3)
Complete_sequnece_T3_T3$row_names <- c(1:nrow(Complete_sequnece_T3_T3))
q1 <- nrow(Complete_sequnece_T3_T3)
t3_t3 <- apply(Complete_sequnece_T3_T3[,1:4], 1, function(x) {if(nchar(x[1]) == 1 & nchar(x[2]) == 1 & x[1] != x[2]) {return(1)}else{return(0)}}) %>% sum()
average_pi <- t3_t3/q1
write(c("average_pi= ", average_pi, "t3_t3 = ", t3_t3, "q1 = ", q1), file = "PI_DIFF_TOTAL_GENOME_Pp_data.txt", append = T, sep = "\t")
t3_t3=0
w_tash3=0
windows_tash3_tash3 <- list()
for(i in 1:nrow(Complete_sequnece_T3_T3)){
if(nchar(Complete_sequnece_T3_T3$First_pop[i]) == 1 & nchar(Complete_sequnece_T3_T3$Second_pop[i]) ==1 & Complete_sequnece_T3_T3$First_pop[i] != Complete_sequnece_T3_T3$Second_pop[i]) {
t3_t3 = t3_t3 +1
}
if(Complete_sequnece_T3_T3$row_names[i] > w_tash3){
windows_tash3_tash3[[ as.character(w_tash3)]] <- c(t3_t3, as.character(Complete_sequnece_T3_T3$Contig[i]))
t3_t3=0
w_tash3=as.integer(w_tash3)+5000
}
}
tash_tash <- transpose(as.data.frame(windows_tash3_tash3, row.names = TRUE))
tash_tash$row_names <- c(1:nrow(tash_tash))
colnames(tash_tash) <- c("Number_of_gt_diff", "contig", "row_number")
tash_tash$Number_of_gt_diff=as.integer(tash_tash$Number_of_gt_diff)
tash_tash$Number_of_gt_diff <- tash_tash[,1]/5000
write.csv(tash_tash, file = "TASH_TASH_PI_5kbp_along_all_genome.csv", quote = FALSE)
|
813a22706126326d181d932e37974832de966501
|
820f8aca9a690688cd5a48caa9038fbeff6ba971
|
/man/adjust_value.Rd
|
33e5b776b635c1a2e6fb99533d1648cfec9a4041
|
[] |
no_license
|
jkennel/transducer
|
07374d4967498762cb692e71068bf89b6f026bc3
|
881ae6eb2570a15c6dc6aa91a69308183c3023f2
|
refs/heads/master
| 2021-06-11T18:14:03.474803
| 2021-06-04T12:22:17
| 2021-06-04T12:22:17
| 195,269,441
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 262
|
rd
|
adjust_value.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/compare_to_manual.R
\name{adjust_value}
\alias{adjust_value}
\title{adjust_value}
\usage{
adjust_value(x, shift)
}
\arguments{
\item{shift}{}
}
\value{
}
\description{
adjust_value
}
|
a2dd249a6670ce422f6746202128f4f1f00ae674
|
6b1d474c1771046189f292dbd48a3fa66432ac48
|
/exploratory/percentwastedfoodsupply.R
|
5b9ded0343c9732fc0e8e8cc3c4fed10d2040c7b
|
[] |
no_license
|
qdread/fwe
|
1393e192d946eb1c0067bbc5ad0f927c49fa0305
|
7f33c87b7e1ad0a64233b28bf4c08b977ca56014
|
refs/heads/master
| 2021-08-08T14:28:26.834715
| 2021-07-12T15:50:47
| 2021-07-12T15:50:47
| 151,155,365
| 3
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,906
|
r
|
percentwastedfoodsupply.R
|
# Calculation of percentage food supply wasted in USA, baseline.
# Done for Jenny Stephenson's EPA report
# QDR / 12 July 2021
library(tidyverse)
flw_rates <- read.csv('C:/Users/qread/Documents/GitHub/foodwaste/halvingfoodwaste/data/flw_rates.csv', stringsAsFactors = FALSE)
industry_proportions <- read.csv('C:/Users/qread/Documents/GitHub/foodwaste/halvingfoodwaste/data/industry_proportions.csv', stringsAsFactors = FALSE) %>%
filter(food_system %in% c('partial', 'y')) %>%
arrange(stage) %>%
mutate(stage_code = case_when(
stage %in% 'agriculture' ~ 'L1',
stage %in% 'processing' ~ 'L2',
stage %in% c('retail', 'wholesale') ~ 'L3',
stage %in% 'foodservice' ~ 'L4a',
stage %in% 'institutional' ~ 'L4b'
))
bea_code_formats <- read.csv('C:/Users/qread/Documents/GitHub/foodwaste/halvingfoodwaste/data/industry_codes.csv', stringsAsFactors = FALSE)
sector_stage_codes <- industry_proportions$stage_code
sector_long_names <- bea_code_formats$sector_desc_drc[match(industry_proportions$BEA_389_code, bea_code_formats$sector_code_uppercase)]
sector_short_names <- industry_proportions$BEA_389_code
final_demand_sector_codes <- sector_stage_codes
final_demand_sector_codes[final_demand_sector_codes %in% c('L1', 'L2', 'L3')] <- 'L5'
drc_base <- read.csv('C:/Users/qread/Documents/GitHub/foodwaste/halvingfoodwaste/USEEIO/useeiopy/Model Builds/USEEIO2012/USEEIO2012_DRC.csv', check.names = FALSE, row.names = 1)
finaldemand <- read_csv("C:/Users/qread/Documents/GitHub/foodwaste/halvingfoodwaste/USEEIO/useeiopy/Model Builds/USEEIO2012/USEEIO2012_FinalDemand.csv") %>%
left_join(industry_proportions, by = c('BEA_389_code', 'BEA_389_def')) %>%
mutate(proportion_food = if_else(is.na(proportion_food), 0, proportion_food))
# Baseline food system demand
f <- finaldemand$`2012_US_Consumption` * finaldemand$proportion_food
# baseline DRC
A <- as.matrix(drc_base)
# baseline total food system demand
total_base <- solve(diag(nrow(A)) - A) %*% f
# Alternative scenario where all waste is zero
demand_change_fn <- function(W0, r, p) p * ((1 - W0) / (1 - (1 - r) * W0) - 1) + 1
flw_rates <- flw_rates %>%
mutate(L1 = loss_ag_production,
L2 = 1 - (1 - loss_handling_storage) * (1 - loss_processing_packaging),
L3 = loss_distribution,
L4a = loss_consumption,
L4b = loss_consumption)
waste_rate_bysector <- t(flw_rates[, industry_proportions$stage_code])
food_category_weights <- industry_proportions %>% select(cereals:beverages)
baseline_waste_rate <- rowSums(waste_rate_bysector * food_category_weights, na.rm = TRUE) / rowSums(food_category_weights)
reduction_by_stage <- setNames(rep(1, 6), c('L1','L2','L3','L4a','L4b','L5'))
intermediate_demand_change_factors <- as.numeric(demand_change_fn(baseline_waste_rate, reduction_by_stage[sector_stage_codes], industry_proportions$proportion_food))
final_demand_change_factors <- as.numeric(demand_change_fn(baseline_waste_rate, reduction_by_stage[final_demand_sector_codes], industry_proportions$proportion_food))
change_factors <- data.frame(BEA_389_code = sector_short_names,
intermediate_factor = intermediate_demand_change_factors,
final_factor = final_demand_change_factors)
finaldemand <- finaldemand %>%
left_join(change_factors) %>%
replace_na(list(intermediate_factor = 0, final_factor = 0))
# Alternative food system demand
f_alt <- finaldemand$`2012_US_Consumption` * finaldemand$proportion_food * finaldemand$final_factor
# Alternative DRC
A_alt <- as.matrix(drc_base)
A_alt[, sector_long_names] <- sweep(A_alt[, sector_long_names], 2, intermediate_demand_change_factors, '*')
# Alternative total food system demand
total_nowaste <- solve(diag(nrow(A_alt)) - A_alt) %*% f_alt
# Result
idx <- finaldemand$stage %in% c('agriculture')
(sum(total_base[idx]) - sum(total_nowaste[idx])) / sum(total_base[idx])
|
a20460f4dd6edc37f74b0f62565a8b21c018d818
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/airr/examples/load_schema.Rd.R
|
7cb089fa623f71ec55316caae60cb348efe5f932
|
[] |
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
| 264
|
r
|
load_schema.Rd.R
|
library(airr)
### Name: load_schema
### Title: Load a schema definition
### Aliases: load_schema
### ** Examples
# Load the Rearrangement definition
schema <- load_schema("Rearrangement")
# Load the Alignment definition
schema <- load_schema("Alignment")
|
06cc137a2d9c69786c9bb2e13079f26553789715
|
514d2567b3d1c640c3bdeee70b5e21a7d6070a54
|
/op.r
|
6bc0e04e1261e685dc3578bb1334fe9fda768a0d
|
[] |
no_license
|
andriyamm/r-snippets
|
2a5e1e937b51008ffd6370862f679640d80e31dc
|
fd8f39284bd93670f47dc132ccb3be2acbb6c075
|
refs/heads/master
| 2020-12-24T16:59:41.074982
| 2014-04-10T04:53:55
| 2014-04-10T04:53:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 456
|
r
|
op.r
|
#You can define your own binary operators.
# User-defined binary operators consist of a string of characters between two % characters.
#To do this, create a function of two
#variables and assign it to an appropriate symbol. For example, let’s define an oper-
# ator %myop% that doubles each operand and then adds them together:
# create own operator
`%myop%` <- function(a, b) {2*a + 2*b}
# use own operator
1 %myop% 1
#[1] 4
1 %myop% 2
#[1] 6
|
3591f7fd18cace87d8196b6916740673deb1adde
|
b660653f7e706a508171171c6196a719a04afc1a
|
/AgeScenarios.R
|
ba9d42d5d62b955ed83d2c8d4edbcdceaaba0b39
|
[] |
no_license
|
GLEON/AgeWaterCarbonr
|
290b288248d9bc6d639f3041ed98e32c9c67545e
|
fbb0c2eded00fe6bb4032ed5d682d4a8dfb68325
|
refs/heads/master
| 2020-04-30T10:49:00.190067
| 2019-03-20T19:23:48
| 2019-03-20T19:23:48
| 176,786,470
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 20,227
|
r
|
AgeScenarios.R
|
# Age of water and Carbon, R version, July 2017
# Adapted from Duffy, CJ, HA Dugan, and PC Hanson, In review, The age of water and carbon in lake catchments: a simple dynamical model, Limnology & Oceanography Letters
source('./AgeOfCarbon.R')
source('./GetAgeParameters.R')
source('./Budyko.R')
#######################
# User parameters
# Scenarios: 1=single run; 2=Current, wet, dry; 2.5, same as 2 but Budyko
# 3=La:Wa gradient; 4=rain gradient; 5=sampling parameters;
# 6=single run with conservative tracer; 7=Across Budyko gradient
myLakeID = 2 # 1=Mendota, 2=Sunapee
Scenario = 6 #2.5
Days = 3650 #10000 # Number of days to run dynamics
AxesCex = 0.9 # Try 0.6 for png, 0.9 for non png
Save2File = FALSE
LegendOn = FALSE
LegendCex = 0.7 # Try 0.7 for non png
# LOCCalVal = 5 # Lake Mendota OC calibration value, mg/L
LabelLake = "Lake OC (mgC/L)" # "Lake P (ug/L)" #
LabelCatchment = "Catchment OC (mgC/L)" # "Catchment P (ug/L)" #
# End user parameters
#######################
# Initial values for state variables
Inits = data.frame(C1=NA,C2=NA,s=NA,Alpha1=NA,Alpha2=NA,Beta=NA,Age1=NA,Age2=NA,AgeS=NA)
Inits$C1 = 15, Duffy 50, 19 is a good starting concentration for Sunapee P
Inits$C2 = 7, Duffy 10, 5 is a good starting concentration for Sunapee P
Inits$s = 100 # Duffy 100
Inits$Alpha1 = 0
Inits$Alpha2 = 0
Inits$Beta = 0
Inits$Age1 = 0
Inits$Age2 = 0
Inits$AgeS = 0
###############################
# Scenario section
# Each scenario has setup and
# actually runs the model
myR = list() # All scenario results go in this list
if (Scenario==1){
# Run once
ScenarioLabels = c('Current')
RunDynamics = TRUE # Whether to run time dynamics
# Set y limitis for figures
SYLim = c(0,200) # Sediment
CYLim = c(0,20) # Catchment
LYLim = c(0,20) # Lake
aSYLim = c(0,5) # Same, but for age
aCYLim = c(0,5)
aLYLim = c(0,5)
# Run this scenario
print('Run 1...')
myParams = GetAgeParameters(myLakeID)
myR[[1]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
if (Scenario==2){
# Run Current, wet, dry scenarios
ScenarioLabels = c('Current ','Wet','Dry')
RunDynamics = TRUE # Whether to run time dynamics
# Set y limitis for figures
SYLim = c(50,200)
CYLim = c(5,50)
LYLim = c(0,25)
aSYLim = c(0,8)
aCYLim = c(0,8)
aLYLim = c(0,8)
# Run Current's scenario
print('Run 1...')
myParams = GetAgeParameters(myLakeID)
myR[[1]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
# Run wet scenario
myParams = GetAgeParameters(myLakeID)
myParams$Q1P = 0.0038537
myParams$Q2P = 0.0038537
myParams$Qe1 = 0.00203543
myParams$Qe2 = 0.00203543
myParams$Q1 = myParams$Q1P - myParams$Qe1
myParams$Q2 = myParams$Q2P - myParams$Qe2
myParams$QPe = 0.0023862
print('Run 2...')
myR[[2]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
# Run dry scenario
myParams = GetAgeParameters(myLakeID)
myParams$Q1P = 0.00158921
myParams$Q2P = 0.00158921
myParams$Qe1 = 0.00133389
myParams$Qe2 = 0.00133389
myParams$QPe = 0.0023862
myParams$Q1 = myParams$Q1P - myParams$Qe1
myParams$Q2 = myParams$Q2P - myParams$Qe2
print('Run 3...')
myR[[3]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
if (Scenario==2.5){
# Just like 2, but use Budyko function to get Qe
# Run Current, wet, dry scenarios
ScenarioLabels = c('Current ','Wet','Dry')
RunDynamics = TRUE # Whether to run time dynamics
# Set y limitis for figures
SYLim = c(50,200)
CYLim = c(5,15)
LYLim = c(0,10)
aSYLim = c(0,8)
aCYLim = c(0,8)
aLYLim = c(0,8)
myParams = GetAgeParameters(myLakeID)
myBudyko = Budyko(myParams$QPe,c(myParams$Q1P,0.0038537,0.00158921),2,TRUE)
# Run Current's scenario
print('Run 1...')
myParams = GetAgeParameters(myLakeID)
myR[[1]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
# Run wet scenario
myParams = GetAgeParameters(myLakeID)
myParams$Q1P = 0.0038537
myParams$Q2P = 0.0038537
myParams$Qe1 = myBudyko$Qe[2]
myParams$Qe2 = myBudyko$Qe[2]
myParams$Q1 = myParams$Q1P - myParams$Qe1
myParams$Q2 = myParams$Q2P - myParams$Qe2
myParams$QPe = 0.0023862
print('Run 2...')
myR[[2]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
# Run dry scenario
myParams = GetAgeParameters(myLakeID)
myParams$Q1P = 0.00158921
myParams$Q2P = 0.00158921
myParams$Qe1 = myBudyko$Qe[3]
myParams$Qe2 = myBudyko$Qe[3]
myParams$QPe = 0.0023862
myParams$Q1 = myParams$Q1P - myParams$Qe1
myParams$Q2 = myParams$Q2P - myParams$Qe2
print('Run 3...')
myR[[3]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
if (Scenario==3){
# Run Current, but with gradient of lake areas
A1A2 = seq(0.01,10,0.01) # La = Wa * A1A2
ScenarioLabels = c('La:Wa gradient')
RunDynamics = FALSE # Whether to run time dynamics
Days = 0 # Days
# Set y limitis for figures
# Run Current's scenario
print('Running area gradient...')
myParams = GetAgeParameters(myLakeID)
for (iA in 1:length(A1A2)){
myParams$A2 = A1A2[iA] * myParams$A1
myR[[iA]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
}
if (Scenario==4){
# Run Current, but with Rain OC concentration gradient
CRain = seq(0.1,100,0.1)
ScenarioLabels = c('C Rain gradient')
RunDynamics = FALSE # Whether to run time dynamics
Days = 0 # Days
# Set y limitis for figures
# Run Current's scenario
print('Running area gradient...')
myParams = GetAgeParameters(myLakeID)
for (iA in 1:length(CRain)){
myParams$C1P = CRain[iA]
myR[[iA]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
}
if (Scenario==5){
# Sample two or more parameters
nSamples = 3000
#P2S = c(5,21) # parameters to sample, Q1P=5,Kr2=21
P2S = c(5,16)
LowerUpper = list(c(0.8,1.5),c(0.8,1.5)) # multiplicative of the default for respective parameter
myR = list()
myParams = GetAgeParameters(myLakeID)
newParams = matrix(data=NA,nrow=length(P2S),ncol=nSamples)
ParamNames = colnames(myParams)[P2S]
for (iP2S in 1:length(P2S)){
Lbound = myParams[P2S[iP2S]][1,1]*LowerUpper[[iP2S]][1]
Ubound = myParams[P2S[iP2S]][1,1]*LowerUpper[[iP2S]][2]
newParams[iP2S,] = runif(nSamples, min=Lbound, max=Ubound)
}
ScenarioLabels = c('Parameter sampling')
RunDynamics = FALSE # Whether to run time dynamics
Days = 0 # Days
# Set y limitis for figures
print('Running parameter sampling...')
myParams = GetAgeParameters(myLakeID)
for (iA in 1:nSamples){
for (iP in 1:length(P2S)){
myParams[P2S[iP]] = newParams[iP,iA]
}
myParams$Q1 = myParams$Q1P - myParams$Qe1
myParams$Q2 = myParams$Q2P - myParams$Qe2
myR[[iA]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
}
if (Scenario==6){
# Run Current, along with conservative tracer
ScenarioLabels = c('Current ','Tracer')
RunDynamics = TRUE # Whether to run time dynamics
# Set y limitis for figures
SYLim = c(50,150)
CYLim = c(0,100)
LYLim = c(0,25)
aSYLim = c(0,8)
aCYLim = c(0,8)
aLYLim = c(0,8)
# Run Current's scenario
print('Run 1...')
myParams = GetAgeParameters(myLakeID)
myR[[1]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
# Run tracer
myParams = GetAgeParameters(myLakeID)
#myParams$kS = 0
myParams$Kr1 = 0
myParams$Kr2 = 0
myParams$Kb2 = 0
print('Run 2...')
myR[[2]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
if (Scenario == 7){
# Run over gradient of precip, using Budyko
myParams = GetAgeParameters(myLakeID)
# Define precipitation range
QP = seq(0.001,0.004,0.0001)
nScale = 3 # scaling parameter for Budyko
QPe = myParams$QPe
myBudyko = Budyko(QPe,QP,nScale,TRUE)
Qe = myBudyko$Qe
ScenarioLabels = c('Precip Gradient via Budyko')
RunDynamics = FALSE # Whether to run time dynamics
Days = 0 # Days
# Set y limitis for figures
# Run scenarios
print('Running Budyko gradient...')
for (iA in 1:length(QP)){
myParams$Q1P = QP[iA]
myParams$Q2P = QP[iA]
myParams$Qe1 = Qe[iA]
myParams$Qe2 = Qe[iA]
myParams$Q1 = myParams$Q1P - myParams$Qe1
myParams$Q2 = myParams$Q2P - myParams$Qe2
myR[[iA]] = AgeOfCarbon(myParams,Inits,Days,RunDynamics)
}
}
###########################
# Process scenario results
# Print steady state values
# All scenarios
nRuns = length(myR)
if (nRuns < 20){
for (iR in 1:nRuns){
mySS = myR[[iR]][[2]]
print('=========================')
print(paste('Scenarion:',ScenarioLabels[iR]))
print(paste('Steady-state DOC for catchment, lake (g/m3):',format(mySS$C1ave,digits=3),',',format(mySS$C2ave,digits=3)))
print(paste('Steady-state Age for catchment, lake (y):',format(mySS$Tau1/365,digits=3),',',format(mySS$Tau2System/365,digits=3)))
}
}
# All scenarios that run dynamics
if (RunDynamics) {
# Determine number of runs
nRuns = length(myR)
myCols = c('black','red','blue','green')
if (Scenario==6){
myCols = c('black','grey','blue','green')
}
#############################
# Plot concentration results
par(
mfrow = c(2,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
# for (iR in 1:nRuns) {
# #Panel one, sediments
# myD = myR[[iR]][[1]]
# if (iR == 1) {
# plot(1:Days / 365,myD$s,ylim = SYLim,type = 'l',lwd = 2,col = myCols[iR],xaxt = 'n',xlab = "",ylab = "Soil OC (mgC/L)",main = "")
# abline(h=myR[[iR]][2][[1]]$SSave,lty=2,col=myCols[iR])
# }else{
# lines(1:Days / 365,myD$s,type = 'l',lwd = 2,col = myCols[iR])
# abline(h=myR[[iR]][2][[1]]$SSave,lty=2,col=myCols[iR])
# }
# }
# #myLegend = c(expression('probe, r'[p]*'/r'[w]*' = 5.0'),expression('probe, r'[p]*'/r'[w]*' = 0.5'))
# legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)
for (iR in 1:nRuns) {
#Panel 2, catchment
myD = myR[[iR]][[1]]
if (iR == 1) {
plot(1:Days / 365,myD$C1,ylim = CYLim,type = 'l',lwd = 2,col = myCols[iR],xaxt = 'n',xlab ="",ylab = LabelCatchment,main = "")
abline(h=myR[[iR]][2][[1]]$C1ave,lty=2,col=myCols[iR])
}else{
lines(1:Days / 365,myD$C1,type = 'l',lwd = 2,col = myCols[iR])
abline(h=myR[[iR]][2][[1]]$C1ave,lty=2,col=myCols[iR])
}
}
if (LegendOn){legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)}
for (iR in 1:nRuns) {
#Panel 3, lake
myD = myR[[iR]][[1]]
if (iR == 1) {
plot(1:Days / 365,myD$C2,ylim = LYLim,type = 'l',lwd = 2,col = myCols[iR],xlab = 'Years', ylab =LabelLake,main = "")
abline(h=myR[[iR]][2][[1]]$C2ave,lty=2,col=myCols[iR])
}else{
lines(1:Days / 365,myD$C2,type = 'l',lwd = 2,col = myCols[iR])
abline(h=myR[[iR]][2][[1]]$C2ave,lty=2,col=myCols[iR])
}
abline(h=12,lty=2,col='blue')
abline(h=24,lty=2,col='green')
}
if (LegendOn){legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)}
if (Save2File){
fName = paste('Concentration_','Scenario',Scenario,'.png',sep="")
dev.copy(png,fName,width=3,height=4.0,units="in",res=300)
dev.off()
}
#############################
# Plot System Age results
par(
mfrow = c(2,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
# for (iR in 1:nRuns) {
# #Panel one, sediments
# myD = myR[[iR]][[1]]
# if (iR == 1) {
# plot(1:Days / 365,myD$AgeS / 365,ylim = aSYLim,type = 'l',col = myCols[iR],xaxt ='n',xlab = "",ylab = "Sediment age (y)",main = "")
# abline(h=myR[[iR]][2][[1]]$TauS/365,lty=2,col=myCols[iR])
# }else{
# lines(1:Days / 365,myD$AgeS / 365,type = 'l',col = myCols[iR])
# abline(h=myR[[iR]][2][[1]]$TauS/365,lty=2,col=myCols[iR])
# }
# }
# legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)
for (iR in 1:nRuns) {
#Panel 2, catchment
myD = myR[[iR]][[1]]
if (iR == 1) {
plot(1:Days / 365,myD$Age1 / 365,ylim = aCYLim,type = 'l',col = myCols[iR],xaxt ='n',xlab = "",ylab = "Catchment OC age (y) ",main = "")
abline(h=myR[[iR]][2][[1]]$Tau1/365,lty=2,col=myCols[iR])
}else{
lines(1:Days / 365,myD$Age1 / 365,type = 'l',col = myCols[iR])
abline(h=myR[[iR]][2][[1]]$Tau1/365,lty=2,col=myCols[iR])
}
}
if (LegendOn){legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)}
for (iR in 1:nRuns) {
#Panel 3, lake
myD = myR[[iR]][[1]]
if (iR == 1) {
plot(1:Days / 365,myD$Age2 / 365,ylim = aLYLim,type = 'l',col = myCols[iR],xlab ='Years', ylab = "System OC age (y)",main = "")
abline(h=myR[[iR]][2][[1]]$Tau2System/365,lty=2,col=myCols[iR])
}else{
lines(1:Days / 365,myD$Age2 / 365,type = 'l',col = myCols[iR])
abline(h=myR[[iR]][2][[1]]$Tau2System/365,lty=2,col=myCols[iR])
}
}
if (LegendOn){legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)}
if (Save2File){
fName = paste('Age_','Scenario',Scenario,'.png',sep="")
dev.copy(png,fName,width=3,height=4.0,units="in",res=300)
dev.off()
}
#############################
# Plot Lake Age results
par(
mfrow = c(2,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
for (iR in 1:nRuns) {
#Panel 2, catchment
myD = myR[[iR]][[1]]
if (iR == 1) {
plot(1:Days / 365,myD$Age1 / 365,ylim = aCYLim,type = 'l',col = myCols[iR],xaxt ='n',xlab = "",ylab = "Catchment OC age (y) ",main = "")
abline(h=myR[[iR]][2][[1]]$Tau1/365,lty=2,col=myCols[iR])
}else{
lines(1:Days / 365,myD$Age1 / 365,type = 'l',col = myCols[iR])
abline(h=myR[[iR]][2][[1]]$Tau1/365,lty=2,col=myCols[iR])
}
}
if (LegendOn){legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)}
for (iR in 1:nRuns) {
#Panel 3, lake
myD = myR[[iR]][[1]]
if (iR == 1) {
plot(1:Days / 365,myD$Age2 / 365,ylim = aLYLim,type = 'l',col = myCols[iR],xlab ='Years', ylab = "Lake OC age (y)",main = "")
abline(h=myR[[iR]][2][[1]]$TauLake/365,lty=2,col=myCols[iR])
}else{
lines(1:Days / 365,myD$Age2 / 365,type = 'l',col = myCols[iR])
abline(h=myR[[iR]][2][[1]]$TauLake/365,lty=2,col=myCols[iR])
}
}
if (LegendOn){legend("topright",y = NULL,ScenarioLabels,lty = rep(1,nRuns),col = myCols[1:nRuns],cex=LegendCex)}
if (Save2File){
fName = paste('Age_Lake_','Scenario',Scenario,'.png',sep="")
dev.copy(png,fName,width=3,height=4.0,units="in",res=300)
dev.off()
}
} # End of plotting dynamics
if (Scenario ==3){
# Move list to vectors
nRuns = length(myR)
newSS = data.frame(Tau2System=rep(NA,nRuns),C2ave=rep(NA,nRuns))
for (i in 1:nRuns){
newSS$Tau2System[i] = myR[[i]][[2]]$Tau2System
newSS$A1A2[i] = myR[[i]][[2]]$A1A2
newSS$C2ave[i] = myR[[i]][[2]]$C2ave
}
par(
mfrow = c(2,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
plot(newSS$Tau2System/365,newSS$C2ave,type='l',xlab='Lake OC Age (y)',ylab='Lake OC (g/m3)')
plot(A1A2,newSS$Tau2System/365,type='l',xlab='La:Ca',ylab='Lake OC Age (y)')
if (Save2File){
fName = paste('LA_WA_ratio_System_','Scenario',Scenario,'.png',sep="")
dev.copy(png,fName,width=3,height=5,units="in",res=300)
dev.off()
}
}
if (Scenario ==4){
# Move list to vectors
nRuns = length(myR)
newSS = data.frame(Tau2System=rep(NA,nRuns),C2ave=rep(NA,nRuns))
for (i in 1:nRuns){
newSS$Tau2System[i] = myR[[i]][[2]]$Tau2System
newSS$A1A2[i] = myR[[i]][[2]]$A1A2
newSS$C2ave[i] = myR[[i]][[2]]$C2ave
}
par(
mfrow = c(3,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
plot(CRain,newSS$C2ave,type='l', xlab='C in Rain (mg/L)', ylab = 'Lake C (mg/L)')
plot(CRain,newSS$Tau2System/365,type='l',xlab='C in Rain (mg/L)', ylab = 'Age (y)')
plot(newSS$Tau2System/365,newSS$C2ave,type='l', xlab='Age (y)', ylab = 'Lake C (mg/L)')
abline(a=0,b=1,lty=2)
if (Save2File){
fName = paste('NotSure_','Scenario',Scenario,'.png',sep="")
dev.copy(png,fName,width=3,height=4.0,units="in",res=300)
dev.off()
}
}
if (Scenario ==5){
# Create a matrix to hold the results
nRuns = length(myR)
nParams = length(P2S)
# newParams = matrix(nrow = nParams,ncol = nSamples)
# P2S = c(5,21) # parameters to sample, Q1P=5,Kr2=21
# ParamNames = colnames(myParams)[P2S]
newSS = data.frame(Tau2System=rep(NA,nRuns),C2ave=rep(NA,nRuns))
for (i in 1:nRuns){
newSS$Tau2System[i] = myR[[i]][[2]]$Tau2System
#newSS$A1A2[i] = myR[[i]][[2]]$A1A2
newSS$C2ave[i] = myR[[i]][[2]]$C2ave
}
# Plot lake C as a function of parameters
par(
mfrow = c(nParams,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
for (i in 1:nParams){
plot(newParams[i,],newSS$C2ave,xlab=ParamNames[i],ylab='Lake C (mg/L)')
#ylim=c(-20,20))
}
# Plot lake C age as a function of parameters
for (i in 1:nParams){
plot(newParams[i,],log10(newSS$Tau2System/365),xlab=ParamNames[i],ylab='Lake C Age (y)')
#ylim=c(0,5))
}
}
if (Scenario==7){
# Create a matrix to hold the results
nRuns = length(myR)
newSS = data.frame(Tau2System=rep(NA,nRuns),C2ave=rep(NA,nRuns))
for (i in 1:nRuns){
newSS$Tau2System[i] = myR[[i]][[2]]$Tau2System
newSS$C2ave[i] = myR[[i]][[2]]$C2ave
}
# Plot lake C as a function of parameters
par(
mfrow = c(2,1),
oma = c(1, 1, 1, 1), # four rows of text at the outer left and bottom margin
mar = c(3.7, 3.7, 0.5, 0.0), # 0.5, 3.7, 0.5, 0.0 space for one row of text at ticks and to separate plots
mgp = c(2.2, 1, 0), # axis label at 2 rows distance, tick labels at 1 row
xpd = FALSE,
cex = AxesCex
) # allow content to protrude into outer margin (and beyond)
plot(QP,newSS$C2ave,type='l',xlab='QP (m/d)',ylab='Lake C (mg/L)')
# Plot lake C age as a function of parameters
plot(QP,log10(newSS$Tau2System/365),type='l',xlab='QP',ylab='Lake C Age (y)')
}
|
e6b41923a579727999b14c25547e674bc00bd72c
|
9900a88e6f3649c3a4451ef9380b9770a9896b8c
|
/server.R
|
7052dfb03dd0033a7af4174608df424f637cb54d
|
[] |
no_license
|
huangzhii/iGenomicsR
|
3345a50a720e2e8095861469a77ab347e1e39c89
|
14085bc647fb0047313a868633a6919ec7f79a79
|
refs/heads/master
| 2021-04-12T09:31:42.509309
| 2019-05-14T20:36:47
| 2019-05-14T20:36:47
| 126,821,968
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 56,718
|
r
|
server.R
|
library(data.table)
library(DT)
library(RColorBrewer)
library(GenomicRanges)
library(ggplot2)
library(reshape2)
library(gplots)
library(plyr)
library(GGally)
library(survival)
library(shinyjs)
source("utils.R")
source("my_heatmap.R")
source("my_analysis.R")
source("gene_filter.R")
options(shiny.maxRequestSize=300*1024^2) # to the top of server.R would increase the limit to 300MB
options(shiny.sanitize.errors = FALSE)
options(stringsAsFactors = FALSE)
function(input, output, session) {
checkdataready <- function(input,output,datafrom){
hideTab(inputId = "data.navigator", target = "Mutation")
hideTab(inputId = "data.navigator", target = "Image features")
hideTab(inputId = "data.navigator", target = "RNA expression")
hideTab(inputId = "data.navigator", target = "Protein expression")
hideTab(inputId = "data.integration", target = "Mutation")
hideTab(inputId = "data.integration", target = "Image features")
hideTab(inputId = "data.integration", target = "RNA expression")
hideTab(inputId = "data.integration", target = "Protein expression")
analysisDataTypeList = list()
if(length(DB.Mutation_gene()) != 0){
output$hasMutationData <- reactive(TRUE)
outputOptions(output, "hasMutationData", suspendWhenHidden = FALSE)
analysisDataTypeList["Mutation"] = 0
showTab(inputId = "data.navigator", target = "Mutation")
showTab(inputId = "data.integration", target = "Mutation")
}
if(length(DB.Image()) != 0){
output$hasImageData <- reactive(TRUE)
outputOptions(output, "hasImageData", suspendWhenHidden = FALSE)
analysisDataTypeList["Image feature"] = 4
showTab(inputId = "data.navigator", target = "Image features")
showTab(inputId = "data.integration", target = "Image features")
}
if(length(DB.RNA()) != 0){
output$hasRNAData <- reactive(TRUE)
outputOptions(output, "hasRNAData", suspendWhenHidden = FALSE)
analysisDataTypeList["RNA expression"] = 1
showTab(inputId = "data.navigator", target = "RNA expression")
showTab(inputId = "data.integration", target = "RNA expression")
}
if(length(DB.Protein()) != 0){
output$hasProteinData <- reactive(TRUE)
outputOptions(output, "hasProteinData", suspendWhenHidden = FALSE)
analysisDataTypeList["Protein expression"] = 2
showTab(inputId = "data.navigator", target = "Protein expression")
showTab(inputId = "data.integration", target = "Protein expression")
}
analysisDataTypeList["Clinical data"] = 3
analysisDataTypeList["Survival"] = 5
output$AnalysisDataTypeUI<-renderUI({
awesomeRadio("AnalysisDataType", "", analysisDataTypeList)
})
if (datafrom == "user"){
if(!((length(DB.Mutation_gene()) > 0) + (length(DB.Image()) > 0) + (length(DB.RNA()) > 0) + (length(DB.Protein()) > 0) + (length(DB.Clinical()) > 0)) >= 3 & !is.null(DB.Clinical())){
sendSweetAlert(session, title = "Insufficient Input Data", text = "Please upload required clinical file and at least two omics data.", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
}
}
else{
output$data_ready_flag <- reactive(TRUE)
outputOptions(output, "data_ready_flag", suspendWhenHidden = FALSE)
sendSweetAlert(session, title = "File Upload Success", text = NULL, type = "success",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
output$dataUploadSummary <- renderTable({
return(summarize_dataUpload())
}, include.colnames=FALSE)
output$sampleVenn <- renderPlot({
# Venn Plot
vennData <- list()
DB_temp = NULL
if (length(DB.Mutation_gene()) != 0) DB_temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB_temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB_temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB_temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB_temp[["Clinical"]] = DB.Clinical()
for(i in setdiff(names(DB_temp), "Clinical")){
vennData[[i]] <- colnames(DB_temp[[i]])
}
if(length(DB.Clinical()) != 0 ){
vennData[["Clinical"]] <- rownames(DB.Clinical())
}
venn(vennData)
}, height = 400, width = 600)
session$sendCustomMessage("buttonCallbackHandler", "tab1")
}
}
checkCatClin_selected <- reactiveVal("")
checkQuanClin_selected <- reactiveVal("")
input.csvfile_mutation <- reactiveVal(NULL)
input.csvfile_image <- reactiveVal(NULL)
input.csvfile_mRNA <- reactiveVal(NULL)
input.csvfile_protein <- reactiveVal(NULL)
input.csvfile_clinical <- reactiveVal(NULL)
uploader_show_reactive <- reactiveVal(TRUE)
DB.Mutation_gene <- reactiveVal(NULL)
DB.Image <- reactiveVal(NULL)
DB.RNA <- reactiveVal(NULL)
DB.Protein <- reactiveVal(NULL)
DB.Clinical <- reactiveVal(NULL)
DB.Clinical_cat_lab <- reactiveVal(0)
DB.Clinical_quan_lab <- reactiveVal(0)
DB.mutation_gene_test <- reactiveVal(0)
OncoPlot_res <- reactiveVal(0)
RNAheat_res <- reactiveVal(0)
Proteinheat_res <- reactiveVal(0)
Clinheat_res <- reactiveVal(0)
Imageheat_res <- reactiveVal(0)
get_analysis_res <- reactiveVal(0)
output$check1 <- renderText({'<img src="./images/check_no.png", style="width:30px">'})
output$check2 <- renderText({'<img src="./images/check_no.png", style="width:30px">'})
output$check3 <- renderText({'<img src="./images/check_no.png", style="width:30px">'})
output$check4 <- renderText({'<img src="./images/check_no.png", style="width:30px">'})
output$check5 <- renderText({'<img src="./images/check_no.png", style="width:30px">'})
########################################################################
# data upload panel
########################################################################
observeEvent(input$action_load_example1,{
input.csvfile_mutation("www/data/mutation.csv")
input.csvfile_image("www/data/Image_Features_Ass_General_CPTAC_merged_by_mean.csv")
input.csvfile_mRNA("www/data/RNA.csv")
input.csvfile_protein("www/data/Protein.csv")
input.csvfile_clinical("www/data/Clinical.csv")
shinyjs::hide("upload_panel")
})
observeEvent(input$action_load_example2,{
input.csvfile_image(NULL)
DB.Image(NULL)
Imageheat_res(0)
output$check5 <- renderText({'<img src="./images/check_no.png", style="width:30px">'})
hideTab(inputId = "data.navigator", target = "Image features")
hideTab(inputId = "data.integration", target = "Image features")
input.csvfile_mutation("www/data/UCEC/UCEC_mutation.csv")
input.csvfile_mRNA("www/data/UCEC/UCEC_RNA.csv")
input.csvfile_protein("www/data/UCEC/UCEC_protein.csv")
input.csvfile_clinical("www/data/UCEC/UCEC_clinical.csv")
shinyjs::hide("upload_panel")
})
observeEvent(DB.Clinical(),{ # if the last file is fully loaded then:x
checkdataready(input,output,"example")
checkCatClin_selected(c("ajcc_neoplasm_disease_lymph_node_stage",
"ajcc_neoplasm_disease_stage",
"breast_carcinoma_estrogen_receptor_status",
"breast_carcinoma_progesterone_receptor_status",
"person_neoplasm_cancer_status",
"DiseaseFreeStatus", "OverallSurvivalStatus"))
checkQuanClin_selected(c("DiseaseFreeMonths", "OverallSurvivalMonths"))
})
observeEvent(input$action1,{
checkdataready(input,output,"user")
})
observeEvent(input$csvfile_clinical,{
input.csvfile_clinical(input$csvfile_clinical$datapath)
})
observeEvent(input$csvfile_mutation,{
input.csvfile_mutation(input$csvfile_mutation$datapath)
})
observeEvent(input$csvfile_image,{
input.csvfile_image(input$csvfile_image$datapath)
})
observeEvent(input$csvfile_mRNA,{
input.csvfile_mRNA(input$csvfile_mRNA$datapath)
})
observeEvent(input$csvfile_protein,{
input.csvfile_protein(input$csvfile_protein$datapath)
})
loadData.clinical<- function(){
if (is.null(input.csvfile_clinical())){
return(NULL)}else{
message("loading clinical data")
table <- read.table(input.csvfile_clinical(), sep=input$sep, header=TRUE, row.names = 1)
DB.Clinical(table)
session$sendCustomMessage("buttonCallbackHandler", "tab1")
}
return(dim(DB.Clinical()))
}
observeEvent(DB.Clinical(),{
output$PatientGroupsInputUI1 <- renderUI({
selectInput(inputId="patientGroups1", label="Select patient group 1 here",
choices = rownames(DB.Clinical()),
multiple = T)
})
})
observeEvent(DB.Clinical(),{
output$PatientGroupsInputUI2 <- renderUI({
selectInput(inputId="patientGroups2", label="Select patient group 2 here",
choices = rownames(DB.Clinical()),
multiple = T)
})
})
loadData.mutation <- function(){
if (is.null(input.csvfile_mutation())){
return(NULL)}else{
message("loading mutation data")
table = read.table(input.csvfile_mutation(), sep=input$sep, header=TRUE, row.names = 1)
colnames(table) <- gsub(".", "-", colnames(table), fixed = TRUE)
table[is.na(table)] <- 0
DB.Mutation_gene(table)
session$sendCustomMessage("buttonCallbackHandler", "tab1")
}
return(dim( DB.Mutation_gene() ))
}
loadData.mRNA <- function(){
if (is.null(input.csvfile_mRNA())){
return(NULL)}else{
message("loading mRNA data")
table = read.table(input.csvfile_mRNA(), sep=input$sep, header=TRUE, row.names = 1)
colnames(table) <- gsub(".", "-", colnames(table), fixed = TRUE)
table <- apply(table, c(1,2), as.numeric)
table[is.na(table)] <- 0
DB.RNA(table)
session$sendCustomMessage("buttonCallbackHandler", "tab1")
}
return(dim( DB.RNA() ))
}
loadData.protein <- function(){
if (is.null(input.csvfile_protein())){
return(NULL)}else{
message("loading protein data")
table = read.table(input.csvfile_protein(), sep=input$sep, header=TRUE, row.names = 1)
colnames(table) <- gsub(".", "-", colnames(table), fixed = TRUE)
table <- apply(table, c(1,2), as.numeric)
table[is.na(table)] <- 0
DB.Protein(table)
session$sendCustomMessage("buttonCallbackHandler", "tab1")
}
return(dim(DB.Protein()))
}
loadData.image<- function(){
if (is.null(input.csvfile_image())){
return(NULL)}else{
message("loading image data")
table <- read.table(input.csvfile_image(), sep=input$sep, header=TRUE, row.names = 1)
table <- t(table)
# Data Integration
table[is.na(table)] <- 0
DB.Image(table)
output$ImageInputFeaturesUI <- renderUI({
selectInput(inputId="ImageInputFeatures", label="Select features here",
choices = rownames(DB.Image()),
multiple = T)
})
output$ImageInputFeaturesSubUI_Mutation <- renderUI({
selectInput(inputId="ImageInputFeaturesSelectionForMutation", label="Select features here",
choices = rownames(DB.Image()),
multiple = T)
})
output$ImageInputFeaturesSubUI_RNA <- renderUI({
selectInput(inputId="ImageInputFeaturesSelectionForRNA", label="Select features here",
choices = rownames(DB.Image()),
multiple = T)
})
output$ImageInputFeaturesSubUI_Protein <- renderUI({
selectInput(inputId="ImageInputFeaturesSelectionForProtein", label="Select features here",
choices = rownames(DB.Image()),
multiple = T)
})
output$ImageInputFeaturesSubUI_Clinical <- renderUI({
selectInput(inputId="ImageInputFeaturesSelectionForClinical", label="Select features here",
choices = rownames(DB.Image()),
multiple = T)
})
session$sendCustomMessage("buttonCallbackHandler", "tab1")
}
return(dim(DB.Image()))
}
observeEvent(loadData.clinical(),{output$check4 <- renderText({'<img src="./images/check_yes.png", style="width:30px">'})})
observeEvent(loadData.mutation(),{output$check1 <- renderText({'<img src="./images/check_yes.png", style="width:30px">'})})
observeEvent(loadData.mRNA(),{output$check2 <- renderText({'<img src="./images/check_yes.png", style="width:30px">'})})
observeEvent(loadData.protein(),{output$check3 <- renderText({'<img src="./images/check_yes.png", style="width:30px">'})})
observeEvent(loadData.image(),{output$check5 <- renderText({'<img src="./images/check_yes.png", style="width:30px">'})})
summarize_dataUpload <- eventReactive(input$uploadSummaryButton, {
smartModal(error=F, title = "Summarizing Uploaded Data", content = "Summarizing uploaded data, please wait for a little while...")
DB_temp = NULL
if (length(DB.Mutation_gene()) != 0) DB_temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB_temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB_temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB_temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB_temp[["Clinical"]] = DB.Clinical()
d <- list()
d[["dataTypes"]] <- c("Uploaded data types", paste(names(DB_temp), collapse = ";"))
for(i in setdiff(names(DB_temp), "Clinical")){
d[[i]] <- c(paste("# of samples for", i), ncol(DB_temp[[i]]))
}
if( "Clinical" %in% names(DB_temp)){
d[["clinFeatures"]] <- c("Clinical features", paste(names(DB_temp[["Clinical"]]), collapse = ";"))
for(i in names(DB_temp[["Clinical"]])){
d[[i]] <- c(paste("# of NA in", i), sum(is.na(toupper(DB_temp[["Clinical"]][,i])) | DB_temp[["Clinical"]][,i]==""))
}
}
removeModal()
return(t(as.data.frame(d)))
})
sampleSelection <- observeEvent(input$sampleSelectionButton, {
DB_temp = NULL
if (length(DB.Mutation_gene()) != 0) DB_temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB_temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB_temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB_temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB_temp[["Clinical"]] = DB.Clinical()
allDataTypes <- colnames(DB_temp) # [1] "Mutation_gene" "RNA" "Protein" "Clinical"
if ("Clinical" %in% allDataTypes){
samples <- rownames(DB_temp[["Clinical"]])
}
else if (length(setdiff(allDataTypes, "Clinical")) >= 1 ){
samples <- colnames(DB_temp[[setdiff(allDataTypes, "Clinical")[1]]])
for(i in setdiff(allDataTypes, "Clinical")){
samples <- intersect(samples, colnames(DB_temp[[i]]))
}
}
for(i in setdiff(allDataTypes, "Clinical")){
if (i == "Mutation_gene") DB.Mutation_gene(DB_temp[[i]][,samples])
if (i == "Image") DB.Image(DB_temp[[i]][,samples])
if (i == "RNA") DB.RNA(DB_temp[[i]][,samples])
if (i == "Protein") DB.Protein(DB_temp[[i]][,samples])
}
if ("Clinical" %in% allDataTypes){
DB.Clinical(DB[["Clinical"]][samples,])
}
DB.Clinical_cat_lab(CatClin())
DB.Clinical_quan_lab(QuanClin())
sendSweetAlert(session, title = "Success", text = "Now only keep samples shared by all subjects", type = "success",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
if ("Mutation_gene" %in% names(DB_temp)){session$sendCustomMessage("download_seleted_data_ready_mutation", "lalala")}
if ("RNA" %in% names(DB_temp)){session$sendCustomMessage("download_seleted_data_ready_rna", "lalala")}
if ("Image" %in% names(DB_temp)){session$sendCustomMessage("download_seleted_data_ready_image", "lalala")}
if ("Protein" %in% names(DB_temp)){session$sendCustomMessage("download_seleted_data_ready_protein", "lalala")}
if ("Clinical" %in% names(DB_temp)){session$sendCustomMessage("download_seleted_data_ready_clinical", "lalala")}
})
get_all_clin <- reactive({
ClinList <- list()
for(i in colnames(DB.Clinical())){
ClinList[[i]] <- i
}
ClinList
})
output$checkCatClinUI <- renderUI({
if (is.null(input.csvfile_clinical()))
return()
checkboxGroupInput('checkCatClin', 'Select categorical clinical feature', get_all_clin(),
selected = checkCatClin_selected())
})
output$checkQuanClinUI <- renderUI({
if (is.null(input.csvfile_clinical()))
return()
checkboxGroupInput('checkQuanClin', 'Select quantitative clinical feature', get_all_clin(),
selected = checkQuanClin_selected())
})
CatClin <- reactive({input$checkCatClin})
QuanClin <- reactive({input$checkQuanClin})
output$downloadSelectedMutation <- downloadHandler(
filename = function() { "SelectedMutationTable.csv" },
content = function(file) {
sampleSelection
write.csv(DB.Mutation_gene(), file, row.names=TRUE)
}) ###
output$downloadSelectedImageFeature <- downloadHandler(
filename = function() { "SelectedImageFeatureTable.csv" },
content = function(file) {
sampleSelection
write.csv(DB.Image(), file, row.names=TRUE)
}) ###
output$downloadSelectedRNA <- downloadHandler(
filename = function() { "SelectedRNATable.csv" },
content = function(file) {
sampleSelection
write.csv(DB.RNA(), file, row.names=TRUE)
}) ###
output$downloadSelectedProtein <- downloadHandler(
filename = function() { "SelectedProteinTable.csv" },
content = function(file) {
sampleSelection
write.csv(DB.Protein(), file, row.names=TRUE)
}) ###
output$downloadSelectedClin <- downloadHandler(
filename = function() { "SelectedClinicalTable.csv" },
content = function(file) {
sampleSelection
write.csv(DB.Clinical(), file, row.names=TRUE)
}) ###
observeEvent(input$action2,{
if( ((length(DB.Mutation_gene()) > 0) + (length(DB.Image()) > 0) + (length(DB.RNA()) > 0) + (length(DB.Protein()) > 0) + (length(DB.Clinical()) > 0)) >= 3 & !is.null(DB.Clinical())){
session$sendCustomMessage("buttonCallbackHandler", "tab2")
}
else{
sendSweetAlert(session, title = "Insufficient Input Data", text = "Please upload required clinical file and at least two omics data.", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
}
})
########################################################################
# Data navigator panel
########################################################################
observeEvent(input$action.navigator.mutation,{
# output gene mutation test result
output$geneMutationTestResTable <- DT::renderDataTable({
# print(head(DB[["Mutation_gene"]]))
DB.mutation_gene_test(run_gene_mutation_association(DB.Mutation_gene()))
# print(head(DB[["mutation_gene_test"]]))
d <- DB.mutation_gene_test()
d[,"oddsRatio"] <- format(as.numeric(d[,"oddsRatio"]),nsmall=2, digits=2)
# d[,"pvalue"] <- format(as.numeric(d[,"pvalue"]),scientific=TRUE, nsmall=2,digits=2)
# d[,"adj_pvalue"] <- format(as.numeric(d[,"adj_pvalue"]),scientific=TRUE, nsmall=2,digits=2)
return(d)
},selection="none",options=list(searching=F, ordering=T))#,extensions = 'Responsive'
output$dowloadGeneMutationTestRes <- downloadHandler(
filename = function() { "mutation_gene_association_test.csv" },
content = function(file) {
write.csv(DB.mutation_gene_test(), file, row.names=FALSE)
})
# output selected mutations
output$selectedGeneMutationsTable <- DT::renderDataTable({
DB.Mutation_gene()[unlist(strsplit(gsub(" ", "", input$MutationInputGenes), ",", fixed = TRUE)),]
},selection="none",options=list(searching=F, ordering=F))#,extensions = 'Responsive'
})
observeEvent(input$action.navigator.RNA,{
output$RNADotPlot <- renderPlot({
genes <- c(input$navigator.RNA.expression.gene.1, input$navigator.RNA.expression.gene.2)
if ( any(!(genes %in% rownames(DB.RNA()))) ){
sendSweetAlert(session, title = "Alert",
text = sprintf("Genes [%s] are not contained in the RNA data",
genes[!(genes %in% rownames(DB.RNA()))]),
type = "warning",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
d <- DB.RNA()[genes,,drop=FALSE]
d <- d[,!apply(d, 2, function(z){any(is.na(z))})]
x <- d[genes[1],,drop=TRUE]
y <- d[genes[2],,drop=TRUE]
corr <- cor(x, y)
plot(x, y, xlab=genes[1], ylab=genes[2], main="RNA expression", sub=paste("correlation:", round(corr, 2)))
}, height = 500, width = 500)
})
observeEvent(input$action.navigator.protein,{
# save(DB, file = "~/Desktop/DB.Rdata")
output$ProteinDotPlot1 <- renderPlot({
genes <- c(input$navigator.protein.expression.gene.1, input$navigator.protein.expression.gene.2)
if ( any(!(genes %in% rownames(DB.Protein()))) ){
sendSweetAlert(session, title = "Alert",
text = sprintf("Genes [%s] are not contained in the protein data",
genes[!(genes %in% rownames(DB.Protein()))]),
type = "warning",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
d <- DB.Protein()[genes,,drop=FALSE]
d <- d[,!apply(d, 2, function(z){any(is.na(z))})]
d <- apply(d, c(1,2), as.numeric)
x <- d[genes[1],,drop=TRUE]
y <- d[genes[2],,drop=TRUE]
corr <- cor(x, y)
plot(x, y, xlab=genes[1], ylab=genes[2], main="Protein expression", sub=paste("correlation:", corr))
}, height = 500, width = 500)
})
output$ImageFeaturesNavigatorPlot <- renderPlot({
# dev.off()
heatmap(DB.Image(), margins = c(8, 15) )
})
output$ImageFeaturesTable <- DT::renderDataTable({
DT::datatable(DB.Image(), escape=F, selection = 'none', rownames = T,
options=list(searching=F, ordering=F)) #, extensions = 'Responsive'
})
output$ClinicalInfoTable <- DT::renderDataTable({
DT::datatable(DB.Clinical(), escape=F, selection = 'none', rownames = T,
options=list(searching=F, ordering=F)) #, extensions = 'Responsive'
})
########################################################################
# mutation panel
########################################################################
# Oncoplot
selectedClinFeature <- reactive({
SCF <- list()
for(i in c(CatClin(), QuanClin())){
SCF[[i]] <- i
}
return(SCF)
})
output$OncoPlotClinUI <- renderUI({
if (!input$OncoPlotHasClin)
return()
checkboxGroupInput('OncoPlotClin', '', selectedClinFeature(), selected = "")
})
output$ImageheatClinUI <- renderUI({
if (!input$ImageheatHasClin)
return()
checkboxGroupInput('ImageheatClin', '', selectedClinFeature(), selected = "")
})
output$RNAheatClinUI <- renderUI({
if (!input$RNAheatHasClin)
return()
checkboxGroupInput('RNAheatClin', '', selectedClinFeature(), selected = "")
})
output$ProteinheatClinUI <- renderUI({
if (!input$ProteinheatHasClin)
return()
checkboxGroupInput('ProteinheatClin', '', selectedClinFeature(), selected = "")
})
output$ClinheatClinUI <- renderUI({
checkboxGroupInput('ClinheatClin', '', c(CatClin(), QuanClin()),
selected = c(CatClin(), QuanClin()))
})
output$ClinheatSelectOrderFeatureUI <- renderUI({
selectInput('ClinheatSelectOrderFeature', "Order samples by", c(CatClin(), QuanClin()),
selected = c(CatClin(), QuanClin())[1])
})
observeEvent(input$action.integration.mutation.inputgenes,{
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
OncoPlot_res.temp <- my_heatmap_mutation(DB.temp, mutation_genes = gsub("\\s","", strsplit(input$genesToPullMutation,",")[[1]]),
image_features = if(input$OncoPlotHasImage){
gsub("\\s","", input$ImageInputFeaturesSelectionForMutation)
},
rna_genes = if(input$OncoPlotHasRna){
gsub("\\s","", strsplit(input$MutationInputRna,",")[[1]])
},
protein_genes = if(input$OncoPlotHasProtein){
gsub("\\s","", strsplit(input$MutationInputProteins,",")[[1]])
},
clinical_lab = input$OncoPlotClin,
order_by="mutation",
sort.mutation = input$do_hclust_mutation,
sort.rna = input$do_hclust_mutation_rna,
sort.image = input$do_hclust_mutation_image,
sort.protein = input$do_hclust_mutation_protein)
OncoPlot_res(OncoPlot_res.temp)
# save(OncoPlot_res(), file= "~/Desktop/oncoplot.Rdata")
height_of_plot <- length(gsub("\\s","", strsplit(input$genesToPullMutation,",")[[1]])) +
length(input$OncoPlotClin)
if(input$OncoPlotHasImage){
height_of_plot = height_of_plot + length(gsub("\\s","", input$ImageInputFeaturesSelectionForMutation))
}
if(input$OncoPlotHasRna){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$MutationInputRna,",")[[1]]))
}
if(input$OncoPlotHasProtein){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$MutationInputProteins,",")[[1]]))
}
output$OncoPlot <- renderPlot({
return(OncoPlot_res()[["plot"]])
}, width=input$myWidth1, height=input$myHeight1/20*height_of_plot)
})
# download ordered data for heatmap
output$downloadOncoPlotData <- downloadHandler(
filename = function() { "data_ordered_by_mutation.csv" },
content = function(file) {
write.csv( t(OncoPlot_res()[["table"]]), file, row.names=TRUE)
}) ###
########################################################################
# image panel
########################################################################
# Imageheat
observeEvent(input$action.integration.image.inputgenes,{
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
Imageheat_res.temp <- my_heatmap_mutation(DB.temp, image_features = gsub("\\s","", input$ImageInputFeatures),
mutation_genes = if(input$ImageheatHasMutation){
gsub("\\s","", strsplit(input$ImageInputMutations,",")[[1]])
},
rna_genes = if(input$ImageheatHasRna){
gsub("\\s","", strsplit(input$ImageInputRna,",")[[1]])
},
protein_genes = if(input$ImageheatHasProtein){
gsub("\\s","", strsplit(input$ImageInputProteins,",")[[1]])
},
clinical_lab = input$ImageheatClin,
order_by="image",
sort.mutation = input$do_hclust_image_mutation,
sort.rna = input$do_hclust_image_rna,
sort.image = input$do_hclust_image,
sort.protein = input$do_hclust_image_protein)
Imageheat_res(Imageheat_res.temp)
# save(Imageheat_res(), file= "~/Desktop/oncoplot.Rdata")
height_of_plot <- length(gsub("\\s","", input$ImageInputFeatures)) +
length(input$ImageheatClin)
if(input$ImageheatHasMutation){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ImageInputMutations,",")[[1]]))
}
if(input$ImageheatHasRna){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ImageInputRna,",")[[1]]))
}
if(input$ImageheatHasProtein){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ImageInputProteins,",")[[1]]))
}
output$Imageheat <- renderPlot({
return(Imageheat_res()[["plot"]])
}, width=input$myWidth2, height=input$myHeight2/20*height_of_plot)
})
# download ordered data for heatmap
output$downloadImageheatData <- downloadHandler(
filename = function() { "data_ordered_by_image_feature.csv" },
content = function(file) {
write.csv( Imageheat_res()[["table"]], file, row.names=TRUE)
}) ###
########################################################################
# rna expression panel
########################################################################
# gene expression clustering and heatmap
observeEvent(input$action.integration.RNA.denovo,{
clust_para <- list()
clust_para[["method"]] <- "hc"
rna_RNAheatClustPara <- clust_para
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
RNAheat_res.temp <- my_heatmap_rna(DB.temp, mode = 1, #denovo
clust_para = rna_RNAheatClustPara,
mutation_genes = if(input$RNAheatHasMutation){
gsub("\\s","", strsplit(input$RNAheatInputMutation,",")[[1]])
},
image_features = if(input$RNAheatHasImage){
gsub("\\s","", input$ImageInputFeaturesSelectionForRNA)
},
protein_genes = if(input$RNAheatHasProtein){
gsub("\\s","", strsplit(input$RNAheatInputProteins,",")[[1]])
},
clinical_lab=input$RNAheatClin,
rna_criteria = strsplit(input$RNAheatGeneCutoff,"and")[[1]],
rna_genes = NULL,
show.RNA.name = input$show.RNA.name.1,
sort.mutation = input$do_hclust_rna_mutation,
sort.rna = F,
sort.image = input$do_hclust_rna_image,
sort.protein = input$do_hclust_rna_protein)
RNAheat_res(RNAheat_res.temp)
height_of_plot <- 40 + length(input$RNAheatClin)
if(input$RNAheatHasMutation){
if((clust_para[["method"]] == "hc")){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$RNAheatInputMutation,",")[[1]]))
}
if((clust_para[["method"]] == "km")){
height_of_plot = height_of_plot + 1
}
}
if(input$RNAheatHasImage){
height_of_plot = height_of_plot + length(gsub("\\s","", input$ImageInputFeaturesSelectionForRNA))
}
if(input$RNAheatHasProtein){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$RNAheatInputProteins,",")[[1]]))
}
output$RNAheat <- renderPlot({
return(RNAheat_res()[["plot"]])
}, height = input$myHeight3/40*height_of_plot, width = input$myWidth3)
# gene clustering dendrogram
if((clust_para[["method"]] == "hc")){
output$RNAdendro <- renderPlot({
plot(RNAheat_res()[["sample_order_res"]][["hc"]], cex=0.5)
}, height = input$myHeight3/2, width = input$myWidth3)
}
})
observeEvent(input$action.integration.RNA.inputgenes,{
clust_para <- list()
clust_para[["method"]] <- c("hc", "km")[as.numeric(input$RNAheatClustMethod) + 1]
if(clust_para[["method"]] == "km"){
clust_para[["k"]] <- as.numeric(input$RNAheatKmeansK)
}
rna_RNAheatClustPara <- clust_para
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
RNAheat_res.temp <- my_heatmap_rna(DB.temp, mode = 0, # gene lists
clust_para = rna_RNAheatClustPara,
mutation_genes = if(input$RNAheatHasMutation){
gsub("\\s","", strsplit(input$RNAheatInputMutation,",")[[1]])
},
image_features = if(input$RNAheatHasImage){
gsub("\\s","", input$ImageInputFeaturesSelectionForRNA)
},
protein_genes = if(input$RNAheatHasProtein){
gsub("\\s","", strsplit(input$RNAheatInputProteins,",")[[1]])
},
clinical_lab=input$RNAheatClin,
rna_criteria = NULL,
rna_genes = gsub("\\s","", strsplit(input$RNAheatInputGenes,",")[[1]]),
show.RNA.name = input$show.RNA.name.2,
sort.mutation = input$do_hclust_rna_mutation,
sort.rna = F,
sort.image = input$do_hclust_rna_image,
sort.protein = input$do_hclust_rna_protein)
RNAheat_res(RNAheat_res.temp)
height_of_plot <- length(gsub("\\s","", strsplit(input$RNAheatInputGenes,",")[[1]])) + length(input$RNAheatClin)
if(input$RNAheatHasMutation){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$RNAheatInputMutation,",")[[1]]))
}
if(input$RNAheatHasImage){
height_of_plot = height_of_plot + length(gsub("\\s","", input$ImageInputFeaturesSelectionForRNA))
}
if(input$RNAheatHasProtein){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$RNAheatInputProteins,",")[[1]]))
}
output$RNAheat <- renderPlot({
return(RNAheat_res()[["plot"]])
}, height = input$myHeight3/20*height_of_plot, width = input$myWidth3)
# gene clustering dendrogram
if((clust_para[["method"]] == "hc")){
output$RNAdendro <- renderPlot({
plot(RNAheat_res()[["sample_order_res"]][["hc"]], cex=0.5)
}, height = input$myHeight3/2, width = input$myWidth3)
}
if((clust_para[["method"]] == "km")){
output$RNAdendro <- renderPlot({
par(mar = c(0,0,0,0))
plot(c(0, 1), c(0, 1), ann = F, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
text(x = 0.5, y = 0.5, paste("K-means algorithm selected.\n",
"RNA dendrogram not available."),
cex = 1.6, col = "black")
})
}
})
# download ordered data for heatmap
output$downloadRNAheatData <- downloadHandler(
filename = function() { "data_ordered_by_rna.csv" },
content = function(file) {
write.csv( RNAheat_res()[["table"]],
file, row.names=TRUE)
}) ###
########################################################################
# protein panel
########################################################################
# plot heatmap order by protein
observeEvent(input$action.integration.protein.denovo,{
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
Proteinheat_res.temp <- my_heatmap_protein(DB.temp, mode=1,
mutation_genes=if(input$ProteinheatHasMutation){
gsub("\\s","", strsplit(input$ProteinheatInputMutation,",")[[1]])
},
image_features = if(input$ProteinheatHasImage){
gsub("\\s","", input$ImageInputFeaturesSelectionForProtein)
},
rna_genes=if(input$ProteinheatHasRNA){
gsub("\\s","", strsplit(input$ProteinheatInputRNA,",")[[1]])
},
clinical_lab=input$ProteinheatClin,
protein_criteria = strsplit(input$ProteinheatGeneCutoff,"and")[[1]],
protein_genes = NULL,
show.protein.name = input$show.protein.name,
sort.mutation = input$do_hclust_protein_mutation,
sort.rna = input$do_hclust_protein_rna,
sort.image = input$do_hclust_protein_image,
sort.protein = F)
Proteinheat_res(Proteinheat_res.temp)
height_of_plot <- 40 + length(input$ProteinheatClin)
if(input$ProteinheatHasMutation){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ProteinheatInputMutation,",")[[1]]))
}
if(input$ProteinheatHasImage){
height_of_plot = height_of_plot + length(gsub("\\s","", input$ImageInputFeaturesSelectionForProtein))
}
if(input$ProteinheatHasRNA){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ProteinheatInputRNA,",")[[1]]))
}
output$Proteinheat <- renderPlot({
Proteinheat_res()[["plot"]]
}, height = input$myHeight4/40*height_of_plot, width = input$myWidth4)
# gene clustering dendrogram
output$Proteindendro <- renderPlot({
plot(Proteinheat_res()[["sample_order_res"]][["hc"]], cex=0.5)
}, height = input$myHeight4/2, width = input$myWidth4)
})
observeEvent(input$action.integration.protein.inputgenes,{
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
Proteinheat_res.temp <- my_heatmap_protein(DB.temp, mode=0,
mutation_genes=if(input$ProteinheatHasMutation){
gsub("\\s","", strsplit(input$ProteinheatInputMutation,",")[[1]])
},
image_features = if(input$ProteinheatHasImage){
gsub("\\s","", input$ImageInputFeaturesSelectionForProtein)
},
rna_genes=if(input$ProteinheatHasRNA){
gsub("\\s","", strsplit(input$ProteinheatInputRNA,",")[[1]])
},
clinical_lab=input$ProteinheatClin,
protein_criteria = NULL,
protein_genes = gsub("\\s","", strsplit(input$ProteinheatInputGenes,",")[[1]]),
sort.mutation = input$do_hclust_protein_mutation,
sort.rna = input$do_hclust_protein_rna,
sort.image = input$do_hclust_protein_image,
sort.protein = F)
Proteinheat_res(Proteinheat_res.temp)
height_of_plot <- length(gsub("\\s","", strsplit(input$ProteinheatInputGenes,",")[[1]])) + length(input$ProteinheatClin)
if(input$ProteinheatHasMutation){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ProteinheatInputMutation,",")[[1]]))
}
if(input$ProteinheatHasImage){
height_of_plot = height_of_plot + length(gsub("\\s","", input$ImageInputFeaturesSelectionForProtein))
}
if(input$ProteinheatHasRNA){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ProteinheatInputRNA,",")[[1]]))
}
output$Proteinheat <- renderPlot({
Proteinheat_res()[["plot"]]
}, height = input$myHeight4/20*height_of_plot, width = input$myWidth4)
# gene clustering dendrogram
output$Proteindendro <- renderPlot({
plot(Proteinheat_res()[["sample_order_res"]][["hc"]], cex=0.5)
}, height = input$myHeight4/2, width = input$myWidth4)
})
# download ordered data for heatmap
output$downloadProteinheatData <- downloadHandler(
filename = function() { "data_ordered_by_protein.csv" },
content = function(file) {
write.csv( Proteinheat_res()[["table"]],
file, row.names=TRUE)
}) ###
########################################################################
# Clinical panel
########################################################################
# plot heatmap order by clinical feature
observeEvent(input$action.integration.clinical,{
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
Clinheat_res.temp <- my_heatmap_mutation(DB.temp, mutation_genes = if(input$ClinheatHasMutation){
gsub("\\s","", strsplit(input$ClinheatInputMutation,",")[[1]])
},
image_features = if(input$ClinheatHasImage){
gsub("\\s","", input$ImageInputFeaturesSelectionForClinical)
},
rna_genes = if(input$ClinheatHasRNA){
gsub("\\s","", strsplit(input$ClinheatInputRNA,",")[[1]])
},
protein_genes = if(input$ClinheatHasProtein){
gsub("\\s","", strsplit(input$ClinheatInputProtein,",")[[1]])
},
clinical_lab = input$ClinheatClin,
order_by = "clinical",
order_clin_feature = input$ClinheatSelectOrderFeature,
sort.mutation = input$do_hclust_clin_mutation,
sort.rna = input$do_hclust_clin_rna,
sort.image = input$do_hclust_clin_image,
sort.protein = input$do_hclust_clin_protein)
height_of_plot <- length(input$ClinheatClin)
if(input$ClinheatHasMutation){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ClinheatInputMutation,",")[[1]]))
}
if(input$ClinheatHasImage){
height_of_plot = height_of_plot + length(gsub("\\s","", input$ImageInputFeaturesSelectionForClinical))
}
if(input$ClinheatHasRNA){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ClinheatInputRNA,",")[[1]]))
}
if(input$ClinheatHasProtein){
height_of_plot = height_of_plot + length(gsub("\\s","", strsplit(input$ClinheatInputProtein,",")[[1]]))
}
Clinheat_res(Clinheat_res.temp)
output$Clinheat <- renderPlot({
Clinheat_res()[["plot"]]
}, height = input$myHeight5/20*height_of_plot, width = input$myWidth5)
})
# download ordered data for heatmap
output$downloadClinheatData <- downloadHandler(
filename = function() { "data_ordered_by_clinical.csv" },
content = function(file) {
write.csv( Clinheat_res()[["table"]], file, row.names=TRUE)
}) ###
########################################################################
# analysis panel
########################################################################
get_patient_groups <- reactive({
if(is.null(input$patientGroups1) | is.null(input$patientGroups2)){
sendSweetAlert(session, title = "Error", text = "Insufficient Input Data.", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
else if(input$patientGroups1 == "" | input$patientGroups2 == "") {
get_patient_groups = NULL
}
tmp1<-matrix(input$patientGroups1)
tmp2<-matrix(input$patientGroups2)
maxlength <- max(length(tmp1), length(tmp2))
length(tmp1) <- maxlength
length(tmp2) <- maxlength
# if(length(tmp1)!=length(tmp2)){
# sendSweetAlert(session, title = "Error", text = "Unbalanced patient groups. (Hint: each should include title in the first row)", type = "error",
# btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
# return()
# }
data = data.frame(cbind(tmp1, tmp2))
colnames(data) <- c("Group 1", "Group 2")
rownames(data) <- rep(1:dim(data)[1])
all_patients <- as.vector(as.matrix(data))
all_patients <- all_patients[all_patients != ""]
all_patients <- all_patients[!is.na(all_patients)]
timesOfPat <- table(all_patients)
if(any(timesOfPat > 1)){
get_patient_groups = paste(names(timesOfPat)[timesOfPat>1], "showed up multiple times")
sendSweetAlert(session, title = "Error",
text = sprintf("Patients %s discovered in both groups. Please make sure two groups of patients are mutually exclusive.",
names(timesOfPat)[timesOfPat>1]),
type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
else{
get_patient_groups = data
}
return(get_patient_groups)
})
observeEvent(input$goAnalysisButton, {
## *** output user inputted patient groups ***
output$inputtedPatientGroups <- DT::renderDataTable({
if(input$patientGroups1 != "" & input$patientGroups1 != ""){
out <- t(get_patient_groups())
out <- cbind(apply(out, 1, function(x){paste(sum(!is.na(x!="")), "patients")}), out)
out
}
}, selection="none",options=list(searching=F, ordering=F)) #,extensions = 'Responsive'
if(((length(DB.Mutation_gene()) > 0) + (length(DB.Image()) > 0) + (length(DB.RNA()) > 0) + (length(DB.Protein()) > 0) + (length(DB.Clinical()) > 0)) == 0){
sendSweetAlert(session, title = "Error", text = "Insufficent input data.", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
# Create a Progress object
progress <- shiny::Progress$new(session)
progress$set(message = "Calculating... This may take a while", value = 0)
# Close the progress when this reactive exits (even if there's an error)
on.exit(progress$close())
dataTypes <- list("0"= "mutation", "1"="rna", "2"="protein", "3"="clinical", "4"="image")
dataTypes_upper <- list("0"= "Mutation", "1"="RNA", "2"="Protein", "3"="Clinical", "4"="Image Features")
analysis.title = sprintf("Current Analysis Results: %s", dataTypes_upper[toString(input$AnalysisDataType)])
output$analysisTitle <- renderUI({
h4(analysis.title, style="color: STEELBLUE")
})
DB.temp = NULL
if (length(DB.Mutation_gene()) != 0) DB.temp[["Mutation_gene"]] = DB.Mutation_gene()
if (length(DB.Image()) != 0) DB.temp[["Image"]] = DB.Image()
if (length(DB.RNA()) != 0) DB.temp[["RNA"]] = DB.RNA()
if (length(DB.Protein()) != 0) DB.temp[["Protein"]] = DB.Protein()
if (length(DB.Clinical()) != 0) DB.temp[["Clinical"]] = DB.Clinical()
if (length(DB.Clinical_cat_lab()) != 0) DB.temp[["Clinical_cat_lab"]] = DB.Clinical_cat_lab()
if (length(DB.Clinical_quan_lab()) != 0) DB.temp[["Clinical_quan_lab"]] = DB.Clinical_quan_lab()
# datatype = dataTypes[toString(input$AnalysisDataType)]
# get_patient_groups = get_patient_groups()
# save(datatype, get_patient_groups, DB.temp, file="~/Desktop/DB.protein.Rdata")
t <- try(get_analysis_res.temp <- run_analysis(dataTypes[toString(input$AnalysisDataType)], get_patient_groups(), DB.temp))
if("try-error" %in% class(t)) {
sendSweetAlert(session, title = "Error Occured", text = "There's an error processing your request. May be wrong patient groups?", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
get_analysis_res.temp <- data.frame(get_analysis_res.temp)
get_analysis_res.temp <- get_analysis_res.temp[sort.list(get_analysis_res.temp$pvalue), ]
get_analysis_res(get_analysis_res.temp)
# save(get_analysis_res, file = "~/Desktop/get_analysis_res.Rdata")
# output analysis result
output$analysisResTable <- DT::renderDataTable({
res <- get_analysis_res()
}, selection="none",options=list(searching=F, ordering=T)) #,extensions = 'Responsive'
})
# Survival Standard Terminology
observeEvent(DB.Clinical(),{
output$SurvivalStandardTerminologyUI1 <- renderUI({
tagList(
fluidRow(
column(3, selectInput(inputId="OS.time.column", label="Overall Survival Time Column",
choices = colnames(DB.Clinical()), selected=NULL,
multiple = F)),
column(3, selectInput(inputId="OS.status.column", label="Overall Survival Status Column",
choices = colnames(DB.Clinical()), selected=NULL,
multiple = F)),
column(3, selectInput(inputId="DFS.time.column", label="Disease Free Survival Time Column",
choices = colnames(DB.Clinical()), selected=NULL,
multiple = F)),
column(3, selectInput(inputId="DFS.status.column", label="Disease Free Survival Status Column",
choices = colnames(DB.Clinical()), selected=NULL,
multiple = F))
)
)
})
})
observeEvent(DB.Clinical(),{
output$SurvivalStandardTerminologyUI2 <- renderUI({
tagList(
fluidRow(
column(3, ""),
column(3, selectInput(inputId="OS.status.censored", label="OS Censored Label (e.g., DECEASED)",
choices = unique(DB.Clinical()[,input$OS.status.column]),
multiple = F)),
column(3, ""),
column(3, selectInput(inputId="DFS.status.censored", label="DFS Censored Label (e.g., DECEASED)",
choices = unique(DB.Clinical()[,input$DFS.status.column]),
multiple = F))
),
actionButton("EFS.OS.confirmed", "Confirm and Run")
)
})
})
# disease free survival
observeEvent(input$EFS.OS.confirmed,{
output[["DFSurvivalPlot"]] <- renderPlot({
PatList <- as.list(get_patient_groups())
PatList <- lapply(PatList, function(x){setdiff(x, "")})
clin_d <- data.frame(time=as.numeric(DB.Clinical()[unlist(PatList),input$DFS.time.column]),
event=as.numeric(DB.Clinical()[unlist(PatList),input$DFS.status.column]==input$DFS.status.censored),
# group = c(rep(names(PatList)[1], length(unlist(PatList[1]))), rep(names(PatList)[2], length(unlist(PatList[2]))))
group = c(rep(1, length(unlist(PatList[1]))), rep(2, length(unlist(PatList[2]))))
)
print("Disease Free Survival")
print(clin_d)
clin_d <- clin_d[apply(clin_d, 1, function(x){!any(is.na(x))}),]
survd <- survdiff(Surv(time, event, type="right") ~ group, data = clin_d)
survf <- survfit(Surv(time,event) ~ group, data = clin_d)
print(ggsurv(survf) + labs(title=paste("pvalue:", 1-pchisq(survd$chisq, 1)),
x='Time (Month)', y='Disease Free Survival'))
}, height = 500, width = 700)
#survival
output[["SurvivalPlot"]] <- renderPlot({
PatList <- as.list(get_patient_groups())
PatList <- lapply(PatList, function(x){setdiff(x, "")})
clin_d <- data.frame(time=as.numeric(DB.Clinical()[unlist(PatList),input$OS.time.column]),
event=as.numeric(DB.Clinical()[unlist(PatList),input$OS.status.column]==input$OS.status.censored),
# group = c(rep(names(PatList)[1], length(unlist(PatList[1]))), rep(names(PatList)[2], length(unlist(PatList[2]))))
group = c(rep(1, length(unlist(PatList[1]))), rep(2, length(unlist(PatList[2]))))
)
print("Overall Survival")
print(clin_d)
clin_d <- clin_d[apply(clin_d, 1, function(x){!any(is.na(x))}),]
survd <- survdiff(Surv(time, event, type="right") ~ group, data = clin_d)
survf <- survfit(Surv(time, event) ~ group, data = clin_d)
print(ggsurv(survf) + labs(title=paste("pvalue:", 1-pchisq(survd$chisq, 1)),
x='Time (Month)', y='Overall Survival'))
}, height = 500, width = 700)
})
output$dowloadAnalysisRes <- downloadHandler(
filename = function() { "full_significant_genes.csv" },
content = function(file) {
write.csv(get_analysis_res(),file, row.names=TRUE)
})
}
|
80b55aa5da0e5f4dc33d5f4ea5bce6fab77abe2b
|
cc541c98fa97f871643e4c83784180404368cc94
|
/man/combn_C.Rd
|
74c08e5ac5c145295f57a662a914ea3cea809ecb
|
[] |
no_license
|
ojessen/ojUtils
|
34e81a8511b96039b5ebb24e08f1d191eefe4b37
|
ce748448fdd71f4d9a459a94ea2b912da75e79a4
|
refs/heads/master
| 2018-11-06T06:50:41.609782
| 2018-09-10T19:02:49
| 2018-09-10T19:02:49
| 21,038,018
| 0
| 1
| null | 2014-06-20T14:55:59
| 2014-06-20T13:01:13
|
C++
|
UTF-8
|
R
| false
| true
| 434
|
rd
|
combn_C.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ifelseR.R
\name{combn_C}
\alias{combn_C}
\title{combn replacement}
\usage{
combn_C(x)
}
\arguments{
\item{x}{is an integer vector, representing a sequence starting at 1.}
}
\description{
This function is an adaptation of combn from base. currently the options are limited, and implying a value of m = 2.
}
\examples{
x = 1:4
all(combn(x,2)==combn_C(x))
}
|
fe231421408ed45e15edd682b79a6030cda38957
|
bc59e431d4ad3db278fdb2cda85c6f9ca213982a
|
/code/ESNreservoir.R
|
bd0873f61dfdfacf91cf345162ee3336d6529430
|
[] |
no_license
|
dylansun/ES2VM
|
46150ee8370fc962f600a971687ba3d7027b0f7e
|
76b2c59bef6c203c56c0c126c0b2a12ec53bfc0b
|
refs/heads/master
| 2021-01-10T12:26:47.943497
| 2016-01-31T03:01:13
| 2016-01-31T03:01:13
| 50,756,272
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 351
|
r
|
ESNreservoir.R
|
ESNreservoir <- function(nodesize = 100, alpha = 0.8){
topright = -alpha^nodesize
# 0 0 0 ... 0 -a^N
# 1 0 0 ... 0 0
# w = 0 1 0 ... 0 0
# 0 0 1 ... 0 0
# 0 0 0 ... 0 0
# 0 0 0 ... 1 0
W = diag(nodesize-1)
W = cbind(W, rep(0, nodesize -1))
W = rbind(c(rep(0,nodesize -1 ), topright), W)
return(W)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.